@malloy-publisher/sdk 0.4.0 → 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.
@@ -8,11 +8,17 @@ 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";
13
17
  import {
18
+ isDocumentNotFound,
14
19
  useOptionalDocumentStorage,
15
20
  type DocumentLocator,
21
+ type Workspace,
16
22
  } from "../DocumentStorage";
17
23
  import { GivensPanel } from "../given";
18
24
  import { SecondaryButton } from "../buttons";
@@ -33,10 +39,13 @@ import { sha256Hex } from "../../utils/sha256";
33
39
  * control row and live tiles that follow the document, a catalog for the
34
40
  * filter window's field search, and saving.
35
41
  *
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.
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.
40
49
  *
41
50
  * What that costs is stated in the toolbar: a control added here is live in the
42
51
  * editor (its value is written into each tile's query) but reaches the package
@@ -54,6 +63,15 @@ export interface DashboardEditorProps {
54
63
  * count; see `DashboardEvent`.
55
64
  */
56
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;
57
75
  }
58
76
 
59
77
  /** The Console's key for a dashboard's copy; see the storage seam's locator rule. */
@@ -74,6 +92,7 @@ export function DashboardEditor({
74
92
  dashboardName,
75
93
  onExit,
76
94
  onEvent,
95
+ onDirtyChange,
77
96
  }: DashboardEditorProps) {
78
97
  const { apiClients, mutable } = useServer();
79
98
  const queryClient = useQueryClient();
@@ -83,6 +102,8 @@ export function DashboardEditor({
83
102
  const startedAt = useRef(now());
84
103
  const onEventRef = useRef(onEvent);
85
104
  onEventRef.current = onEvent;
105
+ const onDirtyChangeRef = useRef(onDirtyChange);
106
+ onDirtyChangeRef.current = onDirtyChange;
86
107
  const storage = useOptionalDocumentStorage()?.documentStorage;
87
108
  const modelPath = `dashboards/${dashboardName}.malloy`;
88
109
 
@@ -100,78 +121,158 @@ export function DashboardEditor({
100
121
  const packageText = (
101
122
  modelQuery.data?.data as { sourceText?: string } | undefined
102
123
  )?.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
124
 
120
- // The host's copy, if one was saved earlier: offered, never assumed.
121
- 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);
122
127
  const [draft, setDraft] = useState<string | undefined>(undefined);
123
128
  const [draftChecked, setDraftChecked] = useState(storage === undefined);
124
- // 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
125
130
  // offered. A copy this session saves is not "edits from an earlier visit".
126
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
+ );
127
138
  useEffect(() => {
128
139
  if (!storage) return;
129
140
  let stale = false;
141
+ setReadFailure(undefined);
130
142
  (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);
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));
148
179
  }
180
+ if (!stale) setDraftChecked(true);
149
181
  })();
150
182
  return () => {
151
183
  stale = true;
152
184
  };
153
185
  }, [storage, environmentName, packageName, modelPath]);
154
186
 
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.
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.
158
197
  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";
198
+ const fromDraft = authoritative
199
+ ? draft !== undefined
200
+ : resume === true && draft !== undefined;
163
201
  const [opened, setOpened] = useState<
164
202
  | { source: string; document: DashboardDocument; generation: number }
165
203
  | undefined
166
204
  >(undefined);
