@malloy-publisher/sdk 0.2.7 → 0.3.0

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 (99) hide show
  1. package/README.md +172 -204
  2. package/dist/ServerProvider-CGnLjzag.cjs.js +1 -0
  3. package/dist/{ServerProvider-ksC5Su_x.es.js → ServerProvider-DSK9rfSY.es.js} +245 -245
  4. package/dist/client/api.d.ts +13 -1
  5. package/dist/client/index.cjs.js +1 -1
  6. package/dist/client/index.es.js +1 -1
  7. package/dist/components/ApiErrorDisplay.d.ts +1 -2
  8. package/dist/components/Dashboard/Dashboard.d.ts +4 -2
  9. package/dist/components/Dashboard/promoteMeasureRow.d.ts +36 -0
  10. package/dist/components/DocumentStorage/BrowserDocumentStorage.d.ts +14 -0
  11. package/dist/components/DocumentStorage/DocumentStorage.d.ts +58 -0
  12. package/dist/components/DocumentStorage/DocumentStorageProvider.d.ts +18 -0
  13. package/dist/components/DocumentStorage/index.d.ts +3 -0
  14. package/dist/components/Model/index.d.ts +0 -1
  15. package/dist/components/RenderedResult/RenderedResult.d.ts +12 -0
  16. package/dist/components/RenderedResult/ResultContainer.d.ts +7 -1
  17. package/dist/components/RenderedResult/index.d.ts +1 -0
  18. package/dist/components/RenderedResult/resultSizing.d.ts +183 -0
  19. package/dist/components/drill/index.d.ts +1 -0
  20. package/dist/components/drill/useDrillSelf.d.ts +46 -0
  21. package/dist/components/given/filterValue.d.ts +63 -0
  22. package/dist/components/given/index.d.ts +1 -0
  23. package/dist/components/given/useGivenUrlParams.d.ts +39 -0
  24. package/dist/components/index.d.ts +2 -3
  25. package/dist/components/styles.d.ts +3 -3
  26. package/dist/core-8NVBCLZh.cjs.js +148 -0
  27. package/dist/{core-BY7vB5gN.es.js → core-B8oMW4sm.es.js} +3540 -2335
  28. package/dist/hooks/index.d.ts +1 -1
  29. package/dist/hooks/useSuggestOptions.d.ts +28 -12
  30. package/dist/index.cjs.js +281 -1
  31. package/dist/index.es.js +45803 -79
  32. package/dist/sdk.css +1 -1
  33. package/dist/styles.css +0 -1
  34. package/package.json +2 -6
  35. package/src/components/ApiErrorDisplay.tsx +1 -1
  36. package/src/components/Connections/EditConnectionDialog.tsx +96 -86
  37. package/src/components/Dashboard/Dashboard.tsx +60 -95
  38. package/src/components/Dashboard/DashboardTile.tsx +25 -2
  39. package/src/components/Dashboard/promoteMeasureRow.spec.ts +137 -0
  40. package/src/components/Dashboard/promoteMeasureRow.ts +129 -0
  41. package/src/components/DocumentStorage/BrowserDocumentStorage.spec.ts +81 -0
  42. package/src/components/DocumentStorage/BrowserDocumentStorage.ts +105 -0
  43. package/src/components/DocumentStorage/DocumentStorage.ts +73 -0
  44. package/src/components/DocumentStorage/DocumentStorageProvider.tsx +46 -0
  45. package/src/components/DocumentStorage/index.ts +15 -0
  46. package/src/components/Model/ModelCell.tsx +2 -1
  47. package/src/components/Model/index.ts +0 -1
  48. package/src/components/Notebook/Notebook.tsx +10 -76
  49. package/src/components/Notebook/NotebookCell.tsx +2 -8
  50. package/src/components/RenderedResult/RenderedResult.tsx +86 -76
  51. package/src/components/RenderedResult/ResultContainer.tsx +21 -24
  52. package/src/components/RenderedResult/index.ts +15 -0
  53. package/src/components/RenderedResult/resultSizing.spec.ts +249 -0
  54. package/src/components/RenderedResult/resultSizing.ts +308 -0
  55. package/src/components/ResultsDialog.tsx +2 -1
  56. package/src/components/drill/index.ts +5 -0
  57. package/src/components/drill/useDrillSelf.spec.tsx +64 -0
  58. package/src/components/drill/useDrillSelf.ts +110 -0
  59. package/src/components/given/GivenInput.spec.tsx +196 -2
  60. package/src/components/given/GivenInput.tsx +300 -25
  61. package/src/components/given/filterValue.spec.ts +112 -0
  62. package/src/components/given/filterValue.ts +188 -0
  63. package/src/components/given/index.ts +4 -0
  64. package/src/components/given/useGivenUrlParams.spec.tsx +74 -0
  65. package/src/components/given/useGivenUrlParams.ts +87 -0
  66. package/src/components/index.ts +5 -3
  67. package/src/hooks/index.ts +0 -1
  68. package/src/hooks/useGivensState.spec.ts +158 -0
  69. package/src/hooks/useGivensState.ts +114 -23
  70. package/src/hooks/useSuggestOptions.dom.spec.ts +60 -1
  71. package/src/hooks/useSuggestOptions.ts +94 -51
  72. package/vite.config.ts +0 -1
  73. package/dist/ServerProvider-xXW1HJOJ.cjs.js +0 -1
  74. package/dist/components/AnalyzePackageButton.d.ts +0 -6
  75. package/dist/components/Workbook/BrowserWorkbookStorage.d.ts +0 -9
  76. package/dist/components/Workbook/EditableMalloyCell.d.ts +0 -11
  77. package/dist/components/Workbook/ModelPicker.d.ts +0 -11
  78. package/dist/components/Workbook/MutableCell.d.ts +0 -17
  79. package/dist/components/Workbook/Workbook.d.ts +0 -7
  80. package/dist/components/Workbook/WorkbookList.d.ts +0 -7
  81. package/dist/components/Workbook/WorkbookManager.d.ts +0 -84
  82. package/dist/components/Workbook/WorkbookStorage.d.ts +0 -17
  83. package/dist/components/Workbook/WorkbookStorageProvider.d.ts +0 -12
  84. package/dist/components/Workbook/index.d.ts +0 -7
  85. package/dist/core-CWKmWEg2.cjs.js +0 -148
  86. package/dist/index-B0WyZAUA.es.js +0 -66412
  87. package/dist/index-kxVD1RjY.cjs.js +0 -356
  88. package/dist/markdown-editor.css +0 -341
  89. package/src/components/AnalyzePackageButton.tsx +0 -319
  90. package/src/components/Workbook/BrowserWorkbookStorage.ts +0 -64
  91. package/src/components/Workbook/EditableMalloyCell.tsx +0 -49
  92. package/src/components/Workbook/ModelPicker.tsx +0 -134
  93. package/src/components/Workbook/MutableCell.tsx +0 -458
  94. package/src/components/Workbook/Workbook.tsx +0 -501
  95. package/src/components/Workbook/WorkbookList.tsx +0 -110
  96. package/src/components/Workbook/WorkbookManager.ts +0 -214
  97. package/src/components/Workbook/WorkbookStorage.ts +0 -35
  98. package/src/components/Workbook/WorkbookStorageProvider.tsx +0 -40
  99. package/src/components/Workbook/index.ts +0 -10
