Skip to content

New feature - typed charts helper#7071

Merged
ckifer merged 12 commits intomainfrom
createtypedchart
Mar 3, 2026
Merged

New feature - typed charts helper#7071
ckifer merged 12 commits intomainfrom
createtypedchart

Conversation

@PavelVanecek
Copy link
Collaborator

@PavelVanecek PavelVanecek commented Mar 1, 2026

Description

Four new functions, and docs.

I will pull tests from the other PR, and I will play around with the polar charts, I am not certain if the current structure makes sense. done

Also I think we don't allow vertical FunnelChart? So that might be something to highlight too. and done

Other than that I think we can merge this once these details are sorted done.

Related Issue

Fixes #7046

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

  • New Features

    • Added typed chart factory APIs for Cartesian and Polar charts with new public helpers for horizontal/vertical and centric/radial layouts.
  • Documentation

    • Added a TypeScript guide with three step-by-step examples, integrated into site navigation and localized strings.
  • Tests

    • Added extensive tests covering the new chart factories, layout enforcement, and type-related behaviors.
  • Chores

    • Updated build/bundling tooling and treeshaking support; adjusted example-validation list to skip certain chart helpers.

…or enhanced TypeScript support and introduce a new TypeScript guide in the documentation.
…ePolarCharts` utilities by omitting the explicit `layout` prop from typed components.
…pes to cartesian contexts, and refine generic types for several chart props.
@coderabbitai
Copy link
Contributor

coderabbitai bot commented Mar 1, 2026

No actionable comments were generated in the recent review. 🎉

ℹ️ Recent review info

Configuration used: Organization UI

Review profile: CHILL

Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between 89e62c9 and e0e67fd.

⛔ Files ignored due to path filters (1)
  • package-lock.json is excluded by !**/package-lock.json
📒 Files selected for processing (6)
  • omnidoc/verifyExamples.spec.ts
  • src/index.ts
  • www/src/locale/en-US.ts
  • www/src/locale/zh-CN.ts
  • www/src/navigation.data.ts
  • www/src/views/GuideView.tsx
🚧 Files skipped from review as they are similar to previous changes (3)
  • www/src/locale/zh-CN.ts
  • www/src/navigation.data.ts
  • www/src/locale/en-US.ts

Walkthrough

Adds four typed chart-factory helpers and their context types, exposes them in the public API, updates treeshaking tooling and build deps, adds TypeScript site guide examples and routes, updates tests and snapshots, and adjusts verifyExamples exclusions.

Changes

Cohort / File(s) Summary
Chart factory utilities
src/util/createCartesianCharts.tsx, src/util/createPolarCharts.tsx
New TypeScript React modules providing typed chart factory functions and exported context/types for horizontal/vertical and radial/centric layouts.
Public API
src/index.ts
Exports new factory functions and typed contexts/types to the public surface.
Treeshaking tooling
scripts/treeshaking.ts, scripts/treeshaking-groups/index.ts
Enhances treeshaking: adds Rollup/Babel/node-resolve plugins, recharts aliasing, file-path entry mode, extended index resolution, and new treeshaking groups for the factories.
Build config / deps
package.json
Bumps Babel preset versions and adds Rollup plugins plus rollup-plugin-esbuild to deps/devDeps.
Examples & Docs (site)
www/src/components/GuideView/TypeScript/*, www/src/components/GuideView/index.ts, www/src/views/GuideView.tsx, www/src/navigation.data.ts, www/src/docs/apiCates.ts
Adds a TypeScript guide (three steps), registers route and guide component, and documents new factory functions in API categories.
Locale updates
www/src/locale/en-US.ts, www/src/locale/zh-CN.ts
Adds TypeScript guide strings for English and Chinese locales.
Tests & verification
test/util/createChartHelpers.spec.tsx, omnidoc/verifyExamples.spec.ts
Adds extensive tests for the new factories; updates verifyExamples exclusions by adding new factory names and typed contexts.
Snapshots / build artifacts
scripts/snapshots/es6Files.txt, scripts/snapshots/libFiles.txt, scripts/snapshots/typesFiles.txt
Adds entries for new utility modules and their type declarations to snapshot listings.
Site component export
www/src/components/GuideView/index.ts
Includes the new TypeScript guide in the exported GuideView components list.

Sequence Diagram(s)

sequenceDiagram
  participant CLI as CLI
  participant Treeshaker as treeshaking.ts
  participant FS as FileSystem
  participant NodeResolve as "@rollup/plugin-node-resolve"
  participant Rollup as Rollup
  participant Babel as "@rollup/plugin-babel"

  CLI->>Treeshaker: invoke (component names | file path)
  Treeshaker->>FS: read src entry or provided file
  Treeshaker->>NodeResolve: resolve imports (index variants, node_modules)
  Treeshaker->>Rollup: run bundling with plugins
  Rollup->>Babel: transpile TS/TSX/JSX with presets
  Rollup->>Treeshaker: return module graph / size report
  Treeshaker->>CLI: output treeshake results / report
Loading

Estimated code review effort

🎯 4 (Complex) | ⏱️ ~45 minutes

Possibly related PRs

Suggested labels

enhancement, feature request, typescript

Suggested reviewers

  • ckifer
🚥 Pre-merge checks | ✅ 4 | ❌ 1

❌ Failed checks (1 warning)

Check name Status Explanation Resolution
Docstring Coverage ⚠️ Warning Docstring coverage is 66.67% which is insufficient. The required threshold is 80.00%. Write docstrings for the functions missing them to satisfy the coverage threshold.
✅ Passed checks (4 passed)
Check name Status Explanation
Title check ✅ Passed The title 'New feature - typed charts helper' clearly summarizes the main change: adding typed chart helper functions.
Description check ✅ Passed PR description covers key sections: description, related issue, types of changes, and completion checklist. Most required template sections are addressed, though motivation/context and testing details are minimal.
Linked Issues check ✅ Passed All objectives from issue #7046 are met: four layout-specific helpers (createHorizontalChart, createVerticalChart, createRadialChart, createCentricChart) implemented, layout prop hardcoded, generics propagated to relevant components, tree-shaking preserved.
Out of Scope Changes check ✅ Passed Changes are tightly scoped: adds typed chart helpers, supporting utilities, documentation, tests, and guide examples. Build configuration updates support the new feature without introducing unrelated changes.

✏️ Tip: You can configure your own custom pre-merge checks in the settings.

✨ Finishing Touches
  • 📝 Generate docstrings (stacked PR)
  • 📝 Generate docstrings (commit on current branch)
🧪 Generate unit tests (beta)
  • Create PR with unit tests
  • Post copyable unit tests in a comment
  • Commit unit tests in branch createtypedchart

Tip

Try Coding Plans. Let us write the prompt for your AI agent so you can ship faster (with fewer bugs).
Share your feedback on Discord.


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

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

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: 8

🧹 Nitpick comments (2)
src/util/createCartesianCharts.tsx (1)

1-99: Unit tests needed for utility module.

This utility module in src/**/util/** should have unit tests. The PR summary mentions tests will be imported from another PR - please ensure this is tracked.

Based on learnings: "Extract pure helper functions for data processing and unit test them" and the guideline to "Aim for 100% unit test code coverage when writing new code."

Would you like me to help generate unit test scaffolding for createHorizontalChart and createVerticalChart?

🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In `@src/util/createCartesianCharts.tsx` around lines 1 - 99, Add unit tests for
the utility functions createHorizontalChart and createVerticalChart: write tests
that import createHorizontalChart and createVerticalChart, call them with a
small TData type and a mock components object, and assert the returned object
contains the wrapped AreaChart/BarChart/LineChart/ComposedChart/ScatterChart
keys and the provided custom components; mount or shallow-render the returned
AreaChart/BarChart/etc. with sample props and verify they receive the correct
layout prop ('horizontal' or 'vertical') and pass through other props unchanged;
also add tests that custom component keys from the input TComponents are present
and callable. If any non-pure data processing is found inside
createCartesianCharts, extract those parts into pure helper functions and unit
test them individually to reach high coverage; ensure tests are tracked in the
PR that will import shared tests as mentioned in the summary.
scripts/treeshaking-groups/index.ts (1)

112-163: Minor inconsistency: self-inclusion in treeshaking groups.

createRadialChart and createCentricChart include themselves in their respective bundle lists (Lines 141, 153), while createVerticalChart and createHorizontalChart do not. This inconsistency may affect treeshaking verification accuracy.

Consider either adding createVerticalChart and createHorizontalChart to their own lists, or removing createRadialChart and createCentricChart from theirs, depending on the expected treeshaking behavior.

🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In `@scripts/treeshaking-groups/index.ts` around lines 112 - 163, The treeshaking
groups are inconsistent: createRadialChart and createCentricChart include their
own names in their arrays while createVerticalChart and createHorizontalChart do
not; pick a consistent approach and apply it across the groups in the
treeshaking map (the arrays for createVerticalChart, createHorizontalChart,
createRadialChart, createCentricChart). Either add 'createVerticalChart' and
'createHorizontalChart' to their respective arrays or remove 'createRadialChart'
and 'createCentricChart' from theirs so all four group definitions treat
self-inclusion the same; update the arrays in the treeshaking-groups file
accordingly.
🤖 Prompt for all review comments with AI agents
Verify each finding against the current code and only fix it if needed.

Inline comments:
In `@scripts/treeshaking.ts`:
- Around line 49-54: The generated import specifiers currently inject OS
absolute paths directly (see variables absolutePath and srcEntry used when
building source), which breaks Node ESM on Windows; convert those filesystem
paths to file:// URLs using pathToFileURL(absolutePath).href and
pathToFileURL(srcEntry).href and then wrap the resulting specifier strings with
JSON.stringify(...) when interpolating into source (the strings created for
source that reference firstArg or importList/componentList) so the specifier is
a valid, escaped ESM URL.
- Around line 7-8: Replace the default imports from the Rollup plugins with
their named exports: change "import resolve from '@rollup/plugin-node-resolve'"
to "import { nodeResolve } from '@rollup/plugin-node-resolve'" and change
"import babel from '@rollup/plugin-babel'" to "import { babel } from
'@rollup/plugin-babel'"; update any usages in this file that pass the plugin
instances (e.g., when building the plugins array or invoking resolve/babel) to
call nodeResolve(...) instead of resolve(...), and ensure any other import
occurrences in this file that reference these plugins (the other import blocks
around the other plugin usages) follow the same named-import pattern.

In `@src/index.ts`:
- Around line 214-220: Add unit tests that cover the newly exported helpers
createHorizontalChart, createVerticalChart, createCentricChart, and
createRadialChart and their exported context types (TypedHorizontalChartContext,
TypedVerticalChartContext, TypedCentricChartContext, TypedRadialChartContext);
specifically write specs that assert layout enforcement behavior (correct layout
values produced/validated) and generic propagation (that supplied generic
props/types flow through the helper to the returned chart context and methods),
include negative cases for invalid layouts, and add a simple matrix of
permutations (cartesian vs polar, horizontal vs vertical/centric vs radial) to
ensure the public API exports are present and fully exercised to meet the
repository’s 100% new-code unit test coverage requirement.

In `@src/util/createCartesianCharts.tsx`:
- Line 93: The generic constraint on withComponents uses Record<string, any>,
which violates the no-any guideline; update the generic TComponents constraint
in the withComponents function (returned by createCartesianCharts) to use
Record<string, unknown> instead of Record<string, any> (mirroring the fix
applied in createHorizontalChart), and ensure any downstream type refinements or
usages of TComponents are narrowed from unknown where needed.
- Line 84: The generic constraint on withComponents currently uses
Record<string, any>, which violates the "no any" rule; change the constraint to
Record<string, unknown> (or a more specific mapped type if you can narrow
component shapes) in the withComponents<TComponents extends Record<string,
unknown>> signature, then refine usages inside
createCartesianCharts/withComponents to properly narrow or type-guard properties
of TComponents where needed.

In `@src/util/createPolarCharts.tsx`:
- Line 63: Replace the generic constraint on withComponents to avoid using the
any type: change TComponents extends Record<string, any> to use unknown (e.g.,
Record<string, unknown>) and update any downstream usages of TComponents inside
withComponents to refine/cast the unknown to the specific expected shapes (or
use type guards) so you preserve type-safety while eliminating any; target the
withComponents<TComponents> declaration and usages inside createPolarCharts.tsx
to make these changes.
- Line 54: The generic constraint on withComponents uses Record<string, any>,
which violates the no-any guideline; change the signature to use unknown (e.g.,
function withComponents<TComponents extends Record<string, unknown>>(components:
TComponents)) and if any places rely on concrete value types, narrow them with
appropriate type guards or casts where used (refer to the withComponents
function and TComponents generic to locate and update usages).

In `@www/src/locale/zh-CN.ts`:
- Around line 74-85: Translate the English strings in the typescript locale
object to Chinese: replace the value for the top-level key typescript.typescript
and the keys 'step-1-title', 'step-1-desc', 'step-2-title', 'step-2-desc',
'step-3-title', and 'step-3-desc' with appropriate zh-CN translations matching
the style of other sections (e.g., use Chinese sentences like the existing
'getting-started' translations); keep the keys unchanged and preserve any inline
code punctuation or examples in backticks when translating descriptions.

---

Nitpick comments:
In `@scripts/treeshaking-groups/index.ts`:
- Around line 112-163: The treeshaking groups are inconsistent:
createRadialChart and createCentricChart include their own names in their arrays
while createVerticalChart and createHorizontalChart do not; pick a consistent
approach and apply it across the groups in the treeshaking map (the arrays for
createVerticalChart, createHorizontalChart, createRadialChart,
createCentricChart). Either add 'createVerticalChart' and
'createHorizontalChart' to their respective arrays or remove 'createRadialChart'
and 'createCentricChart' from theirs so all four group definitions treat
self-inclusion the same; update the arrays in the treeshaking-groups file
accordingly.

In `@src/util/createCartesianCharts.tsx`:
- Around line 1-99: Add unit tests for the utility functions
createHorizontalChart and createVerticalChart: write tests that import
createHorizontalChart and createVerticalChart, call them with a small TData type
and a mock components object, and assert the returned object contains the
wrapped AreaChart/BarChart/LineChart/ComposedChart/ScatterChart keys and the
provided custom components; mount or shallow-render the returned
AreaChart/BarChart/etc. with sample props and verify they receive the correct
layout prop ('horizontal' or 'vertical') and pass through other props unchanged;
also add tests that custom component keys from the input TComponents are present
and callable. If any non-pure data processing is found inside
createCartesianCharts, extract those parts into pure helper functions and unit
test them individually to reach high coverage; ensure tests are tracked in the
PR that will import shared tests as mentioned in the summary.

ℹ️ Review info

Configuration used: Organization UI

Review profile: CHILL

Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between 758c6d4 and 52248ad.

⛔ Files ignored due to path filters (1)
  • package-lock.json is excluded by !**/package-lock.json
📒 Files selected for processing (20)
  • omnidoc/verifyExamples.spec.ts
  • package.json
  • scripts/snapshots/es6Files.txt
  • scripts/snapshots/libFiles.txt
  • scripts/snapshots/typesFiles.txt
  • scripts/treeshaking-groups/index.ts
  • scripts/treeshaking.ts
  • src/index.ts
  • src/util/createCartesianCharts.tsx
  • src/util/createPolarCharts.tsx
  • www/src/components/GuideView/TypeScript/Step1.tsx
  • www/src/components/GuideView/TypeScript/Step2.tsx
  • www/src/components/GuideView/TypeScript/Step3.tsx
  • www/src/components/GuideView/TypeScript/index.tsx
  • www/src/components/GuideView/index.ts
  • www/src/docs/apiCates.ts
  • www/src/locale/en-US.ts
  • www/src/locale/zh-CN.ts
  • www/src/navigation.data.ts
  • www/src/views/GuideView.tsx

@codecov
Copy link

codecov bot commented Mar 1, 2026

Codecov Report

❌ Patch coverage is 49.14530% with 119 lines in your changes missing coverage. Please review.
✅ Project coverage is 89.56%. Comparing base (6ebdad8) to head (e0e67fd).
⚠️ Report is 11 commits behind head on main.

Files with missing lines Patch % Lines
www/src/components/GuideView/TypeScript/index.tsx 13.23% 59 Missing ⚠️
www/src/components/GuideView/TypeScript/Step1.tsx 34.48% 19 Missing ⚠️
www/src/components/GuideView/TypeScript/Step2.tsx 34.48% 19 Missing ⚠️
www/src/components/GuideView/TypeScript/Step3.tsx 44.11% 19 Missing ⚠️
src/util/createCartesianCharts.tsx 90.90% 3 Missing ⚠️
Additional details and impacted files
@@            Coverage Diff             @@
##             main    #7071      +/-   ##
==========================================
- Coverage   89.80%   89.56%   -0.24%     
==========================================
  Files         529      535       +6     
  Lines       39911    40143     +232     
  Branches     5447     5459      +12     
==========================================
+ Hits        35843    35956     +113     
- Misses       4059     4178     +119     
  Partials        9        9              

☔ 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.

@github-actions
Copy link
Contributor

github-actions bot commented Mar 1, 2026

Staging Deployment Details

These deployments will remain available for 30 days.

To update snapshots: Comment /update-snapshots on this PR to automatically update the baseline screenshots.

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.

🧹 Nitpick comments (1)
scripts/treeshaking.ts (1)

80-107: Plugin configuration is duplicated.

The plugin array (recharts-alias, nodeResolve, babel, resolveDirectoryIndexPlugin) is nearly identical in both treeshake() (lines 80-107) and getModuleGraph() (lines 157-182). Consider extracting to a shared helper for maintainability.

♻️ Optional: Extract shared plugin configuration
+function getPlugins() {
+  return [
+    {
+      name: 'recharts-alias',
+      resolveId(source: string) {
+        if (source === 'recharts') {
+          return srcEntry;
+        }
+        if (source.startsWith('file://')) {
+          return fileURLToPath(source);
+        }
+        return null;
+      },
+    },
+    nodeResolve({
+      extensions: ['.mjs', '.js', '.jsx', '.json', '.node', '.ts', '.tsx'],
+      moduleDirectories: ['node_modules'],
+    }),
+    babel({
+      babelHelpers: 'bundled',
+      extensions: ['.js', '.jsx', '.ts', '.tsx'],
+      presets: [
+        ['@babel/preset-env', { targets: { node: 'current' } }],
+        ['@babel/preset-react', { runtime: 'automatic' }],
+        '@babel/preset-typescript',
+      ],
+    }),
+    resolveDirectoryIndexPlugin,
+  ];
+}

Then use plugins: getPlugins() and plugins: [...getPlugins(), captureModuleGraphPlugin] in the respective functions.

Also applies to: 156-182

🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In `@scripts/treeshaking.ts` around lines 80 - 107, The plugins array is
duplicated between treeshake() and getModuleGraph(); extract the shared plugin
configuration into a helper function (e.g., getPlugins) that returns the common
array (including the 'recharts-alias' resolver, nodeResolve, babel, and
resolveDirectoryIndexPlugin entries) and then use plugins: getPlugins() inside
treeshake() and plugins: [...getPlugins(), captureModuleGraphPlugin] (or
similar) inside getModuleGraph() so only the extra captureModuleGraphPlugin is
appended in getModuleGraph; update references to srcEntry/fileURLToPath inside
the extracted helper as needed.
🤖 Prompt for all review comments with AI agents
Verify each finding against the current code and only fix it if needed.

Nitpick comments:
In `@scripts/treeshaking.ts`:
- Around line 80-107: The plugins array is duplicated between treeshake() and
getModuleGraph(); extract the shared plugin configuration into a helper function
(e.g., getPlugins) that returns the common array (including the 'recharts-alias'
resolver, nodeResolve, babel, and resolveDirectoryIndexPlugin entries) and then
use plugins: getPlugins() inside treeshake() and plugins: [...getPlugins(),
captureModuleGraphPlugin] (or similar) inside getModuleGraph() so only the extra
captureModuleGraphPlugin is appended in getModuleGraph; update references to
srcEntry/fileURLToPath inside the extracted helper as needed.

ℹ️ Review info

Configuration used: Organization UI

Review profile: CHILL

Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between 52248ad and fdcc548.

📒 Files selected for processing (5)
  • scripts/treeshaking-groups/index.ts
  • scripts/treeshaking.ts
  • src/util/createPolarCharts.tsx
  • test/util/createChartHelpers.spec.tsx
  • www/src/locale/zh-CN.ts

@github-actions
Copy link
Contributor

github-actions bot commented Mar 1, 2026

Staging Deployment Details

These deployments will remain available for 30 days.

To update snapshots: Comment /update-snapshots on this PR to automatically update the baseline screenshots.

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

🧹 Nitpick comments (1)
src/util/createCartesianCharts.tsx (1)

74-84: Consider adding explicit return type annotation.

Per coding guidelines, function return values should be explicitly typed. While TypeScript can infer the return type, an explicit annotation improves maintainability and catches regressions if the implementation changes.

♻️ Proposed refactor
-const createCartesianCharts = <TData,>(layout: 'horizontal' | 'vertical') => ({
+const createCartesianCharts = <TData,>(layout: 'horizontal' | 'vertical'): {
+  AreaChart: React.ComponentType<Omit<CartesianChartProps<TData>, 'layout'>>;
+  BarChart: React.ComponentType<Omit<CartesianChartProps<TData>, 'layout'>>;
+  LineChart: React.ComponentType<Omit<CartesianChartProps<TData>, 'layout'>>;
+  ComposedChart: React.ComponentType<Omit<CartesianChartProps<TData>, 'layout'>>;
+  ScatterChart: React.ComponentType<Omit<CartesianChartProps<TData>, 'layout'>>;
+} => ({
🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In `@src/util/createCartesianCharts.tsx` around lines 74 - 84, The factory
createCartesianCharts currently relies on inferred return types; add an explicit
return type to the function signature to follow our coding guidelines and catch
future regressions. Update the signature of
createCartesianCharts<TData,>(layout: 'horizontal' | 'vertical') to declare the
concrete returned shape (an object with AreaChart, BarChart, LineChart,
ComposedChart, ScatterChart component types matching
Omit<CartesianChartProps<TData>, 'layout'> => JSX.Element) so the compiler
enforces the API; ensure the return type references the same component prop
shape and JSX.Element return type for OriginalAreaChart, OriginalBarChart,
OriginalLineChart, OriginalComposedChart, and OriginalScatterChart.
🤖 Prompt for all review comments with AI agents
Verify each finding against the current code and only fix it if needed.

Inline comments:
In `@src/util/createCartesianCharts.tsx`:
- Line 126: The double type assertion cast "as unknown as
TypedHorizontalChartContext<TData, TCategorical, TNumerical, TComponents>" is
used repeatedly (e.g., in createCartesianCharts and createPolarCharts) and
violates the contributing rules; either remove it by adjusting the types so the
constructed object matches TypedHorizontalChartContext<TData, TCategorical,
TNumerical, TComponents> directly (fix factory return types, narrow intermediate
types, or introduce a proper helper/constructor type) or, if the cast is an
intentional, documented exception, add a clear comment above the offending
assertion referencing the exception policy and issue `#6898` (similar to the
forwardRef exception) explaining why the double assertion is necessary and
listing the affected symbols (TypedHorizontalChartContext,
createCartesianCharts, createPolarCharts) so maintainers know it’s deliberate.

