Skip to content

fix(charts): Respect legend position in composition API#47478

Open
adamwoodnz wants to merge 3 commits intotrunkfrom
charts-91-composition-legend-should-support-alignment-options
Open

fix(charts): Respect legend position in composition API#47478
adamwoodnz wants to merge 3 commits intotrunkfrom
charts-91-composition-legend-should-support-alignment-options

Conversation

@adamwoodnz
Copy link
Contributor

@adamwoodnz adamwoodnz commented Mar 6, 2026

Fixes CHARTS-91: Composition Legend should support alignment options

Summary

Composition legends (<Chart.Legend position="top" />) always appeared at the bottom because they were rendered in the children slot. This PR extends useChartChildren to extract Legend children, read their position prop, and render them in the correct top/bottom layout slot across all legend-supporting charts.

Proposed changes:

  • Extend useChartChildren to detect and extract Legend children, reading position from props (default 'bottom')
  • Return legendChildren array with { element, position } for each Legend; exclude Legend from otherChildren
  • Update LineChart and BarChart to adopt useChartChildren and render legendChildren in position-based slots
  • Update PieChart, PieSemiCircleChart, and LeaderboardChart to render legendChildren in top/bottom slots based on position
  • Add tests for Legend extraction and position handling in use-chart-children.test.tsx
  • Add second series to WithCompositionLegend story using sampleData.slice(0, 2)

