@malloy-publisher/sdk 0.8.3 → 0.8.4

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 (40) hide show
  1. package/README.md +14 -65
  2. package/dist/{DocumentStorage-CigwNjz4.es.js → Dashboard-DnqWRijB.es.js} +23660 -23575
  3. package/dist/Dashboard-FD3-Af-_.cjs.js +136 -0
  4. package/dist/{RenderedResult-BfayOSk1.es.js → RenderedResult-6UKAHaAj.es.js} +18 -18
  5. package/dist/{RenderedResult-DpHdrFtp.cjs.js → RenderedResult-CetSzFgW.cjs.js} +1 -1
  6. package/dist/ServerProvider-BsjJvkML.cjs.js +1 -0
  7. package/dist/{ServerProvider-CfUFleYe.es.js → ServerProvider-DgRFJ43L.es.js} +983 -957
  8. package/dist/builder/index.cjs.js +50 -50
  9. package/dist/builder/index.es.js +2587 -2511
  10. package/dist/client/api.d.ts +141 -40
  11. package/dist/client/configuration.d.ts +1 -1
  12. package/dist/client/index.cjs.js +1 -1
  13. package/dist/client/index.d.ts +1 -1
  14. package/dist/client/index.es.js +62 -59
  15. package/dist/components/DashboardBuilder/malloyText.d.ts +49 -0
  16. package/dist/components/DashboardBuilder/malloyTree.d.ts +2 -18
  17. package/dist/components/DashboardBuilder/readDocument.d.ts +2 -0
  18. package/dist/components/Notebook/NotebookCell.d.ts +3 -2
  19. package/dist/components/Notebook/cellKind.d.ts +20 -0
  20. package/dist/index.cjs.js +15 -12
  21. package/dist/index.es.js +4528 -4435
  22. package/package.json +1 -1
  23. package/src/components/DashboardBuilder/malloyText.spec.ts +70 -1
  24. package/src/components/DashboardBuilder/malloyText.ts +171 -3
  25. package/src/components/DashboardBuilder/malloyTree.spec.ts +35 -0
  26. package/src/components/DashboardBuilder/malloyTree.ts +28 -4
  27. package/src/components/DashboardBuilder/readDocument.spec.ts +180 -1
  28. package/src/components/DashboardBuilder/readDocument.ts +52 -14
  29. package/src/components/DashboardBuilder/spliceDocument.spec.ts +396 -2
  30. package/src/components/DashboardBuilder/spliceDocument.ts +121 -18
  31. package/src/components/Notebook/Notebook.served.spec.tsx +175 -0
  32. package/src/components/Notebook/Notebook.spec.tsx +33 -2
  33. package/src/components/Notebook/Notebook.tsx +13 -7
  34. package/src/components/Notebook/NotebookCell.tsx +124 -63
  35. package/src/components/Notebook/cellKind.spec.ts +191 -0
  36. package/src/components/Notebook/cellKind.ts +74 -0
  37. package/src/components/Package/Package.notebooks.spec.tsx +90 -0
  38. package/src/components/Package/Package.tsx +18 -4
  39. package/dist/DocumentStorage-DvUNSOiN.cjs.js +0 -134
  40. package/dist/ServerProvider-CuYLH_Yi.cjs.js +0 -1
@@ -2,6 +2,8 @@
2
2
  // SPDX-License-Identifier: MIT
3
3
 
4
4
  import CloseIcon from "@mui/icons-material/Close";
5
+ import ChevronRightIcon from "@mui/icons-material/ChevronRight";
6
+ import ExpandMoreIcon from "@mui/icons-material/ExpandMore";
5
7
  import CodeIcon from "@mui/icons-material/Code";
6
8
  import ContentCopyIcon from "@mui/icons-material/ContentCopy";
7
9
  import LinkOutlinedIcon from "@mui/icons-material/LinkOutlined";
@@ -19,7 +21,7 @@ import {
19
21
  Tooltip,
20
22
  Typography,
21
23
  } from "@mui/material";
