@malloy-publisher/sdk 0.12.1 → 0.12.3

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 (208) hide show
  1. package/README.md +79 -6
  2. package/dist/{RenderedResult-DrNhQ2_9.cjs.js → RenderedResult-C2arX5Zz.cjs.js} +1 -1
  3. package/dist/{RenderedResult-AyM-RQaA.es.js → RenderedResult-DqPvGZgL.es.js} +2 -2
  4. package/dist/ServerProvider-CqL6xzta.cjs.js +1 -0
  5. package/dist/{ServerProvider-a9Ki0QXO.es.js → ServerProvider-DRbZ6tLP.es.js} +1213 -1187
  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 +43 -13
  9. package/dist/client/index.cjs.js +1 -1
  10. package/dist/client/index.es.js +28 -27
  11. package/dist/components/Model/ExplorerPage.d.ts +9 -0
  12. package/dist/components/Model/Model.d.ts +27 -11
  13. package/dist/components/ModelViewer/AccessChips.d.ts +34 -0
  14. package/dist/components/ModelViewer/EmptyRow.d.ts +23 -0
  15. package/dist/components/ModelViewer/Facts.d.ts +15 -0
  16. package/dist/components/ModelViewer/FieldGroup.d.ts +31 -0
  17. package/dist/components/ModelViewer/FieldRow.d.ts +69 -0
  18. package/dist/components/ModelViewer/GivenFacts.d.ts +21 -0
  19. package/dist/components/ModelViewer/HeaderBar.d.ts +75 -0
  20. package/dist/components/ModelViewer/InlineDoc.d.ts +13 -0
  21. package/dist/components/ModelViewer/ModelGivensSection.d.ts +32 -0
  22. package/dist/components/ModelViewer/ModelSection.d.ts +21 -0
  23. package/dist/components/ModelViewer/ModelViewer.d.ts +91 -0
  24. package/dist/components/ModelViewer/QueriesGroup.d.ts +15 -0
  25. package/dist/components/ModelViewer/RowGlyph.d.ts +27 -0
  26. package/dist/components/ModelViewer/RunResult.d.ts +46 -0
  27. package/dist/components/ModelViewer/SampleValues.d.ts +20 -0
  28. package/dist/components/ModelViewer/SchemaJoin.d.ts +51 -0
  29. package/dist/components/ModelViewer/SchemaView.d.ts +52 -0
  30. package/dist/components/ModelViewer/SegmentIcons.d.ts +70 -0
  31. package/dist/components/ModelViewer/SourcesDropdown.d.ts +53 -0
  32. package/dist/components/ModelViewer/SourcesNav.d.ts +25 -0
  33. package/dist/components/ModelViewer/StatusPill.d.ts +56 -0
  34. package/dist/components/ModelViewer/ValueChip.d.ts +17 -0
  35. package/dist/components/ModelViewer/ViewRow.d.ts +36 -0
  36. package/dist/components/ModelViewer/clickableBox.d.ts +29 -0
  37. package/dist/components/ModelViewer/codeDisplay.d.ts +44 -0
  38. package/dist/components/ModelViewer/docAnnotations.d.ts +90 -0
  39. package/dist/components/ModelViewer/explorerModel.d.ts +12 -0
  40. package/dist/components/ModelViewer/extensions.d.ts +94 -0
  41. package/dist/components/ModelViewer/fieldCode.d.ts +74 -0
  42. package/dist/components/ModelViewer/fieldEntities.d.ts +45 -0
  43. package/dist/components/ModelViewer/fieldExpansion.d.ts +41 -0
  44. package/dist/components/ModelViewer/givenUsage.d.ts +71 -0
  45. package/dist/components/ModelViewer/headerCard.d.ts +31 -0
  46. package/dist/components/ModelViewer/httpStatus.d.ts +4 -0
  47. package/dist/components/ModelViewer/icons.d.ts +31 -0
  48. package/dist/components/ModelViewer/index.d.ts +9 -0
  49. package/dist/components/ModelViewer/joinAccess.d.ts +52 -0
  50. package/dist/components/ModelViewer/malloyRunText.d.ts +22 -0
  51. package/dist/components/ModelViewer/malloyText.d.ts +21 -0
  52. package/dist/components/ModelViewer/modelGivens.d.ts +61 -0
  53. package/dist/components/ModelViewer/modelGivensContext.d.ts +9 -0
  54. package/dist/components/ModelViewer/modelHeaderPresentation.d.ts +28 -0
  55. package/dist/components/ModelViewer/modelTextDeclarations.d.ts +32 -0
  56. package/dist/components/ModelViewer/modelTextParse.d.ts +27 -0
  57. package/dist/components/ModelViewer/namedQueryCode.d.ts +12 -0
  58. package/dist/components/ModelViewer/offSurface.d.ts +54 -0
  59. package/dist/components/ModelViewer/rowLayers.d.ts +30 -0
  60. package/dist/components/ModelViewer/runGate.d.ts +49 -0
  61. package/dist/components/ModelViewer/schemaModel.d.ts +109 -0
  62. package/dist/components/ModelViewer/sectionOpenCommand.d.ts +45 -0
  63. package/dist/components/ModelViewer/sourceAccess.d.ts +67 -0
  64. package/dist/components/ModelViewer/sourceLineage.d.ts +14 -0
  65. package/dist/components/ModelViewer/sourcePicker.d.ts +66 -0
  66. package/dist/components/ModelViewer/surface.d.ts +47 -0
  67. package/dist/components/ModelViewer/text.d.ts +6 -0
  68. package/dist/components/ModelViewer/theme.d.ts +63 -0
  69. package/dist/components/ModelViewer/tokens.d.ts +52 -0
  70. package/dist/components/ModelViewer/ui.d.ts +48 -0
  71. package/dist/components/ModelViewer/useDimensionSamples.d.ts +76 -0
  72. package/dist/components/ModelViewer/useModelSources.d.ts +92 -0
  73. package/dist/components/ModelViewer/useRunQuery.d.ts +115 -0
  74. package/dist/components/ReportBuilder/loadMalloy.d.ts +4 -0
  75. package/dist/components/ServerProvider.d.ts +15 -1
  76. package/dist/components/filter/utils.d.ts +1 -1
  77. package/dist/components/given/GivenInput.d.ts +7 -1
  78. package/dist/components/given/GivensPanel.d.ts +3 -1
  79. package/dist/components/given/filterSummary.d.ts +6 -0
  80. package/dist/components/given/useGivenUrlParams.d.ts +11 -0
  81. package/dist/components/index.d.ts +2 -1
  82. package/dist/components/modelPage.d.ts +36 -0
  83. package/dist/hooks/useDimensionalFilterRangeData.d.ts +9 -0
  84. package/dist/hooks/useSuggestOptions.d.ts +26 -2
  85. package/dist/index.cjs.js +47 -19
  86. package/dist/index.es.js +14281 -9879
  87. package/dist/useCompiledDocument--Z7vKZL5.cjs.js +143 -0
  88. package/dist/{useCompiledDocument-Utj2u8CG.es.js → useCompiledDocument-BnT2QpG0.es.js} +6975 -6893
  89. package/dist/utils/filterCondition.d.ts +14 -0
  90. package/dist/utils/malloyLiteral.d.ts +20 -1
  91. package/package.json +2 -2
  92. package/src/components/Model/ExplorerPage.tsx +269 -0
  93. package/src/components/Model/Model.tsx +66 -250
  94. package/src/components/Model/ModelExplorer.spec.tsx +64 -1
  95. package/src/components/ModelViewer/AccessChips.tsx +149 -0
  96. package/src/components/ModelViewer/EmptyRow.tsx +71 -0
  97. package/src/components/ModelViewer/Facts.tsx +46 -0
  98. package/src/components/ModelViewer/FieldGroup.tsx +137 -0
  99. package/src/components/ModelViewer/FieldRow.tsx +566 -0
  100. package/src/components/ModelViewer/GivenFacts.tsx +89 -0
  101. package/src/components/ModelViewer/HeaderBar.tsx +362 -0
  102. package/src/components/ModelViewer/InlineDoc.tsx +50 -0
  103. package/src/components/ModelViewer/ModelGivensSection.tsx +142 -0
  104. package/src/components/ModelViewer/ModelSection.tsx +98 -0
  105. package/src/components/ModelViewer/ModelViewer.spec.tsx +937 -0
  106. package/src/components/ModelViewer/ModelViewer.tsx +777 -0
  107. package/src/components/ModelViewer/QueriesGroup.tsx +107 -0
  108. package/src/components/ModelViewer/RowGlyph.tsx +138 -0
  109. package/src/components/ModelViewer/RunResult.tsx +298 -0
  110. package/src/components/ModelViewer/SampleValues.tsx +97 -0
  111. package/src/components/ModelViewer/SchemaJoin.tsx +258 -0
  112. package/src/components/ModelViewer/SchemaView.tsx +222 -0
  113. package/src/components/ModelViewer/SegmentIcons.tsx +129 -0
  114. package/src/components/ModelViewer/SourcesDropdown.tsx +265 -0
  115. package/src/components/ModelViewer/SourcesNav.tsx +75 -0
  116. package/src/components/ModelViewer/StatusPill.tsx +145 -0
  117. package/src/components/ModelViewer/ValueChip.tsx +39 -0
  118. package/src/components/ModelViewer/ViewRow.tsx +274 -0
  119. package/src/components/ModelViewer/clickableBox.ts +59 -0
  120. package/src/components/ModelViewer/codeDisplay.spec.ts +176 -0
  121. package/src/components/ModelViewer/codeDisplay.ts +118 -0
  122. package/src/components/ModelViewer/docAnnotations.spec.ts +181 -0
  123. package/src/components/ModelViewer/docAnnotations.ts +244 -0
  124. package/src/components/ModelViewer/docAnnotations.typeDetail.spec.ts +114 -0
  125. package/src/components/ModelViewer/explorerModel.spec.ts +43 -0
  126. package/src/components/ModelViewer/explorerModel.ts +31 -0
  127. package/src/components/ModelViewer/extensions.tsx +112 -0
  128. package/src/components/ModelViewer/fieldCode.spec.ts +168 -0
  129. package/src/components/ModelViewer/fieldCode.ts +118 -0
  130. package/src/components/ModelViewer/fieldEntities.ts +63 -0
  131. package/src/components/ModelViewer/fieldExpansion.spec.ts +116 -0
  132. package/src/components/ModelViewer/fieldExpansion.ts +95 -0
  133. package/src/components/ModelViewer/givenUsage.spec.ts +304 -0
  134. package/src/components/ModelViewer/givenUsage.ts +325 -0
  135. package/src/components/ModelViewer/headerCard.tsx +102 -0
  136. package/src/components/ModelViewer/httpStatus.ts +15 -0
  137. package/src/components/ModelViewer/icons.tsx +67 -0
  138. package/src/components/ModelViewer/index.ts +26 -0
  139. package/src/components/ModelViewer/joinAccess.spec.ts +95 -0
  140. package/src/components/ModelViewer/joinAccess.ts +54 -0
  141. package/src/components/ModelViewer/malloyRunText.spec.ts +48 -0
  142. package/src/components/ModelViewer/malloyRunText.ts +51 -0
  143. package/src/components/ModelViewer/malloyText.spec.ts +47 -0
  144. package/src/components/ModelViewer/malloyText.ts +77 -0
  145. package/src/components/ModelViewer/modelGivens.ts +228 -0
  146. package/src/components/ModelViewer/modelGivensContext.ts +13 -0
  147. package/src/components/ModelViewer/modelHeaderPresentation.spec.ts +31 -0
  148. package/src/components/ModelViewer/modelHeaderPresentation.ts +41 -0
  149. package/src/components/ModelViewer/modelTextDeclarations.spec.ts +336 -0
  150. package/src/components/ModelViewer/modelTextDeclarations.ts +228 -0
  151. package/src/components/ModelViewer/modelTextParse.ts +112 -0
  152. package/src/components/ModelViewer/namedQueryCode.spec.ts +58 -0
  153. package/src/components/ModelViewer/namedQueryCode.ts +26 -0
  154. package/src/components/ModelViewer/offSurface.tsx +124 -0
  155. package/src/components/ModelViewer/rowLayers.tsx +104 -0
  156. package/src/components/ModelViewer/runGate.spec.ts +219 -0
  157. package/src/components/ModelViewer/runGate.ts +145 -0
  158. package/src/components/ModelViewer/schemaModel.defaultSource.spec.ts +126 -0
  159. package/src/components/ModelViewer/schemaModel.queries.spec.ts +37 -0
  160. package/src/components/ModelViewer/schemaModel.ts +300 -0
  161. package/src/components/ModelViewer/sectionOpenCommand.tsx +125 -0
  162. package/src/components/ModelViewer/sourceAccess.spec.ts +130 -0
  163. package/src/components/ModelViewer/sourceAccess.ts +194 -0
  164. package/src/components/ModelViewer/sourceLineage.spec.ts +73 -0
  165. package/src/components/ModelViewer/sourceLineage.ts +38 -0
  166. package/src/components/ModelViewer/sourcePicker.spec.ts +294 -0
  167. package/src/components/ModelViewer/sourcePicker.ts +162 -0
  168. package/src/components/ModelViewer/surface.ts +51 -0
  169. package/src/components/ModelViewer/text.tsx +33 -0
  170. package/src/components/ModelViewer/theme.spec.ts +38 -0
  171. package/src/components/ModelViewer/theme.ts +58 -0
  172. package/src/components/ModelViewer/tokens.ts +87 -0
  173. package/src/components/ModelViewer/ui.tsx +201 -0
  174. package/src/components/ModelViewer/useDimensionSamples.spec.tsx +139 -0
  175. package/src/components/ModelViewer/useDimensionSamples.ts +220 -0
  176. package/src/components/ModelViewer/useModelSources.spec.ts +110 -0
  177. package/src/components/ModelViewer/useModelSources.ts +238 -0
  178. package/src/components/ModelViewer/useRunQuery.spec.ts +50 -0
  179. package/src/components/ModelViewer/useRunQuery.ts +223 -0
  180. package/src/components/ReportBuilder/emptyStart.spec.ts +8 -0
  181. package/src/components/ReportBuilder/loadMalloy.ts +8 -1
  182. package/src/components/ServerProvider.tsx +27 -3
  183. package/src/components/filter/utils.ts +4 -60
  184. package/src/components/given/FilterButton.tsx +4 -1
  185. package/src/components/given/GivenInput.tsx +8 -0
  186. package/src/components/given/GivensPanel.tsx +6 -1
  187. package/src/components/given/filterSummary.spec.ts +31 -1
  188. package/src/components/given/filterSummary.ts +41 -19
  189. package/src/components/given/useGivenUrlParams.spec.tsx +32 -0
  190. package/src/components/given/useGivenUrlParams.ts +49 -14
  191. package/src/components/index.ts +6 -1
  192. package/src/components/legacy/malloynb/Notebook.spec.tsx +38 -4
  193. package/src/components/legacy/malloynb/NotebookCell.tsx +8 -2
  194. package/src/components/modelPage.spec.ts +79 -0
  195. package/src/components/modelPage.ts +48 -0
  196. package/src/hooks/useDimensionFilters.ts +3 -58
  197. package/src/hooks/useDimensionFiltersQuery.ts +3 -58
  198. package/src/hooks/useDimensionalFilterRangeData.spec.ts +57 -0
  199. package/src/hooks/useDimensionalFilterRangeData.ts +8 -63
  200. package/src/hooks/useSuggestOptions.dom.spec.ts +54 -1
  201. package/src/hooks/useSuggestOptions.spec.ts +71 -0
  202. package/src/hooks/useSuggestOptions.ts +102 -12
  203. package/src/utils/filterCondition.spec.ts +87 -0
  204. package/src/utils/filterCondition.ts +66 -0
  205. package/src/utils/malloyLiteral.spec.ts +53 -1
  206. package/src/utils/malloyLiteral.ts +47 -12
  207. package/dist/ServerProvider-BvD7PYZ7.cjs.js +0 -1
  208. package/dist/useCompiledDocument-CRhFBKv_.cjs.js +0 -142
