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
feat(visualizations): add a Legend position setting to charts (#83651)
Aleksandr Lesnenkoc47aeb818b58
diff --git a/.loki/reference/chrome_laptop_viz_Legend_LegendLayout_Hidden_On_Narrow_Card.png b/.loki/reference/chrome_laptop_viz_Legend_LegendLayout_Hidden_On_Narrow_Card.pngnew file mode 100644index 00000000000..a551b3fb8f2Binary files /dev/null and b/.loki/reference/chrome_laptop_viz_Legend_LegendLayout_Hidden_On_Narrow_Card.png differdiff --git a/.loki/reference/chrome_laptop_viz_Legend_LegendLayout_Hidden_On_Small_Card.png b/.loki/reference/chrome_laptop_viz_Legend_LegendLayout_Hidden_On_Small_Card.pngdeleted file mode 100644index 2b4cc757840..00000000000Binary files a/.loki/reference/chrome_laptop_viz_Legend_LegendLayout_Hidden_On_Small_Card.png and /dev/null differdiff --git a/.loki/reference/chrome_laptop_viz_Legend_LegendLayout_Hidden_When_Mostly_Truncated.png b/.loki/reference/chrome_laptop_viz_Legend_LegendLayout_Hidden_When_Mostly_Truncated.pngindex e9f9cca376e..e01843d8f2c 100644Binary files a/.loki/reference/chrome_laptop_viz_Legend_LegendLayout_Hidden_When_Mostly_Truncated.png and b/.loki/reference/chrome_laptop_viz_Legend_LegendLayout_Hidden_When_Mostly_Truncated.png differdiff --git a/.loki/reference/chrome_laptop_viz_Legend_LegendLayout_Large_Card_Vertical.png b/.loki/reference/chrome_laptop_viz_Legend_LegendLayout_Large_Card_Vertical.pngindex 3bf7913e9d7..f39f89062ed 100644Binary files a/.loki/reference/chrome_laptop_viz_Legend_LegendLayout_Large_Card_Vertical.png and b/.loki/reference/chrome_laptop_viz_Legend_LegendLayout_Large_Card_Vertical.png differdiff --git a/.loki/reference/chrome_laptop_viz_Legend_LegendLayout_Large_Card_Vertical_Overflow.png b/.loki/reference/chrome_laptop_viz_Legend_LegendLayout_Large_Card_Vertical_Overflow.pngindex bff9bcbae54..1952f59e591 100644Binary files a/.loki/reference/chrome_laptop_viz_Legend_LegendLayout_Large_Card_Vertical_Overflow.png and b/.loki/reference/chrome_laptop_viz_Legend_LegendLayout_Large_Card_Vertical_Overflow.png differdiff --git a/.loki/reference/chrome_laptop_viz_Legend_LegendLayout_Minimum_Card_Size.png b/.loki/reference/chrome_laptop_viz_Legend_LegendLayout_Minimum_Card_Size.pngdeleted file mode 100644index a7746b2ba6b..00000000000Binary files a/.loki/reference/chrome_laptop_viz_Legend_LegendLayout_Minimum_Card_Size.png and /dev/null differdiff --git a/.loki/reference/chrome_laptop_viz_Legend_LegendLayout_Query_Builder_Vertical.png b/.loki/reference/chrome_laptop_viz_Legend_LegendLayout_Query_Builder_Vertical.pngindex aea68c0d285..28046fe0066 100644Binary files a/.loki/reference/chrome_laptop_viz_Legend_LegendLayout_Query_Builder_Vertical.png and b/.loki/reference/chrome_laptop_viz_Legend_LegendLayout_Query_Builder_Vertical.png differdiff --git a/.loki/reference/chrome_laptop_viz_Legend_LegendLayout_Short_Card.png b/.loki/reference/chrome_laptop_viz_Legend_LegendLayout_Short_Card.pngnew file mode 100644index 00000000000..5e57e73c6c4Binary files /dev/null and b/.loki/reference/chrome_laptop_viz_Legend_LegendLayout_Short_Card.png differdiff --git a/.loki/reference/chrome_laptop_viz_Legend_LegendLayout_Vertical.png b/.loki/reference/chrome_laptop_viz_Legend_LegendLayout_Vertical.pngindex 8d73229d012..cb6c579f791 100644Binary files a/.loki/reference/chrome_laptop_viz_Legend_LegendLayout_Vertical.png and b/.loki/reference/chrome_laptop_viz_Legend_LegendLayout_Vertical.png differdiff --git a/.loki/reference/chrome_laptop_viz_Legend_LegendLayout_Vertical_Mostly_Truncated.png b/.loki/reference/chrome_laptop_viz_Legend_LegendLayout_Vertical_Mostly_Truncated.pngnew file mode 100644index 00000000000..828f6129cd7Binary files /dev/null and b/.loki/reference/chrome_laptop_viz_Legend_LegendLayout_Vertical_Mostly_Truncated.png differdiff --git a/.loki/reference/chrome_laptop_viz_Legend_LegendLayout_Vertical_Overflow.png b/.loki/reference/chrome_laptop_viz_Legend_LegendLayout_Vertical_Overflow.pngindex b13d06b8f2e..91f6082c92d 100644Binary files a/.loki/reference/chrome_laptop_viz_Legend_LegendLayout_Vertical_Overflow.png and b/.loki/reference/chrome_laptop_viz_Legend_LegendLayout_Vertical_Overflow.png differdiff --git a/.loki/reference/chrome_laptop_viz_Legend_LegendLayout_Vertical_Truncated.png b/.loki/reference/chrome_laptop_viz_Legend_LegendLayout_Vertical_Truncated.pngindex 8d36a96b17b..7223c12bc1c 100644Binary files a/.loki/reference/chrome_laptop_viz_Legend_LegendLayout_Vertical_Truncated.png and b/.loki/reference/chrome_laptop_viz_Legend_LegendLayout_Vertical_Truncated.png differdiff --git a/.loki/reference/chrome_laptop_viz_Legend_LegendLayout_Visualizer_Small_Canvas_Always_Visible.png b/.loki/reference/chrome_laptop_viz_Legend_LegendLayout_Visualizer_Small_Canvas_Always_Visible.pngindex ce76d1e047d..b6523b3d8fc 100644Binary files a/.loki/reference/chrome_laptop_viz_Legend_LegendLayout_Visualizer_Small_Canvas_Always_Visible.png and b/.loki/reference/chrome_laptop_viz_Legend_LegendLayout_Visualizer_Small_Canvas_Always_Visible.png differdiff --git a/docs/questions/visualizations/line-bar-and-area-charts.md b/docs/questions/visualizations/line-bar-and-area-charts.mdindex b996ac7a7fc..237f08e6150 100644--- a/docs/questions/visualizations/line-bar-and-area-charts.md+++ b/docs/questions/visualizations/line-bar-and-area-charts.md@@ -128,6 +128,7 @@ Use the **Display** tab to set:- [Trend lines](#trend-lines)- [Values on data points](#values-on-data-points)- [Autoformatting](#autoformatting)+- [Legend position](#chart-legend)### Stacking@@ -227,7 +228,15 @@ To permanently hide the series from the chart, use the [data settings](#data-setYou can also select a range on the chart to filter results to a specific time period, then drill through to the individual records.-You can't hide the legend or change its position on the chart.+To move or hide the legend, go to the **Display** tab and set **Legend position** to:++- **Auto**: Put the legend below the chart when all the labels fit, or to the right of the chart when they don't fit or the card is short and wide. If neither spot leaves enough room for the chart, Metabase hides the legend.+- **Top**, **Bottom**, **Left**, or **Right**: Put the legend on that side. Metabase hides the legend only when the card has no room on that side.+- **Off**: Hide the legend. Any series you hid by clicking the legend show up again.++If the legend has more items than fit, the extra items go into a **+ N more** list.++[Dashboard subscriptions](../../dashboards/subscriptions.md) and [alerts](../alerts.md) always show the legend, because a chart in an email, a Slack message, or a PDF has no tooltips.## Further readingdiff --git a/docs/questions/visualizations/pie-or-donut-chart.md b/docs/questions/visualizations/pie-or-donut-chart.mdindex fb73ee2db00..971ddcbc2e2 100644--- a/docs/questions/visualizations/pie-or-donut-chart.md+++ b/docs/questions/visualizations/pie-or-donut-chart.md@@ -74,13 +74,13 @@ To format the total displayed in the middle of the chart, click on the three dotYou can configure whether to show:-- The legend next to the chart.+- The legend. To move it, see [Legend position](#legend-position).- The total in the center of the chart. The format of the total can be changed in the [data settings](#data-settings).- The labels for the pie slices. The labels for the inner ring slices can be changed in the [data settings](#data-settings).For sunburst charts with multiple breakouts, only the inner ring breakout will be displayed in the legend. By default, "Show labels" will be turned on. If you turn off "Show labels", the only way to distinguish slices on a sunburst chart will be to hover over them.-- The percentage values for the slices. If you choose to display percentages **In the legend**, but then toggle off **Show legend**, the percentage values won't show up on the chart.+- The percentage values for the slices. If you choose to display percentages **In the legend**, but then set **Legend position** to **Off**, the percentage values won't show up on the chart.You can always see percentage values for any slice by hovering over the slice.@@ -94,6 +94,18 @@ To make the chart more legible, you can group slices smaller than a certain percCurrently, you can't change the color or label of the **Other** slice.+#### Legend position++To move or hide the legend, go to the **Display** tab and set **Legend position** to:++- **Auto**: Put the legend to the left of the chart on wide cards, or below the chart on tall cards. If the card has no room for the legend, Metabase hides it.+- **Top**, **Bottom**, **Left**, or **Right**: Put the legend on that side. Metabase hides the legend only when the card has no room on that side.+- **Off**: Hide the legend. Any slices you hid by clicking the legend show up again.++Legend items that don't fit go into a **+ N more** list, except when **Auto** puts the legend below the chart. There, the legend wraps onto more rows instead.++[Dashboard subscriptions](../../dashboards/subscriptions.md) and [alerts](../alerts.md) always show the legend, because a chart in an email, a Slack message, or a PDF has no tooltips.+## Limitations and alternativesConsider using a bar or row chart (or a [stacked bar chart](line-bar-and-area-charts.md#stacking)) or a [pivot table](pivot-table.md) instead of a pie or sunburst chart in the following cases:diff --git a/frontend/src/metabase-types/api/card.ts b/frontend/src/metabase-types/api/card.tsindex 14c18ec4b36..7ce53328fb1 100644--- a/frontend/src/metabase-types/api/card.ts+++ b/frontend/src/metabase-types/api/card.ts@@ -259,6 +259,16 @@ export type StackType = "stacked" | "normalized" | null;export type StackValuesDisplay = "total" | "all" | "series";export type StackValueFormat = "value" | "percentage";+export const LEGEND_POSITIONS = [+ "auto",+ "top",+ "bottom",+ "left",+ "right",+ "off",+] as const;+export type LegendPosition = (typeof LEGEND_POSITIONS)[number];+export const numericScale = ["linear", "pow", "log"] as const;export type NumericScale = (typeof numericScale)[number];@@ -417,6 +427,14 @@ export type VisualizationSettings = {/** Render compatible series in separate panels instead of one chart. */"graph.split_panels"?: boolean;+ /**+ * Where the legend sits on charts that have one: cartesian, row, scatter,+ * and box plot charts with several series or a breakout, pies, bar-type+ * funnels, and region maps. "auto" lets the chart pick a side that fits;+ * "off" hides the legend.+ */+ "legend.position"?: LegendPosition;+/*** Result column names used for the x-axis, category, or grouping dimension.* Prefer Metabase defaults unless the query needs a specific split.@@ -502,7 +520,7 @@ export type VisualizationSettings = {/** Sort pie slices by metric value. */"pie.sort_rows"?: boolean;- /** Show the pie legend. */+ /** @deprecated Use `legend.position`. Read only as the pie's fallback. */"pie.show_legend"?: boolean;/** Show the total value in the center of the pie. */diff --git a/frontend/src/metabase-types/guards/card.ts b/frontend/src/metabase-types/guards/card.tsindex cd897bcadee..c64d1a1e4e3 100644--- a/frontend/src/metabase-types/guards/card.ts+++ b/frontend/src/metabase-types/guards/card.ts@@ -1,4 +1,10 @@-import type { Card, LineStyle, UnsavedCard } from "metabase-types/api";+import {+ type Card,+ LEGEND_POSITIONS,+ type LegendPosition,+ type LineStyle,+ type UnsavedCard,+} from "metabase-types/api";export function isSavedCard(card: Card | UnsavedCard): card is Card {return "id" in card && card.id != null;@@ -9,3 +15,7 @@ const LINE_STYLES: LineStyle[] = ["solid", "dashed", "dotted"];export function isLineStyle(value: string): value is LineStyle {return LINE_STYLES.some((style) => style === value);}++export function isLegendPosition(value: unknown): value is LegendPosition {+ return LEGEND_POSITIONS.some((position) => position === value);+}diff --git a/frontend/src/metabase/embedding-sdk/types/question.ts b/frontend/src/metabase/embedding-sdk/types/question.tsindex f8728279488..813749a450e 100644--- a/frontend/src/metabase/embedding-sdk/types/question.ts+++ b/frontend/src/metabase/embedding-sdk/types/question.ts@@ -50,6 +50,7 @@ export type CartesianVisualizationSettings = Pick<| "graph.y_axis.min"| "graph.y_axis.max"| "stackable.stack_type"+ | "legend.position"| "series_settings"| "column_settings">;@@ -66,6 +67,7 @@ export type ScatterVisualizationSettings = Pick<| "graph.x_axis.scale"| "graph.y_axis.scale"| "scatter.bubble"+ | "legend.position"| "series_settings"| "column_settings">;@@ -112,6 +114,7 @@ export type PieVisualizationSettings = Pick<| "pie.dimension"| "pie.metric"| "pie.sort_rows"+ | "legend.position"| "pie.show_legend"| "pie.show_total"| "pie.show_labels"@@ -144,7 +147,7 @@ export type ScalarVisualizationSettings = Pick<*/export type FunnelVisualizationSettings = Pick<VisualizationSettings,- "funnel.rows" | "column_settings"+ "funnel.rows" | "legend.position" | "column_settings">;/**@@ -172,16 +175,17 @@ export type BoxplotVisualizationSettings = Pick<| "boxplot.points_mode"| "boxplot.show_mean"| "boxplot.show_values_mode"+ | "legend.position"| "column_settings">;/**- * Settings for pin and region maps. No map-specific settings are surfaced yet;- * use `column_settings` for stable column formatting only.+ * Settings for pin and region maps. Use `legend.position` to place or hide a+ * region map's legend and `column_settings` for stable column formatting.*/export type MapVisualizationSettings = Pick<VisualizationSettings,- "column_settings"+ "legend.position" | "column_settings">;/**diff --git a/frontend/src/metabase/static-viz/components/ComboChart/ComboChart.tsx b/frontend/src/metabase/static-viz/components/ComboChart/ComboChart.tsxindex 17430125503..21c26c110cb 100644--- a/frontend/src/metabase/static-viz/components/ComboChart/ComboChart.tsx+++ b/frontend/src/metabase/static-viz/components/ComboChart/ComboChart.tsx@@ -11,10 +11,10 @@ import {getChartHeight,} from "metabase/static-viz/lib/utils";import {- foldRowChartModel,getCartesianChartModel,getCartesianChartOption,getChartLayout,+ getChartModelAtHeight,getLegendItems,getSizeAdjustedSettings,isRowChartSeries,@@ -78,9 +78,11 @@ export const ComboChart = ({const chartHeight = getChartHeight({ fitWithinBounds, legendHeight, height });// Fold before layout, off the chart height, as the interactive path does.- const chartModel = baseChartModel.isRowChart- ? foldRowChartModel(baseChartModel, chartHeight, settings)- : baseChartModel;+ const chartModel = getChartModelAtHeight(+ baseChartModel,+ chartHeight,+ settings,+ );const chart = init(null, null, {renderer: "svg",diff --git a/frontend/src/metabase/visualizations/components/ChartWithLegend.module.css b/frontend/src/metabase/visualizations/components/ChartWithLegend.module.cssindex 6495b426b02..404eeb4a7c8 100644--- a/frontend/src/metabase/visualizations/components/ChartWithLegend.module.css+++ b/frontend/src/metabase/visualizations/components/ChartWithLegend.module.css@@ -47,11 +47,20 @@flex-direction: column-reverse;}+.ChartWithLegend.vertical.legendBeforeChart {+ flex-direction: column;+}+.ChartWithLegend.vertical .Legend {flex-shrink: 1;overflow: hidden;}+.ChartWithLegend.vertical.legendBeforeChart .Legend {+ margin-top: 0;+ margin-bottom: 1em;+}+.ChartWithLegend.vertical .LegendWrapper {flex-direction: column;}@@ -72,12 +81,21 @@flex-direction: row;}+.ChartWithLegend.horizontal.legendAfterChart {+ flex-direction: row-reverse;+}+.ChartWithLegend.horizontal .Legend {flex-grow: 0;flex-shrink: 1;overflow: hidden;}+.ChartWithLegend.horizontal.legendAfterChart .Legend {+ margin-right: 0;+ margin-left: 1em;+}+.ChartWithLegend.horizontal .LegendWrapper {flex-direction: row;}diff --git a/frontend/src/metabase/visualizations/components/ChartWithLegend.tsx b/frontend/src/metabase/visualizations/components/ChartWithLegend.tsxindex 4c2b5ce1713..178eac122de 100644--- a/frontend/src/metabase/visualizations/components/ChartWithLegend.tsx+++ b/frontend/src/metabase/visualizations/components/ChartWithLegend.tsx@@ -13,34 +13,16 @@ import {import { ExplicitSize } from "metabase/common/components/ExplicitSize";import DashboardS from "metabase/css/dashboard.module.css";import type { HoveredObject } from "metabase/viz-core";+import type { LegendPosition } from "metabase-types/api";import styles from "./ChartWithLegend.module.css";-import { LegendHorizontal } from "./LegendHorizontal";-import { LegendVertical } from "./LegendVertical";+import {+ CHART_WITH_LEGEND_PADDING,+ type GridSize,+ getChartLayout,+} from "./chart-with-legend-layout";import type { LegendHover, LegendTitle } from "./types";-const GRID_ASPECT_RATIO = 4 / 3;-const PADDING = 14;--const DEFAULT_GRID_SIZE = 100;-export const HIDE_HORIZONTAL_LEGEND_THRESHOLD = 180;-export const HIDE_SECONDARY_INFO_THRESHOLD = 260;--type GridSize = {- width: number;- height: number;-};--type ChartLayout = {- type: "horizontal" | "vertical" | "small";- LegendComponent: typeof LegendHorizontal | typeof LegendVertical | undefined;- processedLegendTitles: LegendTitle[];- chartWidth: number | undefined;- chartHeight: number | undefined;- flexChart: boolean;- hasDimensions: boolean;-};-type ChartWithLegendProps = {children?: ReactNode;legendTitles: LegendTitle[];@@ -55,7 +37,7 @@ type ChartWithLegendProps = {aspectRatio?: number;height: number;width: number;- showLegend?: boolean;+ legendPosition?: LegendPosition;isDashboard?: boolean;isDocument?: boolean;isMetricsViewer?: boolean;@@ -77,7 +59,7 @@ const ChartWithLegendInner = ({aspectRatio = 1,height,width,- showLegend = true,+ legendPosition = "auto",isDashboard,isDocument,isMetricsViewer,@@ -101,27 +83,35 @@ const ChartWithLegendInner = ({const layout = useMemo(() =>getChartLayout({+ position: legendPosition,width: stableWidth,height: stableHeight,gridSize,aspectRatio,legendTitles,}),- [stableWidth, stableHeight, gridSize, aspectRatio, legendTitles],+ [+ legendPosition,+ stableWidth,+ stableHeight,+ gridSize,+ aspectRatio,+ legendTitles,+ ],);- const legend =- showLegend && layout.type !== "small" && layout.LegendComponent ? (- <layout.LegendComponent- className={styles.Legend}- titles={layout.processedLegendTitles}- hiddenIndices={legendHiddenIndices}- colors={legendColors}- hovered={hovered}- onHoverChange={onHoverChange}- onToggleSeriesVisibility={onToggleSeriesVisibility}- />- ) : null;+ const legend = layout.LegendComponent ? (+ <layout.LegendComponent+ className={styles.Legend}+ titles={layout.processedLegendTitles}+ hiddenIndices={legendHiddenIndices}+ colors={legendColors}+ hovered={hovered}+ onHoverChange={onHoverChange}+ onToggleSeriesVisibility={onToggleSeriesVisibility}+ isSingleRow={layout.isLegendSingleRow}+ />+ ) : null;return (<div@@ -131,12 +121,15 @@ const ChartWithLegendInner = ({styles.ChartWithLegend,styles[layout.type],layout.flexChart && styles.flexChart,+ layout.isLegendBeforeChart+ ? styles.legendBeforeChart+ : styles.legendAfterChart,)}style={{...style,- paddingBottom: PADDING,- paddingLeft: PADDING,- paddingRight: PADDING,+ paddingBottom: CHART_WITH_LEGEND_PADDING,+ paddingLeft: CHART_WITH_LEGEND_PADDING,+ paddingRight: CHART_WITH_LEGEND_PADDING,}}data-testid="chart-with-legend"data-legend-position={layout.type}@@ -186,82 +179,3 @@ export const ChartWithLegend = ExplicitSize<ChartWithLegendProps>({wrapped: true,refreshMode: "debounce",})(ChartWithLegendRefWrapper);--export function getChartLayout({- width,- height,- gridSize,- aspectRatio,- legendTitles,-}: {- width: number;- height: number;- gridSize: GridSize | undefined;- aspectRatio: number;- legendTitles: LegendTitle[];-}): ChartLayout {- const adjustedWidth = width - PADDING * 2;- const adjustedHeight = height - PADDING;- const hasDimensions = adjustedWidth > 0 && adjustedHeight > 0;-- const calculatedGridSize = gridSize || {- width: adjustedWidth / DEFAULT_GRID_SIZE,- height: adjustedHeight / DEFAULT_GRID_SIZE,- };-- const isHorizontal =- calculatedGridSize.width > calculatedGridSize.height / GRID_ASPECT_RATIO;-- if (isHorizontal && adjustedWidth > HIDE_HORIZONTAL_LEGEND_THRESHOLD) {- const processedLegendTitles =- adjustedWidth < HIDE_SECONDARY_INFO_THRESHOLD- ? legendTitles.map((title) =>- Array.isArray(title) ? title.slice(0, 1) : title,- )- : legendTitles;- const desiredWidth = adjustedHeight * aspectRatio;- const flexChart = desiredWidth > adjustedWidth * (2 / 3);-- return {- type: "horizontal",- LegendComponent: LegendVertical,- processedLegendTitles,- chartWidth: flexChart ? undefined : desiredWidth,- chartHeight: adjustedHeight,- flexChart,- hasDimensions,- };- }-- if (- !isHorizontal &&- calculatedGridSize.height > 3 &&- calculatedGridSize.width > 2- ) {- const processedLegendTitles = legendTitles.map((title) =>- Array.isArray(title) ? title.join(" ") : title,- );- const desiredHeight = adjustedWidth * (1 / aspectRatio);- const flexChart = desiredHeight > adjustedHeight * (3 / 4);-- return {- type: "vertical",- LegendComponent: LegendHorizontal,- processedLegendTitles,- chartWidth: adjustedWidth,- chartHeight: flexChart ? undefined : desiredHeight,- flexChart,- hasDimensions,- };- }-- return {- type: "small",- LegendComponent: undefined,- processedLegendTitles: legendTitles,- chartWidth: undefined,- chartHeight: undefined,- flexChart: false,- hasDimensions,- };-}diff --git a/frontend/src/metabase/visualizations/components/ChartWithLegend.unit.spec.tsx b/frontend/src/metabase/visualizations/components/ChartWithLegend.unit.spec.tsxindex 1ea54b2ddf0..3166856efb1 100644--- a/frontend/src/metabase/visualizations/components/ChartWithLegend.unit.spec.tsx+++ b/frontend/src/metabase/visualizations/components/ChartWithLegend.unit.spec.tsx@@ -2,15 +2,13 @@ import type { CSSProperties, MouseEvent, ReactNode } from "react";import { render, screen } from "__support__/ui";import type { HoveredObject } from "metabase/viz-core";+import type { LegendPosition } from "metabase-types/api";+import { ChartWithLegend } from "./ChartWithLegend";import {- ChartWithLegend,HIDE_HORIZONTAL_LEGEND_THRESHOLD,HIDE_SECONDARY_INFO_THRESHOLD,- getChartLayout,-} from "./ChartWithLegend";-import { LegendHorizontal } from "./LegendHorizontal";-import { LegendVertical } from "./LegendVertical";+} from "./chart-with-legend-layout";import type { LegendHover, LegendTitle } from "./types";interface SetupProps {@@ -29,7 +27,7 @@ interface SetupProps {aspectRatio?: number;height: number;width: number;- showLegend?: boolean;+ legendPosition?: LegendPosition;isDashboard?: boolean;isDocument?: boolean;onToggleSeriesVisibility?: (event: MouseEvent, index: number) => void;@@ -41,7 +39,6 @@ const defaultProps: SetupProps = {["Series 2", "50%"],],legendColors: ["Red", "Green"],- showLegend: true,width: 800,height: 600,gridSize: { width: 8, height: 6 },@@ -102,92 +99,11 @@ describe("ChartWithLegend", () => {expect(screen.getByTestId("chart-legend")).toHaveTextContent("Foo 10%");expect(screen.getByTestId("chart-legend")).toHaveTextContent("Bar 90%");});-});--describe("getChartLayout", () => {- const defaultInput: Parameters<typeof getChartLayout>[0] = {- width: 800,- height: 400,- gridSize: undefined,- aspectRatio: 1,- legendTitles: ["Series 1", "Series 2"],- };-- it("should lay out a wide chart horizontally with a fixed chart size", () => {- const layout = getChartLayout(defaultInput);-- expect(layout).toMatchObject({- type: "horizontal",- LegendComponent: LegendVertical,- chartWidth: 386,- chartHeight: 386,- flexChart: false,- hasDimensions: true,- });- expect(layout.processedLegendTitles).toEqual(["Series 1", "Series 2"]);- });-- it("should hide secondary title info and flex the chart when the area is narrow", () => {- const layout = getChartLayout({- ...defaultInput,- width: 250,- height: 200,- legendTitles: [["Series 1", "50%"], "Series 2"],- });-- expect(layout).toMatchObject({- type: "horizontal",- flexChart: true,- chartWidth: undefined,- chartHeight: 186,- });- expect(layout.processedLegendTitles).toEqual([["Series 1"], "Series 2"]);- });-- it("should lay out vertically with joined titles when the grid is tall", () => {- const layout = getChartLayout({- ...defaultInput,- height: 600,- gridSize: { width: 3, height: 8 },- aspectRatio: 2,- legendTitles: [["Series 1", "50%"], "Series 2"],- });-- expect(layout).toMatchObject({- type: "vertical",- LegendComponent: LegendHorizontal,- chartWidth: 772,- chartHeight: 386,- flexChart: false,- });- expect(layout.processedLegendTitles).toEqual(["Series 1 50%", "Series 2"]);- });-- it("should use the small layout when the grid has too few columns", () => {- const layout = getChartLayout({- ...defaultInput,- gridSize: { width: 2, height: 8 },- });-- expect(layout).toMatchObject({- type: "small",- LegendComponent: undefined,- chartWidth: undefined,- chartHeight: undefined,- flexChart: false,- });- });- it("should use the small layout when a horizontal chart is below the legend width threshold", () => {- const layout = getChartLayout({ ...defaultInput, width: 200, height: 100 });-- expect(layout.type).toBe("small");- expect(layout.LegendComponent).toBeUndefined();- });+ it("should render no legend when the position is off", () => {+ setup({ legendPosition: "off" });- it("should report missing dimensions when the chart is not measured yet", () => {- const layout = getChartLayout({ ...defaultInput, width: 0, height: 0 });-- expect(layout).toMatchObject({ type: "small", hasDimensions: false });+ expect(screen.getByText("Chart stub")).toBeInTheDocument();+ expect(screen.queryByTestId("chart-legend")).not.toBeInTheDocument();});});diff --git a/frontend/src/metabase/visualizations/components/ChoroplethMap.tsx b/frontend/src/metabase/visualizations/components/ChoroplethMap.tsxindex 6b439def594..d33e72167cf 100644--- a/frontend/src/metabase/visualizations/components/ChoroplethMap.tsx+++ b/frontend/src/metabase/visualizations/components/ChoroplethMap.tsx@@ -452,6 +452,7 @@ function ChoroplethMapInner(props: ChoroplethMapProps) {aspectRatio={aspectRatio}legendTitles={legendTitles}legendColors={heatMapColors}+ legendPosition={settings["legend.position"]}gridSize={gridSize}hovered={hovered}onHoverChange={onLegendHoverChange}diff --git a/frontend/src/metabase/visualizations/components/Legend.module.css b/frontend/src/metabase/visualizations/components/Legend.module.cssindex c86d4d14dd2..0b4cbdebcc4 100644--- a/frontend/src/metabase/visualizations/components/Legend.module.css+++ b/frontend/src/metabase/visualizations/components/Legend.module.css@@ -35,6 +35,17 @@ fullscreen dashboard modemargin-top: 1em;}+.Legend.horizontal.singleRow {+ flex-wrap: nowrap;++ /* overflow only past the end, so it folds from the end */+ justify-content: safe center;+}++.singleRowItem {+ min-width: 0;+}+.DashCard.LegendItem {font-weight: normal;color: var(--mb-color-text-primary);diff --git a/frontend/src/metabase/visualizations/components/LegendHorizontal.tsx b/frontend/src/metabase/visualizations/components/LegendHorizontal.tsxindex 2f31e3a9eff..63cefca513f 100644--- a/frontend/src/metabase/visualizations/components/LegendHorizontal.tsx+++ b/frontend/src/metabase/visualizations/components/LegendHorizontal.tsx@@ -1,10 +1,19 @@import cx from "classnames";import { useRef } from "react";+import CS from "metabase/css/core/index.css";+import { useLegendOverflow } from "metabase/visualizations/hooks/use-legend-overflow";+import LegendS from "./Legend.module.css";import { LegendItem } from "./LegendItem";+import { LegendOverflow } from "./LegendVertical";+import { MIN_VISIBLE_COUNT } from "./legend/constants";import type { LegendProps } from "./types";+type LegendHorizontalProps = LegendProps & {+ isSingleRow?: boolean;+};+export function LegendHorizontal({className,titles,@@ -13,12 +22,31 @@ export function LegendHorizontal({hovered,onHoverChange,onToggleSeriesVisibility,-}: LegendProps) {+ isSingleRow = false,+}: LegendHorizontalProps) {const legendItemRefs = useRef<Record<number, HTMLSpanElement | null>>({});+ const { overflowCount, visibleCount, containerRef, itemRefs } =+ useLegendOverflow({+ titles,+ minVisibleCount: MIN_VISIBLE_COUNT,+ axis: "horizontal",+ isEnabled: isSingleRow,+ });+ const itemClassName = isSingleRow+ ? cx(LegendS.singleRowItem, {+ // items keep their natural width until the overflow is measured+ [CS.flexNoShrink]: overflowCount === 0,+ })+ : undefined;return (- <ol className={cx(className, LegendS.Legend, LegendS.horizontal)}>- {titles.map((title, index) => {+ <ol+ className={cx(className, LegendS.Legend, LegendS.horizontal, {+ [LegendS.singleRow]: isSingleRow,+ })}+ ref={containerRef}+ >+ {titles.slice(0, visibleCount).map((title, index) => {const isMuted = hovered?.index != null && index !== hovered.index;const isVisible = !hiddenIndices.includes(index);@@ -36,6 +64,10 @@ export function LegendHorizontal({return (<likey={index}+ ref={(element) => {+ itemRefs.current[index] = element;+ }}+ className={itemClassName}data-testid={`legend-item-${title}`}aria-current={hovered ? !isMuted : undefined}>@@ -66,6 +98,15 @@ export function LegendHorizontal({</li>);})}+ {visibleCount < titles.length && (+ <LegendOverflow+ titles={titles}+ colors={colors}+ hiddenIndices={hiddenIndices}+ visibleCount={visibleCount}+ onToggleSeriesVisibility={onToggleSeriesVisibility}+ />+ )}</ol>);}diff --git a/frontend/src/metabase/visualizations/components/LegendHorizontal.unit.spec.tsx b/frontend/src/metabase/visualizations/components/LegendHorizontal.unit.spec.tsxnew file mode 100644index 00000000000..9a6e872d21a--- /dev/null+++ b/frontend/src/metabase/visualizations/components/LegendHorizontal.unit.spec.tsx@@ -0,0 +1,156 @@+import userEvent from "@testing-library/user-event";++import { createMockDOMRect, render, screen } from "__support__/ui";++import { LegendHorizontal } from "./LegendHorizontal";++const ITEM_WIDTH = 100;+const SHORT_ITEM_WIDTH = 50;+const ROW_HEIGHT = 20;+const TITLES = ["Widget", "Gadget", "Gizmo", "Doohickey", "Thingamajig"];+const SHORT_TITLES = ["A", "B", "C", "D", "E"];+const COLORS = ["red", "green", "blue", "yellow", "purple"];++interface RowLayoutOpts {+ rowWidth: number;+ titles?: string[];+ itemWidth?: number;+}++// lays the list items side by side, itemWidth each, in a list rowWidth wide+const mockRowLayout = ({+ rowWidth,+ titles = TITLES,+ itemWidth = ITEM_WIDTH,+}: RowLayoutOpts) => {+ jest+ .spyOn(window.Element.prototype, "getBoundingClientRect")+ .mockImplementation(function (this: Element) {+ const itemIndex = titles.findIndex(+ (title) => this.getAttribute("data-testid") === `legend-item-${title}`,+ );+ if (itemIndex >= 0) {+ const left = itemIndex * itemWidth;+ return createMockDOMRect({+ left,+ right: left + itemWidth,+ width: itemWidth,+ bottom: ROW_HEIGHT,+ height: ROW_HEIGHT,+ });+ }+ return createMockDOMRect({+ right: rowWidth,+ width: rowWidth,+ bottom: ROW_HEIGHT,+ height: ROW_HEIGHT,+ });+ });+};++interface SetupOpts {+ rowWidth: number;+ isSingleRow?: boolean;+}++const setup = ({ rowWidth, isSingleRow }: SetupOpts) => {+ mockRowLayout({ rowWidth });+ const { rerender } = render(+ <LegendHorizontal+ titles={TITLES}+ colors={COLORS}+ isSingleRow={isSingleRow}+ />,+ );+ const rerenderWithTitles = (titles: string[]) =>+ rerender(+ <LegendHorizontal+ titles={titles}+ colors={COLORS.slice(0, titles.length)}+ isSingleRow={isSingleRow}+ />,+ );+ return { rerenderWithTitles };+};++describe("LegendHorizontal", () => {+ afterEach(() => {+ jest.restoreAllMocks();+ });++ it("should render every title when the rows may wrap", () => {+ setup({ rowWidth: 250 });++ TITLES.forEach((title) =>+ expect(screen.getByText(title)).toBeInTheDocument(),+ );+ expect(screen.queryByText(/more/)).not.toBeInTheDocument();+ });++ it("should render every title in a single row when they fit", () => {+ setup({ rowWidth: 500, isSingleRow: true });++ TITLES.forEach((title) =>+ expect(screen.getByText(title)).toBeInTheDocument(),+ );+ expect(screen.queryByText(/more/)).not.toBeInTheDocument();+ });++ it("should fold the titles that do not fit a single row into a '+ N more' popover", async () => {+ // 3 items fit in 300px, one more folds to make room for "+ 3 more"+ setup({ rowWidth: 300, isSingleRow: true });++ expect(screen.getByText("Widget")).toBeInTheDocument();+ expect(screen.getByText("Gadget")).toBeInTheDocument();+ expect(screen.queryByText("Gizmo")).not.toBeInTheDocument();++ await userEvent.click(screen.getByText("+ 3 more"));++ expect(await screen.findByText("Gizmo")).toBeInTheDocument();+ expect(screen.getByText("Doohickey")).toBeInTheDocument();+ expect(screen.getByText("Thingamajig")).toBeInTheDocument();+ });++ it("should keep the first title visible when no title fits", () => {+ setup({ rowWidth: 50, isSingleRow: true });++ expect(screen.getByText("Widget")).toBeInTheDocument();+ expect(screen.queryByText("Gadget")).not.toBeInTheDocument();+ expect(screen.getByText("+ 4 more")).toBeInTheDocument();+ });++ it("should measure again when fewer titles arrive in a row of the same width", () => {+ const { rerenderWithTitles } = setup({+ rowWidth: 300,+ isSingleRow: true,+ });+ expect(screen.getByText("+ 3 more")).toBeInTheDocument();++ rerenderWithTitles(TITLES.slice(0, 3));++ expect(screen.getByText("Widget")).toBeInTheDocument();+ expect(screen.getByText("Gadget")).toBeInTheDocument();+ expect(screen.getByText("Gizmo")).toBeInTheDocument();+ expect(screen.queryByText(/more/)).not.toBeInTheDocument();+ });++ it("should measure again when as many different titles arrive in a row of the same width", () => {+ const { rerenderWithTitles } = setup({+ rowWidth: 300,+ isSingleRow: true,+ });+ expect(screen.getByText("+ 3 more")).toBeInTheDocument();++ mockRowLayout({+ rowWidth: 300,+ titles: SHORT_TITLES,+ itemWidth: SHORT_ITEM_WIDTH,+ });+ rerenderWithTitles(SHORT_TITLES);++ SHORT_TITLES.forEach((title) =>+ expect(screen.getByText(title)).toBeInTheDocument(),+ );+ expect(screen.queryByText(/more/)).not.toBeInTheDocument();+ });+});diff --git a/frontend/src/metabase/visualizations/components/LegendVertical.tsx b/frontend/src/metabase/visualizations/components/LegendVertical.tsxindex 8092a52c582..8d1e779c175 100644--- a/frontend/src/metabase/visualizations/components/LegendVertical.tsx+++ b/frontend/src/metabase/visualizations/components/LegendVertical.tsx@@ -1,13 +1,14 @@import cx from "classnames";-import { useLayoutEffect, useRef, useState } from "react";-import { t } from "ttag";+import { useRef } from "react";import CS from "metabase/css/core/index.css";import DashboardS from "metabase/css/dashboard.module.css";import { Popover } from "metabase/ui";+import { useLegendOverflow } from "metabase/visualizations/hooks/use-legend-overflow";import LegendS from "./Legend.module.css";import { LegendItem } from "./LegendItem";+import { getOverflowLabel } from "./legend/measure";import type { LegendProps } from "./types";export function LegendVertical({@@ -19,62 +20,19 @@ export function LegendVertical({onHoverChange,onToggleSeriesVisibility,}: LegendProps) {- const [overflowCount, setOverflowCount] = useState(0);- const [size, setSize] = useState<DOMRect | null>(null);- const listContainerRef = useRef<HTMLOListElement>(null);- const itemRefs = useRef<Record<number, HTMLLIElement | null>>({});- const legendItemRefs = useRef<Record<number, HTMLSpanElement | null>>({});- const prevOverflowCountRef = useRef(overflowCount);-- // Measures whether legend items overflow the widget area. Runs after every- // render because the container can resize without any prop or state change.- // eslint-disable-next-line react-hooks/exhaustive-deps- useLayoutEffect(() => {- const prevOverflowCount = prevOverflowCountRef.current;- prevOverflowCountRef.current = overflowCount;-- const containerRect = listContainerRef.current?.getBoundingClientRect();- if (!containerRect) {- return;- }-- // check the height, width may fluctuate depending on the browser causing an infinite loop- // check overflowCount, because after setting overflowCount the height changes and it causing an infinite loop too- if (- size &&- containerRect.height !== size.height &&- prevOverflowCount === overflowCount- ) {- setOverflowCount(0);- setSize(containerRect);- } else if (overflowCount === 0) {- let currentOverflowCount = 0;- for (let i = 0; i < titles.length; i++) {- const itemRect = itemRefs.current[i]?.getBoundingClientRect();- if (- itemRect &&- (containerRect.top > itemRect.top ||- containerRect.bottom < itemRect.bottom)- ) {- currentOverflowCount++;- }- }- if (currentOverflowCount !== overflowCount) {- setOverflowCount(currentOverflowCount);- setSize(containerRect);- }- }+ const { visibleCount, containerRef, itemRefs } = useLegendOverflow({+ titles,+ minVisibleCount: 0,+ axis: "vertical",});-- const hasOverflow = overflowCount > 0;- const items = hasOverflow ? titles.slice(0, -overflowCount - 1) : titles;+ const legendItemRefs = useRef<Record<number, HTMLSpanElement | null>>({});return (<olclassName={cx(className, LegendS.Legend, LegendS.vertical)}- ref={listContainerRef}+ ref={containerRef}>- {items.map((title, index) => {+ {titles.slice(0, visibleCount).map((title, index) => {const isMuted = hovered?.index != null && index !== hovered.index;const legendItemTitle = Array.isArray(title) ? title[0] : title;const isVisible = !hiddenIndices.includes(index);@@ -142,34 +100,61 @@ export function LegendVertical({</li>);})}- {hasOverflow ? (- <Popover>- <Popover.Target>- <li className={cx(CS.flex, CS.flexNoShrink, CS.cursorPointer)}>- <LegendItem- title={overflowCount + 1 + " " + t`more`}- color="gray"- showTooltip={false}- />- </li>- </Popover.Target>- <Popover.Dropdown>- <LegendVertical- className={CS.p2}- titles={titles.slice(-overflowCount - 1)}- colors={colors- .slice(-overflowCount - 1)- .concat(colors.slice(0, -overflowCount - 1))}- hiddenIndices={hiddenIndices- .filter((i) => i >= items.length - 1)- .map((i) => i - items.length)}- onToggleSeriesVisibility={(event, sliceIndex) =>- onToggleSeriesVisibility?.(event, sliceIndex + items.length)- }- />- </Popover.Dropdown>- </Popover>- ) : null}+ {visibleCount < titles.length && (+ <LegendOverflow+ titles={titles}+ colors={colors}+ hiddenIndices={hiddenIndices}+ visibleCount={visibleCount}+ onToggleSeriesVisibility={onToggleSeriesVisibility}+ />+ )}</ol>);}++type LegendOverflowProps = Pick<+ LegendProps,+ "titles" | "colors" | "hiddenIndices" | "onToggleSeriesVisibility"+> & {+ visibleCount: number;+};++export function LegendOverflow({+ titles,+ colors,+ hiddenIndices = [],+ visibleCount,+ onToggleSeriesVisibility,+}: LegendOverflowProps) {+ const foldedCount = titles.length - visibleCount;++ return (+ <Popover>+ <Popover.Target>+ <li className={cx(CS.flex, CS.flexNoShrink, CS.cursorPointer)}>+ <LegendItem+ title={getOverflowLabel(foldedCount)}+ color="gray"+ showTooltip={false}+ />+ </li>+ </Popover.Target>+ <Popover.Dropdown>+ <LegendVertical+ className={CS.p2}+ titles={titles.slice(-foldedCount)}+ colors={colors+ .slice(-foldedCount)+ .concat(colors.slice(0, -foldedCount))}+ hiddenIndices={hiddenIndices+ .filter((i) => i >= visibleCount)+ .map((i) => i - visibleCount)}+ onToggleSeriesVisibility={(event, sliceIndex) =>+ onToggleSeriesVisibility?.(event, sliceIndex + visibleCount)+ }+ />+ </Popover.Dropdown>+ </Popover>+ );+}diff --git a/frontend/src/metabase/visualizations/components/chart-with-legend-layout.ts b/frontend/src/metabase/visualizations/components/chart-with-legend-layout.tsnew file mode 100644index 00000000000..955f5c6c787--- /dev/null+++ b/frontend/src/metabase/visualizations/components/chart-with-legend-layout.ts@@ -0,0 +1,224 @@+import type { LegendPosition } from "metabase-types/api";++import { LegendHorizontal } from "./LegendHorizontal";+import { LegendVertical } from "./LegendVertical";+import { LEGEND_PLACEMENTS, type LegendPlacement } from "./legend/placement";+import type { LegendTitle } from "./types";++const GRID_ASPECT_RATIO = 4 / 3;+export const CHART_WITH_LEGEND_PADDING = 14;++const DEFAULT_GRID_SIZE = 100;+export const HIDE_HORIZONTAL_LEGEND_THRESHOLD = 180;+export const HIDE_SECONDARY_INFO_THRESHOLD = 260;+const MIN_ROW_GRID_HEIGHT = 3;+const MIN_ROW_GRID_WIDTH = 2;++export type GridSize = {+ width: number;+ height: number;+};++type ChartLayout = {+ type: "horizontal" | "vertical" | "small";+ isLegendBeforeChart: boolean;+ LegendComponent: typeof LegendHorizontal | typeof LegendVertical | undefined;+ isLegendSingleRow: boolean;+ processedLegendTitles: LegendTitle[];+ chartWidth: number | undefined;+ chartHeight: number | undefined;+ flexChart: boolean;+ hasDimensions: boolean;+};++interface LayoutArea {+ adjustedWidth: number;+ adjustedHeight: number;+ hasDimensions: boolean;+ aspectRatio: number;+ legendTitles: LegendTitle[];+}++export function getChartLayout({+ position,+ width,+ height,+ gridSize,+ aspectRatio,+ legendTitles,+}: {+ position: LegendPosition;+ width: number;+ height: number;+ gridSize: GridSize | undefined;+ aspectRatio: number;+ legendTitles: LegendTitle[];+}): ChartLayout {+ const adjustedWidth = width - CHART_WITH_LEGEND_PADDING * 2;+ const adjustedHeight = height - CHART_WITH_LEGEND_PADDING;+ const area: LayoutArea = {+ adjustedWidth,+ adjustedHeight,+ hasDimensions: adjustedWidth > 0 && adjustedHeight > 0,+ aspectRatio,+ legendTitles,+ };++ const placement = getPlacement(position, area, getGridSize(area, gridSize));+ if (placement == null) {+ return getSmallLayout(area);+ }++ const isAuto = position === "auto";+ const { orientation, isBeforeChart } = LEGEND_PLACEMENTS[placement];+ if (orientation === "vertical") {+ return getSideLayout(area, { isLegendBeforeChart: isBeforeChart });+ }+ return getStackedLayout(area, {+ isLegendBeforeChart: isBeforeChart,+ isLegendSingleRow: !isAuto,+ });+}++function getPlacement(+ position: LegendPosition,+ area: LayoutArea,+ grid: GridSize,+): LegendPlacement | null {+ if (position === "off") {+ return null;+ }+ if (position === "auto") {+ return getAutoPlacement(area, grid);+ }+ return hasRoomForPlacement(position, area, grid) ? position : null;+}++function getGridSize(+ { adjustedWidth, adjustedHeight }: LayoutArea,+ gridSize: GridSize | undefined,+): GridSize {+ return (+ gridSize ?? {+ width: adjustedWidth / DEFAULT_GRID_SIZE,+ height: adjustedHeight / DEFAULT_GRID_SIZE,+ }+ );+}++function getAutoPlacement(+ area: LayoutArea,+ grid: GridSize,+): LegendPlacement | null {+ const isHorizontal = grid.width > grid.height / GRID_ASPECT_RATIO;++ if (isHorizontal && hasRoomForColumn(area)) {+ return "left";+ }++ if (!isHorizontal && hasRoomForRow(grid)) {+ return "bottom";+ }++ return null;+}++function hasRoomForPlacement(+ placement: LegendPlacement,+ area: LayoutArea,+ grid: GridSize,+): boolean {+ const { orientation } = LEGEND_PLACEMENTS[placement];+ return orientation === "vertical"+ ? hasRoomForColumn(area)+ : hasRoomForRow(grid);+}++function hasRoomForColumn({ adjustedWidth }: LayoutArea): boolean {+ return adjustedWidth > HIDE_HORIZONTAL_LEGEND_THRESHOLD;+}++function hasRoomForRow(grid: GridSize): boolean {+ return grid.height > MIN_ROW_GRID_HEIGHT && grid.width > MIN_ROW_GRID_WIDTH;+}++function getSideLayout(+ {+ adjustedWidth,+ adjustedHeight,+ hasDimensions,+ aspectRatio,+ legendTitles,+ }: LayoutArea,+ { isLegendBeforeChart }: Pick<ChartLayout, "isLegendBeforeChart">,+): ChartLayout {+ const processedLegendTitles =+ adjustedWidth < HIDE_SECONDARY_INFO_THRESHOLD+ ? legendTitles.map((title) =>+ Array.isArray(title) ? title.slice(0, 1) : title,+ )+ : legendTitles;+ const desiredWidth = adjustedHeight * aspectRatio;+ const flexChart = desiredWidth > adjustedWidth * (2 / 3);++ return {+ type: "horizontal",+ isLegendBeforeChart,+ LegendComponent: LegendVertical,+ isLegendSingleRow: false,+ processedLegendTitles,+ chartWidth: flexChart ? undefined : desiredWidth,+ chartHeight: adjustedHeight,+ flexChart,+ hasDimensions,+ };+}++function getStackedLayout(+ {+ adjustedWidth,+ adjustedHeight,+ hasDimensions,+ aspectRatio,+ legendTitles,+ }: LayoutArea,+ {+ isLegendBeforeChart,+ isLegendSingleRow,+ }: Pick<ChartLayout, "isLegendBeforeChart" | "isLegendSingleRow">,+): ChartLayout {+ const processedLegendTitles = legendTitles.map((title) =>+ Array.isArray(title) ? title.join(" ") : title,+ );+ const desiredHeight = adjustedWidth * (1 / aspectRatio);+ const flexChart = desiredHeight > adjustedHeight * (3 / 4);++ return {+ type: "vertical",+ isLegendBeforeChart,+ LegendComponent: LegendHorizontal,+ isLegendSingleRow,+ processedLegendTitles,+ chartWidth: adjustedWidth,+ chartHeight: flexChart ? undefined : desiredHeight,+ flexChart,+ hasDimensions,+ };+}++function getSmallLayout({+ hasDimensions,+ legendTitles,+}: LayoutArea): ChartLayout {+ return {+ type: "small",+ isLegendBeforeChart: false,+ LegendComponent: undefined,+ isLegendSingleRow: false,+ processedLegendTitles: legendTitles,+ chartWidth: undefined,+ chartHeight: undefined,+ flexChart: false,+ hasDimensions,+ };+}diff --git a/frontend/src/metabase/visualizations/components/chart-with-legend-layout.unit.spec.ts b/frontend/src/metabase/visualizations/components/chart-with-legend-layout.unit.spec.tsnew file mode 100644index 00000000000..adfe0669ea9--- /dev/null+++ b/frontend/src/metabase/visualizations/components/chart-with-legend-layout.unit.spec.ts@@ -0,0 +1,240 @@+import type { LegendPosition } from "metabase-types/api";++import { LegendHorizontal } from "./LegendHorizontal";+import { LegendVertical } from "./LegendVertical";+import {+ HIDE_HORIZONTAL_LEGEND_THRESHOLD,+ getChartLayout,+} from "./chart-with-legend-layout";++describe("getChartLayout", () => {+ const defaultInput: Parameters<typeof getChartLayout>[0] = {+ position: "auto",+ width: 800,+ height: 400,+ gridSize: undefined,+ aspectRatio: 1,+ legendTitles: ["Series 1", "Series 2"],+ };++ it("should lay out a wide chart horizontally with a fixed chart size", () => {+ const layout = getChartLayout(defaultInput);++ expect(layout).toMatchObject({+ type: "horizontal",+ isLegendBeforeChart: true,+ LegendComponent: LegendVertical,+ chartWidth: 386,+ chartHeight: 386,+ flexChart: false,+ hasDimensions: true,+ });+ expect(layout.processedLegendTitles).toEqual(["Series 1", "Series 2"]);+ });++ it("should hide secondary title info and flex the chart when the area is narrow", () => {+ const layout = getChartLayout({+ ...defaultInput,+ width: 250,+ height: 200,+ legendTitles: [["Series 1", "50%"], "Series 2"],+ });++ expect(layout).toMatchObject({+ type: "horizontal",+ flexChart: true,+ chartWidth: undefined,+ chartHeight: 186,+ });+ expect(layout.processedLegendTitles).toEqual([["Series 1"], "Series 2"]);+ });++ it("should lay out vertically with joined titles when the grid is tall", () => {+ const layout = getChartLayout({+ ...defaultInput,+ height: 600,+ gridSize: { width: 3, height: 8 },+ aspectRatio: 2,+ legendTitles: [["Series 1", "50%"], "Series 2"],+ });++ expect(layout).toMatchObject({+ type: "vertical",+ isLegendBeforeChart: false,+ LegendComponent: LegendHorizontal,+ isLegendSingleRow: false,+ chartWidth: 772,+ chartHeight: 386,+ flexChart: false,+ });+ expect(layout.processedLegendTitles).toEqual(["Series 1 50%", "Series 2"]);+ });++ it("should use the small layout when the grid has too few columns", () => {+ const layout = getChartLayout({+ ...defaultInput,+ gridSize: { width: 2, height: 8 },+ });++ expect(layout).toMatchObject({+ type: "small",+ LegendComponent: undefined,+ chartWidth: undefined,+ chartHeight: undefined,+ flexChart: false,+ });+ });++ it("should use the small layout when a horizontal chart is below the legend width threshold", () => {+ const layout = getChartLayout({ ...defaultInput, width: 200, height: 100 });++ expect(layout.type).toBe("small");+ expect(layout.LegendComponent).toBeUndefined();+ });++ it("should report missing dimensions when the chart is not measured yet", () => {+ const layout = getChartLayout({ ...defaultInput, width: 0, height: 0 });++ expect(layout).toMatchObject({ type: "small", hasDimensions: false });+ });++ it.each<{ position: LegendPosition; isLegendBeforeChart: boolean }>([+ { position: "left", isLegendBeforeChart: true },+ { position: "right", isLegendBeforeChart: false },+ ])(+ "should place a $position legend beside the chart even when the grid is tall",+ ({ position, isLegendBeforeChart }) => {+ const layout = getChartLayout({+ ...defaultInput,+ position,+ height: 600,+ gridSize: { width: 3, height: 8 },+ legendTitles: [["Series 1", "50%"], "Series 2"],+ });++ expect(layout).toMatchObject({+ type: "horizontal",+ isLegendBeforeChart,+ LegendComponent: LegendVertical,+ flexChart: true,+ });+ expect(layout.processedLegendTitles).toEqual([+ ["Series 1", "50%"],+ "Series 2",+ ]);+ },+ );++ it.each<{ position: LegendPosition; isLegendBeforeChart: boolean }>([+ { position: "top", isLegendBeforeChart: true },+ { position: "bottom", isLegendBeforeChart: false },+ ])(+ "should stack a $position legend with the chart even when the area is wide",+ ({ position, isLegendBeforeChart }) => {+ const layout = getChartLayout({+ ...defaultInput,+ position,+ legendTitles: [["Series 1", "50%"], "Series 2"],+ });++ expect(layout).toMatchObject({+ type: "vertical",+ isLegendBeforeChart,+ LegendComponent: LegendHorizontal,+ isLegendSingleRow: true,+ flexChart: true,+ });+ expect(layout.processedLegendTitles).toEqual([+ "Series 1 50%",+ "Series 2",+ ]);+ },+ );++ it.each<LegendPosition>(["left", "right"])(+ "should show a %s legend on a tall card wide enough for a column where the automatic layout hides it",+ (position) => {+ const input = {+ ...defaultInput,+ width: 300,+ height: 600,+ gridSize: { width: 2, height: 8 },+ };++ expect(getChartLayout(input).type).toBe("small");+ expect(getChartLayout({ ...input, position })).toMatchObject({+ type: "horizontal",+ LegendComponent: LegendVertical,+ });+ },+ );++ it.each<LegendPosition>(["top", "bottom"])(+ "should show a %s legend on a wide card whose grid fits a row where the automatic layout hides it",+ (position) => {+ const input = {+ ...defaultInput,+ width: 200,+ height: 150,+ gridSize: { width: 6, height: 4 },+ };++ expect(getChartLayout(input).type).toBe("small");+ expect(getChartLayout({ ...input, position })).toMatchObject({+ type: "vertical",+ LegendComponent: LegendHorizontal,+ });+ },+ );++ it.each<LegendPosition>(["left", "right"])(+ "should hide a %s legend when the card is too narrow for a column",+ (position) => {+ const layout = getChartLayout({+ ...defaultInput,+ position,+ width: HIDE_HORIZONTAL_LEGEND_THRESHOLD,+ height: 600,+ gridSize: { width: 6, height: 8 },+ });++ expect(layout).toMatchObject({+ type: "small",+ LegendComponent: undefined,+ });+ },+ );++ it.each<LegendPosition>(["top", "bottom"])(+ "should hide a %s legend when the grid is too short for a row",+ (position) => {+ const layout = getChartLayout({+ ...defaultInput,+ position,+ gridSize: { width: 8, height: 3 },+ });++ expect(layout).toMatchObject({+ type: "small",+ LegendComponent: undefined,+ });+ },+ );++ it.each<LegendPosition>(["top", "bottom", "left", "right"])(+ "should hide a %s legend on a card too small for any legend",+ (position) => {+ const layout = getChartLayout({+ ...defaultInput,+ position,+ width: 200,+ height: 100,+ });++ expect(layout).toMatchObject({+ type: "small",+ LegendComponent: undefined,+ });+ },+ );+});diff --git a/frontend/src/metabase/visualizations/components/legend/Legend.module.css b/frontend/src/metabase/visualizations/components/legend/Legend.module.cssindex 6d2ff601d61..60106ed5686 100644--- a/frontend/src/metabase/visualizations/components/legend/Legend.module.css+++ b/frontend/src/metabase/visualizations/components/legend/Legend.module.css@@ -1,3 +1,7 @@+.pinnedRowItem {+ flex-shrink: 0;+}+.popoverScroll {overflow-x: hidden;}diff --git a/frontend/src/metabase/visualizations/components/legend/Legend.tsx b/frontend/src/metabase/visualizations/components/legend/Legend.tsxindex c7222a872c0..f265a0c8dcb 100644--- a/frontend/src/metabase/visualizations/components/legend/Legend.tsx+++ b/frontend/src/metabase/visualizations/components/legend/Legend.tsx@@ -8,12 +8,9 @@ import type { HoveredObject } from "metabase/viz-core";import S from "./Legend.module.css";import type { LegendItemData } from "./LegendItem";import { LegendItem } from "./LegendItem";-import {- LEGEND_PADDING,- LEGEND_SIZES,- type LegendSize,- getOverflowLabel,-} from "./layout";+import { LEGEND_PADDING } from "./constants";+import { getOverflowLabel } from "./measure";+import { LEGEND_SIZES, type LegendSize } from "./sizes";const POPOVER_BORDER = 1;const POPOVER_PADDING = 8;@@ -57,6 +54,8 @@ export const Legend = ({const overflowIndex = visibleIndex + visibleLength;const visibleItems = items.slice(visibleIndex, overflowIndex);const overflowLength = items.length - overflowIndex;+ const shouldPinRowItemWidths = !isVertical && overflowLength > 0;+ const lastVisibleIndex = visibleItems.length - 1;const { itemGap, rowGap, maxVerticalWidth, typography } = LEGEND_SIZES[size];return (@@ -79,6 +78,10 @@ export const Legend = ({return (<LegendItemkey={item.key}+ className={cx({+ [S.pinnedRowItem]:+ shouldPinRowItemWidths && index < lastVisibleIndex,+ })}item={item}index={itemIndex}isMuted={hovered != null && itemIndex !== hovered.index}@@ -119,7 +122,7 @@ export const Legend = ({hovered={hovered}visibleIndex={overflowIndex}visibleLength={overflowLength}- isVertical={isVertical}+ isVerticalsize={size}onHoverChange={onHoverChange}onSelectSeries={onSelectSeries}diff --git a/frontend/src/metabase/visualizations/components/legend/LegendItem.tsx b/frontend/src/metabase/visualizations/components/legend/LegendItem.tsxindex f7f68ebb283..545a4d56cfb 100644--- a/frontend/src/metabase/visualizations/components/legend/LegendItem.tsx+++ b/frontend/src/metabase/visualizations/components/legend/LegendItem.tsx@@ -8,7 +8,7 @@ import * as Urls from "metabase/urls";import S from "./LegendItem.module.css";import { LegendItemDot } from "./LegendItemDot";-import { LEGEND_SIZES, type LegendSize } from "./layout";+import { LEGEND_SIZES, type LegendSize } from "./sizes";// Before the real URL is computed, a non-empty href keeps the title a// focusable link, so focusing it can trigger that computation.@@ -22,6 +22,7 @@ export interface LegendItemData {}interface LegendItemProps {+ className?: string;item: LegendItemData;size?: LegendSize;index: number;@@ -38,6 +39,7 @@ interface LegendItemProps {}const LegendItemInner = ({+ className,item,size = "sm",index,@@ -86,7 +88,7 @@ const LegendItemInner = ({return (<Flex- className={S.root}+ className={cx(S.root, className)}align="center"miw={0}opacity={isMuted ? 0.4 : 1}diff --git a/frontend/src/metabase/visualizations/components/legend/LegendLayout.stories.tsx b/frontend/src/metabase/visualizations/components/legend/LegendLayout.stories.tsxindex ce581f70489..16b60ccc9be 100644--- a/frontend/src/metabase/visualizations/components/legend/LegendLayout.stories.tsx+++ b/frontend/src/metabase/visualizations/components/legend/LegendLayout.stories.tsx@@ -5,7 +5,7 @@ import { measureTextWidth } from "metabase/utils/measure-text";import type { LegendItemData } from "./LegendItem";import { LegendLayout } from "./LegendLayout";-import { MIN_LEGEND_CARD_HEIGHT, MIN_LEGEND_CARD_WIDTH } from "./layout";+import { MIN_LEGEND_CARD_WIDTH } from "./layout";export default {title: "viz/Legend/LegendLayout",@@ -38,10 +38,6 @@ interface CardProps {alwaysVisible?: boolean;}-// vertical padding of the card wrapper below; real charts measure their-// viewport, so the stories pass the equivalent height for exact row fitting-const CARD_VERTICAL_PADDING = 16;-const Card = ({names,width,@@ -61,7 +57,6 @@ const Card = ({hasLegendwidth={width}height={height}- chartHeight={height - CARD_VERTICAL_PADDING}isQueryBuilder={isQueryBuilder}alwaysVisible={alwaysVisible}fontFamily="Lato"@@ -86,20 +81,14 @@ export const Horizontal: StoryObj = {render: () => <Card names={SHORT_NAMES} width={600} height={300} />,};-// the smallest card that still shows a legend (the unit tests cover the-// exact 420x200 boundary)-export const MinimumCardSize: StoryObj = {- render: () => (- <Card- names={SHORT_NAMES}- width={MIN_LEGEND_CARD_WIDTH}- height={MIN_LEGEND_CARD_HEIGHT}- />- ),+// a short card keeps a complete row while the row leaves the plot most of its height+export const ShortCard: StoryObj = {+ render: () => <Card names={SHORT_NAMES} width={300} height={120} />,};-export const HiddenOnSmallCard: StoryObj = {- render: () => <Card names={SHORT_NAMES} width={360} height={180} />,+// the plot would be narrower than 150px+export const HiddenOnNarrowCard: StoryObj = {+ render: () => <Card names={SHORT_NAMES} width={140} height={180} />,};export const Vertical: StoryObj = {@@ -122,11 +111,18 @@ export const VerticalTruncated: StoryObj = {),};-// more than half of the names are truncated, so the legend is dropped-export const HiddenWhenMostlyTruncated: StoryObj = {+export const VerticalMostlyTruncated: StoryObj = {render: () => <Card names={LONG_NAMES} width={600} height={300} />,};+// below this width a column with most names truncated is dropped, and a row+// fits only one item+export const HiddenWhenMostlyTruncated: StoryObj = {+ render: () => (+ <Card names={LONG_NAMES} width={MIN_LEGEND_CARD_WIDTH - 20} height={300} />+ ),+};+export const LargeCardHorizontal: StoryObj = {render: () => <Card names={SHORT_NAMES} width={700} height={420} />,};diff --git a/frontend/src/metabase/visualizations/components/legend/LegendLayout.tsx b/frontend/src/metabase/visualizations/components/legend/LegendLayout.tsxindex 88753390c7c..2bced45f21e 100644--- a/frontend/src/metabase/visualizations/components/legend/LegendLayout.tsx+++ b/frontend/src/metabase/visualizations/components/legend/LegendLayout.tsx@@ -1,16 +1,33 @@import cx from "classnames";-import { type ReactNode, useMemo } from "react";+import {+ type ReactNode,+ useLayoutEffect,+ useMemo,+ useRef,+ useState,+} from "react";+import _ from "underscore";import CS from "metabase/css/core/index.css";import { Box, Flex } from "metabase/ui";import type { TextWidthMeasurer } from "metabase/utils/measure-text";import type { HoveredObject } from "metabase/viz-core";+import type { LegendPosition } from "metabase-types/api";import { Legend } from "./Legend";import { LegendActions } from "./LegendActions";import type { LegendItemData } from "./LegendItem";import S from "./LegendLayout.module.css";-import { LEGEND_SIZES, getLegendLayout, getLegendSize } from "./layout";+import { LEGEND_COLUMN_GAP, LEGEND_COLUMN_MARGIN_TOP } from "./constants";+import { HIDDEN_LEGEND_LAYOUT, getLegendLayout } from "./layout";+import { measureLegend } from "./measure";+import {+ type ChartSize,+ type LegendChart,+ getLegendPlots,+ getPlotsWithoutAxes,+} from "./plots";+import { LEGEND_SIZES, getLegendSize } from "./sizes";interface LegendLayoutProps {className?: string;@@ -18,9 +35,9 @@ interface LegendLayoutProps {hovered?: HoveredObject | null;width?: number;height?: number;- chartHeight?: number;- indent?: number;+ chart?: LegendChart;hasLegend: boolean;+ legendPosition?: LegendPosition;alwaysVisible?: boolean;actionButtons?: ReactNode;isFullscreen?: boolean;@@ -51,9 +68,9 @@ export const LegendLayout = ({hovered,width = 0,height = 0,- chartHeight,- indent = 0,+ chart,hasLegend,+ legendPosition = "auto",alwaysVisible,actionButtons,isFullscreen,@@ -68,36 +85,60 @@ export const LegendLayout = ({isReversed,}: LegendLayoutProps) => {const hasDimensions = width > 0 && height > 0;+ const canShowLegend = hasDimensions && hasLegend && legendPosition !== "off";const size = getLegendSize({ width, height, isQueryBuilder, isFullscreen });+ const { rootRef, chartAreaRef, chartRoom } = useChartRoom(width, height);- const layout = useMemo(+ const metrics = useMemo(() =>- getLegendLayout({- items,- width,- height,- chartHeight,- horizontalWidth: width - Math.abs(indent),- size,- fontFamily,- measureText,- alwaysVisible,- }),+ canShowLegend+ ? measureLegend({+ items,+ width,+ height,+ chartRoom,+ size,+ fontFamily,+ measureText,+ isReversed,+ })+ : null,[+ canShowLegend,items,width,height,- chartHeight,- indent,+ chartRoom,size,fontFamily,measureText,- alwaysVisible,+ isReversed,],);- const isVisible = hasDimensions && hasLegend && layout.type !== "hidden";- const { horizontalGap, verticalGap } = LEGEND_SIZES[size];+ const plots = useMemo(() => {+ if (metrics == null) {+ return null;+ }+ return chart+ ? getLegendPlots(chart, metrics.chartSizes)+ : getPlotsWithoutAxes(metrics.chartSizes);+ }, [metrics, chart]);++ const layout = useMemo(+ () =>+ metrics && plots+ ? getLegendLayout(metrics, {+ position: legendPosition,+ plots,+ alwaysVisible,+ })+ : HIDDEN_LEGEND_LAYOUT,+ [metrics, plots, legendPosition, alwaysVisible],+ );++ const isLegendBeforeChart = layout.type !== "hidden" && layout.isBeforeChart;+ const { rowChartGap } = LEGEND_SIZES[size];const legendProps = {items,@@ -110,45 +151,82 @@ export const LegendLayout = ({isReversed,};+ const horizontalLegend = layout.type === "horizontal" && (+ <Flex+ justify="center"+ flex="0 0 auto"+ miw={0}+ mt={isLegendBeforeChart ? 0 : rowChartGap}+ mb={isLegendBeforeChart ? rowChartGap : 0}+ ml={Math.max(layout.indent, 0)}+ mr={Math.max(-layout.indent, 0)}+ data-testid="legend-horizontal"+ >+ <Legend {...legendProps} visibleLength={layout.visibleCount} />+ </Flex>+ );++ const verticalLegend = layout.type === "vertical" && (+ <Box+ className={cx(S.verticalLegend, CS.overflowHidden)}+ flex="0 0 auto"+ miw={0}+ mt={LEGEND_COLUMN_MARGIN_TOP}+ ml={isLegendBeforeChart ? 0 : LEGEND_COLUMN_GAP}+ mr={isLegendBeforeChart ? LEGEND_COLUMN_GAP : 0}+ style={{ width: layout.width }}+ data-testid="legend-vertical"+ >+ <Legend {...legendProps} visibleLength={layout.visibleCount} isVertical />+ </Box>+ );+return (- <Flex className={className} flex="1 1 auto" miw={0} mih={0}>+ <Flex ref={rootRef} className={className} flex="1 1 auto" miw={0} mih={0}>+ {isLegendBeforeChart && verticalLegend}<Flex direction="column" flex="1 1 auto" miw={0} mih={0}>{actionButtons && <LegendActions>{actionButtons}</LegendActions>}- {hasDimensions && (- <Flex direction="column" flex="1 0 auto" mih={0}>- {children}- </Flex>- )}- {isVisible && layout.type === "horizontal" && (- <Flex- justify="center"- flex="0 0 auto"- miw={0}- mt={horizontalGap}- ml={Math.max(indent, 0)}- mr={Math.max(-indent, 0)}- data-testid="legend-horizontal"- >- <Legend {...legendProps} />- </Flex>- )}- </Flex>- {isVisible && layout.type === "vertical" && (- <Box- className={cx(S.verticalLegend, CS.overflowHidden)}- flex="0 0 auto"+ <Flex+ ref={chartAreaRef}+ direction="column"+ flex="1 1 auto"miw={0}- ml={verticalGap}- style={{ width: layout.width }}- data-testid="legend-vertical"+ mih={0}>- <Legend- {...legendProps}- visibleLength={layout.visibleCount}- isVertical- />- </Box>- )}+ {isLegendBeforeChart && horizontalLegend}+ {hasDimensions && (+ <Flex direction="column" flex="1 0 auto" mih={0}>+ {children}+ </Flex>+ )}+ {!isLegendBeforeChart && horizontalLegend}+ </Flex>+ </Flex>+ {!isLegendBeforeChart && verticalLegend}</Flex>);};++// The legend root keeps its width and the chart area its height whichever+// legend shows, so the layout can depend on them without feeding back. They+// are measured when the card size props change, so a render the chart's own+// resize triggers before those props catch up keeps the room that matches them.+function useChartRoom(width: number, height: number) {+ const rootRef = useRef<HTMLDivElement>(null);+ const chartAreaRef = useRef<HTMLDivElement>(null);+ const [chartRoom, setChartRoom] = useState<ChartSize>();++ useLayoutEffect(() => {+ const roomWidth = rootRef.current?.clientWidth ?? 0;+ const roomHeight = chartAreaRef.current?.clientHeight ?? 0;+ const measuredRoom =+ roomWidth > 0 && roomHeight > 0+ ? { width: roomWidth, height: roomHeight }+ : undefined;+ setChartRoom((room) =>+ _.isEqual(room, measuredRoom) ? room : measuredRoom,+ );+ }, [width, height]);++ return { rootRef, chartAreaRef, chartRoom };+}diff --git a/frontend/src/metabase/visualizations/components/legend/LegendLayout.unit.spec.tsx b/frontend/src/metabase/visualizations/components/legend/LegendLayout.unit.spec.tsxindex bd8e59af795..1a19b298bfc 100644--- a/frontend/src/metabase/visualizations/components/legend/LegendLayout.unit.spec.tsx+++ b/frontend/src/metabase/visualizations/components/legend/LegendLayout.unit.spec.tsx@@ -1,36 +1,46 @@import userEvent from "@testing-library/user-event";import { render, screen, within } from "__support__/ui";+import { rem } from "metabase/ui";+import type { TextWidthMeasurer } from "metabase/utils/measure-text";+import type { LegendPosition } from "metabase-types/api";import type { LegendItemData } from "./LegendItem";import { LegendLayout } from "./LegendLayout";+import { LEGEND_COLUMN_MARGIN_TOP } from "./constants";+import { MIN_LEGEND_CARD_WIDTH } from "./layout";const CHAR_WIDTH = 6;-const measureText = (text: string) => text.length * CHAR_WIDTH;+const measureTextByLength = (text: string) => text.length * CHAR_WIDTH;const createItems = (names: string[]): LegendItemData[] =>names.map((name) => ({ key: name, name, color: "red" }));interface SetupOpts {names: string[];+ legendPosition?: LegendPosition;width?: number;height?: number;isQueryBuilder?: boolean;actionButtons?: React.ReactNode;+ measureText?: TextWidthMeasurer;}const setup = ({names,+ legendPosition,width = 600,height = 300,isQueryBuilder,actionButtons,+ measureText = measureTextByLength,}: SetupOpts) => {render(<LegendLayoutitems={createItems(names)}hasLegend+ legendPosition={legendPosition}width={width}height={height}isQueryBuilder={isQueryBuilder}@@ -43,12 +53,37 @@ const setup = ({);};+const MOSTLY_TRUNCATED_NAMES = [+ "a".repeat(40),+ "b".repeat(40),+ "c".repeat(40),+ "d",+];++const expectNoLegend = () => {+ expect(screen.getByTestId("chart")).toBeInTheDocument();+ expect(screen.queryByLabelText("Legend")).not.toBeInTheDocument();+};++const isBefore = (element: Element, other: Element) =>+ Boolean(+ element.compareDocumentPosition(other) & Node.DOCUMENT_POSITION_FOLLOWING,+ );+describe("LegendLayout", () => {- it("should render the chart without a legend on cards smaller than the minimum size", () => {- setup({ names: ["a", "b"], width: 400, height: 150 });+ it("should render the chart without a legend when the plot would be under 150px wide", () => {+ setup({ names: ["a", "b"], width: 149 });++ expectNoLegend();+ });++ it("should render a vertical legend on a wide short card", () => {+ // row plot 900 x 70.2, column plot 822 x 100: 70.2 < 100 * 75%+ setup({ names: ["first", "second"], width: 900, height: 116 });- expect(screen.getByTestId("chart")).toBeInTheDocument();- expect(screen.queryByLabelText("Legend")).not.toBeInTheDocument();+ const legend = screen.getByTestId("legend-vertical");+ expect(within(legend).getAllByTestId("legend-item")).toHaveLength(2);+ expect(screen.queryByTestId("legend-horizontal")).not.toBeInTheDocument();});it("should render a horizontal legend below the chart when the items fit", () => {@@ -57,10 +92,7 @@ describe("LegendLayout", () => {const legend = screen.getByTestId("legend-horizontal");expect(within(legend).getAllByTestId("legend-item")).toHaveLength(2);expect(screen.queryByTestId("legend-vertical")).not.toBeInTheDocument();- expect(- screen.getByTestId("chart").compareDocumentPosition(legend) &- Node.DOCUMENT_POSITION_FOLLOWING,- ).toBeTruthy();+ expect(isBefore(screen.getByTestId("chart"), legend)).toBe(true);});it("should render a vertical legend next to the chart when the items overflow the row", () => {@@ -87,11 +119,17 @@ describe("LegendLayout", () => {expect(within(popover).getByText("series 19")).toBeInTheDocument();});- it("should hide the legend when more than half of the items would be truncated", () => {- setup({ names: ["a".repeat(40), "b".repeat(40), "c".repeat(40), "d"] });+ it("should render a column with most items truncated on cards at least 420px wide", () => {+ setup({ names: MOSTLY_TRUNCATED_NAMES, width: MIN_LEGEND_CARD_WIDTH });++ const legend = screen.getByTestId("legend-vertical");+ expect(within(legend).getAllByTestId("legend-item")).toHaveLength(4);+ });++ it("should hide a column with most items truncated on narrower cards", () => {+ setup({ names: MOSTLY_TRUNCATED_NAMES, width: MIN_LEGEND_CARD_WIDTH - 1 });- expect(screen.getByTestId("chart")).toBeInTheDocument();- expect(screen.queryByLabelText("Legend")).not.toBeInTheDocument();+ expectNoLegend();});it("should keep the action buttons above the chart", () => {@@ -101,10 +139,122 @@ describe("LegendLayout", () => {});expect(- screen- .getByText("action")- .compareDocumentPosition(screen.getByTestId("chart")) &- Node.DOCUMENT_POSITION_FOLLOWING,- ).toBeTruthy();+ isBefore(screen.getByText("action"), screen.getByTestId("chart")),+ ).toBe(true);+ });+});++describe("LegendLayout with an explicit position", () => {+ it("should render no legend when the position is off", () => {+ setup({ names: ["first", "second"], legendPosition: "off" });++ expectNoLegend();+ });++ it("should not measure the legend labels when the position is off", () => {+ const measureText = jest.fn(measureTextByLength);+ setup({ names: ["first", "second"], legendPosition: "off", measureText });++ expect(measureText).not.toHaveBeenCalled();+ });++ it("should render a bottom legend on a short card", () => {+ setup({+ names: ["first", "second"],+ legendPosition: "bottom",+ width: 300,+ height: 60,+ });++ expect(screen.getByTestId("legend-horizontal")).toBeInTheDocument();+ });++ it("should hide a bottom legend when the plot would be under 150px wide", () => {+ setup({+ names: ["first", "second"],+ legendPosition: "bottom",+ width: 149,+ });++ expectNoLegend();+ });++ it("should render a left column with most items truncated", () => {+ setup({+ names: MOSTLY_TRUNCATED_NAMES,+ legendPosition: "left",+ width: MIN_LEGEND_CARD_WIDTH - 1,+ });++ expect(screen.getByTestId("legend-vertical")).toBeInTheDocument();+ });++ it.each<{+ legendPosition: LegendPosition;+ testId: string;+ isLegendFirst: boolean;+ }>([+ { legendPosition: "top", testId: "legend-horizontal", isLegendFirst: true },+ {+ legendPosition: "bottom",+ testId: "legend-horizontal",+ isLegendFirst: false,+ },+ { legendPosition: "left", testId: "legend-vertical", isLegendFirst: true },+ {+ legendPosition: "right",+ testId: "legend-vertical",+ isLegendFirst: false,+ },+ ])(+ "should render a $legendPosition legend on that side of the chart",+ ({ legendPosition, testId, isLegendFirst }) => {+ setup({ names: ["first", "second"], legendPosition });++ const legend = screen.getByTestId(testId);+ expect(within(legend).getAllByTestId("legend-item")).toHaveLength(2);+ expect(isBefore(legend, screen.getByTestId("chart"))).toBe(isLegendFirst);+ },+ );++ it.each<LegendPosition>(["left", "right"])(+ "should start a %s legend level with the top of the plot",+ (legendPosition) => {+ setup({ names: ["first", "second"], legendPosition });++ expect(screen.getByTestId("legend-vertical")).toHaveStyle({+ marginTop: rem(LEGEND_COLUMN_MARGIN_TOP),+ });+ },+ );++ it("should keep the action buttons above a top legend", () => {+ setup({+ names: ["first", "second"],+ legendPosition: "top",+ actionButtons: <button>action</button>,+ });++ expect(+ isBefore(+ screen.getByText("action"),+ screen.getByTestId("legend-horizontal"),+ ),+ ).toBe(true);+ });++ it("should show what fits in a top row and list the rest behind '+ N more'", async () => {+ const names = Array.from({ length: 10 }, (_, i) => `series ${i}`);+ setup({ names, legendPosition: "top", width: 420 });++ const legend = screen.getByTestId("legend-horizontal");+ expect(within(legend).getAllByTestId("legend-item")).toHaveLength(4);+ expect(screen.queryByTestId("legend-vertical")).not.toBeInTheDocument();++ await userEvent.click(within(legend).getByText("+ 6 more"));++ const popover = await screen.findByRole("dialog");+ expect(within(popover).getAllByTestId("legend-item")).toHaveLength(6);+ expect(within(popover).getByText("series 9")).toBeInTheDocument();});});diff --git a/frontend/src/metabase/visualizations/components/legend/constants.ts b/frontend/src/metabase/visualizations/components/legend/constants.tsindex af3070c9bdb..01b8c0c9add 100644--- a/frontend/src/metabase/visualizations/components/legend/constants.ts+++ b/frontend/src/metabase/visualizations/components/legend/constants.ts@@ -1,3 +1,12 @@+import { CHART_STYLE } from "metabase/viz-core";+// DashCardVisualization measures the caption title with these, so they must match how LegendCaption renders itexport const LEGEND_LABEL_FONT_SIZE = "0.875rem";export const LEGEND_LABEL_FONT_WEIGHT = 700;+// room for the focus outline of the legend items+export const LEGEND_PADDING = 2;+export const MIN_VISIBLE_COUNT = 1;+// the horizontal space between a left or right legend and the chart+export const LEGEND_COLUMN_GAP = 24;+// a column's first item lines up with the top of a plot without value labels+export const LEGEND_COLUMN_MARGIN_TOP = CHART_STYLE.padding.y - LEGEND_PADDING;diff --git a/frontend/src/metabase/visualizations/components/legend/layout.ts b/frontend/src/metabase/visualizations/components/legend/layout.tsindex 586e6200bc4..13e95575bae 100644--- a/frontend/src/metabase/visualizations/components/legend/layout.ts+++ b/frontend/src/metabase/visualizations/components/legend/layout.ts@@ -1,200 +1,224 @@-import { c } from "ttag";--import type { TextWidthMeasurer } from "metabase/utils/measure-text";--import type { LegendItemData } from "./LegendItem";--export type LegendSize = "sm" | "lg" | "md";--interface LegendSizeConfig {- typography: "sm" | "md";- fontSize: number;- lineHeight: number;- dotSize: number;- dotGap: number;- itemGap: number;- rowGap: number;- horizontalGap: number;- verticalGap: number;- maxVerticalWidth: number;- horizontalPadding: number;- verticalPadding: number;-}+import _ from "underscore";-export const LEGEND_SIZES = {- sm: {- typography: "sm",- fontSize: 12,- lineHeight: 1.15,- dotSize: 8,- dotGap: 6,- itemGap: 12,- rowGap: 8,- horizontalGap: 12,- verticalGap: 24,- maxVerticalWidth: 200,- horizontalPadding: 32,- verticalPadding: 16,- },- lg: {- typography: "sm",- fontSize: 12,- lineHeight: 1.15,- dotSize: 8,- dotGap: 6,- itemGap: 12,- rowGap: 12,- horizontalGap: 16,- verticalGap: 40,- maxVerticalWidth: 200,- horizontalPadding: 80,- verticalPadding: 76,- },- md: {- typography: "md",- fontSize: 14,- lineHeight: 1.22,- dotSize: 14,- dotGap: 8,- itemGap: 16,- rowGap: 16,- horizontalGap: 24,- verticalGap: 64,- maxVerticalWidth: 256,- horizontalPadding: 48,- verticalPadding: 32,- },-} as const satisfies Record<LegendSize, LegendSizeConfig>;--// mirrors the large card tier in visualizations/CartesianChart/sizing.ts-const LARGE_CARD_MIN_WIDTH = 640;-const LARGE_CARD_MIN_HEIGHT = 360;--interface GetLegendSizeOptions {- width: number;- height: number;- isQueryBuilder?: boolean;- isFullscreen?: boolean;-}+import type { LegendPosition } from "metabase-types/api";++import { LEGEND_PADDING, MIN_VISIBLE_COUNT } from "./constants";+import { type LegendMetrics, getRowWidth } from "./measure";+import { LEGEND_PLACEMENTS } from "./placement";+import type { ChartSize, LegendCandidates, Plot } from "./plots";-export const getLegendSize = ({- width,- height,- isQueryBuilder,- isFullscreen,-}: GetLegendSizeOptions): LegendSize => {- if (isQueryBuilder || isFullscreen) {- return "md";- }- return width >= LARGE_CARD_MIN_WIDTH && height >= LARGE_CARD_MIN_HEIGHT- ? "lg"- : "sm";-};--export const LEGEND_FONT_WEIGHT = 400;-// room for the focus outline of the legend items-export const LEGEND_PADDING = 2;export const MIN_LEGEND_CARD_WIDTH = 420;-export const MIN_LEGEND_CARD_HEIGHT = 200;-const MAX_VERTICAL_WIDTH_RATIO = 0.25;-const MAX_TRUNCATED_ITEMS_RATIO = 0.5;+const AUTO_MIN_VISIBLE_COUNT = 2;+// the plot is the chart without its axes, as in PLOT_HEIGHT_BREAKPOINTS+const MIN_PLOT_WIDTH = 150;+// A plot wider than this many times its height gains little from more width,+// so Auto measures a plot by the height it can use.+const PLOT_ASPECT_RATIO = 3;+// Auto keeps a bottom row unless a column leaves the plot a third more height.+const MIN_AUTO_ROW_TO_COLUMN_PLOT_RATIO = 0.75;+// Auto hides a legend that leaves the plot under this share of the bare chart's.+const MIN_AUTO_LEGEND_PLOT_RATIO = 0.6;+const MIN_COLUMN_CARD_HEIGHT = 100;+export type LegendLayoutResult =| { type: "hidden" }- | { type: "horizontal" }- | { type: "vertical"; width: number; visibleCount: number };+ | {+ type: "horizontal";+ isBeforeChart: boolean;+ // the plot's indent, which the row lines up with, or 0 for a full-width row+ indent: number;+ visibleCount: number;+ }+ | {+ type: "vertical";+ isBeforeChart: boolean;+ width: number;+ visibleCount: number;+ };++export const HIDDEN_LEGEND_LAYOUT: LegendLayoutResult = { type: "hidden" };interface GetLegendLayoutOptions {- items: LegendItemData[];- width: number;- height: number;- chartHeight?: number;- horizontalWidth?: number;- size: LegendSize;- fontFamily: string;- measureText: TextWidthMeasurer;+ position: LegendPosition;+ plots: LegendCandidates<Plot>;alwaysVisible?: boolean;}-export const getOverflowLabel = (count: number) =>- c("{0} is the number of hidden legend items").t`+ ${count} more`;--export function getLegendLayout({- items,- width,- height,- chartHeight,- horizontalWidth = width,- size,- fontFamily,- measureText,- alwaysVisible = false,-}: GetLegendLayoutOptions): LegendLayoutResult {- const isCardTooSmall =- width < MIN_LEGEND_CARD_WIDTH || height < MIN_LEGEND_CARD_HEIGHT;- if (items.length === 0 || (isCardTooSmall && !alwaysVisible)) {- return { type: "hidden" };+export function getLegendLayout(+ metrics: LegendMetrics,+ { position, plots, alwaysVisible = false }: GetLegendLayoutOptions,+): LegendLayoutResult {+ if (metrics.itemWidths.length === 0 || position === "off") {+ return HIDDEN_LEGEND_LAYOUT;+ }+ if (position === "auto") {+ return getAutoLayout(metrics, plots, alwaysVisible);}+ const { orientation, isBeforeChart } = LEGEND_PLACEMENTS[position];+ const fit = {+ isBeforeChart,+ minVisibleCount: MIN_VISIBLE_COUNT,+ alwaysVisible,+ };+ return orientation === "horizontal"+ ? getRowLayout(metrics, plots.row, fit)+ : getColumnLayout(metrics, plots.column, {+ ...fit,+ allowMostlyTruncated: true,+ });+}- const config = LEGEND_SIZES[size];- const font = {- size: config.fontSize,- weight: LEGEND_FONT_WEIGHT,- family: fontFamily,+/**+ * Auto weighs each legend by the plot it leaves. A complete row below the+ * chart wins unless a right column leaves the plot clearly more usable height,+ * as on wide short cards. A partial row with "+ N more" comes last.+ *+ * A legend that hides x-axis labels the bare chart shows, or leaves the plot+ * under MIN_AUTO_LEGEND_PLOT_RATIO of its bare height, is not an option. A+ * column with most labels truncated needs a card MIN_LEGEND_CARD_WIDTH wide.+ */+function getAutoLayout(+ metrics: LegendMetrics,+ plots: LegendCandidates<Plot>,+ alwaysVisible: boolean,+): LegendLayoutResult {+ const itemCount = metrics.itemWidths.length;+ const fit = {+ isBeforeChart: false,+ minVisibleCount: alwaysVisible ? MIN_VISIBLE_COUNT : AUTO_MIN_VISIBLE_COUNT,+ alwaysVisible,};- const labelWidths = items.map((item) => measureText(item.name, font));- const itemWidths = labelWidths.map(- (labelWidth) => config.dotSize + config.dotGap + labelWidth,- );+ const row = getRowLayout(metrics, plots.row, fit);+ const column = getColumnLayout(metrics, plots.column, {+ ...fit,+ allowMostlyTruncated:+ alwaysVisible || metrics.width >= MIN_LEGEND_CARD_WIDTH,+ });+ const isRowComplete = row.type !== "hidden" && row.visibleCount === itemCount;+ if (alwaysVisible) {+ return isRowComplete || column.type === "hidden" ? row : column;+ }- const availableWidth = width - config.horizontalPadding;- const availableHorizontalWidth = Math.min(- availableWidth,- horizontalWidth - LEGEND_PADDING * 2,- );- const itemsWidth =- itemWidths.reduce((total, width) => total + width, 0) +- config.itemGap * (items.length - 1);- if (itemsWidth <= availableHorizontalWidth) {- return { type: "horizontal" };+ const rowHeight =+ row.type === "hidden" ? null : getAutoPlotHeight(plots.row, plots.none);+ const columnHeight =+ column.type === "hidden"+ ? null+ : getAutoPlotHeight(plots.column, plots.none);+ if (rowHeight === null) {+ return columnHeight === null ? HIDDEN_LEGEND_LAYOUT : column;}+ if (columnHeight === null) {+ return row;+ }+ const isRowPreferred =+ isRowComplete &&+ rowHeight >= columnHeight * MIN_AUTO_ROW_TO_COLUMN_PLOT_RATIO;+ return isRowPreferred ? row : column;+}- const legendWidth = Math.min(- Math.max(...itemWidths),- availableWidth * MAX_VERTICAL_WIDTH_RATIO,- config.maxVerticalWidth,- );- const labelWidth = legendWidth - (config.dotSize + config.dotGap);- const truncatedCount = labelWidths.filter((w) => w > labelWidth).length;- const isMostlyTruncated =- truncatedCount > items.length * MAX_TRUNCATED_ITEMS_RATIO;- if (isMostlyTruncated && !alwaysVisible) {- return { type: "hidden" };+const getUsablePlotHeight = ({ width, height }: ChartSize) =>+ Math.max(Math.min(height, width / PLOT_ASPECT_RATIO), 0);++// the usable plot height a legend leaves, or null when Auto must not show it+function getAutoPlotHeight(plot: Plot, barePlot: Plot): number | null {+ const keepsXAxisLabels = plot.hasXAxisLabels || !barePlot.hasXAxisLabels;+ const plotHeight = getUsablePlotHeight(plot);+ const isWorthShowing =+ keepsXAxisLabels &&+ plotHeight >= getUsablePlotHeight(barePlot) * MIN_AUTO_LEGEND_PLOT_RATIO;+ return isWorthShowing ? plotHeight : null;+}++interface LegendFit {+ isBeforeChart: boolean;+ minVisibleCount: number;+ alwaysVisible: boolean;+}++function getRowLayout(+ metrics: LegendMetrics,+ plot: Plot,+ { isBeforeChart, minVisibleCount, alwaysVisible }: LegendFit,+): LegendLayoutResult {+ const { config, itemWidths, availableWidth } = metrics;+ if (plot.width < MIN_PLOT_WIDTH && !alwaysVisible) {+ return HIDDEN_LEGEND_LAYOUT;}+ const rowWidthInsideIndent =+ availableWidth - Math.abs(plot.indent) - LEGEND_PADDING * 2;+ const visibleCount = getRowVisibleCount(metrics, rowWidthInsideIndent);+ // a row that only fits across the y-axis indent starts at the card edge, as on x.64+ const isIndented =+ visibleCount === itemWidths.length ||+ getRowWidth(itemWidths, config) > availableWidth - LEGEND_PADDING * 2;+ if (+ isIndented &&+ visibleCount < Math.min(minVisibleCount, itemWidths.length)+ ) {+ return HIDDEN_LEGEND_LAYOUT;+ }+ return {+ type: "horizontal",+ isBeforeChart,+ indent: isIndented ? plot.indent : 0,+ visibleCount: isIndented ? visibleCount : itemWidths.length,+ };+}- const availableHeight =- (chartHeight ?? height - config.verticalPadding) - LEGEND_PADDING * 2;- const rowPitch = config.fontSize * config.lineHeight + config.rowGap;- const maxRows = Math.floor((availableHeight + config.rowGap) / rowPitch);- // the last row is reserved for the "+ N more" label when items overflow- const visibleCount =- items.length <= maxRows- ? items.length- : Math.max(maxRows - 1, alwaysVisible ? 1 : 0);- if (visibleCount === 0) {- return { type: "hidden" };+function getRowVisibleCount(+ { itemWidths, config, measureOverflowLabel }: LegendMetrics,+ rowWidthInsideIndent: number,+): number {+ if (getRowWidth(itemWidths, config) <= rowWidthInsideIndent) {+ return itemWidths.length;}- const overflowCount = items.length - visibleCount;- const overflowLabelWidth =- overflowCount > 0 ? measureText(getOverflowLabel(overflowCount), font) : 0;- const columnWidth = Math.max(- legendWidth,- Math.min(overflowLabelWidth, config.maxVerticalWidth),+ const fitsWithOverflowLabel = (visibleCount: number) =>+ getRowWidth(itemWidths.slice(0, visibleCount), config) ++ config.itemGap ++ measureOverflowLabel(itemWidths.length - visibleCount) <=+ rowWidthInsideIndent;++ return (+ _.range(itemWidths.length - 1, MIN_VISIBLE_COUNT, -1).find(+ fitsWithOverflowLabel,+ ) ?? MIN_VISIBLE_COUNT);+}++function getColumnLayout(+ metrics: LegendMetrics,+ plot: Plot,+ {+ isBeforeChart,+ minVisibleCount,+ alwaysVisible,+ allowMostlyTruncated,+ }: LegendFit & { allowMostlyTruncated: boolean },+): LegendLayoutResult {+ const {+ height,+ itemWidths,+ columnFitCount,+ columnVisibleCount,+ columnWidth,+ } = metrics;+ const hasRoom =+ plot.width >= MIN_PLOT_WIDTH &&+ height >= MIN_COLUMN_CARD_HEIGHT &&+ columnFitCount >= Math.min(minVisibleCount, itemWidths.length);+ if (!alwaysVisible && !hasRoom) {+ return HIDDEN_LEGEND_LAYOUT;+ }+ if (!allowMostlyTruncated && metrics.isColumnMostlyTruncated) {+ return HIDDEN_LEGEND_LAYOUT;+ }return {type: "vertical",- width: Math.ceil(columnWidth) + LEGEND_PADDING * 2,- visibleCount,+ isBeforeChart,+ width: columnWidth,+ visibleCount: columnVisibleCount,};}diff --git a/frontend/src/metabase/visualizations/components/legend/layout.unit.spec.ts b/frontend/src/metabase/visualizations/components/legend/layout.unit.spec.tsindex d4249f7a2d0..00125a285b8 100644--- a/frontend/src/metabase/visualizations/components/legend/layout.unit.spec.ts+++ b/frontend/src/metabase/visualizations/components/legend/layout.unit.spec.ts@@ -1,87 +1,317 @@+import type { LegendPosition } from "metabase-types/api";+import type { LegendItemData } from "./LegendItem";import {+ LEGEND_COLUMN_GAP,+ LEGEND_COLUMN_MARGIN_TOP,LEGEND_PADDING,- LEGEND_SIZES,- type LegendSize,- getLegendLayout,- getLegendSize,-} from "./layout";+} from "./constants";+import { MIN_LEGEND_CARD_WIDTH, getLegendLayout } from "./layout";+import { measureLegend } from "./measure";+import { type ChartSize, mapLegendCandidates } from "./plots";+import { LEGEND_SIZES, type LegendSize } from "./sizes";const CHAR_WIDTH = 6;+const MIN_PLOT_WIDTH = 150;+const SM = LEGEND_SIZES.sm;+const ROW_HEIGHT =+ SM.fontSize * SM.lineHeight + SM.rowChartGap + LEGEND_PADDING * 2;const measureText = (text: string) => text.length * CHAR_WIDTH;const createItems = (names: string[]): LegendItemData[] =>names.map((name) => ({ key: name, name, color: "red" }));+const getItemWidth = (name: string) =>+ SM.dotSize + SM.dotGap + measureText(name);++const getRowWidth = (names: string[]) =>+ names.reduce((total, name) => total + getItemWidth(name), 0) ++ SM.itemGap * (names.length - 1);++// the smallest card whose row holds every item without the y-axis indent+const getCardWidthForRow = (names: string[]) =>+ SM.horizontalPadding + LEGEND_PADDING * 2 + getRowWidth(names);++const getColumnSpace = (columnItemWidth: number) =>+ columnItemWidth + LEGEND_PADDING * 2 + LEGEND_COLUMN_GAP;++const createSeriesNames = (count: number) =>+ Array.from({ length: count }, (_, i) => `series ${i}`);++// 3 of 4 labels are cut in any column narrower than 254px+const MOSTLY_TRUNCATED_NAMES = [+ "a".repeat(40),+ "b".repeat(40),+ "c".repeat(40),+ "d".repeat(10),+];++// 26px items, narrower than the column's "+ N more" label+const TWO_DIGIT_NAMES = Array.from({ length: 20 }, (_, i) =>+ `${i}`.padStart(2, "0"),+);++const SHORT_CARD = { width: 300, height: 60 };+interface LayoutOpts {+ position?: LegendPosition;width?: number;height?: number;+ chartAreaHeight?: number;size?: LegendSize;- horizontalWidth?: number;+ // the plot's y-axis indent at every size+ indent?: number;+ plotInset?: ChartSize;+ // the narrowest chart that still draws its x-axis labels+ minXAxisLabelsWidth?: number;+ alwaysVisible?: boolean;+ isReversed?: boolean;}const layout = (names: string[],- { width = 600, height = 300, size = "sm", horizontalWidth }: LayoutOpts = {},-) =>- getLegendLayout({+ {+ position = "auto",+ width = 600,+ height = 300,+ chartAreaHeight,+ size = "sm",+ indent = 0,+ plotInset = { width: 0, height: 0 },+ minXAxisLabelsWidth = 0,+ alwaysVisible,+ isReversed,+ }: LayoutOpts = {},+) => {+ const metrics = measureLegend({items: createItems(names),width,height,+ chartRoom:+ chartAreaHeight === undefined+ ? undefined+ : { width, height: chartAreaHeight },size,- horizontalWidth,fontFamily: "Lato",measureText,+ isReversed,});+ const plots = mapLegendCandidates(metrics.chartSizes, (chart) => ({+ width: chart.width - plotInset.width,+ height: chart.height - plotInset.height,+ hasXAxisLabels: chart.width >= minXAxisLabelsWidth,+ indent,+ }));+ return getLegendLayout(metrics, { position, plots, alwaysVisible });+};++const row = (+ visibleCount: number,+ { isBeforeChart = false, indent = 0 } = {},+) => ({+ type: "horizontal",+ isBeforeChart,+ indent,+ visibleCount,+});++const HIDDEN = { type: "hidden" };describe("getLegendLayout", () => {it("should hide the legend when there are no items", () => {- expect(layout([])).toEqual({ type: "hidden" });+ expect(layout([])).toEqual(HIDDEN);+ });++ it("should hide the legend when the position is off", () => {+ expect(layout(["a", "b"], { position: "off" })).toEqual(HIDDEN);+ });+});++describe("getLegendLayout auto", () => {+ it("should hide a row that leaves a short card's plot under 60% of its height", () => {+ // 300 x 44 plot, 14.2 under a row; no column under 100px+ expect(layout(["first", "second"], SHORT_CARD)).toEqual(HIDDEN);+ });++ describe("weighing a row against a column", () => {+ // the column takes "second" = 8 + 6 + 36 = 50px + 2 * 2 padding + 24 gap+ const plotInset = { width: 0, height: 20 };++ it("should move the legend to a right column on a wide short card", () => {+ // row plot 900 x 50.2, column plot 822 x 80: 50.2 < 80 * 75%+ expect(+ layout(["first", "second"], {+ width: 900,+ chartAreaHeight: 100,+ plotInset,+ }),+ ).toMatchObject({ type: "vertical", isBeforeChart: false });+ });++ it("should keep the row when the column leaves at most a third more height", () => {+ // row plot 900 x 150.2, column plot 822 x 180: 150.2 >= 180 * 75%+ expect(+ layout(["first", "second"], {+ width: 900,+ chartAreaHeight: 200,+ plotInset,+ }),+ ).toEqual(row(2));+ });++ it("should count only the height a narrow plot can use", () => {+ // column plot (259 - 78) x 97 uses 181 / 3 = 60.3, row plot 259 x 67.2 all of it+ expect(+ layout(["first", "second"], {+ width: 259,+ chartAreaHeight: 131,+ plotInset: { width: 0, height: 34 },+ }),+ ).toEqual(row(2));+ });});- it("should hide the legend on cards smaller than 420×200", () => {- expect(layout(["a", "b"], { width: 419, height: 300 })).toEqual({- type: "hidden",+ describe("when a column would hide the x-axis labels", () => {+ // the 8x4 card with 90-degree labels: bare plot 311 x 48+ const CRAMPED_CARD = {+ width: 311,+ chartAreaHeight: 131,+ plotInset: { width: 0, height: 83 },+ };++ it("should hide the legend when a row leaves the plot under 60% of its height", () => {+ // row plot 311 x 18.2 < 48 * 60%, column chart 233px wide+ expect(+ layout(["first", "second"], {+ ...CRAMPED_CARD,+ minXAxisLabelsWidth: 300,+ }),+ ).toEqual(HIDDEN);});- expect(layout(["a", "b"], { width: 600, height: 199 })).toEqual({- type: "hidden",++ it("should show the column when it keeps the labels", () => {+ expect(+ layout(["first", "second"], {+ ...CRAMPED_CARD,+ minXAxisLabelsWidth: 200,+ }),+ ).toMatchObject({ type: "vertical" });});- expect(layout(["a", "b"], { width: 420, height: 200 })).toEqual({- type: "horizontal",++ it("should not count labels the bare chart hides too", () => {+ expect(+ layout(["first", "second"], {+ ...CRAMPED_CARD,+ plotInset: { width: 0, height: 34 },+ minXAxisLabelsWidth: 1000,+ }),+ ).toEqual(row(2));});});- it("should lay items out horizontally when they fit in one row", () => {- // item = 8 + 6 + 5 * 6 = 44, two items + 12 gap = 100, card 420 - 32 = 388- expect(layout(["12345", "12345"], { width: 420 })).toEqual({- type: "horizontal",+ it("should size the chart beside each candidate", () => {+ const { chartSizes } = measureLegend({+ items: createItems(createSeriesNames(10)),+ width: 420,+ height: 300,+ chartRoom: { width: 420, height: 200 },+ size: "sm",+ fontFamily: "Lato",+ measureText,+ });++ expect(chartSizes).toEqual({+ none: { width: 420, height: 200 },+ row: { width: 420, height: 200 - ROW_HEIGHT },+ column: { width: 420 - getColumnSpace(62), height: 200 },});});- it("should switch to the vertical layout when the row overflows", () => {- const names = Array.from({ length: 10 }, (_, i) => `series ${i}`);+ it("should switch to a right column when the row overflows and the plot keeps 150px", () => {// item = 8 + 6 + 8 * 6 = 62, 10 items + 9 * 12 gap = 728 > 388- expect(layout(names, { width: 420, height: 400 })).toEqual({+ expect(layout(createSeriesNames(10), { width: 420, height: 400 })).toEqual({type: "vertical",- width: 66,+ isBeforeChart: false,+ width: 62 + LEGEND_PADDING * 2,visibleCount: 10,});});- it("should switch to the vertical layout when the items do not fit within the indented legend width", () => {+ describe("when a column would leave the plot under 150px", () => {+ // (200 - 32) * 25% = 42px column, 200 - 70 = 130 < 150+ const NARROW_CARD = { width: 200, height: 300 };++ it("should fall back to a partial bottom row with at least 2 items", () => {+ const names = Array.from({ length: 10 }, (_, i) => `s${i}`);+ // item = 8 + 6 + 2 * 6 = 26, 3 items + 2 gaps + 12 gap + "+ 7 more" 48 = 162 <= 164+ expect(layout(names, NARROW_CARD)).toEqual(row(3));+ });++ it("should hide the legend when the row fits only 1 item", () => {+ // item = 62, 2 items + gap + 12 gap + "+ 8 more" 48 = 196 > 164+ expect(layout(createSeriesNames(10), NARROW_CARD)).toEqual(HIDDEN);+ });+ });++ it("should show a column with most labels truncated on cards at least 420px wide", () => {+ // 25% of (420 - 32) = 97px column+ expect(+ layout(MOSTLY_TRUNCATED_NAMES, { width: MIN_LEGEND_CARD_WIDTH }),+ ).toEqual({+ type: "vertical",+ isBeforeChart: false,+ width: 97 + LEGEND_PADDING * 2,+ visibleCount: 4,+ });+ });++ it("should skip a column with most labels truncated on narrower cards", () => {+ // the row then fits one 254px item, under the 2 Auto needs+ expect(+ layout(MOSTLY_TRUNCATED_NAMES, { width: MIN_LEGEND_CARD_WIDTH - 1 }),+ ).toEqual(HIDDEN);+ });++ it("should keep a column when at most half of the labels are truncated", () => {+ // 25% of 368 = 92, label room = 78 → 13 chars fit+ const names = [+ "a".repeat(40),+ "b".repeat(40),+ "c".repeat(10),+ "d".repeat(10),+ ];+ expect(layout(names, { width: 400 })).toMatchObject({+ type: "vertical",+ visibleCount: 4,+ });+ });++ it("should leave the y-axis indent when the row fits only across it", () => {const names = ["first", "other", "third", "fourth", "fifth"];+ const width = getCardWidthForRow(names);++ expect(layout(names, { width: width + 1, indent: 1 })).toEqual(+ row(5, { indent: 1 }),+ );+ expect(layout(names, { width, indent: 1 })).toEqual(row(5, { indent: 0 }));+ });++ it("should take the plot inset from the room left for the plot", () => {+ const names = createSeriesNames(10);+ const width = 420;+ const insetWidth = width - getColumnSpace(62) - MIN_PLOT_WIDTH;- expect(layout(names, { width: 420 })).toEqual({ type: "horizontal" });expect(- layout(names, {- width: 420,- horizontalWidth: 232,- }),- ).toMatchObject({ type: "vertical", visibleCount: 5 });+ layout(names, { width, plotInset: { width: insetWidth, height: 0 } }),+ ).toMatchObject({ type: "vertical" });+ // 4 items + 3 gaps + 12 gap + "+ 6 more" 48 = 344 <= 384+ expect(+ layout(names, { width, plotInset: { width: insetWidth + 1, height: 0 } }),+ ).toEqual(row(4));});- it("should cap the vertical legend width at 25% of the available width", () => {+ it("should cap the column width at 25% of the available width", () => {const names = ["a".repeat(40), ...Array(6).fill("12345")];// longest item = 254 > 25% of (600 - 32) = 142 < 200expect(layout(names, { width: 600 })).toMatchObject({@@ -90,7 +320,7 @@ describe("getLegendLayout", () => {});});- it("should cap the vertical legend width at the size's maximum", () => {+ it("should cap the column width at the size's maximum", () => {const names = ["a".repeat(40), "b".repeat(40), ...Array(10).fill("12345")];// 25% of (900 - 32) = 217 > 200expect(layout(names, { width: 900 })).toMatchObject({@@ -104,162 +334,266 @@ describe("getLegendLayout", () => {});});- it("should keep the vertical legend when at most half of the items are truncated", () => {- // 25% of 568 = 142, label room = 128 → 22 chars fit- const names = [- "a".repeat(40),- "b".repeat(40),- "c".repeat(10),- "d".repeat(10),- ];- expect(layout(names, { width: 600 })).toMatchObject({+ it("should reserve the last column row for the overflow label", () => {+ // (200 - 16 - 10 - 4 + 8) / (13.8 + 8) = 8 rows, 7 items + "+ 13 more"+ expect(layout(createSeriesNames(20), { width: 420, height: 200 })).toEqual({type: "vertical",- visibleCount: 4,+ isBeforeChart: false,+ width: 72,+ visibleCount: 7,});});- it("should hide the legend when more than half of the items are truncated", () => {- const names = [- "a".repeat(40),- "b".repeat(40),- "c".repeat(40),- "d".repeat(10),- ];- expect(layout(names, { width: 600 })).toEqual({ type: "hidden" });- });-- it("should reserve the last row for the overflow label when rows do not fit", () => {- const names = Array.from({ length: 20 }, (_, i) => `series ${i}`);- // (200 - 16 + 8) / (14 + 8) = 8 rows, 7 items + "+ 13 more"- expect(layout(names, { width: 420, height: 200 })).toEqual({+ it("should fit column rows into the measured chart area when it is known", () => {+ // (100 - 10 - 4 + 8) / (13.8 + 8) = 4 rows, 3 items + "+ 17 more"+ expect(+ layout(createSeriesNames(20), {+ width: 420,+ height: 300,+ chartAreaHeight: 100,+ }),+ ).toEqual({type: "vertical",+ isBeforeChart: false,width: 72,- visibleCount: 7,+ visibleCount: 3,});});- it("should fit rows into the measured chart height when it is known", () => {- const names = Array.from({ length: 20 }, (_, i) => `series ${i}`);- // (100 + 8) / (14 + 8) = 4 rows, 3 items + "+ 17 more"+ it("should not reserve outline room below the '+ N more' label", () => {+ // (169 - 2 + 8) / (13.8 + 8) = 8 rows, 7 items + "+ 13 more"expect(- getLegendLayout({- items: createItems(names),+ layout(createSeriesNames(20), {width: 420,height: 300,- chartHeight: 100,- size: "sm",- fontFamily: "Lato",- measureText,+ chartAreaHeight: LEGEND_COLUMN_MARGIN_TOP + 169,}),- ).toEqual({ type: "vertical", width: 72, visibleCount: 3 });+ ).toMatchObject({ type: "vertical", visibleCount: 7 });+ });++ it("should leave the column's top margin out of its rows", () => {+ // (169 - 10 - 2 + 8) / (13.8 + 8) = 7 rows, 6 items + "+ 14 more"+ expect(+ layout(createSeriesNames(20), {+ width: 420,+ height: 300,+ chartAreaHeight: 169,+ }),+ ).toMatchObject({ type: "vertical", visibleCount: 6 });+ });++ it("should widen the column to fit the '+ N more' label", () => {+ // item = 8 + 6 + 12 = 26 < "+ 13 more" = 9 * 6 = 54+ expect(layout(TWO_DIGIT_NAMES, { width: 420, height: 200 })).toEqual({+ type: "vertical",+ isBeforeChart: false,+ width: 58,+ visibleCount: 7,+ });});it("should use the larger metrics for the md size", () => {const names = ["12345", "12345", "12345", "12345"];- // sm: item = 8 + 6 + 30 = 44, 4 items + 3 * 12 = 212 <= 388- expect(layout(names, { width: 420 })).toEqual({ type: "horizontal" });- // md: item = 14 + 8 + 30 = 52, 4 items + 3 * 16 = 256 <= 372- expect(layout(names, { width: 420, size: "md" })).toEqual({- type: "horizontal",- });- // md: 8 items = 416 + 112 = 528 > 372+ // md: item = 14 + 8 + 30 = 52, 4 items + 3 * 16 = 256 <= 368+ expect(layout(names, { width: 420, size: "md" })).toEqual(row(4));+ // md: 8 items = 416 + 112 = 528 > 368expect(layout([...names, ...names], { width: 420, size: "md" })).toEqual({type: "vertical",+ isBeforeChart: false,width: 56,visibleCount: 8,});});-});-describe("getLegendLayout overflow label", () => {- it("should widen the column to fit the '+ N more' label", () => {- const names = Array.from({ length: 20 }, () => "ab");- // item = 8 + 6 + 12 = 26 < "+ 13 more" = 9 * 6 = 54+ it("should use the roomier lg metrics for column rows", () => {+ // (200 - 4 + 12) / (13.8 + 12) = 8 rows, 7 items + the overflow labelexpect(- getLegendLayout({- items: names.map((name, i) => ({ key: `${i}`, name, color: "red" })),- width: 420,- height: 200,- size: "sm",- fontFamily: "Lato",- measureText,+ layout(createSeriesNames(20), {+ width: 700,+ height: 400,+ chartAreaHeight: LEGEND_COLUMN_MARGIN_TOP + 200,+ size: "lg",}),- ).toEqual({ type: "vertical", width: 58, visibleCount: 7 });+ ).toMatchObject({ type: "vertical", visibleCount: 7 });});});-describe("getLegendLayout truncation at the rendered width", () => {- it("should hide the legend when all names are truncated by the 25% squeeze, even if they would fit a wider card", () => {- // labels 180 fit the 200px cap but not the squeezed 142px column- const names = Array.from({ length: 4 }, (_, i) => `${i}`.padEnd(30, "a"));- expect(layout(names, { width: 600 })).toEqual({ type: "hidden" });- });-});+describe("getLegendLayout with an explicit position", () => {+ it.each<LegendPosition>(["top", "bottom"])(+ "should show a %s row on a cramped card where auto hides it",+ (position) => {+ const isBeforeChart = position === "top";+ const card = {+ width: 311,+ chartAreaHeight: 131,+ plotInset: { width: 0, height: 83 },+ minXAxisLabelsWidth: 300,+ };+ expect(layout(["first", "second"], card)).toEqual(HIDDEN);+ expect(layout(["first", "second"], { ...card, position })).toEqual(+ row(2, { isBeforeChart }),+ );+ },+ );-describe("getLegendLayout alwaysVisible", () => {- const opts = {- size: "sm" as const,- fontFamily: "Lato",- measureText,- alwaysVisible: true,- };+ it.each<LegendPosition>(["top", "bottom"])(+ "should hide a %s row when the plot would be under 150px wide",+ (position) => {+ expect(+ layout(["a", "b"], { width: MIN_PLOT_WIDTH, position }),+ ).toMatchObject({ type: "horizontal" });+ expect(+ layout(["a", "b"], { width: MIN_PLOT_WIDTH - 1, position }),+ ).toEqual(HIDDEN);+ expect(+ layout(["a", "b"], {+ width: 300,+ plotInset: { width: 151, height: 0 },+ position,+ }),+ ).toEqual(HIDDEN);+ },+ );++ it.each<LegendPosition>(["left", "right"])(+ "should hide a %s column when the plot beside it would be under 150px wide",+ (position) => {+ // (200 - 32) * 25% = 42px column, 200 - 70 = 130 < 150+ expect(layout(createSeriesNames(2), { width: 200, position })).toEqual(+ HIDDEN,+ );+ expect(+ layout(createSeriesNames(2), {+ width: 420,+ plotInset: {+ width: 420 - getColumnSpace(62) - MIN_PLOT_WIDTH + 1,+ height: 0,+ },+ position,+ }),+ ).toEqual(HIDDEN);+ },+ );++ it.each<LegendPosition>(["left", "right"])(+ "should show a %s column with most labels truncated on any card it fits",+ (position) => {+ expect(+ layout(MOSTLY_TRUNCATED_NAMES, {+ width: MIN_LEGEND_CARD_WIDTH - 1,+ position,+ }),+ ).toEqual({+ type: "vertical",+ isBeforeChart: position === "left",+ width: 97 + LEGEND_PADDING * 2,+ visibleCount: 4,+ });+ },+ );++ it("should leave the plot the room beside a column widened to fit the '+ N more' label", () => {+ // the 58px column leaves 420 - 58 - 24 = 338px, not 420 - 30 - 24 = 366px+ const card: LayoutOpts = { width: 420, height: 200, position: "right" };+ const insetWidth = 338 - MIN_PLOT_WIDTH;- it("should show the legend on cards below the minimum size", () => {expect(- getLegendLayout({- items: createItems(["a", "b"]),- width: 300,- height: 150,- ...opts,+ layout(TWO_DIGIT_NAMES, {+ ...card,+ plotInset: { width: insetWidth, height: 0 },}),- ).toEqual({ type: "horizontal" });+ ).toMatchObject({ type: "vertical", width: 58 });+ expect(+ layout(TWO_DIGIT_NAMES, {+ ...card,+ plotInset: { width: insetWidth + 1, height: 0 },+ }),+ ).toEqual(HIDDEN);});- it("should show at least one row even when nothing fits", () => {- const names = Array.from({ length: 8 }, () => "a".repeat(40));+ it("should keep a row instead of switching to a column when the items overflow", () => {+ // item = 62, 4 items + 3 gaps = 284, + 12 gap + "+ 6 more" 48 = 344 <= 384expect(- getLegendLayout({- items: createItems(names),- width: 300,- height: 40,- chartHeight: 10,- ...opts,- }),- ).toMatchObject({ type: "vertical", visibleCount: 1 });+ layout(createSeriesNames(10), { width: 420, position: "top" }),+ ).toEqual(row(4, { isBeforeChart: true }));});-});-describe("getLegendSize", () => {- it("should pick lg for large dashboard cards and sm otherwise", () => {- expect(getLegendSize({ width: 640, height: 360 })).toBe("lg");- expect(getLegendSize({ width: 639, height: 360 })).toBe("sm");- expect(getLegendSize({ width: 640, height: 359 })).toBe("sm");+ it("should keep at least one item in the row when even one item does not fit", () => {+ const names = ["a".repeat(100), "b", "c"];+ expect(layout(names, { width: 420, position: "bottom" })).toEqual(row(1));});- it("should always pick md in the query builder and fullscreen", () => {+ it("should fit the row in the order the legend displays the items", () => {+ const names = ["a".repeat(50), "b", "c", "d", "e"];+ expect(layout(names, { width: 420, position: "top" })).toMatchObject({+ visibleCount: 1,+ });expect(- getLegendSize({ width: 300, height: 200, isQueryBuilder: true }),- ).toBe("md");+ layout(names, { width: 420, position: "top", isReversed: true }),+ ).toMatchObject({ visibleCount: 4 });+ });++ it("should hide a column when its height fits no item", () => {expect(- getLegendSize({ width: 2000, height: 900, isFullscreen: true }),- ).toBe("md");+ layout(["a", "b"], { chartAreaHeight: 10, position: "right" }),+ ).toEqual(HIDDEN);+ });++ describe("in the query builder with the chart indent", () => {+ // outer width 880 holds the md card padding 48 and the 73px indent, so+ // the row's items get 880 - 48 - 73 - 2 * 2 = 755px+ const QUERY_BUILDER_ROW = {+ width: 880,+ indent: 73,+ size: "md" as const,+ };+ // md item = 14 + 8 + 3 * 6 = 40, one item per 40 + 16 gap+ const names = Array.from({ length: 49 }, (_, i) => `S${i + 10}`);++ it("should budget the row after both the card padding and the indent", () => {+ // 12 items = 12 * 56 - 16 = 656, + 16 gap + "+ 37 more" 54 = 726 <= 755+ // 13 items = 13 * 56 - 16 = 712, + 16 gap + "+ 36 more" 54 = 782 > 755+ expect(layout(names, { ...QUERY_BUILDER_ROW, position: "top" })).toEqual(+ row(12, { isBeforeChart: true, indent: 73 }),+ );+ });++ it("should leave the indent for a row that fits only across it", () => {+ // 14 items = 14 * 56 - 16 = 768 > 755, but within 880 - 48 - 4 = 828+ expect(+ layout(names.slice(0, 14), {+ ...QUERY_BUILDER_ROW,+ position: "bottom",+ }),+ ).toEqual(row(14, { indent: 0 }));+ });});});-describe("getLegendLayout lg size", () => {- it("should use the roomier lg metrics for row fitting", () => {- const names = Array.from({ length: 20 }, (_, i) => `series ${i}`);- // (200 + 12) / (13.8 + 12) = 8 rows, 7 items + the overflow label+describe("getLegendLayout alwaysVisible", () => {+ it.each<LegendPosition>(["auto", "bottom"])(+ "should show a %s legend where the plot would be too narrow",+ (position) => {+ expect(+ layout(["a", "b"], {+ width: 100,+ height: 40,+ alwaysVisible: true,+ position,+ }),+ ).toMatchObject({ type: "horizontal", visibleCount: 2 });+ },+ );++ it("should show at least one item even when nothing fits", () => {+ const names = Array.from({ length: 8 }, (_, i) => `${i}`.repeat(40));expect(- getLegendLayout({- items: createItems(names),- width: 700,- height: 400,- chartHeight: 200,- size: "lg",- fontFamily: "Lato",- measureText,+ layout(names, {+ width: 300,+ height: 40,+ chartAreaHeight: 10,+ alwaysVisible: true,}),- ).toMatchObject({ type: "vertical", visibleCount: 7 });+ ).toMatchObject({ visibleCount: 1 });});});diff --git a/frontend/src/metabase/visualizations/components/legend/measure.ts b/frontend/src/metabase/visualizations/components/legend/measure.tsnew file mode 100644index 00000000000..e471972d693--- /dev/null+++ b/frontend/src/metabase/visualizations/components/legend/measure.ts@@ -0,0 +1,188 @@+import { c } from "ttag";++import type { TextWidthMeasurer } from "metabase/utils/measure-text";++import type { LegendItemData } from "./LegendItem";+import {+ LEGEND_COLUMN_GAP,+ LEGEND_COLUMN_MARGIN_TOP,+ LEGEND_PADDING,+ MIN_VISIBLE_COUNT,+} from "./constants";+import type { ChartSize, LegendCandidates } from "./plots";+import { LEGEND_SIZES, type LegendSize, type LegendSizeConfig } from "./sizes";++const LEGEND_FONT_WEIGHT = 400;+const MAX_VERTICAL_WIDTH_RATIO = 0.25;+const MAX_TRUNCATED_ITEMS_RATIO = 0.5;++export interface MeasureLegendOptions {+ items: LegendItemData[];+ width: number;+ height: number;+ // the room the chart shares with its legend, the same whichever legend shows+ chartRoom?: ChartSize;+ size: LegendSize;+ fontFamily: string;+ measureText: TextWidthMeasurer;+ isReversed?: boolean;+}++export interface LegendMetrics {+ config: LegendSizeConfig;+ width: number;+ height: number;+ chartSizes: LegendCandidates<ChartSize>;+ labelWidths: number[];+ itemWidths: number[];+ availableWidth: number;+ // 0 when no item fits, while a column always shows columnVisibleCount+ columnFitCount: number;+ columnVisibleCount: number;+ columnWidth: number;+ isColumnMostlyTruncated: boolean;+ measureOverflowLabel: (overflowCount: number) => number;+}++export const getOverflowLabel = (count: number) =>+ c("{0} is the number of hidden legend items").t`+ ${count} more`;++export function measureLegend({+ items,+ width,+ height,+ chartRoom: measuredChartRoom,+ size,+ fontFamily,+ measureText,+ isReversed,+}: MeasureLegendOptions): LegendMetrics {+ const config = LEGEND_SIZES[size];+ const font = {+ size: config.fontSize,+ weight: LEGEND_FONT_WEIGHT,+ family: fontFamily,+ };+ const displayedItems = isReversed ? [...items].reverse() : items;+ const labelWidths = displayedItems.map((item) =>+ measureText(item.name, font),+ );+ const dotWidth = getDotWidth(config);+ const availableWidth = width - config.horizontalPadding;+ const chartRoom = measuredChartRoom ?? {+ width,+ height: height - config.verticalPadding,+ };+ const itemWidths = labelWidths.map((labelWidth) => dotWidth + labelWidth);+ const measureOverflowLabel = (overflowCount: number) =>+ measureText(getOverflowLabel(overflowCount), font);+ const columnFitCount = getColumnFitCount(+ { itemWidths, config },+ chartRoom.height - LEGEND_COLUMN_MARGIN_TOP,+ );+ const columnVisibleCount = Math.max(columnFitCount, MIN_VISIBLE_COUNT);+ const columnWidth = getColumnWidth(+ { itemWidths, config, availableWidth, measureOverflowLabel },+ columnVisibleCount,+ );++ return {+ config,+ width,+ height,+ chartSizes: {+ none: chartRoom,+ row: {+ width: chartRoom.width,+ height: Math.max(chartRoom.height - getRowHeight(config), 0),+ },+ column: {+ width: Math.max(chartRoom.width - columnWidth - LEGEND_COLUMN_GAP, 0),+ height: chartRoom.height,+ },+ },+ labelWidths,+ itemWidths,+ availableWidth,+ columnFitCount,+ columnVisibleCount,+ columnWidth,+ isColumnMostlyTruncated: isColumnMostlyTruncated({+ labelWidths,+ itemWidths,+ config,+ availableWidth,+ }),+ measureOverflowLabel,+ };+}++const getRowHeight = (config: LegendSizeConfig) =>+ config.fontSize * config.lineHeight + config.rowChartGap + LEGEND_PADDING * 2;++const getDotWidth = (config: LegendSizeConfig) =>+ config.dotSize + config.dotGap;++export const getRowWidth = (itemWidths: number[], config: LegendSizeConfig) =>+ itemWidths.reduce((total, width) => total + width, 0) ++ config.itemGap * (itemWidths.length - 1);++const getColumnItemWidth = ({+ itemWidths,+ config,+ availableWidth,+}: Pick<LegendMetrics, "itemWidths" | "config" | "availableWidth">) =>+ Math.max(+ 0,+ Math.min(+ Math.max(...itemWidths),+ availableWidth * MAX_VERTICAL_WIDTH_RATIO,+ config.maxVerticalWidth,+ ),+ );++function getColumnFitCount(+ { itemWidths, config }: Pick<LegendMetrics, "itemWidths" | "config">,+ columnHeight: number,+): number {+ const rowPitch = config.fontSize * config.lineHeight + config.rowGap;+ const getMaxRows = (rowsHeight: number) =>+ Math.floor((rowsHeight + config.rowGap) / rowPitch);+ if (itemWidths.length <= getMaxRows(columnHeight - LEGEND_PADDING * 2)) {+ return itemWidths.length;+ }+ // the last row is the "+ N more" label, which takes no focus outline+ return Math.max(getMaxRows(columnHeight - LEGEND_PADDING) - 1, 0);+}++function getColumnWidth(+ metrics: Pick<+ LegendMetrics,+ "itemWidths" | "config" | "availableWidth" | "measureOverflowLabel"+ >,+ visibleCount: number,+): number {+ const overflowCount = metrics.itemWidths.length - visibleCount;+ const overflowLabelWidth =+ overflowCount > 0 ? metrics.measureOverflowLabel(overflowCount) : 0;+ const contentWidth = Math.max(+ getColumnItemWidth(metrics),+ Math.min(overflowLabelWidth, metrics.config.maxVerticalWidth),+ );+ return Math.ceil(contentWidth) + LEGEND_PADDING * 2;+}++function isColumnMostlyTruncated(+ metrics: Pick<+ LegendMetrics,+ "labelWidths" | "itemWidths" | "config" | "availableWidth"+ >,+): boolean {+ const labelWidth = getColumnItemWidth(metrics) - getDotWidth(metrics.config);+ const truncatedCount = metrics.labelWidths.filter(+ (width) => width > labelWidth,+ ).length;+ return (+ truncatedCount > metrics.labelWidths.length * MAX_TRUNCATED_ITEMS_RATIO+ );+}diff --git a/frontend/src/metabase/visualizations/components/legend/placement.ts b/frontend/src/metabase/visualizations/components/legend/placement.tsnew file mode 100644index 00000000000..e90aef2021d--- /dev/null+++ b/frontend/src/metabase/visualizations/components/legend/placement.ts@@ -0,0 +1,17 @@+import type { LegendPosition } from "metabase-types/api";++export type LegendPlacement = Exclude<LegendPosition, "auto" | "off">;++export type LegendOrientation = "horizontal" | "vertical";++interface LegendPlacementConfig {+ orientation: LegendOrientation;+ isBeforeChart: boolean;+}++export const LEGEND_PLACEMENTS = {+ top: { orientation: "horizontal", isBeforeChart: true },+ bottom: { orientation: "horizontal", isBeforeChart: false },+ left: { orientation: "vertical", isBeforeChart: true },+ right: { orientation: "vertical", isBeforeChart: false },+} as const satisfies Record<LegendPlacement, LegendPlacementConfig>;diff --git a/frontend/src/metabase/visualizations/components/legend/plots.ts b/frontend/src/metabase/visualizations/components/legend/plots.tsnew file mode 100644index 00000000000..1715d7daf77--- /dev/null+++ b/frontend/src/metabase/visualizations/components/legend/plots.ts@@ -0,0 +1,87 @@+import {+ type BaseCartesianChartModel,+ type ChartLayoutInput,+ type ComputedVisualizationSettings,+ type RenderingContext,+ getChartLayout,+ getChartModelAtHeight,+} from "metabase/viz-core";++export interface ChartSize {+ width: number;+ height: number;+}++/** The plot a chart keeps inside its axes at one size. */+export interface Plot extends ChartSize {+ hasXAxisLabels: boolean;+ // the left axes' width minus the right axes'+ indent: number;+}++/** One value for each option Auto weighs: no legend, a row, or a column. */+export interface LegendCandidates<T> {+ none: T;+ row: T;+ column: T;+}++export const mapLegendCandidates = <T, U>(+ candidates: LegendCandidates<T>,+ transform: (value: T) => U,+): LegendCandidates<U> => ({+ none: transform(candidates.none),+ row: transform(candidates.row),+ column: transform(candidates.column),+});++/**+ * What the legend needs to lay the chart out at each candidate size. A row+ * chart folds to each height, so a cartesian chart comes as its unfolded model.+ */+export type LegendChart = {+ settings: ComputedVisualizationSettings;+ hasTimelineEvents: boolean;+ renderingContext: RenderingContext;+} & (+ | { chartModel: BaseCartesianChartModel }+ | { layoutInput: ChartLayoutInput }+);++const getLayoutInputAtHeight = (+ chart: LegendChart,+ height: number,+): ChartLayoutInput =>+ "chartModel" in chart+ ? getChartModelAtHeight(chart.chartModel, height, chart.settings)+ : chart.layoutInput;++export const getLegendPlots = (+ chart: LegendChart,+ chartSizes: LegendCandidates<ChartSize>,+): LegendCandidates<Plot> =>+ mapLegendCandidates(chartSizes, ({ width, height }) => {+ const { padding, axisEnabledSetting } = getChartLayout(+ getLayoutInputAtHeight(chart, height),+ chart.settings,+ chart.hasTimelineEvents,+ width,+ height,+ chart.renderingContext,+ );+ return {+ width: width - padding.left - padding.right,+ height: height - padding.top - padding.bottom,+ hasXAxisLabels: axisEnabledSetting !== false,+ indent: padding.left - padding.right,+ };+ });++export const getPlotsWithoutAxes = (+ chartSizes: LegendCandidates<ChartSize>,+): LegendCandidates<Plot> =>+ mapLegendCandidates(chartSizes, (size) => ({+ ...size,+ hasXAxisLabels: true,+ indent: 0,+ }));diff --git a/frontend/src/metabase/visualizations/components/legend/plots.unit.spec.ts b/frontend/src/metabase/visualizations/components/legend/plots.unit.spec.tsnew file mode 100644index 00000000000..65c1700234b--- /dev/null+++ b/frontend/src/metabase/visualizations/components/legend/plots.unit.spec.ts@@ -0,0 +1,147 @@+import {+ type ChartLayoutInput,+ DEFAULT_VISUALIZATION_THEME,+ type RenderingContext,+ X_AXIS_DATA_KEY,+ getCartesianChartModel,+} from "metabase/viz-core";+import {+ createMockCard,+ createMockColumn,+ createMockDatasetData,+ createMockVisualizationSettings,+} from "metabase-types/api/mocks";++import { type LegendChart, getLegendPlots } from "./plots";++const CATEGORY_COUNT = 20;+const LABEL_WIDTH = 40;+const ROW_LEGEND_HEIGHT = 30;++const layoutInput: ChartLayoutInput = {+ xAxisModel: {+ axisType: "category",+ isHistogram: false,+ valuesCount: CATEGORY_COUNT,+ formatter: (value) => String(value),+ },+ leftAxisModel: {+ seriesKeys: ["count"],+ extent: [0, 100],+ column: createMockColumn({ name: "count" }),+ formatter: (value) => String(value),+ formatGoal: (value) => String(value),+ splitNumber: 5,+ },+ rightAxisModel: null,+ yAxisScaleTransforms: {+ toEChartsAxisValue: (value) => (typeof value === "number" ? value : null),+ fromEChartsAxisValue: (value) => value,+ },+ dataset: Array.from({ length: CATEGORY_COUNT }, (_, index) => ({+ [X_AXIS_DATA_KEY]: `category ${index}`,+ count: index,+ })),+};++const renderingContext: RenderingContext = {+ getColor: (name) => name,+ measureText: () => LABEL_WIDTH,+ measureTextHeight: () => 0,+ fontFamily: "",+ theme: DEFAULT_VISUALIZATION_THEME,+};++const chart: LegendChart = {+ layoutInput,+ settings: createMockVisualizationSettings({+ "graph.x_axis.axis_enabled": true,+ "graph.x_axis.scale": "ordinal",+ "graph.y_axis.axis_enabled": true,+ }),+ hasTimelineEvents: false,+ renderingContext,+};++describe("getLegendPlots", () => {+ const plots = getLegendPlots(chart, {+ none: { width: 600, height: 200 },+ row: { width: 600, height: 200 - ROW_LEGEND_HEIGHT },+ column: { width: 150, height: 200 },+ });++ it("should leave the plot what the axes do not take", () => {+ expect(plots.none.width).toBeLessThan(600);+ expect(plots.none.height).toBeLessThan(200);+ expect(plots.row.width).toBe(plots.none.width);+ expect(plots.row.height).toBe(plots.none.height - ROW_LEGEND_HEIGHT);+ });++ it("should report the y-axis indent a row legend lines up with", () => {+ expect(plots.none.indent).toBeGreaterThan(0);+ expect(plots.row.indent).toBe(plots.none.indent);+ });++ it("should report x-axis labels only where the chart has room for them", () => {+ expect(plots.none.hasXAxisLabels).toBe(true);+ expect(plots.row.hasXAxisLabels).toBe(true);+ expect(plots.column.hasXAxisLabels).toBe(false);+ });+});++describe("getLegendPlots on a row chart", () => {+ const CHAR_WIDTH = 6;+ const ROW_COUNT = 10;+ const LONG_LABEL = "a category name long enough to take half the chart";++ const rowSettings = createMockVisualizationSettings({+ "graph.dimensions": ["CATEGORY"],+ "graph.metrics": ["count"],+ "graph.x_axis.scale": "ordinal",+ series: () => ({ display: "bar" }),+ });+ const rowRenderingContext: RenderingContext = {+ ...renderingContext,+ measureText: (text) => text.length * CHAR_WIDTH,+ };+ const labels = Array.from({ length: ROW_COUNT }, (_, index) =>+ index === ROW_COUNT - 1 ? LONG_LABEL : `C${index}`,+ );+ const chartModel = getCartesianChartModel(+ [+ {+ card: createMockCard({ display: "row" }),+ data: createMockDatasetData({+ rows: labels.map((label) => [label, 1]),+ cols: [+ createMockColumn({ name: "CATEGORY", base_type: "type/Text" }),+ createMockColumn({ name: "count", base_type: "type/Integer" }),+ ],+ }),+ },+ ],+ rowSettings,+ [],+ rowRenderingContext,+ );++ it("should lay out only the rows the chart keeps at each height", () => {+ const plots = getLegendPlots(+ {+ chartModel,+ settings: rowSettings,+ hasTimelineEvents: false,+ renderingContext: rowRenderingContext,+ },+ // ten rows need 10 * 24px, so only the row candidate folds+ {+ none: { width: 600, height: 240 },+ row: { width: 600, height: 240 - ROW_LEGEND_HEIGHT },+ column: { width: 450, height: 240 },+ },+ );++ // the long last row folds into "Other" only under a bottom legend+ expect(plots.row.width - plots.none.width).toBeGreaterThan(150);+ });+});diff --git a/frontend/src/metabase/visualizations/components/legend/sizes.ts b/frontend/src/metabase/visualizations/components/legend/sizes.tsnew file mode 100644index 00000000000..4575c2517dc--- /dev/null+++ b/frontend/src/metabase/visualizations/components/legend/sizes.ts@@ -0,0 +1,83 @@+export type LegendSize = "sm" | "lg" | "md";++export interface LegendSizeConfig {+ typography: "sm" | "md";+ fontSize: number;+ lineHeight: number;+ dotSize: number;+ dotGap: number;+ itemGap: number;+ rowGap: number;+ // the vertical space between a top or bottom legend and the chart+ rowChartGap: number;+ maxVerticalWidth: number;+ horizontalPadding: number;+ verticalPadding: number;+}++export const LEGEND_SIZES = {+ sm: {+ typography: "sm",+ fontSize: 12,+ lineHeight: 1.15,+ dotSize: 8,+ dotGap: 6,+ itemGap: 12,+ rowGap: 8,+ rowChartGap: 12,+ maxVerticalWidth: 200,+ horizontalPadding: 32,+ verticalPadding: 16,+ },+ lg: {+ typography: "sm",+ fontSize: 12,+ lineHeight: 1.15,+ dotSize: 8,+ dotGap: 6,+ itemGap: 12,+ rowGap: 12,+ rowChartGap: 16,+ maxVerticalWidth: 200,+ horizontalPadding: 80,+ verticalPadding: 76,+ },+ md: {+ typography: "md",+ fontSize: 14,+ lineHeight: 1.22,+ dotSize: 14,+ dotGap: 8,+ itemGap: 16,+ rowGap: 16,+ rowChartGap: 24,+ maxVerticalWidth: 256,+ horizontalPadding: 48,+ verticalPadding: 32,+ },+} as const satisfies Record<LegendSize, LegendSizeConfig>;++// mirrors the large card tier in visualizations/CartesianChart/sizing.ts+const LARGE_CARD_MIN_WIDTH = 640;+const LARGE_CARD_MIN_HEIGHT = 360;++interface GetLegendSizeOptions {+ width: number;+ height: number;+ isQueryBuilder?: boolean;+ isFullscreen?: boolean;+}++export const getLegendSize = ({+ width,+ height,+ isQueryBuilder,+ isFullscreen,+}: GetLegendSizeOptions): LegendSize => {+ if (isQueryBuilder || isFullscreen) {+ return "md";+ }+ return width >= LARGE_CARD_MIN_WIDTH && height >= LARGE_CARD_MIN_HEIGHT+ ? "lg"+ : "sm";+};diff --git a/frontend/src/metabase/visualizations/components/legend/sizes.unit.spec.ts b/frontend/src/metabase/visualizations/components/legend/sizes.unit.spec.tsnew file mode 100644index 00000000000..631d3c243cc--- /dev/null+++ b/frontend/src/metabase/visualizations/components/legend/sizes.unit.spec.ts@@ -0,0 +1,18 @@+import { getLegendSize } from "./sizes";++describe("getLegendSize", () => {+ it("should pick lg for large dashboard cards and sm otherwise", () => {+ expect(getLegendSize({ width: 640, height: 360 })).toBe("lg");+ expect(getLegendSize({ width: 639, height: 360 })).toBe("sm");+ expect(getLegendSize({ width: 640, height: 359 })).toBe("sm");+ });++ it("should always pick md in the query builder and fullscreen", () => {+ expect(+ getLegendSize({ width: 300, height: 200, isQueryBuilder: true }),+ ).toBe("md");+ expect(+ getLegendSize({ width: 2000, height: 900, isFullscreen: true }),+ ).toBe("md");+ });+});diff --git a/frontend/src/metabase/visualizations/hooks/use-legend-hidden-series.ts b/frontend/src/metabase/visualizations/hooks/use-legend-hidden-series.tsnew file mode 100644index 00000000000..51a7f101ed9--- /dev/null+++ b/frontend/src/metabase/visualizations/hooks/use-legend-hidden-series.ts@@ -0,0 +1,25 @@+import { useEffect } from "react";+import { useSet } from "react-use";++import type { LegendPosition } from "metabase-types/api";++const NO_HIDDEN_SERIES = new Set<never>();++/**+ * Series the user hid through the legend. Turning the legend off brings them+ * all back, since the legend is the only control that hides them.+ */+export function useLegendHiddenSeries<Key>(+ legendPosition: LegendPosition | undefined,+): [hiddenSeries: Set<Key>, toggleSeries: (key: Key) => void] {+ const [hiddenSeries, { toggle, reset }] = useSet<Key>();+ const isLegendOff = legendPosition === "off";++ useEffect(() => {+ if (isLegendOff) {+ reset();+ }+ }, [isLegendOff, reset]);++ return [isLegendOff ? NO_HIDDEN_SERIES : hiddenSeries, toggle];+}diff --git a/frontend/src/metabase/visualizations/hooks/use-legend-hidden-series.unit.spec.ts b/frontend/src/metabase/visualizations/hooks/use-legend-hidden-series.unit.spec.tsnew file mode 100644index 00000000000..d8b65a460cf--- /dev/null+++ b/frontend/src/metabase/visualizations/hooks/use-legend-hidden-series.unit.spec.ts@@ -0,0 +1,44 @@+import { act, renderHook } from "@testing-library/react";++import type { LegendPosition } from "metabase-types/api";++import { useLegendHiddenSeries } from "./use-legend-hidden-series";++interface SetupOpts {+ legendPosition: LegendPosition;+}++const setup = ({ legendPosition }: SetupOpts) =>+ renderHook(+ (props: SetupOpts) => useLegendHiddenSeries<string>(props.legendPosition),+ { initialProps: { legendPosition } },+ );++describe("useLegendHiddenSeries", () => {+ it("should hide the series toggled through the legend", () => {+ const { result } = setup({ legendPosition: "auto" });++ act(() => result.current[1]("a"));++ expect([...result.current[0]]).toEqual(["a"]);+ });++ it("should show every series again when the legend is turned off", () => {+ const { result, rerender } = setup({ legendPosition: "auto" });+ act(() => result.current[1]("a"));++ rerender({ legendPosition: "off" });++ expect(result.current[0].size).toBe(0);+ });++ it("should not hide the series again when the legend comes back", () => {+ const { result, rerender } = setup({ legendPosition: "right" });+ act(() => result.current[1]("a"));++ rerender({ legendPosition: "off" });+ rerender({ legendPosition: "right" });++ expect(result.current[0].size).toBe(0);+ });+});diff --git a/frontend/src/metabase/visualizations/hooks/use-legend-overflow.ts b/frontend/src/metabase/visualizations/hooks/use-legend-overflow.tsnew file mode 100644index 00000000000..03e8bd72651--- /dev/null+++ b/frontend/src/metabase/visualizations/hooks/use-legend-overflow.ts@@ -0,0 +1,106 @@+import { useLayoutEffect, useRef, useState } from "react";+import _ from "underscore";++import type { LegendTitle } from "metabase/visualizations/components/types";++type LegendOverflowAxis = "vertical" | "horizontal";++const AXIS_EDGES = {+ vertical: { start: "top", end: "bottom", extent: "height" },+ horizontal: { start: "left", end: "right", extent: "width" },+} as const satisfies Record<+ LegendOverflowAxis,+ { start: keyof DOMRect; end: keyof DOMRect; extent: keyof DOMRect }+>;++interface UseLegendOverflowOptions {+ titles: LegendTitle[];+ minVisibleCount: number;+ axis: LegendOverflowAxis;+ isEnabled?: boolean;+}++/**+ * Measures how many legend items overflow the container along `axis`.+ * `visibleCount` is how many leading items to render, leaving one slot for the+ * overflow label but never fewer than `minVisibleCount`. New titles discard the+ * previous measurement. A disabled hook measures nothing and shows every item.+ */+export function useLegendOverflow({+ titles,+ minVisibleCount,+ axis,+ isEnabled = true,+}: UseLegendOverflowOptions) {+ const itemCount = titles.length;+ const [overflowCount, setOverflowCount] = useState(0);+ const [size, setSize] = useState<DOMRect | null>(null);+ const containerRef = useRef<HTMLOListElement>(null);+ const itemRefs = useRef<Record<number, HTMLLIElement | null>>({});+ const prevOverflowCountRef = useRef(overflowCount);+ const prevItemsKeyRef = useRef<string | null>(null);++ // Runs after every render because the container can resize without any+ // prop or state change.+ // eslint-disable-next-line react-hooks/exhaustive-deps+ useLayoutEffect(() => {+ const container = containerRef.current;+ if (!isEnabled || !container) {+ return;+ }++ const prevOverflowCount = prevOverflowCountRef.current;+ prevOverflowCountRef.current = overflowCount;+ const itemsKey = JSON.stringify(titles);+ const prevItemsKey = prevItemsKeyRef.current;+ prevItemsKeyRef.current = itemsKey;++ const { start, end, extent } = AXIS_EDGES[axis];+ const containerRect = container.getBoundingClientRect();++ // check only the extent along the axis, the other one may fluctuate depending on the browser causing an infinite loop+ // check overflowCount, because after setting overflowCount the extent changes and it causing an infinite loop too+ const isResized =+ size != null &&+ containerRect[extent] !== size[extent] &&+ prevOverflowCount === overflowCount;+ // a count measured for other items is stale even when the container keeps its size+ const hasStaleCount = overflowCount > 0 && itemsKey !== prevItemsKey;+ if (isResized || hasStaleCount) {+ setOverflowCount(0);+ setSize(containerRect);+ return;+ }++ // only a full render, with no items folded, can be measured+ if (overflowCount > 0) {+ return;+ }++ const measuredOverflowCount = _.range(itemCount).filter((index) => {+ const itemRect = itemRefs.current[index]?.getBoundingClientRect();+ return (+ itemRect != null &&+ (containerRect[start] > itemRect[start] ||+ containerRect[end] < itemRect[end])+ );+ }).length;+ if (measuredOverflowCount > 0) {+ setOverflowCount(measuredOverflowCount);+ setSize(containerRect);+ }+ });++ const activeOverflowCount = isEnabled ? overflowCount : 0;+ const visibleCount =+ activeOverflowCount > 0+ ? Math.max(itemCount - activeOverflowCount - 1, minVisibleCount)+ : itemCount;++ return {+ overflowCount: activeOverflowCount,+ visibleCount,+ containerRef,+ itemRefs,+ };+}diff --git a/frontend/src/metabase/visualizations/visualizations/BoxPlot/BoxPlot.tsx b/frontend/src/metabase/visualizations/visualizations/BoxPlot/BoxPlot.tsxindex 72173b88e3e..330d420bfc0 100644--- a/frontend/src/metabase/visualizations/visualizations/BoxPlot/BoxPlot.tsx+++ b/frontend/src/metabase/visualizations/visualizations/BoxPlot/BoxPlot.tsx@@ -1,6 +1,5 @@import type { EChartsType } from "echarts/core";import { type MouseEvent, useCallback, useMemo, useRef, useState } from "react";-import { useSet } from "react-use";import { isReducedMotionPreferred } from "metabase/utils/dom";import { assignLazily } from "metabase/utils/merge-lazily";@@ -8,7 +7,9 @@ import { ChartRenderingErrorBoundary } from "metabase/visualizations/components/import { DataPointsVisiblePopover } from "metabase/visualizations/components/DataPointsVisiblePopover/DataPointsVisiblePopover";import { ResponsiveEChartsRenderer } from "metabase/visualizations/components/EChartsRenderer";import { LegendCaption } from "metabase/visualizations/components/legend/LegendCaption";+import type { LegendChart } from "metabase/visualizations/components/legend/plots";import { useBrowserRenderingContext } from "metabase/visualizations/hooks/use-browser-rendering-context";+import { useLegendHiddenSeries } from "metabase/visualizations/hooks/use-legend-hidden-series";import type { VisualizationProps } from "metabase/visualizations/types";import {CartesianChartLegendLayout,@@ -63,7 +64,6 @@ function BoxPlotInner({const chartRef = useRef<EChartsType>();const [chartInstance, setChartInstance] = useState<EChartsType>();const [chartSize, setChartSize] = useState({ width: 0, height: 0 });- const [hiddenSeries, { toggle: toggleSeriesVisibility }] = useSet<string>();const rawSeriesWithRemappings = useMemo(() => extractRemappings(rawSeries),@@ -81,6 +81,10 @@ function BoxPlotInner({[originalSettings, height, width, isMobile, gridSize],);+ const [hiddenSeries, toggleSeriesVisibility] = useLegendHiddenSeries<string>(+ settings["legend.position"],+ );+const renderingContext = useBrowserRenderingContext({fontFamily,isDashboard,@@ -133,17 +137,38 @@ function BoxPlotInner({[chartModel, hiddenSeries, toggleSeriesVisibility],);+ const layoutInput = useMemo(+ () => ({ ...chartModel, dataset: chartModel.boxDataset }),+ [chartModel],+ );+const cartesianLayout = useMemo(() =>getChartLayout(- { ...chartModel, dataset: chartModel.boxDataset },+ layoutInput,settings,false,chartSize.width,chartSize.height,renderingContext,),- [chartModel, settings, chartSize.width, chartSize.height, renderingContext],+ [+ layoutInput,+ settings,+ chartSize.width,+ chartSize.height,+ renderingContext,+ ],+ );++ const legendChart: LegendChart = useMemo(+ () => ({+ layoutInput,+ settings,+ hasTimelineEvents: false,+ renderingContext,+ }),+ [layoutInput, settings, renderingContext],);const layoutModel = useMemo(@@ -228,6 +253,7 @@ function BoxPlotInner({<CartesianChartLegendLayoutisReversed={settings["legend.is_reversed"]}hasLegend={hasLegend}+ legendPosition={settings["legend.position"]}alwaysVisible={isVisualizer}items={legendItems}actionButtons={!showTitle ? actionButtons : undefined}@@ -240,8 +266,7 @@ function BoxPlotInner({onHoverChange={onHoverChange}width={width}height={height}- chartHeight={chartSize.height || undefined}- indent={cartesianLayout.padding.left - cartesianLayout.padding.right}+ chart={legendChart}><ResponsiveEChartsRendererkey={hasValidOption ? "chart" : "measuring"}diff --git a/frontend/src/metabase/visualizations/visualizations/BoxPlot/definition.ts b/frontend/src/metabase/visualizations/visualizations/BoxPlot/definition.tsindex ae6ae70723f..9898a3518d2 100644--- a/frontend/src/metabase/visualizations/visualizations/BoxPlot/definition.ts+++ b/frontend/src/metabase/visualizations/visualizations/BoxPlot/definition.ts@@ -7,6 +7,7 @@ import {type ComputedVisualizationSettings,GRAPH_AXIS_SETTINGS,GRAPH_GOAL_SETTINGS,+ LEGEND_POSITION_SETTINGS,type VisualizationDefinition,getDefaultSize,getMinSize,@@ -49,6 +50,7 @@ export const BOXPLOT_CHART_DEFINITION: VisualizationDefinition = {...BOXPLOT_SETTINGS,...GRAPH_GOAL_SETTINGS,...GRAPH_AXIS_SETTINGS,+ ...LEGEND_POSITION_SETTINGS,...BOXPLOT_DATA_SETTINGS,},};diff --git a/frontend/src/metabase/visualizations/visualizations/CartesianChart/CartesianChart.tsx b/frontend/src/metabase/visualizations/visualizations/CartesianChart/CartesianChart.tsxindex 9ca9d9149aa..103e06f7564 100644--- a/frontend/src/metabase/visualizations/visualizations/CartesianChart/CartesianChart.tsx+++ b/frontend/src/metabase/visualizations/visualizations/CartesianChart/CartesianChart.tsx@@ -6,13 +6,13 @@ import React, {useRef,useState,} from "react";-import { useSet } from "react-use";import { isWebkit } from "metabase/utils/browser";import { ChartRenderingErrorBoundary } from "metabase/visualizations/components/ChartRenderingErrorBoundary";import { DataPointsVisiblePopover } from "metabase/visualizations/components/DataPointsVisiblePopover/DataPointsVisiblePopover";import { ResponsiveEChartsRenderer } from "metabase/visualizations/components/EChartsRenderer";import { LegendCaption } from "metabase/visualizations/components/legend/LegendCaption";+import { useLegendHiddenSeries } from "metabase/visualizations/hooks/use-legend-hidden-series";import { useTimelineEvents } from "metabase/visualizations/hooks/use-timeline-events";import type { VisualizationProps } from "metabase/visualizations/types";import {@@ -41,8 +41,6 @@ function CartesianChartInner(props: VisualizationProps) {// however, for correct ECharts option calculation we need to use the dimensions of the chart viewportconst [chartSize, setChartSize] = useState({ width: 0, height: 0 });- const [hiddenSeries, { toggle: toggleSeriesVisibility }] = useSet<string>();-const {showAllLegendItems,hideLegend,@@ -85,6 +83,10 @@ function CartesianChartInner(props: VisualizationProps) {[originalSettings, outerHeight, outerWidth, isMobile, gridSize],);+ const [hiddenSeries, toggleSeriesVisibility] = useLegendHiddenSeries<string>(+ settings["legend.position"],+ );+// Row charts don't offer timeline events (UXW-4833).const { timelineEvents } = useTimelineEvents({...props,@@ -98,6 +100,7 @@ function CartesianChartInner(props: VisualizationProps) {const {chartModel,chartLayout,+ legendChart,timelineEventsModel,option,renderingContext,@@ -247,6 +250,7 @@ function CartesianChartInner(props: VisualizationProps) {<CartesianChartLegendLayoutisReversed={settings["legend.is_reversed"]}hasLegend={hasLegend}+ legendPosition={settings["legend.position"]}alwaysVisible={isVisualizer}items={legendItems}actionButtons={!showTitle ? actionButtons : undefined}@@ -263,8 +267,7 @@ function CartesianChartInner(props: VisualizationProps) {onHoverChange={onHoverChange}width={outerWidth}height={outerHeight}- chartHeight={chartSize.height || undefined}- indent={chartLayout.padding.left - chartLayout.padding.right}+ chart={legendChart}><ResponsiveEChartsRendererref={containerRef}diff --git a/frontend/src/metabase/visualizations/visualizations/CartesianChart/definition.ts b/frontend/src/metabase/visualizations/visualizations/CartesianChart/definition.tsindex ba2c85572f6..f2b7e98528e 100644--- a/frontend/src/metabase/visualizations/visualizations/CartesianChart/definition.ts+++ b/frontend/src/metabase/visualizations/visualizations/CartesianChart/definition.ts@@ -8,6 +8,7 @@ import {GRAPH_DISPLAY_VALUES_SETTINGS,GRAPH_GOAL_SETTINGS,GRAPH_TREND_SETTINGS,+ LEGEND_POSITION_SETTINGS,LEGEND_SETTINGS,LINE_SETTINGS,SERIES_SETTING_KEY,@@ -121,6 +122,7 @@ export const COMBO_CHARTS_SETTINGS_DEFINITIONS: VisualizationSettingsDefinitionsGRAPH_COLORS_SETTINGS,GRAPH_AXIS_SETTINGS,GRAPH_DISPLAY_VALUES_SETTINGS,+ LEGEND_POSITION_SETTINGS,GRAPH_DATA_SETTINGS,TOOLTIP_SETTINGS,LEGEND_SETTINGS,diff --git a/frontend/src/metabase/visualizations/visualizations/CartesianChart/legend-settings.unit.spec.ts b/frontend/src/metabase/visualizations/visualizations/CartesianChart/legend-settings.unit.spec.tsnew file mode 100644index 00000000000..24eb29ef39d--- /dev/null+++ b/frontend/src/metabase/visualizations/visualizations/CartesianChart/legend-settings.unit.spec.ts@@ -0,0 +1,60 @@+import { registerVisualizations } from "metabase/visualizations/register";+import {+ getSettingsWidgetsForSeries,+ getVisualizationTransformed,+} from "metabase/viz-core";+import type { CardDisplayType } from "metabase-types/api";+import {+ createMockCard,+ createMockColumn,+ createMockDatasetData,+ createMockSingleSeries,+} from "metabase-types/api/mocks";++registerVisualizations();++const getDisplayWidgetIds = (display: CardDisplayType) => {+ const rawSeries = [+ createMockSingleSeries(+ createMockCard({+ display,+ visualization_settings: {+ "graph.dimensions": ["category"],+ "graph.metrics": ["a", "b"],+ },+ }),+ {+ data: createMockDatasetData({+ cols: [+ createMockColumn({ name: "category", base_type: "type/Text" }),+ createMockColumn({ name: "a", base_type: "type/Number" }),+ createMockColumn({ name: "b", base_type: "type/Number" }),+ ],+ rows: [+ ["x", 1, 2],+ ["y", 3, 4],+ ],+ }),+ },+ ),+ ];+ const { series } = getVisualizationTransformed(rawSeries);+ return getSettingsWidgetsForSeries(series, () => {}, true)+ .filter((widget) => !widget.hidden && widget.section === "Display")+ .map((widget) => widget.id);+};++describe("legend.position in the dashboard settings sidebar", () => {+ it.each<CardDisplayType>(["bar", "line", "area", "combo", "scatter"])(+ "sits above the series list for %s",+ (display) => {+ const ids = getDisplayWidgetIds(display);++ expect(ids).toContain("series_settings");+ expect(ids).toContain("legend.position");+ expect(ids.indexOf("legend.position")).toBeLessThan(+ ids.indexOf("series_settings"),+ );+ },+ );+});diff --git a/frontend/src/metabase/visualizations/visualizations/CartesianChart/use-models-and-option.ts b/frontend/src/metabase/visualizations/visualizations/CartesianChart/use-models-and-option.tsindex 801a2443b3f..79373e59554 100644--- a/frontend/src/metabase/visualizations/visualizations/CartesianChart/use-models-and-option.ts+++ b/frontend/src/metabase/visualizations/visualizations/CartesianChart/use-models-and-option.ts@@ -2,6 +2,7 @@ import { useCallback, useMemo } from "react";import { useTranslateContent } from "metabase/content-translation/hooks";import { isReducedMotionPreferred } from "metabase/utils/dom";+import type { LegendChart } from "metabase/visualizations/components/legend/plots";import { getTooltipOption } from "metabase/visualizations/echarts/cartesian/option/tooltip";import { useBrowserRenderingContext } from "metabase/visualizations/hooks/use-browser-rendering-context";import type { VisualizationProps } from "metabase/visualizations/types";@@ -10,10 +11,10 @@ import {type ScatterPlotModel,type WaterfallChartModel,extractRemappings,- foldRowChartModel,getCartesianChartModel,getCartesianChartOption,getChartLayout,+ getChartModelAtHeight,getScatterPlotModel,getScatterPlotOption,getTimelineEventsModel,@@ -109,13 +110,20 @@ export function useModelsAndOption(// Fold before layout: the fold decides which category labels get measured.const chartModel = useMemo(- () =>- baseChartModel.isRowChart- ? foldRowChartModel(baseChartModel, height, settings)- : baseChartModel,+ () => getChartModelAtHeight(baseChartModel, height, settings),[baseChartModel, height, settings],);+ const legendChart: LegendChart = useMemo(+ () => ({+ chartModel: baseChartModel,+ settings,+ hasTimelineEvents,+ renderingContext,+ }),+ [baseChartModel, settings, hasTimelineEvents, renderingContext],+ );+const chartLayout = useMemo(() =>getChartLayout(@@ -218,6 +226,7 @@ export function useModelsAndOption(return {chartModel,chartLayout,+ legendChart,timelineEventsModel,option,renderingContext,diff --git a/frontend/src/metabase/visualizations/visualizations/Funnel/definition.ts b/frontend/src/metabase/visualizations/visualizations/Funnel/definition.tsindex 8ef3be75408..e362e578f3d 100644--- a/frontend/src/metabase/visualizations/visualizations/Funnel/definition.ts+++ b/frontend/src/metabase/visualizations/visualizations/Funnel/definition.ts@@ -10,6 +10,7 @@ import {columnSettings,dimensionSetting,getDefaultSize,+ getLegendPositionSetting,getMinSize,metricSetting,} from "metabase/viz-core";@@ -168,5 +169,9 @@ export const FUNNEL_CHART_DEFINITION: VisualizationDefinition = {getDefault: (series: RawSeries) => (series.length > 1 ? "bar" : "funnel"),useRawSeries: true,},+ "legend.position": getLegendPositionSetting({+ getHidden: (_series, settings) => settings["funnel.type"] !== "bar",+ readDependencies: ["funnel.type"],+ }),},};diff --git a/frontend/src/metabase/visualizations/visualizations/Funnel/definition.unit.spec.ts b/frontend/src/metabase/visualizations/visualizations/Funnel/definition.unit.spec.tsnew file mode 100644index 00000000000..d9d862dbd54--- /dev/null+++ b/frontend/src/metabase/visualizations/visualizations/Funnel/definition.unit.spec.ts@@ -0,0 +1,19 @@+import { checkNotNull } from "metabase/utils/types";+import { createMockSingleSeries } from "metabase-types/api/mocks";++import { FUNNEL_CHART_DEFINITION } from "./definition";++describe("FUNNEL_CHART_DEFINITION legend.position", () => {+ const getHidden = checkNotNull(+ FUNNEL_CHART_DEFINITION.settings?.["legend.position"]?.getHidden,+ );+ const series = [createMockSingleSeries({ display: "funnel" })];++ it("should offer the setting on the bar funnel, which has a legend", () => {+ expect(getHidden(series, { "funnel.type": "bar" })).toBe(false);+ });++ it("should hide the setting on the classic funnel, which has no legend", () => {+ expect(getHidden(series, { "funnel.type": "funnel" })).toBe(true);+ });+});diff --git a/frontend/src/metabase/visualizations/visualizations/Funnel/funnel-bar-transform.ts b/frontend/src/metabase/visualizations/visualizations/Funnel/funnel-bar-transform.tsindex 8dd2a63a1eb..ef5e9b0f659 100644--- a/frontend/src/metabase/visualizations/visualizations/Funnel/funnel-bar-transform.ts+++ b/frontend/src/metabase/visualizations/visualizations/Funnel/funnel-bar-transform.ts@@ -51,6 +51,7 @@ export const funnelToBarTransform: TransformSeries = (rawSeries, settings) => {"graph.y_axis.auto_split": false,"graph.y_axis.title_text": cols[metricIndex].display_name,"legend.is_reversed": false,+ "legend.position": settings["legend.position"],},},data: {diff --git a/frontend/src/metabase/visualizations/visualizations/Funnel/funnel-bar-transform.unit.spec.ts b/frontend/src/metabase/visualizations/visualizations/Funnel/funnel-bar-transform.unit.spec.tsnew file mode 100644index 00000000000..1d9866c328d--- /dev/null+++ b/frontend/src/metabase/visualizations/visualizations/Funnel/funnel-bar-transform.unit.spec.ts@@ -0,0 +1,41 @@+import {+ createMockColumn,+ createMockDatasetData,+ createMockNumericColumn,+ createMockSingleSeries,+} from "metabase-types/api/mocks";++import { funnelToBarTransform } from "./funnel-bar-transform";++const rawSeries = [+ createMockSingleSeries(+ { display: "funnel" },+ {+ data: createMockDatasetData({+ cols: [+ createMockColumn({ name: "step", display_name: "Step" }),+ createMockNumericColumn({ name: "count", display_name: "Count" }),+ ],+ rows: [+ ["Visited", 100],+ ["Purchased", 10],+ ],+ }),+ },+ ),+];++describe("funnelToBarTransform", () => {+ it("should carry legend.position to every bar series", () => {+ const barSeries = funnelToBarTransform(rawSeries, {+ "funnel.dimension": "step",+ "funnel.metric": "count",+ "legend.position": "off",+ });++ expect(barSeries).toHaveLength(2);+ barSeries.forEach(({ card }) => {+ expect(card.visualization_settings["legend.position"]).toBe("off");+ });+ });+});diff --git a/frontend/src/metabase/visualizations/visualizations/Map/definition.tsx b/frontend/src/metabase/visualizations/visualizations/Map/definition.tsxindex 55ad9834606..e3815b866c2 100644--- a/frontend/src/metabase/visualizations/visualizations/Map/definition.tsx+++ b/frontend/src/metabase/visualizations/visualizations/Map/definition.tsx@@ -12,6 +12,7 @@ import {getDefaultMapDimension,getDefaultMapMetric,getDefaultSize,+ getLegendPositionSetting,getMinSize,metricSetting,} from "metabase/viz-core";@@ -237,6 +238,10 @@ export const MAP_VIZ_DEFINITION: VisualizationDefinition = {getHidden: (_series, vizSettings) => vizSettings["map.type"] !== "region",readDependencies: ["map.metric"],},+ "legend.position": getLegendPositionSetting({+ getHidden: (_series, settings) => settings["map.type"] !== "region",+ readDependencies: ["map.type"],+ }),"map.zoom": {},"map.center_latitude": {},"map.center_longitude": {},diff --git a/frontend/src/metabase/visualizations/visualizations/Map/definition.unit.spec.ts b/frontend/src/metabase/visualizations/visualizations/Map/definition.unit.spec.tsnew file mode 100644index 00000000000..cc18ff4e32c--- /dev/null+++ b/frontend/src/metabase/visualizations/visualizations/Map/definition.unit.spec.ts@@ -0,0 +1,27 @@+import { checkNotNull } from "metabase/utils/types";+import { createMockSingleSeries } from "metabase-types/api/mocks";++import { MAP_VIZ_DEFINITION } from "./definition";++describe("MAP_VIZ_DEFINITION legend.position", () => {+ const setting = checkNotNull(+ MAP_VIZ_DEFINITION.settings?.["legend.position"],+ );+ const getHidden = checkNotNull(setting.getHidden);+ const series = [createMockSingleSeries({ display: "map" })];++ it("should place the legend automatically by default", () => {+ expect(setting.getDefault?.(series, {})).toBe("auto");+ });++ it("should offer the setting on region maps", () => {+ expect(getHidden(series, { "map.type": "region" })).toBe(false);+ });++ it.each(["pin", "grid", "heat"] as const)(+ "should hide the setting on %s maps, which have no legend",+ (mapType) => {+ expect(getHidden(series, { "map.type": mapType })).toBe(true);+ },+ );+});diff --git a/frontend/src/metabase/visualizations/visualizations/PieChart/PieChart.tsx b/frontend/src/metabase/visualizations/visualizations/PieChart/PieChart.tsxindex 847e214c9d6..1f6274f251c 100644--- a/frontend/src/metabase/visualizations/visualizations/PieChart/PieChart.tsx+++ b/frontend/src/metabase/visualizations/visualizations/PieChart/PieChart.tsx@@ -1,12 +1,12 @@import type { EChartsType } from "echarts/core";import { type MouseEvent, useCallback, useMemo, useRef, useState } from "react";-import { useSet } from "react-use";import { isNotNull } from "metabase/utils/types";import { ChartWithLegend } from "metabase/visualizations/components/ChartWithLegend";import { ResponsiveEChartsRenderer } from "metabase/visualizations/components/EChartsRenderer";import { getTooltipOption } from "metabase/visualizations/echarts/pie/tooltip";import { useBrowserRenderingContext } from "metabase/visualizations/hooks/use-browser-rendering-context";+import { useLegendHiddenSeries } from "metabase/visualizations/hooks/use-legend-hidden-series";import type { VisualizationProps } from "metabase/visualizations/types";import { useTooltipMouseLeave } from "metabase/visualizations/visualizations/CartesianChart/use-tooltip-mouse-leave";import {@@ -33,9 +33,9 @@ function PieChartComponent(props: VisualizationProps) {const chartRef = useRef<EChartsType>();const [sideLength, setSideLength] = useState(0);- const [hiddenSlices, { toggle: toggleSliceVisibility }] = useSet<+ const [hiddenSlices, toggleSliceVisibility] = useLegendHiddenSeries<string | number- >();+ >(settings["legend.position"]);const showWarning = useCallback((warning: string) => onRender({ warnings: [warning] }),@@ -141,8 +141,6 @@ function PieChartComponent(props: VisualizationProps) {.filter((s) => s.includeInLegend).map((s) => s.color);- const showLegend = settings["pie.show_legend"];-const onHoverChange = (hoverData: any) =>props.onHoverChange(hoverData && {@@ -171,7 +169,7 @@ function PieChartComponent(props: VisualizationProps) {legendTitles={legendTitles}legendHiddenIndices={hiddenSlicesLegendIndices}legendColors={legendColors}- showLegend={showLegend}+ legendPosition={settings["legend.position"]}onHoverChange={onHoverChange}className={props.className}chartClassName={S.PieChartContainer}diff --git a/frontend/src/metabase/visualizations/visualizations/PieChart/definition.ts b/frontend/src/metabase/visualizations/visualizations/PieChart/definition.tsindex bd905016f81..f965544adfe 100644--- a/frontend/src/metabase/visualizations/visualizations/PieChart/definition.ts+++ b/frontend/src/metabase/visualizations/visualizations/PieChart/definition.ts@@ -9,14 +9,15 @@ import {type VisualizationDefinition,columnSettings,dimensionSetting,+ getDefaultLegendPosition,getDefaultPercentVisibility,getDefaultPieColumns,getDefaultShowLabels,- getDefaultShowLegend,getDefaultShowTotal,getDefaultSize,getDefaultSliceThreshold,getDefaultSortRows,+ getLegendPositionSetting,getMinSize,getPieRows,getPieSortRowsDimensionSetting,@@ -200,18 +201,9 @@ export const PIE_CHART_DEFINITION: VisualizationDefinition = {}),readDependencies: ["pie.dimension", "pie.rows"],},- "pie.show_legend": {- getSection: () => t`Display`,- get title() {- return t`Show legend`;- },- widget: "toggle",- getDefault: getDefaultShowLegend,- inline: true,- getWrapperStyle: () => ({- marginBottom: "1rem",- }),- },+ "legend.position": getLegendPositionSetting({+ getDefault: getDefaultLegendPosition,+ }),"pie.show_total": {getSection: () => t`Display`,get title() {diff --git a/frontend/src/metabase/visualizations/visualizations/PieChart/definition.unit.spec.ts b/frontend/src/metabase/visualizations/visualizations/PieChart/definition.unit.spec.tsindex 40b7cf54e58..8a53c5a94bb 100644--- a/frontend/src/metabase/visualizations/visualizations/PieChart/definition.unit.spec.ts+++ b/frontend/src/metabase/visualizations/visualizations/PieChart/definition.unit.spec.ts@@ -1,11 +1,19 @@+import { registerVisualizations } from "metabase/visualizations/register";import { PIE_CHART_DEFINITION } from "metabase/visualizations/visualizations/PieChart/definition";-import type { RawSeries, RowValues } from "metabase-types/api";+import { getComputedSettingsForSeries } from "metabase/viz-core";+import type {+ RawSeries,+ RowValues,+ VisualizationSettings,+} from "metabase-types/api";import {createMockCard,createMockColumn,createMockDatasetData,} from "metabase-types/api/mocks";+registerVisualizations();+const ROWS = 200;/**@@ -59,3 +67,42 @@ describe("PieChart pie.rows caching", () => {expect(readPieRows(rebuilt)).not.toBe(readPieRows(series));});});++describe("PieChart legend.position", () => {+ const computeLegend = (settings: VisualizationSettings) =>+ getComputedSettingsForSeries([+ {+ ...makeSeries()[0],+ card: createMockCard({+ display: "pie",+ visualization_settings: settings,+ }),+ },+ ])["legend.position"];++ it("places the legend automatically by default", () => {+ expect(computeLegend({})).toBe("auto");+ });++ it("turns the legend off for a card saved with pie.show_legend false", () => {+ expect(computeLegend({ "pie.show_legend": false })).toBe("off");+ });++ it("keeps auto for a card saved with pie.show_legend true", () => {+ expect(computeLegend({ "pie.show_legend": true })).toBe("auto");+ });++ it("prefers legend.position over pie.show_legend", () => {+ expect(+ computeLegend({ "pie.show_legend": false, "legend.position": "right" }),+ ).toBe("right");+ });++ it("falls back to auto for a stored value outside the enum", () => {+ const stored: VisualizationSettings = JSON.parse(+ '{"legend.position":"middle"}',+ );++ expect(computeLegend(stored)).toBe("auto");+ });+});diff --git a/frontend/src/metabase/visualizations/visualizations/RowChart/utils/settings-definitions.ts b/frontend/src/metabase/visualizations/visualizations/RowChart/utils/settings-definitions.tsindex 92765667bd9..74c71175871 100644--- a/frontend/src/metabase/visualizations/visualizations/RowChart/utils/settings-definitions.ts+++ b/frontend/src/metabase/visualizations/visualizations/RowChart/utils/settings-definitions.ts@@ -2,6 +2,7 @@ import { t } from "ttag";import {GRAPH_GOAL_SETTINGS,+ LEGEND_POSITION_SETTINGS,TOOLTIP_SETTINGS,type VisualizationSettingsDefinitions,getDefaultDimensionLabel,@@ -339,4 +340,5 @@ export const ROW_CHART_SETTINGS: VisualizationSettingsDefinitions = {getDefault: () => "full",readDependencies: ["graph.show_values"],},+ ...LEGEND_POSITION_SETTINGS,};diff --git a/frontend/src/metabase/visualizations/visualizations/ScatterPlot/definition.ts b/frontend/src/metabase/visualizations/visualizations/ScatterPlot/definition.tsindex ed4854e0ac4..2a5d68ff442 100644--- a/frontend/src/metabase/visualizations/visualizations/ScatterPlot/definition.ts+++ b/frontend/src/metabase/visualizations/visualizations/ScatterPlot/definition.ts@@ -8,6 +8,7 @@ import {GRAPH_DATA_SETTINGS,GRAPH_GOAL_SETTINGS,GRAPH_TREND_SETTINGS,+ LEGEND_POSITION_SETTINGS,SPLIT_PANELS_SETTINGS,TIMELINE_EVENTS_SETTINGS,TOOLTIP_SETTINGS,@@ -34,6 +35,7 @@ const ScatterViz: Omit<...GRAPH_TREND_SETTINGS,...GRAPH_COLORS_SETTINGS,...GRAPH_AXIS_SETTINGS,+ ...LEGEND_POSITION_SETTINGS,...GRAPH_DATA_SETTINGS,...SPLIT_PANELS_SETTINGS,...TOOLTIP_SETTINGS,diff --git a/frontend/src/metabase/viz-core/echarts/cartesian/model/row-fold.ts b/frontend/src/metabase/viz-core/echarts/cartesian/model/row-fold.tsindex 03a244a0443..a1439f30e25 100644--- a/frontend/src/metabase/viz-core/echarts/cartesian/model/row-fold.ts+++ b/frontend/src/metabase/viz-core/echarts/cartesian/model/row-fold.ts@@ -108,3 +108,13 @@ export const foldRowChartModel = <Model extends BaseCartesianChartModel>(},};};++/** The model a chart renders at this height: a row chart folds the rows that don't fit. */+export const getChartModelAtHeight = <Model extends BaseCartesianChartModel>(+ chartModel: Model,+ height: number,+ settings: ComputedVisualizationSettings,+): Model =>+ chartModel.isRowChart+ ? foldRowChartModel(chartModel, height, settings)+ : chartModel;diff --git a/frontend/src/metabase/viz-core/echarts/pie/model/index.unit.spec.ts b/frontend/src/metabase/viz-core/echarts/pie/model/index.unit.spec.tsindex 5b50739be6e..2c339fdf4b1 100644--- a/frontend/src/metabase/viz-core/echarts/pie/model/index.unit.spec.ts+++ b/frontend/src/metabase/viz-core/echarts/pie/model/index.unit.spec.ts@@ -139,7 +139,7 @@ describe("getPieChartModel", () => {],"pie.sort_rows_dimension": ["birth_year"],series_settings: {},- "pie.show_legend": true,+ "legend.position": "auto","pie.show_total": true,"pie.show_labels": false,"pie.percent_visibility": "legend",diff --git a/frontend/src/metabase/viz-core/index.ts b/frontend/src/metabase/viz-core/index.tsindex 3b1b21b5d38..6ce57aad844 100644--- a/frontend/src/metabase/viz-core/index.ts+++ b/frontend/src/metabase/viz-core/index.ts@@ -30,8 +30,10 @@ export {export {ROW_CHART_MIN_BAR_HEIGHT,foldRowChartModel,+ getChartModelAtHeight,} from "./echarts/cartesian/model/row-fold";export { getChartLayout } from "./echarts/cartesian/layout";+export type { ChartLayoutInput } from "./echarts/cartesian/layout";export type {ChartBoundsCoords,ChartLayout,@@ -346,6 +348,10 @@ export {STACKABLE_SETTINGS,TOOLTIP_SETTINGS,} from "./lib/settings/graph";+export {+ getLegendPositionSetting,+ LEGEND_POSITION_SETTINGS,+} from "./lib/settings/legend";export { nestedSettings } from "./lib/settings/nested";export { keyForSingleSeries } from "./lib/settings/series";export { TIMELINE_EVENTS_SETTINGS } from "./lib/settings/timelineEvents";@@ -427,8 +433,8 @@ export {export {getDefaultPercentVisibility,getDefaultPieColumns,+ getDefaultLegendPosition,getDefaultShowLabels,- getDefaultShowLegend,getDefaultShowTotal,getDefaultSliceThreshold,getDefaultSortRows,diff --git a/frontend/src/metabase/viz-core/lib/settings/legend.ts b/frontend/src/metabase/viz-core/lib/settings/legend.tsnew file mode 100644index 00000000000..46e2111d86d--- /dev/null+++ b/frontend/src/metabase/viz-core/lib/settings/legend.ts@@ -0,0 +1,62 @@+import { t } from "ttag";++import {+ LEGEND_POSITIONS,+ type LegendPosition,+ type Series,+} from "metabase-types/api";+import { isLegendPosition } from "metabase-types/guards";++import type {+ ComputedVisualizationSettings,+ SeriesSettingDefinition,+ VisualizationSettingsDefinitions,+} from "../../types";++const LEGEND_POSITION_LABELS: Record<LegendPosition, () => string> = {+ auto: () => t`Auto`,+ top: () => t`Top`,+ bottom: () => t`Bottom`,+ left: () => t`Left`,+ right: () => t`Right`,+ off: () => t`Off`,+};++export const DEFAULT_LEGEND_POSITION: LegendPosition = "auto";++export const getLegendPositionSetting = (+ overrides: Pick<+ SeriesSettingDefinition,+ "getDefault" | "getHidden" | "readDependencies"+ > = {},+): SeriesSettingDefinition => ({+ getSection: () => t`Display`,+ get title() {+ return t`Legend position`;+ },+ widget: "select",+ getDefault: () => DEFAULT_LEGEND_POSITION,+ isValid: (_series, settings) => isLegendPosition(settings["legend.position"]),+ getProps: () => ({+ options: LEGEND_POSITIONS.map((value) => ({+ name: LEGEND_POSITION_LABELS[value](),+ value,+ })),+ }),+ ...overrides,+});++const hasSingleSeries = (+ series: Series,+ settings: ComputedVisualizationSettings,+) =>+ series.length <= 1 &&+ (settings["graph.dimensions"]?.length ?? 0) <= 1 &&+ (settings["graph.metrics"]?.length ?? 0) <= 1;++export const LEGEND_POSITION_SETTINGS: VisualizationSettingsDefinitions = {+ "legend.position": getLegendPositionSetting({+ getHidden: hasSingleSeries,+ readDependencies: ["graph.dimensions", "graph.metrics"],+ }),+};diff --git a/frontend/src/metabase/viz-core/lib/settings/legend.unit.spec.ts b/frontend/src/metabase/viz-core/lib/settings/legend.unit.spec.tsnew file mode 100644index 00000000000..70f8558deb9--- /dev/null+++ b/frontend/src/metabase/viz-core/lib/settings/legend.unit.spec.ts@@ -0,0 +1,93 @@+import { checkNotNull } from "metabase/utils/types";+import type { LegendPosition, VisualizationSettings } from "metabase-types/api";+import { createMockSingleSeries } from "metabase-types/api/mocks";++import { LEGEND_POSITION_SETTINGS } from "./legend";++const singleSeries = [createMockSingleSeries({ display: "line" })];++describe("LEGEND_POSITION_SETTINGS", () => {+ const setting = checkNotNull(LEGEND_POSITION_SETTINGS["legend.position"]);+ const getHidden = checkNotNull(setting.getHidden);+ const isValid = checkNotNull(setting.isValid);++ it("places the legend automatically by default", () => {+ expect(setting.getDefault?.(singleSeries, {})).toBe("auto");+ });++ it.each<LegendPosition>(["auto", "top", "bottom", "left", "right", "off"])(+ "accepts a stored %s",+ (position) => {+ expect(isValid(singleSeries, { "legend.position": position })).toBe(true);+ },+ );++ it("rejects a stored value outside the enum", () => {+ const stored: VisualizationSettings = JSON.parse(+ '{"legend.position":"middle"}',+ );++ expect(isValid(singleSeries, stored)).toBe(false);+ });++ it("offers every position in a select in the designer's order", () => {+ expect(setting.widget).toBe("select");+ expect(+ setting.getProps?.(+ singleSeries,+ {},+ () => {},+ {},+ () => {},+ ),+ ).toEqual({+ options: [+ { name: "Auto", value: "auto" },+ { name: "Top", value: "top" },+ { name: "Bottom", value: "bottom" },+ { name: "Left", value: "left" },+ { name: "Right", value: "right" },+ { name: "Off", value: "off" },+ ],+ });+ });++ it("hides the setting for a single series with one dimension and one metric", () => {+ expect(+ getHidden(singleSeries, {+ "graph.dimensions": ["CREATED_AT"],+ "graph.metrics": ["count"],+ }),+ ).toBe(true);+ });++ it("shows the setting when there are several series", () => {+ expect(+ getHidden(+ [+ createMockSingleSeries({ display: "line" }),+ createMockSingleSeries({ display: "line" }),+ ],+ { "graph.dimensions": ["CREATED_AT"], "graph.metrics": ["count"] },+ ),+ ).toBe(false);+ });++ it("shows the setting when there is a breakout", () => {+ expect(+ getHidden(singleSeries, {+ "graph.dimensions": ["CREATED_AT", "CATEGORY"],+ "graph.metrics": ["count"],+ }),+ ).toBe(false);+ });++ it("shows the setting when there are several metrics", () => {+ expect(+ getHidden(singleSeries, {+ "graph.dimensions": ["CREATED_AT"],+ "graph.metrics": ["count", "sum"],+ }),+ ).toBe(false);+ });+});diff --git a/frontend/src/metabase/viz-core/shared/settings/pie.ts b/frontend/src/metabase/viz-core/shared/settings/pie.tsindex 2708ec1b10c..115b37c1414 100644--- a/frontend/src/metabase/viz-core/shared/settings/pie.ts+++ b/frontend/src/metabase/viz-core/shared/settings/pie.ts@@ -9,6 +9,7 @@ import {import { checkNotNull, checkNumber, isNumber } from "metabase/utils/types";import {type DatasetColumn,+ type LegendPosition,type PieRow,type RawSeries,type RowValue,@@ -21,6 +22,7 @@ import { getPieColumns } from "../../echarts/pie/model";import type { ShowWarning } from "../../echarts/types";import { getHexColor } from "../../lib/color";import { getChartColor } from "../../lib/color-name";+import { DEFAULT_LEGEND_POSITION } from "../../lib/settings/legend";import { getNumberOr } from "../../lib/settings/row-values";import { getDefaultDimensionsAndMetrics } from "../../lib/utils";import { unaggregatedDataWarningPie } from "../../lib/warnings";@@ -46,7 +48,11 @@ export function getDefaultPieColumns(rawSeries: RawSeries) {};}-export const getDefaultShowLegend = () => true;+export const getDefaultLegendPosition = (+ _series: unknown,+ settings: ComputedVisualizationSettings,+): LegendPosition =>+ settings["pie.show_legend"] === false ? "off" : DEFAULT_LEGEND_POSITION;export const getDefaultShowTotal = () => true;diff --git a/frontend/src/metabase/viz-core/types/definition.ts b/frontend/src/metabase/viz-core/types/definition.tsindex a0f8e1aed5c..1d5f3352ba5 100644--- a/frontend/src/metabase/viz-core/types/definition.ts+++ b/frontend/src/metabase/viz-core/types/definition.ts@@ -289,6 +289,7 @@ export type VisualizationSettingsDefinitions = {"graph.y_axis.title_text"?: SeriesSettingDefinition<Value, Props>;"graph.y_axis.unpin_from_zero"?: SeriesSettingDefinition<Value, Props>;"legend.is_reversed"?: SeriesSettingDefinition<Value, Props>;+ "legend.position"?: SeriesSettingDefinition<Value, Props>;"line.interpolate"?: SingleSeriesSettingDefinition<Value, Props>;"line.marker_enabled"?: SingleSeriesSettingDefinition<Value, Props>;"line.missing"?: SingleSeriesSettingDefinition<Value, Props>;@@ -318,7 +319,6 @@ export type VisualizationSettingsDefinitions = {"pie.rows"?: SeriesSettingDefinition<Value, Props>;"pie.slice_threshold"?: SeriesSettingDefinition<Value, Props>;"pie.show_labels"?: SeriesSettingDefinition<Value, Props>;- "pie.show_legend"?: SeriesSettingDefinition<Value, Props>;"pie.show_total"?: SeriesSettingDefinition<Value, Props>;"pie.sort_rows"?: SeriesSettingDefinition<Value, Props>;"pie.sort_rows_dimension"?: SeriesSettingDefinition<Value, Props>;diff --git a/resources/mcp/v2/skills/visualization-settings/references/settings.md b/resources/mcp/v2/skills/visualization-settings/references/settings.mdindex 9c266a53398..5fe3cb6596a 100644--- a/resources/mcp/v2/skills/visualization-settings/references/settings.md+++ b/resources/mcp/v2/skills/visualization-settings/references/settings.md@@ -24,15 +24,17 @@ Data labels: `graph.show_values` (bool), `graph.label_value_frequency` (`"fit"`/Axes: `graph.x_axis.scale` (`"timeseries"` `"linear"` `"pow"` `"log"` `"histogram"` `"ordinal"`), `graph.y_axis.scale` (`"linear"` `"pow"` `"log"`), `graph.x_axis.axis_enabled` (`true`/`false`/`"compact"`/`"rotate-45"`/`"rotate-90"`), `graph.y_axis.axis_enabled` (bool), `graph.y_axis.auto_range` (bool) with `graph.y_axis.min`/`.max`, `graph.y_axis.unpin_from_zero` (bool), `graph.y_axis.auto_split` (bool), `graph.x_axis.title_text` / `graph.y_axis.title_text`, and `graph.y_axis.right.title_text` for the right axis of a split chart (unset or blank falls back to `graph.y_axis.title_text`).+Legend: `legend.position` (`"auto"`/`"top"`/`"bottom"`/`"left"`/`"right"`/`"off"`, default `"auto"`; not on waterfall). The legend only shows with several series or a breakout; `"off"` hides it.+Tooltip: `graph.tooltip_columns` (string[] — extra columns on hover).Extras: `scatter.bubble` (numeric column name → bubble size). Waterfall: `waterfall.increase_color`, `waterfall.decrease_color`, `waterfall.show_total` (bool), `waterfall.total_color`. Row charts: `graph.dimensions` is the y-axis (categories), x-scale `"ordinal"` only.## Part-to-whole & single value-**pie** — required `pie.dimension` (string, or array for up to 3 concentric rings), `pie.metric`. Optional: `pie.show_legend`, `pie.show_total`, `pie.show_labels`, `pie.percent_visibility` (`"off"`/`"legend"`/`"inside"`/`"both"`), `pie.decimal_places`, `pie.slice_threshold` (min % before grouping into "Other", default 2.5).+**pie** — required `pie.dimension` (string, or array for up to 3 concentric rings), `pie.metric`. Optional: `legend.position` (as for cartesian charts; replaces the deprecated `pie.show_legend`), `pie.show_total`, `pie.show_labels`, `pie.percent_visibility` (`"off"`/`"legend"`/`"inside"`/`"both"`), `pie.decimal_places`, `pie.slice_threshold` (min % before grouping into "Other", default 2.5).-**funnel** — required `funnel.dimension` (stage), `funnel.metric` (value). Optional: `funnel.type` (`"funnel"`/`"bar"`), `funnel.rows` (`[{key, name, enabled}]` step order).+**funnel** — required `funnel.dimension` (stage), `funnel.metric` (value). Optional: `funnel.type` (`"funnel"`/`"bar"`), `legend.position` (bar type only), `funnel.rows` (`[{key, name, enabled}]` step order).**gauge** — `gauge.segments`: `[{min, max, color?, label?}]` (min/max required per segment).@@ -59,7 +61,7 @@ Conditional formatting — `table.column_formatting` is a list of rules:**pivot** — needs an aggregated query built in the query builder (not native). `pivot_table.column_split`: `{"rows": [...names], "columns": [...names], "values": [...names]}`; `pivot.show_row_totals`, `pivot.show_column_totals`, `pivot.condense_duplicate_totals` (bools); `pivot_table.column_formatting` (as table's). Per-column under `column_settings`: `pivot_table.column_sort_order` (`"ascending"`/`"descending"`), `pivot_table.column_show_totals` (bool).-**map** — `map.type`: `"region"` (choropleth), `"pin"`, `"grid"`. Region: `map.region` (`"us_states"`, `"world_countries"`, or a custom-geojson key), `map.dimension`, `map.metric`, `map.colors`. Pin/grid: `map.latitude_column`, `map.longitude_column`, `map.metric_column`, `map.pin_type` (`"tiles"`/`"markers"`/`"grid"`/`"heat"`), `map.heat.radius`/`.blur`/`.min-opacity`/`.max-zoom`.+**map** — `map.type`: `"region"` (choropleth), `"pin"`, `"grid"`. Region: `map.region` (`"us_states"`, `"world_countries"`, or a custom-geojson key), `map.dimension`, `map.metric`, `map.colors`, `legend.position`. Pin/grid: `map.latitude_column`, `map.longitude_column`, `map.metric_column`, `map.pin_type` (`"tiles"`/`"markers"`/`"grid"`/`"heat"`), `map.heat.radius`/`.blur`/`.min-opacity`/`.max-zoom`.**sankey** — `sankey.source`, `sankey.target`, `sankey.value` (column names; distinct source/target, acyclic, ≤150 nodes); `sankey.node_align` (`"left"`/`"right"`/`"justify"`), `sankey.show_edge_labels` (bool), `sankey.label_value_formatting` (`"auto"`/`"compact"`/`"full"`), `sankey.edge_color` (`"gray"`/`"source"`/`"target"`).