@malloy-publisher/sdk 0.3.0 → 0.3.1

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 (156) hide show
  1. package/README.md +8 -0
  2. package/dist/DocumentStorageProvider-BeBD0uWc.cjs.js +134 -0
  3. package/dist/DocumentStorageProvider-tGvodI8f.es.js +24268 -0
  4. package/dist/RenderedResult-CPi6uQWq.cjs.js +115 -0
  5. package/dist/RenderedResult-mDE-4u8S.es.js +542 -0
  6. package/dist/ServerProvider-CH71GsoL.cjs.js +1 -0
  7. package/dist/{ServerProvider-DSK9rfSY.es.js → ServerProvider-X2Ma0HRs.es.js} +486 -521
  8. package/dist/builder/index.cjs.js +105 -0
  9. package/dist/builder/index.d.ts +2 -0
  10. package/dist/builder/index.es.js +9561 -0
  11. package/dist/builder-entry.d.ts +8 -0
  12. package/dist/client/index.cjs.js +1 -1
  13. package/dist/client/index.es.js +1 -1
  14. package/dist/components/Dashboard/Dashboard.d.ts +19 -14
  15. package/dist/components/Dashboard/DashboardGrid.d.ts +67 -0
  16. package/dist/components/Dashboard/DashboardTile.d.ts +6 -1
  17. package/dist/components/Dashboard/ExploreDialog.d.ts +18 -0
  18. package/dist/components/Dashboard/RowsDialog.d.ts +47 -0
  19. package/dist/components/Dashboard/TileCard.d.ts +44 -0
  20. package/dist/components/Dashboard/index.d.ts +2 -0
  21. package/dist/components/Dashboard/promoteMeasureRow.d.ts +7 -3
  22. package/dist/components/Dashboard/telemetry.d.ts +43 -0
  23. package/dist/components/DashboardBuilder/AddTileDialog.d.ts +35 -0
  24. package/dist/components/DashboardBuilder/BuilderToolbar.d.ts +29 -0
  25. package/dist/components/DashboardBuilder/DashboardBuilder.d.ts +112 -0
  26. package/dist/components/DashboardBuilder/DashboardEditor.d.ts +32 -0
  27. package/dist/components/DashboardBuilder/DiffDialog.d.ts +15 -0
  28. package/dist/components/DashboardBuilder/DrillDialog.d.ts +15 -0
  29. package/dist/components/DashboardBuilder/FilterDialog.d.ts +54 -0
  30. package/dist/components/DashboardBuilder/FilterStrip.d.ts +17 -0
  31. package/dist/components/DashboardBuilder/SettingsPopover.d.ts +20 -0
  32. package/dist/components/DashboardBuilder/TileFrame.d.ts +42 -0
  33. package/dist/components/DashboardBuilder/TileMenu.d.ts +24 -0
  34. package/dist/components/DashboardBuilder/catalog.d.ts +62 -0
  35. package/dist/components/DashboardBuilder/controls.d.ts +157 -0
  36. package/dist/components/DashboardBuilder/diff.d.ts +35 -0
  37. package/dist/components/DashboardBuilder/document.d.ts +218 -0
  38. package/dist/components/DashboardBuilder/layout.d.ts +71 -0
  39. package/dist/components/DashboardBuilder/malloyText.d.ts +45 -0
  40. package/dist/components/DashboardBuilder/preview.d.ts +60 -0
  41. package/dist/components/DashboardBuilder/readDocument.d.ts +106 -0
  42. package/dist/components/DashboardBuilder/sortable.d.ts +51 -0
  43. package/dist/components/DashboardBuilder/spliceDocument.d.ts +44 -0
  44. package/dist/components/DashboardBuilder/testing/fixtures.d.ts +10 -0
  45. package/dist/components/DashboardBuilder/useBuilderShortcuts.d.ts +22 -0
  46. package/dist/components/DashboardBuilder/useDashboardEditor.d.ts +63 -0
  47. package/dist/components/DashboardBuilder/useDraft.d.ts +13 -0
  48. package/dist/components/DashboardBuilder/useFilterForm.d.ts +65 -0
  49. package/dist/components/DashboardBuilder/useTileReorder.d.ts +22 -0
  50. package/dist/components/DashboardBuilder/useTileResize.d.ts +29 -0
  51. package/dist/components/DocumentStorage/DocumentStorageProvider.d.ts +7 -0
  52. package/dist/components/DocumentStorage/index.d.ts +1 -1
  53. package/dist/components/FloatingIconButton.d.ts +16 -0
  54. package/dist/components/Prose.d.ts +46 -0
  55. package/dist/components/RenderedResult/ResultPanel.d.ts +30 -0
  56. package/dist/components/RenderedResult/index.d.ts +1 -0
  57. package/dist/components/drill/index.d.ts +1 -1
  58. package/dist/components/drill/resolveDrill.d.ts +22 -0
  59. package/dist/components/drill/useDrill.d.ts +11 -2
  60. package/dist/components/index.d.ts +1 -0
  61. package/dist/components/styles.d.ts +0 -4
  62. package/dist/hooks/index.d.ts +2 -0
  63. package/dist/hooks/useDocumentControls.d.ts +70 -0
  64. package/dist/hooks/useQueryResult.d.ts +40 -0
  65. package/dist/index.cjs.js +23 -270
  66. package/dist/index.es.js +16977 -41293
  67. package/dist/utils/malloyLiteral.d.ts +11 -0
  68. package/package.json +24 -9
  69. package/src/builder-entry.ts +55 -0
  70. package/src/components/Dashboard/Dashboard.spec.tsx +7 -10
  71. package/src/components/Dashboard/Dashboard.tsx +165 -175
  72. package/src/components/Dashboard/DashboardGrid.tsx +124 -0
  73. package/src/components/Dashboard/DashboardTile.spec.tsx +30 -6
  74. package/src/components/Dashboard/DashboardTile.tsx +66 -123
  75. package/src/components/Dashboard/ExploreDialog.tsx +84 -0
  76. package/src/components/Dashboard/RowsDialog.spec.ts +42 -0
  77. package/src/components/Dashboard/RowsDialog.tsx +234 -0
  78. package/src/components/Dashboard/TileCard.tsx +120 -0
  79. package/src/components/Dashboard/index.ts +2 -0
  80. package/src/components/Dashboard/promoteMeasureRow.spec.ts +70 -0
  81. package/src/components/Dashboard/promoteMeasureRow.ts +33 -2
  82. package/src/components/Dashboard/telemetry.ts +44 -0
  83. package/src/components/Dashboard/tileGridColumn.spec.ts +1 -1
  84. package/src/components/DashboardBuilder/AddTileDialog.tsx +249 -0
  85. package/src/components/DashboardBuilder/BuilderToolbar.tsx +270 -0
  86. package/src/components/DashboardBuilder/DashboardBuilder.spec.tsx +858 -0
  87. package/src/components/DashboardBuilder/DashboardBuilder.tsx +653 -0
  88. package/src/components/DashboardBuilder/DashboardEditor.spec.tsx +211 -0
  89. package/src/components/DashboardBuilder/DashboardEditor.tsx +493 -0
  90. package/src/components/DashboardBuilder/DiffDialog.tsx +129 -0
  91. package/src/components/DashboardBuilder/DrillDialog.tsx +281 -0
  92. package/src/components/DashboardBuilder/FilterDialog.tsx +581 -0
  93. package/src/components/DashboardBuilder/FilterStrip.tsx +125 -0
  94. package/src/components/DashboardBuilder/SettingsPopover.tsx +168 -0
  95. package/src/components/DashboardBuilder/TileFrame.tsx +380 -0
  96. package/src/components/DashboardBuilder/TileMenu.tsx +188 -0
  97. package/src/components/DashboardBuilder/catalog.spec.ts +215 -0
  98. package/src/components/DashboardBuilder/catalog.ts +225 -0
  99. package/src/components/DashboardBuilder/controls.spec.ts +243 -0
  100. package/src/components/DashboardBuilder/controls.ts +398 -0
  101. package/src/components/DashboardBuilder/diff.spec.ts +44 -0
  102. package/src/components/DashboardBuilder/diff.ts +93 -0
  103. package/src/components/DashboardBuilder/document.ts +209 -0
  104. package/src/components/DashboardBuilder/keepRowStructure.spec.ts +84 -0
  105. package/src/components/DashboardBuilder/layout.ts +143 -0
  106. package/src/components/DashboardBuilder/malloyText.spec.ts +84 -0
  107. package/src/components/DashboardBuilder/malloyText.ts +151 -0
  108. package/src/components/DashboardBuilder/moveIntoGap.spec.ts +90 -0
  109. package/src/components/DashboardBuilder/preview.spec.ts +149 -0
  110. package/src/components/DashboardBuilder/preview.ts +172 -0
  111. package/src/components/DashboardBuilder/readDocument.spec.ts +375 -0
  112. package/src/components/DashboardBuilder/readDocument.ts +467 -0
  113. package/src/components/DashboardBuilder/sortable.tsx +151 -0
  114. package/src/components/DashboardBuilder/spliceDocument.spec.ts +1108 -0
  115. package/src/components/DashboardBuilder/spliceDocument.ts +1098 -0
  116. package/src/components/DashboardBuilder/testing/fixtures.ts +48 -0
  117. package/src/components/DashboardBuilder/useBuilderShortcuts.ts +88 -0
  118. package/src/components/DashboardBuilder/useDashboardEditor.spec.ts +255 -0
  119. package/src/components/DashboardBuilder/useDashboardEditor.ts +193 -0
  120. package/src/components/DashboardBuilder/useDraft.ts +43 -0
  121. package/src/components/DashboardBuilder/useFilterForm.spec.tsx +144 -0
  122. package/src/components/DashboardBuilder/useFilterForm.ts +352 -0
  123. package/src/components/DashboardBuilder/useTileReorder.spec.tsx +97 -0
  124. package/src/components/DashboardBuilder/useTileReorder.ts +115 -0
  125. package/src/components/DashboardBuilder/useTileResize.spec.tsx +121 -0
  126. package/src/components/DashboardBuilder/useTileResize.ts +110 -0
  127. package/src/components/DashboardBuilder/withGaps.spec.ts +96 -0
  128. package/src/components/DocumentStorage/DocumentStorageProvider.tsx +12 -0
  129. package/src/components/DocumentStorage/index.ts +1 -0
  130. package/src/components/Environment/About.tsx +4 -36
  131. package/src/components/FloatingIconButton.tsx +41 -0
  132. package/src/components/Model/Model.tsx +6 -23
  133. package/src/components/Model/ModelCell.tsx +33 -72
  134. package/src/components/Notebook/Notebook.tsx +25 -88
  135. package/src/components/Notebook/NotebookCell.tsx +35 -183
  136. package/src/components/Prose.spec.tsx +85 -0
  137. package/src/components/Prose.tsx +179 -0
  138. package/src/components/QueryResult/QueryResult.tsx +15 -43
  139. package/src/components/RenderedResult/ResultContainer.tsx +4 -12
  140. package/src/components/RenderedResult/ResultPanel.spec.tsx +49 -0
  141. package/src/components/RenderedResult/ResultPanel.tsx +73 -0
  142. package/src/components/RenderedResult/index.ts +1 -0
  143. package/src/components/drill/index.ts +1 -0
  144. package/src/components/drill/resolveDrill.ts +22 -1
  145. package/src/components/drill/useDrill.spec.tsx +94 -0
  146. package/src/components/drill/useDrill.tsx +52 -12
  147. package/src/components/given/GivensPanel.tsx +1 -1
  148. package/src/components/index.ts +6 -0
  149. package/src/components/styles.ts +0 -37
  150. package/src/hooks/index.ts +13 -0
  151. package/src/hooks/useDocumentControls.ts +170 -0
  152. package/src/hooks/useQueryResult.ts +82 -0
  153. package/src/utils/malloyLiteral.spec.ts +43 -0
  154. package/src/utils/malloyLiteral.ts +76 -0
  155. package/vite.config.ts +5 -0
  156. package/dist/ServerProvider-CGnLjzag.cjs.js +0 -1
