Compare commits

...

8 Commits

Author SHA1 Message Date
Abhi Kumar
5318bdec45 feat(charts): let the mean sort compare means as a share of an axis range 2026-12-01 19:48:27 +05:30
Abhi Kumar
03fdbd5a53 feat(uplot): draw one baseline under every value axis
uPlot draws each axis's own edge line only, which leaves axes stacked beside
the plot floating.
2026-12-01 19:48:24 +05:30
Abhi Kumar
e5f4b36833 feat(uplot): show the axis unit on legend rows of multi-axis charts
The layout measures the same label-plus-suffix text the row renders.
2026-12-01 19:48:17 +05:30
Abhi Kumar
89d90fd388 fix(uplot): measure the clicked series on its own scale 2026-12-01 19:48:13 +05:30
Abhi Kumar
0d4476c012 feat(uplot): format tooltip rows in their series' scale unit
The panel unit stays the fallback for a scale without one.
2026-12-01 19:48:09 +05:30
Abhi Kumar
3885c69e8d feat(charts): stack series within their own scale
Totals and bands are kept per scale. A percent stack normalises the primary
scale only; series on other scales keep their raw values.
2026-12-01 19:48:05 +05:30
Abhi Kumar
6d3760c9cb feat(uplot): expose scale units and band stacks per scale
Stack bands pair consecutive series of one scale only. The builder reports
each value scale's unit, and legend items carry theirs once more than one
value axis is drawn.
2026-12-01 19:48:01 +05:30
Abhi Kumar
247ce1a981 feat(uplot): treat every non-x scale as a value axis
Ticks format in the axis unit and the width follows the widest label for any
scale key, not only y. An axis can keep its edge line with a hidden grid and
reserve a margin beyond its labels for an axis stacked outside it.
2026-12-01 19:47:53 +05:30
25 changed files with 500 additions and 56 deletions

View File

