@malloy-publisher/sdk 0.3.1 → 0.4.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 (136) hide show
  1. package/README.md +33 -9
  2. package/dist/{DocumentStorageProvider-tGvodI8f.es.js → DocumentStorage-BiFqO15i.es.js} +7126 -6943
  3. package/dist/DocumentStorage-CMyLifsz.cjs.js +134 -0
  4. package/dist/RenderedResult-CZzE8wv-.cjs.js +115 -0
  5. package/dist/{RenderedResult-mDE-4u8S.es.js → RenderedResult-CvrmYyr5.es.js} +64 -57
  6. package/dist/{ServerProvider-X2Ma0HRs.es.js → ServerProvider-BWOEKg0O.es.js} +1217 -1244
  7. package/dist/ServerProvider-Cc489A3f.cjs.js +1 -0
  8. package/dist/builder/index.cjs.js +52 -52
  9. package/dist/builder/index.es.js +3961 -3960
  10. package/dist/client/api.d.ts +100 -42
  11. package/dist/client/index.cjs.js +1 -1
  12. package/dist/client/index.es.js +1 -1
  13. package/dist/components/AppDialog.d.ts +30 -0
  14. package/dist/components/BackLink.d.ts +32 -0
  15. package/dist/components/Dashboard/DashboardBar.d.ts +21 -0
  16. package/dist/components/Dashboard/telemetry.d.ts +24 -7
  17. package/dist/components/DashboardBuilder/BuilderToolbar.d.ts +12 -10
  18. package/dist/components/DashboardBuilder/DashboardBuilder.d.ts +20 -2
  19. package/dist/components/DashboardBuilder/DashboardEditor.d.ts +21 -11
  20. package/dist/components/DashboardBuilder/newDashboard.d.ts +17 -0
  21. package/dist/components/DashboardBuilder/spliceDocument.d.ts +10 -1
  22. package/dist/components/DocumentStorage/DocumentStorage.d.ts +69 -5
  23. package/dist/components/DocumentStorage/index.d.ts +1 -0
  24. package/dist/components/ItemRow.d.ts +38 -0
  25. package/dist/components/Materializations/MaterializationDetailDialog.d.ts +1 -2
  26. package/dist/components/Materializations/MaterializationRunsList.d.ts +1 -5
  27. package/dist/components/Materializations/Materializations.d.ts +7 -3
  28. package/dist/components/Materializations/ScopeButton.d.ts +18 -0
  29. package/dist/components/Materializations/SectionLabel.d.ts +7 -4
  30. package/dist/components/Materializations/TriggerLabel.d.ts +14 -0
  31. package/dist/components/Materializations/index.d.ts +0 -1
  32. package/dist/components/Package/ContentTypeIcon.d.ts +3 -5
  33. package/dist/components/Package/NewDashboardDialog.d.ts +18 -0
  34. package/dist/components/Package/index.d.ts +0 -1
  35. package/dist/components/PackageSection.d.ts +23 -0
  36. package/dist/components/buttons.d.ts +53 -0
  37. package/dist/components/index.d.ts +5 -0
  38. package/dist/components/styles.d.ts +49 -40
  39. package/dist/hooks/useCrudMutation.d.ts +42 -0
  40. package/dist/index.cjs.js +22 -26
  41. package/dist/index.d.ts +1 -0
  42. package/dist/index.es.js +17431 -20676
  43. package/dist/telemetry/consoleEvents.d.ts +60 -0
  44. package/dist/utils/sha256.d.ts +2 -0
  45. package/package.json +1 -1
  46. package/src/components/AppDialog.tsx +115 -0
  47. package/src/components/BackLink.tsx +83 -0
  48. package/src/components/Connections/AddConnectionDialog.tsx +50 -70
  49. package/src/components/Connections/DeleteConnectionDialog.tsx +23 -50
  50. package/src/components/Connections/EditConnectionDialog.tsx +54 -73
  51. package/src/components/Dashboard/DashboardBar.tsx +88 -0
  52. package/src/components/Dashboard/telemetry.ts +24 -5
  53. package/src/components/DashboardBuilder/AddTileDialog.tsx +141 -143
  54. package/src/components/DashboardBuilder/BuilderToolbar.tsx +110 -218
  55. package/src/components/DashboardBuilder/DashboardBuilder.spec.tsx +5 -11
  56. package/src/components/DashboardBuilder/DashboardBuilder.tsx +202 -171
  57. package/src/components/DashboardBuilder/DashboardEditor.authoritative.spec.tsx +706 -0
  58. package/src/components/DashboardBuilder/DashboardEditor.package.spec.tsx +163 -0
  59. package/src/components/DashboardBuilder/DashboardEditor.spec.tsx +2 -25
  60. package/src/components/DashboardBuilder/DashboardEditor.tsx +442 -94
  61. package/src/components/DashboardBuilder/DiffDialog.tsx +75 -82
  62. package/src/components/DashboardBuilder/DrillDialog.tsx +144 -156
  63. package/src/components/DashboardBuilder/FilterDialog.tsx +276 -295
  64. package/src/components/DashboardBuilder/FilterStrip.tsx +11 -10
  65. package/src/components/DashboardBuilder/newDashboard.spec.ts +40 -0
  66. package/src/components/DashboardBuilder/newDashboard.ts +48 -0
  67. package/src/components/DashboardBuilder/spliceDocument.spec.ts +53 -0
  68. package/src/components/DashboardBuilder/spliceDocument.ts +45 -8
  69. package/src/components/DashboardBuilder/useDashboardEditor.spec.ts +56 -0
  70. package/src/components/DashboardBuilder/useDashboardEditor.ts +12 -4
  71. package/src/components/DocumentStorage/BrowserDocumentStorage.ts +7 -6
  72. package/src/components/DocumentStorage/DocumentStorage.ts +78 -5
  73. package/src/components/DocumentStorage/index.ts +1 -0
  74. package/src/components/Environment/About.tsx +14 -28
  75. package/src/components/Environment/AddPackageDialog.tsx +85 -154
  76. package/src/components/Environment/Connections.tsx +125 -205
  77. package/src/components/Environment/DeletePackageDialog.tsx +32 -77
  78. package/src/components/Environment/EditPackageDialog.tsx +46 -58
  79. package/src/components/Environment/Environment.tsx +34 -36
  80. package/src/components/Environment/Packages.tsx +63 -128
  81. package/src/components/Home/AddEnvironmentDialog.tsx +47 -70
  82. package/src/components/Home/DeleteEnvironmentDialog.tsx +32 -77
  83. package/src/components/Home/EditEnvironmentDialog.tsx +47 -61
  84. package/src/components/Home/Home.tsx +101 -214
  85. package/src/components/ItemRow.tsx +165 -0
  86. package/src/components/Materializations/CreateMaterializationDialog.tsx +34 -51
  87. package/src/components/Materializations/DeleteMaterializationDialog.tsx +31 -53
  88. package/src/components/Materializations/MaterializationDetailDialog.tsx +60 -69
  89. package/src/components/Materializations/MaterializationRunsList.tsx +29 -42
  90. package/src/components/Materializations/Materializations.tsx +137 -140
  91. package/src/components/Materializations/ScopeButton.tsx +85 -0
  92. package/src/components/Materializations/SectionLabel.tsx +7 -4
  93. package/src/components/Materializations/SetScheduleDialog.tsx +48 -89
  94. package/src/components/Materializations/TriggerLabel.tsx +36 -0
  95. package/src/components/Materializations/cron.spec.ts +113 -0
  96. package/src/components/Materializations/index.ts +0 -1
  97. package/src/components/Materializations/utils.spec.ts +182 -0
  98. package/src/components/Package/ContentTypeIcon.spec.ts +22 -37
  99. package/src/components/Package/ContentTypeIcon.tsx +10 -12
  100. package/src/components/Package/NewDashboardDialog.spec.tsx +129 -0
  101. package/src/components/Package/NewDashboardDialog.tsx +265 -0
  102. package/src/components/Package/Package.tsx +184 -238
  103. package/src/components/Package/index.ts +0 -1
  104. package/src/components/PackageSection.tsx +85 -0
  105. package/src/components/RenderedResult/RenderedResult.lifecycle.spec.tsx +198 -0
  106. package/src/components/RenderedResult/RenderedResult.tsx +22 -8
  107. package/src/components/ResultsDialog.tsx +8 -32
  108. package/src/components/buttons.tsx +114 -0
  109. package/src/components/designSystem.spec.tsx +316 -0
  110. package/src/components/given/paramCodec.spec.ts +1 -1
  111. package/src/components/index.ts +10 -0
  112. package/src/components/styles.ts +49 -85
  113. package/src/hooks/useCrudMutation.spec.tsx +119 -0
  114. package/src/hooks/useCrudMutation.tsx +85 -0
  115. package/src/index.ts +9 -0
  116. package/src/telemetry/consoleEvents.spec.ts +130 -0
  117. package/src/telemetry/consoleEvents.ts +124 -0
  118. package/src/theme/defaults.ts +34 -23
  119. package/src/theme/resolveTheme.spec.ts +9 -4
  120. package/src/theme/resolveTheme.ts +12 -8
  121. package/src/utils/sha256.ts +13 -0
  122. package/test/README.md +1 -1
  123. package/test/serverProvider.tsx +5 -2
  124. package/dist/DocumentStorageProvider-BeBD0uWc.cjs.js +0 -134
  125. package/dist/RenderedResult-CPi6uQWq.cjs.js +0 -115
  126. package/dist/ServerProvider-CH71GsoL.cjs.js +0 -1
  127. package/dist/components/Materializations/CreateEnvMaterializationDialog.d.ts +0 -14
  128. package/dist/components/Materializations/EnvironmentMaterializations.d.ts +0 -7
  129. package/dist/components/Materializations/ScheduleCard.d.ts +0 -20
  130. package/dist/components/Materializations/TriggerChip.d.ts +0 -10
  131. package/dist/components/Package/Models.d.ts +0 -6
  132. package/src/components/Materializations/CreateEnvMaterializationDialog.tsx +0 -179
  133. package/src/components/Materializations/EnvironmentMaterializations.tsx +0 -267
  134. package/src/components/Materializations/ScheduleCard.tsx +0 -231
  135. package/src/components/Materializations/TriggerChip.tsx +0 -44
  136. package/src/components/Package/Models.tsx +0 -71
