@malloy-publisher/sdk 0.3.0 → 0.3.1

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 (156) hide show
  1. package/README.md +8 -0
  2. package/dist/DocumentStorageProvider-BeBD0uWc.cjs.js +134 -0
  3. package/dist/DocumentStorageProvider-tGvodI8f.es.js +24268 -0
  4. package/dist/RenderedResult-CPi6uQWq.cjs.js +115 -0
  5. package/dist/RenderedResult-mDE-4u8S.es.js +542 -0
  6. package/dist/ServerProvider-CH71GsoL.cjs.js +1 -0
  7. package/dist/{ServerProvider-DSK9rfSY.es.js → ServerProvider-X2Ma0HRs.es.js} +486 -521
  8. package/dist/builder/index.cjs.js +105 -0
  9. package/dist/builder/index.d.ts +2 -0
  10. package/dist/builder/index.es.js +9561 -0
  11. package/dist/builder-entry.d.ts +8 -0
  12. package/dist/client/index.cjs.js +1 -1
  13. package/dist/client/index.es.js +1 -1
  14. package/dist/components/Dashboard/Dashboard.d.ts +19 -14
  15. package/dist/components/Dashboard/DashboardGrid.d.ts +67 -0
  16. package/dist/components/Dashboard/DashboardTile.d.ts +6 -1
  17. package/dist/components/Dashboard/ExploreDialog.d.ts +18 -0
  18. package/dist/components/Dashboard/RowsDialog.d.ts +47 -0
  19. package/dist/components/Dashboard/TileCard.d.ts +44 -0
  20. package/dist/components/Dashboard/index.d.ts +2 -0
  21. package/dist/components/Dashboard/promoteMeasureRow.d.ts +7 -3
  22. package/dist/components/Dashboard/telemetry.d.ts +43 -0
  23. package/dist/components/DashboardBuilder/AddTileDialog.d.ts +35 -0
  24. package/dist/components/DashboardBuilder/BuilderToolbar.d.ts +29 -0
  25. package/dist/components/DashboardBuilder/DashboardBuilder.d.ts +112 -0
  26. package/dist/components/DashboardBuilder/DashboardEditor.d.ts +32 -0
  27. package/dist/components/DashboardBuilder/DiffDialog.d.ts +15 -0
  28. package/dist/components/DashboardBuilder/DrillDialog.d.ts +15 -0
  29. package/dist/components/DashboardBuilder/FilterDialog.d.ts +54 -0
  30. package/dist/components/DashboardBuilder/FilterStrip.d.ts +17 -0
  31. package/dist/components/DashboardBuilder/SettingsPopover.d.ts +20 -0
  32. package/dist/components/DashboardBuilder/TileFrame.d.ts +42 -0
  33. package/dist/components/DashboardBuilder/TileMenu.d.ts +24 -0
  34. package/dist/components/DashboardBuilder/catalog.d.ts +62 -0
  35. package/dist/components/DashboardBuilder/controls.d.ts +157 -0
  36. package/dist/components/DashboardBuilder/diff.d.ts +35 -0
  37. package/dist/components/DashboardBuilder/document.d.ts +218 -0
  38. package/dist/components/DashboardBuilder/layout.d.ts +71 -0
  39. package/dist/components/DashboardBuilder/malloyText.d.ts +45 -0
  40. package/dist/components/DashboardBuilder/preview.d.ts +60 -0
  41. package/dist/components/DashboardBuilder/readDocument.d.ts +106 -0
  42. package/dist/components/DashboardBuilder/sortable.d.ts +51 -0
  43. package/dist/components/DashboardBuilder/spliceDocument.d.ts +44 -0
  44. package/dist/components/DashboardBuilder/testing/fixtures.d.ts +10 -0
  45. package/dist/components/DashboardBuilder/useBuilderShortcuts.d.ts +22 -0
  46. package/dist/components/DashboardBuilder/useDashboardEditor.d.ts +63 -0
  47. package/dist/components/DashboardBuilder/useDraft.d.ts +13 -0
  48. package/dist/components/DashboardBuilder/useFilterForm.d.ts +65 -0
  49. package/dist/components/DashboardBuilder/useTileReorder.d.ts +22 -0
  50. package/dist/components/DashboardBuilder/useTileResize.d.ts +29 -0
  51. package/dist/components/DocumentStorage/DocumentStorageProvider.d.ts +7 -0
  52. package/dist/components/DocumentStorage/index.d.ts +1 -1
  53. package/dist/components/FloatingIconButton.d.ts +16 -0
  54. package/dist/components/Prose.d.ts +46 -0
  55. package/dist/components/RenderedResult/ResultPanel.d.ts +30 -0
  56. package/dist/components/RenderedResult/index.d.ts +1 -0
  57. package/dist/components/drill/index.d.ts +1 -1
  58. package/dist/components/drill/resolveDrill.d.ts +22 -0
  59. package/dist/components/drill/useDrill.d.ts +11 -2
  60. package/dist/components/index.d.ts +1 -0
  61. package/dist/components/styles.d.ts +0 -4
  62. package/dist/hooks/index.d.ts +2 -0
  63. package/dist/hooks/useDocumentControls.d.ts +70 -0
  64. package/dist/hooks/useQueryResult.d.ts +40 -0
  65. package/dist/index.cjs.js +23 -270
  66. package/dist/index.es.js +16977 -41293
  67. package/dist/utils/malloyLiteral.d.ts +11 -0
  68. package/package.json +24 -9
  69. package/src/builder-entry.ts +55 -0
  70. package/src/components/Dashboard/Dashboard.spec.tsx +7 -10
  71. package/src/components/Dashboard/Dashboard.tsx +165 -175
  72. package/src/components/Dashboard/DashboardGrid.tsx +124 -0
  73. package/src/components/Dashboard/DashboardTile.spec.tsx +30 -6
  74. package/src/components/Dashboard/DashboardTile.tsx +66 -123
  75. package/src/components/Dashboard/ExploreDialog.tsx +84 -0
  76. package/src/components/Dashboard/RowsDialog.spec.ts +42 -0
  77. package/src/components/Dashboard/RowsDialog.tsx +234 -0
  78. package/src/components/Dashboard/TileCard.tsx +120 -0
  79. package/src/components/Dashboard/index.ts +2 -0
  80. package/src/components/Dashboard/promoteMeasureRow.spec.ts +70 -0
  81. package/src/components/Dashboard/promoteMeasureRow.ts +33 -2
  82. package/src/components/Dashboard/telemetry.ts +44 -0
  83. package/src/components/Dashboard/tileGridColumn.spec.ts +1 -1
  84. package/src/components/DashboardBuilder/AddTileDialog.tsx +249 -0
  85. package/src/components/DashboardBuilder/BuilderToolbar.tsx +270 -0
  86. package/src/components/DashboardBuilder/DashboardBuilder.spec.tsx +858 -0
  87. package/src/components/DashboardBuilder/DashboardBuilder.tsx +653 -0
  88. package/src/components/DashboardBuilder/DashboardEditor.spec.tsx +211 -0
  89. package/src/components/DashboardBuilder/DashboardEditor.tsx +493 -0
  90. package/src/components/DashboardBuilder/DiffDialog.tsx +129 -0
  91. package/src/components/DashboardBuilder/DrillDialog.tsx +281 -0
  92. package/src/components/DashboardBuilder/FilterDialog.tsx +581 -0
  93. package/src/components/DashboardBuilder/FilterStrip.tsx +125 -0
  94. package/src/components/DashboardBuilder/SettingsPopover.tsx +168 -0
  95. package/src/components/DashboardBuilder/TileFrame.tsx +380 -0
  96. package/src/components/DashboardBuilder/TileMenu.tsx +188 -0
  97. package/src/components/DashboardBuilder/catalog.spec.ts +215 -0
  98. package/src/components/DashboardBuilder/catalog.ts +225 -0
  99. package/src/components/DashboardBuilder/controls.spec.ts +243 -0
  100. package/src/components/DashboardBuilder/controls.ts +398 -0
  101. package/src/components/DashboardBuilder/diff.spec.ts +44 -0
  102. package/src/components/DashboardBuilder/diff.ts +93 -0
  103. package/src/components/DashboardBuilder/document.ts +209 -0
  104. package/src/components/DashboardBuilder/keepRowStructure.spec.ts +84 -0
  105. package/src/components/DashboardBuilder/layout.ts +143 -0
  106. package/src/components/DashboardBuilder/malloyText.spec.ts +84 -0
  107. package/src/components/DashboardBuilder/malloyText.ts +151 -0
  108. package/src/components/DashboardBuilder/moveIntoGap.spec.ts +90 -0
  109. package/src/components/DashboardBuilder/preview.spec.ts +149 -0
  110. package/src/components/DashboardBuilder/preview.ts +172 -0
  111. package/src/components/DashboardBuilder/readDocument.spec.ts +375 -0
  112. package/src/components/DashboardBuilder/readDocument.ts +467 -0
  113. package/src/components/DashboardBuilder/sortable.tsx +151 -0
  114. package/src/components/DashboardBuilder/spliceDocument.spec.ts +1108 -0
  115. package/src/components/DashboardBuilder/spliceDocument.ts +1098 -0
  116. package/src/components/DashboardBuilder/testing/fixtures.ts +48 -0
  117. package/src/components/DashboardBuilder/useBuilderShortcuts.ts +88 -0
  118. package/src/components/DashboardBuilder/useDashboardEditor.spec.ts +255 -0
  119. package/src/components/DashboardBuilder/useDashboardEditor.ts +193 -0
  120. package/src/components/DashboardBuilder/useDraft.ts +43 -0
  121. package/src/components/DashboardBuilder/useFilterForm.spec.tsx +144 -0
  122. package/src/components/DashboardBuilder/useFilterForm.ts +352 -0
  123. package/src/components/DashboardBuilder/useTileReorder.spec.tsx +97 -0
  124. package/src/components/DashboardBuilder/useTileReorder.ts +115 -0
  125. package/src/components/DashboardBuilder/useTileResize.spec.tsx +121 -0
  126. package/src/components/DashboardBuilder/useTileResize.ts +110 -0
  127. package/src/components/DashboardBuilder/withGaps.spec.ts +96 -0
  128. package/src/components/DocumentStorage/DocumentStorageProvider.tsx +12 -0
  129. package/src/components/DocumentStorage/index.ts +1 -0
  130. package/src/components/Environment/About.tsx +4 -36
  131. package/src/components/FloatingIconButton.tsx +41 -0
  132. package/src/components/Model/Model.tsx +6 -23
  133. package/src/components/Model/ModelCell.tsx +33 -72
  134. package/src/components/Notebook/Notebook.tsx +25 -88
  135. package/src/components/Notebook/NotebookCell.tsx +35 -183
  136. package/src/components/Prose.spec.tsx +85 -0
  137. package/src/components/Prose.tsx +179 -0
  138. package/src/components/QueryResult/QueryResult.tsx +15 -43
  139. package/src/components/RenderedResult/ResultContainer.tsx +4 -12
  140. package/src/components/RenderedResult/ResultPanel.spec.tsx +49 -0
  141. package/src/components/RenderedResult/ResultPanel.tsx +73 -0
  142. package/src/components/RenderedResult/index.ts +1 -0
  143. package/src/components/drill/index.ts +1 -0
  144. package/src/components/drill/resolveDrill.ts +22 -1
  145. package/src/components/drill/useDrill.spec.tsx +94 -0
  146. package/src/components/drill/useDrill.tsx +52 -12
  147. package/src/components/given/GivensPanel.tsx +1 -1
  148. package/src/components/index.ts +6 -0
  149. package/src/components/styles.ts +0 -37
  150. package/src/hooks/index.ts +13 -0
  151. package/src/hooks/useDocumentControls.ts +170 -0
  152. package/src/hooks/useQueryResult.ts +82 -0
  153. package/src/utils/malloyLiteral.spec.ts +43 -0
  154. package/src/utils/malloyLiteral.ts +76 -0
  155. package/vite.config.ts +5 -0
  156. package/dist/ServerProvider-CGnLjzag.cjs.js +0 -1
