Skip to content

Commit f56c10f

Browse files
committed
fix(echarts): reserve multiline legend row height
1 parent 9b8da16 commit f56c10f

3 files changed

Lines changed: 145 additions & 4 deletions

File tree

‎superset-frontend/plugins/plugin-chart-echarts/src/utils/series.ts‎

Lines changed: 28 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -61,6 +61,7 @@ const DEFAULT_LEGEND_ICON_WIDTH = 25;
6161
const LEGEND_ICON_LABEL_GAP = 5;
6262
const LEGACY_LEGEND_HORIZONTAL_SIDE_GUTTER = 16;
6363
const ECHARTS_LEGEND_HORIZONTAL_PADDING = 10;
64+
const ECHARTS_LEGEND_PADDING = 5;
6465
const LEGACY_LEGEND_HORIZONTAL_ROW_HEIGHT = 24;
6566
const MAX_LEGEND_MARGIN_RATIO = 0.4;
6667
const LEGEND_VERTICAL_SIDE_GUTTER = 16;
@@ -70,6 +71,12 @@ const LEGEND_MARGIN_GUTTER = 45;
7071
// values intentionally overestimate selector space to avoid clipping.
7172
const ESTIMATED_LEGEND_SELECTOR_WIDTH = 112;
7273
const LEGEND_TEXT_WIDTH_CACHE = new Map<string, number>();
74+
// The two 20px Timeseries offsets, less ECharts' 5px inset, accommodate a
75+
// final legend row up to this height without additional margin.
76+
const TIMESERIES_HORIZONTAL_LEGEND_ROW_CLEARANCE =
77+
defaultLegendPadding[LegendOrientation.Top] +
78+
TIMESERIES_CONSTANTS.gridOffsetTop -
79+
ECHARTS_LEGEND_PADDING;
7380

7481
type LegendDataItem =
7582
| string
@@ -260,7 +267,8 @@ function estimateEchartsHorizontalLegendAdditionalMargin(
260267
let currentLineMaxHeight = 0;
261268
let currentX = 0;
262269
let currentY = 0;
263-
const rowOffsets: number[] = [];
270+
let hasLeadingRowBreak = false;
271+
const positionedItems: { height: number; y: number }[] = [];
264272

265273
itemRects.forEach((rect, index) => {
266274
const nextRect = itemRects[index + 1];
@@ -278,13 +286,30 @@ function estimateEchartsHorizontalLegendAdditionalMargin(
278286
currentLineMaxHeight = Math.max(currentLineMaxHeight, rect.height);
279287
}
280288
if (rect.newline) {
289+
if (positionedItems.length === 0) {
290+
hasLeadingRowBreak = true;
291+
}
281292
return;
282293
}
283-
rowOffsets.push(currentY);
294+
positionedItems.push({ height: rect.height, y: currentY });
284295
currentX = nextX + ECHARTS_LEGEND_ITEM_GAP;
285296
});
286297

287-
return Math.max(0, (rowOffsets.at(-1) ?? 0) - (rowOffsets[0] ?? 0));
298+
const lastRowOffset = positionedItems.at(-1)?.y;
299+
if (lastRowOffset === undefined) {
300+
return 0;
301+
}
302+
const firstRowOffset = hasLeadingRowBreak ? 0 : (positionedItems[0]?.y ?? 0);
303+
const lastRowHeight = Math.max(
304+
...positionedItems
305+
.filter(item => item.y === lastRowOffset)
306+
.map(item => item.height),
307+
);
308+
309+
return (
310+
Math.max(0, lastRowOffset - firstRowOffset) +
311+
Math.max(0, lastRowHeight - TIMESERIES_HORIZONTAL_LEGEND_ROW_CLEARANCE)
312+
);
288313
}
289314

