@malloy-publisher/sdk 0.8.1 → 0.8.2

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 (34) hide show
  1. package/dist/{DocumentStorage-D7yF4_T3.cjs.js → DocumentStorage-B0_YgSzt.cjs.js} +32 -32
  2. package/dist/{DocumentStorage-BCpTBa7U.es.js → DocumentStorage-BZqn0x5r.es.js} +3826 -3741
  3. package/dist/{RenderedResult-ChkvK7b2.cjs.js → RenderedResult-Bu25oAAr.cjs.js} +1 -1
  4. package/dist/{RenderedResult-CDA9mN_6.es.js → RenderedResult-DKOl0FQ8.es.js} +2 -2
  5. package/dist/{ServerProvider-CvMqBhuj.es.js → ServerProvider-CfUFleYe.es.js} +4 -4
  6. package/dist/builder/index.cjs.js +1 -1
  7. package/dist/builder/index.es.js +2 -2
  8. package/dist/client/api.d.ts +10 -4
  9. package/dist/client/index.es.js +1 -1
  10. package/dist/components/Dashboard/ExploreDialog.d.ts +3 -1
  11. package/dist/components/Model/Model.d.ts +10 -3
  12. package/dist/components/Model/ModelExplorer.d.ts +21 -1
  13. package/dist/components/Model/ModelExplorerDialog.d.ts +4 -1
  14. package/dist/components/Model/SourcesExplorer.d.ts +8 -1
  15. package/dist/components/Model/index.d.ts +1 -0
  16. package/dist/components/Model/runGate.d.ts +19 -0
  17. package/dist/components/Notebook/NotebookCell.d.ts +10 -1
  18. package/dist/index.cjs.js +13 -13
  19. package/dist/index.es.js +3754 -3732
  20. package/package.json +1 -1
  21. package/src/components/Dashboard/Dashboard.spec.tsx +58 -2
  22. package/src/components/Dashboard/Dashboard.tsx +8 -1
  23. package/src/components/Dashboard/ExploreDialog.tsx +5 -0
  24. package/src/components/Model/Model.tsx +28 -1
  25. package/src/components/Model/ModelExplorer.spec.tsx +404 -0
  26. package/src/components/Model/ModelExplorer.tsx +65 -2
  27. package/src/components/Model/ModelExplorerDialog.tsx +12 -0
  28. package/src/components/Model/SourcesExplorer.tsx +70 -15
  29. package/src/components/Model/index.ts +1 -0
  30. package/src/components/Model/runGate.spec.ts +102 -0
  31. package/src/components/Model/runGate.ts +67 -0
  32. package/src/components/Notebook/Notebook.spec.tsx +67 -3
  33. package/src/components/Notebook/Notebook.tsx +12 -2
  34. package/src/components/Notebook/NotebookCell.tsx +26 -7
@@ -4,12 +4,16 @@
4
4
  import { Box, Stack } from "@mui/material";
5
5
  import Autocomplete from "@mui/material/Autocomplete";
6
6
  import TextField from "@mui/material/TextField";
7
- import React from "react";
7
+ import React, { useMemo } from "react";
8
8
  import { CompiledModel } from "../../client";
9
+ import { useDocumentControls } from "../../hooks/useDocumentControls";
9
10
  import { parseResourceUri } from "../../utils/formatting";
10
11
  import { ApiErrorDisplay } from "../ApiErrorDisplay";
12
+ import { GivensPanel } from "../given";
13
+ import { givensToRequest } from "../given/paramCodec";
11
14
  import { Loading } from "../Loading";
12
15
  import { StyledCard, StyledCardContent, StyledCardMedia } from "../styles";
16
+ import { runGate } from "./runGate";
13
17
  import { QueryExplorerResult, SourcesExplorer } from "./SourcesExplorer";
14
18
  import { useModelData } from "./useModelData";
15
19
 
