@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,228 @@
1
+ // Copyright (c) Credible Data Inc.
2
+ // SPDX-License-Identifier: MIT
3
+
4
+ import type { DocumentSymbol } from "@malloydata/malloy";
5
+ import { rangeText, type ParsedModelText } from "./modelTextParse";
6
+
7
+ /** The field kinds a source declares with `kind: name is …`. */
8
+ export type DeclaredKind = "view" | "measure" | "dimension";
9
+
10
+ /** One field's declaration as written in the model file. */
11
+ export interface TextDeclaration {
12
+ kind: DeclaredKind;
13
+ /**
14
+ * The annotation lines directly above it, then the declaration from its name
15
+ * (`name is …`) to its end — the shape of the entities artifact's `code`, so
16
+ * the row's code display (viewDeclaration, stripDefinitionWrapper) reads both alike.
17
+ */
18
+ code: string;
19
+ }
20
+
21
+ /**
22
+ * Every view, measure and dimension a source declares, read from the model
23
+ * file with Malloy's parser: field name → its declaration.
24
+ *
25
+ * A host's entities can carry a field's code, but the Publisher's own reads
26
+ * don't, so without them the rows would offer no code at all. The compiled
27
+ * model carries the file's text, and this reads the declarations from it, as
28
+ * `namedQueryCode` does for a named query.
29
+ *
30
+ * The parser gives each declaration's exact text but not its kind, so the kind
31
+ * is the `dimension:` / `measure:` / `view:` keyword that owns the entry.
32
+ * Fields the source inherits from the source it extends (`source: b is a
33
+ * extend { … }`, `a` in the same file) are read from `a`'s declaration, the
34
+ * source's own taking precedence. A name declared twice is left out rather than
35
+ * guessed, and so is anything that is not a `name is …` definition under one of
36
+ * those keywords (a `rename:`, a query source's `group_by: carrier`, a field
37
+ * from another file): the row then says it has no code.
38
+ */
39
+ export function fieldDeclarations(
40
+ parsed: ParsedModelText | undefined,
41
+ sourceName: string | undefined,
42
+ ): ReadonlyMap<string, TextDeclaration> {
43
+ const out = new Map<string, TextDeclaration>();
44
+ if (!parsed || !sourceName) return out;
45
+ const sources = new Map<string, DocumentSymbol>();
46
+ for (const symbol of parsed.symbols)
47
+ if (symbol.type === "explore") sources.set(unquote(symbol.name), symbol);
48
+ const seen = new Set<string>();
49
+ for (let name: string | undefined = sourceName; name && !seen.has(name); ) {
50
+ seen.add(name);
51
+ const source = sources.get(name);
52
+ if (!source) break;
53
+ for (const [field, decl] of declarationsIn(parsed.lines, source)) {
54
+ if (!out.has(field)) out.set(field, decl);
55
+ }
56
+ name = baseOf(rangeText(parsed.lines, source.range));
57
+ }
58
+ return out;
59
+ }
60
+
61
+ const DECLARED_KIND = /^\s*(view|measure|dimension)\s*:\s*$/;
62
+ /** A definition, `name is …`, as against a reference (`carrier` in a query source's `group_by:`). */
63
+ const DEFINITION = /^`?([A-Za-z_]\w*)`?\s+is\b/;
64
+
65
+ function declarationsIn(
66
+ lines: string[],
67
+ source: DocumentSymbol,
68
+ ): Map<string, TextDeclaration> {
69
+ const found = new Map<string, TextDeclaration | null>();
70
+ // The keyword that owns the entry: the last one between the previous entry
71
+ // and this one, or the previous entry's when there is none between them
72
+ // (`measure: a is count(), b is sum(x)`, or entries on lines of their own).
73
+ let keyword: string | undefined;
74
+ let from = source.range.start;
75
+ for (const child of source.children) {
76
+ const gap = rangeText(lines, { start: from, end: child.range.start });
77
+ keyword = lastKeyword(gap) ?? keyword;
78
+ from = child.range.end;
79
+ const kind = declaredKind(child, keyword);
80
+ if (!kind) continue;
81
+ const decl = declarationOf(lines, child, kind);
82
+ if (!decl) continue;
83
+ const name = unquote(child.name);
84
+ // Declared twice: neither is shown, rather than the wrong one.
85
+ found.set(name, found.has(name) ? null : decl);
86
+ }
87
+ const out = new Map<string, TextDeclaration>();
88
+ for (const [name, decl] of found) if (decl) out.set(name, decl);
89
+ return out;
90
+ }
91
+
92
+ function declaredKind(
93
+ symbol: DocumentSymbol,
94
+ keyword: string | undefined,
95
+ ): DeclaredKind | undefined {
96
+ if (symbol.type === "query") return keyword === "view" ? "view" : undefined;
97
+ if (
98
+ symbol.type === "field" &&
99
+ (keyword === "dimension" || keyword === "measure")
100
+ )
101
+ return keyword;
102
+ return undefined;
103
+ }
104
+
105
+ /**
106
+ * The entry's annotations then its text from its name. The parser's range
107
+ * holds an annotation written on the entry itself (`# percent` above `a is
108
+ * count()` inside a `measure:` block); one above the statement (`# currency`
109
+ * above `dimension: carrier is …`) is outside it, so it is read from the lines
110
+ * above.
111
+ */
112
+ function declarationOf(
113
+ lines: string[],
114
+ symbol: DocumentSymbol,
115
+ kind: DeclaredKind,
116
+ ): TextDeclaration | undefined {
117
+ const text = rangeText(lines, symbol.range).split("\n");
118
+ const own: string[] = [];
119
+ // The annotations it opens with; a comment between them is not part of the code shown.
120
+ while (text.length > 1 && /^\s*(#|\/\/|--|$)/.test(text[0])) {
121
+ const line = text.shift()!.trim();
122
+ if (line.startsWith("#")) own.push(line);
123
+ }
124
+ text[0] = text[0].trimStart();
125
+ const body = text.join("\n").trimEnd();
126
+ const definition = DEFINITION.exec(body);
127
+ if (!definition || definition[1] !== unquote(symbol.name)) return undefined;
128
+ return {
129
+ kind,
130
+ code: [...annotationsAbove(lines, symbol.range.start), ...own, body].join(
131
+ "\n",
132
+ ),
133
+ };
134
+ }
135
+
136
+ /**
137
+ * The `#` lines directly above an entry that starts its line (after nothing,
138
+ * or after its `view:` / `measure:` / `dimension:`), and — when it is the first
139
+ * entry under a bare keyword line — those above that line too, since they apply
140
+ * to every entry the statement declares. An entry later on a line (after a
141
+ * comma, or a one-line source's `extend {`) has none.
142
+ */
143
+ function annotationsAbove(
144
+ lines: string[],
145
+ start: { line: number; character: number },
146
+ ): string[] {
147
+ const before = (lines[start.line] ?? "").slice(0, start.character);
148
+ const startsLine = before.trim() === "";
149
+ if (!startsLine && !DECLARED_KIND.test(before)) return [];
150
+ const collect = (from: number) => {
151
+ const out: string[] = [];
152
+ let i = from;
153
+ while (i >= 0 && lines[i].trim().startsWith("#"))
154
+ out.unshift(lines[i--].trim());
155
+ return { out, next: i };
156
+ };
157
+ const own = collect(start.line - 1);
158
+ if (startsLine && own.next >= 0 && DECLARED_KIND.test(lines[own.next])) {
159
+ return [...collect(own.next - 1).out, ...own.out];
160
+ }
161
+ return own.out;
162
+ }
163
+
164
+ /** A statement keyword (`measure:`, `where:`), not a `::` cast. */
165
+ const KEYWORD = /(?<![\w:])([A-Za-z_]\w*)\s*:(?!:)/g;
166
+
167
+ /** The last statement keyword in some text, its strings, comments and annotations skipped. */
168
+ function lastKeyword(text: string): string | undefined {
169
+ let last: string | undefined;
170
+ for (const match of codeOnly(text).matchAll(KEYWORD)) last = match[1];
171
+ return last;
172
+ }
173
+
174
+ /** The text with its strings, comments and annotations blanked. */
175
+ function codeOnly(text: string): string {
176
+ let out = "";
177
+ for (let i = 0; i < text.length; i++) {
178
+ const c = text[i];
179
+ if (text.startsWith('"""', i)) {
180
+ const close = text.indexOf('"""', i + 3);
181
+ const end = close === -1 ? text.length : close + 3;
182
+ out += " ".repeat(end - i);
183
+ i = end - 1;
184
+ } else if (c === '"' || c === "'" || c === "`") {
185
+ const close = closingQuote(text, i);
186
+ out += " ".repeat(close - i + 1);
187
+ i = close;
188
+ } else if (
189
+ c === "#" ||
190
+ (c === "/" && text[i + 1] === "/") ||
191
+ (c === "-" && text[i + 1] === "-")
192
+ ) {
193
+ const eol = text.indexOf("\n", i);
194
+ const end = eol === -1 ? text.length : eol;
195
+ out += " ".repeat(end - i);
196
+ i = end - 1;
197
+ } else {
198
+ out += c;
199
+ }
200
+ }
201
+ return out;
202
+ }
203
+
204
+ /** The index of the quote that closes the one at `open`, past escapes (or the text's end). */
205
+ function closingQuote(text: string, open: number): number {
206
+ const quote = text[open];
207
+ for (let i = open + 1; i < text.length; i++) {
208
+ if (text[i] === "\\") i++;
209
+ else if (text[i] === quote) return i;
210
+ }
211
+ return text.length;
212
+ }
213
+
214
+ /**
215
+ * The source a source's declaration (`b is a extend { … }`) builds on, when
216
+ * that passes `a`'s fields on: `extend`, or `b is a` alone. A query's (`b is a
217
+ * -> { group_by: x }`) output columns are new fields that do not carry `a`'s
218
+ * definitions.
219
+ */
220
+ function baseOf(declaration: string): string | undefined {
221
+ return /^`?[A-Za-z_]\w*`?\s+is\s+`?([A-Za-z_]\w*)`?\s*(?:extend\b|$)/.exec(
222
+ declaration,
223
+ )?.[1];
224
+ }
225
+
226
+ function unquote(name: string): string {
227
+ return name.replace(/^`(.*)`$/, "$1");
228
+ }
@@ -0,0 +1,112 @@
1
+ // Copyright (c) Credible Data Inc.
2
+ // SPDX-License-Identifier: MIT
3
+
4
+ import { useEffect, useMemo, useState } from "react";
5
+ import type { DocumentRange, DocumentSymbol } from "@malloydata/malloy";
6
+
7
+ type MalloyModule = typeof import("@malloydata/malloy");
8
+
9
+ /**
10
+ * A model file's text with the symbols Malloy's parser finds in it: each
11
+ * source, its fields, views and joins, and the file's named queries, each with
12
+ * the range of text that declares it. Parsing does not compile, so a file
13
+ * mid-edit still yields what the parser could read.
14
+ */
15
+ export interface ParsedModelText {
16
+ /** The file's lines, CRLF read as LF, which the symbols' ranges index. */
17
+ lines: string[];
18
+ symbols: DocumentSymbol[];
19
+ }
20
+
21
+ // The last text parsed: a page's views and its named queries read the same file.
22
+ let lastParse:
23
+ | { text: string; parsed: ParsedModelText | undefined }
24
+ | undefined;
25
+
26
+ /** Undefined when the parser throws: the rows then say they have no code. */
27
+ export function parseModelText(
28
+ malloy: MalloyModule,
29
+ text: string,
30
+ ): ParsedModelText | undefined {
31
+ if (lastParse?.text === text) return lastParse.parsed;
32
+ const source = text.replace(/\r\n/g, "\n");
33
+ let parsed: ParsedModelText | undefined;
34
+ try {
35
+ parsed = {
36
+ lines: source.split("\n"),
37
+ symbols: malloy.Malloy.parse({ source }).symbols,
38
+ };
39
+ } catch {
40
+ parsed = undefined;
41
+ }
42
+ lastParse = { text, parsed };
43
+ return parsed;
44
+ }
45
+
46
+ /** The text a range covers. */
47
+ export function rangeText(
48
+ lines: readonly string[],
49
+ range: DocumentRange,
50
+ ): string {
51
+ const { start, end } = range;
52
+ if (start.line === end.line)
53
+ return (lines[start.line] ?? "").slice(start.character, end.character);
54
+ return [
55
+ (lines[start.line] ?? "").slice(start.character),
56
+ ...lines.slice(start.line + 1, end.line),
57
+ (lines[end.line] ?? "").slice(0, end.character),
58
+ ].join("\n");
59
+ }
60
+
61
+ let loaded: MalloyModule | undefined;
62
+ let loading: Promise<MalloyModule> | undefined;
63
+
64
+ /**
65
+ * Malloy's parser is about 450 KB gzipped. The Publisher SDK already loads it
66
+ * lazily, into a chunk of its own, so importing it the same way here shares
67
+ * that chunk and only a page that needs a declaration from the text fetches it.
68
+ */
69
+ function loadMalloy(): Promise<MalloyModule> {
70
+ loading ??= import("@malloydata/malloy").then((ns) => {
71
+ // A CommonJS module's exports can arrive under `default`, depending on the bundler.
72
+ const mod = (
73
+ "Malloy" in ns ? ns : (ns as { default: MalloyModule }).default
74
+ ) as MalloyModule;
75
+ loaded = mod;
76
+ return mod;
77
+ });
78
+ loading.catch(() => {
79
+ loading = undefined;
80
+ });
81
+ return loading;
82
+ }
83
+
84
+ /**
85
+ * `text` parsed, once the parser has loaded. `pending` while it loads; when
86
+ * `wanted` is false nothing is loaded or parsed. A parser that fails to load
87
+ * leaves `parsed` undefined and `pending` false.
88
+ */
89
+ export function useParsedModelText(
90
+ text: string | undefined,
91
+ wanted = true,
92
+ ): { parsed: ParsedModelText | undefined; pending: boolean } {
93
+ const [malloy, setMalloy] = useState<MalloyModule | undefined>(loaded);
94
+ const [failed, setFailed] = useState(false);
95
+ const need = !!text && wanted;
96
+ useEffect(() => {
97
+ if (!need || malloy) return;
98
+ let live = true;
99
+ loadMalloy().then(
100
+ (mod) => live && setMalloy(mod),
101
+ () => live && setFailed(true),
102
+ );
103
+ return () => {
104
+ live = false;
105
+ };
106
+ }, [need, malloy]);
107
+ const parsed = useMemo(
108
+ () => (need && malloy && text ? parseModelText(malloy, text) : undefined),
109
+ [need, malloy, text],
110
+ );
111
+ return { parsed, pending: need && !malloy && !failed };
112
+ }
@@ -0,0 +1,58 @@
1
+ // Copyright (c) Credible Data Inc.
2
+ // SPDX-License-Identifier: MIT
3
+
4
+ import { describe, expect, it } from "bun:test";
5
+ import * as malloy from "@malloydata/malloy";
6
+ import { namedQueryCode as queryCodeOf } from "./namedQueryCode";
7
+ import { parseModelText } from "./modelTextParse";
8
+
9
+ const namedQueryCode = (text: string | undefined, name: string) =>
10
+ queryCodeOf(
11
+ text === undefined ? undefined : parseModelText(malloy, text),
12
+ name,
13
+ );
14
+
15
+ const FILE = `source: flights is duckdb.table('flights.parquet') extend {
16
+ measure: flight_count is count()
17
+ }
18
+
19
+ #(doc) Top carriers by flights
20
+ query: top_carriers is flights -> {
21
+ group_by: carrier
22
+ aggregate: flight_count
23
+ where: carrier != "}"
24
+ }
25
+
26
+ query: by_month is flights
27
+ -> { group_by: dep_month is dep_time.month }
28
+ -> { select: * }
29
+
30
+ run: flights -> { aggregate: flight_count }
31
+ `;
32
+
33
+ describe("namedQueryCode", () => {
34
+ it("cuts a named query's declaration out of its model file", () => {
35
+ expect(namedQueryCode(FILE, "top_carriers")).toBe(
36
+ `query: top_carriers is flights -> {\n group_by: carrier\n aggregate: flight_count\n where: carrier != "}"\n}`,
37
+ );
38
+ });
39
+
40
+ it("keeps a pipeline continued on the next lines", () => {
41
+ expect(namedQueryCode(FILE, "by_month")).toBe(
42
+ "query: by_month is flights\n -> { group_by: dep_month is dep_time.month }\n -> { select: * }",
43
+ );
44
+ });
45
+
46
+ it("reads each of several queries one `query:` declares", () => {
47
+ const text =
48
+ "query: a is flights -> { group_by: carrier }, b is flights -> { group_by: origin }\n";
49
+ expect(namedQueryCode(text, "b")).toBe(
50
+ "query: b is flights -> { group_by: origin }",
51
+ );
52
+ });
53
+
54
+ it("has nothing to show for a name the file doesn't declare, or no file", () => {
55
+ expect(namedQueryCode(FILE, "nope")).toBeUndefined();
56
+ expect(namedQueryCode(undefined, "top_carriers")).toBeUndefined();
57
+ });
58
+ });
@@ -0,0 +1,26 @@
1
+ // Copyright (c) Credible Data Inc.
2
+ // SPDX-License-Identifier: MIT
3
+
4
+ import { rangeText, type ParsedModelText } from "./modelTextParse";
5
+
6
+ /**
7
+ * A model-level named query's declaration (`query: name is …`), read from the
8
+ * model file with Malloy's parser. The compiled model lists a query's name and
9
+ * annotations only, never its definition (see ExplorerQuery), so the file is
10
+ * the one place its code exists; this is what a query row's Code shows.
11
+ *
12
+ * Undefined where the file isn't available, doesn't declare the name, or
13
+ * declares it twice: the row's Code then says it has nothing to show, never a
14
+ * guess.
15
+ */
16
+ export function namedQueryCode(
17
+ parsed: ParsedModelText | undefined,
18
+ name: string,
19
+ ): string | undefined {
20
+ if (!parsed) return undefined;
21
+ const declared = parsed.symbols.filter(
22
+ (s) => s.type === "query" && s.name.replace(/^`(.*)`$/, "$1") === name,
23
+ );
24
+ if (declared.length !== 1) return undefined;
25
+ return `query: ${rangeText(parsed.lines, declared[0].range).trimEnd()}`;
26
+ }
@@ -0,0 +1,124 @@
1
+ // Copyright (c) Credible Data Inc.
2
+ // SPDX-License-Identifier: MIT
3
+
4
+ import { Tooltip } from "@mui/material";
5
+ import { StatusPill } from "./StatusPill";
6
+ import { HeaderChip } from "./headerCard";
7
+
8
+ /**
9
+ * A package whose root `index.malloy` decides what it publishes hides every other
10
+ * model file: the models list leaves it out and the model GET answers 404. People
11
+ * who can edit the package still need to read those files, so for them the app asks
12
+ * with `includeHiddenFilesAndSources`, which a host allows only for someone who can edit
13
+ * the package. The same flag rides on their runs of such a file, and Publisher then drops
14
+ * the surface limit for that run, so an editor can query a hidden source too. Anyone else
15
+ * never sends the flag, so for them a hidden file stays a 404.
16
+ */
17
+
18
+ /** The marker on a hidden file, in the package's models list and on its page. */
19
+ export const OFF_SURFACE_LABEL = "Private";
20
+
21
+ /** What the marker means: its tooltip, wherever it shows. */
22
+ export const OFF_SURFACE_DETAIL =
23
+ "index.malloy doesn't export this file, so only people who can edit the package see it.";
24
+
25
+ /** Whether a models-list entry is a file the package hides. Absent (an older server) reads as not hidden. */
26
+ export function isHidden(model: { isHidden?: boolean }): boolean {
27
+ return model.isHidden === true;
28
+ }
29
+
30
+ /**
31
+ * The Private marker on a row of the package's models list: not a tab stop, since the row is
32
+ * one link and a control inside it would be a second. Its why is in the tooltip for a pointer,
33
+ * and in the row's accessible name for everyone else ({@link surfaceRowLabel}), as a row's
34
+ * access pills put theirs (AccessChips `accessRowLabel`).
35
+ */
36
+ export function OffSurfacePill() {
37
+ return (
38
+ <Tooltip title={OFF_SURFACE_DETAIL}>
39
+ <StatusPill tone="warning" data-testid="model-viewer-off-surface">
40
+ {OFF_SURFACE_LABEL}
41
+ </StatusPill>
42
+ </Tooltip>
43
+ );
44
+ }
45
+
46
+ /**
47
+ * The Private marker on a hidden file's own page (its source's status row, or above the code):
48
+ * a status-row chip like its siblings (HeaderChip), so it is a tab stop whose accessible name
49
+ * is its why, reachable by keyboard and read by a screen reader, not only shown on hover.
50
+ */
51
+ export function OffSurfaceChip() {
52
+ return (
53
+ <HeaderChip
54
+ title={`${OFF_SURFACE_LABEL}: ${OFF_SURFACE_DETAIL}`}
55
+ testId="model-viewer-off-surface"
56
+ >
57
+ <StatusPill tone="warning" size="header">
58
+ {OFF_SURFACE_LABEL}
59
+ </StatusPill>
60
+ </HeaderChip>
61
+ );
62
+ }
63
+
64
+ /** The marker on the package's root `index.malloy`: the sources it exports are the package's public ones. */
65
+ export const PUBLIC_SURFACE_LABEL = "Public";
66
+
67
+ /** What the marker means on the root `index.malloy`'s row in the package's models list. */
68
+ export const PUBLIC_FILE_DETAIL =
69
+ "What index.malloy exports is what the package publishes: everyone who can read the package can query its sources.";
70
+
71
+ /** What the marker means in a source's status row on the root `index.malloy`'s page. */
72
+ export const PUBLIC_SOURCE_DETAIL =
73
+ "index.malloy exports this source, so everyone who can read the package can query it.";
74
+
75
+ /**
76
+ * The marker on the package's root `index.malloy`'s row in the models list: what it exports is
77
+ * what the package publishes, so it is the model a reader should open first. Green beside the
78
+ * amber Private on the files it leaves out ({@link OffSurfacePill}), so the two read as one
79
+ * public/private pair (the guide's §4 names this pair as the one Declaration that takes a
80
+ * tone), and drawn the same way: not a tab stop, its why in the tooltip and in the row's
81
+ * accessible name ({@link surfaceRowLabel}).
82
+ */
83
+ export function PublicSurfacePill() {
84
+ return (
85
+ <Tooltip title={PUBLIC_FILE_DETAIL}>
86
+ <StatusPill
87
+ tone="positive"
88
+ data-testid="model-viewer-public-surface"
89
+ sx={{ alignSelf: "center" }}
90
+ >
91
+ {PUBLIC_SURFACE_LABEL}
92
+ </StatusPill>
93
+ </Tooltip>
94
+ );
95
+ }
96
+
97
+ /**
98
+ * The Public marker in a source's status row on the root `index.malloy`'s page: a status-row
99
+ * chip like its siblings (HeaderChip), a tab stop whose accessible name is its why.
100
+ */
101
+ export function PublicSurfaceChip() {
102
+ return (
103
+ <HeaderChip
104
+ title={`${PUBLIC_SURFACE_LABEL}: ${PUBLIC_SOURCE_DETAIL}`}
105
+ testId="model-viewer-public-surface"
106
+ >
107
+ <StatusPill tone="positive" size="header">
108
+ {PUBLIC_SURFACE_LABEL}
109
+ </StatusPill>
110
+ </HeaderChip>
111
+ );
112
+ }
113
+
114
+ /** Which side of the package's surface a models-list row's file is on, when it is marked. */
115
+ export type FileSurface = "public" | "private";
116
+
117
+ /** The words a models-list row's accessible name adds for its surface pill (", Private: …"). */
118
+ export function surfaceRowLabel(surface: FileSurface | undefined): string {
119
+ if (surface === "public")
120
+ return `, ${PUBLIC_SURFACE_LABEL}: ${PUBLIC_FILE_DETAIL}`;
121
+ if (surface === "private")
122
+ return `, ${OFF_SURFACE_LABEL}: ${OFF_SURFACE_DETAIL}`;
123
+ return "";
124
+ }
@@ -0,0 +1,104 @@
1
+ // Copyright (c) Credible Data Inc.
2
+ // SPDX-License-Identifier: MIT
3
+
4
+ import { useState, type ReactNode } from "react";
5
+ import {
6
+ IconCode,
7
+ IconFields,
8
+ IconGivens,
9
+ IconLock,
10
+ IconResult,
11
+ IconValues,
12
+ } from "./icons";
13
+ import { SegmentIcons } from "./SegmentIcons";
14
+
15
+ /**
16
+ * The kinds of content an open model row can show. An open row shows ONE card;
17
+ * where it has more than one of these, the switch on its line picks which, in
18
+ * this order.
19
+ */
20
+ export type RowLayer =
21
+ | "result"
22
+ | "fields"
23
+ | "code"
24
+ | "values"
25
+ | "givens"
26
+ | "access";
27
+
28
+ const LAYER_ORDER: ReadonlyArray<RowLayer> = [
29
+ "result",
30
+ // Beside Result: the values a result ran with.
31
+ "givens",
32
+ "fields",
33
+ "code",
34
+ "values",
35
+ "access",
36
+ ];
37
+
38
+ /** Each layer's icon and word: a result's chart, the code brackets, the lock a
39
+ * governed thing carries. */
40
+ const LAYER_OPTIONS: Record<RowLayer, { icon: ReactNode; label: string }> = {
41
+ result: { icon: <IconResult size={14} />, label: "Result" },
42
+ fields: { icon: <IconFields size={14} />, label: "Fields" },
43
+ code: { icon: <IconCode size={14} />, label: "Code" },
44
+ values: { icon: <IconValues size={14} />, label: "Values" },
45
+ givens: { icon: <IconGivens size={14} />, label: "Givens" },
46
+ access: { icon: <IconLock size={14} />, label: "Access" },
47
+ };
48
+
49
+ /**
50
+ * The layer an open row shows: the one the reader picked while it is available,
51
+ * else `initial` (when available), else the first available. `available` is in
52
+ * any order; it is read in {@link LAYER_ORDER}.
53
+ */
54
+ export function useRowLayer(
55
+ available: ReadonlyArray<RowLayer>,
56
+ initial?: RowLayer,
57
+ ) {
58
+ const layers = LAYER_ORDER.filter((l) => available.includes(l));
59
+ const [picked, setPicked] = useState<RowLayer | undefined>(undefined);
60
+ const layer =
61
+ picked !== undefined && layers.includes(picked)
62
+ ? picked
63
+ : initial !== undefined && layers.includes(initial)
64
+ ? initial
65
+ : layers[0];
66
+ return { layers, layer, setLayer: setPicked };
67
+ }
68
+
69
+ /**
70
+ * The switch between an open row's layers, drawn as action icons on its line.
71
+ * Nothing when there is only one layer: a switch with one option has nothing to
72
+ * switch. A layer the row has but cannot show here keeps its place, disabled with
73
+ * its reason (SegmentIcons).
74
+ */
75
+ export function RowLayerSwitch({
76
+ layers,
77
+ value,
78
+ onChange,
79
+ "aria-label": ariaLabel,
80
+ disabledReasons,
81
+ }: {
82
+ layers: ReadonlyArray<RowLayer>;
83
+ value: RowLayer | undefined;
84
+ onChange: (layer: RowLayer) => void;
85
+ "aria-label": string;
86
+ disabledReasons?: Partial<Record<RowLayer, string>>;
87
+ }) {
88
+ if (layers.length < 2 || value === undefined) return null;
89
+ return (
90
+ <SegmentIcons<RowLayer>
91
+ aria-label={ariaLabel}
92
+ value={value}
93
+ onChange={onChange}
94
+ options={layers.map((l) => {
95
+ const reason = disabledReasons?.[l];
96
+ return {
97
+ value: l,
98
+ ...LAYER_OPTIONS[l],
99
+ ...(reason ? { disabled: true, disabledReason: reason } : {}),
100
+ };
101
+ })}
102
+ />
103
+ );
104
+ }