@malloy-publisher/sdk 0.2.6 → 0.3.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 (100) hide show
  1. package/README.md +172 -204
  2. package/dist/ServerProvider-CGnLjzag.cjs.js +1 -0
  3. package/dist/{ServerProvider-ksC5Su_x.es.js → ServerProvider-DSK9rfSY.es.js} +245 -245
  4. package/dist/client/api.d.ts +13 -1
  5. package/dist/client/index.cjs.js +1 -1
  6. package/dist/client/index.es.js +1 -1
  7. package/dist/components/ApiErrorDisplay.d.ts +1 -2
  8. package/dist/components/Dashboard/Dashboard.d.ts +4 -2
  9. package/dist/components/Dashboard/promoteMeasureRow.d.ts +36 -0
  10. package/dist/components/DocumentStorage/BrowserDocumentStorage.d.ts +14 -0
  11. package/dist/components/DocumentStorage/DocumentStorage.d.ts +58 -0
  12. package/dist/components/DocumentStorage/DocumentStorageProvider.d.ts +18 -0
  13. package/dist/components/DocumentStorage/index.d.ts +3 -0
  14. package/dist/components/Model/index.d.ts +0 -1
  15. package/dist/components/RenderedResult/RenderedResult.d.ts +12 -0
  16. package/dist/components/RenderedResult/ResultContainer.d.ts +7 -1
  17. package/dist/components/RenderedResult/index.d.ts +1 -0
  18. package/dist/components/RenderedResult/resultSizing.d.ts +183 -0
  19. package/dist/components/drill/index.d.ts +1 -0
  20. package/dist/components/drill/useDrillSelf.d.ts +46 -0
  21. package/dist/components/given/filterValue.d.ts +63 -0
  22. package/dist/components/given/index.d.ts +1 -0
  23. package/dist/components/given/useGivenUrlParams.d.ts +39 -0
  24. package/dist/components/index.d.ts +2 -3
  25. package/dist/components/styles.d.ts +3 -3
  26. package/dist/core-8NVBCLZh.cjs.js +148 -0
  27. package/dist/{core-xdZbLgaF.es.js → core-B8oMW4sm.es.js} +3540 -2335
  28. package/dist/hooks/index.d.ts +1 -1
  29. package/dist/hooks/useSuggestOptions.d.ts +28 -12
  30. package/dist/index.cjs.js +281 -1
  31. package/dist/index.es.js +45803 -79
  32. package/dist/sdk.css +1 -1
  33. package/dist/styles.css +0 -1
  34. package/package.json +2 -6
  35. package/src/components/ApiErrorDisplay.tsx +1 -1
  36. package/src/components/Connections/EditConnectionDialog.tsx +96 -86
  37. package/src/components/Dashboard/Dashboard.tsx +60 -95
  38. package/src/components/Dashboard/DashboardTile.tsx +25 -2
  39. package/src/components/Dashboard/promoteMeasureRow.spec.ts +137 -0
  40. package/src/components/Dashboard/promoteMeasureRow.ts +129 -0
  41. package/src/components/DocumentStorage/BrowserDocumentStorage.spec.ts +81 -0
  42. package/src/components/DocumentStorage/BrowserDocumentStorage.ts +105 -0
  43. package/src/components/DocumentStorage/DocumentStorage.ts +73 -0
  44. package/src/components/DocumentStorage/DocumentStorageProvider.tsx +46 -0
  45. package/src/components/DocumentStorage/index.ts +15 -0
  46. package/src/components/Environment/Connections.tsx +15 -15
  47. package/src/components/Model/ModelCell.tsx +2 -1
  48. package/src/components/Model/index.ts +0 -1
  49. package/src/components/Notebook/Notebook.tsx +10 -76
  50. package/src/components/Notebook/NotebookCell.tsx +2 -8
  51. package/src/components/RenderedResult/RenderedResult.tsx +86 -76
  52. package/src/components/RenderedResult/ResultContainer.tsx +21 -24
  53. package/src/components/RenderedResult/index.ts +15 -0
  54. package/src/components/RenderedResult/resultSizing.spec.ts +249 -0
  55. package/src/components/RenderedResult/resultSizing.ts +308 -0
  56. package/src/components/ResultsDialog.tsx +2 -1
  57. package/src/components/drill/index.ts +5 -0
  58. package/src/components/drill/useDrillSelf.spec.tsx +64 -0
  59. package/src/components/drill/useDrillSelf.ts +110 -0
  60. package/src/components/given/GivenInput.spec.tsx +196 -2
  61. package/src/components/given/GivenInput.tsx +300 -25
  62. package/src/components/given/filterValue.spec.ts +112 -0
  63. package/src/components/given/filterValue.ts +188 -0
  64. package/src/components/given/index.ts +4 -0
  65. package/src/components/given/useGivenUrlParams.spec.tsx +74 -0
  66. package/src/components/given/useGivenUrlParams.ts +87 -0
  67. package/src/components/index.ts +5 -3
  68. package/src/hooks/index.ts +0 -1
  69. package/src/hooks/useGivensState.spec.ts +158 -0
  70. package/src/hooks/useGivensState.ts +114 -23
  71. package/src/hooks/useSuggestOptions.dom.spec.ts +60 -1
  72. package/src/hooks/useSuggestOptions.ts +94 -51
  73. package/vite.config.ts +0 -1
  74. package/dist/ServerProvider-xXW1HJOJ.cjs.js +0 -1
  75. package/dist/components/AnalyzePackageButton.d.ts +0 -6
  76. package/dist/components/Workbook/BrowserWorkbookStorage.d.ts +0 -9
  77. package/dist/components/Workbook/EditableMalloyCell.d.ts +0 -11
  78. package/dist/components/Workbook/ModelPicker.d.ts +0 -11
  79. package/dist/components/Workbook/MutableCell.d.ts +0 -17
  80. package/dist/components/Workbook/Workbook.d.ts +0 -7
  81. package/dist/components/Workbook/WorkbookList.d.ts +0 -7
  82. package/dist/components/Workbook/WorkbookManager.d.ts +0 -84
  83. package/dist/components/Workbook/WorkbookStorage.d.ts +0 -17
  84. package/dist/components/Workbook/WorkbookStorageProvider.d.ts +0 -12
  85. package/dist/components/Workbook/index.d.ts +0 -7
  86. package/dist/core-RvrkY1Ss.cjs.js +0 -148
  87. package/dist/index-B3scIDRd.cjs.js +0 -356
  88. package/dist/index-Bda7HuZc.es.js +0 -66409
  89. package/dist/markdown-editor.css +0 -341
  90. package/src/components/AnalyzePackageButton.tsx +0 -319
  91. package/src/components/Workbook/BrowserWorkbookStorage.ts +0 -64
  92. package/src/components/Workbook/EditableMalloyCell.tsx +0 -49
  93. package/src/components/Workbook/ModelPicker.tsx +0 -134
  94. package/src/components/Workbook/MutableCell.tsx +0 -458
  95. package/src/components/Workbook/Workbook.tsx +0 -501
  96. package/src/components/Workbook/WorkbookList.tsx +0 -110
  97. package/src/components/Workbook/WorkbookManager.ts +0 -214
  98. package/src/components/Workbook/WorkbookStorage.ts +0 -35
  99. package/src/components/Workbook/WorkbookStorageProvider.tsx +0 -40
  100. package/src/components/Workbook/index.ts +0 -10
