@malloy-publisher/sdk 0.9.4 → 0.9.6

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 (53) hide show
  1. package/dist/{RenderedResult-DwB0-9Yx.es.js → RenderedResult-BUb2Xvr2.es.js} +34 -19
  2. package/dist/{RenderedResult-hKjFEqaN.cjs.js → RenderedResult-qnpbr4tc.cjs.js} +15 -3
  3. package/dist/{ServerProvider-CcSrGaRN.es.js → ServerProvider-C6QQVKPm.es.js} +149 -141
  4. package/dist/ServerProvider-Gj-im5VD.cjs.js +1 -0
  5. package/dist/builder/index.cjs.js +82 -82
  6. package/dist/builder/index.es.js +3242 -3188
  7. package/dist/client/api.d.ts +54 -11
  8. package/dist/client/index.cjs.js +1 -1
  9. package/dist/client/index.es.js +57 -56
  10. package/dist/components/DashboardBuilder/AddTileDialog.d.ts +8 -5
  11. package/dist/components/DashboardBuilder/DashboardBuilder.d.ts +3 -1
  12. package/dist/components/DashboardBuilder/addTileToDocument.d.ts +14 -0
  13. package/dist/components/DashboardBuilder/catalog.d.ts +5 -1
  14. package/dist/components/DashboardBuilder/imports.d.ts +11 -12
  15. package/dist/components/DashboardBuilder/spliceDocument.d.ts +2 -0
  16. package/dist/components/DashboardBuilder/useDashboardEditor.d.ts +2 -0
  17. package/dist/components/DashboardBuilder/useTileEditing.d.ts +3 -1
  18. package/dist/index.cjs.js +1 -1
  19. package/dist/index.es.js +5 -5
  20. package/dist/theme/buildVegaThemeOverride.d.ts +7 -3
  21. package/dist/{useCompiledDocument-BU6d8FPp.es.js → useCompiledDocument-0sxonf6N.es.js} +3707 -3686
  22. package/dist/{useCompiledDocument-pOg2W-Yt.cjs.js → useCompiledDocument-tBejqZ7s.cjs.js} +31 -31
  23. package/package.json +2 -1
  24. package/src/components/DashboardBuilder/AddTileDialog.tsx +16 -11
  25. package/src/components/DashboardBuilder/DashboardBuilder.sources.spec.tsx +13 -5
  26. package/src/components/DashboardBuilder/DashboardBuilder.tsx +5 -0
  27. package/src/components/DashboardBuilder/DashboardEditor.emptyStart.spec.tsx +3 -0
  28. package/src/components/DashboardBuilder/DashboardEditor.resourceUri.spec.tsx +3 -0
  29. package/src/components/DashboardBuilder/DashboardEditor.spec.tsx +10 -2
  30. package/src/components/DashboardBuilder/DashboardEditor.textSource.spec.tsx +79 -3
  31. package/src/components/DashboardBuilder/EditorSurface.tsx +30 -2
  32. package/src/components/DashboardBuilder/addTile.compile.spec.ts +184 -0
  33. package/src/components/DashboardBuilder/addTileToDocument.spec.ts +58 -0
  34. package/src/components/DashboardBuilder/addTileToDocument.ts +64 -0
  35. package/src/components/DashboardBuilder/catalog.aggregate.spec.ts +1 -0
  36. package/src/components/DashboardBuilder/catalog.spec.ts +79 -3
  37. package/src/components/DashboardBuilder/catalog.ts +23 -5
  38. package/src/components/DashboardBuilder/imports.spec.ts +56 -0
  39. package/src/components/DashboardBuilder/imports.ts +16 -13
  40. package/src/components/DashboardBuilder/preview.spec.ts +21 -0
  41. package/src/components/DashboardBuilder/preview.ts +10 -1
  42. package/src/components/DashboardBuilder/spliceDocument.spec.ts +24 -9
  43. package/src/components/DashboardBuilder/spliceDocument.ts +18 -6
  44. package/src/components/DashboardBuilder/useDashboardEditor.ts +6 -2
  45. package/src/components/DashboardBuilder/useTileEditing.ts +13 -48
  46. package/src/components/RenderedResult/RenderedResult.tsx +12 -0
  47. package/src/components/given/GivenInput.tsx +39 -16
  48. package/src/components/given/utils.spec.ts +5 -0
  49. package/src/components/given/utils.ts +1 -1
  50. package/src/theme/buildVegaThemeOverride.spec.ts +11 -1
  51. package/src/theme/buildVegaThemeOverride.ts +10 -3
  52. package/src/timezone_runs.spec.ts +64 -0
  53. package/dist/ServerProvider-Gbf1YPOP.cjs.js +0 -1
