@malloy-publisher/sdk 0.12.0 → 0.12.2

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (214) hide show
  1. package/README.md +79 -6
  2. package/dist/{RenderedResult-SgDlxzs9.cjs.js → RenderedResult-Cgw4iqev.cjs.js} +1 -1
  3. package/dist/{RenderedResult-D8bCgThO.es.js → RenderedResult-DEjFM1DL.es.js} +2 -2
  4. package/dist/ServerProvider-BRQl_cBo.cjs.js +1 -0
  5. package/dist/{ServerProvider-DBw-thY0.es.js → ServerProvider-RnliA2Ao.es.js} +1084 -723
  6. package/dist/builder/index.cjs.js +1 -1
  7. package/dist/builder/index.es.js +3 -3
  8. package/dist/client/api.d.ts +754 -41
  9. package/dist/client/index.cjs.js +1 -1
  10. package/dist/client/index.es.js +120 -110
  11. package/dist/components/Materializations/MaterializationDetailDialog.d.ts +16 -1
  12. package/dist/components/Model/ExplorerPage.d.ts +9 -0
  13. package/dist/components/Model/Model.d.ts +27 -11
  14. package/dist/components/ModelViewer/AccessChips.d.ts +34 -0
  15. package/dist/components/ModelViewer/EmptyRow.d.ts +23 -0
  16. package/dist/components/ModelViewer/Facts.d.ts +15 -0
  17. package/dist/components/ModelViewer/FieldGroup.d.ts +31 -0
  18. package/dist/components/ModelViewer/FieldRow.d.ts +69 -0
  19. package/dist/components/ModelViewer/GivenFacts.d.ts +21 -0
  20. package/dist/components/ModelViewer/HeaderBar.d.ts +75 -0
  21. package/dist/components/ModelViewer/InlineDoc.d.ts +13 -0
  22. package/dist/components/ModelViewer/ModelGivensSection.d.ts +32 -0
  23. package/dist/components/ModelViewer/ModelSection.d.ts +21 -0
  24. package/dist/components/ModelViewer/ModelViewer.d.ts +91 -0
  25. package/dist/components/ModelViewer/QueriesGroup.d.ts +15 -0
  26. package/dist/components/ModelViewer/RowGlyph.d.ts +27 -0
  27. package/dist/components/ModelViewer/RunResult.d.ts +46 -0
  28. package/dist/components/ModelViewer/SampleValues.d.ts +20 -0
  29. package/dist/components/ModelViewer/SchemaJoin.d.ts +51 -0
  30. package/dist/components/ModelViewer/SchemaView.d.ts +52 -0
  31. package/dist/components/ModelViewer/SegmentIcons.d.ts +70 -0
  32. package/dist/components/ModelViewer/SourcesDropdown.d.ts +53 -0
  33. package/dist/components/ModelViewer/SourcesNav.d.ts +25 -0
  34. package/dist/components/ModelViewer/StatusPill.d.ts +56 -0
  35. package/dist/components/ModelViewer/ValueChip.d.ts +17 -0
  36. package/dist/components/ModelViewer/ViewRow.d.ts +36 -0
  37. package/dist/components/ModelViewer/clickableBox.d.ts +29 -0
  38. package/dist/components/ModelViewer/codeDisplay.d.ts +44 -0
  39. package/dist/components/ModelViewer/docAnnotations.d.ts +90 -0
  40. package/dist/components/ModelViewer/explorerModel.d.ts +12 -0
  41. package/dist/components/ModelViewer/extensions.d.ts +94 -0
  42. package/dist/components/ModelViewer/fieldCode.d.ts +74 -0
  43. package/dist/components/ModelViewer/fieldEntities.d.ts +45 -0
  44. package/dist/components/ModelViewer/fieldExpansion.d.ts +41 -0
  45. package/dist/components/ModelViewer/givenUsage.d.ts +71 -0
  46. package/dist/components/ModelViewer/headerCard.d.ts +31 -0
  47. package/dist/components/ModelViewer/httpStatus.d.ts +4 -0
  48. package/dist/components/ModelViewer/icons.d.ts +31 -0
  49. package/dist/components/ModelViewer/index.d.ts +9 -0
  50. package/dist/components/ModelViewer/joinAccess.d.ts +52 -0
  51. package/dist/components/ModelViewer/malloyRunText.d.ts +22 -0
  52. package/dist/components/ModelViewer/malloyText.d.ts +21 -0
  53. package/dist/components/ModelViewer/modelGivens.d.ts +61 -0
  54. package/dist/components/ModelViewer/modelGivensContext.d.ts +9 -0
  55. package/dist/components/ModelViewer/modelHeaderPresentation.d.ts +28 -0
  56. package/dist/components/ModelViewer/modelTextDeclarations.d.ts +32 -0
  57. package/dist/components/ModelViewer/modelTextParse.d.ts +27 -0
  58. package/dist/components/ModelViewer/namedQueryCode.d.ts +12 -0
  59. package/dist/components/ModelViewer/offSurface.d.ts +54 -0
  60. package/dist/components/ModelViewer/rowLayers.d.ts +30 -0
  61. package/dist/components/ModelViewer/runGate.d.ts +49 -0
  62. package/dist/components/ModelViewer/schemaModel.d.ts +109 -0
  63. package/dist/components/ModelViewer/sectionOpenCommand.d.ts +45 -0
  64. package/dist/components/ModelViewer/sourceAccess.d.ts +67 -0
  65. package/dist/components/ModelViewer/sourceLineage.d.ts +14 -0
  66. package/dist/components/ModelViewer/sourcePicker.d.ts +66 -0
  67. package/dist/components/ModelViewer/surface.d.ts +47 -0
  68. package/dist/components/ModelViewer/text.d.ts +6 -0
  69. package/dist/components/ModelViewer/theme.d.ts +63 -0
  70. package/dist/components/ModelViewer/tokens.d.ts +52 -0
  71. package/dist/components/ModelViewer/ui.d.ts +48 -0
  72. package/dist/components/ModelViewer/useDimensionSamples.d.ts +76 -0
  73. package/dist/components/ModelViewer/useModelSources.d.ts +92 -0
  74. package/dist/components/ModelViewer/useRunQuery.d.ts +115 -0
  75. package/dist/components/ReportBuilder/loadMalloy.d.ts +4 -0
  76. package/dist/components/ServerProvider.d.ts +17 -2
  77. package/dist/components/filter/utils.d.ts +1 -1
  78. package/dist/components/given/GivenInput.d.ts +7 -1
  79. package/dist/components/given/GivensPanel.d.ts +3 -1
  80. package/dist/components/given/filterSummary.d.ts +6 -0
  81. package/dist/components/given/useGivenUrlParams.d.ts +11 -0
  82. package/dist/components/index.d.ts +2 -1
  83. package/dist/components/modelPage.d.ts +36 -0
  84. package/dist/hooks/useDimensionalFilterRangeData.d.ts +9 -0
  85. package/dist/hooks/useSuggestOptions.d.ts +26 -2
  86. package/dist/index.cjs.js +47 -19
  87. package/dist/index.es.js +14137 -9697
  88. package/dist/useCompiledDocument-D88_2cGS.cjs.js +143 -0
  89. package/dist/{useCompiledDocument-CXMPtJkJ.es.js → useCompiledDocument-Dmm6xkom.es.js} +6975 -6893
  90. package/dist/utils/filterCondition.d.ts +14 -0
  91. package/dist/utils/malloyLiteral.d.ts +20 -1
  92. package/package.json +2 -2
  93. package/src/components/Materializations/MaterializationDetailDialog.tsx +33 -7
  94. package/src/components/Materializations/Materializations.tsx +47 -4
  95. package/src/components/Materializations/Materializations.versions.spec.tsx +140 -1
  96. package/src/components/Model/ExplorerPage.tsx +269 -0
  97. package/src/components/Model/Model.tsx +66 -250
  98. package/src/components/Model/ModelExplorer.spec.tsx +64 -1
  99. package/src/components/ModelViewer/AccessChips.tsx +149 -0
  100. package/src/components/ModelViewer/EmptyRow.tsx +71 -0
  101. package/src/components/ModelViewer/Facts.tsx +46 -0
  102. package/src/components/ModelViewer/FieldGroup.tsx +137 -0
  103. package/src/components/ModelViewer/FieldRow.tsx +566 -0
  104. package/src/components/ModelViewer/GivenFacts.tsx +89 -0
  105. package/src/components/ModelViewer/HeaderBar.tsx +362 -0
  106. package/src/components/ModelViewer/InlineDoc.tsx +50 -0
  107. package/src/components/ModelViewer/ModelGivensSection.tsx +142 -0
  108. package/src/components/ModelViewer/ModelSection.tsx +98 -0
  109. package/src/components/ModelViewer/ModelViewer.spec.tsx +937 -0
  110. package/src/components/ModelViewer/ModelViewer.tsx +777 -0
  111. package/src/components/ModelViewer/QueriesGroup.tsx +107 -0
  112. package/src/components/ModelViewer/RowGlyph.tsx +138 -0
  113. package/src/components/ModelViewer/RunResult.tsx +298 -0
  114. package/src/components/ModelViewer/SampleValues.tsx +97 -0
  115. package/src/components/ModelViewer/SchemaJoin.tsx +258 -0
  116. package/src/components/ModelViewer/SchemaView.tsx +222 -0
  117. package/src/components/ModelViewer/SegmentIcons.tsx +129 -0
  118. package/src/components/ModelViewer/SourcesDropdown.tsx +265 -0
  119. package/src/components/ModelViewer/SourcesNav.tsx +75 -0
  120. package/src/components/ModelViewer/StatusPill.tsx +145 -0
  121. package/src/components/ModelViewer/ValueChip.tsx +39 -0
  122. package/src/components/ModelViewer/ViewRow.tsx +274 -0
  123. package/src/components/ModelViewer/clickableBox.ts +59 -0
  124. package/src/components/ModelViewer/codeDisplay.spec.ts +176 -0
  125. package/src/components/ModelViewer/codeDisplay.ts +118 -0
  126. package/src/components/ModelViewer/docAnnotations.spec.ts +181 -0
  127. package/src/components/ModelViewer/docAnnotations.ts +244 -0
  128. package/src/components/ModelViewer/docAnnotations.typeDetail.spec.ts +114 -0
  129. package/src/components/ModelViewer/explorerModel.spec.ts +43 -0
  130. package/src/components/ModelViewer/explorerModel.ts +31 -0
  131. package/src/components/ModelViewer/extensions.tsx +112 -0
  132. package/src/components/ModelViewer/fieldCode.spec.ts +168 -0
  133. package/src/components/ModelViewer/fieldCode.ts +118 -0
  134. package/src/components/ModelViewer/fieldEntities.ts +63 -0
  135. package/src/components/ModelViewer/fieldExpansion.spec.ts +116 -0
  136. package/src/components/ModelViewer/fieldExpansion.ts +95 -0
  137. package/src/components/ModelViewer/givenUsage.spec.ts +304 -0
  138. package/src/components/ModelViewer/givenUsage.ts +325 -0
  139. package/src/components/ModelViewer/headerCard.tsx +102 -0
  140. package/src/components/ModelViewer/httpStatus.ts +15 -0
  141. package/src/components/ModelViewer/icons.tsx +67 -0
  142. package/src/components/ModelViewer/index.ts +26 -0
  143. package/src/components/ModelViewer/joinAccess.spec.ts +95 -0
  144. package/src/components/ModelViewer/joinAccess.ts +54 -0
  145. package/src/components/ModelViewer/malloyRunText.spec.ts +48 -0
  146. package/src/components/ModelViewer/malloyRunText.ts +51 -0
  147. package/src/components/ModelViewer/malloyText.spec.ts +47 -0
  148. package/src/components/ModelViewer/malloyText.ts +77 -0
  149. package/src/components/ModelViewer/modelGivens.ts +228 -0
  150. package/src/components/ModelViewer/modelGivensContext.ts +13 -0
  151. package/src/components/ModelViewer/modelHeaderPresentation.spec.ts +31 -0
  152. package/src/components/ModelViewer/modelHeaderPresentation.ts +41 -0
  153. package/src/components/ModelViewer/modelTextDeclarations.spec.ts +336 -0
  154. package/src/components/ModelViewer/modelTextDeclarations.ts +228 -0
  155. package/src/components/ModelViewer/modelTextParse.ts +112 -0
  156. package/src/components/ModelViewer/namedQueryCode.spec.ts +58 -0
  157. package/src/components/ModelViewer/namedQueryCode.ts +26 -0
  158. package/src/components/ModelViewer/offSurface.tsx +124 -0
  159. package/src/components/ModelViewer/rowLayers.tsx +104 -0
  160. package/src/components/ModelViewer/runGate.spec.ts +219 -0
  161. package/src/components/ModelViewer/runGate.ts +145 -0
  162. package/src/components/ModelViewer/schemaModel.defaultSource.spec.ts +126 -0
  163. package/src/components/ModelViewer/schemaModel.queries.spec.ts +37 -0
  164. package/src/components/ModelViewer/schemaModel.ts +300 -0
  165. package/src/components/ModelViewer/sectionOpenCommand.tsx +125 -0
  166. package/src/components/ModelViewer/sourceAccess.spec.ts +130 -0
  167. package/src/components/ModelViewer/sourceAccess.ts +194 -0
  168. package/src/components/ModelViewer/sourceLineage.spec.ts +73 -0
  169. package/src/components/ModelViewer/sourceLineage.ts +38 -0
  170. package/src/components/ModelViewer/sourcePicker.spec.ts +294 -0
  171. package/src/components/ModelViewer/sourcePicker.ts +162 -0
  172. package/src/components/ModelViewer/surface.ts +51 -0
  173. package/src/components/ModelViewer/text.tsx +33 -0
  174. package/src/components/ModelViewer/theme.spec.ts +38 -0
  175. package/src/components/ModelViewer/theme.ts +58 -0
  176. package/src/components/ModelViewer/tokens.ts +87 -0
  177. package/src/components/ModelViewer/ui.tsx +201 -0
  178. package/src/components/ModelViewer/useDimensionSamples.spec.tsx +139 -0
  179. package/src/components/ModelViewer/useDimensionSamples.ts +220 -0
  180. package/src/components/ModelViewer/useModelSources.spec.ts +110 -0
  181. package/src/components/ModelViewer/useModelSources.ts +238 -0
  182. package/src/components/ModelViewer/useRunQuery.spec.ts +50 -0
  183. package/src/components/ModelViewer/useRunQuery.ts +223 -0
  184. package/src/components/Package/Package.agents.spec.tsx +5 -4
  185. package/src/components/Package/Package.tsx +8 -1
  186. package/src/components/ReportBuilder/emptyStart.spec.ts +8 -0
  187. package/src/components/ReportBuilder/loadMalloy.ts +8 -1
  188. package/src/components/ServerProvider.tsx +29 -3
  189. package/src/components/filter/utils.ts +4 -60
  190. package/src/components/given/FilterButton.tsx +4 -1
  191. package/src/components/given/GivenInput.tsx +8 -0
  192. package/src/components/given/GivensPanel.tsx +6 -1
  193. package/src/components/given/filterSummary.spec.ts +31 -1
  194. package/src/components/given/filterSummary.ts +41 -19
  195. package/src/components/given/useGivenUrlParams.spec.tsx +32 -0
  196. package/src/components/given/useGivenUrlParams.ts +49 -14
  197. package/src/components/index.ts +6 -1
  198. package/src/components/legacy/malloynb/Notebook.spec.tsx +38 -4
  199. package/src/components/legacy/malloynb/NotebookCell.tsx +8 -2
  200. package/src/components/modelPage.spec.ts +79 -0
  201. package/src/components/modelPage.ts +48 -0
  202. package/src/hooks/useDimensionFilters.ts +3 -58
  203. package/src/hooks/useDimensionFiltersQuery.ts +3 -58
  204. package/src/hooks/useDimensionalFilterRangeData.spec.ts +57 -0
  205. package/src/hooks/useDimensionalFilterRangeData.ts +8 -63
  206. package/src/hooks/useSuggestOptions.dom.spec.ts +54 -1
  207. package/src/hooks/useSuggestOptions.spec.ts +71 -0
  208. package/src/hooks/useSuggestOptions.ts +102 -12
  209. package/src/utils/filterCondition.spec.ts +87 -0
  210. package/src/utils/filterCondition.ts +66 -0
  211. package/src/utils/malloyLiteral.spec.ts +53 -1
  212. package/src/utils/malloyLiteral.ts +47 -12
  213. package/dist/ServerProvider-BHfg1Ed6.cjs.js +0 -1
  214. package/dist/useCompiledDocument-D7X_K6YU.cjs.js +0 -142
