Skip to content

Conversation

@chriskmnds
Copy link
Contributor

@chriskmnds chriskmnds commented Nov 7, 2025

Fixes https://linear.app/a8c/issue/M4R73CH-1201/v2-hd-charts-on-monitoring-page-touch-the-card-border.

Proposed changes:

  • Make the X-axis margin minimal and dynamic, computing it as fontSize + tickLength based on the theme's axisStyles.x.* / svgLabelSmall, with documented defaults when not present.
  • For a bottom X-axis, use bottom = max(DEFAULT_MARGIN_BOTTOM, fontSize + tickLength); for a top X-axis, use top = max(DEFAULT_MARGIN_TOP, fontSize + tickLength) and a small fixed bottom = DEFAULT_BOTTOM_FOR_TOP_AXIS (10px).
  • Keep the existing Y-axis behavior (using getLongestTickWidth) but introduce documented constants (DEFAULT_Y_TICK_WIDTH, DEFAULT_MARGIN_*) instead of magic numbers.
  • Extract X-axis font/tick logic into helpers (resolveFontSize, getXAxisLabelMetrics) to simplify useChartMargin and align the structure with the Y-axis logic.

Other information:

  • Have you written new tests for your changes, if applicable? (Updated use-chart-margin tests to cover bottom/top X-axis cases.)
  • Have you checked the E2E test CI results, and verified that your changes do not break them? (Charts package tests pass; no E2E impact expected.)
  • Have you tested your changes on WordPress.com, if applicable (if so, you'll see a generated comment below with a script to run)?

Jetpack product discussion

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

No.

Testing instructions:

  • In the charts package:
    • Run pnpm -C projects/js-packages/charts test and verify tests pass.
    • Run pnpm -C projects/js-packages/charts storybook and open Storybook.
      • Inspect LineChart stories with the default theme and confirm X-axis tick labels do not touch the container edge.
      • Increase the axis label font size (or use a theme with larger tick labels) and confirm the bottom/top margin grows just enough to fit labels without adding excessive padding.
      • Set axis.x.orientation = 'top' in a LineChart story and verify the top margin increases appropriately while the bottom margin is a small 10px buffer.

@github-actions
Copy link
Contributor

github-actions bot commented Nov 7, 2025

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 update/fix-chart-x-axis-margins branch.
  • To test on Simple, run the following command on your sandbox:
bin/jetpack-downloader test jetpack update/fix-chart-x-axis-margins

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 Nov 7, 2025

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 a "[Type]" label (Bug, Enhancement, Janitorial, Task).
  • ✅ 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 🤖


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!

@github-actions github-actions bot added the [Status] Needs Author Reply We need more details from you. This label will be auto-added until the PR meets all requirements. label Nov 7, 2025
@jp-launch-control
Copy link

jp-launch-control bot commented Nov 7, 2025

Code Coverage Summary

Coverage changed in 1 file.

File Coverage Δ% Δ Uncovered
projects/js-packages/charts/src/hooks/use-chart-margin.tsx 45/47 (95.74%) -4.26% 2 ❤️‍🩹

Full summary · PHP report · JS report

expect( result.current.top ).toBe( 20 );
// 12px font → ~15px line-height + 8 tick length + 8 padding = 31
expect( result.current.top ).toBe( 31 );
expect( result.current.bottom ).toBe( 10 );
Copy link
Contributor

Choose a reason for hiding this comment

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

FAIL src/hooks/test/use-chart-margin.test.tsx
● useChartMargin › sets top and bottom margin for top x axis

expect(received).toBe(expected) // Object.is equality

Expected: 10
Received: 20

  105 |             // 12px font → ~15px line-height + 8 tick length + 8 padding = 31
  106 |             expect( result.current.top ).toBe( 31 );
> 107 |             expect( result.current.bottom ).toBe( 10 );
      |                                             ^
  108 |     } );
  109 |
  110 |     it( 'returns default margin if no axis options', () => {

  at Object.toBe (src/hooks/test/use-chart-margin.test.tsx:107:35)

Copy link
Contributor

Choose a reason for hiding this comment

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

Feel like bottom should be 20 here, but I'll leave it to @chihsuan for a second opinion.

Copy link
Member

Choose a reason for hiding this comment

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

I think we should set it to 10, since having the orientation as top eliminates the need for a large bottom margin.

IMO, this line is unnecessary.

Copy link
Contributor Author

Choose a reason for hiding this comment

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

Thanks for flagging this. The X‑axis margin logic has been updated so that for a top x‑axis the bottom margin is always DEFAULT_BOTTOM_FOR_TOP_AXIS = 10, independent of the dynamic computation; the test now asserts top === 20 (12px font + 8px tick) and bottom === 10, and it passes with the new implementation.

Copy link
Member

@chihsuan chihsuan left a comment

Choose a reason for hiding this comment

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

Thanks for the PR! @chriskmnds I like the idea of respecting theming and different font sizes. 🙂

However, I think we should think more carefully about whether we want to add extra padding.

Before this PR, what we had was:

Image

Now we have:

Image

It does make sense to add padding between each chart and its container (card). However, IMO, it's better to let consumers decide how much padding they want between the chart and its container.

Additionally, this change might cause issues with Woo Analytics widgets, since we don't currently define explicit margins for the charts.

Image

In other words, I think we should adjust the x-axis margin dynamically, but keep it just sufficient to prevent the chart from overlapping its container. If additional space is needed, consumers can add padding to the container as desired. Does that make sense?

const xTickLength =
// Prefer axis-specific tick length when present, else theme fallback
xAxisStyles?.tickLength ?? themeWithX.tickLength ?? 8;
const xPadding = 8;
Copy link
Member

Choose a reason for hiding this comment

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

Would it be possible to move the hardcoded values (such as padding, line height, and default settings) into named constants, and add comments that clarify their purposes? This would improve readability and maintainability.

Copy link
Contributor Author

Choose a reason for hiding this comment

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

Done. All previously hardcoded values have been moved into documented constants at the top, with brief comments describing what each controls. The hook body now refers to these constants rather than inline numbers.

return isNaN( parsed ) ? undefined : parsed;
}
return undefined;
};
Copy link
Member

