@malloy-publisher/sdk 0.3.0 → 0.3.1

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 (156) hide show
  1. package/README.md +8 -0
  2. package/dist/DocumentStorageProvider-BeBD0uWc.cjs.js +134 -0
  3. package/dist/DocumentStorageProvider-tGvodI8f.es.js +24268 -0
  4. package/dist/RenderedResult-CPi6uQWq.cjs.js +115 -0
  5. package/dist/RenderedResult-mDE-4u8S.es.js +542 -0
  6. package/dist/ServerProvider-CH71GsoL.cjs.js +1 -0
  7. package/dist/{ServerProvider-DSK9rfSY.es.js → ServerProvider-X2Ma0HRs.es.js} +486 -521
  8. package/dist/builder/index.cjs.js +105 -0
  9. package/dist/builder/index.d.ts +2 -0
  10. package/dist/builder/index.es.js +9561 -0
  11. package/dist/builder-entry.d.ts +8 -0
  12. package/dist/client/index.cjs.js +1 -1
  13. package/dist/client/index.es.js +1 -1
  14. package/dist/components/Dashboard/Dashboard.d.ts +19 -14
  15. package/dist/components/Dashboard/DashboardGrid.d.ts +67 -0
  16. package/dist/components/Dashboard/DashboardTile.d.ts +6 -1
  17. package/dist/components/Dashboard/ExploreDialog.d.ts +18 -0
  18. package/dist/components/Dashboard/RowsDialog.d.ts +47 -0
  19. package/dist/components/Dashboard/TileCard.d.ts +44 -0
  20. package/dist/components/Dashboard/index.d.ts +2 -0
  21. package/dist/components/Dashboard/promoteMeasureRow.d.ts +7 -3
  22. package/dist/components/Dashboard/telemetry.d.ts +43 -0
  23. package/dist/components/DashboardBuilder/AddTileDialog.d.ts +35 -0
  24. package/dist/components/DashboardBuilder/BuilderToolbar.d.ts +29 -0
  25. package/dist/components/DashboardBuilder/DashboardBuilder.d.ts +112 -0
  26. package/dist/components/DashboardBuilder/DashboardEditor.d.ts +32 -0
  27. package/dist/components/DashboardBuilder/DiffDialog.d.ts +15 -0
  28. package/dist/components/DashboardBuilder/DrillDialog.d.ts +15 -0
  29. package/dist/components/DashboardBuilder/FilterDialog.d.ts +54 -0
  30. package/dist/components/DashboardBuilder/FilterStrip.d.ts +17 -0
  31. package/dist/components/DashboardBuilder/SettingsPopover.d.ts +20 -0
  32. package/dist/components/DashboardBuilder/TileFrame.d.ts +42 -0
  33. package/dist/components/DashboardBuilder/TileMenu.d.ts +24 -0
  34. package/dist/components/DashboardBuilder/catalog.d.ts +62 -0
  35. package/dist/components/DashboardBuilder/controls.d.ts +157 -0
  36. package/dist/components/DashboardBuilder/diff.d.ts +35 -0
  37. package/dist/components/DashboardBuilder/document.d.ts +218 -0
  38. package/dist/components/DashboardBuilder/layout.d.ts +71 -0
  39. package/dist/components/DashboardBuilder/malloyText.d.ts +45 -0
  40. package/dist/components/DashboardBuilder/preview.d.ts +60 -0
  41. package/dist/components/DashboardBuilder/readDocument.d.ts +106 -0
  42. package/dist/components/DashboardBuilder/sortable.d.ts +51 -0
  43. package/dist/components/DashboardBuilder/spliceDocument.d.ts +44 -0
  44. package/dist/components/DashboardBuilder/testing/fixtures.d.ts +10 -0
  45. package/dist/components/DashboardBuilder/useBuilderShortcuts.d.ts +22 -0
  46. package/dist/components/DashboardBuilder/useDashboardEditor.d.ts +63 -0
  47. package/dist/components/DashboardBuilder/useDraft.d.ts +13 -0
  48. package/dist/components/DashboardBuilder/useFilterForm.d.ts +65 -0
  49. package/dist/components/DashboardBuilder/useTileReorder.d.ts +22 -0
  50. package/dist/components/DashboardBuilder/useTileResize.d.ts +29 -0
  51. package/dist/components/DocumentStorage/DocumentStorageProvider.d.ts +7 -0
  52. package/dist/components/DocumentStorage/index.d.ts +1 -1
  53. package/dist/components/FloatingIconButton.d.ts +16 -0
  54. package/dist/components/Prose.d.ts +46 -0
  55. package/dist/components/RenderedResult/ResultPanel.d.ts +30 -0
  56. package/dist/components/RenderedResult/index.d.ts +1 -0
  57. package/dist/components/drill/index.d.ts +1 -1
  58. package/dist/components/drill/resolveDrill.d.ts +22 -0
  59. package/dist/components/drill/useDrill.d.ts +11 -2
  60. package/dist/components/index.d.ts +1 -0
  61. package/dist/components/styles.d.ts +0 -4
  62. package/dist/hooks/index.d.ts +2 -0
  63. package/dist/hooks/useDocumentControls.d.ts +70 -0
  64. package/dist/hooks/useQueryResult.d.ts +40 -0
  65. package/dist/index.cjs.js +23 -270
  66. package/dist/index.es.js +16977 -41293
  67. package/dist/utils/malloyLiteral.d.ts +11 -0
  68. package/package.json +24 -9
  69. package/src/builder-entry.ts +55 -0
  70. package/src/components/Dashboard/Dashboard.spec.tsx +7 -10
  71. package/src/components/Dashboard/Dashboard.tsx +165 -175
  72. package/src/components/Dashboard/DashboardGrid.tsx +124 -0
  73. package/src/components/Dashboard/DashboardTile.spec.tsx +30 -6
  74. package/src/components/Dashboard/DashboardTile.tsx +66 -123
  75. package/src/components/Dashboard/ExploreDialog.tsx +84 -0
  76. package/src/components/Dashboard/RowsDialog.spec.ts +42 -0
  77. package/src/components/Dashboard/RowsDialog.tsx +234 -0
  78. package/src/components/Dashboard/TileCard.tsx +120 -0
  79. package/src/components/Dashboard/index.ts +2 -0
  80. package/src/components/Dashboard/promoteMeasureRow.spec.ts +70 -0
  81. package/src/components/Dashboard/promoteMeasureRow.ts +33 -2
  82. package/src/components/Dashboard/telemetry.ts +44 -0
  83. package/src/components/Dashboard/tileGridColumn.spec.ts +1 -1
  84. package/src/components/DashboardBuilder/AddTileDialog.tsx +249 -0
  85. package/src/components/DashboardBuilder/BuilderToolbar.tsx +270 -0
  86. package/src/components/DashboardBuilder/DashboardBuilder.spec.tsx +858 -0
  87. package/src/components/DashboardBuilder/DashboardBuilder.tsx +653 -0
  88. package/src/components/DashboardBuilder/DashboardEditor.spec.tsx +211 -0
  89. package/src/components/DashboardBuilder/DashboardEditor.tsx +493 -0
  90. package/src/components/DashboardBuilder/DiffDialog.tsx +129 -0
  91. package/src/components/DashboardBuilder/DrillDialog.tsx +281 -0
  92. package/src/components/DashboardBuilder/FilterDialog.tsx +581 -0
  93. package/src/components/DashboardBuilder/FilterStrip.tsx +125 -0
  94. package/src/components/DashboardBuilder/SettingsPopover.tsx +168 -0
  95. package/src/components/DashboardBuilder/TileFrame.tsx +380 -0
  96. package/src/components/DashboardBuilder/TileMenu.tsx +188 -0
  97. package/src/components/DashboardBuilder/catalog.spec.ts +215 -0
  98. package/src/components/DashboardBuilder/catalog.ts +225 -0
  99. package/src/components/DashboardBuilder/controls.spec.ts +243 -0
  100. package/src/components/DashboardBuilder/controls.ts +398 -0
  101. package/src/components/DashboardBuilder/diff.spec.ts +44 -0
  102. package/src/components/DashboardBuilder/diff.ts +93 -0
  103. package/src/components/DashboardBuilder/document.ts +209 -0
  104. package/src/components/DashboardBuilder/keepRowStructure.spec.ts +84 -0
  105. package/src/components/DashboardBuilder/layout.ts +143 -0
  106. package/src/components/DashboardBuilder/malloyText.spec.ts +84 -0
  107. package/src/components/DashboardBuilder/malloyText.ts +151 -0
  108. package/src/components/DashboardBuilder/moveIntoGap.spec.ts +90 -0
  109. package/src/components/DashboardBuilder/preview.spec.ts +149 -0
  110. package/src/components/DashboardBuilder/preview.ts +172 -0
  111. package/src/components/DashboardBuilder/readDocument.spec.ts +375 -0
  112. package/src/components/DashboardBuilder/readDocument.ts +467 -0
  113. package/src/components/DashboardBuilder/sortable.tsx +151 -0
  114. package/src/components/DashboardBuilder/spliceDocument.spec.ts +1108 -0
  115. package/src/components/DashboardBuilder/spliceDocument.ts +1098 -0
  116. package/src/components/DashboardBuilder/testing/fixtures.ts +48 -0
  117. package/src/components/DashboardBuilder/useBuilderShortcuts.ts +88 -0
  118. package/src/components/DashboardBuilder/useDashboardEditor.spec.ts +255 -0
  119. package/src/components/DashboardBuilder/useDashboardEditor.ts +193 -0
  120. package/src/components/DashboardBuilder/useDraft.ts +43 -0
  121. package/src/components/DashboardBuilder/useFilterForm.spec.tsx +144 -0
  122. package/src/components/DashboardBuilder/useFilterForm.ts +352 -0
  123. package/src/components/DashboardBuilder/useTileReorder.spec.tsx +97 -0
  124. package/src/components/DashboardBuilder/useTileReorder.ts +115 -0
  125. package/src/components/DashboardBuilder/useTileResize.spec.tsx +121 -0
  126. package/src/components/DashboardBuilder/useTileResize.ts +110 -0
  127. package/src/components/DashboardBuilder/withGaps.spec.ts +96 -0
  128. package/src/components/DocumentStorage/DocumentStorageProvider.tsx +12 -0
  129. package/src/components/DocumentStorage/index.ts +1 -0
  130. package/src/components/Environment/About.tsx +4 -36
  131. package/src/components/FloatingIconButton.tsx +41 -0
  132. package/src/components/Model/Model.tsx +6 -23
  133. package/src/components/Model/ModelCell.tsx +33 -72
  134. package/src/components/Notebook/Notebook.tsx +25 -88
  135. package/src/components/Notebook/NotebookCell.tsx +35 -183
  136. package/src/components/Prose.spec.tsx +85 -0
  137. package/src/components/Prose.tsx +179 -0
  138. package/src/components/QueryResult/QueryResult.tsx +15 -43
  139. package/src/components/RenderedResult/ResultContainer.tsx +4 -12
  140. package/src/components/RenderedResult/ResultPanel.spec.tsx +49 -0
  141. package/src/components/RenderedResult/ResultPanel.tsx +73 -0
  142. package/src/components/RenderedResult/index.ts +1 -0
  143. package/src/components/drill/index.ts +1 -0
  144. package/src/components/drill/resolveDrill.ts +22 -1
  145. package/src/components/drill/useDrill.spec.tsx +94 -0
  146. package/src/components/drill/useDrill.tsx +52 -12
  147. package/src/components/given/GivensPanel.tsx +1 -1
  148. package/src/components/index.ts +6 -0
  149. package/src/components/styles.ts +0 -37
  150. package/src/hooks/index.ts +13 -0
  151. package/src/hooks/useDocumentControls.ts +170 -0
  152. package/src/hooks/useQueryResult.ts +82 -0
  153. package/src/utils/malloyLiteral.spec.ts +43 -0
  154. package/src/utils/malloyLiteral.ts +76 -0
  155. package/vite.config.ts +5 -0
  156. package/dist/ServerProvider-CGnLjzag.cjs.js +0 -1
