@malloy-publisher/sdk 0.9.12 → 0.9.14

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 (69) 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 +51 -51
  7. package/dist/builder/index.es.js +3638 -3698
  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 +8 -2
  16. package/dist/components/ReportBuilder/ReportBuilder.d.ts +3 -10
  17. package/dist/components/ReportBuilder/ReportEditor.d.ts +18 -7
  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 +16 -11
  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.queryVersion.spec.tsx +292 -0
  48. package/src/components/ReportBuilder/ReportEditor.tsx +22 -11
  49. package/src/components/ReportBuilder/SaveStatus.tsx +271 -0
  50. package/src/components/ReportBuilder/TileFrame.spec.ts +34 -0
  51. package/src/components/ReportBuilder/TileFrame.tsx +10 -3
  52. package/src/components/ReportBuilder/builderControls.ts +39 -13
  53. package/src/components/ReportBuilder/emptyStart.spec.ts +1 -1
  54. package/src/components/ReportBuilder/useReportDraft.ts +38 -4
  55. package/src/components/given/GivenInput.tsx +219 -104
  56. package/src/components/given/GivensPanel.spec.tsx +19 -0
  57. package/src/components/given/GivensPanel.tsx +31 -1
  58. package/src/components/given/useOptionSearch.spec.tsx +218 -0
  59. package/src/components/given/useOptionSearch.ts +100 -0
  60. package/src/hooks/index.ts +5 -1
  61. package/src/hooks/useDocumentControls.ts +12 -1
  62. package/src/hooks/useGivensState.spec.ts +54 -0
  63. package/src/hooks/useGivensState.ts +21 -1
  64. package/src/hooks/useSuggestOptions.dom.spec.ts +125 -4
  65. package/src/hooks/useSuggestOptions.spec.ts +73 -2
  66. package/src/hooks/useSuggestOptions.ts +234 -62
  67. package/dist/ServerProvider-DKrBcXL7.cjs.js +0 -1
  68. package/dist/useCompiledDocument-XsQz85Ri.cjs.js +0 -141
  69. package/src/components/ReportBuilder/ReportBuilder.layoutSwitch.spec.tsx +0 -145
