Skip to content

The Open Standard for Generative UI

Horizontal bar chart (#153)

subhamab40ef6ca12e
diff --git a/js/packages/react-ui/package.json b/js/packages/react-ui/package.json
index 6ed42e5a6..023e4fd17 100644
--- a/js/packages/react-ui/package.json
+++ b/js/packages/react-ui/package.json
@@ -2,7 +2,7 @@
"type": "module",
"name": "@crayonai/react-ui",
"license": "MIT",
- "version": "0.8.6",
+ "version": "0.8.7",
"description": "Component library for Generative UI SDK",
"main": "dist/index.js",
"types": "dist/index.d.ts",
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 71c28519b..0c9d532bc 100644
--- a/js/packages/react-ui/src/components/Charts/BarChart/BarChart.tsx
+++ b/js/packages/react-ui/src/components/Charts/BarChart/BarChart.tsx
@@ -10,6 +10,7 @@ import {
cartesianGrid,
CustomTooltipContent,
DefaultLegend,
+ LineInBarShape,
SideBarTooltip,
XAxisTick,
XAxisTickProps,
@@ -17,23 +18,22 @@ import {
} from "../shared";
import { ScrollButtonsHorizontal } from "../shared/ScrollButtonsHorizontal/ScrollButtonsHorizontal";
-import { XAxisTickVariant, type LegendItem } from "../types";
+import { XAxisTickVariant } from "../types";
+import { type LegendItem } from "../types/Legend";
import { useChartPalette, type PaletteName } from "../utils/PalletUtils";
import { LabelTooltipProvider } from "../shared/LabelTooltip/LabelTooltip";
+import { findNearestSnapPosition, getRadiusArray } from "../utils/BarCharts/BarChartsUtils";
import {
get2dChartConfig,
getColorForDataKey,
getDataKeys,
getLegendItems,
} from "../utils/dataUtils";
-import { LineInBarShape } from "./components/LineInBarShape";
import { BarChartData, BarChartVariant } from "./types";
import {
BAR_WIDTH,
- findNearestSnapPosition,
getPadding,
- getRadiusArray,
getSnapPositions,
getWidthOfData,
getWidthOfGroup,
@@ -347,6 +347,7 @@ const BarChartComponent = <T extends BarChartData>({
radius={getRadiusArray(
variant,
radius,
+ "vertical",
variant === "stacked" ? isFirstInStack : undefined,
variant === "stacked" ? isLastInStack : undefined,
)}
diff --git a/js/packages/react-ui/src/components/Charts/BarChart/BarSeries.tsx b/js/packages/react-ui/src/components/Charts/BarChart/BarSeries.tsx
index 8456e81b2..7fa14f418 100644
--- a/js/packages/react-ui/src/components/Charts/BarChart/BarSeries.tsx
+++ b/js/packages/react-ui/src/components/Charts/BarChart/BarSeries.tsx
@@ -1,7 +1,8 @@
import { Bar } from "recharts";
-import { LineInBarShape } from "./components/LineInBarShape";
+import { LineInBarShape } from "../shared";
+import { getRadiusArray } from "../utils/BarCharts/BarChartsUtils";
import { BarChartVariant } from "./types";
-import { BAR_WIDTH, getRadiusArray } from "./utils/BarChartUtils";
+import { BAR_WIDTH } from "./utils/BarChartUtils";
const BAR_INTERNAL_LINE_WIDTH = 1;
@@ -42,6 +43,7 @@ export const BarSeries = ({
radius={getRadiusArray(
variant,
radius,
+ "vertical",
variant === "stacked" ? isFirstInStack : undefined,
variant === "stacked" ? isLastInStack : undefined,
)}
diff --git a/js/packages/react-ui/src/components/Charts/BarChart/components/LineInBarShape.tsx b/js/packages/react-ui/src/components/Charts/BarChart/components/LineInBarShape.tsx
deleted file mode 100644
index 091677f10..000000000
--- a/js/packages/react-ui/src/components/Charts/BarChart/components/LineInBarShape.tsx
+++ /dev/null
@@ -1,200 +0,0 @@
-import React, { FunctionComponent, useMemo } from "react";
-
-interface BarWithInternalLineProps {
- x?: number;
- y?: number;
- width?: number;
- height?: number;
- fill?: string;
- stroke?: string;
- strokeWidth?: number | string;
- radius?: number | number[];
- internalLineColor?: string;
- internalLineWidth?: number;
- isHovered?: boolean;
- hoveredCategory?: string | number | null;
- categoryKey?: string;
- payload?: any;
- // New props for stacked bar gaps
- variant?: "grouped" | "stacked";
- stackGap?: number;
-
- // Recharts also passes other props like payload, value, etc.
- // we can add them here if our shape component needs them.
- // console.log("props", props);
- [key: string]: any; // Allow other props from Recharts
-}
-
-const DEFAULT_STACK_GAP = 1;
-const MIN_LINE_HEIGHT = 8;
-const LINE_PADDING = 6;
-const MIN_GROUP_BAR_HEIGHT = 2;
-const MIN_STACKED_BAR_HEIGHT = 4;
-
-const LineInBarShape: FunctionComponent<BarWithInternalLineProps> = React.memo((props) => {
- const {
- x = 0, // Default to 0 to avoid NaN issues if undefined
- y = 0,
- width = 0,
- height = 0,
- fill,
- radius: r, // Renaming to avoid conflict with BarChartV2's radius prop
- stroke,
- strokeWidth,
- internalLineColor: iLineColor, // Use prop or fallback
- internalLineWidth: iLineWidth,
- isHovered,
- hoveredCategory,
- categoryKey,
- payload,
- variant = "grouped",
- stackGap = DEFAULT_STACK_GAP, // Default 1px gap
- } = props;
-
- // Memoized radius calculations - Ensure rTL and rTR are always numbers, defaulting to 0.
- // This calculation is memoized to avoid recalculating on every render when radius prop hasn't changed
- const { rTL, rTR } = useMemo(() => {
- // For grouped bars, if the height is too small, we should not apply corner radius
- // as it can lead to weird shapes. MIN_LINE_HEIGHT is a reasonable threshold.
- if (variant === "grouped" && height < MIN_GROUP_BAR_HEIGHT) {
- return { rTL: 0, rTR: 0 };
- }
-
- if (variant === "stacked" && height < MIN_STACKED_BAR_HEIGHT) {
- return { rTL: 0, rTR: 0 };
- }
-
- if (Array.isArray(r)) {
- return { rTL: r[0] || 0, rTR: r[1] || 0 };
- } else if (typeof r === "number") {
- return { rTL: r, rTR: r };
- }
- return { rTL: 0, rTR: 0 };
- }, [r, variant, height]);
-
- // Memoized opacity calculation for hover effects
- // Calculate the opacity value for the bar based on hover state
- // When a category is hovered:
- // - Bars in the hovered category maintain full opacity (1)
- // - All other bars are dimmed to 60% opacity (0.6)
- // This creates a visual hierarchy highlighting the hovered category
- //
- // @default 1 - Full opacity when no hover state is active
- // @requires isHovered - Boolean indicating if any category is being hovered
- // @requires hoveredCategory - The category value currently being hovered (string|number|null)
- // @requires payload - The data payload for this bar containing category information
- // @requires categoryKey - The key used to access the category value in the payload
- const opacity = useMemo(() => {
- if (!isHovered || hoveredCategory === null || !payload || !categoryKey) {
- return 1;
- }
- const currentCategoryValue = payload[categoryKey];
- return currentCategoryValue === hoveredCategory ? 1 : 0.4;
- }, [isHovered, hoveredCategory, payload, categoryKey]);
-
- // Memoized adjusted dimensions for stacked bar gaps
- // Adjust dimensions for stacked bar gaps
- // This creates visual separation between bars in a stack by reducing height only
- // We don't adjust Y position to avoid double gaps and positioning issues
- // Only reduce height at the top of each bar except the last one (bottom-most in stack)
- // This creates a gap between this bar and the bar above it
- const { adjustedY, adjustedHeight } = useMemo(() => {
- let finalHeight = height;
- if (variant === "stacked" && stackGap > 0) {
- finalHeight = height - stackGap;
- }
-
- // Enforce a minimum height for visibility, but only if the original height is non-zero.
- // This prevents bars with a value of 0 from being rendered.
- if (height > 0 && variant === "grouped") {
- finalHeight = Math.max(finalHeight, MIN_GROUP_BAR_HEIGHT);
- }
-
- if (height > 0 && variant === "stacked") {
- finalHeight = Math.max(finalHeight, MIN_STACKED_BAR_HEIGHT - stackGap);
- }
-
- // We need to adjust the y position to keep the bar bottom-aligned
- // when we enforce a minimum height.
- const finalY = y + height - finalHeight;
-
- return {
- adjustedY: finalY,
- adjustedHeight: finalHeight,
- };
- }, [variant, stackGap, y, height]);
-
- // Memoized SVG path calculation for optimized rendering
- // Path data for a rectangle with potentially rounded top corners and stack gaps
- // M = move to, L = line to, A = arc, Z = close path
- // Handle cases where rTL or rTR might be 0 (sharp corners)
- // This SVG path string creates a rectangle with optional rounded top corners
- // The path is constructed using SVG path commands:
- // M = Move to starting point
- // L = Draw line to point
- // A = Draw arc (rx,ry rotation large-arc-flag sweep-flag x,y)
- // Z = Close path back to start
- //
- // The path construction:
- // 1. Starts at bottom left corner (x, adjustedY+rTL)
- // 2. If rTL > 0, draws arc for top left corner, else draws straight line
- // 3. Draws line across top to right side
- // 4. If rTR > 0, draws arc for top right corner, else draws straight line
- // 5. Draws straight line down right side
- // 6. Draws straight line across bottom
- // 7. Closes path back to start
- const path = useMemo(() => {
- return `
- M ${x},${adjustedY + rTL}
- ${rTL > 0 ? `A ${rTL},${rTL} 0 0 1 ${x + rTL},${adjustedY}` : `L ${x},${adjustedY}`}
- L ${x + width - rTR},${adjustedY}
- ${rTR > 0 ? `A ${rTR},${rTR} 0 0 1 ${x + width},${adjustedY + rTR}` : `L ${x + width},${adjustedY}`}
- L ${x + width},${adjustedY + adjustedHeight}
- L ${x},${adjustedY + adjustedHeight}
- Z
- `;
- }, [x, adjustedY, adjustedHeight, width, rTL, rTR]);
-
- // Memoized line coordinates calculation for the internal vertical line
- // Only calculate coordinates if bar has sufficient width and height
- // The internal line is centered horizontally and padded vertically for better visual appearance
- const lineCoords = useMemo(() => {
- if (width <= 0 || adjustedHeight <= MIN_LINE_HEIGHT) {
- return null;
- }
-
- const centerX = x + width / 2;
- return {
- x1: centerX,
- y1: adjustedY + LINE_PADDING, // Starts below the top edge of the adjusted bar
- x2: centerX,
- y2: adjustedY + adjustedHeight - LINE_PADDING, // Ends above the bottom edge of the adjusted bar
- };
- }, [x, width, adjustedY, adjustedHeight]);
-
- return (
- <g>
- {/* The main bar shape (using <path> for rounded corners and stack gaps) */}
- <path d={path} fill={fill} stroke={stroke} strokeWidth={strokeWidth} opacity={opacity} />
-
- {/* The internal vertical line - adjusted for stack gaps */}
- {lineCoords && (
- <line
- x1={lineCoords.x1}
- y1={lineCoords.y1}
- x2={lineCoords.x2}
- y2={lineCoords.y2}
- stroke={iLineColor}
- strokeWidth={iLineWidth}
- strokeLinecap="round"
- opacity={opacity}
- />
- )}
- </g>
- );
-});
-
-// Add display name for better debugging
-LineInBarShape.displayName = "LineInBarShape";
-
-export { LineInBarShape };
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 0f6cbff72..ea465fa27 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
@@ -79,41 +79,6 @@ const getPadding = (
}
};
-/**
- * This function returns the radius for the chart, used for the radius of the LineInBarShape.tsx.
- * @param variant - The variant of the chart.
- * @param radius - The radius of the chart.
- * @param isFirst - Whether the first item in the stack.
- * @param isLast - Whether the last item in the stack.
- */
-const getRadiusArray = (
- variant: BarChartVariant,
- radius: number,
- isFirst?: boolean,
- isLast?: boolean,
-): [number, number, number, number] => {
- if (variant === "grouped") {
- return [radius, radius, 0, 0];
- } else if (variant === "stacked") {
- if (isFirst && isLast) {
- // Single item in stack
- return [radius, radius, radius, radius];
- }
- if (isFirst) {
- // Bottom of the stack
- return [0, 0, 0, 0];
- }
- if (isLast) {
- // Top of the stack
- return [radius, radius, 0, 0];
- }
- // Middle of the stack
- return [0, 0, 0, 0];
- }
- // Default or other variants
- return [radius, radius, radius, radius];
-};
-
/**
* 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.
@@ -170,55 +135,4 @@ const getSnapPositions = (
return positions;
};
-/**
- * This function returns the nearest snap position for the chart, used for the nearest snap position of the chart.
- * @param snapPositions - The snap positions for the chart.
- * @param currentScroll - The current scroll of the chart.
- * @param direction - The direction of the scroll.
- * @returns The nearest snap position for the chart.
- */
-const findNearestSnapPosition = (
- snapPositions: number[],
- currentScroll: number,
- direction: "left" | "right",
-): number => {
- // Find current position index
- let currentIndex = 0;
- for (let i = 0; i < snapPositions.length; i++) {
- const snapPosition = snapPositions[i]!;
- if (currentScroll >= snapPosition) {
- currentIndex = i;
- } else {
- break;
- }
- }
-
- if (direction === "left") {
- // Go to previous snap position
- return Math.max(0, currentIndex - 1);
- } else {
- // Go to next snap position
- return Math.min(snapPositions.length - 1, currentIndex + 1);
- }
-};
-
-/**
- * This function returns the chart height for the chart, used for the chart height of the chart.
- * @param containerWidth - The width of the container of the chart.
- * @returns The chart height for the chart.
- * 16:9 aspect ratio
- * to change the aspect ratio, change the 9/16 to the desired aspect ratio
- */
-const getChartHeight = (containerWidth: number): number => {
- return containerWidth ? containerWidth * (9 / 16) : 400;
-};
-
-export {
- findNearestSnapPosition,
- getChartHeight,
- getPadding,
- getRadiusArray,
- getSnapPositions,
- getWidthOfData,
- getWidthOfGroup,
-};
+export { getPadding, getSnapPositions, getWidthOfData, getWidthOfGroup };
diff --git a/js/packages/react-ui/src/components/Charts/HorizontalBarChart/HorizontalBarChart.tsx b/js/packages/react-ui/src/components/Charts/HorizontalBarChart/HorizontalBarChart.tsx
new file mode 100644
index 000000000..5ee115f6b
--- /dev/null
+++ b/js/packages/react-ui/src/components/Charts/HorizontalBarChart/HorizontalBarChart.tsx
@@ -0,0 +1,468 @@
+import clsx from "clsx";
+import React, { useCallback, useEffect, useMemo, useRef, useState } from "react";
+import { Bar, BarChart as RechartsBarChart, XAxis, YAxis } from "recharts";
+import { useId } from "../../../polyfills";
+import { useTheme } from "../../ThemeProvider";
+import { ChartConfig, ChartContainer, ChartTooltip } from "../Charts";
+import { SideBarChartData, SideBarTooltipProvider } from "../context/SideBarTooltipContext";
+import { useTransformedKeys } from "../hooks";
+import { useHorizontalBarLabelHeight } from "../hooks/useMaxLabelHeight";
+import {
+ CustomTooltipContent,
+ DefaultLegend,
+ SideBarTooltip,
+ verticalCartesianGrid,
+ YAxisTick,
+} from "../shared";
+import { ScrollButtonsVertical } from "../shared/ScrollButtonsVertical";
+
+import { type LegendItem } from "../types/Legend";
+import { useChartPalette, type PaletteName } from "../utils/PalletUtils";
+
+import { LabelTooltipProvider } from "../shared/LabelTooltip/LabelTooltip";
+import { findNearestSnapPosition, getRadiusArray } from "../utils/BarCharts/BarChartsUtils";
+import {
+ get2dChartConfig,
+ getColorForDataKey,
+ getDataKeys,
+ getLegendItems,
+} from "../utils/dataUtils";
+import { numberTickFormatter } from "../utils/styleUtils";
+import { CustomBarShape } from "./components/CustomBarShape";
+import { HorizontalBarChartData, HorizontalBarChartVariant } from "./types";
+import {
+ BAR_GAP,
+ BAR_HEIGHT,
+ getHeightOfData,
+ getMaxCategoryLabelWidth,
+ getPadding,
+ getSnapPositions,
+} from "./utils/HorizontalBarChartUtils";
+
+// Type for onClick event
+type HorizontalBarChartOnClick = React.ComponentProps<typeof RechartsBarChart>["onClick"];
+type HorizontalBarClickData = Parameters<NonNullable<HorizontalBarChartOnClick>>[0];
+
+export interface HorizontalBarChartProps<T extends HorizontalBarChartData> {
+ data: T;
+ categoryKey: keyof T[number];
+ theme?: PaletteName;
+ customPalette?: string[];
+ variant?: HorizontalBarChartVariant;
+ grid?: boolean;
+ radius?: number;
+ icons?: Partial<Record<keyof T[number], React.ComponentType>>;
+ isAnimationActive?: boolean;
+ showXAxis?: boolean;
+ xAxisLabel?: React.ReactNode;
+ yAxisLabel?: React.ReactNode;
+ legend?: boolean;
+ className?: string;
+ height?: number;
+ width?: number;
+}
+
+const X_AXIS_HEIGHT = 40; // Height of X-axis chart when shown
+const BAR_CATEGORY_GAP = "20%"; // Gap between categories
+const BAR_INTERNAL_LINE_WIDTH = 1;
+const BAR_RADIUS = 4;
+
+const HorizontalBarChartComponent = <T extends HorizontalBarChartData>({
+ data,
+ categoryKey,
+ theme = "ocean",
+ customPalette,
+ variant = "grouped",
+ grid = true,
+ icons = {},
+ radius = BAR_RADIUS,
+ isAnimationActive = false,
+ showXAxis = true,
+ xAxisLabel,
+ yAxisLabel,
+ legend = true,
+ className,
+ height,
+ width,
+}: HorizontalBarChartProps<T>) => {
+ const maxCategoryLabelWidth = getMaxCategoryLabelWidth(data, categoryKey as string);
+
+ const chartContainerRef = useRef<HTMLDivElement>(null);
+ const mainContainerRef = useRef<HTMLDivElement>(null);
+ const [containerWidth, setContainerWidth] = useState<number>(0);
+ const [canScrollUp, setCanScrollUp] = useState(false);
+ const [canScrollDown, setCanScrollDown] = useState(false);
+ const [hoveredCategory, setHoveredCategory] = useState<string | number | null>(null);
+ const [isLegendExpanded, setIsLegendExpanded] = useState(false);
+ const [isSideBarTooltipOpen, setIsSideBarTooltipOpen] = useState(false);
+ const [sideBarTooltipData, setSideBarTooltipData] = useState<SideBarChartData>({
+ title: "",
+ values: [],
+ });
+
+ // Calculate chart width for internal calculations (legend, xAxis, etc.)
+ const effectiveWidth = useMemo(() => {
+ return width ?? containerWidth;
+ }, [width, containerWidth]);
+
+ // Calculate label height for better group height calculation
+ // Use chart width for label height calculation since labels span full width
+ const labelHeight = useHorizontalBarLabelHeight(data, categoryKey as string, effectiveWidth);
+
+ const dataKeys = useMemo(() => {
+ return getDataKeys(data, categoryKey as string);
+ }, [data, categoryKey]);
+
+ const transformedKeys = useTransformedKeys(dataKeys);
+
+ const colors = useChartPalette({
+ chartThemeName: theme,
+ customPalette,
+ themePaletteName: "barChartPalette",
+ dataLength: dataKeys.length,
+ });
+
+ const chartConfig: ChartConfig = useMemo(() => {
+ return get2dChartConfig(dataKeys, colors, transformedKeys, undefined, icons);
+ }, [dataKeys, icons, colors, transformedKeys]);
+
+ // Use provided height or observed height
+ const effectiveHeight = useMemo(() => {
+ return height ?? 296 + X_AXIS_HEIGHT;
+ }, [height]);
+
+ // Calculate effective container height (excluding X-axis)
+ const effectiveContainerHeight = useMemo(() => {
+ const xAxisHeight = showXAxis ? X_AXIS_HEIGHT : 0;
+ return Math.max(0, effectiveHeight - xAxisHeight);
+ }, [effectiveHeight, showXAxis]);
+
+ const padding = useMemo(() => {
+ return getPadding(data, categoryKey as string, effectiveContainerHeight, variant, labelHeight);
+ }, [data, categoryKey, effectiveContainerHeight, variant, labelHeight]);
+
+ const dataHeight = useMemo(() => {
+ return getHeightOfData(data, categoryKey as string, variant, labelHeight);
+ }, [data, categoryKey, variant, labelHeight]);
+
+ // Calculate snap positions for proper group alignment
+ const snapPositions = useMemo(() => {
+ return getSnapPositions(data, categoryKey as string, variant, labelHeight);
+ }, [data, categoryKey, variant, labelHeight]);
+
+ // Check scroll boundaries
+ const updateScrollState = useCallback(() => {
+ if (mainContainerRef.current) {
+ const { scrollTop, scrollHeight, clientHeight } = mainContainerRef.current;
+ setCanScrollUp(scrollTop > 0);
+ setCanScrollDown(scrollTop < scrollHeight - clientHeight - 1);
+ }
+ }, []);
+
+ const scrollUp = useCallback(() => {
+ if (mainContainerRef.current) {
+ const currentScroll = mainContainerRef.current.scrollTop;
+ const targetIndex = findNearestSnapPosition(snapPositions, currentScroll, "up");
+ const targetPosition = snapPositions[targetIndex] ?? 0;
+
+ mainContainerRef.current.scrollTo({
+ top: targetPosition,
+ behavior: "smooth",
+ });
+ }
+ }, [snapPositions]);
+
+ const scrollDown = useCallback(() => {
+ if (mainContainerRef.current) {
+ const currentScroll = mainContainerRef.current.scrollTop;
+ const targetIndex = findNearestSnapPosition(snapPositions, currentScroll, "down");
+ const targetPosition = snapPositions[targetIndex] ?? 0;
+
+ mainContainerRef.current.scrollTo({
+ top: targetPosition,
+ behavior: "smooth",
+ });
+ }
+ }, [snapPositions]);
+
+ useEffect(() => {
+ // Set up ResizeObserver if height or width is not provided
+ if (!chartContainerRef.current) {
+ return () => {};
+ }
+
+ const resizeObserver = new ResizeObserver((entries) => {
+ for (const entry of entries) {
+ if (!width) {
+ setContainerWidth(entry.contentRect.width);
+ }
+ }
+ });
+
+ resizeObserver.observe(chartContainerRef.current);
+
+ return () => {
+ resizeObserver.disconnect();
+ };
+ }, [height, width]);
+
+ // Update scroll state when container dimensions or data height changes
+ useEffect(() => {
+ updateScrollState();
+ }, [effectiveContainerHeight, dataHeight, containerWidth, updateScrollState]);
+
+ useEffect(() => {
+ setIsSideBarTooltipOpen(false);
+ setIsLegendExpanded(false);
+ }, [dataKeys]);
+
+ // Add scroll event listener to update button states
+ useEffect(() => {
+ const mainContainer = mainContainerRef.current;
+ if (!mainContainer) return;
+
+ const handleScroll = () => {
+ updateScrollState();
+ };
+
+ mainContainer.addEventListener("scroll", handleScroll);
+ return () => {
+ mainContainer.removeEventListener("scroll", handleScroll);
+ };
+ }, [updateScrollState]);
+
+ // Memoize legend items creation
+ const legendItems: LegendItem[] = useMemo(() => {
+ return getLegendItems(dataKeys, colors, icons);
+ }, [dataKeys, colors, icons]);
+
+ const id = useId();
+
+ const xAxis = useMemo(() => {
+ if (!showXAxis) {
+ return null;
+ }
+ return (
+ <div className="crayon-horizontal-bar-chart-x-axis-container">
+ {/* X-axis only chart - synchronized with main chart */}
+ <ChartContainer
+ config={chartConfig}
+ style={{ width: "100%", height: X_AXIS_HEIGHT }}
+ rechartsProps={{
+ height: X_AXIS_HEIGHT,
+ }}
+ >
+ <RechartsBarChart
+ key={`x-axis-horizontal-bar-chart-${id}`}
+ data={data}
+ layout="vertical"
+ margin={{
+ top: 0,
+ bottom: 0,
+ left: 5,
+ right: 2,
+ }}
+ >
+ <XAxis
+ type="number"
+ height={X_AXIS_HEIGHT}
+ tickLine={false}
+ axisLine={false}
+ tickFormatter={numberTickFormatter}
+ tick={{ fontSize: 12 }}
+ />
+ {/* Invisible bars to maintain scale synchronization */}
+ {dataKeys.map((key) => {
+ return (
+ <Bar
+ key={`xaxis-horizontal-bar-chart-${key}`}
+ dataKey={key}
+ fill="transparent"
+ stackId={variant === "stacked" ? "a" : undefined}
+ isAnimationActive={false}
+ maxBarSize={0}
+ />
+ );
+ })}
+ </RechartsBarChart>
+ </ChartContainer>
+ </div>
+ );
+ }, [showXAxis, chartConfig, data, dataKeys, variant, id, maxCategoryLabelWidth]);
+
+ // Handle mouse events for group hovering
+ const handleChartMouseMove = useCallback((state: any) => {
+ if (state && state.activeLabel !== undefined) {
+ setHoveredCategory(state.activeLabel);
+ }
+ }, []);
+
+ const handleChartMouseLeave = useCallback(() => {
+ setHoveredCategory(null);
+ }, []);
+
+ const { mode } = useTheme();
+
+ const barInternalLineColor = useMemo(() => {
+ if (mode === "light") {
+ return "rgba(255, 255, 255, 0.3)";
+ }
+ return "rgba(0, 0, 0, 0.3)";
+ }, [mode]);
+
+ const onBarsClick = useCallback(
+ (data: HorizontalBarClickData) => {
+ if (data?.activePayload?.length && data.activePayload.length > 10) {
+ setIsSideBarTooltipOpen(true);
+ setSideBarTooltipData({
+ title: data.activeLabel as string,
+ values: data.activePayload.map((payload) => ({
+ value: payload.value as number,
+ label: payload.name || payload.dataKey,
+ color: getColorForDataKey(payload.dataKey, dataKeys, colors),
+ })),
+ });
+ }
+ },
+ [dataKeys, colors],
+ );
+
+ return (
+ <LabelTooltipProvider>
+ <SideBarTooltipProvider
+ isSideBarTooltipOpen={isSideBarTooltipOpen}
+ setIsSideBarTooltipOpen={setIsSideBarTooltipOpen}
+ data={sideBarTooltipData}
+ setData={setSideBarTooltipData}
+ >
+ <div className={clsx("crayon-horizontal-bar-chart-container", className)}>
+ <div
+ className="crayon-horizontal-bar-chart-container-inner-wrapper"
+ style={{
+ height: height ? `${height}px` : effectiveHeight,
+ }}
+ >
+ <div className="crayon-horizontal-bar-chart-container-inner" ref={chartContainerRef}>
+ <div className="crayon-horizontal-bar-chart-main-container" ref={mainContainerRef}>
+ <ChartContainer
+ config={chartConfig}
+ style={{ height: dataHeight, minHeight: "100%", width: "100%" }}
+ >
+ <RechartsBarChart
+ accessibilityLayer
+ key={`horizontal-bar-chart-${id}`}
+ data={data}
+ layout="vertical"
+ onClick={onBarsClick}
+ onMouseMove={handleChartMouseMove}
+ onMouseLeave={handleChartMouseLeave}
+ barGap={BAR_GAP}
+ barCategoryGap={BAR_CATEGORY_GAP}
+ margin={{
+ top: 0,
+ bottom: 0,
+ left: 2,
+ right: 2,
+ }}
+ >
+ {grid && verticalCartesianGrid()}
+ <XAxis type="number" tickLine={false} axisLine={false} hide />
+ <YAxis
+ type="category"
+ dataKey={categoryKey as string}
+ tickLine={false}
+ axisLine={false}
+ width={maxCategoryLabelWidth}
+ tick={<YAxisTick />}
+ interval={0}
+ // gives the padding on the 2 sides see the function for reference
+ padding={padding}
+ hide
+ />
+
+ <ChartTooltip
+ cursor={{
+ fill: "var(--crayon-sunk-fills)",
+ stroke: "var(--crayon-stroke-default)",
+ opacity: 1,
+ strokeWidth: 1,
+ }}
+ content={<CustomTooltipContent />}
+ 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,
+ "horizontal",
+ variant === "stacked" ? isFirstInStack : undefined,
+ variant === "stacked" ? isLastInStack : undefined,
+ )}
+ stackId={variant === "stacked" ? "a" : undefined}
+ isAnimationActive={isAnimationActive}
+ maxBarSize={BAR_HEIGHT}
+ barSize={BAR_HEIGHT}
+ shape={
+ <CustomBarShape
+ index={index}
+ categoryKey={categoryKey as string}
+ effectiveWidth={effectiveWidth}
+ labelHeight={labelHeight}
+ barInternalLineColor={barInternalLineColor}
+ internalLineWidth={BAR_INTERNAL_LINE_WIDTH}
+ hoveredCategory={hoveredCategory}
+ variant={variant}
+ />
+ }
+ />
+ );
+ })}
+ </RechartsBarChart>
+ </ChartContainer>
+ </div>
+ {/* X-axis of the chart */}
+ {xAxis}
+ </div>
+ {/* if the data height is greater than the effective height, then show the scroll buttons */}
+ <ScrollButtonsVertical
+ dataHeight={dataHeight}
+ effectiveHeight={effectiveContainerHeight}
+ canScrollUp={canScrollUp}
+ canScrollDown={canScrollDown}
+ isSideBarTooltipOpen={isSideBarTooltipOpen}
+ onScrollUp={scrollUp}
+ onScrollDown={scrollDown}
+ />
+ {isSideBarTooltipOpen && <SideBarTooltip height={effectiveHeight} />}
+ </div>
+ {legend && (
+ <DefaultLegend
+ items={legendItems}
+ yAxisLabel={yAxisLabel}
+ xAxisLabel={xAxisLabel}
+ containerWidth={effectiveWidth}
+ isExpanded={isLegendExpanded}
+ setIsExpanded={setIsLegendExpanded}
+ />
+ )}
+ </div>
+ </SideBarTooltipProvider>
+ </LabelTooltipProvider>
+ );
+};
+
+// Added React.memo for performance optimization to avoid unnecessary re-renders
+export const HorizontalBarChart = React.memo(
+ HorizontalBarChartComponent,
+) as typeof HorizontalBarChartComponent;
diff --git a/js/packages/react-ui/src/components/Charts/HorizontalBarChart/components/CustomBarShape.tsx b/js/packages/react-ui/src/components/Charts/HorizontalBarChart/components/CustomBarShape.tsx
new file mode 100644
index 000000000..2607c1e5a
--- /dev/null
+++ b/js/packages/react-ui/src/components/Charts/HorizontalBarChart/components/CustomBarShape.tsx
@@ -0,0 +1,87 @@
+import React from "react";
+
+import { LineInBarShape } from "../../shared";
+import { type HorizontalBarChartVariant } from "../types";
+
+interface CustomBarShapeProps {
+ // from recharts (can be more)
+ x?: number;
+ y?: number;
+ width?: number;
+ height?: number;
+ payload?: any;
+ // from parent scope
+ index: number;
+ categoryKey: string;
+ effectiveWidth: number;
+ labelHeight: number;
+ barInternalLineColor: string;
+ internalLineWidth: number;
+ hoveredCategory: string | number | null;
+ variant: HorizontalBarChartVariant;
+}
+
+const CustomBarShapeComponent = (props: CustomBarShapeProps) => {
+ const {
+ // recharts props
+ y,
+ payload,
+ // my props
+ index,
+ categoryKey,
+ effectiveWidth,
+ labelHeight,
+ barInternalLineColor,
+ internalLineWidth,
+ hoveredCategory,
+ variant,
+ // rest of recharts props to pass down
+ ...rest
+ } = props;
+
+ // y might be undefined if not passed by recharts, but it's used.
+ // The original code has `let { y } = barProps;`. If `barProps.y` is undefined, `y` is undefined.
+ // The same for `payload`.
+ if (y === undefined || !payload) {
+ return null; // Or some fallback
+ }
+
+ let label = null;
+ if (index === 0 && payload[categoryKey]) {
+ const labelX = 0;
+ const labelWidth = effectiveWidth;
+ const labelY = y - labelHeight / 2;
+ label = (
+ <foreignObject
+ x={labelX}
+ y={labelY}
+ width={labelWidth}
+ height={labelHeight}
+ style={{ pointerEvents: "none" }}
+ xmlns="http://www.w3.org/1999/xhtml"
+ >
+ <div className="crayon-horizontal-bar-chart-category-label">{payload[categoryKey]}</div>
+ </foreignObject>
+ );
+ }
+
+ return (
+ <g>
+ {label}
+ <LineInBarShape
+ {...rest}
+ payload={payload}
+ y={y + labelHeight / 2}
+ internalLineColor={barInternalLineColor}
+ internalLineWidth={internalLineWidth}
+ isHovered={hoveredCategory !== null}
+ hoveredCategory={hoveredCategory}
+ categoryKey={categoryKey as string}
+ variant={variant}
+ orientation="horizontal"
+ />
+ </g>
+ );
+};
+
+export const CustomBarShape = React.memo(CustomBarShapeComponent);
diff --git a/js/packages/react-ui/src/components/Charts/HorizontalBarChart/dependencies.ts b/js/packages/react-ui/src/components/Charts/HorizontalBarChart/dependencies.ts
new file mode 100644
index 000000000..e69de29bb
diff --git a/js/packages/react-ui/src/components/Charts/HorizontalBarChart/horizontalBarChart.scss b/js/packages/react-ui/src/components/Charts/HorizontalBarChart/horizontalBarChart.scss
new file mode 100644
index 000000000..b5f96492c
--- /dev/null
+++ b/js/packages/react-ui/src/components/Charts/HorizontalBarChart/horizontalBarChart.scss
@@ -0,0 +1,62 @@
+@use "../../../cssUtils" as cssUtils;
+
+.crayon-horizontal-bar-chart-container {
+ position: relative;
+ width: 100%;
+ height: auto;
+ display: flex;
+ flex-direction: column;
+
+ .crayon-horizontal-bar-chart-container-inner {
+ position: relative;
+ display: flex;
+ flex-direction: column;
+ width: 100%;
+ flex: 1;
+ min-width: 0;
+ }
+
+ .crayon-horizontal-bar-chart-x-axis-container {
+ flex-shrink: 0;
+ width: 100%;
+ box-sizing: border-box;
+ border-top: 1px solid cssUtils.$stroke-default;
+ padding-top: cssUtils.$spacing-2xs;
+ }
+
+ .crayon-horizontal-bar-chart-container-inner-wrapper {
+ width: 100%;
+ display: flex;
+ flex-direction: row;
+ width: 100%;
+ overflow: hidden;
+ }
+
+ .crayon-horizontal-bar-chart-main-container {
+ height: 100%;
+ overflow-y: auto;
+ /* Hide scrollbar for Chrome, Safari and Opera */
+ &::-webkit-scrollbar {
+ display: none;
+ }
+
+ /* Hide scrollbar for Firefox */
+ scrollbar-width: none;
+
+ /* Hide scrollbar for IE and Edge */
+ -ms-overflow-style: none;
+ }
+
+ .crayon-horizontal-bar-chart-category-label {
+ display: flex;
+ align-items: center;
+ color: cssUtils.$secondary-text;
+ @include cssUtils.typography(label, extra-small);
+ overflow: hidden;
+ white-space: nowrap;
+ text-overflow: ellipsis;
+ width: 100%;
+ padding-left: cssUtils.$spacing-m;
+ box-sizing: border-box;
+ }
+}
diff --git a/js/packages/react-ui/src/components/Charts/HorizontalBarChart/index.ts b/js/packages/react-ui/src/components/Charts/HorizontalBarChart/index.ts
new file mode 100644
index 000000000..e45239e58
--- /dev/null
+++ b/js/packages/react-ui/src/components/Charts/HorizontalBarChart/index.ts
@@ -0,0 +1,2 @@
+export * from "./HorizontalBarChart";
+export * from "./types";
diff --git a/js/packages/react-ui/src/components/Charts/HorizontalBarChart/stories/HorizontalBarChart.stories.tsx b/js/packages/react-ui/src/components/Charts/HorizontalBarChart/stories/HorizontalBarChart.stories.tsx
new file mode 100644
index 000000000..689438af7
--- /dev/null
+++ b/js/packages/react-ui/src/components/Charts/HorizontalBarChart/stories/HorizontalBarChart.stories.tsx
@@ -0,0 +1,879 @@
+import type { Meta, StoryObj } from "@storybook/react";
+import { Monitor, TabletSmartphone } from "lucide-react";
+import { useState } from "react";
+import { Card } from "../../../Card";
+import { HorizontalBarChart, HorizontalBarChartProps } from "../HorizontalBarChart";
+
+// πŸ“Š ALL DATA VARIATIONS - For easy switching in stories
+const dataVariations = {
+ default: [
+ {
+ category: "A",
+ desktop: 150,
+ mobile: 90,
+ tablet: 120,
+ laptop: 180,
+ },
+ {
+ category: "B",
+ desktop: 280,
+ mobile: 180,
+ tablet: 140,
+ laptop: 160,
+ },
+ {
+ category: "C",
+ desktop: 220,
+ mobile: 140,
+ tablet: 160,
+ laptop: 180,
+ },
+ {
+ category: "D",
+ desktop: 180,
+ mobile: 160,
+ tablet: 180,
+ laptop: 200,
+ },
+ {
+ category: "E",
+ desktop: 250,
+ mobile: 120,
+ tablet: 140,
+ laptop: 160,
+ },
+ ],
+ small: [
+ { category: "Q1", desktop: 150, mobile: 90 },
+ { category: "Q2", desktop: 280, mobile: 180 },
+ { category: "Q3", desktop: 220, mobile: 140 },
+ ],
+ large: [
+ {
+ category: "North America",
+ revenue: 150000,
+ expenses: 90000,
+ profit: 60000,
+ marketing: 30000,
+ operations: 40000,
+ },
+ {
+ category: "Europe",
+ revenue: 280000,
+ expenses: 180000,
+ profit: 100000,
+ marketing: 50000,
+ operations: 70000,
+ },
+ {
+ category: "Asia Pacific",
+ revenue: 220000,
+ expenses: 140000,
+ profit: 80000,
+ marketing: 40000,
+ operations: 60000,
+ },
+ {
+ category: "Latin America",
+ revenue: 180000,
+ expenses: 160000,
+ profit: 20000,
+ marketing: 35000,
+ operations: 55000,
+ },
+ {
+ category: "Middle East",
+ revenue: 250000,
+ expenses: 120000,
+ profit: 130000,
+ marketing: 45000,
+ operations: 65000,
+ },
+ {
+ category: "Africa",
+ revenue: 120000,
+ expenses: 80000,
+ profit: 40000,
+ marketing: 25000,
+ operations: 35000,
+ },
+ {
+ category: "Oceania",
+ revenue: 95000,
+ expenses: 65000,
+ profit: 30000,
+ marketing: 20000,
+ operations: 25000,
+ },
+ {
+ category: "Southeast Asia",
+ revenue: 180000,
+ expenses: 110000,
+ profit: 70000,
+ marketing: 35000,
+ operations: 50000,
+ },
+ {
+ category: "Eastern Europe",
+ revenue: 140000,
+ expenses: 95000,
+ profit: 45000,
+ marketing: 28000,
+ operations: 42000,
+ },
+ {
+ category: "Scandinavia",
+ revenue: 160000,
+ expenses: 100000,
+ profit: 60000,
+ marketing: 32000,
+ operations: 48000,
+ },
+ ],
+ simple: [
+ { department: "Sales", performance: 1200 },
+ { department: "Marketing", performance: 950 },
+ { department: "Engineering", performance: 1100 },
+ { department: "Support", performance: 800 },
+ ],
+ edge: [{ period: "Current Quarter", sales: 500, target: 600 }],
+ bigNumbers: [
+ { company: "Apple Inc.", revenue: 394328000000, profit: 99803000000 },
+ { company: "Microsoft Corp.", revenue: 211915000000, profit: 83383000000 },
+ { company: "Alphabet Inc.", revenue: 307394000000, profit: 76033000000 },
+ { company: "Amazon.com Inc.", revenue: 574785000000, profit: 33364000000 },
+ ],
+ expandCollapseChannels: [
+ {
+ channel: "Website Traffic and Organic Search Results",
+ impressions: 120000,
+ clicks: 15000,
+ conversions: 1200,
+ cost: 8500,
+ revenue: 24000,
+ roi: 182,
+ ctr: 12.5,
+ cpc: 0.57,
+ cpa: 7.08,
+ reach: 95000,
+ engagement: 8200,
+ shares: 420,
+ saves: 180,
+ comments: 650,
+ videoViews: 0,
+ },
+ {
+ channel: "Social Media Engagement and Brand Awareness",
+ impressions: 85000,
+ clicks: 12000,
+ conversions: 950,
+ cost: 6200,
+ revenue: 19000,
+ roi: 206,
+ ctr: 14.1,
+ cpc: 0.52,
+ cpa: 6.53,
+ reach: 72000,
+ engagement: 15400,
+ shares: 890,
+ saves: 340,
+ comments: 1200,
+ videoViews: 28000,
+ },
+ {
+ channel: "Email Marketing Campaign Performance",
+ impressions: 45000,
+ clicks: 8500,
+ conversions: 800,
+ cost: 2100,
+ revenue: 16000,
+ roi: 562,
+ ctr: 18.9,
+ cpc: 0.25,
+ cpa: 2.63,
+ reach: 42000,
+ engagement: 6800,
+ shares: 120,
+ saves: 85,
+ comments: 240,
+ videoViews: 0,
+ },
+ {
+ channel: "Paid Advertising and PPC Campaign ROI",
+ impressions: 95000,
+ clicks: 18000,
+ conversions: 1500,
+ cost: 12500,
+ revenue: 30000,
+ roi: 140,
+ ctr: 18.9,
+ cpc: 0.69,
+ cpa: 8.33,
+ reach: 88000,
+ engagement: 12600,
+ shares: 320,
+ saves: 150,
+ comments: 480,
+ videoViews: 5200,
+ },
+ {
+ channel: "Content Marketing and Blog Performance",
+ impressions: 60000,
+ clicks: 9500,
+ conversions: 750,
+ cost: 4800,
+ revenue: 15000,
+ roi: 213,
+ ctr: 15.8,
+ cpc: 0.51,
+ cpa: 6.4,
+ reach: 55000,
+ engagement: 7800,
+ shares: 680,
+ saves: 420,
+ comments: 950,
+ videoViews: 12000,
+ },
+ {
+ channel: "Mobile Application Downloads and Usage",
+ impressions: 70000,
+ clicks: 11000,
+ conversions: 1100,
+ cost: 5500,
+ revenue: 22000,
+ roi: 300,
+ ctr: 15.7,
+ cpc: 0.5,
+ cpa: 5.0,
+ reach: 65000,
+ engagement: 9200,
+ shares: 180,
+ saves: 95,
+ comments: 320,
+ videoViews: 8500,
+ },
+ {
+ channel: "Customer Support Response Time and Quality",
+ impressions: 35000,
+ clicks: 5500,
+ conversions: 450,
+ cost: 2800,
+ revenue: 9000,
+ roi: 221,
+ ctr: 15.7,
+ cpc: 0.51,
+ cpa: 6.22,
+ reach: 32000,
+ engagement: 4200,
+ shares: 45,
+ saves: 25,
+ comments: 180,
+ videoViews: 0,
+ },
+ {
+ channel: "Sales Funnel Conversion and Lead Generation",
+ impressions: 110000,
+ clicks: 22000,
+ conversions: 1800,
+ cost: 15000,
+ revenue: 36000,
+ roi: 140,
+ ctr: 20.0,
+ cpc: 0.68,
+ cpa: 8.33,
+ reach: 98000,
+ engagement: 18500,
+ shares: 420,
+ saves: 280,
+ comments: 750,
+ videoViews: 3200,
+ },
+ {
+ channel: "User Retention and Churn Rate Analysis",
+ impressions: 80000,
+ clicks: 14000,
+ conversions: 1200,
+ cost: 7200,
+ revenue: 24000,
+ roi: 233,
+ ctr: 17.5,
+ cpc: 0.51,
+ cpa: 6.0,
+ reach: 75000,
+ engagement: 11200,
+ shares: 280,
+ saves: 150,
+ comments: 420,
+ videoViews: 6800,
+ },
+ {
+ channel: "Product Feature Usage and Performance Metrics",
+ impressions: 65000,
+ clicks: 10500,
+ conversions: 900,
+ cost: 5200,
+ revenue: 18000,
+ roi: 246,
+ ctr: 16.2,
+ cpc: 0.5,
+ cpa: 5.78,
+ reach: 58000,
+ engagement: 8500,
+ shares: 320,
+ saves: 180,
+ comments: 650,
+ videoViews: 4200,
+ },
+ {
+ channel: "Market Research and Competitive Analysis",
+ impressions: 40000,
+ clicks: 6500,
+ conversions: 500,
+ cost: 3200,
+ revenue: 10000,
+ roi: 213,
+ ctr: 16.3,
+ cpc: 0.49,
+ cpa: 6.4,
+ reach: 36000,
+ engagement: 5200,
+ shares: 95,
+ saves: 65,
+ comments: 220,
+ videoViews: 1800,
+ },
+ {
+ channel: "Brand Sentiment and Public Relations Impact",
+ impressions: 55000,
+ clicks: 8000,
+ conversions: 650,
+ cost: 4100,
+ revenue: 13000,
+ roi: 217,
+ ctr: 14.5,
+ cpc: 0.51,
+ cpa: 6.31,
+ reach: 48000,
+ engagement: 6800,
+ shares: 520,
+ saves: 280,
+ comments: 950,
+ videoViews: 15000,
+ },
+ ],
+ singleGroup: [
+ { region: "North America (USA, Canada, Mexico)", sales: 150000 },
+ { region: "Europe (UK, Germany, France, Italy)", sales: 280000 },
+ { region: "Asia Pacific (Japan, Australia, South Korea)", sales: 220000 },
+ { region: "Latin America (Brazil, Argentina, Chile)", sales: 180000 },
+ { region: "Middle East (UAE, Saudi Arabia, Israel)", sales: 250000 },
+ ],
+};
+
+// Category key mappings for different datasets
+const categoryKeys = {
+ default: "category",
+ small: "category",
+ large: "category",
+ simple: "department",
+ edge: "period",
+ bigNumbers: "company",
+ expandCollapseChannels: "channel",
+ singleGroup: "region",
+};
+
+// πŸ”₯ ACTIVE DATA - For backward compatibility
+const horizontalBarChartData = dataVariations.default;
+
+const icons = {
+ desktop: Monitor,
+ mobile: TabletSmartphone,
+} as const;
+
+/**
+ * # HorizontalBarChart Component Documentation
+ *
+ * The HorizontalBarChart is a versatile component for comparing values across different categories in a horizontal layout.
+ * It's highly effective for:
+ *
+ * - **Category Comparison**: Easily compare metrics like sales, performance, or revenue across different groups.
+ * - **Ranking**: Show the highest and lowest performing items with a clear visual hierarchy.
+ * - **Data with Long Labels**: Perfect for datasets with lengthy category names that don't fit well in vertical layouts.
+ *
+ * ## Key Features
+ *
+ * ### Layout Variants
+ * - **Grouped**: Compare sub-categories side-by-side within a primary category.
+ * - **Stacked**: Show how sub-categories contribute to a total value for each primary category.
+ *
+ * ### Interactive & Responsive
+ * - **Vertical Scrolling**: Automatically enables scrolling when the number of bars exceeds the container height.
+ * - **Interactive Legend**: Toggle data series on and off. Handles overflow with a "Show More" button.
+ * - **Hover Tooltips**: Provides detailed data on hover for better user engagement.
+ * - **Responsive Design**: Adjusts gracefully to the size of its container.
+ *
+ * ### Customization
+ * - **Theming**: Six built-in color palettes, or use custom colors with `customPalette`.
+ * - **Bar Styling**: Customize the corner radius of the bars.
+ * - **Axis and Grid Control**: Toggle visibility of axes and grid lines.
+ */
+const meta: Meta<HorizontalBarChartProps<typeof horizontalBarChartData>> = {
+ title: "Components/Charts/HorizontalBarChart",
+ component: HorizontalBarChart,
+ parameters: {
+ layout: "centered",
+ docs: {
+ description: {
+ component: `
+## Installation and Basic Usage
+
+\`\`\`tsx
+import { HorizontalBarChart } from '@crayon-ui/react-ui/Charts/HorizontalBarChart';
+
+const salesData = [
+ { region: "North America", sales: 150000, profit: 45000 },
+ { region: "Europe", sales: 280000, profit: 68000 },
+ { region: "Asia Pacific", sales: 220000, profit: 52000 },
+];
+
+// Basic implementation
+<HorizontalBarChart
+ data={salesData}
+ categoryKey="region"
+ theme="ocean"
+/>
+
+// With custom colors
+<HorizontalBarChart
+ data={salesData}
+ categoryKey="region"
+ customPalette={["#FF6B6B", "#4ECDC4", "#45B7D1"]}
+/>
+\`\`\`
+
+## Data Structure Requirements
+
+Your data should be an array of objects. Each object must contain:
+- A **category field** (string or number): Used for the Y-axis labels (e.g., regions, departments).
+- One or more **data series fields** (number): These are the values that will be plotted as bars. The key of the field is used as the series name in the legend and tooltip.
+
+\`\`\`tsx
+const performanceData = [
+ { department: "Sales", performance: 5400, target: 6000 },
+ { department: "Marketing", performance: 8200, target: 7500 },
+ { department: "Engineering", performance: 7100, target: 7000 },
+];
+\`\`\`
+
+## Performance Considerations
+- **Data Volume**: The chart uses virtualization for vertical scrolling, but performance can still be impacted by an extremely large number of data points (e.g., 1000+).
+- **Responsiveness**: The chart adapts to its container, but ensure that bar heights and gaps are readable on very small screens.
+- **Animation**: Can be disabled via \`isAnimationActive={false}\` for better performance with large datasets.
+`,
+ },
+ },
+ },
+ tags: ["!dev", "autodocs"],
+ argTypes: {
+ data: {
+ description: `
+**Required.** An array of data objects representing your dataset. Each object should contain:
+- A category identifier (string/number) for the Y-axis.
+- One or more numeric values for the X-axis bars.
+`,
+ control: false,
+ table: {
+ type: { summary: "Array<Record<string, string | number>>" },
+ category: "πŸ“Š Data Configuration",
+ },
+ },
+ categoryKey: {
+ description:
+ "**Required.** The key in your data object that represents the category for the Y-axis (e.g., 'region', 'department').",
+ control: false,
+ table: {
+ type: { summary: "string" },
+ category: "πŸ“Š Data Configuration",
+ },
+ },
+ theme: {
+ description:
+ "Specifies the color palette for the chart's bars, tooltips, and legend. Ignored when customPalette is provided.",
+ control: "select",
+ options: ["ocean", "orchid", "emerald", "sunset", "spectrum", "vivid"],
+ table: {
+ defaultValue: { summary: "ocean" },
+ category: "🎨 Visual Styling",
+ },
+ },
+ customPalette: {
+ description:
+ "Custom array of colors to use instead of the theme palette. Overrides the theme prop when provided.",
+ control: "object",
+ table: {
+ type: { summary: "string[]" },
+ category: "🎨 Visual Styling",
+ },
+ },
+ variant: {
+ description:
+ "Defines how multiple data series are displayed: `grouped` (side-by-side) or `stacked` (on top of each other).",
+ control: "radio",
+ options: ["grouped", "stacked"],
+ table: {
+ defaultValue: { summary: "grouped" },
+ category: "🎨 Visual Styling",
+ },
+ },
+ radius: {
+ description: "Sets the corner radius for the bars, creating a rounded look.",
+ control: { type: "number", min: 0, max: 20 },
+ table: {
+ type: { summary: "number" },
+ defaultValue: { summary: "4" },
+ category: "🎨 Visual Styling",
+ },
+ },
+ icons: {
+ description:
+ "An object mapping data series keys to React components to be used as icons in the legend.",
+ control: false,
+ table: {
+ type: { summary: "Record<string, React.ReactNode>" },
+ category: "🎨 Visual Styling",
+ },
+ },
+ grid: {
+ description: "Toggles the visibility of the background grid lines.",
+ control: "boolean",
+ table: {
+ defaultValue: { summary: "true" },
+ category: "πŸ“± Display Options",
+ },
+ },
+ legend: {
+ description: "Toggles the visibility of the chart legend.",
+ control: "boolean",
+ table: {
+ defaultValue: { summary: "true" },
+ category: "πŸ“± Display Options",
+ },
+ },
+ showXAxis: {
+ description: "Toggles the visibility of the X-axis line and labels.",
+ control: "boolean",
+ table: {
+ defaultValue: { summary: "true" },
+ category: "πŸ“± Display Options",
+ },
+ },
+ xAxisLabel: {
+ description: "A label to display below the X-axis.",
+ control: "text",
+ table: {
+ type: { summary: "React.ReactNode" },
+ category: "πŸ“± Display Options",
+ },
+ },
+ yAxisLabel: {
+ description: "A label to display beside the Y-axis.",
+ control: "text",
+ table: {
+ type: { summary: "React.ReactNode" },
+ category: "πŸ“± Display Options",
+ },
+ },
+ isAnimationActive: {
+ description: "Enables or disables the initial loading animation for the bars.",
+ control: "boolean",
+ table: {
+ defaultValue: { summary: "false" },
+ category: "🎬 Animation & Interaction",
+ },
+ },
+ height: {
+ description: "Sets a fixed height for the chart container in pixels.",
+ control: "number",
+ table: {
+ type: { summary: "number" },
+ category: "Layout & Sizing",
+ },
+ },
+ width: {
+ description: "Sets a fixed width for the chart container in pixels.",
+ control: "number",
+ table: {
+ type: { summary: "number" },
+ category: "Layout & Sizing",
+ },
+ },
+ },
+} satisfies Meta<typeof HorizontalBarChart>;
+
+export default meta;
+
+type Story = StoryObj<typeof meta>;
+
+/**
+ * ## Comprehensive Data Explorer
+ *
+ * This story serves as a comprehensive test suite for the HorizontalBarChart component.
+ * Use the buttons to switch between various datasets designed to test edge cases in:
+ *
+ * - **Data Volume**: Scenarios with few, many, or a single data point.
+ * - **Data Formatting**: Handling of large numbers and different value ranges.
+ * - **Legend Overflow**: A dataset with many series to test legend expand/collapse functionality.
+ *
+ * It's an excellent tool for developers to see how the chart behaves under different conditions.
+ */
+export const DataExplorer: Story = {
+ name: "πŸŽ›οΈ Comprehensive Data Explorer",
+ args: {
+ data: horizontalBarChartData,
+ categoryKey: "category",
+ theme: "ocean",
+ variant: "grouped",
+ radius: 4,
+ grid: true,
+ isAnimationActive: false,
+ showXAxis: true,
+ legend: true,
+ height: 400,
+ width: 600,
+ },
+ render: (args: any) => {
+ const [selectedDataType, setSelectedDataType] =
+ useState<keyof typeof dataVariations>("default");
+
+ const currentData = dataVariations[selectedDataType];
+ const currentCategoryKey = categoryKeys[selectedDataType];
+
+ const buttonStyle = {
+ margin: "2px",
+ padding: "6px 12px",
+ fontSize: "12px",
+ border: "1px solid #ddd",
+ borderRadius: "4px",
+ cursor: "pointer",
+ background: "#fff",
+ };
+
+ const activeButtonStyle = {
+ ...buttonStyle,
+ background: "#007acc",
+ color: "white",
+ border: "1px solid #007acc",
+ };
+
+ return (
+ <div>
+ <div
+ style={{
+ marginBottom: "16px",
+ padding: "12px",
+ background: "#f8f9fa",
+ borderRadius: "8px",
+ border: "1px solid #e9ecef",
+ width: "700px",
+ }}
+ >
+ <strong>πŸ’‘ Quick Data Switch:</strong>
+ <div style={{ marginTop: "8px", display: "flex", flexWrap: "wrap", gap: "4px" }}>
+ <button
+ onClick={() => setSelectedDataType("default")}
+ style={selectedDataType === "default" ? activeButtonStyle : buttonStyle}
+ >
+ πŸ“Š Default (5 categories)
+ </button>
+ <button
+ onClick={() => setSelectedDataType("small")}
+ style={selectedDataType === "small" ? activeButtonStyle : buttonStyle}
+ >
+ πŸ“± Small (3 items)
+ </button>
+ <button
+ onClick={() => setSelectedDataType("large")}
+ style={selectedDataType === "large" ? activeButtonStyle : buttonStyle}
+ >
+ 🌐 Large (10 regions)
+ </button>
+ <button
+ onClick={() => setSelectedDataType("simple")}
+ style={selectedDataType === "simple" ? activeButtonStyle : buttonStyle}
+ >
+ 🏒 Simple (4 departments)
+ </button>
+ <button
+ onClick={() => setSelectedDataType("bigNumbers")}
+ style={selectedDataType === "bigNumbers" ? activeButtonStyle : buttonStyle}
+ >
+ πŸ’° Big Numbers
+ </button>
+ <button
+ onClick={() => setSelectedDataType("edge")}
+ style={selectedDataType === "edge" ? activeButtonStyle : buttonStyle}
+ >
+ 🎯 Single Item
+ </button>
+ <button
+ onClick={() => setSelectedDataType("singleGroup")}
+ style={selectedDataType === "singleGroup" ? activeButtonStyle : buttonStyle}
+ >
+ 🌍 Single Group
+ </button>
+ <button
+ onClick={() => setSelectedDataType("expandCollapseChannels")}
+ style={
+ selectedDataType === "expandCollapseChannels" ? activeButtonStyle : buttonStyle
+ }
+ >
+ πŸ”„ Marketing Channels
+ </button>
+ </div>
+ <div style={{ marginTop: "8px", fontSize: "12px", color: "#666" }}>
+ <strong>Current:</strong> {selectedDataType} | <strong>Items:</strong>{" "}
+ {currentData.length} | <strong>Category:</strong> {currentCategoryKey}
+ </div>
+ </div>
+ <Card style={{ width: "700px" }}>
+ <HorizontalBarChart {...args} data={currentData} categoryKey={currentCategoryKey} />
+ </Card>
+ </div>
+ );
+ },
+};
+
+// Basic stories using the new data structure
+export const Default: Story = {
+ args: {
+ data: dataVariations.default,
+ categoryKey: "category",
+ theme: "ocean",
+ variant: "grouped",
+ height: 400,
+ width: 600,
+ },
+ render: (args: any) => (
+ <Card style={{ width: "600px" }}>
+ <HorizontalBarChart {...args} />
+ </Card>
+ ),
+};
+
+export const Stacked: Story = {
+ args: {
+ data: dataVariations.default,
+ categoryKey: "category",
+ theme: "ocean",
+ variant: "stacked",
+ height: 400,
+ width: 600,
+ },
+ render: (args: any) => (
+ <Card style={{ width: "600px" }}>
+ <HorizontalBarChart {...args} />
+ </Card>
+ ),
+};
+
+export const WithAnimations: Story = {
+ args: {
+ data: dataVariations.default,
+ categoryKey: "category",
+ theme: "ocean",
+ variant: "grouped",
+ isAnimationActive: true,
+ height: 400,
+ width: 600,
+ },
+ render: (args: any) => (
+ <Card style={{ width: "600px" }}>
+ <HorizontalBarChart {...args} />
+ </Card>
+ ),
+};
+
+export const CustomPalette: Story = {
+ args: {
+ data: dataVariations.default,
+ categoryKey: "category",
+ customPalette: ["#FF6B6B", "#4ECDC4", "#45B7D1", "#96CEB4", "#FECA57"],
+ variant: "grouped",
+ height: 400,
+ width: 600,
+ },
+ render: (args: any) => (
+ <Card style={{ width: "600px" }}>
+ <HorizontalBarChart {...args} />
+ </Card>
+ ),
+};
+
+export const CustomPaletteVibrant: Story = {
+ name: "🎨 Custom Palette - Vibrant",
+ args: {
+ data: dataVariations.default,
+ categoryKey: "category",
+ customPalette: ["#FF1744", "#00E676", "#2979FF", "#FF9100", "#9C27B0"],
+ variant: "grouped",
+ height: 400,
+ width: 600,
+ },
+ render: (args: any) => (
+ <Card style={{ width: "600px" }}>
+ <HorizontalBarChart {...args} />
+ </Card>
+ ),
+};
+
+export const BigNumbers: Story = {
+ args: {
+ data: dataVariations.bigNumbers,
+ categoryKey: "company",
+ theme: "vivid",
+ variant: "grouped",
+ height: 400,
+ width: 600,
+ },
+ render: (args: any) => (
+ <Card style={{ width: "600px" }}>
+ <HorizontalBarChart {...args} />
+ </Card>
+ ),
+};
+
+export const LargeDataset: Story = {
+ args: {
+ data: dataVariations.large,
+ categoryKey: "category",
+ theme: "emerald",
+ variant: "grouped",
+ height: 400,
+ width: 600,
+ },
+ render: (args: any) => (
+ <Card style={{ width: "600px" }}>
+ <HorizontalBarChart {...args} />
+ </Card>
+ ),
+};
+
+export const WithIcons: Story = {
+ args: {
+ data: dataVariations.default,
+ categoryKey: "category",
+ theme: "ocean",
+ variant: "grouped",
+ height: 400,
+ width: 600,
+ icons: {
+ desktop: Monitor,
+ mobile: TabletSmartphone,
+ },
+ },
+ render: (args: any) => (
+ <Card style={{ width: "600px" }}>
+ <HorizontalBarChart {...args} />
+ </Card>
+ ),
+};
diff --git a/js/packages/react-ui/src/components/Charts/HorizontalBarChart/types/index.ts b/js/packages/react-ui/src/components/Charts/HorizontalBarChart/types/index.ts
new file mode 100644
index 000000000..c1d14df8c
--- /dev/null
+++ b/js/packages/react-ui/src/components/Charts/HorizontalBarChart/types/index.ts
@@ -0,0 +1,3 @@
+export type HorizontalBarChartVariant = "grouped" | "stacked";
+
+export type HorizontalBarChartData = Array<Record<string, string | number>>;
diff --git a/js/packages/react-ui/src/components/Charts/HorizontalBarChart/utils/HorizontalBarChartUtils.ts b/js/packages/react-ui/src/components/Charts/HorizontalBarChart/utils/HorizontalBarChartUtils.ts
new file mode 100644
index 000000000..d22c25c82
--- /dev/null
+++ b/js/packages/react-ui/src/components/Charts/HorizontalBarChart/utils/HorizontalBarChartUtils.ts
@@ -0,0 +1,151 @@
+import { getDataKeys } from "../../utils/dataUtils";
+import { getCanvasContext } from "../../utils/styleUtils";
+import { HorizontalBarChartVariant } from "../types";
+
+export const BAR_HEIGHT = 16;
+export const BAR_GAP = 10;
+
+/**
+ * Get the maximum text width for category labels
+ * @param data - The data to be displayed in the chart
+ * @param categoryKey - The key of the category to be displayed in the chart
+ * @returns The maximum width needed for category labels
+ */
+export const getMaxCategoryLabelWidth = (
+ data: Array<Record<string, string | number>>,
+ categoryKey: string,
+): number => {
+ if (data.length === 0) {
+ return 100; // Default fallback
+ }
+
+ const context = getCanvasContext();
+ if (!context) {
+ return Math.max(...data.map((item) => String(item[categoryKey] || "").length * 8), 100);
+ }
+
+ return Math.max(
+ ...data.map((item) => {
+ const text = String(item[categoryKey] || "");
+ return context.measureText(text).width;
+ }),
+ 100,
+ );
+};
+
+/**
+ * This function returns the height of the data in the chart, used for padding calculation, scroll amount calculation, and
+ * for the height of the chart container.
+ * @param data - The data to be displayed in the chart.
+ * @param categoryKey - The key of the category to be displayed in the chart.
+ * @param variant - The variant of the chart.
+ * @param labelHeight - The height of the category label.
+ */
+const getHeightOfData = (
+ data: Array<Record<string, string | number>>,
+ categoryKey: string,
+ variant: HorizontalBarChartVariant,
+ labelHeight: number,
+) => {
+ if (data.length === 0) {
+ return 0;
+ }
+
+ const height = data.length * getHeightOfGroup(data, categoryKey, variant, labelHeight);
+
+ if (data.length === 1) {
+ const minSingleDataHeight = 80; // Minimum height for single data points
+ return Math.max(height, minSingleDataHeight);
+ }
+ return height;
+};
+
+/**
+ * This function returns the padding for the chart, used for the padding of the chart container.
+ * @param data - The data to be displayed in the chart.
+ * @param categoryKey - The key of the category to be displayed in the chart.
+ * @param containerHeight - The height of the container of the chart.
+ * @param variant - The variant of the chart.
+ * @param labelHeight - The height of the category label.
+ */
+const getPadding = (
+ data: Array<Record<string, string | number>>,
+ categoryKey: string,
+ containerHeight: number,
+ variant: HorizontalBarChartVariant,
+ labelHeight: number,
+) => {
+ const chartHeight = getHeightOfData(data, categoryKey, variant, labelHeight);
+ const paddingValue = containerHeight - chartHeight;
+
+ if (paddingValue < 0) {
+ // If chart content is taller than container, no padding
+ return {
+ top: 10,
+ bottom: 10,
+ };
+ } else {
+ return {
+ top: paddingValue / 2,
+ bottom: paddingValue / 2,
+ };
+ }
+};
+
+/**
+ * This function returns the height of each group/category.
+ * @param data - The data to be displayed in the chart.
+ * @param categoryKey - The key of the category to be displayed in the chart.
+ * @param variant - The variant of the chart.
+ * @param labelHeight - The height of the category label.
+ */
+const getHeightOfGroup = (
+ data: Array<Record<string, string | number>>,
+ categoryKey: string,
+ variant: HorizontalBarChartVariant,
+ labelHeight: number,
+) => {
+ if (data.length === 0) return 200; // Fallback
+
+ // Get the number of data keys (excluding categoryKey)
+ const dataKeys = getDataKeys(data, categoryKey);
+ const PADDING = 16;
+
+ if (variant === "stacked") {
+ // For stacked: each category is one stack
+ return BAR_HEIGHT + labelHeight + PADDING;
+ } else {
+ // For grouped: each category contains multiple bars
+ const seriesPerCategory = dataKeys.length;
+ return seriesPerCategory * (BAR_HEIGHT + BAR_GAP) - BAR_GAP + labelHeight + PADDING;
+ }
+};
+
+/**
+ * This function returns the snap positions for the chart, used for the snap positions of the chart.
+ * @param data - The data to be displayed in the chart.
+ * @param categoryKey - The key of the category to be displayed in the chart.
+ * @param variant - The variant of the chart.
+ * @param labelHeight - The height of the category label.
+ * @returns The snap positions for the chart.
+ */
+const getSnapPositions = (
+ data: Array<Record<string, string | number>>,
+ categoryKey: string,
+ variant: HorizontalBarChartVariant,
+ labelHeight: number,
+): number[] => {
+ if (data.length === 0) return [0];
+
+ const positions = [0]; // Start position
+ const groupHeightValue = getHeightOfGroup(data, categoryKey, variant, labelHeight);
+
+ // Calculate all valid snap positions based on groups
+ for (let i = 1; i < data.length; i++) {
+ positions.push(i * groupHeightValue);
+ }
+
+ return positions;
+};
+
+export { getHeightOfData, getHeightOfGroup, getPadding, getSnapPositions };
diff --git a/js/packages/react-ui/src/components/Charts/MiniBarChart/MiniBarChart.tsx b/js/packages/react-ui/src/components/Charts/MiniBarChart/MiniBarChart.tsx
index 63e54f625..8f9de2801 100644
--- a/js/packages/react-ui/src/components/Charts/MiniBarChart/MiniBarChart.tsx
+++ b/js/packages/react-ui/src/components/Charts/MiniBarChart/MiniBarChart.tsx
@@ -2,8 +2,8 @@ import clsx from "clsx";
import { useEffect, useMemo, useRef, useState } from "react";
import { Bar, BarChart, XAxis } from "recharts";
import { useTheme } from "../../ThemeProvider";
-import { LineInBarShape } from "../BarChart/components/LineInBarShape";
import { ChartConfig, ChartContainer } from "../Charts";
+import { LineInBarShape } from "../shared";
import { getDistributedColors, getPalette, PaletteName } from "../utils/PalletUtils";
import { type MiniBarChartData } from "./types";
import {
diff --git a/js/packages/react-ui/src/components/Charts/charts.scss b/js/packages/react-ui/src/components/Charts/charts.scss
index 9b991dd0e..25bb23ac6 100644
--- a/js/packages/react-ui/src/components/Charts/charts.scss
+++ b/js/packages/react-ui/src/components/Charts/charts.scss
@@ -2,6 +2,7 @@
// bar chart css
@forward "./BarChart/barChart.scss";
+@forward "./HorizontalBarChart/horizontalBarChart.scss";
@forward "./MiniBarChart/miniBarChart.scss";
// area chart css
@@ -28,6 +29,7 @@
@forward "./shared/StackedLegend/stackedLegend.scss";
@forward "./shared/YAxisTick/yAxisTick.scss";
@forward "./shared/ScrollButtonsHorizontal/scrollButtonsHorizontal.scss";
+@forward "./shared/ScrollButtonsVertical/scrollButtonsVertical.scss";
@forward "./shared/LabelTooltip/labelTooltip.scss";
// portal tooltip css
@@ -76,46 +78,14 @@
stroke: cssUtils.$stroke-default;
}
-.crayon-chart-polar-grid {
+.crayon-chart-vertical-cartesian-grid {
stroke: cssUtils.$stroke-default;
}
-.crayon-chart-label-list {
- fill: cssUtils.$secondary-text;
-}
-
-//Pie Chart styles
-// @subham either remove this or move this to it dedicated file.
-
-.crayon-pie-chart {
- &-container {
- margin-left: auto;
- margin-right: auto;
- aspect-ratio: 1/1;
-
- &-fullscreen {
- min-height: 400px;
- width: 100%;
- }
-
- &-mobile {
- min-height: 300px;
- width: 100%;
- }
-
- &-tray {
- min-height: 350px;
- width: 100%;
- }
-
- &-copilot {
- min-height: 350px;
- width: 100%;
- }
- }
+.crayon-chart-polar-grid {
+ stroke: cssUtils.$stroke-default;
}
-.crayon-pie-chart-label {
+.crayon-chart-label-list {
fill: cssUtils.$secondary-text;
- padding: 0;
}
diff --git a/js/packages/react-ui/src/components/Charts/hooks/useMaxLabelHeight.tsx b/js/packages/react-ui/src/components/Charts/hooks/useMaxLabelHeight.tsx
index cc78f2d56..bec9aa8df 100644
--- a/js/packages/react-ui/src/components/Charts/hooks/useMaxLabelHeight.tsx
+++ b/js/packages/react-ui/src/components/Charts/hooks/useMaxLabelHeight.tsx
@@ -64,3 +64,73 @@ export const useMaxLabelHeight = (
return DEFAULT_HEIGHT;
}
};
+
+/**
+ * Hook to calculate the maximum label height for horizontal bar charts.
+ * This considers the vertical layout and label width constraints specific to horizontal bars.
+ * @param data - The chart data
+ * @param categoryKey - The category key
+ * @param labelWidth - The available width for labels (full chart width for horizontal bars)
+ * @returns The calculated label height
+ */
+export const useHorizontalBarLabelHeight = (
+ data: Record<string, string | number>[],
+ categoryKey: string,
+ labelWidth: number,
+) => {
+ const { theme: userTheme } = useTheme();
+
+ const labelHeight = useMemo(() => {
+ if (typeof window === "undefined" || !data || data.length === 0) {
+ return 20; // Default height for horizontal bar labels
+ }
+
+ const largestLabel = data.reduce((max, item) => {
+ const label = String(item[categoryKey]);
+ if (max.length < label.length) {
+ return label;
+ }
+ return max;
+ }, "");
+
+ const [div1, div2] = [document.createElement("div"), document.createElement("div")];
+
+ // Apply the same typography as the horizontal bar chart labels
+ div1.style.font = userTheme.fontLabelExtraSmall ?? "";
+ div1.style.letterSpacing = userTheme.fontLabelExtraSmallLetterSpacing ?? "";
+ div1.style.opacity = "0";
+ div1.style.pointerEvents = "none";
+ div1.style.position = "absolute";
+ div1.style.visibility = "hidden";
+
+ div2.innerText = largestLabel;
+ div1.append(div2);
+
+ // For horizontal bar charts, labels span the full width
+ // Set width constraint for horizontal bar labels
+ div1.style.width = `${labelWidth}px`;
+ div1.style.maxWidth = `${labelWidth}px`;
+ div1.style.overflow = "hidden";
+ div1.style.whiteSpace = "nowrap";
+ div1.style.textOverflow = "ellipsis";
+ div1.style.display = "flex";
+ div1.style.alignItems = "center";
+
+ document.body.append(div1);
+
+ const calculatedHeight = div2.getBoundingClientRect().height;
+ div1.remove();
+
+ // Add some padding for better visual spacing
+ // For horizontal bars, we need more space since labels are positioned above bars
+ return Math.max(calculatedHeight + 8, 24);
+ }, [
+ data,
+ categoryKey,
+ labelWidth,
+ userTheme.fontLabelExtraSmall,
+ userTheme.fontLabelExtraSmallLetterSpacing,
+ ]);
+
+ return labelHeight;
+};
diff --git a/js/packages/react-ui/src/components/Charts/index.ts b/js/packages/react-ui/src/components/Charts/index.ts
index 92b81eaf9..68f02c49b 100644
--- a/js/packages/react-ui/src/components/Charts/index.ts
+++ b/js/packages/react-ui/src/components/Charts/index.ts
@@ -1,5 +1,6 @@
export * from "./AreaChart";
export * from "./BarChart";
+export * from "./HorizontalBarChart";
export * from "./LineChart";
export * from "./PieChart";
export * from "./RadarChart";
diff --git a/js/packages/react-ui/src/components/Charts/shared/CartesianGrid/cartesianGrid.tsx b/js/packages/react-ui/src/components/Charts/shared/CartesianGrid/cartesianGrid.tsx
index e8f60d989..492485311 100644
--- a/js/packages/react-ui/src/components/Charts/shared/CartesianGrid/cartesianGrid.tsx
+++ b/js/packages/react-ui/src/components/Charts/shared/CartesianGrid/cartesianGrid.tsx
@@ -13,3 +13,17 @@ export const cartesianGrid = () => (
className="crayon-chart-cartesian-grid"
/>
);
+
+export const verticalCartesianGrid = () => (
+ <CartesianGrid
+ horizontal={false}
+ fillOpacity={1}
+ strokeOpacity={1}
+ strokeWidth={1}
+ strokeDasharray="0"
+ strokeLinecap="round"
+ strokeLinejoin="round"
+ stroke="currentColor"
+ className="crayon-chart-vertical-cartesian-grid"
+ />
+);
diff --git a/js/packages/react-ui/src/components/Charts/shared/LineInBarShape/LineInBarShape.tsx b/js/packages/react-ui/src/components/Charts/shared/LineInBarShape/LineInBarShape.tsx
new file mode 100644
index 000000000..94ca615c8
--- /dev/null
+++ b/js/packages/react-ui/src/components/Charts/shared/LineInBarShape/LineInBarShape.tsx
@@ -0,0 +1,187 @@
+import React, { FunctionComponent, useMemo } from "react";
+
+interface LineInBarShapeProps {
+ x?: number;
+ y?: number;
+ width?: number;
+ height?: number;
+ fill?: string;
+ stroke?: string;
+ strokeWidth?: number | string;
+ radius?: number | number[];
+ internalLineColor?: string;
+ internalLineWidth?: number;
+ isHovered?: boolean;
+ hoveredCategory?: string | number | null;
+ categoryKey?: string;
+ payload?: any;
+ variant?: "grouped" | "stacked";
+ stackGap?: number;
+ orientation?: "vertical" | "horizontal";
+ [key: string]: any; // Allow other props from Recharts
+}
+
+const DEFAULT_STACK_GAP = 1;
+const MIN_LINE_DIMENSION = 8; // For internal line visibility
+const LINE_PADDING = 6;
+const MIN_GROUP_BAR_HEIGHT = 2; // For vertical bars
+const MIN_STACKED_BAR_HEIGHT = 4; // For vertical bars
+const MIN_BAR_WIDTH = 2; // For horizontal bars
+
+const LineInBarShape: FunctionComponent<LineInBarShapeProps> = React.memo((props) => {
+ const {
+ x = 0,
+ y = 0,
+ width = 0,
+ height = 0,
+ fill,
+ radius: r,
+ stroke,
+ strokeWidth,
+ internalLineColor: iLineColor,
+ internalLineWidth: iLineWidth,
+ isHovered,
+ hoveredCategory,
+ categoryKey,
+ payload,
+ variant = "grouped",
+ stackGap = DEFAULT_STACK_GAP,
+ orientation = "vertical",
+ } = props;
+
+ const isVertical = orientation === "vertical";
+
+ const { rTL, rTR, rBR } = useMemo(() => {
+ const minHeight = isVertical ? MIN_GROUP_BAR_HEIGHT : MIN_BAR_WIDTH;
+ if (
+ (variant === "grouped" && height < minHeight) ||
+ (variant === "stacked" && height < MIN_STACKED_BAR_HEIGHT)
+ ) {
+ return { rTL: 0, rTR: 0, rBR: 0 };
+ }
+
+ if (Array.isArray(r)) {
+ if (isVertical) return { rTL: r[0] || 0, rTR: r[1] || 0, rBR: 0 };
+ return { rTL: 0, rTR: r[1] || 0, rBR: r[2] || 0 };
+ } else if (typeof r === "number") {
+ if (isVertical) return { rTL: r, rTR: r, rBR: 0 };
+ return { rTL: 0, rTR: r, rBR: r };
+ }
+ return { rTL: 0, rTR: 0, rBR: 0 };
+ }, [r, variant, height, isVertical]);
+
+ const opacity = useMemo(() => {
+ if (!isHovered || hoveredCategory === null || !payload || !categoryKey) return 1;
+ return payload[categoryKey] === hoveredCategory ? 1 : 0.4;
+ }, [isHovered, hoveredCategory, payload, categoryKey]);
+
+ const { adjustedX, adjustedY, adjustedWidth, adjustedHeight } = useMemo(() => {
+ let finalX = x;
+ let finalY = y;
+ let finalWidth = width;
+ let finalHeight = height;
+
+ if (isVertical) {
+ if (variant === "stacked" && stackGap > 0) finalHeight = height - stackGap;
+ if (height > 0) {
+ const minHeight =
+ variant === "grouped" ? MIN_GROUP_BAR_HEIGHT : MIN_STACKED_BAR_HEIGHT - stackGap;
+ finalHeight = Math.max(finalHeight, minHeight);
+ }
+ finalY = y + height - finalHeight;
+ } else {
+ // Horizontal
+ if (variant === "stacked" && stackGap > 0) finalWidth = width - stackGap;
+ if (width > 0) {
+ const minWidth = MIN_BAR_WIDTH;
+ finalWidth = Math.max(finalWidth, minWidth);
+ }
+ // No adjustment for X as it grows left-to-right
+ }
+
+ return {
+ adjustedX: finalX,
+ adjustedY: finalY,
+ adjustedWidth: finalWidth,
+ adjustedHeight: finalHeight,
+ };
+ }, [variant, stackGap, x, y, width, height, isVertical]);
+
+ const path = useMemo(() => {
+ if (isVertical) {
+ return `
+ M ${x},${adjustedY + rTL}
+ ${rTL > 0 ? `A ${rTL},${rTL} 0 0 1 ${x + rTL},${adjustedY}` : `L ${x},${adjustedY}`}
+ L ${x + adjustedWidth - rTR},${adjustedY}
+ ${rTR > 0 ? `A ${rTR},${rTR} 0 0 1 ${x + adjustedWidth},${adjustedY + rTR}` : `L ${x + adjustedWidth},${adjustedY}`}
+ L ${x + adjustedWidth},${adjustedY + adjustedHeight}
+ L ${x},${adjustedY + adjustedHeight}
+ Z`;
+ }
+ // Horizontal
+ return `
+ M ${adjustedX},${y}
+ L ${adjustedX + adjustedWidth - rTR},${y}
+ ${rTR > 0 ? `A ${rTR},${rTR} 0 0 1 ${adjustedX + adjustedWidth},${y + rTR}` : `L ${adjustedX + adjustedWidth},${y}`}
+ L ${adjustedX + adjustedWidth},${y + height - rBR}
+ ${rBR > 0 ? `A ${rBR},${rBR} 0 0 1 ${adjustedX + adjustedWidth - rBR},${y + height}` : `L ${adjustedX + adjustedWidth},${y + height}`}
+ L ${adjustedX},${y + height}
+ Z`;
+ }, [
+ x,
+ y,
+ adjustedX,
+ adjustedY,
+ adjustedWidth,
+ adjustedHeight,
+ height,
+ rTL,
+ rTR,
+ rBR,
+ isVertical,
+ ]);
+
+ const lineCoords = useMemo(() => {
+ if (isVertical) {
+ if (width <= 0 || adjustedHeight <= MIN_LINE_DIMENSION) return null;
+ const centerX = x + width / 2;
+ return {
+ x1: centerX,
+ y1: adjustedY + LINE_PADDING,
+ x2: centerX,
+ y2: adjustedY + adjustedHeight - LINE_PADDING,
+ };
+ }
+ // Horizontal
+ if (adjustedWidth <= MIN_LINE_DIMENSION || height <= 0) return null;
+ const centerY = y + height / 2;
+ return {
+ x1: adjustedX + LINE_PADDING,
+ y1: centerY,
+ x2: adjustedX + adjustedWidth - LINE_PADDING,
+ y2: centerY,
+ };
+ }, [x, y, adjustedX, adjustedY, width, height, adjustedWidth, adjustedHeight, isVertical]);
+
+ return (
+ <g>
+ <path d={path} fill={fill} stroke={stroke} strokeWidth={strokeWidth} opacity={opacity} />
+ {lineCoords && (
+ <line
+ x1={lineCoords.x1}
+ y1={lineCoords.y1}
+ x2={lineCoords.x2}
+ y2={lineCoords.y2}
+ stroke={iLineColor}
+ strokeWidth={iLineWidth}
+ strokeLinecap="round"
+ opacity={opacity}
+ />
+ )}
+ </g>
+ );
+});
+
+LineInBarShape.displayName = "LineInBarShape";
+
+export { LineInBarShape };
diff --git a/js/packages/react-ui/src/components/Charts/shared/LineInBarShape/index.ts b/js/packages/react-ui/src/components/Charts/shared/LineInBarShape/index.ts
new file mode 100644
index 000000000..c06d067c4
--- /dev/null
+++ b/js/packages/react-ui/src/components/Charts/shared/LineInBarShape/index.ts
@@ -0,0 +1 @@
+export * from "./LineInBarShape";
diff --git a/js/packages/react-ui/src/components/Charts/shared/ScrollButtonsVertical/ScrollButtonsVertical.tsx b/js/packages/react-ui/src/components/Charts/shared/ScrollButtonsVertical/ScrollButtonsVertical.tsx
new file mode 100644
index 000000000..fe6e3f65f
--- /dev/null
+++ b/js/packages/react-ui/src/components/Charts/shared/ScrollButtonsVertical/ScrollButtonsVertical.tsx
@@ -0,0 +1,65 @@
+import clsx from "clsx";
+import { ChevronDown, ChevronUp } from "lucide-react";
+import React from "react";
+import { IconButton } from "../../../IconButton";
+
+interface ScrollButtonsVerticalProps {
+ dataHeight: number;
+ effectiveHeight: number;
+ canScrollUp: boolean;
+ canScrollDown: boolean;
+ isSideBarTooltipOpen: boolean;
+ onScrollUp: () => void;
+ onScrollDown: () => void;
+}
+
+export const ScrollButtonsVertical = React.memo(
+ ({
+ dataHeight,
+ effectiveHeight,
+ canScrollUp,
+ canScrollDown,
+ isSideBarTooltipOpen,
+ onScrollUp,
+ onScrollDown,
+ }: ScrollButtonsVerticalProps) => {
+ if (dataHeight <= effectiveHeight) {
+ return null;
+ }
+
+ return (
+ <div className="crayon-chart-vertical-scroll-buttons-container">
+ <IconButton
+ className={clsx(
+ "crayon-chart-vertical-scroll-button crayon-chart-vertical-scroll-button--up",
+ {
+ "crayon-chart-vertical-scroll-button--disabled": !canScrollUp,
+ },
+ )}
+ icon={<ChevronUp />}
+ variant="secondary"
+ onClick={onScrollUp}
+ size="extra-small"
+ disabled={!canScrollUp}
+ />
+
+ <IconButton
+ className={clsx(
+ "crayon-chart-vertical-scroll-button crayon-chart-vertical-scroll-button--down",
+ {
+ "crayon-chart-vertical-scroll-button--disabled": !canScrollDown,
+ "crayon-chart-vertical-scroll-button--SideBarTooltip": isSideBarTooltipOpen,
+ },
+ )}
+ icon={<ChevronDown />}
+ variant="secondary"
+ size="extra-small"
+ onClick={onScrollDown}
+ disabled={!canScrollDown}
+ />
+ </div>
+ );
+ },
+);
+
+ScrollButtonsVertical.displayName = "ScrollButtonsVertical";
diff --git a/js/packages/react-ui/src/components/Charts/shared/ScrollButtonsVertical/index.ts b/js/packages/react-ui/src/components/Charts/shared/ScrollButtonsVertical/index.ts
new file mode 100644
index 000000000..a379c56b7
--- /dev/null
+++ b/js/packages/react-ui/src/components/Charts/shared/ScrollButtonsVertical/index.ts
@@ -0,0 +1 @@
+export * from "./ScrollButtonsVertical";
diff --git a/js/packages/react-ui/src/components/Charts/shared/ScrollButtonsVertical/scrollButtonsVertical.scss b/js/packages/react-ui/src/components/Charts/shared/ScrollButtonsVertical/scrollButtonsVertical.scss
new file mode 100644
index 000000000..b91eac12b
--- /dev/null
+++ b/js/packages/react-ui/src/components/Charts/shared/ScrollButtonsVertical/scrollButtonsVertical.scss
@@ -0,0 +1,32 @@
+@use "../../../../cssUtils.scss" as cssUtils;
+
+.crayon-chart-vertical-scroll {
+ &-buttons-container {
+ display: flex;
+ flex-direction: column;
+ justify-content: space-between;
+ width: 25px;
+ height: calc(100% - 44px);
+ flex-shrink: 0;
+ padding-left: cssUtils.$spacing-2xs;
+ }
+
+ &-button {
+ background-color: cssUtils.$bg-container;
+ pointer-events: auto;
+
+ &:hover {
+ background-color: cssUtils.$bg-container;
+ }
+
+ &--disabled {
+ visibility: hidden;
+ cursor: not-allowed;
+ transition: visibility 0.1s linear;
+ }
+
+ &--SideBarTooltip {
+ margin-right: 190px;
+ }
+ }
+}
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 7c6a2d0dc..b6d36939c 100644
--- a/js/packages/react-ui/src/components/Charts/shared/index.ts
+++ b/js/packages/react-ui/src/components/Charts/shared/index.ts
@@ -1,8 +1,10 @@
export * from "./ActiveDot/ActiveDot";
export * from "./CartesianGrid/cartesianGrid";
export * from "./DefaultLegend/DefaultLegend";
+export * from "./LineInBarShape";
export * from "./PortalTooltip";
export * from "./ScrollButtonsHorizontal";
+export * from "./ScrollButtonsVertical";
export * from "./SideBarTooltip";
export * from "./StackedLegend/StackedLegend";
export * from "./XAxisTick/XAxisTick";
diff --git a/js/packages/react-ui/src/components/Charts/types/common.ts b/js/packages/react-ui/src/components/Charts/types/common.ts
new file mode 100644
index 000000000..0019c0f7a
--- /dev/null
+++ b/js/packages/react-ui/src/components/Charts/types/common.ts
@@ -0,0 +1 @@
+export type BarChartVariant = "grouped" | "stacked";
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 9b8f3e3b3..033cda0b0 100644
--- a/js/packages/react-ui/src/components/Charts/types/index.ts
+++ b/js/packages/react-ui/src/components/Charts/types/index.ts
@@ -1,2 +1,3 @@
+export * from "./common";
export * from "./Legend";
export * from "./XAxisTicks";
diff --git a/js/packages/react-ui/src/components/Charts/utils/BarCharts/BarChartsUtils.ts b/js/packages/react-ui/src/components/Charts/utils/BarCharts/BarChartsUtils.ts
new file mode 100644
index 000000000..f4974d3d5
--- /dev/null
+++ b/js/packages/react-ui/src/components/Charts/utils/BarCharts/BarChartsUtils.ts
@@ -0,0 +1,72 @@
+import { BarChartVariant } from "../../types";
+
+export const getRadiusArray = (
+ variant: BarChartVariant,
+ radius: number,
+ orientation: "vertical" | "horizontal",
+ isFirst?: boolean,
+ isLast?: boolean,
+): [number, number, number, number] => {
+ if (variant === "grouped") {
+ if (orientation === "vertical") {
+ return [radius, radius, 0, 0]; // top-left, top-right, bottom-right, bottom-left
+ } else {
+ // horizontal
+ return [0, radius, radius, 0];
+ }
+ } else if (variant === "stacked") {
+ if (isFirst && isLast) {
+ // Single item in stack
+ return [radius, radius, radius, radius];
+ }
+ if (orientation === "vertical") {
+ if (isFirst) {
+ // Bottom of the stack for vertical bar
+ return [0, 0, 0, 0];
+ }
+ if (isLast) {
+ // Top of the stack for vertical bar
+ return [radius, radius, 0, 0];
+ }
+ } else {
+ // horizontal
+ if (isFirst) {
+ // Left of the stack for horizontal bar
+ return [0, 0, 0, 0];
+ }
+ if (isLast) {
+ // Right of the stack for horizontal bar
+ return [0, radius, radius, 0];
+ }
+ }
+ // Middle of the stack
+ return [0, 0, 0, 0];
+ }
+ // Default or other variants
+ return [radius, radius, radius, radius];
+};
+
+export const findNearestSnapPosition = (
+ snapPositions: number[],
+ currentScroll: number,
+ direction: "up" | "down" | "left" | "right",
+): number => {
+ // Find current position index
+ let currentIndex = 0;
+ for (let i = 0; i < snapPositions.length; i++) {
+ const snapPosition = snapPositions[i]!;
+ if (currentScroll >= snapPosition) {
+ currentIndex = i;
+ } else {
+ break;
+ }
+ }
+
+ if (direction === "up" || direction === "left") {
+ // Go to previous snap position
+ return Math.max(0, currentIndex - 1);
+ } else {
+ // Go to next snap position
+ return Math.min(snapPositions.length - 1, currentIndex + 1);
+ }
+};
diff --git a/js/packages/react-ui/src/components/ThemeProvider/types.ts b/js/packages/react-ui/src/components/ThemeProvider/types.ts
index 23ddd13ab..70443692e 100644
--- a/js/packages/react-ui/src/components/ThemeProvider/types.ts
+++ b/js/packages/react-ui/src/components/ThemeProvider/types.ts
@@ -122,6 +122,7 @@ export interface ChartColorPalette {
pieChartPalette?: string[];
radarChartPalette?: string[];
radialChartPalette?: string[];
+ horizontalBarChartPalette?: string[];
}
// Layout-related theme properties
export interface LayoutTheme {