@@ -0,0 +1,105 @@
1
+ // Copyright (c) Credible Data Inc.
2
+ // SPDX-License-Identifier: MIT
3
+
4
+ import type {
5
+ DocumentLocator,
6
+ DocumentStorage,
7
+ DocumentType,
8
+ Workspace,
9
+ } from "./DocumentStorage";
10
+
11
+ const LOCAL_WORKSPACE: Workspace = {
12
+ name: "Local",
13
+ description: "Stored in this browser only",
14
+ writeable: true,
15
+ };
16
+
17
+ /**
18
+ * Every key this store writes starts with this, so it can list its own
19
+ * documents without reading everything else the page keeps in localStorage
20
+ * (the theme mode, other libraries' state). The predecessor enumerated every
21
+ * key as a document.
22
+ */
23
+ const KEY_PREFIX = "publisher:document:";
24
+
25
+ /**
26
+ * A {@link DocumentStorage} in the browser's localStorage: one workspace,
27
+ * `Local`, private to this browser and this origin. The Console's default, and
28
+ * what a host uses before it has a store of its own.
29
+ */
30
+ export class BrowserDocumentStorage implements DocumentStorage {
31
+ async listWorkspaces(writeableOnly: boolean): Promise<Workspace[]> {
32
+ void writeableOnly; // the one workspace is writeable
33
+ return [LOCAL_WORKSPACE];
34
+ }
35
+
36
+ async listDocuments(
37
+ workspace: Workspace,
38
+ type?: DocumentType,
39
+ ): Promise<DocumentLocator[]> {
40
+ if (workspace.name !== LOCAL_WORKSPACE.name) return [];
41
+ const found: DocumentLocator[] = [];
42
+ for (let i = 0; i < localStorage.length; i++) {
43
+ const key = localStorage.key(i);
44
+ const locator = key === null ? undefined : locatorOf(key);
45
+ if (locator && (type === undefined || locator.type === type)) {
46
+ found.push(locator);
47
+ }
48
+ }
49
+ return found;
50
+ }
51
+
52
+ async getDocument(locator: DocumentLocator): Promise<string> {
53
+ const content = localStorage.getItem(keyOf(locator));
54
+ if (content === null) throw missing(locator);
55
+ return content;
56
+ }
57
+
58
+ async saveDocument(
59
+ locator: DocumentLocator,
60
+ content: string,
61
+ ): Promise<void> {
62
+ localStorage.setItem(keyOf(locator), content);
63
+ }
64
+
65
+ async deleteDocument(locator: DocumentLocator): Promise<void> {
66
+ const key = keyOf(locator);
67
+ if (localStorage.getItem(key) === null) throw missing(locator);
68
+ localStorage.removeItem(key);
69
+ }
70
+
71
+ async moveDocument(
72
+ from: DocumentLocator,
73
+ to: DocumentLocator,
74
+ ): Promise<void> {
75
+ const content = await this.getDocument(from);
76
+ localStorage.setItem(keyOf(to), content);
77
+ localStorage.removeItem(keyOf(from));
78
+ }
79
+ }
80
+
81
+ function keyOf(locator: DocumentLocator): string {
82
+ // The type is one segment; the path may contain anything, so it goes last
83
+ // and is read back as "the rest".
84
+ return `${KEY_PREFIX}${locator.type}:${locator.path}`;
85
+ }
86
+
87
+ function locatorOf(key: string): DocumentLocator | undefined {
88
+ if (!key.startsWith(KEY_PREFIX)) return undefined;
89
+ const rest = key.slice(KEY_PREFIX.length);
90
+ const separator = rest.indexOf(":");
91
+ if (separator <= 0) return undefined;
92
+ const type = rest.slice(0, separator);
93
+ if (type !== "dashboard" && type !== "notebook") return undefined;
94
+ return {
95
+ workspace: LOCAL_WORKSPACE.name,
96
+ type,
97
+ path: rest.slice(separator + 1),
98
+ };
99
+ }
100
+
101
+ function missing(locator: DocumentLocator): Error {
102
+ return new Error(
103
+ `No ${locator.type} at ${locator.workspace}/${locator.path}`,
104
+ );
105
+ }
@@ -0,0 +1,73 @@
1
+ // Copyright (c) Credible Data Inc.
2
+ // SPDX-License-Identifier: MIT
3
+
4
+ /**
5
+ * Where authored documents are kept, as an interface the host hands the SDK.
6
+ *
7
+ * The SDK renders dashboards and notebooks that a Publisher server serves out
8
+ * of a package, and it will author them too, but it does not decide where an
9
+ * authored document goes. That is the host's business: the Console keeps one
10
+ * in the browser, a platform keeps one in its own document store, a repo-backed
11
+ * host writes it to the package directory. So the SDK asks for a
12
+ * {@link DocumentStorage} through {@link DocumentStorageProvider} and calls it,
13
+ * and never touches a backend itself.
14
+ *
15
+ * A document is a string. The interface does not know whether it is a
16
+ * `dashboards/*.malloy` file, a `.malloynb`, or something else; the
17
+ * {@link DocumentLocator.type} says what kind it is so a backend can keep the
18
+ * kinds apart (a database column, a directory, a key prefix) and a listing can
19
+ * ask for one kind. Everything else a backend may know about a document, who
20
+ * changed it and when, who may see it, stays with the backend.
21
+ *
22
+ * Every method rejects rather than returning a sentinel when the document is
23
+ * not there, so a caller can tell "missing" from "empty".
24
+ */
25
+
26
+ /**
27
+ * The kinds of document the SDK authors. A `dashboard` is a
28
+ * `dashboards/<slug>.malloy` file; a `notebook` is a `.malloynb`.
29
+ */
30
+ export type DocumentType = "dashboard" | "notebook";
31
+
32
+ /** A place documents live, as the backend presents it to a reader. */
33
+ export interface Workspace {
34
+ name: string;
35
+ /** False for a workspace this reader may list and open but not save into. */
36
+ writeable: boolean;
37
+ description: string;
38
+ }
39
+
40
+ /** One document's address: which workspace, which kind, and its path there. */
41
+ export interface DocumentLocator {
42
+ workspace: string;
43
+ type: DocumentType;
44
+ /**
45
+ * The document's path within the workspace, spelled the way the backend
46
+ * spells it. For a repo-backed store that is the file path relative to the
47
+ * package (`dashboards/overview.malloy`); a database store may use a slug.
48
+ */
49
+ path: string;
50
+ }
51
+
52
+ export interface DocumentStorage {
53
+ /** The workspaces this reader can see; only the writeable ones when asked. */
54
+ listWorkspaces(writeableOnly: boolean): Promise<Workspace[]>;
55
+
56
+ /** Every document in a workspace, or only those of one kind. */
57
+ listDocuments(
58
+ workspace: Workspace,
59
+ type?: DocumentType,
60
+ ): Promise<DocumentLocator[]>;
61
+
62
+ /** The document's content. Rejects when there is no document there. */
63
+ getDocument(locator: DocumentLocator): Promise<string>;
64
+
65
+ /** Write the content, creating the document or replacing it. */
66
+ saveDocument(locator: DocumentLocator, content: string): Promise<void>;
67
+
68
+ /** Remove the document. Rejects when there is no document there. */
69
+ deleteDocument(locator: DocumentLocator): Promise<void>;
70
+
71
+ /** Rename or relocate a document, keeping its content. Rejects when `from` is missing. */
72
+ moveDocument(from: DocumentLocator, to: DocumentLocator): Promise<void>;
73
+ }
@@ -0,0 +1,46 @@
1
+ // Copyright (c) Credible Data Inc.
2
+ // SPDX-License-Identifier: MIT
3
+
4
+ import React, { createContext, useContext, useMemo } from "react";
5
+ import type { DocumentStorage } from "./DocumentStorage";
6
+
7
+ export interface DocumentStorageProviderProps {
8
+ children: React.ReactNode;
9
+ documentStorage: DocumentStorage;
10
+ }
11
+
12
+ interface DocumentStorageContextValue {
13
+ documentStorage: DocumentStorage;
14
+ }
15
+
16
+ const DocumentStorageContext = createContext<
17
+ DocumentStorageContextValue | undefined
18
+ >(undefined);
19
+
20
+ /**
21
+ * Hands a {@link DocumentStorage} to every SDK component beneath it. The host
22
+ * constructs the storage; the SDK only ever reads it through
23
+ * {@link useDocumentStorage}.
24
+ */
25
+ export function DocumentStorageProvider({
26
+ children,
27
+ documentStorage,
28
+ }: DocumentStorageProviderProps) {
29
+ const value = useMemo(() => ({ documentStorage }), [documentStorage]);
30
+ return (
31
+ <DocumentStorageContext.Provider value={value}>
32
+ {children}
33
+ </DocumentStorageContext.Provider>
34
+ );
35
+ }
36
+
37
+ /** The host's storage, or a thrown error outside a provider: there is no default. */
38
+ export function useDocumentStorage(): DocumentStorageContextValue {
39
+ const context = useContext(DocumentStorageContext);
40
+ if (!context) {
41
+ throw new Error(
42
+ "useDocumentStorage must be used within a DocumentStorageProvider",
43
+ );
44
+ }
45
+ return context;
46
+ }
@@ -0,0 +1,15 @@
1
+ // Copyright (c) Credible Data Inc.
2
+ // SPDX-License-Identifier: MIT
3
+
4
+ export type {
5
+ DocumentLocator,
6
+ DocumentStorage,
7
+ DocumentType,
8
+ Workspace,
9
+ } from "./DocumentStorage";
10
+ export {
11
+ DocumentStorageProvider,
12
+ useDocumentStorage,
13
+ type DocumentStorageProviderProps,
14
+ } from "./DocumentStorageProvider";
15
+ export { BrowserDocumentStorage } from "./BrowserDocumentStorage";
@@ -11,6 +11,7 @@ import { parseResourceUri } from "../../utils/formatting";
11
11
  import { CHART_RESULT_QUERY_OPTIONS } from "../../utils/queryClient";