Choose a reason for hiding this comment

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

Can we move this function out of useChartMargin? The hook is getting a bit too complex. It would be nice to split it up into smaller functions. An idea would be to extract all font size calculation logic into a separate function, similar to how we handle the Y axis.

Copy link
Contributor Author

Choose a reason for hiding this comment

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

Agreed, that block was getting heavy. I’ve extracted the X‑axis font/tick logic into resolveFontSize( ... ) and getXAxisLabelMetrics( theme, orientation ), so useChartMargin now just calls the helper and then combines the metrics into margins. This mirrors the way Y‑axis width is delegated to getLongestTickWidth and keeps the hook itself much simpler.

if ( xOrientation === 'top' ) {
// Preserve a small bottom margin for layout breathing room
defaultMargin.top = Math.max( defaultMargin.top, computedXMargin );
defaultMargin.bottom = Math.max( defaultMargin.bottom, 10 );
Copy link
Member

Choose a reason for hiding this comment

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

This is consistently assigned the value of defaultMargin.bottom because defaultMargin.bottom is 20. I think we should set the defaultMargin.bottom to 10.

Copy link
Contributor Author

Choose a reason for hiding this comment

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

You’re right. Math.max( defaultMargin.bottom, 10 ) was effectively always 20. I’ve introduced DEFAULT_BOTTOM_FOR_TOP_AXIS = 10 and, in the top‑axis case, we now assign defaultMargin.bottom = DEFAULT_BOTTOM_FOR_TOP_AXIS directly. The bottom margin for a top X‑axis is now 10px instead of 20px.

@chriskmnds
Copy link
Contributor Author

chriskmnds commented Nov 10, 2025

Thanks for reviewing! @kangzj @chihsuan

It does make sense to add padding between each chart and its container (card). However, IMO, it's better to let consumers decide how much padding they want between the chart and its container.

There is a point to that, how a "raw" chart component would have zero paddings/margins. I am just proposing this as something done similarly for y-axis. Happy to abandon direction - in fact, I'd love it if one of you would take over if you'd like to entertain this further (being as it is that a shole team is in charge of the charts). I created a PR as I feared just an issue might sit longer in backlog.

Let me know what your final take is - push forward, abandon, or leave it to your hands? :-)