---

Nitpick comments:
In `@src/util/createCartesianCharts.tsx`:
- Around line 74-84: The factory createCartesianCharts currently relies on
inferred return types; add an explicit return type to the function signature to
follow our coding guidelines and catch future regressions. Update the signature
of createCartesianCharts<TData,>(layout: 'horizontal' | 'vertical') to declare
the concrete returned shape (an object with AreaChart, BarChart, LineChart,
ComposedChart, ScatterChart component types matching
Omit<CartesianChartProps<TData>, 'layout'> => JSX.Element) so the compiler
enforces the API; ensure the return type references the same component prop
shape and JSX.Element return type for OriginalAreaChart, OriginalBarChart,
OriginalLineChart, OriginalComposedChart, and OriginalScatterChart.

ℹ️ Review info

Configuration used: Organization UI

Review profile: CHILL

Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between fdcc548 and 89e62c9.

📒 Files selected for processing (9)
  • omnidoc/verifyExamples.spec.ts
  • scripts/treeshaking-groups/index.ts
  • src/index.ts
  • src/util/createCartesianCharts.tsx
  • src/util/createPolarCharts.tsx
  • test/util/createChartHelpers.spec.tsx
  • www/src/components/GuideView/TypeScript/index.tsx
  • www/src/locale/en-US.ts
  • www/src/locale/zh-CN.ts
