Skip to content

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

Adding folded row chart tooltip and drill to row charts (#84715)

Nick Fitzpatrickf75513208da2
diff --git a/frontend/src/metabase/visualizations/visualizations/CartesianChart/events.ts b/frontend/src/metabase/visualizations/visualizations/CartesianChart/events.ts
index b1ae27b01d4..00fa178657e 100644
--- a/frontend/src/metabase/visualizations/visualizations/CartesianChart/events.ts
+++ b/frontend/src/metabase/visualizations/visualizations/CartesianChart/events.ts
@@ -153,7 +153,14 @@ export const getEventDimensions = (
const hasDimensionValue = sameCardDatumColumns.includes(dimensionColumn);
const dimensions: ClickObjectDimension[] = [];
- if (hasDimensionValue) {
+ if (datum[IS_FOLDED_ROW_DATA_KEY]) {
+ dimensions.push({
+ column: dimensionColumn,
+ value: (chartModel.foldedDataset ?? []).map((foldedDatum) =>
+ normalizeDimensionValue(dimensionColumn, foldedDatum[X_AXIS_DATA_KEY]),
+ ),
+ });
+ } else if (hasDimensionValue) {
dimensions.push({
column: dimensionColumn,
value: normalizeDimensionValue(dimensionColumn, datum[X_AXIS_DATA_KEY]),
@@ -458,6 +465,10 @@ export const getTooltipModel = (
return null;
}
+ if (datum[IS_FOLDED_ROW_DATA_KEY]) {
+ return getFoldedRowTooltipModel(chartModel, settings, datum, hoveredSeries);
+ }
+
const seriesStack = chartModel.stackModels.find((stackModel) =>
stackModel.seriesKeys.includes(hoveredSeries.dataKey),
);
@@ -494,6 +505,71 @@ export const getTooltipModel = (
);
};
+// The hovered series leads, as the tooltip's one full-emphasis value column.
+const getFoldedRowTooltipSeries = (
+ chartModel: BaseCartesianChartModel,
+ hoveredSeries: SeriesModel,
+): SeriesModel[] => [
+ hoveredSeries,
+ ...chartModel.seriesModels.filter(
+ (seriesModel) =>
+ seriesModel.visible && seriesModel.dataKey !== hoveredSeries.dataKey,
+ ),
+];
+
+const getFoldedRowTooltipModel = (
+ chartModel: BaseCartesianChartModel,
+ settings: ComputedVisualizationSettings,
+ datum: Datum,
+ hoveredSeries: SeriesModel,
+): EChartsTooltipModel => {
+ const tooltipSeries = getFoldedRowTooltipSeries(chartModel, hoveredSeries);
+ const formatSeriesValues = (seriesDatum: Datum) =>
+ tooltipSeries.map(({ dataKey, column }) =>
+ String(
+ formatValueForTooltip({
+ value: seriesDatum[dataKey],
+ column,
+ settings,
+ isAlreadyScaled: true,
+ }),
+ ),
+ );
+
+ const markerColorClass = getMarkerColorClass(hoveredSeries.color);
+
+ const seriesNamesRows: EChartsTooltipRow[] =
+ tooltipSeries.length > 1
+ ? [
+ {
+ name: "",
+ isSecondary: true,
+ values: tooltipSeries.map((seriesModel) => seriesModel.name),
+ },
+ ]
+ : [];
+
+ const categoryRows: EChartsTooltipRow[] = (
+ chartModel.foldedDataset ?? []
+ ).map((foldedDatum) => ({
+ name: String(
+ formatValueForTooltip({
+ value: foldedDatum[X_AXIS_DATA_KEY],
+ column: chartModel.dimensionModel.column,
+ settings,
+ }),
+ ),
+ markerColorClass,
+ values: formatSeriesValues(foldedDatum),
+ }));
+
+ return {
+ header: String(datum[X_AXIS_DATA_KEY]),
+ rows: [...seriesNamesRows, ...categoryRows],
+ footer: { name: t`Total`, values: formatSeriesValues(datum) },
+ };
+};
+
const getSingleSeriesTooltipModel = (
chartModel: BaseCartesianChartModel,
datum: Datum,
@@ -925,8 +1001,11 @@ export const getSeriesClickData = (
}
const datum = chartModel.dataset[dataIndex];
- // A row chart's folded "Other" row has no single category to drill into.
- if (datum[IS_FOLDED_ROW_DATA_KEY]) {
+ // Binned drills filter to a single bin, not the folded row's set of bins.
+ const isFoldedBinnedRow =
+ datum[IS_FOLDED_ROW_DATA_KEY] &&
+ chartModel.dimensionModel.column.binning_info != null;
+ if (isFoldedBinnedRow) {
return null;
}
diff --git a/frontend/src/metabase/visualizations/visualizations/CartesianChart/events.unit.spec.ts b/frontend/src/metabase/visualizations/visualizations/CartesianChart/events.unit.spec.ts
index 1fe81339cfb..a00bd32dcc6 100644
--- a/frontend/src/metabase/visualizations/visualizations/CartesianChart/events.unit.spec.ts
+++ b/frontend/src/metabase/visualizations/visualizations/CartesianChart/events.unit.spec.ts
@@ -11,11 +11,14 @@ import {
type EChartsSeriesBrushEndEvent,
type EChartsSeriesBrushSelectedEvent,
type EChartsSeriesMouseEvent,
+ type EChartsTooltipModel,
INDEX_KEY,
+ ROW_CHART_MIN_BAR_HEIGHT,
X_AXIS_DATA_KEY,
foldRowChartModel,
getDatasetKey,
} from "metabase/viz-core";
+import type { DatasetColumn } from "metabase-types/api";
import {
createMockColumn,
createMockDatetimeColumn,
@@ -863,19 +866,89 @@ describe("getTooltipModel", () => {
describe("row chart folded Other row", () => {
const COUNT_KEY = "count";
- const CATEGORIES = ["A", "B", "C", "D", "E"];
+ const SUM_KEY = "sum";
- // Five rows in a chart tall enough for two: one kept row plus "Other (4)".
- const getFoldedChartModel = () => {
- const dataset: Datum[] = CATEGORIES.map((category, index) => ({
- [X_AXIS_DATA_KEY]: category,
- [COUNT_KEY]: 10 * (index + 1),
+ const categoryColumn = createMockColumn({
+ name: "CATEGORY",
+ display_name: "Category",
+ source: "breakout",
+ base_type: "type/Text",
+ effective_type: "type/Text",
+ });
+ const countColumn = createMockColumn({
+ name: COUNT_KEY,
+ source: "aggregation",
+ base_type: "type/Integer",
+ effective_type: "type/Integer",
+ });
+ const sumColumn = createMockColumn({
+ name: SUM_KEY,
+ source: "aggregation",
+ base_type: "type/Integer",
+ effective_type: "type/Integer",
+ });
+
+ interface ExtraSeries {
+ dataKey: string;
+ values: number[];
+ visible?: boolean;
+ }
+
+ interface SetupOpts {
+ counts?: number[];
+ sums?: number[];
+ extraSeries?: ExtraSeries[];
+ dimensionColumn?: DatasetColumn;
+ }
+
+ // Categories C1, C2, … where C1 is kept and the rest fold into "Other".
+ const getFoldedChartModel = ({
+ counts = [50, 10, 30, 20, 40],
+ sums,
+ extraSeries = [],
+ dimensionColumn = categoryColumn,
+ }: SetupOpts = {}) => {
+ const dataset: Datum[] = counts.map((count, index) => ({
+ [X_AXIS_DATA_KEY]: `C${index + 1}`,
+ [COUNT_KEY]: count,
+ ...(sums && { [SUM_KEY]: sums[index] }),
+ ...Object.fromEntries(
+ extraSeries.map(({ dataKey, values }) => [dataKey, values[index]]),
+ ),
}));
+ const seriesModels = [
+ createMockSeriesModel({ dataKey: COUNT_KEY, column: countColumn }),
+ ...(sums
+ ? [createMockSeriesModel({ dataKey: SUM_KEY, column: sumColumn })]
+ : []),
+ ...extraSeries.map(({ dataKey, visible = true }) =>
+ createMockSeriesModel({
+ dataKey,
+ visible,
+ column: createMockColumn({
+ name: dataKey,
+ source: "aggregation",
+ base_type: "type/Integer",
+ effective_type: "type/Integer",
+ }),
+ }),
+ ),
+ ];
+ const visibleSeriesCount = seriesModels.filter(
+ (seriesModel) => seriesModel.visible,
+ ).length;
+ // Two rows fit: unstacked, each row needs a band per visible series.
+ const chartHeight = 2 * ROW_CHART_MIN_BAR_HEIGHT * visibleSeriesCount;
return foldRowChartModel(
{
...createMockCartesianChartModel({
- seriesModels: [createMockSeriesModel({ dataKey: COUNT_KEY })],
- seriesIdToDataKey: { [COUNT_KEY]: COUNT_KEY },
+ dimensionModel: {
+ column: dimensionColumn,
+ columnIndex: 0,
+ columnByCardId: {},
+ columns: [dimensionColumn],
+ },
+ seriesModels,
dataset,
transformedDataset: dataset.map((datum, index) => ({
...datum,
@@ -892,7 +965,7 @@ describe("row chart folded Other row", () => {
totalNumberOfLabels: 0,
},
},
- 48,
+ chartHeight,
createMockVisualizationSettings(),
);
};
@@ -907,20 +980,116 @@ describe("row chart folded Other row", () => {
const OTHER_INDEX = 1;
- it("names the Other row in its tooltip", () => {
- const chartModel = getFoldedChartModel();
-
- const tooltipModel = getTooltipModel(
+ const getFoldedRowTooltip = (
+ chartModel: ReturnType<typeof getFoldedChartModel>,
+ seriesDataKey = COUNT_KEY,
+ ) =>
+ getTooltipModel(
chartModel,
createMockVisualizationSettings(),
OTHER_INDEX,
"row",
- COUNT_KEY,
+ seriesDataKey,
);
+ const getRowTexts = (tooltipModel: EChartsTooltipModel | null) =>
+ tooltipModel?.rows.map((row) => [row.name, ...row.values]);
+
+ it("names the Other row in its tooltip", () => {
+ const tooltipModel = getFoldedRowTooltip(getFoldedChartModel());
+
expect(tooltipModel?.header).toBe("Other (4)");
});
+ it("lists the folded categories in chart order, with their total", () => {
+ const tooltipModel = getFoldedRowTooltip(getFoldedChartModel());
+
+ expect(getRowTexts(tooltipModel)).toEqual([
+ ["C2", "10"],
+ ["C3", "30"],
+ ["C4", "20"],
+ ["C5", "40"],
+ ]);
+ expect(tooltipModel?.footer).toEqual({ name: "Total", values: ["100"] });
+ });
+
+ it("lists every folded category, however many there are", () => {
+ // C1 is kept; C2 (1) … C15 (14) fold.
+ const foldedCounts = Array.from({ length: 14 }, (_, i) => i + 1);
+
+ const tooltipModel = getFoldedRowTooltip(
+ getFoldedChartModel({ counts: [100, ...foldedCounts] }),
+ );
+
+ expect(getRowTexts(tooltipModel)).toEqual(
+ foldedCounts.map((count) => [`C${count + 1}`, String(count)]),
+ );
+ expect(tooltipModel?.footer).toEqual({ name: "Total", values: ["105"] });
+ });
+
+ it("lists every series' values, the hovered series first, when there are several series", () => {
+ const chartModel = getFoldedChartModel({
+ counts: [50, 10, 30, 20, 40],
+ sums: [1, 400, 100, 300, 200],
+ });
+
+ const tooltipModel = getFoldedRowTooltip(chartModel, SUM_KEY);
+
+ expect(getRowTexts(tooltipModel)).toEqual([
+ ["", "name for sum", "name for count"],
+ ["C2", "400", "10"],
+ ["C3", "100", "30"],
+ ["C4", "300", "20"],
+ ["C5", "200", "40"],
+ ]);
+ expect(tooltipModel?.footer).toEqual({
+ name: "Total",
+ values: ["1,000", "100"],
+ });
+ });
+
+ it("leaves hidden series out of the Other tooltip", () => {
+ const chartModel = getFoldedChartModel({
+ sums: [1, 400, 100, 300, 200],
+ extraSeries: [
+ { dataKey: "avg", values: [5, 4, 3, 2, 1] },
+ { dataKey: "max", values: [9, 9, 9, 9, 9], visible: false },
+ ],
+ });
+
+ const tooltipModel = getFoldedRowTooltip(chartModel);
+
+ expect(tooltipModel?.rows[0].values).toEqual([
+ "name for count",
+ "name for sum",
+ "name for avg",
+ ]);
+ });
+
+ it("lists every visible series, however many there are", () => {
+ const chartModel = getFoldedChartModel({
+ sums: [1, 400, 100, 300, 200],
+ extraSeries: [
+ { dataKey: "avg", values: [5, 4, 3, 2, 1] },
+ { dataKey: "max", values: [9, 8, 7, 6, 5] },
+ ],
+ });
+
+ const tooltipModel = getFoldedRowTooltip(chartModel);
+
+ expect(getRowTexts(tooltipModel)).toEqual([
+ ["", "name for count", "name for sum", "name for avg", "name for max"],
+ ["C2", "10", "400", "4", "8"],
+ ["C3", "30", "100", "3", "7"],
+ ["C4", "20", "300", "2", "6"],
+ ["C5", "40", "200", "1", "5"],
+ ]);
+ expect(tooltipModel?.footer).toEqual({
+ name: "Total",
+ values: ["100", "1,000", "10", "26"],
+ });
+ });
+
it("reports hovering the Other row, so the rest of the chart dims", () => {
const chartModel = getFoldedChartModel();
@@ -929,12 +1098,35 @@ describe("row chart folded Other row", () => {
);
});
- it("does not drill into the Other row, like the legacy renderer", () => {
+ it("drills into the Other row by filtering to its folded categories", () => {
const chartModel = getFoldedChartModel();
+ expect(
+ getSeriesClickData(chartModel, {}, createMouseEvent(OTHER_INDEX)),
+ ).toMatchObject({
+ column: countColumn,
+ value: 100,
+ dimensions: [{ column: categoryColumn, value: ["C2", "C3", "C4", "C5"] }],
+ });
+ });
+
+ it("does not drill into the Other row of a binned dimension, whose drills take one bin", () => {
+ const binnedColumn = createMockColumn({
+ ...categoryColumn,
+ base_type: "type/Float",
+ effective_type: "type/Float",
+ binning_info: { binning_strategy: "num-bins", num_bins: 100 },
+ });
+ const chartModel = getFoldedChartModel({ dimensionColumn: binnedColumn });
+
expect(
getSeriesClickData(chartModel, {}, createMouseEvent(OTHER_INDEX)),
).toBeNull();
+ });
+
+ it("drills into a kept row by its own category", () => {
+ const chartModel = getFoldedChartModel();
+
expect(
getSeriesClickData(chartModel, {}, createMouseEvent(0)),
).not.toBeNull();
diff --git a/frontend/src/metabase/viz-core/echarts/cartesian/model/row-fold.ts b/frontend/src/metabase/viz-core/echarts/cartesian/model/row-fold.ts
index 709ccb7b8f6..03a244a0443 100644
--- a/frontend/src/metabase/viz-core/echarts/cartesian/model/row-fold.ts
+++ b/frontend/src/metabase/viz-core/echarts/cartesian/model/row-fold.ts
@@ -10,11 +10,11 @@ import { applyVisualizationSettingsDataTransformations } from "./dataset";
import type { BaseCartesianChartModel, ChartDataset, Datum } from "./types";
// Rows that don't fit fold into one summed "Other" row. One rule for app and
-// email: each band (per series, or one when stacked) needs MIN_BAR_HEIGHT.
-export const MIN_BAR_HEIGHT = 24;
+// email: each band (per series, or one when stacked) needs this much height.
+export const ROW_CHART_MIN_BAR_HEIGHT = 24;
const getRowChartBudget = (chartHeight: number, bandCount: number): number =>
- Math.max(Math.floor(chartHeight / (MIN_BAR_HEIGHT * bandCount)), 1);
+ Math.max(Math.floor(chartHeight / (ROW_CHART_MIN_BAR_HEIGHT * bandCount)), 1);
const sumInto = (target: Datum, source: Datum, keys: string[]) => {
keys.forEach((key) => {
@@ -32,7 +32,7 @@ const foldDataset = (
dataset: ChartDataset,
budget: number,
seriesKeys: string[],
-): ChartDataset => {
+): { dataset: ChartDataset; foldedDataset: ChartDataset } => {
const kept = dataset.slice(0, budget - 1);
const folded = dataset.slice(budget - 1);
@@ -47,7 +47,7 @@ const foldDataset = (
};
folded.forEach((datum) => sumInto(total, datum, seriesKeys));
- return [...kept, total];
+ return { dataset: [...kept, total], foldedDataset: folded };
};
export const foldRowChartModel = <Model extends BaseCartesianChartModel>(
@@ -76,7 +76,11 @@ export const foldRowChartModel = <Model extends BaseCartesianChartModel>(
...chartModel.seriesModels,
...(chartModel.groupedSeriesModels ?? []),
].map((series) => series.dataKey);
- const dataset = foldDataset(chartModel.dataset, budget, seriesKeys);
+ const { dataset, foldedDataset } = foldDataset(
+ chartModel.dataset,
+ budget,
+ seriesKeys,
+ );
const transformedDataset = applyVisualizationSettingsDataTransformations(
dataset,
chartModel.stackModels,
@@ -91,6 +95,7 @@ export const foldRowChartModel = <Model extends BaseCartesianChartModel>(
...chartModel,
dataset,
transformedDataset,
+ foldedDataset,
// "Other" can exceed every row's range; row charts only have a left axis.
leftAxisModel: chartModel.leftAxisModel && {
...chartModel.leftAxisModel,
diff --git a/frontend/src/metabase/viz-core/echarts/cartesian/model/row-fold.unit.spec.ts b/frontend/src/metabase/viz-core/echarts/cartesian/model/row-fold.unit.spec.ts
index e1c80c95f3a..c850f126626 100644
--- a/frontend/src/metabase/viz-core/echarts/cartesian/model/row-fold.unit.spec.ts
+++ b/frontend/src/metabase/viz-core/echarts/cartesian/model/row-fold.unit.spec.ts
@@ -14,7 +14,7 @@ import { DEFAULT_VISUALIZATION_THEME } from "../../../shared/utils/theme";
import type { RenderingContext } from "../../../types";
import { OTHER_DATA_KEY } from "../constants/dataset";
-import { MIN_BAR_HEIGHT, foldRowChartModel } from "./row-fold";
+import { ROW_CHART_MIN_BAR_HEIGHT, foldRowChartModel } from "./row-fold";
import { getCartesianChartModel } from "./index";
@@ -61,7 +61,7 @@ const single = (values: number[]) => values.map((value) => [value]);
describe("foldRowChartModel", () => {
const ROW_BUDGET = 4;
- const chartHeight = ROW_BUDGET * MIN_BAR_HEIGHT;
+ const chartHeight = ROW_BUDGET * ROW_CHART_MIN_BAR_HEIGHT;
it("refits the metric axis to the folded Other row's total", () => {
const model = getModel(single([100, 100, 100, 100, 100, 100, 100, 100]));
@@ -83,6 +83,16 @@ describe("foldRowChartModel", () => {
expect(folded.leftAxisModel?.extent).toEqual([-150, 300]);
});
+ it("keeps the rows folded into Other, in order, without rendering them", () => {
+ const model = getModel(single([800, 700, 600, 500, 400, 300, 200, 100]));
+
+ const folded = foldRowChartModel(model, chartHeight, settings);
+
+ expect(folded.foldedDataset).toEqual(model.dataset.slice(ROW_BUDGET - 1));
+ expect(folded.dataset).toHaveLength(ROW_BUDGET);
+ expect(folded.transformedDataset).toHaveLength(ROW_BUDGET);
+ });
+
it("leaves a model that fits untouched", () => {
const model = getModel(single([100, 200, 300]));
diff --git a/frontend/src/metabase/viz-core/echarts/cartesian/model/types.ts b/frontend/src/metabase/viz-core/echarts/cartesian/model/types.ts
index 65b27742324..0a663164cf1 100644
--- a/frontend/src/metabase/viz-core/echarts/cartesian/model/types.ts
+++ b/frontend/src/metabase/viz-core/echarts/cartesian/model/types.ts
@@ -256,6 +256,9 @@ export type BaseCartesianChartModel = {
// For `graph.max_categories` setting
groupedSeriesModels?: SeriesModel[];
+
+ // Row chart rows summed into the folded "Other" row
+ foldedDataset?: ChartDataset;
};
export type CartesianChartModel = BaseCartesianChartModel & {
diff --git a/frontend/src/metabase/viz-core/index.ts b/frontend/src/metabase/viz-core/index.ts
index ffdbd40fccd..3b1b21b5d38 100644
--- a/frontend/src/metabase/viz-core/index.ts
+++ b/frontend/src/metabase/viz-core/index.ts
@@ -27,7 +27,10 @@ export {
TIMELINE_BAND_HEIGHT,
TIMELINE_EVENTS_BAND,
} from "./echarts/cartesian/constants/style";
-export { foldRowChartModel } from "./echarts/cartesian/model/row-fold";
+export {
+ ROW_CHART_MIN_BAR_HEIGHT,
+ foldRowChartModel,
+} from "./echarts/cartesian/model/row-fold";
export { getChartLayout } from "./echarts/cartesian/layout";
export type {
ChartBoundsCoords,