@@ -0,0 +1,292 @@
1
+ // Copyright (c) Credible Data Inc.
2
+ // SPDX-License-Identifier: MIT
3
+
4
+ import { fireEvent, render, screen, waitFor } from "@testing-library/react";
5
+ import { beforeEach, describe, expect, it, mock } from "bun:test";
6
+ import {
7
+ cacheKeys,
8
+ clearCache,
9
+ mockServerProvider,
10
+ pending,
11
+ serverWrapper,
12
+ TEST_SERVER,
13
+ } from "../../../test/serverProvider";
14
+ import { BrowserDocumentStorage } from "../DocumentStorage/BrowserDocumentStorage";
15
+ import { DocumentStorageProvider } from "../DocumentStorage/DocumentStorageProvider";
16
+ import { editInline } from "./testing/inline";
17
+ import { reportDraftKey } from "./useReportDraft";
18
+
19
+ /**
20
+ * `queryVersionId`: the version the builder's queries run at, apart from the
21
+ * document's identity. A host whose package republishes on every change opens
22
+ * the builder on an unversioned `resourceUri` with its reader's version here,
23
+ * so the builder reuses the reader's results while the kept draft, the save
24
+ * target and the save caption stay with the unversioned document.
25
+ */
26
+ const REPORT = "dashboards/overview.malloy";
27
+ const PACKAGE_FILE = `## artifact { title="Storefront" tiles=["a -> by_cat"] } dashboard { columns=12 }
28
+ import { scoped_orders } from "../data_app.malloy"
29
+
30
+ source: a is scoped_orders extend {
31
+ # colspan=6
32
+ # label="By category"
33
+ view: by_cat is by_category
34
+ }`;
35
+
36
+ const getModel = mock(
37
+ (_env: string, _pkg: string, path: string, _versionId?: string) =>
38
+ Promise.resolve({
39
+ data:
40
+ path === REPORT
41
+ ? { modelPath: path, sourceText: PACKAGE_FILE }
42
+ : {
43
+ modelPath: path,
44
+ modelInfo: JSON.stringify({
45
+ entries: [{ kind: "source", name: "scoped_orders" }],
46
+ }),
47
+ sources: [
48
+ {
49
+ name: "scoped_orders",
50
+ views: [{ name: "by_category" }],
51
+ },
52
+ ],
53
+ sourceInfos: [
54
+ JSON.stringify({
55
+ name: "scoped_orders",
56
+ schema: { fields: [] },
57
+ }),
58
+ ],
59
+ },
60
+ }),
61
+ );
62
+ const getReport = mock(
63
+ (
64
+ _env: string,
65
+ _pkg: string,
66
+ _path: string,
67
+ _versionId?: string,
68
+ _options?: unknown,
69
+ ) =>
70
+ Promise.resolve({
71
+ data: {
72
+ path: REPORT,
73
+ name: "overview",
74
+ title: "Storefront",
75
+ layout: "grid",
76
+ givens: [],
77
+ tiles: [{ kind: "query", query: "a -> by_cat", givenNames: [] }],
78
+ },
79
+ }),
80
+ );
81
+ const listModels = mock((_env: string, _pkg: string, _versionId?: string) =>
82
+ Promise.resolve({ data: [{ path: "data_app.malloy" }] }),
83
+ );
84
+ const listReports = mock((_env: string, _pkg: string, _versionId?: string) =>
85
+ Promise.resolve({
86
+ data: [{ path: REPORT, name: "overview", layout: "grid" }],
87
+ }),
88
+ );
89
+ const updateModelSource = mock(
90
+ (_env: string, _pkg: string, path: string, body: { source: string }) =>
91
+ Promise.resolve({
92
+ data: {
93
+ path,
94
+ contentHash: `hash-of-${body.source.length}`,
95
+ created: false,
96
+ },
97
+ }),
98
+ );
99
+ // Answers by default, so the reader's tiles land in the cache; a test that
100
+ // wants nothing to settle swaps in `pending`.
101
+ let answer: () => Promise<unknown> = () =>
102
+ Promise.resolve({ data: { result: "{}" } });
103
+ const executeQueryModel = mock(
104
+ (
105
+ _env: string,
106
+ _pkg: string,
107
+ _path: string,
108
+ _body: { query?: string; givens?: unknown; versionId?: string },
109
+ ) => answer(),
110
+ );
111
+
112
+ const serverContext = { mutable: false };
113
+ mockServerProvider(
114
+ {
115
+ models: { getModel, executeQueryModel, updateModelSource, listModels },
116
+ reports: { getReport, listReports },
117
+ notebooks: { getNotebook: () => pending() },
118
+ },
119
+ serverContext,
120
+ );
121
+
122
+ const { ReportEditor } = await import("./ReportEditor");
123
+ const { Report } = await import("../Report/Report");
124
+
125
+ const URI = "publisher://environments/env/packages/pkg";
126
+
127
+ const mountEditor = (
128
+ props: { queryVersionId?: string; keepDraft?: boolean } = {},
129
+ resourceUri = URI,
130
+ ) =>
131
+ render(
132
+ <DocumentStorageProvider documentStorage={new BrowserDocumentStorage()}>
133
+ <ReportEditor resourceUri={resourceUri} path={REPORT} {...props} />
134
+ </DocumentStorageProvider>,
135
+ { wrapper: serverWrapper },
136
+ );
137
+
138
+ // The tile, as the reader and an untouched builder tile both ask for it.
139
+ const tileCalls = () =>
140
+ executeQueryModel.mock.calls.filter((call) =>
141
+ call[3].query?.includes("a -> by_cat"),
142
+ );
143
+
144
+ beforeEach(() => {
145
+ clearCache();
146
+ localStorage.clear();
147
+ for (const fn of [
148
+ getModel,
149
+ getReport,
150
+ listModels,
151
+ listReports,
152
+ updateModelSource,
153
+ executeQueryModel,
154
+ ])
155
+ fn.mockClear();
156
+ answer = () => Promise.resolve({ data: { result: "{}" } });
157
+ serverContext.mutable = false;
158
+ });
159
+
160
+ describe("queryVersionId", () => {
161
+ it("serves the builder's tile from the result the reader cached at that version", async () => {
162
+ const reader = render(
163
+ <Report resourceUri={`${URI}?versionId=v7`} path={REPORT} />,
164
+ { wrapper: serverWrapper },
165
+ );
166
+ await waitFor(() => expect(tileCalls()).toHaveLength(1));
167
+ expect(tileCalls()[0][3].versionId).toBe("v7");
168
+ await waitFor(() =>
169
+ expect(
170
+ cacheKeys("queryResult").some((key) => key.includes('"v7"')),
171
+ ).toBe(true),
172
+ );
173
+ reader.unmount();
174
+
175
+ mountEditor({ queryVersionId: "v7" });
176
+ expect(await screen.findByText("Storefront")).toBeDefined();
177
+ // Everything the builder reads besides the file itself has answered,
178
+ // so a tile that was going to run has run by now.
179
+ await waitFor(() =>
180
+ expect(
181
+ getModel.mock.calls.some((call) => call[2] === "data_app.malloy"),
182
+ ).toBe(true),
183
+ );
184
+ await new Promise((resolve) => setTimeout(resolve, 50));
185
+ expect(tileCalls()).toHaveLength(1);
186
+ // Nothing was asked unversioned: no second copy of the tile's result.
187
+ expect(
188
+ cacheKeys("queryResult").every((key) => key.includes('"v7"')),
189
+ ).toBe(true);
190
+ });
191
+
192
+ it("runs every query at that version, and reads the document unversioned", async () => {
193
+ answer = () => pending();
194
+ mountEditor({ queryVersionId: "v7" });
195
+ expect(await screen.findByText("Storefront")).toBeDefined();
196
+ await waitFor(() =>
197
+ expect(
198
+ getModel.mock.calls.some((call) => call[2] === "data_app.malloy"),
199
+ ).toBe(true),
200
+ );
201
+ await waitFor(() => expect(tileCalls().length).toBeGreaterThan(0));
202
+
203
+ // The document: the file the editor opens and saves.
204
+ expect(getModel.mock.calls.find((call) => call[2] === REPORT)).toEqual([
205
+ "env",
206
+ "pkg",
207
+ REPORT,
208
+ undefined,
209
+ ]);
210
+ // The queries: the manifest, the listing, the catalog and the tiles.
211
+ expect(getReport.mock.calls[0].slice(0, 4)).toEqual([
212
+ "env",
213
+ "pkg",
214
+ REPORT,
215
+ "v7",
216
+ ]);
217
+ expect(listReports.mock.calls[0]).toEqual(["env", "pkg", "v7"]);
218
+ expect(listModels.mock.calls[0]).toEqual(["env", "pkg", "v7"]);
219
+ expect(
220
+ getModel.mock.calls.find((call) => call[2] === "data_app.malloy"),
221
+ ).toEqual(["env", "pkg", "data_app.malloy", "v7"]);
222
+ for (const call of tileCalls()) expect(call[3].versionId).toBe("v7");
223
+ });
224
+
225
+ it("keeps the draft under the document's key, not the query version's", async () => {
226
+ answer = () => pending();
227
+ mountEditor({ queryVersionId: "v7", keepDraft: true });
228
+ await screen.findByText("Storefront");
229
+ editInline("By category", "Tile title", "Categories");
230
+
231
+ const unversioned = reportDraftKey({
232
+ server: TEST_SERVER,
233
+ environmentName: "env",
234
+ packageName: "pkg",
235
+ path: REPORT,
236
+ });
237
+ await waitFor(() =>
238
+ expect(
239
+ Object.keys(localStorage).some((key) => key.endsWith(unversioned)),
240
+ ).toBe(true),
241
+ );
242
+ expect(
243
+ Object.keys(localStorage).some((key) => key.includes("@v7/")),
244
+ ).toBe(false);
245
+ });
246
+
247
+ it("saves to the package as an unpinned document, with no pinned-version caption", async () => {
248
+ answer = () => pending();
249
+ serverContext.mutable = true;
250
+ mountEditor({ queryVersionId: "v7" });
251
+ await screen.findByText("Storefront");
252
+ expect(screen.queryByText(/Reading version/)).toBeNull();
253
+
254
+ editInline("By category", "Tile title", "Categories");
255
+ fireEvent.click(
256
+ screen.getByRole("button", { name: "Save", hidden: true }),
257
+ );
258
+ await waitFor(() => expect(updateModelSource).toHaveBeenCalledTimes(1));
259
+ expect(updateModelSource.mock.calls[0].slice(0, 3)).toEqual([
260
+ "env",
261
+ "pkg",
262
+ REPORT,
263
+ ]);
264
+ });
265
+
266
+ it("unset, runs the queries at the resourceUri's version, pinned as before", async () => {
267
+ answer = () => pending();
268
+ serverContext.mutable = true;
269
+ mountEditor({}, `${URI}?versionId=v7`);
270
+ await screen.findByText("Storefront");
271
+ await waitFor(() => expect(tileCalls().length).toBeGreaterThan(0));
272
+
273
+ expect(getModel.mock.calls.find((call) => call[2] === REPORT)?.[3]).toBe(
274
+ "v7",
275
+ );
276
+ for (const call of tileCalls()) expect(call[3].versionId).toBe("v7");
277
+ expect(
278
+ screen.getByText(
279
+ "Reading version v7: a version is a fixed point in history, so Save is off.",
280
+ ),
281
+ ).toBeDefined();
282
+ });
283
+
284
+ it("unset with no version anywhere, asks every query unversioned", async () => {
285
+ answer = () => pending();
286
+ mountEditor();
287
+ await screen.findByText("Storefront");
288
+ await waitFor(() => expect(tileCalls().length).toBeGreaterThan(0));
289
+ for (const call of tileCalls()) expect(call[3].versionId).toBeUndefined();
290
+ expect(getReport.mock.calls[0][3]).toBeUndefined();
291
+ });
292
+ });
@@ -108,7 +108,7 @@ export type ReportEditorProps = (
108
108
  * report's copy is read back only from an authoritative store) and is what
109
109
  * a save records until the text says otherwise; once open, the document's
110
110
  * own tag decides how it is drawn, what a save records and which events it
111
- * reports, and the layout switch changes that.
111
+ * reports.
112
112
  */
113
113
  layout?: ReportLayout;
114
114
  /** @deprecated Pass `layout`: `dashboard` is grid, `notebook` linear. */
@@ -141,7 +141,7 @@ export type ReportEditorProps = (
141
141
  onOpenModel?: (modelPath: string) => void;
142
142
  /**
143
143
  * Take over the builder's page-level controls (save status and Save, undo
144
- * and redo, the layout switch, Add): handed over as `BuilderControls`
144
+ * and redo, Add): handed over as `BuilderControls`
145
145
  * whenever they change, with no toolbar drawn on the page. Draw them with
146
146
  * `BuilderBar` in the host's header, or place each in its own chrome.
147
147
  */
@@ -156,12 +156,23 @@ export type ReportEditorProps = (
156
156
  /** Edit a document held as text; see {@link TextSourceOptions}. */
157
157
  textSource?: TextSourceOptions;
158
158
  /**
159
- * Whether the toolbar offers the Linear / Grid layout switch. Default
160
- * true. A host that files a report by its layout passes false, so an
161
- * author cannot change a layout the host files by. A document held as text
162
- * never gets the switch.
159
+ * The package version the builder's queries run at, apart from the
160
+ * document's own identity: every tile, the report's manifest, filter
161
+ * options and suggestions, the report listing and the field catalog.
162
+ *
163
+ * The document is still the one `resourceUri` and `path` name, so the kept
164
+ * draft, where a save goes, the save caption and whether a save is a pinned
165
+ * one all follow `resourceUri` alone. A host editing a package that is
166
+ * republished on every change passes an unversioned `resourceUri` and the
167
+ * version its reader ran at here: the builder then reuses the reader's
168
+ * results instead of running every tile again, and kept edits survive the
169
+ * next republish.
170
+ *
171
+ * Unset, queries run at the `resourceUri`'s version, as before. A text-held
172
+ * document's compile has no version, so it is compiled as today; its tiles
173
+ * do run at this version.
163
174
  */
164
- allowLayoutChange?: boolean;
175
+ queryVersionId?: string;
165
176
  };
166
177
 
167
178
  /**
@@ -217,7 +228,7 @@ export function ReportEditor(props: ReportEditorProps) {
217
228
  kind,
218
229
  path,
219
230
  textSource,
220
- allowLayoutChange,
231
+ queryVersionId,
221
232
  } = props;
222
233
  const layout: ReportLayout =
223
234
  props.layout ?? (kind ? layoutOfKind(kind) : "grid");
@@ -544,6 +555,9 @@ export function ReportEditor(props: ReportEditorProps) {
544
555
  {...(textSource ? { textSource } : {})}
545
556
  slug={dashboardName}
546
557
  {...(versionId !== undefined ? { versionId } : {})}
558
+ {...((queryVersionId ?? versionId) !== undefined
559
+ ? { queryVersionId: queryVersionId ?? versionId }
560
+ : {})}
547
561
  opened={opened}
548
562
  {...(fromDraft &&
549
563
  writer === "package" &&
@@ -556,9 +570,6 @@ export function ReportEditor(props: ReportEditorProps) {
556
570
  {...(onOpenModel ? { onOpenModel } : {})}
557
571
  {...(onControlsChange ? { onControlsChange } : {})}
558
572
  {...(draftKey !== undefined ? { draftKey } : {})}
559
- {...(allowLayoutChange !== undefined
560
- ? { allowLayoutChange }
561
- : {})}
562
573
  savesTo={savesTo}
563
574
  {...(saveLabel ? { saveLabel } : {})}
564
575
  {...(onEvent ? { onEvent: reportEvent } : {})}
@@ -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
+ });