Skip to content

Commit c538e0f

Browse files
committed
wip(ui): titled x-axis ticks, no phone cut on rotated labels, no swatch for per-category bars
Co-Authored-By: Claude <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_01L9qibzKuj2HUUN2wUhZ9Go
1 parent b25b6eb commit c538e0f

4 files changed

Lines changed: 128 additions & 29 deletions

File tree

‎ui/packages/plugin-charts/src/AdvancedChartImpl.dashboardReadability-27520.test.tsx‎

Lines changed: 64 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -154,3 +154,67 @@ describe('horizontal bar category labels on a phone (row 18)', () => {
154154
expect(backlog?.querySelector('title')).toBeNull();
155155
});
156156
});
157+
158+
describe('vertical bar category labels on a phone (row 18)', () => {
159+
const asPhone = () => {
160+
(window as any).innerWidth = 390;
161+
window.dispatchEvent(new Event('resize'));
162+
};
163+
const xTicks = (c: HTMLElement) =>
164+
Array.from(c.querySelectorAll<SVGTextElement>('.recharts-xAxis-tick-labels .recharts-cartesian-axis-tick-value'));
165+
166+
it('a few buckets rotate and draw "In Progress" whole, where the phone cut drew "In Progr…"', () => {
167+
asPhone();
168+
const { container } = render(
169+
<AdvancedChartImpl
170+
chartType="bar"
171+
data={[{ s: 'Backlog', n: 2 }, { s: 'To Do', n: 2 }, { s: 'In Progress', n: 2 }, { s: 'In Review', n: 2 }, { s: 'Done', n: 2 }]}
172+
xAxisKey="s"
173+
series={[{ dataKey: 'n', label: 'Tasks' }]}
174+
isAnimationActive={false}
175+
/>,
176+
);
177+
const labels = xTicks(container).map((t) => t.textContent);
178+
expect(labels).toContain('In Progress');
179+
expect(container.textContent).not.toContain('In Progr…');
180+
});
181+
182+
it('a label still cut carries the full label as its tooltip; a whole one carries none', () => {
183+
const long = 'Waiting on the customer to confirm';
184+
const { container } = render(
185+
<AdvancedChartImpl
186+
chartType="bar"
187+
data={[{ s: long, n: 2 }, { s: 'Done', n: 3 }]}
188+
xAxisKey="s"
189+
series={[{ dataKey: 'n', label: 'Tasks' }]}
190+
isAnimationActive={false}
191+
/>,
192+
);
193+
const ticks = Array.from(container.querySelectorAll('.recharts-xAxis-tick-labels .recharts-cartesian-axis-tick-label'));
194+
const cut = ticks.find((t) => (t.textContent ?? '').includes('…'));
195+
expect(cut, 'the long label was not cut, so this measures nothing').toBeDefined();
196+
expect(cut!.querySelector('title')?.textContent).toBe(long);
197+
const whole = ticks.find((t) => t.querySelector('.recharts-cartesian-axis-tick-value')?.textContent === 'Done');
198+
expect(whole?.querySelector('title')).toBeNull();
199+
});
200+
});
201+
202+
describe('a lone bar series painted per category (row 15 control)', () => {
203+
it('draws its legend label with no swatch, since no one colour names it', async () => {
204+
const { container } = render(
205+
<AdvancedChartImpl
206+
chartType="bar"
207+
data={[{ h: 'green', n: 3 }, { h: 'red', n: 1 }]}
208+
xAxisKey="h"
209+
series={[{ dataKey: 'n', label: 'Projects' }]}
210+
config={{ n: { label: 'Projects' } }}
211+
categoryColors={{ green: '#22c55e', red: '#ef4444' }}
212+
isAnimationActive={false}
213+
/>,
214+
);
215+
await settle();
216+
expect(container.querySelector('.recharts-legend-wrapper')?.textContent).toContain('Projects');
217+
expect(swatches(container)).toHaveLength(0);
218+
});
219+
});
220+

‎ui/packages/plugin-charts/src/AdvancedChartImpl.labelFitBand-13241.test.tsx‎

