Skip to content

Add zIndex to bar background#6536

Merged
ckifer merged 1 commit intomainfrom
stacked-bar-background
Oct 30, 2025
Merged

Add zIndex to bar background#6536
ckifer merged 1 commit intomainfrom
stacked-bar-background

Conversation

@PavelVanecek
Copy link
Collaborator

@PavelVanecek PavelVanecek commented Oct 30, 2025

Description

This is a problem in stacked charts so why not fix it now that we have the technology.

Related Issue

Fixes #2826

Types of changes

  • Bug fix (non-breaking change which fixes an issue)
  • New feature (non-breaking change which adds functionality)
  • Breaking change (fix or feature that would cause existing functionality to change)

Checklist:

  • My change requires a change to the documentation.
  • I have updated the documentation accordingly.
  • I have added tests to cover my changes.
  • I have added a storybook story or VR test, or extended an existing story or VR test to show my changes

Summary by CodeRabbit

Release Notes

  • New Features
    • Bar and RadialBar components now properly layer background elements with correct z-index ordering, ensuring backgrounds appear behind other chart elements.
    • Updated documentation examples to demonstrate background rendering in stacked bar charts.

@coderabbitai
Copy link
Contributor

coderabbitai bot commented Oct 30, 2025

Walkthrough

The PR adds z-index layering support for bar backgrounds in both Cartesian and polar coordinate systems. It introduces a new default z-index value (barBackground: -50) and updates Bar and RadialBar components to render their backgrounds within a ZIndexLayer, ensuring proper layering order. Tests are updated to reflect the new z-index value, and an example component demonstrates the feature.

Changes

Cohort / File(s) Summary
Z-index infrastructure
src/zindex/DefaultZIndexes.tsx
Added new public z-index entry barBackground: -50 for bar/radial bar backgrounds.
Cartesian bar rendering
src/cartesian/Bar.tsx
Introduced getZIndex() helper; wrapped BarBackground rendering in ZIndexLayer using computed z-index from props or default value.
Polar bar rendering
src/polar/RadialBar.tsx
Added getZIndexForRadialBarBackground() helper; refactored renderBackground() to wrap radial bar sectors in ZIndexLayer with computed z-index.
Test updates
test/zindex/zIndexSelectors.spec.ts
Updated expected z-index arrays across all test scenarios to include the new barBackground: -50 value.
Example component
www/src/docs/exampleComponents/BarChart/StackedBarChart.tsx
Added background prop to both stacked bar components (pv and uv bars).

Estimated code review effort

🎯 2 (Simple) | ⏱️ ~12 minutes

  • RadialBar.tsx may require slightly more attention due to the refactoring of renderBackground() logic and key adjustment.
  • Verify that the z-index layering order does not introduce unintended visual regressions in edge cases (e.g., overlapping bars with multiple backgrounds).

Possibly related PRs

  • zIndex #6479: Introduces the z-index system with ZIndexLayer and DefaultZIndexes infrastructure that these changes directly extend.

Suggested labels

enhancement, feature request

Suggested reviewers

  • ckifer

Pre-merge checks and finishing touches

