The easy-to-use open source Business Intelligence and Embedded Analytics tool that lets everyone work with data :bar_chart:
TypeScript analyticsbibusiness-intelligencebusinessintelligenceclojuredashboarddatadata-analysisdata-visualizationdatabasemetabasemysqlpostgrespostgresqlreportingslacksql-editorvisualization
Gdgt 2498 integration treemap (#76346)
Jakub Chodorowicz65a4459af7ca
diff --git a/.loki/reference/chrome_laptop_Viz_Static_Viz_TreemapChart_One_Level.png b/.loki/reference/chrome_laptop_Viz_Static_Viz_TreemapChart_One_Level.pngnew file mode 100644index 00000000000..cdc5c9d274fBinary files /dev/null and b/.loki/reference/chrome_laptop_Viz_Static_Viz_TreemapChart_One_Level.png differdiff --git a/.loki/reference/chrome_laptop_Viz_Static_Viz_TreemapChart_Two_Level.png b/.loki/reference/chrome_laptop_Viz_Static_Viz_TreemapChart_Two_Level.pngnew file mode 100644index 00000000000..51f5688680dBinary files /dev/null and b/.loki/reference/chrome_laptop_Viz_Static_Viz_TreemapChart_Two_Level.png differdiff --git a/.loki/reference/chrome_laptop_Viz_Static_Viz_TreemapChart_Watermark.png b/.loki/reference/chrome_laptop_Viz_Static_Viz_TreemapChart_Watermark.pngnew file mode 100644index 00000000000..ac48567b700Binary files /dev/null and b/.loki/reference/chrome_laptop_Viz_Static_Viz_TreemapChart_Watermark.png differdiff --git a/.loki/reference/chrome_laptop_viz_TreemapChart_Dark_Theme.png b/.loki/reference/chrome_laptop_viz_TreemapChart_Dark_Theme.pngnew file mode 100644index 00000000000..aee63b68476Binary files /dev/null and b/.loki/reference/chrome_laptop_viz_TreemapChart_Dark_Theme.png differdiff --git a/.loki/reference/chrome_laptop_viz_TreemapChart_One_Level.png b/.loki/reference/chrome_laptop_viz_TreemapChart_One_Level.pngnew file mode 100644index 00000000000..609bcd607c0Binary files /dev/null and b/.loki/reference/chrome_laptop_viz_TreemapChart_One_Level.png differdiff --git a/.loki/reference/chrome_laptop_viz_TreemapChart_Two_Level.png b/.loki/reference/chrome_laptop_viz_TreemapChart_Two_Level.pngnew file mode 100644index 00000000000..3923c8cb3b7Binary files /dev/null and b/.loki/reference/chrome_laptop_viz_TreemapChart_Two_Level.png differdiff --git a/e2e/test/scenarios/question/settings.cy.spec.js b/e2e/test/scenarios/question/settings.cy.spec.jsindex 63a1c91fce4..03c95c5403b 100644--- a/e2e/test/scenarios/question/settings.cy.spec.js+++ b/e2e/test/scenarios/question/settings.cy.spec.js@@ -364,7 +364,6 @@ describe("scenarios > question > settings", () => {.findByRole("listitem").within(() => {cy.findByLabelText("ellipsis icon").should("be.visible");- cy.findByLabelText("grabber icon").should("be.visible");cy.findByLabelText("eye_outline icon").should("be.visible");cy.findByText(longName).should("be.visible");});diff --git a/e2e/test/scenarios/visualizations-charts/treemap.cy.spec.ts b/e2e/test/scenarios/visualizations-charts/treemap.cy.spec.tsnew file mode 100644index 00000000000..970bc4a28bb--- /dev/null+++ b/e2e/test/scenarios/visualizations-charts/treemap.cy.spec.ts@@ -0,0 +1,139 @@+const { H } = cy;+import { SAMPLE_DB_ID } from "e2e/support/cypress_data";+import { SAMPLE_DATABASE } from "e2e/support/cypress_sample_database";++const { ORDERS, ORDERS_ID, PRODUCTS } = SAMPLE_DATABASE;++const TREEMAP_QUERY = `+SELECT 'Legumes' AS category, 'Chickpeas' AS item, 50 AS sales+UNION ALL SELECT 'Legumes', 'Lentils', 40+UNION ALL SELECT 'Legumes', 'Black Beans', 30+UNION ALL SELECT 'Grains', 'Quinoa', 35+UNION ALL SELECT 'Grains', 'Brown Rice', 45+UNION ALL SELECT 'Nuts', 'Almonds', 40+UNION ALL SELECT 'Nuts', 'Walnuts', 35;+`;++function treemapBreadcrumb() {+ return cy.findByTestId("treemap-breadcrumb");+}++describe("scenarios > visualizations > treemap", () => {+ beforeEach(() => {+ H.restore();+ cy.signInAsNormalUser();+ });++ it("should render and configure a treemap in the query builder", () => {+ H.visitQuestionAdhoc({+ display: "table",+ dataset_query: {+ type: "native",+ native: { query: TREEMAP_QUERY },+ database: SAMPLE_DB_ID,+ },+ });++ cy.log("Switch to the Treemap visualization");+ H.openVizTypeSidebar();+ cy.findByTestId("Treemap-button").click();++ cy.log("Top-level groups and leaf tiles render");+ H.echartsContainer()+ .should("contain", "Legumes")+ .and("contain", "Grains")+ .and("contain", "Nuts")+ .and("contain", "Chickpeas");++ cy.log("Toggle leaf labels off and on");+ H.openVizSettingsSidebar();+ cy.findByTestId("chartsettings-sidebar")+ .as("settings-sidebar")+ .findByText("Display")+ .click();++ cy.get("@settings-sidebar").findByText("Show leaf labels").click();++ H.echartsContainer()+ .should("contain", "Legumes")+ .and("not.contain", "Chickpeas");++ cy.get("@settings-sidebar").findByText("Show leaf labels").click();+ H.echartsContainer().should("contain", "Chickpeas");++ cy.log("Saving the question works");+ cy.findByTestId("qb-save-button").click();+ cy.findByPlaceholderText("What is the name of your question?").type(+ "My Treemap",+ );+ cy.findByTestId("save-question-modal").findByText("Save").click();+ H.checkSavedToCollectionQuestionToast();+ });++ it("should drill into a group and navigate back via the breadcrumb", () => {+ H.visitQuestionAdhoc({+ display: "treemap",+ dataset_query: {+ type: "native",+ native: { query: TREEMAP_QUERY },+ database: SAMPLE_DB_ID,+ },+ });++ cy.log("Overview breadcrumb shows the grand total");+ treemapBreadcrumb().should("contain", "Total");+ H.echartsContainer()+ .should("contain", "Legumes")+ .and("contain", "Grains")+ .and("contain", "Nuts");++ cy.log("Clicking a group drills into it");+ H.echartsContainer().findByText("Legumes").click();++ treemapBreadcrumb()+ .findByRole("button", { name: "Legumes" })+ .should("be.visible");+ H.echartsContainer()+ .should("contain", "Chickpeas")+ .and("contain", "Lentils")+ .and("not.contain", "Quinoa");++ cy.log("Back button returns to the overview");+ treemapBreadcrumb().findByRole("button", { name: "Legumes" }).click();++ treemapBreadcrumb().should("contain", "Total");+ H.echartsContainer().should("contain", "Grains").and("contain", "Nuts");+ });++ it("should drill through from a tile", () => {+ H.visitQuestionAdhoc({+ display: "treemap",+ dataset_query: {+ type: "query",+ database: SAMPLE_DB_ID,+ query: {+ "source-table": ORDERS_ID,+ aggregation: [["count"]],+ breakout: [+ ["field", PRODUCTS.CATEGORY, { "source-field": ORDERS.PRODUCT_ID }],+ ],+ },+ },+ });++ cy.log("One-level treemap renders the category tiles");+ H.echartsContainer()+ .should("contain", "Doohickey")+ .and("contain", "Widget");++ cy.log("Clicking a tile drills through to a filtered view");+ cy.intercept("POST", "/api/dataset").as("dataset");+ H.echartsContainer().findByText("Doohickey").click();+ H.popover().findByText("See these Orders").click();++ cy.wait("@dataset");+ cy.findByTestId("qb-filters-panel")+ .findByText("Product → Category is Doohickey")+ .should("be.visible");+ });+});diff --git a/frontend/src/embedding-sdk-bundle/components/public/SdkQuestion/SdkQuestion.unit.spec.tsx b/frontend/src/embedding-sdk-bundle/components/public/SdkQuestion/SdkQuestion.unit.spec.tsxindex 33cfa0592a4..8e9c541652b 100644--- a/frontend/src/embedding-sdk-bundle/components/public/SdkQuestion/SdkQuestion.unit.spec.tsx+++ b/frontend/src/embedding-sdk-bundle/components/public/SdkQuestion/SdkQuestion.unit.spec.tsx@@ -353,7 +353,7 @@ describe("InteractiveQuestion", () => {await userEvent.paste("A New Test Column");expect(- await screen.findByTestId("draggable-item-A New Test Column"),+ await screen.findByTestId("A New Test Column-settings-button"),).toBeInTheDocument();});diff --git a/frontend/src/metabase-types/api/card.ts b/frontend/src/metabase-types/api/card.tsindex 57e16c913fa..462e53a2123 100644--- a/frontend/src/metabase-types/api/card.ts+++ b/frontend/src/metabase-types/api/card.ts@@ -30,7 +30,11 @@ import type { CollectionEssentials } from "./search";import type { Table, TableId } from "./table";import type { UserInfo } from "./user";import type { CardDisplayType, VisualizationDisplay } from "./visualization";-import type { PieRow, SmartScalarComparison } from "./visualization-settings";+import type {+ PieRow,+ SmartScalarComparison,+ TreemapRow,+} from "./visualization-settings";export const CARD_TYPES = ["model", "question", "metric"] as const;export type CardType = (typeof CARD_TYPES)[number];@@ -355,6 +359,16 @@ export type VisualizationSettings = {"sankey.show_edge_labels"?: boolean;"sankey.label_value_formatting"?: "auto" | "full" | "compact";+ // Treemap settings+ "treemap.grouping"?: string;+ "treemap.sub_grouping"?: string | null;+ "treemap.value"?: string;+ "treemap.rows"?: TreemapRow[];+ "treemap.show_parent_labels"?: boolean;+ "treemap.show_parent_values"?: boolean;+ "treemap.show_leaf_labels"?: boolean;+ "treemap.show_leaf_values"?: boolean;+// BoxPlot settings"boxplot.whisker_type"?: BoxPlotWhiskerType;"boxplot.points_mode"?: BoxPlotPointsMode;diff --git a/frontend/src/metabase-types/api/icon.ts b/frontend/src/metabase-types/api/icon.tsindex 80e99ba3751..9520552a54a 100644--- a/frontend/src/metabase-types/api/icon.ts+++ b/frontend/src/metabase-types/api/icon.ts@@ -263,6 +263,7 @@ export type IconName =| "time_history"| "trash"| "trash_filled"+ | "treemap"| "triangle_left"| "triangle_right"| "unarchive"diff --git a/frontend/src/metabase-types/api/visualization-settings.ts b/frontend/src/metabase-types/api/visualization-settings.tsindex 63c9039050f..b1027a0e1ed 100644--- a/frontend/src/metabase-types/api/visualization-settings.ts+++ b/frontend/src/metabase-types/api/visualization-settings.ts@@ -53,3 +53,13 @@ export interface PieRow {hidden: boolean;isOther: boolean;}++export interface TreemapRow {+ key: string;+ name: string;+ originalName: string;+ color: string;+ defaultColor: boolean;+ enabled: boolean;+ hidden: boolean;+}diff --git a/frontend/src/metabase-types/api/visualization.ts b/frontend/src/metabase-types/api/visualization.tsindex c7275785587..fbc7c86d300 100644--- a/frontend/src/metabase-types/api/visualization.ts+++ b/frontend/src/metabase-types/api/visualization.ts@@ -35,6 +35,7 @@ export const cardDisplayTypes = ["boxplot","waterfall","sankey",+ "treemap","list",] as const;diff --git a/frontend/src/metabase/embedding/mcp/utils/getMcpChartTypes.ts b/frontend/src/metabase/embedding/mcp/utils/getMcpChartTypes.tsindex 56f37352f4e..4800d8e4afc 100644--- a/frontend/src/metabase/embedding/mcp/utils/getMcpChartTypes.ts+++ b/frontend/src/metabase/embedding/mcp/utils/getMcpChartTypes.ts@@ -22,6 +22,7 @@ const MCP_CHART_TYPE_ICONS: Record<CardDisplayType, IconName> = {scatter: "bubble",smartscalar: "smartscalar",table: "table2",+ treemap: "treemap",waterfall: "waterfall",list: "table2",};diff --git a/frontend/src/metabase/metabot/utils/chart-analysis.ts b/frontend/src/metabase/metabot/utils/chart-analysis.tsindex ca80567bb14..949646d080f 100644--- a/frontend/src/metabase/metabot/utils/chart-analysis.ts+++ b/frontend/src/metabase/metabot/utils/chart-analysis.ts@@ -19,6 +19,7 @@ const CHART_ANALYSIS_ENABLED = {row: true,sankey: true,scatter: true,+ treemap: true,waterfall: true,// disabledaction: false,@@ -62,6 +63,7 @@ export const CHART_ANALYSIS_RENDER_FORMATS = {row: "svg",sankey: "svg",scatter: "svg",+ treemap: "svg",waterfall: "svg",} as const satisfies { [display in EnabledChartTypes]: "png" | "svg" | "none" };diff --git a/frontend/src/metabase/static-viz/components/StaticVisualization/StaticVisualization.tsx b/frontend/src/metabase/static-viz/components/StaticVisualization/StaticVisualization.tsxindex 022cc308cf6..b65cf976625 100644--- a/frontend/src/metabase/static-viz/components/StaticVisualization/StaticVisualization.tsx+++ b/frontend/src/metabase/static-viz/components/StaticVisualization/StaticVisualization.tsx@@ -13,6 +13,7 @@ import { SankeyChart } from "../SankeyChart";import { ScalarChart } from "../ScalarChart";import { ScatterPlot } from "../ScatterPlot/ScatterPlot";import { SmartScalar } from "../SmartScalar";+import { TreemapChart } from "../TreemapChart";import { WaterfallChart } from "../WaterfallChart/WaterfallChart";registerStaticVisualizations();@@ -62,6 +63,8 @@ export const StaticVisualization = ({return <PieChart {...props} />;case "sankey":return <SankeyChart {...props} />;+ case "treemap":+ return <TreemapChart {...props} />;case "progress":return <ProgressBar {...props} />;case "row":diff --git a/frontend/src/metabase/static-viz/components/TreemapChart/TreemapChart.stories.tsx b/frontend/src/metabase/static-viz/components/TreemapChart/TreemapChart.stories.tsxnew file mode 100644index 00000000000..c72e5263be4--- /dev/null+++ b/frontend/src/metabase/static-viz/components/TreemapChart/TreemapChart.stories.tsx@@ -0,0 +1,63 @@+import type { StoryFn } from "@storybook/react";++import {+ measureTextHeight,+ measureTextWidth,+} from "metabase/static-viz/lib/text";+import { color } from "metabase/ui/colors";+import { DEFAULT_VISUALIZATION_THEME } from "metabase/visualizations/shared/utils/theme";+import type { RenderingContext } from "metabase/visualizations/types";++import {+ type StaticChartProps,+ StaticVisualization,+} from "../StaticVisualization";++import { data } from "./stories-data";++export default {+ title: "Viz/Static Viz/TreemapChart",+ component: StaticVisualization,+};++const Template: StoryFn<StaticChartProps> = (args) => {+ return (+ <div style={{ border: "1px solid black", display: "inline-block" }}>+ <StaticVisualization {...args} isStorybook />+ </div>+ );+};++const renderingContext: RenderingContext = {+ getColor: color,+ measureText: (text, style) =>+ measureTextWidth(text, Number(style.size), Number(style.weight)),+ measureTextHeight: (_, style) => measureTextHeight(Number(style.size)),+ fontFamily: "Lato",+ theme: DEFAULT_VISUALIZATION_THEME,+};++export const TwoLevel = {+ render: Template,+ args: {+ rawSeries: data.twoLevel,+ renderingContext,+ },+};++export const OneLevel = {+ render: Template,+ args: {+ rawSeries: data.oneLevel,+ renderingContext,+ },+};++export const Watermark = {+ render: Template,+ args: {+ rawSeries: data.twoLevel,+ renderingContext,+ hasDevWatermark: true,+ },+};diff --git a/frontend/src/metabase/static-viz/components/TreemapChart/TreemapChart.tsx b/frontend/src/metabase/static-viz/components/TreemapChart/TreemapChart.tsxnew file mode 100644index 00000000000..9b170eb2498--- /dev/null+++ b/frontend/src/metabase/static-viz/components/TreemapChart/TreemapChart.tsx@@ -0,0 +1,121 @@+import { Group } from "@visx/group";+import { init } from "echarts/core";++import type { StaticChartProps } from "metabase/static-viz/components/StaticVisualization";+import { sanitizeSvgForBatik } from "metabase/static-viz/lib/svg";+import { extractRemappings } from "metabase/visualizations";+import { registerEChartsModules } from "metabase/visualizations/echarts";+import { getTreemapColors } from "metabase/visualizations/echarts/graph/treemap/model/colors";+import {+ getTreemapChartColumns,+ getTreemapData,+} from "metabase/visualizations/echarts/graph/treemap/model/data";+import { getTreemapFormatters } from "metabase/visualizations/echarts/graph/treemap/model/formatters";+import { shouldShowParentLabels } from "metabase/visualizations/echarts/graph/treemap/model/labels";+import { measureTreemapLabelLayouts } from "metabase/visualizations/echarts/graph/treemap/model/measure";+import { getTreemapLayoutNodes } from "metabase/visualizations/echarts/graph/treemap/model/tree";+import {+ type TreemapChartOptionConfig,+ getStaticTreemapOption,+} from "metabase/visualizations/echarts/graph/treemap/option/option";++import Watermark from "../../watermark.svg?component";++import { TreemapLegend } from "./TreemapLegend";+import { LEGEND_WIDTH, getTreemapLegendModel } from "./legend";++const CHART_WIDTH = 965;+const CHART_HEIGHT = 764;+const LEGEND_GAP = 48;++registerEChartsModules();++export function TreemapChart({+ rawSeries,+ settings,+ renderingContext,+ isStorybook = false,+ hasDevWatermark = false,+}: StaticChartProps) {+ const rawSeriesWithRemappings = extractRemappings(rawSeries);+ const cols = rawSeriesWithRemappings[0]?.data?.cols ?? [];+ const treemapColumns = getTreemapChartColumns(cols, settings);+ if (!treemapColumns) {+ return null;+ }++ const treemapRows = settings["treemap.rows"];+ const tree = getTreemapData(+ rawSeriesWithRemappings,+ treemapColumns,+ treemapRows,+ settings,+ );+ const colors = getTreemapColors(tree, treemapRows);+ const formatters = getTreemapFormatters(treemapColumns, settings);++ const config: TreemapChartOptionConfig = {+ tree,+ colors,+ showParentLabels: shouldShowParentLabels(undefined, settings),+ showLeafLabels: settings["treemap.show_leaf_labels"] ?? true,+ formatValue: formatters.value,+ formatPercent: formatters.percent,+ renderingContext,+ };++ const chart = init(null, null, {+ renderer: "svg",+ ssr: true,+ width: CHART_WIDTH,+ height: CHART_HEIGHT,+ });++ // first pass to general layout of nodes+ chart.setOption(getStaticTreemapOption(config));+ chart.renderToSVGString();+ const layouts = measureTreemapLabelLayouts({+ nodes: getTreemapLayoutNodes(chart),+ tree,+ formatters,+ renderingContext,+ showLeafLabels: settings["treemap.show_leaf_labels"] ?? true,+ showLeafValues: settings["treemap.show_leaf_values"] ?? true,+ showParentValues: settings["treemap.show_parent_values"] ?? true,+ });++ // 2nd to render/hide labels+ chart.setOption(getStaticTreemapOption(config, layouts));+ const chartSvg = sanitizeSvgForBatik(chart.renderToSVGString(), isStorybook);++ const legendModel = getTreemapLegendModel(+ tree,+ colors,+ formatters.value,+ formatters.percent,+ );+ const width = CHART_WIDTH + LEGEND_GAP + LEGEND_WIDTH;+ const height = Math.max(CHART_HEIGHT, legendModel.height);++ return (+ <svg xmlns="http://www.w3.org/2000/svg" width={width} height={height}>+ <Group dangerouslySetInnerHTML={{ __html: chartSvg }}></Group>+ <TreemapLegend+ model={legendModel}+ left={CHART_WIDTH + LEGEND_GAP}+ renderingContext={renderingContext}+ />+ {hasDevWatermark && (+ <Watermark+ x="0"+ y="0"+ height={height}+ width={width}+ preserveAspectRatio="xMinYMin slice"+ fill={renderingContext.getColor("text-secondary")}+ opacity={0.2}+ />+ )}+ </svg>+ );+}diff --git a/frontend/src/metabase/static-viz/components/TreemapChart/TreemapChart.unit.spec.tsx b/frontend/src/metabase/static-viz/components/TreemapChart/TreemapChart.unit.spec.tsxnew file mode 100644index 00000000000..f7a24f6bec9--- /dev/null+++ b/frontend/src/metabase/static-viz/components/TreemapChart/TreemapChart.unit.spec.tsx@@ -0,0 +1,99 @@+import { render, screen } from "@testing-library/react";++import { createStaticRenderingContext } from "metabase/static-viz/lib/rendering-context";+import type { ComputedVisualizationSettings } from "metabase/visualizations/types";+import type { RawSeries } from "metabase-types/api";+import { createMockCard } from "metabase-types/api/mocks/card";+import {+ createMockColumn,+ createMockDatasetData,+} from "metabase-types/api/mocks/dataset";++import { TreemapChart } from "./TreemapChart";++function getRenderingContext() {+ return createStaticRenderingContext();+}++const settings = {+ "treemap.grouping": "Category",+ "treemap.sub_grouping": "SubCategory",+ "treemap.value": "Amount",+ column: () => ({}),+} as unknown as ComputedVisualizationSettings;++function makeRawSeries(rows: (string | number | null)[][]): RawSeries {+ return [+ {+ card: createMockCard({ display: "treemap" }),+ data: createMockDatasetData({+ cols: [+ createMockColumn({+ name: "Category",+ display_name: "Category",+ base_type: "type/Text",+ }),+ createMockColumn({+ name: "SubCategory",+ display_name: "Sub-Category",+ base_type: "type/Text",+ }),+ createMockColumn({+ name: "Amount",+ display_name: "Amount",+ base_type: "type/Number",+ semantic_type: "type/Number",+ }),+ ],+ rows,+ }),+ },+ ];+}++describe("static TreemapChart", () => {+ it("renders one legend row per top-level group, sorted by value desc, plus a total", () => {+ render(+ <TreemapChart+ rawSeries={makeRawSeries([+ ["Soy", "Tempeh", 20],+ ["Legumes", "Chickpeas", 60],+ ["Legumes", "Lentils", 20],+ ])}+ settings={settings}+ renderingContext={getRenderingContext()}+ isStorybook+ />,+ );++ const legendNames = screen+ .getAllByTestId("legend-name")+ .map((node) => node.textContent);+ expect(legendNames).toEqual(["Legumes", "Soy", "Total"]);++ expect(screen.getAllByTestId("legend-dot")).toHaveLength(2);+ });++ it("renders a 1-level treemap with a flat, dot-less legend", () => {+ render(+ <TreemapChart+ rawSeries={makeRawSeries([+ ["Legumes", null, 80],+ ["Soy", null, 20],+ ])}+ settings={{+ ...settings,+ "treemap.sub_grouping": undefined,+ }}+ renderingContext={getRenderingContext()}+ isStorybook+ />,+ );++ const legendNames = screen+ .getAllByTestId("legend-name")+ .map((node) => node.textContent);+ expect(legendNames).toEqual(["Legumes", "Soy", "Total"]);+ expect(screen.queryByTestId("legend-dot")).not.toBeInTheDocument();+ });+});diff --git a/frontend/src/metabase/static-viz/components/TreemapChart/TreemapLegend.tsx b/frontend/src/metabase/static-viz/components/TreemapChart/TreemapLegend.tsxnew file mode 100644index 00000000000..93468248a4a--- /dev/null+++ b/frontend/src/metabase/static-viz/components/TreemapChart/TreemapLegend.tsx@@ -0,0 +1,140 @@+import { Group } from "@visx/group";++import { Text } from "metabase/static-viz/components/Text";+import { measureTextWidth } from "metabase/static-viz/lib/text";+import { truncateText } from "metabase/visualizations/lib/text";+import type { RenderingContext } from "metabase/visualizations/types";++import {+ DOT_GAP,+ DOT_RADIUS,+ DOT_SIZE,+ FONT_SIZE,+ INDENT,+ LEGEND_WIDTH,+ NAME_CLUSTER_GAP,+ PADDING_TOP,+ PERCENT_WIDTH,+ ROW_CENTER_Y,+ type TreemapLegendModel,+ type TreemapLegendRow,+ VALUE_PERCENT_GAP,+ VALUE_WIDTH,+} from "./legend";++const FONT_WEIGHT_REGULAR = 400;+const FONT_WEIGHT_BOLD = 700;++type TreemapLegendProps = {+ model: TreemapLegendModel;+ left?: number;+ top?: number;+ width?: number;+ renderingContext: RenderingContext;+};++export function TreemapLegend({+ model,+ left,+ top,+ width = LEGEND_WIDTH,+ renderingContext,+}: TreemapLegendProps) {+ const { getColor } = renderingContext;+ const valueRight = width - PERCENT_WIDTH - VALUE_PERCENT_GAP;++ return (+ <Group left={left} top={top}>+ {model.rows.map((row, index) => {+ const fontWeight = getRowFontWeight(row);+ const indent = row.indent ? INDENT : 0;+ const nameX =+ indent + (row.color !== undefined ? DOT_SIZE + DOT_GAP : 0);+ const name = truncateName(row, width - nameX);++ return (+ <Group key={index} top={row.top}>+ {row.type === "total" && (+ <line+ data-testid="legend-separator"+ x1={0}+ x2={width}+ y1={-PADDING_TOP}+ y2={-PADDING_TOP}+ stroke={getColor("border")}+ />+ )}+ {row.color !== undefined && (+ <circle+ data-testid="legend-dot"+ cx={indent + DOT_RADIUS}+ cy={ROW_CENTER_Y}+ r={DOT_RADIUS}+ fill={row.color}+ />+ )}+ <Text+ data-testid="legend-name"+ x={nameX}+ y={ROW_CENTER_Y}+ verticalAnchor="middle"+ fontSize={FONT_SIZE}+ fontWeight={fontWeight}+ fill={getColor("text-primary")}+ >+ {name}+ </Text>+ <Text+ x={valueRight}+ y={ROW_CENTER_Y}+ textAnchor="end"+ verticalAnchor="middle"+ fontSize={FONT_SIZE}+ fontWeight={fontWeight}+ fill={getColor("text-primary")}+ >+ {row.valueLabel}+ </Text>+ <Text+ x={width}+ y={ROW_CENTER_Y}+ textAnchor="end"+ verticalAnchor="middle"+ fontSize={FONT_SIZE}+ fontWeight={fontWeight}+ fill={getColor("text-secondary")}+ >+ {row.percentLabel}+ </Text>+ </Group>+ );+ })}+ </Group>+ );+}++function getRowFontWeight(row: TreemapLegendRow) {+ return row.type === "leaf" ? FONT_WEIGHT_REGULAR : FONT_WEIGHT_BOLD;+}++function truncateName(row: TreemapLegendRow, availableFromNameX: number) {+ const fontWeight = getRowFontWeight(row);+ const nameMaxWidth =+ availableFromNameX -+ NAME_CLUSTER_GAP -+ VALUE_WIDTH -+ VALUE_PERCENT_GAP -+ PERCENT_WIDTH;++ return truncateText(+ row.name,+ nameMaxWidth,+ (text, style) =>+ measureTextWidth(text, Number(style.size), Number(style.weight)),+ {+ size: FONT_SIZE,+ weight: fontWeight,+ family: "Lato",+ },+ );+}diff --git a/frontend/src/metabase/static-viz/components/TreemapChart/TreemapLegend.unit.spec.tsx b/frontend/src/metabase/static-viz/components/TreemapChart/TreemapLegend.unit.spec.tsxnew file mode 100644index 00000000000..5a59ff6da61--- /dev/null+++ b/frontend/src/metabase/static-viz/components/TreemapChart/TreemapLegend.unit.spec.tsx@@ -0,0 +1,86 @@+import { render, screen } from "@testing-library/react";++import { measureTextWidth } from "metabase/static-viz/lib/text";+import type { RenderingContext } from "metabase/visualizations/types";++import { TreemapLegend } from "./TreemapLegend";+import type { TreemapLegendModel } from "./legend";++const renderingContext = {+ getColor: (color: string) => color,+ measureText: (text: string, style: { size: number; weight: number }) =>+ measureTextWidth(text, style.size, style.weight),+ measureTextHeight: () => 16,+ fontFamily: "Lato",+ theme: {} as RenderingContext["theme"],+} as RenderingContext;++const model: TreemapLegendModel = {+ rows: [+ {+ type: "parent",+ name: "Legumes",+ valueLabel: "$60",+ percentLabel: "60.00 %",+ color: "#509ee3",+ indent: false,+ top: 0,+ },+ {+ type: "leaf",+ name: "Chickpeas",+ valueLabel: "$40",+ percentLabel: "40.00 %",+ indent: true,+ top: 28,+ },+ {+ type: "total",+ name: "Total",+ valueLabel: "$100",+ percentLabel: "100 %",+ indent: true,+ top: 96,+ },+ ],+ height: 112,+};++function setup() {+ return render(+ <svg>+ <TreemapLegend model={model} renderingContext={renderingContext} />+ </svg>,+ );+}++describe("TreemapLegend", () => {+ it("renders every row's name, value, and percent", () => {+ setup();++ expect(screen.getByText("Legumes")).toBeInTheDocument();+ expect(screen.getByText("$60")).toBeInTheDocument();+ expect(screen.getByText("60.00 %")).toBeInTheDocument();+ expect(screen.getByText("Chickpeas")).toBeInTheDocument();+ expect(screen.getByText("Total")).toBeInTheDocument();+ expect(screen.getByText("100 %")).toBeInTheDocument();+ });++ it("bolds parent and total rows but not leaf rows", () => {+ setup();++ const [legumes, chickpeas, total] = screen.getAllByTestId("legend-name");+ expect(legumes).toHaveAttribute("font-weight", "700");+ expect(total).toHaveAttribute("font-weight", "700");+ expect(chickpeas).toHaveAttribute("font-weight", "400");+ });++ it("draws a color dot only for rows with a color, and one separator line", () => {+ setup();++ const dots = screen.getAllByTestId("legend-dot");+ expect(dots).toHaveLength(1);+ expect(dots[0]).toHaveAttribute("fill", "#509ee3");+ expect(screen.getAllByTestId("legend-separator")).toHaveLength(1);+ });+});diff --git a/frontend/src/metabase/static-viz/components/TreemapChart/index.ts b/frontend/src/metabase/static-viz/components/TreemapChart/index.tsnew file mode 100644index 00000000000..153ac35fa15--- /dev/null+++ b/frontend/src/metabase/static-viz/components/TreemapChart/index.ts@@ -0,0 +1 @@+export { TreemapChart } from "./TreemapChart";diff --git a/frontend/src/metabase/static-viz/components/TreemapChart/legend.ts b/frontend/src/metabase/static-viz/components/TreemapChart/legend.tsnew file mode 100644index 00000000000..785f9fb5afb--- /dev/null+++ b/frontend/src/metabase/static-viz/components/TreemapChart/legend.ts@@ -0,0 +1,78 @@+import { t } from "ttag";++import { formatPercent as formatPercentDefault } from "metabase/static-viz/lib/numbers";+import { getTreemapNodeKey } from "metabase/visualizations/echarts/graph/treemap/model/data";+import { getTreemapPercentOfTotalFormatter } from "metabase/visualizations/echarts/graph/treemap/model/formatters";+import { hasChildren } from "metabase/visualizations/echarts/graph/treemap/model/tree";+import type { TreemapTree } from "metabase/visualizations/echarts/graph/treemap/model/types";+import { getTreemapTotal } from "metabase/visualizations/echarts/graph/treemap/model/value";++export const LEGEND_WIDTH = 363;+export const ROW_HEIGHT = 16;+export const ROW_CENTER_Y = ROW_HEIGHT / 2;+export const GROUP_GAP = 24;+export const ROW_GAP = GROUP_GAP / 2;+export const PADDING_TOP = 16;+export const INDENT = 18;+export const DOT_SIZE = 12;+export const DOT_RADIUS = DOT_SIZE / 2;+export const DOT_GAP = 6;+export const VALUE_WIDTH = 112;+export const PERCENT_WIDTH = 52;+export const VALUE_PERCENT_GAP = 8;+export const NAME_CLUSTER_GAP = 16;+export const FONT_SIZE = 14;++export interface TreemapLegendRow {+ type: "parent" | "leaf" | "total";+ name: string;+ valueLabel: string;+ percentLabel: string;+ color?: string;+ indent: boolean;+ top: number;+}++export interface TreemapLegendModel {+ rows: TreemapLegendRow[];+ height: number;+}++export function getTreemapLegendModel(+ tree: TreemapTree,+ colors: Record<string, string>,+ formatValue: (value: number) => string,+ formatPercent: (ratio: number) => string = formatPercentDefault,+): TreemapLegendModel {+ const total = getTreemapTotal(tree);+ const formatShare = getTreemapPercentOfTotalFormatter(tree, formatPercent);+ const treeHasChildren = tree.some(hasChildren);++ const stride = ROW_HEIGHT + GROUP_GAP;++ const rows: TreemapLegendRow[] = [...tree]+ .sort((a, b) => b.value - a.value)+ .map((node, index) => ({+ type: treeHasChildren ? "parent" : "leaf",+ name: node.displayName,+ valueLabel: formatValue(node.value),+ percentLabel: formatShare(node.value),+ indent: false,+ top: stride * index,+ ...(treeHasChildren ? { color: colors[getTreemapNodeKey(node)] } : {}),+ }));++ const totalRow: TreemapLegendRow = {+ type: "total",+ name: t`Total`,+ valueLabel: formatValue(total),+ percentLabel: formatPercent(1),+ indent: treeHasChildren,+ top: stride * rows.length + PADDING_TOP,+ };++ return {+ rows: [...rows, totalRow],+ height: totalRow.top + ROW_HEIGHT,+ };+}diff --git a/frontend/src/metabase/static-viz/components/TreemapChart/stories-data/index.ts b/frontend/src/metabase/static-viz/components/TreemapChart/stories-data/index.tsnew file mode 100644index 00000000000..50114263efd--- /dev/null+++ b/frontend/src/metabase/static-viz/components/TreemapChart/stories-data/index.ts@@ -0,0 +1,4 @@+import oneLevel from "./one-level.json";+import twoLevel from "./two-level.json";++export const data = { twoLevel, oneLevel };diff --git a/frontend/src/metabase/static-viz/components/TreemapChart/stories-data/one-level.json b/frontend/src/metabase/static-viz/components/TreemapChart/stories-data/one-level.jsonnew file mode 100644index 00000000000..eb993ddeb51--- /dev/null+++ b/frontend/src/metabase/static-viz/components/TreemapChart/stories-data/one-level.json@@ -0,0 +1,41 @@+[+ {+ "card": {+ "id": 2,+ "name": "Sales by product",+ "display": "treemap",+ "visualization_settings": {+ "treemap.grouping": "PRODUCT",+ "treemap.value": "sum"+ }+ },+ "data": {+ "rows": [+ ["Oat Milk", 7089142.4],+ ["Soy Milk", 3139411.2],+ ["Almond Milk", 667935.2],+ ["Organic Unsweetened Barista Cashew Milk", 476931.2],+ ["Rice Milk", 250000],+ ["Hemp Milk", 120000]+ ],+ "cols": [+ {+ "name": "PRODUCT",+ "display_name": "Product",+ "base_type": "type/Text",+ "effective_type": "type/Text",+ "semantic_type": "type/Category",+ "source": "breakout"+ },+ {+ "name": "sum",+ "display_name": "Sum of Price",+ "base_type": "type/Float",+ "effective_type": "type/Float",+ "semantic_type": null,+ "source": "aggregation"+ }+ ]+ }+ }+]diff --git a/frontend/src/metabase/static-viz/components/TreemapChart/stories-data/two-level.json b/frontend/src/metabase/static-viz/components/TreemapChart/stories-data/two-level.jsonnew file mode 100644index 00000000000..5c9ac2935a9--- /dev/null+++ b/frontend/src/metabase/static-viz/components/TreemapChart/stories-data/two-level.json@@ -0,0 +1,62 @@+[+ {+ "card": {+ "id": 1,+ "name": "Sales by category and product",+ "display": "treemap",+ "visualization_settings": {+ "treemap.grouping": "CATEGORY",+ "treemap.sub_grouping": "PRODUCT",+ "treemap.value": "sum"+ }+ },+ "data": {+ "rows": [+ ["Plant Milks", "Oat Milk", 7089142.4],+ ["Plant Milks", "Soy Milk", 3139411.2],+ ["Plant Milks", "Almond Milk", 667935.2],+ ["Plant Milks", "Organic Unsweetened Barista Cashew Milk", 476931.2],+ ["Plant Milks", "Rice Milk", 250000],+ ["Plant Milks", "Hemp Milk", 120000],+ ["Meat Alternatives", "Seitan", 5349411.1],+ ["Meat Alternatives", "Tempeh", 1500000],+ ["Meat Alternatives", "Tofu", 800000],+ ["Meat Alternatives", "Jackfruit", 300000],+ ["Meat Alternatives", "Plant-Based Patties", 150000],+ ["Fresh Produce", "Leafy Greens", 401917.6],+ ["Fresh Produce", "Root Vegetables", 350000],+ ["Fresh Produce", "Stone Fruit", 250000],+ ["Pantry Staples", "Dried Legumes", 786234.2],+ ["Pantry Staples", "Whole Grains", 200000],+ ["Snacks", "Kale Chips", 150000],+ ["Snacks", "Energy Balls", 52580]+ ],+ "cols": [+ {+ "name": "CATEGORY",+ "display_name": "Category",+ "base_type": "type/Text",+ "effective_type": "type/Text",+ "semantic_type": "type/Category",+ "source": "breakout"+ },+ {+ "name": "PRODUCT",+ "display_name": "Product",+ "base_type": "type/Text",+ "effective_type": "type/Text",+ "semantic_type": "type/Category",+ "source": "breakout"+ },+ {+ "name": "sum",+ "display_name": "Sum of Price",+ "base_type": "type/Float",+ "effective_type": "type/Float",+ "semantic_type": null,+ "source": "aggregation"+ }+ ]+ }+ }+]diff --git a/frontend/src/metabase/static-viz/register.ts b/frontend/src/metabase/static-viz/register.tsindex 45f674ef6aa..5949ad6effe 100644--- a/frontend/src/metabase/static-viz/register.ts+++ b/frontend/src/metabase/static-viz/register.ts@@ -15,6 +15,7 @@ import { SankeyChart } from "metabase/visualizations/visualizations/SankeyChart"import { Scalar } from "metabase/visualizations/visualizations/Scalar";import { ScatterPlot } from "metabase/visualizations/visualizations/ScatterPlot";import { SmartScalar } from "metabase/visualizations/visualizations/SmartScalar";+import { TreemapChart } from "metabase/visualizations/visualizations/TreemapChart";import { WaterfallChart } from "metabase/visualizations/visualizations/WaterfallChart";export const registerStaticVisualizations = () => {@@ -47,5 +48,7 @@ export const registerStaticVisualizations = () => {// @ts-expect-error: incompatible prop types with registerVisualizationregisterVisualization(Progress);// @ts-expect-error: incompatible prop types with registerVisualization+ registerVisualization(TreemapChart);+ // @ts-expect-error: incompatible prop types with registerVisualizationsetDefaultVisualization(Scalar);};diff --git a/frontend/src/metabase/ui/components/icons/Icon/icons/index.ts b/frontend/src/metabase/ui/components/icons/Icon/icons/index.tsindex dd4d2d0c4c4..987d12423c6 100644--- a/frontend/src/metabase/ui/components/icons/Icon/icons/index.ts+++ b/frontend/src/metabase/ui/components/icons/Icon/icons/index.ts@@ -534,6 +534,8 @@ import trash_component from "./trash.svg?component";import trash_source from "./trash.svg?source";import trash_filled_component from "./trash_filled.svg?component";import trash_filled_source from "./trash_filled.svg?source";+import treemap_component from "./treemap.svg?component";+import treemap_source from "./treemap.svg?source";import triangle_left_component from "./triangle_left.svg?component";import triangle_left_source from "./triangle_left.svg?source";import triangle_right_component from "./triangle_right.svg?component";@@ -1625,6 +1627,10 @@ export const Icons: Record<IconName, { component: React.VFC; source: string }> =component: trash_filled_component,source: trash_filled_source,},+ treemap: {+ component: treemap_component,+ source: treemap_source,+ },triangle_left: {component: triangle_left_component,source: triangle_left_source,diff --git a/frontend/src/metabase/ui/components/icons/Icon/icons/treemap.svg b/frontend/src/metabase/ui/components/icons/Icon/icons/treemap.svgnew file mode 100644index 00000000000..61919483801--- /dev/null+++ b/frontend/src/metabase/ui/components/icons/Icon/icons/treemap.svg@@ -0,0 +1,3 @@+<svg width="16" height="16" viewBox="0 0 16 16" xmlns="http://www.w3.org/2000/svg">+<path d="M12 1.25C13.5188 1.25 14.75 2.48122 14.75 4V12C14.75 13.5188 13.5188 14.75 12 14.75H4C2.48122 14.75 1.25 13.5188 1.25 12V4C1.25 2.48122 2.48122 1.25 4 1.25H12ZM4 2.75C3.30964 2.75 2.75 3.30964 2.75 4V12C2.75 12.6904 3.30964 13.25 4 13.25H7.25V2.75H4ZM8.75 10.75V13.25H12C12.6904 13.25 13.25 12.6904 13.25 12V10.75H8.75ZM8.75 9.25H13.25V4C13.25 3.30964 12.6904 2.75 12 2.75H8.75V9.25Z" fill="currentColor"/>+</svg>diff --git a/frontend/src/metabase/visualizations/components/ChartSettings/BaseChartSettings/BaseChartSettings.tsx b/frontend/src/metabase/visualizations/components/ChartSettings/BaseChartSettings/BaseChartSettings.tsxindex aa6a1cae7a0..41a969fd0c6 100644--- a/frontend/src/metabase/visualizations/components/ChartSettings/BaseChartSettings/BaseChartSettings.tsx+++ b/frontend/src/metabase/visualizations/components/ChartSettings/BaseChartSettings/BaseChartSettings.tsx@@ -85,10 +85,13 @@ export const BaseChartSettings = ({widgets.find((widget) => widget.id === SERIES_SETTING_KEY);const display = transformedSeries?.[0]?.card?.display;- // In the pie the chart, clicking on the "measure" settings menu will only+ // In the pie and treemap charts, clicking on the "measure" settings menu will only// open a formatting widget, and we don't want the style widget (used only// for dimension) to override that- if (display === "pie" && currentWidget?.id === "column_settings") {+ if (+ (display === "pie" || display === "treemap") &&+ currentWidget?.id === "column_settings"+ ) {return null;}diff --git a/frontend/src/metabase/visualizations/components/EmptyVizState/utils.ts b/frontend/src/metabase/visualizations/components/EmptyVizState/utils.tsindex c7dfa06e6ef..2b87f3d04e9 100644--- a/frontend/src/metabase/visualizations/components/EmptyVizState/utils.ts+++ b/frontend/src/metabase/visualizations/components/EmptyVizState/utils.ts@@ -224,6 +224,19 @@ const emptyVizConfig: Record<SupportedDisplayType, EmptyVizConfig> = {return t`E.g. Count of orders grouped by Month`;},},+ treemap: {+ get imgSrc() {+ return getSubpathSafeUrl(+ "app/assets/img/empty-states/visualizations/treemap.svg",+ );+ },+ get primaryText() {+ return t`Then pick a metric and one or two columns to group by.`;+ },+ get secondaryText() {+ return t`E.g., Revenue grouped by Region and Country`;+ },+ },waterfall: {get imgSrc() {return getSubpathSafeUrl(diff --git a/frontend/src/metabase/visualizations/components/settings/ChartSettingOrderedItems/ChartSettingOrderedItems.tsx b/frontend/src/metabase/visualizations/components/settings/ChartSettingOrderedItems/ChartSettingOrderedItems.tsxindex eb3765fc4b2..82f07845f25 100644--- a/frontend/src/metabase/visualizations/components/settings/ChartSettingOrderedItems/ChartSettingOrderedItems.tsx+++ b/frontend/src/metabase/visualizations/components/settings/ChartSettingOrderedItems/ChartSettingOrderedItems.tsx@@ -34,6 +34,7 @@ interface ChartSettingOrderedItemsProps<onSortEnd: ({ id, newIndex }: DragEndEvent) => void;items: T[];getId: (item: T) => string | number;+ isSortable?: boolean;removeIcon?: IconProps["name"];accentColorOptions?: AccentColorOptions;getItemColor?: (item: SortableItem) => string | undefined;@@ -51,12 +52,13 @@ export function ChartSettingOrderedItems<T extends SortableItem>({items,onColorChange,getId,+ isSortable = true,removeIcon,accentColorOptions,getItemColor = (item) => item.color,dividers = [],}: ChartSettingOrderedItemsProps<T>) {- const isDragDisabled = items.length < 1;+ const isDragDisabled = !isSortable || items.length < 2;const sensors = useDndSensors({ distance: 15 });const renderItem = useCallback(diff --git a/frontend/src/metabase/visualizations/components/settings/ChartSettingSeriesOrder.tsx b/frontend/src/metabase/visualizations/components/settings/ChartSettingSeriesOrder.tsxindex 74783762789..913e96b9e9b 100644--- a/frontend/src/metabase/visualizations/components/settings/ChartSettingSeriesOrder.tsx+++ b/frontend/src/metabase/visualizations/components/settings/ChartSettingSeriesOrder.tsx@@ -43,6 +43,7 @@ export type ChartSettingSeriesOrderProps = {hasEditSettings: boolean;onChangeSeriesColor: (seriesKey: string, color: string) => void;onSortEnd: (newItems: SortableItem[]) => void;+ isSortable?: boolean;accentColorOptions?: AccentColorOptions;getItemColor?: (item: SortableChartSettingOrderedItem) => string | undefined;addButtonLabel?: string;@@ -63,6 +64,7 @@ export const ChartSettingSeriesOrder = ({hasEditSettings = true,onChangeSeriesColor,onSortEnd,+ isSortable = true,getItemColor,accentColorOptions,otherColor,@@ -220,6 +222,7 @@ export const ChartSettingSeriesOrder = ({onRemove={visibleItems.length > 1 ? toggleDisplay : undefined}onEnable={toggleDisplay}onSortEnd={handleSortEnd}+ isSortable={isSortable}onEdit={hasEditSettings ? handleOnEdit : undefined}onColorChange={handleColorChange}getId={getId}diff --git a/frontend/src/metabase/visualizations/components/settings/ChartSettingToggle.tsx b/frontend/src/metabase/visualizations/components/settings/ChartSettingToggle.tsxindex 9d626eea06d..c6e5aca893d 100644--- a/frontend/src/metabase/visualizations/components/settings/ChartSettingToggle.tsx+++ b/frontend/src/metabase/visualizations/components/settings/ChartSettingToggle.tsx@@ -4,10 +4,12 @@ export const ChartSettingToggle = ({value,onChange,id,+ disabled,}: {value: boolean | undefined;onChange: (value: boolean) => void;id?: string;+ disabled?: boolean;}) => (<SwitchlabelPosition="left"@@ -16,5 +18,6 @@ export const ChartSettingToggle = ({id={id}role="switch"size="sm"+ disabled={disabled}/>);diff --git a/frontend/src/metabase/visualizations/echarts/graph/treemap/model/breadcrumb.ts b/frontend/src/metabase/visualizations/echarts/graph/treemap/model/breadcrumb.tsnew file mode 100644index 00000000000..a2470f8670c--- /dev/null+++ b/frontend/src/metabase/visualizations/echarts/graph/treemap/model/breadcrumb.ts@@ -0,0 +1,24 @@+import { isOverview } from "./tree";+import type { TreemapTree } from "./types";+import { getTreemapTotal } from "./value";++export interface TreemapBreadcrumbModel {+ groupLabel: string | null;+ value: number;+}++export function getTreemapBreadcrumbModel(+ tree: TreemapTree,+ viewRootId: string | null,+): TreemapBreadcrumbModel {+ if (isOverview(viewRootId)) {+ return { groupLabel: null, value: getTreemapTotal(tree) };+ }++ const group = tree[Number(viewRootId)];+ if (group) {+ return { groupLabel: group.displayName, value: group.value };+ }++ return { groupLabel: null, value: getTreemapTotal(tree) };+}diff --git a/frontend/src/metabase/visualizations/echarts/graph/treemap/model/colors.ts b/frontend/src/metabase/visualizations/echarts/graph/treemap/model/colors.tsnew file mode 100644index 00000000000..53741d2ebdc--- /dev/null+++ b/frontend/src/metabase/visualizations/echarts/graph/treemap/model/colors.ts@@ -0,0 +1,40 @@+import Color from "color";++import { getColorsForValues } from "metabase/ui/colors/charts";+import type { TreemapRow } from "metabase-types/api";++import { getTreemapNodeKey } from "./data";+import type { TreemapTree } from "./types";++const LEAF_LIGHTNESS_MIN = 0.3;+const LEAF_LIGHTNESS_MAX = 0.5;++export function getTreemapColors(+ tree: TreemapTree,+ treemapRows?: TreemapRow[],+): Record<string, string> {+ const colors = getColorsForValues(tree.map(getTreemapNodeKey));+ treemapRows?.forEach((row) => {+ colors[row.key] = row.color;+ });+ return colors;+}++export function getTreemapLeafColor(+ groupColor: string | undefined,+ value: number,+ minValue: number,+ maxValue: number,+): string | undefined {+ if (!groupColor) {+ return undefined;+ }+ const normalized =+ maxValue === minValue ? 0.5 : (value - minValue) / (maxValue - minValue);+ const lightness =+ LEAF_LIGHTNESS_MIN + normalized * (LEAF_LIGHTNESS_MAX - LEAF_LIGHTNESS_MIN);+ return Color(groupColor)+ .lightness(lightness * 100)+ .rgb()+ .string();+}diff --git a/frontend/src/metabase/visualizations/echarts/graph/treemap/model/data.ts b/frontend/src/metabase/visualizations/echarts/graph/treemap/model/data.tsnew file mode 100644index 00000000000..bb4f6d3aea1--- /dev/null+++ b/frontend/src/metabase/visualizations/echarts/graph/treemap/model/data.ts@@ -0,0 +1,173 @@+import { NULL_DISPLAY_VALUE } from "metabase/utils/constants";+import { sumMetric } from "metabase/visualizations/lib/dataset";+import { getColumnDescriptors } from "metabase/visualizations/lib/graph/columns";+import { getKeyFromDimensionValue } from "metabase/visualizations/shared/settings/pie";+import type { ComputedVisualizationSettings } from "metabase/visualizations/types";+import type {+ DatasetColumn,+ RawSeries,+ RowValue,+ TreemapRow,+} from "metabase-types/api";++import { getTreemapColumnFormatter } from "./formatters";+import type { TreemapChartColumns, TreemapNode, TreemapTree } from "./types";++/**+ * The stable settings key for a top-level node — the same key `treemap.rows`+ * entries use, so colors and custom names resolve across data changes.+ */+export function getTreemapNodeKey(node: TreemapNode): string {+ return getKeyFromDimensionValue(node.rawName);+}++type TreemapSettingsColumns =+ | "treemap.grouping"+ | "treemap.sub_grouping"+ | "treemap.value";++export function getTreemapChartColumns<TColumn extends DatasetColumn>(+ columns: TColumn[],+ settings: Pick<ComputedVisualizationSettings, TreemapSettingsColumns>,+): TreemapChartColumns | null {+ const groupingColumnName = settings["treemap.grouping"];+ const valueColumnName = settings["treemap.value"];+ const subGroupingColumnName = settings["treemap.sub_grouping"];++ if (groupingColumnName == null || valueColumnName == null) {+ return null;+ }++ const grouping = getColumnDescriptors([groupingColumnName], columns)[0];+ const value = getColumnDescriptors([valueColumnName], columns)[0];++ if (!grouping?.column || !value?.column) {+ return null;+ }++ const subGroupingCandidate =+ subGroupingColumnName != null+ ? getColumnDescriptors([subGroupingColumnName], columns)[0]+ : undefined;++ return {+ grouping,+ subGrouping: subGroupingCandidate?.column+ ? subGroupingCandidate+ : undefined,+ value,+ };+}++export function getTreemapData(+ rawSeries: RawSeries,+ treemapColumns: TreemapChartColumns,+ treemapRows?: TreemapRow[],+ settings?: Pick<ComputedVisualizationSettings, "column">,+): TreemapTree {+ const [+ {+ data: { rows },+ },+ ] = rawSeries;+ const { grouping, subGrouping, value } = treemapColumns;+ const formatGroupingName = getTreemapColumnFormatter(+ grouping.column,+ settings,+ );+ const formatSubGroupingName =+ subGrouping != null+ ? getTreemapColumnFormatter(subGrouping.column, settings)+ : null;++ const rowNameByKey = new Map<string, string>(+ (treemapRows ?? []).map((row) => [row.key, row.name]),+ );++ const userDisabledRows = new Set(+ (treemapRows ?? [])+ .filter((row) => row.enabled === false)+ .map((row) => row.key),+ );++ const rootByKey = new Map<RowValue, TreemapNode>();+ const leafMapByRoot = new Map<TreemapNode, Map<RowValue, TreemapNode>>();++ rows.forEach((row, rowIndex) => {+ const groupingValue = row[grouping.index];+ const metricValue = row[value.index];++ if (userDisabledRows.has(getKeyFromDimensionValue(groupingValue))) {+ return;+ }++ const { node: rootNode } = getOrCreateNode({+ map: rootByKey,+ rawName: groupingValue,+ displayName:+ rowNameByKey.get(getKeyFromDimensionValue(groupingValue)) ??+ formatGroupingName(groupingValue),+ withChildren: subGrouping != null,+ });+ addRowMetric(rootNode, metricValue, rowIndex);++ if (subGrouping == null) {+ return;+ }++ const subGroupingValue = row[subGrouping.index];+ let leafMap = leafMapByRoot.get(rootNode);+ if (leafMap == null) {+ leafMap = new Map();+ leafMapByRoot.set(rootNode, leafMap);+ }+ const { node: leaf, wasCreated } = getOrCreateNode({+ map: leafMap,+ rawName: subGroupingValue,+ displayName:+ formatSubGroupingName?.(subGroupingValue) ?? NULL_DISPLAY_VALUE,+ withChildren: false,+ });+ addRowMetric(leaf, metricValue, rowIndex);+ if (wasCreated) {+ rootNode.children?.push(leaf);+ }+ });++ return Array.from(rootByKey.values());+}++function getOrCreateNode({+ map,+ rawName,+ displayName,+ withChildren,+}: {+ map: Map<RowValue, TreemapNode>;+ rawName: RowValue;+ displayName: string;+ withChildren: boolean;+}): { node: TreemapNode; wasCreated: boolean } {+ const existing = map.get(rawName);+ if (existing != null) {+ return { node: existing, wasCreated: false };+ }+ const node: TreemapNode = {+ rawName,+ displayName,+ value: 0,+ rowIndices: [],+ ...(withChildren ? { children: [] } : {}),+ };+ map.set(rawName, node);+ return { node, wasCreated: true };+}++function addRowMetric(+ node: TreemapNode,+ metricValue: RowValue,+ rowIndex: number,+): void {+ node.value = sumMetric(node.value, metricValue) ?? node.value;+ node.rowIndices.push(rowIndex);+}diff --git a/frontend/src/metabase/visualizations/echarts/graph/treemap/model/data.unit.spec.ts b/frontend/src/metabase/visualizations/echarts/graph/treemap/model/data.unit.spec.tsnew file mode 100644index 00000000000..edb20df578f--- /dev/null+++ b/frontend/src/metabase/visualizations/echarts/graph/treemap/model/data.unit.spec.ts@@ -0,0 +1,331 @@+import { NULL_DISPLAY_VALUE } from "metabase/utils/constants";+import { getNodesFromPath } from "metabase/visualizations/echarts/graph/treemap/model/tree";+import type { DatasetColumn, RowValue } from "metabase-types/api";+import { createMockCard } from "metabase-types/api/mocks/card";+import {+ createMockColumn,+ createMockDatasetData,+} from "metabase-types/api/mocks/dataset";++import { getTreemapChartColumns, getTreemapData } from "./data";+import type { TreemapChartColumns, TreemapTree } from "./types";++const columns: DatasetColumn[] = [+ createMockColumn({+ name: "Category",+ display_name: "Category",+ base_type: "type/Text",+ }),+ createMockColumn({+ name: "Amount",+ display_name: "Amount",+ base_type: "type/Number",+ semantic_type: "type/Number",+ }),+];++const columnsWithSub: DatasetColumn[] = [+ createMockColumn({+ name: "Category",+ display_name: "Category",+ base_type: "type/Text",+ }),+ createMockColumn({+ name: "SubCategory",+ display_name: "Sub-Category",+ base_type: "type/Text",+ }),+ createMockColumn({+ name: "Amount",+ display_name: "Amount",+ base_type: "type/Number",+ semantic_type: "type/Number",+ }),+];++const columnsWithNumericSub: DatasetColumn[] = [+ createMockColumn({+ name: "Category",+ display_name: "Category",+ base_type: "type/Text",+ }),+ createMockColumn({+ name: "SubAmount",+ display_name: "Sub-Amount",+ base_type: "type/Number",+ semantic_type: "type/Number",+ }),+ createMockColumn({+ name: "Amount",+ display_name: "Amount",+ base_type: "type/Number",+ semantic_type: "type/Number",+ }),+];++const treemapColumns: TreemapChartColumns = {+ grouping: { index: 0, column: columns[0] },+ value: { index: 1, column: columns[1] },+};++const treemapColumnsWithSub: TreemapChartColumns = {+ grouping: { index: 0, column: columnsWithSub[0] },+ subGrouping: { index: 1, column: columnsWithSub[1] },+ value: { index: 2, column: columnsWithSub[2] },+};++const treemapColumnsWithNumericSub: TreemapChartColumns = {+ grouping: { index: 0, column: columnsWithNumericSub[0] },+ subGrouping: { index: 1, column: columnsWithNumericSub[1] },+ value: { index: 2, column: columnsWithNumericSub[2] },+};++function makeRawSeries1Level(rows: RowValue[][]) {+ return [+ {+ card: createMockCard({ name: "Treemap card" }),+ data: createMockDatasetData({ rows, cols: columns }),+ },+ ];+}++function makeRawSeries2Level(rows: RowValue[][]) {+ return [+ {+ card: createMockCard({ name: "Treemap card" }),+ data: createMockDatasetData({ rows, cols: columnsWithSub }),+ },+ ];+}++function makeRawSeries2LevelWithNumericSub(rows: RowValue[][]) {+ return [+ {+ card: createMockCard({ name: "Treemap card" }),+ data: createMockDatasetData({ rows, cols: columnsWithNumericSub }),+ },+ ];+}++describe("treemap data model", () => {+ it("resolves columns and falls back when sub-grouping is invalid", () => {+ expect(+ getTreemapChartColumns(columns, {+ "treemap.grouping": "Category",+ }),+ ).toBeNull();++ expect(+ getTreemapChartColumns(columns, {+ "treemap.grouping": "Category",+ "treemap.value": "Amount",+ }),+ ).toEqual({+ grouping: expect.objectContaining({ index: 0 }),+ value: expect.objectContaining({ index: 1 }),+ });++ expect(+ getTreemapChartColumns(columnsWithSub, {+ "treemap.grouping": "Category",+ "treemap.sub_grouping": "SubCategory",+ "treemap.value": "Amount",+ }),+ ).toEqual({+ grouping: expect.objectContaining({ index: 0 }),+ subGrouping: expect.objectContaining({ index: 1 }),+ value: expect.objectContaining({ index: 2 }),+ });++ expect(+ getTreemapChartColumns(columnsWithSub, {+ "treemap.grouping": "Category",+ "treemap.sub_grouping": "DoesNotExist",+ "treemap.value": "Amount",+ }),+ ).toEqual({+ grouping: expect.objectContaining({ index: 0 }),+ value: expect.objectContaining({ index: 2 }),+ });+ });++ it("builds a 1-level tree with aggregation and treemap.rows behavior", () => {+ const result = getTreemapData(+ makeRawSeries1Level([+ [null, 7],+ ["A", 10],+ ["A", null],+ ["B", 20],+ ]),+ treemapColumns,+ [+ {+ key: NULL_DISPLAY_VALUE,+ name: "No category",+ originalName: NULL_DISPLAY_VALUE,+ color: "#FF0000",+ defaultColor: false,+ enabled: true,+ hidden: false,+ },+ {+ key: "A",+ name: "Renamed A",+ originalName: "A",+ color: "#00FF00",+ defaultColor: false,+ enabled: true,+ hidden: false,+ },+ {+ key: "B",+ name: "B",+ originalName: "B",+ color: "#0000FF",+ defaultColor: true,+ enabled: false,+ hidden: false,+ },+ ],+ );++ expect(result).toEqual([+ {+ rawName: null,+ displayName: "No category",+ value: 7,+ rowIndices: [0],+ },+ {+ rawName: "A",+ displayName: "Renamed A",+ value: 10,+ rowIndices: [1, 2],+ },+ ]);+ });++ it("builds a 2-level tree with duplicate and null sub-grouping aggregation", () => {+ const result = getTreemapData(+ makeRawSeries2Level([+ ["A", "x", 10],+ ["A", null, 4],+ ["A", "x", 3],+ ["B", "x", 2],+ ]),+ treemapColumnsWithSub,+ );++ expect(result).toEqual([+ {+ rawName: "A",+ displayName: "A",+ value: 17,+ rowIndices: [0, 1, 2],+ children: [+ {+ rawName: "x",+ displayName: "x",+ value: 13,+ rowIndices: [0, 2],+ },+ {+ rawName: null,+ displayName: NULL_DISPLAY_VALUE,+ value: 4,+ rowIndices: [1],+ },+ ],+ },+ {+ rawName: "B",+ displayName: "B",+ value: 2,+ rowIndices: [3],+ children: [+ {+ rawName: "x",+ displayName: "x",+ value: 2,+ rowIndices: [3],+ },+ ],+ },+ ]);+ });++ it("formats 2-level sub-grouping leaf display names from column settings", () => {+ const result = getTreemapData(+ makeRawSeries2LevelWithNumericSub([+ ["A", 1000, 1],+ ["A", 2500, 2],+ ]),+ treemapColumnsWithNumericSub,+ undefined,+ {+ column: (column) =>+ column.name === "SubAmount" ? { prefix: "$" } : {},+ },+ );++ expect(result).toMatchObject([+ {+ rawName: "A",+ value: 3,+ rowIndices: [0, 1],+ children: [+ {+ rawName: 1000,+ displayName: "$1,000",+ value: 1,+ rowIndices: [0],+ },+ {+ rawName: 2500,+ displayName: "$2,500",+ value: 2,+ rowIndices: [1],+ },+ ],+ },+ ]);+ });+});++describe("getNodesFromPath", () => {+ const tree: TreemapTree = [+ {+ rawName: "Legumes",+ displayName: "Legumes",+ value: 30,+ rowIndices: [],+ children: [+ {+ rawName: "Chickpeas",+ displayName: "Chickpeas",+ value: 20,+ rowIndices: [],+ },+ {+ rawName: "Lentils",+ displayName: "Lentils",+ value: 10,+ rowIndices: [],+ },+ ],+ },+ { rawName: "Grains", displayName: "Grains", value: 5, rowIndices: [] },+ ];++ it("resolves top-level and leaf paths, and rejects invalid ids", () => {+ expect(getNodesFromPath(tree, "1")).toEqual([tree[1]]);+ expect(getNodesFromPath(tree, "0-1")).toEqual([+ tree[0],+ tree[0].children?.[1],+ ]);++ expect(getNodesFromPath(tree, "5")).toBeNull();+ expect(getNodesFromPath(tree, "0-9")).toBeNull();+ expect(getNodesFromPath(tree, "1-0")).toBeNull();+ });+});diff --git a/frontend/src/metabase/visualizations/echarts/graph/treemap/model/formatters.ts b/frontend/src/metabase/visualizations/echarts/graph/treemap/model/formatters.tsnew file mode 100644index 00000000000..df3a167ff11--- /dev/null+++ b/frontend/src/metabase/visualizations/echarts/graph/treemap/model/formatters.ts@@ -0,0 +1,59 @@+import { NULL_DISPLAY_VALUE } from "metabase/utils/constants";+import { formatValue } from "metabase/visualizations/lib/formatting";+import type { ComputedVisualizationSettings } from "metabase/visualizations/types";+import type { DatasetColumn, RowValue } from "metabase-types/api";++import type { TreemapChartColumns, TreemapTree } from "./types";+import { getTreemapTotal } from "./value";++export interface TreemapFormatters {+ value: (value: number) => string;+ percent: (ratio: number) => string;+}++export function getTreemapFormatters(+ columns: TreemapChartColumns,+ settings: ComputedVisualizationSettings,+): TreemapFormatters {+ const valueColumn = columns.value.column;+ return {+ value: getTreemapColumnFormatter(valueColumn, settings),+ percent: (ratio: number) =>+ String(+ formatValue(ratio, {+ column: valueColumn,+ number_style: "percent",+ decimals: Math.abs(ratio) === 1 ? 0 : 2,+ }),+ ),+ };+}++export function getTreemapColumnFormatter(+ column: DatasetColumn,+ settings?: Pick<ComputedVisualizationSettings, "column">,+) {+ const columnSettings = settings?.column?.(column);++ return (value: RowValue): string => {+ if (value == null) {+ return NULL_DISPLAY_VALUE;+ }++ return String(+ formatValue(value, {+ ...columnSettings,+ column,+ }) ?? NULL_DISPLAY_VALUE,+ );+ };+}++export function getTreemapPercentOfTotalFormatter(+ tree: TreemapTree,+ formatPercent: (ratio: number) => string,+) {+ const total = getTreemapTotal(tree);++ return (value: number) => formatPercent(total === 0 ? 0 : value / total);+}diff --git a/frontend/src/metabase/visualizations/echarts/graph/treemap/model/labels.ts b/frontend/src/metabase/visualizations/echarts/graph/treemap/model/labels.tsnew file mode 100644index 00000000000..d4c9a7c25c3--- /dev/null+++ b/frontend/src/metabase/visualizations/echarts/graph/treemap/model/labels.ts@@ -0,0 +1,150 @@+import type { VisualizationGridSize } from "custom-viz";+import { match } from "ts-pattern";++import type { VisualizationProps } from "metabase/visualizations/types";++import { LABEL_PADDING, groupHeader } from "../style";++import type { TreemapLayoutNode } from "./types";++export const PARENT_MIN_HEADER_VISIBLE_CHARS = 3;+export const PARENT_HEADER_VALUE_PERCENT_GAP = 8;+const PARENT_LABEL_MIN_GRID_WIDTH = 12;+const PARENT_LABEL_MIN_GRID_HEIGHT = 8;++export type TreemapLabelDetail = "full" | "labelOnly" | "none";++export interface TreemapLabelLayout {+ detail: TreemapLabelDetail;+ width: number;+}++export function shouldShowParentLabels(+ gridSize: VisualizationGridSize | undefined,+ settings: VisualizationProps["settings"],+) {+ const fitsParentLabels =+ gridSize === undefined ||+ (gridSize.width >= PARENT_LABEL_MIN_GRID_WIDTH &&+ gridSize.height >= PARENT_LABEL_MIN_GRID_HEIGHT);++ return (settings["treemap.show_parent_labels"] ?? true) && fitsParentLabels;+}++export interface ParentLabelLayout {+ showText: boolean;+ showValuePercent: boolean;+ nameColumnWidth?: number;+}++export interface ParentLabelLayoutConfig {+ measureTextWidth: (text: string) => number;+ getLabel: (id: string) => string | undefined;+ getValuePercentWidth?: (id: string) => number;+}++export function getAllParentLabelLayouts(+ nodes: TreemapLayoutNode[],+ config: ParentLabelLayoutConfig,+): Record<string, ParentLabelLayout> {+ const layouts: Record<string, ParentLabelLayout> = {};+ for (const node of nodes) {+ if (node.isLeaf) {+ continue;+ }+ const label = config.getLabel(node.id);+ if (label == null) {+ continue;+ }+ const available = node.rect.width - groupHeader.paddingX * 2;+ const minReadable = label.slice(0, PARENT_MIN_HEADER_VISIBLE_CHARS);+ const minLabelWidth = config.measureTextWidth(minReadable);+ const fullLabelWidth = config.measureTextWidth(label);+ const showText = minLabelWidth <= available;+ let showValuePercent = false;+ let nameColumnWidth: number | undefined;+ if (showText) {+ const clusterWidth = config.getValuePercentWidth?.(node.id) ?? Infinity;++ showValuePercent =+ fullLabelWidth + PARENT_HEADER_VALUE_PERCENT_GAP + clusterWidth <=+ available;++ if (showValuePercent) {+ nameColumnWidth =+ available - PARENT_HEADER_VALUE_PERCENT_GAP - clusterWidth;+ }+ }+ layouts[node.id] = {+ showText,+ showValuePercent,+ nameColumnWidth,+ };+ }+ return layouts;+}++export const MIN_LABEL_TILE_WIDTH = 100;+export const MIN_LABEL_TILE_HEIGHT = 40;+export const MIN_FULL_LABEL_TILE_HEIGHT = 100;++export interface TileLabelLayoutsConfig {+ getValueLabelWidth?: (id: string) => number;+ showLeafLabels?: boolean;+}++interface GetTileLabelLayoutArgs {+ rect: { width: number; height: number };+ valueLabelWidth: number;+}++export function getAllTileLabelLayouts(+ nodes: TreemapLayoutNode[],+ {+ getValueLabelWidth = () => Infinity,+ showLeafLabels = true,+ }: TileLabelLayoutsConfig,+): Record<string, TreemapLabelLayout> {+ const layouts: Record<string, TreemapLabelLayout> = {};+ for (const node of nodes) {+ if (!node.isLeaf) {+ continue;+ }+ if (!showLeafLabels) {+ layouts[node.id] = {+ detail: "none",+ width: Math.max(0, node.rect.width - LABEL_PADDING * 2),+ };+ continue;+ }+ const fitsLabel =+ node.rect.width >= MIN_LABEL_TILE_WIDTH &&+ node.rect.height >= MIN_LABEL_TILE_HEIGHT;+ const fitsFull =+ fitsLabel && node.rect.height >= MIN_FULL_LABEL_TILE_HEIGHT;+ layouts[node.id] = getTileLabelLayout({+ rect: node.rect,+ valueLabelWidth: fitsFull ? getValueLabelWidth(node.id) : Infinity,+ });+ }+ return layouts;+}++export function getTileLabelLayout({+ rect,+ valueLabelWidth,+}: GetTileLabelLayoutArgs): TreemapLabelLayout {+ const innerWidth = Math.max(0, rect.width - LABEL_PADDING * 2);+ const fitsLabel =+ rect.width >= MIN_LABEL_TILE_WIDTH && rect.height >= MIN_LABEL_TILE_HEIGHT;+ const fitsFull =+ fitsLabel &&+ rect.height >= MIN_FULL_LABEL_TILE_HEIGHT &&+ innerWidth >= valueLabelWidth;++ const detail: TreemapLabelDetail = match({ fitsFull, fitsLabel })+ .with({ fitsFull: true }, () => "full" as const)+ .with({ fitsLabel: true }, () => "labelOnly" as const)+ .otherwise(() => "none");+ return { detail, width: innerWidth };+}diff --git a/frontend/src/metabase/visualizations/echarts/graph/treemap/model/labels.unit.spec.ts b/frontend/src/metabase/visualizations/echarts/graph/treemap/model/labels.unit.spec.tsnew file mode 100644index 00000000000..bb5b3627550--- /dev/null+++ b/frontend/src/metabase/visualizations/echarts/graph/treemap/model/labels.unit.spec.ts@@ -0,0 +1,145 @@+import {+ getAllParentLabelLayouts,+ getAllTileLabelLayouts,+ getTileLabelLayout,+} from "./labels";+import type { TreemapLayoutNode } from "./types";++function leaf(id: string, width: number, height: number): TreemapLayoutNode {+ return { id, rect: { width, height }, isLeaf: true };+}++function group(id: string, width: number): TreemapLayoutNode {+ return { id, rect: { width, height: 32 }, isLeaf: false };+}++describe("getTreemapLabelLayout", () => {+ it("returns full detail for large tiles when the value block fits", () => {+ expect(+ getTileLabelLayout({+ rect: { width: 200, height: 120 },+ valueLabelWidth: 120,+ }),+ ).toEqual({+ detail: "full",+ width: 176,+ });+ });++ it("degrades to labelOnly or none when constraints are not met", () => {+ expect(+ getTileLabelLayout({+ rect: { width: 200, height: 120 },+ valueLabelWidth: 200,+ }),+ ).toEqual({+ detail: "labelOnly",+ width: 176,+ });++ expect(+ getTileLabelLayout({+ rect: { width: 80, height: 300 },+ valueLabelWidth: 0,+ }),+ ).toEqual({+ detail: "none",+ width: 56,+ });+ });+});++describe("getTreemapLabelLayouts", () => {+ it("keeps leaf nodes only and applies per-leaf value widths", () => {+ const nodes: TreemapLayoutNode[] = [+ group("0", 300),+ leaf("0-0", 200, 120),+ leaf("0-1", 200, 120),+ ];+ const valueWidths: Record<string, number> = { "0-0": 100, "0-1": 500 };++ expect(+ getAllTileLabelLayouts(nodes, {+ getValueLabelWidth: (id) => valueWidths[id],+ }),+ ).toEqual({+ "0-0": { detail: "full", width: 176 },+ "0-1": { detail: "labelOnly", width: 176 },+ });+ });++ it("measures leaf value width only when a tile can show full detail", () => {+ const nodes: TreemapLayoutNode[] = [+ leaf("0-0", 80, 120),+ leaf("0-1", 200, 80),+ leaf("0-2", 200, 120),+ ];+ const getValueLabelWidth = jest.fn(() => 100);++ expect(+ getAllTileLabelLayouts(nodes, {+ getValueLabelWidth,+ }),+ ).toEqual({+ "0-0": { detail: "none", width: 56 },+ "0-1": { detail: "labelOnly", width: 176 },+ "0-2": { detail: "full", width: 176 },+ });+ expect(getValueLabelWidth).toHaveBeenCalledTimes(1);+ expect(getValueLabelWidth).toHaveBeenCalledWith("0-2");+ });++ it("renders no leaf labels when leaf labels are turned off", () => {+ const nodes: TreemapLayoutNode[] = [+ group("0", 300),+ leaf("0-0", 200, 120),+ leaf("0-1", 200, 120),+ ];+ const getValueLabelWidth = jest.fn(() => 100);++ expect(+ getAllTileLabelLayouts(nodes, {+ getValueLabelWidth,+ showLeafLabels: false,+ }),+ ).toEqual({+ "0-0": { detail: "none", width: 176 },+ "0-1": { detail: "none", width: 176 },+ });+ expect(getValueLabelWidth).not.toHaveBeenCalled();+ });+});++describe("getTreemapParentLabelLayouts", () => {+ const labels: Record<string, string> = { "0": "Quinoa", "1": "Lentils" };+ const parentConfig = {+ measureTextWidth: (text: string) => text.length * 6,+ getLabel: (id: string) => labels[id],+ getValuePercentWidth: () => 100,+ };++ it("shows text and value-percent only when both prefix and cluster fit", () => {+ expect(+ getAllParentLabelLayouts([group("0", 200), group("1", 60)], parentConfig),+ ).toEqual({+ "0": { showText: true, showValuePercent: true, nameColumnWidth: 68 },+ "1": { showText: true, showValuePercent: false },+ });+ });++ it("skips value-percent measurement when the label text does not fit", () => {+ const getValuePercentWidth = jest.fn(() => 100);++ expect(+ getAllParentLabelLayouts([group("0", 200), group("1", 30)], {+ ...parentConfig,+ getValuePercentWidth,+ }),+ ).toEqual({+ "0": { showText: true, showValuePercent: true, nameColumnWidth: 68 },+ "1": { showText: false, showValuePercent: false },+ });+ expect(getValuePercentWidth).toHaveBeenCalledTimes(1);+ expect(getValuePercentWidth).toHaveBeenCalledWith("0");+ });+});diff --git a/frontend/src/metabase/visualizations/echarts/graph/treemap/model/measure.ts b/frontend/src/metabase/visualizations/echarts/graph/treemap/model/measure.tsnew file mode 100644index 00000000000..82548c7e1d1--- /dev/null+++ b/frontend/src/metabase/visualizations/echarts/graph/treemap/model/measure.ts@@ -0,0 +1,92 @@+import type { RenderingContext } from "metabase/visualizations/types";++import { groupHeader, leafBlock } from "../style";++import {+ type TreemapFormatters,+ getTreemapPercentOfTotalFormatter,+} from "./formatters";+import {+ type ParentLabelLayout,+ type TreemapLabelLayout,+ getAllParentLabelLayouts,+ getAllTileLabelLayouts,+} from "./labels";+import { getNode } from "./tree";+import type { NodeId, TreemapLayoutNode, TreemapTree } from "./types";++export interface TreemapMeasuredLabelLayouts {+ leafLabelLayout: Record<NodeId, TreemapLabelLayout>;+ parentLabelLayout: Record<NodeId, ParentLabelLayout>;+}++/**+ * Based on real rendered sizes of headers and tiles, decide which labels show+ */+export function measureTreemapLabelLayouts({+ nodes,+ tree,+ formatters,+ renderingContext,+ showLeafLabels,+ showLeafValues,+ showParentValues,+}: {+ nodes: TreemapLayoutNode[];+ tree: TreemapTree;+ formatters: TreemapFormatters;+ renderingContext: RenderingContext;+ showLeafLabels: boolean;+ showLeafValues: boolean;+ showParentValues: boolean;+}): TreemapMeasuredLabelLayouts {+ const formatShare = getTreemapPercentOfTotalFormatter(+ tree,+ formatters.percent,+ );++ const labelLayout = getAllTileLabelLayouts(nodes, {+ showLeafLabels,+ getValueLabelWidth: (id) => {+ if (!showLeafValues) {+ return Infinity;+ }+ const node = getNode(id, tree);+ if (node == null) {+ return Infinity;+ }+ return renderingContext.measureText(formatters.value(node.value), {+ size: leafBlock.value.fontSize,+ family: renderingContext.fontFamily,+ weight: leafBlock.value.fontWeight,+ });+ },+ });++ const measureHeader = (text: string, weight: number) =>+ renderingContext.measureText(text, {+ size: groupHeader.fontSize,+ family: renderingContext.fontFamily,+ weight,+ });+ const parentLabelLayout = getAllParentLabelLayouts(nodes, {+ getLabel: (id) => getNode(id, tree)?.displayName,+ measureTextWidth: (text) => measureHeader(text, groupHeader.fontWeight),+ getValuePercentWidth: (id) => {+ if (!showParentValues) {+ return Infinity;+ }+ const node = getNode(id, tree);+ if (node == null) {+ return Infinity;+ }+ return (+ measureHeader(formatters.value(node.value), groupHeader.fontWeight) ++ groupHeader.valuePercentGap ++ measureHeader(formatShare(node.value), groupHeader.percentFontWeight)+ );+ },+ });++ return { leafLabelLayout: labelLayout, parentLabelLayout };+}diff --git a/frontend/src/metabase/visualizations/echarts/graph/treemap/model/tooltip.ts b/frontend/src/metabase/visualizations/echarts/graph/treemap/model/tooltip.tsnew file mode 100644index 00000000000..2e6afdd4da6--- /dev/null+++ b/frontend/src/metabase/visualizations/echarts/graph/treemap/model/tooltip.ts@@ -0,0 +1,158 @@+import { t } from "ttag";++import type {+ EChartsTooltipModel,+ EChartsTooltipRow,+} from "metabase/visualizations/components/ChartTooltip/EChartsTooltip";+import { getMarkerColorClass } from "metabase/visualizations/echarts/tooltip";++import type { ParentLabelLayout, TreemapLabelLayout } from "./labels";+import { getSiblings, isOverview, parseTreemapNodeId } from "./tree";+import type {+ ChartPointer,+ TreemapNode,+ TreemapRect,+ TreemapTree,+} from "./types";+import { getTreemapTotal } from "./value";++export interface TreemapTooltipContext {+ header?: string;+ siblings: TreemapTree;+ focusedNode: TreemapNode;+ parentNode?: TreemapNode;+}++export interface TreemapInlineValueIds {+ fullLeafIds: Set<string>;+ valuePercentHeaderIds: Set<string>;+}++export function getTreemapInlineValueIds(+ labelLayout: Record<string, TreemapLabelLayout>,+ parentLabelLayout: Record<string, ParentLabelLayout>,+): TreemapInlineValueIds {+ const fullLeafIds = new Set<string>();+ for (const [id, layout] of Object.entries(labelLayout)) {+ if (layout.detail === "full") {+ fullLeafIds.add(id);+ }+ }+ const valuePercentHeaderIds = new Set<string>();+ for (const [id, layout] of Object.entries(parentLabelLayout)) {+ if (layout.showValuePercent) {+ valuePercentHeaderIds.add(id);+ }+ }+ return { fullLeafIds, valuePercentHeaderIds };+}++export function isTreemapTooltipSuppressed(+ id: string,+ viewRootId: string | null,+ isTwoLevel: boolean,+ { fullLeafIds, valuePercentHeaderIds }: TreemapInlineValueIds,+): boolean {+ if (isGroupHeaderNode(id, viewRootId, isTwoLevel)) {+ return valuePercentHeaderIds.has(id);+ }+ return fullLeafIds.has(id);+}++export function getTreemapTooltipContext(+ tree: TreemapTree,+ id: string,+ viewRootId: string | null,+ groupingHeader?: string,+): TreemapTooltipContext | null {+ const { rootIndex, leafIndex } = parseTreemapNodeId(id);++ if (isOverview(viewRootId)) {+ const isHeader = leafIndex == null;+ if (isHeader) {+ const focusedNode = tree[rootIndex];+ if (focusedNode == null) {+ return null;+ }+ return { header: groupingHeader, siblings: tree, focusedNode };+ }++ const parent = tree[rootIndex];+ const siblings = getSiblings(tree, id);+ const focusedNode = siblings?.[leafIndex];+ if (parent == null || siblings == null || focusedNode == null) {+ return null;+ }+ return {+ header: parent.displayName,+ siblings,+ focusedNode,+ parentNode: parent,+ };+ }++ const root = tree[Number(viewRootId)];+ const siblings = getSiblings(tree, id);+ const focusedNode = siblings?.[leafIndex ?? -1];+ if (root == null || siblings == null || focusedNode == null) {+ return null;+ }++ return {+ header: root.displayName,+ siblings,+ focusedNode,+ parentNode: root,+ };+}++export function getTreemapTooltipModel(+ context: TreemapTooltipContext,+ getColor: (node: TreemapNode) => string | undefined,+ formatValue: (value: number) => string,+ formatPercent: (ratio: number) => string,+): EChartsTooltipModel {+ const { header, siblings, focusedNode } = context;+ const total = getTreemapTotal(siblings);++ const sortedSiblings = [...siblings].sort((a, b) => b.value - a.value);++ const rows: EChartsTooltipRow[] = sortedSiblings.map((node) => {+ const color = getColor(node);+ return {+ isFocused: node === focusedNode,+ markerColorClass: color != null ? getMarkerColorClass(color) : undefined,+ name: node.displayName,+ values: [+ formatValue(node.value),+ formatPercent(total === 0 ? 0 : node.value / total),+ ],+ };+ });++ return {+ header,+ rows,+ footer:+ siblings.length > 1+ ? { name: t`Total`, values: [formatValue(total), formatPercent(1)] }+ : undefined,+ };+}++export function isGroupHeaderNode(+ id: string,+ viewRootId: string | null,+ isTwoLevel: boolean,+): boolean {+ const { leafIndex } = parseTreemapNodeId(id);+ return isOverview(viewRootId) && isTwoLevel && leafIndex == null;+}++export function isPointerBelowGroupHeader(+ rect: TreemapRect,+ pointer: ChartPointer,+ headerHeight: number,+): boolean {+ return pointer.y > rect.y + headerHeight;+}diff --git a/frontend/src/metabase/visualizations/echarts/graph/treemap/model/tooltip.unit.spec.ts b/frontend/src/metabase/visualizations/echarts/graph/treemap/model/tooltip.unit.spec.tsnew file mode 100644index 00000000000..a6b9ebf0917--- /dev/null+++ b/frontend/src/metabase/visualizations/echarts/graph/treemap/model/tooltip.unit.spec.ts@@ -0,0 +1,154 @@+import {+ type TreemapInlineValueIds,+ getTreemapTooltipContext,+ isTreemapTooltipSuppressed,+} from "./tooltip";+import type { TreemapNode, TreemapTree } from "./types";++const leaf = (+ displayName: string,+ value: number,+ rowIndices: number[],+): TreemapNode => ({+ rawName: displayName,+ displayName,+ value,+ rowIndices,+});++const twoLevelTree: TreemapTree = [+ {+ rawName: "A",+ displayName: "Group A",+ value: 30,+ rowIndices: [0, 1],+ children: [leaf("Leaf A1", 20, [0]), leaf("Leaf A2", 10, [1])],+ },+ {+ rawName: "B",+ displayName: "Group B",+ value: 15,+ rowIndices: [2],+ children: [leaf("Leaf B1", 15, [2])],+ },+];++const singleLevelTree: TreemapTree = [+ leaf("Leaf X", 40, [0]),+ leaf("Leaf Y", 10, [1]),+];++describe("getTreemapTooltipContext", () => {+ it("shows the parent group's leaves when hovering a leaf at overview", () => {+ const context = getTreemapTooltipContext(+ twoLevelTree,+ "0-1",+ null,+ "Category",+ );++ expect(context).toEqual({+ header: "Group A",+ siblings: twoLevelTree[0].children,+ focusedNode: twoLevelTree[0].children?.[1],+ parentNode: twoLevelTree[0],+ });+ });++ it("shows all groups when hovering a group header at overview", () => {+ const context = getTreemapTooltipContext(+ twoLevelTree,+ "0",+ null,+ "Category",+ );++ expect(context).toEqual({+ header: "Category",+ siblings: twoLevelTree,+ focusedNode: twoLevelTree[0],+ });+ expect(context?.parentNode).toBeUndefined();+ });++ it("shows all root leaves when hovering a leaf in a single-level chart", () => {+ const context = getTreemapTooltipContext(+ singleLevelTree,+ "0",+ null,+ "Category",+ );++ expect(context).toEqual({+ header: "Category",+ siblings: singleLevelTree,+ focusedNode: singleLevelTree[0],+ });+ });++ it("shows the group's leaves when hovering a leaf in the drilled view", () => {+ const context = getTreemapTooltipContext(+ twoLevelTree,+ "0-0",+ "0",+ "Category",+ );++ expect(context).toEqual({+ header: "Group A",+ siblings: twoLevelTree[0].children,+ focusedNode: twoLevelTree[0].children?.[0],+ parentNode: twoLevelTree[0],+ });+ });+});++describe("isTreemapTooltipSuppressed", () => {+ const inlineIds = (+ fullLeafIds: string[],+ valuePercentHeaderIds: string[],+ ): TreemapInlineValueIds => ({+ fullLeafIds: new Set(fullLeafIds),+ valuePercentHeaderIds: new Set(valuePercentHeaderIds),+ });++ describe("two-level overview", () => {+ it("suppresses a leaf whose value is fully shown on the tile", () => {+ expect(+ isTreemapTooltipSuppressed("0-1", null, true, inlineIds(["0-1"], [])),+ ).toBe(true);+ });++ it("does not suppress a leaf without a fully shown value", () => {+ expect(+ isTreemapTooltipSuppressed("0-1", null, true, inlineIds([], [])),+ ).toBe(false);+ });++ it("suppresses a group header whose value+percent is shown", () => {+ expect(+ isTreemapTooltipSuppressed("0", null, true, inlineIds([], ["0"])),+ ).toBe(true);+ });++ it("does not suppress a group header without value+percent", () => {+ expect(+ isTreemapTooltipSuppressed("0", null, true, inlineIds([], [])),+ ).toBe(false);+ });+ });++ describe("single-level", () => {+ it("suppresses a root leaf whose value is fully shown", () => {+ expect(+ isTreemapTooltipSuppressed("0", null, false, inlineIds(["0"], [])),+ ).toBe(true);+ });++ it("does not suppress a root leaf without a fully shown value", () => {+ expect(+ isTreemapTooltipSuppressed("0", null, false, inlineIds([], [])),+ ).toBe(false);+ });+ });+});diff --git a/frontend/src/metabase/visualizations/echarts/graph/treemap/model/tree.ts b/frontend/src/metabase/visualizations/echarts/graph/treemap/model/tree.tsnew file mode 100644index 00000000000..34c3ae82ea1--- /dev/null+++ b/frontend/src/metabase/visualizations/echarts/graph/treemap/model/tree.ts@@ -0,0 +1,165 @@+import type { EChartsType } from "echarts/core";+import type { TreeNode } from "echarts/types/src/data/Tree";+import type GlobalModel from "echarts/types/src/model/Global";++import type {+ NodeId,+ TreemapLayoutNode,+ TreemapNode,+ TreemapRect,+ TreemapTree,+} from "./types";++// `TreeNode.getLayout()` is typed `any` by ECharts; narrow to the fields we read.+type TreeNodeLayout =+ | { x?: number; y?: number; width?: number; height?: number }+ | undefined;++/**+ * The treemap's laid-out tree (with per-node pixel layout) lives on the raw+ * series data (`.tree.root`). `getModel()` is declared `private` in ECharts'.+ */+function getTreemapRoot(chart: EChartsType): TreeNode | undefined {+ // @ts-expect-error -- getModel is private in ECharts' public types+ const globalModel: GlobalModel = chart.getModel();++ return globalModel?.getSeriesByIndex(0)?.getRawData()?.tree?.root;+}++/**+ * The rendered pixel rectangle of the tile with the given path-encoded id (the+ * ids set in `option.ts`: "0", "0-1"), or `null` if the node isn't laid out yet+ * or has no usable rect. Used to position the hover overlay over a whole+ * section (see `TreemapChart/events.ts`).+ */+export function getTreemapNodeRectById(+ chart: EChartsType,+ id: string,+): TreemapRect | null {+ const root = getTreemapRoot(chart);+ if (!root) {+ return null;+ }++ let rect: TreemapRect | null = null;+ root.eachNode((node) => {+ if (rect != null || node.getId() !== id) {+ return;+ }+ const layout: TreeNodeLayout = node.getLayout();+ if (+ layout?.width == null ||+ layout?.height == null ||+ layout.x == null ||+ layout.y == null+ ) {+ return;+ }+ rect = {+ x: layout.x,+ y: layout.y,+ width: layout.width,+ height: layout.height,+ };+ });+ return rect;+}++export function getNode(id: NodeId, tree: TreemapTree) {+ return getNodesFromPath(tree, id)?.at(-1);+}++const NODE_ID_SEP = "-";++export function getTreemapNodeId(+ rootIndex: number,+ leafIndex?: number,+): string {+ return leafIndex == null+ ? `${rootIndex}`+ : `${rootIndex}${NODE_ID_SEP}${leafIndex}`;+}++export function getTreemapRootNodeId(id: NodeId): NodeId {+ return id.split(NODE_ID_SEP)[0];+}++/** Whether the chart shows the top-level overview rather than a drilled-in group. */+export function isOverview(viewRootId: NodeId | null): boolean {+ return viewRootId == null;+}++export function parseTreemapNodeId(id: NodeId): {+ rootIndex: number;+ leafIndex?: number;+} {+ const [root, leaf] = id.split(NODE_ID_SEP);+ return {+ rootIndex: Number(root),+ leafIndex: leaf == null ? undefined : Number(leaf),+ };+}++export function hasChildren(+ node: TreemapNode,+): node is TreemapNode & { children: NonNullable<TreemapNode["children"]> } {+ return node.children != null;+}++/**+ * Pull the laid-out treemap tiles off an ECharts instance. Off-screen or+ * zero-area nodes (no usable layout) are skipped.+ */+export function getTreemapLayoutNodes(chart: EChartsType): TreemapLayoutNode[] {+ const root = getTreemapRoot(chart);++ if (!root) {+ return [];+ }++ const nodes: TreemapLayoutNode[] = [];+ root.eachNode((node) => {+ const layout: TreeNodeLayout = node.getLayout();+ if (!layout?.width || !layout?.height) {+ return;+ }+ nodes.push({+ id: node.getId(),+ rect: { width: layout.width, height: layout.height },+ isLeaf: node.children == null || node.children.length === 0,+ });+ });+ return nodes;+}++/**+ * `"0"` → `[tree[0]]`, `"0-1"` → `[tree[0], tree[0].children[1]]`+ */+export function getNodesFromPath(+ tree: TreemapTree,+ id: NodeId,+): TreemapNode[] | null {+ const path: TreemapNode[] = [];+ let nodes: TreemapTree | undefined = tree;+ for (const segment of id.split(NODE_ID_SEP)) {+ const index = Number(segment);+ const node: TreemapNode | undefined = Number.isInteger(index)+ ? nodes?.[index]+ : undefined;+ if (node == null) {+ return null;+ }+ path.push(node);+ nodes = node.children;+ }+ return path;+}++/** The nodes on the same level as `id` */+export function getSiblings(+ tree: TreemapTree,+ id: NodeId,+): TreemapTree | undefined {+ const { rootIndex, leafIndex } = parseTreemapNodeId(id);+ return leafIndex == null ? tree : tree[rootIndex]?.children;+}diff --git a/frontend/src/metabase/visualizations/echarts/graph/treemap/model/types.ts b/frontend/src/metabase/visualizations/echarts/graph/treemap/model/types.tsnew file mode 100644index 00000000000..09208abf759--- /dev/null+++ b/frontend/src/metabase/visualizations/echarts/graph/treemap/model/types.ts@@ -0,0 +1,60 @@+import type { ColumnDescriptor } from "metabase/visualizations/lib/graph/columns";+import type { RowValue } from "metabase-types/api";++export type NodeId = string;++export interface TreemapChartColumns {+ grouping: ColumnDescriptor;+ subGrouping?: ColumnDescriptor;+ value: ColumnDescriptor;+}++export interface TreemapNode {+ rawName: RowValue;+ displayName: string;+ value: number;+ rowIndices: number[];+ children?: TreemapNode[];+}++export interface TreemapSeriesNode {+ id: string;+ name: string;+ value: number;+ rawName: TreemapNode["rawName"];+ rowIndices: number[];+ itemStyle?: { color?: string; borderColor?: string };+ label?: {+ show?: boolean;+ width?: number;+ overflow?: "truncate" | "break";+ formatter?: string;+ };+ upperLabel?: {+ backgroundColor?: string;+ color?: string;+ formatter?: string;+ rich?: Record<string, Record<string, unknown>>;+ };+ children?: TreemapSeriesNode[];+}++export type TreemapTree = TreemapNode[];++export interface TreemapRect {+ x: number;+ y: number;+ width: number;+ height: number;+}++export interface ChartPointer {+ x: number;+ y: number;+}++export interface TreemapLayoutNode {+ id: string /* encodes path: ("0", "0-1") */;+ rect: { width: number; height: number };+ isLeaf: boolean;+}diff --git a/frontend/src/metabase/visualizations/echarts/graph/treemap/model/value.ts b/frontend/src/metabase/visualizations/echarts/graph/treemap/model/value.tsnew file mode 100644index 00000000000..c1d00a0fcf7--- /dev/null+++ b/frontend/src/metabase/visualizations/echarts/graph/treemap/model/value.ts@@ -0,0 +1,25 @@+import type { TreemapTree } from "./types";++export function getTreemapTotal(tree: TreemapTree) {+ return tree.reduce((sum, node) => sum + node.value, 0);+}++export function getLeafPercentLabel({+ isDrilled,+ value,+ parentValue,+ formatPercentOfTotal,+ formatPercent,+}: {+ isDrilled: boolean;+ value: number;+ parentValue?: number;+ formatPercentOfTotal: (value: number) => string;+ formatPercent: (ratio: number) => string;+}): string {+ if (!isDrilled || parentValue == null) {+ return formatPercentOfTotal(value);+ }++ return formatPercent(parentValue === 0 ? 0 : value / parentValue);+}diff --git a/frontend/src/metabase/visualizations/echarts/graph/treemap/option/option.ts b/frontend/src/metabase/visualizations/echarts/graph/treemap/option/option.tsnew file mode 100644index 00000000000..68779b5fc41--- /dev/null+++ b/frontend/src/metabase/visualizations/echarts/graph/treemap/option/option.ts@@ -0,0 +1,497 @@+import type { TreemapSeriesOption } from "echarts/charts";+import { match } from "ts-pattern";++import { formatPercent as formatPercentDefault } from "metabase/static-viz/lib/numbers";+import { getTextColorForBackground } from "metabase/ui/colors";+import { truncateText } from "metabase/visualizations/lib/text";+import type { RenderingContext } from "metabase/visualizations/types";++import { getTreemapColors, getTreemapLeafColor } from "../model/colors";+import { getTreemapNodeKey } from "../model/data";+import { getTreemapPercentOfTotalFormatter } from "../model/formatters";+import type { ParentLabelLayout, TreemapLabelLayout } from "../model/labels";+import type { TreemapMeasuredLabelLayouts } from "../model/measure";+import { getTreemapNodeId, hasChildren } from "../model/tree";+import type {+ TreemapNode,+ TreemapSeriesNode,+ TreemapTree,+} from "../model/types";+import { getLeafPercentLabel } from "../model/value";+import {+ TREEMAP_CHART_STYLE,+ getGroupHeaderBgTint,+ groupHeader,+ leafBlock,+} from "../style";+import {+ getLeafFormatter,+ getLeafLabelStyle,+ getRichLeafLabel,+ getRichUpperLabel,+ sanitizeRichTextContent,+} from "../style.rich";++type TreemapChartSeriesOption = TreemapSeriesOption & {+ type: "treemap";+ data: TreemapSeriesNode[];+};++export type TreemapChartOptionConfig = {+ tree: TreemapTree;+ colors?: Record<string, string>;+ isDrilled?: boolean;+ formatValue?: (value: number) => string;+ formatPercent?: (ratio: number) => string;+ showLeafLabels?: boolean;+ showParentLabels?: boolean;+ isCompact?: boolean;+ labelLayout?: Record<string, TreemapLabelLayout>;+ parentLabelLayout?: Record<string, ParentLabelLayout>;+ renderingContext: RenderingContext;+};++type TreemapSeriesBuildConfig = {+ colors: Record<string, string>;+ isDrilled: boolean;+ showLeafLabels: boolean;+ labelLayout: Record<string, TreemapLabelLayout>;+ parentLabelLayout: Record<string, ParentLabelLayout>;+ formatValue: (value: number) => string;+ formatPercent: (ratio: number) => string;+ formatPercentOfTotal: (value: number) => string;+ headerTintTarget: string;+ renderingContext: RenderingContext;+};++const HIDDEN_LABEL_OVERRIDE: Pick<TreemapSeriesNode, "label"> = {+ label: { show: false },+};++const MIN_TILE_SIZE = 25 * 25;++export function getTreemapChartOption(config: TreemapChartOptionConfig): {+ series: TreemapChartSeriesOption;+} {+ const {+ tree,+ showParentLabels = true,+ isCompact = false,+ renderingContext,+ } = config;+ const buildConfig = createSeriesBuildConfig(config);+ const hasNestedChildren = tree.some(hasChildren);++ const groupUpperLabel = getUpperLabelDefault({+ showParentLabels,+ isDrilled: buildConfig.isDrilled,+ isCompact,+ renderingContext,+ });++ const rootLevel: NonNullable<TreemapSeriesOption["levels"]>[number] = {+ itemStyle: { borderWidth: 0, gapWidth: 2, borderColor: "transparent" },+ upperLabel: { show: false },+ };++ const groupLevel: NonNullable<TreemapSeriesOption["levels"]>[number] = {+ itemStyle: { borderWidth: 0, gapWidth: 1 },+ upperLabel: groupUpperLabel,+ // no label by default for groups; this is overridden on per-group basis+ label: { show: false },+ };++ const series: TreemapChartSeriesOption = {+ type: "treemap",+ nodeClick: false,+ roam: false,+ emphasis: { disabled: true }, // We're adding custom hover effect to be able to highlight the whole group.+ breadcrumb: { show: false },+ label: getTileLabelDefault({+ showLeafLabels: buildConfig.showLeafLabels,+ renderingContext,+ }),+ upperLabel: { show: false },+ top: 0,+ left: 0,+ right: 0,+ bottom: 0,+ leafDepth: 2,+ visibleMin: MIN_TILE_SIZE,+ childrenVisibleMin: MIN_TILE_SIZE,+ levels: hasNestedChildren ? [rootLevel, groupLevel] : [rootLevel],+ data: toSeriesData({ tree, config: buildConfig }),+ };++ return { series };+}++function createSeriesBuildConfig({+ tree,+ colors = getTreemapColors(tree),+ isDrilled = false,+ showLeafLabels = true,+ labelLayout = {},+ parentLabelLayout = {},+ formatValue = (value: number) => String(value),+ formatPercent = formatPercentDefault,+ renderingContext,+}: TreemapChartOptionConfig): TreemapSeriesBuildConfig {+ return {+ colors,+ isDrilled,+ showLeafLabels,+ labelLayout,+ parentLabelLayout,+ formatValue,+ formatPercent,+ formatPercentOfTotal: getTreemapPercentOfTotalFormatter(+ tree,+ formatPercent,+ ),+ headerTintTarget: renderingContext.getColor("white"),+ renderingContext,+ };+}++function toSeriesData({+ tree,+ config,+}: {+ tree: TreemapTree;+ config: TreemapSeriesBuildConfig;+}): TreemapSeriesNode[] {+ return tree.map((node, rootIndex) =>+ toGroupSeriesNode({ config, node, rootIndex }),+ );+}++function toGroupSeriesNode({+ config,+ node,+ rootIndex,+}: {+ config: TreemapSeriesBuildConfig;+ node: TreemapNode;+ rootIndex: number;+}): TreemapSeriesNode {+ const {+ colors,+ headerTintTarget,+ isDrilled,+ parentLabelLayout,+ formatValue,+ formatPercentOfTotal,+ renderingContext,+ } = config;+ const groupColor = colors[getTreemapNodeKey(node)];+ const groupTint = getGroupHeaderBgTint(groupColor, headerTintTarget);+ const groupId = getTreemapNodeId(rootIndex);+ const nodeHasChildren = hasChildren(node);+ const valueLabel = formatValue(node.value);+ const percentLabel = formatPercentOfTotal(node.value);++ const upperLabel = getUpperLabelOverride({+ groupTint,+ hasChildren: nodeHasChildren,+ layout: parentLabelLayout[groupId],+ displayName: node.displayName,+ valueLabel,+ percentLabel,+ renderingContext,+ });++ const itemStyle = getItemStyle({+ groupColor,+ groupTint,+ hasChildren: nodeHasChildren,+ isDrilled,+ });++ const groupNode: TreemapSeriesNode = {+ id: groupId,+ name: node.displayName,+ value: node.value,+ rawName: node.rawName,+ rowIndices: node.rowIndices,+ itemStyle,+ upperLabel,+ };++ if (!nodeHasChildren) {+ return {+ ...groupNode,+ ...getTileLabelOverride({+ config,+ id: groupId,+ value: node.value,+ displayName: node.displayName,+ backgroundColor: groupColor,+ }),+ };+ }++ const childValues = node.children.map((child) => child.value);+ const minChildValue = Math.min(...childValues);+ const maxChildValue = Math.max(...childValues);++ return {+ ...groupNode,+ children: node.children.map((leaf, leafIndex) =>+ toLeafSeriesNode({+ config,+ leaf,+ parentValue: node.value,+ rootIndex,+ leafIndex,+ color: getTreemapLeafColor(+ groupColor,+ leaf.value,+ minChildValue,+ maxChildValue,+ ),+ }),+ ),+ };+}++function toLeafSeriesNode({+ config,+ leaf,+ parentValue,+ rootIndex,+ leafIndex,+ color,+}: {+ config: TreemapSeriesBuildConfig;+ leaf: TreemapNode;+ parentValue: number;+ rootIndex: number;+ leafIndex: number;+ color: string | undefined;+}): TreemapSeriesNode {+ const leafId = getTreemapNodeId(rootIndex, leafIndex);++ return {+ id: leafId,+ name: leaf.displayName,+ value: leaf.value,+ rawName: leaf.rawName,+ rowIndices: leaf.rowIndices,+ itemStyle: { color },+ ...getTileLabelOverride({+ config,+ id: leafId,+ value: leaf.value,+ displayName: leaf.displayName,+ parentValue,+ backgroundColor: color,+ }),+ };+}++function getItemStyle({+ groupColor,+ groupTint,+ hasChildren,+ isDrilled,+}: {+ groupColor: string | undefined;+ groupTint: string | undefined;+ hasChildren: boolean;+ isDrilled: boolean;+}) {+ return {+ color: groupColor,+ ...(hasChildren+ ? { borderColor: isDrilled ? "transparent" : groupTint }+ : {}),+ };+}++function getTileLabelDefault({+ showLeafLabels,+ renderingContext,+}: {+ showLeafLabels: boolean;+ renderingContext: RenderingContext;+}): NonNullable<TreemapChartSeriesOption["label"]> {+ return {+ ...TREEMAP_CHART_STYLE.nodeLabels,+ fontFamily: renderingContext.fontFamily,+ show: showLeafLabels,+ overflow: "break",+ lineOverflow: "truncate",+ rich: getRichLeafLabel(renderingContext),+ };+}++function getTileLabelOverride({+ config,+ id,+ value,+ displayName,+ parentValue,+ backgroundColor,+}: {+ config: TreemapSeriesBuildConfig;+ id: string;+ value: number;+ displayName: string;+ parentValue?: number;+ backgroundColor: string | undefined;+}): Pick<TreemapSeriesNode, "label"> {+ const {+ showLeafLabels,+ isDrilled,+ labelLayout,+ formatValue,+ formatPercent,+ formatPercentOfTotal,+ renderingContext,+ } = config;+ if (!showLeafLabels) {+ return HIDDEN_LABEL_OVERRIDE;+ }+ const layout = labelLayout[id];+ if (layout == null) {+ return HIDDEN_LABEL_OVERRIDE;+ }+ const textColor = backgroundColor+ ? getTextColorForBackground(backgroundColor, renderingContext.getColor)+ : undefined;+ const leafLabelStyle = getLeafLabelStyle(renderingContext, textColor);+ // ECharts truncation is unreliable, so we use our own truncation logic+ const leafName = truncateText(+ displayName,+ layout.width,+ renderingContext.measureText,+ {+ size: leafBlock.name.fontSize,+ family: renderingContext.fontFamily,+ weight: leafBlock.name.fontWeight,+ },+ );++ return match(layout.detail)+ .with("none", () => HIDDEN_LABEL_OVERRIDE)+ .with("full", () => ({+ label: {+ show: true,+ width: layout.width,+ overflow: "truncate" as const,+ ...leafLabelStyle,+ formatter: getLeafFormatter(+ leafName,+ formatValue(value),+ getLeafPercentLabel({+ isDrilled,+ value,+ parentValue,+ formatPercentOfTotal,+ formatPercent,+ }),+ ),+ },+ }))+ .otherwise(() => ({+ label: {+ show: true,+ width: layout.width,+ overflow: "truncate" as const,+ ...leafLabelStyle,+ formatter: sanitizeRichTextContent(leafName),+ },+ }));+}++function getUpperLabelDefault({+ showParentLabels,+ isDrilled,+ isCompact,+ renderingContext,+}: {+ showParentLabels: boolean;+ isDrilled: boolean;+ isCompact: boolean;+ renderingContext: RenderingContext;+}): NonNullable<TreemapChartSeriesOption["upperLabel"]> {+ const height = isCompact ? groupHeader.compactHeight : groupHeader.height;+ return {+ show: showParentLabels && !isDrilled,+ color: renderingContext.getColor("text-primary"),+ height,+ fontFamily: renderingContext.fontFamily,+ fontSize: groupHeader.fontSize,+ fontWeight: groupHeader.fontWeight,+ lineHeight: height,+ padding: [0, groupHeader.paddingX],+ overflow: "truncate",+ };+}++function getUpperLabelOverride({+ groupTint,+ hasChildren,+ layout,+ displayName,+ valueLabel,+ percentLabel,+ renderingContext,+}: {+ groupTint: string | undefined;+ hasChildren: boolean;+ layout: ParentLabelLayout | undefined;+ displayName: string;+ valueLabel: string;+ percentLabel: string;+ renderingContext: RenderingContext;+}): TreemapSeriesNode["upperLabel"] {+ if (+ hasChildren &&+ layout?.showValuePercent &&+ layout.nameColumnWidth != null+ ) {+ return getRichUpperLabel({+ groupTint,+ displayName,+ valueLabel,+ percentLabel,+ nameColumnWidth: layout.nameColumnWidth,+ renderingContext,+ });+ }++ const color =+ hasChildren && layout?.showText === false ? "transparent" : undefined;++ const basicLabel = {+ backgroundColor: groupTint,+ color,+ };++ if (Object.values(basicLabel).every((value) => value === undefined)) {+ return undefined;+ }++ return basicLabel;+}++export function getStaticTreemapOption(+ config: TreemapChartOptionConfig,+ layouts?: Partial<TreemapMeasuredLabelLayouts>,+): {+ series: TreemapChartSeriesOption;+ animation: boolean;+} {+ const option = getTreemapChartOption({+ ...config,+ labelLayout: layouts?.leafLabelLayout,+ parentLabelLayout: layouts?.parentLabelLayout,+ });++ return {+ ...option,+ animation: false,+ };+}diff --git a/frontend/src/metabase/visualizations/echarts/graph/treemap/option/option.unit.spec.ts b/frontend/src/metabase/visualizations/echarts/graph/treemap/option/option.unit.spec.tsnew file mode 100644index 00000000000..a4311d19894--- /dev/null+++ b/frontend/src/metabase/visualizations/echarts/graph/treemap/option/option.unit.spec.ts@@ -0,0 +1,212 @@+import { formatPercent } from "metabase/static-viz/lib/numbers";+import { DEFAULT_VISUALIZATION_THEME } from "metabase/visualizations/shared/utils/theme";+import type { RenderingContext } from "metabase/visualizations/types";++import type { TreemapTree } from "../model/types";++import { getTreemapChartOption } from "./option";++// getTextColorForBackground parses these through the `color` library, so they+// must be real, parseable colors rather than the bare key.+const MOCK_COLORS: Record<string, string> = {+ "text-primary": "#4c5773",+ "text-primary-inverse": "#ffffff",+ "text-secondary": "#949aab",+ white: "#ffffff",+};++const renderingContext: RenderingContext = {+ getColor: (name) => MOCK_COLORS[name] ?? name,+ measureText: () => 0,+ measureTextHeight: () => 0,+ fontFamily: "",+ theme: DEFAULT_VISUALIZATION_THEME,+};++const TWO_LEVEL_TREE: TreemapTree = [+ {+ rawName: "Legumes",+ displayName: "Legumes",+ value: 30,+ rowIndices: [0, 1],+ children: [+ {+ rawName: "Chickpeas",+ displayName: "Chickpeas",+ value: 20,+ rowIndices: [0],+ },+ {+ rawName: "Lentils",+ displayName: "Lentils",+ value: 10,+ rowIndices: [1],+ },+ ],+ },+];++describe("getTreemapChartOption", () => {+ it("assigns path-based ids so interactions can resolve hovered nodes", () => {+ const { series } = getTreemapChartOption({+ tree: TWO_LEVEL_TREE,+ renderingContext,+ });++ expect(series.data[0].id).toBe("0");+ expect(series.data[0].children?.[0].id).toBe("0-0");+ expect(series.data[0].children?.[1].id).toBe("0-1");+ });++ it("applies tile label override branches: missing, none, labelOnly, and full", () => {+ const tree: TreemapTree = [+ {+ rawName: "Group",+ displayName: "Group",+ value: 100,+ rowIndices: [0, 1, 2, 3],+ children: [+ { rawName: "A", displayName: "A", value: 50, rowIndices: [0] }, // missing layout => hidden+ { rawName: "B", displayName: "B", value: 30, rowIndices: [1] }, // none+ { rawName: "C", displayName: "C", value: 15, rowIndices: [2] }, // labelOnly+ { rawName: "D", displayName: "D", value: 5, rowIndices: [3] }, // full+ ],+ },+ ];++ const { series } = getTreemapChartOption({+ tree,+ formatValue: (value) => `$${value}`,+ labelLayout: {+ "0-1": { detail: "none", width: 40 },+ "0-2": { detail: "labelOnly", width: 80 },+ "0-3": { detail: "full", width: 120 },+ },+ renderingContext,+ });++ const [a, b, c, d] = series.data[0].children ?? [];+ expect(a.label).toEqual({ show: false });+ expect(b.label).toEqual({ show: false });+ expect(c.label).toMatchObject({+ show: true,+ width: 80,+ overflow: "truncate",+ formatter: "C",+ color: expect.any(String),+ });+ expect(d.label).toMatchObject({+ show: true,+ width: 120,+ overflow: "truncate",+ formatter: `{name|D}\n{value|$5}\n{pct|${formatPercent(0.05)}}`,+ color: expect.any(String),+ });+ });++ it("uses the drilled group total for full leaf label percentages", () => {+ const tree: TreemapTree = [+ {+ rawName: "Group",+ displayName: "Group",+ value: 100,+ rowIndices: [0, 1, 2, 3],+ children: [+ { rawName: "A", displayName: "A", value: 60, rowIndices: [0] },+ { rawName: "B", displayName: "B", value: 40, rowIndices: [1] },+ ],+ },+ { rawName: "Other", displayName: "Other", value: 300, rowIndices: [4] },+ ];++ const { series } = getTreemapChartOption({+ tree,+ isDrilled: true,+ formatValue: (value) => `$${value}`,+ labelLayout: {+ "0-0": { detail: "full", width: 120 },+ },+ renderingContext,+ });++ expect(series.data[0].children?.[0].label).toMatchObject({+ show: true,+ width: 120,+ overflow: "truncate",+ formatter: `{name|A}\n{value|$60}\n{pct|${formatPercent(0.6)}}`,+ color: expect.any(String),+ });+ });++ it("applies upper label defaults and per-group overrides", () => {+ const overview = getTreemapChartOption({+ tree: TWO_LEVEL_TREE,+ renderingContext,+ });+ const drilled = getTreemapChartOption({+ tree: TWO_LEVEL_TREE,+ isDrilled: true,+ renderingContext,+ });+ const rich = getTreemapChartOption({+ tree: TWO_LEVEL_TREE,+ formatValue: (value) => `$${value}`,+ parentLabelLayout: {+ "0": { showText: true, showValuePercent: true, nameColumnWidth: 90 },+ },+ renderingContext,+ });+ const hiddenText = getTreemapChartOption({+ tree: TWO_LEVEL_TREE,+ parentLabelLayout: {+ "0": { showText: false, showValuePercent: false },+ },+ renderingContext,+ });++ expect(overview.series.levels?.[1]?.upperLabel).toMatchObject({+ show: true,+ });+ expect(drilled.series.levels?.[1]?.upperLabel).toMatchObject({+ show: false,+ });++ expect(rich.series.data[0].upperLabel?.formatter).toBe(+ `{name|Legumes}{value|$30}{pct|${formatPercent(1)}}`,+ );+ expect(rich.series.data[0].upperLabel?.rich).toMatchObject({+ name: { width: 90, overflow: "truncate" },+ });++ expect(hiddenText.series.data[0].upperLabel).toMatchObject({+ color: "transparent",+ backgroundColor: expect.any(String),+ });+ });++ it("hides series and per-tile labels when showLeafLabels is false", () => {+ const twoLevel = getTreemapChartOption({+ tree: TWO_LEVEL_TREE,+ showLeafLabels: false,+ renderingContext,+ });+ const oneLevel = getTreemapChartOption({+ tree: [+ { rawName: "A", displayName: "A", value: 10, rowIndices: [0] },+ { rawName: "B", displayName: "B", value: 25, rowIndices: [1] },+ ],+ showLeafLabels: false,+ renderingContext,+ });++ expect(twoLevel.series.label).toMatchObject({ show: false });+ twoLevel.series.data.forEach((group) => {+ group.children?.forEach((leaf) => {+ expect(leaf.label).toMatchObject({ show: false });+ });+ });+ oneLevel.series.data.forEach((tile) => {+ expect(tile.label).toMatchObject({ show: false });+ });+ });+});diff --git a/frontend/src/metabase/visualizations/echarts/graph/treemap/style.rich.ts b/frontend/src/metabase/visualizations/echarts/graph/treemap/style.rich.tsnew file mode 100644index 00000000000..ec39eff855a--- /dev/null+++ b/frontend/src/metabase/visualizations/echarts/graph/treemap/style.rich.ts@@ -0,0 +1,124 @@+import type { RenderingContext } from "metabase/visualizations/types";++import { PARENT_HEADER_VALUE_PERCENT_GAP } from "./model/labels";+import { groupHeader, leafBlock } from "./style";++export function getLeafLabelStyle(+ renderingContext: RenderingContext,+ textColor?: string,+) {+ const color = textColor ?? renderingContext.getColor("white");+ return {+ color,+ rich: getRichLeafLabel(renderingContext, textColor),+ };+}++export function getRichLeafLabel(+ renderingContext: RenderingContext,+ textColor?: string,+) {+ const color = textColor ?? renderingContext.getColor("white");+ const base = {+ fontFamily: renderingContext.fontFamily,+ color,+ };++ return {+ name: {+ ...base,+ fontSize: leafBlock.name.fontSize,+ fontWeight: leafBlock.name.fontWeight,+ height: leafBlock.name.height,+ verticalAlign: "middle" as const,+ },+ value: {+ ...base,+ fontSize: leafBlock.value.fontSize,+ fontWeight: leafBlock.value.fontWeight,+ padding: [leafBlock.valueGap, 0, 0, 0],+ height: leafBlock.value.height,+ verticalAlign: "middle" as const,+ },+ pct: {+ ...base,+ fontSize: leafBlock.percent.fontSize,+ fontWeight: leafBlock.percent.fontWeight,+ height: leafBlock.percent.height,+ lineHeight: leafBlock.percent.height,+ padding: [leafBlock.percentGap, 0, 0, 0],+ verticalAlign: "middle" as const,+ },+ };+}++export function getRichUpperLabel({+ groupTint,+ displayName,+ valueLabel,+ percentLabel,+ nameColumnWidth,+ renderingContext,+}: {+ groupTint: string | undefined;+ displayName: string;+ valueLabel: string;+ percentLabel: string;+ nameColumnWidth: number;+ renderingContext: RenderingContext;+}) {+ const textPrimary = renderingContext.getColor("text-primary");+ const textSecondary = renderingContext.getColor("text-secondary");+ const fontFamily = renderingContext.fontFamily;++ return {+ backgroundColor: groupTint,+ formatter: getHeaderFormatter(displayName, valueLabel, percentLabel),+ rich: {+ name: {+ fontFamily,+ width: nameColumnWidth,+ overflow: "truncate",+ align: "left",+ color: textPrimary,+ fontSize: groupHeader.fontSize,+ fontWeight: groupHeader.fontWeight,+ },+ value: {+ fontFamily,+ color: textPrimary,+ fontSize: groupHeader.fontSize,+ fontWeight: groupHeader.fontWeight,+ padding: [0, 0, 0, PARENT_HEADER_VALUE_PERCENT_GAP],+ },+ pct: {+ fontFamily,+ color: textSecondary,+ fontSize: groupHeader.fontSize,+ fontWeight: groupHeader.percentFontWeight,+ padding: [0, 0, 0, groupHeader.valuePercentGap],+ },+ },+ };+}++function getHeaderFormatter(+ displayName: string,+ valueLabel: string,+ percentLabel: string,+) {+ return `{name|${sanitizeRichTextContent(displayName)}}{value|${sanitizeRichTextContent(valueLabel)}}{pct|${sanitizeRichTextContent(percentLabel)}}`;+}++export function getLeafFormatter(+ name: string,+ valueLabel: string,+ percentLabel: string,+): string {+ return `{name|${sanitizeRichTextContent(name)}}\n{value|${sanitizeRichTextContent(valueLabel)}}\n{pct|${sanitizeRichTextContent(percentLabel)}}`;+}++// characters {}| are part of the echarts rich template syntax+export function sanitizeRichTextContent(text: string): string {+ return text.replace(/[{}|]/g, "");+}diff --git a/frontend/src/metabase/visualizations/echarts/graph/treemap/style.rich.unit.spec.ts b/frontend/src/metabase/visualizations/echarts/graph/treemap/style.rich.unit.spec.tsnew file mode 100644index 00000000000..7867fb8f82c--- /dev/null+++ b/frontend/src/metabase/visualizations/echarts/graph/treemap/style.rich.unit.spec.ts@@ -0,0 +1,11 @@+import { sanitizeRichTextContent } from "./style.rich";++describe("sanitizeRichTextContent", () => {+ it("removes rich-text control characters", () => {+ expect(sanitizeRichTextContent("a{b|c}")).toBe("abc");+ expect(sanitizeRichTextContent("Europe}}")).toBe("Europe");+ expect(sanitizeRichTextContent(String.raw`back\slash`)).toBe(+ String.raw`back\slash`,+ );+ });+});diff --git a/frontend/src/metabase/visualizations/echarts/graph/treemap/style.ts b/frontend/src/metabase/visualizations/echarts/graph/treemap/style.tsnew file mode 100644index 00000000000..02f14f04b90--- /dev/null+++ b/frontend/src/metabase/visualizations/echarts/graph/treemap/style.ts@@ -0,0 +1,57 @@+import Color from "color";++export const LABEL_PADDING = 12;++export const TREEMAP_CHART_STYLE = {+ nodeLabels: {+ fontWeight: 700,+ size: 12,+ position: [LABEL_PADDING, LABEL_PADDING],+ fontFamily: "Lato, sans-serif",+ },+};++export const groupHeader = {+ fontWeight: 700,+ fontSize: 12,+ height: 32,+ compactHeight: 24,+ paddingX: 12,+ percentFontWeight: 400,+ valuePercentGap: 8,+} as const;++export const leafBlock = {+ name: { fontSize: 12, fontWeight: 700, height: 16 },+ value: { fontSize: 20, fontWeight: 700, height: 24 },+ percent: { fontSize: 12, fontWeight: 400, height: 16 },+ valueGap: 16,+ percentGap: 8,+} as const;++export const GROUP_HEADER_BG_TINT = 0.4;++export function getGroupHeaderBgTint(+ groupColor: string | undefined,+ headerTintTarget: string,+) {+ if (!groupColor) {+ return undefined;+ }++ return Color(groupColor)+ .mix(Color(headerTintTarget), 1 - GROUP_HEADER_BG_TINT)+ .string();+}++export function getChartPadding(isDashboard: boolean) {+ const side = isDashboard ? "1rem" : "2rem";+ return `0 ${side} ${side} ${side}`;+}++export const TREEMAP_HOVER_OVERLAY_FILL = Color("black")+ .alpha(0.1)+ .rgb()+ .string();++export const HOVER_OVERLAY_Z = 100;diff --git a/frontend/src/metabase/visualizations/echarts/index.ts b/frontend/src/metabase/visualizations/echarts/index.tsindex db91992f648..00bb494d446 100644--- a/frontend/src/metabase/visualizations/echarts/index.ts+++ b/frontend/src/metabase/visualizations/echarts/index.ts@@ -6,6 +6,7 @@ import {SankeyChart,ScatterChart,SunburstChart,+ TreemapChart,} from "echarts/charts";import {BrushComponent,@@ -40,6 +41,7 @@ export const registerEChartsModules = () => {BrushComponent,DatasetComponent,SankeyChart,+ TreemapChart,LabelLayout,TooltipComponent,]);diff --git a/frontend/src/metabase/visualizations/lib/sensibility.ts b/frontend/src/metabase/visualizations/lib/sensibility.tsindex 274a1a6f302..b9ffe2d951f 100644--- a/frontend/src/metabase/visualizations/lib/sensibility.ts+++ b/frontend/src/metabase/visualizations/lib/sensibility.ts@@ -163,6 +163,10 @@ function getRecommendedVisualizations(// the sankey sensibility check is quite robust, so we recommend it whenever it's sensiblerecommended.push("sankey");}+ if (sensible.includes("treemap") && nonLatLongDimensionCount >= 2) {+ // treemap best with two-level grouping+ recommended.push("treemap");+ }return recommended;}diff --git a/frontend/src/metabase/visualizations/lib/utils.ts b/frontend/src/metabase/visualizations/lib/utils.tsindex d24f3ee9366..810a617544c 100644--- a/frontend/src/metabase/visualizations/lib/utils.ts+++ b/frontend/src/metabase/visualizations/lib/utils.ts@@ -33,7 +33,7 @@ const SPLIT_AXIS_MAX_DEPTH = 8;// NOTE Atte Keinänen 8/3/17: Moved from settings.js because this way we// are able to avoid circular dependency errors in e2e testsexport function columnsAreValid(- colNames: (string | undefined)[] | undefined,+ colNames: (string | null | undefined)[] | undefined,data: DatasetData,filter: (column: DatasetColumn) => boolean = () => true,): boolean {diff --git a/frontend/src/metabase/visualizations/register.js b/frontend/src/metabase/visualizations/register.jsindex e7077054985..1fac677d618 100644--- a/frontend/src/metabase/visualizations/register.js+++ b/frontend/src/metabase/visualizations/register.js@@ -22,6 +22,7 @@ import { Scalar } from "./visualizations/Scalar";import { ScatterPlot } from "./visualizations/ScatterPlot";import { SmartScalar } from "./visualizations/SmartScalar";import { Table } from "./visualizations/Table/Table";+import { TreemapChart } from "./visualizations/TreemapChart";import { WaterfallChart } from "./visualizations/WaterfallChart";// eslint-disable-next-line import/no-default-export -- deprecated usage@@ -45,6 +46,7 @@ export default function () {registerVisualization(ObjectDetail);registerVisualization(PivotTable);registerVisualization(SankeyChart);+ registerVisualization(TreemapChart);registerVisualization(ListViz);diff --git a/frontend/src/metabase/visualizations/shared/settings/treemap.ts b/frontend/src/metabase/visualizations/shared/settings/treemap.tsnew file mode 100644index 00000000000..f59a2a95df3--- /dev/null+++ b/frontend/src/metabase/visualizations/shared/settings/treemap.ts@@ -0,0 +1,166 @@+import { getColorsForValues } from "metabase/ui/colors/charts";+import { NULL_DISPLAY_VALUE } from "metabase/utils/constants";+import { getTreemapChartColumns } from "metabase/visualizations/echarts/graph/treemap/model/data";+import { getNumberOr } from "metabase/visualizations/lib/settings/row-values";+import type {+ ComputedVisualizationSettings,+ Formatter,+} from "metabase/visualizations/types";+import type { RawSeries, RowValue, TreemapRow } from "metabase-types/api";++import { getKeyFromDimensionValue } from "./pie";++type AggregatedTreemapValues = {+ rawValueByKey: Map<string, RowValue>;+ currentKeys: string[];+};++type NameFormatter = (rawValue: RowValue) => string;++export function getTreemapRows(+ rawSeries: RawSeries,+ settings: ComputedVisualizationSettings,+ formatter: Formatter,+): TreemapRow[] {+ const [+ {+ data: { rows, cols },+ },+ ] = rawSeries;++ const treemapColumns = getTreemapChartColumns(cols, settings);+ if (treemapColumns == null) {+ return [];+ }++ const { grouping, value } = treemapColumns;+ const { rawValueByKey, currentKeys } = aggregateRowsByKey({+ rows,+ groupingIndex: grouping.index,+ valueIndex: value.index,+ });+ const colors = getColorsForValues(currentKeys);+ const groupingColumnSettings = settings["column"]?.(grouping.column);+ const formatName = createNameFormatter({+ groupingColumnSettings,+ formatter,+ });++ const savedRows = settings["treemap.rows"] ?? [];+ const savedRowByKey = new Map(savedRows.map((row) => [row.key, row]));+ const newRows = buildCurrentRows({+ currentKeys,+ savedRowByKey,+ rawValueByKey,+ colors,+ formatName,+ });++ addHiddenSavedRows({ rows: newRows, savedRows, currentKeys });++ return newRows;+}++function aggregateRowsByKey({+ rows,+ groupingIndex,+ valueIndex,+}: {+ rows: RowValue[][];+ groupingIndex: number;+ valueIndex: number;+}): AggregatedTreemapValues {+ const valueByKey = new Map<string, number>();+ const rawValueByKey = new Map<string, RowValue>();++ rows.forEach((row) => {+ const rawValue = row[groupingIndex];+ const key = getKeyFromDimensionValue(rawValue);+ const metricValue = getNumberOr(row[valueIndex], 0);+ const newValue = (valueByKey.get(key) ?? 0) + metricValue;+ valueByKey.set(key, newValue);+ if (!rawValueByKey.has(key)) {+ rawValueByKey.set(key, rawValue);+ }+ });++ const currentKeys = Array.from(valueByKey.keys()).sort(+ (keyA, keyB) => (valueByKey.get(keyB) ?? 0) - (valueByKey.get(keyA) ?? 0),+ );++ return { rawValueByKey, currentKeys };+}++function createNameFormatter({+ groupingColumnSettings,+ formatter,+}: {+ groupingColumnSettings:+ | ReturnType<NonNullable<ComputedVisualizationSettings["column"]>>+ | undefined;+ formatter: Formatter;+}): NameFormatter {+ return (rawValue: RowValue) => {+ if (rawValue == null) {+ return NULL_DISPLAY_VALUE;+ }+ return formatter(rawValue, groupingColumnSettings) ?? NULL_DISPLAY_VALUE;+ };+}++function buildCurrentRows({+ currentKeys,+ savedRowByKey,+ rawValueByKey,+ colors,+ formatName,+}: {+ currentKeys: string[];+ savedRowByKey: Map<string, TreemapRow>;+ rawValueByKey: Map<string, RowValue>;+ colors: ReturnType<typeof getColorsForValues>;+ formatName: (rawValue: RowValue) => string;+}): TreemapRow[] {+ return currentKeys.map((key) => {+ const savedRow = savedRowByKey.get(key);+ if (savedRow != null) {+ return {+ ...savedRow,+ enabled: savedRow.enabled !== false,+ hidden: false,+ ...(savedRow.defaultColor ? { color: colors[key] } : {}),+ };+ }+ const name = formatName(rawValueByKey.get(key) ?? null);+ return {+ key,+ name,+ originalName: name,+ color: colors[key],+ defaultColor: true,+ enabled: true,+ hidden: false,+ };+ });+}++function addHiddenSavedRows({+ rows,+ savedRows,+ currentKeys,+}: {+ rows: TreemapRow[];+ savedRows: TreemapRow[];+ currentKeys: string[];+}) {+ const currentKeySet = new Set(currentKeys);+ savedRows.forEach((savedRow) => {+ if (!currentKeySet.has(savedRow.key)) {+ rows.push({+ ...savedRow,+ enabled: savedRow.enabled !== false,+ hidden: true,+ });+ }+ });+}diff --git a/frontend/src/metabase/visualizations/shared/settings/treemap.unit.spec.ts b/frontend/src/metabase/visualizations/shared/settings/treemap.unit.spec.tsnew file mode 100644index 00000000000..a050e350da5--- /dev/null+++ b/frontend/src/metabase/visualizations/shared/settings/treemap.unit.spec.ts@@ -0,0 +1,69 @@+import type { ComputedVisualizationSettings } from "metabase/visualizations/types";+import type { RawSeries, RowValue, TreemapRow } from "metabase-types/api";+import { createMockCard } from "metabase-types/api/mocks/card";+import {+ createMockColumn,+ createMockDatasetData,+} from "metabase-types/api/mocks/dataset";++import { getTreemapRows } from "./treemap";++const columns = [+ createMockColumn({+ name: "Category",+ display_name: "Category",+ base_type: "type/Text",+ }),+ createMockColumn({+ name: "Amount",+ display_name: "Amount",+ base_type: "type/Number",+ semantic_type: "type/Number",+ }),+];++function createRawSeries(rows: RowValue[][]): RawSeries {+ return [+ {+ card: createMockCard({ display: "treemap" }),+ data: createMockDatasetData({ cols: columns, rows }),+ },+ ];+}++function createSettings(+ savedRows?: TreemapRow[],+): ComputedVisualizationSettings {+ return {+ "treemap.grouping": "Category",+ "treemap.value": "Amount",+ "treemap.rows": savedRows,+ column: () => ({}),+ };+}++const formatter = (value: RowValue) => String(value);++describe("getTreemapRows", () => {+ it("keeps a group disabled via the X across recomputes", () => {+ const rawSeries = createRawSeries([+ ["Phones", 10],+ ["Laptops", 30],+ ]);+ const saved: TreemapRow = {+ key: "Phones",+ name: "Phones",+ originalName: "Phones",+ color: "#509EE3",+ defaultColor: true,+ enabled: false,+ hidden: false,+ };+ const rows = getTreemapRows(rawSeries, createSettings([saved]), formatter);++ expect(rows.find((row) => row.key === "Phones")).toMatchObject({+ enabled: false,+ hidden: false,+ });+ });+});diff --git a/frontend/src/metabase/visualizations/types/visualization.ts b/frontend/src/metabase/visualizations/types/visualization.tsindex c6600102cee..9c4f0e71522 100644--- a/frontend/src/metabase/visualizations/types/visualization.ts+++ b/frontend/src/metabase/visualizations/types/visualization.ts@@ -51,6 +51,7 @@ import type { ChartSettingTableColumnsProps } from "../components/settings/Chartimport type { LegacySeriesSettingsObjectKey } from "../echarts/cartesian/model/types";import type { DimensionsWidgetProps } from "../visualizations/PieChart/DimensionsWidget";import type { SmartScalarComparisonWidgetProps } from "../visualizations/SmartScalar/SettingsComponents/SmartScalarSettingsWidgets";+import type { TreemapGroupsPickerProps } from "../visualizations/TreemapChart/TreemapGroupsPicker";import type { RemappingHydratedDatasetColumn } from "./columns";import type { HoveredObject } from "./hover";@@ -585,6 +586,18 @@ export type VisualizationSettingsDefinitions = {time_enabled?: DatasetColumnSettingDefinition<Value, Props>;time_style?: DatasetColumnSettingDefinition<Value, Props>;title?: SingleSeriesSettingDefinition<Value, Props>;+ "treemap._groups_widget"?: SeriesSettingDefinition<+ Value,+ TreemapGroupsPickerProps+ >;+ "treemap.grouping"?: SeriesSettingDefinition<Value, Props>;+ "treemap.rows"?: SeriesSettingDefinition<Value, Props>;+ "treemap.show_leaf_labels"?: SeriesSettingDefinition<Value, Props>;+ "treemap.show_leaf_values"?: SeriesSettingDefinition<Value, Props>;+ "treemap.show_parent_labels"?: SeriesSettingDefinition<Value, Props>;+ "treemap.show_parent_values"?: SeriesSettingDefinition<Value, Props>;+ "treemap.sub_grouping"?: SeriesSettingDefinition<Value, Props>;+ "treemap.value"?: SeriesSettingDefinition<Value, Props>;view_as?: SeriesSettingDefinition<Value, Props>;"waterfall.decrease_color"?: SeriesSettingDefinition<Value, Props>;"waterfall.increase_color"?: SeriesSettingDefinition<Value, Props>;diff --git a/frontend/src/metabase/visualizations/visualizations/PieChart/SliceNameWidget.tsx b/frontend/src/metabase/visualizations/visualizations/PieChart/SliceNameWidget.tsxindex 37c7aae3c82..8f9d32fbfcf 100644--- a/frontend/src/metabase/visualizations/visualizations/PieChart/SliceNameWidget.tsx+++ b/frontend/src/metabase/visualizations/visualizations/PieChart/SliceNameWidget.tsx@@ -3,9 +3,13 @@ import type { PieRow } from "metabase-types/api";import { SliceNameInput } from "./SliceNameWidget.styled";+// The widget only reads these fields, so any row shape that carries them works+// (PieRow for pie, TreemapRow for treemap).+type NameableRow = Pick<PieRow, "key" | "name" | "originalName">;+export type SliceNameWidgetProps = {initialKey: string | number;- pieRows: PieRow[];+ pieRows: NameableRow[];updateRowName: (newName: string, key: string | number) => void;};diff --git a/frontend/src/metabase/visualizations/visualizations/TreemapChart/TreemapBreadcrumb.tsx b/frontend/src/metabase/visualizations/visualizations/TreemapChart/TreemapBreadcrumb.tsxnew file mode 100644index 00000000000..d4915b0a0f5--- /dev/null+++ b/frontend/src/metabase/visualizations/visualizations/TreemapChart/TreemapBreadcrumb.tsx@@ -0,0 +1,45 @@+import { t } from "ttag";++import { Group, Icon, Text, UnstyledButton } from "metabase/ui";++interface TreemapBreadcrumbProps {+ groupLabel: string | null;+ value: string;+ onBackClick: () => void;+}++export function TreemapBreadcrumb({+ groupLabel,+ value,+ onBackClick,+}: TreemapBreadcrumbProps) {+ return (+ <Group data-testid="treemap-breadcrumb" gap="sm">+ <Label groupLabel={groupLabel} onBackClick={onBackClick} />+ <Text fw={400} lh="md">+ {value}+ </Text>+ </Group>+ );+}++function Label({+ groupLabel,+ onBackClick,+}: {+ groupLabel: string | null;+ onBackClick: () => void;+}) {+ if (groupLabel == null) {+ return <Text fw={700} lh="md">{t`Total`}</Text>;+ }++ return (+ <UnstyledButton type="button" onClick={onBackClick}>+ <Group>+ <Icon name="arrow_left" aria-hidden />+ <Text fw={700}>{groupLabel}</Text>+ </Group>+ </UnstyledButton>+ );+}diff --git a/frontend/src/metabase/visualizations/visualizations/TreemapChart/TreemapBreadcrumb.unit.spec.tsx b/frontend/src/metabase/visualizations/visualizations/TreemapChart/TreemapBreadcrumb.unit.spec.tsxnew file mode 100644index 00000000000..9dbfdfec92a--- /dev/null+++ b/frontend/src/metabase/visualizations/visualizations/TreemapChart/TreemapBreadcrumb.unit.spec.tsx@@ -0,0 +1,39 @@+import userEvent from "@testing-library/user-event";++import { renderWithProviders, screen } from "__support__/ui";++import { TreemapBreadcrumb } from "./TreemapBreadcrumb";++describe("TreemapBreadcrumb", () => {+ it("shows 'Total' with the value at the overview", () => {+ renderWithProviders(+ <TreemapBreadcrumb+ groupLabel={null}+ value="$11,576,000"+ onBackClick={jest.fn()}+ />,+ );++ expect(screen.getByText("Total")).toBeInTheDocument();+ expect(screen.getByText("$11,576,000")).toBeInTheDocument();+ expect(screen.queryByRole("button")).not.toBeInTheDocument();+ });++ it("shows a back button with the drilled-in group when drilled", async () => {+ const onBackClick = jest.fn();+ renderWithProviders(+ <TreemapBreadcrumb+ groupLabel="Legumes"+ value="$2,100,000"+ onBackClick={onBackClick}+ />,+ );++ expect(screen.getByRole("button", { name: "Legumes" })).toBeInTheDocument();+ expect(screen.getByText("$2,100,000")).toBeInTheDocument();+ expect(screen.queryByText("Total")).not.toBeInTheDocument();++ await userEvent.click(screen.getByRole("button", { name: "Legumes" }));+ expect(onBackClick).toHaveBeenCalledTimes(1);+ });+});diff --git a/frontend/src/metabase/visualizations/visualizations/TreemapChart/TreemapChart.module.css b/frontend/src/metabase/visualizations/visualizations/TreemapChart/TreemapChart.module.cssnew file mode 100644index 00000000000..ddb25f07694--- /dev/null+++ b/frontend/src/metabase/visualizations/visualizations/TreemapChart/TreemapChart.module.css@@ -0,0 +1,6 @@+/* rounded corners on the chart container */+.root {+ & [data-testid="chart-container"] svg {+ clip-path: inset(0 round 1rem);+ }+}diff --git a/frontend/src/metabase/visualizations/visualizations/TreemapChart/TreemapChart.stories.tsx b/frontend/src/metabase/visualizations/visualizations/TreemapChart/TreemapChart.stories.tsxnew file mode 100644index 00000000000..6bfbd7e86d5--- /dev/null+++ b/frontend/src/metabase/visualizations/visualizations/TreemapChart/TreemapChart.stories.tsx@@ -0,0 +1,56 @@+import type { StoryFn } from "@storybook/react";++import { VisualizationWrapper } from "__support__/storybook";+import { data } from "metabase/static-viz/components/TreemapChart/stories-data";+import { Box } from "metabase/ui";+import { registerVisualization } from "metabase/visualizations";+import Visualization from "metabase/visualizations/components/Visualization";+import type { Series } from "metabase-types/api";++import { TreemapChart } from "./TreemapChart";++export default {+ title: "viz/TreemapChart",+ component: TreemapChart,+};++// @ts-expect-error: incompatible prop types with registerVisualization+registerVisualization(TreemapChart);++type TemplateArgs = { rawSeries: Series; displayTheme?: "light" | "dark" };++const Template: StoryFn<TemplateArgs> = ({ rawSeries, displayTheme }) => {+ return (+ <VisualizationWrapper displayTheme={displayTheme}>+ <Box w={1000} h={600}>+ <Visualization+ rawSeries={rawSeries}+ width={1000}+ handleVisualizationClick={() => {}}+ />+ </Box>+ </VisualizationWrapper>+ );+};++export const TwoLevel = {+ render: Template,+ args: {+ rawSeries: data.twoLevel,+ },+};++export const OneLevel = {+ render: Template,+ args: {+ rawSeries: data.oneLevel,+ },+};++export const DarkTheme = {+ render: Template,+ args: {+ rawSeries: data.twoLevel,+ displayTheme: "dark",+ },+};diff --git a/frontend/src/metabase/visualizations/visualizations/TreemapChart/TreemapChart.tsx b/frontend/src/metabase/visualizations/visualizations/TreemapChart/TreemapChart.tsxnew file mode 100644index 00000000000..b417946ca04--- /dev/null+++ b/frontend/src/metabase/visualizations/visualizations/TreemapChart/TreemapChart.tsx@@ -0,0 +1,284 @@+import type { EChartsType } from "echarts/core";+import { useCallback, useEffect, useMemo, useRef, useState } from "react";+import { useLatest } from "react-use";++import { Box, Stack } from "metabase/ui";+import { extractRemappings } from "metabase/visualizations";+import { ResponsiveEChartsRenderer } from "metabase/visualizations/components/EChartsRenderer";+import { getTreemapBreadcrumbModel } from "metabase/visualizations/echarts/graph/treemap/model/breadcrumb";+import { getTreemapColors } from "metabase/visualizations/echarts/graph/treemap/model/colors";+import {+ getTreemapChartColumns,+ getTreemapData,+} from "metabase/visualizations/echarts/graph/treemap/model/data";+import { getTreemapFormatters } from "metabase/visualizations/echarts/graph/treemap/model/formatters";+import { shouldShowParentLabels } from "metabase/visualizations/echarts/graph/treemap/model/labels";+import { getTreemapInlineValueIds } from "metabase/visualizations/echarts/graph/treemap/model/tooltip";+import { isOverview } from "metabase/visualizations/echarts/graph/treemap/model/tree";+import { getTreemapChartOption } from "metabase/visualizations/echarts/graph/treemap/option/option";+import {+ getChartPadding,+ groupHeader,+} from "metabase/visualizations/echarts/graph/treemap/style";+import {+ useCloseTooltipOnScroll,+ useInjectSeriesColorsClasses,+} from "metabase/visualizations/echarts/tooltip";+import { useBrowserRenderingContext } from "metabase/visualizations/hooks/use-browser-rendering-context";+import type { VisualizationProps } from "metabase/visualizations/types";++import { TreemapBreadcrumb } from "./TreemapBreadcrumb";+import S from "./TreemapChart.module.css";+import { TREEMAP_CHART_DEFINITION } from "./chart-definition";+import { dispatchTreemapViewRoot, useChartEvents } from "./events";+import { type TreemapHoverOverlay, hideTreemapHoverOverlay } from "./overlay";+import { getTreemapTooltipOption } from "./tooltip";+import { useLabelMeasurement } from "./use-label-measurement";+import { usePointerTracking } from "./use-pointer-tracking";+import { useTreemapNavigation } from "./use-treemap-navigation";++export const TreemapChart = ({+ rawSeries,+ settings,+ fontFamily,+ onVisualizationClick,+ clicked,+ isDashboard,+ isDocument,+ gridSize,+}: VisualizationProps) => {+ const rawSeriesWithRemappings = useMemo(+ () => extractRemappings(rawSeries),+ [rawSeries],+ );++ const containerRef = useRef<HTMLDivElement>(null);+ const chartRef = useRef<EChartsType>();+ const overlayRef = useRef<TreemapHoverOverlay | null>(null);+ const isAnimatingRef = useRef(false);+ const clickedRef = useLatest(clicked);++ const { zrEventHandlers, getPointer } = usePointerTracking();++ const chartData = useMemo(() => {+ const cols = rawSeriesWithRemappings[0]?.data?.cols ?? [];+ const treemapColumns = getTreemapChartColumns(cols, settings);+ if (!treemapColumns) {+ return null;+ }+ const treemapRows = settings["treemap.rows"];+ const tree = getTreemapData(+ rawSeriesWithRemappings,+ treemapColumns,+ treemapRows,+ settings,+ );+ const colors = getTreemapColors(tree, treemapRows);+ return { tree, colors, treemapColumns };+ }, [rawSeriesWithRemappings, settings]);++ const { viewRootId, viewRootIdRef, setViewRoot } = useTreemapNavigation(+ chartData?.tree ?? null,+ );++ const renderingContext = useBrowserRenderingContext({ fontFamily });++ const formatters = useMemo(+ () =>+ chartData+ ? getTreemapFormatters(chartData.treemapColumns, settings)+ : null,+ [chartData, settings],+ );++ const { labelLayout, parentLabelLayout, handleLabelMeasure } =+ useLabelMeasurement({+ chartRef,+ tree: chartData?.tree ?? null,+ formatters,+ renderingContext,+ viewRootId,+ showLeafLabels: settings["treemap.show_leaf_labels"] ?? true,+ showLeafValues: settings["treemap.show_leaf_values"] ?? true,+ showParentValues: settings["treemap.show_parent_values"] ?? true,+ gridSize,+ });++ const isCompact = isDashboard || isDocument;++ const option = useMemo(() => {+ const showLeafLabels = settings["treemap.show_leaf_labels"] ?? true;+ if (!chartData || !formatters) {+ return null;+ }+ const { tree, colors, treemapColumns } = chartData;+ const showParentLabels = shouldShowParentLabels(gridSize, settings);+ const seriesOption = getTreemapChartOption({+ tree,+ colors,+ isDrilled: viewRootId !== null,+ showParentLabels,+ showLeafLabels,+ isCompact,+ labelLayout,+ parentLabelLayout,+ formatValue: formatters.value,+ formatPercent: formatters.percent,+ renderingContext,+ });++ const headerHeight = showParentLabels+ ? isCompact+ ? groupHeader.compactHeight+ : groupHeader.height+ : 0;++ return {+ ...seriesOption,+ tooltip: getTreemapTooltipOption(+ tree,+ colors,+ formatters.value,+ formatters.percent,+ containerRef,+ () => viewRootIdRef.current,+ () => clickedRef.current != null,+ () => isAnimatingRef.current,+ () => chartRef.current,+ getPointer,+ headerHeight,+ getTreemapInlineValueIds(labelLayout, parentLabelLayout),+ treemapColumns.grouping.column.display_name,+ ),+ };+ }, [+ chartData,+ gridSize,+ formatters,+ settings,+ viewRootId,+ viewRootIdRef,+ isCompact,+ labelLayout,+ parentLabelLayout,+ renderingContext,+ clickedRef,+ getPointer,+ ]);++ const [chartInstance, setChartInstance] = useState<EChartsType>();+ const handleInit = useCallback((chart: EChartsType) => {+ chartRef.current = chart;+ setChartInstance(chart);+ }, []);++ const handleResize = useCallback(+ (_width: number, _height: number) => {+ hideTreemapHoverOverlay(chartRef, overlayRef);+ handleLabelMeasure();+ },+ [handleLabelMeasure],+ );++ const hasChildren = Boolean(+ chartData?.tree.some((node) => node.children != null),+ );+ const { eventHandlers } = useChartEvents({+ chartRef,+ overlayRef,+ hasChildren,+ isDrilled: !isOverview(viewRootId),+ onDrillToGroup: setViewRoot,+ tree: chartData?.tree ?? [],+ treemapColumns: chartData?.treemapColumns ?? null,+ rawSeries: rawSeriesWithRemappings,+ settings,+ onVisualizationClick,+ });++ const handleFinished = useCallback(() => {+ isAnimatingRef.current = false;+ handleLabelMeasure();+ }, [handleLabelMeasure]);++ const allEventHandlers = useMemo(+ () => [+ ...eventHandlers,+ { eventName: "finished", handler: handleFinished },+ ],+ [eventHandlers, handleFinished],+ );++ // reapply current zoom level that lives outside echarts+ useEffect(() => {+ hideTreemapHoverOverlay(chartRef, overlayRef);+ dispatchTreemapViewRoot(chartRef, viewRootId);+ }, [option, viewRootId]);++ const prevViewRootIdRef = useRef(viewRootId);+ useEffect(() => {+ const isDrillTransition = prevViewRootIdRef.current !== viewRootId;+ prevViewRootIdRef.current = viewRootId;+ if (isDrillTransition) {+ isAnimatingRef.current = true;+ } else {+ handleLabelMeasure();+ }+ }, [chartInstance, option, viewRootId, handleLabelMeasure]);++ const breadcrumb = chartData+ ? getTreemapBreadcrumbModel(chartData.tree, viewRootId)+ : null;++ const handleBreadcrumbBack = useCallback(() => {+ setViewRoot(null);+ }, [setViewRoot]);++ useCloseTooltipOnScroll(chartRef);++ const colorsCss = useInjectSeriesColorsClasses(+ useMemo(() => Object.values(chartData?.colors ?? {}), [chartData]),+ );++ if (!option) {+ return null;+ }++ return (+ <Stack+ w="100%"+ h="100%"+ display="flex"+ style={{ flexDirection: "column" }}+ gap={isCompact ? "md" : 28}+ >+ {breadcrumb && formatters && (+ <Box px={isDashboard ? "md" : "xl"} pt={isDashboard ? 12 : 24}>+ <TreemapBreadcrumb+ groupLabel={breadcrumb.groupLabel}+ value={formatters.value(breadcrumb.value)}+ onBackClick={handleBreadcrumbBack}+ />+ </Box>+ )}+ <Box+ className={S.root}+ p={getChartPadding(isDashboard)}+ w="100%"+ style={{ flex: 1, minHeight: 0 }}+ >+ <ResponsiveEChartsRenderer+ ref={containerRef}+ option={option}+ eventHandlers={allEventHandlers}+ zrEventHandlers={zrEventHandlers}+ onInit={handleInit}+ onResize={handleResize}+ />+ {colorsCss}+ </Box>+ </Stack>+ );+};++Object.assign(TreemapChart, TREEMAP_CHART_DEFINITION);diff --git a/frontend/src/metabase/visualizations/visualizations/TreemapChart/TreemapGroupsPicker.tsx b/frontend/src/metabase/visualizations/visualizations/TreemapChart/TreemapGroupsPicker.tsxnew file mode 100644index 00000000000..991c88978a0--- /dev/null+++ b/frontend/src/metabase/visualizations/visualizations/TreemapChart/TreemapGroupsPicker.tsx@@ -0,0 +1,65 @@+import { t } from "ttag";++import { ChartSettingSeriesOrder } from "metabase/visualizations/components/settings/ChartSettingSeriesOrder";+import { getTreemapChartColumns } from "metabase/visualizations/echarts/graph/treemap/model/data";+import type { ComputedVisualizationSettings } from "metabase/visualizations/types";+import type { RawSeries, TreemapRow } from "metabase-types/api";++export type TreemapGroupsPickerProps = {+ rawSeries: RawSeries;+ settings: ComputedVisualizationSettings;+ onChangeSettings: (newSettings: ComputedVisualizationSettings) => void;+ onShowWidget: (+ widget: { id?: string; props?: { seriesKey: string } },+ ref: HTMLElement | undefined,+ ) => void;+};++export function TreemapGroupsPicker({+ rawSeries,+ settings,+ onChangeSettings,+ onShowWidget,+}: TreemapGroupsPickerProps) {+ const treemapRows = settings["treemap.rows"];++ if (treemapRows == null || treemapRows.length === 0) {+ return null;+ }++ const isTwoLevel =+ getTreemapChartColumns(rawSeries[0]?.data?.cols ?? [], settings)+ ?.subGrouping != null;++ const handleChangeSeriesColor = (groupKey: string, color: string) =>+ onChangeSettings({+ "treemap.rows": treemapRows.map((row) => {+ if (row.key !== groupKey) {+ return row;+ }+ return { ...row, color, defaultColor: false };+ }),+ });++ return (+ <ChartSettingSeriesOrder+ value={treemapRows}+ series={rawSeries}+ onChange={(rows) =>+ onChangeSettings({ "treemap.rows": rows as TreemapRow[] })+ }+ onChangeSeriesColor={handleChangeSeriesColor}+ onSortEnd={() => {}}+ onShowWidget={onShowWidget}+ hasEditSettings+ isSortable={false}+ accentColorOptions={+ isTwoLevel+ ? { main: true, light: false, dark: false, harmony: false }+ : undefined+ }+ addButtonLabel={t`Add another group`}+ searchPickerPlaceholder={t`Select a group`}+ />+ );+}diff --git a/frontend/src/metabase/visualizations/visualizations/TreemapChart/chart-definition.ts b/frontend/src/metabase/visualizations/visualizations/TreemapChart/chart-definition.tsnew file mode 100644index 00000000000..d756003fa06--- /dev/null+++ b/frontend/src/metabase/visualizations/visualizations/TreemapChart/chart-definition.ts@@ -0,0 +1,309 @@+import { t } from "ttag";++import { getTreemapChartColumns } from "metabase/visualizations/echarts/graph/treemap/model/data";+import { ChartSettingsError } from "metabase/visualizations/lib/errors";+import { formatValue } from "metabase/visualizations/lib/formatting";+import { columnSettings } from "metabase/visualizations/lib/settings/column";+import { nestedSettings } from "metabase/visualizations/lib/settings/nested";+import { keyForSingleSeries } from "metabase/visualizations/lib/settings/series";+import {+ dimensionSetting,+ metricSetting,+} from "metabase/visualizations/lib/settings/utils";+import { columnsAreValid } from "metabase/visualizations/lib/utils";+import { SERIES_SETTING_KEY } from "metabase/visualizations/shared/settings/series";+import { getTreemapRows } from "metabase/visualizations/shared/settings/treemap";+import type {+ ComputedVisualizationSettings,+ VisualizationDefinition,+ VisualizationSettingsDefinitions,+} from "metabase/visualizations/types";+import { isDimension, isMetric } from "metabase-lib/v1/types/utils/isa";+import type { DatasetData, RawSeries, SingleSeries } from "metabase-types/api";++import {+ SliceNameWidget,+ type SliceNameWidgetProps,+} from "../PieChart/SliceNameWidget";++import { TreemapGroupsPicker } from "./TreemapGroupsPicker";++export const SETTINGS_DEFINITIONS: VisualizationSettingsDefinitions = {+ ...columnSettings({ getHidden: () => true }),+ ...dimensionSetting("treemap.grouping", {+ getSection: () => t`Data`,+ get title() {+ return t`Grouping`;+ },+ showColumnSetting: true,+ persistDefault: true,+ dashboard: false,+ autoOpenWhenUnset: false,+ // Remove persisted row settings when changing the grouping+ eraseDependencies: ["treemap.rows"],+ getDefault: ([{ data }]) => {+ const firstDimension = data.cols.find(+ (col) => isDimension(col) && !isMetric(col),+ );+ return firstDimension?.name;+ },+ getWrapperStyle: (+ _series: RawSeries,+ vizSettings: ComputedVisualizationSettings,+ ) =>+ vizSettings["treemap.rows"]?.some((row) => !row.hidden)+ ? { marginBottom: 0 }+ : undefined,+ }),+ "treemap._groups_widget": {+ getSection: () => t`Data`,+ widget: TreemapGroupsPicker,+ getWrapperStyle: () => ({ marginBottom: 0 }),+ getProps: (+ rawSeries: RawSeries,+ settings: ComputedVisualizationSettings,+ _onChange: unknown,+ _extra: unknown,+ onChangeSettings: (newSettings: ComputedVisualizationSettings) => void,+ ) => ({+ rawSeries,+ settings,+ onChangeSettings,+ }),+ readDependencies: ["treemap.rows"],+ },+ ...nestedSettings<+ "series_settings",+ SingleSeries,+ unknown,+ SliceNameWidgetProps+ >(SERIES_SETTING_KEY, {+ getObjectKey: keyForSingleSeries,+ widget: SliceNameWidget,+ getHidden: (_series, _settings, extra) => !extra?.isDashboard,+ getSection: (_series, _settings, extra) =>+ extra?.isDashboard ? t`Display` : t`Style`,+ getWrapperStyle: () => ({+ marginBottom: 0,+ }),+ getProps: (_series, vizSettings, _onChange, _extra, onChangeSettings) => {+ const treemapRows = vizSettings["treemap.rows"];+ if (treemapRows == null) {+ return { pieRows: [], updateRowName: () => null };+ }++ return {+ pieRows: treemapRows,+ updateRowName: (newName: string, key: string | number) => {+ onChangeSettings({+ "treemap.rows": treemapRows.map((row) => {+ if (row.key !== key) {+ return row;+ }+ return { ...row, name: newName };+ }),+ });+ },+ };+ },+ readDependencies: ["treemap.rows"],+ }),+ ...dimensionSetting("treemap.sub_grouping", {+ getSection: () => t`Data`,+ get title() {+ return t`Sub-grouping`;+ },+ showColumnSetting: true,+ dashboard: false,+ autoOpenWhenUnset: false,+ getDefault: ([{ data }], vizSettings) => {+ const grouping = vizSettings["treemap.grouping"];+ const value = vizSettings["treemap.value"];+ const secondDimension = data.cols.find(+ (col) =>+ isDimension(col) && col.name !== grouping && col.name !== value,+ );+ return secondDimension?.name;+ },+ isValid: ([{ card, data }]) =>+ columnsAreValid(+ [card.visualization_settings["treemap.sub_grouping"]],+ data,+ isDimension,+ ),+ getHidden: ([{ data }], vizSettings) => {+ const grouping = vizSettings["treemap.grouping"];+ const value = vizSettings["treemap.value"];+ return !data.cols.some(+ (col) =>+ isDimension(col) && col.name !== grouping && col.name !== value,+ );+ },+ getProps: ([{ data }], vizSettings, onChange) => {+ const grouping = vizSettings["treemap.grouping"];+ return {+ options: data.cols+ .filter((col) => isDimension(col) && col.name !== grouping)+ .map((col) => ({ name: col.display_name, value: col.name })),+ columns: data.cols,+ onRemove: vizSettings["treemap.sub_grouping"]+ ? () => onChange(null)+ : null,+ };+ },+ readDependencies: ["treemap.grouping", "treemap.value"],+ }),+ ...metricSetting("treemap.value", {+ getSection: () => t`Data`,+ get title() {+ return t`Value`;+ },+ showColumnSetting: true,+ persistDefault: true,+ dashboard: false,+ autoOpenWhenUnset: false,+ getDefault: ([{ data }], vizSettings) => {+ const grouping = vizSettings["treemap.grouping"];+ const firstMetric = data.cols.find(+ (col) => isMetric(col) && col.name !== grouping,+ );+ return firstMetric?.name;+ },+ readDependencies: ["treemap.grouping"],+ }),+ "treemap.rows": {+ getHidden: () => true,+ getValue: (series: RawSeries, settings: ComputedVisualizationSettings) =>+ getTreemapRows(series, settings, (value, options) =>+ String(formatValue(value, options)),+ ),+ readDependencies: [+ "treemap.grouping",+ "treemap.sub_grouping",+ "treemap.value",+ ],+ },+ "treemap.show_parent_labels": {+ getSection: () => t`Display`,+ get group() {+ return t`Parent categories`;+ },+ get title() {+ return t`Show parent labels`;+ },+ widget: "toggle",+ index: 0,+ getDefault: () => true,+ inline: true,+ getHidden: (+ _series: RawSeries,+ vizSettings: ComputedVisualizationSettings,+ ) => !vizSettings["treemap.sub_grouping"],+ readDependencies: ["treemap.sub_grouping"],+ },+ "treemap.show_parent_values": {+ getSection: () => t`Display`,+ get group() {+ return t`Parent categories`;+ },+ get title() {+ return t`Show parent values`;+ },+ widget: "toggle",+ index: 1,+ getDefault: () => true,+ inline: true,+ getProps: (+ _series: RawSeries,+ vizSettings: ComputedVisualizationSettings,+ ) => ({+ disabled: vizSettings["treemap.show_parent_labels"] === false,+ }),+ getHidden: (+ _series: RawSeries,+ vizSettings: ComputedVisualizationSettings,+ ) => !vizSettings["treemap.sub_grouping"],+ readDependencies: ["treemap.sub_grouping", "treemap.show_parent_labels"],+ },+ "treemap.show_leaf_labels": {+ getSection: () => t`Display`,+ get group() {+ return t`Leaves`;+ },+ get title() {+ return t`Show leaf labels`;+ },+ widget: "toggle",+ index: 0,+ getDefault: () => true,+ inline: true,+ },+ "treemap.show_leaf_values": {+ getSection: () => t`Display`,+ get group() {+ return t`Leaves`;+ },+ get title() {+ return t`Show leaf values`;+ },+ widget: "toggle",+ index: 1,+ getDefault: () => true,+ inline: true,+ getProps: (+ _series: RawSeries,+ vizSettings: ComputedVisualizationSettings,+ ) => ({+ disabled: vizSettings["treemap.show_leaf_labels"] === false,+ }),+ readDependencies: ["treemap.show_leaf_labels"],+ },+};++export const TREEMAP_CHART_DEFINITION: VisualizationDefinition = {+ getUiName: () => t`Treemap`,+ identifier: "treemap",+ iconName: "treemap",+ get noun() {+ return t`treemap chart`;+ },+ minSize: { width: 6, height: 4 },+ defaultSize: { width: 12, height: 8 },+ disableVisualizer: true,+ hasEmptyState: true,+ isSensible: (data: DatasetData) => {+ const { cols, rows } = data;+ const numDimensions = cols.filter(isDimension).length;+ const numMetrics = cols.filter(isMetric).length;+ return rows.length >= 1 && numDimensions >= 1 && numMetrics >= 1;+ },+ checkRenderable: (+ rawSeries: RawSeries,+ settings: ComputedVisualizationSettings,+ ) => {+ const { rows, cols } = rawSeries[0].data;+ if (rows.length === 0) {+ return;+ }++ const hasPotentialMetricColumn = cols.some(+ (col) => isMetric(col) && col.name !== settings["treemap.grouping"],+ );+ if (!hasPotentialMetricColumn) {+ throw new ChartSettingsError(+ t`Add at least one metric column to use as the value.`,+ {+ section: "Data",+ },+ );+ }++ const treemapColumns = getTreemapChartColumns(cols, settings);+ if (!treemapColumns) {+ throw new ChartSettingsError(t`Which columns do you want to use?`, {+ section: "Data",+ });+ }+ },+ settings: SETTINGS_DEFINITIONS,+};diff --git a/frontend/src/metabase/visualizations/visualizations/TreemapChart/chart-definition.unit.spec.ts b/frontend/src/metabase/visualizations/visualizations/TreemapChart/chart-definition.unit.spec.tsnew file mode 100644index 00000000000..5024438ae27--- /dev/null+++ b/frontend/src/metabase/visualizations/visualizations/TreemapChart/chart-definition.unit.spec.ts@@ -0,0 +1,451 @@+import { checkNotNull } from "metabase/utils/types";+import { ChartSettingsError } from "metabase/visualizations/lib/errors";+import {+ getComputedSettings,+ getSettingsWidgets,+} from "metabase/visualizations/lib/settings";+import type { RowValues } from "metabase-types/api/dataset";+import { createMockCard } from "metabase-types/api/mocks/card";+import {+ createMockColumn,+ createMockDatasetData,+} from "metabase-types/api/mocks/dataset";++import { TREEMAP_CHART_DEFINITION } from "./chart-definition";++const isSensible = checkNotNull(TREEMAP_CHART_DEFINITION.isSensible);++const baseColumns = [+ createMockColumn({+ name: "Category",+ display_name: "Category",+ base_type: "type/Text",+ }),+ createMockColumn({+ name: "Amount",+ display_name: "Amount",+ base_type: "type/Number",+ semantic_type: "type/Number",+ }),+];++const columnsWithSubgrouping = [+ createMockColumn({+ name: "Category",+ display_name: "Category",+ base_type: "type/Text",+ }),+ createMockColumn({+ name: "SubCategory",+ display_name: "Sub-Category",+ base_type: "type/Text",+ }),+ createMockColumn({+ name: "Amount",+ display_name: "Amount",+ base_type: "type/Number",+ semantic_type: "type/Number",+ }),+];++const makeSeries = (+ cols = baseColumns,+ rows: RowValues[] = [+ ["A", 10],+ ["B", 20],+ ],+) => [+ {+ card: createMockCard(),+ data: createMockDatasetData({ cols, rows }),+ },+];++describe("TREEMAP_CHART_DEFINITION", () => {+ describe("isSensible", () => {+ it("returns true with at least one row, one dimension, and one metric", () => {+ const data = createMockDatasetData({+ rows: [+ ["A", 10],+ ["B", 20],+ ],+ cols: baseColumns,+ });++ expect(isSensible(data)).toBe(true);+ });++ it("returns false when there are no rows", () => {+ const data = createMockDatasetData({ rows: [], cols: baseColumns });+ expect(isSensible(data)).toBe(false);+ });++ it("returns false when there is no metric", () => {+ const data = createMockDatasetData({+ rows: [["A", "X"]],+ cols: [+ createMockColumn({+ name: "Category",+ display_name: "Category",+ base_type: "type/Text",+ }),+ createMockColumn({+ name: "SubCategory",+ display_name: "SubCategory",+ base_type: "type/Text",+ }),+ ],+ });++ expect(isSensible(data)).toBe(false);+ });+ });++ describe("checkRenderable", () => {+ const settings = {+ "treemap.grouping": "Category",+ "treemap.value": "Amount",+ };++ it("does not throw for valid data", () => {+ expect(() =>+ TREEMAP_CHART_DEFINITION.checkRenderable(makeSeries(), settings),+ ).not.toThrow();+ });++ it("does not throw for empty data", () => {+ expect(() =>+ TREEMAP_CHART_DEFINITION.checkRenderable(+ makeSeries(baseColumns, []),+ settings,+ ),+ ).not.toThrow();+ });++ it("throws when required columns are unset", () => {+ expect(() =>+ TREEMAP_CHART_DEFINITION.checkRenderable(makeSeries(), {}),+ ).toThrow(+ new ChartSettingsError("Which columns do you want to use?", {+ section: "Data",+ }),+ );+ });++ it("throws when there is no available metric after grouping selection", () => {+ const metricAsGroupingCols = [+ createMockColumn({+ name: "Category",+ display_name: "Category",+ base_type: "type/Text",+ }),+ createMockColumn({+ name: "Amount",+ display_name: "Amount",+ base_type: "type/Number",+ semantic_type: "type/Number",+ }),+ ];++ expect(() =>+ TREEMAP_CHART_DEFINITION.checkRenderable(+ makeSeries(metricAsGroupingCols),+ {+ "treemap.grouping": "Amount",+ "treemap.value": "Amount",+ },+ ),+ ).toThrow(+ new ChartSettingsError(+ "Add at least one metric column to use as the value.",+ {+ section: "Data",+ },+ ),+ );+ });++ it("allows valid two-level grouping", () => {+ expect(() =>+ TREEMAP_CHART_DEFINITION.checkRenderable(+ makeSeries(columnsWithSubgrouping, [+ ["A", "x", 10],+ ["B", "y", 20],+ ]),+ {+ "treemap.grouping": "Category",+ "treemap.sub_grouping": "SubCategory",+ "treemap.value": "Amount",+ },+ ),+ ).not.toThrow();+ });+ });++ describe("data setting defaults", () => {+ const groupingSetting = checkNotNull(+ TREEMAP_CHART_DEFINITION.settings?.["treemap.grouping"],+ );+ const valueSetting = checkNotNull(+ TREEMAP_CHART_DEFINITION.settings?.["treemap.value"],+ );+ const subGroupingSetting = checkNotNull(+ TREEMAP_CHART_DEFINITION.settings?.["treemap.sub_grouping"],+ );++ it("defaults grouping to first non-metric dimension", () => {+ const getDefault = checkNotNull(groupingSetting.getDefault);+ expect(getDefault(makeSeries(baseColumns, [["A", 10]]), {})).toBe(+ "Category",+ );+ });++ it("defaults value to first metric that differs from grouping", () => {+ const getDefault = checkNotNull(valueSetting.getDefault);+ expect(+ getDefault(makeSeries(columnsWithSubgrouping, [["A", "x", 10]]), {+ "treemap.grouping": "Category",+ }),+ ).toBe("Amount");+ });++ it("defaults sub-grouping to second dimension", () => {+ const getDefault = checkNotNull(subGroupingSetting.getDefault);+ expect(+ getDefault(makeSeries(columnsWithSubgrouping, [["A", "x", 10]]), {+ "treemap.grouping": "Category",+ "treemap.value": "Amount",+ }),+ ).toBe("SubCategory");+ });++ it("defaults sub-grouping to undefined for one dimension", () => {+ const getDefault = checkNotNull(subGroupingSetting.getDefault);+ expect(+ getDefault(makeSeries(baseColumns, [["A", 10]]), {+ "treemap.grouping": "Category",+ "treemap.value": "Amount",+ }),+ ).toBeUndefined();+ });++ it("hides sub-grouping when no second dimension is available", () => {+ const getHidden = checkNotNull(subGroupingSetting.getHidden);+ expect(+ getHidden(makeSeries(baseColumns, [["A", 10]]), {+ "treemap.grouping": "Category",+ "treemap.value": "Amount",+ }),+ ).toBe(true);+ expect(+ getHidden(makeSeries(columnsWithSubgrouping, [["A", "x", 10]]), {+ "treemap.grouping": "Category",+ "treemap.value": "Amount",+ }),+ ).toBe(false);+ });++ it("excludes the main grouping column from sub-grouping options", () => {+ const getProps = checkNotNull(subGroupingSetting.getProps);+ const props = getProps(+ makeSeries(columnsWithSubgrouping, [["A", "x", 10]]),+ {+ "treemap.grouping": "Category",+ "treemap.value": "Amount",+ },+ () => undefined,+ undefined,+ () => undefined,+ );++ expect(props).toEqual(+ expect.objectContaining({+ options: expect.arrayContaining([+ expect.objectContaining({ value: "SubCategory" }),+ ]),+ }),+ );+ expect(props).not.toEqual(+ expect.objectContaining({+ options: expect.arrayContaining([+ expect.objectContaining({ value: "Category" }),+ ]),+ }),+ );+ });++ it("keeps sub-grouping unset when explicitly cleared", () => {+ const series = makeSeries(columnsWithSubgrouping, [["A", "x", 10]]);+ const storedSettings = {+ "treemap.grouping": "Category",+ "treemap.value": "Amount",+ "treemap.sub_grouping": null,+ };++ const computedSettings = getComputedSettings(+ {+ "treemap.grouping": groupingSetting,+ "treemap.value": valueSetting,+ "treemap.sub_grouping": subGroupingSetting,+ },+ series,+ storedSettings,+ );++ expect(computedSettings["treemap.sub_grouping"]).toBeNull();+ });+ });++ describe("display toggles", () => {+ const showParentLabelsSetting = checkNotNull(+ TREEMAP_CHART_DEFINITION.settings?.["treemap.show_parent_labels"],+ );+ const showParentValuesSetting = checkNotNull(+ TREEMAP_CHART_DEFINITION.settings?.["treemap.show_parent_values"],+ );+ const showLeafValuesSetting = checkNotNull(+ TREEMAP_CHART_DEFINITION.settings?.["treemap.show_leaf_values"],+ );++ it("shows parent labels/value controls only when sub-grouping is selected", () => {+ const getParentLabelsHidden = checkNotNull(+ showParentLabelsSetting.getHidden,+ );+ const getParentValuesHidden = checkNotNull(+ showParentValuesSetting.getHidden,+ );++ expect(getParentLabelsHidden([], {}, {})).toBe(true);+ expect(+ getParentLabelsHidden(+ [],+ { "treemap.sub_grouping": "SubCategory" },+ {},+ ),+ ).toBe(false);+ expect(getParentValuesHidden([], {}, {})).toBe(true);+ expect(+ getParentValuesHidden(+ [],+ { "treemap.sub_grouping": "SubCategory" },+ {},+ ),+ ).toBe(false);+ });++ it("disables parent values when parent labels are off", () => {+ const getProps = checkNotNull(showParentValuesSetting.getProps);+ expect(+ getProps(+ [],+ { "treemap.show_parent_labels": false },+ jest.fn(),+ undefined,+ jest.fn(),+ ),+ ).toEqual({ disabled: true });+ });++ it("disables leaf values when leaf labels are off", () => {+ const getProps = checkNotNull(showLeafValuesSetting.getProps);+ expect(+ getProps(+ [],+ { "treemap.show_leaf_labels": false },+ jest.fn(),+ undefined,+ jest.fn(),+ ),+ ).toEqual({ disabled: true });+ });+ });++ describe("treemap.rows and rename settings", () => {+ const rowsSetting = checkNotNull(+ TREEMAP_CHART_DEFINITION.settings?.["treemap.rows"],+ );+ const seriesSetting = checkNotNull(+ TREEMAP_CHART_DEFINITION.settings?.["series_settings"],+ );++ const rawSeries = makeSeries(baseColumns, [+ ["Phones", 10],+ ["Laptops", 30],+ ]);++ it("computes one row per grouping value, value-descending", () => {+ const getValue = checkNotNull(rowsSetting.getValue);+ const rows = getValue(rawSeries, {+ "treemap.grouping": "Category",+ "treemap.value": "Amount",+ column: () => ({}),+ });++ expect(rows).toMatchObject([{ key: "Laptops" }, { key: "Phones" }]);+ expect(rowsSetting.readDependencies).toEqual([+ "treemap.grouping",+ "treemap.sub_grouping",+ "treemap.value",+ ]);+ });++ it("erases saved rows when the grouping column changes", () => {+ const groupingSetting = checkNotNull(+ TREEMAP_CHART_DEFINITION.settings?.["treemap.grouping"],+ );+ const onChangeSettings = jest.fn();+ const widgets = getSettingsWidgets(+ { "treemap.grouping": groupingSetting },+ { "treemap.grouping": "Category" },+ { "treemap.grouping": "Category" },+ rawSeries,+ onChangeSettings,+ );+ const groupingWidget = checkNotNull(+ widgets.find((widget) => widget.id === "treemap.grouping"),+ );++ groupingWidget.onChange?.("Region");++ expect(onChangeSettings).toHaveBeenCalledWith(+ { "treemap.grouping": "Region", "treemap.rows": null },+ undefined,+ );+ });++ it("renames a treemap row through nested series settings", () => {+ const treemapRows = [+ {+ key: "Phones",+ name: "Phones",+ originalName: "Phones",+ color: "#509EE3",+ defaultColor: true,+ enabled: true,+ hidden: false,+ },+ ];+ const onChangeSettings = jest.fn();+ const getProps = checkNotNull(seriesSetting.getProps);+ const props = getProps(+ [],+ { "treemap.rows": treemapRows },+ jest.fn(),+ undefined,+ onChangeSettings,+ );++ props.updateRowName("Smartphones", "Phones");++ expect(onChangeSettings).toHaveBeenCalledWith({+ "treemap.rows": [+ expect.objectContaining({+ key: "Phones",+ name: "Smartphones",+ originalName: "Phones",+ }),+ ],+ });+ });+ });+});diff --git a/frontend/src/metabase/visualizations/visualizations/TreemapChart/events.ts b/frontend/src/metabase/visualizations/visualizations/TreemapChart/events.tsnew file mode 100644index 00000000000..f371b24ff9c--- /dev/null+++ b/frontend/src/metabase/visualizations/visualizations/TreemapChart/events.ts@@ -0,0 +1,293 @@+import type { EChartsType } from "echarts/core";+import { type MutableRefObject, useMemo } from "react";++import { isNative } from "metabase/common/utils/card";+import {+ getNodesFromPath,+ getTreemapRootNodeId,+ isOverview,+} from "metabase/visualizations/echarts/graph/treemap/model/tree";+import type {+ TreemapChartColumns,+ TreemapTree,+} from "metabase/visualizations/echarts/graph/treemap/model/types";+import type { EChartsSeriesMouseEvent } from "metabase/visualizations/echarts/types";+import type {+ ClickObject,+ ComputedVisualizationSettings,+ VisualizationProps,+} from "metabase/visualizations/types";+import type { EChartsEventHandler } from "metabase/visualizations/types/echarts";+import type { ClickObjectDimension } from "metabase-lib";+import { getColumnKey } from "metabase-lib/v1/queries/utils/column-key";+import type { RawSeries, RowValue } from "metabase-types/api";++import {+ type TreemapHoverOverlayRef,+ hideTreemapHoverOverlay,+ showTreemapHoverOverlay,+} from "./overlay";++type TreemapSeriesMouseEvent = EChartsSeriesMouseEvent<{ id?: unknown }>;++export function dispatchTreemapViewRoot(+ chartRef: MutableRefObject<EChartsType | undefined>,+ viewRootId: string | null,+): void {+ if (isOverview(viewRootId)) {+ return;+ }+ chartRef.current?.dispatchAction({+ type: "treemapRootToNode",+ seriesIndex: 0,+ targetNode: viewRootId,+ });+}++export function getTreemapClickData({+ tree,+ id,+ treemapColumns,+ rawSeries,+ settings,+ event,+}: {+ tree: TreemapTree;+ id: string;+ treemapColumns: TreemapChartColumns;+ rawSeries: RawSeries;+ settings: ComputedVisualizationSettings;+ event: TreemapSeriesMouseEvent;+}): ClickObject | null {+ const path = getNodesFromPath(tree, id);+ if (path == null) {+ return null;+ }++ const { grouping, subGrouping, value } = treemapColumns;+ const groupingNode = path[0];+ const clickedNode = path[path.length - 1];+ const isLeafWithSubGrouping = subGrouping != null && path.length > 1;++ const dimensions: ClickObjectDimension[] = [+ { column: grouping.column, value: groupingNode.rawName },+ ];+ if (isLeafWithSubGrouping) {+ dimensions.push({ column: subGrouping.column, value: clickedNode.rawName });+ }++ const columnValues: Record<string, RowValue> = {+ [getColumnKey(grouping.column)]: groupingNode.rawName,+ [getColumnKey(value.column)]: clickedNode.value,+ };+ if (isLeafWithSubGrouping) {+ columnValues[getColumnKey(subGrouping.column)] = clickedNode.rawName;+ }++ const [+ {+ data: { cols },+ },+ ] = rawSeries;++ const clickData: ClickObject = {+ event: event.event.event,+ value: clickedNode.value,+ column: value.column,+ data: cols.map((col) => ({+ col,+ value: columnValues[getColumnKey(col)] ?? null,+ key: col.display_name,+ })),+ settings,+ };++ if (!isNative(rawSeries[0].card)) {+ clickData.dimensions = dimensions;+ }++ return clickData;+}++export function getTreemapClickHandler({+ chartRef,+ hasChildren,+ isDrilled,+ onDrillToGroup,+ tree,+ treemapColumns,+ rawSeries,+ settings,+ onVisualizationClick,+}: {+ chartRef: MutableRefObject<EChartsType | undefined>;+ hasChildren: boolean;+ isDrilled: boolean;+ onDrillToGroup: (viewRootId: string) => void;+ tree: TreemapTree;+ treemapColumns: TreemapChartColumns | null;+ rawSeries: RawSeries;+ settings: ComputedVisualizationSettings;+ onVisualizationClick: VisualizationProps["onVisualizationClick"];+}): EChartsEventHandler {+ return {+ eventName: "click",+ handler: (event: TreemapSeriesMouseEvent) => {+ const id = event?.data?.id;+ if (typeof id !== "string") {+ return;+ }++ chartRef.current?.dispatchAction({ type: "hideTip" });++ // Sub-grouping + overview+ if (hasChildren && !isDrilled) {+ onDrillToGroup(getTreemapRootNodeId(id));+ return;+ }++ if (treemapColumns == null) {+ return;+ }++ const clickData = getTreemapClickData({+ tree,+ id,+ treemapColumns,+ rawSeries,+ settings,+ event,+ });+ if (clickData != null) {+ onVisualizationClick?.(clickData);+ }+ },+ };+}++/* Custom hover overlay. ECharts doesn't support hover overlays on whole groups. */+export function getTreemapHoverHandlers({+ chartRef,+ overlayRef,+ isDrilled,+}: {+ chartRef: MutableRefObject<EChartsType | undefined>;+ overlayRef: TreemapHoverOverlayRef;+ isDrilled: boolean;+}): EChartsEventHandler[] {+ return [+ {+ eventName: "mouseover",+ handler: (event: TreemapSeriesMouseEvent) => {+ const id = event?.data?.id;+ if (typeof id !== "string") {+ return;+ }+ const targetId = isDrilled ? id : getTreemapRootNodeId(id);+ showTreemapHoverOverlay(chartRef, overlayRef, targetId);+ },+ },+ {+ eventName: "globalout",+ handler: () => hideTreemapHoverOverlay(chartRef, overlayRef),+ },+ ];+}++/** All treemap event handlers: click (drill-down / drill-through) + hover wash. */+export function getTreemapEventHandlers({+ chartRef,+ overlayRef,+ hasChildren,+ isDrilled,+ onDrillToGroup,+ tree,+ treemapColumns,+ rawSeries,+ settings,+ onVisualizationClick,+}: {+ chartRef: MutableRefObject<EChartsType | undefined>;+ overlayRef: TreemapHoverOverlayRef;+ hasChildren: boolean;+ isDrilled: boolean;+ onDrillToGroup: (viewRootId: string) => void;+ tree: TreemapTree;+ treemapColumns: TreemapChartColumns | null;+ rawSeries: RawSeries;+ settings: ComputedVisualizationSettings;+ onVisualizationClick: VisualizationProps["onVisualizationClick"];+}): EChartsEventHandler[] {+ return [+ getTreemapClickHandler({+ chartRef,+ hasChildren,+ isDrilled,+ onDrillToGroup,+ tree,+ treemapColumns,+ rawSeries,+ settings,+ onVisualizationClick,+ }),+ ...getTreemapHoverHandlers({+ chartRef,+ overlayRef,+ isDrilled,+ }),+ ];+}++export function useChartEvents({+ chartRef,+ overlayRef,+ hasChildren,+ isDrilled,+ onDrillToGroup,+ tree,+ treemapColumns,+ rawSeries,+ settings,+ onVisualizationClick,+}: {+ chartRef: MutableRefObject<EChartsType | undefined>;+ overlayRef: TreemapHoverOverlayRef;+ hasChildren: boolean;+ isDrilled: boolean;+ onDrillToGroup: (viewRootId: string) => void;+ tree: TreemapTree;+ treemapColumns: TreemapChartColumns | null;+ rawSeries: RawSeries;+ settings: ComputedVisualizationSettings;+ onVisualizationClick: VisualizationProps["onVisualizationClick"];+}) {+ const eventHandlers = useMemo(+ () =>+ getTreemapEventHandlers({+ chartRef,+ overlayRef,+ hasChildren,+ isDrilled,+ onDrillToGroup,+ tree,+ treemapColumns,+ rawSeries,+ settings,+ onVisualizationClick,+ }),+ [+ chartRef,+ overlayRef,+ hasChildren,+ isDrilled,+ onDrillToGroup,+ tree,+ treemapColumns,+ rawSeries,+ settings,+ onVisualizationClick,+ ],+ );++ return { eventHandlers };+}diff --git a/frontend/src/metabase/visualizations/visualizations/TreemapChart/events.unit.spec.ts b/frontend/src/metabase/visualizations/visualizations/TreemapChart/events.unit.spec.tsnew file mode 100644index 00000000000..763d995549b--- /dev/null+++ b/frontend/src/metabase/visualizations/visualizations/TreemapChart/events.unit.spec.ts@@ -0,0 +1,505 @@+import type { EChartsType } from "echarts/core";++import { getTreemapRootNodeId } from "metabase/visualizations/echarts/graph/treemap/model/tree";+import type {+ TreemapChartColumns,+ TreemapRect,+ TreemapTree,+} from "metabase/visualizations/echarts/graph/treemap/model/types";+import { TREEMAP_HOVER_OVERLAY_FILL } from "metabase/visualizations/echarts/graph/treemap/style";+import type { ComputedVisualizationSettings } from "metabase/visualizations/types";+import type { RawSeries } from "metabase-types/api";+import {+ createMockCard,+ createMockNativeCard,+} from "metabase-types/api/mocks/card";+import {+ createMockColumn,+ createMockDatasetData,+} from "metabase-types/api/mocks/dataset";++import {+ dispatchTreemapViewRoot,+ getTreemapClickData,+ getTreemapEventHandlers,+} from "./events";+import {+ type TreemapHoverOverlay,+ type TreemapHoverOverlayRef,+ hideTreemapHoverOverlay,+} from "./overlay";++const groupingCol = createMockColumn({+ name: "Category",+ display_name: "Category",+ base_type: "type/Text",+});+const subGroupingCol = createMockColumn({+ name: "Product",+ display_name: "Product",+ base_type: "type/Text",+});+const valueCol = createMockColumn({+ name: "Sales",+ display_name: "Sales",+ base_type: "type/Number",+ semantic_type: "type/Number",+});++const cols1 = [groupingCol, valueCol];+const cols2 = [groupingCol, subGroupingCol, valueCol];++const treemapColumns1: TreemapChartColumns = {+ grouping: { index: 0, column: groupingCol },+ value: { index: 1, column: valueCol },+};+const treemapColumns2: TreemapChartColumns = {+ grouping: { index: 0, column: groupingCol },+ subGrouping: { index: 1, column: subGroupingCol },+ value: { index: 2, column: valueCol },+};++// One root, two leaves.+const tree2: TreemapTree = [+ {+ rawName: "Legumes",+ displayName: "Legumes",+ value: 30,+ rowIndices: [0, 1],+ children: [+ {+ rawName: "Chickpeas",+ displayName: "Chickpeas",+ value: 20,+ rowIndices: [0],+ },+ {+ rawName: "Lentils",+ displayName: "Lentils",+ value: 10,+ rowIndices: [1],+ },+ ],+ },+];+// Two roots, no children.+const tree1: TreemapTree = [+ { rawName: "Legumes", displayName: "Legumes", value: 30, rowIndices: [0] },+ { rawName: "Grains", displayName: "Grains", value: 15, rowIndices: [1] },+];++const settings = {} as ComputedVisualizationSettings;++const rawSeries1 = [+ {+ card: createMockCard(),+ data: createMockDatasetData({+ cols: cols1,+ rows: [+ ["Legumes", 30],+ ["Grains", 15],+ ],+ }),+ },+] as RawSeries;+const rawSeries2 = [+ {+ card: createMockCard(),+ data: createMockDatasetData({+ cols: cols2,+ rows: [+ ["Legumes", "Chickpeas", 20],+ ["Legumes", "Lentils", 10],+ ],+ }),+ },+] as RawSeries;++// A click event carrying the path-encoded node id plus the nested DOM event+// that `getTreemapClickData` forwards onto the `ClickObject`.+function makeClickEvent(id: unknown) {+ const domEvent = {} as MouseEvent;+ return { data: { id }, event: { event: domEvent } };+}++function makeChartRef(overrides: Record<string, unknown> = {}) {+ const dispatchAction = jest.fn();+ const setOption = jest.fn();+ const add = jest.fn();+ const remove = jest.fn();+ const zr = { add, remove };+ const chartRef = {+ current: {+ dispatchAction,+ setOption,+ isDisposed: () => false,+ getZr: () => zr,+ ...overrides,+ },+ } as unknown as React.MutableRefObject<EChartsType | undefined>;+ return { chartRef, dispatchAction, setOption, add, remove };+}++function makeOverlayRef(): TreemapHoverOverlayRef {+ return { current: null };+}++describe("getTreemapRootNodeId", () => {+ it("returns the id unchanged for a top-level grouping node", () => {+ expect(getTreemapRootNodeId("0")).toBe("0");+ expect(getTreemapRootNodeId("2")).toBe("2");+ });++ it("returns the grouping segment for a sub-group leaf node", () => {+ expect(getTreemapRootNodeId("0-1")).toBe("0");+ expect(getTreemapRootNodeId("3-12")).toBe("3");+ });+});++function makeChartRefWithNode(id: string, rect: TreemapRect | null) {+ return makeChartRef({+ getModel: () => ({+ getSeriesByIndex: () => ({+ getRawData: () => ({+ tree: {+ root: {+ eachNode: (cb: (node: unknown) => void) =>+ cb({ getId: () => id, getLayout: () => rect }),+ },+ },+ }),+ }),+ }),+ });+}++describe("getTreemapEventHandlers", () => {+ const baseArgs = {+ chartRef: makeChartRef().chartRef,+ overlayRef: makeOverlayRef(),+ hasChildren: true,+ isDrilled: false,+ onDrillToGroup: jest.fn(),+ tree: tree2,+ treemapColumns: treemapColumns2,+ rawSeries: rawSeries2,+ settings,+ onVisualizationClick: jest.fn(),+ };++ it("drills DOWN (zoom) at the overview when there is sub-grouping", () => {+ const onDrillToGroup = jest.fn();+ const onVisualizationClick = jest.fn();+ const handlers = getTreemapEventHandlers({+ ...baseArgs,+ onDrillToGroup,+ onVisualizationClick,+ });++ const clickHandler = handlers.find((h) => h.eventName === "click");+ expect(clickHandler).toBeDefined();++ clickHandler?.handler(makeClickEvent("1-4"));+ expect(onDrillToGroup).toHaveBeenLastCalledWith("1");++ clickHandler?.handler(makeClickEvent("0"));+ expect(onDrillToGroup).toHaveBeenLastCalledWith("0");++ // Overview clicks zoom, they never drill through.+ expect(onVisualizationClick).not.toHaveBeenCalled();+ });++ it("drills THROUGH on a 1-level node click (no zoom exists)", () => {+ const onDrillToGroup = jest.fn();+ const onVisualizationClick = jest.fn();+ const handlers = getTreemapEventHandlers({+ ...baseArgs,+ hasChildren: false,+ tree: tree1,+ treemapColumns: treemapColumns1,+ rawSeries: rawSeries1,+ onDrillToGroup,+ onVisualizationClick,+ });++ handlers.find((h) => h.eventName === "click")?.handler(makeClickEvent("1"));++ expect(onDrillToGroup).not.toHaveBeenCalled();+ expect(onVisualizationClick).toHaveBeenCalledTimes(1);+ const clickData = onVisualizationClick.mock.calls[0][0];+ expect(clickData.value).toBe(15);+ expect(clickData.column).toBe(valueCol);+ expect(clickData.dimensions).toEqual([+ { column: groupingCol, value: "Grains" },+ ]);+ });++ it("drills THROUGH on a leaf click while drilled into a group (2-level)", () => {+ const onDrillToGroup = jest.fn();+ const onVisualizationClick = jest.fn();+ const handlers = getTreemapEventHandlers({+ ...baseArgs,+ isDrilled: true,+ onDrillToGroup,+ onVisualizationClick,+ });++ handlers+ .find((h) => h.eventName === "click")+ ?.handler(makeClickEvent("0-1"));++ expect(onDrillToGroup).not.toHaveBeenCalled();+ expect(onVisualizationClick).toHaveBeenCalledTimes(1);+ const clickData = onVisualizationClick.mock.calls[0][0];+ expect(clickData.value).toBe(10);+ expect(clickData.column).toBe(valueCol);+ expect(clickData.dimensions).toEqual([+ { column: groupingCol, value: "Legumes" },+ { column: subGroupingCol, value: "Lentils" },+ ]);+ });++ it("ignores clicks without a string node id (background)", () => {+ const onDrillToGroup = jest.fn();+ const onVisualizationClick = jest.fn();+ const handlers = getTreemapEventHandlers({+ ...baseArgs,+ onDrillToGroup,+ onVisualizationClick,+ });+ const clickHandler = handlers.find((h) => h.eventName === "click");++ clickHandler?.handler({ data: undefined });+ clickHandler?.handler({});+ clickHandler?.handler({ data: { id: 5 } });++ expect(onDrillToGroup).not.toHaveBeenCalled();+ expect(onVisualizationClick).not.toHaveBeenCalled();+ });++ it("wires hover overlay handlers both at the overview and while drilled", () => {+ for (const isDrilled of [false, true]) {+ const handlers = getTreemapEventHandlers({ ...baseArgs, isDrilled });+ expect(handlers.map((h) => h.eventName)).toEqual(+ expect.arrayContaining(["mouseover", "globalout"]),+ );+ }+ });++ it("washes the hovered element's whole section on mouseover at the overview", () => {+ const rect = { x: 10, y: 20, width: 100, height: 50 };+ const { chartRef, add } = makeChartRefWithNode("1", rect);+ const overlayRef = makeOverlayRef();+ const handlers = getTreemapEventHandlers({+ ...baseArgs,+ chartRef,+ overlayRef,+ });+ const mouseover = handlers.find((h) => h.eventName === "mouseover");++ // Hovering a leaf "1-4" overlays its top-level section "1".+ mouseover?.handler({ data: { id: "1-4" } });++ expect(add).toHaveBeenCalledTimes(1);+ expect(overlayRef.current?.shape).toMatchObject(rect);+ expect(overlayRef.current?.style).toMatchObject({+ fill: TREEMAP_HOVER_OVERLAY_FILL,+ });+ expect(overlayRef.current?.silent).toBe(true);+ });++ it("washes just the hovered leaf tile on mouseover while drilled", () => {+ const rect = { x: 10, y: 20, width: 100, height: 50 };+ const { chartRef, add } = makeChartRefWithNode("1-4", rect);+ const overlayRef = makeOverlayRef();+ const handlers = getTreemapEventHandlers({+ ...baseArgs,+ chartRef,+ overlayRef,+ isDrilled: true,+ });+ const mouseover = handlers.find((h) => h.eventName === "mouseover");++ // Drilled: hovering leaf "1-4" overlays that exact tile, not section "1".+ mouseover?.handler({ data: { id: "1-4" } });++ expect(add).toHaveBeenCalledTimes(1);+ expect(overlayRef.current?.shape).toMatchObject(rect);+ });++ it("repositions the existing overlay rather than adding a second one", () => {+ const first = { x: 0, y: 0, width: 10, height: 10 };+ const second = { x: 50, y: 50, width: 20, height: 20 };+ const { chartRef, add } = makeChartRefWithNode("1", first);+ const overlayRef = makeOverlayRef();+ const handlers = getTreemapEventHandlers({+ ...baseArgs,+ chartRef,+ overlayRef,+ });+ const mouseover = handlers.find((h) => h.eventName === "mouseover");++ mouseover?.handler({ data: { id: "1" } });+ // Re-point the fake chart's node rect, then hover again.+ (chartRef.current as unknown as { getModel: unknown }).getModel = () => ({+ getSeriesByIndex: () => ({+ getRawData: () => ({+ tree: {+ root: {+ eachNode: (cb: (node: unknown) => void) =>+ cb({ getId: () => "1", getLayout: () => second }),+ },+ },+ }),+ }),+ });+ mouseover?.handler({ data: { id: "1" } });++ expect(add).toHaveBeenCalledTimes(1);+ expect(overlayRef.current?.shape).toMatchObject(second);+ });++ it("does not paint an overlay when the section has no laid-out rect", () => {+ const { chartRef, add } = makeChartRefWithNode("1", null);+ const overlayRef = makeOverlayRef();+ const handlers = getTreemapEventHandlers({+ ...baseArgs,+ chartRef,+ overlayRef,+ });+ const mouseover = handlers.find((h) => h.eventName === "mouseover");++ mouseover?.handler({ data: { id: "1" } });++ expect(add).not.toHaveBeenCalled();+ expect(overlayRef.current).toBeNull();+ });++ it("clears the overlay when the cursor leaves the chart (globalout)", () => {+ const rect = { x: 10, y: 20, width: 100, height: 50 };+ const { chartRef, add, remove } = makeChartRefWithNode("1", rect);+ const overlayRef = makeOverlayRef();+ const handlers = getTreemapEventHandlers({+ ...baseArgs,+ chartRef,+ overlayRef,+ });++ handlers+ .find((h) => h.eventName === "mouseover")+ ?.handler({+ data: { id: "1" },+ });+ const overlay = overlayRef.current;+ expect(add).toHaveBeenCalledTimes(1);++ handlers.find((h) => h.eventName === "globalout")?.handler({});++ expect(remove).toHaveBeenCalledWith(overlay);+ expect(overlayRef.current).toBeNull();+ });+});++describe("getTreemapClickData", () => {+ it("returns null when the node id doesn't resolve to a tree node", () => {+ expect(+ getTreemapClickData({+ tree: tree2,+ id: "9-9",+ treemapColumns: treemapColumns2,+ rawSeries: rawSeries2,+ settings,+ event: makeClickEvent("9-9") as never,+ }),+ ).toBeNull();+ });++ it("omits dimensions for a native card (no field refs to filter on)", () => {+ const nativeRawSeries = [+ { card: createMockNativeCard(), data: rawSeries2[0].data },+ ] as RawSeries;++ const clickData = getTreemapClickData({+ tree: tree2,+ id: "0-1",+ treemapColumns: treemapColumns2,+ rawSeries: nativeRawSeries,+ settings,+ event: makeClickEvent("0-1") as never,+ });++ expect(clickData?.dimensions).toBeUndefined();+ expect(clickData?.value).toBe(10);+ });++ it("populates data with the clicked node's column values", () => {+ const clickData = getTreemapClickData({+ tree: tree2,+ id: "0-1",+ treemapColumns: treemapColumns2,+ rawSeries: rawSeries2,+ settings,+ event: makeClickEvent("0-1") as never,+ });++ expect(clickData?.data).toEqual([+ { col: groupingCol, value: "Legumes", key: "Category" },+ { col: subGroupingCol, value: "Lentils", key: "Product" },+ { col: valueCol, value: 10, key: "Sales" },+ ]);+ });+});++describe("hideTreemapHoverOverlay", () => {+ it("is a no-op when there's no overlay", () => {+ const { chartRef, remove } = makeChartRef();+ const overlayRef = makeOverlayRef();++ hideTreemapHoverOverlay(chartRef, overlayRef);++ expect(remove).not.toHaveBeenCalled();+ expect(overlayRef.current).toBeNull();+ });++ it("clears the ref even when the chart is already disposed", () => {+ const { chartRef, remove } = makeChartRef({ isDisposed: () => true });+ const overlayRef = {+ current: {} as TreemapHoverOverlay,+ };++ hideTreemapHoverOverlay(chartRef, overlayRef);++ expect(remove).not.toHaveBeenCalled();+ expect(overlayRef.current).toBeNull();+ });+});++describe("dispatchTreemapViewRoot", () => {+ it("dispatches treemapRootToNode for a drilled-in view root", () => {+ const { chartRef, dispatchAction } = makeChartRef();++ dispatchTreemapViewRoot(chartRef, "1");++ expect(dispatchAction).toHaveBeenCalledWith({+ type: "treemapRootToNode",+ seriesIndex: 0,+ targetNode: "1",+ });+ });++ it("does nothing for the overview (null view root) — setOption already renders the root", () => {+ const { chartRef, dispatchAction } = makeChartRef();++ dispatchTreemapViewRoot(chartRef, null);++ expect(dispatchAction).not.toHaveBeenCalled();+ });++ it("is a no-op when the chart isn't ready", () => {+ const chartRef = {+ current: undefined,+ } as React.MutableRefObject<EChartsType | undefined>;++ expect(() => dispatchTreemapViewRoot(chartRef, "0")).not.toThrow();+ });+});diff --git a/frontend/src/metabase/visualizations/visualizations/TreemapChart/index.ts b/frontend/src/metabase/visualizations/visualizations/TreemapChart/index.tsnew file mode 100644index 00000000000..4690ac275b6--- /dev/null+++ b/frontend/src/metabase/visualizations/visualizations/TreemapChart/index.ts@@ -0,0 +1 @@+export * from "./TreemapChart";diff --git a/frontend/src/metabase/visualizations/visualizations/TreemapChart/overlay.ts b/frontend/src/metabase/visualizations/visualizations/TreemapChart/overlay.tsnew file mode 100644index 00000000000..c81b9e99b18--- /dev/null+++ b/frontend/src/metabase/visualizations/visualizations/TreemapChart/overlay.ts@@ -0,0 +1,56 @@+import { type EChartsType, graphic } from "echarts/core";+import type { MutableRefObject } from "react";++import { getTreemapNodeRectById } from "metabase/visualizations/echarts/graph/treemap/model/tree";+import {+ HOVER_OVERLAY_Z,+ TREEMAP_HOVER_OVERLAY_FILL,+} from "metabase/visualizations/echarts/graph/treemap/style";++export type TreemapHoverOverlay = InstanceType<typeof graphic.Rect>;+export type TreemapHoverOverlayRef =+ MutableRefObject<TreemapHoverOverlay | null>;++export function showTreemapHoverOverlay(+ chartRef: MutableRefObject<EChartsType | undefined>,+ overlayRef: TreemapHoverOverlayRef,+ nodeId: string,+): void {+ const chart = chartRef.current;+ if (!chart) {+ return;+ }+ const rect = getTreemapNodeRectById(chart, nodeId);+ if (!rect) {+ return;+ }+ if (overlayRef.current == null) {+ overlayRef.current = new graphic.Rect({+ silent: true,+ z: HOVER_OVERLAY_Z,+ shape: rect,+ style: { fill: TREEMAP_HOVER_OVERLAY_FILL },+ });+ chart.getZr().add(overlayRef.current);+ } else {+ overlayRef.current.attr({+ shape: rect,+ style: { fill: TREEMAP_HOVER_OVERLAY_FILL },+ });+ }+}++export function hideTreemapHoverOverlay(+ chartRef: MutableRefObject<EChartsType | undefined>,+ overlayRef: TreemapHoverOverlayRef,+): void {+ const overlay = overlayRef.current;+ if (overlay === null) {+ return;+ }+ const chart = chartRef.current;+ if (chart && !chart.isDisposed()) {+ chart.getZr().remove(overlay);+ }+ overlayRef.current = null;+}diff --git a/frontend/src/metabase/visualizations/visualizations/TreemapChart/tooltip.tsx b/frontend/src/metabase/visualizations/visualizations/TreemapChart/tooltip.tsxnew file mode 100644index 00000000000..e06da05618a--- /dev/null+++ b/frontend/src/metabase/visualizations/visualizations/TreemapChart/tooltip.tsx@@ -0,0 +1,104 @@+import type { EChartsType } from "echarts/core";+import type { TooltipOption } from "echarts/types/dist/shared";+import _ from "underscore";++import { reactNodeToHtmlString } from "metabase/utils/react-to-html";+import { EChartsTooltip } from "metabase/visualizations/components/ChartTooltip/EChartsTooltip";+import { getTreemapNodeKey } from "metabase/visualizations/echarts/graph/treemap/model/data";+import {+ type TreemapInlineValueIds,+ getTreemapTooltipContext,+ getTreemapTooltipModel,+ isGroupHeaderNode,+ isPointerBelowGroupHeader,+ isTreemapTooltipSuppressed,+} from "metabase/visualizations/echarts/graph/treemap/model/tooltip";+import { getTreemapNodeRectById } from "metabase/visualizations/echarts/graph/treemap/model/tree";+import type {+ ChartPointer,+ TreemapNode,+ TreemapTree,+} from "metabase/visualizations/echarts/graph/treemap/model/types";+import { getTooltipBaseOption } from "metabase/visualizations/echarts/tooltip";++const hasId = (value: unknown): value is { id: unknown } =>+ _.isObject(value) && "id" in value;++export function getTreemapTooltipOption(+ tree: TreemapTree,+ colors: Record<string, string>,+ formatValue: (value: number) => string,+ formatPercent: (ratio: number) => string,+ containerRef: React.RefObject<HTMLDivElement>,+ getViewRootId: () => string | null,+ getIsClicked: () => boolean,+ getIsAnimating: () => boolean,+ getChart: () => EChartsType | undefined,+ getPointer: () => ChartPointer | null,+ headerHeight: number,+ inlineValueIds: TreemapInlineValueIds,+ groupingHeader?: string,+): TooltipOption {+ const isTwoLevel = tree.some((node) => node.children != null);+ return {+ ...getTooltipBaseOption(containerRef),+ trigger: "item",+ formatter: (params) => {+ if (getIsClicked() || getIsAnimating()) {+ return "";+ }+ if (Array.isArray(params)) {+ return "";+ }+ const id =+ hasId(params.data) && typeof params.data.id === "string"+ ? params.data.id+ : undefined;+ if (id == null) {+ return "";+ }+ const viewRootId = getViewRootId();+ if (+ isTreemapTooltipSuppressed(id, viewRootId, isTwoLevel, inlineValueIds)+ ) {+ return "";+ }++ if (isGroupHeaderNode(id, viewRootId, isTwoLevel)) {+ const chart = getChart();+ const pointer = getPointer();+ const rect = chart ? getTreemapNodeRectById(chart, id) : null;+ if (+ rect == null ||+ pointer == null ||+ isPointerBelowGroupHeader(rect, pointer, headerHeight)+ ) {+ return "";+ }+ }+ const context = getTreemapTooltipContext(+ tree,+ id,+ viewRootId,+ groupingHeader,+ );+ if (context == null) {+ return "";+ }++ const getColor = (node: TreemapNode) =>+ context.parentNode ? undefined : colors[getTreemapNodeKey(node)];++ return reactNodeToHtmlString(+ <EChartsTooltip+ {...getTreemapTooltipModel(+ context,+ getColor,+ formatValue,+ formatPercent,+ )}+ />,+ );+ },+ };+}diff --git a/frontend/src/metabase/visualizations/visualizations/TreemapChart/use-label-measurement.ts b/frontend/src/metabase/visualizations/visualizations/TreemapChart/use-label-measurement.tsnew file mode 100644index 00000000000..5d78043e186--- /dev/null+++ b/frontend/src/metabase/visualizations/visualizations/TreemapChart/use-label-measurement.ts@@ -0,0 +1,156 @@+import type { EChartsType } from "echarts/core";+import { type MutableRefObject, useCallback, useRef, useState } from "react";+import _ from "underscore";++import type { TreemapFormatters } from "metabase/visualizations/echarts/graph/treemap/model/formatters";+import type {+ ParentLabelLayout,+ TreemapLabelLayout,+} from "metabase/visualizations/echarts/graph/treemap/model/labels";+import { measureTreemapLabelLayouts } from "metabase/visualizations/echarts/graph/treemap/model/measure";+import { getTreemapLayoutNodes } from "metabase/visualizations/echarts/graph/treemap/model/tree";+import type {+ NodeId,+ TreemapTree,+} from "metabase/visualizations/echarts/graph/treemap/model/types";+import type { RenderingContext } from "metabase/visualizations/types";++interface UseLabelMeasurementOptions {+ chartRef: MutableRefObject<EChartsType | undefined>;+ tree: TreemapTree | null;+ formatters: TreemapFormatters | null;+ renderingContext: RenderingContext;+ /** The view root the chart is currently showing (null at the overview). */+ viewRootId: NodeId | null;+ showLeafLabels: boolean;+ showLeafValues: boolean;+ showParentValues: boolean;+ gridSize?: { width: number; height: number };+}++interface MeasurementKey {+ tree: TreemapTree | null;+ viewRootId: NodeId | null;+ renderingContext: RenderingContext | null;+ formatters: TreemapFormatters | null;+ showLeafLabels: boolean;+ showLeafValues: boolean;+ showParentValues: boolean;+ gridSize?: { width: number; height: number };+}++interface MeasuredLayouts extends MeasurementKey {+ leafLabelLayout: Record<NodeId, TreemapLabelLayout>;+ parentLabelLayout: Record<NodeId, ParentLabelLayout>;+}++const EMPTY_MEASURED: MeasuredLayouts = {+ tree: null,+ viewRootId: null,+ renderingContext: null,+ formatters: null,+ showLeafLabels: false,+ showLeafValues: false,+ showParentValues: false,+ gridSize: undefined,+ leafLabelLayout: {},+ parentLabelLayout: {},+};++function isMeasuredFor(measured: MeasurementKey, key: MeasurementKey): boolean {+ return (+ measured.tree === key.tree &&+ measured.viewRootId === key.viewRootId &&+ measured.renderingContext === key.renderingContext &&+ measured.formatters === key.formatters &&+ measured.showLeafLabels === key.showLeafLabels &&+ measured.showLeafValues === key.showLeafValues &&+ measured.showParentValues === key.showParentValues &&+ _.isEqual(measured.gridSize, key.gridSize)+ );+}++export function useLabelMeasurement({+ chartRef,+ tree,+ formatters,+ renderingContext,+ viewRootId,+ showLeafLabels,+ showLeafValues,+ showParentValues,+ gridSize,+}: UseLabelMeasurementOptions) {+ const [measured, setMeasured] = useState<MeasuredLayouts>(EMPTY_MEASURED);++ const currentKey: MeasurementKey = {+ tree,+ viewRootId,+ renderingContext,+ formatters,+ showLeafLabels,+ showLeafValues,+ showParentValues,+ gridSize,+ };+ const currentKeyRef = useRef(currentKey);+ currentKeyRef.current = currentKey;++ const handleLabelMeasure = useCallback(() => {+ const chart = chartRef.current;+ if (!chart || !tree || !formatters) {+ return;+ }+ const key: MeasurementKey = {+ tree,+ viewRootId,+ renderingContext,+ formatters,+ showLeafLabels,+ showLeafValues,+ showParentValues,+ gridSize,+ };+ const { leafLabelLayout, parentLabelLayout } = measureTreemapLabelLayouts({+ nodes: getTreemapLayoutNodes(chart),+ tree,+ formatters,+ renderingContext,+ showLeafLabels,+ showLeafValues,+ showParentValues,+ });+ setMeasured((prev) => {+ if (!isMeasuredFor(currentKeyRef.current, key)) {+ return prev;+ }+ return isMeasuredFor(prev, key) &&+ _.isEqual(prev.leafLabelLayout, leafLabelLayout) &&+ _.isEqual(prev.parentLabelLayout, parentLabelLayout)+ ? prev+ : { ...key, leafLabelLayout: leafLabelLayout, parentLabelLayout };+ });+ }, [+ chartRef,+ tree,+ formatters,+ renderingContext,+ viewRootId,+ showLeafLabels,+ showLeafValues,+ showParentValues,+ gridSize,+ ]);++ const isStale = !isMeasuredFor(measured, currentKey);++ return {+ labelLayout: isStale+ ? EMPTY_MEASURED.leafLabelLayout+ : measured.leafLabelLayout,+ parentLabelLayout: isStale+ ? EMPTY_MEASURED.parentLabelLayout+ : measured.parentLabelLayout,+ handleLabelMeasure,+ };+}diff --git a/frontend/src/metabase/visualizations/visualizations/TreemapChart/use-label-measurement.unit.spec.ts b/frontend/src/metabase/visualizations/visualizations/TreemapChart/use-label-measurement.unit.spec.tsnew file mode 100644index 00000000000..02169d0d00a--- /dev/null+++ b/frontend/src/metabase/visualizations/visualizations/TreemapChart/use-label-measurement.unit.spec.ts@@ -0,0 +1,169 @@+import { act, renderHook } from "@testing-library/react";+import type { EChartsType } from "echarts/core";+import type { MutableRefObject } from "react";++import type { TreemapFormatters } from "metabase/visualizations/echarts/graph/treemap/model/formatters";+import type { TreemapTree } from "metabase/visualizations/echarts/graph/treemap/model/types";+import { DEFAULT_VISUALIZATION_THEME } from "metabase/visualizations/shared/utils/theme";+import type { RenderingContext } from "metabase/visualizations/types";++import { useLabelMeasurement } from "./use-label-measurement";++const renderingContext: RenderingContext = {+ getColor: (name) => name,+ measureText: () => 10,+ measureTextHeight: () => 0,+ fontFamily: "",+ theme: DEFAULT_VISUALIZATION_THEME,+};++const formatters = {+ value: (value: number) => String(value),+ percent: (ratio: number) => `${ratio * 100}%`,+};++const TREE: TreemapTree = [+ {+ rawName: "G",+ displayName: "G",+ value: 100,+ rowIndices: [0, 1],+ children: [+ { rawName: "Big", displayName: "Big", value: 98, rowIndices: [0] },+ { rawName: "Tiny", displayName: "Tiny", value: 2, rowIndices: [1] },+ ],+ },+];++// A echarts fake laid-out tree exposing exactly what `getTreemapLayoutNodes` gets+function createMockChartRef(+ layouts: Record<string, { width: number; height: number }>,+) {+ const fakeNodes = Object.entries(layouts).map(([id, rect]) => ({+ getId: () => id,+ getLayout: () => ({ x: 0, y: 0, ...rect }),+ children: id.includes("-") ? [] : [{}],+ }));+ const chart = {+ getModel: () => ({+ getSeriesByIndex: () => ({+ getRawData: () => ({+ tree: {+ root: {+ eachNode: (cb: (node: unknown) => void) => fakeNodes.forEach(cb),+ },+ },+ }),+ }),+ }),+ } as unknown as EChartsType;+ return { current: chart } as MutableRefObject<EChartsType | undefined>;+}++type HookOverrides = Partial<{+ viewRootId: string | null;+ renderingContext: RenderingContext;+ formatters: TreemapFormatters;+ showLeafLabels: boolean;+ showLeafValues: boolean;+ showParentValues: boolean;+ gridSize: { width: number; height: number };+}>;++function setup(initialProps: HookOverrides = {}) {+ const chartRef = createMockChartRef({+ "0": { width: 600, height: 400 },+ "0-0": { width: 400, height: 400 },+ "0-1": { width: 200, height: 400 },+ });++ return renderHook(+ (props: HookOverrides) =>+ useLabelMeasurement({+ chartRef,+ tree: TREE,+ formatters,+ renderingContext,+ viewRootId: null,+ showLeafLabels: true,+ showLeafValues: true,+ showParentValues: true,+ gridSize: undefined,+ ...props,+ }),+ { initialProps },+ );+}++describe("useLabelMeasurement", () => {+ it("starts with empty layout maps before the first measurement", () => {+ const { result } = setup();++ expect(result.current.labelLayout).toEqual({});+ expect(result.current.parentLabelLayout).toEqual({});+ });++ it("exposes the measured layouts after a finished-event measurement", () => {+ const { result } = setup();++ act(() => result.current.handleLabelMeasure());++ expect(result.current.labelLayout["0-0"]).toMatchObject({+ detail: expect.not.stringMatching("none"),+ });+ expect(result.current.labelLayout["0-1"]).toMatchObject({+ detail: expect.not.stringMatching("none"),+ });+ expect(result.current.parentLabelLayout["0"]).toMatchObject({+ showText: true,+ });+ });++ it("hides labels on zoomin and zoom out animations", () => {+ const { result, rerender } = setup();++ rerender({ viewRootId: "0" });+ expect(result.current.labelLayout).toEqual({});+ expect(result.current.parentLabelLayout).toEqual({});++ act(() => result.current.handleLabelMeasure());+ expect(result.current.labelLayout["0-0"]).toMatchObject({+ detail: expect.not.stringMatching("none"),+ });++ rerender({ viewRootId: null });+ expect(result.current.labelLayout).toEqual({});++ act(() => result.current.handleLabelMeasure());++ expect(result.current.labelLayout["0-1"]).toMatchObject({+ detail: expect.not.stringMatching("none"),+ });+ });++ it("becomes stale when gridSize changes and re-measures from the new size", () => {+ const { result, rerender } = setup();++ act(() => result.current.handleLabelMeasure());+ expect(result.current.labelLayout["0-0"]).toMatchObject({+ detail: expect.not.stringMatching("none"),+ });++ rerender({ gridSize: { width: 10, height: 10 } });+ expect(result.current.labelLayout).toEqual({});++ act(() => result.current.handleLabelMeasure());+ expect(result.current.labelLayout["0-0"]).toMatchObject({+ detail: expect.not.stringMatching("none"),+ });+ });++ it("reports no leaf labels when leaf labels are turned off so tooltips can show", () => {+ const { result } = setup({ showLeafLabels: false });++ act(() => result.current.handleLabelMeasure());++ expect(result.current.labelLayout["0-0"]).toMatchObject({ detail: "none" });+ expect(result.current.labelLayout["0-1"]).toMatchObject({ detail: "none" });+ });+});diff --git a/frontend/src/metabase/visualizations/visualizations/TreemapChart/use-pointer-tracking.ts b/frontend/src/metabase/visualizations/visualizations/TreemapChart/use-pointer-tracking.tsnew file mode 100644index 00000000000..0299318dec0--- /dev/null+++ b/frontend/src/metabase/visualizations/visualizations/TreemapChart/use-pointer-tracking.ts@@ -0,0 +1,33 @@+import { useCallback, useMemo, useRef } from "react";++import type { ChartPointer } from "metabase/visualizations/echarts/graph/treemap/model/types";+import type { ZREventHandler } from "metabase/visualizations/types/echarts";++export function usePointerTracking(): {+ zrEventHandlers: ZREventHandler[];+ getPointer: () => ChartPointer | null;+} {+ const pointerRef = useRef<ChartPointer | null>(null);++ const zrEventHandlers = useMemo<ZREventHandler[]>(+ () => [+ {+ eventName: "mousemove",+ handler: (event: { offsetX: number; offsetY: number }) => {+ pointerRef.current = { x: event.offsetX, y: event.offsetY };+ },+ },+ {+ eventName: "globalout",+ handler: () => {+ pointerRef.current = null;+ },+ },+ ],+ [],+ );++ const getPointer = useCallback(() => pointerRef.current, []);++ return { zrEventHandlers, getPointer };+}diff --git a/frontend/src/metabase/visualizations/visualizations/TreemapChart/use-treemap-navigation.ts b/frontend/src/metabase/visualizations/visualizations/TreemapChart/use-treemap-navigation.tsnew file mode 100644index 00000000000..d58c3badebe--- /dev/null+++ b/frontend/src/metabase/visualizations/visualizations/TreemapChart/use-treemap-navigation.ts@@ -0,0 +1,60 @@+import {+ type MutableRefObject,+ useCallback,+ useEffect,+ useRef,+ useState,+} from "react";+import { useLatest } from "react-use";++import { getTreemapNodeKey } from "metabase/visualizations/echarts/graph/treemap/model/data";+import {+ getNode,+ getTreemapNodeId,+} from "metabase/visualizations/echarts/graph/treemap/model/tree";+import type {+ NodeId,+ TreemapTree,+} from "metabase/visualizations/echarts/graph/treemap/model/types";++interface TreemapNavigation {+ viewRootId: NodeId | null;+ viewRootIdRef: MutableRefObject<NodeId | null>;+ setViewRoot: (id: NodeId | null) => void;+}++export function useTreemapNavigation(+ tree: TreemapTree | null,+): TreemapNavigation {+ const [viewRootId, setViewRootId] = useState<NodeId | null>(null);+ const viewRootIdRef = useRef<NodeId | null>(null);+ const viewRootKeyRef = useRef<string | null>(null);+ const treeRef = useLatest(tree);++ const setViewRoot = useCallback(+ (id: NodeId | null) => {+ viewRootIdRef.current = id;+ const node = id != null ? getNode(id, treeRef.current ?? []) : null;+ viewRootKeyRef.current = node != null ? getTreemapNodeKey(node) : null;+ setViewRootId(id);+ },+ [treeRef],+ );++ useEffect(() => {+ const drilledKey = viewRootKeyRef.current;+ if (drilledKey == null) {+ return;+ }+ const nodes = tree ?? [];+ const index = nodes.findIndex(+ (node) => getTreemapNodeKey(node) === drilledKey,+ );+ const nextId = index === -1 ? null : getTreemapNodeId(index);+ if (nextId !== viewRootIdRef.current) {+ setViewRoot(nextId);+ }+ }, [tree, setViewRoot]);++ return { viewRootId, viewRootIdRef, setViewRoot };+}diff --git a/resources/frontend_client/app/assets/img/empty-states/visualizations/treemap.svg b/resources/frontend_client/app/assets/img/empty-states/visualizations/treemap.svgnew file mode 100644index 00000000000..4ee1d8d72f6--- /dev/null+++ b/resources/frontend_client/app/assets/img/empty-states/visualizations/treemap.svg@@ -0,0 +1 @@+<svg xmlns="http://www.w3.org/2000/svg" width="320" height="200" fill="none"><g clip-path="url(#a)"><path fill="url(#b)" fill-opacity=".15" d="M161 0h79v99h-79z"/><path fill="#f3f3f4" d="M241 0h71a8 8 0 0 1 8 8v41h-79z"/><path fill="url(#c)" fill-opacity=".05" d="M241 0h71a8 8 0 0 1 8 8v41h-79z"/><path fill="#f3f3f4" d="M241 50h79v49h-79zM161 100h118v100H161z"/><path fill="url(#d)" fill-opacity=".05" d="M161 100h118v100H161z"/><path fill="url(#e)" fill-opacity=".15" d="M280 100h40v92a8 8 0 0 1-8 8h-32z"/><path fill="#f3f3f4" d="M0 8a8 8 0 0 1 8-8h152v200H8a8 8 0 0 1-8-8z"/></g><defs><linearGradient id="b" x1="200.5" x2="200.5" y1="3.328" y2="99" gradientUnits="userSpaceOnUse"><stop stop-color="#2f3c45"/><stop offset="1" stop-color="#2f3c45"/></linearGradient><linearGradient id="c" x1="280.5" x2="280.5" y1="1.647" y2="49" gradientUnits="userSpaceOnUse"><stop stop-color="#2f3c45" stop-opacity=".5"/><stop offset="1" stop-color="#2f3c45"/></linearGradient><linearGradient id="d" x1="220" x2="220" y1="103.361" y2="200" gradientUnits="userSpaceOnUse"><stop stop-color="#2f3c45" stop-opacity=".5"/><stop offset="1" stop-color="#2f3c45"/></linearGradient><linearGradient id="e" x1="300" x2="300" y1="103.361" y2="200" gradientUnits="userSpaceOnUse"><stop stop-color="#2f3c45"/><stop offset="1" stop-color="#2f3c45"/></linearGradient><clipPath id="a"><path fill="#fff" d="M0 0h320v200H0z"/></clipPath></defs></svg>\ No newline at end of filediff --git a/src/metabase/channel/render/card.clj b/src/metabase/channel/render/card.cljindex c5e1ce9f04e..0c39cbf0b6a 100644--- a/src/metabase/channel/render/card.clj+++ b/src/metabase/channel/render/card.clj@@ -182,6 +182,7 @@(#{:smartscalar:progress:sankey+ :treemap:scalar:pie:scatterdiff --git a/test/metabase/channel/render/body_test.clj b/test/metabase/channel/render/body_test.cljindex 668356cc93b..ef572d4b7ba 100644--- a/test/metabase/channel/render/body_test.clj+++ b/test/metabase/channel/render/body_test.clj@@ -1187,6 +1187,27 @@(testing "Renders with at least one category name visible"(is (= "Doohickey" category-text)))))))))+(deftest render-treemap-chart-test+ (testing "The static-viz treemap chart renders correctly."+ (mt/dataset test-data+ (let [q (mt/mbql-query products+ {:aggregation [[:count]]+ :breakout [$category $vendor]})+ card {:name "treemap-test"+ :display :treemap+ :dataset_query q+ :visualization_settings+ {:treemap.grouping "CATEGORY"+ :treemap.sub_grouping "VENDOR"+ :treemap.value "count"}}]+ (mt/with-temp [:model/Card {card-id :id} card]+ (let [doc (render.tu/render-card-as-hickory! card-id)+ category-text (->> (hik.s/select (hik.s/find-in-text #"Doohickey") doc)+ (map (fn [el] (-> el :content first)))+ first)]+ (testing "Renders with at least one category name visible"+ (is (= "Doohickey" category-text)))))))))+(deftest render-correct-day-of-week-test(testing "The static-viz bar chart renders with the correct start of the week."(mt/with-temporary-setting-values [start-of-week "monday"]diff --git a/test/metabase/channel/render/card_test.clj b/test/metabase/channel/render/card_test.cljindex 3efb638f829..c210022cda6 100644--- a/test/metabase/channel/render/card_test.clj+++ b/test/metabase/channel/render/card_test.clj@@ -293,6 +293,17 @@:rows [["apple" 3]["banana" 4]]})))))+(deftest ^:parallel detect-pulse-chart-type-test-8b+ (testing "Treemap charts are correctly identified and return `:javascript_visualization`."+ (is (= :javascript_visualization+ (channel.render/detect-pulse-chart-type {:display :treemap}+ nil+ {:cols [{:base_type :type/Text}+ {:base_type :type/Text}+ {:base_type :type/Number}]+ :rows [["apple" "fuji" 3]+ ["banana" "cavendish" 4]]})))))+(deftest ^:parallel detect-pulse-chart-type-test-9(testing "Dashboard Cards can return `:multiple`."(is (= :javascript_visualization