@@ -1,19 +1,28 @@
1
1
  // Copyright (c) Credible Data Inc.
2
2
  // SPDX-License-Identifier: MIT
3
3
 
4
- import DownloadIcon from "@mui/icons-material/Download";
4
+ import CheckIcon from "@mui/icons-material/Check";
5
5
  import { Alert, Box, Button, Stack, Typography } from "@mui/material";
6
+ import { useQueryClient } from "@tanstack/react-query";
6
7
  import { useCallback, useEffect, useMemo, useRef, useState } from "react";
7
8
  import { useQueryWithApiError } from "../../hooks/useQueryWithApiError";
8
9
  import { ApiErrorDisplay } from "../ApiErrorDisplay";
9
10
  import { DashboardTile, tileTitle } from "../Dashboard/DashboardTile";
10
- import { now, type DashboardEventHandler } from "../Dashboard/telemetry";
11
+ import {
12
+ now,
13
+ type DashboardEvent,
14
+ type DashboardEventHandler,
15
+ } from "../Dashboard/telemetry";
11
16
  import { useDocumentControls } from "../../hooks/useDocumentControls";
12
17
  import {
18
+ isDocumentNotFound,
13
19
  useOptionalDocumentStorage,
14
20
  type DocumentLocator,
21
+ type Workspace,
15
22
  } from "../DocumentStorage";
