@malloy-publisher/sdk 0.9.13 → 0.9.15

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 (148) hide show
  1. package/dist/RenderedResult-BClN_PG6.cjs.js +154 -0
  2. package/dist/{RenderedResult-DnBtf-cI.es.js → RenderedResult-YBzVMVH2.es.js} +295 -234
  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 +7430 -6548
  7. package/dist/client/api.d.ts +30 -6
  8. package/dist/client/index.cjs.js +1 -1
  9. package/dist/client/index.es.js +1 -1
  10. package/dist/components/Dashboard/DashboardGrid.d.ts +49 -1
  11. package/dist/components/Dashboard/DashboardTile.d.ts +5 -2
  12. package/dist/components/Dashboard/DashboardView.d.ts +9 -2
  13. package/dist/components/Dashboard/index.d.ts +1 -1
  14. package/dist/components/Dashboard/promoteMeasureRow.d.ts +5 -7
  15. package/dist/components/Dashboard/useStuck.d.ts +18 -12
  16. package/dist/components/RenderedResult/RenderedResult.d.ts +3 -2
  17. package/dist/components/RenderedResult/ResultContainer.d.ts +11 -1
  18. package/dist/components/RenderedResult/ResultPanel.d.ts +5 -1
  19. package/dist/components/RenderedResult/chartPresentation.d.ts +15 -0
  20. package/dist/components/RenderedResult/chartShapeProblem.d.ts +55 -0
  21. package/dist/components/RenderedResult/resultSizing.d.ts +42 -6
  22. package/dist/components/Report/Report.d.ts +7 -1
  23. package/dist/components/Report/ReportPage.d.ts +7 -0
  24. package/dist/components/Report/layoutRules.d.ts +45 -0
  25. package/dist/components/ReportBuilder/AddTileDialog.d.ts +2 -1
  26. package/dist/components/ReportBuilder/BuilderGrid.d.ts +14 -1
  27. package/dist/components/ReportBuilder/ChartPicker.d.ts +4 -2
  28. package/dist/components/ReportBuilder/EditorSurface.d.ts +17 -1
  29. package/dist/components/ReportBuilder/ReportEditor.d.ts +18 -0
  30. package/dist/components/ReportBuilder/TileFrame.d.ts +33 -1
  31. package/dist/components/ReportBuilder/TileMenu.d.ts +5 -2
  32. package/dist/components/ReportBuilder/catalog.d.ts +23 -0
  33. package/dist/components/ReportBuilder/chartLine.d.ts +38 -5
  34. package/dist/components/ReportBuilder/controls.d.ts +2 -2
  35. package/dist/components/ReportBuilder/document.d.ts +53 -5
  36. package/dist/components/ReportBuilder/imports.d.ts +7 -0
  37. package/dist/components/ReportBuilder/placement.d.ts +75 -0
  38. package/dist/components/ReportBuilder/preview.d.ts +59 -10
  39. package/dist/components/ReportBuilder/sortable.d.ts +3 -1
  40. package/dist/components/ReportBuilder/useTileHeight.d.ts +39 -0
  41. package/dist/components/ReportBuilder/useTileReorder.d.ts +27 -3
  42. package/dist/components/ReportBuilder/useTileResize.d.ts +8 -0
  43. package/dist/index.cjs.js +7 -7
  44. package/dist/index.es.js +3328 -3287
  45. package/dist/text/index.es.js +1 -1
  46. package/dist/{text-entry-72YFLeNk.es.js → text-entry-YKJZbRPo.es.js} +2 -2
  47. package/dist/theme/resolveTheme.d.ts +15 -0
  48. package/dist/{useCompiledDocument-B4QF1mIl.es.js → useCompiledDocument-BGk38oaW.es.js} +5097 -4805
  49. package/dist/useCompiledDocument-D9t5ry_t.cjs.js +142 -0
  50. package/dist/utils/blankQuoted.d.ts +15 -0
  51. package/package.json +1 -1
  52. package/src/components/Dashboard/DashboardGrid.tsx +127 -10
  53. package/src/components/Dashboard/DashboardTile.tsx +11 -1
  54. package/src/components/Dashboard/DashboardView.tsx +63 -10
  55. package/src/components/Dashboard/TileCard.tsx +6 -0
  56. package/src/components/Dashboard/index.ts +1 -0
  57. package/src/components/Dashboard/promoteMeasureRow.spec.ts +19 -0
  58. package/src/components/Dashboard/promoteMeasureRow.ts +15 -36
  59. package/src/components/Dashboard/tileHeight.spec.ts +72 -0
  60. package/src/components/Dashboard/useStuck.ts +76 -28
  61. package/src/components/Package/NewDocumentDialog.spec.tsx +20 -16
  62. package/src/components/Package/NewDocumentDialog.tsx +10 -11
  63. package/src/components/RenderedResult/RenderedResult.lifecycle.spec.tsx +167 -2
  64. package/src/components/RenderedResult/RenderedResult.tsx +21 -6
  65. package/src/components/RenderedResult/ResultContainer.tsx +60 -7
  66. package/src/components/RenderedResult/ResultPanel.tsx +21 -1
  67. package/src/components/RenderedResult/chartPresentation.spec.ts +153 -0
  68. package/src/components/RenderedResult/chartPresentation.ts +166 -0
  69. package/src/components/RenderedResult/chartShapeProblem.spec.tsx +245 -0
  70. package/src/components/RenderedResult/chartShapeProblem.ts +219 -0
  71. package/src/components/RenderedResult/resultSizing.spec.ts +75 -3
  72. package/src/components/RenderedResult/resultSizing.ts +65 -11
  73. package/src/components/Report/Report.spec.tsx +19 -0
  74. package/src/components/Report/Report.tsx +8 -1
  75. package/src/components/Report/ReportPage.tsx +13 -1
  76. package/src/components/Report/layoutRules.spec.ts +43 -3
  77. package/src/components/Report/layoutRules.ts +70 -0
  78. package/src/components/Report/tileOverflow.spec.tsx +162 -0
  79. package/src/components/ReportBuilder/AddTileDialog.spec.tsx +2 -2
  80. package/src/components/ReportBuilder/AddTileDialog.tsx +11 -6
  81. package/src/components/ReportBuilder/BuilderBar.tsx +1 -1
  82. package/src/components/ReportBuilder/BuilderDialogs.tsx +20 -0
  83. package/src/components/ReportBuilder/BuilderGrid.tsx +126 -20
  84. package/src/components/ReportBuilder/ChartPicker.spec.ts +91 -4
  85. package/src/components/ReportBuilder/ChartPicker.tsx +45 -10
  86. package/src/components/ReportBuilder/DrillDialog.tsx +8 -2
  87. package/src/components/ReportBuilder/EditorSurface.tsx +110 -28
  88. package/src/components/ReportBuilder/FilterDialog.tsx +17 -8
  89. package/src/components/ReportBuilder/FilterStrip.tsx +2 -1
  90. package/src/components/ReportBuilder/ReportBuilder.charts.spec.tsx +193 -2
  91. package/src/components/ReportBuilder/ReportBuilder.controls.spec.tsx +4 -2
  92. package/src/components/ReportBuilder/ReportBuilder.notebook.spec.tsx +2 -2
  93. package/src/components/ReportBuilder/ReportBuilder.spec.tsx +143 -2
  94. package/src/components/ReportBuilder/ReportBuilder.tsx +73 -19
  95. package/src/components/ReportBuilder/ReportEditor.fileModel.spec.tsx +178 -0
  96. package/src/components/ReportBuilder/ReportEditor.modelFilters.spec.tsx +3 -5
  97. package/src/components/ReportBuilder/ReportEditor.queryVersion.spec.tsx +292 -0
  98. package/src/components/ReportBuilder/ReportEditor.readOnlyTitle.spec.tsx +92 -0
  99. package/src/components/ReportBuilder/ReportEditor.tsx +35 -0
  100. package/src/components/ReportBuilder/TileFrame.tsx +251 -6
  101. package/src/components/ReportBuilder/TileMenu.tsx +259 -20
  102. package/src/components/ReportBuilder/ViewPicker.tsx +4 -3
  103. package/src/components/ReportBuilder/addTileToDocument.spec.ts +34 -0
  104. package/src/components/ReportBuilder/addTileToDocument.ts +26 -1
  105. package/src/components/ReportBuilder/catalog.aggregate.spec.ts +137 -1
  106. package/src/components/ReportBuilder/catalog.ts +90 -37
  107. package/src/components/ReportBuilder/chartLine.spec.ts +42 -5
  108. package/src/components/ReportBuilder/chartLine.ts +80 -2
  109. package/src/components/ReportBuilder/controls.ts +4 -3
  110. package/src/components/ReportBuilder/document.ts +65 -7
  111. package/src/components/ReportBuilder/emptyStart.spec.ts +1 -1
  112. package/src/components/ReportBuilder/entryLayout.spec.ts +151 -0
  113. package/src/components/ReportBuilder/imports.ts +1 -1
  114. package/src/components/ReportBuilder/invariants.spec.ts +18 -10
  115. package/src/components/ReportBuilder/layout.ts +3 -0
  116. package/src/components/ReportBuilder/placement.spec.ts +193 -0
  117. package/src/components/ReportBuilder/placement.ts +250 -0
  118. package/src/components/ReportBuilder/preview.shapes.spec.ts +46 -6
  119. package/src/components/ReportBuilder/preview.spec.ts +151 -11
  120. package/src/components/ReportBuilder/preview.ts +203 -40
  121. package/src/components/ReportBuilder/preview.unsaved.compile.spec.ts +190 -0
  122. package/src/components/ReportBuilder/readDocument.spec.ts +46 -2
  123. package/src/components/ReportBuilder/readDocument.ts +194 -23
  124. package/src/components/ReportBuilder/scannerShapes.spec.ts +10 -10
  125. package/src/components/ReportBuilder/sortable.tsx +4 -0
  126. package/src/components/ReportBuilder/spliceDocument.chart.spec.ts +1 -1
  127. package/src/components/ReportBuilder/spliceDocument.color.spec.ts +80 -0
  128. package/src/components/ReportBuilder/spliceDocument.colspan.spec.ts +78 -0
  129. package/src/components/ReportBuilder/spliceDocument.spec.ts +110 -18
  130. package/src/components/ReportBuilder/spliceDocument.ts +139 -52
  131. package/src/components/ReportBuilder/statementExtent.spec.ts +3 -3
  132. package/src/components/ReportBuilder/testing/reportGivenOrder.json +42 -0
  133. package/src/components/ReportBuilder/textTiles.spec.ts +2 -2
  134. package/src/components/ReportBuilder/tileDisplayTitle.ts +2 -2
  135. package/src/components/ReportBuilder/useTileEditing.ts +16 -3
  136. package/src/components/ReportBuilder/useTileHeight.ts +149 -0
  137. package/src/components/ReportBuilder/useTileReorder.ts +143 -6
  138. package/src/components/ReportBuilder/useTileResize.ts +16 -1
  139. package/src/components/given/FilterButton.spec.tsx +27 -11
  140. package/src/components/given/FilterButton.tsx +19 -6
  141. package/src/theme/resolveTheme.spec.ts +72 -1
  142. package/src/theme/resolveTheme.ts +43 -0
  143. package/src/utils/blankQuoted.spec.ts +50 -0
  144. package/src/utils/blankQuoted.ts +32 -0
  145. package/src/utils/malloyText.ts +2 -1
  146. package/dist/RenderedResult-DtQtNV0d.cjs.js +0 -153
  147. package/dist/ServerProvider-BIFPCzTD.cjs.js +0 -1
  148. package/dist/useCompiledDocument-D0OAMejE.cjs.js +0 -142
