The easy-to-use open source Business Intelligence and Embedded Analytics tool that lets everyone work with data :bar_chart:
TypeScript analyticsbibusiness-intelligencebusinessintelligenceclojuredashboarddatadata-analysisdata-visualizationdatabasemetabasemysqlpostgrespostgresqlreportingslacksql-editorvisualization
GDGT-2750: Treemap renders incorrectly in PDF export (#76996)
Jakub Chodorowicz3487a7801ffc
diff --git a/.loki/reference/chrome_laptop_Viz_Static_Viz_TreemapChart_Grid_Cell_Wide_Short.png b/.loki/reference/chrome_laptop_Viz_Static_Viz_TreemapChart_Grid_Cell_Wide_Short.pngnew file mode 100644index 00000000000..20638f86c9fBinary files /dev/null and b/.loki/reference/chrome_laptop_Viz_Static_Viz_TreemapChart_Grid_Cell_Wide_Short.png differdiff --git a/frontend/src/metabase/static-viz/components/TreemapChart/TreemapChart.stories.tsx b/frontend/src/metabase/static-viz/components/TreemapChart/TreemapChart.stories.tsxindex c72e5263be4..8a569413076 100644--- a/frontend/src/metabase/static-viz/components/TreemapChart/TreemapChart.stories.tsx+++ b/frontend/src/metabase/static-viz/components/TreemapChart/TreemapChart.stories.tsx@@ -61,3 +61,14 @@ export const Watermark = {hasDevWatermark: true,},};++export const GridCellWideShort = {+ render: Template,+ args: {+ rawSeries: data.twoLevel,+ renderingContext,+ width: 1200,+ height: 320,+ fitWithinBounds: true,+ },+};diff --git a/frontend/src/metabase/static-viz/components/TreemapChart/TreemapChart.tsx b/frontend/src/metabase/static-viz/components/TreemapChart/TreemapChart.tsxindex 9b170eb2498..cb1c4cea761 100644--- a/frontend/src/metabase/static-viz/components/TreemapChart/TreemapChart.tsx+++ b/frontend/src/metabase/static-viz/components/TreemapChart/TreemapChart.tsx@@ -1,5 +1,5 @@import { Group } from "@visx/group";-import { init } from "echarts/core";+import { type EChartsType, init } from "echarts/core";import type { StaticChartProps } from "metabase/static-viz/components/StaticVisualization";import { sanitizeSvgForBatik } from "metabase/static-viz/lib/svg";@@ -14,10 +14,15 @@ import { getTreemapFormatters } from "metabase/visualizations/echarts/graph/treeimport { shouldShowParentLabels } from "metabase/visualizations/echarts/graph/treemap/model/labels";import { measureTreemapLabelLayouts } from "metabase/visualizations/echarts/graph/treemap/model/measure";import { getTreemapLayoutNodes } from "metabase/visualizations/echarts/graph/treemap/model/tree";+import type { TreemapTree } from "metabase/visualizations/echarts/graph/treemap/model/types";import {type TreemapChartOptionConfig,getStaticTreemapOption,} from "metabase/visualizations/echarts/graph/treemap/option/option";+import type {+ ComputedVisualizationSettings,+ RenderingContext,+} from "metabase/visualizations/types";import Watermark from "../../watermark.svg?component";@@ -36,6 +41,9 @@ export function TreemapChart({renderingContext,isStorybook = false,hasDevWatermark = false,+ width,+ height,+ fitWithinBounds = false,}: StaticChartProps) {const rawSeriesWithRemappings = extractRemappings(rawSeries);const cols = rawSeriesWithRemappings[0]?.data?.cols ?? [];@@ -64,41 +72,73 @@ export function TreemapChart({renderingContext,};- const chart = init(null, null, {- renderer: "svg",- ssr: true,- width: CHART_WIDTH,- height: CHART_HEIGHT,- });+ // render treemap in a fixed-size box, with no side legend and no stretching+ // this applies to PDF rendering which follows grid layout like a dashboard+ if (fitWithinBounds && width !== undefined && height !== undefined) {+ const chartSvg = renderTreemapChartSvg({+ config,+ settings,+ tree,+ formatters,+ renderingContext,+ chartWidth: width,+ chartHeight: height,+ isStorybook,+ });- // first pass to general layout of nodes- chart.setOption(getStaticTreemapOption(config));- chart.renderToSVGString();- const layouts = measureTreemapLabelLayouts({- nodes: getTreemapLayoutNodes(chart),- tree,- formatters,- renderingContext,- showLeafLabels: settings["treemap.show_leaf_labels"] ?? true,- showLeafValues: settings["treemap.show_leaf_values"] ?? true,- showParentValues: settings["treemap.show_parent_values"] ?? true,- });-- // 2nd to render/hide labels- chart.setOption(getStaticTreemapOption(config, layouts));- const chartSvg = sanitizeSvgForBatik(chart.renderToSVGString(), isStorybook);+ return (+ <svg+ xmlns="http://www.w3.org/2000/svg"+ width={width}+ height={height}+ data-testid="treemap-root"+ >+ <Group dangerouslySetInnerHTML={{ __html: chartSvg }}></Group>+ {hasDevWatermark && (+ <Watermark+ x="0"+ y="0"+ height={height}+ width={width}+ preserveAspectRatio="xMinYMin slice"+ fill={renderingContext.getColor("text-secondary")}+ opacity={0.2}+ />+ )}+ </svg>+ );+ }+ // No explicit box (subscription email single-card path, default stories): keep the fixed+ // intrinsic size with the legend stacked to the right.const legendModel = getTreemapLegendModel(tree,colors,formatters.value,formatters.percent,);- const width = CHART_WIDTH + LEGEND_GAP + LEGEND_WIDTH;- const height = Math.max(CHART_HEIGHT, legendModel.height);++ const chartSvg = renderTreemapChartSvg({+ config,+ settings,+ tree,+ formatters,+ renderingContext,+ chartWidth: CHART_WIDTH,+ chartHeight: CHART_HEIGHT,+ isStorybook,+ });++ const svgWidth = CHART_WIDTH + LEGEND_GAP + LEGEND_WIDTH;+ const svgHeight = Math.max(CHART_HEIGHT, legendModel.height);return (- <svg xmlns="http://www.w3.org/2000/svg" width={width} height={height}>+ <svg+ xmlns="http://www.w3.org/2000/svg"+ width={svgWidth}+ height={svgHeight}+ data-testid="treemap-root"+ ><Group dangerouslySetInnerHTML={{ __html: chartSvg }}></Group><TreemapLegendmodel={legendModel}@@ -109,8 +149,8 @@ export function TreemapChart({<Watermarkx="0"y="0"- height={height}- width={width}+ height={svgHeight}+ width={svgWidth}preserveAspectRatio="xMinYMin slice"fill={renderingContext.getColor("text-secondary")}opacity={0.2}@@ -119,3 +159,52 @@ export function TreemapChart({</svg>);}++interface RenderTreemapSvgOptions {+ config: TreemapChartOptionConfig;+ settings: ComputedVisualizationSettings;+ tree: TreemapTree;+ formatters: ReturnType<typeof getTreemapFormatters>;+ renderingContext: RenderingContext;+ chartWidth: number;+ chartHeight: number;+ isStorybook: boolean;+}++// Renders the treemap tiles as an SVG string using ECharts' SSR mode. The two passes match the+// browser implementation: the first lays the nodes out so labels can be measured, the second+// re-renders with those measurements to show/hide labels that fit.+function renderTreemapChartSvg({+ config,+ settings,+ tree,+ formatters,+ renderingContext,+ chartWidth,+ chartHeight,+ isStorybook,+}: RenderTreemapSvgOptions): string {+ const chart: EChartsType = init(null, null, {+ renderer: "svg",+ ssr: true,+ width: chartWidth,+ height: chartHeight,+ });++ // first pass to generate layout of nodes+ chart.setOption(getStaticTreemapOption(config));+ chart.renderToSVGString();+ const layouts = measureTreemapLabelLayouts({+ nodes: getTreemapLayoutNodes(chart),+ tree,+ formatters,+ renderingContext,+ showLeafLabels: settings["treemap.show_leaf_labels"] ?? true,+ showLeafValues: settings["treemap.show_leaf_values"] ?? true,+ showParentValues: settings["treemap.show_parent_values"] ?? true,+ });++ // 2nd to render/hide labels+ chart.setOption(getStaticTreemapOption(config, layouts));+ return sanitizeSvgForBatik(chart.renderToSVGString(), isStorybook);+}diff --git a/frontend/src/metabase/static-viz/components/TreemapChart/TreemapChart.unit.spec.tsx b/frontend/src/metabase/static-viz/components/TreemapChart/TreemapChart.unit.spec.tsxindex f7a24f6bec9..e3d46828b7c 100644--- a/frontend/src/metabase/static-viz/components/TreemapChart/TreemapChart.unit.spec.tsx+++ b/frontend/src/metabase/static-viz/components/TreemapChart/TreemapChart.unit.spec.tsx@@ -96,4 +96,48 @@ describe("static TreemapChart", () => {expect(legendNames).toEqual(["Legumes", "Soy", "Total"]);expect(screen.queryByTestId("legend-dot")).not.toBeInTheDocument();});++ it("uses the fixed intrinsic size when no output box is provided", () => {+ render(+ <TreemapChart+ rawSeries={makeRawSeries([+ ["Legumes", "Chickpeas", 60],+ ["Soy", "Tempeh", 20],+ ])}+ settings={settings}+ renderingContext={getRenderingContext()}+ isStorybook+ />,+ );++ const svg = screen.getByTestId("treemap-root");+ // CHART_WIDTH(965) + LEGEND_GAP(48) + LEGEND_WIDTH(363)+ expect(svg).toHaveAttribute("width", "1376");+ expect(svg).toHaveAttribute("height", "764");+ });++ it("fills the provided output box with no legend so the tiles span the full width", () => {+ render(+ <TreemapChart+ rawSeries={makeRawSeries([+ ["Legumes", "Chickpeas", 60],+ ["Soy", "Tempeh", 20],+ ])}+ settings={settings}+ renderingContext={getRenderingContext()}+ width={1200}+ height={320}+ fitWithinBounds+ isStorybook+ />,+ );++ const svg = screen.getByTestId("treemap-root");+ expect(svg).toHaveAttribute("width", "1200");+ expect(svg).toHaveAttribute("height", "320");++ // The grid/PDF render drops the side legend entirely so the treemap spans the full width.+ expect(screen.queryByTestId("legend-name")).not.toBeInTheDocument();+ expect(screen.queryByTestId("legend-dot")).not.toBeInTheDocument();+ });});diff --git a/src/metabase/channel/render/pdf.clj b/src/metabase/channel/render/pdf.cljindex 0b1b8209b9d..2c0a7071f9f 100644--- a/src/metabase/channel/render/pdf.clj+++ b/src/metabase/channel/render/pdf.clj@@ -86,7 +86,7 @@Other types (pie, gauge, funnel, progress, scalar, table, ...) have a fixed size when rendered, and resized to fittheir grid cell, preserving aspect ratio."- #{:line :area :bar :combo :scatter :boxplot :waterfall :sankey :row})+ #{:line :area :bar :combo :scatter :boxplot :waterfall :sankey :row :treemap});; --------------------------------------------------------------------------------------------;; Page geometry