Lines changed: 4 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -113,7 +113,10 @@ describe('an x-axis label rotates and is cut only when its band cannot hold it (
113113
// The cut name is still reachable whole: the pointer over its bar opens
114114
// the tooltip, which names the category in full. recharts throttles a
115115
// pointer move through `requestAnimationFrame`, so the frame is flushed.
116-
expect(container.textContent).not.toContain('Needs Analysis');
116+
// The axis draws only the cut; the full name rides in the tick's own
117+
// tooltip (objectstack#27520) and in the chart tooltip below.
118+
expect(labelsOf(ticks)).not.toContain('Needs Analysis');
119+
expect(ticks[2].closest('.recharts-cartesian-axis-tick-label')?.querySelector('title')?.textContent).toBe('Needs Analysis');
117120
const bar = container.querySelectorAll('.recharts-rectangle')[2] as SVGElement;
118121
const x = Number(bar.getAttribute('x')) + Number(bar.getAttribute('width')) / 2;
119122
const y = Number(bar.getAttribute('y')) + Number(bar.getAttribute('height')) / 2;

‎ui/packages/plugin-charts/src/AdvancedChartImpl.tsx‎

Lines changed: 56 additions & 25 deletions
Original file line numberDiff line numberDiff line change
@@ -37,6 +37,7 @@ import {
3737
ReferenceLine,
3838
ReferenceArea,
3939
Brush,
40+
Text,
4041
type SankeyLinkProps,
4142
type SankeyNode,
4243
type SankeyNodeProps,
@@ -535,6 +536,22 @@ function wrapCategoryLabel(label: string, maxWidthPx: number): { lines: string[]
535536
*/
536537
const CATEGORY_TICK_INSET_PX = RECHARTS_TICK_SIZE + 2;
537538

539+
/** An unrotated x-axis label on a phone is cut past this many characters. */
540+
const PHONE_X_LABEL_MAX_CHARS = 8;
541+
542+
/**
543+
* The x axis's category tick: recharts' own tick text, drawn from the axis's
544+
* `tickFormatter`, plus the full label (`fullLabel`) as a tooltip whenever the
545+
* formatter had to cut it, so a phone's "In Progr…" still names its bucket.
546+
*/
547+
function TitledCategoryTick(props: any) {
548+
const { fullLabel, tickFormatter, payload, index, ...rest } = props;
549+
const shown = String(tickFormatter ? tickFormatter(payload?.value, index) : (payload?.value ?? ''));
550+
const full = String(fullLabel(payload?.value) ?? '');
551+
const text = <Text {...rest} fill={AXIS_TICK_STYLE.fill}>{shown}</Text>;
552+
return shown === full ? text : <g><title>{full}</title>{text}</g>;
553+
}
554+
538555
/** The line advance of a wrapped category label, in em. */
539556
const CATEGORY_LABEL_LINE_EM = 1.1;
540557

@@ -2365,8 +2382,8 @@ function AdvancedChartImplInner({
23652382

23662383
// Format ISO date strings into compact "MMM D" / "MMM YYYY" labels for X-axis ticks.
23672384
// Falls back to the raw value when not parseable as a date. The full label:
2368-
// `formatTick` below adds the phone cut, which the horizontal-bar category
2369-
// axis does not take (it wraps instead, see `WrappedCategoryTick`).
2385+
// the x axis cuts it only where its band needs that (`xAxisTickFormatter`),
2386+
// and the horizontal-bar category axis wraps it (`WrappedCategoryTick`).
23702387
const formatCategoryLabel = React.useCallback((value: any): string => {
23712388
if (value == null || value === '') return '';
23722389
// A resolved display label for this exact category value — the same
@@ -2418,11 +2435,6 @@ function AdvancedChartImplInner({
24182435
}
24192436
return str;
24202437
}, [data, xAxisKey, config, displayLocale]);
2421-
const formatTick = React.useCallback((value: any): string => {
2422-
const str = formatCategoryLabel(value);
2423-
if (isMobile && str.length > 8) return str.slice(0, 8) + '…';
2424-
return str;
2425-
}, [formatCategoryLabel, isMobile]);
24262438

24272439
// Memoize whether any X-axis label is long enough to warrant angle rotation
24282440
const hasLongLabels = React.useMemo(
@@ -2495,8 +2507,8 @@ function AdvancedChartImplInner({
24952507
yAxisUndrawnNotes(yPlacement, yAxes, categoriesRunDown),
24962508
);
24972509
const xTickFormatter = React.useMemo(
2498-
() => formatterFor(xAxisSpec?.format, displayLocale) ?? formatTick,
2499-
[xAxisSpec?.format, displayLocale, formatTick],
2510+
() => formatterFor(xAxisSpec?.format, displayLocale) ?? formatCategoryLabel,
2511+
[xAxisSpec?.format, displayLocale, formatCategoryLabel],
25002512
);
25012513

25022514
// objectui#13241 — whether the drawn labels fit their bands unrotated, read
@@ -2525,19 +2537,33 @@ function AdvancedChartImplInner({
25252537
* is sized from the longest label drawn, so the cap is what keeps that band
25262538
* bounded. See `ROTATED_X_LABEL_MAX_CHARS`.
25272539
*
2528-
* Kept separate from `xTickFormatter` on purpose — that one also formats the
2529-
* horizontal-bar family's CATEGORY axis, which is the y axis, sizes its own
2530-
* width from the longest label, and already draws all of them.
2540+
* An unrotated label on a phone keeps the eight-character cut, unless the
2541+
* axis declares a `format`: there the rotated band is what holds a long
2542+
* label, so a phone rotates its few labels and draws "In Progress" whole
2543+
* where the cut drew "In Progr…" (objectstack#27520). Either cut leaves the
2544+
* full label in the tick's tooltip (`TitledCategoryTick`).
2545+
*
2546+
* Kept separate from `xTickFormatter` on purpose — that one is the full
2547+
* label, which the fit and rotation decisions above measure, and which the
2548+
* tooltip of a cut label carries.
25312549
*/
25322550
const xAxisTickFormatter = React.useMemo(() => {
2533-
if (!rotateXLabels) return xTickFormatter;
2534-
return (value: any): string => {
2535-
const label = String(xTickFormatter(value) ?? '');
2536-
return label.length > ROTATED_X_LABEL_MAX_CHARS
2537-
? `${label.slice(0, ROTATED_X_LABEL_MAX_CHARS - 1)}…`
2538-
: label;
2539-
};
2540-
}, [rotateXLabels, xTickFormatter]);
2551+
if (rotateXLabels) {
2552+
return (value: any): string => {
2553+
const label = String(xTickFormatter(value) ?? '');
2554+
return label.length > ROTATED_X_LABEL_MAX_CHARS
2555+
? `${label.slice(0, ROTATED_X_LABEL_MAX_CHARS - 1)}…`
2556+
: label;
2557+
};
2558+
}
2559+
if (isMobile && !xAxisSpec?.format) {
2560+
return (value: any): string => {
2561+
const label = String(xTickFormatter(value) ?? '');
2562+
return label.length > PHONE_X_LABEL_MAX_CHARS ? `${label.slice(0, PHONE_X_LABEL_MAX_CHARS)}…` : label;
2563+
};
2564+
}
2565+
return xTickFormatter;
2566+
}, [rotateXLabels, isMobile, xAxisSpec?.format, xTickFormatter]);
25412567

25422568
// objectui#11796 — the band a rotated x axis reserves, from the longest
25432569
// label it draws (see `rotatedXAxisHeight`). A number, so the axis props
@@ -2737,7 +2763,7 @@ function AdvancedChartImplInner({
27372763
// 180-point daily series at 800px still thinned to 11 ticks with zero
27382764
// overlap, unchanged in kind from before this change.
27392765
const xAxisCommonProps = React.useMemo(() => ({
2740-
tick: AXIS_TICK_STYLE,
2766+
tick: (tickProps: any) => <TitledCategoryTick {...tickProps} fullLabel={xTickFormatter} />,
27412767
tickLine: false as const,
27422768
tickMargin: X_AXIS_TICK_MARGIN,
27432769
axisLine: false as const,
@@ -2761,7 +2787,7 @@ function AdvancedChartImplInner({
27612787
textAnchor: 'end' as const,
27622788
height: rotatedXAxisBand,
27632789
}),
2764-
}), [labelEveryBucket, rotateXLabels, xAxisTickFormatter, xAxisSpec?.title, xAxisAcross, rotatedXAxisBand]);
2790+
}), [labelEveryBucket, rotateXLabels, xAxisTickFormatter, xTickFormatter, xAxisSpec?.title, xAxisAcross, rotatedXAxisBand]);
27652791

27662792
// #2942 — the non-series spec families used to fall through the component
27672793
// map's `|| BarChart` into a bar shell whose series marks all returned
@@ -3608,10 +3634,16 @@ function AdvancedChartImplInner({
36083634
// swatch can draw; the swatch takes the series colour instead. A comparison
36093635
// swatch is drawn hollow, the way its mark is muted, so it reads apart from
36103636
// the primary series it shares a colour with.
3637+
// A lone bar series painted per category draws no swatch: no one colour
3638+
// names it, and the bars it would sit beside are each another one.
3639+
const perCategoryBars = (chartType === 'bar' || chartType === 'horizontal-bar')
3640+
&& !!categoryColors && series.length === 1 && series[0]?.variant !== 'comparison' && data.length > 1;
36113641
const legendSwatches: Record<string, LegendSwatch> = Object.fromEntries(
36123642
series.map((s: any, sIdx: number) => [
36133643
String(s.dataKey),
3614-
{ color: seriesColorAt(sIdx), comparison: s.variant === 'comparison' },
3644+
perCategoryBars
3645+
? { color: seriesColorAt(sIdx), none: true }
3646+
: { color: seriesColorAt(sIdx), comparison: s.variant === 'comparison' },
36153647
]),
36163648
);
36173649

@@ -3769,8 +3801,7 @@ function AdvancedChartImplInner({
37693801
// that has one keeps it, every other bar takes the series colour.
37703802
// With a comparison overlay the chart has two series, so each
37713803
// keeps its own series colour.
3772-
const primaryCount = series.filter((p: any) => p.variant !== 'comparison').length;
3773-
const semanticPerCategory = !!categoryColors && primaryCount === 1 && !isComparison && series.length === 1 && data.length > 1;
3804+
const semanticPerCategory = perCategoryBars;
37743805
const pres = seriesStyle(s, 'bar');
37753806
return (
37763807
<Bar key={s.dataKey} dataKey={s.dataKey} fill={`url(#bg-${gslug(seriesColor)})`} radius={4} fillOpacity={pres.fillOpacity} strokeOpacity={pres.strokeOpacity} strokeDasharray={pres.strokeDasharray} {...stackProps} {...axisProps} {...animProps} {...markClickProps(s)}>

‎ui/packages/plugin-charts/src/ChartContainerImpl.tsx‎

Lines changed: 4 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -450,9 +450,10 @@ const ChartLegend = Legend
450450
* the chart knows better than the colour recharts hands the legend: a mark
451451
* filled from a gradient hands it a paint-server reference (`url(#…)`), which
452452
* no swatch can draw. A `comparison` series draws its swatch hollow, the way
453-
* its mark is muted.
453+
* its mark is muted. `none` draws no swatch, only the label: a series whose
454+
* marks each carry another colour.
454455
*/
455-
export type LegendSwatch = { color: string; comparison?: boolean }
456+
export type LegendSwatch = { color: string; comparison?: boolean; none?: boolean }
456457

457458
function ChartLegendContent({
458459
className,
@@ -490,7 +491,7 @@ function ChartLegendContent({
490491
"[&>svg]:text-muted-foreground flex items-center gap-1.5 [&>svg]:h-3 [&>svg]:w-3"
491492
)}
492493
>
493-
{itemConfig?.icon && !hideIcon ? (
494+
{swatch?.none ? null : itemConfig?.icon && !hideIcon ? (
494495
<itemConfig.icon />
495496
) : (
496497
// The series colour is author-declared, so it reaches the DOM

0 commit comments

Comments
 (0)