@@ -8,11 +8,14 @@ import {
8
8
  DRILL_SELF,
9
9
  drillDestinations,
10
10
  drillGivenName,
11
+ drillValueLabel,
12
+ drillValueToFilter,
11
13
  humanizeSlug,
12
14
  resolveDrill,
13
15
  type DrillClickPayload,
14
16
  type DrillIntent,
15
17
  type DrillNavigation,
18
+ type DrillRowsRequest,
16
19
  } from "./resolveDrill";
17
20
 
18
21
  export interface UseDrillOptions {
@@ -43,6 +46,15 @@ export interface UseDrillOptions {
43
46
  * cannot know which document the reader is in, so the surface names itself.
44
47
  */
45
48
  selfLabel?: string;
49
+ /**
50
+ * Show the rows behind a grouped value. With it, EVERY dimension cell is
51
+ * clickable: one with no `# drill` this surface can honour opens the rows;
52
+ * one with a drill behaves exactly as it does without this option, since a
53
+ * drill is the author's own instruction for that value. Omitted on a
54
+ * surface with nowhere to show them, and cells then click only where a tag
55
+ * says so.
56
+ */
57
+ onRows?: (request: DrillRowsRequest) => void;
46
58
  }
47
59
 
48
60
  /**
@@ -70,11 +82,12 @@ export interface UseDrillResult {
70
82
  }
71
83
 
72
84
  interface DrillMenuState {
73
- intent: DrillIntent;
85
+ intent?: DrillIntent;
74
86
  destinations: string[];
75
87
  event?: MouseEvent;
76
88
  top: number;
77
89
  left: number;
90
+ label: string;
78
91
  }
79
92
 
80
93
  /**
@@ -91,6 +104,7 @@ export function useDrill({
91
104
  onSelf,
92
105
  selfLabel = "Filter this view",
93
106
  canSelf,
107
+ onRows,
94
108
  }: UseDrillOptions): UseDrillResult {
95
109
  // A cell inside the renderer's own DOM is the anchor, and this component
96
110
  // holds no ref to it, so the menu is positioned from the click coordinates.
@@ -128,35 +142,60 @@ export function useDrill({
128
142
  [onNavigate, onSelf],
129
143
  );
130
144
 
145
+ // The rows behind this click, when the surface shows rows and the click is
146
+ // on a grouped value. A header names the field and has no value; a measure
147
+ // has no rows of its own; an empty cell is more likely a misclick.
148
+ const rowsBehind = useCallback(
149
+ (payload: DrillClickPayload): DrillRowsRequest | undefined => {
150
+ if (!onRows || payload.isHeader || !payload.field) return undefined;
151
+ if (!(payload.field.wasDimension?.() ?? false)) return undefined;
152
+ if (drillValueToFilter(payload.value) === undefined) return undefined;
153
+ return {
154
+ field: payload.field.name,
155
+ rawValue: payload.value,
156
+ label: drillValueLabel(payload.value),
157
+ ...(payload.context === undefined
158
+ ? {}
159
+ : { context: payload.context }),
160
+ };
161
+ },
162
+ [onRows],
163
+ );
164
+
131
165
  const onClick = useCallback(
132
166
  (payload: DrillClickPayload) => {
133
167
  // Runs on every cell click, so "not a drill" is the ordinary answer.
134
168
  const intent = resolveDrill(payload);
135
- if (!intent) return;
136
-
169
+ const rows = rowsBehind(payload);
137
170
  // Offer only what this surface can actually do, so a menu never lists a
138
171
  // destination that would be a no-op when picked.
139
- const destinations = honorable(intent.to, intent.given);
140
- if (destinations.length === 0) return;
141
- if (destinations.length === 1) {
172
+ const destinations = intent ? honorable(intent.to, intent.given) : [];
173
+ if (destinations.length === 0) {
174
+ if (rows) onRows?.(rows);
175
+ return;
176
+ }
177
+ if (destinations.length === 1 && intent) {
142
178
  go(intent, destinations[0], payload.event);
143
179
  return;
144
180
  }
145
181
  setMenu({
146
- intent,
182
+ ...(intent ? { intent } : {}),
147
183
  destinations,
148
184
  event: payload.event,
149
185
  top: payload.event?.clientY ?? 0,
150
186
  left: payload.event?.clientX ?? 0,
187
+ label: intent?.label ?? rows?.label ?? "",
151
188
  });
152
189
  },
153
- [go, honorable],
190
+ [go, honorable, onRows, rowsBehind],
154
191
  );
155
192
 
156
193
  const canDrill = useCallback(
157
194
  (field: DrillField) =>
158
- honorable(drillDestinations(field), drillGivenName(field)).length > 0,
159
- [honorable],
195
+ honorable(drillDestinations(field), drillGivenName(field)).length >
196
+ 0 ||
197
+ (onRows !== undefined && (field.wasDimension?.() ?? false)),
198
+ [honorable, onRows],
160
199
  );
161
200
 
162
201
  const drill = useMemo<DrillBinding>(
@@ -176,7 +215,7 @@ export function useDrill({
176
215
  anchorPosition={{ top: menu?.top ?? 0, left: menu?.left ?? 0 }}
177
216
  >
178
217
  <ListSubheader sx={{ lineHeight: "32px" }}>
179
- {menu ? `${menu.intent.label} →` : ""}
218
+ {menu ? `${menu.label} →` : ""}
180
219
  </ListSubheader>
181
220
  {/* Deduplicated: `# drill { to=[overview, overview] }` is a typo
182
221
  rather than a request for two identical rows, and React keys
@@ -188,7 +227,8 @@ export function useDrill({
188
227
  key={destination}
189
228
  onClick={() => {
190
229
  close();
191
- if (menu) go(menu.intent, destination, menu.event);
230
+ if (menu?.intent)
231
+ go(menu.intent, destination, menu.event);
192
232
  }}
193
233
  >
194
234
  {destination === DRILL_SELF
@@ -166,7 +166,7 @@ export function GivensPanel({
166
166
  >
167
167
  <Typography
168
168
  variant="subtitle2"
169
- sx={{ fontWeight: 600, color: "#333" }}
169
+ sx={{ fontWeight: 600, color: "text.primary" }}
170
170
  >
171
171
  {title ?? "Parameters"}
172
172
  </Typography>
@@ -18,6 +18,12 @@ export * from "./Materializations";
18
18
  export * from "./Model";
19
19
  export * from "./Notebook";
20
20
  export * from "./Package";
21
+ export {
22
+ Prose,
23
+ type ProseLinkContext,
24
+ type ProseProps,
25
+ type ProseVariant,
26
+ } from "./Prose";
21
27
  export * from "./QueryResult";
22
28
  export * from "./RenderedResult";
23
29
  export { ServerProvider, useServer } from "./ServerProvider";
@@ -85,12 +85,6 @@ export const CleanNotebookContainer = styled("div")(({ theme }) => ({
85
85
  margin: "0 auto",
86
86
  }));
87
87
 
88
- export const CleanNotebookHeader = styled("div")(({ theme }) => ({
89
- marginBottom: "40px",
90
- paddingBottom: "24px",
91
- borderBottom: `1px solid ${theme.palette.divider}`,
92
- }));
93
-
94
88
  export const CleanNotebookSection = styled("div")({
95
89
  marginBottom: "48px",
96
90
  padding: "0",
@@ -99,14 +93,6 @@ export const CleanNotebookSection = styled("div")({
99
93
  boxShadow: "none",
100
94
  });
101
95
 
102
- export const CleanNotebookCell = styled("div")({
103
- marginBottom: "0",
104
- padding: "0",
105
- backgroundColor: "transparent",
106
- border: "none",
107
- boxShadow: "none",
108
- });
109
-
110
96
  export const CleanMetricCard = styled("div")({
111
97
  backgroundColor: "transparent",
112
98
  paddingTop: "12px",
@@ -117,29 +103,6 @@ export const CleanMetricCard = styled("div")({
117
103
  marginBottom: "0",
118
104
  });
119
105
 
120
- export const CleanCodeBlock = styled("div")(({ theme }) => ({
121
- backgroundColor: theme.palette.mode === "dark" ? "#1e293b" : "#f8f9fa",
122
- padding: "16px",
123
- borderRadius: "8px",
124
- border: `1px solid ${theme.palette.divider}`,
125
- fontFamily: "'Monaco', 'Menlo', 'Ubuntu Mono', monospace",
126
- fontSize: "13px",
127
- lineHeight: "1.5",
128
- overflowX: "auto",
129
- color: theme.palette.text.primary,
130
- }));
131
-
132
- export const CleanActionBar = styled("div")(({ theme }) => ({
133
- backgroundColor: theme.palette.mode === "dark" ? "#1e293b" : "#f8f9fa",
134
- padding: "12px 16px",
135
- borderRadius: "8px",
136
- border: `1px solid ${theme.palette.divider}`,
137
- marginBottom: "16px",
138
- display: "flex",
139
- justifyContent: "space-between",
140
- alignItems: "center",
141
- }));
142
-
143
106
  export const StyledExplorerPage = styled("div")({
144
107
  height: "100%",
145
108
  });
@@ -43,3 +43,16 @@ export {
43
43
  type UseGivensStateResult,
44
44
  } from "./useGivensState";
45
45
  export { useSuggestOptions } from "./useSuggestOptions";
46
+
47
+ // One query, and one control row, as every surface asks for them
48
+ export {
49
+ queryResultKey,
50
+ useQueryResult,
51
+ type QueryRequestSpec,
52
+ type QueryResultState,
53
+ } from "./useQueryResult";
54
+ export {
55
+ useDocumentControls,
56
+ type DocumentControls,
57
+ type UseDocumentControlsOptions,
58
+ } from "./useDocumentControls";
@@ -0,0 +1,170 @@
1
+ // Copyright (c) Credible Data Inc.
2
+ // SPDX-License-Identifier: MIT
3
+
4
+ import { useCallback, useMemo } from "react";
5
+ import type { Given } from "../client";
6
+ import { useDrillSelf } from "../components/drill/useDrillSelf";
7
+ import type { GivensPanelProps } from "../components/given/GivensPanel";
8
+ import { useGivensState, type UseGivensStateResult } from "./useGivensState";
9
+ import { useSuggestOptions } from "./useSuggestOptions";
10
+
11
+ /**
12
+ * Everything a document's control row needs, from what the document declares.
13
+ *
14
+ * A dashboard, a notebook and the builder's harness each wired this by hand:
15
+ * the declared types read off the givens, the report to the host guarded on the
16
+ * document having loaded, `useGivensState`, `useSuggestOptions` for the pickers'
17
+ * options, `useDrillSelf` for `to=self`, and the same nine props into
18
+ * `GivensPanel`. Sixty lines each, with the same reasoning in the comments of
19
+ * each. This is that wiring once, so a control gains a behaviour on every
20
+ * surface at the same time.
21
+ */
22
+ export interface UseDocumentControlsOptions {
23
+ /** The document's declared givens. Empty until it has loaded. */
24
+ specs: Given[];
25
+ /**
26
+ * Whether the document has loaded. Reports to the host are WITHHELD until
27
+ * it has: before then the declared set is empty, so a report would say "no
28
+ * values, and I manage nothing", which a host reasonably reads as "clear
29
+ * what you wrote" — and during an in-app move from one document to the next
30
+ * that window sits between the two, so the parameters it would clear belong
31
+ * to the document now arriving. A document that genuinely declares no givens
32
+ * still reports, because by then the empty set is the answer rather than
33
+ * the absence of one.
34
+ */
35
+ loaded: boolean;
36
+ /** Where the controls start, from the file. A URL beats them. */
37
+ startingValues?: Record<string, string>;
38
+ /** Control values from the host, typically its URL query parameters. */
39
+ params?: Record<string, string>;
40
+ /**
41
+ * Applied values, for a host that wants them in its URL, with every name
42
+ * this document manages — `givens` alone says which parameters to write but
43
+ * not which to remove.
44
+ */
45
+ onGivensChange?: (
46
+ givens: Record<string, string>,
47
+ managed: readonly string[],
48
+ ) => void;
49
+ /**
50
+ * Which document the edits belong to. Without it the edits are keyed by
51
+ * their starting VALUES alone, so two documents whose starting values
52
+ * coincide (the common case: both empty) look like one, and the one you came
53
+ * from keeps filtering the one you moved to. The version belongs in it too,
54
+ * so a swap between versions drops the edits made to the other.
55
+ */
56
+ documentKey: string;
57
+ /** False batches changes behind Apply. */
58
+ autorun: boolean;
59
+ /** Where `suggest` queries run: the document's own model. */
60
+ environmentName: string;
61
+ packageName: string;
62
+ modelPath: string | undefined;
63
+ versionId?: string;
64
+ /** How the document names itself in a refused-drill warning. */
65
+ documentName: string;
66
+ }
67
+
68
+ export interface DocumentControls extends UseGivensStateResult {
69
+ /** Declared type per given name: what this document can set and how a value is encoded. */
70
+ declaredTypes: ReadonlyMap<string, string | undefined>;
71
+ options: Map<string, string[]>;
72
+ optionsLoading: boolean;
73
+ optionsFailed: ReadonlySet<string>;
74
+ /** For `useDrill`: whether a `to=self` on this given can be honoured. */
75
+ canSelf: (given: string) => boolean;
76
+ /** For `useDrill`: set the given to the clicked value, encoded for its type. */
77
+ onSelf: (given: string, rawValue: unknown) => void;
78
+ /** Everything `GivensPanel` takes except its layout: spread it in. */
79
+ panel: Omit<GivensPanelProps, "layout" | "title">;
80
+ }
81
+
82
+ export function useDocumentControls({
83
+ specs,
84
+ loaded,
85
+ startingValues,
86
+ params,
87
+ onGivensChange,
88
+ documentKey,
89
+ autorun,
90
+ environmentName,
91
+ packageName,
92
+ modelPath,
93
+ versionId,
94
+ documentName,
95
+ }: UseDocumentControlsOptions): DocumentControls {
96
+ const declaredTypes = useMemo(
97
+ () =>
98
+ new Map(
99
+ specs
100
+ .filter((spec) => spec.name !== undefined)
101
+ .map((spec) => [spec.name as string, spec.type]),
102
+ ),
103
+ [specs],
104
+ );
105
+
106
+ const report = useCallback(
107
+ (next: Record<string, string>) => {
108
+ if (!loaded) return;
109
+ onGivensChange?.(next, Array.from(declaredTypes.keys()));
110
+ },
111
+ [loaded, onGivensChange, declaredTypes],
112
+ );
113
+
114
+ const state = useGivensState({
115
+ declaredTypes,
116
+ startingValues,
117
+ params,
118
+ // Withheld, not accepted and dropped: `useGivensState` records what it
119
+ // last reported BEFORE calling out, so a report the callback threw away
120
+ // would be remembered as delivered and never retried, leaving a parameter
121
+ // stranded in the host's URL. Passing undefined skips the report and
122
+ // leaves its record untouched.
123
+ onParamsChange: loaded ? report : undefined,
124
+ documentKey,
125
+ autorun,
126
+ });
127
+
128
+ const {
129
+ options,
130
+ isLoading: optionsLoading,
131
+ failed: optionsFailed,
132
+ } = useSuggestOptions(
133
+ environmentName,
134
+ packageName,
135
+ modelPath,
136
+ specs,
137
+ versionId,
138
+ // So a suggest over a gated or scoped source carries the givens it needs.
139
+ { values: state.applied, declaredTypes },
140
+ );
141
+
142
+ const { canSelf, onSelf } = useDrillSelf({
143
+ declaredTypes,
144
+ setGiven: state.setGiven,
145
+ documentName,
146
+ });
147
+
148
+ return {
149
+ ...state,
150
+ declaredTypes,
151
+ options,
152
+ optionsLoading,
153
+ optionsFailed,
154
+ canSelf,
155
+ onSelf,
156
+ panel: {
157
+ givens: specs,
158
+ values: state.draft,
159
+ onChange: state.setGiven,
160
+ onReset: state.reset,
161
+ options,
162
+ optionsLoading,
163
+ optionsFailed,
164
+ // Absent means autorun; only an explicit `false` batches behind Apply.
165
+ apply: autorun
166
+ ? undefined
167
+ : { onApply: state.apply, pending: state.pending },
168
+ },
169
+ };
170
+ }
@@ -0,0 +1,82 @@
1
+ // Copyright (c) Credible Data Inc.
2
+ // SPDX-License-Identifier: MIT
3
+
4
+ import type { QueryKey } from "@tanstack/react-query";
5
+ import { useServer } from "../components/ServerProvider";
6
+ import { CHART_RESULT_QUERY_OPTIONS } from "../utils/queryClient";
7
+ import { useQueryWithApiError } from "./useQueryWithApiError";
8
+
9
+ /**
10
+ * One query against one model, as every result surface asks for it.
11
+ *
12
+ * A dashboard tile, a model page's named query and an embedded `QueryResult`
13
+ * each ran a query through `executeQueryModel` with their own copy of the
14
+ * request, their own cache key and their own loading and error states — three
15
+ * spellings of one thing, and one of them (the model cell) had no error state
16
+ * at all. This is the request and the key; `ResultPanel` is the states.
17
+ */
18
+ export interface QueryRequestSpec {
19
+ environmentName: string;
20
+ packageName: string;
21
+ modelPath: string;
22
+ /** The package version the caller's URI named, when it named one. */
23
+ versionId?: string;
24
+ /** A named query on the model. */
25
+ queryName?: string;
26
+ /** A run expression: `run: source -> view`. */
27
+ query?: string;
28
+ sourceName?: string;
29
+ /** The applied control values this query reads, already encoded. */
30
+ givens?: Record<string, unknown>;
31
+ }
32
+
33
+ /**
34
+ * The cache key: every value the request is built from, in a fixed order, so
35
+ * the key cannot drift out of step with the request. A version that reached
36
+ * the request alone would leave two versions of one query on a single cache
37
+ * entry, each able to serve the other's result. `useQueryWithApiError` appends
38
+ * the server, so one key never spans two of them.
39
+ */
40
+ export function queryResultKey(spec: QueryRequestSpec): QueryKey {
41
+ return [
42
+ "queryResult",
43
+ spec.environmentName,
44
+ spec.packageName,
45
+ spec.versionId,
46
+ spec.modelPath,
47
+ spec.queryName,
48
+ spec.query,
49
+ spec.sourceName,
50
+ // Re-runs when the applied values change, which is the whole point of a
51
+ // control row.
52
+ JSON.stringify(spec.givens ?? {}),
53
+ ];
54
+ }
55
+
56
+ export function useQueryResult(
57
+ spec: QueryRequestSpec,
58
+ { enabled = true }: { enabled?: boolean } = {},
59
+ ) {
60
+ const { apiClients } = useServer();
61
+ return useQueryWithApiError({
62
+ queryKey: queryResultKey(spec),
63
+ queryFn: () =>
64
+ apiClients.models.executeQueryModel(
65
+ spec.environmentName,
66
+ spec.packageName,
67
+ spec.modelPath,
68
+ {
69
+ queryName: spec.queryName,
70
+ query: spec.query,
71
+ sourceName: spec.sourceName,
72
+ givens: spec.givens,
73
+ versionId: spec.versionId,
74
+ },
75
+ ),
76
+ enabled,
77
+ ...CHART_RESULT_QUERY_OPTIONS,
78
+ });
79
+ }
80
+
81
+ /** What a result surface holds while a query runs: hand it to `ResultPanel`. */
82
+ export type QueryResultState = ReturnType<typeof useQueryResult>;
@@ -0,0 +1,43 @@
1
+ // Copyright (c) Credible Data Inc.
2
+ // SPDX-License-Identifier: MIT
3
+
4
+ import { describe, expect, it } from "bun:test";
5
+ import { malloyLiteral } from "./malloyLiteral";
6
+
7
+ describe("malloyLiteral", () => {
8
+ it("spells a value the way its given's type reads it", () => {
9
+ expect(malloyLiteral("Nike", "filter<string>")).toBe("f'Nike'");
10
+ expect(malloyLiteral(">= 10", "filter<number>")).toBe("f'>= 10'");
11
+ expect(malloyLiteral("O'Neil", "string")).toBe("'O\\'Neil'");
12
+ expect(malloyLiteral("42", "number")).toBe("42");
13
+ expect(malloyLiteral("forty", "number")).toBeUndefined();
14
+ expect(malloyLiteral(true, "boolean")).toBe("true");
15
+ expect(malloyLiteral("2024-01-31", "date")).toBe("@2024-01-31");
16
+ expect(malloyLiteral(new Date("2024-01-31T09:30:00Z"), "timestamp")).toBe(
17
+ "@2024-01-31 09:30:00",
18
+ );
19
+ });
20
+
21
+ it("spells a value by its own type when no given is involved", () => {
22
+ expect(malloyLiteral("Jeans")).toBe("'Jeans'");
23
+ expect(malloyLiteral("Ben's & Jerry\\s")).toBe("'Ben\\'s & Jerry\\\\s'");
24
+ expect(malloyLiteral(42)).toBe("42");
25
+ expect(malloyLiteral(true)).toBe("true");
26
+ expect(malloyLiteral(new Date("2024-03-05T00:00:00Z"))).toBe(
27
+ "@2024-03-05",
28
+ );
29
+ expect(malloyLiteral(new Date("2024-03-05T13:45:00Z"))).toBe(
30
+ "@2024-03-05 13:45:00",
31
+ );
32
+ });
33
+
34
+ it("has nothing to write for an empty value or a type it cannot spell", () => {
35
+ expect(malloyLiteral("", "filter<string>")).toBeUndefined();
36
+ expect(malloyLiteral(null, "filter<string>")).toBeUndefined();
37
+ expect(malloyLiteral("x", "geometry")).toBeUndefined();
38
+ expect(malloyLiteral(null)).toBeUndefined();
39
+ expect(malloyLiteral(Number.NaN)).toBeUndefined();
40
+ expect(malloyLiteral({})).toBeUndefined();
41
+ expect(malloyLiteral(new Date("nope"))).toBeUndefined();
42
+ });
43
+ });
@@ -0,0 +1,76 @@
1
+ // Copyright (c) Credible Data Inc.
2
+ // SPDX-License-Identifier: MIT
3
+
4
+ import { escapeMalloyString } from "./malloyString";
5
+
6
+ /**
7
+ * A value as a Malloy literal: `'text'`, `42`, `true`, `@2024-01-31`,
8
+ * `@2024-01-31 09:30:00`, or `f'…'` for a `filter<…>` type.
9
+ *
10
+ * With `type` — a given's declared type — the value is spelled the way that
11
+ * type reads it, so `"42"` for a `number` given is `42` and `true` for a
12
+ * `boolean` is `true`. Without it the JavaScript type decides, which is what a
13
+ * clicked cell's value needs. Undefined when there is nothing to write: no
14
+ * value, or one the type cannot spell.
15
+ */
16
+ export function malloyLiteral(
17
+ value: unknown,
18
+ type?: string,
19
+ ): string | undefined {
20
+ if (value === undefined || value === null || value === "") return undefined;
21
+ const quote = (text: string) => `'${escapeMalloyString(text)}'`;
22
+ const scalar =
23
+ type === undefined
24
+ ? inferredType(value)
25
+ : type.startsWith("filter<")
26
+ ? "filter"
27
+ : type;
28
+ switch (scalar) {
29
+ case "filter":
30
+ return `f${quote(String(value))}`;
31
+ case "string":
32
+ return quote(String(value));
33
+ case "number": {
34
+ const n = typeof value === "number" ? value : Number(value);
35
+ return Number.isFinite(n) ? String(n) : undefined;
36
+ }
37
+ case "boolean":
38
+ return value === true || value === "true" ? "true" : "false";
39
+ case "date": {
40
+ const day = datePart(value);
41
+ return day && `@${day}`;
42
+ }
43
+ case "timestamp": {
44
+ const day = datePart(value);
45
+ if (!day) return undefined;
46
+ const time =
47
+ value instanceof Date
48
+ ? value.toISOString().slice(11, 19)
49
+ : (/[T ](\d{2}:\d{2}(?::\d{2})?)/.exec(String(value))?.[1] ??
50
+ "00:00:00");
51
+ return `@${day} ${time}`;
52
+ }
53
+ default:
54
+ return undefined;
55
+ }
56
+ }
57
+
58
+ function inferredType(value: unknown): string | undefined {
59
+ if (typeof value === "string") return "string";
60
+ if (typeof value === "number") return "number";
61
+ if (typeof value === "boolean") return "boolean";
62
+ if (value instanceof Date && !Number.isNaN(value.getTime()))
63
+ return value.toISOString().slice(11, 19) === "00:00:00"
64
+ ? "date"
65
+ : "timestamp";
66
+ return undefined;
67
+ }
68
+
69
+ /** `2024-01-31` out of a Date (UTC) or an ISO-ish string, else undefined. */
70
+ function datePart(value: unknown): string | undefined {
71
+ if (value instanceof Date)
72
+ return Number.isNaN(value.getTime())
73
+ ? undefined
74
+ : value.toISOString().slice(0, 10);
75
+ return /^(\d{4}-\d{2}-\d{2})/.exec(String(value))?.[1];
76
+ }
package/vite.config.ts CHANGED
@@ -23,6 +23,9 @@ export default ({ mode }) => {
23
23
  entry: {
24
24
  index: "./src/index.ts",
25
25
  "client/index": "./src/client-entry.ts",
26
+ // The dashboard builder, and with it the Malloy parser: its own
27
+ // entry so a host loads it only when someone opens the builder.
28
+ "builder/index": "./src/builder-entry.ts",
26
29
  },
27
30
  name: "@malloy-publisher/sdk",
28
31
  fileName: (format, entryName) => {
@@ -30,6 +33,8 @@ export default ({ mode }) => {
30
33
  return `index.${format}.js`;
31
34
  } else if (entryName === "client/index") {
32
35
  return `client/index.${format}.js`;
36
+ } else if (entryName === "builder/index") {
37
+ return `builder/index.${format}.js`;
33
38
  }
34
39
  return `${entryName}.${format}.js`;
35
40
  },