@malloy-publisher/sdk 0.3.0 → 0.4.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (244) hide show
  1. package/README.md +22 -9
  2. package/dist/DocumentStorageProvider-CyOJ0hqf.es.js +24443 -0
  3. package/dist/DocumentStorageProvider-DGPQEd_l.cjs.js +134 -0
  4. package/dist/RenderedResult-BnPzJ9Jf.es.js +549 -0
  5. package/dist/RenderedResult-Dp22kZsQ.cjs.js +115 -0
  6. package/dist/{ServerProvider-DSK9rfSY.es.js → ServerProvider-BWOEKg0O.es.js} +1256 -1318
  7. package/dist/ServerProvider-Cc489A3f.cjs.js +1 -0
  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 +9482 -0
  11. package/dist/builder-entry.d.ts +8 -0
  12. package/dist/client/api.d.ts +100 -42
  13. package/dist/client/index.cjs.js +1 -1
  14. package/dist/client/index.es.js +1 -1
  15. package/dist/components/AppDialog.d.ts +30 -0
  16. package/dist/components/BackLink.d.ts +32 -0
  17. package/dist/components/Dashboard/Dashboard.d.ts +19 -14
  18. package/dist/components/Dashboard/DashboardBar.d.ts +21 -0
  19. package/dist/components/Dashboard/DashboardGrid.d.ts +67 -0
  20. package/dist/components/Dashboard/DashboardTile.d.ts +6 -1
  21. package/dist/components/Dashboard/ExploreDialog.d.ts +18 -0
  22. package/dist/components/Dashboard/RowsDialog.d.ts +47 -0
  23. package/dist/components/Dashboard/TileCard.d.ts +44 -0
  24. package/dist/components/Dashboard/index.d.ts +2 -0
  25. package/dist/components/Dashboard/promoteMeasureRow.d.ts +7 -3
  26. package/dist/components/Dashboard/telemetry.d.ts +48 -0
  27. package/dist/components/DashboardBuilder/AddTileDialog.d.ts +35 -0
  28. package/dist/components/DashboardBuilder/BuilderToolbar.d.ts +31 -0
  29. package/dist/components/DashboardBuilder/DashboardBuilder.d.ts +118 -0
  30. package/dist/components/DashboardBuilder/DashboardEditor.d.ts +30 -0
  31. package/dist/components/DashboardBuilder/DiffDialog.d.ts +15 -0
  32. package/dist/components/DashboardBuilder/DrillDialog.d.ts +15 -0
  33. package/dist/components/DashboardBuilder/FilterDialog.d.ts +54 -0
  34. package/dist/components/DashboardBuilder/FilterStrip.d.ts +17 -0
  35. package/dist/components/DashboardBuilder/SettingsPopover.d.ts +20 -0
  36. package/dist/components/DashboardBuilder/TileFrame.d.ts +42 -0
  37. package/dist/components/DashboardBuilder/TileMenu.d.ts +24 -0
  38. package/dist/components/DashboardBuilder/catalog.d.ts +62 -0
  39. package/dist/components/DashboardBuilder/controls.d.ts +157 -0
  40. package/dist/components/DashboardBuilder/diff.d.ts +35 -0
  41. package/dist/components/DashboardBuilder/document.d.ts +218 -0
  42. package/dist/components/DashboardBuilder/layout.d.ts +71 -0
  43. package/dist/components/DashboardBuilder/malloyText.d.ts +45 -0
  44. package/dist/components/DashboardBuilder/newDashboard.d.ts +17 -0
  45. package/dist/components/DashboardBuilder/preview.d.ts +60 -0
  46. package/dist/components/DashboardBuilder/readDocument.d.ts +106 -0
  47. package/dist/components/DashboardBuilder/sortable.d.ts +51 -0
  48. package/dist/components/DashboardBuilder/spliceDocument.d.ts +53 -0
  49. package/dist/components/DashboardBuilder/testing/fixtures.d.ts +10 -0
  50. package/dist/components/DashboardBuilder/useBuilderShortcuts.d.ts +22 -0
  51. package/dist/components/DashboardBuilder/useDashboardEditor.d.ts +63 -0
  52. package/dist/components/DashboardBuilder/useDraft.d.ts +13 -0
  53. package/dist/components/DashboardBuilder/useFilterForm.d.ts +65 -0
  54. package/dist/components/DashboardBuilder/useTileReorder.d.ts +22 -0
  55. package/dist/components/DashboardBuilder/useTileResize.d.ts +29 -0
  56. package/dist/components/DocumentStorage/DocumentStorageProvider.d.ts +7 -0
  57. package/dist/components/DocumentStorage/index.d.ts +1 -1
  58. package/dist/components/FloatingIconButton.d.ts +16 -0
  59. package/dist/components/ItemRow.d.ts +38 -0
  60. package/dist/components/Materializations/MaterializationDetailDialog.d.ts +1 -2
  61. package/dist/components/Materializations/MaterializationRunsList.d.ts +1 -5
  62. package/dist/components/Materializations/Materializations.d.ts +7 -3
  63. package/dist/components/Materializations/ScopeButton.d.ts +18 -0
  64. package/dist/components/Materializations/SectionLabel.d.ts +7 -4
  65. package/dist/components/Materializations/TriggerLabel.d.ts +14 -0
  66. package/dist/components/Materializations/index.d.ts +0 -1
  67. package/dist/components/Package/ContentTypeIcon.d.ts +3 -5
  68. package/dist/components/Package/NewDashboardDialog.d.ts +18 -0
  69. package/dist/components/Package/index.d.ts +0 -1
  70. package/dist/components/PackageSection.d.ts +23 -0
  71. package/dist/components/Prose.d.ts +46 -0
  72. package/dist/components/RenderedResult/ResultPanel.d.ts +30 -0
  73. package/dist/components/RenderedResult/index.d.ts +1 -0
  74. package/dist/components/buttons.d.ts +53 -0
  75. package/dist/components/drill/index.d.ts +1 -1
  76. package/dist/components/drill/resolveDrill.d.ts +22 -0
  77. package/dist/components/drill/useDrill.d.ts +11 -2
  78. package/dist/components/index.d.ts +6 -0
  79. package/dist/components/styles.d.ts +49 -44
  80. package/dist/hooks/index.d.ts +2 -0
  81. package/dist/hooks/useCrudMutation.d.ts +42 -0
  82. package/dist/hooks/useDocumentControls.d.ts +70 -0
  83. package/dist/hooks/useQueryResult.d.ts +40 -0
  84. package/dist/index.cjs.js +22 -273
  85. package/dist/index.d.ts +1 -0
  86. package/dist/index.es.js +16888 -44451
  87. package/dist/telemetry/consoleEvents.d.ts +60 -0
  88. package/dist/utils/malloyLiteral.d.ts +11 -0
  89. package/dist/utils/sha256.d.ts +2 -0
  90. package/package.json +24 -9
  91. package/src/builder-entry.ts +55 -0
  92. package/src/components/AppDialog.tsx +115 -0
  93. package/src/components/BackLink.tsx +83 -0
  94. package/src/components/Connections/AddConnectionDialog.tsx +50 -70
  95. package/src/components/Connections/DeleteConnectionDialog.tsx +23 -50
  96. package/src/components/Connections/EditConnectionDialog.tsx +54 -73
  97. package/src/components/Dashboard/Dashboard.spec.tsx +7 -10
  98. package/src/components/Dashboard/Dashboard.tsx +165 -175
  99. package/src/components/Dashboard/DashboardBar.tsx +88 -0
  100. package/src/components/Dashboard/DashboardGrid.tsx +124 -0
  101. package/src/components/Dashboard/DashboardTile.spec.tsx +30 -6
  102. package/src/components/Dashboard/DashboardTile.tsx +66 -123
  103. package/src/components/Dashboard/ExploreDialog.tsx +84 -0
  104. package/src/components/Dashboard/RowsDialog.spec.ts +42 -0
  105. package/src/components/Dashboard/RowsDialog.tsx +234 -0
  106. package/src/components/Dashboard/TileCard.tsx +120 -0
  107. package/src/components/Dashboard/index.ts +2 -0
  108. package/src/components/Dashboard/promoteMeasureRow.spec.ts +70 -0
  109. package/src/components/Dashboard/promoteMeasureRow.ts +33 -2
  110. package/src/components/Dashboard/telemetry.ts +51 -0
  111. package/src/components/Dashboard/tileGridColumn.spec.ts +1 -1
  112. package/src/components/DashboardBuilder/AddTileDialog.tsx +247 -0
  113. package/src/components/DashboardBuilder/BuilderToolbar.tsx +162 -0
  114. package/src/components/DashboardBuilder/DashboardBuilder.spec.tsx +852 -0
  115. package/src/components/DashboardBuilder/DashboardBuilder.tsx +666 -0
  116. package/src/components/DashboardBuilder/DashboardEditor.package.spec.tsx +163 -0
  117. package/src/components/DashboardBuilder/DashboardEditor.spec.tsx +188 -0
  118. package/src/components/DashboardBuilder/DashboardEditor.tsx +567 -0
  119. package/src/components/DashboardBuilder/DiffDialog.tsx +122 -0
  120. package/src/components/DashboardBuilder/DrillDialog.tsx +269 -0
  121. package/src/components/DashboardBuilder/FilterDialog.tsx +562 -0
  122. package/src/components/DashboardBuilder/FilterStrip.tsx +126 -0
  123. package/src/components/DashboardBuilder/SettingsPopover.tsx +168 -0
  124. package/src/components/DashboardBuilder/TileFrame.tsx +380 -0
  125. package/src/components/DashboardBuilder/TileMenu.tsx +188 -0
  126. package/src/components/DashboardBuilder/catalog.spec.ts +215 -0
  127. package/src/components/DashboardBuilder/catalog.ts +225 -0
  128. package/src/components/DashboardBuilder/controls.spec.ts +243 -0
  129. package/src/components/DashboardBuilder/controls.ts +398 -0
  130. package/src/components/DashboardBuilder/diff.spec.ts +44 -0
  131. package/src/components/DashboardBuilder/diff.ts +93 -0
  132. package/src/components/DashboardBuilder/document.ts +209 -0
  133. package/src/components/DashboardBuilder/keepRowStructure.spec.ts +84 -0
  134. package/src/components/DashboardBuilder/layout.ts +143 -0
  135. package/src/components/DashboardBuilder/malloyText.spec.ts +84 -0
  136. package/src/components/DashboardBuilder/malloyText.ts +151 -0
  137. package/src/components/DashboardBuilder/moveIntoGap.spec.ts +90 -0
  138. package/src/components/DashboardBuilder/newDashboard.spec.ts +40 -0
  139. package/src/components/DashboardBuilder/newDashboard.ts +48 -0
  140. package/src/components/DashboardBuilder/preview.spec.ts +149 -0
  141. package/src/components/DashboardBuilder/preview.ts +172 -0
  142. package/src/components/DashboardBuilder/readDocument.spec.ts +375 -0
  143. package/src/components/DashboardBuilder/readDocument.ts +467 -0
  144. package/src/components/DashboardBuilder/sortable.tsx +151 -0
  145. package/src/components/DashboardBuilder/spliceDocument.spec.ts +1161 -0
  146. package/src/components/DashboardBuilder/spliceDocument.ts +1135 -0
  147. package/src/components/DashboardBuilder/testing/fixtures.ts +48 -0
  148. package/src/components/DashboardBuilder/useBuilderShortcuts.ts +88 -0
  149. package/src/components/DashboardBuilder/useDashboardEditor.spec.ts +311 -0
  150. package/src/components/DashboardBuilder/useDashboardEditor.ts +201 -0
  151. package/src/components/DashboardBuilder/useDraft.ts +43 -0
  152. package/src/components/DashboardBuilder/useFilterForm.spec.tsx +144 -0
  153. package/src/components/DashboardBuilder/useFilterForm.ts +352 -0
  154. package/src/components/DashboardBuilder/useTileReorder.spec.tsx +97 -0
  155. package/src/components/DashboardBuilder/useTileReorder.ts +115 -0
  156. package/src/components/DashboardBuilder/useTileResize.spec.tsx +121 -0
  157. package/src/components/DashboardBuilder/useTileResize.ts +110 -0
  158. package/src/components/DashboardBuilder/withGaps.spec.ts +96 -0
  159. package/src/components/DocumentStorage/DocumentStorageProvider.tsx +12 -0
  160. package/src/components/DocumentStorage/index.ts +1 -0
  161. package/src/components/Environment/About.tsx +16 -62
  162. package/src/components/Environment/AddPackageDialog.tsx +85 -154
  163. package/src/components/Environment/Connections.tsx +125 -205
  164. package/src/components/Environment/DeletePackageDialog.tsx +32 -77
  165. package/src/components/Environment/EditPackageDialog.tsx +46 -58
  166. package/src/components/Environment/Environment.tsx +34 -36
  167. package/src/components/Environment/Packages.tsx +63 -128
  168. package/src/components/FloatingIconButton.tsx +41 -0
  169. package/src/components/Home/AddEnvironmentDialog.tsx +47 -70
  170. package/src/components/Home/DeleteEnvironmentDialog.tsx +32 -77
  171. package/src/components/Home/EditEnvironmentDialog.tsx +47 -61
  172. package/src/components/Home/Home.tsx +101 -214
  173. package/src/components/ItemRow.tsx +165 -0
  174. package/src/components/Materializations/CreateMaterializationDialog.tsx +34 -51
  175. package/src/components/Materializations/DeleteMaterializationDialog.tsx +31 -53
  176. package/src/components/Materializations/MaterializationDetailDialog.tsx +60 -69
  177. package/src/components/Materializations/MaterializationRunsList.tsx +29 -42
  178. package/src/components/Materializations/Materializations.tsx +137 -140
  179. package/src/components/Materializations/ScopeButton.tsx +85 -0
  180. package/src/components/Materializations/SectionLabel.tsx +7 -4
  181. package/src/components/Materializations/SetScheduleDialog.tsx +48 -89
  182. package/src/components/Materializations/TriggerLabel.tsx +36 -0
  183. package/src/components/Materializations/cron.spec.ts +113 -0
  184. package/src/components/Materializations/index.ts +0 -1
  185. package/src/components/Materializations/utils.spec.ts +182 -0
  186. package/src/components/Model/Model.tsx +6 -23
  187. package/src/components/Model/ModelCell.tsx +33 -72
  188. package/src/components/Notebook/Notebook.tsx +25 -88
  189. package/src/components/Notebook/NotebookCell.tsx +35 -183
  190. package/src/components/Package/ContentTypeIcon.spec.ts +22 -37
  191. package/src/components/Package/ContentTypeIcon.tsx +10 -12
  192. package/src/components/Package/NewDashboardDialog.spec.tsx +129 -0
  193. package/src/components/Package/NewDashboardDialog.tsx +265 -0
  194. package/src/components/Package/Package.tsx +179 -238
  195. package/src/components/Package/index.ts +0 -1
  196. package/src/components/PackageSection.tsx +85 -0
  197. package/src/components/Prose.spec.tsx +85 -0
  198. package/src/components/Prose.tsx +179 -0
  199. package/src/components/QueryResult/QueryResult.tsx +15 -43
  200. package/src/components/RenderedResult/RenderedResult.lifecycle.spec.tsx +198 -0
  201. package/src/components/RenderedResult/RenderedResult.tsx +22 -8
  202. package/src/components/RenderedResult/ResultContainer.tsx +4 -12
  203. package/src/components/RenderedResult/ResultPanel.spec.tsx +49 -0
  204. package/src/components/RenderedResult/ResultPanel.tsx +73 -0
  205. package/src/components/RenderedResult/index.ts +1 -0
  206. package/src/components/ResultsDialog.tsx +8 -32
  207. package/src/components/buttons.tsx +114 -0
  208. package/src/components/designSystem.spec.tsx +316 -0
  209. package/src/components/drill/index.ts +1 -0
  210. package/src/components/drill/resolveDrill.ts +22 -1
  211. package/src/components/drill/useDrill.spec.tsx +94 -0
  212. package/src/components/drill/useDrill.tsx +52 -12
  213. package/src/components/given/GivensPanel.tsx +1 -1
  214. package/src/components/given/paramCodec.spec.ts +1 -1
  215. package/src/components/index.ts +16 -0
  216. package/src/components/styles.ts +49 -122
  217. package/src/hooks/index.ts +13 -0
  218. package/src/hooks/useCrudMutation.spec.tsx +119 -0
  219. package/src/hooks/useCrudMutation.tsx +85 -0
  220. package/src/hooks/useDocumentControls.ts +170 -0
  221. package/src/hooks/useQueryResult.ts +82 -0
  222. package/src/index.ts +9 -0
  223. package/src/telemetry/consoleEvents.spec.ts +130 -0
  224. package/src/telemetry/consoleEvents.ts +124 -0
  225. package/src/theme/defaults.ts +34 -23
  226. package/src/theme/resolveTheme.spec.ts +9 -4
  227. package/src/theme/resolveTheme.ts +12 -8
  228. package/src/utils/malloyLiteral.spec.ts +43 -0
  229. package/src/utils/malloyLiteral.ts +76 -0
  230. package/src/utils/sha256.ts +13 -0
  231. package/test/README.md +1 -1
  232. package/test/serverProvider.tsx +5 -2
  233. package/vite.config.ts +5 -0
  234. package/dist/ServerProvider-CGnLjzag.cjs.js +0 -1
  235. package/dist/components/Materializations/CreateEnvMaterializationDialog.d.ts +0 -14
  236. package/dist/components/Materializations/EnvironmentMaterializations.d.ts +0 -7
  237. package/dist/components/Materializations/ScheduleCard.d.ts +0 -20
  238. package/dist/components/Materializations/TriggerChip.d.ts +0 -10
  239. package/dist/components/Package/Models.d.ts +0 -6
  240. package/src/components/Materializations/CreateEnvMaterializationDialog.tsx +0 -179
  241. package/src/components/Materializations/EnvironmentMaterializations.tsx +0 -267
  242. package/src/components/Materializations/ScheduleCard.tsx +0 -231
  243. package/src/components/Materializations/TriggerChip.tsx +0 -44
  244. package/src/components/Package/Models.tsx +0 -71
