fix(echarts): prevent plain legend clipping in dashboards (#38675)

This commit is contained in:
Richard Fogaca Nienkotter
2026-03-25 09:38:31 -03:00
committed by GitHub
parent 3fb903fdc6
commit 12aca72074
16 changed files with 1514 additions and 102 deletions

View File

@@ -303,4 +303,69 @@ describe('legend sorting', () => {
const legendData = (result.echartOptions.legend as any).data;
expect(legendData).toEqual(['series value 2', 'series value 1']);
});
test('falls back to scroll for plain legends with an overlong legend item', () => {
const props = new ChartProps({
...chartPropsConfig,
width: 320,
formData: {
...formData,
legendType: LegendType.Plain,
},
queriesData: [
{
data: [
{
startTime: Date.UTC(2025, 1, 1, 13, 0, 0),
endTime: Date.UTC(2025, 1, 1, 14, 0, 0),
'Y Axis': 'first',
tooltip_column: 'tooltip value 1',
series:
'This is a ridiculously long legend label that should switch to scroll',
},
{
startTime: Date.UTC(2025, 1, 1, 18, 0, 0),
endTime: Date.UTC(2025, 1, 1, 20, 0, 0),
'Y Axis': 'second',
tooltip_column: 'tooltip value 2',
series: 'short label',
},
],
colnames: [
'startTime',
'endTime',
'Y Axis',
'tooltip_column',
'series',
],
},
],
});
const result = transformProps(props as EchartsGanttChartProps);
expect((result.echartOptions.legend as any).type).toBe(LegendType.Scroll);
});
test('keeps legend visibility driven by showLegend for single-series charts', () => {
const props = new ChartProps({
...chartPropsConfig,
queriesData: [
{
data: [queriesData[0].data[0]],
colnames: [
'startTime',
'endTime',
'Y Axis',
'tooltip_column',
'series',
],
},
],
});
const result = transformProps(props as EchartsGanttChartProps);
expect((result.echartOptions.legend as any).show).toBe(true);
});
});

View File

