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.
TypeScript apmapplication-monitoringdistributed-tracinggogood-first-issuejaegerloglogsmetricsmonitoringnextjsobservabilityopen-sourceopentelemetryprometheusreactreactjsself-hostedtracingtypescript
feat: added changes to compute legend items width for virtualization (#10196)
Abhi kumar594d4dc73705
diff --git a/frontend/src/container/DashboardContainer/visualization/charts/utils.ts b/frontend/src/container/DashboardContainer/visualization/charts/utils.tsindex e6a4880b45..46100d3e56 100644--- a/frontend/src/container/DashboardContainer/visualization/charts/utils.ts+++ b/frontend/src/container/DashboardContainer/visualization/charts/utils.ts@@ -5,25 +5,32 @@ export interface ChartDimensions {height: number;legendWidth: number;legendHeight: number;- legendsPerSet: number;+ averageLegendWidth: number;}const AVG_CHAR_WIDTH = 8;+const LEGEND_WIDTH_PERCENTILE = 0.85;const DEFAULT_AVG_LABEL_LENGTH = 15;-const LEGEND_GAP = 16;+const BASE_LEGEND_WIDTH = 16;const LEGEND_PADDING = 12;-const LEGEND_LINE_HEIGHT = 36;+const LEGEND_LINE_HEIGHT = 28;/**- * Average text width from series labels (for legendsPerSet).+ * Calculates the average width of the legend items based on the labels of the series.+ * @param legends - The labels of the series.+ * @returns The average width of the legend items.*/export function calculateAverageLegendWidth(legends: string[]): number {if (legends.length === 0) {- return DEFAULT_AVG_LABEL_LENGTH;+ return DEFAULT_AVG_LABEL_LENGTH * AVG_CHAR_WIDTH;}- const averageLabelLength =- legends.reduce((sum, l) => sum + l.length, 0) / legends.length;- return averageLabelLength * AVG_CHAR_WIDTH;++ const lengths = legends.map((l) => l.length).sort((a, b) => a - b);++ const index = Math.ceil(LEGEND_WIDTH_PERCENTILE * lengths.length) - 1;+ const percentileLength = lengths[Math.max(0, index)];++ return BASE_LEGEND_WIDTH + percentileLength * AVG_CHAR_WIDTH;}/**@@ -64,7 +71,7 @@ export function calculateChartDimensions({height: 0,legendWidth: 0,legendHeight: 0,- legendsPerSet: 0,+ averageLegendWidth: 0,};}@@ -85,13 +92,15 @@ export function calculateChartDimensions({legendWidth: rightLegendWidth,legendHeight: containerHeight,// Single vertical list on the right.- legendsPerSet: 1,+ averageLegendWidth: rightLegendWidth,};}const legendRowHeight = LEGEND_LINE_HEIGHT + LEGEND_PADDING;- const legendItemWidth = Math.min(approxLegendItemWidth, 400);+ const legendItemWidth = Math.ceil(+ Math.min(approxLegendItemWidth, MAX_LEGEND_WIDTH),+ );const legendItemsPerRow = Math.max(1,Math.floor((containerWidth - LEGEND_PADDING * 2) / legendItemWidth),@@ -114,17 +123,11 @@ export function calculateChartDimensions({maxAllowedLegendHeight,);- // How many legend items per row in the Legend component.- const legendsPerSet = Math.ceil(- (containerWidth + LEGEND_GAP) /- (Math.min(MAX_LEGEND_WIDTH, approxLegendItemWidth) + LEGEND_GAP),- );-return {width: containerWidth,height: Math.max(0, containerHeight - bottomLegendHeight),legendWidth: containerWidth,legendHeight: bottomLegendHeight,- legendsPerSet,+ averageLegendWidth: legendItemWidth,};}diff --git a/frontend/src/container/DashboardContainer/visualization/layout/ChartLayout/ChartLayout.tsx b/frontend/src/container/DashboardContainer/visualization/layout/ChartLayout/ChartLayout.tsxindex aedf3e87cf..62e9325a61 100644--- a/frontend/src/container/DashboardContainer/visualization/layout/ChartLayout/ChartLayout.tsx+++ b/frontend/src/container/DashboardContainer/visualization/layout/ChartLayout/ChartLayout.tsx@@ -65,7 +65,7 @@ export default function ChartLayout({width: chartDimensions.legendWidth,}}>- {legendComponent(chartDimensions.legendsPerSet)}+ {legendComponent(chartDimensions.averageLegendWidth)}</div></div>{layoutChildren}diff --git a/frontend/src/lib/uPlotV2/components/Legend/Legend.styles.scss b/frontend/src/lib/uPlotV2/components/Legend/Legend.styles.scssindex 2e8cc5925e..013a39caf5 100644--- a/frontend/src/lib/uPlotV2/components/Legend/Legend.styles.scss+++ b/frontend/src/lib/uPlotV2/components/Legend/Legend.styles.scss@@ -1,7 +1,18 @@+.legend-search-container {+ flex-shrink: 0;+ width: 100%;+ padding-right: 8px;++ .legend-search-input {+ font-size: 12px;+ }+}+.legend-container {display: flex;flex-direction: column;align-items: center;+ gap: 12px;height: 100%;width: 100%;@@ -17,6 +28,38 @@height: 100%;width: 100%;+ .virtuoso-grid-list {+ min-width: 0;+ display: grid;+ grid-auto-flow: row;+ grid-template-columns: repeat(+ auto-fill,+ minmax(var(--legend-average-width, 240px), 1fr)+ );+ row-gap: 4px;+ column-gap: 12px;+ }++ .virtuoso-grid-item {+ min-width: 0;+ }++ &.legend-virtuoso-container-right {+ .virtuoso-grid-list {+ grid-template-columns: 1fr;+ }+ }++ &.legend-virtuoso-container-single-row {+ .virtuoso-grid-list {+ grid-template-columns: repeat(+ auto-fit,+ minmax(var(--legend-average-width, 240px), max-content)+ );+ justify-content: center;+ }+ }+&::-webkit-scrollbar {width: 0.3rem;}@@ -58,9 +101,15 @@align-items: center;gap: 6px;padding: 4px 8px;+ max-width: 100%;+ overflow: hidden;border-radius: 4px;cursor: pointer;+ &.legend-item-right {+ width: 100%;+ }+&.legend-item-off {opacity: 0.3;text-decoration: line-through;diff --git a/frontend/src/lib/uPlotV2/components/Legend/Legend.tsx b/frontend/src/lib/uPlotV2/components/Legend/Legend.tsxindex f81fc42ede..23b3caf44c 100644--- a/frontend/src/lib/uPlotV2/components/Legend/Legend.tsx+++ b/frontend/src/lib/uPlotV2/components/Legend/Legend.tsx@@ -1,23 +1,21 @@-import { useCallback, useMemo, useRef } from 'react';-import { Virtuoso } from 'react-virtuoso';-import { Tooltip as AntdTooltip } from 'antd';+import { useCallback, useMemo, useRef, useState } from 'react';+import { VirtuosoGrid } from 'react-virtuoso';+import { Input, Tooltip as AntdTooltip } from 'antd';import cx from 'classnames';import { LegendItem } from 'lib/uPlotV2/config/types';import useLegendsSync from 'lib/uPlotV2/hooks/useLegendsSync';-import { LegendPosition } from 'types/api/dashboard/getAll';-import { LegendProps } from '../types';+import { LegendPosition, LegendProps } from '../types';import { useLegendActions } from './useLegendActions';import './Legend.styles.scss';-export const MAX_LEGEND_WIDTH = 320;-const LEGENDS_PER_SET_DEFAULT = 5;+export const MAX_LEGEND_WIDTH = 240;export default function Legend({position = LegendPosition.BOTTOM,config,- legendsPerSet = LEGENDS_PER_SET_DEFAULT,+ averageLegendWidth = MAX_LEGEND_WIDTH,}: LegendProps): JSX.Element {const {legendItemsMap,@@ -33,54 +31,54 @@ export default function Legend({focusedSeriesIndex,});const legendContainerRef = useRef<HTMLDivElement | null>(null);+ const [legendSearchQuery, setLegendSearchQuery] = useState('');- // Chunk legend items into rows of LEGENDS_PER_ROW items each- const legendRows = useMemo(() => {- const legendItems = Object.values(legendItemsMap);+ const legendItems = useMemo(() => Object.values(legendItemsMap), [+ legendItemsMap,+ ]);- return legendItems.reduce((acc: LegendItem[][], curr, i) => {- if (i % legendsPerSet === 0) {- acc.push([]);- }- acc[acc.length - 1].push(curr);- return acc;- }, [] as LegendItem[][]);- }, [legendItemsMap, legendsPerSet]);+ const isSingleRow = useMemo(() => {+ if (!legendContainerRef.current || position !== LegendPosition.BOTTOM) {+ return false;+ }+ const containerWidth = legendContainerRef.current.clientWidth;- const renderLegendRow = useCallback(- (rowIndex: number, row: LegendItem[]): JSX.Element => (- <div- key={rowIndex}- className={cx(- 'legend-row',- `legend-row-${position.toLowerCase()}`,- legendRows.length === 1 && position === LegendPosition.BOTTOM- ? 'legend-single-row'- : '',- )}- >- {row.map((item) => (- <AntdTooltip key={item.seriesIndex} title={item.label}>- <div- data-legend-item-id={item.seriesIndex}- className={cx('legend-item', {- 'legend-item-off': !item.show,- 'legend-item-focused': focusedSeriesIndex === item.seriesIndex,- })}- style={{ maxWidth: `min(${MAX_LEGEND_WIDTH}px, 100%)` }}- >- <div- className="legend-marker"- style={{ borderColor: String(item.color) }}- data-is-legend-marker={true}- />- <span className="legend-label">{item.label}</span>- </div>- </AntdTooltip>- ))}- </div>+ const totalLegendWidth = legendItems.length * (averageLegendWidth + 16);+ const totalRows = Math.ceil(totalLegendWidth / containerWidth);+ return totalRows <= 1;+ }, [averageLegendWidth, legendContainerRef, legendItems.length, position]);++ const visibleLegendItems = useMemo(() => {+ if (position !== LegendPosition.RIGHT || !legendSearchQuery.trim()) {+ return legendItems;+ }++ const query = legendSearchQuery.trim().toLowerCase();+ return legendItems.filter((item) =>+ item.label?.toLowerCase().includes(query),+ );+ }, [position, legendSearchQuery, legendItems]);++ const renderLegendItem = useCallback(+ (item: LegendItem): JSX.Element => (+ <AntdTooltip key={item.seriesIndex} title={item.label}>+ <div+ data-legend-item-id={item.seriesIndex}+ className={cx('legend-item', `legend-item-${position.toLowerCase()}`, {+ 'legend-item-off': !item.show,+ 'legend-item-focused': focusedSeriesIndex === item.seriesIndex,+ })}+ >+ <div+ className="legend-marker"+ style={{ borderColor: String(item.color) }}+ data-is-legend-marker={true}+ />+ <span className="legend-label">{item.label}</span>+ </div>+ </AntdTooltip>),- [focusedSeriesIndex, position, legendRows],+ [focusedSeriesIndex, position],);return (@@ -90,11 +88,29 @@ export default function Legend({onClick={onLegendClick}onMouseMove={onLegendMouseMove}onMouseLeave={onLegendMouseLeave}+ style={{+ ['--legend-average-width' as string]: `${averageLegendWidth + 16}px`, // 16px is the marker width+ }}>- <Virtuoso- className="legend-virtuoso-container"- data={legendRows}- itemContent={(index, row): JSX.Element => renderLegendRow(index, row)}+ {position === LegendPosition.RIGHT && (+ <div className="legend-search-container">+ <Input+ allowClear+ placeholder="Search..."+ value={legendSearchQuery}+ onChange={(e): void => setLegendSearchQuery(e.target.value)}+ className="legend-search-input"+ />+ </div>+ )}+ <VirtuosoGrid+ className={cx(+ 'legend-virtuoso-container',+ `legend-virtuoso-container-${position.toLowerCase()}`,+ { 'legend-virtuoso-container-single-row': isSingleRow },+ )}+ data={visibleLegendItems}+ itemContent={(_, item): JSX.Element => renderLegendItem(item)}/></div>);diff --git a/frontend/src/lib/uPlotV2/components/types.ts b/frontend/src/lib/uPlotV2/components/types.tsindex 7f5e3473a3..e1a016df17 100644--- a/frontend/src/lib/uPlotV2/components/types.ts+++ b/frontend/src/lib/uPlotV2/components/types.ts@@ -75,7 +75,7 @@ export interface LegendConfig {export interface LegendProps {position?: LegendPosition;config: UPlotConfigBuilder;- legendsPerSet?: number;+ averageLegendWidth?: number;}export interface TooltipContentItem {