Compare commits

...

12 Commits

Author SHA1 Message Date
Abhi Kumar
0b4f3808bc test(storybook): add secondary axis controls to the Panels story 2026-12-01 19:49:46 +05:30
Abhi Kumar
61ab580e56 feat(dashboards): draw series on the secondary axis that names them
A series is bound by the column key Table's columnUnits use; an unbound key
stays on the primary axis. Series paint tallest-on-their-axis first, so a
short bar on any axis shows over a tall one.
2026-12-01 19:49:43 +05:30
Abhi Kumar
f3465d7aa3 feat(dashboards): resolve a panel's y axes from its spec
resolveAxes turns the primary fields and axes.secondary[] into one list the
chart scaffolding loops over: a scale, an axis and a threshold hook each,
gridlines on the first drawn axis, a margin between axes on one side.
2026-12-01 19:49:38 +05:30
Abhi Kumar
5059b0c59a chore(api): regenerate the dashboard DTOs
The reflector flattens embedded structs, so ThresholdWithLabel no longer has a
schema of its own; its readers take AxisThreshold.
2026-12-01 19:49:27 +05:30
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
53 changed files with 1625 additions and 223 deletions

View File

@@ -5448,12 +5448,77 @@ export interface DashboardtypesAreaChartAppearanceDTO {
spanGaps?: DashboardtypesSpanGapsDTO;
}
export interface DashboardtypesAxisChartAppearanceDTO {
/**
* @description How points are joined: linear, spline, step_after or step_before. Null inherits the panel.
*/
lineInterpolation?: DashboardtypesLineInterpolationDTO;
/**
* @description The line stroke: solid or dashed. Null inherits the panel.
*/
lineStyle?: DashboardtypesLineStyleDTO;
}
export enum DashboardtypesAxisSideDTO {
left = 'left',
right = 'right',
}
export interface DashboardtypesSecondaryAxisDTO {
/**
* @description Set fields override the panel's chartAppearance for every series on this axis. Bar ignores it.
*/
chartAppearance?: DashboardtypesAxisChartAppearanceDTO;
/**
* @type string
* @description Unique within the panel; thresholds[].axis refers to it.
*/
id: string;
/**
* @type boolean
* @description Whether the axis uses a logarithmic scale.
*/
isLogScale?: boolean;
/**
* @type array,null
* @description Column keys drawn on this axis: the query name for a builder query with one aggregation (A), the query name dotted with the aggregation expression for several (A.p99(duration_nano)), or a formula name (F1). A key may appear on one axis only; a key the query no longer produces is ignored.
*/
series?: string[] | null;
/**
* @description The plot edge the axis is drawn on: left (default) or right.
*/
side?: DashboardtypesAxisSideDTO;
/**
* @type number,null
* @description The highest value the axis always shows; data above it still extends the axis. Null fits the data.
*/
softMax?: number | null;
/**
* @type number,null
* @description The lowest value the axis always shows; data below it still extends the axis. Null fits the data.
*/
softMin?: number | null;
/**
* @type string
* @description The unit id of the axis and of every series on it, such as ms or percent. Values are labelled in it, not converted.
*/
unit?: string;
}
export interface DashboardtypesAxesDTO {
/**
* @type boolean
* @description Whether the Y axis uses a logarithmic scale.
*/
isLogScale?: boolean;
/**
* @type array,null
* @description Further Y axes. Series on none of them use the primary axis. Axes on one side stack outward in array order; only the primary axis draws gridlines.
*/
secondary?: DashboardtypesSecondaryAxisDTO[] | null;
/**
* @description The plot edge the primary Y axis is drawn on: left (default) or right.
*/
side?: DashboardtypesAxisSideDTO;
/**
* @type number,null
* @description The highest value the Y axis always shows; data above it still extends the axis. Null fits the data.
@@ -5522,7 +5587,12 @@ export interface DashboardtypesLegendDTO {
position?: DashboardtypesLegendPositionDTO;
}
export interface DashboardtypesThresholdWithLabelDTO {
export interface DashboardtypesAxisThresholdDTO {
/**
* @type string
* @description Id of the secondary axis the line is drawn on. Empty means the primary axis.
*/
axis?: string;
/**
* @type string
* @description The CSS color of the line, for example #F1575F, which matches the SigNoz red preset; CSS named colors such as red also work.
@@ -5598,9 +5668,9 @@ export interface DashboardtypesAreaChartPanelSpecDTO {
legend?: DashboardtypesLegendDTO;
/**
* @type array,null
* @description Horizontal reference lines drawn at fixed values.
* @description Horizontal reference lines drawn at fixed values, each on the primary axis or a secondary axis it names.
*/
thresholds?: DashboardtypesThresholdWithLabelDTO[] | null;
thresholds?: DashboardtypesAxisThresholdDTO[] | null;
/**
* @description Time range, gap handling and stacking.
*/
@@ -5645,9 +5715,9 @@ export interface DashboardtypesBarChartPanelSpecDTO {
legend?: DashboardtypesLegendDTO;
/**
* @type array,null
* @description Horizontal reference lines drawn at fixed values.
* @description Horizontal reference lines drawn at fixed values, each on the primary axis or a secondary axis it names.
*/
thresholds?: DashboardtypesThresholdWithLabelDTO[] | null;
thresholds?: DashboardtypesAxisThresholdDTO[] | null;
/**
* @description Time range, gap handling and stacking.
*/
@@ -6255,9 +6325,9 @@ export interface DashboardtypesTimeSeriesPanelSpecDTO {
legend?: DashboardtypesLegendDTO;
/**
* @type array,null
* @description Horizontal reference lines drawn at fixed values.
* @description Horizontal reference lines drawn at fixed values, each on the primary axis or a secondary axis it names.
*/
thresholds?: DashboardtypesThresholdWithLabelDTO[] | null;
thresholds?: DashboardtypesAxisThresholdDTO[] | null;
/**
* @description Time range and gap handling.
*/

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,

View File

@@ -1,11 +1,11 @@
import { useState } from 'react';
import type { DashboardtypesThresholdWithLabelDTO } from 'api/generated/services/sigNoz.schemas';
import type { DashboardtypesAxisThresholdDTO } from 'api/generated/services/sigNoz.schemas';
import type { AnyThreshold } from 'pages/DashboardPage/DashboardContainer/Panels/types/sections';
import { render, screen, userEvent, waitFor } from 'tests/test-utils';
import ThresholdsSection from '../ThresholdsSection';
const THRESHOLDS: DashboardtypesThresholdWithLabelDTO[] = [
const THRESHOLDS: DashboardtypesAxisThresholdDTO[] = [
{ value: 80, color: '#F5B225', label: 'High', unit: 'percent' },
];

View File

@@ -28,7 +28,7 @@ import { stepClickTimeRange } from '../../utils/drilldown/chartClickTimeRange';
import { enrichChartClick } from '../../utils/drilldown/enrichChartClick';
import { getBuilderQueries } from '../../utils/getBuilderQueries';
import { getPanelTimeRange } from '../../utils/getPanelTimeRange';
import { sortSeriesByMeanDesc } from '../../utils/sortSeriesByMean';
import { sortSeriesByPlottedHeight } from '../../utils/axes/sortSeriesByPlottedHeight';
import { buildAreaChartConfig } from './utils/buildConfig';
import { ChartClickData } from 'lib/uPlotV2/plugins/TooltipPlugin/types';
@@ -73,13 +73,15 @@ function AreaChartPanelRenderer({
const flatSeries = useMemo(
() =>
sortSeriesByMeanDesc(
sortSeriesByPlottedHeight(
flattenTimeSeries(
getTimeSeriesResults(data.response),
data.legendMap ?? {},
),
builderQueries,
spec.axes,
),
[data.response, data.legendMap],
[data.response, data.legendMap, builderQueries, spec.axes],
);
const config = useMemo(

View File

@@ -5,11 +5,15 @@ import {
type TimeAxisChromeArgs,
} from 'pages/DashboardPage/DashboardContainer/Panels/utils/baseConfigBuilder';
import {
LINE_INTERPOLATION_MAP,
LINE_STYLE_MAP,
} from 'pages/DashboardPage/DashboardContainer/Panels/utils/chartAppearance/enumMaps';
buildSeriesScaleKeys,
resolveAxes,
type ResolvedAxis,
resolveSeriesScaleKey,
} from 'pages/DashboardPage/DashboardContainer/Panels/utils/axes/resolveAxes';
import {
resolveAreaFillMode,
resolveLineInterpolation,
resolveLineStyle,
resolveSpanGaps,
} from 'pages/DashboardPage/DashboardContainer/Panels/utils/chartAppearance/resolvers';
import { resolveSeriesLabelV5 } from 'pages/DashboardPage/DashboardContainer/Panels/utils/resolveSeriesLabel';
@@ -20,11 +24,7 @@ import {
toClickPluginPayload,
} from 'pages/DashboardPage/DashboardContainer/queryV5/uplotData';
import getLabelName from 'lib/getLabelName';
import {
DrawStyle,
LineInterpolation,
LineStyle,
} from 'lib/uPlotV2/config/types';
import { DrawStyle } from 'lib/uPlotV2/config/types';
import { UPlotConfigBuilder } from 'lib/uPlotV2/config/UPlotConfigBuilder';
import type { BuilderQuery } from 'types/api/v5/queryRange';
@@ -57,17 +57,23 @@ export function buildAreaChartConfig({
minTimeScale,
maxTimeScale,
}: BuildAreaChartConfigArgs): UPlotConfigBuilder {
const seriesScaleKeys = buildSeriesScaleKeys(spec.axes);
const scaleKeyOfSeries = series.map((s) =>
resolveSeriesScaleKey(s, builderQueries, seriesScaleKeys),
);
const axes = resolveAxes({
axes: spec.axes,
unit: spec.formatting?.unit,
thresholds: spec.thresholds,
usedScaleKeys: new Set(scaleKeyOfSeries),
});
const builder = buildBaseConfig({
panelId,
isTimeAxis: true,
isDarkMode,
timezone,
panelMode,
isLogScale: spec.axes?.isLogScale,
softMin: spec.axes?.softMin ?? undefined,
softMax: spec.axes?.softMax ?? undefined,
formatting: spec.formatting,
thresholds: spec.thresholds,
axes,
stepIntervals,
clickPayload: toClickPluginPayload(series),
minTimeScale,
@@ -79,6 +85,8 @@ export function buildAreaChartConfig({
addSeries({
builder,
spec,
axes,
scaleKeyOfSeries,
builderQueries,
series,
stepIntervals,
@@ -91,6 +99,9 @@ export function buildAreaChartConfig({
interface AddSeriesArgs {
builder: UPlotConfigBuilder;
spec: DashboardtypesAreaChartPanelSpecDTO;
axes: ResolvedAxis[];
/** Each entry's scale key, aligned with `series`. */
scaleKeyOfSeries: string[];
builderQueries: BuilderQuery[];
series: PanelSeries[];
/** Per-query step intervals (seconds); floor for a numeric spanGaps threshold. */
@@ -105,12 +116,17 @@ interface AddSeriesArgs {
function addSeries({
builder,
spec,
axes,
scaleKeyOfSeries,
builderQueries,
series,
stepIntervals,
isDarkMode,
}: AddSeriesArgs): void {
const chartAppearance = spec.chartAppearance;
const appearanceByScale = new Map(
axes.map((axis) => [axis.scaleKey, axis.appearance]),
);
// `customColors` is nullable on the spec; coerce so `addSeries` always gets
// a defined record (it dereferences keys without a guard).
const colorMapping = spec.legend?.customColors ?? {};
@@ -125,31 +141,31 @@ function addSeries({
? Math.max(minStep, resolvedSpanGaps)
: resolvedSpanGaps;
const lineStyle = chartAppearance?.lineStyle
? LINE_STYLE_MAP[chartAppearance.lineStyle]
: LineStyle.Solid;
const lineInterpolation = chartAppearance?.lineInterpolation
? LINE_INTERPOLATION_MAP[chartAppearance.lineInterpolation]
: LineInterpolation.Spline;
const fillMode = resolveAreaFillMode(chartAppearance?.fillMode);
// Null and undefined both mean "kind default", which the chart layer resolves.
const fillOpacity = chartAppearance?.fillOpacity ?? undefined;
series.forEach((s) => {
series.forEach((s, index) => {
const hasSingleValidPoint = hasSingleVisiblePoint(s.values);
const baseLabel = getLabelName(s.labels, s.queryName, s.legend);
const label = resolveSeriesLabelV5(s, builderQueries, baseLabel);
const scaleKey = scaleKeyOfSeries[index];
const axisAppearance = appearanceByScale.get(scaleKey);
builder.addSeries({
scaleKey: 'y',
scaleKey,
// A single visible point can't be drawn as a line — degrade to points
// so the user still sees the datum (matches V1 behavior).
drawStyle: hasSingleValidPoint ? DrawStyle.Points : DrawStyle.Line,
label,
colorMapping,
spanGaps,
lineStyle,
lineInterpolation,
lineStyle: resolveLineStyle(
axisAppearance?.lineStyle ?? chartAppearance?.lineStyle,
),
lineInterpolation: resolveLineInterpolation(
axisAppearance?.lineInterpolation ?? chartAppearance?.lineInterpolation,
),
showPoints: chartAppearance?.showPoints || hasSingleValidPoint,
pointSize: DEFAULT_POINT_SIZE,
fillMode,

View File

@@ -28,7 +28,7 @@ import { stepClickTimeRange } from '../../utils/drilldown/chartClickTimeRange';
import { enrichChartClick } from '../../utils/drilldown/enrichChartClick';
import { getBuilderQueries } from '../../utils/getBuilderQueries';
import { getPanelTimeRange } from '../../utils/getPanelTimeRange';
import { sortSeriesByMeanDesc } from '../../utils/sortSeriesByMean';
import { sortSeriesByPlottedHeight } from '../../utils/axes/sortSeriesByPlottedHeight';
import { buildBarChartConfig } from './utils/buildConfig';
import { ChartClickData } from 'lib/uPlotV2/plugins/TooltipPlugin/types';
@@ -72,13 +72,15 @@ function BarPanelRenderer({
const flatSeries = useMemo(
() =>
sortSeriesByMeanDesc(
sortSeriesByPlottedHeight(
flattenTimeSeries(
getTimeSeriesResults(data.response),
data.legendMap ?? {},
),
builderQueries,
spec.axes,
),
[data.response, data.legendMap],
[data.response, data.legendMap, builderQueries, spec.axes],
);
const config = useMemo(

View File

@@ -1,4 +1,9 @@
import type { DashboardtypesBarChartPanelSpecDTO } from 'api/generated/services/sigNoz.schemas';
import {
buildSeriesScaleKeys,
resolveAxes,
resolveSeriesScaleKey,
} from 'pages/DashboardPage/DashboardContainer/Panels/utils/axes/resolveAxes';
import {
buildBaseConfig,
type TimeAxisChromeArgs,
@@ -37,17 +42,22 @@ export function buildBarChartConfig({
minTimeScale,
maxTimeScale,
}: BuildBarChartConfigArgs): UPlotConfigBuilder {
const seriesScaleKeys = buildSeriesScaleKeys(spec.axes);
const scaleKeyOfSeries = series.map((s) =>
resolveSeriesScaleKey(s, builderQueries, seriesScaleKeys),
);
const builder = buildBaseConfig({
panelId,
isTimeAxis: true,
isDarkMode,
timezone,
panelMode,
isLogScale: spec.axes?.isLogScale,
softMin: spec.axes?.softMin ?? undefined,
softMax: spec.axes?.softMax ?? undefined,
formatting: spec.formatting,
thresholds: spec.thresholds,
axes: resolveAxes({
axes: spec.axes,
unit: spec.formatting?.unit,
thresholds: spec.thresholds,
usedScaleKeys: new Set(scaleKeyOfSeries),
}),
stepIntervals,
clickPayload: toClickPluginPayload(series),
minTimeScale,
@@ -59,6 +69,7 @@ export function buildBarChartConfig({
addSeries({
builder,
spec,
scaleKeyOfSeries,
builderQueries,
series,
stepIntervals,
@@ -71,6 +82,8 @@ export function buildBarChartConfig({
interface AddSeriesArgs {
builder: UPlotConfigBuilder;
spec: DashboardtypesBarChartPanelSpecDTO;
/** Each entry's scale key, aligned with `series`. */
scaleKeyOfSeries: string[];
builderQueries: BuilderQuery[];
series: PanelSeries[];
stepIntervals?: Record<string, number>;
@@ -85,6 +98,7 @@ interface AddSeriesArgs {
function addSeries({
builder,
spec,
scaleKeyOfSeries,
builderQueries,
series,
stepIntervals,
@@ -92,13 +106,13 @@ function addSeries({
}: AddSeriesArgs): void {
const colorMapping = spec.legend?.customColors ?? {};
series.forEach((s) => {
series.forEach((s, index) => {
const baseLabel = getLabelName(s.labels, s.queryName, s.legend);
const label = resolveSeriesLabelV5(s, builderQueries, baseLabel);
const stepInterval = s.queryName ? stepIntervals?.[s.queryName] : undefined;
builder.addSeries({
scaleKey: 'y',
scaleKey: scaleKeyOfSeries[index],
drawStyle: DrawStyle.Bar,
label,
colorMapping,

View File

@@ -1,4 +1,5 @@
import type { DashboardtypesHistogramPanelSpecDTO } from 'api/generated/services/sigNoz.schemas';
import { resolveAxes } from 'pages/DashboardPage/DashboardContainer/Panels/utils/axes/resolveAxes';
import {
buildBaseConfig,
type PanelChromeArgs,
@@ -44,6 +45,7 @@ export function buildHistogramConfig({
isDarkMode,
timezone,
panelMode,
axes: resolveAxes({}),
});
builder.setCursor({

View File

@@ -9,7 +9,7 @@ import {
ScatterAxisScale,
} from 'lib/visualization/charts/Scatter/types';
import { mapThresholds } from '../../../utils/baseConfigBuilder';
import { mapThresholds } from '../../../utils/axes/resolveAxes';
const CHART_SCALE: Record<DashboardtypesAxisScaleDTO, ScatterAxisScale> = {
[DashboardtypesAxisScaleDTO.auto]: ScatterAxisScale.Auto,

View File

@@ -27,7 +27,7 @@ import { stepClickTimeRange } from '../../utils/drilldown/chartClickTimeRange';
import { enrichChartClick } from '../../utils/drilldown/enrichChartClick';
import { getBuilderQueries } from '../../utils/getBuilderQueries';
import { getPanelTimeRange } from '../../utils/getPanelTimeRange';
import { sortSeriesByMeanDesc } from '../../utils/sortSeriesByMean';
import { sortSeriesByPlottedHeight } from '../../utils/axes/sortSeriesByPlottedHeight';
import { buildTimeSeriesConfig } from './utils/buildConfig';
import { ChartClickData } from 'lib/uPlotV2/plugins/TooltipPlugin/types';
@@ -72,13 +72,15 @@ function TimeSeriesPanelRenderer({
const flatSeries = useMemo(
() =>
sortSeriesByMeanDesc(
sortSeriesByPlottedHeight(
flattenTimeSeries(
getTimeSeriesResults(data.response),
data.legendMap ?? {},
),
builderQueries,
spec.axes,
),
[data.response, data.legendMap],
[data.response, data.legendMap, builderQueries, spec.axes],
);
const config = useMemo(

View File

@@ -1,7 +1,11 @@
import type { DashboardtypesTimeSeriesPanelSpecDTO } from 'api/generated/services/sigNoz.schemas';
import {
DashboardtypesLineStyleDTO,
type DashboardtypesTimeSeriesPanelSpecDTO,
} from 'api/generated/services/sigNoz.schemas';
import { UTC_TIMEZONE } from 'components/CustomTimePicker/timezoneUtils';
import type { ExtendedSeries } from 'lib/uPlotV2/config/types';
import { type ExtendedSeries, LineStyle } from 'lib/uPlotV2/config/types';
import { PanelMode } from 'lib/visualization/panels/types';
import type uPlot from 'uplot';
import type { PanelSeries } from 'pages/DashboardPage/DashboardContainer/queryV5/types';
import { buildTimeSeriesConfig } from '../buildConfig';
@@ -99,3 +103,111 @@ describe('buildTimeSeriesConfig partial buckets', () => {
expect(config.partialTimestamps).toStrictEqual(new Set([61]));
});
});
describe('buildTimeSeriesConfig secondary axes', () => {
it('draws a series named by a secondary axis on that scale with the axis appearance', () => {
const spec = {
formatting: { unit: 'reqps' },
axes: {
secondary: [
{
id: 'lat',
unit: 'ms',
series: ['B'],
chartAppearance: { lineStyle: DashboardtypesLineStyleDTO.dashed },
},
],
},
thresholds: [{ value: 500, color: '#f00', axis: 'lat' }],
} as DashboardtypesTimeSeriesPanelSpecDTO;
const config = buildTimeSeriesConfig({
panelId: 'p1',
spec,
builderQueries: [],
series: [series[0], { ...series[0], queryName: 'B', legend: 'B' }],
isDarkMode: false,
timezone: UTC_TIMEZONE,
panelMode: PanelMode.DASHBOARD_VIEW,
});
const plot = config.getConfig();
expect(plot.series?.map((s) => s.scale)).toStrictEqual([
undefined,
'y',
'y:lat',
]);
expect(plot.axes?.map((axis) => [axis.scale, axis.side])).toStrictEqual([
['x', 2],
['y', 3],
['y:lat', 3],
]);
expect(plot.axes?.[2].grid?.show).toBe(false);
expect(Object.keys(plot.scales ?? {})).toStrictEqual(['x', 'y', 'y:lat']);
expect(config.getScaleUnits()).toStrictEqual({ y: 'reqps', 'y:lat': 'ms' });
expect(config.series[1].props.lineStyle).toBe(LineStyle.Dashed);
expect(config.series[0].props.lineStyle).toBe(LineStyle.Solid);
});
it('hands the gridlines to the secondary axis when every series sits on it', () => {
const spec = {
axes: { secondary: [{ id: 'lat', unit: 'ms', series: ['A'] }] },
} as DashboardtypesTimeSeriesPanelSpecDTO;
const plot = buildTimeSeriesConfig({
panelId: 'p1',
spec,
builderQueries: [],
series,
isDarkMode: false,
timezone: UTC_TIMEZONE,
panelMode: PanelMode.DASHBOARD_VIEW,
}).getConfig();
expect(plot.axes?.map((axis) => [axis.scale, axis.show])).toStrictEqual([
['x', true],
['y', false],
['y:lat', true],
]);
expect(plot.axes?.[1].grid?.show).toBe(false);
expect(plot.axes?.[2].grid?.show).toBe(true);
});
it('reserves a margin on every same-side axis that has another outside it', () => {
const spec = {
axes: {
secondary: [
{ id: 'lat', series: ['B'] },
{ id: 'pct', series: ['C'] },
],
},
} as DashboardtypesTimeSeriesPanelSpecDTO;
const config = buildTimeSeriesConfig({
panelId: 'p1',
spec,
builderQueries: [],
series: ['A', 'B', 'C'].map((queryName) => ({
...series[0],
queryName,
legend: queryName,
})),
isDarkMode: false,
timezone: UTC_TIMEZONE,
panelMode: PanelMode.DASHBOARD_VIEW,
});
// Every axis sits on the left: the primary and the first secondary have one outside them.
const plot = config.getConfig();
const fakeInstance = {
axes: plot.axes,
ctx: { font: '', measureText: (): { width: number } => ({ width: 0 }) },
} as unknown as uPlot;
const widths = (plot.axes ?? [])
.slice(1)
.map((axis, index) =>
typeof axis.size === 'function'
? axis.size(fakeInstance, ['1'], index + 1, 0)
: axis.size,
);
expect(widths[0]).toBe((widths[2] ?? 0) + 12);
expect(widths[1]).toBe((widths[2] ?? 0) + 12);
});
});

View File

@@ -5,11 +5,17 @@ import {
type TimeAxisChromeArgs,
} from 'pages/DashboardPage/DashboardContainer/Panels/utils/baseConfigBuilder';
import {
FILL_MODE_MAP,
LINE_INTERPOLATION_MAP,
LINE_STYLE_MAP,
} from 'pages/DashboardPage/DashboardContainer/Panels/utils/chartAppearance/enumMaps';
import { resolveSpanGaps } from 'pages/DashboardPage/DashboardContainer/Panels/utils/chartAppearance/resolvers';
buildSeriesScaleKeys,
resolveAxes,
type ResolvedAxis,
resolveSeriesScaleKey,
} from 'pages/DashboardPage/DashboardContainer/Panels/utils/axes/resolveAxes';
import { FILL_MODE_MAP } from 'pages/DashboardPage/DashboardContainer/Panels/utils/chartAppearance/enumMaps';
import {
resolveLineInterpolation,
resolveLineStyle,
resolveSpanGaps,
} from 'pages/DashboardPage/DashboardContainer/Panels/utils/chartAppearance/resolvers';
import { resolveSeriesLabelV5 } from 'pages/DashboardPage/DashboardContainer/Panels/utils/resolveSeriesLabel';
import type { PanelSeries } from 'pages/DashboardPage/DashboardContainer/queryV5/types';
import {
@@ -18,12 +24,7 @@ import {
toClickPluginPayload,
} from 'pages/DashboardPage/DashboardContainer/queryV5/uplotData';
import getLabelName from 'lib/getLabelName';
import {
DrawStyle,
FillMode,
LineInterpolation,
LineStyle,
} from 'lib/uPlotV2/config/types';
import { DrawStyle, FillMode } from 'lib/uPlotV2/config/types';
import { UPlotConfigBuilder } from 'lib/uPlotV2/config/UPlotConfigBuilder';
import type { BuilderQuery } from 'types/api/v5/queryRange';
@@ -52,17 +53,23 @@ export function buildTimeSeriesConfig({
minTimeScale,
maxTimeScale,
}: BuildTimeSeriesConfigArgs): UPlotConfigBuilder {
const seriesScaleKeys = buildSeriesScaleKeys(spec.axes);
const scaleKeyOfSeries = series.map((s) =>
resolveSeriesScaleKey(s, builderQueries, seriesScaleKeys),
);
const axes = resolveAxes({
axes: spec.axes,
unit: spec.formatting?.unit,
thresholds: spec.thresholds,
usedScaleKeys: new Set(scaleKeyOfSeries),
});
const builder = buildBaseConfig({
panelId,
isTimeAxis: true,
isDarkMode,
timezone,
panelMode,
isLogScale: spec.axes?.isLogScale,
softMin: spec.axes?.softMin ?? undefined,
softMax: spec.axes?.softMax ?? undefined,
formatting: spec.formatting,
thresholds: spec.thresholds,
axes,
stepIntervals,
clickPayload: toClickPluginPayload(series),
minTimeScale,
@@ -74,6 +81,8 @@ export function buildTimeSeriesConfig({
addSeries({
builder,
spec,
axes,
scaleKeyOfSeries,
builderQueries,
series,
stepIntervals,
@@ -86,6 +95,9 @@ export function buildTimeSeriesConfig({
interface AddSeriesArgs {
builder: UPlotConfigBuilder;
spec: DashboardtypesTimeSeriesPanelSpecDTO;
axes: ResolvedAxis[];
/** Each entry's scale key, aligned with `series`. */
scaleKeyOfSeries: string[];
builderQueries: BuilderQuery[];
series: PanelSeries[];
/** Per-query step intervals (seconds); floor for a numeric spanGaps threshold. */
@@ -100,12 +112,17 @@ interface AddSeriesArgs {
function addSeries({
builder,
spec,
axes,
scaleKeyOfSeries,
builderQueries,
series,
stepIntervals,
isDarkMode,
}: AddSeriesArgs): void {
const chartAppearance = spec.chartAppearance;
const appearanceByScale = new Map(
axes.map((axis) => [axis.scaleKey, axis.appearance]),
);
// `customColors` is nullable on the spec; coerce so `addSeries` always gets
// a defined record (it dereferences keys without a guard).
const colorMapping = spec.legend?.customColors ?? {};
@@ -120,31 +137,31 @@ function addSeries({
? Math.max(minStep, resolvedSpanGaps)
: resolvedSpanGaps;
const lineStyle = chartAppearance?.lineStyle
? LINE_STYLE_MAP[chartAppearance.lineStyle]
: LineStyle.Solid;
const lineInterpolation = chartAppearance?.lineInterpolation
? LINE_INTERPOLATION_MAP[chartAppearance.lineInterpolation]
: LineInterpolation.Spline;
const fillMode = chartAppearance?.fillMode
? FILL_MODE_MAP[chartAppearance.fillMode]
: FillMode.None;
series.forEach((s) => {
series.forEach((s, index) => {
const hasSingleValidPoint = hasSingleVisiblePoint(s.values);
const baseLabel = getLabelName(s.labels, s.queryName, s.legend);
const label = resolveSeriesLabelV5(s, builderQueries, baseLabel);
const scaleKey = scaleKeyOfSeries[index];
const axisAppearance = appearanceByScale.get(scaleKey);
builder.addSeries({
scaleKey: 'y',
scaleKey,
// A single visible point can't be drawn as a line — degrade to points
// so the user still sees the datum (matches V1 behavior).
drawStyle: hasSingleValidPoint ? DrawStyle.Points : DrawStyle.Line,
label,
colorMapping,
spanGaps,
lineStyle,
lineInterpolation,
lineStyle: resolveLineStyle(
axisAppearance?.lineStyle ?? chartAppearance?.lineStyle,
),
lineInterpolation: resolveLineInterpolation(
axisAppearance?.lineInterpolation ?? chartAppearance?.lineInterpolation,
),
showPoints: chartAppearance?.showPoints || hasSingleValidPoint,
pointSize: DEFAULT_POINT_SIZE,
fillMode,

View File

@@ -26,7 +26,7 @@ import type {
DashboardtypesTableFormattingDTO,
DashboardtypesTableThresholdDTO,
DashboardtypesTextPresentationDTO,
DashboardtypesThresholdWithLabelDTO,
DashboardtypesAxisThresholdDTO,
DashboardtypesTimePreferenceDTO,
DashboardtypesTopListAppearanceDTO,
TelemetrytypesTelemetryFieldKeyDTO,
@@ -101,7 +101,7 @@ export enum ThresholdVariant {
/** Union of every threshold element shape stored under `plugin.spec.thresholds`. */
export type AnyThreshold =
| DashboardtypesThresholdWithLabelDTO
| DashboardtypesAxisThresholdDTO
| DashboardtypesScatterPlotThresholdDTO
| DashboardtypesComparisonThresholdDTO
| DashboardtypesTableThresholdDTO

View File

@@ -0,0 +1,174 @@
import {
DashboardtypesAxisSideDTO,
DashboardtypesLineStyleDTO,
} from 'api/generated/services/sigNoz.schemas';
import type { PanelSeries } from 'pages/DashboardPage/DashboardContainer/queryV5/types';
import type { BuilderQuery } from 'types/api/v5/queryRange';
import {
buildSeriesScaleKeys,
resolveAxes,
resolveSeriesScaleKey,
} from '../resolveAxes';
const secondary = [
{
id: 'lat',
unit: 'ms',
side: DashboardtypesAxisSideDTO.right,
softMax: 1000,
series: ['B', 'C.p99(duration_ms)'],
chartAppearance: { lineStyle: DashboardtypesLineStyleDTO.dashed },
},
{ id: 'pct', unit: 'percent', isLogScale: true, series: ['F1'] },
];
describe('resolveAxes', () => {
it('reads the primary axis from the panel fields, on the left by default', () => {
const [primary] = resolveAxes({
axes: { softMin: 0, isLogScale: true },
unit: 'reqps',
});
expect(primary).toStrictEqual({
scaleKey: 'y',
unit: 'reqps',
side: 3,
softMin: 0,
softMax: undefined,
isLogScale: true,
thresholds: [],
show: true,
});
});
it('draws a secondary axis only when it carries series or a threshold', () => {
const [, bare, withThreshold, withSeries] = resolveAxes({
axes: {
secondary: [
{ id: 'bare', series: [] },
{ id: 'marked' },
{ id: 'bound', series: ['B'] },
],
},
thresholds: [{ value: 1, color: 'red', axis: 'marked' }],
});
expect(bare.show).toBe(false);
expect(withThreshold.show).toBe(true);
expect(withSeries.show).toBe(true);
});
it('hides the primary axis too once every series resolved elsewhere', () => {
const [primary, lat] = resolveAxes({
axes: { secondary: [{ id: 'lat', series: ['A'] }] },
usedScaleKeys: new Set(['y:lat']),
});
expect(primary.show).toBe(false);
expect(lat.show).toBe(true);
});
it('derives one axis per secondary entry, keyed by id, with its own side, scale and appearance', () => {
const [, lat, pct] = resolveAxes({
axes: { side: DashboardtypesAxisSideDTO.right, secondary },
});
expect(lat).toMatchObject({
scaleKey: 'y:lat',
unit: 'ms',
side: 1,
softMax: 1000,
isLogScale: false,
appearance: { lineStyle: DashboardtypesLineStyleDTO.dashed },
});
expect(pct).toMatchObject({
scaleKey: 'y:pct',
unit: 'percent',
side: 3,
isLogScale: true,
});
expect(pct).not.toHaveProperty('appearance');
});
it('places each threshold on the axis it names and drops one naming no axis', () => {
const axes = resolveAxes({
axes: { secondary },
unit: 'reqps',
thresholds: [
{ value: 1000, color: '#0f0', label: 'Capacity' },
{ value: 500, color: '#f00', label: 'SLO', axis: 'lat' },
{ value: 1, color: '#00f', axis: 'gone' },
],
});
expect(axes.map((axis) => axis.thresholds)).toStrictEqual([
[
{
thresholdValue: 1000,
thresholdColor: '#0f0',
thresholdUnit: undefined,
thresholdLabel: 'Capacity',
},
],
[
{
thresholdValue: 500,
thresholdColor: '#f00',
thresholdUnit: undefined,
thresholdLabel: 'SLO',
},
],
[],
]);
});
});
describe('resolveSeriesScaleKey', () => {
const builderQueries = [
{ name: 'A', aggregations: [{ expression: 'count()' }] },
{
name: 'C',
aggregations: [
{ expression: 'count()' },
{ expression: 'p99(duration_ms)' },
],
},
] as unknown as BuilderQuery[];
const seriesScaleKeys = buildSeriesScaleKeys({ secondary });
const seriesOf = (queryName: string, aggregationIndex = 0): PanelSeries => ({
queryName,
legend: queryName,
labels: {},
values: [],
kind: 'series',
aggregation: { index: aggregationIndex, alias: '' },
});
it('keys a series the way Table column units do', () => {
expect(
resolveSeriesScaleKey(seriesOf('A'), builderQueries, seriesScaleKeys),
).toBe('y');
expect(
resolveSeriesScaleKey(seriesOf('B'), builderQueries, seriesScaleKeys),
).toBe('y:lat');
expect(
resolveSeriesScaleKey(seriesOf('C', 0), builderQueries, seriesScaleKeys),
).toBe('y');
expect(
resolveSeriesScaleKey(seriesOf('C', 1), builderQueries, seriesScaleKeys),
).toBe('y:lat');
expect(
resolveSeriesScaleKey(seriesOf('F1'), builderQueries, seriesScaleKeys),
).toBe('y:pct');
});
it('falls back to the primary axis when no secondary axis names the series', () => {
expect(
resolveSeriesScaleKey(seriesOf('Z'), builderQueries, seriesScaleKeys),
).toBe('y');
expect(resolveSeriesScaleKey(seriesOf('B'), builderQueries, new Map())).toBe(
'y',
);
});
});

View File

@@ -0,0 +1,67 @@
import type { PanelSeries } from 'pages/DashboardPage/DashboardContainer/queryV5/types';
import { sortSeriesByPlottedHeight } from '../sortSeriesByPlottedHeight';
const seriesOf = (queryName: string, values: number[]): PanelSeries => ({
queryName,
legend: queryName,
labels: {},
values: values.map((value, index) => ({ timestamp: index, value })),
kind: 'series',
aggregation: { index: 0, alias: '' },
});
describe('sortSeriesByPlottedHeight', () => {
it('orders by each mean as a share of its own axis range, tallest first', () => {
// Counts reach 5000 on the primary axis; p99 fills its own axis; B is a short bar.
const series = [
seriesOf('B', [900, 900]),
seriesOf('A', [5000, 5000]),
seriesOf('P', [4e9, 4e9]),
];
const sorted = sortSeriesByPlottedHeight(series, [], {
secondary: [
{ id: 'lat', series: ['P'] },
{ id: 'cnt', series: ['B'] },
],
});
// A and P each fill their axis (share 1); B shares an axis with nothing taller,
// so it fills its own too. Ties fall back to the key, so the order is stable.
expect(sorted.map((entry) => entry.queryName)).toStrictEqual(['A', 'B', 'P']);
});
it('interleaves axes by share of their own range, ties broken by key', () => {
const series = [
seriesOf('short', [1, 1]),
seriesOf('tall', [80, 80]),
seriesOf('other', [10, 10]),
seriesOf('full', [100, 100]),
seriesOf('cap', [20, 20]),
];
const sorted = sortSeriesByPlottedHeight(series, [], {
secondary: [{ id: 'x', series: ['cap', 'other', 'short'] }],
});
// Primary range 100: full 1, tall 0.8. Secondary range 20: cap 1, other 0.5, short 0.05.
expect(sorted.map((entry) => entry.queryName)).toStrictEqual([
'cap',
'full',
'tall',
'other',
'short',
]);
});
it('is the plain mean sort without secondary axes', () => {
const series = [seriesOf('low', [1]), seriesOf('high', [9])];
expect(
sortSeriesByPlottedHeight(series, [], undefined).map(
(entry) => entry.queryName,
),
).toStrictEqual(['high', 'low']);
});
});

View File

@@ -0,0 +1,181 @@
import {
type DashboardtypesAxesDTO,
type DashboardtypesAxisChartAppearanceDTO,
DashboardtypesAxisSideDTO,
type DashboardtypesAxisThresholdDTO,
} from 'api/generated/services/sigNoz.schemas';
import type { Threshold } from 'lib/uPlotV2/hooks/types';
import type { BuilderQuery } from 'types/api/v5/queryRange';
import { getAggregationColumnKey } from '../../../queryV5/prepareScalarTables';
import type { PanelSeries } from '../../../queryV5/types';
/** The primary axis keeps uPlot's conventional key; secondary axes derive theirs from their id. */
export const PRIMARY_SCALE_KEY = 'y';
export function secondaryScaleKey(id: string): string {
return `y:${id}`;
}
/** uPlot axis sides: 1 is right, 3 is left. */
const AXIS_SIDE: Record<DashboardtypesAxisSideDTO, 1 | 3> = {
[DashboardtypesAxisSideDTO.left]: 3,
[DashboardtypesAxisSideDTO.right]: 1,
};
/**
* One Y axis in the shape the chart scaffolding consumes, whether it came from
* the spec's primary fields (`formatting.unit`, `axes`, unassigned `thresholds`)
* or from an `axes.secondary[]` entry.
*/
export interface ResolvedAxis {
scaleKey: string;
unit?: string;
side: 1 | 3;
softMin?: number;
softMax?: number;
isLogScale: boolean;
thresholds: Threshold[];
/**
* Whether the axis is drawn. The scale always exists, so a threshold can still land
* on it; an axis with neither series nor thresholds has nothing to show.
*/
show: boolean;
/** Secondary axes only: set fields override the panel's chart appearance. */
appearance?: DashboardtypesAxisChartAppearanceDTO;
}
export interface ResolveAxesArgs {
axes?: DashboardtypesAxesDTO;
/** `formatting.unit`: the primary axis unit. */
unit?: string;
thresholds?: DashboardtypesAxisThresholdDTO[] | null;
/**
* Scale keys the panel's series resolved to (`resolveSeriesScaleKey`). Decides which
* axes are drawn; left out, every axis with a series key or a threshold is.
*/
usedScaleKeys?: Set<string>;
}
type LabelThresholdFields = Pick<
DashboardtypesAxisThresholdDTO,
'value' | 'unit' | 'color' | 'label'
>;
/** Perses-shape thresholds → the draw-hook shape uPlotV2 consumes. */
export function mapThresholds(
thresholds: LabelThresholdFields[] | null | undefined,
): Threshold[] {
if (!thresholds || thresholds.length === 0) {
return [];
}
return thresholds.map((t) => ({
thresholdValue: t.value,
thresholdColor: t.color,
thresholdUnit: t.unit,
thresholdLabel: t.label,
}));
}
/** Thresholds by the axis id they name (`''` is the primary); one naming no axis is dropped. */
function groupThresholdsByAxis(
thresholds: DashboardtypesAxisThresholdDTO[] | null | undefined,
secondaryIds: Set<string>,
): Map<string, DashboardtypesAxisThresholdDTO[]> {
const byAxis = new Map<string, DashboardtypesAxisThresholdDTO[]>();
(thresholds ?? []).forEach((threshold) => {
const axisId = threshold.axis ?? '';
if (axisId !== '' && !secondaryIds.has(axisId)) {
return;
}
byAxis.set(axisId, [...(byAxis.get(axisId) ?? []), threshold]);
});
return byAxis;
}
/** Primary axis first, then the secondary axes in spec order. */
export function resolveAxes({
axes,
unit,
thresholds,
usedScaleKeys,
}: ResolveAxesArgs): ResolvedAxis[] {
const secondary = axes?.secondary ?? [];
const thresholdsByAxis = groupThresholdsByAxis(
thresholds,
new Set(secondary.map((axis) => axis.id)),
);
const isUsed = (scaleKey: string, seriesKeys: number): boolean =>
usedScaleKeys ? usedScaleKeys.has(scaleKey) : seriesKeys > 0;
const primaryThresholds = mapThresholds(thresholdsByAxis.get(''));
const primary: ResolvedAxis = {
scaleKey: PRIMARY_SCALE_KEY,
unit,
side: AXIS_SIDE[axes?.side ?? DashboardtypesAxisSideDTO.left],
softMin: axes?.softMin ?? undefined,
softMax: axes?.softMax ?? undefined,
isLogScale: axes?.isLogScale ?? false,
thresholds: primaryThresholds,
// Without the resolved series the primary axis is assumed to carry some.
show: usedScaleKeys
? usedScaleKeys.has(PRIMARY_SCALE_KEY) || primaryThresholds.length > 0
: true,
};
return [
primary,
...secondary.map((axis): ResolvedAxis => {
const thresholds = mapThresholds(thresholdsByAxis.get(axis.id));
return {
scaleKey: secondaryScaleKey(axis.id),
unit: axis.unit || undefined,
side: AXIS_SIDE[axis.side ?? DashboardtypesAxisSideDTO.left],
softMin: axis.softMin ?? undefined,
softMax: axis.softMax ?? undefined,
isLogScale: axis.isLogScale ?? false,
thresholds,
show:
isUsed(secondaryScaleKey(axis.id), axis.series?.length ?? 0) ||
thresholds.length > 0,
...(axis.chartAppearance && { appearance: axis.chartAppearance }),
};
}),
];
}
/** Column key → scale key for every series a secondary axis names. */
export function buildSeriesScaleKeys(
axes: DashboardtypesAxesDTO | undefined,
): Map<string, string> {
const scaleKeys = new Map<string, string>();
(axes?.secondary ?? []).forEach((axis) => {
(axis.series ?? []).forEach((key) => {
scaleKeys.set(key, secondaryScaleKey(axis.id));
});
});
return scaleKeys;
}
/**
* The scale a flattened series is drawn on. Its column key is the one Table's
* `columnUnits` uses (`A`, `A.p99(duration_nano)`, `F1`); a key no secondary
* axis names, or that the queries no longer produce, lands on the primary axis.
*/
export function resolveSeriesScaleKey(
series: PanelSeries,
builderQueries: BuilderQuery[],
seriesScaleKeys: Map<string, string>,
): string {
if (seriesScaleKeys.size === 0) {
return PRIMARY_SCALE_KEY;
}
const query = builderQueries.find((q) => q.name === series.queryName);
const aggregations = query?.aggregations?.map((aggregation) => ({
expression: 'expression' in aggregation ? (aggregation.expression ?? '') : '',
}));
const columnKey = getAggregationColumnKey(
series.queryName,
aggregations,
series.aggregation.index,
);
return seriesScaleKeys.get(columnKey) ?? PRIMARY_SCALE_KEY;
}

View File

@@ -0,0 +1,49 @@
import type { DashboardtypesAxesDTO } from 'api/generated/services/sigNoz.schemas';
import { sortByMeanDesc } from 'lib/visualization/charts/utils/sortByMeanDesc';
import type { BuilderQuery } from 'types/api/v5/queryRange';
import type { PanelSeries } from '../../../queryV5/types';
import { seriesKey, sortSeriesByMeanDesc } from '../sortSeriesByMean';
import { buildSeriesScaleKeys, resolveSeriesScaleKey } from './resolveAxes';
const seriesMax = (series: PanelSeries): number =>
series.values.reduce(
(max, point) =>
Number.isFinite(point.value) ? Math.max(max, point.value) : max,
0,
);
/**
* `sortSeriesByMeanDesc` for a panel with secondary axes: each mean is taken as a
* share of its axis's data range, so uPlot paints the series that reaches highest on
* its own axis first and the shorter ones over it, whichever axis they are on.
*/
export function sortSeriesByPlottedHeight(
series: PanelSeries[],
builderQueries: BuilderQuery[],
axes: DashboardtypesAxesDTO | undefined,
): PanelSeries[] {
const seriesScaleKeys = buildSeriesScaleKeys(axes);
if (seriesScaleKeys.size === 0) {
return sortSeriesByMeanDesc(series);
}
const scaleKeyOf = new Map(
series.map((entry) => [
entry,
resolveSeriesScaleKey(entry, builderQueries, seriesScaleKeys),
]),
);
const rangeByScale = new Map<string, number>();
series.forEach((entry) => {
const scaleKey = scaleKeyOf.get(entry) ?? '';
rangeByScale.set(
scaleKey,
Math.max(rangeByScale.get(scaleKey) ?? 0, seriesMax(entry)),
);
});
return sortByMeanDesc(series, {
getValues: (entry) => entry.values.map((point) => point.value),
getKey: seriesKey,
getAxisRange: (entry) => rangeByScale.get(scaleKeyOf.get(entry) ?? '') ?? 0,
});
}

View File

@@ -1,7 +1,3 @@
import type {
DashboardtypesPanelFormattingDTO,
DashboardtypesThresholdWithLabelDTO,
} from 'api/generated/services/sigNoz.schemas';
import { Timezone } from 'components/CustomTimePicker/timezoneUtils';
import { PanelMode } from 'lib/visualization/panels/types';
import onClickPlugin, {
@@ -9,10 +5,12 @@ import onClickPlugin, {
} from 'lib/uPlotLib/plugins/onClickPlugin';
import { DistributionType } from 'lib/uPlotV2/config/types';
import { UPlotConfigBuilder } from 'lib/uPlotV2/config/UPlotConfigBuilder';
import { axisBaselineDrawHook } from 'lib/uPlotV2/hooks/axisBaselineDrawHook';
import { ThresholdsDrawHookOptions } from 'lib/uPlotV2/hooks/types';
import { MetricRangePayloadProps } from 'types/api/metrics/getQueryRange';
import uPlot from 'uplot';
import type { ResolvedAxis } from './axes/resolveAxes';
import {
resolveSelectionPreferencesSource,
shouldSaveSelectionPreference,
@@ -34,16 +32,11 @@ export interface BuildBaseConfigArgs {
timezone: Timezone;
panelMode: PanelMode;
/** From `spec.axes` — drives the Y scale and (when log) both scales' base. */
isLogScale?: boolean;
softMin?: number;
softMax?: number;
/** From `spec.formatting.unit` — drives Y axis tick formatting + threshold formatting. */
formatting?: DashboardtypesPanelFormattingDTO;
/** From `spec.thresholds` — perses shape, mapped to the draw-hook shape internally. */
thresholds?: DashboardtypesThresholdWithLabelDTO[] | null;
/**
* Y axes, primary first (`resolveAxes`). Each gets a scale, an axis and its own
* threshold hook; only the primary draws gridlines.
*/
axes: ResolvedAxis[];
/** Per-query step intervals from the response exec stats. */
stepIntervals?: Record<string, number>;
@@ -71,6 +64,9 @@ export type TimeAxisChromeArgs = PanelChromeArgs &
'stepIntervals' | 'minTimeScale' | 'maxTimeScale' | 'onDragSelect' | 'onClick'
>;
/** Breathing room between two value axes drawn on the same side. */
const STACKED_AXIS_MARGIN = 12;
/**
* Builds the panel-agnostic scaffolding of a uPlot chart (scales, thresholds,
* axes, drag-to-zoom, click plugin). Callers then `addSeries`/`addPlugin` on the
@@ -82,11 +78,7 @@ export function buildBaseConfig({
isDarkMode,
timezone,
panelMode,
isLogScale,
softMin,
softMax,
formatting,
thresholds,
axes,
stepIntervals,
clickPayload,
minTimeScale,
@@ -94,7 +86,7 @@ export function buildBaseConfig({
onDragSelect,
onClick,
}: BuildBaseConfigArgs): UPlotConfigBuilder {
const yAxisUnit = formatting?.unit;
const isLogScale = axes[0]?.isLogScale ?? false;
const builder = new UPlotConfigBuilder({
id: panelId,
@@ -105,14 +97,6 @@ export function buildBaseConfig({
stepInterval: stepIntervals ? minStepInterval(stepIntervals) : undefined,
});
const thresholdOptions: ThresholdsDrawHookOptions = {
scaleKey: 'y',
thresholds: mapThresholds(thresholds),
yAxisUnit,
};
builder.addThresholds(thresholdOptions);
builder.addScale({
scaleKey: 'x',
time: true,
@@ -124,18 +108,26 @@ export function buildBaseConfig({
: DistributionType.Linear,
});
builder.addScale({
scaleKey: 'y',
time: false,
min: undefined,
max: undefined,
softMin,
softMax,
thresholds: thresholdOptions,
logBase: isLogScale ? 10 : undefined,
distribution: isLogScale
? DistributionType.Logarithmic
: DistributionType.Linear,
axes.forEach((axis) => {
const thresholdOptions: ThresholdsDrawHookOptions = {
scaleKey: axis.scaleKey,
thresholds: axis.thresholds,
yAxisUnit: axis.unit,
};
builder.addThresholds(thresholdOptions);
builder.addScale({
scaleKey: axis.scaleKey,
time: false,
min: undefined,
max: undefined,
softMin: axis.softMin,
softMax: axis.softMax,
thresholds: thresholdOptions,
logBase: axis.isLogScale ? 10 : undefined,
distribution: axis.isLogScale
? DistributionType.Logarithmic
: DistributionType.Linear,
});
});
if (typeof onClick === 'function') {
@@ -151,13 +143,35 @@ export function buildBaseConfig({
isTimeAxis,
});
builder.addAxis({
scaleKey: 'y',
show: true,
side: 3,
isDarkMode,
isLogScale,
yAxisUnit,
// Only one value axis draws gridlines: the primary, or the first drawn one once the
// primary carries nothing.
const drawnAxes = axes.filter((axis) => axis.show);
const gridScaleKey = drawnAxes[0]?.scaleKey;
// uPlot stacks same-side axes outward in order, so every drawn axis but the last on
// its side has another one outside it.
const outermostBySide = new Map(
drawnAxes.map((axis) => [axis.side, axis.scaleKey]),
);
if (drawnAxes.length > 1) {
builder.addHook('draw', axisBaselineDrawHook);
}
axes.forEach((axis) => {
builder.addAxis({
scaleKey: axis.scaleKey,
show: axis.show,
side: axis.side,
isDarkMode,
isLogScale: axis.isLogScale,
yAxisUnit: axis.unit,
...(axis.show &&
outermostBySide.get(axis.side) !== axis.scaleKey && {
outerMargin: STACKED_AXIS_MARGIN,
}),
...(axis.scaleKey !== gridScaleKey && {
grid: { show: false },
showBorder: true,
}),
});
});
return builder;
@@ -173,24 +187,6 @@ function makeTzDate(
uPlot.tzDate(new Date(timestamp * 1e3), timezone.value);
}
/**
* Perses-shape thresholds → the draw-hook shape uPlotV2 consumes. Exported so
* panels feeding the same list elsewhere don't redo the mapping.
*/
export function mapThresholds(
thresholds: DashboardtypesThresholdWithLabelDTO[] | null | undefined,
): ThresholdsDrawHookOptions['thresholds'] {
if (!thresholds || thresholds.length === 0) {
return [];
}
return thresholds.map((t) => ({
thresholdValue: t.value,
thresholdColor: t.color,
thresholdUnit: t.unit,
thresholdLabel: t.label,
}));
}
/**
* Smallest per-query step interval (seconds), fed to uPlot so tick density matches the
* densest query. Falls back to `undefined` (uPlot "auto") on an empty map, since

View File

@@ -6,13 +6,20 @@ import {
DashboardtypesPrecisionOptionDTO,
Querybuildertypesv5BucketOptionsLinearDTOKind,
type DashboardtypesHeatmapColorsDTO,
type DashboardtypesLineInterpolationDTO,
type DashboardtypesLineStyleDTO,
type DashboardtypesSpanGapsDTO,
type DashboardtypesStackModeDTO,
type Querybuildertypesv5BucketOptionsDTO,
} from 'api/generated/services/sigNoz.schemas';
import { PrecisionOption, PrecisionOptionsEnum } from 'components/Graph/types';
import { LegendPosition } from 'lib/uPlotV2/components/types';
import { FillMode, StackMode } from 'lib/uPlotV2/config/types';
import {
FillMode,
LineInterpolation,
LineStyle,
StackMode,
} from 'lib/uPlotV2/config/types';
import { clampColorSteps } from 'lib/visualization/colorRamp/colorScale';
import { HeatmapAxisScale } from 'lib/uPlotV2/plugins/HeatmapPlugin/types';
import type { ColorRampOptions } from 'lib/visualization/colorRamp/types';
@@ -24,6 +31,8 @@ import {
HEATMAP_PALETTE_MAP,
HEATMAP_Y_SCALE_MAP,
LEGEND_POSITION_MAP,
LINE_INTERPOLATION_MAP,
LINE_STYLE_MAP,
STACK_MODE_MAP,
} from './enumMaps';
@@ -149,3 +158,17 @@ export function resolveHeatmapColors(
...(colors.fill !== undefined && { fill: colors.fill }),
};
}
export function resolveLineStyle(
lineStyle: DashboardtypesLineStyleDTO | undefined,
): LineStyle {
return lineStyle ? LINE_STYLE_MAP[lineStyle] : LineStyle.Solid;
}
export function resolveLineInterpolation(
lineInterpolation: DashboardtypesLineInterpolationDTO | undefined,
): LineInterpolation {
return lineInterpolation
? LINE_INTERPOLATION_MAP[lineInterpolation]
: LineInterpolation.Spline;
}

View File

@@ -1,7 +1,8 @@
import { sortByMeanDesc } from 'lib/visualization/charts/utils/sortByMeanDesc';
import type { PanelSeries } from 'pages/DashboardPage/DashboardContainer/queryV5/types';
function seriesKey(series: PanelSeries): string {
/** Stable identity of a flattened series, for tie-breaks. */
export function seriesKey(series: PanelSeries): string {
const labels = Object.keys(series.labels)
.sort()
.map((name) => `${name}=${series.labels[name]}`)

View File

@@ -7,6 +7,7 @@ import { rest } from 'msw';
import ROUTES from 'constants/routes';
import { buildRoutePath } from 'lib/router/buildRoutePath';
import {
DashboardtypesAxisSideDTO as AxisSide,
DashboardtypesHeatmapPaletteDTO as HeatmapPalette,
DashboardtypesHeatmapYScaleDTO as HeatmapYScale,
DashboardtypesLegendPositionDTO as LegendPosition,
@@ -26,6 +27,7 @@ import { defineStoryMocks } from '@/storybook/controls/defineStoryMocks';
import { publicDashboardMeta } from '../__story_mockdata__/publicDashboard';
import {
AXIS_SIDES,
BUCKET_WIDTHS,
GAPS,
HEATMAP_COUNT_RANGES,
@@ -35,6 +37,7 @@ import {
HEATMAP_Y_SCALES,
LEGEND_POSITIONS,
LINE_STYLES,
MAX_SECONDARY_AXES,
MAX_SERIES,
PANEL_KINDS,
PANEL_RESULTS,
@@ -175,6 +178,24 @@ export const panelsMocks = defineStoryMocks({
options: Y_SCALES,
value: 'linear',
}),
primarySide: choiceControl<AxisSide>('Primary axis side', {
group: PANEL,
description: 'Which edge the y axis of Time Series, Bar and Area sits on.',
options: AXIS_SIDES,
value: AxisSide.left,
}),
secondaryAxes: countControl('Secondary axes', {
group: PANEL,
description:
'More y axes on Time Series, Bar and Area, each with one query of its own: requests/s on the right, error % on the left, bytes out on the right again. With Thresholds on, the first one gets a line too.',
value: 0,
max: MAX_SECONDARY_AXES,
}),
secondaryLog: toggleControl('Secondary log scale', {
group: PANEL,
description: 'The first secondary axis on a log scale.',
value: false,
}),
lineStyle: choiceControl<LineStyle>('Line style', {
group: PANEL,
description: 'Time Series and Area lines.',
@@ -315,6 +336,7 @@ export const panelsMocks = defineStoryMocks({
listWideRows: values.listWideRows,
gaps: values.gaps,
pieSlices: values.pieSlices,
secondaryAxes: values.secondaryAxes,
});
}),
),

View File

@@ -67,6 +67,21 @@ export const BarStacked: Story = {
play: playPanel,
};
/**
* p99 latency on the left with requests/s on the right and error % further
* left, each line read in its own unit, with a threshold on the first two axes.
*/
export const TimeSeriesSecondaryAxes: Story = {
args: { secondaryAxes: 2, thresholds: true },
play: playPanel,
};
/** The services' bars stacked on the left axis beside a lone requests/s bar series on the right. */
export const BarStackedSecondaryAxis: Story = {
args: { kind: 'Bar', stack: StackMode.normal, secondaryAxes: 1 },
play: playPanel,
};
/** The services as filled areas, drawn independently. */
export const Area: Story = {
args: { kind: 'Area' },

View File

@@ -5,6 +5,7 @@
import { Color } from '@signozhq/design-tokens';
import {
DashboardtypesAxisSideDTO as AxisSide,
DashboardtypesHeatmapPaletteDTO as HeatmapPalette,
DashboardtypesHeatmapYScaleDTO as HeatmapYScale,
DashboardtypesLegendPositionDTO as LegendPosition,
@@ -78,6 +79,50 @@ export const TEXT_ALIGNS = Object.values(TextAlign);
export const Y_SCALES = ['linear', 'log'] as const;
export const AXIS_SIDES = [AxisSide.left, AxisSide.right] as const;
/**
* Each secondary axis binds one more query, drawn in its own unit and magnitude on
* the side listed, so the sides alternate as axes are added.
*/
export const SECONDARY_AXES = [
{
id: 'throughput',
query: 'B',
metricName: 'signoz_calls',
legend: 'Requests',
unit: 'reqps',
side: AxisSide.right,
base: 1200,
amplitude: 300,
},
{
id: 'errors',
query: 'C',
metricName: 'signoz_errors',
legend: 'Error %',
unit: 'percent',
side: AxisSide.left,
base: 4,
amplitude: 2,
},
{
id: 'egress',
query: 'D',
metricName: 'signoz_egress',
legend: 'Bytes out',
unit: 'bytes',
side: AxisSide.right,
base: 50000000,
amplitude: 10000000,
},
] as const;
export const MAX_SECONDARY_AXES = SECONDARY_AXES.length;
/** Inside the first secondary axis's range, so its line crosses the series. */
export const SECONDARY_THRESHOLD_VALUE = 1400;
export const LINE_STYLES = Object.values(LineStyle);
export const GAPS = ['none', 'hole'] as const;

View File

@@ -16,15 +16,20 @@ import {
DashboardtypesPanelPluginVariantGithubComSigNozSignozPkgTypesDashboardtypesTimeSeriesPanelSpecDTOKind as TimeSeriesKind,
DashboardtypesPanelPluginVariantGithubComSigNozSignozPkgTypesDashboardtypesTopListPanelSpecDTOKind as TopListKind,
MetrictypesSpaceAggregationDTO as SpaceAggregation,
DashboardtypesLineInterpolationDTO as LineInterpolation,
DashboardtypesStackModeDTO as StackMode,
DashboardtypesTextModeDTO as TextMode,
Querybuildertypesv5RequestTypeDTO as RequestType,
type DashboardtypesAxesDTO,
type DashboardtypesAxisThresholdDTO,
type DashboardtypesPanelPluginDTO,
type DashboardtypesQueryDTO,
type DashboardtypesSecondaryAxisDTO,
} from 'api/generated/services/sigNoz.schemas';
import {
HEATMAP_FIXED_COUNTS,
SECONDARY_AXES,
TABLE_SECOND_COLUMN,
TABLE_THRESHOLD_VALUE,
TABLE_VALUE_COLUMN,
@@ -36,6 +41,7 @@ import {
eventHeatmapQuery,
logQuery,
metricQuery,
secondaryAxisThresholds,
tableThresholds,
TEXT_BODIES,
} from './panelQueries';
@@ -49,15 +55,50 @@ interface PanelShape {
const unitOf = (unit: PanelUnit): string | undefined =>
unit === 'none' ? undefined : unit;
const timeSeriesQueries = (): DashboardtypesQueryDTO[] => [
/** The grouped latency query, then one ungrouped query per secondary axis. */
const timeSeriesQueries = (secondaryAxes = 0): DashboardtypesQueryDTO[] => [
metricQuery(RequestType.time_series, { grouped: true }),
...SECONDARY_AXES.slice(0, secondaryAxes).map((axis) =>
metricQuery(RequestType.time_series, {
grouped: false,
name: axis.query,
metricName: axis.metricName,
legend: axis.legend,
}),
),
];
/** The first secondary axis carries the log toggle and a stepped line. */
const secondaryAxes = (args: PanelArgs): DashboardtypesSecondaryAxisDTO[] =>
SECONDARY_AXES.slice(0, args.secondaryAxes).map((axis, index) => ({
id: axis.id,
unit: axis.unit,
side: axis.side,
isLogScale: index === 0 && args.secondaryLog,
series: [axis.query],
...(index === 0 && {
chartAppearance: { lineInterpolation: LineInterpolation.step_after },
}),
}));
/** The primary axis from its controls, then the secondary axes. */
const axesOf = (args: PanelArgs): DashboardtypesAxesDTO => ({
isLogScale: args.yScale === 'log',
side: args.primarySide,
secondary: secondaryAxes(args),
});
/** The primary line, plus one on the first secondary axis once there is one. */
const chartThresholds = (args: PanelArgs): DashboardtypesAxisThresholdDTO[] => [
...labelThresholds(args.thresholds),
...secondaryAxisThresholds(args.thresholds && args.secondaryAxes > 0),
];
export const panelShape = (args: PanelArgs): PanelShape => {
const formatting = { unit: unitOf(args.unit) };
const legend = { position: args.legend };
const axes = { isLogScale: args.yScale === 'log' };
const thresholds = labelThresholds(args.thresholds);
const axes = axesOf(args);
const thresholds = chartThresholds(args);
const chartAppearance = {
lineStyle: args.lineStyle,
showPoints: args.showPoints,
@@ -80,7 +121,7 @@ export const panelShape = (args: PanelArgs): PanelShape => {
visualization: { stackedBarChart: args.stack !== StackMode.none },
},
},
queries: timeSeriesQueries(),
queries: timeSeriesQueries(args.secondaryAxes),
};
case 'Area':
return {
@@ -95,7 +136,7 @@ export const panelShape = (args: PanelArgs): PanelShape => {
visualization: { stack: args.stack },
},
},
queries: timeSeriesQueries(),
queries: timeSeriesQueries(args.secondaryAxes),
};
case 'Histogram':
return {
@@ -235,7 +276,7 @@ export const panelShape = (args: PanelArgs): PanelShape => {
kind: TimeSeriesKind['signoz/TimeSeriesPanel'],
spec: { axes, chartAppearance, formatting, legend, thresholds },
},
queries: timeSeriesQueries(),
queries: timeSeriesQueries(args.secondaryAxes),
};
}
};

View File

@@ -18,7 +18,7 @@ import {
type DashboardtypesComparisonThresholdDTO,
type DashboardtypesQueryDTO,
type DashboardtypesTableThresholdDTO,
type DashboardtypesThresholdWithLabelDTO,
type DashboardtypesAxisThresholdDTO,
type Querybuildertypesv5QueryBuilderQueryGithubComSigNozSignozPkgTypesQuerybuildertypesQuerybuildertypesv5LogAggregationDTO as LogBuilderQuery,
type Querybuildertypesv5QueryBuilderQueryGithubComSigNozSignozPkgTypesQuerybuildertypesQuerybuildertypesv5MetricAggregationDTO as MetricBuilderQuery,
type Querybuildertypesv5QueryBuilderQueryGithubComSigNozSignozPkgTypesQuerybuildertypesQuerybuildertypesv5TraceAggregationDTO as TraceBuilderQuery,
@@ -27,6 +27,8 @@ import {
import {
CHART_THRESHOLD_VALUE,
HEATMAP_FIELDS,
SECONDARY_AXES,
SECONDARY_THRESHOLD_VALUE,
NUMBER_THRESHOLD_VALUE,
QUERY_NAME,
TABLE_THRESHOLD_VALUE,
@@ -37,11 +39,26 @@ import type { HeatmapSource, TextSample } from './types';
export const labelThresholds = (
on: boolean,
): DashboardtypesThresholdWithLabelDTO[] =>
): DashboardtypesAxisThresholdDTO[] =>
on
? [{ value: CHART_THRESHOLD_VALUE, color: THRESHOLD_COLOR, label: 'SLO' }]
: [];
/** A line on the first secondary axis, in its own unit. */
export const secondaryAxisThresholds = (
on: boolean,
): DashboardtypesAxisThresholdDTO[] =>
on
? [
{
value: SECONDARY_THRESHOLD_VALUE,
color: THRESHOLD_COLOR,
label: 'Capacity',
axis: SECONDARY_AXES[0].id,
},
]
: [];
export const comparisonThresholds = (
on: boolean,
value = NUMBER_THRESHOLD_VALUE,
@@ -96,6 +113,7 @@ interface MetricQueryOptions {
name?: string;
metricName?: string;
spaceAggregation?: SpaceAggregation;
legend?: string;
}
export const metricQuery = (
@@ -106,6 +124,7 @@ export const metricQuery = (
name = QUERY_NAME,
metricName = 'signoz_latency',
spaceAggregation = SpaceAggregation.p99,
legend,
}: MetricQueryOptions,
): DashboardtypesQueryDTO => {
const spec: MetricBuilderQuery = {
@@ -120,9 +139,10 @@ export const metricQuery = (
],
groupBy: grouped ? [{ name: 'service.name' }] : undefined,
legend:
grouped && requestType !== RequestType.scalar
legend ??
(grouped && requestType !== RequestType.scalar
? '{{service.name}}'
: undefined,
: undefined),
bucketOptions: heatmap
? { kind: LinearBuckets.linear, spec: { maxValue: 1000, numBuckets: 10 } }
: undefined,

View File

@@ -30,6 +30,7 @@ import {
MAX_SERIES,
NUMBER_VALUE,
QUERY_NAME,
SECONDARY_AXES,
SERVICES,
TABLE_SECOND_COLUMN,
} from './constants';
@@ -90,11 +91,27 @@ export const serviceIndex = (label: string): number =>
serviceAt(index),
).indexOf(label);
/** The one series a secondary axis's query answers with, in that axis's magnitude. */
export const secondaryAxisPoints = (
{ start, end }: PanelWindow,
axisIndex: number,
): { timestamp: number; value: number }[] => {
const { base, amplitude } = SECONDARY_AXES[axisIndex];
return timeSeriesPoints({
start,
end,
base,
amplitude,
seed: 7 * (axisIndex + 1),
});
};
const latencySeries = (
window: PanelWindow,
count: number,
gaps: Gaps,
warning: Warning | undefined,
secondaryAxes: number,
): MetricRangePayloadV5 =>
queryRangeV5TimeSeriesResponse(
[
@@ -105,6 +122,10 @@ const latencySeries = (
values: latencyPoints(window, index, gaps),
})),
},
...SECONDARY_AXES.slice(0, secondaryAxes).map((axis, index) => ({
queryName: axis.query,
series: [{ labels: [], values: secondaryAxisPoints(window, index) }],
})),
],
{ warning },
);
@@ -237,6 +258,7 @@ export const panelQueryResponse = ({
listWideRows,
gaps,
pieSlices,
secondaryAxes,
window,
offset,
limit,
@@ -291,6 +313,6 @@ export const panelQueryResponse = ({
},
);
default:
return latencySeries(window, series, gaps, warning);
return latencySeries(window, series, gaps, warning, secondaryAxes);
}
};

View File

@@ -4,6 +4,7 @@
*/
import type {
DashboardtypesAxisSideDTO as AxisSide,
DashboardtypesHeatmapPaletteDTO as HeatmapPalette,
DashboardtypesHeatmapYScaleDTO as HeatmapYScale,
DashboardtypesLegendPositionDTO as LegendPosition,
@@ -69,6 +70,10 @@ export interface PanelArgs {
textAlign: TextAlign;
hideHeader: boolean;
yScale: YScale;
primarySide: AxisSide;
/** How many of `SECONDARY_AXES` the panel declares, each with its own query. */
secondaryAxes: number;
secondaryLog: boolean;
lineStyle: LineStyle;
showPoints: boolean;
spanGaps: SpanGaps;
@@ -94,4 +99,5 @@ export interface PanelResponseArgs extends PanelRequest {
listWideRows: boolean;
gaps: Gaps;
pieSlices: PieSlices;
secondaryAxes: number;
}

View File

@@ -1,4 +1,5 @@
import {
DashboardtypesAxisSideDTO as AxisSide,
DashboardtypesLineStyleDTO as LineStyle,
DashboardtypesStackModeDTO as StackMode,
} from 'api/generated/services/sigNoz.schemas';
@@ -7,6 +8,8 @@ import type uPlot from 'uplot';
import {
CHART_THRESHOLD_VALUE,
SECONDARY_AXES,
SECONDARY_THRESHOLD_VALUE,
THRESHOLD_COLOR,
} from '../__story_mockdata__/constants';
import {
@@ -29,6 +32,45 @@ const isPercent = ({ kind, stack }: PanelArgs): boolean =>
const hasLineAppearance = ({ kind }: PanelArgs): boolean =>
kind === 'TimeSeries' || kind === 'Area';
/** uPlot axis sides: 1 is right, 3 is left. */
const UPLOT_SIDE: Record<AxisSide, number> = {
[AxisSide.left]: 3,
[AxisSide.right]: 1,
};
const secondaryScaleKey = (index: number): string =>
`y:${SECONDARY_AXES[index].id}`;
/** One axis per declared secondary axis, on its side, with its series and log scale. */
const expectAxes = async (plot: uPlot, args: PanelPlayArgs): Promise<void> => {
const secondary = SECONDARY_AXES.slice(0, args.secondaryAxes);
await expect(plot.axes.map((axis) => [axis.scale, axis.side])).toStrictEqual([
['x', 2],
['y', UPLOT_SIDE[args.primarySide]],
...secondary.map((axis, index) => [
secondaryScaleKey(index),
UPLOT_SIDE[axis.side],
]),
]);
// The renderer orders series by mean, so a secondary series can land anywhere.
await expect(
plot.series
.slice(1)
.map((series) => series.scale)
.sort((a, b) => String(a).localeCompare(String(b))),
).toStrictEqual(
[
...Array.from({ length: args.series }, () => 'y'),
...secondary.map((_axis, index) => secondaryScaleKey(index)),
].sort((a, b) => String(a).localeCompare(String(b))),
);
if (secondary.length > 0) {
await expect(plot.scales[secondaryScaleKey(0)].distr).toBe(
args.secondaryLog ? 3 : 1,
);
}
};
const nullCount = (plot: uPlot): number =>
plot.data
.slice(1)
@@ -82,9 +124,12 @@ const expectPercentShares = async (
if (!request) {
throw new Error('the panel sent no query_range');
}
const seriesCount = plot.series.length - 1;
const raw = plot.series.slice(1).map(({ label }) => {
const index = serviceIndex(String(label));
// Only the primary axis's series share in the 100; the others keep their raw values.
const primaryIndexes = plot.series
.map((series, index) => (index > 0 && series.scale === 'y' ? index : 0))
.filter((index) => index > 0);
const raw = primaryIndexes.map((seriesIndex) => {
const index = serviceIndex(String(plot.series[seriesIndex].label));
return new Map(
latencyPoints(request.window, index, args.gaps).map((point) => [
Math.round(point.timestamp / 1000),
@@ -101,11 +146,12 @@ const expectPercentShares = async (
continue;
}
const total = (values as number[]).reduce((sum, value) => sum + value, 0);
for (let series = 1; series <= seriesCount; series++) {
const below = series < seriesCount ? (plotted[series + 1][column] ?? 0) : 0;
const share = (plotted[series][column] ?? 0) - below;
for (const [position, seriesIndex] of primaryIndexes.entries()) {
const belowIndex = primaryIndexes[position + 1];
const below = belowIndex ? (plotted[belowIndex][column] ?? 0) : 0;
const share = (plotted[seriesIndex][column] ?? 0) - below;
await expect(share).toBeCloseTo(
((values[series - 1] as number) / total) * 100,
((values[position] as number) / total) * 100,
3,
);
}
@@ -118,15 +164,17 @@ export const expectLineChart = async (
root: HTMLElement,
args: PanelPlayArgs,
): Promise<void> => {
const plot = await waitForPlot(root, args.series);
const plot = await waitForPlot(root, args.series + args.secondaryAxes);
// Set from options at construction; uPlot's typings leave it off the instance.
// A secondary axis holds one series, so only the primary axis's stack has bands.
const { bands } = plot as uPlot & { bands?: uPlot.Band[] };
await expect(bands?.length ?? 0).toBe(isStacked(args) ? args.series - 1 : 0);
// A percent stack replaces the y scale with its own 0–100 one.
if (!isPercent(args)) {
await expect(plot.scales.y.distr).toBe(args.yScale === 'log' ? 3 : 1);
}
await expectAxes(plot, args);
await expectLineAppearance(plot, args);
if (args.legend === 'right') {
await expect(
@@ -137,7 +185,7 @@ export const expectLineChart = async (
() =>
expect(
root.querySelectorAll('[data-legend-item-id][aria-checked="true"]'),
).toHaveLength(args.series),
).toHaveLength(args.series + args.secondaryAxes),
PANEL_LOAD,
);
@@ -153,5 +201,15 @@ export const expectLineChart = async (
} else if (!args.thresholds) {
await expect(coverage).toBeLessThan(0.1);
}
if (args.thresholds && args.secondaryAxes > 0) {
await expect(
lineCoverage(
plot,
SECONDARY_THRESHOLD_VALUE,
THRESHOLD_COLOR,
secondaryScaleKey(0),
),
).toBeGreaterThan(0.4);
}
}, PANEL_LOAD);
};

View File

@@ -47,9 +47,10 @@ export const lineCoverage = (
plot: uPlot,
value: number,
color: string,
scaleKey = 'y',
): number => {
const [r, g, b] = toRgb(color);
const y = Math.round(plot.valToPos(value, 'y', true));
const y = Math.round(plot.valToPos(value, scaleKey, true));
const x = Math.round(plot.bbox.left);
const width = Math.round(plot.bbox.width);
const { data } = plot.ctx.getImageData(x, y - 1, width, 3);