@malloy-publisher/sdk 0.9.12 → 0.9.13

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 (68) hide show
  1. package/README.md +5 -7
  2. package/dist/{RenderedResult-CDiXJAh9.es.js → RenderedResult-DnBtf-cI.es.js} +2 -2
  3. package/dist/{RenderedResult-De51QvsZ.cjs.js → RenderedResult-DtQtNV0d.cjs.js} +1 -1
  4. package/dist/ServerProvider-BIFPCzTD.cjs.js +1 -0
  5. package/dist/{ServerProvider-RvKSbvnL.es.js → ServerProvider-BV7IoDMR.es.js} +805 -606
  6. package/dist/builder/index.cjs.js +72 -72
  7. package/dist/builder/index.es.js +4156 -4219
  8. package/dist/builder-entry.d.ts +1 -0
  9. package/dist/client/api.d.ts +178 -0
  10. package/dist/client/index.cjs.js +1 -1
  11. package/dist/client/index.es.js +41 -37
  12. package/dist/components/Report/telemetry.d.ts +0 -5
  13. package/dist/components/ReportBuilder/BuilderBar.d.ts +1 -1
  14. package/dist/components/ReportBuilder/BuilderToolbar.d.ts +14 -10
  15. package/dist/components/ReportBuilder/EditorSurface.d.ts +1 -2
  16. package/dist/components/ReportBuilder/ReportBuilder.d.ts +3 -10
  17. package/dist/components/ReportBuilder/ReportEditor.d.ts +2 -9
  18. package/dist/components/ReportBuilder/SaveStatus.d.ts +16 -0
  19. package/dist/components/ReportBuilder/TileFrame.d.ts +9 -2
  20. package/dist/components/ReportBuilder/builderControls.d.ts +14 -6
  21. package/dist/components/ReportBuilder/useBuilderSession.d.ts +1 -1
  22. package/dist/components/ReportBuilder/useReportDraft.d.ts +6 -2
  23. package/dist/components/given/GivenInput.d.ts +18 -1
  24. package/dist/components/given/GivensPanel.d.ts +12 -1
  25. package/dist/components/given/useOptionSearch.d.ts +30 -0
  26. package/dist/hooks/index.d.ts +1 -1
  27. package/dist/hooks/useDocumentControls.d.ts +5 -0
  28. package/dist/hooks/useGivensState.d.ts +7 -0
  29. package/dist/hooks/useSuggestOptions.d.ts +60 -4
  30. package/dist/index.cjs.js +1 -1
  31. package/dist/index.es.js +5 -5
  32. package/dist/{useCompiledDocument-Bf4RSfB6.es.js → useCompiledDocument-B4QF1mIl.es.js} +6912 -6759
  33. package/dist/useCompiledDocument-D0OAMejE.cjs.js +142 -0
  34. package/package.json +1 -1
  35. package/src/builder-entry.ts +1 -0
  36. package/src/components/Report/ReportPage.tsx +5 -1
  37. package/src/components/Report/telemetry.ts +0 -6
  38. package/src/components/ReportBuilder/AddTileDialog.tsx +2 -2
  39. package/src/components/ReportBuilder/BuilderBar.tsx +5 -256
  40. package/src/components/ReportBuilder/BuilderHeader.tsx +9 -3
  41. package/src/components/ReportBuilder/BuilderToolbar.tsx +15 -38
  42. package/src/components/ReportBuilder/EditorSurface.tsx +0 -3
  43. package/src/components/ReportBuilder/FilterDialog.tsx +1 -1
  44. package/src/components/ReportBuilder/ReportBuilder.controls.spec.tsx +210 -24
  45. package/src/components/ReportBuilder/ReportBuilder.tsx +43 -85
  46. package/src/components/ReportBuilder/ReportEditor.package.spec.tsx +0 -36
  47. package/src/components/ReportBuilder/ReportEditor.tsx +2 -13
  48. package/src/components/ReportBuilder/SaveStatus.tsx +271 -0
  49. package/src/components/ReportBuilder/TileFrame.spec.ts +34 -0
  50. package/src/components/ReportBuilder/TileFrame.tsx +10 -3
  51. package/src/components/ReportBuilder/builderControls.ts +39 -13
  52. package/src/components/ReportBuilder/emptyStart.spec.ts +1 -1
  53. package/src/components/ReportBuilder/useReportDraft.ts +38 -4
  54. package/src/components/given/GivenInput.tsx +219 -104
  55. package/src/components/given/GivensPanel.spec.tsx +19 -0
  56. package/src/components/given/GivensPanel.tsx +31 -1
  57. package/src/components/given/useOptionSearch.spec.tsx +218 -0
  58. package/src/components/given/useOptionSearch.ts +100 -0
  59. package/src/hooks/index.ts +5 -1
  60. package/src/hooks/useDocumentControls.ts +12 -1
  61. package/src/hooks/useGivensState.spec.ts +54 -0
  62. package/src/hooks/useGivensState.ts +21 -1
  63. package/src/hooks/useSuggestOptions.dom.spec.ts +125 -4
  64. package/src/hooks/useSuggestOptions.spec.ts +73 -2
  65. package/src/hooks/useSuggestOptions.ts +234 -62
  66. package/dist/ServerProvider-DKrBcXL7.cjs.js +0 -1
  67. package/dist/useCompiledDocument-XsQz85Ri.cjs.js +0 -141
  68. package/src/components/ReportBuilder/ReportBuilder.layoutSwitch.spec.tsx +0 -145
