@malloy-publisher/sdk 0.2.7 → 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 (221) hide show
  1. package/README.md +180 -204
  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-xXW1HJOJ.cjs.js → ServerProvider-CH71GsoL.cjs.js} +1 -1
  7. package/dist/{ServerProvider-ksC5Su_x.es.js → ServerProvider-X2Ma0HRs.es.js} +324 -359
  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/api.d.ts +13 -1
  13. package/dist/client/index.cjs.js +1 -1
  14. package/dist/client/index.es.js +1 -1
  15. package/dist/components/ApiErrorDisplay.d.ts +1 -2
  16. package/dist/components/Dashboard/Dashboard.d.ts +23 -16
  17. package/dist/components/Dashboard/DashboardGrid.d.ts +67 -0
  18. package/dist/components/Dashboard/DashboardTile.d.ts +6 -1
  19. package/dist/components/Dashboard/ExploreDialog.d.ts +18 -0
  20. package/dist/components/Dashboard/RowsDialog.d.ts +47 -0
  21. package/dist/components/Dashboard/TileCard.d.ts +44 -0
  22. package/dist/components/Dashboard/index.d.ts +2 -0
  23. package/dist/components/Dashboard/promoteMeasureRow.d.ts +40 -0
  24. package/dist/components/Dashboard/telemetry.d.ts +43 -0
  25. package/dist/components/DashboardBuilder/AddTileDialog.d.ts +35 -0
  26. package/dist/components/DashboardBuilder/BuilderToolbar.d.ts +29 -0
  27. package/dist/components/DashboardBuilder/DashboardBuilder.d.ts +112 -0
  28. package/dist/components/DashboardBuilder/DashboardEditor.d.ts +32 -0
  29. package/dist/components/DashboardBuilder/DiffDialog.d.ts +15 -0
  30. package/dist/components/DashboardBuilder/DrillDialog.d.ts +15 -0
  31. package/dist/components/DashboardBuilder/FilterDialog.d.ts +54 -0
  32. package/dist/components/DashboardBuilder/FilterStrip.d.ts +17 -0
  33. package/dist/components/DashboardBuilder/SettingsPopover.d.ts +20 -0
  34. package/dist/components/DashboardBuilder/TileFrame.d.ts +42 -0
  35. package/dist/components/DashboardBuilder/TileMenu.d.ts +24 -0
  36. package/dist/components/DashboardBuilder/catalog.d.ts +62 -0
  37. package/dist/components/DashboardBuilder/controls.d.ts +157 -0
  38. package/dist/components/DashboardBuilder/diff.d.ts +35 -0
  39. package/dist/components/DashboardBuilder/document.d.ts +218 -0
  40. package/dist/components/DashboardBuilder/layout.d.ts +71 -0
  41. package/dist/components/DashboardBuilder/malloyText.d.ts +45 -0
  42. package/dist/components/DashboardBuilder/preview.d.ts +60 -0
  43. package/dist/components/DashboardBuilder/readDocument.d.ts +106 -0
  44. package/dist/components/DashboardBuilder/sortable.d.ts +51 -0
  45. package/dist/components/DashboardBuilder/spliceDocument.d.ts +44 -0
  46. package/dist/components/DashboardBuilder/testing/fixtures.d.ts +10 -0
  47. package/dist/components/DashboardBuilder/useBuilderShortcuts.d.ts +22 -0
  48. package/dist/components/DashboardBuilder/useDashboardEditor.d.ts +63 -0
  49. package/dist/components/DashboardBuilder/useDraft.d.ts +13 -0
  50. package/dist/components/DashboardBuilder/useFilterForm.d.ts +65 -0
  51. package/dist/components/DashboardBuilder/useTileReorder.d.ts +22 -0
  52. package/dist/components/DashboardBuilder/useTileResize.d.ts +29 -0
  53. package/dist/components/DocumentStorage/BrowserDocumentStorage.d.ts +14 -0
  54. package/dist/components/DocumentStorage/DocumentStorage.d.ts +58 -0
  55. package/dist/components/DocumentStorage/DocumentStorageProvider.d.ts +25 -0
  56. package/dist/components/DocumentStorage/index.d.ts +3 -0
  57. package/dist/components/FloatingIconButton.d.ts +16 -0
  58. package/dist/components/Model/index.d.ts +0 -1
  59. package/dist/components/Prose.d.ts +46 -0
  60. package/dist/components/RenderedResult/RenderedResult.d.ts +12 -0
  61. package/dist/components/RenderedResult/ResultContainer.d.ts +7 -1
  62. package/dist/components/RenderedResult/ResultPanel.d.ts +30 -0
  63. package/dist/components/RenderedResult/index.d.ts +2 -0
  64. package/dist/components/RenderedResult/resultSizing.d.ts +183 -0
  65. package/dist/components/drill/index.d.ts +2 -1
  66. package/dist/components/drill/resolveDrill.d.ts +22 -0
  67. package/dist/components/drill/useDrill.d.ts +11 -2
  68. package/dist/components/drill/useDrillSelf.d.ts +46 -0
  69. package/dist/components/given/filterValue.d.ts +63 -0
  70. package/dist/components/given/index.d.ts +1 -0
  71. package/dist/components/given/useGivenUrlParams.d.ts +39 -0
  72. package/dist/components/index.d.ts +3 -3
  73. package/dist/components/styles.d.ts +3 -7
  74. package/dist/core-8NVBCLZh.cjs.js +148 -0
  75. package/dist/{core-BY7vB5gN.es.js → core-B8oMW4sm.es.js} +3540 -2335
  76. package/dist/hooks/index.d.ts +3 -1
  77. package/dist/hooks/useDocumentControls.d.ts +70 -0
  78. package/dist/hooks/useQueryResult.d.ts +40 -0
  79. package/dist/hooks/useSuggestOptions.d.ts +28 -12
  80. package/dist/index.cjs.js +34 -1
  81. package/dist/index.es.js +21487 -79
  82. package/dist/sdk.css +1 -1
  83. package/dist/styles.css +0 -1
  84. package/dist/utils/malloyLiteral.d.ts +11 -0
  85. package/package.json +25 -14
  86. package/src/builder-entry.ts +55 -0
  87. package/src/components/ApiErrorDisplay.tsx +1 -1
  88. package/src/components/Connections/EditConnectionDialog.tsx +96 -86
  89. package/src/components/Dashboard/Dashboard.spec.tsx +7 -10
  90. package/src/components/Dashboard/Dashboard.tsx +184 -229
  91. package/src/components/Dashboard/DashboardGrid.tsx +124 -0
  92. package/src/components/Dashboard/DashboardTile.spec.tsx +30 -6
  93. package/src/components/Dashboard/DashboardTile.tsx +67 -101
  94. package/src/components/Dashboard/ExploreDialog.tsx +84 -0
  95. package/src/components/Dashboard/RowsDialog.spec.ts +42 -0
  96. package/src/components/Dashboard/RowsDialog.tsx +234 -0
  97. package/src/components/Dashboard/TileCard.tsx +120 -0
  98. package/src/components/Dashboard/index.ts +2 -0
  99. package/src/components/Dashboard/promoteMeasureRow.spec.ts +207 -0
  100. package/src/components/Dashboard/promoteMeasureRow.ts +160 -0
  101. package/src/components/Dashboard/telemetry.ts +44 -0
  102. package/src/components/Dashboard/tileGridColumn.spec.ts +1 -1
  103. package/src/components/DashboardBuilder/AddTileDialog.tsx +249 -0
  104. package/src/components/DashboardBuilder/BuilderToolbar.tsx +270 -0
  105. package/src/components/DashboardBuilder/DashboardBuilder.spec.tsx +858 -0
  106. package/src/components/DashboardBuilder/DashboardBuilder.tsx +653 -0
  107. package/src/components/DashboardBuilder/DashboardEditor.spec.tsx +211 -0
  108. package/src/components/DashboardBuilder/DashboardEditor.tsx +493 -0
  109. package/src/components/DashboardBuilder/DiffDialog.tsx +129 -0
  110. package/src/components/DashboardBuilder/DrillDialog.tsx +281 -0
  111. package/src/components/DashboardBuilder/FilterDialog.tsx +581 -0
  112. package/src/components/DashboardBuilder/FilterStrip.tsx +125 -0
  113. package/src/components/DashboardBuilder/SettingsPopover.tsx +168 -0
  114. package/src/components/DashboardBuilder/TileFrame.tsx +380 -0
  115. package/src/components/DashboardBuilder/TileMenu.tsx +188 -0
  116. package/src/components/DashboardBuilder/catalog.spec.ts +215 -0
  117. package/src/components/DashboardBuilder/catalog.ts +225 -0
  118. package/src/components/DashboardBuilder/controls.spec.ts +243 -0
  119. package/src/components/DashboardBuilder/controls.ts +398 -0
  120. package/src/components/DashboardBuilder/diff.spec.ts +44 -0
  121. package/src/components/DashboardBuilder/diff.ts +93 -0
  122. package/src/components/DashboardBuilder/document.ts +209 -0
  123. package/src/components/DashboardBuilder/keepRowStructure.spec.ts +84 -0
  124. package/src/components/DashboardBuilder/layout.ts +143 -0
  125. package/src/components/DashboardBuilder/malloyText.spec.ts +84 -0
  126. package/src/components/DashboardBuilder/malloyText.ts +151 -0
  127. package/src/components/DashboardBuilder/moveIntoGap.spec.ts +90 -0
  128. package/src/components/DashboardBuilder/preview.spec.ts +149 -0
  129. package/src/components/DashboardBuilder/preview.ts +172 -0
  130. package/src/components/DashboardBuilder/readDocument.spec.ts +375 -0
  131. package/src/components/DashboardBuilder/readDocument.ts +467 -0
  132. package/src/components/DashboardBuilder/sortable.tsx +151 -0
  133. package/src/components/DashboardBuilder/spliceDocument.spec.ts +1108 -0
  134. package/src/components/DashboardBuilder/spliceDocument.ts +1098 -0
  135. package/src/components/DashboardBuilder/testing/fixtures.ts +48 -0
  136. package/src/components/DashboardBuilder/useBuilderShortcuts.ts +88 -0
  137. package/src/components/DashboardBuilder/useDashboardEditor.spec.ts +255 -0
  138. package/src/components/DashboardBuilder/useDashboardEditor.ts +193 -0
  139. package/src/components/DashboardBuilder/useDraft.ts +43 -0
  140. package/src/components/DashboardBuilder/useFilterForm.spec.tsx +144 -0
  141. package/src/components/DashboardBuilder/useFilterForm.ts +352 -0
  142. package/src/components/DashboardBuilder/useTileReorder.spec.tsx +97 -0
  143. package/src/components/DashboardBuilder/useTileReorder.ts +115 -0
  144. package/src/components/DashboardBuilder/useTileResize.spec.tsx +121 -0
  145. package/src/components/DashboardBuilder/useTileResize.ts +110 -0
  146. package/src/components/DashboardBuilder/withGaps.spec.ts +96 -0
  147. package/src/components/DocumentStorage/BrowserDocumentStorage.spec.ts +81 -0
  148. package/src/components/DocumentStorage/BrowserDocumentStorage.ts +105 -0
  149. package/src/components/DocumentStorage/DocumentStorage.ts +73 -0
  150. package/src/components/DocumentStorage/DocumentStorageProvider.tsx +58 -0
  151. package/src/components/DocumentStorage/index.ts +16 -0
  152. package/src/components/Environment/About.tsx +4 -36
  153. package/src/components/FloatingIconButton.tsx +41 -0
  154. package/src/components/Model/Model.tsx +6 -23
  155. package/src/components/Model/ModelCell.tsx +34 -72
  156. package/src/components/Model/index.ts +0 -1
  157. package/src/components/Notebook/Notebook.tsx +27 -156
  158. package/src/components/Notebook/NotebookCell.tsx +37 -191
  159. package/src/components/Prose.spec.tsx +85 -0
  160. package/src/components/Prose.tsx +179 -0
  161. package/src/components/QueryResult/QueryResult.tsx +15 -43
  162. package/src/components/RenderedResult/RenderedResult.tsx +86 -76
  163. package/src/components/RenderedResult/ResultContainer.tsx +25 -36
  164. package/src/components/RenderedResult/ResultPanel.spec.tsx +49 -0
  165. package/src/components/RenderedResult/ResultPanel.tsx +73 -0
  166. package/src/components/RenderedResult/index.ts +16 -0
  167. package/src/components/RenderedResult/resultSizing.spec.ts +249 -0
  168. package/src/components/RenderedResult/resultSizing.ts +308 -0
  169. package/src/components/ResultsDialog.tsx +2 -1
  170. package/src/components/drill/index.ts +6 -0
  171. package/src/components/drill/resolveDrill.ts +22 -1
  172. package/src/components/drill/useDrill.spec.tsx +94 -0
  173. package/src/components/drill/useDrill.tsx +52 -12
  174. package/src/components/drill/useDrillSelf.spec.tsx +64 -0
  175. package/src/components/drill/useDrillSelf.ts +110 -0
  176. package/src/components/given/GivenInput.spec.tsx +196 -2
  177. package/src/components/given/GivenInput.tsx +300 -25
  178. package/src/components/given/GivensPanel.tsx +1 -1
  179. package/src/components/given/filterValue.spec.ts +112 -0
  180. package/src/components/given/filterValue.ts +188 -0
  181. package/src/components/given/index.ts +4 -0
  182. package/src/components/given/useGivenUrlParams.spec.tsx +74 -0
  183. package/src/components/given/useGivenUrlParams.ts +87 -0
  184. package/src/components/index.ts +11 -3
  185. package/src/components/styles.ts +0 -37
  186. package/src/hooks/index.ts +13 -1
  187. package/src/hooks/useDocumentControls.ts +170 -0
  188. package/src/hooks/useGivensState.spec.ts +158 -0
  189. package/src/hooks/useGivensState.ts +114 -23
  190. package/src/hooks/useQueryResult.ts +82 -0
  191. package/src/hooks/useSuggestOptions.dom.spec.ts +60 -1
  192. package/src/hooks/useSuggestOptions.ts +94 -51
  193. package/src/utils/malloyLiteral.spec.ts +43 -0
  194. package/src/utils/malloyLiteral.ts +76 -0
  195. package/vite.config.ts +5 -1
  196. package/dist/components/AnalyzePackageButton.d.ts +0 -6
  197. package/dist/components/Workbook/BrowserWorkbookStorage.d.ts +0 -9
  198. package/dist/components/Workbook/EditableMalloyCell.d.ts +0 -11
  199. package/dist/components/Workbook/ModelPicker.d.ts +0 -11
  200. package/dist/components/Workbook/MutableCell.d.ts +0 -17
  201. package/dist/components/Workbook/Workbook.d.ts +0 -7
  202. package/dist/components/Workbook/WorkbookList.d.ts +0 -7
  203. package/dist/components/Workbook/WorkbookManager.d.ts +0 -84
  204. package/dist/components/Workbook/WorkbookStorage.d.ts +0 -17
  205. package/dist/components/Workbook/WorkbookStorageProvider.d.ts +0 -12
  206. package/dist/components/Workbook/index.d.ts +0 -7
  207. package/dist/core-CWKmWEg2.cjs.js +0 -148
  208. package/dist/index-B0WyZAUA.es.js +0 -66412
  209. package/dist/index-kxVD1RjY.cjs.js +0 -356
  210. package/dist/markdown-editor.css +0 -341
  211. package/src/components/AnalyzePackageButton.tsx +0 -319
  212. package/src/components/Workbook/BrowserWorkbookStorage.ts +0 -64
  213. package/src/components/Workbook/EditableMalloyCell.tsx +0 -49
  214. package/src/components/Workbook/ModelPicker.tsx +0 -134
  215. package/src/components/Workbook/MutableCell.tsx +0 -458
  216. package/src/components/Workbook/Workbook.tsx +0 -501
  217. package/src/components/Workbook/WorkbookList.tsx +0 -110
  218. package/src/components/Workbook/WorkbookManager.ts +0 -214
  219. package/src/components/Workbook/WorkbookStorage.ts +0 -35
  220. package/src/components/Workbook/WorkbookStorageProvider.tsx +0 -40
  221. package/src/components/Workbook/index.ts +0 -10