Other information:

  • Have you written new tests for your changes, if applicable?
  • Have you checked the E2E test CI results, and verified that your changes do not break them?
  • Have you tested your changes on WordPress.com, if applicable (if so, you'll see a generated comment below with a script to run)?

Does this pull request change what data or activity we track or use?

No.

Testing instructions:

  1. Run pnpm test in projects/js-packages/charts to verify all tests pass
  2. Start Storybook: pnpm run storybook from the charts package (or jp build plugins/jetpack and use the monorepo Storybook)
  3. Navigate to JS Packages > Charts Library > Charts > Line Chart
  4. Select the With Composition Legend story
  5. In the Controls panel, set legendPosition to top — the legend should move above the chart
  6. Set legendPosition to bottom — the legend should appear below the chart
  7. Verify legendAlignment (start/center/end) and legendOrientation (horizontal/vertical) still work as before
  8. Repeat with PieChart, BarChart, PieSemiCircleChart, and LeaderboardChart composition legend stories to confirm position works across all charts

Changelog

  • Generate changelog entries for this PR (using AI).

Made with Cursor

Composition legends (<Chart.Legend position="top" />) always appeared
at the bottom because they were rendered in the children slot, which
comes after the chart in the Stack layout. Alignment and orientation
worked since they affect Legend styling; position controls layout
placement and was ignored.

Extend useChartChildren to extract Legend children, read their position
prop, and return legendChildren. Charts now render legendChildren in
the top or bottom slot based on position, so composition legends honor
position="top" and position="bottom" across LineChart, BarChart,
PieChart, PieSemiCircleChart, and LeaderboardChart.

Fixes CHARTS-91.

Made-with: Cursor
@adamwoodnz adamwoodnz added Bug When a feature is broken and / or not performing as intended [Status] Needs Review This PR is ready for review. labels Mar 6, 2026
Copilot AI review requested due to automatic review settings March 6, 2026 03:48
@adamwoodnz adamwoodnz added the Enhancement Changes to an existing feature — removing, adding, or changing parts of it label Mar 6, 2026
@adamwoodnz adamwoodnz self-assigned this Mar 6, 2026
@github-actions
Copy link
Contributor

github-actions bot commented Mar 6, 2026

Are you an Automattician? Please test your changes on all WordPress.com environments to help mitigate accidental explosions.

  • To test on WoA, go to the Plugins menu on a WoA dev site. Click on the "Upload" button and follow the upgrade flow to be able to upload, install, and activate the Jetpack Beta plugin. Once the plugin is active, go to Jetpack > Jetpack Beta, select your plugin (Jetpack), and enable the charts-91-composition-legend-should-support-alignment-options branch.
  • To test on Simple, run the following command on your sandbox:
bin/jetpack-downloader test jetpack charts-91-composition-legend-should-support-alignment-options

Interested in more tips and information?

  • In your local development environment, use the jetpack rsync command to sync your changes to a WoA dev blog.
  • Read more about our development workflow here: PCYsg-eg0-p2
  • Figure out when your changes will be shipped to customers here: PCYsg-eg5-p2

@github-actions
Copy link
Contributor

github-actions bot commented Mar 6, 2026

Thank you for your PR!

When contributing to Jetpack, we have a few suggestions that can help us test and review your patch:

  • ✅ Include a description of your PR changes.
  • 🔴 Add a "[Status]" label (In Progress, Needs Review, ...).
  • ✅ Add testing instructions.
  • ✅ Specify whether this PR includes any changes to data or privacy.
  • 🔴 Add changelog entries to affected projects

This comment will be updated as you work on your PR and make changes. If you think that some of those checks are not needed for your PR, please explain why you think so. Thanks for cooperation 🤖


🔴 Action required: Please add missing changelog entries for the following projects: projects/js-packages/charts

Use the Jetpack CLI tool to generate changelog entries by running the following command: jetpack changelog add.
Guidelines: /docs/writing-a-good-changelog-entry.md


Follow this PR Review Process:

  1. Ensure all required checks appearing at the bottom of this PR are passing.
  2. Make sure to test your changes on all platforms that it applies to. You're responsible for the quality of the code you ship.
  3. You can use GitHub's Reviewers functionality to request a review.
  4. When it's reviewed and merged, you will be pinged in Slack to deploy the changes to WordPress.com simple once the build is done.

If you have questions about anything, reach out in #jetpack-developers for guidance!

Copy link
Contributor

Copilot AI left a comment

Choose a reason for hiding this comment

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

Pull request overview

This PR fixes the charts composition API so <Chart.Legend position="top" /> and position="bottom" are rendered in the correct layout slot (instead of always appearing at the bottom as a normal child), across all legend-supporting charts.

Changes:

  • Extend useChartChildren to extract Legend children (with position, defaulting to bottom) into a dedicated legendChildren bucket.
  • Update BarChart, LineChart, PieChart, PieSemiCircleChart, and LeaderboardChart to render extracted legends in top/bottom slots and to exclude legends from otherChildren.
  • Add/extend tests for legend extraction and update a LineChart Storybook story related to composition legends.

Reviewed changes

Copilot reviewed 10 out of 10 changed files in this pull request and generated 8 comments.

Show a summary per file
File Description
projects/js-packages/charts/src/charts/private/chart-composition/use-chart-children.ts Adds legendChildren extraction (element + position) alongside existing SVG/HTML/other categorization.
projects/js-packages/charts/src/charts/private/chart-composition/test/use-chart-children.test.tsx Adds coverage for Legend extraction and position handling.
projects/js-packages/charts/src/charts/private/chart-composition/index.ts Re-exports LegendChild type.
projects/js-packages/charts/src/charts/pie-chart/pie-chart.tsx Renders composition legends in top/bottom slots using legendChildren.
projects/js-packages/charts/src/charts/pie-semi-circle-chart/pie-semi-circle-chart.tsx Renders composition legends in top/bottom slots using legendChildren.
projects/js-packages/charts/src/charts/line-chart/line-chart.tsx Switches legend-child detection to useChartChildren; renders composition legends in top/bottom slots; renders otherChildren only.
projects/js-packages/charts/src/charts/bar-chart/bar-chart.tsx Switches legend-child detection to useChartChildren; renders composition legends in top/bottom slots; renders otherChildren only.
projects/js-packages/charts/src/charts/leaderboard-chart/leaderboard-chart.tsx Renders composition legends in top/bottom slots (including empty-state path) using legendChildren.
projects/js-packages/charts/src/charts/line-chart/stories/index.stories.tsx Adjusts the WithCompositionLegend story render approach.
projects/js-packages/charts/CHANGELOG.md Adds an “Unreleased” entry describing the fix.

💡 Add Copilot custom instructions for smarter, more guided reviews. Learn how to get started.

if ( isValidElement( child ) ) {
// Extract Legend children for position-based slot rendering
if ( child.type === Legend ) {
const position = ( child.props?.position ?? 'bottom' ) as 'top' | 'bottom';
Copy link

Copilot AI Mar 6, 2026

Choose a reason for hiding this comment

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

position is being coerced with a type cast. If a consumer passes an unexpected value at runtime (e.g. via JS, or a future extension like 'left'/'right'), it will be stored as 'top'|'bottom' but won’t match either filter later, so the legend silently disappears. Consider validating child.props.position against 'top'/'bottom' and defaulting to 'bottom' (or falling back to the chart’s legendPosition) when invalid.

Suggested change
const position = ( child.props?.position ?? 'bottom' ) as 'top' | 'bottom';
const rawPosition = child.props?.position;
const position: 'top' | 'bottom' =
rawPosition === 'top' || rawPosition === 'bottom' ? rawPosition : 'bottom';

Copilot uses AI. Check for mistakes.
Comment on lines +358 to +360
.map( ( l, i ) => (
<Fragment key={ `legend-top-${ i }` }>{ l.element }</Fragment>
) ) }
Copy link

Copilot AI Mar 6, 2026

Choose a reason for hiding this comment

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

These legends are rendered via .map((l, i) => ...) with an index-based key. If legend children are conditionally added/removed or reordered, this can cause unnecessary remounts and state loss. Prefer using the existing l.element.key when available (or a stable derived key), and consider returning l.element directly so React can use the element’s own key.

Suggested change
.map( ( l, i ) => (
<Fragment key={ `legend-top-${ i }` }>{ l.element }</Fragment>
) ) }
.map( l => l.element ) }

Copilot uses AI. Check for mistakes.
Comment on lines +390 to +394
{ legendChildren
.filter( l => l.position === 'top' )
.map( ( l, i ) => (
<Fragment key={ `legend-top-${ i }` }>{ l.element }</Fragment>
) ) }
Copy link

Copilot AI Mar 6, 2026

Choose a reason for hiding this comment

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

