@malloy-publisher/sdk 0.4.0 → 0.5.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 (72) hide show
  1. package/README.md +19 -0
  2. package/dist/{DocumentStorageProvider-CyOJ0hqf.es.js → DocumentStorage-B04sZ5Ie.es.js} +2307 -2334
  3. package/dist/{DocumentStorageProvider-DGPQEd_l.cjs.js → DocumentStorage-B_MMJ0Ot.cjs.js} +20 -20
  4. package/dist/{RenderedResult-BnPzJ9Jf.es.js → RenderedResult-BB7eokcf.es.js} +100 -80
  5. package/dist/RenderedResult-DVuGhatg.cjs.js +135 -0
  6. package/dist/ServerProvider-D-jjzfE5.cjs.js +1 -0
  7. package/dist/{ServerProvider-BWOEKg0O.es.js → ServerProvider-Do-GBvpn.es.js} +492 -481
  8. package/dist/builder/index.cjs.js +57 -52
  9. package/dist/builder/index.es.js +4421 -3738
  10. package/dist/client/api.d.ts +14 -1
  11. package/dist/client/index.cjs.js +1 -1
  12. package/dist/client/index.es.js +1 -1
  13. package/dist/components/Dashboard/TileCard.d.ts +7 -3
  14. package/dist/components/Dashboard/telemetry.d.ts +20 -8
  15. package/dist/components/DashboardBuilder/DashboardBuilder.d.ts +16 -4
  16. package/dist/components/DashboardBuilder/DashboardEditor.d.ts +31 -8
  17. package/dist/components/DashboardBuilder/controls.d.ts +8 -6
  18. package/dist/components/DashboardBuilder/document.d.ts +19 -5
  19. package/dist/components/DashboardBuilder/malloyText.d.ts +0 -30
  20. package/dist/components/DashboardBuilder/malloyTree.d.ts +232 -0
  21. package/dist/components/DashboardBuilder/preview.d.ts +17 -0
  22. package/dist/components/DashboardBuilder/readDocument.d.ts +23 -28
  23. package/dist/components/DashboardBuilder/spliceDocument.d.ts +12 -0
  24. package/dist/components/DocumentStorage/DocumentStorage.d.ts +69 -5
  25. package/dist/components/DocumentStorage/index.d.ts +1 -0
  26. package/dist/index.cjs.js +9 -9
  27. package/dist/index.es.js +508 -506
  28. package/dist/theme/resolveTheme.d.ts +1 -1
  29. package/dist/theme/types.d.ts +12 -2
  30. package/package.json +1 -1
  31. package/src/components/Dashboard/TileCard.tsx +8 -4
  32. package/src/components/Dashboard/telemetry.ts +20 -8
  33. package/src/components/DashboardBuilder/BuilderToolbar.tsx +4 -5
  34. package/src/components/DashboardBuilder/DashboardBuilder.tsx +21 -3
  35. package/src/components/DashboardBuilder/DashboardEditor.authoritative.spec.tsx +706 -0
  36. package/src/components/DashboardBuilder/DashboardEditor.resourceUri.spec.tsx +356 -0
  37. package/src/components/DashboardBuilder/DashboardEditor.tsx +468 -103
  38. package/src/components/DashboardBuilder/FilterDialog.tsx +19 -6
  39. package/src/components/DashboardBuilder/TileFrame.tsx +11 -2
  40. package/src/components/DashboardBuilder/TileMenu.tsx +6 -0
  41. package/src/components/DashboardBuilder/__test__/inventory.ts +367 -0
  42. package/src/components/DashboardBuilder/controls.spec.ts +53 -3
  43. package/src/components/DashboardBuilder/controls.ts +9 -7
  44. package/src/components/DashboardBuilder/document.ts +17 -5
  45. package/src/components/DashboardBuilder/invariants.spec.ts +297 -0
  46. package/src/components/DashboardBuilder/malloyText.spec.ts +27 -66
  47. package/src/components/DashboardBuilder/malloyText.ts +4 -109
  48. package/src/components/DashboardBuilder/malloyTree.spec.ts +362 -0
  49. package/src/components/DashboardBuilder/malloyTree.ts +954 -0
  50. package/src/components/DashboardBuilder/preview.spec.ts +18 -0
  51. package/src/components/DashboardBuilder/preview.ts +24 -6
  52. package/src/components/DashboardBuilder/readDocument.spec.ts +312 -21
  53. package/src/components/DashboardBuilder/readDocument.ts +144 -165
  54. package/src/components/DashboardBuilder/scannerShapes.spec.ts +550 -0
  55. package/src/components/DashboardBuilder/spliceDocument.spec.ts +955 -21
  56. package/src/components/DashboardBuilder/spliceDocument.ts +509 -119
  57. package/src/components/DashboardBuilder/statementExtent.spec.ts +606 -0
  58. package/src/components/DocumentStorage/BrowserDocumentStorage.ts +7 -6
  59. package/src/components/DocumentStorage/DocumentStorage.ts +78 -5
  60. package/src/components/DocumentStorage/index.ts +1 -0
  61. package/src/components/Package/Package.tsx +12 -7
  62. package/src/components/RenderedResult/RenderedResult.tsx +21 -1
  63. package/src/components/given/GivensPanel.tsx +15 -3
  64. package/src/theme/buildTableCssVars.spec.ts +3 -0
  65. package/src/theme/buildTableCssVars.ts +6 -0
  66. package/src/theme/defaults.ts +16 -12
  67. package/src/theme/resolveTheme.spec.ts +14 -7
  68. package/src/theme/resolveTheme.ts +14 -8
  69. package/src/theme/types.ts +12 -2
  70. package/tsconfig.spec.json +5 -1
  71. package/dist/RenderedResult-Dp22kZsQ.cjs.js +0 -115
  72. package/dist/ServerProvider-Cc489A3f.cjs.js +0 -1