@@ -0,0 +1,271 @@
1
+ // Copyright (c) Credible Data Inc.
2
+ // SPDX-License-Identifier: MIT
3
+
4
+ import { reportClasses } from "../../theme/classes";
5
+ import CheckIcon from "@mui/icons-material/Check";
6
+ import ExpandMoreIcon from "@mui/icons-material/ExpandMore";
7
+ import RestartAltIcon from "@mui/icons-material/RestartAlt";
8
+ import { Box, ButtonBase, Menu, MenuItem, Tooltip } from "@mui/material";
9
+ import type { Theme } from "@mui/material";
10
+ import { useState } from "react";
11
+ import { MOTION_FAST } from "../../theme/motion";
12
+ import { usePublisherTheme } from "../../theme/ThemeContext";
13
+ import { edgeColor } from "../controlTokens";
14
+ import type { BuilderControls } from "./builderControls";
15
+
16
+ /** What the status reads: a slice of the builder's controls. */
17
+ export type SaveStatusProps = Pick<
18
+ BuilderControls,
19
+ | "status"
20
+ | "saveTarget"
21
+ | "draftKeptAt"
22
+ | "discard"
23
+ | "restored"
24
+ | "dismissRestored"
25
+ >;
26
+
27
+ /**
28
+ * Where the edits stand: saved, saving, kept in this browser, or (with no
29
+ * draft) unsaved. While there are edits to drop, it opens a menu offering
30
+ * Discard edits, which is one undoable edit back to the saved report.
31
+ *
32
+ * Edits put back from this browser on opening are said here, not in a banner
33
+ * over the page: the dot takes the accent, and the menu's first line says when
34
+ * the edits are from, until the menu has been opened once or the author edits
35
+ * again.
36
+ */
37
+ export function SaveStatus(props: SaveStatusProps) {
38
+ const { theme } = usePublisherTheme();
39
+ const ui = theme.ui;
40
+ const [anchor, setAnchor] = useState<HTMLElement | null>(null);
41
+ const { status, draftKeptAt, discard, restored, dismissRestored } = props;
42
+ // A stale draft is the page's to ask about; only edits actually put back
43
+ // are news for the status.
44
+ const news =
45
+ restored !== undefined && !restored.pending && status === "unsaved"
46
+ ? restored
47
+ : undefined;
48
+ const words =
49
+ status === "saved"
50
+ ? "Saved"
51
+ : status === "saving"
52
+ ? "Saving…"
53
+ : draftKeptAt !== undefined
54
+ ? "Draft saved"
55
+ : "Unsaved changes";
56
+ const restoredLine = news
57
+ ? `Restored your unsaved edits from ${clockTime(news.savedAt)}`
58
+ : undefined;
59
+ const hint =
60
+ status === "unsaved" && draftKeptAt !== undefined
61
+ ? "Your edits are kept in this browser. Done saves them to the report."
62
+ : props.saveTarget;
63
+ // One element for every state, set the same way: the same type and
64
+ // padding, an icon slot of one size (a dot, or the check), and the
65
+ // chevron's room kept whether or not the menu is offered. Each state used
66
+ // to be drawn differently (a menu button for a draft, bare text otherwise),
67
+ // so Draft saved → Saving… → Saved changed font, padding and width at every
68
+ // step, and the controls beside it jumped. A minimum width, with the words
69
+ // set against the undo buttons, keeps them still.
70
+ const menu = discard !== undefined && status === "unsaved";
71
+ const close = () => {
72
+ setAnchor(null);
73
+ // Seen: the menu said it once, and the status goes back to plain.
74
+ if (news) dismissRestored?.();
75
+ };
76
+ const sx = (mui: Theme) => ({
77
+ display: "inline-flex",
78
+ alignItems: "center",
79
+ justifyContent: "flex-end",
80
+ gap: 0.75,
81
+ minWidth: 132,
82
+ height: ui.size.control,
83
+ px: 1,
84
+ borderRadius: ui.radius.control,
85
+ font: "inherit",
86
+ ...ui.type.control,
87
+ whiteSpace: "nowrap" as const,
88
+ color:
89
+ status === "saved"
90
+ ? mui.palette.text.secondary
91
+ : mui.palette.text.primary,
92
+ transition: `color ${MOTION_FAST}, background-color ${MOTION_FAST}`,
93
+ ...(menu ? { "&:hover": { bgcolor: mui.palette.action.hover } } : {}),
94
+ });
95
+ const inner = (
96
+ <>
97
+ <Box
98
+ component="span"
99
+ aria-hidden
100
+ sx={{
101
+ width: 16,
102
+ height: 16,
103
+ flex: "none",
104
+ display: "inline-flex",
105
+ alignItems: "center",
106
+ justifyContent: "center",
107
+ }}
108
+ >
109
+ {status === "saved" ? (
110
+ <CheckIcon sx={{ fontSize: 16 }} />
111
+ ) : (
112
+ <Box
113
+ component="span"
114
+ data-restored={news ? "true" : undefined}
115
+ sx={(mui) => ({
116
+ width: 7,
117
+ height: 7,
118
+ borderRadius: "50%",
119
+ bgcolor: news
120
+ ? theme.accent
121
+ : status === "saving" || draftKeptAt !== undefined
122
+ ? mui.palette.text.disabled
123
+ : mui.palette.warning.main,
124
+ transition: `background-color ${MOTION_FAST}`,
125
+ })}
126
+ />
127
+ )}
128
+ </Box>
129
+ <Box component="span" aria-hidden>
130
+ {words}
131
+ </Box>
132
+ <ExpandMoreIcon
133
+ aria-hidden
134
+ sx={{
135
+ fontSize: 16,
136
+ ml: -0.25,
137
+ visibility: menu ? "visible" : "hidden",
138
+ }}
139
+ />
140
+ </>
141
+ );
142
+ // The words a screen reader hears as they change, beside the control
143
+ // rather than in it, so a button around them is named by its words.
144
+ const announce = (
145
+ <Box
146
+ component="span"
147
+ role="status"
148
+ aria-live="polite"
149
+ sx={VISUALLY_HIDDEN}
150
+ >
151
+ {restoredLine ? `${words}. ${restoredLine}.` : words}
152
+ </Box>
153
+ );
154
+ return (
155
+ <>
156
+ {announce}
157
+ <Tooltip title={restoredLine ?? hint} describeChild>
158
+ {menu ? (
159
+ <ButtonBase
160
+ className={reportClasses.saveStatus}
161
+ aria-label={words}
162
+ {...(restoredLine
163
+ ? { "aria-description": restoredLine }
164
+ : {})}
165
+ aria-haspopup="menu"
166
+ aria-expanded={anchor !== null}
167
+ onClick={(event) => setAnchor(event.currentTarget)}
168
+ sx={sx}
169
+ >
170
+ {inner}
171
+ </ButtonBase>
172
+ ) : (
173
+ <Box
174
+ component="span"
175
+ className={reportClasses.saveStatus}
176
+ sx={sx}
177
+ >
178
+ {inner}
179
+ </Box>
180
+ )}
181
+ </Tooltip>
182
+ <Menu
183
+ className={reportClasses.menu}
184
+ anchorEl={anchor}
185
+ open={anchor !== null}
186
+ onClose={close}
187
+ anchorOrigin={{ vertical: "bottom", horizontal: "left" }}
188
+ transformOrigin={{ vertical: -4, horizontal: "left" }}
189
+ slotProps={{
190
+ paper: {
191
+ sx: {
192
+ minWidth: 240,
193
+ borderRadius: ui.radius.menu,
194
+ border: `1px solid ${edgeColor(theme.cardBorder)}`,
195
+ boxShadow: ui.shadow.menu,
196
+ },
197
+ },
198
+ }}
199
+ MenuListProps={{ dense: true, sx: { py: 0.5 } }}
200
+ >
201
+ {(restoredLine !== undefined || draftKeptAt !== undefined) && (
202
+ <Box
203
+ component="li"
204
+ role="presentation"
205
+ sx={{
206
+ px: 1.75,
207
+ pt: 0.75,
208
+ pb: 1,
209
+ ...ui.type.caption,
210
+ color: "text.secondary",
211
+ }}
212
+ >
213
+ {restoredLine ??
214
+ `Kept in this browser at ${clockTime(draftKeptAt!)}`}
215
+ </Box>
216
+ )}
217
+ <MenuItem
218
+ onClick={() => {
219
+ setAnchor(null);
220
+ discard?.();
221
+ }}
222
+ sx={{
223
+ mx: 0.5,
224
+ borderRadius: ui.radius.control,
225
+ gap: 1.25,
226
+ color: "error.main",
227
+ // The menu focuses its item on open; a full focus ring
228
+ // there read as two stray rules across the menu.
229
+ "&.Mui-focusVisible": {
230
+ outline: "none",
231
+ bgcolor: "action.hover",
232
+ },
233
+ }}
234
+ >
235
+ <RestartAltIcon fontSize="small" />
236
+ Discard edits
237
+ </MenuItem>
238
+ </Menu>
239
+ </>
240
+ );
241
+ }
242
+
243
+ /** A time of day, or a date and time when not today: when a draft was kept. */
244
+ export function clockTime(at: number): string {
245
+ const when = new Date(at);
246
+ const today = new Date().toDateString() === when.toDateString();
247
+ return today
248
+ ? when.toLocaleTimeString([], { hour: "numeric", minute: "2-digit" })
249
+ : when.toLocaleString([], {
250
+ month: "short",
251
+ day: "numeric",
252
+ hour: "numeric",
253
+ minute: "2-digit",
254
+ });
255
+ }
256
+
257
+ /** In the accessibility tree, not on screen: the status line's announcement. */
258
+ const VISUALLY_HIDDEN = {
259
+ position: "absolute",
260
+ // Strings, not numbers: in `sx` a width or height of 1 is 100%, and a
261
+ // margin of -1 is one spacing unit. As numbers, this "hidden" span was as
262
+ // wide as the host's header and scrolled its panel sideways.
263
+ width: "1px",
264
+ height: "1px",
265
+ margin: "-1px",
266
+ padding: 0,
267
+ overflow: "hidden",
268
+ clip: "rect(0 0 0 0)",
269
+ whiteSpace: "nowrap",
270
+ border: 0,
271
+ } as const;
@@ -0,0 +1,34 @@
1
+ // Copyright (c) Credible Data Inc.
2
+ // SPDX-License-Identifier: MIT
3
+
4
+ import { describe, expect, it } from "bun:test";
5
+ import { resolveTheme } from "../../theme/resolveTheme";
6
+ import { selectionSx } from "./TileFrame";
7
+
8
+ const theme = resolveTheme([], "light");
9
+ const ringInset = (sx: ReturnType<typeof selectionSx>) =>
10
+ (sx as { "&::before": { inset: string } })["&::before"].inset;
11
+
12
+ describe("selectionSx: a bare ring", () => {
13
+ it("stands off its prose by one distance all round", () => {
14
+ expect(
15
+ ringInset(
16
+ selectionSx(theme, { selected: true, bare: true, ringOffset: 12 }),
17
+ ),
18
+ ).toBe("-12px");
19
+ });
20
+
21
+ it("stands off by one distance across and another above and below", () => {
22
+ // The description's: wide across, close above and below, so its halo
23
+ // stays inside the gaps to the title and the filter row.
24
+ expect(
25
+ ringInset(
26
+ selectionSx(theme, {
27
+ selected: true,
28
+ bare: true,
29
+ ringOffset: { x: 12, y: 6 },
30
+ }),
31
+ ),
32
+ ).toBe("-6px -12px");
33
+ });
34
+ });
@@ -478,8 +478,12 @@ export const selectionSx = (
478
478
  selected: boolean;
479
479
  flash?: boolean;
480
480
  bare?: boolean;
481
- /** How far a bare ring stands off its prose. Only content outside the grid may go wider than the grid's own. */
482
- ringOffset?: number;
481
+ /**
482
+ * How far a bare ring stands off its prose: one distance, or one across
483
+ * and one above and below. Only content outside the grid may go wider
484
+ * than the grid's own.
485
+ */
486
+ ringOffset?: number | { x: number; y: number };
483
487
  },
