Skip to content

The easy-to-use open source Business Intelligence and Embedded Analytics tool that lets everyone work with data :bar_chart:

Overhaul pie chart static viz. Fix leaking HSLA values (#77303)

Nick Fitzpatricka8234bd97c10
diff --git a/frontend/src/metabase/static-viz/components/Legend/utils.ts b/frontend/src/metabase/static-viz/components/Legend/utils.ts
index 933c26c5401..ab27a75be07 100644
--- a/frontend/src/metabase/static-viz/components/Legend/utils.ts
+++ b/frontend/src/metabase/static-viz/components/Legend/utils.ts
@@ -143,31 +143,25 @@ export const calculateLegendRows = ({
};
};
-function calculateNumRowsCols(
+export function calculateNumRowsCols(
items: LegendItem[],
width: number,
fontSize: number,
fontWeight: number,
legendItemMarginRight: number,
) {
- let colWidth: number;
- let numCols = 2;
-
- do {
- if (numCols >= items.length) {
- return { numRows: 1, numCols: items.length };
- }
-
- colWidth = Math.floor(width / ++numCols);
- } while (
- items.every(
+ const maxItemWidth = Math.max(
+ ...items.map(
(item) =>
- calculateItemWidth(item, fontSize, fontWeight) +
- legendItemMarginRight <=
- colWidth,
- )
+ calculateItemWidth(item, fontSize, fontWeight) + legendItemMarginRight,
+ ),
);
- numCols--; // This value failed the test, so we decrement to the last passing value
+
+ // Most columns that still fit the widest item without truncation. This grid legend keeps a
+ // minimum of two columns (truncating names if needed) so it never collapses to a single tall
+ // column -- see #45149; only capped lower when there's a single item.
+ const numColsThatFit = Math.floor(width / Math.ceil(maxItemWidth));
+ let numCols = Math.min(items.length, Math.max(2, numColsThatFit));
const numRows = Math.ceil(items.length / numCols);
diff --git a/frontend/src/metabase/static-viz/components/Legend/utils.unit.spec.ts b/frontend/src/metabase/static-viz/components/Legend/utils.unit.spec.ts
new file mode 100644
index 00000000000..738f0c4ff82
--- /dev/null
+++ b/frontend/src/metabase/static-viz/components/Legend/utils.unit.spec.ts
@@ -0,0 +1,89 @@
+import { measureTextWidth } from "metabase/static-viz/lib/text";
+import type { LegendItem } from "metabase/visualizations/echarts/cartesian/model/types";
+
+import {
+ DEFAULT_LEGEND_FONT_SIZE,
+ DEFAULT_LEGEND_FONT_WEIGHT,
+ LEGEND_CIRCLE_MARGIN_RIGHT,
+ LEGEND_CIRCLE_SIZE,
+ LEGEND_ITEM_MARGIN_RIGHT_GRID,
+} from "./constants";
+import { calculateNumRowsCols } from "./utils";
+
+const FONT_SIZE = DEFAULT_LEGEND_FONT_SIZE;
+const FONT_WEIGHT = DEFAULT_LEGEND_FONT_WEIGHT;
+const MARGIN = LEGEND_ITEM_MARGIN_RIGHT_GRID;
+
+// A width no realistic legend can exceed, so every item fits and column count is bounded only by
+// the item count.
+const UNCONSTRAINED_WIDTH = 10_000;
+
+const makeItems = (count: number, name = "Category"): LegendItem[] =>
+ Array.from({ length: count }, (_, index) => ({
+ name,
+ color: "#509ee3",
+ key: `item-${index}`,
+ }));
+
+// The minimum column width at which one item still fits, matching what the function compares against.
+const itemSlotWidth = (item: LegendItem): number =>
+ LEGEND_CIRCLE_SIZE +
+ LEGEND_CIRCLE_MARGIN_RIGHT +
+ measureTextWidth(item.name, FONT_SIZE, FONT_WEIGHT) +
+ (item.percent != null
+ ? measureTextWidth(item.percent, FONT_SIZE, FONT_WEIGHT)
+ : 0) +
+ MARGIN;
+
+// A box exactly `cols` slots wide, so `cols` columns fit but `cols + 1` do not (items identical).
+const widthForColumns = (item: LegendItem, cols: number): number =>
+ cols * Math.ceil(itemSlotWidth(item));
+
+const run = (items: LegendItem[], width: number) =>
+ calculateNumRowsCols(items, width, FONT_SIZE, FONT_WEIGHT, MARGIN);
+
+describe("calculateNumRowsCols", () => {
+ it("puts a single item in one row and one column", () => {
+ expect(run(makeItems(1), UNCONSTRAINED_WIDTH)).toEqual({
+ numRows: 1,
+ numCols: 1,
+ });
+ });
+
+ it("uses as many columns as items when the box is wide enough", () => {
+ expect(run(makeItems(5), UNCONSTRAINED_WIDTH)).toEqual({
+ numRows: 1,
+ numCols: 5,
+ });
+ });
+
+ it("uses the most columns that fit without truncation", () => {
+ const items = makeItems(4);
+ expect(run(items, widthForColumns(items[0], 2))).toEqual({
+ numRows: 2,
+ numCols: 2,
+ });
+ });
+
+ it("keeps a minimum of two columns even when items don't fit, truncating instead (#45149)", () => {
+ // A width smaller than a single item's slot: rather than collapse to one tall column, the grid
+ // holds two columns and lets the names truncate.
+ const WIDTH_TOO_NARROW_FOR_TWO_COLUMNS = 8;
+ expect(run(makeItems(5), WIDTH_TOO_NARROW_FOR_TWO_COLUMNS)).toEqual({
+ numRows: 3,
+ numCols: 2,
+ });
+ });
+
+ it("uses a single column for a lone item", () => {
+ expect(run(makeItems(1), 8)).toEqual({ numRows: 1, numCols: 1 });
+ });
+
+ it("drops a trailing column that would be entirely empty", () => {
+ const items = makeItems(5);
+ expect(run(items, widthForColumns(items[0], 4))).toEqual({
+ numRows: 2,
+ numCols: 3,
+ });
+ });
+});
diff --git a/frontend/src/metabase/static-viz/components/PieChart/PieChart.tsx b/frontend/src/metabase/static-viz/components/PieChart/PieChart.tsx
index 56d3d18da88..a8b56377308 100644
--- a/frontend/src/metabase/static-viz/components/PieChart/PieChart.tsx
+++ b/frontend/src/metabase/static-viz/components/PieChart/PieChart.tsx
@@ -1,151 +1,14 @@
-import { Group } from "@visx/group";
-import { init } from "echarts/core";
-
-import { sanitizeSvgForBatik } from "metabase/static-viz/lib/svg";
-import { registerEChartsModules } from "metabase/visualizations/echarts";
-import { DIMENSIONS } from "metabase/visualizations/echarts/pie/constants";
-import { getPieChartFormatters } from "metabase/visualizations/echarts/pie/format";
-import { getPieChartModel } from "metabase/visualizations/echarts/pie/model";
-import { getPieChartOption } from "metabase/visualizations/echarts/pie/option";
-
-import Watermark from "../../watermark.svg?component";
-import { Legend } from "../Legend";
-import { LEGEND_ITEM_MARGIN_RIGHT_GRID } from "../Legend/constants";
import type { StaticChartProps } from "../StaticVisualization";
-import { getPieChartLegend, getPieChartSideLegend } from "./legend";
-
-registerEChartsModules();
-
-function renderPieSvg(
- option: ReturnType<typeof getPieChartOption>,
- side: number,
- isStorybook?: boolean,
-) {
- const chart = init(null, null, {
- renderer: "svg",
- ssr: true,
- width: side,
- height: side,
- });
- chart.setOption(option);
- const chartSvg = sanitizeSvgForBatik(
- chart.renderToSVGString(),
- isStorybook ?? false,
- );
- chart.dispose();
- return chartSvg;
-}
-
-export function PieChart({
- rawSeries,
- renderingContext,
- settings,
- isStorybook,
- hasDevWatermark = false,
- width,
- height,
-}: StaticChartProps) {
- const chartModel = getPieChartModel(
- rawSeries,
- settings,
- [],
- renderingContext,
- );
- const formatters = getPieChartFormatters(chartModel, settings);
+import { PieChartWithBottomLegend } from "./PieChartWithBottomLegend";
+import { PieChartWithSideLegend } from "./PieChartWithSideLegend";
- // When an explicit box is provided and it's square-or-wider, render the legend as a single
- // column to the LEFT of the circle (and enlarge the circle), matching the app's responsive
- // pie layout. Otherwise keep the default square-circle-with-legend-below layout (which is
- // also what subscription emails use, since they don't pass width/height).
+export function PieChart(props: StaticChartProps) {
+ const { width, height } = props;
+ // A square-or-wider box fits the legend beside the circle (like the app); a taller box, or an
+ // email (which passes no dimensions), puts it below.
if (width != null && height != null && width >= height) {
- const totalW = width;
- const totalH = height;
- const gap = DIMENSIONS.padding.side;
- // Reserve room for the legend, but never more than ~45% of the width, and keep at least
- // half the height for the circle.
- const maxLegendW = Math.min(
- totalW * 0.45,
- Math.max(0, totalW - totalH * 0.5),
- );
- const { items, legendHeight, legendWidth } = getPieChartSideLegend(
- chartModel,
- formatters,
- settings,
- maxLegendW,
- );
- const legendColumnWidth = legendWidth > 0 ? legendWidth + gap : 0;
- const side = Math.max(0, Math.min(totalH, totalW - legendColumnWidth));
- const option = getPieChartOption(
- chartModel,
- formatters,
- settings,
- renderingContext,
- side,
- );
- const chartSvg = renderPieSvg(option, side, isStorybook);
-
- return (
- <svg xmlns="http://www.w3.org/2000/svg" width={totalW} height={totalH}>
- <Group
- left={legendColumnWidth}
- top={(totalH - side) / 2}
- dangerouslySetInnerHTML={{ __html: chartSvg }}
- ></Group>
- <Legend
- items={items}
- top={Math.max(0, (totalH - legendHeight) / 2)}
- left={gap}
- legendItemMarginRight={LEGEND_ITEM_MARGIN_RIGHT_GRID}
- />
- {hasDevWatermark && (
- <Watermark
- x="0"
- y="0"
- height={totalH}
- width={totalW}
- preserveAspectRatio="xMinYMin slice"
- fill={renderingContext.getColor("text-secondary")}
- opacity={0.2}
- />
- )}
- </svg>
- );
+ return <PieChartWithSideLegend {...props} width={width} height={height} />;
}
-
- const option = getPieChartOption(
- chartModel,
- formatters,
- settings,
- renderingContext,
- DIMENSIONS.maxSideLength,
- );
- const { legendHeight, Legend: BottomLegend } = getPieChartLegend(
- chartModel,
- formatters,
- settings,
- );
- const chartSvg = renderPieSvg(option, DIMENSIONS.maxSideLength, isStorybook);
-
- const svgHeight =
- DIMENSIONS.maxSideLength + DIMENSIONS.padding.legend + legendHeight;
- const svgWidth = DIMENSIONS.maxSideLength;
-
- return (
- <svg xmlns="http://www.w3.org/2000/svg" width={svgWidth} height={svgHeight}>
- <Group dangerouslySetInnerHTML={{ __html: chartSvg }}></Group>
- <BottomLegend />
- {hasDevWatermark && (
- <Watermark
- x="0"
- y="0"
- height={svgHeight}
- width={svgWidth}
- preserveAspectRatio="xMinYMin slice"
- fill={renderingContext.getColor("text-secondary")}
- opacity={0.2}
- />
- )}
- </svg>
- );
+ return <PieChartWithBottomLegend {...props} />;
}
diff --git a/frontend/src/metabase/static-viz/components/PieChart/PieChart.unit.spec.tsx b/frontend/src/metabase/static-viz/components/PieChart/PieChart.unit.spec.tsx
new file mode 100644
index 00000000000..cb286dd0fd5
--- /dev/null
+++ b/frontend/src/metabase/static-viz/components/PieChart/PieChart.unit.spec.tsx
@@ -0,0 +1,101 @@
+/* eslint-disable testing-library/render-result-naming-convention --
+ These tests use ReactDOMServer.renderToStaticMarkup (a server-side string render), not an RTL
+ render, so the "view"/"utils" naming convention doesn't apply. */
+import ReactDOMServer from "react-dom/server";
+
+import { createStaticRenderingContext } from "metabase/static-viz/lib/rendering-context";
+import type { RawSeries, VisualizationSettings } from "metabase-types/api";
+import { createMockCard } from "metabase-types/api/mocks/card";
+import {
+ createMockColumn,
+ createMockDatasetData,
+} from "metabase-types/api/mocks/dataset";
+
+import { StaticVisualization } from "../StaticVisualization";
+
+const renderingContext = createStaticRenderingContext();
+
+const DIMENSION_COL = createMockColumn({
+ name: "type_1",
+ display_name: "Type",
+ base_type: "type/Text",
+});
+const METRIC_COL = createMockColumn({
+ name: "count",
+ display_name: "Count",
+ base_type: "type/BigInteger",
+});
+
+const ROWS = [
+ ["Bug", 81],
+ ["Dark", 44],
+ ["Dragon", 40],
+ ["Electric", 61],
+ ["Fairy", 22],
+ ["Fighting", 38],
+ ["Fire", 65],
+ ["Flying", 8],
+ ["Ghost", 41],
+ ["Grass", 91],
+ ["Ground", 41],
+ ["Ice", 36],
+ ["Normal", 115],
+ ["Poison", 39],
+ ["Psychic", 76],
+ ["Rock", 60],
+ ["Steel", 36],
+ ["Water", 134],
+];
+
+// A genuinely-typed pie `RawSeries` (no cast). `pie.show_labels` paints slice labels on the chart,
+// which is what exercises getTextColorForBackground -- the source of the hsla() values below.
+const pieSeries = (settings: VisualizationSettings = {}): RawSeries => [
+ {
+ card: createMockCard({
+ display: "pie",
+ visualization_settings: {
+ "pie.dimension": "type_1",
+ "pie.metric": "count",
+ "pie.show_labels": true,
+ ...settings,
+ },
+ }),
+ data: createMockDatasetData({
+ cols: [DIMENSION_COL, METRIC_COL],
+ rows: ROWS,
+ }),
+ },
+];
+
+const toSvg = (
+ rawSeries: RawSeries,
+ dimensions?: { width: number; height: number },
+) =>
+ ReactDOMServer.renderToStaticMarkup(
+ <StaticVisualization
+ rawSeries={rawSeries}
+ renderingContext={renderingContext}
+ width={dimensions?.width}
+ height={dimensions?.height}
+ />,
+ );
+
+describe("static PieChart", () => {
+ // Slice label colors come from getTextColorForBackground, whose base is hsla(); the static
+ // context must map them to hex, since the PDF rasterizer (Batik) can't parse hsla.
+ it("renders to an <svg> free of hsl()/hsla() colors, across both legend layouts", () => {
+ const bottomLegend = toSvg(pieSeries());
+ const sideLegend = toSvg(pieSeries(), { width: 500, height: 300 });
+ const sideLegendWithPercent = toSvg(
+ pieSeries({ "pie.percent_visibility": "both" }),
+ { width: 500, height: 300 },
+ );
+
+ expect(bottomLegend).toContain("<svg");
+ expect(bottomLegend).not.toMatch(/hsla?\(/);
+ expect(sideLegend).toContain("<svg");
+ expect(sideLegend).not.toMatch(/hsla?\(/);
+ expect(sideLegendWithPercent).toContain("<svg");
+ expect(sideLegendWithPercent).not.toMatch(/hsla?\(/);
+ });
+});
diff --git a/frontend/src/metabase/static-viz/components/PieChart/PieChartWithBottomLegend.tsx b/frontend/src/metabase/static-viz/components/PieChart/PieChartWithBottomLegend.tsx
new file mode 100644
index 00000000000..c3971268e62
--- /dev/null
+++ b/frontend/src/metabase/static-viz/components/PieChart/PieChartWithBottomLegend.tsx
@@ -0,0 +1,97 @@
+import { Group } from "@visx/group";
+
+import { DIMENSIONS } from "metabase/visualizations/echarts/pie/constants";
+import { getPieChartFormatters } from "metabase/visualizations/echarts/pie/format";
+import { getPieChartModel } from "metabase/visualizations/echarts/pie/model";
+import { getPieChartOption } from "metabase/visualizations/echarts/pie/option";
+
+import Watermark from "../../watermark.svg?component";
+import { Legend } from "../Legend";
+import { LEGEND_ITEM_MARGIN_RIGHT_GRID } from "../Legend/constants";
+import type { StaticChartProps } from "../StaticVisualization";
+
+import { getPieChartBottomLegendLayout, renderPieSvg } from "./utils";
+
+// The circle takes at most this fraction of the box height, leaving room for the legend below.
+const MAX_CIRCLE_HEIGHT_RATIO = 0.7;
+
+export function PieChartWithBottomLegend({
+ rawSeries,
+ renderingContext,
+ settings,
+ isStorybook,
+ hasDevWatermark = false,
+ width,
+ height,
+}: StaticChartProps) {
+ const chartModel = getPieChartModel(
+ rawSeries,
+ settings,
+ [],
+ renderingContext,
+ );
+ const formatters = getPieChartFormatters(chartModel, settings);
+
+ const hasDimensions = width != null && height != null;
+ const gap = DIMENSIONS.padding.legend;
+ const side = hasDimensions
+ ? Math.max(0, Math.min(width, height * MAX_CIRCLE_HEIGHT_RATIO))
+ : DIMENSIONS.maxSideLength;
+
+ const { items, legendHeight, legendWidth } = getPieChartBottomLegendLayout(
+ chartModel,
+ formatters,
+ settings,
+ hasDimensions ? width : DIMENSIONS.maxSideLength,
+ hasDimensions ? Math.max(0, height - side - gap) : undefined,
+ renderingContext,
+ );
+
+ const option = getPieChartOption(
+ chartModel,
+ formatters,
+ settings,
+ renderingContext,
+ side,
+ );
+ const chartSvg = renderPieSvg(option, side, isStorybook);
+
+ // The [circle | gap | legend] block; also the SVG height for emails, which fit the box to it.
+ const blockHeight = side + gap + legendHeight;
+ const svgWidth = hasDimensions ? width : DIMENSIONS.maxSideLength;
+ const svgHeight = hasDimensions ? height : blockHeight;
+
+ // Vertically center the block in the box (top-anchored for emails).
+ const topOffset = hasDimensions
+ ? Math.max(0, (svgHeight - blockHeight) / 2)
+ : 0;
+ // The grid positions items from `padding.side`, so back it out to center the content.
+ const legendLeft = (svgWidth - legendWidth) / 2 - DIMENSIONS.padding.side;
+
+ return (
+ <svg xmlns="http://www.w3.org/2000/svg" width={svgWidth} height={svgHeight}>
+ <Group
+ left={(svgWidth - side) / 2}
+ top={topOffset}
+ dangerouslySetInnerHTML={{ __html: chartSvg }}
+ ></Group>
+ <Legend
+ items={items}
+ top={topOffset + side + gap}
+ left={legendLeft}
+ legendItemMarginRight={LEGEND_ITEM_MARGIN_RIGHT_GRID}
+ />
+ {hasDevWatermark && (
+ <Watermark
+ x="0"
+ y="0"
+ height={svgHeight}
+ width={svgWidth}
+ preserveAspectRatio="xMinYMin slice"
+ fill={renderingContext.getColor("text-secondary")}
+ opacity={0.2}
+ />
+ )}
+ </svg>
+ );
+}
diff --git a/frontend/src/metabase/static-viz/components/PieChart/PieChartWithSideLegend.tsx b/frontend/src/metabase/static-viz/components/PieChart/PieChartWithSideLegend.tsx
new file mode 100644
index 00000000000..67d28fa3b6c
--- /dev/null
+++ b/frontend/src/metabase/static-viz/components/PieChart/PieChartWithSideLegend.tsx
@@ -0,0 +1,94 @@
+import { Group } from "@visx/group";
+
+import { DIMENSIONS } from "metabase/visualizations/echarts/pie/constants";
+import { getPieChartFormatters } from "metabase/visualizations/echarts/pie/format";
+import { getPieChartModel } from "metabase/visualizations/echarts/pie/model";
+import { getPieChartOption } from "metabase/visualizations/echarts/pie/option";
+
+import Watermark from "../../watermark.svg?component";
+import { Legend } from "../Legend";
+import { LEGEND_ITEM_MARGIN_RIGHT_GRID } from "../Legend/constants";
+import type { StaticChartProps } from "../StaticVisualization";
+
+import { getPieChartSideLegendLayout, renderPieSvg } from "./utils";
+
+type PieChartWithSideLegendProps = StaticChartProps & {
+ width: number;
+ height: number;
+};
+
+export function PieChartWithSideLegend({
+ rawSeries,
+ renderingContext,
+ settings,
+ isStorybook,
+ hasDevWatermark = false,
+ width,
+ height,
+}: PieChartWithSideLegendProps) {
+ const chartModel = getPieChartModel(
+ rawSeries,
+ settings,
+ [],
+ renderingContext,
+ );
+ const formatters = getPieChartFormatters(chartModel, settings);
+
+ const totalW = width;
+ const totalH = height;
+ const gap = DIMENSIONS.padding.side;
+ // Reserve room for the legend, but never more than ~45% of the width, and keep at least
+ // half the height for the circle.
+ const maxLegendW = Math.min(
+ totalW * 0.45,
+ Math.max(0, totalW - totalH * 0.5),
+ );
+ const { items, legendHeight, legendWidth } = getPieChartSideLegendLayout(
+ chartModel,
+ formatters,
+ settings,
+ maxLegendW,
+ totalH,
+ renderingContext,
+ );
+ const legendColumnWidth = legendWidth > 0 ? legendWidth + gap : 0;
+ const side = Math.max(0, Math.min(totalH, totalW - legendColumnWidth));
+
+ // Center the legend+circle block so extra width splits evenly instead of hugging the left.
+ const xOffset = Math.max(0, (totalW - (legendColumnWidth + side)) / 2);
+ const option = getPieChartOption(
+ chartModel,
+ formatters,
+ settings,
+ renderingContext,
+ side,
+ );
+ const chartSvg = renderPieSvg(option, side, isStorybook);
+
+ return (
+ <svg xmlns="http://www.w3.org/2000/svg" width={totalW} height={totalH}>
+ <Group
+ left={xOffset + legendColumnWidth}
+ top={(totalH - side) / 2}
+ dangerouslySetInnerHTML={{ __html: chartSvg }}
+ ></Group>
+ <Legend
+ items={items}
+ top={Math.max(0, (totalH - legendHeight) / 2)}
+ left={xOffset + gap}
+ legendItemMarginRight={LEGEND_ITEM_MARGIN_RIGHT_GRID}
+ />
+ {hasDevWatermark && (
+ <Watermark
+ x="0"
+ y="0"
+ height={totalH}
+ width={totalW}
+ preserveAspectRatio="xMinYMin slice"
+ fill={renderingContext.getColor("text-secondary")}
+ opacity={0.2}
+ />
+ )}
+ </svg>
+ );
+}
diff --git a/frontend/src/metabase/static-viz/components/PieChart/legend.tsx b/frontend/src/metabase/static-viz/components/PieChart/legend.tsx
deleted file mode 100644
index ae620084bc1..00000000000
--- a/frontend/src/metabase/static-viz/components/PieChart/legend.tsx
+++ /dev/null
@@ -1,118 +0,0 @@
-import { measureTextWidth } from "metabase/static-viz/lib/text";
-import type { LegendItem } from "metabase/visualizations/echarts/cartesian/model/types";
-import { DIMENSIONS } from "metabase/visualizations/echarts/pie/constants";
-import type { PieChartFormatters } from "metabase/visualizations/echarts/pie/format";
-import type { PieChartModel } from "metabase/visualizations/echarts/pie/model/types";
-import { getArrayFromMapValues } from "metabase/visualizations/echarts/pie/util";
-import type { ComputedVisualizationSettings } from "metabase/visualizations/types";
-
-import { Legend } from "../Legend";
-import {
- DEFAULT_LEGEND_FONT_SIZE,
- DEFAULT_LEGEND_FONT_WEIGHT,
- LEGEND_CIRCLE_MARGIN_RIGHT,
- LEGEND_CIRCLE_SIZE,
- LEGEND_ITEM_MARGIN_RIGHT_GRID,
-} from "../Legend/constants";
-import {
- calculateLegendRows,
- calculateLegendRowsWithColumns,
-} from "../Legend/utils";
-
-function getPieLegendItems(
- chartModel: PieChartModel,
- formatters: PieChartFormatters,
- settings: ComputedVisualizationSettings,
-): LegendItem[] {
- const pieChartVisibility = settings["pie.percent_visibility"];
-
- return getArrayFromMapValues(chartModel.sliceTree)
- .filter((s) => s.includeInLegend)
- .map((s) => ({
- name: s.name,
- percent:
- pieChartVisibility === "legend" || pieChartVisibility === "both"
- ? formatters.formatPercent(s.normalizedPercentage, "legend")
- : undefined,
- color: s.color,
- key: String(s.key),
- }));
-}
-
-function measureLegendItemWidth(item: LegendItem): number {
- const fontSize = DEFAULT_LEGEND_FONT_SIZE;
- const fontWeight = DEFAULT_LEGEND_FONT_WEIGHT;
- const percentWidth =
- item.percent != null
- ? measureTextWidth(item.percent, fontSize, fontWeight)
- : 0;
- return (
- LEGEND_CIRCLE_SIZE +
- LEGEND_CIRCLE_MARGIN_RIGHT +
- measureTextWidth(item.name, fontSize, fontWeight) +
- percentWidth
- );
-}
-
-export function getPieChartLegend(
- chartModel: PieChartModel,
- formatters: PieChartFormatters,
- settings: ComputedVisualizationSettings,
-) {
- const {
- height: legendHeight,
- width: legendWidth,
- items,
- } = calculateLegendRowsWithColumns({
- items: getPieLegendItems(chartModel, formatters, settings),
- width: DIMENSIONS.maxSideLength,
- horizontalPadding: DIMENSIONS.padding.side,
- });
-
- return {
- legendHeight,
- Legend: () => (
- <Legend
- items={items}
- top={DIMENSIONS.maxSideLength + DIMENSIONS.padding.legend}
- left={
- (DIMENSIONS.maxSideLength -
- DIMENSIONS.padding.side * 2 -
- legendWidth) /
- 2
- }
- legendItemMarginRight={LEGEND_ITEM_MARGIN_RIGHT_GRID}
- />
- ),
- };
-}
-
-/**
- * Build a single-column (vertical) legend for placing to the side of the circle. `maxWidth`
- * caps the column width; item names are truncated to fit. Returns the positioned items plus
- * the rendered legend block dimensions.
- */
-export function getPieChartSideLegend(
- chartModel: PieChartModel,
- formatters: PieChartFormatters,
- settings: ComputedVisualizationSettings,
- maxWidth: number,
-) {
- const items = getPieLegendItems(chartModel, formatters, settings);
- if (items.length === 0) {
- return { items: [], legendHeight: 0, legendWidth: 0 };
- }
- // Budget the column at (at most) the widest item so two items never share a row -> one column.
- const widest = Math.max(...items.map(measureLegendItemWidth));
- const budget = Math.max(1, Math.min(widest, maxWidth));
- const {
- items: positioned,
- height,
- width,
- } = calculateLegendRows({
- items,
- width: budget,
- horizontalPadding: 0,
- });
- return { items: positioned, legendHeight: height, legendWidth: width };
-}
diff --git a/frontend/src/metabase/static-viz/components/PieChart/utils.ts b/frontend/src/metabase/static-viz/components/PieChart/utils.ts
new file mode 100644
index 00000000000..8df0d48c975
--- /dev/null
+++ b/frontend/src/metabase/static-viz/components/PieChart/utils.ts
@@ -0,0 +1,196 @@
+import { init } from "echarts/core";
+import { t } from "ttag";
+
+import { sanitizeSvgForBatik } from "metabase/static-viz/lib/svg";
+import { measureTextWidth } from "metabase/static-viz/lib/text";
+import { registerEChartsModules } from "metabase/visualizations/echarts";
+import type { LegendItem } from "metabase/visualizations/echarts/cartesian/model/types";
+import { DIMENSIONS } from "metabase/visualizations/echarts/pie/constants";
+import type { PieChartFormatters } from "metabase/visualizations/echarts/pie/format";
+import type { PieChartModel } from "metabase/visualizations/echarts/pie/model/types";
+import type { getPieChartOption } from "metabase/visualizations/echarts/pie/option";
+import { getArrayFromMapValues } from "metabase/visualizations/echarts/pie/util";
+import type {
+ ComputedVisualizationSettings,
+ RenderingContext,
+} from "metabase/visualizations/types";
+
+import {
+ DEFAULT_LEGEND_FONT_SIZE,
+ DEFAULT_LEGEND_FONT_WEIGHT,
+ DEFAULT_LEGEND_LINE_HEIGHT,
+ LEGEND_CIRCLE_MARGIN_RIGHT,
+ LEGEND_CIRCLE_SIZE,
+ LEGEND_ITEM_MARGIN_RIGHT_GRID,
+} from "../Legend/constants";
+import {
+ calculateLegendRows,
+ calculateLegendRowsWithColumns,
+ calculateNumRowsCols,
+} from "../Legend/utils";
+
+registerEChartsModules();
+
+// Synthetic key for the "And N more" legend overflow row.
+const MORE_LEGEND_KEY = "___PIE_LEGEND_MORE___";
+
+function getPieLegendItems(
+ chartModel: PieChartModel,
+ formatters: PieChartFormatters,
+ settings: ComputedVisualizationSettings,
+): LegendItem[] {
+ const pieChartVisibility = settings["pie.percent_visibility"];
+
+ return getArrayFromMapValues(chartModel.sliceTree)
+ .filter((s) => s.includeInLegend)
+ .map((s) => ({
+ name: s.name,
+ percent:
+ pieChartVisibility === "legend" || pieChartVisibility === "both"
+ ? formatters.formatPercent(s.normalizedPercentage, "legend")
+ : undefined,
+ color: s.color,
+ key: String(s.key),
+ }));
+}
+
+function measureLegendItemWidth(item: LegendItem): number {
+ const fontSize = DEFAULT_LEGEND_FONT_SIZE;
+ const fontWeight = DEFAULT_LEGEND_FONT_WEIGHT;
+ const percentWidth =
+ item.percent != null
+ ? measureTextWidth(item.percent, fontSize, fontWeight)
+ : 0;
+ return (
+ LEGEND_CIRCLE_SIZE +
+ LEGEND_CIRCLE_MARGIN_RIGHT +
+ measureTextWidth(item.name, fontSize, fontWeight) +
+ percentWidth
+ );
+}
+
+function moreLegendItem(
+ count: number,
+ renderingContext: RenderingContext,
+): LegendItem {
+ return {
+ name: t`And ${count} more`,
+ color: renderingContext.getColor("text-secondary"),
+ key: MORE_LEGEND_KEY,
+ };
+}
+
+/**
+ * Lay out a wrapped multi-column legend for below the circle. `maxWidth` caps the grid width;
+ * given a `maxHeight`, overflow collapses into a final "And N more" cell. Returns positioned
+ * items plus the rendered block dimensions.
+ */
+export function getPieChartBottomLegendLayout(
+ chartModel: PieChartModel,
+ formatters: PieChartFormatters,
+ settings: ComputedVisualizationSettings,
+ maxWidth: number = DIMENSIONS.maxSideLength,
+ maxHeight?: number,
+ renderingContext?: RenderingContext,
+) {
+ const horizontalPadding = DIMENSIONS.padding.side;
+ let items = getPieLegendItems(chartModel, formatters, settings);
+
+ if (maxHeight != null && renderingContext != null && items.length > 0) {
+ // The height budget caps rows (hence items); the rest collapse into "And N more".
+ const { numCols } = calculateNumRowsCols(
+ items,
+ maxWidth - 2 * horizontalPadding,
+ DEFAULT_LEGEND_FONT_SIZE,
+ DEFAULT_LEGEND_FONT_WEIGHT,
+ LEGEND_ITEM_MARGIN_RIGHT_GRID,
+ );
+ const maxRows = Math.max(
+ 1,
+ Math.floor(maxHeight / DEFAULT_LEGEND_LINE_HEIGHT),
+ );
+ const maxItems = maxRows * numCols;
+ if (items.length > maxItems) {
+ items = [
+ ...items.slice(0, maxItems - 1),
+ moreLegendItem(items.length - (maxItems - 1), renderingContext),
+ ];
+ }
+ }
+
+ const {
+ height: legendHeight,
+ width: legendWidth,
+ items: positioned,
+ } = calculateLegendRowsWithColumns({
+ items,
+ width: maxWidth,
+ horizontalPadding,
+ });
+
+ return { items: positioned, legendHeight, legendWidth };
+}
+
+/**
+ * Lay out a single-column legend for beside the circle. `maxWidth` caps the column width,
+ * `maxHeight` the row count; overflow collapses into a final "And N more" row. Returns
+ * positioned items plus the rendered block dimensions.
+ */
+export function getPieChartSideLegendLayout(
+ chartModel: PieChartModel,
+ formatters: PieChartFormatters,
+ settings: ComputedVisualizationSettings,
+ maxWidth: number,
+ maxHeight: number,
+ renderingContext: RenderingContext,
+) {
+ let items = getPieLegendItems(chartModel, formatters, settings);
+ if (items.length === 0) {
+ return { items: [], legendHeight: 0, legendWidth: 0 };
+ }
+
+ const maxRows = Math.max(
+ 1,
+ Math.floor(maxHeight / DEFAULT_LEGEND_LINE_HEIGHT),
+ );
+ if (items.length > maxRows) {
+ const shown = items.slice(0, maxRows - 1);
+ items = [
+ ...shown,
+ moreLegendItem(items.length - shown.length, renderingContext),
+ ];
+ }
+ // Budget the column at (at most) the widest item so two items never share a row -> one column.
+ const widest = Math.max(...items.map(measureLegendItemWidth));
+ const budget = Math.max(1, Math.min(widest, maxWidth));
+ const {
+ items: positioned,
+ height,
+ width,
+ } = calculateLegendRows({
+ items,
+ width: budget,
+ horizontalPadding: 0,
+ });
+ return { items: positioned, legendHeight: height, legendWidth: width };
+}
+
+export function renderPieSvg(
+ option: ReturnType<typeof getPieChartOption>,
+ side: number,
+ isStorybook?: boolean,
+) {
+ const chart = init(null, null, {
+ renderer: "svg",
+ ssr: true,
+ width: side,
+ height: side,
+ });
+ chart.setOption(option);
+ const chartSvg = sanitizeSvgForBatik(
+ chart.renderToSVGString(),
+ isStorybook ?? false,
+ );
+ chart.dispose();
+ return chartSvg;
+}
diff --git a/frontend/src/metabase/ui/colors/palette.ts b/frontend/src/metabase/ui/colors/palette.ts
index c8d7a041655..dbf2ca63624 100644
--- a/frontend/src/metabase/ui/colors/palette.ts
+++ b/frontend/src/metabase/ui/colors/palette.ts
@@ -155,7 +155,10 @@ export const getTextColorForBackground = (
background.contrast(Color(LIGHT_TEXT_COLOR)) * whiteTextColorPriorityFactor;
const darkTextContrast = background.contrast(Color(DARK_TEXT_COLOR));
- return lightTextContrast > darkTextContrast
- ? LIGHT_TEXT_COLOR
- : DARK_TEXT_COLOR;
+ const textColor =
+ lightTextContrast > darkTextContrast ? LIGHT_TEXT_COLOR : DARK_TEXT_COLOR;
+
+ // Resolve through `getColor` so each medium normalizes the base hsla(): static viz maps it to
+ // hex (Batik can't parse hsla), while the app keeps the semi-transparent text unchanged.
+ return getColor(textColor);
};
diff --git a/src/metabase/channel/render/pdf.clj b/src/metabase/channel/render/pdf.clj
index c258f1ab0c4..6653a2eba05 100644
--- a/src/metabase/channel/render/pdf.clj
+++ b/src/metabase/channel/render/pdf.clj
@@ -85,8 +85,9 @@
"Display types whose static-viz (ECharts/visx) renderer honors an explicit width AND height, so we can render them
to exactly fit their grid cell (like the frontend).
- Other types (pie, gauge, funnel, progress, scalar, table, ...) have a fixed size when rendered, and resized to fit
- their grid cell, preserving aspect ratio."
+ Pies also fill their box (their static-viz component lays the legend out to the box), but are handled separately
+ since they aren't in this set. Other types (gauge, funnel, progress, scalar, table, ...) have a fixed size when
+ rendered, and are resized to fit their grid cell, preserving aspect ratio."
#{:line :area :bar :combo :scatter :boxplot :waterfall :sankey :row :treemap})
(def ^:private table-like-chart-types
@@ -561,7 +562,7 @@
"Rasterize a `:card` part's body (chart/table/scalar) to PNG bytes, WITHOUT its title or description -- those are
drawn natively at the PDF level.
- Used for card types that can't fill an arbitrary box (pie, gauge, funnel, progress, scalar, table, ...); resize
+ Used for card types that can't fill an arbitrary box (gauge, funnel, progress, scalar, table, ...); resize
to fit while preserving aspect."
^bytes [timezone {:keys [card dashcard result]} px-width]
(-> (render.card/render-pulse-card :inline timezone card dashcard result
@@ -571,7 +572,7 @@
(defn- draw-image-in-cell!
"Draw `img`, resizing to fit (preserving aspect) within a cell rectangle, horizontally centered and top-anchored.
- Used for card types that can't fill an arbitrary box (scalar, pie, gauge, ...). Horizontal centering keeps a narrow
+ Used for card types that can't fill an arbitrary box (scalar, gauge, ...). Horizontal centering keeps a narrow
scalar (e.g. a big number) from hugging the left edge of its cell."
[^PDPageContentStream cs ^PDImageXObject img x top-y cell-w cell-h]
(let [iw (.getWidth img)
@@ -1095,11 +1096,10 @@
body-top (- top-y header)
body-h (- cell-h header)
display (effective-display card dashcard)
- ;; Rectangular charts always fill their box; pies fill (and move their legend to the
- ;; side) only when the body area is square-or-wider, otherwise they keep a bottom legend.
+ ;; Rectangular charts and pies both fill their box exactly; the pie's static-viz component
+ ;; then places its legend to the side (wide box) or below (tall box).
fill? (or (contains? rectangular-displays display)
- (and (= :pie display)
- (>= cell-w body-h)))
+ (= :pie display))
chart-type (render.card/detect-pulse-chart-type card dashcard data)
tabular? (contains? table-like-chart-types chart-type)
;; a no-row result detects as :empty regardless of display -> no-results placeholder
@@ -1136,7 +1136,7 @@
:let [png (when fill?
(sized-chart-png card dashcard data (pt->px cell-w) (pt->px body-h)))]
- ;; rectangular charts (and wide pies): fill the body area exactly
+ ;; rectangular charts and pies: fill the body area exactly
png
(.drawImage cs (PDImageXObject/createFromByteArray doc png "chart")
(float x) (float (- body-top body-h))