Skip to content

The Open Standard for Generative UI

Svg tick fix (#227)

Ankit Das6564beb6e070
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 34e1ccc93..2a4fa7380 100644
--- a/js/packages/react-ui/src/components/Charts/AreaChartCondensed/AreaChartCondensed.tsx
+++ b/js/packages/react-ui/src/components/Charts/AreaChartCondensed/AreaChartCondensed.tsx
@@ -4,7 +4,7 @@ import { Area, AreaChart as RechartsAreaChart, XAxis, YAxis } from "recharts";
import { useId } from "../../../polyfills";
import { AreaChartData, AreaChartVariant } from "../AreaChart/types";
import { ChartConfig, ChartContainer, ChartTooltip } from "../Charts";
-import { X_AXIS_PADDING } from "../constants";
+import { DEFAULT_X_AXIS_HEIGHT, X_AXIS_PADDING } from "../constants";
import { SideBarChartData, SideBarTooltipProvider } from "../context/SideBarTooltipContext";
import {
useAutoAngleCalculation,
@@ -74,16 +74,32 @@ const AreaChartCondensedComponent = <T extends AreaChartData>({
const maxLabelWidth = useMaxLabelWidth(data, categoryKey as string);
+ const chartContainerRef = useRef<HTMLDivElement>(null);
+ const [chartContainerWidth, setChartContainerWidth] = useState<number>(0);
+
+ const widthOfData = useMemo(() => {
+ if (data.length === 0) {
+ return 0;
+ }
+ return chartContainerWidth / data.length;
+ }, [chartContainerWidth, data]);
+
const { angle: calculatedAngle, height: xAxisHeight } = useAutoAngleCalculation(
maxLabelWidth,
tickVariant === "angled",
+ // if the max label width is less than 100px, then we use the width of the data to calculate the angle, gives better results for small datasets
+ maxLabelWidth < 100 ? widthOfData : undefined,
);
+ const isAngled = useMemo(() => {
+ return calculatedAngle !== 0;
+ }, [calculatedAngle]);
+
const effectiveHeight = useMemo(() => {
if (tickVariant === "angled") {
return xAxisHeight + height;
}
- return height;
+ return height + DEFAULT_X_AXIS_HEIGHT;
}, [height, xAxisHeight, tickVariant]);
const transformedKeys = useTransformedKeys(dataKeys);
@@ -129,18 +145,24 @@ const AreaChartCondensedComponent = <T extends AreaChartData>({
// Observe container width for legend
useEffect(() => {
// Only set up ResizeObserver if width is not provided
- if (width || !containerRef.current) {
+ if (width || !containerRef.current || !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) {
- setContainerWidth(entry.contentRect.width);
+ if (entry.target === containerRef.current) {
+ setContainerWidth(entry.contentRect.width);
+ }
+ if (entry.target === chartContainerRef.current) {
+ setChartContainerWidth(entry.contentRect.width);
+ }
}
});
resizeObserver.observe(containerRef.current);
+ resizeObserver.observe(chartContainerRef.current);
return () => {
resizeObserver.disconnect();
@@ -232,7 +254,7 @@ const AreaChartCondensedComponent = <T extends AreaChartData>({
<div className="crayon-area-chart-condensed-container-inner" ref={containerRef}>
{/* Y-axis of the chart */}
{yAxis}
- <div className="crayon-area-chart-condensed">
+ <div className="crayon-area-chart-condensed" ref={chartContainerRef}>
<ChartContainer
config={chartConfig}
style={{ width: "100%", height: effectiveHeight }}
@@ -253,7 +275,7 @@ const AreaChartCondensedComponent = <T extends AreaChartData>({
dataKey={categoryKey as string}
tickLine={false}
axisLine={false}
- textAnchor={tickVariant === "angled" ? "end" : "middle"}
+ textAnchor={isAngled ? "end" : "middle"}
interval="preserveStartEnd"
minTickGap={5}
height={xAxisHeight}
diff --git a/js/packages/react-ui/src/components/Charts/AreaChartCondensed/stories/areaChartCondensed.stories.tsx b/js/packages/react-ui/src/components/Charts/AreaChartCondensed/stories/areaChartCondensed.stories.tsx
index 39f0d690e..e8454d44d 100644
--- a/js/packages/react-ui/src/components/Charts/AreaChartCondensed/stories/areaChartCondensed.stories.tsx
+++ b/js/packages/react-ui/src/components/Charts/AreaChartCondensed/stories/areaChartCondensed.stories.tsx
@@ -1,221 +1,269 @@
import type { Meta, StoryObj } from "@storybook/react";
-import { Calendar, Globe, Laptop, Monitor, Smartphone, TabletSmartphone } from "lucide-react";
+import {
+ Calendar,
+ Globe,
+ Laptop,
+ Monitor,
+ Smartphone,
+ TabletSmartphone,
+ Tv,
+ Watch,
+} from "lucide-react";
+import { useState } from "react";
import { Card } from "../../../Card";
import { AreaChartCondensed, AreaChartCondensedProps } from "../AreaChartCondensed";
-// Test Data Generators
-const generateLargeDataset = (points: number) => {
- return Array.from({ length: points }, (_, i) => ({
- date: `Day ${i + 1}`,
- value1: Math.floor(Math.random() * 1000) + 100,
- value2: Math.floor(Math.random() * 800) + 50,
- value3: Math.floor(Math.random() * 600) + 30,
- }));
-};
-
-const generateTimeSeriesData = (days: number) => {
- const startDate = new Date("2024-01-01");
- return Array.from({ length: days }, (_, i) => {
- const date = new Date(startDate);
- date.setDate(date.getDate() + i);
- return {
- date: date.toISOString().split("T")[0],
- sales: Math.floor(Math.random() * 5000) + 1000,
- orders: Math.floor(Math.random() * 200) + 50,
- };
- });
-};
-
-// Test Data Variations
-const testData = {
- // Edge Cases
- empty: [],
- singlePoint: [{ month: "Jan", value: 100 }],
- twoPoints: [
- { month: "Jan", value: 100 },
- { month: "Feb", value: 200 },
- ],
-
- // Small Datasets
- threePoints: [
- { month: "Jan", value: 100 },
- { month: "Feb", value: 150 },
- { month: "Mar", value: 120 },
- ],
- fivePoints: [
- { month: "Jan", desktop: 150, mobile: 90 },
- { month: "Feb", desktop: 280, mobile: 180 },
- { month: "Mar", desktop: 220, mobile: 140 },
- { month: "Apr", desktop: 180, mobile: 160 },
- { month: "May", desktop: 250, mobile: 120 },
- ],
-
- // Medium Datasets
- twelvePoints: [
- { month: "Jan", desktop: 150, mobile: 90, tablet: 120 },
- { month: "Feb", desktop: 280, mobile: 180, tablet: 140 },
- { month: "Mar", desktop: 220, mobile: 140, tablet: 160 },
- { month: "Apr", desktop: 180, mobile: 160, tablet: 180 },
+// πŸ”₯ COMPREHENSIVE DATA VARIATIONS - Designed to test various scenarios
+const dataVariations = {
+ default: [
+ { month: "January", desktop: 150, mobile: 90, tablet: 120 },
+ { month: "February", desktop: 280, mobile: 180, tablet: 140 },
+ { month: "March", desktop: 220, mobile: 140, tablet: 160 },
+ { month: "April", desktop: 180, mobile: 160, tablet: 180 },
{ month: "May", desktop: 250, mobile: 120, tablet: 140 },
- { month: "Jun", desktop: 300, mobile: 180, tablet: 160 },
- { month: "Jul", desktop: 320, mobile: 200, tablet: 180 },
- { month: "Aug", desktop: 290, mobile: 170, tablet: 150 },
- { month: "Sep", desktop: 310, mobile: 190, tablet: 170 },
- { month: "Oct", desktop: 280, mobile: 160, tablet: 140 },
- { month: "Nov", desktop: 350, mobile: 210, tablet: 190 },
- { month: "Dec", desktop: 400, mobile: 250, tablet: 220 },
- ],
-
- // Large Datasets
- large50: generateLargeDataset(50),
- large100: generateLargeDataset(100),
- large500: generateLargeDataset(500),
-
- // Special Value Cases
- allZeros: [
- { month: "Jan", value: 0 },
- { month: "Feb", value: 0 },
- { month: "Mar", value: 0 },
- { month: "Apr", value: 0 },
+ { month: "June", desktop: 300, mobile: 180, tablet: 160 },
+ { month: "July", desktop: 350, mobile: 220, tablet: 180 },
+ { month: "August", desktop: 400, mobile: 240, tablet: 200 },
+ { month: "September", desktop: 450, mobile: 260, tablet: 220 },
+ { month: "October", desktop: 500, mobile: 280, tablet: 240 },
+ { month: "November", desktop: 550, mobile: 300, tablet: 260 },
+ { month: "December", desktop: 600, mobile: 320, tablet: 280 },
],
- withZeros: [
- { month: "Jan", desktop: 100, mobile: 0 },
- { month: "Feb", desktop: 0, mobile: 50 },
- { month: "Mar", desktop: 150, mobile: 0 },
- { month: "Apr", desktop: 0, mobile: 100 },
+ // 🏷️ BIG LABELS - Testing angled tick labels
+ bigLabels: [
+ {
+ category: "Very Long Category Name That Should Be Truncated",
+ sales: 150,
+ revenue: 90,
+ profit: 120,
+ },
+ {
+ category: "Another Extremely Long Label That Causes Collisions",
+ sales: 280,
+ revenue: 180,
+ profit: 140,
+ },
+ {
+ category: "Super Duper Long Category Name That Tests Truncation",
+ sales: 220,
+ revenue: 140,
+ profit: 160,
+ },
+ {
+ category: "Incredibly Long Text That Should Trigger Collision Detection",
+ sales: 180,
+ revenue: 160,
+ profit: 180,
+ },
+ {
+ category: "Maximum Length Category Name That Tests All Edge Cases",
+ sales: 250,
+ revenue: 120,
+ profit: 140,
+ },
+ {
+ category: "Extra Long Business Category Name With Many Words",
+ sales: 300,
+ revenue: 180,
+ profit: 160,
+ },
+ {
+ category: "Comprehensive Long Label For Testing Horizontal Offset",
+ sales: 350,
+ revenue: 220,
+ profit: 180,
+ },
+ {
+ category: "Extended Category Name That Pushes Truncation Limits",
+ sales: 400,
+ revenue: 240,
+ profit: 200,
+ },
],
- negativeValues: [
- { month: "Jan", profit: -50, loss: -30 },
- { month: "Feb", profit: 100, loss: -20 },
- { month: "Mar", profit: -30, loss: -40 },
- { month: "Apr", profit: 150, loss: -10 },
+ // πŸ“… DENSE TIMELINE - Many items with medium-length labels
+ denseTimeline: [
+ { period: "Q1 2022 Jan-Mar", visitors: 120, conversions: 15, revenue: 1200 },
+ { period: "Q1 2022 Apr-Jun", visitors: 150, conversions: 22, revenue: 1800 },
+ { period: "Q2 2022 Jul-Sep", visitors: 180, conversions: 28, revenue: 2100 },
+ { period: "Q2 2022 Oct-Dec", visitors: 200, conversions: 35, revenue: 2500 },
+ { period: "Q3 2023 Jan-Mar", visitors: 160, conversions: 18, revenue: 1600 },
+ { period: "Q3 2023 Apr-Jun", visitors: 190, conversions: 32, revenue: 2300 },
+ { period: "Q4 2023 Jul-Sep", visitors: 220, conversions: 40, revenue: 2800 },
+ { period: "Q4 2023 Oct-Dec", visitors: 240, conversions: 45, revenue: 3200 },
+ { period: "Q1 2024 Jan-Mar", visitors: 210, conversions: 38, revenue: 2700 },
+ { period: "Q1 2024 Apr-Jun", visitors: 230, conversions: 42, revenue: 3000 },
+ { period: "Q2 2024 Jul-Sep", visitors: 250, conversions: 48, revenue: 3400 },
+ { period: "Q2 2024 Oct-Dec", visitors: 270, conversions: 52, revenue: 3800 },
+ { period: "Q3 2024 Jan-Mar", visitors: 260, conversions: 50, revenue: 3600 },
+ { period: "Q3 2024 Apr-Jun", visitors: 280, conversions: 55, revenue: 4000 },
+ { period: "Q4 2024 Jul-Sep", visitors: 300, conversions: 60, revenue: 4300 },
+ { period: "Q4 2024 Oct-Dec", visitors: 290, conversions: 58, revenue: 4100 },
],
- mixedValues: [
- { month: "Jan", value1: -100, value2: 200 },
- { month: "Feb", value1: 150, value2: -50 },
- { month: "Mar", value1: -75, value2: 300 },
- { month: "Apr", value1: 200, value2: -100 },
+ // 🏒 COMPANY NAMES - Real-world long business names
+ companyNames: [
+ { company: "Apple Inc.", revenue: 394328000000, profit: 99803000000, marketCap: 3500000000000 },
+ {
+ company: "Microsoft Corporation",
+ revenue: 211915000000,
+ profit: 83383000000,
+ marketCap: 2800000000000,
+ },
+ {
+ company: "Alphabet Inc. (Google)",
+ revenue: 307394000000,
+ profit: 76033000000,
+ marketCap: 2100000000000,
+ },
+ {
+ company: "Amazon.com Inc.",
+ revenue: 574785000000,
+ profit: 33364000000,
+ marketCap: 1600000000000,
+ },
+ {
+ company: "Tesla Motors Inc.",
+ revenue: 96773000000,
+ profit: 15000000000,
+ marketCap: 800000000000,
+ },
+ {
+ company: "Meta Platforms Inc.",
+ revenue: 134902000000,
+ profit: 39370000000,
+ marketCap: 900000000000,
+ },
+ {
+ company: "NVIDIA Corporation",
+ revenue: 60922000000,
+ profit: 29760000000,
+ marketCap: 1800000000000,
+ },
+ {
+ company: "Berkshire Hathaway Inc.",
+ revenue: 364482000000,
+ profit: 96223000000,
+ marketCap: 780000000000,
+ },
],
-
- // Extreme Values
- veryLarge: [
- { month: "Jan", value: 1000000, secondary: 500000 },
- { month: "Feb", value: 1500000, secondary: 750000 },
- { month: "Mar", value: 1200000, secondary: 600000 },
+ // 🌍 COUNTRY NAMES - Geographic labels with varying lengths
+ countryData: [
+ { country: "United States of America", population: 331900000, gdp: 26900000000000 },
+ { country: "People's Republic of China", population: 1412000000, gdp: 17700000000000 },
+ { country: "Federal Republic of Germany", population: 83200000, gdp: 4300000000000 },
+ { country: "United Kingdom of Great Britain", population: 67500000, gdp: 3100000000000 },
+ { country: "French Republic", population: 68000000, gdp: 2900000000000 },
+ { country: "Republic of India", population: 1380000000, gdp: 3700000000000 },
+ { country: "Federative Republic of Brazil", population: 215000000, gdp: 2100000000000 },
+ { country: "Russian Federation", population: 146000000, gdp: 1800000000000 },
],
- verySmall: [
- { month: "Jan", value: 0.001, secondary: 0.002 },
- { month: "Feb", value: 0.003, secondary: 0.0015 },
- { month: "Mar", value: 0.002, secondary: 0.0025 },
+ // πŸ“ˆ FINANCIAL QUARTERS - Testing medium-density scenarios
+ financialQuarters: [
+ { quarter: "Q1 FY2022", revenue: 1200000, expenses: 800000, profit: 400000 },
+ { quarter: "Q2 FY2022", revenue: 1500000, expenses: 950000, profit: 550000 },
+ { quarter: "Q3 FY2022", revenue: 1800000, expenses: 1100000, profit: 700000 },
+ { quarter: "Q4 FY2022", revenue: 2000000, expenses: 1300000, profit: 700000 },
+ { quarter: "Q1 FY2023", revenue: 2200000, expenses: 1400000, profit: 800000 },
+ { quarter: "Q2 FY2023", revenue: 2500000, expenses: 1600000, profit: 900000 },
+ { quarter: "Q3 FY2023", revenue: 2800000, expenses: 1800000, profit: 1000000 },
+ { quarter: "Q4 FY2023", revenue: 3000000, expenses: 1900000, profit: 1100000 },
],
- wideRange: [
- { month: "Jan", small: 1, large: 1000000 },
- { month: "Feb", small: 2, large: 1500000 },
- { month: "Mar", small: 1.5, large: 1200000 },
+ // πŸ”€ MIXED LENGTHS - Testing various label length scenarios
+ mixedLengths: [
+ { item: "A", valueA: 100, valueB: 80 },
+ { item: "Short", valueA: 150, valueB: 120 },
+ { item: "Medium Length Item", valueA: 200, valueB: 160 },
+ { item: "Very Long Item Name That Tests Truncation", valueA: 250, valueB: 200 },
+ { item: "B", valueA: 180, valueB: 140 },
+ { item: "Another Really Long Category Name", valueA: 220, valueB: 180 },
+ { item: "XL", valueA: 190, valueB: 150 },
],
-
- // Pattern Tests
- linear: Array.from({ length: 10 }, (_, i) => ({
- x: `P${i + 1}`,
- y: i * 10,
- })),
- exponential: Array.from({ length: 10 }, (_, i) => ({
- x: `P${i + 1}`,
- y: Math.pow(2, i),
- })),
- sinusoidal: Array.from({ length: 20 }, (_, i) => ({
- x: `P${i + 1}`,
- y: Math.sin(i / 3) * 100 + 150,
- })),
- constant: Array.from({ length: 8 }, (_, i) => ({
- x: `P${i + 1}`,
- y: 100,
- })),
- volatile: Array.from({ length: 15 }, (_, i) => ({
- x: `P${i + 1}`,
- spike: i % 3 === 0 ? 500 : 50,
- normal: 100 + Math.random() * 20,
- })),
-
- // Real-world Scenarios
- dailySales: generateTimeSeriesData(30),
- quarterlySales: [
- { quarter: "Q1 2023", revenue: 12000, profit: 4000, costs: 8000 },
- { quarter: "Q2 2023", revenue: 15000, profit: 5500, costs: 9500 },
- { quarter: "Q3 2023", revenue: 18000, profit: 7000, costs: 11000 },
- { quarter: "Q4 2023", revenue: 20000, profit: 7000, costs: 13000 },
- { quarter: "Q1 2024", revenue: 22000, profit: 8000, costs: 14000 },
+ // 🎯 EDGE CASES - Extreme scenarios
+ edgeCases: [
+ {
+ name: "SinglePointDataSetForTestingEdgeCasesInCollisionDetectionAndLabelTruncationFunctionality",
+ value: 500,
+ },
+ {
+ name: "SecondExtremelyLongDataPointNameThatShouldDefinitelyTriggerTruncationMechanisms",
+ value: 600,
+ },
],
- weeklyTraffic: [
- { day: "Mon", visits: 2200, conversions: 180, bounces: 800 },
- { day: "Tue", visits: 2500, conversions: 220, bounces: 900 },
- { day: "Wed", visits: 2300, conversions: 190, bounces: 850 },
- { day: "Thu", visits: 2800, conversions: 250, bounces: 1000 },
- { day: "Fri", visits: 3200, conversions: 280, bounces: 1100 },
- { day: "Sat", visits: 1800, conversions: 120, bounces: 600 },
- { day: "Sun", visits: 1500, conversions: 100, bounces: 500 },
+ // πŸ“± MINIMAL - Small dataset for baseline testing
+ minimal: [
+ { category: "Mobile Devices", users: 150, sessions: 90 },
+ { category: "Desktop Computers", users: 280, sessions: 180 },
+ { category: "Tablet Devices", users: 220, sessions: 140 },
],
};
+// Category key mappings for different datasets
+const categoryKeys = {
+ default: "month",
+ bigLabels: "category",
+ denseTimeline: "period",
+ companyNames: "company",
+ countryData: "country",
+ financialQuarters: "quarter",
+ mixedLengths: "item",
+ edgeCases: "name",
+ minimal: "category",
+};
+
+// πŸ”₯ ACTIVE DATA - For backward compatibility
+const areaChartCondensedData = dataVariations.default;
+
const icons = {
desktop: Monitor,
mobile: TabletSmartphone,
tablet: Calendar,
- revenue: Globe,
- profit: Smartphone,
- visits: Monitor,
- conversions: Laptop,
- value: Monitor,
- value1: Monitor,
- value2: TabletSmartphone,
- value3: Calendar,
- small: Smartphone,
- large: Globe,
sales: Globe,
- orders: Laptop,
- bounces: Calendar,
- costs: Smartphone,
+ revenue: Smartphone,
+ profit: Laptop,
+ visitors: Tv,
+ conversions: Watch,
+ users: Monitor,
+ sessions: TabletSmartphone,
+ expenses: Calendar,
+ marketCap: Globe,
+ population: Monitor,
+ gdp: Smartphone,
+ valueA: Monitor,
+ valueB: TabletSmartphone,
+ value: Calendar,
} as const;
/**
- * # AreaChartCondensed Test Suite
+ * # AreaChartCondensed Component Documentation
*
- * This file contains comprehensive test cases for the AreaChartCondensed component,
- * covering edge cases, data variations, and stress testing scenarios.
+ * The AreaChartCondensed is a compact version of AreaChart, designed for space-constrained layouts
+ * like dashboards and sidebars. It's ideal for:
*
- * ## Test Categories
+ * - **Compact Dashboards**: Showing multiple metrics in limited space
+ * - **Sidebar Analytics**: Quick trend visualization without taking up too much room
+ * - **Dense Data Display**: Efficiently showing many data points in a small area
*
- * ### 1. Edge Cases
- * - Empty data
- * - Single data point
- * - Two data points (minimum for area)
+ * ## Key Features
*
- * ### 2. Data Size Variations
- * - Small datasets (3-5 points)
- * - Medium datasets (10-20 points)
- * - Large datasets (50-500 points)
+ * ### Space-Efficient Design
+ * - **Compact Height**: Default 200px height for tight layouts
+ * - **Minimal Legend**: Legend is compact and doesn't take up vertical space
+ * - **Adjustable Tick Variants**: Choose between horizontal or angled labels for better space usage
*
- * ### 3. Value Ranges
- * - Zero values
- * - Negative values
- * - Mixed positive/negative
- * - Very large numbers (millions)
- * - Very small decimals
- * - Wide value ranges
+ * ### Flexible Label Handling
+ * - **Single Line Ticks**: Horizontal labels with automatic collision detection
+ * - **Angled Ticks**: -45Β° rotation for longer labels that need more space
+ * - **Smart Angle Calculation**: Automatically calculates optimal rotation based on label width
*
- * ### 4. Data Patterns
- * - Linear progression
- * - Exponential growth
- * - Sinusoidal waves
- * - Constant values
- * - Volatile/spike patterns
+ * ### Interactive & Responsive
+ * - **Hover Tooltips**: Standard tooltip showing all data series
+ * - **Responsive Design**: Adapts fluidly to its container's size
*
- * ### 5. Real-world Scenarios
- * - Time series data
- * - Financial data
- * - Traffic analytics
+ * ### Customization
+ * - **Theming**: Comes with six pre-built color palettes
+ * - **Area Styles**: Supports `linear`, `natural` (smooth), and `step` interpolation
+ * - **Styling Options**: Control grid visibility, axes, and more
*/
-const meta: Meta<AreaChartCondensedProps<any>> = {
+const meta: Meta<AreaChartCondensedProps<typeof areaChartCondensedData>> = {
title: "Components/Charts/AreaChartCondensed",
component: AreaChartCondensed,
parameters: {
@@ -223,43 +271,63 @@ const meta: Meta<AreaChartCondensedProps<any>> = {
docs: {
description: {
component: `
-## Test Suite Overview
+## Installation and Basic Usage
-This comprehensive test suite validates the AreaChartCondensed component across various scenarios:
-
-### Test Coverage Areas
-
-1. **Edge Cases**: Empty data, single point, minimal data
-2. **Data Size**: Small (3-5), Medium (10-20), Large (50-500+) datasets
-3. **Value Ranges**: Zeros, negatives, extremes (millions to decimals)
-4. **Data Patterns**: Linear, exponential, sinusoidal, constant, volatile
-5. **Real-world**: Time series, financial, analytics data
-
-### How to Use This Test Suite
+\`\`\`tsx
+import { AreaChartCondensed } from '@crayonai/react-ui/Charts/AreaChartCondensed';
-Each story represents a specific test case. Use these to:
-- Verify component behavior with different data types
-- Check rendering performance with large datasets
-- Validate handling of edge cases
-- Ensure visual consistency across variations
+const trafficData = [
+ { date: "2023-01-01", visits: 2200 },
+ { date: "2023-01-02", visits: 2500 },
+ { date: "2023-01-03", visits: 2300 },
+];
-\`\`\`tsx
-// Example: Testing with large dataset
+// Basic implementation
<AreaChartCondensed
- data={testData.large100}
+ data={trafficData}
categoryKey="date"
theme="ocean"
height={200}
/>
\`\`\`
+
+## Data Structure Requirements
+
+Your data should be an array of objects. Each object must contain:
+- A **category field** (string or number): This will be used for the X-axis labels (e.g., dates, names, etc.).
+- One or more **data series fields** (number): These are the values that will be plotted on the Y-axis.
+
+\`\`\`tsx
+const salesData = [
+ { month: "January", desktop: 150, mobile: 90 },
+ { month: "February", desktop: 280, mobile: 180 },
+ { month: "March", desktop: 220, mobile: 140 },
+];
+\`\`\`
+
+## Key Differences from AreaChart
+
+- **Compact**: Designed for smaller spaces with a default height of 200px
+- **No Interactive Legend**: Legend is simplified and non-interactive
+- **Tick Variants**: Supports both horizontal (singleLine) and angled labels
+- **Performance**: Optimized for quick rendering in dashboards
+
+## Performance Considerations
+- **Data Density**: For very large datasets, consider disabling animations
+- **Responsiveness**: The chart is fully responsive, but test label visibility on small screens
+- **Animation**: Controlled via \`isAnimationActive={false}\`
`,
},
},
},
- tags: ["dev", "autodocs"],
+ tags: ["!dev", "autodocs"],
argTypes: {
data: {
- description: "Array of data objects for the chart. Same format as AreaChart.",
+ description: `
+**Required.** An array of data objects for the area chart. Each object should contain:
+- A category identifier (string/number) for the X-axis.
+- One or more numeric values for the Y-axis.
+`,
control: false,
table: {
type: { summary: "Array<Record<string, string | number>>" },
@@ -267,7 +335,8 @@ Each story represents a specific test case. Use these to:
},
},
categoryKey: {
- description: "The key in your data object for the X-axis category.",
+ description:
+ "**Required.** The key in your data object that represents the category for the X-axis.",
control: false,
table: {
type: { summary: "string" },
@@ -275,7 +344,8 @@ Each story represents a specific test case. Use these to:
},
},
theme: {
- description: "Color palette for the chart. Ignored when customPalette is provided.",
+ description:
+ "Specifies the color palette for the chart's areas and tooltips. Ignored when customPalette is provided.",
control: "select",
options: ["ocean", "orchid", "emerald", "sunset", "spectrum", "vivid"],
table: {
@@ -284,7 +354,8 @@ Each story represents a specific test case. Use these to:
},
},
customPalette: {
- description: "Custom color array. Overrides theme when provided.",
+ description:
+ "Custom array of colors to use instead of the theme palette. Overrides the theme prop when provided.",
control: "object",
table: {
type: { summary: "string[]" },
@@ -292,7 +363,7 @@ Each story represents a specific test case. Use these to:
},
},
variant: {
- description: "Area interpolation method.",
+ description: "Determines the area interpolation method, affecting the shape of the curves.",
control: "radio",
options: ["linear", "natural", "step"],
table: {
@@ -302,7 +373,7 @@ Each story represents a specific test case. Use these to:
},
tickVariant: {
description:
- "X-axis tick label style. Choose between singleLine (horizontal) or angled (-45Β°).",
+ "X-axis tick label style. Choose between 'singleLine' (horizontal) or 'angled' (rotated at optimal angle).",
control: "radio",
options: ["singleLine", "angled"],
table: {
@@ -310,8 +381,17 @@ Each story represents a specific test case. Use these to:
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: "Show or hide grid lines.",
+ description: "Toggles the visibility of the background grid lines.",
control: "boolean",
table: {
defaultValue: { summary: "true" },
@@ -319,23 +399,39 @@ Each story represents a specific test case. Use these to:
},
},
showYAxis: {
- description: "Show or hide Y-axis.",
+ description: "Toggles the visibility of the Y-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: "Enable loading animation.",
+ description: "Enables or disables the initial loading animation for the areas.",
control: "boolean",
table: {
defaultValue: { summary: "false" },
- category: "🎬 Animation",
+ category: "🎬 Animation & Interaction",
},
},
height: {
- description: "Chart height in pixels.",
+ description: "Sets a fixed height for the chart container in pixels.",
control: "number",
table: {
defaultValue: { summary: "200" },
@@ -344,7 +440,7 @@ Each story represents a specific test case. Use these to:
},
},
width: {
- description: "Chart width in pixels. Defaults to 100% of container.",
+ description: "Sets a fixed width for the chart container in pixels.",
control: "number",
table: {
type: { summary: "number" },
@@ -352,7 +448,7 @@ Each story represents a specific test case. Use these to:
},
},
className: {
- description: "Custom CSS class for the container.",
+ description: "Custom CSS class to apply to the chart's container.",
control: "text",
table: {
type: { summary: "string" },
@@ -365,704 +461,475 @@ Each story represents a specific test case. Use these to:
export default meta;
type Story = StoryObj<typeof meta>;
-// ============================================================================
-// EDGE CASES - Testing component behavior with minimal/unusual data
-// ============================================================================
-
/**
- * ## TEST: Empty Data
+ * ## Comprehensive Data Explorer
*
- * **Purpose**: Verify component handles empty array gracefully
- * **Expected**: Should render without errors, show empty state or message
- */
-export const EdgeCase_EmptyData: Story = {
- args: {
- data: testData.empty as any,
- categoryKey: "month" as any,
- theme: "ocean",
- height: 200,
- },
- render: (args: any) => (
- <Card style={{ width: "500px", padding: "16px" }}>
- <div style={{ marginBottom: "8px", fontSize: "12px", color: "#666" }}>
- <strong>Test:</strong> Empty dataset | <strong>Data points:</strong> 0
- </div>
- <AreaChartCondensed {...args} />
- </Card>
- ),
-};
-
-/**
- * ## TEST: Single Data Point
+ * This story serves as a comprehensive test suite for the AreaChartCondensed component.
+ * Use the buttons to switch between various datasets designed to test edge cases in:
*
- * **Purpose**: Verify rendering with only one data point
- * **Expected**: Should render single point, may not show area
+ * - **Label Handling**: Datasets with long, dense, or overlapping labels.
+ * - **Data Density**: Scenarios with few or many data points.
+ * - **Tick Variants**: Toggle between horizontal and angled label orientations.
+ *
+ * It's an excellent tool for developers to see how the chart behaves under different conditions.
*/
-export const EdgeCase_SinglePoint: Story = {
+export const DataExplorer: Story = {
+ name: "πŸŽ›οΈ Comprehensive Data Explorer",
args: {
- data: testData.singlePoint as any,
- categoryKey: "month" as any,
+ data: areaChartCondensedData,
+ categoryKey: "month",
theme: "ocean",
+ variant: "natural",
+ tickVariant: "singleLine",
+ grid: true,
+ isAnimationActive: false,
+ showYAxis: true,
+ xAxisLabel: "Time Period",
+ yAxisLabel: "Values",
height: 200,
},
- render: (args: any) => (
- <Card style={{ width: "500px", padding: "16px" }}>
- <div style={{ marginBottom: "8px", fontSize: "12px", color: "#666" }}>
- <strong>Test:</strong> Single point | <strong>Data points:</strong> 1
+ render: (args: any) => {
+ const [selectedDataType, setSelectedDataType] =
+ useState<keyof typeof dataVariations>("default");
+ const [tickVariant, setTickVariant] = useState<"singleLine" | "angled">("singleLine");
+
+ 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",
+ fontFamily: "monospace",
+ };
+
+ 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: "600px",
+ }}
+ >
+ <strong>🏷️ Dataset Selection:</strong>
+ <div style={{ marginTop: "8px", display: "flex", flexWrap: "wrap", gap: "4px" }}>
+ <button
+ onClick={() => setSelectedDataType("default")}
+ style={selectedDataType === "default" ? activeButtonStyle : buttonStyle}
+ >
+ πŸ“… Default (12 months)
+ </button>
+ <button
+ onClick={() => setSelectedDataType("bigLabels")}
+ style={selectedDataType === "bigLabels" ? activeButtonStyle : buttonStyle}
+ >
+ 🏷️ Big Labels
+ </button>
+ <button
+ onClick={() => setSelectedDataType("denseTimeline")}
+ style={selectedDataType === "denseTimeline" ? activeButtonStyle : buttonStyle}
+ >
+ πŸ“… Dense Timeline (16)
+ </button>
+ <button
+ onClick={() => setSelectedDataType("companyNames")}
+ style={selectedDataType === "companyNames" ? activeButtonStyle : buttonStyle}
+ >
+ 🏒 Company Names
+ </button>
+ <button
+ onClick={() => setSelectedDataType("countryData")}
+ style={selectedDataType === "countryData" ? activeButtonStyle : buttonStyle}
+ >
+ 🌍 Country Names
+ </button>
+ <button
+ onClick={() => setSelectedDataType("financialQuarters")}
+ style={selectedDataType === "financialQuarters" ? activeButtonStyle : buttonStyle}
+ >
+ πŸ“ˆ Financial Quarters
+ </button>
+ <button
+ onClick={() => setSelectedDataType("mixedLengths")}
+ style={selectedDataType === "mixedLengths" ? activeButtonStyle : buttonStyle}
+ >
+ πŸ”€ Mixed Lengths
+ </button>
+ <button
+ onClick={() => setSelectedDataType("edgeCases")}
+ style={selectedDataType === "edgeCases" ? activeButtonStyle : buttonStyle}
+ >
+ 🎯 Edge Cases
+ </button>
+ <button
+ onClick={() => setSelectedDataType("minimal")}
+ style={selectedDataType === "minimal" ? activeButtonStyle : buttonStyle}
+ >
+ πŸ“± Minimal (3 items)
+ </button>
+ </div>
+ <div style={{ marginTop: "12px" }}>
+ <strong>πŸ“ Tick Variant:</strong>
+ <div style={{ marginTop: "8px", display: "flex", gap: "4px" }}>
+ <button
+ onClick={() => setTickVariant("singleLine")}
+ style={tickVariant === "singleLine" ? activeButtonStyle : buttonStyle}
+ >
+ Horizontal Labels
+ </button>
+ <button
+ onClick={() => setTickVariant("angled")}
+ style={tickVariant === "angled" ? activeButtonStyle : buttonStyle}
+ >
+ Angled Labels
+ </button>
+ </div>
+ </div>
+ <div
+ style={{ marginTop: "12px", fontSize: "12px", color: "#666", fontFamily: "monospace" }}
+ >
+ <div>
+ <strong>Current Dataset:</strong> {selectedDataType}
+ </div>
+ <div>
+ <strong>Items:</strong> {currentData.length} | <strong>Category Key:</strong>{" "}
+ {currentCategoryKey} | <strong>Tick:</strong> {tickVariant}
+ </div>
+ </div>
+ </div>
+ <Card style={{ width: "600px" }}>
+ <AreaChartCondensed
+ {...args}
+ data={currentData}
+ categoryKey={currentCategoryKey}
+ tickVariant={tickVariant}
+ />
+ </Card>
</div>
- <AreaChartCondensed {...args} />
- </Card>
- ),
+ );
+ },
+ parameters: {
+ docs: {
+ description: {
+ story:
+ "**πŸŽ›οΈ Interactive Explorer:** This story allows you to explore different datasets and tick variants interactively. Use the buttons to switch between:\n\n**Datasets:**\n- **Default**: Standard 12-month data\n- **Big Labels**: Extremely long category names\n- **Dense Timeline**: Many items with medium-length labels\n- **Company Names**: Real-world business names\n- **Country Names**: Geographic labels\n- **Financial Quarters**: Quarterly financial data\n- **Mixed Lengths**: Combination of short and long labels\n- **Edge Cases**: Extreme scenarios\n- **Minimal**: Baseline with 3 items\n\n**Tick Variants:**\n- **Horizontal Labels**: Standard single-line labels with collision detection\n- **Angled Labels**: Rotated labels for better space utilization",
+ },
+ },
+ },
};
/**
- * ## TEST: Two Data Points
+ * ## Big Labels
*
- * **Purpose**: Minimum data to show an area (edge case)
- * **Expected**: Should show basic area between two points
+ * This story demonstrates the chart's ability to handle very long category labels.
+ * The angled tick variant is particularly useful here for preventing label overlap.
*/
-export const EdgeCase_TwoPoints: Story = {
+export const BigLabelsStory: Story = {
+ name: "🏷️ Big Labels (Angled Ticks)",
args: {
- data: testData.twoPoints as any,
- categoryKey: "month" as any,
+ data: dataVariations.bigLabels as any,
+ categoryKey: "category" as any,
theme: "emerald",
- height: 200,
+ variant: "natural",
+ tickVariant: "angled",
+ grid: true,
+ isAnimationActive: false,
+ showYAxis: true,
+ height: 250,
},
render: (args: any) => (
- <Card style={{ width: "500px", padding: "16px" }}>
- <div style={{ marginBottom: "8px", fontSize: "12px", color: "#666" }}>
- <strong>Test:</strong> Two points (minimum area) | <strong>Data points:</strong> 2
- </div>
+ <Card style={{ width: "700px" }}>
<AreaChartCondensed {...args} />
</Card>
),
-};
-
-// ============================================================================
-// DATA SIZE TESTS - Testing performance with different dataset sizes
-// ============================================================================
-
-/**
- * ## TEST: Small Dataset (3 points)
- *
- * **Purpose**: Verify rendering with minimal but valid data
- * **Expected**: Clean rendering, good spacing
- */
-export const DataSize_Small3Points: Story = {
- args: {
- data: testData.threePoints as any,
- categoryKey: "month" as any,
- theme: "ocean",
- height: 200,
+ parameters: {
+ docs: {
+ description: {
+ story:
+ "Tests the chart with extremely long category names. The angled tick variant automatically rotates labels at an optimal angle to prevent overlapping and maximize readability.",
+ },
+ },
},
- render: (args: any) => (
- <Card style={{ width: "400px", padding: "16px" }}>
- <div style={{ marginBottom: "8px", fontSize: "12px", color: "#666" }}>
- <strong>Test:</strong> Small dataset | <strong>Data points:</strong> 3
- </div>
- <AreaChartCondensed {...args} />
- </Card>
- ),
};
/**
- * ## TEST: Small Dataset (5 points, multiple series)
+ * ## Dense Timeline
*
- * **Purpose**: Test small data with multiple data series
- * **Expected**: All series visible, good color differentiation
+ * Tests how the chart handles many data points with medium-length period labels.
+ * The angled tick variant helps display more labels without collision.
*/
-export const DataSize_Small5Points: Story = {
+export const DenseTimelineStory: Story = {
+ name: "πŸ“… Dense Timeline (Many Periods)",
args: {
- data: testData.fivePoints as any,
- categoryKey: "month" as any,
+ data: dataVariations.denseTimeline as any,
+ categoryKey: "period" as any,
theme: "sunset",
- icons,
- height: 200,
+ variant: "natural",
+ tickVariant: "angled",
+ grid: true,
+ isAnimationActive: false,
+ showYAxis: true,
+ height: 250,
},
render: (args: any) => (
- <Card style={{ width: "450px", padding: "16px" }}>
- <div style={{ marginBottom: "8px", fontSize: "12px", color: "#666" }}>
- <strong>Test:</strong> Small dataset, 2 series | <strong>Data points:</strong> 5
- </div>
+ <Card style={{ width: "700px" }}>
<AreaChartCondensed {...args} />
</Card>
),
-};
-
-/**
- * ## TEST: Medium Dataset (12 points, 3 series)
- *
- * **Purpose**: Standard use case with monthly data
- * **Expected**: Clean rendering, all points visible
- */
-export const DataSize_Medium12Points: Story = {
- args: {
- data: testData.twelvePoints as any,
- categoryKey: "month" as any,
- theme: "orchid",
- icons,
- height: 200,
+ parameters: {
+ docs: {
+ description: {
+ story:
+ "Tests how the chart handles many data points (16 periods) with medium-length labels. The angled tick variant provides better label visibility compared to horizontal labels.",
+ },
+ },
},
- render: (args: any) => (
- <Card style={{ width: "600px", padding: "16px" }}>
- <div style={{ marginBottom: "8px", fontSize: "12px", color: "#666" }}>
- <strong>Test:</strong> Medium dataset, 3 series | <strong>Data points:</strong> 12
- </div>
- <AreaChartCondensed {...args} />
- </Card>
- ),
};
/**
- * ## TEST: Large Dataset (50 points)
+ * ## Company Names
*
- * **Purpose**: Test performance with larger dataset
- * **Expected**: Should handle smoothly, may need scrolling or compression
+ * This story tests the chart with real-world company names that have varying lengths.
+ * It demonstrates how the chart handles business data with naturally occurring long labels.
*/
-export const DataSize_Large50Points: Story = {
+export const CompanyNamesStory: Story = {
+ name: "🏒 Company Names (Real-world Labels)",
args: {
- data: testData.large50 as any,
- categoryKey: "date" as any,
- theme: "emerald",
+ data: dataVariations.companyNames as any,
+ categoryKey: "company" as any,
+ theme: "vivid",
+ variant: "natural",
+ tickVariant: "angled",
+ grid: true,
+ isAnimationActive: false,
+ showYAxis: true,
height: 250,
},
render: (args: any) => (
- <Card style={{ width: "700px", padding: "16px" }}>
- <div style={{ marginBottom: "8px", fontSize: "12px", color: "#666" }}>
- <strong>Test:</strong> Large dataset, 3 series | <strong>Data points:</strong> 50
- </div>
+ <Card style={{ width: "700px" }}>
<AreaChartCondensed {...args} />
</Card>
),
+ parameters: {
+ docs: {
+ description: {
+ story:
+ "Tests with real-world company names that have varying lengths. Demonstrates how the chart handles business data with naturally occurring long labels.",
+ },
+ },
+ },
};
/**
- * ## TEST: Large Dataset (100 points)
+ * ## Country Names
*
- * **Purpose**: Stress test rendering performance
- * **Expected**: Chart should remain responsive
+ * This story tests the chart with official country names, which are often long.
+ * It shows how geographic data is handled by the angled tick system.
*/
-export const DataSize_Large100Points: Story = {
+export const CountryDataStory: Story = {
+ name: "🌍 Country Names (Geographic Labels)",
args: {
- data: testData.large100 as any,
- categoryKey: "date" as any,
- theme: "vivid",
+ data: dataVariations.countryData as any,
+ categoryKey: "country" as any,
+ theme: "orchid",
+ variant: "natural",
+ tickVariant: "angled",
+ grid: true,
+ isAnimationActive: false,
+ showYAxis: true,
height: 250,
},
render: (args: any) => (
- <Card style={{ width: "800px", padding: "16px" }}>
- <div style={{ marginBottom: "8px", fontSize: "12px", color: "#666" }}>
- <strong>Test:</strong> Large dataset, 3 series | <strong>Data points:</strong> 100
- </div>
+ <Card style={{ width: "700px" }}>
<AreaChartCondensed {...args} />
</Card>
),
+ parameters: {
+ docs: {
+ description: {
+ story:
+ "Tests with official country names that include full formal names. Shows how geographic data with naturally long names is handled.",
+ },
+ },
+ },
};
/**
- * ## TEST: Very Large Dataset (500 points)
+ * ## Mixed Lengths
*
- * **Purpose**: Maximum stress test for performance
- * **Expected**: Should handle without crashing, check render time
+ * This story tests the chart's ability to handle a mix of very short and very long labels
+ * within the same dataset, demonstrating its adaptive behavior.
*/
-export const DataSize_VeryLarge500Points: Story = {
+export const MixedLengthsStory: Story = {
+ name: "πŸ”€ Mixed Lengths (Varied Label Sizes)",
args: {
- data: testData.large500 as any,
- categoryKey: "date" as any,
+ data: dataVariations.mixedLengths as any,
+ categoryKey: "item" as any,
theme: "spectrum",
- height: 300,
+ variant: "linear",
+ tickVariant: "singleLine",
+ grid: true,
+ isAnimationActive: false,
showYAxis: true,
+ height: 200,
},
render: (args: any) => (
- <Card style={{ width: "1000px", padding: "16px" }}>
- <div style={{ marginBottom: "8px", fontSize: "12px", color: "#666" }}>
- <strong>⚠️ Stress Test:</strong> Very large dataset | <strong>Data points:</strong> 500
- </div>
+ <Card style={{ width: "500px" }}>
<AreaChartCondensed {...args} />
</Card>
),
+ parameters: {
+ docs: {
+ description: {
+ story:
+ "Tests the chart's ability to handle a mix of very short and very long labels within the same dataset.",
+ },
+ },
+ },
};
-// ============================================================================
-// VALUE RANGE TESTS - Testing different value types and ranges
-// ============================================================================
-
/**
- * ## TEST: All Zero Values
+ * ## Edge Cases
*
- * **Purpose**: Verify behavior when all values are zero
- * **Expected**: Should show flat line at zero
+ * This story tests extreme edge cases with exceptionally long labels and minimal data points.
*/
-export const ValueRange_AllZeros: Story = {
+export const EdgeCasesStory: Story = {
+ name: "🎯 Edge Cases (Extreme Scenarios)",
args: {
- data: testData.allZeros as any,
- categoryKey: "month" as any,
+ data: dataVariations.edgeCases as any,
+ categoryKey: "name" as any,
theme: "ocean",
- height: 200,
+ variant: "step",
+ tickVariant: "angled",
+ grid: true,
+ isAnimationActive: false,
+ showYAxis: true,
+ height: 250,
},
render: (args: any) => (
- <Card style={{ width: "400px", padding: "16px" }}>
- <div style={{ marginBottom: "8px", fontSize: "12px", color: "#666" }}>
- <strong>Test:</strong> All zero values
- </div>
+ <Card style={{ width: "500px" }}>
<AreaChartCondensed {...args} />
</Card>
),
+ parameters: {
+ docs: {
+ description: {
+ story:
+ "Tests extreme edge cases with exceptionally long labels and minimal data points. Pushes the label handling system to its limits.",
+ },
+ },
+ },
};
/**
- * ## TEST: Mixed Zeros in Series
+ * ## Minimal Data
*
- * **Purpose**: Test handling of zero values mixed with non-zero
- * **Expected**: Should handle gaps/zeros gracefully
+ * A baseline test with a small dataset and standard-length labels. This serves as a control
+ * case to compare against the more complex label scenarios.
*/
-export const ValueRange_WithZeros: Story = {
+export const MinimalDataStory: Story = {
+ name: "πŸ“± Minimal Data (Baseline)",
args: {
- data: testData.withZeros as any,
- categoryKey: "month" as any,
+ data: dataVariations.minimal as any,
+ categoryKey: "category" as any,
theme: "emerald",
- icons,
+ variant: "natural",
+ tickVariant: "singleLine",
+ grid: true,
+ isAnimationActive: false,
+ showYAxis: true,
height: 200,
},
render: (args: any) => (
- <Card style={{ width: "450px", padding: "16px" }}>
- <div style={{ marginBottom: "8px", fontSize: "12px", color: "#666" }}>
- <strong>Test:</strong> Zeros mixed with values
- </div>
+ <Card style={{ width: "400px" }}>
<AreaChartCondensed {...args} />
</Card>
),
-};
-
-/**
- * ## TEST: Negative Values
- *
- * **Purpose**: Verify handling of negative numbers
- * **Expected**: Should display below zero line correctly
- */
-export const ValueRange_Negative: Story = {
- args: {
- data: testData.negativeValues as any,
- categoryKey: "month" as any,
- theme: "sunset",
- height: 200,
+ parameters: {
+ docs: {
+ description: {
+ story:
+ "Baseline test with minimal data and standard-length labels. Provides a control case to compare against complex scenarios.",
+ },
+ },
},
- render: (args: any) => (
- <Card style={{ width: "450px", padding: "16px" }}>
- <div style={{ marginBottom: "8px", fontSize: "12px", color: "#666" }}>
- <strong>Test:</strong> Negative values
- </div>
- <AreaChartCondensed {...args} />
- </Card>
- ),
};
/**
- * ## TEST: Mixed Positive/Negative
+ * ## Custom Palette
*
- * **Purpose**: Test combination of positive and negative values
- * **Expected**: Should show crossing zero line
+ * This story demonstrates how to use the customPalette prop to provide your own color scheme
+ * for the chart. This is useful when you need to match your brand colors.
*/
-export const ValueRange_Mixed: Story = {
+export const CustomPaletteStory: Story = {
+ name: "🎨 Custom Palette",
args: {
- data: testData.mixedValues as any,
+ data: dataVariations.default as any,
categoryKey: "month" as any,
- theme: "orchid",
- height: 200,
- },
- render: (args: any) => (
- <Card style={{ width: "450px", padding: "16px" }}>
- <div style={{ marginBottom: "8px", fontSize: "12px", color: "#666" }}>
- <strong>Test:</strong> Mixed positive/negative values
- </div>
- <AreaChartCondensed {...args} />
- </Card>
- ),
-};
-
-/**
- * ## TEST: Very Large Numbers (Millions)
- *
- * **Purpose**: Test formatting and display of large numbers
- * **Expected**: Should format with appropriate abbreviations (K, M, B)
- */
-export const ValueRange_VeryLarge: Story = {
- args: {
- data: testData.veryLarge as any,
- categoryKey: "month" as any,
- theme: "vivid",
- height: 200,
- },
- render: (args: any) => (
- <Card style={{ width: "450px", padding: "16px" }}>
- <div style={{ marginBottom: "8px", fontSize: "12px", color: "#666" }}>
- <strong>Test:</strong> Very large numbers (millions)
- </div>
- <AreaChartCondensed {...args} />
- </Card>
- ),
-};
-
-/**
- * ## TEST: Very Small Decimals
- *
- * **Purpose**: Test precision handling for small decimal values
- * **Expected**: Should display appropriate decimal precision
- */
-export const ValueRange_VerySmall: Story = {
- args: {
- data: testData.verySmall as any,
- categoryKey: "month" as any,
- theme: "emerald",
- height: 200,
- },
- render: (args: any) => (
- <Card style={{ width: "450px", padding: "16px" }}>
- <div style={{ marginBottom: "8px", fontSize: "12px", color: "#666" }}>
- <strong>Test:</strong> Very small decimal values
- </div>
- <AreaChartCondensed {...args} />
- </Card>
- ),
-};
-
-/**
- * ## TEST: Wide Value Range
- *
- * **Purpose**: Test scaling when series have vastly different magnitudes
- * **Expected**: Should scale appropriately or show warning
- */
-export const ValueRange_WideRange: Story = {
- args: {
- data: testData.wideRange as any,
- categoryKey: "month" as any,
- theme: "spectrum",
- height: 200,
- },
- render: (args: any) => (
- <Card style={{ width: "500px", padding: "16px" }}>
- <div style={{ marginBottom: "8px", fontSize: "12px", color: "#666" }}>
- <strong>Test:</strong> Wide range (1 to 1,000,000)
- </div>
- <AreaChartCondensed {...args} />
- </Card>
- ),
-};
-
-// ============================================================================
-// PATTERN TESTS - Testing different data patterns and shapes
-// ============================================================================
-
-/**
- * ## TEST: Linear Progression
- *
- * **Purpose**: Verify rendering of linear increasing data
- * **Expected**: Clean straight line progression
- */
-export const Pattern_Linear: Story = {
- args: {
- data: testData.linear as any,
- categoryKey: "x" as any,
- theme: "ocean",
- variant: "linear",
- height: 200,
- },
- render: (args: any) => (
- <Card style={{ width: "500px", padding: "16px" }}>
- <div style={{ marginBottom: "8px", fontSize: "12px", color: "#666" }}>
- <strong>Test:</strong> Linear progression pattern
- </div>
- <AreaChartCondensed {...args} />
- </Card>
- ),
-};
-
-/**
- * ## TEST: Exponential Growth
- *
- * **Purpose**: Test rendering of exponentially increasing values
- * **Expected**: Should handle steep curve and wide Y-axis range
- */
-export const Pattern_Exponential: Story = {
- args: {
- data: testData.exponential as any,
- categoryKey: "x" as any,
- theme: "emerald",
- variant: "natural",
- height: 200,
- },
- render: (args: any) => (
- <Card style={{ width: "500px", padding: "16px" }}>
- <div style={{ marginBottom: "8px", fontSize: "12px", color: "#666" }}>
- <strong>Test:</strong> Exponential growth pattern
- </div>
- <AreaChartCondensed {...args} />
- </Card>
- ),
-};
-
-/**
- * ## TEST: Sinusoidal Wave
- *
- * **Purpose**: Test smooth curves with wave pattern
- * **Expected**: Natural variant should show smooth sine wave
- */
-export const Pattern_Sinusoidal: Story = {
- args: {
- data: testData.sinusoidal as any,
- categoryKey: "x" as any,
- theme: "orchid",
- variant: "natural",
- height: 200,
- },
- render: (args: any) => (
- <Card style={{ width: "600px", padding: "16px" }}>
- <div style={{ marginBottom: "8px", fontSize: "12px", color: "#666" }}>
- <strong>Test:</strong> Sinusoidal wave pattern
- </div>
- <AreaChartCondensed {...args} />
- </Card>
- ),
-};
-
-/**
- * ## TEST: Constant Values
- *
- * **Purpose**: Test behavior with no variation in data
- * **Expected**: Flat horizontal line
- */
-export const Pattern_Constant: Story = {
- args: {
- data: testData.constant as any,
- categoryKey: "x" as any,
- theme: "sunset",
- height: 200,
- },
- render: (args: any) => (
- <Card style={{ width: "450px", padding: "16px" }}>
- <div style={{ marginBottom: "8px", fontSize: "12px", color: "#666" }}>
- <strong>Test:</strong> Constant value pattern
- </div>
- <AreaChartCondensed {...args} />
- </Card>
- ),
-};
-
-/**
- * ## TEST: Volatile/Spike Pattern
- *
- * **Purpose**: Test rendering of data with extreme spikes
- * **Expected**: Should handle spikes without distortion
- */
-export const Pattern_Volatile: Story = {
- args: {
- data: testData.volatile as any,
- categoryKey: "x" as any,
- theme: "vivid",
- height: 200,
- },
- render: (args: any) => (
- <Card style={{ width: "550px", padding: "16px" }}>
- <div style={{ marginBottom: "8px", fontSize: "12px", color: "#666" }}>
- <strong>Test:</strong> Volatile pattern with spikes
- </div>
- <AreaChartCondensed {...args} />
- </Card>
- ),
-};
-
-// ============================================================================
-// REAL-WORLD SCENARIO TESTS - Practical use cases
-// ============================================================================
-
-/**
- * ## TEST: Daily Time Series (30 days)
- *
- * **Purpose**: Test typical time-series sales data
- * **Expected**: Clean rendering of date-based data
- */
-export const RealWorld_DailySales: Story = {
- args: {
- data: testData.dailySales as any,
- categoryKey: "date" as any,
- theme: "ocean",
- icons,
- height: 220,
- },
- render: (args: any) => (
- <Card style={{ width: "700px", padding: "16px" }}>
- <div style={{ marginBottom: "8px", fontSize: "12px", color: "#666" }}>
- <strong>Test:</strong> Daily sales time series | <strong>Days:</strong> 30
- </div>
- <AreaChartCondensed {...args} />
- </Card>
- ),
-};
-
-/**
- * ## TEST: Quarterly Financial Data
- *
- * **Purpose**: Test financial reporting scenario
- * **Expected**: Clear visualization of revenue, profit, costs
- */
-export const RealWorld_QuarterlySales: Story = {
- args: {
- data: testData.quarterlySales as any,
- categoryKey: "quarter" as any,
- theme: "emerald",
- icons,
- height: 220,
- },
- render: (args: any) => (
- <Card style={{ width: "600px", padding: "16px" }}>
- <div style={{ marginBottom: "8px", fontSize: "12px", color: "#666" }}>
- <strong>Test:</strong> Quarterly financial data | <strong>Quarters:</strong> 5
- </div>
- <AreaChartCondensed {...args} />
- </Card>
- ),
-};
-
-/**
- * ## TEST: Weekly Analytics Traffic
- *
- * **Purpose**: Test typical analytics dashboard data
- * **Expected**: Multiple metrics clearly differentiated
- */
-export const RealWorld_WeeklyTraffic: Story = {
- args: {
- data: testData.weeklyTraffic as any,
- categoryKey: "day" as any,
- theme: "sunset",
- icons,
- height: 220,
- },
- render: (args: any) => (
- <Card style={{ width: "650px", padding: "16px" }}>
- <div style={{ marginBottom: "8px", fontSize: "12px", color: "#666" }}>
- <strong>Test:</strong> Weekly traffic analytics | <strong>Metrics:</strong> 3
- </div>
- <AreaChartCondensed {...args} />
- </Card>
- ),
-};
-
-// ============================================================================
-// VARIANT & CONFIGURATION TESTS
-// ============================================================================
-
-/**
- * ## TEST: Variant Comparison
- *
- * **Purpose**: Compare all interpolation variants side-by-side
- * **Expected**: Visual difference between linear, natural, step
- */
-export const Config_VariantComparison: Story = {
- render: () => (
- <div style={{ display: "flex", flexDirection: "column", gap: "16px" }}>
- <Card style={{ width: "600px", padding: "16px" }}>
- <div style={{ marginBottom: "8px", fontSize: "12px", color: "#666" }}>
- <strong>Variant:</strong> Linear
- </div>
- <AreaChartCondensed
- data={testData.twelvePoints as any}
- categoryKey="month"
- variant="linear"
- theme="ocean"
- height={150}
- />
- </Card>
- <Card style={{ width: "600px", padding: "16px" }}>
- <div style={{ marginBottom: "8px", fontSize: "12px", color: "#666" }}>
- <strong>Variant:</strong> Natural (smooth)
- </div>
- <AreaChartCondensed
- data={testData.twelvePoints as any}
- categoryKey="month"
- variant="natural"
- theme="emerald"
- height={150}
- />
- </Card>
- <Card style={{ width: "600px", padding: "16px" }}>
- <div style={{ marginBottom: "8px", fontSize: "12px", color: "#666" }}>
- <strong>Variant:</strong> Step
- </div>
- <AreaChartCondensed
- data={testData.twelvePoints as any}
- categoryKey="month"
- variant="step"
- theme="sunset"
- height={150}
- />
- </Card>
- </div>
- ),
-};
-
-/**
- * ## TEST: Without Y-Axis
- *
- * **Purpose**: Test ultra-compact mode without Y-axis
- * **Expected**: More horizontal space, clean minimal look
- */
-export const Config_WithoutYAxis: Story = {
- args: {
- data: testData.twelvePoints as any,
- categoryKey: "month" as any,
- theme: "vivid",
- showYAxis: false,
- grid: false,
- height: 150,
- },
- render: (args: any) => (
- <Card style={{ width: "500px", padding: "16px" }}>
- <div style={{ marginBottom: "8px", fontSize: "12px", color: "#666" }}>
- <strong>Test:</strong> Y-axis hidden, grid off
- </div>
- <AreaChartCondensed {...args} />
- </Card>
- ),
-};
-
-/**
- * ## TEST: Custom Color Palette
- *
- * **Purpose**: Verify custom palette override functionality
- * **Expected**: Uses custom colors instead of theme
- */
-export const Config_CustomPalette: Story = {
- args: {
- data: testData.twelvePoints as any,
- categoryKey: "month" as any,
- customPalette: ["#FF6B6B", "#4ECDC4", "#45B7D1"],
+ theme: "ocean", // This will be overridden by customPalette
+ variant: "natural",
+ tickVariant: "singleLine",
+ grid: true,
+ isAnimationActive: false,
+ showYAxis: true,
+ xAxisLabel: "Month",
+ yAxisLabel: "Traffic",
+ customPalette: ["#FF6B6B", "#4ECDC4", "#45B7D1"],
height: 200,
},
render: (args: any) => (
<div>
<div
style={{
- marginBottom: "12px",
+ marginBottom: "16px",
padding: "12px",
background: "#f8f9fa",
borderRadius: "8px",
- width: "550px",
+ border: "1px solid #e9ecef",
+ width: "600px",
}}
>
- <strong>Custom Palette:</strong>
- <div style={{ display: "flex", gap: "8px", marginTop: "8px" }}>
+ <h4 style={{ margin: "0 0 8px 0", color: "#333" }}>🎨 Custom Color Palette</h4>
+ <p style={{ margin: "0 0 12px 0", fontSize: "14px", color: "#666" }}>
+ This chart uses a custom color palette instead of the default theme colors.
+ </p>
+ <div style={{ display: "flex", gap: "8px", flexWrap: "wrap" }}>
{args.customPalette?.map((color: string, index: number) => (
<div
key={index}
- style={{ display: "flex", alignItems: "center", gap: "4px", fontSize: "12px" }}
+ style={{
+ display: "flex",
+ alignItems: "center",
+ gap: "4px",
+ padding: "4px 8px",
+ background: "white",
+ borderRadius: "4px",
+ border: "1px solid #ddd",
+ fontSize: "12px",
+ }}
>
<div
style={{
- width: "16px",
- height: "16px",
+ width: "12px",
+ height: "12px",
+ borderRadius: "2px",
backgroundColor: color,
- borderRadius: "3px",
- border: "1px solid #ddd",
+ border: "1px solid #ccc",
}}
/>
<span style={{ fontFamily: "monospace" }}>{color}</span>
@@ -1070,212 +937,63 @@ export const Config_CustomPalette: Story = {
))}
</div>
</div>
- <Card style={{ width: "550px", padding: "16px" }}>
+ <Card style={{ width: "600px" }}>
<AreaChartCondensed {...args} />
</Card>
</div>
),
-};
-
-// ============================================================================
-// STRESS & PERFORMANCE TESTS
-// ============================================================================
-
-/**
- * ## TEST: Multiple Charts Dashboard
- *
- * **Purpose**: Test rendering multiple charts simultaneously
- * **Expected**: All charts render smoothly without performance issues
- */
-export const Stress_MultipleCharts: Story = {
- render: () => (
- <div
- style={{
- display: "grid",
- gridTemplateColumns: "repeat(2, 1fr)",
- gap: "16px",
- width: "900px",
- }}
- >
- <Card style={{ padding: "16px" }}>
- <div style={{ marginBottom: "8px", fontSize: "12px", fontWeight: "600" }}>
- Small Dataset
- </div>
- <AreaChartCondensed
- data={testData.fivePoints as any}
- categoryKey="month"
- theme="ocean"
- height={140}
- />
- </Card>
- <Card style={{ padding: "16px" }}>
- <div style={{ marginBottom: "8px", fontSize: "12px", fontWeight: "600" }}>
- Medium Dataset
- </div>
- <AreaChartCondensed
- data={testData.twelvePoints as any}
- categoryKey="month"
- theme="emerald"
- height={140}
- />
- </Card>
- <Card style={{ padding: "16px" }}>
- <div style={{ marginBottom: "8px", fontSize: "12px", fontWeight: "600" }}>
- Large Dataset (50)
- </div>
- <AreaChartCondensed
- data={testData.large50 as any}
- categoryKey="date"
- theme="sunset"
- height={140}
- />
- </Card>
- <Card style={{ padding: "16px" }}>
- <div style={{ marginBottom: "8px", fontSize: "12px", fontWeight: "600" }}>Time Series</div>
- <AreaChartCondensed
- data={testData.dailySales as any}
- categoryKey="date"
- theme="orchid"
- height={140}
- />
- </Card>
- </div>
- ),
- parameters: {
- docs: {
- description: {
- story: "Stress test with 4 charts rendering simultaneously with varying dataset sizes.",
- },
- },
- },
-};
-
-// Test Data for Long Labels
-const longLabelData = [
- { category: "Q1 2024 January Total Revenue and Expenses", sales: 186, expenses: 80, profit: 106 },
- {
- category: "Q1 2024 February Marketing Campaign Results",
- sales: 305,
- expenses: 200,
- profit: 105,
- },
- { category: "Q1 2024 March Product Launch Performance", sales: 237, expenses: 120, profit: 117 },
- { category: "Q2 2024 April Customer Acquisition Metrics", sales: 273, expenses: 190, profit: 83 },
- { category: "Q2 2024 May Operational Efficiency Report", sales: 209, expenses: 130, profit: 79 },
- {
- category: "Q2 2024 June Strategic Initiative Outcomes",
- sales: 314,
- expenses: 140,
- profit: 174,
- },
- { category: "Q3 2024 July Market Expansion Analysis", sales: 350, expenses: 180, profit: 170 },
- {
- category: "Q3 2024 August Technology Investment Returns",
- sales: 280,
- expenses: 160,
- profit: 120,
- },
- { category: "Q3 2024 September Partnership Performance", sales: 320, expenses: 170, profit: 150 },
- { category: "Q4 2024 October Year-End Projections", sales: 290, expenses: 150, profit: 140 },
- { category: "Q4 2024 November Holiday Season Preview", sales: 340, expenses: 180, profit: 160 },
- { category: "Q4 2024 December Annual Summary Report", sales: 420, expenses: 220, profit: 200 },
-];
-
-// Tick Variant Stories
-export const TickVariantSingleLine: Story = {
- render: () => (
- <Card style={{ padding: "24px", width: "900px", maxWidth: "900px" }}>
- <div style={{ marginBottom: "16px", fontSize: "16px", fontWeight: "600" }}>
- Single Line Tick Variant
- </div>
- <div style={{ marginBottom: "8px", fontSize: "13px", color: "#666" }}>
- Standard horizontal labels with automatic collision detection
- </div>
- <AreaChartCondensed
- data={longLabelData as any}
- categoryKey="category"
- tickVariant="singleLine"
- theme="ocean"
- height={200}
- />
- </Card>
- ),
parameters: {
docs: {
description: {
story:
- "Single line tick variant with standard horizontal labels. Automatically handles collision detection.",
+ 'Demonstrates how to use the `customPalette` prop to provide your own color scheme. When `customPalette` is provided, it overrides the `theme` prop.\n\n**Usage:**\n```tsx\n<AreaChartCondensed\n data={data}\n categoryKey="month"\n customPalette={["#FF6B6B", "#4ECDC4", "#45B7D1"]}\n/>\n```',
},
},
},
};
-export const TickVariantAngled: Story = {
- render: () => (
- <Card style={{ padding: "24px", width: "900px", maxWidth: "900px" }}>
- <div style={{ marginBottom: "16px", fontSize: "16px", fontWeight: "600" }}>
- Angled Tick Variant
- </div>
- <div style={{ marginBottom: "8px", fontSize: "13px", color: "#666" }}>
- -45Β° rotation perfect for long labels that would overlap horizontally
- </div>
- <AreaChartCondensed
- data={longLabelData as any}
- categoryKey="category"
- tickVariant="angled"
- theme="emerald"
- height={280}
- />
- </Card>
- ),
- parameters: {
- docs: {
- description: {
- story:
- "Angled tick variant with -45Β° rotation. Perfect for long labels that would overlap horizontally.",
- },
- },
- },
-};
-
-// Dense Data with Tick Variants
-const denseData = Array.from({ length: 30 }, (_, i) => ({
- day: `Day ${i + 1}`,
- revenue: Math.floor(Math.random() * 500) + 100,
- costs: Math.floor(Math.random() * 300) + 50,
-}));
-
-export const TickVariantComparisonDenseData: Story = {
+/**
+ * ## Tick Variant Comparison
+ *
+ * Side-by-side comparison of single-line (horizontal) and angled tick variants.
+ * This helps you choose the right variant for your data.
+ */
+export const TickVariantComparison: Story = {
+ name: "πŸ“ Tick Variant Comparison",
render: () => (
- <div style={{ display: "grid", gridTemplateColumns: "1fr", gap: "24px", maxWidth: "1100px" }}>
- <Card style={{ padding: "24px" }}>
- <div style={{ marginBottom: "16px", fontSize: "16px", fontWeight: "600" }}>
- Single Line Variant (Dense Data - 30 Points)
- </div>
- <div style={{ marginBottom: "8px", fontSize: "13px", color: "#666" }}>
- Recharts automatically hides overlapping labels
+ <div style={{ display: "flex", flexDirection: "column", gap: "24px" }}>
+ <Card style={{ width: "700px", padding: "16px" }}>
+ <div style={{ marginBottom: "12px" }}>
+ <div style={{ fontSize: "16px", fontWeight: "600", marginBottom: "4px" }}>
+ Single Line Variant (Horizontal)
+ </div>
+ <div style={{ fontSize: "13px", color: "#666" }}>
+ Standard horizontal labels. Recharts automatically hides overlapping labels.
+ </div>
</div>
<AreaChartCondensed
- data={denseData as any}
- categoryKey="day"
+ data={dataVariations.bigLabels as any}
+ categoryKey="category"
tickVariant="singleLine"
theme="ocean"
height={200}
/>
</Card>
- <Card style={{ padding: "24px" }}>
- <div style={{ marginBottom: "16px", fontSize: "16px", fontWeight: "600" }}>
- Angled Variant (Dense Data - 30 Points)
- </div>
- <div style={{ marginBottom: "8px", fontSize: "13px", color: "#666" }}>
- Shows more labels with angled orientation
+ <Card style={{ width: "700px", padding: "16px" }}>
+ <div style={{ marginBottom: "12px" }}>
+ <div style={{ fontSize: "16px", fontWeight: "600", marginBottom: "4px" }}>
+ Angled Variant (Rotated)
+ </div>
+ <div style={{ fontSize: "13px", color: "#666" }}>
+ Automatically rotates labels at an optimal angle. Shows more labels without collision.
+ </div>
</div>
<AreaChartCondensed
- data={denseData as any}
- categoryKey="day"
+ data={dataVariations.bigLabels as any}
+ categoryKey="category"
tickVariant="angled"
theme="emerald"
- height={280}
+ height={260}
/>
</Card>
</div>
@@ -1284,26 +1002,136 @@ export const TickVariantComparisonDenseData: Story = {
docs: {
description: {
story:
- "Comparison of tick variants (singleLine and angled) with dense data (30 data points). Shows how each variant handles label collision with Recharts' built-in collision detection.",
+ "**Side-by-side comparison** of tick variants:\n\n- **Single Line**: Standard horizontal labels with automatic collision detection. Recharts hides overlapping labels.\n- **Angled**: Rotates labels at an optimal angle calculated based on label width and available space. Shows more labels without collision.\n\n**When to use each:**\n- Use **singleLine** for short labels or when you have few data points\n- Use **angled** for long labels or many data points where horizontal labels would overlap",
},
},
},
};
-export const SimpleExample: Story = {
+/**
+ * ## Responsive Behavior Demo
+ *
+ * This story demonstrates the responsive capabilities of the AreaChartCondensed.
+ * Drag the handles on the container to resize it and observe how the chart adapts.
+ */
+export const ResponsiveBehaviorDemo: Story = {
+ name: "πŸ“± Responsive Behavior Demo",
args: {
- data: [
- { label: "A", value: 40 },
- { label: "B", value: 65 },
- { label: "C", value: 30 },
- ],
- categoryKey: "label",
- height: 180,
- theme: "ocean",
+ data: dataVariations.bigLabels as any,
+ categoryKey: "category" as any,
+ theme: "sunset",
+ variant: "natural",
+ tickVariant: "angled",
+ grid: true,
+ isAnimationActive: false,
+ showYAxis: true,
+ height: 250,
+ },
+ render: (args: any) => {
+ const [dimensions, setDimensions] = useState<{ width: number }>({
+ width: 700,
+ });
+
+ const handleMouseDown = (e: React.MouseEvent<HTMLDivElement>, handle: string) => {
+ e.preventDefault();
+ e.stopPropagation();
+ const startX = e.clientX;
+ const startWidth = dimensions.width;
+
+ const doDrag = (e: MouseEvent) => {
+ const dx = e.clientX - startX;
+ let newWidth = startWidth;
+
+ if (handle.includes("e")) newWidth = startWidth + dx;
+ if (handle.includes("w")) newWidth = startWidth - dx;
+
+ setDimensions({
+ width: Math.max(300, newWidth),
+ });
+ };
+
+ const stopDrag = () => {
+ document.removeEventListener("mousemove", doDrag);
+ document.removeEventListener("mouseup", stopDrag);
+ };
+
+ document.addEventListener("mousemove", doDrag);
+ document.addEventListener("mouseup", stopDrag);
+ };
+
+ const handleStyle: React.CSSProperties = {
+ position: "absolute",
+ background: "#3b82f6",
+ opacity: 0.6,
+ zIndex: 10,
+ transition: "opacity 0.2s ease",
+ };
+
+ return (
+ <div style={{ padding: "20px" }}>
+ <div style={{ marginBottom: "20px" }}>
+ <h3 style={{ margin: "0 0 8px 0", fontSize: "18px", fontWeight: "600" }}>
+ Responsive Behavior Demonstration
+ </h3>
+ <p style={{ margin: "0 0 12px 0", color: "#666", fontSize: "14px" }}>
+ Drag the left or right edges of the container to see how the chart adapts
+ </p>
+ <div
+ style={{
+ padding: "12px",
+ backgroundColor: "#e3f2fd",
+ borderRadius: "6px",
+ fontSize: "12px",
+ color: "#1565c0",
+ }}
+ >
+ <strong>🎯 Try This:</strong> Resize the container to see how angled labels adapt to
+ available space.
+ </div>
+ </div>
+
+ <Card
+ style={{
+ position: "relative",
+ width: `${dimensions.width}px`,
+ border: "2px dashed #9ca3af",
+ padding: "20px",
+ boxSizing: "border-box",
+ overflow: "hidden",
+ cursor: "default",
+ }}
+ >
+ <AreaChartCondensed {...args} />
+
+ {/* Resize Handles */}
+ <div
+ style={{ ...handleStyle, top: 0, bottom: 0, left: -2, width: 12, cursor: "ew-resize" }}
+ onMouseDown={(e) => handleMouseDown(e, "w")}
+ />
+ <div
+ style={{ ...handleStyle, top: 0, bottom: 0, right: -2, width: 12, cursor: "ew-resize" }}
+ onMouseDown={(e) => handleMouseDown(e, "e")}
+ />
+
+ {/* Dimension Display */}
+ <div
+ style={{
+ position: "absolute",
+ bottom: 8,
+ right: 8,
+ background: "rgba(0,0,0,0.8)",
+ color: "white",
+ padding: "4px 8px",
+ borderRadius: "4px",
+ fontSize: "11px",
+ fontFamily: "monospace",
+ fontWeight: "500",
+ }}
+ >
+ {dimensions.width}px
+ </div>
+ </Card>
+ </div>
+ );
},
- render: (args: any) => (
- <Card style={{ width: "620px", padding: "16px" }}>
- <AreaChartCondensed {...args} xAxisLabel="Month" yAxisLabel="Sales" />
- </Card>
- ),
};
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 03617644b..79db5f7ad 100644
--- a/js/packages/react-ui/src/components/Charts/BarChartCondensed/BarChartCondensed.tsx
+++ b/js/packages/react-ui/src/components/Charts/BarChartCondensed/BarChartCondensed.tsx
@@ -5,7 +5,7 @@ import { useId } from "../../../polyfills";
import { useTheme } from "../../ThemeProvider";
import { BarChartData, BarChartVariant } from "../BarChart/types";
import { ChartConfig, ChartContainer, ChartTooltip } from "../Charts";
-import { X_AXIS_PADDING } from "../constants";
+import { DEFAULT_X_AXIS_HEIGHT, X_AXIS_PADDING } from "../constants";
import { SideBarChartData, SideBarTooltipProvider } from "../context/SideBarTooltipContext";
import {
useAutoAngleCalculation,
@@ -83,16 +83,31 @@ const BarChartCondensedComponent = <T extends BarChartData>({
const maxLabelWidth = useMaxLabelWidth(data, categoryKey as string);
+ const chartContainerRef = useRef<HTMLDivElement>(null);
+ const [chartContainerWidth, setChartContainerWidth] = useState<number>(0);
+
+ const widthOfData = useMemo(() => {
+ if (data.length === 0) {
+ return 0;
+ }
+ return chartContainerWidth / data.length;
+ }, [chartContainerWidth, data]);
+
const { angle: calculatedAngle, height: xAxisHeight } = useAutoAngleCalculation(
maxLabelWidth,
tickVariant === "angled",
+ maxLabelWidth < 100 ? widthOfData : undefined,
);
+ const isAngled = useMemo(() => {
+ return calculatedAngle !== 0;
+ }, [calculatedAngle]);
+
const effectiveHeight = useMemo(() => {
if (tickVariant === "angled") {
return xAxisHeight + height;
}
- return height;
+ return height + DEFAULT_X_AXIS_HEIGHT;
}, [height, xAxisHeight, tickVariant]);
const transformedKeys = useTransformedKeys(dataKeys);
@@ -173,18 +188,24 @@ const BarChartCondensedComponent = <T extends BarChartData>({
// Observe container width for legend
useEffect(() => {
// Only set up ResizeObserver if width is not provided
- if (width || !containerRef.current) {
+ if (width || !containerRef.current || !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) {
- setContainerWidth(entry.contentRect.width);
+ if (entry.target === containerRef.current) {
+ setContainerWidth(entry.contentRect.width);
+ }
+ if (entry.target === chartContainerRef.current) {
+ setChartContainerWidth(entry.contentRect.width);
+ }
}
});
resizeObserver.observe(containerRef.current);
+ resizeObserver.observe(chartContainerRef.current);
return () => {
resizeObserver.disconnect();
@@ -335,7 +356,7 @@ const BarChartCondensedComponent = <T extends BarChartData>({
<div className="crayon-bar-chart-condensed-container-inner" ref={containerRef}>
{/* Y-axis of the chart */}
{yAxis}
- <div className="crayon-bar-chart-condensed">
+ <div className="crayon-bar-chart-condensed" ref={chartContainerRef}>
<ChartContainer
config={chartConfig}
style={{ width: "100%", height: effectiveHeight }}
@@ -361,7 +382,7 @@ const BarChartCondensedComponent = <T extends BarChartData>({
dataKey={categoryKey as string}
tickLine={false}
axisLine={false}
- textAnchor={tickVariant === "angled" ? "end" : "middle"}
+ textAnchor={isAngled ? "end" : "middle"}
interval="preserveStartEnd"
minTickGap={5}
height={xAxisHeight}
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 e980569ee..1cab9d8c3 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
@@ -1,213 +1,214 @@
import type { Meta, StoryObj } from "@storybook/react";
-import { Calendar, Globe, Laptop, Monitor, Smartphone, TabletSmartphone } from "lucide-react";
+import {
+ Calendar,
+ Globe,
+ Laptop,
+ Monitor,
+ Smartphone,
+ TabletSmartphone,
+ Tv,
+ Watch,
+} from "lucide-react";
+import { useState } from "react";
import { Card } from "../../../Card";
import { BarChartCondensed, BarChartCondensedProps } from "../BarChartCondensed";
-// Test Data Generators
-const generateLargeDataset = (points: number) => {
- return Array.from({ length: points }, (_, i) => ({
- date: `Day ${i + 1}`,
- value1: Math.floor(Math.random() * 1000) + 100,
- value2: Math.floor(Math.random() * 800) + 50,
- value3: Math.floor(Math.random() * 600) + 30,
- }));
-};
-
-const generateTimeSeriesData = (days: number) => {
- const startDate = new Date("2024-01-01");
- return Array.from({ length: days }, (_, i) => {
- const date = new Date(startDate);
- date.setDate(date.getDate() + i);
- return {
- date: date.toISOString().split("T")[0],
- sales: Math.floor(Math.random() * 5000) + 1000,
- orders: Math.floor(Math.random() * 200) + 50,
- };
- });
-};
-
-// Test Data Variations
-const testData = {
- // Edge Cases
- empty: [],
- singlePoint: [{ month: "Jan", value: 100 }],
- twoPoints: [
- { month: "Jan", value: 100 },
- { month: "Feb", value: 200 },
- ],
-
- // Small Datasets
- threePoints: [
- { month: "Jan", value: 100 },
- { month: "Feb", value: 150 },
- { month: "Mar", value: 120 },
- ],
- fivePoints: [
- { month: "Jan", desktop: 150, mobile: 90 },
- { month: "Feb", desktop: 280, mobile: 180 },
- { month: "Mar", desktop: 220, mobile: 140 },
- { month: "Apr", desktop: 180, mobile: 160 },
- { month: "May", desktop: 250, mobile: 120 },
- ],
-
- // Medium Datasets
- twelvePoints: [
- { month: "Jan", desktop: 150, mobile: 90, tablet: 120 },
- { month: "Feb", desktop: 280, mobile: 180, tablet: 140 },
- { month: "Mar", desktop: 220, mobile: 140, tablet: 160 },
- { month: "Apr", desktop: 180, mobile: 160, tablet: 180 },
+// πŸ”₯ COMPREHENSIVE DATA VARIATIONS - Designed to test various scenarios
+const dataVariations = {
+ default: [
+ { month: "January", desktop: 150, mobile: 90, tablet: 120 },
+ { month: "February", desktop: 280, mobile: 180, tablet: 140 },
+ { month: "March", desktop: 220, mobile: 140, tablet: 160 },
+ { month: "April", desktop: 180, mobile: 160, tablet: 180 },
{ month: "May", desktop: 250, mobile: 120, tablet: 140 },
- { month: "Jun", desktop: 300, mobile: 180, tablet: 160 },
- { month: "Jul", desktop: 320, mobile: 200, tablet: 180 },
- { month: "Aug", desktop: 290, mobile: 170, tablet: 150 },
- { month: "Sep", desktop: 310, mobile: 190, tablet: 170 },
- { month: "Oct", desktop: 280, mobile: 160, tablet: 140 },
- { month: "Nov", desktop: 350, mobile: 210, tablet: 190 },
- { month: "Dec", desktop: 400, mobile: 250, tablet: 220 },
- ],
-
- // Large Datasets
- large50: generateLargeDataset(50),
- large100: generateLargeDataset(100),
-
- // Special Value Cases
- allZeros: [
- { month: "Jan", value: 0 },
- { month: "Feb", value: 0 },
- { month: "Mar", value: 0 },
- { month: "Apr", value: 0 },
- ],
- withZeros: [
- { month: "Jan", desktop: 100, mobile: 0 },
- { month: "Feb", desktop: 0, mobile: 50 },
- { month: "Mar", desktop: 150, mobile: 0 },
- { month: "Apr", desktop: 0, mobile: 100 },
- ],
- negativeValues: [
- { month: "Jan", profit: -50, loss: -30 },
- { month: "Feb", profit: 100, loss: -20 },
- { month: "Mar", profit: -30, loss: -40 },
- { month: "Apr", profit: 150, loss: -10 },
- ],
- mixedValues: [
- { month: "Jan", value1: -100, value2: 200 },
- { month: "Feb", value1: 150, value2: -50 },
- { month: "Mar", value1: -75, value2: 300 },
- { month: "Apr", value1: 200, value2: -100 },
+ { month: "June", desktop: 300, mobile: 180, tablet: 160 },
+ { month: "July", desktop: 350, mobile: 220, tablet: 180 },
+ { month: "August", desktop: 400, mobile: 240, tablet: 200 },
+ { month: "September", desktop: 450, mobile: 260, tablet: 220 },
+ { month: "October", desktop: 500, mobile: 280, tablet: 240 },
+ { month: "November", desktop: 550, mobile: 300, tablet: 260 },
+ { month: "December", desktop: 600, mobile: 320, tablet: 280 },
],
-
- // Extreme Values
- veryLarge: [
- { month: "Jan", value: 1000000, secondary: 500000 },
- { month: "Feb", value: 1500000, secondary: 750000 },
- { month: "Mar", value: 1200000, secondary: 600000 },
+ // 🏷️ BIG LABELS - Testing angled tick labels
+ bigLabels: [
+ {
+ category: "Very Long Category Name That Should Be Truncated",
+ sales: 150,
+ revenue: 90,
+ profit: 120,
+ },
+ {
+ category: "Another Extremely Long Label That Causes Collisions",
+ sales: 280,
+ revenue: 180,
+ profit: 140,
+ },
+ {
+ category: "Super Duper Long Category Name That Tests Truncation",
+ sales: 220,
+ revenue: 140,
+ profit: 160,
+ },
+ {
+ category: "Incredibly Long Text That Should Trigger Collision Detection",
+ sales: 180,
+ revenue: 160,
+ profit: 180,
+ },
+ {
+ category: "Maximum Length Category Name That Tests All Edge Cases",
+ sales: 250,
+ revenue: 120,
+ profit: 140,
+ },
+ {
+ category: "Extra Long Business Category Name With Many Words",
+ sales: 300,
+ revenue: 180,
+ profit: 160,
+ },
+ {
+ category: "Comprehensive Long Label For Testing Horizontal Offset",
+ sales: 350,
+ revenue: 220,
+ profit: 180,
+ },
+ {
+ category: "Extended Category Name That Pushes Truncation Limits",
+ sales: 400,
+ revenue: 240,
+ profit: 200,
+ },
],
- verySmall: [
- { month: "Jan", value: 0.001, secondary: 0.002 },
- { month: "Feb", value: 0.003, secondary: 0.0015 },
- { month: "Mar", value: 0.002, secondary: 0.0025 },
+ // 🏒 COMPANY NAMES - Real-world long business names
+ companyNames: [
+ { company: "Apple Inc.", revenue: 394328000000, profit: 99803000000, marketCap: 3500000000000 },
+ {
+ company: "Microsoft Corporation",
+ revenue: 211915000000,
+ profit: 83383000000,
+ marketCap: 2800000000000,
+ },
+ {
+ company: "Alphabet Inc. (Google)",
+ revenue: 307394000000,
+ profit: 76033000000,
+ marketCap: 2100000000000,
+ },
+ {
+ company: "Amazon.com Inc.",
+ revenue: 574785000000,
+ profit: 33364000000,
+ marketCap: 1600000000000,
+ },
+ {
+ company: "Tesla Motors Inc.",
+ revenue: 96773000000,
+ profit: 15000000000,
+ marketCap: 800000000000,
+ },
+ {
+ company: "Meta Platforms Inc.",
+ revenue: 134902000000,
+ profit: 39370000000,
+ marketCap: 900000000000,
+ },
],
- wideRange: [
- { month: "Jan", small: 1, large: 1000000 },
- { month: "Feb", small: 2, large: 1500000 },
- { month: "Mar", small: 1.5, large: 1200000 },
+ // πŸ“ˆ FINANCIAL QUARTERS - Testing medium-density scenarios
+ financialQuarters: [
+ { quarter: "Q1 FY2022", revenue: 1200000, expenses: 800000, profit: 400000 },
+ { quarter: "Q2 FY2022", revenue: 1500000, expenses: 950000, profit: 550000 },
+ { quarter: "Q3 FY2022", revenue: 1800000, expenses: 1100000, profit: 700000 },
+ { quarter: "Q4 FY2022", revenue: 2000000, expenses: 1300000, profit: 700000 },
+ { quarter: "Q1 FY2023", revenue: 2200000, expenses: 1400000, profit: 800000 },
+ { quarter: "Q2 FY2023", revenue: 2500000, expenses: 1600000, profit: 900000 },
+ { quarter: "Q3 FY2023", revenue: 2800000, expenses: 1800000, profit: 1000000 },
+ { quarter: "Q4 FY2023", revenue: 3000000, expenses: 1900000, profit: 1100000 },
],
-
- // Pattern Tests
- linear: Array.from({ length: 10 }, (_, i) => ({
- x: `Point ${i + 1}`,
- y: i * 10,
- })),
- increasing: Array.from({ length: 8 }, (_, i) => ({
- x: `Point ${i + 1}`,
- y: Math.pow(i + 1, 1.5) * 10,
- })),
- constant: Array.from({ length: 8 }, (_, i) => ({
- x: `Point ${i + 1}`,
- y: 100,
- })),
- volatile: Array.from({ length: 15 }, (_, i) => ({
- x: `Point ${i + 1}`,
- spike: i % 3 === 0 ? 500 : 50,
- normal: 100 + Math.random() * 20,
- })),
-
- // Real-world Scenarios
- dailySales: generateTimeSeriesData(30),
- quarterlySales: [
- { quarter: "Q1 2023", revenue: 12000, profit: 4000, costs: 8000 },
- { quarter: "Q2 2023", revenue: 15000, profit: 5500, costs: 9500 },
- { quarter: "Q3 2023", revenue: 18000, profit: 7000, costs: 11000 },
- { quarter: "Q4 2023", revenue: 20000, profit: 7000, costs: 13000 },
- { quarter: "Q1 2024", revenue: 22000, profit: 8000, costs: 14000 },
+ // πŸ“± MINIMAL - Small dataset for baseline testing
+ minimal: [
+ { category: "Mobile Devices", users: 150, sessions: 90 },
+ { category: "Desktop Computers", users: 280, sessions: 180 },
+ { category: "Tablet Devices", users: 220, sessions: 140 },
],
+ // πŸ“Š WEEKLY TRAFFIC
weeklyTraffic: [
- { day: "Mon", visits: 2200, conversions: 180, bounces: 800 },
- { day: "Tue", visits: 2500, conversions: 220, bounces: 900 },
- { day: "Wed", visits: 2300, conversions: 190, bounces: 850 },
- { day: "Thu", visits: 2800, conversions: 250, bounces: 1000 },
- { day: "Fri", visits: 3200, conversions: 280, bounces: 1100 },
- { day: "Sat", visits: 1800, conversions: 120, bounces: 600 },
- { day: "Sun", visits: 1500, conversions: 100, bounces: 500 },
+ { day: "Monday", visits: 2200, conversions: 180, bounces: 800 },
+ { day: "Tuesday", visits: 2500, conversions: 220, bounces: 900 },
+ { day: "Wednesday", visits: 2300, conversions: 190, bounces: 850 },
+ { day: "Thursday", visits: 2800, conversions: 250, bounces: 1000 },
+ { day: "Friday", visits: 3200, conversions: 280, bounces: 1100 },
+ { day: "Saturday", visits: 1800, conversions: 120, bounces: 600 },
+ { day: "Sunday", visits: 1500, conversions: 100, bounces: 500 },
],
};
+// Category key mappings for different datasets
+const categoryKeys = {
+ default: "month",
+ bigLabels: "category",
+ companyNames: "company",
+ financialQuarters: "quarter",
+ minimal: "category",
+ weeklyTraffic: "day",
+};
+
+// πŸ”₯ ACTIVE DATA - For backward compatibility
+const barChartCondensedData = dataVariations.default;
+
const icons = {
desktop: Monitor,
mobile: TabletSmartphone,
tablet: Calendar,
- revenue: Globe,
- profit: Smartphone,
- visits: Monitor,
- conversions: Laptop,
- value: Monitor,
- value1: Monitor,
- value2: TabletSmartphone,
- value3: Calendar,
- small: Smartphone,
- large: Globe,
sales: Globe,
- orders: Laptop,
+ revenue: Smartphone,
+ profit: Laptop,
+ visitors: Tv,
+ conversions: Watch,
+ users: Monitor,
+ sessions: TabletSmartphone,
+ expenses: Calendar,
+ marketCap: Globe,
+ visits: Monitor,
bounces: Calendar,
- costs: Smartphone,
} as const;
/**
- * # BarChartCondensed Test Suite
+ * # BarChartCondensed Component Documentation
+ *
+ * The BarChartCondensed is a compact version of BarChart, designed for space-constrained layouts
+ * like dashboards and sidebars. It's ideal for:
*
- * This file contains comprehensive test cases for the BarChartCondensed component,
- * covering edge cases, data variations, and stress testing scenarios.
+ * - **Compact Dashboards**: Showing multiple metrics in limited space
+ * - **Sidebar Analytics**: Quick comparison visualization without taking up too much room
+ * - **Dense Data Display**: Efficiently showing many data points in a small area
*
- * ## Test Categories
+ * ## Key Features
*
- * ### 1. Edge Cases
- * - Empty data
- * - Single data point
- * - Two data points (minimum for comparison)
+ * ### Space-Efficient Design
+ * - **Compact Height**: Default 200px height for tight layouts
+ * - **Minimal Legend**: Legend is compact and doesn't take up vertical space
+ * - **Adjustable Tick Variants**: Choose between horizontal or angled labels for better space usage
*
- * ### 2. Data Size Variations
- * - Small datasets (3-5 points)
- * - Medium datasets (10-20 points)
- * - Large datasets (50-100 points)
+ * ### Layout Variants
+ * - **Grouped**: Compare sub-categories side-by-side within a primary category
+ * - **Stacked**: Show how sub-categories contribute to a total value
*
- * ### 3. Value Ranges
- * - Zero values
- * - Negative values
- * - Mixed positive/negative
- * - Very large numbers (millions)
- * - Very small decimals
- * - Wide value ranges
+ * ### Flexible Label Handling
+ * - **Single Line Ticks**: Horizontal labels with automatic collision detection
+ * - **Angled Ticks**: Optimal rotation angle for longer labels that need more space
+ * - **Smart Angle Calculation**: Automatically calculates optimal rotation based on label width
*
- * ### 4. Chart Variants
- * - Grouped bars
- * - Stacked bars
+ * ### Interactive & Responsive
+ * - **Hover Tooltips**: Standard tooltip showing all data series
+ * - **Responsive Design**: Adapts fluidly to its container's size
*
- * ### 5. Real-world Scenarios
- * - Time series data
- * - Financial data
- * - Traffic analytics
+ * ### Customization
+ * - **Theming**: Comes with six pre-built color palettes
+ * - **Bar Styling**: Customize corner radius with the radius prop
+ * - **Styling Options**: Control grid visibility, axes, and more
*/
-const meta: Meta<BarChartCondensedProps<any>> = {
+const meta: Meta<BarChartCondensedProps<typeof barChartCondensedData>> = {
title: "Components/Charts/BarChartCondensed",
component: BarChartCondensed,
parameters: {
@@ -215,44 +216,63 @@ const meta: Meta<BarChartCondensedProps<any>> = {
docs: {
description: {
component: `
-## Test Suite Overview
-
-This comprehensive test suite validates the BarChartCondensed component across various scenarios:
-
-### Test Coverage Areas
+## Installation and Basic Usage
-1. **Edge Cases**: Empty data, single point, minimal data
-2. **Data Size**: Small (3-5), Medium (10-20), Large (50-100+) datasets
-3. **Value Ranges**: Zeros, negatives, extremes (millions to decimals)
-4. **Chart Variants**: Grouped and stacked bar configurations
-5. **Real-world**: Time series, financial, analytics data
-
-### How to Use This Test Suite
+\`\`\`tsx
+import { BarChartCondensed } from '@crayonai/react-ui/Charts/BarChartCondensed';
-Each story represents a specific test case. Use these to:
-- Verify component behavior with different data types
-- Check rendering performance with large datasets
-- Validate handling of edge cases
-- Ensure visual consistency across variations
+const salesData = [
+ { month: "January", desktop: 150, mobile: 90 },
+ { month: "February", desktop: 280, mobile: 180 },
+ { month: "March", desktop: 220, mobile: 140 },
+];
-\`\`\`tsx
-// Example: Testing with large dataset
+// Basic implementation
<BarChartCondensed
- data={testData.large100}
- categoryKey="date"
- variant="grouped"
+ data={salesData}
+ categoryKey="month"
theme="ocean"
height={200}
/>
\`\`\`
+
+## Data Structure Requirements
+
+Your data should be an array of objects. Each object must contain:
+- A **category field** (string or number): This will be used for the X-axis labels (e.g., months, categories, etc.).
+- One or more **data series fields** (number): These are the values that will be plotted as bars.
+
+\`\`\`tsx
+const salesData = [
+ { region: "North", sales: 150, marketing: 90 },
+ { region: "South", sales: 280, marketing: 180 },
+ { region: "East", sales: 220, marketing: 140 },
+];
+\`\`\`
+
+## Key Differences from BarChart
+
+- **Compact**: Designed for smaller spaces with a default height of 200px
+- **No Interactive Legend**: Legend is simplified and non-interactive
+- **Tick Variants**: Supports both horizontal (singleLine) and angled labels
+- **Performance**: Optimized for quick rendering in dashboards
+
+## Performance Considerations
+- **Data Density**: For very large datasets, consider disabling animations
+- **Responsiveness**: The chart is fully responsive, but test label visibility on small screens
+- **Animation**: Controlled via \`isAnimationActive={false}\`
`,
},
},
},
- tags: ["dev", "autodocs"],
+ tags: ["!dev", "autodocs"],
argTypes: {
data: {
- description: "Array of data objects for the chart. Same format as BarChart.",
+ description: `
+**Required.** An array of data objects for the bar chart. Each object should contain:
+- A category identifier (string/number) for the X-axis.
+- One or more numeric values for the Y-axis bars.
+`,
control: false,
table: {
type: { summary: "Array<Record<string, string | number>>" },
@@ -260,7 +280,8 @@ Each story represents a specific test case. Use these to:
},
},
categoryKey: {
- description: "The key in your data object for the X-axis category.",
+ description:
+ "**Required.** The key in your data object that represents the category for the X-axis.",
control: false,
table: {
type: { summary: "string" },
@@ -268,7 +289,8 @@ Each story represents a specific test case. Use these to:
},
},
theme: {
- description: "Color palette for the chart. Ignored when customPalette is provided.",
+ description:
+ "Specifies the color palette for the chart's bars and tooltips. Ignored when customPalette is provided.",
control: "select",
options: ["ocean", "orchid", "emerald", "sunset", "spectrum", "vivid"],
table: {
@@ -277,7 +299,8 @@ Each story represents a specific test case. Use these to:
},
},
customPalette: {
- description: "Custom color array. Overrides theme when provided.",
+ description:
+ "Custom array of colors to use instead of the theme palette. Overrides the theme prop when provided.",
control: "object",
table: {
type: { summary: "string[]" },
@@ -285,7 +308,8 @@ Each story represents a specific test case. Use these to:
},
},
variant: {
- description: "Bar chart layout: grouped (side-by-side) or stacked.",
+ 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: {
@@ -295,7 +319,7 @@ Each story represents a specific test case. Use these to:
},
tickVariant: {
description:
- "X-axis tick label style. Choose between singleLine (horizontal) or angled (-45Β°).",
+ "X-axis tick label style. Choose between 'singleLine' (horizontal) or 'angled' (rotated at optimal angle).",
control: "radio",
options: ["singleLine", "angled"],
table: {
@@ -304,15 +328,24 @@ Each story represents a specific test case. Use these to:
},
},
radius: {
- description: "Corner radius for bars in pixels.",
+ description: "Sets the corner radius for the top of each bar, creating a rounded look.",
control: { type: "number", min: 0, max: 12, step: 1 },
table: {
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: "Show or hide grid lines.",
+ description: "Toggles the visibility of the background grid lines.",
control: "boolean",
table: {
defaultValue: { summary: "true" },
@@ -320,23 +353,39 @@ Each story represents a specific test case. Use these to:
},
},
showYAxis: {
- description: "Show or hide Y-axis.",
+ description: "Toggles the visibility of the Y-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: "Enable loading animation.",
+ description: "Enables or disables the initial loading animation for the bars.",
control: "boolean",
table: {
defaultValue: { summary: "false" },
- category: "🎬 Animation",
+ category: "🎬 Animation & Interaction",
},
},
height: {
- description: "Chart height in pixels.",
+ description: "Sets a fixed height for the chart container in pixels.",
control: "number",
table: {
defaultValue: { summary: "200" },
@@ -345,7 +394,7 @@ Each story represents a specific test case. Use these to:
},
},
width: {
- description: "Chart width in pixels. Defaults to 100% of container.",
+ description: "Sets a fixed width for the chart container in pixels.",
control: "number",
table: {
type: { summary: "number" },
@@ -353,7 +402,7 @@ Each story represents a specific test case. Use these to:
},
},
className: {
- description: "Custom CSS class for the container.",
+ description: "Custom CSS class to apply to the chart's container.",
control: "text",
table: {
type: { summary: "string" },
@@ -366,784 +415,502 @@ Each story represents a specific test case. Use these to:
export default meta;
type Story = StoryObj<typeof meta>;
-// ============================================================================
-// EDGE CASES - Testing component behavior with minimal/unusual data
-// ============================================================================
-
/**
- * ## TEST: Empty Data
+ * ## Comprehensive Data Explorer
+ *
+ * This story serves as a comprehensive test suite for the BarChartCondensed component.
+ * Use the buttons to switch between various datasets designed to test edge cases in:
*
- * **Purpose**: Verify component handles empty array gracefully
- * **Expected**: Should render without errors, show empty state or message
+ * - **Label Handling**: Datasets with long, dense, or overlapping labels.
+ * - **Data Density**: Scenarios with few or many data points.
+ * - **Chart Variants**: Toggle between grouped and stacked layouts.
+ * - **Tick Variants**: Toggle between horizontal and angled label orientations.
+ *
+ * It's an excellent tool for developers to see how the chart behaves under different conditions.
*/
-export const EdgeCase_EmptyData: Story = {
+export const DataExplorer: Story = {
+ name: "πŸŽ›οΈ Comprehensive Data Explorer",
args: {
- data: testData.empty as any,
- categoryKey: "month" as any,
+ data: barChartCondensedData,
+ categoryKey: "month",
theme: "ocean",
+ variant: "grouped",
+ tickVariant: "singleLine",
+ radius: 4,
+ grid: true,
+ isAnimationActive: false,
+ showYAxis: true,
+ xAxisLabel: "Time Period",
+ yAxisLabel: "Values",
height: 200,
},
- render: (args: any) => (
- <Card style={{ width: "500px", padding: "16px" }}>
- <div style={{ marginBottom: "8px", fontSize: "12px", color: "#666" }}>
- <strong>Test:</strong> Empty dataset | <strong>Data points:</strong> 0
+ render: (args: any) => {
+ const [selectedDataType, setSelectedDataType] =
+ useState<keyof typeof dataVariations>("default");
+ const [variant, setVariant] = useState<"grouped" | "stacked">("grouped");
+ const [tickVariant, setTickVariant] = useState<"singleLine" | "angled">("singleLine");
+
+ 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",
+ fontFamily: "monospace",
+ };
+
+ 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: "600px",
+ }}
+ >
+ <strong>🏷️ Dataset Selection:</strong>
+ <div style={{ marginTop: "8px", display: "flex", flexWrap: "wrap", gap: "4px" }}>
+ <button
+ onClick={() => setSelectedDataType("default")}
+ style={selectedDataType === "default" ? activeButtonStyle : buttonStyle}
+ >
+ πŸ“… Default (12 months)
+ </button>
+ <button
+ onClick={() => setSelectedDataType("bigLabels")}
+ style={selectedDataType === "bigLabels" ? activeButtonStyle : buttonStyle}
+ >
+ 🏷️ Big Labels
+ </button>
+ <button
+ onClick={() => setSelectedDataType("companyNames")}
+ style={selectedDataType === "companyNames" ? activeButtonStyle : buttonStyle}
+ >
+ 🏒 Company Names
+ </button>
+ <button
+ onClick={() => setSelectedDataType("financialQuarters")}
+ style={selectedDataType === "financialQuarters" ? activeButtonStyle : buttonStyle}
+ >
+ πŸ“ˆ Financial Quarters
+ </button>
+ <button
+ onClick={() => setSelectedDataType("minimal")}
+ style={selectedDataType === "minimal" ? activeButtonStyle : buttonStyle}
+ >
+ πŸ“± Minimal (3 items)
+ </button>
+ <button
+ onClick={() => setSelectedDataType("weeklyTraffic")}
+ style={selectedDataType === "weeklyTraffic" ? activeButtonStyle : buttonStyle}
+ >
+ πŸ“Š Weekly Traffic
+ </button>
+ </div>
+ <div style={{ marginTop: "12px" }}>
+ <strong>πŸ“Š Chart Variant:</strong>
+ <div style={{ marginTop: "8px", display: "flex", gap: "4px" }}>
+ <button
+ onClick={() => setVariant("grouped")}
+ style={variant === "grouped" ? activeButtonStyle : buttonStyle}
+ >
+ Grouped (Side-by-side)
+ </button>
+ <button
+ onClick={() => setVariant("stacked")}
+ style={variant === "stacked" ? activeButtonStyle : buttonStyle}
+ >
+ Stacked (On top)
+ </button>
+ </div>
+ </div>
+ <div style={{ marginTop: "12px" }}>
+ <strong>πŸ“ Tick Variant:</strong>
+ <div style={{ marginTop: "8px", display: "flex", gap: "4px" }}>
+ <button
+ onClick={() => setTickVariant("singleLine")}
+ style={tickVariant === "singleLine" ? activeButtonStyle : buttonStyle}
+ >
+ Horizontal Labels
+ </button>
+ <button
+ onClick={() => setTickVariant("angled")}
+ style={tickVariant === "angled" ? activeButtonStyle : buttonStyle}
+ >
+ Angled Labels
+ </button>
+ </div>
+ </div>
+ <div
+ style={{ marginTop: "12px", fontSize: "12px", color: "#666", fontFamily: "monospace" }}
+ >
+ <div>
+ <strong>Current Dataset:</strong> {selectedDataType}
+ </div>
+ <div>
+ <strong>Items:</strong> {currentData.length} | <strong>Category Key:</strong>{" "}
+ {currentCategoryKey} | <strong>Variant:</strong> {variant} | <strong>Tick:</strong>{" "}
+ {tickVariant}
+ </div>
+ </div>
+ </div>
+ <Card style={{ width: "600px" }}>
+ <BarChartCondensed
+ {...args}
+ data={currentData}
+ categoryKey={currentCategoryKey}
+ variant={variant}
+ tickVariant={tickVariant}
+ />
+ </Card>
</div>
- <BarChartCondensed {...args} />
- </Card>
- ),
+ );
+ },
+ parameters: {
+ docs: {
+ description: {
+ story:
+ "**πŸŽ›οΈ Interactive Explorer:** This story allows you to explore different datasets, chart variants, and tick variants interactively. Use the buttons to switch between:\n\n**Datasets:**\n- **Default**: Standard 12-month data\n- **Big Labels**: Extremely long category names\n- **Company Names**: Real-world business names\n- **Financial Quarters**: Quarterly financial data\n- **Minimal**: Baseline with 3 items\n- **Weekly Traffic**: 7-day traffic data\n\n**Chart Variants:**\n- **Grouped**: Bars side-by-side for comparison\n- **Stacked**: Bars stacked to show totals\n\n**Tick Variants:**\n- **Horizontal Labels**: Standard single-line labels with collision detection\n- **Angled Labels**: Rotated labels for better space utilization",
+ },
+ },
+ },
};
/**
- * ## TEST: Single Data Point
+ * ## Grouped vs Stacked Comparison
*
- * **Purpose**: Verify rendering with only one data point
- * **Expected**: Should render single bar correctly
+ * Side-by-side comparison of grouped and stacked bar chart variants.
+ * This helps you choose the right variant for your data visualization needs.
*/
-export const EdgeCase_SinglePoint: Story = {
- args: {
- data: testData.singlePoint as any,
- categoryKey: "month" as any,
- theme: "ocean",
- height: 200,
- },
- render: (args: any) => (
- <Card style={{ width: "500px", padding: "16px" }}>
- <div style={{ marginBottom: "8px", fontSize: "12px", color: "#666" }}>
- <strong>Test:</strong> Single point | <strong>Data points:</strong> 1
- </div>
- <BarChartCondensed {...args} />
- </Card>
+export const VariantComparison: Story = {
+ name: "πŸ“Š Grouped vs Stacked Comparison",
+ render: () => (
+ <div style={{ display: "flex", flexDirection: "column", gap: "24px" }}>
+ <Card style={{ width: "700px", padding: "16px" }}>
+ <div style={{ marginBottom: "12px" }}>
+ <div style={{ fontSize: "16px", fontWeight: "600", marginBottom: "4px" }}>
+ Grouped Variant (Side-by-side)
+ </div>
+ <div style={{ fontSize: "13px", color: "#666" }}>
+ Best for comparing individual values across categories
+ </div>
+ </div>
+ <BarChartCondensed
+ data={dataVariations.default as any}
+ categoryKey="month"
+ variant="grouped"
+ theme="ocean"
+ height={200}
+ />
+ </Card>
+ <Card style={{ width: "700px", padding: "16px" }}>
+ <div style={{ marginBottom: "12px" }}>
+ <div style={{ fontSize: "16px", fontWeight: "600", marginBottom: "4px" }}>
+ Stacked Variant (On top of each other)
+ </div>
+ <div style={{ fontSize: "13px", color: "#666" }}>
+ Best for showing how parts contribute to a total
+ </div>
+ </div>
+ <BarChartCondensed
+ data={dataVariations.default as any}
+ categoryKey="month"
+ variant="stacked"
+ theme="emerald"
+ height={200}
+ />
+ </Card>
+ </div>
),
+ parameters: {
+ docs: {
+ description: {
+ story:
+ "**Side-by-side comparison** of chart variants:\n\n- **Grouped**: Bars are placed side-by-side within each category. Perfect for comparing individual values across different categories.\n- **Stacked**: Bars are stacked on top of each other to show how parts contribute to a total. Great for showing composition and totals simultaneously.\n\n**When to use each:**\n- Use **grouped** when you want to compare individual series values\n- Use **stacked** when you want to emphasize totals and part-to-whole relationships",
+ },
+ },
+ },
};
/**
- * ## TEST: Two Data Points
+ * ## Big Labels with Angled Ticks
*
- * **Purpose**: Minimum data for comparison (edge case)
- * **Expected**: Should show two bars for comparison
+ * This story demonstrates the chart's ability to handle very long category labels.
+ * The angled tick variant is particularly useful here for preventing label overlap.
*/
-export const EdgeCase_TwoPoints: Story = {
+export const BigLabelsStory: Story = {
+ name: "🏷️ Big Labels (Angled Ticks)",
args: {
- data: testData.twoPoints as any,
- categoryKey: "month" as any,
+ data: dataVariations.bigLabels as any,
+ categoryKey: "category" as any,
theme: "emerald",
- height: 200,
+ variant: "grouped",
+ tickVariant: "angled",
+ radius: 4,
+ grid: true,
+ isAnimationActive: false,
+ showYAxis: true,
+ height: 250,
},
render: (args: any) => (
- <Card style={{ width: "500px", padding: "16px" }}>
- <div style={{ marginBottom: "8px", fontSize: "12px", color: "#666" }}>
- <strong>Test:</strong> Two points (minimum comparison) | <strong>Data points:</strong> 2
- </div>
+ <Card style={{ width: "700px" }}>
<BarChartCondensed {...args} />
</Card>
),
-};
-
-// ============================================================================
-// DATA SIZE TESTS - Testing performance with different dataset sizes
-// ============================================================================
-
-/**
- * ## TEST: Small Dataset (3 points)
- *
- * **Purpose**: Verify rendering with minimal but valid data
- * **Expected**: Clean rendering, good spacing
- */
-export const DataSize_Small3Points: Story = {
- args: {
- data: testData.threePoints as any,
- categoryKey: "month" as any,
- theme: "ocean",
- height: 200,
+ parameters: {
+ docs: {
+ description: {
+ story:
+ "Tests the chart with extremely long category names. The angled tick variant automatically rotates labels at an optimal angle to prevent overlapping and maximize readability.",
+ },
+ },
},
- render: (args: any) => (
- <Card style={{ width: "400px", padding: "16px" }}>
- <div style={{ marginBottom: "8px", fontSize: "12px", color: "#666" }}>
- <strong>Test:</strong> Small dataset | <strong>Data points:</strong> 3
- </div>
- <BarChartCondensed {...args} />
- </Card>
- ),
};
/**
- * ## TEST: Small Dataset (5 points, multiple series)
+ * ## Company Names with Big Numbers
*
- * **Purpose**: Test small data with multiple data series (grouped)
- * **Expected**: All series visible, good color differentiation
+ * This story tests the chart with real-world company names and very large numbers (billions/trillions).
+ * It demonstrates both label handling and number formatting capabilities.
*/
-export const DataSize_Small5PointsGrouped: Story = {
+export const CompanyNamesStory: Story = {
+ name: "🏒 Company Names (Big Numbers)",
args: {
- data: testData.fivePoints as any,
- categoryKey: "month" as any,
+ data: dataVariations.companyNames as any,
+ categoryKey: "company" as any,
+ theme: "vivid",
variant: "grouped",
- theme: "sunset",
- icons,
- height: 200,
+ tickVariant: "angled",
+ radius: 4,
+ grid: true,
+ isAnimationActive: false,
+ showYAxis: true,
+ height: 250,
},
render: (args: any) => (
- <Card style={{ width: "450px", padding: "16px" }}>
- <div style={{ marginBottom: "8px", fontSize: "12px", color: "#666" }}>
- <strong>Test:</strong> Small dataset, 2 series (grouped) | <strong>Data points:</strong> 5
- </div>
+ <Card style={{ width: "700px" }}>
<BarChartCondensed {...args} />
</Card>
),
-};
-
-/**
- * ## TEST: Small Dataset (5 points, stacked)
- *
- * **Purpose**: Test small data with multiple data series (stacked)
- * **Expected**: All series stacked properly, good visual hierarchy
- */
-export const DataSize_Small5PointsStacked: Story = {
- args: {
- data: testData.fivePoints as any,
- categoryKey: "month" as any,
- variant: "stacked",
- theme: "orchid",
- icons,
- height: 200,
+ parameters: {
+ docs: {
+ description: {
+ story:
+ "Tests with real-world company names and very large numbers (billions and trillions). The Y-axis should format numbers with appropriate suffixes (B, T).",
+ },
+ },
},
- render: (args: any) => (
- <Card style={{ width: "450px", padding: "16px" }}>
- <div style={{ marginBottom: "8px", fontSize: "12px", color: "#666" }}>
- <strong>Test:</strong> Small dataset, 2 series (stacked) | <strong>Data points:</strong> 5
- </div>
- <BarChartCondensed {...args} xAxisLabel="Month" yAxisLabel="Sales" />
- </Card>
- ),
};
/**
- * ## TEST: Medium Dataset (12 points, 3 series, grouped)
+ * ## Financial Quarters (Grouped)
*
- * **Purpose**: Standard use case with monthly data (grouped)
- * **Expected**: Clean rendering, all bars visible
+ * Standard financial reporting scenario with quarterly data in grouped layout.
*/
-export const DataSize_Medium12PointsGrouped: Story = {
+export const FinancialQuartersGrouped: Story = {
+ name: "πŸ“ˆ Financial Quarters (Grouped)",
args: {
- data: testData.twelvePoints as any,
- categoryKey: "month" as any,
+ data: dataVariations.financialQuarters as any,
+ categoryKey: "quarter" as any,
+ theme: "sunset",
variant: "grouped",
- theme: "emerald",
- icons,
- height: 200,
+ tickVariant: "singleLine",
+ radius: 4,
+ grid: true,
+ isAnimationActive: false,
+ showYAxis: true,
+ height: 220,
},
render: (args: any) => (
- <Card style={{ width: "600px", padding: "16px" }}>
- <div style={{ marginBottom: "8px", fontSize: "12px", color: "#666" }}>
- <strong>Test:</strong> Medium dataset, 3 series (grouped) | <strong>Data points:</strong> 12
- </div>
+ <Card style={{ width: "600px" }}>
<BarChartCondensed {...args} />
</Card>
),
+ parameters: {
+ docs: {
+ description: {
+ story:
+ "Financial reporting scenario with quarterly data. Grouped layout allows comparison of revenue, expenses, and profit across quarters.",
+ },
+ },
+ },
};
/**
- * ## TEST: Medium Dataset (12 points, 3 series, stacked)
+ * ## Financial Quarters (Stacked)
*
- * **Purpose**: Standard use case with monthly data (stacked)
- * **Expected**: Clean rendering, all stacks visible
+ * Same financial data in stacked layout to show totals and composition.
*/
-export const DataSize_Medium12PointsStacked: Story = {
+export const FinancialQuartersStacked: Story = {
+ name: "πŸ“ˆ Financial Quarters (Stacked)",
args: {
- data: testData.twelvePoints as any,
- categoryKey: "month" as any,
+ data: dataVariations.financialQuarters as any,
+ categoryKey: "quarter" as any,
+ theme: "orchid",
variant: "stacked",
- theme: "vivid",
- icons,
- height: 200,
+ tickVariant: "singleLine",
+ radius: 4,
+ grid: true,
+ isAnimationActive: false,
+ showYAxis: true,
+ height: 220,
},
render: (args: any) => (
- <Card style={{ width: "600px", padding: "16px" }}>
- <div style={{ marginBottom: "8px", fontSize: "12px", color: "#666" }}>
- <strong>Test:</strong> Medium dataset, 3 series (stacked) | <strong>Data points:</strong> 12
- </div>
+ <Card style={{ width: "600px" }}>
<BarChartCondensed {...args} />
</Card>
),
+ parameters: {
+ docs: {
+ description: {
+ story:
+ "Same financial data in stacked layout. This view emphasizes the total values and how components contribute to them.",
+ },
+ },
+ },
};
/**
- * ## TEST: Large Dataset (50 points, grouped)
+ * ## Weekly Traffic Analytics
*
- * **Purpose**: Test performance with larger dataset (grouped)
- * **Expected**: Should handle smoothly, condensed layout
+ * Typical analytics dashboard data showing weekly traffic metrics.
*/
-export const DataSize_Large50PointsGrouped: Story = {
+export const WeeklyTrafficStory: Story = {
+ name: "πŸ“Š Weekly Traffic Analytics",
args: {
- data: testData.large50 as any,
- categoryKey: "date" as any,
+ data: dataVariations.weeklyTraffic as any,
+ categoryKey: "day" as any,
+ theme: "spectrum",
variant: "grouped",
- theme: "ocean",
- height: 250,
+ tickVariant: "singleLine",
+ radius: 4,
+ grid: true,
+ isAnimationActive: false,
+ showYAxis: true,
+ height: 220,
},
render: (args: any) => (
- <Card style={{ width: "700px", padding: "16px" }}>
- <div style={{ marginBottom: "8px", fontSize: "12px", color: "#666" }}>
- <strong>Test:</strong> Large dataset, 3 series (grouped) | <strong>Data points:</strong> 50
- </div>
+ <Card style={{ width: "650px" }}>
<BarChartCondensed {...args} />
</Card>
),
+ parameters: {
+ docs: {
+ description: {
+ story: "Weekly traffic analytics showing visits, conversions, and bounces across the week.",
+ },
+ },
+ },
};
/**
- * ## TEST: Large Dataset (100 points, stacked)
+ * ## Minimal Data
*
- * **Purpose**: Stress test rendering performance (stacked)
- * **Expected**: Chart should remain responsive
+ * A baseline test with a small dataset and standard-length labels.
*/
-export const DataSize_Large100PointsStacked: Story = {
+export const MinimalDataStory: Story = {
+ name: "πŸ“± Minimal Data (Baseline)",
args: {
- data: testData.large100 as any,
- categoryKey: "date" as any,
- variant: "stacked",
- theme: "spectrum",
- height: 250,
+ data: dataVariations.minimal as any,
+ categoryKey: "category" as any,
+ theme: "emerald",
+ variant: "grouped",
+ tickVariant: "singleLine",
+ radius: 4,
+ grid: true,
+ isAnimationActive: false,
+ showYAxis: true,
+ height: 200,
},
render: (args: any) => (
- <Card style={{ width: "800px", padding: "16px" }}>
- <div style={{ marginBottom: "8px", fontSize: "12px", color: "#666" }}>
- <strong>⚠️ Stress Test:</strong> Large dataset, 3 series (stacked) |{" "}
- <strong>Data points:</strong> 100
- </div>
+ <Card style={{ width: "400px" }}>
<BarChartCondensed {...args} />
</Card>
),
+ parameters: {
+ docs: {
+ description: {
+ story: "Baseline test with minimal data (3 items) and standard-length labels.",
+ },
+ },
+ },
};
-// ============================================================================
-// VALUE RANGE TESTS - Testing different value types and ranges
-// ============================================================================
-
/**
- * ## TEST: All Zero Values
+ * ## Custom Palette
*
- * **Purpose**: Verify behavior when all values are zero
- * **Expected**: Should show bars at baseline
+ * This story demonstrates how to use the customPalette prop to provide your own color scheme.
*/
-export const ValueRange_AllZeros: Story = {
+export const CustomPaletteStory: Story = {
+ name: "🎨 Custom Palette",
args: {
- data: testData.allZeros as any,
+ data: dataVariations.default as any,
categoryKey: "month" as any,
- theme: "ocean",
- height: 200,
- },
- render: (args: any) => (
- <Card style={{ width: "400px", padding: "16px" }}>
- <div style={{ marginBottom: "8px", fontSize: "12px", color: "#666" }}>
- <strong>Test:</strong> All zero values
- </div>
- <BarChartCondensed {...args} />
- </Card>
- ),
-};
-
-/**
- * ## TEST: Mixed Zeros in Series (Grouped)
- *
- * **Purpose**: Test handling of zero values mixed with non-zero (grouped)
- * **Expected**: Should show zero-height bars or hide them appropriately
- */
-export const ValueRange_WithZerosGrouped: Story = {
- args: {
- data: testData.withZeros as any,
- categoryKey: "month" as any,
- variant: "grouped",
- theme: "emerald",
- icons,
- height: 200,
- },
- render: (args: any) => (
- <Card style={{ width: "450px", padding: "16px" }}>
- <div style={{ marginBottom: "8px", fontSize: "12px", color: "#666" }}>
- <strong>Test:</strong> Zeros mixed with values (grouped)
- </div>
- <BarChartCondensed {...args} />
- </Card>
- ),
-};
-
-/**
- * ## TEST: Negative Values (Grouped)
- *
- * **Purpose**: Verify handling of negative numbers (grouped)
- * **Expected**: Should display bars below zero line correctly
- */
-export const ValueRange_NegativeGrouped: Story = {
- args: {
- data: testData.negativeValues as any,
- categoryKey: "month" as any,
- variant: "grouped",
- theme: "sunset",
- height: 200,
- },
- render: (args: any) => (
- <Card style={{ width: "450px", padding: "16px" }}>
- <div style={{ marginBottom: "8px", fontSize: "12px", color: "#666" }}>
- <strong>Test:</strong> Negative values (grouped)
- </div>
- <BarChartCondensed {...args} />
- </Card>
- ),
-};
-
-/**
- * ## TEST: Negative Values (Stacked)
- *
- * **Purpose**: Verify handling of negative numbers (stacked)
- * **Expected**: Should stack negative values separately from positive
- */
-export const ValueRange_NegativeStacked: Story = {
- args: {
- data: testData.negativeValues as any,
- categoryKey: "month" as any,
- variant: "stacked",
- theme: "orchid",
- height: 200,
- },
- render: (args: any) => (
- <Card style={{ width: "450px", padding: "16px" }}>
- <div style={{ marginBottom: "8px", fontSize: "12px", color: "#666" }}>
- <strong>Test:</strong> Negative values (stacked)
- </div>
- <BarChartCondensed {...args} />
- </Card>
- ),
-};
-
-/**
- * ## TEST: Mixed Positive/Negative (Grouped)
- *
- * **Purpose**: Test combination of positive and negative values (grouped)
- * **Expected**: Should show bars crossing zero line
- */
-export const ValueRange_MixedGrouped: Story = {
- args: {
- data: testData.mixedValues as any,
- categoryKey: "month" as any,
- variant: "grouped",
- theme: "vivid",
- height: 200,
- },
- render: (args: any) => (
- <Card style={{ width: "450px", padding: "16px" }}>
- <div style={{ marginBottom: "8px", fontSize: "12px", color: "#666" }}>
- <strong>Test:</strong> Mixed positive/negative values (grouped)
- </div>
- <BarChartCondensed {...args} />
- </Card>
- ),
-};
-
-/**
- * ## TEST: Mixed Positive/Negative (Stacked)
- *
- * **Purpose**: Test combination of positive and negative values (stacked)
- * **Expected**: Should separate positive and negative stacks
- */
-export const ValueRange_MixedStacked: Story = {
- args: {
- data: testData.mixedValues as any,
- categoryKey: "month" as any,
- variant: "stacked",
- theme: "emerald",
- height: 200,
- },
- render: (args: any) => (
- <Card style={{ width: "450px", padding: "16px" }}>
- <div style={{ marginBottom: "8px", fontSize: "12px", color: "#666" }}>
- <strong>Test:</strong> Mixed positive/negative values (stacked)
- </div>
- <BarChartCondensed {...args} />
- </Card>
- ),
-};
-
-/**
- * ## TEST: Very Large Numbers (Millions)
- *
- * **Purpose**: Test formatting and display of large numbers
- * **Expected**: Should format with appropriate abbreviations (K, M, B)
- */
-export const ValueRange_VeryLarge: Story = {
- args: {
- data: testData.veryLarge as any,
- categoryKey: "month" as any,
- variant: "grouped",
- theme: "spectrum",
- height: 200,
- },
- render: (args: any) => (
- <Card style={{ width: "450px", padding: "16px" }}>
- <div style={{ marginBottom: "8px", fontSize: "12px", color: "#666" }}>
- <strong>Test:</strong> Very large numbers (millions)
- </div>
- <BarChartCondensed {...args} />
- </Card>
- ),
-};
-
-/**
- * ## TEST: Very Small Decimals
- *
- * **Purpose**: Test precision handling for small decimal values
- * **Expected**: Should display appropriate decimal precision
- */
-export const ValueRange_VerySmall: Story = {
- args: {
- data: testData.verySmall as any,
- categoryKey: "month" as any,
- variant: "grouped",
- theme: "ocean",
- height: 200,
- },
- render: (args: any) => (
- <Card style={{ width: "450px", padding: "16px" }}>
- <div style={{ marginBottom: "8px", fontSize: "12px", color: "#666" }}>
- <strong>Test:</strong> Very small decimal values
- </div>
- <BarChartCondensed {...args} />
- </Card>
- ),
-};
-
-/**
- * ## TEST: Wide Value Range
- *
- * **Purpose**: Test scaling when series have vastly different magnitudes
- * **Expected**: Should scale appropriately or show warning
- */
-export const ValueRange_WideRange: Story = {
- args: {
- data: testData.wideRange as any,
- categoryKey: "month" as any,
- variant: "grouped",
- theme: "sunset",
- height: 200,
- },
- render: (args: any) => (
- <Card style={{ width: "500px", padding: "16px" }}>
- <div style={{ marginBottom: "8px", fontSize: "12px", color: "#666" }}>
- <strong>Test:</strong> Wide range (1 to 1,000,000)
- </div>
- <BarChartCondensed {...args} />
- </Card>
- ),
-};
-
-// ============================================================================
-// REAL-WORLD SCENARIO TESTS - Practical use cases
-// ============================================================================
-
-/**
- * ## TEST: Daily Time Series (30 days, grouped)
- *
- * **Purpose**: Test typical time-series sales data (grouped)
- * **Expected**: Clean rendering of date-based data
- */
-export const RealWorld_DailySalesGrouped: Story = {
- args: {
- data: testData.dailySales as any,
- categoryKey: "date" as any,
- variant: "grouped",
- theme: "ocean",
- icons,
- height: 220,
- },
- render: (args: any) => (
- <Card style={{ width: "700px", padding: "16px" }}>
- <div style={{ marginBottom: "8px", fontSize: "12px", color: "#666" }}>
- <strong>Test:</strong> Daily sales time series (grouped) | <strong>Days:</strong> 30
- </div>
- <BarChartCondensed {...args} />
- </Card>
- ),
-};
-
-/**
- * ## TEST: Daily Time Series (30 days, stacked)
- *
- * **Purpose**: Test typical time-series sales data (stacked)
- * **Expected**: Clean rendering of date-based data with stacked bars
- */
-export const RealWorld_DailySalesStacked: Story = {
- args: {
- data: testData.dailySales as any,
- categoryKey: "date" as any,
- variant: "stacked",
- theme: "emerald",
- icons,
- height: 220,
- },
- render: (args: any) => (
- <Card style={{ width: "700px", padding: "16px" }}>
- <div style={{ marginBottom: "8px", fontSize: "12px", color: "#666" }}>
- <strong>Test:</strong> Daily sales time series (stacked) | <strong>Days:</strong> 30
- </div>
- <BarChartCondensed {...args} />
- </Card>
- ),
-};
-
-/**
- * ## TEST: Quarterly Financial Data (Grouped)
- *
- * **Purpose**: Test financial reporting scenario (grouped)
- * **Expected**: Clear visualization of revenue, profit, costs
- */
-export const RealWorld_QuarterlySalesGrouped: Story = {
- args: {
- data: testData.quarterlySales as any,
- categoryKey: "quarter" as any,
- variant: "grouped",
- theme: "sunset",
- icons,
- height: 220,
- },
- render: (args: any) => (
- <Card style={{ width: "600px", padding: "16px" }}>
- <div style={{ marginBottom: "8px", fontSize: "12px", color: "#666" }}>
- <strong>Test:</strong> Quarterly financial data (grouped) | <strong>Quarters:</strong> 5
- </div>
- <BarChartCondensed {...args} />
- </Card>
- ),
-};
-
-/**
- * ## TEST: Quarterly Financial Data (Stacked)
- *
- * **Purpose**: Test financial reporting scenario (stacked)
- * **Expected**: Clear visualization showing total and components
- */
-export const RealWorld_QuarterlySalesStacked: Story = {
- args: {
- data: testData.quarterlySales as any,
- categoryKey: "quarter" as any,
- variant: "stacked",
- theme: "orchid",
- icons,
- height: 220,
- },
- render: (args: any) => (
- <Card style={{ width: "600px", padding: "16px" }}>
- <div style={{ marginBottom: "8px", fontSize: "12px", color: "#666" }}>
- <strong>Test:</strong> Quarterly financial data (stacked) | <strong>Quarters:</strong> 5
- </div>
- <BarChartCondensed {...args} />
- </Card>
- ),
-};
-
-/**
- * ## TEST: Weekly Analytics Traffic (Grouped)
- *
- * **Purpose**: Test typical analytics dashboard data (grouped)
- * **Expected**: Multiple metrics clearly differentiated
- */
-export const RealWorld_WeeklyTrafficGrouped: Story = {
- args: {
- data: testData.weeklyTraffic as any,
- categoryKey: "day" as any,
- variant: "grouped",
- theme: "vivid",
- icons,
- height: 220,
- },
- render: (args: any) => (
- <Card style={{ width: "650px", padding: "16px" }}>
- <div style={{ marginBottom: "8px", fontSize: "12px", color: "#666" }}>
- <strong>Test:</strong> Weekly traffic analytics (grouped) | <strong>Metrics:</strong> 3
- </div>
- <BarChartCondensed {...args} />
- </Card>
- ),
-};
-
-/**
- * ## TEST: Weekly Analytics Traffic (Stacked)
- *
- * **Purpose**: Test typical analytics dashboard data (stacked)
- * **Expected**: Clear total traffic visualization
- */
-export const RealWorld_WeeklyTrafficStacked: Story = {
- args: {
- data: testData.weeklyTraffic as any,
- categoryKey: "day" as any,
- variant: "stacked",
- theme: "spectrum",
- icons,
- height: 220,
- },
- render: (args: any) => (
- <Card style={{ width: "650px", padding: "16px" }}>
- <div style={{ marginBottom: "8px", fontSize: "12px", color: "#666" }}>
- <strong>Test:</strong> Weekly traffic analytics (stacked) | <strong>Metrics:</strong> 3
- </div>
- <BarChartCondensed {...args} />
- </Card>
- ),
-};
-
-// ============================================================================
-// VARIANT & CONFIGURATION TESTS
-// ============================================================================
-
-/**
- * ## TEST: Variant Comparison (Grouped vs Stacked)
- *
- * **Purpose**: Compare grouped and stacked variants side-by-side
- * **Expected**: Visual difference between variants
- */
-export const Config_VariantComparison: Story = {
- render: () => (
- <div style={{ display: "flex", flexDirection: "column", gap: "16px" }}>
- <Card style={{ width: "600px", padding: "16px" }}>
- <div style={{ marginBottom: "8px", fontSize: "12px", color: "#666" }}>
- <strong>Variant:</strong> Grouped (bars side-by-side)
- </div>
- <BarChartCondensed
- data={testData.twelvePoints as any}
- categoryKey="month"
- variant="grouped"
- theme="ocean"
- height={150}
- />
- </Card>
- <Card style={{ width: "600px", padding: "16px" }}>
- <div style={{ marginBottom: "8px", fontSize: "12px", color: "#666" }}>
- <strong>Variant:</strong> Stacked (bars on top of each other)
- </div>
- <BarChartCondensed
- data={testData.twelvePoints as any}
- categoryKey="month"
- variant="stacked"
- theme="emerald"
- height={150}
- />
- </Card>
- </div>
- ),
-};
-
-/**
- * ## TEST: Radius Variations
- *
- * **Purpose**: Test different corner radius values
- * **Expected**: Clear visual difference in bar rounding
- */
-export const Config_RadiusVariations: Story = {
- render: () => (
- <div style={{ display: "flex", flexDirection: "column", gap: "16px" }}>
- <Card style={{ width: "600px", padding: "16px" }}>
- <div style={{ marginBottom: "8px", fontSize: "12px", color: "#666" }}>
- <strong>Radius:</strong> 0px (Sharp corners)
- </div>
- <BarChartCondensed
- data={testData.twelvePoints as any}
- categoryKey="month"
- theme="ocean"
- height={150}
- radius={0}
- />
- </Card>
- <Card style={{ width: "600px", padding: "16px" }}>
- <div style={{ marginBottom: "8px", fontSize: "12px", color: "#666" }}>
- <strong>Radius:</strong> 4px (Default)
- </div>
- <BarChartCondensed
- data={testData.twelvePoints as any}
- categoryKey="month"
- theme="emerald"
- height={150}
- radius={4}
- />
- </Card>
- <Card style={{ width: "600px", padding: "16px" }}>
- <div style={{ marginBottom: "8px", fontSize: "12px", color: "#666" }}>
- <strong>Radius:</strong> 8px (Rounded)
- </div>
- <BarChartCondensed
- data={testData.twelvePoints as any}
- categoryKey="month"
- theme="sunset"
- height={150}
- radius={8}
- />
- </Card>
- </div>
- ),
-};
-
-/**
- * ## TEST: Without Y-Axis
- *
- * **Purpose**: Test ultra-compact mode without Y-axis
- * **Expected**: More horizontal space, clean minimal look
- */
-export const Config_WithoutYAxis: Story = {
- args: {
- data: testData.twelvePoints as any,
- categoryKey: "month" as any,
- variant: "grouped",
- theme: "vivid",
- showYAxis: false,
- grid: false,
- height: 150,
- },
- render: (args: any) => (
- <Card style={{ width: "500px", padding: "16px" }}>
- <div style={{ marginBottom: "8px", fontSize: "12px", color: "#666" }}>
- <strong>Test:</strong> Y-axis hidden, grid off
- </div>
- <BarChartCondensed {...args} />
- </Card>
- ),
-};
-
-/**
- * ## TEST: Custom Color Palette
- *
- * **Purpose**: Verify custom palette override functionality
- * **Expected**: Uses custom colors instead of theme
- */
-export const Config_CustomPalette: Story = {
- args: {
- data: testData.twelvePoints as any,
- categoryKey: "month" as any,
- variant: "grouped",
- customPalette: ["#FF6B6B", "#4ECDC4", "#45B7D1"],
+ theme: "ocean", // This will be overridden by customPalette
+ variant: "grouped",
+ tickVariant: "singleLine",
+ radius: 4,
+ grid: true,
+ isAnimationActive: false,
+ showYAxis: true,
+ xAxisLabel: "Month",
+ yAxisLabel: "Traffic",
+ customPalette: ["#FF6B6B", "#4ECDC4", "#45B7D1"],
height: 200,
},
render: (args: any) => (
<div>
<div
style={{
- marginBottom: "12px",
+ marginBottom: "16px",
padding: "12px",
background: "#f8f9fa",
borderRadius: "8px",
- width: "550px",
+ border: "1px solid #e9ecef",
+ width: "600px",
}}
>
- <strong>Custom Palette:</strong>
- <div style={{ display: "flex", gap: "8px", marginTop: "8px" }}>
+ <h4 style={{ margin: "0 0 8px 0", color: "#333" }}>🎨 Custom Color Palette</h4>
+ <p style={{ margin: "0 0 12px 0", fontSize: "14px", color: "#666" }}>
+ This chart uses a custom color palette instead of the default theme colors.
+ </p>
+ <div style={{ display: "flex", gap: "8px", flexWrap: "wrap" }}>
{args.customPalette?.map((color: string, index: number) => (
<div
key={index}
- style={{ display: "flex", alignItems: "center", gap: "4px", fontSize: "12px" }}
+ style={{
+ display: "flex",
+ alignItems: "center",
+ gap: "4px",
+ padding: "4px 8px",
+ background: "white",
+ borderRadius: "4px",
+ border: "1px solid #ddd",
+ fontSize: "12px",
+ }}
>
<div
style={{
- width: "16px",
- height: "16px",
+ width: "12px",
+ height: "12px",
+ borderRadius: "2px",
backgroundColor: color,
- borderRadius: "3px",
- border: "1px solid #ddd",
+ border: "1px solid #ccc",
}}
/>
<span style={{ fontFamily: "monospace" }}>{color}</span>
@@ -1151,79 +918,76 @@ export const Config_CustomPalette: Story = {
))}
</div>
</div>
- <Card style={{ width: "550px", padding: "16px" }}>
+ <Card style={{ width: "600px" }}>
<BarChartCondensed {...args} />
</Card>
</div>
),
+ parameters: {
+ docs: {
+ description: {
+ story:
+ 'Demonstrates how to use the `customPalette` prop to provide your own color scheme. When `customPalette` is provided, it overrides the `theme` prop.\n\n**Usage:**\n```tsx\n<BarChartCondensed\n data={data}\n categoryKey="month"\n customPalette={["#FF6B6B", "#4ECDC4", "#45B7D1"]}\n/>\n```',
+ },
+ },
+ },
};
-// ============================================================================
-// STRESS & PERFORMANCE TESTS
-// ============================================================================
-
/**
- * ## TEST: Multiple Charts Dashboard
+ * ## Radius Comparison
*
- * **Purpose**: Test rendering multiple charts simultaneously
- * **Expected**: All charts render smoothly without performance issues
+ * Compare different corner radius values for the bars.
*/
-export const Stress_MultipleCharts: Story = {
+export const RadiusComparison: Story = {
+ name: "πŸ”˜ Radius Comparison",
render: () => (
- <div
- style={{
- display: "grid",
- gridTemplateColumns: "repeat(2, 1fr)",
- gap: "16px",
- width: "900px",
- }}
- >
- <Card style={{ padding: "16px" }}>
- <div style={{ marginBottom: "8px", fontSize: "12px", fontWeight: "600" }}>
- Small Dataset (Grouped)
+ <div style={{ display: "flex", flexDirection: "column", gap: "24px" }}>
+ <Card style={{ width: "700px", padding: "16px" }}>
+ <div style={{ marginBottom: "12px" }}>
+ <div style={{ fontSize: "16px", fontWeight: "600", marginBottom: "4px" }}>
+ Sharp Corners (0px)
+ </div>
+ <div style={{ fontSize: "13px", color: "#666" }}>No rounding, clean angular look</div>
</div>
<BarChartCondensed
- data={testData.fivePoints as any}
+ data={dataVariations.default as any}
categoryKey="month"
variant="grouped"
theme="ocean"
- height={140}
+ radius={0}
+ height={180}
/>
</Card>
- <Card style={{ padding: "16px" }}>
- <div style={{ marginBottom: "8px", fontSize: "12px", fontWeight: "600" }}>
- Medium Dataset (Stacked)
+ <Card style={{ width: "700px", padding: "16px" }}>
+ <div style={{ marginBottom: "12px" }}>
+ <div style={{ fontSize: "16px", fontWeight: "600", marginBottom: "4px" }}>
+ Default Radius (4px)
+ </div>
+ <div style={{ fontSize: "13px", color: "#666" }}>Subtle rounding, balanced look</div>
</div>
<BarChartCondensed
- data={testData.twelvePoints as any}
+ data={dataVariations.default as any}
categoryKey="month"
- variant="stacked"
+ variant="grouped"
theme="emerald"
- height={140}
+ radius={4}
+ height={180}
/>
</Card>
- <Card style={{ padding: "16px" }}>
- <div style={{ marginBottom: "8px", fontSize: "12px", fontWeight: "600" }}>
- Large Dataset (Grouped)
+ <Card style={{ width: "700px", padding: "16px" }}>
+ <div style={{ marginBottom: "12px" }}>
+ <div style={{ fontSize: "16px", fontWeight: "600", marginBottom: "4px" }}>
+ Rounded Corners (8px)
+ </div>
+ <div style={{ fontSize: "13px", color: "#666" }}>More pronounced rounding</div>
</div>
<BarChartCondensed
- data={testData.large50 as any}
- categoryKey="date"
+ data={dataVariations.default as any}
+ categoryKey="month"
variant="grouped"
theme="sunset"
- height={140}
- />
- </Card>
- <Card style={{ padding: "16px" }}>
- <div style={{ marginBottom: "8px", fontSize: "12px", fontWeight: "600" }}>
- Time Series (Stacked)
- </div>
- <BarChartCondensed
- data={testData.dailySales as any}
- categoryKey="date"
- variant="stacked"
- theme="orchid"
- height={140}
+ radius={8}
+ height={180}
/>
</Card>
</div>
@@ -1232,142 +996,55 @@ export const Stress_MultipleCharts: Story = {
docs: {
description: {
story:
- "Stress test with 4 charts rendering simultaneously with varying dataset sizes and variants.",
- },
- },
- },
-};
-
-// Test Data for Long Labels
-const longLabelData = [
- { category: "Q1 2024 January Total Revenue and Expenses", sales: 186, expenses: 80, profit: 106 },
- {
- category: "Q1 2024 February Marketing Campaign Results",
- sales: 305,
- expenses: 200,
- profit: 105,
- },
- { category: "Q1 2024 March Product Launch Performance", sales: 237, expenses: 120, profit: 117 },
- { category: "Q2 2024 April Customer Acquisition Metrics", sales: 273, expenses: 190, profit: 83 },
- { category: "Q2 2024 May Operational Efficiency Report", sales: 209, expenses: 130, profit: 79 },
- {
- category: "Q2 2024 June Strategic Initiative Outcomes",
- sales: 314,
- expenses: 140,
- profit: 174,
- },
- { category: "Q3 2024 July Market Expansion Analysis", sales: 350, expenses: 180, profit: 170 },
- {
- category: "Q3 2024 August Technology Investment Returns",
- sales: 280,
- expenses: 160,
- profit: 120,
- },
- { category: "Q3 2024 September Partnership Performance", sales: 320, expenses: 170, profit: 150 },
- { category: "Q4 2024 October Year-End Projections", sales: 290, expenses: 150, profit: 140 },
- { category: "Q4 2024 November Holiday Season Preview", sales: 340, expenses: 180, profit: 160 },
- { category: "Q4 2024 December Annual Summary Report", sales: 420, expenses: 220, profit: 200 },
-];
-
-// Tick Variant Stories
-export const TickVariantSingleLine: Story = {
- render: () => (
- <Card style={{ padding: "24px", width: "900px", maxWidth: "900px" }}>
- <div style={{ marginBottom: "16px", fontSize: "16px", fontWeight: "600" }}>
- Single Line Tick Variant
- </div>
- <div style={{ marginBottom: "8px", fontSize: "13px", color: "#666" }}>
- Standard horizontal labels with automatic collision detection
- </div>
- <BarChartCondensed
- data={longLabelData as any}
- categoryKey="category"
- variant="grouped"
- tickVariant="singleLine"
- theme="ocean"
- height={200}
- />
- </Card>
- ),
- parameters: {
- docs: {
- description: {
- story:
- "Single line tick variant with standard horizontal labels. Automatically handles collision detection.",
+ "**Radius comparison** showing different corner radius values:\n\n- **0px**: Sharp, angular corners for a clean, modern look\n- **4px**: Default subtle rounding, balanced appearance\n- **8px**: More pronounced rounding for a softer appearance\n\n**When to use each:**\n- Use **0px** for a clean, technical, or minimalist aesthetic\n- Use **4px** (default) for general purpose use\n- Use **8px** for a friendlier, more approachable design",
},
},
},
};
-export const TickVariantAngled: Story = {
- render: () => (
- <Card style={{ padding: "24px", width: "900px", maxWidth: "900px" }}>
- <div style={{ marginBottom: "16px", fontSize: "16px", fontWeight: "600" }}>
- Angled Tick Variant
- </div>
- <div style={{ marginBottom: "8px", fontSize: "13px", color: "#666" }}>
- -45Β° rotation perfect for long labels that would overlap horizontally
- </div>
- <BarChartCondensed
- data={longLabelData as any}
- categoryKey="category"
- variant="grouped"
- tickVariant="angled"
- theme="emerald"
- height={280}
- />
- </Card>
- ),
- parameters: {
- docs: {
- description: {
- story:
- "Angled tick variant with -45Β° rotation. Perfect for long labels that would overlap horizontally.",
- },
- },
- },
-};
-
-// Dense Data with Tick Variants
-const denseData = Array.from({ length: 30 }, (_, i) => ({
- day: `Day ${i + 1}`,
- revenue: Math.floor(Math.random() * 500) + 100,
- costs: Math.floor(Math.random() * 300) + 50,
-}));
-
-export const TickVariantComparisonDenseData: Story = {
+/**
+ * ## Tick Variant Comparison
+ *
+ * Side-by-side comparison of single-line (horizontal) and angled tick variants.
+ */
+export const TickVariantComparison: Story = {
+ name: "πŸ“ Tick Variant Comparison",
render: () => (
- <div style={{ display: "grid", gridTemplateColumns: "1fr", gap: "24px", maxWidth: "1100px" }}>
- <Card style={{ padding: "24px" }}>
- <div style={{ marginBottom: "16px", fontSize: "16px", fontWeight: "600" }}>
- Single Line Variant (Dense Data - 30 Points, Grouped)
- </div>
- <div style={{ marginBottom: "8px", fontSize: "13px", color: "#666" }}>
- Recharts automatically hides overlapping labels
+ <div style={{ display: "flex", flexDirection: "column", gap: "24px" }}>
+ <Card style={{ width: "700px", padding: "16px" }}>
+ <div style={{ marginBottom: "12px" }}>
+ <div style={{ fontSize: "16px", fontWeight: "600", marginBottom: "4px" }}>
+ Single Line Variant (Horizontal)
+ </div>
+ <div style={{ fontSize: "13px", color: "#666" }}>
+ Standard horizontal labels. Recharts automatically hides overlapping labels.
+ </div>
</div>
<BarChartCondensed
- data={denseData as any}
- categoryKey="day"
+ data={dataVariations.bigLabels as any}
+ categoryKey="category"
variant="grouped"
tickVariant="singleLine"
theme="ocean"
height={200}
/>
</Card>
- <Card style={{ padding: "24px" }}>
- <div style={{ marginBottom: "16px", fontSize: "16px", fontWeight: "600" }}>
- Angled Variant (Dense Data - 30 Points, Stacked)
- </div>
- <div style={{ marginBottom: "8px", fontSize: "13px", color: "#666" }}>
- Shows more labels with angled orientation
+ <Card style={{ width: "700px", padding: "16px" }}>
+ <div style={{ marginBottom: "12px" }}>
+ <div style={{ fontSize: "16px", fontWeight: "600", marginBottom: "4px" }}>
+ Angled Variant (Rotated)
+ </div>
+ <div style={{ fontSize: "13px", color: "#666" }}>
+ Automatically rotates labels at an optimal angle. Shows more labels without collision.
+ </div>
</div>
<BarChartCondensed
- data={denseData as any}
- categoryKey="day"
- variant="stacked"
+ data={dataVariations.bigLabels as any}
+ categoryKey="category"
+ variant="grouped"
tickVariant="angled"
theme="emerald"
- height={280}
+ height={260}
/>
</Card>
</div>
@@ -1376,36 +1053,137 @@ export const TickVariantComparisonDenseData: Story = {
docs: {
description: {
story:
- "Comparison of tick variants (singleLine and angled) with dense data (30 data points). Shows how each variant handles label collision with Recharts' built-in collision detection.",
+ "**Side-by-side comparison** of tick variants:\n\n- **Single Line**: Standard horizontal labels with automatic collision detection. Recharts hides overlapping labels.\n- **Angled**: Rotates labels at an optimal angle calculated based on label width and available space. Shows more labels without collision.\n\n**When to use each:**\n- Use **singleLine** for short labels or when you have few data points\n- Use **angled** for long labels or many data points where horizontal labels would overlap",
},
},
},
};
-export const SimpleExample: Story = {
+/**
+ * ## Responsive Behavior Demo
+ *
+ * This story demonstrates the responsive capabilities of the BarChartCondensed.
+ * Drag the handles on the container to resize it and observe how the chart adapts.
+ */
+export const ResponsiveBehaviorDemo: Story = {
+ name: "πŸ“± Responsive Behavior Demo",
args: {
- data: [
- { label: "A", value: 40 },
- { label: "B", value: 65 },
- { label: "C", value: 30 },
- ],
- categoryKey: "label",
- height: 180,
- theme: "ocean",
+ data: dataVariations.bigLabels as any,
+ categoryKey: "category" as any,
+ theme: "sunset",
+ variant: "grouped",
+ tickVariant: "angled",
+ radius: 4,
+ grid: true,
+ isAnimationActive: false,
+ showYAxis: true,
+ height: 250,
},
- render: (args: any) => (
- <Card style={{ width: "620px", padding: "16px" }}>
- <div style={{ marginBottom: "8px", fontSize: "14px", color: "#666" }}>
- Simple BarChartCondensed Example
+ render: (args: any) => {
+ const [dimensions, setDimensions] = useState<{ width: number }>({
+ width: 700,
+ });
+
+ const handleMouseDown = (e: React.MouseEvent<HTMLDivElement>, handle: string) => {
+ e.preventDefault();
+ e.stopPropagation();
+ const startX = e.clientX;
+ const startWidth = dimensions.width;
+
+ const doDrag = (e: MouseEvent) => {
+ const dx = e.clientX - startX;
+ let newWidth = startWidth;
+
+ if (handle.includes("e")) newWidth = startWidth + dx;
+ if (handle.includes("w")) newWidth = startWidth - dx;
+
+ setDimensions({
+ width: Math.max(300, newWidth),
+ });
+ };
+
+ const stopDrag = () => {
+ document.removeEventListener("mousemove", doDrag);
+ document.removeEventListener("mouseup", stopDrag);
+ };
+
+ document.addEventListener("mousemove", doDrag);
+ document.addEventListener("mouseup", stopDrag);
+ };
+
+ const handleStyle: React.CSSProperties = {
+ position: "absolute",
+ background: "#3b82f6",
+ opacity: 0.6,
+ zIndex: 10,
+ transition: "opacity 0.2s ease",
+ };
+
+ return (
+ <div style={{ padding: "20px" }}>
+ <div style={{ marginBottom: "20px" }}>
+ <h3 style={{ margin: "0 0 8px 0", fontSize: "18px", fontWeight: "600" }}>
+ Responsive Behavior Demonstration
+ </h3>
+ <p style={{ margin: "0 0 12px 0", color: "#666", fontSize: "14px" }}>
+ Drag the left or right edges of the container to see how the chart adapts
+ </p>
+ <div
+ style={{
+ padding: "12px",
+ backgroundColor: "#e3f2fd",
+ borderRadius: "6px",
+ fontSize: "12px",
+ color: "#1565c0",
+ }}
+ >
+ <strong>🎯 Try This:</strong> Resize the container to see how bar widths and labels
+ adapt to available space.
+ </div>
+ </div>
+
+ <Card
+ style={{
+ position: "relative",
+ width: `${dimensions.width}px`,
+ border: "2px dashed #9ca3af",
+ padding: "20px",
+ boxSizing: "border-box",
+ overflow: "hidden",
+ cursor: "default",
+ }}
+ >
+ <BarChartCondensed {...args} />
+
+ {/* Resize Handles */}
+ <div
+ style={{ ...handleStyle, top: 0, bottom: 0, left: -2, width: 12, cursor: "ew-resize" }}
+ onMouseDown={(e) => handleMouseDown(e, "w")}
+ />
+ <div
+ style={{ ...handleStyle, top: 0, bottom: 0, right: -2, width: 12, cursor: "ew-resize" }}
+ onMouseDown={(e) => handleMouseDown(e, "e")}
+ />
+
+ {/* Dimension Display */}
+ <div
+ style={{
+ position: "absolute",
+ bottom: 8,
+ right: 8,
+ background: "rgba(0,0,0,0.8)",
+ color: "white",
+ padding: "4px 8px",
+ borderRadius: "4px",
+ fontSize: "11px",
+ fontFamily: "monospace",
+ fontWeight: "500",
+ }}
+ >
+ {dimensions.width}px
+ </div>
+ </Card>
</div>
- <BarChartCondensed {...args} xAxisLabel="Month" yAxisLabel="Sales" />
- </Card>
- ),
- parameters: {
- docs: {
- description: {
- story: "A simple BarChartCondensed rendering with 3 data points and a single series.",
- },
- },
+ );
},
};
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 c645a1367..fe1d8af4d 100644
--- a/js/packages/react-ui/src/components/Charts/LineChartCondensed/LineChartCondensed.tsx
+++ b/js/packages/react-ui/src/components/Charts/LineChartCondensed/LineChartCondensed.tsx
@@ -3,7 +3,7 @@ import React, { useEffect, useMemo, useRef, useState } from "react";
import { Line, LineChart as RechartsLineChart, XAxis, YAxis } from "recharts";
import { useId } from "../../../polyfills";
import { ChartConfig, ChartContainer, ChartTooltip } from "../Charts";
-import { X_AXIS_PADDING } from "../constants";
+import { DEFAULT_X_AXIS_HEIGHT, X_AXIS_PADDING } from "../constants";
import { SideBarChartData, SideBarTooltipProvider } from "../context/SideBarTooltipContext";
import {
useAutoAngleCalculation,
@@ -76,16 +76,31 @@ const LineChartCondensedComponent = <T extends LineChartData>({
const maxLabelWidth = useMaxLabelWidth(data, categoryKey as string);
+ const chartContainerRef = useRef<HTMLDivElement>(null);
+ const [chartContainerWidth, setChartContainerWidth] = useState<number>(0);
+
+ const widthOfData = useMemo(() => {
+ if (data.length === 0) {
+ return 0;
+ }
+ return chartContainerWidth / data.length;
+ }, [chartContainerWidth, data]);
+
const { angle: calculatedAngle, height: xAxisHeight } = useAutoAngleCalculation(
maxLabelWidth,
tickVariant === "angled",
+ maxLabelWidth < 100 ? widthOfData : undefined,
);
+ const isAngled = useMemo(() => {
+ return calculatedAngle !== 0;
+ }, [calculatedAngle]);
+
const effectiveHeight = useMemo(() => {
if (tickVariant === "angled") {
return xAxisHeight + height;
}
- return height;
+ return height + DEFAULT_X_AXIS_HEIGHT;
}, [height, xAxisHeight, tickVariant]);
const transformedKeys = useTransformedKeys(dataKeys);
@@ -130,18 +145,24 @@ const LineChartCondensedComponent = <T extends LineChartData>({
// Observe container width for legend
useEffect(() => {
// Only set up ResizeObserver if width is not provided
- if (width || !containerRef.current) {
+ if (width || !containerRef.current || !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) {
- setContainerWidth(entry.contentRect.width);
+ if (entry.target === containerRef.current) {
+ setContainerWidth(entry.contentRect.width);
+ }
+ if (entry.target === chartContainerRef.current) {
+ setChartContainerWidth(entry.contentRect.width);
+ }
}
});
resizeObserver.observe(containerRef.current);
+ resizeObserver.observe(chartContainerRef.current);
return () => {
resizeObserver.disconnect();
@@ -233,7 +254,7 @@ const LineChartCondensedComponent = <T extends LineChartData>({
<div className="crayon-line-chart-condensed-container-inner" ref={containerRef}>
{/* Y-axis of the chart */}
{yAxis}
- <div className="crayon-line-chart-condensed">
+ <div className="crayon-line-chart-condensed" ref={chartContainerRef}>
<ChartContainer
config={chartConfig}
style={{ width: "100%", height: effectiveHeight }}
@@ -254,7 +275,7 @@ const LineChartCondensedComponent = <T extends LineChartData>({
dataKey={categoryKey as string}
tickLine={false}
axisLine={false}
- textAnchor={tickVariant === "angled" ? "end" : "middle"}
+ textAnchor={isAngled ? "end" : "middle"}
interval="preserveStartEnd"
minTickGap={5}
height={xAxisHeight}
diff --git a/js/packages/react-ui/src/components/Charts/LineChartCondensed/stories/lineChartCondensed.stories.tsx b/js/packages/react-ui/src/components/Charts/LineChartCondensed/stories/lineChartCondensed.stories.tsx
index 4e6ed25e8..61580c15c 100644
--- a/js/packages/react-ui/src/components/Charts/LineChartCondensed/stories/lineChartCondensed.stories.tsx
+++ b/js/packages/react-ui/src/components/Charts/LineChartCondensed/stories/lineChartCondensed.stories.tsx
@@ -1,221 +1,270 @@
import type { Meta, StoryObj } from "@storybook/react";
-import { Calendar, Globe, Laptop, Monitor, Smartphone, TabletSmartphone } from "lucide-react";
+import {
+ Calendar,
+ Globe,
+ Laptop,
+ Monitor,
+ Smartphone,
+ TabletSmartphone,
+ Tv,
+ Watch,
+} from "lucide-react";
+import { useState } from "react";
import { Card } from "../../../Card";
import { LineChartCondensed, LineChartCondensedProps } from "../LineChartCondensed";
-// Test Data Generators
-const generateLargeDataset = (points: number) => {
- return Array.from({ length: points }, (_, i) => ({
- date: `Day ${i + 1}`,
- value1: Math.floor(Math.random() * 1000) + 100,
- value2: Math.floor(Math.random() * 800) + 50,
- value3: Math.floor(Math.random() * 600) + 30,
- }));
-};
-
-const generateTimeSeriesData = (days: number) => {
- const startDate = new Date("2024-01-01");
- return Array.from({ length: days }, (_, i) => {
- const date = new Date(startDate);
- date.setDate(date.getDate() + i);
- return {
- date: date.toISOString().split("T")[0],
- sales: Math.floor(Math.random() * 5000) + 1000,
- orders: Math.floor(Math.random() * 200) + 50,
- };
- });
-};
-
-// Test Data Variations
-const testData = {
- // Edge Cases
- empty: [],
- singlePoint: [{ month: "Jan", value: 100 }],
- twoPoints: [
- { month: "Jan", value: 100 },
- { month: "Feb", value: 200 },
- ],
-
- // Small Datasets
- threePoints: [
- { month: "Jan", value: 100 },
- { month: "Feb", value: 150 },
- { month: "Mar", value: 120 },
- ],
- fivePoints: [
- { month: "Jan", desktop: 150, mobile: 90 },
- { month: "Feb", desktop: 280, mobile: 180 },
- { month: "Mar", desktop: 220, mobile: 140 },
- { month: "Apr", desktop: 180, mobile: 160 },
- { month: "May", desktop: 250, mobile: 120 },
- ],
-
- // Medium Datasets
- twelvePoints: [
- { month: "Jan", desktop: 150, mobile: 90, tablet: 120 },
- { month: "Feb", desktop: 280, mobile: 180, tablet: 140 },
- { month: "Mar", desktop: 220, mobile: 140, tablet: 160 },
- { month: "Apr", desktop: 180, mobile: 160, tablet: 180 },
+// πŸ”₯ COMPREHENSIVE DATA VARIATIONS - Designed to test various scenarios
+const dataVariations = {
+ default: [
+ { month: "January", desktop: 150, mobile: 90, tablet: 120 },
+ { month: "February", desktop: 280, mobile: 180, tablet: 140 },
+ { month: "March", desktop: 220, mobile: 140, tablet: 160 },
+ { month: "April", desktop: 180, mobile: 160, tablet: 180 },
{ month: "May", desktop: 250, mobile: 120, tablet: 140 },
- { month: "Jun", desktop: 300, mobile: 180, tablet: 160 },
- { month: "Jul", desktop: 320, mobile: 200, tablet: 180 },
- { month: "Aug", desktop: 290, mobile: 170, tablet: 150 },
- { month: "Sep", desktop: 310, mobile: 190, tablet: 170 },
- { month: "Oct", desktop: 280, mobile: 160, tablet: 140 },
- { month: "Nov", desktop: 350, mobile: 210, tablet: 190 },
- { month: "Dec", desktop: 400, mobile: 250, tablet: 220 },
- ],
-
- // Large Datasets
- large50: generateLargeDataset(50),
- large100: generateLargeDataset(100),
- large500: generateLargeDataset(500),
-
- // Special Value Cases
- allZeros: [
- { month: "Jan", value: 0 },
- { month: "Feb", value: 0 },
- { month: "Mar", value: 0 },
- { month: "Apr", value: 0 },
+ { month: "June", desktop: 300, mobile: 180, tablet: 160 },
+ { month: "July", desktop: 350, mobile: 220, tablet: 180 },
+ { month: "August", desktop: 400, mobile: 240, tablet: 200 },
+ { month: "September", desktop: 450, mobile: 260, tablet: 220 },
+ { month: "October", desktop: 500, mobile: 280, tablet: 240 },
+ { month: "November", desktop: 550, mobile: 300, tablet: 260 },
+ { month: "December", desktop: 600, mobile: 320, tablet: 280 },
],
- withZeros: [
- { month: "Jan", desktop: 100, mobile: 0 },
- { month: "Feb", desktop: 0, mobile: 50 },
- { month: "Mar", desktop: 150, mobile: 0 },
- { month: "Apr", desktop: 0, mobile: 100 },
+ // 🏷️ BIG LABELS - Testing angled tick labels
+ bigLabels: [
+ {
+ category: "Very Long Category Name That Should Be Truncated",
+ sales: 150,
+ revenue: 90,
+ profit: 120,
+ },
+ {
+ category: "Another Extremely Long Label That Causes Collisions",
+ sales: 280,
+ revenue: 180,
+ profit: 140,
+ },
+ {
+ category: "Super Duper Long Category Name That Tests Truncation",
+ sales: 220,
+ revenue: 140,
+ profit: 160,
+ },
+ {
+ category: "Incredibly Long Text That Should Trigger Collision Detection",
+ sales: 180,
+ revenue: 160,
+ profit: 180,
+ },
+ {
+ category: "Maximum Length Category Name That Tests All Edge Cases",
+ sales: 250,
+ revenue: 120,
+ profit: 140,
+ },
+ {
+ category: "Extra Long Business Category Name With Many Words",
+ sales: 300,
+ revenue: 180,
+ profit: 160,
+ },
+ {
+ category: "Comprehensive Long Label For Testing Horizontal Offset",
+ sales: 350,
+ revenue: 220,
+ profit: 180,
+ },
+ {
+ category: "Extended Category Name That Pushes Truncation Limits",
+ sales: 400,
+ revenue: 240,
+ profit: 200,
+ },
],
- negativeValues: [
- { month: "Jan", profit: -50, loss: -30 },
- { month: "Feb", profit: 100, loss: -20 },
- { month: "Mar", profit: -30, loss: -40 },
- { month: "Apr", profit: 150, loss: -10 },
+ // πŸ“… DENSE TIMELINE - Many items with medium-length labels
+ denseTimeline: [
+ { period: "Q1 2022 Jan-Mar", visitors: 120, conversions: 15, revenue: 1200 },
+ { period: "Q1 2022 Apr-Jun", visitors: 150, conversions: 22, revenue: 1800 },
+ { period: "Q2 2022 Jul-Sep", visitors: 180, conversions: 28, revenue: 2100 },
+ { period: "Q2 2022 Oct-Dec", visitors: 200, conversions: 35, revenue: 2500 },
+ { period: "Q3 2023 Jan-Mar", visitors: 160, conversions: 18, revenue: 1600 },
+ { period: "Q3 2023 Apr-Jun", visitors: 190, conversions: 32, revenue: 2300 },
+ { period: "Q4 2023 Jul-Sep", visitors: 220, conversions: 40, revenue: 2800 },
+ { period: "Q4 2023 Oct-Dec", visitors: 240, conversions: 45, revenue: 3200 },
+ { period: "Q1 2024 Jan-Mar", visitors: 210, conversions: 38, revenue: 2700 },
+ { period: "Q1 2024 Apr-Jun", visitors: 230, conversions: 42, revenue: 3000 },
+ { period: "Q2 2024 Jul-Sep", visitors: 250, conversions: 48, revenue: 3400 },
+ { period: "Q2 2024 Oct-Dec", visitors: 270, conversions: 52, revenue: 3800 },
+ { period: "Q3 2024 Jan-Mar", visitors: 260, conversions: 50, revenue: 3600 },
+ { period: "Q3 2024 Apr-Jun", visitors: 280, conversions: 55, revenue: 4000 },
+ { period: "Q4 2024 Jul-Sep", visitors: 300, conversions: 60, revenue: 4300 },
+ { period: "Q4 2024 Oct-Dec", visitors: 290, conversions: 58, revenue: 4100 },
],
- mixedValues: [
- { month: "Jan", value1: -100, value2: 200 },
- { month: "Feb", value1: 150, value2: -50 },
- { month: "Mar", value1: -75, value2: 300 },
- { month: "Apr", value1: 200, value2: -100 },
+ // 🏒 COMPANY NAMES - Real-world long business names
+ companyNames: [
+ { company: "Apple Inc.", revenue: 394328000000, profit: 99803000000, marketCap: 3500000000000 },
+ {
+ company: "Microsoft Corporation",
+ revenue: 211915000000,
+ profit: 83383000000,
+ marketCap: 2800000000000,
+ },
+ {
+ company: "Alphabet Inc. (Google)",
+ revenue: 307394000000,
+ profit: 76033000000,
+ marketCap: 2100000000000,
+ },
+ {
+ company: "Amazon.com Inc.",
+ revenue: 574785000000,
+ profit: 33364000000,
+ marketCap: 1600000000000,
+ },
+ {
+ company: "Tesla Motors Inc.",
+ revenue: 96773000000,
+ profit: 15000000000,
+ marketCap: 800000000000,
+ },
+ {
+ company: "Meta Platforms Inc.",
+ revenue: 134902000000,
+ profit: 39370000000,
+ marketCap: 900000000000,
+ },
+ {
+ company: "NVIDIA Corporation",
+ revenue: 60922000000,
+ profit: 29760000000,
+ marketCap: 1800000000000,
+ },
+ {
+ company: "Berkshire Hathaway Inc.",
+ revenue: 364482000000,
+ profit: 96223000000,
+ marketCap: 780000000000,
+ },
],
-
- // Extreme Values
- veryLarge: [
- { month: "Jan", value: 1000000, secondary: 500000 },
- { month: "Feb", value: 1500000, secondary: 750000 },
- { month: "Mar", value: 1200000, secondary: 600000 },
+ // 🌍 COUNTRY NAMES - Geographic labels with varying lengths
+ countryData: [
+ { country: "United States of America", population: 331900000, gdp: 26900000000000 },
+ { country: "People's Republic of China", population: 1412000000, gdp: 17700000000000 },
+ { country: "Federal Republic of Germany", population: 83200000, gdp: 4300000000000 },
+ { country: "United Kingdom of Great Britain", population: 67500000, gdp: 3100000000000 },
+ { country: "French Republic", population: 68000000, gdp: 2900000000000 },
+ { country: "Republic of India", population: 1380000000, gdp: 3700000000000 },
+ { country: "Federative Republic of Brazil", population: 215000000, gdp: 2100000000000 },
+ { country: "Russian Federation", population: 146000000, gdp: 1800000000000 },
],
- verySmall: [
- { month: "Jan", value: 0.001, secondary: 0.002 },
- { month: "Feb", value: 0.003, secondary: 0.0015 },
- { month: "Mar", value: 0.002, secondary: 0.0025 },
+ // πŸ“ˆ FINANCIAL QUARTERS - Testing medium-density scenarios
+ financialQuarters: [
+ { quarter: "Q1 FY2022", revenue: 1200000, expenses: 800000, profit: 400000 },
+ { quarter: "Q2 FY2022", revenue: 1500000, expenses: 950000, profit: 550000 },
+ { quarter: "Q3 FY2022", revenue: 1800000, expenses: 1100000, profit: 700000 },
+ { quarter: "Q4 FY2022", revenue: 2000000, expenses: 1300000, profit: 700000 },
+ { quarter: "Q1 FY2023", revenue: 2200000, expenses: 1400000, profit: 800000 },
+ { quarter: "Q2 FY2023", revenue: 2500000, expenses: 1600000, profit: 900000 },
+ { quarter: "Q3 FY2023", revenue: 2800000, expenses: 1800000, profit: 1000000 },
+ { quarter: "Q4 FY2023", revenue: 3000000, expenses: 1900000, profit: 1100000 },
],
- wideRange: [
- { month: "Jan", small: 1, large: 1000000 },
- { month: "Feb", small: 2, large: 1500000 },
- { month: "Mar", small: 1.5, large: 1200000 },
+ // πŸ”€ MIXED LENGTHS - Testing various label length scenarios
+ mixedLengths: [
+ { item: "A", valueA: 100, valueB: 80 },
+ { item: "Short", valueA: 150, valueB: 120 },
+ { item: "Medium Length Item", valueA: 200, valueB: 160 },
+ { item: "Very Long Item Name That Tests Truncation", valueA: 250, valueB: 200 },
+ { item: "B", valueA: 180, valueB: 140 },
+ { item: "Another Really Long Category Name", valueA: 220, valueB: 180 },
+ { item: "XL", valueA: 190, valueB: 150 },
],
-
- // Pattern Tests
- linear: Array.from({ length: 10 }, (_, i) => ({
- x: `pat${i + 1}`,
- y: i * 10,
- })),
- exponential: Array.from({ length: 10 }, (_, i) => ({
- x: `pat${i + 1}`,
- y: Math.pow(2, i),
- })),
- sinusoidal: Array.from({ length: 20 }, (_, i) => ({
- x: `pat${i + 1}`,
- y: Math.sin(i / 3) * 100 + 150,
- })),
- constant: Array.from({ length: 8 }, (_, i) => ({
- x: `pat${i + 1}`,
- y: 100,
- })),
- volatile: Array.from({ length: 15 }, (_, i) => ({
- x: `pat${i + 1}`,
- spike: i % 3 === 0 ? 500 : 50,
- normal: 100 + Math.random() * 20,
- })),
-
- // Real-world Scenarios
- dailySales: generateTimeSeriesData(30),
- quarterlySales: [
- { quarter: "Q1 2023", revenue: 12000, profit: 4000, costs: 8000 },
- { quarter: "Q2 2023", revenue: 15000, profit: 5500, costs: 9500 },
- { quarter: "Q3 2023", revenue: 18000, profit: 7000, costs: 11000 },
- { quarter: "Q4 2023", revenue: 20000, profit: 7000, costs: 13000 },
- { quarter: "Q1 2024", revenue: 22000, profit: 8000, costs: 14000 },
+ // 🎯 EDGE CASES - Extreme scenarios
+ edgeCases: [
+ {
+ name: "SinglePointDataSetForTestingEdgeCasesInCollisionDetectionAndLabelTruncationFunctionality",
+ value: 500,
+ },
+ {
+ name: "SecondExtremelyLongDataPointNameThatShouldDefinitelyTriggerTruncationMechanisms",
+ value: 600,
+ },
],
- weeklyTraffic: [
- { day: "Mon", visits: 2200, conversions: 180, bounces: 800 },
- { day: "Tue", visits: 2500, conversions: 220, bounces: 900 },
- { day: "Wed", visits: 2300, conversions: 190, bounces: 850 },
- { day: "Thu", visits: 2800, conversions: 250, bounces: 1000 },
- { day: "Fri", visits: 3200, conversions: 280, bounces: 1100 },
- { day: "Sat", visits: 1800, conversions: 120, bounces: 600 },
- { day: "Sun", visits: 1500, conversions: 100, bounces: 500 },
+ // πŸ“± MINIMAL - Small dataset for baseline testing
+ minimal: [
+ { category: "Mobile Devices", users: 150, sessions: 90 },
+ { category: "Desktop Computers", users: 280, sessions: 180 },
+ { category: "Tablet Devices", users: 220, sessions: 140 },
],
};
+// Category key mappings for different datasets
+const categoryKeys = {
+ default: "month",
+ bigLabels: "category",
+ denseTimeline: "period",
+ companyNames: "company",
+ countryData: "country",
+ financialQuarters: "quarter",
+ mixedLengths: "item",
+ edgeCases: "name",
+ minimal: "category",
+};
+
+// πŸ”₯ ACTIVE DATA - For backward compatibility
+const lineChartCondensedData = dataVariations.default;
+
const icons = {
desktop: Monitor,
mobile: TabletSmartphone,
tablet: Calendar,
- revenue: Globe,
- profit: Smartphone,
- visits: Monitor,
- conversions: Laptop,
- value: Monitor,
- value1: Monitor,
- value2: TabletSmartphone,
- value3: Calendar,
- small: Smartphone,
- large: Globe,
sales: Globe,
- orders: Laptop,
- bounces: Calendar,
- costs: Smartphone,
+ revenue: Smartphone,
+ profit: Laptop,
+ visitors: Tv,
+ conversions: Watch,
+ users: Monitor,
+ sessions: TabletSmartphone,
+ expenses: Calendar,
+ marketCap: Globe,
+ population: Monitor,
+ gdp: Smartphone,
+ valueA: Monitor,
+ valueB: TabletSmartphone,
+ value: Calendar,
} as const;
/**
- * # LineChartCondensed Test Suite
+ * # LineChartCondensed Component Documentation
*
- * This file contains comprehensive test cases for the LineChartCondensed component,
- * covering edge cases, data variations, and stress testing scenarios.
+ * The LineChartCondensed is a compact version of LineChart, designed for space-constrained layouts
+ * like dashboards and sidebars. It's ideal for:
*
- * ## Test Categories
+ * - **Compact Dashboards**: Showing multiple trends in limited space
+ * - **Sidebar Analytics**: Quick trend visualization without taking up too much room
+ * - **Dense Data Display**: Efficiently showing many data points in a small area
*
- * ### 1. Edge Cases
- * - Empty data
- * - Single data point
- * - Two data points (minimum for line)
+ * ## Key Features
*
- * ### 2. Data Size Variations
- * - Small datasets (3-5 points)
- * - Medium datasets (10-20 points)
- * - Large datasets (50-500 points)
+ * ### Space-Efficient Design
+ * - **Compact Height**: Default 200px height for tight layouts
+ * - **Minimal Legend**: Legend is compact and doesn't take up vertical space
+ * - **Adjustable Tick Variants**: Choose between horizontal or angled labels for better space usage
*
- * ### 3. Value Ranges
- * - Zero values
- * - Negative values
- * - Mixed positive/negative
- * - Very large numbers (millions)
- * - Very small decimals
- * - Wide value ranges
+ * ### Flexible Label Handling
+ * - **Single Line Ticks**: Horizontal labels with automatic collision detection
+ * - **Angled Ticks**: Optimal rotation angle for longer labels that need more space
+ * - **Smart Angle Calculation**: Automatically calculates optimal rotation based on label width
*
- * ### 4. Data Patterns
- * - Linear progression
- * - Exponential growth
- * - Sinusoidal waves
- * - Constant values
- * - Volatile/spike patterns
+ * ### Interactive & Responsive
+ * - **Hover Tooltips**: Standard tooltip showing all data series
+ * - **Responsive Design**: Adapts fluidly to its container's size
+ * - **Line Customization**: Control line thickness with strokeWidth prop
*
- * ### 5. Real-world Scenarios
- * - Time series data
- * - Financial data
- * - Traffic analytics
+ * ### Customization
+ * - **Theming**: Comes with six pre-built color palettes
+ * - **Line Styles**: Supports `linear`, `natural` (smooth), and `step` interpolation
+ * - **Styling Options**: Control grid visibility, axes, stroke width, and more
*/
-const meta: Meta<LineChartCondensedProps<any>> = {
+const meta: Meta<LineChartCondensedProps<typeof lineChartCondensedData>> = {
title: "Components/Charts/LineChartCondensed",
component: LineChartCondensed,
parameters: {
@@ -223,43 +272,64 @@ const meta: Meta<LineChartCondensedProps<any>> = {
docs: {
description: {
component: `
-## Test Suite Overview
+## Installation and Basic Usage
-This comprehensive test suite validates the LineChartCondensed component across various scenarios:
-
-### Test Coverage Areas
-
-1. **Edge Cases**: Empty data, single point, minimal data
-2. **Data Size**: Small (3-5), Medium (10-20), Large (50-500+) datasets
-3. **Value Ranges**: Zeros, negatives, extremes (millions to decimals)
-4. **Data Patterns**: Linear, exponential, sinusoidal, constant, volatile
-5. **Real-world**: Time series, financial, analytics data
-
-### How to Use This Test Suite
+\`\`\`tsx
+import { LineChartCondensed } from '@crayonai/react-ui/Charts/LineChartCondensed';
-Each story represents a specific test case. Use these to:
-- Verify component behavior with different data types
-- Check rendering performance with large datasets
-- Validate handling of edge cases
-- Ensure visual consistency across variations
+const trafficData = [
+ { date: "2023-01-01", visits: 2200 },
+ { date: "2023-01-02", visits: 2500 },
+ { date: "2023-01-03", visits: 2300 },
+];
-\`\`\`tsx
-// Example: Testing with large dataset
+// Basic implementation
<LineChartCondensed
- data={testData.large100}
+ data={trafficData}
categoryKey="date"
theme="ocean"
height={200}
/>
\`\`\`
+
+## Data Structure Requirements
+
+Your data should be an array of objects. Each object must contain:
+- A **category field** (string or number): This will be used for the X-axis labels (e.g., dates, names, etc.).
+- One or more **data series fields** (number): These are the values that will be plotted on the Y-axis.
+
+\`\`\`tsx
+const salesData = [
+ { month: "January", desktop: 150, mobile: 90 },
+ { month: "February", desktop: 280, mobile: 180 },
+ { month: "March", desktop: 220, mobile: 140 },
+];
+\`\`\`
+
+## Key Differences from LineChart
+
+- **Compact**: Designed for smaller spaces with a default height of 200px
+- **No Interactive Legend**: Legend is simplified and non-interactive
+- **Tick Variants**: Supports both horizontal (singleLine) and angled labels
+- **Performance**: Optimized for quick rendering in dashboards
+- **Stroke Width Control**: Customize line thickness with strokeWidth prop
+
+## Performance Considerations
+- **Data Density**: For very large datasets, consider disabling animations
+- **Responsiveness**: The chart is fully responsive, but test label visibility on small screens
+- **Animation**: Controlled via \`isAnimationActive={false}\`
`,
},
},
},
- tags: ["dev", "autodocs"],
+ tags: ["!dev", "autodocs"],
argTypes: {
data: {
- description: "Array of data objects for the chart. Same format as LineChart.",
+ description: `
+**Required.** An array of data objects for the line chart. Each object should contain:
+- A category identifier (string/number) for the X-axis.
+- One or more numeric values for the Y-axis.
+`,
control: false,
table: {
type: { summary: "Array<Record<string, string | number>>" },
@@ -267,7 +337,8 @@ Each story represents a specific test case. Use these to:
},
},
categoryKey: {
- description: "The key in your data object for the X-axis category.",
+ description:
+ "**Required.** The key in your data object that represents the category for the X-axis.",
control: false,
table: {
type: { summary: "string" },
@@ -275,7 +346,8 @@ Each story represents a specific test case. Use these to:
},
},
theme: {
- description: "Color palette for the chart. Ignored when customPalette is provided.",
+ description:
+ "Specifies the color palette for the chart's lines and tooltips. Ignored when customPalette is provided.",
control: "select",
options: ["ocean", "orchid", "emerald", "sunset", "spectrum", "vivid"],
table: {
@@ -284,7 +356,8 @@ Each story represents a specific test case. Use these to:
},
},
customPalette: {
- description: "Custom color array. Overrides theme when provided.",
+ description:
+ "Custom array of colors to use instead of the theme palette. Overrides the theme prop when provided.",
control: "object",
table: {
type: { summary: "string[]" },
@@ -292,7 +365,7 @@ Each story represents a specific test case. Use these to:
},
},
variant: {
- description: "Line interpolation method.",
+ description: "Determines the line interpolation method, affecting the shape of the curves.",
control: "radio",
options: ["linear", "natural", "step"],
table: {
@@ -302,7 +375,7 @@ Each story represents a specific test case. Use these to:
},
tickVariant: {
description:
- "X-axis tick label style. Choose between singleLine (horizontal) or angled (-45Β°).",
+ "X-axis tick label style. Choose between 'singleLine' (horizontal) or 'angled' (rotated at optimal angle).",
control: "radio",
options: ["singleLine", "angled"],
table: {
@@ -311,15 +384,24 @@ Each story represents a specific test case. Use these to:
},
},
strokeWidth: {
- description: "Line thickness in pixels.",
- control: { type: "number", min: 1, max: 10, step: 1 },
+ description: "Line thickness in pixels. Controls the width of the line strokes.",
+ control: { type: "number", min: 1, max: 10, step: 0.5 },
table: {
defaultValue: { summary: "2" },
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: "Show or hide grid lines.",
+ description: "Toggles the visibility of the background grid lines.",
control: "boolean",
table: {
defaultValue: { summary: "true" },
@@ -327,23 +409,39 @@ Each story represents a specific test case. Use these to:
},
},
showYAxis: {
- description: "Show or hide Y-axis.",
+ description: "Toggles the visibility of the Y-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: "Enable loading animation.",
+ description: "Enables or disables the initial loading animation for the lines.",
control: "boolean",
table: {
defaultValue: { summary: "false" },
- category: "🎬 Animation",
+ category: "🎬 Animation & Interaction",
},
},
height: {
- description: "Chart height in pixels.",
+ description: "Sets a fixed height for the chart container in pixels.",
control: "number",
table: {
defaultValue: { summary: "200" },
@@ -352,7 +450,7 @@ Each story represents a specific test case. Use these to:
},
},
width: {
- description: "Chart width in pixels. Defaults to 100% of container.",
+ description: "Sets a fixed width for the chart container in pixels.",
control: "number",
table: {
type: { summary: "number" },
@@ -360,7 +458,7 @@ Each story represents a specific test case. Use these to:
},
},
className: {
- description: "Custom CSS class for the container.",
+ description: "Custom CSS class to apply to the chart's container.",
control: "text",
table: {
type: { summary: "string" },
@@ -373,753 +471,484 @@ Each story represents a specific test case. Use these to:
export default meta;
type Story = StoryObj<typeof meta>;
-// ============================================================================
-// EDGE CASES - Testing component behavior with minimal/unusual data
-// ============================================================================
-
/**
- * ## TEST: Empty Data
+ * ## Comprehensive Data Explorer
*
- * **Purpose**: Verify component handles empty array gracefully
- * **Expected**: Should render without errors, show empty state or message
- */
-export const EdgeCase_EmptyData: Story = {
- args: {
- data: testData.empty as any,
- categoryKey: "month" as any,
- theme: "ocean",
- height: 200,
- },
- render: (args: any) => (
- <Card style={{ width: "500px", padding: "16px" }}>
- <div style={{ marginBottom: "8px", fontSize: "12px", color: "#666" }}>
- <strong>Test:</strong> Empty dataset | <strong>Data points:</strong> 0
- </div>
- <LineChartCondensed {...args} />
- </Card>
- ),
-};
-
-/**
- * ## TEST: Single Data Point
+ * This story serves as a comprehensive test suite for the LineChartCondensed component.
+ * Use the buttons to switch between various datasets designed to test edge cases in:
*
- * **Purpose**: Verify rendering with only one data point
- * **Expected**: Should render single point, may not show line
+ * - **Label Handling**: Datasets with long, dense, or overlapping labels.
+ * - **Data Density**: Scenarios with few or many data points.
+ * - **Tick Variants**: Toggle between horizontal and angled label orientations.
+ *
+ * It's an excellent tool for developers to see how the chart behaves under different conditions.
*/
-export const EdgeCase_SinglePoint: Story = {
+export const DataExplorer: Story = {
+ name: "πŸŽ›οΈ Comprehensive Data Explorer",
args: {
- data: testData.singlePoint as any,
- categoryKey: "month" as any,
+ data: lineChartCondensedData,
+ categoryKey: "month",
theme: "ocean",
+ variant: "natural",
+ tickVariant: "singleLine",
+ strokeWidth: 2,
+ grid: true,
+ isAnimationActive: false,
+ showYAxis: true,
+ xAxisLabel: "Time Period",
+ yAxisLabel: "Values",
height: 200,
},
- render: (args: any) => (
- <Card style={{ width: "500px", padding: "16px" }}>
- <div style={{ marginBottom: "8px", fontSize: "12px", color: "#666" }}>
- <strong>Test:</strong> Single point | <strong>Data points:</strong> 1
+ render: (args: any) => {
+ const [selectedDataType, setSelectedDataType] =
+ useState<keyof typeof dataVariations>("default");
+ const [tickVariant, setTickVariant] = useState<"singleLine" | "angled">("singleLine");
+
+ 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",
+ fontFamily: "monospace",
+ };
+
+ 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: "600px",
+ }}
+ >
+ <strong>🏷️ Dataset Selection:</strong>
+ <div style={{ marginTop: "8px", display: "flex", flexWrap: "wrap", gap: "4px" }}>
+ <button
+ onClick={() => setSelectedDataType("default")}
+ style={selectedDataType === "default" ? activeButtonStyle : buttonStyle}
+ >
+ πŸ“… Default (12 months)
+ </button>
+ <button
+ onClick={() => setSelectedDataType("bigLabels")}
+ style={selectedDataType === "bigLabels" ? activeButtonStyle : buttonStyle}
+ >
+ 🏷️ Big Labels
+ </button>
+ <button
+ onClick={() => setSelectedDataType("denseTimeline")}
+ style={selectedDataType === "denseTimeline" ? activeButtonStyle : buttonStyle}
+ >
+ πŸ“… Dense Timeline (16)
+ </button>
+ <button
+ onClick={() => setSelectedDataType("companyNames")}
+ style={selectedDataType === "companyNames" ? activeButtonStyle : buttonStyle}
+ >
+ 🏒 Company Names
+ </button>
+ <button
+ onClick={() => setSelectedDataType("countryData")}
+ style={selectedDataType === "countryData" ? activeButtonStyle : buttonStyle}
+ >
+ 🌍 Country Names
+ </button>
+ <button
+ onClick={() => setSelectedDataType("financialQuarters")}
+ style={selectedDataType === "financialQuarters" ? activeButtonStyle : buttonStyle}
+ >
+ πŸ“ˆ Financial Quarters
+ </button>
+ <button
+ onClick={() => setSelectedDataType("mixedLengths")}
+ style={selectedDataType === "mixedLengths" ? activeButtonStyle : buttonStyle}
+ >
+ πŸ”€ Mixed Lengths
+ </button>
+ <button
+ onClick={() => setSelectedDataType("edgeCases")}
+ style={selectedDataType === "edgeCases" ? activeButtonStyle : buttonStyle}
+ >
+ 🎯 Edge Cases
+ </button>
+ <button
+ onClick={() => setSelectedDataType("minimal")}
+ style={selectedDataType === "minimal" ? activeButtonStyle : buttonStyle}
+ >
+ πŸ“± Minimal (3 items)
+ </button>
+ </div>
+ <div style={{ marginTop: "12px" }}>
+ <strong>πŸ“ Tick Variant:</strong>
+ <div style={{ marginTop: "8px", display: "flex", gap: "4px" }}>
+ <button
+ onClick={() => setTickVariant("singleLine")}
+ style={tickVariant === "singleLine" ? activeButtonStyle : buttonStyle}
+ >
+ Horizontal Labels
+ </button>
+ <button
+ onClick={() => setTickVariant("angled")}
+ style={tickVariant === "angled" ? activeButtonStyle : buttonStyle}
+ >
+ Angled Labels
+ </button>
+ </div>
+ </div>
+ <div
+ style={{ marginTop: "12px", fontSize: "12px", color: "#666", fontFamily: "monospace" }}
+ >
+ <div>
+ <strong>Current Dataset:</strong> {selectedDataType}
+ </div>
+ <div>
+ <strong>Items:</strong> {currentData.length} | <strong>Category Key:</strong>{" "}
+ {currentCategoryKey} | <strong>Tick:</strong> {tickVariant}
+ </div>
+ </div>
+ </div>
+ <Card style={{ width: "600px" }}>
+ <LineChartCondensed
+ {...args}
+ data={currentData}
+ categoryKey={currentCategoryKey}
+ tickVariant={tickVariant}
+ />
+ </Card>
</div>
- <LineChartCondensed {...args} />
- </Card>
- ),
+ );
+ },
+ parameters: {
+ docs: {
+ description: {
+ story:
+ "**πŸŽ›οΈ Interactive Explorer:** This story allows you to explore different datasets and tick variants interactively. Use the buttons to switch between:\n\n**Datasets:**\n- **Default**: Standard 12-month data\n- **Big Labels**: Extremely long category names\n- **Dense Timeline**: Many items with medium-length labels\n- **Company Names**: Real-world business names\n- **Country Names**: Geographic labels\n- **Financial Quarters**: Quarterly financial data\n- **Mixed Lengths**: Combination of short and long labels\n- **Edge Cases**: Extreme scenarios\n- **Minimal**: Baseline with 3 items\n\n**Tick Variants:**\n- **Horizontal Labels**: Standard single-line labels with collision detection\n- **Angled Labels**: Rotated labels for better space utilization",
+ },
+ },
+ },
};
/**
- * ## TEST: Two Data Points
+ * ## Big Labels
*
- * **Purpose**: Minimum data to show a line (edge case)
- * **Expected**: Should show basic line between two points
+ * This story demonstrates the chart's ability to handle very long category labels.
+ * The angled tick variant is particularly useful here for preventing label overlap.
*/
-export const EdgeCase_TwoPoints: Story = {
+export const BigLabelsStory: Story = {
+ name: "🏷️ Big Labels (Angled Ticks)",
args: {
- data: testData.twoPoints as any,
- categoryKey: "month" as any,
+ data: dataVariations.bigLabels as any,
+ categoryKey: "category" as any,
theme: "emerald",
- height: 200,
+ variant: "natural",
+ tickVariant: "angled",
+ strokeWidth: 2,
+ grid: true,
+ isAnimationActive: false,
+ showYAxis: true,
+ height: 250,
},
render: (args: any) => (
- <Card style={{ width: "500px", padding: "16px" }}>
- <div style={{ marginBottom: "8px", fontSize: "12px", color: "#666" }}>
- <strong>Test:</strong> Two points (minimum line) | <strong>Data points:</strong> 2
- </div>
+ <Card style={{ width: "700px" }}>
<LineChartCondensed {...args} />
</Card>
),
-};
-
-// ============================================================================
-// DATA SIZE TESTS - Testing performance with different dataset sizes
-// ============================================================================
-
-/**
- * ## TEST: Small Dataset (3 points)
- *
- * **Purpose**: Verify rendering with minimal but valid data
- * **Expected**: Clean rendering, good spacing
- */
-export const DataSize_Small3Points: Story = {
- args: {
- data: testData.threePoints as any,
- categoryKey: "month" as any,
- theme: "ocean",
- height: 200,
+ parameters: {
+ docs: {
+ description: {
+ story:
+ "Tests the chart with extremely long category names. The angled tick variant automatically rotates labels at an optimal angle to prevent overlapping and maximize readability.",
+ },
+ },
},
- render: (args: any) => (
- <Card style={{ width: "400px", padding: "16px" }}>
- <div style={{ marginBottom: "8px", fontSize: "12px", color: "#666" }}>
- <strong>Test:</strong> Small dataset | <strong>Data points:</strong> 3
- </div>
- <LineChartCondensed {...args} />
- </Card>
- ),
};
/**
- * ## TEST: Small Dataset (5 points, multiple series)
+ * ## Dense Timeline
*
- * **Purpose**: Test small data with multiple data series
- * **Expected**: All series visible, good color differentiation
+ * Tests how the chart handles many data points with medium-length period labels.
+ * The angled tick variant helps display more labels without collision.
*/
-export const DataSize_Small5Points: Story = {
+export const DenseTimelineStory: Story = {
+ name: "πŸ“… Dense Timeline (Many Periods)",
args: {
- data: testData.fivePoints as any,
- categoryKey: "month" as any,
+ data: dataVariations.denseTimeline as any,
+ categoryKey: "period" as any,
theme: "sunset",
- icons,
- height: 200,
+ variant: "natural",
+ tickVariant: "angled",
+ strokeWidth: 2,
+ grid: true,
+ isAnimationActive: false,
+ showYAxis: true,
+ height: 250,
},
render: (args: any) => (
- <Card style={{ width: "450px", padding: "16px" }}>
- <div style={{ marginBottom: "8px", fontSize: "12px", color: "#666" }}>
- <strong>Test:</strong> Small dataset, 2 series | <strong>Data points:</strong> 5
- </div>
+ <Card style={{ width: "700px" }}>
<LineChartCondensed {...args} />
</Card>
),
-};
-
-/**
- * ## TEST: Medium Dataset (12 points, 3 series)
- *
- * **Purpose**: Standard use case with monthly data
- * **Expected**: Clean rendering, all points visible
- */
-export const DataSize_Medium12Points: Story = {
- args: {
- data: testData.twelvePoints as any,
- categoryKey: "month" as any,
- theme: "orchid",
- icons,
- height: 200,
+ parameters: {
+ docs: {
+ description: {
+ story:
+ "Tests how the chart handles many data points (16 periods) with medium-length labels. The angled tick variant provides better label visibility compared to horizontal labels.",
+ },
+ },
},
- render: (args: any) => (
- <Card style={{ width: "600px", padding: "16px" }}>
- <div style={{ marginBottom: "8px", fontSize: "12px", color: "#666" }}>
- <strong>Test:</strong> Medium dataset, 3 series | <strong>Data points:</strong> 12
- </div>
- <LineChartCondensed {...args} />
- </Card>
- ),
};
/**
- * ## TEST: Large Dataset (50 points)
+ * ## Company Names
*
- * **Purpose**: Test performance with larger dataset
- * **Expected**: Should handle smoothly, may need scrolling or compression
+ * This story tests the chart with real-world company names that have varying lengths.
+ * It demonstrates how the chart handles business data with naturally occurring long labels.
*/
-export const DataSize_Large50Points: Story = {
+export const CompanyNamesStory: Story = {
+ name: "🏒 Company Names (Real-world Labels)",
args: {
- data: testData.large50 as any,
- categoryKey: "date" as any,
- theme: "emerald",
+ data: dataVariations.companyNames as any,
+ categoryKey: "company" as any,
+ theme: "vivid",
+ variant: "natural",
+ tickVariant: "angled",
+ strokeWidth: 2,
+ grid: true,
+ isAnimationActive: false,
+ showYAxis: true,
height: 250,
},
render: (args: any) => (
- <Card style={{ width: "700px", padding: "16px" }}>
- <div style={{ marginBottom: "8px", fontSize: "12px", color: "#666" }}>
- <strong>Test:</strong> Large dataset, 3 series | <strong>Data points:</strong> 50
- </div>
+ <Card style={{ width: "700px" }}>
<LineChartCondensed {...args} />
</Card>
),
+ parameters: {
+ docs: {
+ description: {
+ story:
+ "Tests with real-world company names that have varying lengths. Demonstrates how the chart handles business data with naturally occurring long labels.",
+ },
+ },
+ },
};
/**
- * ## TEST: Large Dataset (100 points)
+ * ## Country Names
*
- * **Purpose**: Stress test rendering performance
- * **Expected**: Chart should remain responsive
+ * This story tests the chart with official country names, which are often long.
+ * It shows how geographic data is handled by the angled tick system.
*/
-export const DataSize_Large100Points: Story = {
+export const CountryDataStory: Story = {
+ name: "🌍 Country Names (Geographic Labels)",
args: {
- data: testData.large100 as any,
- categoryKey: "date" as any,
- theme: "vivid",
+ data: dataVariations.countryData as any,
+ categoryKey: "country" as any,
+ theme: "orchid",
+ variant: "natural",
+ tickVariant: "angled",
+ strokeWidth: 2,
+ grid: true,
+ isAnimationActive: false,
+ showYAxis: true,
height: 250,
},
render: (args: any) => (
- <Card style={{ width: "800px", padding: "16px" }}>
- <div style={{ marginBottom: "8px", fontSize: "12px", color: "#666" }}>
- <strong>Test:</strong> Large dataset, 3 series | <strong>Data points:</strong> 100
- </div>
+ <Card style={{ width: "700px" }}>
<LineChartCondensed {...args} />
</Card>
),
+ parameters: {
+ docs: {
+ description: {
+ story:
+ "Tests with official country names that include full formal names. Shows how geographic data with naturally long names is handled.",
+ },
+ },
+ },
};
/**
- * ## TEST: Very Large Dataset (500 points)
+ * ## Mixed Lengths
*
- * **Purpose**: Maximum stress test for performance
- * **Expected**: Should handle without crashing, check render time
+ * This story tests the chart's ability to handle a mix of very short and very long labels
+ * within the same dataset, demonstrating its adaptive behavior.
*/
-export const DataSize_VeryLarge500Points: Story = {
+export const MixedLengthsStory: Story = {
+ name: "πŸ”€ Mixed Lengths (Varied Label Sizes)",
args: {
- data: testData.large500 as any,
- categoryKey: "date" as any,
+ data: dataVariations.mixedLengths as any,
+ categoryKey: "item" as any,
theme: "spectrum",
- height: 300,
+ variant: "linear",
+ tickVariant: "singleLine",
+ strokeWidth: 2,
+ grid: true,
+ isAnimationActive: false,
showYAxis: true,
+ height: 200,
},
render: (args: any) => (
- <Card style={{ width: "1000px", padding: "16px" }}>
- <div style={{ marginBottom: "8px", fontSize: "12px", color: "#666" }}>
- <strong>⚠️ Stress Test:</strong> Very large dataset | <strong>Data points:</strong> 500
- </div>
+ <Card style={{ width: "500px" }}>
<LineChartCondensed {...args} />
</Card>
),
+ parameters: {
+ docs: {
+ description: {
+ story:
+ "Tests the chart's ability to handle a mix of very short and very long labels within the same dataset.",
+ },
+ },
+ },
};
-// ============================================================================
-// VALUE RANGE TESTS - Testing different value types and ranges
-// ============================================================================
-
/**
- * ## TEST: All Zero Values
+ * ## Edge Cases
*
- * **Purpose**: Verify behavior when all values are zero
- * **Expected**: Should show flat line at zero
+ * This story tests extreme edge cases with exceptionally long labels and minimal data points.
*/
-export const ValueRange_AllZeros: Story = {
+export const EdgeCasesStory: Story = {
+ name: "🎯 Edge Cases (Extreme Scenarios)",
args: {
- data: testData.allZeros as any,
- categoryKey: "month" as any,
+ data: dataVariations.edgeCases as any,
+ categoryKey: "name" as any,
theme: "ocean",
- height: 200,
+ variant: "step",
+ tickVariant: "angled",
+ strokeWidth: 2,
+ grid: true,
+ isAnimationActive: false,
+ showYAxis: true,
+ height: 250,
},
render: (args: any) => (
- <Card style={{ width: "400px", padding: "16px" }}>
- <div style={{ marginBottom: "8px", fontSize: "12px", color: "#666" }}>
- <strong>Test:</strong> All zero values
- </div>
+ <Card style={{ width: "500px" }}>
<LineChartCondensed {...args} />
</Card>
),
+ parameters: {
+ docs: {
+ description: {
+ story:
+ "Tests extreme edge cases with exceptionally long labels and minimal data points. Pushes the label handling system to its limits.",
+ },
+ },
+ },
};
/**
- * ## TEST: Mixed Zeros in Series
+ * ## Minimal Data
*
- * **Purpose**: Test handling of zero values mixed with non-zero
- * **Expected**: Should handle gaps/zeros gracefully
+ * A baseline test with a small dataset and standard-length labels. This serves as a control
+ * case to compare against the more complex label scenarios.
*/
-export const ValueRange_WithZeros: Story = {
+export const MinimalDataStory: Story = {
+ name: "πŸ“± Minimal Data (Baseline)",
args: {
- data: testData.withZeros as any,
- categoryKey: "month" as any,
+ data: dataVariations.minimal as any,
+ categoryKey: "category" as any,
theme: "emerald",
- icons,
+ variant: "natural",
+ tickVariant: "singleLine",
+ strokeWidth: 2,
+ grid: true,
+ isAnimationActive: false,
+ showYAxis: true,
height: 200,
},
render: (args: any) => (
- <Card style={{ width: "450px", padding: "16px" }}>
- <div style={{ marginBottom: "8px", fontSize: "12px", color: "#666" }}>
- <strong>Test:</strong> Zeros mixed with values
- </div>
+ <Card style={{ width: "400px" }}>
<LineChartCondensed {...args} />
</Card>
),
-};
-
-/**
- * ## TEST: Negative Values
- *
- * **Purpose**: Verify handling of negative numbers
- * **Expected**: Should display below zero line correctly
- */
-export const ValueRange_Negative: Story = {
- args: {
- data: testData.negativeValues as any,
- categoryKey: "month" as any,
- theme: "sunset",
- height: 200,
+ parameters: {
+ docs: {
+ description: {
+ story:
+ "Baseline test with minimal data and standard-length labels. Provides a control case to compare against complex scenarios.",
+ },
+ },
},
- render: (args: any) => (
- <Card style={{ width: "450px", padding: "16px" }}>
- <div style={{ marginBottom: "8px", fontSize: "12px", color: "#666" }}>
- <strong>Test:</strong> Negative values
- </div>
- <LineChartCondensed {...args} />
- </Card>
- ),
};
/**
- * ## TEST: Mixed Positive/Negative
+ * ## Custom Palette
*
- * **Purpose**: Test combination of positive and negative values
- * **Expected**: Should show crossing zero line
+ * This story demonstrates how to use the customPalette prop to provide your own color scheme
+ * for the chart. This is useful when you need to match your brand colors.
*/
-export const ValueRange_Mixed: Story = {
+export const CustomPaletteStory: Story = {
+ name: "🎨 Custom Palette",
args: {
- data: testData.mixedValues as any,
+ data: dataVariations.default as any,
categoryKey: "month" as any,
- theme: "orchid",
- height: 200,
- },
- render: (args: any) => (
- <Card style={{ width: "450px", padding: "16px" }}>
- <div style={{ marginBottom: "8px", fontSize: "12px", color: "#666" }}>
- <strong>Test:</strong> Mixed positive/negative values
- </div>
- <LineChartCondensed {...args} />
- </Card>
- ),
-};
-
-/**
- * ## TEST: Very Large Numbers (Millions)
- *
- * **Purpose**: Test formatting and display of large numbers
- * **Expected**: Should format with appropriate abbreviations (K, M, B)
- */
-export const ValueRange_VeryLarge: Story = {
- args: {
- data: testData.veryLarge as any,
- categoryKey: "month" as any,
- theme: "vivid",
- height: 200,
- },
- render: (args: any) => (
- <Card style={{ width: "450px", padding: "16px" }}>
- <div style={{ marginBottom: "8px", fontSize: "12px", color: "#666" }}>
- <strong>Test:</strong> Very large numbers (millions)
- </div>
- <LineChartCondensed {...args} />
- </Card>
- ),
-};
-
-/**
- * ## TEST: Very Small Decimals
- *
- * **Purpose**: Test precision handling for small decimal values
- * **Expected**: Should display appropriate decimal precision
- */
-export const ValueRange_VerySmall: Story = {
- args: {
- data: testData.verySmall as any,
- categoryKey: "month" as any,
- theme: "emerald",
- height: 200,
- },
- render: (args: any) => (
- <Card style={{ width: "450px", padding: "16px" }}>
- <div style={{ marginBottom: "8px", fontSize: "12px", color: "#666" }}>
- <strong>Test:</strong> Very small decimal values
- </div>
- <LineChartCondensed {...args} />
- </Card>
- ),
-};
-
-/**
- * ## TEST: Wide Value Range
- *
- * **Purpose**: Test scaling when series have vastly different magnitudes
- * **Expected**: Should scale appropriately or show warning
- */
-export const ValueRange_WideRange: Story = {
- args: {
- data: testData.wideRange as any,
- categoryKey: "month" as any,
- theme: "spectrum",
- height: 200,
- },
- render: (args: any) => (
- <Card style={{ width: "500px", padding: "16px" }}>
- <div style={{ marginBottom: "8px", fontSize: "12px", color: "#666" }}>
- <strong>Test:</strong> Wide range (1 to 1,000,000)
- </div>
- <LineChartCondensed {...args} />
- </Card>
- ),
-};
-
-// ============================================================================
-// PATTERN TESTS - Testing different data patterns and shapes
-// ============================================================================
-
-/**
- * ## TEST: Linear Progression
- *
- * **Purpose**: Verify rendering of linear increasing data
- * **Expected**: Clean straight line progression
- */
-export const Pattern_Linear: Story = {
- args: {
- data: testData.linear as any,
- categoryKey: "x" as any,
- theme: "ocean",
- variant: "linear",
- height: 200,
- },
- render: (args: any) => (
- <Card style={{ width: "500px", padding: "16px" }}>
- <div style={{ marginBottom: "8px", fontSize: "12px", color: "#666" }}>
- <strong>Test:</strong> Linear progression pattern
- </div>
- <LineChartCondensed {...args} />
- </Card>
- ),
-};
-
-/**
- * ## TEST: Exponential Growth
- *
- * **Purpose**: Test rendering of exponentially increasing values
- * **Expected**: Should handle steep curve and wide Y-axis range
- */
-export const Pattern_Exponential: Story = {
- args: {
- data: testData.exponential as any,
- categoryKey: "x" as any,
- theme: "emerald",
- variant: "natural",
- height: 200,
- },
- render: (args: any) => (
- <Card style={{ width: "500px", padding: "16px" }}>
- <div style={{ marginBottom: "8px", fontSize: "12px", color: "#666" }}>
- <strong>Test:</strong> Exponential growth pattern
- </div>
- <LineChartCondensed {...args} />
- </Card>
- ),
-};
-
-/**
- * ## TEST: Sinusoidal Wave
- *
- * **Purpose**: Test smooth curves with wave pattern
- * **Expected**: Natural variant should show smooth sine wave
- */
-export const Pattern_Sinusoidal: Story = {
- args: {
- data: testData.sinusoidal as any,
- categoryKey: "x" as any,
- theme: "orchid",
- variant: "natural",
- height: 200,
- },
- render: (args: any) => (
- <Card style={{ width: "600px", padding: "16px" }}>
- <div style={{ marginBottom: "8px", fontSize: "12px", color: "#666" }}>
- <strong>Test:</strong> Sinusoidal wave pattern
- </div>
- <LineChartCondensed {...args} />
- </Card>
- ),
-};
-
-/**
- * ## TEST: Constant Values
- *
- * **Purpose**: Test behavior with no variation in data
- * **Expected**: Flat horizontal line
- */
-export const Pattern_Constant: Story = {
- args: {
- data: testData.constant as any,
- categoryKey: "x" as any,
- theme: "sunset",
- height: 200,
- },
- render: (args: any) => (
- <Card style={{ width: "450px", padding: "16px" }}>
- <div style={{ marginBottom: "8px", fontSize: "12px", color: "#666" }}>
- <strong>Test:</strong> Constant value pattern
- </div>
- <LineChartCondensed {...args} />
- </Card>
- ),
-};
-
-/**
- * ## TEST: Volatile/Spike Pattern
- *
- * **Purpose**: Test rendering of data with extreme spikes
- * **Expected**: Should handle spikes without distortion
- */
-export const Pattern_Volatile: Story = {
- args: {
- data: testData.volatile as any,
- categoryKey: "x" as any,
- theme: "vivid",
- height: 200,
- },
- render: (args: any) => (
- <Card style={{ width: "550px", padding: "16px" }}>
- <div style={{ marginBottom: "8px", fontSize: "12px", color: "#666" }}>
- <strong>Test:</strong> Volatile pattern with spikes
- </div>
- <LineChartCondensed {...args} />
- </Card>
- ),
-};
-
-// ============================================================================
-// REAL-WORLD SCENARIO TESTS - Practical use cases
-// ============================================================================
-
-/**
- * ## TEST: Daily Time Series (30 days)
- *
- * **Purpose**: Test typical time-series sales data
- * **Expected**: Clean rendering of date-based data
- */
-export const RealWorld_DailySales: Story = {
- args: {
- data: testData.dailySales as any,
- categoryKey: "date" as any,
- theme: "ocean",
- icons,
- height: 220,
- },
- render: (args: any) => (
- <Card style={{ width: "700px", padding: "16px" }}>
- <div style={{ marginBottom: "8px", fontSize: "12px", color: "#666" }}>
- <strong>Test:</strong> Daily sales time series | <strong>Days:</strong> 30
- </div>
- <LineChartCondensed {...args} />
- </Card>
- ),
-};
-
-/**
- * ## TEST: Quarterly Financial Data
- *
- * **Purpose**: Test financial reporting scenario
- * **Expected**: Clear visualization of revenue, profit, costs
- */
-export const RealWorld_QuarterlySales: Story = {
- args: {
- data: testData.quarterlySales as any,
- categoryKey: "quarter" as any,
- theme: "emerald",
- icons,
- height: 220,
- },
- render: (args: any) => (
- <Card style={{ width: "600px", padding: "16px" }}>
- <div style={{ marginBottom: "8px", fontSize: "12px", color: "#666" }}>
- <strong>Test:</strong> Quarterly financial data | <strong>Quarters:</strong> 5
- </div>
- <LineChartCondensed {...args} />
- </Card>
- ),
-};
-
-/**
- * ## TEST: Weekly Analytics Traffic
- *
- * **Purpose**: Test typical analytics dashboard data
- * **Expected**: Multiple metrics clearly differentiated
- */
-export const RealWorld_WeeklyTraffic: Story = {
- args: {
- data: testData.weeklyTraffic as any,
- categoryKey: "day" as any,
- theme: "sunset",
- icons,
- height: 220,
- },
- render: (args: any) => (
- <Card style={{ width: "650px", padding: "16px" }}>
- <div style={{ marginBottom: "8px", fontSize: "12px", color: "#666" }}>
- <strong>Test:</strong> Weekly traffic analytics | <strong>Metrics:</strong> 3
- </div>
- <LineChartCondensed {...args} />
- </Card>
- ),
-};
-
-// ============================================================================
-// VARIANT & CONFIGURATION TESTS
-// ============================================================================
-
-/**
- * ## TEST: Variant Comparison
- *
- * **Purpose**: Compare all interpolation variants side-by-side
- * **Expected**: Visual difference between linear, natural, step
- */
-export const Config_VariantComparison: Story = {
- render: () => (
- <div style={{ display: "flex", flexDirection: "column", gap: "16px" }}>
- <Card style={{ width: "600px", padding: "16px" }}>
- <div style={{ marginBottom: "8px", fontSize: "12px", color: "#666" }}>
- <strong>Variant:</strong> Linear
- </div>
- <LineChartCondensed
- data={testData.twelvePoints as any}
- categoryKey="month"
- variant="linear"
- theme="ocean"
- height={150}
- />
- </Card>
- <Card style={{ width: "600px", padding: "16px" }}>
- <div style={{ marginBottom: "8px", fontSize: "12px", color: "#666" }}>
- <strong>Variant:</strong> Natural (smooth)
- </div>
- <LineChartCondensed
- data={testData.twelvePoints as any}
- categoryKey="month"
- variant="natural"
- theme="emerald"
- height={150}
- />
- </Card>
- <Card style={{ width: "600px", padding: "16px" }}>
- <div style={{ marginBottom: "8px", fontSize: "12px", color: "#666" }}>
- <strong>Variant:</strong> Step
- </div>
- <LineChartCondensed
- data={testData.twelvePoints as any}
- categoryKey="month"
- variant="step"
- theme="sunset"
- height={150}
- />
- </Card>
- </div>
- ),
-};
-
-/**
- * ## TEST: Stroke Width Variations
- *
- * **Purpose**: Test different line thicknesses
- * **Expected**: Clear visual difference in line width
- */
-export const Config_StrokeWidthVariations: Story = {
- render: () => (
- <div style={{ display: "flex", flexDirection: "column", gap: "16px" }}>
- <Card style={{ width: "600px", padding: "16px" }}>
- <div style={{ marginBottom: "8px", fontSize: "12px", color: "#666" }}>
- <strong>Stroke Width:</strong> 1px (Thin)
- </div>
- <LineChartCondensed
- data={testData.twelvePoints as any}
- categoryKey="month"
- theme="ocean"
- height={150}
- strokeWidth={1}
- />
- </Card>
- <Card style={{ width: "600px", padding: "16px" }}>
- <div style={{ marginBottom: "8px", fontSize: "12px", color: "#666" }}>
- <strong>Stroke Width:</strong> 2px (Default)
- </div>
- <LineChartCondensed
- data={testData.twelvePoints as any}
- categoryKey="month"
- theme="emerald"
- height={150}
- strokeWidth={2}
- />
- </Card>
- <Card style={{ width: "600px", padding: "16px" }}>
- <div style={{ marginBottom: "8px", fontSize: "12px", color: "#666" }}>
- <strong>Stroke Width:</strong> 4px (Thick)
- </div>
- <LineChartCondensed
- data={testData.twelvePoints as any}
- categoryKey="month"
- theme="sunset"
- height={150}
- strokeWidth={4}
- />
- </Card>
- </div>
- ),
-};
-
-/**
- * ## TEST: Without Y-Axis
- *
- * **Purpose**: Test ultra-compact mode without Y-axis
- * **Expected**: More horizontal space, clean minimal look
- */
-export const Config_WithoutYAxis: Story = {
- args: {
- data: testData.twelvePoints as any,
- categoryKey: "month" as any,
- theme: "vivid",
- showYAxis: false,
- grid: false,
- height: 150,
- },
- render: (args: any) => (
- <Card style={{ width: "500px", padding: "16px" }}>
- <div style={{ marginBottom: "8px", fontSize: "12px", color: "#666" }}>
- <strong>Test:</strong> Y-axis hidden, grid off
- </div>
- <LineChartCondensed {...args} />
- </Card>
- ),
-};
-
-/**
- * ## TEST: Custom Color Palette
- *
- * **Purpose**: Verify custom palette override functionality
- * **Expected**: Uses custom colors instead of theme
- */
-export const Config_CustomPalette: Story = {
- args: {
- data: testData.twelvePoints as any,
- categoryKey: "month" as any,
- customPalette: ["#FF6B6B", "#4ECDC4", "#45B7D1"],
+ theme: "ocean", // This will be overridden by customPalette
+ variant: "natural",
+ tickVariant: "singleLine",
+ strokeWidth: 2,
+ grid: true,
+ isAnimationActive: false,
+ showYAxis: true,
+ xAxisLabel: "Month",
+ yAxisLabel: "Traffic",
+ customPalette: ["#FF6B6B", "#4ECDC4", "#45B7D1"],
height: 200,
},
render: (args: any) => (
<div>
<div
style={{
- marginBottom: "12px",
+ marginBottom: "16px",
padding: "12px",
background: "#f8f9fa",
borderRadius: "8px",
- width: "550px",
+ border: "1px solid #e9ecef",
+ width: "600px",
}}
>
- <strong>Custom Palette:</strong>
- <div style={{ display: "flex", gap: "8px", marginTop: "8px" }}>
+ <h4 style={{ margin: "0 0 8px 0", color: "#333" }}>🎨 Custom Color Palette</h4>
+ <p style={{ margin: "0 0 12px 0", fontSize: "14px", color: "#666" }}>
+ This chart uses a custom color palette instead of the default theme colors.
+ </p>
+ <div style={{ display: "flex", gap: "8px", flexWrap: "wrap" }}>
{args.customPalette?.map((color: string, index: number) => (
<div
key={index}
- style={{ display: "flex", alignItems: "center", gap: "4px", fontSize: "12px" }}
+ style={{
+ display: "flex",
+ alignItems: "center",
+ gap: "4px",
+ padding: "4px 8px",
+ background: "white",
+ borderRadius: "4px",
+ border: "1px solid #ddd",
+ fontSize: "12px",
+ }}
>
<div
style={{
- width: "16px",
- height: "16px",
+ width: "12px",
+ height: "12px",
+ borderRadius: "2px",
backgroundColor: color,
- borderRadius: "3px",
- border: "1px solid #ddd",
+ border: "1px solid #ccc",
}}
/>
<span style={{ fontFamily: "monospace" }}>{color}</span>
@@ -1127,212 +956,131 @@ export const Config_CustomPalette: Story = {
))}
</div>
</div>
- <Card style={{ width: "550px", padding: "16px" }}>
+ <Card style={{ width: "600px" }}>
<LineChartCondensed {...args} />
</Card>
</div>
),
+ parameters: {
+ docs: {
+ description: {
+ story:
+ 'Demonstrates how to use the `customPalette` prop to provide your own color scheme. When `customPalette` is provided, it overrides the `theme` prop.\n\n**Usage:**\n```tsx\n<LineChartCondensed\n data={data}\n categoryKey="month"\n customPalette={["#FF6B6B", "#4ECDC4", "#45B7D1"]}\n/>\n```',
+ },
+ },
+ },
};
-// ============================================================================
-// STRESS & PERFORMANCE TESTS
-// ============================================================================
-
/**
- * ## TEST: Multiple Charts Dashboard
+ * ## Stroke Width Comparison
*
- * **Purpose**: Test rendering multiple charts simultaneously
- * **Expected**: All charts render smoothly without performance issues
+ * Compare different line thickness options to find the right visual weight for your data.
*/
-export const Stress_MultipleCharts: Story = {
+export const StrokeWidthComparison: Story = {
+ name: "πŸ“ Stroke Width Comparison",
render: () => (
- <div
- style={{
- display: "grid",
- gridTemplateColumns: "repeat(2, 1fr)",
- gap: "16px",
- width: "900px",
- }}
- >
- <Card style={{ padding: "16px" }}>
- <div style={{ marginBottom: "8px", fontSize: "12px", fontWeight: "600" }}>
- Small Dataset
+ <div style={{ display: "flex", flexDirection: "column", gap: "24px" }}>
+ <Card style={{ width: "700px", padding: "16px" }}>
+ <div style={{ marginBottom: "12px" }}>
+ <div style={{ fontSize: "16px", fontWeight: "600", marginBottom: "4px" }}>
+ Thin Lines (1px)
+ </div>
+ <div style={{ fontSize: "13px", color: "#666" }}>Subtle, minimal visual weight</div>
</div>
<LineChartCondensed
- data={testData.fivePoints as any}
+ data={dataVariations.default as any}
categoryKey="month"
theme="ocean"
- height={140}
+ strokeWidth={1}
+ height={180}
/>
</Card>
- <Card style={{ padding: "16px" }}>
- <div style={{ marginBottom: "8px", fontSize: "12px", fontWeight: "600" }}>
- Medium Dataset
+ <Card style={{ width: "700px", padding: "16px" }}>
+ <div style={{ marginBottom: "12px" }}>
+ <div style={{ fontSize: "16px", fontWeight: "600", marginBottom: "4px" }}>
+ Default Lines (2px)
+ </div>
+ <div style={{ fontSize: "13px", color: "#666" }}>Balanced, standard weight</div>
</div>
<LineChartCondensed
- data={testData.twelvePoints as any}
+ data={dataVariations.default as any}
categoryKey="month"
theme="emerald"
- height={140}
+ strokeWidth={2}
+ height={180}
/>
</Card>
- <Card style={{ padding: "16px" }}>
- <div style={{ marginBottom: "8px", fontSize: "12px", fontWeight: "600" }}>
- Large Dataset (50)
+ <Card style={{ width: "700px", padding: "16px" }}>
+ <div style={{ marginBottom: "12px" }}>
+ <div style={{ fontSize: "16px", fontWeight: "600", marginBottom: "4px" }}>
+ Thick Lines (4px)
+ </div>
+ <div style={{ fontSize: "13px", color: "#666" }}>Bold, high emphasis</div>
</div>
<LineChartCondensed
- data={testData.large50 as any}
- categoryKey="date"
+ data={dataVariations.default as any}
+ categoryKey="month"
theme="sunset"
- height={140}
- />
- </Card>
- <Card style={{ padding: "16px" }}>
- <div style={{ marginBottom: "8px", fontSize: "12px", fontWeight: "600" }}>Time Series</div>
- <LineChartCondensed
- data={testData.dailySales as any}
- categoryKey="date"
- theme="orchid"
- height={140}
+ strokeWidth={4}
+ height={180}
/>
</Card>
</div>
),
- parameters: {
- docs: {
- description: {
- story: "Stress test with 4 charts rendering simultaneously with varying dataset sizes.",
- },
- },
- },
-};
-
-// Test Data for Long Labels
-const longLabelData = [
- { category: "Q1 2024 January Total Revenue and Expenses", sales: 186, expenses: 80, profit: 106 },
- {
- category: "Q1 2024 February Marketing Campaign Results",
- sales: 305,
- expenses: 200,
- profit: 105,
- },
- { category: "Q1 2024 March Product Launch Performance", sales: 237, expenses: 120, profit: 117 },
- { category: "Q2 2024 April Customer Acquisition Metrics", sales: 273, expenses: 190, profit: 83 },
- { category: "Q2 2024 May Operational Efficiency Report", sales: 209, expenses: 130, profit: 79 },
- {
- category: "Q2 2024 June Strategic Initiative Outcomes",
- sales: 314,
- expenses: 140,
- profit: 174,
- },
- { category: "Q3 2024 July Market Expansion Analysis", sales: 350, expenses: 180, profit: 170 },
- {
- category: "Q3 2024 August Technology Investment Returns",
- sales: 280,
- expenses: 160,
- profit: 120,
- },
- { category: "Q3 2024 September Partnership Performance", sales: 320, expenses: 170, profit: 150 },
- { category: "Q4 2024 October Year-End Projections", sales: 290, expenses: 150, profit: 140 },
- { category: "Q4 2024 November Holiday Season Preview", sales: 340, expenses: 180, profit: 160 },
- { category: "Q4 2024 December Annual Summary Report", sales: 420, expenses: 220, profit: 200 },
-];
-
-// Tick Variant Stories
-export const TickVariantSingleLine: Story = {
- render: () => (
- <Card style={{ padding: "24px", width: "900px", maxWidth: "900px" }}>
- <div style={{ marginBottom: "16px", fontSize: "16px", fontWeight: "600" }}>
- Single Line Tick Variant
- </div>
- <div style={{ marginBottom: "8px", fontSize: "13px", color: "#666" }}>
- Standard horizontal labels with automatic collision detection
- </div>
- <LineChartCondensed
- data={longLabelData as any}
- categoryKey="category"
- tickVariant="singleLine"
- theme="ocean"
- height={200}
- />
- </Card>
- ),
parameters: {
docs: {
description: {
story:
- "Single line tick variant with standard horizontal labels. Automatically handles collision detection.",
+ "**Side-by-side comparison** of stroke widths:\n\n- **1px**: Thin, subtle lines perfect for dense data or multiple overlapping series\n- **2px**: Default weight, balanced for most use cases\n- **4px**: Thick, bold lines for high emphasis or presentations\n\n**When to use each:**\n- Use **1px** for many overlapping series or subtle trends\n- Use **2px** (default) for general purpose visualization\n- Use **4px** for presentations or when emphasizing specific trends",
},
},
},
};
-export const TickVariantAngled: Story = {
- render: () => (
- <Card style={{ padding: "24px", width: "900px", maxWidth: "900px" }}>
- <div style={{ marginBottom: "16px", fontSize: "16px", fontWeight: "600" }}>
- Angled Tick Variant
- </div>
- <div style={{ marginBottom: "8px", fontSize: "13px", color: "#666" }}>
- -45Β° rotation perfect for long labels that would overlap horizontally
- </div>
- <LineChartCondensed
- data={longLabelData as any}
- categoryKey="category"
- tickVariant="angled"
- theme="emerald"
- height={280}
- />
- </Card>
- ),
- parameters: {
- docs: {
- description: {
- story:
- "Angled tick variant with -45Β° rotation. Perfect for long labels that would overlap horizontally.",
- },
- },
- },
-};
-
-// Dense Data with Tick Variants
-const denseData = Array.from({ length: 30 }, (_, i) => ({
- day: `Day ${i + 1}`,
- revenue: Math.floor(Math.random() * 500) + 100,
- costs: Math.floor(Math.random() * 300) + 50,
-}));
-
-export const TickVariantComparisonDenseData: Story = {
+/**
+ * ## Tick Variant Comparison
+ *
+ * Side-by-side comparison of single-line (horizontal) and angled tick variants.
+ * This helps you choose the right variant for your data.
+ */
+export const TickVariantComparison: Story = {
+ name: "πŸ“ Tick Variant Comparison",
render: () => (
- <div style={{ display: "grid", gridTemplateColumns: "1fr", gap: "24px", maxWidth: "1100px" }}>
- <Card style={{ padding: "24px" }}>
- <div style={{ marginBottom: "16px", fontSize: "16px", fontWeight: "600" }}>
- Single Line Variant (Dense Data - 30 Points)
- </div>
- <div style={{ marginBottom: "8px", fontSize: "13px", color: "#666" }}>
- Recharts automatically hides overlapping labels
+ <div style={{ display: "flex", flexDirection: "column", gap: "24px" }}>
+ <Card style={{ width: "700px", padding: "16px" }}>
+ <div style={{ marginBottom: "12px" }}>
+ <div style={{ fontSize: "16px", fontWeight: "600", marginBottom: "4px" }}>
+ Single Line Variant (Horizontal)
+ </div>
+ <div style={{ fontSize: "13px", color: "#666" }}>
+ Standard horizontal labels. Recharts automatically hides overlapping labels.
+ </div>
</div>
<LineChartCondensed
- data={denseData as any}
- categoryKey="day"
+ data={dataVariations.bigLabels as any}
+ categoryKey="category"
tickVariant="singleLine"
theme="ocean"
+ strokeWidth={2}
height={200}
/>
</Card>
- <Card style={{ padding: "24px" }}>
- <div style={{ marginBottom: "16px", fontSize: "16px", fontWeight: "600" }}>
- Angled Variant (Dense Data - 30 Points)
- </div>
- <div style={{ marginBottom: "8px", fontSize: "13px", color: "#666" }}>
- Shows more labels with angled orientation
+ <Card style={{ width: "700px", padding: "16px" }}>
+ <div style={{ marginBottom: "12px" }}>
+ <div style={{ fontSize: "16px", fontWeight: "600", marginBottom: "4px" }}>
+ Angled Variant (Rotated)
+ </div>
+ <div style={{ fontSize: "13px", color: "#666" }}>
+ Automatically rotates labels at an optimal angle. Shows more labels without collision.
+ </div>
</div>
<LineChartCondensed
- data={denseData as any}
- categoryKey="day"
+ data={dataVariations.bigLabels as any}
+ categoryKey="category"
tickVariant="angled"
theme="emerald"
- height={280}
+ strokeWidth={2}
+ height={260}
/>
</Card>
</div>
@@ -1341,8 +1089,137 @@ export const TickVariantComparisonDenseData: Story = {
docs: {
description: {
story:
- "Comparison of tick variants (singleLine and angled) with dense data (30 data points). Shows how each variant handles label collision with Recharts' built-in collision detection.",
+ "**Side-by-side comparison** of tick variants:\n\n- **Single Line**: Standard horizontal labels with automatic collision detection. Recharts hides overlapping labels.\n- **Angled**: Rotates labels at an optimal angle calculated based on label width and available space. Shows more labels without collision.\n\n**When to use each:**\n- Use **singleLine** for short labels or when you have few data points\n- Use **angled** for long labels or many data points where horizontal labels would overlap",
},
},
},
};
+
+/**
+ * ## Responsive Behavior Demo
+ *
+ * This story demonstrates the responsive capabilities of the LineChartCondensed.
+ * Drag the handles on the container to resize it and observe how the chart adapts.
+ */
+export const ResponsiveBehaviorDemo: Story = {
+ name: "πŸ“± Responsive Behavior Demo",
+ args: {
+ data: dataVariations.bigLabels as any,
+ categoryKey: "category" as any,
+ theme: "sunset",
+ variant: "natural",
+ tickVariant: "angled",
+ strokeWidth: 2,
+ grid: true,
+ isAnimationActive: false,
+ showYAxis: true,
+ height: 250,
+ },
+ render: (args: any) => {
+ const [dimensions, setDimensions] = useState<{ width: number }>({
+ width: 700,
+ });
+
+ const handleMouseDown = (e: React.MouseEvent<HTMLDivElement>, handle: string) => {
+ e.preventDefault();
+ e.stopPropagation();
+ const startX = e.clientX;
+ const startWidth = dimensions.width;
+
+ const doDrag = (e: MouseEvent) => {
+ const dx = e.clientX - startX;
+ let newWidth = startWidth;
+
+ if (handle.includes("e")) newWidth = startWidth + dx;
+ if (handle.includes("w")) newWidth = startWidth - dx;
+
+ setDimensions({
+ width: Math.max(300, newWidth),
+ });
+ };
+
+ const stopDrag = () => {
+ document.removeEventListener("mousemove", doDrag);
+ document.removeEventListener("mouseup", stopDrag);
+ };
+
+ document.addEventListener("mousemove", doDrag);
+ document.addEventListener("mouseup", stopDrag);
+ };
+
+ const handleStyle: React.CSSProperties = {
+ position: "absolute",
+ background: "#3b82f6",
+ opacity: 0.6,
+ zIndex: 10,
+ transition: "opacity 0.2s ease",
+ };
+
+ return (
+ <div style={{ padding: "20px" }}>
+ <div style={{ marginBottom: "20px" }}>
+ <h3 style={{ margin: "0 0 8px 0", fontSize: "18px", fontWeight: "600" }}>
+ Responsive Behavior Demonstration
+ </h3>
+ <p style={{ margin: "0 0 12px 0", color: "#666", fontSize: "14px" }}>
+ Drag the left or right edges of the container to see how the chart adapts
+ </p>
+ <div
+ style={{
+ padding: "12px",
+ backgroundColor: "#e3f2fd",
+ borderRadius: "6px",
+ fontSize: "12px",
+ color: "#1565c0",
+ }}
+ >
+ <strong>🎯 Try This:</strong> Resize the container to see how angled labels adapt to
+ available space.
+ </div>
+ </div>
+
+ <Card
+ style={{
+ position: "relative",
+ width: `${dimensions.width}px`,
+ border: "2px dashed #9ca3af",
+ padding: "20px",
+ boxSizing: "border-box",
+ overflow: "hidden",
+ cursor: "default",
+ }}
+ >
+ <LineChartCondensed {...args} />
+
+ {/* Resize Handles */}
+ <div
+ style={{ ...handleStyle, top: 0, bottom: 0, left: -2, width: 12, cursor: "ew-resize" }}
+ onMouseDown={(e) => handleMouseDown(e, "w")}
+ />
+ <div
+ style={{ ...handleStyle, top: 0, bottom: 0, right: -2, width: 12, cursor: "ew-resize" }}
+ onMouseDown={(e) => handleMouseDown(e, "e")}
+ />
+
+ {/* Dimension Display */}
+ <div
+ style={{
+ position: "absolute",
+ bottom: 8,
+ right: 8,
+ background: "rgba(0,0,0,0.8)",
+ color: "white",
+ padding: "4px 8px",
+ borderRadius: "4px",
+ fontSize: "11px",
+ fontFamily: "monospace",
+ fontWeight: "500",
+ }}
+ >
+ {dimensions.width}px
+ </div>
+ </Card>
+ </div>
+ );
+ },
+};
diff --git a/js/packages/react-ui/src/components/Charts/hooks/useAutoAngleCalculation.ts b/js/packages/react-ui/src/components/Charts/hooks/useAutoAngleCalculation.ts
index 3d1812a46..46df941b8 100644
--- a/js/packages/react-ui/src/components/Charts/hooks/useAutoAngleCalculation.ts
+++ b/js/packages/react-ui/src/components/Charts/hooks/useAutoAngleCalculation.ts
@@ -25,6 +25,7 @@ interface AngleCalculationResult {
export const useAutoAngleCalculation = (
maxLabelWidth: number,
enabled: boolean,
+ widthOfData?: number,
): AngleCalculationResult => {
return useMemo(() => {
// If not enabled, return default values for horizontal labels
@@ -36,9 +37,8 @@ export const useAutoAngleCalculation = (
}
// Calculate the base (horizontal distance from left edge to first label anchor)
- let base = 0;
-
- base = X_AXIS_PADDING;
+ // Use widthOfData if provided (space per data point), otherwise fall back to padding
+ const base = widthOfData ?? X_AXIS_PADDING;
// The hypotenuse is the maximum label width
const hypotenuse = maxLabelWidth;
@@ -79,5 +79,5 @@ export const useAutoAngleCalculation = (
angle: -finalAngle, // Negative for counter-clockwise rotation
height: Math.max(finalHeight + 16, DEFAULT_X_AXIS_HEIGHT), // Ensure minimum height
};
- }, [maxLabelWidth, enabled]);
+ }, [maxLabelWidth, enabled, widthOfData]);
};