@@ -5,6 +5,7 @@ import { useQueries } from "@tanstack/react-query";
5
5
  import { useMemo, useRef } from "react";
6
6
  import type { Given } from "../client";
7
7
  import { withPreamble } from "../components/Dashboard/textSource";
8
+ import { malloyIdentifier } from "../components/ModelViewer/malloyRunText";
8
9
  import {
9
10
  givensToRequest,
10
11
  withHostGivens,
@@ -64,11 +65,61 @@ export interface OptionSearch {
64
65
  * products.category` is refused outright ("order_by takes the name of a field in
65
66
  * the query output, not a path"), while `group_by: products.category` names its
66
67
  * column `category`. A joined dimension is the ordinary case for a `suggest`, so
67
- * getting this wrong would have failed the option query for most of them.
68
+ * getting this wrong would have failed the option query for most of them. A
69
+ * segment the author quoted is the name inside its backticks: `` `a.b` ``
70
+ * names its column `a.b`.
68
71
  */
69
72
  function outputFieldName(dimension: string): string {
70
- const segments = dimension.split(".");
71
- return segments[segments.length - 1];
73
+ const last = pathSegments(dimension).at(-1) ?? dimension;
74
+ return /^`.*`$/.test(last)
75
+ ? last.slice(1, -1).replace(/\\(.)/g, "$1")
76
+ : last;
77
+ }
78
+
79
+ /**
80
+ * A field path's segments, split only on the dots outside backticks. One pass
81
+ * over the text, not a regular expression: the path is the author's, and an
82
+ * alternation over quoted runs backtracks without bound on one that never
83
+ * closes.
84
+ */
85
+ function pathSegments(path: string): string[] {
86
+ const segments: string[] = [];
87
+ let current = "";
88
+ let quoted = false;
89
+ for (let i = 0; i < path.length; i++) {
90
+ const char = path[i];
91
+ if (quoted && char === "\\" && i + 1 < path.length) {
92
+ current += char + path[++i];
93
+ continue;
94
+ }
95
+ if (char === "`") quoted = !quoted;
96
+ if (char === "." && !quoted) {
97
+ segments.push(current);
98
+ current = "";
99
+ continue;
100
+ }
101
+ current += char;
102
+ }
103
+ segments.push(current);
104
+ return segments;
105
+ }
106
+
107
+ /**
108
+ * A name as the query writes it: backtick-quoted, so a reserved word (`year`,
109
+ * `source`) or a name with a space is still read as a name. One the author
110
+ * already quoted is kept as written.
111
+ */
112
+ function quotedName(name: string): string {
113
+ return /^`.*`$/.test(name) ? name : malloyIdentifier(name);
114
+ }
115
+
116
+ /**
117
+ * A field path with each of its segments quoted ({@link quotedName}). Split
118
+ * only on the dots outside backticks, so a name the author quoted because it
119
+ * holds a dot (`` `a.b` ``) stays one segment.
120
+ */
121
+ function quotedPath(path: string): string {
122
+ return pathSegments(path).map(quotedName).join(".");
72
123
  }
