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
Fix handling of object columns in pie charts (#68095)
Kevin Kelleherb161e194421b
diff --git a/frontend/src/metabase/visualizations/shared/settings/pie.ts b/frontend/src/metabase/visualizations/shared/settings/pie.tsindex 4eede673fed..d31fa6e803c 100644--- a/frontend/src/metabase/visualizations/shared/settings/pie.ts+++ b/frontend/src/metabase/visualizations/shared/settings/pie.ts@@ -1,4 +1,3 @@-import Color from "color";import _ from "underscore";import { getColorsForValues } from "metabase/lib/colors/charts";@@ -63,6 +62,8 @@ export const getDefaultSliceThreshold = () => SLICE_THRESHOLD * 100;export function getKeyFromDimensionValue(dimensionValue: RowValue) {if (dimensionValue == null) {return NULL_DISPLAY_VALUE;+ } else if (typeof dimensionValue === "object") {+ return JSON.stringify(dimensionValue);}return String(dimensionValue);}@@ -80,7 +81,7 @@ export function getAggregatedRows() {const dimensionToMetricValues = new Map<string, number>();rows.forEach((row) => {- const dimensionValue = String(row[dimensionIndex]);+ const dimensionValue = getKeyFromDimensionValue(row[dimensionIndex]);const metricValue = getNumberOr(row[metricIndex], 0);const existingMetricValue =@@ -96,7 +97,7 @@ export function getAggregatedRows(const seenDimensionValues = new Set<string>();rows.forEach((row) => {- const dimensionValue = String(row[dimensionIndex]);+ const dimensionValue = getKeyFromDimensionValue(row[dimensionIndex]);if (seenDimensionValues.has(dimensionValue)) {return;}@@ -164,17 +165,53 @@ export function getColors(metricIndex,);- const dimensionValues = sortedRows.map((r) => String(r[dimensionIndex]));-- // Sometimes viz settings are malformed and "pie.colors" does not- // contain a key for the current dimension value, so we need to compute- // defaults to ensure every key has a color.- const defaultColors = getColorsForValues(- dimensionValues,- currentSettings["pie.colors"],+ const dimensionValues = sortedRows.map((r) =>+ getKeyFromDimensionValue(r[dimensionIndex]),);- return { ...defaultColors, ...currentSettings["pie.colors"] };+ let existingColorMapping: Record<string, string> = {};++ // pie.colors is the legacy setting for colors+ if (currentSettings["pie.colors"]) {+ existingColorMapping = Object.fromEntries(+ Object.entries(currentSettings["pie.colors"]).map(([key, value]) => [+ // Historically we used String(dimensionValue) in the `pie.colors` setting instead of `getKeyFromDimensionValue`+ // For compatibility with old charts, we'll transform the strings "null" and "undefined" into NULL_DISPLAY_VALUE+ key === "null" || key === "undefined" ? NULL_DISPLAY_VALUE : key,+ getHexColor(value),+ ]),+ );+ }++ // pie.rows is the new setting for colors - takes precedence over pie.colors+ if (currentSettings["pie.rows"]) {+ for (const row of currentSettings["pie.rows"]) {+ if (!row.defaultColor && row.color) {+ existingColorMapping[row.key] = getHexColor(row.color);+ }+ }+ }++ // historically we used "null" rather than NULL_DISPLAY_VALUE in `getColorsForValues`+ // to avoid changing existing charts, we'll convert NULL_DISPLAY_VALUE to "null"+ const colors = getColorsForValues(+ dimensionValues.map((value) =>+ value === NULL_DISPLAY_VALUE ? "null" : value,+ ),+ Object.fromEntries(+ Object.entries(existingColorMapping).map(([key, value]) => [+ key === NULL_DISPLAY_VALUE ? "null" : key,+ value,+ ]),+ ),+ );+ // then flip it back+ return Object.fromEntries(+ Object.entries(colors).map(([key, value]) => [+ key === "null" ? NULL_DISPLAY_VALUE : key,+ value,+ ]),+ );}export function getPieRows(@@ -213,14 +250,7 @@ export function getPieRows(return formatter(value, dimensionColSettings);};- let colors = getColors(rawSeries, settings);- // `pie.colors` is a legacy setting used by old questions for their- // colors. We'll still read it to preserve those color selections, but- // will no longer write values to it, instead storing colors here in- // `pie.rows`.- if (settings["pie.colors"] != null) {- colors = { ...colors, ...settings["pie.colors"] };- }+ const colors = getColors(rawSeries, settings);const rowsForKeys = getRowsForStableKeys(rawSeries[0].data);const currentDataRows = getAggregatedRows(@@ -278,19 +308,14 @@ export function getPieRows(newPieRows = sortedCurrentDataRows.map((dataRow) => {const dimensionValue = dataRow[dimensionDesc.index];const key = getKeyFromDimensionValue(dimensionValue);- // Historically we have used the dimension value in the `pie.colors`- // setting instead of the key computed above. For compatibility with- // existing questions we will continue to use the dimension value.- const color = getHexColor(colors[String(dimensionValue)]);+ const color = colors[key];const savedRow = keyToSavedPieRow.get(key);if (savedRow != null) {const newRow = { ...savedRow, hidden: false };-if (savedRow.defaultColor) {newRow.color = color;}-return newRow;}@@ -318,11 +343,11 @@ export function getPieRows(if (savedPieRow == null) {throw Error(`Did not find saved pie row for kept key ${keptKey}`);}-- return {- ...savedPieRow,- hidden: false,- };+ const newRow = { ...savedPieRow, hidden: false };+ if (savedPieRow.defaultColor) {+ newRow.color = colors[keptKey];+ }+ return newRow;});const addedRows = added.map((addedKey) => {@@ -339,8 +364,8 @@ export function getPieRows(...sortedAddedRows.map((addedDataRow) => {const dimensionValue = addedDataRow[dimensionDesc.index];- const color = Color(colors[String(dimensionValue)]).hex();const key = getKeyFromDimensionValue(dimensionValue);+ const color = colors[key];const displayValue = getDisplayValue(dimensionValue);const name = formatDimensionValue(displayValue);diff --git a/frontend/src/metabase/visualizations/shared/settings/pie.unit.spec.ts b/frontend/src/metabase/visualizations/shared/settings/pie.unit.spec.tsnew file mode 100644index 00000000000..0db3990083d--- /dev/null+++ b/frontend/src/metabase/visualizations/shared/settings/pie.unit.spec.ts@@ -0,0 +1,146 @@+import { NULL_DISPLAY_VALUE } from "metabase/lib/constants";+import type { PieRow } from "metabase/visualizations/echarts/pie/model/types";+import type { RawSeries } from "metabase-types/api";+import {+ createMockColumn,+ createMockDatasetData,+} from "metabase-types/api/mocks";++import { getAggregatedRows, getColors, getKeyFromDimensionValue } from "./pie";++describe("getKeyFromDimensionValue", () => {+ it("should return NULL_DISPLAY_VALUE for null", () => {+ expect(getKeyFromDimensionValue(null)).toBe(NULL_DISPLAY_VALUE);+ });++ it("should return string representation for strings", () => {+ expect(getKeyFromDimensionValue("test")).toBe("test");+ });++ it("should return string representation for numbers", () => {+ expect(getKeyFromDimensionValue(123)).toBe("123");+ });++ it("should return string representation for booleans", () => {+ expect(getKeyFromDimensionValue(true)).toBe("true");+ expect(getKeyFromDimensionValue(false)).toBe("false");+ });++ it("should return JSON string for objects (metabase#52686)", () => {+ const obj = { nestedKey1: "nestedValue2" };+ expect(getKeyFromDimensionValue(obj)).toBe('{"nestedKey1":"nestedValue2"}');+ });++ it("should return JSON string for arrays", () => {+ expect(getKeyFromDimensionValue([1, 2, 3])).toBe("[1,2,3]");+ });+});++describe("getAggregatedRows", () => {+ it("should aggregate rows by dimension value", () => {+ const rows = [+ ["A", 10],+ ["B", 20],+ ["A", 15],+ ];+ const result = getAggregatedRows(rows, 0, 1);++ expect(result).toEqual([+ ["A", 25],+ ["B", 20],+ ]);+ });++ it("should handle null dimension values", () => {+ const rows = [+ [null, 10],+ ["A", 20],+ [null, 15],+ ];+ const result = getAggregatedRows(rows, 0, 1);++ expect(result).toEqual([+ [null, 25],+ ["A", 20],+ ]);+ });++ it("should aggregate rows with object dimension values correctly (metabase#52686)", () => {+ const obj1 = { nestedKey1: "nestedValue2" };+ const obj2 = { nestedKey1: "nestedValue7", nestedKey2: "nestedValue8" };+ const obj3 = { nestedKey1: "nestedValue13" };+ const obj1Duplicate = { nestedKey1: "nestedValue2" };++ const rows = [+ [obj1, 1],+ [obj2, 1],+ [obj3, 1],+ [obj1Duplicate, 2], // Should aggregate with obj1 since they're equivalent+ [null, 2],+ ];++ const result = getAggregatedRows(rows, 0, 1);++ expect(result).toEqual([+ [obj1, 3],+ [obj2, 1],+ [obj3, 1],+ [null, 2],+ ]);+ });+});++describe("getColors", () => {+ it("should respect pie.color and pie.rows", () => {+ const columns = [+ createMockColumn({ name: "Category" }),+ createMockColumn({ name: "Count" }),+ ];+ const rawSeries = [+ {+ data: createMockDatasetData({+ rows: [+ ["Doohickey", 1],+ ["Gadget", 2],+ ["Gizmo", 3],+ ["Widget", 4],+ ],+ cols: columns,+ }),+ },+ ] as RawSeries;+ const settings = {+ "pie.metric": "Count",+ "pie.dimension": "Category",+ "pie.colors": {+ Doohickey: "#FF0000",+ Gadget: "#00FF00",+ Gizmo: "#FFFFFF",+ },+ "pie.rows": [+ {+ key: "Gadget",+ defaultColor: false,+ color: "#0000FF",+ },+ {+ key: "Gizmo",+ defaultColor: true,+ color: "#00FF00",+ },+ {+ key: "Widget",+ defaultColor: false,+ color: "#000000",+ },+ ] as PieRow[],+ };+ const result = getColors(rawSeries, settings);+ expect(result).toEqual({+ Doohickey: "#FF0000",+ Gadget: "#0000FF",+ Gizmo: "#FFFFFF",+ Widget: "#000000",+ });+ });+});diff --git a/frontend/src/metabase/visualizations/visualizations/PieChart/use-chart-events.ts b/frontend/src/metabase/visualizations/visualizations/PieChart/use-chart-events.tsindex 1037d707bf8..5f22ecf8dab 100644--- a/frontend/src/metabase/visualizations/visualizations/PieChart/use-chart-events.ts+++ b/frontend/src/metabase/visualizations/visualizations/PieChart/use-chart-events.ts@@ -135,10 +135,26 @@ function handleClick(}const rowIndex = sliceTreeNode.rowIndex;+ const row = rowIndex != null ? dataProp.rows[rowIndex] : undefined;++ // the underlying records filter doesn't support objects, so return early if any of the dimension values are objects+ if (+ row &&+ [+ chartModel.colDescs.dimensionDesc.index,+ chartModel.colDescs.middleDimensionDesc?.index,+ chartModel.colDescs.outerDimensionDesc?.index,+ ]+ .filter((index) => index != null)+ .map((index) => row[index])+ .some((value) => value != null && typeof value === "object")+ ) {+ return;+ }const data =- rowIndex != null- ? dataProp.rows[rowIndex].map((value, index) => ({+ row != null+ ? row.map((value, index) => ({value,col: dataProp.cols[index],}))