package/package.json CHANGED
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "name": "@malloy-publisher/sdk",
3
3
  "description": "Malloy Publisher SDK",
4
- "version": "0.9.4",
4
+ "version": "0.9.6",
5
5
  "type": "module",
6
6
  "main": "dist/index.cjs.js",
7
7
  "module": "dist/index.es.js",
@@ -75,6 +75,7 @@
75
75
  "build": "bun generate-api-types && bunx vite build",
76
76
  "postbuild": "cp ../../node_modules/@malloydata/malloy-explorer/dist/malloy-explorer.css ./dist/malloy-explorer.css && echo '/* SDK Styles */\n@import \"./malloy-explorer.css\";' > ./dist/styles.css",
77
77
  "test": "bun test",
78
+ "test:tz": "bun test ./src/components/given/GivenInput.spec.tsx ./src/components/given/paramCodec.spec.ts ./src/utils/malloyLiteral.spec.ts ./src/components/drill/resolveDrill.spec.ts ./src/components/DashboardBuilder/preview.spec.ts ./src/components/Materializations/cron.spec.ts ./src/components/Materializations/utils.spec.ts",
78
79
  "lint": "bunx eslint ./src ./test --fix",
79
80
  "format": "bunx prettier --write --parser typescript '**/*.{ts,tsx}'",
80
81
  "analyze": "bunx vite-bundle-visualizer",
@@ -27,16 +27,19 @@ import { SourceViewPicker } from "./SourceViewPicker";
27
27
  * a tile that does not resolve — which is why saving needs no compile step
28
28
  * beyond the reader's own round-trip.
29
29
  *
30
- * Every source the package publishes is offered. A tile's view is declared in
31
- * an extension of its model source, so a source the file cannot see yet is
32
- * imported by name when the tile is added (`withSource`); one the file already
33
- * reaches, by name or through a whole-file import of its model, is left alone.
30
+ * Every source a model of the package exports is offered. A tile's view is
31
+ * declared in an extension of its model source, so a source the file cannot see
32
+ * yet is imported by name when the tile is added (`withSource`); one the file
33
+ * already reaches, by name or through a whole-file import of an exporter, is
34
+ * left alone.
34
35
  */
