The Open Standard for Generative UI
Performance improvement (#151)
Ankit Das0906d6376a34
diff --git a/js/packages/react-ui/src/components/Charts/AreaChart/AreaChart.tsx b/js/packages/react-ui/src/components/Charts/AreaChart/AreaChart.tsxindex e8089f050..eebe10c69 100644--- a/js/packages/react-ui/src/components/Charts/AreaChart/AreaChart.tsx+++ b/js/packages/react-ui/src/components/Charts/AreaChart/AreaChart.tsx@@ -4,7 +4,7 @@ import { Area, AreaChart as RechartsAreaChart, XAxis, YAxis } from "recharts";import { useId } from "../../../polyfills";import { ChartConfig, ChartContainer, ChartTooltip } from "../Charts";import { SideBarChartData, SideBarTooltipProvider } from "../context/SideBarTooltipContext";-import { useMaxLabelHeight, useTransformedKeys } from "../hooks";+import { useMaxLabelHeight, useTransformedKeys, useYAxisLabelWidth } from "../hooks";import {ActiveDot,cartesianGrid,@@ -19,7 +19,6 @@ import { LabelTooltipProvider } from "../shared/LabelTooltip/LabelTooltip";import { LegendItem, XAxisTickVariant } from "../types";import {findNearestSnapPosition,- getOptimalXAxisTickFormatter,getSnapPositions,getWidthOfData,getWidthOfGroup,@@ -31,7 +30,6 @@ import {getDataKeys,getLegendItems,} from "../utils/dataUtils";-import { getYAxisTickFormatter } from "../utils/styleUtils";import { AreaChartData, AreaChartVariant } from "./types";// this a technic to get the type of the onClick event of the bar chart@@ -58,7 +56,6 @@ export interface AreaChartProps<T extends AreaChartData> {width?: number;}-const Y_AXIS_WIDTH = 40; // Width of Y-axis chart when shownconst X_AXIS_PADDING = 36;const CHART_CONTAINER_BOTTOM_MARGIN = 10;@@ -84,6 +81,8 @@ const AreaChartComponent = <T extends AreaChartData>({return getDataKeys(data, categoryKey as string);}, [data, categoryKey]);+ const yAxisWidth = useYAxisLabelWidth(data, dataKeys);+const widthOfGroup = useMemo(() => {return getWidthOfGroup(data);}, [data]);@@ -121,9 +120,9 @@ const AreaChartComponent = <T extends AreaChartData>({}, [width, containerWidth]);const effectiveContainerWidth = useMemo(() => {- const yAxisWidth = showYAxis ? Y_AXIS_WIDTH : 0;- return Math.max(0, effectiveWidth - yAxisWidth - 40); // -40 because we are giving 20px padding in xAxis on each side- }, [effectiveWidth, showYAxis]);+ const dynamicYAxisWidth = showYAxis ? yAxisWidth : 0;+ return Math.max(0, effectiveWidth - dynamicYAxisWidth - 40); // -40 because we are giving 20px padding in xAxis on each side+ }, [effectiveWidth, showYAxis, yAxisWidth]);const dataWidth = useMemo(() => {return getWidthOfData(data, effectiveContainerWidth);@@ -138,11 +137,6 @@ const AreaChartComponent = <T extends AreaChartData>({return height ?? 296 + maxLabelHeight;}, [height, maxLabelHeight]);- // Calculate optimal tick formatter for collision detection and truncation- const xAxisTickFormatter = useMemo(() => {- return getOptimalXAxisTickFormatter(data, effectiveContainerWidth);- }, [data, effectiveContainerWidth]);-// Check scroll boundariesconst updateScrollState = useCallback(() => {if (mainContainerRef.current) {@@ -258,7 +252,7 @@ const AreaChartComponent = <T extends AreaChartData>({{/* Y-axis only chart - synchronized with main chart */}<RechartsAreaChartkey={`y-axis-chart-${id}`}- width={Y_AXIS_WIDTH}+ width={yAxisWidth}height={chartHeight}data={data}margin={{@@ -268,13 +262,7 @@ const AreaChartComponent = <T extends AreaChartData>({right: 0,}}>- <YAxis- width={Y_AXIS_WIDTH}- tickLine={false}- axisLine={false}- tickFormatter={getYAxisTickFormatter()}- tick={<YAxisTick />}- />+ <YAxis width={yAxisWidth} tickLine={false} axisLine={false} tick={<YAxisTick />} />{/* Invisible area to maintain scale synchronization */}{dataKeys.map((key) => {return (@@ -292,7 +280,7 @@ const AreaChartComponent = <T extends AreaChartData>({</RechartsAreaChart></div>);- }, [showYAxis, chartHeight, data, dataKeys, variant, id, maxLabelHeight]);+ }, [showYAxis, chartHeight, data, dataKeys, variant, id, maxLabelHeight, yAxisWidth]);return (<LabelTooltipProvider>@@ -337,7 +325,6 @@ const AreaChartComponent = <T extends AreaChartData>({axisLine={false}textAnchor="middle"interval={0}- tickFormatter={xAxisTickFormatter}height={maxLabelHeight}tick={<XAxisTickdiff --git a/js/packages/react-ui/src/components/Charts/BarChart/BarChart.tsx b/js/packages/react-ui/src/components/Charts/BarChart/BarChart.tsxindex 290b8f307..71c28519b 100644--- a/js/packages/react-ui/src/components/Charts/BarChart/BarChart.tsx+++ b/js/packages/react-ui/src/components/Charts/BarChart/BarChart.tsx@@ -5,7 +5,7 @@ import { useId } from "../../../polyfills";import { useTheme } from "../../ThemeProvider";import { ChartConfig, ChartContainer, ChartTooltip } from "../Charts";import { SideBarChartData, SideBarTooltipProvider } from "../context/SideBarTooltipContext";-import { useMaxLabelHeight, useTransformedKeys } from "../hooks";+import { useMaxLabelHeight, useTransformedKeys, useYAxisLabelWidth } from "../hooks";import {cartesianGrid,CustomTooltipContent,@@ -27,13 +27,11 @@ import {getDataKeys,getLegendItems,} from "../utils/dataUtils";-import { getYAxisTickFormatter } from "../utils/styleUtils";import { LineInBarShape } from "./components/LineInBarShape";import { BarChartData, BarChartVariant } from "./types";import {BAR_WIDTH,findNearestSnapPosition,- getOptimalXAxisTickFormatter,getPadding,getRadiusArray,getSnapPositions,@@ -65,7 +63,6 @@ export interface BarChartProps<T extends BarChartData> {width?: number;}-const Y_AXIS_WIDTH = 40; // Width of Y-axis chart when shownconst BAR_GAP = 10; // Gap between barsconst BAR_CATEGORY_GAP = "20%"; // Gap between categoriesconst BAR_INTERNAL_LINE_WIDTH = 1;@@ -99,6 +96,8 @@ const BarChartComponent = <T extends BarChartData>({return getDataKeys(data, categoryKey as string);}, [data, categoryKey]);+ const yAxisWidth = useYAxisLabelWidth(data, dataKeys);+const transformedKeys = useTransformedKeys(dataKeys);const colors = useChartPalette({@@ -132,9 +131,9 @@ const BarChartComponent = <T extends BarChartData>({// need this to calculate the padding for the chart container, because the y-axis is rendered in a separate chartconst effectiveContainerWidth = useMemo(() => {- const yAxisWidth = showYAxis ? Y_AXIS_WIDTH : 0;- return Math.max(0, effectiveWidth - yAxisWidth);- }, [effectiveWidth, showYAxis]);+ const dynamicYAxisWidth = showYAxis ? yAxisWidth : 0;+ return Math.max(0, effectiveWidth - dynamicYAxisWidth);+ }, [effectiveWidth, showYAxis, yAxisWidth]);const padding = useMemo(() => {return getPadding(data, categoryKey as string, effectiveContainerWidth, variant);@@ -248,11 +247,6 @@ const BarChartComponent = <T extends BarChartData>({const id = useId();- // Get the optimal X-axis tick formatter based on available space- const xAxisTickFormatter = useMemo(() => {- return getOptimalXAxisTickFormatter(data, categoryKey as string, variant);- }, [data, categoryKey, variant]);-const yAxis = useMemo(() => {if (!showYAxis) {return null;@@ -262,7 +256,7 @@ const BarChartComponent = <T extends BarChartData>({{/* Y-axis only chart - synchronized with main chart */}<RechartsBarChartkey={`y-axis-bar-chart-${id}`}- width={Y_AXIS_WIDTH}+ width={yAxisWidth}height={chartHeight}data={data}margin={{@@ -272,13 +266,7 @@ const BarChartComponent = <T extends BarChartData>({right: 0,}}>- <YAxis- width={Y_AXIS_WIDTH}- tickLine={false}- axisLine={false}- tickFormatter={getYAxisTickFormatter()}- tick={<YAxisTick />}- />+ <YAxis width={yAxisWidth} tickLine={false} axisLine={false} tick={<YAxisTick />} />{/* Invisible bars to maintain scale synchronization */}{dataKeys.map((key) => {return (@@ -295,7 +283,7 @@ const BarChartComponent = <T extends BarChartData>({</RechartsBarChart></div>);- }, [showYAxis, chartHeight, data, dataKeys, variant, id, maxLabelHeight]);+ }, [showYAxis, chartHeight, data, dataKeys, variant, id, maxLabelHeight, yAxisWidth]);// Handle mouse events for group hoveringconst handleChartMouseMove = useCallback((state: any) => {@@ -344,6 +332,52 @@ const BarChartComponent = <T extends BarChartData>({[dataKeys, colors],);+ const barElements = useMemo(() => {+ return dataKeys.map((key, index) => {+ const transformedKey = transformedKeys[key];+ const color = `var(--color-${transformedKey})`;+ const isFirstInStack = index === 0;+ const isLastInStack = index === dataKeys.length - 1;++ return (+ <Bar+ key={`main-${key}`}+ dataKey={key}+ fill={color}+ radius={getRadiusArray(+ variant,+ radius,+ variant === "stacked" ? isFirstInStack : undefined,+ variant === "stacked" ? isLastInStack : undefined,+ )}+ stackId={variant === "stacked" ? "a" : undefined}+ isAnimationActive={isAnimationActive}+ maxBarSize={BAR_WIDTH}+ barSize={BAR_WIDTH}+ shape={+ <LineInBarShape+ internalLineColor={barInternalLineColor}+ internalLineWidth={BAR_INTERNAL_LINE_WIDTH}+ isHovered={hoveredCategory !== null}+ hoveredCategory={hoveredCategory}+ categoryKey={categoryKey as string}+ variant={variant}+ />+ }+ />+ );+ });+ }, [+ dataKeys,+ transformedKeys,+ variant,+ radius,+ isAnimationActive,+ barInternalLineColor,+ hoveredCategory,+ categoryKey,+ ]);+return (<LabelTooltipProvider><SideBarTooltipProvider@@ -390,7 +424,6 @@ const BarChartComponent = <T extends BarChartData>({tickLine={false}axisLine={false}textAnchor={"middle"}- tickFormatter={xAxisTickFormatter}interval={0}height={maxLabelHeight}tick={@@ -420,40 +453,7 @@ const BarChartComponent = <T extends BarChartData>({offset={15}/>- {dataKeys.map((key, index) => {- const transformedKey = transformedKeys[key];- const color = `var(--color-${transformedKey})`;- const isFirstInStack = index === 0;- const isLastInStack = index === dataKeys.length - 1;-- return (- <Bar- key={`main-${key}`}- dataKey={key}- fill={color}- radius={getRadiusArray(- variant,- radius,- variant === "stacked" ? isFirstInStack : undefined,- variant === "stacked" ? isLastInStack : undefined,- )}- stackId={variant === "stacked" ? "a" : undefined}- isAnimationActive={isAnimationActive}- maxBarSize={BAR_WIDTH}- barSize={BAR_WIDTH}- shape={- <LineInBarShape- internalLineColor={barInternalLineColor}- internalLineWidth={BAR_INTERNAL_LINE_WIDTH}- isHovered={hoveredCategory !== null}- hoveredCategory={hoveredCategory}- categoryKey={categoryKey as string}- variant={variant}- />- }- />- );- })}+ {barElements}</RechartsBarChart></ChartContainer></div>diff --git a/js/packages/react-ui/src/components/Charts/BarChart/BarSeries.tsx b/js/packages/react-ui/src/components/Charts/BarChart/BarSeries.tsxnew file mode 100644index 000000000..8456e81b2--- /dev/null+++ b/js/packages/react-ui/src/components/Charts/BarChart/BarSeries.tsx@@ -0,0 +1,67 @@+import { Bar } from "recharts";+import { LineInBarShape } from "./components/LineInBarShape";+import { BarChartVariant } from "./types";+import { BAR_WIDTH, getRadiusArray } from "./utils/BarChartUtils";++const BAR_INTERNAL_LINE_WIDTH = 1;++export interface BarSeriesProps {+ dataKeys: string[];+ transformedKeys: Record<string, string>;+ variant: BarChartVariant;+ radius: number;+ isAnimationActive: boolean;+ barInternalLineColor: string;+ hoveredCategory: string | number | null;+ categoryKey: string;+}++export const BarSeries = ({+ dataKeys,+ transformedKeys,+ variant,+ radius,+ isAnimationActive,+ barInternalLineColor,+ hoveredCategory,+ categoryKey,+}: BarSeriesProps) => {+ return (+ <>+ {dataKeys.map((key, index) => {+ const transformedKey = transformedKeys[key];+ const color = `var(--color-${transformedKey})`;+ const isFirstInStack = index === 0;+ const isLastInStack = index === dataKeys.length - 1;++ return (+ <Bar+ key={`main-${key}`}+ dataKey={key}+ fill={color}+ radius={getRadiusArray(+ variant,+ radius,+ variant === "stacked" ? isFirstInStack : undefined,+ variant === "stacked" ? isLastInStack : undefined,+ )}+ stackId={variant === "stacked" ? "a" : undefined}+ isAnimationActive={isAnimationActive}+ maxBarSize={BAR_WIDTH}+ barSize={BAR_WIDTH}+ shape={+ <LineInBarShape+ internalLineColor={barInternalLineColor}+ internalLineWidth={BAR_INTERNAL_LINE_WIDTH}+ isHovered={hoveredCategory !== null}+ hoveredCategory={hoveredCategory}+ categoryKey={categoryKey}+ variant={variant}+ />+ }+ />+ );+ })}+ </>+ );+};diff --git a/js/packages/react-ui/src/components/Charts/BarChart/utils/BarChartUtils.ts b/js/packages/react-ui/src/components/Charts/BarChart/utils/BarChartUtils.tsindex e36696d9a..0f6cbff72 100644--- a/js/packages/react-ui/src/components/Charts/BarChart/utils/BarChartUtils.ts+++ b/js/packages/react-ui/src/components/Charts/BarChart/utils/BarChartUtils.ts@@ -1,5 +1,4 @@import { getDataKeys } from "../../utils/dataUtils";-import { getCanvasContext } from "../../utils/styleUtils";import { BarChartVariant } from "../types";export const BAR_WIDTH = 16;@@ -115,76 +114,6 @@ const getRadiusArray = (return [radius, radius, radius, radius];};-/**- * INTERNAL HELPER FUNCTION- * This function returns the formatter for the X-axis tick values with intelligent truncation.- * @param groupWidth - The width available for each group/category (optional)- * @param variant - The chart variant (affects truncation logic)- * @returns The formatter for the X-axis tick values.- * internally used by the XAxis component reCharts- */-const getXAxisTickFormatter = (groupWidth?: number, variant: BarChartVariant = "grouped") => {- const PADDING = 2; // Safety padding for better visual spacing- const context = getCanvasContext();-- return (value: string) => {- const stringValue = String(value);-- // Fallback for SSR, or if canvas/groupWidth is not available.- if (!context || !groupWidth) {- if (variant === "stacked") {- return stringValue.slice(0, 3);- } else {- return stringValue.length > 3 ? `${stringValue.slice(0, 3)}...` : stringValue;- }- }-- const availableWidth = Math.max(0, groupWidth - PADDING);-- if (context.measureText(stringValue).width <= availableWidth) {- return stringValue; // Full text fits.- }-- // If text overflows, find the best truncation point with ellipsis.- let low = 0;- let high = stringValue.length;- let result = "";- while (low <= high) {- const mid = Math.floor((low + high) / 2);- if (mid === 0) {- low = mid + 1;- continue;- }- const truncated = stringValue.substring(0, mid) + "...";- if (context.measureText(truncated).width <= availableWidth) {- result = truncated;- low = mid + 1;- } else {- high = mid - 1;- }- }-- return result;- };-};--/**- * Helper function to get the optimal X-axis tick formatter with calculated group width- * @param data - The chart data- * @param categoryKey - The category key- * @param variant - The chart variant- * @returns The optimized formatter function- */-const getOptimalXAxisTickFormatter = (- data: Array<Record<string, string | number>>,- categoryKey: string,- variant: BarChartVariant,-) => {- // Calculate the available width per group- const groupWidth = getWidthOfGroup(data, categoryKey, variant);- return getXAxisTickFormatter(groupWidth, variant);-};-/*** This function returns the scroll amount for the chart, used for the scroll amount of the chart.* This can also be used to calculate the width of each group/category.@@ -287,7 +216,6 @@ const getChartHeight = (containerWidth: number): number => {export {findNearestSnapPosition,getChartHeight,- getOptimalXAxisTickFormatter,getPadding,getRadiusArray,getSnapPositions,diff --git a/js/packages/react-ui/src/components/Charts/LineChart/LineChart.tsx b/js/packages/react-ui/src/components/Charts/LineChart/LineChart.tsxindex 5e9b28120..7ea55ee2b 100644--- a/js/packages/react-ui/src/components/Charts/LineChart/LineChart.tsx+++ b/js/packages/react-ui/src/components/Charts/LineChart/LineChart.tsx@@ -4,7 +4,7 @@ import { Line, LineChart as RechartsLineChart, XAxis, YAxis } from "recharts";import { useId } from "../../../polyfills";import { ChartConfig, ChartContainer, ChartTooltip } from "../Charts";import { SideBarChartData, SideBarTooltipProvider } from "../context/SideBarTooltipContext";-import { useMaxLabelHeight, useTransformedKeys } from "../hooks";+import { useMaxLabelHeight, useTransformedKeys, useYAxisLabelWidth } from "../hooks";import {ActiveDot,cartesianGrid,@@ -19,7 +19,6 @@ import { LabelTooltipProvider } from "../shared/LabelTooltip/LabelTooltip";import { LegendItem, XAxisTickVariant } from "../types";import {findNearestSnapPosition,- getOptimalXAxisTickFormatter,getSnapPositions,getWidthOfData,getWidthOfGroup,@@ -31,7 +30,6 @@ import {getDataKeys,getLegendItems,} from "../utils/dataUtils";-import { getYAxisTickFormatter } from "../utils/styleUtils";import { LineChartData, LineChartVariant } from "./types";type LineChartOnClick = React.ComponentProps<typeof RechartsLineChart>["onClick"];@@ -57,7 +55,6 @@ export interface LineChartProps<T extends LineChartData> {strokeWidth?: number;}-const Y_AXIS_WIDTH = 40; // Width of Y-axis chart when shownconst X_AXIS_PADDING = 36;const CHART_CONTAINER_BOTTOM_MARGIN = 10;@@ -84,6 +81,8 @@ export const LineChart = <T extends LineChartData>({return getDataKeys(data, categoryKey as string);}, [data, categoryKey]);+ const yAxisWidth = useYAxisLabelWidth(data, dataKeys);+const widthOfGroup = useMemo(() => {return getWidthOfGroup(data);}, [data]);@@ -121,9 +120,9 @@ export const LineChart = <T extends LineChartData>({}, [width, containerWidth]);const effectiveContainerWidth = useMemo(() => {- const yAxisWidth = showYAxis ? Y_AXIS_WIDTH : 0;- return Math.max(0, effectiveWidth - yAxisWidth - 40); // -40 because we are giving 20px padding in xAxis on each side- }, [effectiveWidth, showYAxis]);+ const dynamicYAxisWidth = showYAxis ? yAxisWidth : 0;+ return Math.max(0, effectiveWidth - dynamicYAxisWidth - 40); // -40 because we are giving 20px padding in xAxis on each side+ }, [effectiveWidth, showYAxis, yAxisWidth]);const dataWidth = useMemo(() => {return getWidthOfData(data, effectiveContainerWidth);@@ -138,11 +137,6 @@ export const LineChart = <T extends LineChartData>({return height ?? 296 + maxLabelHeight;}, [height, maxLabelHeight]);- // Calculate optimal tick formatter for collision detection and truncation- const xAxisTickFormatter = useMemo(() => {- return getOptimalXAxisTickFormatter(data, effectiveContainerWidth);- }, [data, effectiveContainerWidth]);-// Check scroll boundariesconst updateScrollState = useCallback(() => {if (mainContainerRef.current) {@@ -255,7 +249,7 @@ export const LineChart = <T extends LineChartData>({{/* Y-axis only chart - synchronized with main chart */}<RechartsLineChartkey={`y-axis-chart-${id}`}- width={Y_AXIS_WIDTH}+ width={yAxisWidth}height={chartHeight}data={data}margin={{@@ -266,13 +260,7 @@ export const LineChart = <T extends LineChartData>({}}onClick={onLineClick}>- <YAxis- width={Y_AXIS_WIDTH}- tickLine={false}- axisLine={false}- tickFormatter={getYAxisTickFormatter()}- tick={<YAxisTick />}- />+ <YAxis width={yAxisWidth} tickLine={false} axisLine={false} tick={<YAxisTick />} />{/* Invisible lines to maintain scale synchronization */}{dataKeys.map((key) => {return (@@ -301,6 +289,7 @@ export const LineChart = <T extends LineChartData>({variant,isAnimationActive,maxLabelHeight,+ yAxisWidth,]);return (@@ -347,7 +336,6 @@ export const LineChart = <T extends LineChartData>({height={maxLabelHeight}textAnchor="middle"interval={0}- tickFormatter={xAxisTickFormatter}tick={<XAxisTickvariant={tickVariant}diff --git a/js/packages/react-ui/src/components/Charts/hooks/index.ts b/js/packages/react-ui/src/components/Charts/hooks/index.tsindex b9f48f801..1f50b568e 100644--- a/js/packages/react-ui/src/components/Charts/hooks/index.ts+++ b/js/packages/react-ui/src/components/Charts/hooks/index.ts@@ -1,2 +1,3 @@export * from "./useMaxLabelHeight";export * from "./useTransformKey";+export * from "./useYAxisLabelWidth";diff --git a/js/packages/react-ui/src/components/Charts/hooks/useYAxisLabelWidth.tsx b/js/packages/react-ui/src/components/Charts/hooks/useYAxisLabelWidth.tsxnew file mode 100644index 000000000..d50ac66c2--- /dev/null+++ b/js/packages/react-ui/src/components/Charts/hooks/useYAxisLabelWidth.tsx@@ -0,0 +1,57 @@+import { useMemo } from "react";++import { useTheme } from "../../ThemeProvider";+import { AreaChartData } from "../AreaChart";+import { BarChartData } from "../BarChart";+import { LineChartData } from "../LineChart";+import { getCanvasContext, numberTickFormatter } from "../utils";++const DEFAULT_Y_AXIS_WIDTH = 40;+const MIN_Y_AXIS_WIDTH = 30;+const MAX_Y_AXIS_WIDTH = 120;++export const useYAxisLabelWidth = (+ data: AreaChartData | LineChartData | BarChartData,+ dataKeys: string[],+) => {+ const { theme: userTheme } = useTheme();++ const maxLabelWidth = useMemo(() => {+ if (typeof window === "undefined" || !data || data.length === 0 || !dataKeys.length) {+ return DEFAULT_Y_AXIS_WIDTH;+ }++ const context = getCanvasContext();+ if (!context) {+ return DEFAULT_Y_AXIS_WIDTH;+ }++ // Set font to match Y-axis tick styling+ const font = userTheme.fontLabelExtraSmall ?? "400 10px/12px Inter";+ context.font = font;++ let maxWidth = 0;++ // Measure all possible Y-axis values+ dataKeys.forEach((key) => {+ // Get all unique values for this data key we basically want to get the max width of the values+ const values = [+ ...new Set(data.map((item) => item[key]).filter((v) => v != null && typeof v === "number")),+ ];++ values.forEach((value) => {+ const displayValue = numberTickFormatter(value);+ const textWidth = context.measureText(displayValue).width;+ maxWidth = Math.max(maxWidth, textWidth);+ });+ });++ // Add padding for better visual appearance+ const totalWidth = Math.ceil(maxWidth) + 10; // 6px padding on each side++ // Clamp the width between MIN and MAX values+ return Math.max(MIN_Y_AXIS_WIDTH, Math.min(MAX_Y_AXIS_WIDTH, totalWidth));+ }, [data, dataKeys, userTheme.fontLabelExtraSmall]);++ return maxLabelWidth;+};diff --git a/js/packages/react-ui/src/components/Charts/shared/XAxisTick/XAxisTick.tsx b/js/packages/react-ui/src/components/Charts/shared/XAxisTick/XAxisTick.tsxindex 34e9998ac..993475857 100644--- a/js/packages/react-ui/src/components/Charts/shared/XAxisTick/XAxisTick.tsx+++ b/js/packages/react-ui/src/components/Charts/shared/XAxisTick/XAxisTick.tsx@@ -1,3 +1,4 @@+import clsx from "clsx";import React, { useLayoutEffect, useRef, useState } from "react";import { XAxisTickVariant } from "../../types";import { LabelTooltip } from "../LabelTooltip/LabelTooltip";@@ -36,7 +37,6 @@ const XAxisTick = React.forwardRef<SVGGElement, XAxisTickProps>((props, ref) =>x,y,payload,- tickFormatter,className,variant = "multiLine",widthOfGroup = 70,@@ -45,19 +45,22 @@ const XAxisTick = React.forwardRef<SVGGElement, XAxisTickProps>((props, ref) =>onMouseLeave,} = props;- const value = String(payload?.value || "");+ const rawValue = payload?.value;+ const value = String(rawValue || "");const foreignObjectRef = useRef<SVGForeignObjectElement>(null);const spanRef = useRef<HTMLSpanElement>(null);- const [isMultiLineTruncated, setIsMultiLineTruncated] = useState(false);+ const [isTruncated, setIsTruncated] = useState(false);- // Check if multiLine text is truncated+ // Check if text is truncateduseLayoutEffect(() => {- if (variant === "multiLine" && spanRef.current) {+ if (spanRef.current) {const element = spanRef.current;- // Check if the text is clamped by comparing scrollHeight with clientHeight- const isTruncated = element.scrollHeight > element.clientHeight;- setIsMultiLineTruncated(isTruncated);+ const isCurrentlyTruncated =+ variant === "multiLine"+ ? element.scrollHeight > element.clientHeight+ : element.scrollWidth > element.clientWidth;+ setIsTruncated(isCurrentlyTruncated);}}, [value, variant, widthOfGroup]);@@ -65,67 +68,51 @@ const XAxisTick = React.forwardRef<SVGGElement, XAxisTickProps>((props, ref) =>return null;}- if (variant === "multiLine") {- // The x position from Recharts is the center of the group- // To center the foreignObject, we need to offset by half of widthOfGroup- const calX = x - widthOfGroup / 2;- const calWidth = widthOfGroup - 4;+ // The x position from Recharts is the center of the group+ // To center the foreignObject, we need to offset by half of widthOfGroup+ // +2 is for the multiLine variant to center the text+ // +5 is for the singleLine variant to center the text+ // offset for padding - 4 and -10 respectively+ const calX = variant === "multiLine" ? x - widthOfGroup / 2 + 2 : x - widthOfGroup / 2 + 5;+ const calWidth = variant === "multiLine" ? widthOfGroup - 4 : widthOfGroup - 10;- return (- <g ref={ref} transform={`translate(${calX},${y})`}>- <foreignObject- ref={foreignObjectRef}- transform="translate(0, 0)"- width={calWidth}- height={labelHeight} // Initial height, will be updated by useLayoutEffect- className="crayon-chart-x-axis-tick-foreign"- >- <div- style={{- width: "100%",- height: "100%",- boxSizing: "border-box",- }}- onMouseEnter={() => onMouseEnter?.(props)}- onMouseLeave={() => onMouseLeave?.(props)}- >- <LabelTooltip content={value} side="top" disabled={!isMultiLineTruncated}>- <span- ref={spanRef}- style={{- textAlign: "center",- wordBreak: "break-word",- }}- className="crayon-chart-x-axis-tick-multi-line"- >- {value}- </span>- </LabelTooltip>- </div>- </foreignObject>- </g>- );- }-- const displayValue = tickFormatter ? tickFormatter(payload?.value) : value;- // Check if displayValue ends with dots (indicating truncation)- const isTruncated = displayValue.endsWith("...");+ const spanClassName =+ variant === "multiLine"+ ? "crayon-chart-x-axis-tick-multi-line"+ : "crayon-chart-x-axis-tick-single-line";return (- <g ref={ref} transform={`translate(${x},${y})`} className={className}>- <LabelTooltip content={value} side="top" disabled={!isTruncated}>- <text- x={0}- y={0}- dy={12}- textAnchor={"middle"}- className="crayon-chart-x-axis-tick"+ <g ref={ref} transform={`translate(${calX},${y})`}>+ <foreignObject+ ref={foreignObjectRef}+ transform="translate(0, 0)"+ width={calWidth}+ height={labelHeight} // Initial height, will be updated by useLayoutEffect+ className="crayon-chart-x-axis-tick-foreign"+ >+ <div+ style={{+ width: "100%",+ height: "100%",+ boxSizing: "border-box",+ }}onMouseEnter={() => onMouseEnter?.(props)}onMouseLeave={() => onMouseLeave?.(props)}>- {displayValue}- </text>- </LabelTooltip>+ <LabelTooltip content={value} side="top" disabled={!isTruncated}>+ <span+ ref={spanRef}+ style={{+ textAlign: "center",+ wordBreak: "break-word",+ }}+ className={clsx(spanClassName, className)}+ >+ {value}+ </span>+ </LabelTooltip>+ </div>+ </foreignObject></g>);});diff --git a/js/packages/react-ui/src/components/Charts/shared/XAxisTick/xAxisTick.scss b/js/packages/react-ui/src/components/Charts/shared/XAxisTick/xAxisTick.scssindex f35c8d225..d01cfc89e 100644--- a/js/packages/react-ui/src/components/Charts/shared/XAxisTick/xAxisTick.scss+++ b/js/packages/react-ui/src/components/Charts/shared/XAxisTick/xAxisTick.scss@@ -1,20 +1,10 @@@use "../../../../cssUtils" as cssUtils;-.crayon-chart-x-axis-tick {- @include cssUtils.typography(label, extra-small);- fill: cssUtils.$secondary-text;-}--.crayon-chart-x-axis-tick-multi-line-container {- // this is the div inside foreignObject- @include cssUtils.typography(label, extra-small);- color: cssUtils.$secondary-text;-}-.crayon-chart-x-axis-tick-multi-line {- color: cssUtils.$secondary-text;margin: 0;padding: 0;+ @include cssUtils.typography(label, extra-small);+ color: cssUtils.$secondary-text;display: -webkit-box;-webkit-box-orient: vertical;line-clamp: 3;@@ -24,3 +14,13 @@word-break: break-word;min-width: 0;}++.crayon-chart-x-axis-tick-single-line {+ @include cssUtils.typography(label, extra-small);+ color: cssUtils.$secondary-text;+ white-space: nowrap;+ overflow: hidden;+ text-overflow: ellipsis;+ width: 100%;+ display: block;+}diff --git a/js/packages/react-ui/src/components/Charts/shared/YAxisTick/YAxisTick.tsx b/js/packages/react-ui/src/components/Charts/shared/YAxisTick/YAxisTick.tsxindex b3d3b1471..9ba948cf4 100644--- a/js/packages/react-ui/src/components/Charts/shared/YAxisTick/YAxisTick.tsx+++ b/js/packages/react-ui/src/components/Charts/shared/YAxisTick/YAxisTick.tsx@@ -1,3 +1,5 @@+import { numberTickFormatter } from "../../utils";+interface YAxisTickProps {x?: number;y?: number;@@ -23,10 +25,12 @@ interface YAxisTickProps {}const YAxisTick: React.FC<YAxisTickProps> = (props) => {- const { x, y, payload, textAnchor, verticalAnchor, tickFormatter, className } = props;+ const { x, y, payload, textAnchor, verticalAnchor, className } = props;- // Use the provided tickFormatter or fallback to displaying raw value- const displayValue = tickFormatter ? tickFormatter(payload?.value) : String(payload?.value || "");+ const displayValue =+ typeof payload?.value === "number"+ ? numberTickFormatter(payload?.value)+ : String(payload?.value);return (<g transform={`translate(${x},${y})`} className={className}>diff --git a/js/packages/react-ui/src/components/Charts/utils/AreaAndLine/AreaAndLineUtils.ts b/js/packages/react-ui/src/components/Charts/utils/AreaAndLine/AreaAndLineUtils.tsindex 367b93ef1..7fefe4570 100644--- a/js/packages/react-ui/src/components/Charts/utils/AreaAndLine/AreaAndLineUtils.ts+++ b/js/packages/react-ui/src/components/Charts/utils/AreaAndLine/AreaAndLineUtils.ts@@ -3,7 +3,6 @@import { AreaChartData } from "../../AreaChart/types";import { LineChartData } from "../../LineChart/types";-import { getCanvasContext } from "../styleUtils";const ELEMENT_SPACING = 72;@@ -40,83 +39,6 @@ export const getWidthOfData = (data: ChartData, containerWidth: number) => {return width;};-/**- * SHARED UTILITY FUNCTION- * This function returns the formatter for the X-axis tick values with intelligent truncation.- * This is identical for both AreaChart and LineChart components.- * @param groupWidth - The width available for each group/category (optional)- * @param containerWidth - The total container width for responsive calculations (optional)- * @returns The formatter for the X-axis tick values.- * Internally used by the XAxis component in Recharts- * this function can be improved for coalition detection and better truncation- */-export const getXAxisTickFormatter = (groupWidth?: number, containerWidth?: number) => {- const PADDING = 10; // More generous padding for visual clarity- const context = getCanvasContext();-- return (value: string) => {- // If canvas isn't supported, or for some reason context is null, return original value.- if (!context) return String(value);-- const stringValue = String(value);-- // Determine the maximum available width for the tick. Prioritize groupWidth.- let availableWidth = 0;- if (groupWidth) {- availableWidth = Math.max(0, groupWidth - PADDING);- } else if (containerWidth) {- // Fallback responsive logic if no groupWidth is available.- // We assume a certain number of ticks could be visible.- // This is less accurate but better than nothing.- const assumedMaxTicks = containerWidth / 100; // e.g., assume ticks are ~100px apart- availableWidth = Math.max(0, containerWidth / assumedMaxTicks - PADDING);- } else {- // No width info at all, perform a simple character slice as a last resort.- return stringValue.length > 10 ? `${stringValue.slice(0, 10)}...` : stringValue;- }-- // If the original text already fits, return it.- if (context.measureText(stringValue).width <= availableWidth) {- return stringValue;- }-- // If it doesn't fit, perform a binary search to find the best truncation point.- let low = 0;- let high = stringValue.length;- let result = "";-- // binary search to find the best truncation point.- while (low <= high) {- const mid = Math.floor((low + high) / 2);- // Don't append "..." if mid is 0, just return an empty string or first char.- if (mid === 0) {- low = mid + 1;- continue;- }- const truncated = stringValue.substring(0, mid) + "...";- const measuredWidth = context.measureText(truncated).width;-- if (measuredWidth <= availableWidth) {- result = truncated;- low = mid + 1;- } else {- high = mid - 1;- }- }-- // A final check: if result is empty (very tight space), it might be better- // to show the first character instead of nothing.- if (result === "") {- const firstChar = stringValue.substring(0, 1);- if (context.measureText(firstChar).width <= availableWidth) {- return firstChar;- }- }-- return result;- };-};-/*** SHARED UTILITY FUNCTION* This function returns the nearest snap position index for both chart types.@@ -165,20 +87,6 @@ export const getWidthOfGroup = (data: ChartData) => {return ELEMENT_SPACING;};-/**- * SHARED UTILITY FUNCTION- * Helper function to get the optimal X-axis tick formatter with calculated group width.- * This is generic and works for both AreaChart and LineChart data.- * @param data - The chart data- * @param containerWidth - The container width for responsive calculations- * @returns The optimized formatter function- */-export const getOptimalXAxisTickFormatter = (data: ChartData, containerWidth?: number) => {- // Calculate the available width per group- const groupWidth = getWidthOfGroup(data);- return getXAxisTickFormatter(groupWidth, containerWidth);-};-/*** SHARED UTILITY FUNCTION* This function returns the snap positions for both chart types, used for smooth scrolling.diff --git a/js/packages/react-ui/src/components/Charts/utils/index.ts b/js/packages/react-ui/src/components/Charts/utils/index.tsnew file mode 100644index 000000000..b1abb1e73--- /dev/null+++ b/js/packages/react-ui/src/components/Charts/utils/index.ts@@ -0,0 +1,3 @@+export * from "./dataUtils";+export * from "./PalletUtils";+export * from "./styleUtils";diff --git a/js/packages/react-ui/src/components/Charts/utils/styleUtils.ts b/js/packages/react-ui/src/components/Charts/utils/styleUtils.tsindex 1839f472c..b1ed9609c 100644--- a/js/packages/react-ui/src/components/Charts/utils/styleUtils.ts+++ b/js/packages/react-ui/src/components/Charts/utils/styleUtils.ts@@ -3,26 +3,24 @@* @returns The formatter for the Y-axis tick values.* internally used by the YAxis component reCharts*/-const getYAxisTickFormatter = () => {- return (value: any) => {- // Format the Y-axis tick values with abbreviations- if (typeof value === "number") {- const absValue = Math.abs(value);+const numberTickFormatter = (value: number) => {+ // Format the Y-axis tick values with abbreviations+ if (typeof value === "number") {+ const absValue = Math.abs(value);- if (absValue >= 1e12) {- return (value / 1e12).toFixed(absValue >= 10e12 ? 0 : 1) + "T";- } else if (absValue >= 1e9) {- return (value / 1e9).toFixed(absValue >= 10e9 ? 0 : 1) + "B";- } else if (absValue >= 1e6) {- return (value / 1e6).toFixed(absValue >= 10e6 ? 0 : 1) + "M";- } else if (absValue >= 1e3) {- return (value / 1e3).toFixed(absValue >= 10e3 ? 0 : 1) + "K";- } else {- return value.toString();- }+ if (absValue >= 1e12) {+ return (value / 1e12).toFixed(absValue >= 10e12 ? 0 : 1) + "T";+ } else if (absValue >= 1e9) {+ return (value / 1e9).toFixed(absValue >= 10e9 ? 0 : 1) + "B";+ } else if (absValue >= 1e6) {+ return (value / 1e6).toFixed(absValue >= 10e6 ? 0 : 1) + "M";+ } else if (absValue >= 1e3) {+ return (value / 1e3).toFixed(absValue >= 10e3 ? 0 : 1) + "K";+ } else {+ return value.toString();}- return String(value);- };+ }+ return String(value);};/**@@ -60,4 +58,4 @@ const getCanvasContext = (): CanvasRenderingContext2D | null => {return context;};-export { getCanvasContext, getYAxisTickFormatter };+export { getCanvasContext, numberTickFormatter };