@@ -8,11 +8,18 @@ import { useCallback, useEffect, useMemo, useRef, useState } from "react";
8
8
  import { useQueryWithApiError } from "../../hooks/useQueryWithApiError";
9
9
  import { ApiErrorDisplay } from "../ApiErrorDisplay";
10
10
  import { DashboardTile, tileTitle } from "../Dashboard/DashboardTile";
11
- import { now, type DashboardEventHandler } from "../Dashboard/telemetry";
11
+ import {
12
+ now,
13
+ type DashboardEvent,
14
+ type DashboardEventHandler,
15
+ } from "../Dashboard/telemetry";
12
16
  import { useDocumentControls } from "../../hooks/useDocumentControls";
17
+ import { parseResourceUri } from "../../utils/formatting";
13
18
  import {
19
+ isDocumentNotFound,
14
20
  useOptionalDocumentStorage,
15
21
  type DocumentLocator,
22
+ type Workspace,
16
23
  } from "../DocumentStorage";
17
24
  import { GivensPanel } from "../given";
18
25
  import { SecondaryButton } from "../buttons";
@@ -33,20 +40,37 @@ import { sha256Hex } from "../../utils/sha256";
33
40
  * control row and live tiles that follow the document, a catalog for the
34
41
  * filter window's field search, and saving.
35
42
  *
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.
43
+ * SAVING goes wherever the record is. A {@link Workspace} the host marks
44
+ * `authoritative` IS the record, so the editor opens that copy and writes back
45
+ * to it, and the package file is a deploy of it. Otherwise the record is the
46
+ * package: the editor writes there on a server that takes writes, and
47
+ * otherwise keeps a copy beside it in the host's {@link DocumentStorage} — the
48
+ * Console's default is this browser, where the copy is offered back on the
49
+ * next visit. A host with neither still gets the editor, without Save.
40
50
  *
41
51
  * What that costs is stated in the toolbar: a control added here is live in the