@@ -11,6 +11,13 @@ import {
11
11
  filterInnerType,
12
12
  isFilterType,
13
13
  isPlainFilterList,
14
+ decodeBetween,
15
+ decodeDayRange,
16
+ decodeTimePreset,
17
+ encodeBetween,
18
+ encodeDayRange,
19
+ encodeTimePreset,
20
+ TIME_PRESETS,
14
21
  } from "./filterValue";
15
22
 
16
23
  /**
@@ -362,3 +369,108 @@ describe("isPlainFilterList", () => {
362
369
  expect(isPlainFilterList("-Nike")).toBe(false);
363
370
  });
364
371
  });
372
+
373
+ describe("encodeBetween / decodeBetween, the two-handled slider's filter", () => {
374
+ it("writes Malloy's closed range, the spelling Malloyyo writes too", () => {
375
+ expect(encodeBetween(10, 20)).toBe("[10 to 20]");
376
+ expect(decodeBetween("[10 to 20]")).toEqual([10, 20]);
377
+ });
378
+
379
+ it("reads whitespace and decimals the grammar accepts", () => {
380
+ expect(decodeBetween(" [0.5 to 1e3] ")).toEqual([0.5, 1000]);
381
+ });
382
+
383
+ it("refuses a half-open range, which no thumb can show", () => {
384
+ expect(decodeBetween("(10 to 20]")).toBeUndefined();
385
+ expect(decodeBetween("[10 to 20)")).toBeUndefined();
386
+ });
387
+
388
+ it("refuses a negation, a threshold and the empty filter", () => {
389
+ expect(decodeBetween("not [10 to 20]")).toBeUndefined();
390
+ expect(decodeBetween(">= 5")).toBeUndefined();
391
+ expect(decodeBetween("")).toBeUndefined();
392
+ });
393
+
394
+ it("refuses an inverted range rather than drawing it backwards", () => {
395
+ expect(decodeBetween("[20 to 10]")).toBeUndefined();
396
+ });
397
+ });
398
+
399
+ describe("time presets", () => {
400
+ it("spell each preset in the filter grammar Malloyyo uses", () => {
401
+ expect(TIME_PRESETS.map((p) => encodeTimePreset(p.key))).toEqual([
402
+ "today",
403
+ "7 days",
404
+ "30 days",
405
+ "90 days",
406
+ "12 months",
407
+ ]);
408
+ });
409
+
410
+ it("round-trip every preset", () => {
411
+ for (const preset of TIME_PRESETS) {
412
+ expect(decodeTimePreset(encodeTimePreset(preset.key)!)).toBe(
413
+ preset.key,
414
+ );
415
+ }
416
+ });
417
+
418
+ it("match on the clause, not the spelling", () => {
419
+ expect(decodeTimePreset("7 day")).toBe("7d");
420
+ expect(decodeTimePreset(" 12 months ")).toBe("12m");
421
+ });
422
+
423
+ it("are not fooled by a window of another size, or a negation", () => {
424
+ expect(decodeTimePreset("8 days")).toBeUndefined();
425
+ expect(decodeTimePreset("not today")).toBeUndefined();
426
+ expect(decodeTimePreset("last 7 days")).toBeUndefined();
427
+ expect(decodeTimePreset("")).toBeUndefined();
428
+ });
429
+
430
+ it("have no key that is not encodable", () => {
431
+ expect(encodeTimePreset("nope")).toBeUndefined();
432
+ });
433
+ });
434
+
435
+ describe("encodeDayRange / decodeDayRange, inclusive days over a half-open grammar", () => {
436
+ it("encodes the day after the last picked day, since `to` excludes its end", () => {
437
+ expect(encodeDayRange("2024-01-01", "2024-01-31")).toBe(
438
+ "2024-01-01 to 2024-02-01",
439
+ );
440
+ // A single picked day is that whole day.
441
+ expect(encodeDayRange("2024-02-28", "2024-02-28")).toBe(
442
+ "2024-02-28 to 2024-02-29",
443
+ );
444
+ });
445
+
446
+ it("decodes back to the days the filter actually selects", () => {
447
+ expect(decodeDayRange("2024-01-01 to 2024-02-01")).toEqual({
448
+ firstDay: "2024-01-01",
449
+ lastDay: "2024-01-31",
450
+ });
451
+ });
452
+
453
+ it("round-trips through a leap day and a year end", () => {
454
+ for (const [a, b] of [
455
+ ["2024-02-28", "2024-02-29"],
456
+ ["2023-12-25", "2024-01-05"],
457
+ ]) {
458
+ expect(decodeDayRange(encodeDayRange(a, b))).toEqual({
459
+ firstDay: a,
460
+ lastDay: b,
461
+ });
462
+ }
463
+ });
464
+
465
+ it("refuses an end that is not after the start", () => {
466
+ expect(decodeDayRange("2024-01-10 to 2024-01-10")).toBeUndefined();
467
+ expect(decodeDayRange("2024-01-10 to 2024-01-01")).toBeUndefined();
468
+ });
469
+
470
+ it("refuses ends two day pickers cannot show", () => {
471
+ expect(decodeDayRange("2024-01-01 to now")).toBeUndefined();
472
+ expect(decodeDayRange("2024-01-01 12:00 to 2024-01-02")).toBeUndefined();
473
+ expect(decodeDayRange("not 2024-01-01 to 2024-02-01")).toBeUndefined();
474
+ expect(decodeDayRange("7 days")).toBeUndefined();
475
+ });
476
+ });
@@ -26,9 +26,16 @@ import {
26
26
  isStringCondition,
27
27
  NumberFilterExpression,
28
28
  StringFilterExpression,
29
+ TemporalFilterExpression,
30
+ type Moment,
29
31
  type StringCondition,
30
32
  type StringFilter,
33
+ type TemporalFilter,
31
34
  } from "@malloydata/malloy-filter";
35
+ import dayjs from "dayjs";
36
+ import utc from "dayjs/plugin/utc";
37
+
38
+ dayjs.extend(utc);
32
39
 
33
40
  /** True for the `filter<…>` family, whose values are filter syntax, not plain. */