16
23
  import { GivensPanel } from "../given";
24
+ import { SecondaryButton } from "../buttons";
25
+ import { DashboardBar } from "../Dashboard/DashboardBar";
17
26
  import { Loading } from "../Loading";
18
27
  import { TILE_MAX_HEIGHT } from "../RenderedResult/resultSizing";
19
28
  import { useServer } from "../ServerProvider";
@@ -22,7 +31,7 @@ import { DashboardBuilder } from "./DashboardBuilder";
22
31
  import type { DashboardDocument } from "./document";
23
32
  import { previewGivens, previewTileQuery } from "./preview";
24
33
  import { readDashboardDocument, readFailed } from "./readDocument";
25
- import { spliceDashboardDocument, spliceFailed } from "./spliceDocument";
34
+ import { sha256Hex } from "../../utils/sha256";
26
35
 
27
36
  /**
28
37
  * The builder, opened on a package dashboard, with everything a host has to
@@ -30,29 +39,39 @@ import { spliceDashboardDocument, spliceFailed } from "./spliceDocument";
30
39
  * control row and live tiles that follow the document, a catalog for the
31
40
  * filter window's field search, and saving.
32
41
  *
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.
42
+ * SAVING goes wherever the record is. A {@link Workspace} the host marks
43
+ * `authoritative` IS the record, so the editor opens that copy and writes back
44
+ * to it, and the package file is a deploy of it. Otherwise the record is the
45
+ * package: the editor writes there on a server that takes writes, and
46
+ * otherwise keeps a copy beside it in the host's {@link DocumentStorage} — the
47
+ * Console's default is this browser, where the copy is offered back on the
48
+ * next visit. A host with neither still gets the editor, without Save.
39
49
  *
40
50
  * What that costs is stated in the toolbar: a control added here is live in the
41
51
  * editor (its value is written into each tile's query) but reaches the package
42
- * only when the exported file does.
52
+ * only when the file is saved into it.
43
53
  */
44
54
  export interface DashboardEditorProps {
45
55
  environmentName: string;
46
56
  packageName: string;
47
57
  /** The dashboard's slug: `overview`, not `dashboards/overview.malloy`. */
48
58
  dashboardName: string;
49
- /** Leave the editor: the host's "Done". Absent, no Done button. */
59
+ /** Leave the editor: the host's "Done editing". Absent, no such button. */
50
60
  onExit?: () => void;
51
61
  /**
52
- * What the editor does — opened, saved, exported, refused — for the host
53
- * to log or count; see `DashboardEvent`.
62
+ * What the editor does — opened, saved, refused — for the host to log or
63
+ * count; see `DashboardEvent`.
54
64
  */
55
65
  onEvent?: DashboardEventHandler;
66
+ /**
67
+ * Whether there are edits the record does not have, on every change and
68
+ * whenever the editor opens a document.
69
+ *
70
+ * For a host that owns the way out: a route change, a tab close, its own
71
+ * "are you sure". The editor will not discard unsaved work on its own, so
72
+ * without this a host cannot tell whether leaving costs anything.
73
+ */
74
+ onDirtyChange?: (dirty: boolean) => void;
56
75
  }
57
76
 
58
77
  /** The Console's key for a dashboard's copy; see the storage seam's locator rule. */