@@ -19,8 +19,10 @@
import {
AnnotationStyle,
AnnotationType,
AnnotationSourceType,
DataRecord,
FormulaAnnotationLayer,
IntervalAnnotationLayer,
VizType,
ChartDataResponseResult,
} from '@superset-ui/core';
@@ -366,6 +368,67 @@ test('legend margin: right orientation sets grid.right correctly', () => {
expect((transformed.echartOptions.grid as any).right).toEqual(270);
});
test('should exclude unnamed annotation helper series from legend data', () => {
const interval: IntervalAnnotationLayer = {
annotationType: AnnotationType.Interval,
name: 'My Interval',
show: true,
showLabel: true,
sourceType: AnnotationSourceType.Table,
titleColumn: '',
timeColumn: 'start',
intervalEndColumn: 'end',
descriptionColumns: [],
style: AnnotationStyle.Dashed,
value: 2,
};
const annotationData = {
'My Interval': {
columns: ['start', 'end', 'title'],
records: [
{
start: 2000,
end: 3000,
title: 'My Title',
},
],
},
};
const chartProps = createEchartsTimeseriesTestChartProps<
EchartsMixedTimeseriesFormData,
EchartsMixedTimeseriesProps
>({
...MIXED_TIMESERIES_CHART_PROPS_DEFAULTS,
defaultQueriesData: [],
formData: {
...formData,
annotationLayers: [interval],
showLegend: true,
showQueryIdentifiers: true,
},
queriesData: [
createTestQueryData(defaultQueryRows, {
label_map: defaultLabelMap,
annotation_data: annotationData,
}),
createTestQueryData(defaultQueryRows, {
label_map: defaultLabelMap,
annotation_data: annotationData,
}),
],
});
const transformed = transformProps(chartProps);
expect((transformed.echartOptions.legend as any).data).toEqual([
'sum__num (Query A), girl',
'sum__num (Query A), boy',
'sum__num (Query B), girl',
'sum__num (Query B), boy',
]);
});
test('should add a formula annotation when X-axis column has dataset-level label', () => {
const formula: FormulaAnnotationLayer = {
name: 'My Formula',

View File

@@ -29,6 +29,7 @@ import type {
} from 'echarts/types/src/util/types';
import transformProps, { parseParams } from '../../src/Pie/transformProps';
import { EchartsPieChartProps, PieChartDataItem } from '../../src/Pie/types';
import { LegendOrientation, LegendType } from '../../src/types';
describe('Pie transformProps', () => {
const formData: SqlaFormData = {
@@ -84,6 +85,51 @@ describe('Pie transformProps', () => {
}),
);
});
test('falls back to scroll for plain legends with overlong labels', () => {
const longLegendChartProps = new ChartProps({
formData: {
colorScheme: 'bnbColors',
datasource: '3__table',
granularity_sqla: 'ds',
metric: 'sum__num',
groupby: ['category'],
viz_type: 'pie',
legendType: LegendType.Plain,
legendOrientation: LegendOrientation.Top,
showLegend: true,
} as SqlaFormData,
width: 320,
height: 600,
queriesData: [
{
data: [
{
category: 'This is a very long pie legend label one',
sum__num: 10,
},
{
category: 'This is a very long pie legend label two',
sum__num: 20,
},
{
category: 'This is a very long pie legend label three',
sum__num: 30,
},
],
},
],
theme: supersetTheme,
});
const transformed = transformProps(
longLegendChartProps as EchartsPieChartProps,
);
expect((transformed.echartOptions.legend as any).type).toBe(
LegendType.Scroll,
);
});
});
describe('formatPieLabel', () => {

View File

@@ -16,12 +16,62 @@
* specific language governing permissions and limitations
* under the License.
*/
import { ChartProps, SqlaFormData } from '@superset-ui/core';
import {
ChartDataResponseResult,
ChartProps,
DataRecord,
SqlaFormData,
} from '@superset-ui/core';
import { GenericDataType } from '@apache-superset/core/common';
import { supersetTheme } from '@apache-superset/core/theme';
import { EchartsTimeseriesChartProps } from '../../../src/types';
import type {
GridComponentOption,
LegendComponentOption,
} from 'echarts/components';
import {
EchartsTimeseriesChartProps,
LegendOrientation,
LegendType,
} from '../../../src/types';
import transformProps from '../../../src/Timeseries/transformProps';
import { DEFAULT_FORM_DATA } from '../../../src/Timeseries/constants';
import { EchartsTimeseriesSeriesType } from '../../../src/Timeseries/types';
import {
EchartsTimeseriesFormData,
OrientationType,
EchartsTimeseriesSeriesType,
} from '../../../src/Timeseries/types';
import { getPadding } from '../../../src/Timeseries/transformers';
import {
getHorizontalLegendAvailableWidth,
getLegendLayoutResult,
} from '../../../src/utils/series';
import { createEchartsTimeseriesTestChartProps } from '../../helpers';
function createTestQueryData(
data: DataRecord[],
overrides?: Partial<ChartDataResponseResult>,
): ChartDataResponseResult {
return {
annotation_data: null,
cache_key: null,
cache_timeout: null,
cached_dttm: null,
queried_dttm: null,
data,
colnames: [],
coltypes: [],
error: null,
is_cached: false,
query: '',
rowcount: data.length,
sql_rowcount: data.length,
stacktrace: null,
status: 'success',
from_dttm: null,
to_dttm: null,
...overrides,
};
}
describe('Bar Chart X-axis Time Formatting', () => {
const baseFormData: SqlaFormData = {
@@ -570,6 +620,48 @@ describe('Bar Chart X-axis Time Formatting', () => {
expect(legendData).toContain('C');
});
test('should preserve source order for color-by-primary-axis legends when label sorting is enabled', () => {
const unsortedCategoricalData = [
{
data: [
{ category: 'Zulu', value: 100 },
{ category: 'Alpha', value: 150 },
{ category: 'Mike', value: 200 },
],
colnames: ['category', 'value'],
coltypes: ['STRING', 'BIGINT'],
},
];
const formData = {
...baseFormData,
colorByPrimaryAxis: true,
groupby: [],
legendSort: 'asc',
x_axis: 'category',
metric: 'value',
};
const chartProps = new ChartProps({
...baseChartPropsConfig,
queriesData: unsortedCategoricalData,
formData,
});
const transformedProps = transformProps(
chartProps as unknown as EchartsTimeseriesChartProps,
);
const legend = transformedProps.echartOptions.legend as {
data: { name: string }[];
};
expect(legend.data.map(item => item.name)).toEqual([
'Zulu',
'Alpha',
'Mike',
]);
});
test('should deduplicate legend entries when x-axis has repeated values', () => {
const repeatedData = [
{
@@ -634,4 +726,180 @@ describe('Bar Chart X-axis Time Formatting', () => {
expect(hiddenSeries.length).toBe(3);
});
});
describe('Legend layout regressions', () => {
const getBottomLegendLayout = (
chartWidth: number,
legendItems: string[],
legendMargin?: string | number | null,
) =>
getLegendLayoutResult({
availableWidth: getHorizontalLegendAvailableWidth({
chartWidth,
orientation: LegendOrientation.Bottom,
padding: getPadding(
true,
LegendOrientation.Bottom,
false,
false,
legendMargin,
false,
undefined,
undefined,
undefined,
true,
),
}),
chartHeight: baseChartPropsConfig.height,
chartWidth,
legendItems,
legendMargin,
orientation: LegendOrientation.Bottom,
show: true,
theme: supersetTheme,
type: LegendType.Plain,
});
test('should fall back to scroll for horizontal bottom legends after margin expansion reduces available width', () => {
const legendLabels = [
'This is a long sales legend',
'This is a long marketing legend',
'This is a long operations legend',
];
const longLegendData: ChartDataResponseResult[] = [
createTestQueryData(
[
{
[legendLabels[0]]: 100,
[legendLabels[1]]: null,
[legendLabels[2]]: null,
__timestamp: 1609459200000,
},
{
[legendLabels[0]]: null,
[legendLabels[1]]: 150,
[legendLabels[2]]: null,
__timestamp: 1612137600000,
},
{
[legendLabels[0]]: null,
[legendLabels[1]]: null,
[legendLabels[2]]: 200,
__timestamp: 1614556800000,
},
],
{
colnames: [...legendLabels, '__timestamp'],
coltypes: [
GenericDataType.Numeric,
GenericDataType.Numeric,
GenericDataType.Numeric,
GenericDataType.Temporal,
],
},
),
];
const regressionFormData: EchartsTimeseriesFormData = {
...(baseFormData as EchartsTimeseriesFormData),
metric: legendLabels,
orientation: OrientationType.Horizontal,
legendOrientation: LegendOrientation.Bottom,
legendType: LegendType.Plain,
showLegend: true,
};
const baselineChartProps = createEchartsTimeseriesTestChartProps<
EchartsTimeseriesFormData,
EchartsTimeseriesChartProps
>({
defaultFormData: regressionFormData,
defaultVizType: 'echarts_timeseries_bar',
defaultQueriesData: longLegendData,
width: baseChartPropsConfig.width,
height: baseChartPropsConfig.height,
});
const baselineTransformed = transformProps(baselineChartProps);
const legendItems = (
(baselineTransformed.echartOptions.legend as LegendComponentOption)
.data as Array<string | { name: string }>
).map(item => (typeof item === 'string' ? item : item.name));
let chartWidth: number | undefined;
let expandedLegendMargin: number | null = null;
for (let width = 300; width <= 700; width += 1) {
const initialLayout = getBottomLegendLayout(width, legendItems, null);
if (initialLayout.effectiveType !== LegendType.Plain) {
continue;
}
const refinedLayout = getBottomLegendLayout(
width,
legendItems,
initialLayout.effectiveMargin ?? null,
);
if (refinedLayout.effectiveType === LegendType.Scroll) {
chartWidth = width;
expandedLegendMargin = initialLayout.effectiveMargin ?? null;
break;
}
}
expect(chartWidth).toBeDefined();
expect(expandedLegendMargin).not.toBeNull();
const resolvedChartWidth = chartWidth ?? baseChartPropsConfig.width;
const chartProps = createEchartsTimeseriesTestChartProps<
EchartsTimeseriesFormData,
EchartsTimeseriesChartProps
>({
defaultFormData: regressionFormData,
defaultVizType: 'echarts_timeseries_bar',
defaultQueriesData: longLegendData,
width: resolvedChartWidth,
height: baseChartPropsConfig.height,
});
const transformedProps = transformProps(chartProps);
const legend = transformedProps.echartOptions
.legend as LegendComponentOption;
const grid = transformedProps.echartOptions.grid as GridComponentOption;
const expectedPadding = getPadding(
true,
LegendOrientation.Bottom,
false,
false,
null,
false,
undefined,
undefined,
undefined,
true,
);
[expectedPadding.bottom, expectedPadding.left] = [
expectedPadding.left,
expectedPadding.bottom,
];
const expandedPadding = getPadding(
true,
LegendOrientation.Bottom,
false,
false,
expandedLegendMargin,
false,
undefined,
undefined,
undefined,
true,
);
[expandedPadding.bottom, expandedPadding.left] = [
expandedPadding.left,
expandedPadding.bottom,
];
expect(legend.type).toBe(LegendType.Scroll);
expect(grid.bottom).toBe(expectedPadding.bottom);
expect(grid.bottom).not.toBe(expandedPadding.bottom);
});
});
});

View File

@@ -37,7 +37,8 @@ import {
OrientationType,
EchartsTimeseriesFormData,
} from '../../src/Timeseries/types';
import { StackControlsValue } from '../../src/constants';
import { StackControlsValue, TIMESERIES_CONSTANTS } from '../../src/constants';
import { LegendOrientation, LegendType } from '../../src/types';
import { DEFAULT_FORM_DATA } from '../../src/Timeseries/constants';
import { createEchartsTimeseriesTestChartProps } from '../helpers';
import { BASE_TIMESTAMP, createTestData } from './helpers';
@@ -898,6 +899,40 @@ describe('legend sorting', () => {
'Boston',
]);
});
test('falls back to scroll for zoomable top legends when toolbox space reduces available width', () => {
const narrowLegendData = [
createTestQueryData(
createTestData(
[
{
Alpha: 1,
Beta: 2,
Gamma: 3,
},
],
{ intervalMs: 300000000 },
),
),
];
const chartProps = createTestChartProps({
width: 190 + TIMESERIES_CONSTANTS.legendTopRightOffset,
formData: {
...formData,
legendType: LegendType.Plain,
legendOrientation: LegendOrientation.Top,
showLegend: true,
zoomable: true,
},
queriesData: narrowLegendData,
});
const transformed = transformProps(chartProps);
expect((transformed.echartOptions.legend as any).type).toBe(
LegendType.Scroll,
);
});
});
const timeCompareFormData: SqlaFormData = {

View File

@@ -16,7 +16,7 @@
* specific language governing permissions and limitations
* under the License.
*/
import { SortSeriesType } from '@superset-ui/chart-controls';
import { LegendPaddingType, SortSeriesType } from '@superset-ui/chart-controls';
import {
AxisType,
DataRecord,
@@ -51,6 +51,71 @@ import {
import { defaultLegendPadding } from '../../src/defaults';
import { NULL_STRING } from '../../src/constants';
const {
getHorizontalLegendAvailableWidth,
getLegendLayoutResult,
}: {
getHorizontalLegendAvailableWidth: (args: {
chartWidth: number;
orientation: LegendOrientation.Top | LegendOrientation.Bottom;
padding?: LegendPaddingType;
zoomable?: boolean;
}) => number;
getLegendLayoutResult: (args: {
availableHeight?: number;
availableWidth?: number;
chartHeight: number;
chartWidth: number;
legendItems?: (
| string
| number
| null
| undefined
| { name?: string | number | null }
)[];
legendMargin?: string | number | null;
orientation: LegendOrientation;
show: boolean;
showSelectors?: boolean;
theme: typeof theme;
type: LegendType;
}) => {
effectiveMargin?: number;
effectiveType: LegendType;
};
} = require('../../src/utils/series');
const {
resolveLegendLayout,
}: {
resolveLegendLayout: (args: {
availableHeight?: number;
availableWidth?: number;
chartHeight: number;
chartWidth: number;
legendItems?: (
| string
| number
| null
| undefined
| { name?: string | number | null }
)[];
legendMargin?: string | number | null;
orientation: LegendOrientation;
show: boolean;
showSelectors?: boolean;
theme: typeof theme;
type: LegendType;
}) => {
effectiveLegendMargin?: string | number | null;
effectiveLegendType: LegendType;
legendLayout: {
effectiveMargin?: number;
effectiveType: LegendType;
};
};
} = require('../../src/utils/legendLayout');
const expectedThemeProps = {
selector: ['all', 'inverse'],
selected: {},
@@ -891,19 +956,20 @@ describe('getLegendProps', () => {
});
});
test('should default plain legends to scroll for bottom orientation', () => {
test('should return the correct props for plain type with bottom orientation', () => {
expect(
getLegendProps(LegendType.Plain, LegendOrientation.Bottom, false, theme),
).toEqual({
show: false,
bottom: 0,
right: 0,
orient: 'horizontal',
type: 'scroll',
type: 'plain',
...expectedThemeProps,
});
});
test('should default plain legends to scroll for top orientation', () => {
test('should return the correct props for plain type with top orientation', () => {
expect(
getLegendProps(LegendType.Plain, LegendOrientation.Top, false, theme),
).toEqual({
@@ -911,12 +977,248 @@ describe('getLegendProps', () => {
top: 0,
right: 0,
orient: 'horizontal',
type: 'scroll',
type: 'plain',
...expectedThemeProps,
});
});
});
test('getLegendLayoutResult keeps plain horizontal legends when they fit within two rows', () => {
expect(
getLegendLayoutResult({
chartHeight: 400,
chartWidth: 800,
legendItems: ['Alpha', 'Beta', 'Gamma', 'Delta'],
legendMargin: null,
orientation: LegendOrientation.Top,
show: true,
theme,
type: LegendType.Plain,
}),
).toEqual({
effectiveMargin: defaultLegendPadding[LegendOrientation.Top],
effectiveType: LegendType.Plain,
});
});
test('getLegendLayoutResult adds extra margin for wrapped plain horizontal legends', () => {
const layout = getLegendLayoutResult({
chartHeight: 400,
chartWidth: 640,
legendItems: [
'This is a long legend label',
'Another long legend label',
'Third long legend label',
],
legendMargin: null,
orientation: LegendOrientation.Top,
show: true,
theme,
type: LegendType.Plain,
});
expect(layout).toMatchObject({
effectiveType: LegendType.Plain,
});
expect(layout.effectiveMargin).toBeGreaterThan(
defaultLegendPadding[LegendOrientation.Top],
);
});
test('getLegendLayoutResult falls back to scroll when horizontal plain legends exceed two rows', () => {
expect(
getLegendLayoutResult({
chartHeight: 400,
chartWidth: 240,
legendItems: [
'This is a long legend label',
'Another long legend label',
'Third long legend label',
],
legendMargin: null,
orientation: LegendOrientation.Top,
show: true,
theme,
type: LegendType.Plain,
}),
).toEqual({
effectiveType: LegendType.Scroll,
});
});
test('getLegendLayoutResult falls back to scroll when a single horizontal plain legend item exceeds available width', () => {
expect(
getLegendLayoutResult({
chartHeight: 400,
chartWidth: 260,
legendItems: [
'This is a ridiculously long legend label that should not fit on one line',
],
legendMargin: null,
orientation: LegendOrientation.Top,
show: true,
theme,
type: LegendType.Plain,
}),
).toEqual({
effectiveType: LegendType.Scroll,
});
});
test('getLegendLayoutResult falls back to scroll when reserved horizontal width reduces plain legend capacity', () => {
const availableWidth = getHorizontalLegendAvailableWidth({
chartWidth: 265,
orientation: LegendOrientation.Top,
padding: { left: 20 },
zoomable: true,
});
expect(
getLegendLayoutResult({
availableWidth,
chartHeight: 400,
chartWidth: 265,
legendItems: ['Alpha', 'Beta', 'Gamma'],
legendMargin: null,
orientation: LegendOrientation.Top,
show: true,
theme,
type: LegendType.Plain,
}),
).toEqual({
effectiveType: LegendType.Scroll,
});
});
test('getLegendLayoutResult falls back to scroll when horizontal legend selectors alone exceed available width', () => {
expect(
getLegendLayoutResult({
chartHeight: 400,
chartWidth: 95,
legendItems: ['A'],
legendMargin: null,
orientation: LegendOrientation.Top,
show: true,
theme,
type: LegendType.Plain,
}),
).toEqual({
effectiveType: LegendType.Scroll,
});
});
test('getLegendLayoutResult keeps plain vertical legends when they fit within a single column', () => {
expect(
getLegendLayoutResult({
chartHeight: 400,
chartWidth: 800,
legendItems: ['Alpha', 'Beta', 'Gamma'],
legendMargin: null,
orientation: LegendOrientation.Left,
show: true,
theme,
type: LegendType.Plain,
}),
).toEqual({
effectiveMargin: defaultLegendPadding[LegendOrientation.Left],
effectiveType: LegendType.Plain,
});
});
test('getLegendLayoutResult adds extra margin for wide vertical plain legends', () => {
const layout = getLegendLayoutResult({
chartHeight: 400,
chartWidth: 800,
legendItems: ['This is a very long legend label'],
legendMargin: null,
orientation: LegendOrientation.Left,
show: true,
theme,
type: LegendType.Plain,
});
expect(layout).toMatchObject({
effectiveType: LegendType.Plain,
});
expect(layout.effectiveMargin).toBeGreaterThan(
defaultLegendPadding[LegendOrientation.Left],
);
});
test('getLegendLayoutResult falls back to scroll when vertical plain legends exceed one column', () => {
expect(
getLegendLayoutResult({
chartHeight: 160,
chartWidth: 800,
legendItems: ['Alpha', 'Beta', 'Gamma', 'Delta', 'Epsilon'],
legendMargin: null,
orientation: LegendOrientation.Left,
show: true,
theme,
type: LegendType.Plain,
}),
).toEqual({
effectiveType: LegendType.Scroll,
});
});
test('getLegendLayoutResult falls back to scroll when vertical plain legend selectors exceed available width', () => {
expect(
getLegendLayoutResult({
chartHeight: 400,
chartWidth: 300,
legendItems: ['A', 'B', 'C'],
legendMargin: null,
orientation: LegendOrientation.Left,
show: true,
theme,
type: LegendType.Plain,
}),
).toEqual({
effectiveType: LegendType.Scroll,
});
});
test('getLegendLayoutResult counts empty-string legend labels when estimating layout', () => {
expect(
getLegendLayoutResult({
chartHeight: 400,
chartWidth: 116,
legendItems: ['', 'A', 'B', 'C', 'D'],
legendMargin: null,
orientation: LegendOrientation.Top,
show: true,
showSelectors: false,
theme,
type: LegendType.Plain,
}),
).toEqual({
effectiveType: LegendType.Scroll,
});
});
test('resolveLegendLayout returns both raw and effective legend layout values', () => {
expect(
resolveLegendLayout({
chartHeight: 400,
chartWidth: 800,
legendItems: ['Alpha', 'Beta'],
legendMargin: null,
orientation: LegendOrientation.Top,
show: true,
theme,
type: LegendType.Plain,
}),
).toEqual({
effectiveLegendMargin: defaultLegendPadding[LegendOrientation.Top],
effectiveLegendType: LegendType.Plain,
legendLayout: {
effectiveMargin: defaultLegendPadding[LegendOrientation.Top],
effectiveType: LegendType.Plain,
},
});
});
describe('getChartPadding', () => {
test('should handle top default', () => {
expect(getChartPadding(true, LegendOrientation.Top)).toEqual({