35
36
  export interface NewTile {
36
37
  /** The model source the view lives on. */
37
38
  base: string;
38
- /** The model that declares it, for the import a source the file cannot see yet needs. */
39
+ /** The model that exports it, for the import a source the file cannot see yet needs. */
39
40
  modelPath: string;
41
+ /** Every model that exports it; absent when only `modelPath` does. */
42
+ exporters?: string[];
40
43
  /** The view, as the catalog names it. */
41
44
  view: string;
42
45
  label?: string;
@@ -103,9 +106,10 @@ export function AddTileDialog({
103
106
  (name) =>
104
107
  `"${name}" is not a plain Malloy name, so a tile cannot be written for it.`,
105
108
  )[0];
106
- const picked = sources
107
- .find((source) => source.name === base)
108
- ?.views.find((candidate) => candidate.name === view);
109
+ const pickedSource = sources.find((source) => source.name === base);
110
+ const picked = pickedSource?.views.find(
111
+ (candidate) => candidate.name === view,
112
+ );
109
113
 
110
114
  return (
111
115
  <AppDialog
@@ -126,9 +130,10 @@ export function AddTileDialog({
126
130
  ? onAddText()
127
131
  : onAdd({
128
132
  base,
129
- modelPath:
130
- sources.find((s) => s.name === base)
131
- ?.modelPath ?? "",
133
+ modelPath: pickedSource?.modelPath ?? "",
134
+ ...(pickedSource?.exporters
135
+ ? { exporters: pickedSource.exporters }
136
+ : {}),
132
137
  view,
133
138
  ...(label.trim() ? { label: label.trim() } : {}),
134
139
  ...(chart !== "default"
@@ -22,9 +22,10 @@ source: a is scoped_orders extend {
22
22
  }
23
23
  `;
24
24
 
25
- const source = (name: string, modelPath: string) => ({
25
+ const source = (name: string, modelPath: string, ...also: string[]) => ({
26
26
  name,
27
27
  modelPath,
28
+ exporters: [modelPath, ...also],
28
29
  views: [{ name: "by_x" }],
29
30
  givens: [],
30
31
  fields: [],
@@ -34,8 +35,9 @@ const catalog = {
34
35
  source("scoped_orders", "data_app.malloy"),
35
36
  source("spare", "spare.malloy"),
36
37
  source("regions", "data_app.malloy"),
37
- source("events", "events.malloy"),
38
- source("hidden", "dashboards/shared.malloy"),
38
+ // Re-exported by spare.malloy, which the file already imports by name.
39
+ source("events", "events.malloy", "spare.malloy"),
40
+ source("reports", "reports.malloy"),
39
41
  ],
40
42
  };
41
43
 
@@ -102,12 +104,18 @@ describe("adding a tile brings its source in", () => {
102
104
  });
103
105
 
104
106
  it("gives a source from a model the file does not import a line of its own", async () => {
105
- const text = await written("events");
107
+ const text = await written("reports");
106
108
  expect(text).toContain(
107
- 'import { spare } from "../spare.malloy"\nimport { events } from "../events.malloy"\n',
109
+ 'import { spare } from "../spare.malloy"\nimport { reports } from "../reports.malloy"\n',
108
110
  );
109
111
  });
110
112
 
113
+ it("joins an import of a model that re-exports the source rather than adding another model's", async () => {
114
+ const text = await written("events");
115
+ expect(text).toContain('import { spare, events } from "../spare.malloy"');
116
+ expect(text).not.toContain("events.malloy");
117
+ });
118
+
111
119
  it("offers no Settings to edit sources by hand", async () => {
112
120
  await mount(() => {});
113
121
  expect(
@@ -177,6 +177,8 @@ export interface DashboardBuilderProps {
177
177
  modelPath?: string;
178
178
  /** The document is held as text, which the server reads by its tags rather than its folder: the tag always carries `kind=`. */
179
179
  explicitKind?: boolean;
180
+ /** Set for a document held as text: the sources it sees without an `import`. A tile on one of them adds no import. */
181
+ visibleSources?: readonly string[];
180
182
  /**
181
183
  * Why "Add filter" is off, or absent when it is on. A document kept as bare
182
184
  * text has no `given:` of its own to write, so only the model's givens can
@@ -212,6 +214,7 @@ export function DashboardBuilder({
212
214
  replaces,
213
215
  modelPath,
214
216
  explicitKind,
217
+ visibleSources,
215
218
  addFilterDisabledReason,
216
219
  }: DashboardBuilderProps) {
217
220
  const editor = useDashboardEditor({
@@ -222,6 +225,7 @@ export function DashboardBuilder({
222
225
  ...(replaces !== undefined ? { replaces } : {}),
223
226
  ...(modelPath !== undefined ? { modelPath } : {}),
224
227
  ...(explicitKind ? { explicitKind } : {}),
228
+ ...(visibleSources ? { visibleSources } : {}),
225
229
  });
226
230
  const gridBox = useRef<HTMLDivElement>(null);
227
231
  const {
@@ -272,6 +276,7 @@ export function DashboardBuilder({
272
276
  notebook,
273
277
  columns,
274
278
  modelPath,
279
+ textHeld: visibleSources !== undefined,
275
280
  selectTile,
276
281
  deselectTile,
277
282
  });
@@ -35,6 +35,9 @@ const getModel = mock((_env: string, _pkg: string, path: string) =>
35
35
  ? { modelPath: path, sourceText: served }
36
36
  : {
37
37
  modelPath: path,
38
+ modelInfo: JSON.stringify({
39
+ entries: [{ kind: "source", name: "scoped_orders" }],
40
+ }),
38
41
  sources: [
39
42
  {
40
43
  name: "scoped_orders",
@@ -43,6 +43,9 @@ const getModel = mock(
43
43
  ? { modelPath: path, sourceText: PACKAGE_FILE }
44
44
  : {
45
45
  modelPath: path,
46
+ modelInfo: JSON.stringify({
47
+ entries: [{ kind: "source", name: "scoped_orders" }],
48
+ }),
46
49
  sources: [
47
50
  {
48
51
  name: "scoped_orders",
@@ -49,6 +49,9 @@ const getModel = mock((_env: string, _pkg: string, path: string) =>
49
49
  ? { modelPath: path, sourceText: served }
50
50
  : {
51
51
  modelPath: path,
52
+ modelInfo: JSON.stringify({
53
+ entries: [{ kind: "source", name: "scoped_orders" }],
54
+ }),
52
55
  sources: [
53
56
  {
54
57
  name: "scoped_orders",
@@ -230,8 +233,13 @@ describe("DashboardEditor", () => {
230
233
  getModel.mock.calls.some((call) => call[2] === "broken.malloy"),
231
234
  ).toBe(true),
232
235
  );
233
- // Adding a tile needs a catalog, so the button is the proof it built.
234
- await screen.findByRole("button", { name: "Add tile", hidden: true });
236
+ // The picker offers the source the working model exports: an empty catalog would offer none.
237
+ fireEvent.click(
238
+ await screen.findByRole("button", { name: "Add tile", hidden: true }),
239
+ );
240
+ expect(
241
+ await screen.findByRole("button", { name: "View by_category" }),
242
+ ).toBeDefined();
235
243
  });
236
244
 
237
245
  it("saves an edit into the browser and marks it saved", async () => {
@@ -1,7 +1,14 @@
1
1
  // Copyright (c) Credible Data Inc.
2
2
  // SPDX-License-Identifier: MIT
3
3
 
4
- import { cleanup, render, screen, waitFor } from "@testing-library/react";
4
+ import {
5
+ cleanup,
6
+ fireEvent,
7
+ render,
8
+ screen,
9
+ waitFor,
10
+ within,
11
+ } from "@testing-library/react";
5
12
  import { beforeEach, describe, expect, it, mock } from "bun:test";
6
13
  import {
7
14
  clearCache,
@@ -70,11 +77,14 @@ const executeQueryModel = mock(
70
77
  _body: { query?: string; queryName?: string },
71
78
  ) => pending(),
72
79
  );
73
- const getModel = mock(() => pending());
80
+ const getModel = mock((..._args: unknown[]): Promise<unknown> => pending());
81
+ const listModels = mock(
82
+ (..._args: unknown[]): Promise<unknown> => Promise.resolve({ data: [] }),
83
+ );
74
84
 
75
85
  mockServerProvider(
76
86
  {
77
- models: { compileModelSource, executeQueryModel, getModel },
87
+ models: { compileModelSource, executeQueryModel, getModel, listModels },
78
88
  dashboards: {
79
89
  getDashboard: mock(() => pending()),
80
90
  listDashboards: mock(() => Promise.resolve({ data: [] })),
@@ -146,6 +156,7 @@ beforeEach(() => {
146
156
  compileModelSource.mockClear();
147
157
  executeQueryModel.mockClear();
148
158
  getModel.mockClear();
159
+ listModels.mockClear();
149
160
  });
150
161
 
151
162
  describe("DashboardEditor in text-source mode", () => {
@@ -291,6 +302,71 @@ describe("DashboardEditor in text-source mode", () => {
291
302
  expect(ran.some((query) => query?.includes("gated"))).toBe(false);
292
303
  });
293
304
 
305
+ // A text-held document has no `import`, so it can only name what its run model lists, imported or not.
306
+ it("offers only the run model's sources for a new tile, and writes no import for it", async () => {
307
+ const exporting = (name: string) => ({
308
+ modelPath: `models/${name}.malloy`,
309
+ modelInfo: JSON.stringify({ entries: [{ kind: "source", name }] }),
310
+ // orders also lists `other`, which it imports without exporting.
311
+ sources: [
312
+ { name, views: [{ name: "by_x" }] },
313
+ ...(name === "orders"
314
+ ? [{ name: "other", views: [{ name: "by_x" }] }]
315
+ : []),
316
+ ],
317
+ });
318
+ listModels.mockImplementation(() =>
319
+ Promise.resolve({
320
+ data: [
321
+ { path: "models/other.malloy" },
322
+ { path: "models/orders.malloy" },
323
+ ],
324
+ }),
325
+ );
326
+ getModel.mockImplementation((_env, _pkg, path) =>
327
+ Promise.resolve({
328
+ data: exporting(String(path).replace(/^models\/|\.malloy$/g, "")),
329
+ }),
330
+ );
331
+ try {
332
+ const storage = documentStore();
333
+ mount(storage);
334
+
335
+ fireEvent.click(
336
+ await screen.findByRole("button", { name: "Add tile" }),
337
+ );
338
+ fireEvent.mouseDown(
339
+ await screen.findByRole("combobox", { name: /Source/ }),
340
+ );
341
+ const options = within(screen.getByRole("listbox")).getAllByRole(
342
+ "option",
343
+ );
344
+ expect(options.map((o) => o.textContent).sort()).toEqual([
345
+ "orders",
346
+ "other",
347
+ ]);
348
+ fireEvent.keyDown(screen.getByRole("listbox"), { key: "Escape" });
349
+ fireEvent.click(await screen.findByLabelText("View by_x"));
350
+ fireEvent.click(
351
+ screen.getByRole("button", { name: "Add tile", hidden: false }),
352
+ );
353
+ fireEvent.click(
354
+ screen.getByRole("button", { name: "Save", hidden: true }),
355
+ );
356
+
357
+ await waitFor(() =>
358
+ expect(
359
+ storage.documents.get("env/pkg/dashboards/ops.malloy"),
360
+ ).toContain("by_x_tile"),
361
+ );
362
+ const saved = storage.documents.get("env/pkg/dashboards/ops.malloy")!;
363
+ expect(saved).not.toMatch(/^import /m);
364
+ } finally {
365
+ listModels.mockImplementation(() => Promise.resolve({ data: [] }));
366
+ getModel.mockImplementation(() => pending());
367
+ }
368
+ });
369
+
294
370
  it("turns Add filter off, since the document holds no given: of its own", async () => {
295
371
  mount(documentStore());
296
372
 
@@ -249,6 +249,32 @@ export function EditorSurface({
249
249
  },
250
250
  });
251
251
 
252
+ // A text-held document has no `import`, so only what its run model lists resolves for it.
253
+ const runSources = useMemo(
254
+ () =>
255
+ textSource
256
+ ? (catalog?.sources ?? [])
257
+ .filter((s) =>
258
+ (s.visibleIn ?? s.exporters ?? [s.modelPath]).includes(
259
+ runModelPath,
260
+ ),
261
+ )
262
+ .map((s) => s.name)
263
+ : undefined,
264
+ [catalog, textSource, runModelPath],
265
+ );
266
+ const offered = useMemo(
267
+ () =>
268
+ catalog && runSources
269
+ ? {
270
+ sources: catalog.sources.filter((s) =>
271
+ runSources.includes(s.name),
272
+ ),
273
+ }
274
+ : catalog,
275
+ [catalog, runSources],
276
+ );
277
+
252
278
  const [doc, setDoc] = useState(opened.document);
253
279
  useEffect(() => setDoc(opened.document), [opened.document]);
254
280
  // Only a package write can make the package serve it; a copy in the host's store does not.
@@ -445,7 +471,7 @@ export function EditorSurface({
445
471
  onDirtyChange={onDirtyChange}
446
472
  {...(onExit ? { onExit } : {})}
447
473
  {...(opened.conversion ? { conversion: opened.conversion } : {})}
448
- {...(catalog ? { catalog } : {})}
474
+ {...(offered ? { catalog: offered } : {})}
449
475
  dashboards={otherDashboards}
450
476
  {...(onEvent ? { onEvent } : {})}
451
477
  controls={
@@ -459,7 +485,9 @@ export function EditorSurface({
459
485
  {...(saveLabel ? { saveLabel } : {})}
460
486
  {...(replaces !== undefined ? { replaces } : {})}
461
487
  modelPath={modelPath}
462
- {...(textSource ? { explicitKind: true } : {})}
488
+ {...(textSource
489
+ ? { explicitKind: true, visibleSources: runSources }
490
+ : {})}
463
491
  />
464
492
  <Box sx={{ px: 0.5 }}>
465
493
  <Typography variant="caption" sx={{ opacity: 0.7 }}>
@@ -0,0 +1,184 @@
1
+ // Copyright (c) Credible Data Inc.
2
+ // SPDX-License-Identifier: MIT
3
+
4
+ import { describe, expect, it } from "bun:test";
5
+ import * as fs from "fs";
6
+ import * as path from "path";
7
+ import { fileURLToPath, pathToFileURL } from "url";
8
+ import type { CompiledModel } from "../../client";
9
+ import { buildCatalog } from "./catalog";
10
+ import { addTileToDocument } from "./addTileToDocument";
11
+ import { spliceDashboardDocument, spliceFailed } from "./spliceDocument";
12
+ import { openDocument } from "./testing/fixtures";
13
+
14
+ /**
15
+ * The file an add-tile writes, compiled by Malloy against the real storefront
16
+ * package. The catalog is built the way the server lists models: every source
17
+ * in `modelDef.contents`, imported ones included.
18
+ */
19
+ const PACKAGE = path.resolve(
20
+ import.meta.dir,
21
+ "../../../../../examples/storefront",
22
+ );
23
+ const DOCUMENT = "dashboards/x.malloy";
24
+
25
+ async function loadPackage() {
26
+ const { Runtime, isSourceDef, modelDefToModelInfo } = await import(
27
+ "@malloydata/malloy"
28
+ );
29
+ const { DuckDBConnection } = await import("@malloydata/db-duckdb");
30
+ const connection = new DuckDBConnection("duckdb", ":memory:", PACKAGE);
31
+ const overlay = new Map<string, string>();
32
+ const runtime = new Runtime({
33
+ urlReader: {
34
+ readURL: async (at: URL) =>
35
+ overlay.get(at.href) ??
36
+ fs.readFileSync(fileURLToPath(at.href), "utf8"),
37
+ },
38
+ connections: { lookupConnection: async () => connection },
39
+ } as never);
40
+ const urlOf = (file: string) => pathToFileURL(path.join(PACKAGE, file)).href;
41
+
42
+ const models: CompiledModel[] = [];
43
+ for (const file of ["data_app.malloy", "storefront.malloy"]) {
44
+ const { _modelDef: def } = await runtime
45
+ .loadModel(new URL(urlOf(file)))
46
+ .getModel();
47
+ const listed = Object.entries(def.contents)
48
+ .filter(([, entry]) => isSourceDef(entry as never))
49
+ .map(([name]) => ({
50
+ name,
51
+ views: [{ name: "by_category" }],
52
+ }));
53
+ models.push({
54
+ modelPath: file,
55
+ modelInfo: JSON.stringify(modelDefToModelInfo(def)),
56
+ sources: listed,
57
+ } as unknown as CompiledModel);
58
+ }
59
+
60
+ return {
61
+ models,
62
+ /** Compile `text` as the dashboard file; the errors, or none. */
63
+ problems: async (text: string) => {
64
+ overlay.set(urlOf(DOCUMENT), text);
65
+ try {
66
+ await runtime.loadModel(new URL(urlOf(DOCUMENT))).getModel();
67
+ return [];
68
+ } catch (error) {
69
+ return [String(error)];
70
+ }
71
+ },
72
+ close: () => connection.close(),
73
+ };
74
+ }
75
+
76
+ /** What the builder writes for a new tile on `base`, through the same function the add-tile hook calls. */
77
+ async function addTile(
78
+ text: string,
79
+ base: string,
80
+ catalog: ReturnType<typeof buildCatalog>,
81
+ { textHeld = false } = {},
82
+ ) {
83
+ const source = catalog.sources.find((s) => s.name === base)!;
84
+ const document = structuredClone(await openDocument(text));
85
+ addTileToDocument(
86
+ document,
87
+ {
88
+ base,
89
+ modelPath: source.modelPath,
90
+ exporters: source.exporters,
91
+ view: "by_category",
92
+ colspan: 6,
93
+ },
94
+ { modelPath: DOCUMENT, textHeld, notebook: false },
95
+ );
96
+ const result = await spliceDashboardDocument(text, document, {
97
+ modelPath: DOCUMENT,
98
+ });
99
+ if (spliceFailed(result)) throw new Error(result.reason);
100
+ return result.source;
101
+ }
102
+
103
+ const FILE = (imports: string) => `##! experimental.givens
104
+ ## artifact { title="X" tiles=[] } dashboard { columns=12 }
105
+ ${imports}
106
+ `;
107
+
108
+ describe("the file an add-tile writes compiles", () => {
109
+ it("lists the imported source under the importer, as the server does", async () => {
110
+ const pkg = await loadPackage();
111
+ try {
112
+ const dataApp = pkg.models[0];
113
+ expect(dataApp.sources?.map((s) => s.name)).toContain("order_items");
114
+ } finally {
115
+ await pkg.close();
116
+ }
117
+ });
118
+
119
+ it("imports a source from its exporter, not from the model listed first", async () => {
120
+ const pkg = await loadPackage();
121
+ try {
122
+ const catalog = buildCatalog(pkg.models);
123
+ const text = await addTile(
124
+ FILE('import { products } from "../storefront.malloy"'),
125
+ "order_items",
126
+ catalog,
127
+ );
128
+ expect(await pkg.problems(text)).toEqual([]);
129
+ expect(
130
+ catalog.sources.find((s) => s.name === "order_items")?.modelPath,
131
+ ).toBe("storefront.malloy");
132
+ expect(text).toContain(
133
+ 'import { products, order_items } from "../storefront.malloy"',
134
+ );
135
+ } finally {
136
+ await pkg.close();
137
+ }
138
+ });
139
+
140
+ it("writes no import for a source a whole-file import already carries", async () => {
141
+ const pkg = await loadPackage();
142
+ try {
143
+ const text = await addTile(
144
+ FILE('import "../storefront.malloy"'),
145
+ "order_items",
146
+ buildCatalog(pkg.models),
147
+ );
148
+ expect(await pkg.problems(text)).toEqual([]);
149
+ expect(text.match(/^import /gm)).toHaveLength(1);
150
+ } finally {
151
+ await pkg.close();
152
+ }
153
+ });
154
+
155
+ it("writes no import for a text-held document, whatever the source", async () => {
156
+ const pkg = await loadPackage();
157
+ try {
158
+ const text = await addTile(
159
+ FILE('import "../storefront.malloy"'),
160
+ "order_items",
161
+ buildCatalog(pkg.models),
162
+ { textHeld: true },
163
+ );
164
+ expect(text.match(/^import /gm)).toHaveLength(1);
165
+ } finally {
166
+ await pkg.close();
167
+ }
168
+ });
169
+
170
+ it("accepts a tile on the source a whole-file import of its model brings", async () => {
171
+ const pkg = await loadPackage();
172
+ try {
173
+ const text = await addTile(
174
+ FILE('import "../data_app.malloy"'),
175
+ "scoped_orders",
176
+ buildCatalog(pkg.models),
177
+ );
178
+ expect(text.match(/^import /gm)).toHaveLength(1);
179
+ expect(await pkg.problems(text)).toEqual([]);
180
+ } finally {
181
+ await pkg.close();
182
+ }
183
+ });
184
+ });
@@ -0,0 +1,58 @@
1
+ // Copyright (c) Credible Data Inc.
2
+ // SPDX-License-Identifier: MIT
3
+
4
+ import { describe, expect, it } from "bun:test";
5
+ import type { NewTile } from "./AddTileDialog";
6
+ import { addTileToDocument, type AddTileContext } from "./addTileToDocument";
7
+ import type { DashboardDocument } from "./document";
8
+
9
+ const document = (): DashboardDocument => ({
10
+ title: "X",
11
+ imports: [{ kind: "all", from: "../b.malloy" }],
12
+ sources: [],
13
+ tiles: [],
14
+ });
15
+
16
+ // `orders` is exported by both models; the file whole-imports the second.
17
+ const tile: NewTile = {
18
+ base: "orders",
19
+ modelPath: "a.malloy",
20
+ exporters: ["a.malloy", "b.malloy"],
21
+ view: "by_day",
22
+ colspan: 6,
23
+ };
24
+ const context: AddTileContext = {
25
+ modelPath: "dashboards/x.malloy",
26
+ textHeld: false,
27
+ notebook: false,
28
+ };
29
+
30
+ describe("addTileToDocument", () => {
31
+ it("adds no import when a whole-file import reaches any exporter of the source", () => {
32
+ const draft = document();
33
+ addTileToDocument(draft, tile, context);
34
+ expect(draft.imports).toEqual([{ kind: "all", from: "../b.malloy" }]);
35
+ });
36
+
37
+ it("imports from the crediting model when no exporter is reached", () => {
38
+ const draft = { ...document(), imports: [] };
39
+ addTileToDocument(draft, tile, context);
40
+ expect(draft.imports).toEqual([
41
+ { kind: "names", names: ["orders"], from: "../a.malloy" },
42
+ ]);
43
+ });
44
+
45
+ it("writes no import for a document held as text", () => {
46
+ const draft = { ...document(), imports: [] };
47
+ addTileToDocument(draft, tile, { ...context, textHeld: true });
48
+ expect(draft.imports).toEqual([]);
49
+ });
50
+
51
+ it("puts the tile on a new extension of its base, and leaves a notebook tile without a width", () => {
52
+ const draft = document();
53
+ addTileToDocument(draft, tile, { ...context, notebook: true });
54
+ expect(draft.sources).toEqual([{ name: "orders_tiles", base: "orders" }]);
55
+ expect(draft.tiles).toHaveLength(1);
56
+ expect(draft.tiles[0]).not.toHaveProperty("colspan");
57
+ });
58
+ });
@@ -0,0 +1,64 @@
1
+ // Copyright (c) Credible Data Inc.
2
+ // SPDX-License-Identifier: MIT
3
+
4
+ import type { NewTile } from "./AddTileDialog";
5
+ import { isQueryTile, type DashboardDocument } from "./document";
6
+ import { withSource } from "./imports";
7
+
8
+ /** Where a tile is added and what the document is: the parts of an add that are not the tile. */
9
+ export interface AddTileContext {
10
+ /** The document's file within the package, which a tile's import is relative to. */
11
+ modelPath: string | undefined;
12
+ /** The document is held as text: it has no `import`, so a tile's source is the run model's and nothing is imported. */
13
+ textHeld: boolean;
14
+ notebook: boolean;
15
+ /** Where the tile lands; undefined appends. */
16
+ insertAt?: number;
17
+ }
18
+
19
+ /** A tile from the picker, added to a draft: on the extension of its source, or a new one. */
20
+ export function addTileToDocument(
21
+ draft: DashboardDocument,
22
+ tile: NewTile,
23
+ { modelPath, textHeld, notebook, insertAt }: AddTileContext,
24
+ ): void {
25
+ // A source the file cannot see yet comes in by name, with the tile.
26
+ if (tile.modelPath && !textHeld)
27
+ draft.imports = withSource(
28
+ draft,
29
+ tile.base,
30
+ tile.modelPath,
31
+ modelPath,
32
+ tile.exporters ?? [tile.modelPath],
33
+ );
34
+ let extension = draft.sources.find((s) => s.base === tile.base);
35
+ if (!extension) {
36
+ // A name of the file's own: the base's, suffixed, since an
37
+ // extension cannot share its base's name.
38
+ const taken = new Set(draft.sources.map((s) => s.name));
39
+ let name = `${tile.base}_tiles`;
40
+ for (let n = 2; taken.has(name); n++) name = `${tile.base}_tiles_${n}`;
41
+ extension = { name, base: tile.base };
42
+ draft.sources.push(extension);
43
+ }
44
+ // The view's name in the extension: the base view's, suffixed,
45
+ // because an extension inherits its base's views and cannot redeclare
46
+ // one under the same name; then kept distinct from its siblings.
47
+ const used = new Set(
48
+ draft.tiles
49
+ .filter(isQueryTile)
50
+ .filter((t) => t.source === extension!.name)
51
+ .map((t) => t.name),
52
+ );
53
+ let name = `${tile.view}_tile`;
54
+ for (let n = 2; used.has(name); n++) name = `${tile.view}_tile_${n}`;
55
+ draft.tiles.splice(insertAt ?? draft.tiles.length, 0, {
56
+ name,
57
+ source: extension.name,
58
+ declaration: { kind: "reference", from: tile.view },
59
+ ...(notebook ? {} : { colspan: tile.colspan }),
60
+ ...(tile.label ? { label: tile.label } : {}),
61
+ ...(tile.chart ? { chart: tile.chart } : {}),
62
+ ...(tile.chartCarried ? { chartCarried: tile.chartCarried } : {}),
63
+ });
64
+ }
@@ -13,6 +13,7 @@ const REAL = String.raw`{"name":"s","schema":{"fields":[{"kind":"view","name":"k
13
13
 
14
14
  const MODEL = {
15
15
  modelPath: "notebooks/n.malloy",
16
+ modelInfo: JSON.stringify({ entries: [{ kind: "source", name: "s" }] }),
16
17
  sources: [
17
18
  {
18
19
  name: "s",