@malloy-publisher/sdk 0.9.14 → 0.9.16

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 (164) hide show
  1. package/dist/RenderedResult-5hOs5XnV.cjs.js +171 -0
  2. package/dist/RenderedResult-DxmHGZNQ.es.js +671 -0
  3. package/dist/{ServerProvider-BV7IoDMR.es.js → ServerProvider-D7neZcTk.es.js} +283 -265
  4. package/dist/ServerProvider-e2369oom.cjs.js +1 -0
  5. package/dist/builder/index.cjs.js +80 -79
  6. package/dist/builder/index.es.js +7732 -6717
  7. package/dist/builder-entry.d.ts +1 -1
  8. package/dist/client/api.d.ts +31 -7
  9. package/dist/client/index.cjs.js +1 -1
  10. package/dist/client/index.es.js +1 -1
  11. package/dist/components/Dashboard/DashboardGrid.d.ts +51 -1
  12. package/dist/components/Dashboard/DashboardTile.d.ts +7 -2
  13. package/dist/components/Dashboard/DashboardView.d.ts +9 -2
  14. package/dist/components/Dashboard/index.d.ts +1 -1
  15. package/dist/components/Dashboard/promoteMeasureRow.d.ts +5 -7
  16. package/dist/components/Dashboard/useStuck.d.ts +18 -12
  17. package/dist/components/RenderedResult/RenderedResult.d.ts +3 -2
  18. package/dist/components/RenderedResult/ResultContainer.d.ts +18 -1
  19. package/dist/components/RenderedResult/ResultPanel.d.ts +7 -1
  20. package/dist/components/RenderedResult/chartPresentation.d.ts +15 -0
  21. package/dist/components/RenderedResult/chartShapeProblem.d.ts +55 -0
  22. package/dist/components/RenderedResult/resultSizing.d.ts +47 -6
  23. package/dist/components/Report/Report.d.ts +7 -1
  24. package/dist/components/Report/ReportPage.d.ts +7 -0
  25. package/dist/components/Report/layoutRules.d.ts +45 -0
  26. package/dist/components/ReportBuilder/AddTileDialog.d.ts +2 -1
  27. package/dist/components/ReportBuilder/ArrangeMenu.d.ts +9 -0
  28. package/dist/components/ReportBuilder/BuilderGrid.d.ts +15 -4
  29. package/dist/components/ReportBuilder/BuilderToolbar.d.ts +3 -1
  30. package/dist/components/ReportBuilder/ChartPicker.d.ts +4 -2
  31. package/dist/components/ReportBuilder/EditorSurface.d.ts +10 -1
  32. package/dist/components/ReportBuilder/ReportBuilder.d.ts +1 -1
  33. package/dist/components/ReportBuilder/TileFrame.d.ts +54 -10
  34. package/dist/components/ReportBuilder/TileMenu.d.ts +5 -2
  35. package/dist/components/ReportBuilder/builderControls.d.ts +19 -0
  36. package/dist/components/ReportBuilder/catalog.d.ts +23 -0
  37. package/dist/components/ReportBuilder/chartLine.d.ts +38 -5
  38. package/dist/components/ReportBuilder/controls.d.ts +2 -2
  39. package/dist/components/ReportBuilder/document.d.ts +53 -5
  40. package/dist/components/ReportBuilder/imports.d.ts +7 -0
  41. package/dist/components/ReportBuilder/placement.d.ts +121 -0
  42. package/dist/components/ReportBuilder/preview.d.ts +59 -10
  43. package/dist/components/ReportBuilder/sortable.d.ts +12 -1
  44. package/dist/components/ReportBuilder/useBuilderSession.d.ts +1 -1
  45. package/dist/components/ReportBuilder/useBuilderShortcuts.d.ts +9 -1
  46. package/dist/components/ReportBuilder/useEdgeResize.d.ts +84 -0
  47. package/dist/components/ReportBuilder/useTileReorder.d.ts +30 -3
  48. package/dist/index.cjs.js +7 -7
  49. package/dist/index.es.js +3349 -3307
  50. package/dist/text/index.es.js +1 -1
  51. package/dist/{text-entry-72YFLeNk.es.js → text-entry-YKJZbRPo.es.js} +2 -2
  52. package/dist/theme/classes.d.ts +1 -1
  53. package/dist/theme/resolveTheme.d.ts +15 -0
  54. package/dist/{useCompiledDocument-B4QF1mIl.es.js → useCompiledDocument-CaYP_OYG.es.js} +6353 -6047
  55. package/dist/useCompiledDocument-zYEfLogf.cjs.js +142 -0
  56. package/dist/utils/blankQuoted.d.ts +15 -0
  57. package/package.json +1 -1
  58. package/src/builder-entry.ts +1 -0
  59. package/src/components/Dashboard/DashboardGrid.tsx +129 -10
  60. package/src/components/Dashboard/DashboardTile.tsx +15 -1
  61. package/src/components/Dashboard/DashboardView.tsx +64 -10
  62. package/src/components/Dashboard/TileCard.tsx +6 -0
  63. package/src/components/Dashboard/index.ts +1 -0
  64. package/src/components/Dashboard/promoteMeasureRow.spec.ts +19 -0
  65. package/src/components/Dashboard/promoteMeasureRow.ts +15 -36
  66. package/src/components/Dashboard/tileHeight.spec.ts +72 -0
  67. package/src/components/Dashboard/useStuck.ts +76 -28
  68. package/src/components/Package/NewDocumentDialog.spec.tsx +20 -16
  69. package/src/components/Package/NewDocumentDialog.tsx +10 -11
  70. package/src/components/RenderedResult/RenderedResult.lifecycle.spec.tsx +167 -2
  71. package/src/components/RenderedResult/RenderedResult.tsx +39 -6
  72. package/src/components/RenderedResult/ResultContainer.tsx +99 -10
  73. package/src/components/RenderedResult/ResultPanel.tsx +25 -1
  74. package/src/components/RenderedResult/chartPresentation.spec.ts +153 -0
  75. package/src/components/RenderedResult/chartPresentation.ts +166 -0
  76. package/src/components/RenderedResult/chartShapeProblem.spec.tsx +245 -0
  77. package/src/components/RenderedResult/chartShapeProblem.ts +219 -0
  78. package/src/components/RenderedResult/resultSizing.spec.ts +75 -3
  79. package/src/components/RenderedResult/resultSizing.ts +71 -11
  80. package/src/components/Report/Report.spec.tsx +19 -0
  81. package/src/components/Report/Report.tsx +8 -1
  82. package/src/components/Report/ReportPage.tsx +13 -1
  83. package/src/components/Report/layoutRules.spec.ts +43 -3
  84. package/src/components/Report/layoutRules.ts +70 -0
  85. package/src/components/Report/tileOverflow.spec.tsx +162 -0
  86. package/src/components/ReportBuilder/AddTileDialog.spec.tsx +2 -2
  87. package/src/components/ReportBuilder/AddTileDialog.tsx +11 -6
  88. package/src/components/ReportBuilder/ArrangeMenu.tsx +80 -0
  89. package/src/components/ReportBuilder/BuilderBar.tsx +5 -1
  90. package/src/components/ReportBuilder/BuilderDialogs.tsx +28 -1
  91. package/src/components/ReportBuilder/BuilderGrid.tsx +142 -35
  92. package/src/components/ReportBuilder/BuilderToolbar.tsx +4 -0
  93. package/src/components/ReportBuilder/ChartPicker.spec.ts +91 -4
  94. package/src/components/ReportBuilder/ChartPicker.tsx +45 -10
  95. package/src/components/ReportBuilder/DrillDialog.tsx +8 -2
  96. package/src/components/ReportBuilder/EditorSurface.tsx +101 -20
  97. package/src/components/ReportBuilder/FilterDialog.tsx +17 -8
  98. package/src/components/ReportBuilder/FilterStrip.tsx +2 -1
  99. package/src/components/ReportBuilder/ReportBuilder.charts.spec.tsx +193 -2
  100. package/src/components/ReportBuilder/ReportBuilder.controls.spec.tsx +4 -2
  101. package/src/components/ReportBuilder/ReportBuilder.notebook.spec.tsx +2 -2
  102. package/src/components/ReportBuilder/ReportBuilder.spec.tsx +242 -2
  103. package/src/components/ReportBuilder/ReportBuilder.tsx +161 -27
  104. package/src/components/ReportBuilder/ReportEditor.fileModel.spec.tsx +178 -0
  105. package/src/components/ReportBuilder/ReportEditor.modelFilters.spec.tsx +3 -5
  106. package/src/components/ReportBuilder/ReportEditor.readOnlyTitle.spec.tsx +92 -0
  107. package/src/components/ReportBuilder/ReportEditor.tsx +13 -0
  108. package/src/components/ReportBuilder/TileFrame.tsx +366 -170
  109. package/src/components/ReportBuilder/TileMenu.tsx +259 -20
  110. package/src/components/ReportBuilder/ViewPicker.tsx +4 -3
  111. package/src/components/ReportBuilder/addTileToDocument.spec.ts +34 -0
  112. package/src/components/ReportBuilder/addTileToDocument.ts +26 -1
  113. package/src/components/ReportBuilder/builderControls.ts +34 -0
  114. package/src/components/ReportBuilder/catalog.aggregate.spec.ts +137 -1
  115. package/src/components/ReportBuilder/catalog.ts +90 -37
  116. package/src/components/ReportBuilder/chartLine.spec.ts +42 -5
  117. package/src/components/ReportBuilder/chartLine.ts +80 -2
  118. package/src/components/ReportBuilder/controls.ts +4 -3
  119. package/src/components/ReportBuilder/document.ts +65 -7
  120. package/src/components/ReportBuilder/emptyStart.spec.ts +1 -1
  121. package/src/components/ReportBuilder/entryLayout.spec.ts +151 -0
  122. package/src/components/ReportBuilder/imports.ts +1 -1
  123. package/src/components/ReportBuilder/invariants.spec.ts +18 -10
  124. package/src/components/ReportBuilder/layout.ts +3 -0
  125. package/src/components/ReportBuilder/placement.spec.ts +401 -0
  126. package/src/components/ReportBuilder/placement.ts +416 -0
  127. package/src/components/ReportBuilder/preview.shapes.spec.ts +46 -6
  128. package/src/components/ReportBuilder/preview.spec.ts +151 -11
  129. package/src/components/ReportBuilder/preview.ts +203 -40
  130. package/src/components/ReportBuilder/preview.unsaved.compile.spec.ts +190 -0
  131. package/src/components/ReportBuilder/readDocument.spec.ts +53 -19
  132. package/src/components/ReportBuilder/readDocument.ts +197 -29
  133. package/src/components/ReportBuilder/scannerShapes.spec.ts +10 -10
  134. package/src/components/ReportBuilder/sortable.tsx +30 -2
  135. package/src/components/ReportBuilder/spliceDocument.chart.spec.ts +1 -1
  136. package/src/components/ReportBuilder/spliceDocument.color.spec.ts +80 -0
  137. package/src/components/ReportBuilder/spliceDocument.colspan.spec.ts +78 -0
  138. package/src/components/ReportBuilder/spliceDocument.spec.ts +110 -58
  139. package/src/components/ReportBuilder/spliceDocument.ts +139 -91
  140. package/src/components/ReportBuilder/statementExtent.spec.ts +3 -3
  141. package/src/components/ReportBuilder/testing/reportGivenOrder.json +42 -0
  142. package/src/components/ReportBuilder/textTiles.spec.ts +2 -2
  143. package/src/components/ReportBuilder/tileDisplayTitle.ts +2 -2
  144. package/src/components/ReportBuilder/useBuilderSession.ts +7 -2
  145. package/src/components/ReportBuilder/useBuilderShortcuts.ts +25 -1
  146. package/src/components/ReportBuilder/useEdgeResize.spec.tsx +324 -0
  147. package/src/components/ReportBuilder/useEdgeResize.ts +397 -0
  148. package/src/components/ReportBuilder/useTileEditing.ts +16 -3
  149. package/src/components/ReportBuilder/useTileReorder.ts +143 -6
  150. package/src/components/given/FilterButton.spec.tsx +27 -11
  151. package/src/components/given/FilterButton.tsx +19 -6
  152. package/src/theme/classes.ts +1 -1
  153. package/src/theme/resolveTheme.spec.ts +72 -1
  154. package/src/theme/resolveTheme.ts +43 -0
  155. package/src/utils/blankQuoted.spec.ts +50 -0
  156. package/src/utils/blankQuoted.ts +32 -0
  157. package/src/utils/malloyText.ts +2 -1
  158. package/dist/RenderedResult-DnBtf-cI.es.js +0 -593
  159. package/dist/RenderedResult-DtQtNV0d.cjs.js +0 -153
  160. package/dist/ServerProvider-BIFPCzTD.cjs.js +0 -1
  161. package/dist/components/ReportBuilder/useTileResize.d.ts +0 -32
  162. package/dist/useCompiledDocument-D0OAMejE.cjs.js +0 -142
  163. package/src/components/ReportBuilder/useTileResize.spec.tsx +0 -146
  164. package/src/components/ReportBuilder/useTileResize.ts +0 -133
