mirror of
https://github.com/SigNoz/signoz.git
synced 2026-12-03 13:40:42 +00:00
Compare commits
17 Commits
chore/dead
...
feat/multi
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
c4537f5f38 | ||
|
|
17bd6531da | ||
|
|
cbfa698404 | ||
|
|
a3300666a3 | ||
|
|
e21281dcf3 | ||
|
|
0b4f3808bc | ||
|
|
61ab580e56 | ||
|
|
f3465d7aa3 | ||
|
|
5059b0c59a | ||
|
|
5318bdec45 | ||
|
|
03fdbd5a53 | ||
|
|
e5f4b36833 | ||
|
|
89d90fd388 | ||
|
|
0d4476c012 | ||
|
|
3885c69e8d | ||
|
|
6d3760c9cb | ||
|
|
247ce1a981 |
@@ -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.
|
||||
*/
|
||||
|
||||
@@ -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;
|
||||
|
||||
@@ -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">
|
||||
|
||||
@@ -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}` : '';
|
||||
}
|
||||
|
||||
@@ -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,
|
||||
|
||||
@@ -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,
|
||||
|
||||
@@ -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[] = [
|
||||
|
||||
@@ -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),
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -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;
|
||||
|
||||
@@ -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;
|
||||
|
||||
@@ -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;
|
||||
|
||||
@@ -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 });
|
||||
});
|
||||
});
|
||||
|
||||
@@ -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] }]);
|
||||
});
|
||||
});
|
||||
});
|
||||
|
||||
@@ -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;
|
||||
}
|
||||
|
||||
@@ -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();
|
||||
});
|
||||
});
|
||||
47
frontend/src/lib/uPlotV2/hooks/axisBaselineDrawHook.ts
Normal file
47
frontend/src/lib/uPlotV2/hooks/axisBaselineDrawHook.ts
Normal 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();
|
||||
}
|
||||
@@ -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);
|
||||
|
||||
@@ -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);
|
||||
|
||||
@@ -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,
|
||||
|
||||
@@ -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 }));
|
||||
|
||||
@@ -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(() => {
|
||||
|
||||
@@ -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,
|
||||
|
||||
@@ -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] }]);
|
||||
});
|
||||
});
|
||||
});
|
||||
|
||||
@@ -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;
|
||||
|
||||
@@ -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] });
|
||||
|
||||
@@ -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,
|
||||
|
||||
@@ -5,8 +5,10 @@ import {
|
||||
SECTION_METADATA,
|
||||
type SectionConfig,
|
||||
SectionKind,
|
||||
type SectionSpecMap,
|
||||
} from 'pages/DashboardPage/DashboardContainer/Panels/types/sections';
|
||||
import type { SeededPluginSpec } from 'pages/DashboardPage/DashboardContainer/Panels/utils/buildPluginSpec';
|
||||
import { getTableColumnKeys } from 'pages/DashboardPage/DashboardContainer/Panels/utils/getTableColumnKeys';
|
||||
|
||||
import type { SectionEditorContext } from '../sectionContext';
|
||||
import { getSectionDefault, resolveSectionEditor } from '../sectionRegistry';
|
||||
@@ -131,8 +133,14 @@ function SectionSlot({
|
||||
// Atomic sections carry no `controls`; controlled ones do.
|
||||
const controls = 'controls' in config ? config.controls : undefined;
|
||||
// Forwarded to editors that scope to the panel's unit (e.g. the thresholds unit picker).
|
||||
const yAxisUnit = (spec.plugin.spec as { formatting?: PanelFormattingSlice })
|
||||
.formatting?.unit;
|
||||
const { formatting, axes, visualization, chartAppearance } = spec.plugin
|
||||
.spec as {
|
||||
formatting?: PanelFormattingSlice;
|
||||
axes?: SectionSpecMap[SectionKind.Axes];
|
||||
visualization?: SectionSpecMap[SectionKind.Visualization];
|
||||
chartAppearance?: SectionSpecMap[SectionKind.ChartAppearance];
|
||||
};
|
||||
const yAxisUnit = formatting?.unit;
|
||||
|
||||
const headerSlot = SECTION_HEADER_SLOT[config.kind]?.(triggerHeaderAction);
|
||||
|
||||
@@ -144,6 +152,10 @@ function SectionSlot({
|
||||
sizeColumnLabel: getSizeColumnLabel(spec, tableColumns),
|
||||
axisColumnNames: getScatterAxisColumnNames(spec, tableColumns),
|
||||
axisColumnUnits: getScatterAxisColumnUnits(spec, tableColumns),
|
||||
valueColumnKeys: getTableColumnKeys(spec.queries ?? []),
|
||||
secondaryAxes: axes?.secondary ?? undefined,
|
||||
stackMode: visualization?.stack,
|
||||
chartAppearance,
|
||||
signal,
|
||||
panelKind,
|
||||
onChangePanelKind,
|
||||
|
||||
@@ -1,8 +1,13 @@
|
||||
import type { TelemetrytypesSignalDTO } from 'api/generated/services/sigNoz.schemas';
|
||||
import type {
|
||||
DashboardtypesSecondaryAxisDTO,
|
||||
DashboardtypesStackModeDTO,
|
||||
TelemetrytypesSignalDTO,
|
||||
} from 'api/generated/services/sigNoz.schemas';
|
||||
|
||||
import type { GeoMapPlacement } from 'pages/DashboardPage/DashboardContainer/Panels/kinds/GeoMapPanel/types';
|
||||
|
||||
import type { PanelKind } from '../../Panels/types/panelKind';
|
||||
import type { PanelChartAppearanceSlice } from '../../Panels/types/sections';
|
||||
import type { LegendSeries } from 'pages/DashboardPage/DashboardContainer/Panels/utils/legendSeries';
|
||||
import type { TableColumnOption } from '../hooks/useTableColumns';
|
||||
import { EQueryType } from 'types/common/dashboard';
|
||||
@@ -23,6 +28,14 @@ export interface SectionEditorContext {
|
||||
axisColumnNames?: { x?: string; y?: string };
|
||||
/** Unit of the column each Scatter Plot axis plots. */
|
||||
axisColumnUnits?: { x?: string; y?: string };
|
||||
/** Value column keys the panel's queries produce; empty when only a run can tell. */
|
||||
valueColumnKeys?: string[];
|
||||
/** The panel's `axes.secondary`, for the threshold axis picker. */
|
||||
secondaryAxes?: DashboardtypesSecondaryAxisDTO[];
|
||||
/** Area's stack mode; `percent` keeps every series on the primary axis. */
|
||||
stackMode?: DashboardtypesStackModeDTO;
|
||||
/** The panel's own line settings, which a secondary axis overrides or inherits. */
|
||||
chartAppearance?: PanelChartAppearanceSlice;
|
||||
/** Geo Map's rows as the preview places them, for the location status and circle size. */
|
||||
geoMapPlacement?: GeoMapPlacement;
|
||||
signal?: TelemetrytypesSignalDTO;
|
||||
|
||||
@@ -1,5 +1,6 @@
|
||||
import type { ComponentType } from 'react';
|
||||
import {
|
||||
type DashboardtypesAxisThresholdDTO,
|
||||
type DashboardtypesGeoMapChartAppearanceDTO,
|
||||
DashboardtypesGeoMapLayerDTO,
|
||||
type DashboardtypesGeoMapLocationDTO,
|
||||
@@ -23,6 +24,7 @@ import {
|
||||
type SectionSpecMap,
|
||||
} from 'pages/DashboardPage/DashboardContainer/Panels/types/sections';
|
||||
import { fitBubbleRadius } from 'pages/DashboardPage/DashboardContainer/Panels/kinds/GeoMapPanel/utils/chartOptions';
|
||||
import { dropDanglingThresholdAxes } from 'pages/DashboardPage/DashboardContainer/Panels/utils/axes/reconcileAxes';
|
||||
import type { SeededPluginSpec } from 'pages/DashboardPage/DashboardContainer/Panels/utils/buildPluginSpec';
|
||||
|
||||
import type { SectionEditorContext } from './sectionContext';
|
||||
@@ -92,11 +94,25 @@ export const SECTION_REGISTRY: {
|
||||
update: (spec, formatting): PanelSpec =>
|
||||
updatePluginSlice(spec, 'formatting', formatting),
|
||||
},
|
||||
// Removing a secondary axis moves its thresholds to the primary axis.
|
||||
[SectionKind.Axes]: {
|
||||
Component: AxesSection,
|
||||
get: (spec): PanelAxesSlice | undefined =>
|
||||
getPluginSlice<PanelAxesSlice>(spec, 'axes'),
|
||||
update: (spec, axes): PanelSpec => updatePluginSlice(spec, 'axes', axes),
|
||||
update: (spec, axes): PanelSpec => {
|
||||
const thresholds = getPluginSlice<AnyThreshold[]>(spec, 'thresholds');
|
||||
const next = updatePluginSlice(spec, 'axes', axes);
|
||||
return thresholds?.length
|
||||
? updatePluginSlice(
|
||||
next,
|
||||
'thresholds',
|
||||
dropDanglingThresholdAxes(
|
||||
thresholds as DashboardtypesAxisThresholdDTO[],
|
||||
axes,
|
||||
),
|
||||
)
|
||||
: next;
|
||||
},
|
||||
},
|
||||
// Same `axes` key as above, in Scatter Plot's per-axis shape.
|
||||
[SectionKind.ScatterAxes]: {
|
||||
|
||||
@@ -3,3 +3,19 @@
|
||||
flex-direction: column;
|
||||
gap: 14px;
|
||||
}
|
||||
|
||||
.axisList {
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
gap: 12px;
|
||||
}
|
||||
|
||||
// The antd Select inside the unit selector sizes to its content; the other
|
||||
// sections' unit pickers stretch it the same way.
|
||||
.unitSelector {
|
||||
width: 100%;
|
||||
|
||||
:global(.ant-select) {
|
||||
width: 100%;
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1,4 +1,7 @@
|
||||
import { DashboardtypesHeatmapYScaleDTO } from 'api/generated/services/sigNoz.schemas';
|
||||
import {
|
||||
DashboardtypesHeatmapYScaleDTO,
|
||||
DashboardtypesStackModeDTO,
|
||||
} from 'api/generated/services/sigNoz.schemas';
|
||||
import type {
|
||||
SectionEditorProps,
|
||||
SectionKind,
|
||||
@@ -6,10 +9,13 @@ import type {
|
||||
|
||||
import ConfigField from '../../controls/ConfigField/ConfigField';
|
||||
import ConfigTiles from '../../controls/ConfigTiles/ConfigTiles';
|
||||
import type { SectionEditorContext } from '../../sectionContext';
|
||||
import { createFieldResetter } from '../../utils/changes';
|
||||
import AxisFields from './AxisFields';
|
||||
import AxisRangeField from './AxisRangeField';
|
||||
import AxisScaleField from './AxisScaleField';
|
||||
import AxisSideField from './AxisSideField';
|
||||
import SecondaryAxesList from './SecondaryAxesList';
|
||||
import {
|
||||
BUCKET_SCALE_HELP,
|
||||
BUCKET_SCALE_OPTIONS,
|
||||
@@ -17,17 +23,28 @@ import {
|
||||
SCALE_HELP,
|
||||
} from './options';
|
||||
|
||||
type AxesSectionProps = SectionEditorProps<SectionKind.Axes> &
|
||||
Pick<
|
||||
SectionEditorContext,
|
||||
'valueColumnKeys' | 'stackMode' | 'metricUnit' | 'chartAppearance'
|
||||
>;
|
||||
|
||||
/**
|
||||
* Edits the `axes` slice of a panel spec: soft Y-axis min/max bounds, the
|
||||
* linear/logarithmic scale toggle, or — for the heatmap, which has no soft bounds —
|
||||
* the bucket-axis distribution. Each control is gated by its `controls` flag.
|
||||
* linear/logarithmic scale toggle, the primary axis side and the secondary axes, or —
|
||||
* for the heatmap, which has no soft bounds — the bucket-axis distribution. Each
|
||||
* control is gated by its `controls` flag.
|
||||
*/
|
||||
function AxesSection({
|
||||
value,
|
||||
savedValue,
|
||||
controls,
|
||||
onChange,
|
||||
}: SectionEditorProps<SectionKind.Axes>): JSX.Element {
|
||||
valueColumnKeys = [],
|
||||
stackMode,
|
||||
metricUnit,
|
||||
chartAppearance,
|
||||
}: AxesSectionProps): JSX.Element {
|
||||
const reset = createFieldResetter(value, savedValue, onChange);
|
||||
|
||||
if (controls.y) {
|
||||
@@ -52,30 +69,60 @@ function AxesSection({
|
||||
}
|
||||
|
||||
return (
|
||||
<ConfigField label="Y axis" {...reset('softMin', 'softMax', 'isLogScale')}>
|
||||
<AxisFields>
|
||||
{controls.minMax && (
|
||||
<AxisRangeField
|
||||
testIdPrefix="panel-editor-v2"
|
||||
value={value}
|
||||
onChange={(bounds): void => onChange({ ...value, ...bounds })}
|
||||
/>
|
||||
)}
|
||||
<>
|
||||
<ConfigField
|
||||
label="Y axis"
|
||||
{...reset('softMin', 'softMax', 'isLogScale', 'side')}
|
||||
>
|
||||
<AxisFields>
|
||||
{controls.side && (
|
||||
<AxisSideField
|
||||
testId="panel-editor-v2-axis-side"
|
||||
value={value?.side}
|
||||
onChange={(side): void => onChange({ ...value, side })}
|
||||
/>
|
||||
)}
|
||||
{controls.minMax && (
|
||||
<AxisRangeField
|
||||
testIdPrefix="panel-editor-v2"
|
||||
value={value}
|
||||
onChange={(bounds): void => onChange({ ...value, ...bounds })}
|
||||
/>
|
||||
)}
|
||||
|
||||
{controls.logScale && (
|
||||
<AxisScaleField
|
||||
testId="panel-editor-v2-log-scale"
|
||||
aria-label="Y-axis scale"
|
||||
value={value?.isLogScale ? 'log' : 'linear'}
|
||||
items={LOG_SCALE_OPTIONS}
|
||||
help={SCALE_HELP}
|
||||
onChange={(next): void =>
|
||||
onChange({ ...value, isLogScale: next === 'log' })
|
||||
}
|
||||
/>
|
||||
)}
|
||||
</AxisFields>
|
||||
</ConfigField>
|
||||
{controls.logScale && (
|
||||
<AxisScaleField
|
||||
testId="panel-editor-v2-log-scale"
|
||||
aria-label="Y-axis scale"
|
||||
value={value?.isLogScale ? 'log' : 'linear'}
|
||||
items={LOG_SCALE_OPTIONS}
|
||||
help={SCALE_HELP}
|
||||
onChange={(next): void =>
|
||||
onChange({ ...value, isLogScale: next === 'log' })
|
||||
}
|
||||
/>
|
||||
)}
|
||||
</AxisFields>
|
||||
</ConfigField>
|
||||
{controls.secondary && (
|
||||
<SecondaryAxesList
|
||||
axes={value?.secondary ?? []}
|
||||
valueColumnKeys={valueColumnKeys}
|
||||
panelAppearance={
|
||||
controls.secondaryAppearance ? (chartAppearance ?? {}) : undefined
|
||||
}
|
||||
isPercentStacked={stackMode === DashboardtypesStackModeDTO.percent}
|
||||
metricUnit={metricUnit}
|
||||
{...reset('secondary')}
|
||||
onChange={(secondary): void =>
|
||||
onChange({
|
||||
...value,
|
||||
secondary: secondary.length > 0 ? secondary : undefined,
|
||||
})
|
||||
}
|
||||
/>
|
||||
)}
|
||||
</>
|
||||
);
|
||||
}
|
||||
|
||||
|
||||
@@ -0,0 +1,55 @@
|
||||
import { ArrowLeftToLine, ArrowRightToLine } from '@signozhq/icons';
|
||||
import {
|
||||
ToggleGroup,
|
||||
type ToggleGroupItemProps,
|
||||
} from '@signozhq/ui/toggle-group';
|
||||
import { DashboardtypesAxisSideDTO } from 'api/generated/services/sigNoz.schemas';
|
||||
|
||||
import ConfigInlineField from '../../controls/ConfigInlineField/ConfigInlineField';
|
||||
|
||||
const AXIS_SIDE_ITEMS: ToggleGroupItemProps[] = [
|
||||
{
|
||||
value: DashboardtypesAxisSideDTO.left,
|
||||
label: 'Left',
|
||||
prefix: <ArrowLeftToLine size={14} />,
|
||||
},
|
||||
{
|
||||
value: DashboardtypesAxisSideDTO.right,
|
||||
label: 'Right',
|
||||
prefix: <ArrowRightToLine size={14} />,
|
||||
},
|
||||
];
|
||||
|
||||
interface AxisSideFieldProps {
|
||||
/** Names the group; each button is `${testId}-button-${side}`. */
|
||||
testId: string;
|
||||
value: DashboardtypesAxisSideDTO | undefined;
|
||||
onChange: (side: DashboardtypesAxisSideDTO) => void;
|
||||
}
|
||||
|
||||
/** Which plot edge the axis is drawn on; unset reads as left. */
|
||||
function AxisSideField({
|
||||
testId,
|
||||
value,
|
||||
onChange,
|
||||
}: AxisSideFieldProps): JSX.Element {
|
||||
return (
|
||||
<ConfigInlineField label="Side">
|
||||
<ToggleGroup
|
||||
type="single"
|
||||
variant="outlined"
|
||||
color="secondary"
|
||||
size="md"
|
||||
width="100%"
|
||||
aria-label="Axis side"
|
||||
testId={testId}
|
||||
value={value ?? DashboardtypesAxisSideDTO.left}
|
||||
items={AXIS_SIDE_ITEMS}
|
||||
// The buttons' values are the enum's members; ToggleGroup reports them as strings.
|
||||
onChange={(side): void => onChange(side as DashboardtypesAxisSideDTO)}
|
||||
/>
|
||||
</ConfigInlineField>
|
||||
);
|
||||
}
|
||||
|
||||
export default AxisSideField;
|
||||
@@ -0,0 +1,189 @@
|
||||
import { useRef, useState } from 'react';
|
||||
import { ArrowLeftToLine, ArrowRightToLine, Plus } from '@signozhq/icons';
|
||||
import { Button } from '@signozhq/ui/button';
|
||||
import {
|
||||
DashboardtypesAxisSideDTO,
|
||||
type DashboardtypesSecondaryAxisDTO,
|
||||
} from 'api/generated/services/sigNoz.schemas';
|
||||
import { v4 as uuid } from 'uuid';
|
||||
|
||||
import ConfigField from '../../controls/ConfigField/ConfigField';
|
||||
import type { PanelChartAppearanceSlice } from 'pages/DashboardPage/DashboardContainer/Panels/types/sections';
|
||||
|
||||
import type { FieldResetProps } from '../../utils/changes';
|
||||
import ThresholdRowShell from '../ThresholdsSection/rows/shared/ThresholdRowShell';
|
||||
import {
|
||||
MAX_READABLE_AXES,
|
||||
PERCENT_STACK_HINT,
|
||||
TOO_MANY_AXES_HINT,
|
||||
} from './options';
|
||||
import SecondaryAxisFields from './SecondaryAxisFields';
|
||||
|
||||
import styles from './AxesSection.module.scss';
|
||||
|
||||
interface SecondaryAxesListProps extends FieldResetProps {
|
||||
axes: DashboardtypesSecondaryAxisDTO[];
|
||||
/** Value column keys the panel's queries produce; empty when only a run can tell. */
|
||||
valueColumnKeys: string[];
|
||||
/** The panel's line settings; unset hides the per-axis line fields (Bar). */
|
||||
panelAppearance?: PanelChartAppearanceSlice;
|
||||
/** A percent stack keeps every series on the primary axis. */
|
||||
isPercentStacked: boolean;
|
||||
metricUnit?: string;
|
||||
onChange: (next: DashboardtypesSecondaryAxisDTO[]) => void;
|
||||
}
|
||||
|
||||
/** Ids only need to be unique within the panel; thresholds refer to them. */
|
||||
const newAxisId = (): string => uuid().slice(0, 8);
|
||||
|
||||
const SIDE_LABEL: Record<DashboardtypesAxisSideDTO, string> = {
|
||||
[DashboardtypesAxisSideDTO.left]: 'Left',
|
||||
[DashboardtypesAxisSideDTO.right]: 'Right',
|
||||
};
|
||||
|
||||
/**
|
||||
* The `axes.secondary` list, with the thresholds list's mechanics: one row edits at a
|
||||
* time, edits stream into the spec so the preview follows, a freshly-added row is
|
||||
* removed if discarded before saving, and Discard on an existing row restores it.
|
||||
*/
|
||||
function SecondaryAxesList({
|
||||
axes,
|
||||
valueColumnKeys,
|
||||
panelAppearance,
|
||||
isPercentStacked,
|
||||
metricUnit,
|
||||
changed,
|
||||
onReset,
|
||||
onChange,
|
||||
}: SecondaryAxesListProps): JSX.Element {
|
||||
const [editingIndex, setEditingIndex] = useState<number | null>(null);
|
||||
const [unsavedIndex, setUnsavedIndex] = useState<number | null>(null);
|
||||
const editSnapshot = useRef<DashboardtypesSecondaryAxisDTO | null>(null);
|
||||
|
||||
const tooMany = axes.length + 1 > MAX_READABLE_AXES;
|
||||
const help = isPercentStacked
|
||||
? PERCENT_STACK_HINT
|
||||
: tooMany
|
||||
? TOO_MANY_AXES_HINT
|
||||
: undefined;
|
||||
|
||||
const updateAt =
|
||||
(index: number) =>
|
||||
(next: DashboardtypesSecondaryAxisDTO): void => {
|
||||
onChange(axes.map((axis, i) => (i === index ? next : axis)));
|
||||
};
|
||||
|
||||
const removeAt = (index: number): void => {
|
||||
onChange(axes.filter((_axis, i) => i !== index));
|
||||
setEditingIndex(null);
|
||||
setUnsavedIndex(null);
|
||||
};
|
||||
|
||||
const addAxis = (): void => {
|
||||
onChange([
|
||||
...axes,
|
||||
{ id: newAxisId(), side: DashboardtypesAxisSideDTO.right, series: [] },
|
||||
]);
|
||||
setEditingIndex(axes.length);
|
||||
setUnsavedIndex(axes.length);
|
||||
};
|
||||
|
||||
const beginEdit = (index: number): void => {
|
||||
editSnapshot.current = axes[index] ?? null;
|
||||
setEditingIndex(index);
|
||||
};
|
||||
|
||||
const save = (): void => {
|
||||
setEditingIndex(null);
|
||||
setUnsavedIndex(null);
|
||||
};
|
||||
|
||||
const discardAt = (index: number) => (): void => {
|
||||
if (index === unsavedIndex) {
|
||||
removeAt(index);
|
||||
return;
|
||||
}
|
||||
const original = editSnapshot.current;
|
||||
if (original) {
|
||||
onChange(axes.map((axis, i) => (i === index ? original : axis)));
|
||||
}
|
||||
setEditingIndex(null);
|
||||
};
|
||||
|
||||
const summaryOf = (
|
||||
axis: DashboardtypesSecondaryAxisDTO,
|
||||
index: number,
|
||||
): { title: string; subtitle: string } => {
|
||||
const series = axis.series ?? [];
|
||||
const name = `Secondary axis ${index + 1}`;
|
||||
const seriesText = series.length > 0 ? series.join(', ') : 'no series';
|
||||
return {
|
||||
title: axis.unit ? `${name} · ${axis.unit}` : name,
|
||||
subtitle: `${SIDE_LABEL[axis.side ?? DashboardtypesAxisSideDTO.left]} · ${seriesText}`,
|
||||
};
|
||||
};
|
||||
|
||||
return (
|
||||
<ConfigField
|
||||
label="Secondary axes"
|
||||
help={help}
|
||||
changed={changed}
|
||||
onReset={onReset}
|
||||
>
|
||||
<div className={styles.axisList}>
|
||||
{axes.map((axis, index) => {
|
||||
const boundElsewhere = new Set(
|
||||
axes.flatMap((other, i) => (i === index ? [] : (other.series ?? []))),
|
||||
);
|
||||
const { title, subtitle } = summaryOf(axis, index);
|
||||
const SideIcon =
|
||||
axis.side === DashboardtypesAxisSideDTO.right
|
||||
? ArrowRightToLine
|
||||
: ArrowLeftToLine;
|
||||
return (
|
||||
<ThresholdRowShell
|
||||
key={axis.id}
|
||||
index={index}
|
||||
testIdPrefix="secondary-axis"
|
||||
noun="secondary axis"
|
||||
marker={<SideIcon size={14} aria-hidden />}
|
||||
isEditing={editingIndex === index}
|
||||
isNew={unsavedIndex === index}
|
||||
title={title}
|
||||
subtitle={subtitle}
|
||||
onEdit={(): void => beginEdit(index)}
|
||||
onSave={save}
|
||||
onDiscard={discardAt(index)}
|
||||
onRemove={(): void => removeAt(index)}
|
||||
>
|
||||
<SecondaryAxisFields
|
||||
index={index}
|
||||
axis={axis}
|
||||
seriesKeys={valueColumnKeys.filter((key) => !boundElsewhere.has(key))}
|
||||
hasKnownKeys={valueColumnKeys.length > 0}
|
||||
panelAppearance={panelAppearance}
|
||||
metricUnit={metricUnit}
|
||||
onChange={updateAt(index)}
|
||||
/>
|
||||
</ThresholdRowShell>
|
||||
);
|
||||
})}
|
||||
<Button
|
||||
size="md"
|
||||
type="button"
|
||||
variant="dashed"
|
||||
color="secondary"
|
||||
prefix={<Plus size={14} />}
|
||||
testId="panel-editor-v2-add-axis"
|
||||
disabled={isPercentStacked}
|
||||
disabledTooltip={PERCENT_STACK_HINT}
|
||||
onClick={addAxis}
|
||||
>
|
||||
Add axis
|
||||
</Button>
|
||||
</div>
|
||||
</ConfigField>
|
||||
);
|
||||
}
|
||||
|
||||
export default SecondaryAxesList;
|
||||
@@ -0,0 +1,156 @@
|
||||
import type {
|
||||
DashboardtypesLineInterpolationDTO,
|
||||
DashboardtypesLineStyleDTO,
|
||||
DashboardtypesSecondaryAxisDTO,
|
||||
} from 'api/generated/services/sigNoz.schemas';
|
||||
import YAxisUnitSelector from 'components/YAxisUnitSelector';
|
||||
import { YAxisSource } from 'components/YAxisUnitSelector/types';
|
||||
import type { PanelChartAppearanceSlice } from 'pages/DashboardPage/DashboardContainer/Panels/types/sections';
|
||||
|
||||
import ConfigField from '../../controls/ConfigField/ConfigField';
|
||||
import ConfigInlineField from '../../controls/ConfigInlineField/ConfigInlineField';
|
||||
import ConfigMultiSelect from '../../controls/ConfigMultiSelect/ConfigMultiSelect';
|
||||
import ConfigTiles from '../../controls/ConfigTiles/ConfigTiles';
|
||||
import {
|
||||
LINE_INTERPOLATION_HELP,
|
||||
LINE_INTERPOLATION_OPTIONS,
|
||||
LINE_STYLE_OPTIONS,
|
||||
} from '../ChartAppearanceSection/options';
|
||||
import AxisRangeField from './AxisRangeField';
|
||||
import AxisScaleField from './AxisScaleField';
|
||||
import AxisSideField from './AxisSideField';
|
||||
import {
|
||||
LOG_SCALE_OPTIONS,
|
||||
NO_SERIES_HINT,
|
||||
NO_SERIES_KEYS_HINT,
|
||||
SCALE_HELP,
|
||||
} from './options';
|
||||
|
||||
import styles from './AxesSection.module.scss';
|
||||
|
||||
interface SecondaryAxisFieldsProps {
|
||||
index: number;
|
||||
axis: DashboardtypesSecondaryAxisDTO;
|
||||
/** Column keys this axis may take: the panel's value columns not on another axis. */
|
||||
seriesKeys: string[];
|
||||
/** Whether the panel's queries can name their columns before a run. */
|
||||
hasKnownKeys: boolean;
|
||||
/** The panel's line settings, shown where the axis has no override; unset hides the fields. */
|
||||
panelAppearance?: PanelChartAppearanceSlice;
|
||||
metricUnit?: string;
|
||||
onChange: (next: DashboardtypesSecondaryAxisDTO) => void;
|
||||
}
|
||||
|
||||
/** One secondary axis's edit fields: unit, side, bounds, scale, its series and its line look. */
|
||||
function SecondaryAxisFields({
|
||||
index,
|
||||
axis,
|
||||
seriesKeys,
|
||||
hasKnownKeys,
|
||||
panelAppearance,
|
||||
metricUnit,
|
||||
onChange,
|
||||
}: SecondaryAxisFieldsProps): JSX.Element {
|
||||
const testId = `secondary-axis-${index}`;
|
||||
const series = axis.series ?? [];
|
||||
const appearance = axis.chartAppearance;
|
||||
const lineStyle = appearance?.lineStyle ?? panelAppearance?.lineStyle;
|
||||
const lineInterpolation =
|
||||
appearance?.lineInterpolation ?? panelAppearance?.lineInterpolation;
|
||||
|
||||
// An override equal to the panel's own value is no override: the field inherits again.
|
||||
const setAppearance = (
|
||||
field: 'lineStyle' | 'lineInterpolation',
|
||||
next: DashboardtypesLineStyleDTO | DashboardtypesLineInterpolationDTO,
|
||||
): void => {
|
||||
const rest = { ...appearance };
|
||||
delete rest[field];
|
||||
const chartAppearance =
|
||||
next === panelAppearance?.[field] ? rest : { ...rest, [field]: next };
|
||||
onChange({
|
||||
...axis,
|
||||
chartAppearance:
|
||||
Object.keys(chartAppearance).length > 0 ? chartAppearance : undefined,
|
||||
});
|
||||
};
|
||||
|
||||
return (
|
||||
<div className={styles.fields} data-testid={testId}>
|
||||
<ConfigInlineField label="Unit">
|
||||
<YAxisUnitSelector
|
||||
data-testid={`${testId}-unit`}
|
||||
placeholder="Select unit"
|
||||
source={YAxisSource.DASHBOARDS}
|
||||
value={axis.unit}
|
||||
initialValue={metricUnit}
|
||||
containerClassName={styles.unitSelector}
|
||||
onChange={(unit): void => onChange({ ...axis, unit })}
|
||||
/>
|
||||
</ConfigInlineField>
|
||||
<AxisSideField
|
||||
testId={`${testId}-side`}
|
||||
value={axis.side}
|
||||
onChange={(side): void => onChange({ ...axis, side })}
|
||||
/>
|
||||
<AxisRangeField
|
||||
testIdPrefix={testId}
|
||||
value={axis}
|
||||
onChange={(bounds): void => onChange({ ...axis, ...bounds })}
|
||||
/>
|
||||
<AxisScaleField
|
||||
testId={`${testId}-log-scale`}
|
||||
aria-label={`Secondary axis ${index + 1} scale`}
|
||||
value={axis.isLogScale ? 'log' : 'linear'}
|
||||
items={LOG_SCALE_OPTIONS}
|
||||
help={SCALE_HELP}
|
||||
onChange={(next): void => onChange({ ...axis, isLogScale: next === 'log' })}
|
||||
/>
|
||||
<ConfigInlineField
|
||||
label="Series"
|
||||
help={
|
||||
!hasKnownKeys
|
||||
? NO_SERIES_KEYS_HINT
|
||||
: series.length === 0
|
||||
? NO_SERIES_HINT
|
||||
: undefined
|
||||
}
|
||||
helpTestId={`${testId}-series-hint`}
|
||||
>
|
||||
<ConfigMultiSelect
|
||||
testId={`${testId}-series`}
|
||||
value={series}
|
||||
placeholder="Pick series"
|
||||
items={seriesKeys.map((key) => ({ value: key, label: key }))}
|
||||
onChange={(next): void => onChange({ ...axis, series: next })}
|
||||
/>
|
||||
</ConfigInlineField>
|
||||
{panelAppearance && (
|
||||
<>
|
||||
<ConfigField label="Line">
|
||||
<ConfigTiles
|
||||
testId={`${testId}-line-style`}
|
||||
aria-label={`Secondary axis ${index + 1} line style`}
|
||||
value={lineStyle}
|
||||
items={LINE_STYLE_OPTIONS}
|
||||
onChange={(next): void => setAppearance('lineStyle', next)}
|
||||
/>
|
||||
</ConfigField>
|
||||
<ConfigField
|
||||
label="How points connect"
|
||||
help={lineInterpolation && LINE_INTERPOLATION_HELP[lineInterpolation]}
|
||||
>
|
||||
<ConfigTiles
|
||||
testId={`${testId}-line-interpolation`}
|
||||
aria-label={`Secondary axis ${index + 1}: how points connect`}
|
||||
value={lineInterpolation}
|
||||
items={LINE_INTERPOLATION_OPTIONS}
|
||||
onChange={(next): void => setAppearance('lineInterpolation', next)}
|
||||
/>
|
||||
</ConfigField>
|
||||
</>
|
||||
)}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
export default SecondaryAxisFields;
|
||||
@@ -1,4 +1,12 @@
|
||||
import { DashboardtypesHeatmapYScaleDTO } from 'api/generated/services/sigNoz.schemas';
|
||||
import { useState } from 'react';
|
||||
import {
|
||||
type DashboardtypesAxesDTO,
|
||||
DashboardtypesAxisSideDTO,
|
||||
DashboardtypesHeatmapYScaleDTO,
|
||||
DashboardtypesLineStyleDTO,
|
||||
type DashboardtypesSecondaryAxisDTO,
|
||||
DashboardtypesStackModeDTO,
|
||||
} from 'api/generated/services/sigNoz.schemas';
|
||||
import { render, screen, userEvent } from 'tests/test-utils';
|
||||
|
||||
import AxesSection from '../AxesSection';
|
||||
@@ -147,4 +155,204 @@ describe('AxesSection', () => {
|
||||
screen.queryByText(/The axis always shows at least this range/),
|
||||
).not.toBeInTheDocument();
|
||||
});
|
||||
|
||||
it('writes the primary axis side', async () => {
|
||||
const user = userEvent.setup();
|
||||
const onChange = jest.fn();
|
||||
render(
|
||||
<AxesSection
|
||||
value={{ softMin: 0 }}
|
||||
controls={{ side: true }}
|
||||
onChange={onChange}
|
||||
/>,
|
||||
);
|
||||
|
||||
await user.click(
|
||||
screen.getByTestId('panel-editor-v2-axis-side-button-right'),
|
||||
);
|
||||
|
||||
expect(onChange).toHaveBeenCalledWith({ softMin: 0, side: 'right' });
|
||||
});
|
||||
|
||||
it('adds a secondary axis on the right and removes it again', async () => {
|
||||
const user = userEvent.setup();
|
||||
const onChange = jest.fn();
|
||||
const { rerender } = render(
|
||||
<AxesSection
|
||||
value={{}}
|
||||
controls={{ secondary: true }}
|
||||
valueColumnKeys={['A', 'B']}
|
||||
onChange={onChange}
|
||||
/>,
|
||||
);
|
||||
|
||||
await user.click(screen.getByTestId('panel-editor-v2-add-axis'));
|
||||
|
||||
const added = onChange.mock.calls[0][0] as DashboardtypesAxesDTO;
|
||||
expect(added.secondary).toHaveLength(1);
|
||||
expect(added.secondary?.[0]).toMatchObject({ side: 'right', series: [] });
|
||||
expect(added.secondary?.[0].id).not.toBe('');
|
||||
|
||||
rerender(
|
||||
<AxesSection
|
||||
value={added}
|
||||
controls={{ secondary: true }}
|
||||
valueColumnKeys={['A', 'B']}
|
||||
onChange={onChange}
|
||||
/>,
|
||||
);
|
||||
// A new axis opens in edit mode and shows its fields.
|
||||
expect(screen.getByTestId('secondary-axis-0-series-hint')).toHaveTextContent(
|
||||
'Pick the series to draw on this axis',
|
||||
);
|
||||
|
||||
await user.click(screen.getByTestId('secondary-axis-save-0'));
|
||||
expect(screen.getByTestId('secondary-axis-view-0')).toHaveTextContent(
|
||||
'Right · no series',
|
||||
);
|
||||
|
||||
await user.click(screen.getByTestId('secondary-axis-remove-0'));
|
||||
|
||||
expect(onChange).toHaveBeenLastCalledWith({ secondary: undefined });
|
||||
});
|
||||
|
||||
it('restores an existing axis when its edit is discarded', async () => {
|
||||
const user = userEvent.setup();
|
||||
const onChange = jest.fn();
|
||||
const saved: DashboardtypesSecondaryAxisDTO = {
|
||||
id: 'a',
|
||||
side: DashboardtypesAxisSideDTO.left,
|
||||
series: [],
|
||||
};
|
||||
function Harness(): JSX.Element {
|
||||
const [value, setValue] = useState<DashboardtypesAxesDTO>({
|
||||
secondary: [saved],
|
||||
});
|
||||
return (
|
||||
<AxesSection
|
||||
value={value}
|
||||
controls={{ secondary: true }}
|
||||
onChange={(next): void => {
|
||||
setValue(next);
|
||||
onChange(next);
|
||||
}}
|
||||
/>
|
||||
);
|
||||
}
|
||||
render(<Harness />);
|
||||
|
||||
await user.click(screen.getByTestId('secondary-axis-edit-0'));
|
||||
await user.click(screen.getByTestId('secondary-axis-0-side-button-right'));
|
||||
expect(onChange).toHaveBeenLastCalledWith({
|
||||
secondary: [{ ...saved, side: DashboardtypesAxisSideDTO.right }],
|
||||
});
|
||||
|
||||
await user.click(screen.getByTestId('secondary-axis-discard-0'));
|
||||
|
||||
expect(onChange).toHaveBeenLastCalledWith({ secondary: [saved] });
|
||||
});
|
||||
|
||||
it('removes a new axis that is discarded before saving', async () => {
|
||||
const user = userEvent.setup();
|
||||
const onChange = jest.fn();
|
||||
// The list only shows the rows its value holds, so the harness feeds edits back.
|
||||
function Harness(): JSX.Element {
|
||||
const [value, setValue] = useState<DashboardtypesAxesDTO>({});
|
||||
return (
|
||||
<AxesSection
|
||||
value={value}
|
||||
controls={{ secondary: true }}
|
||||
onChange={(next): void => {
|
||||
setValue(next);
|
||||
onChange(next);
|
||||
}}
|
||||
/>
|
||||
);
|
||||
}
|
||||
render(<Harness />);
|
||||
|
||||
await user.click(screen.getByTestId('panel-editor-v2-add-axis'));
|
||||
expect(screen.getByTestId('secondary-axis-0')).toBeInTheDocument();
|
||||
|
||||
await user.click(screen.getByTestId('secondary-axis-discard-0'));
|
||||
|
||||
expect(onChange).toHaveBeenLastCalledWith({ secondary: undefined });
|
||||
expect(screen.queryByTestId('secondary-axis-0')).not.toBeInTheDocument();
|
||||
});
|
||||
|
||||
it('summarises each saved axis by side and series', () => {
|
||||
render(
|
||||
<AxesSection
|
||||
value={{
|
||||
secondary: [
|
||||
{ id: 'a', series: ['A'] },
|
||||
{ id: 'b', series: [] },
|
||||
],
|
||||
}}
|
||||
controls={{ secondary: true }}
|
||||
valueColumnKeys={['A', 'B']}
|
||||
onChange={jest.fn()}
|
||||
/>,
|
||||
);
|
||||
|
||||
expect(screen.getByTestId('secondary-axis-view-1')).toHaveTextContent(
|
||||
'Left · no series',
|
||||
);
|
||||
expect(screen.getByTestId('secondary-axis-view-0')).toHaveTextContent('A');
|
||||
});
|
||||
|
||||
it('disables adding axes under a percent stack', () => {
|
||||
render(
|
||||
<AxesSection
|
||||
value={{}}
|
||||
controls={{ secondary: true }}
|
||||
stackMode={DashboardtypesStackModeDTO.percent}
|
||||
onChange={jest.fn()}
|
||||
/>,
|
||||
);
|
||||
|
||||
expect(screen.getByTestId('panel-editor-v2-add-axis')).toHaveAttribute(
|
||||
'aria-disabled',
|
||||
'true',
|
||||
);
|
||||
});
|
||||
|
||||
it('writes a line override and drops it again when it matches the panel', async () => {
|
||||
const user = userEvent.setup();
|
||||
const onChange = jest.fn();
|
||||
function Harness(): JSX.Element {
|
||||
const [value, setValue] = useState<DashboardtypesAxesDTO>({
|
||||
secondary: [{ id: 'a', series: [] }],
|
||||
});
|
||||
return (
|
||||
<AxesSection
|
||||
value={value}
|
||||
controls={{ secondary: true, secondaryAppearance: true }}
|
||||
chartAppearance={{ lineStyle: DashboardtypesLineStyleDTO.solid }}
|
||||
onChange={(next): void => {
|
||||
setValue(next);
|
||||
onChange(next);
|
||||
}}
|
||||
/>
|
||||
);
|
||||
}
|
||||
render(<Harness />);
|
||||
await user.click(screen.getByTestId('secondary-axis-edit-0'));
|
||||
|
||||
await user.click(screen.getByTestId('secondary-axis-0-line-style-dashed'));
|
||||
expect(onChange).toHaveBeenLastCalledWith({
|
||||
secondary: [
|
||||
{
|
||||
id: 'a',
|
||||
series: [],
|
||||
chartAppearance: { lineStyle: DashboardtypesLineStyleDTO.dashed },
|
||||
},
|
||||
],
|
||||
});
|
||||
|
||||
await user.click(screen.getByTestId('secondary-axis-0-line-style-solid'));
|
||||
expect(onChange).toHaveBeenLastCalledWith({
|
||||
secondary: [{ id: 'a', series: [], chartAppearance: undefined }],
|
||||
});
|
||||
});
|
||||
});
|
||||
|
||||
@@ -67,3 +67,17 @@ export const RANGE_HELP =
|
||||
'The axis always shows at least this range. Data outside it still stretches the axis.';
|
||||
|
||||
export const RANGE_INVERTED_ERROR = "Min can't be greater than Max.";
|
||||
|
||||
/** Past this many axes the plot has little room left. */
|
||||
export const MAX_READABLE_AXES = 4;
|
||||
|
||||
export const TOO_MANY_AXES_HINT = `More than ${MAX_READABLE_AXES} axes squeeze the plot.`;
|
||||
|
||||
export const PERCENT_STACK_HINT =
|
||||
'A percent stack normalises only the primary axis; series on other axes keep their own values.';
|
||||
|
||||
export const NO_SERIES_HINT =
|
||||
'Pick the series to draw on this axis. Until then it shows only if a threshold uses it.';
|
||||
|
||||
export const NO_SERIES_KEYS_HINT =
|
||||
'Series keys are known once the query runs; a ClickHouse SQL or PromQL query cannot list them here.';
|
||||
|
||||
@@ -13,6 +13,7 @@ import {
|
||||
AnyThreshold,
|
||||
SECTION_METADATA,
|
||||
SectionKind,
|
||||
ThresholdAxisPicker,
|
||||
ThresholdVariant,
|
||||
} from 'pages/DashboardPage/DashboardContainer/Panels/types/sections';
|
||||
import { ThresholdColor } from 'pages/DashboardPage/DashboardContainer/Panels/types/threshold';
|
||||
@@ -22,6 +23,7 @@ import type { SectionEditorContext } from '../../sectionContext';
|
||||
import { resolveColorColumn } from './colorColumn';
|
||||
import ComparisonThresholdRow from './rows/ComparisonThresholdRow';
|
||||
import LabelThresholdRow from './rows/LabelThresholdRow';
|
||||
import type { ThresholdAxisOption } from './rows/shared/ThresholdAxisSelect';
|
||||
import TableThresholdRow from './rows/TableThresholdRow';
|
||||
|
||||
import styles from './ThresholdsSection.module.scss';
|
||||
@@ -47,6 +49,23 @@ const ADD_TESTID: Record<ThresholdVariant, string> = {
|
||||
color: 'panel-editor-v2-add-color-threshold',
|
||||
};
|
||||
|
||||
/** The primary axis first, then each secondary axis named by its unit. */
|
||||
function secondaryAxisOptions(
|
||||
yAxisUnit: string | undefined,
|
||||
secondaryAxes: SectionEditorContext['secondaryAxes'],
|
||||
): ThresholdAxisOption[] {
|
||||
const named = (name: string, unit: string | undefined): string =>
|
||||
unit ? `${name} · ${unit}` : name;
|
||||
return [
|
||||
{ value: '', label: named('Primary', yAxisUnit), unit: yAxisUnit },
|
||||
...(secondaryAxes ?? []).map((axis, index) => ({
|
||||
value: axis.id,
|
||||
label: named(`Secondary axis ${index + 1}`, axis.unit),
|
||||
unit: axis.unit || undefined,
|
||||
})),
|
||||
];
|
||||
}
|
||||
|
||||
// Seed for a freshly-added row, in the shape the variant's editor + spec expect.
|
||||
function defaultThreshold(
|
||||
variant: ThresholdVariant,
|
||||
@@ -88,13 +107,14 @@ function defaultThreshold(
|
||||
type ThresholdsSectionProps = {
|
||||
value: AnyThreshold[] | undefined;
|
||||
/** `variant` picks the row editor + element shape; defaults to `label`. */
|
||||
controls?: { variant?: ThresholdVariant; axis?: boolean };
|
||||
controls?: { variant?: ThresholdVariant; axis?: ThresholdAxisPicker };
|
||||
onChange: (next: AnyThreshold[]) => void;
|
||||
} & Pick<
|
||||
SectionEditorContext,
|
||||
| 'yAxisUnit'
|
||||
| 'tableColumns'
|
||||
| 'axisColumnUnits'
|
||||
| 'secondaryAxes'
|
||||
| 'registerHeaderAction'
|
||||
| 'geoMapPlacement'
|
||||
>;
|
||||
@@ -112,6 +132,7 @@ function ThresholdsSection({
|
||||
yAxisUnit,
|
||||
tableColumns = [],
|
||||
axisColumnUnits,
|
||||
secondaryAxes,
|
||||
registerHeaderAction,
|
||||
geoMapPlacement,
|
||||
}: ThresholdsSectionProps): JSX.Element {
|
||||
@@ -120,7 +141,12 @@ function ThresholdsSection({
|
||||
variant === ThresholdVariant.COLOR
|
||||
? resolveColorColumn(geoMapPlacement, tableColumns)
|
||||
: undefined;
|
||||
const withAxis = !!controls?.axis;
|
||||
const withAxis = controls?.axis === ThresholdAxisPicker.SCATTER;
|
||||
// Offered only once there is an axis to pick besides the primary.
|
||||
const axisOptions =
|
||||
controls?.axis === ThresholdAxisPicker.SECONDARY && secondaryAxes?.length
|
||||
? secondaryAxisOptions(yAxisUnit, secondaryAxes)
|
||||
: undefined;
|
||||
const thresholds = value ?? [];
|
||||
// Which row is being edited, and whether it was just added (so Discard removes it).
|
||||
const [editingIndex, setEditingIndex] = useState<number | null>(null);
|
||||
@@ -237,6 +263,7 @@ function ThresholdsSection({
|
||||
threshold={threshold as DashboardtypesScatterPlotThresholdDTO}
|
||||
showAxis={withAxis}
|
||||
axisUnits={axisColumnUnits}
|
||||
axisOptions={axisOptions}
|
||||
{...common}
|
||||
/>
|
||||
);
|
||||
|
||||
@@ -1,11 +1,12 @@
|
||||
import { useState } from 'react';
|
||||
import type { DashboardtypesThresholdWithLabelDTO } from 'api/generated/services/sigNoz.schemas';
|
||||
import type { DashboardtypesAxisThresholdDTO } from 'api/generated/services/sigNoz.schemas';
|
||||
import { ThresholdAxisPicker } from 'pages/DashboardPage/DashboardContainer/Panels/types/sections';
|
||||
import type { AnyThreshold } from 'pages/DashboardPage/DashboardContainer/Panels/types/sections';
|
||||
import { render, screen, userEvent, waitFor } from 'tests/test-utils';
|
||||
import { render, screen, userEvent, waitFor, within } from 'tests/test-utils';
|
||||
|
||||
import ThresholdsSection from '../ThresholdsSection';
|
||||
|
||||
const THRESHOLDS: DashboardtypesThresholdWithLabelDTO[] = [
|
||||
const THRESHOLDS: DashboardtypesAxisThresholdDTO[] = [
|
||||
{ value: 80, color: '#F5B225', label: 'High', unit: 'percent' },
|
||||
];
|
||||
|
||||
@@ -184,7 +185,7 @@ describe('ThresholdsSection with an axis picker', () => {
|
||||
return (
|
||||
<ThresholdsSection
|
||||
value={value}
|
||||
controls={{ axis: true }}
|
||||
controls={{ axis: ThresholdAxisPicker.SCATTER }}
|
||||
axisColumnUnits={{ x: 'reqps', y: 'ms' }}
|
||||
onChange={(next): void => {
|
||||
setValue(next);
|
||||
@@ -221,4 +222,58 @@ describe('ThresholdsSection with an axis picker', () => {
|
||||
|
||||
expect(screen.queryByTestId('threshold-axis-0')).not.toBeInTheDocument();
|
||||
});
|
||||
|
||||
it('lists the primary and secondary axes and saves the picked id', async () => {
|
||||
const user = userEvent.setup();
|
||||
const onChange = jest.fn();
|
||||
function SecondaryHarness(): JSX.Element {
|
||||
const [value, setValue] = useState<AnyThreshold[]>([]);
|
||||
return (
|
||||
<ThresholdsSection
|
||||
value={value}
|
||||
controls={{ axis: ThresholdAxisPicker.SECONDARY }}
|
||||
yAxisUnit="reqps"
|
||||
secondaryAxes={[{ id: 'lat', unit: 'ms' }]}
|
||||
onChange={(next): void => {
|
||||
setValue(next);
|
||||
onChange(next);
|
||||
}}
|
||||
/>
|
||||
);
|
||||
}
|
||||
render(<SecondaryHarness />);
|
||||
|
||||
await user.click(screen.getByTestId('panel-editor-v2-add-threshold'));
|
||||
expect(onChange).toHaveBeenLastCalledWith([
|
||||
expect.not.objectContaining({ axis: expect.anything() }),
|
||||
]);
|
||||
|
||||
await user.click(
|
||||
within(screen.getByTestId('threshold-axis-0')).getByRole('combobox'),
|
||||
);
|
||||
await user.click(
|
||||
await screen.findByRole('option', { name: 'Secondary axis 1 · ms' }),
|
||||
);
|
||||
await user.click(screen.getByTestId('threshold-save-0'));
|
||||
|
||||
expect(onChange).toHaveBeenLastCalledWith([
|
||||
expect.objectContaining({ axis: 'lat' }),
|
||||
]);
|
||||
});
|
||||
|
||||
it('hides the secondary axis picker while the panel has one axis', async () => {
|
||||
const user = userEvent.setup();
|
||||
render(
|
||||
<ThresholdsSection
|
||||
value={[]}
|
||||
controls={{ axis: ThresholdAxisPicker.SECONDARY }}
|
||||
secondaryAxes={[]}
|
||||
onChange={jest.fn()}
|
||||
/>,
|
||||
);
|
||||
|
||||
await user.click(screen.getByTestId('panel-editor-v2-add-threshold'));
|
||||
|
||||
expect(screen.queryByTestId('threshold-axis-0')).not.toBeInTheDocument();
|
||||
});
|
||||
});
|
||||
|
||||
@@ -9,6 +9,9 @@ import { formatPanelValue } from 'pages/DashboardPage/DashboardContainer/Panels/
|
||||
|
||||
import ThresholdAmountField from './shared/ThresholdAmountField';
|
||||
import ThresholdAxisField from './shared/ThresholdAxisField';
|
||||
import ThresholdAxisSelect, {
|
||||
type ThresholdAxisOption,
|
||||
} from './shared/ThresholdAxisSelect';
|
||||
import ThresholdColorField from './shared/ThresholdColorField';
|
||||
import ThresholdMarker from './shared/ThresholdMarker';
|
||||
import ThresholdRowShell from './shared/ThresholdRowShell';
|
||||
@@ -16,17 +19,21 @@ import { useThresholdDraft } from './shared/useThresholdDraft';
|
||||
|
||||
import styles from '../ThresholdsSection.module.scss';
|
||||
|
||||
/** `axis` is set only where the row picks one (Scatter Plot). */
|
||||
type LabelThreshold = DashboardtypesScatterPlotThresholdDTO;
|
||||
/** `axis` is Scatter Plot's x/y, or a secondary axis id on the time charts. */
|
||||
type LabelThreshold = Omit<DashboardtypesScatterPlotThresholdDTO, 'axis'> & {
|
||||
axis?: string;
|
||||
};
|
||||
|
||||
interface LabelThresholdRowProps {
|
||||
index: number;
|
||||
threshold: LabelThreshold;
|
||||
/** Panel formatting unit — scopes the unit picker to its category (V1 parity). */
|
||||
yAxisUnit?: string;
|
||||
/** Shows the axis picker; the unit picker then scopes to the picked axis's unit. */
|
||||
/** Shows the x/y picker; the unit picker then scopes to the picked axis's unit. */
|
||||
showAxis?: boolean;
|
||||
axisUnits?: { x?: string; y?: string };
|
||||
/** The primary and secondary axes to pick from; set only when there is a choice. */
|
||||
axisOptions?: ThresholdAxisOption[];
|
||||
isEditing: boolean;
|
||||
isNew: boolean;
|
||||
onEdit: () => void;
|
||||
@@ -43,6 +50,7 @@ function LabelThresholdRow({
|
||||
yAxisUnit,
|
||||
showAxis,
|
||||
axisUnits,
|
||||
axisOptions,
|
||||
isEditing,
|
||||
isNew,
|
||||
onEdit,
|
||||
@@ -63,15 +71,20 @@ function LabelThresholdRow({
|
||||
}, [onSave, draft]);
|
||||
|
||||
const draftAxis = draft.axis ?? DashboardtypesThresholdAxisDTO.y;
|
||||
const scopeUnit = showAxis ? axisUnits?.[draftAxis] : yAxisUnit;
|
||||
const subtitle = showAxis
|
||||
? [
|
||||
`${(threshold.axis ?? DashboardtypesThresholdAxisDTO.y).toUpperCase()} axis`,
|
||||
threshold.label,
|
||||
]
|
||||
.filter(Boolean)
|
||||
.join(' · ')
|
||||
: threshold.label;
|
||||
const draftAxisOption = axisOptions?.find(
|
||||
(option) => option.value === (draft.axis ?? ''),
|
||||
);
|
||||
const scopeUnit = axisOptions
|
||||
? draftAxisOption?.unit
|
||||
: showAxis
|
||||
? axisUnits?.[draftAxis as DashboardtypesThresholdAxisDTO]
|
||||
: yAxisUnit;
|
||||
const axisName = axisOptions
|
||||
? axisOptions.find((option) => option.value === (threshold.axis ?? ''))?.label
|
||||
: showAxis
|
||||
? `${(threshold.axis ?? DashboardtypesThresholdAxisDTO.y).toUpperCase()} axis`
|
||||
: undefined;
|
||||
const subtitle = [axisName, threshold.label].filter(Boolean).join(' · ');
|
||||
|
||||
return (
|
||||
<ThresholdRowShell
|
||||
@@ -90,10 +103,20 @@ function LabelThresholdRow({
|
||||
{showAxis && (
|
||||
<ThresholdAxisField
|
||||
testId={`threshold-axis-${index}`}
|
||||
value={draftAxis}
|
||||
value={draftAxis as DashboardtypesThresholdAxisDTO}
|
||||
onChange={(axis): void => setDraft((d) => ({ ...d, axis }))}
|
||||
/>
|
||||
)}
|
||||
{axisOptions && (
|
||||
<ThresholdAxisSelect
|
||||
testId={`threshold-axis-${index}`}
|
||||
value={draft.axis ?? ''}
|
||||
options={axisOptions}
|
||||
onChange={(axis): void =>
|
||||
setDraft((d) => (axis ? { ...d, axis } : { ...d, axis: undefined }))
|
||||
}
|
||||
/>
|
||||
)}
|
||||
<ThresholdAmountField
|
||||
label="Draw a line at"
|
||||
testIdPrefix="threshold"
|
||||
@@ -102,7 +125,9 @@ function LabelThresholdRow({
|
||||
onValueChange={setValue}
|
||||
unit={draft.unit}
|
||||
scopeUnit={scopeUnit}
|
||||
scopeLabel={`${showAxis ? draftAxis : 'y'}-axis unit`}
|
||||
scopeLabel={
|
||||
axisOptions ? 'axis unit' : `${showAxis ? draftAxis : 'y'}-axis unit`
|
||||
}
|
||||
onUnitChange={(unit): void => setDraft((d) => ({ ...d, unit }))}
|
||||
/>
|
||||
<ThresholdColorField
|
||||
|
||||
@@ -0,0 +1,49 @@
|
||||
import { Typography } from '@signozhq/ui/typography';
|
||||
|
||||
import ConfigSelect from '../../../../controls/ConfigSelect/ConfigSelect';
|
||||
|
||||
import styles from '../../ThresholdsSection.module.scss';
|
||||
|
||||
/** One Y axis a threshold can sit on: `''` is the primary axis. */
|
||||
export interface ThresholdAxisOption {
|
||||
value: string;
|
||||
label: string;
|
||||
unit?: string;
|
||||
}
|
||||
|
||||
interface ThresholdAxisSelectProps {
|
||||
testId: string;
|
||||
value: string;
|
||||
options: ThresholdAxisOption[];
|
||||
onChange: (axis: string) => void;
|
||||
}
|
||||
|
||||
function ThresholdAxisSelect({
|
||||
testId,
|
||||
value,
|
||||
options,
|
||||
onChange,
|
||||
}: ThresholdAxisSelectProps): JSX.Element {
|
||||
return (
|
||||
<div className={styles.field}>
|
||||
<Typography
|
||||
variant="paragraph"
|
||||
size="base"
|
||||
weight="regular"
|
||||
color="secondary"
|
||||
as="span"
|
||||
textOverflow="wrap"
|
||||
>
|
||||
Axis
|
||||
</Typography>
|
||||
<ConfigSelect
|
||||
testId={testId}
|
||||
value={value}
|
||||
items={options.map(({ value: axis, label }) => ({ value: axis, label }))}
|
||||
onChange={onChange}
|
||||
/>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
export default ThresholdAxisSelect;
|
||||
@@ -9,6 +9,8 @@ interface ThresholdRowShellProps {
|
||||
index: number;
|
||||
/** testId prefix per variant: `threshold` | `comparison-threshold` | `table-threshold`. */
|
||||
testIdPrefix: string;
|
||||
/** What a row is, in the headings and button labels. */
|
||||
noun?: string;
|
||||
marker: ReactNode;
|
||||
isEditing: boolean;
|
||||
isNew: boolean;
|
||||
@@ -23,13 +25,15 @@ interface ThresholdRowShellProps {
|
||||
}
|
||||
|
||||
/**
|
||||
* Shared chrome for a threshold row's V1-style view/edit modes: the view summary with
|
||||
* Shared chrome for a list row's V1-style view/edit modes: the view summary with
|
||||
* Edit/Delete, and the edit form's Discard/Save actions. Each variant supplies its own
|
||||
* `summary` and field `children`; everything else (layout, buttons, testIds) is shared.
|
||||
* Secondary axes reuse it with their own `noun`.
|
||||
*/
|
||||
function ThresholdRowShell({
|
||||
index,
|
||||
testIdPrefix,
|
||||
noun = 'threshold',
|
||||
marker,
|
||||
isEditing,
|
||||
isNew,
|
||||
@@ -58,7 +62,7 @@ function ThresholdRowShell({
|
||||
color="secondary"
|
||||
size="sm"
|
||||
icon
|
||||
aria-label={`Edit threshold ${index + 1}`}
|
||||
aria-label={`Edit ${noun} ${index + 1}`}
|
||||
testId={`${testIdPrefix}-edit-${index}`}
|
||||
onClick={onEdit}
|
||||
>
|
||||
@@ -70,7 +74,7 @@ function ThresholdRowShell({
|
||||
color="danger"
|
||||
size="sm"
|
||||
icon
|
||||
aria-label={`Remove threshold ${index + 1}`}
|
||||
aria-label={`Remove ${noun} ${index + 1}`}
|
||||
testId={`${testIdPrefix}-remove-${index}`}
|
||||
onClick={onRemove}
|
||||
>
|
||||
@@ -90,7 +94,7 @@ function ThresholdRowShell({
|
||||
as="span"
|
||||
textOverflow="wrap"
|
||||
>
|
||||
{isNew ? 'New threshold' : 'Edit threshold'}
|
||||
{`${isNew ? 'New' : 'Edit'} ${noun}`}
|
||||
</Typography>
|
||||
{children}
|
||||
|
||||
|
||||
@@ -13,6 +13,7 @@ import { getActiveBuilder } from 'lib/query/builderSlot';
|
||||
import { isEqual } from 'lodash-es';
|
||||
import type { Query } from 'types/api/queryBuilder/queryBuilderData';
|
||||
|
||||
import { pruneSecondaryAxisSeries } from '../../Panels/utils/axes/reconcileAxes';
|
||||
import { toQueryEnvelopes } from '../../queryV5/buildQueryRangeRequest';
|
||||
import { fromPerses, toPerses } from '../../queryV5/persesQueryAdapters';
|
||||
|
||||
@@ -182,11 +183,14 @@ export function usePanelEditorQuerySync({
|
||||
[currentQuery, panelType, baselineEnvelopes],
|
||||
);
|
||||
|
||||
// Series keys the edited queries no longer produce leave their secondary axis here.
|
||||
const buildSaveSpec = useCallback(
|
||||
(spec: DashboardtypesPanelSpecDTO): DashboardtypesPanelSpecDTO =>
|
||||
isQueryDirty || alwaysSerializeQuery
|
||||
? { ...spec, queries: toPerses(currentQuery, panelType) }
|
||||
: spec,
|
||||
pruneSecondaryAxisSeries(
|
||||
isQueryDirty || alwaysSerializeQuery
|
||||
? { ...spec, queries: toPerses(currentQuery, panelType) }
|
||||
: spec,
|
||||
),
|
||||
[isQueryDirty, alwaysSerializeQuery, currentQuery, panelType],
|
||||
);
|
||||
|
||||
|
||||
@@ -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(
|
||||
|
||||
@@ -1,6 +1,7 @@
|
||||
import { resolveTimeSeriesLegendSeries } from '../../utils/legendSeries';
|
||||
import {
|
||||
SectionKind,
|
||||
ThresholdAxisPicker,
|
||||
ThresholdVariant,
|
||||
type SectionConfig,
|
||||
} from '../../types/sections';
|
||||
@@ -18,7 +19,16 @@ export const sections: SectionConfig[] = [
|
||||
},
|
||||
},
|
||||
{ kind: SectionKind.Formatting, controls: { unit: true, decimals: true } },
|
||||
{ kind: SectionKind.Axes, controls: { minMax: true, logScale: true } },
|
||||
{
|
||||
kind: SectionKind.Axes,
|
||||
controls: {
|
||||
minMax: true,
|
||||
logScale: true,
|
||||
side: true,
|
||||
secondary: true,
|
||||
secondaryAppearance: true,
|
||||
},
|
||||
},
|
||||
{
|
||||
kind: SectionKind.Legend,
|
||||
controls: { position: true, colors: resolveTimeSeriesLegendSeries },
|
||||
@@ -36,7 +46,10 @@ export const sections: SectionConfig[] = [
|
||||
},
|
||||
{
|
||||
kind: SectionKind.Thresholds,
|
||||
controls: { variant: ThresholdVariant.LABEL },
|
||||
controls: {
|
||||
variant: ThresholdVariant.LABEL,
|
||||
axis: ThresholdAxisPicker.SECONDARY,
|
||||
},
|
||||
},
|
||||
{ kind: SectionKind.ContextLinks },
|
||||
];
|
||||
|
||||
@@ -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,
|
||||
|
||||
@@ -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(
|
||||
|
||||
@@ -1,6 +1,7 @@
|
||||
import { resolveTimeSeriesLegendSeries } from '../../utils/legendSeries';
|
||||
import {
|
||||
SectionKind,
|
||||
ThresholdAxisPicker,
|
||||
ThresholdVariant,
|
||||
type SectionConfig,
|
||||
} from '../../types/sections';
|
||||
@@ -13,14 +14,25 @@ export const sections: SectionConfig[] = [
|
||||
controls: { switchPanelKind: true, timePreference: true, stacking: true },
|
||||
},
|
||||
{ kind: SectionKind.Formatting, controls: { unit: true, decimals: true } },
|
||||
{ kind: SectionKind.Axes, controls: { minMax: true, logScale: true } },
|
||||
{
|
||||
kind: SectionKind.Axes,
|
||||
controls: {
|
||||
minMax: true,
|
||||
logScale: true,
|
||||
side: true,
|
||||
secondary: true,
|
||||
},
|
||||
},
|
||||
{
|
||||
kind: SectionKind.Legend,
|
||||
controls: { position: true, colors: resolveTimeSeriesLegendSeries },
|
||||
},
|
||||
{
|
||||
kind: SectionKind.Thresholds,
|
||||
controls: { variant: ThresholdVariant.LABEL },
|
||||
controls: {
|
||||
variant: ThresholdVariant.LABEL,
|
||||
axis: ThresholdAxisPicker.SECONDARY,
|
||||
},
|
||||
},
|
||||
{ kind: SectionKind.ContextLinks },
|
||||
];
|
||||
|
||||
@@ -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,
|
||||
|
||||
@@ -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({
|
||||
|
||||
@@ -1,6 +1,7 @@
|
||||
import { resolveScatterLegendSeries } from '../../utils/legendSeries';
|
||||
import {
|
||||
SectionKind,
|
||||
ThresholdAxisPicker,
|
||||
ThresholdVariant,
|
||||
type SectionConfig,
|
||||
} from '../../types/sections';
|
||||
@@ -23,7 +24,10 @@ export const sections: SectionConfig[] = [
|
||||
},
|
||||
{
|
||||
kind: SectionKind.Thresholds,
|
||||
controls: { variant: ThresholdVariant.LABEL, axis: true },
|
||||
controls: {
|
||||
variant: ThresholdVariant.LABEL,
|
||||
axis: ThresholdAxisPicker.SCATTER,
|
||||
},
|
||||
},
|
||||
{ kind: SectionKind.ContextLinks },
|
||||
];
|
||||
|
||||
@@ -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,
|
||||
|
||||
@@ -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(
|
||||
|
||||
@@ -1,6 +1,7 @@
|
||||
import { resolveTimeSeriesLegendSeries } from '../../utils/legendSeries';
|
||||
import {
|
||||
SectionKind,
|
||||
ThresholdAxisPicker,
|
||||
ThresholdVariant,
|
||||
type SectionConfig,
|
||||
} from '../../types/sections';
|
||||
@@ -11,7 +12,16 @@ export const sections: SectionConfig[] = [
|
||||
controls: { switchPanelKind: true, timePreference: true, fillSpans: true },
|
||||
},
|
||||
{ kind: SectionKind.Formatting, controls: { unit: true, decimals: true } },
|
||||
{ kind: SectionKind.Axes, controls: { minMax: true, logScale: true } },
|
||||
{
|
||||
kind: SectionKind.Axes,
|
||||
controls: {
|
||||
minMax: true,
|
||||
logScale: true,
|
||||
side: true,
|
||||
secondary: true,
|
||||
secondaryAppearance: true,
|
||||
},
|
||||
},
|
||||
{
|
||||
kind: SectionKind.Legend,
|
||||
controls: { position: true, colors: resolveTimeSeriesLegendSeries },
|
||||
@@ -28,7 +38,10 @@ export const sections: SectionConfig[] = [
|
||||
},
|
||||
{
|
||||
kind: SectionKind.Thresholds,
|
||||
controls: { variant: ThresholdVariant.LABEL },
|
||||
controls: {
|
||||
variant: ThresholdVariant.LABEL,
|
||||
axis: ThresholdAxisPicker.SECONDARY,
|
||||
},
|
||||
},
|
||||
{ kind: SectionKind.ContextLinks },
|
||||
];
|
||||
|
||||
@@ -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);
|
||||
});
|
||||
});
|
||||
|
||||
@@ -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,
|
||||
|
||||
@@ -26,7 +26,7 @@ import type {
|
||||
DashboardtypesTableFormattingDTO,
|
||||
DashboardtypesTableThresholdDTO,
|
||||
DashboardtypesTextPresentationDTO,
|
||||
DashboardtypesThresholdWithLabelDTO,
|
||||
DashboardtypesAxisThresholdDTO,
|
||||
DashboardtypesTimePreferenceDTO,
|
||||
DashboardtypesTopListAppearanceDTO,
|
||||
TelemetrytypesTelemetryFieldKeyDTO,
|
||||
@@ -99,9 +99,17 @@ export enum ThresholdVariant {
|
||||
COLOR = 'color',
|
||||
}
|
||||
|
||||
/** Which axes a `label` threshold can be placed on. */
|
||||
export enum ThresholdAxisPicker {
|
||||
/** Scatter Plot's x or y. */
|
||||
SCATTER = 'scatter',
|
||||
/** The primary axis or one of `axes.secondary[]`, by id. */
|
||||
SECONDARY = 'secondary',
|
||||
}
|
||||
|
||||
/** Union of every threshold element shape stored under `plugin.spec.thresholds`. */
|
||||
export type AnyThreshold =
|
||||
| DashboardtypesThresholdWithLabelDTO
|
||||
| DashboardtypesAxisThresholdDTO
|
||||
| DashboardtypesScatterPlotThresholdDTO
|
||||
| DashboardtypesComparisonThresholdDTO
|
||||
| DashboardtypesTableThresholdDTO
|
||||
@@ -187,10 +195,15 @@ export interface SectionControls {
|
||||
};
|
||||
// minMax → softMin/softMax; y → the heatmap's bucket-axis scale, whose domain
|
||||
// comes from the response and so takes no soft bounds.
|
||||
// side → the primary axis's edge; secondary → the `axes.secondary[]` list, whose
|
||||
// line style and interpolation fields show only with `secondaryAppearance`.
|
||||
[SectionKind.Axes]: {
|
||||
minMax?: boolean;
|
||||
logScale?: boolean;
|
||||
y?: boolean;
|
||||
side?: boolean;
|
||||
secondary?: boolean;
|
||||
secondaryAppearance?: boolean;
|
||||
};
|
||||
[SectionKind.Legend]: {
|
||||
position?: boolean;
|
||||
@@ -236,8 +249,11 @@ export interface SectionControls {
|
||||
fillSpans?: boolean;
|
||||
};
|
||||
// Editor discriminator (not a spec field): which threshold variant a kind edits.
|
||||
// axis → a `label` threshold picks the axis it marks (Scatter Plot).
|
||||
[SectionKind.Thresholds]: { variant?: ThresholdVariant; axis?: boolean };
|
||||
// axis → a `label` threshold picks the axis it marks.
|
||||
[SectionKind.Thresholds]: {
|
||||
variant?: ThresholdVariant;
|
||||
axis?: ThresholdAxisPicker;
|
||||
};
|
||||
[SectionKind.Appearance]: {
|
||||
showRank?: boolean;
|
||||
showShare?: boolean;
|
||||
|
||||
@@ -22,6 +22,7 @@ import { sections as listSections } from '../../kinds/ListPanel/sections';
|
||||
import { sections as timeSeriesSections } from '../../kinds/TimeSeriesPanel/sections';
|
||||
import {
|
||||
SectionKind,
|
||||
ThresholdAxisPicker,
|
||||
ThresholdVariant,
|
||||
type SectionConfig,
|
||||
} from '../../types/sections';
|
||||
@@ -683,7 +684,7 @@ describe('buildPluginSpec', () => {
|
||||
variant: ThresholdVariant | undefined,
|
||||
thresholds: unknown[],
|
||||
queries: unknown[] = [],
|
||||
axis?: boolean,
|
||||
axis?: ThresholdAxisPicker,
|
||||
): unknown {
|
||||
const sections: SectionConfig[] = [
|
||||
{ kind: SectionKind.Thresholds, controls: { variant, axis } },
|
||||
@@ -804,7 +805,7 @@ describe('buildPluginSpec', () => {
|
||||
{ value: 80, color: '#F1575F' },
|
||||
],
|
||||
[],
|
||||
true,
|
||||
ThresholdAxisPicker.SCATTER,
|
||||
),
|
||||
).toStrictEqual([
|
||||
{ value: 5, color: '#F1575F', axis: DashboardtypesThresholdAxisDTO.x },
|
||||
|
||||
@@ -0,0 +1,66 @@
|
||||
import {
|
||||
type DashboardtypesPanelSpecDTO,
|
||||
DashboardtypesPanelPluginVariantGithubComSigNozSignozPkgTypesDashboardtypesTimeSeriesPanelSpecDTOKind as TimeSeriesKind,
|
||||
} from 'api/generated/services/sigNoz.schemas';
|
||||
import { getQueryColumnKeys } from 'pages/DashboardPage/DashboardContainer/Panels/utils/getQueryColumnKeys';
|
||||
|
||||
import {
|
||||
dropDanglingThresholdAxes,
|
||||
pruneSecondaryAxisSeries,
|
||||
} from '../reconcileAxes';
|
||||
|
||||
jest.mock(
|
||||
'pages/DashboardPage/DashboardContainer/Panels/utils/getQueryColumnKeys',
|
||||
() => ({ getQueryColumnKeys: jest.fn() }),
|
||||
);
|
||||
|
||||
const specWithAxes = (series: string[]): DashboardtypesPanelSpecDTO =>
|
||||
({
|
||||
queries: [],
|
||||
plugin: {
|
||||
kind: TimeSeriesKind['signoz/TimeSeriesPanel'],
|
||||
spec: { axes: { secondary: [{ id: 'lat', series }] } },
|
||||
},
|
||||
}) as unknown as DashboardtypesPanelSpecDTO;
|
||||
|
||||
describe('dropDanglingThresholdAxes', () => {
|
||||
it('moves a threshold naming a removed axis to the primary axis and leaves the rest', () => {
|
||||
expect(
|
||||
dropDanglingThresholdAxes(
|
||||
[
|
||||
{ value: 1, color: 'red', axis: 'lat' },
|
||||
{ value: 2, color: 'red', axis: 'gone' },
|
||||
{ value: 3, color: 'red' },
|
||||
],
|
||||
{ secondary: [{ id: 'lat' }] },
|
||||
),
|
||||
).toStrictEqual([
|
||||
{ value: 1, color: 'red', axis: 'lat' },
|
||||
{ value: 2, color: 'red', axis: '' },
|
||||
{ value: 3, color: 'red' },
|
||||
]);
|
||||
});
|
||||
});
|
||||
|
||||
describe('pruneSecondaryAxisSeries', () => {
|
||||
it('drops series keys the queries no longer produce', () => {
|
||||
jest.mocked(getQueryColumnKeys).mockReturnValue({
|
||||
valueKeys: new Set(['A']),
|
||||
groupKeys: new Set(),
|
||||
});
|
||||
|
||||
const pruned = pruneSecondaryAxisSeries(specWithAxes(['A', 'B']));
|
||||
|
||||
expect(
|
||||
(pruned.plugin.spec as { axes: { secondary: { series: string[] }[] } }).axes
|
||||
.secondary[0].series,
|
||||
).toStrictEqual(['A']);
|
||||
});
|
||||
|
||||
it('keeps every key when a query cannot name its columns before a run', () => {
|
||||
jest.mocked(getQueryColumnKeys).mockReturnValue(null);
|
||||
const spec = specWithAxes(['A', 'B']);
|
||||
|
||||
expect(pruneSecondaryAxisSeries(spec)).toBe(spec);
|
||||
});
|
||||
});
|
||||
@@ -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',
|
||||
);
|
||||
});
|
||||
});
|
||||
@@ -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']);
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,52 @@
|
||||
import type {
|
||||
DashboardtypesAxesDTO,
|
||||
DashboardtypesAxisThresholdDTO,
|
||||
DashboardtypesPanelSpecDTO,
|
||||
} from 'api/generated/services/sigNoz.schemas';
|
||||
|
||||
import { getQueryColumnKeys } from '../getQueryColumnKeys';
|
||||
|
||||
/** A threshold naming an axis that no longer exists moves to the primary axis. */
|
||||
export function dropDanglingThresholdAxes(
|
||||
thresholds: DashboardtypesAxisThresholdDTO[] | null | undefined,
|
||||
axes: DashboardtypesAxesDTO | undefined,
|
||||
): DashboardtypesAxisThresholdDTO[] | null | undefined {
|
||||
if (!thresholds?.length) {
|
||||
return thresholds;
|
||||
}
|
||||
const ids = new Set((axes?.secondary ?? []).map((axis) => axis.id));
|
||||
return thresholds.map((threshold) =>
|
||||
threshold.axis && !ids.has(threshold.axis)
|
||||
? { ...threshold, axis: '' }
|
||||
: threshold,
|
||||
);
|
||||
}
|
||||
|
||||
/**
|
||||
* Drops series keys the queries no longer produce from every secondary axis. Keys are
|
||||
* left alone when a ClickHouse SQL or PromQL query makes them unknowable before a run.
|
||||
*/
|
||||
export function pruneSecondaryAxisSeries(
|
||||
spec: DashboardtypesPanelSpecDTO,
|
||||
): DashboardtypesPanelSpecDTO {
|
||||
const pluginSpec = spec.plugin.spec as { axes?: DashboardtypesAxesDTO };
|
||||
const secondary = pluginSpec.axes?.secondary;
|
||||
if (!secondary?.length) {
|
||||
return spec;
|
||||
}
|
||||
const columnKeys = getQueryColumnKeys(spec.queries ?? []);
|
||||
if (!columnKeys) {
|
||||
return spec;
|
||||
}
|
||||
const pruned = secondary.map((axis) => ({
|
||||
...axis,
|
||||
series: (axis.series ?? []).filter((key) => columnKeys.valueKeys.has(key)),
|
||||
}));
|
||||
return {
|
||||
...spec,
|
||||
plugin: {
|
||||
...spec.plugin,
|
||||
spec: { ...pluginSpec, axes: { ...pluginSpec.axes, secondary: pruned } },
|
||||
} as DashboardtypesPanelSpecDTO['plugin'],
|
||||
};
|
||||
}
|
||||
@@ -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;
|
||||
}
|
||||
@@ -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,
|
||||
});
|
||||
}
|
||||
@@ -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
|
||||
|
||||
@@ -27,6 +27,7 @@ import {
|
||||
type SectionControls,
|
||||
SectionKind,
|
||||
type SectionSpecMap,
|
||||
ThresholdAxisPicker,
|
||||
ThresholdVariant,
|
||||
} from '../types/sections';
|
||||
import { DEFAULT_BAR_COLOR } from '../../PanelEditor/ConfigPane/sections/AppearanceSection/barColorOptions';
|
||||
@@ -70,14 +71,16 @@ interface AnyThresholdFields {
|
||||
format?: DashboardtypesThresholdFormatDTO;
|
||||
columnName?: string;
|
||||
label?: string;
|
||||
axis?: DashboardtypesThresholdAxisDTO;
|
||||
/** Scatter's x/y, or a secondary axis id. */
|
||||
axis?: string;
|
||||
}
|
||||
|
||||
/** Remaps a threshold to the target variant, seeding the fields that variant needs to stay functional. */
|
||||
function toThresholdVariant(
|
||||
source: AnyThresholdFields,
|
||||
variant: ThresholdVariant,
|
||||
withAxis: boolean,
|
||||
axisPicker: ThresholdAxisPicker | undefined,
|
||||
secondaryAxisIds: Set<string>,
|
||||
defaultColumnName?: string,
|
||||
): AnyThreshold {
|
||||
const core = {
|
||||
@@ -106,10 +109,24 @@ function toThresholdVariant(
|
||||
columnName: source.columnName || defaultColumnName || '',
|
||||
};
|
||||
}
|
||||
const label = source.label !== undefined && { label: source.label };
|
||||
if (axisPicker === ThresholdAxisPicker.SCATTER) {
|
||||
return {
|
||||
...core,
|
||||
...label,
|
||||
axis:
|
||||
source.axis === DashboardtypesThresholdAxisDTO.x
|
||||
? DashboardtypesThresholdAxisDTO.x
|
||||
: DashboardtypesThresholdAxisDTO.y,
|
||||
};
|
||||
}
|
||||
// A secondary id carries only to a kind that keeps that axis; anything else is primary.
|
||||
const axis =
|
||||
source.axis && secondaryAxisIds.has(source.axis) ? source.axis : '';
|
||||
return {
|
||||
...core,
|
||||
...(source.label !== undefined && { label: source.label }),
|
||||
...(withAxis && { axis: source.axis ?? DashboardtypesThresholdAxisDTO.y }),
|
||||
...label,
|
||||
...(axisPicker === ThresholdAxisPicker.SECONDARY && axis && { axis }),
|
||||
};
|
||||
}
|
||||
|
||||
@@ -292,6 +309,11 @@ const SECTION_SEEDS: SectionSeeds = {
|
||||
typeof old.softMax === 'number' && { softMax: old.softMax }),
|
||||
...(controls.logScale &&
|
||||
old.isLogScale !== undefined && { isLogScale: old.isLogScale }),
|
||||
...(controls.side && old.side && { side: old.side }),
|
||||
// The appearance override rides along even where the kind ignores it
|
||||
// (Bar), so switching back restores it.
|
||||
...(controls.secondary &&
|
||||
old.secondary?.length && { secondary: old.secondary }),
|
||||
// Seeded so the control opens on the axis being drawn.
|
||||
...(controls.y && {
|
||||
y: { scale: old.y?.scale ?? DashboardtypesHeatmapYScaleDTO.auto },
|
||||
@@ -414,15 +436,25 @@ const SECTION_SEEDS: SectionSeeds = {
|
||||
variant === ThresholdVariant.TABLE
|
||||
? getTableColumnKeys(oldSpec?.queries ?? [])[0]
|
||||
: undefined;
|
||||
const withAxis = !!controls.axis;
|
||||
// Only a kind that picks the axis can place an x threshold.
|
||||
const axisPicker = controls.axis;
|
||||
const secondaryAxisIds = new Set(
|
||||
(oldPluginSpec?.axes?.secondary ?? []).map((axis) => axis.id),
|
||||
);
|
||||
// Only Scatter can place an x threshold.
|
||||
const mapped = (old as AnyThresholdFields[])
|
||||
.filter(
|
||||
(threshold) =>
|
||||
withAxis || threshold.axis !== DashboardtypesThresholdAxisDTO.x,
|
||||
axisPicker === ThresholdAxisPicker.SCATTER ||
|
||||
threshold.axis !== DashboardtypesThresholdAxisDTO.x,
|
||||
)
|
||||
.map((threshold) =>
|
||||
toThresholdVariant(threshold, variant, withAxis, defaultColumnName),
|
||||
toThresholdVariant(
|
||||
threshold,
|
||||
variant,
|
||||
axisPicker,
|
||||
secondaryAxisIds,
|
||||
defaultColumnName,
|
||||
),
|
||||
);
|
||||
return variant === ThresholdVariant.TABLE
|
||||
? mapped.filter((t) => (t as { columnName?: string }).columnName)
|
||||
|
||||
@@ -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;
|
||||
}
|
||||
|
||||
@@ -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]}`)
|
||||
|
||||
@@ -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,
|
||||
});
|
||||
}),
|
||||
),
|
||||
|
||||
@@ -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' },
|
||||
|
||||
@@ -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;
|
||||
|
||||
@@ -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),
|
||||
};
|
||||
}
|
||||
};
|
||||
|
||||
@@ -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,
|
||||
|
||||
@@ -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);
|
||||
}
|
||||
};
|
||||
|
||||
@@ -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;
|
||||
}
|
||||
|
||||
@@ -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);
|
||||
};
|
||||
|
||||
@@ -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);
|
||||
|
||||
19
tests/e2e/drivers/dashboard-spec.types.ts
generated
19
tests/e2e/drivers/dashboard-spec.types.ts
generated
@@ -49,9 +49,25 @@ export interface Query {
|
||||
|
||||
// ─── Panel plugin specs ──────────────────────────────────────────────────
|
||||
|
||||
export interface SecondaryAxis {
|
||||
id: string;
|
||||
unit?: string;
|
||||
side?: 'left' | 'right';
|
||||
softMin?: number | null;
|
||||
softMax?: number | null;
|
||||
isLogScale?: boolean;
|
||||
series?: string[] | null;
|
||||
chartAppearance?: {
|
||||
lineStyle?: 'solid' | 'dashed';
|
||||
lineInterpolation?: 'linear' | 'spline' | 'step_before' | 'step_after';
|
||||
};
|
||||
}
|
||||
|
||||
export interface Threshold {
|
||||
value: number;
|
||||
color: string;
|
||||
/** Scatter's `x`/`y`, or a secondary axis id on the time charts; empty is primary. */
|
||||
axis?: string;
|
||||
operator?:
|
||||
| 'above'
|
||||
| 'aboveOrEqual'
|
||||
@@ -119,6 +135,9 @@ export interface PanelPluginSpec {
|
||||
softMin?: number | null;
|
||||
softMax?: number | null;
|
||||
isLogScale?: boolean;
|
||||
/** Time Series, Bar and Area: the primary axis edge and the further axes. */
|
||||
side?: 'left' | 'right';
|
||||
secondary?: SecondaryAxis[];
|
||||
/** Heatmap only, and its only axis key. */
|
||||
y?: { scale: 'auto' | 'linear' | 'log' | 'symlog' };
|
||||
};
|
||||
|
||||
50
tests/e2e/drivers/panel-config.ts
generated
50
tests/e2e/drivers/panel-config.ts
generated
@@ -11,8 +11,34 @@ import { getViaApi } from './dashboards';
|
||||
import { driver } from './kit';
|
||||
import { test as editorTest } from './panel-editor';
|
||||
|
||||
// The panel editor's config editors with UI of their own: thresholds and
|
||||
// context links.
|
||||
// The panel editor's config editors with UI of their own: thresholds,
|
||||
// secondary axes and context links.
|
||||
|
||||
/**
|
||||
* One `axes.secondary` entry, by its position in the list. A new row opens in edit
|
||||
* mode; `save` collapses it to its view row, where `edit` and `remove` live.
|
||||
*/
|
||||
export interface SecondaryAxisRow {
|
||||
/** The edit-mode fields. */
|
||||
root(): Locator;
|
||||
view(): Locator;
|
||||
/** A ToggleGroup button: `secondary-axis-<index>-side-button-<value>`. */
|
||||
side(value: 'left' | 'right'): Locator;
|
||||
softMin(): Locator;
|
||||
softMax(): Locator;
|
||||
/** The series Combobox trigger, for `comboboxAt`. */
|
||||
series(): Locator;
|
||||
save(): Locator;
|
||||
edit(): Locator;
|
||||
remove(): Locator;
|
||||
}
|
||||
|
||||
export interface Axes {
|
||||
/** A ToggleGroup button of the primary axis's side. */
|
||||
primarySide(value: 'left' | 'right'): Locator;
|
||||
addButton(): Locator;
|
||||
row(index: number): SecondaryAxisRow;
|
||||
}
|
||||
|
||||
/** The label variant TimeSeries, Bar and Area use. */
|
||||
export interface ThresholdRow {
|
||||
@@ -49,6 +75,7 @@ export interface SavedPanel {
|
||||
|
||||
export interface PanelConfig {
|
||||
thresholds: Thresholds;
|
||||
axes: Axes;
|
||||
contextLinks: ContextLinks;
|
||||
/** The plugin spec and links as persisted, straight from the API. */
|
||||
saved(dashboardId: string, panelId?: string): Promise<SavedPanel>;
|
||||
@@ -66,6 +93,25 @@ function panelConfigDriver(page: Page): PanelConfig {
|
||||
save: () => page.getByTestId(`threshold-save-${index}`),
|
||||
}),
|
||||
},
|
||||
axes: {
|
||||
primarySide: (value) =>
|
||||
page.getByTestId(`panel-editor-v2-axis-side-button-${value}`),
|
||||
addButton: () => page.getByTestId('panel-editor-v2-add-axis'),
|
||||
row: (index) => {
|
||||
const prefix = `secondary-axis-${index}`;
|
||||
return {
|
||||
root: () => page.getByTestId(prefix),
|
||||
side: (value) => page.getByTestId(`${prefix}-side-button-${value}`),
|
||||
softMin: () => page.getByTestId(`${prefix}-soft-min`),
|
||||
softMax: () => page.getByTestId(`${prefix}-soft-max`),
|
||||
series: () => page.getByTestId(`${prefix}-series`),
|
||||
view: () => page.getByTestId(`secondary-axis-view-${index}`),
|
||||
save: () => page.getByTestId(`secondary-axis-save-${index}`),
|
||||
edit: () => page.getByTestId(`secondary-axis-edit-${index}`),
|
||||
remove: () => page.getByTestId(`secondary-axis-remove-${index}`),
|
||||
};
|
||||
},
|
||||
},
|
||||
contextLinks: {
|
||||
addButton: () => page.getByTestId('panel-editor-v2-add-link'),
|
||||
headerAdd: () => page.getByTestId('panel-editor-v2-add-link-header'),
|
||||
|
||||
96
tests/e2e/tests/dashboards/editor/axes.spec.ts
Normal file
96
tests/e2e/tests/dashboards/editor/axes.spec.ts
Normal file
@@ -0,0 +1,96 @@
|
||||
import { comboboxAt } from '../../../drivers/combobox';
|
||||
import {
|
||||
expect,
|
||||
PanelKind,
|
||||
PATH,
|
||||
QueryRange,
|
||||
ramp,
|
||||
Section,
|
||||
SINGLE_PANEL_ID,
|
||||
singlePanelDashboard,
|
||||
test,
|
||||
} from '../../../drivers/panel-config';
|
||||
|
||||
// Scope: the Axes section's primary side and secondary axis list, saved from
|
||||
// the editor, read back from the stored spec and drawn after a reload.
|
||||
|
||||
const SERIES = QueryRange.timeSeries([
|
||||
{ labels: { 'service.name': 'adservice' }, points: ramp(24, 10, 80) },
|
||||
{ labels: { 'service.name': 'cartservice' }, points: ramp(24, 20, 60) },
|
||||
]);
|
||||
|
||||
test.describe('Dashboards — editor axes', () => {
|
||||
test('TC-01 a secondary axis and a right-hand primary axis persist and render', async ({
|
||||
authedPage: page,
|
||||
dashboards,
|
||||
queryRange,
|
||||
editor,
|
||||
panels,
|
||||
config,
|
||||
}) => {
|
||||
await queryRange.respond(SERIES);
|
||||
const id = await dashboards.seedAndEdit(
|
||||
singlePanelDashboard({ kind: PanelKind.TimeSeries }),
|
||||
SINGLE_PANEL_ID,
|
||||
);
|
||||
|
||||
await editor.section.expand(Section.axes);
|
||||
await config.axes.primarySide('right').click();
|
||||
await config.axes.addButton().click();
|
||||
const axis = config.axes.row(0);
|
||||
await expect(axis.root()).toBeVisible();
|
||||
await axis.softMax().fill('95');
|
||||
await comboboxAt(page, axis.series()).pick('A');
|
||||
await axis.save().click();
|
||||
await expect(axis.view()).toContainText('Right · A');
|
||||
await editor.save();
|
||||
await page.waitForURL(PATH.onDashboard(id));
|
||||
|
||||
const { plugin } = await config.saved(id);
|
||||
expect(plugin.axes).toMatchObject({ side: 'right' });
|
||||
expect(plugin.axes?.secondary).toHaveLength(1);
|
||||
expect(plugin.axes?.secondary?.[0]).toMatchObject({
|
||||
side: 'right',
|
||||
softMax: 95,
|
||||
series: ['A'],
|
||||
});
|
||||
expect(plugin.axes?.secondary?.[0].id).not.toBe('');
|
||||
|
||||
const target = panels.panel(SINGLE_PANEL_ID);
|
||||
const expectTwoYAxes = async (): Promise<void> => {
|
||||
await target.waitRendered(PanelKind.TimeSeries);
|
||||
// uPlot draws one `.u-axis` per axis: x, the primary y and the secondary y.
|
||||
await expect(target.root().locator('.u-axis')).toHaveCount(3);
|
||||
};
|
||||
await expectTwoYAxes();
|
||||
|
||||
await dashboards.reload();
|
||||
await expectTwoYAxes();
|
||||
});
|
||||
|
||||
test('TC-02 removing the only secondary axis empties the list in the saved spec', async ({
|
||||
dashboards,
|
||||
editor,
|
||||
config,
|
||||
}) => {
|
||||
const id = await dashboards.seedAndEdit(
|
||||
singlePanelDashboard({
|
||||
kind: PanelKind.TimeSeries,
|
||||
pluginSpec: {
|
||||
axes: { secondary: [{ id: 'lat', unit: 'ms', series: ['A'] }] },
|
||||
thresholds: [{ value: 5, color: '#F1575F', axis: 'lat' }],
|
||||
},
|
||||
}),
|
||||
SINGLE_PANEL_ID,
|
||||
);
|
||||
|
||||
await editor.section.expand(Section.axes);
|
||||
await config.axes.row(0).remove().click();
|
||||
await editor.save();
|
||||
|
||||
const { plugin } = await config.saved(id);
|
||||
expect(plugin.axes?.secondary).toEqual([]);
|
||||
// The threshold that pointed at the removed axis falls back to the primary axis.
|
||||
expect(plugin.thresholds?.[0]).not.toMatchObject({ axis: 'lat' });
|
||||
});
|
||||
});
|
||||
Reference in New Issue
Block a user