@@ -0,0 +1,151 @@
1
+ // Copyright (c) Credible Data Inc.
2
+ // SPDX-License-Identifier: MIT
3
+
4
+ /**
5
+ * The textual reading of a dashboard file that the reader and the writer
6
+ * share: where declarations are, and how a tile expression splits.
7
+ *
8
+ * Text, not the parser's symbol tree, because the tree is unreliable inside a
9
+ * source — measured, a refinement spelled `+ { limit: 5, where: … }` makes it
10
+ * report the refined view's base as a child and drop the next declaration —
11
+ * and does not cover `given:` at all. A `<keyword>: <name> is` line under a
12
+ * `source: <name> is` line is unambiguous, and Malloy has no nested sources
13
+ * to confuse it. Both sides reading the same lines the same way is also what
14
+ * lets the writer patch exactly what the reader read.
15
+ */
16
+ const IDENT = "[A-Za-z_][A-Za-z0-9_]*";
17
+
18
+ export const isIdentifier = (text: string) =>
19
+ new RegExp(`^${IDENT}$`).test(text);
20
+
21
+ /** A one-line `<keyword>: <name> is <rest>` declaration. */
22
+ export interface DeclarationAt {
23
+ line: number;
24
+ /** Everything after `is`, trimmed: a base view, an expression, or `{`. */
25
+ rest: string;
26
+ }
27
+
28
+ /**
29
+ * The `<keyword>:` declarations under `source: <owner>`, in file order. The
30
+ * body of a source ends at the next top-level declaration or `##` line.
31
+ */
32
+ export function declarationsUnder(
33
+ lines: string[],
34
+ owner: string,
35
+ keyword: "view" | "dimension",
36
+ ): Map<string, DeclarationAt> {
37
+ const found = new Map<string, DeclarationAt>();
38
+ const declaration = new RegExp(
39
+ `^\\s*${keyword}:\\s*(${IDENT})\\s+is\\b\\s*(.*)$`,
40
+ );
41
+ let current: string | undefined;
42
+ for (let line = 0; line < lines.length; line++) {
43
+ const text = lines[line];
44
+ const source = new RegExp(`^\\s*source:\\s*(${IDENT})\\s+is\\b`).exec(
45
+ text,
46
+ );
47
+ if (source) {
48
+ current = source[1];
49
+ continue;
50
+ }
51
+ if (/^\s*(query|run|import|given)\b/.test(text) || text.startsWith("##"))
52
+ current = undefined;
53
+ if (current !== owner) continue;
54
+ const m = declaration.exec(text);
55
+ if (m) found.set(m[1], { line, rest: m[2].trim() });
56
+ }
57
+ return found;
58
+ }
59
+
60
+ /** The line declaring `<keyword>: <name> is`, or -1. */
61
+ export function declarationLine(
62
+ lines: string[],
63
+ keyword: "view" | "source",
64
+ name: string,
65
+ ): number {
66
+ const re = new RegExp(`^\\s*${keyword}:\\s*${name}\\s+is\\b`);
67
+ return lines.findIndex((l) => re.test(l));
68
+ }
69
+
70
+ /** The line carrying the model-level `## artifact` tag, or -1. */
71
+ export const artifactLine = (lines: string[]) =>
72
+ lines.findIndex(
73
+ (l) => l.trimStart().startsWith("##") && l.includes("artifact"),
74
+ );
75
+
76
+ /** A `given:` declaration: its line, and the block header when it is in one. */
77
+ export interface GivenAt {
78
+ line: number;
79
+ blockHeader?: number;
80
+ /** `NAME :: type is default`, as written. */
81
+ declaration: string;
82
+ }
83
+
84
+ /**
85
+ * Every `given:` declaration, by name, in both spellings Malloy accepts:
86
+ *
87
+ * given: CATEGORY :: filter<string> is f'' // one per line
88
+ *
89
+ * given: // a block
90
+ * CATEGORY :: filter<string> is f''
91
+ * SINCE :: date is @2023-01-01
92
+ */
93
+ export function givenDeclarations(lines: string[]): Map<string, GivenAt> {
94
+ const found = new Map<string, GivenAt>();
95
+ const nameOf = (declaration: string) =>
96
+ /^([A-Z_][A-Z0-9_]*)\s*::/.exec(declaration)?.[1];
97
+ const add = (line: number, declaration: string, blockHeader?: number) => {
98
+ const text = declaration.trim();
99
+ const name = nameOf(text);
100
+ if (name)
101
+ found.set(name, {
102
+ line,
103
+ declaration: text,
104
+ ...(blockHeader === undefined ? {} : { blockHeader }),
105
+ });
106
+ };
107
+ for (let i = 0; i < lines.length; i++) {
108
+ const text = lines[i].trim();
109
+ if (text === "given:") {
110
+ for (let j = i + 1; j < lines.length; j++) {
111
+ const inner = lines[j].trim();
112
+ if (
113
+ inner === "" ||
114
+ /^(source|query|import|run|given|##)/.test(inner)
115
+ )
116
+ break;
117
+ add(j, inner, i);
118
+ }
119
+ } else if (text.startsWith("given:")) {
120
+ add(i, text.slice("given:".length));
121
+ }
122
+ }
123
+ return found;
124
+ }
125
+
126
+ /** A tile expression's steps: `orders -> by_brand + { limit: 2 }`. */
127
+ export interface TileSteps {
128
+ source: string;
129
+ view: string;
130
+ /** The refinement on the view, `+ { … }`, when the expression carries one. */
131
+ refinement?: string;
132
+ }
133
+
134
+ /**
135
+ * `source -> view`, optionally refined — the one form the builder lays out.
136
+ * Undefined for anything else: an inline stage, or a longer pipeline.
137
+ */
138
+ export function tileSteps(
139
+ expression: string | undefined,
140
+ ): TileSteps | undefined {
141
+ const parts = (expression ?? "").split("->").map((p) => p.trim());
142
+ if (parts.length !== 2) return undefined;
143
+ const plus = parts[1].indexOf("+");
144
+ const view = plus < 0 ? parts[1] : parts[1].slice(0, plus).trim();
145
+ const refinement = plus < 0 ? undefined : parts[1].slice(plus).trim();
146
+ return {
147
+ source: parts[0],
148
+ view,
149
+ ...(refinement === undefined ? {} : { refinement }),
150
+ };
151
+ }
@@ -0,0 +1,90 @@
1
+ // Copyright (c) Credible Data Inc.
2
+ // SPDX-License-Identifier: MIT
3
+
4
+ import { describe, expect, it } from "bun:test";
5
+ import { moveIntoGap } from "./layout";
6
+ import type { DashboardTile } from "./document";
7
+
8
+ const tile = (
9
+ name: string,
10
+ colspan: number,
11
+ starts = false,
12
+ ): DashboardTile => ({
13
+ name,
14
+ source: "a",
15
+ declaration: { kind: "reference", from: `${name}_view` },
16
+ colspan,
17
+ ...(starts ? { break: true } : {}),
18
+ });
19
+
20
+ const rows = (tiles: DashboardTile[]) =>
21
+ tiles.map((each) => each.break ?? false);
22
+ const names = (tiles: DashboardTile[]) => tiles.map((each) => each.name);
23
+
24
+ describe("moveIntoGap", () => {
25
+ // The storefront overview with the trend narrowed to half width: a gap to
26
+ // its right, because `kpis` breaks onto a fresh row, then the map beside
27
+ // the kpis. The move that was impossible: the map, up into that gap.
28
+ const overview = [
29
+ tile("trend", 6),
30
+ tile("kpis", 6, true),
31
+ tile("map", 6),
32
+ tile("category", 6),
33
+ ];
34
+
35
+ it("flows the tile into the gap, and the next row still starts where it did", () => {
36
+ // After `trend` (index 0): slot 1 once `map` is taken out.
37
+ const settled = moveIntoGap(overview, 2, 1);
38
+
39
+ expect(names(settled)).toEqual(["trend", "map", "kpis", "category"]);
40
+ // `map` arrives with no break, so it sits beside `trend`; `kpis` keeps
41
+ // its break and still heads the second row. The positional rule would
42
+ // have put the break on `map` by position and left the gap in place.
43
+ expect(rows(settled)).toEqual([false, false, true, false]);
44
+ });
45
+
46
+ it("closes up the row the tile left, handing its row start on", () => {
47
+ const grid = [
48
+ tile("one", 6),
49
+ tile("two", 6, true),
50
+ tile("three", 6, true),
51
+ tile("four", 6),
52
+ ];
53
+ // `three` started its row; moving it up beside `one` must not leave
54
+ // `four` flowing into the row above, so `four` starts the row now.
55
+ const settled = moveIntoGap(grid, 2, 1);
56
+
57
+ expect(names(settled)).toEqual(["one", "three", "two", "four"]);
58
+ expect(rows(settled)).toEqual([false, false, true, true]);
59
+ });
60
+
61
+ it("does not hand on a row start the follower already has", () => {
62
+ const grid = [
63
+ tile("one", 6),
64
+ tile("two", 6, true),
65
+ tile("three", 6, true),
66
+ ];
67
+ const settled = moveIntoGap(grid, 1, 1);
68
+ // `two` was pulled up into the gap above itself. `three` already broke;
69
+ // it is not given a second one, and the object is left alone.
70
+ expect(rows(settled)).toEqual([false, false, true]);
71
+ expect(settled[2]).toBe(grid[2]);
72
+ });
73
+
74
+ it("pulling a tile into the gap right above it moves it up, and its row start on", () => {
75
+ // The tile has not moved in the array — but it has moved on the page:
76
+ // `kpis` loses its break and flows up beside `trend`, and `map`, which
77
+ // followed it, heads the row it left. The same hand-off as any other gap
78
+ // drop; the array order happening to be unchanged does not exempt it.
79
+ const settled = moveIntoGap(overview, 1, 1);
80
+ expect(names(settled)).toEqual(names(overview));
81
+ expect(rows(settled)).toEqual([false, false, true, false]);
82
+ });
83
+
84
+ it("leaves the tiles it did not touch as the objects they were", () => {
85
+ const settled = moveIntoGap(overview, 2, 1);
86
+ expect(settled[0]).toBe(overview[0]);
87
+ expect(settled[2]).toBe(overview[1]);
88
+ expect(settled[3]).toBe(overview[3]);
89
+ });
90
+ });
@@ -0,0 +1,149 @@
1
+ // Copyright (c) Credible Data Inc.
2
+ // SPDX-License-Identifier: MIT
3
+
4
+ import { describe, expect, it } from "bun:test";
5
+ import type { GivenValue } from "../../hooks/givenValue";
6
+ import type { DashboardDocument, DashboardTile } from "./document";
7
+ import { previewGivens, previewTileQuery } from "./preview";
8
+
9
+ const tile = (
10
+ name: string,
11
+ from: string,
12
+ filters?: DashboardTile["filters"],
13
+ ): DashboardTile => ({
14
+ name,
15
+ source: "overview",
16
+ declaration: { kind: "reference", from },
17
+ ...(filters ? { filters } : {}),
18
+ });
19
+
20
+ const document: DashboardDocument = {
21
+ title: "Overview",
22
+ imports: [],
23
+ sources: [{ name: "overview", base: "order_items" }],
24
+ localGivens: [
25
+ {
26
+ name: "CATEGORY",
27
+ type: "filter<string>",
28
+ default: "f''",
29
+ label: "Category",
30
+ control: "select",
31
+ suggest: { source: "products", dimension: "category" },
32
+ },
33
+ { name: "SINCE", type: "date", default: "@2023-01-01", label: "Since" },
34
+ { name: "UNBOUND", type: "filter<string>", default: "f''" },
35
+ ],
36
+ tiles: [
37
+ tile("kpis", "key_figures", [
38
+ { field: "category", given: "CATEGORY" },
39
+ { field: "created_at", given: "SINCE", op: ">=" },
40
+ ]),
41
+ tile("trend", "sales_by_month", [
42
+ { field: "category", given: "CATEGORY" },
43
+ ]),
44
+ tile("plain", "by_state"),
45
+ ],
46
+ };
47
+
48
+ describe("previewGivens", () => {
49
+ it("shows the givens some tile binds, this file's first, in declaration order", () => {
50
+ const specs = previewGivens(document, [
51
+ { name: "REGION", type: "filter<string>" },
52
+ { name: "CATEGORY", type: "filter<string>", label: "From the model" },
53
+ ]);
54
+ // UNBOUND is declared and bound by nothing, so it is not a control; the
55
+ // model's REGION is bound by nothing either. The model's CATEGORY shares
56
+ // a name with the local one, and the local declaration is the control.
57
+ expect(specs.map((s) => s.name)).toEqual(["CATEGORY", "SINCE"]);
58
+ expect(specs[0].label).toBe("Category");
59
+ expect(specs[0].control).toBe("select");
60
+ expect(specs[0].suggest).toEqual({
61
+ source: "products",
62
+ dimension: "category",
63
+ });
64
+ });
65
+
66
+ it("uses the model's own spec for a model given a tile binds", () => {
67
+ const withModel: DashboardDocument = {
68
+ ...document,
69
+ localGivens: [],
70
+ tiles: [tile("t", "v", [{ field: "brand", given: "BRAND" }])],
71
+ };
72
+ const spec = {
73
+ name: "BRAND",
74
+ type: "filter<string>",
75
+ suggest: {
76
+ query: "brand_suggest",
77
+ dimension: "brand",
78
+ givenNames: ["REGION"],
79
+ },
80
+ };
81
+ expect(previewGivens(withModel, [spec])).toEqual([spec]);
82
+ });
83
+ });
84
+
85
+ describe("previewTileQuery", () => {
86
+ const runnable = new Set(["CATEGORY", "SINCE"]);
87
+
88
+ it("runs the view on the source the extension extends, with the document's bindings", () => {
89
+ const q = previewTileQuery(document, document.tiles[0], runnable);
90
+ expect(q.expression).toBe(
91
+ "overview -> key_figures + { where: category ~ $CATEGORY, where: created_at >= $SINCE }",
92
+ );
93
+ expect(q.givenNames).toEqual(["CATEGORY", "SINCE"]);
94
+ });
95
+
96
+ it("sends a tile only the givens it binds", () => {
97
+ // `trend` binds CATEGORY alone: SINCE moving must not re-run it, and
98
+ // unbinding a tile is what takes a control's effect off it.
99
+ const q = previewTileQuery(document, document.tiles[1], runnable);
100
+ expect(q.givenNames).toEqual(["CATEGORY"]);
101
+ const bare = previewTileQuery(document, document.tiles[2], runnable);
102
+ expect(bare.expression).toBe("overview -> by_state");
103
+ expect(bare.givenNames).toEqual([]);
104
+ });
105
+
106
+ it("writes the value of a given the server does not know yet as a literal", () => {
107
+ // SINCE is declared here and not compiled on the server: it cannot be
108
+ // sent by name, so its value goes into the query, and a new filter works
109
+ // before the file is saved. Only CATEGORY travels with the request.
110
+ const q = previewTileQuery(
111
+ document,
112
+ document.tiles[0],
113
+ new Set(["CATEGORY"]),
114
+ new Map<string, GivenValue>([
115
+ ["CATEGORY", "Shoes"],
116
+ ["SINCE", new Date("2024-01-31T00:00:00Z")],
117
+ ]),
118
+ );
119
+ expect(q.expression).toBe(
120
+ "overview -> key_figures + { where: category ~ $CATEGORY, where: created_at >= @2024-01-31 }",
121
+ );
122
+ expect(q.givenNames).toEqual(["CATEGORY"]);
123
+ });
124
+
125
+ it("leaves out an unsent given with no value yet, and one nobody declares", () => {
126
+ const q = previewTileQuery(document, document.tiles[0], new Set());
127
+ expect(q.expression).toBe("overview -> key_figures");
128
+ expect(q.givenNames).toEqual([]);
129
+ const stray: DashboardTile = tile("t", "v", [
130
+ { field: "x", given: "NOBODY" },
131
+ ]);
132
+ expect(
133
+ previewTileQuery(document, stray, new Set(), new Map([["NOBODY", 1]]))
134
+ .expression,
135
+ ).toBe("overview -> v");
136
+ });
137
+
138
+ it("runs an inherited tile as the model has it, sending the whole row", () => {
139
+ const inherited: DashboardTile = {
140
+ name: "by_brand",
141
+ source: "orders",
142
+ declaration: { kind: "inherited" },
143
+ };
144
+ expect(previewTileQuery(document, inherited, runnable)).toEqual({
145
+ expression: "orders -> by_brand",
146
+ givenNames: undefined,
147
+ });
148
+ });
149
+ });
@@ -0,0 +1,172 @@
1
+ // Copyright (c) Credible Data Inc.
2
+ // SPDX-License-Identifier: MIT
3
+
4
+ import type { Given } from "../../client";
5
+ import type { GivenValue } from "../../hooks/givenValue";
6
+ import { malloyLiteral } from "../../utils/malloyLiteral";
7
+ import type { DashboardDocument, DashboardTile, LocalGiven } from "./document";
8
+
9
+ /**
10
+ * What a reader would see if the DOCUMENT were the file: the controls, and
11
+ * each tile's query — so the builder's live view follows an edit the moment it
12
+ * is made, rather than the file on the server's disk. Run from the file, an
13
+ * unbound tile keeps filtering and a removed control stays in the row until a
14
+ * save lands, so the edit looks like it did nothing.
15
+ *
16
+ * Two functions, one per half of what a reader sees. Both are pure, so the
17
+ * host can hold the live document and derive its preview from it. A given the
18
+ * document declares but the server's model has not compiled cannot be SENT to
19
+ * it — the server refuses a given it does not know — so a new control's value
20
+ * is written into the query as a literal instead, and the new filter works the
21
+ * moment it is added rather than after a save.
22
+ */
23
+
24
+ /**
25
+ * The controls this document shows: every given some tile binds, this file's
26
+ * own declarations first in declaration order, then the model's.
27
+ *
28
+ * That is the reader's rule — only a given some tile reads becomes a control
29
+ * — applied to the document instead of the manifest. A local declaration is
30
+ * built into a `Given` from its control contract; a model given is the
31
+ * manifest's own spec, which carries what the file cannot say (`givenNames` a
32
+ * suggest is gated by, for one).
33
+ */
34
+ export function previewGivens(
35
+ document: DashboardDocument,
36
+ modelSpecs: readonly Given[],
37
+ ): Given[] {
38
+ const bound = new Set<string>();
39
+ for (const tile of document.tiles)
40
+ for (const filter of tile.filters ?? []) bound.add(filter.given);
41
+
42
+ const out: Given[] = [];
43
+ const seen = new Set<string>();
44
+ for (const local of document.localGivens ?? []) {
45
+ if (!bound.has(local.name)) continue;
46
+ seen.add(local.name);
47
+ out.push(givenFromLocal(local));
48
+ }
49
+ for (const spec of modelSpecs) {
50
+ if (
51
+ spec.name === undefined ||
52
+ seen.has(spec.name) ||
53
+ !bound.has(spec.name)
54
+ )
55
+ continue;
56
+ seen.add(spec.name);
57
+ out.push(spec);
58
+ }
59
+ return out;
60
+ }
61
+
62
+ /** A `given:` this file declares, as the `Given` the control row renders. */
63
+ function givenFromLocal(local: LocalGiven): Given {
64
+ return {
65
+ name: local.name,
66
+ type: local.type,
67
+ default: local.default,
68
+ ...(local.label === undefined ? {} : { label: local.label }),
69
+ ...(local.description === undefined
70
+ ? {}
71
+ : { description: local.description }),
72
+ ...(local.control === undefined
73
+ ? {}
74
+ : { control: local.control as Given["control"] }),
75
+ ...(local.suggest
76
+ ? {
77
+ suggest: {
78
+ ...(local.suggest.source === undefined
79
+ ? {}
80
+ : { source: local.suggest.source }),
81
+ ...(local.suggest.query === undefined
82
+ ? {}
83
+ : { query: local.suggest.query }),
84
+ dimension: local.suggest.dimension,
85
+ },
86
+ }
87
+ : {}),
88
+ ...(local.rangeMin === undefined ? {} : { rangeMin: local.rangeMin }),
89
+ ...(local.rangeMax === undefined ? {} : { rangeMax: local.rangeMax }),
90
+ };
91
+ }
92
+
93
+ /** A tile's query as the document has it, and the givens it sends. */
94
+ export interface PreviewTileQuery {
95
+ /** A run expression, without `run:` — what `DashboardTile.tile` takes. */
96
+ expression: string;
97
+ /**
98
+ * The givens this tile binds and the server can take, for narrowing the
99
+ * request. Undefined for a tile whose bindings live in the model, where the
100
+ * document cannot know them: send the whole row, as the reader does.
101
+ */
102
+ givenNames: string[] | undefined;
103
+ }
104
+
105
+ /**
106
+ * A tile's query with the DOCUMENT's bindings, run on the dashboard's own
107
+ * extension.
108
+ *
109
+ * `overview -> revenue_trend` would run the view AS SAVED, bindings and all.
110
+ * `overview -> sales_by_month + { where: category ~ $CATEGORY }` is the base
111
+ * view the tile names, on the same extension, refined by what the document
112
+ * binds now — which is exactly the declaration the writer would produce, run
113
+ * before it is written. Every reference tile has such a base view, and the
114
+ * extension inherits it: `view: x is base_view + …` can only name a view of the
115
+ * source the extension extends.
116
+ *
117
+ * `runnable` is the set of givens the server's model declares; a binding to
118
+ * one of them is written as `$NAME` and the given is sent with the request. A
119
+ * binding to a given outside it — one this document just declared, which the
120
+ * server would refuse by name — is written with its VALUE as a literal,
121
+ * `where: brand ~ f'Nike'`, from `values` and the declaration's type; with no
122
+ * value yet it is left out, which is what an empty filter means. A binding to
123
+ * a given neither side knows is left out too.
124
+ */
125
+ export function previewTileQuery(
126
+ document: DashboardDocument,
127
+ tile: DashboardTile,
128
+ runnable: ReadonlySet<string>,
129
+ values: ReadonlyMap<string, GivenValue> = new Map(),
130
+ ): PreviewTileQuery {
131
+ if (tile.declaration.kind !== "reference") {
132
+ // Inherited: the model's view, bindings in the model. Inline: this file's
133
+ // query body, which the document does not model and cannot rebind.
134
+ return {
135
+ expression: `${tile.source} -> ${tile.name}`,
136
+ givenNames: tile.declaration.kind === "inherited" ? undefined : [],
137
+ };
138
+ }
139
+ // Run on the dashboard's OWN extension, not the model source it extends.
140
+ // An extension inherits every view of its base, so `overview -> sales_by_month`
141
+ // resolves; and it carries whatever else the extension declares — a
142
+ // source-level `where:`, a `# drill` dimension — which the base does not.
143
+ // Running on the base showed unscoped numbers for a dashboard that scopes
144
+ // its source, and the saved page then differed from what the author watched.
145
+ const on = tile.source;
146
+ const localTypes = new Map(
147
+ (document.localGivens ?? []).map((local) => [local.name, local.type]),
148
+ );
149
+ const sent: string[] = [];
150
+ const clauses: string[] = [];
151
+ for (const filter of tile.filters ?? []) {
152
+ const comparison = `where: ${filter.field} ${filter.op ?? "~"}`;
153
+ if (runnable.has(filter.given)) {
154
+ sent.push(filter.given);
155
+ clauses.push(`${comparison} $${filter.given}`);
156
+ continue;
157
+ }
158
+ if (!localTypes.has(filter.given)) continue;
159
+ const literal = malloyLiteral(
160
+ values.get(filter.given),
161
+ localTypes.get(filter.given),
162
+ );
163
+ if (literal !== undefined) clauses.push(`${comparison} ${literal}`);
164
+ }
165
+ const refinement = clauses.join(", ");
166
+ return {
167
+ expression:
168
+ `${on} -> ${tile.declaration.from}` +
169
+ (refinement ? ` + { ${refinement} }` : ""),
170
+ givenNames: sent,
171
+ };
172
+ }