34
41
  export function isFilterType(type: string | undefined): boolean {
@@ -205,3 +212,184 @@ export function decodeAtLeast(value: string): number | undefined {
205
212
  const bound = Number(parsed.values[0]);
206
213
  return Number.isFinite(bound) ? bound : undefined;
207
214
  }
215
+
216
+ /**
217
+ * An inclusive number range, which is what a two-handled slider means:
218
+ * `encodeBetween(10, 20)` is `[10 to 20]`, Malloy's `>= 10 and <= 20`. The same
219
+ * spelling Malloyyo's `filters.between` writes, so a value set on either host
220
+ * reads back on the other.
221
+ */
222
+ export function encodeBetween(lo: number, hi: number): string {
223
+ return NumberFilterExpression.unparse({
224
+ operator: "range",
225
+ startOperator: ">=",
226
+ startValue: String(lo),
227
+ endOperator: "<=",
228
+ endValue: String(hi),
229
+ });
230
+ }
231
+
232
+ /**
233
+ * The bounds back out of {@link encodeBetween}, or undefined for any other
234
+ * filter. Only the closed range round-trips: `(10 to 20]` and its kin exclude an
235
+ * end the slider's thumbs cannot express, and a negated range is not a range at
236
+ * all, so both fall through to the text box rather than being redrawn as
237
+ * something else.
238
+ */
239
+ export function decodeBetween(value: string): [number, number] | undefined {
240
+ const text = value.trim();
241
+ if (text === "") return undefined;
242
+ const { parsed } = NumberFilterExpression.parse(text);
243
+ if (
244
+ parsed === null ||
245
+ parsed.operator !== "range" ||
246
+ parsed.not === true ||
247
+ parsed.startOperator !== ">=" ||
248
+ parsed.endOperator !== "<="
249
+ ) {
250
+ return undefined;
251
+ }
252
+ const lo = Number(parsed.startValue);
253
+ const hi = Number(parsed.endValue);
254
+ return Number.isFinite(lo) && Number.isFinite(hi) && lo <= hi
255
+ ? [lo, hi]
256
+ : undefined;
257
+ }
258
+
259
+ /**
260
+ * The preset windows a time-range control offers for a `filter<date>` or
261
+ * `filter<timestamp>` given. The same six Malloyyo's `TimeRange` widget ships,
262
+ * spelled in Malloy's filter grammar: `today` is the current day, `7 days` is
263
+ * Malloy's "in the last 7 days", a rolling window ending now.
264
+ *
265
+ * Structured clauses rather than strings so the spelling on the wire is the
266
+ * filter package's own, and {@link decodeTimePreset} compares against the same
267
+ * structure the parser returns rather than against text that may be spelled
268
+ * `7 day`, `7 days` or `7 days` by whoever wrote the URL.
269
+ */
270
+ export const TIME_PRESETS: readonly {
271
+ key: string;
272
+ label: string;
273
+ clause: TemporalFilter;
274
+ }[] = [
275
+ {
276
+ key: "today",
277
+ label: "Today",
278
+ clause: { operator: "in", in: { moment: "today" } },
279
+ },
280
+ {
281
+ key: "7d",
282
+ label: "Last 7 days",
283
+ clause: { operator: "in_last", units: "day", n: "7" },
284
+ },
285
+ {
286
+ key: "30d",
287
+ label: "Last 30 days",
288
+ clause: { operator: "in_last", units: "day", n: "30" },
289
+ },
290
+ {
291
+ key: "90d",
292
+ label: "Last 90 days",
293
+ clause: { operator: "in_last", units: "day", n: "90" },
294
+ },
295
+ {
296
+ key: "12m",
297
+ label: "Last 12 months",
298
+ clause: { operator: "in_last", units: "month", n: "12" },
299
+ },
300
+ ];
301
+
302
+ /** The filter text for one of {@link TIME_PRESETS}, by key. */
303
+ export function encodeTimePreset(key: string): string | undefined {
304
+ const preset = TIME_PRESETS.find((p) => p.key === key);
305
+ return preset ? TemporalFilterExpression.unparse(preset.clause) : undefined;
306
+ }
307
+
308
+ /**
309
+ * Which preset a filter is, or undefined when it is none of them. Matched on the
310
+ * parsed clause, so `7 day` and `7 days` are the same window, and a negated or
311
+ * compound filter is not a preset however it is spelled.
312
+ */
313
+ export function decodeTimePreset(value: string): string | undefined {
314
+ const text = value.trim();
315
+ if (text === "") return undefined;
316
+ const { parsed } = TemporalFilterExpression.parse(text);
317
+ if (parsed === null) return undefined;
318
+ for (const preset of TIME_PRESETS) {
319
+ const want = preset.clause;
320
+ if (want.operator !== parsed.operator) continue;
321
+ if (want.operator === "in" && parsed.operator === "in") {
322
+ if (parsed.not !== true && parsed.in.moment === want.in.moment) {
323
+ return preset.key;
324
+ }
325
+ }
326
+ if (want.operator === "in_last" && parsed.operator === "in_last") {
327
+ if (
328
+ parsed.not !== true &&
329
+ parsed.units === want.units &&
330
+ Number(parsed.n) === Number(want.n)
331
+ ) {
332
+ return preset.key;
333
+ }
334
+ }
335
+ }
336
+ return undefined;
337
+ }
338
+
339
+ const DAY = /^\d{4}-\d{2}-\d{2}$/;
340
+
341
+ /**
342
+ * An inclusive range of whole days, as two `YYYY-MM-DD` strings, in Malloy's
343
+ * filter grammar.
344
+ *
345
+ * Malloy's `A to B` runs from the start of A up to but NOT including the start
346
+ * of B (`filter_compilers.ts`, `case 'to'`), while a reader picking "January
347
+ * 1st to January 31st" means both days. So the end is encoded as the day AFTER
348
+ * the last day picked: `encodeDayRange("2024-01-01", "2024-01-31")` is
349
+ * `2024-01-01 to 2024-02-01`. {@link decodeDayRange} undoes exactly that, so a
350
+ * range written by Malloyyo (which encodes the picked day verbatim) displays
351
+ * here as the days it actually selects.
352
+ */
353
+ export function encodeDayRange(firstDay: string, lastDay: string): string {
354
+ const end = dayjs.utc(lastDay, "YYYY-MM-DD").add(1, "day");
355
+ return TemporalFilterExpression.unparse({
356
+ operator: "to",
357
+ fromMoment: { moment: "literal", literal: firstDay, units: "day" },
358
+ toMoment: {
359
+ moment: "literal",
360
+ literal: end.format("YYYY-MM-DD"),
361
+ units: "day",
362
+ },
363
+ });
364
+ }
365
+
366
+ /**
367
+ * The inclusive days back out of {@link encodeDayRange}, or undefined for any
368
+ * other filter. Both ends must be whole-day literals: a range with a time of
369
+ * day, a relative end (`2024-01-01 to now`), or a negation is not something two
370
+ * day pickers can show, and falls through to the text box.
371
+ */
372
+ export function decodeDayRange(
373
+ value: string,
374
+ ): { firstDay: string; lastDay: string } | undefined {
375
+ const text = value.trim();
376
+ if (text === "") return undefined;
377
+ const { parsed } = TemporalFilterExpression.parse(text);
378
+ if (parsed === null || parsed.operator !== "to" || parsed.not === true) {
379
+ return undefined;
380
+ }
381
+ const from = dayLiteral(parsed.fromMoment);
382
+ const to = dayLiteral(parsed.toMoment);
383
+ if (from === undefined || to === undefined) return undefined;
384
+ const lastDay = dayjs.utc(to, "YYYY-MM-DD").subtract(1, "day");
385
+ if (!lastDay.isValid() || lastDay.isBefore(dayjs.utc(from, "YYYY-MM-DD"))) {
386
+ return undefined;
387
+ }
388
+ return { firstDay: from, lastDay: lastDay.format("YYYY-MM-DD") };
389
+ }
390
+
391
+ function dayLiteral(moment: Moment): string | undefined {
392
+ return moment.moment === "literal" && DAY.test(moment.literal)
393
+ ? moment.literal
394
+ : undefined;
395
+ }
@@ -7,3 +7,7 @@ export {
7
7
  type GivensLayout,
8
8
  type GivensPanelProps,
9
9
  } from "./GivensPanel";
10
+ export {
11
+ useGivenUrlParams,
12
+ type UseGivenUrlParamsResult,
13
+ } from "./useGivenUrlParams";
@@ -0,0 +1,74 @@
1
+ // Copyright (c) Credible Data Inc.
2
+ // SPDX-License-Identifier: MIT
3
+
4
+ import { describe, expect, it } from "bun:test";
5
+ import { act, renderHook } from "@testing-library/react";
6
+ import type { ReactNode } from "react";
7
+ import { MemoryRouter, useLocation } from "react-router-dom";
8
+ import { useGivenUrlParams } from "./useGivenUrlParams";
9
+
10
+ function mount(initialEntry: string) {
11
+ const wrapper = ({ children }: { children: ReactNode }) => (
12
+ <MemoryRouter initialEntries={[initialEntry]}>{children}</MemoryRouter>
13
+ );
14
+ const view = renderHook(
15
+ () => ({ hook: useGivenUrlParams(), location: useLocation() }),
16
+ { wrapper },
17
+ );
18
+ return {
19
+ get params() {
20
+ return view.result.current.hook.params;
21
+ },
22
+ get search() {
23
+ return new URLSearchParams(view.result.current.location.search);
24
+ },
25
+ get hash() {
26
+ return view.result.current.location.hash;
27
+ },
28
+ change(next: Record<string, string>, managed: string[]) {
29
+ act(() => view.result.current.hook.onGivensChange(next, managed));
30
+ },
31
+ };
32
+ }
33
+
34
+ describe("useGivenUrlParams", () => {
35
+ it("reads the query string as a flat record", () => {
36
+ const host = mount("/d?REGION=West&utm=x");
37
+ expect(host.params).toEqual({ REGION: "West", utm: "x" });
38
+ });
39
+
40
+ it("merges into the query string, leaving parameters that are not ours", () => {
41
+ const host = mount("/d?utm=x");
42
+ host.change({ REGION: "West" }, ["REGION"]);
43
+ expect(host.search.get("REGION")).toBe("West");
44
+ expect(host.search.get("utm")).toBe("x");
45
+ });
46
+
47
+ it("removes a managed name that was cleared, and only that", () => {
48
+ const host = mount("/d?REGION=West&STATUS=open&utm=x");
49
+ host.change({ STATUS: "open" }, ["REGION", "STATUS"]);
50
+ expect(host.search.has("REGION")).toBe(false);
51
+ expect(host.search.get("STATUS")).toBe("open");
52
+ expect(host.search.get("utm")).toBe("x");
53
+ });
54
+
55
+ it("remembers what it wrote, so a given the model stopped declaring is still cleaned up", () => {
56
+ const host = mount("/d");
57
+ host.change({ REGION: "West" }, ["REGION"]);
58
+ // The model reloads without REGION; the report no longer manages it.
59
+ host.change({}, []);
60
+ expect(host.search.has("REGION")).toBe(false);
61
+ });
62
+
63
+ it("keeps the fragment the reader arrived on", () => {
64
+ const host = mount("/d?utm=x#trend");
65
+ host.change({ REGION: "West" }, ["REGION"]);
66
+ expect(host.hash).toBe("#trend");
67
+ });
68
+
69
+ it("is not fooled by a given named like an Object.prototype member", () => {
70
+ const host = mount("/d?constructor=1");
71
+ host.change({}, ["constructor"]);
72
+ expect(host.search.has("constructor")).toBe(false);
73
+ });
74
+ });
@@ -0,0 +1,87 @@
1
+ // Copyright (c) Credible Data Inc.
2
+ // SPDX-License-Identifier: MIT
3
+
4
+ import { useCallback, useMemo, useRef } from "react";
5
+ import { useLocation, useNavigate, useSearchParams } from "react-router-dom";
6
+
7
+ export interface UseGivenUrlParamsResult {
8
+ /** The query string as a flat record: what a document reads its givens from. */
9
+ params: Record<string, string>;
10
+ /**
11
+ * For a document's `onGivensChange`: writes the applied values into the
12
+ * query string, in place, leaving every parameter that is not a given alone.
13
+ */
14
+ onGivensChange: (
15
+ next: Record<string, string>,
16
+ managed: readonly string[],
17
+ ) => void;
18
+ }
19
+
20
+ /**
21
+ * Keep a document's control values in the page's query string, so a filtered
22
+ * dashboard or a parameterized notebook is a shareable link.
23
+ *
24
+ * This is the host side of `useGivensState`: the document reports its applied
25
+ * values and the names it manages, this writes them into the URL and feeds the
26
+ * URL back in as `params`. The two Console pages carried a copy each; they
27
+ * agreed line for line, so this is that code once, for any host on
28
+ * react-router.
29
+ *
30
+ * Three things it is careful about, each of which was a bug once:
31
+ *
32
+ * - **Merge, never replace.** The query string is not the document's alone: a
33
+ * tracking tag or any other unrelated parameter shares it, and replacing the
34
+ * whole string dropped those on LOAD, as soon as the first report arrived.
35
+ * Only names that are ours are touched: what the document manages now, plus
36
+ * anything this hook wrote earlier, so a control cleared after a model reload
37
+ * stopped declaring it still gets its parameter removed. That memory outlives
38
+ * a document swap on purpose: the parameter written for the previous
39
+ * document is the stale one the next should clear.
40
+ * - **`hasOwnProperty`, not `in`.** `next` is a plain object literal, so `in`
41
+ * walks its prototype and reports `constructor`, `toString` and friends as
42
+ * present; a given with one of those names could never be cleared.
43
+ * - **Replace, and keep the hash.** Changing a control is not a navigation
44
+ * step, so Back should leave the document rather than walk back through
45
+ * every value tried. And a navigation that names only `search` resolves to an
46
+ * empty fragment, which dropped whatever anchor the reader arrived on;
47
+ * `setSearchParams` has that problem, which is why this navigates itself.
48
+ */
49
+ export function useGivenUrlParams(): UseGivenUrlParamsResult {
50
+ const [searchParams] = useSearchParams();
51
+ const navigate = useNavigate();
52
+ const location = useLocation();
53
+
54
+ const params = useMemo(
55
+ () => Object.fromEntries(searchParams.entries()),
56
+ [searchParams],
57
+ );
58
+
59
+ const writtenRef = useRef<Set<string>>(new Set());
60
+
61
+ const onGivensChange = useCallback(
62
+ (next: Record<string, string>, managed: readonly string[]) => {
63
+ const ours = new Set([...managed, ...writtenRef.current]);
64
+ writtenRef.current = new Set([
65
+ ...writtenRef.current,
66
+ ...Object.keys(next),
67
+ ...managed,
68
+ ]);
69
+ const merged = new URLSearchParams(location.search);
70
+ for (const name of ours) {
71
+ if (!Object.prototype.hasOwnProperty.call(next, name)) {
72
+ merged.delete(name);
73
+ }
74
+ }
75
+ for (const [name, value] of Object.entries(next)) {
76
+ merged.set(name, value);
77
+ }
78
+ navigate(
79
+ { search: merged.toString(), hash: location.hash },
80
+ { replace: true },
81
+ );
82
+ },
83
+ [navigate, location],
84
+ );
85
+
86
+ return { params, onGivensChange };
87
+ }
@@ -1,7 +1,10 @@
1
1
  // Copyright (c) Credible Data Inc.
2
2
  // SPDX-License-Identifier: MIT
3
3
 
4
- export { AnalyzePackageButton } from "./AnalyzePackageButton";
4
+ // Exported because Dashboard, DashboardTile and Notebook all present request
5
+ // failures through it; a host composing those needs the same presentation for
6
+ // its own.
7
+ export { ApiErrorDisplay, type ApiErrorDisplayProps } from "./ApiErrorDisplay";
5
8
  export { useRouterClickHandler, type NavigationClick } from "./click_helper";
6
9
  export * from "./Dashboard";
7
10
  export * from "./DataAppViewer";
@@ -19,5 +22,4 @@ export * from "./QueryResult";
19
22
  export * from "./RenderedResult";
20
23
  export { ServerProvider, useServer } from "./ServerProvider";
21
24
  export type { ServerContextValue, ServerProviderProps } from "./ServerProvider";
22
- export * from "./Workbook";
23
- export type { WorkbookStorage } from "./Workbook";
25
+ export * from "./DocumentStorage";
@@ -26,7 +26,6 @@ export {
26
26
  export {
27
27
  useDimensionalFilterRangeData,
28
28
  getDimensionKey,
29
- makeDimensionKey,
30
29
  type DimensionalFilterRangeDataResult,
31
30
  type DimensionSpec,
32
31
  type DimensionValue,
@@ -447,3 +447,161 @@ describe("useGivensState: swapping documents", () => {
447
447
  expect(entries(result.current.applied)).toEqual({});
448
448
  });
449
449
  });
450
+
451
+ describe("useGivensState: clearing a given that has a starting value", () => {
452
+ // The limitation this hook used to document. A clear dropped the name from
453
+ // the report, the host removed it from the URL and fed that URL back in, and
454
+ // the changed `params` re-keyed the edits away: `initial` recomputed from the
455
+ // starting values and the control snapped back to what was just cleared.
456
+ it("stays cleared when the host echoes the URL back", () => {
457
+ const host = renderWithUrlHost({
458
+ autorun: true,
459
+ startingValues: { REGION: "West" },
460
+ });
461
+ expect(entries(host.current.applied)).toEqual({ REGION: "West" });
462
+
463
+ act(() => host.current.setGiven("REGION", null));
464
+ host.settle();
465
+ expect(entries(host.current.applied)).toEqual({});
466
+ expect(entries(host.current.draft)).toEqual({});
467
+ expect(host.url).toEqual({});
468
+ });
469
+
470
+ it("clears one starting value while keeping another", () => {
471
+ const host = renderWithUrlHost({
472
+ autorun: true,
473
+ startingValues: { REGION: "West", MIN_AMOUNT: "5" },
474
+ });
475
+ act(() => host.current.setGiven("REGION", null));
476
+ host.settle();
477
+ expect(entries(host.current.applied)).toEqual({ MIN_AMOUNT: 5 });
478
+ expect(host.url).toEqual({ MIN_AMOUNT: "5" });
479
+ });
480
+
481
+ it("still takes a URL the host did NOT get from us, such as a drill landing", () => {
482
+ const { result, rerender } = renderHook(
483
+ (props: { params: Record<string, string> }) =>
484
+ useGivensState({
485
+ declaredTypes: TYPES,
486
+ startingValues: { REGION: "West" },
487
+ params: props.params,
488
+ documentKey: "overview",
489
+ autorun: true,
490
+ }),
491
+ { initialProps: { params: {} } },
492
+ );
493
+ act(() => result.current.setGiven("REGION", null));
494
+ expect(entries(result.current.applied)).toEqual({});
495
+
496
+ // Not an echo: nothing this hook reported said East.
497
+ rerender({ params: { REGION: "East" } });
498
+ expect(entries(result.current.applied)).toEqual({ REGION: "East" });
499
+ });
500
+
501
+ it("treats a host that keeps unrelated parameters beside ours as an echo", () => {
502
+ const { result, rerender } = renderHook(
503
+ (props: { params: Record<string, string> }) =>
504
+ useGivensState({
505
+ declaredTypes: TYPES,
506
+ startingValues: { REGION: "West" },
507
+ params: props.params,
508
+ documentKey: "overview",
509
+ autorun: true,
510
+ }),
511
+ { initialProps: { params: { tab: "sales" } } },
512
+ );
513
+ act(() => result.current.setGiven("REGION", null));
514
+ // The host writes our (empty) report but keeps its own `tab`.
515
+ rerender({ params: { tab: "sales" } });
516
+ expect(entries(result.current.applied)).toEqual({});
517
+ // And the same with the report carrying a value.
518
+ act(() => result.current.setGiven("REGION", "East"));
519
+ rerender({ params: { tab: "sales", REGION: "East" } });
520
+ expect(entries(result.current.applied)).toEqual({ REGION: "East" });
521
+ });
522
+
523
+ // The regression that broke notebook clearing. A report does not reach
524
+ // `params` in the same tick, so a re-render in between (a cell finishing, the
525
+ // host's callback changing identity with its location) arrives carrying the
526
+ // URL the report has not replaced yet. Matching only the newest report read
527
+ // that stale URL as an external push: the anchor moved, the edits were
528
+ // discarded, and `initial` put the cleared value back in the control and then
529
+ // wrote it to the URL again.
530
+ it("keeps a clear across a render that still carries the pre-report URL", () => {
531
+ let url: Record<string, string> = {};
532
+ const urlWrites: Record<string, string>[] = [];
533
+ const { result, rerender } = renderHook(
534
+ (props: { params: Record<string, string> }) =>
535
+ useGivensState({
536
+ declaredTypes: TYPES,
537
+ params: props.params,
538
+ onParamsChange: (next) => {
539
+ url = next;
540
+ urlWrites.push(next);
541
+ },
542
+ documentKey: "notebook",
543
+ autorun: true,
544
+ }),
545
+ { initialProps: { params: url } },
546
+ );
547
+
548
+ act(() => result.current.setGiven("REGION", "East"));
549
+ rerender({ params: url });
550
+ expect(entries(result.current.applied)).toEqual({ REGION: "East" });
551
+
552
+ act(() => result.current.setGiven("REGION", null));
553
+ expect(url).toEqual({});
554
+
555
+ // The stale render: the host has been told, but its URL has not landed.
556
+ rerender({ params: { REGION: "East" } });
557
+ expect(entries(result.current.applied)).toEqual({});
558
+
559
+ // And then the real one.
560
+ rerender({ params: url });
561
+ expect(entries(result.current.applied)).toEqual({});
562
+ expect(urlWrites.at(-1)).toEqual({});
563
+ });
564
+
565
+ // The other half: once the newer report HAS been seen, the URL it replaced is
566
+ // no longer in flight, so going back to it is a real navigation.
567
+ it("treats the previous URL as a new starting point once the report lands", () => {
568
+ let url: Record<string, string> = {};
569
+ const { result, rerender } = renderHook(
570
+ (props: { params: Record<string, string> }) =>
571
+ useGivensState({
572
+ declaredTypes: TYPES,
573
+ params: props.params,
574
+ onParamsChange: (next) => {
575
+ url = next;
576
+ },
577
+ documentKey: "notebook",
578
+ autorun: true,
579
+ }),
580
+ { initialProps: { params: url } },
581
+ );
582
+
583
+ act(() => result.current.setGiven("REGION", "East"));
584
+ rerender({ params: url });
585
+ act(() => result.current.setGiven("REGION", null));
586
+ rerender({ params: url });
587
+ expect(entries(result.current.applied)).toEqual({});
588
+
589
+ // Back button to the URL that carried East: a starting point, not an echo.
590
+ rerender({ params: { REGION: "East" } });
591
+ expect(entries(result.current.applied)).toEqual({ REGION: "East" });
592
+ });
593
+
594
+ it("Reset after a clear restores the starting value and runs once", () => {
595
+ const host = renderWithUrlHost({
596
+ autorun: true,
597
+ startingValues: { REGION: "West" },
598
+ });
599
+ act(() => host.current.setGiven("REGION", null));
600
+ host.settle();
601
+ const writes = host.urlWrites.length;
602
+ act(() => host.current.reset());
603
+ host.settle();
604
+ expect(entries(host.current.applied)).toEqual({ REGION: "West" });
605
+ expect(host.urlWrites.length).toBe(writes + 1);
606
+ });
607
+ });