@malloy-publisher/sdk 0.0.382-dev → 0.2.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (284) hide show
  1. package/README.md +115 -95
  2. package/TREE_SHAKING.md +16 -11
  3. package/bunfig.toml +7 -0
  4. package/dist/ServerProvider-Cn_LhKda.cjs.js +1 -0
  5. package/dist/ServerProvider-sfabtriY.es.js +4076 -0
  6. package/dist/client/api.d.ts +3773 -1515
  7. package/dist/client/configuration.d.ts +1 -1
  8. package/dist/client/index.cjs.js +1 -1
  9. package/dist/client/index.d.ts +1 -1
  10. package/dist/client/index.es.js +86 -59
  11. package/dist/components/Connections/EditConnectionDialog.d.ts +2 -1
  12. package/dist/components/Connections/common.d.ts +8 -2
  13. package/dist/components/Dashboard/Dashboard.d.ts +62 -0
  14. package/dist/components/Dashboard/DashboardTile.d.ts +57 -0
  15. package/dist/components/Dashboard/index.d.ts +2 -0
  16. package/dist/components/DataAppViewer/DataAppViewer.d.ts +23 -0
  17. package/dist/components/DataAppViewer/index.d.ts +1 -0
  18. package/dist/components/Environment/Environment.d.ts +6 -0
  19. package/dist/components/Environment/index.d.ts +2 -0
  20. package/dist/components/Home/AddEnvironmentDialog.d.ts +1 -0
  21. package/dist/components/Home/DeleteEnvironmentDialog.d.ts +5 -0
  22. package/dist/components/Home/EditEnvironmentDialog.d.ts +7 -0
  23. package/dist/components/Home/Home.d.ts +2 -2
  24. package/dist/components/Materializations/CreateEnvMaterializationDialog.d.ts +14 -0
  25. package/dist/components/Materializations/CreateMaterializationDialog.d.ts +10 -0
  26. package/dist/components/Materializations/DeleteMaterializationDialog.d.ts +7 -0
  27. package/dist/components/Materializations/EnvironmentMaterializations.d.ts +7 -0
  28. package/dist/components/Materializations/ManifestView.d.ts +13 -0
  29. package/dist/components/Materializations/MaterializationDetailDialog.d.ts +9 -0
  30. package/dist/components/Materializations/MaterializationRunsList.d.ts +15 -0
  31. package/dist/components/Materializations/Materializations.d.ts +7 -0
  32. package/dist/components/Materializations/ScheduleCard.d.ts +20 -0
  33. package/dist/components/Materializations/SectionLabel.d.ts +10 -0
  34. package/dist/components/Materializations/SetScheduleDialog.d.ts +11 -0
  35. package/dist/components/Materializations/TriggerChip.d.ts +10 -0
  36. package/dist/components/Materializations/cron.d.ts +23 -0
  37. package/dist/components/Materializations/index.d.ts +2 -0
  38. package/dist/components/Materializations/utils.d.ts +46 -0
  39. package/dist/components/Notebook/Notebook.d.ts +47 -4
  40. package/dist/components/Notebook/NotebookCell.d.ts +37 -1
  41. package/dist/components/Notebook/runPlan.d.ts +29 -0
  42. package/dist/components/Notebook/types.d.ts +10 -0
  43. package/dist/components/Package/ContentTypeIcon.d.ts +31 -0
  44. package/dist/components/Package/Package.d.ts +1 -4
  45. package/dist/components/RenderedResult/RenderedResult.d.ts +7 -1
  46. package/dist/components/RenderedResult/ResultContainer.d.ts +5 -1
  47. package/dist/components/RenderedResult/renderLogs.d.ts +6 -0
  48. package/dist/components/ResultsDialog.d.ts +6 -1
  49. package/dist/components/ServerProvider.d.ts +28 -4
  50. package/dist/components/click_helper.d.ts +10 -1
  51. package/dist/components/drill/index.d.ts +3 -0
  52. package/dist/components/drill/markDrillableCells.d.ts +55 -0
  53. package/dist/components/drill/resolveDrill.d.ts +139 -0
  54. package/dist/components/drill/useDrill.d.ts +63 -0
  55. package/dist/components/given/GivenInput.d.ts +52 -0
  56. package/dist/components/given/GivensPanel.d.ts +47 -0
  57. package/dist/components/given/filterValue.d.ts +97 -0
  58. package/dist/components/given/index.d.ts +2 -0
  59. package/dist/components/given/paramCodec.d.ts +60 -0
  60. package/dist/components/given/utils.d.ts +17 -0
  61. package/dist/components/highlighter.d.ts +6 -1
  62. package/dist/components/index.d.ts +7 -2
  63. package/dist/components/styles.d.ts +47 -0
  64. package/dist/constants/docLinks.d.ts +12 -0
  65. package/dist/{core-YNpOLuB1.cjs.js → core-CqRKhtoy.cjs.js} +1 -1
  66. package/dist/{core-CjeTkq8O.es.js → core-DyU47reh.es.js} +1 -1
  67. package/dist/github-dark-BKL9xNgN.cjs.js +1 -0
  68. package/dist/github-dark-DenFmJkN.es.js +4 -0
  69. package/dist/hooks/givenValue.d.ts +10 -0
  70. package/dist/hooks/index.d.ts +4 -0
  71. package/dist/hooks/useDimensionFiltersFromSpec.d.ts +3 -3
  72. package/dist/hooks/useDimensionFiltersQuery.d.ts +3 -3
  73. package/dist/hooks/useDimensionalFilterRangeData.d.ts +4 -4
  74. package/dist/hooks/useGivensState.d.ts +64 -0
  75. package/dist/hooks/useModelGivens.d.ts +10 -0
  76. package/dist/hooks/useSuggestOptions.d.ts +78 -0
  77. package/dist/{index-DRDu9kIV.es.js → index-CAkFE4Ol.es.js} +41278 -28504
  78. package/dist/index-DD4b_bt0.cjs.js +356 -0
  79. package/dist/index.cjs.js +1 -1
  80. package/dist/index.d.ts +4 -1
  81. package/dist/index.es.js +79 -48
  82. package/dist/malloy-explorer.css +12 -1
  83. package/dist/sdk.css +1 -1
  84. package/dist/theme/ThemeContext.d.ts +45 -0
  85. package/dist/theme/buildMalloyExplicitTheme.d.ts +34 -0
  86. package/dist/theme/buildTableCssVars.d.ts +41 -0
  87. package/dist/theme/buildVegaThemeOverride.d.ts +16 -0
  88. package/dist/theme/defaults.d.ts +7 -0
  89. package/dist/theme/index.d.ts +8 -0
  90. package/dist/theme/keys.d.ts +20 -0
  91. package/dist/theme/readChartAnnotations.d.ts +23 -0
  92. package/dist/theme/resolveTheme.d.ts +22 -0
  93. package/dist/theme/types.d.ts +70 -0
  94. package/dist/utils/dataAppEmbed.d.ts +44 -0
  95. package/dist/utils/formatting.d.ts +1 -1
  96. package/dist/utils/malloyString.d.ts +7 -0
  97. package/dist/utils/parsing.d.ts +2 -2
  98. package/dist/utils/queryClient.d.ts +5 -0
  99. package/package.json +19 -8
  100. package/src/client-entry.ts +3 -0
  101. package/src/components/AnalyzePackageButton.tsx +9 -3
  102. package/src/components/ApiErrorDisplay.tsx +3 -0
  103. package/src/components/Connections/AddConnectionDialog.tsx +132 -25
  104. package/src/components/Connections/DeleteConnectionDialog.tsx +14 -3
  105. package/src/components/Connections/EditConnectionDialog.tsx +167 -37
  106. package/src/components/Connections/common.ts +94 -3
  107. package/src/components/DOMElement/DOMElement.tsx +3 -0
  108. package/src/components/DOMElement/index.ts +3 -0
  109. package/src/components/Dashboard/Dashboard.spec.tsx +216 -0
  110. package/src/components/Dashboard/Dashboard.tsx +458 -0
  111. package/src/components/Dashboard/DashboardTile.spec.tsx +81 -0
  112. package/src/components/Dashboard/DashboardTile.tsx +199 -0
  113. package/src/components/Dashboard/index.ts +5 -0
  114. package/src/components/Dashboard/tileGridColumn.spec.ts +35 -0
  115. package/src/components/DataAppViewer/DataAppViewer.tsx +214 -0
  116. package/src/components/DataAppViewer/index.ts +4 -0
  117. package/src/components/{Project → Environment}/About.tsx +11 -4
  118. package/src/components/Environment/AddPackageDialog.tsx +202 -0
  119. package/src/components/{Project → Environment}/ConnectionExplorer.tsx +17 -14
  120. package/src/components/Environment/Connections.tsx +391 -0
  121. package/src/components/{Project → Environment}/DeletePackageDialog.tsx +8 -4
  122. package/src/components/{Project → Environment}/EditPackageDialog.tsx +21 -13
  123. package/src/components/Environment/Environment.tsx +89 -0
  124. package/src/components/Environment/Packages.tsx +206 -0
  125. package/src/components/Environment/index.ts +5 -0
  126. package/src/components/Home/{AddProjectDialog.tsx → AddEnvironmentDialog.tsx} +25 -19
  127. package/src/components/Home/{DeleteProjectDialog.tsx → DeleteEnvironmentDialog.tsx} +20 -15
  128. package/src/components/Home/{EditProjectDialog.tsx → EditEnvironmentDialog.tsx} +35 -28
  129. package/src/components/Home/Home.tsx +386 -408
  130. package/src/components/Home/index.ts +3 -0
  131. package/src/components/Loading.tsx +3 -0
  132. package/src/components/Materializations/CreateEnvMaterializationDialog.tsx +179 -0
  133. package/src/components/Materializations/CreateMaterializationDialog.tsx +112 -0
  134. package/src/components/Materializations/DeleteMaterializationDialog.tsx +109 -0
  135. package/src/components/Materializations/EnvironmentMaterializations.tsx +267 -0
  136. package/src/components/Materializations/ManifestView.tsx +87 -0
  137. package/src/components/Materializations/MaterializationDetailDialog.tsx +259 -0
  138. package/src/components/Materializations/MaterializationRunsList.tsx +256 -0
  139. package/src/components/Materializations/Materializations.tsx +355 -0
  140. package/src/components/Materializations/ScheduleCard.tsx +231 -0
  141. package/src/components/Materializations/SectionLabel.tsx +30 -0
  142. package/src/components/Materializations/SetScheduleDialog.tsx +162 -0
  143. package/src/components/Materializations/TriggerChip.tsx +44 -0
  144. package/src/components/Materializations/cron.ts +124 -0
  145. package/src/components/Materializations/index.ts +5 -0
  146. package/src/components/Materializations/utils.ts +145 -0
  147. package/src/components/Model/Model.tsx +44 -2
  148. package/src/components/Model/ModelCell.tsx +14 -5
  149. package/src/components/Model/ModelExplorer.tsx +3 -0
  150. package/src/components/Model/ModelExplorerDialog.tsx +4 -1
  151. package/src/components/Model/SourcesExplorer.tsx +9 -6
  152. package/src/components/Model/index.ts +3 -0
  153. package/src/components/Model/useModelData.ts +6 -3
  154. package/src/components/Notebook/Notebook.spec.tsx +88 -0
  155. package/src/components/Notebook/Notebook.tsx +476 -339
  156. package/src/components/Notebook/NotebookCell.tsx +264 -25
  157. package/src/components/Notebook/index.ts +3 -0
  158. package/src/components/Notebook/runPlan.spec.ts +155 -0
  159. package/src/components/Notebook/runPlan.ts +67 -0
  160. package/src/components/Notebook/types.ts +14 -0
  161. package/src/components/Package/ContentTypeIcon.spec.ts +91 -0
  162. package/src/components/Package/ContentTypeIcon.tsx +177 -0
  163. package/src/components/Package/FileTreeView.tsx +3 -0
  164. package/src/components/Package/Models.tsx +7 -4
  165. package/src/components/Package/Package.spec.tsx +113 -0
  166. package/src/components/Package/Package.tsx +692 -59
  167. package/src/components/Package/index.ts +3 -0
  168. package/src/components/QueryResult/QueryResult.tsx +17 -8
  169. package/src/components/QueryResult/index.ts +3 -0
  170. package/src/components/RenderedResult/RenderedResult.tsx +725 -67
  171. package/src/components/RenderedResult/ResultContainer.tsx +71 -2
  172. package/src/components/RenderedResult/index.ts +3 -0
  173. package/src/components/RenderedResult/renderLogs.spec.ts +58 -0
  174. package/src/components/RenderedResult/renderLogs.ts +43 -0
  175. package/src/components/ResultsDialog.tsx +13 -1
  176. package/src/components/ServerProvider.tsx +175 -51
  177. package/src/components/Workbook/BrowserWorkbookStorage.ts +3 -0
  178. package/src/components/Workbook/EditableMalloyCell.tsx +3 -0
  179. package/src/components/Workbook/ModelPicker.tsx +7 -4
  180. package/src/components/Workbook/MutableCell.tsx +10 -5
  181. package/src/components/Workbook/Workbook.tsx +8 -5
  182. package/src/components/Workbook/WorkbookList.tsx +3 -0
  183. package/src/components/Workbook/WorkbookManager.ts +3 -0
  184. package/src/components/Workbook/WorkbookStorage.ts +3 -0
  185. package/src/components/Workbook/WorkbookStorageProvider.tsx +3 -0
  186. package/src/components/Workbook/index.ts +3 -0
  187. package/src/components/click_helper.ts +17 -1
  188. package/src/components/drill/index.ts +28 -0
  189. package/src/components/drill/markDrillableCells.dom.spec.ts +313 -0
  190. package/src/components/drill/markDrillableCells.spec.ts +109 -0
  191. package/src/components/drill/markDrillableCells.ts +314 -0
  192. package/src/components/drill/resolveDrill.spec.ts +449 -0
  193. package/src/components/drill/resolveDrill.ts +375 -0
  194. package/src/components/drill/useDrill.tsx +203 -0
  195. package/src/components/filter/DimensionFilter.tsx +3 -0
  196. package/src/components/filter/index.ts +3 -0
  197. package/src/components/filter/utils.ts +16 -5
  198. package/src/components/given/GivenInput.spec.tsx +689 -0
  199. package/src/components/given/GivenInput.tsx +801 -0
  200. package/src/components/given/GivensPanel.spec.tsx +175 -0
  201. package/src/components/given/GivensPanel.tsx +195 -0
  202. package/src/components/given/filterValue.spec.ts +364 -0
  203. package/src/components/given/filterValue.ts +207 -0
  204. package/src/components/given/index.ts +9 -0
  205. package/src/components/given/paramCodec.spec.ts +857 -0
  206. package/src/components/given/paramCodec.ts +483 -0
  207. package/src/components/given/utils.spec.ts +60 -0
  208. package/src/components/given/utils.ts +79 -0
  209. package/src/components/highlighter.ts +22 -5
  210. package/src/components/index.ts +10 -2
  211. package/src/components/styles.ts +82 -33
  212. package/src/constants/docLinks.spec.ts +54 -0
  213. package/src/constants/docLinks.ts +46 -0
  214. package/src/hooks/givenValue.ts +13 -0
  215. package/src/hooks/index.ts +13 -0
  216. package/src/hooks/useDimensionFilters.ts +4 -7
  217. package/src/hooks/useDimensionFiltersFromSpec.ts +8 -5
  218. package/src/hooks/useDimensionFiltersQuery.ts +10 -13
  219. package/src/hooks/useDimensionalFilterRangeData.ts +11 -14
  220. package/src/hooks/useGivensState.spec.ts +449 -0
  221. package/src/hooks/useGivensState.ts +340 -0
  222. package/src/hooks/useModelGivens.ts +29 -0
  223. package/src/hooks/useQueryWithApiError.ts +3 -0
  224. package/src/hooks/useRawQueryData.ts +6 -3
  225. package/src/hooks/useSuggestOptions.dom.spec.ts +91 -0
  226. package/src/hooks/useSuggestOptions.spec.ts +112 -0
  227. package/src/hooks/useSuggestOptions.ts +268 -0
  228. package/src/index.ts +10 -1
  229. package/src/react-app-env.d.ts +3 -0
  230. package/src/theme/ThemeContext.tsx +86 -0
  231. package/src/theme/buildMalloyExplicitTheme.ts +61 -0
  232. package/src/theme/buildTableCssVars.spec.ts +86 -0
  233. package/src/theme/buildTableCssVars.ts +98 -0
  234. package/src/theme/buildVegaThemeOverride.spec.ts +56 -0
  235. package/src/theme/buildVegaThemeOverride.ts +47 -0
  236. package/src/theme/defaults.ts +78 -0
  237. package/src/theme/index.ts +11 -0
  238. package/src/theme/keys.ts +32 -0
  239. package/src/theme/readChartAnnotations.spec.ts +58 -0
  240. package/src/theme/readChartAnnotations.ts +69 -0
  241. package/src/theme/resolveTheme.spec.ts +160 -0
  242. package/src/theme/resolveTheme.ts +121 -0
  243. package/src/theme/types.ts +79 -0
  244. package/src/utils/dataAppEmbed.spec.ts +63 -0
  245. package/src/utils/dataAppEmbed.ts +84 -0
  246. package/src/utils/formatting.spec.ts +25 -21
  247. package/src/utils/formatting.ts +11 -7
  248. package/src/utils/malloyString.spec.ts +24 -0
  249. package/src/utils/malloyString.ts +12 -0
  250. package/src/utils/parsing.spec.ts +26 -19
  251. package/src/utils/parsing.ts +11 -6
  252. package/src/utils/queryClient.ts +17 -0
  253. package/test/README.md +185 -0
  254. package/test/serverProvider.tsx +72 -0
  255. package/test/setup.ts +29 -0
  256. package/tsconfig.json +12 -1
  257. package/tsconfig.spec.json +22 -0
  258. package/vite.config.ts +3 -0
  259. package/dist/ServerProvider-lOQXDlqB.cjs.js +0 -1
  260. package/dist/ServerProvider-on-8FH5Z.es.js +0 -3060
  261. package/dist/components/Home/AddProjectDialog.d.ts +0 -1
  262. package/dist/components/Home/DeleteProjectDialog.d.ts +0 -5
  263. package/dist/components/Home/EditProjectDialog.d.ts +0 -7
  264. package/dist/components/Package/Config.d.ts +0 -5
  265. package/dist/components/Package/Databases.d.ts +0 -5
  266. package/dist/components/Package/Notebooks.d.ts +0 -6
  267. package/dist/components/Project/Project.d.ts +0 -6
  268. package/dist/components/Project/index.d.ts +0 -2
  269. package/dist/index-BOLBP6_i.cjs.js +0 -233
  270. package/src/components/Package/Config.tsx +0 -97
  271. package/src/components/Package/Connections.tsx +0 -373
  272. package/src/components/Package/Databases.tsx +0 -228
  273. package/src/components/Package/Notebooks.tsx +0 -77
  274. package/src/components/Project/AddPackageDialog.tsx +0 -159
  275. package/src/components/Project/Packages.tsx +0 -191
  276. package/src/components/Project/Project.tsx +0 -52
  277. package/src/components/Project/index.ts +0 -2
  278. /package/dist/components/{Project → Environment}/About.d.ts +0 -0
  279. /package/dist/components/{Project → Environment}/AddPackageDialog.d.ts +0 -0
  280. /package/dist/components/{Project → Environment}/ConnectionExplorer.d.ts +0 -0
  281. /package/dist/components/{Package → Environment}/Connections.d.ts +0 -0
  282. /package/dist/components/{Project → Environment}/DeletePackageDialog.d.ts +0 -0
  283. /package/dist/components/{Project → Environment}/EditPackageDialog.d.ts +0 -0
  284. /package/dist/components/{Project → Environment}/Packages.d.ts +0 -0