@@ -53,6 +57,29 @@ export interface ModelExplorerProps {
53
57
  /** Callback when source selection changes */
54
58
  onSourceChange?: (index: number) => void;
55
59
  resourceUri: string;
60
+ /**
61
+ * Control values from the host, typically its URL query parameters. These
62
+ * beat the model's own starting values, so a shared link shows what the
63
+ * sender was looking at.
64
+ */
65
+ givens?: Record<string, string>;
66
+ /**
67
+ * Applied control values, for a host that wants them in its URL.
68
+ *
69
+ * `managed` is every given this model declares, whether or not it currently
70
+ * holds a value, and a host writing to a shared query string needs it.
71
+ * `givens` alone says which parameters to write but not which to REMOVE, so
72
+ * a host that guesses by deleting everything it did not just receive
73
+ * deletes the unrelated parameters it has no business touching. Same
74
+ * contract as `Dashboard` and `Notebook`, so a host can treat every surface
75
+ * alike.
76
+ */
77
+ onGivensChange?: (
78
+ givens: Record<string, string>,
79
+ managed: readonly string[],
80
+ ) => void;
81
+ /** Where the controls start, from the host, e.g. a dashboard tile's values. */
82
+ startingGivens?: Record<string, string>;
56
83
  }
57
84
 
58
85
  /**
@@ -68,6 +95,9 @@ export function ModelExplorer({
68
95
  initialSelectedSourceIndex = 0,
69
96
  onSourceChange,
70
97
  resourceUri,
98
+ givens,
99
+ onGivensChange,
100
+ startingGivens,
71
101
  }: ModelExplorerProps) {
72
102
  const [selectedTab, setSelectedTab] = React.useState(
73
103
  initialSelectedSourceIndex,
@@ -85,10 +115,40 @@ export function ModelExplorer({
85
115
  isLoading,
86
116
  error,
87
117
  } = useModelData(resourceUri, !data); // we shld only fetch when data is not provided
88
- const { modelPath } = parseResourceUri(resourceUri);
118
+ const { environmentName, packageName, modelPath, versionId } =
119
+ parseResourceUri(resourceUri);
89
120
 
90
121
  const effectiveData = data || fetchedData;
91
122
 
123
+ // Above the early returns, which would otherwise skip these hooks.
124
+ const specs = React.useMemo(
125
+ () => effectiveData?.givens ?? [],
126
+ [effectiveData],
127
+ );
128
+ const controls = useDocumentControls({
129
+ specs,
130
+ loaded: !!effectiveData,
131
+ params: givens,
132
+ onGivensChange,
133
+ startingValues: startingGivens,
134
+ documentKey: resourceUri,
135
+ // No Apply button: the Explorer already waits for an explicit Run.
136
+ autorun: true,
137
+ environmentName: environmentName ?? "",
138
+ packageName: packageName ?? "",
139
+ modelPath,
140
+ versionId,
141
+ documentName: modelPath,
142
+ });
143
+ const requestGivens = useMemo(
144
+ () => givensToRequest(controls.applied, controls.declaredTypes),
145
+ [controls.applied, controls.declaredTypes],
146
+ );
147
+ const gate = useMemo(
148
+ () => runGate(specs, controls.applied),
149
+ [specs, controls.applied],
150
+ );
151
+
92
152
  if (isLoading && !data) {
93
153
  return <Loading text="Fetching Model..." />;
94
154
  }
@@ -180,6 +240,7 @@ export function ModelExplorer({
180
240
  />
181
241
  </Stack>
182
242
  </StyledCardContent>
243
+ <GivensPanel {...controls.panel} />
183
244
  <StyledCardMedia>
184
245
  <Stack spacing={2} component="section">
185
246
  {/* Render the selected source info */}
@@ -199,6 +260,8 @@ export function ModelExplorer({
199
260
  existingQuery={existingQuery}
200
261
  onQueryChange={onChange}
201
262
  resourceUri={resourceUri}
263
+ givens={requestGivens}
264
+ gate={gate}
202
265
  />
203
266
  )}
204
267
 