73
124
 
74
125
  /**
@@ -84,22 +135,42 @@ export function buildSuggestQuery(
84
135
  dimension: string,
85
136
  /** Text the values must contain, ignoring case: a search of a truncated list. */
86
137
  search?: string,
138
+ options: SuggestQueryOptions = {},
87
139
  ): string {
88
140
  // One row past the limit, so a list that was cut off says so.
89
141
  const limit =
90
142
  (search === undefined ? SUGGEST_OPTION_LIMIT : SUGGEST_SEARCH_LIMIT) + 1;
143
+ const quoted = options.quoteNames === true;
144
+ const name = quoted ? quotedName : (text: string) => text;
145
+ const field = quoted ? quotedPath(dimension) : dimension;
146
+ const orderBy = quoted
147
+ ? quotedName(outputFieldName(dimension))
148
+ : (dimension.split(".").at(-1) ?? dimension);
91
149
  return (
92
- `run: ${source} -> {\n` +
93
- ` group_by: ${dimension}\n` +
150
+ `run: ${name(source)} -> {\n` +
151
+ ` group_by: ${field}\n` +
94
152
  (search === undefined
95
153
  ? ""
96
- : ` where: ${containsCondition(dimension, search)}\n`) +
97
- ` order_by: ${outputFieldName(dimension)} asc\n` +
154
+ : ` where: ${containsCondition(field, search)}\n`) +
155
+ ` order_by: ${orderBy} asc\n` +
98
156
  ` limit: ${limit}\n` +
99
157
  `}`
100
158
  );
