Skip to content

The Open Standard for Generative UI

Some performance improvement and introducing multi line xaxis ticks, for line, bar and area charts, (#145)

Ankit Dasd6ff776d5869
diff --git a/js/packages/react-ui/src/components/Charts/AreaChart/AreaChart.tsx b/js/packages/react-ui/src/components/Charts/AreaChart/AreaChart.tsx
index 6861723ae..9b11960d4 100644
--- a/js/packages/react-ui/src/components/Charts/AreaChart/AreaChart.tsx
+++ b/js/packages/react-ui/src/components/Charts/AreaChart/AreaChart.tsx
@@ -1,28 +1,27 @@
import clsx from "clsx";
-import { ChevronLeft, ChevronRight } from "lucide-react";
import React, { useCallback, useEffect, useMemo, useRef, useState } from "react";
import { Area, AreaChart as RechartsAreaChart, XAxis, YAxis } from "recharts";
import { useId } from "../../../polyfills";
-import { IconButton } from "../../IconButton";
import { ChartConfig, ChartContainer, ChartTooltip } from "../Charts";
import { SideBarChartData, SideBarTooltipProvider } from "../context/SideBarTooltipContext";
-import { useTransformedKeys } from "../hooks";
+import { useMaxLabelHeight, useTransformedKeys } from "../hooks";
import {
ActiveDot,
cartesianGrid,
CustomTooltipContent,
DefaultLegend,
+ ScrollButtonsHorizontal,
SideBarTooltip,
XAxisTick,
YAxisTick,
} from "../shared";
-import { LegendItem } from "../types";
+import { LegendItem, XAxisTickVariant } from "../types";
import {
findNearestSnapPosition,
getOptimalXAxisTickFormatter,
getSnapPositions,
getWidthOfData,
- getXAxisTickPositionData,
+ getWidthOfGroup,
} from "../utils/AreaAndLine/AreaAndLineUtils";
import { PaletteName, useChartPalette } from "../utils/PalletUtils";
import {
@@ -45,6 +44,7 @@ export interface AreaChartProps<T extends AreaChartData> {
theme?: PaletteName;
customPalette?: string[];
variant?: AreaChartVariant;
+ tickVariant?: XAxisTickVariant;
grid?: boolean;
legend?: boolean;
icons?: Partial<Record<keyof T[number], React.ComponentType>>;
@@ -58,6 +58,7 @@ export interface AreaChartProps<T extends AreaChartData> {
}
const Y_AXIS_WIDTH = 40; // Width of Y-axis chart when shown
+const X_AXIS_PADDING = 36;
const AreaChartComponent = <T extends AreaChartData>({
data,
@@ -65,6 +66,7 @@ const AreaChartComponent = <T extends AreaChartData>({
theme = "ocean",
customPalette,
variant = "natural",
+ tickVariant = "multiLine",
grid = true,
icons = {},
isAnimationActive = false,
@@ -80,6 +82,12 @@ const AreaChartComponent = <T extends AreaChartData>({
return getDataKeys(data, categoryKey as string);
}, [data, categoryKey]);
+ const widthOfGroup = useMemo(() => {
+ return getWidthOfGroup(data);
+ }, [data]);
+
+ const maxLabelHeight = useMaxLabelHeight(data, categoryKey as string, tickVariant, widthOfGroup);
+
const transformedKeys = useTransformedKeys(dataKeys);
const colors = useChartPalette({
@@ -125,19 +133,14 @@ const AreaChartComponent = <T extends AreaChartData>({
}, [data]);
const chartHeight = useMemo(() => {
- return height ?? 296;
- }, [height]);
+ return height ?? 296 + maxLabelHeight;
+ }, [height, maxLabelHeight]);
// Calculate optimal tick formatter for collision detection and truncation
const xAxisTickFormatter = useMemo(() => {
return getOptimalXAxisTickFormatter(data, effectiveContainerWidth);
}, [data, effectiveContainerWidth]);
- // Calculate position data for X-axis tick offset handling
- const xAxisPositionData = useMemo(() => {
- return getXAxisTickPositionData(data, categoryKey as string);
- }, [data, categoryKey]);
-
// Check scroll boundaries
const updateScrollState = useCallback(() => {
if (mainContainerRef.current) {
@@ -225,8 +228,6 @@ const AreaChartComponent = <T extends AreaChartData>({
const id = useId();
- const chartSyncID = useMemo(() => `area-chart-sync-${id}`, [id]);
-
const gradientID = useMemo(() => `area-chart-gradient-${id}`, [id]);
const onAreaClick = useCallback(
@@ -246,6 +247,51 @@ const AreaChartComponent = <T extends AreaChartData>({
[dataKeys, colors],
);
+ const yAxis = useMemo(() => {
+ if (!showYAxis) {
+ return null;
+ }
+ return (
+ <div className="crayon-area-chart-y-axis-container">
+ {/* Y-axis only chart - synchronized with main chart */}
+ <RechartsAreaChart
+ key={`y-axis-chart-${id}`}
+ width={Y_AXIS_WIDTH}
+ height={chartHeight}
+ data={data}
+ margin={{
+ top: 20,
+ bottom: maxLabelHeight, // this is required for to give space for x-axis
+ left: 0,
+ right: 0,
+ }}
+ >
+ <YAxis
+ width={Y_AXIS_WIDTH}
+ tickLine={false}
+ axisLine={false}
+ tickFormatter={getYAxisTickFormatter()}
+ tick={<YAxisTick />}
+ />
+ {/* Invisible area to maintain scale synchronization */}
+ {dataKeys.map((key) => {
+ return (
+ <Area
+ key={`y-axis-${key}`}
+ dataKey={key}
+ type={variant}
+ stroke="none"
+ fill="transparent"
+ fillOpacity={0}
+ stackId="a"
+ />
+ );
+ })}
+ </RechartsAreaChart>
+ </div>
+ );
+ }, [showYAxis, chartHeight, data, dataKeys, variant, id, maxLabelHeight]);
+
return (
<SideBarTooltipProvider
isSideBarTooltipOpen={isSideBarTooltipOpen}
@@ -260,46 +306,8 @@ const AreaChartComponent = <T extends AreaChartData>({
}}
>
<div className="crayon-area-chart-container-inner" ref={chartContainerRef}>
- {showYAxis && (
- <div className="crayon-area-chart-y-axis-container">
- {/* Y-axis only chart - synchronized with main chart */}
- <RechartsAreaChart
- key={`y-axis-chart-${id}`}
- width={Y_AXIS_WIDTH}
- height={chartHeight}
- data={data}
- margin={{
- top: 20,
- bottom: 32, // this is required for to give space for x-axis
- left: 0,
- right: 0,
- }}
- syncId={chartSyncID}
- >
- <YAxis
- width={Y_AXIS_WIDTH}
- tickLine={false}
- axisLine={false}
- tickFormatter={getYAxisTickFormatter()}
- tick={<YAxisTick />}
- />
- {/* Invisible area to maintain scale synchronization */}
- {dataKeys.map((key) => {
- return (
- <Area
- key={`y-axis-${key}`}
- dataKey={key}
- type={variant}
- stroke="none"
- fill="transparent"
- fillOpacity={0}
- stackId="a"
- />
- );
- })}
- </RechartsAreaChart>
- </div>
- )}
+ {/* Y-axis of the chart */}
+ {yAxis}
<div className="crayon-area-chart-main-container" ref={mainContainerRef}>
<ChartContainer
config={chartConfig}
@@ -317,7 +325,6 @@ const AreaChartComponent = <T extends AreaChartData>({
top: 20,
bottom: 0,
}}
- syncId={chartSyncID}
onClick={onAreaClick}
>
{grid && cartesianGrid()}
@@ -328,17 +335,18 @@ const AreaChartComponent = <T extends AreaChartData>({
textAnchor="middle"
interval={0}
tickFormatter={xAxisTickFormatter}
+ height={maxLabelHeight}
tick={
<XAxisTick
- getPositionOffset={xAxisPositionData.getPositionOffset}
- isFirstTick={xAxisPositionData.isFirstTick}
- isLastTick={xAxisPositionData.isLastTick}
+ variant={tickVariant}
+ widthOfGroup={widthOfGroup}
+ labelHeight={maxLabelHeight}
/>
}
orientation="bottom"
padding={{
- left: 25,
- right: 20,
+ left: X_AXIS_PADDING,
+ right: X_AXIS_PADDING,
}}
/>
@@ -387,37 +395,15 @@ const AreaChartComponent = <T extends AreaChartData>({
{isSideBarTooltipOpen && <SideBarTooltip height={chartHeight} />}
</div>
{/* if the data width is greater than the effective width, then show the scroll buttons */}
- {dataWidth > effectiveWidth && (
- <div className="crayon-area-chart-scroll-container">
- <IconButton
- className={clsx(
- "crayon-area-chart-scroll-button crayon-area-chart-scroll-button--left",
- {
- "crayon-area-chart-scroll-button--disabled": !canScrollLeft,
- },
- )}
- icon={<ChevronLeft />}
- variant="secondary"
- onClick={scrollLeft}
- size="extra-small"
- disabled={!canScrollLeft}
- />
- <IconButton
- className={clsx(
- "crayon-area-chart-scroll-button crayon-area-chart-scroll-button--right",
- {
- "crayon-area-chart-scroll-button--disabled": !canScrollRight,
- "crayon-area-chart-scroll-button--SideBarTooltip": isSideBarTooltipOpen,
- },
- )}
- icon={<ChevronRight />}
- variant="secondary"
- size="extra-small"
- onClick={scrollRight}
- disabled={!canScrollRight}
- />
- </div>
- )}
+ <ScrollButtonsHorizontal
+ dataWidth={dataWidth}
+ effectiveWidth={effectiveWidth}
+ canScrollLeft={canScrollLeft}
+ canScrollRight={canScrollRight}
+ isSideBarTooltipOpen={isSideBarTooltipOpen}
+ onScrollLeft={scrollLeft}
+ onScrollRight={scrollRight}
+ />
{legend && (
<DefaultLegend
items={legendItems}
diff --git a/js/packages/react-ui/src/components/Charts/AreaChart/areaChart.scss b/js/packages/react-ui/src/components/Charts/AreaChart/areaChart.scss
index f447954f4..2ced964e3 100644
--- a/js/packages/react-ui/src/components/Charts/AreaChart/areaChart.scss
+++ b/js/packages/react-ui/src/components/Charts/AreaChart/areaChart.scss
@@ -23,40 +23,3 @@
/* Hide scrollbar for IE and Edge */
-ms-overflow-style: none;
}
-
-.crayon-area-chart-scroll-container {
- position: relative;
-}
-
-button.crayon-area-chart-scroll-button {
- position: absolute;
- background-color: cssUtils.$bg-container;
-
- &:hover {
- background-color: cssUtils.$bg-container;
- }
-
- &--left {
- top: -15px;
- transform: translateY(-50%);
- left: 20px;
- }
-
- &--right {
- top: -15px;
- transform: translateY(-50%);
- right: 0px;
- }
-
- &--disabled {
- visibility: hidden;
- cursor: not-allowed;
- transition: visibility 0.1s linear;
- }
-
- &--SideBarTooltip {
- top: -15px;
- transform: translateY(-50%);
- right: 185px;
- }
-}
diff --git a/js/packages/react-ui/src/components/Charts/BarChart/BarChart.tsx b/js/packages/react-ui/src/components/Charts/BarChart/BarChart.tsx
index c9e81dc6e..4f669ceb2 100644
--- a/js/packages/react-ui/src/components/Charts/BarChart/BarChart.tsx
+++ b/js/packages/react-ui/src/components/Charts/BarChart/BarChart.tsx
@@ -1,13 +1,11 @@
import clsx from "clsx";
-import { ChevronLeft, ChevronRight } from "lucide-react";
import React, { useCallback, useEffect, useMemo, useRef, useState } from "react";
import { Bar, BarChart as RechartsBarChart, XAxis, YAxis } from "recharts";
import { useId } from "../../../polyfills";
-import { IconButton } from "../../IconButton";
import { useTheme } from "../../ThemeProvider";
import { ChartConfig, ChartContainer, ChartTooltip } from "../Charts";
import { SideBarChartData, SideBarTooltipProvider } from "../context/SideBarTooltipContext";
-import { useTransformedKeys } from "../hooks";
+import { useMaxLabelHeight, useTransformedKeys } from "../hooks";
import {
cartesianGrid,
CustomTooltipContent,
@@ -16,8 +14,11 @@ import {
XAxisTick,
YAxisTick,
} from "../shared";
-import { type LegendItem } from "../types";
+
+import { ScrollButtonsHorizontal } from "../shared/ScrollButtonsHorizontal/ScrollButtonsHorizontal";
+import { XAxisTickVariant, type LegendItem } from "../types";
import { useChartPalette, type PaletteName } from "../utils/PalletUtils";
+
import {
get2dChartConfig,
getColorForDataKey,
@@ -35,6 +36,7 @@ import {
getRadiusArray,
getSnapPositions,
getWidthOfData,
+ getWidthOfGroup,
} from "./utils/BarChartUtils";
// this a technic to get the type of the onClick event of the bar chart
@@ -47,6 +49,7 @@ export interface BarChartProps<T extends BarChartData> {
theme?: PaletteName;
customPalette?: string[];
variant?: BarChartVariant;
+ tickVariant?: XAxisTickVariant;
grid?: boolean;
radius?: number;
icons?: Partial<Record<keyof T[number], React.ComponentType>>;
@@ -72,6 +75,7 @@ const BarChartComponent = <T extends BarChartData>({
theme = "ocean",
customPalette,
variant = "grouped",
+ tickVariant = "multiLine",
grid = true,
icons = {},
radius = BAR_RADIUS,
@@ -84,6 +88,10 @@ const BarChartComponent = <T extends BarChartData>({
height,
width,
}: BarChartProps<T>) => {
+ const widthOfGroup = getWidthOfGroup(data, categoryKey as string, variant);
+
+ const maxLabelHeight = useMaxLabelHeight(data, categoryKey as string, tickVariant, widthOfGroup);
+
const dataKeys = useMemo(() => {
return getDataKeys(data, categoryKey as string);
}, [data, categoryKey]);
@@ -147,8 +155,8 @@ const BarChartComponent = <T extends BarChartData>({
// we want to chart to scale with width but height will be fixed
const chartHeight = useMemo(() => {
- return height ?? 296;
- }, [height]);
+ return height ?? 296 + maxLabelHeight;
+ }, [height, maxLabelHeight]);
// Check scroll boundaries
const updateScrollState = useCallback(() => {
@@ -237,13 +245,55 @@ const BarChartComponent = <T extends BarChartData>({
const id = useId();
- const chartSyncID = useMemo(() => `bar-chart-sync-${id}`, [id]);
-
// 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;
+ }
+ return (
+ <div className="crayon-bar-chart-y-axis-container">
+ {/* Y-axis only chart - synchronized with main chart */}
+ <RechartsBarChart
+ key={`y-axis-bar-chart-${id}`}
+ width={Y_AXIS_WIDTH}
+ height={chartHeight}
+ data={data}
+ margin={{
+ top: 20,
+ bottom: maxLabelHeight, // this is required for to give space for x-axis
+ left: 0,
+ right: 0,
+ }}
+ >
+ <YAxis
+ width={Y_AXIS_WIDTH}
+ tickLine={false}
+ axisLine={false}
+ tickFormatter={getYAxisTickFormatter()}
+ tick={<YAxisTick />}
+ />
+ {/* Invisible bars to maintain scale synchronization */}
+ {dataKeys.map((key) => {
+ return (
+ <Bar
+ key={`yaxis-bar-chart-${key}`}
+ dataKey={key}
+ fill="transparent"
+ stackId={variant === "stacked" ? "a" : undefined}
+ isAnimationActive={false}
+ maxBarSize={0}
+ />
+ );
+ })}
+ </RechartsBarChart>
+ </div>
+ );
+ }, [showYAxis, chartHeight, data, dataKeys, variant, id, maxLabelHeight]);
+
// Handle mouse events for group hovering
const handleChartMouseMove = useCallback((state: any) => {
if (state && state.activeLabel !== undefined) {
@@ -295,45 +345,8 @@ const BarChartComponent = <T extends BarChartData>({
}}
>
<div className="crayon-bar-chart-container-inner" ref={chartContainerRef}>
- {showYAxis && (
- <div className="crayon-bar-chart-y-axis-container">
- {/* Y-axis only chart - synchronized with main chart */}
- <RechartsBarChart
- key={`y-axis-bar-chart-${id}`}
- width={Y_AXIS_WIDTH}
- height={chartHeight}
- data={data}
- margin={{
- top: 20,
- bottom: 32, // this is required for to give space for x-axis
- left: 0,
- right: 0,
- }}
- syncId={chartSyncID}
- >
- <YAxis
- width={Y_AXIS_WIDTH}
- tickLine={false}
- axisLine={false}
- tickFormatter={getYAxisTickFormatter()}
- tick={<YAxisTick />}
- />
- {/* Invisible bars to maintain scale synchronization */}
- {dataKeys.map((key) => {
- return (
- <Bar
- key={`yaxis-bar-chart-${key}`}
- dataKey={key}
- fill="transparent"
- stackId={variant === "stacked" ? "a" : undefined}
- isAnimationActive={false}
- maxBarSize={0}
- />
- );
- })}
- </RechartsBarChart>
- </div>
- )}
+ {/* Y-axis of the chart */}
+ {yAxis}
<div className="crayon-bar-chart-main-container" ref={mainContainerRef}>
<ChartContainer
config={chartConfig}
@@ -356,17 +369,23 @@ const BarChartComponent = <T extends BarChartData>({
onMouseLeave={handleChartMouseLeave}
barGap={BAR_GAP}
barCategoryGap={BAR_CATEGORY_GAP}
- syncId={chartSyncID}
>
{grid && cartesianGrid()}
<XAxis
dataKey={categoryKey as string}
tickLine={false}
axisLine={false}
- textAnchor="middle"
+ textAnchor={"middle"}
tickFormatter={xAxisTickFormatter}
interval={0}
- tick={<XAxisTick />}
+ height={maxLabelHeight}
+ tick={
+ <XAxisTick
+ variant={tickVariant}
+ widthOfGroup={widthOfGroup}
+ labelHeight={maxLabelHeight}
+ />
+ }
orientation="bottom"
// gives the padding on the 2 sides see the function for reference
padding={padding}
@@ -425,38 +444,15 @@ const BarChartComponent = <T extends BarChartData>({
{isSideBarTooltipOpen && <SideBarTooltip height={chartHeight} />}
</div>
{/* if the data width is greater than the effective width, then show the scroll buttons */}
- {dataWidth > effectiveWidth && (
- <div className="crayon-bar-chart-scroll-container">
- <IconButton
- className={clsx(
- "crayon-bar-chart-scroll-button crayon-bar-chart-scroll-button--left",
- {
- "crayon-bar-chart-scroll-button--disabled": !canScrollLeft,
- },
- )}
- icon={<ChevronLeft />}
- variant="secondary"
- onClick={scrollLeft}
- size="extra-small"
- disabled={!canScrollLeft}
- />
-
- <IconButton
- className={clsx(
- "crayon-bar-chart-scroll-button crayon-bar-chart-scroll-button--right",
- {
- "crayon-bar-chart-scroll-button--disabled": !canScrollRight,
- "crayon-bar-chart-scroll-button--SideBarTooltip": isSideBarTooltipOpen,
- },
- )}
- icon={<ChevronRight />}
- variant="secondary"
- size="extra-small"
- onClick={scrollRight}
- disabled={!canScrollRight}
- />
- </div>
- )}
+ <ScrollButtonsHorizontal
+ dataWidth={dataWidth}
+ effectiveWidth={effectiveWidth}
+ canScrollLeft={canScrollLeft}
+ canScrollRight={canScrollRight}
+ isSideBarTooltipOpen={isSideBarTooltipOpen}
+ onScrollLeft={scrollLeft}
+ onScrollRight={scrollRight}
+ />
{legend && (
<DefaultLegend
items={legendItems}
diff --git a/js/packages/react-ui/src/components/Charts/BarChart/barChart.scss b/js/packages/react-ui/src/components/Charts/BarChart/barChart.scss
index 77438cbd9..75c49e89a 100644
--- a/js/packages/react-ui/src/components/Charts/BarChart/barChart.scss
+++ b/js/packages/react-ui/src/components/Charts/BarChart/barChart.scss
@@ -23,40 +23,3 @@
/* Hide scrollbar for IE and Edge */
-ms-overflow-style: none;
}
-
-.crayon-bar-chart-scroll-container {
- position: relative;
-}
-
-.crayon-bar-chart-scroll-button {
- position: absolute;
- background-color: cssUtils.$bg-container;
-
- &:hover {
- background-color: cssUtils.$bg-container;
- }
-
- &--left {
- top: -15px;
- transform: translateY(-50%);
- left: 20px;
- }
-
- &--right {
- top: -15px;
- transform: translateY(-50%);
- right: 0px;
- }
-
- &--disabled {
- visibility: hidden;
- cursor: not-allowed;
- transition: visibility 0.1s linear;
- }
-
- &--SideBarTooltip {
- top: -15px;
- transform: translateY(-50%);
- right: 185px;
- }
-}
diff --git a/js/packages/react-ui/src/components/Charts/BarChart/stories/barChart.stories.tsx b/js/packages/react-ui/src/components/Charts/BarChart/stories/barChart.stories.tsx
index 65ed580a6..79cc30a84 100644
--- a/js/packages/react-ui/src/components/Charts/BarChart/stories/barChart.stories.tsx
+++ b/js/packages/react-ui/src/components/Charts/BarChart/stories/barChart.stories.tsx
@@ -7,18 +7,90 @@ import { BarChart, BarChartProps } from "../BarChart";
// 📊 ALL DATA VARIATIONS - For easy switching in stories
const dataVariations = {
default: [
- { month: "January", desktop: 150, mobile: 90, tablet: 120, laptop: 180 },
- { month: "February", desktop: 280, mobile: 180, tablet: 140, laptop: 160 },
- { month: "March", desktop: 220, mobile: 140, tablet: 160, laptop: 180 },
- { month: "April", desktop: 180, mobile: 160, tablet: 180, laptop: 200 },
- { month: "May", desktop: 250, mobile: 120, tablet: 140, laptop: 160 },
- { month: "June", desktop: 300, mobile: 180, tablet: 160, laptop: 180 },
- { month: "July", desktop: 350, mobile: 220, tablet: 180, laptop: 200 },
- { month: "August", desktop: 400, mobile: 240, tablet: 200, laptop: 220 },
- { month: "September", desktop: 450, mobile: 260, tablet: 220, laptop: 240 },
- { month: "October", desktop: 500, mobile: 280, tablet: 240, laptop: 260 },
- { month: "November", desktop: 550, mobile: 300, tablet: 260, laptop: 280 },
- { month: "December", desktop: 600, mobile: 320, tablet: 280, laptop: 300 },
+ {
+ month: "January 2024 - First Month of the Year",
+ desktop: 150,
+ mobile: 90,
+ tablet: 120,
+ laptop: 180,
+ },
+ {
+ month: "February 2024 - Second Month of the Year",
+ desktop: 280,
+ mobile: 180,
+ tablet: 140,
+ laptop: 160,
+ },
+ {
+ month: "March 2024 - Third Month of the Year",
+ desktop: 220,
+ mobile: 140,
+ tablet: 160,
+ laptop: 180,
+ },
+ {
+ month: "April 2024 - Fourth Month of the Year",
+ desktop: 180,
+ mobile: 160,
+ tablet: 180,
+ laptop: 200,
+ },
+ {
+ month: "May 2024 - Fifth Month of the Year",
+ desktop: 250,
+ mobile: 120,
+ tablet: 140,
+ laptop: 160,
+ },
+ {
+ month: "June 2024 - Sixth Month of the Year",
+ desktop: 300,
+ mobile: 180,
+ tablet: 160,
+ laptop: 180,
+ },
+ {
+ month: "July 2024 - Seventh Month of the Year",
+ desktop: 350,
+ mobile: 220,
+ tablet: 180,
+ laptop: 200,
+ },
+ {
+ month: "August 2024 - Eighth Month of the Year",
+ desktop: 400,
+ mobile: 240,
+ tablet: 200,
+ laptop: 220,
+ },
+ {
+ month: "September 2024 - Ninth Month of the Year",
+ desktop: 450,
+ mobile: 260,
+ tablet: 220,
+ laptop: 240,
+ },
+ {
+ month: "October 2024 - Tenth Month of the Year",
+ desktop: 500,
+ mobile: 280,
+ tablet: 240,
+ laptop: 260,
+ },
+ {
+ month: "November 2024 - Eleventh Month of the Year",
+ desktop: 550,
+ mobile: 300,
+ tablet: 260,
+ laptop: 280,
+ },
+ {
+ month: "December 2024 - Twelfth Month of the Year",
+ desktop: 600,
+ mobile: 320,
+ tablet: 280,
+ laptop: 300,
+ },
],
small: [
{ month: "Jan", desktop: 150, mobile: 90 },
@@ -466,14 +538,14 @@ const dataVariations = {
},
],
singleGroup: [
- { month: "January", sales: 150 },
- { month: "February", sales: 280 },
- { month: "March", sales: 220 },
- { month: "April", sales: 180 },
- { month: "May", sales: 250 },
- { month: "June", sales: 300 },
- { month: "July", sales: 350 },
- { month: "August", sales: 400 },
+ { month: "January 1st - January 31st, 2024 (Winter Quarter)", sales: 150 },
+ { month: "February 1st - February 28th, 2024 (Winter Quarter)", sales: 280 },
+ { month: "March 1st - March 31st, 2024 (Spring Quarter)", sales: 220 },
+ { month: "April 1st - April 30th, 2024 (Spring Quarter)", sales: 180 },
+ { month: "May 1st - May 31st, 2024 (Spring Quarter)", sales: 250 },
+ { month: "June 1st - June 30th, 2024 (Summer Quarter)", sales: 300 },
+ { month: "July 1st - July 31st, 2024 (Summer Quarter)", sales: 350 },
+ { month: "August 1st - August 31st, 2024 (Summer Quarter)", sales: 400 },
],
};
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.ts
index 93b167e85..e36696d9a 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,4 +1,5 @@
import { getDataKeys } from "../../utils/dataUtils";
+import { getCanvasContext } from "../../utils/styleUtils";
import { BarChartVariant } from "../types";
export const BAR_WIDTH = 16;
@@ -68,8 +69,8 @@ const getPadding = (
if (paddingValue < 0) {
// If chart content is wider than container, no padding
return {
- left: 1,
- right: 1,
+ left: 10,
+ right: 10,
};
} else {
return {
@@ -124,13 +125,7 @@ const getRadiusArray = (
*/
const getXAxisTickFormatter = (groupWidth?: number, variant: BarChartVariant = "grouped") => {
const PADDING = 2; // Safety padding for better visual spacing
-
- // Setup canvas context for accurate text measurement.
- const canvas = document.createElement("canvas");
- const context = canvas.getContext("2d");
- if (context) {
- context.font = "12px Inter";
- }
+ const context = getCanvasContext();
return (value: string) => {
const stringValue = String(value);
@@ -191,7 +186,6 @@ const getOptimalXAxisTickFormatter = (
};
/**
- * INTERNAL HELPER FUNCTION
* 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.
* @param data - The data to be displayed in the chart.
@@ -298,4 +292,5 @@ export {
getRadiusArray,
getSnapPositions,
getWidthOfData,
+ getWidthOfGroup,
};
diff --git a/js/packages/react-ui/src/components/Charts/LineChart/LineChart.tsx b/js/packages/react-ui/src/components/Charts/LineChart/LineChart.tsx
index 7d79a5bd6..5b1a0038b 100644
--- a/js/packages/react-ui/src/components/Charts/LineChart/LineChart.tsx
+++ b/js/packages/react-ui/src/components/Charts/LineChart/LineChart.tsx
@@ -1,28 +1,27 @@
import clsx from "clsx";
-import { ChevronLeft, ChevronRight } from "lucide-react";
import React, { useCallback, useEffect, useMemo, useRef, useState } from "react";
import { Line, LineChart as RechartsLineChart, XAxis, YAxis } from "recharts";
import { useId } from "../../../polyfills";
-import { IconButton } from "../../IconButton";
import { ChartConfig, ChartContainer, ChartTooltip } from "../Charts";
import { SideBarChartData, SideBarTooltipProvider } from "../context/SideBarTooltipContext";
-import { useTransformedKeys } from "../hooks";
+import { useMaxLabelHeight, useTransformedKeys } from "../hooks";
import {
ActiveDot,
cartesianGrid,
CustomTooltipContent,
DefaultLegend,
+ ScrollButtonsHorizontal,
SideBarTooltip,
XAxisTick,
YAxisTick,
} from "../shared";
-import { LegendItem } from "../types";
+import { LegendItem, XAxisTickVariant } from "../types";
import {
findNearestSnapPosition,
getOptimalXAxisTickFormatter,
getSnapPositions,
getWidthOfData,
- getXAxisTickPositionData,
+ getWidthOfGroup,
} from "../utils/AreaAndLine/AreaAndLineUtils";
import { PaletteName, useChartPalette } from "../utils/PalletUtils";
import {
@@ -43,6 +42,7 @@ export interface LineChartProps<T extends LineChartData> {
theme?: PaletteName;
customPalette?: string[];
variant?: LineChartVariant;
+ tickVariant?: XAxisTickVariant;
grid?: boolean;
legend?: boolean;
icons?: Partial<Record<keyof T[number], React.ComponentType>>;
@@ -57,6 +57,7 @@ export interface LineChartProps<T extends LineChartData> {
}
const Y_AXIS_WIDTH = 40; // Width of Y-axis chart when shown
+const X_AXIS_PADDING = 36;
export const LineChart = <T extends LineChartData>({
data,
@@ -64,6 +65,7 @@ export const LineChart = <T extends LineChartData>({
theme = "ocean",
customPalette,
variant = "natural",
+ tickVariant = "multiLine",
grid = true,
icons = {},
isAnimationActive = false,
@@ -80,6 +82,12 @@ export const LineChart = <T extends LineChartData>({
return getDataKeys(data, categoryKey as string);
}, [data, categoryKey]);
+ const widthOfGroup = useMemo(() => {
+ return getWidthOfGroup(data);
+ }, [data]);
+
+ const maxLabelHeight = useMaxLabelHeight(data, categoryKey as string, tickVariant, widthOfGroup);
+
const transformedKeys = useTransformedKeys(dataKeys);
const colors = useChartPalette({
@@ -125,19 +133,14 @@ export const LineChart = <T extends LineChartData>({
}, [data]);
const chartHeight = useMemo(() => {
- return height ?? 296;
- }, [height]);
+ return height ?? 296 + maxLabelHeight;
+ }, [height, maxLabelHeight]);
// Calculate optimal tick formatter for collision detection and truncation
const xAxisTickFormatter = useMemo(() => {
return getOptimalXAxisTickFormatter(data, effectiveContainerWidth);
}, [data, effectiveContainerWidth]);
- // Calculate position data for X-axis tick offset handling
- const xAxisPositionData = useMemo(() => {
- return getXAxisTickPositionData(data, categoryKey as string);
- }, [data, categoryKey]);
-
// Check scroll boundaries
const updateScrollState = useCallback(() => {
if (mainContainerRef.current) {
@@ -224,8 +227,6 @@ export const LineChart = <T extends LineChartData>({
const id = useId();
- const chartSyncID = useMemo(() => `line-chart-sync-${id}`, [id]);
-
const onLineClick = useCallback(
(data: LineClickData) => {
if (data?.activePayload?.length && data.activePayload.length > 10) {
@@ -243,6 +244,63 @@ export const LineChart = <T extends LineChartData>({
[dataKeys, colors],
);
+ const yAxis = useMemo(() => {
+ if (!showYAxis) {
+ return null;
+ }
+ return (
+ <div className="crayon-line-chart-y-axis-container">
+ {/* Y-axis only chart - synchronized with main chart */}
+ <RechartsLineChart
+ key={`y-axis-chart-${id}`}
+ width={Y_AXIS_WIDTH}
+ height={chartHeight}
+ data={data}
+ margin={{
+ top: 20,
+ bottom: maxLabelHeight, // this is required for to give space for x-axis
+ left: 0,
+ right: 0,
+ }}
+ onClick={onLineClick}
+ >
+ <YAxis
+ width={Y_AXIS_WIDTH}
+ tickLine={false}
+ axisLine={false}
+ tickFormatter={getYAxisTickFormatter()}
+ tick={<YAxisTick />}
+ />
+ {/* Invisible lines to maintain scale synchronization */}
+ {dataKeys.map((key) => {
+ return (
+ <Line
+ key={`y-axis-${key}`}
+ dataKey={key}
+ type={variant}
+ stroke="transparent"
+ strokeWidth={0}
+ dot={false}
+ activeDot={false}
+ isAnimationActive={isAnimationActive}
+ />
+ );
+ })}
+ </RechartsLineChart>
+ </div>
+ );
+ }, [
+ showYAxis,
+ id,
+ chartHeight,
+ data,
+ onLineClick,
+ dataKeys,
+ variant,
+ isAnimationActive,
+ maxLabelHeight,
+ ]);
+
return (
<SideBarTooltipProvider
isSideBarTooltipOpen={isSideBarTooltipOpen}
@@ -257,48 +315,8 @@ export const LineChart = <T extends LineChartData>({
}}
>
<div className="crayon-line-chart-container-inner" ref={chartContainerRef}>
- {showYAxis && (
- <div className="crayon-line-chart-y-axis-container">
- {/* Y-axis only chart - synchronized with main chart */}
- <RechartsLineChart
- key={`y-axis-chart-${id}`}
- width={Y_AXIS_WIDTH}
- height={chartHeight}
- data={data}
- margin={{
- top: 20,
- bottom: 32, // this is required for to give space for x-axis
- left: 0,
- right: 0,
- }}
- syncId={chartSyncID}
- onClick={onLineClick}
- >
- <YAxis
- width={Y_AXIS_WIDTH}
- tickLine={false}
- axisLine={false}
- tickFormatter={getYAxisTickFormatter()}
- tick={<YAxisTick />}
- />
- {/* Invisible lines to maintain scale synchronization */}
- {dataKeys.map((key) => {
- return (
- <Line
- key={`y-axis-${key}`}
- dataKey={key}
- type={variant}
- stroke="transparent"
- strokeWidth={0}
- dot={false}
- activeDot={false}
- isAnimationActive={isAnimationActive}
- />
- );
- })}
- </RechartsLineChart>
- </div>
- )}
+ {/* Y-axis of the chart */}
+ {yAxis}
<div className="crayon-line-chart-main-container" ref={mainContainerRef}>
<ChartContainer
config={chartConfig}
@@ -316,7 +334,6 @@ export const LineChart = <T extends LineChartData>({
top: 20,
bottom: 0,
}}
- syncId={chartSyncID}
onClick={onLineClick}
>
{grid && cartesianGrid()}
@@ -324,20 +341,21 @@ export const LineChart = <T extends LineChartData>({
dataKey={categoryKey as string}
tickLine={false}
axisLine={false}
+ height={maxLabelHeight}
textAnchor="middle"
interval={0}
tickFormatter={xAxisTickFormatter}
tick={
<XAxisTick
- getPositionOffset={xAxisPositionData.getPositionOffset}
- isFirstTick={xAxisPositionData.isFirstTick}
- isLastTick={xAxisPositionData.isLastTick}
+ variant={tickVariant}
+ widthOfGroup={widthOfGroup}
+ labelHeight={maxLabelHeight}
/>
}
orientation="bottom"
padding={{
- left: 25,
- right: 20,
+ left: X_AXIS_PADDING,
+ right: X_AXIS_PADDING,
}}
/>
@@ -365,37 +383,15 @@ export const LineChart = <T extends LineChartData>({
{isSideBarTooltipOpen && <SideBarTooltip height={chartHeight} />}
</div>
{/* if the data width is greater than the effective width, then show the scroll buttons */}
- {dataWidth > effectiveWidth && (
- <div className="crayon-line-chart-scroll-container">
- <IconButton
- className={clsx(
- "crayon-line-chart-scroll-button crayon-line-chart-scroll-button--left",
- {
- "crayon-line-chart-scroll-button--disabled": !canScrollLeft,
- },
- )}
- icon={<ChevronLeft />}
- variant="secondary"
- onClick={scrollLeft}
- size="extra-small"
- disabled={!canScrollLeft}
- />
- <IconButton
- className={clsx(
- "crayon-line-chart-scroll-button crayon-line-chart-scroll-button--right",
- {
- "crayon-line-chart-scroll-button--disabled": !canScrollRight,
- "crayon-line-chart-scroll-button--SideBarTooltip": isSideBarTooltipOpen,
- },
- )}
- icon={<ChevronRight />}
- variant="secondary"
- size="extra-small"
- onClick={scrollRight}
- disabled={!canScrollRight}
- />
- </div>
- )}
+ <ScrollButtonsHorizontal
+ dataWidth={dataWidth}
+ effectiveWidth={effectiveWidth}
+ canScrollLeft={canScrollLeft}
+ canScrollRight={canScrollRight}
+ isSideBarTooltipOpen={isSideBarTooltipOpen}
+ onScrollLeft={scrollLeft}
+ onScrollRight={scrollRight}
+ />
{legend && (
<DefaultLegend
items={legendItems}
diff --git a/js/packages/react-ui/src/components/Charts/LineChart/lineChart.scss b/js/packages/react-ui/src/components/Charts/LineChart/lineChart.scss
index 2a2be6ba9..d62a61e58 100644
--- a/js/packages/react-ui/src/components/Charts/LineChart/lineChart.scss
+++ b/js/packages/react-ui/src/components/Charts/LineChart/lineChart.scss
@@ -23,40 +23,3 @@
/* Hide scrollbar for IE and Edge */
-ms-overflow-style: none;
}
-
-.crayon-line-chart-scroll-container {
- position: relative;
-}
-
-button.crayon-line-chart-scroll-button {
- position: absolute;
- background-color: cssUtils.$bg-container;
-
- &:hover {
- background-color: cssUtils.$bg-container;
- }
-
- &--left {
- top: -15px;
- transform: translateY(-50%);
- left: 20px;
- }
-
- &--right {
- top: -15px;
- transform: translateY(-50%);
- right: 0px;
- }
-
- &--disabled {
- visibility: hidden;
- cursor: not-allowed;
- transition: visibility 0.1s linear;
- }
-
- &--SideBarTooltip {
- top: -15px;
- transform: translateY(-50%);
- right: 185px;
- }
-}
diff --git a/js/packages/react-ui/src/components/Charts/charts.scss b/js/packages/react-ui/src/components/Charts/charts.scss
index 759377bed..d364fc021 100644
--- a/js/packages/react-ui/src/components/Charts/charts.scss
+++ b/js/packages/react-ui/src/components/Charts/charts.scss
@@ -27,6 +27,7 @@
@forward "./shared/DefaultLegend/defaultLegend.scss";
@forward "./shared/StackedLegend/stackedLegend.scss";
@forward "./shared/YAxisTick/yAxisTick.scss";
+@forward "./shared/ScrollButtonsHorizontal/scrollButtonsHorizontal.scss";
// portal tooltip css
@forward "./shared/PortalTooltip/portalTooltip.scss";
diff --git a/js/packages/react-ui/src/components/Charts/hooks/index.ts b/js/packages/react-ui/src/components/Charts/hooks/index.ts
index 82638018f..b9f48f801 100644
--- a/js/packages/react-ui/src/components/Charts/hooks/index.ts
+++ b/js/packages/react-ui/src/components/Charts/hooks/index.ts
@@ -1 +1,2 @@
+export * from "./useMaxLabelHeight";
export * from "./useTransformKey";
diff --git a/js/packages/react-ui/src/components/Charts/hooks/useMaxLabelHeight.tsx b/js/packages/react-ui/src/components/Charts/hooks/useMaxLabelHeight.tsx
new file mode 100644
index 000000000..ce719a78f
--- /dev/null
+++ b/js/packages/react-ui/src/components/Charts/hooks/useMaxLabelHeight.tsx
@@ -0,0 +1,68 @@
+import { useMemo } from "react";
+
+import { useTheme } from "../../ThemeProvider";
+import { XAxisTickVariant } from "../types";
+
+const DEFAULT_HEIGHT = 30;
+
+export const useMaxLabelHeight = (
+ data: Record<string, string | number>[],
+ categoryKey: string,
+ tickVariant: XAxisTickVariant,
+ widthOfGroup = 70,
+) => {
+ const { theme: userTheme } = useTheme();
+
+ const maxLabelHeight = useMemo(() => {
+ if (typeof window === "undefined" || !data || data.length === 0) {
+ return DEFAULT_HEIGHT;
+ }
+
+ const largestLabel = data.reduce((max, item) => {
+ const label = String(item[categoryKey]);
+ if (max.length < label.length) {
+ return label;
+ }
+ return max;
+ }, "");
+
+ const [div1, div2, div3] = [
+ document.createElement("div"),
+ document.createElement("div"),
+ document.createElement("div"),
+ ];
+
+ div1.style.font = userTheme.fontLabelExtraSmall ?? "";
+ div1.style.letterSpacing = userTheme.fontLabelExtraSmallLetterSpacing ?? "";
+ div1.style.opacity = "0";
+ div1.style.pointerEvents = "none";
+
+ div2.innerText = largestLabel;
+ div3.innerText = "a";
+ div1.append(div2, div3);
+
+ div1.style.width = `${widthOfGroup}px`;
+ div1.style.maxWidth = `${widthOfGroup}px`;
+ div1.style.wordBreak = "break-word";
+ div1.style.position = "absolute";
+ div1.style.visibility = "hidden";
+
+ document.body.append(div1);
+
+ const largestLabelHeight = Math.min(
+ div2.getBoundingClientRect().height,
+ div3.getBoundingClientRect().height * 3,
+ );
+ div1.remove();
+
+ return largestLabelHeight;
+ }, [data, categoryKey, tickVariant, widthOfGroup]);
+
+ if (tickVariant === "multiLine") {
+ return Math.max(maxLabelHeight + 13, DEFAULT_HEIGHT);
+ } else if (tickVariant === "angled") {
+ return Math.max(maxLabelHeight + 13, DEFAULT_HEIGHT);
+ } else {
+ return DEFAULT_HEIGHT;
+ }
+};
diff --git a/js/packages/react-ui/src/components/Charts/hooks/useTransformKey.tsx b/js/packages/react-ui/src/components/Charts/hooks/useTransformKey.tsx
index fc563b0a4..c6fc6cf60 100644
--- a/js/packages/react-ui/src/components/Charts/hooks/useTransformKey.tsx
+++ b/js/packages/react-ui/src/components/Charts/hooks/useTransformKey.tsx
@@ -12,9 +12,3 @@ export const useTransformedKeys = (keys: string[]) => {
);
}, [keys]);
};
-
-// const transformedKeys = useTransformedKeys(["a", "b", "c"])
-
-// dataKeys.map((key) => {
-// return `var(${transformedKeys[key]})`
-// })
diff --git a/js/packages/react-ui/src/components/Charts/shared/ScrollButtonsHorizontal/ScrollButtonsHorizontal.tsx b/js/packages/react-ui/src/components/Charts/shared/ScrollButtonsHorizontal/ScrollButtonsHorizontal.tsx
new file mode 100644
index 000000000..9d18f83dd
--- /dev/null
+++ b/js/packages/react-ui/src/components/Charts/shared/ScrollButtonsHorizontal/ScrollButtonsHorizontal.tsx
@@ -0,0 +1,65 @@
+import clsx from "clsx";
+import { ChevronLeft, ChevronRight } from "lucide-react";
+import React from "react";
+import { IconButton } from "../../../IconButton";
+
+interface ScrollButtonsHorizontalProps {
+ dataWidth: number;
+ effectiveWidth: number;
+ canScrollLeft: boolean;
+ canScrollRight: boolean;
+ isSideBarTooltipOpen: boolean;
+ onScrollLeft: () => void;
+ onScrollRight: () => void;
+}
+
+export const ScrollButtonsHorizontal = React.memo(
+ ({
+ dataWidth,
+ effectiveWidth,
+ canScrollLeft,
+ canScrollRight,
+ isSideBarTooltipOpen,
+ onScrollLeft,
+ onScrollRight,
+ }: ScrollButtonsHorizontalProps) => {
+ if (dataWidth <= effectiveWidth) {
+ return null;
+ }
+
+ return (
+ <div className="crayon-chart-horizontal-scroll-buttons-container">
+ <IconButton
+ className={clsx(
+ "crayon-chart-horizontal-scroll-button crayon-chart-horizontal-scroll-button--left",
+ {
+ "crayon-chart-horizontal-scroll-button--disabled": !canScrollLeft,
+ },
+ )}
+ icon={<ChevronLeft />}
+ variant="secondary"
+ onClick={onScrollLeft}
+ size="extra-small"
+ disabled={!canScrollLeft}
+ />
+
+ <IconButton
+ className={clsx(
+ "crayon-chart-horizontal-scroll-button crayon-chart-horizontal-scroll-button--right",
+ {
+ "crayon-chart-horizontal-scroll-button--disabled": !canScrollRight,
+ "crayon-chart-horizontal-scroll-button--SideBarTooltip": isSideBarTooltipOpen,
+ },
+ )}
+ icon={<ChevronRight />}
+ variant="secondary"
+ size="extra-small"
+ onClick={onScrollRight}
+ disabled={!canScrollRight}
+ />
+ </div>
+ );
+ },
+);
+
+ScrollButtonsHorizontal.displayName = "ScrollButtonsHorizontal";
diff --git a/js/packages/react-ui/src/components/Charts/shared/ScrollButtonsHorizontal/index.ts b/js/packages/react-ui/src/components/Charts/shared/ScrollButtonsHorizontal/index.ts
new file mode 100644
index 000000000..0c82716bd
--- /dev/null
+++ b/js/packages/react-ui/src/components/Charts/shared/ScrollButtonsHorizontal/index.ts
@@ -0,0 +1 @@
+export * from "./ScrollButtonsHorizontal";
diff --git a/js/packages/react-ui/src/components/Charts/shared/ScrollButtonsHorizontal/scrollButtonsHorizontal.scss b/js/packages/react-ui/src/components/Charts/shared/ScrollButtonsHorizontal/scrollButtonsHorizontal.scss
new file mode 100644
index 000000000..7dbd0d13d
--- /dev/null
+++ b/js/packages/react-ui/src/components/Charts/shared/ScrollButtonsHorizontal/scrollButtonsHorizontal.scss
@@ -0,0 +1,40 @@
+@use "../../../../cssUtils.scss" as cssUtils;
+
+.crayon-chart-horizontal-scroll {
+ &-buttons-container {
+ position: relative;
+ }
+
+ &-button {
+ position: absolute;
+ background-color: cssUtils.$bg-container;
+
+ &:hover {
+ background-color: cssUtils.$bg-container;
+ }
+
+ &--left {
+ top: -12px;
+ transform: translateY(-50%);
+ left: 20px;
+ }
+
+ &--right {
+ top: -12px;
+ transform: translateY(-50%);
+ right: 0px;
+ }
+
+ &--disabled {
+ visibility: hidden;
+ cursor: not-allowed;
+ transition: visibility 0.1s linear;
+ }
+
+ &--SideBarTooltip {
+ top: -12px;
+ transform: translateY(-50%);
+ right: 185px;
+ }
+ }
+}
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.tsx
index 8a1b40d80..f33785593 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,4 +1,5 @@
-import React from "react";
+import React, { useRef } from "react";
+import { XAxisTickVariant } from "../../types";
interface XAxisTickProps {
x?: number;
y?: number;
@@ -21,10 +22,9 @@ interface XAxisTickProps {
tickFormatter?: (value: any) => string;
index?: number;
visibleTicksCount?: number;
- // Extended props for position-based offset handling
- getPositionOffset?: (value: string) => number;
- isFirstTick?: (value: string) => boolean;
- isLastTick?: (value: string) => boolean;
+ variant?: XAxisTickVariant;
+ widthOfGroup?: number;
+ labelHeight?: number;
}
const XAxisTick = React.forwardRef<SVGGElement, XAxisTickProps>((props, ref) => {
@@ -32,43 +32,85 @@ const XAxisTick = React.forwardRef<SVGGElement, XAxisTickProps>((props, ref) =>
x,
y,
payload,
- textAnchor = "middle",
- fill = "#666",
tickFormatter,
className,
- getPositionOffset,
- isFirstTick,
- isLastTick,
+ variant = "multiLine",
+ widthOfGroup = 70,
+ labelHeight = 20,
} = props;
const value = String(payload?.value || "");
- const displayValue = tickFormatter ? tickFormatter(payload?.value) : value;
- // Calculate position offset for first and last labels (optional extension)
- let xOffset = 0;
- if (getPositionOffset) {
- xOffset = getPositionOffset(value);
+ const foreignObjectRef = useRef<SVGForeignObjectElement>(null);
+ const spanRef = useRef<HTMLSpanElement>(null);
+
+ if (x === undefined || y === undefined) {
+ return null;
}
- // Optional text anchor adjustment for first and last labels
- // if the text need to get adjusted then we can do so from here
- let adjustedTextAnchor = textAnchor;
- if (isFirstTick && isFirstTick(value)) {
- adjustedTextAnchor = "middle";
- } else if (isLastTick && isLastTick(value)) {
- adjustedTextAnchor = "middle";
+ 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;
+
+ 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",
+ }}
+ >
+ <span
+ ref={spanRef}
+ style={{
+ textAlign: "center",
+ wordBreak: "break-word",
+ }}
+ className="crayon-chart-x-axis-tick-multi-line"
+ title={value}
+ >
+ {value}
+ </span>
+ </div>
+ </foreignObject>
+ </g>
+ );
}
+ if (variant === "angled") {
+ const displayValue = value;
+ return (
+ <g ref={ref} transform={`translate(${x},${y})`} className={className}>
+ <text
+ x={0}
+ y={0}
+ dy={10}
+ textAnchor="end"
+ transform="rotate(-10)"
+ className="crayon-chart-x-axis-tick"
+ >
+ <title>{value}</title>
+ {displayValue}
+ </text>
+ </g>
+ );
+ }
+
+ const displayValue = tickFormatter ? tickFormatter(payload?.value) : value;
+
return (
<g ref={ref} transform={`translate(${x},${y})`} className={className}>
- <text
- x={xOffset}
- y={0}
- dy={10}
- textAnchor={adjustedTextAnchor}
- fill={fill}
- className="crayon-chart-x-axis-tick"
- >
+ <text x={0} y={0} dy={12} textAnchor={"middle"} className="crayon-chart-x-axis-tick">
<title>{value}</title>
{displayValue}
</text>
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.scss
index 328931058..f35c8d225 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
@@ -4,3 +4,23 @@
@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;
+ display: -webkit-box;
+ -webkit-box-orient: vertical;
+ line-clamp: 3;
+ -webkit-line-clamp: 3;
+ overflow: hidden;
+ text-overflow: ellipsis;
+ word-break: break-word;
+ min-width: 0;
+}
diff --git a/js/packages/react-ui/src/components/Charts/shared/index.ts b/js/packages/react-ui/src/components/Charts/shared/index.ts
index 8d85cffde..7c6a2d0dc 100644
--- a/js/packages/react-ui/src/components/Charts/shared/index.ts
+++ b/js/packages/react-ui/src/components/Charts/shared/index.ts
@@ -2,6 +2,7 @@ export * from "./ActiveDot/ActiveDot";
export * from "./CartesianGrid/cartesianGrid";
export * from "./DefaultLegend/DefaultLegend";
export * from "./PortalTooltip";
+export * from "./ScrollButtonsHorizontal";
export * from "./SideBarTooltip";
export * from "./StackedLegend/StackedLegend";
export * from "./XAxisTick/XAxisTick";
diff --git a/js/packages/react-ui/src/components/Charts/types/XAxisTicks.ts b/js/packages/react-ui/src/components/Charts/types/XAxisTicks.ts
new file mode 100644
index 000000000..03e2e1370
--- /dev/null
+++ b/js/packages/react-ui/src/components/Charts/types/XAxisTicks.ts
@@ -0,0 +1 @@
+export type XAxisTickVariant = "singleLine" | "multiLine" | "angled";
diff --git a/js/packages/react-ui/src/components/Charts/types/index.ts b/js/packages/react-ui/src/components/Charts/types/index.ts
index a39cb6790..9b8f3e3b3 100644
--- a/js/packages/react-ui/src/components/Charts/types/index.ts
+++ b/js/packages/react-ui/src/components/Charts/types/index.ts
@@ -1 +1,2 @@
export * from "./Legend";
+export * from "./XAxisTicks";
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.ts
index fafef7c0d..367b93ef1 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,8 +3,9 @@
import { AreaChartData } from "../../AreaChart/types";
import { LineChartData } from "../../LineChart/types";
+import { getCanvasContext } from "../styleUtils";
-const ELEMENT_SPACING = 70;
+const ELEMENT_SPACING = 72;
// Common type for chart data - both AreaChart and LineChart data structures
type ChartData = AreaChartData | LineChartData;
@@ -16,28 +17,24 @@ type ChartData = AreaChartData | LineChartData;
* @param data - The data to be displayed in the chart.
*/
export const getWidthOfData = (data: ChartData, containerWidth: number) => {
- // For area charts, we calculate based on the number of data points (always stacked)
- const numberOfElements = data.length; // Number of data points
-
- let width = numberOfElements * ELEMENT_SPACING - ELEMENT_SPACING; // here we are defining the spacing between the data points,
- // as the data point has no width, we are just calculating the spacing between the data points
- // if 3 data points, then 2 spaces between them, so 2*70 = 140
- // so the subtraction is to remove the last spacing as number of data points is 1 more than the number of spaces
+ if (data.length === 0) {
+ return containerWidth;
+ }
+ // For area charts, we calculate based on the number of data points.
+ // We use getWidthOfGroup to ensure consistency
+ const width = data.length * getWidthOfGroup(data);
// if the container width is greater than the width of the data, then we return the container width
// because the we need the chart minimum width to be the container width
// this decision is made because area chart an bar chart are span from the left to the right of the container
-
if (containerWidth >= width) {
return containerWidth;
}
if (data.length === 1) {
const minSingleDataWidth = 200; // Minimum width for single data points
- // self note:
// if the data point is only one, then we need to set the width to the minimum width
-
- width = Math.max(width, minSingleDataWidth);
+ return Math.max(width, minSingleDataWidth);
}
return width;
@@ -55,14 +52,7 @@ export const getWidthOfData = (data: ChartData, containerWidth: number) => {
*/
export const getXAxisTickFormatter = (groupWidth?: number, containerWidth?: number) => {
const PADDING = 10; // More generous padding for visual clarity
-
- // Setup canvas context once per formatter creation for efficiency.
- const canvas = document.createElement("canvas");
- const context = canvas.getContext("2d");
- if (context) {
- // Should match the chart's actual font for accuracy
- context.font = "12px Inter";
- }
+ const context = getCanvasContext();
return (value: string) => {
// If canvas isn't supported, or for some reason context is null, return original value.
@@ -189,41 +179,6 @@ export const getOptimalXAxisTickFormatter = (data: ChartData, containerWidth?: n
return getXAxisTickFormatter(groupWidth, containerWidth);
};
-/**
- * SHARED UTILITY FUNCTION
- * Helper function to get position information for X-axis ticks with offset handling.
- * This is generic and works for both AreaChart and LineChart data.
- * @param data - The chart data
- * @param categoryKey - The category key for the chart
- * @returns Object containing position data for the tick renderer
- */
-export const getXAxisTickPositionData = (data: ChartData, categoryKey: string) => {
- return {
- dataLength: data.length,
- categoryValues: data.map((item) => String(item[categoryKey])),
- getPositionOffset: (value: string): number => {
- const index = data.findIndex((item) => String(item[categoryKey]) === value);
- if (index === 0) {
- // First label: offset to the right by 5px
- return 5;
- } else if (index === data.length - 1) {
- // Last label: offset to the left by 5px
- return -5;
- }
- // Middle labels: no offset
- return 0;
- },
- isFirstTick: (value: string): boolean => {
- const index = data.findIndex((item) => String(item[categoryKey]) === value);
- return index === 0;
- },
- isLastTick: (value: string): boolean => {
- const index = data.findIndex((item) => String(item[categoryKey]) === value);
- return index === data.length - 1;
- },
- };
-};
-
/**
* 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/styleUtils.ts b/js/packages/react-ui/src/components/Charts/utils/styleUtils.ts
index dddbf55c2..1839f472c 100644
--- a/js/packages/react-ui/src/components/Charts/utils/styleUtils.ts
+++ b/js/packages/react-ui/src/components/Charts/utils/styleUtils.ts
@@ -25,4 +25,39 @@ const getYAxisTickFormatter = () => {
};
};
-export { getYAxisTickFormatter };
+/**
+ * Creates a canvas 2D rendering context and sets its font style.
+ *
+ * This function initializes a canvas element in memory, gets its 2D context,
+ * and then attempts to apply a font style based on the `--crayon-font-label-extra-small`
+ * CSS custom property from the document's body. It includes a fallback to a default
+ * font if the custom property is not available (e.g., in an SSR environment).
+ *
+ * @returns The canvas 2D context with the font style applied, or `null` if the
+ * context could not be created.
+ */
+const getCanvasContext = (): CanvasRenderingContext2D | null => {
+ if (typeof document === "undefined" || typeof window === "undefined") {
+ return null;
+ }
+ const canvas = document.createElement("canvas");
+ const context = canvas.getContext("2d");
+ if (context) {
+ // Should match the chart's actual font for accuracy.
+ // The font is defined in `xAxisTick.scss` via a mixin, which uses the
+ // CSS variable `--crayon-font-label-extra-small`.
+ // in future we have to target the actual element instead of the body
+ let font = "12px Inter"; // Default fallback.
+ const value = window
+ .getComputedStyle(document.body)
+ .getPropertyValue("--crayon-font-label-extra-small");
+ // trim is important, it can come with whitespace.
+ if (value) {
+ font = value.trim();
+ }
+ context.font = font;
+ }
+ return context;
+};
+
+export { getCanvasContext, getYAxisTickFormatter };
diff --git a/js/packages/react-ui/src/components/CopilotShell/stories/Shell.stories.tsx b/js/packages/react-ui/src/components/CopilotShell/stories/Shell.stories.tsx
index 0bab03593..5fab3c30f 100644
--- a/js/packages/react-ui/src/components/CopilotShell/stories/Shell.stories.tsx
+++ b/js/packages/react-ui/src/components/CopilotShell/stories/Shell.stories.tsx
@@ -19,7 +19,7 @@ import logoUrl from "./thesysdev_logo.jpeg";
export default {
title: "Copilot Shell",
- tags: ["dev", "!autodocs"],
+ tags: ["!dev", "!autodocs"],
};
export const Default = {
diff --git a/js/packages/react-ui/src/components/CrayonChat/stories/CrayonChat.stories.tsx b/js/packages/react-ui/src/components/CrayonChat/stories/CrayonChat.stories.tsx
index 16919999d..06bcdfa59 100644
--- a/js/packages/react-ui/src/components/CrayonChat/stories/CrayonChat.stories.tsx
+++ b/js/packages/react-ui/src/components/CrayonChat/stories/CrayonChat.stories.tsx
@@ -3,7 +3,7 @@ import { CrayonChat } from "../CrayonChat";
export default {
title: "Components/CrayonChat",
- tags: ["dev", "!autodocs"],
+ tags: ["!dev", "!autodocs"],
argTypes: {
type: {
control: "select",
diff --git a/js/packages/react-ui/src/components/Shell/stories/Shell.stories.tsx b/js/packages/react-ui/src/components/Shell/stories/Shell.stories.tsx
index 40cd59f6e..eb51f4a67 100644
--- a/js/packages/react-ui/src/components/Shell/stories/Shell.stories.tsx
+++ b/js/packages/react-ui/src/components/Shell/stories/Shell.stories.tsx
@@ -14,7 +14,7 @@ import logoUrl from "./thesysdev_logo.jpeg";
export default {
title: "Shell",
- tags: ["dev", "!autodocs"],
+ tags: ["!dev", "!autodocs"],
};
export const Default = {
diff --git a/js/packages/react-ui/src/components/ThemeProvider/ThemeProvider.tsx b/js/packages/react-ui/src/components/ThemeProvider/ThemeProvider.tsx
index 1ffffb485..76cacb695 100644
--- a/js/packages/react-ui/src/components/ThemeProvider/ThemeProvider.tsx
+++ b/js/packages/react-ui/src/components/ThemeProvider/ThemeProvider.tsx
@@ -23,7 +23,7 @@ export const useTheme = () => {
const context = useContext(ThemeContext);
if (!context) {
return {
- theme: lightTheme,
+ theme: themes.light,
mode: "light",
};
}