@@ -73,14 +92,18 @@ export function DashboardEditor({
73
92
  dashboardName,
74
93
  onExit,
75
94
  onEvent,
95
+ onDirtyChange,
76
96
  }: DashboardEditorProps) {
77
- const { apiClients } = useServer();
97
+ const { apiClients, mutable } = useServer();
98
+ const queryClient = useQueryClient();
78
99
  // When the editor was asked for — or the reader chose what to open — so
79
100
  // "opened" can say how long it took. Read through refs by the open effect,
80
101
  // so a host's handler changing identity does not re-open the document.
81
102
  const startedAt = useRef(now());
82
103
  const onEventRef = useRef(onEvent);
83
104
  onEventRef.current = onEvent;
105
+ const onDirtyChangeRef = useRef(onDirtyChange);
106
+ onDirtyChangeRef.current = onDirtyChange;
84
107
  const storage = useOptionalDocumentStorage()?.documentStorage;
85
108
  const modelPath = `dashboards/${dashboardName}.malloy`;
86
109
 
@@ -99,57 +122,157 @@ export function DashboardEditor({
99
122
  modelQuery.data?.data as { sourceText?: string } | undefined
100
123
  )?.sourceText;
101
124
 
102
- // The host's copy, if one was saved earlier: offered, never assumed.
103
- const [workspace, setWorkspace] = useState<string | undefined>(undefined);
125
+ // The host's copy, if one was saved earlier.
126
+ const [workspace, setWorkspace] = useState<Workspace | undefined>(undefined);
104
127
  const [draft, setDraft] = useState<string | undefined>(undefined);
105
128
  const [draftChecked, setDraftChecked] = useState(storage === undefined);
106
- // Whether a draft was there when the editor opened: only that one is
129
+ // Whether a copy was there when the editor opened: only that one is
107
130
  // offered. A copy this session saves is not "edits from an earlier visit".
108
131
  const [offered, setOffered] = useState(false);
132
+ // A read the backend could not answer, which is not the same as no
133
+ // document. Held rather than swallowed, because "there is nothing saved"
134
+ // is what makes overwriting the record look safe.
135
+ const [readFailure, setReadFailure] = useState<string | undefined>(
136
+ undefined,
137
+ );
109
138
  useEffect(() => {
110
139
  if (!storage) return;
111
140
  let stale = false;
141
+ setReadFailure(undefined);
112
142
  (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);
143
+ try {
144
+ // Every workspace, not only the writeable ones: a reader who
145
+ // cannot write to the record still has to be shown the record.
146
+ // Asking for writeable only would hide it and fall back to the
147
+ // package, which on a server that takes writes means publishing a
148
+ // deploy of the record over the record.
149
+ const all = await storage.listWorkspaces(false);
150
+ // The record when one declares itself, and otherwise the first
151
+ // writeable one, which is what the editor has always taken.
152
+ const chosen =
153
+ all.find((candidate) => candidate.authoritative) ??
154
+ all.find((candidate) => candidate.writeable);
155
+ if (stale) return;
156
+ setWorkspace(chosen);
157
+ if (chosen !== undefined) {
158
+ const text = await storage
159
+ .getDocument(
160
+ dashboardLocator(
161
+ chosen.name,
162
+ environmentName,
163
+ packageName,
164
+ modelPath,
165
+ ),
166
+ )
167
+ // Absence is the ordinary first visit, not a failure.
168
+ .catch((error: unknown) => {
169
+ if (isDocumentNotFound(error)) return undefined;
170
+ throw error;
171
+ });
172
+ if (stale) return;
173
+ setDraft(text);
174
+ setOffered(text !== undefined);
175
+ }
176
+ } catch (error) {
177
+ if (stale) return;
178
+ setReadFailure(storageErrorMessage(error));
130
179
  }
180
+ if (!stale) setDraftChecked(true);
131
181
  })();
132
182
  return () => {
133
183
  stale = true;
134
184
  };
135
185
  }, [storage, environmentName, packageName, modelPath]);
136
186
 
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.
187
+ // The host's copy is the record: the editor opens it, writes back to it,
188
+ // and never offers to "resume" it, because a record is not a pending edit.
189
+ const authoritative = workspace?.authoritative === true;
190
+ // The package file is a deploy of the record, so opening it when the record
191
+ // itself could not be read would put a reader on the wrong document.
192
+ const blockedOnRecord = authoritative && readFailure !== undefined;
193
+
194
+ // What the editor opens: the record when the host keeps one, the copy when
195
+ // the reader chose to resume it, the package file otherwise. `generation`
196
+ // remounts the builder for a fresh history when that choice changes.
140
197
  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";
198
+ const fromDraft = authoritative
199
+ ? draft !== undefined
200
+ : resume === true && draft !== undefined;
145
201
  const [opened, setOpened] = useState<
146
202
  | { source: string; document: DashboardDocument; generation: number }
147
203
  | undefined
148
204
  >(undefined);
149
205
  const [openError, setOpenError] = useState<string | undefined>(undefined);