@kangzj
Copy link
Contributor

kangzj commented Nov 17, 2025

I tracked it with CHARTS-134: Optimize bottom/top margin to fit tick labels. I'll take a look this week. Thanks!

@kangzj kangzj removed their assignment Nov 17, 2025
@chriskmnds chriskmnds force-pushed the update/fix-chart-x-axis-margins branch from 9432b9d to bc041d8 Compare November 17, 2025 12:41
@chriskmnds
Copy link
Contributor Author

chriskmnds commented Nov 17, 2025

Thanks again for the review and for raising the concerns about extra padding and theme consistency. The useChartMargin is updated so the X‑axis margin is now the minimum needed to fit tick labels (fontSize + tickLength), using the existing visx axisStyles.x / svgLabelSmall information, and documented defaults added to the top. The Y‑axis defaults are aligned to use the same pattern. This keeps default layouts effectively unchanged, avoids adding new visual padding at the library level, and still scales correctly for different themes and font sizes. Any additional spacing around the chart is left to consumers via their own container padding/margins.

Please review. Next, will run some tests and update the test cases to cover.

@chriskmnds chriskmnds changed the title Charts: Dynamic x‑axis margin in LineChart to prevent crowded/clipped tick labels Charts: Minimal dynamic X-axis margin in LineChart to fit tick labels Nov 17, 2025
Copy link
Contributor

@kangzj kangzj left a comment

Choose a reason for hiding this comment

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

The PR look good and tests as described 👍

Image

I don't see we allow axisStyles in our theme - the option is available for XYChartTheme only the moment, which means customized fontSize is not yet supported with our exposed API. However, if supported, we will need this.

I think we can merge the PR and then we could consider support for the ability to customize styles for axis in some ways(might not be necessary though. not 100% sure). It seems we will need our version of buildChartTheme. We should probably get rid of XYChart in the long run because we don't have full control over some functionalities otherwise.

Not sure what you think @adamwoodnz.

@kangzj kangzj force-pushed the update/fix-chart-x-axis-margins branch from 3666bcd to a700d6b Compare November 20, 2025 02:38
@adamwoodnz adamwoodnz added the [Status] Needs Review This PR is ready for review. label Nov 20, 2025
@adamwoodnz adamwoodnz added [Type] Enhancement Changes to an existing feature — removing, adding, or changing parts of it and removed [Status] Needs Author Reply We need more details from you. This label will be auto-added until the PR meets all requirements. labels Nov 20, 2025
@adamwoodnz
Copy link
Contributor

adamwoodnz commented Nov 20, 2025

Thanks again for working on this.

  • Increase the axis label font size (or use a theme with larger tick labels) and confirm the bottom/top margin grows just enough to fit labels without adding excessive padding.

I increased the axis label font size using svgLabelSmall: { fontSize: '20px' }, in the default theme and the labels have blown out so I'm not sure this is working as intended:

Screenshot 2025-11-20 at 4 04 12 PM

Axis labels aren't something we've spent much time on yet in terms of theming, so that's the only lever we have at present. As @kangzj mentioned we don't support theme axisStyles yet so maybe that needs to be added as a more robust way of controlling the label font size.

@chriskmnds
Copy link
Contributor Author

Thanks @kangzj @adamwoodnz !

I did notice something odd about axisStyles, but this is something already utilised in the code for the y-axis.

It sounds like I may need to give better focus here. Most definitely didn't test much. Thanks for testing!

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

[JS Package] Charts RNA [Status] Needs Review This PR is ready for review. [Tests] Includes Tests [Type] Enhancement Changes to an existing feature — removing, adding, or changing parts of it

Projects

None yet

Development

Successfully merging this pull request may close these issues.

5 participants