@malloy-publisher/sdk 0.9.14 → 0.9.16

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 (164) hide show
  1. package/dist/RenderedResult-5hOs5XnV.cjs.js +171 -0
  2. package/dist/RenderedResult-DxmHGZNQ.es.js +671 -0
  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 +7732 -6717
  7. package/dist/builder-entry.d.ts +1 -1
  8. package/dist/client/api.d.ts +31 -7
  9. package/dist/client/index.cjs.js +1 -1
  10. package/dist/client/index.es.js +1 -1
  11. package/dist/components/Dashboard/DashboardGrid.d.ts +51 -1
  12. package/dist/components/Dashboard/DashboardTile.d.ts +7 -2
  13. package/dist/components/Dashboard/DashboardView.d.ts +9 -2
  14. package/dist/components/Dashboard/index.d.ts +1 -1
  15. package/dist/components/Dashboard/promoteMeasureRow.d.ts +5 -7
  16. package/dist/components/Dashboard/useStuck.d.ts +18 -12
  17. package/dist/components/RenderedResult/RenderedResult.d.ts +3 -2
  18. package/dist/components/RenderedResult/ResultContainer.d.ts +18 -1
  19. package/dist/components/RenderedResult/ResultPanel.d.ts +7 -1
  20. package/dist/components/RenderedResult/chartPresentation.d.ts +15 -0
  21. package/dist/components/RenderedResult/chartShapeProblem.d.ts +55 -0
  22. package/dist/components/RenderedResult/resultSizing.d.ts +47 -6
  23. package/dist/components/Report/Report.d.ts +7 -1
  24. package/dist/components/Report/ReportPage.d.ts +7 -0
  25. package/dist/components/Report/layoutRules.d.ts +45 -0
  26. package/dist/components/ReportBuilder/AddTileDialog.d.ts +2 -1
  27. package/dist/components/ReportBuilder/ArrangeMenu.d.ts +9 -0
  28. package/dist/components/ReportBuilder/BuilderGrid.d.ts +15 -4
  29. package/dist/components/ReportBuilder/BuilderToolbar.d.ts +3 -1
  30. package/dist/components/ReportBuilder/ChartPicker.d.ts +4 -2
  31. package/dist/components/ReportBuilder/EditorSurface.d.ts +10 -1
  32. package/dist/components/ReportBuilder/ReportBuilder.d.ts +1 -1
  33. package/dist/components/ReportBuilder/TileFrame.d.ts +54 -10
  34. package/dist/components/ReportBuilder/TileMenu.d.ts +5 -2
  35. package/dist/components/ReportBuilder/builderControls.d.ts +19 -0
  36. package/dist/components/ReportBuilder/catalog.d.ts +23 -0
  37. package/dist/components/ReportBuilder/chartLine.d.ts +38 -5
  38. package/dist/components/ReportBuilder/controls.d.ts +2 -2
  39. package/dist/components/ReportBuilder/document.d.ts +53 -5
  40. package/dist/components/ReportBuilder/imports.d.ts +7 -0
  41. package/dist/components/ReportBuilder/placement.d.ts +121 -0
  42. package/dist/components/ReportBuilder/preview.d.ts +59 -10
  43. package/dist/components/ReportBuilder/sortable.d.ts +12 -1
  44. package/dist/components/ReportBuilder/useBuilderSession.d.ts +1 -1
  45. package/dist/components/ReportBuilder/useBuilderShortcuts.d.ts +9 -1
  46. package/dist/components/ReportBuilder/useEdgeResize.d.ts +84 -0
  47. package/dist/components/ReportBuilder/useTileReorder.d.ts +30 -3
  48. package/dist/index.cjs.js +7 -7
  49. package/dist/index.es.js +3349 -3307
  50. package/dist/text/index.es.js +1 -1
  51. package/dist/{text-entry-72YFLeNk.es.js → text-entry-YKJZbRPo.es.js} +2 -2
  52. package/dist/theme/classes.d.ts +1 -1
  53. package/dist/theme/resolveTheme.d.ts +15 -0
  54. package/dist/{useCompiledDocument-B4QF1mIl.es.js → useCompiledDocument-CaYP_OYG.es.js} +6353 -6047
  55. package/dist/useCompiledDocument-zYEfLogf.cjs.js +142 -0
  56. package/dist/utils/blankQuoted.d.ts +15 -0
  57. package/package.json +1 -1
  58. package/src/builder-entry.ts +1 -0
  59. package/src/components/Dashboard/DashboardGrid.tsx +129 -10
  60. package/src/components/Dashboard/DashboardTile.tsx +15 -1
  61. package/src/components/Dashboard/DashboardView.tsx +64 -10
  62. package/src/components/Dashboard/TileCard.tsx +6 -0
  63. package/src/components/Dashboard/index.ts +1 -0
  64. package/src/components/Dashboard/promoteMeasureRow.spec.ts +19 -0
  65. package/src/components/Dashboard/promoteMeasureRow.ts +15 -36
  66. package/src/components/Dashboard/tileHeight.spec.ts +72 -0
  67. package/src/components/Dashboard/useStuck.ts +76 -28
  68. package/src/components/Package/NewDocumentDialog.spec.tsx +20 -16
  69. package/src/components/Package/NewDocumentDialog.tsx +10 -11
  70. package/src/components/RenderedResult/RenderedResult.lifecycle.spec.tsx +167 -2
  71. package/src/components/RenderedResult/RenderedResult.tsx +39 -6
  72. package/src/components/RenderedResult/ResultContainer.tsx +99 -10
  73. package/src/components/RenderedResult/ResultPanel.tsx +25 -1
  74. package/src/components/RenderedResult/chartPresentation.spec.ts +153 -0
  75. package/src/components/RenderedResult/chartPresentation.ts +166 -0
  76. package/src/components/RenderedResult/chartShapeProblem.spec.tsx +245 -0
  77. package/src/components/RenderedResult/chartShapeProblem.ts +219 -0
  78. package/src/components/RenderedResult/resultSizing.spec.ts +75 -3
  79. package/src/components/RenderedResult/resultSizing.ts +71 -11
  80. package/src/components/Report/Report.spec.tsx +19 -0
  81. package/src/components/Report/Report.tsx +8 -1
  82. package/src/components/Report/ReportPage.tsx +13 -1
  83. package/src/components/Report/layoutRules.spec.ts +43 -3
  84. package/src/components/Report/layoutRules.ts +70 -0
  85. package/src/components/Report/tileOverflow.spec.tsx +162 -0
  86. package/src/components/ReportBuilder/AddTileDialog.spec.tsx +2 -2
  87. package/src/components/ReportBuilder/AddTileDialog.tsx +11 -6
  88. package/src/components/ReportBuilder/ArrangeMenu.tsx +80 -0
  89. package/src/components/ReportBuilder/BuilderBar.tsx +5 -1
  90. package/src/components/ReportBuilder/BuilderDialogs.tsx +28 -1
  91. package/src/components/ReportBuilder/BuilderGrid.tsx +142 -35
  92. package/src/components/ReportBuilder/BuilderToolbar.tsx +4 -0
  93. package/src/components/ReportBuilder/ChartPicker.spec.ts +91 -4
  94. package/src/components/ReportBuilder/ChartPicker.tsx +45 -10
  95. package/src/components/ReportBuilder/DrillDialog.tsx +8 -2
  96. package/src/components/ReportBuilder/EditorSurface.tsx +101 -20
  97. package/src/components/ReportBuilder/FilterDialog.tsx +17 -8
  98. package/src/components/ReportBuilder/FilterStrip.tsx +2 -1
  99. package/src/components/ReportBuilder/ReportBuilder.charts.spec.tsx +193 -2
  100. package/src/components/ReportBuilder/ReportBuilder.controls.spec.tsx +4 -2
  101. package/src/components/ReportBuilder/ReportBuilder.notebook.spec.tsx +2 -2
  102. package/src/components/ReportBuilder/ReportBuilder.spec.tsx +242 -2
  103. package/src/components/ReportBuilder/ReportBuilder.tsx +161 -27
  104. package/src/components/ReportBuilder/ReportEditor.fileModel.spec.tsx +178 -0
  105. package/src/components/ReportBuilder/ReportEditor.modelFilters.spec.tsx +3 -5
  106. package/src/components/ReportBuilder/ReportEditor.readOnlyTitle.spec.tsx +92 -0
  107. package/src/components/ReportBuilder/ReportEditor.tsx +13 -0
  108. package/src/components/ReportBuilder/TileFrame.tsx +366 -170
  109. package/src/components/ReportBuilder/TileMenu.tsx +259 -20
  110. package/src/components/ReportBuilder/ViewPicker.tsx +4 -3
  111. package/src/components/ReportBuilder/addTileToDocument.spec.ts +34 -0
  112. package/src/components/ReportBuilder/addTileToDocument.ts +26 -1
  113. package/src/components/ReportBuilder/builderControls.ts +34 -0
  114. package/src/components/ReportBuilder/catalog.aggregate.spec.ts +137 -1
  115. package/src/components/ReportBuilder/catalog.ts +90 -37
  116. package/src/components/ReportBuilder/chartLine.spec.ts +42 -5
  117. package/src/components/ReportBuilder/chartLine.ts +80 -2
  118. package/src/components/ReportBuilder/controls.ts +4 -3
  119. package/src/components/ReportBuilder/document.ts +65 -7
  120. package/src/components/ReportBuilder/emptyStart.spec.ts +1 -1
  121. package/src/components/ReportBuilder/entryLayout.spec.ts +151 -0
  122. package/src/components/ReportBuilder/imports.ts +1 -1
  123. package/src/components/ReportBuilder/invariants.spec.ts +18 -10
  124. package/src/components/ReportBuilder/layout.ts +3 -0
  125. package/src/components/ReportBuilder/placement.spec.ts +401 -0
  126. package/src/components/ReportBuilder/placement.ts +416 -0
  127. package/src/components/ReportBuilder/preview.shapes.spec.ts +46 -6
  128. package/src/components/ReportBuilder/preview.spec.ts +151 -11
  129. package/src/components/ReportBuilder/preview.ts +203 -40
  130. package/src/components/ReportBuilder/preview.unsaved.compile.spec.ts +190 -0
  131. package/src/components/ReportBuilder/readDocument.spec.ts +53 -19
  132. package/src/components/ReportBuilder/readDocument.ts +197 -29
  133. package/src/components/ReportBuilder/scannerShapes.spec.ts +10 -10
  134. package/src/components/ReportBuilder/sortable.tsx +30 -2
  135. package/src/components/ReportBuilder/spliceDocument.chart.spec.ts +1 -1
  136. package/src/components/ReportBuilder/spliceDocument.color.spec.ts +80 -0
  137. package/src/components/ReportBuilder/spliceDocument.colspan.spec.ts +78 -0
  138. package/src/components/ReportBuilder/spliceDocument.spec.ts +110 -58
  139. package/src/components/ReportBuilder/spliceDocument.ts +139 -91
  140. package/src/components/ReportBuilder/statementExtent.spec.ts +3 -3
  141. package/src/components/ReportBuilder/testing/reportGivenOrder.json +42 -0
  142. package/src/components/ReportBuilder/textTiles.spec.ts +2 -2
  143. package/src/components/ReportBuilder/tileDisplayTitle.ts +2 -2
  144. package/src/components/ReportBuilder/useBuilderSession.ts +7 -2
  145. package/src/components/ReportBuilder/useBuilderShortcuts.ts +25 -1
  146. package/src/components/ReportBuilder/useEdgeResize.spec.tsx +324 -0
  147. package/src/components/ReportBuilder/useEdgeResize.ts +397 -0
  148. package/src/components/ReportBuilder/useTileEditing.ts +16 -3
  149. package/src/components/ReportBuilder/useTileReorder.ts +143 -6
  150. package/src/components/given/FilterButton.spec.tsx +27 -11
  151. package/src/components/given/FilterButton.tsx +19 -6
  152. package/src/theme/classes.ts +1 -1
  153. package/src/theme/resolveTheme.spec.ts +72 -1
  154. package/src/theme/resolveTheme.ts +43 -0
  155. package/src/utils/blankQuoted.spec.ts +50 -0
  156. package/src/utils/blankQuoted.ts +32 -0
  157. package/src/utils/malloyText.ts +2 -1
  158. package/dist/RenderedResult-DnBtf-cI.es.js +0 -593
  159. package/dist/RenderedResult-DtQtNV0d.cjs.js +0 -153
  160. package/dist/ServerProvider-BIFPCzTD.cjs.js +0 -1
  161. package/dist/components/ReportBuilder/useTileResize.d.ts +0 -32
  162. package/dist/useCompiledDocument-D0OAMejE.cjs.js +0 -142
  163. package/src/components/ReportBuilder/useTileResize.spec.tsx +0 -146
  164. package/src/components/ReportBuilder/useTileResize.ts +0 -133