❌ Failed checks (1 warning, 1 inconclusive)
Check name Status Explanation Resolution
Docstring Coverage ⚠️ Warning Docstring coverage is 0.00% which is insufficient. The required threshold is 80.00%. You can run @coderabbitai generate docstrings to improve docstring coverage.
Description Check ❓ Inconclusive The pull request description provides the Related Issue link (#2826) and correctly identifies the change as both a bug fix and new feature with appropriate checkboxes marked. However, critical sections of the template are missing or incomplete: the Motivation and Context section is absent, the How Has This Been Tested section is not provided, and the description section itself is extremely brief ("This is a problem in stacked charts so why not fix it now that we have the technology"). While the checklist indicates a storybook/VR test was added, the description does not document testing details or explain the problem context, making it difficult to understand the full scope of the changes. The author should expand the description section to explain the problem and solution clearly, add a Motivation and Context section explaining why z-index was needed for bar backgrounds in stacked charts, and provide a How Has This Been Tested section detailing the testing approach including the storybook/VR test mentioned in the checklist. Adding screenshots or links showing the fix resolving issue #2826 would also strengthen the description.
✅ Passed checks (3 passed)
Check name Status Explanation
Title Check ✅ Passed The title "Add zIndex to bar background" directly and clearly describes the primary change in the pull request. The changeset introduces z-index support for bar backgrounds across Bar and RadialBar components by adding a new DefaultZIndexes entry and wrapping background rendering in ZIndexLayer components. The title is concise, specific, and accurately reflects the main technical change without vague language or noise.
Linked Issues Check ✅ Passed The changes directly address the core issue described in #2826: bar backgrounds covering other bars in stacked charts due to z-index/render order problems. The implementation adds a barBackground: -50 z-index entry to DefaultZIndexes, modifies Bar.tsx and RadialBar.tsx to wrap background rendering in ZIndexLayer components with the computed z-index, and updates tests and examples accordingly. This approach ensures bar backgrounds render at a controlled z-index level, preventing them from overlapping sibling bars in the stack, which aligns perfectly with the expected behavior specified in the issue.
Out of Scope Changes Check ✅ Passed All changes in the pull request are directly related to the z-index functionality for bar backgrounds. Modifications to Bar.tsx and RadialBar.tsx implement the z-index wrapping logic, DefaultZIndexes.tsx defines the barBackground z-index value, tests are updated to verify the new z-index entry, and the example is updated to demonstrate the background prop usage. No unrelated refactoring, cleanup, or tangential changes are present outside the scope of fixing the z-index issue in stacked and radial bar charts.
✨ Finishing touches
  • 📝 Generate docstrings
🧪 Generate unit tests (beta)

✅ Unit Test PR creation complete.

  • Create PR with unit tests
  • Commit unit tests in branch stacked-bar-background
  • Post copyable unit tests in a comment

Comment @coderabbitai help to get the list of available commands and usage tips.

@codecov
Copy link

codecov bot commented Oct 30, 2025

Codecov Report

❌ Patch coverage is 85.41667% with 7 lines in your changes missing coverage. Please review.
✅ Project coverage is 93.42%. Comparing base (bf4e0b2) to head (70a7bc9).
⚠️ Report is 5 commits behind head on main.

Files with missing lines Patch % Lines
src/polar/RadialBar.tsx 86.48% 5 Missing ⚠️
src/cartesian/Bar.tsx 75.00% 2 Missing ⚠️
Additional details and impacted files
@@            Coverage Diff             @@
##             main    #6536      +/-   ##
==========================================
- Coverage   93.43%   93.42%   -0.01%     
==========================================
  Files         436      436              
  Lines       39545    39566      +21     
  Branches     4599     4605       +6     
==========================================
+ Hits        36950    36966      +16     
- Misses       2579     2584       +5     
  Partials       16       16              

☔ View full report in Codecov by Sentry.
📢 Have feedback on the report? Share it here.

🚀 New features to boost your workflow:
  • ❄️ Test Analytics: Detect flaky tests, report on failures, and find test suite problems.

@codecov
Copy link

codecov bot commented Oct 30, 2025

Bundle Report

Changes will increase total bundle size by 1.99kB (0.08%) ⬆️. This is within the configured threshold ✅

Detailed changes
Bundle name Size Change
recharts/bundle-cjs 1.11MB 893 bytes (0.08%) ⬆️
recharts/bundle-es6 961.15kB 833 bytes (0.09%) ⬆️
recharts/bundle-umd 507.16kB 264 bytes (0.05%) ⬆️

Affected Assets, Files, and Routes:

view changes for bundle: recharts/bundle-es6

Assets Changed:

Asset Name Size Change Total Size Change (%)
cartesian/Bar.js 271 bytes 24.96kB 1.1%
polar/RadialBar.js 385 bytes 19.22kB 2.04%
zindex/DefaultZIndexes.js 177 bytes 1.42kB 14.24% ⚠️
view changes for bundle: recharts/bundle-umd

Assets Changed:

Asset Name Size Change Total Size Change (%)
Recharts.js 264 bytes 507.16kB 0.05%
view changes for bundle: recharts/bundle-cjs

Assets Changed:

Asset Name Size Change Total Size Change (%)
cartesian/Bar.js 301 bytes 26.55kB 1.15%
polar/RadialBar.js 415 bytes 20.59kB 2.06%
zindex/DefaultZIndexes.js 177 bytes 1.55kB 12.86% ⚠️

@PavelVanecek PavelVanecek requested a review from ckifer October 30, 2025 14:58
Copy link
Contributor

@coderabbitai coderabbitai bot left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Actionable comments posted: 1

Caution

Some comments are outside the diff and can’t be posted inline due to platform limitations.

⚠️ Outside diff range comments (1)
src/cartesian/Bar.tsx (1)

281-315: Add tests for background zIndex layering functionality.

The new BarBackground component wrapped in ZIndexLayer with computed getZIndex(backgroundFromProps) lacks test coverage. No existing tests cover either the getZIndex function or ZIndexLayer usage for backgrounds. The three existing background tests only validate basic rendering and props, not the zIndex layering behavior.

Per coding guidelines: add appropriate tests when changing functionality and aim for 100% unit test coverage. Tests should verify that:

  • Background renders within correct ZIndexLayer with appropriate zIndex value
  • getZIndex computes correct zIndex based on background prop
🧹 Nitpick comments (1)
src/polar/RadialBar.tsx (1)

338-348: Consider extracting shared zIndex helper logic.

The getZIndexForRadialBarBackground function is nearly identical to getZIndex in src/cartesian/Bar.tsx (lines 249-254). Both extract a zIndex from a background object with the same fallback. Consider extracting this to a shared utility function to reduce duplication.

Example shared utility:

// src/util/zIndexUtils.ts
export function extractZIndexFromBackground(
  background: unknown,
  fallback: number
): number {
  if (
    background != null &&
    typeof background === 'object' &&
    'zIndex' in background &&
    typeof background.zIndex === 'number'
  ) {
    return background.zIndex;
  }
  return fallback;
}

Then both components could use:

extractZIndexFromBackground(background, DefaultZIndexes.barBackground)
📜 Review details

Configuration used: CodeRabbit UI

Review profile: CHILL

Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between bf4e0b2 and 70a7bc9.

📒 Files selected for processing (5)
  • src/cartesian/Bar.tsx (3 hunks)
  • src/polar/RadialBar.tsx (1 hunks)
  • src/zindex/DefaultZIndexes.tsx (1 hunks)
  • test/zindex/zIndexSelectors.spec.ts (4 hunks)
  • www/src/docs/exampleComponents/BarChart/StackedBarChart.tsx (1 hunks)
🧰 Additional context used
📓 Path-based instructions (5)
**/*.{ts,tsx}

📄 CodeRabbit inference engine (CONTRIBUTING.md)

**/*.{ts,tsx}: Ensure code lints cleanly before submitting PRs (npm run lint)
Never use the TypeScript any type (implicit or explicit)
Prefer unknown over any and refine types appropriately
Explicitly type all function parameters and return values; do not rely on implicit any or inference
Do not use as type assertions; the only exception is as const

Files:

  • src/zindex/DefaultZIndexes.tsx
  • src/polar/RadialBar.tsx
  • www/src/docs/exampleComponents/BarChart/StackedBarChart.tsx
  • test/zindex/zIndexSelectors.spec.ts
  • src/cartesian/Bar.tsx
src/**/*.{js,jsx,ts,tsx}

📄 CodeRabbit inference engine (AGENTS.md)

Do not hardcode any user-facing strings or formatting choices in the library code; leave internationalization to library users

Files:

  • src/zindex/DefaultZIndexes.tsx
  • src/polar/RadialBar.tsx
  • src/cartesian/Bar.tsx
www/**

📄 CodeRabbit inference engine (DEVELOPING.md)

Use the www directory to add and commit examples for the documentation website (recharts.github.io)

Files:

  • www/src/docs/exampleComponents/BarChart/StackedBarChart.tsx
{test,www/test}/**

📄 CodeRabbit inference engine (DEVELOPING.md)

Place unit tests in the test directory; some tests may also live in www/test

Files:

  • test/zindex/zIndexSelectors.spec.ts
test/**/*.spec.{ts,tsx}

📄 CodeRabbit inference engine (CONTRIBUTING.md)

test/**/*.spec.{ts,tsx}: When writing new code, aim for 100% unit test code coverage
When adding or changing functionality, add appropriate tests (prefer unit tests; use RTL if rendering is involved)

Files:

  • test/zindex/zIndexSelectors.spec.ts
🧠 Learnings (7)
📚 Learning: 2025-10-25T07:36:02.211Z
Learnt from: CR
PR: recharts/recharts#0
File: AGENTS.md:0-0
Timestamp: 2025-10-25T07:36:02.211Z
Learning: Recharts aims for simple, declarative, and composable charts; prioritize consistency, usability, performance, and accessibility

Applied to files:

  • www/src/docs/exampleComponents/BarChart/StackedBarChart.tsx
📚 Learning: 2025-10-25T07:35:14.559Z
Learnt from: CR
PR: recharts/recharts#0
File: CONTRIBUTING.md:0-0
Timestamp: 2025-10-25T07:35:14.559Z
Learning: Provide a reduced, reproducible test case (e.g., via CodeSandbox or fork of recharts.github.io) when reporting issues

Applied to files:

  • www/src/docs/exampleComponents/BarChart/StackedBarChart.tsx
📚 Learning: 2025-10-25T07:35:46.180Z
Learnt from: CR
PR: recharts/recharts#0
File: test/README.md:0-0
Timestamp: 2025-10-25T07:35:46.180Z
Learning: Applies to test/**/*.test.{ts,tsx} : When testing selectors, verify render counts using the spy and rerenderSameComponent from createSelectorTestCase

Applied to files:

  • test/zindex/zIndexSelectors.spec.ts
📚 Learning: 2025-10-25T07:35:46.180Z
Learnt from: CR
PR: recharts/recharts#0
File: test/README.md:0-0
Timestamp: 2025-10-25T07:35:46.180Z
Learning: Applies to test/**/*.test.{ts,tsx} : In tests not using createSelectorTestCase, advance timers after renders with vi.runOnlyPendingTimers()

Applied to files:

  • test/zindex/zIndexSelectors.spec.ts
📚 Learning: 2025-10-25T07:35:14.559Z
Learnt from: CR
PR: recharts/recharts#0
File: CONTRIBUTING.md:0-0
Timestamp: 2025-10-25T07:35:14.559Z
Learning: Applies to test/**/*.spec.{ts,tsx} : When adding or changing functionality, add appropriate tests (prefer unit tests; use RTL if rendering is involved)

Applied to files:

  • test/zindex/zIndexSelectors.spec.ts
📚 Learning: 2025-10-25T07:35:46.180Z
Learnt from: CR
PR: recharts/recharts#0
File: test/README.md:0-0
Timestamp: 2025-10-25T07:35:46.180Z
Learning: Applies to test/**/*.test.{ts,tsx} : Prefer using the createSelectorTestCase helper when writing or modifying tests

Applied to files:

  • test/zindex/zIndexSelectors.spec.ts
📚 Learning: 2025-10-25T07:35:46.180Z
Learnt from: CR
PR: recharts/recharts#0
File: test/README.md:0-0
Timestamp: 2025-10-25T07:35:46.180Z
Learning: Applies to test/**/*.test.{ts,tsx} : Avoid vi.runAllTimers() in tests to prevent infinite loops caused by chained scheduled timers

Applied to files:

  • test/zindex/zIndexSelectors.spec.ts
🧬 Code graph analysis (4)
src/polar/RadialBar.tsx (5)
src/zindex/DefaultZIndexes.tsx (1)
  • DefaultZIndexes (4-65)
src/util/svgPropertiesNoEvents.ts (1)
  • svgPropertiesNoEventsFromUnknown (362-379)
src/zindex/ZIndexLayer.tsx (1)
  • ZIndexLayer (44-103)
src/util/RadialBarUtils.tsx (3)
  • RadialBarSectorProps (32-36)
  • parseCornerRadius (7-13)
  • RadialBarSector (38-40)
src/util/types.ts (1)
  • adaptEventsOfChild (875-897)
www/src/docs/exampleComponents/BarChart/StackedBarChart.tsx (1)
src/cartesian/Bar.tsx (1)
  • Bar (891-891)
test/zindex/zIndexSelectors.spec.ts (1)
src/zindex/zIndexSelectors.ts (1)
  • selectAllRegisteredZIndexes (36-50)
src/cartesian/Bar.tsx (3)
src/util/types.ts (1)
  • ActiveShape (1037-1042)
src/zindex/DefaultZIndexes.tsx (1)
  • DefaultZIndexes (4-65)
src/zindex/ZIndexLayer.tsx (1)
  • ZIndexLayer (44-103)
🔇 Additional comments (5)
test/zindex/zIndexSelectors.spec.ts (1)

59-59: LGTM! Test expectations correctly updated for new default zIndex.

All test expectations have been consistently updated to include the new -50 zIndex value for barBackground. The value appears in the correct sorted position across all test scenarios.

Also applies to: 68-68, 73-73, 79-79, 98-98, 112-112, 117-117, 125-125, 131-131, 139-139

www/src/docs/exampleComponents/BarChart/StackedBarChart.tsx (1)

68-69: LGTM! Example demonstrates the new background feature.

The addition of the background prop to both stacked Bar components appropriately demonstrates the feature introduced by this PR, which addresses the z-index issue described in #2826.

src/zindex/DefaultZIndexes.tsx (1)

9-13: LGTM! Well-documented default zIndex for bar backgrounds.

The new barBackground property with value -50 is appropriately positioned in the z-index layering hierarchy and includes clear documentation about its purpose and usage.

src/cartesian/Bar.tsx (1)

249-254: LGTM! Helper function correctly extracts zIndex with appropriate fallback.

The getZIndex helper properly handles the various types that ActiveShape can represent, using runtime type guards to safely extract the zIndex property when present, and falling back to the default value otherwise.

src/polar/RadialBar.tsx (1)

338-348: LGTM! Helper function mirrors Bar implementation correctly.

The getZIndexForRadialBarBackground helper appropriately handles the various RadialBarBackground types and extracts zIndex with a sensible default fallback.

Comment on lines +357 to +388
return (
<ZIndexLayer zIndex={getZIndexForRadialBarBackground(this.props.background)}>
{sectors.map((entry, i) => {
const { value, background, ...rest } = entry;

if (!background) {
return null;
}

const props: RadialBarSectorProps = {
cornerRadius: parseCornerRadius(cornerRadius),
...rest,
// @ts-expect-error backgroundProps is contributing unknown props
fill: '#eee',
...background,
...backgroundProps,
...adaptEventsOfChild(this.props, entry, i),
index: i,
className: clsx('recharts-radial-bar-background-sector', String(backgroundProps?.className)),
option: background,
isActive: false,
};

return (
<RadialBarSector
key={`background-${rest.cx}-${rest.cy}-${rest.innerRadius}-${rest.outerRadius}-${rest.startAngle}-${rest.endAngle}-${i}`} // eslint-disable-line react/no-array-index-key
{...props}
/>
);
});
return (
<RadialBarSector
key={`background-${rest.cx}-${rest.cy}-${rest.innerRadius}-${rest.outerRadius}-${rest.startAngle}-${rest.endAngle}-${i}`} // eslint-disable-line react/no-array-index-key
{...props}
/>
);
})}
</ZIndexLayer>
);
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