🚧 Files skipped from review as they are similar to previous changes (7)
  • scripts/treeshaking-groups/index.ts
  • test/util/createChartHelpers.spec.tsx
  • src/util/createPolarCharts.tsx
  • www/src/locale/en-US.ts
  • www/src/components/GuideView/TypeScript/index.tsx
  • omnidoc/verifyExamples.spec.ts
  • www/src/locale/zh-CN.ts

return {
...createCartesianCharts<TData>('horizontal'),
...components,
} as unknown as TypedHorizontalChartContext<TData, TCategorical, TNumerical, TComponents>;
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 | 🟡 Minor

🧩 Analysis chain

🏁 Script executed:

# First, let's look at the specific file and line
cat -n src/util/createCartesianCharts.tsx | sed -n '120,135p'

Repository: recharts/recharts

Length of output: 864


🏁 Script executed:

# Check for similar double assertions as requested in the review
rg -n "as unknown as" --type ts --type tsx -g '!test/**' -g '!*.spec.*'

Repository: recharts/recharts

Length of output: 88


🏁 Script executed:

# Get broader context around line 126
wc -l src/util/createCartesianCharts.tsx

Repository: recharts/recharts

Length of output: 99


🏁 Script executed:

# Search for "as unknown as" patterns without file type issues
rg "as unknown as" --include="*.ts" --include="*.tsx" | grep -v test | grep -v spec

