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
Row charts echarts migration (#83378)
Nick Fitzpatrick5607adebe672
diff --git a/.loki/reference/chrome_laptop_Viz_Shared_RowChart_Default.png b/.loki/reference/chrome_laptop_Viz_Shared_RowChart_Default.pngdeleted file mode 100644index a5f7341aee1..00000000000Binary files a/.loki/reference/chrome_laptop_Viz_Shared_RowChart_Default.png and /dev/null differdiff --git a/.loki/reference/chrome_laptop_Viz_Shared_RowChart_Huge_Font.png b/.loki/reference/chrome_laptop_Viz_Shared_RowChart_Huge_Font.pngdeleted file mode 100644index c706e44bd33..00000000000Binary files a/.loki/reference/chrome_laptop_Viz_Shared_RowChart_Huge_Font.png and /dev/null differdiff --git a/.loki/reference/chrome_laptop_Viz_Static_Viz_RowChart_Default.png b/.loki/reference/chrome_laptop_Viz_Static_Viz_RowChart_Default.pngindex 85190fbfaad..6d5af7692a1 100644Binary files a/.loki/reference/chrome_laptop_Viz_Static_Viz_RowChart_Default.png and b/.loki/reference/chrome_laptop_Viz_Static_Viz_RowChart_Default.png differdiff --git a/.loki/reference/chrome_laptop_Viz_Static_Viz_RowChart_Metric_Column_With_Scaling.png b/.loki/reference/chrome_laptop_Viz_Static_Viz_RowChart_Metric_Column_With_Scaling.pngindex bab1afe3686..37369216a8c 100644Binary files a/.loki/reference/chrome_laptop_Viz_Static_Viz_RowChart_Metric_Column_With_Scaling.png and b/.loki/reference/chrome_laptop_Viz_Static_Viz_RowChart_Metric_Column_With_Scaling.png differdiff --git a/.loki/reference/chrome_laptop_Viz_Static_Viz_RowChart_Watermark.png b/.loki/reference/chrome_laptop_Viz_Static_Viz_RowChart_Watermark.pngindex 4c494ea41fa..da8668847b1 100644Binary files a/.loki/reference/chrome_laptop_Viz_Static_Viz_RowChart_Watermark.png and b/.loki/reference/chrome_laptop_Viz_Static_Viz_RowChart_Watermark.png differdiff --git a/.loki/reference/chrome_laptop_viz_RowChart_Huge_Font.png b/.loki/reference/chrome_laptop_viz_RowChart_Huge_Font.pngnew file mode 100644index 00000000000..b60672c99f1Binary files /dev/null and b/.loki/reference/chrome_laptop_viz_RowChart_Huge_Font.png differdiff --git a/.loki/reference/chrome_laptop_viz_RowChart_Two_Metrics.png b/.loki/reference/chrome_laptop_viz_RowChart_Two_Metrics.pngnew file mode 100644index 00000000000..7b7751b6bdeBinary files /dev/null and b/.loki/reference/chrome_laptop_viz_RowChart_Two_Metrics.png differdiff --git a/bun.lock b/bun.lockindex 75905cce6e7..ac0bf4e141d 100644--- a/bun.lock+++ b/bun.lock@@ -66,9 +66,7 @@"@tiptap/starter-kit": "^3.31.3","@tiptap/suggestion": "^3.31.3","@uiw/react-codemirror": "^4.23.6",- "@visx/axis": "^3.10.1","@visx/clip-path": "^3.3.0",- "@visx/grid": "^3.5.0","@visx/group": "^3.3.0","@visx/scale": "^3.5.0","@visx/shape": "^3.5.0",@@ -2075,18 +2073,12 @@"@unrs/resolver-binding-win32-x64-msvc": ["@unrs/[email protected]", "", { "os": "win32", "cpu": "x64" }, "sha512-lrW200hZdbfRtztbygyaq/6jP6AKE8qQN2KvPcJ+x7wiD038YtnYtZ82IMNJ69GJibV7bwL3y9FgK+5w/pYt6g=="],- "@visx/axis": ["@visx/[email protected]", "", { "dependencies": { "@types/react": "*", "@visx/group": "3.3.0", "@visx/point": "3.3.0", "@visx/scale": "3.5.0", "@visx/shape": "3.5.0", "@visx/text": "3.3.0", "classnames": "^2.3.1", "prop-types": "^15.6.0" } }, "sha512-HBEDLcpZoJ16hFbkYu3S6mN5mbwlFmUWY5yN967X06RdIL4LmAG3gnZ7u4F9buA3LQo+trJXW78moN005odD4Q=="],-"@visx/clip-path": ["@visx/[email protected]", "", { "dependencies": { "@types/react": "*", "prop-types": "^15.5.10" } }, "sha512-uMuI2M05qZTgUdTSHJGg4VDr2gytGmGyuaC89iByHqNaeMHkrJqQi/cOFAZi4D0dn75p7lVirJijEgDgSpcrMQ=="],"@visx/curve": ["@visx/[email protected]", "", { "dependencies": { "@types/d3-shape": "^1.3.1", "d3-shape": "^1.0.6" } }, "sha512-G1l1rzGWwIs8ka3mBhO/gj8uYK6XdU/3bwRSoiZ+MockMahQFPog0bUkuVgPwwzPSJfsA/E5u53Y/DNesnHQxg=="],- "@visx/grid": ["@visx/[email protected]", "", { "dependencies": { "@types/react": "*", "@visx/curve": "3.3.0", "@visx/group": "3.3.0", "@visx/point": "3.3.0", "@visx/scale": "3.5.0", "@visx/shape": "3.5.0", "classnames": "^2.3.1", "prop-types": "^15.6.2" } }, "sha512-i1pdobTE223ItMiER3q4ojIaZWja3vg46TkS6FotnBZ4c0VRDHSrALQPdi0na+YEgppASWCQ2WrI/vD6mIkhSg=="],-"@visx/group": ["@visx/[email protected]", "", { "dependencies": { "@types/react": "*", "classnames": "^2.3.1", "prop-types": "^15.6.2" } }, "sha512-yKepDKwJqlzvnvPS0yDuW13XNrYJE4xzT6xM7J++441nu6IybWWwextyap8ey+kU651cYDb+q1Oi6aHvQwyEyw=="],- "@visx/point": ["@visx/[email protected]", "", {}, "sha512-03eBBIJarkmX79WbeEGTUZwmS5/MUuabbiM9KfkGS9pETBTWkp1DZtEHZdp5z34x5TDQVLSi0rk1Plg3/8RtDg=="],-"@visx/scale": ["@visx/[email protected]", "", { "dependencies": { "@visx/vendor": "3.5.0" } }, "sha512-xo3zrXV2IZxrMq9Y9RUVJUpd93h3NO/r/y3GVi5F9AsbOzOhsLIbsPkunhO9mpUSR8LZ9TiumLEBrY+3frRBSg=="],"@visx/shape": ["@visx/[email protected]", "", { "dependencies": { "@types/d3-path": "^1.0.8", "@types/d3-shape": "^1.3.1", "@types/lodash": "^4.14.172", "@types/react": "*", "@visx/curve": "3.3.0", "@visx/group": "3.3.0", "@visx/scale": "3.5.0", "classnames": "^2.3.1", "d3-path": "^1.0.5", "d3-shape": "^1.2.0", "lodash": "^4.17.21", "prop-types": "^15.5.10" } }, "sha512-DP3t9jBQ7dSE3e6ptA1xO4QAIGxO55GrY/6P+S6YREuQGjZgq20TLYLAsiaoPEzFSS4tp0m12ZTPivWhU2VBTw=="],@@ -5743,12 +5735,8 @@"@unrs/resolver-binding-wasm32-wasi/@napi-rs/wasm-runtime": ["@napi-rs/[email protected]", "", { "dependencies": { "@emnapi/core": "^1.4.3", "@emnapi/runtime": "^1.4.3", "@tybys/wasm-util": "^0.10.0" } }, "sha512-ZVWUcfwY4E/yPitQJl481FjFo3K22D6qF0DuFH6Y/nbnE11GY5uguDxZMGXPQ8WQ0128MXQD7TnfHyK4oWoIJQ=="],- "@visx/axis/classnames": ["[email protected]", "", {}, "sha512-saHYOzhIQs6wy2sVxTM6bUDsQO4F50V9RQ22qBpEdCW+I+/Wmke2HOl6lS6dTpdxVhb88/I6+Hs+438c3lfUow=="],-"@visx/curve/@types/d3-shape": ["@types/[email protected]", "", { "dependencies": { "@types/d3-path": "^1" } }, "sha512-8oMzcd4+poSLGgV0R1Q1rOlx/xdmozS4Xab7np0eamFFUYq71AU9pOCJEFnkXW2aI/oXdVYJzw6pssbSut7Z9Q=="],- "@visx/grid/classnames": ["[email protected]", "", {}, "sha512-saHYOzhIQs6wy2sVxTM6bUDsQO4F50V9RQ22qBpEdCW+I+/Wmke2HOl6lS6dTpdxVhb88/I6+Hs+438c3lfUow=="],-"@visx/group/classnames": ["[email protected]", "", {}, "sha512-saHYOzhIQs6wy2sVxTM6bUDsQO4F50V9RQ22qBpEdCW+I+/Wmke2HOl6lS6dTpdxVhb88/I6+Hs+438c3lfUow=="],"@visx/shape/@types/d3-path": ["@types/[email protected]", "", {}, "sha512-4pQMp8ldf7UaB/gR8Fvvy69psNHkTpD/pVw3vmEi8iZAB9EPMBruB1JvHO4BIq9QkUUd2lV1F5YXpMNj7JPBpw=="],diff --git a/e2e/test/scenarios/dashboard/dashcard-click-behavior-reproductions.cy.spec.ts b/e2e/test/scenarios/dashboard/dashcard-click-behavior-reproductions.cy.spec.tsindex 77306a76f7d..488945cb077 100644--- a/e2e/test/scenarios/dashboard/dashcard-click-behavior-reproductions.cy.spec.ts+++ b/e2e/test/scenarios/dashboard/dashcard-click-behavior-reproductions.cy.spec.ts@@ -898,7 +898,8 @@ SELECT 'group_2', 'sub_group_2', 52, 'group_2__sub_group_2';});it("passes values from unused columns of row visualization to click behavior (metabase#46318)", () => {- cy.findAllByRole("graphics-symbol").eq(0).click();+ // One colour per sub group; bars follow the row order (group_1, group_2).+ H.chartPathWithFillColor("#98D9D9").should("have.length", 2).eq(0).click();cy.location("href").should("eq",`${Cypress.config("baseUrl")}/?q=group_1__sub_group_1`,@@ -906,7 +907,7 @@ SELECT 'group_2', 'sub_group_2', 52, 'group_2__sub_group_2';cy.go("back");- cy.findAllByRole("graphics-symbol").eq(2).click(); // intentionally eq(2), not eq(1) - that's how row viz works+ H.chartPathWithFillColor("#F2A86F").should("have.length", 2).eq(0).click();cy.location("href").should("eq",`${Cypress.config("baseUrl")}/?q=group_1__sub_group_2`,@@ -914,14 +915,14 @@ SELECT 'group_2', 'sub_group_2', 52, 'group_2__sub_group_2';cy.go("back");- cy.findAllByRole("graphics-symbol").eq(1).click(); // intentionally eq(1), not eq(2) - that's how row viz works+ H.chartPathWithFillColor("#98D9D9").should("have.length", 2).eq(1).click();cy.location("href").should("eq",`${Cypress.config("baseUrl")}/?q=group_2__sub_group_1`,);cy.go("back");- cy.findAllByRole("graphics-symbol").eq(3).click();+ H.chartPathWithFillColor("#F2A86F").should("have.length", 2).eq(1).click();cy.location("href").should("eq",`${Cypress.config("baseUrl")}/?q=group_2__sub_group_2`,diff --git a/e2e/test/scenarios/monitor/ai-auditing/usage-auditing.cy.spec.ts b/e2e/test/scenarios/monitor/ai-auditing/usage-auditing.cy.spec.tsindex f96e245ef7d..96920d37b09 100644--- a/e2e/test/scenarios/monitor/ai-auditing/usage-auditing.cy.spec.ts+++ b/e2e/test/scenarios/monitor/ai-auditing/usage-auditing.cy.spec.ts@@ -61,7 +61,7 @@ function assertChartRendered(title: string): void {.should("be.visible").parent().within(() => {- cy.findByTestId(/^(chart|row-chart)-container$/, {+ cy.findByTestId("chart-container", {timeout: CHART_RENDER_TIMEOUT,}).should("be.visible")diff --git a/e2e/test/scenarios/visualizations/charts/rows.cy.spec.js b/e2e/test/scenarios/visualizations/charts/rows.cy.spec.jsindex e0951484ad9..7cc581fa90e 100644--- a/e2e/test/scenarios/visualizations/charts/rows.cy.spec.js+++ b/e2e/test/scenarios/visualizations/charts/rows.cy.spec.js@@ -88,16 +88,20 @@ describe("scenarios > visualizations > rows", () => {});// Verify hovering bars does not change their size (metabase#43631)- cy.findByTestId("query-visualization-root")- .findByRole("graphics-symbol", { name: "51" })- .as("firstBar");- cy.get("@firstBar")- .invoke("attr", "width")- .then((prevWidth) => {- expect(Number(prevWidth)).to.be.greaterThan(0);- cy.get("@firstBar").realHover();- H.tooltip().should("contain", "51");- cy.get("@firstBar").should("have.attr", "width", prevWidth);+ H.chartPathWithFillColor("#F2A86F")+ .first()+ .then(($bar) => {+ const prevWidth = $bar[0].getBoundingClientRect().width;+ expect(prevWidth).to.be.greaterThan(0);+ cy.wrap($bar).realHover();+ H.assertEChartsTooltip({+ header: "a",+ rows: [{ name: "COLUMN_TWO", value: "51" }],+ });+ // Re-querying after the hover finds a different bar, so measure the same node.+ cy.wrap($bar).should(([hoveredBar]) => {+ expect(hoveredBar.getBoundingClientRect().width).to.equal(prevWidth);+ });});});@@ -139,19 +143,28 @@ describe("scenarios > visualizations > rows", () => {cy.findByTestId("query-visualization-root").within(() => {// Check that the visualization renders without errors- cy.findAllByRole("graphics-symbol").should("have.length.greaterThan", 0);-- // Check chart bars section - it should take 50% of width- cy.get(".visx-columns")- .should("exist")- .invoke("width")- .should("be.gt", 500);-- // Check that axis labels are present- cy.get(".visx-axis-left")- .should("exist")- .invoke("width")- .should("be.gt", 500);+ H.chartPathWithFillColor("#509EE3").should("have.length.greaterThan", 0);++ H.echartsContainer().then(([container]) => {+ const chartWidth = container.getBoundingClientRect().width;+ const widest = (elements) =>+ Math.max(+ ...[...elements].map((el) => el.getBoundingClientRect().width),+ );++ // The labels don't crowd out the bars+ H.chartPathWithFillColor("#509EE3").should((bars) => {+ expect(widest(bars)).to.be.gt(chartWidth / 3);+ });++ // Long labels are truncated to at most half the chart, not hidden+ cy.wrap(container)+ .find("text")+ .should((labels) => {+ expect(widest(labels)).to.be.gt(chartWidth / 3);+ expect(widest(labels)).to.be.at.most(chartWidth / 2);+ });+ });});});@@ -234,7 +247,7 @@ describe("scenarios > visualizations > rows", () => {},});- cy.findByTestId("goal-line-marker").trigger("mouseover");+ H.goalLineMarker().should("be.visible").trigger("mousemove");H.tooltip().within(() => {cy.findByText("Target:").should("be.visible");diff --git a/enterprise/frontend/src/metabase-enterprise/monitor/ai-auditing/metabot-analytics/components/ConversationStatsPage/BreakoutChart.unit.spec.tsx b/enterprise/frontend/src/metabase-enterprise/monitor/ai-auditing/metabot-analytics/components/ConversationStatsPage/BreakoutChart.unit.spec.tsxindex dca5c771121..c2f1aa8019f 100644--- a/enterprise/frontend/src/metabase-enterprise/monitor/ai-auditing/metabot-analytics/components/ConversationStatsPage/BreakoutChart.unit.spec.tsx+++ b/enterprise/frontend/src/metabase-enterprise/monitor/ai-auditing/metabot-analytics/components/ConversationStatsPage/BreakoutChart.unit.spec.tsx@@ -163,9 +163,8 @@ describe("metabot usage stats charts", () => {setupBreakoutChart("conversations", "row");expect(await screen.findByText(TITLES.conversations)).toBeInTheDocument();- expect(- await screen.findByTestId("row-chart-container"),- ).toBeInTheDocument();+ const container = await screen.findByTestId("chart-container");+ expect(container.querySelector("svg")).toBeInTheDocument();});it.each(METRICS)("renders the daily timeseries for %s", async (metric) => {diff --git a/frontend/src/metabase/static-viz/components/ComboChart/ComboChart.tsx b/frontend/src/metabase/static-viz/components/ComboChart/ComboChart.tsxindex ea648094425..17430125503 100644--- a/frontend/src/metabase/static-viz/components/ComboChart/ComboChart.tsx+++ b/frontend/src/metabase/static-viz/components/ComboChart/ComboChart.tsx@@ -7,16 +7,20 @@ import { withCartesianChartSize } from "metabase/static-viz/lib/rendering-conteximport { sanitizeSvgForBatik } from "metabase/static-viz/lib/svg";import {STATIC_CARTESIAN_CHART_SIZE,+ STATIC_ROW_CHART_SIZE,getChartHeight,} from "metabase/static-viz/lib/utils";import {+ foldRowChartModel,getCartesianChartModel,getCartesianChartOption,getChartLayout,getLegendItems,getSizeAdjustedSettings,+ isRowChartSeries,registerEChartsModules,} from "metabase/viz-core";+import type { RawSeries } from "metabase-types/api";import Watermark from "../../watermark.svg?component";import { DataOutOfRangeOverlay } from "../DataOutOfRangeOverlay/DataOutOfRangeOverlay";@@ -27,12 +31,17 @@ const LEGEND_PADDING = 8;registerEChartsModules();+const getDefaultSize = (rawSeries: RawSeries) =>+ isRowChartSeries(rawSeries)+ ? STATIC_ROW_CHART_SIZE+ : STATIC_CARTESIAN_CHART_SIZE;+export const ComboChart = ({rawSeries,settings: originalSettings,renderingContext: originalRenderingContext,- width = STATIC_CARTESIAN_CHART_SIZE.width,- height = STATIC_CARTESIAN_CHART_SIZE.height,+ width = getDefaultSize(rawSeries).width,+ height = getDefaultSize(rawSeries).height,isStorybook = false,hasDevWatermark = false,fitWithinBounds = false,@@ -48,14 +57,14 @@ export const ComboChart = ({height,gridSize,});- const chartModel = getCartesianChartModel(+ const baseChartModel = getCartesianChartModel(rawSeries,settings,[],renderingContext,);- const legendItems = getLegendItems(chartModel.seriesModels);+ const legendItems = getLegendItems(baseChartModel.seriesModels);const isReversed = settings["legend.is_reversed"];const { height: legendHeight, items: legendLayoutItems } =calculateLegendRows({@@ -68,6 +77,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 chart = init(null, null, {renderer: "svg",ssr: true,diff --git a/frontend/src/metabase/static-viz/components/ComboChart/ComboChart.unit.spec.tsx b/frontend/src/metabase/static-viz/components/ComboChart/ComboChart.unit.spec.tsxnew file mode 100644index 00000000000..818f6cfda72--- /dev/null+++ b/frontend/src/metabase/static-viz/components/ComboChart/ComboChart.unit.spec.tsx@@ -0,0 +1,377 @@+import { render, screen } from "@testing-library/react";++import { StaticVisualization } from "metabase/static-viz/components/StaticVisualization";+import { createStaticRenderingContext } from "metabase/static-viz/lib/rendering-context";+import type { RawSeries, VisualizationSettings } from "metabase-types/api";+import {+ createMockCard,+ createMockColumn,+ createMockDatasetData,+} from "metabase-types/api/mocks";++const CATEGORIES = Array.from({ length: 16 }, (_, index) => `C${index + 1}`);+// Offsets keep segment values clear of the round numbers used as axis ticks.+const SOURCE_A_VALUES = CATEGORIES.map((_, index) => 1003 + index);+const SOURCE_B_VALUES = CATEGORIES.map((_, index) => 2005 + index);+const STACK_TOTALS = CATEGORIES.map(+ (_, index) => SOURCE_A_VALUES[index] + SOURCE_B_VALUES[index],+);++const createStackedRowSeries = (+ settings: VisualizationSettings = {},+): RawSeries => [+ {+ card: createMockCard({+ display: "row",+ visualization_settings: {+ "graph.dimensions": ["CATEGORY", "SOURCE"],+ "graph.metrics": ["count"],+ "stackable.stack_type": "stacked",+ "graph.show_values": true,+ ...settings,+ },+ }),+ data: createMockDatasetData({+ cols: [+ createMockColumn({+ name: "CATEGORY",+ display_name: "Category",+ base_type: "type/Text",+ semantic_type: "type/Category",+ source: "breakout",+ }),+ createMockColumn({+ name: "SOURCE",+ display_name: "Source",+ id: 2,+ field_ref: ["field", 2, null],+ base_type: "type/Text",+ semantic_type: "type/Category",+ source: "breakout",+ }),+ createMockColumn({+ name: "count",+ display_name: "Count",+ base_type: "type/Integer",+ semantic_type: "type/Quantity",+ source: "aggregation",+ }),+ ],+ rows: CATEGORIES.flatMap((category, index) => [+ [category, "A", SOURCE_A_VALUES[index]],+ [category, "B", SOURCE_B_VALUES[index]],+ ]),+ }),+ },+];++const setup = ({+ settings,+ width,+}: {+ settings?: VisualizationSettings;+ width: number;+}) => {+ render(+ <StaticVisualization+ rawSeries={createStackedRowSeries(settings)}+ renderingContext={createStaticRenderingContext()}+ width={width}+ height={900}+ />,+ );++ const countRendered = (values: number[]) =>+ values.filter(+ (value) =>+ screen.queryAllByText(value.toLocaleString("en-US")).length > 0,+ ).length;++ return { countRendered };+};++const CHART_HEIGHT = 440;+const AXIS_TITLE_FONT_SIZE = 13;++const categoryColumn = createMockColumn({+ name: "CATEGORY",+ display_name: "Category",+ base_type: "type/Text",+ semantic_type: "type/Category",+ source: "breakout",+});++const metricColumns = [+ createMockColumn({+ name: "count",+ display_name: "Count",+ base_type: "type/Integer",+ semantic_type: "type/Quantity",+ source: "aggregation",+ }),+ createMockColumn({+ name: "sum",+ display_name: "Sum of Total",+ id: 3,+ field_ref: ["field", 3, null],+ base_type: "type/Integer",+ semantic_type: "type/Quantity",+ source: "aggregation",+ }),+];++const createGroupedRowSeries = ({+ metricCount,+ settings = {},+ getValue = (rowIndex, metricIndex) => 100 * (rowIndex + metricIndex + 1),+ categories = ["Doohickey", "Gadget", "Gizmo", "Widget"],+}: {+ metricCount: 1 | 2;+ settings?: VisualizationSettings;+ getValue?: (rowIndex: number, metricIndex: number) => number;+ categories?: string[];+}): RawSeries => {+ const metrics = metricColumns.slice(0, metricCount);+ return [+ {+ card: createMockCard({+ display: "row",+ visualization_settings: {+ "graph.dimensions": ["CATEGORY"],+ "graph.metrics": metrics.map((column) => column.name),+ ...settings,+ },+ }),+ data: createMockDatasetData({+ cols: [categoryColumn, ...metrics],+ rows: categories.map((category, index) => [+ category,+ ...metrics.map((_, metricIndex) => getValue(index, metricIndex)),+ ]),+ }),+ },+ ];+};++// ECharts SSR positions text with `translate(x y)`, or `matrix(a,b,c,d,x,y)`+// when rotated, and centres it on that anchor (`dominant-baseline="central"`).+const TRANSLATE_PATTERN = /^translate\((?<x>[-\d.]+) (?<y>[-\d.]+)\)$/;+const MATRIX_PATTERN = /^matrix\((?:[-\d.]+,){4}(?<x>[-\d.]+),(?<y>[-\d.]+)\)$/;++const parseTranslation = (transform: string | null) => {+ const match =+ transform?.match(TRANSLATE_PATTERN) ?? transform?.match(MATRIX_PATTERN);+ const groups = match?.groups;+ return groups ? { x: Number(groups.x), y: Number(groups.y) } : null;+};++const getTextAnchors = (text: string) =>+ screen+ .queryAllByText(text)+ .map((element) => parseTranslation(element.getAttribute("transform")))+ .filter((anchor) => anchor !== null);++const renderRowChart = (rawSeries: RawSeries) =>+ render(+ <StaticVisualization+ rawSeries={rawSeries}+ renderingContext={createStaticRenderingContext()}+ width={620}+ height={CHART_HEIGHT}+ />,+ );++describe("static row chart", () => {+ it("folds like the legacy static row chart when no size is given", () => {+ render(+ <StaticVisualization+ rawSeries={createGroupedRowSeries({+ metricCount: 1,+ categories: Array.from({ length: 40 }, (_, index) => `C${index + 1}`),+ getValue: () => 100,+ })}+ renderingContext={createStaticRenderingContext()}+ />,+ );++ // The legacy 440px height fits 18 rows: 17 kept, then "Other" for 23 more.+ expect(screen.getByText("Other (23)")).toBeInTheDocument();+ });++ it("extends the metric axis to the folded Other row's total", () => {+ renderRowChart(+ createGroupedRowSeries({+ metricCount: 1,+ categories: Array.from({ length: 40 }, (_, index) => `C${index + 1}`),+ getValue: () => 100,+ }),+ );++ // Rows of 100 fold into an "Other" worth thousands; the axis must reach it.+ expect(screen.getByText(/^Other \(\d+\)$/)).toBeInTheDocument();+ expect(screen.getByText("1,000")).toBeInTheDocument();+ });++ describe("folded Other row labels", () => {+ const FOLDED_CATEGORIES = Array.from(+ { length: 40 },+ (_, index) => `C${index + 1}`,+ );++ const getFoldedRowCount = () =>+ Number(+ /\((\d+)\)/.exec(+ screen.getByText(/^Other \(\d+\)$/).textContent ?? "",+ )?.[1],+ );++ it("labels the Other row's value", () => {+ renderRowChart(+ createGroupedRowSeries({+ metricCount: 1,+ categories: FOLDED_CATEGORIES,+ getValue: () => 13,+ settings: { "graph.show_values": true },+ }),+ );++ // Labels render twice: an outline stroke and the fill.+ expect(+ screen.getAllByText(String(getFoldedRowCount() * 13)).length,+ ).toBeGreaterThan(0);+ });++ it("labels the Other row's stack total", () => {+ const sourceColumn = createMockColumn({+ name: "SOURCE",+ display_name: "Source",+ id: 2,+ field_ref: ["field", 2, null],+ base_type: "type/Text",+ semantic_type: "type/Category",+ source: "breakout",+ });+ renderRowChart([+ {+ card: createMockCard({+ display: "row",+ visualization_settings: {+ "graph.dimensions": ["CATEGORY", "SOURCE"],+ "graph.metrics": ["count"],+ "stackable.stack_type": "stacked",+ "graph.show_values": true,+ },+ }),+ data: createMockDatasetData({+ cols: [categoryColumn, sourceColumn, metricColumns[0]],+ rows: FOLDED_CATEGORIES.flatMap((category) => [+ [category, "A", 10],+ [category, "B", 7],+ ]),+ }),+ },+ ]);++ // Labels render twice: an outline stroke and the fill.+ expect(+ screen.getAllByText(String(getFoldedRowCount() * 17)).length,+ ).toBeGreaterThan(0);+ });+ });++ it("keeps the dimension axis title inside the chart with more than one metric", () => {+ renderRowChart(createGroupedRowSeries({ metricCount: 2 }));++ const [title] = getTextAnchors("Category");+ expect(title.x - AXIS_TITLE_FONT_SIZE / 2).toBeGreaterThanOrEqual(0);+ });++ it("keeps the metric axis title inside the chart when the dimension title is hidden", () => {+ renderRowChart(+ createGroupedRowSeries({+ metricCount: 1,+ settings: { "graph.x_axis.labels_enabled": false },+ }),+ );++ const [title] = getTextAnchors("Count");+ expect(title.y + AXIS_TITLE_FONT_SIZE / 2).toBeLessThanOrEqual(+ CHART_HEIGHT,+ );+ });++ it.each([+ ["an automatic", {}],+ [+ "a manual",+ {+ "graph.y_axis.auto_range": false,+ "graph.y_axis.min": -380,+ "graph.y_axis.max": 420,+ },+ ],+ ])(+ "keeps a negative bar's value label clear of its category label with %s axis range",+ (_range, rangeSettings) => {+ const values = [420, -380, 310, -260];+ renderRowChart(+ createGroupedRowSeries({+ metricCount: 1,+ settings: { "graph.show_values": true, ...rangeSettings },+ getValue: (rowIndex) => values[rowIndex],+ }),+ );++ const { measureText, fontFamily, theme } = createStaticRenderingContext();+ const labelWidth = measureText("-380", {+ family: fontFamily,+ size: theme.cartesian.label.fontSize,+ weight: 700,+ });+ // Both labels are right-aligned at their anchor.+ const [label] = getTextAnchors("-380");+ const [category] = getTextAnchors("Gadget");+ expect(label.x - labelWidth).toBeGreaterThan(category.x);+ },+ );++ it("keeps the goal label inside the chart when values are shown", () => {+ renderRowChart(+ createGroupedRowSeries({+ metricCount: 1,+ settings: {+ "graph.show_goal": true,+ "graph.goal_value": 250,+ "graph.goal_label": "Target",+ "graph.show_values": true,+ },+ }),+ );++ const [label] = getTextAnchors("Target");+ expect(label.y - AXIS_TITLE_FONT_SIZE / 2).toBeGreaterThanOrEqual(0);+ });++ it.each([300, 620])(+ "labels every stack total on a %ipx-wide chart",+ (width) => {+ const { countRendered } = setup({ width });++ expect(countRendered(STACK_TOTALS)).toBe(CATEGORIES.length);+ },+ );++ it.each(["series", "all"] as const)(+ "ignores a stored show_stack_values of %s carried over from a bar chart",+ (showStackValues) => {+ const { countRendered } = setup({+ width: 620,+ settings: { "graph.show_stack_values": showStackValues },+ });++ expect(countRendered(STACK_TOTALS)).toBe(CATEGORIES.length);+ expect(countRendered(SOURCE_A_VALUES)).toBe(0);+ expect(countRendered(SOURCE_B_VALUES)).toBe(0);+ },+ );+});diff --git a/frontend/src/metabase/static-viz/components/RowChart/stories-data.ts b/frontend/src/metabase/static-viz/components/ComboChart/stories-data/row-chart.tssimilarity index 99%rename from frontend/src/metabase/static-viz/components/RowChart/stories-data.tsrename to frontend/src/metabase/static-viz/components/ComboChart/stories-data/row-chart.tsindex 714e296f7fd..d1f7b8c49cc 100644--- a/frontend/src/metabase/static-viz/components/RowChart/stories-data.ts+++ b/frontend/src/metabase/static-viz/components/ComboChart/stories-data/row-chart.ts@@ -8,7 +8,7 @@ import {type RenderingContext,} from "metabase/viz-core";-import type { StaticChartProps } from "../StaticVisualization";+import type { StaticChartProps } from "../../StaticVisualization";export const renderingContext: RenderingContext = {getColor: color,diff --git a/frontend/src/metabase/static-viz/components/RowChart/RowChart.stories.tsx b/frontend/src/metabase/static-viz/components/ComboChart/stories/RowChart.stories.tsxsimilarity index 88%rename from frontend/src/metabase/static-viz/components/RowChart/RowChart.stories.tsxrename to frontend/src/metabase/static-viz/components/ComboChart/stories/RowChart.stories.tsxindex dc0f0be2004..a458db640e1 100644--- a/frontend/src/metabase/static-viz/components/RowChart/RowChart.stories.tsx+++ b/frontend/src/metabase/static-viz/components/ComboChart/stories/RowChart.stories.tsx@@ -1,15 +1,15 @@import type { StoryFn } from "@storybook/react";-import {- METRIC_COLUMN_WITH_SCALING,- MULTIPLE_SERIES,-} from "metabase/static-viz/components/RowChart/stories-data";import { color } from "metabase/ui/colors";import {type StaticChartProps,StaticVisualization,-} from "../StaticVisualization";+} from "../../StaticVisualization";+import {+ METRIC_COLUMN_WITH_SCALING,+ MULTIPLE_SERIES,+} from "../stories-data/row-chart";export default {title: "Viz/Static Viz/RowChart",diff --git a/frontend/src/metabase/static-viz/components/RowChart/RowChart.tsx b/frontend/src/metabase/static-viz/components/RowChart/RowChart.tsxdeleted file mode 100644index 752425d71ad..00000000000--- a/frontend/src/metabase/static-viz/components/RowChart/RowChart.tsx+++ /dev/null@@ -1,156 +0,0 @@-import { Group } from "@visx/group";--import type { StaticChartProps } from "metabase/static-viz/components/StaticVisualization";-import { measureTextWidth } from "metabase/static-viz/lib/text";-import { getChartHeight } from "metabase/static-viz/lib/utils";-import type { FontStyle, TextWidthMeasurer } from "metabase/utils/measure-text";-import {- getColumnValueFormatter,- getFormatters,- getLabelsFormatter,-} from "metabase/visualizations/visualizations/RowChart/utils/format";-import { getLegendItems } from "metabase/visualizations/visualizations/RowChart/utils/legend";-import {- getAxesVisibility,- getLabelledSeries,- getLabels,- getXValueRange,-} from "metabase/visualizations/visualizations/RowChart/utils/settings";-import {- RowChart,- getChartGoal,- getGroupedDataset,- getStackOffset,- getStaticChartTheme,- getTwoDimensionalChartSeries,- trimData,-} from "metabase/viz-core";--import Watermark from "../../watermark.svg?component";-import { Legend } from "../Legend";-import { calculateLegendRows } from "../Legend/utils";--const CHART_PADDING = 16;-const LEGEND_FONT = {- lineHeight: 20,- size: 14,- weight: 700,-};--const WIDTH = 620;-const HEIGHT = 440;--const staticTextMeasurer: TextWidthMeasurer = (- text: string,- style: FontStyle,-) =>- measureTextWidth(- text,- parseInt(style.size.toString(), 10),- style.weight ? parseInt(style.weight.toString(), 10) : 400,- );--export const StaticRowChart = ({- rawSeries,- settings,- renderingContext,- width = WIDTH,- height = HEIGHT,- hasDevWatermark = false,- fitWithinBounds = false,-}: StaticChartProps) => {- const data = rawSeries[0].data;- const { getColor } = renderingContext;- const columnValueFormatter = getColumnValueFormatter();-- const { chartColumns, series, seriesColors } = getTwoDimensionalChartSeries(- data,- settings,- columnValueFormatter,- );- const groupedData = getGroupedDataset(- data,- chartColumns,- settings,- columnValueFormatter,- );- const labelsFormatter = getLabelsFormatter(chartColumns, settings);- const goal = getChartGoal(settings);- const theme = getStaticChartTheme(getColor);- const stackOffset = getStackOffset(settings);-- const tickFormatters = getFormatters(chartColumns, settings);-- const { xLabel, yLabel } = getLabels(settings);-- const { hasXAxis, hasYAxis } = getAxesVisibility(settings);- const xValueRange = getXValueRange(settings);- const labelledSeries = getLabelledSeries(settings, series);-- const legendItems = getLegendItems(series, seriesColors);- const legend = calculateLegendRows({- items: legendItems,- width,- lineHeight: LEGEND_FONT.lineHeight,- fontSize: LEGEND_FONT.size,- fontWeight: LEGEND_FONT.weight,- });-- const legendHeight = legend != null ? legend.height + CHART_PADDING : 0;- const chartHeight = getChartHeight({ fitWithinBounds, legendHeight, height });-- const fullChartHeight = fitWithinBounds ? height : height + legendHeight;-- return (- <svg- xmlns="http://www.w3.org/2000/svg"- width={width}- height={fullChartHeight}- fontFamily="Lato"- >- {legend.items.length > 0 && (- <Legend- items={legend.items}- top={CHART_PADDING}- fontSize={LEGEND_FONT.size}- fontWeight={LEGEND_FONT.weight}- />- )}- <Group top={legendHeight}>- <RowChart- width={width}- height={chartHeight}- data={groupedData}- trimData={trimData}- series={series}- seriesColors={seriesColors}- goal={goal}- theme={theme}- stackOffset={stackOffset}- tickFormatters={tickFormatters}- labelsFormatter={labelsFormatter}- measureTextWidth={staticTextMeasurer}- xLabel={xLabel}- yLabel={yLabel}- hasXAxis={hasXAxis}- hasYAxis={hasYAxis}- xScaleType={settings["graph.y_axis.scale"]}- xValueRange={xValueRange}- labelledSeries={labelledSeries}- isStatic- />- </Group>- {hasDevWatermark && (- <Watermark- x="0"- y="0"- height={fullChartHeight}- width={width}- preserveAspectRatio="xMinYMin slice"- fill={renderingContext.getColor("text-secondary")}- opacity={0.2}- />- )}- </svg>- );-};diff --git a/frontend/src/metabase/static-viz/components/RowChart/index.ts b/frontend/src/metabase/static-viz/components/RowChart/index.tsdeleted file mode 100644index 7864b3a75f1..00000000000--- a/frontend/src/metabase/static-viz/components/RowChart/index.ts+++ /dev/null@@ -1 +0,0 @@-export { StaticRowChart } from "./RowChart";diff --git a/frontend/src/metabase/static-viz/components/StaticVisualization/StaticVisualization.tsx b/frontend/src/metabase/static-viz/components/StaticVisualization/StaticVisualization.tsxindex f0a0037b540..fee5872df7b 100644--- a/frontend/src/metabase/static-viz/components/StaticVisualization/StaticVisualization.tsx+++ b/frontend/src/metabase/static-viz/components/StaticVisualization/StaticVisualization.tsx@@ -10,7 +10,6 @@ import { ComboChart } from "../ComboChart";import { FunnelBarChart } from "../FunnelBarChart";import { PieChart } from "../PieChart/PieChart";import { ProgressBar } from "../ProgressBar";-import { StaticRowChart } from "../RowChart/RowChart";import { SankeyChart } from "../SankeyChart";import { ScalarChart } from "../ScalarChart";import { ScatterPlot } from "../ScatterPlot/ScatterPlot";@@ -29,7 +28,7 @@ export const StaticVisualization = ({height,fitWithinBounds,gridSize,-}: StaticVisualizationProps) => {+}: StaticVisualizationProps): JSX.Element => {const display = rawSeries[0].card.display;const transformedSeries = getVisualizationTransformed(rawSeries).series;const settings = getComputedSettingsForSeries(transformedSeries);@@ -50,6 +49,7 @@ export const StaticVisualization = ({case "area":case "bar":case "combo":+ case "row":return <ComboChart {...props} />;case "scatter":return <ScatterPlot {...props} />;@@ -71,9 +71,6 @@ export const StaticVisualization = ({return <TreemapChart {...props} />;case "progress":return <ProgressBar {...props} />;- case "row":- // TODO: replace with an ECharts implementation- return <StaticRowChart {...props} />;}throw new Error(`Unsupported display type: ${display}`);diff --git a/frontend/src/metabase/static-viz/lib/utils.ts b/frontend/src/metabase/static-viz/lib/utils.tsindex 5b0bf5c2fb9..0edcfca3fc8 100644--- a/frontend/src/metabase/static-viz/lib/utils.ts+++ b/frontend/src/metabase/static-viz/lib/utils.ts@@ -3,6 +3,12 @@ export const STATIC_CARTESIAN_CHART_SIZE = {height: 360,} as const;+// Row charts keep the size the legacy static row chart (v64 or earlier) was drawn at.+export const STATIC_ROW_CHART_SIZE = {+ width: 620,+ height: 440,+} as const;+export const getChartHeight = ({fitWithinBounds,height,diff --git a/frontend/src/metabase/visualizations/components/ChartTooltip/ChartTooltip.tsx b/frontend/src/metabase/visualizations/components/ChartTooltip/ChartTooltip.tsxindex 56799d3ff8b..ac964225dd8 100644--- a/frontend/src/metabase/visualizations/components/ChartTooltip/ChartTooltip.tsx+++ b/frontend/src/metabase/visualizations/components/ChartTooltip/ChartTooltip.tsx@@ -8,7 +8,6 @@ import type { HoveredObject } from "metabase/viz-core";import type { VisualizationSettings } from "metabase-types/api";import KeyValuePairChartTooltip from "./KeyValuePairChartTooltip";-import StackedDataTooltip from "./StackedDataTooltip";export interface ChartTooltipProps {hovered?: HoveredObject | null;@@ -45,10 +44,6 @@ export const ChartTooltipContent = ({return null;}- if (hovered.stackedTooltipModel) {- return <StackedDataTooltip {...hovered.stackedTooltipModel} />;- }-return <KeyValuePairChartTooltip hovered={hovered} settings={settings} />;};@@ -69,7 +64,6 @@ const ChartTooltip = ({}return (hovered.value !== undefined ||- !_.isEmpty(hovered.stackedTooltipModel) ||!_.isEmpty(hovered.data) ||!_.isEmpty(hovered.dimensions));@@ -89,14 +83,12 @@ const ChartTooltip = ({const lastDisplayRef = useRef<{content: ReactNode;rect: TargetRect;- isPadded: boolean;} | null>(null);if (isOpen) {lastDisplayRef.current = {content: tooltip,rect: targetRect,- isPadded: !hovered?.stackedTooltipModel,};}@@ -107,12 +99,7 @@ const ChartTooltip = ({<Tooltipopened={isOpen}label={display?.content ?? null}- styles={{- tooltip: {- maxWidth: "unset",- ...(display?.isPadded === false ? { padding: 0 } : null),- },- }}+ styles={{ tooltip: { maxWidth: "unset" } }}><Boxdata-testid="chart-tooltip-proxy"diff --git a/frontend/src/metabase/visualizations/components/ChartTooltip/StackedDataTooltip/StackedDataTooltip.module.css b/frontend/src/metabase/visualizations/components/ChartTooltip/StackedDataTooltip/StackedDataTooltip.module.cssdeleted file mode 100644index c9aeec725f4..00000000000--- a/frontend/src/metabase/visualizations/components/ChartTooltip/StackedDataTooltip/StackedDataTooltip.module.css+++ /dev/null@@ -1,23 +0,0 @@-.tableRowSpacing::after {- line-height: var(--mantine-spacing-sm);- content: " ";- display: block;- white-space: pre;-}--.dataPointTable {- border-collapse: collapse;- margin: 0 0.75rem 0.75rem 0.75rem;-}--.dataPointTableBody {- border-top: 1px solid var(--mb-color-background_page-secondary-inverse);-}--.dataPointTableBody::before,-.dataPointTableFooter::before {- line-height: var(--mantine-spacing-sm);- content: " ";- display: block;- white-space: pre;-}diff --git a/frontend/src/metabase/visualizations/components/ChartTooltip/StackedDataTooltip/StackedDataTooltip.tsx b/frontend/src/metabase/visualizations/components/ChartTooltip/StackedDataTooltip/StackedDataTooltip.tsxdeleted file mode 100644index 8068eef6f9c..00000000000--- a/frontend/src/metabase/visualizations/components/ChartTooltip/StackedDataTooltip/StackedDataTooltip.tsx+++ /dev/null@@ -1,121 +0,0 @@-import { useMemo } from "react";--import { Box, Stack } from "metabase/ui";-import { color } from "metabase/ui/colors";-import {- type StackedTooltipModel,- getPercent,- getSortedRows,- getTotalValue,- groupExcessiveTooltipRows,-} from "metabase/viz-core";--import { TooltipRow, TooltipTotalRow } from "../TooltipRow";--import S from "./StackedDataTooltip.module.css";--const MAX_BODY_ROWS = 8;--type StackedDataTooltipProps = StackedTooltipModel;--const StackedDataTooltip = ({- headerTitle,- headerRows,- bodyRows = [],- grandTotal,- showTotal,- showPercentages,- totalFormatter = (value: unknown) => String(value),-}: StackedDataTooltipProps) => {- const sortedHeaderRows = useMemo(- () => getSortedRows(headerRows),- [headerRows],- );- const sortedBodyRows = useMemo(() => getSortedRows(bodyRows), [bodyRows]);- const rowsTotal = useMemo(- () => getTotalValue(sortedHeaderRows, sortedBodyRows),- [sortedHeaderRows, sortedBodyRows],- );-- const isShowingTotalSensible =- sortedHeaderRows.length + sortedBodyRows.length > 1;- const hasColorIndicators = useMemo(- () =>- [...sortedBodyRows, ...sortedHeaderRows].some((row) => row.color != null),- [sortedHeaderRows, sortedBodyRows],- );-- // For some charts such as PieChart we intentionally show only certain data rows that do not represent the full data.- // In order to calculate percentages correctly we provide the grand total value- const percentCalculationTotal = grandTotal ?? rowsTotal;-- const trimmedBodyRows = groupExcessiveTooltipRows(- sortedBodyRows,- MAX_BODY_ROWS,- hasColorIndicators ? color("text-disabled") : undefined,- );-- return (- <Stack gap={0} pt="lg">- {headerTitle && (- <Box- component="header"- tt="uppercase"- fz="sm"- px="xl"- pb="xxs"- data-testid="tooltip-header"- >- {headerTitle}- </Box>- )}- <table className={S.dataPointTable}>- <thead- className={sortedBodyRows.length > 0 ? S.tableRowSpacing : undefined}- >- {sortedHeaderRows.map((row, index) => (- <TooltipRow- key={index}- isHeader- percent={- showPercentages ? getPercent(rowsTotal, row.value) : undefined- }- {...row}- />- ))}- </thead>-- {trimmedBodyRows.length > 0 && (- <tbody className={S.dataPointTableBody}>- {trimmedBodyRows.map((row, index) => (- <TooltipRow- key={index}- percent={- showPercentages ? getPercent(rowsTotal, row.value) : undefined- }- {...row}- />- ))}- </tbody>- )}-- {showTotal && isShowingTotalSensible && (- <tfoot className={S.dataPointTableFooter}>- <TooltipTotalRow- value={totalFormatter(rowsTotal)}- hasIcon={hasColorIndicators}- percent={- showPercentages- ? getPercent(percentCalculationTotal, rowsTotal)- : undefined- }- />- </tfoot>- )}- </table>- </Stack>- );-};--// eslint-disable-next-line import/no-default-export -- deprecated usage-export default StackedDataTooltip;diff --git a/frontend/src/metabase/visualizations/components/ChartTooltip/StackedDataTooltip/StackedDataTooltip.unit.spec.tsx b/frontend/src/metabase/visualizations/components/ChartTooltip/StackedDataTooltip/StackedDataTooltip.unit.spec.tsxdeleted file mode 100644index 472e314261a..00000000000--- a/frontend/src/metabase/visualizations/components/ChartTooltip/StackedDataTooltip/StackedDataTooltip.unit.spec.tsx+++ /dev/null@@ -1,188 +0,0 @@-import _ from "underscore";--import { renderWithProviders, screen } from "__support__/ui";-import type { StackedTooltipModel } from "metabase/viz-core";--import StackedDataTooltip from "./StackedDataTooltip";--const defaultHeaderRows = [- {- color: "red",- name: "2020",- value: 300,- formatter: (value: unknown) => `(${value})`,- },-];--const defaultBodyRows = [- {- color: "green",- name: "2019",- value: 200,- formatter: (value: unknown) => `_${value}_`,- },- {- color: "blue",- name: "2018",- value: 100,- formatter: (value: unknown) => `[${value}]`,- },-];--const setup = ({- headerTitle = "header-title",- headerRows = defaultHeaderRows,- bodyRows = defaultBodyRows,- ...rest-}: Partial<StackedTooltipModel> = {}) => {- renderWithProviders(- <StackedDataTooltip- headerTitle={headerTitle}- headerRows={headerRows}- bodyRows={bodyRows}- {...rest}- />,- );-- const header = screen.queryByTestId("tooltip-header");- const rowNames = screen- .queryAllByTestId("row-name")- .map((el) => el.innerHTML);- const rowValues = screen- .queryAllByTestId("row-value")- .map((el) => el.innerHTML);- const rowPercents = screen- .queryAllByTestId("row-percent")- .map((el) => el.innerHTML);-- return {- header,- rowNames,- rowValues,- rowPercents,- };-};--describe("StackedDataTooltip", () => {- it("renders the header with formatted name—value pairs", () => {- const { rowNames, rowValues, header } = setup();- expect(header).toHaveTextContent("header-title");- expect(rowNames).toStrictEqual(["2020", "2019", "2018"]);- expect(rowValues).toStrictEqual(["(300)", "_200_", "[100]"]);- });-- it("does not percentages when showPercentages is falsy", () => {- const { rowPercents } = setup();- expect(rowPercents).toStrictEqual([]);- });-- it("renders percentages when showPercentages=true", () => {- const { rowPercents } = setup({ showPercentages: true });- expect(rowPercents).toStrictEqual(["50.00 %", "33.33 %", "16.67 %"]);- });-- it("renders the total row when showTotal=true", () => {- const { rowNames, rowValues } = setup({ showTotal: true });- expect(rowNames[rowNames.length - 1]).toBe("Total");- expect(rowValues[rowValues.length - 1]).toBe("600");- });-- it("groups excessive tooltip rows", () => {- const bodyRows = _.range(10).map((rowNumber) => ({- color: "red",- name: `body row ${rowNumber}`,- value: rowNumber * 100,- }));-- const { rowNames, rowValues } = setup({- showTotal: true,- headerRows: [],- bodyRows,- });-- expect(rowNames).toStrictEqual([- "body row 9",- "body row 8",- "body row 7",- "body row 6",- "body row 5",- "body row 4",- "body row 3",- "Other",- "Total",- ]);-- expect(rowValues).toStrictEqual([- "900",- "800",- "700",- "600",- "500",- "400",- "300",- "300",- "4500",- ]);- });-- it("sorts rows by value from highest to lowest", () => {- const unsortedRows = [- {- color: "red",- name: "100",- value: 100,- },- {- color: "red",- name: "null",- value: null,- },- {- color: "red",- name: "50",- value: 50,- },- {- color: "red",- name: "200",- value: 200,- },- ];-- const { rowNames, rowValues } = setup({- showTotal: true,- headerRows: unsortedRows,- bodyRows: unsortedRows,- });-- expect(rowNames).toStrictEqual([- // header- "200",- "100",- "50",- "null",- // body- "200",- "100",- "50",- "null",- // total- "Total",- ]);-- expect(rowValues).toStrictEqual([- // header- "200",- "100",- "50",- "null",- // body- "200",- "100",- "50",- "null",- // total- "700",- ]);- });-});diff --git a/frontend/src/metabase/visualizations/components/ChartTooltip/StackedDataTooltip/index.ts b/frontend/src/metabase/visualizations/components/ChartTooltip/StackedDataTooltip/index.tsdeleted file mode 100644index a1a5f236960..00000000000--- a/frontend/src/metabase/visualizations/components/ChartTooltip/StackedDataTooltip/index.ts+++ /dev/null@@ -1,2 +0,0 @@-// eslint-disable-next-line import/no-default-export -- deprecated usage-export { default } from "./StackedDataTooltip";diff --git a/frontend/src/metabase/visualizations/components/ChartTooltip/TooltipRow/TooltipRow.module.css b/frontend/src/metabase/visualizations/components/ChartTooltip/TooltipRow/TooltipRow.module.cssdeleted file mode 100644index 7b946251e85..00000000000--- a/frontend/src/metabase/visualizations/components/ChartTooltip/TooltipRow/TooltipRow.module.css+++ /dev/null@@ -1,67 +0,0 @@-.tooltipRowRoot {- font-size: var(--mantine-font-size-sm);-}--.header {- font-size: var(--mantine-font-size-md);-}--.colorIndicator {- display: block;- margin: 0 auto;- width: 0.5rem;- height: 0.5rem;- border-radius: 100%;-}--.colorIndicatorLarge {- width: 0.75rem;- height: 0.75rem;-}--.cell {- vertical-align: middle;- padding: 0.375rem var(--mantine-spacing-sm);- font-weight: 700;- overflow: hidden;- text-overflow: ellipsis;- white-space: nowrap;- max-width: 13.75rem;-- &:first-of-type,- &:last-of-type {- padding-left: 0.75rem;- padding-right: 0.75rem;- }-- &:first-of-type {- border-top-left-radius: var(--mantine-radius-xxs);- border-bottom-left-radius: var(--mantine-radius-xxs);- }-- &:last-of-type {- border-bottom-right-radius: var(--mantine-radius-xxs);- border-top-right-radius: var(--mantine-radius-xxs);- }-}--.colorIndicatorCell {- width: 1%;- text-align: center;- padding-right: var(--mantine-spacing-xxs);-}--.valueCell {- padding-left: var(--mantine-spacing-xxl);- text-align: right;-}--.percentCell {- padding-left: var(--mantine-spacing-lg);- color: var(--mb-color-tooltip-text-secondary);- text-align: right;-}--.totalRowRoot {- background-color: var(--mb-color-tooltip-background-focused);-}diff --git a/frontend/src/metabase/visualizations/components/ChartTooltip/TooltipRow/TooltipRow.tsx b/frontend/src/metabase/visualizations/components/ChartTooltip/TooltipRow/TooltipRow.tsxdeleted file mode 100644index f0c6fd3da56..00000000000--- a/frontend/src/metabase/visualizations/components/ChartTooltip/TooltipRow/TooltipRow.tsx+++ /dev/null@@ -1,72 +0,0 @@-import cx from "classnames";-import { t } from "ttag";--import { formatPercent } from "metabase/utils/formatting";-import type { TooltipRowModel } from "metabase/viz-core";--import S from "./TooltipRow.module.css";--export interface TooltipRowProps extends TooltipRowModel {- isHeader?: boolean;- percent?: number;-}--export const TooltipRow = ({- name,- value,- color,- percent,- isHeader,- formatter = (value: unknown) => String(value),-}: TooltipRowProps) => (- <tr className={cx(S.tooltipRowRoot, { [S.header]: isHeader })}>- {color && (- <td className={cx(S.cell, S.colorIndicatorCell)}>- <span- className={cx(S.colorIndicator, {- [S.colorIndicatorLarge]: isHeader,- })}- style={{ backgroundColor: color }}- />- </td>- )}- <td className={S.cell} data-testid="row-name">- {name}- </td>- <td className={cx(S.cell, S.valueCell)} data-testid="row-value">- {formatter(value)}- </td>- {percent != null ? (- <td className={cx(S.cell, S.percentCell)} data-testid="row-percent">- {formatPercent(percent)}- </td>- ) : null}- </tr>-);--interface TotalTooltipRow {- value: string;- percent?: number;- hasIcon?: boolean;-}--export const TooltipTotalRow = ({- value,- percent,- hasIcon,-}: TotalTooltipRow) => (- <tr className={S.totalRowRoot}>- {hasIcon && <td className={cx(S.cell, S.colorIndicatorCell)}>=</td>}- <td className={S.cell} data-testid="row-name">- {t`Total`}- </td>- <td className={cx(S.cell, S.valueCell)} data-testid="row-value">- {value}- </td>- {percent != null && (- <td className={cx(S.cell, S.percentCell)} data-testid="row-percent">- {formatPercent(percent)}- </td>- )}- </tr>-);diff --git a/frontend/src/metabase/visualizations/components/ChartTooltip/TooltipRow/index.ts b/frontend/src/metabase/visualizations/components/ChartTooltip/TooltipRow/index.tsdeleted file mode 100644index 75a6c606f2c..00000000000--- a/frontend/src/metabase/visualizations/components/ChartTooltip/TooltipRow/index.ts+++ /dev/null@@ -1 +0,0 @@-export * from "./TooltipRow";diff --git a/frontend/src/metabase/visualizations/hooks/use-timeline-events.ts b/frontend/src/metabase/visualizations/hooks/use-timeline-events.tsindex a7427dae30a..901d5d73aaf 100644--- a/frontend/src/metabase/visualizations/hooks/use-timeline-events.ts+++ b/frontend/src/metabase/visualizations/hooks/use-timeline-events.ts@@ -33,6 +33,8 @@ interface UseTimelineEventsProps {isDashboard?: boolean;width?: number;height?: number;+ // Neither fetch nor return events, even ones passed in.+ skip?: boolean;}interface UseTimelineEventsResult {@@ -60,8 +62,9 @@ export function useTimelineEvents({isDashboard = false,width = 0,height = 0,+ skip = false,}: UseTimelineEventsProps): UseTimelineEventsResult {- const isEnabled = isTimelineEventsEnabled(settings);+ const isEnabled = !skip && isTimelineEventsEnabled(settings);const visibility = isEnabled? (timelineEventsVisibility ??getRecordedTimelineEventsVisibility(settings))diff --git a/frontend/src/metabase/visualizations/hooks/use-timeline-events.unit.spec.ts b/frontend/src/metabase/visualizations/hooks/use-timeline-events.unit.spec.tsindex 0bcd02af825..ce3872975db 100644--- a/frontend/src/metabase/visualizations/hooks/use-timeline-events.unit.spec.ts+++ b/frontend/src/metabase/visualizations/hooks/use-timeline-events.unit.spec.ts@@ -95,6 +95,7 @@ const setup = ({isDashboard = false,width,height,+ skip,providers = getTestStoreAndWrapper({ initialRoute: "/" }),}: {savedSettings?: VisualizationSettings;@@ -108,6 +109,7 @@ const setup = ({isDashboard?: boolean;width?: number;height?: number;+ skip?: boolean;providers?: ReturnType<typeof getTestStoreAndWrapper>;} = {}) => {setupTimelinesEndpoints(timelines);@@ -122,6 +124,7 @@ const setup = ({isDashboard,width,height,+ skip,...props,}),{ initialProps: { series, settings }, wrapper: providers.wrapper },@@ -255,6 +258,21 @@ describe("useTimelineEvents", () => {expect(getTimelineRequests()).toHaveLength(0);});+ it("loads nothing when skipped", () => {+ const { result } = setup({ skip: true });++ // A query that will fetch reports loading from its first render.+ expect(result.current.isLoading).toBe(false);+ expect(result.current.timelineEvents).toEqual([]);+ expect(getTimelineRequests()).toHaveLength(0);+ });++ it("ignores the events it is given when skipped", () => {+ const { result } = setup({ skip: true, timelineEvents: [SHOWN_EVENT] });++ expect(result.current.timelineEvents).toEqual([]);+ });+it("loads nothing when the host selects no timelines", () => {const { result } = setup({timelineEventsVisibility: { "timeline.selected_timeline_ids": [] },diff --git a/frontend/src/metabase/visualizations/shared/components/RowChart/RowChart.stories.tsx b/frontend/src/metabase/visualizations/shared/components/RowChart/RowChart.stories.tsxdeleted file mode 100644index 1be439dedc4..00000000000--- a/frontend/src/metabase/visualizations/shared/components/RowChart/RowChart.stories.tsx+++ /dev/null@@ -1,105 +0,0 @@-import type { StoryFn } from "@storybook/react";--import { SdkVisualizationWrapper } from "__support__/storybook";-import { Box } from "metabase/ui";-import { color } from "metabase/ui/colors";-import { measureTextWidth } from "metabase/utils/measure-text";-import { useRowChartTheme } from "metabase/visualizations/visualizations/RowChart/utils/theme";-import {- RowChart,- type RowChartProps,- getStaticChartTheme,-} from "metabase/viz-core";--export default {- title: "Viz/Shared/RowChart",- component: RowChart,-};--const Template: StoryFn<RowChartProps<any>> = (args) => {- return (- <Box h={600} bg="core-white" p="8px">- <RowChart {...args} />- </Box>- );-};--const DEFAULT_ROW_CHART_ARGS = {- width: 800,- height: 400,- data: [- {- y: "Gizmo",- x1: 110,- x2: 45,- },- {- y: "Gadget",- x1: 120,- x2: 46,- },- {- y: "Doohickey",- x1: 30,- x2: 56,- },- {- y: "Widget",- x1: 80,- x2: 60,- },- ],- series: [- {- seriesKey: "count",- seriesName: "Count",- xAccessor: (datum: any) => datum.x1,- yAccessor: (datum: any) => datum.y,- },- {- seriesKey: "avg",- seriesName: "Average of something",- xAccessor: (datum: any) => datum.x2,- yAccessor: (datum: any) => datum.y,- },- ],- seriesColors: {- count: color("accent3"),- avg: color("accent1"),- },-- goal: {- label: "Very very very long goal label",- value: 100,- },-- xLabel: "X Label",- yLabel: "Y Label",-- theme: getStaticChartTheme(color),-- measureTextWidth,-- style: { fontFamily: "Lato" },-};--export const Default = {- render: Template,- args: DEFAULT_ROW_CHART_ARGS,-};--const ThemedRowChart = () => {- const theme = useRowChartTheme("Lato", false);-- return (- <Box h={600} bg="core-white" p="8px">- <RowChart {...DEFAULT_ROW_CHART_ARGS} theme={theme} stackOffset={null} />- </Box>- );-};--export const HugeFont = () => (- <SdkVisualizationWrapper theme={{ fontSize: "20px" }}>- <ThemedRowChart />- </SdkVisualizationWrapper>-);diff --git a/frontend/src/metabase/visualizations/tests/timeseries-intervals.unit.spec.ts b/frontend/src/metabase/visualizations/tests/timeseries-intervals.unit.spec.tsindex e110b8c16fb..1532bc02013 100644--- a/frontend/src/metabase/visualizations/tests/timeseries-intervals.unit.spec.ts+++ b/frontend/src/metabase/visualizations/tests/timeseries-intervals.unit.spec.ts@@ -3,7 +3,7 @@ import { dayjs } from "metabase/dayjs";import { registerVisualizations } from "metabase/visualizations/register";import {type CartesianChartDateTimeAbsoluteUnit,- type ContinuousDomain,+ type Extent,type TimeSeriesInterval,computeTimeseriesDataInterval,computeTimeseriesTicksInterval,@@ -321,7 +321,7 @@ describe("timeseries intervals", () => {const mockFormatter = (value: RowValue) => String(value);type TickInput = {- xDomain: ContinuousDomain;+ xDomain: Extent;xInterval: TimeSeriesInterval;outerWidth: number;paddingX?: number;diff --git a/frontend/src/metabase/visualizations/visualizations/CartesianChart/CartesianChart.tsx b/frontend/src/metabase/visualizations/visualizations/CartesianChart/CartesianChart.tsxindex cb84eedafec..f2c7a7df58d 100644--- a/frontend/src/metabase/visualizations/visualizations/CartesianChart/CartesianChart.tsx+++ b/frontend/src/metabase/visualizations/visualizations/CartesianChart/CartesianChart.tsx@@ -24,6 +24,7 @@ import { useChartEvents } from "metabase/visualizations/visualizations/Cartesianimport {type TimelineEventGroup,getLegendItems,+ isRowChartSeries,useCartesianChartSeriesColorsClasses,useCloseTooltipOnScroll,} from "metabase/viz-core";@@ -84,7 +85,12 @@ function CartesianChartInner(props: VisualizationProps) {[originalSettings, outerHeight, outerWidth, isMobile, gridSize],);- const { timelineEvents } = useTimelineEvents({ ...props, settings });+ // Row charts don't offer timeline events (UXW-4833).+ const { timelineEvents } = useTimelineEvents({+ ...props,+ settings,+ skip: isRowChartSeries(rawSeries),+ });const [hoveredTimelineEventGroup, setHoveredTimelineEventGroup] =useState<TimelineEventGroup | null>(null);diff --git a/frontend/src/metabase/visualizations/visualizations/CartesianChart/events.ts b/frontend/src/metabase/visualizations/visualizations/CartesianChart/events.tsindex 1bdb5811af6..b1ae27b01d4 100644--- a/frontend/src/metabase/visualizations/visualizations/CartesianChart/events.ts+++ b/frontend/src/metabase/visualizations/visualizations/CartesianChart/events.ts@@ -33,6 +33,7 @@ import {type EChartsTooltipModel,type EChartsTooltipRow,INDEX_KEY,+ IS_FOLDED_ROW_DATA_KEY,IS_WATERFALL_TOTAL_DATA_KEY,OTHER_DATA_KEY,type SeriesModel,@@ -924,6 +925,10 @@ export const getSeriesClickData = (}const datum = chartModel.dataset[dataIndex];+ // A row chart's folded "Other" row has no single category to drill into.+ if (datum[IS_FOLDED_ROW_DATA_KEY]) {+ return null;+ }const data = getEventColumnsData(chartModel, seriesModel, datum);const dimensions = getEventDimensions(diff --git a/frontend/src/metabase/visualizations/visualizations/CartesianChart/events.unit.spec.ts b/frontend/src/metabase/visualizations/visualizations/CartesianChart/events.unit.spec.tsindex d0e6c68ef7b..1fe81339cfb 100644--- a/frontend/src/metabase/visualizations/visualizations/CartesianChart/events.unit.spec.ts+++ b/frontend/src/metabase/visualizations/visualizations/CartesianChart/events.unit.spec.ts@@ -13,6 +13,7 @@ import {type EChartsSeriesMouseEvent,INDEX_KEY,X_AXIS_DATA_KEY,+ foldRowChartModel,getDatasetKey,} from "metabase/viz-core";import {@@ -29,6 +30,7 @@ import {getEventDimensions,getGoalLineHoverData,getSeriesClickData,+ getSeriesHovered,getTooltipModel,normalizeDimensionValue,} from "./events";@@ -859,6 +861,86 @@ describe("getTooltipModel", () => {});});+describe("row chart folded Other row", () => {+ const COUNT_KEY = "count";+ const CATEGORIES = ["A", "B", "C", "D", "E"];++ // Five rows in a chart tall enough for two: one kept row plus "Other (4)".+ const getFoldedChartModel = () => {+ const dataset: Datum[] = CATEGORIES.map((category, index) => ({+ [X_AXIS_DATA_KEY]: category,+ [COUNT_KEY]: 10 * (index + 1),+ }));+ return foldRowChartModel(+ {+ ...createMockCartesianChartModel({+ seriesModels: [createMockSeriesModel({ dataKey: COUNT_KEY })],+ seriesIdToDataKey: { [COUNT_KEY]: COUNT_KEY },+ dataset,+ transformedDataset: dataset.map((datum, index) => ({+ ...datum,+ [INDEX_KEY]: index,+ })),+ }),+ stackedLabelsFormatters: {},+ dataDensity: {+ type: "combo",+ seriesDataKeysWithLabels: [],+ stackedDisplayWithLabels: [],+ numberOfDotsBySeriesKey: {},+ averageLabelWidth: 0,+ totalNumberOfLabels: 0,+ },+ },+ 48,+ createMockVisualizationSettings(),+ );+ };++ const createMouseEvent = (dataIndex: number) =>+ // A partial ECharts event: only these fields are read by the helpers under test.+ ({+ dataIndex,+ seriesId: COUNT_KEY,+ event: { event: new MouseEvent("click") },+ }) as EChartsSeriesMouseEvent;++ const OTHER_INDEX = 1;++ it("names the Other row in its tooltip", () => {+ const chartModel = getFoldedChartModel();++ const tooltipModel = getTooltipModel(+ chartModel,+ createMockVisualizationSettings(),+ OTHER_INDEX,+ "row",+ COUNT_KEY,+ );++ expect(tooltipModel?.header).toBe("Other (4)");+ });++ it("reports hovering the Other row, so the rest of the chart dims", () => {+ const chartModel = getFoldedChartModel();++ expect(getSeriesHovered(chartModel, createMouseEvent(OTHER_INDEX))).toEqual(+ { index: 0, datumIndex: OTHER_INDEX },+ );+ });++ it("does not drill into the Other row, like the legacy renderer", () => {+ const chartModel = getFoldedChartModel();++ expect(+ getSeriesClickData(chartModel, {}, createMouseEvent(OTHER_INDEX)),+ ).toBeNull();+ expect(+ getSeriesClickData(chartModel, {}, createMouseEvent(0)),+ ).not.toBeNull();+ });+});+describe("getGoalLineHoverData", () => {const createMarkerElement = () =>document.createElementNS("http://www.w3.org/2000/svg", "path");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 3db354197e0..801a2443b3f 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@@ -10,6 +10,7 @@ import {type ScatterPlotModel,type WaterfallChartModel,extractRemappings,+ foldRowChartModel,getCartesianChartModel,getCartesianChartOption,getChartLayout,@@ -62,7 +63,7 @@ export function useModelsAndOption(? timelineEvents.length !== 0: false;- const chartModel = useMemo(() => {+ const baseChartModel = useMemo(() => {let getModel;settings["graph.x_axis.title_text"] = tc(@@ -106,6 +107,15 @@ export function useModelsAndOption(tc,]);+ // Fold before layout: the fold decides which category labels get measured.+ const chartModel = useMemo(+ () =>+ baseChartModel.isRowChart+ ? foldRowChartModel(baseChartModel, height, settings)+ : baseChartModel,+ [baseChartModel, height, settings],+ );+const chartLayout = useMemo(() =>getChartLayout(diff --git a/frontend/src/metabase/visualizations/visualizations/RowChart/RowChart.stories.tsx b/frontend/src/metabase/visualizations/visualizations/RowChart/RowChart.stories.tsxindex 669e3ab3ce9..f9b98c74c22 100644--- a/frontend/src/metabase/visualizations/visualizations/RowChart/RowChart.stories.tsx+++ b/frontend/src/metabase/visualizations/visualizations/RowChart/RowChart.stories.tsx@@ -4,13 +4,21 @@ import type { StoryFn } from "@storybook/react";import { useState } from "react";import { useMount } from "react-use";-import { VisualizationWrapper } from "__support__/storybook";+import {+ IsomorphicVisualizationStory,+ SdkVisualizationStory,+ VisualizationWrapper,+ createWaitForChartsDecorator,+} from "__support__/storybook";import { NumberColumn, StringColumn } from "__support__/visualizations";import { Box } from "metabase/ui";import Visualization from "metabase/visualizations/components/Visualization";import { registerVisualization } from "metabase/viz-core";import type { RawSeries, Series } from "metabase-types/api";-import { createMockCard } from "metabase-types/api/mocks";+import {+ createMockCard,+ createMockDatasetData,+} from "metabase-types/api/mocks";import { RowChart } from "./RowChart";@@ -105,3 +113,50 @@ export const WithLongNames = () => {WithLongNames.parameters = {loki: { skip: true },};++const TWO_METRICS_SERIES: RawSeries = [+ {+ card: createMockCard({+ name: "Two metrics",+ display: "row",+ visualization_settings: {+ "graph.dimensions": ["Category"],+ "graph.metrics": ["Count", "Average"],+ "graph.show_goal": true,+ "graph.goal_value": 100,+ "graph.goal_label": "Very very very long goal label",+ // Row charts draw the x_axis (dimension) title on the left.+ "graph.x_axis.title_text": "Y Label",+ "graph.y_axis.title_text": "X Label",+ },+ }),+ data: createMockDatasetData({+ cols: [+ StringColumn({ name: "Category" }),+ NumberColumn({ name: "Count" }),+ NumberColumn({ name: "Average" }),+ ],+ rows: [+ ["Gizmo", 110, 45],+ ["Gadget", 120, 46],+ ["Doohickey", 30, 56],+ ["Widget", 80, 60],+ ],+ }),+ },+];++export const TwoMetrics = {+ render: () => <IsomorphicVisualizationStory rawSeries={TWO_METRICS_SERIES} />,+ decorators: [createWaitForChartsDecorator({ count: 1 })],+};++export const HugeFont = {+ render: () => (+ <SdkVisualizationStory+ rawSeries={TWO_METRICS_SERIES}+ theme={{ fontSize: "20px" }}+ />+ ),+ decorators: [createWaitForChartsDecorator({ count: 1 })],+};diff --git a/frontend/src/metabase/visualizations/visualizations/RowChart/RowChart.styled.tsx b/frontend/src/metabase/visualizations/visualizations/RowChart/RowChart.styled.tsxdeleted file mode 100644index f6919b7f6b1..00000000000--- a/frontend/src/metabase/visualizations/visualizations/RowChart/RowChart.styled.tsx+++ /dev/null@@ -1,34 +0,0 @@-// eslint-disable-next-line eslint-js/no-restricted-imports-import styled from "@emotion/styled";--import { LegendCaption } from "metabase/visualizations/components/legend/LegendCaption";-import { LegendLayout } from "metabase/visualizations/components/legend/LegendLayout";-import { getChartPadding } from "metabase/visualizations/visualizations/CartesianChart/padding";--interface RowVisualizationRootProps {- isQueryBuilder: boolean;-}--export const RowVisualizationRoot = styled.div<RowVisualizationRootProps>`- display: flex;- flex-direction: column;- padding: ${getChartPadding};- overflow: hidden;-`;--export const RowLegendCaption = styled(LegendCaption)`- flex: 0 0 auto;- margin-bottom: 0.5rem;-`;--export const RowChartContainer = styled.div`- position: absolute;- top: 0;- bottom: 0;- right: 0;- left: 0;-`;--export const RowChartLegendLayout = styled(LegendLayout)`- height: 100%;-`;diff --git a/frontend/src/metabase/visualizations/visualizations/RowChart/RowChart.tsx b/frontend/src/metabase/visualizations/visualizations/RowChart/RowChart.tsxindex 42b15a02b6a..ef4b59660aa 100644--- a/frontend/src/metabase/visualizations/visualizations/RowChart/RowChart.tsx+++ b/frontend/src/metabase/visualizations/visualizations/RowChart/RowChart.tsx@@ -1,334 +1,14 @@-import { useEffect, useMemo } from "react";--import { ExplicitSize } from "metabase/common/components/ExplicitSize";-import CS from "metabase/css/core/index.css";-import { getFontFamilyValue } from "metabase/utils/fonts";-import type { FontStyle } from "metabase/utils/measure-text";-import { measureTextWidth } from "metabase/utils/measure-text";import { assignLazily } from "metabase/utils/merge-lazily";import type { VisualizationProps } from "metabase/visualizations/types";-import {- getClickData,- getHoverData,- getLegendClickData,-} from "metabase/visualizations/visualizations/RowChart/utils/events";-import { useRowChartTheme } from "metabase/visualizations/visualizations/RowChart/utils/theme";-import {- type BarData,- type ChartGoal,- type GroupedDatum,- type HoveredData,- type RemappingHydratedChartData,- type RowChartProps,- type SeriesInfo,- RowChart as SharedRowChart,- extractRemappedColumns,- getChartGoal,- getGroupedDataset,- getStackOffset,- getTwoDimensionalChartSeries,- trimData,-} from "metabase/viz-core";+import { CartesianChart } from "metabase/visualizations/visualizations/CartesianChart";-import {- RowChartContainer,- RowChartLegendLayout,- RowLegendCaption,- RowVisualizationRoot,-} from "./RowChart.styled";import { ROW_CHART_DEFINITION } from "./definition";-import {- getColumnValueFormatter,- getFormatters,- getLabelsFormatter,-} from "./utils/format";-import { getLegendItems } from "./utils/legend";-import {- getAxesVisibility,- getLabelledSeries,- getLabels,- getXValueRange,-} from "./utils/settings";-import { getChartWarnings } from "./utils/warnings";--interface RowChartRendererProps extends RowChartProps<GroupedDatum> {- className?: string;-}-function RowChartRendererInner(props: RowChartRendererProps) {- return (- <RowChartContainer data-testid="row-chart-container">- <SharedRowChart {...props} />- </RowChartContainer>- );+// A rotated cartesian bar chart; see `BaseCartesianChartModel.isRowChart`.+function RowChartVisualization(props: VisualizationProps) {+ return <CartesianChart {...props} />;}-const RowChartRenderer = ExplicitSize<RowChartRendererProps>({- wrapped: true,- refreshMode: "throttle",-})(RowChartRendererInner);--const RowChartVisualization = ({- card,- className,- settings,- visualizationIsClickable,- onVisualizationClick,- hovered,- headerIcon,- actionButtons,- isFullscreen,- isQueryBuilder,- isVisualizer,- isDashboard,- onRender,- onHoverChange,- showTitle,- onChangeCardAndRun,- rawSeries: rawMultipleSeries,- fontFamily,- width: outerWidth,- height: outerHeight,- getHref,- hideLegend,-}: VisualizationProps) => {- const formatColumnValue = useMemo(() => {- return getColumnValueFormatter();- }, []);- const [chartSeries] = rawMultipleSeries;-- const data = useMemo(- () =>- // Unjustified type cast. FIXME- extractRemappedColumns(chartSeries.data) as RemappingHydratedChartData,- [chartSeries.data],- );-- const { chartColumns, series, seriesColors } = useMemo(- () => getTwoDimensionalChartSeries(data, settings, formatColumnValue),- [data, formatColumnValue, settings],- );-- const groupedData = useMemo(- () => getGroupedDataset(data, chartColumns, settings, formatColumnValue),- [chartColumns, data, settings, formatColumnValue],- );- const goal = useMemo(() => getChartGoal(settings), [settings]);- const stackOffset = getStackOffset(settings);- const theme = useRowChartTheme(getFontFamilyValue(fontFamily), isDashboard);-- const chartWarnings = useMemo(- () => getChartWarnings(chartColumns, data.rows),- [chartColumns, data.rows],- );-- useEffect(- function warnOnRendered() {- onRender({ warnings: chartWarnings });- },- [chartWarnings, onRender],- );-- const tickFormatters = useMemo(- () => getFormatters(chartColumns, settings),- [chartColumns, settings],- );-- const labelsFormatter = useMemo(- () => getLabelsFormatter(chartColumns, settings),- [chartColumns, settings],- );-- const handleClick = (- event: React.MouseEvent,- bar: BarData<GroupedDatum, SeriesInfo>,- ) => {- if (!bar.datum.isClickable) {- return;- }-- const clickData = getClickData(bar, settings, chartColumns, data.cols);- onVisualizationClick({ ...clickData, element: event.currentTarget });- };-- const handleHover = (- event: React.MouseEvent,- bar: BarData<GroupedDatum, SeriesInfo> | null,- ) => {- if (bar == null) {- onHoverChange?.(null);- return;- }- const hoverData = getHoverData(- bar,- settings,- chartColumns,- data.cols,- series,- seriesColors,- );-- onHoverChange?.({- ...hoverData,- // since we already scaled the dataset, we do not want the tool-tip- // formatter to apply scaling a second time- isAlreadyScaled: true,- event: event.nativeEvent,- element: event.currentTarget,- });- };-- const handleGoalHover = (event: React.MouseEvent, goal: ChartGoal | null) => {- if (goal == null) {- onHoverChange?.(null);- return;- }-- onHoverChange?.({- element: event.currentTarget,- data: [- {- col: null,- key: goal.label,- value: tickFormatters.xTickFormatter(goal.value),- },- ],- });- };-- const openQuestion = () => {- if (onChangeCardAndRun) {- onChangeCardAndRun({- nextCard: card,- });- }- };-- const handleSelectSeries = (event: React.MouseEvent, seriesIndex: number) => {- const clickData = {- ...getLegendClickData(- seriesIndex,- series,- settings,- chartColumns,- groupedData,- ),- element: event.currentTarget,- };-- const areMultipleCards = rawMultipleSeries.length > 1;- if (areMultipleCards) {- openQuestion();- return;- }-- if ("breakout" in chartColumns && visualizationIsClickable(clickData)) {- onVisualizationClick(clickData);- } else if (isDashboard) {- openQuestion();- }- };-- const hoverData: HoveredData | null =- hovered?.index != null- ? {- seriesIndex: hovered?.index,- datumIndex: hovered?.datumIndex,- }- : null;-- const hasTitle = showTitle && settings["card.title"];- const title = settings["card.title"] || card.name;- const description = settings["card.description"];- const canSelectTitle = !!onChangeCardAndRun;-- const legendItems = useMemo(- () => getLegendItems(series, seriesColors),- [series, seriesColors],- );-- const { xLabel, yLabel } = useMemo(() => getLabels(settings), [settings]);-- const xValueRange = useMemo(() => getXValueRange(settings), [settings]);-- const labelledSeries = useMemo(- () => getLabelledSeries(settings, series),- [series, settings],- );-- const { hasXAxis, hasYAxis } = useMemo(- () => getAxesVisibility(settings),- [settings],- );-- const textMeasurer = useMemo(() => {- return (text: string, style: FontStyle) =>- measureTextWidth(text, {- ...style,- family: fontFamily,- });- }, [fontFamily]);-- const hasBreakout = (settings["graph.dimensions"]?.length ?? 0) > 1;- const hasLegend = !hideLegend && (series.length > 1 || hasBreakout);-- return (- <RowVisualizationRoot className={className} isQueryBuilder={isQueryBuilder}>- {hasTitle && (- <RowLegendCaption- title={title}- description={description}- icon={headerIcon}- actionButtons={actionButtons}- onSelectTitle={canSelectTitle ? openQuestion : undefined}- width={outerWidth}- getHref={getHref}- />- )}- <RowChartLegendLayout- width={outerWidth}- height={outerHeight}- hasLegend={hasLegend}- alwaysVisible={isVisualizer}- items={legendItems}- actionButtons={!hasTitle ? actionButtons : undefined}- hovered={hovered}- onHoverChange={onHoverChange}- isFullscreen={isFullscreen}- isQueryBuilder={isQueryBuilder}- fontFamily={fontFamily}- measureText={textMeasurer}- onSelectSeries={handleSelectSeries}- >- <RowChartRenderer- className={CS.flexFull}- data={groupedData}- trimData={trimData}- series={series}- seriesColors={seriesColors}- goal={goal}- theme={theme}- stackOffset={stackOffset}- tickFormatters={tickFormatters}- labelsFormatter={labelsFormatter}- measureTextWidth={textMeasurer}- hoveredData={hoverData}- onClick={handleClick}- onHover={handleHover}- onGoalHover={handleGoalHover}- xLabel={xLabel}- yLabel={yLabel}- xScaleType={settings["graph.y_axis.scale"]}- xValueRange={xValueRange}- labelledSeries={labelledSeries}- hasXAxis={hasXAxis}- hasYAxis={hasYAxis}- />- </RowChartLegendLayout>- </RowVisualizationRoot>- );-};-export const RowChart = assignLazily(RowChartVisualization,ROW_CHART_DEFINITION,diff --git a/frontend/src/metabase/visualizations/visualizations/RowChart/RowChart.unit.spec.ts b/frontend/src/metabase/visualizations/visualizations/RowChart/RowChart.unit.spec.tsnew file mode 100644index 00000000000..3d618909531--- /dev/null+++ b/frontend/src/metabase/visualizations/visualizations/RowChart/RowChart.unit.spec.ts@@ -0,0 +1,259 @@+import { registerVisualizations } from "metabase/visualizations/register";+import {+ canBrush,+ getTooltipModel,+} from "metabase/visualizations/visualizations/CartesianChart/events";+import {+ DEFAULT_VISUALIZATION_THEME,+ type RenderingContext,+ getCartesianChartModel,+ getComputedSettingsForSeries,+ getSizeAdjustedSettings,+ getVisualizationTransformed,+} from "metabase/viz-core";+import { getColumnKey } from "metabase-lib/v1/queries/utils/column-key";+import type {+ RawSeries,+ VisualizationDisplay,+ VisualizationSettings,+} from "metabase-types/api";+import {+ createMockCard,+ createMockColumn,+ createMockDatasetData,+} from "metabase-types/api/mocks";++registerVisualizations();++const renderingContext: RenderingContext = {+ getColor: (name) => name,+ measureText: () => 10,+ measureTextHeight: () => 0,+ fontFamily: "",+ theme: DEFAULT_VISUALIZATION_THEME,+};++const createdAtColumn = createMockColumn({+ name: "CREATED_AT",+ display_name: "Created At",+ base_type: "type/DateTime",+ effective_type: "type/DateTime",+ unit: "month",+ source: "breakout",+});++const sumColumn = createMockColumn({+ name: "sum",+ display_name: "Sum",+ id: 42,+ field_ref: ["field", 42, null],+ base_type: "type/Integer",+ source: "aggregation",+});++const createSeries = (+ display: VisualizationDisplay,+ settings: VisualizationSettings,+): RawSeries => [+ {+ card: createMockCard({+ display,+ visualization_settings: {+ "graph.dimensions": ["CREATED_AT"],+ "graph.metrics": ["count", "sum"],+ ...settings,+ },+ }),+ data: createMockDatasetData({+ cols: [+ createdAtColumn,+ createMockColumn({+ name: "count",+ display_name: "Count",+ base_type: "type/Integer",+ source: "aggregation",+ }),+ sumColumn,+ ],+ rows: [+ ["2024-01-01T00:00:00Z", 10, 100],+ ["2024-02-01T00:00:00Z", 20, 150],+ ],+ }),+ },+];++const setup = (+ display: VisualizationDisplay,+ settings: VisualizationSettings,+) => {+ const rawSeries = createSeries(display, settings);+ const computedSettings = getComputedSettingsForSeries(+ getVisualizationTransformed(rawSeries).series,+ );+ const chartModel = getCartesianChartModel(+ rawSeries,+ computedSettings,+ [],+ renderingContext,+ );+ const seriesDisplays = chartModel.seriesModels.map(+ (seriesModel) =>+ computedSettings.series?.(seriesModel.legacySeriesSettingsObjectKey)+ ?.display,+ );++ return { rawSeries, computedSettings, chartModel, seriesDisplays };+};++// A card switched to a row chart keeps settings saved as a bar or combo chart.+describe("row chart settings carried over from another chart type", () => {+ it.each(["timeseries", "linear"] as const)(+ "ignores a saved %s dimension scale, so the axis stays categorical and brush zoom stays off",+ (scale) => {+ const { rawSeries, computedSettings, chartModel } = setup("row", {+ "graph.x_axis.scale": scale,+ });++ expect(computedSettings["graph.x_axis.scale"]).toBe("ordinal");+ expect(chartModel.xAxisModel.axisType).toBe("category");+ expect(+ canBrush(rawSeries, computedSettings, createdAtColumn, () => {}),+ ).toBe(false);+ },+ );++ it.each(["rotate-45", "rotate-90", "compact"] as const)(+ "shows category labels unrotated despite a saved %s label setting",+ (axisEnabled) => {+ const { computedSettings } = setup("row", {+ "graph.x_axis.axis_enabled": axisEnabled,+ });++ expect(computedSettings["graph.x_axis.axis_enabled"]).toBe(true);+ },+ );++ it("keeps hidden category labels hidden", () => {+ const { computedSettings } = setup("row", {+ "graph.x_axis.axis_enabled": false,+ });++ expect(computedSettings["graph.x_axis.axis_enabled"]).toBe(false);+ });++ it("draws every series as a bar despite a saved line or area display", () => {+ const { seriesDisplays } = setup("row", {+ series_settings: { count: { display: "line" }, sum: { display: "area" } },+ });++ expect(seriesDisplays).toEqual(["bar", "bar"]);+ });++ it("keeps one metric axis despite a saved right-axis position", () => {+ const { chartModel } = setup("row", {+ series_settings: { sum: { axis: "right" } },+ });++ expect(chartModel.rightAxisModel).toBeNull();+ expect(chartModel.leftAxisModel?.seriesKeys).toHaveLength(2);+ });++ it("keeps one metric axis where a bar chart would auto-split a second", () => {+ const getRightAxisModel = (display: VisualizationDisplay) => {+ const rawSeries = createSeries(display, {+ "graph.y_axis.auto_split": true,+ });+ // "sum" runs a million times larger than "count".+ rawSeries[0].data.rows = [+ ["2024-01-01T00:00:00Z", 1, 1_000_000],+ ["2024-02-01T00:00:00Z", 2, 2_000_000],+ ];+ const computedSettings = getComputedSettingsForSeries(+ getVisualizationTransformed(rawSeries).series,+ );+ return getCartesianChartModel(+ rawSeries,+ computedSettings,+ [],+ renderingContext,+ ).rightAxisModel;+ };++ expect(getRightAxisModel("bar")).not.toBeNull();+ expect(getRightAxisModel("row")).toBeNull();+ });++ it("leaves those settings working on other chart types", () => {+ const { seriesDisplays, chartModel } = setup("bar", {+ series_settings: { count: { display: "line" }, sum: { axis: "right" } },+ });++ expect(seriesDisplays).toEqual(["line", "bar"]);+ expect(chartModel.rightAxisModel?.seriesKeys).toHaveLength(1);+ });+});++describe("row chart axis 'Show label' setting", () => {+ const getAxisTitles = (width: number, height: number) => {+ // One metric, so the metric axis has a default title.+ const rawSeries = createSeries("row", { "graph.metrics": ["count"] });+ const settings = getSizeAdjustedSettings({+ settings: getComputedSettingsForSeries(+ getVisualizationTransformed(rawSeries).series,+ ),+ width,+ height,+ });+ const chartModel = getCartesianChartModel(+ rawSeries,+ settings,+ [],+ renderingContext,+ );+ return [chartModel.xAxisModel.label, chartModel.leftAxisModel?.label];+ };++ it("defaults to Auto on both axes, as on bar charts", () => {+ const { computedSettings } = setup("row", {});++ expect(computedSettings["graph.x_axis.labels_enabled"]).toBe("auto");+ expect(computedSettings["graph.y_axis.labels_enabled"]).toBe("auto");+ });++ it("keeps axis titles on a large chart and hides them on a small one", () => {+ expect(getAxisTitles(640, 420)).toEqual(["Created At", "Count"]);+ expect(getAxisTitles(300, 200)).toEqual([undefined, undefined]);+ });+});++describe("row chart additional tooltip columns", () => {+ const getTooltipRowNames = (settings: VisualizationSettings) => {+ // "sum" is left off the chart, so it's available as a tooltip column.+ const { computedSettings, chartModel } = setup("row", {+ "graph.metrics": ["count"],+ ...settings,+ });+ const tooltipModel = getTooltipModel(+ chartModel,+ computedSettings,+ 0,+ "row",+ chartModel.seriesModels[0].dataKey,+ );++ return tooltipModel?.rows.map((row) => row.name);+ };++ it("shows none by default, as on bar charts", () => {+ expect(getTooltipRowNames({})).toEqual(["Count"]);+ });++ it("shows the columns picked in the setting", () => {+ expect(+ getTooltipRowNames({+ "graph.tooltip_columns": [getColumnKey(sumColumn)],+ }),+ ).toEqual(["Count", "Sum"]);+ });+});diff --git a/frontend/src/metabase/visualizations/visualizations/RowChart/utils/events.ts b/frontend/src/metabase/visualizations/visualizations/RowChart/utils/events.tsdeleted file mode 100644index 7612ef13268..00000000000--- a/frontend/src/metabase/visualizations/visualizations/RowChart/utils/events.ts+++ /dev/null@@ -1,351 +0,0 @@-import { getIn } from "icepick";-import _ from "underscore";--import { formatNullable } from "metabase/utils/formatting";-import { isNotNull } from "metabase/utils/types";-import {- type BarData,- type CartesianChartColumns,- type ColumnDescriptor,- type DataPoint,- type GroupedDataset,- type GroupedDatum,- type MetricDatum,- type Series,- type SeriesInfo,- type StackedTooltipModel,- type TooltipRowModel,- formatValueForTooltipWithoutScaling,- getColumnDescriptors,- getStackOffset,- sumMetric,-} from "metabase/viz-core";-import type {- ClickObject,- ClickObjectDimension,-} from "metabase-lib/v1/queries/drills/types";-import { isMetric } from "metabase-lib/v1/types/utils/isa";-import type {- DatasetColumn,- RowValue,- RowValues,- VisualizationSettings,-} from "metabase-types/api";--const getMetricColumnData = (- columns: DatasetColumn[],- metricDatum: MetricDatum,- visualizationSettings: VisualizationSettings,-) => {- return Object.entries(metricDatum).map(([columnName, value]) => {- const col = columns.find((column) => column.name === columnName)!;- const key =- getIn(visualizationSettings, ["series_settings", col.name, "title"]) ??- col.display_name;-- return {- key,- value: formatNullable(value),- col,- };- });-};--const getColumnData = (columns: ColumnDescriptor[], rawRows: RowValues[]) => {- return columns- .map((columnDescriptor) => {- const { column, index } = columnDescriptor;-- let value;-- if (isMetric(column)) {- const metricSum = rawRows.reduce<number | null>(- (acc, currentRow) => sumMetric(acc, currentRow[index]),- null,- );-- value = formatNullable(metricSum);- } else {- value = rawRows[0]?.[index];- }-- return value != null- ? {- key: column.display_name,- value: formatNullable(value),- col: column,- }- : null;- })- .filter(isNotNull);-};--const getColumnsData = (- chartColumns: CartesianChartColumns,- series: Series<GroupedDatum>,- datum: GroupedDatum,- datasetColumns: DatasetColumn[],- visualizationSettings: VisualizationSettings,-) => {- const columnTitle =- visualizationSettings["graph.x_axis.title_text"] ??- chartColumns.dimension.column.display_name;-- const data = [- {- key: columnTitle,- value: formatNullable(datum.dimensionValue),- col: chartColumns.dimension.column,- },- ];-- let metricDatum: MetricDatum;- let rawRows: RowValues[];-- if ("breakout" in chartColumns && datum.breakout) {- data.push({- key: chartColumns.breakout.column.display_name,- value: series.seriesKey,- col: chartColumns.breakout.column,- });-- metricDatum = datum.breakout[series.seriesKey].metrics;- rawRows = datum.breakout[series.seriesKey].rawRows;- } else {- metricDatum = datum.metrics;- rawRows = datum.rawRows;- }-- data.push(- ...getMetricColumnData(datasetColumns, metricDatum, visualizationSettings),- );-- const otherColumnsDescriptors = getColumnDescriptors(- datasetColumns- .filter((column) => !data.some((item) => item.col === column))- .map((column) => column.name),- datasetColumns,- );-- data.push(...getColumnData(otherColumnsDescriptors, rawRows));- return data;-};--export const getClickData = (- bar: BarData<GroupedDatum, SeriesInfo>,- visualizationSettings: VisualizationSettings,- chartColumns: CartesianChartColumns,- datasetColumns: DatasetColumn[],-): ClickObject => {- const { series, datum } = bar;- const data = getColumnsData(- chartColumns,- series,- datum,- datasetColumns,- visualizationSettings,- );-- const xValue = series.xAccessor(datum);-- const dimensions: ClickObjectDimension[] = [- {- column: chartColumns.dimension.column,- value: datum.dimensionValue,- },- ];-- if ("breakout" in chartColumns) {- const breakoutRawRows =- datum.breakout?.[series.seriesKey]?.rawRows ?? datum.rawRows;- const rawBreakoutValue =- breakoutRawRows[0]?.[chartColumns.breakout.index] ?? null;- dimensions.push({- column: chartColumns.breakout.column,- value: rawBreakoutValue,- });- }-- return {- value: xValue,- column: series.seriesInfo?.metricColumn,- dimensions,- data,- settings: visualizationSettings,- };-};--const getRawBreakoutValue = (- groupedData: GroupedDataset,- seriesKey: string,- breakoutColumnIndex: number,-): RowValue => {- for (const datum of groupedData) {- const rawRows = datum.breakout?.[seriesKey]?.rawRows;- if (rawRows && rawRows.length > 0) {- return rawRows[0][breakoutColumnIndex] ?? null;- }- }- return null;-};--export const getLegendClickData = (- seriesIndex: number,- series: Series<GroupedDatum, SeriesInfo>[],- visualizationSettings: VisualizationSettings,- chartColumns: CartesianChartColumns,- groupedData: GroupedDataset,-) => {- const currentSeries = series[seriesIndex];-- const dimensions =- "breakout" in chartColumns- ? [- {- column: chartColumns.breakout.column,- value: getRawBreakoutValue(- groupedData,- currentSeries.seriesKey,- chartColumns.breakout.index,- ),- },- ]- : undefined;-- return {- column: currentSeries.seriesInfo?.metricColumn,- dimensions,- settings: visualizationSettings,- };-};--export const getStackedTooltipRows = <TDatum>(- bar: BarData<TDatum>,- settings: VisualizationSettings,- multipleSeries: Series<TDatum, SeriesInfo>[],- seriesColors: Record<string, string>,-): TooltipRowModel[] =>- multipleSeries- .map((series) => {- const value = series.xAccessor(bar.datum);- if (value == null) {- return null;- }-- return {- name: series.seriesName,- color: seriesColors[series.seriesKey],- value,- formatter: (value: unknown) =>- String(- formatValueForTooltipWithoutScaling({- value,- settings,- column: series.seriesInfo?.metricColumn,- }),- ),- };- })- .filter(isNotNull);--export const getTooltipModel = <TDatum>(- bar: BarData<TDatum>,- settings: VisualizationSettings,- chartColumns: CartesianChartColumns,- multipleSeries: Series<TDatum, SeriesInfo>[],- seriesColors: Record<string, string>,-) => {- const { series, datum } = bar;- const dimensionValue = series.yAccessor(datum);-- const headerTitle = String(- formatValueForTooltipWithoutScaling({- value: dimensionValue,- column: chartColumns.dimension.column,- settings,- }),- );-- const hasBreakout = "breakout" in chartColumns;- const rows = getStackedTooltipRows(- bar,- settings,- multipleSeries,- seriesColors,- );-- const [headerRows, bodyRows] = _.partition(- rows,- (row) => row.name === series.seriesName,- );-- const totalFormatter = (value: unknown) =>- String(- formatValueForTooltipWithoutScaling({- value,- settings,- column: hasBreakout- ? chartColumns.metric.column- : chartColumns.metrics[0].column,- }),- );-- return {- headerTitle,- headerRows,- bodyRows,- totalFormatter,- showTotal: true,- showPercentages: true,- };-};--export const getHoverData = (- bar: BarData<GroupedDatum>,- settings: VisualizationSettings,- chartColumns: CartesianChartColumns,- datasetColumns: DatasetColumn[],- multipleSeries: Series<GroupedDatum, SeriesInfo>[],- seriesColors: Record<string, string>,-): {- settings: VisualizationSettings;- datumIndex: number;- index: number;- data?: DataPoint[];- stackedTooltipModel?: StackedTooltipModel;-} => {- const hoverData = {- settings,- datumIndex: bar.datumIndex,- index: bar.seriesIndex,- };-- const hasMultipleSeries =- "breakout" in chartColumns || chartColumns.metrics.length > 1;- const isStacked = getStackOffset(settings) != null;- if (!isStacked || !hasMultipleSeries) {- const data = getColumnsData(- chartColumns,- bar.series,- bar.datum,- datasetColumns,- settings,- );-- return {- ...hoverData,- data,- };- }-- return {- ...hoverData,- stackedTooltipModel: getTooltipModel(- bar,- settings,- chartColumns,- multipleSeries,- seriesColors,- ),- };-};diff --git a/frontend/src/metabase/visualizations/visualizations/RowChart/utils/events.unit.spec.ts b/frontend/src/metabase/visualizations/visualizations/RowChart/utils/events.unit.spec.tsdeleted file mode 100644index e000783b198..00000000000--- a/frontend/src/metabase/visualizations/visualizations/RowChart/utils/events.unit.spec.ts+++ /dev/null@@ -1,670 +0,0 @@-import type {- BarData,- BreakoutChartColumns,- GroupedDatum,- MultipleMetricsChartColumns,- RemappingHydratedDatasetColumn,- Series,- SeriesInfo,- TooltipRowModel,-} from "metabase/viz-core";-import type { VisualizationSettings } from "metabase-types/api";-import {- createMockColumn,- createMockNumericColumn,-} from "metabase-types/api/mocks";--import {- getClickData,- getHoverData,- getLegendClickData,- getStackedTooltipRows,-} from "./events";--const datasetColumns = [- // Unjustified type cast. FIXME- { name: "y", display_name: "Y" } as RemappingHydratedDatasetColumn,- // Unjustified type cast. FIXME- { name: "x", display_name: "X" } as RemappingHydratedDatasetColumn,- // Unjustified type cast. FIXME- { name: "x1", display_name: "X1" } as RemappingHydratedDatasetColumn,-];--const chartColumns: MultipleMetricsChartColumns = {- dimension: {- index: 0,- column: datasetColumns[0],- },- metrics: [- {- index: 1,- column: datasetColumns[1],- },- {- index: 2,- column: datasetColumns[2],- },- ],-};--const multipleMetricsData: GroupedDatum[] = [- {- dimensionValue: "foo",- metrics: { x: 100, x1: 200 },- rawRows: [],- },-];--const seriesColors = {- x: "red",- x1: "green",-};--const SERIES_Y_ACCESSOR = (datum: GroupedDatum) =>- typeof datum.dimensionValue === "object"- ? JSON.stringify(datum.dimensionValue)- : datum.dimensionValue;--const series1 = {- seriesKey: "x",- seriesName: "Series 1",- xAccessor: (datum: GroupedDatum) => datum.metrics["x"],- yAccessor: SERIES_Y_ACCESSOR,-};-const series2 = {- seriesKey: "x1",- seriesName: "Series 2",- xAccessor: (datum: GroupedDatum) => datum.metrics["x1"],- yAccessor: SERIES_Y_ACCESSOR,-};--const barData: BarData<GroupedDatum> = {- isNegative: false,- xStartValue: 0,- xEndValue: 100,- yValue: "foo",- datum: multipleMetricsData[0],- datumIndex: 0,- series: series1,- seriesIndex: 0,-};--describe("events utils", () => {- describe("getHoverData", () => {- it("returns dimension key based on axis title setting when set", () => {- const keyValueData = getHoverData(- barData,- {- "graph.x_axis.title_text": "My Custom Dimension Label",- },- {- dimension: chartColumns.dimension,- metrics: [chartColumns.metrics[0]],- },- datasetColumns,- [series1],- seriesColors,- ).data;-- expect(keyValueData?.[0].key).toBe("My Custom Dimension Label");- });-- it("returns key-value pairs based on series_settings for charts without a breakout", () => {- const keyValueData = getHoverData(- barData,- {- series_settings: {- [chartColumns.metrics[0].column.name]: {- title: "my custom label",- },- },- },- {- dimension: chartColumns.dimension,- metrics: [chartColumns.metrics[0]],- },- datasetColumns,- [series1],- seriesColors,- ).data;-- expect(keyValueData).toStrictEqual([- { col: chartColumns.dimension.column, key: "Y", value: "foo" },- {- col: chartColumns.metrics[0].column,- key: "my custom label",- value: 100,- },- { col: chartColumns.metrics[1].column, key: "X1", value: 200 },- ]);- });-- it.each(["stacked", "normalized"])(- "returns stacked tooltip model for stacked charts",- (stackType) => {- const tooltipModel = getHoverData(- barData,- {- "stackable.stack_type":- // Unjustified type cast. FIXME- stackType as VisualizationSettings["stackable.stack_type"],- },- chartColumns,- datasetColumns,- [series1, series2],- seriesColors,- ).stackedTooltipModel;-- const { headerRows, bodyRows, headerTitle } = tooltipModel ?? {};-- expect(headerTitle).toBe("foo");- expect(headerRows).toHaveLength(1);- expect(headerRows?.[0]).toEqual(- expect.objectContaining({- color: "red",- name: "Series 1",- value: 100,- }),- );- expect(bodyRows).toHaveLength(1);- expect(bodyRows?.[0]).toEqual(- expect.objectContaining({- color: "green",- name: "Series 2",- value: 200,- }),- );- },- );-- it("does not return stacked tooltip model for stacked charts with a single metric without a breakout", () => {- const tooltipModel = getHoverData(- barData,- {- "stackable.stack_type": "stacked",- },- {- dimension: chartColumns.dimension,- metrics: [chartColumns.metrics[0]],- },- datasetColumns,- [series1],- seriesColors,- ).stackedTooltipModel;-- expect(tooltipModel).not.toBeDefined();- });-- it("does not return stacked tooltip model for non-stacked charts", () => {- const tooltipModel = getHoverData(- barData,- {},- chartColumns,- datasetColumns,- [series1, series1],- seriesColors,- ).stackedTooltipModel;-- expect(tooltipModel).not.toBeDefined();- });-- it("handles breakout where datum has fewer rawRows than seriesIndex (UXW-2597)", () => {- // Simulates: SELECT 'Production' as stage, 'App1' as application, 'Finished' as status, 2000000 as x- // UNION SELECT 'Development', 'App2', 'Finished', 2000000- // Each dimension value has only one breakout value, but series are created for all breakout values- const dataWithSparseBreakout: GroupedDatum[] = [- {- dimensionValue: "Production",- metrics: { x: 2000000 },- isClickable: true,- rawRows: [["Production", "App1", "Finished", 2000000]],- breakout: {- App1: {- metrics: { x: 2000000 },- rawRows: [["Production", "App1", "Finished", 2000000]],- },- },- },- {- dimensionValue: "Development",- metrics: { x: 2000000 },- isClickable: true,- rawRows: [["Development", "App2", "Finished", 2000000]],- breakout: {- App2: {- metrics: { x: 2000000 },- rawRows: [["Development", "App2", "Finished", 2000000]],- },- },- },- ];-- const datasetColumns = [- createMockColumn({ name: "stage", display_name: "Stage" }),- createMockColumn({ name: "application", display_name: "Application" }),- createMockColumn({ name: "status", display_name: "Status" }),- createMockNumericColumn({ name: "x", display_name: "X" }),- ];-- const columnsMap = {- stage: datasetColumns[0],- application: datasetColumns[1],- status: datasetColumns[2],- x: datasetColumns[3],- };-- const chartColumns: BreakoutChartColumns = {- dimension: { index: 0, column: columnsMap.stage },- breakout: { index: 1, column: columnsMap.application },- metric: { index: 3, column: columnsMap.x },- };-- const seriesApp1: Series<GroupedDatum, SeriesInfo> = {- seriesKey: "App1",- seriesName: "App1",- seriesInfo: {- metricColumn: columnsMap.x,- dimensionColumn: columnsMap.stage,- breakoutValue: "App1",- },- xAccessor: (datum: GroupedDatum) => datum.metrics["x"],- yAccessor: SERIES_Y_ACCESSOR,- };-- const seriesApp2: Series<GroupedDatum, SeriesInfo> = {- seriesKey: "App2",- seriesName: "App2",- seriesInfo: {- metricColumn: columnsMap.x,- dimensionColumn: columnsMap.stage,- breakoutValue: "App2",- },- xAccessor: (datum: GroupedDatum) => datum.metrics["x"],- yAccessor: SERIES_Y_ACCESSOR,- };-- const seriesColors = {- App1: "#509EE3",- App2: "#88BF4D",- };-- // Hover on Development/App2 bar - seriesIndex is 1 but datum.rawRows.length is 1- const barData: BarData<GroupedDatum> = {- isNegative: false,- xStartValue: 0,- xEndValue: 2000000,- yValue: "Development",- datum: dataWithSparseBreakout[1],- datumIndex: 1,- series: seriesApp2,- seriesIndex: 1, // Second series, but datum only has 1 rawRow- };-- // Should not throw and should return correct status value from breakout-specific rawRows- const tooltipData = getHoverData(- barData,- { "graph.dimensions": ["stage", "application"] },- chartColumns,- datasetColumns,- [seriesApp1, seriesApp2],- seriesColors,- );-- expect(tooltipData.data).toBeDefined();- expect(- tooltipData.data?.find(({ col }) => col?.name === "status")?.value,- ).toBe("Finished");- expect(- tooltipData.data?.find(({ col }) => col?.name === "x")?.value,- ).toBe(2000000);- });-- it("does handle data with breakout correctly (metabase#64931)", () => {- const dataWithBreakout: GroupedDatum[] = [- {- breakout: {- "2025-03-31": {- metrics: {- FUTURESPEND: 1000,- },- rawRows: [["2025-03-31", "US", 10, 100, 1000]],- },- "2024-03-31": {- metrics: {- FUTURESPEND: 2000,- },- rawRows: [["2024-03-31", "US", 20, 200, 2000]],- },- "2023-03-31": {- metrics: {- FUTURESPEND: 6000,- },- rawRows: [- ["2023-03-31", "US", 30, 300, 3000],- ["2023-03-31", "US", 30, 300, 3000],- ],- },- },- dimensionValue: "US",- metrics: { FUTURESPEND: 9000 },- isClickable: true,- rawRows: [- ["2025-03-31", "US", 10, 100, 1000],- ["2024-03-31", "US", 20, 200, 2000],- ["2023-03-31", "US", 30, 300, 3000],- ["2023-03-31", "US", 30, 300, 3000],- ],- },- ];-- const datasetColumns = [- createMockColumn({- name: "TIME",- display_name: "TIME",- }),- createMockColumn({- name: "COUNTRY",- display_name: "COUNTRY",- }),- createMockNumericColumn({- name: "PERCENTAGEOFTOTALSPEND",- display_name: "PERCENTAGEOFTOTALSPEND",- }),- createMockNumericColumn({- name: "TOTALSPEND",- display_name: "TOTALSPEND",- }),- createMockNumericColumn({- name: "FUTURESPEND",- display_name: "FUTURESPEND",- }),- ];-- const COLUMNS_MAP = {- TIME: datasetColumns[0],- COUNTRY: datasetColumns[1],- PERCENTAGEOFTOTALSPEND: datasetColumns[2],- TOTALSPEND: datasetColumns[3],- FUTURESPEND: datasetColumns[4],- };-- const chartColumns: BreakoutChartColumns = {- dimension: {- index: 1,- column: COLUMNS_MAP.COUNTRY,- },- breakout: {- index: 0,- column: COLUMNS_MAP.TIME,- },- metric: {- index: 4,- column: COLUMNS_MAP.FUTURESPEND,- },- };-- const series0: Series<GroupedDatum, SeriesInfo> = {- seriesKey: "2025-03-31",- seriesName: "2025-03-31",- seriesInfo: {- metricColumn: COLUMNS_MAP.FUTURESPEND,- dimensionColumn: COLUMNS_MAP.COUNTRY,- breakoutValue: "2025-03-31",- },- xAccessor: (datum: GroupedDatum) => datum.metrics["FUTURESPEND"],- yAccessor: SERIES_Y_ACCESSOR,- };- const series1: Series<GroupedDatum, SeriesInfo> = {- seriesKey: "2024-03-31",- seriesName: "2024-03-31",- seriesInfo: {- metricColumn: COLUMNS_MAP.FUTURESPEND,- dimensionColumn: COLUMNS_MAP.COUNTRY,- breakoutValue: "2024-03-31",- },- xAccessor: (datum: GroupedDatum) => datum.metrics["FUTURESPEND"],- yAccessor: SERIES_Y_ACCESSOR,- };- const series2: Series<GroupedDatum, SeriesInfo> = {- seriesKey: "2023-03-31",- seriesName: "2023-03-31",- seriesInfo: {- metricColumn: COLUMNS_MAP.FUTURESPEND,- dimensionColumn: COLUMNS_MAP.COUNTRY,- breakoutValue: "2023-03-31",- },- xAccessor: (datum: GroupedDatum) => datum.metrics["FUTURESPEND"],- yAccessor: SERIES_Y_ACCESSOR,- };-- const barData: BarData<GroupedDatum> = {- isNegative: false,- xStartValue: 0,- xEndValue: 6000,- yValue: "US",- datum: dataWithBreakout[0],- datumIndex: 0,- series: series2,- seriesIndex: 2,- };-- const seriesColors = {- "2023-03-31": "#98D9D9",- "2024-03-31": "#F2A86F",- "2025-03-31": "#F9D45C",- };-- const tooltipData = getHoverData(- barData,- {- "graph.dimensions": ["COUNTRY", "TIME"],- },- chartColumns,- datasetColumns,- [series0, series1, series2],- seriesColors,- );-- expect(- tooltipData.data?.find(({ col }) => col?.name === "FUTURESPEND")?.value,- ).toBe(6000);- expect(- tooltipData.data?.find(- ({ col }) => col?.name === "PERCENTAGEOFTOTALSPEND",- )?.value,- ).toBe(60);- expect(- tooltipData.data?.find(({ col }) => col?.name === "TOTALSPEND")?.value,- ).toBe(600);- });- });-});--describe("getClickData", () => {- it("passes raw null dimension value through to drill-thru (QUE2-97)", () => {- const dimensionColumn = createMockColumn({- name: "label",- display_name: "Label",- });- const breakoutColumn = createMockColumn({- name: "quarter",- display_name: "Quarter",- });- const metricColumn = createMockNumericColumn({- name: "count",- display_name: "Count",- });- const datasetColumns = [dimensionColumn, breakoutColumn, metricColumn];-- const chartColumns: BreakoutChartColumns = {- dimension: { index: 0, column: dimensionColumn },- breakout: { index: 1, column: breakoutColumn },- metric: { index: 2, column: metricColumn },- };-- const datum: GroupedDatum = {- dimensionValue: null,- metrics: { count: 5 },- isClickable: true,- rawRows: [[null, null, 5]],- breakout: {- "(empty)": {- metrics: { count: 5 },- rawRows: [[null, null, 5]],- },- },- };-- const series: Series<GroupedDatum, SeriesInfo> = {- seriesKey: "(empty)",- seriesName: "(empty)",- seriesInfo: {- metricColumn,- dimensionColumn,- breakoutValue: "(empty)",- },- xAccessor: (datum: GroupedDatum) => datum.metrics["count"],- yAccessor: SERIES_Y_ACCESSOR,- };-- const bar: BarData<GroupedDatum, SeriesInfo> = {- isNegative: false,- xStartValue: 0,- xEndValue: 5,- yValue: "(empty)",- datum,- datumIndex: 0,- series,- seriesIndex: 0,- };-- const clickData = getClickData(bar, {}, chartColumns, datasetColumns);-- expect(clickData.dimensions).toEqual([- { column: dimensionColumn, value: null },- { column: breakoutColumn, value: null },- ]);- });-});--describe("getLegendClickData", () => {- it("passes raw null breakout value through to drill-thru (QUE2-97)", () => {- const dimensionColumn = createMockColumn({- name: "label",- display_name: "Label",- });- const breakoutColumn = createMockColumn({- name: "quarter",- display_name: "Quarter",- });- const metricColumn = createMockNumericColumn({- name: "count",- display_name: "Count",- });-- const chartColumns: BreakoutChartColumns = {- dimension: { index: 0, column: dimensionColumn },- breakout: { index: 1, column: breakoutColumn },- metric: { index: 2, column: metricColumn },- };-- const groupedData: GroupedDatum[] = [- {- dimensionValue: "A",- metrics: { count: 5 },- isClickable: true,- rawRows: [["A", null, 5]],- breakout: {- "(empty)": {- metrics: { count: 5 },- rawRows: [["A", null, 5]],- },- },- },- ];-- const series: Series<GroupedDatum, SeriesInfo>[] = [- {- seriesKey: "(empty)",- seriesName: "(empty)",- seriesInfo: {- metricColumn,- dimensionColumn,- breakoutValue: "(empty)",- },- xAccessor: (datum: GroupedDatum) => datum.metrics["count"],- yAccessor: SERIES_Y_ACCESSOR,- },- ];-- const result = getLegendClickData(0, series, {}, chartColumns, groupedData);-- expect(result.dimensions).toEqual([- { column: breakoutColumn, value: null },- ]);- });-});--describe("getStackedTooltipRows", () => {- const settings: VisualizationSettings = {};- const seriesColors = {- metric1: "red",- metric2: "blue",- metric3: "green",- };-- const createMockSeries = (- metricKey: string,- metricName: string,- ): Series<Record<string, number | null>, SeriesInfo> => ({- seriesKey: metricKey,- seriesName: metricName,- xAccessor: (datum: Record<string, number | null>) => datum[metricKey],- yAccessor: () => "Category A",- seriesInfo: {- metricColumn: createMockColumn({- name: metricKey,- display_name: metricName,- }),- dimensionColumn: createMockColumn({- name: "dimension",- display_name: "Dimension column",- }),- },- });-- const series = [- createMockSeries("metric1", "Metric 1"),- createMockSeries("metric2", "Metric 2"),- createMockSeries("metric3", "Metric 3"),- ];-- const bar: BarData<Record<string, number | null>, SeriesInfo> = {- datum: { metric1: 10, metric2: null, metric3: 30 },- xStartValue: 0,- xEndValue: 40,- yValue: "Category A",- isNegative: false,- datumIndex: 0,- seriesIndex: 0,- series: series[0],- };-- it("should filter out null values and return formatted rows", () => {- const result = getStackedTooltipRows(bar, settings, series, seriesColors);-- expect(result).toHaveLength(2);- expect(result).toEqual([- expect.objectContaining<Partial<TooltipRowModel>>({- name: "Metric 1",- value: 10,- color: "red",- }),- expect.objectContaining<Partial<TooltipRowModel>>({- name: "Metric 3",- value: 30,- color: "green",- }),- ]);- });-});diff --git a/frontend/src/metabase/visualizations/visualizations/RowChart/utils/format.ts b/frontend/src/metabase/visualizations/visualizations/RowChart/utils/format.tsindex 286a41f44d4..2cfb2b97988 100644--- a/frontend/src/metabase/visualizations/visualizations/RowChart/utils/format.ts+++ b/frontend/src/metabase/visualizations/visualizations/RowChart/utils/format.ts@@ -1,93 +1,7 @@-import type { NumberLike, StringLike } from "@visx/scale";-import { getNullDisplayValue } from "metabase/utils/constants";import { isEmpty } from "metabase/utils/validate";import { formatValue } from "metabase/value-formatting";-import {- type BarData,- type CartesianChartColumns,- type ChartTicksFormatters,- type GroupedDatum,- type SeriesInfo,- getFormattingOptionsWithoutScaling,- getLabelsMetricColumn,- getStackOffset,-} from "metabase/viz-core";-import type {- DatasetColumn,- RowValue,- VisualizationSettings,-} from "metabase-types/api";--export const getFormatters = (- chartColumns: CartesianChartColumns,- settings: VisualizationSettings,-): ChartTicksFormatters => {- const yTickFormatter = (value: StringLike) => {- const options = getFormattingOptionsWithoutScaling({- ...settings.column(chartColumns.dimension.column),- jsx: false,- });- return String(formatValue(value, options));- };-- const metricColumn = getLabelsMetricColumn(chartColumns);-- const percentXTicksFormatter = (percent: NumberLike) => {- const column = metricColumn.column;- const number_separators = settings.column(column)?.number_separators;- const options = getFormattingOptionsWithoutScaling({- column,- number_separators,- jsx: false,- number_style: "percent",- decimals: 2,- });-- return String(formatValue(percent, options));- };-- const xTickFormatter = (value: NumberLike) => {- const options = getFormattingOptionsWithoutScaling({- ...settings.column(metricColumn.column),- jsx: false,- });-- return String(formatValue(value, options));- };-- const shouldFormatXTicksAsPercent = getStackOffset(settings) === "expand";-- return {- yTickFormatter,- xTickFormatter: shouldFormatXTicksAsPercent- ? percentXTicksFormatter- : xTickFormatter,- };-};--export const getLabelsFormatter = (- chartColumns: CartesianChartColumns,- settings: VisualizationSettings,-): ((value: any, bar?: BarData<GroupedDatum, SeriesInfo>) => string) => {- const fallbackColumn = getLabelsMetricColumn(chartColumns).column;-- const labelsFormatter = (- value: any,- bar?: BarData<GroupedDatum, SeriesInfo>,- ) => {- const column = bar?.series.seriesInfo?.metricColumn ?? fallbackColumn;- const options = getFormattingOptionsWithoutScaling({- ...settings.column(column),- jsx: false,- compact: settings["graph.label_value_formatting"] === "compact",- });-- return String(formatValue(value, options));- };-- return labelsFormatter;-};+import type { DatasetColumn, RowValue } from "metabase-types/api";export const getColumnValueFormatter = () => {return (value: RowValue, column: DatasetColumn) =>diff --git a/frontend/src/metabase/visualizations/visualizations/RowChart/utils/format.unit.spec.ts b/frontend/src/metabase/visualizations/visualizations/RowChart/utils/format.unit.spec.tsdeleted file mode 100644index e59ac11a810..00000000000--- a/frontend/src/metabase/visualizations/visualizations/RowChart/utils/format.unit.spec.ts+++ /dev/null@@ -1,86 +0,0 @@-import type {- BarData,- CartesianChartColumns,- GroupedDatum,- SeriesInfo,-} from "metabase/viz-core";-import type { DatasetColumn, VisualizationSettings } from "metabase-types/api";-import { createMockColumn } from "metabase-types/api/mocks";--import { getLabelsFormatter } from "./format";--const itemColumn = createMockColumn({- name: "ITEM",- display_name: "Item",- base_type: "type/Text",-});--const quantityColumn = createMockColumn({- name: "TOTAL_QUANTITY",- display_name: "Total Quantity",- base_type: "type/Integer",- effective_type: "type/Integer",- semantic_type: "type/Quantity",-});--const paidColumn = createMockColumn({- name: "TOTAL_PAID",- display_name: "Total Paid",- base_type: "type/Decimal",- effective_type: "type/Decimal",-});--const chartColumns: CartesianChartColumns = {- dimension: { column: itemColumn, index: 0 },- metrics: [- { column: paidColumn, index: 2 },- { column: quantityColumn, index: 1 },- ],-};--// Unjustified type cast. FIXME-const settings = {- "graph.label_value_formatting": "full",- column: (column: DatasetColumn) => {- if (column.name === "TOTAL_PAID") {- return {- column,- currency: "USD",- currency_style: "symbol",- number_style: "currency",- };- }-- return {- column,- number_style: "decimal",- };- },-} as VisualizationSettings;--const getBar = (metricColumn: DatasetColumn) =>- // Unjustified type cast. FIXME- ({- series: {- seriesInfo: {- metricColumn,- },- },- }) as BarData<GroupedDatum, SeriesInfo>;--describe("RowChart format", () => {- describe("getLabelsFormatter", () => {- it("formats data labels using the current series metric column", () => {- const formatter = getLabelsFormatter(chartColumns, settings);-- expect(formatter(769.76, getBar(paidColumn))).toBe("$769.76");- expect(formatter(409, getBar(quantityColumn))).toBe("409");- });-- it("falls back to the first metric when no bar is provided", () => {- const formatter = getLabelsFormatter(chartColumns, settings);-- expect(formatter(409)).toBe("$409.00");- });- });-});diff --git a/frontend/src/metabase/visualizations/visualizations/RowChart/utils/legend.ts b/frontend/src/metabase/visualizations/visualizations/RowChart/utils/legend.tsdeleted file mode 100644index a3faf1ea919..00000000000--- a/frontend/src/metabase/visualizations/visualizations/RowChart/utils/legend.ts+++ /dev/null@@ -1,12 +0,0 @@-import type { LegendItem, Series } from "metabase/viz-core";--export const getLegendItems = <TDatum>(- multipleSeries: Series<TDatum>[],- seriesColors: Record<string, string>,-): LegendItem[] => {- return multipleSeries.map((series) => ({- key: series.seriesKey,- name: series.seriesName,- color: seriesColors[series.seriesKey],- }));-};diff --git a/frontend/src/metabase/visualizations/visualizations/RowChart/utils/settings-definitions.ts b/frontend/src/metabase/visualizations/visualizations/RowChart/utils/settings-definitions.tsindex e37c236bd77..92765667bd9 100644--- a/frontend/src/metabase/visualizations/visualizations/RowChart/utils/settings-definitions.ts+++ b/frontend/src/metabase/visualizations/visualizations/RowChart/utils/settings-definitions.ts@@ -2,12 +2,19 @@ import { t } from "ttag";import {GRAPH_GOAL_SETTINGS,+ TOOLTIP_SETTINGS,type VisualizationSettingsDefinitions,getDefaultDimensionLabel,+ getIsXAxisLabelEnabledDefault,+ getIsYAxisLabelEnabledDefault,} from "metabase/viz-core";import type { Series, VisualizationSettings } from "metabase-types/api";export const ROW_CHART_SETTINGS: VisualizationSettingsDefinitions = {+ "graph.show_stack_values": {+ getValue: () => "total",+ getHidden: () => true,+ },"stackable.stack_type": {getSection: () => t`Display`,get title() {@@ -40,6 +47,7 @@ export const ROW_CHART_SETTINGS: VisualizationSettingsDefinitions = {}),},...GRAPH_GOAL_SETTINGS,+ ...TOOLTIP_SETTINGS,"graph.x_axis.scale": {getSection: () => t`Axes`,get group() {@@ -50,6 +58,10 @@ export const ROW_CHART_SETTINGS: VisualizationSettingsDefinitions = {},index: 4,widget: "select",+ // Row charts only draw a categorical axis; a time or linear scale saved as+ // a bar chart would make it continuous and enable brush zoom.+ isValid: (_series, vizSettings) =>+ vizSettings["graph.x_axis.scale"] === "ordinal",getDefault: () => "ordinal",getProps: () => {return { options: [{ name: t`Ordinal`, value: "ordinal" }] };@@ -84,6 +96,10 @@ export const ROW_CHART_SETTINGS: VisualizationSettingsDefinitions = {},index: 3,widget: "select",+ // Only show or hide; other viz types use values like "compact" or "rotate-45"+ // in this setting+ isValid: (_series, vizSettings) =>+ typeof vizSettings["graph.x_axis.axis_enabled"] === "boolean",getProps: () => ({options: [{@@ -180,9 +196,30 @@ export const ROW_CHART_SETTINGS: VisualizationSettingsDefinitions = {get title() {return t`Show label`;},- inline: true,- widget: "toggle",- getDefault: () => true,+ widget: "segmentedControl",+ getProps: () => ({+ options: [+ {+ get name() {+ return t`Auto`;+ },+ value: "auto",+ },+ {+ get name() {+ return t`On`;+ },+ value: true,+ },+ {+ get name() {+ return t`Off`;+ },+ value: false,+ },+ ],+ }),+ getDefault: getIsXAxisLabelEnabledDefault,},"graph.x_axis.title_text": {getSection: () => t`Axes`,@@ -210,9 +247,30 @@ export const ROW_CHART_SETTINGS: VisualizationSettingsDefinitions = {get group() {return t`X-axis`;},- widget: "toggle",- inline: true,- getDefault: () => true,+ widget: "segmentedControl",+ getProps: () => ({+ options: [+ {+ get name() {+ return t`Auto`;+ },+ value: "auto",+ },+ {+ get name() {+ return t`On`;+ },+ value: true,+ },+ {+ get name() {+ return t`Off`;+ },+ value: false,+ },+ ],+ }),+ getDefault: getIsYAxisLabelEnabledDefault,},"graph.y_axis.title_text": {getSection: () => t`Axes`,diff --git a/frontend/src/metabase/visualizations/visualizations/RowChart/utils/settings.ts b/frontend/src/metabase/visualizations/visualizations/RowChart/utils/settings.tsdeleted file mode 100644index 49b3f8e158d..00000000000--- a/frontend/src/metabase/visualizations/visualizations/RowChart/utils/settings.ts+++ /dev/null@@ -1,62 +0,0 @@-import { type Range, type Series, getStackOffset } from "metabase/viz-core";-import type { VisualizationSettings } from "metabase-types/api";--export const getLabelledSeries = <TDatum>(- settings: VisualizationSettings,- series: Series<TDatum>[],-) => {- const stackOffset = getStackOffset(settings);-- if (stackOffset === "expand") {- return null;- }-- return series- .filter((series) => {- const showSeriesValuesSetting =- settings?.series_settings?.[series.seriesKey]?.show_series_values;-- return (- showSeriesValuesSetting ||- (typeof showSeriesValuesSetting === "undefined" &&- settings["graph.show_values"] === true)- );- })- .map((series) => series.seriesKey);-};--export const getAxesVisibility = (settings: VisualizationSettings) => {- return {- hasXAxis: !!(settings["graph.y_axis.axis_enabled"] ?? true),- hasYAxis: !!(settings["graph.x_axis.axis_enabled"] ?? true),- };-};--export const getXValueRange = (- settings: VisualizationSettings,-): Range | undefined => {- const isAutoRange = settings["graph.y_axis.auto_range"] ?? true;-- if (isAutoRange) {- return undefined;- }-- return [settings["graph.y_axis.min"] ?? 0, settings["graph.y_axis.max"] ?? 0];-};--export const getLabels = (settings: VisualizationSettings) => {- const yLabel =- settings["graph.x_axis.labels_enabled"] &&- (settings["graph.x_axis.title_text"]?.length ?? 0) > 0- ? settings["graph.x_axis.title_text"]- : undefined;- const xLabel =- settings["graph.y_axis.labels_enabled"] &&- (settings["graph.y_axis.title_text"]?.length ?? 0) > 0- ? settings["graph.y_axis.title_text"]- : undefined;- return {- xLabel,- yLabel,- };-};diff --git a/frontend/src/metabase/visualizations/visualizations/RowChart/utils/theme.ts b/frontend/src/metabase/visualizations/visualizations/RowChart/utils/theme.tsdeleted file mode 100644index 1b344f41729..00000000000--- a/frontend/src/metabase/visualizations/visualizations/RowChart/utils/theme.ts+++ /dev/null@@ -1,62 +0,0 @@-import { useMemo } from "react";--import { useMantineTheme } from "metabase/ui";-import { color } from "metabase/ui/utils/colors";-import { type RowChartTheme, getVisualizationTheme } from "metabase/viz-core";--export const useRowChartTheme = (- fontFamily: string = "Lato",- isDashboard: boolean,-): RowChartTheme => {- const theme = useMantineTheme();-- return useMemo(() => {- const { cartesian } = getVisualizationTheme({- theme: theme.other,- isDashboard,- });-- return {- axis: {- color: color("border-neutral"),- ticks: {- size: cartesian.label.fontSize,- weight: 400,- color: color("text-secondary"),- family: fontFamily,- },- label: {- size: cartesian.label.fontSize,- weight: 400,- color: color("text-secondary"),- family: fontFamily,- },- },- goal: {- lineStroke: color("icon-primary"),- lineShadowStroke: color("background_surface-primary"),- label: {- size: cartesian.goalLine.label.fontSize,- weight: 400,- color: color("text-secondary"),- family: fontFamily,- },- marker: {- iconColor: color("icon-primary"),- backgroundColor: color("background_surface-primary"),- hoverBackgroundColor: color("background_surface-primary-hover"),- shadowColor: color("shadow-default"),- },- },- dataLabels: {- weight: 400,- color: color("text-secondary"),- size: cartesian.label.fontSize,- family: fontFamily,- },- grid: {- color: color("border-neutral-subtle"),- },- };- }, [theme, fontFamily, isDashboard]);-};diff --git a/frontend/src/metabase/visualizations/visualizations/RowChart/utils/warnings.ts b/frontend/src/metabase/visualizations/visualizations/RowChart/utils/warnings.tsdeleted file mode 100644index 1ef56e32437..00000000000--- a/frontend/src/metabase/visualizations/visualizations/RowChart/utils/warnings.ts+++ /dev/null@@ -1,25 +0,0 @@-import {- type CartesianChartColumns,- unaggregatedDataWarning,-} from "metabase/viz-core";-import type { RowValues } from "metabase-types/api";--export const getChartWarnings = (- chartColumns: CartesianChartColumns,- rows: RowValues[],-) => {- const chartValuesKeys = new Set(- rows.map((row) => {- const dimensionValue = row[chartColumns.dimension.index];- return "breakout" in chartColumns- ? `${row[chartColumns.breakout.index]}:${dimensionValue}`- : String(dimensionValue);- }),- );-- const hasUngroupedData = chartValuesKeys.size < rows.length;-- return hasUngroupedData- ? [unaggregatedDataWarning(chartColumns.dimension.column, "y").text]- : [];-};diff --git a/frontend/src/metabase/viz-core/echarts/cartesian/constants/dataset.ts b/frontend/src/metabase/viz-core/echarts/cartesian/constants/dataset.tsindex dab5ccce553..70cdd67203f 100644--- a/frontend/src/metabase/viz-core/echarts/cartesian/constants/dataset.ts+++ b/frontend/src/metabase/viz-core/echarts/cartesian/constants/dataset.ts@@ -27,6 +27,9 @@ export const X_AXIS_RAW_VALUE_DATA_KEY = `${NULL_CHAR}_x_raw` as const;// Key for the "other" series created by the `graph.max_categories` settingexport const OTHER_DATA_KEY = `${NULL_CHAR}_other` as const;+// Marks the summed "Other" row a row chart folds its overflow rows into.+export const IS_FOLDED_ROW_DATA_KEY = `${NULL_CHAR}_is_folded` as const;+// Stores the index that links this data point to its source in the original dataset (chartModel.dataset)// This reference allows tracking the origin of each point after dataset transformations are applied.export const INDEX_KEY = `${NULL_CHAR}_index` as const;diff --git a/frontend/src/metabase/viz-core/echarts/cartesian/layout/index.ts b/frontend/src/metabase/viz-core/echarts/cartesian/layout/index.tsindex 15cd39db8ef..75e3dc47f3c 100644--- a/frontend/src/metabase/viz-core/echarts/cartesian/layout/index.ts+++ b/frontend/src/metabase/viz-core/echarts/cartesian/layout/index.ts@@ -16,34 +16,18 @@ import type {AxisFormatter,ChartDataset,NumericAxisScaleTransforms,- SeriesFormatters,- SeriesModel,StackModel,XAxisModel,YAxisModel,} from "../model/types";import { getPaddedAxisLabel } from "../option/utils";-import type { ChartBoundsCoords, ChartLayout, TicksDimensions } from "./types";--export interface ChartLayoutInput {- xAxisModel: XAxisModel;- leftAxisModel: YAxisModel | null;- rightAxisModel: YAxisModel | null;- splitPanelYAxisModels?: YAxisModel[];- yAxisScaleTransforms: NumericAxisScaleTransforms;- transformedDataset?: ChartDataset;- dataset?: ChartDataset;- seriesModels?: SeriesModel[];- stackModels?: StackModel[];- seriesLabelsFormatters?: SeriesFormatters;-}--// Cartesian charts use `transformedDataset` (scaled/transformed values) while simpler-// charts like boxplot only have `dataset`. This helper provides unified access.-const getDataset = (input: ChartLayoutInput): ChartDataset => {- return input.transformedDataset ?? input.dataset ?? [];-};+import { getRowChartLayout } from "./row";+import type { ChartLayout, TicksDimensions } from "./types";+import { type ChartLayoutInput, getChartBounds, getDataset } from "./utils";++export type { ChartLayoutInput };+export { getChartBounds };const getEvenlySpacedIndices = (length: number,@@ -727,20 +711,6 @@ export const getCartesianChartPadding = (return padding;};-export const getChartBounds = (- width: number,- height: number,- padding: Padding,- ticksDimensions: TicksDimensions,-): ChartBoundsCoords => {- return {- top: padding.top,- bottom: height - padding.bottom - ticksDimensions.xTicksHeight,- left: padding.left + ticksDimensions.yTicksWidthLeft,- right: width - padding.right - ticksDimensions.yTicksWidthRight,- };-};-const getDimensionWidth = ({ xAxisModel }: ChartLayoutInput,boundaryWidth: number,@@ -913,6 +883,10 @@ export const getChartLayout = ();}+ if (input.isRowChart) {+ return getRowChartLayout(input, settings, width, height, renderingContext);+ }+const { ticksDimensions, axisEnabledSetting } = getTicksDimensions(input,width,diff --git a/frontend/src/metabase/viz-core/echarts/cartesian/layout/index.unit.spec.ts b/frontend/src/metabase/viz-core/echarts/cartesian/layout/index.unit.spec.tsindex f99f9252db1..0cddfa1d572 100644--- a/frontend/src/metabase/viz-core/echarts/cartesian/layout/index.unit.spec.ts+++ b/frontend/src/metabase/viz-core/echarts/cartesian/layout/index.unit.spec.ts@@ -292,4 +292,193 @@ describe("getChartLayout", () => {WIDEST_MEASURED_TICK_WIDTH + 24 + CHART_STYLE.padding.x,);});++ it("reserves row value label room for the drawn label on a log scale", () => {+ const chartContext: RenderingContext = {+ ...getChartContext(),+ measureText: (text) => text.length * 10,+ };+ const rowInput: ChartLayoutInput = {+ ...input,+ isRowChart: true,+ // log10(1,000,000) and the sign-preserving log10(1,000).+ transformedDataset: [+ { [X_AXIS_DATA_KEY]: "A", count: 6 },+ { [X_AXIS_DATA_KEY]: "B", count: -3 },+ ],+ yAxisScaleTransforms: {+ toEChartsAxisValue: (value) =>+ typeof value === "number"+ ? Math.sign(value) * Math.log10(Math.abs(value))+ : null,+ fromEChartsAxisValue: (value) =>+ Math.sign(value) * 10 ** Math.abs(value),+ },+ seriesLabelsFormatters: { count: (value) => String(value) },+ };++ const chartLayout = getChartLayout(+ rowInput,+ createMockVisualizationSettings({ "graph.show_values": true }),+ false,+ 480,+ 274,+ chartContext,+ );++ // "1000000" and "-1000", not "6" and "-3".+ expect(chartLayout.padding.right).toBe(+ CHART_STYLE.padding.x + 70 + CHART_STYLE.seriesLabels.offset,+ );+ expect(chartLayout.negativeDataLabelsWidth).toBe(+ 50 + CHART_STYLE.seriesLabels.offset,+ );+ });++ it("reserves no row value label room for a series hidden from the legend", () => {+ const chartContext: RenderingContext = {+ ...getChartContext(),+ measureText: (text) => text.length * 10,+ };+ const rowInput: ChartLayoutInput = {+ ...input,+ isRowChart: true,+ transformedDataset: [+ { [X_AXIS_DATA_KEY]: "A", count: 12, sum: 1234567 },+ { [X_AXIS_DATA_KEY]: "B", count: 34, sum: -7654321 },+ ],+ seriesModels: [+ createMockSeriesModel({ dataKey: "count" }),+ createMockSeriesModel({ dataKey: "sum", visible: false }),+ ],+ seriesLabelsFormatters: {+ count: (value) => String(value),+ sum: (value) => String(value),+ },+ };++ const chartLayout = getChartLayout(+ rowInput,+ createMockVisualizationSettings({ "graph.show_values": true }),+ false,+ 480,+ 274,+ chartContext,+ );++ // Only "34", the widest visible label; nothing for the hidden "sum".+ expect(chartLayout.padding.right).toBe(+ CHART_STYLE.padding.x + 20 + CHART_STYLE.seriesLabels.offset,+ );+ expect(chartLayout.negativeDataLabelsWidth).toBe(0);+ });++ it("reserves the metric tick labels' margin below a row chart's plot", () => {+ const chartContext = getChartContext();+ const { ticks } = chartContext.theme.cartesian;+ const rowInput: ChartLayoutInput = {+ ...input,+ isRowChart: true,+ transformedDataset: [{ [X_AXIS_DATA_KEY]: "A", price: 1500 }],+ };++ const chartLayout = getChartLayout(+ rowInput,+ createMockVisualizationSettings(),+ false,+ 480,+ 274,+ chartContext,+ );++ expect(chartLayout.ticksDimensions.xTicksHeight).toBe(+ ticks.fontSize + ticks.marginX,+ );+ });++ it("reserves the same category title room on a row chart as an upright chart's left axis", () => {+ const chartContext = getChartContext();+ const { fontSize, marginY } = chartContext.theme.cartesian.axisTitle;+ const rowInput: ChartLayoutInput = {+ ...input,+ isRowChart: true,+ transformedDataset: [{ [X_AXIS_DATA_KEY]: "A", price: 1500 }],+ };+ const getLeftPadding = (titleText: string) =>+ getChartLayout(+ rowInput,+ createMockVisualizationSettings({+ "graph.x_axis.labels_enabled": true,+ "graph.x_axis.title_text": titleText,+ }),+ false,+ 480,+ 274,+ chartContext,+ ).padding.left;++ expect(getLeftPadding("Category")).toBe(+ getLeftPadding("") + fontSize + marginY,+ );+ });++ it("measures row category labels as drawn, padded with spaces", () => {+ const chartContext: RenderingContext = {+ ...getChartContext(),+ measureText: (text) => text.length * 10,+ };+ const rowInput: ChartLayoutInput = {+ ...input,+ isRowChart: true,+ transformedDataset: [{ [X_AXIS_DATA_KEY]: "ABC", price: 1500 }],+ };++ const chartLayout = getChartLayout(+ rowInput,+ createMockVisualizationSettings(),+ false,+ 480,+ 274,+ chartContext,+ );++ // " ABC " is 5 characters wide.+ expect(chartLayout.ticksDimensions.yTicksWidthLeft).toBe(+ 50 + chartContext.theme.cartesian.ticks.marginY,+ );+ });++ it("reserves row goal label room only in static renders, which show the label", () => {+ const rowInput: ChartLayoutInput = {+ ...input,+ isRowChart: true,+ transformedDataset: [{ [X_AXIS_DATA_KEY]: "A", price: 1500 }],+ };+ const getTopPadding = ({+ hasGoal,+ isStatic,+ }: {+ hasGoal: boolean;+ isStatic: boolean;+ }) =>+ getChartLayout(+ rowInput,+ createMockVisualizationSettings({+ "graph.show_goal": hasGoal,+ "graph.goal_value": 1500,+ "graph.goal_label": "Target",+ }),+ false,+ 480,+ 274,+ { ...getChartContext(), isStatic },+ ).padding.top;++ expect(getTopPadding({ hasGoal: true, isStatic: false })).toBe(+ getTopPadding({ hasGoal: false, isStatic: false }),+ );+ expect(getTopPadding({ hasGoal: true, isStatic: true })).toBeGreaterThan(+ getTopPadding({ hasGoal: false, isStatic: true }),+ );+ });});diff --git a/frontend/src/metabase/viz-core/echarts/cartesian/layout/row.ts b/frontend/src/metabase/viz-core/echarts/cartesian/layout/row.tsnew file mode 100644index 00000000000..20e7b3a6f24--- /dev/null+++ b/frontend/src/metabase/viz-core/echarts/cartesian/layout/row.ts@@ -0,0 +1,257 @@+// Layout for row charts: a cartesian bar chart with the axes swapped.+import type {+ ComputedVisualizationSettings,+ Padding,+ RenderingContext,+} from "../../../types";+import {+ NEGATIVE_STACK_TOTAL_DATA_KEY,+ POSITIVE_STACK_TOTAL_DATA_KEY,+ X_AXIS_DATA_KEY,+} from "../constants/dataset";+import { CHART_STYLE } from "../constants/style";+import { getStackTotalValue } from "../model/series";+import type { LabelFormatter } from "../model/types";+import { getPaddedAxisLabel } from "../option/utils";+import { ROW_CHART_STYLE } from "../row/constants";+import { getRowChartSpacing } from "../row/spacing";++import type { ChartLayout, TicksDimensions } from "./types";+import { type ChartLayoutInput, getChartBounds, getDataset } from "./utils";++// Caps the category label gutter so long names still leave room for bars.+const ROW_CHART_LABEL_MAX_WIDTH_RATIO = 0.5;++// Upright `TicksDimensions` with roles swapped: `yTicksWidthLeft` holds the+// category labels, `xTicksHeight` the metric ticks.+const getRowChartTicksDimensions = (+ input: ChartLayoutInput,+ settings: ComputedVisualizationSettings,+ chartWidth: number,+ renderingContext: RenderingContext,+): TicksDimensions => {+ const { measureText, fontFamily, theme } = renderingContext;+ const { tickFontSize, categoryTickMargin, metricTickMargin } =+ getRowChartSpacing(theme);+ const fontStyle = {+ ...CHART_STYLE.axisTicks,+ family: fontFamily,+ size: tickFontSize,+ };++ const hasCategoryTicks = settings["graph.x_axis.axis_enabled"] !== false;+ const hasMetricTicks = settings["graph.y_axis.axis_enabled"] !== false;++ const formatter = input.xAxisModel.formatter;+ const widestLabel = hasCategoryTicks+ ? getDataset(input).reduce((widest, datum) => {+ // Measured as drawn: the category axis pads each label with spaces.+ const label = getPaddedAxisLabel(formatter(datum[X_AXIS_DATA_KEY]));+ return Math.max(widest, measureText(label, fontStyle));+ }, 0)+ : 0;++ const cap = chartWidth * ROW_CHART_LABEL_MAX_WIDTH_RATIO;+ const isCapped = widestLabel > cap;++ return {+ yTicksWidthLeft: hasCategoryTicks+ ? Math.min(widestLabel, cap) + categoryTickMargin+ : 0,+ yTicksWidthRight: 0,+ xTicksHeight: hasMetricTicks ? tickFontSize + metricTickMargin : 0,+ xTickWidthCap: isCapped ? cap : Infinity,+ firstXTickWidth: 0,+ lastXTickWidth: 0,+ getXTickWidth: (text: string) => measureText(text, fontStyle),+ };+};++// Room for data labels past each bar's end: right of positive bars, left of+// negative ones.+const getRowChartDataLabelsWidths = (+ input: ChartLayoutInput,+ settings: ComputedVisualizationSettings,+ { measureText, fontFamily, theme }: RenderingContext,+): { positive: number; negative: number } => {+ if (!settings["graph.show_values"]) {+ return { positive: 0, negative: 0 };+ }++ const hiddenSeriesKeys = new Set(+ (input.seriesModels ?? [])+ .filter((series) => !series.visible)+ .map((series) => series.dataKey),+ );+ const stackedLabelsFormatters = input.stackedLabelsFormatters ?? {};+ const seriesLabelsFormatters = input.seriesLabelsFormatters ?? {};++ // Every value label drawn: each stack's per-sign total, as the totals series+ // computes it, plus every labelled non-stacked value.+ const labels = getDataset(input).flatMap(+ (datum): { value: number; formatter: LabelFormatter }[] => {+ const stackTotals = (input.stackModels ?? []).flatMap((stackModel) => {+ const formatter = stackedLabelsFormatters[stackModel.display];+ if (formatter == null) {+ return [];+ }+ const stackKeys = stackModel.seriesKeys.filter(+ (dataKey) => !hiddenSeriesKeys.has(dataKey),+ );+ return [POSITIVE_STACK_TOTAL_DATA_KEY, NEGATIVE_STACK_TOTAL_DATA_KEY]+ .map((signKey) => getStackTotalValue(datum, stackKeys, signKey))+ .filter((value): value is number => value != null)+ .map((value) => ({ value, formatter }));+ });++ const seriesValues = Object.entries(seriesLabelsFormatters).flatMap(+ ([dataKey, formatter]) => {+ const value = datum[dataKey];+ return formatter != null &&+ !hiddenSeriesKeys.has(dataKey) &&+ typeof value === "number"+ ? [{ value, formatter }]+ : [];+ },+ );++ return [...stackTotals, ...seriesValues];+ },+ );++ const fontStyle = {+ family: fontFamily,+ weight: CHART_STYLE.seriesLabels.weight,+ size: theme.cartesian.label.fontSize,+ };+ const sideOf = (value: number) => (value < 0 ? "negative" : "positive");+ const { fromEChartsAxisValue } = input.yAxisScaleTransforms;+ const widestOn = (side: "positive" | "negative") => {+ const widths = labels+ .filter(({ value }) => sideOf(value) === side)+ // Labels show the original value, not its log or power transform.+ .map(({ value, formatter }) =>+ measureText(String(formatter(fromEChartsAxisValue(value))), fontStyle),+ );+ return widths.length === 0+ ? 0+ : Math.max(...widths) + CHART_STYLE.seriesLabels.offset;+ };++ return { positive: widestOn("positive"), negative: widestOn("negative") };+};++// Built in row terms because every reserve in `getCartesianChartPadding`+// assumes an upright chart.+const getRowChartPadding = (+ input: ChartLayoutInput,+ settings: ComputedVisualizationSettings,+ ticksDimensions: TicksDimensions,+ dataLabelsWidth: number,+ renderingContext: RenderingContext,+): Padding => {+ const { theme } = renderingContext;+ const { axisTitleFontSize, metricAxisTitleMargin, dimensionAxisTitleMargin } =+ getRowChartSpacing(theme);+ // The same title reserves as upright charts' bottom and left axes.+ const metricNameHeight = axisTitleFontSize / 2 + metricAxisTitleMargin;+ const dimensionNameWidth = axisTitleFontSize + dimensionAxisTitleMargin;+ // Mirrors what the axis builders render as each axis's `name`.+ const hasDimensionName = Boolean(+ settings["graph.x_axis.labels_enabled"] &&+ settings["graph.x_axis.title_text"],+ );+ const hasMetricName = Boolean(input.leftAxisModel?.label);+ // Static renders label the goal above the plot; the interactive goal marker+ // fits in the base padding.+ const hasGoalLabel = Boolean(+ renderingContext.isStatic &&+ settings["graph.show_goal"] &&+ settings["graph.goal_label"],+ );++ return {+ top:+ CHART_STYLE.padding.y ++ (hasGoalLabel+ ? theme.cartesian.label.fontSize + CHART_STYLE.seriesLabels.offset+ : 0),+ left:+ CHART_STYLE.padding.x ++ ticksDimensions.yTicksWidthLeft ++ (hasDimensionName ? dimensionNameWidth : 0),+ bottom:+ CHART_STYLE.padding.y ++ ticksDimensions.xTicksHeight ++ (hasMetricName ? metricNameHeight : 0),+ // Row charts have a single metric axis, so nothing else sits on the right.+ right: CHART_STYLE.padding.x + dataLabelsWidth,+ };+};++export const getRowChartLayout = (+ input: ChartLayoutInput,+ settings: ComputedVisualizationSettings,+ width: number,+ height: number,+ renderingContext: RenderingContext,+): ChartLayout => {+ const ticksDimensions = getRowChartTicksDimensions(+ input,+ settings,+ width,+ renderingContext,+ );++ const dataLabelsWidths = getRowChartDataLabelsWidths(+ input,+ settings,+ renderingContext,+ );++ // ECharts ignores `boundaryGap` once `min` is fixed, so negative labels get+ // an inset between the category axis and the plot instead.+ const hasFixedMin =+ !settings["graph.y_axis.auto_range"] &&+ settings["graph.y_axis.min"] != null;+ const negativeDataLabelsInset = hasFixedMin ? dataLabelsWidths.negative : 0;++ const basePadding = getRowChartPadding(+ input,+ settings,+ ticksDimensions,+ dataLabelsWidths.positive,+ renderingContext,+ );++ // Shrinks the grid so ECharts' centred bands land where visx's did.+ const bandPadding = ROW_CHART_STYLE.bandOuterPadding;+ const gridHeight = height - basePadding.top - basePadding.bottom;+ const legacyBandStep =+ gridHeight / (Math.max(getDataset(input).length, 1) + bandPadding);+ const outerInset = (bandPadding / 2) * legacyBandStep;++ const padding = {+ ...basePadding,+ top: basePadding.top + outerInset,+ bottom: basePadding.bottom + outerInset,+ left: basePadding.left + negativeDataLabelsInset,+ };++ const bounds = getChartBounds(width, height, padding, ticksDimensions);++ return {+ ticksDimensions,+ padding,+ bounds,+ negativeDataLabelsWidth: hasFixedMin ? 0 : dataLabelsWidths.negative,+ negativeDataLabelsInset,+ // Rotated bars share the plot height, not its width.+ boundaryWidth:+ height - padding.top - padding.bottom - ticksDimensions.xTicksHeight,+ outerHeight: height,+ outerWidth: width,+ axisEnabledSetting: settings["graph.x_axis.axis_enabled"],+ panelGap: 0,+ };+};diff --git a/frontend/src/metabase/viz-core/echarts/cartesian/layout/types.ts b/frontend/src/metabase/viz-core/echarts/cartesian/layout/types.tsindex 42c231bfeb9..2cb5a13b720 100644--- a/frontend/src/metabase/viz-core/echarts/cartesian/layout/types.ts+++ b/frontend/src/metabase/viz-core/echarts/cartesian/layout/types.ts@@ -20,6 +20,8 @@ export interface ChartBoundsCoords {export type TicksRotation = "horizontal" | "vertical";export interface ChartLayout {+ negativeDataLabelsWidth?: number;+ negativeDataLabelsInset?: number;padding: Padding;ticksDimensions: TicksDimensions;bounds: ChartBoundsCoords;diff --git a/frontend/src/metabase/viz-core/echarts/cartesian/layout/utils.ts b/frontend/src/metabase/viz-core/echarts/cartesian/layout/utils.tsnew file mode 100644index 00000000000..eab92371fd7--- /dev/null+++ b/frontend/src/metabase/viz-core/echarts/cartesian/layout/utils.ts@@ -0,0 +1,48 @@+// Helpers shared by the upright (`index.ts`) and row (`row.ts`) layouts.+import type { Padding } from "../../../types";+import type {+ ChartDataset,+ NumericAxisScaleTransforms,+ SeriesFormatters,+ SeriesModel,+ StackModel,+ StackedSeriesFormatters,+ XAxisModel,+ YAxisModel,+} from "../model/types";++import type { ChartBoundsCoords, TicksDimensions } from "./types";++export interface ChartLayoutInput {+ isRowChart?: boolean;+ xAxisModel: XAxisModel;+ leftAxisModel: YAxisModel | null;+ rightAxisModel: YAxisModel | null;+ splitPanelYAxisModels?: YAxisModel[];+ yAxisScaleTransforms: NumericAxisScaleTransforms;+ transformedDataset?: ChartDataset;+ dataset?: ChartDataset;+ seriesModels?: SeriesModel[];+ stackModels?: StackModel[];+ seriesLabelsFormatters?: SeriesFormatters;+ stackedLabelsFormatters?: StackedSeriesFormatters;+}++// Cartesian charts use `transformedDataset`; boxplot only has `dataset`.+export const getDataset = (input: ChartLayoutInput): ChartDataset => {+ return input.transformedDataset ?? input.dataset ?? [];+};++export const getChartBounds = (+ width: number,+ height: number,+ padding: Padding,+ ticksDimensions: TicksDimensions,+): ChartBoundsCoords => {+ return {+ top: padding.top,+ bottom: height - padding.bottom - ticksDimensions.xTicksHeight,+ left: padding.left + ticksDimensions.yTicksWidthLeft,+ right: width - padding.right - ticksDimensions.yTicksWidthRight,+ };+};diff --git a/frontend/src/metabase/viz-core/echarts/cartesian/model/axis.ts b/frontend/src/metabase/viz-core/echarts/cartesian/model/axis.tsindex f91a2367566..3d938cae965 100644--- a/frontend/src/metabase/viz-core/echarts/cartesian/model/axis.ts+++ b/frontend/src/metabase/viz-core/echarts/cartesian/model/axis.ts@@ -483,7 +483,7 @@ function findWidestRange(extents: Extent[]): Extent | null {return [min, max];}-function getYAxisExtent(+export function getYAxisExtent(seriesKeys: DataKey[],stackModels: StackModel[],dataset: ChartDataset,diff --git a/frontend/src/metabase/viz-core/echarts/cartesian/model/dataset.ts b/frontend/src/metabase/viz-core/echarts/cartesian/model/dataset.tsindex b85f60309e5..651f3a2c676 100644--- a/frontend/src/metabase/viz-core/echarts/cartesian/model/dataset.ts+++ b/frontend/src/metabase/viz-core/echarts/cartesian/model/dataset.ts@@ -939,6 +939,7 @@ const sortByDimension = (export const getSortedSeriesModels = (seriesModels: SeriesModel[],settings: ComputedVisualizationSettings,+ isRowChart = false,): SeriesModel[] => {const breakoutSeriesOrder = settings["graph.series_order"];if (breakoutSeriesOrder == null || breakoutSeriesOrder.length === 0) {@@ -964,10 +965,9 @@ export const getSortedSeriesModels = (}).filter(isNotNull);- // On stacked charts we reverse the order of series so that the series- // order in the sidebar matches series order on the chart.- // Also it produces historically correct order of series on already saved questions.- const isReversed = !isEmpty(settings["stackable.stack_type"]);+ // Upright stacks are reversed so the sidebar order matches the chart (and saved+ // questions keep their order); row stacks grow left to right, so already match.+ const isReversed = !isRowChart && !isEmpty(settings["stackable.stack_type"]);if (isReversed) {orderedSeriesModels.reverse();}diff --git a/frontend/src/metabase/viz-core/echarts/cartesian/model/dataset.unit.spec.ts b/frontend/src/metabase/viz-core/echarts/cartesian/model/dataset.unit.spec.tsindex e0779608a63..cee7d9f1313 100644--- a/frontend/src/metabase/viz-core/echarts/cartesian/model/dataset.unit.spec.ts+++ b/frontend/src/metabase/viz-core/echarts/cartesian/model/dataset.unit.spec.ts@@ -33,6 +33,7 @@ import {getDatasetKey,getJoinedCardsDataset,getNoXAxisValuesErrorMessage,+ getSortedSeriesModels,replaceValues,sortDataset,} from "./dataset";@@ -1001,4 +1002,31 @@ describe("dataset transform functions", () => {expect(result[2][X_AXIS_DATA_KEY]).toBe(1000);});});++ describe("getSortedSeriesModels", () => {+ const KEYS = ["A", "B", "C"];+ const seriesModels = KEYS.map((key) =>+ createMockSeriesModel({ dataKey: key }),+ );+ const settings = createMockComputedVisualizationSettings({+ "graph.series_order": KEYS.map((key) => ({+ key,+ name: key,+ enabled: true,+ })),+ "stackable.stack_type": "stacked",+ });+ const getSortedKeys = (isRowChart?: boolean) =>+ getSortedSeriesModels(seriesModels, settings, isRowChart).map(+ (seriesModel) => seriesModel.dataKey,+ );++ it("reverses stacked series so the stack matches the sidebar order", () => {+ expect(getSortedKeys()).toEqual(["C", "B", "A"]);+ });++ it("keeps row chart stacks in sidebar order, since they grow left to right", () => {+ expect(getSortedKeys(true)).toEqual(["A", "B", "C"]);+ });+ });});diff --git a/frontend/src/metabase/viz-core/echarts/cartesian/model/index.ts b/frontend/src/metabase/viz-core/echarts/cartesian/model/index.tsindex b393830b1a3..a52cfa03f0c 100644--- a/frontend/src/metabase/viz-core/echarts/cartesian/model/index.ts+++ b/frontend/src/metabase/viz-core/echarts/cartesian/model/index.ts@@ -6,6 +6,7 @@ import {getCartesianChartColumns,getReferencedColumns,} from "../../../lib/graph/columns";+import { isRowChartSeries } from "../../../lib/series";import { getSingleSeriesDimensionsAndMetrics } from "../../../lib/utils";import { getAreDimensionsAndMetricsValid } from "../../../shared/settings/cartesian-chart";import type {@@ -121,7 +122,11 @@ export const getChartSeriesModels = (const hasMultipleCards = rawSeries.length > 1;const sortedSeriesModels = hasMultipleCards? unsortedSeriesModels- : getSortedSeriesModels(unsortedSeriesModels, settings);+ : getSortedSeriesModels(+ unsortedSeriesModels,+ settings,+ isRowChartSeries(rawSeries),+ );const { ungroupedSeriesModels: seriesModels, groupedSeriesModels } =groupSeriesIntoOther(sortedSeriesModels, settings);@@ -148,6 +153,7 @@ export const getCartesianChartModel = (renderingContext: RenderingContext,showWarning?: ShowWarning,): CartesianChartModel => {+ const isRowChart = isRowChartSeries(rawSeries);const hasResponsiveTicks =renderingContext.cartesianSize != null &&renderingContext.cartesianSize !== "fullscreen";@@ -258,5 +264,6 @@ export const getCartesianChartModel = (stackedLabelsFormatters,dataDensity,groupedSeriesModels,+ isRowChart,};};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.tsnew file mode 100644index 00000000000..709ccb7b8f6--- /dev/null+++ b/frontend/src/metabase/viz-core/echarts/cartesian/model/row-fold.ts@@ -0,0 +1,105 @@+import { t } from "ttag";++import { checkNumber } from "metabase/utils/types";++import type { ComputedVisualizationSettings } from "../../../types";+import { IS_FOLDED_ROW_DATA_KEY, X_AXIS_DATA_KEY } from "../constants/dataset";++import { getYAxisExtent } from "./axis";+import { applyVisualizationSettingsDataTransformations } from "./dataset";+import type { BaseCartesianChartModel, ChartDataset, Datum } from "./types";++// Rows that don't fit fold into one summed "Other" row. One rule for app and+// email: each band (per series, or one when stacked) needs MIN_BAR_HEIGHT.+export const MIN_BAR_HEIGHT = 24;++const getRowChartBudget = (chartHeight: number, bandCount: number): number =>+ Math.max(Math.floor(chartHeight / (MIN_BAR_HEIGHT * bandCount)), 1);++const sumInto = (target: Datum, source: Datum, keys: string[]) => {+ keys.forEach((key) => {+ const value = source[key];+ if (value == null) {+ return;+ }+ const current = target[key];+ target[key] =+ (current == null ? 0 : checkNumber(current)) + checkNumber(value);+ });+};++const foldDataset = (+ dataset: ChartDataset,+ budget: number,+ seriesKeys: string[],+): ChartDataset => {+ const kept = dataset.slice(0, budget - 1);+ const folded = dataset.slice(budget - 1);++ const label =+ kept.length === 0+ ? t`All values (${folded.length})`+ : t`Other (${folded.length})`;++ const total: Datum = {+ [X_AXIS_DATA_KEY]: label,+ [IS_FOLDED_ROW_DATA_KEY]: true,+ };+ folded.forEach((datum) => sumInto(total, datum, seriesKeys));++ return [...kept, total];+};++export const foldRowChartModel = <Model extends BaseCartesianChartModel>(+ chartModel: Model,+ chartHeight: number,+ settings: ComputedVisualizationSettings,+): Model => {+ const visibleSeries = chartModel.seriesModels.filter(+ (series) => series.visible,+ );+ if (visibleSeries.length === 0 || chartHeight <= 0) {+ return chartModel;+ }++ const isStacked = chartModel.stackModels.length > 0;+ const bandCount = isStacked ? 1 : visibleSeries.length;+ const budget = getRowChartBudget(chartHeight, bandCount);++ if (chartModel.dataset.length <= budget) {+ return chartModel;+ }++ // Fold the untransformed values (grouped series too), then re-run the chart's+ // own transforms, so "Other" is totaled, normalized and scaled like any row.+ const seriesKeys = [+ ...chartModel.seriesModels,+ ...(chartModel.groupedSeriesModels ?? []),+ ].map((series) => series.dataKey);+ const dataset = foldDataset(chartModel.dataset, budget, seriesKeys);+ const transformedDataset = applyVisualizationSettingsDataTransformations(+ dataset,+ chartModel.stackModels,+ chartModel.xAxisModel,+ chartModel.seriesModels,+ chartModel.groupedSeriesModels ?? [],+ chartModel.yAxisScaleTransforms,+ settings,+ );++ return {+ ...chartModel,+ dataset,+ transformedDataset,+ // "Other" can exceed every row's range; row charts only have a left axis.+ leftAxisModel: chartModel.leftAxisModel && {+ ...chartModel.leftAxisModel,+ extent: getYAxisExtent(+ chartModel.leftAxisModel.seriesKeys,+ chartModel.stackModels,+ transformedDataset,+ settings["stackable.stack_type"],+ ),+ },+ };+};diff --git a/frontend/src/metabase/viz-core/echarts/cartesian/model/row-fold.unit.spec.ts b/frontend/src/metabase/viz-core/echarts/cartesian/model/row-fold.unit.spec.tsnew file mode 100644index 00000000000..e1c80c95f3a--- /dev/null+++ b/frontend/src/metabase/viz-core/echarts/cartesian/model/row-fold.unit.spec.ts@@ -0,0 +1,180 @@+import type {+ RawSeries,+ RowValue,+ VisualizationSettings,+} from "metabase-types/api";+import {+ createMockCard,+ createMockColumn,+ createMockDatasetData,+ createMockVisualizationSettings,+} from "metabase-types/api/mocks";++import { DEFAULT_VISUALIZATION_THEME } from "../../../shared/utils/theme";+import type { RenderingContext } from "../../../types";+import { OTHER_DATA_KEY } from "../constants/dataset";++import { MIN_BAR_HEIGHT, foldRowChartModel } from "./row-fold";++import { getCartesianChartModel } from "./index";++const renderingContext: RenderingContext = {+ getColor: (name) => name,+ measureText: () => 0,+ measureTextHeight: () => 0,+ fontFamily: "",+ theme: DEFAULT_VISUALIZATION_THEME,+};++const createSettings = (extra: VisualizationSettings = {}) =>+ createMockVisualizationSettings({+ "graph.dimensions": ["CATEGORY"],+ "graph.metrics": ["count"],+ "graph.x_axis.scale": "ordinal",+ series: () => ({ display: "bar" }),+ ...extra,+ });++const settings = createSettings();++// Each row is [count] or, for two metrics, [count, sum].+const getModel = (rows: RowValue[][], modelSettings = settings) => {+ const metricNames = ["count", "sum"].slice(0, rows[0].length);+ const rawSeries: RawSeries = [+ {+ card: createMockCard({ display: "row" }),+ data: createMockDatasetData({+ rows: rows.map((values, index) => [`C${index + 1}`, ...values]),+ cols: [+ createMockColumn({ name: "CATEGORY", base_type: "type/Text" }),+ ...metricNames.map((name) =>+ createMockColumn({ name, base_type: "type/Integer" }),+ ),+ ],+ }),+ },+ ];+ return getCartesianChartModel(rawSeries, modelSettings, [], renderingContext);+};++const single = (values: number[]) => values.map((value) => [value]);++describe("foldRowChartModel", () => {+ const ROW_BUDGET = 4;+ const chartHeight = ROW_BUDGET * MIN_BAR_HEIGHT;++ it("refits the metric axis to the folded Other row's total", () => {+ const model = getModel(single([100, 100, 100, 100, 100, 100, 100, 100]));+ expect(model.leftAxisModel?.extent).toEqual([100, 100]);++ const folded = foldRowChartModel(model, chartHeight, settings);++ // Three rows kept; the other five sum into "Other".+ expect(folded.transformedDataset).toHaveLength(ROW_BUDGET);+ expect(folded.leftAxisModel?.extent).toEqual([100, 500]);+ });++ it("refits the metric axis when folded rows sum below zero", () => {+ const model = getModel(single([300, 200, 100, -10, -20, -30, -40, -50]));++ const folded = foldRowChartModel(model, chartHeight, settings);++ // "Other" sums the five negatives to -150, below every original row.+ expect(folded.leftAxisModel?.extent).toEqual([-150, 300]);+ });++ it("leaves a model that fits untouched", () => {+ const model = getModel(single([100, 200, 300]));++ expect(foldRowChartModel(model, chartHeight, settings)).toBe(model);+ });++ // "Other" is the 4th row: three kept rows, then five folded 100s (raw 500).+ const OTHER_INDEX = 3;+ const SCALED_VALUES = single([1000, 900, 800, 100, 100, 100, 100, 100]);++ it.each(["log", "pow"] as const)(+ "scales the Other row's raw total on a %s axis",+ (scale) => {+ const scaledSettings = createSettings({ "graph.y_axis.scale": scale });+ const model = getModel(SCALED_VALUES, scaledSettings);+ const [{ dataKey }] = model.seriesModels;++ const folded = foldRowChartModel(model, chartHeight, scaledSettings);++ expect(folded.dataset[OTHER_INDEX][dataKey]).toBe(500);+ expect(folded.transformedDataset[OTHER_INDEX][dataKey]).toBeCloseTo(+ Number(model.yAxisScaleTransforms.toEChartsAxisValue(500)),+ );+ },+ );++ it("skips non-numeric values when summing the Other row", () => {+ const model = getModel([[1000], [900], [800], [100], ["n/a"], [100]]);+ const [{ dataKey }] = model.seriesModels;++ const folded = foldRowChartModel(model, chartHeight, settings);++ expect(folded.dataset[OTHER_INDEX][dataKey]).toBe(200);+ });++ it("normalizes the Other row of a 100% stacked chart", () => {+ const stackedSettings = createSettings({+ "graph.metrics": ["count", "sum"],+ "stackable.stack_type": "normalized",+ });+ const model = getModel(+ [30, 40, 50, 60, 70, 80, 90, 100].map((count) => [count, 100 - count]),+ stackedSettings,+ );+ const dataKeys = model.seriesModels.map((series) => series.dataKey);++ const folded = foldRowChartModel(model, chartHeight, stackedSettings);+ const other = folded.transformedDataset[OTHER_INDEX];++ expect(+ dataKeys.reduce((total, dataKey) => total + Number(other[dataKey]), 0),+ ).toBeCloseTo(1);+ });++ it("includes series grouped by max categories in the Other row", () => {+ // `isValid` blocks max categories today (metabase#50510); mock settings skip it.+ const groupedSettings = createSettings({+ "graph.dimensions": ["CATEGORY", "SOURCE"],+ "graph.max_categories_enabled": true,+ "graph.max_categories": 1,+ });+ const countBySource = { A: 100, B: 10, C: 1 };+ const rawSeries: RawSeries = [+ {+ card: createMockCard({ display: "row" }),+ data: createMockDatasetData({+ rows: SCALED_VALUES.flatMap((_, index) =>+ Object.entries(countBySource).map(([source, count]) => [+ `C${index + 1}`,+ source,+ count,+ ]),+ ),+ cols: [+ createMockColumn({ name: "CATEGORY", base_type: "type/Text" }),+ createMockColumn({ name: "SOURCE", base_type: "type/Text" }),+ createMockColumn({ name: "count", base_type: "type/Integer" }),+ ],+ }),+ },+ ];+ const model = getCartesianChartModel(+ rawSeries,+ groupedSettings,+ [],+ renderingContext,+ );+ expect(model.groupedSeriesModels).toHaveLength(2);++ const folded = foldRowChartModel(model, chartHeight, groupedSettings);++ // Two bands per row leave room for two rows: seven fold, each B (10) + C (1).+ expect(folded.transformedDataset.at(-1)?.[OTHER_DATA_KEY]).toBe(77);+ });+});diff --git a/frontend/src/metabase/viz-core/echarts/cartesian/model/types.ts b/frontend/src/metabase/viz-core/echarts/cartesian/model/types.tsindex 8bce72c4de6..65b27742324 100644--- a/frontend/src/metabase/viz-core/echarts/cartesian/model/types.ts+++ b/frontend/src/metabase/viz-core/echarts/cartesian/model/types.ts@@ -231,6 +231,7 @@ export type ComboChartDataDensity = BaseChartDataDensity & {};export type BaseCartesianChartModel = {+ isRowChart?: boolean;dimensionModel: DimensionModel;seriesModels: SeriesModel[];dataset: ChartDataset;diff --git a/frontend/src/metabase/viz-core/echarts/cartesian/option/goal-line.ts b/frontend/src/metabase/viz-core/echarts/cartesian/option/goal-line.tsindex 2191334dd6b..11594b1c05e 100644--- a/frontend/src/metabase/viz-core/echarts/cartesian/option/goal-line.ts+++ b/frontend/src/metabase/viz-core/echarts/cartesian/option/goal-line.ts@@ -17,7 +17,7 @@ export const GOAL_LINE_WIDTH = 1;export const isGoalLineSeriesId = (seriesId: string | undefined) =>seriesId?.startsWith(GOAL_LINE_SERIES_ID) ?? false;-function getFirstNonNullXValue(dataset: ChartDataset) {+export function getFirstNonNullXValue(dataset: ChartDataset) {for (let i = 0; i < dataset.length; i++) {const xValue = dataset[i][X_AXIS_DATA_KEY];@@ -105,7 +105,7 @@ function buildGoalLineLabel({];}-function buildGoalLineMarker({+export function buildGoalLineMarker({xEnd,y,renderingContext,diff --git a/frontend/src/metabase/viz-core/echarts/cartesian/option/index.ts b/frontend/src/metabase/viz-core/echarts/cartesian/option/index.tsindex 3365caf9d39..0549ff6a9ec 100644--- a/frontend/src/metabase/viz-core/echarts/cartesian/option/index.ts+++ b/frontend/src/metabase/viz-core/echarts/cartesian/option/index.ts@@ -28,11 +28,19 @@ import type {SeriesModel,} from "../model/types";import { getBarSeriesDataLabelKey } from "../model/util";+import { getRowGoalLineSeriesOption } from "../row/option/goal-line";+import { getRowChartSpacing } from "../row/spacing";import type { SplitPanelYExtent } from "../timeline-events/option";import { getTimelineEventsSelectionSeries } from "../timeline-events/option";import type { TimelineEventsModel } from "../timeline-events/types";-import { buildAxes, buildDimensionAxis, buildMetricAxis } from "./axis";+import {+ buildAxes,+ buildDimensionAxis,+ buildMetricAxis,+ getXAxisNameGap,+ getYAxisNameGap,+} from "./axis";import { getGoalLineParams, getGoalLineSeriesOption } from "./goal-line";import { applyResponsiveYAxisTicks } from "./responsive-axis";import { buildEChartsSeries } from "./series";@@ -115,9 +123,14 @@ const isNonCategoryYAxisOption = (axis: YAXisOption,): axis is NonCategoryYAxisOption => axis.type !== "category";+const withAxisLabelMargin = <Axis extends { axisLabel?: object }>(+ axis: Axis,+ margin: number,+): Axis => ({ ...axis, axisLabel: { ...axis.axisLabel, margin } });+export const ensureRoomForLabels = (axes: Axes,- { leftAxisModel, rightAxisModel }: CartesianChartModel,+ { leftAxisModel, rightAxisModel, isRowChart }: CartesianChartModel,chartLayout: ChartLayout,seriesOption: EChartsSeriesOption[],): Axes => ({@@ -134,6 +147,19 @@ export const ensureRoomForLabels = (return axis;}const [min] = axisModel.extent;+ if (min < 0 && isRowChart) {+ // Rotated, negative labels sit left of their bars+ const labelWidth = chartLayout.negativeDataLabelsWidth ?? 0;+ const { padding, outerWidth } = chartLayout;+ const plotWidth = outerWidth - padding.left - padding.right;+ if (labelWidth === 0 || !isNonCategoryYAxisOption(axis)) {+ return axis;+ }+ return {+ ...axis,+ boundaryGap: [labelWidth / Math.max(plotWidth - labelWidth, 1), 0],+ };+ }if (min < 0) {const { bounds } = chartLayout;const innerHeight = Math.abs(bounds.bottom - bounds.top);@@ -166,7 +192,10 @@ export function buildGridAndSeriesOption(const panelCount = visibleSeries.length;const isSplitPanels = chartLayout.panelHeight != null;- const baseGoalSeriesOption = getGoalLineSeriesOption(+ const getGoalSeriesOption = chartModel.isRowChart+ ? getRowGoalLineSeriesOption+ : getGoalLineSeriesOption;+ const baseGoalSeriesOption = getGoalSeriesOption(getGoalLineParams(chartModel),settings,renderingContext,@@ -197,7 +226,13 @@ export function buildGridAndSeriesOption(const grid: GridOption | GridOption[] = isSplitPanels? buildSplitPanelGrid(chartLayout, panelCount)- : { ...chartLayout.padding, outerBoundsMode: "none" };+ : {+ ...chartLayout.padding,+ // Row charts let ECharts keep metric tick labels in bounds+ ...(chartModel.isRowChart+ ? { outerBoundsMode: "auto", outerBoundsContain: "axisLabel" }+ : { outerBoundsMode: "none" }),+ };const splitPanelOverrides = isSplitPanels? buildSplitPanelOverrides(@@ -296,8 +331,38 @@ export const getCartesianChartOption = (chartLayout,dataSeriesOptions,);- xAxis = axes.xAxis;- yAxis = axes.yAxis;+ if (chartModel.isRowChart) {+ // The rotation: metric axes become x, the dimension axis becomes y+ // (`inverse` keeps the first row on top). Names and label margins follow.+ const { ticksDimensions } = chartLayout;+ const { theme } = renderingContext;+ const spacing = getRowChartSpacing(theme);++ xAxis = axes.yAxis.map(({ mainType: _omitMainType, ...axis }) => ({+ ...withAxisLabelMargin(axis, spacing.metricTickMargin),+ position: "bottom",+ nameGap: getXAxisNameGap(ticksDimensions.xTicksHeight, theme),+ axisLine: {+ show: !!settings["graph.y_axis.axis_enabled"],+ lineStyle: {+ color: renderingContext.getColor("border-neutral"),+ },+ },+ }));+ const { mainType: _omitMainType, ...dimensionAxis } = axes.xAxis;+ yAxis = [+ {+ ...withAxisLabelMargin(dimensionAxis, spacing.categoryTickMargin),+ position: "left",+ inverse: true,+ offset: chartLayout.negativeDataLabelsInset,+ nameGap: getYAxisNameGap(ticksDimensions.yTicksWidthLeft, theme),+ },+ ];+ } else {+ xAxis = axes.xAxis;+ yAxis = axes.yAxis;+ }}return {diff --git a/frontend/src/metabase/viz-core/echarts/cartesian/option/index.unit.spec.ts b/frontend/src/metabase/viz-core/echarts/cartesian/option/index.unit.spec.tsindex f8429516ad9..08e70ae9455 100644--- a/frontend/src/metabase/viz-core/echarts/cartesian/option/index.unit.spec.ts+++ b/frontend/src/metabase/viz-core/echarts/cartesian/option/index.unit.spec.ts@@ -1,3 +1,4 @@+import type { BarSeriesOption } from "echarts/charts";import { BarChart } from "echarts/charts";import {BrushComponent,@@ -8,7 +9,11 @@ import * as echarts from "echarts/core";import { SVGRenderer } from "echarts/renderers";import type { XAXisOption, YAXisOption } from "echarts/types/dist/shared";-import type { RawSeries, SingleSeries } from "metabase-types/api";+import type {+ RawSeries,+ SingleSeries,+ VisualizationSettings,+} from "metabase-types/api";import {createMockCard,createMockColumn,@@ -18,13 +23,21 @@ import {import { DEFAULT_VISUALIZATION_THEME } from "../../../shared/utils/theme";import type { RenderingContext } from "../../../types";+import { registerEChartsModules } from "../../index";+import { X_AXIS_DATA_KEY } from "../constants/dataset";+import { CHART_STYLE } from "../constants/style";import { getChartLayout } from "../layout";import { getCartesianChartModel } from "../model";+import { getBarSeriesDataLabelKey } from "../model/util";import { buildAxes } from "./axis";import { buildEChartsSeries } from "./series";-import { ensureRoomForLabels, getSharedEChartsOptions } from "./index";+import {+ ensureRoomForLabels,+ getCartesianChartOption,+ getSharedEChartsOptions,+} from "./index";echarts.use([BarChart,@@ -209,3 +222,229 @@ describe("brushSelected / brushEnd ordering", () => {chart.dispose();});});++describe("row chart bands", () => {+ beforeAll(() => registerEChartsModules());++ const CATEGORIES = ["Doohickey", "Gadget", "Gizmo", "Widget"];++ // Bars render as `<path d="M{x} {y}l{w} 0l0 {h}l-{w} 0Z">`; returns each+ // series-0 bar's top, length and thickness.+ const getBarRects = (svg: string) =>+ [+ ...svg.matchAll(+ /<path d="M[\d.]+ ([\d.]+)l([\d.]+) 0l0 ([\d.]+)l-[\d.]+ 0Z"[^>]*ecmeta_series_index="0"/g,+ ),+ ].map((match) => ({+ top: Number(match[1]),+ length: Number(match[2]),+ thickness: Number(match[3]),+ }));++ const getRowChartOption = (+ values = CATEGORIES.map((_, index) => 100 * (index + 1)),+ extraSettings: VisualizationSettings = {},+ ) => {+ const renderingContext: RenderingContext = {+ ...mockRenderingContext,+ getColor: () => "#509EE3",+ };+ const rowSettings = createMockVisualizationSettings({+ "graph.dimensions": ["CATEGORY"],+ "graph.metrics": ["count"],+ "graph.x_axis.scale": "ordinal",+ series: () => ({ display: "bar" }),+ ...extraSettings,+ });+ const rawSeries: RawSeries = [+ {+ card: createMockCard({ display: "row" }),+ data: createMockDatasetData({+ rows: CATEGORIES.map((category, index) => [category, values[index]]),+ cols: [+ createMockColumn({ name: "CATEGORY", base_type: "type/Text" }),+ createMockColumn({ name: "count", base_type: "type/Integer" }),+ ],+ }),+ },+ ];+ const chartModel = getCartesianChartModel(+ rawSeries,+ rowSettings,+ hiddenSeries,+ renderingContext,+ );+ const chartLayout = getChartLayout(+ chartModel,+ rowSettings,+ hasTimelineEvents,+ chartWidth,+ chartHeight,+ renderingContext,+ );++ return getCartesianChartOption(+ chartModel,+ chartLayout,+ hasTimelineEvents,+ null,+ [],+ rowSettings,+ chartWidth,+ false,+ renderingContext,+ );+ };++ const renderRowChartBars = (values?: number[]) => {+ const chart = echarts.init(null, null, {+ renderer: "svg",+ ssr: true,+ width: chartWidth,+ height: chartHeight,+ });+ chart.setOption(getRowChartOption(values));+ const bars = getBarRects(chart.renderToSVGString());+ chart.dispose();++ expect(bars).toHaveLength(CATEGORIES.length);+ return { bars, pitch: bars[1].top - bars[0].top };+ };++ it("gives each bar 80% of its category band, like the legacy renderer", () => {+ const { bars, pitch } = renderRowChartBars();++ for (const { thickness } of bars) {+ expect(thickness / pitch).toBeCloseTo(0.8, 2);+ }+ });++ it("keeps 20% of a band clear above the first bar, like the legacy renderer", () => {+ const { bars, pitch } = renderRowChartBars();++ // With no goal label, the plot starts at the base top padding.+ expect((bars[0].top - CHART_STYLE.padding.y) / pitch).toBeCloseTo(0.2, 2);+ });++ it("draws near-zero bars at least 1px long", () => {+ const { bars } = renderRowChartBars([1_000_000, 1, 2, 3]);++ for (const { length } of bars) {+ expect(length).toBeGreaterThanOrEqual(1);+ }+ });++ it("puts value labels at the end of each bar, on the side it grows", () => {+ const option = getRowChartOption([120, -80, 60, -40], {+ "graph.show_values": true,+ series: () => ({ display: "bar", show_series_values: true }),+ });+ // Row charts build an array of series options; the bar series comes first.+ const [barSeries, ...labelSeries] = option.series as BarSeriesOption[];+ const labelFor = (sign: "+" | "-") =>+ labelSeries.find((series) =>+ String(series.id).endsWith(getBarSeriesDataLabelKey("1:count", sign)),+ );++ // The bar's own label only shows on hover, in place of the label series.+ expect(barSeries.label?.position).toBe("outside");+ expect(labelFor("+")?.label?.position).toBe("right");+ expect(labelFor("-")?.label?.position).toBe("left");+ expect(labelFor("-")?.encode).toEqual({+ x: getBarSeriesDataLabelKey("1:count", "-"),+ y: X_AXIS_DATA_KEY,+ });+ });++ const getRowChartAxes = (extraSettings?: VisualizationSettings) => {+ const option = getRowChartOption(undefined, extraSettings);+ // Row charts always build an x axis array, holding the metric axes.+ const [metricAxis] = option.xAxis as XAXisOption[];+ // ...and a one-element y axis array, holding the category axis.+ const [categoryAxis] = option.yAxis as YAXisOption[];+ return { metricAxis, categoryAxis };+ };++ it("puts the categories down the left, first row on top, and the metric along the bottom", () => {+ const { metricAxis, categoryAxis } = getRowChartAxes();++ expect(categoryAxis).toMatchObject({+ type: "category",+ position: "left",+ inverse: true,+ });+ expect(metricAxis.position).toBe("bottom");+ });++ it("draws the metric axis line only while the metric axis is shown", () => {+ const getAxisLine = (isShown: boolean) =>+ getRowChartAxes({ "graph.y_axis.axis_enabled": isShown }).metricAxis+ .axisLine?.show;++ expect(getAxisLine(true)).toBe(true);+ expect(getAxisLine(false)).toBe(false);+ });++ it("gives each rotated axis the tick label margin of the side it's drawn on", () => {+ const { ticks } = DEFAULT_VISUALIZATION_THEME.cartesian;+ const { metricAxis, categoryAxis } = getRowChartAxes();++ expect(metricAxis.axisLabel?.margin).toBe(ticks.marginX);+ expect(categoryAxis.axisLabel?.margin).toBe(ticks.marginY);+ });++ it("puts axis titles as far from their tick labels as upright charts do", () => {+ const { ticks, axisTitle } = DEFAULT_VISUALIZATION_THEME.cartesian;+ const { metricAxis, categoryAxis } = getRowChartAxes();++ // Labels measure 0px wide here, so only the font and margins remain.+ expect(metricAxis.nameGap).toBe(+ ticks.fontSize + ticks.marginX + axisTitle.marginX,+ );+ expect(categoryAxis.nameGap).toBe(ticks.marginY + axisTitle.marginY);+ });++ it("lets ECharts keep metric tick labels inside the chart, but not move axis names", () => {+ expect(getRowChartOption().grid).toMatchObject({+ outerBoundsMode: "auto",+ outerBoundsContain: "axisLabel",+ });+ });+});++describe("chart grid bounds", () => {+ it("keeps upright charts inside the layout's own padding", () => {+ seriesFn.mockReturnValue({ display: "bar" });+ const renderingContext: RenderingContext = {+ ...mockRenderingContext,+ getColor: () => "#509EE3",+ };+ const chartModel = getCartesianChartModel(+ [mockSeries],+ mockSettings,+ hiddenSeries,+ renderingContext,+ );+ const chartLayout = getChartLayout(+ chartModel,+ mockSettings,+ hasTimelineEvents,+ chartWidth,+ chartHeight,+ renderingContext,+ );+ const option = getCartesianChartOption(+ chartModel,+ chartLayout,+ hasTimelineEvents,+ null,+ [],+ mockSettings,+ chartWidth,+ false,+ renderingContext,+ );++ expect(option.grid).toMatchObject({ outerBoundsMode: "none" });+ });+});diff --git a/frontend/src/metabase/viz-core/echarts/cartesian/option/series.ts b/frontend/src/metabase/viz-core/echarts/cartesian/option/series.tsindex 55ec8f2f444..db9e3b3176d 100644--- a/frontend/src/metabase/viz-core/echarts/cartesian/option/series.ts+++ b/frontend/src/metabase/viz-core/echarts/cartesian/option/series.ts@@ -56,6 +56,7 @@ import type {XAxisModel,} from "../model/types";import { getBarSeriesDataLabelKey } from "../model/util";+import { ROW_CHART_STYLE } from "../row/constants";import { getPadding } from "./ticks";import type { EChartsSeriesOption } from "./types";@@ -160,15 +161,24 @@ export function getDataLabelFormatter(yAxisScaleTransforms: NumericAxisScaleTransforms,formatter: LabelFormatter,chartWidth: number,- settings?: ComputedVisualizationSettings,- chartDataDensity?: ChartDataDensity,- accessor?: (datum: Datum) => RowValue,+ {+ settings,+ chartDataDensity,+ accessor,+ isRowChart = false,+ }: {+ settings?: ComputedVisualizationSettings;+ chartDataDensity?: ChartDataDensity;+ accessor?: (datum: Datum) => RowValue;+ isRowChart?: boolean;+ } = {},) {const getShowLabel = getShowLabelFn(chartWidth,dataKey,chartDataDensity,settings,+ isRowChart,);return (params: CallbackDataParams) => {@@ -189,10 +199,15 @@ function getShowLabelFn(dataKey: DataKey,chartDataDensity?: ChartDataDensity,settings?: ComputedVisualizationSettings,+ isRowChart = false,): (params: CallbackDataParams) => boolean {if (!settings || !chartDataDensity) {return () => true;}+ // Row charts hanle this with row folding+ if (isRowChart) {+ return () => true;+ }if (settings["graph.label_value_frequency"] === "all") {return () => true;}@@ -288,10 +303,19 @@ export const buildEChartsLabelOptions = (yAxisScaleTransforms: NumericAxisScaleTransforms,renderingContext: RenderingContext,chartWidth: number,- formatter?: LabelFormatter,- settings?: ComputedVisualizationSettings,- chartDataDensity?: ChartDataDensity,- position?: LabelOption["position"],+ {+ formatter,+ settings,+ chartDataDensity,+ position,+ isRowChart = false,+ }: {+ formatter?: LabelFormatter;+ settings?: ComputedVisualizationSettings;+ chartDataDensity?: ChartDataDensity;+ position?: LabelOption["position"];+ isRowChart?: boolean;+ } = {},): SeriesLabelOption => {const { fontSize } = renderingContext.theme.cartesian.label;@@ -313,8 +337,7 @@ export const buildEChartsLabelOptions = (yAxisScaleTransforms,formatter,chartWidth,- settings,- chartDataDensity,+ { settings, chartDataDensity, isRowChart },),};};@@ -512,10 +535,18 @@ function getDataLabelSeriesOption(formatter: (params: CallbackDataParams) => string,position: LabelOption["position"],renderingContext: RenderingContext,- showInBlur = true,+ {+ isRowChart = false,+ showInBlur = true,+ }: { isRowChart?: boolean; showInBlur?: boolean } = {},) {const stackName = seriesOption.stack;+ // Callers pass upright positions; rotated, top/bottom become right/left.+ const rotatedPosition =+ position === "top" ? "right" : position === "bottom" ? "left" : position;+ const labelPosition = isRowChart ? rotatedPosition : position;+const dataLabelSeriesOption = {xAxisIndex: seriesOption.xAxisIndex,yAxisIndex: seriesOption.yAxisIndex,@@ -526,14 +557,13 @@ function getDataLabelSeriesOption(},id: `${stackName}_${dataKey}`,stack: stackName,- encode: {- y: dataKey,- x: X_AXIS_DATA_KEY,- },+ encode: isRowChart+ ? { x: dataKey, y: X_AXIS_DATA_KEY }+ : { y: dataKey, x: X_AXIS_DATA_KEY },label: {...seriesOption.label,show: true,- position,+ position: labelPosition,formatter,fontFamily: renderingContext.fontFamily,fontWeight: CHART_STYLE.seriesLabels.weight,@@ -579,6 +609,7 @@ const buildEChartsBarSeries = (renderingContext: RenderingContext,stackModel: StackModel | undefined,xAxisIndex?: number,+ isRowChart = false,): BarSeriesOption | BarSeriesOption[] => {const stack = stackName ?? `bar_${seriesModel.dataKey}`;const isStacked = settings["stackable.stack_type"] != null;@@ -604,6 +635,9 @@ const buildEChartsBarSeries = (yAxisIndex,barGap: 0,barMinHeight: 1,+ ...(isRowChart && {+ barCategoryGap: ROW_CHART_STYLE.barCategoryGap,+ }),stack,barWidth: computeBarWidth(xAxisModel,@@ -612,10 +646,9 @@ const buildEChartsBarSeries = (isStacked,settings["graph.x_axis.scale"],),- encode: {- y: seriesModel.dataKey,- x: X_AXIS_DATA_KEY,- },+ encode: isRowChart+ ? { x: seriesModel.dataKey, y: X_AXIS_DATA_KEY }+ : { y: seriesModel.dataKey, x: X_AXIS_DATA_KEY },label: isStacked? buildEChartsStackLabelOptions(seriesModel,@@ -625,33 +658,40 @@ const buildEChartsBarSeries = (settings,stackModel,)- : buildEChartsLabelOptions(- seriesModel,- yAxisScaleTransforms,- renderingContext,- chartWidth,- labelFormatter,- settings,- chartDataDensity,- ["50%", 0],- ),- labelLayout: isStacked- ? getBarInsideLabelLayout(- dataset,- settings,- seriesModel.dataKey,- chartLayout.stackedBarTicksRotation,- )- : getBarLabelLayout({- settings,- getNegativeBarYOffset: ({ rect }) => rect.height,- getBarDirection: ({ dataIndex }) => {- if (dataIndex == null) {- return null;- }- return dataset[dataIndex][seriesModel.dataKey];- },- }),+ : {+ ...buildEChartsLabelOptions(+ seriesModel,+ yAxisScaleTransforms,+ renderingContext,+ chartWidth,+ {+ formatter: labelFormatter,+ settings,+ chartDataDensity,+ isRowChart,+ },+ ),+ position: isRowChart ? "outside" : ["50%", 0],+ },+ labelLayout: isRowChart+ ? undefined+ : isStacked+ ? getBarInsideLabelLayout(+ dataset,+ settings,+ seriesModel.dataKey,+ chartLayout.stackedBarTicksRotation,+ )+ : getBarLabelLayout({+ settings,+ getNegativeBarYOffset: ({ rect }) => rect.height,+ getBarDirection: ({ dataIndex }) => {+ if (dataIndex == null) {+ return null;+ }+ return dataset[dataIndex][seriesModel.dataKey];+ },+ }),itemStyle: {color: seriesModel.color,},@@ -678,23 +718,29 @@ const buildEChartsBarSeries = (yAxisScaleTransforms,labelFormatter,chartWidth,- settings,- chartDataDensity,- (datum) => {- const value = datum[seriesModel.dataKey];- const isZero = value === null && datum[labelDataKey] != null;- return isZero ? 0 : value;+ {+ settings,+ chartDataDensity,+ accessor: (datum) => {+ const value = datum[seriesModel.dataKey];+ const isZero = value === null && datum[labelDataKey] != null;+ return isZero ? 0 : value;+ },+ isRowChart,},),- ["50%", 0],+ // Negative rotated bars grow leftward, so their labels go on the left.+ isRowChart ? (sign === "+" ? "right" : "left") : ["50%", 0],renderingContext,- false,+ { isRowChart, showInBlur: false },),- labelLayout: getBarLabelLayout({- settings,- getBarDirection: () => (sign === "+" ? 1 : -1),- getNegativeBarYOffset: () => 0,- }),+ labelLayout: isRowChart+ ? undefined+ : getBarLabelLayout({+ settings,+ getBarDirection: () => (sign === "+" ? 1 : -1),+ getNegativeBarYOffset: () => 0,+ }),type: "bar", // ensure type is bar for typescript};},@@ -791,10 +837,12 @@ const buildEChartsLineAreaSeries = (yAxisScaleTransforms,renderingContext,chartWidth,- labelFormatter,- settings,- chartDataDensity,- "top",+ {+ formatter: labelFormatter,+ settings,+ chartDataDensity,+ position: "top",+ },),labelLayout: {hideOverlap: settings["graph.label_value_frequency"] === "fit",@@ -850,12 +898,14 @@ function getStackedDataLabelFormatter(chartDataDensity: ComboChartDataDensity,chartWidth: number,settings: ComputedVisualizationSettings,+ isRowChart = false,) {const getShowStackedLabel = getShowStackedLabelFn(chartWidth,stackName,chartDataDensity,settings,+ isRowChart,);return (params: CallbackDataParams) => {@@ -889,10 +939,14 @@ function getShowStackedLabelFn(stackName: string | undefined,chartDataDensity: ComboChartDataDensity,settings: ComputedVisualizationSettings,+ isRowChart = false,): (params: CallbackDataParams) => boolean {if (!settings || !chartDataDensity) {return () => true;}+ if (isRowChart) {+ return () => true;+ }if (settings["graph.label_value_frequency"] === "all") {return () => true;}@@ -964,6 +1018,7 @@ export const getStackTotalsSeries = (chartWidth: number,seriesOptions: (LineSeriesOption | BarSeriesOption)[],renderingContext: RenderingContext,+ isRowChart = false,) => {const seriesByStackName = _.groupBy(seriesOptions.filter((s) => s.stack != null),@@ -1005,9 +1060,11 @@ export const getStackTotalsSeries = (chartModel.dataDensity,chartWidth,settings,+ isRowChart,),"top",renderingContext,+ { isRowChart },),getDataLabelSeriesOption(NEGATIVE_STACK_TOTAL_DATA_KEY,@@ -1024,9 +1081,11 @@ export const getStackTotalsSeries = (chartModel.dataDensity,chartWidth,settings,+ isRowChart,),"bottom",renderingContext,+ { isRowChart },),];});@@ -1131,6 +1190,7 @@ export const buildEChartsSeries = (renderingContext,stackModel,panelIndex,+ chartModel.isRowChart,);}}@@ -1172,6 +1232,7 @@ export const buildEChartsSeries = (chartWidth,series,renderingContext,+ chartModel.isRowChart,),);}diff --git a/frontend/src/metabase/viz-core/echarts/cartesian/option/ticks.ts b/frontend/src/metabase/viz-core/echarts/cartesian/option/ticks.tsindex 3044a7a27c0..a79afdd072e 100644--- a/frontend/src/metabase/viz-core/echarts/cartesian/option/ticks.ts+++ b/frontend/src/metabase/viz-core/echarts/cartesian/option/ticks.ts@@ -1,6 +1,6 @@import { type Dayjs, dayjs } from "metabase/dayjs";-import type { ContinuousDomain } from "../../../shared/types/scale";+import type { Extent } from "../../../types";import type { ChartLayout } from "../layout/types";import type {TimeSeriesAxisFormatter,@@ -49,7 +49,7 @@ export const getTicksOptions = (throw new Error(`Invalid range dates: ${JSON.stringify(range)}`);}return adjustedDate.valueOf();- }) as ContinuousDomain;+ }) as Extent;const isSingleItem = xDomain[0] === xDomain[1];const padding = getPadding(intervalsCount);diff --git a/frontend/src/metabase/viz-core/echarts/cartesian/row/constants.ts b/frontend/src/metabase/viz-core/echarts/cartesian/row/constants.tsnew file mode 100644index 00000000000..75ea3429eea--- /dev/null+++ b/frontend/src/metabase/viz-core/echarts/cartesian/row/constants.ts@@ -0,0 +1,4 @@+export const ROW_CHART_STYLE = {+ barCategoryGap: "20%",+ bandOuterPadding: 0.2,+} as const;diff --git a/frontend/src/metabase/viz-core/echarts/cartesian/row/option/goal-line.ts b/frontend/src/metabase/viz-core/echarts/cartesian/row/option/goal-line.tsnew file mode 100644index 00000000000..1a6a372ef98--- /dev/null+++ b/frontend/src/metabase/viz-core/echarts/cartesian/row/option/goal-line.ts@@ -0,0 +1,133 @@+import type { CustomSeriesOption } from "echarts/charts";++import type {+ ComputedVisualizationSettings,+ RenderingContext,+} from "../../../../types";+import type { EChartsCartesianCoordinateSystem } from "../../../types";+import { GOAL_LINE_SERIES_ID } from "../../constants/dataset";+import { CHART_STYLE, Z_INDEXES } from "../../constants/style";+import {+ GOAL_LINE_DASH,+ GOAL_LINE_WIDTH,+ type GoalLineParams,+ buildGoalLineMarker,+ getFirstNonNullXValue,+ getGoalLineValue,+} from "../../option/goal-line";++// Row charts: the goal is an x-coordinate and the line runs vertically.+export function getRowGoalLineSeriesOption(+ {+ dataset,+ isNormalized,+ toEChartsAxisValue,+ }: Pick<GoalLineParams, "dataset" | "isNormalized" | "toEChartsAxisValue">,+ settings: ComputedVisualizationSettings,+ renderingContext: RenderingContext,+): CustomSeriesOption | null {+ if (!settings["graph.show_goal"] || settings["graph.goal_value"] == null) {+ return null;+ }++ const scaleTransformedGoalValue = getGoalLineValue(+ settings["graph.goal_value"],+ { isNormalized, toEChartsAxisValue },+ );+ const { fontSize } = renderingContext.theme.cartesian.goalLine.label;+ const labelText = settings["graph.goal_label"] ?? "";+ const labelWidth = renderingContext.measureText(labelText, {+ family: renderingContext.fontFamily,+ size: fontSize,+ weight: CHART_STYLE.goalLine.label.weight,+ });++ return {+ id: GOAL_LINE_SERIES_ID,+ type: "custom",+ data: [[scaleTransformedGoalValue, getFirstNonNullXValue(dataset)]],+ z: Z_INDEXES.goalLine,+ blur: {+ opacity: 1,+ },+ renderItem: (params, api) => {+ const coordSys =+ // ECharts types coordSys as `{ type }`; a cartesian series gets the grid rect.+ params.coordSys as unknown as EChartsCartesianCoordinateSystem;+ const [goalX] = api.coord([scaleTransformedGoalValue, null]);+ const xEnd = coordSys.width + coordSys.x;+ const yStart = coordSys.y;+ const yEnd = coordSys.height + coordSys.y;+ // Snapped to the pixel grid so the line and its shadow beside it stay crisp.+ const lineX =+ Math.round(goalX - GOAL_LINE_WIDTH / 2) + GOAL_LINE_WIDTH / 2;++ const getLine = (offsetX: number, stroke: string) => ({+ type: "line" as const,+ shape: {+ x1: lineX + offsetX,+ x2: lineX + offsetX,+ y1: yStart,+ y2: Math.round(yEnd),+ },+ // Only the marker is a hover target, so the line itself is inert.+ silent: true,+ blur: {+ style: {+ opacity: 1,+ },+ },+ emphasis: {+ style: {+ stroke,+ },+ },+ style: {+ lineWidth: GOAL_LINE_WIDTH,+ stroke,+ color: stroke,+ lineDash: GOAL_LINE_DASH,+ },+ });++ const line = getLine(0, renderingContext.getColor("icon-primary"));+ const lineShadow = getLine(+ GOAL_LINE_WIDTH,+ renderingContext.getColor("background_surface-primary"),+ );++ // Static renders keep the label above the line, flipped left near the+ // right edge; interactive ones get the marker.+ const endDecoration = renderingContext.isStatic+ ? [+ {+ type: "text" as const,+ x: lineX,+ y: yStart - fontSize - CHART_STYLE.goalLine.label.margin,+ blur: {+ style: {+ opacity: 1,+ },+ },+ style: {+ align:+ lineX + labelWidth > xEnd+ ? ("right" as const)+ : ("left" as const),+ text: labelText,+ fontFamily: renderingContext.fontFamily,+ fontSize,+ fontWeight: CHART_STYLE.goalLine.label.weight,+ fill: renderingContext.getColor("text-secondary"),+ },+ },+ ]+ : buildGoalLineMarker({ xEnd: lineX, y: yStart, renderingContext });++ return {+ type: "group" as const,+ children: [lineShadow, line, ...endDecoration],+ };+ },+ };+}diff --git a/frontend/src/metabase/viz-core/echarts/cartesian/row/option/goal-line.unit.spec.ts b/frontend/src/metabase/viz-core/echarts/cartesian/row/option/goal-line.unit.spec.tsnew file mode 100644index 00000000000..f12b59e8492--- /dev/null+++ b/frontend/src/metabase/viz-core/echarts/cartesian/row/option/goal-line.unit.spec.ts@@ -0,0 +1,160 @@+import { CustomChart } from "echarts/charts";+import { GridComponent } from "echarts/components";+import * as echarts from "echarts/core";+import { SVGRenderer } from "echarts/renderers";++import { DEFAULT_VISUALIZATION_THEME } from "../../../../shared/utils/theme";+import type {+ ComputedVisualizationSettings,+ RenderingContext,+} from "../../../../types";+import { GOAL_LINE_SERIES_ID, X_AXIS_DATA_KEY } from "../../constants/dataset";++import { getRowGoalLineSeriesOption } from "./goal-line";++echarts.use([CustomChart, GridComponent, SVGRenderer]);++const CHART_WIDTH = 600;+const CHART_HEIGHT = 400;+const GRID_MARGIN = 50;+const X_AXIS_MAX = 100;+const GOAL_LABEL = "Target";++const goalX = (goalValue: number) =>+ GRID_MARGIN + ((CHART_WIDTH - 2 * GRID_MARGIN) * goalValue) / X_AXIS_MAX;++const PARAMS = {+ dataset: [{ [X_AXIS_DATA_KEY]: "a" }],+ isNormalized: false,+ toEChartsAxisValue: (value: unknown) => Number(value),+};++const createSettings = (+ opts: Partial<ComputedVisualizationSettings> = {},+): ComputedVisualizationSettings => ({+ "graph.show_goal": true,+ "graph.goal_value": X_AXIS_MAX / 2,+ "graph.goal_label": GOAL_LABEL,+ ...opts,+});++const createRenderingContext = (+ opts: Partial<RenderingContext> = {},+): RenderingContext => ({+ getColor: (name) => name,+ measureText: () => 0,+ measureTextHeight: () => 0,+ fontFamily: "Lato",+ theme: DEFAULT_VISUALIZATION_THEME,+ ...opts,+});++interface SetupOpts {+ settings?: Partial<ComputedVisualizationSettings>;+ renderingContext?: Partial<RenderingContext>;+}++const charts: echarts.ECharts[] = [];++const setup = ({ settings, renderingContext }: SetupOpts = {}) => {+ const container = document.createElement("div");+ document.body.appendChild(container);++ const chart = echarts.init(container, undefined, {+ renderer: "svg",+ width: CHART_WIDTH,+ height: CHART_HEIGHT,+ });+ charts.push(chart);++ chart.setOption({+ animation: false,+ grid: {+ left: GRID_MARGIN,+ right: GRID_MARGIN,+ top: GRID_MARGIN,+ bottom: GRID_MARGIN,+ outerBoundsMode: "none",+ },+ xAxis: { type: "value", min: 0, max: X_AXIS_MAX },+ yAxis: { type: "category", data: ["a", "b", "c"] },+ series: [+ getRowGoalLineSeriesOption(+ PARAMS,+ createSettings(settings),+ createRenderingContext(renderingContext),+ ),+ ],+ });++ const onGoalHover = jest.fn();+ chart.on("mousemove", { seriesId: GOAL_LINE_SERIES_ID }, onGoalHover);++ const hover = (position: { zrX: number; zrY: number }) =>+ chart.getZr().handler.dispatch("mousemove", position);++ const getGoalLabel = () =>+ Array.from(container.querySelectorAll("text")).find(+ (text) => text.textContent === GOAL_LABEL,+ );++ return { onGoalHover, hover, getGoalLabel };+};++describe("getRowGoalLineSeriesOption", () => {+ afterEach(() => {+ charts.splice(0).forEach((chart) => chart.dispose());+ document.body.innerHTML = "";+ });++ it("returns null when the goal is not enabled or has no value", () => {+ expect(+ getRowGoalLineSeriesOption(+ PARAMS,+ createSettings({ "graph.show_goal": false }),+ createRenderingContext(),+ ),+ ).toBeNull();+ expect(+ getRowGoalLineSeriesOption(+ PARAMS,+ createSettings({ "graph.goal_value": undefined }),+ createRenderingContext(),+ ),+ ).toBeNull();+ });++ it("triggers the goal tooltip only from the marker at the line's top end", () => {+ const { hover, onGoalHover } = setup();+ const x = goalX(X_AXIS_MAX / 2);++ hover({ zrX: x, zrY: CHART_HEIGHT / 2 });+ hover({ zrX: x, zrY: CHART_HEIGHT - GRID_MARGIN });+ expect(onGoalHover).not.toHaveBeenCalled();++ hover({ zrX: x, zrY: GRID_MARGIN });+ expect(onGoalHover).toHaveBeenCalledTimes(1);+ });++ describe("static rendering", () => {+ it("shows the label, which interactive charts replace with the marker", () => {+ const staticChart = setup({ renderingContext: { isStatic: true } });+ const interactiveChart = setup();++ expect(staticChart.getGoalLabel()).toBeDefined();+ expect(interactiveChart.getGoalLabel()).toBeUndefined();+ });++ it("flips the label left of the line when it would overflow the plot", () => {+ const renderingContext = { isStatic: true, measureText: () => 100 };+ const middle = setup({ renderingContext });+ const nearMax = setup({+ settings: { "graph.goal_value": X_AXIS_MAX * 0.9 },+ renderingContext,+ });++ expect(middle.getGoalLabel()?.getAttribute("text-anchor")).toBe("start");+ expect(nearMax.getGoalLabel()?.getAttribute("text-anchor")).toBe("end");+ });+ });+});diff --git a/frontend/src/metabase/viz-core/echarts/cartesian/row/spacing.ts b/frontend/src/metabase/viz-core/echarts/cartesian/row/spacing.tsnew file mode 100644index 00000000000..9b6615625b1--- /dev/null+++ b/frontend/src/metabase/viz-core/echarts/cartesian/row/spacing.ts@@ -0,0 +1,10 @@+import type { VisualizationTheme } from "../../../types";++export const getRowChartSpacing = ({ cartesian }: VisualizationTheme) => ({+ tickFontSize: cartesian.ticks.fontSize,+ categoryTickMargin: cartesian.ticks.marginY,+ metricTickMargin: cartesian.ticks.marginX,+ axisTitleFontSize: cartesian.axisTitle.fontSize,+ metricAxisTitleMargin: cartesian.axisTitle.marginX,+ dimensionAxisTitleMargin: cartesian.axisTitle.marginY,+});diff --git a/frontend/src/metabase/viz-core/echarts/cartesian/utils/timeseries.ts b/frontend/src/metabase/viz-core/echarts/cartesian/utils/timeseries.tsindex 0300e1c53fa..20a42cd1816 100644--- a/frontend/src/metabase/viz-core/echarts/cartesian/utils/timeseries.ts+++ b/frontend/src/metabase/viz-core/echarts/cartesian/utils/timeseries.ts@@ -14,7 +14,7 @@ import {multipleTimezoneWarning,unexpectedTimezoneWarning,} from "../../../lib/warnings";-import type { ContinuousDomain } from "../../../shared/types/scale";+import type { Extent } from "../../../types";import type { ShowWarning } from "../../types";import type { ChartLayout } from "../layout/types";import type {@@ -302,7 +302,7 @@ export function getGridTickDates(// over years) would otherwise allocate millions of dates.export function expectedTickCount(interval: TimeSeriesInterval,- xDomain: ContinuousDomain,+ xDomain: Extent,dataUnit: TimeSeriesInterval["unit"] = interval.unit,): number {if (interval.unit === "ms") {@@ -324,7 +324,7 @@ export function expectedTickCount(/// Get the appropriate tick interval option from the TIMESERIES_INTERVALS above based on the xAxis bucketing/// and the max number of ticks we want to show (itself calculated from chart width).export function computeTimeseriesTicksInterval(- xDomain: ContinuousDomain,+ xDomain: Extent,xInterval: TimeSeriesInterval,chartLayout: ChartLayout,formatter: TimeSeriesAxisFormatter,diff --git a/frontend/src/metabase/viz-core/echarts/cartesian/waterfall/option/index.ts b/frontend/src/metabase/viz-core/echarts/cartesian/waterfall/option/index.tsindex 0d2d217a3db..2eee52f7fe8 100644--- a/frontend/src/metabase/viz-core/echarts/cartesian/waterfall/option/index.ts+++ b/frontend/src/metabase/viz-core/echarts/cartesian/waterfall/option/index.ts@@ -117,7 +117,7 @@ export const buildEChartsWaterfallSeries = (chartModel.yAxisScaleTransforms,renderingContext,chartWidth,- labelFormatter,+ { formatter: labelFormatter },),formatter:labelFormatter &&@@ -126,8 +126,7 @@ export const buildEChartsWaterfallSeries = (chartModel.yAxisScaleTransforms,labelFormatter,chartWidth,- settings,- chartModel.dataDensity,+ { settings, chartDataDensity: chartModel.dataDensity },),});diff --git a/frontend/src/metabase/viz-core/echarts/tooltip/utils.ts b/frontend/src/metabase/viz-core/echarts/tooltip/utils.tsindex 2a744087d1f..b82c54ae48c 100644--- a/frontend/src/metabase/viz-core/echarts/tooltip/utils.ts+++ b/frontend/src/metabase/viz-core/echarts/tooltip/utils.ts@@ -1,5 +1,3 @@-import { t } from "ttag";-import type { TooltipRowModel } from "../../types";export const getTotalValue = (@@ -19,46 +17,3 @@ export const getPercent = (total: number, value: unknown) => {return value / Math.abs(total);};--export const groupExcessiveTooltipRows = (- rows: TooltipRowModel[],- maxRows: number,- groupedColor?: string,-) => {- if (rows.length <= maxRows) {- return rows;- }-- const groupStartingFromIndex = maxRows - 1;- const rowsToKeep = rows.slice(0, groupStartingFromIndex);- const rowsToGroup = rows.slice(groupStartingFromIndex);-- const groupedRow = rowsToGroup.reduce(- (grouped, current) => {- if (- typeof current.value === "number" &&- typeof grouped.value === "number"- ) {- grouped.value += current.value;- }- return grouped;- },- {- color: groupedColor,- name: t`Other`,- value: 0,- formatter: rowsToGroup[0].formatter,- },- );-- return [...rowsToKeep, groupedRow];-};--export const getSortedRows = <TRow extends TooltipRowModel>(rows: TRow[]) => {- return [...rows].sort(({ value: leftValue }, { value: rightValue }) => {- return (- (typeof rightValue === "number" ? rightValue : 0) -- (typeof leftValue === "number" ? leftValue : 0)- );- });-};diff --git a/frontend/src/metabase/viz-core/index.ts b/frontend/src/metabase/viz-core/index.tsindex fc465a21209..ffdbd40fccd 100644--- a/frontend/src/metabase/viz-core/index.ts+++ b/frontend/src/metabase/viz-core/index.ts@@ -16,6 +16,7 @@ export { extractSeriesDataKeyFromName } from "./echarts/boxplot/utils";export {GOAL_LINE_SERIES_ID,INDEX_KEY,+ IS_FOLDED_ROW_DATA_KEY,IS_WATERFALL_TOTAL_DATA_KEY,OTHER_DATA_KEY,X_AXIS_DATA_KEY,@@ -26,6 +27,7 @@ export {TIMELINE_BAND_HEIGHT,TIMELINE_EVENTS_BAND,} from "./echarts/cartesian/constants/style";+export { foldRowChartModel } from "./echarts/cartesian/model/row-fold";export { getChartLayout } from "./echarts/cartesian/layout";export type {ChartBoundsCoords,@@ -205,12 +207,7 @@ export {usePieChartValuesColorsClasses,useSankeyChartColorsClasses,} from "./echarts/tooltip";-export {- getPercent,- getSortedRows,- getTotalValue,- groupExcessiveTooltipRows,-} from "./echarts/tooltip/utils";+export { getPercent, getTotalValue } from "./echarts/tooltip/utils";export { isLineXBrushRange } from "./echarts/types";export type {EChartsSeriesBrushEndEvent,@@ -311,6 +308,7 @@ export {getSeriesWithDisplay,getVisualizerSeriesCardId,getVisualizerSeriesCardIndex,+ isRowChartSeries,updateSeriesColor,} from "./lib/series";export {@@ -328,7 +326,7 @@ export {NUMBER_COLUMN_SETTINGS,tableColumnSettings,} from "./lib/settings/column";-export { getChartGoal, GRAPH_GOAL_SETTINGS } from "./lib/settings/goal";+export { GRAPH_GOAL_SETTINGS } from "./lib/settings/goal";export {BOXPLOT_DATA_SETTINGS,BOXPLOT_SETTINGS,@@ -347,7 +345,6 @@ export {} from "./lib/settings/graph";export { nestedSettings } from "./lib/settings/nested";export { keyForSingleSeries } from "./lib/settings/series";-export { getStackOffset } from "./lib/settings/stacking";export { TIMELINE_EVENTS_SETTINGS } from "./lib/settings/timelineEvents";export {extendCardWithDashcardSettings,@@ -393,7 +390,6 @@ export {export { truncateText } from "./lib/text";export { dimensionIsTimeseries } from "./lib/timeseries";export { getTimeseriesXAxis } from "./lib/timeseries-x-axis";-export { formatValueForTooltipWithoutScaling } from "./lib/tooltip";export {computePreviousPeriodChange,findPreviousNonEmptyRowIndex,@@ -418,18 +414,12 @@ export {unaggregatedDataWarningMap,} from "./lib/warnings";export { getSettingsWidgets, getSettingsWidgetsForSeries } from "./lib/widgets";-export { RowChart } from "./shared/components/RowChart/RowChart";-export type { RowChartProps } from "./shared/components/RowChart/RowChart";-export { getStaticChartTheme } from "./shared/components/RowChart/theme";-export type {- BarData,- RowChartTheme,- Series,-} from "./shared/components/RowChart/types";export { getSizeAdjustedSettings } from "./shared/settings-adjustments";export {getDefaultDimensionFilter,getDefaultMetricFilter,+ getIsXAxisLabelEnabledDefault,+ getIsYAxisLabelEnabledDefault,} from "./shared/settings/cartesian-chart";export {getDefaultPercentVisibility,@@ -446,21 +436,7 @@ export {} from "./shared/settings/pie";export { getSeriesColors, SERIES_SETTING_KEY } from "./shared/settings/series";export { getTreemapRows } from "./shared/settings/treemap";-export type {- GroupedDataset,- GroupedDatum,- MetricDatum,- SeriesInfo,-} from "./shared/types/data";-export type { HoveredData } from "./shared/types/events";-export type { ChartTicksFormatters } from "./shared/types/format";-export type { ContinuousDomain, Range } from "./shared/types/scale";-export type { ChartGoal } from "./shared/types/settings";-export { getGroupedDataset, getSeries, trimData } from "./shared/utils/data";-export {- getLabelsMetricColumn,- getTwoDimensionalChartSeries,-} from "./shared/utils/series";+export { getSeries } from "./shared/utils/data";export { getSizeInPx } from "./shared/utils/size-in-px";export {getDefaultSize,@@ -496,11 +472,11 @@ export type {HighlightedObject,HoveredDimension,HoveredObject,- StackedTooltipModel,TooltipRowModel,} from "./types/hover";export type {CartesianChartSize,+ Extent,Padding,RenderingContext,StaticVisualizationProps,diff --git a/frontend/src/metabase/viz-core/lib/series.ts b/frontend/src/metabase/viz-core/lib/series.tsindex aa15293e96a..049fe6fcb72 100644--- a/frontend/src/metabase/viz-core/lib/series.ts+++ b/frontend/src/metabase/viz-core/lib/series.ts@@ -30,6 +30,10 @@ export const updateSeriesColor = ();};+// The first card decides the chart type, including for cards combined on a dashboard.+export const isRowChartSeries = (series?: RawSeries | Series) =>+ series?.[0]?.card.display === "row";+export const getNameForCard = (card: SeriesCard) => {return card?.name || "";};diff --git a/frontend/src/metabase/viz-core/lib/settings/goal.ts b/frontend/src/metabase/viz-core/lib/settings/goal.tsindex 91c83387a72..1bf42502998 100644--- a/frontend/src/metabase/viz-core/lib/settings/goal.ts+++ b/frontend/src/metabase/viz-core/lib/settings/goal.ts@@ -1,30 +1,8 @@import { t } from "ttag";-import type { VisualizationSettings } from "metabase-types/api";-import { getDefaultGoalLabel } from "../../shared/settings/cartesian-chart";-import type { ChartGoal } from "../../shared/types/settings";import type { VisualizationSettingsDefinitions } from "../../types";-import { getStackOffset } from "./stacking";--const getGoalValue = (value: number, isPercent: boolean) =>- isPercent ? value / 100 : value;--export const getChartGoal = (- settings: VisualizationSettings,-): ChartGoal | null => {- if (!settings["graph.show_goal"]) {- return null;- }- const isPercent = getStackOffset(settings) === "expand";-- return {- value: getGoalValue(settings["graph.goal_value"] ?? 0, isPercent),- label: settings["graph.goal_label"] ?? getDefaultGoalLabel(),- };-};-export const GRAPH_GOAL_SETTINGS: VisualizationSettingsDefinitions = {"graph.show_goal": {getSection: () => t`Display`,diff --git a/frontend/src/metabase/viz-core/lib/settings/series.ts b/frontend/src/metabase/viz-core/lib/settings/series.tsindex f4d7980cd63..7136ce33fdd 100644--- a/frontend/src/metabase/viz-core/lib/settings/series.ts+++ b/frontend/src/metabase/viz-core/lib/settings/series.ts@@ -31,7 +31,7 @@ import type {SettingsExtra,VisualizationSettingsDefinitions,} from "../../types";-import { getNameForCard } from "../series";+import { getNameForCard, isRowChartSeries } from "../series";import { type NestedSettingsOptions, nestedSettings } from "./nested";@@ -114,6 +114,8 @@ export function seriesSetting({getHidden: (single, settings, _extra) =>!["line", "area", "bar", "combo"].includes(single.card.display ?? "") ||settings["stackable.stack_type"] != null,+ // Row charts only draw bars; ignore a display saved as another chart type.+ isValid: (_single, _settings, extra) => !isRowChartSeries(extra?.series),getDefault: (single, _settings, extra) => {const { series = [] } = extra ?? {};if (keyForSingleSeries(single) === OTHER_DATA_KEY) {@@ -237,9 +239,11 @@ export function seriesSetting({return t`Y-axis position`;},widget: "segmentedControl",- getHidden: (single, _seriesSettings, extra) =>- single.card.display === "row" ||+ getHidden: (_single, _seriesSettings, extra) =>+ isRowChartSeries(extra?.series) ||extra?.settings?.["graph.split_panels"] === true,+ // Row charts have a single metric axis; ignore a saved position.+ isValid: (_single, _settings, extra) => !isRowChartSeries(extra?.series),getDefault: (_single, _seriesSettings, extra) =>extra?.settings?.["graph.split_panels"] === true ? "left" : null,getProps: () => ({diff --git a/frontend/src/metabase/viz-core/lib/settings/series.unit.spec.ts b/frontend/src/metabase/viz-core/lib/settings/series.unit.spec.tsindex 9d522977c3a..6b8ffb7c18b 100644--- a/frontend/src/metabase/viz-core/lib/settings/series.unit.spec.ts+++ b/frontend/src/metabase/viz-core/lib/settings/series.unit.spec.ts@@ -105,31 +105,50 @@ describe("Series unit settings", () => {});});-describe("series trend line settings", () => {- // the definitions map has a catch-all index signature, so type the nested- // widget props at this boundary to keep the guard calls below checked- type SeriesSettingsWidgetProps = {- getSettingDefinitionsForObject: (- series: Series,- single: SingleSeries,- ) => VisualizationSettingsDefinitions;- };-- const getSeriesSettingDefinitions = (+// the definitions map has a catch-all index signature, so type the nested+// widget props at this boundary to keep the guard calls below checked+type SeriesSettingsWidgetProps = {+ getSettingDefinitionsForObject: (series: Series,- settings: ComputedVisualizationSettings,- ): VisualizationSettingsDefinitions => {- const getProps = checkNotNull(- seriesSetting()[SERIES_SETTING_KEY]?.getProps,- );- const { getSettingDefinitionsForObject }: SeriesSettingsWidgetProps =- getProps(series, { [SERIES_SETTING_KEY]: {}, ...settings }, _.noop, {- series,- settings,+ single: SingleSeries,+ ) => VisualizationSettingsDefinitions;+};++const getSeriesSettingDefinitions = (+ series: Series,+ settings: ComputedVisualizationSettings,+): VisualizationSettingsDefinitions => {+ const getProps = checkNotNull(seriesSetting()[SERIES_SETTING_KEY]?.getProps);+ const { getSettingDefinitionsForObject }: SeriesSettingsWidgetProps =+ getProps(series, { [SERIES_SETTING_KEY]: {}, ...settings }, _.noop, {+ series,+ settings,+ });+ return getSettingDefinitionsForObject(series, series[0]);+};++describe("series axis setting", () => {+ it.each([+ ["row", true],+ ["bar", false],+ ] as const)(+ "hides the Y-axis position on %s charts: %s",+ (display, isHidden) => {+ const series = [createMockSingleSeries({ display })];+ const settings = createMockVisualizationSettings({+ "graph.metrics": ["count"],+ "graph.dimensions": ["CATEGORY"],});- return getSettingDefinitionsForObject(series, series[0]);- };+ const getHidden = checkNotNull(+ getSeriesSettingDefinitions(series, settings).axis?.getHidden,+ );++ expect(getHidden(series[0], {}, { series, settings })).toBe(isHidden);+ },+ );+});+describe("series trend line settings", () => {const getIsHidden = (key: "show_series_trendline" | "trendline.color" | "trendline.style",series: Series,diff --git a/frontend/src/metabase/viz-core/lib/settings/stacking.ts b/frontend/src/metabase/viz-core/lib/settings/stacking.tsdeleted file mode 100644index bd71c6b6b14..00000000000--- a/frontend/src/metabase/viz-core/lib/settings/stacking.ts+++ /dev/null@@ -1,15 +0,0 @@-import type { VisualizationSettings } from "metabase-types/api";--import type { StackOffset } from "../../shared/components/RowChart/types";--export const getStackOffset = (- settings: VisualizationSettings,-): StackOffset => {- if (settings["stackable.stack_type"] == null) {- return null;- }-- return settings["stackable.stack_type"] === "stacked"- ? "diverging"- : "expand";-};diff --git a/frontend/src/metabase/viz-core/lib/tooltip.ts b/frontend/src/metabase/viz-core/lib/tooltip.tsdeleted file mode 100644index 247ef576e56..00000000000--- a/frontend/src/metabase/viz-core/lib/tooltip.ts+++ /dev/null@@ -1,29 +0,0 @@-import { formatNullable } from "metabase/utils/formatting";-import { formatValue } from "metabase/value-formatting";-import type { DatasetColumn, VisualizationSettings } from "metabase-types/api";--import { getFormattingOptionsWithoutScaling } from "../echarts/cartesian/model/util";--export const formatValueForTooltipWithoutScaling = ({- value,- column,- settings,-}: {- value?: unknown;- column?: DatasetColumn;- settings?: VisualizationSettings;-}) => {- const nullableValue = formatNullable(value);-- // since we already transformed the dataset values, we do not need to- // consider scaling anymore- const options = getFormattingOptionsWithoutScaling({- ...(settings && settings.column && column- ? settings.column(column)- : { column }),- weekday_enabled: true,- type: "tooltip",- majorWidth: 0,- });- return formatValue(nullableValue, options);-};diff --git a/frontend/src/metabase/viz-core/shared/components/RowChart/RowChart.tsx b/frontend/src/metabase/viz-core/shared/components/RowChart/RowChart.tsxdeleted file mode 100644index 85251a97e2d..00000000000--- a/frontend/src/metabase/viz-core/shared/components/RowChart/RowChart.tsx+++ /dev/null@@ -1,297 +0,0 @@-import type { NumberValue } from "d3-scale";-import { useMemo } from "react";--import type { TextWidthMeasurer } from "metabase/utils/measure-text";--import type { SeriesInfo } from "../../types/data";-import type { HoveredData } from "../../types/events";-import type { ChartTicksFormatters } from "../../types/format";-import type { ContinuousScaleType, Range } from "../../types/scale";-import type { ChartGoal } from "../../types/settings";-import RowChartView from "../RowChartView/RowChartView";--import type { BarData, RowChartTheme, Series, StackOffset } from "./types";-import { calculateNonStackedBars, calculateStackedBars } from "./utils/data";-import {- getChartMargin,- getMaxYValuesCount,- getRowChartGoal,-} from "./utils/layout";-import { addSideSpacingForTicksAndLabels, getChartScales } from "./utils/scale";-import { getXTicks } from "./utils/ticks";--const MIN_BAR_HEIGHT = 24;--const defaultFormatter = (value: any) => String(value);--export interface RowChartProps<TDatum> {- width?: number | null;- height?: number | null;-- data: TDatum[];- series: Series<TDatum, SeriesInfo>[];- seriesColors: Record<string, string>;-- trimData?: (data: TDatum[], maxLength: number) => TDatum[];-- goal?: ChartGoal | null;- theme: RowChartTheme;- stackOffset: StackOffset;- labelledSeries?: string[] | null;-- xValueRange?: Range;-- yLabel?: string;- xLabel?: string;-- hasXAxis?: boolean;- hasYAxis?: boolean;-- tickFormatters?: ChartTicksFormatters;- labelsFormatter?: (- value: NumberValue,- bar?: BarData<TDatum, SeriesInfo>,- ) => string;- measureTextWidth: TextWidthMeasurer;-- xScaleType?: ContinuousScaleType;-- style?: React.CSSProperties;- isStatic?: boolean;-- hoveredData?: HoveredData | null;- onClick?: (event: React.MouseEvent, bar: BarData<TDatum, SeriesInfo>) => void;- onHover?: (- event: React.MouseEvent,- bar: BarData<TDatum, SeriesInfo> | null,- ) => void;- onGoalHover?: (event: React.MouseEvent, goal: ChartGoal | null) => void;-}--export const RowChart = <TDatum,>({- width,- height,-- data,- trimData,- series: multipleSeries,- seriesColors,-- goal,- theme,- stackOffset,- labelledSeries,-- xLabel,- yLabel,-- hasXAxis = true,- hasYAxis = true,-- xValueRange,-- tickFormatters = {- xTickFormatter: defaultFormatter,- yTickFormatter: defaultFormatter,- },- labelsFormatter = defaultFormatter,-- xScaleType = "linear",-- measureTextWidth,-- style,- isStatic,-- hoveredData,- onClick,- onHover,- onGoalHover,-}: RowChartProps<TDatum>) => {- const isMeasured = typeof width === "number" && typeof height === "number";-- const maxYValues = useMemo(- () =>- isMeasured- ? getMaxYValuesCount(- height,- MIN_BAR_HEIGHT,- stackOffset != null,- multipleSeries.length,- )- : 0,- [height, multipleSeries.length, stackOffset, isMeasured],- );-- const trimmedData = useMemo(- () => trimData?.(data, maxYValues) ?? data,- [data, maxYValues, trimData],- );-- const seriesData = useMemo(- () =>- stackOffset != null- ? calculateStackedBars<TDatum>(- trimmedData,- multipleSeries,- stackOffset,- seriesColors,- xScaleType,- )- : calculateNonStackedBars<TDatum>(- trimmedData,- multipleSeries,- seriesColors,- xScaleType,- ),- [stackOffset, trimmedData, multipleSeries, seriesColors, xScaleType],- );-- const { xTickFormatter, yTickFormatter } = tickFormatters;-- const margin = useMemo(- () =>- getChartMargin(- seriesData,- yTickFormatter,- theme.axis.ticks,- theme.axis.label,- goal != null,- measureTextWidth,- xLabel,- yLabel,- hasXAxis,- hasYAxis,- width,- ),- [- seriesData,- yTickFormatter,- theme.axis.ticks,- theme.axis.label,- goal,- measureTextWidth,- xLabel,- yLabel,- hasXAxis,- hasYAxis,- width,- ],- );-- const innerWidth = isMeasured ? width - margin.left - margin.right : 0;- const innerHeight = isMeasured ? height - margin.top - margin.bottom : 0;-- const additionalXValues = useMemo(- () => (goal != null ? [goal.value ?? 0] : []),- [goal],- );-- const { xScale, yScale } = useMemo(- () =>- getChartScales(- seriesData,- innerHeight,- innerWidth,- additionalXValues,- xScaleType,- stackOffset,- xValueRange,- ),- [- additionalXValues,- innerHeight,- innerWidth,- seriesData,- stackOffset,- xScaleType,- xValueRange,- ],- );-- const paddedXScale = useMemo(- () =>- addSideSpacingForTicksAndLabels(- xScale,- measureTextWidth,- theme.axis.ticks,- xTickFormatter,- theme.dataLabels,- labelsFormatter,- (labelledSeries ?? []).length > 0,- ),- [- labelsFormatter,- measureTextWidth,- labelledSeries,- theme.axis.ticks,- theme.dataLabels,- xScale,- xTickFormatter,- ],- );-- const xTicks = useMemo(- () =>- getXTicks(- theme.axis.ticks,- innerWidth,- paddedXScale,- xTickFormatter,- measureTextWidth,- xScaleType,- ),- [- innerWidth,- measureTextWidth,- theme.axis.ticks,- paddedXScale,- xScaleType,- xTickFormatter,- ],- );-- const rowChartGoal = useMemo(- () =>- getRowChartGoal(- goal,- theme.goal,- measureTextWidth,- paddedXScale,- isStatic,- ),- [goal, measureTextWidth, theme.goal, paddedXScale, isStatic],- );-- return (- <RowChartView- style={style}- isStacked={stackOffset != null}- isStatic={isStatic}- seriesData={seriesData}- innerHeight={innerHeight}- innerWidth={innerWidth}- margin={margin}- theme={theme}- width={width}- height={height}- xScale={paddedXScale}- yScale={yScale}- goal={rowChartGoal}- hoveredData={hoveredData}- yTickFormatter={yTickFormatter}- xTickFormatter={xTickFormatter}- labelsFormatter={labelsFormatter}- xTicks={xTicks}- labelledSeries={labelledSeries}- yLabel={yLabel}- xLabel={xLabel}- hasXAxis={hasXAxis}- hasYAxis={hasYAxis}- measureTextWidth={measureTextWidth}- onClick={onClick}- onHover={onHover}- onGoalHover={onGoalHover}- />- );-};diff --git a/frontend/src/metabase/viz-core/shared/components/RowChart/RowChart.unit.spec.tsx b/frontend/src/metabase/viz-core/shared/components/RowChart/RowChart.unit.spec.tsxdeleted file mode 100644index 191c10984b7..00000000000--- a/frontend/src/metabase/viz-core/shared/components/RowChart/RowChart.unit.spec.tsx+++ /dev/null@@ -1,408 +0,0 @@-import userEvent from "@testing-library/user-event";-import type { NumberValue } from "d3-scale";--import { render, screen } from "__support__/ui";-import { measureTextWidth } from "metabase/utils/measure-text";--import type { ChartFont } from "../../types/style";--import type { RowChartProps } from "./RowChart";-import { RowChart } from "./RowChart";-import type { RowChartTheme } from "./types";--type TestDatum = { y: string; x: number; x1: number };--const testFont: ChartFont = {- size: 10,- family: "Lato",- weight: 400,- color: "grey",-};--const theme: RowChartTheme = {- axis: { color: "gray", ticks: testFont, label: testFont },- dataLabels: testFont,- goal: {- lineStroke: "gray",- lineShadowStroke: "white",- label: testFont,- marker: {- iconColor: "gray",- backgroundColor: "white",- hoverBackgroundColor: "gray",- shadowColor: "gray",- },- },- grid: {- color: "gray",- },-};--const series1 = {- seriesKey: "series 1",- seriesName: "Series 1",- xAccessor: (datum: TestDatum) => datum.x,- yAccessor: (datum: TestDatum) => datum.y,-};-const series2 = {- seriesKey: "series 2",- seriesName: "Series 2",- xAccessor: (datum: TestDatum) => datum.x1,- yAccessor: (datum: TestDatum) => datum.y,-};--const defaultProps = {- width: 1000,- height: 1000,- data: [- { y: "foo", x: 100, x1: 200 },- { y: "bar", x: 200, x1: 400 },- { y: "baz", x: 300, x1: 600 },- ],- series: [series1, series2],- seriesColors: {- "series 1": "red",- "series 2": "green",- },- theme,- stackOffset: null,- measureTextWidth,-};--const setup = (props?: Partial<RowChartProps<TestDatum>>) => {- const { container } = render(<RowChart {...defaultProps} {...props} />);- const bars = screen- .getAllByRole("graphics-symbol")- .filter((el) => el.getAttribute("aria-roledescription") === "bar");- const dataLabels = screen.queryAllByTestId("data-label");- const goalLine = screen- .queryAllByRole("graphics-symbol")- .find((el) => el.getAttribute("aria-roledescription") === "goal line");-- const xTicks = Array.from(- container // eslint-disable-line testing-library/no-container- .getElementsByClassName("visx-axis-bottom")[0] // eslint-disable-line testing-library/no-node-access- ?.getElementsByTagName("tspan") || [], // eslint-disable-line testing-library/no-node-access- ).map((tspan) => tspan.textContent);-- const yTicks = Array.from(- container // eslint-disable-line testing-library/no-container- .getElementsByClassName("visx-axis-left")[0] // eslint-disable-line testing-library/no-node-access- ?.getElementsByTagName("tspan") || [], // eslint-disable-line testing-library/no-node-access- ).map((tspan) => tspan.textContent);-- return {- bars,- dataLabels,- goalLine,- xTicks,- yTicks,- };-};--describe("RowChart", () => {- describe("axes", () => {- it("should render Y-ticks", () => {- const { yTicks } = setup({ series: [series1] });-- expect(yTicks).toStrictEqual(["foo", "bar", "baz"]);- });-- it("should not render Y-ticks when disabled", () => {- const { yTicks } = setup({- series: [series1],- hasYAxis: false,- });-- expect(yTicks).toStrictEqual([]);- });-- it("should render the last tick", () => {- const { xTicks } = setup({ series: [series1], xValueRange: [0, 1] });- expect(xTicks).toStrictEqual([- "0",- "0.1",- "0.2",- "0.3",- "0.4",- "0.5",- "0.6",- "0.7",- "0.8",- "0.9",- "1",- ]);- });-- it("should render nice values for X-ticks", () => {- const { xTicks } = setup({ series: [series1] });-- expect(xTicks).toStrictEqual([- "0",- "50",- "100",- "150",- "200",- "250",- "300",- ]);- });-- it("should not render X-ticks when disabled", () => {- const { xTicks } = setup({- series: [series1],- hasXAxis: false,- });-- expect(xTicks).toStrictEqual([]);- });-- it("should apply formatting", () => {- const { xTicks, yTicks } = setup({- series: [series1],- tickFormatters: {- xTickFormatter: (value: string) => `x_${value}`,- yTickFormatter: (value: string) => `y_${value}`,- },- });-- expect(xTicks).toStrictEqual([- "x_0",- "x_50",- "x_100",- "x_150",- "x_200",- "x_250",- "x_300",- ]);- expect(yTicks).toStrictEqual(["y_foo", "y_bar", "y_baz"]);- });-- it("should render labels when specified", () => {- setup({- series: [series1],- xLabel: "X Label",- yLabel: "Y Label",- });-- expect(screen.getByText("X Label")).toBeInTheDocument();- expect(screen.getByText("Y Label")).toBeInTheDocument();- });- });-- describe("bars", () => {- it("should render chart bars for a single series chart", () => {- const { bars } = setup({ series: [series1] });- expect(bars).toHaveLength(3);- expect(bars[0]).toHaveAttribute("aria-label", "100");- expect(bars[1]).toHaveAttribute("aria-label", "200");- expect(bars[2]).toHaveAttribute("aria-label", "300");- });-- it("should render chart bars for a multi-series chart", () => {- const { bars } = setup();- expect(bars).toHaveLength(6);-- // Series 1- expect(bars[0]).toHaveAttribute("aria-label", "100");- expect(bars[1]).toHaveAttribute("aria-label", "200");- expect(bars[2]).toHaveAttribute("aria-label", "300");-- // Series 2- expect(bars[3]).toHaveAttribute("aria-label", "200");- expect(bars[4]).toHaveAttribute("aria-label", "400");- expect(bars[5]).toHaveAttribute("aria-label", "600");- });- });-- describe("data labels", () => {- it("should not render data labels when not specified", () => {- const { dataLabels } = setup();- expect(dataLabels).toHaveLength(0);- });-- it("should render data labels for specified series", () => {- const { dataLabels } = setup({ labelledSeries: ["series 1"] });- expect(dataLabels.map((el) => el.textContent)).toStrictEqual([- "100",- "200",- "300",- ]);- });-- it("should render formatted data labels when enabled", () => {- const { dataLabels } = setup({- labelledSeries: ["series 1"],- labelsFormatter: (value: NumberValue) => `_${value}_`,- });- expect(dataLabels.map((el) => el.textContent)).toStrictEqual([- "_100_",- "_200_",- "_300_",- ]);- });-- it("should pass the current bar to the data label formatter", () => {- const { dataLabels } = setup({- labelledSeries: ["series 1", "series 2"],- labelsFormatter: (value, bar) => `${bar?.series.seriesKey}_${value}`,- });-- expect(dataLabels.map((el) => el.textContent)).toStrictEqual([- "series 1_100",- "series 1_200",- "series 1_300",- "series 2_200",- "series 2_400",- "series 2_600",- ]);- });- });-- describe("goal line", () => {- it("should not render goal line when not specified", () => {- const { goalLine } = setup();- expect(goalLine).toBeFalsy();- });-- it("should call onGoalHover when hovering the goal marker", async () => {- const goal = { label: "Goal label", value: 100 };- const onGoalHover = jest.fn();- setup({ goal, onGoalHover });-- await userEvent.hover(screen.getByTestId("goal-line-marker"));- expect(onGoalHover).toHaveBeenLastCalledWith(- expect.objectContaining({ target: expect.anything() }),- expect.objectContaining(goal),- );-- await userEvent.unhover(screen.getByTestId("goal-line-marker"));- expect(onGoalHover).toHaveBeenLastCalledWith(- expect.objectContaining({ target: expect.anything() }),- null,- );- });-- it("should show the goal label instead of the marker on static rendering", () => {- const { goalLine } = setup({- goal: { label: "Goal label", value: 100 },- isStatic: true,- });-- expect(goalLine).toHaveTextContent("Goal label");- expect(screen.queryByTestId("goal-line-marker")).not.toBeInTheDocument();- });- });-- describe("events", () => {- it("should call onClick with the clicked datum info", async () => {- const onClick = jest.fn();-- const { bars } = setup({ onClick });- await userEvent.click(bars[0]);-- expect(onClick).toHaveBeenCalledWith(- expect.objectContaining({ target: expect.anything() }),- expect.objectContaining({- datum: expect.objectContaining({ x: 100, x1: 200, y: "foo" }),- series: expect.objectContaining({- seriesKey: "series 1",- seriesName: "Series 1",- }),- datumIndex: 0,- isNegative: false,- }),- );-- onClick.mockClear();-- // the last bar- await userEvent.click(bars[5]);-- expect(onClick).toHaveBeenCalledWith(- expect.objectContaining({ target: expect.anything() }),- expect.objectContaining({- datum: expect.objectContaining({ x: 300, x1: 600, y: "baz" }),- series: expect.objectContaining({- seriesKey: "series 2",- seriesName: "Series 2",- }),- datumIndex: 2,- isNegative: false,- }),- );- });-- it("should call onHover with the clicked datum info", async () => {- const onHover = jest.fn();-- const { bars } = setup({ onHover });- await userEvent.hover(bars[0]);-- expect(onHover).toHaveBeenCalledWith(- expect.objectContaining({ target: expect.anything() }),- expect.objectContaining({- datum: expect.objectContaining({ x: 100, x1: 200, y: "foo" }),- series: expect.objectContaining({- seriesKey: "series 1",- seriesName: "Series 1",- }),- datumIndex: 0,- isNegative: false,- }),- );-- onHover.mockClear();-- // the last bar- await userEvent.click(bars[5]);-- expect(onHover).toHaveBeenCalledWith(- expect.objectContaining({ target: expect.anything() }),- expect.objectContaining({- datum: expect.objectContaining({ x: 300, x1: 600, y: "baz" }),- series: expect.objectContaining({- seriesKey: "series 2",- seriesName: "Series 2",- }),- datumIndex: 2,- isNegative: false,- }),- );- });-- it("should highlight all bars of hovered series when multi-series", () => {- const hoveredData = {- seriesIndex: 1,- datumIndex: 1,- };-- const { bars } = setup({ hoveredData });- const firstSeriesBars = bars.slice(0, 3);- const secondSeriesBars = bars.slice(3);-- firstSeriesBars.forEach((bar) =>- expect(bar).toHaveAttribute("opacity", "0.4"),- );-- secondSeriesBars.forEach((bar) =>- expect(bar).toHaveAttribute("opacity", "1"),- );- });-- it("should highlight only hovered bar when single-series", () => {- const hoveredData = {- seriesIndex: 0,- datumIndex: 1,- };-- const { bars } = setup({ hoveredData, series: [series1] });-- expect(bars.map((bar) => bar.getAttribute("opacity"))).toStrictEqual([- "0.4",- "1",- "0.4",- ]);- });- });-});diff --git a/frontend/src/metabase/viz-core/shared/components/RowChart/constants.ts b/frontend/src/metabase/viz-core/shared/components/RowChart/constants.tsdeleted file mode 100644index b22fb15b2ef..00000000000--- a/frontend/src/metabase/viz-core/shared/components/RowChart/constants.ts+++ /dev/null@@ -1 +0,0 @@-export const LABEL_PADDING = 4;diff --git a/frontend/src/metabase/viz-core/shared/components/RowChart/index.ts b/frontend/src/metabase/viz-core/shared/components/RowChart/index.tsdeleted file mode 100644index df7f33b8d50..00000000000--- a/frontend/src/metabase/viz-core/shared/components/RowChart/index.ts+++ /dev/null@@ -1 +0,0 @@-export * from "./RowChart";diff --git a/frontend/src/metabase/viz-core/shared/components/RowChart/theme.ts b/frontend/src/metabase/viz-core/shared/components/RowChart/theme.tsdeleted file mode 100644index 9502b7f6315..00000000000--- a/frontend/src/metabase/viz-core/shared/components/RowChart/theme.ts+++ /dev/null@@ -1,51 +0,0 @@-import type { ColorGetter } from "metabase/ui/colors/types";--import type { RowChartTheme } from "./types";--export const getStaticChartTheme = (- getColor: ColorGetter,- fontFamily = "Lato",-): RowChartTheme => {- return {- axis: {- color: getColor("border-neutral"),- ticks: {- size: 12,- weight: 700,- color: getColor("text-secondary"),- family: fontFamily,- },- label: {- size: 14,- weight: 700,- color: getColor("text-secondary"),- family: fontFamily,- },- },- goal: {- lineStroke: getColor("icon-primary"),- lineShadowStroke: getColor("background_surface-primary"),- label: {- size: 14,- weight: 700,- color: getColor("text-secondary"),- family: fontFamily,- },- marker: {- iconColor: getColor("icon-primary"),- backgroundColor: getColor("background_surface-primary"),- hoverBackgroundColor: getColor("background_surface-primary-hover"),- shadowColor: getColor("shadow-default"),- },- },- dataLabels: {- weight: 700,- color: getColor("text-primary"),- size: 12,- family: fontFamily,- },- grid: {- color: getColor("border-neutral"),- },- };-};diff --git a/frontend/src/metabase/viz-core/shared/components/RowChart/types.ts b/frontend/src/metabase/viz-core/shared/components/RowChart/types.tsdeleted file mode 100644index d728209bc3b..00000000000--- a/frontend/src/metabase/viz-core/shared/components/RowChart/types.ts+++ /dev/null@@ -1,43 +0,0 @@-import type { StringLike } from "@visx/scale";--import type { AxisStyle, ChartFont, GoalStyle } from "../../types/style";--export type XValue = number | null;-export type YValue = string | number | boolean | null;--export type Series<TDatum, TSeriesInfo = unknown> = {- seriesKey: string;- seriesName: string;- xAccessor: (datum: TDatum) => XValue;- yAccessor: (datum: TDatum) => YValue;- seriesInfo?: TSeriesInfo;-};--export type BarData<TDatum, TSeriesInfo = unknown> = {- xStartValue: number | null;- xEndValue: number | null;- yValue: StringLike;- isNegative: boolean;- isBorderValue?: boolean;- datum: TDatum;- datumIndex: number;- series: Series<TDatum, TSeriesInfo>;- seriesIndex: number;-};--export type SeriesData<TDatum, TSeriesInfo = unknown> = {- key: string;- color: string;- bars: BarData<TDatum, TSeriesInfo>[];-};--export type RowChartTheme = {- axis: AxisStyle;- dataLabels: ChartFont;- goal: GoalStyle;- grid: {- color: string;- };-};--export type StackOffset = "diverging" | "expand" | null;diff --git a/frontend/src/metabase/viz-core/shared/components/RowChart/utils/data.ts b/frontend/src/metabase/viz-core/shared/components/RowChart/utils/data.tsdeleted file mode 100644index b4bfbabfa34..00000000000--- a/frontend/src/metabase/viz-core/shared/components/RowChart/utils/data.ts+++ /dev/null@@ -1,144 +0,0 @@-import type { Series as D3Series } from "d3";-import * as d3 from "d3";-import { stack, stackOffsetDiverging, stackOffsetExpand } from "d3";--import { formatNullable } from "metabase/utils/formatting";-import { memoize } from "metabase/utils/memoize";--import type { SeriesInfo } from "../../../types/data";-import type { ContinuousScaleType } from "../../../types/scale";-import type { BarData, Series, SeriesData, StackOffset } from "../types";--export const StackOffsetFn = {- diverging: stackOffsetDiverging,- expand: stackOffsetExpand,-} as const;--export const calculateNonStackedBars = <TDatum>(- data: TDatum[],- multipleSeries: Series<TDatum, SeriesInfo>[],- seriesColors: Record<string, string>,- xScaleType: ContinuousScaleType,-) => {- const defaultXValue = xScaleType === "log" ? 1 : 0;- return multipleSeries.map((series, seriesIndex) => {- const bars: BarData<TDatum, SeriesInfo>[] = data.map(- (datum, datumIndex) => {- const yValue = formatNullable(series.yAccessor(datum));- const xValue = series.xAccessor(datum);- const isNegative = xValue != null && xValue < 0;-- const xStartValue = isNegative ? xValue : defaultXValue;- const xEndValue = isNegative ? defaultXValue : xValue;-- return {- isNegative,- xStartValue,- xEndValue,- yValue,- datum,- datumIndex,- series,- seriesIndex,- };- },- );-- return {- bars,- color: seriesColors[series.seriesKey],- key: series.seriesKey,- };- });-};--// For log scale starting value for stack is 1-// Stacked log charts does not make much sense but we support them, so I replicate the behavior of line/area/bar charts-const patchD3StackDataForLogScale = <TDatum>(- stackedSeries: D3Series<TDatum, string>[],-) => {- stackedSeries.forEach((series) => {- series.forEach((datum) => {- datum.forEach((value, index) => {- if (value === 0) {- datum[index] = 1;- }- });- });- });-};--export const calculateStackedBars = <TDatum>(- data: TDatum[],- multipleSeries: Series<TDatum, SeriesInfo>[],- stackOffset: StackOffset,- seriesColors: Record<string, string>,- xScaleType: ContinuousScaleType,-) => {- const seriesByKey = multipleSeries.reduce<Record<string, Series<TDatum>>>(- (acc, series) => {- acc[series.seriesKey] = series;- return acc;- },- {},- );-- const d3Stack = stack<TDatum>()- .keys(multipleSeries.map((s) => s.seriesKey))- .value((datum, seriesKey) => seriesByKey[seriesKey].xAccessor(datum) ?? 0)- .offset(StackOffsetFn[stackOffset ?? "diverging"]);-- const stackedSeries = d3Stack(data);-- if (xScaleType === "log") {- patchD3StackDataForLogScale(stackedSeries);- }-- const getDatumExtent = memoize(- (stackedSeries: D3Series<TDatum, string>[], datumIndex: number) => {- return d3.extent(stackedSeries.flatMap((series) => series[datumIndex]));- },- );-- const seriesData: SeriesData<TDatum, SeriesInfo>[] = multipleSeries.map(- (series, seriesIndex) => {- const bars: BarData<TDatum, SeriesInfo>[] = data.map(- (datum, datumIndex) => {- const [datumMin, datumMax] = getDatumExtent(- stackedSeries,- datumIndex,- );- const stackedDatum = stackedSeries[seriesIndex][datumIndex];-- const [xStartValue, xEndValue] = stackedDatum;-- const yValue = formatNullable(series.yAccessor(stackedDatum.data));- const isNegative = xStartValue < 0;- const isBorderValue =- (isNegative && xStartValue === datumMin) ||- (!isNegative && xEndValue === datumMax);-- return {- xStartValue,- xEndValue,- yValue,- isNegative,- isBorderValue,- datum,- datumIndex,- series,- seriesIndex,- };- },- );-- return {- bars,- key: series.seriesKey,- color: seriesColors[series.seriesKey],- };- },- );-- return seriesData;-};diff --git a/frontend/src/metabase/viz-core/shared/components/RowChart/utils/domain.ts b/frontend/src/metabase/viz-core/shared/components/RowChart/utils/domain.tsdeleted file mode 100644index 9f16b7ba1c9..00000000000--- a/frontend/src/metabase/viz-core/shared/components/RowChart/utils/domain.ts+++ /dev/null@@ -1,38 +0,0 @@-import { extent } from "d3";--import { isNotNull } from "metabase/utils/types";--import type {- ContinuousDomain,- ContinuousScaleType,-} from "../../../types/scale";-import type { SeriesData } from "../types";--const getExtent = (values: number[]) => {- const [min, max] = extent(values);- return [min ?? 0, max ?? 0];-};--export const createYDomain = <TDatum>(data: SeriesData<TDatum>[]) => {- // taking first series assuming all series have the same Y-axis values- return data[0]?.bars.map((bar) => bar.yValue) ?? [];-};--export const createXDomain = <TDatum>(- data: SeriesData<TDatum>[],- additionalValues: number[],- xScaleType: ContinuousScaleType,-): ContinuousDomain => {- const allXValues = data.flatMap((series) =>- series.bars- .flatMap((bar) => [bar.xStartValue, bar.xEndValue])- .filter(isNotNull),- );- const [min, max] = getExtent([...allXValues, ...additionalValues]);-- if (xScaleType === "log") {- return [1, Math.max(max, 1)];- }-- return [Math.min(min, 0), Math.max(max, 0)];-};diff --git a/frontend/src/metabase/viz-core/shared/components/RowChart/utils/layout.ts b/frontend/src/metabase/viz-core/shared/components/RowChart/utils/layout.tsdeleted file mode 100644index 7461a48510d..00000000000--- a/frontend/src/metabase/viz-core/shared/components/RowChart/utils/layout.ts+++ /dev/null@@ -1,117 +0,0 @@-import type { ScaleContinuousNumeric } from "d3-scale";--import type { TextWidthMeasurer } from "metabase/utils/measure-text";--import type { Margin } from "../../../types/layout";-import type { ChartGoal } from "../../../types/settings";-import type { ChartFont, GoalStyle } from "../../../types/style";-import { LABEL_PADDING } from "../constants";-import type { SeriesData } from "../types";--const CHART_PADDING = 10;-const TICKS_OFFSET = 10;-const GOAL_LINE_PADDING = 14;--export const getMaxWidth = (- formattedYTicks: string[],- ticksFont: ChartFont,- measureTextWidth: TextWidthMeasurer,-): number => {- return Math.max(- ...formattedYTicks.map((tick) =>- measureTextWidth(tick, {- size: `${ticksFont.size}px`,- family: "Lato",- weight: String(ticksFont.weight ?? 400),- }),- ),- );-};--export const getChartMargin = <TDatum>(- seriesData: SeriesData<TDatum>[],- yTickFormatter: (value: any) => string,- ticksFont: ChartFont,- labelFont: ChartFont,- hasGoalLine: boolean,- measureTextWidth: TextWidthMeasurer,- xLabel?: string | null,- yLabel?: string | null,- hasXAxis?: boolean,- hasYAxis?: boolean,- chartWidth?: number | null,-): Margin => {- const maxYAxisLabelWidth = hasYAxis- ? getMaxWidth(- seriesData.flatMap((seriesData) =>- seriesData.bars.map((bar) => yTickFormatter(bar.yValue)),- ),- ticksFont,- measureTextWidth,- )- : 0;-- // Limit y-axis labels to 50% of chart width to ensure bars remain visible- const maxAllowedYAxisWidth = chartWidth ? chartWidth * 0.5 : Infinity;- const yAxisOffset = hasYAxis- ? Math.min(maxYAxisLabelWidth, maxAllowedYAxisWidth) + TICKS_OFFSET- : 0;-- const xAxisOffset = hasXAxis ? TICKS_OFFSET + ticksFont.size : 0;-- const margin: Margin = {- top: hasGoalLine ? GOAL_LINE_PADDING : CHART_PADDING,- left:- yAxisOffset +- CHART_PADDING +- (yLabel != null ? LABEL_PADDING + labelFont.size : 0),- bottom:- CHART_PADDING +- xAxisOffset +- (xLabel != null ? LABEL_PADDING + labelFont.size : 0),- right: CHART_PADDING,- };-- return margin;-};--export const getMaxYValuesCount = (- viewportHeight: number,- minBarWidth: number,- isStacked: boolean,- seriesCount: number,-) => {- const singleValueHeight = isStacked ? minBarWidth : minBarWidth * seriesCount;-- return Math.max(Math.floor(viewportHeight / singleValueHeight), 1);-};--export const getRowChartGoal = (- goal: ChartGoal | null | undefined,- style: GoalStyle,- measureTextWidth: TextWidthMeasurer,- xScale: ScaleContinuousNumeric<number, number, never>,- isStatic?: boolean,-) => {- if (!goal) {- return null;- }-- if (!isStatic) {- return { ...goal, position: "right" as const };- }-- const labelWidth = measureTextWidth(goal.label, style.label);- const goalX = xScale(goal.value);- const xMax = xScale.range()[1];- const availableRightSideSpace = xMax - goalX;- const position =- labelWidth > availableRightSideSpace- ? ("left" as const)- : ("right" as const);-- return {- ...goal,- position,- };-};diff --git a/frontend/src/metabase/viz-core/shared/components/RowChart/utils/scale.ts b/frontend/src/metabase/viz-core/shared/components/RowChart/utils/scale.tsdeleted file mode 100644index cfb5d00e4f5..00000000000--- a/frontend/src/metabase/viz-core/shared/components/RowChart/utils/scale.ts+++ /dev/null@@ -1,162 +0,0 @@-import type { ContinuousDomain } from "@visx/scale";-import { scaleBand, scaleLinear, scaleLog, scalePower } from "@visx/scale";-import type { ScaleContinuousNumeric } from "d3-scale";--import type { TextWidthMeasurer } from "metabase/utils/measure-text";--import type { ValueFormatter } from "../../../types/format";-import type { ContinuousScaleType, Range } from "../../../types/scale";-import type { ChartFont } from "../../../types/style";-import { DATA_LABEL_OFFSET } from "../../RowChartView";-import type { SeriesData, StackOffset } from "../types";--import { createXDomain, createYDomain } from "./domain";--export const createXScale = (- domain: ContinuousDomain,- range: Range,- type: ContinuousScaleType = "linear",- isExactRange: boolean,-): ScaleContinuousNumeric<number, number, never> => {- switch (type) {- case "pow":- return scalePower({- range,- domain,- exponent: 2,- clamp: isExactRange,- });- case "log":- return scaleLog({- range,- domain,- base: 10,- clamp: isExactRange,- });- default:- return scaleLinear({- range,- domain,- nice: !isExactRange,- clamp: isExactRange,- });- }-};--export const getChartScales = <TDatum>(- seriesData: SeriesData<TDatum>[],- innerHeight: number,- innerWidth: number,- additionalXValues: number[],- xScaleType: ContinuousScaleType,- stackOffset: StackOffset,- rangeOverride?: Range,-) => {- const yDomain = createYDomain(seriesData);- const yScale = scaleBand({- domain: yDomain,- range: [0, innerHeight],- padding: 0.2,- });-- const xDomain =- rangeOverride ?? createXDomain(seriesData, additionalXValues, xScaleType);-- const isExactRange = !!rangeOverride || stackOffset === "expand";- const xScale = createXScale(- xDomain,- [0, innerWidth],- xScaleType,- isExactRange,- );-- return {- yDomain,- xDomain,- yScale,- xScale,- };-};--export const addScalePadding = (- scale: ScaleContinuousNumeric<number, number, never>,- paddingStart: number = 0,- paddingEnd: number = 0,-) => {- const [start, end] = scale.range();-- return scale.copy().range([start + paddingStart, end - paddingEnd]);-};--const getTickInfo = (- tickX: number,- tickFormatter: ValueFormatter,- tickFont: ChartFont,- measureTextWidth: TextWidthMeasurer,- xScale: ScaleContinuousNumeric<number, number, never>,-) => {- const value = xScale.invert(tickX);-- return {- value,- tickX,- formatted: tickFormatter(value),- tickWidth: measureTextWidth(tickFormatter(value), tickFont),- };-};--const Y_AXIS_LEFT_PADDING = 16;--export const addSideSpacingForTicksAndLabels = (- xScale: ScaleContinuousNumeric<number, number, never>,- measureTextWidth: TextWidthMeasurer,- tickFont: ChartFont,- tickFormatter: ValueFormatter,- labelFont: ChartFont,- labelFormatter: ValueFormatter,- shouldShowLabels?: boolean,-) => {- const [rangeMin, rangeMax] = xScale.range();- const [domainMin, domainMax] = xScale.domain();- let [leftPadding, rightPadding] = [0, 0];-- const minTick = getTickInfo(- rangeMin,- tickFormatter,- tickFont,- measureTextWidth,- xScale,- );-- if (minTick.value < 0) {- const minTickOverflow = rangeMin - (minTick.tickX - minTick.tickWidth / 2);- const leftLabelOverflow = shouldShowLabels- ? rangeMin -- (xScale(domainMin) -- measureTextWidth(labelFormatter(domainMin), labelFont) -- DATA_LABEL_OFFSET * 2 -- Y_AXIS_LEFT_PADDING)- : 0;-- leftPadding = Math.max(0, minTickOverflow, leftLabelOverflow);- }-- const maxTick = getTickInfo(- rangeMax,- tickFormatter,- tickFont,- measureTextWidth,- xScale,- );- const maxTickOverflow = maxTick.tickX + maxTick.tickWidth / 2 - rangeMax;- const rightLabelOverflow = shouldShowLabels- ? xScale(domainMax) +- measureTextWidth(labelFormatter(domainMax), labelFont) +- DATA_LABEL_OFFSET -- rangeMax- : 0;-- rightPadding = Math.max(0, maxTickOverflow, rightLabelOverflow);-- return addScalePadding(xScale, leftPadding, rightPadding);-};diff --git a/frontend/src/metabase/viz-core/shared/components/RowChart/utils/scale.unit.spec.ts b/frontend/src/metabase/viz-core/shared/components/RowChart/utils/scale.unit.spec.tsdeleted file mode 100644index b9f88b2d776..00000000000--- a/frontend/src/metabase/viz-core/shared/components/RowChart/utils/scale.unit.spec.ts+++ /dev/null@@ -1,23 +0,0 @@-import { scaleLinear } from "@visx/scale";--import { addScalePadding } from "./scale";--describe("addScalePadding", () => {- it("should not mutate the original scale", () => {- const originalScale = scaleLinear({- domain: [0, 100],- range: [0, 500],- });-- const originalRange = [...originalScale.range()];- const originalDomain = [...originalScale.domain()];-- const paddedScale = addScalePadding(originalScale, 10, 20);-- expect(originalScale.range()).toEqual(originalRange);- expect(originalScale.domain()).toEqual(originalDomain);-- expect(paddedScale.range()).toEqual([10, 480]);- expect(paddedScale).not.toBe(originalScale);- });-});diff --git a/frontend/src/metabase/viz-core/shared/components/RowChart/utils/ticks.ts b/frontend/src/metabase/viz-core/shared/components/RowChart/utils/ticks.tsdeleted file mode 100644index 75e80414e38..00000000000--- a/frontend/src/metabase/viz-core/shared/components/RowChart/utils/ticks.ts+++ /dev/null@@ -1,149 +0,0 @@-import type { ScaleContinuousNumeric } from "d3-scale";-import _ from "underscore";--import type { TextWidthMeasurer } from "metabase/utils/measure-text";--import type { ValueFormatter } from "../../../types/format";-import type { ContinuousScaleType } from "../../../types/scale";-import type { ChartFont } from "../../../types/style";--const TICK_SPACING = 20;--const getWidthBasedTickInterval = (innerWidth: number) => innerWidth / 12;--const omitOverlappingTicks = (- ticks: number[],- tickFont: ChartFont,- xScale: ScaleContinuousNumeric<number, number, never>,- tickFormatter: ValueFormatter,- measureTextWidth: TextWidthMeasurer,-) => {- if (ticks.length <= 1) {- return ticks;- }-- const [_min, max] = xScale.range();-- const nonOverlappingTicks: number[] = [];- let nextAvailableX = Infinity;-- for (let i = ticks.length - 1; i >= 0; i--) {- const currentTick = ticks[i];- const currentTickWidth = measureTextWidth(- tickFormatter(currentTick),- tickFont,- );- const currentTickX = xScale(currentTick);-- const currentTickEnd = currentTickX + currentTickWidth / 2;- const currentTickStart = currentTickX - currentTickWidth / 2;-- if (- currentTickEnd > nextAvailableX ||- currentTickEnd > max + currentTickWidth / 2- ) {- continue;- }-- nonOverlappingTicks.push(currentTick);- nextAvailableX = currentTickStart + TICK_SPACING;- }-- nonOverlappingTicks.sort((a, b) => a - b);- return nonOverlappingTicks;-};--const getMaxTickWidth = (- scale: ScaleContinuousNumeric<number, number, never>,- measureTextWidth: TextWidthMeasurer,- tickFormatter: ValueFormatter,- tickFont: ChartFont,-) => {- // Assume border ticks on a continuous scale are the widest- const borderTicksWidths = scale- .domain()- .map(- (tick) => measureTextWidth(tickFormatter(tick), tickFont) + TICK_SPACING,- );-- return Math.max(...borderTicksWidths);-};--const getMinTicksInterval = (- scale: ScaleContinuousNumeric<number, number, never>,- measureText: TextWidthMeasurer,- tickFormatter: ValueFormatter,- tickFont: ChartFont,- innerWidth: number,-) => {- const maxTickWidth = getMaxTickWidth(- scale,- measureText,- tickFormatter,- tickFont,- );- return Math.max(maxTickWidth, getWidthBasedTickInterval(innerWidth));-};--const getEvenlySpacedTicks = (- scale: ScaleContinuousNumeric<number, number, never>,- ticksInterval: number,- ticksCount: number,-) => {- const [startCoordinate] = scale.range();-- return _.range(ticksCount).map((i) => {- const tickCoordinate = startCoordinate + i * ticksInterval;- return scale.invert(tickCoordinate);- });-};--const getLimitedCountAutoTicks = (- scale: ScaleContinuousNumeric<number, number, never>,- countLimit: number,-) => {- let suggestedCount = countLimit;- while (suggestedCount > 0) {- const ticks = scale.ticks(suggestedCount);-- if (ticks.length <= countLimit) {- return ticks;- }-- suggestedCount--;- }-- return [];-};--export const getXTicks = (- tickFont: ChartFont,- innerWidth: number,- xScale: ScaleContinuousNumeric<number, number, never>,- tickFormatter: ValueFormatter,- measureTextWidth: TextWidthMeasurer,- scaleType: ContinuousScaleType,-) => {- const ticksInterval = getMinTicksInterval(- xScale,- measureTextWidth,- tickFormatter,- tickFont,- innerWidth,- );-- const ticksCount = Math.floor(innerWidth / ticksInterval);-- const ticks =- scaleType !== "linear"- ? getEvenlySpacedTicks(xScale, ticksInterval, ticksCount)- : getLimitedCountAutoTicks(xScale, ticksCount);-- return omitOverlappingTicks(- ticks,- tickFont,- xScale,- tickFormatter,- measureTextWidth,- );-};diff --git a/frontend/src/metabase/viz-core/shared/components/RowChartView/RowChartView.tsx b/frontend/src/metabase/viz-core/shared/components/RowChartView/RowChartView.tsxdeleted file mode 100644index 03d0bfd8eab..00000000000--- a/frontend/src/metabase/viz-core/shared/components/RowChartView/RowChartView.tsx+++ /dev/null@@ -1,303 +0,0 @@-import type { AxisScale } from "@visx/axis";-import { AxisBottom, AxisLeft } from "@visx/axis";-import { GridColumns } from "@visx/grid";-import { Group } from "@visx/group";-import type { NumberLike, StringLike } from "@visx/scale";-import { scaleBand } from "@visx/scale";-import { Bar } from "@visx/shape";-import { Text } from "@visx/text";-import type { ScaleBand, ScaleContinuousNumeric } from "d3-scale";-import * as React from "react";--import type { TextWidthMeasurer } from "metabase/utils/measure-text";--import { truncateText } from "../../../lib/text";-import type { SeriesInfo } from "../../types/data";-import type { HoveredData } from "../../types/events";-import type { Margin } from "../../types/layout";-import type { ChartGoal } from "../../types/settings";-import type { BarData, RowChartTheme, SeriesData } from "../RowChart/types";-import { VerticalGoalLine } from "../VerticalGoalLine/VerticalGoalLine";--import { DATA_LABEL_OFFSET } from "./constants";-import { getDataLabel } from "./utils/data-labels";--export interface RowChartViewProps<TDatum> {- width?: number | null;- height?: number | null;- yScale: ScaleBand<StringLike>;- xScale: ScaleContinuousNumeric<number, number, never>;- seriesData: SeriesData<TDatum, SeriesInfo>[];- labelsFormatter: (- value: NumberLike,- bar?: BarData<TDatum, SeriesInfo>,- ) => string;- yTickFormatter: (value: StringLike) => string;- xTickFormatter: (value: NumberLike) => string;- xTicks: number[];- goal: {- label: string;- value: number;- position: "left" | "right";- } | null;- theme: RowChartTheme;- margin: Margin;- innerWidth: number;- innerHeight: number;- labelledSeries?: string[] | null;- xLabel?: string | null;- yLabel?: string | null;- hasXAxis?: boolean;- hasYAxis?: boolean;- isStacked?: boolean;- isStatic?: boolean;- style?: React.CSSProperties;- hoveredData?: HoveredData | null;- measureTextWidth?: TextWidthMeasurer;- onHover?: (- event: React.MouseEvent<Element>,- bar: BarData<TDatum, SeriesInfo> | null,- ) => void;- onClick?: (- event: React.MouseEvent<Element>,- bar: BarData<TDatum, SeriesInfo>,- ) => void;- onGoalHover?: (- event: React.MouseEvent<Element>,- goal: ChartGoal | null,- ) => void;-}--const RowChartView = <TDatum,>({- width,- height,- innerHeight,- xScale,- yScale,- seriesData,- goal,- theme,- margin,- labelsFormatter,- yTickFormatter,- xTickFormatter,- xTicks,- labelledSeries,- yLabel,- xLabel,- hasXAxis = true,- hasYAxis = true,- isStacked,- isStatic,- style,- hoveredData,- measureTextWidth,- onHover,- onClick,- onGoalHover,-}: RowChartViewProps<TDatum>) => {- const innerBarScale = isStacked- ? null- : scaleBand({- domain: seriesData.map((_, index) => index),- range: [0, yScale.bandwidth()],- });-- const goalLineX = xScale(goal?.value ?? 0);-- const ellipsifiedYTickFormatter = React.useMemo(() => {- if (!measureTextWidth || !width) {- return yTickFormatter;- }-- // Calculate the maximum allowed width for y-axis labels (50% of chart width)- const maxLabelWidth =- margin.left - (yLabel ? theme.axis.label.size * 2 : 0);-- return (value: StringLike) => {- const originalText = yTickFormatter(value);- return truncateText(- originalText,- maxLabelWidth,- measureTextWidth,- theme.axis.ticks,- );- };- }, [- measureTextWidth,- width,- margin.left,- yLabel,- theme.axis.label.size,- theme.axis.ticks,- yTickFormatter,- ]);-- return (- <svg width={width ?? undefined} height={height ?? undefined} style={style}>- <Group top={margin.top} left={margin.left}>- <GridColumns- // Unjustified type cast. FIXME- scale={xScale as AxisScale<number>}- height={innerHeight}- stroke={theme.grid.color}- tickValues={xTicks}- />-- {seriesData.map((series, seriesIndex) => {- return series.bars.map((bar) => {- const { xStartValue, xEndValue, isNegative, yValue, datumIndex } =- bar;- let y = yScale(yValue);-- if (y == null || xStartValue == null || xEndValue == null) {- return null;- }-- y += innerBarScale?.(seriesIndex) ?? 0;-- const x = xScale(xStartValue);- const width = Math.abs(xScale(xEndValue) - x);-- const hasSeriesHover = hoveredData != null;- const isSeriesHovered = hoveredData?.seriesIndex === seriesIndex;- const isDatumHovered = hoveredData?.datumIndex === datumIndex;-- const shouldHighlightBar =- seriesData.length === 1 && isDatumHovered;- const shouldHighlightSeries =- seriesData.length > 1 && isSeriesHovered;-- const opacity =- !hasSeriesHover || shouldHighlightSeries || shouldHighlightBar- ? 1- : 0.4;-- const label = getDataLabel(- bar,- xScale,- series.key,- isStacked,- labelledSeries,- );-- const height = innerBarScale?.bandwidth() ?? yScale.bandwidth();- const value = isNegative ? xStartValue : xEndValue;- const barKey = `${seriesIndex}:${datumIndex}`;- const ariaLabelledBy = `bar-${barKey}-value`;-- return (- <React.Fragment key={barKey}>- <Bar- aria-label={String(value)}- role="graphics-symbol"- aria-roledescription="bar"- aria-labelledby={label != null ? ariaLabelledBy : undefined}- style={{ transition: "opacity 300ms", cursor: "pointer" }}- key={barKey}- x={x}- y={y}- width={width}- height={height}- fill={series.color}- opacity={opacity}- onClick={(event) => onClick?.(event, bar)}- onMouseEnter={(event) => onHover?.(event, bar)}- onMouseLeave={(event) => onHover?.(event, null)}- />- {label != null && (- <Text- data-testid="data-label"- id={ariaLabelledBy}- textAnchor={isNegative ? "end" : "start"}- fontSize={theme.dataLabels.size}- fill={theme.dataLabels.color}- fontWeight={theme.dataLabels.weight}- dx={(isNegative ? "-" : "") + DATA_LABEL_OFFSET}- x={xScale(value)}- y={y + height / 2}- verticalAnchor="middle"- >- {labelsFormatter(label, bar)}- </Text>- )}- </React.Fragment>- );- });- })}-- <AxisLeft- label={yLabel ?? ""}- labelProps={{- fill: theme.axis.label.color,- fontFamily: theme.dataLabels.family,- fontSize: theme.axis.label.size,- fontWeight: theme.axis.label.weight,- textAnchor: "middle",- verticalAnchor: "start",- }}- labelOffset={margin.left - theme.axis.label.size}- tickFormat={ellipsifiedYTickFormatter}- hideAxisLine={!hasYAxis}- hideTicks- tickValues={hasYAxis ? undefined : []}- numTicks={Infinity}- scale={yScale}- stroke={theme.axis.color}- tickStroke={theme.axis.color}- tickLabelProps={() => ({- fill: theme.axis.ticks.color,- fontFamily: theme.dataLabels.family,- fontSize: theme.axis.ticks.size,- fontWeight: theme.axis.ticks.weight,- textAnchor: "end",- dy: "0.33em",- })}- />- <AxisBottom- label={xLabel ?? ""}- labelProps={{- fill: theme.axis.label.color,- fontFamily: theme.dataLabels.family,- fontSize: theme.axis.label.size,- fontWeight: theme.axis.label.weight,- textAnchor: "middle",- dy: hasXAxis ? undefined : "-1em",- }}- hideAxisLine={!hasXAxis}- hideTicks- tickValues={hasXAxis ? xTicks : []}- tickFormat={xTickFormatter}- top={innerHeight}- // Unjustified type cast. FIXME- scale={xScale as AxisScale<number>}- stroke={theme.axis.color}- tickStroke={theme.axis.color}- tickLabelProps={() => ({- fill: theme.axis.ticks.color,- fontFamily: theme.dataLabels.family,- fontSize: theme.axis.ticks.size,- fontWeight: theme.axis.ticks.weight,- textAnchor: "middle",- })}- />-- {goal && (- <VerticalGoalLine- x={goalLineX}- height={innerHeight}- label={goal.label}- style={theme.goal}- position={goal.position}- isStatic={isStatic}- onMarkerMouseEnter={(event) => onGoalHover?.(event, goal)}- onMarkerMouseLeave={(event) => onGoalHover?.(event, null)}- />- )}- </Group>- </svg>- );-};--// eslint-disable-next-line import/no-default-export -- deprecated usage-export default RowChartView;diff --git a/frontend/src/metabase/viz-core/shared/components/RowChartView/constants.ts b/frontend/src/metabase/viz-core/shared/components/RowChartView/constants.tsdeleted file mode 100644index 3969dddae8e..00000000000--- a/frontend/src/metabase/viz-core/shared/components/RowChartView/constants.ts+++ /dev/null@@ -1 +0,0 @@-export const DATA_LABEL_OFFSET = 4;diff --git a/frontend/src/metabase/viz-core/shared/components/RowChartView/index.ts b/frontend/src/metabase/viz-core/shared/components/RowChartView/index.tsdeleted file mode 100644index 434a032d4d3..00000000000--- a/frontend/src/metabase/viz-core/shared/components/RowChartView/index.ts+++ /dev/null@@ -1,2 +0,0 @@-export * from "./RowChartView";-export * from "./constants";diff --git a/frontend/src/metabase/viz-core/shared/components/RowChartView/utils/data-labels.ts b/frontend/src/metabase/viz-core/shared/components/RowChartView/utils/data-labels.tsdeleted file mode 100644index 3966c80ef46..00000000000--- a/frontend/src/metabase/viz-core/shared/components/RowChartView/utils/data-labels.ts+++ /dev/null@@ -1,30 +0,0 @@-import type { ScaleContinuousNumeric } from "d3-scale";--import type { BarData } from "../../RowChart/types";--export const getDataLabel = <TDatum>(- bar: BarData<TDatum>,- xScale: ScaleContinuousNumeric<number, number, never>,- seriesKey: string,- isStacked?: boolean,- labelledSeries?: string[] | null,-) => {- const { xStartValue, xEndValue, isNegative } = bar;- const value = isNegative ? xStartValue : xEndValue;-- if (value == null) {- return null;- }-- const [xDomainStart, xDomainEnd] = xScale.domain();- const isOutOfDomain = value < xDomainStart || value > xDomainEnd;-- if (isOutOfDomain) {- return null;- }-- const isLabelVisible =- labelledSeries?.includes(seriesKey) && (!isStacked || bar.isBorderValue);-- return isLabelVisible ? value : null;-};diff --git a/frontend/src/metabase/viz-core/shared/components/RowChartView/utils/data-labels.unit.spec.ts b/frontend/src/metabase/viz-core/shared/components/RowChartView/utils/data-labels.unit.spec.tsdeleted file mode 100644index 4ef9c5719a6..00000000000--- a/frontend/src/metabase/viz-core/shared/components/RowChartView/utils/data-labels.unit.spec.ts+++ /dev/null@@ -1,98 +0,0 @@-import { scaleLinear } from "d3-scale";--import type { BarData } from "../../RowChart/types";--import { getDataLabel } from "./data-labels";--describe("getDataLabel", () => {- const mockXScale = scaleLinear().domain([0, 100]).range([0, 500]);- const seriesKey = "test-series";-- const createBarData = <T>(overrides: Partial<BarData<T>> = {}): BarData<T> =>- // Unjustified type cast. FIXME- ({- xStartValue: 10,- xEndValue: 50,- isNegative: false,- isBorderValue: false,- ...overrides,- }) as any;-- it("returns null when value is null", () => {- const bar = createBarData({ xEndValue: null });- const result = getDataLabel(bar, mockXScale, seriesKey);- expect(result).toBeNull();- });-- it("returns null when value is out of domain (below)", () => {- const bar = createBarData({ xEndValue: -10 });- const result = getDataLabel(bar, mockXScale, seriesKey);- expect(result).toBeNull();- });-- it("returns null when value is out of domain (above)", () => {- const bar = createBarData({ xEndValue: 150 });- const result = getDataLabel(bar, mockXScale, seriesKey);- expect(result).toBeNull();- });-- it("returns null when series is not in labelledSeries", () => {- const bar = createBarData();- const result = getDataLabel(bar, mockXScale, seriesKey, false, [- "other-series",- ]);- expect(result).toBeNull();- });-- it("returns null when labelledSeries is null", () => {- const bar = createBarData();- const result = getDataLabel(bar, mockXScale, seriesKey, false, null);- expect(result).toBeNull();- });-- it("returns value for positive bar when conditions are met", () => {- const bar = createBarData({ xEndValue: 75 });- const result = getDataLabel(bar, mockXScale, seriesKey, false, [seriesKey]);- expect(result).toBe(75);- });-- it("returns xStartValue for negative bar", () => {- const bar = createBarData({- xStartValue: 25,- xEndValue: 75,- isNegative: true,- });- const result = getDataLabel(bar, mockXScale, seriesKey, false, [seriesKey]);- expect(result).toBe(25);- });-- it("returns null for stacked bar that is not border value", () => {- const bar = createBarData({ isBorderValue: false });- const result = getDataLabel(bar, mockXScale, seriesKey, true, [seriesKey]);- expect(result).toBeNull();- });-- it("returns value for stacked bar that is border value", () => {- const bar = createBarData({- xEndValue: 60,- isBorderValue: true,- });- const result = getDataLabel(bar, mockXScale, seriesKey, true, [seriesKey]);- expect(result).toBe(60);- });-- it("returns value for non-stacked bar regardless of border value", () => {- const bar = createBarData({- xEndValue: 40,- isBorderValue: false,- });- const result = getDataLabel(bar, mockXScale, seriesKey, false, [seriesKey]);- expect(result).toBe(40);- });-- it("handles edge case where value equals domain boundary (metabase#59507)", () => {- const bar = createBarData({ xEndValue: 100 }); // equals domain end- const result = getDataLabel(bar, mockXScale, seriesKey, false, [seriesKey]);- expect(result).toBe(100);- });-});diff --git a/frontend/src/metabase/viz-core/shared/components/VerticalGoalLine/GoalLineMarker.tsx b/frontend/src/metabase/viz-core/shared/components/VerticalGoalLine/GoalLineMarker.tsxdeleted file mode 100644index 3a078595995..00000000000--- a/frontend/src/metabase/viz-core/shared/components/VerticalGoalLine/GoalLineMarker.tsx+++ /dev/null@@ -1,70 +0,0 @@-import { useState } from "react";--import { CHART_STYLE } from "../../../echarts/cartesian/constants/style";-import type { GoalMarkerStyle } from "../../types/style";--interface GoalLineMarkerProps {- x: number;- y: number;- style: GoalMarkerStyle;- onMouseEnter?: (event: React.MouseEvent) => void;- onMouseLeave?: (event: React.MouseEvent) => void;-}--export const GoalLineMarker = ({- x,- y,- style,- onMouseEnter,- onMouseLeave,-}: GoalLineMarkerProps) => {- const [isHovered, setIsHovered] = useState(false);- const {- outerRingRadius,- innerRingRadius,- ringWidth,- backgroundRadius,- shadowSpread,- hitAreaRadius,- } = CHART_STYLE.goalLine.marker;-- const handleMouseEnter = (event: React.MouseEvent) => {- setIsHovered(true);- onMouseEnter?.(event);- };-- const handleMouseLeave = (event: React.MouseEvent) => {- setIsHovered(false);- onMouseLeave?.(event);- };-- return (- <g- data-testid="goal-line-marker"- transform={`translate(${x}, ${y})`}- onMouseEnter={handleMouseEnter}- onMouseLeave={handleMouseLeave}- >- <g pointerEvents="none">- <circle r={backgroundRadius + shadowSpread} fill={style.shadowColor} />- <circle r={backgroundRadius} fill={style.backgroundColor} />- {isHovered && (- <circle r={backgroundRadius} fill={style.hoverBackgroundColor} />- )}- <circle- r={outerRingRadius}- fill="none"- stroke={style.iconColor}- strokeWidth={ringWidth}- />- <circle- r={innerRingRadius}- fill="none"- stroke={style.iconColor}- strokeWidth={ringWidth}- />- </g>- <circle r={hitAreaRadius} fill={style.iconColor} opacity={0} />- </g>- );-};diff --git a/frontend/src/metabase/viz-core/shared/components/VerticalGoalLine/VerticalGoalLine.tsx b/frontend/src/metabase/viz-core/shared/components/VerticalGoalLine/VerticalGoalLine.tsxdeleted file mode 100644index 7d1e3b88ac5..00000000000--- a/frontend/src/metabase/viz-core/shared/components/VerticalGoalLine/VerticalGoalLine.tsx+++ /dev/null@@ -1,87 +0,0 @@-import { Line } from "@visx/shape";-import { Text } from "@visx/text";--import {- GOAL_LINE_DASH,- GOAL_LINE_WIDTH,-} from "../../../echarts/cartesian/option/goal-line";-import type { GoalStyle } from "../../types/style";--import { GoalLineMarker } from "./GoalLineMarker";--interface VerticalGoalLineProps {- x: number;- height: number;- label: string;- position: "left" | "right";- style: GoalStyle;- isStatic?: boolean;- onMarkerMouseEnter?: (event: React.MouseEvent) => void;- onMarkerMouseLeave?: (event: React.MouseEvent) => void;-}--export const VerticalGoalLine = ({- x,- height,- label,- style,- position = "right",- isStatic,- onMarkerMouseEnter,- onMarkerMouseLeave,-}: VerticalGoalLineProps) => {- const textAnchor = position === "right" ? "start" : "end";-- return (- <g role="graphics-symbol" aria-roledescription="goal line">- <GoalLineStroke- x={x + GOAL_LINE_WIDTH}- height={height}- stroke={style.lineShadowStroke}- />- <GoalLineStroke x={x} height={height} stroke={style.lineStroke} />- {isStatic ? (- <Text- y={0}- textAnchor={textAnchor}- verticalAnchor="end"- dy="-0.2em"- x={x}- fill={style.label.color}- fontSize={style.label.size}- fontWeight={style.label.weight}- >- {label}- </Text>- ) : (- <GoalLineMarker- x={x}- y={0}- style={style.marker}- onMouseEnter={onMarkerMouseEnter}- onMouseLeave={onMarkerMouseLeave}- />- )}- </g>- );-};--interface GoalLineStrokeProps {- x: number;- height: number;- stroke: string;-}--const GoalLineStroke = ({ x, height, stroke }: GoalLineStrokeProps) => (- <Line- x1={x}- x2={x}- y1={0}- y2={height}- stroke={stroke}- strokeWidth={GOAL_LINE_WIDTH}- strokeDasharray={GOAL_LINE_DASH.join(",")}- shapeRendering="crispEdges"- pointerEvents="none"- />-);diff --git a/frontend/src/metabase/viz-core/shared/settings/series.ts b/frontend/src/metabase/viz-core/shared/settings/series.tsindex 386e85daccb..65ebd08267b 100644--- a/frontend/src/metabase/viz-core/shared/settings/series.ts+++ b/frontend/src/metabase/viz-core/shared/settings/series.ts@@ -64,6 +64,11 @@ export const getSeriesDefaultDisplay = (cardDisplay: string, index: number) => {return index === 0 ? "line" : "bar";}+ // Row charts are rotated bars; "row" matches no series builder.+ if (cardDisplay === "row") {+ return "bar";+ }+return cardDisplay;};diff --git a/frontend/src/metabase/viz-core/shared/types/data.ts b/frontend/src/metabase/viz-core/shared/types/data.tsdeleted file mode 100644index f4ca6bcc9f5..00000000000--- a/frontend/src/metabase/viz-core/shared/types/data.ts+++ /dev/null@@ -1,27 +0,0 @@-import type { DatasetColumn, RowValue, RowValues } from "metabase-types/api";--export type SeriesInfo = {- metricColumn: DatasetColumn;- dimensionColumn: DatasetColumn;- breakoutValue?: RowValue;-};--export type MetricValue = number | null;-export type MetricName = string;-export type BreakoutName = string;-export type MetricDatum = { [key: MetricName]: MetricValue };--export type GroupedDatum = {- dimensionValue: RowValue;- metrics: MetricDatum;- isClickable?: boolean;- breakout?: {- [key: BreakoutName]: {- metrics: MetricDatum;- rawRows: RowValues[];- };- };- rawRows: RowValues[];-};--export type GroupedDataset = GroupedDatum[];diff --git a/frontend/src/metabase/viz-core/shared/types/events.ts b/frontend/src/metabase/viz-core/shared/types/events.tsdeleted file mode 100644index e8386b3baad..00000000000--- a/frontend/src/metabase/viz-core/shared/types/events.ts+++ /dev/null@@ -1,4 +0,0 @@-export type HoveredData = {- seriesIndex: number;- datumIndex?: number;-};diff --git a/frontend/src/metabase/viz-core/shared/types/format.ts b/frontend/src/metabase/viz-core/shared/types/format.tsdeleted file mode 100644index 98ffca57319..00000000000--- a/frontend/src/metabase/viz-core/shared/types/format.ts+++ /dev/null@@ -1,10 +0,0 @@-import type { DatasetColumn } from "metabase-types/api";--export type ValueFormatter = (value: any) => string;--export type ColumnFormatter = (value: any, column: DatasetColumn) => string;--export type ChartTicksFormatters = {- xTickFormatter: ValueFormatter;- yTickFormatter: ValueFormatter;-};diff --git a/frontend/src/metabase/viz-core/shared/types/layout.ts b/frontend/src/metabase/viz-core/shared/types/layout.tsdeleted file mode 100644index b501e5aaae8..00000000000--- a/frontend/src/metabase/viz-core/shared/types/layout.ts+++ /dev/null@@ -1,6 +0,0 @@-export type Margin = {- top: number;- bottom: number;- right: number;- left: number;-};diff --git a/frontend/src/metabase/viz-core/shared/types/scale.ts b/frontend/src/metabase/viz-core/shared/types/scale.tsdeleted file mode 100644index 3081ccf894a..00000000000--- a/frontend/src/metabase/viz-core/shared/types/scale.ts+++ /dev/null@@ -1,3 +0,0 @@-export type ContinuousScaleType = "linear" | "pow" | "log";-export type ContinuousDomain = [number, number];-export type Range = [number, number];diff --git a/frontend/src/metabase/viz-core/shared/types/settings.ts b/frontend/src/metabase/viz-core/shared/types/settings.tsdeleted file mode 100644index 5ebbf4a4ef0..00000000000--- a/frontend/src/metabase/viz-core/shared/types/settings.ts+++ /dev/null@@ -1,4 +0,0 @@-export type ChartGoal = {- label: string;- value: number;-};diff --git a/frontend/src/metabase/viz-core/shared/types/style.ts b/frontend/src/metabase/viz-core/shared/types/style.tsdeleted file mode 100644index ae055d32b1c..00000000000--- a/frontend/src/metabase/viz-core/shared/types/style.ts+++ /dev/null@@ -1,26 +0,0 @@-export type ChartFont = {- size: number;- family: string;- weight: number;- color: string;-};--export type GoalMarkerStyle = {- iconColor: string;- backgroundColor: string;- hoverBackgroundColor: string;- shadowColor: string;-};--export type GoalStyle = {- lineStroke: string;- lineShadowStroke: string;- label: ChartFont;- marker: GoalMarkerStyle;-};--export type AxisStyle = {- color: string;- ticks: ChartFont;- label: ChartFont;-};diff --git a/frontend/src/metabase/viz-core/shared/utils/colors.ts b/frontend/src/metabase/viz-core/shared/utils/colors.tsdeleted file mode 100644index c0625a8fd3e..00000000000--- a/frontend/src/metabase/viz-core/shared/utils/colors.ts+++ /dev/null@@ -1,32 +0,0 @@-import { getColorsForValues } from "metabase/ui/colors/charts";-import type { VisualizationSettings } from "metabase-types/api";--import { getChartColor } from "../../lib/color-name";-import type { Series } from "../components/RowChart/types";--export const getSeriesColors = <TDatum, TSeriesInfo>(- settings: VisualizationSettings,- series: Series<TDatum, TSeriesInfo>[],-): Record<string, string> => {- const settingsColorMapping = Object.entries(- settings.series_settings ?? {},- ).reduce(- (mapping, [seriesName, seriesSettings]) => {- if (typeof seriesSettings?.color === "string") {- mapping[seriesName] = getChartColor(- seriesSettings.color,- seriesSettings.color_name,- );- }-- return mapping;- },- // Unjustified type cast. FIXME- {} as Record<string, string>,- );-- return getColorsForValues(- series.map((series) => series.seriesKey),- settingsColorMapping,- );-};diff --git a/frontend/src/metabase/viz-core/shared/utils/colors.unit.spec.ts b/frontend/src/metabase/viz-core/shared/utils/colors.unit.spec.tsdeleted file mode 100644index dd1a8c25cdd..00000000000--- a/frontend/src/metabase/viz-core/shared/utils/colors.unit.spec.ts+++ /dev/null@@ -1,169 +0,0 @@-import { color } from "metabase/ui/colors";-import { getColorsForValues } from "metabase/ui/colors/charts";-import type { VisualizationSettings } from "metabase-types/api";--import { getSeriesColors } from "./colors";--jest.mock("metabase/ui/colors/charts");--// Unjustified type cast. FIXME-const mockGetColorsForValues = getColorsForValues as jest.MockedFunction<- typeof getColorsForValues->;--describe("getSeriesColors", () => {- beforeEach(() => {- jest.clearAllMocks();- mockGetColorsForValues.mockReturnValue({- "Series 1": "#509EE3",- "Series 2": "#88BF4D",- });- });-- it("should handle undefined series_settings entries (metabase#66490)", () => {- const settings: Partial<VisualizationSettings> = {- series_settings: {- "Series 1": undefined,- "Series 2": { color: "#FF0000" },- },- };-- const series = [- {- seriesKey: "Series 1",- seriesName: "Series 1",- xAccessor: (d: any) => d.x,- yAccessor: (d: any) => d.y,- },- {- seriesKey: "Series 2",- seriesName: "Series 2",- xAccessor: (d: any) => d.x,- yAccessor: (d: any) => d.y,- },- ];-- const result = getSeriesColors(settings, series);-- // Verify getColorsForValues was called with correct parameters- expect(mockGetColorsForValues).toHaveBeenCalledWith(- ["Series 1", "Series 2"],- {- "Series 2": "#FF0000",- },- );-- expect(result).toEqual({- "Series 1": "#509EE3",- "Series 2": "#88BF4D",- });- });-- it("should filter out undefined values from settings color mapping", () => {- const settings = {- series_settings: {- "Series 1": undefined,- "Series 2": undefined,- "Series 3": { color: undefined },- },- };-- const series = [- {- seriesKey: "Series 1",- seriesName: "Series 1",- xAccessor: (d: any) => d.x,- yAccessor: (d: any) => d.y,- },- {- seriesKey: "Series 2",- seriesName: "Series 2",- xAccessor: (d: any) => d.x,- yAccessor: (d: any) => d.y,- },- {- seriesKey: "Series 3",- seriesName: "Series 3",- xAccessor: (d: any) => d.x,- yAccessor: (d: any) => d.y,- },- ];-- getSeriesColors(settings, series);-- // When all series_settings are undefined or have undefined colors,- // the mapping should be empty- expect(mockGetColorsForValues).toHaveBeenCalledWith(- ["Series 1", "Series 2", "Series 3"],- {},- );- });-- it("should work with valid series_settings", () => {- const settings = {- series_settings: {- "Series 1": { color: "#FF0000" },- "Series 2": { color: "#00FF00" },- },- };-- const series = [- {- seriesKey: "Series 1",- seriesName: "Series 1",- xAccessor: (d: any) => d.x,- yAccessor: (d: any) => d.y,- },- {- seriesKey: "Series 2",- seriesName: "Series 2",- xAccessor: (d: any) => d.x,- yAccessor: (d: any) => d.y,- },- ];-- getSeriesColors(settings, series);-- expect(mockGetColorsForValues).toHaveBeenCalledWith(- ["Series 1", "Series 2"],- {- "Series 1": "#FF0000",- "Series 2": "#00FF00",- },- );- });-- it("should use the palette color a series records over its stored color", () => {- const settings = {- series_settings: {- "Series 1": { color: "#FF0000", color_name: "accent3" },- "Series 2": { color: "#00FF00" },- },- };-- const series = [- {- seriesKey: "Series 1",- seriesName: "Series 1",- xAccessor: (d: any) => d.x,- yAccessor: (d: any) => d.y,- },- {- seriesKey: "Series 2",- seriesName: "Series 2",- xAccessor: (d: any) => d.x,- yAccessor: (d: any) => d.y,- },- ];-- getSeriesColors(settings, series);-- expect(mockGetColorsForValues).toHaveBeenCalledWith(- ["Series 1", "Series 2"],- {- "Series 1": color("accent3"),- "Series 2": "#00FF00",- },- );- });-});diff --git a/frontend/src/metabase/viz-core/shared/utils/data.ts b/frontend/src/metabase/viz-core/shared/utils/data.tsindex 6cc5ac0e5cd..a8b0207bba3 100644--- a/frontend/src/metabase/viz-core/shared/utils/data.ts+++ b/frontend/src/metabase/viz-core/shared/utils/data.ts@@ -1,174 +1,31 @@-import { t } from "ttag";--import { formatNullable } from "metabase/utils/formatting";import {+ type DatasetColumn,type DatasetData,type RowValue,- type SeriesOrderSetting,getRowsForStableKeys,} from "metabase-types/api";-import { getColumnScaling } from "../../echarts/cartesian/model/util";-import { sumMetric } from "../../lib/dataset";import type {CartesianChartColumns,ColumnDescriptor,} from "../../lib/graph/columns";-import type {- ComputedVisualizationSettings,- RemappingHydratedDatasetColumn,-} from "../../types";-import type { Series } from "../components/RowChart/types";-import type {- GroupedDataset,- GroupedDatum,- MetricDatum,- MetricValue,- SeriesInfo,-} from "../types/data";-import type { ColumnFormatter } from "../types/format";+import type { ComputedVisualizationSettings } from "../../types";-import { getChartMetrics } from "./series";--const getMetricValue = (+export type ColumnFormatter = (value: RowValue,- metric: RemappingHydratedDatasetColumn,- settings: ComputedVisualizationSettings,-): MetricValue => {- const scale = getColumnScaling(metric, settings);-- if (typeof value === "number") {- return scale * value;- }-- return null;-};--const sumMetrics = (left: MetricDatum, right: MetricDatum): MetricDatum => {- const keys = new Set([...Object.keys(left), ...Object.keys(right)]);- return Array.from(keys).reduce<MetricDatum>((datum, metricKey) => {- datum[metricKey] = sumMetric(left[metricKey], right[metricKey]);- return datum;- }, {});-};--export const getGroupedDataset = (- data: Pick<DatasetData, "rows" | "untranslatedRows">,- chartColumns: CartesianChartColumns,- settings: ComputedVisualizationSettings,- columnFormatter: ColumnFormatter,-): GroupedDataset => {- const { dimension } = chartColumns;-- const groupedData = new Map<RowValue, GroupedDatum>();- const rowsForBreakoutKeys = getRowsForStableKeys(data);-- data.rows.forEach((row, rowIndex) => {- const dimensionValue = row[dimension.index];-- const datum = groupedData.get(dimensionValue) ?? {- dimensionValue,- metrics: {},- isClickable: true,- rawRows: [],- };-- const rowMetrics = getChartMetrics(chartColumns).reduce<MetricDatum>(- (datum, metric) => {- datum[metric.column.name] = getMetricValue(- row[metric.index],- metric.column,- settings,- );- return datum;- },- {},- );-- datum.metrics = sumMetrics(rowMetrics, datum.metrics);-- if ("breakout" in chartColumns) {- const breakoutName = columnFormatter(- rowsForBreakoutKeys[rowIndex][chartColumns.breakout.index],- chartColumns.breakout.column,- );+ column: DatasetColumn,+) => string;- const breakoutRawRows = datum.breakout?.[breakoutName]?.rawRows ?? [];- breakoutRawRows.push(row);-- const breakoutMetrics = sumMetrics(- rowMetrics,- datum.breakout?.[breakoutName]?.metrics ?? {},- );-- datum.breakout = {- ...datum.breakout,- [breakoutName]: {- metrics: breakoutMetrics,- rawRows: breakoutRawRows,- },- };- }-- datum.rawRows.push(row);-- groupedData.set(dimensionValue, datum);- });-- return Array.from(groupedData.values());+export type SeriesInfo = {+ metricColumn: DatasetColumn;+ dimensionColumn: DatasetColumn;+ breakoutValue?: RowValue;};-export const trimData = (- dataset: GroupedDataset,- valuesCountLimit: number,-): GroupedDataset => {- if (dataset.length <= valuesCountLimit) {- return dataset;- }-- const groupStartingFromIndex = valuesCountLimit - 1;- const result = dataset.slice();- const dataToGroup = result.splice(groupStartingFromIndex);-- const groupedDatumDimensionValue =- dataToGroup.length === dataset.length- ? t`All values (${dataToGroup.length})`- : t`Other (${dataToGroup.length})`;-- const groupedValuesDatum = dataToGroup.reduce(- (groupedValue, currentValue) => {- groupedValue.metrics = sumMetrics(- groupedValue.metrics,- currentValue.metrics,- );-- Object.keys(currentValue.breakout ?? {}).map((breakoutName) => {- groupedValue.breakout ??= {};- groupedValue.breakout[breakoutName] = {- metrics: sumMetrics(- groupedValue.breakout[breakoutName]?.metrics ?? {},- currentValue.breakout?.[breakoutName].metrics ?? {},- ),- rawRows: [- ...(groupedValue.breakout[breakoutName]?.rawRows ?? []),- ...(currentValue.breakout?.[breakoutName].rawRows ?? []),- ],- };- });-- groupedValue.rawRows.push(...currentValue.rawRows);-- return groupedValue;- },- {- dimensionValue: groupedDatumDimensionValue,- metrics: {},- isClickable: false,- rawRows: [],- },- );-- return [...result, groupedValuesDatum];+type SeriesDefinition = {+ seriesKey: string;+ seriesName: string;+ seriesInfo: SeriesInfo;};const getBreakoutDistinctValues = (@@ -203,21 +60,13 @@ const getBreakoutSeries = (metric: ColumnDescriptor,dimension: ColumnDescriptor,settings: ComputedVisualizationSettings,-): Series<GroupedDatum, SeriesInfo>[] => {+): SeriesDefinition[] => {return Array.from(breakoutValues.entries()).map(([breakoutKey, displayValue]) => {const customName = settings?.series_settings?.[breakoutKey]?.title;return {seriesKey: breakoutKey,seriesName: customName ?? displayValue,- yAccessor: (datum: GroupedDatum) =>- formatNullable(- typeof datum.dimensionValue === "object"- ? JSON.stringify(datum.dimensionValue)- : datum.dimensionValue,- ),- xAccessor: (datum: GroupedDatum) =>- datum.breakout?.[breakoutKey]?.metrics[metric.column.name] ?? null,seriesInfo: {metricColumn: metric.column,dimensionColumn: dimension.column,@@ -232,7 +81,7 @@ const getMultipleMetricSeries = (dimension: ColumnDescriptor,metrics: ColumnDescriptor[],settings: ComputedVisualizationSettings,-): Series<GroupedDatum, SeriesInfo>[] => {+): SeriesDefinition[] => {return metrics.map((metric) => {const seriesKey = metric.column.name;const customName = settings?.series_settings?.[seriesKey]?.title;@@ -240,12 +89,6 @@ const getMultipleMetricSeries = (return {seriesKey,seriesName: customName ?? defaultName,- yAccessor: (datum: GroupedDatum) =>- datum.dimensionValue !== null &&- typeof datum.dimensionValue === "object"- ? JSON.stringify(datum.dimensionValue)- : datum.dimensionValue,- xAccessor: (datum: GroupedDatum) => datum.metrics[metric.column.name],seriesInfo: {dimensionColumn: dimension.column,metricColumn: metric.column,@@ -259,7 +102,7 @@ export const getSeries = (chartColumns: CartesianChartColumns,columnFormatter: ColumnFormatter,settings: ComputedVisualizationSettings,-): Series<GroupedDatum, SeriesInfo>[] => {+): SeriesDefinition[] => {if ("breakout" in chartColumns) {const breakoutValues = getBreakoutDistinctValues(data,@@ -282,27 +125,6 @@ export const getSeries = ();};-export const getOrderedSeries = (- series: Series<GroupedDatum, SeriesInfo>[],- seriesOrder?: SeriesOrderSetting[],-) => {- if (seriesOrder == null || seriesOrder.length === 0) {- return series;- }-- return seriesOrder- .filter((orderSetting) => orderSetting.enabled)- .map((orderSetting) => {- const foundSeries = series.find(- (singleSeries) => singleSeries.seriesKey === orderSetting.key,- );- if (foundSeries === undefined) {- throw new TypeError("Series not found");- }- return foundSeries;- });-};-export const sanitizeResultData = (data: DatasetData) => {return {...data,diff --git a/frontend/src/metabase/viz-core/shared/utils/data.unit.spec.ts b/frontend/src/metabase/viz-core/shared/utils/data.unit.spec.tsindex 9b28bb54597..f580dadd90a 100644--- a/frontend/src/metabase/viz-core/shared/utils/data.unit.spec.ts+++ b/frontend/src/metabase/viz-core/shared/utils/data.unit.spec.ts@@ -8,9 +8,8 @@ import type {BreakoutChartColumns,MultipleMetricsChartColumns,} from "../../lib/graph/columns";-import type { ColumnFormatter } from "../types/format";-import { getGroupedDataset, getSeries } from "./data";+import { type ColumnFormatter, getSeries } from "./data";const columnFormatter: ColumnFormatter = (value: any) => String(value);@@ -65,135 +64,6 @@ const multipleMetricsChartColumns: MultipleMetricsChartColumns = {};describe("data utils", () => {- describe("getGroupedDataset", () => {- describe("chart with multiple metrics", () => {- it("should group dataset by dimension values", () => {- const groupedData = getGroupedDataset(- { rows },- multipleMetricsChartColumns,- createMockVisualizationSettings({ column: () => {} }),- columnFormatter,- );-- expect(groupedData).toStrictEqual([- {- dimensionValue: 2020,- isClickable: true,- metrics: {- count: 850,- avg: 190,- },- rawRows: [rows[0], rows[1]],- },- {- dimensionValue: 2021,- isClickable: true,- metrics: {- count: 1050,- avg: 230,- },- rawRows: [rows[2], rows[3]],- },- ]);- });- });- });-- describe("chart with a breakout", () => {- it("should group dataset by dimension values and breakout", () => {- const groupedData = getGroupedDataset(- { rows },- breakoutChartColumns,- createMockVisualizationSettings({ column: () => {} }),- columnFormatter,- );-- expect(groupedData).toStrictEqual([- {- dimensionValue: 2020,- isClickable: true,- metrics: {- count: 850,- },- rawRows: [rows[0], rows[1]],- breakout: {- Doohickey: {- metrics: {- count: 400,- },- rawRows: [rows[0]],- },- Gadget: {- metrics: {- count: 450,- },- rawRows: [rows[1]],- },- },- },- {- dimensionValue: 2021,- isClickable: true,- metrics: {- count: 1050,- },- rawRows: [rows[2], rows[3]],- breakout: {- Doohickey: {- metrics: {- count: 500,- },- rawRows: [rows[2]],- },- Gadget: {- metrics: {- count: 550,- },- rawRows: [rows[3]],- },- },- },- ]);- });-- it("should use untranslatedRows for breakout keys when present", () => {- const translatedRows = [- [2020, "Appareil", 400, 90],- [2020, "Bidule", 450, 100],- [2021, "Appareil", 500, 110],- [2021, "Bidule", 550, 120],- ];-- const groupedData = getGroupedDataset(- { rows: translatedRows, untranslatedRows: rows },- breakoutChartColumns,- createMockVisualizationSettings({ column: () => {} }),- columnFormatter,- );-- expect(groupedData[0].breakout).toStrictEqual({- Doohickey: {- metrics: { count: 400 },- rawRows: [translatedRows[0]],- },- Gadget: {- metrics: { count: 450 },- rawRows: [translatedRows[1]],- },- });- expect(groupedData[1].breakout).toStrictEqual({- Doohickey: {- metrics: { count: 500 },- rawRows: [translatedRows[2]],- },- Gadget: {- metrics: { count: 550 },- rawRows: [translatedRows[3]],- },- });- });- });-describe("getSeries", () => {describe("chart with breakout", () => {it("should return series for each breakout value", () => {diff --git a/frontend/src/metabase/viz-core/shared/utils/series.ts b/frontend/src/metabase/viz-core/shared/utils/series.tsdeleted file mode 100644index 120fdeaf191..00000000000--- a/frontend/src/metabase/viz-core/shared/utils/series.ts+++ /dev/null@@ -1,45 +0,0 @@-import type { DatasetData, VisualizationSettings } from "metabase-types/api";--import type { CartesianChartColumns } from "../../lib/graph/columns";-import { getCartesianChartColumns } from "../../lib/graph/columns";-import type { ColumnFormatter } from "../types/format";--import { getSeriesColors } from "./colors";-import { getOrderedSeries, getSeries } from "./data";--export const getTwoDimensionalChartSeries = (- data: DatasetData,- settings: VisualizationSettings,- columnFormatter: ColumnFormatter,-) => {- const chartColumns = getCartesianChartColumns(data.cols, settings);- const unorderedSeries = getSeries(- data,- chartColumns,- columnFormatter,- settings,- );- const seriesOrder = settings["graph.series_order"];- const series = getOrderedSeries(unorderedSeries, seriesOrder);-- const seriesColors = getSeriesColors(settings, series);-- return {- chartColumns,- series,- seriesColors,- };-};--export const getLabelsMetricColumn = (chartColumns: CartesianChartColumns) => {- // For multi-metrics charts we use the first metric column settings for formatting- return "breakout" in chartColumns- ? chartColumns.metric- : chartColumns.metrics[0];-};--export const getChartMetrics = (chartColumns: CartesianChartColumns) => {- return "breakout" in chartColumns- ? [chartColumns.metric]- : chartColumns.metrics;-};diff --git a/frontend/src/metabase/viz-core/types/hover.ts b/frontend/src/metabase/viz-core/types/hover.tsindex b8a2307064b..e5a46918104 100644--- a/frontend/src/metabase/viz-core/types/hover.ts+++ b/frontend/src/metabase/viz-core/types/hover.ts@@ -20,16 +20,6 @@ export interface TooltipRowModel {formatter?: (value: RowValue) => string;}-export interface StackedTooltipModel {- headerTitle?: string;- headerRows: TooltipRowModel[];- bodyRows?: TooltipRowModel[];- totalFormatter?: (value: unknown) => string;- showTotal?: boolean;- showPercentages?: boolean;- grandTotal?: number;-}-export interface HoveredObject {index?: number;seriesIndex?: number;@@ -43,7 +33,6 @@ export interface HoveredObject {settings?: ComputedVisualizationSettings;element?: Element;event?: MouseEvent;- stackedTooltipModel?: StackedTooltipModel;isAlreadyScaled?: boolean;pieSliceKeyPath?: string[];pieLegendHoverIndex?: number;diff --git a/frontend/test/__support__/storybook.tsx b/frontend/test/__support__/storybook.tsxindex 9fac2bc7931..7fc933c20f4 100644--- a/frontend/test/__support__/storybook.tsx+++ b/frontend/test/__support__/storybook.tsx@@ -18,7 +18,7 @@ import { Box } from "metabase/ui";import Visualization from "metabase/visualizations/components/Visualization";import type { RawSeries } from "metabase-types/api";-import { getStore } from "./entities-store";+import { getMainStore, getStore } from "./entities-store";import { TestWrapper } from "./ui";export const ReduxProvider = ({@@ -44,7 +44,8 @@ export const VisualizationWrapper = ({displayTheme?: "light" | "dark";initialStore?: State;}) => {- const store = getStore(mainReducers, initialStore);+ // Visualizations call RTK Query hooks, which need the `Api` reducer and middleware.+ const store = getMainStore(initialStore);return (<TestWrapperdiff --git a/package.json b/package.jsonindex d48e5b7517f..7b69f8e5d08 100644--- a/package.json+++ b/package.json@@ -75,9 +75,7 @@"@tiptap/starter-kit": "^3.31.3","@tiptap/suggestion": "^3.31.3","@uiw/react-codemirror": "^4.23.6",- "@visx/axis": "^3.10.1","@visx/clip-path": "^3.3.0",- "@visx/grid": "^3.5.0","@visx/group": "^3.3.0","@visx/scale": "^3.5.0","@visx/shape": "^3.5.0",