@@ -19,6 +19,12 @@ interface ModelExplorerDialogProps {
19
19
  initialSelectedSourceIndex?: number;
20
20
  onChange?: (query: QueryExplorerResult) => void;
21
21
  onSourceChange?: (index: number) => void;
22
+ givens?: Record<string, string>;
23
+ onGivensChange?: (
24
+ givens: Record<string, string>,
25
+ managed: readonly string[],
26
+ ) => void;
27
+ startingGivens?: Record<string, string>;
22
28
  }
23
29
 
24
30
  export function ModelExplorerDialog({
@@ -32,6 +38,9 @@ export function ModelExplorerDialog({
32
38
  initialSelectedSourceIndex,
33
39
  onChange,
34
40
  onSourceChange,
41
+ givens,
42
+ onGivensChange,
43
+ startingGivens,
35
44
  }: ModelExplorerDialogProps) {
36
45
  return (
37
46
  <Dialog open={open} onClose={onClose} fullScreen>
@@ -56,6 +65,9 @@ export function ModelExplorerDialog({
56
65
  initialSelectedSourceIndex={initialSelectedSourceIndex}
57
66
  onChange={onChange}
58
67
  onSourceChange={onSourceChange}
68
+ givens={givens}
69
+ onGivensChange={onGivensChange}
70
+ startingGivens={startingGivens}
59
71
  />
60
72
  ) : (
61
73
  <div>No valid import statement found in cell</div>
@@ -2,6 +2,7 @@
2
2
  // SPDX-License-Identifier: MIT
3
3
 
4
4
  import * as Malloy from "@malloydata/malloy-interfaces";
5
+ import type { Message } from "@malloydata/malloy-explorer";
5
6
  import { Box, Stack } from "@mui/system";
6
7
  import {
7
8
  StyledCardMedia,
@@ -14,6 +15,7 @@ import { useMutationWithApiError } from "../../hooks/useQueryWithApiError";
14
15
  import { parseResourceUri } from "../../utils/formatting";
15
16
  // import { ApiErrorDisplay } from "../ApiErrorDisplay";
16
17
  import { useServer } from "../ServerProvider";
18
+ import { missingGivensHint, type RunGate } from "./runGate";
17
19
 
18
20
  type ExplorerComponents = typeof import("@malloydata/malloy-explorer");
19
21
  type QueryBuilder = typeof import("@malloydata/malloy-query-builder");
@@ -30,6 +32,10 @@ export interface SourceExplorerProps {
30
32
  onQueryChange?: (query: QueryExplorerResult) => void;
31
33
  onSourceChange?: (index: number) => void;
32
34
  resourceUri: string;
35
+ /** The control row's current values, sent with every Run. */
36
+ givens?: Record<string, unknown>;
37
+ /** What the control row leaves unset, for the words around a result or a refusal. */
38
+ gate?: RunGate;
33
39
  }
34
40
 
35
41
  /**
@@ -46,6 +52,8 @@ export function SourcesExplorer({
46
52
  onQueryChange,
47
53
  onSourceChange,
48
54
  resourceUri,
55
+ givens,
56
+ gate,
49
57
  }: SourceExplorerProps) {
50
58
  // Notify parent component when selected source changes
51
59
  React.useEffect(() => {
@@ -66,6 +74,8 @@ export function SourcesExplorer({
66
74
  }
67
75
  }}
68
76
  resourceUri={resourceUri}
77
+ givens={givens}
78
+ gate={gate}
69
79
  />
70
80
  <Box height="5px" />
71
81
  </Stack>
@@ -78,6 +88,8 @@ interface SourceExplorerComponentProps {
78
88
  existingQuery?: QueryExplorerResult;
79
89
  onChange?: (query: QueryExplorerResult) => void;
80
90
  resourceUri: string;
91
+ givens?: Record<string, unknown>;
92
+ gate?: RunGate;
81
93
  }
82
94
 
83
95
  export interface QueryExplorerResult {
@@ -100,6 +112,8 @@ function SourceExplorerComponentInner({
100
112
  explorerComponents,
101
113
  QueryBuilder,
102
114
  resourceUri,
115
+ givens,
116
+ gate,
103
117
  }: SourceExplorerComponentProps & {
104
118
  explorerComponents: ExplorerComponents;
105
119
  QueryBuilder: QueryBuilder;
@@ -112,7 +126,8 @@ function SourceExplorerComponentInner({
112
126
  | {
113
127
  executionState: "running" | "finished";
114
128
  response: {
115
- result: Malloy.Result;
129
+ result?: Malloy.Result;
130
+ messages?: Message[];
116
131
  };
117
132
  query: Malloy.Query | string;
118
133
  queryResolutionStartMillis: number;
@@ -151,18 +166,14 @@ function SourceExplorerComponentInner({
151
166
  } = parseResourceUri(resourceUri);
152
167
  const { apiClients } = useServer();
153
168
 
169
+ // Captured at Run, so the defaults note describes the run that produced the result.
170
+ const gateAtRunRef = React.useRef<RunGate | undefined>(undefined);
171
+
154
172
  const mutation = useMutationWithApiError({
155
173
  mutationFn: () => {
156
- // If malloyQuery is a string, we can use it directly, otherwise convert to Malloy
157
- const malloy =
158
- typeof query?.malloyQuery === "string"
159
- ? query.malloyQuery
160
- : new QueryBuilder.ASTQuery({
161
- source: sourceAndPath.sourceInfo,
162
- query: query?.malloyQuery,
163
- }).toMalloy();
164
-
165
- // Set submitted query when execution starts
174
+ gateAtRunRef.current = gate;
175
+ // Before building the Malloy, so a build that throws still has a run
176
+ // for `onError` to report into.
166
177
  setSubmittedQuery({
167
178
  executionState: "running",
168
179
  query: query?.malloyQuery,
@@ -171,11 +182,18 @@ function SourceExplorerComponentInner({
171
182
  mutation.reset();
172
183
  setSubmittedQuery(undefined);
173
184
  },
174
- response: {
175
- result: {} as Malloy.Result, // placeholder
176
- },
185
+ response: {},
177
186
  });
178
187
 
188
+ // If malloyQuery is a string, we can use it directly, otherwise convert to Malloy
189
+ const malloy =
190
+ typeof query?.malloyQuery === "string"
191
+ ? query.malloyQuery
192
+ : new QueryBuilder.ASTQuery({
193
+ source: sourceAndPath.sourceInfo,
194
+ query: query?.malloyQuery,
195
+ }).toMalloy();
196
+
179
197
  setQuery({
180
198
  ...query,
181
199
  query: malloy,
@@ -189,6 +207,8 @@ function SourceExplorerComponentInner({
189
207
  sourceName: undefined,
190
208
  queryName: undefined,
191
209
  versionId: versionId,
210
+ // Omitted when empty, so a model with no givens sends the same body as before.
211
+ ...(givens && Object.keys(givens).length > 0 ? { givens } : {}),
192
212
  },
193
213
  );
194
214
  },
@@ -199,6 +219,7 @@ function SourceExplorerComponentInner({
199
219
  ...query,
200
220
  malloyResult: parsedResult as Malloy.Result,
201
221
  });
222
+ const ranGate = gateAtRunRef.current;
202
223
  // Update submitted query with results
203
224
  setSubmittedQuery((prev) =>
204
225
  prev
@@ -207,6 +228,16 @@ function SourceExplorerComponentInner({
207
228
  executionState: "finished",
208
229
  response: {
209
230
  result: parsedResult as Malloy.Result,
231
+ ...(ranGate?.defaultsNote
232
+ ? {
233
+ messages: [
234
+ {
235
+ severity: "INFO",
236
+ title: ranGate.defaultsNote,
237
+ },
238
+ ],
239
+ }
240
+ : {}),
210
241
  },
211
242
  }
212
243
  : undefined,
@@ -214,8 +245,32 @@ function SourceExplorerComponentInner({
214
245
  }
215
246
  },
216
247
  onError: (error) => {
217
- setSubmittedQuery(undefined);
218
248
  console.error("Query execution error:", error);
249
+ const message =
250
+ (error as { data?: { message?: string } } | undefined)?.data
251
+ ?.message ??
252
+ (error as Error | undefined)?.message ??
253
+ "The query could not be run.";
254
+ const messages: Message[] = [{ severity: "ERROR", title: message }];
255
+ // A gate's 403 names only the source, so say which blank givens it may want.
256
+ const missing = gateAtRunRef.current?.missing ?? [];
257
+ const refused =
258
+ (error as { status?: number } | undefined)?.status === 403 ||
259
+ /Access denied for source/i.test(message);
260
+ if (refused && missing.length > 0) {
261
+ messages.push({
262
+ severity: "WARN",
263
+ title: missingGivensHint(missing),
264
+ });
265
+ }
266
+ // Shown in the results pane rather than cleared, so the server's
267
+ // reason is visible. No run means Cancel cleared it: a late failure
268
+ // from that request must not bring the pane back.
269
+ setSubmittedQuery((prev) =>
270
+ prev
271
+ ? { ...prev, executionState: "finished", response: { messages } }
272
+ : undefined,
273
+ );
219
274
  },
220
275
  });
221
276
 
@@ -2,6 +2,7 @@
2
2
  // SPDX-License-Identifier: MIT
3
3
 
4
4
  export { default as Model } from "./Model";
5
+ export type { ModelProps } from "./Model";
5
6
  export { ModelExplorer } from "./ModelExplorer";
6
7
  export { ModelExplorerDialog } from "./ModelExplorerDialog";
7
8
  export { SourcesExplorer } from "./SourcesExplorer";
@@ -0,0 +1,102 @@
1
+ // Copyright (c) Credible Data Inc.
2
+ // SPDX-License-Identifier: MIT
3
+
4
+ import { describe, expect, it } from "bun:test";
5
+ import type { Given } from "../../client";
6
+ import type { GivenValue } from "../../hooks/givenValue";
7
+ import { missingGivensHint, runGate } from "./runGate";
8
+
9
+ const values = (entries: Record<string, GivenValue>) =>
10
+ new Map<string, GivenValue>(Object.entries(entries));
11
+
12
+ describe("runGate", () => {
13
+ it("reports nothing with no declared givens", () => {
14
+ expect(runGate([], values({}))).toEqual({ missing: [] });
15
+ });
16
+
17
+ it("reports nothing when every given is set", () => {
18
+ const givens: Given[] = [{ name: "TENANT" }, { name: "REGION" }];
19
+ expect(runGate(givens, values({ TENANT: "acme", REGION: "us" }))).toEqual(
20
+ { missing: [] },
21
+ );
22
+ });
23
+
24
+ it("lists unset givens that have no default", () => {
25
+ const givens: Given[] = [{ name: "TENANT" }, { name: "REGION" }];
26
+ expect(runGate(givens, values({})).missing).toEqual(["TENANT", "REGION"]);
27
+ });
28
+
29
+ it("treats a null default as no default", () => {
30
+ // The API sends `default: null` for some types rather than omitting it.
31
+ const givens = [
32
+ { name: "TENANTS", type: "string[]", default: null },
33
+ ] as unknown as Given[];
34
+ expect(runGate(givens, values({}))).toEqual({ missing: ["TENANTS"] });
35
+ });
36
+
37
+ it("notes a default that an unset given fell back to", () => {
38
+ const givens: Given[] = [{ name: "X", default: "5" }];
39
+ expect(runGate(givens, values({}))).toEqual({
40
+ missing: [],
41
+ defaultsNote: "Ran with the default X = 5",
42
+ });
43
+ });
44
+
45
+ it("names only the defaulted givens when some are set and some default", () => {
46
+ const givens: Given[] = [
47
+ { name: "X", default: "5" },
48
+ { name: "Y", default: "'a'" },
49
+ { name: "Z" },
50
+ ];
51
+ expect(runGate(givens, values({ Z: "set" }))).toEqual({
52
+ missing: [],
53
+ defaultsNote: "Ran with defaults X = 5, Y = a",
54
+ });
55
+ });
56
+
57
+ it("spells defaults as the panel does and leaves empty filters out", () => {
58
+ const givens: Given[] = [
59
+ { name: "CATEGORY", type: "filter<string>", default: "f''" },
60
+ { name: "SINCE", type: "date", default: "@2023-01-01" },
61
+ ];
62
+ expect(runGate(givens, values({})).defaultsNote).toBe(
63
+ "Ran with the default SINCE = 2023-01-01",
64
+ );
65
+ });
66
+
67
+ it("adds no note when every unset default is an empty filter", () => {
68
+ const givens: Given[] = [
69
+ { name: "CATEGORY", type: "filter<string>", default: "f''" },
70
+ ];
71
+ expect(runGate(givens, values({}))).toEqual({ missing: [] });
72
+ });
73
+
74
+ it("counts an empty string as set, since it is sent rather than defaulted", () => {
75
+ const givens: Given[] = [
76
+ { name: "TENANT" },
77
+ { name: "REGION", type: "filter<string>", default: "f'West'" },
78
+ ];
79
+ expect(runGate(givens, values({ TENANT: "", REGION: "" }))).toEqual({
80
+ missing: [],
81
+ });
82
+ });
83
+
84
+ it("skips a spec with no name", () => {
85
+ const givens: Given[] = [{ type: "string" }];
86
+ expect(runGate(givens, values({}))).toEqual({ missing: [] });
87
+ });
88
+ });
89
+
90
+ describe("missingGivensHint", () => {
91
+ it("uses the singular wording for one given", () => {
92
+ expect(missingGivensHint(["TENANT"])).toBe(
93
+ "This source may need a value for the given TENANT. Set it in the parameters above.",
94
+ );
95
+ });
96
+
97
+ it("uses the plural wording for several", () => {
98
+ expect(missingGivensHint(["TENANT", "REGION"])).toBe(
99
+ "This source may need values for the givens TENANT, REGION. Set them in the parameters above.",
100
+ );
101
+ });
102
+ });
@@ -0,0 +1,67 @@
1
+ // Copyright (c) Credible Data Inc.
2
+ // SPDX-License-Identifier: MIT
3
+
4
+ import type { Given } from "../../client";
5
+ import type { GivenValue } from "../../hooks/givenValue";
6
+ import { renderGivenDefault } from "../given/utils";
7
+
8
+ /**
9
+ * What a Run is about to send, measured against the model's declared givens.
10
+ *
11
+ * Nothing here refuses a Run. Givens are declared model-wide but read per
12
+ * source, and nothing on the client says which source reads which, so a blank
13
+ * given with no default may be exactly right for the source being explored.
14
+ * The server decides; this only supplies the words around its answer.
15
+ */
16
+ export interface RunGate {
17
+ /** Unset givens with no default: named in a hint when the server refuses. */
18
+ missing: string[];
19
+ /** Set when an unset given fell back to a non-empty default. */
20
+ defaultsNote?: string;
21
+ }
22
+
23
+ /**
24
+ * Unset means exactly what `givensToRequest` leaves out of the request. An
25
+ * empty string is not unset: for a string or filter given it is a value the
26
+ * reader typed, and it is sent, so the default does not apply.
27
+ */
28
+ function isSet(value: GivenValue | undefined): boolean {
29
+ return value !== null && value !== undefined;
30
+ }
31
+
32
+ export function runGate(
33
+ givens: readonly Given[],
34
+ values: ReadonlyMap<string, GivenValue>,
35
+ ): RunGate {
36
+ const missing: string[] = [];
37
+ const defaults: string[] = [];
38
+ for (const given of givens) {
39
+ if (given.name === undefined) continue;
40
+ if (isSet(values.get(given.name))) continue;
41
+ // `==`, not `===`: the API sends a missing default as null for some types.
42
+ if (given.default == null) {
43
+ missing.push(given.name);
44
+ continue;
45
+ }
46
+ // Spelled as the panel's "Default:" caption; an empty default (an unset
47
+ // filter, say) changes nothing, so the note leaves it out.
48
+ const display = renderGivenDefault(given.type ?? "string", given.default);
49
+ if (display) defaults.push(`${given.name} = ${display}`);
50
+ }
51
+
52
+ const gate: RunGate = { missing };
53
+ if (defaults.length > 0) {
54
+ gate.defaultsNote =
55
+ defaults.length === 1
56
+ ? `Ran with the default ${defaults[0]}`
57
+ : `Ran with defaults ${defaults.join(", ")}`;
58
+ }
59
+ return gate;
60
+ }
61
+
62
+ /** The hint shown under a refusal when the reader left no-default givens blank. */
63
+ export function missingGivensHint(missing: readonly string[]): string {
64
+ return missing.length === 1
65
+ ? `This source may need a value for the given ${missing[0]}. Set it in the parameters above.`
66
+ : `This source may need values for the givens ${missing.join(", ")}. Set them in the parameters above.`;
67
+ }
@@ -11,7 +11,8 @@
11
11
  * test noticing, so it is asserted here rather than only on the hook.
12
12
  */
13
13
  import { beforeEach, expect, it, mock } from "bun:test";
14
- import { render, waitFor } from "@testing-library/react";
14
+ import { fireEvent, render, screen, waitFor } from "@testing-library/react";
15
+ import type { ReactNode } from "react";
15
16
  import {
16
17
  cacheKeys,
17
18
  clearCache,
@@ -22,7 +23,15 @@ import {
22
23
  import type { RawNotebook } from "../../client";
23
24
 
24
25
  const NOTEBOOK: RawNotebook = {
25
- notebookCells: [],
26
+ notebookCells: [
27
+ {
28
+ type: "code",
29
+ text: "import { orders } from './orders.malloy'",
30
+ // `newSources` is what makes the cell's "Data sources" icon appear;
31
+ // see `NotebookCell.tsx`'s `hasValidImport` check.
32
+ newSources: [JSON.stringify({ name: "orders" })],
33
+ } as RawNotebook["notebookCells"][number],
34
+ ],
26
35
  sources: [
27
36
  {
28
37
  name: "orders",
@@ -32,6 +41,10 @@ const NOTEBOOK: RawNotebook = {
32
41
  control: "select",
33
42
  suggest: { source: "orders", dimension: "region" },
34
43
  },
44
+ // Plain text, unlike REGION: the "Data sources" dialog test below
45
+ // needs a control `fireEvent.change` can drive directly, rather
46
+ // than a select whose options load from a suggest query.
47
+ { name: "TENANT", type: "string" },
35
48
  ],
36
49
  },
37
50
  ],
@@ -53,9 +66,35 @@ const executeQueryModel = mock(
53
66
  _request: { versionId?: string },
54
67
  ) => pending(),
55
68
  );
69
+ // The notebook's real run path for a code cell, distinct from
70
+ // `executeQueryModel`: without it, the cell this spec adds (for the "Data
71
+ // sources" dialog) fails with "not a function" on every render.
72
+ const executeNotebookCell = mock(() => pending());
73
+
74
+ // Stubbed rather than let the cell's "Data sources" dialog reach the real
75
+ // ModelExplorer: that pulls in the lazy-loaded, WASM-backed
76
+ // `@malloydata/malloy-explorer`, which is not this file's business. Only what
77
+ // the notebook hands it matters here, so the stub just records its props.
78
+ const dataSourcesDialogProps = mock(
79
+ (_props: {
80
+ open: boolean;
81
+ startingGivens?: Record<string, string>;
82
+ data?: { givens?: { name?: string }[] };
83
+ }) => {},
84
+ );
85
+ mock.module("../Model/ModelExplorerDialog", () => ({
86
+ ModelExplorerDialog: (props: {
87
+ open: boolean;
88
+ startingGivens?: Record<string, string>;
89
+ data?: { givens?: { name?: string }[] };
90
+ }) => {
91
+ dataSourcesDialogProps(props);
92
+ return null as ReactNode;
93
+ },
94
+ }));
56
95
 
57
96
  mockServerProvider({
58
- notebooks: { getNotebook },
97
+ notebooks: { getNotebook, executeNotebookCell },
59
98
  models: { executeQueryModel },
60
99
  });
61
100
 
@@ -68,6 +107,8 @@ beforeEach(() => {
68
107
  clearCache();
69
108
  getNotebook.mockClear();
70
109
  executeQueryModel.mockClear();
110
+ executeNotebookCell.mockClear();
111
+ dataSourcesDialogProps.mockClear();
71
112
  });
72
113
 
73
114
  it("runs its suggest queries against the version it was opened at", async () => {
@@ -86,3 +127,26 @@ it("sends none when the notebook was opened without one", async () => {
86
127
  await waitFor(() => expect(executeQueryModel).toHaveBeenCalled());
87
128
  expect(executeQueryModel.mock.calls[0][3].versionId).toBeUndefined();
88
129
  });
130
+
131
+ it("opens a cell's 'Data sources' dialog with the notebook's current values", async () => {
132
+ render(<Notebook resourceUri={URI} />, { wrapper: serverWrapper });
133
+
134
+ const input = (await screen.findByLabelText("TENANT")) as HTMLInputElement;
135
+ fireEvent.change(input, { target: { value: "acme" } });
136
+ // Wait for the control's own re-render before opening the dialog: without
137
+ // it the click can land on the render that has not yet carried the new
138
+ // value into `cellStartingGivens`.
139
+ await waitFor(() => expect(input.value).toBe("acme"));
140
+
141
+ fireEvent.click(await screen.findByLabelText("Data sources"));
142
+
143
+ await waitFor(() =>
144
+ expect(dataSourcesDialogProps.mock.calls.at(-1)?.[0]?.open).toBe(true),
145
+ );
146
+ const lastCall = dataSourcesDialogProps.mock.calls.at(-1)?.[0];
147
+ expect(lastCall?.startingGivens).toEqual({ TENANT: "acme" });
148
+ // The values alone render nothing: the dialog needs the declarations too.
149
+ expect(lastCall?.data?.givens?.map((given) => given.name)).toContain(
150
+ "TENANT",
151
+ );
152
+ });
@@ -3,7 +3,7 @@
3
3
 
4
4
  import "@malloydata/malloy-explorer/styles.css";
5
5
  import { Stack, Typography } from "@mui/material";
6
- import { useCallback, useEffect, useRef, useState } from "react";
6
+ import { useCallback, useEffect, useMemo, useRef, useState } from "react";
7
7
  import { planRun } from "./runPlan";
8
8
  import { RawNotebook } from "../../client";
9
9
  import { GivenValue } from "../../hooks/givenValue";
@@ -15,7 +15,7 @@ import { ApiErrorDisplay } from "../ApiErrorDisplay";
15
15
  import type { NavigationClick } from "../click_helper";
16
16
  import type { DrillNavigation } from "../drill";
17
17
  import { GivensPanel } from "../given";
18
- import { givensToRequest } from "../given/paramCodec";
18
+ import { givensToParams, givensToRequest } from "../given/paramCodec";
19
19
  import { Loading } from "../Loading";
20
20
  import { useServer } from "../ServerProvider";
21
21
  import { CleanNotebookContainer, CleanNotebookSection } from "../styles";
@@ -205,6 +205,14 @@ export default function Notebook({
205
205
  [declaredTypes],
206
206
  );
207
207
 
208
+ // For a cell's "Data Sources" dialog: the notebook's current values, so
209
+ // exploring from a cell starts from what the reader is looking at rather
210
+ // than the model's bare defaults.
211
+ const cellStartingGivens = useMemo(
212
+ () => givensToParams(applied, declaredTypes),
213
+ [applied, declaredTypes],
214
+ );
215
+
208
216
  /**
209
217
  * Run every code cell with one set of given values, up to
210
218
  * {@link MAX_CONCURRENT} at a time.
@@ -524,6 +532,8 @@ export default function Notebook({
524
532
  resourceUri={resourceUri}
525
533
  maxResultSize={maxResultSize}
526
534
  isExecuting={isExecuting}
535
+ givens={cellStartingGivens}
536
+ givenSpecs={declaredGivens}
527
537
  // Distinct from `isExecuting`: the cell's spinner is
528
538
  // gated on `!cell.result`, so feeding this through it
529
539
  // showed nothing on a re-run, which is the only case