@@ -0,0 +1,188 @@
1
+ // Copyright (c) Credible Data Inc.
2
+ // SPDX-License-Identifier: MIT
3
+
4
+ import {
5
+ Button,
6
+ Divider,
7
+ Popover,
8
+ Stack,
9
+ TextField,
10
+ Typography,
11
+ } from "@mui/material";
12
+ import { useDraft } from "./useDraft";
13
+ import { usePublisherTheme } from "../../theme/ThemeContext";
14
+ import type { DashboardTile } from "./document";
15
+
16
+ /**
17
+ * A tile's own settings, on the tile: a popover off its menu button, so
18
+ * editing it never means scrolling away from it. Its title, subtitle, width
19
+ * presets, clickable cells and removal. Its row is set by dragging it — a drop
20
+ * into the empty end of a row is what "start a new row" means — and its card
21
+ * is the reader's to decide, so neither is a toggle here. Which controls it
22
+ * answers to is not here either: filters are configured in one place, the
23
+ * strip under the header. Edits commit on close (`useDraft`).
24
+ */
25
+ export interface TileMenuProps {
26
+ anchor: HTMLElement | null;
27
+ tile: DashboardTile | undefined;
28
+ onClose: () => void;
29
+ /** Apply the edited tile. Called once, on close, only when something changed. */
30
+ onCommit: (next: DashboardTile) => void;
31
+ /** Take the tile off the dashboard. Offered on every tile: order is this file's. */
32
+ onRemove: () => void;
33
+ /** The grid's width, which the width presets are fractions of. */
34
+ columns: number;
35
+ /** Open the clickable-cells window for this tile's source. */
36
+ onDrills: () => void;
37
+ }
38
+
39
+ export function TileMenu({
40
+ anchor,
41
+ tile,
42
+ onClose,
43
+ onCommit,
44
+ onRemove,
45
+ columns,
46
+ onDrills,
47
+ }: TileMenuProps) {
48
+ const { theme } = usePublisherTheme();
49
+ const { draft, patch, close, discard } = useDraft(
50
+ tile,
51
+ anchor !== null,
52
+ onCommit,
53
+ onClose,
54
+ );
55
+
56
+ const editable =
57
+ draft !== undefined && draft.declaration.kind !== "inherited";
58
+
59
+ return (
60
+ <Popover
61
+ open={anchor !== null && draft !== undefined}
62
+ anchorEl={anchor}
63
+ onClose={close}
64
+ anchorOrigin={{ vertical: "bottom", horizontal: "right" }}
65
+ transformOrigin={{ vertical: "top", horizontal: "right" }}
66
+ slotProps={{ paper: { sx: { width: 320, p: 2 } } }}
67
+ >
68
+ {draft && (
69
+ <Stack sx={{ gap: 1.5 }}>
70
+ <Typography
71
+ variant="overline"
72
+ sx={{ color: theme.tileTitle, lineHeight: 1.5 }}
73
+ >
74
+ {draft.source} → {draft.name}
75
+ </Typography>
76
+
77
+ {editable ? (
78
+ <>
79
+ <TextField
80
+ size="small"
81
+ label="Title"
82
+ value={draft.label ?? ""}
83
+ autoFocus
84
+ inputProps={{ "aria-label": "Tile title" }}
85
+ onChange={(event) =>
86
+ patch((t) => {
87
+ const v = event.target.value;
88
+ if (v === "") delete t.label;
89
+ else t.label = v;
90
+ })
91
+ }
92
+ />
93
+ <TextField
94
+ size="small"
95
+ label="Subtitle"
96
+ value={draft.subtitle ?? ""}
97
+ inputProps={{ "aria-label": "Tile subtitle" }}
98
+ onChange={(event) =>
99
+ patch((t) => {
100
+ const v = event.target.value;
101
+ if (v === "") delete t.subtitle;
102
+ else t.subtitle = v;
103
+ })
104
+ }
105
+ />
106
+ {/* Width presets, as fractions of this grid. A
107
+ tile's width is otherwise a drag, and a drag cannot
108
+ say "a third". */}
109
+ <Stack
110
+ direction="row"
111
+ sx={{ gap: 0.5, alignItems: "center" }}
112
+ >
113
+ <Typography
114
+ variant="caption"
115
+ sx={{ color: theme.tileTitle, mr: 0.5 }}
116
+ >
117
+ Width
118
+ </Typography>
119
+ {(
120
+ [
121
+ ["Full", 1],
122
+ ["½", 2],
123
+ ["⅓", 3],
124
+ ["¼", 4],
125
+ ] as const
126
+ ).map(([label, share]) => {
127
+ const span = Math.max(
128
+ 1,
129
+ Math.round(columns / share),
130
+ );
131
+ const active = (draft.colspan ?? 1) === span;
132
+ return (
133
+ <Button
134
+ key={label}
135
+ size="small"
136
+ variant={active ? "contained" : "outlined"}
137
+ aria-label={`Width ${label}`}
138
+ aria-pressed={active}
139
+ onClick={() =>
140
+ patch((t) => {
141
+ t.colspan = span;
142
+ })
143
+ }
144
+ sx={{ minWidth: 40, px: 1 }}
145
+ >
146
+ {label}
147
+ </Button>
148
+ );
149
+ })}
150
+ </Stack>
151
+ </>
152
+ ) : (
153
+ <Typography variant="body2" sx={{ color: theme.tileTitle }}>
154
+ Declared on its source, so its title and layout are set in
155
+ the model. It can still be moved.
156
+ </Typography>
157
+ )}
158
+ <Divider />
159
+ <Stack direction="row" sx={{ justifyContent: "space-between" }}>
160
+ {editable ? (
161
+ <Button
162
+ size="small"
163
+ onClick={() => {
164
+ close();
165
+ onDrills();
166
+ }}
167
+ >
168
+ Clickable cells…
169
+ </Button>
170
+ ) : (
171
+ <span />
172
+ )}
173
+ <Button
174
+ color="error"
175
+ size="small"
176
+ onClick={() => {
177
+ discard();
178
+ onRemove();
179
+ }}
180
+ >
181
+ Remove tile
182
+ </Button>
183
+ </Stack>
184
+ </Stack>
185
+ )}
186
+ </Popover>
187
+ );
188
+ }
@@ -0,0 +1,215 @@
1
+ // Copyright (c) Credible Data Inc.
2
+ // SPDX-License-Identifier: MIT
3
+
4
+ import { describe, expect, it } from "bun:test";
5
+ import type { CompiledModel } from "../../client";
6
+ import {
7
+ buildCatalog,
8
+ chartOf,
9
+ docOf,
10
+ filterableFields,
11
+ isDashboardModel,
12
+ } from "./catalog";
13
+
14
+ /**
15
+ * Shaped like the real response, including the two details that are easy to get
16
+ * wrong from the type alone: annotations arrive RAW with their trailing newline,
17
+ * and `sourceInfos` is an array of JSON STRINGS rather than objects.
18
+ */
19
+ const MODEL: CompiledModel = {
20
+ modelPath: "data_app.malloy",
21
+ sources: [
22
+ {
23
+ name: "scoped_orders",
24
+ annotations: ["#(doc) Order lines narrowed by the control row\n"],
25
+ views: [
26
+ {
27
+ name: "by_category",
28
+ annotations: [
29
+ "#(doc) Revenue by product category\n",
30
+ "# bar_chart\n",
31
+ ],
32
+ },
33
+ { name: "top_products", annotations: ["#(doc) Top products\n"] },
34
+ ],
35
+ givens: [{ name: "CATEGORY" }, { name: "BRAND" }],
36
+ },
37
+ ],
38
+ sourceInfos: [
39
+ JSON.stringify({
40
+ name: "scoped_orders",
41
+ schema: {
42
+ fields: [
43
+ {
44
+ name: "category",
45
+ kind: "dimension",
46
+ type: { kind: "string_type" },
47
+ },
48
+ {
49
+ name: "total_sales",
50
+ kind: "measure",
51
+ type: { kind: "number_type" },
52
+ },
53
+ { name: "ignored", kind: "something_else" },
54
+ ],
55
+ },
56
+ }),
57
+ ],
58
+ } as CompiledModel;
59
+
60
+ describe("reading raw annotations", () => {
61
+ it("takes the doc text without its marker or newline", () => {
62
+ expect(docOf(["#(doc) Revenue by product category\n"])).toBe(
63
+ "Revenue by product category",
64
+ );
65
+ expect(docOf(["# bar_chart\n"])).toBeUndefined();
66
+ expect(docOf(undefined)).toBeUndefined();
67
+ });
68
+
69
+ // Only the renderer's own chart tags, so a `# colspan` or a `# label` is not
70
+ // mistaken for a visualization.
71
+ it("takes a chart tag and ignores every other tag", () => {
72
+ expect(chartOf(["# bar_chart\n"])).toBe("bar_chart");
73
+ expect(chartOf(["# shape_map\n"])).toBe("shape_map");
74
+ expect(chartOf(["# colspan=6\n", '# label="x"\n'])).toBeUndefined();
75
+ });
76
+ });
77
+
78
+ describe("buildCatalog", () => {
79
+ it("shapes a source with its views, givens and fields", () => {
80
+ const catalog = buildCatalog([MODEL]);
81
+ expect(catalog.sources).toHaveLength(1);
82
+ const source = catalog.sources[0];
83
+ expect(source).toMatchObject({
84
+ name: "scoped_orders",
85
+ modelPath: "data_app.malloy",
86
+ description: "Order lines narrowed by the control row",
87
+ givens: ["CATEGORY", "BRAND"],
88
+ });
89
+ expect(source.views).toEqual([
90
+ {
91
+ name: "by_category",
92
+ description: "Revenue by product category",
93
+ chart: "bar_chart",
94
+ },
95
+ { name: "top_products", description: "Top products" },
96
+ ]);
97
+ });
98
+
99
+ // `sourceInfos` is JSON strings, and a field whose kind is neither a
100
+ // dimension nor a measure is not something a drill can be declared on.
101
+ it("reads fields out of the JSON-string sourceInfos", () => {
102
+ const [source] = buildCatalog([MODEL]).sources;
103
+ expect(source.fields).toEqual([
104
+ { name: "category", kind: "dimension", type: "string_type" },
105
+ { name: "total_sales", kind: "measure", type: "number_type" },
106
+ ]);
107
+ });
108
+
109
+ it("survives a malformed sourceInfos entry rather than failing", () => {
110
+ const catalog = buildCatalog([
111
+ { ...MODEL, sourceInfos: ["{not json"] } as CompiledModel,
112
+ ]);
113
+ expect(catalog.sources[0].fields).toEqual([]);
114
+ expect(catalog.sources[0].views).toHaveLength(2);
115
+ });
116
+
117
+ // Offering a dashboard's own tiles as things to put on a dashboard would be
118
+ // circular, and the endpoint lists dashboards because they are models too.
119
+ it("leaves dashboards out", () => {
120
+ expect(isDashboardModel("dashboards/overview.malloy")).toBe(true);
121
+ expect(isDashboardModel("data_app.malloy")).toBe(false);
122
+ const catalog = buildCatalog([
123
+ { ...MODEL, modelPath: "dashboards/overview.malloy" } as CompiledModel,
124
+ ]);
125
+ expect(catalog.sources).toEqual([]);
126
+ });
127
+
128
+ // An imported source appears in every model that imports it. The first one
129
+ // to declare it wins, so a preview runs against the file that defines it.
130
+ it("keeps one entry for a source that several models carry", () => {
131
+ const catalog = buildCatalog([
132
+ MODEL,
133
+ { ...MODEL, modelPath: "storefront.malloy" } as CompiledModel,
134
+ ]);
135
+ expect(catalog.sources).toHaveLength(1);
136
+ expect(catalog.sources[0].modelPath).toBe("data_app.malloy");
137
+ });
138
+ });
139
+
140
+ describe("filterableFields", () => {
141
+ // Captured from the storefront package's `order_items`: a join's fields are
142
+ // what people filter on, and a view is not a field at all.
143
+ const model: CompiledModel = {
144
+ modelPath: "storefront.malloy",
145
+ sources: [{ name: "order_items" }],
146
+ sourceInfos: [
147
+ JSON.stringify({
148
+ name: "order_items",
149
+ schema: {
150
+ fields: [
151
+ {
152
+ name: "status",
153
+ kind: "dimension",
154
+ type: { kind: "string_type" },
155
+ },
156
+ {
157
+ name: "total_sales",
158
+ kind: "measure",
159
+ type: { kind: "number_type" },
160
+ },
161
+ {
162
+ name: "products",
163
+ kind: "join",
164
+ schema: {
165
+ fields: [
166
+ {
167
+ name: "category",
168
+ kind: "dimension",
169
+ type: { kind: "string_type" },
170
+ },
171
+ {
172
+ name: "supplier",
173
+ kind: "join",
174
+ schema: {
175
+ fields: [
176
+ { name: "region", kind: "dimension" },
177
+ ],
178
+ },
179
+ },
180
+ ],
181
+ },
182
+ },
183
+ {
184
+ name: "by_status",
185
+ kind: "view",
186
+ schema: {
187
+ fields: [{ name: "status", kind: "dimension" }],
188
+ },
189
+ },
190
+ ],
191
+ },
192
+ }),
193
+ ],
194
+ } as CompiledModel;
195
+
196
+ it("offers dimensions, with a join's fields as paths, and no measures or views", () => {
197
+ const fields = filterableFields(buildCatalog([model]), "order_items");
198
+ expect(fields?.map((f) => f.name)).toEqual([
199
+ "status",
200
+ "products.category",
201
+ ]);
202
+ expect(fields?.[1]).toEqual({
203
+ name: "products.category",
204
+ kind: "dimension",
205
+ type: "string_type",
206
+ });
207
+ });
208
+
209
+ it("has no list for a source the catalog does not know, or no catalog", () => {
210
+ expect(
211
+ filterableFields(buildCatalog([model]), "elsewhere"),
212
+ ).toBeUndefined();
213
+ expect(filterableFields(undefined, "order_items")).toBeUndefined();
214
+ });
215
+ });
@@ -0,0 +1,225 @@
1
+ // Copyright (c) Credible Data Inc.
2
+ // SPDX-License-Identifier: MIT
3
+
4
+ import type { CompiledModel } from "../../client";
5
+
6
+ /**
7
+ * What a package offers a dashboard: the sources, the views on them, and the
8
+ * fields a drill can be declared on.
9
+ *
10
+ * This is what makes a tile expression correct BY CONSTRUCTION. The builder only
11
+ * ever offers `source -> view` pairs that came from here, so it cannot emit a
12
+ * tile that does not resolve — which is the reason validation needs nothing more
13
+ * than the existing compile endpoint.
14
+ *
15
+ * Shaped from the models endpoint as it is, rather than from a new one. The cost
16
+ * is that annotations arrive RAW — `'# bar_chart\n'`, `'#(doc) Revenue by
17
+ * category\n'` — so the small amount of reading below happens here instead of on
18
+ * the server.
19
+ */
20
+
21
+ export interface CatalogField {
22
+ name: string;
23
+ kind: "dimension" | "measure";
24
+ type?: string;
25
+ }
26
+
27
+ export interface CatalogView {
28
+ name: string;
29
+ /** From a `#(doc)` annotation, which is what a picker should show. */
30
+ description?: string;
31
+ /** `bar_chart`, `line_chart`, `shape_map`, … if the view declares one. */
32
+ chart?: string;
33
+ }
34
+
35
+ export interface CatalogSource {
36
+ name: string;
37
+ /** The model that declares it, which is what a preview runs against. */
38
+ modelPath: string;
39
+ description?: string;
40
+ views: CatalogView[];
41
+ /**
42
+ * The givens this source is scoped by, which is also the control row a tile
43
+ * reading it will show — measured equal to the manifest's per-tile
44
+ * `givenNames` for the `source -> view` form.
45
+ */
46
+ givens: string[];
47
+ /** For declaring a `# drill` dimension. */
48
+ fields: CatalogField[];
49
+ }
50
+
51
+ export interface PackageCatalog {
52
+ sources: CatalogSource[];
53
+ }
54
+
55
+ /** The renderer's chart tags, as they are spelled in a model. */
56
+ const CHART_TAGS = [
57
+ "bar_chart",
58
+ "line_chart",
59
+ "scatter_chart",
60
+ "shape_map",
61
+ "segment_map",
62
+ "big_value",
63
+ "sparkline",
64
+ ];
65
+
66
+ /** `#(doc) Revenue by product category\n` -> `Revenue by product category`. */
67
+ export function docOf(annotations: string[] | undefined): string | undefined {
68
+ for (const raw of annotations ?? []) {
69
+ const m = /^#\(doc\)\s*(.*)$/s.exec(raw.trim());
70
+ if (m) return m[1].trim();
71
+ }
72
+ return undefined;
73
+ }
74
+
75
+ /** `# bar_chart\n` -> `bar_chart`. Only the renderer's own chart tags count. */
76
+ export function chartOf(annotations: string[] | undefined): string | undefined {
77
+ for (const raw of annotations ?? []) {
78
+ const name = /^#\s*([a-z_]+)/.exec(raw.trim())?.[1];
79
+ if (name && CHART_TAGS.includes(name)) return name;
80
+ }
81
+ return undefined;
82
+ }
83
+
84
+ /**
85
+ * How far into a source's joins the field list reaches. One level:
86
+ * `products.category` is a field people filter on; `products.supplier.region`
87
+ * is where a list stops being a list.
88
+ */
89
+ const JOIN_DEPTH = 1;
90
+
91
+ /**
92
+ * The fields of one schema, with a JOIN's fields under it as `join.field`
93
+ * paths — the spelling a `where:` uses for them, and the fields a filter most
94
+ * often wants. A view is not a field and is left out.
95
+ */
96
+ function schemaFields(
97
+ fields: Array<Record<string, unknown>> | undefined,
98
+ prefix: string,
99
+ depth: number,
100
+ ): CatalogField[] {
101
+ const out: CatalogField[] = [];
102
+ for (const field of fields ?? []) {
103
+ const name = field["name"];
104
+ const kind = field["kind"];
105
+ if (typeof name !== "string") continue;
106
+ if (kind === "dimension" || kind === "measure") {
107
+ const type = (field["type"] as { kind?: string } | undefined)?.kind;
108
+ out.push({ name: prefix + name, kind, ...(type ? { type } : {}) });
109
+ } else if (kind === "join" && depth > 0) {
110
+ const nested = (field["schema"] as { fields?: unknown } | undefined)
111
+ ?.fields as Array<Record<string, unknown>> | undefined;
112
+ out.push(...schemaFields(nested, `${prefix}${name}.`, depth - 1));
113
+ }
114
+ }
115
+ return out;
116
+ }
117
+
118
+ /**
119
+ * Per-source fields, from `sourceInfos`, which the endpoint returns as an array
120
+ * of JSON STRINGS rather than objects. A malformed entry is skipped rather than
121
+ * failing the catalog: a picker missing one source's fields is a smaller problem
122
+ * than a builder that will not open.
123
+ */
124
+ function fieldsOf(model: CompiledModel): Map<string, CatalogField[]> {
125
+ const byName = new Map<string, CatalogField[]>();
126
+ for (const entry of model.sourceInfos ?? []) {
127
+ let parsed: unknown;
128
+ try {
129
+ parsed = typeof entry === "string" ? JSON.parse(entry) : entry;
130
+ } catch {
131
+ continue;
132
+ }
133
+ const info = parsed as {
134
+ name?: string;
135
+ schema?: { fields?: Array<Record<string, unknown>> };
136
+ };
137
+ if (!info?.name) continue;
138
+ byName.set(info.name, schemaFields(info.schema?.fields, "", JOIN_DEPTH));
139
+ }
140
+ return byName;
141
+ }
142
+
143
+ /**
144
+ * The fields a filter on `source` may name: its dimensions, joins included as
145
+ * paths. Measures are not filterable with `where:` and are left out. Undefined
146
+ * when the catalog has no such source, which a picker reads as "no list".
147
+ */
148
+ export function filterableFields(
149
+ catalog: PackageCatalog | undefined,
150
+ source: string | undefined,
151
+ ): CatalogField[] | undefined {
152
+ if (!catalog || source === undefined) return undefined;
153
+ const found = catalog.sources.find((s) => s.name === source);
154
+ return found?.fields.filter((field) => field.kind === "dimension");
155
+ }
156
+
157
+ /**
158
+ * A dashboard file is itself a model, so the endpoint lists it alongside the
159
+ * real ones. Offering a dashboard's own tile views as things to put on a
160
+ * dashboard would be circular, so they are left out.
161
+ */
162
+ export const isDashboardModel = (path: string | undefined) =>
163
+ (path ?? "").startsWith("dashboards/");
164
+
165
+ /**
166
+ * The model's own path.
167
+ *
168
+ * Two spellings, and the generated client only knows one: the models LIST
169
+ * returns `path`, while a single model returns `modelPath`. Reading `path`
170
+ * alone yields an empty string against the real server, which silently disables
171
+ * the dashboard exclusion below and leaves a preview with nothing to run
172
+ * against. Measured, not deduced from the type.
173
+ */
174
+ const pathOf = (model: CompiledModel): string =>
175
+ (model as { modelPath?: string }).modelPath ?? model.path ?? "";
176
+
177
+ export function buildCatalog(models: CompiledModel[]): PackageCatalog {
178
+ const sources: CatalogSource[] = [];
179
+ const seen = new Set<string>();
180
+
181
+ for (const model of models) {
182
+ const modelPath = pathOf(model);
183
+ if (isDashboardModel(modelPath)) continue;
184
+ const fields = fieldsOf(model);
185
+
186
+ for (const source of model.sources ?? []) {
187
+ const name = source.name;
188
+ if (!name) continue;
189
+ // A source reached through an import appears in every model that
190
+ // imports it. The first model to declare it wins, so a preview runs
191
+ // against the file that actually defines it.
192
+ if (seen.has(name)) continue;
193
+ seen.add(name);
194
+
195
+ const givens = (
196
+ (source as { givens?: Array<{ name?: string }> }).givens ?? []
197
+ )
198
+ .map((g) => g.name)
199
+ .filter((n): n is string => typeof n === "string");
200
+
201
+ sources.push({
202
+ name,
203
+ modelPath,
204
+ ...(docOf(source.annotations)
205
+ ? { description: docOf(source.annotations) as string }
206
+ : {}),
207
+ views: (source.views ?? [])
208
+ .filter((view) => typeof view.name === "string")
209
+ .map((view) => ({
210
+ name: view.name as string,
211
+ ...(docOf(view.annotations)
212
+ ? { description: docOf(view.annotations) as string }
213
+ : {}),
214
+ ...(chartOf(view.annotations)
215
+ ? { chart: chartOf(view.annotations) as string }
216
+ : {}),
217
+ })),
218
+ givens,
219
+ fields: fields.get(name) ?? [],
220
+ });
221
+ }
222
+ }
223
+
224
+ return { sources };
225
+ }