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
Add RowChart labels truncation, #59899 (#62042)
Denis Berezinc5e5f16faf1e
diff --git a/.loki/reference/chrome_laptop_Viz_Static_Viz_FunnelChart_Default.png b/.loki/reference/chrome_laptop_Viz_Static_Viz_FunnelChart_Default.pngindex fb363bec329..69e9be1df32 100644Binary files a/.loki/reference/chrome_laptop_Viz_Static_Viz_FunnelChart_Default.png and b/.loki/reference/chrome_laptop_Viz_Static_Viz_FunnelChart_Default.png differdiff --git a/.loki/reference/chrome_laptop_Viz_Static_Viz_FunnelChart_Watermark.png b/.loki/reference/chrome_laptop_Viz_Static_Viz_FunnelChart_Watermark.pngindex 43880eeeffc..8223e35cadf 100644Binary files a/.loki/reference/chrome_laptop_Viz_Static_Viz_FunnelChart_Watermark.png and b/.loki/reference/chrome_laptop_Viz_Static_Viz_FunnelChart_Watermark.png differdiff --git a/.loki/reference/chrome_laptop_Viz_Static_Viz_FunnelChart_With_Duplicated_Steps.png b/.loki/reference/chrome_laptop_Viz_Static_Viz_FunnelChart_With_Duplicated_Steps.pngindex 6a7ada8fc90..ac670af73b9 100644Binary files a/.loki/reference/chrome_laptop_Viz_Static_Viz_FunnelChart_With_Duplicated_Steps.png and b/.loki/reference/chrome_laptop_Viz_Static_Viz_FunnelChart_With_Duplicated_Steps.png differdiff --git a/.loki/reference/chrome_laptop_Viz_Static_Viz_PieChart_Labels_With_Percent.png b/.loki/reference/chrome_laptop_Viz_Static_Viz_PieChart_Labels_With_Percent.pngindex a2be1c67970..be5251d32d4 100644Binary files a/.loki/reference/chrome_laptop_Viz_Static_Viz_PieChart_Labels_With_Percent.png and b/.loki/reference/chrome_laptop_Viz_Static_Viz_PieChart_Labels_With_Percent.png differdiff --git a/.loki/reference/chrome_laptop_Viz_Static_Viz_PieChart_Three_Rings_Percentages_And_Labels.png b/.loki/reference/chrome_laptop_Viz_Static_Viz_PieChart_Three_Rings_Percentages_And_Labels.pngindex 85246d0b716..44acadc861b 100644Binary files a/.loki/reference/chrome_laptop_Viz_Static_Viz_PieChart_Three_Rings_Percentages_And_Labels.png and b/.loki/reference/chrome_laptop_Viz_Static_Viz_PieChart_Three_Rings_Percentages_And_Labels.png differdiff --git a/.loki/reference/chrome_laptop_viz_RowChart_Default.png b/.loki/reference/chrome_laptop_viz_RowChart_Default.pngnew file mode 100644index 00000000000..a814917a26aBinary files /dev/null and b/.loki/reference/chrome_laptop_viz_RowChart_Default.png differdiff --git a/.loki/reference/chrome_laptop_viz_RowChart_With_Long_Names.png b/.loki/reference/chrome_laptop_viz_RowChart_With_Long_Names.pngnew file mode 100644index 00000000000..f220606dbd4Binary files /dev/null and b/.loki/reference/chrome_laptop_viz_RowChart_With_Long_Names.png differdiff --git a/e2e/test/scenarios/visualizations-charts/rows.cy.spec.js b/e2e/test/scenarios/visualizations-charts/rows.cy.spec.jsindex 5b3c94f0f4e..ae6f17144e7 100644--- a/e2e/test/scenarios/visualizations-charts/rows.cy.spec.js+++ b/e2e/test/scenarios/visualizations-charts/rows.cy.spec.js@@ -1,5 +1,11 @@+import _ from "underscore";++import { SAMPLE_DATABASE } from "e2e/support/cypress_sample_database";+const { H } = cy;+const { PRODUCTS, PRODUCTS_ID } = SAMPLE_DATABASE;+describe("scenarios > visualizations > rows", () => {beforeEach(() => {H.restore();@@ -94,4 +100,58 @@ describe("scenarios > visualizations > rows", () => {});});});++ it("should handle very long product titles in row chart", () => {+ H.createQuestion(+ {+ name: "Orders created before June 1st 2022",+ query: {+ "source-table": PRODUCTS_ID,+ expressions: {+ LongName: [+ "concat",+ ..._.times(10, () => {+ return [+ "field",+ PRODUCTS.TITLE,+ {+ "base-type": "type/Text",+ },+ ];+ }),+ ],+ },+ aggregation: [["count"]],+ breakout: [+ [+ "expression",+ "LongName",+ {+ "base-type": "type/Text",+ },+ ],+ ],+ },+ display: "row",+ },+ { visitQuestion: true },+ );++ cy.findByTestId("query-visualization-root").within(() => {+ // Check that the visualization renders without errors+ cy.findAllByRole("graphics-symbol").should("have.length.greaterThan", 0);++ // Check chart bars section - it should take 50% of width+ cy.get(".visx-columns")+ .should("exist")+ .invoke("width")+ .should("be.gt", 500);++ // Check that axis labels are present+ cy.get(".visx-axis-left")+ .should("exist")+ .invoke("width")+ .should("be.gt", 500);+ });+ });});diff --git a/frontend/src/metabase/visualizations/lib/text.ts b/frontend/src/metabase/visualizations/lib/text.tsindex 670e62915ab..ddf8d81f654 100644--- a/frontend/src/metabase/visualizations/lib/text.ts+++ b/frontend/src/metabase/visualizations/lib/text.ts@@ -7,17 +7,38 @@ export const CHAR_ELLIPSES = "…";export function truncateText(text: string,- width: number,+ maxWidth: number,measurer: TextWidthMeasurer,fontStyle: FontStyle,) {- if (measurer(text, fontStyle) <= width) {+ if (measurer(text, fontStyle) <= maxWidth) {return text;}- while (text.length && measurer(text + CHAR_ELLIPSES, fontStyle) > width) {- text = text.substring(0, text.length - 1).trim();+ const ellipsisWidth = measurer(CHAR_ELLIPSES, fontStyle);++ const availableWidth = maxWidth - ellipsisWidth;+ if (availableWidth <= 0) {+ return CHAR_ELLIPSES;+ }++ // Binary search to find the longest text that fits+ let left = 0;+ let right = text.length;+ let bestFit = "";++ while (left <= right) {+ const mid = Math.floor((left + right) / 2);+ const truncated = text.slice(0, mid);+ const truncatedWidth = measurer(truncated, fontStyle);++ if (truncatedWidth <= availableWidth) {+ bestFit = truncated;+ left = mid + 1;+ } else {+ right = mid - 1;+ }}- return text + CHAR_ELLIPSES;+ return bestFit + CHAR_ELLIPSES;}diff --git a/frontend/src/metabase/visualizations/shared/components/RowChart/RowChart.tsx b/frontend/src/metabase/visualizations/shared/components/RowChart/RowChart.tsxindex 97d19eafad7..3bb4ac6007f 100644--- a/frontend/src/metabase/visualizations/shared/components/RowChart/RowChart.tsx+++ b/frontend/src/metabase/visualizations/shared/components/RowChart/RowChart.tsx@@ -155,6 +155,7 @@ export const RowChart = <TDatum,>({yLabel,hasXAxis,hasYAxis,+ width,),[seriesData,@@ -167,6 +168,7 @@ export const RowChart = <TDatum,>({yLabel,hasXAxis,hasYAxis,+ width,],);@@ -271,6 +273,7 @@ export const RowChart = <TDatum,>({xLabel={xLabel}hasXAxis={hasXAxis}hasYAxis={hasYAxis}+ measureTextWidth={measureTextWidth}onClick={onClick}onHover={onHover}/>diff --git a/frontend/src/metabase/visualizations/shared/components/RowChart/utils/layout.ts b/frontend/src/metabase/visualizations/shared/components/RowChart/utils/layout.tsindex 8833ba6f97c..18ffe94466b 100644--- a/frontend/src/metabase/visualizations/shared/components/RowChart/utils/layout.ts+++ b/frontend/src/metabase/visualizations/shared/components/RowChart/utils/layout.ts@@ -42,15 +42,22 @@ export const getChartMargin = <TDatum>(yLabel?: string | null,hasXAxis?: boolean,hasYAxis?: boolean,+ chartWidth?: number | null,): Margin => {- const yAxisOffset = hasYAxis+ const maxYAxisLabelWidth = hasYAxis? getMaxWidth(seriesData.flatMap((seriesData) =>seriesData.bars.map((bar) => yTickFormatter(bar.yValue)),),ticksFont,measureTextWidth,- ) + TICKS_OFFSET+ )+ : 0;++ // Limit y-axis labels to 50% of chart width to ensure bars remain visible+ const maxAllowedYAxisWidth = chartWidth ? chartWidth * 0.5 : Infinity;+ const yAxisOffset = hasYAxis+ ? Math.min(maxYAxisLabelWidth, maxAllowedYAxisWidth) + TICKS_OFFSET: 0;const xAxisOffset = hasXAxis ? TICKS_OFFSET + ticksFont.size : 0;diff --git a/frontend/src/metabase/visualizations/shared/components/RowChartView/RowChartView.tsx b/frontend/src/metabase/visualizations/shared/components/RowChartView/RowChartView.tsxindex 305de9186bd..1700b2c5fd0 100644--- a/frontend/src/metabase/visualizations/shared/components/RowChartView/RowChartView.tsx+++ b/frontend/src/metabase/visualizations/shared/components/RowChartView/RowChartView.tsx@@ -9,8 +9,10 @@ import { Text } from "@visx/text";import type { ScaleBand, ScaleContinuousNumeric } from "d3-scale";import * as React from "react";+import { truncateText } from "metabase/visualizations/lib/text";import type { HoveredData } from "metabase/visualizations/shared/types/events";import type { Margin } from "metabase/visualizations/shared/types/layout";+import type { TextWidthMeasurer } from "metabase/visualizations/shared/types/measure-text";import type { SeriesInfo } from "../../types/data";import type { BarData, RowChartTheme, SeriesData } from "../RowChart/types";@@ -46,6 +48,7 @@ export interface RowChartViewProps<TDatum> {isStacked?: boolean;style?: React.CSSProperties;hoveredData?: HoveredData | null;+ measureTextWidth?: TextWidthMeasurer;onHover?: (event: React.MouseEvent<Element>,bar: BarData<TDatum, SeriesInfo> | null,@@ -78,6 +81,7 @@ const RowChartView = <TDatum,>({isStacked,style,hoveredData,+ measureTextWidth,onHover,onClick,}: RowChartViewProps<TDatum>) => {@@ -90,6 +94,34 @@ const RowChartView = <TDatum,>({const goalLineX = xScale(goal?.value ?? 0);+ const ellipsifiedYTickFormatter = React.useMemo(() => {+ if (!measureTextWidth || !width) {+ return yTickFormatter;+ }++ // Calculate the maximum allowed width for y-axis labels (50% of chart width)+ const maxLabelWidth =+ margin.left - (yLabel ? theme.axis.label.size * 2 : 0);++ return (value: StringLike) => {+ const originalText = yTickFormatter(value);+ return truncateText(+ originalText,+ maxLabelWidth,+ measureTextWidth,+ theme.axis.ticks,+ );+ };+ }, [+ measureTextWidth,+ width,+ margin.left,+ yLabel,+ theme.axis.label.size,+ theme.axis.ticks,+ yTickFormatter,+ ]);+return (<svg width={width ?? undefined} height={height ?? undefined} style={style}><Group top={margin.top} left={margin.left}>@@ -203,7 +235,7 @@ const RowChartView = <TDatum,>({verticalAnchor: "start",}}labelOffset={margin.left - theme.axis.label.size}- tickFormat={yTickFormatter}+ tickFormat={ellipsifiedYTickFormatter}hideAxisLine={!hasYAxis}hideTickstickValues={hasYAxis ? undefined : []}diff --git a/frontend/src/metabase/visualizations/visualizations/RowChart/RowChart.stories.tsx b/frontend/src/metabase/visualizations/visualizations/RowChart/RowChart.stories.tsxnew file mode 100644index 00000000000..466b2ffc38d--- /dev/null+++ b/frontend/src/metabase/visualizations/visualizations/RowChart/RowChart.stories.tsx@@ -0,0 +1,98 @@+// @ts-expect-error There is no type definition+import createAsyncCallback from "@loki/create-async-callback";+import type { StoryFn } from "@storybook/react";+import { useState } from "react";+import { useMount } from "react-use";++import { VisualizationWrapper } from "__support__/storybook";+import { NumberColumn, StringColumn } from "__support__/visualizations";+import { Box } from "metabase/ui";+import { registerVisualization } from "metabase/visualizations";+import Visualization from "metabase/visualizations/components/Visualization";+import type { RawSeries, Series } from "metabase-types/api";+import { createMockCard } from "metabase-types/api/mocks";++import RowChart from "./RowChart";++export default {+ title: "viz/RowChart",+ component: RowChart,+};++// @ts-expect-error: incompatible prop types with registerVisualization+registerVisualization(RowChart);++const MOCK_SERIES = [+ {+ card: createMockCard({ name: "Card", display: "row" }),+ data: {+ cols: [+ StringColumn({ name: "Dimension" }),+ NumberColumn({ name: "Count" }),+ ],+ rows: [+ ["foo", 1],+ ["bar", 2],+ ],+ },+ },+] as Series;++export const Default: StoryFn<{ series: RawSeries }> = ({+ series = MOCK_SERIES,+}: {+ series: RawSeries;+}) => {+ return (+ <VisualizationWrapper>+ <Box h={500}>+ <Visualization rawSeries={series} width={500} />+ </Box>+ </VisualizationWrapper>+ );+};++export const WithLongNames = () => {+ const [series, setSeries] = useState([+ {+ card: createMockCard({ name: "Card", display: "row" }),+ data: {+ cols: [+ StringColumn({ name: "Dimension" }),+ NumberColumn({ name: "Count" }),+ ],+ rows: [+ [+ "Aerodynamic Bronze HatAerodynamic Bronze HatAerodynamic Bronze HatAerodynamic Bronze HatAerodynamic Bronze HatAerodynamic Bronze HatAerodynamic Bronze Hat",+ 1,+ ],+ [+ "Aerodynamic Concrete BenchAerodynamic Concrete BenchAerodynamic Concrete BenchAerodynamic Concrete BenchAerodynamic Concrete BenchAerodynamic Concrete BenchAerodynamic Concrete Bench",+ 2,+ ],+ ],+ },+ },+ ] as Series);++ useMount(() => {+ const asyncCallback = createAsyncCallback();++ // trigger rerender to avoid weird issue with first calculation being incorrect. Maybe because of fonts are not loaded?+ setTimeout(() => {+ setSeries([...series]);++ setTimeout(() => {+ asyncCallback();+ });+ }, 100);+ });++ return (+ <VisualizationWrapper>+ <Box h={500}>+ <Visualization rawSeries={series} width={500} />+ </Box>+ </VisualizationWrapper>+ );+};