⚠️ Potential issue | 🔴 Critical

🧩 Analysis chain

Verify test coverage for RadialBar background zIndex functionality.

The background rendering now correctly uses a ZIndexLayer for proper layering. However, per the coding guidelines, "when adding or changing functionality, add appropriate tests."

[As per coding guidelines]

Run the following script to check for existing tests covering RadialBar background with zIndex:


🏁 Script executed:

#!/bin/bash
# Search for tests related to RadialBar background and zIndex
rg -n -C3 --type=ts --type=tsx 'RadialBar.*background.*zIndex|background.*zIndex.*RadialBar' test/ -g '*.{spec,test}.{ts,tsx}'

# Search for RadialBar component tests
fd -e ts -e tsx 'RadialBar.*\.(spec|test)' test/

Length of output: 172



---

🏁 Script executed:

```shell
#!/bin/bash
# Examine the test files for background-related tests
echo "=== Checking test/polar/RadialBar.spec.tsx for background tests ==="
grep -n -A5 -B2 "background" test/polar/RadialBar.spec.tsx | head -50

echo ""
echo "=== Checking test/polar/RadialBar.animation.spec.tsx for background tests ==="
grep -n -A5 -B2 "background" test/polar/RadialBar.animation.spec.tsx | head -50

echo ""
echo "=== Searching for ZIndexLayer tests in RadialBar tests ==="
grep -n -C3 "ZIndexLayer" test/polar/RadialBar*.spec.tsx test/chart/RadialBarChart*.spec.tsx 2>/dev/null

echo ""
echo "=== Searching for zIndex tests ==="
grep -n -C3 "zIndex" test/polar/RadialBar*.spec.tsx test/chart/RadialBarChart*.spec.tsx 2>/dev/null

Length of output: 1945



---

🏁 Script executed:

```shell
#!/bin/bash
# Get context of the background tests to understand what they're verifying
echo "=== Full test cases using background in RadialBar.spec.tsx ==="
grep -n -B10 "background:" test/polar/RadialBar.spec.tsx | grep -E "it\(|describe\(|background:" | head -20

