Skip to content

fix(hooks): snap inverse band scales to category centers - #8307

Merged
PavelVanecek merged 4 commits into
recharts:mainfrom
13Sharad:fix-inverse-band-centers
Nov 27, 2026
Merged

PavelVanecek merged 4 commits into
recharts:mainfrom
13Sharad:fix-inverse-band-centers

Conversation

@13Sharad

@13Sharad 13Sharad commented Nov 25, 2026 •

Copy link
Copy Markdown
Contributor

Description

Use each band's center when converting pixel coordinates back to categories. scaleBand returns the band's start, while chart ticks and bars are centered in the band. Comparing the pointer to band starts shifts selection boundaries by half a band, so the inverse hooks can return B over bar A and C over bar B.

Add half the bandwidth before the existing nearest-neighbor search. Scales without bandwidth, and point scales with zero bandwidth, keep the existing behavior. This fixes useXAxisInverseScale, useYAxisInverseScale and their data-snap counterparts for band scales. It does not change the built-in Tooltip logic or add a public API.

Related Issue

Fixes #8306

Motivation and Context

Custom selection and annotation interactions using the public inverse hooks should identify the category under the pointer rather than an adjacent category.

How Has This Been Tested?

  • Four new unit regression cases fail on unchanged main: ascending/descending ranges, with and without band padding.
  • Four new actual BarChart hook cases fail on unchanged main: horizontal/vertical layouts, normal/reversed axes. Each checks inverse and data-snap results at several positions within each band.
  • Two point-scale controls pass unchanged and remain passing. Existing continuous-scale tests remain passing.
  • npm run test-lib -- test/util test/hooks --maxWorkers=2: 1,265 passed, 1 expected failure, across 59 files.
  • npm run check-types-test with NODE_OPTIONS=--max-old-space-size=2048: passed.
  • Changed-file ESLint: passed.
  • Library declaration, CJS, ESM and UMD builds completed. npm run test-build-output: 14 passed.
  • Targeted helper coverage: 100% statements/lines/functions, 92.3% branches for the whole helper file.
  • Local Chromium before/after rendering verified the incorrect B/C/C selection becomes A/B/C for positions inside the three bars.

The full test suite and repository-wide lint attempts were interrupted by execution time limits, so they are not claimed passing. Docker is not available in this environment; the official Playwright VR matrix was not run. No VR snapshots changed.

Tested on Linux, Node 22.23.5, React 18.3.1 and current main 5a89f8e2835e7b919dfa6a58546bcff50d019091. All three committed files were read back and matched the locally tested bytes.

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

  • Bug Fixes
    • Improved category selection on bar charts when interacting within a category’s band, including charts with reversed axes and horizontal or vertical layouts.
    • Category mapping is more consistent across different band widths and padding settings, while point-scale behavior remains supported.

Use band centers for inverse pixel-distance selection. Regression tests follow in this branch. Related upstream issue recharts#8306.
Cover padded and reversed band ranges and preserve point-scale behavior.
Exercise inverse and data-snap hooks in horizontal, vertical and reversed BarCharts.
@coderabbitai

coderabbitai Bot commented Nov 25, 2026 •

Copy link
Copy Markdown
Contributor

Explain Change →

Important

Review skipped

Review was skipped as selected files did not have any reviewable changes.

Run configuration

  • Source mode: Auto
  • Repository: Unavailable
  • Branch: Unavailable
  • File: No configuration file from this repository applied
  • Commit: Unavailable
  • Layers: Organization UI
  • Review profile: CHILL
  • Plan: Advanced
  • Run ID: fb5e1468-324b-4614-a0b2-b01e80b6e8c8
Commits

Reviewing files that changed from the base of the PR and between 6ca7020 and e5221ec.

You can disable this status message by setting the reviews.review_status to false in the CodeRabbit configuration file.

Use the checkbox below for a quick retry:

  • Trigger review

No actionable comments were generated in the recent review.

Walkthrough

Categorical inverse mapping now accounts for half the scale bandwidth when locating the nearest category. Tests cover band and point scales, range directions, padding, and inverse and data-snap hooks on horizontal and vertical bar charts.

Changes

Categorical inverse scale mapping

Layer / File(s) Summary
Band-center inverse mapping
src/util/scale/createCategoricalInverse.ts, test/util/scale/createCategoricalInverse.spec.ts
Inverse mapping offsets band positions by half the bandwidth. Tests cover padded and unpadded bands, ascending and descending ranges, and point scales.
Bar-chart inverse hook validation
test/hooks/useAxisInverseBandScale.spec.tsx
Tests check inverse and data-snap scale results at offsets around category ticks for horizontal and vertical bar charts, with reversed and non-reversed axes.

Estimated code review effort: 2 (Simple) | ~10 minutes

Change: Bug fix · Severity of issue fixed: Medium

Suggested reviewers: pavelvanecek

Merge Risk: Minimal · previous review 6ca70