@@ -1,7 +1,54 @@
1
- import React, { Suspense, useLayoutEffect, useRef } from "react";
1
+ // Copyright (c) Credible Data Inc.
2
+ // SPDX-License-Identifier: MIT
3
+
4
+ import { Box, useTheme } from "@mui/material";
5
+ import React, {
6
+ Suspense,
7
+ useCallback,
8
+ useEffect,
9
+ useLayoutEffect,
10
+ useMemo,
11
+ useRef,
12
+ } from "react";
13
+ import { buildMalloyExplicitTheme } from "../../theme/buildMalloyExplicitTheme";
14
+ import {
15
+ buildTableCssVars,
16
+ DASHBOARD_CARD_PADDING_PX,
17
+ type DashboardCardGeometry,
18
+ } from "../../theme/buildTableCssVars";
19
+ import { buildVegaThemeOverride } from "../../theme/buildVegaThemeOverride";
20
+ import { readChartAnnotations } from "../../theme/readChartAnnotations";
21
+ import { resolveTheme } from "../../theme/resolveTheme";
22
+ import { usePublisherTheme } from "../../theme/ThemeContext";
23
+ import type { ResolvedTheme } from "../../theme/types";
24
+ import {
25
+ DRILL_CELL_CLASS,
26
+ moveDrillStop,
27
+ drillableFieldNames,
28
+ markDrillableCells,
29
+ type DrillMetadataSource,
30
+ } from "../drill/markDrillableCells";
31
+ import type { DrillClickPayload } from "../drill/resolveDrill";
32
+ import type { DrillBinding } from "../drill/useDrill";
2
33
 
