@malloy-publisher/sdk 0.3.0 → 0.3.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (156) hide show
  1. package/README.md +8 -0
  2. package/dist/DocumentStorageProvider-BeBD0uWc.cjs.js +134 -0
  3. package/dist/DocumentStorageProvider-tGvodI8f.es.js +24268 -0
  4. package/dist/RenderedResult-CPi6uQWq.cjs.js +115 -0
  5. package/dist/RenderedResult-mDE-4u8S.es.js +542 -0
  6. package/dist/ServerProvider-CH71GsoL.cjs.js +1 -0
  7. package/dist/{ServerProvider-DSK9rfSY.es.js → ServerProvider-X2Ma0HRs.es.js} +486 -521
  8. package/dist/builder/index.cjs.js +105 -0
  9. package/dist/builder/index.d.ts +2 -0
  10. package/dist/builder/index.es.js +9561 -0
  11. package/dist/builder-entry.d.ts +8 -0
  12. package/dist/client/index.cjs.js +1 -1
  13. package/dist/client/index.es.js +1 -1
  14. package/dist/components/Dashboard/Dashboard.d.ts +19 -14
  15. package/dist/components/Dashboard/DashboardGrid.d.ts +67 -0
  16. package/dist/components/Dashboard/DashboardTile.d.ts +6 -1
  17. package/dist/components/Dashboard/ExploreDialog.d.ts +18 -0
  18. package/dist/components/Dashboard/RowsDialog.d.ts +47 -0
  19. package/dist/components/Dashboard/TileCard.d.ts +44 -0
  20. package/dist/components/Dashboard/index.d.ts +2 -0
  21. package/dist/components/Dashboard/promoteMeasureRow.d.ts +7 -3
  22. package/dist/components/Dashboard/telemetry.d.ts +43 -0
  23. package/dist/components/DashboardBuilder/AddTileDialog.d.ts +35 -0
  24. package/dist/components/DashboardBuilder/BuilderToolbar.d.ts +29 -0
  25. package/dist/components/DashboardBuilder/DashboardBuilder.d.ts +112 -0
  26. package/dist/components/DashboardBuilder/DashboardEditor.d.ts +32 -0
  27. package/dist/components/DashboardBuilder/DiffDialog.d.ts +15 -0
  28. package/dist/components/DashboardBuilder/DrillDialog.d.ts +15 -0
  29. package/dist/components/DashboardBuilder/FilterDialog.d.ts +54 -0
  30. package/dist/components/DashboardBuilder/FilterStrip.d.ts +17 -0
  31. package/dist/components/DashboardBuilder/SettingsPopover.d.ts +20 -0
  32. package/dist/components/DashboardBuilder/TileFrame.d.ts +42 -0
  33. package/dist/components/DashboardBuilder/TileMenu.d.ts +24 -0
  34. package/dist/components/DashboardBuilder/catalog.d.ts +62 -0
  35. package/dist/components/DashboardBuilder/controls.d.ts +157 -0
  36. package/dist/components/DashboardBuilder/diff.d.ts +35 -0
  37. package/dist/components/DashboardBuilder/document.d.ts +218 -0
  38. package/dist/components/DashboardBuilder/layout.d.ts +71 -0
  39. package/dist/components/DashboardBuilder/malloyText.d.ts +45 -0
  40. package/dist/components/DashboardBuilder/preview.d.ts +60 -0
  41. package/dist/components/DashboardBuilder/readDocument.d.ts +106 -0
  42. package/dist/components/DashboardBuilder/sortable.d.ts +51 -0
  43. package/dist/components/DashboardBuilder/spliceDocument.d.ts +44 -0
  44. package/dist/components/DashboardBuilder/testing/fixtures.d.ts +10 -0
  45. package/dist/components/DashboardBuilder/useBuilderShortcuts.d.ts +22 -0
  46. package/dist/components/DashboardBuilder/useDashboardEditor.d.ts +63 -0
  47. package/dist/components/DashboardBuilder/useDraft.d.ts +13 -0
  48. package/dist/components/DashboardBuilder/useFilterForm.d.ts +65 -0
  49. package/dist/components/DashboardBuilder/useTileReorder.d.ts +22 -0
  50. package/dist/components/DashboardBuilder/useTileResize.d.ts +29 -0
  51. package/dist/components/DocumentStorage/DocumentStorageProvider.d.ts +7 -0
  52. package/dist/components/DocumentStorage/index.d.ts +1 -1
  53. package/dist/components/FloatingIconButton.d.ts +16 -0
  54. package/dist/components/Prose.d.ts +46 -0
  55. package/dist/components/RenderedResult/ResultPanel.d.ts +30 -0
  56. package/dist/components/RenderedResult/index.d.ts +1 -0
  57. package/dist/components/drill/index.d.ts +1 -1
  58. package/dist/components/drill/resolveDrill.d.ts +22 -0
  59. package/dist/components/drill/useDrill.d.ts +11 -2
  60. package/dist/components/index.d.ts +1 -0
  61. package/dist/components/styles.d.ts +0 -4
  62. package/dist/hooks/index.d.ts +2 -0
  63. package/dist/hooks/useDocumentControls.d.ts +70 -0
  64. package/dist/hooks/useQueryResult.d.ts +40 -0
  65. package/dist/index.cjs.js +23 -270
  66. package/dist/index.es.js +16977 -41293
  67. package/dist/utils/malloyLiteral.d.ts +11 -0
  68. package/package.json +24 -9
  69. package/src/builder-entry.ts +55 -0
  70. package/src/components/Dashboard/Dashboard.spec.tsx +7 -10
  71. package/src/components/Dashboard/Dashboard.tsx +165 -175
  72. package/src/components/Dashboard/DashboardGrid.tsx +124 -0
  73. package/src/components/Dashboard/DashboardTile.spec.tsx +30 -6
  74. package/src/components/Dashboard/DashboardTile.tsx +66 -123
  75. package/src/components/Dashboard/ExploreDialog.tsx +84 -0
  76. package/src/components/Dashboard/RowsDialog.spec.ts +42 -0
  77. package/src/components/Dashboard/RowsDialog.tsx +234 -0
  78. package/src/components/Dashboard/TileCard.tsx +120 -0
  79. package/src/components/Dashboard/index.ts +2 -0
  80. package/src/components/Dashboard/promoteMeasureRow.spec.ts +70 -0
  81. package/src/components/Dashboard/promoteMeasureRow.ts +33 -2
  82. package/src/components/Dashboard/telemetry.ts +44 -0
  83. package/src/components/Dashboard/tileGridColumn.spec.ts +1 -1
  84. package/src/components/DashboardBuilder/AddTileDialog.tsx +249 -0
  85. package/src/components/DashboardBuilder/BuilderToolbar.tsx +270 -0
  86. package/src/components/DashboardBuilder/DashboardBuilder.spec.tsx +858 -0
  87. package/src/components/DashboardBuilder/DashboardBuilder.tsx +653 -0
  88. package/src/components/DashboardBuilder/DashboardEditor.spec.tsx +211 -0
  89. package/src/components/DashboardBuilder/DashboardEditor.tsx +493 -0
  90. package/src/components/DashboardBuilder/DiffDialog.tsx +129 -0
  91. package/src/components/DashboardBuilder/DrillDialog.tsx +281 -0
  92. package/src/components/DashboardBuilder/FilterDialog.tsx +581 -0
  93. package/src/components/DashboardBuilder/FilterStrip.tsx +125 -0
  94. package/src/components/DashboardBuilder/SettingsPopover.tsx +168 -0
  95. package/src/components/DashboardBuilder/TileFrame.tsx +380 -0
  96. package/src/components/DashboardBuilder/TileMenu.tsx +188 -0
  97. package/src/components/DashboardBuilder/catalog.spec.ts +215 -0
  98. package/src/components/DashboardBuilder/catalog.ts +225 -0
  99. package/src/components/DashboardBuilder/controls.spec.ts +243 -0
  100. package/src/components/DashboardBuilder/controls.ts +398 -0
  101. package/src/components/DashboardBuilder/diff.spec.ts +44 -0
  102. package/src/components/DashboardBuilder/diff.ts +93 -0
  103. package/src/components/DashboardBuilder/document.ts +209 -0
  104. package/src/components/DashboardBuilder/keepRowStructure.spec.ts +84 -0
  105. package/src/components/DashboardBuilder/layout.ts +143 -0
  106. package/src/components/DashboardBuilder/malloyText.spec.ts +84 -0
  107. package/src/components/DashboardBuilder/malloyText.ts +151 -0
  108. package/src/components/DashboardBuilder/moveIntoGap.spec.ts +90 -0
  109. package/src/components/DashboardBuilder/preview.spec.ts +149 -0
  110. package/src/components/DashboardBuilder/preview.ts +172 -0
  111. package/src/components/DashboardBuilder/readDocument.spec.ts +375 -0
  112. package/src/components/DashboardBuilder/readDocument.ts +467 -0
  113. package/src/components/DashboardBuilder/sortable.tsx +151 -0
  114. package/src/components/DashboardBuilder/spliceDocument.spec.ts +1108 -0
  115. package/src/components/DashboardBuilder/spliceDocument.ts +1098 -0
  116. package/src/components/DashboardBuilder/testing/fixtures.ts +48 -0
  117. package/src/components/DashboardBuilder/useBuilderShortcuts.ts +88 -0
  118. package/src/components/DashboardBuilder/useDashboardEditor.spec.ts +255 -0
  119. package/src/components/DashboardBuilder/useDashboardEditor.ts +193 -0
  120. package/src/components/DashboardBuilder/useDraft.ts +43 -0
  121. package/src/components/DashboardBuilder/useFilterForm.spec.tsx +144 -0
  122. package/src/components/DashboardBuilder/useFilterForm.ts +352 -0
  123. package/src/components/DashboardBuilder/useTileReorder.spec.tsx +97 -0
  124. package/src/components/DashboardBuilder/useTileReorder.ts +115 -0
  125. package/src/components/DashboardBuilder/useTileResize.spec.tsx +121 -0
  126. package/src/components/DashboardBuilder/useTileResize.ts +110 -0
  127. package/src/components/DashboardBuilder/withGaps.spec.ts +96 -0
  128. package/src/components/DocumentStorage/DocumentStorageProvider.tsx +12 -0
  129. package/src/components/DocumentStorage/index.ts +1 -0
  130. package/src/components/Environment/About.tsx +4 -36
  131. package/src/components/FloatingIconButton.tsx +41 -0
  132. package/src/components/Model/Model.tsx +6 -23
  133. package/src/components/Model/ModelCell.tsx +33 -72
  134. package/src/components/Notebook/Notebook.tsx +25 -88
  135. package/src/components/Notebook/NotebookCell.tsx +35 -183
  136. package/src/components/Prose.spec.tsx +85 -0
  137. package/src/components/Prose.tsx +179 -0
  138. package/src/components/QueryResult/QueryResult.tsx +15 -43
  139. package/src/components/RenderedResult/ResultContainer.tsx +4 -12
  140. package/src/components/RenderedResult/ResultPanel.spec.tsx +49 -0
  141. package/src/components/RenderedResult/ResultPanel.tsx +73 -0
  142. package/src/components/RenderedResult/index.ts +1 -0
  143. package/src/components/drill/index.ts +1 -0
  144. package/src/components/drill/resolveDrill.ts +22 -1
  145. package/src/components/drill/useDrill.spec.tsx +94 -0
  146. package/src/components/drill/useDrill.tsx +52 -12
  147. package/src/components/given/GivensPanel.tsx +1 -1
  148. package/src/components/index.ts +6 -0
  149. package/src/components/styles.ts +0 -37
  150. package/src/hooks/index.ts +13 -0
  151. package/src/hooks/useDocumentControls.ts +170 -0
  152. package/src/hooks/useQueryResult.ts +82 -0
  153. package/src/utils/malloyLiteral.spec.ts +43 -0
  154. package/src/utils/malloyLiteral.ts +76 -0
  155. package/vite.config.ts +5 -0
  156. package/dist/ServerProvider-CGnLjzag.cjs.js +0 -1
