@malloy-publisher/sdk 0.9.13 → 0.9.15

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 (148) hide show
  1. package/dist/RenderedResult-BClN_PG6.cjs.js +154 -0
  2. package/dist/{RenderedResult-DnBtf-cI.es.js → RenderedResult-YBzVMVH2.es.js} +295 -234
  3. package/dist/{ServerProvider-BV7IoDMR.es.js → ServerProvider-D7neZcTk.es.js} +283 -265
  4. package/dist/ServerProvider-e2369oom.cjs.js +1 -0
  5. package/dist/builder/index.cjs.js +80 -79
  6. package/dist/builder/index.es.js +7430 -6548
  7. package/dist/client/api.d.ts +30 -6
  8. package/dist/client/index.cjs.js +1 -1
  9. package/dist/client/index.es.js +1 -1
  10. package/dist/components/Dashboard/DashboardGrid.d.ts +49 -1
  11. package/dist/components/Dashboard/DashboardTile.d.ts +5 -2
  12. package/dist/components/Dashboard/DashboardView.d.ts +9 -2
  13. package/dist/components/Dashboard/index.d.ts +1 -1
  14. package/dist/components/Dashboard/promoteMeasureRow.d.ts +5 -7
  15. package/dist/components/Dashboard/useStuck.d.ts +18 -12
  16. package/dist/components/RenderedResult/RenderedResult.d.ts +3 -2
  17. package/dist/components/RenderedResult/ResultContainer.d.ts +11 -1
  18. package/dist/components/RenderedResult/ResultPanel.d.ts +5 -1
  19. package/dist/components/RenderedResult/chartPresentation.d.ts +15 -0
  20. package/dist/components/RenderedResult/chartShapeProblem.d.ts +55 -0
  21. package/dist/components/RenderedResult/resultSizing.d.ts +42 -6
  22. package/dist/components/Report/Report.d.ts +7 -1
  23. package/dist/components/Report/ReportPage.d.ts +7 -0
  24. package/dist/components/Report/layoutRules.d.ts +45 -0
  25. package/dist/components/ReportBuilder/AddTileDialog.d.ts +2 -1
  26. package/dist/components/ReportBuilder/BuilderGrid.d.ts +14 -1
  27. package/dist/components/ReportBuilder/ChartPicker.d.ts +4 -2
  28. package/dist/components/ReportBuilder/EditorSurface.d.ts +17 -1
  29. package/dist/components/ReportBuilder/ReportEditor.d.ts +18 -0
  30. package/dist/components/ReportBuilder/TileFrame.d.ts +33 -1
  31. package/dist/components/ReportBuilder/TileMenu.d.ts +5 -2
  32. package/dist/components/ReportBuilder/catalog.d.ts +23 -0
  33. package/dist/components/ReportBuilder/chartLine.d.ts +38 -5
  34. package/dist/components/ReportBuilder/controls.d.ts +2 -2
  35. package/dist/components/ReportBuilder/document.d.ts +53 -5
  36. package/dist/components/ReportBuilder/imports.d.ts +7 -0
  37. package/dist/components/ReportBuilder/placement.d.ts +75 -0
  38. package/dist/components/ReportBuilder/preview.d.ts +59 -10
  39. package/dist/components/ReportBuilder/sortable.d.ts +3 -1
  40. package/dist/components/ReportBuilder/useTileHeight.d.ts +39 -0
  41. package/dist/components/ReportBuilder/useTileReorder.d.ts +27 -3
  42. package/dist/components/ReportBuilder/useTileResize.d.ts +8 -0
  43. package/dist/index.cjs.js +7 -7
  44. package/dist/index.es.js +3328 -3287
  45. package/dist/text/index.es.js +1 -1
  46. package/dist/{text-entry-72YFLeNk.es.js → text-entry-YKJZbRPo.es.js} +2 -2
  47. package/dist/theme/resolveTheme.d.ts +15 -0
  48. package/dist/{useCompiledDocument-B4QF1mIl.es.js → useCompiledDocument-BGk38oaW.es.js} +5097 -4805
  49. package/dist/useCompiledDocument-D9t5ry_t.cjs.js +142 -0
  50. package/dist/utils/blankQuoted.d.ts +15 -0
  51. package/package.json +1 -1
  52. package/src/components/Dashboard/DashboardGrid.tsx +127 -10
  53. package/src/components/Dashboard/DashboardTile.tsx +11 -1
  54. package/src/components/Dashboard/DashboardView.tsx +63 -10
  55. package/src/components/Dashboard/TileCard.tsx +6 -0
  56. package/src/components/Dashboard/index.ts +1 -0
  57. package/src/components/Dashboard/promoteMeasureRow.spec.ts +19 -0
  58. package/src/components/Dashboard/promoteMeasureRow.ts +15 -36
  59. package/src/components/Dashboard/tileHeight.spec.ts +72 -0
  60. package/src/components/Dashboard/useStuck.ts +76 -28
  61. package/src/components/Package/NewDocumentDialog.spec.tsx +20 -16
  62. package/src/components/Package/NewDocumentDialog.tsx +10 -11
  63. package/src/components/RenderedResult/RenderedResult.lifecycle.spec.tsx +167 -2
  64. package/src/components/RenderedResult/RenderedResult.tsx +21 -6
  65. package/src/components/RenderedResult/ResultContainer.tsx +60 -7
  66. package/src/components/RenderedResult/ResultPanel.tsx +21 -1
  67. package/src/components/RenderedResult/chartPresentation.spec.ts +153 -0
  68. package/src/components/RenderedResult/chartPresentation.ts +166 -0
  69. package/src/components/RenderedResult/chartShapeProblem.spec.tsx +245 -0
  70. package/src/components/RenderedResult/chartShapeProblem.ts +219 -0
  71. package/src/components/RenderedResult/resultSizing.spec.ts +75 -3
  72. package/src/components/RenderedResult/resultSizing.ts +65 -11
  73. package/src/components/Report/Report.spec.tsx +19 -0
  74. package/src/components/Report/Report.tsx +8 -1
  75. package/src/components/Report/ReportPage.tsx +13 -1
  76. package/src/components/Report/layoutRules.spec.ts +43 -3
  77. package/src/components/Report/layoutRules.ts +70 -0
  78. package/src/components/Report/tileOverflow.spec.tsx +162 -0
  79. package/src/components/ReportBuilder/AddTileDialog.spec.tsx +2 -2
  80. package/src/components/ReportBuilder/AddTileDialog.tsx +11 -6
  81. package/src/components/ReportBuilder/BuilderBar.tsx +1 -1
  82. package/src/components/ReportBuilder/BuilderDialogs.tsx +20 -0
  83. package/src/components/ReportBuilder/BuilderGrid.tsx +126 -20
  84. package/src/components/ReportBuilder/ChartPicker.spec.ts +91 -4
  85. package/src/components/ReportBuilder/ChartPicker.tsx +45 -10
  86. package/src/components/ReportBuilder/DrillDialog.tsx +8 -2
  87. package/src/components/ReportBuilder/EditorSurface.tsx +110 -28
  88. package/src/components/ReportBuilder/FilterDialog.tsx +17 -8
  89. package/src/components/ReportBuilder/FilterStrip.tsx +2 -1
  90. package/src/components/ReportBuilder/ReportBuilder.charts.spec.tsx +193 -2
  91. package/src/components/ReportBuilder/ReportBuilder.controls.spec.tsx +4 -2
  92. package/src/components/ReportBuilder/ReportBuilder.notebook.spec.tsx +2 -2
  93. package/src/components/ReportBuilder/ReportBuilder.spec.tsx +143 -2
  94. package/src/components/ReportBuilder/ReportBuilder.tsx +73 -19
  95. package/src/components/ReportBuilder/ReportEditor.fileModel.spec.tsx +178 -0
  96. package/src/components/ReportBuilder/ReportEditor.modelFilters.spec.tsx +3 -5
  97. package/src/components/ReportBuilder/ReportEditor.queryVersion.spec.tsx +292 -0
  98. package/src/components/ReportBuilder/ReportEditor.readOnlyTitle.spec.tsx +92 -0
  99. package/src/components/ReportBuilder/ReportEditor.tsx +35 -0
  100. package/src/components/ReportBuilder/TileFrame.tsx +251 -6
  101. package/src/components/ReportBuilder/TileMenu.tsx +259 -20
  102. package/src/components/ReportBuilder/ViewPicker.tsx +4 -3
  103. package/src/components/ReportBuilder/addTileToDocument.spec.ts +34 -0
  104. package/src/components/ReportBuilder/addTileToDocument.ts +26 -1
  105. package/src/components/ReportBuilder/catalog.aggregate.spec.ts +137 -1
  106. package/src/components/ReportBuilder/catalog.ts +90 -37
  107. package/src/components/ReportBuilder/chartLine.spec.ts +42 -5
  108. package/src/components/ReportBuilder/chartLine.ts +80 -2
  109. package/src/components/ReportBuilder/controls.ts +4 -3
  110. package/src/components/ReportBuilder/document.ts +65 -7
  111. package/src/components/ReportBuilder/emptyStart.spec.ts +1 -1
  112. package/src/components/ReportBuilder/entryLayout.spec.ts +151 -0
  113. package/src/components/ReportBuilder/imports.ts +1 -1
  114. package/src/components/ReportBuilder/invariants.spec.ts +18 -10
  115. package/src/components/ReportBuilder/layout.ts +3 -0
  116. package/src/components/ReportBuilder/placement.spec.ts +193 -0
  117. package/src/components/ReportBuilder/placement.ts +250 -0
  118. package/src/components/ReportBuilder/preview.shapes.spec.ts +46 -6
  119. package/src/components/ReportBuilder/preview.spec.ts +151 -11
  120. package/src/components/ReportBuilder/preview.ts +203 -40
  121. package/src/components/ReportBuilder/preview.unsaved.compile.spec.ts +190 -0
  122. package/src/components/ReportBuilder/readDocument.spec.ts +46 -2
  123. package/src/components/ReportBuilder/readDocument.ts +194 -23
  124. package/src/components/ReportBuilder/scannerShapes.spec.ts +10 -10
  125. package/src/components/ReportBuilder/sortable.tsx +4 -0
  126. package/src/components/ReportBuilder/spliceDocument.chart.spec.ts +1 -1
  127. package/src/components/ReportBuilder/spliceDocument.color.spec.ts +80 -0
  128. package/src/components/ReportBuilder/spliceDocument.colspan.spec.ts +78 -0
  129. package/src/components/ReportBuilder/spliceDocument.spec.ts +110 -18
  130. package/src/components/ReportBuilder/spliceDocument.ts +139 -52
  131. package/src/components/ReportBuilder/statementExtent.spec.ts +3 -3
  132. package/src/components/ReportBuilder/testing/reportGivenOrder.json +42 -0
  133. package/src/components/ReportBuilder/textTiles.spec.ts +2 -2
  134. package/src/components/ReportBuilder/tileDisplayTitle.ts +2 -2
  135. package/src/components/ReportBuilder/useTileEditing.ts +16 -3
  136. package/src/components/ReportBuilder/useTileHeight.ts +149 -0
  137. package/src/components/ReportBuilder/useTileReorder.ts +143 -6
  138. package/src/components/ReportBuilder/useTileResize.ts +16 -1
  139. package/src/components/given/FilterButton.spec.tsx +27 -11
  140. package/src/components/given/FilterButton.tsx +19 -6
  141. package/src/theme/resolveTheme.spec.ts +72 -1
  142. package/src/theme/resolveTheme.ts +43 -0
  143. package/src/utils/blankQuoted.spec.ts +50 -0
  144. package/src/utils/blankQuoted.ts +32 -0
  145. package/src/utils/malloyText.ts +2 -1
  146. package/dist/RenderedResult-DtQtNV0d.cjs.js +0 -153
  147. package/dist/ServerProvider-BIFPCzTD.cjs.js +0 -1
  148. package/dist/useCompiledDocument-D0OAMejE.cjs.js +0 -142