@@ -4,14 +4,29 @@
4
4
  import { Warning } from "@mui/icons-material";
5
5
  import InfoOutlinedIcon from "@mui/icons-material/InfoOutlined";
6
6
  import { Box, Button, Tooltip, Typography } from "@mui/material";
7
- import { lazy, Suspense, useEffect, useRef, useState } from "react";
7
+ import {
8
+ lazy,
9
+ Suspense,
10
+ useCallback,
11
+ useEffect,
12
+ useRef,
13
+ useState,
14
+ } from "react";
8
15
  import { LogMessage } from "../../client";
9
16
  import type { DrillBinding } from "../drill/useDrill";
10
17
  import { FloatingIconButton } from "../FloatingIconButton";
11
18
  import { Loading, LOADING_COPY } from "../Loading";
12
19
  import { warmMalloyRenderer } from "./loadRenderer";
13
20
  import { summarizeRenderLogs } from "./renderLogs";
14
- import { resolveResultHeight, type ResultSizing } from "./resultSizing";
21
+ import {
22
+ resolveResultHeight,
23
+ resultCap,
24
+ type ResultSizing,
25
+ TIGHT_ATTR,
26
+ } from "./resultSizing";
27
+
28
+ /** The box a dashboard tile's result scrolls in when it is taller than its cap. */
29
+ export const RESULT_SCROLLER_CLASS = "publisher-result-scroller";
15
30
 
