@malloy-publisher/sdk 0.3.0 → 0.4.0

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 (244) hide show
  1. package/README.md +22 -9
  2. package/dist/DocumentStorageProvider-CyOJ0hqf.es.js +24443 -0
  3. package/dist/DocumentStorageProvider-DGPQEd_l.cjs.js +134 -0
  4. package/dist/RenderedResult-BnPzJ9Jf.es.js +549 -0
  5. package/dist/RenderedResult-Dp22kZsQ.cjs.js +115 -0
  6. package/dist/{ServerProvider-DSK9rfSY.es.js → ServerProvider-BWOEKg0O.es.js} +1256 -1318
  7. package/dist/ServerProvider-Cc489A3f.cjs.js +1 -0
  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 +9482 -0
  11. package/dist/builder-entry.d.ts +8 -0
  12. package/dist/client/api.d.ts +100 -42
  13. package/dist/client/index.cjs.js +1 -1
  14. package/dist/client/index.es.js +1 -1
  15. package/dist/components/AppDialog.d.ts +30 -0
  16. package/dist/components/BackLink.d.ts +32 -0
  17. package/dist/components/Dashboard/Dashboard.d.ts +19 -14
  18. package/dist/components/Dashboard/DashboardBar.d.ts +21 -0
  19. package/dist/components/Dashboard/DashboardGrid.d.ts +67 -0
  20. package/dist/components/Dashboard/DashboardTile.d.ts +6 -1
  21. package/dist/components/Dashboard/ExploreDialog.d.ts +18 -0
  22. package/dist/components/Dashboard/RowsDialog.d.ts +47 -0
  23. package/dist/components/Dashboard/TileCard.d.ts +44 -0
  24. package/dist/components/Dashboard/index.d.ts +2 -0
  25. package/dist/components/Dashboard/promoteMeasureRow.d.ts +7 -3
  26. package/dist/components/Dashboard/telemetry.d.ts +48 -0
  27. package/dist/components/DashboardBuilder/AddTileDialog.d.ts +35 -0
  28. package/dist/components/DashboardBuilder/BuilderToolbar.d.ts +31 -0
  29. package/dist/components/DashboardBuilder/DashboardBuilder.d.ts +118 -0
  30. package/dist/components/DashboardBuilder/DashboardEditor.d.ts +30 -0
  31. package/dist/components/DashboardBuilder/DiffDialog.d.ts +15 -0
  32. package/dist/components/DashboardBuilder/DrillDialog.d.ts +15 -0
  33. package/dist/components/DashboardBuilder/FilterDialog.d.ts +54 -0
  34. package/dist/components/DashboardBuilder/FilterStrip.d.ts +17 -0
  35. package/dist/components/DashboardBuilder/SettingsPopover.d.ts +20 -0
  36. package/dist/components/DashboardBuilder/TileFrame.d.ts +42 -0
  37. package/dist/components/DashboardBuilder/TileMenu.d.ts +24 -0
  38. package/dist/components/DashboardBuilder/catalog.d.ts +62 -0
  39. package/dist/components/DashboardBuilder/controls.d.ts +157 -0
  40. package/dist/components/DashboardBuilder/diff.d.ts +35 -0
  41. package/dist/components/DashboardBuilder/document.d.ts +218 -0
  42. package/dist/components/DashboardBuilder/layout.d.ts +71 -0
  43. package/dist/components/DashboardBuilder/malloyText.d.ts +45 -0
  44. package/dist/components/DashboardBuilder/newDashboard.d.ts +17 -0
  45. package/dist/components/DashboardBuilder/preview.d.ts +60 -0
  46. package/dist/components/DashboardBuilder/readDocument.d.ts +106 -0
  47. package/dist/components/DashboardBuilder/sortable.d.ts +51 -0
  48. package/dist/components/DashboardBuilder/spliceDocument.d.ts +53 -0
  49. package/dist/components/DashboardBuilder/testing/fixtures.d.ts +10 -0
  50. package/dist/components/DashboardBuilder/useBuilderShortcuts.d.ts +22 -0
  51. package/dist/components/DashboardBuilder/useDashboardEditor.d.ts +63 -0
  52. package/dist/components/DashboardBuilder/useDraft.d.ts +13 -0
  53. package/dist/components/DashboardBuilder/useFilterForm.d.ts +65 -0
  54. package/dist/components/DashboardBuilder/useTileReorder.d.ts +22 -0
  55. package/dist/components/DashboardBuilder/useTileResize.d.ts +29 -0
  56. package/dist/components/DocumentStorage/DocumentStorageProvider.d.ts +7 -0
  57. package/dist/components/DocumentStorage/index.d.ts +1 -1
  58. package/dist/components/FloatingIconButton.d.ts +16 -0
  59. package/dist/components/ItemRow.d.ts +38 -0
  60. package/dist/components/Materializations/MaterializationDetailDialog.d.ts +1 -2
  61. package/dist/components/Materializations/MaterializationRunsList.d.ts +1 -5
  62. package/dist/components/Materializations/Materializations.d.ts +7 -3
  63. package/dist/components/Materializations/ScopeButton.d.ts +18 -0
  64. package/dist/components/Materializations/SectionLabel.d.ts +7 -4
  65. package/dist/components/Materializations/TriggerLabel.d.ts +14 -0
  66. package/dist/components/Materializations/index.d.ts +0 -1
  67. package/dist/components/Package/ContentTypeIcon.d.ts +3 -5
  68. package/dist/components/Package/NewDashboardDialog.d.ts +18 -0
  69. package/dist/components/Package/index.d.ts +0 -1
  70. package/dist/components/PackageSection.d.ts +23 -0
  71. package/dist/components/Prose.d.ts +46 -0
  72. package/dist/components/RenderedResult/ResultPanel.d.ts +30 -0
  73. package/dist/components/RenderedResult/index.d.ts +1 -0
  74. package/dist/components/buttons.d.ts +53 -0
  75. package/dist/components/drill/index.d.ts +1 -1
  76. package/dist/components/drill/resolveDrill.d.ts +22 -0
  77. package/dist/components/drill/useDrill.d.ts +11 -2
  78. package/dist/components/index.d.ts +6 -0
  79. package/dist/components/styles.d.ts +49 -44
  80. package/dist/hooks/index.d.ts +2 -0
  81. package/dist/hooks/useCrudMutation.d.ts +42 -0
  82. package/dist/hooks/useDocumentControls.d.ts +70 -0
  83. package/dist/hooks/useQueryResult.d.ts +40 -0
  84. package/dist/index.cjs.js +22 -273
  85. package/dist/index.d.ts +1 -0
  86. package/dist/index.es.js +16888 -44451
  87. package/dist/telemetry/consoleEvents.d.ts +60 -0
  88. package/dist/utils/malloyLiteral.d.ts +11 -0
  89. package/dist/utils/sha256.d.ts +2 -0
  90. package/package.json +24 -9
  91. package/src/builder-entry.ts +55 -0
  92. package/src/components/AppDialog.tsx +115 -0
  93. package/src/components/BackLink.tsx +83 -0
  94. package/src/components/Connections/AddConnectionDialog.tsx +50 -70
  95. package/src/components/Connections/DeleteConnectionDialog.tsx +23 -50
  96. package/src/components/Connections/EditConnectionDialog.tsx +54 -73
  97. package/src/components/Dashboard/Dashboard.spec.tsx +7 -10
  98. package/src/components/Dashboard/Dashboard.tsx +165 -175
  99. package/src/components/Dashboard/DashboardBar.tsx +88 -0
  100. package/src/components/Dashboard/DashboardGrid.tsx +124 -0
  101. package/src/components/Dashboard/DashboardTile.spec.tsx +30 -6
  102. package/src/components/Dashboard/DashboardTile.tsx +66 -123
  103. package/src/components/Dashboard/ExploreDialog.tsx +84 -0
  104. package/src/components/Dashboard/RowsDialog.spec.ts +42 -0
  105. package/src/components/Dashboard/RowsDialog.tsx +234 -0
  106. package/src/components/Dashboard/TileCard.tsx +120 -0
  107. package/src/components/Dashboard/index.ts +2 -0
  108. package/src/components/Dashboard/promoteMeasureRow.spec.ts +70 -0
  109. package/src/components/Dashboard/promoteMeasureRow.ts +33 -2
  110. package/src/components/Dashboard/telemetry.ts +51 -0
  111. package/src/components/Dashboard/tileGridColumn.spec.ts +1 -1
  112. package/src/components/DashboardBuilder/AddTileDialog.tsx +247 -0
  113. package/src/components/DashboardBuilder/BuilderToolbar.tsx +162 -0
  114. package/src/components/DashboardBuilder/DashboardBuilder.spec.tsx +852 -0
  115. package/src/components/DashboardBuilder/DashboardBuilder.tsx +666 -0
  116. package/src/components/DashboardBuilder/DashboardEditor.package.spec.tsx +163 -0
  117. package/src/components/DashboardBuilder/DashboardEditor.spec.tsx +188 -0
  118. package/src/components/DashboardBuilder/DashboardEditor.tsx +567 -0
  119. package/src/components/DashboardBuilder/DiffDialog.tsx +122 -0
  120. package/src/components/DashboardBuilder/DrillDialog.tsx +269 -0
  121. package/src/components/DashboardBuilder/FilterDialog.tsx +562 -0
  122. package/src/components/DashboardBuilder/FilterStrip.tsx +126 -0
  123. package/src/components/DashboardBuilder/SettingsPopover.tsx +168 -0
  124. package/src/components/DashboardBuilder/TileFrame.tsx +380 -0
  125. package/src/components/DashboardBuilder/TileMenu.tsx +188 -0
  126. package/src/components/DashboardBuilder/catalog.spec.ts +215 -0
  127. package/src/components/DashboardBuilder/catalog.ts +225 -0
  128. package/src/components/DashboardBuilder/controls.spec.ts +243 -0
  129. package/src/components/DashboardBuilder/controls.ts +398 -0
  130. package/src/components/DashboardBuilder/diff.spec.ts +44 -0
  131. package/src/components/DashboardBuilder/diff.ts +93 -0
  132. package/src/components/DashboardBuilder/document.ts +209 -0
  133. package/src/components/DashboardBuilder/keepRowStructure.spec.ts +84 -0
  134. package/src/components/DashboardBuilder/layout.ts +143 -0
  135. package/src/components/DashboardBuilder/malloyText.spec.ts +84 -0
  136. package/src/components/DashboardBuilder/malloyText.ts +151 -0
  137. package/src/components/DashboardBuilder/moveIntoGap.spec.ts +90 -0
  138. package/src/components/DashboardBuilder/newDashboard.spec.ts +40 -0
  139. package/src/components/DashboardBuilder/newDashboard.ts +48 -0
  140. package/src/components/DashboardBuilder/preview.spec.ts +149 -0
  141. package/src/components/DashboardBuilder/preview.ts +172 -0
  142. package/src/components/DashboardBuilder/readDocument.spec.ts +375 -0
  143. package/src/components/DashboardBuilder/readDocument.ts +467 -0
  144. package/src/components/DashboardBuilder/sortable.tsx +151 -0
  145. package/src/components/DashboardBuilder/spliceDocument.spec.ts +1161 -0
  146. package/src/components/DashboardBuilder/spliceDocument.ts +1135 -0
  147. package/src/components/DashboardBuilder/testing/fixtures.ts +48 -0
  148. package/src/components/DashboardBuilder/useBuilderShortcuts.ts +88 -0
  149. package/src/components/DashboardBuilder/useDashboardEditor.spec.ts +311 -0
  150. package/src/components/DashboardBuilder/useDashboardEditor.ts +201 -0
  151. package/src/components/DashboardBuilder/useDraft.ts +43 -0
  152. package/src/components/DashboardBuilder/useFilterForm.spec.tsx +144 -0
  153. package/src/components/DashboardBuilder/useFilterForm.ts +352 -0
  154. package/src/components/DashboardBuilder/useTileReorder.spec.tsx +97 -0
  155. package/src/components/DashboardBuilder/useTileReorder.ts +115 -0
  156. package/src/components/DashboardBuilder/useTileResize.spec.tsx +121 -0
  157. package/src/components/DashboardBuilder/useTileResize.ts +110 -0
  158. package/src/components/DashboardBuilder/withGaps.spec.ts +96 -0
  159. package/src/components/DocumentStorage/DocumentStorageProvider.tsx +12 -0
  160. package/src/components/DocumentStorage/index.ts +1 -0
  161. package/src/components/Environment/About.tsx +16 -62
  162. package/src/components/Environment/AddPackageDialog.tsx +85 -154
  163. package/src/components/Environment/Connections.tsx +125 -205
  164. package/src/components/Environment/DeletePackageDialog.tsx +32 -77
  165. package/src/components/Environment/EditPackageDialog.tsx +46 -58
  166. package/src/components/Environment/Environment.tsx +34 -36
  167. package/src/components/Environment/Packages.tsx +63 -128
  168. package/src/components/FloatingIconButton.tsx +41 -0
  169. package/src/components/Home/AddEnvironmentDialog.tsx +47 -70
  170. package/src/components/Home/DeleteEnvironmentDialog.tsx +32 -77
  171. package/src/components/Home/EditEnvironmentDialog.tsx +47 -61
  172. package/src/components/Home/Home.tsx +101 -214
  173. package/src/components/ItemRow.tsx +165 -0
  174. package/src/components/Materializations/CreateMaterializationDialog.tsx +34 -51
  175. package/src/components/Materializations/DeleteMaterializationDialog.tsx +31 -53
  176. package/src/components/Materializations/MaterializationDetailDialog.tsx +60 -69
  177. package/src/components/Materializations/MaterializationRunsList.tsx +29 -42
  178. package/src/components/Materializations/Materializations.tsx +137 -140
  179. package/src/components/Materializations/ScopeButton.tsx +85 -0
  180. package/src/components/Materializations/SectionLabel.tsx +7 -4
  181. package/src/components/Materializations/SetScheduleDialog.tsx +48 -89
  182. package/src/components/Materializations/TriggerLabel.tsx +36 -0
  183. package/src/components/Materializations/cron.spec.ts +113 -0
  184. package/src/components/Materializations/index.ts +0 -1
  185. package/src/components/Materializations/utils.spec.ts +182 -0
  186. package/src/components/Model/Model.tsx +6 -23
  187. package/src/components/Model/ModelCell.tsx +33 -72
  188. package/src/components/Notebook/Notebook.tsx +25 -88
  189. package/src/components/Notebook/NotebookCell.tsx +35 -183
  190. package/src/components/Package/ContentTypeIcon.spec.ts +22 -37
  191. package/src/components/Package/ContentTypeIcon.tsx +10 -12
  192. package/src/components/Package/NewDashboardDialog.spec.tsx +129 -0
  193. package/src/components/Package/NewDashboardDialog.tsx +265 -0
  194. package/src/components/Package/Package.tsx +179 -238
  195. package/src/components/Package/index.ts +0 -1
  196. package/src/components/PackageSection.tsx +85 -0
  197. package/src/components/Prose.spec.tsx +85 -0
  198. package/src/components/Prose.tsx +179 -0
  199. package/src/components/QueryResult/QueryResult.tsx +15 -43
  200. package/src/components/RenderedResult/RenderedResult.lifecycle.spec.tsx +198 -0
  201. package/src/components/RenderedResult/RenderedResult.tsx +22 -8
  202. package/src/components/RenderedResult/ResultContainer.tsx +4 -12
  203. package/src/components/RenderedResult/ResultPanel.spec.tsx +49 -0
  204. package/src/components/RenderedResult/ResultPanel.tsx +73 -0
  205. package/src/components/RenderedResult/index.ts +1 -0
  206. package/src/components/ResultsDialog.tsx +8 -32
  207. package/src/components/buttons.tsx +114 -0
  208. package/src/components/designSystem.spec.tsx +316 -0
  209. package/src/components/drill/index.ts +1 -0
  210. package/src/components/drill/resolveDrill.ts +22 -1
  211. package/src/components/drill/useDrill.spec.tsx +94 -0
  212. package/src/components/drill/useDrill.tsx +52 -12
  213. package/src/components/given/GivensPanel.tsx +1 -1
  214. package/src/components/given/paramCodec.spec.ts +1 -1
  215. package/src/components/index.ts +16 -0
  216. package/src/components/styles.ts +49 -122
  217. package/src/hooks/index.ts +13 -0
  218. package/src/hooks/useCrudMutation.spec.tsx +119 -0
  219. package/src/hooks/useCrudMutation.tsx +85 -0
  220. package/src/hooks/useDocumentControls.ts +170 -0
  221. package/src/hooks/useQueryResult.ts +82 -0
  222. package/src/index.ts +9 -0
  223. package/src/telemetry/consoleEvents.spec.ts +130 -0
  224. package/src/telemetry/consoleEvents.ts +124 -0
  225. package/src/theme/defaults.ts +34 -23
  226. package/src/theme/resolveTheme.spec.ts +9 -4
  227. package/src/theme/resolveTheme.ts +12 -8
  228. package/src/utils/malloyLiteral.spec.ts +43 -0
  229. package/src/utils/malloyLiteral.ts +76 -0
  230. package/src/utils/sha256.ts +13 -0
  231. package/test/README.md +1 -1
  232. package/test/serverProvider.tsx +5 -2
  233. package/vite.config.ts +5 -0
  234. package/dist/ServerProvider-CGnLjzag.cjs.js +0 -1
  235. package/dist/components/Materializations/CreateEnvMaterializationDialog.d.ts +0 -14
  236. package/dist/components/Materializations/EnvironmentMaterializations.d.ts +0 -7
  237. package/dist/components/Materializations/ScheduleCard.d.ts +0 -20
  238. package/dist/components/Materializations/TriggerChip.d.ts +0 -10
  239. package/dist/components/Package/Models.d.ts +0 -6
  240. package/src/components/Materializations/CreateEnvMaterializationDialog.tsx +0 -179
  241. package/src/components/Materializations/EnvironmentMaterializations.tsx +0 -267
  242. package/src/components/Materializations/ScheduleCard.tsx +0 -231
  243. package/src/components/Materializations/TriggerChip.tsx +0 -44
  244. package/src/components/Package/Models.tsx +0 -71