167
205
  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);
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";
172
267
  useEffect(() => {
173
- if (opening === undefined || opening === savedRef.current) 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;
174
273
  let stale = false;
274
+ const packageAtOpen = packageNowRef.current;
275
+ const latestAtOpen = latestRef.current;
175
276
  void readDashboardDocument(opening).then((result) => {
176
277
  if (stale) return;
177
278
  if (readFailed(result)) {
@@ -183,6 +284,14 @@ export function DashboardEditor({
183
284
  return;
184
285
  }
185
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);
186
295
  setOpened((previous) => ({
187
296
  source: opening,
188
297
  document: result.document,
@@ -198,31 +307,60 @@ export function DashboardEditor({
198
307
  return () => {
199
308
  stale = true;
200
309
  };
201
- }, [opening]);
310
+ }, [opening, draftChecked, blockedOnRecord]);
202
311
 
203
312
  const locator =
204
313
  workspace === undefined
205
314
  ? undefined
206
- : dashboardLocator(workspace, environmentName, packageName, modelPath);
207
- const saveToBrowser = useCallback(
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(
208
324
  async (source: string) => {
209
325
  if (!storage || !locator)
210
326
  throw new Error(
211
327
  "This host keeps no documents, so there is nowhere to save.",
212
328
  );
213
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 });
214
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);
215
339
  // Saving without choosing is choosing the package file.
216
- setResume((chosen) => chosen ?? false);
340
+ if (!authoritative) setResume((chosen) => chosen ?? false);
217
341
  },
218
- [storage, locator],
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,
219
348
  );
220
349
  // Into the package itself, when the server takes writes: compile-checked,
221
350
  // 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.
351
+ // it was opened. A copy of the same file kept beside it is superseded by it.
223
352
  const saveToPackage = useCallback(
224
353
  async (source: string) => {
225
- if (packageHash === undefined)
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)
226
364
  throw new Error("The package file is still loading; try again.");
227
365
  let result;
228
366
  try {
@@ -230,19 +368,45 @@ export function DashboardEditor({
230
368
  environmentName,
231
369
  packageName,
232
370
  modelPath,
233
- { source, expectedHash: packageHash },
371
+ { source, expectedHash },
234
372
  );
235
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
+ });
236
385
  throw new Error(apiErrorMessage(error));
237
386
  }
238
- savedRef.current = source;
239
- setPackageHash(result.data.contentHash);
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);
240
392
  if (storage && locator) {
241
- await storage.deleteDocument(locator).catch(() => undefined);
242
- setDraft(undefined);
243
- setOffered(false);
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
+ }
244
405
  }
245
- setResume((chosen) => chosen ?? false);
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);
246
410
  // The package changed: the file, the manifest the live view reads,
247
411
  // the package's dashboards list, and the dashboard the reader sees.
248
412
  await queryClient.invalidateQueries({
@@ -265,21 +429,62 @@ export function DashboardEditor({
265
429
  environmentName,
266
430
  packageName,
267
431
  modelPath,
268
- packageHash,
269
432
  storage,
270
433
  locator,
271
434
  queryClient,
272
435
  ],
273
436
  );
274
- const save = mutable
275
- ? saveToPackage
276
- : storage && locator
277
- ? saveToBrowser
278
- : undefined;
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,
468
+ );
469
+ },
470
+ [workspaceName],
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.
279
479
  const choose = (resumeDraft: boolean) => {
280
480
  startedAt.current = now();
481
+ setAccepted(resumeDraft ? draft : packageNow);
281
482
  setResume(resumeDraft);
282
483
  };
484
+ const acceptHeld = () => {
485
+ startedAt.current = now();
486
+ setAccepted(held);
487
+ };
283
488
 
284
489
  if (modelQuery.isError)
285
490
  return (
@@ -298,6 +503,15 @@ export function DashboardEditor({
298
503
  <Loading text="Opening the dashboard…" />
299
504
  </Stack>
300
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
+ );
301
515
  if (openError)
302
516
  return (
303
517
  <Alert severity="error" sx={{ m: 2 }}>
@@ -308,7 +522,7 @@ export function DashboardEditor({
308
522
  const draftDiffers = draft !== undefined && draft !== packageText;
309
523
  return (
310
524
  <Stack sx={{ gap: 2 }}>
311
- {offered && draftDiffers && resume === undefined && (
525
+ {!authoritative && offered && draftDiffers && resume === undefined && (
312
526
  <Alert
313
527
  severity="info"
314
528
  action={
@@ -326,6 +540,29 @@ export function DashboardEditor({
326
540
  package does not have.
327
541
  </Alert>
328
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
+ )}
329
566
  {opened && (
330
567
  <Surface
331
568
  key={opened.generation}
@@ -335,8 +572,9 @@ export function DashboardEditor({
335
572
  slug={dashboardName}
336
573
  opened={opened}
337
574
  onSave={save}
338
- savesTo={mutable ? "package" : "browser"}
339
- {...(onEvent ? { onEvent } : {})}
575
+ onDirtyChange={reportDirty}
576
+ savesTo={savesTo}
577
+ {...(onEvent ? { onEvent: reportEvent } : {})}
340
578
  toolbar={
341
579
  onExit && (
342
580
  <SecondaryButton
@@ -346,19 +584,47 @@ export function DashboardEditor({
346
584
  />
347
585
  )
348
586
  }
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
- }
587
+ note={caption({
588
+ authoritative,
589
+ mutable,
590
+ ...(workspace ? { workspace } : {}),
591
+ ...(readFailure !== undefined ? { readFailure } : {}),
592
+ })}
356
593
  />
357
594
  )}
358
595
  </Stack>
359
596
  );
360
597
  }
361
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
+
362
628
  /**
363
629
  * The builder under a real control row, with the controls driving the tiles,
364
630
  * both following the LIVE document rather than the saved file.
@@ -377,6 +643,7 @@ function Surface({
377
643
  slug,
378
644
  opened,
379
645
  onSave,
646
+ onDirtyChange,
380
647
  onEvent,
381
648
  savesTo,
382
649
  toolbar,
@@ -388,8 +655,9 @@ function Surface({
388
655
  slug: string;
389
656
  opened: { source: string; document: DashboardDocument; generation: number };
390
657
  onSave?: (source: string) => Promise<void>;
658
+ onDirtyChange: (dirty: boolean) => void;
391
659
  onEvent?: DashboardEventHandler;
392
- savesTo: "package" | "browser";
660
+ savesTo: "package" | "browser" | "host";
393
661
  toolbar: React.ReactNode;
394
662
  note: string;
395
663
  }) {
@@ -539,6 +807,7 @@ function Surface({
539
807
  : {}),
540
808
  }))}
541
809
  onChange={setDoc}
810
+ onDirtyChange={onDirtyChange}
542
811
  {...(catalog ? { catalog } : {})}
543
812
  dashboards={otherDashboards}
544
813
  {...(onEvent ? { onEvent } : {})}
@@ -558,6 +827,11 @@ function Surface({
558
827
  );
559
828
  }
560
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
+
561
835
  /** The server's own reason for a refused write, when it gave one. */
562
836
  function apiErrorMessage(error: unknown): string {
563
837
  const data = (error as { response?: { data?: { message?: string } } })
@@ -1,11 +1,12 @@
1
1
  // Copyright (c) Credible Data Inc.
2
2
  // SPDX-License-Identifier: MIT
3
3
 
4
- import type {
5
- DocumentLocator,
6
- DocumentStorage,
7
- DocumentType,
8
- Workspace,
4
+ import {
5
+ DocumentNotFoundError,
6
+ type DocumentLocator,
7
+ type DocumentStorage,
8
+ type DocumentType,
9
+ type Workspace,
9
10
  } from "./DocumentStorage";
10
11
 
11
12
  const LOCAL_WORKSPACE: Workspace = {
@@ -99,7 +100,7 @@ function locatorOf(key: string): DocumentLocator | undefined {
99
100
  }
100
101
 
101
102
  function missing(locator: DocumentLocator): Error {
102
- return new Error(
103
+ return new DocumentNotFoundError(
103
104
  `No ${locator.type} at ${locator.workspace}/${locator.path}`,
104
105
  );
105
106
  }