This change makes the inverse-axis hooks pick the category whose rendered band center is closest to the pointer. Point and continuous scales behave as before. The change is small and covered by regression tests, and no merge-blocking risk was found.

Pre-merge checks: Passed 4

Check name Status Explanation
Title check Passed The title names the main change: band-scale inverse hooks now snap to category centers, which matches the createCategoricalInverse change that adds half the bandwidth before the nearest-neighbor searc…
Linked Issues check Passed [#8306] requires inverse hooks to select the category whose band center is nearest to the pointer. The reviewed diff in src/util/scale/createCategoricalInverse.ts adds offset = (scale.bandwidth?.() ??…
Out of Scope Changes check Passed The source change is a three-line adjustment in createCategoricalInverse.ts. It adds the band-center offset and a comment that explains it. This directly implements [#8306]. The test changes in test/u…
Description check Passed The description follows the repository template. It covers the change, the linked issue (#8306), the motivation, detailed testing, and the bug fix type. It also ticks the tests checkbox. Remaining gap…
Full details: Title check

Explanation

The title names the main change: band-scale inverse hooks now snap to category centers, which matches the createCategoricalInverse change that adds half the bandwidth before the nearest-neighbor search. It is specific and follows the fix(hooks) convention. The title is short, a single sentence, and free of noise.

Full details: Linked Issues check

Explanation

[#8306] requires inverse hooks to select the category whose band center is nearest to the pointer. The reviewed diff in src/util/scale/createCategoricalInverse.ts adds offset = (scale.bandwidth?.() ?? 0) / 2 to each mapped domain pixel position before the existing nearest-neighbor search. For the issue's reduced example, scaleBand with domain [A, B, C] and range [0, 300] gives centers 50, 150, 250. With the offset, pixel 90 resolves to A, as the issue requires. Continuous scales have no bandwidth method, so the offset is 0 and their behavior is unchanged. Point scales report bandwidth 0, so their behavior is also unchanged. The change sits in the shared helper that the X and Y inverse and data-snap hooks use, so it covers the affected hooks. The PR summary reports new regression tests for ascending and descending ranges, padded and unpadded bands, and horizontal and vertical BarChart hooks. I did not re-run these tests. The test evidence comes from the PR summary and the test file change summary.

Full details: Out of Scope Changes check

Explanation

The source change is a three-line adjustment in createCategoricalInverse.ts. It adds the band-center offset and a comment that explains it. This directly implements [#8306]. The test changes in test/util/scale/createCategoricalInverse.spec.ts and test/hooks/useAxisInverseBandScale.spec.tsx cover the same behavior and support this implementation. No unrelated files appear in the reviewed changes. The PR description states that built-in Tooltip logic and public APIs are not changed. I did not enumerate every caller of createCategoricalInverse, so a Tooltip-side effect from the shared helper is not fully excluded by direct inspection. No concrete unrelated change was found.

Full details: Description check

Explanation

The description follows the repository template. It covers the change, the linked issue (#8306), the motivation, detailed testing, and the bug fix type. It also ticks the tests checkbox. Remaining gaps are minor: the documentation and storybook/VR checkboxes are unticked, and the Screenshots section is absent. The author also explains that VR snapshots were not run, which is disclosed. The description is substantially complete.

Finishing Touches

Generate unit tests (beta)

  • Create a new PR
  • Autofix · Keep fixing CodeRabbit findings and required CI, and resolving merge conflicts

Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out.

Share

Recent review info

Run configuration

  • Source mode: Auto
  • Repository: Unavailable
  • Branch: Unavailable
  • File: No configuration file from this repository applied
  • Commit: Unavailable
  • Layers: Organization UI
  • Review profile: CHILL
  • Plan: Advanced
  • Run ID: cd0a0f94-a3af-4e08-b041-b37db4255e76
Commits

Reviewing files that changed from the base of the PR and between 5a89f8e and 6ca7020.

Files selected for processing: 3

  • src/util/scale/createCategoricalInverse.ts
  • test/hooks/useAxisInverseBandScale.spec.tsx
  • test/util/scale/createCategoricalInverse.spec.ts

Included review availability: This review used your included allowance. Your plan provides up to 10 included reviews per hour; 9 remain after this review.

@codecov

codecov Bot commented Nov 27, 2026 •

Copy link
Copy Markdown

Bundle Report

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

Detailed changes
Bundle name Size Change
recharts/bundle-cjs 1.87MB 371 bytes (0.02%) ⬆️
recharts/bundle-es6 1.68MB 371 bytes (0.02%) ⬆️
recharts/bundle-umd 687.54kB 96 bytes (0.01%) ⬆️
recharts/bundle-treeshaking-cartesian 945.12kB 371 bytes (0.04%) ⬆️
recharts/bundle-treeshaking-polar 657.44kB 371 bytes (0.06%) ⬆️
recharts/bundle-treeshaking-treemap 567.62kB 371 bytes (0.07%) ⬆️

Affected Assets, Files, and Routes:

view changes for bundle: recharts/bundle-treeshaking-treemap

Assets Changed:

Asset Name Size Change Total Size Change (%)
bundle.js 371 bytes 567.62kB 0.07%
view changes for bundle: recharts/bundle-treeshaking-polar

Assets Changed:

Asset Name Size Change Total Size Change (%)
bundle.js 371 bytes 657.44kB 0.06%
view changes for bundle: recharts/bundle-treeshaking-cartesian

Assets Changed:

Asset Name Size Change Total Size Change (%)
bundle.js 371 bytes 945.12kB 0.04%
view changes for bundle: recharts/bundle-umd

Assets Changed:

Asset Name Size Change Total Size Change (%)
Recharts.js 96 bytes 687.54kB 0.01%
view changes for bundle: recharts/bundle-cjs

Assets Changed:

Asset Name Size Change Total Size Change (%)
util/scale/createCategoricalInverse.js 371 bytes 2.85kB 14.97% ⚠️
view changes for bundle: recharts/bundle-es6

Assets Changed:

Asset Name Size Change Total Size Change (%)
util/scale/createCategoricalInverse.js 371 bytes 2.7kB 15.94% ⚠️

@flakiness-io

flakiness-io Bot commented Nov 27, 2026 •

Copy link
Copy Markdown

Test Results Summary

This comment shows the latest test results for this pull request.

Commit Status Test Results CI Runs
e5221ec ✅ Passed 3978 passed · 18 skipped 9 runs

View full report

ℹ️ About Flakiness.io in GitHub

Your team has set up Flakiness.io pull request comments. This comment is updated when

  • The first test results arrive for this pull request
  • A later run reports more results for the same commit
  • A new commit is pushed and tested

Flakiness.io rewrites the comment in place, so it always reflects the most recently tested commit.

@codecov

codecov Bot commented Nov 27, 2026

Copy link
Copy Markdown

Codecov Report

✅ All modified and coverable lines are covered by tests.
✅ Project coverage is 89.84%. Comparing base (f29e240) to head (e5221ec).

Additional details and impacted files
@@            Coverage Diff             @@
##             main    #8307      +/-   ##
==========================================
+ Coverage   89.80%   89.84%   +0.03%     
==========================================
  Files         692      692              
  Lines       17977    17978       +1     
  Branches     4865     4870       +5     
==========================================
+ Hits        16145    16152       +7     
+ Misses       1628     1623       -5     
+ Partials      204      203       -1     

☔ View full report in Codecov by Harness.
📢 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.

@PavelVanecek
PavelVanecek merged commit 3f01d1e into recharts:main Nov 27, 2026
64 checks passed
PavelVanecek pushed a commit that referenced this pull request Nov 29, 2026
… cannot place (#8309)

## Description

`createCategoricalInverse` now pairs each value with its pixel position,
skips values the scale can't place (`null`, or a category outside the
domain), and sorts by pixel before the binary search. Before, it
searched values that were pre-sorted by number, and gave unplaceable
values pixel 0.

## Related Issue

Fixes #8308

## Motivation and Context

`useXAxisInverseDataSnapScale` / `useYAxisInverseDataSnapScale` returned
the wrong data point when:

- a series has gaps (`null`): on a YAxis with `[10, null, 20, 30]`, the
pixel of 10 snapped to 30, 20 to 10, and 30 to `null`;
- a categorical axis has number-like values that aren't ascending (e.g.
years newest first): the pixel of 2022 snapped to 2023.

`selectSortedDataPoints` sorts numerically and keeps nullish values, but
a categorical axis keeps domain order and `null` got pixel 0, so the
bisect saw an unsorted list. The plain inverse hooks on categorical axes
use the same helper; their band order was already sorted, so their
results don't change.

This touches the same lines as #8307 (band centre offset), so whichever
lands second will need a small rebase.

## How Has This Been Tested?

- New unit tests in `test/util/scale/createCategoricalInverse.spec.ts`
and hook tests in `test/hooks/useAxisScale.spec.tsx`. All 5 fail on
`main` and pass with the fix.
- `npm run test -- test/util test/hooks test/state`: 1885 passed.
- `check-types-lib`, `check-types-test`, eslint and prettier pass on the
changed files.

## Types of changes

- [x] 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.
- [x] 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


<!-- This is an auto-generated comment: release notes by coderabbit.ai
-->
<!-- coderabbit-ai-generated:v1 -->

## Summary by CodeRabbit

* **Bug Fixes**
* Category-axis snapping now selects the closest category based on its
displayed position, even when category order differs.
* Unplaceable categories are skipped, and snapping returns no result
when no category can be placed.
* Axis data snapping handles non-ascending category order and avoids
selecting points with null values, choosing the closest available
non-null value instead.
<!-- end of auto-generated comment: release notes by coderabbit.ai -->
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.

Inverse-axis hooks snap to an adjacent category inside BarChart bands

2 participants