@@ -0,0 +1,567 @@
1
+ // Copyright (c) Credible Data Inc.
2
+ // SPDX-License-Identifier: MIT
3
+
4
+ import CheckIcon from "@mui/icons-material/Check";
5
+ import { Alert, Box, Button, Stack, Typography } from "@mui/material";
6
+ import { useQueryClient } from "@tanstack/react-query";
7
+ import { useCallback, useEffect, useMemo, useRef, useState } from "react";
8
+ import { useQueryWithApiError } from "../../hooks/useQueryWithApiError";
9
+ import { ApiErrorDisplay } from "../ApiErrorDisplay";
10
+ import { DashboardTile, tileTitle } from "../Dashboard/DashboardTile";
11
+ import { now, type DashboardEventHandler } from "../Dashboard/telemetry";
12
+ import { useDocumentControls } from "../../hooks/useDocumentControls";
13
+ import {
14
+ useOptionalDocumentStorage,
15
+ type DocumentLocator,
16
+ } from "../DocumentStorage";
17
+ import { GivensPanel } from "../given";
18
+ import { SecondaryButton } from "../buttons";
19
+ import { DashboardBar } from "../Dashboard/DashboardBar";
20
+ import { Loading } from "../Loading";
21
+ import { TILE_MAX_HEIGHT } from "../RenderedResult/resultSizing";
22
+ import { useServer } from "../ServerProvider";
23
+ import { buildCatalog, type PackageCatalog } from "./catalog";
24
+ import { DashboardBuilder } from "./DashboardBuilder";
25
+ import type { DashboardDocument } from "./document";
26
+ import { previewGivens, previewTileQuery } from "./preview";
27
+ import { readDashboardDocument, readFailed } from "./readDocument";
28
+ import { sha256Hex } from "../../utils/sha256";
29
+
30
+ /**
31
+ * The builder, opened on a package dashboard, with everything a host has to
32
+ * supply already wired: the file's text and manifest from the server, a live
33
+ * control row and live tiles that follow the document, a catalog for the
34
+ * filter window's field search, and saving.
35
+ *
36
+ * SAVING goes to the package on a server that takes writes, and otherwise to
37
+ * the host's {@link DocumentStorage} — the Console's default is this browser,
38
+ * where the copy is offered back on the next visit. A host with neither still
39
+ * gets the editor, without Save.
40
+ *
41
+ * What that costs is stated in the toolbar: a control added here is live in the
42
+ * editor (its value is written into each tile's query) but reaches the package
43
+ * only when the file is saved into it.
44
+ */
45
+ export interface DashboardEditorProps {
46
+ environmentName: string;
47
+ packageName: string;
48
+ /** The dashboard's slug: `overview`, not `dashboards/overview.malloy`. */
49
+ dashboardName: string;
50
+ /** Leave the editor: the host's "Done editing". Absent, no such button. */
51
+ onExit?: () => void;
52
+ /**
53
+ * What the editor does — opened, saved, refused — for the host to log or
54
+ * count; see `DashboardEvent`.
55
+ */
56
+ onEvent?: DashboardEventHandler;
57
+ }
58
+
59
+ /** The Console's key for a dashboard's copy; see the storage seam's locator rule. */
60
+ const dashboardLocator = (
61
+ workspace: string,
62
+ environmentName: string,
63
+ packageName: string,
64
+ modelPath: string,
65
+ ): DocumentLocator => ({
66
+ workspace,
67
+ type: "dashboard",
68
+ path: `${environmentName}/${packageName}/${modelPath}`,
69
+ });
70
+
71
+ export function DashboardEditor({
72
+ environmentName,
73
+ packageName,
74
+ dashboardName,
75
+ onExit,
76
+ onEvent,
77
+ }: DashboardEditorProps) {
78
+ const { apiClients, mutable } = useServer();
79
+ const queryClient = useQueryClient();
80
+ // When the editor was asked for — or the reader chose what to open — so
81
+ // "opened" can say how long it took. Read through refs by the open effect,
82
+ // so a host's handler changing identity does not re-open the document.
83
+ const startedAt = useRef(now());
84
+ const onEventRef = useRef(onEvent);
85
+ onEventRef.current = onEvent;
86
+ const storage = useOptionalDocumentStorage()?.documentStorage;
87
+ const modelPath = `dashboards/${dashboardName}.malloy`;
88
+
89
+ // The file as the package has it. `sourceText` rides on the compiled model.
90
+ const modelQuery = useQueryWithApiError({
91
+ queryKey: [
92
+ "dashboard-editor-model",
93
+ environmentName,
94
+ packageName,
95
+ modelPath,
96
+ ],
97
+ queryFn: () =>
98
+ apiClients.models.getModel(environmentName, packageName, modelPath),
99
+ });
100
+ const packageText = (
101
+ modelQuery.data?.data as { sourceText?: string } | undefined
102
+ )?.sourceText;
103
+ // The hash of the package file as opened: what a save into the package
104
+ // hands back as `expectedHash`, so a copy someone else changed in the
105
+ // meantime is refused rather than overwritten.
106
+ const [packageHash, setPackageHash] = useState<string | undefined>(
107
+ undefined,
108
+ );
109
+ useEffect(() => {
110
+ if (packageText === undefined) return;
111
+ let stale = false;
112
+ void sha256Hex(packageText).then((hash) => {
113
+ if (!stale) setPackageHash(hash);
114
+ });
115
+ return () => {
116
+ stale = true;
117
+ };
118
+ }, [packageText]);
119
+
120
+ // The host's copy, if one was saved earlier: offered, never assumed.
121
+ const [workspace, setWorkspace] = useState<string | undefined>(undefined);
122
+ const [draft, setDraft] = useState<string | undefined>(undefined);
123
+ const [draftChecked, setDraftChecked] = useState(storage === undefined);
124
+ // Whether a draft was there when the editor opened: only that one is
125
+ // offered. A copy this session saves is not "edits from an earlier visit".
126
+ const [offered, setOffered] = useState(false);
127
+ useEffect(() => {
128
+ if (!storage) return;
129
+ let stale = false;
130
+ (async () => {
131
+ const writeable = await storage.listWorkspaces(true);
132
+ const name = writeable[0]?.name;
133
+ if (stale) return;
134
+ setWorkspace(name);
135
+ if (name === undefined) {
136
+ setDraftChecked(true);
137
+ return;
138
+ }
139
+ const text = await storage
140
+ .getDocument(
141
+ dashboardLocator(name, environmentName, packageName, modelPath),
142
+ )
143
+ .catch(() => undefined);
144
+ if (!stale) {
145
+ setDraft(text);
146
+ setOffered(text !== undefined);
147
+ setDraftChecked(true);
148
+ }
149
+ })();
150
+ return () => {
151
+ stale = true;
152
+ };
153
+ }, [storage, environmentName, packageName, modelPath]);
154
+
155
+ // What the editor opens: the draft when the reader chose to resume it, the
156
+ // package file otherwise. `generation` remounts the builder for a fresh
157
+ // history when that choice changes.
158
+ const [resume, setResume] = useState<boolean | undefined>(undefined);
159
+ const fromDraft = resume === true && draft !== undefined;
160
+ const opening = fromDraft ? draft : packageText;
161
+ const fromRef = useRef<"package" | "draft">("package");
162
+ fromRef.current = fromDraft ? "draft" : "package";
163
+ const [opened, setOpened] = useState<
164
+ | { source: string; document: DashboardDocument; generation: number }
165
+ | undefined
166
+ >(undefined);
167
+ const [openError, setOpenError] = useState<string | undefined>(undefined);
168
+ // The text the builder last saved into the package. When that text comes
169
+ // back from the server it is not a new document to open — the builder
170
+ // already holds it, with its history — so the open effect leaves it be.
171
+ const savedRef = useRef<string | undefined>(undefined);
172
+ useEffect(() => {
173
+ if (opening === undefined || opening === savedRef.current) return;
174
+ let stale = false;
175
+ void readDashboardDocument(opening).then((result) => {
176
+ if (stale) return;
177
+ if (readFailed(result)) {
178
+ const reason = result.line
179
+ ? `${result.reason} (line ${result.line})`
180
+ : result.reason;
181
+ setOpenError(reason);
182
+ onEventRef.current?.({ type: "dashboard.open_refused", reason });
183
+ return;
184
+ }
185
+ setOpenError(undefined);
186
+ setOpened((previous) => ({
187
+ source: opening,
188
+ document: result.document,
189
+ generation: (previous?.generation ?? 0) + 1,
190
+ }));
191
+ onEventRef.current?.({
192
+ type: "dashboard.opened",
193
+ from: fromRef.current,
194
+ tiles: result.document.tiles.length,
195
+ durationMs: now() - startedAt.current,
196
+ });
197
+ });
198
+ return () => {
199
+ stale = true;
200
+ };
201
+ }, [opening]);
202
+
203
+ const locator =
204
+ workspace === undefined
205
+ ? undefined
206
+ : dashboardLocator(workspace, environmentName, packageName, modelPath);
207
+ const saveToBrowser = useCallback(
208
+ async (source: string) => {
209
+ if (!storage || !locator)
210
+ throw new Error(
211
+ "This host keeps no documents, so there is nowhere to save.",
212
+ );
213
+ await storage.saveDocument(locator, source);
214
+ setDraft(source);
215
+ // Saving without choosing is choosing the package file.
216
+ setResume((chosen) => chosen ?? false);
217
+ },
218
+ [storage, locator],
219
+ );
220
+ // Into the package itself, when the server takes writes: compile-checked,
221
+ // written atomically and reloaded there, refused if the file changed since
222
+ // it was opened. A browser draft of the same file is superseded by it.
223
+ const saveToPackage = useCallback(
224
+ async (source: string) => {
225
+ if (packageHash === undefined)
226
+ throw new Error("The package file is still loading; try again.");
227
+ let result;
228
+ try {
229
+ result = await apiClients.models.updateModelSource(
230
+ environmentName,
231
+ packageName,
232
+ modelPath,
233
+ { source, expectedHash: packageHash },
234
+ );
235
+ } catch (error) {
236
+ throw new Error(apiErrorMessage(error));
237
+ }
238
+ savedRef.current = source;
239
+ setPackageHash(result.data.contentHash);
240
+ if (storage && locator) {
241
+ await storage.deleteDocument(locator).catch(() => undefined);
242
+ setDraft(undefined);
243
+ setOffered(false);
244
+ }
245
+ setResume((chosen) => chosen ?? false);
246
+ // The package changed: the file, the manifest the live view reads,
247
+ // the package's dashboards list, and the dashboard the reader sees.
248
+ await queryClient.invalidateQueries({
249
+ queryKey: [
250
+ "dashboard-editor-model",
251
+ environmentName,
252
+ packageName,
253
+ modelPath,
254
+ ],
255
+ });
256
+ for (const key of [
257
+ "dashboard-editor-manifest",
258
+ "dashboards",
259
+ "dashboard",
260
+ ])
261
+ void queryClient.invalidateQueries({ queryKey: [key] });
262
+ },
263
+ [
264
+ apiClients,
265
+ environmentName,
266
+ packageName,
267
+ modelPath,
268
+ packageHash,
269
+ storage,
270
+ locator,
271
+ queryClient,
272
+ ],
273
+ );
274
+ const save = mutable
275
+ ? saveToPackage
276
+ : storage && locator
277
+ ? saveToBrowser
278
+ : undefined;
279
+ const choose = (resumeDraft: boolean) => {
280
+ startedAt.current = now();
281
+ setResume(resumeDraft);
282
+ };
283
+
284
+ if (modelQuery.isError)
285
+ return (
286
+ <ApiErrorDisplay
287
+ error={modelQuery.error}
288
+ context="Opening the dashboard"
289
+ />
290
+ );
291
+ if (!packageText || !draftChecked)
292
+ // The bar first, so the page it is opening into is already the right
293
+ // shape: the reader's view had a bar in this spot, and a spinner where
294
+ // the bar was made the switch look like a page reload.
295
+ return (
296
+ <Stack sx={{ gap: 2 }}>
297
+ <DashboardBar />
298
+ <Loading text="Opening the dashboard…" />
299
+ </Stack>
300
+ );
301
+ if (openError)
302
+ return (
303
+ <Alert severity="error" sx={{ m: 2 }}>
304
+ This dashboard cannot be opened in the builder: {openError}
305
+ </Alert>
306
+ );
307
+
308
+ const draftDiffers = draft !== undefined && draft !== packageText;
309
+ return (
310
+ <Stack sx={{ gap: 2 }}>
311
+ {offered && draftDiffers && resume === undefined && (
312
+ <Alert
313
+ severity="info"
314
+ action={
315
+ <Stack direction="row" sx={{ gap: 1 }}>
316
+ <Button size="small" onClick={() => choose(true)}>
317
+ Resume
318
+ </Button>
319
+ <Button size="small" onClick={() => choose(false)}>
320
+ Start from the package
321
+ </Button>
322
+ </Stack>
323
+ }
324
+ >
325
+ You have edits to this dashboard saved in this browser that the
326
+ package does not have.
327
+ </Alert>
328
+ )}
329
+ {opened && (
330
+ <Surface
331
+ key={opened.generation}
332
+ environmentName={environmentName}
333
+ packageName={packageName}
334
+ modelPath={modelPath}
335
+ slug={dashboardName}
336
+ opened={opened}
337
+ onSave={save}
338
+ savesTo={mutable ? "package" : "browser"}
339
+ {...(onEvent ? { onEvent } : {})}
340
+ toolbar={
341
+ onExit && (
342
+ <SecondaryButton
343
+ label="Done editing"
344
+ icon={<CheckIcon />}
345
+ onClick={onExit}
346
+ />
347
+ )
348
+ }
349
+ note={
350
+ mutable
351
+ ? "Save writes the file into the package."
352
+ : storage
353
+ ? "Saved in this browser: this server does not take writes."
354
+ : "This server does not take writes."
355
+ }
356
+ />
357
+ )}
358
+ </Stack>
359
+ );
360
+ }
361
+
362
+ /**
363
+ * The builder under a real control row, with the controls driving the tiles,
364
+ * both following the LIVE document rather than the saved file.
365
+ *
366
+ * Owns the given values for the same reason the reader's `Dashboard` does: the
367
+ * bar and the tiles have to read one set of values, so whatever holds them has
368
+ * to sit above both. The manifest supplies what the file cannot say about the
369
+ * model's own givens, and the set of givens the server can be sent; a control
370
+ * declared here and not yet in the package is written into each tile's query as
371
+ * a literal, so it works the moment it is added.
372
+ */
373
+ function Surface({
374
+ environmentName,
375
+ packageName,
376
+ modelPath,
377
+ slug,
378
+ opened,
379
+ onSave,
380
+ onEvent,
381
+ savesTo,
382
+ toolbar,
383
+ note,
384
+ }: {
385
+ environmentName: string;
386
+ packageName: string;
387
+ modelPath: string;
388
+ slug: string;
389
+ opened: { source: string; document: DashboardDocument; generation: number };
390
+ onSave?: (source: string) => Promise<void>;
391
+ onEvent?: DashboardEventHandler;
392
+ savesTo: "package" | "browser";
393
+ toolbar: React.ReactNode;
394
+ note: string;
395
+ }) {
396
+ const { apiClients } = useServer();
397
+
398
+ const { data, isSuccess } = useQueryWithApiError({
399
+ queryKey: [
400
+ "dashboard-editor-manifest",
401
+ environmentName,
402
+ packageName,
403
+ slug,
404
+ ],
405
+ queryFn: () =>
406
+ apiClients.dashboards.getDashboard(
407
+ environmentName,
408
+ packageName,
409
+ slug,
410
+ undefined,
411
+ ),
412
+ });
413
+ const manifest = data?.data;
414
+
415
+ // The package's other dashboards, by slug: where a clicked cell can go.
416
+ const { data: dashboardList } = useQueryWithApiError({
417
+ queryKey: ["dashboard-editor-dashboards", environmentName, packageName],
418
+ queryFn: () =>
419
+ apiClients.dashboards.listDashboards(
420
+ environmentName,
421
+ packageName,
422
+ undefined,
423
+ ),
424
+ });
425
+ const otherDashboards = useMemo(
426
+ () =>
427
+ (dashboardList?.data ?? [])
428
+ .map((d) => d.name)
429
+ .filter((name): name is string => !!name && name !== slug),
430
+ [dashboardList, slug],
431
+ );
432
+
433
+ // The catalog: the models this file imports, which is where its tiles'
434
+ // sources and their fields are declared.
435
+ const importPaths = useMemo(() => {
436
+ const dir = modelPath.slice(0, modelPath.lastIndexOf("/") + 1);
437
+ const resolved = new Set<string>();
438
+ for (const imported of opened.document.imports) {
439
+ const url = new URL(imported.from, `https://malloy.invalid/${dir}`);
440
+ resolved.add(url.pathname.slice(1));
441
+ }
442
+ return [...resolved];
443
+ }, [opened.document.imports, modelPath]);
444
+ const { data: catalog } = useQueryWithApiError<PackageCatalog>({
445
+ queryKey: [
446
+ "dashboard-editor-catalog",
447
+ environmentName,
448
+ packageName,
449
+ ...importPaths,
450
+ ],
451
+ queryFn: async () => {
452
+ const models = await Promise.all(
453
+ importPaths.map((path) =>
454
+ apiClients.models
455
+ .getModel(environmentName, packageName, path)
456
+ .then((response) => response.data),
457
+ ),
458
+ );
459
+ return buildCatalog(models);
460
+ },
461
+ enabled: importPaths.length > 0,
462
+ });
463
+
464
+ const [doc, setDoc] = useState(opened.document);
465
+ useEffect(() => setDoc(opened.document), [opened.document]);
466
+ const modelSpecs = useMemo(() => manifest?.givens ?? [], [manifest]);
467
+ const runnable = useMemo(
468
+ () =>
469
+ new Set(
470
+ modelSpecs
471
+ .map((spec) => spec.name)
472
+ .filter((name): name is string => name !== undefined),
473
+ ),
474
+ [modelSpecs],
475
+ );
476
+ const specs = useMemo(
477
+ () => previewGivens(doc, modelSpecs),
478
+ [doc, modelSpecs],
479
+ );
480
+ const { declaredTypes, applied, panel } = useDocumentControls({
481
+ specs,
482
+ loaded: isSuccess,
483
+ startingValues: manifest?.startingGivens,
484
+ documentKey: `${environmentName}/${packageName}/${slug}/edit`,
485
+ autorun: manifest?.autorun !== false,
486
+ environmentName,
487
+ packageName,
488
+ modelPath: manifest?.path,
489
+ documentName: slug,
490
+ });
491
+
492
+ const renderTile = useMemo(
493
+ () =>
494
+ function LiveTile(tile: DashboardDocument["tiles"][number]) {
495
+ const query = previewTileQuery(doc, tile, runnable, applied);
496
+ return (
497
+ <DashboardTile
498
+ environmentName={environmentName}
499
+ packageName={packageName}
500
+ modelPath={modelPath}
501
+ tile={query.expression}
502
+ label={
503
+ tile.label ?? tileTitle(`${tile.source} -> ${tile.name}`)
504
+ }
505
+ subtitle={tile.subtitle}
506
+ borderless={tile.borderless}
507
+ givens={applied}
508
+ declaredTypes={declaredTypes}
509
+ givenNames={query.givenNames}
510
+ height={TILE_MAX_HEIGHT}
511
+ />
512
+ );
513
+ },
514
+ [
515
+ doc,
516
+ runnable,
517
+ environmentName,
518
+ packageName,
519
+ modelPath,
520
+ applied,
521
+ declaredTypes,
522
+ ],
523
+ );
524
+
525
+ return (
526
+ <Stack sx={{ gap: 1 }}>
527
+ <DashboardBuilder
528
+ source={opened.source}
529
+ document={opened.document}
530
+ renderTile={renderTile}
531
+ givens={specs
532
+ .filter((spec) => spec.name !== undefined)
533
+ .map((spec) => ({
534
+ name: spec.name as string,
535
+ ...(spec.label ? { label: spec.label } : {}),
536
+ ...(spec.type ? { type: spec.type } : {}),
537
+ ...(spec.suggest?.dimension
538
+ ? { field: spec.suggest.dimension }
539
+ : {}),
540
+ }))}
541
+ onChange={setDoc}
542
+ {...(catalog ? { catalog } : {})}
543
+ dashboards={otherDashboards}
544
+ {...(onEvent ? { onEvent } : {})}
545
+ toolbar={toolbar}
546
+ controls={
547
+ isSuccess ? <GivensPanel {...panel} layout="bar" /> : undefined
548
+ }
549
+ {...(onSave ? { onSave } : {})}
550
+ savesTo={savesTo}
551
+ />
552
+ <Box sx={{ px: 0.5 }}>
553
+ <Typography variant="caption" sx={{ opacity: 0.7 }}>
554
+ {note}
555
+ </Typography>
556
+ </Box>
557
+ </Stack>
558
+ );
559
+ }
560
+
561
+ /** The server's own reason for a refused write, when it gave one. */
562
+ function apiErrorMessage(error: unknown): string {
563
+ const data = (error as { response?: { data?: { message?: string } } })
564
+ .response?.data;
565
+ if (data?.message) return data.message;
566
+ return error instanceof Error ? error.message : String(error);
567
+ }
@@ -0,0 +1,122 @@
1
+ // Copyright (c) Credible Data Inc.
2
+ // SPDX-License-Identifier: MIT
3
+
4
+ import { Box, Button } from "@mui/material";
5
+ import { useMemo } from "react";
6
+ import { usePublisherTheme } from "../../theme/ThemeContext";
7
+ import { foldUnchanged, lineDiff } from "./diff";
8
+ import { AppDialog } from "../AppDialog";
9
+
10
+ /**
11
+ * What a save will do to the file, before it does it.
12
+ *
13
+ * Shown for a STRUCTURAL save — a tile added or removed — because those move
14
+ * declarations and the comments beside them, and the file is git-native: a
15
+ * diff is the idiom its authors already read. A property edit never needs
16
+ * this; it changes one tag on one line.
17
+ */
18
+ export function DiffDialog({
19
+ open,
20
+ before,
21
+ after,
22
+ onConfirm,
23
+ onClose,
24
+ }: {
25
+ open: boolean;
26
+ before: string;
27
+ after: string;
28
+ onConfirm: () => void;
29
+ onClose: () => void;
30
+ }) {
31
+ const { theme } = usePublisherTheme();
32
+ const lines = useMemo(
33
+ () => (open ? foldUnchanged(lineDiff(before, after)) : []),
34
+ [open, before, after],
35
+ );
36
+ const added = lines.filter((l) => l.kind === "add").length;
37
+ const removed = lines.filter((l) => l.kind === "del").length;
38
+ return (
39
+ <AppDialog
40
+ open={open}
41
+ onClose={onClose}
42
+ maxWidth="md"
43
+ title="Review the change to the file"
44
+ description={
45
+ <>
46
+ A tile was added or removed, which moves declarations. Lines the
47
+ builder does not own — comments, other Malloy — are left where
48
+ they were; check they still read right.{" "}
49
+ <Box
50
+ component="span"
51
+ sx={{ fontVariantNumeric: "tabular-nums" }}
52
+ >
53
+ +{added} −{removed}
54
+ </Box>
55
+ </>
56
+ }
57
+ actions={
58
+ <>
59
+ <Button onClick={onClose}>Keep editing</Button>
60
+ <Button variant="contained" onClick={onConfirm}>
61
+ Save this
62
+ </Button>
63
+ </>
64
+ }
65
+ >
66
+ <Box
67
+ component="pre"
68
+ aria-label="File changes"
69
+ sx={{
70
+ m: 0,
71
+ px: 2,
72
+ py: 1,
73
+ fontFamily: "ui-monospace, SFMono-Regular, Menlo, monospace",
74
+ fontSize: 12,
75
+ lineHeight: 1.6,
76
+ overflowX: "auto",
77
+ bgcolor: theme.background,
78
+ color: theme.foreground,
79
+ }}
80
+ >
81
+ {lines.map((line, index) =>
82
+ line.kind === "fold" ? (
83
+ <Box
84
+ key={index}
85
+ component="span"
86
+ sx={{ display: "block", opacity: 0.55, py: 0.25 }}
87
+ >
88
+ {`⋯ ${line.count} unchanged line${line.count === 1 ? "" : "s"}`}
89
+ </Box>
90
+ ) : (
91
+ <Box
92
+ key={index}
93
+ component="span"
94
+ sx={{
95
+ display: "block",
96
+ mx: -2,
97
+ px: 2,
98
+ whiteSpace: "pre",
99
+ bgcolor:
100
+ line.kind === "add"
101
+ ? "rgba(46, 125, 91, 0.16)"
102
+ : line.kind === "del"
103
+ ? "rgba(168, 41, 31, 0.14)"
104
+ : "transparent",
105
+ textDecoration:
106
+ line.kind === "del" ? "line-through" : "none",
107
+ opacity: line.kind === "del" ? 0.8 : 1,
108
+ }}
109
+ >
110
+ {line.kind === "add"
111
+ ? "+ "
112
+ : line.kind === "del"
113
+ ? "− "
114
+ : " "}
115
+ {line.text}
116
+ </Box>
117
+ ),
118
+ )}
119
+ </Box>
120
+ </AppDialog>
121
+ );
122
+ }