@@ -0,0 +1,190 @@
1
+ // Copyright (c) Credible Data Inc.
2
+ // SPDX-License-Identifier: MIT
3
+
4
+ import { describe, expect, it, setDefaultTimeout } from "bun:test";
5
+ import * as fs from "fs";
6
+ import * as path from "path";
7
+ import { fileURLToPath, pathToFileURL } from "url";
8
+ import { addTileToDocument } from "./addTileToDocument";
9
+ import { isQueryTile, type QueryTile } from "./document";
10
+ import { previewTileQuery, unsavedSources } from "./preview";
11
+ import { spliceDashboardDocument, spliceFailed } from "./spliceDocument";
12
+ import { openDocument } from "./testing/fixtures";
13
+
14
+ /**
15
+ * A tile added on a source the file has no extension of goes on a NEW
16
+ * extension, which the served model does not have until the file is saved. Its
17
+ * preview is run here by Malloy against the served file, as the server runs it,
18
+ * and its rows are checked against the saved file's own tile.
19
+ */
20
+ const PACKAGE = path.resolve(
21
+ import.meta.dir,
22
+ "../../../../../examples/storefront",
23
+ );
24
+ const DOCUMENT = "dashboards/x.malloy";
25
+
26
+ // DuckDB from cold, as in addTile.compile.spec.ts.
27
+ setDefaultTimeout(30_000);
28
+
29
+ async function loadPackage() {
30
+ const { Runtime } = await import("@malloydata/malloy");
31
+ const { DuckDBConnection } = await import("@malloydata/db-duckdb");
32
+ const connection = new DuckDBConnection("duckdb", ":memory:", PACKAGE);
33
+ const overlay = new Map<string, string>();
34
+ const runtime = new Runtime({
35
+ urlReader: {
36
+ readURL: async (at: URL) =>
37
+ overlay.get(at.href) ??
38
+ fs.readFileSync(fileURLToPath(at.href), "utf8"),
39
+ },
40
+ connections: { lookupConnection: async () => connection },
41
+ } as never);
42
+ const urlOf = (file: string) => pathToFileURL(path.join(PACKAGE, file)).href;
43
+ return {
44
+ /** Serve `text` as the report file. */
45
+ serve: (text: string) => overlay.set(urlOf(DOCUMENT), text),
46
+ /** Run `query` on the served `model`: its rows, or the error. */
47
+ rows: async (model: string, query: string) => {
48
+ try {
49
+ const result = await runtime
50
+ .loadModel(new URL(urlOf(model)))
51
+ .loadQuery(query)
52
+ .run();
53
+ return { rows: result.data.toObject() };
54
+ } catch (error) {
55
+ return { error: String(error) };
56
+ }
57
+ },
58
+ close: () => connection.close(),
59
+ };
60
+ }
61
+
62
+ const FILE = (imports: string) => `##! experimental.givens
63
+ ## artifact { title="X" tiles=[] } dashboard { columns=12 }
64
+ ${imports}
65
+ `;
66
+
67
+ /** The served file, the document after an add-tile on `base`, and the file that add saves. */
68
+ async function addOn(served: string, base: string) {
69
+ const opened = await openDocument(served);
70
+ const document = structuredClone(opened);
71
+ addTileToDocument(
72
+ document,
73
+ {
74
+ base,
75
+ modelPath: "storefront.malloy",
76
+ exporters: ["storefront.malloy"],
77
+ view: "by_category",
78
+ colspan: 6,
79
+ },
80
+ { modelPath: DOCUMENT, textHeld: false, widths: true },
81
+ );
82
+ const saved = await spliceDashboardDocument(served, document);
83
+ if (spliceFailed(saved)) throw new Error(saved.reason);
84
+ const tile = document.tiles.filter(isQueryTile).at(-1) as QueryTile;
85
+ return { opened, document, tile, saved: saved.source };
86
+ }
87
+
88
+ describe("a tile on an extension the served model does not have yet", () => {
89
+ it("follows a copy of a new tile to the view it shows, and keeps a filtering extension", () => {
90
+ const tile = (name: string, source: string, from: string): QueryTile => ({
91
+ name,
92
+ source,
93
+ declaration: { kind: "reference", from },
94
+ });
95
+ const document = {
96
+ layout: "grid" as const,
97
+ title: "T",
98
+ imports: [],
99
+ sources: [
100
+ { name: "a_tiles", base: "a" },
101
+ { name: "a_tiles_tiles", base: "a_tiles" },
102
+ { name: "scoped", base: "a", scopedBy: ["X"] },
103
+ ],
104
+ tiles: [
105
+ tile("v_tile", "a_tiles", "v"),
106
+ tile("v_tile_tile", "a_tiles_tiles", "v_tile"),
107
+ tile("w_tile", "scoped", "w"),
108
+ ],
109
+ };
110
+ const unsaved = {
111
+ sources: new Set(["a_tiles", "a_tiles_tiles", "scoped"]),
112
+ };
113
+ const run = (t: QueryTile) =>
114
+ previewTileQuery(document, t, new Set(), new Map(), undefined, unsaved)
115
+ .expression;
116
+ expect(run(document.tiles[0])).toBe("a -> v");
117
+ expect(run(document.tiles[1])).toBe("a -> v");
118
+ // Its base would show rows its `where:` leaves out: run as before.
119
+ expect(run(document.tiles[2])).toBe("scoped -> w");
120
+ });
121
+
122
+ it("fails as a reference to an undefined object when run on that extension", async () => {
123
+ const pkg = await loadPackage();
124
+ try {
125
+ const served = FILE(
126
+ 'import { order_items } from "../storefront.malloy"',
127
+ );
128
+ const { document, tile } = await addOn(served, "order_items");
129
+ const q = previewTileQuery(document, tile, new Set());
130
+ pkg.serve(served);
131
+ const run = await pkg.rows(DOCUMENT, `run: ${q.expression}`);
132
+ expect(q.expression).toBe("order_items_tiles -> by_category");
133
+ expect(run.error).toContain("order_items_tiles");
134
+ } finally {
135
+ await pkg.close();
136
+ }
137
+ });
138
+
139
+ for (const [why, imports, model] of [
140
+ [
141
+ "a source the file imports",
142
+ 'import { order_items } from "../storefront.malloy"',
143
+ undefined,
144
+ ],
145
+ [
146
+ "a source whose import is unsaved too",
147
+ 'import { products } from "../storefront.malloy"',
148
+ "storefront.malloy",
149
+ ],
150
+ ] as const)
151
+ it(`previews what the saved page shows, on ${why}`, async () => {
152
+ const pkg = await loadPackage();
153
+ try {
154
+ const served = FILE(imports);
155
+ const { opened, document, tile, saved } = await addOn(
156
+ served,
157
+ "order_items",
158
+ );
159
+ expect(tile.source).toBe("order_items_tiles");
160
+
161
+ const q = previewTileQuery(
162
+ document,
163
+ tile,
164
+ new Set(),
165
+ new Map(),
166
+ undefined,
167
+ unsavedSources(document, opened, DOCUMENT, false),
168
+ );
169
+ expect(q.expression).toBe("order_items -> by_category");
170
+ expect(q.modelPath).toBe(model);
171
+ pkg.serve(served);
172
+ const preview = await pkg.rows(
173
+ q.modelPath ?? DOCUMENT,
174
+ `${q.annotation ? `${q.annotation}\n` : ""}run: ${q.expression}`,
175
+ );
176
+ expect(preview.error).toBeUndefined();
177
+
178
+ pkg.serve(saved);
179
+ const page = await pkg.rows(
180
+ DOCUMENT,
181
+ `run: ${tile.source} -> ${tile.name}`,
182
+ );
183
+ expect(page.error).toBeUndefined();
184
+ expect(page.rows?.length).toBeGreaterThan(0);
185
+ expect(preview.rows).toEqual(page.rows);
186
+ } finally {
187
+ await pkg.close();
188
+ }
189
+ });
190
+ });
@@ -192,42 +192,32 @@ describe("blockAbove", () => {
192
192
  });