Repository: recharts/recharts

Length of output: 502


🏁 Script executed:

# Get more context around line 126 - see the function definition and types
cat -n src/util/createCartesianCharts.tsx | sed -n '100,150p'

Repository: recharts/recharts

Length of output: 2893


🏁 Script executed:

# Check if TypedHorizontalChartContext is defined and understand the type structure
rg -n "TypedHorizontalChartContext" --include="*.ts" --include="*.tsx"

Repository: recharts/recharts

Length of output: 502


🏁 Script executed:

# Search for "as unknown as" with correct rg syntax
rg "as unknown as" -g '!test' -g '!spec'

Repository: recharts/recharts

Length of output: 718


🏁 Script executed:

# Find TypedHorizontalChartContext type definition
rg -n "type TypedHorizontalChartContext"

Repository: recharts/recharts

Length of output: 188


🏁 Script executed:

# Also check for TypedVerticalChartContext to see if there's a similar pattern
rg -n "TypedVerticalChartContext\|TypedHorizontalChartContext" src/util/

Repository: recharts/recharts

Length of output: 43


🏁 Script executed:

# Check the return type of createCartesianCharts
rg -A 5 "function createCartesianCharts" src/util/createCartesianCharts.tsx

Repository: recharts/recharts

Length of output: 43