42
52
  * editor (its value is written into each tile's query) but reaches the package
43
53
  * only when the file is saved into it.
44
54
  */
45
- export interface DashboardEditorProps {
46
- environmentName: string;
47
- packageName: string;
48
- /** The dashboard's slug: `overview`, not `dashboards/overview.malloy`. */
49
- dashboardName: string;
55
+ export type DashboardEditorProps = (
56
+ | {
57
+ /** `publisher://environments/{env}/packages/{pkg}`, optionally `?versionId=`. */
58
+ resourceUri: string;
59
+ /** The dashboard's slug, as listed by the dashboards endpoint. */
60
+ dashboard: string;
61
+ }
62
+ | {
63
+ /** @deprecated Pass `resourceUri` and `dashboard` instead. */
64
+ environmentName: string;
65
+ /** @deprecated Pass `resourceUri` and `dashboard` instead. */
66
+ packageName: string;
67
+ /**
68
+ * @deprecated Pass `resourceUri` and `dashboard` instead. The
69
+ * dashboard's slug: `overview`, not `dashboards/overview.malloy`.
70
+ */
71
+ dashboardName: string;
72
+ }
73
+ ) & {
50
74
  /** Leave the editor: the host's "Done editing". Absent, no such button. */
51
75
  onExit?: () => void;
52
76
  /**
@@ -54,7 +78,16 @@ export interface DashboardEditorProps {
54
78
  * count; see `DashboardEvent`.
55
79
  */
56
80
  onEvent?: DashboardEventHandler;
57
- }
81
+ /**
82
+ * Whether there are edits the record does not have, on every change and
83
+ * whenever the editor opens a document.
84
+ *
85
+ * For a host that owns the way out: a route change, a tab close, its own
86
+ * "are you sure". The editor will not discard unsaved work on its own, so
87
+ * without this a host cannot tell whether leaving costs anything.
88
+ */
89
+ onDirtyChange?: (dirty: boolean) => void;
90
+ };
58
91
 
59
92
  /** The Console's key for a dashboard's copy; see the storage seam's locator rule. */
60
93
  const dashboardLocator = (
@@ -68,13 +101,40 @@ const dashboardLocator = (
68
101
  path: `${environmentName}/${packageName}/${modelPath}`,
69
102
  });
70
103
 
71
- export function DashboardEditor({
72
- environmentName,
73
- packageName,
74
- dashboardName,
75
- onExit,
76
- onEvent,
77
- }: DashboardEditorProps) {
104
+ export function DashboardEditor(props: DashboardEditorProps) {
105
+ const { onExit, onEvent, onDirtyChange } = props;
106
+ // Resolved once, so the rest of the body reads these locals and never the
107
+ // union directly. Degraded, not thrown, on a bad URI: see `Dashboard`'s
108
+ // note on the same call — a throw in a render body takes the host's whole
109
+ // tree down, which is a white screen instead of a message. The deprecated
110
+ // form cannot be malformed the same way, so it always names both.
111
+ // `parseResourceUri` THROWS on a string that is not a `publisher://` URI at
112
+ // all, which a render body must not do; only its missing-name case returns.
113
+ const parsed = (() => {
114
+ if (!("resourceUri" in props)) return undefined;
115
+ try {
116
+ return parseResourceUri(props.resourceUri);
117
+ } catch {
118
+ return undefined;
119
+ }
120
+ })();
121
+ const environmentName =
122
+ "resourceUri" in props
123
+ ? (parsed?.environmentName ?? "")
124
+ : props.environmentName;
125
+ const packageName =
126
+ "resourceUri" in props ? (parsed?.packageName ?? "") : props.packageName;
127
+ const dashboardName =
128
+ "resourceUri" in props ? props.dashboard : props.dashboardName;
129
+ const versionId = parsed?.versionId;
130
+ // Keyed on the prop form, not on `parsed`: a URI that failed to parse at all
131
+ // also leaves `parsed` undefined, and reading that as "no URI to check" would
132
+ // skip the error display and run the editor against empty names.
133
+ const uriNamesBoth =
134
+ "resourceUri" in props
135
+ ? !!parsed?.environmentName && !!parsed?.packageName
136
+ : true;
137
+
78
138
  const { apiClients, mutable } = useServer();
79
139
  const queryClient = useQueryClient();
80
140
  // When the editor was asked for — or the reader chose what to open — so
@@ -83,6 +143,8 @@ export function DashboardEditor({
83
143
  const startedAt = useRef(now());
84
144
  const onEventRef = useRef(onEvent);
85
145
  onEventRef.current = onEvent;
146
+ const onDirtyChangeRef = useRef(onDirtyChange);
147
+ onDirtyChangeRef.current = onDirtyChange;
86
148
  const storage = useOptionalDocumentStorage()?.documentStorage;
87
149
  const modelPath = `dashboards/${dashboardName}.malloy`;
88
150
 
@@ -93,85 +155,172 @@ export function DashboardEditor({
93
155
  environmentName,
94
156
  packageName,
95
157
  modelPath,
158
+ versionId,
96
159
  ],
97
160
  queryFn: () =>
98
- apiClients.models.getModel(environmentName, packageName, modelPath),
161
+ apiClients.models.getModel(
162
+ environmentName,
163
+ packageName,
164
+ modelPath,
165
+ versionId,
166
+ ),
167
+ enabled: uriNamesBoth,
99
168
  });
100
169
  const packageText = (
101
170
  modelQuery.data?.data as { sourceText?: string } | undefined
102
171
  )?.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
172
 
120
- // The host's copy, if one was saved earlier: offered, never assumed.
121
- const [workspace, setWorkspace] = useState<string | undefined>(undefined);
173
+ // The host's copy, if one was saved earlier.
174
+ const [workspace, setWorkspace] = useState<Workspace | undefined>(undefined);
122
175
  const [draft, setDraft] = useState<string | undefined>(undefined);
123
176
  const [draftChecked, setDraftChecked] = useState(storage === undefined);
124
- // Whether a draft was there when the editor opened: only that one is
177
+ // Whether a copy was there when the editor opened: only that one is
125
178
  // offered. A copy this session saves is not "edits from an earlier visit".
126
179
  const [offered, setOffered] = useState(false);
180
+ // A read the backend could not answer, which is not the same as no
181
+ // document. Held rather than swallowed, because "there is nothing saved"
182
+ // is what makes overwriting the record look safe.
183
+ const [readFailure, setReadFailure] = useState<string | undefined>(
184
+ undefined,
185
+ );
127
186
  useEffect(() => {
128
187
  if (!storage) return;
129
188
  let stale = false;
189
+ setReadFailure(undefined);
130
190
  (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);
191
+ try {
192
+ // Every workspace, not only the writeable ones: a reader who
193
+ // cannot write to the record still has to be shown the record.
194
+ // Asking for writeable only would hide it and fall back to the
195
+ // package, which on a server that takes writes means publishing a
196
+ // deploy of the record over the record.
197
+ const all = await storage.listWorkspaces(false);
198
+ // The record when one declares itself, and otherwise the first
199
+ // writeable one, which is what the editor has always taken.
200
+ const chosen =
201
+ all.find((candidate) => candidate.authoritative) ??
202
+ all.find((candidate) => candidate.writeable);
203
+ if (stale) return;
204
+ setWorkspace(chosen);
205
+ if (chosen !== undefined) {
206
+ const text = await storage
207
+ .getDocument(
208
+ dashboardLocator(
209
+ chosen.name,
210
+ environmentName,
211
+ packageName,
212
+ modelPath,
213
+ ),
214
+ )
215
+ // Absence is the ordinary first visit, not a failure.
216
+ .catch((error: unknown) => {
217
+ if (isDocumentNotFound(error)) return undefined;
218
+ throw error;
219
+ });
220
+ if (stale) return;
221
+ setDraft(text);
222
+ setOffered(text !== undefined);
223
+ }
224
+ } catch (error) {
225
+ if (stale) return;
226
+ setReadFailure(storageErrorMessage(error));
148
227
  }
228
+ if (!stale) setDraftChecked(true);
149
229
  })();
150
230
  return () => {
151
231
  stale = true;
152
232
  };
153
233
  }, [storage, environmentName, packageName, modelPath]);
154
234
 
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.
235
+ // The host's copy is the record: the editor opens it, writes back to it,
236
+ // and never offers to "resume" it, because a record is not a pending edit.
237
+ const authoritative = workspace?.authoritative === true;
238
+ // The package file is a deploy of the record, so opening it when the record
239
+ // itself could not be read would put a reader on the wrong document.
240
+ const blockedOnRecord = authoritative && readFailure !== undefined;
241
+
242
+ // What the editor opens: the record when the host keeps one, the copy when
243
+ // the reader chose to resume it, the package file otherwise. `generation`
244
+ // remounts the builder for a fresh history when that choice changes.
158
245
  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";
246
+ const fromDraft = authoritative
247
+ ? draft !== undefined
248
+ : resume === true && draft !== undefined;
163
249
  const [opened, setOpened] = useState<
164
250
  | { source: string; document: DashboardDocument; generation: number }
165
251
  | undefined
166
252
  >(undefined);
167
253
  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);
254
+ // The package's hash after this editor's last write, as the server computed
255
+ // it: the base the next save is spliced against.
256
+ const savedHashRef = useRef<string | undefined>(undefined);
257
+ // The package file as it stood when the editor last opened a document. The
258
+ // base a save is spliced against is the package's, which is NOT the text
259
+ // the builder holds: a resumed copy was opened from the store, and a
260
+ // version held back while the reader keeps editing has moved the fetch
261
+ // past the file the reader is answering for.
262
+ const packageBaseRef = useRef<string | undefined>(undefined);
263
+ // What this editor last wrote into the package, and the fetch it was
264
+ // written on top of. The write is in the file before the fetch behind
265
+ // `packageText` catches up, so until a fetch actually lands `packageText`
266
+ // is the text the save replaced rather than a version to open. Tied to the
267
+ // fetch and not to the text, so the NEXT fetch speaks for the file whether
268
+ // it carries this editor's write or someone else's.
269
+ const [wrote, setWrote] = useState<
270
+ { text: string; onFetch: number } | undefined
271
+ >(undefined);
272
+ const fetchedAt = modelQuery.dataUpdatedAt;
273
+ const fetchedAtRef = useRef(fetchedAt);
274
+ fetchedAtRef.current = fetchedAt;
275
+ const packageNow =
276
+ wrote !== undefined && wrote.onFetch === fetchedAt
277
+ ? wrote.text
278
+ : packageText;
279
+ const packageNowRef = useRef(packageNow);
280
+ packageNowRef.current = packageNow;
281
+ const latest = fromDraft ? draft : packageNow;
282
+
283
+ // Whether the builder holds edits the record does not have, and the version
284
+ // being held back because of them.
285
+ const [dirty, setDirty] = useState(false);
286
+ const [accepted, setAccepted] = useState<string | undefined>(undefined);
287
+ // The text on this channel the editor has already reckoned with: what it
288
+ // opened, and what it wrote. Compared against the CHANNEL rather than
289
+ // against the builder, because the two diverge legitimately — a copy saved
290
+ // beside the package leaves the builder ahead of a package that has not
291
+ // moved, and reading that as an incoming version would offer a reader
292
+ // their own work back forever.
293
+ const [seen, setSeen] = useState<string | undefined>(undefined);
294
+ const incoming = latest !== undefined && latest !== seen;
295
+ // What the builder is on. A save does not remount it, so this follows the
296
+ // save rather than the text the builder was opened with.
297
+ const current = opened?.source;
298
+ const holding =
299
+ incoming && dirty && current !== undefined && latest !== accepted;
300
+ const opening = holding ? current : incoming ? latest : (current ?? latest);
301
+ const held = holding ? latest : undefined;
302
+
303
+ // Read by the open effect so it keeps its single dependency: the guard must
304
+ // not re-run the effect when what it compares against changes.
305
+ const openedSourceRef = useRef(current);
306
+ openedSourceRef.current = current;
307
+ const latestRef = useRef(latest);
308
+ latestRef.current = latest;
309
+ const fromRef = useRef<"package" | "draft" | "record">("package");
310
+ fromRef.current = fromDraft
311
+ ? authoritative
312
+ ? "record"
313
+ : "draft"
314
+ : "package";
172
315
  useEffect(() => {
173
- if (opening === undefined || opening === savedRef.current) return;
316
+ // Not until the storage answer is in. Opening on the package file while
317
+ // the editor still has no idea whether the host keeps the record would
318
+ // open the wrong document, and report an open of it.
319
+ if (opening === undefined || !draftChecked || blockedOnRecord) return;
320
+ if (opening === openedSourceRef.current) return;
174
321
  let stale = false;
322
+ const packageAtOpen = packageNowRef.current;
323
+ const latestAtOpen = latestRef.current;
175
324
  void readDashboardDocument(opening).then((result) => {
176
325
  if (stale) return;
177
326
  if (readFailed(result)) {
@@ -183,6 +332,14 @@ export function DashboardEditor({
183
332
  return;
184
333
  }
185
334
  setOpenError(undefined);
335
+ // A different document is open, so what this editor wrote before is
336
+ // no longer the base anything is spliced against; the package file
337
+ // the reader is now answering for is the one current at this open.
338
+ savedHashRef.current = undefined;
339
+ packageBaseRef.current = packageAtOpen;
340
+ setWrote(undefined);
341
+ setAccepted(undefined);
342
+ setSeen(latestAtOpen);
186
343
  setOpened((previous) => ({
187
344
  source: opening,
188
345
  document: result.document,
@@ -198,31 +355,60 @@ export function DashboardEditor({
198
355
  return () => {
199
356
  stale = true;
200
357
  };
201
- }, [opening]);
358
+ }, [opening, draftChecked, blockedOnRecord]);
202
359
 
203
360
  const locator =
204
361
  workspace === undefined
205
362
  ? undefined
206
- : dashboardLocator(workspace, environmentName, packageName, modelPath);
207
- const saveToBrowser = useCallback(
363
+ : dashboardLocator(
364
+ workspace.name,
365
+ environmentName,
366
+ packageName,
367
+ modelPath,
368
+ );
369
+ // Into the host's store: the record when the host says so, and otherwise a
370
+ // copy kept beside the package.
371
+ const saveToStorage = useCallback(
208
372
  async (source: string) => {
209
373
  if (!storage || !locator)
210
374
  throw new Error(
211
375
  "This host keeps no documents, so there is nowhere to save.",
212
376
  );
213
377
  await storage.saveDocument(locator, source);
378
+ // The builder keeps its history and its text; what it holds is now
379
+ // this, not the text it was opened with.
380
+ setOpened((previous) => previous && { ...previous, source });
214
381
  setDraft(source);
382
+ // Whenever the copy IS the channel — the record, or a copy the reader
383
+ // resumed — the write moved that channel, and its own text is not an
384
+ // incoming version. A copy written while the package is what is open
385
+ // leaves the package where it was, so nothing there has moved.
386
+ if (authoritative || resume === true) setSeen(source);
215
387
  // Saving without choosing is choosing the package file.
216
- setResume((chosen) => chosen ?? false);
388
+ if (!authoritative) setResume((chosen) => chosen ?? false);
217
389
  },
218
- [storage, locator],
390
+ [storage, locator, authoritative, resume],
391
+ );
392
+ // A supersede that did not happen, left where a reader can see it: the copy
393
+ // is still there and will be offered again on the next visit.
394
+ const [supersedeFailure, setSupersedeFailure] = useState<string | undefined>(
395
+ undefined,
219
396
  );
220
397
  // Into the package itself, when the server takes writes: compile-checked,
221
398
  // 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.
399
+ // it was opened. A copy of the same file kept beside it is superseded by it.
223
400
  const saveToPackage = useCallback(
224
401
  async (source: string) => {
225
- if (packageHash === undefined)
402
+ // The hash of the package file this editor opened against, never of
403
+ // the latest fetch. A version held back while the reader keeps
404
+ // editing moves the fetch past that file, and a hash taken from it
405
+ // would match, be accepted, and overwrite the change the reader was
406
+ // just told about.
407
+ const base = packageBaseRef.current;
408
+ const expectedHash =
409
+ savedHashRef.current ??
410
+ (base === undefined ? undefined : await sha256Hex(base));
411
+ if (expectedHash === undefined)
226
412
  throw new Error("The package file is still loading; try again.");
227
413
  let result;
228
414
  try {
@@ -230,19 +416,46 @@ export function DashboardEditor({
230
416
  environmentName,
231
417
  packageName,
232
418
  modelPath,
233
- { source, expectedHash: packageHash },
419
+ { source, expectedHash },
234
420
  );
235
421
  } catch (error) {
422
+ // A refused write usually means the file moved. Fetch it, so the
423
+ // reader is offered that version rather than left re-saving
424
+ // against a base the server will go on rejecting.
425
+ void queryClient.invalidateQueries({
426
+ queryKey: [
427
+ "dashboard-editor-model",
428
+ environmentName,
429
+ packageName,
430
+ modelPath,
431
+ versionId,
432
+ ],
433
+ });
236
434
  throw new Error(apiErrorMessage(error));
237
435
  }
238
- savedRef.current = source;
239
- setPackageHash(result.data.contentHash);
436
+ setOpened((previous) => previous && { ...previous, source });
437
+ setWrote({ text: source, onFetch: fetchedAtRef.current });
438
+ setSeen(source);
439
+ savedHashRef.current = result.data.contentHash;
440
+ setSupersedeFailure(undefined);
240
441
  if (storage && locator) {
241
- await storage.deleteDocument(locator).catch(() => undefined);
242
- setDraft(undefined);
243
- setOffered(false);
442
+ try {
443
+ await storage.deleteDocument(locator);
444
+ setDraft(undefined);
445
+ setOffered(false);
446
+ } catch (error) {
447
+ // Only absence means the copy is gone. Any other rejection
448
+ // leaves it there, so the state must keep saying so.
449
+ if (isDocumentNotFound(error)) {
450
+ setDraft(undefined);
451
+ setOffered(false);
452
+ } else setSupersedeFailure(storageErrorMessage(error));
453
+ }
244
454
  }
245
- setResume((chosen) => chosen ?? false);
455
+ // The package is what is open now, even if the copy beside it
456
+ // survived the supersede: reading the channel off a stale copy would
457
+ // put the builder back on the text this save replaced.
458
+ setResume(false);
246
459
  // The package changed: the file, the manifest the live view reads,
247
460
  // the package's dashboards list, and the dashboard the reader sees.
248
461
  await queryClient.invalidateQueries({
@@ -251,6 +464,7 @@ export function DashboardEditor({
251
464
  environmentName,
252
465
  packageName,
253
466
  modelPath,
467
+ versionId,
254
468
  ],
255
469
  });
256
470
  for (const key of [
@@ -265,22 +479,83 @@ export function DashboardEditor({
265
479
  environmentName,
266
480
  packageName,
267
481
  modelPath,
268
- packageHash,
482
+ versionId,
269
483
  storage,
270
484
  locator,
271
485
  queryClient,
272
486
  ],
273
487
  );
274
- const save = mutable
275
- ? saveToPackage
276
- : storage && locator
277
- ? saveToBrowser
278
- : undefined;
488
+ // `authoritative` wins outright rather than breaking a tie: a host whose
489
+ // store is the record may well sit on a server that reports itself
490
+ // writable, and writing the package there would edit a deploy of the
491
+ // record instead of the record.
492
+ const savesTo = authoritative ? "host" : mutable ? "package" : "browser";
493
+ const canWriteWorkspace = workspace?.writeable === true;
494
+ // A version is an immutable checkpoint, and `updateModelSource` cannot be
495
+ // told to write against one (the server answers 501). Without this guard,
496
+ // `expectedHash` would be the hash of the pinned text, the server would
497
+ // refuse every save against the current file, and the catch would refetch
498
+ // the same pinned text, so the "changed since you opened it" banner would
499
+ // never fire either: a dead end with no way out. Storage-backed saves are
500
+ // unaffected, since they never touch the package's compare-and-swap.
501
+ const pinnedPackageSave = versionId !== undefined && savesTo === "package";
502
+ const writer = authoritative
503
+ ? storage && locator && canWriteWorkspace
504
+ ? saveToStorage
505
+ : undefined
506
+ : pinnedPackageSave
507
+ ? undefined
508
+ : mutable
509
+ ? saveToPackage
510
+ : storage && locator && canWriteWorkspace
511
+ ? saveToStorage
512
+ : undefined;
513
+ // A copy that could not be read is not a copy that is not there. Saving on
514
+ // that belief is what rewinds the record, so Save is off until a reader can
515
+ // be told what actually happened.
516
+ const save = readFailure === undefined ? writer : undefined;
517
+ const workspaceName = workspace?.name;
518
+ const reportEvent = useCallback(
519
+ (event: DashboardEvent) => {
520
+ // Only where a workspace actually took the write: a save into the
521
+ // package was not taken by one, and naming it there would say the
522
+ // record moved somewhere it did not.
523
+ onEventRef.current?.(
524
+ event.type === "dashboard.saved" &&
525
+ event.where !== "package" &&
526
+ workspaceName !== undefined
527
+ ? { ...event, workspace: workspaceName }
528
+ : event,
529
+ );
530
+ },
531
+ [workspaceName],
532
+ );
533
+ // Stable: the builder fires this from an effect that depends on it.
534
+ const reportDirty = useCallback((value: boolean) => {
535
+ setDirty(value);
536
+ onDirtyChangeRef.current?.(value);
537
+ }, []);
538
+ // An explicit choice is a choice about the very text that would otherwise
539
+ // be held back, so it is never held.
279
540
  const choose = (resumeDraft: boolean) => {
280
541
  startedAt.current = now();
542
+ setAccepted(resumeDraft ? draft : packageNow);
281
543
  setResume(resumeDraft);
282
544
  };
545
+ const acceptHeld = () => {
546
+ startedAt.current = now();
547
+ setAccepted(held);
548
+ };
283
549
 
550
+ // After every hook, so the hook order does not depend on the URI. Same
551
+ // reasoning as `Dashboard`'s own check.
552
+ if (!uriNamesBoth && "resourceUri" in props)
553
+ return (
554
+ <Alert severity="error" sx={{ m: 2 }}>
555
+ A dashboard resource URI must name an environment and a package.
556
+ Received: {props.resourceUri}
557
+ </Alert>
558
+ );
284
559
  if (modelQuery.isError)
285
560
  return (
286
561
  <ApiErrorDisplay
@@ -298,6 +573,15 @@ export function DashboardEditor({
298
573
  <Loading text="Opening the dashboard…" />
299
574
  </Stack>
300
575
  );
576
+ // Where the host's copy IS the document, a copy that could not be read
577
+ // leaves nothing safe to edit: the package file is a deploy of the record,
578
+ // so opening it and arming Save would publish it over the record.
579
+ if (blockedOnRecord)
580
+ return (
581
+ <Alert severity="error" sx={{ m: 2 }}>
582
+ This dashboard cannot be opened: {readFailure}
583
+ </Alert>
584
+ );
301
585
  if (openError)
302
586
  return (
303
587
  <Alert severity="error" sx={{ m: 2 }}>
@@ -308,7 +592,7 @@ export function DashboardEditor({
308
592
  const draftDiffers = draft !== undefined && draft !== packageText;
309
593
  return (
310
594
  <Stack sx={{ gap: 2 }}>
311
- {offered && draftDiffers && resume === undefined && (
595
+ {!authoritative && offered && draftDiffers && resume === undefined && (
312
596
  <Alert
313
597
  severity="info"
314
598
  action={
@@ -326,6 +610,29 @@ export function DashboardEditor({
326
610
  package does not have.
327
611
  </Alert>
328
612
  )}
613
+ {held !== undefined && (
614
+ <Alert
615
+ severity="warning"
616
+ action={
617
+ <Button size="small" onClick={acceptHeld}>
618
+ Load it
619
+ </Button>
620
+ }
621
+ >
622
+ {savesTo === "package"
623
+ ? "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."
624
+ : savesTo === "host"
625
+ ? "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."
626
+ : "The package's copy of this dashboard changed since you opened it. Your edits are still here; loading the new version replaces them."}
627
+ </Alert>
628
+ )}
629
+ {supersedeFailure !== undefined && (
630
+ <Alert severity="warning">
631
+ The file was saved into the package, but the copy kept beside it
632
+ could not be cleared, so it will be offered again:{" "}
633
+ {supersedeFailure}
634
+ </Alert>
635
+ )}
329
636
  {opened && (
330
637
  <Surface
331
638
  key={opened.generation}
@@ -333,10 +640,12 @@ export function DashboardEditor({
333
640
  packageName={packageName}
334
641
  modelPath={modelPath}
335
642
  slug={dashboardName}
643
+ {...(versionId !== undefined ? { versionId } : {})}
336
644
  opened={opened}
337
645
  onSave={save}
338
- savesTo={mutable ? "package" : "browser"}
339
- {...(onEvent ? { onEvent } : {})}
646
+ onDirtyChange={reportDirty}
647
+ savesTo={savesTo}
648
+ {...(onEvent ? { onEvent: reportEvent } : {})}
340
649
  toolbar={
341
650
  onExit && (
342
651
  <SecondaryButton
@@ -346,19 +655,55 @@ export function DashboardEditor({
346
655
  />
347
656
  )
348
657
  }
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
- }
658
+ note={caption({
659
+ authoritative,
660
+ mutable,
661
+ pinnedPackageSave,
662
+ ...(workspace ? { workspace } : {}),
663
+ ...(readFailure !== undefined ? { readFailure } : {}),
664
+ ...(versionId !== undefined ? { versionId } : {}),
665
+ })}
356
666
  />
357
667
  )}
358
668
  </Stack>
359
669
  );
360
670
  }
361
671
 
672
+ /**
673
+ * What the toolbar says about where Save goes, in the backend's own words
674
+ * wherever it has any: a workspace carries a `description` precisely so the
675
+ * editor does not have to guess, and "this browser" is one host's answer
676
+ * rather than the interface's.
677
+ */
678
+ function caption({
679
+ authoritative,
680
+ mutable,
681
+ pinnedPackageSave,
682
+ workspace,
683
+ readFailure,
684
+ versionId,
685
+ }: {
686
+ authoritative: boolean;
687
+ mutable: boolean;
688
+ pinnedPackageSave: boolean;
689
+ workspace?: Workspace;
690
+ readFailure?: string;
691
+ versionId?: string;
692
+ }): string {
693
+ if (readFailure !== undefined)
694
+ return `The saved copy could not be read, so Save is off: ${readFailure}`;
695
+ if (authoritative && workspace)
696
+ return workspace.writeable
697
+ ? workspace.description
698
+ : `${workspace.description}: you cannot save into it.`;
699
+ if (pinnedPackageSave)
700
+ return `Reading version ${versionId}: a version is a fixed point in history, so Save is off.`;
701
+ if (mutable) return "Save writes the file into the package.";
702
+ if (workspace)
703
+ return `${workspace.description}: this server does not take writes.`;
704
+ return "This server does not take writes.";
705
+ }
706
+
362
707
  /**
363
708
  * The builder under a real control row, with the controls driving the tiles,
364
709
  * both following the LIVE document rather than the saved file.
@@ -375,8 +720,10 @@ function Surface({
375
720
  packageName,
376
721
  modelPath,
377
722
  slug,
723
+ versionId,
378
724
  opened,
379
725
  onSave,
726
+ onDirtyChange,
380
727
  onEvent,
381
728
  savesTo,
382
729
  toolbar,
@@ -386,10 +733,12 @@ function Surface({
386
733
  packageName: string;
387
734
  modelPath: string;
388
735
  slug: string;
736
+ versionId?: string;
389
737
  opened: { source: string; document: DashboardDocument; generation: number };
390
738
  onSave?: (source: string) => Promise<void>;
739
+ onDirtyChange: (dirty: boolean) => void;
391
740
  onEvent?: DashboardEventHandler;
392
- savesTo: "package" | "browser";
741
+ savesTo: "package" | "browser" | "host";
393
742
  toolbar: React.ReactNode;
394
743
  note: string;
395
744
  }) {
@@ -401,25 +750,31 @@ function Surface({
401
750
  environmentName,
402
751
  packageName,
403
752
  slug,
753
+ versionId,
404
754
  ],
405
755
  queryFn: () =>
406
756
  apiClients.dashboards.getDashboard(
407
757
  environmentName,
408
758
  packageName,
409
759
  slug,
410
- undefined,
760
+ versionId,
411
761
  ),
412
762
  });
413
763
  const manifest = data?.data;
414
764
 
415
765
  // The package's other dashboards, by slug: where a clicked cell can go.
416
766
  const { data: dashboardList } = useQueryWithApiError({
417
- queryKey: ["dashboard-editor-dashboards", environmentName, packageName],
767
+ queryKey: [
768
+ "dashboard-editor-dashboards",
769
+ environmentName,
770
+ packageName,
771
+ versionId,
772
+ ],
418
773
  queryFn: () =>
419
774
  apiClients.dashboards.listDashboards(
420
775
  environmentName,
421
776
  packageName,
422
- undefined,
777
+ versionId,
423
778
  ),
424
779
  });
425
780
  const otherDashboards = useMemo(
@@ -447,12 +802,13 @@ function Surface({
447
802
  environmentName,
448
803
  packageName,
449
804
  ...importPaths,
805
+ versionId,
450
806
  ],
451
807
  queryFn: async () => {
452
808
  const models = await Promise.all(
453
809
  importPaths.map((path) =>
454
810
  apiClients.models
455
- .getModel(environmentName, packageName, path)
811
+ .getModel(environmentName, packageName, path, versionId)
456
812
  .then((response) => response.data),
457
813
  ),
458
814
  );
@@ -481,11 +837,12 @@ function Surface({
481
837
  specs,
482
838
  loaded: isSuccess,
483
839
  startingValues: manifest?.startingGivens,
484
- documentKey: `${environmentName}/${packageName}/${slug}/edit`,
840
+ documentKey: `${environmentName}/${packageName}/${versionId ?? ""}/${slug}/edit`,
485
841
  autorun: manifest?.autorun !== false,
486
842
  environmentName,
487
843
  packageName,
488
844
  modelPath: manifest?.path,
845
+ versionId,
489
846
  documentName: slug,
490
847
  });
491
848
 
@@ -497,6 +854,7 @@ function Surface({
497
854
  <DashboardTile
498
855
  environmentName={environmentName}
499
856
  packageName={packageName}
857
+ versionId={versionId}
500
858
  modelPath={modelPath}
501
859
  tile={query.expression}
502
860
  label={
@@ -516,6 +874,7 @@ function Surface({
516
874
  runnable,
517
875
  environmentName,
518
876
  packageName,
877
+ versionId,
519
878
  modelPath,
520
879
  applied,
521
880
  declaredTypes,
@@ -539,6 +898,7 @@ function Surface({
539
898
  : {}),
540
899
  }))}
541
900
  onChange={setDoc}
901
+ onDirtyChange={onDirtyChange}
542
902
  {...(catalog ? { catalog } : {})}
543
903
  dashboards={otherDashboards}
544
904
  {...(onEvent ? { onEvent } : {})}
@@ -558,6 +918,11 @@ function Surface({
558
918
  );
559
919
  }
560
920
 
921
+ /** What a storage backend said went wrong, for a reader who has to act on it. */
922
+ function storageErrorMessage(error: unknown): string {
923
+ return error instanceof Error ? error.message : String(error);
924
+ }
925
+
561
926
  /** The server's own reason for a refused write, when it gave one. */
562
927
  function apiErrorMessage(error: unknown): string {
563
928
  const data = (error as { response?: { data?: { message?: string } } })