193
193
 
194
194
  describe("readDashboardDocument", () => {
195
- it("reads a width spelled only as the dashboard_columns alias", async () => {
196
- const doc = await read(
197
- SIMPLE.replace(
198
- '"a -> by_cat"] givens { CATEGORY="Jeans" } } dashboard { columns=12 }',
199
- '"a -> by_cat"] givens { CATEGORY="Jeans" } dashboard_columns=8 }',
200
- ),
201
- );
202
- expect(doc.columns).toBe(8);
203
- });
204
-
205
195
  describe("a width written badly", () => {
206
196
  const withTag = (tagLine: string) =>
207
197
  SIMPLE.replace(/^## artifact.*$/m, tagLine);
208
198
 
209
- it("lets a written columns win even when it is not a width", async () => {
199
+ it("leaves the default width for a columns that is not a width", async () => {
210
200
  const doc = await read(
211
201
  withTag(
212
- '## artifact { tiles=["a -> by_cat"] dashboard_columns=8 } dashboard { columns=1.5 }',
202
+ '## artifact { tiles=["a -> by_cat"] } dashboard { columns=1.5 }',
213
203
  ),
214
204
  );
215
205
  expect(doc.columns).toBeUndefined();
216
206
  });
217
207
 
218
- it("reads the alias, spaced round its =, when no columns is written", async () => {
208
+ it("takes text that only begins with digits as no width", async () => {
219
209
  const doc = await read(
220
210
  withTag(
221
- '## artifact { tiles=["a -> by_cat"] dashboard_columns = 8 }',
211
+ '## artifact { tiles=["a -> by_cat"] } dashboard { columns="8px" }',
222
212
  ),
223
213
  );
224
- expect(doc.columns).toBe(8);
214
+ expect(doc.columns).toBeUndefined();
225
215
  });
226
216
 
227
- it("takes text that only begins with digits as no width", async () => {
217
+ it("reads no width from the removed dashboard_columns spelling", async () => {
228
218
  const doc = await read(
229
219
  withTag(
230
- '## artifact { tiles=["a -> by_cat"] dashboard_columns=8px }',
220
+ '## artifact { tiles=["a -> by_cat"] dashboard_columns=8 }',
231
221
  ),
232
222
  );
233
223
  expect(doc.columns).toBeUndefined();
@@ -802,14 +792,58 @@ describe("readDashboardDocument: what it refuses", () => {
802
792
  if (readFailed(r)) expect(r.reason).toContain("not a report");
803
793
  });
804
794
 
805
- it("refuses a tile that is not a source -> view expression", async () => {
795
+ it("refuses a tile that is neither a source -> view expression nor a query's name", async () => {
806
796
  const r = await readDashboardDocument(
807
- `## artifact { title="T" tiles=["just_a_name"] }\nsource: a is b extend { view: x is y }`,
797
+ `## artifact { title="T" tiles=["a -> x -> y"] }\nsource: a is b extend { view: x is y }`,
808
798
  );
809
799
  expect(r.ok).toBe(false);
810
800
  if (readFailed(r)) expect(r.reason).toContain("source -> view");
811
801
  });
812
802
 
803
+ // The server's reader runs a quoted bare name as `run: <name>`, so a report
804
+ // listing a named query is served; the builder used to refuse it whole.
805
+ it("opens a tile that names a query, read-only and with no source", async () => {
806
+ const doc = await read(
807
+ `## artifact { title="T" tiles=["by_carrier", "flights -> by_month"] }\nimport { flights } from '../flights.malloy'\n\nquery: by_carrier is flights -> { group_by: carrier; aggregate: flight_count }`,
808
+ );
809
+ expect(doc.tiles).toEqual([
810
+ { name: "by_carrier", declaration: { kind: "query" } },
811
+ {
812
+ name: "by_month",
813
+ source: "flights",
814
+ declaration: { kind: "inherited" },
815
+ },
816
+ ]);
817
+ expect(tileKey(doc.tiles[0])).toBe("query.by_carrier");
818
+ });
819
+
820
+ // The bare spelling (`tiles=[by_carrier]`) is the query-tile form the docs
821
+ // give, and the server reads it the same way.
822
+ it("opens a tile that names a query unquoted", async () => {
823
+ const doc = await read(
824
+ `## artifact { title="T" tiles=[by_carrier, "flights -> by_month"] }\nimport { flights } from '../flights.malloy'\n\nquery: by_carrier is flights -> { group_by: carrier; aggregate: flight_count }`,
825
+ );
826
+ expect(doc.tiles[0]).toEqual({
827
+ name: "by_carrier",
828
+ declaration: { kind: "query" },
829
+ });
830
+ });
831
+
832
+ // The reader frames a query tile by the query's own tags, so the builder
833
+ // draws it at the same width and on the same row.
834
+ it("reads a query tile's frame off the query's own tags", async () => {
835
+ const doc = await read(
836
+ `## artifact { title="T" tiles=["flights -> by_month", "by_carrier"] } dashboard { columns=12 }\nimport { flights } from '../flights.malloy'\n\n# colspan=6\n# break\n# label="By airline"\nquery: by_carrier is flights -> { group_by: carrier; aggregate: flight_count }`,
837
+ );
838
+ expect(doc.tiles[1]).toEqual({
839
+ name: "by_carrier",
840
+ declaration: { kind: "query" },
841
+ label: "By airline",
842
+ colspan: 6,
843
+ break: true,
844
+ });
845
+ });
846
+
813
847
  // NOT a refusal, and the tripwire is what taught us so: a dashboard whose
814
848
  // only tile reads a view on an IMPORTED source declares nothing at all, and
815
849
  // is a complete dashboard. It opens, and that tile is read-only because its
@@ -1,9 +1,11 @@
1
1
  // Copyright (c) Credible Data Inc.
2
2
  // SPDX-License-Identifier: MIT
3
3
 
4
+ import type { Tag } from "@malloydata/malloy-tag";
4
5
  import {
5
6
  chartLinesOf,
6
7
  chartStateOfTagLines,
8
+ seriesColorOf,
7
9
  type ChartState,
8
10
  } from "./chartLine";
9
11
  import type {
@@ -151,13 +153,35 @@ const tagText = (tags: Array<{ text: string }>) => tags.map((t) => t.text);
151
153
  function chartField(tags: Array<{ text: string }>): {
152
154
  chart?: ChartState;
153
155
  chartLines?: string[];
156
+ color?: string;
154
157
  } {
155
158
  const lines = tagText(tags);
156
159
  const chart = chartStateOfTagLines(lines);
157
- if (chart === undefined) return {};
160
+ // The last colour line wins, as it does in the renderer's tag merge.
161
+ const color = lines.map(seriesColorOf).filter(Boolean).at(-1);
162
+ const colored = color ? { color } : {};
163
+ if (chart === undefined) return colored;
158
164
  return chart === "custom"
159
- ? { chart, chartLines: chartLinesOf(lines) }
160
- : { chart };
165
+ ? { chart, chartLines: chartLinesOf(lines), ...colored }
166
+ : { chart, ...colored };
167
+ }
168
+
169
+ /**
170
+ * Whether a tile's own tags set the series palette in a line the builder did
171
+ * not write; see {@link QueryTile.ownPalette}. Each line is parsed on its own,
172
+ * so `# theme { palette.series=[…] }` counts as well as the dotted spelling.
173
+ */
174
+ function ownPaletteField(
175
+ tags: Array<{ text: string }>,
176
+ parse: ParseTags,
177
+ ): { ownPalette?: true } {
178
+ const own = tagText(tags).some(
179
+ (line) =>
180
+ seriesColorOf(line) === undefined &&
181
+ parse([line]).tag?.tag("theme")?.tag("palette")?.tag("series") !==
182
+ undefined,
183
+ );
184
+ return own ? { ownPalette: true } : {};
161
185
  }
162
186
 
163
187
  /**
@@ -263,6 +287,20 @@ function readControlTags(tag: TagLike | null | undefined): Partial<LocalGiven> {
263
287
  };
264
288
  }
265
289
 
290
+ /** A view's own `# colspan` and `# break`, read as the builder always has. */
291
+ function viewLayout(
292
+ t:
293
+ | { numeric(key: string): number | undefined; has(key: string): boolean }
294
+ | null
295
+ | undefined,
296
+ ): { colspan?: number; break?: boolean } {
297
+ const colspan = t?.numeric("colspan");
298
+ return {
299
+ ...(colspan === undefined ? {} : { colspan }),
300
+ ...(t?.has("break") ? { break: true } : {}),
301
+ };
302
+ }
303
+
266
304
  /** A grid width: a plain decimal positive integer, else undefined. */
267
305
  function gridWidth(
268
306
  tag: { text(key: string): string | undefined } | undefined,
@@ -278,8 +316,113 @@ function gridWidth(
278
316
  return Number.isInteger(value) && value >= 1 ? value : undefined;
279
317
  }
280
318
 
281
- const QUOTED_ENTRY = /^"((?:[^"\\]|\\.)+)"$/;
319
+ /** A quoted run expression, with the `{ … }` of layout an entry may carry after it. */
320
+ const QUOTED_ENTRY = /^"((?:[^"\\]|\\.)+)"\s*(\{[\s\S]*\})?$/;
321
+
322
+ /** The layout a `tiles=[…]` entry carries, read the way the server reads it. */
323
+ function entryLayout(
324
+ tag:
325
+ | {
326
+ text(key: string): string | undefined;
327
+ has(key: string): boolean;
328
+ }
329
+ | undefined,
330
+ ): EntryLayout {
331
+ const colspan = gridWidth(tag, "colspan");
332
+ const rowspan = gridWidth(tag, "rowspan");
333
+ const row = gridWidth(tag, "row");
334
+ const col = gridWidth(tag, "col");
335
+ return {
336
+ ...(colspan === undefined ? {} : { colspan }),
337
+ ...(tag?.has("break") ? { break: tag.text("break") !== "false" } : {}),
338
+ ...(rowspan === undefined ? {} : { rowspan }),
339
+ ...(row === undefined ? {} : { row }),
340
+ ...(col === undefined ? {} : { col }),
341
+ };
342
+ }
343
+
344
+ /** What an entry in `tiles=[…]` can say about where its tile sits. */
345
+ interface EntryLayout {
346
+ colspan?: number;
347
+ break?: boolean;
348
+ rowspan?: number;
349
+ row?: number;
350
+ col?: number;
351
+ }
352
+
353
+ /** An entry's layout over a view's own: each property the entry sets wins, and a `break` that ends up off is no field. */
354
+ function placed(
355
+ view: { colspan?: number; break?: boolean },
356
+ entry: EntryLayout,
357
+ ): {
358
+ colspan?: number;
359
+ break?: true;
360
+ rowspan?: number;
361
+ row?: number;
362
+ col?: number;
363
+ } {
364
+ const colspan = entry.colspan ?? view.colspan;
365
+ return {
366
+ ...(colspan === undefined ? {} : { colspan }),
367
+ ...((entry.break ?? view.break) ? { break: true as const } : {}),
368
+ ...(entry.rowspan === undefined ? {} : { rowspan: entry.rowspan }),
369
+ ...(entry.row === undefined ? {} : { row: entry.row }),
370
+ ...(entry.col === undefined ? {} : { col: entry.col }),
371
+ };
372
+ }
282
373
  const TEXT_ENTRY = /^([A-Za-z_][A-Za-z0-9_]*)\s*\{/;
374
+ /** An entry that is one plain name, quoted or bare: a query, as the server's reader takes it. */
375
+ const NAMED_QUERY = /^[A-Za-z_][A-Za-z0-9_]*$/;
376
+
377
+ /**
378
+ * The `#` lines above `query: <name> is …` in this file, or none when the
379
+ * query is declared in the model. `name` is a plain name ({@link NAMED_QUERY}).
380
+ */
381
+ function queryTags(
382
+ parsed: ParsedMalloy,
383
+ lines: string[],
384
+ name: string,
385
+ ): Array<{ line: number; text: string }> {
386
+ const declares = new RegExp(`^\\s*query\\s*:\\s*${name}\\s+is\\b`);
387
+ for (let i = 0; i < lines.length; i++) {
388
+ if (parsed.commentLine(i) || parsed.proseLine(i)) continue;
389
+ if (declares.test(lines[i])) return blockAbove(parsed, lines, i).tags;
390
+ }
391
+ return [];
392
+ }
393
+
394
+ /**
395
+ * What the reader takes off a tile's own tags for its frame: label, subtitle,
396
+ * width, a row break, no border. For a tile the builder draws but does not
397
+ * rewrite, so it is drawn as the reader draws it.
398
+ */
399
+ function readOnlyFrame(t: Tag | undefined): {
400
+ label?: string;
401
+ subtitle?: string;
402
+ colspan?: number;
403
+ break?: true;
404
+ borderless?: true;
405
+ } {
406
+ return {
407
+ ...(t?.text("label") ? { label: t.text("label") as string } : {}),
408
+ ...(t?.text("subtitle")
409
+ ? { subtitle: t.text("subtitle") as string }
410
+ : {}),
411
+ ...(t?.numeric("colspan") !== undefined
412
+ ? { colspan: t.numeric("colspan") as number }
413
+ : {}),
414
+ ...(t?.has("break") ? { break: true as const } : {}),
415
+ ...(t?.has("borderless") ? { borderless: true as const } : {}),
416
+ };
417
+ }
418
+
419
+ /** A frame with its layout taken off, for a tile whose layout comes from {@link placed}. */
420
+ function frameWithout<T extends { colspan?: number; break?: true }>(
421
+ frame: T,
422
+ ): Omit<T, "colspan" | "break"> {
423
+ const { colspan: _colspan, break: _break, ...rest } = frame;
424
+ return rest;
425
+ }
283
426
 
284
427
  /** Refuses rather than throws: `Tag.text()` throws on a malformed date literal such as `@2024-13-01`, and dropping the value would lose it on the next save. */
285
428
  export async function readDashboardDocument(
@@ -418,12 +561,34 @@ async function readDocumentText(sourceText: string): Promise<ReadResult> {
418
561
  }
419
562
 
420
563
  const tiles: DashboardTile[] = [];
564
+ /**
565
+ * A tile that names a query: framed by the query's own tags when the file
566
+ * declares it, and laid out by its entry over the query's `# colspan` and
567
+ * `# break`, as a view's tile is.
568
+ */
569
+ const namedQueryTile = (name: string, own: EntryLayout): DashboardTile => {
570
+ const frame = readOnlyFrame(
571
+ parseAnnotation(tagText(queryTags(parsed, lines, name))).tag,
572
+ );
573
+ return {
574
+ name,
575
+ declaration: { kind: "query" },
576
+ ...frameWithout(frame),
577
+ ...placed({ colspan: frame.colspan, break: frame.break }, own),
578
+ };
579
+ };
421
580
  for (const { text: entryText } of list.entries) {
422
581
  const quoted = QUOTED_ENTRY.exec(entryText);
423
582
  const textName = quoted ? undefined : TEXT_ENTRY.exec(entryText)?.[1];
424
583
  if (textName !== undefined) {
425
584
  const textTag = parseAnnotation([`# ${entryText}`]).tag?.tag(textName);
426
- if (textTag?.text("kind") !== "text") {
585
+ // A bare named query with its layout on it, `by_carrier { row=1 col=1 }`.
586
+ const entryKind = textTag?.text("kind");
587
+ if (entryKind === undefined || entryKind === "query") {
588
+ tiles.push(namedQueryTile(textName, entryLayout(textTag)));
589
+ continue;
590
+ }
591
+ if (entryKind !== "text") {
427
592
  return {
428
593
  ok: false,
429
594
  reason:
@@ -438,26 +603,39 @@ async function readDocumentText(sourceText: string): Promise<ReadResult> {
438
603
  reason: `Two text tiles are named \`${textName}\`, so the builder cannot tell them apart.`,
439
604
  };
440
605
  }
441
- const colspan = gridWidth(textTag, "colspan");
442
606
  tiles.push({
443
607
  kind: "text",
444
608
  name: textName,
445
609
  markdown:
446
610
  parsed.textBlocks.find((block) => block.name === textName)
447
611
  ?.body ?? "",
448
- ...(colspan === undefined ? {} : { colspan }),
449
- ...(textTag.has("break") ? { break: true } : {}),
612
+ ...placed({}, entryLayout(textTag)),
450
613
  });
451
614
  continue;
452
615
  }
453
616
  const entry = quoted?.[1] ?? entryText;
617
+ const own = entryLayout(
618
+ quoted?.[2]
619
+ ? (parseAnnotation([`# tile ${quoted[2]}`]).tag?.tag("tile") ??
620
+ undefined)
621
+ : undefined,
622
+ );
623
+ // A plain name, quoted or bare, is a named query,
624
+ // `query: by_carrier is flights -> { … }`, here or in the model: the
625
+ // server's reader runs it as `run: by_carrier`. Shown and movable, never
626
+ // rewritten (see the `query` declaration), and framed by the query's own
627
+ // tags when this file declares it, as the reader frames it.
628
+ if (NAMED_QUERY.test(entry.trim())) {
629
+ tiles.push(namedQueryTile(entry.trim(), own));
630
+ continue;
631
+ }
454
632
  const steps = quoted ? tileSteps(entry) : undefined;
455
633
  if (!steps) {
456
634
  return {
457
635
  ok: false,
458
636
  reason:
459
- `The tile \`${entry}\` is not a \`source -> view\` expression, ` +
460
- `which is the only form the builder can lay out.`,
637
+ `The tile \`${entry}\` is neither a \`source -> view\` expression ` +
638
+ `nor the name of a query, which are the forms the builder can lay out.`,
461
639
  };
462
640
  }
463
641
  const { source: sourceName, view: viewName } = steps;
@@ -473,6 +651,7 @@ async function readDocumentText(sourceText: string): Promise<ReadResult> {
473
651
  name: viewName,
474
652
  source: sourceName,
475
653
  declaration: { kind: "inherited" },
654
+ ...placed({}, own),
476
655
  });
477
656
  continue;
478
657
  }
@@ -501,16 +680,10 @@ async function readDocumentText(sourceText: string): Promise<ReadResult> {
501
680
  ? view.body.why
502
681
  : "unreadable",
503
682
  },
504
- ...(t?.text("label") ? { label: t.text("label") as string } : {}),
505
- ...(t?.text("subtitle")
506
- ? { subtitle: t.text("subtitle") as string }
507
- : {}),
508
- ...(t?.numeric("colspan") !== undefined
509
- ? { colspan: t.numeric("colspan") as number }
510
- : {}),
683
+ ...frameWithout(readOnlyFrame(t)),
684
+ ...placed(viewLayout(t), own),
511
685
  ...chartField(view.tags),
512
- ...(t?.has("break") ? { break: true } : {}),
513
- ...(t?.has("borderless") ? { borderless: true } : {}),
686
+ ...ownPaletteField(view.tags, parseAnnotation as ParseTags),
514
687
  });
515
688
  continue;
516
689
  }
@@ -532,11 +705,9 @@ async function readDocumentText(sourceText: string): Promise<ReadResult> {
532
705
  ...(t?.text("subtitle")
533
706
  ? { subtitle: t.text("subtitle") as string }
534
707
  : {}),
535
- ...(t?.numeric("colspan") !== undefined
536
- ? { colspan: t.numeric("colspan") as number }
537
- : {}),
708
+ ...placed(viewLayout(t), own),
538
709
  ...chartField(view.tags),
539
- ...(t?.has("break") ? { break: true } : {}),
710
+ ...ownPaletteField(view.tags, parseAnnotation as ParseTags),
540
711
  ...(t?.has("borderless") ? { borderless: true } : {}),
541
712
  });
542
713
  }
@@ -550,14 +721,11 @@ async function readDocumentText(sourceText: string): Promise<ReadResult> {
550
721
  if (value !== undefined) startingGivens[key] = value;
551
722
  }
552
723
 
553
- // The server's rule: a written `dashboard { columns }` wins even when it is
554
- // not a width (the default width then applies), and the alias only counts
555
- // beside `tiles`.
724
+ // The server's rule: a `dashboard { columns }` that is not a width leaves
725
+ // the default width.
556
726
  const columnsTag = tag?.tag("dashboard")?.has("columns")
557
727
  ? gridWidth(tag.tag("dashboard"), "columns")
558
- : artifactTag?.array("tiles")
559
- ? gridWidth(artifactTag, "dashboard_columns")
560
- : undefined;
728
+ : undefined;
561
729
 
562
730
  return {
563
731
  ok: true,
@@ -243,12 +243,12 @@ source: a is scoped_orders extend {
243
243
  view: other is { aggregate: m is count() }
244
244
  }`;
245
245
  const out = await spliced(source, (d) => {
246
- d.tiles[1].colspan = 6;
246
+ queryTile(d, 1).label = "W";
247
247
  });
248
248
  expect(out).toContain(
249
- " # colspan=6\n view: other is { aggregate: m is count() }",
249
+ ' # label="W"\n view: other is { aggregate: m is count() }',
250
250
  );
251
- expect(out).not.toContain("colspan=6\n group_by: cat");
251
+ expect(out).not.toContain('label="W"\n group_by: cat');
252
252
  });
253
253
 
254
254
  // declarationExtent: `//` inside a quoted literal is not a comment, so a
@@ -260,10 +260,10 @@ source: a is one extend {
260
260
  view: y is vy
261
261
  }`;
262
262
  const out = await spliced(source, (d) => {
263
- d.tiles[1].colspan = 4;
263
+ queryTile(d, 1).label = "W";
264
264
  });
265
- expect(out).toContain(" # colspan=4\n view: y is vy");
266
- expect(out).not.toContain("colspan=4\n view: x");
265
+ expect(out).toContain(' # label="W"\n view: y is vy');
266
+ expect(out).not.toContain('label="W"\n view: x');
267
267
  });
268
268
 
269
269
  // declarationExtent: a brace inside a single-quoted filter literal is text,
@@ -280,10 +280,10 @@ source: a is one extend {
280
280
  view: other is { aggregate: m is count() }
281
281
  }`;
282
282
  const out = await spliced(source, (d) => {
283
- d.tiles[1].colspan = 4;
283
+ queryTile(d, 1).label = "W";
284
284
  });
285
285
  expect(out).toContain(
286
- " # colspan=4\n view: other is { aggregate: m is count() }",
286
+ ' # label="W"\n view: other is { aggregate: m is count() }',
287
287
  );
288
288
  }
289
289
  });
@@ -300,10 +300,10 @@ source: a is one extend {
300
300
  view: other is { aggregate: m is count() }
301
301
  }`;
302
302
  const out = await spliced(source, (d) => {
303
- d.tiles[1].colspan = 4;
303
+ queryTile(d, 1).label = "W";
304
304
  });
305
305
  expect(out).toContain(
306
- " # colspan=4\n view: other is { aggregate: m is count() }",
306
+ ' # label="W"\n view: other is { aggregate: m is count() }',
307
307
  );
308
308
  });
309
309
  });