Skip to content

The Open Standard for Generative UI

CondensedChart Fix (#253)

Ankit Das65216f3a49fa
diff --git a/js/packages/react-ui/package.json b/js/packages/react-ui/package.json
index 2d45b7be7..dfd4ab3d2 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.9.15",
+ "version": "0.9.16",
"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/AreaChartCondensed/AreaChartCondensed.tsx b/js/packages/react-ui/src/components/Charts/AreaChartCondensed/AreaChartCondensed.tsx
index 54b3b253f..d412acf53 100644
--- a/js/packages/react-ui/src/components/Charts/AreaChartCondensed/AreaChartCondensed.tsx
+++ b/js/packages/react-ui/src/components/Charts/AreaChartCondensed/AreaChartCondensed.tsx
@@ -100,8 +100,10 @@ const AreaChartCondensedComponent = <T extends AreaChartData>({
if (data.length === 0) {
return 0;
}
- return chartContainerWidth / data.length;
- }, [chartContainerWidth, data]);
+ // Use passed width if available, otherwise use observed chartContainerWidth
+ const chartWidth = width ?? chartContainerWidth;
+ return chartWidth / data.length;
+ }, [width, chartContainerWidth, data]);
const { angle: calculatedAngle, height: xAxisHeight } = useAutoAngleCalculation(
maxLabelWidth,
diff --git a/js/packages/react-ui/src/components/Charts/BarChartCondensed/BarChartCondensed.tsx b/js/packages/react-ui/src/components/Charts/BarChartCondensed/BarChartCondensed.tsx
index 8ece25982..f2d61b5d8 100644
--- a/js/packages/react-ui/src/components/Charts/BarChartCondensed/BarChartCondensed.tsx
+++ b/js/packages/react-ui/src/components/Charts/BarChartCondensed/BarChartCondensed.tsx
@@ -59,9 +59,14 @@ export interface BarChartCondensedProps<T extends BarChartData> {
className?: string;
height?: number;
width?: number;
+ /** Maximum bar width in pixels. Prevents bars from becoming too wide. Default: 12 */
+ maxBarWidth?: number;
}
-const BAR_WIDTH = 12;
+// Default maximum bar width - prevents bars from becoming too wide with sparse data
+const DEFAULT_MAX_BAR_WIDTH = 12;
+
+// Layout constants
const BAR_GAP = 10;
const BAR_CATEGORY_GAP = "20%";
const BAR_INTERNAL_LINE_WIDTH = 1;
@@ -87,6 +92,7 @@ const BarChartCondensedComponent = <T extends BarChartData>({
className,
height = CHART_HEIGHT,
width,
+ maxBarWidth = DEFAULT_MAX_BAR_WIDTH,
}: BarChartCondensedProps<T>) => {
const printContext = usePrintContext();
isAnimationActive = printContext ? false : isAnimationActive;
@@ -106,8 +112,10 @@ const BarChartCondensedComponent = <T extends BarChartData>({
if (data.length === 0) {
return 0;
}
- return chartContainerWidth / data.length;
- }, [chartContainerWidth, data]);
+ // Use passed width if available, otherwise use observed chartContainerWidth
+ const chartWidth = width ?? chartContainerWidth;
+ return chartWidth / data.length;
+ }, [chartContainerWidth, data, width]);
const { angle: calculatedAngle, height: xAxisHeight } = useAutoAngleCalculation(
maxLabelWidth,
@@ -201,6 +209,39 @@ const BarChartCondensedComponent = <T extends BarChartData>({
return width ?? containerWidth;
}, [width, containerWidth]);
+ // Calculate explicit chart width when width prop is provided
+ // This allows Recharts to calculate bar dimensions on first render
+ const explicitChartWidth = useMemo(() => {
+ if (!width) return undefined;
+ // Subtract Y-axis width and margins to get the actual chart area width
+ const yAxisSpace = showYAxis ? yAxisWidth : 0;
+ return width - yAxisSpace - chartMargin.left - chartMargin.right;
+ }, [width, showYAxis, yAxisWidth, chartMargin.left, chartMargin.right]);
+
+ // Calculate optimal bar width based on available space
+ // Only applies maximum constraint - Recharts handles thin bars automatically
+ const calculatedBarWidth = useMemo(() => {
+ // Use explicitChartWidth if available, otherwise fall back to chartContainerWidth
+ const availableWidth = explicitChartWidth ?? chartContainerWidth;
+
+ // If no width available, return undefined and let Recharts auto-size
+ if (!availableWidth || availableWidth === 0 || data.length === 0) {
+ return undefined;
+ }
+
+ // Calculate space per category (Recharts handles gaps automatically via barGap and barCategoryGap props)
+ const spacePerCategory = availableWidth / data.length;
+
+ // For grouped charts, multiple bars share the category space
+ const barsPerCategory = variant === "stacked" ? 1 : dataKeys.length;
+
+ // Simple division - let Recharts apply gaps via barGap and barCategoryGap props
+ const barWidth = spacePerCategory / barsPerCategory;
+
+ // Only apply maximum constraint, let Recharts handle thin bars automatically
+ return Math.min(maxBarWidth, barWidth);
+ }, [explicitChartWidth, chartContainerWidth, data.length, dataKeys.length, variant, maxBarWidth]);
+
// Handle mouse events for bar hovering
const handleChartMouseMove = useCallback((state: any) => {
if (state && state.activeLabel !== undefined) {
@@ -231,15 +272,16 @@ const BarChartCondensedComponent = <T extends BarChartData>({
// Observe container width for legend
useEffect(() => {
- // Only set up ResizeObserver if width is not provided
- if (width || !containerRef.current || !chartContainerRef.current) {
+ // Always set up ResizeObserver for chartContainerRef to get accurate bar width calculations
+ if (!chartContainerRef.current) {
return () => {};
}
const resizeObserver = new ResizeObserver((entries) => {
// there is only one entry in the entries array because we are observing the chart container
for (const entry of entries) {
- if (entry.target === containerRef.current) {
+ if (entry.target === containerRef.current && !width) {
+ // Only observe containerRef if width is not provided
setContainerWidth(entry.contentRect.width);
}
if (entry.target === chartContainerRef.current) {
@@ -248,9 +290,14 @@ const BarChartCondensedComponent = <T extends BarChartData>({
}
});
- resizeObserver.observe(containerRef.current);
+ // Always observe chartContainerRef
resizeObserver.observe(chartContainerRef.current);
+ // Only observe containerRef if width is not provided
+ if (!width && containerRef.current) {
+ resizeObserver.observe(containerRef.current);
+ }
+
return () => {
resizeObserver.disconnect();
};
@@ -335,8 +382,8 @@ const BarChartCondensedComponent = <T extends BarChartData>({
fill={color}
stackId={variant === "stacked" ? "a" : undefined}
isAnimationActive={isAnimationActive}
- maxBarSize={BAR_WIDTH}
- barSize={BAR_WIDTH}
+ maxBarSize={calculatedBarWidth}
+ barSize={calculatedBarWidth}
shape={(props: any) => {
const { payload, value, dataKey } = props;
@@ -378,6 +425,7 @@ const BarChartCondensedComponent = <T extends BarChartData>({
barInternalLineColor,
hoveredCategory,
categoryKey,
+ calculatedBarWidth,
]);
return (
@@ -404,10 +452,13 @@ const BarChartCondensedComponent = <T extends BarChartData>({
<div className="crayon-bar-chart-condensed" ref={chartContainerRef}>
<ChartContainer
config={chartConfig}
- style={{ width: "100%", height: effectiveHeight }}
+ style={{
+ width: explicitChartWidth ? `${explicitChartWidth}px` : "100%",
+ height: effectiveHeight,
+ }}
rechartsProps={{
- width: "100%",
- height: "100%",
+ width: explicitChartWidth ?? "100%",
+ height: effectiveHeight,
}}
>
<RechartsBarChart
@@ -421,6 +472,8 @@ const BarChartCondensedComponent = <T extends BarChartData>({
onMouseMove={handleChartMouseMove}
onMouseLeave={handleChartMouseLeave}
onClick={onBarClick}
+ width={explicitChartWidth}
+ height={effectiveHeight}
>
{grid && cartesianGrid()}
diff --git a/js/packages/react-ui/src/components/Charts/BarChartCondensed/stories/barChartCondensed.stories.tsx b/js/packages/react-ui/src/components/Charts/BarChartCondensed/stories/barChartCondensed.stories.tsx
index f97ce8d74..3116cc7c3 100644
--- a/js/packages/react-ui/src/components/Charts/BarChartCondensed/stories/barChartCondensed.stories.tsx
+++ b/js/packages/react-ui/src/components/Charts/BarChartCondensed/stories/barChartCondensed.stories.tsx
@@ -265,7 +265,7 @@ const salesData = [
},
},
},
- tags: ["!dev", "autodocs"],
+ tags: ["dev", "autodocs"],
argTypes: {
data: {
description: `
@@ -1409,3 +1409,366 @@ export const ResponsiveBehaviorDemo: Story = {
);
},
};
+
+/**
+ * 🎯 Bar Width Testing Playground
+ * Interactive story to test bar width calculations with various configurations:
+ * - Different data set sizes (few bars vs many bars)
+ * - Grouped vs Stacked variants
+ * - Max bar width constraint (prevents bars from being too wide)
+ * - Container width variations
+ */
+export const BarWidthPlayground: StoryObj<typeof BarChartCondensed> = {
+ render: () => {
+ const [variant, setVariant] = useState<"grouped" | "stacked">("grouped");
+ const [dataSize, setDataSize] = useState<"small" | "medium" | "large" | "xlarge">("medium");
+ const [maxBarWidth, setMaxBarWidth] = useState(60);
+ const [containerWidth, setContainerWidth] = useState<number | undefined>(undefined);
+
+ // Generate data based on size selection
+ const generateData = () => {
+ const sizes = {
+ small: 4,
+ medium: 12,
+ large: 24,
+ xlarge: 50,
+ };
+
+ const count = sizes[dataSize];
+ return Array.from({ length: count }, (_, i) => ({
+ quarter: `Q${(i % 4) + 1} FY${2022 + Math.floor(i / 4)}`,
+ revenue: Math.floor(Math.random() * 2000000) + 500000,
+ expenses: Math.floor(Math.random() * 1500000) + 300000,
+ profit: Math.floor(Math.random() * 800000) + 100000,
+ }));
+ };
+
+ const data = generateData();
+
+ return (
+ <div style={{ padding: "20px" }}>
+ {/* Control Panel */}
+ <Card style={{ marginBottom: "24px", padding: "20px" }}>
+ <h3 style={{ marginTop: 0, marginBottom: "20px", fontSize: "18px", fontWeight: 600 }}>
+ πŸŽ›οΈ Bar Width Controls
+ </h3>
+
+ <div style={{ display: "grid", gridTemplateColumns: "1fr 1fr", gap: "20px" }}>
+ {/* Variant Control */}
+ <div>
+ <label style={{ display: "block", marginBottom: "8px", fontWeight: 500 }}>
+ Chart Variant
+ </label>
+ <div style={{ display: "flex", gap: "8px" }}>
+ <button
+ onClick={() => setVariant("grouped")}
+ style={{
+ padding: "8px 16px",
+ borderRadius: "6px",
+ border: "1px solid",
+ borderColor: variant === "grouped" ? "#6366f1" : "#e5e7eb",
+ backgroundColor: variant === "grouped" ? "#6366f1" : "white",
+ color: variant === "grouped" ? "white" : "#374151",
+ cursor: "pointer",
+ fontWeight: 500,
+ }}
+ >
+ Grouped
+ </button>
+ <button
+ onClick={() => setVariant("stacked")}
+ style={{
+ padding: "8px 16px",
+ borderRadius: "6px",
+ border: "1px solid",
+ borderColor: variant === "stacked" ? "#6366f1" : "#e5e7eb",
+ backgroundColor: variant === "stacked" ? "#6366f1" : "white",
+ color: variant === "stacked" ? "white" : "#374151",
+ cursor: "pointer",
+ fontWeight: 500,
+ }}
+ >
+ Stacked
+ </button>
+ </div>
+ </div>
+
+ {/* Data Size Control */}
+ <div>
+ <label style={{ display: "block", marginBottom: "8px", fontWeight: 500 }}>
+ Number of Data Points
+ </label>
+ <select
+ value={dataSize}
+ onChange={(e) => setDataSize(e.target.value as any)}
+ style={{
+ width: "100%",
+ padding: "8px 12px",
+ borderRadius: "6px",
+ border: "1px solid #e5e7eb",
+ fontSize: "14px",
+ }}
+ >
+ <option value="small">Small (4 points)</option>
+ <option value="medium">Medium (12 points)</option>
+ <option value="large">Large (24 points)</option>
+ <option value="xlarge">X-Large (50 points)</option>
+ </select>
+ </div>
+
+ {/* Max Bar Width Control */}
+ <div style={{ gridColumn: "1 / -1" }}>
+ <label style={{ display: "block", marginBottom: "8px", fontWeight: 500 }}>
+ Max Bar Width: {maxBarWidth}px
+ <span style={{ fontWeight: 400, color: "#6b7280", marginLeft: "8px" }}>
+ (Prevents bars from becoming too wide)
+ </span>
+ </label>
+ <input
+ type="range"
+ min="10"
+ max="120"
+ value={maxBarWidth}
+ onChange={(e) => setMaxBarWidth(Number(e.target.value))}
+ style={{ width: "100%" }}
+ />
+ <div
+ style={{
+ display: "flex",
+ justifyContent: "space-between",
+ fontSize: "11px",
+ color: "#6b7280",
+ marginTop: "4px",
+ }}
+ >
+ <span>10px</span>
+ <span>120px</span>
+ </div>
+ </div>
+
+ {/* Container Width Control */}
+ <div style={{ gridColumn: "1 / -1" }}>
+ <label style={{ display: "block", marginBottom: "8px", fontWeight: 500 }}>
+ Container Width: {containerWidth ? `${containerWidth}px` : "Auto (100%)"}
+ </label>
+ <div style={{ display: "flex", gap: "8px", alignItems: "center" }}>
+ <input
+ type="range"
+ min="400"
+ max="1400"
+ step="50"
+ value={containerWidth || 1400}
+ onChange={(e) => setContainerWidth(Number(e.target.value))}
+ style={{ flex: 1 }}
+ disabled={!containerWidth}
+ />
+ <button
+ onClick={() => setContainerWidth(containerWidth ? undefined : 800)}
+ style={{
+ padding: "6px 12px",
+ borderRadius: "6px",
+ border: "1px solid #e5e7eb",
+ backgroundColor: containerWidth ? "#ef4444" : "#10b981",
+ color: "white",
+ cursor: "pointer",
+ fontSize: "12px",
+ fontWeight: 500,
+ }}
+ >
+ {containerWidth ? "Auto" : "Fixed"}
+ </button>
+ </div>
+ <div
+ style={{
+ display: "flex",
+ justifyContent: "space-between",
+ fontSize: "11px",
+ color: "#6b7280",
+ marginTop: "4px",
+ }}
+ >
+ <span>400px</span>
+ <span>1400px</span>
+ </div>
+ </div>
+ </div>
+
+ {/* Info Display */}
+ <div
+ style={{
+ marginTop: "20px",
+ padding: "12px",
+ backgroundColor: "#f3f4f6",
+ borderRadius: "6px",
+ fontSize: "13px",
+ }}
+ >
+ <div style={{ display: "grid", gridTemplateColumns: "1fr 1fr 1fr", gap: "12px" }}>
+ <div>
+ <strong>Data Points:</strong> {data.length}
+ </div>
+ <div>
+ <strong>Bars per Category:</strong> {variant === "stacked" ? 1 : 3}
+ </div>
+ <div>
+ <strong>Total Bars:</strong> {data.length * (variant === "stacked" ? 1 : 3)}
+ </div>
+ </div>
+ </div>
+ </Card>
+
+ {/* Chart Display */}
+ <Card>
+ <h3 style={{ marginTop: 0, marginBottom: "16px" }}>
+ {variant === "grouped" ? "πŸ“Š Grouped" : "πŸ“š Stacked"} Bar Chart - Bar Width Test
+ </h3>
+ <div style={{ width: containerWidth ? `${containerWidth}px` : "100%" }}>
+ <BarChartCondensed
+ data={data}
+ categoryKey="quarter"
+ variant={variant}
+ maxBarWidth={maxBarWidth}
+ width={containerWidth}
+ height={400}
+ legend
+ grid
+ showYAxis
+ xAxisLabel="Fiscal Quarter"
+ yAxisLabel="Amount ($)"
+ />
+ </div>
+ </Card>
+
+ {/* Quick Test Presets */}
+ <Card style={{ marginTop: "24px", padding: "20px" }}>
+ <h3 style={{ marginTop: 0, marginBottom: "16px", fontSize: "16px", fontWeight: 600 }}>
+ πŸš€ Quick Test Presets
+ </h3>
+ <div style={{ display: "grid", gridTemplateColumns: "repeat(3, 1fr)", gap: "12px" }}>
+ <button
+ onClick={() => {
+ setDataSize("small");
+ setVariant("grouped");
+ setMaxBarWidth(60);
+ setContainerWidth(undefined);
+ }}
+ style={{
+ padding: "12px",
+ borderRadius: "6px",
+ border: "1px solid #e5e7eb",
+ backgroundColor: "white",
+ cursor: "pointer",
+ textAlign: "left",
+ }}
+ >
+ <div style={{ fontWeight: 600, marginBottom: "4px" }}>🎯 Few Bars (Wide)</div>
+ <div style={{ fontSize: "12px", color: "#6b7280" }}>4 points, max 60px cap</div>
+ </button>
+
+ <button
+ onClick={() => {
+ setDataSize("xlarge");
+ setVariant("grouped");
+ setMaxBarWidth(60);
+ setContainerWidth(undefined);
+ }}
+ style={{
+ padding: "12px",
+ borderRadius: "6px",
+ border: "1px solid #e5e7eb",
+ backgroundColor: "white",
+ cursor: "pointer",
+ textAlign: "left",
+ }}
+ >
+ <div style={{ fontWeight: 600, marginBottom: "4px" }}>πŸ“‰ Many Bars (Thin)</div>
+ <div style={{ fontSize: "12px", color: "#6b7280" }}>
+ 50 points, auto-sized thin bars
+ </div>
+ </button>
+
+ <button
+ onClick={() => {
+ setDataSize("large");
+ setVariant("stacked");
+ setMaxBarWidth(40);
+ setContainerWidth(800);
+ }}
+ style={{
+ padding: "12px",
+ borderRadius: "6px",
+ border: "1px solid #e5e7eb",
+ backgroundColor: "white",
+ cursor: "pointer",
+ textAlign: "left",
+ }}
+ >
+ <div style={{ fontWeight: 600, marginBottom: "4px" }}>πŸ”„ Fixed Container</div>
+ <div style={{ fontSize: "12px", color: "#6b7280" }}>24 points, stacked, 800px</div>
+ </button>
+
+ <button
+ onClick={() => {
+ setDataSize("medium");
+ setVariant("grouped");
+ setMaxBarWidth(100);
+ setContainerWidth(undefined);
+ }}
+ style={{
+ padding: "12px",
+ borderRadius: "6px",
+ border: "1px solid #e5e7eb",
+ backgroundColor: "white",
+ cursor: "pointer",
+ textAlign: "left",
+ }}
+ >
+ <div style={{ fontWeight: 600, marginBottom: "4px" }}>🎨 Large Max Width</div>
+ <div style={{ fontSize: "12px", color: "#6b7280" }}>Medium data, max 100px</div>
+ </button>
+
+ <button
+ onClick={() => {
+ setDataSize("small");
+ setVariant("stacked");
+ setMaxBarWidth(30);
+ setContainerWidth(400);
+ }}
+ style={{
+ padding: "12px",
+ borderRadius: "6px",
+ border: "1px solid #e5e7eb",
+ backgroundColor: "white",
+ cursor: "pointer",
+ textAlign: "left",
+ }}
+ >
+ <div style={{ fontWeight: 600, marginBottom: "4px" }}>πŸ“± Narrow Container</div>
+ <div style={{ fontSize: "12px", color: "#6b7280" }}>Small data, 400px width</div>
+ </button>
+
+ <button
+ onClick={() => {
+ setDataSize("xlarge");
+ setVariant("stacked");
+ setMaxBarWidth(20);
+ setContainerWidth(undefined);
+ }}
+ style={{
+ padding: "12px",
+ borderRadius: "6px",
+ border: "1px solid #e5e7eb",
+ backgroundColor: "white",
+ cursor: "pointer",
+ textAlign: "left",
+ }}
+ >
+ <div style={{ fontWeight: 600, marginBottom: "4px" }}>πŸ”¬ Ultra Condensed</div>
+ <div style={{ fontSize: "12px", color: "#6b7280" }}>50 points, stacked, max 20px</div>
+ </button>
+ </div>
+ </Card>
+ </div>
+ );
+ },
+};
diff --git a/js/packages/react-ui/src/components/Charts/LineChartCondensed/LineChartCondensed.tsx b/js/packages/react-ui/src/components/Charts/LineChartCondensed/LineChartCondensed.tsx
index 8ee1fe9e5..aabf781ba 100644
--- a/js/packages/react-ui/src/components/Charts/LineChartCondensed/LineChartCondensed.tsx
+++ b/js/packages/react-ui/src/components/Charts/LineChartCondensed/LineChartCondensed.tsx
@@ -102,8 +102,10 @@ const LineChartCondensedComponent = <T extends LineChartData>({
if (data.length === 0) {
return 0;
}
- return chartContainerWidth / data.length;
- }, [chartContainerWidth, data]);
+ // Use passed width if available, otherwise use observed chartContainerWidth
+ const chartWidth = width ?? chartContainerWidth;
+ return chartWidth / data.length;
+ }, [width, chartContainerWidth, data]);
const { angle: calculatedAngle, height: xAxisHeight } = useAutoAngleCalculation(
maxLabelWidth,
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
index f984adef6..a55b9e94a 100644
--- a/js/packages/react-ui/src/components/Charts/shared/LineInBarShape/LineInBarShape.tsx
+++ b/js/packages/react-ui/src/components/Charts/shared/LineInBarShape/LineInBarShape.tsx
@@ -23,7 +23,8 @@ interface LineInBarShapeProps {
}
const DEFAULT_STACK_GAP = 1;
-const MIN_LINE_DIMENSION = 8; // For internal line visibility
+const MIN_LINE_DIMENSION = 8; // For internal line visibility (height/width threshold)
+const MIN_BAR_WIDTH_FOR_LINE = 3; // Minimum bar width to show internal line in vertical mode
const LINE_PADDING = 6;
const MIN_GROUP_BAR_HEIGHT = 2; // For vertical bars
const MIN_STACKED_BAR_HEIGHT = 4; // For vertical bars
@@ -302,7 +303,11 @@ const LineInBarShape: FunctionComponent<LineInBarShapeProps> = React.memo((props
const lineCoords = useMemo(() => {
if (isVertical) {
- if (width <= 0 || adjustedHeight < MIN_LINE_DIMENSION) return null;
+ // For vertical bars: hide line if bar width < 3px (too thin) OR height < 8px (too short)
+ // This ensures thin bars don't have a visible internal line that looks awkward
+ if (width <= 0 || width < MIN_BAR_WIDTH_FOR_LINE || adjustedHeight < MIN_LINE_DIMENSION) {
+ return null;
+ }
const centerX = x + width / 2;
return {
x1: centerX,
@@ -311,7 +316,7 @@ const LineInBarShape: FunctionComponent<LineInBarShapeProps> = React.memo((props
y2: adjustedY + adjustedHeight - LINE_PADDING,
};
}
- // Horizontal
+ // Horizontal bars: hide line if width < 8px OR height <= 0
if (adjustedWidth < MIN_LINE_DIMENSION || height <= 0) return null;
const centerY = y + height / 2;
return {