Skip to content

SigNoz is an open-source, OpenTelemetry-native observability platform for your team and their AI agents. Get logs, metrics, and traces in one tool with features like APM, distributed tracing, log management, infra monitoring, etc. Combined with SigNoz MCP and a native AI teammate (in SigNoz Cloud) it helps you build more resilient apps.

feat: added changes for spangaps thresholds (#10570)

Abhi kumar0faef8705de3
diff --git a/frontend/src/container/DashboardContainer/visualization/charts/ChartWrapper/ChartWrapper.tsx b/frontend/src/container/DashboardContainer/visualization/charts/ChartWrapper/ChartWrapper.tsx
index bd005e9fdf..b5e79fcef2 100644
--- a/frontend/src/container/DashboardContainer/visualization/charts/ChartWrapper/ChartWrapper.tsx
+++ b/frontend/src/container/DashboardContainer/visualization/charts/ChartWrapper/ChartWrapper.tsx
@@ -5,7 +5,7 @@ import {
LegendPosition,
TooltipRenderArgs,
} from 'lib/uPlotV2/components/types';
-import UPlotChart from 'lib/uPlotV2/components/UPlotChart';
+import UPlotChart from 'lib/uPlotV2/components/UPlotChart/UPlotChart';
import { PlotContextProvider } from 'lib/uPlotV2/context/PlotContext';
import TooltipPlugin from 'lib/uPlotV2/plugins/TooltipPlugin/TooltipPlugin';
import noop from 'lodash-es/noop';
diff --git a/frontend/src/container/DashboardContainer/visualization/panels/TimeSeriesPanel/utils.ts b/frontend/src/container/DashboardContainer/visualization/panels/TimeSeriesPanel/utils.ts
index 2261b49998..8bd0fe1e39 100644
--- a/frontend/src/container/DashboardContainer/visualization/panels/TimeSeriesPanel/utils.ts
+++ b/frontend/src/container/DashboardContainer/visualization/panels/TimeSeriesPanel/utils.ts
@@ -123,7 +123,7 @@ export const prepareUPlotConfig = ({
drawStyle: hasSingleValidPoint ? DrawStyle.Points : DrawStyle.Line,
label: label,
colorMapping: widget.customLegendColors ?? {},
- spanGaps: true,
+ spanGaps: widget.spanGaps ?? true,
lineStyle: widget.lineStyle || LineStyle.Solid,
lineInterpolation: widget.lineInterpolation || LineInterpolation.Spline,
showPoints:
diff --git a/frontend/src/container/NewWidget/RightContainer/RightContainer.styles.scss b/frontend/src/container/NewWidget/RightContainer/RightContainer.styles.scss
index 10e66f7109..6647d57926 100644
--- a/frontend/src/container/NewWidget/RightContainer/RightContainer.styles.scss
+++ b/frontend/src/container/NewWidget/RightContainer/RightContainer.styles.scss
@@ -4,6 +4,10 @@
font-family: 'Space Mono';
padding-bottom: 48px;
+ .panel-type-select {
+ width: 100%;
+ }
+
.section-heading {
font-family: 'Space Mono';
color: var(--bg-vanilla-400);
@@ -26,10 +30,6 @@
letter-spacing: 0.48px;
}
- .panel-type-select {
- width: 100%;
- }
-
.header {
display: flex;
padding: 14px 14px 14px 12px;
@@ -216,7 +216,8 @@
.lightMode {
.right-container {
background-color: var(--bg-vanilla-100);
- .section-heading {
+ .section-heading,
+ .section-heading-small {
color: var(--bg-ink-400);
}
.header {
diff --git a/frontend/src/container/NewWidget/RightContainer/SettingSections/ChartAppearanceSection/ChartAppearanceSection.tsx b/frontend/src/container/NewWidget/RightContainer/SettingSections/ChartAppearanceSection/ChartAppearanceSection.tsx
index 4df781ea27..68a412d53f 100644
--- a/frontend/src/container/NewWidget/RightContainer/SettingSections/ChartAppearanceSection/ChartAppearanceSection.tsx
+++ b/frontend/src/container/NewWidget/RightContainer/SettingSections/ChartAppearanceSection/ChartAppearanceSection.tsx
@@ -7,9 +7,10 @@ import {
} from 'lib/uPlotV2/config/types';
import { Paintbrush } from 'lucide-react';
-import { FillModeSelector } from '../../components/FillModeSelector/FillModeSelector';
-import { LineInterpolationSelector } from '../../components/LineInterpolationSelector/LineInterpolationSelector';
-import { LineStyleSelector } from '../../components/LineStyleSelector/LineStyleSelector';
+import DisconnectValuesSelector from '../../components/DisconnectValuesSelector/DisconnectValuesSelector';
+import FillModeSelector from '../../components/FillModeSelector/FillModeSelector';
+import LineInterpolationSelector from '../../components/LineInterpolationSelector/LineInterpolationSelector';
+import LineStyleSelector from '../../components/LineStyleSelector/LineStyleSelector';
import SettingsSection from '../../components/SettingsSection/SettingsSection';
interface ChartAppearanceSectionProps {
@@ -21,10 +22,14 @@ interface ChartAppearanceSectionProps {
setLineInterpolation: Dispatch<SetStateAction<LineInterpolation>>;
showPoints: boolean;
setShowPoints: Dispatch<SetStateAction<boolean>>;
+ spanGaps: boolean | number;
+ setSpanGaps: Dispatch<SetStateAction<boolean | number>>;
allowFillMode: boolean;
allowLineStyle: boolean;
allowLineInterpolation: boolean;
allowShowPoints: boolean;
+ allowSpanGaps: boolean;
+ stepInterval: number;
}
export default function ChartAppearanceSection({
@@ -36,10 +41,14 @@ export default function ChartAppearanceSection({
setLineInterpolation,
showPoints,
setShowPoints,
+ spanGaps,
+ setSpanGaps,
allowFillMode,
allowLineStyle,
allowLineInterpolation,
allowShowPoints,
+ allowSpanGaps,
+ stepInterval,
}: ChartAppearanceSectionProps): JSX.Element {
return (
<SettingsSection title="Chart Appearance" icon={<Paintbrush size={14} />}>
@@ -66,6 +75,13 @@ export default function ChartAppearanceSection({
<Switch size="small" checked={showPoints} onChange={setShowPoints} />
</section>
)}
+ {allowSpanGaps && (
+ <DisconnectValuesSelector
+ value={spanGaps}
+ minValue={stepInterval}
+ onChange={setSpanGaps}
+ />
+ )}
</SettingsSection>
);
}
diff --git a/frontend/src/container/NewWidget/RightContainer/__tests__/RightContainer.test.tsx b/frontend/src/container/NewWidget/RightContainer/__tests__/RightContainer.test.tsx
index b12e30bbde..a6881a5638 100644
--- a/frontend/src/container/NewWidget/RightContainer/__tests__/RightContainer.test.tsx
+++ b/frontend/src/container/NewWidget/RightContainer/__tests__/RightContainer.test.tsx
@@ -178,6 +178,8 @@ describe('RightContainer - Alerts Section', () => {
setLineStyle: jest.fn(),
showPoints: false,
setShowPoints: jest.fn(),
+ spanGaps: false,
+ setSpanGaps: jest.fn(),
};
beforeEach(() => {
diff --git a/frontend/src/container/NewWidget/RightContainer/components/DisconnectValuesSelector/DisconnectValuesModeToggle.tsx b/frontend/src/container/NewWidget/RightContainer/components/DisconnectValuesSelector/DisconnectValuesModeToggle.tsx
new file mode 100644
index 0000000000..c5ed204d7d
--- /dev/null
+++ b/frontend/src/container/NewWidget/RightContainer/components/DisconnectValuesSelector/DisconnectValuesModeToggle.tsx
@@ -0,0 +1,38 @@
+import { ToggleGroup, ToggleGroupItem } from '@signozhq/toggle-group';
+import { Typography } from 'antd';
+import { DisconnectedValuesMode } from 'lib/uPlotV2/config/types';
+
+interface DisconnectValuesModeToggleProps {
+ value: DisconnectedValuesMode;
+ onChange: (value: DisconnectedValuesMode) => void;
+}
+
+export default function DisconnectValuesModeToggle({
+ value,
+ onChange,
+}: DisconnectValuesModeToggleProps): JSX.Element {
+ return (
+ <ToggleGroup
+ type="single"
+ value={value}
+ size="lg"
+ onValueChange={(newValue): void => {
+ if (newValue) {
+ onChange(newValue as DisconnectedValuesMode);
+ }
+ }}
+ >
+ <ToggleGroupItem value={DisconnectedValuesMode.Never} aria-label="Never">
+ <Typography.Text className="section-heading-small">Never</Typography.Text>
+ </ToggleGroupItem>
+ <ToggleGroupItem
+ value={DisconnectedValuesMode.Threshold}
+ aria-label="Threshold"
+ >
+ <Typography.Text className="section-heading-small">
+ Threshold
+ </Typography.Text>
+ </ToggleGroupItem>
+ </ToggleGroup>
+ );
+}
diff --git a/frontend/src/container/NewWidget/RightContainer/components/DisconnectValuesSelector/DisconnectValuesSelector.styles.scss b/frontend/src/container/NewWidget/RightContainer/components/DisconnectValuesSelector/DisconnectValuesSelector.styles.scss
new file mode 100644
index 0000000000..c540a90dbd
--- /dev/null
+++ b/frontend/src/container/NewWidget/RightContainer/components/DisconnectValuesSelector/DisconnectValuesSelector.styles.scss
@@ -0,0 +1,21 @@
+.disconnect-values-selector {
+ .disconnect-values-input-wrapper {
+ display: flex;
+ flex-direction: column;
+ gap: 16px;
+
+ .disconnect-values-threshold-wrapper {
+ display: flex;
+ flex-direction: column;
+ gap: 8px;
+ .disconnect-values-threshold-input {
+ max-width: 160px;
+ height: auto;
+ .disconnect-values-threshold-prefix {
+ padding: 0 8px;
+ font-size: 20px;
+ }
+ }
+ }
+ }
+}
diff --git a/frontend/src/container/NewWidget/RightContainer/components/DisconnectValuesSelector/DisconnectValuesSelector.tsx b/frontend/src/container/NewWidget/RightContainer/components/DisconnectValuesSelector/DisconnectValuesSelector.tsx
new file mode 100644
index 0000000000..fc72e5b6fc
--- /dev/null
+++ b/frontend/src/container/NewWidget/RightContainer/components/DisconnectValuesSelector/DisconnectValuesSelector.tsx
@@ -0,0 +1,91 @@
+import { useEffect, useState } from 'react';
+import { Typography } from 'antd';
+import { DisconnectedValuesMode } from 'lib/uPlotV2/config/types';
+
+import DisconnectValuesModeToggle from './DisconnectValuesModeToggle';
+import DisconnectValuesThresholdInput from './DisconnectValuesThresholdInput';
+
+import './DisconnectValuesSelector.styles.scss';
+
+const DEFAULT_THRESHOLD_SECONDS = 60;
+
+interface DisconnectValuesSelectorProps {
+ value: boolean | number;
+ minValue: number;
+ onChange: (value: boolean | number) => void;
+}
+
+export default function DisconnectValuesSelector({
+ value,
+ minValue,
+ onChange,
+}: DisconnectValuesSelectorProps): JSX.Element {
+ const [mode, setMode] = useState<DisconnectedValuesMode>(() => {
+ if (typeof value === 'number') {
+ return DisconnectedValuesMode.Threshold;
+ }
+ return DisconnectedValuesMode.Never;
+ });
+ const [thresholdSeconds, setThresholdSeconds] = useState<number>(
+ typeof value === 'number' ? value : minValue ?? DEFAULT_THRESHOLD_SECONDS,
+ );
+
+ useEffect(() => {
+ if (typeof value === 'boolean') {
+ setMode(DisconnectedValuesMode.Never);
+ } else if (typeof value === 'number') {
+ setMode(DisconnectedValuesMode.Threshold);
+ setThresholdSeconds(value);
+ }
+ }, [value]);
+
+ useEffect(() => {
+ if (minValue !== undefined) {
+ setThresholdSeconds(minValue);
+ if (mode === DisconnectedValuesMode.Threshold) {
+ onChange(minValue);
+ }
+ }
+ // eslint-disable-next-line react-hooks/exhaustive-deps
+ }, [minValue]);
+
+ const handleModeChange = (newMode: DisconnectedValuesMode): void => {
+ setMode(newMode);
+ switch (newMode) {
+ case DisconnectedValuesMode.Never:
+ onChange(true);
+ break;
+ case DisconnectedValuesMode.Threshold:
+ onChange(thresholdSeconds);
+ break;
+ }
+ };
+
+ const handleThresholdChange = (seconds: number): void => {
+ setThresholdSeconds(seconds);
+ onChange(seconds);
+ };
+
+ return (
+ <section className="disconnect-values-selector control-container">
+ <Typography.Text className="section-heading">
+ Disconnect values
+ </Typography.Text>
+ <div className="disconnect-values-input-wrapper">
+ <DisconnectValuesModeToggle value={mode} onChange={handleModeChange} />
+ {mode === DisconnectedValuesMode.Threshold && (
+ <section className="control-container">
+ <Typography.Text className="section-heading">
+ Threshold Value
+ </Typography.Text>
+ <DisconnectValuesThresholdInput
+ value={thresholdSeconds}
+ minValue={minValue}
+ onChange={handleThresholdChange}
+ />
+ </section>
+ )}
+ </div>
+ </section>
+ );
+}
diff --git a/frontend/src/container/NewWidget/RightContainer/components/DisconnectValuesSelector/DisconnectValuesThresholdInput.tsx b/frontend/src/container/NewWidget/RightContainer/components/DisconnectValuesSelector/DisconnectValuesThresholdInput.tsx
new file mode 100644
index 0000000000..6e4ae57098
--- /dev/null
+++ b/frontend/src/container/NewWidget/RightContainer/components/DisconnectValuesSelector/DisconnectValuesThresholdInput.tsx
@@ -0,0 +1,92 @@
+import { ChangeEvent, useEffect, useState } from 'react';
+import { rangeUtil } from '@grafana/data';
+import { Callout, Input } from '@signozhq/ui';
+interface DisconnectValuesThresholdInputProps {
+ value: number;
+ onChange: (seconds: number) => void;
+ minValue: number;
+}
+
+export default function DisconnectValuesThresholdInput({
+ value,
+ onChange,
+ minValue,
+}: DisconnectValuesThresholdInputProps): JSX.Element {
+ const [inputValue, setInputValue] = useState<string>(
+ rangeUtil.secondsToHms(value),
+ );
+ const [error, setError] = useState<string | null>(null);
+
+ useEffect(() => {
+ setInputValue(rangeUtil.secondsToHms(value));
+ setError(null);
+ }, [value]);
+
+ const updateValue = (txt: string): void => {
+ if (!txt) {
+ return;
+ }
+ try {
+ let seconds: number;
+ if (rangeUtil.isValidTimeSpan(txt)) {
+ seconds = rangeUtil.intervalToSeconds(txt);
+ } else {
+ const parsed = Number(txt);
+ if (Number.isNaN(parsed) || parsed <= 0) {
+ setError('Enter a valid duration (e.g. 1h, 10m, 1d)');
+ return;
+ }
+ seconds = parsed;
+ }
+ if (minValue !== undefined && seconds < minValue) {
+ setError(`Threshold should be > ${rangeUtil.secondsToHms(minValue)}`);
+ return;
+ }
+ setError(null);
+ setInputValue(txt);
+ onChange(seconds);
+ } catch {
+ setError('Invalid threshold value');
+ }
+ };
+
+ const handleKeyDown = (e: React.KeyboardEvent<HTMLInputElement>): void => {
+ if (e.key === 'Enter') {
+ updateValue(e.currentTarget.value);
+ }
+ };
+
+ const handleBlur = (e: React.FocusEvent<HTMLInputElement>): void => {
+ updateValue(e.currentTarget.value);
+ };
+
+ const handleChange = (e: ChangeEvent<HTMLInputElement>): void => {
+ setInputValue(e.currentTarget.value);
+ if (error) {
+ setError(null);
+ }
+ };
+
+ return (
+ <div className="disconnect-values-threshold-wrapper">
+ <Input
+ name="disconnect-values-threshold"
+ type="text"
+ className="disconnect-values-threshold-input"
+ prefix={<span className="disconnect-values-threshold-prefix">&gt;</span>}
+ value={inputValue}
+ onChange={handleChange}
+ onKeyDown={handleKeyDown}
+ onBlur={handleBlur}
+ autoFocus={true}
+ aria-invalid={!!error}
+ aria-describedby={error ? 'threshold-error' : undefined}
+ />
+ {error && (
+ <Callout type="error" size="small" showIcon>
+ {error}
+ </Callout>
+ )}
+ </div>
+ );
+}
diff --git a/frontend/src/container/NewWidget/RightContainer/components/FillModeSelector/FillModeSelector.tsx b/frontend/src/container/NewWidget/RightContainer/components/FillModeSelector/FillModeSelector.tsx
index 831a27fcb9..51e7af9824 100644
--- a/frontend/src/container/NewWidget/RightContainer/components/FillModeSelector/FillModeSelector.tsx
+++ b/frontend/src/container/NewWidget/RightContainer/components/FillModeSelector/FillModeSelector.tsx
@@ -9,7 +9,7 @@ interface FillModeSelectorProps {
onChange: (value: FillMode) => void;
}
-export function FillModeSelector({
+export default function FillModeSelector({
value,
onChange,
}: FillModeSelectorProps): JSX.Element {
diff --git a/frontend/src/container/NewWidget/RightContainer/components/LineInterpolationSelector/LineInterpolationSelector.tsx b/frontend/src/container/NewWidget/RightContainer/components/LineInterpolationSelector/LineInterpolationSelector.tsx
index 76736d358a..cb55997aac 100644
--- a/frontend/src/container/NewWidget/RightContainer/components/LineInterpolationSelector/LineInterpolationSelector.tsx
+++ b/frontend/src/container/NewWidget/RightContainer/components/LineInterpolationSelector/LineInterpolationSelector.tsx
@@ -9,7 +9,7 @@ interface LineInterpolationSelectorProps {
onChange: (value: LineInterpolation) => void;
}
-export function LineInterpolationSelector({
+export default function LineInterpolationSelector({
value,
onChange,
}: LineInterpolationSelectorProps): JSX.Element {
diff --git a/frontend/src/container/NewWidget/RightContainer/components/LineStyleSelector/LineStyleSelector.tsx b/frontend/src/container/NewWidget/RightContainer/components/LineStyleSelector/LineStyleSelector.tsx
index fd7b8dd67b..840a6c236c 100644
--- a/frontend/src/container/NewWidget/RightContainer/components/LineStyleSelector/LineStyleSelector.tsx
+++ b/frontend/src/container/NewWidget/RightContainer/components/LineStyleSelector/LineStyleSelector.tsx
@@ -9,7 +9,7 @@ interface LineStyleSelectorProps {
onChange: (value: LineStyle) => void;
}
-export function LineStyleSelector({
+export default function LineStyleSelector({
value,
onChange,
}: LineStyleSelectorProps): JSX.Element {
diff --git a/frontend/src/container/NewWidget/RightContainer/constants.ts b/frontend/src/container/NewWidget/RightContainer/constants.ts
index d62ff01c94..bbc97d763b 100644
--- a/frontend/src/container/NewWidget/RightContainer/constants.ts
+++ b/frontend/src/container/NewWidget/RightContainer/constants.ts
@@ -262,3 +262,17 @@ export const panelTypeVsShowPoints: {
[PANEL_TYPES.TRACE]: false,
[PANEL_TYPES.EMPTY_WIDGET]: false,
} as const;
+
+export const panelTypeVsSpanGaps: {
+ [key in PANEL_TYPES]: boolean;
+} = {
+ [PANEL_TYPES.TIME_SERIES]: true,
+ [PANEL_TYPES.VALUE]: false,
+ [PANEL_TYPES.TABLE]: false,
+ [PANEL_TYPES.LIST]: false,
+ [PANEL_TYPES.PIE]: false,
+ [PANEL_TYPES.BAR]: false,
+ [PANEL_TYPES.HISTOGRAM]: false,
+ [PANEL_TYPES.TRACE]: false,
+ [PANEL_TYPES.EMPTY_WIDGET]: false,
+} as const;
diff --git a/frontend/src/container/NewWidget/RightContainer/index.tsx b/frontend/src/container/NewWidget/RightContainer/index.tsx
index d4053a2c4e..700c7f01cd 100644
--- a/frontend/src/container/NewWidget/RightContainer/index.tsx
+++ b/frontend/src/container/NewWidget/RightContainer/index.tsx
@@ -1,6 +1,7 @@
import { Dispatch, SetStateAction, useMemo } from 'react';
import { UseQueryResult } from 'react-query';
import { Typography } from 'antd';
+import { ExecStats } from 'api/v5/v5';
import { PrecisionOption, PrecisionOptionsEnum } from 'components/Graph/types';
import { PANEL_TYPES, PanelDisplay } from 'constants/queryBuilder';
import { PanelTypesWithData } from 'container/DashboardContainer/PanelTypeSelectionModal/menuItems';
@@ -11,6 +12,7 @@ import {
LineInterpolation,
LineStyle,
} from 'lib/uPlotV2/config/types';
+import get from 'lodash-es/get';
import { SuccessResponse } from 'types/api';
import {
ColumnUnit,
@@ -36,6 +38,7 @@ import {
panelTypeVsPanelTimePreferences,
panelTypeVsShowPoints,
panelTypeVsSoftMinMax,
+ panelTypeVsSpanGaps,
panelTypeVsStackingChartPreferences,
panelTypeVsThreshold,
panelTypeVsYAxisUnit,
@@ -68,6 +71,8 @@ function RightContainer({
setLineStyle,
showPoints,
setShowPoints,
+ spanGaps,
+ setSpanGaps,
bucketCount,
bucketWidth,
stackedBarChart,
@@ -138,6 +143,7 @@ function RightContainer({
const allowLineStyle = panelTypeVsLineStyle[selectedGraph];
const allowFillMode = panelTypeVsFillMode[selectedGraph];
const allowShowPoints = panelTypeVsShowPoints[selectedGraph];
+ const allowSpanGaps = panelTypeVsSpanGaps[selectedGraph];
const decimapPrecisionOptions = useMemo(
() => [
@@ -176,10 +182,26 @@ function RightContainer({
(allowFillMode ||
allowLineStyle ||
allowLineInterpolation ||
- allowShowPoints),
- [allowFillMode, allowLineStyle, allowLineInterpolation, allowShowPoints],
+ allowShowPoints ||
+ allowSpanGaps),
+ [
+ allowFillMode,
+ allowLineStyle,
+ allowLineInterpolation,
+ allowShowPoints,
+ allowSpanGaps,
+ ],
);
+ const stepInterval = useMemo(() => {
+ const stepIntervals: ExecStats['stepIntervals'] = get(
+ queryResponse,
+ 'data.payload.data.newResult.meta.stepIntervals',
+ {},
+ );
+ return Math.min(...Object.values(stepIntervals));
+ }, [queryResponse]);
+
return (
<div className="right-container">
<section className="header">
@@ -237,10 +259,14 @@ function RightContainer({
setLineInterpolation={setLineInterpolation}
showPoints={showPoints}
setShowPoints={setShowPoints}
+ spanGaps={spanGaps}
+ setSpanGaps={setSpanGaps}
allowFillMode={allowFillMode}
allowLineStyle={allowLineStyle}
allowLineInterpolation={allowLineInterpolation}
allowShowPoints={allowShowPoints}
+ allowSpanGaps={allowSpanGaps}
+ stepInterval={stepInterval}
/>
)}
@@ -364,6 +390,8 @@ export interface RightContainerProps {
setLineStyle: Dispatch<SetStateAction<LineStyle>>;
showPoints: boolean;
setShowPoints: Dispatch<SetStateAction<boolean>>;
+ spanGaps: boolean | number;
+ setSpanGaps: Dispatch<SetStateAction<boolean | number>>;
}
RightContainer.defaultProps = {
diff --git a/frontend/src/container/NewWidget/__test__/NewWidget.test.tsx b/frontend/src/container/NewWidget/__test__/NewWidget.test.tsx
index 6425db00b5..9451d63880 100644
--- a/frontend/src/container/NewWidget/__test__/NewWidget.test.tsx
+++ b/frontend/src/container/NewWidget/__test__/NewWidget.test.tsx
@@ -14,7 +14,6 @@ import { DashboardProvider } from 'providers/Dashboard/Dashboard';
import { PreferenceContextProvider } from 'providers/preferences/context/PreferenceContextProvider';
import i18n from 'ReactI18';
import {
- fireEvent,
getByText as getByTextUtil,
render,
userEvent,
@@ -342,9 +341,8 @@ describe('Stacking bar in new panel', () => {
const STACKING_STATE_ATTR = 'data-stacking-state';
describe('when switching to BAR panel type', () => {
- jest.setTimeout(10000);
-
beforeEach(() => {
+ jest.useFakeTimers();
jest.clearAllMocks();
// Mock useSearchParams to return the expected values
@@ -354,7 +352,15 @@ describe('when switching to BAR panel type', () => {
]);
});
+ afterEach(() => {
+ jest.useRealTimers();
+ });
+
it('should preserve saved stacking value of true', async () => {
+ const user = userEvent.setup({
+ advanceTimers: jest.advanceTimersByTime.bind(jest),
+ });
+
const { getByTestId, getByText, container } = render(
<DashboardProvider dashboardId="">
<NewWidget
@@ -370,7 +376,7 @@ describe('when switching to BAR panel type', () => {
'true',
);
- await userEvent.click(getByText('Bar')); // Panel Type Selected
+ await user.click(getByText('Bar')); // Panel Type Selected
// find dropdown with - .ant-select-dropdown
const panelDropdown = document.querySelector(
@@ -380,7 +386,7 @@ describe('when switching to BAR panel type', () => {
// Select TimeSeries from dropdown
const option = within(panelDropdown).getByText('Time Series');
- fireEvent.click(option);
+ await user.click(option);
expect(getByTestId('panel-change-select')).toHaveAttribute(
STACKING_STATE_ATTR,
@@ -395,7 +401,7 @@ describe('when switching to BAR panel type', () => {
expect(panelTypeDropdown2).toBeInTheDocument();
expect(getByTextUtil(panelTypeDropdown2, 'Time Series')).toBeInTheDocument();
- fireEvent.click(getByTextUtil(panelTypeDropdown2, 'Time Series'));
+ await user.click(getByTextUtil(panelTypeDropdown2, 'Time Series'));
// find dropdown with - .ant-select-dropdown
const panelDropdown2 = document.querySelector(
@@ -403,7 +409,7 @@ describe('when switching to BAR panel type', () => {
) as HTMLElement;
// // Select BAR from dropdown
const BarOption = within(panelDropdown2).getByText('Bar');
- fireEvent.click(BarOption);
+ await user.click(BarOption);
// Stack series should be true
checkStackSeriesState(container, true);
diff --git a/frontend/src/container/NewWidget/index.tsx b/frontend/src/container/NewWidget/index.tsx
index 3f0ffc82a0..1f1f855fc1 100644
--- a/frontend/src/container/NewWidget/index.tsx
+++ b/frontend/src/container/NewWidget/index.tsx
@@ -220,6 +220,9 @@ function NewWidget({
const [showPoints, setShowPoints] = useState<boolean>(
selectedWidget?.showPoints ?? false,
);
+ const [spanGaps, setSpanGaps] = useState<boolean | number>(
+ selectedWidget?.spanGaps ?? true,
+ );
const [customLegendColors, setCustomLegendColors] = useState<
Record<string, string>
>(selectedWidget?.customLegendColors || {});
@@ -289,6 +292,7 @@ function NewWidget({
fillMode,
lineStyle,
showPoints,
+ spanGaps,
columnUnits,
bucketCount,
stackedBarChart,
@@ -328,6 +332,7 @@ function NewWidget({
fillMode,
lineStyle,
showPoints,
+ spanGaps,
customLegendColors,
contextLinks,
selectedWidget.columnWidths,
@@ -541,6 +546,7 @@ function NewWidget({
softMin: selectedWidget?.softMin || 0,
softMax: selectedWidget?.softMax || 0,
fillSpans: selectedWidget?.fillSpans,
+ spanGaps: selectedWidget?.spanGaps ?? true,
isLogScale: selectedWidget?.isLogScale || false,
bucketWidth: selectedWidget?.bucketWidth || 0,
bucketCount: selectedWidget?.bucketCount || 0,
@@ -572,6 +578,7 @@ function NewWidget({
softMin: selectedWidget?.softMin || 0,
softMax: selectedWidget?.softMax || 0,
fillSpans: selectedWidget?.fillSpans,
+ spanGaps: selectedWidget?.spanGaps ?? true,
isLogScale: selectedWidget?.isLogScale || false,
bucketWidth: selectedWidget?.bucketWidth || 0,
bucketCount: selectedWidget?.bucketCount || 0,
@@ -889,6 +896,8 @@ function NewWidget({
setLineStyle={setLineStyle}
showPoints={showPoints}
setShowPoints={setShowPoints}
+ spanGaps={spanGaps}
+ setSpanGaps={setSpanGaps}
opacity={opacity}
yAxisUnit={yAxisUnit}
columnUnits={columnUnits}
diff --git a/frontend/src/lib/uPlotV2/components/UPlotChart.tsx b/frontend/src/lib/uPlotV2/components/UPlotChart/UPlotChart.tsx
similarity index 91%
rename from frontend/src/lib/uPlotV2/components/UPlotChart.tsx
rename to frontend/src/lib/uPlotV2/components/UPlotChart/UPlotChart.tsx
index 7e6320ea5f..1588317f09 100644
--- a/frontend/src/lib/uPlotV2/components/UPlotChart.tsx
+++ b/frontend/src/lib/uPlotV2/components/UPlotChart/UPlotChart.tsx
@@ -6,8 +6,9 @@ import { LineChart } from 'lucide-react';
import ErrorBoundaryFallback from 'pages/ErrorBoundaryFallback/ErrorBoundaryFallback';
import uPlot, { AlignedData, Options } from 'uplot';
-import { usePlotContext } from '../context/PlotContext';
-import { UPlotChartProps } from './types';
+import { usePlotContext } from '../../context/PlotContext';
+import { UPlotChartProps } from '../types';
+import { prepareAlignedData } from './utils';
/**
* Check if dimensions have changed
@@ -83,8 +84,11 @@ export default function UPlotChart({
...configOptions,
} as Options;
+ // prepare final AlignedData
+ const preparedData = prepareAlignedData({ data, config });
+
// Create new plot instance
- const plot = new uPlot(plotConfig, data as AlignedData, containerRef.current);
+ const plot = new uPlot(plotConfig, preparedData, containerRef.current);
if (plotRef) {
plotRef(plot);
@@ -162,7 +166,8 @@ export default function UPlotChart({
}
// Update data if only data changed
else if (!sameData(prevProps, currentProps) && plotInstanceRef.current) {
- plotInstanceRef.current.setData(data as AlignedData);
+ const preparedData = prepareAlignedData({ data, config });
+ plotInstanceRef.current.setData(preparedData as AlignedData);
}
prevPropsRef.current = currentProps;
diff --git a/frontend/src/lib/uPlotV2/components/UPlotChart/utils.ts b/frontend/src/lib/uPlotV2/components/UPlotChart/utils.ts
new file mode 100644
index 0000000000..25c997d7ec
--- /dev/null
+++ b/frontend/src/lib/uPlotV2/components/UPlotChart/utils.ts
@@ -0,0 +1,16 @@
+import { UPlotConfigBuilder } from 'lib/uPlotV2/config/UPlotConfigBuilder';
+import { applySpanGapsToAlignedData } from 'lib/uPlotV2/utils/dataUtils';
+import { AlignedData } from 'uplot';
+
+export function prepareAlignedData({
+ data,
+ config,
+}: {
+ data: AlignedData;
+ config: UPlotConfigBuilder;
+}): AlignedData {
+ const seriesSpanGaps = config.getSeriesSpanGapsOptions();
+ return seriesSpanGaps.length > 0
+ ? applySpanGapsToAlignedData(data as AlignedData, seriesSpanGaps)
+ : (data as AlignedData);
+}
diff --git a/frontend/src/lib/uPlotV2/components/__tests__/UPlotChart.test.tsx b/frontend/src/lib/uPlotV2/components/__tests__/UPlotChart.test.tsx
index c0908a323a..0f01d641e8 100644
--- a/frontend/src/lib/uPlotV2/components/__tests__/UPlotChart.test.tsx
+++ b/frontend/src/lib/uPlotV2/components/__tests__/UPlotChart.test.tsx
@@ -4,7 +4,7 @@ import { UPlotConfigBuilder } from 'lib/uPlotV2/config/UPlotConfigBuilder';
import type { AlignedData } from 'uplot';
import { PlotContextProvider } from '../../context/PlotContext';
-import UPlotChart from '../UPlotChart';
+import UPlotChart from '../UPlotChart/UPlotChart';
// ---------------------------------------------------------------------------
// Mocks
@@ -86,6 +86,7 @@ const createMockConfig = (): UPlotConfigBuilder => {
}),
getId: jest.fn().mockReturnValue(undefined),
getShouldSaveSelectionPreference: jest.fn().mockReturnValue(false),
+ getSeriesSpanGapsOptions: jest.fn().mockReturnValue([]),
} as unknown) as UPlotConfigBuilder;
};
@@ -328,6 +329,78 @@ describe('UPlotChart', () => {
});
});
+ describe('spanGaps data transformation', () => {
+ it('inserts null break points before passing data to uPlot when a gap exceeds the numeric threshold', () => {
+ const config = createMockConfig();
+ // gap 0→100 = 100 > threshold 50 → null inserted at midpoint x=50
+ (config.getSeriesSpanGapsOptions as jest.Mock).mockReturnValue([
+ { spanGaps: 50 },
+ ]);
+ const data: AlignedData = [
+ [0, 100],
+ [1, 2],
+ ];
+
+ render(<UPlotChart config={config} data={data} width={600} height={400} />, {
+ wrapper: Wrapper,
+ });
+
+ const [, receivedData] = mockUPlotConstructor.mock.calls[0];
+ expect(receivedData[0]).toEqual([0, 50, 100]);
+ expect(receivedData[1]).toEqual([1, null, 2]);
+ });
+
+ it('passes data through unchanged when no gap exceeds the numeric threshold', () => {
+ const config = createMockConfig();
+ // all gaps = 10, threshold = 50 → no insertions, same reference returned
+ (config.getSeriesSpanGapsOptions as jest.Mock).mockReturnValue([
+ { spanGaps: 50 },
+ ]);
+ const data: AlignedData = [
+ [0, 10, 20],
+ [1, 2, 3],
+ ];
+
+ render(<UPlotChart config={config} data={data} width={600} height={400} />, {
+ wrapper: Wrapper,
+ });
+
+ const [, receivedData] = mockUPlotConstructor.mock.calls[0];
+ expect(receivedData).toBe(data);
+ });
+
+ it('transforms data passed to setData when data updates and a new gap exceeds the threshold', () => {
+ const config = createMockConfig();
+ (config.getSeriesSpanGapsOptions as jest.Mock).mockReturnValue([
+ { spanGaps: 50 },
+ ]);
+
+ // initial render: gap 10 < 50, no transformation
+ const initialData: AlignedData = [
+ [0, 10],
+ [1, 2],
+ ];
+ // updated data: gap 100 > 50 → null inserted at midpoint x=50
+ const newData: AlignedData = [
+ [0, 100],
+ [3, 4],
+ ];
+
+ const { rerender } = render(
+ <UPlotChart config={config} data={initialData} width={600} height={400} />,
+ { wrapper: Wrapper },
+ );
+
+ rerender(
+ <UPlotChart config={config} data={newData} width={600} height={400} />,
+ );
+
+ const receivedData = instances[0].setData.mock.calls[0][0];
+ expect(receivedData[0]).toEqual([0, 50, 100]);
+ expect(receivedData[1]).toEqual([3, null, 4]);
+ });
+ });
+
describe('prop updates', () => {
it('calls setData without recreating the plot when only data changes', () => {
const config = createMockConfig();
diff --git a/frontend/src/lib/uPlotV2/config/UPlotConfigBuilder.ts b/frontend/src/lib/uPlotV2/config/UPlotConfigBuilder.ts
index ed8f36efdd..aa74efe818 100644
--- a/frontend/src/lib/uPlotV2/config/UPlotConfigBuilder.ts
+++ b/frontend/src/lib/uPlotV2/config/UPlotConfigBuilder.ts
@@ -14,6 +14,7 @@ import {
STEP_INTERVAL_MULTIPLIER,
} from '../constants';
import { calculateWidthBasedOnStepInterval } from '../utils';
+import { SeriesSpanGapsOption } from '../utils/dataUtils';
import {
ConfigBuilder,
ConfigBuilderProps,
@@ -161,6 +162,13 @@ export class UPlotConfigBuilder extends ConfigBuilder<
this.series.push(new UPlotSeriesBuilder(props));
}
+ getSeriesSpanGapsOptions(): SeriesSpanGapsOption[] {
+ return this.series.map((s) => {
+ const { spanGaps } = s.props;
+ return { spanGaps };
+ });
+ }
+
/**
* Add a hook for extensibility
*/
diff --git a/frontend/src/lib/uPlotV2/config/UPlotSeriesBuilder.ts b/frontend/src/lib/uPlotV2/config/UPlotSeriesBuilder.ts
index 30d05e1279..3541fcd265 100644
--- a/frontend/src/lib/uPlotV2/config/UPlotSeriesBuilder.ts
+++ b/frontend/src/lib/uPlotV2/config/UPlotSeriesBuilder.ts
@@ -212,7 +212,12 @@ export class UPlotSeriesBuilder extends ConfigBuilder<SeriesProps, Series> {
return {
scale: scaleKey,
label,
- spanGaps: typeof spanGaps === 'boolean' ? spanGaps : false,
+ // When spanGaps is numeric, we always disable uPlot's internal
+ // spanGaps behavior and rely on data-prep to implement the
+ // threshold-based null handling. When spanGaps is boolean we
+ // map it directly. When spanGaps is undefined we fall back to
+ // the default of true.
+ spanGaps: typeof spanGaps === 'number' ? false : spanGaps ?? true,
value: (): string => '',
pxAlign: true,
show,
diff --git a/frontend/src/lib/uPlotV2/config/__tests__/UPlotSeriesBuilder.test.ts b/frontend/src/lib/uPlotV2/config/__tests__/UPlotSeriesBuilder.test.ts
index f13cf1ef7d..6b7764c76c 100644
--- a/frontend/src/lib/uPlotV2/config/__tests__/UPlotSeriesBuilder.test.ts
+++ b/frontend/src/lib/uPlotV2/config/__tests__/UPlotSeriesBuilder.test.ts
@@ -40,6 +40,37 @@ describe('UPlotSeriesBuilder', () => {
expect(typeof config.value).toBe('function');
});
+ it('maps boolean spanGaps directly to uPlot spanGaps', () => {
+ const trueBuilder = new UPlotSeriesBuilder(
+ createBaseProps({
+ spanGaps: true,
+ }),
+ );
+ const falseBuilder = new UPlotSeriesBuilder(
+ createBaseProps({
+ spanGaps: false,
+ }),
+ );
+
+ const trueConfig = trueBuilder.getConfig();
+ const falseConfig = falseBuilder.getConfig();
+
+ expect(trueConfig.spanGaps).toBe(true);
+ expect(falseConfig.spanGaps).toBe(false);
+ });
+
+ it('disables uPlot spanGaps when spanGaps is a number', () => {
+ const builder = new UPlotSeriesBuilder(
+ createBaseProps({
+ spanGaps: 10000,
+ }),
+ );
+
+ const config = builder.getConfig();
+
+ expect(config.spanGaps).toBe(false);
+ });
+
it('uses explicit lineColor when provided, regardless of mapping', () => {
const builder = new UPlotSeriesBuilder(
createBaseProps({
diff --git a/frontend/src/lib/uPlotV2/config/types.ts b/frontend/src/lib/uPlotV2/config/types.ts
index 664c310e14..808260ff60 100644
--- a/frontend/src/lib/uPlotV2/config/types.ts
+++ b/frontend/src/lib/uPlotV2/config/types.ts
@@ -99,6 +99,11 @@ export interface ScaleProps {
distribution?: DistributionType;
}
+export enum DisconnectedValuesMode {
+ Never = 'never',
+ Threshold = 'threshold',
+}
+
/**
* Props for configuring a series
*/
@@ -175,7 +180,16 @@ export interface SeriesProps extends LineConfig, PointsConfig, BarConfig {
pointsFilter?: Series.Points.Filter;
pointsBuilder?: Series.Points.Show;
show?: boolean;
- spanGaps?: boolean;
+ /**
+ * Controls how nulls are treated for this series.
+ *
+ * - boolean: mapped directly to uPlot's spanGaps behavior
+ * - number: interpreted as an X-axis threshold (same unit as ref values),
+ * where gaps smaller than this threshold are spanned by
+ * converting short null runs to undefined during data prep
+ * while uPlot's internal spanGaps is kept disabled.
+ */
+ spanGaps?: boolean | number;
fillColor?: string;
fillMode?: FillMode;
isDarkMode?: boolean;
diff --git a/frontend/src/lib/uPlotV2/utils/__tests__/dataUtils.test.ts b/frontend/src/lib/uPlotV2/utils/__tests__/dataUtils.test.ts
index f869c1d28c..e2ac93899a 100644
--- a/frontend/src/lib/uPlotV2/utils/__tests__/dataUtils.test.ts
+++ b/frontend/src/lib/uPlotV2/utils/__tests__/dataUtils.test.ts
@@ -1,4 +1,12 @@
-import { isInvalidPlotValue, normalizePlotValue } from '../dataUtils';
+import uPlot from 'uplot';
+
+import {
+ applySpanGapsToAlignedData,
+ insertLargeGapNullsIntoAlignedData,
+ isInvalidPlotValue,
+ normalizePlotValue,
+ SeriesSpanGapsOption,
+} from '../dataUtils';
describe('dataUtils', () => {
describe('isInvalidPlotValue', () => {
@@ -59,4 +67,217 @@ describe('dataUtils', () => {
expect(normalizePlotValue(42.5)).toBe(42.5);
});
});
+
+ describe('insertLargeGapNullsIntoAlignedData', () => {
+ it('returns original data unchanged when no gap exceeds the threshold', () => {
+ // all gaps = 10, threshold = 25 → no insertions
+ const data: uPlot.AlignedData = [
+ [0, 10, 20, 30],
+ [1, 2, 3, 4],
+ ];
+ const options: SeriesSpanGapsOption[] = [{ spanGaps: 25 }];
+
+ const result = insertLargeGapNullsIntoAlignedData(data, options);
+
+ expect(result).toBe(data);
+ });
+
+ it('does not insert when the gap equals the threshold exactly', () => {
+ // gap = 50, threshold = 50 → condition is gap > threshold, not >=
+ const data: uPlot.AlignedData = [
+ [0, 50],
+ [1, 2],
+ ];
+ const options: SeriesSpanGapsOption[] = [{ spanGaps: 50 }];
+
+ const result = insertLargeGapNullsIntoAlignedData(data, options);
+
+ expect(result).toBe(data);
+ });
+
+ it('inserts a null at the midpoint when a single gap exceeds the threshold', () => {
+ // gap 0→100 = 100 > 50 → insert null at x=50
+ const data: uPlot.AlignedData = [
+ [0, 100],
+ [1, 2],
+ ];
+ const options: SeriesSpanGapsOption[] = [{ spanGaps: 50 }];
+
+ const result = insertLargeGapNullsIntoAlignedData(data, options);
+
+ expect(result[0]).toEqual([0, 50, 100]);
+ expect(result[1]).toEqual([1, null, 2]);
+ });
+
+ it('inserts nulls at every gap that exceeds the threshold', () => {
+ // gaps: 0→100=100, 100→110=10, 110→210=100; threshold=50
+ // → insert at 0→100 and 110→210
+ const data: uPlot.AlignedData = [
+ [0, 100, 110, 210],
+ [1, 2, 3, 4],
+ ];
+ const options: SeriesSpanGapsOption[] = [{ spanGaps: 50 }];
+
+ const result = insertLargeGapNullsIntoAlignedData(data, options);
+
+ expect(result[0]).toEqual([0, 50, 100, 110, 160, 210]);
+ expect(result[1]).toEqual([1, null, 2, 3, null, 4]);
+ });
+
+ it('inserts null for all series at a gap triggered by any one series', () => {
+ // series 0: threshold=50, gap=100 → triggers insertion
+ // series 1: threshold=200, gap=100 → would not trigger alone
+ // result: both series get null at the inserted x because the x-axis is shared
+ const data: uPlot.AlignedData = [
+ [0, 100],
+ [1, 2],
+ [3, 4],
+ ];
+ const options: SeriesSpanGapsOption[] = [
+ { spanGaps: 50 },
+ { spanGaps: 200 },
+ ];
+
+ const result = insertLargeGapNullsIntoAlignedData(data, options);
+
+ expect(result[0]).toEqual([0, 50, 100]);
+ expect(result[1]).toEqual([1, null, 2]);
+ expect(result[2]).toEqual([3, null, 4]);
+ });
+
+ it('ignores boolean spanGaps options (only numeric values trigger insertion)', () => {
+ const data: uPlot.AlignedData = [
+ [0, 100],
+ [1, 2],
+ ];
+ const options: SeriesSpanGapsOption[] = [{ spanGaps: true }];
+
+ const result = insertLargeGapNullsIntoAlignedData(data, options);
+
+ expect(result).toBe(data);
+ });
+
+ it('returns original data when series options array is empty', () => {
+ const data: uPlot.AlignedData = [
+ [0, 100],
+ [1, 2],
+ ];
+
+ const result = insertLargeGapNullsIntoAlignedData(data, []);
+
+ expect(result).toBe(data);
+ });
+
+ it('returns original data when there is only one x point', () => {
+ const data: uPlot.AlignedData = [[0], [1]];
+ const options: SeriesSpanGapsOption[] = [{ spanGaps: 10 }];
+
+ const result = insertLargeGapNullsIntoAlignedData(data, options);
+
+ expect(result).toBe(data);
+ });
+
+ it('preserves existing null values in the series alongside inserted ones', () => {
+ // original series already has a null; gap 0→100 also triggers insertion
+ const data: uPlot.AlignedData = [
+ [0, 100, 110],
+ [1, null, 2],
+ ];
+ const options: SeriesSpanGapsOption[] = [{ spanGaps: 50 }];
+
+ const result = insertLargeGapNullsIntoAlignedData(data, options);
+
+ expect(result[0]).toEqual([0, 50, 100, 110]);
+ expect(result[1]).toEqual([1, null, null, 2]);
+ });
+ });
+
+ describe('applySpanGapsToAlignedData', () => {
+ const xs: uPlot.AlignedData[0] = [0, 10, 20, 30];
+
+ it('returns original data when there are no series', () => {
+ const data: uPlot.AlignedData = [xs];
+ const result = applySpanGapsToAlignedData(data, []);
+
+ expect(result).toBe(data);
+ });
+
+ it('leaves data unchanged when spanGaps is undefined', () => {
+ const ys = [1, null, 2, null];
+ const data: uPlot.AlignedData = [xs, ys];
+ const options: SeriesSpanGapsOption[] = [{}];
+
+ const result = applySpanGapsToAlignedData(data, options);
+
+ expect(result[1]).toEqual(ys);
+ });
+
+ it('converts nulls to undefined when spanGaps is true', () => {
+ const ys = [1, null, 2, null];
+ const data: uPlot.AlignedData = [xs, ys];
+ const options: SeriesSpanGapsOption[] = [{ spanGaps: true }];
+
+ const result = applySpanGapsToAlignedData(data, options);
+
+ expect(result[1]).toEqual([1, undefined, 2, undefined]);
+ });
+
+ it('leaves data unchanged when spanGaps is false', () => {
+ const ys = [1, null, 2, null];
+ const data: uPlot.AlignedData = [xs, ys];
+ const options: SeriesSpanGapsOption[] = [{ spanGaps: false }];
+
+ const result = applySpanGapsToAlignedData(data, options);
+
+ expect(result[1]).toEqual(ys);
+ });
+
+ it('inserts a null break point when a gap exceeds the numeric threshold', () => {
+ // gap 0→100 = 100 > 50 → null inserted at midpoint x=50
+ const data: uPlot.AlignedData = [
+ [0, 100, 110],
+ [1, 2, 3],
+ ];
+ const options: SeriesSpanGapsOption[] = [{ spanGaps: 50 }];
+
+ const result = applySpanGapsToAlignedData(data, options);
+
+ expect(result[0]).toEqual([0, 50, 100, 110]);
+ expect(result[1]).toEqual([1, null, 2, 3]);
+ });
+
+ it('returns original data when no gap exceeds the numeric threshold', () => {
+ // all gaps = 10, threshold = 25 → no insertions
+ const data: uPlot.AlignedData = [xs, [1, 2, 3, 4]];
+ const options: SeriesSpanGapsOption[] = [{ spanGaps: 25 }];
+
+ const result = applySpanGapsToAlignedData(data, options);
+
+ expect(result).toBe(data);
+ });
+
+ it('applies both numeric gap insertion and boolean null-to-undefined in one pass', () => {
+ // series 0: spanGaps: 50 → gap 0→100 triggers a null break at midpoint x=50
+ // series 1: spanGaps: true → the inserted null at x=50 becomes undefined,
+ // so the line spans over it rather than breaking
+ const data: uPlot.AlignedData = [
+ [0, 100],
+ [1, 2],
+ [3, 4],
+ ];
+ const options: SeriesSpanGapsOption[] = [
+ { spanGaps: 50 },
+ { spanGaps: true },
+ ];
+
+ const result = applySpanGapsToAlignedData(data, options);
+
+ // x-axis extended with the inserted midpoint
+ expect(result[0]).toEqual([0, 50, 100]);
+ // series 0: null at midpoint breaks the line
+ expect(result[1]).toEqual([1, null, 2]);
+ // series 1: null at midpoint converted to undefined → line spans over it
+ expect(result[2]).toEqual([3, undefined, 4]);
+ });
+ });
});
diff --git a/frontend/src/lib/uPlotV2/utils/dataUtils.ts b/frontend/src/lib/uPlotV2/utils/dataUtils.ts
index 4aea802e37..74dc6d2d26 100644
--- a/frontend/src/lib/uPlotV2/utils/dataUtils.ts
+++ b/frontend/src/lib/uPlotV2/utils/dataUtils.ts
@@ -24,10 +24,10 @@ export function isInvalidPlotValue(value: unknown): boolean {
}
// Try to parse the string as a number
- const numValue = parseFloat(value);
+ const parsedNumber = parseFloat(value);
// If parsing failed or resulted in a non-finite number, it's invalid
- if (Number.isNaN(numValue) || !Number.isFinite(numValue)) {
+ if (Number.isNaN(parsedNumber) || !Number.isFinite(parsedNumber)) {
return true;
}
}
@@ -51,3 +51,178 @@ export function normalizePlotValue(
// Already a valid number
return value as number;
}
+
+export interface SeriesSpanGapsOption {
+ spanGaps?: boolean | number;
+}
+
+// Internal type alias: a series value array that may contain nulls/undefineds.
+// uPlot uses null to draw a visible gap and undefined to represent "no sample"
+// (the line continues across undefined points but breaks at null ones).
+type SeriesArray = Array<number | null | undefined>;
+
+/**
+ * Returns true if the given gap size exceeds the numeric spanGaps threshold
+ * of at least one series. Used to decide whether to insert a null break point.
+ */
+function gapExceedsThreshold(
+ gapSize: number,
+ seriesOptions: SeriesSpanGapsOption[],
+): boolean {
+ return seriesOptions.some(
+ ({ spanGaps }) =>
+ typeof spanGaps === 'number' && spanGaps > 0 && gapSize > spanGaps,
+ );
+}
+
+/**
+ * For each series with a numeric spanGaps threshold, insert a null data point
+ * between consecutive x timestamps whose gap exceeds the threshold.
+ *
+ * Why: uPlot draws a continuous line between all non-null points. When the
+ * time gap between two consecutive samples is larger than the configured
+ * spanGaps value, we inject a synthetic null at the midpoint so uPlot renders
+ * a visible break instead of a misleading straight line across the gap.
+ *
+ * Because uPlot's AlignedData shares a single x-axis across all series, a null
+ * is inserted for every series at each position where any series needs a break.
+ *
+ * Two-pass approach for performance:
+ * Pass 1 — count how many nulls will be inserted (no allocations).
+ * Pass 2 — fill pre-allocated output arrays by index (no push/reallocation).
+ */
+export function insertLargeGapNullsIntoAlignedData(
+ data: uPlot.AlignedData,
+ seriesOptions: SeriesSpanGapsOption[],
+): uPlot.AlignedData {
+ const [xValues, ...seriesValues] = data;
+
+ if (
+ !Array.isArray(xValues) ||
+ xValues.length < 2 ||
+ seriesValues.length === 0
+ ) {
+ return data;
+ }
+
+ const timestamps = xValues as number[];
+ const totalPoints = timestamps.length;
+
+ // Pass 1: count insertions needed so we know the exact output length.
+ // This lets us pre-allocate arrays rather than growing them dynamically.
+ let insertionCount = 0;
+ for (let i = 0; i < totalPoints - 1; i += 1) {
+ if (gapExceedsThreshold(timestamps[i + 1] - timestamps[i], seriesOptions)) {
+ insertionCount += 1;
+ }
+ }
+
+ // No gaps exceed any threshold — return the original data unchanged.
+ if (insertionCount === 0) {
+ return data;
+ }
+
+ // Pass 2: build output arrays of exact size and fill them.
+ // `writeIndex` is the write cursor into the output arrays.
+ const outputLen = totalPoints + insertionCount;
+ const newX = new Array<number>(outputLen);
+ const newSeries: SeriesArray[] = seriesValues.map(
+ () => new Array<number | null | undefined>(outputLen),
+ );
+
+ let writeIndex = 0;
+ for (let i = 0; i < totalPoints; i += 1) {
+ // Copy the real data point at position i
+ newX[writeIndex] = timestamps[i];
+ for (
+ let seriesIndex = 0;
+ seriesIndex < seriesValues.length;
+ seriesIndex += 1
+ ) {
+ newSeries[seriesIndex][writeIndex] = (seriesValues[
+ seriesIndex
+ ] as SeriesArray)[i];
+ }
+ writeIndex += 1;
+
+ // If the gap to the next x timestamp exceeds the threshold, insert a
+ // synthetic null at the midpoint. The midpoint x is placed halfway
+ // between timestamps[i] and timestamps[i+1] (minimum 1 unit past timestamps[i] to stay unique).
+ if (
+ i < totalPoints - 1 &&
+ gapExceedsThreshold(timestamps[i + 1] - timestamps[i], seriesOptions)
+ ) {
+ newX[writeIndex] =
+ timestamps[i] +
+ Math.max(1, Math.floor((timestamps[i + 1] - timestamps[i]) / 2));
+ for (
+ let seriesIndex = 0;
+ seriesIndex < seriesValues.length;
+ seriesIndex += 1
+ ) {
+ newSeries[seriesIndex][writeIndex] = null; // null tells uPlot to break the line here
+ }
+ writeIndex += 1;
+ }
+ }
+
+ return [newX, ...newSeries] as uPlot.AlignedData;
+}
+
+/**
+ * Apply per-series spanGaps (boolean | number) handling to an aligned dataset.
+ *
+ * spanGaps controls how uPlot handles gaps in a series:
+ * - boolean true → convert null → undefined so uPlot spans over every gap
+ * (draws a continuous line, skipping missing samples)
+ * - boolean false → no change; nulls render as visible breaks (default)
+ * - number → insert a null break point between any two consecutive
+ * timestamps whose difference exceeds the threshold;
+ * gaps smaller than the threshold are left as-is
+ *
+ * The input data is expected to be of the form:
+ * [xValues, series1Values, series2Values, ...]
+ */
+export function applySpanGapsToAlignedData(
+ data: uPlot.AlignedData,
+ seriesOptions: SeriesSpanGapsOption[],
+): uPlot.AlignedData {
+ const [xValues, ...seriesValues] = data;
+
+ if (!Array.isArray(xValues) || seriesValues.length === 0) {
+ return data;
+ }
+
+ // Numeric spanGaps: operates on the whole dataset at once because inserting
+ // null break points requires modifying the shared x-axis.
+ const hasNumericSpanGaps = seriesOptions.some(
+ ({ spanGaps }) => typeof spanGaps === 'number',
+ );
+ const gapProcessed = hasNumericSpanGaps
+ ? insertLargeGapNullsIntoAlignedData(data, seriesOptions)
+ : data;
+
+ // Boolean spanGaps === true: convert null → undefined per series so uPlot
+ // draws a continuous line across missing samples instead of breaking it.
+ // Skip this pass entirely if no series uses spanGaps: true.
+ const hasBooleanTrue = seriesOptions.some(({ spanGaps }) => spanGaps === true);
+ if (!hasBooleanTrue) {
+ return gapProcessed;
+ }
+
+ const [newX, ...newSeries] = gapProcessed;
+ const transformedSeries = newSeries.map((yValues, seriesIndex) => {
+ const { spanGaps } = seriesOptions[seriesIndex] ?? {};
+ if (spanGaps !== true) {
+ // This series doesn't use spanGaps: true — leave it unchanged.
+ return yValues;
+ }
+ // Replace null with undefined: uPlot skips undefined points without
+ // breaking the line, effectively spanning over the gap.
+ return (yValues as SeriesArray).map((pointValue) =>
+ pointValue === null ? undefined : pointValue,
+ ) as uPlot.AlignedData[0];
+ });
+
+ return [newX, ...transformedSeries] as uPlot.AlignedData;
+}
diff --git a/frontend/src/types/api/dashboard/getAll.ts b/frontend/src/types/api/dashboard/getAll.ts
index c55dd2a31c..4110f03481 100644
--- a/frontend/src/types/api/dashboard/getAll.ts
+++ b/frontend/src/types/api/dashboard/getAll.ts
@@ -141,6 +141,7 @@ export interface IBaseWidget {
showPoints?: boolean;
lineStyle?: LineStyle;
fillMode?: FillMode;
+ spanGaps?: boolean | number;
}
export interface Widgets extends IBaseWidget {
query: Query;