Conversation
WalkthroughThis PR refactors Recharts' scale abstraction layer, introducing a new Changes
Estimated code review effort🎯 4 (Complex) | ⏱️ ~60 minutes Areas requiring extra attention:
Possibly related PRs
Suggested labels
Suggested reviewers
Pre-merge checks and finishing touches❌ Failed checks (1 warning)
✅ Passed checks (2 passed)
✨ Finishing touches
🧪 Generate unit tests (beta)
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. Comment |
There was a problem hiding this comment.
Actionable comments posted: 0
🧹 Nitpick comments (6)
src/cartesian/ReferenceArea.tsx (1)
74-91: Consider usingmapWithFallbackfor cleaner implementation.The
CartesianScaleHelperImplprovides amapWithFallbackmethod that handles the fallback logic you're implementing manually. This would eliminate the need for the@ts-expect-errorcomment.🔎 Proposed refactor using mapWithFallback
- const scales = new CartesianScaleHelperImpl({ x: xAxisScale, y: yAxisScale }); - - const p1: NullableCoordinate = { - x: hasX1 ? (xAxisScale.map(xValue1, { position: 'start' }) ?? null) : xAxisScale.rangeMin(), - y: hasY1 ? (yAxisScale.map(yValue1, { position: 'start' }) ?? null) : yAxisScale.rangeMin(), - }; - - const p2: NullableCoordinate = { - x: hasX2 ? (xAxisScale.map(xValue2, { position: 'end' }) ?? null) : xAxisScale.rangeMax(), - y: hasY2 ? (yAxisScale.map(yValue2, { position: 'end' }) ?? null) : yAxisScale.rangeMax(), - }; + const scales = new CartesianScaleHelperImpl({ x: xAxisScale, y: yAxisScale }); + + const p1 = scales.mapWithFallback( + { x: hasX1 ? xValue1 : undefined, y: hasY1 ? yValue1 : undefined }, + { position: 'start', fallback: 'rangeMin' }, + ); + + const p2 = scales.mapWithFallback( + { x: hasX2 ? xValue2 : undefined, y: hasY2 ? yValue2 : undefined }, + { position: 'end', fallback: 'rangeMax' }, + ); if (props.ifOverflow === 'discard' && (!scales.isInRange(p1) || !scales.isInRange(p2))) { return null; } - // @ts-expect-error we're sending nullable coordinates but rectWithPoints expects non-nullable Coordinate return rectWithPoints(p1, p2);Note: The
mapWithFallbackmethod returnsCoordinate(non-nullable), which would eliminate the type mismatch withrectWithPoints. However, this changes behavior slightly - values that fail to map would get fallback values instead of null. Verify this aligns with the intended behavior.src/cartesian/ReferenceDot.tsx (1)
139-140: Unnecessary nullish coalescing operators.The
Coordinatetype returned byscales.map()guaranteesxandyare numbers (never null/undefined), asCartesianScaleHelperImpl.map()uses?? 0internally. The?? undefinedfallback will never be triggered.🔎 Proposed simplification
const dotProps: DotProps = { clipPath, ...svgPropertiesAndEvents(props), - cx: cx ?? undefined, - cy: cy ?? undefined, + cx, + cy, };test/cartesian/ReferenceLine/getEndPoints.spec.tsx (1)
118-131: Dead code: unused variables from previous test setup.The
coord,scales, andbeforeEachsetup are no longer used after the refactor to real scales. These should be removed to avoid confusion.🔎 Proposed fix
describe('fixed Y location when in range', () => { const position = 'start'; const lineLocationY = 9; const yScale = d3ScaleToRechartsScale<number>(scaleLinear().domain([0, 15]).range([0, 150])); - const coord = Symbol('coord'); - const scales = { - y: { - apply: vi.fn(), - isInRange: vi.fn(), - }, - }; - - beforeEach(() => { - scales.y.apply.mockReset(); - scales.y.apply.mockImplementation(() => coord); - scales.y.isInRange.mockReset(); - scales.y.isInRange.mockImplementation(() => true); - }); it('should return coordinates when set to discard overflow', () => {src/cartesian/ReferenceLine.tsx (1)
236-241: Consider extracting CartesianScaleHelperImpl creation.The inline instantiation of
CartesianScaleHelperImplworks, but could be created earlier ingetEndPointsand passed togetSegmentLineEndPointsfor consistency with how the individual axis scales are passed to the horizontal/vertical line functions.This is a minor structural observation - the current approach is functionally correct.
src/util/scale/RechartsScale.ts (1)
87-95: Consider improving type safety for d3 scale lookup.The two
@ts-expect-errorcomments indicate that the dynamic scale lookup fromd3Scaleslacks proper type verification. While functional, this could be improved with a type-safe lookup map.This is a pre-existing pattern in the codebase, so addressing it could be deferred to a future improvement.
src/util/scale/CartesianScaleHelper.ts (1)
41-64: Consider reducing duplication in fallback computation.The if-else blocks for computing
fallbackY(lines 46-52) andfallbackX(lines 53-59) are nearly identical. This could be refactored into a helper function for clarity.🔎 Proposed refactor
+ private getFallback(scale: RechartsScale<unknown>, fallback: 'rangeMin' | 'rangeMax'): number { + if (fallback === 'rangeMin') { + return scale.rangeMin(); + } + if (fallback === 'rangeMax') { + return scale.rangeMax(); + } + return 0; + } + mapWithFallback( value: { x?: XDomain | null | undefined; y?: YDomain | null | undefined }, { position, fallback }: { position?: BandPosition; fallback: 'rangeMin' | 'rangeMax' }, ): Coordinate { - let fallbackY: number, fallbackX: number; - if (fallback === 'rangeMin') { - fallbackY = this.yAxisScale.rangeMin(); - } else if (fallback === 'rangeMax') { - fallbackY = this.yAxisScale.rangeMax(); - } else { - fallbackY = 0; - } - if (fallback === 'rangeMin') { - fallbackX = this.xAxisScale.rangeMin(); - } else if (fallback === 'rangeMax') { - fallbackX = this.xAxisScale.rangeMax(); - } else { - fallbackX = 0; - } + const fallbackX = this.getFallback(this.xAxisScale, fallback); + const fallbackY = this.getFallback(this.yAxisScale, fallback); return { x: this.xAxisScale.map(value.x, { position }) ?? fallbackX, y: this.yAxisScale.map(value.y, { position }) ?? fallbackY, }; }
📜 Review details
Configuration used: Organization UI
Review profile: CHILL
Plan: Pro
📒 Files selected for processing (38)
scripts/snapshots/es6Files.txtscripts/snapshots/libFiles.txtscripts/snapshots/typesFiles.txtsrc/cartesian/Area.tsxsrc/cartesian/Bar.tsxsrc/cartesian/CartesianGrid.tsxsrc/cartesian/ErrorBar.tsxsrc/cartesian/Line.tsxsrc/cartesian/ReferenceArea.tsxsrc/cartesian/ReferenceDot.tsxsrc/cartesian/ReferenceLine.tsxsrc/cartesian/Scatter.tsxsrc/polar/Radar.tsxsrc/polar/RadialBar.tsxsrc/state/selectors/axisSelectors.tssrc/state/selectors/tooltipSelectors.tssrc/util/CartesianUtils.tssrc/util/ChartUtils.tssrc/util/scale/CartesianScaleHelper.tssrc/util/scale/CustomScaleDefinition.tssrc/util/scale/RechartsScale.tssrc/util/types.tstest/cartesian/Area.spec.tsxtest/cartesian/CartesianAxis.spec.tsxtest/cartesian/ReferenceLine/getEndPoints.spec.tsxtest/cartesian/XAxis/XAxis.barSize.spec.tsxtest/cartesian/getEquidistantTicks.spec.tstest/cartesian/getTicks.spec.tstest/chart/ScatterChart.spec.tsxtest/component/Tooltip/Tooltip.multipleDataArrays.spec.tsxtest/helper/expectScale.tstest/helper/mockAxes.tstest/polar/PolarAngleAxis.spec.tsxtest/polar/PolarGrid.spec.tsxtest/util/CartesianUtils/CartesianUtils.spec.tstest/util/ChartUtils.spec.tsxtest/util/ChartUtils/checkDomainOfScale.spec.tstest/util/ChartUtils/getCateCoordinateOfLine.spec.ts
💤 Files with no reviewable changes (2)
- src/cartesian/CartesianGrid.tsx
- src/util/CartesianUtils.ts
🧰 Additional context used
📓 Path-based instructions (8)
**/*.{ts,tsx}
📄 CodeRabbit inference engine (CONTRIBUTING.md)
**/*.{ts,tsx}: Never useanytype (implicit or explicit) in TypeScript code
Preferunknownoveranyand refine the type in TypeScript
Type function parameters and return values explicitly in TypeScript, do not rely on implicit any or inference; exceptions are React components and trivial functions
Do not useastype assertions in TypeScript; the only exception isas const
Files:
test/helper/expectScale.tssrc/cartesian/ErrorBar.tsxsrc/cartesian/Line.tsxsrc/util/types.tstest/cartesian/getTicks.spec.tstest/util/ChartUtils.spec.tsxsrc/util/scale/CartesianScaleHelper.tssrc/polar/Radar.tsxtest/component/Tooltip/Tooltip.multipleDataArrays.spec.tsxtest/polar/PolarGrid.spec.tsxsrc/util/scale/CustomScaleDefinition.tstest/util/ChartUtils/checkDomainOfScale.spec.tssrc/state/selectors/tooltipSelectors.tstest/cartesian/Area.spec.tsxsrc/cartesian/ReferenceLine.tsxtest/util/ChartUtils/getCateCoordinateOfLine.spec.tssrc/cartesian/Area.tsxtest/cartesian/ReferenceLine/getEndPoints.spec.tsxtest/chart/ScatterChart.spec.tsxsrc/util/scale/RechartsScale.tssrc/polar/RadialBar.tsxtest/polar/PolarAngleAxis.spec.tsxsrc/cartesian/ReferenceArea.tsxtest/cartesian/CartesianAxis.spec.tsxsrc/cartesian/ReferenceDot.tsxtest/cartesian/XAxis/XAxis.barSize.spec.tsxsrc/cartesian/Scatter.tsxsrc/state/selectors/axisSelectors.tstest/cartesian/getEquidistantTicks.spec.tssrc/cartesian/Bar.tsxtest/util/CartesianUtils/CartesianUtils.spec.tstest/helper/mockAxes.tssrc/util/ChartUtils.ts
**/*.{js,ts,tsx}
📄 CodeRabbit inference engine (CONTRIBUTING.md)
Ensure code lints by running
npm run lintand follows Airbnb's Style Guide
Files:
test/helper/expectScale.tssrc/cartesian/ErrorBar.tsxsrc/cartesian/Line.tsxsrc/util/types.tstest/cartesian/getTicks.spec.tstest/util/ChartUtils.spec.tsxsrc/util/scale/CartesianScaleHelper.tssrc/polar/Radar.tsxtest/component/Tooltip/Tooltip.multipleDataArrays.spec.tsxtest/polar/PolarGrid.spec.tsxsrc/util/scale/CustomScaleDefinition.tstest/util/ChartUtils/checkDomainOfScale.spec.tssrc/state/selectors/tooltipSelectors.tstest/cartesian/Area.spec.tsxsrc/cartesian/ReferenceLine.tsxtest/util/ChartUtils/getCateCoordinateOfLine.spec.tssrc/cartesian/Area.tsxtest/cartesian/ReferenceLine/getEndPoints.spec.tsxtest/chart/ScatterChart.spec.tsxsrc/util/scale/RechartsScale.tssrc/polar/RadialBar.tsxtest/polar/PolarAngleAxis.spec.tsxsrc/cartesian/ReferenceArea.tsxtest/cartesian/CartesianAxis.spec.tsxsrc/cartesian/ReferenceDot.tsxtest/cartesian/XAxis/XAxis.barSize.spec.tsxsrc/cartesian/Scatter.tsxsrc/state/selectors/axisSelectors.tstest/cartesian/getEquidistantTicks.spec.tssrc/cartesian/Bar.tsxtest/util/CartesianUtils/CartesianUtils.spec.tstest/helper/mockAxes.tssrc/util/ChartUtils.ts
**/*.{ts,tsx,js,jsx}
📄 CodeRabbit inference engine (DEVELOPING.md)
All imports from
rechartsmust use the public API entry point; imports from internal paths likerecharts/types/*orrecharts/src/*are not allowed
Files:
test/helper/expectScale.tssrc/cartesian/ErrorBar.tsxsrc/cartesian/Line.tsxsrc/util/types.tstest/cartesian/getTicks.spec.tstest/util/ChartUtils.spec.tsxsrc/util/scale/CartesianScaleHelper.tssrc/polar/Radar.tsxtest/component/Tooltip/Tooltip.multipleDataArrays.spec.tsxtest/polar/PolarGrid.spec.tsxsrc/util/scale/CustomScaleDefinition.tstest/util/ChartUtils/checkDomainOfScale.spec.tssrc/state/selectors/tooltipSelectors.tstest/cartesian/Area.spec.tsxsrc/cartesian/ReferenceLine.tsxtest/util/ChartUtils/getCateCoordinateOfLine.spec.tssrc/cartesian/Area.tsxtest/cartesian/ReferenceLine/getEndPoints.spec.tsxtest/chart/ScatterChart.spec.tsxsrc/util/scale/RechartsScale.tssrc/polar/RadialBar.tsxtest/polar/PolarAngleAxis.spec.tsxsrc/cartesian/ReferenceArea.tsxtest/cartesian/CartesianAxis.spec.tsxsrc/cartesian/ReferenceDot.tsxtest/cartesian/XAxis/XAxis.barSize.spec.tsxsrc/cartesian/Scatter.tsxsrc/state/selectors/axisSelectors.tstest/cartesian/getEquidistantTicks.spec.tssrc/cartesian/Bar.tsxtest/util/CartesianUtils/CartesianUtils.spec.tstest/helper/mockAxes.tssrc/util/ChartUtils.ts
src/**/*.{ts,tsx}
📄 CodeRabbit inference engine (AGENTS.md)
Do not hardcode any strings or formatting choices in library code; users should provide localized strings as desired
Files:
src/cartesian/ErrorBar.tsxsrc/cartesian/Line.tsxsrc/util/types.tssrc/util/scale/CartesianScaleHelper.tssrc/polar/Radar.tsxsrc/util/scale/CustomScaleDefinition.tssrc/state/selectors/tooltipSelectors.tssrc/cartesian/ReferenceLine.tsxsrc/cartesian/Area.tsxsrc/util/scale/RechartsScale.tssrc/polar/RadialBar.tsxsrc/cartesian/ReferenceArea.tsxsrc/cartesian/ReferenceDot.tsxsrc/cartesian/Scatter.tsxsrc/state/selectors/axisSelectors.tssrc/cartesian/Bar.tsxsrc/util/ChartUtils.ts
test/**/*.spec.{ts,tsx}
📄 CodeRabbit inference engine (CONTRIBUTING.md)
Aim for 100% unit test code coverage when writing new code
Files:
test/cartesian/getTicks.spec.tstest/util/ChartUtils.spec.tsxtest/component/Tooltip/Tooltip.multipleDataArrays.spec.tsxtest/polar/PolarGrid.spec.tsxtest/util/ChartUtils/checkDomainOfScale.spec.tstest/cartesian/Area.spec.tsxtest/util/ChartUtils/getCateCoordinateOfLine.spec.tstest/cartesian/ReferenceLine/getEndPoints.spec.tsxtest/chart/ScatterChart.spec.tsxtest/polar/PolarAngleAxis.spec.tsxtest/cartesian/CartesianAxis.spec.tsxtest/cartesian/XAxis/XAxis.barSize.spec.tsxtest/cartesian/getEquidistantTicks.spec.tstest/util/CartesianUtils/CartesianUtils.spec.ts
test/**/*.{test,spec}.{ts,tsx}
📄 CodeRabbit inference engine (test/README.md)
test/**/*.{test,spec}.{ts,tsx}: Aim for 100% unit test code coverage when writing new code
Prefer to use thecreateSelectorTestCasehelper function when writing or modifying tests
Use theexpectLastCalledWithhelper function instead ofexpect(spy).toHaveBeenLastCalledWith(...)for better typing and autocompletion
Verify the number of selector calls using the spy object fromcreateSelectorTestCaseto spot unnecessary re-renders and improve performance
MockgetBoundingClientRectin tests using the helper function provided intest/helper/MockGetBoundingClientRect.ts
Usevi.useFakeTimers()in all tests due to Redux autoBatchEnhancer dependency on timers andrequestAnimationFrame
Callvi.runOnlyPendingTimers()to advance timers after renders when not usingcreateSelectorTestCasehelper, and avoidvi.runAllTimers()to prevent infinite loops
UseuserEvent.setup({ advanceTimers: vi.runOnlyPendingTimers })or theuserEventSetuphelper function fromtest/helper/userEventSetup.tswhen creating userEvent instances
When testing tooltips on hover, usevi.runOnlyPendingTimers()after eachuserEvent.hover()call or use theshowTooltiphelper function fromtooltipTestHelpers.tsto account for requestAnimationFrame delays
Files:
test/cartesian/getTicks.spec.tstest/util/ChartUtils.spec.tsxtest/component/Tooltip/Tooltip.multipleDataArrays.spec.tsxtest/polar/PolarGrid.spec.tsxtest/util/ChartUtils/checkDomainOfScale.spec.tstest/cartesian/Area.spec.tsxtest/util/ChartUtils/getCateCoordinateOfLine.spec.tstest/cartesian/ReferenceLine/getEndPoints.spec.tsxtest/chart/ScatterChart.spec.tsxtest/polar/PolarAngleAxis.spec.tsxtest/cartesian/CartesianAxis.spec.tsxtest/cartesian/XAxis/XAxis.barSize.spec.tsxtest/cartesian/getEquidistantTicks.spec.tstest/util/CartesianUtils/CartesianUtils.spec.ts
**/*.spec.{ts,tsx}
📄 CodeRabbit inference engine (AGENTS.md)
When running unit tests, prefer to run a single test file using
npm run test -- path/to/TestFile.spec.tsxrather than running all tests withnpm test
Files:
test/cartesian/getTicks.spec.tstest/util/ChartUtils.spec.tsxtest/component/Tooltip/Tooltip.multipleDataArrays.spec.tsxtest/polar/PolarGrid.spec.tsxtest/util/ChartUtils/checkDomainOfScale.spec.tstest/cartesian/Area.spec.tsxtest/util/ChartUtils/getCateCoordinateOfLine.spec.tstest/cartesian/ReferenceLine/getEndPoints.spec.tsxtest/chart/ScatterChart.spec.tsxtest/polar/PolarAngleAxis.spec.tsxtest/cartesian/CartesianAxis.spec.tsxtest/cartesian/XAxis/XAxis.barSize.spec.tsxtest/cartesian/getEquidistantTicks.spec.tstest/util/CartesianUtils/CartesianUtils.spec.ts
test/component/**/*.spec.tsx
📄 CodeRabbit inference engine (CONTRIBUTING.md)
Use React Testing Library for testing component interactions and behavior upon rendering
Files:
test/component/Tooltip/Tooltip.multipleDataArrays.spec.tsx
🧠 Learnings (21)
📓 Common learnings
Learnt from: PavelVanecek
Repo: recharts/recharts PR: 6783
File: test/util/ChartUtils.spec.tsx:15-16
Timestamp: 2025-12-16T08:12:13.355Z
Learning: In the recharts codebase, files in the `test` folder are allowed to import from internal paths (e.g., `../../src/state/cartesianAxisSlice`) and do not need to use the public API entry point (`src/index.ts`). The public API import restriction applies only to non-test code.
📚 Learning: 2025-11-25T01:23:08.250Z
Learnt from: CR
Repo: recharts/recharts PR: 0
File: test/README.md:0-0
Timestamp: 2025-11-25T01:23:08.250Z
Learning: Applies to test/**/*.{test,spec}.{ts,tsx} : Use the `expectLastCalledWith` helper function instead of `expect(spy).toHaveBeenLastCalledWith(...)` for better typing and autocompletion
Applied to files:
test/helper/expectScale.tstest/component/Tooltip/Tooltip.multipleDataArrays.spec.tsxtest/polar/PolarGrid.spec.tsxtest/util/ChartUtils/checkDomainOfScale.spec.tstest/cartesian/Area.spec.tsxtest/util/ChartUtils/getCateCoordinateOfLine.spec.tstest/chart/ScatterChart.spec.tsxtest/polar/PolarAngleAxis.spec.tsxtest/cartesian/XAxis/XAxis.barSize.spec.tsxtest/util/CartesianUtils/CartesianUtils.spec.ts
📚 Learning: 2025-12-16T08:12:13.355Z
Learnt from: PavelVanecek
Repo: recharts/recharts PR: 6783
File: test/util/ChartUtils.spec.tsx:15-16
Timestamp: 2025-12-16T08:12:13.355Z
Learning: In the recharts codebase, files in the `test` folder are allowed to import from internal paths (e.g., `../../src/state/cartesianAxisSlice`) and do not need to use the public API entry point (`src/index.ts`). The public API import restriction applies only to non-test code.
Applied to files:
test/helper/expectScale.tstest/cartesian/getTicks.spec.tssrc/util/scale/CartesianScaleHelper.tssrc/polar/Radar.tsxtest/util/ChartUtils/checkDomainOfScale.spec.tsscripts/snapshots/es6Files.txtsrc/cartesian/ReferenceLine.tsxtest/util/ChartUtils/getCateCoordinateOfLine.spec.tssrc/cartesian/Area.tsxsrc/util/scale/RechartsScale.tsscripts/snapshots/typesFiles.txtscripts/snapshots/libFiles.txtsrc/polar/RadialBar.tsxsrc/cartesian/ReferenceArea.tsxsrc/cartesian/ReferenceDot.tsxsrc/state/selectors/axisSelectors.tssrc/cartesian/Bar.tsxtest/util/CartesianUtils/CartesianUtils.spec.tstest/helper/mockAxes.tssrc/util/ChartUtils.ts
📚 Learning: 2025-11-25T01:23:08.250Z
Learnt from: CR
Repo: recharts/recharts PR: 0
File: test/README.md:0-0
Timestamp: 2025-11-25T01:23:08.250Z
Learning: Applies to test/**/*.{test,spec}.{ts,tsx} : Verify the number of selector calls using the spy object from `createSelectorTestCase` to spot unnecessary re-renders and improve performance
Applied to files:
test/helper/expectScale.tstest/util/ChartUtils.spec.tsxtest/component/Tooltip/Tooltip.multipleDataArrays.spec.tsxtest/polar/PolarGrid.spec.tsxtest/util/ChartUtils/checkDomainOfScale.spec.tstest/cartesian/Area.spec.tsxtest/util/ChartUtils/getCateCoordinateOfLine.spec.tstest/cartesian/ReferenceLine/getEndPoints.spec.tsxtest/chart/ScatterChart.spec.tsxtest/polar/PolarAngleAxis.spec.tsxtest/cartesian/XAxis/XAxis.barSize.spec.tsxtest/util/CartesianUtils/CartesianUtils.spec.ts
📚 Learning: 2025-11-25T01:23:08.250Z
Learnt from: CR
Repo: recharts/recharts PR: 0
File: test/README.md:0-0
Timestamp: 2025-11-25T01:23:08.250Z
Learning: Applies to test/**/*.{test,spec}.{ts,tsx} : Prefer to use the `createSelectorTestCase` helper function when writing or modifying tests
Applied to files:
test/helper/expectScale.tstest/component/Tooltip/Tooltip.multipleDataArrays.spec.tsxtest/polar/PolarGrid.spec.tsxtest/chart/ScatterChart.spec.tsxtest/polar/PolarAngleAxis.spec.tsxtest/util/CartesianUtils/CartesianUtils.spec.ts
📚 Learning: 2025-11-25T01:23:08.250Z
Learnt from: CR
Repo: recharts/recharts PR: 0
File: test/README.md:0-0
Timestamp: 2025-11-25T01:23:08.250Z
Learning: Applies to test/**/*.{test,spec}.{ts,tsx} : Mock `getBoundingClientRect` in tests using the helper function provided in `test/helper/MockGetBoundingClientRect.ts`
Applied to files:
test/helper/expectScale.tstest/cartesian/getTicks.spec.tstest/util/ChartUtils.spec.tsxtest/component/Tooltip/Tooltip.multipleDataArrays.spec.tsxtest/util/ChartUtils/checkDomainOfScale.spec.tstest/cartesian/Area.spec.tsxtest/util/ChartUtils/getCateCoordinateOfLine.spec.tstest/cartesian/ReferenceLine/getEndPoints.spec.tsxtest/chart/ScatterChart.spec.tsxtest/cartesian/getEquidistantTicks.spec.tstest/util/CartesianUtils/CartesianUtils.spec.tstest/helper/mockAxes.ts
📚 Learning: 2025-12-14T13:58:49.197Z
Learnt from: PavelVanecek
Repo: recharts/recharts PR: 6771
File: src/shape/Curve.tsx:39-40
Timestamp: 2025-12-14T13:58:49.197Z
Learning: In the recharts codebase, hooks like useAppSelector and other hooks (e.g., useChartLayout()) return undefined when used outside Redux Provider context, instead of throwing. This enables components that call these hooks, such as Curve, to operate in standalone mode by falling back to prop values. During code reviews, ensure TSX files gracefully handle undefined results from hooks and implement fallbacks (e.g., via default props or explicit prop-based values) rather than assuming the hook is always within Provider.
Applied to files:
src/cartesian/ErrorBar.tsxsrc/cartesian/Line.tsxsrc/polar/Radar.tsxsrc/cartesian/ReferenceLine.tsxsrc/cartesian/Area.tsxsrc/polar/RadialBar.tsxsrc/cartesian/ReferenceArea.tsxsrc/cartesian/ReferenceDot.tsxsrc/cartesian/Scatter.tsxsrc/cartesian/Bar.tsx
📚 Learning: 2025-11-25T01:23:08.250Z
Learnt from: CR
Repo: recharts/recharts PR: 0
File: test/README.md:0-0
Timestamp: 2025-11-25T01:23:08.250Z
Learning: Applies to test/**/*.{test,spec}.{ts,tsx} : When testing tooltips on hover, use `vi.runOnlyPendingTimers()` after each `userEvent.hover()` call or use the `showTooltip` helper function from `tooltipTestHelpers.ts` to account for requestAnimationFrame delays
Applied to files:
test/cartesian/getTicks.spec.tstest/component/Tooltip/Tooltip.multipleDataArrays.spec.tsxtest/polar/PolarGrid.spec.tsxtest/util/ChartUtils/checkDomainOfScale.spec.tssrc/state/selectors/tooltipSelectors.tstest/chart/ScatterChart.spec.tsxtest/polar/PolarAngleAxis.spec.tsx
📚 Learning: 2025-12-16T08:12:06.809Z
Learnt from: PavelVanecek
Repo: recharts/recharts PR: 6783
File: test/util/ChartUtils.spec.tsx:15-16
Timestamp: 2025-12-16T08:12:06.809Z
Learning: In tests (files under any test directory, e.g., test/, __tests__/, etc.), allow importing internal module paths (e.g., ../../src/...) and do not require imports to use the public API entry point (src/index.ts). The public API import restriction should apply only to non-test code. During reviews, accept internal imports in test files and enforce the public API pattern only for non-test code.
Applied to files:
test/util/ChartUtils.spec.tsxtest/component/Tooltip/Tooltip.multipleDataArrays.spec.tsxtest/polar/PolarGrid.spec.tsxtest/cartesian/Area.spec.tsxtest/cartesian/ReferenceLine/getEndPoints.spec.tsxtest/chart/ScatterChart.spec.tsxtest/polar/PolarAngleAxis.spec.tsxtest/cartesian/CartesianAxis.spec.tsxtest/cartesian/XAxis/XAxis.barSize.spec.tsx
📚 Learning: 2025-12-06T03:36:59.377Z
Learnt from: CR
Repo: recharts/recharts PR: 0
File: DEVELOPING.md:0-0
Timestamp: 2025-12-06T03:36:59.377Z
Learning: Applies to **/*.{ts,tsx,js,jsx} : All imports from `recharts` must use the public API entry point; imports from internal paths like `recharts/types/*` or `recharts/src/*` are not allowed
Applied to files:
test/util/ChartUtils.spec.tsxscripts/snapshots/es6Files.txttest/cartesian/ReferenceLine/getEndPoints.spec.tsxsrc/util/scale/RechartsScale.tsscripts/snapshots/typesFiles.txtscripts/snapshots/libFiles.txtsrc/state/selectors/axisSelectors.tstest/util/CartesianUtils/CartesianUtils.spec.tstest/helper/mockAxes.ts
📚 Learning: 2025-11-23T13:30:10.395Z
Learnt from: PavelVanecek
Repo: recharts/recharts PR: 6669
File: www/src/docs/exampleComponents/ScatterChart/ScatterChartWithLabels.tsx:2-2
Timestamp: 2025-11-23T13:30:10.395Z
Learning: The `TooltipIndex` type from recharts is defined in `src/state/tooltipSlice.ts` but is not currently exported from the public API entry points. It should not be imported from `recharts/types/state/tooltipSlice` as this is an internal implementation path. An ESLint rule is needed to prevent regressions.
Applied to files:
test/util/ChartUtils.spec.tsxtest/component/Tooltip/Tooltip.multipleDataArrays.spec.tsxtest/util/ChartUtils/checkDomainOfScale.spec.tssrc/state/selectors/tooltipSelectors.tstest/chart/ScatterChart.spec.tsxsrc/util/scale/RechartsScale.tsscripts/snapshots/typesFiles.txttest/cartesian/XAxis/XAxis.barSize.spec.tsxsrc/state/selectors/axisSelectors.tstest/helper/mockAxes.tssrc/util/ChartUtils.ts
📚 Learning: 2025-11-19T14:08:01.728Z
Learnt from: PavelVanecek
Repo: recharts/recharts PR: 6659
File: www/src/components/GuideView/Performance/index.tsx:232-250
Timestamp: 2025-11-19T14:08:01.728Z
Learning: In Recharts version 3.4.2, object-as-prop optimizations were introduced to reduce unnecessary re-renders when new object references are passed as props. This affects the recommendation for the `react-perf/jsx-no-new-object-as-prop` ESLint rule.
Applied to files:
test/util/ChartUtils.spec.tsxsrc/cartesian/ReferenceLine.tsx
📚 Learning: 2025-11-25T01:22:59.729Z
Learnt from: CR
Repo: recharts/recharts PR: 0
File: CONTRIBUTING.md:0-0
Timestamp: 2025-11-25T01:22:59.729Z
Learning: Applies to storybook/stories/**/*.stories.tsx : Update Storybook stories when APIs have been changed to ensure they work as expected
Applied to files:
test/component/Tooltip/Tooltip.multipleDataArrays.spec.tsxtest/cartesian/Area.spec.tsx
📚 Learning: 2025-11-25T01:23:08.250Z
Learnt from: CR
Repo: recharts/recharts PR: 0
File: test/README.md:0-0
Timestamp: 2025-11-25T01:23:08.250Z
Learning: Applies to test/**/*.{test,spec}.{ts,tsx} : Call `vi.runOnlyPendingTimers()` to advance timers after renders when not using `createSelectorTestCase` helper, and avoid `vi.runAllTimers()` to prevent infinite loops
Applied to files:
test/polar/PolarGrid.spec.tsxtest/chart/ScatterChart.spec.tsxtest/polar/PolarAngleAxis.spec.tsx
📚 Learning: 2025-11-25T01:22:59.729Z
Learnt from: CR
Repo: recharts/recharts PR: 0
File: CONTRIBUTING.md:0-0
Timestamp: 2025-11-25T01:22:59.729Z
Learning: Applies to test/component/**/*.spec.tsx : Use React Testing Library for testing component interactions and behavior upon rendering
Applied to files:
test/polar/PolarGrid.spec.tsxtest/chart/ScatterChart.spec.tsxtest/polar/PolarAngleAxis.spec.tsx
📚 Learning: 2025-11-25T01:22:59.729Z
Learnt from: CR
Repo: recharts/recharts PR: 0
File: CONTRIBUTING.md:0-0
Timestamp: 2025-11-25T01:22:59.729Z
Learning: Applies to **/*.{ts,tsx} : Type function parameters and return values explicitly in TypeScript, do not rely on implicit any or inference; exceptions are React components and trivial functions
Applied to files:
test/util/ChartUtils/checkDomainOfScale.spec.ts
📚 Learning: 2025-11-25T01:22:59.729Z
Learnt from: CR
Repo: recharts/recharts PR: 0
File: CONTRIBUTING.md:0-0
Timestamp: 2025-11-25T01:22:59.729Z
Learning: Applies to **/*.{ts,tsx} : Do not use `as` type assertions in TypeScript; the only exception is `as const`
Applied to files:
test/util/ChartUtils/checkDomainOfScale.spec.ts
📚 Learning: 2025-11-25T01:23:08.250Z
Learnt from: CR
Repo: recharts/recharts PR: 0
File: test/README.md:0-0
Timestamp: 2025-11-25T01:23:08.250Z
Learning: Applies to test/**/*.{test,spec}.{ts,tsx} : Use `vi.useFakeTimers()` in all tests due to Redux autoBatchEnhancer dependency on timers and `requestAnimationFrame`
Applied to files:
test/util/ChartUtils/checkDomainOfScale.spec.tstest/cartesian/Area.spec.tsxtest/util/CartesianUtils/CartesianUtils.spec.ts
📚 Learning: 2025-11-25T01:22:59.729Z
Learnt from: CR
Repo: recharts/recharts PR: 0
File: CONTRIBUTING.md:0-0
Timestamp: 2025-11-25T01:22:59.729Z
Learning: Applies to test/**/*.spec.{ts,tsx} : Aim for 100% unit test code coverage when writing new code
Applied to files:
test/util/ChartUtils/checkDomainOfScale.spec.ts
📚 Learning: 2025-12-14T13:58:58.361Z
Learnt from: PavelVanecek
Repo: recharts/recharts PR: 6771
File: src/shape/Curve.tsx:39-40
Timestamp: 2025-12-14T13:58:58.361Z
Learning: In the recharts codebase, `useAppSelector` and hooks like `useChartLayout()` are designed to return `undefined` when used outside Redux Provider context, rather than throwing errors. This allows components like `Curve` that call these hooks to work standalone by falling back to prop values.
Applied to files:
scripts/snapshots/es6Files.txtscripts/snapshots/libFiles.txtsrc/state/selectors/axisSelectors.tstest/helper/mockAxes.ts
📚 Learning: 2025-11-25T01:22:59.729Z
Learnt from: CR
Repo: recharts/recharts PR: 0
File: CONTRIBUTING.md:0-0
Timestamp: 2025-11-25T01:22:59.729Z
Learning: Extract pure helper functions for data processing and write unit tests for them
Applied to files:
test/util/CartesianUtils/CartesianUtils.spec.ts
🧬 Code graph analysis (15)
src/cartesian/Line.tsx (1)
src/util/DataUtils.ts (1)
isNullish(180-182)
test/cartesian/getTicks.spec.ts (1)
src/util/types.ts (1)
TickItem(832-844)
test/util/ChartUtils.spec.tsx (2)
src/util/ChartUtils.ts (1)
AxisPropsNeededForTicksGenerator(153-168)src/util/scale/RechartsScale.ts (1)
d3ScaleToRechartsScale(99-139)
src/util/scale/CartesianScaleHelper.ts (2)
src/util/types.ts (3)
CategoricalDomainItem(732-732)Coordinate(100-103)NullableCoordinate(105-108)src/util/scale/RechartsScale.ts (2)
BandPosition(82-82)RechartsScale(15-74)
src/polar/Radar.tsx (1)
src/util/DataUtils.ts (1)
isNullish(180-182)
test/util/ChartUtils/checkDomainOfScale.spec.ts (1)
src/util/ChartUtils.ts (1)
checkDomainOfScale(284-301)
test/cartesian/Area.spec.tsx (1)
test/helper/mockAxes.ts (1)
mockScale(5-5)
src/cartesian/ReferenceLine.tsx (5)
src/util/scale/RechartsScale.ts (2)
BandPosition(82-82)RechartsScale(15-74)src/util/types.ts (2)
CartesianViewBoxRequired(866-866)Coordinate(100-103)src/util/isWellBehavedNumber.ts (1)
isWellBehavedNumber(1-3)src/util/scale/CartesianScaleHelper.ts (2)
CartesianScaleHelper(4-16)CartesianScaleHelperImpl(21-71)src/util/DataUtils.ts (1)
isNumOrStr(27-27)
test/cartesian/ReferenceLine/getEndPoints.spec.tsx (2)
src/util/scale/RechartsScale.ts (3)
RechartsScale(15-74)d3ScaleToRechartsScale(99-139)BandPosition(82-82)src/cartesian/ReferenceLine.tsx (2)
getEndPoints(216-245)ReferenceLineSegment(38-47)
src/cartesian/ReferenceArea.tsx (2)
src/util/scale/CartesianScaleHelper.ts (1)
CartesianScaleHelperImpl(21-71)src/util/types.ts (1)
NullableCoordinate(105-108)
src/cartesian/ReferenceDot.tsx (2)
src/util/types.ts (1)
Coordinate(100-103)src/util/scale/CartesianScaleHelper.ts (1)
CartesianScaleHelperImpl(21-71)
src/state/selectors/axisSelectors.ts (4)
src/util/scale/RechartsScale.ts (1)
rechartsScaleFactory(147-171)src/util/types.ts (2)
CategoricalDomainItem(732-732)TickItem(832-844)src/util/isWellBehavedNumber.ts (1)
isWellBehavedNumber(1-3)src/util/DataUtils.ts (1)
isNotNil(202-204)
test/util/CartesianUtils/CartesianUtils.spec.ts (2)
src/util/scale/CartesianScaleHelper.ts (1)
CartesianScaleHelperImpl(21-71)src/util/scale/RechartsScale.ts (1)
d3ScaleToRechartsScale(99-139)
test/helper/mockAxes.ts (1)
src/util/scale/RechartsScale.ts (2)
RechartsScale(15-74)d3ScaleToRechartsScale(99-139)
src/util/ChartUtils.ts (5)
src/util/isWellBehavedNumber.ts (1)
isWellBehavedNumber(1-3)src/util/types.ts (2)
CategoricalDomainItem(732-732)TickItem(832-844)src/util/scale/CustomScaleDefinition.ts (1)
CustomScaleDefinition(13-71)src/index.ts (1)
CustomScaleDefinition(97-97)src/util/DataUtils.ts (2)
isNumber(24-25)isNullish(180-182)
⏰ Context from checks skipped due to timeout of 90000ms. You can increase the timeout in your CodeRabbit configuration to a maximum of 15 minutes (900000ms). (2)
- GitHub Check: Build, Test, Pack
- GitHub Check: Analyze (javascript-typescript)
🔇 Additional comments (67)
scripts/snapshots/typesFiles.txt (1)
240-240: LGTM - Snapshot correctly updated for new CartesianScaleHelper.The addition of the CartesianScaleHelper type definition file to the snapshot is correct and aligns with the introduction of the new scale helper utility.
scripts/snapshots/libFiles.txt (1)
240-240: LGTM - Snapshot correctly updated for new CartesianScaleHelper.The addition of the CartesianScaleHelper library file to the snapshot is correct and aligns with the introduction of the new scale helper utility.
src/util/types.ts (1)
836-843: LGTM - Clear documentation for the offset field.The JSDoc comment clearly explains the purpose of the
offsetfield and its role in the external API. The note about Recharts not reading it internally is helpful context for maintainers.test/component/Tooltip/Tooltip.multipleDataArrays.spec.tsx (1)
134-141: LGTM - Test correctly updated to use map-based scale API.The change from
scale(value)toscale.map(value)correctly adopts the new scale API pattern while maintaining the same expected behavior.test/cartesian/getEquidistantTicks.spec.ts (2)
29-29: LGTM - Test data correctly includes offset field.The addition of
offset: 0to tick objects correctly reflects the updated TickItem type. For non-band scales, the offset is always 0, which is the correct default value.
48-54: LGTM - Test data correctly structured with offset and index fields.The CartesianTickItem objects now properly include the
offsetfield, and the index is correctly added via the map transformation. This aligns with the updated TickItem interface.scripts/snapshots/es6Files.txt (1)
240-240: LGTM - Snapshot correctly updated for new CartesianScaleHelper.The addition of the CartesianScaleHelper ES6 module file to the snapshot is correct and aligns with the introduction of the new scale helper utility.
test/util/ChartUtils/checkDomainOfScale.spec.ts (1)
161-207: LGTM - Type suppressions necessary for comprehensive scale testing.The
@ts-expect-errorannotations are appropriate here. The test arrays contain various D3 scale types with incompatible generic parameters (numbers, dates, strings), whilecheckDomainOfScalehas a generic constraint. The runtime behavior is correct; these suppressions allow comprehensive testing across all scale types without splitting into multiple type-specific test cases.test/util/ChartUtils/getCateCoordinateOfLine.spec.ts (1)
6-6: LGTM - Test mock correctly updated to RechartsScale interface.The mock scale has been properly updated from a callable function to an object with a
mapmethod, aligning with the new RechartsScale API. The behavior remains identical (multiplying by 2), ensuring test continuity.test/cartesian/XAxis/XAxis.barSize.spec.tsx (1)
148-185: LGTM! Test expectations correctly updated for the new TickItem shape.The test expectations now include the
indexfield for each tick, with sequential values from 0 to 5. This aligns with the broader TickItem type enhancement mentioned in the AI summary.src/util/scale/CustomScaleDefinition.ts (1)
51-62: LGTM! Excellent documentation improvement.The expanded JSDoc provides valuable context about the
ticksmethod, including when it's available (quantitative scales only) and references to d3 documentation. This helps developers understand the method's behavior and limitations.test/cartesian/CartesianAxis.spec.tsx (1)
23-29: LGTM! Test data correctly updated for the new TickItem shape.The tick objects now include
index(sequential 0-4) andoffset(consistently 0) fields, matching the enhanced TickItem type signature mentioned in the PR objectives.src/cartesian/Scatter.tsx (1)
748-748: LGTM! Scale API usage correctly updated.The change from
zAxis.scale(z)tozAxis.scale.map(z)aligns with the PR's goal to replace the implicit call signature with an explicitmapmethod for better searchability and to avoid passingthis.test/helper/expectScale.ts (1)
23-23: LGTM! Test helper correctly updated for the new scale API.The change from validating
scaleas a function to validatingscale.mapas a function correctly reflects the new RechartsScale API where scales are objects with amapmethod rather than callable functions.test/cartesian/Area.spec.tsx (1)
1214-1215: LGTM! Test mocks correctly updated for the new scale API.The mock scales now expose a
mapmethod instead of being callable functions themselves, matching the new RechartsScale interface. The scaling behavior is preserved (multiplying by 2 and 3 respectively).src/cartesian/ErrorBar.tsx (2)
169-187: LGTM! Scale API usage correctly updated for x-direction error bars.The change from
scale(value ± bound)toscale.map(value ± bound)aligns with the PR's scale API refactor. The null checking and line construction logic remain unchanged, preserving the existing behavior.
188-207: LGTM! Scale API usage correctly updated for y-direction error bars.The y-direction error bar calculation is updated consistently with the x-direction changes. The use of
scale.map(value ± bound)replaces the previous direct invocation while maintaining the same behavior.src/cartesian/Line.tsx (2)
933-942: LGTM! Scale API usage correctly updated for horizontal layout.The change from
yAxis.scale(value)toyAxis.scale.map(value)aligns with the PR's scale API refactor. The null handling withisNullishcheck is preserved, maintaining the existing behavior for handling missing or invalid data.
944-955: LGTM! Scale API usage correctly updated for vertical layout.The vertical layout is updated consistently with the horizontal layout, using
xAxis.scale.map(value)instead of direct invocation. The null handling and filtering logic remain unchanged, preserving the component's behavior.src/cartesian/Area.tsx (1)
1034-1070:computeAreamigration toscale.maplooks correct and preserves semanticsUsing
xAxis.scale.map(...)/yAxis.scale.map(...)with?? nulland the existingbaseLine ?? 0fallback matches the newRechartsScaleAPI while keeping previous behavior for out-of-domain or nullish values. No issues spotted.src/state/selectors/tooltipSelectors.ts (1)
355-387: Tick generation now correctly usesRechartsScale.mapReplacing
scale(entry)withscale.map(entry)in both categorical and non-categorical branches aligns this selector with the newRechartsScaleinterface, while the existingisWellBehavedNumberguard keeps invalid mappings filtered out. Looks good.test/polar/PolarAngleAxis.spec.tsx (1)
181-234: Tick expectations updated coherently to the richerTickItemshapeAdding explicit
index(andoffsetwhere applicable) to TickItem expectations and tick payloads keeps these tests in sync with the extendedTickItemtype and new scale/tick logic. Indexing and coordinates are consistent across the various radar and radial bar cases.Also applies to: 716-745, 1069-1222, 1780-1796, 1894-1906, 2737-2776
test/helper/mockAxes.ts (1)
3-6: Mock axes now use the sameRechartsScaleabstraction as production codeWrapping the linear D3 scale with
d3ScaleToRechartsScaleand typingmockScaleasRechartsScale<number>aligns the test helper with the new axis scale contract and should make future refactors aroundmap-based usage smoother.src/polar/Radar.tsx (1)
236-267:computeRadarPointssafely migrates toscale.mapfor angle and radiusAngle and radius computations now use
angleAxis.scale.map/radiusAxis.scale.mapwith a?? 0fallback, which integrates withRechartsScaleand avoids leakingundefinedinto the polar coordinate math. The range-handling for baseline points is updated consistently too.test/util/ChartUtils.spec.tsx (2)
16-22: Tests now construct scales viad3ScaleToRechartsScale, matching production typesWrapping
scaleLinear,scaleBand, andscalePointwithd3ScaleToRechartsScalebrings the testAxisPropsNeededForTicksGenerator.scaleandBaseAxisWithScale.scaleinto alignment with theRechartsScaleinterface used inChartUtils, so tick-related helpers exercise the same abstraction as real axes.Also applies to: 34-41, 94-97, 114-127, 131-144
145-151: Tick fixtures updated to includeindex/offsetin line with the newTickItemcontractAdding
index(andoffset: 0where relevant) toTickItemarrays used ingetBandSizeOfAxisandcalculateActiveTickIndextests keeps these expectations compatible with the enrichedTickItemtype and with how ticks are produced elsewhere.Also applies to: 246-252
src/polar/RadialBar.tsx (1)
587-621: Radial bar sector geometry correctly moved toscale.mapUsing
angleAxis.scale.mapandradiusAxis.scale.mapincomputeRadialBarDataItemsaligns radial bar geometry with the new scale abstraction while preserving the existing minPointSize and background-sector logic. Fallback torootStartAngle/rootEndAngleon failed angle mapping is a reasonable safety net.test/polar/PolarGrid.spec.tsx (1)
689-717: Polar grid tick expectations updated consistently with new TickItem shapeThe various polar grid tests now assert full TickItem objects (coordinate, value, index, offset), which matches the updated selector behavior and shared TickItem type. The values look internally consistent across implicit and multi-axis scenarios.
Also applies to: 775-788, 938-959, 1012-1022, 1218-1262
test/chart/ScatterChart.spec.tsx (2)
796-803: Test expectations correctly updated for new TickItem shape.The updated expectations now include
indexandoffsetproperties, aligning with the enhancedTickItemtype. Theoffset: 0is correct for numerical axes without bands.
938-943: Consistent update for YAxis tick expectations.The test expectations correctly include
indexandoffsetfields matching the updatedTickItemtype.src/cartesian/Bar.tsx (3)
959-959: Correct migration to map-based scale access.The
stackedBarStartcomputation correctly usesscale.map()instead of direct invocation.
983-984: Proper null handling preserved after map() migration.The existing null checks on lines 985-987 correctly handle potential
undefinedreturns fromscale.map().
1009-1010: Consistent map-based access for vertical layout.The vertical layout path mirrors the horizontal path correctly, with null checks on lines 1011-1013.
src/cartesian/ReferenceDot.tsx (1)
83-85: Clean migration to CartesianScaleHelperImpl.The use of
scales.map()withposition: 'middle'correctly centers the dot on band scales.src/util/ChartUtils.ts (4)
215-227: Correct migration to map-based scaling with proper null handling.The
scale.map()invocation withisWellBehavedNumbercheck ensures only valid coordinates are used for tick generation.
284-301: Well-designed generic signature for checkDomainOfScale.The generic
<T extends CategoricalDomainItem>constraint ensures type safety while supporting all domain types. The added null check on line 298 properly guards against scales that return undefined for boundary values.
540-545: Improved null safety in getCateCoordinateOfLine.The explicit
isNumbercheck afterscale.map()correctly handles cases where the scale returns undefined, returningnullinstead of potentially propagating undefined values.
565-577: Consistent map-based access in getCateCoordinateOfBar.The null safety pattern is consistent with other scale usages in this file.
test/cartesian/ReferenceLine/getEndPoints.spec.tsx (2)
8-27: Well-designed mock for testing scale isolation.The
throwingScalemock is a good pattern to ensure that certain code paths don't invoke scale methods when they shouldn't. This provides clear test isolation.
352-384: Good use of parameterized tests for overflow scenarios.Using
it.eachfor testing multiple overflow values (hidden,visible,extendDomain,discard) is a clean approach that ensures consistent behavior across all modes while keeping the tests DRY.test/cartesian/getTicks.spec.ts (2)
14-20: Test fixtures correctly updated with offset field.The addition of
offset: 0to all tick items aligns with the updatedTickItemtype. For non-banded scales, an offset of 0 is the expected value.
224-231: Consistent offset handling in dynamically generated tick items.The offset field is correctly added in the dynamically created tick items within the test helper function.
test/util/CartesianUtils/CartesianUtils.spec.ts (4)
8-12: Comprehensive test setup with parameterized position variants.Using
describe.eachfor testing all three position values ('start','middle','end') is an efficient approach that ensures consistent behavior across all band positions.
61-92: Thorough isInRange edge case coverage.The tests cover important edge cases including:
- Values in range
- Values out of range on individual axes
- Missing/null coordinates (which are treated as "in range")
- Empty coordinate objects
This is excellent coverage for the
isInRangemethod.
114-117: Good test for unmapped values in band scales.Testing that unmapped values (values not in the domain like
'Z'and'5') return{ x: 0, y: 0 }validates the fallback behavior of themapmethod.
150-159: Good coverage for fallback behavior with unmapped values.Testing both
'rangeMin'and'rangeMax'fallbacks for unmapped domain values ensures themapWithFallbackmethod correctly falls back when the scale can't map a value.src/cartesian/ReferenceLine.tsx (3)
146-170: Clean refactor using new scale abstraction.The
getHorizontalLineEndPointsfunction now properly usesscale.map()for coordinate calculation andscale.isInRange()for overflow detection. The early return pattern withisWellBehavedNumbervalidation is a good defensive practice.
198-214: Consistent use of CartesianScaleHelper for segment handling.Using
scales.mapWithFallback()with appropriate fallback values ('rangeMin'for start point,'rangeMax'for end point) is a sensible approach for handling partial segment coordinates. TheisInRangecheck properly validates both points.
274-282: Clean integration with the new scale API.The
ReferenceLineImplnow correctly passesxAxisScaleandyAxisScaledirectly togetEndPoints, aligning with the refactored function signature.src/util/scale/RechartsScale.ts (5)
33-47: Well-documented interface extensions.The new
rangeMin(),rangeMax(), andisInRange()methods are clearly documented and provide useful utilities for range validation. This is a clean addition to the interface.
76-82: Good inline documentation for BandPosition type.The
@inlineJSDoc tag and clear description make the type self-documenting.
110-114: Robust isInRange implementation handling reversed ranges.The implementation correctly handles both normal ranges (where
first <= last) and reversed ranges. Usingrange[range.length - 1]is defensive, thoughrange[1]would work given the range is always a tuple of two numbers.
117-137: Correct band position offset calculation.The
mapmethod properly applies band position offsets:
'start': no adjustment (default)'middle': adds half bandwidth'end': adds full bandwidthThe null check on
baseValueensures undefined is returned for unmapped domain values.
147-153: Good immutability pattern with copy().Using
scale.copy()before applying domain and range ensures the original scale is not mutated. This is important for React integration as noted in the interface documentation.src/util/scale/CartesianScaleHelper.ts (3)
1-16: Well-designed interface with proper generic typing.The
CartesianScaleHelperinterface cleanly abstracts the coordinate mapping operations with appropriate domain type parameters. The method signatures properly handle optional/nullable values inmapWithFallbackandisInRange.
18-39: Implementation looks correct.The class properly implements the interface, and the
mapmethod correctly falls back to0when the underlying scale returnsundefined, which aligns with theCoordinatetype requiring concrete numbers.
66-70: Correct null-handling logic inisInRange.Treating
null/undefinedcoordinates as "in range" is appropriate since partial coordinates should not fail the range check. The implementation correctly delegates to the underlying scale'sisInRangemethod.src/state/selectors/axisSelectors.ts (10)
89-89: Import updated to use new scale factory.The import correctly reflects the rename from
makeRechartsScaletorechartsScaleFactory.
1144-1158: Scale factory usage is correct.The function properly delegates to
rechartsScaleFactoryfor both custom scale functions and string-based scale types, maintaining the expected return type.
1845-1845: Type annotation improved.Changing
categoricalDomainfromReadonlyArray<unknown>toReadonlyArray<CategoricalDomainItem>provides better type safety and aligns with the coding guidelines to avoidanyandunknownwhere possible.
1869-1886: Scale mapping refactored correctly.The transition from direct scale invocation to
scale.map()is correctly applied. The null check viaisWellBehavedNumberappropriately handles cases wheremap()returnsundefined.
1888-1904: Categorical domain handling updated with proper typing.The
entryparameter is now correctly typed asCategoricalDomainItem, and thescale.map(entry)call follows the new API pattern.
1906-1917: Tick generation with scale.ticks() correctly uses map().The refactored code properly chains
scale.ticks(tickCount)with.map()and usesscale.map(entry)for coordinate calculation.
1919-1936: Domain-based tick generation updated correctly.The fallback path using
scale.domain()properly appliesscale.map(entry)with the typedCategoricalDomainItem. The remaining@ts-expect-erroron line 1929-1930 is an acknowledged limitation with Date indexing.
1965-1976: Function signature properly updated.The
categoricalDomainparameter type is correctly changed toReadonlyArray<CategoricalDomainItem>, consistent withcombineAxisTicks.
1987-2015: Tick generation paths correctly use scale.map().Both the categorical domain path and the
scale.ticks()path correctly apply the newscale.map(entry)pattern with proper null handling.
2017-2034: Domain fallback path updated consistently.The domain-based tick generation mirrors the pattern in
combineAxisTicks, with the same acknowledged limitation for Date indexing preserved via@ts-expect-error.
Codecov Report❌ Patch coverage is
Additional details and impacted files@@ Coverage Diff @@
## main #6811 +/- ##
==========================================
- Coverage 93.44% 93.44% -0.01%
==========================================
Files 522 523 +1
Lines 45580 45622 +42
Branches 5047 5056 +9
==========================================
+ Hits 42594 42632 +38
- Misses 2979 2983 +4
Partials 7 7 ☔ View full report in Codecov by Sentry. 🚀 New features to boost your workflow:
|
|
Staging Deployment Details
These deployments will remain available for 30 days. To update snapshots: Comment |
Bundle ReportChanges will increase total bundle size by 2.61kB (0.1%) ⬆️. This is within the configured threshold ✅ Detailed changes
Affected Assets, Files, and Routes:view changes for bundle: recharts/bundle-umdAssets Changed:
view changes for bundle: recharts/bundle-cjsAssets Changed:
view changes for bundle: recharts/bundle-es6Assets Changed:
|
Description
Now that we have internal and external scale representations, we can make changes to the internal one.
First I renamed the "apply/implicit call signature" (typescript treats them equally even though they have different arguments - very confusing) to "map" so that we can search for usage and we do not need to worry about passing "this"
That exposed many many @ts-expect-error so I removed and fixed those - this was hiding a tick index/offset problem so I fixed that.
Then I added the "position" argument from ScaleHelper.apply into RechartsScale.map, this is useful
Then I replaced "createLabeledScales" with new "CartesianScaleHelper" and used it in Reference elements
And then removed ScaleHelper and createLabeledScales and replaced all "any" with RechartsScale/CartesianScaleHelper.
Related Issue
#6645
Motivation and Context
Removing
anySummary by CodeRabbit
New Features
Enhancements
✏️ Tip: You can customize this high-level summary in your review settings.