290315
export function getHorizontalLegendAvailableWidth({

‎superset-frontend/plugins/plugin-chart-echarts/test/Timeseries/transformProps.test.ts‎

Lines changed: 89 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -36,7 +36,7 @@ import {
3636
} from '@superset-ui/core';
3737
import { GenericDataType } from '@apache-superset/core/common';
3838
import { supersetTheme } from '@apache-superset/core/theme';
39-
import type { SeriesOption } from 'echarts';
39+
import { init, type SeriesOption } from 'echarts';
4040
import type { GridComponentOption } from 'echarts/components';
4141
import transformProps from '../../src/Timeseries/transformProps';
4242
import {
@@ -1252,6 +1252,94 @@ test('reserves Forecast legend rows using the final rendered series order', () =
12521252
expect(transformed.contentHeight).toBeCloseTo(966.8);
12531253
});
12541254

1255+
test.each([3, 4, 6])(
1256+
'keeps a rendered %i-line final legend row above the plot',
1257+
lineCount => {
1258+
const multilineLegendName = Array.from(
1259+
{ length: lineCount },
1260+
(_, index) => `Dimension ${index + 1}`,
1261+
).join('\n');
1262+
const chartProps = createTestChartProps({
1263+
width: 800,
1264+
height: 400,
1265+
formData: {
1266+
...formData,
1267+
legendType: LegendType.Plain,
1268+
legendOrientation: LegendOrientation.Top,
1269+
showLegend: true,
1270+
yAxisTitleMargin: 0,
1271+
yAxisTitlePosition: 'Left',
1272+
},
1273+
queriesData: [
1274+
createTestQueryData(
1275+
createTestData([{ [multilineLegendName]: 1 }], {
1276+
intervalMs: 300000000,
1277+
}),
1278+
),
1279+
],
1280+
});
1281+
const getContext = jest
1282+
.spyOn(HTMLCanvasElement.prototype, 'getContext')
1283+
.mockReturnValue({
1284+
font: '',
1285+
measureText: (text: string) => ({
1286+
width: text === '国' ? 12 : text.length * 7,
1287+
}),
1288+
} as unknown as CanvasRenderingContext2D);
1289+
const transformed = transformProps(chartProps);
1290+
const chart = init(null, null, {
1291+
height: transformed.contentHeight,
1292+
renderer: 'svg',
1293+
ssr: true,
1294+
width: transformed.width,
1295+
});
1296+
1297+
try {
1298+
chart.setOption(transformed.echartOptions);
1299+
type BoundingRect = {
1300+
applyTransform: (transform?: number[]) => void;
1301+
clone: () => BoundingRect;
1302+
height: number;
1303+
y: number;
1304+
};
1305+
type LegendView = {
1306+
__model?: { mainType?: string };
1307+
getContentGroup: () => {
1308+
getBoundingRect: () => BoundingRect;
1309+
getComputedTransform: () => number[] | undefined;
1310+
};
1311+
};
1312+
const legendView = (
1313+
chart as unknown as { _componentsViews: LegendView[] }
1314+
)._componentsViews.find(view => view.__model?.mainType === 'legend');
1315+
const contentGroup = legendView?.getContentGroup();
1316+
if (!contentGroup) {
1317+
throw new Error('Expected ECharts to render a legend content group');
1318+
}
1319+
const legendRect = contentGroup.getBoundingRect().clone();
1320+
legendRect.applyTransform(contentGroup.getComputedTransform());
1321+
const legendBottom = legendRect.y + legendRect.height;
1322+
const gridModel = (
1323+
chart as unknown as {
1324+
getModel: () => {
1325+
getComponent: (mainType: string) => {
1326+
coordinateSystem: { getRect: () => { y: number } };
1327+
};
1328+
};
1329+
}
1330+
)
1331+
.getModel()
1332+
.getComponent('grid');
1333+
const plotTop = gridModel.coordinateSystem.getRect().y;
1334+
1335+
expect(legendBottom - plotTop).toBeCloseTo(0);
1336+
} finally {
1337+
chart.dispose();
1338+
getContext.mockRestore();
1339+
}
1340+
},
1341+
);
1342+
12551343
test('grows the content instead of using a negative offset for a pathological Plain legend', () => {
12561344
const chartHeight = 200;
12571345
const pathologicalLegendValues = Object.fromEntries(

‎superset-frontend/plugins/plugin-chart-echarts/test/utils/series.test.ts‎

Lines changed: 28 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1775,6 +1775,34 @@ test.each(['', '\n'])(
17751775
},
17761776
);
17771777

1778+
test.each([
1779+
{ expectedContentHeight: 21.6, expectedMargin: 28, legendItems: ['', 'B'] },
1780+
{
1781+
expectedContentHeight: 29.6,
1782+
expectedMargin: 36,
1783+
legendItems: ['', '\n', 'B'],
1784+
},
1785+
])(
1786+
'getLegendLayoutResult preserves leading row-break space for $legendItems',
1787+
({ expectedContentHeight, expectedMargin, legendItems }) => {
1788+
expectTimeseriesLegendLayoutMatchesEcharts({
1789+
chartWidth: 600,
1790+
expectedContentHeight,
1791+
expectedMargin,
1792+
expectedRows: 2,
1793+
legendItems,
1794+
series: [
1795+
{
1796+
data: [0, 1],
1797+
name: 'B',
1798+
symbol: 'emptyCircle',
1799+
type: 'line',
1800+
},
1801+
],
1802+
});
1803+
},
1804+
);
1805+
17781806
test('getLegendLayoutResult uses Line geometry for shown annotation layers', () => {
17791807
const observationNames = Array.from(
17801808
{ length: 38 },

0 commit comments

Comments
 (0)