@@ -7,7 +7,7 @@ import { previewTileQuery } from "./preview";
7
7
  import { openDocument, queryTile, spliced } from "./testing/fixtures";
8
8
 
9
9
  const NONE =
10
- "# -line_chart -bar_chart -big_value -scatter_chart -shape_map -segment_map -viz";
10
+ "# -line_chart -bar_chart -scatter_chart -shape_map -segment_map -combo_chart";
11
11
 
12
12
  const SHAPES = `## artifact { title="T" tiles=["a -> inl", "a -> comp", "a -> pipe", "a -> chain", "a -> paren", "a -> ref"] }
13
13
  import "../m.malloy"
@@ -34,17 +34,57 @@ describe("the Default chart preview, for the shapes a real dashboard reads", ()
34
34
  ).annotation,
35
35
  ]),
36
36
  );
37
+ // No tile here has a colour, so each one that runs its own saved view
38
+ // also takes off any colour that view was saved with.
39
+ const RESET = "# -theme.palette.series";
37
40
  expect(annotations).toEqual({
38
- inl: NONE,
39
- comp: NONE,
40
- pipe: NONE,
41
- chain: undefined,
42
- paren: undefined,
41
+ inl: `${NONE}\n${RESET}`,
42
+ comp: `${NONE}\n${RESET}`,
43
+ pipe: `${NONE}\n${RESET}`,
44
+ chain: RESET,
45
+ paren: RESET,
43
46
  ref: undefined,
44
47
  });
45
48
  });
46
49
  });
47
50
 
51
+ describe("the Theme colour preview, for the colour lines a real dashboard reads", () => {
52
+ const COLORS = `## artifact { title="T" tiles=["a -> picked", "a -> listed", "a -> block", "a -> spelled"] }
53
+ import "../m.malloy"
54
+
55
+ source: a is one extend {
56
+ # theme.palette.series=["#7f9862"]
57
+ view: picked is { group_by: x }
58
+ # theme.palette.series=["#111111", "#222222"]
59
+ view: listed is { group_by: x }
60
+ # theme { palette.series=["#111111"] }
61
+ view: block is { group_by: x }
62
+ # theme.palette.series = [ '#111111' ]
63
+ view: spelled is { group_by: x }
64
+ }`;
65
+
66
+ it("takes a builder colour off on Theme, and keeps a palette the author wrote", async () => {
67
+ const document = await openDocument(COLORS);
68
+ const annotations = Object.fromEntries(
69
+ document.tiles.map((tile) => {
70
+ // Theme: what the Color item's Theme leaves on the tile.
71
+ const { color: _picked, ...theme } = tile as QueryTile;
72
+ return [
73
+ tile.name,
74
+ previewTileQuery(document, theme as QueryTile, new Set())
75
+ .annotation,
76
+ ];
77
+ }),
78
+ );
79
+ expect(annotations).toEqual({
80
+ picked: "# -theme.palette.series",
81
+ listed: undefined,
82
+ block: undefined,
83
+ spelled: undefined,
84
+ });
85
+ });
86
+ });
87
+
48
88
  describe("a filter field is read and written as it stands", () => {
49
89
  const FILTERS = `##! experimental.givens
