@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,777 @@
1
+ // Copyright (c) Credible Data Inc.
2
+ // SPDX-License-Identifier: MIT
3
+
4
+ import { Box, Link } from "@mui/material";
5
+ import { useCallback, useMemo, useState, type ReactNode } from "react";
6
+ import { useGivensState } from "../../hooks/useGivensState";
7
+ import { usePublisherTheme } from "../../theme/ThemeContext";
8
+ import { parseResourceUri } from "../../utils/formatting";
9
+ import { Loading } from "../Loading";
10
+ import { ownSourceDoc } from "./docAnnotations";
11
+ import { EmptyRow } from "./EmptyRow";
12
+ import { GivenFacts } from "./GivenFacts";
13
+ import {
14
+ ModelViewerExtensionsContext,
15
+ type ModelViewerExtensions,
16
+ } from "./extensions";
17
+ import {
18
+ requiredFiltersBySource as requiredFiltersOf,
19
+ sourceNameSet,
20
+ } from "./explorerModel";
21
+ import {
22
+ groupEntitiesBySource,
23
+ type EntitiesByField,
24
+ type FieldEntity,
25
+ } from "./fieldEntities";
26
+ import {
27
+ givensDeclaredIn,
28
+ givensInheritedBy,
29
+ scanGivensForSource,
30
+ } from "./givenUsage";
31
+ import { HeaderBar } from "./HeaderBar";
32
+ import { isNotFoundOrForbidden } from "./httpStatus";
33
+ import { joinAccess, type JoinLink } from "./joinAccess";
34
+ import { ModelGivensContext } from "./modelGivensContext";
35
+ import { ModelGivensSection } from "./ModelGivensSection";
36
+ import { ModelSection } from "./ModelSection";
37
+ import { declaredTypesOf, givensRequest, type GivenInfo } from "./modelGivens";
38
+ import { sourceCountLabel } from "./modelHeaderPresentation";
39
+ import { QueriesGroup } from "./QueriesGroup";
40
+ import { SchemaView } from "./SchemaView";
41
+ import {
42
+ fieldCount,
43
+ pickDefaultSource,
44
+ toExplorerQueries,
45
+ toExplorerSource,
46
+ } from "./schemaModel";
47
+ import { accessOf, hasAccessRules, type SourceAccess } from "./sourceAccess";
48
+ import { baseSourceName } from "./sourceLineage";
49
+ import {
50
+ exportOrder,
51
+ orderPickerSources,
52
+ pickerDescription,
53
+ sourceMetaLine,
54
+ } from "./sourcePicker";
55
+ import type { SourceNavItem } from "./SourcesDropdown";
56
+ import { SourcesNav } from "./SourcesNav";
57
+ import { wordList } from "./runGate";
58
+ import { BodyText } from "./text";
59
+ import { CONTENT_COLUMN_SX, FILE_VIEW_TOP_GAP, FLAT_PANE_SX } from "./surface";
60
+ import { MONO_FONT_FAMILY, MONO_FONT_VAR, TEXT_TERTIARY } from "./theme";
61
+ import { describeApiError, LoadErrorAlert, serverMessage } from "./ui";
62
+ import type { QueryRunEvent, RunContext } from "./useRunQuery";
63
+ import { useModelSources } from "./useModelSources";
64
+
65
+ export interface ModelViewerProps {
66
+ /** The model, as `publisher://environments/{env}/packages/{pkg}/models/{path}`
67
+ * (`encodeResourceUri`), with an optional `versionId`. */
68
+ resourceUri: string;
69
+ /**
70
+ * The source on screen, for a host that keeps it (in its address, say). With
71
+ * it the viewer is controlled: picking a source calls `onSourceChange` and
72
+ * shows what the host passes back. A name the model doesn't expose shows a
73
+ * not-found state naming the sources it does.
74
+ */
75
+ sourceName?: string;
76
+ /** Called with the source a reader picks. */
77
+ onSourceChange?: (sourceName: string) => void;
78
+ /** Which source to open on when uncontrolled; the model's default otherwise. */
79
+ initialSourceName?: string;
80
+ /**
81
+ * Read and run the files and sources the package's `index.malloy` hides, for a
82
+ * reader the server lets edit the package; anyone else is refused. A file read
83
+ * this way is marked Private on its header.
84
+ */
85
+ includeHiddenFilesAndSources?: boolean;
86
+ /** Givens the host fills on every query (`$GROUPS`, say): never a reader's input. */
87
+ hostGivenNames?: ReadonlyArray<string>;
88
+ /**
89
+ * Given values from the host, typically its URL's query parameters
90
+ * (`useGivenUrlParams`), so a link to the page opens with them applied. Read
91
+ * as the page loads and whenever they change beneath it; names the model
92
+ * doesn't declare are ignored. Without it the values live in the viewer.
93
+ */
94
+ givens?: Record<string, string>;
95
+ /**
96
+ * The applied values whenever they change, with every given name the model
97
+ * declares (`managed`, so the host knows which parameters to remove), for a
98
+ * host that keeps them in its URL. Called once the model has loaded.
99
+ */
100
+ onGivensChange?: (
101
+ givens: Record<string, string>,
102
+ managed: readonly string[],
103
+ ) => void;
104
+ /** Show the Malloy of a source's access rules beside their words. */
105
+ showAccessRules?: boolean;
106
+ /** The heading level of the source's name: `h1` where the viewer is the page. */
107
+ headingLevel?: "h1" | "h2";
108
+ /** Controls at the right of the source's heading. */
109
+ headerActions?: ReactNode;
110
+ /** A host's chips on the source's status row. */
111
+ renderSourceStatus?: (sourceName: string) => ReactNode;
112
+ /**
113
+ * A host's fuller record of the model's fields (see {@link FieldEntity}):
114
+ * per-field code where the file's text isn't served, inherited columns, join
115
+ * targets and declarations. The viewer reads the model file's text without it.
116
+ */
117
+ entities?: ReadonlyArray<FieldEntity>;
118
+ /** `entities` is still being read: rows hold their code rather than saying there is none. */
119
+ entitiesLoading?: boolean;
120
+ /** `entities` could not be read: a row whose code would come from them says so. */
121
+ entitiesError?: boolean;
122
+ /**
123
+ * A host's descriptions of the columns each source's table passes through
124
+ * (source name → column → text), for a dimension with no `#(doc)` of its
125
+ * own; shown marked as generated.
126
+ */
127
+ columnDescriptions?: ReadonlyMap<string, ReadonlyMap<string, string>>;
128
+ /** Where a join to a source in another model file opens; without it such a join has no arrow. */
129
+ joinHref?: (target: {
130
+ modelPath: string;
131
+ sourceName: string;
132
+ }) => string | undefined;
133
+ /** Labels every run carries (`QueryRequest.queryMetadata`). */
134
+ queryMetadata?: Readonly<Record<string, string>>;
135
+ /** Called once per run that settles. */
136
+ onQueryRun?: (event: QueryRunEvent) => void;
137
+ /** A result larger than this (bytes) is held behind a warning before it renders. */
138
+ maxResultSize?: number;
139
+ /** What a host adds to the rows and runs (see {@link ModelViewerExtensions}). */
140
+ extensions?: ModelViewerExtensions;
141
+ }
142
+
143
+ const NO_ENTITIES: ReadonlyMap<string, EntitiesByField> = new Map();
144
+
145
+ /** A model's display name: its file name without `.malloy`. */
146
+ function modelDisplayName(modelPath: string): string {
147
+ return (modelPath.split("/").pop() ?? modelPath).replace(/\.malloy$/, "");
148
+ }
149
+
150
+ /**
151
+ * Where a givens-only model's givens come from: the compiled model lists the
152
+ * ones it imports beside its own, so the line says which are which.
153
+ */
154
+ function givensOnlyWhere(
155
+ sourceText: string | undefined,
156
+ givens: ReadonlyArray<GivenInfo>,
157
+ ): string {
158
+ const declared = givensDeclaredIn(sourceText, givens);
159
+ const imported = givens.filter((g) => !declared.has(g.name));
160
+ const readsNone = "Nothing on this page reads them.";
161
+ if (imported.length === 0)
162
+ return `Declared here for the models that import this file. ${readsNone}`;
163
+ if (imported.length === givens.length)
164
+ return `Imported from another file, for the models that import this one. ${readsNone}`;
165
+ return `For the models that import this file. ${wordList(
166
+ imported.map((g) => g.name),
167
+ "and",
168
+ )} ${imported.length === 1 ? "comes" : "come"} from a file this one imports; the rest are declared here. ${readsNone}`;
169
+ }
170
+
171
+ /**
172
+ * A Malloy model, read-only: the selected source's givens, views, the model's
173
+ * named queries, and the source's measures, calculations, dimensions and joins,
174
+ * under a header whose "2 sources ▾" pill switches between the model's sources.
175
+ * Every view and named query runs when opened, and a given's picker reads its
176
+ * options when opened, never on render, so browsing costs nothing; a dimension
177
+ * the model tags `#(index)` lists its common values.
178
+ *
179
+ * Nothing here writes a value into Malloy text. A run is a view or a query by
180
+ * name, every name is quoted (`malloyIdentifier`), and given values travel as
181
+ * the request's `givens`, which the server binds.
182
+ */
183
+ export function ModelViewer({
184
+ resourceUri,
185
+ sourceName: controlledSourceName,
186
+ onSourceChange,
187
+ initialSourceName,
188
+ includeHiddenFilesAndSources = false,
189
+ hostGivenNames,
190
+ givens: hostParams,
191
+ onGivensChange,
192
+ showAccessRules = false,
193
+ headingLevel = "h1",
194
+ headerActions,
195
+ renderSourceStatus,
196
+ entities,
197
+ entitiesLoading = false,
198
+ entitiesError = false,
199
+ columnDescriptions,
200
+ joinHref,
201
+ queryMetadata,
202
+ onQueryRun,
203
+ maxResultSize,
204
+ extensions,
205
+ }: ModelViewerProps) {
206
+ const {
207
+ environmentName,
208
+ packageName,
209
+ modelPath = "",
210
+ versionId,
211
+ } = parseResourceUri(resourceUri);
212
+ const monoFont = usePublisherTheme().theme.ui.font.mono;
213
+ const {
214
+ sources: sourceInfos,
215
+ queries: namedQueries,
216
+ sourceText,
217
+ givens: modelGivens,
218
+ access: accessBySource,
219
+ modelDoc,
220
+ hasImports,
221
+ isLoading,
222
+ isError,
223
+ error,
224
+ refetch,
225
+ } = useModelSources(
226
+ environmentName,
227
+ packageName,
228
+ modelPath,
229
+ versionId,
230
+ true,
231
+ includeHiddenFilesAndSources,
232
+ );
233
+
234
+ const hostGivens = useMemo(
235
+ () => new Set(hostGivenNames ?? []),
236
+ [hostGivenNames],
237
+ );
238
+ const givens = useMemo<GivenInfo[]>(
239
+ () => modelGivens.filter((g) => !hostGivens.has(g.name)),
240
+ [modelGivens, hostGivens],
241
+ );
242
+ const sources = useMemo(
243
+ () => sourceInfos.map(toExplorerSource),
244
+ [sourceInfos],
245
+ );
246
+ const queries = useMemo(
247
+ () => toExplorerQueries(namedQueries),
248
+ [namedQueries],
249
+ );
250
+ const sourceNames = useMemo(() => sourceNameSet(sources), [sources]);
251
+ const requiredFiltersBySource = useMemo(
252
+ () => requiredFiltersOf(sourceInfos),
253
+ [sourceInfos],
254
+ );
255
+
256
+ // Given values the reader sets in the Givens section, kept with the model
257
+ // version they were set for: another version may declare different givens.
258
+ // A change takes effect as it is made, and Reset puts every given back to
259
+ // its declared default. A host that keeps them in its URL gets each applied
260
+ // set back, so a link (and Copy link) carries what the page is running with.
261
+ const declaredTypes = useMemo(() => declaredTypesOf(givens), [givens]);
262
+ // Only the names this model declares: the host's other parameters (the
263
+ // source on screen, say) changing must not read as new given values.
264
+ const hostParamsKey = JSON.stringify(hostParams ?? null);
265
+ const declaredParams = useMemo(
266
+ () =>
267
+ hostParams &&
268
+ Object.fromEntries(
269
+ Object.entries(hostParams).filter(([name]) =>
270
+ declaredTypes.has(name),
271
+ ),
272
+ ),
273
+ // eslint-disable-next-line react-hooks/exhaustive-deps -- `hostParams` by value
274
+ [hostParamsKey, declaredTypes],
275
+ );
276
+ // Withheld until the model has loaded: before then nothing is declared, and
277
+ // a report would tell the host to clear every parameter it wrote.
278
+ const loaded = !isLoading && !isError;
279
+ const reportGivens = useCallback(
280
+ (next: Record<string, string>) =>
281
+ onGivensChange?.(next, Array.from(declaredTypes.keys())),
282
+ [onGivensChange, declaredTypes],
283
+ );
284
+ const givensState = useGivensState({
285
+ declaredTypes,
286
+ params: declaredParams,
287
+ onParamsChange: loaded && onGivensChange ? reportGivens : undefined,
288
+ documentKey: `${environmentName}/${packageName}@${versionId ?? ""}/${modelPath}`,
289
+ autorun: true,
290
+ });
291
+ // Only the givens THIS model declares are sent: a value set against an
292
+ // earlier version for a since-removed given must not reach the server.
293
+ const givenValues = useMemo(
294
+ () => givensRequest(givensState.applied, declaredTypes),
295
+ [givensState.applied, declaredTypes],
296
+ );
297
+ // Each source's givens, as its Givens section shows them: what its
298
+ // declaration reads (through what it extends or joins), plus the model-wide
299
+ // ones no source reads. A run gates on the same set. Where the scan can't
300
+ // tell, every given, and the ones it can't tie to the source either way are
301
+ // in `unknownGivensBySource`.
302
+ const { givensBySource, unknownGivensBySource } = useMemo(() => {
303
+ const bySource = new Map<string, GivenInfo[]>();
304
+ const unknown = new Map<string, ReadonlySet<string>>();
305
+ for (const s of sources) {
306
+ const scan = scanGivensForSource(sourceText, s.name, givens);
307
+ bySource.set(s.name, scan.givens);
308
+ if (scan.unknown.size > 0) unknown.set(s.name, scan.unknown);
309
+ }
310
+ return { givensBySource: bySource, unknownGivensBySource: unknown };
311
+ }, [sources, sourceText, givens]);
312
+ const run = useMemo<RunContext>(
313
+ () => ({
314
+ projectName: environmentName,
315
+ packageName,
316
+ versionId,
317
+ givens,
318
+ givensBySource,
319
+ unknownGivensBySource,
320
+ requiredFiltersBySource,
321
+ givenValues,
322
+ accessBySource,
323
+ includeHiddenFilesAndSources,
324
+ queryMetadata,
325
+ onQueryRun,
326
+ maxResultSize,
327
+ }),
328
+ [
329
+ environmentName,
330
+ packageName,
331
+ versionId,
332
+ givens,
333
+ givensBySource,
334
+ unknownGivensBySource,
335
+ requiredFiltersBySource,
336
+ givenValues,
337
+ accessBySource,
338
+ includeHiddenFilesAndSources,
339
+ queryMetadata,
340
+ onQueryRun,
341
+ maxResultSize,
342
+ ],
343
+ );
344
+
345
+ // The source on screen: the host's when it keeps it, else this viewer's own.
346
+ const [localSourceName, setLocalSourceName] = useState<string | undefined>(
347
+ initialSourceName,
348
+ );
349
+ const controlled = controlledSourceName !== undefined;
350
+ const requestedSourceName = controlled
351
+ ? controlledSourceName
352
+ : localSourceName;
353
+ const pickSource = useCallback(
354
+ (name: string) => {
355
+ if (!controlled) setLocalSourceName(name);
356
+ onSourceChange?.(name);
357
+ },
358
+ [controlled, onSourceChange],
359
+ );
360
+ const defaultSource = useMemo(
361
+ () => pickDefaultSource(sources, modelPath),
362
+ [sources, modelPath],
363
+ );
364
+ const requestedSource = sources.find((s) => s.name === requestedSourceName);
365
+ const activeSource =
366
+ requestedSource ?? (controlled ? undefined : defaultSource);
367
+
368
+ const sourceGivens = useMemo(
369
+ () =>
370
+ activeSource
371
+ ? (givensBySource.get(activeSource.name) ?? givens)
372
+ : givens,
373
+ [activeSource, givensBySource, givens],
374
+ );
375
+ // Which of those come from a source the page can't open, and from which.
376
+ const inheritedGivens = useMemo(
377
+ () =>
378
+ activeSource
379
+ ? givensInheritedBy(
380
+ sourceText,
381
+ activeSource.name,
382
+ givens,
383
+ sourceNames,
384
+ )
385
+ : new Map<string, string[]>(),
386
+ [activeSource, sourceText, givens, sourceNames],
387
+ );
388
+ // The header's description: this source's own doc, less what it inherited
389
+ // from the source it extends (named in the model text).
390
+ const baseName = useMemo(
391
+ () => baseSourceName(sourceText, activeSource?.name, sourceNames),
392
+ [sourceText, activeSource?.name, sourceNames],
393
+ );
394
+ const activeSourceDoc = useMemo(
395
+ () =>
396
+ activeSource
397
+ ? ownSourceDoc(
398
+ activeSource,
399
+ sources.find((s) => s.name === baseName),
400
+ )
401
+ : undefined,
402
+ [activeSource, sources, baseName],
403
+ );
404
+
405
+ // A host's entities, by declaring source, and what they say about joins.
406
+ const entitiesBySource = useMemo(
407
+ () => (entities ? groupEntitiesBySource(entities) : NO_ENTITIES),
408
+ [entities],
409
+ );
410
+ const entitiesByName = activeSource
411
+ ? entitiesBySource.get(activeSource.name)
412
+ : undefined;
413
+ const { joinLinks, joinEntities, joinCodes, joinAccessRules } =
414
+ useMemo(() => {
415
+ const links = new Map<string, JoinLink>();
416
+ const fields = new Map<string, EntitiesByField>();
417
+ const codes = new Map<string, string>();
418
+ const rules = new Map<
419
+ string,
420
+ { sourceName: string; access: SourceAccess }
421
+ >();
422
+ const browsable = new Map([[modelPath, new Set(sourceNames)]]);
423
+ for (const entity of entitiesByName?.values() ?? []) {
424
+ if (entity.fieldType !== "join") continue;
425
+ if (entity.code) codes.set(entity.name, entity.code);
426
+ const target = entity.joinTarget;
427
+ if (!target) continue;
428
+ if (target.modelPath === modelPath) {
429
+ const joined = entitiesBySource.get(target.sourceName);
430
+ if (joined) fields.set(entity.name, joined);
431
+ const access = accessOf(accessBySource, target.sourceName);
432
+ if (hasAccessRules(access))
433
+ rules.set(entity.name, {
434
+ sourceName: target.sourceName,
435
+ access,
436
+ });
437
+ const reach = joinAccess(target, browsable);
438
+ // Same model: an in-page selection, as the sources pill makes.
439
+ links.set(
440
+ entity.name,
441
+ reach.kind === "link"
442
+ ? { ...reach, onOpen: () => pickSource(target.sourceName) }
443
+ : reach,
444
+ );
445
+ } else {
446
+ const href = joinHref?.(target);
447
+ if (href) links.set(entity.name, { kind: "link", href });
448
+ }
449
+ }
450
+ return {
451
+ joinLinks: links,
452
+ joinEntities: fields,
453
+ joinCodes: codes,
454
+ joinAccessRules: rules,
455
+ };
456
+ }, [
457
+ entitiesByName,
458
+ entitiesBySource,
459
+ modelPath,
460
+ sourceNames,
461
+ accessBySource,
462
+ pickSource,
463
+ joinHref,
464
+ ]);
465
+
466
+ // The picker, in the order a reader chooses from: on the package's root
467
+ // `index.malloy`, the order it exports its sources in.
468
+ const publicSurface =
469
+ modelPath === "index.malloy" && !includeHiddenFilesAndSources;
470
+ const pickerOrder = useMemo(
471
+ () =>
472
+ orderPickerSources(
473
+ sources,
474
+ defaultSource,
475
+ publicSurface
476
+ ? { exportOrder: exportOrder(sourceText) }
477
+ : undefined,
478
+ ),
479
+ [sources, defaultSource, publicSurface, sourceText],
480
+ );
481
+ const describePickerSource = extensions?.describePickerSource;
482
+ const navSources = useMemo<SourceNavItem[]>(
483
+ () =>
484
+ pickerOrder.sources.map((s) => {
485
+ const extras = describePickerSource?.({
486
+ modelPath,
487
+ sourceName: s.name,
488
+ });
489
+ return {
490
+ name: s.name,
491
+ description: pickerDescription(s.doc, extras?.summary),
492
+ descriptionPending:
493
+ !s.doc?.trim() &&
494
+ !extras?.summary &&
495
+ !!extras?.summaryPending,
496
+ meta: sourceMetaLine(s),
497
+ mostViews: pickerOrder.mostViews === s.name,
498
+ access: accessOf(accessBySource, s.name),
499
+ status: extras?.status,
500
+ };
501
+ }),
502
+ [pickerOrder, accessBySource, describePickerSource, modelPath],
503
+ );
504
+
505
+ const body = (() => {
506
+ if (isLoading) return <Loading text="Fetching Model..." />;
507
+ if (isError) {
508
+ // A refused read is an answer, not a failure: no Retry that asks the
509
+ // same question again. In the server's words where it gave some.
510
+ if (isNotFoundOrForbidden(error)) {
511
+ return (
512
+ <Box sx={{ pt: FILE_VIEW_TOP_GAP }}>
513
+ <EmptyRow
514
+ message={
515
+ serverMessage(error) ??
516
+ `${packageName}/${modelPath} doesn't exist, or you don't have access to it.`
517
+ }
518
+ />
519
+ </Box>
520
+ );
521
+ }
522
+ return (
523
+ <LoadErrorAlert
524
+ message={describeApiError("Failed to load model", error)}
525
+ onRetry={() => void refetch()}
526
+ />
527
+ );
528
+ }
529
+ const queriesGroup = queries.length > 0 && (
530
+ <QueriesGroup
531
+ queries={queries}
532
+ sourceText={sourceText}
533
+ modelPath={modelPath}
534
+ run={run}
535
+ />
536
+ );
537
+ if (sources.length === 0) {
538
+ if (queries.length === 0) {
539
+ // Still the model's page, with its heading and actions (Copy
540
+ // link): a givens-only file is a model like any other, and its
541
+ // givens are what it holds, so they are listed.
542
+ return (
543
+ <>
544
+ <HeaderBar
545
+ headingLevel={headingLevel}
546
+ title={modelDisplayName(modelPath)}
547
+ meta={
548
+ givens.length > 0
549
+ ? `${givens.length} ${givens.length === 1 ? "given" : "givens"}`
550
+ : undefined
551
+ }
552
+ actions={headerActions}
553
+ isSource={false}
554
+ offSurface={includeHiddenFilesAndSources}
555
+ />
556
+ <EmptyRow
557
+ message="This model defines no sources or queries."
558
+ secondary={
559
+ hasImports && (
560
+ <>
561
+ It imports other files but re-exports nothing. Add{" "}
562
+ <code>export {"{ source_name }"}</code> to surface
563
+ imported sources here.
564
+ </>
565
+ )
566
+ }
567
+ />
568
+ <ModelSection
569
+ label="Givens"
570
+ count={givens.length}
571
+ testId="model-viewer-declared-givens"
572
+ >
573
+ <BodyText
574
+ data-testid="model-viewer-declared-givens-where"
575
+ sx={{ mb: 1 }}
576
+ >
577
+ {givensOnlyWhere(sourceText, givens)}
578
+ </BodyText>
579
+ <GivenFacts givens={givens} />
580
+ </ModelSection>
581
+ </>
582
+ );
583
+ }
584
+ // No sources, but named queries: the page is its queries, titled by
585
+ // the model (there is no source to name it).
586
+ return (
587
+ <>
588
+ <HeaderBar
589
+ headingLevel={headingLevel}
590
+ title={modelDisplayName(modelPath)}
591
+ meta={`${queries.length} ${queries.length === 1 ? "query" : "queries"}`}
592
+ actions={headerActions}
593
+ isSource={false}
594
+ offSurface={includeHiddenFilesAndSources}
595
+ />
596
+ {queriesGroup}
597
+ </>
598
+ );
599
+ }
600
+ if (!activeSource) {
601
+ // A name the model doesn't expose (renamed, removed, or hidden by the
602
+ // package's surface): a clean not-found state, never another source
603
+ // under the wrong name, and alike for "never existed" and "hidden".
604
+ return (
605
+ <Box sx={{ pt: FILE_VIEW_TOP_GAP }}>
606
+ <EmptyRow
607
+ message={`This model has no source named ${requestedSourceName}.`}
608
+ secondary={
609
+ <Box
610
+ component="span"
611
+ data-testid="model-viewer-source-links"
612
+ >
613
+ {"Sources in this model: "}
614
+ {sources.map((s, i) => (
615
+ <span key={s.name}>
616
+ {i > 0 && ", "}
617
+ <Link
618
+ component="button"
619
+ type="button"
620
+ onClick={() => pickSource(s.name)}
621
+ sx={{
622
+ fontFamily: MONO_FONT_FAMILY,
623
+ verticalAlign: "baseline",
624
+ }}
625
+ >
626
+ {s.name}
627
+ </Link>
628
+ </span>
629
+ ))}
630
+ </Box>
631
+ }
632
+ />
633
+ </Box>
634
+ );
635
+ }
636
+ const n = fieldCount(activeSource);
637
+ // A derived source names the source it's built from, which picks it in
638
+ // this same viewer (an in-page selection, like the sources pill); one on
639
+ // a table names the table, where a host's entities say which.
640
+ const table = baseName
641
+ ? undefined
642
+ : [...(entitiesByName?.values() ?? [])].find((e) => e.table)?.table;
643
+ const provenance = baseName ? (
644
+ <>
645
+ {"from "}
646
+ <Link
647
+ component="button"
648
+ type="button"
649
+ onClick={() => pickSource(baseName)}
650
+ sx={{
651
+ fontFamily: MONO_FONT_FAMILY,
652
+ color: TEXT_TERTIARY,
653
+ textDecorationColor: "inherit",
654
+ verticalAlign: "baseline",
655
+ }}
656
+ >
657
+ {baseName}
658
+ </Link>
659
+ </>
660
+ ) : table ? (
661
+ <>
662
+ {"reads "}
663
+ <Box
664
+ component="span"
665
+ data-testid="model-viewer-source-table"
666
+ sx={{ fontFamily: MONO_FONT_FAMILY }}
667
+ >
668
+ {[
669
+ table.connectionName,
670
+ table.catalogName,
671
+ table.schemaName,
672
+ table.tableName,
673
+ ]
674
+ .filter(Boolean)
675
+ .join(".")}
676
+ </Box>
677
+ </>
678
+ ) : undefined;
679
+ const sourceDetail = extensions?.renderSourceDetail?.({
680
+ modelPath,
681
+ sourceName: activeSource.name,
682
+ });
683
+ return (
684
+ <>
685
+ <HeaderBar
686
+ headingLevel={headingLevel}
687
+ title={activeSource.name}
688
+ titleAdornments={
689
+ sources.length > 1 && (
690
+ <SourcesNav
691
+ sources={navSources}
692
+ currentName={activeSource.name}
693
+ countLabel={sourceCountLabel(
694
+ navSources.length,
695
+ pickerOrder.curated,
696
+ )}
697
+ onPickSource={pickSource}
698
+ curated={pickerOrder.curated}
699
+ exportOrdered={pickerOrder.exportOrdered}
700
+ />
701
+ )
702
+ }
703
+ actions={headerActions}
704
+ status={renderSourceStatus?.(activeSource.name)}
705
+ kindLabel="Source"
706
+ meta={`${n} ${n === 1 ? "field" : "fields"}`}
707
+ doc={activeSourceDoc}
708
+ modelDoc={modelDoc}
709
+ access={accessOf(accessBySource, activeSource.name)}
710
+ showRules={showAccessRules}
711
+ offSurface={includeHiddenFilesAndSources}
712
+ publicSurface={publicSurface}
713
+ provenance={provenance}
714
+ />
715
+ {sourceDetail && (
716
+ <Box data-testid="model-viewer-source-detail" sx={{ mt: 1.5 }}>
717
+ {sourceDetail}
718
+ </Box>
719
+ )}
720
+ <ModelGivensContext.Provider value={givens}>
721
+ <SchemaView
722
+ // Keyed by source: switching source presents it fresh, with
723
+ // none of the previous source's rows left open.
724
+ key={activeSource.name}
725
+ source={activeSource}
726
+ modelPath={modelPath}
727
+ entitiesByName={entitiesByName}
728
+ entitiesLoading={entitiesLoading}
729
+ entitiesError={entitiesError}
730
+ columnDescriptions={columnDescriptions?.get(
731
+ activeSource.name,
732
+ )}
733
+ modelText={sourceText}
734
+ joinLinks={joinLinks}
735
+ joinAccess={joinAccessRules}
736
+ showRules={showAccessRules}
737
+ joinEntities={joinEntities}
738
+ joinCodes={joinCodes}
739
+ run={run}
740
+ queries={queriesGroup}
741
+ givens={
742
+ <ModelGivensSection
743
+ givens={sourceGivens}
744
+ unknown={
745
+ activeSource
746
+ ? unknownGivensBySource.get(activeSource.name)
747
+ : undefined
748
+ }
749
+ inheritedFrom={inheritedGivens}
750
+ values={givensState.draft}
751
+ onChange={givensState.setGiven}
752
+ onReset={givensState.reset}
753
+ environmentName={environmentName}
754
+ packageName={packageName}
755
+ modelPath={modelPath}
756
+ versionId={versionId}
757
+ declaredTypes={declaredTypes}
758
+ />
759
+ }
760
+ />
761
+ </ModelGivensContext.Provider>
762
+ </>
763
+ );
764
+ })();
765
+
766
+ return (
767
+ <ModelViewerExtensionsContext.Provider value={extensions ?? {}}>
768
+ <Box
769
+ data-testid="model-viewer"
770
+ // The host's code face, for every name and block of Malloy below.
771
+ sx={{ ...CONTENT_COLUMN_SX, pb: 2, [MONO_FONT_VAR]: monoFont }}
772
+ >
773
+ <Box sx={FLAT_PANE_SX}>{body}</Box>
774
+ </Box>
775
+ </ModelViewerExtensionsContext.Provider>
776
+ );
777
+ }