Skip to content

The Open Standard for Generative UI

feat(BarChart): Add positive and negative data variation support (#158)

Ankit Das18e186dd8495
diff --git a/js/packages/react-ui/package.json b/js/packages/react-ui/package.json
index b79165750..362433457 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.13",
+ "version": "0.8.14",
"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 0c9d532bc..3875adb3e 100644
--- a/js/packages/react-ui/src/components/Charts/BarChart/BarChart.tsx
+++ b/js/packages/react-ui/src/components/Charts/BarChart/BarChart.tsx
@@ -23,7 +23,11 @@ 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 {
+ findNearestSnapPosition,
+ getBarStackInfo,
+ getRadiusArray,
+} from "../utils/BarCharts/BarChartsUtils";
import {
get2dChartConfig,
getColorForDataKey,
@@ -259,6 +263,7 @@ const BarChartComponent = <T extends BarChartData>({
width={yAxisWidth}
height={chartHeight}
data={data}
+ stackOffset="sign"
margin={{
top: 20,
bottom: maxLabelHeight + CHART_CONTAINER_BOTTOM_MARGIN, // this is required for to give space for x-axis
@@ -333,38 +338,48 @@ const BarChartComponent = <T extends BarChartData>({
);
const barElements = useMemo(() => {
- return dataKeys.map((key, index) => {
+ return dataKeys.map((key) => {
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,
- "vertical",
- variant === "stacked" ? isFirstInStack : undefined,
- variant === "stacked" ? isLastInStack : undefined,
- )}
stackId={variant === "stacked" ? "a" : undefined}
isAnimationActive={isAnimationActive}
maxBarSize={BAR_WIDTH}
barSize={BAR_WIDTH}
- shape={
- <LineInBarShape
- internalLineColor={barInternalLineColor}
- internalLineWidth={BAR_INTERNAL_LINE_WIDTH}
- isHovered={hoveredCategory !== null}
- hoveredCategory={hoveredCategory}
- categoryKey={categoryKey as string}
- variant={variant}
- />
- }
+ shape={(props: any) => {
+ const { payload, value, dataKey } = props;
+
+ const { isNegative, isFirstInStack, isLastInStack, hasNegativeValueInStack } =
+ getBarStackInfo(variant, value, dataKey, payload, dataKeys);
+
+ const customRadius = getRadiusArray(
+ variant,
+ radius,
+ "vertical",
+ isFirstInStack,
+ isLastInStack,
+ isNegative,
+ );
+
+ return (
+ <LineInBarShape
+ {...props}
+ radius={customRadius}
+ internalLineColor={barInternalLineColor}
+ internalLineWidth={BAR_INTERNAL_LINE_WIDTH}
+ isHovered={hoveredCategory !== null}
+ hoveredCategory={hoveredCategory}
+ categoryKey={categoryKey as string}
+ variant={variant}
+ hasNegativeValueInStack={hasNegativeValueInStack}
+ />
+ );
+ }}
/>
);
});
@@ -406,6 +421,7 @@ const BarChartComponent = <T extends BarChartData>({
}}
>
<RechartsBarChart
+ stackOffset="sign"
accessibilityLayer
key={`bar-chart-${id}`}
data={data}
diff --git a/js/packages/react-ui/src/components/Charts/BarChart/stories/barChart.stories.tsx b/js/packages/react-ui/src/components/Charts/BarChart/stories/barChart.stories.tsx
index 79cc30a84..6305bcb39 100644
--- a/js/packages/react-ui/src/components/Charts/BarChart/stories/barChart.stories.tsx
+++ b/js/packages/react-ui/src/components/Charts/BarChart/stories/barChart.stories.tsx
@@ -547,6 +547,14 @@ const dataVariations = {
{ month: "July 1st - July 31st, 2024 (Summer Quarter)", sales: 350 },
{ month: "August 1st - August 31st, 2024 (Summer Quarter)", sales: 400 },
],
+ positiveNegative: [
+ { month: "January", profit: -4000000, loss: -2000000, netWorth: 2000000 },
+ { month: "February", profit: 3000000, loss: -4000000, netWorth: -1000000 },
+ { month: "March", profit: -1000000, loss: -1500000, netWorth: -2500000 },
+ { month: "April", profit: 5000000, loss: -2500000, netWorth: 2500000 },
+ { month: "May", profit: -2000000, loss: -3000000, netWorth: -5000000 },
+ { month: "June", profit: 1000000, loss: -500000, netWorth: 500000 },
+ ],
};
// Category key mappings for different datasets
@@ -561,6 +569,7 @@ const categoryKeys = {
bigNumbers: "company",
expandCollapseMarketing: "channel",
singleGroup: "month",
+ positiveNegative: "month",
};
// πŸ”₯ ACTIVE DATA - For backward compatibility
@@ -913,6 +922,12 @@ export const DataExplorer: Story = {
>
πŸ”„ Marketing Channels
</button>
+ <button
+ onClick={() => setSelectedDataType("positiveNegative")}
+ style={selectedDataType === "positiveNegative" ? activeButtonStyle : buttonStyle}
+ >
+ πŸ“ˆ Positive & Negative
+ </button>
</div>
<div style={{ marginTop: "8px", fontSize: "12px", color: "#666" }}>
<strong>Current:</strong> {selectedDataType} | <strong>Items:</strong>{" "}
diff --git a/js/packages/react-ui/src/components/Charts/Charts.tsx b/js/packages/react-ui/src/components/Charts/Charts.tsx
index 65a60026f..d3ef81787 100644
--- a/js/packages/react-ui/src/components/Charts/Charts.tsx
+++ b/js/packages/react-ui/src/components/Charts/Charts.tsx
@@ -65,24 +65,6 @@ function useChart() {
return context;
}
-export function keyTransform(key: string) {
- return (
- key
- // Replace whitespace with hyphens
- .replaceAll(/\s+/g, "-")
- // Replace any character that's not alphanumeric, hyphen, or underscore with hyphen
- .replaceAll(/[^a-zA-Z0-9_-]/g, "-")
- // Remove multiple consecutive hyphens
- .replaceAll(/-+/g, "-")
- // Remove leading/trailing hyphens
- .replace(/^-+|-+$/g, "")
- // Ensure it doesn't start with a number (prepend 'key-' if it does)
- .replace(/^(\d)/, "key-$1") ??
- // Fallback with unique ID if the key is empty
- `key-${uniqueId()}`
- );
-}
-
/**
* Component that generates theme-specific styles for chart elements
*/
diff --git a/js/packages/react-ui/src/components/Charts/HorizontalBarChart/HorizontalBarChart.tsx b/js/packages/react-ui/src/components/Charts/HorizontalBarChart/HorizontalBarChart.tsx
index 6aaf78601..1d5c075e3 100644
--- a/js/packages/react-ui/src/components/Charts/HorizontalBarChart/HorizontalBarChart.tsx
+++ b/js/packages/react-ui/src/components/Charts/HorizontalBarChart/HorizontalBarChart.tsx
@@ -20,7 +20,11 @@ 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 {
+ findNearestSnapPosition,
+ getBarStackInfo,
+ getRadiusArray,
+} from "../utils/BarCharts/BarChartsUtils";
import {
get2dChartConfig,
getColorForDataKey,
@@ -262,6 +266,7 @@ const HorizontalBarChartComponent = <T extends HorizontalBarChartData>({
left: 5,
right: 2,
}}
+ stackOffset="sign"
>
<XAxis
type="number"
@@ -275,7 +280,7 @@ const HorizontalBarChartComponent = <T extends HorizontalBarChartData>({
{dataKeys.map((key) => {
return (
<Bar
- key={`xaxis-horizontal-bar-chart-${key}`}
+ key={`x-axis-horizontal-bar-chart-${key}`}
dataKey={key}
fill="transparent"
stackId={variant === "stacked" ? "a" : undefined}
@@ -364,6 +369,7 @@ const HorizontalBarChartComponent = <T extends HorizontalBarChartData>({
left: 2,
right: 2,
}}
+ stackOffset="sign"
>
{grid && verticalCartesianGrid()}
{/* this x axis is not visible but is needed for the chart to work */}
@@ -395,37 +401,51 @@ const HorizontalBarChartComponent = <T extends HorizontalBarChartData>({
{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}
- />
- }
+ shape={(props: any) => {
+ const { payload, value, dataKey } = props;
+
+ const { isNegative, isFirstInStack, isLastInStack } = getBarStackInfo(
+ variant,
+ value,
+ dataKey,
+ payload,
+ dataKeys,
+ );
+
+ const customRadius = getRadiusArray(
+ variant,
+ radius,
+ "horizontal",
+ isFirstInStack,
+ isLastInStack,
+ isNegative,
+ );
+
+ return (
+ <CustomBarShape
+ {...props}
+ radius={customRadius}
+ index={index}
+ categoryKey={categoryKey as string}
+ effectiveWidth={effectiveWidth}
+ labelHeight={labelHeight}
+ barInternalLineColor={barInternalLineColor}
+ internalLineWidth={BAR_INTERNAL_LINE_WIDTH}
+ hoveredCategory={hoveredCategory}
+ variant={variant}
+ />
+ );
+ }}
/>
);
})}
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
index 689438af7..8ad88bac2 100644
--- 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
@@ -361,6 +361,13 @@ const dataVariations = {
videoViews: 15000,
},
],
+ mixedPositiveNegative: [
+ { category: "Product A", profit: 100, loss: -50, net: 50 },
+ { category: "Product B", profit: 150, loss: -200, net: -50 },
+ { category: "Product C", profit: 200, loss: -100, net: 100 },
+ { category: "Product D", profit: -80, loss: -120, net: -200 },
+ { category: "Product E", profit: 300, loss: -150, net: 150 },
+ ],
singleGroup: [
{ region: "North America (USA, Canada, Mexico)", sales: 150000 },
{ region: "Europe (UK, Germany, France, Italy)", sales: 280000 },
@@ -379,6 +386,7 @@ const categoryKeys = {
edge: "period",
bigNumbers: "company",
expandCollapseChannels: "channel",
+ mixedPositiveNegative: "category",
singleGroup: "region",
};
@@ -721,6 +729,12 @@ export const DataExplorer: Story = {
>
🌍 Single Group
</button>
+ <button
+ onClick={() => setSelectedDataType("mixedPositiveNegative")}
+ style={selectedDataType === "mixedPositiveNegative" ? activeButtonStyle : buttonStyle}
+ >
+ πŸ“ˆ Mixed +/-
+ </button>
<button
onClick={() => setSelectedDataType("expandCollapseChannels")}
style={
@@ -858,6 +872,23 @@ export const LargeDataset: Story = {
),
};
+export const MixedPositiveNegative: Story = {
+ name: "πŸ“ˆ Mixed Positive and Negative",
+ args: {
+ data: dataVariations.mixedPositiveNegative,
+ categoryKey: "category",
+ theme: "spectrum",
+ variant: "grouped",
+ height: 400,
+ width: 600,
+ },
+ render: (args: any) => (
+ <Card style={{ width: "600px" }}>
+ <HorizontalBarChart {...args} />
+ </Card>
+ ),
+};
+
export const WithIcons: Story = {
args: {
data: dataVariations.default,
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 94ca615c8..b4af728bb 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
@@ -18,6 +18,7 @@ interface LineInBarShapeProps {
variant?: "grouped" | "stacked";
stackGap?: number;
orientation?: "vertical" | "horizontal";
+ hasNegativeValueInStack?: boolean;
[key: string]: any; // Allow other props from Recharts
}
@@ -47,68 +48,204 @@ const LineInBarShape: FunctionComponent<LineInBarShapeProps> = React.memo((props
variant = "grouped",
stackGap = DEFAULT_STACK_GAP,
orientation = "vertical",
+ hasNegativeValueInStack,
} = props;
const isVertical = orientation === "vertical";
+ const isNegative = isVertical ? height < 0 : width < 0;
- const { rTL, rTR, rBR } = useMemo(() => {
- const minHeight = isVertical ? MIN_GROUP_BAR_HEIGHT : MIN_BAR_WIDTH;
+ const w = isNegative && !isVertical ? -width : width;
+ const h = isNegative && isVertical ? -height : height;
+
+ const x_ = isNegative && !isVertical ? x + width : x;
+ const y_ = isNegative && isVertical ? y + height : y;
+
+ /**
+ * Calculates the corner radii for the bar.
+ * This logic ensures that only the "outer" corners of a bar are rounded,
+ * depending on its orientation (vertical/horizontal) and whether it's a
+ * positive or negative value.
+ *
+ * - For vertical bars, top corners are rounded for positive values, and
+ * bottom corners for negative values.
+ * - For horizontal bars, right corners are rounded for positive values, and
+ * left corners for negative values.
+ *
+ * If the bar's dimensions are below a certain threshold, no rounding is applied.
+ * The `radius` prop can be a single number or an array `[rTL, rTR, rBR, rBL]`.
+ */
+ const { rTL, rTR, rBL, rBR } = useMemo(() => {
+ // This code calculates which corners of a bar should be rounded based on several factors:
+
+ // First check if the bar is too small to have rounded corners
+ const minDimension = isVertical ? MIN_GROUP_BAR_HEIGHT : MIN_BAR_WIDTH;
+ const dimension = isVertical ? h : w;
+
+ // If bar is too small, return no rounded corners
if (
- (variant === "grouped" && height < minHeight) ||
- (variant === "stacked" && height < MIN_STACKED_BAR_HEIGHT)
+ (variant === "grouped" && dimension < minDimension) ||
+ (variant === "stacked" && dimension < MIN_STACKED_BAR_HEIGHT)
) {
- return { rTL: 0, rTR: 0, rBR: 0 };
+ return { rTL: 0, rTR: 0, rBL: 0, rBR: 0 };
}
+ // If radius is an array, apply specific radius to each corner
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 };
+ // The radius array is expected to be in the format [rTL, rTR, rBR, rBL].
+ return { rTL: r[0] || 0, rTR: r[1] || 0, rBR: r[2] || 0, rBL: r[3] || 0 };
} else if (typeof r === "number") {
- if (isVertical) return { rTL: r, rTR: r, rBR: 0 };
- return { rTL: 0, rTR: r, rBR: r };
+ // If radius is a single number, apply it consistently based on orientation
+ if (isVertical) {
+ if (isNegative) return { rTL: 0, rTR: 0, rBL: r, rBR: r };
+ return { rTL: r, rTR: r, rBL: 0, rBR: 0 };
+ }
+ // For horizontal bars
+ if (isNegative) return { rTL: r, rTR: 0, rBL: r, rBR: 0 };
+ return { rTL: 0, rTR: r, rBL: 0, rBR: r };
}
- return { rTL: 0, rTR: 0, rBR: 0 };
- }, [r, variant, height, isVertical]);
+ // Default case - no rounded corners
+ return { rTL: 0, rTR: 0, rBL: 0, rBR: 0 };
+ }, [r, variant, h, w, isVertical, isNegative]);
+ // This code calculates the opacity of a bar based on hover state:
+ // - Returns 1 (fully opaque) if:
+ // - Chart is not being hovered (isHovered is false)
+ // - No category is being hovered (hoveredCategory is null)
+ // - Missing required data (payload or categoryKey)
+ // - If chart is being hovered:
+ // - Returns 1 if this bar's category matches the hovered category
+ // - Returns 0.4 (40% opacity) if this bar's category doesn't match
const opacity = useMemo(() => {
if (!isHovered || hoveredCategory === null || !payload || !categoryKey) return 1;
return payload[categoryKey] === hoveredCategory ? 1 : 0.4;
}, [isHovered, hoveredCategory, payload, categoryKey]);
+ // This code adjusts the dimensions and position of bars in the chart:
+ // - For vertical bars:
+ // - Reduces height by stackGap if stacked variant
+ // - Enforces minimum height based on variant (grouped vs stacked)
+ // - Adjusts Y position for positive values to align from bottom
+ // - For horizontal bars:
+ // - Reduces width by stackGap if stacked variant
+ // - Enforces minimum width
+ // Returns adjusted x, y coordinates and dimensions while preserving original values
const { adjustedX, adjustedY, adjustedWidth, adjustedHeight } = useMemo(() => {
- let finalX = x;
- let finalY = y;
- let finalWidth = width;
- let finalHeight = height;
+ // Initialize final dimensions with original values
+ let finalX = x_; // Starting x position
+ let finalY = y_; // Starting y position
+ let finalWidth = w; // Original width
+ let finalHeight = h; // Original height
if (isVertical) {
- if (variant === "stacked" && stackGap > 0) finalHeight = height - stackGap;
- if (height > 0) {
+ // For vertical bars:
+
+ // If stacked bars, reduce height by gap between bars
+ if (variant === "stacked" && stackGap > 0) {
+ finalHeight = h - stackGap;
+ }
+
+ // Enforce minimum height based on variant
+ if (h > 0) {
const minHeight =
- variant === "grouped" ? MIN_GROUP_BAR_HEIGHT : MIN_STACKED_BAR_HEIGHT - stackGap;
+ variant === "grouped"
+ ? MIN_GROUP_BAR_HEIGHT // Minimum 2px for grouped bars
+ : MIN_STACKED_BAR_HEIGHT - stackGap; // Minimum 4px minus gap for stacked
finalHeight = Math.max(finalHeight, minHeight);
}
- finalY = y + height - finalHeight;
+
+ // For positive values, adjust Y to align from bottom
+ if (!isNegative) {
+ if (variant === "stacked" && stackGap > 0 && hasNegativeValueInStack) {
+ finalY = y + h - finalHeight - stackGap;
+ } else {
+ finalY = y + h - finalHeight;
+ }
+ }
} else {
- // Horizontal
- if (variant === "stacked" && stackGap > 0) finalWidth = width - stackGap;
- if (width > 0) {
- const minWidth = MIN_BAR_WIDTH;
- finalWidth = Math.max(finalWidth, minWidth);
+ // For horizontal bars:
+
+ // If stacked, reduce width by gap between bars
+ if (variant === "stacked" && stackGap > 0) {
+ finalWidth = w - stackGap;
+ }
+
+ // Enforce minimum width of 2px
+ if (w > 0) {
+ finalWidth = Math.max(finalWidth, MIN_BAR_WIDTH);
}
- // No adjustment for X as it grows left-to-right
}
+ // Return adjusted dimensions and positions
return {
adjustedX: finalX,
adjustedY: finalY,
adjustedWidth: finalWidth,
adjustedHeight: finalHeight,
};
- }, [variant, stackGap, x, y, width, height, isVertical]);
+ }, [variant, stackGap, x, y, w, h, isVertical, isNegative, x_, y_]);
+
+ /**
+ * Generates the SVG path for the bar.
+ * This code creates the SVG path string for a bar with rounded corners.
+ * The path drawing logic changes based on:
+ * 1. Bar orientation (vertical vs horizontal)
+ * 2. Value sign (positive vs negative)
+ *
+ * The SVG path is drawn using commands:
+ * - M x,y: Move to point (x,y) without drawing
+ * - L x,y: Draw line to point (x,y)
+ * - A rx,ry angle,large-arc,sweep x,y: Draw arc with radius rx,ry to point (x,y)
+ * The arc parameters control:
+ * - angle: rotation of arc (0 = no rotation)
+ * - large-arc: 0 = small arc, 1 = large arc
+ * - sweep: 0 = counter-clockwise, 1 = clockwise
+ * - Z: Close path by drawing line back to start
+ *
+ * For rounded corners, we:
+ * 1. Move to start point
+ * 2. Draw straight edges
+ * 3. For each corner that should be rounded:
+ * - Stop short of corner by radius amount
+ * - Draw arc with specified radius to next edge
+ * - Continue with straight edges
+ * 4. Close path
+ */
const path = useMemo(() => {
+ // This code generates SVG path strings to draw bars with rounded corners
+ // The path drawing logic changes based on:
+ // 1. Bar orientation (vertical vs horizontal)
+ // 2. Value sign (positive vs negative)
+
if (isVertical) {
+ // For vertical bars
+ if (isNegative) {
+ // Draw downward pointing bar with rounded bottom corners if specified
+ // This path draws a vertical bar with rounded bottom corners for negative values
+ // Here's how each command works:
+ // 1. M ${x},${adjustedY} - Move to top-left corner
+ // 2. L ${x + adjustedWidth},${adjustedY} - Draw line to top-right corner
+ // 3. L ${x + adjustedWidth},${adjustedY + adjustedHeight - rBR} - Draw line down right side, stopping before bottom-right corner
+ // 4. If bottom-right radius (rBR) > 0:
+ // A ${rBR},${rBR} 0 0 1 ${x + adjustedWidth - rBR},${adjustedY + adjustedHeight}
+ // Draw arc: radius rBR, no rotation (0), small arc (0), clockwise (1), end at bottom-right rounded corner
+ // Else: Draw straight line to bottom-right corner
+ // 5. L ${x + rBL},${adjustedY + adjustedHeight} - Draw line left along bottom, stopping before bottom-left corner
+ // 6. If bottom-left radius (rBL) > 0:
+ // A ${rBL},${rBL} 0 0 1 ${x},${adjustedY + adjustedHeight - rBL}
+ // Draw arc: radius rBL, no rotation (0), small arc (0), clockwise (1), end at bottom-left rounded corner
+ // Else: Draw straight line to bottom-left corner
+ // 7. Z - Close path by drawing line back to start
+ return `
+ M ${x},${adjustedY}
+ L ${x + adjustedWidth},${adjustedY}
+ L ${x + adjustedWidth},${adjustedY + adjustedHeight - rBR}
+ ${rBR > 0 ? `A ${rBR},${rBR} 0 0 1 ${x + adjustedWidth - rBR},${adjustedY + adjustedHeight}` : `L ${x + adjustedWidth},${adjustedY + adjustedHeight}`}
+ L ${x + rBL},${adjustedY + adjustedHeight}
+ ${rBL > 0 ? `A ${rBL},${rBL} 0 0 1 ${x},${adjustedY + adjustedHeight - rBL}` : `L ${x},${adjustedY + adjustedHeight}`}
+ Z`;
+ }
+ // Draw upward pointing bar with rounded top corners if specified
return `
M ${x},${adjustedY + rTL}
${rTL > 0 ? `A ${rTL},${rTL} 0 0 1 ${x + rTL},${adjustedY}` : `L ${x},${adjustedY}`}
@@ -118,7 +255,20 @@ const LineInBarShape: FunctionComponent<LineInBarShapeProps> = React.memo((props
L ${x},${adjustedY + adjustedHeight}
Z`;
}
- // Horizontal
+
+ // For horizontal bars
+ if (isNegative) {
+ // Draw leftward pointing bar with rounded left corners if specified
+ return `
+ M ${adjustedX + rTL},${y}
+ ${rTL > 0 ? `A ${rTL},${rTL} 0 0 0 ${adjustedX},${y + rTL}` : `L ${adjustedX},${y}`}
+ L ${adjustedX},${y + height - rBL}
+ ${rBL > 0 ? `A ${rBL},${rBL} 0 0 0 ${adjustedX + rBL},${y + height}` : `L ${adjustedX},${y + height}`}
+ L ${adjustedX + adjustedWidth},${y + height}
+ L ${adjustedX + adjustedWidth},${y}
+ Z`;
+ }
+ // Draw rightward pointing bar with rounded right corners if specified
return `
M ${adjustedX},${y}
L ${adjustedX + adjustedWidth - rTR},${y}
@@ -137,13 +287,15 @@ const LineInBarShape: FunctionComponent<LineInBarShapeProps> = React.memo((props
height,
rTL,
rTR,
+ rBL,
rBR,
isVertical,
+ isNegative,
]);
const lineCoords = useMemo(() => {
if (isVertical) {
- if (width <= 0 || adjustedHeight <= MIN_LINE_DIMENSION) return null;
+ if (width <= 0 || adjustedHeight < MIN_LINE_DIMENSION) return null;
const centerX = x + width / 2;
return {
x1: centerX,
@@ -153,7 +305,7 @@ const LineInBarShape: FunctionComponent<LineInBarShapeProps> = React.memo((props
};
}
// Horizontal
- if (adjustedWidth <= MIN_LINE_DIMENSION || height <= 0) return null;
+ if (adjustedWidth < MIN_LINE_DIMENSION || height <= 0) return null;
const centerY = y + height / 2;
return {
x1: adjustedX + LINE_PADDING,
diff --git a/js/packages/react-ui/src/components/Charts/shared/PortalTooltip/utils/index.ts b/js/packages/react-ui/src/components/Charts/shared/PortalTooltip/utils/index.ts
index 6dc61a404..a97be63e6 100644
--- a/js/packages/react-ui/src/components/Charts/shared/PortalTooltip/utils/index.ts
+++ b/js/packages/react-ui/src/components/Charts/shared/PortalTooltip/utils/index.ts
@@ -1,11 +1,14 @@
const tooltipNumberFormatter = (value: number) => {
- if (value < 100000) {
- return value.toLocaleString();
+ const isNegative = value < 0;
+ const absValue = Math.abs(value);
+
+ if (absValue < 100000) {
+ return (isNegative ? "-" : "") + absValue.toLocaleString();
}
const units = ["", "K", "M", "B", "T"];
let unitIndex = 0;
- let scaledValue = value;
+ let scaledValue = absValue;
while (scaledValue >= 1000 && unitIndex < units.length - 1) {
scaledValue /= 1000;
@@ -15,7 +18,7 @@ const tooltipNumberFormatter = (value: number) => {
// Format with at most 1 decimal place
const formattedValue = Math.floor(scaledValue * 10) / 10;
- return `${formattedValue}${units[unitIndex]}`;
+ return (isNegative ? "-" : "") + `${formattedValue}${units[unitIndex]}`;
};
export { tooltipNumberFormatter };
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
index f4974d3d5..8cf311f41 100644
--- a/js/packages/react-ui/src/components/Charts/utils/BarCharts/BarChartsUtils.ts
+++ b/js/packages/react-ui/src/components/Charts/utils/BarCharts/BarChartsUtils.ts
@@ -6,40 +6,52 @@ export const getRadiusArray = (
orientation: "vertical" | "horizontal",
isFirst?: boolean,
isLast?: boolean,
+ isNegative?: boolean,
): [number, number, number, number] => {
if (variant === "grouped") {
if (orientation === "vertical") {
- return [radius, radius, 0, 0]; // top-left, top-right, bottom-right, bottom-left
+ if (isNegative) {
+ return [0, 0, radius, radius]; // bottom-right, bottom-left for negative bars
+ }
+ return [radius, radius, 0, 0]; // top-left, top-right for positive bars
} else {
// horizontal
- return [0, radius, radius, 0];
+ if (isNegative) {
+ return [radius, 0, 0, radius]; // top-left, bottom-left for negative bars
+ }
+ return [0, radius, radius, 0]; // top-right, bottom-right for positive bars
}
} else if (variant === "stacked") {
+ // For single-item stacks, round the end of the bar.
if (isFirst && isLast) {
- // Single item in stack
- return [radius, radius, radius, radius];
+ if (orientation === "vertical") {
+ return isNegative ? [0, 0, radius, radius] : [radius, radius, 0, 0];
+ } else {
+ // horizontal
+ return isNegative ? [radius, 0, 0, radius] : [0, radius, radius, 0];
+ }
}
+
+ // For multi-item stacks, only round the last bar in the stack.
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
+ if (isNegative) {
+ return [0, 0, radius, radius];
+ }
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
+ if (isNegative) {
+ return [radius, 0, 0, radius];
+ }
return [0, radius, radius, 0];
}
}
- // Middle of the stack
+ // First and middle bars of the stack have no rounding.
return [0, 0, 0, 0];
}
// Default or other variants
@@ -70,3 +82,41 @@ export const findNearestSnapPosition = (
return Math.min(snapPositions.length - 1, currentIndex + 1);
}
};
+
+export interface BarStackInfo {
+ isNegative: boolean;
+ isFirstInStack?: boolean;
+ isLastInStack?: boolean;
+ hasNegativeValueInStack?: boolean;
+}
+
+export function getBarStackInfo(
+ variant: "grouped" | "stacked",
+ value: number | [number, number],
+ dataKey: string,
+ payload: Record<string, unknown>,
+ dataKeys: string[],
+): BarStackInfo {
+ const isNegative = Array.isArray(value) ? value[0] <= 0 && value[1] < 0 : value < 0;
+
+ if (variant !== "stacked") {
+ return { isNegative };
+ }
+
+ const stackedKeys = dataKeys.filter((k) => typeof payload[k] === "number");
+ const positiveKeys = stackedKeys.filter((k) => (payload[k] as number) >= 0);
+ const negativeKeys = stackedKeys.filter((k) => (payload[k] as number) < 0);
+ const hasNegativeValueInStack = negativeKeys.length > 0;
+
+ const keys = isNegative ? negativeKeys : positiveKeys;
+ const currentIndex = keys.indexOf(dataKey);
+ const isFirstInStack = currentIndex === 0;
+ const isLastInStack = currentIndex === keys.length - 1;
+
+ return {
+ isNegative,
+ isFirstInStack,
+ isLastInStack,
+ hasNegativeValueInStack,
+ };
+}