50
90
  ## artifact { title="T" tiles=["a -> x", "a -> y", "a -> z"] }
@@ -4,7 +4,9 @@
4
4
  import { describe, expect, it } from "bun:test";
5
5
  import type { GivenValue } from "../../hooks/givenValue";
6
6
  import type { DashboardDocument, QueryTile } from "./document";
7
- import { queryTile } from "./testing/fixtures";
7
+ import fs from "node:fs";
8
+ import path from "node:path";
9
+ import { openDocument, queryTile } from "./testing/fixtures";
8
10
  import {
9
11
  givensReadThroughModel,
10
12
  previewGivens,
@@ -53,7 +55,7 @@ const document: DashboardDocument = {
53
55
  };
54
56
 
55
57
  describe("previewGivens", () => {
56
- it("shows the givens some tile binds, this file's first, in declaration order", () => {
58
+ it("shows the givens some tile binds, tile by tile, in binding order", () => {
57
59
  const specs = previewGivens(document, [
58
60
  { name: "REGION", type: "filter<string>" },
59
61
  { name: "CATEGORY", type: "filter<string>", label: "From the model" },
@@ -144,6 +146,15 @@ describe("givens read through the model", () => {
144
146
  expect(
145
147
  previewGivens(recalls, MODEL, reads).map((spec) => spec.name),
146
148
  ).toEqual(MODEL.map((spec) => spec.name));
149
+ // With each tile's served reads, the reader's order: tile by tile.
150
+ expect(
151
+ previewGivens(recalls, MODEL, reads, served).map((spec) => spec.name),
152
+ ).toEqual([
153
+ "manufacturer_filter",
154
+ "recall_date_filter",
155
+ "major_recall_filter",
156
+ "subject_filter",
157
+ ]);
147
158
  // Without the reads, the row the builder drew before: empty.
148
159
  expect(previewGivens(recalls, MODEL)).toEqual([]);
149
160
  });
@@ -170,7 +181,7 @@ describe("givens read through the model", () => {
170
181
  expect([...reads]).toEqual(["manufacturer_filter"]);
171
182
  });
172
183
 
173
- it("puts this file's bound declarations first, then the model's", () => {
184
+ it("puts a tile's model reads before its own bindings", () => {
174
185
  const mixed: DashboardDocument = {
175
186
  ...recalls,
176
187
  localGivens: [{ name: "SINCE", type: "date", default: "@2020-01-01" }],
@@ -185,12 +196,12 @@ describe("givens read through the model", () => {
185
196
  };
186
197
  const reads = givensReadThroughModel(mixed, mixed, served);
187
198
  expect(
188
- previewGivens(mixed, MODEL, reads).map((spec) => spec.name),
199
+ previewGivens(mixed, MODEL, reads, served).map((spec) => spec.name),
189
200
  ).toEqual([
190
- "SINCE",
191
201
  "manufacturer_filter",
192
- "major_recall_filter",
193
202
  "recall_date_filter",
203
+ "major_recall_filter",
204
+ "SINCE",
194
205
  ]);
195
206
  });
196
207
 
@@ -244,10 +255,10 @@ describe("previewTileQuery", () => {
244
255
  runnable,
245
256
  ).annotation;
246
257
  expect(withChart("bar_chart")).toBe(
247
- "# -line_chart -big_value -scatter_chart -shape_map -segment_map -viz bar_chart",
258
+ "# -line_chart -big_value -scatter_chart -shape_map -segment_map -combo_chart -viz bar_chart",
248
259
  );
249
260
  expect(withChart("none")).toBe(
250
- "# -line_chart -bar_chart -big_value -scatter_chart -shape_map -segment_map -viz",
261
+ "# -line_chart -bar_chart -big_value -scatter_chart -shape_map -segment_map -combo_chart -viz",
251
262
  );
252
263
  expect(withChart("custom")).toBe("# bar_chart { size=spark }");
253
264
  expect(withChart("default")).toBeUndefined();
@@ -255,17 +266,29 @@ describe("previewTileQuery", () => {
255
266
  });
256
267
 
257
268
  it("clears the saved view's own chart line for an inline or opaque tile on Default", () => {
269
+ // Every chart tag off and `viz` left alone: not Table's line, so a view
270
+ // of totals still draws as big numbers, as it does with no line at all.
258
271
  const NONE =
259
- "# -line_chart -bar_chart -big_value -scatter_chart -shape_map -segment_map -viz";
272
+ "# -line_chart -bar_chart -scatter_chart -shape_map -segment_map -combo_chart";
273
+ // A colour is set so this reads the chart line alone; Theme's line is pinned below.
260
274
  const annotationOf = (
261
275
  declaration: QueryTile["declaration"],
262
276
  chart: QueryTile["chart"],
263
277
  ) =>
264
278
  previewTileQuery(
265
279
  document,
266
- { name: "x", source: "overview", declaration, chart },
280
+ {
281
+ name: "x",
282
+ source: "overview",
283
+ declaration,
284
+ chart,
285
+ color: "#123456",
286
+ },
267
287
  runnable,
268
- ).annotation;
288
+ )
289
+ .annotation?.split("\n")
290
+ .filter((line) => line !== '# theme.palette.series=["#123456"]')
291
+ .join("\n") || undefined;
269
292
  expect(annotationOf({ kind: "inline" }, "default")).toBe(NONE);
270
293
  for (const why of [
271
294
  "a `{ … } + { … }` compound refinement",
@@ -287,6 +310,42 @@ describe("previewTileQuery", () => {
287
310
  ).toBeUndefined();
288
311
  });
289
312
 
313
+ it("takes the saved view's colour off an inline or opaque tile set to Theme", () => {
314
+ // An inline tile runs its own saved view, which still carries the colour
315
+ // it was saved with: without this line, picking Theme kept drawing that
316
+ // colour while the menu showed the theme's. A reference tile runs its
317
+ // base view, which never had the wrapper's colour, so it needs none.
318
+ const RESET = "# -theme.palette.series";
319
+ const annotationOf = (
320
+ declaration: QueryTile["declaration"],
321
+ color?: string,
322
+ ) =>
323
+ previewTileQuery(
324
+ document,
325
+ {
326
+ name: "x",
327
+ source: "overview",
328
+ declaration,
329
+ chart: "combo_chart",
330
+ ...(color ? { color } : {}),
331
+ },
332
+ runnable,
333
+ ).annotation?.split("\n");
334
+ expect(annotationOf({ kind: "inline" })).toEqual([
335
+ "# -line_chart -bar_chart -big_value -scatter_chart -shape_map -segment_map -viz combo_chart",
336
+ RESET,
337
+ ]);
338
+ expect(
339
+ annotationOf({ kind: "opaque", why: "a chained refinement" })?.at(-1),
340
+ ).toBe(RESET);
341
+ expect(
342
+ annotationOf({ kind: "reference", from: "v" })?.includes(RESET),
343
+ ).toBe(false);
344
+ expect(annotationOf({ kind: "inline" }, "#7f9862")?.at(-1)).toBe(
345
+ '# theme.palette.series=["#7f9862"]',
346
+ );
347
+ });
348
+
290
349
  it("sends a tile only the givens it binds", () => {
291
350
  // `trend` binds CATEGORY alone: SINCE moving must not re-run it, and
292
351
  // unbinding a tile is what takes a control's effect off it.
@@ -352,6 +411,18 @@ describe("previewTileQuery", () => {
352
411
  expect(q.givenNames).toEqual(["CATEGORY"]);
353
412
  });
354
413
 
414
+ it("runs a named-query tile by its name, sending the whole row", () => {
415
+ const named: QueryTile = {
416
+ name: "by_carrier",
417
+ declaration: { kind: "query" },
418
+ };
419
+ expect(previewTileQuery(document, named, runnable)).toEqual({
420
+ expression: "by_carrier",
421
+ givenNames: undefined,
422
+ reads: undefined,
423
+ });
424
+ });
425
+
355
426
  it("runs an inherited tile as the model has it, sending the whole row", () => {
356
427
  const inherited: QueryTile = {
357
428
  name: "by_brand",
@@ -454,3 +525,72 @@ describe("previewTileQuery: a filter on a reserved field name", () => {
454
525
  );
455
526
  });
456
527
  });
528
+
529
+ /**
530
+ * The builder's row against the reader's, from one case table: the server's
531
+ * `report_given_order.spec.ts` compiles each report and pins the manifest's
532
+ * row and each tile's `givenNames`; here the same text is read into a
533
+ * document and the builder is handed what the server would hand it.
534
+ */
535
+ describe("previewGivens orders the row as the reader does", () => {
536
+ const { cases } = JSON.parse(
537
+ fs.readFileSync(
538
+ path.join(import.meta.dir, "testing/reportGivenOrder.json"),
539
+ "utf8",
540
+ ),
541
+ ) as {
542
+ cases: {
543
+ name: string;
544
+ report: string;
545
+ tiles: Record<string, string[]>;
546
+ row: string[];
547
+ }[];
548
+ };
549
+
550
+ for (const { name, report, tiles, row } of cases)
551
+ it(name, async () => {
552
+ const doc = await openDocument(report);
553
+ const served = new Map(
554
+ Object.entries(tiles).map(([query, names]) => [
555
+ tileExpressionKey(query),
556
+ names,
557
+ ]),
558
+ );
559
+ // The manifest's specs, as the builder gets them: the whole row.
560
+ const specs = row.map((given) => ({
561
+ name: given,
562
+ type: "filter<string>",
563
+ }));
564
+ const reads = givensReadThroughModel(doc, doc, served);
565
+ expect(
566
+ previewGivens(doc, specs, reads, served).map((spec) => spec.name),
567
+ ).toEqual(row);
568
+ });
569
+
570
+ it("puts a new binding after its tile's existing ones, where the save writes it", async () => {
571
+ // The first tile binds SINCE on a source that reads nothing; the
572
+ // second reads the model's MANUFACTURER and binds SUBJECT.
573
+ const shape = cases[3];
574
+ const opened = await openDocument(shape.report);
575
+ const served = new Map(
576
+ Object.entries(shape.tiles).map(([query, names]) => [
577
+ tileExpressionKey(query),
578
+ names,
579
+ ]),
580
+ );
581
+ const doc = structuredClone(opened);
582
+ // The first tile now binds SUBJECT too, so it moves up with that tile.
583
+ queryTile(doc, 0).filters = [
584
+ ...(queryTile(doc, 0).filters ?? []),
585
+ { field: "subject", given: "SUBJECT" },
586
+ ];
587
+ const specs = shape.row.map((given) => ({
588
+ name: given,
589
+ type: "filter<string>",
590
+ }));
591
+ const reads = givensReadThroughModel(doc, opened, served);
592
+ expect(
593
+ previewGivens(doc, specs, reads, served).map((spec) => spec.name),
594
+ ).toEqual(["SINCE", "SUBJECT", "MANUFACTURER"]);
595
+ });
596
+ });
@@ -4,14 +4,23 @@
4
4
  import type { Given } from "../../client";
5
5
  import type { GivenValue } from "../../hooks/givenValue";
6
6
  import { malloyLiteral } from "../../utils/malloyLiteral";
7
- import { chartLineText, isChartPick } from "./chartLine";
7
+ import {
8
+ chartLineText,
9
+ chartResetLine,
10
+ isChartPick,
11
+ seriesColorLine,
12
+ seriesColorResetLine,
13
+ } from "./chartLine";
8
14
  import {
9
15
  isQueryTile,
16
+ isReadOnlyTile,
17
+ tileExpression,
10
18
  type DashboardDocument,
11
19
  type QueryTile,
12
20
  } from "./document";
13
21
  import { malloyPath } from "../../utils/malloyText";
14
22
  import { localGivenSpec } from "./localGiven";
23
+ import { reaches, resolvedOf } from "./imports";
15
24
 
16
25
  /**
17
26
  * What a reader would see if the DOCUMENT were the file: the controls, and
@@ -29,43 +38,65 @@ import { localGivenSpec } from "./localGiven";
29
38
  */
30
39
 
31
40
  /**
32
- * The controls this document shows: every given some tile binds, this file's
33
- * own declarations first in declaration order, then the model's in the
34
- * manifest's order, whether a tile binds one in this file or reads it through
35
- * the model (`modelReads`, from {@link givensReadThroughModel}).
41
+ * The controls this document shows, in the order the reader shows them: every
42
+ * given some tile binds in this file or reads through the model (`modelReads`,
43
+ * from {@link givensReadThroughModel}).
36
44
  *
37
45
  * That is the reader's rule — only a given some tile reads becomes a control
38
- * — applied to the document instead of the manifest. A local declaration is
39
- * built into a `Given` from its control contract; a model given is the
40
- * manifest's own spec, which carries what the file cannot say (`givenNames` a
41
- * suggest is gated by, for one).
46
+ * — applied to the document instead of the manifest, and so is the order. The
47
+ * server builds the row tile by tile, in tile order, each tile's givens as its
48
+ * compiled query reads them: what the tile's source reads first, then the
49
+ * tile's own `where:` bindings. So here too: per tile, the givens its served
50
+ * self read (`servedReads`), less the bindings since removed, then the tile's
51
+ * current bindings not already listed — a new filter lands after the tile's
52
+ * existing ones, where the save will put it. A model read no tile position
53
+ * accounts for (no `servedReads` given) goes first, in the manifest's order,
54
+ * since a model read is a source's and the reader lists a source's first.
55
+ *
56
+ * A local declaration is built into a `Given` from its control contract, and
57
+ * wins over a model given of the same name; a model given is the manifest's
58
+ * own spec, which carries what the file cannot say (`givenNames` a suggest is
59
+ * gated by, for one).
42
60
  */
43
61
  export function previewGivens(
44
62
  document: DashboardDocument,
45
63
  modelSpecs: readonly Given[],
46
64
  modelReads: ReadonlySet<string> = new Set(),
65
+ servedReads: ReadonlyMap<string, readonly string[]> = new Map(),
47
66
  ): Given[] {
48
- const bound = new Set<string>();
49
- for (const tile of document.tiles)
50
- for (const filter of isQueryTile(tile) ? (tile.filters ?? []) : [])
51
- bound.add(filter.given);
67
+ const order: string[] = [];
68
+ for (const tile of document.tiles) {
69
+ if (!isQueryTile(tile)) continue;
70
+ const binds = (tile.filters ?? []).map((filter) => filter.given);
71
+ const served =
72
+ servedReads.get(tileExpressionKey(`${tile.source} -> ${tile.name}`)) ??
73
+ [];
74
+ for (const name of served)
75
+ if (modelReads.has(name) || binds.includes(name)) order.push(name);
76
+ order.push(...binds);
77
+ }
78
+ const placed = new Set(order);
79
+ const unplaced = modelSpecs.flatMap((spec) =>
80
+ spec.name !== undefined &&
81
+ modelReads.has(spec.name) &&
82
+ !placed.has(spec.name)
83
+ ? [spec.name]
84
+ : [],
85
+ );
52
86
 
87
+ const locals = new Map(
88
+ (document.localGivens ?? []).map((local) => [local.name, local]),
89
+ );
90
+ const models = new Map(
91
+ modelSpecs.flatMap((spec) =>
92
+ spec.name === undefined ? [] : [[spec.name, spec] as const],
93
+ ),
94
+ );
53
95
  const out: Given[] = [];
54
- const seen = new Set<string>();
55
- for (const local of document.localGivens ?? []) {
56
- if (!bound.has(local.name)) continue;
57
- seen.add(local.name);
58
- out.push(localGivenSpec(local));
59
- }
60
- for (const spec of modelSpecs) {
61
- if (
62
- spec.name === undefined ||
63
- seen.has(spec.name) ||
64
- !(bound.has(spec.name) || modelReads.has(spec.name))
65
- )
66
- continue;
67
- seen.add(spec.name);
68
- out.push(spec);
96
+ for (const name of new Set([...unplaced, ...order])) {
97
+ const local = locals.get(name);
98
+ const spec = local ? localGivenSpec(local) : models.get(name);
99
+ if (spec) out.push(spec);
69
100
  }
70
101
  return out;
71
102
  }
@@ -91,14 +122,14 @@ export function givensReadThroughModel(
91
122
  for (const tile of opened.tiles) {
92
123
  if (!isQueryTile(tile)) continue;
93
124
  boundWhenOpened.set(
94
- tileExpressionKey(`${tile.source} -> ${tile.name}`),
125
+ tileExpressionKey(tileExpression(tile)),
95
126
  new Set((tile.filters ?? []).map((filter) => filter.given)),
96
127
  );
97
128
  }
98
129
  const reads = new Set<string>();
99
130
  for (const tile of document.tiles) {
100
131
  if (!isQueryTile(tile)) continue;
101
- const key = tileExpressionKey(`${tile.source} -> ${tile.name}`);
132
+ const key = tileExpressionKey(tileExpression(tile));
102
133
  const bound = boundWhenOpened.get(key);
103
134
  for (const name of servedReads.get(key) ?? [])
104
135
  if (!bound?.has(name)) reads.add(name);
@@ -166,6 +197,107 @@ export interface PreviewTileQuery {
166
197
  * side reads no given either.
167
198
  */
168
199
  reads: string[] | undefined;
200
+ /**
201
+ * The package model to run on instead of the report's own. Set only where
202
+ * the tile's source comes in through an import the served report does not
203
+ * have yet; see {@link UnsavedSources}.
204
+ */
205
+ modelPath?: string;
206
+ }
207
+
208
+ /**
209
+ * What the builder added that the served model does not have yet, so a tile on
210
+ * it can be previewed before the save.
211
+ *
212
+ * Add tile puts a tile on the file's extension of its source, and where the
213
+ * file has none it declares a new one: `source: flights_tiles is flights extend
214
+ * { view: kpis_tile is kpis }`. Until the file is saved and served, the model
215
+ * the tiles run on has no `flights_tiles`, and `flights_tiles -> kpis` fails as
216
+ * a reference to an undefined object. A new extension declares no `where:` and
217
+ * no field, so its views are its base's, and `flights -> kpis` returns what the
218
+ * saved page will.
219
+ */
220
+ export interface UnsavedSources {
221
+ /** The document's extensions that the served model does not declare. */
222
+ sources: ReadonlySet<string>;
223
+ /**
224
+ * The package path of the model to run `base` on, when the served report
225
+ * cannot see `base` because its import is unsaved too. Undefined: the
226
+ * report's own model sees it.
227
+ */
228
+ modelOf?: (base: string) => string | undefined;
229
+ }
230
+
231
+ /**
232
+ * The {@link UnsavedSources} of `document` against the document as it was
233
+ * opened, which is what the served model was built from. Undefined when the
234
+ * document declares no extension the opened one did not.
235
+ *
236
+ * A base the opened file could not see came in with an import this session
237
+ * added, and runs on the model that import names. A report held as text has no
238
+ * imports: its sources are all the run model's.
239
+ */
240
+ export function unsavedSources(
241
+ document: DashboardDocument,
242
+ opened: DashboardDocument,
243
+ documentPath: string,
244
+ textHeld: boolean,
245
+ ): UnsavedSources | undefined {
246
+ const openedNames = new Set(opened.sources.map((s) => s.name));
247
+ const sources = new Set(
248
+ document.sources.map((s) => s.name).filter((n) => !openedNames.has(n)),
249
+ );
250
+ if (sources.size === 0) return undefined;
251
+ const modelOf = (base: string) => {
252
+ if (textHeld) return undefined;
253
+ const by = document.imports.find(
254
+ (i) => i.kind === "names" && i.names.includes(base),
255
+ );
256
+ if (by === undefined) return undefined;
257
+ const model = resolvedOf(by.from, documentPath);
258
+ return reaches(opened, base, model, documentPath) ? undefined : model;
259
+ };
260
+ return { sources, modelOf };
261
+ }
262
+
263
+ /**
264
+ * Where a reference tile on an unsaved extension resolves: the view it names,
265
+ * followed through that extension's own tiles (a copy of a new tile names the
266
+ * new tile's view) down to a source the served model has.
267
+ *
268
+ * Undefined when the tile runs on its own extension as usual, and when the
269
+ * chain reaches an extension that filters its tiles with a `where:`, whose base
270
+ * would show other rows than the saved page.
271
+ */
272
+ function runsOnBase(
273
+ document: DashboardDocument,
274
+ tile: QueryTile,
275
+ unsaved: UnsavedSources | undefined,
276
+ ): { source: string; view: string; modelPath?: string } | undefined {
277
+ if (!unsaved || tile.declaration.kind !== "reference") return undefined;
278
+ let source = tile.source;
279
+ let view = tile.declaration.from;
280
+ if (source === undefined || !unsaved.sources.has(source)) return undefined;
281
+ // Each step leaves an extension or follows one of its tiles, so this bound
282
+ // is never reached on a document the reader produced.
283
+ const bound = document.tiles.length + document.sources.length;
284
+ for (let step = 0; step <= bound; step++) {
285
+ if (!unsaved.sources.has(source)) {
286
+ const modelPath = unsaved.modelOf?.(source);
287
+ return { source, view, ...(modelPath ? { modelPath } : {}) };
288
+ }
289
+ const extension = document.sources.find((s) => s.name === source);
290
+ if (!extension || extension.scopedBy?.length) return undefined;
291
+ const own = document.tiles.find(
292
+ (t): t is QueryTile =>
293
+ isQueryTile(t) && t.source === source && t.name === view,
294
+ );
295
+ if (!own) source = extension.base;
296
+ else if (own.declaration.kind === "reference")
297
+ view = own.declaration.from;
298
+ else return undefined;
299
+ }
300
+ return undefined;
169
301
  }
170
302
 
171
303
  /**
@@ -212,12 +344,14 @@ export function previewTileQuery(
212
344
  values: ReadonlyMap<string, GivenValue> = new Map(),
213
345
  /** What the served file's compiled tile reads (`DashboardTile.givenNames`), when it has this tile. */
214
346
  served?: readonly string[],
347
+ /** What the served model does not have yet; see {@link UnsavedSources}. */
348
+ unsaved?: UnsavedSources,
215
349
  ): PreviewTileQuery {
216
- if (tile.declaration.kind === "inherited") {
217
- // Declared in the model; bindings live there too, out of this
218
- // document's reach, so the server is sent the whole row as it does.
350
+ if (isReadOnlyTile(tile)) {
351
+ // Declared in the model, or a named query; bindings live there too, out
352
+ // of this document's reach, so the server is sent the whole row as it does.
219
353
  return {
220
- expression: `${tile.source} -> ${tile.name}`,
354
+ expression: tileExpression(tile),
221
355
  givenNames: undefined,
222
356
  reads: served && [...served],
223
357
  };
@@ -228,9 +362,20 @@ export function previewTileQuery(
228
362
  // source-level `where:`, a `# drill` dimension — which the base does not.
229
363
  // Running on the base showed unscoped numbers for a dashboard that scopes
230
364
  // its source, and the saved page then differed from what the author watched.
231
- const on = tile.source;
365
+ //
366
+ // Except on an extension the served model does not have yet, which runs
367
+ // where it resolves to instead; see `runsOnBase`.
368
+ const fallback = runsOnBase(document, tile, unsaved);
369
+ const on = fallback?.source ?? tile.source;
232
370
  const baseView =
233
- tile.declaration.kind === "reference" ? tile.declaration.from : tile.name;
371
+ fallback?.view ??
372
+ (tile.declaration.kind === "reference"
373
+ ? tile.declaration.from
374
+ : tile.name);
375
+ // A model other than the report's declares none of the report's givens, so
376
+ // every binding is written there as a literal.
377
+ const sendable =
378
+ fallback?.modelPath !== undefined ? new Set<string>() : runnable;
234
379
  const localTypes = new Map(
235
380
  (document.localGivens ?? []).map((local) => [local.name, local.type]),
236
381
  );
@@ -245,14 +390,14 @@ export function previewTileQuery(
245
390
  document.sources.find((source) => source.name === on)?.scopedBy ?? [];
246
391
  // What the served tile reads moves it in the reader, so the preview sends it too.
247
392
  const sent = new Set(
248
- [...scopedBy, ...(served ?? [])].filter((name) => runnable.has(name)),
393
+ [...scopedBy, ...(served ?? [])].filter((name) => sendable.has(name)),
249
394
  );
250
395
  // A binding removed but not yet saved still counts here until the save.
251
396
  const reads = new Set<string>([...scopedBy, ...(served ?? [])]);
252
397
  const clauses: string[] = [];
253
398
  for (const filter of tile.filters ?? []) {
254
399
  const comparison = `where: ${malloyPath(filter.field)} ${filter.op ?? "~"}`;
255
- if (runnable.has(filter.given)) {
400
+ if (sendable.has(filter.given)) {
256
401
  sent.add(filter.given);
257
402
  reads.add(filter.given);
258
403
  clauses.push(`${comparison} $${filter.given}`);
@@ -270,16 +415,34 @@ export function previewTileQuery(
270
415
  }
271
416
  const refinement = clauses.join(", ");
272
417
  const chart = tile.chart;
273
- const annotation =
418
+ const chartAnnotation =
274
419
  chart === "none" || isChartPick(chart)
275
420
  ? chartLineText(chart, tile.chartCarried)
276
421
  : chart === "custom" && tile.chartLines?.length
277
422
  ? tile.chartLines.join("\n")
278
423
  : chart === "default" && dropsBaseChart(tile.declaration)
279
- ? chartLineText("none")
424
+ ? chartResetLine()
280
425
  : undefined;
426
+ // The tile's colour, under its chart line: the base view never saw the
427
+ // wrapper's line, so the preview carries it as it carries the chart. With
428
+ // no colour (Theme), an inline or opaque tile runs its own SAVED view, whose
429
+ // last-saved colour line would still apply, so the preview takes it off.
430
+ // Not where the tile's own tags carry a palette the builder did not write:
431
+ // that line is the author's, it stays in the file, and the page draws it.
432
+ const colorAnnotation =
433
+ tile.color !== undefined
434
+ ? seriesColorLine(tile.color)
435
+ : tile.declaration.kind !== "reference" && !tile.ownPalette
436
+ ? seriesColorResetLine
437
+ : undefined;
438
+ const annotation =
439
+ [chartAnnotation, colorAnnotation].filter(Boolean).join("\n") ||
440
+ undefined;
281
441
  return {
282
442
  ...(annotation ? { annotation } : {}),
443
+ ...(fallback?.modelPath !== undefined
444
+ ? { modelPath: fallback.modelPath }
445
+ : {}),
283
446
  expression:
284
447
  `${on} -> ${baseView}` + (refinement ? ` + { ${refinement} }` : ""),
285
448
  givenNames: Array.from(sent),