16
31
  const RenderedResult = lazy(() => import("../RenderedResult/RenderedResult"));
17
32
 
@@ -24,6 +39,14 @@ interface ResultContainerProps {
24
39
  * not be clipped to tidy it.
25
40
  */
26
41
  maxHeight?: number;
42
+ /**
43
+ * A further cap for a result whose root is a table, and only then. A
44
+ * linear report sets it: its tiles grow to fit, except a long table, which
45
+ * stops here and scrolls inside itself under its pinned header row.
46
+ */
47
+ tableMaxHeight?: number;
48
+ /** The height to paint at before the result is measured, in place of the default (see `initialResultHeight`). */
49
+ firstPaintHeight?: number;
27
50
  // if Results are larger than this size, show a warning and a button to proceed
28
51
  // this is to prevent performance issues with large results.
29
52
  // the default is 0, which means no warning will be shown.
@@ -42,6 +65,13 @@ interface ResultContainerProps {
42
65
  * tile's card is. Leave it off wherever the result sets the surface's height.
43
66
  */
44
67
  fill?: boolean;
68
+ /**
69
+ * The cell's height is set (a tile given rows), not its content's: only
70
+ * then is a result taller than it drawn compact to fit. A cell that grows
71
+ * with its content is briefly shorter than a result that just grew, and
72
+ * compact there would be a mistake that never undoes itself.
73
+ */
74
+ compactToFit?: boolean;
45
75
  }
46
76
 
47
77
  // ResultContainer is a component that renders a result, with a toggle button to expand/collapse the result.
@@ -51,10 +81,13 @@ interface ResultContainerProps {
51
81
  export default function ResultContainer({
52
82
  result,
53
83
  maxHeight,
84
+ tableMaxHeight,
85
+ firstPaintHeight,
54
86
  maxResultSize = 0,
55
87
  renderLogs,
56
88
  drill,
57
89
  fill = false,
90
+ compactToFit = false,
58
91
  }: ResultContainerProps) {
59
92
  const containerRef = useRef<HTMLDivElement>(null);
60
93
  // A result is here: start the renderer download if no panel already has.
@@ -66,6 +99,15 @@ export default function ResultContainer({
66
99
  const [contentHeight, setContentHeight] = useState<number | undefined>(
67
100
  undefined,
68
101
  );
102
+ // The root's render type, which decides whether `tableMaxHeight` applies.
103
+ const [renderAs, setRenderAs] = useState<string | undefined>(undefined);
104
+ const onSizing = useCallback(
105
+ (next: ResultSizing, root: string | undefined) => {
106
+ setSizing(next);
107
+ setRenderAs(root);
108
+ },
109
+ [],
110
+ );
69
111
  const [userAcknowledged, setUserAcknowledged] = useState(false);
70
112
  const [cellHeight, setCellHeight] = useState<number | undefined>(undefined);
71
113
  const renderLogSummary = summarizeRenderLogs(renderLogs);
@@ -74,13 +116,37 @@ export default function ResultContainer({
74
116
  useEffect(() => {
75
117
  const box = containerRef.current;
76
118
  if (!fill || !box) return;
77
- const observer = new ResizeObserver(([entry]) =>
78
- setCellHeight(Math.round(entry.contentRect.height)),
79
- );
119
+ const observer = new ResizeObserver(([entry]) => {
120
+ setCellHeight(Math.round(entry.contentRect.height));
121
+ setCellWidth(Math.round(entry.contentRect.width));
122
+ });
80
123
  observer.observe(box);
81
124
  return () => observer.disconnect();
82
125
  }, [fill, hasResult, userAcknowledged]);
83
126
 
127
+ // Tight: a content-sized result taller than the cell it fills (value cards
128
+ // in a tile set shorter than they are), drawn compact so it fits rather
129
+ // than scrolls. Held at the height it needed at full size, and let go only
130
+ // once the cell is that tall again: let go as soon as the compact result
131
+ // fit, it would grow back past the cell and the two would flicker.
132
+ const [tightFrom, setTightFrom] = useState<number | undefined>(undefined);
133
+ const [cellWidth, setCellWidth] = useState<number | undefined>(undefined);
134
+ const mayTighten = fill && compactToFit && sizing === "content";
135
+ // A new result, or a cell of another width, may fit at full size where the
136
+ // last one did not: let go and measure again, rather than stay compact on
137
+ // the strength of a height measured for something else.
138
+ useEffect(() => {
139
+ setTightFrom(undefined);
140
+ }, [result, cellWidth, mayTighten]);
141
+ useEffect(() => {
142
+ if (!mayTighten) return;
143
+ if (cellHeight === undefined || contentHeight === undefined) return;
144
+ if (tightFrom === undefined && contentHeight > cellHeight + 1)
145
+ setTightFrom(contentHeight);
146
+ else if (tightFrom !== undefined && cellHeight >= tightFrom)
147
+ setTightFrom(undefined);
148
+ }, [mayTighten, cellHeight, contentHeight, tightFrom]);
149
+
84
150
  if (!result) {
85
151
  return null;
86
152
  }
@@ -123,11 +189,13 @@ export default function ResultContainer({
123
189
  const loading = (
124
190
  <Loading text={LOADING_COPY.loading} centered={true} size={32} />
125
191
  );
192
+ const cap = resultCap({ renderAs, maxHeight, tableMaxHeight });
126
193
  const renderedHeight = resolveResultHeight({
127
194
  sizing,
128
195
  contentHeight,
129
- maxHeight,
196
+ maxHeight: cap,
130
197
  fillHeight: fill ? cellHeight : undefined,
198
+ firstPaintHeight,
131
199
  });
132
200
  const renderedResult = (
133
201
  <Suspense fallback={loading}>
@@ -135,7 +203,7 @@ export default function ResultContainer({
135
203
  result={result}
136
204
  height={renderedHeight}
137
205
  onSizeChange={setContentHeight}
138
- onSizing={setSizing}
206
+ onSizing={onSizing}
139
207
  drill={drill}
140
208
  fill={fill}
141
209
  />
@@ -150,17 +218,38 @@ export default function ResultContainer({
150
218
  height: "auto",
151
219
  border: "0px",
152
220
  borderRadius: 0,
153
- overflow: "hidden",
221
+ // Unfilled, the box is the result's own height, so a result that
222
+ // outgrows its cap scrolls here rather than being cut off.
223
+ overflowX: "hidden",
224
+ overflowY: fill ? "hidden" : "auto",
154
225
  // Grows from the unfloored height, so a result that gets shorter
155
226
  // lets its row shrink; the result is out of flow for the same reason.
156
227
  ...(fill && {
157
- flex: `1 1 ${resolveResultHeight({ sizing, contentHeight, maxHeight })}px`,
228
+ flex: `1 1 ${resolveResultHeight({ sizing, contentHeight, maxHeight: cap, firstPaintHeight })}px`,
158
229
  minHeight: 0,
159
230
  }),
160
231
  }}
161
232
  >
162
233
  {fill ? (
163
- <Box sx={{ position: "absolute", inset: 0 }}>{renderedResult}</Box>
234
+ // Scrolls rather than clips. A result taller than its cap (a row of
235
+ // KPI cards wrapped one per line in a narrow tile, say) draws past
236
+ // the box it was given; clipped, its last cards could not be reached
237
+ // at all. A table never overflows here: it is held to the box and
238
+ // scrolls inside itself, under its own pinned header.
239
+ <Box
240
+ className={RESULT_SCROLLER_CLASS}
241
+ {...(mayTighten && tightFrom !== undefined
242
+ ? { [TIGHT_ATTR]: "" }
243
+ : {})}
244
+ sx={{
245
+ position: "absolute",
246
+ inset: 0,
247
+ overflowX: "hidden",
248
+ overflowY: "auto",
249
+ }}
250
+ >
251
+ {renderedResult}
252
+ </Box>
164
253
  ) : (
165
254
  renderedResult
166
255
  )}
@@ -1,12 +1,13 @@
1
1
  // Copyright (c) Credible Data Inc.
2
2
  // SPDX-License-Identifier: MIT
3
3
 
4
- import { Box, LinearProgress } from "@mui/material";
4
+ import { Box, LinearProgress, Typography } from "@mui/material";
5
5
  import { useEffect, useMemo } from "react";
6
6
  import type { QueryResultState } from "../../hooks/useQueryResult";
7
7
  import { ApiErrorDisplay } from "../ApiErrorDisplay";
8
8
  import type { DrillBinding } from "../drill/useDrill";
9
9
  import { Loading, LOADING_COPY } from "../Loading";
10
+ import { chartShapeProblem } from "./chartShapeProblem";
10
11
  import { warmMalloyRenderer } from "./loadRenderer";
11
12
  import ResultContainer from "./ResultContainer";
12
13
 
@@ -17,10 +18,16 @@ export interface ResultPanelProps {
17
18
  context: string;
18
19
  loadingText?: string;
19
20
  maxHeight?: number;
21
+ /** See `ResultContainer`: a further cap for a table root only. */
22
+ tableMaxHeight?: number;
23
+ /** See `ResultContainer`: the height to paint at before the result is measured. */
24
+ firstPaintHeight?: number;
20
25
  maxResultSize?: number;
21
26
  drill?: DrillBinding;
22
27
  /** See `ResultContainer`: stretch the result to its cell. */
23
28
  fill?: boolean;
29
+ /** The cell has a set height: a result taller than it is drawn compact (see `ResultContainer`). */
30
+ compactToFit?: boolean;
24
31
  /**
25
32
  * Rewrites the result before it is rendered — a dashboard tile promotes a
26
33
  * one-row measure result to KPI cards this way. Memoized on the result
@@ -45,9 +52,12 @@ export function ResultPanel({
45
52
  context,
46
53
  loadingText = LOADING_COPY.running,
47
54
  maxHeight,
55
+ tableMaxHeight,
56
+ firstPaintHeight,
48
57
  maxResultSize,
49
58
  drill,
50
59
  fill,
60
+ compactToFit,
51
61
  transform,
52
62
  }: ResultPanelProps) {
53
63
  const { data, isSuccess, isError, error, fetchStatus, isPlaceholderData } =
@@ -64,6 +74,9 @@ export function ResultPanel({
64
74
  () => (raw !== undefined && transform ? transform(raw) : raw),
65
75
  [raw, transform],
66
76
  );
77
+ // A chart the result cannot fill, said in plain words in place of the
78
+ // renderer's own error.
79
+ const problem = useMemo(() => chartShapeProblem(result), [result]);
67
80
 
68
81
  if (isError) {
69
82
  return (
@@ -80,14 +93,25 @@ export function ResultPanel({
80
93
  text={fetchStatus === "idle" ? LOADING_COPY.loading : loadingText}
81
94
  />
82
95
  );
96
+ if (problem)
97
+ return (
98
+ <Box sx={{ p: 2 }}>
99
+ <Typography variant="body2" role="status" color="text.secondary">
100
+ {problem}
101
+ </Typography>
102
+ </Box>
103
+ );
83
104
  const shown = (
84
105
  <ResultContainer
85
106
  result={result}
86
107
  maxHeight={maxHeight}
108
+ tableMaxHeight={tableMaxHeight}
109
+ {...(firstPaintHeight !== undefined ? { firstPaintHeight } : {})}
87
110
  maxResultSize={maxResultSize}
88
111
  renderLogs={data.data.renderLogs}
89
112
  drill={drill}
90
113
  fill={fill}
114
+ compactToFit={compactToFit}
91
115
  />
92
116
  );
93
117
  // The previous answer, while the new one runs: it stays where it is, eased
@@ -0,0 +1,153 @@
1
+ // Copyright (c) Credible Data Inc.
2
+ // SPDX-License-Identifier: MIT
3
+
4
+ import { describe, expect, it } from "bun:test";
5
+ import {
6
+ chartMinWidth,
7
+ humanizeFieldName,
8
+ labelChartFields,
9
+ MIN_CHART_WIDTH_PX,
10
+ } from "./chartPresentation";
11
+ import { requestsRowChart } from "./chartShapeProblem";
12
+
13
+ // The shape the server returns: output fields with their annotations, the
14
+ // query's own annotations at the root. Trimmed from a real `orders` result.
15
+ const field = (name: string, ...lines: string[]) => ({
16
+ kind: "dimension",
17
+ name,
18
+ type: { kind: "number_type" },
19
+ annotations: lines.map((value) => ({ value: `${value}\n` })),
20
+ });
21
+
22
+ const result = (rootLines: string[], fields: unknown[], rows = 2) => ({
23
+ annotations: rootLines.map((value) => ({ value: `${value}\n` })),
24
+ schema: { fields },
25
+ data: { kind: "array_cell", array_value: Array.from({ length: rows }) },
26
+ });
27
+
28
+ const labelsOf = (out: { schema: { fields: unknown[] } }) =>
29
+ (
30
+ out.schema.fields as Array<{
31
+ name: string;
32
+ annotations: Array<{ value: string }>;
33
+ }>
34
+ ).map((f) => [
35
+ f.name,
36
+ f.annotations.map((a) => a.value.trim()).find((v) => /label=/.test(v)),
37
+ ]);
38
+
39
+ describe("labelChartFields", () => {
40
+ it("titles a chart's unlabelled fields the way a reader says them", () => {
41
+ const out = labelChartFields(
42
+ result(
43
+ ["# bar_chart"],
44
+ [
45
+ field("order_month"),
46
+ field("total_revenue", "# currency"),
47
+ field("carrier", '# label="Airline"'),
48
+ ],
49
+ ),
50
+ );
51
+ expect(labelsOf(out)).toEqual([
52
+ ["order_month", '# label="Order month"'],
53
+ ["total_revenue", '# label="Total revenue"'],
54
+ // The author's own label is never replaced.
55
+ ["carrier", '# label="Airline"'],
56
+ ]);
57
+ });
58
+
59
+ it("leaves a table's columns as their author named them", () => {
60
+ const input = result([], [field("total_revenue")]);
61
+ expect(labelChartFields(input)).toBe(input);
62
+ });
63
+
64
+ it("follows the builder's chart lines, which negate before they pick", () => {
65
+ const picked = result(
66
+ ["# line_chart", "# -line_chart -viz bar_chart"],
67
+ [field("total_revenue")],
68
+ );
69
+ expect(labelsOf(labelChartFields(picked))[0][1]).toBe(
70
+ '# label="Total revenue"',
71
+ );
72
+ // A table pick on a view that carried a chart: no chart is left.
73
+ const table = result(
74
+ ["# bar_chart", "# -bar_chart -viz"],
75
+ [field("total_revenue")],
76
+ );
77
+ expect(labelChartFields(table)).toBe(table);
78
+ });
79
+
80
+ it("labels a nested chart's fields and not its table sibling's", () => {
81
+ const nest = (name: string, lines: string[]) => ({
82
+ kind: "join",
83
+ name,
84
+ annotations: lines.map((value) => ({ value: `${value}\n` })),
85
+ type: {
86
+ kind: "array_type",
87
+ element_type: {
88
+ kind: "record_type",
89
+ fields: [field("flight_count")],
90
+ },
91
+ },
92
+ });
93
+ const out = labelChartFields(
94
+ result(
95
+ ["# dashboard"],
96
+ [nest("by_month", ["# line_chart"]), nest("detail", [])],
97
+ ),
98
+ ) as unknown as {
99
+ schema: {
100
+ fields: Array<{
101
+ type: {
102
+ element_type: {
103
+ fields: Array<{ annotations: Array<{ value: string }> }>;
104
+ };
105
+ };
106
+ }>;
107
+ };
108
+ };
109
+ const childLines = (index: number) =>
110
+ out.schema.fields[index].type.element_type.fields[0].annotations.map(
111
+ (a) => a.value.trim(),
112
+ );
113
+ expect(childLines(0)).toContain('# label="Flight count"');
114
+ expect(childLines(1)).toEqual([]);
115
+ });
116
+ });
117
+
118
+ describe("requestsRowChart", () => {
119
+ it("reads viz= as a chart, and ignores doc and quoted text", () => {
120
+ expect(requestsRowChart(["# viz=bar"])).toBe(true);
121
+ expect(requestsRowChart(['#" a bar_chart of sales'])).toBe(false);
122
+ expect(requestsRowChart(['# label="bar_chart"'])).toBe(false);
123
+ expect(requestsRowChart(["# big_value"])).toBe(false);
124
+ });
125
+ });
126
+
127
+ describe("humanizeFieldName", () => {
128
+ it("writes snake case as a sentence", () => {
129
+ expect(humanizeFieldName("total_revenue")).toBe("Total revenue");
130
+ expect(humanizeFieldName("name")).toBe("Name");
131
+ });
132
+ });
133
+
134
+ describe("chartMinWidth", () => {
135
+ it("gives a bar chart room for every bar, so none is cut", () => {
136
+ // The renderer draws one bar per 8px and drops the rest.
137
+ const width = chartMinWidth("bar", result(["# bar_chart"], [], 80));
138
+ expect(width).toBeGreaterThanOrEqual(80 * 8);
139
+ });
140
+
141
+ it("floors a short bar or line chart at a readable width", () => {
142
+ expect(chartMinWidth("bar", result([], [], 3))).toBe(MIN_CHART_WIDTH_PX);
143
+ expect(chartMinWidth("line", result([], [], 300))).toBe(
144
+ MIN_CHART_WIDTH_PX,
145
+ );
146
+ });
147
+
148
+ it("leaves anything that is not a plotted chart alone", () => {
149
+ expect(chartMinWidth("table", result([], [], 80))).toBeUndefined();
150
+ expect(chartMinWidth("big_value", result([], []))).toBeUndefined();
151
+ expect(chartMinWidth(undefined, result([], []))).toBeUndefined();
152
+ });
153
+ });
@@ -0,0 +1,166 @@
1
+ // Copyright (c) Credible Data Inc.
2
+ // SPDX-License-Identifier: MIT
3
+
4
+ /**
5
+ * How a chart reads, decided from the result before the renderer sees it.
6
+ *
7
+ * Two things the renderer leaves to the model, which a model rarely says:
8
+ *
9
+ * - An axis is titled with the field's `# label`, or else its name, so a
10
+ * measure nobody labelled is titled `total_revenue`. A chart's unlabelled
11
+ * fields are given a label written the way the builder already titles a tile
12
+ * (`total_revenue` → "Total revenue"). An author's own `# label` always wins:
13
+ * only a field with none is touched, and only in a chart, so a table keeps
14
+ * the column names its author chose.
15
+ * - A plotted chart fills whatever width it is handed, and a bar chart draws at
16
+ * most one bar per 8px of it, cutting the rest under "Showing limited
17
+ * results". {@link chartMinWidth} is the narrowest a chart is drawn, past
18
+ * which its panel scrolls sideways rather than squeezing it.
19
+ *
20
+ * Pure, and over the result's JSON shape only, so it is tested without a
21
+ * renderer.
22
+ */
23
+
24
+ import { requestsRowChart } from "./chartShapeProblem";
25
+
26
+ interface Annotation {
27
+ value?: string;
28
+ }
29
+
30
+ interface ResultField {
31
+ name?: string;
32
+ kind?: string;
33
+ type?: {
34
+ kind?: string;
35
+ fields?: ResultField[];
36
+ element_type?: { kind?: string; fields?: ResultField[] };
37
+ };
38
+ annotations?: Annotation[];
39
+ }
40
+
41
+ interface ResultShape {
42
+ schema?: { fields?: ResultField[] };
43
+ annotations?: Annotation[];
44
+ data?: { kind?: string; array_value?: unknown[] };
45
+ }
46
+
47
+ const linesOf = (annotations: Annotation[] | undefined): string[] =>
48
+ (annotations ?? [])
49
+ .map((a) => a?.value)
50
+ .filter((v): v is string => typeof v === "string");
51
+
52
+ /** `total_revenue` → "Total revenue". */
53
+ export function humanizeFieldName(name: string): string {
54
+ const words = name.replace(/[-_]+/g, " ").replace(/\s+/g, " ").trim();
55
+ return words.charAt(0).toUpperCase() + words.slice(1);
56
+ }
57
+
58
+ const hasLabel = (field: ResultField) =>
59
+ linesOf(field.annotations).some((line) => {
60
+ const text = line.trim();
61
+ // A tag line (not `#(…)` or `#"`) that sets `label=`.
62
+ return /^#[^("]/.test(text) && /(?:^#|[\s{])label\s*=/.test(text);
63
+ });
64
+
65
+ const quoted = (text: string) =>
66
+ `"${text.replace(/\\/g, "\\\\").replace(/"/g, '\\"')}"`;
67
+
68
+ /** The fields of a nested result, wherever its type keeps them. */
69
+ const nestedFields = (field: ResultField): ResultField[] | undefined =>
70
+ field.type?.element_type?.fields ?? field.type?.fields;
71
+
72
+ function labelFields(
73
+ fields: ResultField[],
74
+ isChart: boolean,
75
+ ): { fields: ResultField[]; changed: boolean } {
76
+ let changed = false;
77
+ const out = fields.map((field) => {
78
+ const children = nestedFields(field);
79
+ if (children) {
80
+ // A nest is its own chart, or not, by its own tags.
81
+ const inner = labelFields(
82
+ children,
83
+ requestsRowChart(linesOf(field.annotations)),
84
+ );
85
+ if (!inner.changed) return field;
86
+ changed = true;
87
+ const type = field.type?.element_type
88
+ ? {
89
+ ...field.type,
90
+ element_type: {
91
+ ...field.type.element_type,
92
+ fields: inner.fields,
93
+ },
94
+ }
95
+ : { ...field.type, fields: inner.fields };
96
+ return { ...field, type };
97
+ }
98
+ if (!isChart || !field.name || hasLabel(field)) return field;
99
+ const label = humanizeFieldName(field.name);
100
+ if (label === field.name) return field;
101
+ changed = true;
102
+ return {
103
+ ...field,
104
+ annotations: [
105
+ { value: `# label=${quoted(label)}\n` },
106
+ ...(field.annotations ?? []),
107
+ ],
108
+ };
109
+ });
110
+ return { fields: out, changed };
111
+ }
112
+
113
+ /**
114
+ * The result with a human label on every unlabelled field of a chart, at the
115
+ * root or in a nest; the same object when there is nothing to label.
116
+ */
117
+ export function labelChartFields<T>(result: T): T {
118
+ if (!result || typeof result !== "object") return result;
119
+ const shape = result as ResultShape;
120
+ const fields = shape.schema?.fields;
121
+ if (!Array.isArray(fields)) return result;
122
+ const { fields: labelled, changed } = labelFields(
123
+ fields,
124
+ requestsRowChart(linesOf(shape.annotations)),
125
+ );
126
+ if (!changed) return result;
127
+ return { ...shape, schema: { ...shape.schema, fields: labelled } } as T;
128
+ }
129
+
130
+ /** The narrowest a plotted chart is drawn before its panel scrolls sideways. */
131
+ export const MIN_CHART_WIDTH_PX = 320;
132
+
133
+ /**
134
+ * Room per bar: the renderer draws one bar per 8px and cuts the rest, so this
135
+ * keeps every bar of a result drawn, at a width a bar still reads at.
136
+ */
137
+ const BAR_PX = 10;
138
+
139
+ /** The plot's own chrome beside its bars: the measure axis and its title. */
140
+ const AXIS_PX = 96;
141
+
142
+ /** Past this a chart is wide enough to scroll through, not to fit. */
143
+ const MAX_CHART_WIDTH_PX = 4000;
144
+
145
+ /**
146
+ * The narrowest width a result's chart is drawn at, or undefined for a
147
+ * result that is not a plotted chart (`renderAs` in the renderer's plugin
148
+ * vocabulary: `bar`, `line`, `combo`, or the tag fallback `chart`).
149
+ */
150
+ export function chartMinWidth(
151
+ renderAs: string | undefined,
152
+ result: unknown,
153
+ ): number | undefined {
154
+ if (
155
+ renderAs !== "bar" &&
156
+ renderAs !== "combo" &&
157
+ renderAs !== "line" &&
158
+ renderAs !== "chart" &&
159
+ renderAs !== "scatter_chart"
160
+ )
161
+ return undefined;
162
+ if (renderAs !== "bar" && renderAs !== "combo") return MIN_CHART_WIDTH_PX;
163
+ const rows = (result as ResultShape | undefined)?.data?.array_value?.length;
164
+ const forBars = rows === undefined ? 0 : rows * BAR_PX + AXIS_PX;
165
+ return Math.min(Math.max(MIN_CHART_WIDTH_PX, forBars), MAX_CHART_WIDTH_PX);
166
+ }