echo ""
echo "=== Look for render/snapshot assertions in background tests ==="
grep -n -A20 "background:" test/polar/RadialBar.spec.tsx | grep -E "expect\(|toMatchSnapshot|render|screen" | head -15

echo ""
echo "=== Check RadialBar.tsx implementation for ZIndexLayer and background ==="
grep -n -A3 -B3 "ZIndexLayer.*background\|background.*ZIndexLayer" src/polar/RadialBar.tsx

echo ""
echo "=== Search for getZIndexForRadialBarBackground function ==="
grep -n "getZIndexForRadialBarBackground" src/polar/RadialBar.tsx

Length of output: 1483



---

🏁 Script executed:

```shell
#!/bin/bash
# View the getZIndexForRadialBarBackground function implementation
echo "=== getZIndexForRadialBarBackground function implementation ==="
sed -n '338,346p' src/polar/RadialBar.tsx

echo ""
echo "=== Check for snapshot tests in RadialBar.spec.tsx ==="
grep -n "toMatchSnapshot\|snapshot" test/polar/RadialBar.spec.tsx | head -10

echo ""
echo "=== Check the full test structure - how many test cases and what they do ==="
grep -n "it\(" test/polar/RadialBar.spec.tsx | wc -l

echo ""
echo "=== Find if any test specifically tests the background rendering output ==="
grep -n -A30 "should render sectors" test/polar/RadialBar.spec.tsx | head -40

Length of output: 3071


Add tests for RadialBar background zIndex functionality

Verification confirms a test coverage gap: while background rendering is tested via sector path assertions, the new ZIndexLayer wrapping and zIndex functionality are not. Tests should verify that:

  • Background objects with a zIndex property apply the correct z-index layer
  • Background objects without zIndex use the default value
  • The layering behavior correctly orders background sectors

@coderabbitai
Copy link
Contributor

coderabbitai bot commented Oct 30, 2025

Note

Unit test generation is an Early Access feature. Expect some limitations and changes as we gather feedback and continue to improve it.


Generating unit tests... This may take up to 20 minutes.

@coderabbitai
Copy link
Contributor

coderabbitai bot commented Oct 30, 2025

UTG Post-Process Complete

No new issues were detected in the generated code and all check runs have completed. The unit test generation process has completed successfully.

@coderabbitai
Copy link
Contributor

coderabbitai bot commented Oct 30, 2025

Creating a PR to put the unit tests in...

The changes have been created in this pull request: View PR

Copy link
Member

@ckifer ckifer left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

noice

@ckifer ckifer merged commit 8cf286d into main Oct 30, 2025
25 of 29 checks passed
@ckifer ckifer deleted the stacked-bar-background branch October 30, 2025 19:18
This was referenced Oct 31, 2025
@coderabbitai coderabbitai bot mentioned this pull request Dec 6, 2025
7 tasks
@coderabbitai coderabbitai bot mentioned this pull request Jan 22, 2026
7 tasks
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

Background fill with stacked bar chart does not render correctly (zindex)

2 participants