101
159
  }
102
160
 
161
+ /** How {@link buildSuggestQuery} writes its names. */
162
+ export interface SuggestQueryOptions {
163
+ /**
164
+ * Backtick-quote every name (the source, each segment of the dimension's
165
+ * path, the output column), so a reserved word (`year`, `source`) or a name
166
+ * with a space is still read as a name. Off, the names are written as the
167
+ * `suggest` gave them, as before; a keyword then fails the query. On for a
168
+ * server whose `PUBLISHER_MODEL_PAGE` is `viewer`, and always in the model
169
+ * viewer.
170
+ */
171
+ quoteNames?: boolean;
172
+ }
173
+
103
174
  /**
104
175
  * "The dimension contains this text, ignoring case", in Malloy every dialect
105
176
  * compiles: `strpos` and `lower` are standard functions each dialect maps to
@@ -111,8 +182,8 @@ export function buildSuggestQuery(
111
182
  * Cast to string so a numeric or date dimension searches its text too. The text
112
183
  * is lowercased here, where it is known, and the column in SQL.
113
184
  */
114
- function containsCondition(dimension: string, search: string): string {
115
- return `strpos(lower(${dimension}::string), ${malloyStringLiteral(search.toLowerCase())}) > 0`;
185
+ function containsCondition(field: string, search: string): string {
186
+ return `strpos(lower(${field}::string), ${malloyStringLiteral(search.toLowerCase())}) > 0`;
116
187
  }
117
188
 
118
189
  /**
@@ -216,6 +287,18 @@ export function useSuggestOptions(
216
287
  * the viewer's own text. Absent, a suggest runs by name or by view as before.
217
288
  */
218
289
  preamble?: string,
290
+ /**
291
+ * Only these givens' options are fetched, for a page that loads a picker's
292
+ * list when it is opened rather than on render (the model viewer, where
293
+ * nothing runs until the reader asks). Absent, every picker's list is.
294
+ */
295
+ only?: ReadonlySet<string>,
296
+ /**
297
+ * Quote every name in a generated suggest query (see
298
+ * {@link SuggestQueryOptions}). Absent, the server's model page decides:
299
+ * quoted on a `viewer` server, written as given otherwise.
300
+ */
301
+ quoteNames?: boolean,
219
302
  ): {
220
303
  options: Map<string, string[]>;
221
304
  isLoading: boolean;
@@ -237,7 +320,8 @@ export function useSuggestOptions(
237
320
  /** Server search, per given, for a truncated suggest over a dimension. */
238
321
  search: Map<string, OptionSearch>;
239
322
  } {
240
- const { apiClients } = useServer();
323
+ const { apiClients, modelPage } = useServer();
324
+ const quoteSuggestNames = quoteNames ?? modelPage === "viewer";
241
325
 
242
326
  // Only a picker needs options; a text box or a slider would just be issuing
243
327
  // a query whose answer it never shows.
@@ -274,6 +358,9 @@ export function useSuggestOptions(
274
358
  givens === undefined ? null : JSON.stringify(givens),
275
359
  // Only a text source keys on its definitions, so no other key changes shape.
276
360
  ...(preamble === undefined ? [] : [preamble]),
361
+ // Quoted names are a different query: a list fetched before /status
362
+ // said viewer is asked again, quoted. The default key is unchanged.
363
+ ...(quoteSuggestNames ? ["quoteNames"] : []),
277
364
  ];
278
365
  const run = async (
279
366
  search: string | undefined,
@@ -300,6 +387,7 @@ export function useSuggestOptions(
300
387
  suggest.source as string,
301
388
  suggest.dimension as string,
302
389
  search,
390
+ { quoteNames: quoteSuggestNames },
303
391
  ),
304
392
  ),
305
393
  compactJson: true,
@@ -331,10 +419,12 @@ export function useSuggestOptions(
331
419
  });
332
420
 
333
421
  const results = useQueries({
334
- queries: suggests.map(({ identity, run }) => {
422
+ queries: suggests.map(({ spec, identity, run }) => {
335
423
  return {
336
424
  queryKey: ["givenSuggest", ...identity],
337
- enabled: modelPath !== undefined,
425
+ enabled:
426
+ modelPath !== undefined &&
427
+ (only === undefined || only.has(spec.name as string)),
338
428
  // Option lists change with the data, not with the filters, so they
339
429
  // are cached well past a single control interaction.
340
430
  staleTime: 5 * 60 * 1000,
@@ -0,0 +1,87 @@
1
+ // Copyright (c) Credible Data Inc.
2
+ // SPDX-License-Identifier: MIT
3
+
4
+ import { StringFilterExpression } from "@malloydata/malloy-filter";
5
+ import { describe, expect, it } from "bun:test";
6
+ import { generateFilterClause } from "../components/filter/utils";
7
+ import type { FilterSelection } from "../hooks/useDimensionFilters";
8
+ import { filterCondition } from "./filterCondition";
9
+
10
+ function selection(
11
+ matchType: FilterSelection["matchType"],
12
+ value: FilterSelection["value"],
13
+ value2?: FilterSelection["value2"],
14
+ ): FilterSelection {
15
+ return { dimensionName: "name", source: "items", matchType, value, value2 };
16
+ }
17
+
18
+ /** The filter a `field ~ f'…'` condition runs: Malloy hands the text between the quotes to this parser as written. */
19
+ function parsedFilter(condition: string) {
20
+ const body = /^`name` ~ f'(.*)'$/s.exec(condition)?.[1];
21
+ expect(body).toBeDefined();
22
+ return StringFilterExpression.parse(body!).parsed;
23
+ }
24
+
25
+ describe("a Contains filter", () => {
26
+ // Each of these is special in the string filter grammar: `,` separates
27
+ // alternatives, `%` and `_` are wildcards, a leading `-` negates, `\`
28
+ // escapes, and `null` is a keyword. Spliced into `%…%` as they were, "a,b"
29
+ // matched `a` and `b` but not "a,b", and "50%" also matched "500".
30
+ for (const value of [
31
+ "a,b",
32
+ "50%",
33
+ "x_y",
34
+ "-sale",
35
+ "C:\\temp",
36
+ "it's",
37
+ "null",
38
+ " pad ",
39
+ ]) {
40
+ it(`runs as one contains clause for ${JSON.stringify(value)}`, () => {
41
+ const condition = generateFilterClause(
42
+ [selection("Contains", value)],
43
+ new Map(),
44
+ "items",
45
+ );
46
+ expect(parsedFilter(condition)).toEqual({
47
+ operator: "contains",
48
+ values: [value],
49
+ });
50
+ });
51
+ }
52
+ });
53
+
54
+ describe("filterCondition", () => {
55
+ it("matches any pick of a multi-select, dates as days", () => {
56
+ expect(
57
+ filterCondition(
58
+ "`day`",
59
+ selection("Equals", [new Date(2024, 0, 5), new Date(2024, 0, 6)]),
60
+ ),
61
+ ).toBe("(`day` = @2024-01-05 or `day` = @2024-01-06)");
62
+ expect(filterCondition("`name`", selection("Equals", []))).toBe("");
63
+ expect(filterCondition("`name`", selection("Contains", ["a"]))).toBe("");
64
+ });
65
+
66
+ it("writes a date bound as a date for every comparison", () => {
67
+ const day = new Date(2024, 0, 5);
68
+ expect(filterCondition("`day`", selection("Greater Than", day))).toBe(
69
+ "`day` > @2024-01-05",
70
+ );
71
+ expect(filterCondition("`day`", selection("Before", day))).toBe(
72
+ "`day` < @2024-01-05",
73
+ );
74
+ expect(
75
+ filterCondition(
76
+ "`day`",
77
+ selection("Between", day, new Date(2024, 0, 9)),
78
+ ),
79
+ ).toBe("`day` >= @2024-01-05 and `day` <= @2024-01-09");
80
+ });
81
+
82
+ it("quotes a string value for an equality", () => {
83
+ expect(filterCondition("`name`", selection("Equals", "it's"))).toBe(
84
+ "`name` = 'it\\'s'",
85
+ );
86
+ });
87
+ });
@@ -0,0 +1,66 @@
1
+ // Copyright (c) Credible Data Inc.
2
+ // SPDX-License-Identifier: MIT
3
+
4
+ import { StringFilterExpression } from "@malloydata/malloy-filter";
5
+ import type { FilterSelection } from "../hooks/useDimensionFilters";
6
+ import { formatMalloyValue, malloyFilterLiteral } from "./malloyLiteral";
7
+
8
+ /**
9
+ * One dimension filter's selection as a Malloy condition on `fieldName` (an
10
+ * already-quoted path such as `` `name` ``), or "" when the selection says
11
+ * nothing a condition can.
12
+ *
13
+ * The one place a dimension filter's value becomes Malloy text. A "Contains"
14
+ * value is written in the string filter grammar, where `,` separates
15
+ * alternatives and `%` and `_` are wildcards, so it goes out through
16
+ * `@malloydata/malloy-filter`'s own printer rather than being spliced into
17
+ * `%…%`: spliced, "a,b" matched `a` and `b` but not "a,b", and "50%" also
18
+ * matched "500".
19
+ */
20
+ export function filterCondition(
21
+ fieldName: string,
22
+ selection: FilterSelection,
23
+ ): string {
24
+ const { matchType, value, value2 } = selection;
25
+ if (Array.isArray(value)) {
26
+ // Only a multi-select, which matches any of its picks.
27
+ if (matchType !== "Equals" && matchType !== "Semantic Search") return "";
28
+ if (value.length === 0) return "";
29
+ const conditions = value.map(
30
+ (v) => `${fieldName} = ${formatMalloyValue(v)}`,
31
+ );
32
+ return `(${conditions.join(" or ")})`;
33
+ }
34
+ switch (matchType) {
35
+ case "Equals":
36
+ case "Semantic Search":
37
+ return `${fieldName} = ${formatMalloyValue(value)}`;
38
+
39
+ case "Contains":
40
+ if (typeof value === "string") {
41
+ const filter = StringFilterExpression.unparse({
42
+ operator: "contains",
43
+ values: [value],
44
+ });
45
+ return `${fieldName} ~ ${malloyFilterLiteral(filter)}`;
46
+ }
47
+ return `${fieldName} = ${formatMalloyValue(value)}`;
48
+
49
+ case "After":
50
+ case "Greater Than":
51
+ return `${fieldName} > ${formatMalloyValue(value)}`;
52
+
53
+ case "Before":
54
+ case "Less Than":
55
+ return `${fieldName} < ${formatMalloyValue(value)}`;
56
+
57
+ case "Between":
58
+ if (value2 !== undefined) {
59
+ return `${fieldName} >= ${formatMalloyValue(value)} and ${fieldName} <= ${formatMalloyValue(value2)}`;
60
+ }
61
+ return `${fieldName} >= ${formatMalloyValue(value)}`;
62
+
63
+ default:
64
+ return "";
65
+ }
66
+ }
@@ -1,8 +1,13 @@
1
1
  // Copyright (c) Credible Data Inc.
2
2
  // SPDX-License-Identifier: MIT
3
3
 
4
+ import { StringFilterExpression } from "@malloydata/malloy-filter";
4
5
  import { describe, expect, it } from "bun:test";
5
- import { formatMalloyValue, malloyLiteral } from "./malloyLiteral";
6
+ import {
7
+ formatMalloyValue,
8
+ malloyFilterLiteral,
9
+ malloyLiteral,
10
+ } from "./malloyLiteral";
6
11
 
7
12
  describe("malloyLiteral", () => {
8
13
  it("spells a value the way its given's type reads it", () => {
@@ -40,6 +45,30 @@ describe("malloyLiteral", () => {
40
45
  expect(malloyLiteral({})).toBeUndefined();
41
46
  expect(malloyLiteral(new Date("nope"))).toBeUndefined();
42
47
  });
48
+
49
+ // Malloy passes the text inside `f'…'` to the filter parser as written, so
50
+ // the filter's own escapes have to arrive as the given carried them.
51
+ it("hands a filter given's escapes to the filter parser untouched", () => {
52
+ // The one value "a,b", as the multi-pick control encodes it.
53
+ const picked = StringFilterExpression.unparse({
54
+ operator: "=",
55
+ values: ["a,b"],
56
+ });
57
+ expect(malloyLiteral(picked, "filter<string>")).toBe("f'a\\,b'");
58
+ expect(malloyLiteral("C:\\\\temp", "filter<string>")).toBe(
59
+ "f'C:\\\\temp'",
60
+ );
61
+ });
62
+ });
63
+
64
+ describe("malloyFilterLiteral", () => {
65
+ it("escapes only a bare quote, and a trailing lone backslash", () => {
66
+ expect(malloyFilterLiteral("Nike")).toBe("f'Nike'");
67
+ expect(malloyFilterLiteral("it's")).toBe("f'it\\'s'");
68
+ expect(malloyFilterLiteral("it\\'s")).toBe("f'it\\'s'");
69
+ expect(malloyFilterLiteral("a\\,b")).toBe("f'a\\,b'");
70
+ expect(malloyFilterLiteral("a\\")).toBe("f'a\\\\'");
71
+ });
43
72
  });
44
73
 
45
74
  describe("formatMalloyValue", () => {
@@ -51,4 +80,27 @@ describe("formatMalloyValue", () => {
51
80
  expect(formatMalloyValue("2024-01-31", true)).toBe("@2024-01-31");
52
81
  expect(formatMalloyValue(new Date(2024, 0, 5), true)).toBe("@2024-01-05");
53
82
  });
83
+
84
+ it("spells a Date as a local-time day without isDate too", () => {
85
+ expect(formatMalloyValue(new Date(2024, 0, 5))).toBe("@2024-01-05");
86
+ });
87
+
88
+ it("quotes a string, even one that reads as a date", () => {
89
+ expect(formatMalloyValue("2024-01-31")).toBe("'2024-01-31'");
90
+ expect(formatMalloyValue("2024-01-31 or true")).toBe(
91
+ "'2024-01-31 or true'",
92
+ );
93
+ });
94
+
95
+ // With isDate, only an ISO date or timestamp is written after `@`: the text
96
+ // goes into the query unquoted, so anything else stays a quoted string.
97
+ it("writes a date literal from isDate only for an ISO date or timestamp", () => {
98
+ expect(formatMalloyValue("2024-01-31 09:30:00", true)).toBe(
99
+ "@2024-01-31 09:30:00",
100
+ );
101
+ expect(formatMalloyValue("2024-01-31 or true", true)).toBe(
102
+ "'2024-01-31 or true'",
103
+ );
104
+ expect(formatMalloyValue("yesterday", true)).toBe("'yesterday'");
105
+ });
54
106
  });
@@ -27,7 +27,7 @@ export function malloyLiteral(
27
27
  : type;
28
28
  switch (scalar) {
29
29
  case "filter":
30
- return `f${quote(String(value))}`;
30
+ return malloyFilterLiteral(String(value));
31
31
  case "string":
32
32
  return quote(String(value));
33
33
  case "number": {
@@ -66,6 +66,30 @@ function inferredType(value: unknown): string | undefined {
66
66
  return undefined;
67
67
  }
68
68
 
69
+ /**
70
+ * Filter text as a Malloy filter literal: `f'…'`.
71
+ *
72
+ * Malloy hands the text between the quotes to the filter parser as written, so
73
+ * the filter grammar's own escapes (`\,` for a comma that is part of a value,
74
+ * `\%` for a percent sign) have to reach it untouched. Only a quote the text
75
+ * leaves bare is escaped, and a lone trailing backslash is doubled so it cannot
76
+ * swallow the closing quote. Escaping filter text the way a string literal is
77
+ * escaped doubles every backslash, and `a\,b`, the one value "a,b", runs as
78
+ * "a\" or "b".
79
+ */
80
+ export function malloyFilterLiteral(filter: string): string {
81
+ let body = "";
82
+ for (let i = 0; i < filter.length; i++) {
83
+ const char = filter[i];
84
+ if (char === "\\") {
85
+ body += i + 1 < filter.length ? char + filter[++i] : "\\\\";
86
+ } else {
87
+ body += char === "'" ? "\\'" : char;
88
+ }
89
+ }
90
+ return `f'${body}'`;
91
+ }
92
+
69
93
  /** `2024-01-31` out of a Date (UTC) or an ISO-ish string, else undefined. */
70
94
  function datePart(value: unknown): string | undefined {
71
95
  if (value instanceof Date)
@@ -75,7 +99,18 @@ function datePart(value: unknown): string | undefined {
75
99
  return /^(\d{4}-\d{2}-\d{2})/.exec(String(value))?.[1];
76
100
  }
77
101
 
78
- /** A filter value as a Malloy literal; unlike `malloyLiteral`, a Date is spelled as a local-time day. */
102
+ /** An ISO date or timestamp, the only text a Malloy `@` literal is written from. */
103
+ const ISO_DATE_OR_TIMESTAMP =
104
+ /^\d{4}-\d{2}-\d{2}(?:[ T]\d{2}:\d{2}(?::\d{2}(?:\.\d+)?)?)?$/;
105
+
106
+ /**
107
+ * A filter value as a Malloy literal; unlike `malloyLiteral`, a Date is spelled
108
+ * as a local-time day. A string is a quoted string, whatever it holds, except
109
+ * where `isDate` says the dimension is a date and the string is an ISO date or
110
+ * timestamp, which is written as a date literal (`@2024-01-31`). Any other
111
+ * string stays quoted with `isDate` too: written after `@` unquoted, a value
112
+ * like `2024-01-31 or true` became Malloy.
113
+ */
79
114
  export function formatMalloyValue(
80
115
  value: string | number | boolean | Date | null | undefined,
81
116
  isDate: boolean = false,
@@ -84,11 +119,15 @@ export function formatMalloyValue(
84
119
  return "null";
85
120
  }
86
121
 
87
- if (isDate) {
88
- if (value instanceof Date) {
89
- return `@${value.getFullYear()}-${String(value.getMonth() + 1).padStart(2, "0")}-${String(value.getDate()).padStart(2, "0")}`;
90
- }
91
- // A string is assumed to already be ISO.
122
+ if (value instanceof Date) {
123
+ return `@${value.getFullYear()}-${String(value.getMonth() + 1).padStart(2, "0")}-${String(value.getDate()).padStart(2, "0")}`;
124
+ }
125
+
126
+ if (
127
+ isDate &&
128
+ typeof value === "string" &&
129
+ ISO_DATE_OR_TIMESTAMP.test(value)
130
+ ) {
92
131
  return `@${value}`;
93
132
  }
94
133
 
@@ -100,9 +139,5 @@ export function formatMalloyValue(
100
139
  return String(value);
101
140
  }
102
141
 
103
- if (typeof value === "boolean") {
104
- return value ? "true" : "false";
105
- }
106
-
107
- return String(value);
142
+ return value ? "true" : "false";
108
143
  }