@@ -0,0 +1,274 @@
1
+ // Copyright (c) Credible Data Inc.
2
+ // SPDX-License-Identifier: MIT
3
+
4
+ import { Box, CircularProgress, Collapse, Tooltip } from "@mui/material";
5
+ import { useContext, useMemo, useState } from "react";
6
+ import { viewDeclaration } from "./codeDisplay";
7
+ import { tagNames } from "./docAnnotations";
8
+ import { EmptyRow } from "./EmptyRow";
9
+ import { useModelViewerExtensions } from "./extensions";
10
+ import type { FieldCodeLookup } from "./fieldCode";
11
+ import { hasDefinitionToShow } from "./fieldExpansion";
12
+ import { RowLine } from "./FieldRow";
13
+ import { GivenFacts, GivenPill } from "./GivenFacts";
14
+ import { viewRunQuery } from "./malloyRunText";
15
+ import { RowGlyph } from "./RowGlyph";
16
+ import { RunResult, type ShownRun } from "./RunResult";
17
+ import type { ExplorerField } from "./schemaModel";
18
+ import { StatusPill } from "./StatusPill";
19
+ import { MONO_FONT_FAMILY } from "./theme";
20
+ import { LoadErrorAlert, QueryCode } from "./ui";
21
+ import {
22
+ givensOfRun,
23
+ runQueryKey,
24
+ runReading,
25
+ type RunContext,
26
+ } from "./useRunQuery";
27
+ import { useServer } from "../ServerProvider";
28
+ import { givensReadBy } from "./givenUsage";
29
+ import type { GivenInfo } from "./modelGivens";
30
+ import { ModelGivensContext } from "./modelGivensContext";
31
+ import { useSectionOpen } from "./sectionOpenCommand";
32
+ import { RowLayerSwitch, useRowLayer, type RowLayer } from "./rowLayers";
33
+
34
+ /**
35
+ * A source's view, or a model's named query, as a row of the page — the same
36
+ * line a measure or dimension has (RowLine), opened and closed the same way. Open,
37
+ * it shows its result card under the line, a notebook cell's shape: the Result |
38
+ * Code switch (and a host's actions) and the result, drawn by RunResult.
39
+ *
40
+ * <p>It runs when first opened, on its Result, and never on render: browsing a
41
+ * source costs nothing. The card mounts on first open and stays mounted while
42
+ * closed, so reopening shows the result already drawn; the result itself is the
43
+ * viewer's cache entry (runQueryOptions, kept for the page), so a remount
44
+ * (switching source and back) reopens it without a second request.
45
+ *
46
+ * <p>A row with nowhere to run (no `run`) opens on its Code, Result disabled.
47
+ */
48
+ export function ViewRow({
49
+ field,
50
+ modelPath,
51
+ sourceName,
52
+ fieldCode,
53
+ run,
54
+ runQuery,
55
+ runGivens,
56
+ runGivensUnknown,
57
+ }: {
58
+ field: ExplorerField;
59
+ modelPath: string;
60
+ /** The source the view belongs to; for a named query, the source it runs
61
+ * against when known (for its required filters), else "". */
62
+ sourceName: string;
63
+ /** The view's Malloy, when the source's definitions are available. */
64
+ fieldCode?: FieldCodeLookup;
65
+ /** Where to run it; absent where it can't be run. */
66
+ run?: RunContext;
67
+ /** A named query's `run:` text; a view's is built from its source and name.
68
+ * Its code is then the whole `query:` declaration, shown as written. */
69
+ runQuery?: string;
70
+ /** The givens a run reads, where its source can't say (see RunResult). */
71
+ runGivens?: ReadonlyArray<GivenInfo>;
72
+ /** Those of `runGivens` the page can't tie to the run either way. */
73
+ runGivensUnknown?: ReadonlySet<string>;
74
+ }) {
75
+ const query = runQuery ?? viewRunQuery(sourceName, field.name);
76
+ // What this row sends: only the given values of the givens it reads.
77
+ const readGivens = runGivens ?? (run && givensOfRun(run, sourceName));
78
+ const sent = useMemo(
79
+ () => run && runReading(run, readGivens),
80
+ [run, readGivens],
81
+ );
82
+ const noun = runQuery ? "query" : "view";
83
+ // Open or shut by the reader, and by its section's Expand / Collapse.
84
+ const [open, setOpen] = useSectionOpen();
85
+ const [shownRun, setShownRun] = useState<ShownRun | undefined>(undefined);
86
+ const showDefinition = hasDefinitionToShow(fieldCode);
87
+ const modelGivens = useContext(ModelGivensContext);
88
+ const { renderRunActions } = useModelViewerExtensions();
89
+ const { server } = useServer();
90
+ const givensRead = useMemo(
91
+ () => givensReadBy(fieldCode?.code, modelGivens),
92
+ [fieldCode?.code, modelGivens],
93
+ );
94
+ // Its tags as the names on its chips (`line_chart`), and the tags in full for
95
+ // their hover — only where the chips left something out. Where no tag names
96
+ // anything (`# size=lg`, `# -bar_chart`), the chips are the tags as written,
97
+ // so a tagged view never shows no tag at all.
98
+ const { chartNames, tagsInFull } = useMemo(() => {
99
+ const tags = field.tags ?? [];
100
+ const named = tagNames(tags);
101
+ const names = named.length > 0 ? named : tags;
102
+ return {
103
+ chartNames: names,
104
+ tagsInFull:
105
+ tags.join(" ") === names.join(" ")
106
+ ? undefined
107
+ : tags.map((tag) => `# ${tag}`).join("\n"),
108
+ };
109
+ }, [field.tags]);
110
+ // One card at a time: its result, its Malloy, or the givens it reads. Result
111
+ // and Code keep their places even where one can't be shown (disabled, with
112
+ // why), so the switch doesn't change shape between rows.
113
+ const available: RowLayer[] = [
114
+ "result",
115
+ "code",
116
+ ...(givensRead.length > 0 ? (["givens"] as const) : []),
117
+ ];
118
+ const { layers, layer, setLayer } = useRowLayer(
119
+ available,
120
+ run ? "result" : "code",
121
+ );
122
+ const view = layer ?? "code";
123
+
124
+ // Called only while Code or Givens is shown, so a card on its result never
125
+ // runs the declaration regexes.
126
+ const renderCode = () =>
127
+ view === "givens" ? (
128
+ <GivenFacts givens={givensRead} />
129
+ ) : fieldCode?.loading ? (
130
+ <CircularProgress size={12} sx={{ color: "text.secondary" }} />
131
+ ) : fieldCode?.code ? (
132
+ <QueryCode
133
+ testId="model-viewer-definition"
134
+ code={
135
+ runQuery
136
+ ? fieldCode.code
137
+ : viewDeclaration(field.name, fieldCode.code)
138
+ }
139
+ />
140
+ ) : fieldCode?.error ? (
141
+ <LoadErrorAlert message="Couldn't load this model's code right now." />
142
+ ) : (
143
+ <EmptyRow message={`No Malloy code to show for this ${noun}.`} />
144
+ );
145
+
146
+ return (
147
+ <Box
148
+ data-testid="model-viewer-view-row"
149
+ data-name={field.name}
150
+ sx={open ? { pb: 1.5 } : undefined}
151
+ >
152
+ <RowLine
153
+ glyph={<RowGlyph kind="view" />}
154
+ name={field.name}
155
+ doc={field.doc}
156
+ open={open}
157
+ expandable
158
+ onToggle={() => setOpen((o) => !o)}
159
+ // Open, its Result | Code (| Givens) and a host's actions sit on the
160
+ // row's own line, right of its name and description, as a notebook
161
+ // cell's sit over its result.
162
+ trailing={
163
+ open && (
164
+ <Box
165
+ sx={{ display: "flex", alignItems: "center", gap: "2px" }}
166
+ >
167
+ <RowLayerSwitch
168
+ aria-label={`Show for ${field.name}`}
169
+ layers={layers}
170
+ value={view}
171
+ onChange={setLayer}
172
+ disabledReasons={{
173
+ result: run
174
+ ? undefined
175
+ : `This ${noun} can't be run here`,
176
+ code: showDefinition
177
+ ? undefined
178
+ : `No Malloy code to show for this ${noun}`,
179
+ }}
180
+ />
181
+ {sent &&
182
+ renderRunActions?.({
183
+ kind: runQuery ? "query" : "view",
184
+ modelPath,
185
+ sourceName: runQuery ? "" : sourceName,
186
+ name: field.name,
187
+ query,
188
+ givens: sent.givenValues,
189
+ queryKey: runQueryKey(
190
+ server,
191
+ sent,
192
+ modelPath,
193
+ query,
194
+ ),
195
+ shown: shownRun,
196
+ })}
197
+ </Box>
198
+ )
199
+ }
200
+ // What it is (its chart type, its given) after its name. Not stacked:
201
+ // the name keeps its width and the chips wrap under it, so no chip
202
+ // ever cuts the name to an ellipsis or off the line.
203
+ descriptors={
204
+ <>
205
+ {chartNames.map((name) => {
206
+ // How the view presents is part of what it is; a token from the file.
207
+ const chip = (
208
+ <StatusPill
209
+ key={name}
210
+ voice="token"
211
+ tone="quiet"
212
+ sx={{ alignSelf: "center" }}
213
+ >
214
+ {name}
215
+ </StatusPill>
216
+ );
217
+ // Its parameters are on its Code; where the chip left them out,
218
+ // its hover shows the tag in full, for a reader who wants it
219
+ // without opening the row. Its accessible name is that text too.
220
+ return tagsInFull ? (
221
+ <Tooltip
222
+ key={name}
223
+ title={tagsInFull}
224
+ slotProps={{
225
+ tooltip: {
226
+ sx: {
227
+ whiteSpace: "pre-line",
228
+ fontFamily: MONO_FONT_FAMILY,
229
+ },
230
+ },
231
+ }}
232
+ >
233
+ {chip}
234
+ </Tooltip>
235
+ ) : (
236
+ chip
237
+ );
238
+ })}
239
+ <GivenPill givens={givensRead} />
240
+ </>
241
+ }
242
+ />
243
+ <Collapse in={open} timeout="auto" mountOnEnter>
244
+ {/* The result in the app's quiet card, as a code block or a dashboard tile
245
+ frames its content; under the name on a wide page, the whole column at
246
+ phone width. */}
247
+ <Box
248
+ data-testid="model-viewer-view-card"
249
+ sx={{ mx: "10px", mt: 1, minWidth: 0 }}
250
+ >
251
+ {/* At phone width the result takes the column, and a table wider than
252
+ it scrolls rather than being cut off at the edge */}
253
+ <Box sx={{ minWidth: 0, overflowX: "auto" }}>
254
+ {sent ? (
255
+ <RunResult
256
+ run={sent}
257
+ modelPath={modelPath}
258
+ query={query}
259
+ sourceName={sourceName || undefined}
260
+ givens={runGivens}
261
+ givensUnknown={runGivensUnknown}
262
+ mode={view === "result" ? "result" : "code"}
263
+ renderCode={renderCode}
264
+ onShownChange={setShownRun}
265
+ />
266
+ ) : (
267
+ renderCode()
268
+ )}
269
+ </Box>
270
+ </Box>
271
+ </Collapse>
272
+ </Box>
273
+ );
274
+ }
@@ -0,0 +1,59 @@
1
+ // Copyright (c) Credible Data Inc.
2
+ // SPDX-License-Identifier: MIT
3
+
4
+ /**
5
+ * Button semantics and a focus ring for a control rendered as a plain `Box`.
6
+ *
7
+ * A `Box` with only `onClick` is not in the tab order, is not exposed to
8
+ * assistive tech as a control, and gets no focus indicator from MUI — and a
9
+ * `Tooltip` around it surfaces its label on hover only, since a non-focusable
10
+ * child never receives keyboard focus. Anywhere we reach for a clickable `Box`
11
+ * instead of a `Button`/`ListItemButton` we owe it these, so they are defined
12
+ * once here rather than hand-rolled per site.
13
+ *
14
+ * Prefer a real MUI button component when the styling allows it; use this when
15
+ * it does not.
16
+ */
17
+ import type { KeyboardEvent, MouseEvent, SyntheticEvent } from "react";
18
+
19
+ /**
20
+ * `role`, `tabIndex`, accessible name, and Enter/Space activation for a
21
+ * clickable `Box`. Pair with {@link focusRingSx} so the focus stop is visible.
22
+ *
23
+ * `onActivate` receives the originating event so a control that anchors a popup
24
+ * can read `currentTarget`; handlers that don't need it can ignore it.
25
+ *
26
+ * Pass `undefined` for `label` ONLY when the element's own text content names it
27
+ * — a `role="button"` falls back to its contents, so an explicit label there
28
+ * would just be a second, drift-prone copy of the text on screen. A control
29
+ * whose content is an icon, or arbitrary nodes that may not include text, needs
30
+ * the explicit label.
31
+ */
32
+ export function clickableBoxProps(
33
+ label: string | undefined,
34
+ onActivate?: (e: SyntheticEvent<HTMLElement>) => void,
35
+ ) {
36
+ return {
37
+ role: "button",
38
+ tabIndex: 0,
39
+ ...(label === undefined ? {} : { "aria-label": label }),
40
+ onClick: (e: MouseEvent<HTMLElement>) => onActivate?.(e),
41
+ onKeyDown: (e: KeyboardEvent<HTMLElement>) => {
42
+ // Enter/Space are what a real <button> would honor; preventDefault
43
+ // stops Space from also scrolling the page.
44
+ if (e.key === "Enter" || e.key === " ") {
45
+ e.preventDefault();
46
+ onActivate?.(e);
47
+ }
48
+ },
49
+ } as const;
50
+ }
51
+
52
+ /** Focus ring for a clickable `Box` — MUI draws none, so it needs one explicitly. */
53
+ export const focusRingSx = {
54
+ "&:focus-visible": {
55
+ outline: "2px solid",
56
+ outlineColor: "primary.main",
57
+ outlineOffset: "-2px",
58
+ },
59
+ } as const;
@@ -0,0 +1,176 @@
1
+ // Copyright (c) Credible Data Inc.
2
+ // SPDX-License-Identifier: MIT
3
+
4
+ import { describe, expect, it } from "bun:test";
5
+ import {
6
+ stripDefinitionWrapper,
7
+ stripDocAnnotations,
8
+ viewDeclaration,
9
+ } from "./codeDisplay";
10
+
11
+ describe("stripDocAnnotations", () => {
12
+ it("drops a `#(doc)` line, leaving the definition", () => {
13
+ const code = [
14
+ "#(doc) Year the recall was reported (truncated to Jan 1)",
15
+ " recall_year is `Report Received Date`.year",
16
+ ].join("\n");
17
+ expect(stripDocAnnotations(code)).toBe(
18
+ "recall_year is `Report Received Date`.year",
19
+ );
20
+ });
21
+
22
+ it('drops consecutive `#"` doc lines', () => {
23
+ const code = [
24
+ '#" First paragraph.',
25
+ '#" Second paragraph.',
26
+ "total is sum(x)",
27
+ ].join("\n");
28
+ expect(stripDocAnnotations(code)).toBe("total is sum(x)");
29
+ });
30
+
31
+ it("keeps non-doc annotations — they say how the field behaves", () => {
32
+ const code = ["#(index)", "state is upper(state_code)"].join("\n");
33
+ expect(stripDocAnnotations(code)).toBe(code);
34
+ });
35
+
36
+ it("leaves an undocumented definition untouched", () => {
37
+ expect(stripDocAnnotations("total is sum(x)")).toBe("total is sum(x)");
38
+ });
39
+
40
+ it("drops docs that follow another annotation — both orders are legal Malloy", () => {
41
+ // A `#(index)` first must not end the scan, or the docstring stays in the
42
+ // code block as well as in the hover.
43
+ const code = [
44
+ "#(index)",
45
+ '#" What the field means.',
46
+ "state is upper(state_code)",
47
+ ];
48
+ expect(stripDocAnnotations(code.join("\n"))).toBe(
49
+ ["#(index)", "state is upper(state_code)"].join("\n"),
50
+ );
51
+ });
52
+
53
+ it("keeps the surviving annotations in their original order", () => {
54
+ const code = ["#(doc) Prose.", "#(index)", "# bar_chart", "state is x"];
55
+ expect(stripDocAnnotations(code.join("\n"))).toBe(
56
+ ["#(index)", "# bar_chart", "state is x"].join("\n"),
57
+ );
58
+ });
59
+ });
60
+
61
+ describe("stripDefinitionWrapper", () => {
62
+ it("keeps `name is …` on an expression, so it still reads as a definition", () => {
63
+ // Stripping it left a bare identifier under the field's own name, which
64
+ // reads as a stray reference rather than "this field is defined as that".
65
+ expect(
66
+ stripDefinitionWrapper("category_grain", "category_grain is category"),
67
+ ).toBe("category_grain is category");
68
+ expect(
69
+ stripDefinitionWrapper("airport_count", "airport_count is count()"),
70
+ ).toBe("airport_count is count()");
71
+ });
72
+
73
+ it("keeps the leading kind keyword on an expression too", () => {
74
+ expect(
75
+ stripDefinitionWrapper(
76
+ "airport_count",
77
+ "measure: airport_count is count()",
78
+ ),
79
+ ).toBe("measure: airport_count is count()");
80
+ });
81
+
82
+ it("unwraps a view block's outer braces and dedents the body", () => {
83
+ // A block IS worth unwrapping: the braces and their indent are pure
84
+ // wrapper, and `group_by:` / `aggregate:` describe themselves.
85
+ const code = [
86
+ "by_state is {",
87
+ " where: state != null",
88
+ " group_by: state",
89
+ " aggregate: airport_count",
90
+ " }",
91
+ ].join("\n");
92
+ expect(stripDefinitionWrapper("by_state", code)).toBe(
93
+ [
94
+ "where: state != null",
95
+ "group_by: state",
96
+ "aggregate: airport_count",
97
+ ].join("\n"),
98
+ );
99
+ });
100
+
101
+ it("unwraps a block even with the kind keyword present", () => {
102
+ expect(
103
+ stripDefinitionWrapper(
104
+ "by_state",
105
+ "view: by_state is {\n group_by: state\n}",
106
+ ),
107
+ ).toBe("group_by: state");
108
+ });
109
+
110
+ it("leaves non-matching slices verbatim (never mangle what it can't parse)", () => {
111
+ expect(
112
+ stripDefinitionWrapper("origin_code", "rename: origin_code is origin"),
113
+ ).toBe("rename: origin_code is origin");
114
+ expect(
115
+ stripDefinitionWrapper("engines", "duckdb.table('data/x.parquet')"),
116
+ ).toBe("duckdb.table('data/x.parquet')");
117
+ });
118
+
119
+ it("escapes regex metacharacters in field names", () => {
120
+ // `a+b` must not be treated as a regex; the wrapper is recognized (and
121
+ // kept, since the body is an expression) rather than mangled.
122
+ expect(stripDefinitionWrapper("a+b", "a+b is 1")).toBe("a+b is 1");
123
+ expect(stripDefinitionWrapper("a+b", "a+b is {\n group_by: x\n}")).toBe(
124
+ "group_by: x",
125
+ );
126
+ });
127
+ });
128
+
129
+ describe("viewDeclaration", () => {
130
+ it("shows a view's whole declaration, putting back the keyword a stored slice starts without", () => {
131
+ const code =
132
+ "#(doc) Recall count trend over time by year\n# line_chart\nby_year is {\n group_by: recall_year\n aggregate: recall_count\n}";
133
+ expect(viewDeclaration("by_year", code)).toBe(
134
+ "# line_chart\nview: by_year is {\n group_by: recall_year\n aggregate: recall_count\n}",
135
+ );
136
+ });
137
+
138
+ it("lines the body up under the keyword, however deep the view sat in its file", () => {
139
+ // As stored: cut from inside `source: recalls is … extend {`, so the first line
140
+ // is at column zero and the rest keep their four-space nesting.
141
+ const code = [
142
+ "by_year_manufacturer_line_chart is {",
143
+ " nest: top_manufacturers is {",
144
+ " group_by: Manufacturer",
145
+ " limit: 5",
146
+ " }",
147
+ " }",
148
+ " -> {",
149
+ " # x",
150
+ " group_by: x.recall_year",
151
+ " }",
152
+ ].join("\n");
153
+ expect(viewDeclaration("by_year_manufacturer_line_chart", code)).toBe(
154
+ [
155
+ "view: by_year_manufacturer_line_chart is {",
156
+ " nest: top_manufacturers is {",
157
+ " group_by: Manufacturer",
158
+ " limit: 5",
159
+ " }",
160
+ "}",
161
+ "-> {",
162
+ " # x",
163
+ " group_by: x.recall_year",
164
+ "}",
165
+ ].join("\n"),
166
+ );
167
+ });
168
+
169
+ it("keeps a slice that already carries the keyword, and anything unexpected, as written", () => {
170
+ const withKeyword = "view: by_year is {\n group_by: recall_year\n}";
171
+ expect(viewDeclaration("by_year", withKeyword)).toBe(withKeyword);
172
+ expect(viewDeclaration("by_year", "other_view + { limit: 3 }")).toBe(
173
+ "other_view + { limit: 3 }",
174
+ );
175
+ });
176
+ });
@@ -0,0 +1,118 @@
1
+ // Copyright (c) Credible Data Inc.
2
+ // SPDX-License-Identifier: MIT
3
+
4
+ import { escapeRegExp } from "./malloyText";
5
+
6
+ /**
7
+ * Drop the doc annotations from the head of a stored definition slice.
8
+ *
9
+ * The same text is the row's hover (see DocTooltip), so leaving it in the
10
+ * code block would print the description twice and bury the one thing the
11
+ * expansion exists to show — the expression — under prose. It would also keep
12
+ * the wrapper-strip below from matching, since the slice would not start with
13
+ * `name is`.
14
+ *
15
+ * Doc annotations only: `#(index)`, renderer tags and any other `#` annotation
16
+ * stay, because they are part of how the field behaves rather than a description
17
+ * of it. Both Malloy doc forms are recognized — `#(doc) …` and consecutive `#"`
18
+ * lines.
19
+ *
20
+ * The whole leading annotation run is scanned, not just its first lines: both
21
+ * orders are legal Malloy, so stopping at a `#(index)` would leave the docstring
22
+ * below it in the code block AND in the hover — the double-print this exists to
23
+ * prevent.
24
+ */
25
+ export function stripDocAnnotations(code: string): string {
26
+ const lines = code.replace(/^\n+/, "").split("\n");
27
+ const kept: string[] = [];
28
+ let first = 0;
29
+ while (first < lines.length) {
30
+ const line = lines[first].trim();
31
+ if (!line.startsWith("#")) break;
32
+ if (!line.startsWith('#"') && !line.startsWith("#(doc)"))
33
+ kept.push(lines[first]);
34
+ first += 1;
35
+ }
36
+ return [...kept, ...lines.slice(first)].join("\n").trim();
37
+ }
38
+
39
+ /**
40
+ * Trim the redundant declaration wrapper off a field's stored Malloy
41
+ * definition for display — but only when the body is a BLOCK.
42
+ *
43
+ * `by_state is { … }` shows its dedented body: the braces and their level of
44
+ * indentation are pure wrapper, and `group_by:` / `aggregate:` describe
45
+ * themselves. An EXPRESSION keeps its wrapper, because stripping it throws
46
+ * away the relationship that makes it a definition — `category_grain is
47
+ * category` rendered as a lone `category` reads as a stray field reference,
48
+ * not as "this field is defined as that one".
49
+ *
50
+ * Anything that doesn't match the expected wrapper (multi-statement slices,
51
+ * renames, exotic forms) is shown verbatim rather than mangled.
52
+ */
53
+ export function stripDefinitionWrapper(name: string, code: string): string {
54
+ const raw = stripDocAnnotations(code);
55
+ const escaped = escapeRegExp(name);
56
+ // `measure: airport_count is …` / `view: by_state is …` / bare `x is …`.
57
+ const prefix = new RegExp(
58
+ `^(?:(?:dimension|measure|view)\\s*:\\s*)?${escaped}\\s+is\\s+`,
59
+ );
60
+ const body = raw.replace(prefix, "");
61
+ if (body === raw) return raw; // no wrapper — leave verbatim
62
+
63
+ // Expressions keep `name is …`; only a block body is unwrapped.
64
+ if (!(body.startsWith("{") && body.endsWith("}"))) return raw;
65
+
66
+ const inner = body.slice(1, -1).replace(/^\n/, "").replace(/\s+$/, "");
67
+ // Dedent by the smallest indent of the non-blank lines, so the body sits
68
+ // flush like a top-level block.
69
+ const lines = inner.split("\n");
70
+ const indents = lines
71
+ .filter((l) => l.trim())
72
+ .map((l) => (l.match(/^[ \t]*/) as RegExpMatchArray)[0].length);
73
+ const minIndent = indents.length ? Math.min(...indents) : 0;
74
+ const out = lines
75
+ .map((l) => l.slice(minIndent))
76
+ .join("\n")
77
+ .trim();
78
+ return out || raw;
79
+ }
80
+
81
+ /**
82
+ * A view's whole declaration for display — `view: by_year is { … }`, keyword
83
+ * included, with its tags (`# line_chart`) above it and only the doc text dropped
84
+ * (the row prints that already). A view is read as the thing a model declares, so
85
+ * its Definition shows the declaration rather than just the block's body. The stored
86
+ * slice may start at the name (`by_year is { … }`); the keyword is put back then.
87
+ * Anything that isn't that shape is shown verbatim.
88
+ */
89
+ export function viewDeclaration(name: string, code: string): string {
90
+ const raw = stripDocAnnotations(code);
91
+ const lines = raw.split("\n");
92
+ const firstCode = lines.findIndex((l) => !l.trim().startsWith("#"));
93
+ if (firstCode < 0) return raw;
94
+ const head = lines[firstCode];
95
+ if (/^\s*view\s*:/.test(head))
96
+ return dedentContinuation(lines, firstCode).join("\n");
97
+ const escaped = escapeRegExp(name);
98
+ if (!new RegExp(`^\\s*${escaped}\\s+is\\b`).test(head)) return raw;
99
+ lines[firstCode] = head.replace(/^(\s*)/, "$1view: ");
100
+ return dedentContinuation(lines, firstCode).join("\n");
101
+ }
102
+
103
+ /**
104
+ * A slice cut out of a model file starts at its name, at column zero, while every
105
+ * line after it keeps the indentation it had nested in its `source … extend { }`.
106
+ * Shift the continuation lines left by the shallowest of them — the level of the
107
+ * closing `}` (and of a pipeline's `-> {`), which is where the declaration started —
108
+ * so the body sits one step in from `view:` and the `}` lines up under it.
109
+ */
110
+ function dedentContinuation(lines: string[], first: number): string[] {
111
+ const rest = lines.slice(first + 1).filter((l) => l.trim() !== "");
112
+ if (rest.length === 0) return lines;
113
+ const base = Math.min(...rest.map((l) => l.length - l.trimStart().length));
114
+ if (base === 0) return lines;
115
+ return lines.map((l, i) =>
116
+ i <= first ? l : l.slice(Math.min(base, l.length - l.trimStart().length)),
117
+ );
118
+ }