@@ -0,0 +1,243 @@
1
+ // Copyright (c) Credible Data Inc.
2
+ // SPDX-License-Identifier: MIT
3
+
4
+ import { describe, expect, it } from "bun:test";
5
+ import {
6
+ acceptsField,
7
+ kindForFieldType,
8
+ typeLabel,
9
+ applyMapping,
10
+ controlsOf,
11
+ declareControl,
12
+ defaultOperator,
13
+ givenNameFor,
14
+ mappingOf,
15
+ newLocalGiven,
16
+ removeControl,
17
+ } from "./controls";
18
+ import type { DashboardDocument } from "./document";
19
+
20
+ const doc = (): DashboardDocument => ({
21
+ title: "T",
22
+ imports: [{ kind: "names", names: ["order_items"], from: "../m.malloy" }],
23
+ sources: [{ name: "a", 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
+ ],
34
+ tiles: [
35
+ {
36
+ name: "by_cat",
37
+ source: "a",
38
+ declaration: { kind: "reference", from: "by_category" },
39
+ filters: [{ field: "category", given: "CATEGORY" }],
40
+ },
41
+ {
42
+ name: "by_brand",
43
+ source: "a",
44
+ declaration: { kind: "reference", from: "top_brands" },
45
+ },
46
+ { name: "kpis", source: "a", declaration: { kind: "inline" } },
47
+ ],
48
+ });
49
+
50
+ describe("controlsOf", () => {
51
+ it("lists the dashboard's own controls first, then the model's", () => {
52
+ const out = controlsOf(doc(), [
53
+ { name: "SINCE", type: "date", label: "Since" },
54
+ // Same name as a local one: the local declaration is the one that
55
+ // binds, so the model's copy is not a second control.
56
+ { name: "CATEGORY", type: "filter<string>" },
57
+ ]);
58
+ expect(out.map((c) => [c.name, c.origin, c.boundTiles])).toEqual([
59
+ ["CATEGORY", "dashboard", 1],
60
+ ["SINCE", "model", 0],
61
+ ]);
62
+ expect(out[0].field).toBe("category");
63
+ });
64
+
65
+ // A dashboard over a bare `import '../givens.malloy'` binds names nobody
66
+ // handed the builder. They are still controls, and can still be unbound.
67
+ it("shows a binding to a given nobody declared", () => {
68
+ const d = doc();
69
+ delete d.localGivens;
70
+ expect(controlsOf(d).map((c) => [c.name, c.origin])).toEqual([
71
+ ["CATEGORY", "model"],
72
+ ]);
73
+ });
74
+ });
75
+
76
+ describe("defaultOperator", () => {
77
+ it("leaves a filter implicit and compares a value", () => {
78
+ expect(defaultOperator("filter<string>")).toBeUndefined();
79
+ expect(defaultOperator("filter<number>")).toBeUndefined();
80
+ expect(defaultOperator("date")).toBe(">=");
81
+ expect(defaultOperator("number")).toBe(">=");
82
+ expect(defaultOperator("string")).toBe("=");
83
+ expect(defaultOperator(undefined)).toBeUndefined();
84
+ });
85
+ });
86
+
87
+ describe("givenNameFor", () => {
88
+ it("names a given from a field and keeps it distinct", () => {
89
+ expect(givenNameFor("products.category", [])).toBe("CATEGORY");
90
+ expect(givenNameFor("created_at", [])).toBe("CREATED_AT");
91
+ expect(givenNameFor("category", ["CATEGORY"])).toBe("CATEGORY_2");
92
+ expect(givenNameFor("2nd-tier", [])).toBe("F_2ND_TIER");
93
+ });
94
+ });
95
+
96
+ describe("newLocalGiven", () => {
97
+ it("declares a picker that suggests over the field's own source", () => {
98
+ expect(
99
+ newLocalGiven({
100
+ name: "REGION",
101
+ label: "Region",
102
+ kind: "select",
103
+ field: "regions.region",
104
+ source: "order_items",
105
+ }),
106
+ ).toEqual({
107
+ name: "REGION",
108
+ type: "filter<string>",
109
+ default: "f''",
110
+ label: "Region",
111
+ control: "select",
112
+ suggest: { source: "order_items", dimension: "region" },
113
+ });
114
+ });
115
+
116
+ it("declares a date with the default it was given", () => {
117
+ expect(
118
+ newLocalGiven({
119
+ name: "SINCE",
120
+ label: "",
121
+ kind: "date",
122
+ field: "created_at",
123
+ dateDefault: "2023-01-01",
124
+ }),
125
+ ).toEqual({
126
+ name: "SINCE",
127
+ type: "date",
128
+ default: "@2023-01-01",
129
+ label: "SINCE",
130
+ });
131
+ });
132
+ });
133
+
134
+ describe("mappings", () => {
135
+ it("opens on what is true, with the comparison the type implies", () => {
136
+ const rows = mappingOf(doc(), { name: "CATEGORY", field: "category" });
137
+ expect(rows.map((r) => r.include)).toEqual([true, false, false]);
138
+ const since = mappingOf(doc(), {
139
+ name: "SINCE",
140
+ field: "created_at",
141
+ type: "date",
142
+ });
143
+ expect(since[1]).toEqual({
144
+ include: false,
145
+ field: "created_at",
146
+ op: ">=",
147
+ });
148
+ });
149
+
150
+ it("applies a mapping as a diff and skips tiles that cannot bind", () => {
151
+ const d = doc();
152
+ applyMapping(d, "SINCE", [
153
+ { include: true, field: "created_at", op: ">=" },
154
+ { include: true, field: "created_at", op: ">=" },
155
+ // Inline: cannot take a refinement, so ticking it does nothing.
156
+ { include: true, field: "created_at", op: ">=" },
157
+ ]);
158
+ expect(d.tiles[0].filters).toEqual([
159
+ { field: "category", given: "CATEGORY" },
160
+ { field: "created_at", given: "SINCE", op: ">=" },
161
+ ]);
162
+ expect(d.tiles[1].filters).toEqual([
163
+ { field: "created_at", given: "SINCE", op: ">=" },
164
+ ]);
165
+ expect(d.tiles[2].filters).toBeUndefined();
166
+
167
+ // Unticking removes, and a `~` is left implicit.
168
+ applyMapping(d, "SINCE", [
169
+ { include: false, field: "created_at" },
170
+ { include: true, field: "created_at", op: "~" },
171
+ { include: false, field: "created_at" },
172
+ ]);
173
+ expect(d.tiles[0].filters).toEqual([
174
+ { field: "category", given: "CATEGORY" },
175
+ ]);
176
+ expect(d.tiles[1].filters).toEqual([
177
+ { field: "created_at", given: "SINCE" },
178
+ ]);
179
+ });
180
+ });
181
+
182
+ describe("declareControl and removeControl", () => {
183
+ it("declares in place, and removes the declaration with every binding", () => {
184
+ const d = doc();
185
+ declareControl(d, {
186
+ name: "CATEGORY",
187
+ type: "filter<string>",
188
+ default: "f''",
189
+ label: "Cat",
190
+ });
191
+ expect(d.localGivens?.map((g) => g.label)).toEqual(["Cat"]);
192
+ declareControl(d, {
193
+ name: "SINCE",
194
+ type: "date",
195
+ default: "@2023-01-01",
196
+ });
197
+ expect(d.localGivens?.map((g) => g.name)).toEqual(["CATEGORY", "SINCE"]);
198
+
199
+ removeControl(d, "CATEGORY");
200
+ expect(d.tiles[0].filters).toBeUndefined();
201
+ expect(d.localGivens?.map((g) => g.name)).toEqual(["SINCE"]);
202
+ removeControl(d, "SINCE");
203
+ expect(d.localGivens).toBeUndefined();
204
+ });
205
+ });
206
+
207
+ describe("acceptsField", () => {
208
+ it("matches the given's scalar to the field's type, filter or value alike", () => {
209
+ expect(acceptsField("filter<string>", "string_type")).toBe(true);
210
+ expect(acceptsField("string", "string_type")).toBe(true);
211
+ expect(acceptsField("filter<string>", "number_type")).toBe(false);
212
+ expect(acceptsField("filter<number>", "number_type")).toBe(true);
213
+ expect(acceptsField("number", "string_type")).toBe(false);
214
+ });
215
+
216
+ it("lets dates and timestamps compare with each other, and nothing else", () => {
217
+ expect(acceptsField("date", "timestamp_type")).toBe(true);
218
+ expect(acceptsField("filter<timestamp>", "date_type")).toBe(true);
219
+ expect(acceptsField("date", "string_type")).toBe(false);
220
+ expect(acceptsField("filter<string>", "date_type")).toBe(false);
221
+ });
222
+
223
+ it("accepts what it cannot judge", () => {
224
+ // A catalog with no type, or a given of a type this does not know.
225
+ expect(acceptsField("filter<string>", undefined)).toBe(true);
226
+ expect(acceptsField(undefined, "number_type")).toBe(true);
227
+ });
228
+ });
229
+
230
+ describe("kindForFieldType and typeLabel", () => {
231
+ it("gives a field the control its type wants", () => {
232
+ expect(kindForFieldType("number_type")).toBe("number");
233
+ expect(kindForFieldType("date_type")).toBe("date");
234
+ expect(kindForFieldType("timestamp_type")).toBe("date");
235
+ expect(kindForFieldType("string_type")).toBe("select");
236
+ expect(kindForFieldType(undefined)).toBe("select");
237
+ });
238
+
239
+ it("says a type the way a message would", () => {
240
+ expect(typeLabel("number_type")).toBe("a number");
241
+ expect(typeLabel("string_type")).toBe("text");
242
+ });
243
+ });
@@ -0,0 +1,398 @@
1
+ // Copyright (c) Credible Data Inc.
2
+ // SPDX-License-Identifier: MIT
3
+
4
+ import type { DashboardDocument, DashboardTile, LocalGiven } from "./document";
5
+
6
+ /**
7
+ * The builder's view of the dashboard's filter controls, and the pure edits it
8
+ * makes to them. Kept out of the component so every rule here has a test that
9
+ * needs no DOM.
10
+ *
11
+ * A control is a GIVEN some tile binds. It comes from one of two places, and
12
+ * the difference decides what the builder may do with it:
13
+ *
14
+ * - `dashboard` — declared in this file ({@link LocalGiven}). The builder owns
15
+ * it outright: add, retag, remove, and bind on any tile.
16
+ * - `model` — declared in the model and reaching this file through an import.
17
+ * The builder may bind it on tiles, because a binding is a refinement in this
18
+ * file, but it cannot change or remove the declaration, because the builder
19
+ * never edits imports or model files.
20
+ *
21
+ * Declaring in the dashboard is the convention; see {@link LocalGiven}.
22
+ */
23
+
24
+ export type ControlOrigin = "dashboard" | "model";
25
+
26
+ /** A given the builder can bind a tile to, from either origin. */
27
+ export interface BuilderGiven {
28
+ /** The given's name, as written after `$` in a `where:`. */
29
+ name: string;
30
+ label?: string;
31
+ /** The declared type, which decides how a binding compares; see {@link defaultOperator}. */
32
+ type?: string;
33
+ /**
34
+ * The field to compare against, used as the default when this given is
35
+ * bound to a tile. The dimension its control suggests over is the right
36
+ * guess — a `CATEGORY` control that suggests over `category` is almost
37
+ * always filtering `category` — and it is only a default: the binding is
38
+ * editable afterwards, because the tile's source may spell it differently.
39
+ */
40
+ field?: string;
41
+ }
42
+
43
+ export interface BuilderControl extends BuilderGiven {
44
+ origin: ControlOrigin;
45
+ /** The declaration, for a control this dashboard owns. */
46
+ local?: LocalGiven;
47
+ /** How many tiles bind it. Zero means declared but not yet a control. */
48
+ boundTiles: number;
49
+ }
50
+
51
+ /**
52
+ * Every control the builder can offer: the dashboard's own first, in file
53
+ * order, then the model's that the caller knows about. A model given that
54
+ * shares a name with a local one is the same control as far as any `where:` is
55
+ * concerned, and the local declaration is the one that binds — so it is not
56
+ * listed twice.
57
+ */
58
+ export function controlsOf(
59
+ document: DashboardDocument,
60
+ modelGivens: readonly BuilderGiven[] = [],
61
+ ): BuilderControl[] {
62
+ const bound = new Map<string, number>();
63
+ for (const tile of document.tiles)
64
+ for (const filter of tile.filters ?? [])
65
+ bound.set(filter.given, (bound.get(filter.given) ?? 0) + 1);
66
+
67
+ const out: BuilderControl[] = [];
68
+ const seen = new Set<string>();
69
+ for (const local of document.localGivens ?? []) {
70
+ seen.add(local.name);
71
+ out.push({
72
+ name: local.name,
73
+ ...(local.label === undefined ? {} : { label: local.label }),
74
+ type: local.type,
75
+ ...(local.suggest ? { field: local.suggest.dimension } : {}),
76
+ origin: "dashboard",
77
+ local,
78
+ boundTiles: bound.get(local.name) ?? 0,
79
+ });
80
+ }
81
+ for (const given of modelGivens) {
82
+ if (seen.has(given.name)) continue;
83
+ seen.add(given.name);
84
+ out.push({
85
+ ...given,
86
+ origin: "model",
87
+ boundTiles: bound.get(given.name) ?? 0,
88
+ });
89
+ }
90
+ // A binding to a given nobody declared is still a control the file has —
91
+ // it is how a dashboard over a bare `import '../givens.malloy'` looks when
92
+ // the caller passed no model givens. Shown so it can at least be unbound.
93
+ for (const [name, count] of bound) {
94
+ if (seen.has(name)) continue;
95
+ out.push({ name, origin: "model", boundTiles: count });
96
+ }
97
+ return out;
98
+ }
99
+
100
+ /**
101
+ * How a binding to a given of this type compares.
102
+ *
103
+ * A `filter<…>` given is a filter EXPRESSION and binds with `~`, which is the
104
+ * common case and is left implicit on the binding. A plain-typed given is a
105
+ * VALUE: a `date` is "since", a `number` is "at least", a `string` is "equals".
106
+ * Measured: `created_at ~ $SINCE` does not compile against a `date` given.
107
+ */
108
+ export function defaultOperator(type: string | undefined): string | undefined {
109
+ if (type === undefined || type.startsWith("filter<")) return undefined;
110
+ if (type === "string" || type === "boolean") return "=";
111
+ return ">=";
112
+ }
113
+
114
+ /**
115
+ * The scalar a given compares: `filter<string>` and `string` both compare
116
+ * strings, one as a filter expression and one as a value.
117
+ */
118
+ function givenScalar(type: string | undefined): string | undefined {
119
+ if (!type) return undefined;
120
+ return /^filter<(.+)>$/.exec(type)?.[1] ?? type;
121
+ }
122
+
123
+ /**
124
+ * Whether a given of `givenType` can compare a field of `fieldType` (the
125
+ * catalog's spelling: `string_type`, `number_type`, `date_type`, …).
126
+ *
127
+ * A `filter<string>` over a number field compiles nowhere and a `date` over a
128
+ * string field compares nothing, so the picker offers only the fields a control
129
+ * can take, and a binding to one it cannot is marked. Dates and timestamps
130
+ * compare with each other. Unknown on EITHER side is accepted: the catalog may
131
+ * carry no type, and a given of a type this does not know is not refused on
132
+ * that account.
133
+ */
134
+ export function acceptsField(
135
+ givenType: string | undefined,
136
+ fieldType: string | undefined,
137
+ ): boolean {
138
+ const scalar = givenScalar(givenType);
139
+ const field = fieldType?.replace(/_type$/, "");
140
+ if (!scalar || !field) return true;
141
+ const dateLike = new Set(["date", "timestamp"]);
142
+ if (dateLike.has(scalar)) return dateLike.has(field);
143
+ return scalar === field;
144
+ }
145
+
146
+ /** `number_type` -> "a number", as a message would say it. */
147
+ export function typeLabel(type: string | undefined): string {
148
+ switch (type?.replace(/_type$/, "")) {
149
+ case "string":
150
+ return "text";
151
+ case "number":
152
+ return "a number";
153
+ case "date":
154
+ return "a date";
155
+ case "timestamp":
156
+ return "a timestamp";
157
+ case "boolean":
158
+ return "true or false";
159
+ default:
160
+ return type ?? "an unknown type";
161
+ }
162
+ }
163
+
164
+ /**
165
+ * The control a field of this type naturally gets: a number range for a
166
+ * number, a date picker for a date, a pick-list for anything else. What the
167
+ * window switches a new control to when the field picked does not fit the kind
168
+ * it started with.
169
+ */
170
+ export function kindForFieldType(fieldType: string | undefined): ControlKind {
171
+ switch (fieldType?.replace(/_type$/, "")) {
172
+ case "number":
173
+ return "number";
174
+ case "date":
175
+ case "timestamp":
176
+ return "date";
177
+ default:
178
+ return "select";
179
+ }
180
+ }
181
+
182
+ /** The comparisons a binding can use, with how a reader would say them. */
183
+ export const OPERATORS: ReadonlyArray<{ op: string; label: string }> = [
184
+ { op: "~", label: "matches" },
185
+ { op: "=", label: "equals" },
186
+ { op: ">=", label: "at least" },
187
+ { op: "<=", label: "at most" },
188
+ { op: ">", label: "more than" },
189
+ { op: "<", label: "less than" },
190
+ ];
191
+
192
+ /**
193
+ * A given name from a field: `products.category` -> `CATEGORY`, and kept
194
+ * distinct from any name already taken.
195
+ */
196
+ export function givenNameFor(field: string, taken: Iterable<string>): string {
197
+ const words = (field.split(".").at(-1) ?? "")
198
+ .split(/[^A-Za-z0-9]+/)
199
+ .filter(Boolean);
200
+ const base = words.join("_").toUpperCase() || "FILTER";
201
+ const stem = /^[A-Z_]/.test(base) ? base : `F_${base}`;
202
+ const used = new Set(taken);
203
+ if (!used.has(stem)) return stem;
204
+ for (let n = 2; ; n++) if (!used.has(`${stem}_${n}`)) return `${stem}_${n}`;
205
+ }
206
+
207
+ /** What kind of control a new filter is, in a reader's terms. */
208
+ export type ControlKind = "select" | "multiselect" | "text" | "number" | "date";
209
+
210
+ export const CONTROL_KINDS: ReadonlyArray<{
211
+ kind: ControlKind;
212
+ label: string;
213
+ hint: string;
214
+ }> = [
215
+ {
216
+ kind: "select",
217
+ label: "Pick one",
218
+ hint: "A dropdown of the field's values",
219
+ },
220
+ {
221
+ kind: "multiselect",
222
+ label: "Pick several",
223
+ hint: "The same, taking more than one",
224
+ },
225
+ { kind: "text", label: "Text", hint: "A box taking Malloy filter syntax" },
226
+ {
227
+ kind: "number",
228
+ label: "Number range",
229
+ hint: "A slider over the field's values",
230
+ },
231
+ {
232
+ kind: "date",
233
+ label: "Since a date",
234
+ hint: "A date picker; tiles keep rows on or after it",
235
+ },
236
+ ];
237
+
238
+ /**
239
+ * A new control's declaration, from what the dialog asked.
240
+ *
241
+ * The picker's options come from the source the field lives on — the base of
242
+ * the tile's own extension — which the file necessarily already imports, so a
243
+ * `suggest` here always resolves and the builder never has to add an import.
244
+ */
245
+ export function newLocalGiven(spec: {
246
+ name: string;
247
+ label: string;
248
+ kind: ControlKind;
249
+ field: string;
250
+ /** The source to suggest over, for `select` and `multiselect`. */
251
+ source?: string;
252
+ /** A date's default, `YYYY-MM-DD`; a number range's bounds. */
253
+ dateDefault?: string;
254
+ range?: { min: number; max: number };
255
+ }): LocalGiven {
256
+ const label = spec.label.trim() || spec.name;
257
+ const dimension = spec.field.split(".").at(-1) ?? spec.field;
258
+ switch (spec.kind) {
259
+ case "select":
260
+ case "multiselect":
261
+ return {
262
+ name: spec.name,
263
+ type: "filter<string>",
264
+ default: "f''",
265
+ label,
266
+ control: spec.kind,
267
+ ...(spec.source
268
+ ? { suggest: { source: spec.source, dimension } }
269
+ : {}),
270
+ };
271
+ case "text":
272
+ return {
273
+ name: spec.name,
274
+ type: "filter<string>",
275
+ default: "f''",
276
+ label,
277
+ };
278
+ case "number":
279
+ return {
280
+ name: spec.name,
281
+ type: "filter<number>",
282
+ default: "f''",
283
+ label,
284
+ ...(spec.range
285
+ ? { rangeMin: spec.range.min, rangeMax: spec.range.max }
286
+ : {}),
287
+ };
288
+ case "date":
289
+ return {
290
+ name: spec.name,
291
+ type: "date",
292
+ default: `@${spec.dateDefault ?? new Date().toISOString().slice(0, 10)}`,
293
+ label,
294
+ };
295
+ }
296
+ }
297
+
298
+ /** One tile's row in a control's mapping: whether it binds, and how. */
299
+ export interface MappingRow {
300
+ include: boolean;
301
+ field: string;
302
+ /** Absent means `~`; see {@link defaultOperator}. */
303
+ op?: string;
304
+ }
305
+
306
+ /**
307
+ * Which tiles can take a binding, and why the others cannot.
308
+ *
309
+ * A binding is a `+ { where: … }` refinement on the tile's declaration, so the
310
+ * tile has to BE a declaration this file owns that the reader will read back.
311
+ * That is the `reference` form only: an `inherited` tile is declared on the
312
+ * model's source, and an `inline` tile's body is a query, not a reference, so a
313
+ * refinement written onto it would not come back and the round-trip gate would
314
+ * refuse the whole save. Better to refuse the tick.
315
+ */
316
+ export const canBind = (tile: DashboardTile) =>
317
+ tile.declaration.kind === "reference";
318
+
319
+ /** The mapping a control has NOW, one row per tile, for the dialog to open on. */
320
+ export function mappingOf(
321
+ document: DashboardDocument,
322
+ control: { name: string; field?: string; type?: string },
323
+ ): MappingRow[] {
324
+ return document.tiles.map((tile) => {
325
+ const bound = (tile.filters ?? []).find((f) => f.given === control.name);
326
+ return {
327
+ // Ticked where the tile ALREADY carries this control, so the window
328
+ // opens on what is true rather than on what would be added. That is
329
+ // what lets one window add, change and remove: untick a row to unbind
330
+ // it, untick them all and the control leaves every tile.
331
+ include: bound !== undefined,
332
+ field: bound?.field ?? control.field ?? control.name.toLowerCase(),
333
+ ...(bound?.op !== undefined
334
+ ? { op: bound.op }
335
+ : defaultOperator(control.type) !== undefined
336
+ ? { op: defaultOperator(control.type) as string }
337
+ : {}),
338
+ };
339
+ });
340
+ }
341
+
342
+ /**
343
+ * Apply a mapping: a DIFF against what each tile carries now — added where
344
+ * newly ticked, dropped where unticked, rewritten where only the field or the
345
+ * comparison changed. Mutates the draft; the caller makes it one history entry.
346
+ */
347
+ export function applyMapping(
348
+ draft: DashboardDocument,
349
+ given: string,
350
+ rows: readonly MappingRow[],
351
+ ): void {
352
+ rows.forEach((row, index) => {
353
+ const tile = draft.tiles[index];
354
+ if (!tile || !canBind(tile)) return;
355
+ const rest = (tile.filters ?? []).filter((f) => f.given !== given);
356
+ const next = row.include
357
+ ? [
358
+ ...rest,
359
+ {
360
+ field: row.field.trim() || given.toLowerCase(),
361
+ given,
362
+ ...(row.op && row.op !== "~" ? { op: row.op } : {}),
363
+ },
364
+ ]
365
+ : rest;
366
+ if (next.length > 0) tile.filters = next;
367
+ else delete tile.filters;
368
+ });
369
+ }
370
+
371
+ /** Declare a control in this dashboard, or replace its declaration by name. */
372
+ export function declareControl(
373
+ draft: DashboardDocument,
374
+ given: LocalGiven,
375
+ ): void {
376
+ const rest = (draft.localGivens ?? []).filter((g) => g.name !== given.name);
377
+ const at = (draft.localGivens ?? []).findIndex((g) => g.name === given.name);
378
+ const next = [...rest];
379
+ next.splice(at >= 0 ? at : next.length, 0, given);
380
+ draft.localGivens = next;
381
+ }
382
+
383
+ /**
384
+ * Take a control off the dashboard: every binding to it, and — when this file
385
+ * declares it — the declaration too. A model given keeps its declaration, which
386
+ * is not ours; it simply stops being a control here, because a control is a
387
+ * given some tile binds.
388
+ */
389
+ export function removeControl(draft: DashboardDocument, name: string): void {
390
+ for (const tile of draft.tiles) {
391
+ const kept = (tile.filters ?? []).filter((f) => f.given !== name);
392
+ if (kept.length > 0) tile.filters = kept;
393
+ else delete tile.filters;
394
+ }
395
+ const locals = (draft.localGivens ?? []).filter((g) => g.name !== name);
396
+ if (locals.length > 0) draft.localGivens = locals;
397
+ else delete draft.localGivens;
398
+ }
@@ -0,0 +1,44 @@
1
+ // Copyright (c) Credible Data Inc.
2
+ // SPDX-License-Identifier: MIT
3
+
4
+ import { describe, expect, it } from "bun:test";
5
+ import { foldUnchanged, lineDiff } from "./diff";
6
+
7
+ describe("lineDiff", () => {
8
+ it("reports an inserted and a removed line, and nothing else", () => {
9
+ const before = "a\nb\nc\nd";
10
+ const after = "a\nc\nd\ne";
11
+ expect(lineDiff(before, after)).toEqual([
12
+ { kind: "same", text: "a" },
13
+ { kind: "del", text: "b" },
14
+ { kind: "same", text: "c" },
15
+ { kind: "same", text: "d" },
16
+ { kind: "add", text: "e" },
17
+ ]);
18
+ });
19
+
20
+ it("is empty-handed when nothing changed", () => {
21
+ expect(lineDiff("x\ny", "x\ny").every((l) => l.kind === "same")).toBe(
22
+ true,
23
+ );
24
+ });
25
+ });
26
+
27
+ describe("foldUnchanged", () => {
28
+ it("keeps context around each change and folds the rest", () => {
29
+ const lines = lineDiff(
30
+ Array.from({ length: 20 }, (_, i) => `l${i}`).join("\n"),
31
+ Array.from({ length: 20 }, (_, i) =>
32
+ i === 10 ? "changed" : `l${i}`,
33
+ ).join("\n"),
34
+ );
35
+ const folded = foldUnchanged(lines, 2);
36
+ expect(folded[0]).toEqual({ kind: "fold", count: 8 });
37
+ expect(
38
+ folded
39
+ .filter((l) => l.kind !== "fold")
40
+ .map((l) => (l as { text: string }).text),
41
+ ).toEqual(["l8", "l9", "l10", "changed", "l11", "l12"]);
42
+ expect(folded.at(-1)).toEqual({ kind: "fold", count: 7 });
43
+ });
44
+ });