feat(polar): add radialLabels for crowded pie labels #231
main fromrefs/pull/231/head·opened Refs #227 - outside labels of small adjacent pie slices overlap, and there is no built-in way to spread or hide them.
- New
radialLabelsmark in@tanstack/charts/polar: outside labels with elbow connectors, one text column per side - Overlapping labels move apart as little as possible and stay inside the chart; no connector crosses another label
- Labels that do not fit the height or width hide by
priority(default: datumvalue);maxShiftalso hides labels that move too far
Screenshot:
How to review: start at polar-label-layout-internal.ts (pure layout), then radialLabels in polar.ts; the rest is tests and docs
How to test: pnpm vitest run packages/charts-core/src/polar-label-layout-internal.test.ts packages/charts-core/src/polar-radial-labels.test.ts
More screenshots
maxShift: 24 hides labels that would move too far from their slice:
Review fixture, before and after the text column (red = connector crosses a label):
Requested cases
| Case | Behavior |
|---|---|
| Narrow chart, long labels | Labels that would cross the chart edge hide, lower priority first; widths use the built-in text estimate |
| Resize | Layout runs on every render; a wider chart shows labels a narrow one hid, with the same keys |
| Equal priority | The later row hides first; for the width check, the outermost-connector label hides first because it sets the column |
maxShift | The hidden label loses its text, connector, and interaction point |
| Stable keys | Label keys come from key; connector keys add :connector |
| Motion | With motion(), labels and connectors move to the new layout; hidden labels fade out |
| Renderers | Only label and polyline nodes; tested in SVG, Canvas, and React Native |
| Bundle | polar.ts only re-exports the mark, so polar charts without radialLabels keep the same bundle as main (at most 2 gzip bytes of minifier naming noise) |
| Many labels | 5,000 labels on one side lay out in about 1 ms |
Separate mark or radialText option
- Separate mark (this PR): one mark owns text, connectors, and hiding; the layout code is tree-shaken when unused.
radialTextoption: fewer exports, butradialTextwould need connector options, and hiding a label breaks its rule that every valid row renders.
Local checks
Type check, docs check, and new and changed tests pass. bundle:check fails the same way on clean main; package:check fails on a local Node version mismatch (24.7.0 vs .nvmrc 24.18.0).
- 1
Important
Draft PR not reviewed#
Draft PRs are not automatically reviewed by default.
- Trigger a manual review
To automatically review draft PRs, update your CodeRabbit configuration:
reviews: auto_review: drafts: true- Autofix · Keep fixing CodeRabbit findings and required CI, and resolving merge conflicts
Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out.
Comment `@coderabbitai help` to get the list of available commands.Thanks @hshoja, the requested cases are useful. I independently checked the layout helper at
9da9d8e3in Chromium, Firefox and WebKit: 604 combinations per browser covered spacing, vertical bounds and finite positions, including empty inputs and severalmaxShiftvalues. This was an isolated helper check, not the full PR test suite or a rendered visual review.One performance improvement before this is ready: the capacity loop calls
withoutLowestonce per removed label, scanning and copying the remaining array each time. That is quadratic when many labels cannot fit. In a synthetic 5,000-label, one-side case with room for 25 labels, seven-run medians were about 35 ms in Chromium, 92 ms in Firefox and 52 ms in WebKit. This is a stress case, not a claim about typical small pies.A private prototype selected the highest-priority
capacityrows once, breaking ties by earlier input index, then filtered the original angular ordering through that selection. It produced identical placements across those 604 combinations and the 100/1,000/5,000-row cases in each browser. The 5,000-row Chromium median was about 0.2 ms; the other engines rounded below their timer resolution. Could you apply that capacity-selection approach and retain tests for equal-priority ties and angular order? The separatemaxShiftloop still needs its own behavior preserved.I have not settled the separate-mark API choice yet, and the reported bundle costs and full validation still need independent verification.
One more case from a rendered check of
9da9d8e3: please test connectors against neighboring text bounds, not only label-to-label spacing.My fixture uses 20 rows in input order,
Slice 0has value 50 and the other rows have value 1. Labels areSlice ${index}, except row 1 has a long name. The chart has zero margins,radiusRatio: 0.5, linear angle domain[0, 2 * Math.PI], radius domain[0, 1], and default label styling. At 640 × 320, Firefox reports connectors for rows 3 through 6 intersecting the bounding box ofSlice 7, even with the box inset by 1 px. At 220 × 320, row 17's connector intersectsSlice 18's box. Chromium and WebKit do not report those intersections for this fixture. This is a text-box intersection check, not a claim that every crossed pixel contains glyph ink.All three engines kept labels inside the chart, with no label-to-label overlaps, at 640 × 320, 220 × 320 and 640 × 100. Visible label counts matched interaction-point counts. The connector routes still need a clear corridor beside the text when labels are spread vertically.
I also measured the existing 114 consumer entries independently: 108 are byte-identical, six polar entries change by +0.026 kB minified, at most +0.009 kB gzip and +0.068 kB Brotli. No budget changes are approved by this review.
Thanks for both reviews. Both points are fixed.
1. Faster selection when labels do not fit (8c41042b)#
Before, the code removed the weakest label one at a time and scanned the whole list each time. Now it sorts by priority once, keeps the top labels that fit, and keeps them in slice order. Ties still keep the earlier row, and the
maxShiftstep is unchanged.Example: 5,000 labels on one side with room for 25 took 152.5 ms, and now take about 1 ms.
New tests check that the result is the same as the old one-at-a-time removal (50 inputs), that slice order is kept, and the 5,000-label case.
2. Connectors no longer cross other labels (7d57e934)#
Before, labels followed a curve, so a slanted connector could pass through a neighbor's text. Now all labels on one side start at the same x, just outside the outermost connector. Every connector ends before the text starts, so it cannot cross another label.
If the text does not fit the chart width, the mark hides either the label with the outermost connector or the widest label, whichever has the lower priority. On a tie it hides the outermost one, because that label pushes the column out.
Your fixture, with text boxes grown by 2 px (red = connector crosses a label):
Size Before After 640 × 320 20 labels, 5 crossings 20 labels, 0 crossings 220 × 320 4 labels, 1 crossing 10 labels, 0 crossings 640 × 100 6 labels, 0 crossings 6 labels, 0 crossings Your fixture is now a test. It checks every connector against every other label at all three sizes. On the old code it fails with
Slice 3 crosses Slice 7 at 640x320.Ideas for later#
Not in this PR, until the API is decided:
- wrap long labels instead of hiding them, for example
maxLines: 3with an ellipsis; - let
polarshrink the pie to make room for outside labels.
- wrap long labels instead of hiding them, for example
Thanks @hshoja, I rechecked the rendered fixture at
3797bfbcin Chromium, Firefox and WebKit, with DOM text measurement, at 640 × 320, 220 × 320 and 640 × 100. All three engines have zero connector-to-neighbor text-box crossings and zero label overlaps. Visible labels and interaction points match at 20, 10 and 6.Firefox reports a slightly wider SVG text bounding box than the text advance. I compared screenshots with SVG overflow visible versus clipped, and there were zero changed pixels in all three engines for these fixtures. I do not see painted clipping here.
The revised layout helper also passed 1,812 bounds, spacing and connector-column cases per engine, plus the 5,000-label case with capacity 25. That helper was checked at
6ac6a145and is unchanged in3797bfbc. This is targeted verification, not the full PR suite or motion validation.At the current head, 108 of the 114 existing consumer bundles remain byte-identical. The six changed polar bundles add 0.026 kB minified, at most 0.009 kB gzip and 0.073 kB Brotli. These measurements compare the reviewed source overlay against the current checkout, not a newly approved budget baseline.
The two specific review concerns, repeated capacity scans and connector crossings in this fixture, are addressed. The separate-mark API choice, bundle acceptance and full CI remain open, so this is not merge approval.
Thanks @hshoja, I extended verification at
3797bfbcbc40db52f91c20f53abec58f5fef00e2to an isolated checkout. The DOM run passed 2,262 tests initially; its four Git-fixture failures were caused by blocked access to my global Git configuration, and all four passed when global configuration was explicitly disabled. All six additional framework test targets, TypeScript and the documentation contract pass too.The checked-in bundle gate still fails three gzip ceilings: Polar arc, Polar gauge composition and Radial labels. I have not changed or approved those ceilings. The separate-mark API decision and packed-package verification also remain open, so this is additional test evidence, not merge approval.
Thanks @hshoja, actual packed-package verification now passes at this same head, including bare React Native, Expo, the seven adapters and the unified artifact. The packed radial-label types pass four valid forms and reject four invalid option types; removing the export makes the negative control fail.
The packed full-motion renderer also passes interpolation, reduced motion, interruption and cleanup in Chromium, Firefox and WebKit. Its 118-module packed Charts input closure is unchanged in the final unified artifact. This exact head predates motionLite, so these packed results cover full motion only. The three existing gzip failures, API discussion, draft status and required CI still need resolution.
Verified head:
3797bfbcbc40db52f91c20f53abec58f5fef00e2.Thanks for the extra checks. The branch is now rebased on
main(withmotionLite), and the three gzip ceilings should pass without changing them.What caused it: the polar container passed
measureTextto every polar mark. That added about 9 gzip bytes to every polar chart, even charts without labels.What changed (dfddb479):
radialLabelsmoved to its own module,polar-labels.ts.polar.tsnow only re-exports it.- The polar container is the same as on
main. - The mark uses the built-in text estimate, the same one static SVG uses. In Chrome it is usually a little wider than real text, for example
Chrome 64.2%is 82.7 px estimated vs 80 px real, so labels stay inside the chart.
Gzip bytes vs
main(same esbuild settings asmeasure-bundles.mjs):Entry Before Now Polar arc +6 0 (identical file) Polar gauge +18 0 Radial labels +12 +2 Polar pie +9 0 Radial bars +3 +1 Polar line + scatter -11 0 (identical file) The remaining +1 and +2 bytes are minifier name choices: the JS has the same length as
main. With my local Node,measure-bundles.mjs --checkreports the same polar sizes asmain.Your fixture still has zero connector-to-label crossings at all three sizes, with 20, 10 and 6 labels.
Trade-off: unusual fonts or a large React Native font scale can make the estimate a few pixels off. If you prefer real measurement, it is a one-line change in the polar container, at about 9 gzip bytes per polar chart.
Thanks @hshoja, I checked dfddb479 against current main. The split removes the earlier arc and gauge budget failures. One remains on Node 24.18.0: Radial labels + static SVG is 24.315 decimal kB gzip against the unchanged 24.313 kB ceiling, a 2-byte difference. I have not changed the ceiling.
Independent checks pass: 2,280 tests, typecheck, docs, packed React Native/Expo consumers, all seven framework adapters, and the final unified package. Full motion and motionLite pass interpolation, reduced-motion, resize, interruption and teardown checks through the final packed exports in Chromium, Firefox and WebKit. These checks are on the new head, not carried over from the old package.
The estimate tradeoff is real even with ordinary fonts. In a 400 x 320 static SVG, radiusRatio 0.5, a right-side label at angle PI/2, 12px Arial, WWWWWWWW extends about 2.61px beyond the right edge in Chromium/WebKit. A 12px monospace Long category extends about 5.63px. The fixture sets the rendered font explicitly and uses a one-to-one viewport. Firefox also shows overflow. This is a bounded font test, not a claim about every layout. The docs should describe estimated, rather than guaranteed, edge containment and not limit the caveat to unusual fonts.
The PR is still a draft, and required CI has not run. Keeping the text-measurement/API choice separate from the remaining 2-byte budget decision.
Thanks. Docs are updated in the latest commit: edge containment is now described as estimated, not guaranteed, for all fonts. Example: "rendered text, including common fonts, can extend a few pixels past the chart edge. Leave chart margin when that matters."
For the remaining 2 bytes and the text measurement, which do you prefer?
- Raise the Radial labels ceiling by 2 bytes. The 2 bytes are minifier name choices; the JS has the same length as
main. - Exactly 0 bytes.
polar.tsonly gets theradialLabelsre-export. The cost is a second copy of three internal option types, and noRadialLabelsOptionstype export from@tanstack/charts/polar. - Real text measurement. Pass
measureTextfrom the polar container. This fixes the edge overflow you measured (for exampleWWWWWWWWin 12px Arial), at about +9 gzip bytes on each polar entry.
I'll keep the PR as a draft until you choose.
- Raise the Radial labels ceiling by 2 bytes. The 2 bytes are minifier name choices; the JS has the same length as
Sign in to join this conversation.
🦋 Changeset detected#
Latest commit: 42b055dae0d54fdca3e0ca33bf399961322645d0
The changes in this PR will be included in the next version bump.
This PR includes changesets to release 12 packages
Not sure what this means? Click here to learn what changesets are.
Click here if you're a maintainer who wants to add another changeset to this PR