484
488
  ): SystemStyleObject<Theme> => {
485
489
  const ui = theme.ui;
@@ -504,7 +508,10 @@ export const selectionSx = (
504
508
  "&::before": {
505
509
  content: '""',
506
510
  position: "absolute",
507
- inset: `${-ringOffset}px`,
511
+ inset:
512
+ typeof ringOffset === "number"
513
+ ? `${-ringOffset}px`
514
+ : `${-ringOffset.y}px ${-ringOffset.x}px`,
508
515
  borderRadius: 1,
509
516
  border: `2px solid ${ring}`,
510
517
  ...(halo && { boxShadow: halo }),
@@ -2,7 +2,7 @@
2
2
  // SPDX-License-Identifier: MIT
3
3
 
4
4
  import { useEffect, useMemo, useRef } from "react";
5
- import type { ReportLayout } from "../Package/documentLocation";
5
+ import type { RestoredDraft } from "./useReportDraft";
6
6
 
7
7
  /**
8
8
  * The builder's page-level controls, as state and actions rather than as a
@@ -25,11 +25,6 @@ export interface BuilderControls {
25
25
  undo: () => void;
26
26
  canRedo: boolean;
27
27
  redo: () => void;
28
- /** The layout and its switch. Absent when the layout cannot be changed here. */
29
- layout?: {
30
- value: ReportLayout;
31
- set: (layout: ReportLayout) => void;
32
- };
33
28
  /** What can be added to the page. A missing entry is not offered. */
34
29
  add: {
35
30
  /** Open the picker of views for a query tile. */
@@ -53,6 +48,19 @@ export interface BuilderControls {
53
48
  draftKeptAt?: number;
54
49
  /** Put the report back to the file's, as one undoable edit, and drop the draft. Absent with nothing to discard. */
55
50
  discard?: () => void;
51
+ /**
52
+ * Edits kept in this browser that the builder found on opening. Not
53
+ * `pending`: they were put back, which is news for the save status (the
54
+ * SDK's says when they are from in its menu) until `dismissRestored`, or
55
+ * the next edit. `pending`: the report changed since they were kept, so
56
+ * they are offered, not applied; the page asks the author to choose, and
57
+ * `restore` and `discard` are the two answers.
58
+ */
59
+ restored?: RestoredDraft;
60
+ /** Apply an offered (stale) draft, replacing the current version. Present while `restored.pending`. */
61
+ restore?: () => void;
62
+ /** The author has seen the restored edits: `restored` goes. Present while `restored` is, and not pending. */
63
+ dismissRestored?: () => void;
56
64
  }
57
65
 
58
66
  /** What a host passes to take over the builder's page-level controls. */
@@ -81,14 +89,14 @@ export function useReportControls(
81
89
  save: () => latest.current.save?.(),
82
90
  undo: () => latest.current.undo(),
83
91
  redo: () => latest.current.redo(),
84
- setLayout: (layout: ReportLayout) =>
85
- latest.current.layout?.set(layout),
86
92
  addTile: () => latest.current.add.tile?.(),
87
93
  addText: () => latest.current.add.text?.(),
88
94
  addFilter: () => latest.current.add.filter?.(),
89
95
  exit: () => latest.current.exit?.(),
90
96
  done: () => latest.current.done?.(),
91
97
  discard: () => latest.current.discard?.(),
98
+ restore: () => latest.current.restore?.(),
99
+ dismissRestored: () => latest.current.dismissRestored?.(),
92
100
  }),
93
101
  [],
94
102
  );
@@ -101,7 +109,6 @@ export function useReportControls(
101
109
  add: { filterUnavailable },
102
110
  } = controls;
103
111
  const hasSave = controls.save !== undefined;
104
- const layout = controls.layout?.value;
105
112
  const hasTile = controls.add.tile !== undefined;
106
113
  const hasText = controls.add.text !== undefined;
107
114
  const hasFilter = controls.add.filter !== undefined;
@@ -109,6 +116,11 @@ export function useReportControls(
109
116
  const hasDone = controls.done !== undefined;
110
117
  const hasDiscard = controls.discard !== undefined;
111
118
  const { draftKeptAt } = controls;
119
+ const restoredAt = controls.restored?.savedAt;
120
+ const restoredStale = controls.restored?.stale ?? false;
121
+ const restoredPending = controls.restored?.pending ?? false;
122
+ const hasRestore = controls.restore !== undefined;
123
+ const hasDismissRestored = controls.dismissRestored !== undefined;
112
124
 
113
125
  const shown = useMemo<BuilderControls>(
114
126
  () => ({
@@ -119,9 +131,6 @@ export function useReportControls(
119
131
  undo: actions.undo,
120
132
  canRedo,
121
133
  redo: actions.redo,
122
- ...(layout !== undefined
123
- ? { layout: { value: layout, set: actions.setLayout } }
124
- : {}),
125
134
  add: {
126
135
  ...(hasTile ? { tile: actions.addTile } : {}),
127
136
  ...(hasText ? { text: actions.addText } : {}),
@@ -132,6 +141,19 @@ export function useReportControls(
132
141
  ...(hasDone ? { done: actions.done } : {}),
133
142
  ...(draftKeptAt !== undefined ? { draftKeptAt } : {}),
134
143
  ...(hasDiscard ? { discard: actions.discard } : {}),
144
+ ...(restoredAt !== undefined
145
+ ? {
146
+ restored: {
147
+ savedAt: restoredAt,
148
+ stale: restoredStale,
149
+ pending: restoredPending,
150
+ },
151
+ }
152
+ : {}),
153
+ ...(hasRestore ? { restore: actions.restore } : {}),
154
+ ...(hasDismissRestored
155
+ ? { dismissRestored: actions.dismissRestored }
156
+ : {}),
135
157
  }),
136
158
  [
137
159
  actions,
@@ -140,7 +162,6 @@ export function useReportControls(
140
162
  hasSave,
141
163
  canUndo,
142
164
  canRedo,
143
- layout,
144
165
  hasTile,
145
166
  hasText,
146
167
  hasFilter,
@@ -149,6 +170,11 @@ export function useReportControls(
149
170
  hasDone,
150
171
  draftKeptAt,
151
172
  hasDiscard,
173
+ restoredAt,
174
+ restoredStale,
175
+ restoredPending,
176
+ hasRestore,
177
+ hasDismissRestored,
152
178
  ],
153
179
  );
154
180
 
@@ -125,7 +125,7 @@ source: a is one extend {
125
125
  const suggest = back.localGivens?.[0].suggest;
126
126
  expect(suggest).toEqual({ source: "a", dimension: "products.category" });
127
127
  expect(buildSuggestQuery(suggest!.source!, suggest!.dimension)).toBe(
128
- `run: a -> {\n group_by: products.category\n order_by: category asc\n limit: ${SUGGEST_OPTION_LIMIT}\n}`,
128
+ `run: a -> {\n group_by: products.category\n order_by: category asc\n limit: ${SUGGEST_OPTION_LIMIT + 1}\n}`,
129
129
  );
130
130
  });
131
131
  });
@@ -36,7 +36,11 @@ interface StoredDraft {
36
36
  savedAt: number;
37
37
  }
38
38
 
39
- /** What the builder found on opening, for the notice that says so. */
39
+ /**
40
+ * What the builder found on opening. A draft put back is said in the save
41
+ * status (its menu names when the edits are from) until the author has seen it
42
+ * or edits again; a stale one is a choice the page asks for.
43
+ */
40
44
  export interface RestoredDraft {
41
45
  savedAt: number;
42
46
  /**
@@ -187,7 +191,7 @@ export function useReportDraft(
187
191
  ): {
188
192
  /** When unsaved edits were last kept in this browser; undefined when none are. */
189
193
  keptAt: number | undefined;
190
- /** The draft the builder opened with, until the notice is dismissed. */
194
+ /** The draft the builder opened with: until it is seen, or edited over; a stale one until the author chooses. */
191
195
  restored: RestoredDraft | undefined;
192
196
  dismissRestored: () => void;
193
197
  /** Put the document back to the file's, as one undoable edit; the draft goes with the edits. */
@@ -205,6 +209,12 @@ export function useReportDraft(
205
209
  // A stale draft waiting on the author: kept as it is, not overwritten or
206
210
  // removed by the clean document the builder opened on.
207
211
  const offered = useRef<StoredDraft | undefined>(undefined);
212
+ // The document a draft was put back as, until the next edit: that edit
213
+ // ends the "restored" news, since the draft is now just the edits.
214
+ const restoredAs = useRef<string | undefined>(undefined);
215
+ // Set until the put-back document has rendered: the pass in between still
216
+ // sees the document from before, which is not an edit.
217
+ const restoring = useRef(false);
208
218
  const base = textFingerprint(opened);
209
219
  const editorRef = useRef(editor);
210
220
  editorRef.current = editor;
@@ -227,6 +237,8 @@ export function useReportDraft(
227
237
  return;
228
238
  }
229
239
  current.update((document) => replaceContents(document, draft.document));
240
+ restoredAs.current = JSON.stringify(draft.document);
241
+ restoring.current = true;
230
242
  setRestored({ savedAt: draft.savedAt, stale: false, pending: false });
231
243
  // Only on opening: the key and the file it opened on are fixed for a mount.
232
244
  // eslint-disable-next-line react-hooks/exhaustive-deps
@@ -239,7 +251,21 @@ export function useReportDraft(
239
251
  // The offered draft stands until the author chooses; an edit before
240
252
  // they do is a choice too, and replaces it.
241
253
  if (offered.current && !dirty) return;
242
- offered.current = undefined;
254
+ if (offered.current) {
255
+ // Edited over instead of chosen: the edits are the choice, and the
256
+ // offer goes, so nothing goes on asking about a draft no longer kept.
257
+ offered.current = undefined;
258
+ setRestored(undefined);
259
+ }
260
+ if (restoredAs.current !== undefined) {
261
+ const now = JSON.stringify(document);
262
+ if (restoring.current) {
263
+ if (now === restoredAs.current) restoring.current = false;
264
+ } else if (now !== restoredAs.current) {
265
+ restoredAs.current = undefined;
266
+ setRestored(undefined);
267
+ }
268
+ }
243
269
  if (!dirty) {
244
270
  remove(key);
245
271
  setKeptAt(undefined);
@@ -264,10 +290,17 @@ export function useReportDraft(
264
290
  editorRef.current.update((document) =>
265
291
  replaceContents(document, draft.document),
266
292
  );
293
+ restoredAs.current = JSON.stringify(draft.document);
294
+ restoring.current = true;
267
295
  setRestored((was) => was && { ...was, pending: false });
268
296
  }, []);
269
297
 
270
- const dismissRestored = useCallback(() => setRestored(undefined), []);
298
+ const dismissRestored = useCallback(() => {
299
+ // A stale draft is a choice still to make, not news to dismiss.
300
+ if (offered.current) return;
301
+ restoredAs.current = undefined;
302
+ setRestored(undefined);
303
+ }, []);
271
304
  const discard = useCallback(() => {
272
305
  if (offered.current && key !== undefined) {
273
306
  // An offered draft was never applied: dropping it is all there is.
@@ -278,6 +311,7 @@ export function useReportDraft(
278
311
  }
279
312
  const current = editorRef.current;
280
313
  current.update((document) => replaceContents(document, current.saved));
314
+ restoredAs.current = undefined;
281
315
  setRestored(undefined);
282
316
  }, [key]);
283
317