🏁 Script executed:

# Read the type definition of TypedHorizontalChartContext
cat -n src/util/createCartesianCharts.tsx | sed -n '15,40p'

Repository: recharts/recharts

Length of output: 1582


🏁 Script executed:

# Check ActiveShapeUtils.tsx to see if similar pattern has context
cat -n src/util/ActiveShapeUtils.tsx | grep -B 3 -A 3 "as unknown as ShapePropsType"

Repository: recharts/recharts

Length of output: 686


🏁 Script executed:

# Look at createPolarCharts to see if similar pattern exists
cat -n src/util/createPolarCharts.tsx | grep -B 5 -A 2 "as unknown as TypedCentricChartContext"

Repository: recharts/recharts

Length of output: 571


🏁 Script executed:

# Check if there's any issue or discussion in git history about this pattern
git log --oneline src/util/createCartesianCharts.tsx | head -10

Repository: recharts/recharts

Length of output: 80


Document or restructure to avoid double assertion.

The pattern as unknown as TypedHorizontalChartContext<...> appears systematically across chart factory functions (createCartesianCharts, createPolarCharts) and utility files (6 occurrences total). While this differs from the documented forwardRef exception, it's a deliberate design choice in this codebase.

Either document this as an intentional exception in the code comments (similar to the forwardRef pattern exception tracked in issue #6898), or refactor the type system to eliminate the need for the double assertion. The current approach violates the CONTRIBUTING.md rule without explicit justification.

🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In `@src/util/createCartesianCharts.tsx` at line 126, The double type assertion
cast "as unknown as TypedHorizontalChartContext<TData, TCategorical, TNumerical,
TComponents>" is used repeatedly (e.g., in createCartesianCharts and
createPolarCharts) and violates the contributing rules; either remove it by
adjusting the types so the constructed object matches
TypedHorizontalChartContext<TData, TCategorical, TNumerical, TComponents>
directly (fix factory return types, narrow intermediate types, or introduce a
proper helper/constructor type) or, if the cast is an intentional, documented
exception, add a clear comment above the offending assertion referencing the
exception policy and issue `#6898` (similar to the forwardRef exception)
explaining why the double assertion is necessary and listing the affected
symbols (TypedHorizontalChartContext, createCartesianCharts, createPolarCharts)
so maintainers know it’s deliberate.