22
- import React, { useEffect, useState } from "react";
24
+ import React, { useEffect, useId, useState } from "react";
23
25
  import type { Given } from "../../client";
24
26
  import { usePublisherTheme } from "../../theme/ThemeContext";
25
27
  import { parseResourceUri } from "../../utils/formatting";
@@ -34,6 +36,7 @@ import ResultContainer from "../RenderedResult/ResultContainer";
34
36
  import { NOTEBOOK_CELL_MAX_HEIGHT } from "../RenderedResult/resultSizing";
35
37
  import ResultsDialog from "../ResultsDialog";
36
38
  import { CleanMetricCard } from "../styles";
39
+ import { cellCaption, definitionSummary, stripProse } from "./cellKind";
37
40
  import { EnhancedNotebookCell } from "./types";
38
41
 
39
42
  interface NotebookCellProps {
@@ -43,7 +46,8 @@ interface NotebookCellProps {
43
46
  expandEmbedding?: boolean;
44
47
  hideEmbeddingIcon?: boolean;
45
48
  resourceUri: string;
46
- index: number;
49
+ /** Whether this is the notebook's first markdown cell, which carries the copy-link icon. */
50
+ showCopyLink?: boolean;
47
51
  maxResultSize?: number;
48
52
  isExecuting?: boolean;
49
53
  /**
@@ -98,7 +102,7 @@ export function NotebookCell({
98
102
  hideCodeCellIcon,
99
103
  hideEmbeddingIcon,
100
104
  resourceUri,
101
- index,
105
+ showCopyLink,
102
106
  maxResultSize,
103
107
  isExecuting,
104
108
  pendingRerun,
@@ -121,6 +125,8 @@ export function NotebookCell({
121
125
  const [sourcesDialogOpen, setSourcesDialogOpen] =
122
126
  React.useState<boolean>(false);
123
127
 
128
+ const [definitionOpen, setDefinitionOpen] = useState(false);
129
+ const definitionRegionId = useId();
124
130
  const [copyMessage, setCopyMessage] = useState("");
125
131
 
126
132
  const { environmentName, packageName, modelPath } =
@@ -170,14 +176,6 @@ export function NotebookCell({
170
176
  const IMPORT_MODEL_PATH_REGEX =
171
177
  /import\s*(?:\{[^}]*\}\s*from\s*)?['"`]([^'"`]+)['"`]/;
172
178
 
173
- // Filter out lines starting with ## from Malloy code
174
- const filterMalloyCode = (code: string): string => {
175
- return code
176
- .split("\n")
177
- .filter((line) => !line.trimStart().startsWith("##"))
178
- .join("\n");
179
- };
180
-
181
179
  const hasValidImport =
182
180
  !!cell.text &&
183
181
  (IMPORT_NAMES_REGEX.test(cell.text) ||
@@ -243,7 +241,7 @@ export function NotebookCell({
243
241
  const { mode } = usePublisherTheme();
244
242
  useEffect(() => {
245
243
  if (cell.type === "code")
246
- highlight(filterMalloyCode(cell.text), "malloy", mode).then((code) => {
244
+ highlight(stripProse(cell), "malloy", mode).then((code) => {
247
245
  setHighlightedMalloyCode(code);
248
246
  });
249
247
  }, [cell, mode]);
@@ -254,6 +252,13 @@ export function NotebookCell({
254
252
  });
255
253
  }, [queryResultCodeSnippet, mode]);
256
254
 
255
+ const caption = cell.kind === "query" ? cellCaption(cell) : undefined;
256
+ const header = cell.markdown ? (
257
+ <Prose variant="document" links={links}>
258
+ {cell.markdown}
259
+ </Prose>
260
+ ) : null;
261
+
257
262
  const copyToClipboard = () => {
258
263
  const url = window.location.href;
259
264
  navigator.clipboard
@@ -262,11 +267,62 @@ export function NotebookCell({
262
267
  .catch(() => setCopyMessage("Failed to copy URL"));
263
268
  };
264
269
 
270
+ const codeDialog = (
271
+ <Dialog
272
+ open={codeDialogOpen}
273
+ onClose={() => setCodeDialogOpen(false)}
274
+ maxWidth="lg"
275
+ fullWidth
276
+ >
277
+ <DialogTitle
278
+ sx={{
279
+ display: "flex",
280
+ justifyContent: "space-between",
281
+ alignItems: "center",
282
+ }}
283
+ >
284
+ Malloy Code
285
+ <IconButton
286
+ onClick={() => setCodeDialogOpen(false)}
287
+ sx={{ color: "text.secondary" }}
288
+ >
289
+ <CloseIcon />
290
+ </IconButton>
291
+ </DialogTitle>
292
+ <DialogContent>
293
+ <Box
294
+ sx={(theme) => ({
295
+ border: `1px solid ${theme.palette.divider}`,
296
+ borderRadius: "8px",
297
+ padding: "16px",
298
+ fontFamily: "monospace",
299
+ fontSize: "14px",
300
+ lineHeight: "1.5",
301
+ overflow: "auto",
302
+ maxHeight: "70vh",
303
+ backgroundColor: theme.palette.background.paper,
304
+ color: theme.palette.text.primary,
305
+ })}
306
+ >
307
+ <pre
308
+ className="code-display"
309
+ style={{
310
+ margin: 0,
311
+ }}
312
+ dangerouslySetInnerHTML={{
313
+ __html: highlightedMalloyCode,
314
+ }}
315
+ />
316
+ </Box>
317
+ </DialogContent>
318
+ </Dialog>
319
+ );
320
+
265
321
  return (
266
322
  (cell.type === "markdown" && (
267
323
  <Box>
268
324
  <Box>
269
- {index === 0 ? (
325
+ {showCopyLink ? (
270
326
  <Stack
271
327
  direction="row"
272
328
  alignItems="flex-start"
@@ -301,8 +357,62 @@ export function NotebookCell({
301
357
  </Box>
302
358
  </Box>
303
359
  )) ||
360
+ (cell.kind === "definition" && (
361
+ <Box>
362
+ {header}
363
+ <Box
364
+ component="button"
365
+ type="button"
366
+ aria-expanded={definitionOpen}
367
+ aria-controls={definitionRegionId}
368
+ onClick={() => setDefinitionOpen((open) => !open)}
369
+ sx={{
370
+ display: "flex",
371
+ alignItems: "center",
372
+ gap: "4px",
373
+ p: 0,
374
+ border: 0,
375
+ background: "none",
376
+ cursor: "pointer",
377
+ fontFamily: "monospace",
378
+ fontSize: "13px",
379
+ color: "text.secondary",
380
+ }}
381
+ >
382
+ {definitionOpen ? (
383
+ <ExpandMoreIcon fontSize="small" />
384
+ ) : (
385
+ <ChevronRightIcon fontSize="small" />
386
+ )}
387
+ {definitionSummary(cell)}
388
+ </Box>
389
+ {definitionOpen && (
390
+ <CleanMetricCard
391
+ id={definitionRegionId}
392
+ sx={{ mt: 1, padding: "12px 24px" }}
393
+ >
394
+ <pre
395
+ className="code-display"
396
+ style={{ margin: 0, overflow: "auto" }}
397
+ dangerouslySetInnerHTML={{
398
+ __html: highlightedMalloyCode ?? "",
399
+ }}
400
+ />
401
+ </CleanMetricCard>
402
+ )}
403
+ </Box>
404
+ )) ||
304
405
  (cell.type === "code" && (
305
406
  <Box>
407
+ {header}
408
+ {caption && (
409
+ <Typography
410
+ variant="body2"
411
+ sx={{ color: "text.secondary", mb: 1 }}
412
+ >
413
+ {caption}
414
+ </Typography>
415
+ )}
306
416
  {(!hideCodeCellIcon ||
307
417
  (!hideEmbeddingIcon && cell.result) ||
308
418
  (cell.newSources && cell.newSources.length > 0)) && (
@@ -370,56 +480,7 @@ export function NotebookCell({
370
480
  startingGivens={givens}
371
481
  />
372
482
 
373
- {/* Code Dialog */}
374
- <Dialog
375
- open={codeDialogOpen}
376
- onClose={() => setCodeDialogOpen(false)}
377
- maxWidth="lg"
378
- fullWidth
379
- >
380
- <DialogTitle
381
- sx={{
382
- display: "flex",
383
- justifyContent: "space-between",
384
- alignItems: "center",
385
- }}
386
- >
387
- Malloy Code
388
- <IconButton
389
- onClick={() => setCodeDialogOpen(false)}
390
- sx={{ color: "text.secondary" }}
391
- >
392
- <CloseIcon />
393
- </IconButton>
394
- </DialogTitle>
395
- <DialogContent>
396
- <Box
397
- sx={(theme) => ({
398
- border: `1px solid ${theme.palette.divider}`,
399
- borderRadius: "8px",
400
- padding: "16px",
401
- fontFamily: "monospace",
402
- fontSize: "14px",
403
- lineHeight: "1.5",
404
- overflow: "auto",
405
- maxHeight: "70vh",
406
- backgroundColor: theme.palette.background.paper,
407
- color: theme.palette.text.primary,
408
- })}
409
- >
410
- <pre
411
- className="code-display"
412
- style={{
413
- margin: 0,
414
- }}
415
- dangerouslySetInnerHTML={{
416
- __html: highlightedMalloyCode,
417
- }}
418
- />
419
- </Box>
420
- </DialogContent>
421
- </Dialog>
422
-
483
+ {codeDialog}
423
484
  {/* Embedding Dialog */}
424
485
  <Dialog
425
486
  open={embeddingDialogOpen}
@@ -0,0 +1,191 @@
1
+ // Copyright (c) Credible Data Inc.
2
+ // SPDX-License-Identifier: MIT
3
+
4
+ import { describe, expect, it } from "bun:test";
5
+ import {
6
+ cellCaption,
7
+ cellRuns,
8
+ definitionSummary,
9
+ stripProse,
10
+ } from "./cellKind";
11
+
12
+ describe("cellRuns", () => {
13
+ it("runs a .malloynb code cell and skips its markdown", () => {
14
+ expect(cellRuns({ type: "code" })).toBe(true);
15
+ expect(cellRuns({ type: "markdown" })).toBe(false);
16
+ });
17
+
18
+ it("runs only a query cell of a served notebook", () => {
19
+ expect(cellRuns({ type: "code", kind: "query" })).toBe(true);
20
+ expect(cellRuns({ type: "code", kind: "definition" })).toBe(false);
21
+ expect(cellRuns({ type: "markdown", kind: "markdown" })).toBe(false);
22
+ });
23
+ });
24
+
25
+ describe("cellCaption", () => {
26
+ it("prefers the caption the server sent", () => {
27
+ expect(
28
+ cellCaption({ text: '#" From the text\nrun: q', caption: "Served" }),
29
+ ).toBe("Served");
30
+ });
31
+
32
+ it('falls back to the #" lines of the tag block above the run', () => {
33
+ expect(
34
+ cellCaption({
35
+ text: '#" Revenue by month\n# bar_chart\nrun: sales -> by_month',
36
+ }),
37
+ ).toBe("Revenue by month");
38
+ expect(
39
+ cellCaption({ text: '# bar_chart\n#" First\n#" second\nrun: q' }),
40
+ ).toBe("First second");
41
+ });
42
+
43
+ it('ignores a #" past the tag block, and reads past a // comment', () => {
44
+ expect(
45
+ cellCaption({ text: 'run: q -> {\n#" not a caption\n select: a }' }),
46
+ ).toBeUndefined();
47
+ expect(cellCaption({ text: '// why\n#" Shown\nrun: q' })).toBe("Shown");
48
+ });
49
+
50
+ it("does not read a caption out of the prose lines the server named", () => {
51
+ expect(
52
+ cellCaption({
53
+ text: '#|(markdown)\n#" not a caption\n|#\nrun: q',
54
+ proseLines: [[0, 2]],
55
+ }),
56
+ ).toBeUndefined();
57
+ });
58
+
59
+ it("is undefined when there is no caption", () => {
60
+ expect(cellCaption({ text: "# bar_chart\nrun: q" })).toBeUndefined();
61
+ expect(cellCaption({ text: "" })).toBeUndefined();
62
+ });
63
+ });
64
+
65
+ describe("definitionSummary", () => {
66
+ it("names the statement kind and what it defines", () => {
67
+ expect(
68
+ definitionSummary({ text: "source: sales is orders extend {\n}" }),
69
+ ).toBe("source: sales");
70
+ expect(definitionSummary({ text: "query: top is sales -> q" })).toBe(
71
+ "query: top",
72
+ );
73
+ expect(
74
+ definitionSummary({
75
+ text: '# label="Region"\ngiven: REGION :: filter<string>',
76
+ }),
77
+ ).toBe("given: REGION");
78
+ });
79
+
80
+ it("says only import for an import, whatever it brings in", () => {
81
+ expect(
82
+ definitionSummary({ text: 'import { a, b } from "./m.malloy"' }),
83
+ ).toBe("import");
84
+ });
85
+
86
+ it("skips the prose lines the server named", () => {
87
+ expect(
88
+ definitionSummary({
89
+ text: "#|(markdown)\nThe orders source.\n|#\nsource: o is t",
90
+ proseLines: [[0, 2]],
91
+ }),
92
+ ).toBe("source: o");
93
+ expect(
94
+ definitionSummary({
95
+ text: "#|(markdown)\nsource: not this\n|#\nsource: o is t",
96
+ proseLines: [[0, 2]],
97
+ }),
98
+ ).toBe("source: o");
99
+ });
100
+
101
+ it("falls back to the first line for a statement it does not recognize", () => {
102
+ expect(definitionSummary({ text: "export { a }" })).toBe("export");
103
+ expect(definitionSummary({ text: "// note\nmystery thing" })).toBe(
104
+ "mystery thing",
105
+ );
106
+ });
107
+ });
108
+
109
+ describe("stripProse", () => {
110
+ it("removes exactly the lines the server named, and nothing else", () => {
111
+ expect(
112
+ stripProse({
113
+ text: '#|(markdown)\nBody\n|#\n#" Caption\n#(markdown) note\n# bar_chart\nrun: q',
114
+ proseLines: [
115
+ [0, 2],
116
+ [4, 4],
117
+ ],
118
+ }),
119
+ ).toBe('#" Caption\n# bar_chart\nrun: q');
120
+ });
121
+
122
+ it("keeps a ## line the server did not name", () => {
123
+ expect(
124
+ stripProse({ text: "## kept\nrun: q", proseLines: [[1, 1]] }),
125
+ ).toBe("## kept");
126
+ });
127
+
128
+ it("does not guess at prose in a nested note the server left out", () => {
129
+ expect(
130
+ stripProse({
131
+ text: "#(markdown) lead\nsource: s is a extend {\n #(markdown) about v\n view: v is x\n}",
132
+ proseLines: [[0, 0]],
133
+ }),
134
+ ).toBe(
135
+ "source: s is a extend {\n #(markdown) about v\n view: v is x\n}",
136
+ );
137
+ });
138
+
139
+ it("without ranges, drops the ## lines as the released viewer did", () => {
140
+ expect(
141
+ stripProse({ text: "## title\n ## indented\nrun: q\n#(markdown) x" }),
142
+ ).toBe("run: q\n#(markdown) x");
143
+ });
144
+
145
+ it("without ranges, drops a .malloynb ##! line exactly as the released code did", () => {
146
+ expect(stripProse({ text: "##! experimental.parameters\nrun: q" })).toBe(
147
+ "run: q",
148
+ );
149
+ });
150
+
151
+ it("without ranges, leaves (markdown) lines alone", () => {
152
+ const cell = '#(markdown) note\n#|(markdown)\nbody\n|#\n#" c\nrun: q';
153
+ expect(stripProse({ text: cell })).toBe(cell);
154
+ });
155
+ });
156
+
157
+ describe("a served cell trusts only the server", () => {
158
+ it("keeps a ## line inside a multi-line string when it has no prose", () => {
159
+ const text = 'run: duckdb.sql("""\n## not prose\nselect 1""")';
160
+ expect(stripProse({ text, proseLines: [], codeLine: 0 })).toBe(text);
161
+ });
162
+
163
+ it("shows no caption the server did not send", () => {
164
+ for (const text of [
165
+ '#"x\nrun: q',
166
+ '#"\u00a0nbsp\nrun: q',
167
+ '#|\nlabel="a"\n#" hidden\n|#\nrun: q',
168
+ ]) {
169
+ expect(cellCaption({ text, proseLines: [], codeLine: 0 })).toBe(
170
+ undefined,
171
+ );
172
+ }
173
+ });
174
+
175
+ it("labels a definition by the line the server points at", () => {
176
+ expect(
177
+ definitionSummary({
178
+ text: '#|"\nRegion to filter by\n|#\ngiven: REGION :: string is "x"',
179
+ proseLines: [],
180
+ codeLine: 3,
181
+ }),
182
+ ).toBe("given: REGION");
183
+ expect(
184
+ definitionSummary({
185
+ text: '#|\nlabel="Orders"\n|#\nsource: s is a',
186
+ proseLines: [],
187
+ codeLine: 3,
188
+ }),
189
+ ).toBe("source: s");
190
+ });
191
+ });
@@ -0,0 +1,74 @@
1
+ // Copyright (c) Credible Data Inc.
2
+ // SPDX-License-Identifier: MIT
3
+
4
+ import type { NotebookCell } from "../../client";
5
+
6
+ /**
7
+ * Whether the viewer sends a cell to the server to run. A served notebook's
8
+ * definition cell is `type: code` too, so `type` alone would execute it.
9
+ */
10
+ export function cellRuns(cell: Pick<NotebookCell, "type" | "kind">): boolean {
11
+ return cell.kind ? cell.kind === "query" : cell.type === "code";
12
+ }
13
+
14
+ type CellLines = Pick<NotebookCell, "text" | "proseLines" | "codeLine">;
15
+
16
+ /** Only a served `.malloy` cell carries `proseLines`, `[]` included; a `.malloynb` or an older server sends none. */
17
+ const isServed = (cell: Pick<NotebookCell, "proseLines">): boolean =>
18
+ cell.proseLines !== undefined;
19
+
20
+ /** The lines of a cell the server did not name as prose; all of them when it named none. */
21
+ function codeLines({ text, proseLines }: CellLines): string[] {
22
+ return (text ?? "")
23
+ .split("\n")
24
+ .filter(
25
+ (_, index) =>
26
+ !proseLines?.some(([start, end]) => index >= start && index <= end),
27
+ );
28
+ }
29
+
30
+ /**
31
+ * A query cell's caption. A served cell's is the server's alone, absent meaning none; on an
32
+ * unserved cell (a `.malloynb`, an older server) it is the `#"` lines in the tag block above its `run:`.
33
+ */
34
+ export function cellCaption(
35
+ cell: Pick<NotebookCell, "text" | "caption" | "proseLines" | "codeLine">,
36
+ ): string | undefined {
37
+ if (isServed(cell)) return cell.caption;
38
+ if (cell.caption !== undefined) return cell.caption;
39
+ const lines: string[] = [];
40
+ for (const raw of codeLines(cell)) {
41
+ const line = raw.trim();
42
+ if (line.startsWith("//")) continue;
43
+ if (!line.startsWith("#")) break;
44
+ if (line.startsWith('#"')) lines.push(line.slice(2).trim());
45
+ }
46
+ return lines.length > 0 ? lines.join(" ") : undefined;
47
+ }
48
+
49
+ /**
50
+ * A cell's code without its prose, which renders separately. A served cell loses exactly the
51
+ * lines the server named; an unserved one (a `.malloynb`, an older server) loses its `##` lines.
52
+ */
53
+ export function stripProse(cell: CellLines): string {
54
+ if (isServed(cell)) return codeLines(cell).join("\n");
55
+ return cell.text
56
+ .split("\n")
57
+ .filter((line) => !line.trimStart().startsWith("##"))
58
+ .join("\n");
59
+ }
60
+
61
+ /** One-line label for a folded definition cell: its statement kind and name. */
62
+ export function definitionSummary(cell: CellLines): string {
63
+ const line =
64
+ cell.codeLine !== undefined
65
+ ? (cell.text.split("\n")[cell.codeLine] ?? "").trim()
66
+ : (codeLines(cell)
67
+ .map((raw) => raw.trim())
68
+ .find((l) => l && !l.startsWith("#") && !l.startsWith("//")) ??
69
+ "");
70
+ const named = /^(source|query|given|type):?\s+([A-Za-z_]\w*)/.exec(line);
71
+ if (named) return `${named[1]}: ${named[2]}`;
72
+ const keyword = /^(import|export)\b/.exec(line);
73
+ return keyword ? keyword[1] : line;
74
+ }
@@ -0,0 +1,90 @@
1
+ // Copyright (c) Credible Data Inc.
2
+ // SPDX-License-Identifier: MIT
3
+
4
+ import { beforeEach, expect, it, mock } from "bun:test";
5
+ import { fireEvent, render, screen, waitFor } from "@testing-library/react";
6
+ import {
7
+ clearCache,
8
+ mockServerProvider,
9
+ pending,
10
+ serverWrapper,
11
+ } from "../../../test/serverProvider";
12
+
13
+ let listed: { path: string; title?: string }[] = [];
14
+
15
+ const getNotebook = mock(
16
+ (
17
+ _environmentName: string,
18
+ _packageName: string,
19
+ _notebookPath: string,
20
+ _versionId?: string,
21
+ ) => pending(),
22
+ );
23
+
24
+ mockServerProvider({
25
+ packages: { getPackage: pending },
26
+ notebooks: {
27
+ listNotebooks: () => Promise.resolve({ data: listed }),
28
+ getNotebook,
29
+ executeNotebookCell: pending,
30
+ },
31
+ models: { listModels: pending },
32
+ databases: { listDatabases: pending },
33
+ dataApps: { listDataApps: pending },
34
+ dashboards: { listDashboards: () => Promise.resolve({ data: [] }) },
35
+ });
36
+
37
+ const { default: Package } = await import("./Package");
38
+
39
+ beforeEach(() => {
40
+ clearCache();
41
+ getNotebook.mockClear();
42
+ });
43
+
44
+ it("links a served notebook by slug and a .malloynb by path", async () => {
45
+ listed = [
46
+ { path: "notebooks/tour.malloy", title: "Tour" },
47
+ { path: "old.malloynb", title: "Old" },
48
+ ];
49
+ const onClick = mock((_to: string) => {});
50
+ render(
51
+ <Package
52
+ resourceUri="publisher://environments/env/packages/pkg"
53
+ onClickPackageFile={onClick}
54
+ />,
55
+ { wrapper: serverWrapper },
56
+ );
57
+
58
+ fireEvent.click(await screen.findByText("Tour"));
59
+ fireEvent.click(await screen.findByText("Old"));
60
+
61
+ expect(onClick.mock.calls.map((call) => call[0])).toEqual([
62
+ "/env/pkg/notebooks/tour",
63
+ "/env/pkg/old.malloynb",
64
+ ]);
65
+ });
66
+
67
+ it("pins notebooks/README.malloy to the front page, matching case-insensitively", async () => {
68
+ listed = [{ path: "notebooks/Readme.malloy" }];
69
+ render(<Package resourceUri="publisher://environments/env/packages/pkg" />, {
70
+ wrapper: serverWrapper,
71
+ });
72
+
73
+ await waitFor(() => expect(getNotebook).toHaveBeenCalled());
74
+ expect(getNotebook.mock.calls[0]).toEqual([
75
+ "env",
76
+ "pkg",
77
+ "notebooks/Readme.malloy",
78
+ undefined,
79
+ ]);
80
+ });
81
+
82
+ it("pins the root README.malloynb over notebooks/README.malloy when both exist", async () => {
83
+ listed = [{ path: "notebooks/README.malloy" }, { path: "README.malloynb" }];
84
+ render(<Package resourceUri="publisher://environments/env/packages/pkg" />, {
85
+ wrapper: serverWrapper,
86
+ });
87
+
88
+ await waitFor(() => expect(getNotebook).toHaveBeenCalled());
89
+ expect(getNotebook.mock.calls[0][2]).toBe("README.malloynb");
90
+ });
@@ -40,7 +40,14 @@ import { ItemRow } from "../ItemRow";
40
40
  import { Materializations } from "../Materializations";
41
41
  import { PackageSection } from "../PackageSection";
42
42
 
43
+ // The pinned README: the root `.malloynb`, or a served notebook named README in `notebooks/`.
43
44
  const README_NOTEBOOK = "README.malloynb";
45
+ const isServedReadme = (path: string | undefined) =>
46
+ path?.toLowerCase() === "notebooks/readme.malloy";
47
+
48
+ /** A served notebook opens by slug, like a dashboard; a `.malloynb` opens by path. */
49
+ const servedNotebookSlug = (path: string | undefined) =>
50
+ /^notebooks\/([^/]+)\.malloy$/.exec(path ?? "")?.[1];
44
51
 
45
52
  interface PackageProps {
46
53
  onClickPackageFile?: (to: string, event?: React.MouseEvent) => void;
@@ -228,12 +235,16 @@ export default function Package({
228
235
  .sort((a, b) => a.path.localeCompare(b.path));
229
236
 
230
237
  const description = pkgQuery.data?.data?.description ?? "";
231
- const hasReadme = notebooks.some((n) => n.path === README_NOTEBOOK);
238
+ // The root `.malloynb` wins when both exist, so a listing order never flips the pin.
239
+ const readmePath = (
240
+ notebooks.find((n) => n.path === README_NOTEBOOK) ??
241
+ notebooks.find((n) => isServedReadme(n.path))
242
+ )?.path;
232
243
  const readmeResourceUri = encodeResourceUri({
233
244
  environmentName,
234
245
  packageName,
235
246
  versionId,
236
- modelPath: README_NOTEBOOK,
247
+ modelPath: readmePath,
237
248
  });
238
249
 
239
250
  // The dashboards list is part of the gate, not just the notebooks one,
@@ -442,6 +453,7 @@ export default function Package({
442
453
  // reader needs to find the file is never lost.
443
454
  const hasTitle =
444
455
  !!notebook.title && notebook.title !== notebook.path;
456
+ const slug = servedNotebookSlug(notebook.path);
445
457
  return (
446
458
  <PackageItemRow
447
459
  key={notebook.path}
@@ -450,7 +462,9 @@ export default function Package({
450
462
  rightLabel={hasTitle ? notebook.path : undefined}
451
463
  onClick={(event) =>
452
464
  onClick(
453
- `/${environmentName}/${packageName}/${notebook.path}`,
465
+ slug === undefined
466
+ ? `/${environmentName}/${packageName}/${notebook.path}`
467
+ : `/${environmentName}/${packageName}/notebooks/${encodeURIComponent(slug)}`,
454
468
  event,
455
469
  )
456
470
  }
@@ -564,7 +578,7 @@ export default function Package({
564
578
 
565
579
  <Materializations resourceUri={resourceUri} />
566
580
 
567
- {hasReadme && (
581
+ {readmePath && (
568
582
  <Box sx={{ mt: 6 }}>
569
583
  <Notebook
570
584
  resourceUri={readmeResourceUri}