3
34
  type MalloyRenderElement = HTMLElement & Record<string, unknown>;
4
35
 
36
+ /**
37
+ * Loose alias for the {@link MalloyViz} instance returned by createViz().
38
+ * Avoids pinning the SDK to a specific class import; we only call methods
39
+ * declared on the renderer's public type. Keep in sync with
40
+ * `@malloydata/render` if more methods are needed.
41
+ */
42
+ interface MalloyVizHandle extends DrillMetadataSource {
43
+ setResult: (result: unknown) => void;
44
+ render: (element: HTMLElement) => void;
45
+ remove: () => void;
46
+ // Fires once the chart has painted (or immediately if it already has). We
47
+ // use it to swap a freshly-rendered chart in only when it's ready, so the
48
+ // previously-painted chart never blanks out mid-render.
49
+ onReady: (callback: () => void) => void;
50
+ }
51
+
5
52
  declare global {
6
53
  // eslint-disable-next-line @typescript-eslint/no-namespace
7
54
  namespace JSX {
@@ -19,61 +66,365 @@ interface RenderedResultProps {
19
66
  height?: number;
20
67
  isFillElement?: (boolean) => void;
21
68
  onSizeChange?: (height: number) => void;
22
- onDrill?: (element: unknown) => void;
69
+ /**
70
+ * Makes `# drill` cells clickable, and makes them look it. From `useDrill`
71
+ * on the host surface, which decides where a click may go; omitted where
72
+ * nothing can act on one, and then the result renders inert.
73
+ */
74
+ drill?: DrillBinding;
23
75
  }
24
76
 
25
- // Simple dynamic import function
26
- const createRenderer = async (onDrill?: (element: unknown) => void) => {
27
- // Only import when we're in a browser environment
77
+ const createRenderer = async (
78
+ theme: ResolvedTheme,
79
+ onClick?: DrillBinding["onClick"],
80
+ ): Promise<MalloyVizHandle> => {
28
81
  if (typeof window === "undefined") {
29
82
  throw new Error("MalloyRenderer can only be used in browser environment");
30
83
  }
31
84
 
32
85
  const { MalloyRenderer } = await import("@malloydata/render");
33
86
  const renderer = new MalloyRenderer({
34
- onClick: onDrill,
87
+ onClick,
88
+ vegaConfigOverride: buildVegaThemeOverride(theme),
89
+ // Pass the explicit theme so table chrome and dashboard tiles
90
+ // pick up the operator's colours directly. Without this the
91
+ // renderer's own inline style writes `--malloy-render--*` values
92
+ // sourced from its built-in defaults and shadows whatever we set
93
+ // on the outer wrapper.
94
+ theme: buildMalloyExplicitTheme(theme),
35
95
  onError: (error) => {
36
96
  console.error("Error rendering visualization:", typeof error, error);
37
97
  },
38
98
  });
39
- return renderer.createViz();
99
+ return renderer.createViz() as MalloyVizHandle;
40
100
  };
41
101
 
42
- // Inner component that actually renders the visualization
102
+ // Warm the renderer chunk as soon as this module loads so the first chart
103
+ // paint doesn't have to wait on the dynamic import resolving (the async
104
+ // import is what widened the clear-then-repaint gap into a visible flicker).
105
+ if (typeof window !== "undefined") {
106
+ void import("@malloydata/render");
107
+ }
108
+
109
+ /**
110
+ * Pull a per-chart Theme override out of a parsed Malloy result by reading
111
+ * `# theme.*` annotations on the model and the query. Returns `undefined`
112
+ * if no theme annotations are present, the shape is unexpected, or the
113
+ * annotation parser is unavailable at runtime.
114
+ *
115
+ * Three failure modes are kept distinct so a malformed annotation doesn't
116
+ * masquerade as a missing dependency:
117
+ *
118
+ * 1. No `theme.*` annotations in the result — return undefined silently.
119
+ * 2. `@malloydata/malloy-tag` not resolvable at runtime — return undefined
120
+ * silently. SDK consumers may bundle without it; the chart still renders.
121
+ * 3. Parser threw on a malformed annotation — return undefined AND log a
122
+ * `console.warn` with the offending lines so authors see the typo.
123
+ */
124
+ async function extractChartThemeOverride(parsed: unknown) {
125
+ if (!parsed || typeof parsed !== "object") return undefined;
126
+ const r = parsed as {
127
+ annotations?: Array<{ value?: string }>;
128
+ model_annotations?: Array<{ value?: string }>;
129
+ source_annotations?: Array<{ value?: string }>;
130
+ };
131
+ const lines = [
132
+ ...(Array.isArray(r.model_annotations) ? r.model_annotations : []),
133
+ ...(Array.isArray(r.source_annotations) ? r.source_annotations : []),
134
+ ...(Array.isArray(r.annotations) ? r.annotations : []),
135
+ ]
136
+ .map((a) => (typeof a?.value === "string" ? a.value : undefined))
137
+ .filter((s): s is string => Boolean(s));
138
+ if (lines.length === 0) return undefined;
139
+
140
+ let parseAnnotation: typeof import("@malloydata/malloy-tag").parseAnnotation;
141
+ try {
142
+ ({ parseAnnotation } = await import("@malloydata/malloy-tag"));
143
+ } catch {
144
+ // Missing peer dep is an acceptable fallback. Charts render with the
145
+ // shell theme only.
146
+ return undefined;
147
+ }
148
+
149
+ try {
150
+ const { tag } = parseAnnotation(lines);
151
+ return readChartAnnotations(tag);
152
+ } catch (error) {
153
+ console.warn(
154
+ "Failed to parse # theme.* annotations; chart will render with the shell theme.",
155
+ { error, lines },
156
+ );
157
+ return undefined;
158
+ }
159
+ }
160
+
161
+ function applyTableCssVars(
162
+ element: HTMLElement,
163
+ theme: ResolvedTheme,
164
+ card: DashboardCardGeometry,
165
+ ): void {
166
+ const vars = buildTableCssVars(theme, card);
167
+ for (const [key, value] of Object.entries(vars)) {
168
+ element.style.setProperty(key, value);
169
+ }
170
+ }
171
+
172
+ /**
173
+ * CSS overrides for the renderer's own hardcoded colours.
174
+ *
175
+ * These are appended as a `<style>` in `document.head` by
176
+ * `injectRendererOverrides` below, which is the mechanism actually in use and
177
+ * is described where it happens. An earlier version of this block said the
178
+ * renderer puts its DOM in a Shadow Root and that we register through
179
+ * `MalloyViz.addStylesheet()`. Neither is true of this code: nothing here calls
180
+ * that API, and were the boundary real a `document.head` stylesheet could not
181
+ * reach `.malloy-dashboard` at all, which is precisely what these rules do and
182
+ * what the theming tests check. Selectors are written at higher specificity
183
+ * than the renderer's own so they win regardless of stylesheet order.
184
+ */
185
+ const PUBLISHER_RENDERER_OVERRIDES_CSS = `
186
+ /* Card geometry, through the renderer's OWN theme vars rather than over the top
187
+ of them. It declares --malloy-theme--dashboard-* on .malloy-render itself and
188
+ passes each through to the --malloy-render--* the card CSS reads, so a value
189
+ inherited from our wrapper loses to that declaration however early it is set:
190
+ this has to be a rule on the same element, at higher specificity. Doubling the
191
+ class does that, and then no !important is needed — which matters, because
192
+ !important here also lands on .dashboard-item-borderless and repaints a card
193
+ the author asked to have no card. */
194
+ .malloy-render.malloy-render {
195
+ --malloy-theme--dashboard-card-radius: var(--publisher-dashboard-card-radius);
196
+ --malloy-theme--dashboard-card-padding: var(--publisher-dashboard-card-padding);
197
+ }
198
+ /* dashboard.css hardcodes background: #f7f9fc on .malloy-dashboard
199
+ and .dashboard-row-header, which would paint light grey in dark
200
+ mode and also bleed an operator-picked palette.background across
201
+ the panel chrome in light. Both surfaces use
202
+ --malloy-render--background here, which buildMalloyExplicitTheme
203
+ wires to dashboardRoot: a mode-keyed neutral that stays decoupled
204
+ from palette.background (the chart canvas) on purpose. Selectors
205
+ are duplicated at higher specificity to beat the renderer s own
206
+ scoped rules. */
207
+ .malloy-render .malloy-dashboard,
208
+ .malloy-render.malloy-render .malloy-dashboard,
209
+ div.malloy-render .malloy-dashboard {
210
+ /* --publisher-dashboard-root is set on the outer Publisher wrapper
211
+ (see buildTableCssVars) and stays decoupled from
212
+ --malloy-render--background, which gets shadowed inside the
213
+ renderer when a theme.background annotation is present. The
214
+ dedicated var means the panel between tiles always paints the
215
+ operator neutral dashboardRoot regardless of annotations. */
216
+ background: var(--publisher-dashboard-root) !important;
217
+ background-color: var(--publisher-dashboard-root) !important;
218
+ color: var(--malloy-render--table-body-color) !important;
219
+ }
220
+ .malloy-render .malloy-dashboard .dashboard-row,
221
+ .malloy-render .malloy-dashboard .dashboard-row-body,
222
+ .malloy-render .malloy-dashboard .dashboard-row-header,
223
+ .malloy-render.malloy-render .malloy-dashboard .dashboard-row-header,
224
+ div.malloy-render .malloy-dashboard .dashboard-row-header {
225
+ /* Belt + suspenders: dashboard.css hardcodes .dashboard-row-header
226
+ to #f7f9fc, and row / row-body have no explicit background but
227
+ get caught in any annotation-driven inline writes. Force all of
228
+ them to the neutral panel colour. */
229
+ background: var(--publisher-dashboard-root) !important;
230
+ background-color: var(--publisher-dashboard-root) !important;
231
+ }
232
+ .malloy-render .malloy-dashboard .dashboard-item:not(.dashboard-item-borderless) {
233
+ /* Tile padding around each chart / table. Uses our custom
234
+ --malloy-render--tile-background so the operator can theme the
235
+ tile separately from the table header row (which paints from
236
+ --malloy-render--table-pinned-background below).
237
+
238
+ A flat bordered card rather than the renderer's shadow ring, which is what
239
+ makes it match the composite tile's Paper. :not(borderless) because
240
+ # borderless asks for no card at all, and an !important background and
241
+ border drew one anyway. */
242
+ background: var(--malloy-render--tile-background) !important;
243
+ color: var(--malloy-render--table-body-color) !important;
244
+ box-shadow: none !important;
245
+ border: var(--malloy-render--table-border) !important;
246
+ }
247
+ .malloy-render .malloy-dashboard .dashboard-row-header-separator {
248
+ background: var(--malloy-render--table-border) !important;
249
+ }
250
+ .malloy-render .malloy-table .th.column-cell {
251
+ /* Non-pinned tables have no header background in the renderer's
252
+ own CSS (only pinned scrolled tables paint the pinned-header
253
+ with this var). Force the same value here so every table has a
254
+ visible header band reflecting the operator's choice. */
255
+ background: var(--malloy-render--table-pinned-background) !important;
256
+ }
257
+ .malloy-render .dashboard-item-title,
258
+ .malloy-render .dashboard-dimension-name {
259
+ color: var(--malloy-render--label-color) !important;
260
+ }
261
+ .malloy-render .dashboard-item-value,
262
+ .malloy-render .dashboard-item-value-measure,
263
+ .malloy-render .dashboard-dimension-value {
264
+ color: var(--malloy-render--value-color) !important;
265
+ }
266
+ .malloy-render .malloy-table,
267
+ .malloy-render .malloy-list {
268
+ color: var(--malloy-render--table-body-color) !important;
269
+ }
270
+ .malloy-render .column-cell.th,
271
+ .malloy-render .cell-content.header {
272
+ color: var(--malloy-render--table-header-color) !important;
273
+ }
274
+ /* A cell whose column declares a "# drill" this surface can honor, marked
275
+ by markDrillableCells. Ordinary text with a pointer cursor until hovered,
276
+ then it reads as a link: the same affordance Malloyyo gives the same tag,
277
+ and the only thing that tells a reader a cell navigates. Kept off the
278
+ resting state deliberately: a column painted blue competes with the data.
279
+ (No backticks in here: this is inside a template literal.) */
280
+ .malloy-render .${DRILL_CELL_CLASS} {
281
+ cursor: pointer;
282
+ }
283
+ .malloy-render .${DRILL_CELL_CLASS}:hover > .cell-content {
284
+ color: var(--publisher-drill-link) !important;
285
+ text-decoration: underline;
286
+ }
287
+ /* Keyboard focus reads the same as hover, plus a ring: a hover colour is not
288
+ something a keyboard user can produce, and a focus ring is not something a
289
+ mouse user sees. focus-visible rather than focus, so a click does not leave a
290
+ ring behind it. (No backticks in here: this is inside a template literal.) */
291
+ .malloy-render .${DRILL_CELL_CLASS}:focus-visible {
292
+ outline: 2px solid var(--publisher-drill-link);
293
+ outline-offset: -2px;
294
+ }
295
+ .malloy-render .${DRILL_CELL_CLASS}:focus-visible > .cell-content {
296
+ color: var(--publisher-drill-link) !important;
297
+ text-decoration: underline;
298
+ }
299
+ `;
300
+
301
+ /**
302
+ * Append the overrides as a `<style>` in `document.head`. The renderer
303
+ * adds its own styles the same way (`MalloyViz.addStylesheet` just calls
304
+ * `document.head.appendChild(<style>)`), so this puts our rules in the
305
+ * same cascade. Our selectors are written at higher specificity than the
306
+ * renderer's nested `.malloy-dashboard .dashboard-item`, with !important,
307
+ * so they win whether they land before or after the renderer's stylesheet.
308
+ *
309
+ * Idempotent: the style element is keyed by id, so re-mounts skip
310
+ * re-injection.
311
+ */
312
+ const PUBLISHER_RENDERER_OVERRIDE_ID = "publisher-malloy-renderer-overrides";
313
+ function injectRendererOverrides(): void {
314
+ if (typeof document === "undefined") return;
315
+ if (document.getElementById(PUBLISHER_RENDERER_OVERRIDE_ID)) return;
316
+ const style = document.createElement("style");
317
+ style.id = PUBLISHER_RENDERER_OVERRIDE_ID;
318
+ style.textContent = PUBLISHER_RENDERER_OVERRIDES_CSS;
319
+ document.head.appendChild(style);
320
+ }
321
+
43
322
  function RenderedResultInner({
44
323
  result,
45
324
  height: inputHeight,
46
- onDrill,
325
+ drill,
47
326
  onSizeChange,
48
327
  }: RenderedResultProps) {
49
328
  const ref = useRef<HTMLDivElement>(null);
329
+ // The renderer binds its click handler at construction, so a changing
330
+ // `drill` identity would otherwise re-run the render effect and rebuild the
331
+ // chart: undoing the no-flicker swap below every time the parent
332
+ // re-renders. Read the latest binding through a ref instead, and keep
333
+ // `drill` out of the effect's dependencies, so callers can pass an inline
334
+ // one safely.
335
+ const drillRef = useRef(drill);
336
+ drillRef.current = drill;
337
+ const handleDrillClick = useCallback((payload: DrillClickPayload) => {
338
+ drillRef.current?.onClick(payload);
339
+ }, []);
340
+ // Whether any drill is wired at all, which is what the effect reacts to: a
341
+ // surface that gains or loses the capability has to (re)mark its cells, but
342
+ // a new inline binding with the same capability must not rebuild anything.
343
+ //
344
+ // KNOWN LIMITATION, and the narrower alternative is worse. `canDrill` decides
345
+ // WHICH cells get marked and is read once per render pass, so a predicate
346
+ // that changes while the result stays put leaves the previous pass's marks in
347
+ // place. Depending on the predicate's identity instead was tried and reverted:
348
+ // `canDrill` chains back to the notebook's parameters, so every control edit
349
+ // tore down and rebuilt every chart, which is the flicker this component was
350
+ // fixed for. The stale case needs a host whose predicate resolves after first
351
+ // paint against an unchanged result; it cannot happen in the notebook, where
352
+ // anything that changes the declared givens also rebuilds the cells. Fixing
353
+ // it properly means re-marking without re-rendering, which is a change to the
354
+ // marking pass rather than to this dependency list.
355
+ const drillable = drill !== undefined;
50
356
  const hasMeasuredRef = useRef(false);
357
+ // The chart currently painted into the container, held across renders. A
358
+ // new render paints into a fresh offscreen stage and only swaps in (and
359
+ // disposes this one) once it's ready, so the container never blanks between
360
+ // charts. That up-front clear + cleanup dispose was the flicker.
361
+ const liveRef = useRef<{ viz: MalloyVizHandle; node: HTMLElement } | null>(
362
+ null,
363
+ );
364
+ // Bumped on every render-effect run and on unmount. A slow async render that
365
+ // resolves after a newer one has started (or after unmount) checks this and
366
+ // bails, so overlapping renders can't leave two charts or leak a viz.
367
+ const renderGenRef = useRef(0);
368
+ const { theme: baseTheme, layers, mode } = usePublisherTheme();
369
+ // The host app's card radius, so a dashboard card reads as a card of the app
370
+ // it is embedded in rather than as the renderer's 8px on a 4px page. Both
371
+ // cards take it from here; see DashboardTile, which is the other one.
372
+ const cardRadius = useTheme().shape.borderRadius;
373
+ // Memoized because it is a dependency of the render effect below, and a fresh
374
+ // object each render would re-render the chart on every render.
375
+ const cardGeometry = useMemo<DashboardCardGeometry>(
376
+ () => ({
377
+ radius: `${cardRadius}px`,
378
+ padding: `${DASHBOARD_CARD_PADDING_PX}px`,
379
+ }),
380
+ [cardRadius],
381
+ );
382
+
383
+ // Dispose the last live viz on unmount only. Deliberately NOT done in the
384
+ // render effect's cleanup: a re-run must keep the old chart until the new
385
+ // one has painted, and the new render disposes it during the swap.
386
+ useEffect(() => {
387
+ return () => {
388
+ renderGenRef.current += 1;
389
+ liveRef.current?.viz.remove();
390
+ liveRef.current = null;
391
+ };
392
+ }, []);
51
393
 
52
- // Render the visualization once the component mounts
53
394
  useLayoutEffect(() => {
54
395
  if (!ref.current || !result) return;
55
396
 
56
- let isMounted = true;
57
- const element = ref.current;
58
-
59
- // Clear previous content
60
- while (element.firstChild) {
61
- element.removeChild(element.firstChild);
62
- }
63
-
64
- // Reset measurement flag when result changes
65
- hasMeasuredRef.current = false;
397
+ injectRendererOverrides();
66
398
 
67
- // Set up observer to measure size after render completes
399
+ const element = ref.current;
400
+ const myGen = (renderGenRef.current += 1);
401
+ let cancelled = false;
402
+ const isCurrent = () => !cancelled && myGen === renderGenRef.current;
403
+ // Created inside the async body; hoisted so cleanup can tear them down
404
+ // if this render is superseded before it swaps itself into `liveRef`.
405
+ let stage: HTMLDivElement | undefined;
406
+ let viz: MalloyVizHandle | undefined;
407
+ let drillObserver: MutationObserver | null = null;
408
+ let drillFrame = 0;
409
+ let drillKeydown: ((event: KeyboardEvent) => void) | null = null;
410
+ let drillKeyup: ((event: KeyboardEvent) => void) | null = null;
411
+ let drillFocusIn: ((event: FocusEvent) => void) | null = null;
68
412
  let observer: MutationObserver | null = null;
69
413
  let measureTimeout: NodeJS.Timeout | null = null;
414
+ // Safety net so a render that never signals ready (an async renderer
415
+ // error that only reaches onError) can't leave a previous chart showing
416
+ // stale data forever; see the setTimeout below.
417
+ let readyFallback: ReturnType<typeof setTimeout> | null = null;
70
418
 
71
- const measureRenderedSize = () => {
72
- // Skip if already measured or unmounted
73
- if (hasMeasuredRef.current || !isMounted || !element.firstElementChild)
419
+ hasMeasuredRef.current = false;
420
+
421
+ // Measure the rendered chart's natural height off `root` (the stage that
422
+ // wraps the renderer output) and report it up. Same grandchild/dashboard
423
+ // HACK as before, just anchored on the stage wrapper.
424
+ const measureRenderedSize = (root: HTMLElement) => {
425
+ if (hasMeasuredRef.current || cancelled || !root.firstElementChild)
74
426
  return;
75
- // It's the grandchild that is the actual visualization.
76
- const child = element.firstElementChild as HTMLElement;
427
+ const child = root.firstElementChild as HTMLElement;
77
428
  const grandchild = child.firstElementChild as HTMLElement;
78
429
  if (!grandchild) return;
79
430
  const greatgrandchild = grandchild.firstElementChild as HTMLElement;
@@ -99,45 +450,354 @@ function RenderedResultInner({
99
450
  }
100
451
  };
101
452
 
102
- createRenderer(onDrill)
103
- .then((viz) => {
104
- if (!isMounted) return;
105
-
106
- // Set up mutation observer to detect when rendering is complete
107
- observer = new MutationObserver(() => {
108
- // Debounce - wait for mutations to settle
109
- if (measureTimeout) clearTimeout(measureTimeout);
110
- measureTimeout = setTimeout(() => {
111
- measureRenderedSize();
112
- // Disconnect after measuring to prevent infinite loops
113
- observer?.disconnect();
114
- }, 100);
115
- });
116
-
117
- observer.observe(element, {
118
- childList: true,
119
- subtree: true,
120
- attributes: true,
121
- });
453
+ (async () => {
454
+ let parsed: unknown;
455
+ try {
456
+ parsed = JSON.parse(result);
457
+ } catch (error) {
458
+ console.error("Error parsing visualization result:", error);
459
+ return;
460
+ }
122
461
 
123
- try {
124
- viz.setResult(JSON.parse(result));
125
- viz.render(element);
126
- } catch (error) {
127
- console.error("Error rendering visualization:", error);
128
- observer?.disconnect();
129
- }
130
- })
131
- .catch((error) => {
462
+ const perChart = await extractChartThemeOverride(parsed);
463
+ const effectiveTheme = perChart
464
+ ? resolveTheme([...layers, perChart], mode)
465
+ : baseTheme;
466
+
467
+ if (!isCurrent()) return;
468
+
469
+ try {
470
+ viz = await createRenderer(effectiveTheme, handleDrillClick);
471
+ } catch (error) {
132
472
  console.error("Failed to create renderer:", error);
473
+ return;
474
+ }
475
+ if (!isCurrent()) {
476
+ // Superseded during the dynamic import / construction.
477
+ viz.remove();
478
+ viz = undefined;
479
+ return;
480
+ }
481
+
482
+ // Render into a fresh stage appended to the container. While a
483
+ // previous chart is still on screen, keep the stage laid out (so the
484
+ // fill chart actually measures a size and `onReady` fires) but hidden
485
+ // and overlaid; reveal it and drop the old chart only once painted.
486
+ const previous = liveRef.current;
487
+ stage = document.createElement("div");
488
+ stage.style.width = "100%";
489
+ stage.style.height = "100%";
490
+ // Theme the chart's table/dashboard chrome on the stage itself, not on
491
+ // the shared container: during a swap the outgoing chart is still a
492
+ // child of the container, so writing the new per-chart CSS vars there
493
+ // would repaint the old chart's chrome to the new theme before it is
494
+ // swapped out. Scoping the vars to this stage keeps each chart stable.
495
+ applyTableCssVars(stage, effectiveTheme, cardGeometry);
496
+ if (previous) {
497
+ element.style.position = "relative";
498
+ stage.style.position = "absolute";
499
+ stage.style.inset = "0";
500
+ stage.style.visibility = "hidden";
501
+ }
502
+ element.appendChild(stage);
503
+
504
+ // Fallback measurement if `onReady` never fires: settle on DOM
505
+ // mutations, then measure once.
506
+ const stageNode = stage;
507
+ observer = new MutationObserver(() => {
508
+ if (measureTimeout) clearTimeout(measureTimeout);
509
+ measureTimeout = setTimeout(() => {
510
+ measureRenderedSize(stageNode);
511
+ observer?.disconnect();
512
+ }, 100);
133
513
  });
514
+ observer.observe(stage, {
515
+ childList: true,
516
+ subtree: true,
517
+ attributes: true,
518
+ });
519
+
520
+ const activeViz = viz;
521
+ let promoted = false;
522
+ const promote = () => {
523
+ if (promoted || !isCurrent()) return;
524
+ promoted = true;
525
+ if (readyFallback) {
526
+ clearTimeout(readyFallback);
527
+ readyFallback = null;
528
+ }
529
+ // The new chart has painted; drop the outgoing one now.
530
+ if (previous) {
531
+ previous.viz.remove();
532
+ if (previous.node.parentNode === element) {
533
+ element.removeChild(previous.node);
534
+ }
535
+ }
536
+ stageNode.style.position = "";
537
+ stageNode.style.inset = "";
538
+ stageNode.style.visibility = "";
539
+ element.style.position = "";
540
+ liveRef.current = { viz: activeViz, node: stageNode };
541
+ measureRenderedSize(stageNode);
542
+ };
543
+
544
+ try {
545
+ // The renderer accepts a Malloy Result; we don't import that type
546
+ // in the SDK to avoid pinning to the malloy core types here.
547
+ viz.setResult(parsed);
548
+ viz.render(stage);
549
+
550
+ // Mark the cells a `# drill` makes clickable, so they read as
551
+ // links. The names come from the result's field metadata, which is
552
+ // complete as soon as it is set, but the DOM is not: a
553
+ // `# dashboard` result builds its cards over later frames, so a
554
+ // one-shot pass right after render() would miss every table that
555
+ // appears after it. Hence the observer, which re-marks (batched to
556
+ // a frame) as cards arrive.
557
+ const binding = drillRef.current;
558
+ // Isolated from the render above. The chart has already rendered by
559
+ // this point, and a throw in here would reach the same catch and
560
+ // replace a working result with an error message: the affordance
561
+ // would be taking the chart down with it. `drillableFieldNames`
562
+ // already guards its own metadata read on the same principle.
563
+ try {
564
+ if (binding) {
565
+ const names = drillableFieldNames(viz, binding.canDrill);
566
+ // Guarded INSIDE, not just at the first call. The try
567
+ // below wraps this function's definition, not the frames the
568
+ // observer schedules it on, so a throw on a re-mark escaped
569
+ // to the window and the isolation only ever covered the
570
+ // synchronous pass.
571
+ const mark = () => {
572
+ try {
573
+ markDrillableCells(stageNode, names);
574
+ } catch (markError) {
575
+ console.warn("Drill affordance skipped:", markError);
576
+ }
577
+ };
578
+ mark();
579
+ // Enter and Space fire the drill for a focused cell. Delegated
580
+ // on the stage rather than bound per cell, because the
581
+ // renderer rebuilds cells as a dashboard's cards arrive and a
582
+ // per-cell listener would be lost with them; this one outlives
583
+ // every re-mark.
584
+ //
585
+ // It synthesises a CLICK rather than calling the drill handler
586
+ // directly, so the payload comes from the renderer's own click
587
+ // path. Building one here would mean re-deriving which field
588
+ // and value a cell represents, which is exactly the mapping
589
+ // this module has no access to and the reason the affordance
590
+ // is matched on rendered text in the first place.
591
+ //
592
+ // The click goes to the cell's INNER `.cell-content`, not to
593
+ // the cell. Measured, because dispatching on the cell looked
594
+ // right and silently did nothing: a real mouse click lands on
595
+ // `.cell-content` and the renderer reads the event target to
596
+ // identify the field, so a click on the outer cell reaches the
597
+ // handler with a target it does not recognise and is dropped
598
+ // without a sound. Falls back to the cell for a shape that has
599
+ // no inner content node.
600
+ //
601
+ // Enter fires on keydown and Space on keyUP, which is the
602
+ // native button rule and is load-bearing here rather than
603
+ // pedantry. Firing Space on keydown opened the drill menu and
604
+ // then the SAME keypress's keyup landed on the now-focused
605
+ // first menu item and chose it, so a Space drill navigated
606
+ // straight past the menu it had just opened. Measured: the
607
+ // menu was visible while the key was held and gone, with the
608
+ // URL already changed, once it was released.
609
+ //
610
+ // Dispatched with the cell's own coordinates rather than
611
+ // through `HTMLElement.click()`, which reports `clientX/Y` as
612
+ // 0. A drill offering two destinations anchors its menu on
613
+ // those numbers (`useDrill` holds no ref into the renderer's
614
+ // DOM), so a keyboard-opened menu appeared in the corner of
615
+ // the viewport instead of beside the cell it came from.
616
+ const fire = (cell: Element) => {
617
+ const content =
618
+ cell.querySelector<HTMLElement>(".cell-content");
619
+ const target = content ?? (cell as HTMLElement);
620
+ const rect = target.getBoundingClientRect();
621
+ target.dispatchEvent(
622
+ new MouseEvent("click", {
623
+ bubbles: true,
624
+ cancelable: true,
625
+ view: target.ownerDocument.defaultView,
626
+ clientX: Math.round(rect.left + rect.width / 2),
627
+ clientY: Math.round(rect.bottom),
628
+ }),
629
+ );
630
+ };
631
+ const drillCell = (event: KeyboardEvent) =>
632
+ (
633
+ event.target as HTMLElement | null
634
+ )?.closest?.<HTMLElement>(`.${DRILL_CELL_CLASS}`) ?? null;
635
+ // Move the single tab stop within a drillable column.
636
+ // `markDrillableCells` gives a column one stop rather than one
637
+ // per cell, so these keys are how a reader reaches the other
638
+ // rows; without them the affordance would only ever fire on
639
+ // whichever row held the stop. Clamped rather than wrapping,
640
+ // which is what a table's rows read as.
641
+ const rove = (
642
+ cell: HTMLElement,
643
+ to: number | "first" | "last",
644
+ ) => {
645
+ // The move lives in `markDrillableCells` beside the column
646
+ // rule, because it has to hold the same invariant the
647
+ // marking does: exactly one stop per column. Doing it here
648
+ // by clearing the focused cell assumed that cell HELD the
649
+ // stop, which a click-focused `tabindex="-1"` cell does not.
650
+ moveDrillStop(cell, to)?.focus();
651
+ };
652
+ drillKeydown = (event: KeyboardEvent) => {
653
+ const cell = drillCell(event) as HTMLElement | null;
654
+ if (!cell) return;
655
+ const roveKey =
656
+ event.key === "ArrowDown"
657
+ ? 1
658
+ : event.key === "ArrowUp"
659
+ ? -1
660
+ : event.key === "Home"
661
+ ? ("first" as const)
662
+ : event.key === "End"
663
+ ? ("last" as const)
664
+ : undefined;
665
+ if (roveKey !== undefined) {
666
+ // Prevented whether or not the move happened, so the
667
+ // first and last rows do not scroll the page out from
668
+ // under a reader who is still inside the column.
669
+ event.preventDefault();
670
+ rove(cell, roveKey);
671
+ return;
672
+ }
673
+ if (event.key === "Enter") {
674
+ // Otherwise Enter submits an enclosing form on an
675
+ // embedding host.
676
+ event.preventDefault();
677
+ fire(cell);
678
+ } else if (event.key === " ") {
679
+ // Held Space scrolls the page; the activation itself
680
+ // waits for keyup.
681
+ event.preventDefault();
682
+ }
683
+ };
684
+ drillKeyup = (event: KeyboardEvent) => {
685
+ if (event.key !== " ") return;
686
+ const cell = drillCell(event);
687
+ if (!cell) return;
688
+ event.preventDefault();
689
+ fire(cell);
690
+ };
691
+ // Focus and the tab stop have to agree however focus got
692
+ // there. The arrow handler moves the stop, but a
693
+ // `tabindex="-1"` cell is still CLICK-focusable, so without
694
+ // this a reader who clicked row 5, tabbed away and tabbed back
695
+ // landed on row 0. That is the same asymmetry the arrow path
696
+ // already fixes, for the one way of arriving that does not go
697
+ // through it. `moveDrillStop(cell, 0)` resolves to the cell
698
+ // itself, so it just makes that cell the column's stop.
699
+ drillFocusIn = (event: FocusEvent) => {
700
+ const cell = (
701
+ event.target as HTMLElement | null
702
+ )?.closest?.<HTMLElement>(`.${DRILL_CELL_CLASS}`);
703
+ if (cell) moveDrillStop(cell, 0);
704
+ };
705
+ stageNode.addEventListener("keydown", drillKeydown);
706
+ stageNode.addEventListener("keyup", drillKeyup);
707
+ stageNode.addEventListener("focusin", drillFocusIn);
708
+ if (
709
+ names.size > 0 &&
710
+ typeof MutationObserver !== "undefined"
711
+ ) {
712
+ drillObserver = new MutationObserver(() => {
713
+ cancelAnimationFrame(drillFrame);
714
+ drillFrame = requestAnimationFrame(mark);
715
+ });
716
+ // childList only: marking writes classes, and observing
717
+ // attributes would have it retrigger itself every frame.
718
+ drillObserver.observe(stageNode, {
719
+ childList: true,
720
+ subtree: true,
721
+ });
722
+ }
723
+ }
724
+ } catch (drillError) {
725
+ // No affordance, and the result stands. Clicks still resolve,
726
+ // because the renderer routes those itself.
727
+ console.warn("Drill affordance skipped:", drillError);
728
+ }
729
+
730
+ viz.onReady(promote);
731
+ // If onReady never fires (an async render error that only reaches
732
+ // the renderer's onError), force the swap after a bounded wait so
733
+ // the outcome becomes visible instead of the previous chart
734
+ // lingering with stale data indefinitely.
735
+ readyFallback = setTimeout(promote, 10000);
736
+ } catch (error) {
737
+ console.error("Error rendering visualization:", error);
738
+ observer?.disconnect();
739
+ drillObserver?.disconnect();
740
+ viz.remove();
741
+ viz = undefined;
742
+ if (stageNode.parentNode === element) {
743
+ element.removeChild(stageNode);
744
+ }
745
+ }
746
+ })();
134
747
 
135
748
  return () => {
136
- isMounted = false;
749
+ cancelled = true;
137
750
  observer?.disconnect();
138
751
  if (measureTimeout) clearTimeout(measureTimeout);
752
+ if (readyFallback) clearTimeout(readyFallback);
753
+ // If this render built a stage but never swapped it into `liveRef`
754
+ // (superseded, or unmounted mid-render), tear it down so it can't
755
+ // leak a viz or leave an orphan node behind.
756
+ if (stage && liveRef.current?.node !== stage) {
757
+ // The keyboard listeners go with the stage, and ONLY with the
758
+ // stage. Removing them unconditionally tied their lifetime to the
759
+ // effect RUN instead, while the stage's is tied to `liveRef`: a
760
+ // re-run tore them off the chart that is still on screen, which
761
+ // keeps its `tabindex` and `role="button"` and so still says Enter
762
+ // and Space do something. Usually that window closes when the new
763
+ // render promotes, but a render that never gets that far (a parse
764
+ // failure, a renderer that throws) leaves the visible chart
765
+ // permanently keyboard-dead while still advertising otherwise.
766
+ // Left on a promoted stage they are collected with the node when
767
+ // `promote` removes it, so nothing leaks by keeping them.
768
+ if (drillKeydown)
769
+ stage.removeEventListener("keydown", drillKeydown);
770
+ if (drillKeyup) stage.removeEventListener("keyup", drillKeyup);
771
+ if (drillFocusIn)
772
+ stage.removeEventListener("focusin", drillFocusIn);
773
+ // The re-marker is scoped the same way, and for the same reason.
774
+ // Disconnecting it unconditionally tied it to the effect RUN: a
775
+ // re-run while a `# dashboard` was still building its cards stopped
776
+ // the LIVE stage being re-marked, so cards arriving after that point
777
+ // never became drillable. Like the listeners, it is collected with
778
+ // the node once a promoted stage is dropped.
779
+ drillObserver?.disconnect();
780
+ cancelAnimationFrame(drillFrame);
781
+ viz?.remove();
782
+ if (stage.parentNode === element) {
783
+ element.removeChild(stage);
784
+ }
785
+ // This render may have set the container position:relative for its
786
+ // overlay stage but never promoted; reset it so no stray relative
787
+ // lingers on the container.
788
+ element.style.position = "";
789
+ }
139
790
  };
140
- }, [result, onDrill, onSizeChange]);
791
+ }, [
792
+ result,
793
+ handleDrillClick,
794
+ drillable,
795
+ onSizeChange,
796
+ baseTheme,
797
+ layers,
798
+ mode,
799
+ cardGeometry,
800
+ ]);
141
801
 
142
802
  // Malloy renderer requires explicit pixel height to render visualizations
143
803
  return (
@@ -151,41 +811,39 @@ function RenderedResultInner({
151
811
  );
152
812
  }
153
813
 
154
- // Main component with error boundary and fallback
155
814
  export default function RenderedResult(props: RenderedResultProps) {
156
- // Show loading state if we're in server-side rendering
157
815
  if (typeof window === "undefined") {
158
816
  return (
159
- <div
160
- style={{
817
+ <Box
818
+ sx={{
161
819
  width: "100%",
162
820
  height: props.height ? `${props.height}px` : "100%",
163
821
  display: "flex",
164
822
  alignItems: "center",
165
823
  justifyContent: "center",
166
- color: "#666",
824
+ color: "text.secondary",
167
825
  }}
168
826
  >
169
827
  Loading...
170
- </div>
828
+ </Box>
171
829
  );
172
830
  }
173
831
 
174
832
  return (
175
833
  <Suspense
176
834
  fallback={
177
- <div
178
- style={{
835
+ <Box
836
+ sx={{
179
837
  width: "100%",
180
838
  height: props.height ? `${props.height}px` : "100%",
181
839
  display: "flex",
182
840
  alignItems: "center",
183
841
  justifyContent: "center",
184
- color: "#666",
842
+ color: "text.secondary",
185
843
  }}
186
844
  >
187
845
  Loading visualization...
188
- </div>
846
+ </Box>
189
847
  }
190
848
  >
191
849
  <RenderedResultInner {...props} />