@@ -4,14 +4,28 @@
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
+ } from "./resultSizing";
26
+
27
+ /** The box a dashboard tile's result scrolls in when it is taller than its cap. */
28
+ export const RESULT_SCROLLER_CLASS = "publisher-result-scroller";
15
29
 
16
30
  const RenderedResult = lazy(() => import("../RenderedResult/RenderedResult"));
17
31
 
@@ -24,6 +38,14 @@ interface ResultContainerProps {
24
38
  * not be clipped to tidy it.
25
39
  */
26
40
  maxHeight?: number;
41
+ /**
42
+ * A further cap for a result whose root is a table, and only then. A
43
+ * linear report sets it: its tiles grow to fit, except a long table, which
44
+ * stops here and scrolls inside itself under its pinned header row.
45
+ */
46
+ tableMaxHeight?: number;
47
+ /** The height to paint at before the result is measured, in place of the default (see `initialResultHeight`). */
48
+ firstPaintHeight?: number;
27
49
  // if Results are larger than this size, show a warning and a button to proceed
28
50
  // this is to prevent performance issues with large results.
29
51
  // the default is 0, which means no warning will be shown.
@@ -51,6 +73,8 @@ interface ResultContainerProps {
51
73
  export default function ResultContainer({
52
74
  result,
53
75
  maxHeight,
76
+ tableMaxHeight,
77
+ firstPaintHeight,
54
78
  maxResultSize = 0,
55
79
  renderLogs,
56
80
  drill,
@@ -66,6 +90,15 @@ export default function ResultContainer({
66
90
  const [contentHeight, setContentHeight] = useState<number | undefined>(
67
91
  undefined,
68
92
  );
93
+ // The root's render type, which decides whether `tableMaxHeight` applies.
94
+ const [renderAs, setRenderAs] = useState<string | undefined>(undefined);
95
+ const onSizing = useCallback(
96
+ (next: ResultSizing, root: string | undefined) => {
97
+ setSizing(next);
98
+ setRenderAs(root);
99
+ },
100
+ [],
101
+ );
69
102
  const [userAcknowledged, setUserAcknowledged] = useState(false);
70
103
  const [cellHeight, setCellHeight] = useState<number | undefined>(undefined);
71
104
  const renderLogSummary = summarizeRenderLogs(renderLogs);
@@ -123,11 +156,13 @@ export default function ResultContainer({
123
156
  const loading = (
124
157
  <Loading text={LOADING_COPY.loading} centered={true} size={32} />
125
158
  );
159
+ const cap = resultCap({ renderAs, maxHeight, tableMaxHeight });
126
160
  const renderedHeight = resolveResultHeight({
127
161
  sizing,
128
162
  contentHeight,
129
- maxHeight,
163
+ maxHeight: cap,
130
164
  fillHeight: fill ? cellHeight : undefined,
165
+ firstPaintHeight,
131
166
  });
132
167
  const renderedResult = (
133
168
  <Suspense fallback={loading}>
@@ -135,7 +170,7 @@ export default function ResultContainer({
135
170
  result={result}
136
171
  height={renderedHeight}
137
172
  onSizeChange={setContentHeight}
138
- onSizing={setSizing}
173
+ onSizing={onSizing}
139
174
  drill={drill}
140
175
  fill={fill}
141
176
  />
@@ -150,17 +185,35 @@ export default function ResultContainer({
150
185
  height: "auto",
151
186
  border: "0px",
152
187
  borderRadius: 0,
153
- overflow: "hidden",
188
+ // Unfilled, the box is the result's own height, so a result that
189
+ // outgrows its cap scrolls here rather than being cut off.
190
+ overflowX: "hidden",
191
+ overflowY: fill ? "hidden" : "auto",
154
192
  // Grows from the unfloored height, so a result that gets shorter
155
193
  // lets its row shrink; the result is out of flow for the same reason.
156
194
  ...(fill && {
157
- flex: `1 1 ${resolveResultHeight({ sizing, contentHeight, maxHeight })}px`,
195
+ flex: `1 1 ${resolveResultHeight({ sizing, contentHeight, maxHeight: cap, firstPaintHeight })}px`,
158
196
  minHeight: 0,
159
197
  }),
160
198
  }}
161
199
  >
162
200
  {fill ? (
163
- <Box sx={{ position: "absolute", inset: 0 }}>{renderedResult}</Box>
201
+ // Scrolls rather than clips. A result taller than its cap (a row of
202
+ // KPI cards wrapped one per line in a narrow tile, say) draws past
203
+ // the box it was given; clipped, its last cards could not be reached
204
+ // at all. A table never overflows here: it is held to the box and
205
+ // scrolls inside itself, under its own pinned header.
206
+ <Box
207
+ className={RESULT_SCROLLER_CLASS}
208
+ sx={{
209
+ position: "absolute",
210
+ inset: 0,
211
+ overflowX: "hidden",
212
+ overflowY: "auto",
213
+ }}
214
+ >
215
+ {renderedResult}
216
+ </Box>
164
217
  ) : (
165
218
  renderedResult
166
219
  )}
@@ -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,6 +18,10 @@ 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. */
@@ -45,6 +50,8 @@ export function ResultPanel({
45
50
  context,
46
51
  loadingText = LOADING_COPY.running,
47
52
  maxHeight,
53
+ tableMaxHeight,
54
+ firstPaintHeight,
48
55
  maxResultSize,
49
56
  drill,
50
57
  fill,
@@ -64,6 +71,9 @@ export function ResultPanel({
64
71
  () => (raw !== undefined && transform ? transform(raw) : raw),
65
72
  [raw, transform],
66
73
  );
74
+ // A chart the result cannot fill, said in plain words in place of the
75
+ // renderer's own error.
76
+ const problem = useMemo(() => chartShapeProblem(result), [result]);
67
77
 
68
78
  if (isError) {
69
79
  return (
@@ -80,10 +90,20 @@ export function ResultPanel({
80
90
  text={fetchStatus === "idle" ? LOADING_COPY.loading : loadingText}
81
91
  />
82
92
  );
93
+ if (problem)
94
+ return (
95
+ <Box sx={{ p: 2 }}>
96
+ <Typography variant="body2" role="status" color="text.secondary">
97
+ {problem}
98
+ </Typography>
99
+ </Box>
100
+ );
83
101
  const shown = (
84
102
  <ResultContainer
85
103
  result={result}
86
104
  maxHeight={maxHeight}
105
+ tableMaxHeight={tableMaxHeight}
106
+ {...(firstPaintHeight !== undefined ? { firstPaintHeight } : {})}
87
107
  maxResultSize={maxResultSize}
88
108
  renderLogs={data.data.renderLogs}
89
109
  drill={drill}
@@ -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
+ }