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 new histogram panel component (#10278)

Abhi kumar9b3d3453b12b
diff --git a/frontend/src/container/DashboardContainer/visualization/charts/ChartWrapper/ChartWrapper.tsx b/frontend/src/container/DashboardContainer/visualization/charts/ChartWrapper/ChartWrapper.tsx
index 79f2e117a7..aa1a34f67c 100644
--- a/frontend/src/container/DashboardContainer/visualization/charts/ChartWrapper/ChartWrapper.tsx
+++ b/frontend/src/container/DashboardContainer/visualization/charts/ChartWrapper/ChartWrapper.tsx
@@ -23,6 +23,7 @@ export default function ChartWrapper({
width: containerWidth,
height: containerHeight,
showTooltip = true,
+ showLegend = true,
canPinTooltip = false,
syncMode,
syncKey,
@@ -36,6 +37,9 @@ export default function ChartWrapper({
const legendComponent = useCallback(
(averageLegendWidth: number): React.ReactNode => {
+ if (!showLegend) {
+ return null;
+ }
return (
<Legend
config={config}
@@ -44,7 +48,7 @@ export default function ChartWrapper({
/>
);
},
- [config, legendConfig.position],
+ [config, legendConfig.position, showLegend],
);
const renderTooltipCallback = useCallback(
@@ -60,6 +64,7 @@ export default function ChartWrapper({
return (
<PlotContextProvider>
<ChartLayout
+ showLegend={showLegend}
config={config}
containerWidth={containerWidth}
containerHeight={containerHeight}
diff --git a/frontend/src/container/DashboardContainer/visualization/charts/Histogram/Histogram.tsx b/frontend/src/container/DashboardContainer/visualization/charts/Histogram/Histogram.tsx
new file mode 100644
index 0000000000..550546b27d
--- /dev/null
+++ b/frontend/src/container/DashboardContainer/visualization/charts/Histogram/Histogram.tsx
@@ -0,0 +1,55 @@
+import { useCallback } from 'react';
+import ChartWrapper from 'container/DashboardContainer/visualization/charts/ChartWrapper/ChartWrapper';
+import HistogramTooltip from 'lib/uPlotV2/components/Tooltip/HistogramTooltip';
+import { buildTooltipContent } from 'lib/uPlotV2/components/Tooltip/utils';
+import {
+ HistogramTooltipProps,
+ TooltipRenderArgs,
+} from 'lib/uPlotV2/components/types';
+
+import { HistogramChartProps } from '../types';
+
+export default function Histogram(props: HistogramChartProps): JSX.Element {
+ const {
+ children,
+ renderTooltip: customRenderTooltip,
+ isQueriesMerged,
+ ...rest
+ } = props;
+
+ const renderTooltip = useCallback(
+ (props: TooltipRenderArgs): React.ReactNode => {
+ if (customRenderTooltip) {
+ return customRenderTooltip(props);
+ }
+ const content = buildTooltipContent({
+ data: props.uPlotInstance.data,
+ series: props.uPlotInstance.series,
+ dataIndexes: props.dataIndexes,
+ activeSeriesIndex: props.seriesIndex,
+ uPlotInstance: props.uPlotInstance,
+ yAxisUnit: rest.yAxisUnit ?? '',
+ decimalPrecision: rest.decimalPrecision,
+ });
+ const tooltipProps: HistogramTooltipProps = {
+ ...props,
+ timezone: rest.timezone,
+ yAxisUnit: rest.yAxisUnit,
+ decimalPrecision: rest.decimalPrecision,
+ content,
+ };
+ return <HistogramTooltip {...tooltipProps} />;
+ },
+ [customRenderTooltip, rest.timezone, rest.yAxisUnit, rest.decimalPrecision],
+ );
+
+ return (
+ <ChartWrapper
+ showLegend={!isQueriesMerged}
+ {...rest}
+ renderTooltip={renderTooltip}
+ >
+ {children}
+ </ChartWrapper>
+ );
+}
diff --git a/frontend/src/container/DashboardContainer/visualization/charts/types.ts b/frontend/src/container/DashboardContainer/visualization/charts/types.ts
index 89f5f31868..56c4f8c8d0 100644
--- a/frontend/src/container/DashboardContainer/visualization/charts/types.ts
+++ b/frontend/src/container/DashboardContainer/visualization/charts/types.ts
@@ -7,6 +7,7 @@ interface BaseChartProps {
width: number;
height: number;
showTooltip?: boolean;
+ showLegend?: boolean;
timezone: string;
canPinTooltip?: boolean;
yAxisUnit?: string;
@@ -17,6 +18,7 @@ interface BaseChartProps {
interface UPlotBasedChartProps {
config: UPlotConfigBuilder;
data: uPlot.AlignedData;
+ legendConfig: LegendConfig;
syncMode?: DashboardCursorSync;
syncKey?: string;
plotRef?: (plot: uPlot | null) => void;
@@ -26,14 +28,20 @@ interface UPlotBasedChartProps {
}
export interface TimeSeriesChartProps
+ extends BaseChartProps,
+ UPlotBasedChartProps {}
+
+export interface HistogramChartProps
extends BaseChartProps,
UPlotBasedChartProps {
- legendConfig: LegendConfig;
+ isQueriesMerged?: boolean;
}
export interface BarChartProps extends BaseChartProps, UPlotBasedChartProps {
- legendConfig: LegendConfig;
isStackedBarChart?: boolean;
}
-export type ChartProps = TimeSeriesChartProps | BarChartProps;
+export type ChartProps =
+ | TimeSeriesChartProps
+ | BarChartProps
+ | HistogramChartProps;
diff --git a/frontend/src/container/DashboardContainer/visualization/hooks/__tests__/useScrollWidgetIntoView.test.ts b/frontend/src/container/DashboardContainer/visualization/hooks/__tests__/useScrollWidgetIntoView.test.ts
new file mode 100644
index 0000000000..c4b8cfe2f7
--- /dev/null
+++ b/frontend/src/container/DashboardContainer/visualization/hooks/__tests__/useScrollWidgetIntoView.test.ts
@@ -0,0 +1,69 @@
+import { renderHook } from '@testing-library/react';
+import { useDashboard } from 'providers/Dashboard/Dashboard';
+
+import { useScrollWidgetIntoView } from '../useScrollWidgetIntoView';
+
+jest.mock('providers/Dashboard/Dashboard');
+
+type MockHTMLElement = {
+ scrollIntoView: jest.Mock;
+ focus: jest.Mock;
+};
+
+function createMockElement(): MockHTMLElement {
+ return {
+ scrollIntoView: jest.fn(),
+ focus: jest.fn(),
+ };
+}
+
+describe('useScrollWidgetIntoView', () => {
+ const mockedUseDashboard = useDashboard as jest.MockedFunction<
+ typeof useDashboard
+ >;
+
+ beforeEach(() => {
+ jest.clearAllMocks();
+ });
+
+ it('scrolls into view and focuses when toScrollWidgetId matches widget id', () => {
+ const setToScrollWidgetId = jest.fn();
+ const mockElement = createMockElement();
+ const ref = ({
+ current: mockElement,
+ } as unknown) as React.RefObject<HTMLDivElement>;
+
+ mockedUseDashboard.mockReturnValue(({
+ toScrollWidgetId: 'widget-id',
+ setToScrollWidgetId,
+ } as unknown) as ReturnType<typeof useDashboard>);
+
+ renderHook(() => useScrollWidgetIntoView('widget-id', ref));
+
+ expect(mockElement.scrollIntoView).toHaveBeenCalledWith({
+ behavior: 'smooth',
+ block: 'center',
+ });
+ expect(mockElement.focus).toHaveBeenCalled();
+ expect(setToScrollWidgetId).toHaveBeenCalledWith('');
+ });
+
+ it('does nothing when toScrollWidgetId does not match widget id', () => {
+ const setToScrollWidgetId = jest.fn();
+ const mockElement = createMockElement();
+ const ref = ({
+ current: mockElement,
+ } as unknown) as React.RefObject<HTMLDivElement>;
+
+ mockedUseDashboard.mockReturnValue(({
+ toScrollWidgetId: 'other-widget',
+ setToScrollWidgetId,
+ } as unknown) as ReturnType<typeof useDashboard>);
+
+ renderHook(() => useScrollWidgetIntoView('widget-id', ref));
+
+ expect(mockElement.scrollIntoView).not.toHaveBeenCalled();
+ expect(mockElement.focus).not.toHaveBeenCalled();
+ expect(setToScrollWidgetId).not.toHaveBeenCalled();
+ });
+});
diff --git a/frontend/src/container/DashboardContainer/visualization/hooks/useScrollWidgetIntoView.ts b/frontend/src/container/DashboardContainer/visualization/hooks/useScrollWidgetIntoView.ts
new file mode 100644
index 0000000000..7f5e78bbfc
--- /dev/null
+++ b/frontend/src/container/DashboardContainer/visualization/hooks/useScrollWidgetIntoView.ts
@@ -0,0 +1,26 @@
+import { RefObject, useEffect } from 'react';
+import { useDashboard } from 'providers/Dashboard/Dashboard';
+
+/**
+ * Scrolls the given widget container into view when the dashboard
+ * requests it via `toScrollWidgetId`.
+ *
+ * Intended for use in panel components that render a single widget.
+ */
+export function useScrollWidgetIntoView<T extends HTMLElement>(
+ widgetId: string,
+ widgetContainerRef: RefObject<T>,
+): void {
+ const { toScrollWidgetId, setToScrollWidgetId } = useDashboard();
+
+ useEffect(() => {
+ if (toScrollWidgetId === widgetId) {
+ widgetContainerRef.current?.scrollIntoView({
+ behavior: 'smooth',
+ block: 'center',
+ });
+ widgetContainerRef.current?.focus();
+ setToScrollWidgetId('');
+ }
+ }, [toScrollWidgetId, setToScrollWidgetId, widgetId, widgetContainerRef]);
+}
diff --git a/frontend/src/container/DashboardContainer/visualization/layout/ChartLayout/ChartLayout.tsx b/frontend/src/container/DashboardContainer/visualization/layout/ChartLayout/ChartLayout.tsx
index 4c1a4f0004..5ae8967a71 100644
--- a/frontend/src/container/DashboardContainer/visualization/layout/ChartLayout/ChartLayout.tsx
+++ b/frontend/src/container/DashboardContainer/visualization/layout/ChartLayout/ChartLayout.tsx
@@ -1,12 +1,14 @@
import { useMemo } from 'react';
import cx from 'classnames';
import { calculateChartDimensions } from 'container/DashboardContainer/visualization/charts/utils';
+import { MAX_LEGEND_WIDTH } from 'lib/uPlotV2/components/Legend/Legend';
import { LegendConfig, LegendPosition } from 'lib/uPlotV2/components/types';
import { UPlotConfigBuilder } from 'lib/uPlotV2/config/UPlotConfigBuilder';
import './ChartLayout.styles.scss';
export interface ChartLayoutProps {
+ showLegend?: boolean;
legendComponent: (legendPerSet: number) => React.ReactNode;
children: (props: {
chartWidth: number;
@@ -20,6 +22,7 @@ export interface ChartLayoutProps {
config: UPlotConfigBuilder;
}
export default function ChartLayout({
+ showLegend = true,
legendComponent,
children,
layoutChildren,
@@ -30,6 +33,15 @@ export default function ChartLayout({
}: ChartLayoutProps): JSX.Element {
const chartDimensions = useMemo(
() => {
+ if (!showLegend) {
+ return {
+ width: containerWidth,
+ height: containerHeight,
+ legendWidth: 0,
+ legendHeight: 0,
+ averageLegendWidth: MAX_LEGEND_WIDTH,
+ };
+ }
const legendItemsMap = config.getLegendItems();
const seriesLabels = Object.values(legendItemsMap)
.map((item) => item.label)
@@ -42,7 +54,7 @@ export default function ChartLayout({
});
},
// eslint-disable-next-line react-hooks/exhaustive-deps
- [containerWidth, containerHeight, legendConfig],
+ [containerWidth, containerHeight, legendConfig, showLegend],
);
return (
@@ -60,15 +72,17 @@ export default function ChartLayout({
averageLegendWidth: chartDimensions.averageLegendWidth,
})}
</div>
- <div
- className="chart-layout__legend-wrapper"
- style={{
- height: chartDimensions.legendHeight,
- width: chartDimensions.legendWidth,
- }}
- >
- {legendComponent(chartDimensions.averageLegendWidth)}
- </div>
+ {showLegend && (
+ <div
+ className="chart-layout__legend-wrapper"
+ style={{
+ height: chartDimensions.legendHeight,
+ width: chartDimensions.legendWidth,
+ }}
+ >
+ {legendComponent(chartDimensions.averageLegendWidth)}
+ </div>
+ )}
</div>
{layoutChildren}
</div>
diff --git a/frontend/src/container/DashboardContainer/visualization/panels/BarPanel/BarPanel.tsx b/frontend/src/container/DashboardContainer/visualization/panels/BarPanel/BarPanel.tsx
index 19726099a6..c8795879ee 100644
--- a/frontend/src/container/DashboardContainer/visualization/panels/BarPanel/BarPanel.tsx
+++ b/frontend/src/container/DashboardContainer/visualization/panels/BarPanel/BarPanel.tsx
@@ -1,10 +1,10 @@
import { useCallback, useEffect, useMemo, useRef, useState } from 'react';
+import { useScrollWidgetIntoView } from 'container/DashboardContainer/visualization/hooks/useScrollWidgetIntoView';
import { PanelWrapperProps } from 'container/PanelWrapper/panelWrapper.types';
import { useIsDarkMode } from 'hooks/useDarkMode';
import { useResizeObserver } from 'hooks/useDimensions';
import { LegendPosition } from 'lib/uPlotV2/components/types';
import ContextMenu from 'periscope/components/ContextMenu';
-import { useDashboard } from 'providers/Dashboard/Dashboard';
import { useTimezone } from 'providers/Timezone';
import { MetricRangePayloadProps } from 'types/api/metrics/getQueryRange';
import uPlot from 'uplot';
@@ -27,7 +27,6 @@ function BarPanel(props: PanelWrapperProps): JSX.Element {
onToggleModelHandler,
} = props;
const uPlotRef = useRef<uPlot | null>(null);
- const { toScrollWidgetId, setToScrollWidgetId } = useDashboard();
const graphRef = useRef<HTMLDivElement>(null);
const [minTimeScale, setMinTimeScale] = useState<number>();
const [maxTimeScale, setMaxTimeScale] = useState<number>();
@@ -36,16 +35,7 @@ function BarPanel(props: PanelWrapperProps): JSX.Element {
const isDarkMode = useIsDarkMode();
const { timezone } = useTimezone();
- useEffect(() => {
- if (toScrollWidgetId === widget.id) {
- graphRef.current?.scrollIntoView({
- behavior: 'smooth',
- block: 'center',
- });
- graphRef.current?.focus();
- setToScrollWidgetId('');
- }
- }, [toScrollWidgetId, setToScrollWidgetId, widget.id]);
+ useScrollWidgetIntoView(widget.id, graphRef);
useEffect((): void => {
const { startTime, endTime } = getTimeRange(queryResponse);
diff --git a/frontend/src/container/DashboardContainer/visualization/panels/HistogramPanel/HistogramPanel.tsx b/frontend/src/container/DashboardContainer/visualization/panels/HistogramPanel/HistogramPanel.tsx
new file mode 100644
index 0000000000..986c911073
--- /dev/null
+++ b/frontend/src/container/DashboardContainer/visualization/panels/HistogramPanel/HistogramPanel.tsx
@@ -0,0 +1,113 @@
+import { useMemo, useRef } from 'react';
+import { useScrollWidgetIntoView } from 'container/DashboardContainer/visualization/hooks/useScrollWidgetIntoView';
+import { PanelWrapperProps } from 'container/PanelWrapper/panelWrapper.types';
+import { useIsDarkMode } from 'hooks/useDarkMode';
+import { useResizeObserver } from 'hooks/useDimensions';
+import { LegendPosition } from 'lib/uPlotV2/components/types';
+import { DashboardCursorSync } from 'lib/uPlotV2/plugins/TooltipPlugin/types';
+import { useTimezone } from 'providers/Timezone';
+import { MetricRangePayloadProps } from 'types/api/metrics/getQueryRange';
+import uPlot from 'uplot';
+
+import Histogram from '../../charts/Histogram/Histogram';
+import ChartManager from '../../components/ChartManager/ChartManager';
+import {
+ prepareHistogramPanelConfig,
+ prepareHistogramPanelData,
+} from './utils';
+
+import '../Panel.styles.scss';
+
+function HistogramPanel(props: PanelWrapperProps): JSX.Element {
+ const {
+ panelMode,
+ queryResponse,
+ widget,
+ isFullViewMode,
+ onToggleModelHandler,
+ } = props;
+ const uPlotRef = useRef<uPlot | null>(null);
+ const graphRef = useRef<HTMLDivElement>(null);
+ const containerDimensions = useResizeObserver(graphRef);
+
+ const isDarkMode = useIsDarkMode();
+ const { timezone } = useTimezone();
+
+ useScrollWidgetIntoView(widget.id, graphRef);
+
+ const config = useMemo(() => {
+ return prepareHistogramPanelConfig({
+ widget,
+ isDarkMode,
+ apiResponse: queryResponse?.data?.payload as MetricRangePayloadProps,
+ panelMode,
+ });
+ }, [widget, isDarkMode, queryResponse?.data?.payload, panelMode]);
+
+ const chartData = useMemo(() => {
+ if (!queryResponse?.data?.payload) {
+ return [];
+ }
+ return prepareHistogramPanelData({
+ apiResponse: queryResponse?.data?.payload as MetricRangePayloadProps,
+ bucketWidth: widget?.bucketWidth,
+ bucketCount: widget?.bucketCount,
+ mergeAllActiveQueries: widget?.mergeAllActiveQueries,
+ });
+ }, [
+ queryResponse?.data?.payload,
+ widget?.bucketWidth,
+ widget?.bucketCount,
+ widget?.mergeAllActiveQueries,
+ ]);
+
+ const layoutChildren = useMemo(() => {
+ if (!isFullViewMode) {
+ return null;
+ }
+ return (
+ <ChartManager
+ config={config}
+ alignedData={chartData}
+ yAxisUnit={widget.yAxisUnit}
+ onCancel={onToggleModelHandler}
+ />
+ );
+ }, [
+ isFullViewMode,
+ config,
+ chartData,
+ widget.yAxisUnit,
+ onToggleModelHandler,
+ ]);
+
+ return (
+ <div className="panel-container" ref={graphRef}>
+ {containerDimensions.width > 0 && containerDimensions.height > 0 && (
+ <Histogram
+ config={config}
+ legendConfig={{
+ position: widget?.legendPosition ?? LegendPosition.BOTTOM,
+ }}
+ plotRef={(plot: uPlot | null): void => {
+ uPlotRef.current = plot;
+ }}
+ onDestroy={(): void => {
+ uPlotRef.current = null;
+ }}
+ isQueriesMerged={widget.mergeAllActiveQueries}
+ yAxisUnit={widget.yAxisUnit}
+ decimalPrecision={widget.decimalPrecision}
+ syncMode={DashboardCursorSync.Crosshair}
+ timezone={timezone.value}
+ data={chartData as uPlot.AlignedData}
+ width={containerDimensions.width}
+ height={containerDimensions.height}
+ layoutChildren={layoutChildren}
+ />
+ )}
+ </div>
+ );
+}
+
+export default HistogramPanel;
diff --git a/frontend/src/container/DashboardContainer/visualization/panels/HistogramPanel/utils.ts b/frontend/src/container/DashboardContainer/visualization/panels/HistogramPanel/utils.ts
new file mode 100644
index 0000000000..6839059cae
--- /dev/null
+++ b/frontend/src/container/DashboardContainer/visualization/panels/HistogramPanel/utils.ts
@@ -0,0 +1,231 @@
+import { histogramBucketSizes } from '@grafana/data';
+import { PANEL_TYPES } from 'constants/queryBuilder';
+import { DEFAULT_BUCKET_COUNT } from 'container/PanelWrapper/constants';
+import { getLegend } from 'lib/dashboard/getQueryResults';
+import getLabelName from 'lib/getLabelName';
+import { DrawStyle } from 'lib/uPlotV2/config/types';
+import { UPlotConfigBuilder } from 'lib/uPlotV2/config/UPlotConfigBuilder';
+import { Widgets } from 'types/api/dashboard/getAll';
+import { MetricRangePayloadProps } from 'types/api/metrics/getQueryRange';
+import { AlignedData } from 'uplot';
+import { incrRoundDn, roundDecimals } from 'utils/round';
+
+import { PanelMode } from '../types';
+import { buildBaseConfig } from '../utils/baseConfigBuilder';
+import {
+ buildHistogramBuckets,
+ mergeAlignedDataTables,
+ prependNullBinToFirstHistogramSeries,
+ replaceUndefinedWithNullInAlignedData,
+} from '../utils/histogram';
+
+export interface PrepareHistogramPanelDataParams {
+ apiResponse: MetricRangePayloadProps;
+ bucketWidth?: number;
+ bucketCount?: number;
+ mergeAllActiveQueries?: boolean;
+}
+
+const BUCKET_OFFSET = 0;
+const HIST_SORT = (a: number, b: number): number => a - b;
+
+function extractNumericValues(
+ result: MetricRangePayloadProps['data']['result'],
+): number[] {
+ const values: number[] = [];
+ for (const item of result) {
+ for (const [, valueStr] of item.values) {
+ values.push(Number.parseFloat(valueStr) || 0);
+ }
+ }
+ return values;
+}
+
+function computeSmallestDelta(sortedValues: number[]): number {
+ if (sortedValues.length <= 1) {
+ return 0;
+ }
+ let smallest = Infinity;
+ for (let i = 1; i < sortedValues.length; i++) {
+ const delta = sortedValues[i] - sortedValues[i - 1];
+ if (delta > 0) {
+ smallest = Math.min(smallest, delta);
+ }
+ }
+ return smallest === Infinity ? 0 : smallest;
+}
+
+function selectBucketSize({
+ range,
+ bucketCount,
+ smallestDelta,
+ bucketWidthOverride,
+}: {
+ range: number;
+ bucketCount: number;
+ smallestDelta: number;
+ bucketWidthOverride?: number;
+}): number {
+ if (bucketWidthOverride != null && bucketWidthOverride > 0) {
+ return bucketWidthOverride;
+ }
+ const targetSize = range / bucketCount;
+ for (const candidate of histogramBucketSizes) {
+ if (targetSize < candidate && candidate >= smallestDelta) {
+ return candidate;
+ }
+ }
+ return 0;
+}
+
+function buildFrames(
+ result: MetricRangePayloadProps['data']['result'],
+ mergeAllActiveQueries: boolean,
+): number[][] {
+ const frames: number[][] = result.map((item) =>
+ item.values.map(([, valueStr]) => Number.parseFloat(valueStr) || 0),
+ );
+ if (mergeAllActiveQueries && frames.length > 1) {
+ const first = frames[0];
+ for (let i = 1; i < frames.length; i++) {
+ first.push(...frames[i]);
+ frames[i] = [];
+ }
+ }
+ return frames;
+}
+
+export function prepareHistogramPanelData({
+ apiResponse,
+ bucketWidth,
+ bucketCount: bucketCountProp = DEFAULT_BUCKET_COUNT,
+ mergeAllActiveQueries = false,
+}: PrepareHistogramPanelDataParams): AlignedData {
+ const bucketCount = bucketCountProp ?? DEFAULT_BUCKET_COUNT;
+ const result = apiResponse.data.result;
+
+ const seriesValues = extractNumericValues(result);
+ if (seriesValues.length === 0) {
+ return [[]];
+ }
+
+ const sorted = [...seriesValues].sort((a, b) => a - b);
+ const min = sorted[0];
+ const max = sorted[sorted.length - 1];
+ const range = max - min;
+ const smallestDelta = computeSmallestDelta(sorted);
+ let bucketSize = selectBucketSize({
+ range,
+ bucketCount,
+ smallestDelta,
+ bucketWidthOverride: bucketWidth,
+ });
+ if (bucketSize <= 0) {
+ bucketSize = range > 0 ? range / bucketCount : 1;
+ }
+
+ const getBucket = (v: number): number =>
+ roundDecimals(incrRoundDn(v - BUCKET_OFFSET, bucketSize) + BUCKET_OFFSET, 9);
+
+ const frames = buildFrames(result, mergeAllActiveQueries);
+ const histogramsPerSeries: AlignedData[] = frames
+ .filter((frame) => frame.length > 0)
+ .map((frame) => buildHistogramBuckets(frame, getBucket, HIST_SORT));
+
+ if (histogramsPerSeries.length === 0) {
+ return [[]];
+ }
+
+ const mergedHistogramData = mergeAlignedDataTables(histogramsPerSeries);
+ replaceUndefinedWithNullInAlignedData(mergedHistogramData);
+ prependNullBinToFirstHistogramSeries(mergedHistogramData, bucketSize);
+ return mergedHistogramData;
+}
+
+export function prepareHistogramPanelConfig({
+ widget,
+ apiResponse,
+ panelMode,
+ isDarkMode,
+}: {
+ widget: Widgets;
+ apiResponse: MetricRangePayloadProps;
+ panelMode: PanelMode;
+ isDarkMode: boolean;
+}): UPlotConfigBuilder {
+ const builder = buildBaseConfig({
+ widget,
+ isDarkMode,
+ apiResponse,
+ panelMode,
+ panelType: PANEL_TYPES.HISTOGRAM,
+ });
+ builder.setCursor({
+ drag: {
+ x: false,
+ y: false,
+ setScale: true,
+ },
+ focus: {
+ prox: 1e3,
+ },
+ });
+
+ builder.addScale({
+ scaleKey: 'x',
+ time: false,
+ auto: true,
+ });
+ builder.addScale({
+ scaleKey: 'y',
+ time: false,
+ auto: true,
+ min: 0,
+ });
+
+ const currentQuery = widget.query;
+ const mergeAllActiveQueries = widget?.mergeAllActiveQueries ?? false;
+
+ // When merged, data has only one y column; add one series to match. Otherwise add one per result.
+ if (mergeAllActiveQueries) {
+ builder.addSeries({
+ label: '',
+ scaleKey: 'y',
+ drawStyle: DrawStyle.Bar,
+ panelType: PANEL_TYPES.HISTOGRAM,
+ colorMapping: widget.customLegendColors ?? {},
+ spanGaps: false,
+ barWidthFactor: 1,
+ pointSize: 5,
+ lineColor: '#3f5ecc',
+ fillColor: '#4E74F8',
+ isDarkMode,
+ });
+ } else {
+ apiResponse.data.result.forEach((series) => {
+ const baseLabelName = getLabelName(
+ series.metric,
+ series.queryName || '', // query
+ series.legend || '',
+ );
+
+ const label = currentQuery
+ ? getLegend(series, currentQuery, baseLabelName)
+ : baseLabelName;
+
+ builder.addSeries({
+ label: label,
+ scaleKey: 'y',
+ drawStyle: DrawStyle.Bar,
+ panelType: PANEL_TYPES.HISTOGRAM,
+ colorMapping: widget.customLegendColors ?? {},
+ spanGaps: false,
+ barWidthFactor: 1,
+ pointSize: 5,
+ isDarkMode,
+ });
+ });
+ }
+
+ return builder;
+}
diff --git a/frontend/src/container/DashboardContainer/visualization/panels/TimeSeriesPanel/TimeSeriesPanel.tsx b/frontend/src/container/DashboardContainer/visualization/panels/TimeSeriesPanel/TimeSeriesPanel.tsx
index cede91e5c7..307f393337 100644
--- a/frontend/src/container/DashboardContainer/visualization/panels/TimeSeriesPanel/TimeSeriesPanel.tsx
+++ b/frontend/src/container/DashboardContainer/visualization/panels/TimeSeriesPanel/TimeSeriesPanel.tsx
@@ -2,12 +2,12 @@ import { useEffect, useMemo, useRef, useState } from 'react';
import TimeSeries from 'container/DashboardContainer/visualization/charts/TimeSeries/TimeSeries';
import ChartManager from 'container/DashboardContainer/visualization/components/ChartManager/ChartManager';
import { usePanelContextMenu } from 'container/DashboardContainer/visualization/hooks/usePanelContextMenu';
+import { useScrollWidgetIntoView } from 'container/DashboardContainer/visualization/hooks/useScrollWidgetIntoView';
import { PanelWrapperProps } from 'container/PanelWrapper/panelWrapper.types';
import { useIsDarkMode } from 'hooks/useDarkMode';
import { useResizeObserver } from 'hooks/useDimensions';
import { LegendPosition } from 'lib/uPlotV2/components/types';
import { ContextMenu } from 'periscope/components/ContextMenu';
-import { useDashboard } from 'providers/Dashboard/Dashboard';
import { useTimezone } from 'providers/Timezone';
import { MetricRangePayloadProps } from 'types/api/metrics/getQueryRange';
import uPlot from 'uplot';
@@ -26,7 +26,6 @@ function TimeSeriesPanel(props: PanelWrapperProps): JSX.Element {
isFullViewMode,
onToggleModelHandler,
} = props;
- const { toScrollWidgetId, setToScrollWidgetId } = useDashboard();
const graphRef = useRef<HTMLDivElement>(null);
const [minTimeScale, setMinTimeScale] = useState<number>();
const [maxTimeScale, setMaxTimeScale] = useState<number>();
@@ -35,16 +34,7 @@ function TimeSeriesPanel(props: PanelWrapperProps): JSX.Element {
const isDarkMode = useIsDarkMode();
const { timezone } = useTimezone();
- useEffect(() => {
- if (toScrollWidgetId === widget.id) {
- graphRef.current?.scrollIntoView({
- behavior: 'smooth',
- block: 'center',
- });
- graphRef.current?.focus();
- setToScrollWidgetId('');
- }
- }, [toScrollWidgetId, setToScrollWidgetId, widget.id]);
+ useScrollWidgetIntoView(widget.id, graphRef);
useEffect((): void => {
const { startTime, endTime } = getTimeRange(queryResponse);
diff --git a/frontend/src/container/DashboardContainer/visualization/panels/utils/baseConfigBuilder.ts b/frontend/src/container/DashboardContainer/visualization/panels/utils/baseConfigBuilder.ts
index fa643e1d82..0d6ed75fde 100644
--- a/frontend/src/container/DashboardContainer/visualization/panels/utils/baseConfigBuilder.ts
+++ b/frontend/src/container/DashboardContainer/visualization/panels/utils/baseConfigBuilder.ts
@@ -19,9 +19,9 @@ export interface BaseConfigBuilderProps {
widget: Widgets;
apiResponse: MetricRangePayloadProps;
isDarkMode: boolean;
- onClick: OnClickPluginOpts['onClick'];
- onDragSelect: (startTime: number, endTime: number) => void;
- timezone: Timezone;
+ onClick?: OnClickPluginOpts['onClick'];
+ onDragSelect?: (startTime: number, endTime: number) => void;
+ timezone?: Timezone;
panelMode: PanelMode;
panelType: PANEL_TYPES;
minTimeScale?: number;
@@ -40,8 +40,10 @@ export function buildBaseConfig({
minTimeScale,
maxTimeScale,
}: BaseConfigBuilderProps): UPlotConfigBuilder {
- const tzDate = (timestamp: number): Date =>
- uPlot.tzDate(new Date(timestamp * 1e3), timezone.value);
+ const tzDate = timezone
+ ? (timestamp: number): Date =>
+ uPlot.tzDate(new Date(timestamp * 1e3), timezone.value)
+ : undefined;
const builder = new UPlotConfigBuilder({
onDragSelect,
diff --git a/frontend/src/container/DashboardContainer/visualization/panels/utils/histogram.ts b/frontend/src/container/DashboardContainer/visualization/panels/utils/histogram.ts
new file mode 100644
index 0000000000..c120c3284b
--- /dev/null
+++ b/frontend/src/container/DashboardContainer/visualization/panels/utils/histogram.ts
@@ -0,0 +1,225 @@
+import {
+ NULL_EXPAND,
+ NULL_REMOVE,
+ NULL_RETAIN,
+} from 'container/PanelWrapper/constants';
+import { AlignedData } from 'uplot';
+
+/**
+ * Expands contiguous runs of `null` values to the left and right of their
+ * original positions so that visual gaps in the series are continuous.
+ *
+ * This is used when `NULL_EXPAND` mode is selected while joining series.
+ */
+function propagateNullsAcrossNeighbors(
+ seriesValues: Array<number | null>,
+ nullIndices: number[],
+ alignedLength: number,
+): void {
+ for (
+ let i = 0, currentIndex, lastExpandedNullIndex = -1;
+ i < nullIndices.length;
+ i++
+ ) {
+ const nullIndex = nullIndices[i];
+
+ if (nullIndex > lastExpandedNullIndex) {
+ // expand left until we hit a non-null value
+ currentIndex = nullIndex - 1;
+ while (currentIndex >= 0 && seriesValues[currentIndex] == null) {
+ seriesValues[currentIndex--] = null;
+ }
+
+ // expand right until we hit a non-null value
+ currentIndex = nullIndex + 1;
+ while (currentIndex < alignedLength && seriesValues[currentIndex] == null) {
+ seriesValues[(lastExpandedNullIndex = currentIndex++)] = null;
+ }
+ }
+ }
+}
+
+/**
+ * Merges multiple uPlot `AlignedData` tables into a single aligned table.
+ *
+ * - Merges and sorts all distinct x-values from each table.
+ * - Re-aligns every series onto the merged x-axis.
+ * - Applies per-series null handling (`NULL_REMOVE`, `NULL_RETAIN`, `NULL_EXPAND`).
+ */
+/* eslint-disable sonarjs/cognitive-complexity */
+export function mergeAlignedDataTables(
+ alignedTables: AlignedData[],
+ nullModes?: number[][],
+): AlignedData {
+ let mergedXValues: Set<number>;
+
+ // eslint-disable-next-line prefer-const
+ mergedXValues = new Set();
+
+ // Collect all unique x-values from every table.
+ for (let tableIndex = 0; tableIndex < alignedTables.length; tableIndex++) {
+ const table = alignedTables[tableIndex];
+ const xValues = table[0];
+ const xLength = xValues.length;
+
+ for (let i = 0; i < xLength; i++) {
+ mergedXValues.add(xValues[i]);
+ }
+ }
+
+ // Sorted, merged x-axis used by the final result.
+ const alignedData: (number | null | undefined)[][] = [
+ Array.from(mergedXValues).sort((a, b) => a - b),
+ ];
+
+ const alignedLength = alignedData[0].length;
+
+ // Map from x-value to its index in the merged x-axis.
+ const xValueToIndexMap = new Map<number, number>();
+
+ for (let i = 0; i < alignedLength; i++) {
+ xValueToIndexMap.set(alignedData[0][i] as number, i);
+ }
+
+ // Re-align all series from all tables onto the merged x-axis.
+ for (let tableIndex = 0; tableIndex < alignedTables.length; tableIndex++) {
+ const table = alignedTables[tableIndex];
+ const xValues = table[0];
+
+ for (let seriesIndex = 1; seriesIndex < table.length; seriesIndex++) {
+ const seriesValues = table[seriesIndex];
+
+ const alignedSeriesValues = Array(alignedLength).fill(undefined);
+
+ const nullHandlingMode = nullModes
+ ? nullModes[tableIndex][seriesIndex]
+ : NULL_RETAIN;
+
+ const nullIndices: number[] = [];
+
+ for (let i = 0; i < seriesValues.length; i++) {
+ const valueAtPoint = seriesValues[i];
+ const alignedIndex = xValueToIndexMap.get(xValues[i]);
+
+ if (alignedIndex == null) {
+ continue;
+ }
+
+ if (valueAtPoint === null) {
+ if (nullHandlingMode !== NULL_REMOVE) {
+ alignedSeriesValues[alignedIndex] = valueAtPoint;
+
+ if (nullHandlingMode === NULL_EXPAND) {
+ nullIndices.push(alignedIndex);
+ }
+ }
+ } else {
+ alignedSeriesValues[alignedIndex] = valueAtPoint;
+ }
+ }
+
+ // Optionally expand nulls to visually preserve gaps.
+ propagateNullsAcrossNeighbors(
+ alignedSeriesValues,
+ nullIndices,
+ alignedLength,
+ );
+
+ alignedData.push(alignedSeriesValues);
+ }
+ }
+
+ return alignedData as AlignedData;
+}
+
+/**
+ * Builds histogram buckets from raw values.
+ *
+ * - Each value is mapped into a bucket via `getBucketForValue`.
+ * - Counts how many values fall into each bucket.
+ * - Optionally sorts buckets using the provided comparator.
+ */
+export function buildHistogramBuckets(
+ values: number[],
+ getBucketForValue: (value: number) => number,
+ sortBuckets?: ((a: number, b: number) => number) | null,
+): AlignedData {
+ const bucketMap = new Map<number, { value: number; count: number }>();
+
+ for (let i = 0; i < values.length; i++) {
+ let value = values[i];
+
+ if (value != null) {
+ value = getBucketForValue(value);
+ }
+
+ const bucket = bucketMap.get(value);
+
+ if (bucket) {
+ bucket.count++;
+ } else {
+ bucketMap.set(value, { value, count: 1 });
+ }
+ }
+
+ const buckets = [...bucketMap.values()];
+
+ // eslint-disable-next-line @typescript-eslint/no-unused-expressions
+ sortBuckets && buckets.sort((a, b) => sortBuckets(a.value, b.value));
+
+ const bucketValues = Array(buckets.length);
+ const bucketCounts = Array(buckets.length);
+
+ for (let i = 0; i < buckets.length; i++) {
+ bucketValues[i] = buckets[i].value;
+ bucketCounts[i] = buckets[i].count;
+ }
+
+ return [bucketValues, bucketCounts];
+}
+
+/**
+ * Mutates an `AlignedData` instance, replacing all `undefined` entries
+ * with explicit `null` values so uPlot treats them as gaps.
+ */
+export function replaceUndefinedWithNullInAlignedData(
+ data: AlignedData,
+): AlignedData {
+ const seriesList = data as (number | null | undefined)[][];
+ for (let seriesIndex = 0; seriesIndex < seriesList.length; seriesIndex++) {
+ for (
+ let pointIndex = 0;
+ pointIndex < seriesList[seriesIndex].length;
+ pointIndex++
+ ) {
+ if (seriesList[seriesIndex][pointIndex] === undefined) {
+ seriesList[seriesIndex][pointIndex] = null;
+ }
+ }
+ }
+ return data;
+}
+
+/**
+ * Ensures the first histogram series has a leading "empty" bin so that
+ * all series line up visually when rendered as bars.
+ *
+ * - Prepends a new x-value (first x - `bucketSize`) to the first series.
+ * - Prepends `null` to all subsequent series at the same index.
+ */
+export function prependNullBinToFirstHistogramSeries(
+ alignedData: AlignedData,
+ bucketSize: number,
+): void {
+ const seriesList = alignedData as (number | null)[][];
+ if (
+ seriesList.length > 0 &&
+ seriesList[0].length > 0 &&
+ seriesList[0][0] !== null
+ ) {
+ seriesList[0].unshift(seriesList[0][0] - bucketSize);
+ for (let seriesIndex = 1; seriesIndex < seriesList.length; seriesIndex++) {
+ seriesList[seriesIndex].unshift(null);
+ }
+ }
+}
diff --git a/frontend/src/lib/uPlotV2/components/Tooltip/HistogramTooltip.tsx b/frontend/src/lib/uPlotV2/components/Tooltip/HistogramTooltip.tsx
new file mode 100644
index 0000000000..2eb4bec8dc
--- /dev/null
+++ b/frontend/src/lib/uPlotV2/components/Tooltip/HistogramTooltip.tsx
@@ -0,0 +1,8 @@
+import { HistogramTooltipProps } from '../types';
+import Tooltip from './Tooltip';
+
+export default function HistogramTooltip(
+ props: HistogramTooltipProps,
+): JSX.Element {
+ return <Tooltip {...props} showTooltipHeader={false} />;
+}
diff --git a/frontend/src/lib/uPlotV2/components/Tooltip/Tooltip.tsx b/frontend/src/lib/uPlotV2/components/Tooltip/Tooltip.tsx
index b9693df1a9..653068ff0b 100644
--- a/frontend/src/lib/uPlotV2/components/Tooltip/Tooltip.tsx
+++ b/frontend/src/lib/uPlotV2/components/Tooltip/Tooltip.tsx
@@ -16,12 +16,16 @@ export default function Tooltip({
uPlotInstance,
timezone,
content,
+ showTooltipHeader = true,
}: TooltipProps): JSX.Element {
const isDarkMode = useIsDarkMode();
const tooltipContent = content ?? [];
const headerTitle = useMemo(() => {
+ if (!showTooltipHeader) {
+ return null;
+ }
const data = uPlotInstance.data;
const cursorIdx = uPlotInstance.cursor.idx;
if (cursorIdx == null) {
@@ -30,7 +34,12 @@ export default function Tooltip({
return dayjs(data[0][cursorIdx] * 1000)
.tz(timezone)
.format(DATE_TIME_FORMATS.MONTH_DATETIME_SECONDS);
- }, [timezone, uPlotInstance.data, uPlotInstance.cursor.idx]);
+ }, [
+ timezone,
+ uPlotInstance.data,
+ uPlotInstance.cursor.idx,
+ showTooltipHeader,
+ ]);
return (
<div
@@ -39,9 +48,11 @@ export default function Tooltip({
isDarkMode ? 'darkMode' : 'lightMode',
)}
>
- <div className="uplot-tooltip-header">
- <span>{headerTitle}</span>
- </div>
+ {showTooltipHeader && (
+ <div className="uplot-tooltip-header">
+ <span>{headerTitle}</span>
+ </div>
+ )}
<div
style={{
height: Math.min(
diff --git a/frontend/src/lib/uPlotV2/components/types.ts b/frontend/src/lib/uPlotV2/components/types.ts
index 4655922720..8a3a7ea4d1 100644
--- a/frontend/src/lib/uPlotV2/components/types.ts
+++ b/frontend/src/lib/uPlotV2/components/types.ts
@@ -60,6 +60,7 @@ export interface TooltipRenderArgs {
}
export interface BaseTooltipProps {
+ showTooltipHeader?: boolean;
timezone: string;
yAxisUnit?: string;
decimalPrecision?: PrecisionOption;
@@ -74,7 +75,14 @@ export interface BarTooltipProps extends BaseTooltipProps, TooltipRenderArgs {
isStackedBarChart?: boolean;
}
-export type TooltipProps = TimeSeriesTooltipProps | BarTooltipProps;
+export interface HistogramTooltipProps
+ extends BaseTooltipProps,
+ TooltipRenderArgs {}
+
+export type TooltipProps =
+ | TimeSeriesTooltipProps
+ | BarTooltipProps
+ | HistogramTooltipProps;
export enum LegendPosition {
BOTTOM = 'bottom',
diff --git a/frontend/src/lib/uPlotV2/config/UPlotConfigBuilder.ts b/frontend/src/lib/uPlotV2/config/UPlotConfigBuilder.ts
index 786dfe10d2..c6a642bc10 100644
--- a/frontend/src/lib/uPlotV2/config/UPlotConfigBuilder.ts
+++ b/frontend/src/lib/uPlotV2/config/UPlotConfigBuilder.ts
@@ -387,7 +387,7 @@ export class UPlotConfigBuilder extends ConfigBuilder<
} = this.getVisibilityResolutionState();
config.series = [
- { value: (): string => '' }, // Base series for timestamp
+ { value: (): string => '', label: 'Timestamp' }, // Base series for timestamp
...this.series.map((s) => {
const series = s.getConfig();
// Stored visibility[0] is x-axis/time; data series start at visibility[1]
diff --git a/frontend/src/lib/uPlotV2/config/UPlotSeriesBuilder.ts b/frontend/src/lib/uPlotV2/config/UPlotSeriesBuilder.ts
index bc0f6e545b..122266dd0c 100644
--- a/frontend/src/lib/uPlotV2/config/UPlotSeriesBuilder.ts
+++ b/frontend/src/lib/uPlotV2/config/UPlotSeriesBuilder.ts
@@ -49,7 +49,7 @@ export class UPlotSeriesBuilder extends ConfigBuilder<SeriesProps, Series> {
}: {
resolvedLineColor: string;
}): Partial<Series> {
- const { lineWidth, lineStyle, lineCap } = this.props;
+ const { lineWidth, lineStyle, lineCap, fillColor } = this.props;
const lineConfig: Partial<Series> = {
stroke: resolvedLineColor,
width: lineWidth ?? 2,
@@ -63,8 +63,12 @@ export class UPlotSeriesBuilder extends ConfigBuilder<SeriesProps, Series> {
lineConfig.cap = lineCap;
}
- if (this.props.panelType === PANEL_TYPES.BAR) {
+ if (fillColor) {
+ lineConfig.fill = fillColor;
+ } else if (this.props.panelType === PANEL_TYPES.BAR) {
lineConfig.fill = resolvedLineColor;
+ } else if (this.props.panelType === PANEL_TYPES.HISTOGRAM) {
+ lineConfig.fill = `${resolvedLineColor}40`;
}
return lineConfig;
@@ -147,6 +151,8 @@ export class UPlotSeriesBuilder extends ConfigBuilder<SeriesProps, Series> {
pointsConfig.show = false;
} else if (showPoints === VisibilityMode.Always) {
pointsConfig.show = true;
+ } else {
+ pointsConfig.show = false; // default to hidden
}
return pointsConfig;
diff --git a/frontend/src/lib/uPlotV2/config/types.ts b/frontend/src/lib/uPlotV2/config/types.ts
index 8c06fe8c99..7c0e41dd03 100644
--- a/frontend/src/lib/uPlotV2/config/types.ts
+++ b/frontend/src/lib/uPlotV2/config/types.ts
@@ -175,6 +175,7 @@ export interface SeriesProps extends LineConfig, PointsConfig, BarConfig {
pointsBuilder?: Series.Points.Show;
show?: boolean;
spanGaps?: boolean;
+ fillColor?: string;
isDarkMode?: boolean;
stepInterval?: number;
}
diff --git a/frontend/src/lib/uPlotV2/utils/scale.ts b/frontend/src/lib/uPlotV2/utils/scale.ts
index 089b6d8bb1..c419a24753 100644
--- a/frontend/src/lib/uPlotV2/utils/scale.ts
+++ b/frontend/src/lib/uPlotV2/utils/scale.ts
@@ -11,22 +11,6 @@ import { Threshold } from '../hooks/types';
import { findMinMaxThresholdValues } from './threshold';
import { LogScaleLimits, RangeFunctionParams } from './types';
-/**
- * Rounds a number down to the nearest multiple of incr.
- * Used for linear scale min so the axis starts on a clean tick.
- */
-export function incrRoundDn(num: number, incr: number): number {
- return Math.floor(num / incr) * incr;
-}
-
-/**
- * Rounds a number up to the nearest multiple of incr.
- * Used for linear scale max so the axis ends on a clean tick.
- */
-export function incrRoundUp(num: number, incr: number): number {
- return Math.ceil(num / incr) * incr;
-}
-
/**
* Snaps min/max/softMin/softMax to valid log-scale values (powers of logBase).
* Only applies when distribution is logarithmic; otherwise returns limits unchanged.
@@ -213,25 +197,6 @@ function getLogScaleRange(
);
}
-/**
- * Snaps linear scale min down and max up to whole numbers so axis bounds are clean.
- */
-function roundLinearRange(minMax: Range.MinMax): Range.MinMax {
- const [currentMin, currentMax] = minMax;
- let roundedMin = currentMin;
- let roundedMax = currentMax;
-
- if (roundedMin != null) {
- roundedMin = incrRoundDn(roundedMin, 1);
- }
-
- if (roundedMax != null) {
- roundedMax = incrRoundUp(roundedMax, 1);
- }
-
- return [roundedMin, roundedMax];
-}
-
/**
* Snaps log-scale [min, max] to exact powers of logBase (nearest magnitude below/above).
* If min and max would be equal after snapping, max is increased by one magnitude so the range is valid.
@@ -330,7 +295,6 @@ export function createRangeFunction(
if (scale.distr === 1) {
minMax = getLinearScaleRange(minMax, params, dataMin, dataMax);
- minMax = roundLinearRange(minMax);
} else if (scale.distr === 3) {
minMax = getLogScaleRange(minMax, params, dataMin, dataMax, logBase);
const logFn = scale.log === 2 ? Math.log2 : Math.log10;
diff --git a/frontend/src/utils/round.ts b/frontend/src/utils/round.ts
index 6da6a99f2c..30a219e8da 100644
--- a/frontend/src/utils/round.ts
+++ b/frontend/src/utils/round.ts
@@ -3,3 +3,33 @@
* Example: 1.5 → 2, 1.49 → 1
*/
export const roundHalfUp = (value: number): number => Math.floor(value + 0.5);
+
+/**
+ * Rounds a number down to the nearest multiple of incr.
+ * Used for linear scale min so the axis starts on a clean tick.
+ */
+export function incrRoundDn(num: number, incr: number): number {
+ return Math.floor(num / incr) * incr;
+}
+
+/**
+ * Rounds a number up to the nearest multiple of incr.
+ * Used for linear scale max so the axis ends on a clean tick.
+ */
+export function incrRoundUp(num: number, incr: number): number {
+ return Math.ceil(num / incr) * incr;
+}
+
+/**
+ * Rounds a number to the nearest multiple of 10^dec.
+ * Used for decimal precision.
+ */
+export function roundDecimals(val: number, dec = 0): number {
+ if (Number.isInteger(val)) {
+ return val;
+ }
+
+ const p = 10 ** dec;
+ const n = val * p * (1 + Number.EPSILON);
+ return Math.round(n) / p;
+}