These legends are rendered via .map((l, i) => ...) with an index-based key. If legend children are conditionally added/removed or reordered, this can cause unnecessary remounts and state loss. Prefer using the existing l.element.key when available (or a stable derived key), and consider returning l.element directly so React can use the element’s own key.

Copilot uses AI. Check for mistakes.
Comment on lines +504 to +508
{ legendChildren
.filter( l => l.position === 'top' )
.map( ( l, i ) => (
<Fragment key={ `legend-top-${ i }` }>{ l.element }</Fragment>
) ) }
Copy link

Copilot AI Mar 6, 2026

Choose a reason for hiding this comment

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

These legends are rendered via .map((l, i) => ...) with an index-based key. If legend children are conditionally added/removed or reordered, this can cause unnecessary remounts and state loss. Prefer using the existing l.element.key when available (or a stable derived key), and consider returning l.element directly so React can use the element’s own key.

Copilot uses AI. Check for mistakes.
Comment on lines +372 to +376
{ legendChildren
.filter( l => l.position === 'top' )
.map( ( l, i ) => (
<Fragment key={ `legend-top-${ i }` }>{ l.element }</Fragment>
) ) }
Copy link

Copilot AI Mar 6, 2026

Choose a reason for hiding this comment

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

These legends are rendered via .map((l, i) => ...) with an index-based key. If legend children are conditionally added/removed or reordered, this can cause unnecessary remounts and state loss. Prefer using the existing l.element.key when available (or a stable derived key), and consider returning l.element directly so React can use the element’s own key.

Copilot uses AI. Check for mistakes.
Comment on lines +279 to +283
{ legendChildren
.filter( l => l.position === 'top' )
.map( ( l, i ) => (
<Fragment key={ `legend-top-${ i }` }>{ l.element }</Fragment>
) ) }
Copy link

Copilot AI Mar 6, 2026

Choose a reason for hiding this comment

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

These legends are rendered via .map((l, i) => ...) with an index-based key. If legend children are conditionally added/removed or reordered, this can cause unnecessary remounts and state loss. Prefer using the existing l.element.key when available (or a stable derived key), and consider returning l.element directly so React can use the element’s own key.

Copilot uses AI. Check for mistakes.
@jp-launch-control
Copy link

jp-launch-control bot commented Mar 6, 2026

Code Coverage Summary

Coverage changed in 7 files. Only the first 5 are listed here.

File Coverage Δ% Δ Uncovered
projects/js-packages/charts/src/charts/leaderboard-chart/leaderboard-chart.tsx 52/59 (88.14%) -7.94% 5 💔
projects/js-packages/charts/src/hooks/use-has-legend-child.ts 0/6 (0.00%) -83.33% 5 💔
projects/js-packages/charts/src/charts/bar-chart/bar-chart.tsx 87/97 (89.69%) -3.79% 4 💔
projects/js-packages/charts/src/charts/line-chart/line-chart.tsx 142/151 (94.04%) -2.54% 4 💔
projects/js-packages/charts/src/charts/pie-chart/pie-chart.tsx 82/89 (92.13%) -4.34% 4 💔

Full summary · PHP report · JS report

If appropriate, add one of these labels to override the failing coverage check: Covered by non-unit tests Use to ignore the Code coverage requirement check when E2Es or other non-unit tests cover the code Coverage tests to be added later Use to ignore the Code coverage requirement check when tests will be added in a follow-up PR I don't care about code coverage for this PR Use this label to ignore the check for insufficient code coveage.

Co-authored-by: Copilot <175728472+Copilot@users.noreply.github.com>
Copilot AI review requested due to automatic review settings March 6, 2026 04:19
Copy link
Contributor

Copilot AI left a comment

Choose a reason for hiding this comment

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

Pull request overview

Copilot reviewed 10 out of 10 changed files in this pull request and generated no new comments.

Comments suppressed due to low confidence (1)

projects/js-packages/charts/src/charts/line-chart/stories/index.stories.tsx:184

  • PR description mentions updating this story to use sampleData.slice(0, 2) (2 series), but the new implementation spreads Default.args, which currently sets data: sampleData.slice(0, 4). If the intent is specifically to demonstrate 2-series composition legends, consider explicitly setting data (or seriesCount) here to match the PR description/testing notes.
		<LineChart { ...Default.args } { ...args }>
			<LineChart.Legend
				orientation={ args.legendOrientation || 'horizontal' }
				alignment={ args.legendAlignment || 'center' }
				position={ args.legendPosition || 'bottom' }

💡 Add Copilot custom instructions for smarter, more guided reviews. Learn how to get started.

Manual edits to the changelog are not the way.

Made-with: Cursor
@github-actions github-actions bot added [Status] Needs Author Reply We need more details from you. This label will be auto-added until the PR meets all requirements. and removed [Status] Needs Review This PR is ready for review. labels Mar 6, 2026
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

Bug When a feature is broken and / or not performing as intended Enhancement Changes to an existing feature — removing, adding, or changing parts of it [JS Package] Charts RNA [Status] Needs Author Reply We need more details from you. This label will be auto-added until the PR meets all requirements. [Tests] Includes Tests

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants