@malloy-publisher/sdk 0.12.0 → 0.12.2

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 (214) hide show
  1. package/README.md +79 -6
  2. package/dist/{RenderedResult-SgDlxzs9.cjs.js → RenderedResult-Cgw4iqev.cjs.js} +1 -1
  3. package/dist/{RenderedResult-D8bCgThO.es.js → RenderedResult-DEjFM1DL.es.js} +2 -2
  4. package/dist/ServerProvider-BRQl_cBo.cjs.js +1 -0
  5. package/dist/{ServerProvider-DBw-thY0.es.js → ServerProvider-RnliA2Ao.es.js} +1084 -723
  6. package/dist/builder/index.cjs.js +1 -1
  7. package/dist/builder/index.es.js +3 -3
  8. package/dist/client/api.d.ts +754 -41
  9. package/dist/client/index.cjs.js +1 -1
  10. package/dist/client/index.es.js +120 -110
  11. package/dist/components/Materializations/MaterializationDetailDialog.d.ts +16 -1
  12. package/dist/components/Model/ExplorerPage.d.ts +9 -0
  13. package/dist/components/Model/Model.d.ts +27 -11
  14. package/dist/components/ModelViewer/AccessChips.d.ts +34 -0
  15. package/dist/components/ModelViewer/EmptyRow.d.ts +23 -0
  16. package/dist/components/ModelViewer/Facts.d.ts +15 -0
  17. package/dist/components/ModelViewer/FieldGroup.d.ts +31 -0
  18. package/dist/components/ModelViewer/FieldRow.d.ts +69 -0
  19. package/dist/components/ModelViewer/GivenFacts.d.ts +21 -0
  20. package/dist/components/ModelViewer/HeaderBar.d.ts +75 -0
  21. package/dist/components/ModelViewer/InlineDoc.d.ts +13 -0
  22. package/dist/components/ModelViewer/ModelGivensSection.d.ts +32 -0
  23. package/dist/components/ModelViewer/ModelSection.d.ts +21 -0
  24. package/dist/components/ModelViewer/ModelViewer.d.ts +91 -0
  25. package/dist/components/ModelViewer/QueriesGroup.d.ts +15 -0
  26. package/dist/components/ModelViewer/RowGlyph.d.ts +27 -0
  27. package/dist/components/ModelViewer/RunResult.d.ts +46 -0
  28. package/dist/components/ModelViewer/SampleValues.d.ts +20 -0
  29. package/dist/components/ModelViewer/SchemaJoin.d.ts +51 -0
  30. package/dist/components/ModelViewer/SchemaView.d.ts +52 -0
  31. package/dist/components/ModelViewer/SegmentIcons.d.ts +70 -0
  32. package/dist/components/ModelViewer/SourcesDropdown.d.ts +53 -0
  33. package/dist/components/ModelViewer/SourcesNav.d.ts +25 -0
  34. package/dist/components/ModelViewer/StatusPill.d.ts +56 -0
  35. package/dist/components/ModelViewer/ValueChip.d.ts +17 -0
  36. package/dist/components/ModelViewer/ViewRow.d.ts +36 -0
  37. package/dist/components/ModelViewer/clickableBox.d.ts +29 -0
  38. package/dist/components/ModelViewer/codeDisplay.d.ts +44 -0
  39. package/dist/components/ModelViewer/docAnnotations.d.ts +90 -0
  40. package/dist/components/ModelViewer/explorerModel.d.ts +12 -0
  41. package/dist/components/ModelViewer/extensions.d.ts +94 -0
  42. package/dist/components/ModelViewer/fieldCode.d.ts +74 -0
  43. package/dist/components/ModelViewer/fieldEntities.d.ts +45 -0
  44. package/dist/components/ModelViewer/fieldExpansion.d.ts +41 -0
  45. package/dist/components/ModelViewer/givenUsage.d.ts +71 -0
  46. package/dist/components/ModelViewer/headerCard.d.ts +31 -0
  47. package/dist/components/ModelViewer/httpStatus.d.ts +4 -0
  48. package/dist/components/ModelViewer/icons.d.ts +31 -0
  49. package/dist/components/ModelViewer/index.d.ts +9 -0
  50. package/dist/components/ModelViewer/joinAccess.d.ts +52 -0
  51. package/dist/components/ModelViewer/malloyRunText.d.ts +22 -0
  52. package/dist/components/ModelViewer/malloyText.d.ts +21 -0
  53. package/dist/components/ModelViewer/modelGivens.d.ts +61 -0
  54. package/dist/components/ModelViewer/modelGivensContext.d.ts +9 -0
  55. package/dist/components/ModelViewer/modelHeaderPresentation.d.ts +28 -0
  56. package/dist/components/ModelViewer/modelTextDeclarations.d.ts +32 -0
  57. package/dist/components/ModelViewer/modelTextParse.d.ts +27 -0
  58. package/dist/components/ModelViewer/namedQueryCode.d.ts +12 -0
  59. package/dist/components/ModelViewer/offSurface.d.ts +54 -0
  60. package/dist/components/ModelViewer/rowLayers.d.ts +30 -0
  61. package/dist/components/ModelViewer/runGate.d.ts +49 -0
  62. package/dist/components/ModelViewer/schemaModel.d.ts +109 -0
  63. package/dist/components/ModelViewer/sectionOpenCommand.d.ts +45 -0
  64. package/dist/components/ModelViewer/sourceAccess.d.ts +67 -0
  65. package/dist/components/ModelViewer/sourceLineage.d.ts +14 -0
  66. package/dist/components/ModelViewer/sourcePicker.d.ts +66 -0
  67. package/dist/components/ModelViewer/surface.d.ts +47 -0
  68. package/dist/components/ModelViewer/text.d.ts +6 -0
  69. package/dist/components/ModelViewer/theme.d.ts +63 -0
  70. package/dist/components/ModelViewer/tokens.d.ts +52 -0
  71. package/dist/components/ModelViewer/ui.d.ts +48 -0
  72. package/dist/components/ModelViewer/useDimensionSamples.d.ts +76 -0
  73. package/dist/components/ModelViewer/useModelSources.d.ts +92 -0
  74. package/dist/components/ModelViewer/useRunQuery.d.ts +115 -0
  75. package/dist/components/ReportBuilder/loadMalloy.d.ts +4 -0
  76. package/dist/components/ServerProvider.d.ts +17 -2
  77. package/dist/components/filter/utils.d.ts +1 -1
  78. package/dist/components/given/GivenInput.d.ts +7 -1
  79. package/dist/components/given/GivensPanel.d.ts +3 -1
  80. package/dist/components/given/filterSummary.d.ts +6 -0
  81. package/dist/components/given/useGivenUrlParams.d.ts +11 -0
  82. package/dist/components/index.d.ts +2 -1
  83. package/dist/components/modelPage.d.ts +36 -0
  84. package/dist/hooks/useDimensionalFilterRangeData.d.ts +9 -0
  85. package/dist/hooks/useSuggestOptions.d.ts +26 -2
  86. package/dist/index.cjs.js +47 -19
  87. package/dist/index.es.js +14137 -9697
  88. package/dist/useCompiledDocument-D88_2cGS.cjs.js +143 -0
  89. package/dist/{useCompiledDocument-CXMPtJkJ.es.js → useCompiledDocument-Dmm6xkom.es.js} +6975 -6893
  90. package/dist/utils/filterCondition.d.ts +14 -0
  91. package/dist/utils/malloyLiteral.d.ts +20 -1
  92. package/package.json +2 -2
  93. package/src/components/Materializations/MaterializationDetailDialog.tsx +33 -7
  94. package/src/components/Materializations/Materializations.tsx +47 -4
  95. package/src/components/Materializations/Materializations.versions.spec.tsx +140 -1
  96. package/src/components/Model/ExplorerPage.tsx +269 -0
  97. package/src/components/Model/Model.tsx +66 -250
  98. package/src/components/Model/ModelExplorer.spec.tsx +64 -1
  99. package/src/components/ModelViewer/AccessChips.tsx +149 -0
  100. package/src/components/ModelViewer/EmptyRow.tsx +71 -0
  101. package/src/components/ModelViewer/Facts.tsx +46 -0
  102. package/src/components/ModelViewer/FieldGroup.tsx +137 -0
  103. package/src/components/ModelViewer/FieldRow.tsx +566 -0
  104. package/src/components/ModelViewer/GivenFacts.tsx +89 -0
  105. package/src/components/ModelViewer/HeaderBar.tsx +362 -0
  106. package/src/components/ModelViewer/InlineDoc.tsx +50 -0
  107. package/src/components/ModelViewer/ModelGivensSection.tsx +142 -0
  108. package/src/components/ModelViewer/ModelSection.tsx +98 -0
  109. package/src/components/ModelViewer/ModelViewer.spec.tsx +937 -0
  110. package/src/components/ModelViewer/ModelViewer.tsx +777 -0
  111. package/src/components/ModelViewer/QueriesGroup.tsx +107 -0
  112. package/src/components/ModelViewer/RowGlyph.tsx +138 -0
  113. package/src/components/ModelViewer/RunResult.tsx +298 -0
  114. package/src/components/ModelViewer/SampleValues.tsx +97 -0
  115. package/src/components/ModelViewer/SchemaJoin.tsx +258 -0
  116. package/src/components/ModelViewer/SchemaView.tsx +222 -0
  117. package/src/components/ModelViewer/SegmentIcons.tsx +129 -0
  118. package/src/components/ModelViewer/SourcesDropdown.tsx +265 -0
  119. package/src/components/ModelViewer/SourcesNav.tsx +75 -0
  120. package/src/components/ModelViewer/StatusPill.tsx +145 -0
  121. package/src/components/ModelViewer/ValueChip.tsx +39 -0
  122. package/src/components/ModelViewer/ViewRow.tsx +274 -0
  123. package/src/components/ModelViewer/clickableBox.ts +59 -0
  124. package/src/components/ModelViewer/codeDisplay.spec.ts +176 -0
  125. package/src/components/ModelViewer/codeDisplay.ts +118 -0
  126. package/src/components/ModelViewer/docAnnotations.spec.ts +181 -0
  127. package/src/components/ModelViewer/docAnnotations.ts +244 -0
  128. package/src/components/ModelViewer/docAnnotations.typeDetail.spec.ts +114 -0
  129. package/src/components/ModelViewer/explorerModel.spec.ts +43 -0
  130. package/src/components/ModelViewer/explorerModel.ts +31 -0
  131. package/src/components/ModelViewer/extensions.tsx +112 -0
  132. package/src/components/ModelViewer/fieldCode.spec.ts +168 -0
  133. package/src/components/ModelViewer/fieldCode.ts +118 -0
  134. package/src/components/ModelViewer/fieldEntities.ts +63 -0
  135. package/src/components/ModelViewer/fieldExpansion.spec.ts +116 -0
  136. package/src/components/ModelViewer/fieldExpansion.ts +95 -0
  137. package/src/components/ModelViewer/givenUsage.spec.ts +304 -0
  138. package/src/components/ModelViewer/givenUsage.ts +325 -0
  139. package/src/components/ModelViewer/headerCard.tsx +102 -0
  140. package/src/components/ModelViewer/httpStatus.ts +15 -0
  141. package/src/components/ModelViewer/icons.tsx +67 -0
  142. package/src/components/ModelViewer/index.ts +26 -0
  143. package/src/components/ModelViewer/joinAccess.spec.ts +95 -0
  144. package/src/components/ModelViewer/joinAccess.ts +54 -0
  145. package/src/components/ModelViewer/malloyRunText.spec.ts +48 -0
  146. package/src/components/ModelViewer/malloyRunText.ts +51 -0
  147. package/src/components/ModelViewer/malloyText.spec.ts +47 -0
  148. package/src/components/ModelViewer/malloyText.ts +77 -0
  149. package/src/components/ModelViewer/modelGivens.ts +228 -0
  150. package/src/components/ModelViewer/modelGivensContext.ts +13 -0
  151. package/src/components/ModelViewer/modelHeaderPresentation.spec.ts +31 -0
  152. package/src/components/ModelViewer/modelHeaderPresentation.ts +41 -0
  153. package/src/components/ModelViewer/modelTextDeclarations.spec.ts +336 -0
  154. package/src/components/ModelViewer/modelTextDeclarations.ts +228 -0
  155. package/src/components/ModelViewer/modelTextParse.ts +112 -0
  156. package/src/components/ModelViewer/namedQueryCode.spec.ts +58 -0
  157. package/src/components/ModelViewer/namedQueryCode.ts +26 -0
  158. package/src/components/ModelViewer/offSurface.tsx +124 -0
  159. package/src/components/ModelViewer/rowLayers.tsx +104 -0
  160. package/src/components/ModelViewer/runGate.spec.ts +219 -0
  161. package/src/components/ModelViewer/runGate.ts +145 -0
  162. package/src/components/ModelViewer/schemaModel.defaultSource.spec.ts +126 -0
  163. package/src/components/ModelViewer/schemaModel.queries.spec.ts +37 -0
  164. package/src/components/ModelViewer/schemaModel.ts +300 -0
  165. package/src/components/ModelViewer/sectionOpenCommand.tsx +125 -0
  166. package/src/components/ModelViewer/sourceAccess.spec.ts +130 -0
  167. package/src/components/ModelViewer/sourceAccess.ts +194 -0
  168. package/src/components/ModelViewer/sourceLineage.spec.ts +73 -0
  169. package/src/components/ModelViewer/sourceLineage.ts +38 -0
  170. package/src/components/ModelViewer/sourcePicker.spec.ts +294 -0
  171. package/src/components/ModelViewer/sourcePicker.ts +162 -0
  172. package/src/components/ModelViewer/surface.ts +51 -0
  173. package/src/components/ModelViewer/text.tsx +33 -0
  174. package/src/components/ModelViewer/theme.spec.ts +38 -0
  175. package/src/components/ModelViewer/theme.ts +58 -0
  176. package/src/components/ModelViewer/tokens.ts +87 -0
  177. package/src/components/ModelViewer/ui.tsx +201 -0
  178. package/src/components/ModelViewer/useDimensionSamples.spec.tsx +139 -0
  179. package/src/components/ModelViewer/useDimensionSamples.ts +220 -0
  180. package/src/components/ModelViewer/useModelSources.spec.ts +110 -0
  181. package/src/components/ModelViewer/useModelSources.ts +238 -0
  182. package/src/components/ModelViewer/useRunQuery.spec.ts +50 -0
  183. package/src/components/ModelViewer/useRunQuery.ts +223 -0
  184. package/src/components/Package/Package.agents.spec.tsx +5 -4
  185. package/src/components/Package/Package.tsx +8 -1
  186. package/src/components/ReportBuilder/emptyStart.spec.ts +8 -0
  187. package/src/components/ReportBuilder/loadMalloy.ts +8 -1
  188. package/src/components/ServerProvider.tsx +29 -3
  189. package/src/components/filter/utils.ts +4 -60
  190. package/src/components/given/FilterButton.tsx +4 -1
  191. package/src/components/given/GivenInput.tsx +8 -0
  192. package/src/components/given/GivensPanel.tsx +6 -1
  193. package/src/components/given/filterSummary.spec.ts +31 -1
  194. package/src/components/given/filterSummary.ts +41 -19
  195. package/src/components/given/useGivenUrlParams.spec.tsx +32 -0
  196. package/src/components/given/useGivenUrlParams.ts +49 -14
  197. package/src/components/index.ts +6 -1
  198. package/src/components/legacy/malloynb/Notebook.spec.tsx +38 -4
  199. package/src/components/legacy/malloynb/NotebookCell.tsx +8 -2
  200. package/src/components/modelPage.spec.ts +79 -0
  201. package/src/components/modelPage.ts +48 -0
  202. package/src/hooks/useDimensionFilters.ts +3 -58
  203. package/src/hooks/useDimensionFiltersQuery.ts +3 -58
  204. package/src/hooks/useDimensionalFilterRangeData.spec.ts +57 -0
  205. package/src/hooks/useDimensionalFilterRangeData.ts +8 -63
  206. package/src/hooks/useSuggestOptions.dom.spec.ts +54 -1
  207. package/src/hooks/useSuggestOptions.spec.ts +71 -0
  208. package/src/hooks/useSuggestOptions.ts +102 -12
  209. package/src/utils/filterCondition.spec.ts +87 -0
  210. package/src/utils/filterCondition.ts +66 -0
  211. package/src/utils/malloyLiteral.spec.ts +53 -1
  212. package/src/utils/malloyLiteral.ts +47 -12
  213. package/dist/ServerProvider-BHfg1Ed6.cjs.js +0 -1
  214. package/dist/useCompiledDocument-D7X_K6YU.cjs.js +0 -142