12
12
  import { highlight } from "../highlighter";
13
13
  import ResultContainer from "../RenderedResult/ResultContainer";
14
+ import { MODEL_CELL_MAX_HEIGHT } from "../RenderedResult/resultSizing";
14
15
  import ResultsDialog from "../ResultsDialog";
15
16
  import { useServer } from "../ServerProvider";
16
17
  import { CleanMetricCard, CleanNotebookCell } from "../styles";
@@ -182,7 +183,7 @@ export function ModelCell({
182
183
  queryData?.data?.result && (
183
184
  <ResultContainer
184
185
  result={queryData.data.result}
185
- maxHeight={600}
186
+ maxHeight={MODEL_CELL_MAX_HEIGHT}
186
187
  maxResultSize={maxResultSize}
187
188
  renderLogs={queryData.data.renderLogs}
188
189
  />
@@ -5,7 +5,6 @@ export { default as Model } from "./Model";
5
5
  export { ModelExplorer } from "./ModelExplorer";
6
6
  export { ModelExplorerDialog } from "./ModelExplorerDialog";
7
7
  export { SourcesExplorer } from "./SourcesExplorer";
8
- export { SourceExplorerComponent } from "./SourcesExplorer";
9
8
  export type { SourceAndPath, QueryExplorerResult } from "./SourcesExplorer";
10
9
  export { useModelData } from "./useModelData";
11
10
  export type { ModelExplorerProps } from "./ModelExplorer";
@@ -14,7 +14,7 @@ import { useSuggestOptions } from "../../hooks/useSuggestOptions";
14
14
  import { parseResourceUri } from "../../utils/formatting";
15
15
  import { ApiErrorDisplay } from "../ApiErrorDisplay";
16
16
  import type { NavigationClick } from "../click_helper";
17
- import { encodeDrillValue, type DrillNavigation } from "../drill";
17
+ import { useDrillSelf, type DrillNavigation } from "../drill";
18
18
  import { GivensPanel } from "../given";
19
19
  import { givensToRequest } from "../given/paramCodec";
20
20
  import { Loading } from "../Loading";
@@ -231,83 +231,17 @@ export default function Notebook({
231
231
  notebookPath,
232
232
  declaredGivens,
233
233
  versionId,
234
+ // So a suggest over a gated or scoped source carries the givens it needs.
235
+ { values: applied, declaredTypes },
234
236
  );
235
237
 
236
- // The declared names, indexed case-insensitively, so a drill tag resolves
237
- // whichever way the two were spelled.
238
- //
239
- // Neither convention can be assumed. `# drill` defaults the given name to
240
- // the DIMENSION's name, which is conventionally lower_snake, while givens
241
- // are conventionally SHOUTED (both in-repo examples declare `REGION` and
242
- // `MIN_AMOUNT`). An exact match therefore failed for the common case, and
243
- // upper-casing the dimension name, which is what this did first, only moved
244
- // the failure onto models that spell their givens in lower case. Folding
245
- // case resolves both instead of picking a side.
246
- const givenNamesByFold = useMemo(() => {
247
- const byFold = new Map<string, string>();
248
- for (const name of declaredTypes.keys()) {
249
- // First declaration wins, so a model with `REGION` and `region` keeps
250
- // the one it declared first rather than silently flipping.
251
- if (!byFold.has(name.toLowerCase()))
252
- byFold.set(name.toLowerCase(), name);
253
- }
254
- return byFold;
255
- }, [declaredTypes]);
256
-
257
- /** The declared given a drill tag's name refers to, or undefined. */
258
- const resolveGiven = useCallback(
259
- (given: string) =>
260
- declaredTypes.has(given)
261
- ? given
262
- : givenNamesByFold.get(given.toLowerCase()),
263
- [declaredTypes, givenNamesByFold],
264
- );
265
-
266
- // `to=self` filters in place, which only works for a given this notebook
267
- // actually declares: sending one it cannot bind would fail every cell. The
268
- // mismatch is reported to the author rather than issued: same rule, same
269
- // wording, as the dashboard viewer.
270
- // Asked before a cell is painted as drillable, so the affordance matches what
271
- // a click can actually do. The refusal below still stands as a backstop for a
272
- // caller that does not ask.
273
- const canDrillSelf = useCallback(
274
- (given: string) => resolveGiven(given) !== undefined,
275
- [resolveGiven],
276
- );
277
-
278
- const onDrillSelf = useCallback(
279
- (given: string, rawValue: unknown) => {
280
- const declared = resolveGiven(given);
281
- if (declared === undefined) {
282
- console.warn(
283
- `# drill { to=self } tried to set '${given}', which ` +
284
- `'${notebookPath}' does not declare as a given. Name the ` +
285
- `given with 'given=' on the drill tag.`,
286
- );
287
- return;
288
- }
289
- // Encoded against the declared type of the given being set, which is
290
- // knowable here and is not knowable at the click. Set under the name
291
- // the MODEL declares, not the one the tag spelled, so the value goes
292
- // into the URL and the request under the one name the server knows.
293
- const declaredType = declaredTypes.get(declared);
294
- const value = encodeDrillValue(rawValue, declaredType);
295
- if (value === undefined) {
296
- // Say so. Returning in silence left a whole column painted as
297
- // clickable while every click did nothing, and a `given=` pointing
298
- // at a type the clicked value cannot become is an authoring
299
- // mistake the author has no other way to see. The sibling refusal
300
- // in `resolveDrill` warns for the same reason.
301
- console.warn(
302
- `Drill declined: ${JSON.stringify(rawValue)} cannot be a value for given "${declared}"` +
303
- (declaredType ? ` of type ${declaredType}` : ""),
304
- );
305
- return;
306
- }
307
- setGiven(declared, value);
308
- },
309
- [declaredTypes, notebookPath, resolveGiven, setGiven],
310
- );
238
+ // `to=self` filters in place. Which givens a tag may set, and setting one
239
+ // from a clicked cell, is the same on both surfaces, so it is shared.
240
+ const { canSelf: canDrillSelf, onSelf: onDrillSelf } = useDrillSelf({
241
+ declaredTypes,
242
+ setGiven,
243
+ documentName: notebookPath,
244
+ });
311
245
 
312
246
  /**
313
247
  * The `givens` query param for the notebook-cell GET: the same map the
@@ -29,17 +29,11 @@ import type { NavigationClick } from "../click_helper";
29
29
  import { useDrill, type DrillNavigation } from "../drill";
30
30
  import { createEmbeddedQueryResult } from "../QueryResult/QueryResult";
31
31
  import ResultContainer from "../RenderedResult/ResultContainer";
32
+ import { NOTEBOOK_CELL_MAX_HEIGHT } from "../RenderedResult/resultSizing";
32
33
  import ResultsDialog from "../ResultsDialog";
33
34
  import { CleanMetricCard, CleanNotebookCell } from "../styles";
34
35
  import { EnhancedNotebookCell } from "./types";
35
36
 
36
- /**
37
- * Cap for a cell result that lays itself out: a table, mostly. Tall enough for
38
- * a screenful of rows, after which the cell scrolls rather than the page
39
- * turning into one long table.
40
- */
41
- const CELL_MAX_HEIGHT = 700;
42
-
43
37
  interface NotebookCellProps {
44
38
  cell: EnhancedNotebookCell;
45
39
  expandCodeCell?: boolean;
@@ -670,7 +664,7 @@ export function NotebookCell({
670
664
  >
671
665
  <ResultContainer
672
666
  result={cell.result}
673
- maxHeight={CELL_MAX_HEIGHT}
667
+ maxHeight={NOTEBOOK_CELL_MAX_HEIGHT}
674
668
  maxResultSize={maxResultSize}
675
669
  drill={drill}
676
670
  />
@@ -17,6 +17,14 @@ import {
17
17
  type DashboardCardGeometry,
18
18
  } from "../../theme/buildTableCssVars";
19
19
  import { buildVegaThemeOverride } from "../../theme/buildVegaThemeOverride";
20
+ import {
21
+ contentNode,
22
+ contentNodeDepth,
23
+ measureContentHeight,
24
+ remeasuresAfterReady,
25
+ resultSizing,
26
+ type ResultSizing,
27
+ } from "./resultSizing";
20
28
  import { readChartAnnotations } from "../../theme/readChartAnnotations";
21
29
  import { resolveTheme } from "../../theme/resolveTheme";
22
30
  import { usePublisherTheme } from "../../theme/ThemeContext";
@@ -41,11 +49,17 @@ type MalloyRenderElement = HTMLElement & Record<string, unknown>;
41
49
  */
42
50
  interface MalloyVizHandle extends DrillMetadataSource {
43
51
  // Narrowed from `DrillMetadataSource`, which only declares the part the
44
- // drill affordance reads. `getRootField().renderAs()` is what decides
45
- // whether one measurement is enough; see `sizesToContent`.
52
+ // drill affordance reads. `getRootField().renderAs()` is what every sizing
53
+ // decision keys off; see `./resultSizing`.
46
54
  getMetadata: () =>
47
55
  | (NonNullable<ReturnType<DrillMetadataSource["getMetadata"]>> & {
48
- getRootField: () => { renderAs: () => string };
56
+ getRootField: () => { renderAs: () => string; key: string };
57
+ // The root's render plugin, whose `sizingStrategy` is the renderer's
58
+ // own answer to whether the result fills its box; see
59
+ // `./resultSizing`. A table or a `# dashboard` grid has none.
60
+ getPluginsForField: (
61
+ key: string,
62
+ ) => Array<{ sizingStrategy?: string }> | undefined;
49
63
  })
50
64
  | null
51
65
  | undefined;
@@ -74,7 +88,18 @@ interface RenderedResultProps {
74
88
  result: string;
75
89
  height?: number;
76
90
  isFillElement?: (boolean) => void;
91
+ /**
92
+ * The measured content height. Fires only for a content-sized root; a
93
+ * container-sized one has no height of its own to report. See
94
+ * {@link resultSizing}.
95
+ */
77
96
  onSizeChange?: (height: number) => void;
97
+ /**
98
+ * Which sizing rule the rendered root follows, as soon as the renderer's
99
+ * metadata says. Lets a caller stop treating its cap as a height for a
100
+ * result that will never report one.
101
+ */
102
+ onSizing?: (sizing: ResultSizing) => void;
78
103
  /**
79
104
  * Makes `# drill` cells clickable, and makes them look it. From `useDrill`
80
105
  * on the host surface, which decides where a click may go; omitted where
@@ -328,48 +353,12 @@ function injectRendererOverrides(): void {
328
353
  document.head.appendChild(style);
329
354
  }
330
355
 
331
- /**
332
- * Whether the renderer's top-level output sizes itself to its CONTENT rather
333
- * than to the box it was handed, which decides whether measuring it once is
334
- * enough.
335
- *
336
- * It is not, for a table. The renderer signals `onReady` as soon as it knows it
337
- * can paint, and for a table that is immediately — a chart waits for a non-zero
338
- * parent size, a table does not — so the single measurement taken there lands
339
- * before the table's virtualized grid has laid out, and reads a height the
340
- * table never keeps.
341
- *
342
- * Re-measuring a table TERMINATES: `.malloy-table.root` is
343
- * `height: fit-content; max-height: 100%` in the renderer's own CSS and the
344
- * wrappers between it and the container add no padding, so shrinking the
345
- * container to the table's content height is the exact point at which the cap
346
- * stops binding and the next measurement reports the same number.
347
- *
348
- * A root that FILLS its container stays on the one-shot path deliberately: a
349
- * chart draws itself inset from the box it is given, so feeding its height back
350
- * as the new container height would ratchet the container down by that inset
351
- * every pass and never converge.
352
- *
353
- * A table is the only root that needs this, and the reason is the virtualized
354
- * grid rather than the sizing strategy it shares with a `# size=` chart: that
355
- * chart takes its dimensions from a lookup synchronously, so its first
356
- * measurement is already right. Measured, for every size value and spelling.
357
- */
358
- function sizesToContent(viz: MalloyVizHandle): boolean {
359
- try {
360
- return viz.getMetadata()?.getRootField().renderAs() === "table";
361
- } catch {
362
- // Metadata unavailable: measure once, which is the behavior every
363
- // non-table root gets anyway.
364
- return false;
365
- }
366
- }
367
-
368
356
  function RenderedResultInner({
369
357
  result,
370
358
  height: inputHeight,
371
359
  drill,
372
360
  onSizeChange,
361
+ onSizing,
373
362
  }: RenderedResultProps) {
374
363
  const ref = useRef<HTMLDivElement>(null);
375
364
  // The renderer binds its click handler at construction, so a changing
@@ -469,38 +458,29 @@ function RenderedResultInner({
469
458
 
470
459
  hasMeasuredRef.current = false;
471
460
 
472
- // Measure the rendered chart's natural height off `root` (the stage that
473
- // wraps the renderer output) and report it up. Same grandchild/dashboard
474
- // HACK as before, just anchored on the stage wrapper.
461
+ // What the renderer says it is rendering, read once from its metadata
462
+ // after `setResult`. Every height decision below keys off this rather
463
+ // than off the DOM the renderer went on to build; see `./resultSizing`.
464
+ let renderAs: string | undefined;
465
+ let strategy: string | undefined;
466
+
467
+ // Measure the rendered result's content height off `root` (the stage
468
+ // that wraps the renderer output) and report it up.
475
469
  const measureRenderedSize = (root: HTMLElement) => {
476
470
  if (cancelled || !root.firstElementChild) return;
477
- const child = root.firstElementChild as HTMLElement;
478
- const grandchild = child.firstElementChild as HTMLElement;
479
- if (!grandchild) return;
480
- // A table reports a height of its own, so it keeps being measured
481
- // even after the first one lands. Everything else measures once.
482
- const contentSized = viz !== undefined && sizesToContent(viz);
483
- if (hasMeasuredRef.current && !contentSized) return;
484
- const greatgrandchild = grandchild.firstElementChild as HTMLElement;
485
- // `scrollHeight` is the CONTENT height, so this assumes the box adds
486
- // no chrome of its own. True today: `.malloy-table.root` has no
487
- // border, and a horizontal scrollbar costs no layout where scrollbars
488
- // overlay. A wide table clipped by a few pixels on a platform that
489
- // draws classic scrollbars would be this assumption breaking, and the
490
- // fix is `+ (offsetHeight - clientHeight)`.
491
- let renderedHeight =
492
- grandchild.scrollHeight || grandchild.offsetHeight || 0;
493
-
494
- // HACK - malloy dashboards height are determined by the greatgrandchild.
495
- if (
496
- greatgrandchild &&
497
- grandchild.classList.contains("malloy-dashboard")
498
- ) {
499
- renderedHeight =
500
- greatgrandchild.scrollHeight ||
501
- greatgrandchild.offsetHeight ||
502
- 0;
503
- }
471
+ // A chart fills the box it is handed, so measuring one reports back
472
+ // the height we just gave it. Nothing to learn, and reporting it is
473
+ // what used to ratchet an uncapped chart to its first-paint height.
474
+ if (resultSizing(renderAs, strategy) === "container") return;
475
+ // A content-sized root keeps being measured after the first height
476
+ // lands, because the first one races the renderer's layout.
477
+ const remeasures = remeasuresAfterReady(renderAs, strategy);
478
+ if (hasMeasuredRef.current && !remeasures) return;
479
+
480
+ const renderedHeight = measureContentHeight(
481
+ root,
482
+ contentNodeDepth(renderAs),
483
+ );
504
484
 
505
485
  if (renderedHeight > 0) {
506
486
  hasMeasuredRef.current = true;
@@ -509,14 +489,16 @@ function RenderedResultInner({
509
489
  onSizeChange(renderedHeight);
510
490
  }
511
491
  }
512
- // Watch the table from here on. Attached after the first measurement
513
- // rather than at render time because the node does not exist until
514
- // the renderer builds it, and this is the callback that first sees it.
515
- if (contentSized && observedNode !== grandchild) {
516
- observedNode = grandchild;
492
+ // Watch that same node from here on. Attached after the first
493
+ // measurement rather than at render time because the node does not
494
+ // exist until the renderer builds it, and this is the callback that
495
+ // first sees it.
496
+ const measured = contentNode(root, contentNodeDepth(renderAs));
497
+ if (remeasures && measured && observedNode !== measured) {
498
+ observedNode = measured;
517
499
  sizeObserver?.disconnect();
518
500
  sizeObserver = new ResizeObserver(() => measureRenderedSize(root));
519
- sizeObserver.observe(grandchild);
501
+ sizeObserver.observe(measured);
520
502
  }
521
503
  };
522
504
 
@@ -626,6 +608,33 @@ function RenderedResultInner({
626
608
  // The renderer accepts a Malloy Result; we don't import that type
627
609
  // in the SDK to avoid pinning to the malloy core types here.
628
610
  viz.setResult(parsed);
611
+ // Read the root's render type before painting, so the first
612
+ // measurement already knows whether it is worth taking. Metadata is
613
+ // complete as soon as the result is set; the DOM is not.
614
+ try {
615
+ const metadata = viz.getMetadata();
616
+ const root = metadata?.getRootField();
617
+ renderAs = root?.renderAs();
618
+ // The plugin's own `sizingStrategy`, which decides this outright
619
+ // where there is one. Read from the PLUGIN; the field entry's
620
+ // `renderProperties.sizingStrategy` reads "fit" for every root.
621
+ strategy = root
622
+ ? metadata?.getPluginsForField(root.key)?.[0]?.sizingStrategy
623
+ : undefined;
624
+ } catch {
625
+ // Metadata unavailable: fall through to the content-sized
626
+ // default, which is what every root got before this existed.
627
+ renderAs = undefined;
628
+ strategy = undefined;
629
+ }
630
+ onSizing?.(resultSizing(renderAs, strategy));
631
+ // Published on the stage because every sizing decision keys off it
632
+ // and nothing else in the DOM says what it was. A panel at an
633
+ // unexpected height is otherwise a guessing game about which rule
634
+ // applied, and the rule is chosen from a vocabulary — plugin names
635
+ // — that the rendered markup does not spell out anywhere.
636
+ stage.dataset.malloyRenderAs = renderAs ?? "unknown";
637
+ stage.dataset.malloySizing = resultSizing(renderAs, strategy);
629
638
  viz.render(stage);
630
639
 
631
640
  // Mark the cells a `# drill` makes clickable, so they read as
@@ -876,6 +885,7 @@ function RenderedResultInner({
876
885
  handleDrillClick,
877
886
  drillable,
878
887
  onSizeChange,
888
+ onSizing,
879
889
  baseTheme,
880
890
  layers,
881
891
  mode,