206
+ // The package's hash after this editor's last write, as the server computed
207
+ // it: the base the next save is spliced against.
208
+ const savedHashRef = useRef<string | undefined>(undefined);
209
+ // The package file as it stood when the editor last opened a document. The
210
+ // base a save is spliced against is the package's, which is NOT the text
211
+ // the builder holds: a resumed copy was opened from the store, and a
212
+ // version held back while the reader keeps editing has moved the fetch
213
+ // past the file the reader is answering for.
214
+ const packageBaseRef = useRef<string | undefined>(undefined);
215
+ // What this editor last wrote into the package, and the fetch it was
216
+ // written on top of. The write is in the file before the fetch behind
217
+ // `packageText` catches up, so until a fetch actually lands `packageText`
218
+ // is the text the save replaced rather than a version to open. Tied to the
219
+ // fetch and not to the text, so the NEXT fetch speaks for the file whether
220
+ // it carries this editor's write or someone else's.
221
+ const [wrote, setWrote] = useState<
222
+ { text: string; onFetch: number } | undefined
223
+ >(undefined);
224
+ const fetchedAt = modelQuery.dataUpdatedAt;
225
+ const fetchedAtRef = useRef(fetchedAt);
226
+ fetchedAtRef.current = fetchedAt;
227
+ const packageNow =
228
+ wrote !== undefined && wrote.onFetch === fetchedAt
229
+ ? wrote.text
230
+ : packageText;
231
+ const packageNowRef = useRef(packageNow);
232
+ packageNowRef.current = packageNow;
233
+ const latest = fromDraft ? draft : packageNow;
234
+
235
+ // Whether the builder holds edits the record does not have, and the version
236
+ // being held back because of them.
237
+ const [dirty, setDirty] = useState(false);
238
+ const [accepted, setAccepted] = useState<string | undefined>(undefined);
239
+ // The text on this channel the editor has already reckoned with: what it
240
+ // opened, and what it wrote. Compared against the CHANNEL rather than
241
+ // against the builder, because the two diverge legitimately — a copy saved
242
+ // beside the package leaves the builder ahead of a package that has not
243
+ // moved, and reading that as an incoming version would offer a reader
244
+ // their own work back forever.
245
+ const [seen, setSeen] = useState<string | undefined>(undefined);
246
+ const incoming = latest !== undefined && latest !== seen;
247
+ // What the builder is on. A save does not remount it, so this follows the
248
+ // save rather than the text the builder was opened with.
249
+ const current = opened?.source;
250
+ const holding =
251
+ incoming && dirty && current !== undefined && latest !== accepted;
252
+ const opening = holding ? current : incoming ? latest : (current ?? latest);
253
+ const held = holding ? latest : undefined;
254
+
255
+ // Read by the open effect so it keeps its single dependency: the guard must
256
+ // not re-run the effect when what it compares against changes.
257
+ const openedSourceRef = useRef(current);
258
+ openedSourceRef.current = current;
259
+ const latestRef = useRef(latest);
260
+ latestRef.current = latest;
261
+ const fromRef = useRef<"package" | "draft" | "record">("package");
262
+ fromRef.current = fromDraft
263
+ ? authoritative
264
+ ? "record"
265
+ : "draft"
266
+ : "package";
150
267
  useEffect(() => {
151
- if (opening === undefined) return;
268
+ // Not until the storage answer is in. Opening on the package file while
269
+ // the editor still has no idea whether the host keeps the record would
270
+ // open the wrong document, and report an open of it.
271
+ if (opening === undefined || !draftChecked || blockedOnRecord) return;
272
+ if (opening === openedSourceRef.current) return;
152
273
  let stale = false;
274
+ const packageAtOpen = packageNowRef.current;
275
+ const latestAtOpen = latestRef.current;
153
276
  void readDashboardDocument(opening).then((result) => {
154
277
  if (stale) return;
155
278
  if (readFailed(result)) {
@@ -161,6 +284,14 @@ export function DashboardEditor({
161
284
  return;
162
285
  }
163
286
  setOpenError(undefined);
287
+ // A different document is open, so what this editor wrote before is
288
+ // no longer the base anything is spliced against; the package file
289
+ // the reader is now answering for is the one current at this open.
290
+ savedHashRef.current = undefined;
291
+ packageBaseRef.current = packageAtOpen;
292
+ setWrote(undefined);
293
+ setAccepted(undefined);
294
+ setSeen(latestAtOpen);
164
295
  setOpened((previous) => ({
165
296
  source: opening,
166
297
  document: result.document,
@@ -176,33 +307,184 @@ export function DashboardEditor({
176
307
  return () => {
177
308
  stale = true;
178
309
  };
179
- }, [opening]);
310
+ }, [opening, draftChecked, blockedOnRecord]);
180
311
 
181
- const save = useCallback(
312
+ const locator =
313
+ workspace === undefined
314
+ ? undefined
315
+ : dashboardLocator(
316
+ workspace.name,
317
+ environmentName,
318
+ packageName,
319
+ modelPath,
320
+ );
321
+ // Into the host's store: the record when the host says so, and otherwise a
322
+ // copy kept beside the package.
323
+ const saveToStorage = useCallback(
182
324
  async (source: string) => {
183
- if (!storage || workspace === undefined)
325
+ if (!storage || !locator)
184
326
  throw new Error(
185
327
  "This host keeps no documents, so there is nowhere to save.",
186
328
  );
187
- await storage.saveDocument(
188
- dashboardLocator(
189
- workspace,
329
+ await storage.saveDocument(locator, source);
330
+ // The builder keeps its history and its text; what it holds is now
331
+ // this, not the text it was opened with.
332
+ setOpened((previous) => previous && { ...previous, source });
333
+ setDraft(source);
334
+ // Whenever the copy IS the channel — the record, or a copy the reader
335
+ // resumed — the write moved that channel, and its own text is not an
336
+ // incoming version. A copy written while the package is what is open
337
+ // leaves the package where it was, so nothing there has moved.
338
+ if (authoritative || resume === true) setSeen(source);
339
+ // Saving without choosing is choosing the package file.
340
+ if (!authoritative) setResume((chosen) => chosen ?? false);
341
+ },
342
+ [storage, locator, authoritative, resume],
343
+ );
344
+ // A supersede that did not happen, left where a reader can see it: the copy
345
+ // is still there and will be offered again on the next visit.
346
+ const [supersedeFailure, setSupersedeFailure] = useState<string | undefined>(
347
+ undefined,
348
+ );
349
+ // Into the package itself, when the server takes writes: compile-checked,
350
+ // written atomically and reloaded there, refused if the file changed since
351
+ // it was opened. A copy of the same file kept beside it is superseded by it.
352
+ const saveToPackage = useCallback(
353
+ async (source: string) => {
354
+ // The hash of the package file this editor opened against, never of
355
+ // the latest fetch. A version held back while the reader keeps
356
+ // editing moves the fetch past that file, and a hash taken from it
357
+ // would match, be accepted, and overwrite the change the reader was
358
+ // just told about.
359
+ const base = packageBaseRef.current;
360
+ const expectedHash =
361
+ savedHashRef.current ??
362
+ (base === undefined ? undefined : await sha256Hex(base));
363
+ if (expectedHash === undefined)
364
+ throw new Error("The package file is still loading; try again.");
365
+ let result;
366
+ try {
367
+ result = await apiClients.models.updateModelSource(
190
368
  environmentName,
191
369
  packageName,
192
370
  modelPath,
193
- ),
194
- source,
371
+ { source, expectedHash },
372
+ );
373
+ } catch (error) {
374
+ // A refused write usually means the file moved. Fetch it, so the
375
+ // reader is offered that version rather than left re-saving
376
+ // against a base the server will go on rejecting.
377
+ void queryClient.invalidateQueries({
378
+ queryKey: [
379
+ "dashboard-editor-model",
380
+ environmentName,
381
+ packageName,
382
+ modelPath,
383
+ ],
384
+ });
385
+ throw new Error(apiErrorMessage(error));
386
+ }
387
+ setOpened((previous) => previous && { ...previous, source });
388
+ setWrote({ text: source, onFetch: fetchedAtRef.current });
389
+ setSeen(source);
390
+ savedHashRef.current = result.data.contentHash;
391
+ setSupersedeFailure(undefined);
392
+ if (storage && locator) {
393
+ try {
394
+ await storage.deleteDocument(locator);
395
+ setDraft(undefined);
396
+ setOffered(false);
397
+ } catch (error) {
398
+ // Only absence means the copy is gone. Any other rejection
399
+ // leaves it there, so the state must keep saying so.
400
+ if (isDocumentNotFound(error)) {
401
+ setDraft(undefined);
402
+ setOffered(false);
403
+ } else setSupersedeFailure(storageErrorMessage(error));
404
+ }
405
+ }
406
+ // The package is what is open now, even if the copy beside it
407
+ // survived the supersede: reading the channel off a stale copy would
408
+ // put the builder back on the text this save replaced.
409
+ setResume(false);
410
+ // The package changed: the file, the manifest the live view reads,
411
+ // the package's dashboards list, and the dashboard the reader sees.
412
+ await queryClient.invalidateQueries({
413
+ queryKey: [
414
+ "dashboard-editor-model",
415
+ environmentName,
416
+ packageName,
417
+ modelPath,
418
+ ],
419
+ });
420
+ for (const key of [
421
+ "dashboard-editor-manifest",
422
+ "dashboards",
423
+ "dashboard",
424
+ ])
425
+ void queryClient.invalidateQueries({ queryKey: [key] });
426
+ },
427
+ [
428
+ apiClients,
429
+ environmentName,
430
+ packageName,
431
+ modelPath,
432
+ storage,
433
+ locator,
434
+ queryClient,
435
+ ],
436
+ );
437
+ // `authoritative` wins outright rather than breaking a tie: a host whose
438
+ // store is the record may well sit on a server that reports itself
439
+ // writable, and writing the package there would edit a deploy of the
440
+ // record instead of the record.
441
+ const savesTo = authoritative ? "host" : mutable ? "package" : "browser";
442
+ const canWriteWorkspace = workspace?.writeable === true;
443
+ const writer = authoritative
444
+ ? storage && locator && canWriteWorkspace
445
+ ? saveToStorage
446
+ : undefined
447
+ : mutable
448
+ ? saveToPackage
449
+ : storage && locator && canWriteWorkspace
450
+ ? saveToStorage
451
+ : undefined;
452
+ // A copy that could not be read is not a copy that is not there. Saving on
453
+ // that belief is what rewinds the record, so Save is off until a reader can
454
+ // be told what actually happened.
455
+ const save = readFailure === undefined ? writer : undefined;
456
+ const workspaceName = workspace?.name;
457
+ const reportEvent = useCallback(
458
+ (event: DashboardEvent) => {
459
+ // Only where a workspace actually took the write: a save into the
460
+ // package was not taken by one, and naming it there would say the
461
+ // record moved somewhere it did not.
462
+ onEventRef.current?.(
463
+ event.type === "dashboard.saved" &&
464
+ event.where !== "package" &&
465
+ workspaceName !== undefined
466
+ ? { ...event, workspace: workspaceName }
467
+ : event,
195
468
  );
196
- setDraft(source);
197
- // Saving without choosing is choosing the package file.
198
- setResume((chosen) => chosen ?? false);
199
469
  },
200
- [storage, workspace, environmentName, packageName, modelPath],
470
+ [workspaceName],
201
471
  );
472
+ // Stable: the builder fires this from an effect that depends on it.
473
+ const reportDirty = useCallback((value: boolean) => {
474
+ setDirty(value);
475
+ onDirtyChangeRef.current?.(value);
476
+ }, []);
477
+ // An explicit choice is a choice about the very text that would otherwise
478
+ // be held back, so it is never held.
202
479
  const choose = (resumeDraft: boolean) => {
203
480
  startedAt.current = now();
481
+ setAccepted(resumeDraft ? draft : packageNow);
204
482
  setResume(resumeDraft);
205
483
  };
484
+ const acceptHeld = () => {
485
+ startedAt.current = now();
486
+ setAccepted(held);
487
+ };
206
488
 
207
489
  if (modelQuery.isError)
208
490
  return (
@@ -212,7 +494,24 @@ export function DashboardEditor({
212
494
  />
213
495
  );
214
496
  if (!packageText || !draftChecked)
215
- return <Loading text="Opening the dashboard…" />;
497
+ // The bar first, so the page it is opening into is already the right
498
+ // shape: the reader's view had a bar in this spot, and a spinner where
499
+ // the bar was made the switch look like a page reload.
500
+ return (
501
+ <Stack sx={{ gap: 2 }}>
502
+ <DashboardBar />
503
+ <Loading text="Opening the dashboard…" />
504
+ </Stack>
505
+ );
506
+ // Where the host's copy IS the document, a copy that could not be read
507
+ // leaves nothing safe to edit: the package file is a deploy of the record,
508
+ // so opening it and arming Save would publish it over the record.
509
+ if (blockedOnRecord)
510
+ return (
511
+ <Alert severity="error" sx={{ m: 2 }}>
512
+ This dashboard cannot be opened: {readFailure}
513
+ </Alert>
514
+ );
216
515
  if (openError)
217
516
  return (
218
517
  <Alert severity="error" sx={{ m: 2 }}>
@@ -223,7 +522,7 @@ export function DashboardEditor({
223
522
  const draftDiffers = draft !== undefined && draft !== packageText;
224
523
  return (
225
524
  <Stack sx={{ gap: 2 }}>
226
- {offered && draftDiffers && resume === undefined && (
525
+ {!authoritative && offered && draftDiffers && resume === undefined && (
227
526
  <Alert
228
527
  severity="info"
229
528
  action={
@@ -241,6 +540,29 @@ export function DashboardEditor({
241
540
  package does not have.
242
541
  </Alert>
243
542
  )}
543
+ {held !== undefined && (
544
+ <Alert
545
+ severity="warning"
546
+ action={
547
+ <Button size="small" onClick={acceptHeld}>
548
+ Load it
549
+ </Button>
550
+ }
551
+ >
552
+ {savesTo === "package"
553
+ ? "This dashboard changed since you opened it. Your edits are still here; loading the new version replaces them, and until you do, saving is refused."
554
+ : savesTo === "host"
555
+ ? "This dashboard changed since you opened it. Your edits are still here; loading the new version replaces them, and saving keeps yours and writes over it."
556
+ : "The package's copy of this dashboard changed since you opened it. Your edits are still here; loading the new version replaces them."}
557
+ </Alert>
558
+ )}
559
+ {supersedeFailure !== undefined && (
560
+ <Alert severity="warning">
561
+ The file was saved into the package, but the copy kept beside it
562
+ could not be cleared, so it will be offered again:{" "}
563
+ {supersedeFailure}
564
+ </Alert>
565
+ )}
244
566
  {opened && (
245
567
  <Surface
246
568
  key={opened.generation}
@@ -249,26 +571,60 @@ export function DashboardEditor({
249
571
  modelPath={modelPath}
250
572
  slug={dashboardName}
251
573
  opened={opened}
252
- onSave={storage && workspace !== undefined ? save : undefined}
253
- {...(onEvent ? { onEvent } : {})}
574
+ onSave={save}
575
+ onDirtyChange={reportDirty}
576
+ savesTo={savesTo}
577
+ {...(onEvent ? { onEvent: reportEvent } : {})}
254
578
  toolbar={
255
579
  onExit && (
256
- <Button size="small" onClick={onExit}>
257
- Done
258
- </Button>
580
+ <SecondaryButton
581
+ label="Done editing"
582
+ icon={<CheckIcon />}
583
+ onClick={onExit}
584
+ />
259
585
  )
260
586
  }
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
- }
587
+ note={caption({
588
+ authoritative,
589
+ mutable,
590
+ ...(workspace ? { workspace } : {}),
591
+ ...(readFailure !== undefined ? { readFailure } : {}),
592
+ })}
266
593
  />
267
594
  )}
268
595
  </Stack>
269
596
  );
270
597
  }
271
598
 
599
+ /**
600
+ * What the toolbar says about where Save goes, in the backend's own words
601
+ * wherever it has any: a workspace carries a `description` precisely so the
602
+ * editor does not have to guess, and "this browser" is one host's answer
603
+ * rather than the interface's.
604
+ */
605
+ function caption({
606
+ authoritative,
607
+ mutable,
608
+ workspace,
609
+ readFailure,
610
+ }: {
611
+ authoritative: boolean;
612
+ mutable: boolean;
613
+ workspace?: Workspace;
614
+ readFailure?: string;
615
+ }): string {
616
+ if (readFailure !== undefined)
617
+ return `The saved copy could not be read, so Save is off: ${readFailure}`;
618
+ if (authoritative && workspace)
619
+ return workspace.writeable
620
+ ? workspace.description
621
+ : `${workspace.description}: you cannot save into it.`;
622
+ if (mutable) return "Save writes the file into the package.";
623
+ if (workspace)
624
+ return `${workspace.description}: this server does not take writes.`;
625
+ return "This server does not take writes.";
626
+ }
627
+
272
628
  /**
273
629
  * The builder under a real control row, with the controls driving the tiles,
274
630
  * both following the LIVE document rather than the saved file.
@@ -287,7 +643,9 @@ function Surface({
287
643
  slug,
288
644
  opened,
289
645
  onSave,
646
+ onDirtyChange,
290
647
  onEvent,
648
+ savesTo,
291
649
  toolbar,
292
650
  note,
293
651
  }: {
@@ -297,7 +655,9 @@ function Surface({
297
655
  slug: string;
298
656
  opened: { source: string; document: DashboardDocument; generation: number };
299
657
  onSave?: (source: string) => Promise<void>;
658
+ onDirtyChange: (dirty: boolean) => void;
300
659
  onEvent?: DashboardEventHandler;
660
+ savesTo: "package" | "browser" | "host";
301
661
  toolbar: React.ReactNode;
302
662
  note: string;
303
663
  }) {
@@ -371,22 +731,6 @@ function Surface({
371
731
 
372
732
  const [doc, setDoc] = useState(opened.document);
373
733
  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
734
  const modelSpecs = useMemo(() => manifest?.givens ?? [], [manifest]);
391
735
  const runnable = useMemo(
392
736
  () =>
@@ -463,25 +807,16 @@ function Surface({
463
807
  : {}),
464
808
  }))}
465
809
  onChange={setDoc}
810
+ onDirtyChange={onDirtyChange}
466
811
  {...(catalog ? { catalog } : {})}
467
812
  dashboards={otherDashboards}
468
813
  {...(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
- }
814
+ toolbar={toolbar}
481
815
  controls={
482
816
  isSuccess ? <GivensPanel {...panel} layout="bar" /> : undefined
483
817
  }
484
818
  {...(onSave ? { onSave } : {})}
819
+ savesTo={savesTo}
485
820
  />
486
821
  <Box sx={{ px: 0.5 }}>
487
822
  <Typography variant="caption" sx={{ opacity: 0.7 }}>
@@ -491,3 +826,16 @@ function Surface({
491
826
  </Stack>
492
827
  );
493
828
  }
829
+
830
+ /** What a storage backend said went wrong, for a reader who has to act on it. */
831
+ function storageErrorMessage(error: unknown): string {
832
+ return error instanceof Error ? error.message : String(error);
833
+ }
834
+
835
+ /** The server's own reason for a refused write, when it gave one. */
836
+ function apiErrorMessage(error: unknown): string {
837
+ const data = (error as { response?: { data?: { message?: string } } })
838
+ .response?.data;
839
+ if (data?.message) return data.message;
840
+ return error instanceof Error ? error.message : String(error);
841
+ }