@@ -0,0 +1,467 @@
1
+ // Copyright (c) Credible Data Inc.
2
+ // SPDX-License-Identifier: MIT
3
+
4
+ import type {
5
+ DashboardDocument,
6
+ DashboardDrill,
7
+ DashboardImport,
8
+ DashboardSource,
9
+ DashboardTile,
10
+ LocalGiven,
11
+ } from "./document";
12
+ import {
13
+ type DeclarationAt,
14
+ declarationsUnder,
15
+ givenDeclarations,
16
+ tileSteps,
17
+ } from "./malloyText";
18
+
19
+ /**
20
+ * Read a `dashboards/*.malloy` file into a {@link DashboardDocument}.
21
+ *
22
+ * PURE: source text in, document out. No server, no schema, no connection.
23
+ * `Malloy.parse` needs none of those — only `Malloy.compile` does — so this runs
24
+ * in the browser and in a unit test alike, which is what lets the suite open
25
+ * every dashboard in the repository as a regression gate.
26
+ *
27
+ * Structure comes from the parser's symbol tree, which covers imports (including
28
+ * the items of a named list), sources, views and dimensions, each with a source
29
+ * RANGE. Content comes from the text inside those ranges, and tags from
30
+ * `parseAnnotation` over the block above each declaration.
31
+ *
32
+ * Reading tags from the text rather than from the server, which serves them
33
+ * already attached, is deliberate. The splice writer has to LOCATE a tag in
34
+ * order to edit it, so the scan exists either way; taking the values from the
35
+ * same scan keeps one source of truth for them and keeps this function pure.
36
+ *
37
+ * ALL-OR-NOTHING: a file this cannot fully represent is refused rather than
38
+ * half-opened. The bar is lower than it sounds because the document is an
39
+ * editing projection — unmodelled Malloy survives a splice untouched, so it only
40
+ * blocks when it would make an edit unsafe.
41
+ */
42
+
43
+ /** Why a file could not be opened, in terms its author can act on. */
44
+ export interface ReadFailure {
45
+ ok: false;
46
+ reason: string;
47
+ /** 1-based, for a message that can point at the line. */
48
+ line?: number;
49
+ }
50
+
51
+ export type ReadResult =
52
+ | { ok: true; document: DashboardDocument }
53
+ | ReadFailure;
54
+
55
+ /**
56
+ * Narrow a result to its failure arm.
57
+ *
58
+ * A guard rather than `if (!result.ok)`, because this package compiles with
59
+ * `strict: false` — the tsconfig says why, and it is not ours to change — and
60
+ * without `strictNullChecks` TypeScript does not narrow a discriminated union
61
+ * through a negated discriminant. The failure is quiet: `result.reason` simply
62
+ * does not typecheck, in a codebase where most code never notices.
63
+ */
64
+ export const readFailed = (result: ReadResult): result is ReadFailure =>
65
+ result.ok === false;
66
+
67
+ /** A `#`/`//` block above a declaration, and where it sits. */
68
+ export interface Block {
69
+ /** 0-based line of the first line in the block. */
70
+ start: number;
71
+ /**
72
+ * The `#`-prefixed lines only, in order, WITH their line numbers. The writer
73
+ * needs the numbers to patch a tag in place; the reader only needs the text.
74
+ */
75
+ tags: Array<{ line: number; text: string }>;
76
+ }
77
+
78
+ /**
79
+ * The comment-and-tag block immediately above `declLine`.
80
+ *
81
+ * Scans upward while lines are `#` tags or `//` comments and STOPS AT A BLANK
82
+ * LINE. Validated against the bundled dashboard, where it collects
83
+ * `revenue_trend`'s three tags and the fourteen-line comment explaining its
84
+ * colspan, then stops at the blank line above — which is the right unit to carry
85
+ * when that tile moves.
86
+ *
87
+ * A blank line is the author's own separator, which is why it is the boundary
88
+ * rather than a count or a heuristic about comment content.
89
+ */
90
+ export function blockAbove(lines: string[], declLine: number): Block {
91
+ let start = declLine;
92
+ for (let i = declLine - 1; i >= 0; i--) {
93
+ const text = lines[i].trim();
94
+ if (text === "") break;
95
+ if (text.startsWith("#") || text.startsWith("//")) start = i;
96
+ else break;
97
+ }
98
+ const tags: Array<{ line: number; text: string }> = [];
99
+ for (let i = start; i < declLine; i++) {
100
+ const text = lines[i].trim();
101
+ // `##` at this indent level is a MODEL annotation and never belongs to a
102
+ // declaration; only single-`#` object tags do.
103
+ if (text.startsWith("#") && !text.startsWith("##"))
104
+ tags.push({ line: i, text });
105
+ }
106
+ return { start, tags };
107
+ }
108
+
109
+ /** Just the text of a block's tags, which is what `parseAnnotation` takes. */
110
+ const tagText = (tags: Array<{ text: string }>) => tags.map((t) => t.text);
111
+
112
+ /** The model-level `##` lines, which are not symbols and must be read as text. */
113
+ function modelLines(lines: string[]): {
114
+ description?: string;
115
+ artifact: string[];
116
+ } {
117
+ const doc: string[] = [];
118
+ const artifact: string[] = [];
119
+ for (const raw of lines) {
120
+ const text = raw.trim();
121
+ if (text.startsWith('##"')) doc.push(text.slice(3).trim());
122
+ else if (text.startsWith("##!")) continue;
123
+ else if (text.startsWith("##")) artifact.push(text);
124
+ }
125
+ return {
126
+ description: doc.length > 0 ? doc.join("\n") : undefined,
127
+ artifact,
128
+ };
129
+ }
130
+
131
+ /** `source: overview is scoped_orders extend {` -> `scoped_orders`. */
132
+ function sourceBase(text: string, name: string): string | undefined {
133
+ const m = new RegExp(
134
+ `source:\\s*${name}\\s+is\\s+([A-Za-z_][A-Za-z0-9_.]*)`,
135
+ ).exec(text);
136
+ return m?.[1];
137
+ }
138
+
139
+ /**
140
+ * `view: revenue_trend is sales_by_month + { where: … }` -> base and filters,
141
+ * or `inline` for `view: order_tile is { aggregate: … }`, which is a query body
142
+ * rather than a reference and is read but never rewritten.
143
+ */
144
+ function viewBody(
145
+ text: string,
146
+ name: string,
147
+ ):
148
+ | { kind: "reference"; from: string; refinement?: string }
149
+ | { kind: "inline" }
150
+ | undefined {
151
+ const ref = new RegExp(
152
+ `view:\\s*${name}\\s+is\\s+([A-Za-z_][A-Za-z0-9_.]*)\\s*(\\+\\s*\\{[\\s\\S]*\\})?`,
153
+ ).exec(text);
154
+ if (ref)
155
+ return { kind: "reference", from: ref[1], refinement: ref[2]?.trim() };
156
+ if (new RegExp(`view:\\s*${name}\\s+is\\s*\\{`).test(text))
157
+ return { kind: "inline" };
158
+ return undefined;
159
+ }
160
+
161
+ /**
162
+ * One `where: <field> <op> $<GIVEN>` clause. Exported for the writer, which
163
+ * has to find the same clauses in order to replace them and nothing else.
164
+ */
165
+ export const BINDING_CLAUSE =
166
+ /where:\s*([A-Za-z_][A-Za-z0-9_.]*)\s*(~|>=|<=|!=|=|>|<)\s*\$([A-Za-z_][A-Za-z0-9_]*)/g;
167
+
168
+ /** `where: products.brand ~ $BRAND`, `where: created_at >= $SINCE` … */
169
+ function filtersOf(refinement: string | undefined) {
170
+ if (!refinement) return undefined;
171
+ const out: Array<{ field: string; given: string; op?: string }> = [];
172
+ for (const m of refinement.matchAll(BINDING_CLAUSE))
173
+ out.push({
174
+ field: m[1],
175
+ given: m[3],
176
+ ...(m[2] === "~" ? {} : { op: m[2] }),
177
+ });
178
+ return out.length > 0 ? out : undefined;
179
+ }
180
+
181
+ /**
182
+ * A tag object, as `parseAnnotation` returns it. Only the reads this file makes.
183
+ */
184
+ type TagLike = {
185
+ text: (key: string) => string | undefined;
186
+ numeric: (key: string) => number | undefined;
187
+ tag: (key: string) => TagLike | undefined;
188
+ };
189
+ type ParseTags = (lines: string[]) => { tag?: TagLike | null };
190
+
191
+ /**
192
+ * `given:` declarations, which the parser's symbol tree does not cover at all —
193
+ * its types are query, unnamed_query, explore, field, join, import and
194
+ * import_item. So these are read as text, in BOTH spellings Malloy accepts and
195
+ * this repository uses:
196
+ *
197
+ * given: CATEGORY :: filter<string> is f'' // one per line
198
+ *
199
+ * given: // a block
200
+ * CATEGORY :: filter<string> is f''
201
+ * SINCE :: date is @2023-01-01
202
+ *
203
+ * The one-line form is what `givens.malloy` and the docs write and what the
204
+ * builder emits; the block form is read so a file written the other way still
205
+ * opens. Either way the tags above a declaration are its control contract.
206
+ */
207
+ export function localGivens(
208
+ lines: string[],
209
+ parse: ParseTags,
210
+ ): LocalGiven[] | undefined {
211
+ const out: LocalGiven[] = [];
212
+ for (const at of givenDeclarations(lines).values()) {
213
+ const m = /^([A-Z_][A-Z0-9_]*)\s*::\s*(\S+)\s+is\s+(.+)$/.exec(
214
+ at.declaration,
215
+ );
216
+ if (!m) continue;
217
+ out.push({
218
+ name: m[1],
219
+ type: m[2],
220
+ default: m[3].trim(),
221
+ ...readControlTags(
222
+ parse(tagText(blockAbove(lines, at.line).tags)).tag,
223
+ ),
224
+ });
225
+ }
226
+ return out.length > 0 ? out : undefined;
227
+ }
228
+
229
+ /** The control contract off a given's tags; see {@link LocalGiven}. */
230
+ function readControlTags(tag: TagLike | null | undefined): Partial<LocalGiven> {
231
+ if (!tag) return {};
232
+ const suggest = tag.tag("suggest");
233
+ const dimension = suggest?.text("dimension");
234
+ const rangeMin = tag.numeric("range_min");
235
+ const rangeMax = tag.numeric("range_max");
236
+ return {
237
+ ...(tag.text("label") === undefined ? {} : { label: tag.text("label") }),
238
+ ...(tag.text("description") === undefined
239
+ ? {}
240
+ : { description: tag.text("description") }),
241
+ ...(tag.text("control") === undefined
242
+ ? {}
243
+ : { control: tag.text("control") }),
244
+ ...(suggest && dimension
245
+ ? {
246
+ suggest: {
247
+ ...(suggest.text("source") === undefined
248
+ ? {}
249
+ : { source: suggest.text("source") }),
250
+ ...(suggest.text("query") === undefined
251
+ ? {}
252
+ : { query: suggest.text("query") }),
253
+ dimension,
254
+ },
255
+ }
256
+ : {}),
257
+ ...(rangeMin === undefined ? {} : { rangeMin }),
258
+ ...(rangeMax === undefined ? {} : { rangeMax }),
259
+ };
260
+ }
261
+
262
+ /** The `tiles=[…]` entries, in order, as written. */
263
+ function tileEntries(artifactLine: string): string[] {
264
+ const key = artifactLine.search(/tiles\s*=\s*\[/);
265
+ if (key < 0) return [];
266
+ const open = artifactLine.indexOf("[", key);
267
+ const close = artifactLine.indexOf("]", open);
268
+ if (close < 0) return [];
269
+ const list = artifactLine.slice(open + 1, close);
270
+ return [...list.matchAll(/"([^"]+)"/g)].map((m) => m[1]);
271
+ }
272
+
273
+ export async function readDashboardDocument(
274
+ sourceText: string,
275
+ ): Promise<ReadResult> {
276
+ const { Malloy } = await import("@malloydata/malloy");
277
+ const { parseAnnotation } = await import("@malloydata/malloy-tag");
278
+ const lines = sourceText.split("\n");
279
+
280
+ let symbols;
281
+ try {
282
+ symbols = Malloy.parse({ source: sourceText }).symbols;
283
+ } catch (error) {
284
+ return { ok: false, reason: `This file is not valid Malloy: ${error}` };
285
+ }
286
+
287
+ const { description, artifact } = modelLines(lines);
288
+ const artifactLine = artifact.find((l) => l.includes("artifact"));
289
+ if (artifactLine === undefined) {
290
+ return {
291
+ ok: false,
292
+ reason:
293
+ "No `## artifact { … }` tag, so this file is not a composite dashboard.",
294
+ };
295
+ }
296
+
297
+ const tag = parseAnnotation([artifactLine.replace(/^##\s*/, "# ")]).tag;
298
+ const artifactTag = tag?.tag("artifact");
299
+ const entries = tileEntries(artifactLine);
300
+ if (entries.length === 0) {
301
+ return {
302
+ ok: false,
303
+ reason:
304
+ "The `## artifact` tag names no tiles, so there is nothing to lay out.",
305
+ };
306
+ }
307
+
308
+ const imports: DashboardImport[] = [];
309
+ const sources: DashboardSource[] = [];
310
+ const drills: DashboardDrill[] = [];
311
+ const viewsBySource = new Map<string, Map<string, DeclarationAt>>();
312
+
313
+ for (const symbol of symbols) {
314
+ if (symbol.type === "import") {
315
+ const names = (symbol.children ?? [])
316
+ .filter((c) => c.type === "import_item")
317
+ .map((c) => String(c.name));
318
+ imports.push(
319
+ names.length > 0
320
+ ? { kind: "names", names, from: String(symbol.name) }
321
+ : { kind: "all", from: String(symbol.name) },
322
+ );
323
+ continue;
324
+ }
325
+ if (symbol.type !== "explore") continue;
326
+
327
+ const name = String(symbol.name);
328
+ const head = lines[symbol.range.start.line] ?? "";
329
+ const base = sourceBase(head, name);
330
+ if (base === undefined) {
331
+ return {
332
+ ok: false,
333
+ reason: `Could not read what source \`${name}\` extends.`,
334
+ line: symbol.range.start.line + 1,
335
+ };
336
+ }
337
+ sources.push({ name, base });
338
+
339
+ // The VIEWS are found in the TEXT, attributed to the nearest `source:`
340
+ // above them, and not taken from the symbol tree. The tree is reliable
341
+ // about which sources and imports exist and unreliable about what is
342
+ // inside a source: measured, a refinement spelled `+ { limit: 5, where: … }`
343
+ // — which compiles — makes it report the refined view's BASE as a child
344
+ // view, end the source early, and drop the next declaration altogether,
345
+ // so the tile that named it read back as "inherited" and lost its tags.
346
+ // A `view: <name> is` line under a `source: <name> is` line is
347
+ // unambiguous, and Malloy has no nested sources to confuse it.
348
+ const views = declarationsUnder(lines, name, "view");
349
+ // Dimensions the same way, and drills off THEIR tag blocks: a `# drill`
350
+ // is a tag on a dimension's declaration, so the dimensions this file
351
+ // declares are exactly where one can be authored.
352
+ const dimensions = declarationsUnder(lines, name, "dimension");
353
+ if (dimensions.size > 0) {
354
+ sources[sources.length - 1].dimensions = [...dimensions].map(
355
+ ([dimensionName, at]) => ({
356
+ name: dimensionName,
357
+ expression: at.rest,
358
+ }),
359
+ );
360
+ }
361
+ for (const [dimensionName, at] of dimensions) {
362
+ const { tags } = blockAbove(lines, at.line);
363
+ const drillTag = parseAnnotation(tagText(tags)).tag?.tag("drill");
364
+ if (!drillTag) continue;
365
+ const to = drillTag.textArray("to") ?? [drillTag.text("to") ?? ""];
366
+ drills.push({
367
+ source: name,
368
+ name: dimensionName,
369
+ expression: at.rest,
370
+ to: to.filter(Boolean),
371
+ ...(drillTag.text("given")
372
+ ? { given: drillTag.text("given") as string }
373
+ : {}),
374
+ });
375
+ }
376
+ viewsBySource.set(name, views);
377
+ }
378
+
379
+ const tiles: DashboardTile[] = [];
380
+ for (const entry of entries) {
381
+ const steps = tileSteps(entry);
382
+ if (!steps) {
383
+ return {
384
+ ok: false,
385
+ reason:
386
+ `The tile \`${entry}\` is not a \`source -> view\` expression, ` +
387
+ `which is the only form the builder can lay out.`,
388
+ };
389
+ }
390
+ const { source: sourceName, view: viewName } = steps;
391
+ const declLine = viewsBySource.get(sourceName)?.get(viewName)?.line;
392
+
393
+ // Not declared here: the view belongs to an imported source, which is a
394
+ // complete dashboard in itself — `tiles=["orders -> by_brand"]` over an
395
+ // imported `orders` needs nothing else in the file. Shown, not editable:
396
+ // its tags live on the model's view, and the builder does not write model
397
+ // files.
398
+ if (declLine === undefined) {
399
+ tiles.push({
400
+ name: viewName,
401
+ source: sourceName,
402
+ declaration: { kind: "inherited" },
403
+ });
404
+ continue;
405
+ }
406
+
407
+ const body = viewBody(lines[declLine], viewName);
408
+ if (body === undefined) {
409
+ return {
410
+ ok: false,
411
+ reason: `Could not read what view \`${viewName}\` is declared from.`,
412
+ line: declLine + 1,
413
+ };
414
+ }
415
+ const { tags } = blockAbove(lines, declLine);
416
+ const t = parseAnnotation(tagText(tags)).tag;
417
+ const filters =
418
+ body.kind === "reference" ? filtersOf(body.refinement) : undefined;
419
+ tiles.push({
420
+ name: viewName,
421
+ source: sourceName,
422
+ declaration:
423
+ body.kind === "reference"
424
+ ? { kind: "reference", from: body.from }
425
+ : { kind: "inline" },
426
+ ...(filters ? { filters } : {}),
427
+ ...(t?.text("label") ? { label: t.text("label") as string } : {}),
428
+ ...(t?.text("subtitle")
429
+ ? { subtitle: t.text("subtitle") as string }
430
+ : {}),
431
+ ...(t?.numeric("colspan") !== undefined
432
+ ? { colspan: t.numeric("colspan") as number }
433
+ : {}),
434
+ ...(t?.has("break") ? { break: true } : {}),
435
+ ...(t?.has("borderless") ? { borderless: true } : {}),
436
+ });
437
+ }
438
+
439
+ const givens = localGivens(lines, parseAnnotation as ParseTags);
440
+
441
+ const startingGivens: Record<string, string> = {};
442
+ const givensTag = artifactTag?.tag("givens");
443
+ for (const key of Object.keys(givensTag?.dict ?? {})) {
444
+ const value = givensTag?.text(key);
445
+ if (value !== undefined) startingGivens[key] = value;
446
+ }
447
+
448
+ const columnsTag = tag?.tag("dashboard")?.numeric("columns");
449
+
450
+ return {
451
+ ok: true,
452
+ document: {
453
+ title: artifactTag?.text("title") ?? "",
454
+ ...(description ? { description } : {}),
455
+ ...(columnsTag === undefined ? {} : { columns: columnsTag }),
456
+ ...(artifactTag?.has("autorun")
457
+ ? { autorun: artifactTag.isTrue("autorun") }
458
+ : {}),
459
+ imports,
460
+ sources,
461
+ ...(givens ? { localGivens: givens } : {}),
462
+ ...(Object.keys(startingGivens).length > 0 ? { startingGivens } : {}),
463
+ ...(drills.length > 0 ? { drills } : {}),
464
+ tiles,
465
+ },
466
+ };
467
+ }
@@ -0,0 +1,151 @@
1
+ // Copyright (c) Credible Data Inc.
2
+ // SPDX-License-Identifier: MIT
3
+
4
+ import { pointerIntersection } from "@dnd-kit/collision";
5
+ import { Feedback, KeyboardSensor, PointerSensor } from "@dnd-kit/dom";
6
+ import { useDroppable } from "@dnd-kit/react";
7
+ import { useSortable, type UseSortableInput } from "@dnd-kit/react/sortable";
8
+ import type { ReactNode } from "react";
9
+
10
+ /**
11
+ * The builder's drag and drop, on `@dnd-kit/react`.
12
+ *
13
+ * The library owns the GESTURE: sensors for pointer, touch and keyboard, the
14
+ * activation threshold, collision detection, the copy that follows the pointer,
15
+ * the slide of the other tiles into place, auto-scroll at the viewport's edge,
16
+ * and the screen-reader announcements.
17
+ *
18
+ * The builder owns the LAYOUT and what a drop MEANS. Tiles sit on the reader's
19
+ * own `DashboardGrid`, and where a tile lands in the file — its place in
20
+ * `tiles=[…]`, and which row it starts — is settled by `keepRowStructure` and
21
+ * `moveIntoGap` in the builder. This module only reports "this tile is over
22
+ * that target".
23
+ */
24
+
25
+ /** The draggable type of a tile, and what every drop target accepts. */
26
+ const TILE_TYPE = "tile";
27
+ /** The type of a gap: the empty end of a row, offered as a drop target. */
28
+ export const GAP_TYPE = "gap";
29
+
30
+ /**
31
+ * The sensors: the library's own, with one addition and one exception.
32
+ *
33
+ * The ADDITION is `activatorElements`: the whole tile starts a pointer drag,
34
+ * not only the grip. A 22px corner that appears on hover is not a target a
35
+ * reader finds; the whole card is. The grip stays the `handle`, which is what
36
+ * gives it keyboard focus and the screen-reader instructions — and, by the
37
+ * library's own rule, a press on the handle drags at once while a press
38
+ * anywhere else on the card waits for a short hold or a few pixels of travel,
39
+ * so a click inside a tile stays a click. Those thresholds, and the check that
40
+ * a press on a button or a link is never a drag, are the defaults: they are
41
+ * what every surface built on this library feels like, and the hand-tuned
42
+ * versions this replaced were most of why the gesture felt unfamiliar.
43
+ *
44
+ * The EXCEPTION is the resize handle. Its own pointer handling stops the press
45
+ * in React, but React's listener sits at the root and runs after the sensor's
46
+ * own listener on the tile has already seen it; so the sensor is told directly
47
+ * that a press there is not the start of a move.
48
+ */
49
+ const RESIZE_HANDLE = '[role="separator"]';
50
+ export const builderSensors = [
51
+ PointerSensor.configure({
52
+ activatorElements: (source) => [source.element],
53
+ preventActivation: (event, source) =>
54
+ (PointerSensor.defaults.preventActivation?.(event, source) ?? false) ||
55
+ (event.target instanceof Element &&
56
+ event.target.closest(RESIZE_HANDLE) !== null),
57
+ }),
58
+ KeyboardSensor,
59
+ ];
60
+
61
+ /**
62
+ * What a tile looks like while it is dragged: a COPY follows the pointer, and
63
+ * the tile itself stays in the flow at its previewed place, dimmed. The
64
+ * library's default lifts the element itself out and leaves a placeholder,
65
+ * which is the other way round from the point of the preview — that the row
66
+ * you see reflow under the pointer is the row that lands.
67
+ */
68
+ const tilePlugins: NonNullable<UseSortableInput["plugins"]> = (defaults) => [
69
+ ...defaults,
70
+ Feedback.configure({ feedback: "clone" }),
71
+ ];
72
+
73
+ interface TileSortableHandles {
74
+ /** The tile's element: what is dragged, and what a drop lands on. */
75
+ ref: (element: Element | null) => void;
76
+ /** The grip: keyboard focus and screen-reader instructions live here. */
77
+ handleRef: (element: Element | null) => void;
78
+ /** This tile is the one being dragged. */
79
+ isDragSource: boolean;
80
+ }
81
+
82
+ /**
83
+ * A tile as a sortable item. A component rather than a hook call in the
84
+ * builder's render, because the grid renders tiles through a callback and a
85
+ * hook cannot be called from one.
86
+ *
87
+ * `index` is the tile's place in the PREVIEWED order, which is what lets the
88
+ * library animate a tile to its new slot when that order changes under it.
89
+ */
90
+ export function TileSortable({
91
+ id,
92
+ index,
93
+ children,
94
+ }: {
95
+ id: string;
96
+ index: number;
97
+ children: (handles: TileSortableHandles) => ReactNode;
98
+ }) {
99
+ const { ref, handleRef, isDragSource } = useSortable({
100
+ id,
101
+ index,
102
+ type: TILE_TYPE,
103
+ accept: TILE_TYPE,
104
+ // The same rule the gaps use: the target is what the POINTER is over.
105
+ // The sortable default weighs the dragged shape's overlap, and a wide
106
+ // tile in hand overlaps half the grid, so the target it chose was often
107
+ // not the tile under the cursor. One rule for both kinds of target is
108
+ // what makes a drop land where it looks like it will.
109
+ collisionDetector: pointerIntersection,
110
+ plugins: tilePlugins,
111
+ });
112
+ return <>{children({ ref, handleRef, isDragSource })}</>;
113
+ }
114
+
115
+ /** What a gap drop target carries: the key of the tile the gap follows. */
116
+ export interface GapData {
117
+ after: string;
118
+ }
119
+
120
+ /**
121
+ * The empty end of a row, as a drop target.
122
+ *
123
+ * A flow grid has no element where a row runs out; the space is simply not
124
+ * painted. So while a drag is live the builder lays one of these into each
125
+ * such space, spanning exactly the columns left over, and the library can
126
+ * report the pointer over it like any other target. `pointerIntersection`
127
+ * rather than the default shape overlap: the dragged copy is tile-sized and
128
+ * would overlap a neighbouring tile more than a narrow gap; the pointer is
129
+ * where the reader means.
130
+ */
131
+ export function GapDroppable({
132
+ id,
133
+ after,
134
+ children,
135
+ }: {
136
+ id: string;
137
+ after: string;
138
+ children: (handles: {
139
+ ref: (element: Element | null) => void;
140
+ isDropTarget: boolean;
141
+ }) => ReactNode;
142
+ }) {
143
+ const { ref, isDropTarget } = useDroppable<GapData>({
144
+ id,
145
+ type: GAP_TYPE,
146
+ accept: TILE_TYPE,
147
+ collisionDetector: pointerIntersection,
148
+ data: { after },
149
+ });
150
+ return <>{children({ ref, isDropTarget })}</>;
151
+ }