@github-actions
Copy link
Contributor

github-actions bot commented Mar 1, 2026

Staging Deployment Details

These deployments will remain available for 30 days.

To update snapshots: Comment /update-snapshots on this PR to automatically update the baseline screenshots.

@github-actions
Copy link
Contributor

github-actions bot commented Mar 2, 2026

Staging Deployment Details

These deployments will remain available for 30 days.

To update snapshots: Comment /update-snapshots on this PR to automatically update the baseline screenshots.

@codecov
Copy link

codecov bot commented Mar 2, 2026

Bundle Report

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

Detailed changes
Bundle name Size Change
recharts/bundle-cjs 1.28MB 13.92kB (1.1%) ⬆️
recharts/bundle-es6 1.11MB 11.82kB (1.07%) ⬆️
recharts/bundle-umd 544.49kB 3.36kB (0.62%) ⬆️

Affected Assets, Files, and Routes:

view changes for bundle: recharts/bundle-es6

Assets Changed:

Asset Name Size Change Total Size Change (%)
util/createCartesianCharts.js (New) 6.3kB 6.3kB 100.0% 🚀
util/createPolarCharts.js (New) 5.34kB 5.34kB 100.0% 🚀
index.js 173 bytes 3.87kB 4.68%
view changes for bundle: recharts/bundle-cjs

Assets Changed:

Asset Name Size Change Total Size Change (%)
index.js 774 bytes 14.83kB 5.51% ⚠️
util/createCartesianCharts.js (New) 7.04kB 7.04kB 100.0% 🚀
util/createPolarCharts.js (New) 6.11kB 6.11kB 100.0% 🚀
view changes for bundle: recharts/bundle-umd

Assets Changed:

Asset Name Size Change Total Size Change (%)
Recharts.js 3.36kB 544.49kB 0.62%

@PavelVanecek
Copy link
Collaborator Author

Okay I think this is the last PR we need to merge before 3.8 @ckifer . I'll hold the other PRs, this release is already going to be a big enough one as is.

@ckifer ckifer merged commit 473d55c into main Mar 3, 2026
46 of 49 checks passed
@ckifer ckifer deleted the createtypedchart branch March 3, 2026 17:33
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.

Add type helper function

2 participants