@@ -0,0 +1,300 @@
1
+ // Copyright (c) Credible Data Inc.
2
+ // SPDX-License-Identifier: MIT
3
+
4
+ import type * as Malloy from "@malloydata/malloy-interfaces";
5
+ import { isFieldIndexed } from "./modelGivens";
6
+ import {
7
+ atomicTypeDetail,
8
+ getFieldTagLines,
9
+ recordFieldsTip,
10
+ getDocParts,
11
+ getDocString,
12
+ getTagLines,
13
+ hasPersistTag,
14
+ hasPreaggregateTag,
15
+ } from "./docAnnotations";
16
+ import { AccentName, sourceAccentName } from "./tokens";
17
+ import type { ModelNamedQuery } from "./useModelSources";
18
+
19
+ /**
20
+ * Render-ready view model for the model viewer, flattened from the compiled
21
+ * `Malloy.SourceInfo` metadata.
22
+ *
23
+ * SourceInfo doesn't expose everything the design mock shows — table name,
24
+ * grain, primary key, measure expressions, join `on` conditions, and view
25
+ * group-by/aggregate breakdowns aren't in the compiled metadata, so the
26
+ * explorer renders only name / type / docstring / join relationship. If the
27
+ * model API grows those fields, extend these types rather than re-deriving
28
+ * in components.
29
+ */
30
+
31
+ export interface ExplorerField {
32
+ name: string;
33
+ kind: "dimension" | "measure" | "calculate" | "view";
34
+ /** Type with its detail, e.g. "string", "number · integer", "date · month",
35
+ * "array<string>": dimensions, measures and calculations only. */
36
+ dataType?: string;
37
+ /** A record type's fields, one per line, for the type chip's tooltip. */
38
+ typeTip?: string;
39
+ doc?: string;
40
+ /** True when the dimension carries `#(index)` / `#(index_values)` —
41
+ * its values can be fetched from the dimensional index. */
42
+ indexed?: boolean;
43
+ /** True when the measure carries `#@ preaggregate` — it is DECLARED to roll
44
+ * up into a table at some grain. Says nothing about whether one has been
45
+ * built; that is the measure's binding. */
46
+ preaggregate?: boolean;
47
+ /** Author-facing tags from the non-doc annotation lines: a view's renderer
48
+ * tags (`bar_chart`, `size=lg`), a field's display tags (`label="Revenue"`,
49
+ * `currency`, `percent`). */
50
+ tags?: string[];
51
+ }
52
+
53
+ /**
54
+ * A model-level named query (`query: name is …`). Model-scoped, not a field of
55
+ * any source — so it is listed beside the sources in the rail, not inside one.
56
+ * The compiled metadata carries its name and annotations only (no definition:
57
+ * `modelInfo.entries` never includes queries, and a host's entities have no
58
+ * query kind), so a query is something to RUN rather than something to read.
59
+ */
60
+ export interface ExplorerQuery {
61
+ name: string;
62
+ /** The source the query runs against, when the publisher reports it — the
63
+ * source whose required filters gate a run. */
64
+ sourceName?: string;
65
+ doc?: string;
66
+ /** Renderer/behavior tags (`bar_chart`, …), from the non-doc annotation lines. */
67
+ tags?: string[];
68
+ }
69
+
70
+ export interface ExplorerJoin {
71
+ name: string;
72
+ relationship: Malloy.Relationship;
73
+ doc?: string;
74
+ dimensions: ExplorerField[];
75
+ measures: ExplorerField[];
76
+ }
77
+
78
+ export interface ExplorerSource {
79
+ name: string;
80
+ doc?: string;
81
+ /** Each doc annotation, in order, inherited ones first (see `ownSourceDoc`). */
82
+ docParts?: string[];
83
+ accent: AccentName;
84
+ /** The source carries a `#@ persist` tag — served from a materialized
85
+ * table rather than computed live. */
86
+ persist?: boolean;
87
+ dimensions: ExplorerField[];
88
+ measures: ExplorerField[];
89
+ /** `calculate:` fields. */
90
+ calculations: ExplorerField[];
91
+ views: ExplorerField[];
92
+ joins: ExplorerJoin[];
93
+ }
94
+
95
+ function toField(
96
+ field:
97
+ | Malloy.FieldInfoWithDimension
98
+ | Malloy.FieldInfoWithMeasure
99
+ | Malloy.FieldInfoWithCalculate,
100
+ ): ExplorerField {
101
+ return {
102
+ name: field.name,
103
+ kind: field.kind,
104
+ dataType: atomicTypeDetail(field.type),
105
+ typeTip: recordFieldsTip(field.type),
106
+ tags: getFieldTagLines(field.annotations),
107
+ doc: getDocString(field.annotations),
108
+ indexed: field.kind === "dimension" ? isFieldIndexed(field) : undefined,
109
+ preaggregate:
110
+ field.kind === "measure"
111
+ ? hasPreaggregateTag(field.annotations)
112
+ : undefined,
113
+ };
114
+ }
115
+
116
+ function toJoin(field: Malloy.FieldInfoWithJoin): ExplorerJoin {
117
+ const dimensions: ExplorerField[] = [];
118
+ const measures: ExplorerField[] = [];
119
+ for (const child of field.schema?.fields ?? []) {
120
+ // One level deep is enough for the explorer; nested joins are rare and
121
+ // their fields read better in their own source's entry.
122
+ if (child.kind !== "dimension" && child.kind !== "measure") continue;
123
+ // Join children are indexed under the *joined* source, whose name we
124
+ // can't recover from the join field (the join name may differ). Force
125
+ // indexed=false so the inspector never fetches values against the
126
+ // parent source — a same-named parent dimension would silently return
127
+ // the wrong values. `preaggregate` is cleared for the same reason: the
128
+ // rollup belongs to the joined source, so offering a build from here
129
+ // would scope it to the wrong one.
130
+ const childField = {
131
+ ...toField(child),
132
+ indexed: false,
133
+ preaggregate: false,
134
+ };
135
+ if (child.kind === "dimension") dimensions.push(childField);
136
+ else measures.push(childField);
137
+ }
138
+ return {
139
+ name: field.name,
140
+ relationship: field.relationship,
141
+ doc: getDocString(field.annotations),
142
+ dimensions,
143
+ measures,
144
+ };
145
+ }
146
+
147
+ /** Flatten one compiled source into the explorer view model. */
148
+ export function toExplorerSource(
149
+ source: Malloy.SourceInfo,
150
+ index: number,
151
+ ): ExplorerSource {
152
+ const out: ExplorerSource = {
153
+ name: source.name,
154
+ doc: getDocString(source.annotations),
155
+ docParts: getDocParts(source.annotations),
156
+ accent: sourceAccentName(index),
157
+ persist: hasPersistTag(source.annotations),
158
+ dimensions: [],
159
+ measures: [],
160
+ calculations: [],
161
+ views: [],
162
+ joins: [],
163
+ };
164
+ for (const field of source.schema?.fields ?? []) {
165
+ switch (field.kind) {
166
+ case "dimension":
167
+ case "measure":
168
+ out[field.kind === "dimension" ? "dimensions" : "measures"].push(
169
+ toField(field),
170
+ );
171
+ break;
172
+ case "calculate":
173
+ out.calculations.push(toField(field));
174
+ break;
175
+ case "view":
176
+ out.views.push({
177
+ name: field.name,
178
+ kind: "view",
179
+ doc: getDocString(field.annotations),
180
+ // Views surface their renderer tags (bar_chart, size=lg, …) —
181
+ // how the view presents is part of what it IS.
182
+ tags: getTagLines(field.annotations),
183
+ });
184
+ break;
185
+ case "join":
186
+ out.joins.push(toJoin(field));
187
+ break;
188
+ }
189
+ }
190
+ return out;
191
+ }
192
+
193
+ /**
194
+ * Flatten the model's named queries. The publisher's `CompiledModel.queries`
195
+ * carries annotations as raw lines (not `Malloy.Annotation` objects), so they
196
+ * are wrapped to reuse the one doc/tag parser the fields use.
197
+ */
198
+ export function toExplorerQueries(
199
+ queries: ReadonlyArray<ModelNamedQuery> | undefined,
200
+ ): ExplorerQuery[] {
201
+ const out: ExplorerQuery[] = [];
202
+ for (const q of queries ?? []) {
203
+ if (!q.name) continue;
204
+ const annotations = (q.annotations ?? []).map((value) => ({ value }));
205
+ out.push({
206
+ name: q.name,
207
+ sourceName: q.sourceName || undefined,
208
+ doc: getDocString(annotations),
209
+ tags: getTagLines(annotations),
210
+ });
211
+ }
212
+ return out;
213
+ }
214
+
215
+ /**
216
+ * The fields a source declares: its dimensions, measures, calculations and views.
217
+ *
218
+ * A join's own fields are NOT counted: the pane header's count has to add
219
+ * up to the group counts printed directly beneath it — Dimensions · N, Measures
220
+ * · N, Views · N — and counting fields reachable THROUGH a join made the header
221
+ * read higher than anything visible, with the difference buried inside a
222
+ * collapsed Joins group. A join is counted as a join, not as its fields.
223
+ */
224
+ export function fieldCount(source: ExplorerSource): number {
225
+ return (
226
+ source.dimensions.length +
227
+ source.measures.length +
228
+ source.calculations.length +
229
+ source.views.length
230
+ );
231
+ }
232
+
233
+ /**
234
+ * Which source a model opens on when the address names none.
235
+ *
236
+ * Declaration order is not a ranking. `flights.malloy` declares `carriers`
237
+ * first and `flights` last; `imdb.malloy` declares `people` first and `movies`
238
+ * last — so `sources[0]` opened both files on a lookup table while the source
239
+ * the file is about sat at the bottom of the rail.
240
+ *
241
+ * The signal is **views**: a source someone has written views over is one
242
+ * someone means to be read, and the analytically-central source is where the
243
+ * views accumulate. Ties break toward the file's namesake (`flights.malloy` →
244
+ * `flights`), then toward declaration order, so the pick is total and stable.
245
+ *
246
+ * Namesake alone would not do it: `imdb.malloy` has no `imdb` source, and its
247
+ * subject is `movies`. Views get both files right.
248
+ */
249
+ export function pickDefaultSource(
250
+ sources: ExplorerSource[],
251
+ modelPath?: string,
252
+ ): ExplorerSource | null {
253
+ if (sources.length === 0) return null;
254
+ // `-` and `_` are the same character for this purpose: a file named
255
+ // `purchase-events.malloy` declaring `purchase_events` is a namesake match.
256
+ const norm = (v: string) => v.toLowerCase().replace(/[-_]/g, "");
257
+ const namesake = modelPath
258
+ ? norm((modelPath.split("/").pop() ?? modelPath).replace(/\.malloy$/, ""))
259
+ : undefined;
260
+
261
+ // A source written as `B is A extend { … }` carries A's views plus its own,
262
+ // so it ALWAYS outranks its own base on a view count — `ga4.malloy` would
263
+ // open on `purchase_events` (3) over `events` (1), the narrow slice over the
264
+ // subject. The schema does not say what a source extends, but a strict
265
+ // superset of another's view names is that relationship's signature, so a
266
+ // source that contains another's views entire is set aside while any
267
+ // candidate that is not stands.
268
+ const viewNames = new Map(
269
+ sources.map((s) => [s.name, new Set(s.views.map((v) => v.name))]),
270
+ );
271
+ const extendsAnother = (s: ExplorerSource) =>
272
+ sources.some((other) => {
273
+ if (other.name === s.name || other.views.length === 0) return false;
274
+ const mine = viewNames.get(s.name)!;
275
+ return (
276
+ other.views.length < s.views.length &&
277
+ [...viewNames.get(other.name)!].every((v) => mine.has(v))
278
+ );
279
+ });
280
+ const base = sources.filter((s) => !extendsAnother(s));
281
+ const pool = base.length > 0 ? base : sources;
282
+
283
+ let best = pool[0];
284
+ for (const s of pool.slice(1)) {
285
+ if (s.views.length !== best.views.length) {
286
+ if (s.views.length > best.views.length) best = s;
287
+ continue;
288
+ }
289
+ // Equal views: the namesake wins, and only it — anything else would be
290
+ // declaration order, which `best` already holds.
291
+ if (
292
+ namesake &&
293
+ norm(s.name) === namesake &&
294
+ norm(best.name) !== namesake
295
+ ) {
296
+ best = s;
297
+ }
298
+ }
299
+ return best;
300
+ }
@@ -0,0 +1,125 @@
1
+ // Copyright (c) Credible Data Inc.
2
+ // SPDX-License-Identifier: MIT
3
+
4
+ import { ButtonBase, Tooltip } from "@mui/material";
5
+ import { IconCollapse, IconExpand } from "./icons";
6
+ import { createContext, useContext, useState } from "react";
7
+ import { focusRingSx } from "./clickableBox";
8
+
9
+ /**
10
+ * A section's last "Expand" / "Collapse": every row in the section opens or
11
+ * shuts when `n` changes, then each is the reader's own again. Undefined until
12
+ * the reader asks, so a row starts shut.
13
+ */
14
+ export interface SectionOpenCommand {
15
+ open: boolean;
16
+ n: number;
17
+ }
18
+
19
+ export const SectionOpenCommandContext = createContext<
20
+ SectionOpenCommand | undefined
21
+ >(undefined);
22
+
23
+ /**
24
+ * A row's open state, following its section's Expand / Collapse each time it is
25
+ * asked and the reader's own toggle in between.
26
+ */
27
+ export function useSectionOpen(): [
28
+ boolean,
29
+ (update: (open: boolean) => boolean) => void,
30
+ ] {
31
+ const [open, setOpen] = useState(false);
32
+ const command = useContext(SectionOpenCommandContext);
33
+ const [applied, setApplied] = useState(command?.n);
34
+ if (command && command.n !== applied) {
35
+ setApplied(command.n);
36
+ setOpen(command.open);
37
+ }
38
+ return [open, setOpen];
39
+ }
40
+
41
+ /**
42
+ * The Expand / Collapse control for a section: the chevron saying which way it goes, and
43
+ * an accessible name saying what it opens, its visible words first and then the rows they
44
+ * act on ("Expand all measures"), or why it can't. It changes what the section shows rather
45
+ * than acting on the page, so it is a quiet text link alone on the line under the section's
46
+ * title, in the caption voice, so it reads as part of the section's header.
47
+ */
48
+ export function SectionExpandButton({
49
+ allOpen,
50
+ onToggle,
51
+ noun,
52
+ disabledReason,
53
+ }: {
54
+ allOpen: boolean;
55
+ onToggle: () => void;
56
+ noun: readonly [string, string];
57
+ disabledReason?: string;
58
+ }) {
59
+ const chevron = allOpen ? (
60
+ <IconCollapse size={16} aria-hidden />
61
+ ) : (
62
+ <IconExpand size={16} aria-hidden />
63
+ );
64
+ return (
65
+ <Tooltip title={disabledReason ?? ""}>
66
+ {/* The span keeps the tooltip reachable on a disabled button. */}
67
+ <span>
68
+ <ButtonBase
69
+ disabled={!!disabledReason}
70
+ onClick={onToggle}
71
+ aria-label={
72
+ disabledReason ??
73
+ `${allOpen ? "Collapse" : "Expand"} all ${noun[1]}`
74
+ }
75
+ sx={{
76
+ // The caption's type under the title, so it reads as the header's own line.
77
+ font: "inherit",
78
+ color: "text.secondary",
79
+ gap: 0.25,
80
+ borderRadius: 1,
81
+ "&:hover": {
82
+ color: "text.primary",
83
+ textDecoration: "underline",
84
+ },
85
+ ...focusRingSx,
86
+ "&.Mui-disabled": { opacity: 0.5 },
87
+ }}
88
+ >
89
+ {chevron}
90
+ {allOpen ? "Collapse all" : "Expand all"}
91
+ </ButtonBase>
92
+ </span>
93
+ </Tooltip>
94
+ );
95
+ }
96
+
97
+ /**
98
+ * A section's Expand / Collapse and the command it sends its rows. Always in
99
+ * place on a page section, so the header never moves; disabled, with why, where
100
+ * no row has anything to open.
101
+ */
102
+ export function useSectionExpand({
103
+ noun,
104
+ disabledReason,
105
+ }: {
106
+ noun: readonly [string, string];
107
+ /** Set when no row in the section can open. */
108
+ disabledReason?: string;
109
+ }) {
110
+ const [command, setCommand] = useState<SectionOpenCommand | undefined>(
111
+ undefined,
112
+ );
113
+ const allOpen = command?.open ?? false;
114
+ const action = (
115
+ <SectionExpandButton
116
+ allOpen={allOpen}
117
+ onToggle={() =>
118
+ setCommand({ open: !allOpen, n: (command?.n ?? 0) + 1 })
119
+ }
120
+ noun={noun}
121
+ disabledReason={disabledReason}
122
+ />
123
+ );
124
+ return { command, action };
125
+ }
@@ -0,0 +1,130 @@
1
+ // Copyright (c) Credible Data Inc.
2
+ // SPDX-License-Identifier: MIT
3
+
4
+ import { describe, expect, it } from "bun:test";
5
+ import {
6
+ extractSourceAccess,
7
+ filteredEmptyCaption,
8
+ isRestricted,
9
+ isRowFiltered,
10
+ refusalMessage,
11
+ restrictedToWords,
12
+ } from "./sourceAccess";
13
+
14
+ const gate = (...authorize: string[]) => ({ authorize, accessFilter: [] });
15
+
16
+ describe("isRestricted", () => {
17
+ it('reads the sentinels element-wise: only an all-"true" list is unlocked', () => {
18
+ expect(isRestricted(gate())).toBe(false);
19
+ expect(isRestricted(gate("true"))).toBe(false);
20
+ expect(isRestricted(gate("true", "'finance' in $GROUPS"))).toBe(true);
21
+ expect(isRestricted(gate("false"))).toBe(true);
22
+ });
23
+ });
24
+
25
+ describe("isRowFiltered", () => {
26
+ it("is any access filter at all", () => {
27
+ expect(isRowFiltered({ authorize: [], accessFilter: [] })).toBe(false);
28
+ expect(
29
+ isRowFiltered({ authorize: [], accessFilter: ["region in $GROUPS"] }),
30
+ ).toBe(true);
31
+ });
32
+ });
33
+
34
+ describe("restrictedToWords", () => {
35
+ it("names the groups a membership rule admits", () => {
36
+ expect(restrictedToWords(gate("'finance' in $GROUPS"))).toBe(
37
+ "members of finance",
38
+ );
39
+ expect(restrictedToWords(gate(`"hr" in $GROUPS`))).toBe("members of hr");
40
+ expect(
41
+ restrictedToWords(
42
+ gate("'a' in $GROUPS or 'b' in $GROUPS or 'c' in $GROUPS"),
43
+ ),
44
+ ).toBe("members of a, b or c");
45
+ expect(restrictedToWords(gate("'a' in $GROUPS and 'b' in $GROUPS"))).toBe(
46
+ "members of all of a, b",
47
+ );
48
+ });
49
+
50
+ it("says no one for the false sentinel, and never guesses at another given", () => {
51
+ expect(restrictedToWords(gate("false"))).toBe("no one");
52
+ expect(restrictedToWords(gate("$ROLE = 'analyst'"))).toBe(
53
+ "readers its access rule admits",
54
+ );
55
+ });
56
+
57
+ it("joins several rules, which all apply, and skips the true sentinel", () => {
58
+ expect(
59
+ restrictedToWords(
60
+ gate("true", "'finance' in $GROUPS", "'eu' in $GROUPS"),
61
+ ),
62
+ ).toBe("members of finance, and members of eu");
63
+ });
64
+ });
65
+
66
+ describe("refusalMessage", () => {
67
+ it("says the reader can't access the source, the rule in words, and the way out", () => {
68
+ expect(refusalMessage("payroll", gate("'finance' in $GROUPS"))).toBe(
69
+ "You can't access payroll. It is restricted to members of finance; ask an administrator of this package for access.",
70
+ );
71
+ });
72
+ });
73
+
74
+ describe("extractSourceAccess", () => {
75
+ it("ignores a body with no sources and malformed entries", () => {
76
+ expect(extractSourceAccess({}).size).toBe(0);
77
+ expect(
78
+ extractSourceAccess({
79
+ sources: [
80
+ null,
81
+ { authorize: ["x"] },
82
+ { name: "a", authorize: [1, ""] },
83
+ ],
84
+ }).size,
85
+ ).toBe(0);
86
+ });
87
+ });
88
+
89
+ describe("a refusal on a source with no rule this page knows", () => {
90
+ it("still says the reader can't access it, with the way out", () => {
91
+ expect(
92
+ refusalMessage("orders", { authorize: [], accessFilter: [] }),
93
+ ).toBe(
94
+ "You can't access orders. Ask an administrator of this package for access.",
95
+ );
96
+ expect(
97
+ refusalMessage(undefined, { authorize: [], accessFilter: [] }),
98
+ ).toBe(
99
+ "You don't have access to run this. Ask an administrator of this package for access.",
100
+ );
101
+ });
102
+ });
103
+
104
+ describe("filteredEmptyCaption", () => {
105
+ const empty = JSON.stringify({
106
+ data: { kind: "array_cell", array_value: [] },
107
+ });
108
+ const oneRow = JSON.stringify({
109
+ data: {
110
+ kind: "array_cell",
111
+ array_value: [{ kind: "record_cell", record_value: [] }],
112
+ },
113
+ });
114
+ const filtered = { authorize: [], accessFilter: ["region in $GROUPS"] };
115
+
116
+ it("explains an empty result on a row-filtered source", () => {
117
+ expect(filteredEmptyCaption(filtered, empty)).toBe(
118
+ "Filtered to your rows: this source shows each reader only the rows they're allowed to see.",
119
+ );
120
+ });
121
+
122
+ it("says nothing for rows, for an unfiltered source, or for no result", () => {
123
+ expect(filteredEmptyCaption(filtered, oneRow)).toBeUndefined();
124
+ expect(
125
+ filteredEmptyCaption({ authorize: [], accessFilter: [] }, empty),
126
+ ).toBeUndefined();
127
+ expect(filteredEmptyCaption(filtered, undefined)).toBeUndefined();
128
+ expect(filteredEmptyCaption(filtered, "not json")).toBeUndefined();
129
+ });
130
+ });