@@ -54,7 +54,7 @@ function getPreferredSeriesIndex(
const seriesValue = series?.[timestampIndex];
if (isSeriesValueValid(seriesValue) && u.series[i].show !== false) {
const yPx = u.valToPos(seriesValue as number, 'y');
const yPx = u.valToPos(seriesValue as number, u.series[i].scale ?? 'y');
const diff = Math.abs(yPx - top);
if (diff < closestPixelDiff) {
closestPixelDiff = diff;

View File

@@ -1,11 +1,13 @@
import { KeyboardEvent, memo, MouseEvent, useCallback } from 'react';
import { Button } from '@signozhq/ui/button';
import { Tooltip } from '@signozhq/ui/tooltip';
import { Typography } from '@signozhq/ui/typography';
import cx from 'classnames';
import { LegendItem } from 'lib/uPlotV2/config/types';
import CopyButton from 'periscope/components/CopyButton/CopyButton';
import { LegendAction, OnLegendAction } from '../types';
import { legendUnitSuffix } from './utils';
import styles from './LegendRow.module.scss';
@@ -131,7 +133,23 @@ function LegendRow({
data-testid={`legend-marker-${seriesIndex}`}
/>
<Tooltip title={label} side="top">
<span className={styles.label}>{label}</span>
<span className={styles.label}>
{label}
{/* Inside the label so it truncates with it and the hover actions mask it the same way. */}
{item.unit && (
<Typography
variant="code"
size="small"
weight="regular"
color="tertiary"
as="span"
// Inherits the label's single line; `wrap` let the suffix drop under it.
textOverflow="visible"
>
{legendUnitSuffix(item.unit)}
</Typography>
)}
</span>
</Tooltip>
<div className={styles.actions}>
<Tooltip title={scopeActionLabel} side="top">

View File

@@ -42,3 +42,8 @@ export function getVisibleSeriesState(
areAllSeriesVisible: visible.length === items.length,
};
}
/** The unit suffix a legend row shows after its label; the layout measures the same text. */
export function legendUnitSuffix(unit: string | undefined): string {
return unit ? ` · ${unit}` : '';
}

View File

@@ -15,6 +15,7 @@ export default function BarChartTooltip(props: BarTooltipProps): JSX.Element {
activeSeriesIndex: props.seriesIndex,
uPlotInstance: props.uPlotInstance,
yAxisUnit: props.yAxisUnit ?? '',
scaleUnits: props.scaleUnits,
decimalPrecision: props.decimalPrecision,
isStackedBarChart: props.isStackedBarChart,
syncedSeriesIndexes: props.syncedSeriesIndexes,
@@ -26,6 +27,7 @@ export default function BarChartTooltip(props: BarTooltipProps): JSX.Element {
props.seriesIndex,
props.dataIndexes,
props.yAxisUnit,
props.scaleUnits,
props.decimalPrecision,
props.isStackedBarChart,
props.syncedSeriesIndexes,

View File

@@ -17,6 +17,7 @@ export default function TimeSeriesTooltip(
activeSeriesIndex: props.seriesIndex,
uPlotInstance: props.uPlotInstance,
yAxisUnit: props.yAxisUnit ?? '',
scaleUnits: props.scaleUnits,
decimalPrecision: props.decimalPrecision,
syncedSeriesIndexes: props.syncedSeriesIndexes,
syncFilterMode: props.syncFilterMode,
@@ -27,6 +28,7 @@ export default function TimeSeriesTooltip(
props.seriesIndex,
props.dataIndexes,
props.yAxisUnit,
props.scaleUnits,
props.decimalPrecision,
props.syncedSeriesIndexes,
props.syncFilterMode,

View File

@@ -252,6 +252,35 @@ describe('Tooltip utils', () => {
});
});
it('formats each series in its own scale unit, falling back to the panel unit', () => {
const data: AlignedData = [[0], [10], [20], [30]];
const series = createSeriesConfig();
series[2] = { ...series[2], scale: 'y:lat' } as Series;
const u = createUPlotInstance();
buildTooltipContent({
data,
series,
dataIndexes: [null, 0, 0, 0],
activeSeriesIndex: null,
uPlotInstance: u,
yAxisUnit,
scaleUnits: { 'y:lat': 'percent' },
decimalPrecision,
});
expect(mockGetToolTipValue).toHaveBeenCalledWith(
20,
'percent',
decimalPrecision,
);
expect(mockGetToolTipValue).toHaveBeenCalledWith(
10,
yAxisUnit,
decimalPrecision,
);
});
it('skips series with null data index or non-finite values', () => {
const data: AlignedData = [[0], [42], [Infinity]];
const series: Series[] = [

View File

@@ -62,6 +62,32 @@ export function getTooltipBaseValue({
return baseValue;
}
/** A synced receiver row for a series with nothing at the cursor. */
function noDataItem(
seriesItem: Series,
uPlotInstance: uPlot,
seriesIndex: number,
isHighlighted: boolean,
): TooltipContentItem {
return {
label: String(seriesItem.label ?? ''),
value: 0,
tooltipValue: 'No Data',
color: resolveSeriesColor(seriesItem.stroke, uPlotInstance, seriesIndex),
isActive: false,
isHighlighted,
};
}
/** A series formats in its own scale's unit, falling back to the panel unit. */
function unitForSeries(
seriesItem: Series,
scaleUnits: Record<string, string> | undefined,
yAxisUnit: string,
): string {
return scaleUnits?.[seriesItem.scale ?? ''] ?? yAxisUnit;
}
export function buildTooltipContent({
data,
unstackedData,
@@ -70,6 +96,7 @@ export function buildTooltipContent({
activeSeriesIndex,
uPlotInstance,
yAxisUnit,
scaleUnits,
decimalPrecision,
isStackedBarChart,
syncedSeriesIndexes,
@@ -81,7 +108,10 @@ export function buildTooltipContent({
dataIndexes: Array<number | null>;
activeSeriesIndex: number | null;
uPlotInstance: uPlot;
/** Fallback for a series whose scale has no entry in `scaleUnits`. */
yAxisUnit: string;
/** Unit per value scale key (`UPlotConfigBuilder.getScaleUnits`). */
scaleUnits?: Record<string, string>;
decimalPrecision?: PrecisionOption;
isStackedBarChart?: boolean;
syncedSeriesIndexes?: number[] | null;
@@ -111,14 +141,9 @@ export function buildTooltipContent({
if (dataIndex === null) {
if (isSync) {
items.push({
label: String(seriesItem.label ?? ''),
value: 0,
tooltipValue: 'No Data',
color: resolveSeriesColor(seriesItem.stroke, uPlotInstance, seriesIndex),
isActive: false,
isHighlighted,
});
items.push(
noDataItem(seriesItem, uPlotInstance, seriesIndex, isHighlighted),
);
}
continue;
}
@@ -136,20 +161,19 @@ export function buildTooltipContent({
items.push({
label: String(seriesItem.label ?? ''),
value: baseValue,
tooltipValue: getToolTipValue(baseValue, yAxisUnit, decimalPrecision),
tooltipValue: getToolTipValue(
baseValue,
unitForSeries(seriesItem, scaleUnits, yAxisUnit),
decimalPrecision,
),
color: resolveSeriesColor(seriesItem.stroke, uPlotInstance, seriesIndex),
isActive: seriesIndex === activeSeriesIndex,
isHighlighted,
});
} else if (isSync) {
items.push({
label: String(seriesItem.label ?? ''),
value: 0,
tooltipValue: 'No Data',
color: resolveSeriesColor(seriesItem.stroke, uPlotInstance, seriesIndex),
isActive: false,
isHighlighted,
});
items.push(
noDataItem(seriesItem, uPlotInstance, seriesIndex, isHighlighted),
);
}
}

View File

@@ -92,6 +92,8 @@ export interface BaseTooltipProps {
showTooltipHeader?: boolean;
canPinTooltip?: boolean;
yAxisUnit?: string;
/** Unit per value scale key; a series formats in its own axis unit. */
scaleUnits?: Record<string, string>;
decimalPrecision?: PrecisionOption;
content?: TooltipContentItem[];
renderTooltipFooter?: (args: IRenderTooltipFooterArgs) => ReactNode;

View File

@@ -39,11 +39,12 @@ export class UPlotAxisBuilder extends ConfigBuilder<AxisProps, Axis> {
};
}
/** Styled like the grid. */
/** Styled like the grid. Follows the grid's visibility unless `showBorder` says otherwise. */
private buildBorderConfig(
grid: uPlot.Axis.Grid | undefined,
): uPlot.Axis.Border | undefined {
if (this.props.showBorder === false || !grid || grid.show === false) {
const { showBorder } = this.props;
if (showBorder === false || !grid || (grid.show === false && !showBorder)) {
return undefined;
}
return { show: true, stroke: grid.stroke, width: grid.width };
@@ -123,12 +124,10 @@ export class UPlotAxisBuilder extends ConfigBuilder<AxisProps, Axis> {
return values;
}
// Route to appropriate formatter based on scale key
// Every scale but x is a value scale.
return scaleKey === 'x'
? this.buildXAxisValuesFormatter()
: scaleKey === 'y'
? this.buildValueAxisFormatter()
: undefined;
: this.buildValueAxisFormatter();
}
/**
@@ -142,9 +141,9 @@ export class UPlotAxisBuilder extends ConfigBuilder<AxisProps, Axis> {
return size;
}
// Y-axis needs dynamic sizing based on text width
if (scaleKey === 'y') {
return buildYAxisSizeCalculator(this.props.gap ?? 5);
// Value axes size to their widest label.
if (scaleKey !== 'x') {
return buildYAxisSizeCalculator(this.props.gap ?? 5, this.props.outerMargin);
}
return undefined;

View File

@@ -261,7 +261,7 @@ export class UPlotConfigBuilder extends ConfigBuilder<
});
}
/** Explicit bands win; otherwise a stack fills between consecutive series. */
/** Explicit bands win; otherwise a stack fills between consecutive series on the same scale. */
private resolveBands(): uPlot.Band[] | undefined {
if (this.bands.length > 0) {
return this.bands;
@@ -269,11 +269,37 @@ export class UPlotConfigBuilder extends ConfigBuilder<
if (this.stackMode === StackMode.None || this.series.length < 2) {
return undefined;
}
return (
this.series
.slice(0, -1)
const bands: uPlot.Band[] = [];
this.series.forEach((series, index) => {
const nextIndex = this.series.findIndex(
(candidate, candidateIndex) =>
candidateIndex > index &&
candidate.props.scaleKey === series.props.scaleKey,
);
if (nextIndex !== -1) {
// uPlot series are 1-based (index 0 is the timestamp axis).
.map((_, index) => ({ series: [index + 1, index + 2] as [number, number] }))
bands.push({ series: [index + 1, nextIndex + 1] });
}
});
return bands.length > 0 ? bands : undefined;
}
/** Unit of each value scale, keyed by scale key; the source of truth for tooltips and legends. */
getScaleUnits(): Record<string, string> {
const units: Record<string, string> = {};
Object.values(this.axes).forEach(({ props }) => {
if (props.scaleKey !== 'x' && props.yAxisUnit) {
units[props.scaleKey] = props.yAxisUnit;
}
});
return units;
}
private hasMultipleValueAxes(): boolean {
return (
Object.values(this.axes).filter(
({ props }) => props.scaleKey !== 'x' && props.show !== false,
).length > 1
);
}
@@ -421,11 +447,13 @@ export class UPlotConfigBuilder extends ConfigBuilder<
getLegendItems(): Record<number, LegendItem> {
const { visibleStoredLabels, hiddenStoredLabels, hasActivePreference } =
this.getVisibilityResolutionState();
const scaleUnits = this.hasMultipleValueAxes() ? this.getScaleUnits() : {};
return this.series.reduce(
(acc, s: UPlotSeriesBuilder, index: number) => {
const seriesConfig = s.getConfig();
const label = seriesConfig.label ?? '';
const unit = scaleUnits[seriesConfig.scale ?? ''];
// +1 because uPlot series 0 is x-axis/time; data series are at 1, 2, ... (also matches stored visibility[0]=time, visibility[1]=first data, ...)
const seriesIndex = index + 1;
const show = resolveSeriesVisibility({
@@ -441,6 +469,7 @@ export class UPlotConfigBuilder extends ConfigBuilder<
color: seriesConfig.stroke,
label,
show,
...(unit && { unit }),
};
return acc;

View File

@@ -306,12 +306,12 @@ describe('UPlotAxisBuilder', () => {
expect(config.values).toBe(customValues);
});
it('returns undefined values for scaleKey neither x nor y', () => {
it('formats a custom scale key as a value axis', () => {
const builder = new UPlotAxisBuilder(createAxisProps({ scaleKey: 'custom' }));
const config = builder.getConfig();
expect(config.values).toBeUndefined();
expect(typeof config.values).toBe('function');
});
it('includes space in config when provided', () => {
@@ -458,4 +458,29 @@ describe('UPlotAxisBuilder out-of-range splits', () => {
expect(values).toStrictEqual(['', '0 ms', '500 ms', '']);
});
it('formats and sizes any non-x scale as a value axis', () => {
const config = new UPlotAxisBuilder(
createAxisProps({ scaleKey: 'y:lat', yAxisUnit: 'ms' }),
).getConfig();
const scales = {
'y:lat': { min: 0, max: 100 },
} as unknown as uPlot['scales'];
(config.values as (u: uPlot, t: number[]) => string[])(
{ scales } as unknown as uPlot,
[50],
);
expect(getToolTipValue).toHaveBeenCalledWith('50', 'ms', undefined);
expect(typeof config.size).toBe('function');
});
it('keeps the axis line on a hidden grid when showBorder is set', () => {
const config = new UPlotAxisBuilder(
createAxisProps({ grid: { show: false }, showBorder: true }),
).getConfig();
expect(config.border).toMatchObject({ show: true });
});
});

View File

@@ -682,4 +682,53 @@ describe('UPlotConfigBuilder plot mode', () => {
faceted.setMode(PlotMode.Faceted);
expect(faceted.getConfig().mode).toBe(2);
});
describe('value scales', () => {
const createSeriesProps = (overrides: Partial<SeriesProps>): SeriesProps => ({
scaleKey: 'y',
colorMapping: {},
drawStyle: DrawStyle.Line,
...overrides,
});
function createTwoAxisBuilder(): UPlotConfigBuilder {
const builder = new UPlotConfigBuilder({ id: 'widget-123' });
builder.addAxis({ scaleKey: 'x', isTimeAxis: true });
builder.addAxis({ scaleKey: 'y', yAxisUnit: 'reqps' });
builder.addAxis({ scaleKey: 'y:lat', yAxisUnit: 'ms', side: 1 });
builder.addSeries(createSeriesProps({ label: 'Requests' }));
builder.addSeries(createSeriesProps({ label: 'p99', scaleKey: 'y:lat' }));
builder.addSeries(createSeriesProps({ label: 'p50', scaleKey: 'y:lat' }));
return builder;
}
it('reports the unit of every value scale', () => {
expect(createTwoAxisBuilder().getScaleUnits()).toStrictEqual({
y: 'reqps',
'y:lat': 'ms',
});
});
it('labels legend items with their axis unit only when there is more than one value axis', () => {
const twoAxes = createTwoAxisBuilder().getLegendItems();
expect(twoAxes[1].unit).toBe('reqps');
expect(twoAxes[2].unit).toBe('ms');
const oneAxis = new UPlotConfigBuilder({ id: 'widget-123' });
oneAxis.addAxis({ scaleKey: 'y', yAxisUnit: 'reqps' });
oneAxis.addSeries(createSeriesProps({ label: 'Requests' }));
expect(oneAxis.getLegendItems()[1]).not.toHaveProperty('unit');
// A hidden axis is not on screen to explain a unit.
oneAxis.addAxis({ scaleKey: 'y:lat', yAxisUnit: 'ms', show: false });
expect(oneAxis.getLegendItems()[1]).not.toHaveProperty('unit');
});
it('fills stack bands only between consecutive series on the same scale', () => {
const builder = createTwoAxisBuilder();
builder.setStackMode(StackMode.Normal);
expect(builder.getConfig().bands).toStrictEqual([{ series: [2, 3] }]);
});
});
});

View File

@@ -52,8 +52,8 @@ export interface ConfigBuilderProps {
* Props for configuring an axis
*/
export interface AxisProps {
/** Scale this axis is drawn against — `'x'` / `'y'`, matching an `addScale` key. Also
* selects the default tick formatter and sizing (x: time, y: value + unit). */
/** Scale this axis is drawn against, matching an `addScale` key. `'x'` gets the time
* formatter; every other key is a value scale (unit-formatted ticks, label-width sizing). */
scaleKey: string;
/** Axis title drawn alongside the ticks; omitted when there's nothing to name. */
label?: string;
@@ -82,12 +82,15 @@ export interface AxisProps {
splits?: uPlot.Axis.Splits;
/** Which splits get a label, replacing uPlot's per-distribution default. */
filter?: uPlot.Axis.Filter;
/** Draw the axis line along the plot edge, styled like the grid. Default true. */
/** Draw the axis line along the plot edge, styled like the grid. Unset follows the grid's
* visibility; `true` keeps the line on an axis whose grid is hidden. */
showBorder?: boolean;
/** Pixels between the ticks and their labels; also feeds the y axis width calculation. */
gap?: number;
/** Explicit axis thickness. Left unset, the y axis sizes itself to its widest label. */
size?: uPlot.Axis.Size;
/** Pixels kept free beyond a value axis's labels, for an axis stacked outside it. */
outerMargin?: number;
/** Minimum pixels between ticks, capping how many uPlot draws. For log scale axes. */
space?: number;
/** Picks the dark or light default for stroke and grid color. */
@@ -250,4 +253,6 @@ export interface LegendItem {
label: uPlot.Series['label'];
color: uPlot.Series['stroke'];
show: boolean;
/** The series' axis unit; set only when the chart has more than one value axis. */
unit?: string;
}

View File

@@ -0,0 +1,67 @@
import type uPlot from 'uplot';
import { axisBaselineDrawHook } from '../axisBaselineDrawHook';
function createPlot(axes: object[]): {
plot: uPlot;
moveTo: jest.Mock;
lineTo: jest.Mock;
} {
const moveTo = jest.fn();
const lineTo = jest.fn();
const plot = {
axes,
bbox: { left: 100, top: 10, width: 400, height: 200 },
ctx: {
save: jest.fn(),
restore: jest.fn(),
beginPath: jest.fn(),
stroke: jest.fn(),
moveTo,
lineTo,
},
} as unknown as uPlot;
return { plot, moveTo, lineTo };
}
const xAxis = {
side: 2,
show: true,
border: { show: true, stroke: '#333', width: 1 },
};
describe('axisBaselineDrawHook', () => {
it('runs the baseline from the outermost left axis to the outermost right one', () => {
const { plot, moveTo, lineTo } = createPlot([
xAxis,
{ side: 3, show: true, _pos: 60, _size: 40 },
{ side: 3, show: true, _pos: 20, _size: 40 },
{ side: 1, show: true, _pos: 500, _size: 50 },
]);
axisBaselineDrawHook(plot);
expect(moveTo).toHaveBeenCalledWith(20, 210);
expect(lineTo).toHaveBeenCalledWith(550, 210);
});
it('ignores hidden axes and keeps to the plot edge without any', () => {
const { plot, moveTo, lineTo } = createPlot([
xAxis,
{ side: 3, show: false, _pos: 20, _size: 40 },
]);
axisBaselineDrawHook(plot);
expect(moveTo).toHaveBeenCalledWith(100, 210);
expect(lineTo).toHaveBeenCalledWith(500, 210);
});
it('draws nothing when the x axis has no border to match', () => {
const { plot, moveTo } = createPlot([{ side: 2, show: true }]);
axisBaselineDrawHook(plot);
expect(moveTo).not.toHaveBeenCalled();
});
});

View File

@@ -0,0 +1,47 @@
import uPlot, { type Axis } from 'uplot';
/** uPlot keeps each laid-out axis's slot on the axis object, in CSS pixels. */
type LaidOutAxis = Axis & { _pos?: number; _size?: number; _show?: boolean };
const RIGHT = 1;
const LEFT = 3;
/**
* Draws one line along the bottom of the plot that runs under every value axis, so
* axes stacked beside the plot read as attached to it. uPlot draws only each axis's
* own edge line, which leaves the outer ones floating. Styled like the x axis border.
*/
export function axisBaselineDrawHook(plot: uPlot): void {
const axes = plot.axes as LaidOutAxis[];
const xAxis = axes[0];
const border = xAxis?.border;
if (!border || border.show === false || typeof border.stroke !== 'string') {
return;
}
const { pxRatio } = uPlot;
let left = plot.bbox.left;
let right = plot.bbox.left + plot.bbox.width;
axes.forEach((axis) => {
if (!axis.show || axis._show === false || axis._pos === undefined) {
return;
}
const size = axis._size ?? 0;
if (axis.side === LEFT) {
left = Math.min(left, axis._pos * pxRatio);
} else if (axis.side === RIGHT) {
right = Math.max(right, (axis._pos + size) * pxRatio);
}
});
const { ctx } = plot;
const y = Math.round(plot.bbox.top + plot.bbox.height);
ctx.save();
ctx.strokeStyle = border.stroke;
ctx.lineWidth = (border.width ?? 1) * pxRatio;
ctx.beginPath();
ctx.moveTo(Math.round(left), y);
ctx.lineTo(Math.round(right), y);
ctx.stroke();
ctx.restore();
}

View File

@@ -182,6 +182,24 @@ describe('axis utils', () => {
expect(result).toBe(expected);
});
it('keeps the outer margin free beyond the labels', () => {
const sizeCalculator = buildYAxisSizeCalculator(5, 8);
const axis: Axis = {
ticks: { size: 10 },
font: ['12px sans-serif'] as unknown as string,
};
const self = {
axes: [axis],
ctx: { font: '', measureText: jest.fn(() => ({ width: 0 })) },
} as unknown as uPlot;
if (typeof sizeCalculator === 'number') {
throw new Error('Size calculator is a number');
}
expect(sizeCalculator(self, ['1'], 0, 0)).toBe(23);
});
it('uses 0 ticks size when ticks are not defined', () => {
const gap = 4;
const sizeCalculator = buildYAxisSizeCalculator(gap);

View File

@@ -52,7 +52,15 @@ export function getExistingAxisSize({
return existingSize ?? 0;
}
export function buildYAxisSizeCalculator(gap: number): uPlot.Axis.Size {
/**
* Sizes a value axis to its widest label. `outerMargin` is kept free beyond the labels,
* which uPlot draws on the plot side of the slot, so an axis stacked outside this one
* does not touch them.
*/
export function buildYAxisSizeCalculator(
gap: number,
outerMargin = 0,
): uPlot.Axis.Size {
return (
self: uPlot,
values: string[] | undefined,
@@ -72,7 +80,7 @@ export function buildYAxisSizeCalculator(gap: number): uPlot.Axis.Size {
});
}
let axisSize = (axis.ticks?.size ?? 0) + gap;
let axisSize = (axis.ticks?.size ?? 0) + gap + outerMargin;
axisSize += calculateTextWidth(self, axis, values);
return Math.ceil(axisSize);

View File

@@ -35,6 +35,7 @@ export default function BarChart(props: BarChartProps): JSX.Element {
id: config.getId(),
timezone: rest.timezone,
yAxisUnit: rest.yAxisUnit,
scaleUnits: config.getScaleUnits(),
decimalPrecision: rest.decimalPrecision,
canPinTooltip: rest.canPinTooltip,
renderTooltipFooter: rest.renderTooltipFooter,
@@ -43,6 +44,7 @@ export default function BarChart(props: BarChartProps): JSX.Element {
},
[
customTooltip,
config,
rest.timezone,
rest.yAxisUnit,
rest.decimalPrecision,

View File

@@ -13,6 +13,7 @@ function createConfig(stack: StackMode): {
} {
const hooks: Hooks = {};
const config = {
series: [],
getStackMode: (): StackMode => stack,
addHook: jest.fn((type: string, hook: (...args: unknown[]) => void) => {
hooks[type] = hook;
@@ -53,6 +54,17 @@ describe('useChartStacking', () => {
expect(result.current).toStrictEqual([[1], [100], [25]]);
});
it('leaves series off the primary scale raw under `percent`', () => {
const { config } = createConfig(StackMode.Percent);
(config as { series: unknown[] }).series = [
{ props: { scaleKey: 'y' } },
{ props: { scaleKey: 'y:lat' } },
];
const { result } = renderHook(() => useChartStacking({ data, config }));
expect(result.current).toStrictEqual([[1], [100], [10]]);
});
it('registers the uPlot hooks that re-stack on data and visibility changes', () => {
const { config } = createConfig(StackMode.Normal);
renderHook(() => useChartStacking({ data, config }));

View File

@@ -12,11 +12,28 @@ import uPlot from 'uplot';
import { stackSeries } from 'lib/visualization/charts/utils/stackSeriesUtils';
/** The scale the percent stack and its axis special cases apply to. */
const PRIMARY_SCALE_KEY = 'y';
/** Returns true if the series at the given index is hidden (e.g. via legend toggle). */
function isSeriesHidden(plot: uPlot, seriesIndex: number): boolean {
return !plot.series[seriesIndex]?.show;
}
/**
* Hidden series never stack. A percent stack normalises the primary axis only:
* a share of another axis's total would be drawn against the wrong 0–100.
*/
function omitFromStack(
stack: StackMode,
groupOf: (seriesIndex: number) => string,
isHidden: (seriesIndex: number) => boolean,
): (seriesIndex: number) => boolean {
return (seriesIndex: number): boolean =>
isHidden(seriesIndex) ||
(stack === StackMode.Percent && groupOf(seriesIndex) !== PRIMARY_SCALE_KEY);
}
function canApplyStacking(
unstackedData: uPlot.AlignedData | null,
plot: uPlot,
@@ -85,13 +102,24 @@ export function useChartStacking({
// Guards the re-entrant setData below, which would otherwise re-trigger our own hook.
const isUpdatingChartRef = useRef(false);
// Series stack only with series on their own Y axis.
const groupOf = useCallback(
(seriesIndex: number): string =>
config?.series[seriesIndex - 1]?.props.scaleKey ?? PRIMARY_SCALE_KEY,
[config],
);
const chartData = useMemo((): uPlot.AlignedData => {
if (stack === StackMode.None || !data || data.length < 2) {
return data;
}
const noSeriesHidden = (): boolean => false; // include all series in initial stack
return stackSeries(data, noSeriesHidden, stack).data;
}, [data, stack]);
return stackSeries(
data,
omitFromStack(stack, groupOf, () => false),
stack,
groupOf,
).data;
}, [data, stack, groupOf]);
const updateStacksInChart = useCallback(
(plot: uPlot): void => {
@@ -103,12 +131,11 @@ export function useChartStacking({
return;
}
const shouldExcludeSeries = (idx: number): boolean =>
isSeriesHidden(plot, idx);
const { data: stacked, bands } = stackSeries(
unstacked,
shouldExcludeSeries,
omitFromStack(stack, groupOf, (idx) => isSeriesHidden(plot, idx)),
stack,
groupOf,
);
plot.delBand(null);
@@ -118,7 +145,7 @@ export function useChartStacking({
plot.setData(stacked);
isUpdatingChartRef.current = false;
},
[stack],
[stack, groupOf],
);
useLayoutEffect(() => {

View File

@@ -27,6 +27,7 @@ export default function TimeSeries(props: TimeSeriesChartProps): JSX.Element {
id: rest.config.getId(),
timezone: rest.timezone,
yAxisUnit: rest.yAxisUnit,
scaleUnits: rest.config.getScaleUnits(),
decimalPrecision: rest.decimalPrecision,
canPinTooltip: rest.canPinTooltip,
renderTooltipFooter: rest.renderTooltipFooter,
@@ -35,6 +36,7 @@ export default function TimeSeries(props: TimeSeriesChartProps): JSX.Element {
},
[
customTooltip,
rest.config,
rest.timezone,
rest.yAxisUnit,
rest.decimalPrecision,

View File

@@ -164,4 +164,41 @@ describe('stackSeries', () => {
stackSeries(data, includeAll, StackMode.Normal).data,
);
});
describe('groups', () => {
// Series 1–2 share one axis, 3–4 another; each axis keeps its own total.
const groupOf = (seriesIndex: number): string =>
seriesIndex <= 2 ? 'y' : 'y:lat';
it('accumulates and bands only within a group', () => {
const data: AlignedData = [[1], [10], [10], [30], [10]];
const { data: stacked, bands } = stackSeries(
data,
includeAll,
StackMode.Normal,
groupOf,
);
expect(stacked).toStrictEqual([[1], [20], [10], [40], [10]]);
expect(bands).toStrictEqual([{ series: [1, 2] }, { series: [3, 4] }]);
});
it('normalises percent against the group total', () => {
const data: AlignedData = [[1], [10], [10], [30], [10]];
expect(
stackSeries(data, includeAll, StackMode.Percent, groupOf).data,
).toStrictEqual([[1], [100], [50], [100], [25]]);
});
it('skips a hidden series without bridging the band to the other group', () => {
const data: AlignedData = [[1], [10], [10], [30], [10]];
const hideSecond = (seriesIndex: number): boolean => seriesIndex === 2;
const { bands } = stackSeries(data, hideSecond, StackMode.Normal, groupOf);
expect(bands).toStrictEqual([{ series: [3, 4] }]);
});
});
});

View File

@@ -17,6 +17,11 @@ export interface SortByMeanDescOptions<T> {
getValues: (item: T) => Iterable<MeanInput>;
/** Stable identity of an item, used to break ties on equal means. */
getKey: (item: T) => string;
/**
* The range of the item's axis. Means are compared as a share of it, so items on
* different axes order by plotted height rather than raw magnitude.
*/
getAxisRange?: (item: T) => number;
}
/**
@@ -28,10 +33,15 @@ export interface SortByMeanDescOptions<T> {
*/
export function sortByMeanDesc<T>(
items: T[],
{ getValues, getKey }: SortByMeanDescOptions<T>,
{ getValues, getKey, getAxisRange }: SortByMeanDescOptions<T>,
): T[] {
const plottedMean = (item: T): number | null => {
const mean = finiteMean(getValues(item));
const range = getAxisRange?.(item);
return mean !== null && range ? mean / range : mean;
};
return items
.map((item) => ({ item, mean: finiteMean(getValues(item)) }))
.map((item) => ({ item, mean: plottedMean(item) }))
.sort((a, b) => {
if (a.mean !== null && b.mean !== null && a.mean !== b.mean) {
return b.mean - a.mean;

View File

@@ -1,15 +1,20 @@
import { StackMode } from 'lib/uPlotV2/config/types';
import uPlot, { AlignedData } from 'uplot';
const SINGLE_GROUP = (): string => '';
/**
* Stack data cumulatively (top-down: first series = top, last = bottom).
* When `omit(seriesIndex)` returns true, that series keeps its raw values and
* contributes nothing to the total. `None` is a no-op.
* contributes nothing to the total. `None` is a no-op. Series stack only with
* series `groupOf` puts in the same group (one group per Y axis); the default
* is one group.
*/
export function stackSeries(
data: AlignedData,
omit: (seriesIndex: number) => boolean,
mode: StackMode = StackMode.Normal,
groupOf: (seriesIndex: number) => string = SINGLE_GROUP,
): { data: AlignedData; bands: uPlot.Band[] } {
if (mode === StackMode.None) {
return { data, bands: [] };
@@ -25,8 +30,9 @@ export function stackSeries(
pointCount,
omit,
mode,
groupOf,
});
const bands = buildFillBands(valueSeriesCount + 1, omit); // +1 for 1-based series indices
const bands = buildFillBands(valueSeriesCount + 1, omit, groupOf); // +1 for 1-based series indices
return {
data: [timeAxis, ...stackedSeries] as AlignedData,
@@ -40,6 +46,7 @@ interface BuildStackedSeriesParams {
pointCount: number;
omit: (seriesIndex: number) => boolean;
mode: StackMode;
groupOf: (seriesIndex: number) => string;
}
/** A column whose participating series sum to 0 has no share to divide, so every slice is 0. */
@@ -57,9 +64,19 @@ function buildStackedSeries({
pointCount,
omit,
mode,
groupOf,
}: BuildStackedSeriesParams): (number | null)[][] {
const stackedSeries: (number | null)[][] = Array(valueSeriesCount);
const columnTotals = Array(pointCount).fill(0) as number[];
const groupTotals = new Map<string, number[]>();
const totalsOf = (seriesIndex: number): number[] => {
const group = groupOf(seriesIndex);
let totals = groupTotals.get(group);
if (!totals) {
totals = Array(pointCount).fill(0) as number[];
groupTotals.set(group, totals);
}
return totals;
};
for (let seriesIndex = valueSeriesCount; seriesIndex >= 1; seriesIndex--) {
const rawValues = data[seriesIndex] as (number | null)[];
@@ -67,6 +84,7 @@ function buildStackedSeries({
if (omit(seriesIndex)) {
stackedSeries[seriesIndex - 1] = rawValues;
} else {
const columnTotals = totalsOf(seriesIndex);
stackedSeries[seriesIndex - 1] = rawValues.map((rawValue, pointIndex) => {
const numericValue = rawValue == null ? 0 : Number(rawValue);
return (columnTotals[pointIndex] += numericValue);
@@ -85,6 +103,7 @@ function buildStackedSeries({
if (omit(seriesIndex)) {
continue;
}
const columnTotals = totalsOf(seriesIndex);
stackedSeries[seriesIndex - 1] = stackedSeries[seriesIndex - 1].map(
(value, pointIndex) => toPercent(value as number, columnTotals[pointIndex]),
);
@@ -94,12 +113,13 @@ function buildStackedSeries({
}
/**
* Bands define fill between consecutive visible series for stacked appearance.
* Bands define fill between consecutive visible series of a group for stacked appearance.
* uPlot format: [upperSeriesIdx, lowerSeriesIdx].
*/
function buildFillBands(
seriesLength: number,
omit: (seriesIndex: number) => boolean,
groupOf: (seriesIndex: number) => string,
): uPlot.Band[] {
const bands: uPlot.Band[] = [];
@@ -110,7 +130,8 @@ function buildFillBands(
const nextVisibleSeriesIndex = findNextVisibleSeriesIndex(
seriesLength,
seriesIndex,
omit,
(candidate) =>
omit(candidate) || groupOf(candidate) !== groupOf(seriesIndex),
);
if (nextVisibleSeriesIndex !== -1) {
bands.push({ series: [seriesIndex, nextVisibleSeriesIndex] });

View File

@@ -1,4 +1,5 @@
import { useMemo } from 'react';
import { legendUnitSuffix } from 'lib/uPlotV2/components/Legend/utils';
import cx from 'classnames';
import { calculateChartDimensions } from 'lib/visualization/charts/utils';
import { MAX_LEGEND_WIDTH } from 'lib/uPlotV2/components/Legend/constants';
@@ -62,8 +63,11 @@ export default function ChartLayout({
const seriesLabels =
seriesLabelsOverride ??
Object.values(config.getLegendItems())
.map((item) => item.label)
.filter((label): label is string => label !== undefined);
.filter(
(item): item is typeof item & { label: string } =>
item.label !== undefined,
)
.map((item) => item.label + legendUnitSuffix(item.unit));
return calculateChartDimensions({
containerWidth,
containerHeight,