@@ -0,0 +1,48 @@
1
+ // Copyright (c) Credible Data Inc.
2
+ // SPDX-License-Identifier: MIT
3
+
4
+ import type { DashboardDocument } from "../document";
5
+ import { readDashboardDocument, readFailed } from "../readDocument";
6
+ import {
7
+ spliceDashboardDocument,
8
+ spliceFailed,
9
+ type SpliceResult,
10
+ } from "../spliceDocument";
11
+
12
+ /** The document a file produces, or a thrown reason: what a spec starts from. */
13
+ export async function openDocument(source: string): Promise<DashboardDocument> {
14
+ const result = await readDashboardDocument(source);
15
+ if (readFailed(result))
16
+ throw new Error(`expected a document: ${result.reason}`);
17
+ return result.document;
18
+ }
19
+
20
+ /** Open, edit a copy, and hand back what the writer says. */
21
+ export async function splice(
22
+ source: string,
23
+ edit: (document: DashboardDocument) => void,
24
+ ): Promise<SpliceResult> {
25
+ const next = structuredClone(await openDocument(source));
26
+ edit(next);
27
+ return spliceDashboardDocument(source, next);
28
+ }
29
+
30
+ /** `splice`, for an edit the writer is expected to accept. */
31
+ export async function spliced(
32
+ source: string,
33
+ edit: (document: DashboardDocument) => void,
34
+ ): Promise<string> {
35
+ const result = await splice(source, edit);
36
+ if (spliceFailed(result)) throw new Error(result.reason);
37
+ return result.source;
38
+ }
39
+
40
+ /** `splice`, for an edit the writer is expected to refuse; its reason. */
41
+ export async function refused(
42
+ source: string,
43
+ edit: (document: DashboardDocument) => void,
44
+ ): Promise<string> {
45
+ const result = await splice(source, edit);
46
+ if (!spliceFailed(result)) throw new Error("expected the writer to refuse");
47
+ return result.reason;
48
+ }
@@ -0,0 +1,88 @@
1
+ // Copyright (c) Credible Data Inc.
2
+ // SPDX-License-Identifier: MIT
3
+
4
+ import { useEffect, useRef } from "react";
5
+
6
+ /**
7
+ * The keyboard an editor is expected to have.
8
+ *
9
+ * Undo and redo on the platform's usual keys, save on ⌘S / Ctrl+S (which the
10
+ * browser would otherwise take), Escape to drop the selection, and the arrow
11
+ * keys to nudge the selected tile's width a column at a time — the one layout
12
+ * edit that is otherwise drag-only.
13
+ *
14
+ * Nothing but Escape fires while a text field has focus, so typing into a
15
+ * title never undoes a layout.
16
+ */
17
+ export interface BuilderShortcutHandlers {
18
+ undo: () => void;
19
+ redo: () => void;
20
+ save?: () => void;
21
+ escape: () => void;
22
+ /** Nudge the selected tile's width by ±1 column. */
23
+ nudge: (delta: 1 | -1) => void;
24
+ }
25
+
26
+ const isMac =
27
+ typeof navigator !== "undefined" &&
28
+ /Mac|iPhone|iPad/.test(navigator.platform);
29
+
30
+ /** The modifier's glyph for a tooltip. */
31
+ export const MOD = isMac ? "⌘" : "Ctrl+";
32
+
33
+ const inTextEntry = (target: EventTarget | null) => {
34
+ if (!(target instanceof HTMLElement)) return false;
35
+ if (target.isContentEditable) return true;
36
+ const tag = target.tagName;
37
+ return tag === "INPUT" || tag === "TEXTAREA" || tag === "SELECT";
38
+ };
39
+
40
+ export function useBuilderShortcuts(handlers: BuilderShortcutHandlers) {
41
+ // The handlers are read at keypress time, not bound at subscription time:
42
+ // the caller passes a fresh object every render, and a listener re-bound on
43
+ // each render would be churn that buys nothing.
44
+ const latest = useRef(handlers);
45
+ useEffect(() => {
46
+ latest.current = handlers;
47
+ });
48
+
49
+ useEffect(() => {
50
+ const onKey = (event: KeyboardEvent) => {
51
+ const current = latest.current;
52
+ const mod = isMac ? event.metaKey : event.ctrlKey;
53
+ const key = event.key.toLowerCase();
54
+ if (event.key === "Escape") {
55
+ current.escape();
56
+ return;
57
+ }
58
+ if (inTextEntry(event.target)) return;
59
+ if (mod && key === "z") {
60
+ event.preventDefault();
61
+ if (event.shiftKey) current.redo();
62
+ else current.undo();
63
+ return;
64
+ }
65
+ if (!isMac && mod && key === "y") {
66
+ event.preventDefault();
67
+ current.redo();
68
+ return;
69
+ }
70
+ if (mod && key === "s") {
71
+ event.preventDefault();
72
+ current.save?.();
73
+ return;
74
+ }
75
+ if (
76
+ !mod &&
77
+ !event.altKey &&
78
+ !event.shiftKey &&
79
+ (event.key === "ArrowLeft" || event.key === "ArrowRight")
80
+ ) {
81
+ event.preventDefault();
82
+ current.nudge(event.key === "ArrowRight" ? 1 : -1);
83
+ }
84
+ };
85
+ window.addEventListener("keydown", onKey);
86
+ return () => window.removeEventListener("keydown", onKey);
87
+ }, []);
88
+ }
@@ -0,0 +1,255 @@
1
+ // Copyright (c) Credible Data Inc.
2
+ // SPDX-License-Identifier: MIT
3
+
4
+ import { act, renderHook, waitFor } from "@testing-library/react";
5
+ import { describe, expect, it } from "bun:test";
6
+ import { openDocument } from "./testing/fixtures";
7
+ import { useDashboardEditor } from "./useDashboardEditor";
8
+
9
+ const SOURCE = `## artifact { title="Probe" tiles=["a -> by_cat", "a -> by_brand"] } dashboard { columns=12 }
10
+ import "../data_app.malloy"
11
+
12
+ source: a is scoped_orders extend {
13
+ // Kept, because a splice never rewrites what it did not change.
14
+ # colspan=6
15
+ # label="By category"
16
+ view: by_cat is by_category
17
+
18
+ # colspan=6
19
+ view: by_brand is by_brand_view
20
+ }`;
21
+
22
+ const editor = async (
23
+ onSave?: (source: string) => Promise<void> | void,
24
+ source = SOURCE,
25
+ ) => {
26
+ const document = await openDocument(source);
27
+ return renderHook(() =>
28
+ useDashboardEditor({ source, document, ...(onSave ? { onSave } : {}) }),
29
+ );
30
+ };
31
+
32
+ describe("useDashboardEditor: editing", () => {
33
+ it("applies a change to a copy, leaving the previous state intact", async () => {
34
+ const view = await editor();
35
+ const before = view.result.current.document;
36
+
37
+ act(() => {
38
+ view.result.current.update((d) => {
39
+ d.tiles[0].label = "Categories";
40
+ });
41
+ });
42
+
43
+ expect(view.result.current.document.tiles[0].label).toBe("Categories");
44
+ // The history entry it replaced is untouched, which is what makes undo a
45
+ // move rather than a reconstruction.
46
+ expect(before.tiles[0].label).toBe("By category");
47
+ });
48
+
49
+ it("is dirty only once something actually changed", async () => {
50
+ const view = await editor();
51
+ expect(view.result.current.dirty).toBe(false);
52
+
53
+ act(() => {
54
+ view.result.current.update((d) => {
55
+ d.tiles[0].colspan = 4;
56
+ });
57
+ });
58
+ expect(view.result.current.dirty).toBe(true);
59
+ });
60
+
61
+ // Otherwise a control that sets a value to what it already was would push a
62
+ // history entry, and the next undo would appear to do nothing.
63
+ it("records no history for a change that changes nothing", async () => {
64
+ const view = await editor();
65
+ act(() => {
66
+ view.result.current.update((d) => {
67
+ d.tiles[0].label = "By category";
68
+ });
69
+ });
70
+ expect(view.result.current.canUndo).toBe(false);
71
+ expect(view.result.current.dirty).toBe(false);
72
+ });
73
+ });
74
+
75
+ describe("useDashboardEditor: history", () => {
76
+ it("undoes and redoes a change", async () => {
77
+ const view = await editor();
78
+ act(() => {
79
+ view.result.current.update((d) => {
80
+ d.tiles[0].colspan = 4;
81
+ });
82
+ });
83
+ expect(view.result.current.canUndo).toBe(true);
84
+ expect(view.result.current.canRedo).toBe(false);
85
+
86
+ act(() => view.result.current.undo());
87
+ expect(view.result.current.document.tiles[0].colspan).toBe(6);
88
+ expect(view.result.current.canRedo).toBe(true);
89
+
90
+ act(() => view.result.current.redo());
91
+ expect(view.result.current.document.tiles[0].colspan).toBe(4);
92
+ });
93
+
94
+ it("walks back through several changes in order", async () => {
95
+ const view = await editor();
96
+ for (const colspan of [5, 4, 3]) {
97
+ act(() => {
98
+ view.result.current.update((d) => {
99
+ d.tiles[0].colspan = colspan;
100
+ });
101
+ });
102
+ }
103
+ act(() => view.result.current.undo());
104
+ expect(view.result.current.document.tiles[0].colspan).toBe(4);
105
+ act(() => view.result.current.undo());
106
+ expect(view.result.current.document.tiles[0].colspan).toBe(5);
107
+ act(() => view.result.current.undo());
108
+ expect(view.result.current.document.tiles[0].colspan).toBe(6);
109
+ expect(view.result.current.canUndo).toBe(false);
110
+ });
111
+
112
+ // What every editor does, and what a reader expects: the future you undid
113
+ // is gone once you take a different path.
114
+ it("discards the redo tail when you edit after undoing", async () => {
115
+ const view = await editor();
116
+ act(() => {
117
+ view.result.current.update((d) => {
118
+ d.tiles[0].colspan = 4;
119
+ });
120
+ });
121
+ act(() => view.result.current.undo());
122
+ act(() => {
123
+ view.result.current.update((d) => {
124
+ d.tiles[0].colspan = 2;
125
+ });
126
+ });
127
+ expect(view.result.current.canRedo).toBe(false);
128
+ expect(view.result.current.document.tiles[0].colspan).toBe(2);
129
+ });
130
+
131
+ it("does nothing at the ends of the history", async () => {
132
+ const view = await editor();
133
+ act(() => view.result.current.undo());
134
+ act(() => view.result.current.redo());
135
+ expect(view.result.current.document.tiles[0].colspan).toBe(6);
136
+ });
137
+ });
138
+
139
+ describe("useDashboardEditor: saving", () => {
140
+ it("splices the change into the file and keeps its comments", async () => {
141
+ let written: string | undefined;
142
+ const view = await editor((source) => {
143
+ written = source;
144
+ });
145
+
146
+ act(() => {
147
+ view.result.current.update((d) => {
148
+ d.tiles[0].label = "Categories";
149
+ });
150
+ });
151
+ await act(async () => {
152
+ await view.result.current.save();
153
+ });
154
+
155
+ expect(written).toContain('# label="Categories"');
156
+ expect(written).toContain(
157
+ " // Kept, because a splice never rewrites what it did not change.",
158
+ );
159
+ await waitFor(() => expect(view.result.current.dirty).toBe(false));
160
+ });
161
+
162
+ // The second save has to patch what is now on disk, not the text the session
163
+ // opened with, or it would splice against a stale file.
164
+ it("saves twice, the second against the first result", async () => {
165
+ const written: string[] = [];
166
+ const view = await editor((source) => {
167
+ written.push(source);
168
+ });
169
+
170
+ act(() => {
171
+ view.result.current.update((d) => {
172
+ d.tiles[0].label = "One";
173
+ });
174
+ });
175
+ await act(async () => {
176
+ await view.result.current.save();
177
+ });
178
+ act(() => {
179
+ view.result.current.update((d) => {
180
+ d.tiles[1].label = "Two";
181
+ });
182
+ });
183
+ await act(async () => {
184
+ await view.result.current.save();
185
+ });
186
+
187
+ expect(written).toHaveLength(2);
188
+ expect(written[1]).toContain('# label="One"');
189
+ expect(written[1]).toContain('# label="Two"');
190
+ });
191
+
192
+ // The rule the whole writer rests on: a refused write keeps the work.
193
+ it("keeps the edit when the writer refuses", async () => {
194
+ let called = false;
195
+ const view = await editor(() => {
196
+ called = true;
197
+ });
198
+
199
+ act(() => {
200
+ view.result.current.update((d) => {
201
+ // An import is not the builder's to change, so this is refused.
202
+ // (Tiles, settings and the page's own givens are NOT: the writer
203
+ // handles those, and the builder shows a diff for the structural ones.)
204
+ d.imports.push({ kind: "all", from: "../more.malloy" });
205
+ });
206
+ });
207
+ await act(async () => {
208
+ expect((await view.result.current.save()).ok).toBe(false);
209
+ });
210
+
211
+ expect(called).toBe(false);
212
+ expect(view.result.current.error).toContain("imports");
213
+ // Still there, still dirty. The reader can undo or try something else.
214
+ expect(view.result.current.document.imports).toHaveLength(2);
215
+ expect(view.result.current.dirty).toBe(true);
216
+ });
217
+
218
+ it("stays dirty when storage rejects the write", async () => {
219
+ const view = await editor(() => {
220
+ throw new Error("disk full");
221
+ });
222
+ act(() => {
223
+ view.result.current.update((d) => {
224
+ d.tiles[0].colspan = 4;
225
+ });
226
+ });
227
+ await act(async () => {
228
+ expect((await view.result.current.save()).ok).toBe(false);
229
+ });
230
+ expect(view.result.current.error).toContain("disk full");
231
+ expect(view.result.current.dirty).toBe(true);
232
+ });
233
+
234
+ it("clears the error once an edit is made", async () => {
235
+ const view = await editor(() => {
236
+ throw new Error("disk full");
237
+ });
238
+ act(() => {
239
+ view.result.current.update((d) => {
240
+ d.tiles[0].colspan = 4;
241
+ });
242
+ });
243
+ await act(async () => {
244
+ await view.result.current.save();
245
+ });
246
+ expect(view.result.current.error).toBeDefined();
247
+
248
+ act(() => {
249
+ view.result.current.update((d) => {
250
+ d.tiles[0].colspan = 3;
251
+ });
252
+ });
253
+ expect(view.result.current.error).toBeUndefined();
254
+ });
255
+ });
@@ -0,0 +1,193 @@
1
+ // Copyright (c) Credible Data Inc.
2
+ // SPDX-License-Identifier: MIT
3
+
4
+ import { useCallback, useMemo, useState } from "react";
5
+ import { tileKey, type DashboardDocument } from "./document";
6
+ import { spliceDashboardDocument, spliceFailed } from "./spliceDocument";
7
+
8
+ /**
9
+ * The editor's state: the document being edited, its history, and saving.
10
+ *
11
+ * Deliberately holds the DOCUMENT and nothing else. Given VALUES — what the
12
+ * preview is running with — are editor state rather than document state and
13
+ * live outside this hook, which is what keeps them out of the undo stack. Undo
14
+ * should take back a layout change; it should not rewind the filter someone was
15
+ * previewing under.
16
+ */
17
+
18
+ export interface DashboardEditor {
19
+ document: DashboardDocument;
20
+ /** The file as it currently stands, which is what a save patches. */
21
+ source: string;
22
+ canUndo: boolean;
23
+ canRedo: boolean;
24
+ /** Whether the document has changes the file does not have yet. */
25
+ dirty: boolean;
26
+ /**
27
+ * Why the last save did not happen. The document is untouched when this is
28
+ * set: a refused write keeps the reader's work and reports a defect in the
29
+ * writer, rather than discarding an edit because a tool could not read back
30
+ * what it produced.
31
+ */
32
+ error?: string;
33
+ /** Apply a change. Receives a copy; mutate it freely. */
34
+ update: (change: (draft: DashboardDocument) => void) => void;
35
+ undo: () => void;
36
+ redo: () => void;
37
+ /** Splice the change into the file, or say why it was refused. */
38
+ save: () => Promise<SaveOutcome>;
39
+ /**
40
+ * The file a save would write, without writing it: what a diff preview
41
+ * shows. The failure arm is the writer's refusal, worded for the author.
42
+ */
43
+ preview: () => Promise<
44
+ { ok: true; source: string } | { ok: false; reason: string }
45
+ >;
46
+ /**
47
+ * Whether the unsaved change adds or removes a tile. Those moves touch
48
+ * declarations and the comments beside them, which is when a save is worth
49
+ * showing as a diff first; a property edit never is.
50
+ */
51
+ structural: boolean;
52
+ }
53
+
54
+ export type SaveOutcome = { ok: true } | { ok: false; reason: string };
55
+
56
+ interface History {
57
+ /** Every document state, oldest first. */
58
+ stack: DashboardDocument[];
59
+ /** Which one is current. Undo and redo move this rather than mutating. */
60
+ index: number;
61
+ }
62
+
63
+ /**
64
+ * How many documents of history to keep.
65
+ *
66
+ * A whole document per entry is affordable because the document is small and
67
+ * immutable — it is a list of tiles and their presentation, not the file. Keeping
68
+ * whole states is also what makes undo trivially correct: there is no inverse
69
+ * operation to get wrong for each kind of edit.
70
+ */
71
+ const HISTORY_LIMIT = 100;
72
+
73
+ export function useDashboardEditor(options: {
74
+ /** The file as read from storage. */
75
+ source: string;
76
+ /** The document that file produced. */
77
+ document: DashboardDocument;
78
+ /** Persist the patched file. Rejecting leaves the editor dirty. */
79
+ onSave?: (source: string) => Promise<void> | void;
80
+ }): DashboardEditor {
81
+ const [history, setHistory] = useState<History>({
82
+ stack: [options.document],
83
+ index: 0,
84
+ });
85
+ const [source, setSource] = useState(options.source);
86
+ const [error, setError] = useState<string | undefined>(undefined);
87
+
88
+ // What the file currently holds, so `dirty` compares against the saved state
89
+ // rather than against where the session started.
90
+ //
91
+ // State, not a ref, and the difference is visible: `dirty` is derived from
92
+ // it, and a ref write does not re-render, so a successful save left the
93
+ // editor reporting unsaved changes it had just written.
94
+ const [saved, setSaved] = useState(options.document);
95
+
96
+ const document = history.stack[history.index];
97
+
98
+ const update = useCallback((change: (draft: DashboardDocument) => void) => {
99
+ setError(undefined);
100
+ setHistory((previous) => {
101
+ const draft = structuredClone(previous.stack[previous.index]);
102
+ change(draft);
103
+ // A change that changes nothing does not deserve a history entry;
104
+ // otherwise a click that sets a value to what it already was makes
105
+ // undo appear broken.
106
+ if (
107
+ JSON.stringify(draft) ===
108
+ JSON.stringify(previous.stack[previous.index])
109
+ )
110
+ return previous;
111
+ // Editing after undo discards the redo tail, which is what every
112
+ // editor does and what a reader expects.
113
+ const kept = previous.stack.slice(0, previous.index + 1);
114
+ const stack = [...kept, draft].slice(-HISTORY_LIMIT);
115
+ return { stack, index: stack.length - 1 };
116
+ });
117
+ }, []);
118
+
119
+ const undo = useCallback(() => {
120
+ setError(undefined);
121
+ setHistory((previous) =>
122
+ previous.index > 0
123
+ ? { ...previous, index: previous.index - 1 }
124
+ : previous,
125
+ );
126
+ }, []);
127
+
128
+ const redo = useCallback(() => {
129
+ setError(undefined);
130
+ setHistory((previous) =>
131
+ previous.index < previous.stack.length - 1
132
+ ? { ...previous, index: previous.index + 1 }
133
+ : previous,
134
+ );
135
+ }, []);
136
+
137
+ const save = useCallback(async (): Promise<SaveOutcome> => {
138
+ const result = await spliceDashboardDocument(source, document);
139
+ if (spliceFailed(result)) {
140
+ setError(result.reason);
141
+ return { ok: false, reason: result.reason };
142
+ }
143
+ try {
144
+ await options.onSave?.(result.source);
145
+ } catch (failure) {
146
+ // The file may or may not have been written; what is certain is that
147
+ // the editor must not pretend it was. Staying dirty is the safe read.
148
+ const reason = `Could not save: ${failure}`;
149
+ setError(reason);
150
+ return { ok: false, reason };
151
+ }
152
+ // The patched file is the new baseline, so a second save patches what is
153
+ // now on disk rather than re-deriving from the text this session opened.
154
+ setSource(result.source);
155
+ setSaved(document);
156
+ setError(undefined);
157
+ return { ok: true };
158
+ }, [document, options, source]);
159
+
160
+ const dirty = useMemo(
161
+ () => JSON.stringify(document) !== JSON.stringify(saved),
162
+ [document, saved],
163
+ );
164
+ const structural = useMemo(() => {
165
+ const before = new Set(saved.tiles.map(tileKey));
166
+ const after = new Set(document.tiles.map(tileKey));
167
+ return (
168
+ [...before].some((k) => !after.has(k)) ||
169
+ [...after].some((k) => !before.has(k))
170
+ );
171
+ }, [document, saved]);
172
+ const preview = useCallback(async () => {
173
+ const result = await spliceDashboardDocument(source, document);
174
+ return spliceFailed(result)
175
+ ? { ok: false as const, reason: result.reason }
176
+ : { ok: true as const, source: result.source };
177
+ }, [document, source]);
178
+
179
+ return {
180
+ document,
181
+ source,
182
+ canUndo: history.index > 0,
183
+ canRedo: history.index < history.stack.length - 1,
184
+ dirty,
185
+ ...(error === undefined ? {} : { error }),
186
+ update,
187
+ undo,
188
+ redo,
189
+ save,
190
+ preview,
191
+ structural,
192
+ };
193
+ }
@@ -0,0 +1,43 @@
1
+ // Copyright (c) Credible Data Inc.
2
+ // SPDX-License-Identifier: MIT
3
+
4
+ import { useEffect, useState } from "react";
5
+
6
+ /**
7
+ * A copy of `value` to edit while a window is open, committed ONCE when it
8
+ * closes, and only if something changed.
9
+ *
10
+ * Per-keystroke commits would put a document in the undo stack for every
11
+ * letter typed into a title, and undo would then walk back through the word.
12
+ */
13
+ export function useDraft<T>(
14
+ value: T | undefined,
15
+ open: boolean,
16
+ onCommit: (next: T) => void,
17
+ onClose: () => void,
18
+ ) {
19
+ const [draft, setDraft] = useState<T | undefined>(undefined);
20
+ useEffect(() => {
21
+ if (open && value !== undefined) setDraft(structuredClone(value));
22
+ }, [open, value]);
23
+
24
+ const close = () => {
25
+ if (
26
+ draft !== undefined &&
27
+ value !== undefined &&
28
+ JSON.stringify(draft) !== JSON.stringify(value)
29
+ )
30
+ onCommit(draft);
31
+ onClose();
32
+ };
33
+ const patch = (change: (draft: T) => void) =>
34
+ setDraft((previous) => {
35
+ if (previous === undefined) return previous;
36
+ const next = structuredClone(previous);
37
+ change(next);
38
+ return next;
39
+ });
40
+ /** Drop the draft without committing: for an action that supersedes it. */
41
+ const discard = () => setDraft(undefined);
42
+ return { draft, patch, close, discard };
43
+ }