@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,211 @@
1
+ // Copyright (c) Credible Data Inc.
2
+ // SPDX-License-Identifier: MIT
3
+
4
+ import { fireEvent, render, screen, waitFor } from "@testing-library/react";
5
+ import { beforeEach, describe, expect, it, mock } from "bun:test";
6
+ import {
7
+ clearCache,
8
+ mockServerProvider,
9
+ pending,
10
+ serverWrapper,
11
+ } from "../../../test/serverProvider";
12
+ import { BrowserDocumentStorage } from "../DocumentStorage/BrowserDocumentStorage";
13
+ import { DocumentStorageProvider } from "../DocumentStorage/DocumentStorageProvider";
14
+ import type { DashboardEvent } from "../Dashboard/telemetry";
15
+
16
+ /**
17
+ * The Console's path through the builder, with the server mocked at the
18
+ * client and the browser's storage real: open the package file, offer a
19
+ * saved draft, save an edit into storage, export the file.
20
+ */
21
+ const PACKAGE_FILE = `## artifact { title="Storefront" tiles=["a -> by_cat"] } dashboard { columns=12 }
22
+ import { scoped_orders } from "../data_app.malloy"
23
+
24
+ source: a is scoped_orders extend {
25
+ # colspan=6
26
+ # label="By category"
27
+ view: by_cat is by_category
28
+ }`;
29
+
30
+ const getModel = mock((_env: string, _pkg: string, path: string) =>
31
+ Promise.resolve({
32
+ data:
33
+ path === "dashboards/overview.malloy"
34
+ ? { modelPath: path, sourceText: PACKAGE_FILE }
35
+ : {
36
+ modelPath: path,
37
+ sources: [
38
+ {
39
+ name: "scoped_orders",
40
+ views: [{ name: "by_category" }, { name: "by_brand" }],
41
+ },
42
+ ],
43
+ sourceInfos: [
44
+ JSON.stringify({
45
+ name: "scoped_orders",
46
+ schema: {
47
+ fields: [
48
+ {
49
+ name: "cat",
50
+ kind: "dimension",
51
+ type: { kind: "string_type" },
52
+ },
53
+ ],
54
+ },
55
+ }),
56
+ ],
57
+ },
58
+ }),
59
+ );
60
+ const getDashboard = mock(() =>
61
+ Promise.resolve({
62
+ data: { path: "dashboards/overview.malloy", givens: [], tiles: [] },
63
+ }),
64
+ );
65
+ const listDashboards = mock(() =>
66
+ Promise.resolve({ data: [{ name: "overview" }, { name: "regions" }] }),
67
+ );
68
+ const executeQueryModel = mock(() => pending());
69
+ mockServerProvider({
70
+ models: { getModel, executeQueryModel },
71
+ dashboards: { getDashboard, listDashboards },
72
+ });
73
+
74
+ // Imported after the stub is registered: a static import would hoist above it.
75
+ const { DashboardEditor } = await import("./DashboardEditor");
76
+
77
+ const DRAFT = {
78
+ workspace: "Local",
79
+ type: "dashboard" as const,
80
+ path: "env/pkg/dashboards/overview.malloy",
81
+ };
82
+
83
+ const mount = (
84
+ onExit?: () => void,
85
+ onEvent?: (event: DashboardEvent) => void,
86
+ ) => {
87
+ const storage = new BrowserDocumentStorage();
88
+ render(
89
+ <DocumentStorageProvider documentStorage={storage}>
90
+ <DashboardEditor
91
+ environmentName="env"
92
+ packageName="pkg"
93
+ dashboardName="overview"
94
+ {...(onExit ? { onExit } : {})}
95
+ {...(onEvent ? { onEvent } : {})}
96
+ />
97
+ </DocumentStorageProvider>,
98
+ { wrapper: serverWrapper },
99
+ );
100
+ return storage;
101
+ };
102
+
103
+ const button = (name: string | RegExp) =>
104
+ screen.getByRole("button", { name, hidden: true });
105
+
106
+ beforeEach(() => {
107
+ clearCache();
108
+ localStorage.clear();
109
+ });
110
+
111
+ describe("DashboardEditor", () => {
112
+ it("opens the package file in the builder, with the package's sources to pick from", async () => {
113
+ mount();
114
+ expect(await screen.findByText("Storefront")).toBeDefined();
115
+ expect(screen.getByLabelText("Tile by_cat")).toBeDefined();
116
+ // The catalog came from the model the file imports, by its resolved path.
117
+ await waitFor(() =>
118
+ expect(
119
+ getModel.mock.calls.some((call) => call[2] === "data_app.malloy"),
120
+ ).toBe(true),
121
+ );
122
+ await screen.findByRole("button", { name: "Add tile", hidden: true });
123
+ });
124
+
125
+ it("saves an edit into the browser and marks it saved", async () => {
126
+ const storage = mount();
127
+ await screen.findByText("Storefront");
128
+ fireEvent.click(screen.getByLabelText("Settings for By category"));
129
+ fireEvent.change(screen.getByLabelText("Tile title"), {
130
+ target: { value: "Categories" },
131
+ });
132
+ fireEvent.keyDown(screen.getByLabelText("Tile title"), { key: "Escape" });
133
+ fireEvent.click(button("Save changes"));
134
+ await waitFor(async () =>
135
+ expect(await storage.getDocument(DRAFT)).toContain(
136
+ '# label="Categories"',
137
+ ),
138
+ );
139
+ expect(await storage.getDocument(DRAFT)).toContain("# colspan=6");
140
+ // The copy just written is not "edits from an earlier visit": no offer
141
+ // to resume it appears over the page being edited.
142
+ await waitFor(() => expect(button("Saved")).toBeDefined());
143
+ expect(screen.queryByText(/saved in this browser/)).toBeNull();
144
+ });
145
+
146
+ it("offers a saved draft that differs from the package, and opens it on Resume", async () => {
147
+ const draft = PACKAGE_FILE.replace(
148
+ 'title="Storefront"',
149
+ 'title="Drafted"',
150
+ );
151
+ await new BrowserDocumentStorage().saveDocument(DRAFT, draft);
152
+ const onEvent = mock((_event: DashboardEvent) => {});
153
+ mount(undefined, onEvent);
154
+ expect(
155
+ await screen.findByText(
156
+ /edits to this dashboard saved in this browser/,
157
+ ),
158
+ ).toBeDefined();
159
+ // Until the reader chooses, the package file is what is open.
160
+ expect(await screen.findByText("Storefront")).toBeDefined();
161
+ fireEvent.click(button("Resume"));
162
+ expect(await screen.findByText("Drafted")).toBeDefined();
163
+ expect(onEvent.mock.calls.at(-1)?.[0]).toMatchObject({
164
+ type: "dashboard.opened",
165
+ from: "draft",
166
+ });
167
+ expect(screen.queryByText(/saved in this browser/)).toBeNull();
168
+ });
169
+
170
+ it("exports the file a save would write, hands Done to the host, and reports both opening and exporting", async () => {
171
+ const onExit = mock(() => {});
172
+ const onEvent = mock((_event: DashboardEvent) => {});
173
+ mount(onExit, onEvent);
174
+ await screen.findByText("Storefront");
175
+ await waitFor(() =>
176
+ expect(onEvent.mock.calls.map((call) => call[0].type)).toContain(
177
+ "dashboard.opened",
178
+ ),
179
+ );
180
+ expect(onEvent.mock.calls[0][0]).toMatchObject({
181
+ type: "dashboard.opened",
182
+ from: "package",
183
+ tiles: 1,
184
+ });
185
+ const created: Blob[] = [];
186
+ const createObjectURL = mock((blob: Blob) => {
187
+ created.push(blob);
188
+ return "blob:test";
189
+ });
190
+ const revoked = mock(() => {});
191
+ Object.assign(URL, { createObjectURL, revokeObjectURL: revoked });
192
+ const clicked = mock(() => {});
193
+ const click = HTMLAnchorElement.prototype.click;
194
+ HTMLAnchorElement.prototype.click = clicked;
195
+ try {
196
+ fireEvent.click(button("Export"));
197
+ await waitFor(() => expect(created).toHaveLength(1));
198
+ expect(await created[0].text()).toBe(PACKAGE_FILE);
199
+ expect(clicked).toHaveBeenCalledTimes(1);
200
+ expect(revoked).toHaveBeenCalledWith("blob:test");
201
+ expect(onEvent.mock.calls.at(-1)?.[0]).toEqual({
202
+ type: "dashboard.exported",
203
+ bytes: PACKAGE_FILE.length,
204
+ });
205
+ } finally {
206
+ HTMLAnchorElement.prototype.click = click;
207
+ }
208
+ fireEvent.click(button("Done"));
209
+ expect(onExit).toHaveBeenCalledTimes(1);
210
+ });
211
+ });
@@ -0,0 +1,493 @@
1
+ // Copyright (c) Credible Data Inc.
2
+ // SPDX-License-Identifier: MIT
3
+
4
+ import DownloadIcon from "@mui/icons-material/Download";
5
+ import { Alert, Box, Button, Stack, Typography } from "@mui/material";
6
+ import { useCallback, useEffect, useMemo, useRef, useState } from "react";
7
+ import { useQueryWithApiError } from "../../hooks/useQueryWithApiError";
8
+ import { ApiErrorDisplay } from "../ApiErrorDisplay";
9
+ import { DashboardTile, tileTitle } from "../Dashboard/DashboardTile";
10
+ import { now, type DashboardEventHandler } from "../Dashboard/telemetry";
11
+ import { useDocumentControls } from "../../hooks/useDocumentControls";
12
+ import {
13
+ useOptionalDocumentStorage,
14
+ type DocumentLocator,
15
+ } from "../DocumentStorage";
16
+ import { GivensPanel } from "../given";
17
+ import { Loading } from "../Loading";
18
+ import { TILE_MAX_HEIGHT } from "../RenderedResult/resultSizing";
19
+ import { useServer } from "../ServerProvider";
20
+ import { buildCatalog, type PackageCatalog } from "./catalog";
21
+ import { DashboardBuilder } from "./DashboardBuilder";
22
+ import type { DashboardDocument } from "./document";
23
+ import { previewGivens, previewTileQuery } from "./preview";
24
+ import { readDashboardDocument, readFailed } from "./readDocument";
25
+ import { spliceDashboardDocument, spliceFailed } from "./spliceDocument";
26
+
27
+ /**
28
+ * The builder, opened on a package dashboard, with everything a host has to
29
+ * supply already wired: the file's text and manifest from the server, a live
30
+ * control row and live tiles that follow the document, a catalog for the
31
+ * filter window's field search, and saving.
32
+ *
33
+ * SAVING is through the host's {@link DocumentStorage}, not to the package.
34
+ * The package dashboard is a read-only origin: editing works on a copy, the
35
+ * copy is saved where the host keeps documents (the Console's default is this
36
+ * browser), and "Export" hands the file back so it can be put in the package.
37
+ * That is the plan's copy-and-export model, and it needs no server write path.
38
+ * A host with no storage still gets the editor, without Save.
39
+ *
40
+ * What that costs is stated in the toolbar: a control added here is live in the
41
+ * editor (its value is written into each tile's query) but reaches the package
42
+ * only when the exported file does.
43
+ */
44
+ export interface DashboardEditorProps {
45
+ environmentName: string;
46
+ packageName: string;
47
+ /** The dashboard's slug: `overview`, not `dashboards/overview.malloy`. */
48
+ dashboardName: string;
49
+ /** Leave the editor: the host's "Done". Absent, no Done button. */
50
+ onExit?: () => void;
51
+ /**
52
+ * What the editor does — opened, saved, exported, refused — for the host
53
+ * to log or count; see `DashboardEvent`.
54
+ */
55
+ onEvent?: DashboardEventHandler;
56
+ }
57
+
58
+ /** The Console's key for a dashboard's copy; see the storage seam's locator rule. */
59
+ const dashboardLocator = (
60
+ workspace: string,
61
+ environmentName: string,
62
+ packageName: string,
63
+ modelPath: string,
64
+ ): DocumentLocator => ({
65
+ workspace,
66
+ type: "dashboard",
67
+ path: `${environmentName}/${packageName}/${modelPath}`,
68
+ });
69
+
70
+ export function DashboardEditor({
71
+ environmentName,
72
+ packageName,
73
+ dashboardName,
74
+ onExit,
75
+ onEvent,
76
+ }: DashboardEditorProps) {
77
+ const { apiClients } = useServer();
78
+ // When the editor was asked for — or the reader chose what to open — so
79
+ // "opened" can say how long it took. Read through refs by the open effect,
80
+ // so a host's handler changing identity does not re-open the document.
81
+ const startedAt = useRef(now());
82
+ const onEventRef = useRef(onEvent);
83
+ onEventRef.current = onEvent;
84
+ const storage = useOptionalDocumentStorage()?.documentStorage;
85
+ const modelPath = `dashboards/${dashboardName}.malloy`;
86
+
87
+ // The file as the package has it. `sourceText` rides on the compiled model.
88
+ const modelQuery = useQueryWithApiError({
89
+ queryKey: [
90
+ "dashboard-editor-model",
91
+ environmentName,
92
+ packageName,
93
+ modelPath,
94
+ ],
95
+ queryFn: () =>
96
+ apiClients.models.getModel(environmentName, packageName, modelPath),
97
+ });
98
+ const packageText = (
99
+ modelQuery.data?.data as { sourceText?: string } | undefined
100
+ )?.sourceText;
101
+
102
+ // The host's copy, if one was saved earlier: offered, never assumed.
103
+ const [workspace, setWorkspace] = useState<string | undefined>(undefined);
104
+ const [draft, setDraft] = useState<string | undefined>(undefined);
105
+ const [draftChecked, setDraftChecked] = useState(storage === undefined);
106
+ // Whether a draft was there when the editor opened: only that one is
107
+ // offered. A copy this session saves is not "edits from an earlier visit".
108
+ const [offered, setOffered] = useState(false);
109
+ useEffect(() => {
110
+ if (!storage) return;
111
+ let stale = false;
112
+ (async () => {
113
+ const writeable = await storage.listWorkspaces(true);
114
+ const name = writeable[0]?.name;
115
+ if (stale) return;
116
+ setWorkspace(name);
117
+ if (name === undefined) {
118
+ setDraftChecked(true);
119
+ return;
120
+ }
121
+ const text = await storage
122
+ .getDocument(
123
+ dashboardLocator(name, environmentName, packageName, modelPath),
124
+ )
125
+ .catch(() => undefined);
126
+ if (!stale) {
127
+ setDraft(text);
128
+ setOffered(text !== undefined);
129
+ setDraftChecked(true);
130
+ }
131
+ })();
132
+ return () => {
133
+ stale = true;
134
+ };
135
+ }, [storage, environmentName, packageName, modelPath]);
136
+
137
+ // What the editor opens: the draft when the reader chose to resume it, the
138
+ // package file otherwise. `generation` remounts the builder for a fresh
139
+ // history when that choice changes.
140
+ const [resume, setResume] = useState<boolean | undefined>(undefined);
141
+ const fromDraft = resume === true && draft !== undefined;
142
+ const opening = fromDraft ? draft : packageText;
143
+ const fromRef = useRef<"package" | "draft">("package");
144
+ fromRef.current = fromDraft ? "draft" : "package";
145
+ const [opened, setOpened] = useState<
146
+ | { source: string; document: DashboardDocument; generation: number }
147
+ | undefined
148
+ >(undefined);
149
+ const [openError, setOpenError] = useState<string | undefined>(undefined);
150
+ useEffect(() => {
151
+ if (opening === undefined) return;
152
+ let stale = false;
153
+ void readDashboardDocument(opening).then((result) => {
154
+ if (stale) return;
155
+ if (readFailed(result)) {
156
+ const reason = result.line
157
+ ? `${result.reason} (line ${result.line})`
158
+ : result.reason;
159
+ setOpenError(reason);
160
+ onEventRef.current?.({ type: "dashboard.open_refused", reason });
161
+ return;
162
+ }
163
+ setOpenError(undefined);
164
+ setOpened((previous) => ({
165
+ source: opening,
166
+ document: result.document,
167
+ generation: (previous?.generation ?? 0) + 1,
168
+ }));
169
+ onEventRef.current?.({
170
+ type: "dashboard.opened",
171
+ from: fromRef.current,
172
+ tiles: result.document.tiles.length,
173
+ durationMs: now() - startedAt.current,
174
+ });
175
+ });
176
+ return () => {
177
+ stale = true;
178
+ };
179
+ }, [opening]);
180
+
181
+ const save = useCallback(
182
+ async (source: string) => {
183
+ if (!storage || workspace === undefined)
184
+ throw new Error(
185
+ "This host keeps no documents, so there is nowhere to save.",
186
+ );
187
+ await storage.saveDocument(
188
+ dashboardLocator(
189
+ workspace,
190
+ environmentName,
191
+ packageName,
192
+ modelPath,
193
+ ),
194
+ source,
195
+ );
196
+ setDraft(source);
197
+ // Saving without choosing is choosing the package file.
198
+ setResume((chosen) => chosen ?? false);
199
+ },
200
+ [storage, workspace, environmentName, packageName, modelPath],
201
+ );
202
+ const choose = (resumeDraft: boolean) => {
203
+ startedAt.current = now();
204
+ setResume(resumeDraft);
205
+ };
206
+
207
+ if (modelQuery.isError)
208
+ return (
209
+ <ApiErrorDisplay
210
+ error={modelQuery.error}
211
+ context="Opening the dashboard"
212
+ />
213
+ );
214
+ if (!packageText || !draftChecked)
215
+ return <Loading text="Opening the dashboard…" />;
216
+ if (openError)
217
+ return (
218
+ <Alert severity="error" sx={{ m: 2 }}>
219
+ This dashboard cannot be opened in the builder: {openError}
220
+ </Alert>
221
+ );
222
+
223
+ const draftDiffers = draft !== undefined && draft !== packageText;
224
+ return (
225
+ <Stack sx={{ gap: 2 }}>
226
+ {offered && draftDiffers && resume === undefined && (
227
+ <Alert
228
+ severity="info"
229
+ action={
230
+ <Stack direction="row" sx={{ gap: 1 }}>
231
+ <Button size="small" onClick={() => choose(true)}>
232
+ Resume
233
+ </Button>
234
+ <Button size="small" onClick={() => choose(false)}>
235
+ Start from the package
236
+ </Button>
237
+ </Stack>
238
+ }
239
+ >
240
+ You have edits to this dashboard saved in this browser that the
241
+ package does not have.
242
+ </Alert>
243
+ )}
244
+ {opened && (
245
+ <Surface
246
+ key={opened.generation}
247
+ environmentName={environmentName}
248
+ packageName={packageName}
249
+ modelPath={modelPath}
250
+ slug={dashboardName}
251
+ opened={opened}
252
+ onSave={storage && workspace !== undefined ? save : undefined}
253
+ {...(onEvent ? { onEvent } : {})}
254
+ toolbar={
255
+ onExit && (
256
+ <Button size="small" onClick={onExit}>
257
+ Done
258
+ </Button>
259
+ )
260
+ }
261
+ note={
262
+ storage
263
+ ? "Saved in this browser. Export puts the file in the package."
264
+ : "Export puts the file in the package."
265
+ }
266
+ />
267
+ )}
268
+ </Stack>
269
+ );
270
+ }
271
+
272
+ /**
273
+ * The builder under a real control row, with the controls driving the tiles,
274
+ * both following the LIVE document rather than the saved file.
275
+ *
276
+ * Owns the given values for the same reason the reader's `Dashboard` does: the
277
+ * bar and the tiles have to read one set of values, so whatever holds them has
278
+ * to sit above both. The manifest supplies what the file cannot say about the
279
+ * model's own givens, and the set of givens the server can be sent; a control
280
+ * declared here and not yet in the package is written into each tile's query as
281
+ * a literal, so it works the moment it is added.
282
+ */
283
+ function Surface({
284
+ environmentName,
285
+ packageName,
286
+ modelPath,
287
+ slug,
288
+ opened,
289
+ onSave,
290
+ onEvent,
291
+ toolbar,
292
+ note,
293
+ }: {
294
+ environmentName: string;
295
+ packageName: string;
296
+ modelPath: string;
297
+ slug: string;
298
+ opened: { source: string; document: DashboardDocument; generation: number };
299
+ onSave?: (source: string) => Promise<void>;
300
+ onEvent?: DashboardEventHandler;
301
+ toolbar: React.ReactNode;
302
+ note: string;
303
+ }) {
304
+ const { apiClients } = useServer();
305
+
306
+ const { data, isSuccess } = useQueryWithApiError({
307
+ queryKey: [
308
+ "dashboard-editor-manifest",
309
+ environmentName,
310
+ packageName,
311
+ slug,
312
+ ],
313
+ queryFn: () =>
314
+ apiClients.dashboards.getDashboard(
315
+ environmentName,
316
+ packageName,
317
+ slug,
318
+ undefined,
319
+ ),
320
+ });
321
+ const manifest = data?.data;
322
+
323
+ // The package's other dashboards, by slug: where a clicked cell can go.
324
+ const { data: dashboardList } = useQueryWithApiError({
325
+ queryKey: ["dashboard-editor-dashboards", environmentName, packageName],
326
+ queryFn: () =>
327
+ apiClients.dashboards.listDashboards(
328
+ environmentName,
329
+ packageName,
330
+ undefined,
331
+ ),
332
+ });
333
+ const otherDashboards = useMemo(
334
+ () =>
335
+ (dashboardList?.data ?? [])
336
+ .map((d) => d.name)
337
+ .filter((name): name is string => !!name && name !== slug),
338
+ [dashboardList, slug],
339
+ );
340
+
341
+ // The catalog: the models this file imports, which is where its tiles'
342
+ // sources and their fields are declared.
343
+ const importPaths = useMemo(() => {
344
+ const dir = modelPath.slice(0, modelPath.lastIndexOf("/") + 1);
345
+ const resolved = new Set<string>();
346
+ for (const imported of opened.document.imports) {
347
+ const url = new URL(imported.from, `https://malloy.invalid/${dir}`);
348
+ resolved.add(url.pathname.slice(1));
349
+ }
350
+ return [...resolved];
351
+ }, [opened.document.imports, modelPath]);
352
+ const { data: catalog } = useQueryWithApiError<PackageCatalog>({
353
+ queryKey: [
354
+ "dashboard-editor-catalog",
355
+ environmentName,
356
+ packageName,
357
+ ...importPaths,
358
+ ],
359
+ queryFn: async () => {
360
+ const models = await Promise.all(
361
+ importPaths.map((path) =>
362
+ apiClients.models
363
+ .getModel(environmentName, packageName, path)
364
+ .then((response) => response.data),
365
+ ),
366
+ );
367
+ return buildCatalog(models);
368
+ },
369
+ enabled: importPaths.length > 0,
370
+ });
371
+
372
+ const [doc, setDoc] = useState(opened.document);
373
+ useEffect(() => setDoc(opened.document), [opened.document]);
374
+ // Export: the file a save would write for the document as it stands —
375
+ // spliced when asked for, so an edit costs nothing until then. Refused
376
+ // (which the builder has already reported), the file as opened goes out.
377
+ const exportFile = useCallback(async () => {
378
+ const result = await spliceDashboardDocument(opened.source, doc);
379
+ const text = spliceFailed(result) ? opened.source : result.source;
380
+ onEvent?.({ type: "dashboard.exported", bytes: text.length });
381
+ const blob = new Blob([text], { type: "text/plain;charset=utf-8" });
382
+ const url = URL.createObjectURL(blob);
383
+ const anchor = document.createElement("a");
384
+ anchor.href = url;
385
+ anchor.download = `${slug}.malloy`;
386
+ anchor.click();
387
+ URL.revokeObjectURL(url);
388
+ }, [opened.source, doc, slug, onEvent]);
389
+
390
+ const modelSpecs = useMemo(() => manifest?.givens ?? [], [manifest]);
391
+ const runnable = useMemo(
392
+ () =>
393
+ new Set(
394
+ modelSpecs
395
+ .map((spec) => spec.name)
396
+ .filter((name): name is string => name !== undefined),
397
+ ),
398
+ [modelSpecs],
399
+ );
400
+ const specs = useMemo(
401
+ () => previewGivens(doc, modelSpecs),
402
+ [doc, modelSpecs],
403
+ );
404
+ const { declaredTypes, applied, panel } = useDocumentControls({
405
+ specs,
406
+ loaded: isSuccess,
407
+ startingValues: manifest?.startingGivens,
408
+ documentKey: `${environmentName}/${packageName}/${slug}/edit`,
409
+ autorun: manifest?.autorun !== false,
410
+ environmentName,
411
+ packageName,
412
+ modelPath: manifest?.path,
413
+ documentName: slug,
414
+ });
415
+
416
+ const renderTile = useMemo(
417
+ () =>
418
+ function LiveTile(tile: DashboardDocument["tiles"][number]) {
419
+ const query = previewTileQuery(doc, tile, runnable, applied);
420
+ return (
421
+ <DashboardTile
422
+ environmentName={environmentName}
423
+ packageName={packageName}
424
+ modelPath={modelPath}
425
+ tile={query.expression}
426
+ label={
427
+ tile.label ?? tileTitle(`${tile.source} -> ${tile.name}`)
428
+ }
429
+ subtitle={tile.subtitle}
430
+ borderless={tile.borderless}
431
+ givens={applied}
432
+ declaredTypes={declaredTypes}
433
+ givenNames={query.givenNames}
434
+ height={TILE_MAX_HEIGHT}
435
+ />
436
+ );
437
+ },
438
+ [
439
+ doc,
440
+ runnable,
441
+ environmentName,
442
+ packageName,
443
+ modelPath,
444
+ applied,
445
+ declaredTypes,
446
+ ],
447
+ );
448
+
449
+ return (
450
+ <Stack sx={{ gap: 1 }}>
451
+ <DashboardBuilder
452
+ source={opened.source}
453
+ document={opened.document}
454
+ renderTile={renderTile}
455
+ givens={specs
456
+ .filter((spec) => spec.name !== undefined)
457
+ .map((spec) => ({
458
+ name: spec.name as string,
459
+ ...(spec.label ? { label: spec.label } : {}),
460
+ ...(spec.type ? { type: spec.type } : {}),
461
+ ...(spec.suggest?.dimension
462
+ ? { field: spec.suggest.dimension }
463
+ : {}),
464
+ }))}
465
+ onChange={setDoc}
466
+ {...(catalog ? { catalog } : {})}
467
+ dashboards={otherDashboards}
468
+ {...(onEvent ? { onEvent } : {})}
469
+ toolbar={
470
+ <>
471
+ <Button
472
+ size="small"
473
+ startIcon={<DownloadIcon fontSize="small" />}
474
+ onClick={() => void exportFile()}
475
+ >
476
+ Export
477
+ </Button>
478
+ {toolbar}
479
+ </>
480
+ }
481
+ controls={
482
+ isSuccess ? <GivensPanel {...panel} layout="bar" /> : undefined
483
+ }
484
+ {...(onSave ? { onSave } : {})}
485
+ />
486
+ <Box sx={{ px: 0.5 }}>
487
+ <Typography variant="caption" sx={{ opacity: 0.7 }}>
488
+ {note}
489
+ </Typography>
490
+ </Box>
491
+ </Stack>
492
+ );
493
+ }