From 950601f5f8998f1c316ac2451f671270869e68ad Mon Sep 17 00:00:00 2001 From: robinvrd Date: Tue, 10 Nov 2026 11:48:51 +0100 Subject: [PATCH 01/12] feat(charts): add interactive legend focus --- REFERENCE.md | 3 + .../data-app-react/src/ui/AnalyticsCharts.css | 4 + .../data-app-react/src/ui/ChartLegend.css | 11 + .../data-app-react/src/ui/ComposedChart.tsx | 198 +++++++++++----- .../src/ui/ComposedChartLegend.tsx | 213 +++++++++++------- .../data-app-react/src/ui/FunnelChart.tsx | 109 +++++++-- .../data-app-react/src/ui/RetentionChart.tsx | 74 +++++- .../src/ui/chart-legend-interaction.tsx | 76 +++++++ .../src/ui/chart-primitives.tsx | 54 ++++- tests/public-api/apps-chart-legends.test.ts | 151 +++++++++++++ tests/public-api/fixtures/chart-legends.tsx | 14 ++ 11 files changed, 752 insertions(+), 155 deletions(-) create mode 100644 packages/data-app-react/src/ui/chart-legend-interaction.tsx diff --git a/REFERENCE.md b/REFERENCE.md index a1629cfb..f561355f 100644 --- a/REFERENCE.md +++ b/REFERENCE.md @@ -280,6 +280,7 @@ ComposedChart.LabelList: (props: Props) ComposedChart.ErrorBar: (outsideProps: Props) ComposedChartLegendProps (type, @altertable/data-app-react/ui) ComposedChartLegendProps.maxVisibleItems?: number +ComposedChartLegendProps.interactive?: boolean — Enable hover emphasis and click to focus series. Disable for a descriptive legend or custom controls. ComposedChartLegendProps.…: plus props inherited from React, recharts ComposedChartProps (type, @altertable/data-app-react/ui): = props listed as ComposedChart.* connectionCheck (function, @altertable/data-app/contract): (queries: CheckedQueries): ConnectionOperation — A connectivity probe uses the app's registered connection query. @@ -918,6 +919,7 @@ FunnelChart.className?: string FunnelChart.horizontalGrid?: boolean — Draw horizontal grid lines behind the plotted values. FunnelChart.steps: readonly FunnelChartStep[] FunnelChart.series: readonly FunnelChartSeries[] +FunnelChart.interactiveLegend?: boolean — Disable legend hover and focus controls. FunnelChartProps (type, @altertable/data-app-react/ui): = props listed as FunnelChart.* FunnelChartSeries (type, @altertable/data-app-react/ui) FunnelChartSeries.id: string — Unique, nonblank population ID. @@ -1393,6 +1395,7 @@ RetentionChart.formatValue?: ((value: number) => string) — Formats counts; rat RetentionChart.className?: string RetentionChart.horizontalGrid?: boolean — Draw horizontal grid lines behind the plotted values. RetentionChart.series: readonly RetentionChartSeries[] +RetentionChart.interactiveLegend?: boolean — Disable legend hover and focus controls. RetentionChartPoint (type, @altertable/data-app-react/ui) RetentionChartPoint.offset: number — Nonnegative integer, unique per series; uneven offsets retain their distance. RetentionChartPoint.label: string — Must agree across series for the same offset. diff --git a/packages/data-app-react/src/ui/AnalyticsCharts.css b/packages/data-app-react/src/ui/AnalyticsCharts.css index b6918a4c..c93c0755 100644 --- a/packages/data-app-react/src/ui/AnalyticsCharts.css +++ b/packages/data-app-react/src/ui/AnalyticsCharts.css @@ -14,6 +14,10 @@ display: grid; gap: var(--atbl-space-xs); } +.altertable-funnel-legend-button { + display: grid; + gap: var(--atbl-space-xs); +} .altertable-funnel-series-label { display: flex; align-items: center; diff --git a/packages/data-app-react/src/ui/ChartLegend.css b/packages/data-app-react/src/ui/ChartLegend.css index 185be116..dc24a05e 100644 --- a/packages/data-app-react/src/ui/ChartLegend.css +++ b/packages/data-app-react/src/ui/ChartLegend.css @@ -37,6 +37,10 @@ .altertable-chart-legend-item[data-inactive] { opacity: var(--atbl-control-disabled-opacity); } +.altertable-chart-legend-item[data-legend-muted], +.altertable-chart-legend-item[data-legend-excluded] { + opacity: 0.4; +} .altertable-chart-legend-marker { display: inline-block; width: 8px; @@ -68,6 +72,13 @@ font: inherit; text-align: left; } +.altertable-chart-legend-action:where(button) { + cursor: pointer; +} +.altertable-chart-legend-show-all { + margin-top: var(--atbl-space-xs); + color: var(--atbl-accent); +} .altertable-chart-legend[data-layout='vertical'][data-align='center'] { justify-items: center; } diff --git a/packages/data-app-react/src/ui/ComposedChart.tsx b/packages/data-app-react/src/ui/ComposedChart.tsx index c6c240ac..74ef4dce 100644 --- a/packages/data-app-react/src/ui/ComposedChart.tsx +++ b/packages/data-app-react/src/ui/ComposedChart.tsx @@ -3,6 +3,7 @@ import { Children, Fragment, isValidElement, + cloneElement, useState, useCallback, useEffect, @@ -10,6 +11,7 @@ import { type PointerEvent, type ComponentProps, type ReactNode, + type ReactElement, } from 'react'; import { ComposedChart as RechartsComposedChart, @@ -20,6 +22,10 @@ import { ReferenceDot, Brush, Cell, + Line as NativeLine, + Bar as NativeBar, + Area as NativeArea, + Scatter as NativeScatter, Label, LabelList, ErrorBar, @@ -31,6 +37,10 @@ import { ChartInteractionContext, type ChartPoint, } from './chart-interaction.tsx'; +import { + ChartLegendInteractionContext, + chartLegendSeriesKey, +} from './chart-legend-interaction.tsx'; import { ChartBar as Bar, ChartDot as Dot, @@ -94,6 +104,66 @@ function hasAuthoredGrid(children: ReactNode): boolean { ); } +function applyNativeLegendInteraction( + children: ReactNode, + focusedKeys: ReadonlySet | null, + hoveredKey: string | null, + path = 'root' +): ReactNode { + return Children.map(children, (child, index) => { + if (!isValidElement(child)) return child; + if (child.type === Fragment) { + const props = child.props as { children?: ReactNode }; + return cloneElement(child, { + children: applyNativeLegendInteraction( + props.children, + focusedKeys, + hoveredKey, + `${path}-${child.key ?? index}` + ), + } as { children: ReactNode }); + } + if ( + child.type !== NativeLine && + child.type !== NativeBar && + child.type !== NativeArea && + child.type !== NativeScatter + ) + return child; + const series = child as ReactElement<{ + id?: string; + dataKey?: unknown; + hide?: boolean; + opacity?: number; + style?: { pointerEvents?: string }; + }>; + const id = + series.props.id ?? + (chartLegendSeriesKey(undefined, series.props.dataKey) == null + ? `atbl-native-${path}-${child.key ?? index}` + : undefined); + const key = chartLegendSeriesKey(id, series.props.dataKey)!; + return cloneElement(series, { + id, + opacity: + focusedKeys && !focusedKeys.has(key) + ? 0 + : hoveredKey && + (!focusedKeys || focusedKeys.has(hoveredKey)) && + hoveredKey !== key + ? 0.2 + : series.props.opacity, + style: { + ...series.props.style, + pointerEvents: + focusedKeys && !focusedKeys.has(key) + ? 'none' + : series.props.style?.pointerEvents, + }, + }); + }); +} + /** Compose Cartesian series inside VisualizationWidget. Defaults to responsive * full width and 300px height. Children retain native Recharts props and behavior, * including stacking, numeric/time axes, missing values, tooltips, and keyboard @@ -199,65 +269,91 @@ function ComposedChartRoot({ }); }; }, []); + const [legendHoveredKey, setLegendHoveredKey] = useState(null); + const [focusedLegendKeys, setFocusedLegendKeys] = + useState | null>(null); + const toggleLegendKey = useCallback((key: string) => { + setFocusedLegendKeys(current => { + if (!current) return new Set([key]); + const next = new Set(current); + if (next.has(key)) next.delete(key); + else next.add(key); + return next.size ? next : null; + }); + }, []); return ( - setFocusedLegendKeys(null), }} > -
{ - setHasPointerFocus(trackPointer(event)); + { - if (event.pointerType !== 'touch') { - resetPointerInspection(); - } - }} - onKeyDownCapture={() => { - setHasPointerFocus(false); - resetPointerInspection(); - }} - onBlurCapture={event => { - if (!event.currentTarget.contains(event.relatedTarget)) { + > +
{ + setHasPointerFocus(trackPointer(event)); + }} + onPointerOverCapture={trackPointer} + onPointerMoveCapture={trackPointer} + onPointerLeave={event => { + if (event.pointerType !== 'touch') { + resetPointerInspection(); + } + }} + onKeyDownCapture={() => { setHasPointerFocus(false); resetPointerInspection(); - } - }} - > - - - - {horizontalGrid && !hasAuthoredGrid(children) && ( - - )} - {children} - - - -
-
+ }} + onBlurCapture={event => { + if (!event.currentTarget.contains(event.relatedTarget)) { + setHasPointerFocus(false); + resetPointerInspection(); + } + }} + > + + + + {horizontalGrid && !hasAuthoredGrid(children) && ( + + )} + {applyNativeLegendInteraction( + children, + focusedLegendKeys, + legendHoveredKey + )} + + + +
+
+
); } diff --git a/packages/data-app-react/src/ui/ComposedChartLegend.tsx b/packages/data-app-react/src/ui/ComposedChartLegend.tsx index a392f447..e7ec1561 100644 --- a/packages/data-app-react/src/ui/ComposedChartLegend.tsx +++ b/packages/data-app-react/src/ui/ComposedChartLegend.tsx @@ -1,11 +1,17 @@ import { KEY_SEPARATOR } from '@altertable/data-app/internal'; -import { useState, type ComponentProps } from 'react'; +import { useContext, useState, type ComponentProps } from 'react'; import { Legend, type LegendPayload } from 'recharts'; +import { + ChartLegendInteractionContext, + chartLegendSeriesKey, +} from './chart-legend-interaction.tsx'; import { ChartLegend, type ChartLegendMarkerKind } from './ChartLegend.tsx'; export type ComposedChartLegendProps = ComponentProps & { maxVisibleItems?: number; + /** Enable hover emphasis and click to focus series. Disable for a descriptive legend or custom controls. */ + interactive?: boolean; }; type LegendContentProps = ComposedChartLegendProps & { payload?: readonly LegendPayload[]; @@ -41,11 +47,9 @@ function createLegendItemKeys() { source && typeof source === 'object' && 'id' in source ? source.id : undefined; - if (typeof id === 'string' || typeof id === 'number') - return ['series', typeof id, id].join(KEY_SEPARATOR); const key = entry.dataKey; - if (typeof key === 'string' || typeof key === 'number') - return ['data', typeof key, key].join(KEY_SEPARATOR); + const seriesKey = chartLegendSeriesKey(id, key); + if (seriesKey) return seriesKey; return ['object', identity(typeof key === 'function' ? key : entry)].join( KEY_SEPARATOR ); @@ -80,87 +84,136 @@ function LegendContent({ onClick, onMouseEnter, onMouseLeave, + interactive = true, 'aria-label': ariaLabel, }: LegendContentProps) { const [getItemKeys] = useState(createLegendItemKeys); + const interaction = useContext(ChartLegendInteractionContext); const itemKeys = getItemKeys(payload); + const canInteract = + interactive && + !onClick && + interaction && + (payload.filter(entry => entry.type !== 'none').length > 1 || + interaction.focusedKeys !== null); if (!payload.some(entry => entry.type !== 'none')) return null; const vertical = layout === 'vertical' || (layout === 'auto' && (position === 'left' || position === 'right')); return ( - - {payload.map((entry, index) => { - if (entry.type === 'none') return null; - const type = iconType ?? entry.type; - const kind = iconType - ? (legendMarkerKinds[type ?? 'none'] ?? 'point') - : 'square'; - const formatLabel = entry.formatter ?? formatter; - const label = formatLabel - ? formatLabel(entry.value, entry, index) - : entry.value; - const content = ( - <> - {type !== 'none' && - (entry.legendIcon ?? ( - + + {payload.map((entry, index) => { + if (entry.type === 'none') return null; + const type = iconType ?? entry.type; + const kind = iconType + ? (legendMarkerKinds[type ?? 'none'] ?? 'point') + : 'square'; + const formatLabel = entry.formatter ?? formatter; + const label = formatLabel + ? formatLabel(entry.value, entry, index) + : entry.value; + const content = ( + <> + {type !== 'none' && + (entry.legendIcon ?? ( + + ))} + {label} + + ); + return ( + { + if (canInteract) interaction.hover(itemKeys[index]!); + onMouseEnter?.(entry, index, event); + }} + onMouseLeave={event => { + if (canInteract) interaction.hover(null); + onMouseLeave?.(entry, index, event); + }} + > + {canInteract || onClick ? ( + - ) : ( - content - )} - - ); - })} - + onClick={event => { + if (canInteract) interaction.toggle(itemKeys[index]!); + onClick?.(entry, index, event); + }} + > + {content} + + ) : ( + content + )} + + ); + })} + + {canInteract && interaction.focusedKeys && ( + + )} + ); } @@ -169,13 +222,19 @@ function LegendContent({ * Native positioning, sorting, formatters, callbacks, and custom content remain available. */ export function ComposedChartLegend({ maxVisibleItems, + interactive = true, ...props }: ComposedChartLegendProps) { return ( } + content={ + + } {...props} /> ); diff --git a/packages/data-app-react/src/ui/FunnelChart.tsx b/packages/data-app-react/src/ui/FunnelChart.tsx index e6b91051..0e81f322 100644 --- a/packages/data-app-react/src/ui/FunnelChart.tsx +++ b/packages/data-app-react/src/ui/FunnelChart.tsx @@ -7,6 +7,7 @@ import { type CountChartProps, type HorizontalGridProps, } from './chart-data.ts'; +import { useChartLegendFocus } from './chart-legend-interaction.tsx'; import { ChartTooltipContent } from './chart-primitives.tsx'; import { ChartLegend } from './ChartLegend.tsx'; import { classNames } from './classNames.ts'; @@ -26,6 +27,8 @@ export type FunnelChartProps = CountChartProps & HorizontalGridProps & { steps: readonly FunnelChartStep[]; series: readonly FunnelChartSeries[]; + /** Disable legend hover and focus controls. */ + interactiveLegend?: boolean; }; type FunnelPopulation = { @@ -132,7 +135,9 @@ export function FunnelChart({ className, formatValue = formatNumber, horizontalGrid = true, + interactiveLegend = true, }: FunnelChartProps) { + const legendFocus = useChartLegendFocus(series.map(item => item.id)); const chartId = useSvgId(); const [highlighted, setHighlighted] = useState<{ id: string; @@ -174,19 +179,67 @@ export function FunnelChart({ - - - {item.label} - - - {formatPercent( - rows.at(-1)?.readings.get(item.id)?.conversion ?? null - )} - + {interactiveLegend && populations.length > 1 ? ( + + ) : ( + + + {item.label} + + )} + {(!interactiveLegend || populations.length <= 1) && ( + + {formatPercent( + rows.at(-1)?.readings.get(item.id)?.conversion ?? null + )} + + )} ))} + {interactiveLegend && legendFocus.focusedIds && ( + + )}

{steps[0]!.label} → {steps.at(-1)!.label}

@@ -253,8 +306,21 @@ export function FunnelChart({ maxBarSize={undefined} activeBar={false} minPointSize={0} + style={{ + pointerEvents: + interactiveLegend && !legendFocus.visible(item.id) + ? 'none' + : undefined, + }} opacity={ - !highlighted || highlighted.id === item.id ? 1 : 0.2 + interactiveLegend + ? legendFocus.opacity(item.id) * + (!highlighted || highlighted.id === item.id + ? 1 + : 0.2) + : !highlighted || highlighted.id === item.id + ? 1 + : 0.2 } onMouseEnter={bar => highlight(item.id, true, bar.payload.index) @@ -271,8 +337,21 @@ export function FunnelChart({ name={`${item.label} drop-off`} stackId={item.id} fill={`url(#${item.hatchId})`} + style={{ + pointerEvents: + interactiveLegend && !legendFocus.visible(item.id) + ? 'none' + : undefined, + }} opacity={ - !highlighted || highlighted.id === item.id ? 1 : 0.2 + interactiveLegend + ? legendFocus.opacity(item.id) * + (!highlighted || highlighted.id === item.id + ? 1 + : 0.2) + : !highlighted || highlighted.id === item.id + ? 1 + : 0.2 } onMouseEnter={bar => highlight(item.id, false, bar.payload.index) @@ -297,9 +376,11 @@ export function FunnelChart({ const tooltipItems = [...row.readings.values()] .filter( value => - !highlighted || - highlighted.step !== row.index || - value.population.id === highlighted.id + (!interactiveLegend || + legendFocus.visible(value.population.id)) && + (!highlighted || + highlighted.step !== row.index || + value.population.id === highlighted.id) ) .flatMap(value => { const item = value.population; diff --git a/packages/data-app-react/src/ui/RetentionChart.tsx b/packages/data-app-react/src/ui/RetentionChart.tsx index a0a045cd..6686e754 100644 --- a/packages/data-app-react/src/ui/RetentionChart.tsx +++ b/packages/data-app-react/src/ui/RetentionChart.tsx @@ -6,6 +6,7 @@ import { type CountChartProps, type HorizontalGridProps, } from './chart-data.ts'; +import { useChartLegendFocus } from './chart-legend-interaction.tsx'; import { ChartLegend } from './ChartLegend.tsx'; import { classNames } from './classNames.ts'; import { ComposedChart } from './ComposedChart.tsx'; @@ -34,6 +35,8 @@ export type RetentionChartSeries = { export type RetentionChartProps = CountChartProps & HorizontalGridProps & { series: readonly RetentionChartSeries[]; + /** Disable legend hover and focus controls. */ + interactiveLegend?: boolean; }; type RetentionReading = { @@ -148,7 +151,9 @@ export function RetentionChart({ className, formatValue = formatNumber, horizontalGrid = true, + interactiveLegend = true, }: RetentionChartProps) { + const legendFocus = useChartLegendFocus(series.map(item => item.id)); const { rows, rowsByOffset, cohorts } = createRetentionModel( series, unit, @@ -187,6 +192,13 @@ export function RetentionChart({ } name={item.label} stroke={item.color} + opacity={interactiveLegend ? legendFocus.opacity(item.id) : 1} + style={{ + pointerEvents: + interactiveLegend && !legendFocus.visible(item.id) + ? 'none' + : undefined, + }} connectNulls={false} /> {row.label} {cohorts.map(item => { const reading = row.readings.get(item.id); - if (!reading) return null; + if ( + !reading || + (interactiveLegend && !legendFocus.visible(item.id)) + ) + return null; return ( {item.label}: {reading.description} @@ -229,12 +252,55 @@ export function RetentionChart({ {cohorts.map(item => ( - - - {item.label} + + {interactiveLegend && cohorts.length > 1 ? ( + + ) : ( + <> + + {item.label} + + )} ))} + {interactiveLegend && legendFocus.focusedIds && ( + + )}
    | null; + hover: (key: string | null) => void; + toggle: (key: string) => void; + showAll: () => void; +}; + +export const ChartLegendInteractionContext = + createContext(null); + +export function useChartLegendSeries(id: unknown, dataKey: unknown) { + const interaction = useContext(ChartLegendInteractionContext); + const key = chartLegendSeriesKey(id, dataKey); + return { + hidden: !!( + key && + interaction?.focusedKeys && + !interaction.focusedKeys.has(key) + ), + dimmed: !!( + key && + interaction?.hoveredKey && + (!interaction.focusedKeys || + interaction.focusedKeys.has(interaction.hoveredKey)) && + interaction.hoveredKey !== key + ), + }; +} + +export function useChartLegendFocus(ids: readonly string[]) { + const [hoveredId, setHoveredId] = useState(null); + const [storedFocusedIds, setStoredFocusedIds] = + useState | null>(null); + const available = new Set(ids); + const visibleIds = + storedFocusedIds && + new Set([...storedFocusedIds].filter(id => available.has(id))); + const focusedIds = visibleIds?.size ? visibleIds : null; + function toggle(id: string) { + setStoredFocusedIds(() => { + if (!focusedIds) return new Set([id]); + const next = new Set(focusedIds); + if (next.has(id)) next.delete(id); + else next.add(id); + return next.size ? next : null; + }); + } + return { + hoveredId, + setHoveredId, + focusedIds, + toggle, + showAll: () => setStoredFocusedIds(null), + visible: (id: string) => !focusedIds || focusedIds.has(id), + opacity: (id: string) => + focusedIds && !focusedIds.has(id) + ? 0 + : hoveredId && + (!focusedIds || focusedIds.has(hoveredId)) && + hoveredId !== id + ? 0.2 + : 1, + }; +} diff --git a/packages/data-app-react/src/ui/chart-primitives.tsx b/packages/data-app-react/src/ui/chart-primitives.tsx index c9ac7512..7888ddba 100644 --- a/packages/data-app-react/src/ui/chart-primitives.tsx +++ b/packages/data-app-react/src/ui/chart-primitives.tsx @@ -25,6 +25,11 @@ import { useChartSeries, isChartSeriesActive, } from './chart-interaction.tsx'; +import { + ChartLegendInteractionContext, + chartLegendSeriesKey, + useChartLegendSeries, +} from './chart-legend-interaction.tsx'; import { ChartValueFormat, axisValueFormatter } from './chart-value-format.ts'; import { chartBarFill } from './chartColor.ts'; import { ChartLegend } from './ChartLegend.tsx'; @@ -71,6 +76,7 @@ export function ChartBar( ) { useDateAxisBar(props.xAxisId); const series = useChartSeries(props.id); + const legend = useChartLegendSeries(series.id, props.dataKey); return ( @@ -81,6 +87,11 @@ export function ChartBar( isAnimationActive={false} {...props} id={series.id} + opacity={legend.hidden ? 0 : legend.dimmed ? 0.2 : props.opacity} + style={{ + ...props.style, + pointerEvents: legend.hidden ? 'none' : props.style?.pointerEvents, + }} /> ); @@ -95,6 +106,7 @@ export function ChartLine({ ...props }: LineProps) { const series = useChartSeries(props.id); + const legend = useChartLegendSeries(series.id, props.dataKey); return ( @@ -123,6 +135,11 @@ export function ChartLine({ isAnimationActive={false} {...props} id={series.id} + opacity={legend.hidden ? 0 : legend.dimmed ? 0.2 : props.opacity} + style={{ + ...props.style, + pointerEvents: legend.hidden ? 'none' : props.style?.pointerEvents, + }} /> ); @@ -136,6 +153,7 @@ export function ChartArea({ ...props }: AreaProps) { const series = useChartSeries(props.id); + const legend = useChartLegendSeries(series.id, props.dataKey); return ( @@ -167,6 +185,11 @@ export function ChartArea({ isAnimationActive={false} {...props} id={series.id} + opacity={legend.hidden ? 0 : legend.dimmed ? 0.2 : props.opacity} + style={{ + ...props.style, + pointerEvents: legend.hidden ? 'none' : props.style?.pointerEvents, + }} /> ); @@ -176,6 +199,7 @@ export function ChartScatter( props: ComponentProps> ) { const series = useChartSeries(props.id); + const legend = useChartLegendSeries(series.id, props.dataKey); return ( @@ -183,6 +207,11 @@ export function ChartScatter( isAnimationActive={false} {...props} id={series.id} + opacity={legend.hidden ? 0 : legend.dimmed ? 0.2 : props.opacity} + style={{ + ...props.style, + pointerEvents: legend.hidden ? 'none' : props.style?.pointerEvents, + }} /> ); @@ -309,21 +338,28 @@ export function ChartTooltipContent( export function ChartTooltip(props: ComponentProps) { const dateLabel = useDateAxisLabel(props.axisId); const interaction = useContext(ChartInteractionContext); + const legendInteraction = useContext(ChartLegendInteractionContext); return ( ( entry.graphicalItemId === interaction.activeSeriesId - ) - : content.payload - } + payload={(interaction?.isPointerInspection && + interaction.seriesCount !== 1 && + props.shared !== true + ? content.payload.filter( + entry => entry.graphicalItemId === interaction.activeSeriesId + ) + : content.payload + ).filter(entry => { + if (!legendInteraction?.focusedKeys) return true; + const key = chartLegendSeriesKey( + entry.graphicalItemId, + entry.dataKey + ); + return key == null || legendInteraction.focusedKeys.has(key); + })} /> )} position={ diff --git a/tests/public-api/apps-chart-legends.test.ts b/tests/public-api/apps-chart-legends.test.ts index c97b7e7e..7633e0cf 100644 --- a/tests/public-api/apps-chart-legends.test.ts +++ b/tests/public-api/apps-chart-legends.test.ts @@ -2,6 +2,147 @@ import { expect } from 'vitest'; import { test } from '@/tests/public-api/browser'; +test('automatic legend previews, focuses multiple series, and restores all', async ({ + page, +}) => { + await page.goto('/chart-legends'); + const chart = page.getByRole('region', { + name: 'Response time across twelve services', + exact: true, + }); + const legend = chart.getByRole('list', { name: 'Chart legend' }); + const api = legend.getByRole('button', { name: 'API', exact: true }); + const analytics = legend.getByRole('button', { + name: 'Analytics', + exact: true, + }); + const curves = chart.locator('.recharts-line-curve'); + await expect.poll(() => curves.count()).toBe(12); + await api.hover(); + await expect + .poll(() => + legend.getByRole('listitem').nth(1).getAttribute('data-legend-muted') + ) + .toBe('true'); + await expect + .poll(() => + curves.evaluateAll( + paths => + paths.filter( + path => + path.getAttribute('opacity') === '0.2' || + path.closest('.recharts-line')?.getAttribute('opacity') === '0.2' + ).length + ) + ) + .toBe(11); + await api.click(); + await expect + .poll(async () => legend.locator('[data-legend-excluded]').count()) + .toBe((await legend.locator('button[aria-pressed]').count()) - 1); + await expect + .poll(() => + curves.evaluateAll( + paths => + paths.filter( + path => + path.getAttribute('opacity') === '0' || + path.closest('.recharts-line')?.getAttribute('opacity') === '0' + ).length + ) + ) + .toBe(11); + await expect.poll(() => api.getAttribute('aria-pressed')).toBe('true'); + await analytics.click(); + await expect + .poll(async () => legend.locator('[data-legend-excluded]').count()) + .toBe((await legend.locator('button[aria-pressed]').count()) - 2); + await expect + .poll(() => + curves.evaluateAll( + paths => + paths.filter( + path => + path.getAttribute('opacity') === '0' || + path.closest('.recharts-line')?.getAttribute('opacity') === '0' + ).length + ) + ) + .toBe(10); + await chart.getByRole('button', { name: 'Show all' }).click(); + await expect.poll(() => curves.count()).toBe(12); + await expect + .poll(() => legend.locator('[data-legend-excluded]').count()) + .toBe(0); +}); + +test('funnel and retention legends focus their plotted populations', async ({ + page, +}) => { + await page.goto('/chart-legends'); + for (const [name, first, second] of [ + ['FunnelChart', 'Free plan', 'Paid plan'], + ['RetentionChart', 'Sep 1', 'Sep 8'], + ]) { + const chart = page.getByRole('region', { + name: `${name} basic example`, + exact: true, + }); + const firstButton = chart.getByRole('button', { + name: first, + exact: name === 'RetentionChart', + }); + const secondButton = chart.getByRole('button', { + name: second, + exact: name === 'RetentionChart', + }); + await firstButton.click(); + await expect + .poll(() => firstButton.getAttribute('aria-pressed')) + .toBe('true'); + await expect + .poll(() => chart.locator('[data-legend-excluded]').count()) + .toBe(1); + await secondButton.click(); + await expect + .poll(() => chart.locator('[data-legend-excluded]').count()) + .toBe(0); + await chart.getByRole('button', { name: 'Show all' }).click(); + await expect + .poll(() => firstButton.getAttribute('aria-pressed')) + .toBe('false'); + } +}); + +test('native function-key series respond to the automatic legend', async ({ + page, +}) => { + await page.goto('/chart-legends'); + const chart = page.getByRole('region', { + name: 'Native accessor plot', + exact: true, + }); + const alpha = chart.getByRole('button', { name: 'Alpha', exact: true }); + await alpha.click(); + await expect.poll(() => alpha.getAttribute('aria-pressed')).toBe('true'); + await expect + .poll(() => + chart + .locator('.recharts-line-curve') + .evaluateAll( + paths => + paths.filter( + path => + path.getAttribute('opacity') === '0' || + path.closest('.recharts-line')?.getAttribute('opacity') === '0' + ).length + ) + ) + .toBe(1); + await chart.getByRole('button', { name: 'Show all' }).click(); + await expect.poll(() => alpha.getAttribute('aria-pressed')).toBe('false'); +}); + test('crowded automatic legends reserve a cell for expansion and restore their compact list', async ({ page, }) => { @@ -122,6 +263,16 @@ test('authored legends describe measures without controls and pie legends can be ); expect(await legend.getByRole('button').count()).toBe(0); expect(await legend.getByRole('img').count()).toBe(0); + const sparseRetention = page.getByRole('region', { + name: 'Sparse retention basic example', + exact: true, + }); + expect( + await sparseRetention + .getByRole('list', { name: 'Sparse retention cohorts' }) + .getByRole('button') + .count() + ).toBe(0); const pie = page.getByRole('region', { name: 'Standalone pie basic example', exact: true, diff --git a/tests/public-api/fixtures/chart-legends.tsx b/tests/public-api/fixtures/chart-legends.tsx index e331b718..9433b4a0 100644 --- a/tests/public-api/fixtures/chart-legends.tsx +++ b/tests/public-api/fixtures/chart-legends.tsx @@ -230,6 +230,7 @@ function LegendIdentityExample({ kind }: { kind: LegendKind }) { })} descending ? entry.value === 'Beta' @@ -548,6 +549,18 @@ createRoot(document.getElementById('root')!).render( ))} + + + + + + + + + Date: Tue, 10 Nov 2026 15:50:49 +0100 Subject: [PATCH 02/12] fix(charts): keep legend reset in place and hide excluded dots --- .../data-app-react/src/ui/ChartLegend.css | 26 +- .../data-app-react/src/ui/ChartLegend.tsx | 30 +++ .../data-app-react/src/ui/ComposedChart.tsx | 26 +- .../src/ui/ComposedChartLegend.tsx | 226 +++++++++--------- .../data-app-react/src/ui/FunnelChart.tsx | 116 ++++----- .../data-app-react/src/ui/RetentionChart.tsx | 98 ++++---- .../src/ui/chart-primitives.tsx | 67 +++--- tests/public-api/apps-chart-legends.test.ts | 17 ++ tests/public-api/fixtures/chart-legends.tsx | 12 + 9 files changed, 349 insertions(+), 269 deletions(-) diff --git a/packages/data-app-react/src/ui/ChartLegend.css b/packages/data-app-react/src/ui/ChartLegend.css index dc24a05e..a2f3d8ec 100644 --- a/packages/data-app-react/src/ui/ChartLegend.css +++ b/packages/data-app-react/src/ui/ChartLegend.css @@ -3,6 +3,28 @@ min-width: 0; width: 100%; } +.altertable-chart-legend-frame { + position: relative; + min-width: 0; + padding-inline-end: 48px; +} +.altertable-chart-legend-reset { + position: absolute; + inset-block-start: 0; + inset-inline-end: 0; + min-height: 24px; + padding: 1px 8px; + border: 1px solid var(--atbl-border); + border-radius: var(--atbl-radius-control); + background: var(--atbl-surface); + color: var(--atbl-text); + font: inherit; + font-size: var(--atbl-type-meta-size); + cursor: pointer; +} +.altertable-chart-legend-reset[hidden] { + display: none; +} .altertable-chart-legend { display: grid; grid-template-columns: minmax(0, 1fr); @@ -75,10 +97,6 @@ .altertable-chart-legend-action:where(button) { cursor: pointer; } -.altertable-chart-legend-show-all { - margin-top: var(--atbl-space-xs); - color: var(--atbl-accent); -} .altertable-chart-legend[data-layout='vertical'][data-align='center'] { justify-items: center; } diff --git a/packages/data-app-react/src/ui/ChartLegend.tsx b/packages/data-app-react/src/ui/ChartLegend.tsx index c386d47b..d6d9823f 100644 --- a/packages/data-app-react/src/ui/ChartLegend.tsx +++ b/packages/data-app-react/src/ui/ChartLegend.tsx @@ -21,6 +21,36 @@ export type ChartLegendProps = { maxVisibleItems?: number; } & Omit, 'children'>; +/** Keep the reset control in a stable slot beside an interactive legend. */ +export function ChartLegendFrame({ + children, + onShowAll, + enabled = true, +}: { + children: ReactNode; + onShowAll?: () => void; + enabled?: boolean; +}) { + if (!enabled) return <>{children}; + return ( +
    + {children} + +
    + ); +} + /** Optional chart key, placed beside any chart with the app's layout components. * Items describe displayed series or categories; the caller owns series visibility and interactions. */ function ChartLegendRoot({ diff --git a/packages/data-app-react/src/ui/ComposedChart.tsx b/packages/data-app-react/src/ui/ComposedChart.tsx index 74ef4dce..3222cd8a 100644 --- a/packages/data-app-react/src/ui/ComposedChart.tsx +++ b/packages/data-app-react/src/ui/ComposedChart.tsx @@ -136,6 +136,8 @@ function applyNativeLegendInteraction( hide?: boolean; opacity?: number; style?: { pointerEvents?: string }; + dot?: unknown; + activeDot?: unknown; }>; const id = series.props.id ?? @@ -143,23 +145,23 @@ function applyNativeLegendInteraction( ? `atbl-native-${path}-${child.key ?? index}` : undefined); const key = chartLegendSeriesKey(id, series.props.dataKey)!; + const excluded = !!(focusedKeys && !focusedKeys.has(key)); return cloneElement(series, { id, - opacity: - focusedKeys && !focusedKeys.has(key) - ? 0 - : hoveredKey && - (!focusedKeys || focusedKeys.has(hoveredKey)) && - hoveredKey !== key - ? 0.2 - : series.props.opacity, + opacity: excluded + ? 0 + : hoveredKey && + (!focusedKeys || focusedKeys.has(hoveredKey)) && + hoveredKey !== key + ? 0.2 + : series.props.opacity, style: { ...series.props.style, - pointerEvents: - focusedKeys && !focusedKeys.has(key) - ? 'none' - : series.props.style?.pointerEvents, + pointerEvents: excluded ? 'none' : series.props.style?.pointerEvents, }, + ...(excluded && (child.type === NativeLine || child.type === NativeArea) + ? { dot: false, activeDot: false } + : {}), }); }); } diff --git a/packages/data-app-react/src/ui/ComposedChartLegend.tsx b/packages/data-app-react/src/ui/ComposedChartLegend.tsx index e7ec1561..a6119574 100644 --- a/packages/data-app-react/src/ui/ComposedChartLegend.tsx +++ b/packages/data-app-react/src/ui/ComposedChartLegend.tsx @@ -6,7 +6,11 @@ import { ChartLegendInteractionContext, chartLegendSeriesKey, } from './chart-legend-interaction.tsx'; -import { ChartLegend, type ChartLegendMarkerKind } from './ChartLegend.tsx'; +import { + ChartLegend, + ChartLegendFrame, + type ChartLegendMarkerKind, +} from './ChartLegend.tsx'; export type ComposedChartLegendProps = ComponentProps & { maxVisibleItems?: number; @@ -100,120 +104,114 @@ function LegendContent({ const vertical = layout === 'vertical' || (layout === 'auto' && (position === 'left' || position === 'right')); - return ( - <> - - {payload.map((entry, index) => { - if (entry.type === 'none') return null; - const type = iconType ?? entry.type; - const kind = iconType - ? (legendMarkerKinds[type ?? 'none'] ?? 'point') - : 'square'; - const formatLabel = entry.formatter ?? formatter; - const label = formatLabel - ? formatLabel(entry.value, entry, index) - : entry.value; - const content = ( - <> - {type !== 'none' && - (entry.legendIcon ?? ( - - ))} - {label} - - ); - return ( - { - if (canInteract) interaction.hover(itemKeys[index]!); - onMouseEnter?.(entry, index, event); - }} - onMouseLeave={event => { - if (canInteract) interaction.hover(null); - onMouseLeave?.(entry, index, event); - }} - > - {canInteract || onClick ? ( - - ) : ( - content - )} - - ); - })} - - {canInteract && interaction.focusedKeys && ( - - )} - + /> + ))} + {label} + + ); + return ( + { + if (canInteract) interaction.hover(itemKeys[index]!); + onMouseEnter?.(entry, index, event); + }} + onMouseLeave={event => { + if (canInteract) interaction.hover(null); + onMouseLeave?.(entry, index, event); + }} + > + {canInteract || onClick ? ( + + ) : ( + content + )} + + ); + })} + + ); + return canInteract ? ( + + {legend} + + ) : ( + legend ); } diff --git a/packages/data-app-react/src/ui/FunnelChart.tsx b/packages/data-app-react/src/ui/FunnelChart.tsx index 0e81f322..32abb359 100644 --- a/packages/data-app-react/src/ui/FunnelChart.tsx +++ b/packages/data-app-react/src/ui/FunnelChart.tsx @@ -9,7 +9,7 @@ import { } from './chart-data.ts'; import { useChartLegendFocus } from './chart-legend-interaction.tsx'; import { ChartTooltipContent } from './chart-primitives.tsx'; -import { ChartLegend } from './ChartLegend.tsx'; +import { ChartLegend, ChartLegendFrame } from './ChartLegend.tsx'; import { classNames } from './classNames.ts'; import { ComposedChart } from './ComposedChart.tsx'; import { useSvgId } from './useSvgId.ts'; @@ -174,72 +174,72 @@ export function FunnelChart({ ) : ( <>
    - - {populations.map(item => ( - - {interactiveLegend && populations.length > 1 ? ( - + ) : ( {item.label} + )} + {(!interactiveLegend || populations.length <= 1) && ( {formatPercent( rows.at(-1)?.readings.get(item.id)?.conversion ?? null )} - - ) : ( - - - {item.label} - - )} - {(!interactiveLegend || populations.length <= 1) && ( - - {formatPercent( - rows.at(-1)?.readings.get(item.id)?.conversion ?? null - )} - - )} - - ))} - - {interactiveLegend && legendFocus.focusedIds && ( - - )} + )} + + ))} + +

    {steps[0]!.label} → {steps.at(-1)!.label}

    diff --git a/packages/data-app-react/src/ui/RetentionChart.tsx b/packages/data-app-react/src/ui/RetentionChart.tsx index 6686e754..06954ba6 100644 --- a/packages/data-app-react/src/ui/RetentionChart.tsx +++ b/packages/data-app-react/src/ui/RetentionChart.tsx @@ -7,7 +7,7 @@ import { type HorizontalGridProps, } from './chart-data.ts'; import { useChartLegendFocus } from './chart-legend-interaction.tsx'; -import { ChartLegend } from './ChartLegend.tsx'; +import { ChartLegend, ChartLegendFrame } from './ChartLegend.tsx'; import { classNames } from './classNames.ts'; import { ComposedChart } from './ComposedChart.tsx'; import { TooltipSurface } from './TooltipSurface.tsx'; @@ -250,57 +250,51 @@ export function RetentionChart({ }} /> - - {cohorts.map(item => ( - - {interactiveLegend && cohorts.length > 1 ? ( - - ) : ( - <> - - {item.label} - - )} - - ))} - - {interactiveLegend && legendFocus.focusedIds && ( - - )} + 1} + onShowAll={legendFocus.focusedIds ? legendFocus.showAll : undefined} + > + + {cohorts.map(item => ( + + {interactiveLegend && cohorts.length > 1 ? ( + + ) : ( + <> + + {item.label} + + )} + + ))} + +
      { - if (cx == null || cy == null) return; + if (legend.hidden || cx == null || cy == null) return; return registerPoint?.(seriesId, cx, cy); - }, [registerPoint, seriesId, cx, cy]); - const active = isChartSeriesActive(interaction, seriesId); + }, [registerPoint, seriesId, cx, cy, legend.hidden]); + const active = !legend.hidden && isChartSeriesActive(interaction, seriesId); return active ? ( ({ strokeLinecap="round" strokeLinejoin="round" dot={ - dot === true - ? ({ cx, cy }) => - : dot + legend.hidden + ? false + : dot === true + ? ({ cx, cy }) => + : dot } activeDot={ - activeDot === undefined || activeDot === true - ? ({ cx, cy }) => ( - - ) - : activeDot + legend.hidden + ? false + : activeDot === undefined || activeDot === true + ? ({ cx, cy }) => ( + + ) + : activeDot } isAnimationActive={false} {...props} @@ -166,21 +171,25 @@ export function ChartArea({ fill={stroke} fillOpacity={0.14} dot={ - dot === true - ? ({ cx, cy }) => - : dot + legend.hidden + ? false + : dot === true + ? ({ cx, cy }) => + : dot } activeDot={ - activeDot === undefined || activeDot === true - ? ({ cx, cy }) => ( - - ) - : activeDot + legend.hidden + ? false + : activeDot === undefined || activeDot === true + ? ({ cx, cy }) => ( + + ) + : activeDot } isAnimationActive={false} {...props} diff --git a/tests/public-api/apps-chart-legends.test.ts b/tests/public-api/apps-chart-legends.test.ts index 7633e0cf..778309d2 100644 --- a/tests/public-api/apps-chart-legends.test.ts +++ b/tests/public-api/apps-chart-legends.test.ts @@ -18,6 +18,7 @@ test('automatic legend previews, focuses multiple series, and restores all', asy }); const curves = chart.locator('.recharts-line-curve'); await expect.poll(() => curves.count()).toBe(12); + const chartHeight = (await chart.boundingBox())!.height; await api.hover(); await expect .poll(() => @@ -37,6 +38,7 @@ test('automatic legend previews, focuses multiple series, and restores all', asy ) .toBe(11); await api.click(); + expect((await chart.boundingBox())!.height).toBe(chartHeight); await expect .poll(async () => legend.locator('[data-legend-excluded]').count()) .toBe((await legend.locator('button[aria-pressed]').count()) - 1); @@ -70,12 +72,27 @@ test('automatic legend previews, focuses multiple series, and restores all', asy ) .toBe(10); await chart.getByRole('button', { name: 'Show all' }).click(); + expect((await chart.boundingBox())!.height).toBe(chartHeight); await expect.poll(() => curves.count()).toBe(12); await expect .poll(() => legend.locator('[data-legend-excluded]').count()) .toBe(0); }); +test('focus removes dots from excluded line series', async ({ page }) => { + await page.goto('/chart-legends'); + const chart = page.getByRole('region', { + name: 'Series dot plot', + exact: true, + }); + const dots = chart.locator('.recharts-line-dots circle'); + await expect.poll(() => dots.count()).toBe(4); + await chart.getByRole('button', { name: 'Alpha', exact: true }).click(); + await expect.poll(() => dots.count()).toBe(2); + await chart.getByRole('button', { name: 'Show all' }).click(); + await expect.poll(() => dots.count()).toBe(4); +}); + test('funnel and retention legends focus their plotted populations', async ({ page, }) => { diff --git a/tests/public-api/fixtures/chart-legends.tsx b/tests/public-api/fixtures/chart-legends.tsx index 9433b4a0..02256e0d 100644 --- a/tests/public-api/fixtures/chart-legends.tsx +++ b/tests/public-api/fixtures/chart-legends.tsx @@ -561,6 +561,18 @@ createRoot(document.getElementById('root')!).render( + + + + + + + + + Date: Tue, 10 Nov 2026 16:11:49 +0100 Subject: [PATCH 03/12] refactor(charts): integrate reset into legend overflow --- REFERENCE.md | 1 + .../data-app-react/src/ui/ChartLegend.css | 42 ++++--- .../data-app-react/src/ui/ChartLegend.tsx | 53 +++++---- .../src/ui/ComposedChartLegend.tsx | 21 ++-- .../data-app-react/src/ui/FunnelChart.tsx | 112 +++++++++--------- .../data-app-react/src/ui/RetentionChart.tsx | 95 ++++++++------- .../public-api/apps-chart-inspection.test.ts | 2 +- tests/public-api/apps-chart-legends.test.ts | 41 ++++++- tests/public-api/fixtures/chart-legends.tsx | 18 +++ 9 files changed, 223 insertions(+), 162 deletions(-) diff --git a/REFERENCE.md b/REFERENCE.md index f561355f..e35a8dad 100644 --- a/REFERENCE.md +++ b/REFERENCE.md @@ -166,6 +166,7 @@ ChartLegend.children: ReactNode ChartLegend.layout?: 'horizontal' | 'single-row' | 'vertical' — Single-row fits up to four cells before expansion, adapting to available width. ChartLegend.align?: 'center' | 'end' | 'start' ChartLegend.maxVisibleItems?: number — Optional cell cap, including expansion. Horizontal legends default to two rows. +ChartLegend.action?: ReactNode — Control shown in the final cell, beside the expansion control when needed. ChartLegend.…: plus props inherited from React ChartLegend.Item: (props: ChartLegendItemProps) ChartLegend.Marker: (props: ChartLegendMarkerProps) diff --git a/packages/data-app-react/src/ui/ChartLegend.css b/packages/data-app-react/src/ui/ChartLegend.css index a2f3d8ec..d4d53408 100644 --- a/packages/data-app-react/src/ui/ChartLegend.css +++ b/packages/data-app-react/src/ui/ChartLegend.css @@ -3,28 +3,6 @@ min-width: 0; width: 100%; } -.altertable-chart-legend-frame { - position: relative; - min-width: 0; - padding-inline-end: 48px; -} -.altertable-chart-legend-reset { - position: absolute; - inset-block-start: 0; - inset-inline-end: 0; - min-height: 24px; - padding: 1px 8px; - border: 1px solid var(--atbl-border); - border-radius: var(--atbl-radius-control); - background: var(--atbl-surface); - color: var(--atbl-text); - font: inherit; - font-size: var(--atbl-type-meta-size); - cursor: pointer; -} -.altertable-chart-legend-reset[hidden] { - display: none; -} .altertable-chart-legend { display: grid; grid-template-columns: minmax(0, 1fr); @@ -97,6 +75,22 @@ .altertable-chart-legend-action:where(button) { cursor: pointer; } +.altertable-chart-legend-all { + color: var(--atbl-muted); + font-weight: var(--atbl-type-label-weight); +} +.altertable-chart-legend-all[aria-pressed='true'] { + color: var(--atbl-text); +} +.altertable-chart-legend-all-short { + display: none; +} +.altertable-chart-legend-overflow .altertable-chart-legend-all-long { + display: none; +} +.altertable-chart-legend-overflow .altertable-chart-legend-all-short { + display: inline; +} .altertable-chart-legend[data-layout='vertical'][data-align='center'] { justify-items: center; } @@ -105,6 +99,10 @@ } .altertable-chart-legend-overflow { + display: flex; + align-items: center; + justify-content: space-between; + gap: var(--atbl-space-xs); grid-column: -2 / -1; min-width: 0; color: var(--atbl-muted); diff --git a/packages/data-app-react/src/ui/ChartLegend.tsx b/packages/data-app-react/src/ui/ChartLegend.tsx index d6d9823f..e1bac1ee 100644 --- a/packages/data-app-react/src/ui/ChartLegend.tsx +++ b/packages/data-app-react/src/ui/ChartLegend.tsx @@ -19,35 +19,32 @@ export type ChartLegendProps = { align?: 'start' | 'center' | 'end'; /** Optional cell cap, including expansion. Horizontal legends default to two rows. */ maxVisibleItems?: number; + /** Control shown in the final cell, beside the expansion control when needed. */ + action?: ReactNode; } & Omit, 'children'>; -/** Keep the reset control in a stable slot beside an interactive legend. */ -export function ChartLegendFrame({ - children, - onShowAll, - enabled = true, +export function ChartLegendAllAction({ + active, + onClick, }: { - children: ReactNode; - onShowAll?: () => void; - enabled?: boolean; + active: boolean; + onClick: () => void; }) { - if (!enabled) return <>{children}; return ( -
      - {children} - -
      + + ); } @@ -58,6 +55,7 @@ function ChartLegendRoot({ layout = 'horizontal', align = 'start', maxVisibleItems, + action, className, 'aria-label': ariaLabel = 'Chart legend', ...props @@ -96,7 +94,8 @@ function ChartLegendRoot({ : cappedLimit >= columns ? Math.floor(cappedLimit / columns) * columns : cappedLimit; - const visibleCount = items.length > limit ? limit - 1 : limit; + const visibleCount = + items.length + (action ? 1 : 0) > limit ? Math.max(1, limit - 1) : limit; const hiddenCount = Math.max(0, items.length - visibleCount); return (
      @@ -109,6 +108,11 @@ function ChartLegendRoot({ className={classNames('altertable-chart-legend', className)} > {expanded ? items : items.slice(0, visibleCount)} + {hiddenCount === 0 && action && ( +
    • + {action} +
    • + )} {hiddenCount > 0 && (
    • + {action}
    • )}
    diff --git a/packages/data-app-react/src/ui/ComposedChartLegend.tsx b/packages/data-app-react/src/ui/ComposedChartLegend.tsx index a6119574..086da8f9 100644 --- a/packages/data-app-react/src/ui/ComposedChartLegend.tsx +++ b/packages/data-app-react/src/ui/ComposedChartLegend.tsx @@ -8,7 +8,7 @@ import { } from './chart-legend-interaction.tsx'; import { ChartLegend, - ChartLegendFrame, + ChartLegendAllAction, type ChartLegendMarkerKind, } from './ChartLegend.tsx'; @@ -104,7 +104,7 @@ function LegendContent({ const vertical = layout === 'vertical' || (layout === 'auto' && (position === 'left' || position === 'right')); - const legend = ( + return ( + ) : undefined + } layout={vertical ? 'vertical' : 'horizontal'} align={align === 'right' ? 'end' : align === 'left' ? 'start' : 'center'} > @@ -204,15 +212,6 @@ function LegendContent({ })} ); - return canInteract ? ( - - {legend} - - ) : ( - legend - ); } /** Opt in inside ComposedChart to derive the shared legend from its displayed series. diff --git a/packages/data-app-react/src/ui/FunnelChart.tsx b/packages/data-app-react/src/ui/FunnelChart.tsx index 32abb359..c5686457 100644 --- a/packages/data-app-react/src/ui/FunnelChart.tsx +++ b/packages/data-app-react/src/ui/FunnelChart.tsx @@ -9,7 +9,7 @@ import { } from './chart-data.ts'; import { useChartLegendFocus } from './chart-legend-interaction.tsx'; import { ChartTooltipContent } from './chart-primitives.tsx'; -import { ChartLegend, ChartLegendFrame } from './ChartLegend.tsx'; +import { ChartLegend, ChartLegendAllAction } from './ChartLegend.tsx'; import { classNames } from './classNames.ts'; import { ComposedChart } from './ComposedChart.tsx'; import { useSvgId } from './useSvgId.ts'; @@ -174,72 +174,72 @@ export function FunnelChart({ ) : ( <>
    - 1} - onShowAll={ - legendFocus.focusedIds ? legendFocus.showAll : undefined + 1 ? ( + + ) : undefined } > - - {populations.map(item => ( - - {interactiveLegend && populations.length > 1 ? ( - - ) : ( + {populations.map(item => ( + + {interactiveLegend && populations.length > 1 ? ( + + ) : ( + + + {item.label} + + )} + {(!interactiveLegend || populations.length <= 1) && ( + + {formatPercent( + rows.at(-1)?.readings.get(item.id)?.conversion ?? null + )} + + )} + + ))} +

    {steps[0]!.label} → {steps.at(-1)!.label}

    diff --git a/packages/data-app-react/src/ui/RetentionChart.tsx b/packages/data-app-react/src/ui/RetentionChart.tsx index 06954ba6..4c312c47 100644 --- a/packages/data-app-react/src/ui/RetentionChart.tsx +++ b/packages/data-app-react/src/ui/RetentionChart.tsx @@ -7,7 +7,7 @@ import { type HorizontalGridProps, } from './chart-data.ts'; import { useChartLegendFocus } from './chart-legend-interaction.tsx'; -import { ChartLegend, ChartLegendFrame } from './ChartLegend.tsx'; +import { ChartLegend, ChartLegendAllAction } from './ChartLegend.tsx'; import { classNames } from './classNames.ts'; import { ComposedChart } from './ComposedChart.tsx'; import { TooltipSurface } from './TooltipSurface.tsx'; @@ -250,51 +250,56 @@ export function RetentionChart({ }} /> - 1} - onShowAll={legendFocus.focusedIds ? legendFocus.showAll : undefined} + 1 ? ( + + ) : undefined + } > - - {cohorts.map(item => ( - - {interactiveLegend && cohorts.length > 1 ? ( - - ) : ( - <> - - {item.label} - - )} - - ))} - - + {cohorts.map(item => ( + + {interactiveLegend && cohorts.length > 1 ? ( + + ) : ( + <> + + {item.label} + + )} + + ))} +
      legend.getByRole('listitem').count()).toBe(3); + await expect.poll(() => legend.getByRole('listitem').count()).toBe(4); for (const name of ['Revenue (€k)', 'Forecast (€k)', 'Conversion (%)']) { await expect .poll(() => legend.getByText(name, { exact: true }).isVisible()) diff --git a/tests/public-api/apps-chart-legends.test.ts b/tests/public-api/apps-chart-legends.test.ts index 778309d2..ea810820 100644 --- a/tests/public-api/apps-chart-legends.test.ts +++ b/tests/public-api/apps-chart-legends.test.ts @@ -41,7 +41,7 @@ test('automatic legend previews, focuses multiple series, and restores all', asy expect((await chart.boundingBox())!.height).toBe(chartHeight); await expect .poll(async () => legend.locator('[data-legend-excluded]').count()) - .toBe((await legend.locator('button[aria-pressed]').count()) - 1); + .toBe((await legend.locator('button[aria-pressed]').count()) - 2); await expect .poll(() => curves.evaluateAll( @@ -58,7 +58,7 @@ test('automatic legend previews, focuses multiple series, and restores all', asy await analytics.click(); await expect .poll(async () => legend.locator('[data-legend-excluded]').count()) - .toBe((await legend.locator('button[aria-pressed]').count()) - 2); + .toBe((await legend.locator('button[aria-pressed]').count()) - 3); await expect .poll(() => curves.evaluateAll( @@ -93,6 +93,41 @@ test('focus removes dots from excluded line series', async ({ page }) => { await expect.poll(() => dots.count()).toBe(4); }); +test('automatic legend keeps long labels accessible beside the all-series control', async ({ + mobilePage: page, +}) => { + await page.setViewportSize({ width: 320, height: 900 }); + await page.goto('/chart-legends'); + const chart = page.getByRole('region', { + name: 'Long series labels plot', + exact: true, + }); + const legend = chart.getByRole('list', { name: 'Chart legend' }); + const all = legend.getByRole('button', { name: 'Show all' }); + const label = legend.getByText( + 'Alpha — response time in production workspaces across Europe', + { exact: true } + ); + await expect.poll(() => all.getAttribute('aria-pressed')).toBe('true'); + await expect.poll(() => label.isVisible()).toBe(true); + expect(await label.getAttribute('title')).toBe( + 'Alpha — response time in production workspaces across Europe' + ); + expect( + await label.evaluate(element => element.scrollWidth > element.clientWidth) + ).toBe(true); + const chartHeight = (await chart.boundingBox())!.height; + await legend + .getByRole('button', { + name: 'Alpha — response time in production workspaces across Europe', + }) + .click(); + await expect.poll(() => all.getAttribute('aria-pressed')).toBe('false'); + expect((await chart.boundingBox())!.height).toBe(chartHeight); + await all.click(); + await expect.poll(() => all.getAttribute('aria-pressed')).toBe('true'); +}); + test('funnel and retention legends focus their plotted populations', async ({ page, }) => { @@ -260,7 +295,7 @@ test('crowded legends fill two rows and keep overflow in the final column on res const right = Math.max(...cells.map(cell => cell.right)); return ( cells.length <= 8 && - cells.at(-1)!.text === `+${13 - cells.length} more` && + cells.at(-1)!.text?.startsWith(`+${13 - cells.length} more`) && rows === 2 && cells.length === firstRow * 2 && Math.abs(cells.at(-1)!.right - right) < 1 diff --git a/tests/public-api/fixtures/chart-legends.tsx b/tests/public-api/fixtures/chart-legends.tsx index 02256e0d..aaf8c58d 100644 --- a/tests/public-api/fixtures/chart-legends.tsx +++ b/tests/public-api/fixtures/chart-legends.tsx @@ -573,6 +573,24 @@ createRoot(document.getElementById('root')!).render( + + + + + + + + + Date: Tue, 10 Nov 2026 16:38:04 +0100 Subject: [PATCH 04/12] fix(charts): show legend reset only in focus mode --- REFERENCE.md | 2 +- .../data-app-react/src/ui/ChartLegend.css | 41 ++++++++++--------- .../data-app-react/src/ui/ChartLegend.tsx | 33 +++++++-------- .../data-app-react/src/ui/ComposedChart.css | 4 ++ .../src/ui/ComposedChartLegend.tsx | 2 +- .../data-app-react/src/ui/FunnelChart.tsx | 2 +- .../data-app-react/src/ui/RetentionChart.tsx | 2 +- .../public-api/apps-chart-inspection.test.ts | 2 +- tests/public-api/apps-chart-legends.test.ts | 38 +++++++++++++---- tests/public-api/fixtures/chart-legends.tsx | 20 +++++++++ 10 files changed, 96 insertions(+), 50 deletions(-) diff --git a/REFERENCE.md b/REFERENCE.md index e35a8dad..ea914fd5 100644 --- a/REFERENCE.md +++ b/REFERENCE.md @@ -166,7 +166,7 @@ ChartLegend.children: ReactNode ChartLegend.layout?: 'horizontal' | 'single-row' | 'vertical' — Single-row fits up to four cells before expansion, adapting to available width. ChartLegend.align?: 'center' | 'end' | 'start' ChartLegend.maxVisibleItems?: number — Optional cell cap, including expansion. Horizontal legends default to two rows. -ChartLegend.action?: ReactNode — Control shown in the final cell, beside the expansion control when needed. +ChartLegend.action?: ReactNode — Optional control in a stable toolbar above the legend. ChartLegend.…: plus props inherited from React ChartLegend.Item: (props: ChartLegendItemProps) ChartLegend.Marker: (props: ChartLegendMarkerProps) diff --git a/packages/data-app-react/src/ui/ChartLegend.css b/packages/data-app-react/src/ui/ChartLegend.css index d4d53408..db095b9b 100644 --- a/packages/data-app-react/src/ui/ChartLegend.css +++ b/packages/data-app-react/src/ui/ChartLegend.css @@ -3,6 +3,27 @@ min-width: 0; width: 100%; } +.altertable-chart-legend-container[data-has-action] { + position: relative; + padding-top: 24px; +} +.altertable-chart-legend-toolbar { + position: absolute; + inset-block-start: 0; + inset-inline-end: 0; + display: flex; + justify-content: flex-end; + align-items: center; + height: 20px; +} +.altertable-chart-legend-reset { + color: var(--atbl-muted); + text-decoration: underline; + text-underline-offset: 2px; +} +.altertable-chart-legend-reset[hidden] { + display: none; +} .altertable-chart-legend { display: grid; grid-template-columns: minmax(0, 1fr); @@ -75,22 +96,6 @@ .altertable-chart-legend-action:where(button) { cursor: pointer; } -.altertable-chart-legend-all { - color: var(--atbl-muted); - font-weight: var(--atbl-type-label-weight); -} -.altertable-chart-legend-all[aria-pressed='true'] { - color: var(--atbl-text); -} -.altertable-chart-legend-all-short { - display: none; -} -.altertable-chart-legend-overflow .altertable-chart-legend-all-long { - display: none; -} -.altertable-chart-legend-overflow .altertable-chart-legend-all-short { - display: inline; -} .altertable-chart-legend[data-layout='vertical'][data-align='center'] { justify-items: center; } @@ -99,10 +104,6 @@ } .altertable-chart-legend-overflow { - display: flex; - align-items: center; - justify-content: space-between; - gap: var(--atbl-space-xs); grid-column: -2 / -1; min-width: 0; color: var(--atbl-muted); diff --git a/packages/data-app-react/src/ui/ChartLegend.tsx b/packages/data-app-react/src/ui/ChartLegend.tsx index e1bac1ee..cbf1659c 100644 --- a/packages/data-app-react/src/ui/ChartLegend.tsx +++ b/packages/data-app-react/src/ui/ChartLegend.tsx @@ -19,15 +19,15 @@ export type ChartLegendProps = { align?: 'start' | 'center' | 'end'; /** Optional cell cap, including expansion. Horizontal legends default to two rows. */ maxVisibleItems?: number; - /** Control shown in the final cell, beside the expansion control when needed. */ + /** Optional control in a stable toolbar above the legend. */ action?: ReactNode; } & Omit, 'children'>; export function ChartLegendAllAction({ - active, + visible, onClick, }: { - active: boolean; + visible: boolean; onClick: () => void; }) { return ( @@ -35,15 +35,12 @@ export function ChartLegendAllAction({ type="button" data-atbl-control="action" data-atbl-focus="ring" - className="altertable-chart-legend-action altertable-chart-legend-all" + className="altertable-chart-legend-action altertable-chart-legend-reset" aria-label="Show all" - aria-pressed={active} + hidden={!visible} onClick={onClick} > - All series - + Show all ); } @@ -94,11 +91,14 @@ function ChartLegendRoot({ : cappedLimit >= columns ? Math.floor(cappedLimit / columns) * columns : cappedLimit; - const visibleCount = - items.length + (action ? 1 : 0) > limit ? Math.max(1, limit - 1) : limit; + const visibleCount = items.length > limit ? limit - 1 : limit; const hiddenCount = Math.max(0, items.length - visibleCount); return ( -
      +
        {expanded ? items : items.slice(0, visibleCount)} - {hiddenCount === 0 && action && ( -
      • - {action} -
      • - )} {hiddenCount > 0 && (
      • - {action}
      • )}
      + {action && ( +
      {action}
      + )}
      ); } diff --git a/packages/data-app-react/src/ui/ComposedChart.css b/packages/data-app-react/src/ui/ComposedChart.css index 9e658dad..62613413 100644 --- a/packages/data-app-react/src/ui/ComposedChart.css +++ b/packages/data-app-react/src/ui/ComposedChart.css @@ -17,6 +17,10 @@ .altertable-composed-chart-legend-below { padding-top: var(--atbl-space-md); } +.altertable-chart-legend-container[data-has-action] + .altertable-composed-chart-legend-below { + padding-top: 0; +} .altertable-composed-chart-legend-above { padding-bottom: var(--atbl-space-md); } diff --git a/packages/data-app-react/src/ui/ComposedChartLegend.tsx b/packages/data-app-react/src/ui/ComposedChartLegend.tsx index 086da8f9..b1ebfc59 100644 --- a/packages/data-app-react/src/ui/ComposedChartLegend.tsx +++ b/packages/data-app-react/src/ui/ComposedChartLegend.tsx @@ -119,7 +119,7 @@ function LegendContent({ action={ canInteract ? ( ) : undefined diff --git a/packages/data-app-react/src/ui/FunnelChart.tsx b/packages/data-app-react/src/ui/FunnelChart.tsx index c5686457..b8595f63 100644 --- a/packages/data-app-react/src/ui/FunnelChart.tsx +++ b/packages/data-app-react/src/ui/FunnelChart.tsx @@ -180,7 +180,7 @@ export function FunnelChart({ action={ interactiveLegend && populations.length > 1 ? ( ) : undefined diff --git a/packages/data-app-react/src/ui/RetentionChart.tsx b/packages/data-app-react/src/ui/RetentionChart.tsx index 4c312c47..33e92c21 100644 --- a/packages/data-app-react/src/ui/RetentionChart.tsx +++ b/packages/data-app-react/src/ui/RetentionChart.tsx @@ -255,7 +255,7 @@ export function RetentionChart({ action={ interactiveLegend && cohorts.length > 1 ? ( ) : undefined diff --git a/tests/public-api/apps-chart-inspection.test.ts b/tests/public-api/apps-chart-inspection.test.ts index cda78899..92d38559 100644 --- a/tests/public-api/apps-chart-inspection.test.ts +++ b/tests/public-api/apps-chart-inspection.test.ts @@ -29,7 +29,7 @@ test('mixed chart series describe their measures and inspect the same monthly va .count() ).toBe(1); const legend = chart.getByRole('list', { name: 'Chart legend', exact: true }); - await expect.poll(() => legend.getByRole('listitem').count()).toBe(4); + await expect.poll(() => legend.getByRole('listitem').count()).toBe(3); for (const name of ['Revenue (€k)', 'Forecast (€k)', 'Conversion (%)']) { await expect .poll(() => legend.getByText(name, { exact: true }).isVisible()) diff --git a/tests/public-api/apps-chart-legends.test.ts b/tests/public-api/apps-chart-legends.test.ts index ea810820..13d3200b 100644 --- a/tests/public-api/apps-chart-legends.test.ts +++ b/tests/public-api/apps-chart-legends.test.ts @@ -18,6 +18,7 @@ test('automatic legend previews, focuses multiple series, and restores all', asy }); const curves = chart.locator('.recharts-line-curve'); await expect.poll(() => curves.count()).toBe(12); + expect(await chart.getByRole('button', { name: 'Show all' }).count()).toBe(0); const chartHeight = (await chart.boundingBox())!.height; await api.hover(); await expect @@ -41,7 +42,7 @@ test('automatic legend previews, focuses multiple series, and restores all', asy expect((await chart.boundingBox())!.height).toBe(chartHeight); await expect .poll(async () => legend.locator('[data-legend-excluded]').count()) - .toBe((await legend.locator('button[aria-pressed]').count()) - 2); + .toBe((await legend.locator('button[aria-pressed]').count()) - 1); await expect .poll(() => curves.evaluateAll( @@ -58,7 +59,7 @@ test('automatic legend previews, focuses multiple series, and restores all', asy await analytics.click(); await expect .poll(async () => legend.locator('[data-legend-excluded]').count()) - .toBe((await legend.locator('button[aria-pressed]').count()) - 3); + .toBe((await legend.locator('button[aria-pressed]').count()) - 2); await expect .poll(() => curves.evaluateAll( @@ -93,7 +94,7 @@ test('focus removes dots from excluded line series', async ({ page }) => { await expect.poll(() => dots.count()).toBe(4); }); -test('automatic legend keeps long labels accessible beside the all-series control', async ({ +test('automatic legend keeps long labels accessible with a conditional reset', async ({ mobilePage: page, }) => { await page.setViewportSize({ width: 320, height: 900 }); @@ -103,12 +104,12 @@ test('automatic legend keeps long labels accessible beside the all-series contro exact: true, }); const legend = chart.getByRole('list', { name: 'Chart legend' }); - const all = legend.getByRole('button', { name: 'Show all' }); + const all = chart.getByRole('button', { name: 'Show all' }); const label = legend.getByText( 'Alpha — response time in production workspaces across Europe', { exact: true } ); - await expect.poll(() => all.getAttribute('aria-pressed')).toBe('true'); + expect(await all.count()).toBe(0); await expect.poll(() => label.isVisible()).toBe(true); expect(await label.getAttribute('title')).toBe( 'Alpha — response time in production workspaces across Europe' @@ -122,10 +123,33 @@ test('automatic legend keeps long labels accessible beside the all-series contro name: 'Alpha — response time in production workspaces across Europe', }) .click(); - await expect.poll(() => all.getAttribute('aria-pressed')).toBe('false'); + await expect.poll(() => all.isVisible()).toBe(true); expect((await chart.boundingBox())!.height).toBe(chartHeight); await all.click(); - await expect.poll(() => all.getAttribute('aria-pressed')).toBe('true'); + await expect.poll(() => all.count()).toBe(0); +}); + +test('four series retain every legend cell when focus is toggled', async ({ + page, +}) => { + await page.setViewportSize({ width: 915, height: 968 }); + await page.goto('/chart-legends'); + const chart = page.getByRole('region', { + name: 'Four series plot', + exact: true, + }); + const legend = chart.getByRole('list', { name: 'Chart legend' }); + await expect.poll(() => legend.getByRole('listitem').count()).toBe(4); + expect(await chart.getByRole('button', { name: 'Show all' }).count()).toBe(0); + const height = (await chart.boundingBox())!.height; + await legend.getByRole('button', { name: 'Alpha', exact: true }).click(); + await expect + .poll(() => chart.getByRole('button', { name: 'Show all' }).isVisible()) + .toBe(true); + expect(await legend.getByRole('listitem').count()).toBe(4); + expect((await chart.boundingBox())!.height).toBe(height); + await chart.getByRole('button', { name: 'Show all' }).click(); + expect(await chart.getByRole('button', { name: 'Show all' }).count()).toBe(0); }); test('funnel and retention legends focus their plotted populations', async ({ diff --git a/tests/public-api/fixtures/chart-legends.tsx b/tests/public-api/fixtures/chart-legends.tsx index aaf8c58d..332f4a6e 100644 --- a/tests/public-api/fixtures/chart-legends.tsx +++ b/tests/public-api/fixtures/chart-legends.tsx @@ -591,6 +591,26 @@ createRoot(document.getElementById('root')!).render( + + + + + + + + + + + Date: Tue, 10 Nov 2026 16:41:30 +0100 Subject: [PATCH 05/12] fix(charts): align focus reset with legend heading --- REFERENCE.md | 3 ++- .../data-app-react/src/ui/ChartLegend.css | 21 ++++++++------- .../data-app-react/src/ui/ChartLegend.tsx | 27 ++++++++++++++----- .../data-app-react/src/ui/ComposedChart.css | 2 +- .../src/ui/ComposedChartLegend.tsx | 3 +++ .../data-app-react/src/ui/FunnelChart.tsx | 7 +++++ .../data-app-react/src/ui/RetentionChart.tsx | 5 ++++ tests/public-api/apps-chart-legends.test.ts | 20 ++++++++++++++ 8 files changed, 71 insertions(+), 17 deletions(-) diff --git a/REFERENCE.md b/REFERENCE.md index ea914fd5..b351ca3b 100644 --- a/REFERENCE.md +++ b/REFERENCE.md @@ -166,7 +166,8 @@ ChartLegend.children: ReactNode ChartLegend.layout?: 'horizontal' | 'single-row' | 'vertical' — Single-row fits up to four cells before expansion, adapting to available width. ChartLegend.align?: 'center' | 'end' | 'start' ChartLegend.maxVisibleItems?: number — Optional cell cap, including expansion. Horizontal legends default to two rows. -ChartLegend.action?: ReactNode — Optional control in a stable toolbar above the legend. +ChartLegend.heading?: string — Visible label above the legend items. +ChartLegend.action?: ReactNode — Optional control beside the heading. ChartLegend.…: plus props inherited from React ChartLegend.Item: (props: ChartLegendItemProps) ChartLegend.Marker: (props: ChartLegendMarkerProps) diff --git a/packages/data-app-react/src/ui/ChartLegend.css b/packages/data-app-react/src/ui/ChartLegend.css index db095b9b..408009ea 100644 --- a/packages/data-app-react/src/ui/ChartLegend.css +++ b/packages/data-app-react/src/ui/ChartLegend.css @@ -3,18 +3,21 @@ min-width: 0; width: 100%; } -.altertable-chart-legend-container[data-has-action] { - position: relative; - padding-top: 24px; -} -.altertable-chart-legend-toolbar { - position: absolute; - inset-block-start: 0; - inset-inline-end: 0; +.altertable-chart-legend-container[data-has-heading] { + padding-top: var(--atbl-space-md); +} +.altertable-chart-legend-header { display: flex; - justify-content: flex-end; align-items: center; + justify-content: space-between; + gap: var(--atbl-space-sm); height: 20px; + margin-bottom: var(--atbl-space-xs); + color: var(--atbl-muted); + font-size: var(--atbl-type-meta-size); +} +.altertable-chart-legend-heading { + font-weight: var(--atbl-type-label-weight); } .altertable-chart-legend-reset { color: var(--atbl-muted); diff --git a/packages/data-app-react/src/ui/ChartLegend.tsx b/packages/data-app-react/src/ui/ChartLegend.tsx index cbf1659c..64853965 100644 --- a/packages/data-app-react/src/ui/ChartLegend.tsx +++ b/packages/data-app-react/src/ui/ChartLegend.tsx @@ -19,7 +19,9 @@ export type ChartLegendProps = { align?: 'start' | 'center' | 'end'; /** Optional cell cap, including expansion. Horizontal legends default to two rows. */ maxVisibleItems?: number; - /** Optional control in a stable toolbar above the legend. */ + /** Visible label above the legend items. */ + heading?: string; + /** Optional control beside the heading. */ action?: ReactNode; } & Omit, 'children'>; @@ -52,6 +54,7 @@ function ChartLegendRoot({ layout = 'horizontal', align = 'start', maxVisibleItems, + heading, action, className, 'aria-label': ariaLabel = 'Chart legend', @@ -65,7 +68,9 @@ function ChartLegendRoot({ const container = containerRef.current; if (!container) return; function measure() { - const list = containerRef.current?.firstElementChild; + const list = containerRef.current?.querySelector( + '.altertable-chart-legend' + ); if (list) { setColumns( getComputedStyle(list).gridTemplateColumns.split(' ').length @@ -97,8 +102,21 @@ function ChartLegendRoot({
      + {(heading || action) && ( +
      + {heading && ( + + )} + {action} +
      + )}
        )}
      - {action && ( -
      {action}
      - )}
      ); } diff --git a/packages/data-app-react/src/ui/ComposedChart.css b/packages/data-app-react/src/ui/ComposedChart.css index 62613413..0fae8912 100644 --- a/packages/data-app-react/src/ui/ComposedChart.css +++ b/packages/data-app-react/src/ui/ComposedChart.css @@ -17,7 +17,7 @@ .altertable-composed-chart-legend-below { padding-top: var(--atbl-space-md); } -.altertable-chart-legend-container[data-has-action] +.altertable-chart-legend-container[data-has-heading] .altertable-composed-chart-legend-below { padding-top: 0; } diff --git a/packages/data-app-react/src/ui/ComposedChartLegend.tsx b/packages/data-app-react/src/ui/ComposedChartLegend.tsx index b1ebfc59..8a31a6ff 100644 --- a/packages/data-app-react/src/ui/ComposedChartLegend.tsx +++ b/packages/data-app-react/src/ui/ComposedChartLegend.tsx @@ -116,6 +116,7 @@ function LegendContent({ : undefined } maxVisibleItems={maxVisibleItems} + heading={canInteract ? 'Series' : undefined} action={ canInteract ? ( 1 + ? 'Series' + : undefined + } action={ interactiveLegend && populations.length > 1 ? ( 1 ? 'Cohorts' : undefined + } action={ interactiveLegend && cohorts.length > 1 ? ( api.getAttribute('aria-pressed')).toBe('true'); + await analytics.hover(); + await expect + .poll(() => legend.locator('[data-legend-muted]').count()) + .toBe(0); + await expect + .poll(() => + curves.evaluateAll( + paths => + paths.filter( + path => + path.getAttribute('opacity') === '0.2' || + path.closest('.recharts-line')?.getAttribute('opacity') === '0.2' + ).length + ) + ) + .toBe(0); await analytics.click(); await expect .poll(async () => legend.locator('[data-legend-excluded]').count()) @@ -179,6 +195,10 @@ test('funnel and retention legends focus their plotted populations', async ({ await expect .poll(() => chart.locator('[data-legend-excluded]').count()) .toBe(1); + await secondButton.hover(); + await expect + .poll(() => chart.locator('[data-legend-muted]').count()) + .toBe(0); await secondButton.click(); await expect .poll(() => chart.locator('[data-legend-excluded]').count()) From 81815253ca9fa7136078ec179119060531c59798 Mon Sep 17 00:00:00 2001 From: robinvrd Date: Tue, 10 Nov 2026 17:23:25 +0100 Subject: [PATCH 06/12] feat(charts): adopt Plotly-style legend toggling and isolation --- REFERENCE.md | 8 +- .../data-app-react/src/ui/ChartLegend.css | 24 ---- .../data-app-react/src/ui/ChartLegend.tsx | 47 +------- .../data-app-react/src/ui/ComposedChart.tsx | 22 ++-- .../src/ui/ComposedChartLegend.tsx | 38 +++--- .../data-app-react/src/ui/FunnelChart.tsx | 45 ++++---- .../data-app-react/src/ui/RetentionChart.tsx | 40 ++++--- .../src/ui/chart-legend-interaction.tsx | 85 ++++++++++++-- tests/public-api/apps-chart-legends.test.ts | 108 +++++++++++++----- 9 files changed, 233 insertions(+), 184 deletions(-) diff --git a/REFERENCE.md b/REFERENCE.md index b351ca3b..e992b929 100644 --- a/REFERENCE.md +++ b/REFERENCE.md @@ -166,8 +166,6 @@ ChartLegend.children: ReactNode ChartLegend.layout?: 'horizontal' | 'single-row' | 'vertical' — Single-row fits up to four cells before expansion, adapting to available width. ChartLegend.align?: 'center' | 'end' | 'start' ChartLegend.maxVisibleItems?: number — Optional cell cap, including expansion. Horizontal legends default to two rows. -ChartLegend.heading?: string — Visible label above the legend items. -ChartLegend.action?: ReactNode — Optional control beside the heading. ChartLegend.…: plus props inherited from React ChartLegend.Item: (props: ChartLegendItemProps) ChartLegend.Marker: (props: ChartLegendMarkerProps) @@ -282,7 +280,7 @@ ComposedChart.LabelList: (props: Props) ComposedChart.ErrorBar: (outsideProps: Props) ComposedChartLegendProps (type, @altertable/data-app-react/ui) ComposedChartLegendProps.maxVisibleItems?: number -ComposedChartLegendProps.interactive?: boolean — Enable hover emphasis and click to focus series. Disable for a descriptive legend or custom controls. +ComposedChartLegendProps.interactive?: boolean — Enable hover emphasis, click to toggle, and double-click to isolate series. ComposedChartLegendProps.…: plus props inherited from React, recharts ComposedChartProps (type, @altertable/data-app-react/ui): = props listed as ComposedChart.* connectionCheck (function, @altertable/data-app/contract): (queries: CheckedQueries): ConnectionOperation — A connectivity probe uses the app's registered connection query. @@ -921,7 +919,7 @@ FunnelChart.className?: string FunnelChart.horizontalGrid?: boolean — Draw horizontal grid lines behind the plotted values. FunnelChart.steps: readonly FunnelChartStep[] FunnelChart.series: readonly FunnelChartSeries[] -FunnelChart.interactiveLegend?: boolean — Disable legend hover and focus controls. +FunnelChart.interactiveLegend?: boolean — Disable legend hover, click toggle, and double-click isolation. FunnelChartProps (type, @altertable/data-app-react/ui): = props listed as FunnelChart.* FunnelChartSeries (type, @altertable/data-app-react/ui) FunnelChartSeries.id: string — Unique, nonblank population ID. @@ -1397,7 +1395,7 @@ RetentionChart.formatValue?: ((value: number) => string) — Formats counts; rat RetentionChart.className?: string RetentionChart.horizontalGrid?: boolean — Draw horizontal grid lines behind the plotted values. RetentionChart.series: readonly RetentionChartSeries[] -RetentionChart.interactiveLegend?: boolean — Disable legend hover and focus controls. +RetentionChart.interactiveLegend?: boolean — Disable legend hover, click toggle, and double-click isolation. RetentionChartPoint (type, @altertable/data-app-react/ui) RetentionChartPoint.offset: number — Nonnegative integer, unique per series; uneven offsets retain their distance. RetentionChartPoint.label: string — Must agree across series for the same offset. diff --git a/packages/data-app-react/src/ui/ChartLegend.css b/packages/data-app-react/src/ui/ChartLegend.css index 408009ea..545be08c 100644 --- a/packages/data-app-react/src/ui/ChartLegend.css +++ b/packages/data-app-react/src/ui/ChartLegend.css @@ -3,30 +3,6 @@ min-width: 0; width: 100%; } -.altertable-chart-legend-container[data-has-heading] { - padding-top: var(--atbl-space-md); -} -.altertable-chart-legend-header { - display: flex; - align-items: center; - justify-content: space-between; - gap: var(--atbl-space-sm); - height: 20px; - margin-bottom: var(--atbl-space-xs); - color: var(--atbl-muted); - font-size: var(--atbl-type-meta-size); -} -.altertable-chart-legend-heading { - font-weight: var(--atbl-type-label-weight); -} -.altertable-chart-legend-reset { - color: var(--atbl-muted); - text-decoration: underline; - text-underline-offset: 2px; -} -.altertable-chart-legend-reset[hidden] { - display: none; -} .altertable-chart-legend { display: grid; grid-template-columns: minmax(0, 1fr); diff --git a/packages/data-app-react/src/ui/ChartLegend.tsx b/packages/data-app-react/src/ui/ChartLegend.tsx index 64853965..81b30c92 100644 --- a/packages/data-app-react/src/ui/ChartLegend.tsx +++ b/packages/data-app-react/src/ui/ChartLegend.tsx @@ -19,34 +19,8 @@ export type ChartLegendProps = { align?: 'start' | 'center' | 'end'; /** Optional cell cap, including expansion. Horizontal legends default to two rows. */ maxVisibleItems?: number; - /** Visible label above the legend items. */ - heading?: string; - /** Optional control beside the heading. */ - action?: ReactNode; } & Omit, 'children'>; -export function ChartLegendAllAction({ - visible, - onClick, -}: { - visible: boolean; - onClick: () => void; -}) { - return ( - - ); -} - /** Optional chart key, placed beside any chart with the app's layout components. * Items describe displayed series or categories; the caller owns series visibility and interactions. */ function ChartLegendRoot({ @@ -54,8 +28,6 @@ function ChartLegendRoot({ layout = 'horizontal', align = 'start', maxVisibleItems, - heading, - action, className, 'aria-label': ariaLabel = 'Chart legend', ...props @@ -99,24 +71,7 @@ function ChartLegendRoot({ const visibleCount = items.length > limit ? limit - 1 : limit; const hiddenCount = Math.max(0, items.length - visibleCount); return ( -
      - {(heading || action) && ( -
      - {heading && ( - - )} - {action} -
      - )} +
        ({ const [legendHoveredKey, setLegendHoveredKey] = useState(null); const [focusedLegendKeys, setFocusedLegendKeys] = useState | null>(null); - const toggleLegendKey = useCallback((key: string) => { - setFocusedLegendKeys(current => { - if (!current) return new Set([key]); - const next = new Set(current); - if (next.has(key)) next.delete(key); - else next.add(key); - return next.size ? next : null; - }); + const toggleLegendKey = useCallback( + (key: string, keys: readonly string[]) => { + setFocusedLegendKeys(current => + toggleLegendVisibility(current, key, keys) + ); + }, + [] + ); + const isolateLegendKey = useCallback((key: string) => { + setFocusedLegendKeys(current => isolateLegendVisibility(current, key)); }, []); return ( @@ -291,7 +295,7 @@ function ComposedChartRoot({ focusedKeys: focusedLegendKeys, hover: setLegendHoveredKey, toggle: toggleLegendKey, - showAll: () => setFocusedLegendKeys(null), + isolate: isolateLegendKey, }} > & { maxVisibleItems?: number; - /** Enable hover emphasis and click to focus series. Disable for a descriptive legend or custom controls. */ + /** Enable hover emphasis, click to toggle, and double-click to isolate series. */ interactive?: boolean; }; type LegendContentProps = ComposedChartLegendProps & { @@ -100,6 +97,10 @@ function LegendContent({ interaction && (payload.filter(entry => entry.type !== 'none').length > 1 || interaction.focusedKeys !== null); + const clickActions = useLegendClickActions( + key => interaction?.toggle(key, itemKeys), + key => interaction?.isolate(key) + ); if (!payload.some(entry => entry.type !== 'none')) return null; const vertical = layout === 'vertical' || @@ -116,15 +117,6 @@ function LegendContent({ : undefined } maxVisibleItems={maxVisibleItems} - heading={canInteract ? 'Series' : undefined} - action={ - canInteract ? ( - - ) : undefined - } layout={vertical ? 'vertical' : 'horizontal'} align={align === 'right' ? 'end' : align === 'left' ? 'start' : 'center'} > @@ -189,9 +181,11 @@ function LegendContent({ data-atbl-control="action" data-atbl-focus="ring" className="altertable-chart-legend-action" + aria-keyshortcuts={canInteract ? 'Shift+Enter' : undefined} aria-pressed={ canInteract - ? !!interaction.focusedKeys?.has(itemKeys[index]!) + ? !interaction.focusedKeys || + interaction.focusedKeys.has(itemKeys[index]!) : undefined } onFocus={() => { @@ -201,9 +195,19 @@ function LegendContent({ if (canInteract) interaction.hover(null); }} onClick={event => { - if (canInteract) interaction.toggle(itemKeys[index]!); + if (canInteract) + clickActions.click(itemKeys[index]!, event.detail); onClick?.(entry, index, event); }} + onDoubleClick={() => { + if (canInteract) clickActions.doubleClick(itemKeys[index]!); + }} + onKeyDown={event => { + if (canInteract && event.key === 'Enter' && event.shiftKey) { + event.preventDefault(); + clickActions.doubleClick(itemKeys[index]!); + } + }} > {content} diff --git a/packages/data-app-react/src/ui/FunnelChart.tsx b/packages/data-app-react/src/ui/FunnelChart.tsx index 23eebbb9..91496c50 100644 --- a/packages/data-app-react/src/ui/FunnelChart.tsx +++ b/packages/data-app-react/src/ui/FunnelChart.tsx @@ -7,9 +7,12 @@ import { type CountChartProps, type HorizontalGridProps, } from './chart-data.ts'; -import { useChartLegendFocus } from './chart-legend-interaction.tsx'; +import { + useChartLegendFocus, + useLegendClickActions, +} from './chart-legend-interaction.tsx'; import { ChartTooltipContent } from './chart-primitives.tsx'; -import { ChartLegend, ChartLegendAllAction } from './ChartLegend.tsx'; +import { ChartLegend } from './ChartLegend.tsx'; import { classNames } from './classNames.ts'; import { ComposedChart } from './ComposedChart.tsx'; import { useSvgId } from './useSvgId.ts'; @@ -27,7 +30,7 @@ export type FunnelChartProps = CountChartProps & HorizontalGridProps & { steps: readonly FunnelChartStep[]; series: readonly FunnelChartSeries[]; - /** Disable legend hover and focus controls. */ + /** Disable legend hover, click toggle, and double-click isolation. */ interactiveLegend?: boolean; }; @@ -138,6 +141,10 @@ export function FunnelChart({ interactiveLegend = true, }: FunnelChartProps) { const legendFocus = useChartLegendFocus(series.map(item => item.id)); + const legendClicks = useLegendClickActions( + legendFocus.toggle, + legendFocus.isolate + ); const chartId = useSvgId(); const [highlighted, setHighlighted] = useState<{ id: string; @@ -174,23 +181,7 @@ export function FunnelChart({ ) : ( <>
        - 1 - ? 'Series' - : undefined - } - action={ - interactiveLegend && populations.length > 1 ? ( - - ) : undefined - } - > + {populations.map(item => ( legendFocus.setHoveredId(item.id)} onPointerLeave={() => legendFocus.setHoveredId(null)} onFocus={() => legendFocus.setHoveredId(item.id)} onBlur={() => legendFocus.setHoveredId(null)} - onClick={() => legendFocus.toggle(item.id)} + onClick={event => + legendClicks.click(item.id, event.detail) + } + onDoubleClick={() => legendClicks.doubleClick(item.id)} + onKeyDown={event => { + if (event.key === 'Enter' && event.shiftKey) { + event.preventDefault(); + legendClicks.doubleClick(item.id); + } + }} > diff --git a/packages/data-app-react/src/ui/RetentionChart.tsx b/packages/data-app-react/src/ui/RetentionChart.tsx index 6523a12b..12174a82 100644 --- a/packages/data-app-react/src/ui/RetentionChart.tsx +++ b/packages/data-app-react/src/ui/RetentionChart.tsx @@ -6,8 +6,11 @@ import { type CountChartProps, type HorizontalGridProps, } from './chart-data.ts'; -import { useChartLegendFocus } from './chart-legend-interaction.tsx'; -import { ChartLegend, ChartLegendAllAction } from './ChartLegend.tsx'; +import { + useChartLegendFocus, + useLegendClickActions, +} from './chart-legend-interaction.tsx'; +import { ChartLegend } from './ChartLegend.tsx'; import { classNames } from './classNames.ts'; import { ComposedChart } from './ComposedChart.tsx'; import { TooltipSurface } from './TooltipSurface.tsx'; @@ -35,7 +38,7 @@ export type RetentionChartSeries = { export type RetentionChartProps = CountChartProps & HorizontalGridProps & { series: readonly RetentionChartSeries[]; - /** Disable legend hover and focus controls. */ + /** Disable legend hover, click toggle, and double-click isolation. */ interactiveLegend?: boolean; }; @@ -154,6 +157,10 @@ export function RetentionChart({ interactiveLegend = true, }: RetentionChartProps) { const legendFocus = useChartLegendFocus(series.map(item => item.id)); + const legendClicks = useLegendClickActions( + legendFocus.toggle, + legendFocus.isolate + ); const { rows, rowsByOffset, cohorts } = createRetentionModel( series, unit, @@ -250,20 +257,7 @@ export function RetentionChart({ }} /> - 1 ? 'Cohorts' : undefined - } - action={ - interactiveLegend && cohorts.length > 1 ? ( - - ) : undefined - } - > + {cohorts.map(item => ( legendFocus.setHoveredId(item.id)} onPointerLeave={() => legendFocus.setHoveredId(null)} onFocus={() => legendFocus.setHoveredId(item.id)} onBlur={() => legendFocus.setHoveredId(null)} - onClick={() => legendFocus.toggle(item.id)} + onClick={event => legendClicks.click(item.id, event.detail)} + onDoubleClick={() => legendClicks.doubleClick(item.id)} + onKeyDown={event => { + if (event.key === 'Enter' && event.shiftKey) { + event.preventDefault(); + legendClicks.doubleClick(item.id); + } + }} > {item.label} diff --git a/packages/data-app-react/src/ui/chart-legend-interaction.tsx b/packages/data-app-react/src/ui/chart-legend-interaction.tsx index 445f3278..f88c0688 100644 --- a/packages/data-app-react/src/ui/chart-legend-interaction.tsx +++ b/packages/data-app-react/src/ui/chart-legend-interaction.tsx @@ -1,5 +1,5 @@ import { KEY_SEPARATOR } from '@altertable/data-app/internal'; -import { createContext, useContext, useState } from 'react'; +import { createContext, useContext, useEffect, useRef, useState } from 'react'; export function chartLegendSeriesKey(id: unknown, dataKey: unknown) { if (typeof id === 'string' || typeof id === 'number') @@ -13,10 +13,74 @@ export type ChartLegendInteraction = { hoveredKey: string | null; focusedKeys: ReadonlySet | null; hover: (key: string | null) => void; - toggle: (key: string) => void; - showAll: () => void; + toggle: (key: string, keys: readonly string[]) => void; + isolate: (key: string) => void; }; +export function toggleLegendVisibility( + visible: ReadonlySet | null, + key: string, + keys: readonly string[] +) { + const next = visible ? new Set(visible) : new Set(keys); + if (next.has(key)) next.delete(key); + else next.add(key); + return next.size === new Set(keys).size ? null : next; +} + +export function isolateLegendVisibility( + visible: ReadonlySet | null, + key: string +) { + if ( + visible && + (!visible.has(key) || (visible.size === 1 && visible.has(key))) + ) + return null; + return new Set([key]); +} + +/** Delay pointer clicks so a double-click performs one isolate action. */ +export function useLegendClickActions( + toggle: (key: string) => void, + isolate: (key: string) => void +) { + const pending = useRef<{ + key: string; + timer: ReturnType; + toggle: (key: string) => void; + } | null>(null); + useEffect( + () => () => { + if (pending.current) clearTimeout(pending.current.timer); + }, + [] + ); + return { + click: (key: string, detail: number) => { + if (pending.current) { + clearTimeout(pending.current.timer); + if (pending.current.key !== key) + pending.current.toggle(pending.current.key); + pending.current = null; + } + if (detail === 0) toggle(key); + else { + const timer = setTimeout(() => { + pending.current = null; + toggle(key); + }, 500); + pending.current = { key, timer, toggle }; + } + }, + doubleClick: (key: string) => { + if (pending.current) clearTimeout(pending.current.timer); + pending.current = null; + isolate(key); + }, + }; +} + export const ChartLegendInteractionContext = createContext(null); @@ -47,22 +111,19 @@ export function useChartLegendFocus(ids: readonly string[]) { const visibleIds = storedFocusedIds && new Set([...storedFocusedIds].filter(id => available.has(id))); - const focusedIds = visibleIds?.size ? visibleIds : null; + const focusedIds = visibleIds; function toggle(id: string) { - setStoredFocusedIds(() => { - if (!focusedIds) return new Set([id]); - const next = new Set(focusedIds); - if (next.has(id)) next.delete(id); - else next.add(id); - return next.size ? next : null; - }); + setStoredFocusedIds(current => toggleLegendVisibility(current, id, ids)); + } + function isolate(id: string) { + setStoredFocusedIds(current => isolateLegendVisibility(current, id)); } return { hoveredId, setHoveredId, focusedIds, toggle, - showAll: () => setStoredFocusedIds(null), + isolate, visible: (id: string) => !focusedIds || focusedIds.has(id), opacity: (id: string) => focusedIds && !focusedIds.has(id) diff --git a/tests/public-api/apps-chart-legends.test.ts b/tests/public-api/apps-chart-legends.test.ts index 03862fc5..93e0032c 100644 --- a/tests/public-api/apps-chart-legends.test.ts +++ b/tests/public-api/apps-chart-legends.test.ts @@ -2,7 +2,7 @@ import { expect } from 'vitest'; import { test } from '@/tests/public-api/browser'; -test('automatic legend previews, focuses multiple series, and restores all', async ({ +test('automatic legend previews, toggles, isolates, and restores series', async ({ page, }) => { await page.goto('/chart-legends'); @@ -42,7 +42,7 @@ test('automatic legend previews, focuses multiple series, and restores all', asy expect((await chart.boundingBox())!.height).toBe(chartHeight); await expect .poll(async () => legend.locator('[data-legend-excluded]').count()) - .toBe((await legend.locator('button[aria-pressed]').count()) - 1); + .toBe(1); await expect .poll(() => curves.evaluateAll( @@ -54,7 +54,16 @@ test('automatic legend previews, focuses multiple series, and restores all', asy ).length ) ) - .toBe(11); + .toBe(1); + await expect.poll(() => api.getAttribute('aria-pressed')).toBe('false'); + await api.dblclick(); + await expect + .poll(() => legend.locator('[data-legend-excluded]').count()) + .toBe(0); + await api.dblclick(); + await expect + .poll(() => legend.locator('[data-legend-excluded]').count()) + .toBe(4); await expect.poll(() => api.getAttribute('aria-pressed')).toBe('true'); await analytics.hover(); await expect @@ -88,7 +97,11 @@ test('automatic legend previews, focuses multiple series, and restores all', asy ) ) .toBe(10); - await chart.getByRole('button', { name: 'Show all' }).click(); + await analytics.dblclick(); + await expect + .poll(() => legend.locator('[data-legend-excluded]').count()) + .toBe(4); + await analytics.dblclick(); expect((await chart.boundingBox())!.height).toBe(chartHeight); await expect.poll(() => curves.count()).toBe(12); await expect @@ -96,7 +109,7 @@ test('automatic legend previews, focuses multiple series, and restores all', asy .toBe(0); }); -test('focus removes dots from excluded line series', async ({ page }) => { +test('isolation removes dots from excluded line series', async ({ page }) => { await page.goto('/chart-legends'); const chart = page.getByRole('region', { name: 'Series dot plot', @@ -104,13 +117,38 @@ test('focus removes dots from excluded line series', async ({ page }) => { }); const dots = chart.locator('.recharts-line-dots circle'); await expect.poll(() => dots.count()).toBe(4); - await chart.getByRole('button', { name: 'Alpha', exact: true }).click(); + const alpha = chart.getByRole('button', { name: 'Alpha', exact: true }); + await alpha.dblclick(); await expect.poll(() => dots.count()).toBe(2); - await chart.getByRole('button', { name: 'Show all' }).click(); + await alpha.dblclick(); await expect.poll(() => dots.count()).toBe(4); }); -test('automatic legend keeps long labels accessible with a conditional reset', async ({ +test('legend keyboard controls toggle and isolate series', async ({ page }) => { + await page.goto('/chart-legends'); + const chart = page.getByRole('region', { + name: 'Four series plot', + exact: true, + }); + const alpha = chart.getByRole('button', { name: 'Alpha', exact: true }); + await alpha.focus(); + await page.keyboard.press('Enter'); + await expect.poll(() => alpha.getAttribute('aria-pressed')).toBe('false'); + await page.keyboard.press('Shift+Enter'); + await expect + .poll(() => chart.locator('[data-legend-excluded]').count()) + .toBe(0); + await page.keyboard.press('Shift+Enter'); + await expect + .poll(() => chart.locator('[data-legend-excluded]').count()) + .toBe(3); + await page.keyboard.press('Shift+Enter'); + await expect + .poll(() => chart.locator('[data-legend-excluded]').count()) + .toBe(0); +}); + +test('automatic legend keeps long labels accessible without layout shift', async ({ mobilePage: page, }) => { await page.setViewportSize({ width: 320, height: 900 }); @@ -120,12 +158,10 @@ test('automatic legend keeps long labels accessible with a conditional reset', a exact: true, }); const legend = chart.getByRole('list', { name: 'Chart legend' }); - const all = chart.getByRole('button', { name: 'Show all' }); const label = legend.getByText( 'Alpha — response time in production workspaces across Europe', { exact: true } ); - expect(await all.count()).toBe(0); await expect.poll(() => label.isVisible()).toBe(true); expect(await label.getAttribute('title')).toBe( 'Alpha — response time in production workspaces across Europe' @@ -134,18 +170,21 @@ test('automatic legend keeps long labels accessible with a conditional reset', a await label.evaluate(element => element.scrollWidth > element.clientWidth) ).toBe(true); const chartHeight = (await chart.boundingBox())!.height; - await legend - .getByRole('button', { - name: 'Alpha — response time in production workspaces across Europe', - }) - .click(); - await expect.poll(() => all.isVisible()).toBe(true); + const alpha = legend.getByRole('button', { + name: 'Alpha — response time in production workspaces across Europe', + }); + await alpha.dblclick(); + await expect + .poll(() => legend.locator('[data-legend-excluded]').count()) + .toBeGreaterThan(0); expect((await chart.boundingBox())!.height).toBe(chartHeight); - await all.click(); - await expect.poll(() => all.count()).toBe(0); + await alpha.dblclick(); + await expect + .poll(() => legend.locator('[data-legend-excluded]').count()) + .toBe(0); }); -test('four series retain every legend cell when focus is toggled', async ({ +test('four series retain every legend cell during isolation', async ({ page, }) => { await page.setViewportSize({ width: 915, height: 968 }); @@ -158,14 +197,17 @@ test('four series retain every legend cell when focus is toggled', async ({ await expect.poll(() => legend.getByRole('listitem').count()).toBe(4); expect(await chart.getByRole('button', { name: 'Show all' }).count()).toBe(0); const height = (await chart.boundingBox())!.height; - await legend.getByRole('button', { name: 'Alpha', exact: true }).click(); + const alpha = legend.getByRole('button', { name: 'Alpha', exact: true }); + await alpha.dblclick(); await expect - .poll(() => chart.getByRole('button', { name: 'Show all' }).isVisible()) - .toBe(true); + .poll(() => legend.locator('[data-legend-excluded]').count()) + .toBe(3); expect(await legend.getByRole('listitem').count()).toBe(4); expect((await chart.boundingBox())!.height).toBe(height); - await chart.getByRole('button', { name: 'Show all' }).click(); - expect(await chart.getByRole('button', { name: 'Show all' }).count()).toBe(0); + await alpha.dblclick(); + await expect + .poll(() => legend.locator('[data-legend-excluded]').count()) + .toBe(0); }); test('funnel and retention legends focus their plotted populations', async ({ @@ -188,7 +230,7 @@ test('funnel and retention legends focus their plotted populations', async ({ name: second, exact: name === 'RetentionChart', }); - await firstButton.click(); + await firstButton.dblclick(); await expect .poll(() => firstButton.getAttribute('aria-pressed')) .toBe('true'); @@ -203,10 +245,14 @@ test('funnel and retention legends focus their plotted populations', async ({ await expect .poll(() => chart.locator('[data-legend-excluded]').count()) .toBe(0); - await chart.getByRole('button', { name: 'Show all' }).click(); + await firstButton.dblclick(); + await expect + .poll(() => chart.locator('[data-legend-excluded]').count()) + .toBe(1); + await firstButton.dblclick(); await expect .poll(() => firstButton.getAttribute('aria-pressed')) - .toBe('false'); + .toBe('true'); } }); @@ -219,7 +265,7 @@ test('native function-key series respond to the automatic legend', async ({ exact: true, }); const alpha = chart.getByRole('button', { name: 'Alpha', exact: true }); - await alpha.click(); + await alpha.dblclick(); await expect.poll(() => alpha.getAttribute('aria-pressed')).toBe('true'); await expect .poll(() => @@ -235,8 +281,10 @@ test('native function-key series respond to the automatic legend', async ({ ) ) .toBe(1); - await chart.getByRole('button', { name: 'Show all' }).click(); - await expect.poll(() => alpha.getAttribute('aria-pressed')).toBe('false'); + await alpha.dblclick(); + await expect + .poll(() => chart.locator('[data-legend-excluded]').count()) + .toBe(0); }); test('crowded automatic legends reserve a cell for expansion and restore their compact list', async ({ From 712ac5fe0b1c5109c7bc23965b63a87f5149f65d Mon Sep 17 00:00:00 2001 From: robinvrd Date: Tue, 10 Nov 2026 17:34:22 +0100 Subject: [PATCH 07/12] fix(charts): restore single-click legend focus and auto-exit --- REFERENCE.md | 6 +- .../data-app-react/src/ui/ComposedChart.tsx | 11 +-- .../src/ui/ComposedChartLegend.tsx | 25 ++---- .../data-app-react/src/ui/FunnelChart.tsx | 25 +----- .../data-app-react/src/ui/RetentionChart.tsx | 23 +----- .../src/ui/chart-legend-interaction.tsx | 73 ++---------------- tests/public-api/apps-chart-legends.test.ts | 76 ++++++++----------- 7 files changed, 59 insertions(+), 180 deletions(-) diff --git a/REFERENCE.md b/REFERENCE.md index e992b929..eb806645 100644 --- a/REFERENCE.md +++ b/REFERENCE.md @@ -280,7 +280,7 @@ ComposedChart.LabelList: (props: Props) ComposedChart.ErrorBar: (outsideProps: Props) ComposedChartLegendProps (type, @altertable/data-app-react/ui) ComposedChartLegendProps.maxVisibleItems?: number -ComposedChartLegendProps.interactive?: boolean — Enable hover emphasis, click to toggle, and double-click to isolate series. +ComposedChartLegendProps.interactive?: boolean — Enable hover emphasis and click to focus one or more series. ComposedChartLegendProps.…: plus props inherited from React, recharts ComposedChartProps (type, @altertable/data-app-react/ui): = props listed as ComposedChart.* connectionCheck (function, @altertable/data-app/contract): (queries: CheckedQueries): ConnectionOperation — A connectivity probe uses the app's registered connection query. @@ -919,7 +919,7 @@ FunnelChart.className?: string FunnelChart.horizontalGrid?: boolean — Draw horizontal grid lines behind the plotted values. FunnelChart.steps: readonly FunnelChartStep[] FunnelChart.series: readonly FunnelChartSeries[] -FunnelChart.interactiveLegend?: boolean — Disable legend hover, click toggle, and double-click isolation. +FunnelChart.interactiveLegend?: boolean — Disable legend hover and focus controls. FunnelChartProps (type, @altertable/data-app-react/ui): = props listed as FunnelChart.* FunnelChartSeries (type, @altertable/data-app-react/ui) FunnelChartSeries.id: string — Unique, nonblank population ID. @@ -1395,7 +1395,7 @@ RetentionChart.formatValue?: ((value: number) => string) — Formats counts; rat RetentionChart.className?: string RetentionChart.horizontalGrid?: boolean — Draw horizontal grid lines behind the plotted values. RetentionChart.series: readonly RetentionChartSeries[] -RetentionChart.interactiveLegend?: boolean — Disable legend hover, click toggle, and double-click isolation. +RetentionChart.interactiveLegend?: boolean — Disable legend hover and focus controls. RetentionChartPoint (type, @altertable/data-app-react/ui) RetentionChartPoint.offset: number — Nonnegative integer, unique per series; uneven offsets retain their distance. RetentionChartPoint.label: string — Must agree across series for the same offset. diff --git a/packages/data-app-react/src/ui/ComposedChart.tsx b/packages/data-app-react/src/ui/ComposedChart.tsx index c3ca1925..677e061f 100644 --- a/packages/data-app-react/src/ui/ComposedChart.tsx +++ b/packages/data-app-react/src/ui/ComposedChart.tsx @@ -40,8 +40,7 @@ import { import { ChartLegendInteractionContext, chartLegendSeriesKey, - isolateLegendVisibility, - toggleLegendVisibility, + toggleLegendFocus, } from './chart-legend-interaction.tsx'; import { ChartBar as Bar, @@ -278,15 +277,10 @@ function ComposedChartRoot({ useState | null>(null); const toggleLegendKey = useCallback( (key: string, keys: readonly string[]) => { - setFocusedLegendKeys(current => - toggleLegendVisibility(current, key, keys) - ); + setFocusedLegendKeys(current => toggleLegendFocus(current, key, keys)); }, [] ); - const isolateLegendKey = useCallback((key: string) => { - setFocusedLegendKeys(current => isolateLegendVisibility(current, key)); - }, []); return ( ({ focusedKeys: focusedLegendKeys, hover: setLegendHoveredKey, toggle: toggleLegendKey, - isolate: isolateLegendKey, }} > & { maxVisibleItems?: number; - /** Enable hover emphasis, click to toggle, and double-click to isolate series. */ + /** Enable hover emphasis and click to focus one or more series. */ interactive?: boolean; }; type LegendContentProps = ComposedChartLegendProps & { @@ -91,16 +90,15 @@ function LegendContent({ const [getItemKeys] = useState(createLegendItemKeys); const interaction = useContext(ChartLegendInteractionContext); const itemKeys = getItemKeys(payload); + const selectableKeys = itemKeys.filter( + (_, index) => payload[index]?.type !== 'none' + ); const canInteract = interactive && !onClick && interaction && (payload.filter(entry => entry.type !== 'none').length > 1 || interaction.focusedKeys !== null); - const clickActions = useLegendClickActions( - key => interaction?.toggle(key, itemKeys), - key => interaction?.isolate(key) - ); if (!payload.some(entry => entry.type !== 'none')) return null; const vertical = layout === 'vertical' || @@ -181,11 +179,9 @@ function LegendContent({ data-atbl-control="action" data-atbl-focus="ring" className="altertable-chart-legend-action" - aria-keyshortcuts={canInteract ? 'Shift+Enter' : undefined} aria-pressed={ canInteract - ? !interaction.focusedKeys || - interaction.focusedKeys.has(itemKeys[index]!) + ? !!interaction.focusedKeys?.has(itemKeys[index]!) : undefined } onFocus={() => { @@ -196,18 +192,9 @@ function LegendContent({ }} onClick={event => { if (canInteract) - clickActions.click(itemKeys[index]!, event.detail); + interaction.toggle(itemKeys[index]!, selectableKeys); onClick?.(entry, index, event); }} - onDoubleClick={() => { - if (canInteract) clickActions.doubleClick(itemKeys[index]!); - }} - onKeyDown={event => { - if (canInteract && event.key === 'Enter' && event.shiftKey) { - event.preventDefault(); - clickActions.doubleClick(itemKeys[index]!); - } - }} > {content} diff --git a/packages/data-app-react/src/ui/FunnelChart.tsx b/packages/data-app-react/src/ui/FunnelChart.tsx index 91496c50..a7308aa9 100644 --- a/packages/data-app-react/src/ui/FunnelChart.tsx +++ b/packages/data-app-react/src/ui/FunnelChart.tsx @@ -7,10 +7,7 @@ import { type CountChartProps, type HorizontalGridProps, } from './chart-data.ts'; -import { - useChartLegendFocus, - useLegendClickActions, -} from './chart-legend-interaction.tsx'; +import { useChartLegendFocus } from './chart-legend-interaction.tsx'; import { ChartTooltipContent } from './chart-primitives.tsx'; import { ChartLegend } from './ChartLegend.tsx'; import { classNames } from './classNames.ts'; @@ -30,7 +27,7 @@ export type FunnelChartProps = CountChartProps & HorizontalGridProps & { steps: readonly FunnelChartStep[]; series: readonly FunnelChartSeries[]; - /** Disable legend hover, click toggle, and double-click isolation. */ + /** Disable legend hover and focus controls. */ interactiveLegend?: boolean; }; @@ -141,10 +138,6 @@ export function FunnelChart({ interactiveLegend = true, }: FunnelChartProps) { const legendFocus = useChartLegendFocus(series.map(item => item.id)); - const legendClicks = useLegendClickActions( - legendFocus.toggle, - legendFocus.isolate - ); const chartId = useSvgId(); const [highlighted, setHighlighted] = useState<{ id: string; @@ -205,22 +198,12 @@ export function FunnelChart({ data-atbl-control="action" data-atbl-focus="ring" className="altertable-chart-legend-action altertable-funnel-legend-button" - aria-keyshortcuts="Shift+Enter" - aria-pressed={legendFocus.visible(item.id)} + aria-pressed={!!legendFocus.focusedIds?.has(item.id)} onPointerEnter={() => legendFocus.setHoveredId(item.id)} onPointerLeave={() => legendFocus.setHoveredId(null)} onFocus={() => legendFocus.setHoveredId(item.id)} onBlur={() => legendFocus.setHoveredId(null)} - onClick={event => - legendClicks.click(item.id, event.detail) - } - onDoubleClick={() => legendClicks.doubleClick(item.id)} - onKeyDown={event => { - if (event.key === 'Enter' && event.shiftKey) { - event.preventDefault(); - legendClicks.doubleClick(item.id); - } - }} + onClick={() => legendFocus.toggle(item.id)} > diff --git a/packages/data-app-react/src/ui/RetentionChart.tsx b/packages/data-app-react/src/ui/RetentionChart.tsx index 12174a82..91a60539 100644 --- a/packages/data-app-react/src/ui/RetentionChart.tsx +++ b/packages/data-app-react/src/ui/RetentionChart.tsx @@ -6,10 +6,7 @@ import { type CountChartProps, type HorizontalGridProps, } from './chart-data.ts'; -import { - useChartLegendFocus, - useLegendClickActions, -} from './chart-legend-interaction.tsx'; +import { useChartLegendFocus } from './chart-legend-interaction.tsx'; import { ChartLegend } from './ChartLegend.tsx'; import { classNames } from './classNames.ts'; import { ComposedChart } from './ComposedChart.tsx'; @@ -38,7 +35,7 @@ export type RetentionChartSeries = { export type RetentionChartProps = CountChartProps & HorizontalGridProps & { series: readonly RetentionChartSeries[]; - /** Disable legend hover, click toggle, and double-click isolation. */ + /** Disable legend hover and focus controls. */ interactiveLegend?: boolean; }; @@ -157,10 +154,6 @@ export function RetentionChart({ interactiveLegend = true, }: RetentionChartProps) { const legendFocus = useChartLegendFocus(series.map(item => item.id)); - const legendClicks = useLegendClickActions( - legendFocus.toggle, - legendFocus.isolate - ); const { rows, rowsByOffset, cohorts } = createRetentionModel( series, unit, @@ -280,20 +273,12 @@ export function RetentionChart({ data-atbl-control="action" data-atbl-focus="ring" className="altertable-chart-legend-action" - aria-keyshortcuts="Shift+Enter" - aria-pressed={legendFocus.visible(item.id)} + aria-pressed={!!legendFocus.focusedIds?.has(item.id)} onPointerEnter={() => legendFocus.setHoveredId(item.id)} onPointerLeave={() => legendFocus.setHoveredId(null)} onFocus={() => legendFocus.setHoveredId(item.id)} onBlur={() => legendFocus.setHoveredId(null)} - onClick={event => legendClicks.click(item.id, event.detail)} - onDoubleClick={() => legendClicks.doubleClick(item.id)} - onKeyDown={event => { - if (event.key === 'Enter' && event.shiftKey) { - event.preventDefault(); - legendClicks.doubleClick(item.id); - } - }} + onClick={() => legendFocus.toggle(item.id)} > {item.label} diff --git a/packages/data-app-react/src/ui/chart-legend-interaction.tsx b/packages/data-app-react/src/ui/chart-legend-interaction.tsx index f88c0688..34b872f6 100644 --- a/packages/data-app-react/src/ui/chart-legend-interaction.tsx +++ b/packages/data-app-react/src/ui/chart-legend-interaction.tsx @@ -1,5 +1,5 @@ import { KEY_SEPARATOR } from '@altertable/data-app/internal'; -import { createContext, useContext, useEffect, useRef, useState } from 'react'; +import { createContext, useContext, useState } from 'react'; export function chartLegendSeriesKey(id: unknown, dataKey: unknown) { if (typeof id === 'string' || typeof id === 'number') @@ -14,71 +14,18 @@ export type ChartLegendInteraction = { focusedKeys: ReadonlySet | null; hover: (key: string | null) => void; toggle: (key: string, keys: readonly string[]) => void; - isolate: (key: string) => void; }; -export function toggleLegendVisibility( - visible: ReadonlySet | null, +export function toggleLegendFocus( + focused: ReadonlySet | null, key: string, keys: readonly string[] ) { - const next = visible ? new Set(visible) : new Set(keys); + if (!focused) return new Set([key]); + const next = new Set(focused); if (next.has(key)) next.delete(key); else next.add(key); - return next.size === new Set(keys).size ? null : next; -} - -export function isolateLegendVisibility( - visible: ReadonlySet | null, - key: string -) { - if ( - visible && - (!visible.has(key) || (visible.size === 1 && visible.has(key))) - ) - return null; - return new Set([key]); -} - -/** Delay pointer clicks so a double-click performs one isolate action. */ -export function useLegendClickActions( - toggle: (key: string) => void, - isolate: (key: string) => void -) { - const pending = useRef<{ - key: string; - timer: ReturnType; - toggle: (key: string) => void; - } | null>(null); - useEffect( - () => () => { - if (pending.current) clearTimeout(pending.current.timer); - }, - [] - ); - return { - click: (key: string, detail: number) => { - if (pending.current) { - clearTimeout(pending.current.timer); - if (pending.current.key !== key) - pending.current.toggle(pending.current.key); - pending.current = null; - } - if (detail === 0) toggle(key); - else { - const timer = setTimeout(() => { - pending.current = null; - toggle(key); - }, 500); - pending.current = { key, timer, toggle }; - } - }, - doubleClick: (key: string) => { - if (pending.current) clearTimeout(pending.current.timer); - pending.current = null; - isolate(key); - }, - }; + return next.size === 0 || next.size === new Set(keys).size ? null : next; } export const ChartLegendInteractionContext = @@ -111,19 +58,15 @@ export function useChartLegendFocus(ids: readonly string[]) { const visibleIds = storedFocusedIds && new Set([...storedFocusedIds].filter(id => available.has(id))); - const focusedIds = visibleIds; + const focusedIds = visibleIds?.size ? visibleIds : null; function toggle(id: string) { - setStoredFocusedIds(current => toggleLegendVisibility(current, id, ids)); - } - function isolate(id: string) { - setStoredFocusedIds(current => isolateLegendVisibility(current, id)); + setStoredFocusedIds(current => toggleLegendFocus(current, id, ids)); } return { hoveredId, setHoveredId, focusedIds, toggle, - isolate, visible: (id: string) => !focusedIds || focusedIds.has(id), opacity: (id: string) => focusedIds && !focusedIds.has(id) diff --git a/tests/public-api/apps-chart-legends.test.ts b/tests/public-api/apps-chart-legends.test.ts index 93e0032c..f8834e10 100644 --- a/tests/public-api/apps-chart-legends.test.ts +++ b/tests/public-api/apps-chart-legends.test.ts @@ -2,7 +2,7 @@ import { expect } from 'vitest'; import { test } from '@/tests/public-api/browser'; -test('automatic legend previews, toggles, isolates, and restores series', async ({ +test('automatic legend previews, focuses, and adds series', async ({ page, }) => { await page.goto('/chart-legends'); @@ -42,7 +42,7 @@ test('automatic legend previews, toggles, isolates, and restores series', async expect((await chart.boundingBox())!.height).toBe(chartHeight); await expect .poll(async () => legend.locator('[data-legend-excluded]').count()) - .toBe(1); + .toBe((await legend.locator('button[aria-pressed]').count()) - 1); await expect .poll(() => curves.evaluateAll( @@ -54,16 +54,7 @@ test('automatic legend previews, toggles, isolates, and restores series', async ).length ) ) - .toBe(1); - await expect.poll(() => api.getAttribute('aria-pressed')).toBe('false'); - await api.dblclick(); - await expect - .poll(() => legend.locator('[data-legend-excluded]').count()) - .toBe(0); - await api.dblclick(); - await expect - .poll(() => legend.locator('[data-legend-excluded]').count()) - .toBe(4); + .toBe(11); await expect.poll(() => api.getAttribute('aria-pressed')).toBe('true'); await analytics.hover(); await expect @@ -97,11 +88,8 @@ test('automatic legend previews, toggles, isolates, and restores series', async ) ) .toBe(10); - await analytics.dblclick(); - await expect - .poll(() => legend.locator('[data-legend-excluded]').count()) - .toBe(4); - await analytics.dblclick(); + await api.click(); + await analytics.click(); expect((await chart.boundingBox())!.height).toBe(chartHeight); await expect.poll(() => curves.count()).toBe(12); await expect @@ -109,7 +97,7 @@ test('automatic legend previews, toggles, isolates, and restores series', async .toBe(0); }); -test('isolation removes dots from excluded line series', async ({ page }) => { +test('focus removes dots from excluded line series', async ({ page }) => { await page.goto('/chart-legends'); const chart = page.getByRole('region', { name: 'Series dot plot', @@ -118,13 +106,13 @@ test('isolation removes dots from excluded line series', async ({ page }) => { const dots = chart.locator('.recharts-line-dots circle'); await expect.poll(() => dots.count()).toBe(4); const alpha = chart.getByRole('button', { name: 'Alpha', exact: true }); - await alpha.dblclick(); + await alpha.click(); await expect.poll(() => dots.count()).toBe(2); - await alpha.dblclick(); + await alpha.click(); await expect.poll(() => dots.count()).toBe(4); }); -test('legend keyboard controls toggle and isolate series', async ({ page }) => { +test('legend keyboard controls focus and restore series', async ({ page }) => { await page.goto('/chart-legends'); const chart = page.getByRole('region', { name: 'Four series plot', @@ -133,16 +121,11 @@ test('legend keyboard controls toggle and isolate series', async ({ page }) => { const alpha = chart.getByRole('button', { name: 'Alpha', exact: true }); await alpha.focus(); await page.keyboard.press('Enter'); - await expect.poll(() => alpha.getAttribute('aria-pressed')).toBe('false'); - await page.keyboard.press('Shift+Enter'); - await expect - .poll(() => chart.locator('[data-legend-excluded]').count()) - .toBe(0); - await page.keyboard.press('Shift+Enter'); + await expect.poll(() => alpha.getAttribute('aria-pressed')).toBe('true'); await expect .poll(() => chart.locator('[data-legend-excluded]').count()) .toBe(3); - await page.keyboard.press('Shift+Enter'); + await page.keyboard.press('Enter'); await expect .poll(() => chart.locator('[data-legend-excluded]').count()) .toBe(0); @@ -173,20 +156,18 @@ test('automatic legend keeps long labels accessible without layout shift', async const alpha = legend.getByRole('button', { name: 'Alpha — response time in production workspaces across Europe', }); - await alpha.dblclick(); + await alpha.click(); await expect .poll(() => legend.locator('[data-legend-excluded]').count()) .toBeGreaterThan(0); expect((await chart.boundingBox())!.height).toBe(chartHeight); - await alpha.dblclick(); + await alpha.click(); await expect .poll(() => legend.locator('[data-legend-excluded]').count()) .toBe(0); }); -test('four series retain every legend cell during isolation', async ({ - page, -}) => { +test('four series exit focus when all are re-enabled', async ({ page }) => { await page.setViewportSize({ width: 915, height: 968 }); await page.goto('/chart-legends'); const chart = page.getByRole('region', { @@ -198,16 +179,28 @@ test('four series retain every legend cell during isolation', async ({ expect(await chart.getByRole('button', { name: 'Show all' }).count()).toBe(0); const height = (await chart.boundingBox())!.height; const alpha = legend.getByRole('button', { name: 'Alpha', exact: true }); - await alpha.dblclick(); + await alpha.click(); await expect .poll(() => legend.locator('[data-legend-excluded]').count()) .toBe(3); expect(await legend.getByRole('listitem').count()).toBe(4); expect((await chart.boundingBox())!.height).toBe(height); - await alpha.dblclick(); + for (const name of ['Beta', 'Gamma', 'Delta']) { + await legend.getByRole('button', { name, exact: true }).click(); + } await expect .poll(() => legend.locator('[data-legend-excluded]').count()) .toBe(0); + for (const name of ['Alpha', 'Beta', 'Gamma', 'Delta']) { + await expect + .poll(() => + legend + .getByRole('button', { name, exact: true }) + .getAttribute('aria-pressed') + ) + .toBe('false'); + } + expect((await chart.boundingBox())!.height).toBe(height); }); test('funnel and retention legends focus their plotted populations', async ({ @@ -230,7 +223,7 @@ test('funnel and retention legends focus their plotted populations', async ({ name: second, exact: name === 'RetentionChart', }); - await firstButton.dblclick(); + await firstButton.click(); await expect .poll(() => firstButton.getAttribute('aria-pressed')) .toBe('true'); @@ -245,14 +238,9 @@ test('funnel and retention legends focus their plotted populations', async ({ await expect .poll(() => chart.locator('[data-legend-excluded]').count()) .toBe(0); - await firstButton.dblclick(); - await expect - .poll(() => chart.locator('[data-legend-excluded]').count()) - .toBe(1); - await firstButton.dblclick(); await expect .poll(() => firstButton.getAttribute('aria-pressed')) - .toBe('true'); + .toBe('false'); } }); @@ -265,7 +253,7 @@ test('native function-key series respond to the automatic legend', async ({ exact: true, }); const alpha = chart.getByRole('button', { name: 'Alpha', exact: true }); - await alpha.dblclick(); + await alpha.click(); await expect.poll(() => alpha.getAttribute('aria-pressed')).toBe('true'); await expect .poll(() => @@ -281,7 +269,7 @@ test('native function-key series respond to the automatic legend', async ({ ) ) .toBe(1); - await alpha.dblclick(); + await alpha.click(); await expect .poll(() => chart.locator('[data-legend-excluded]').count()) .toBe(0); From 2e40b937d59fbf3a36dd53bae7c21000e1a70969 Mon Sep 17 00:00:00 2001 From: robinvrd Date: Tue, 10 Nov 2026 17:59:03 +0100 Subject: [PATCH 08/12] fix(charts): suppress plot tooltip during legend focus --- .../data-app-react/src/ui/ComposedChart.tsx | 3 +++ .../src/ui/chart-legend-interaction.tsx | 1 + .../data-app-react/src/ui/chart-primitives.tsx | 5 +++-- tests/public-api/apps-chart-legends.test.ts | 17 +++++++++++++++++ 4 files changed, 24 insertions(+), 2 deletions(-) diff --git a/packages/data-app-react/src/ui/ComposedChart.tsx b/packages/data-app-react/src/ui/ComposedChart.tsx index 677e061f..15f5c298 100644 --- a/packages/data-app-react/src/ui/ComposedChart.tsx +++ b/packages/data-app-react/src/ui/ComposedChart.tsx @@ -163,6 +163,9 @@ function applyNativeLegendInteraction( ...(excluded && (child.type === NativeLine || child.type === NativeArea) ? { dot: false, activeDot: false } : {}), + ...(hoveredKey && (child.type === NativeLine || child.type === NativeArea) + ? { activeDot: false } + : {}), }); }); } diff --git a/packages/data-app-react/src/ui/chart-legend-interaction.tsx b/packages/data-app-react/src/ui/chart-legend-interaction.tsx index 34b872f6..45558c99 100644 --- a/packages/data-app-react/src/ui/chart-legend-interaction.tsx +++ b/packages/data-app-react/src/ui/chart-legend-interaction.tsx @@ -35,6 +35,7 @@ export function useChartLegendSeries(id: unknown, dataKey: unknown) { const interaction = useContext(ChartLegendInteractionContext); const key = chartLegendSeriesKey(id, dataKey); return { + inspectingLegend: !!interaction?.hoveredKey, hidden: !!( key && interaction?.focusedKeys && diff --git a/packages/data-app-react/src/ui/chart-primitives.tsx b/packages/data-app-react/src/ui/chart-primitives.tsx index 7ca90668..f5b837c4 100644 --- a/packages/data-app-react/src/ui/chart-primitives.tsx +++ b/packages/data-app-react/src/ui/chart-primitives.tsx @@ -124,7 +124,7 @@ export function ChartLine({ : dot } activeDot={ - legend.hidden + legend.hidden || legend.inspectingLegend ? false : activeDot === undefined || activeDot === true ? ({ cx, cy }) => ( @@ -178,7 +178,7 @@ export function ChartArea({ : dot } activeDot={ - legend.hidden + legend.hidden || legend.inspectingLegend ? false : activeDot === undefined || activeDot === true ? ({ cx, cy }) => ( @@ -354,6 +354,7 @@ export function ChartTooltip(props: ComponentProps) { content={content => ( { await expect.poll(() => dots.count()).toBe(4); }); +test('first legend click does not activate a plot tooltip', async ({ + page, +}) => { + await page.goto('/chart-legends'); + const chart = page.getByRole('region', { + name: 'Response time across twelve services', + exact: true, + }); + const api = chart.getByRole('button', { name: 'API', exact: true }); + await api.click(); + await expect.poll(() => api.getAttribute('aria-pressed')).toBe('true'); + await expect.poll(() => chart.getByRole('tooltip').count()).toBe(0); + await expect + .poll(() => chart.locator('.recharts-active-dot').count()) + .toBe(0); +}); + test('legend keyboard controls focus and restore series', async ({ page }) => { await page.goto('/chart-legends'); const chart = page.getByRole('region', { From d73b8660e4dcaec1d9c4e4557da4a58db699cac3 Mon Sep 17 00:00:00 2001 From: robinvrd Date: Tue, 10 Nov 2026 18:25:20 +0100 Subject: [PATCH 09/12] fix(charts): reconcile legend focus and plot inspection --- .../data-app-react/src/ui/ComposedChart.tsx | 28 +++++- .../src/ui/ComposedChartLegend.tsx | 10 ++- .../src/ui/chart-legend-interaction.tsx | 26 ++++-- .../src/ui/chart-primitives.tsx | 58 +++++++----- tests/public-api/apps-chart-legends.test.ts | 90 +++++++++++++++++++ tests/public-api/fixtures/chart-legends.tsx | 69 ++++++++++++++ 6 files changed, 246 insertions(+), 35 deletions(-) diff --git a/packages/data-app-react/src/ui/ComposedChart.tsx b/packages/data-app-react/src/ui/ComposedChart.tsx index 15f5c298..92e2b100 100644 --- a/packages/data-app-react/src/ui/ComposedChart.tsx +++ b/packages/data-app-react/src/ui/ComposedChart.tsx @@ -40,6 +40,7 @@ import { import { ChartLegendInteractionContext, chartLegendSeriesKey, + reconcileLegendFocus, toggleLegendFocus, } from './chart-legend-interaction.tsx'; import { @@ -109,6 +110,7 @@ function applyNativeLegendInteraction( children: ReactNode, focusedKeys: ReadonlySet | null, hoveredKey: string | null, + suppressPlotInspection: boolean, path = 'root' ): ReactNode { return Children.map(children, (child, index) => { @@ -120,6 +122,7 @@ function applyNativeLegendInteraction( props.children, focusedKeys, hoveredKey, + suppressPlotInspection, `${path}-${child.key ?? index}` ), } as { children: ReactNode }); @@ -163,7 +166,8 @@ function applyNativeLegendInteraction( ...(excluded && (child.type === NativeLine || child.type === NativeArea) ? { dot: false, activeDot: false } : {}), - ...(hoveredKey && (child.type === NativeLine || child.type === NativeArea) + ...(suppressPlotInspection && + (child.type === NativeLine || child.type === NativeArea) ? { activeDot: false } : {}), }); @@ -227,6 +231,7 @@ function ComposedChartRoot({ resetPointerInspection(); return false; } + setSuppressPlotInspection(false); setIsPointerInspection(true); // Direct-hit series do not need pointer coordinates to select a sample. if (hoveredSeriesId != null && !points.has(hoveredSeriesId)) { @@ -276,10 +281,15 @@ function ComposedChartRoot({ }; }, []); const [legendHoveredKey, setLegendHoveredKey] = useState(null); + const [suppressPlotInspection, setSuppressPlotInspection] = useState(false); const [focusedLegendKeys, setFocusedLegendKeys] = useState | null>(null); + const reconcileLegendKeys = useCallback((keys: readonly string[]) => { + setFocusedLegendKeys(current => reconcileLegendFocus(current, keys)); + }, []); const toggleLegendKey = useCallback( (key: string, keys: readonly string[]) => { + setSuppressPlotInspection(true); setFocusedLegendKeys(current => toggleLegendFocus(current, key, keys)); }, [] @@ -290,8 +300,13 @@ function ComposedChartRoot({ value={{ hoveredKey: legendHoveredKey, focusedKeys: focusedLegendKeys, - hover: setLegendHoveredKey, + suppressPlotInspection, + hover: key => { + setLegendHoveredKey(key); + if (key) setSuppressPlotInspection(true); + }, toggle: toggleLegendKey, + reconcile: reconcileLegendKeys, }} > ({ setHasPointerFocus(false); resetPointerInspection(); }} + onFocusCapture={event => { + const svg = event.currentTarget.querySelector( + 'svg[role="application"]' + ); + if (svg?.contains(event.target)) setSuppressPlotInspection(false); + }} onBlurCapture={event => { if (!event.currentTarget.contains(event.relatedTarget)) { setHasPointerFocus(false); @@ -348,7 +369,8 @@ function ComposedChartRoot({ {applyNativeLegendInteraction( children, focusedLegendKeys, - legendHoveredKey + legendHoveredKey, + suppressPlotInspection )} diff --git a/packages/data-app-react/src/ui/ComposedChartLegend.tsx b/packages/data-app-react/src/ui/ComposedChartLegend.tsx index 3d0c33fc..4750141f 100644 --- a/packages/data-app-react/src/ui/ComposedChartLegend.tsx +++ b/packages/data-app-react/src/ui/ComposedChartLegend.tsx @@ -1,5 +1,10 @@ import { KEY_SEPARATOR } from '@altertable/data-app/internal'; -import { useContext, useState, type ComponentProps } from 'react'; +import { + useContext, + useLayoutEffect, + useState, + type ComponentProps, +} from 'react'; import { Legend, type LegendPayload } from 'recharts'; import { @@ -93,6 +98,9 @@ function LegendContent({ const selectableKeys = itemKeys.filter( (_, index) => payload[index]?.type !== 'none' ); + useLayoutEffect(() => { + interaction?.reconcile(selectableKeys); + }); const canInteract = interactive && !onClick && diff --git a/packages/data-app-react/src/ui/chart-legend-interaction.tsx b/packages/data-app-react/src/ui/chart-legend-interaction.tsx index 45558c99..40755806 100644 --- a/packages/data-app-react/src/ui/chart-legend-interaction.tsx +++ b/packages/data-app-react/src/ui/chart-legend-interaction.tsx @@ -12,17 +12,31 @@ export function chartLegendSeriesKey(id: unknown, dataKey: unknown) { export type ChartLegendInteraction = { hoveredKey: string | null; focusedKeys: ReadonlySet | null; + suppressPlotInspection: boolean; hover: (key: string | null) => void; toggle: (key: string, keys: readonly string[]) => void; + reconcile: (keys: readonly string[]) => void; }; +export function reconcileLegendFocus( + focused: ReadonlySet | null, + keys: readonly string[] +) { + if (!focused) return null; + const available = new Set(keys); + const next = new Set([...focused].filter(key => available.has(key))); + if (next.size === 0 || next.size === available.size) return null; + return next.size === focused.size ? focused : next; +} + export function toggleLegendFocus( focused: ReadonlySet | null, key: string, keys: readonly string[] ) { - if (!focused) return new Set([key]); - const next = new Set(focused); + const current = reconcileLegendFocus(focused, keys); + if (!current) return new Set([key]); + const next = new Set(current); if (next.has(key)) next.delete(key); else next.add(key); return next.size === 0 || next.size === new Set(keys).size ? null : next; @@ -35,7 +49,7 @@ export function useChartLegendSeries(id: unknown, dataKey: unknown) { const interaction = useContext(ChartLegendInteractionContext); const key = chartLegendSeriesKey(id, dataKey); return { - inspectingLegend: !!interaction?.hoveredKey, + inspectingLegend: !!interaction?.suppressPlotInspection, hidden: !!( key && interaction?.focusedKeys && @@ -55,11 +69,7 @@ export function useChartLegendFocus(ids: readonly string[]) { const [hoveredId, setHoveredId] = useState(null); const [storedFocusedIds, setStoredFocusedIds] = useState | null>(null); - const available = new Set(ids); - const visibleIds = - storedFocusedIds && - new Set([...storedFocusedIds].filter(id => available.has(id))); - const focusedIds = visibleIds?.size ? visibleIds : null; + const focusedIds = reconcileLegendFocus(storedFocusedIds, ids); function toggle(id: string) { setStoredFocusedIds(current => toggleLegendFocus(current, id, ids)); } diff --git a/packages/data-app-react/src/ui/chart-primitives.tsx b/packages/data-app-react/src/ui/chart-primitives.tsx index f5b837c4..27ae9e6a 100644 --- a/packages/data-app-react/src/ui/chart-primitives.tsx +++ b/packages/data-app-react/src/ui/chart-primitives.tsx @@ -1,7 +1,13 @@ import { useDateAxisLabel, useDateAxisBar } from './chart-date-axis.tsx'; export { ChartXAxis } from './chart-date-axis.tsx'; import { formatMetric, formatNumber } from '@altertable/data-app/format'; -import { useContext, useLayoutEffect, type ComponentProps } from 'react'; +import { + cloneElement, + isValidElement, + useContext, + useLayoutEffect, + type ComponentProps, +} from 'react'; import { Area, Dot, @@ -14,6 +20,7 @@ import { CartesianGrid, Tooltip, DefaultTooltipContent, + type TooltipContentProps, type BarProps, type LineProps, type AreaProps, @@ -348,30 +355,10 @@ export function ChartTooltip(props: ComponentProps) { const dateLabel = useDateAxisLabel(props.axisId); const interaction = useContext(ChartInteractionContext); const legendInteraction = useContext(ChartLegendInteractionContext); + const { content: authoredContent, ...tooltipProps } = props; return ( ( - entry.graphicalItemId === interaction.activeSeriesId - ) - : content.payload - ).filter(entry => { - if (!legendInteraction?.focusedKeys) return true; - const key = chartLegendSeriesKey( - entry.graphicalItemId, - entry.dataKey - ); - return key == null || legendInteraction.focusedKeys.has(key); - })} - /> - )} position={ interaction?.isPointerInspection && interaction.activePoint ? { y: interaction.activePoint.y } @@ -379,7 +366,32 @@ export function ChartTooltip(props: ComponentProps) { } cursor={false} isAnimationActive={false} - {...props} + {...tooltipProps} + content={content => { + if (legendInteraction?.suppressPlotInspection) return null; + const payload = ( + interaction?.isPointerInspection && + interaction.seriesCount !== 1 && + props.shared !== true + ? content.payload.filter( + entry => entry.graphicalItemId === interaction.activeSeriesId + ) + : content.payload + ).filter(entry => { + if (!legendInteraction?.focusedKeys) return true; + const key = chartLegendSeriesKey( + entry.graphicalItemId, + entry.dataKey + ); + return key == null || legendInteraction.focusedKeys.has(key); + }); + const filtered: TooltipContentProps = { ...content, payload }; + if (typeof authoredContent === 'function') + return authoredContent(filtered); + if (isValidElement(authoredContent)) + return cloneElement(authoredContent, filtered); + return ; + }} /> ); } diff --git a/tests/public-api/apps-chart-legends.test.ts b/tests/public-api/apps-chart-legends.test.ts index 6707383f..0f405e10 100644 --- a/tests/public-api/apps-chart-legends.test.ts +++ b/tests/public-api/apps-chart-legends.test.ts @@ -127,6 +127,11 @@ test('first legend click does not activate a plot tooltip', async ({ await expect .poll(() => chart.locator('.recharts-active-dot').count()) .toBe(0); + await page.mouse.move(20, 20); + await expect.poll(() => chart.getByRole('tooltip').count()).toBe(0); + await expect + .poll(() => chart.locator('.recharts-active-dot').count()) + .toBe(0); }); test('legend keyboard controls focus and restore series', async ({ page }) => { @@ -220,6 +225,91 @@ test('four series exit focus when all are re-enabled', async ({ page }) => { expect((await chart.boundingBox())!.height).toBe(height); }); +test('removing a focused series reconciles focus with current series', async ({ + page, +}) => { + await page.goto('/chart-legends'); + const example = page.getByRole('region', { + name: 'Dynamic legend focus basic example', + exact: true, + }); + const chart = example.getByRole('region', { + name: 'Dynamic legend plot', + exact: true, + }); + await chart.getByRole('button', { name: 'Alpha', exact: true }).click(); + await expect + .poll(() => chart.locator('[data-legend-excluded]').count()) + .toBe(2); + await example.getByRole('button', { name: 'Remove Alpha series' }).click(); + await expect + .poll(() => chart.locator('[data-legend-excluded]').count()) + .toBe(0); + const beta = chart.getByRole('button', { name: 'Beta', exact: true }); + const gamma = chart.getByRole('button', { name: 'Gamma', exact: true }); + await beta.click(); + await expect + .poll(() => chart.locator('[data-legend-excluded]').count()) + .toBe(1); + await gamma.click(); + await expect + .poll(() => chart.locator('[data-legend-excluded]').count()) + .toBe(0); + await expect.poll(() => beta.getAttribute('aria-pressed')).toBe('false'); + await expect.poll(() => gamma.getAttribute('aria-pressed')).toBe('false'); +}); + +test('custom tooltip content receives only focused series', async ({ + page, +}) => { + await page.goto('/chart-legends'); + const chart = page.getByRole('region', { + name: 'Dynamic legend plot', + exact: true, + }); + await chart.getByRole('button', { name: 'Alpha', exact: true }).click(); + await expect.poll(() => chart.getByRole('tooltip').count()).toBe(0); + const plot = chart.getByRole('application'); + await plot.scrollIntoViewIfNeeded(); + const bounds = await plot.boundingBox(); + await page.mouse.move( + bounds!.x + bounds!.width / 2, + bounds!.y + bounds!.height / 2 + ); + const tooltip = chart.getByRole('tooltip'); + await expect.poll(() => tooltip.textContent()).toContain('Alpha'); + expect(await tooltip.textContent()).not.toContain('Beta'); + expect(await tooltip.textContent()).not.toContain('Gamma'); +}); + +test('funnel focus follows changing populations', async ({ page }) => { + await page.goto('/chart-legends'); + const example = page.getByRole('region', { + name: 'Dynamic funnel focus basic example', + exact: true, + }); + const chart = example.getByRole('region', { + name: 'Dynamic funnel plot', + exact: true, + }); + await chart.getByRole('button', { name: /Free plan/ }).click(); + await expect + .poll(() => chart.locator('[data-legend-excluded]').count()) + .toBe(2); + await example.getByRole('button', { name: 'Remove Free plan' }).click(); + await expect + .poll(() => chart.locator('[data-legend-excluded]').count()) + .toBe(0); + await chart.getByRole('button', { name: /Paid plan/ }).click(); + await expect + .poll(() => chart.locator('[data-legend-excluded]').count()) + .toBe(1); + await chart.getByRole('button', { name: /Enterprise plan/ }).click(); + await expect + .poll(() => chart.locator('[data-legend-excluded]').count()) + .toBe(0); +}); + test('funnel and retention legends focus their plotted populations', async ({ page, }) => { diff --git a/tests/public-api/fixtures/chart-legends.tsx b/tests/public-api/fixtures/chart-legends.tsx index 332f4a6e..87d98665 100644 --- a/tests/public-api/fixtures/chart-legends.tsx +++ b/tests/public-api/fixtures/chart-legends.tsx @@ -247,6 +247,63 @@ function LegendIdentityExample({ kind }: { kind: LegendKind }) { ); } +function DynamicLegendExample() { + const [showAlpha, setShowAlpha] = useState(true); + return ( + <> + + + + + + active && payload.length ? ( +
        + {payload.map(entry => String(entry.name)).join(', ')} +
        + ) : null + } + /> + {showAlpha && } + + + +
        + + ); +} + +function DynamicFunnelExample() { + const [showFree, setShowFree] = useState(true); + return ( + <> + + + + ); +} + // Keep large-series rendering cases out of the public gallery. createRoot(document.getElementById('root')!).render( @@ -611,6 +668,18 @@ createRoot(document.getElementById('root')!).render( + + + + + + Date: Thu, 12 Nov 2026 11:41:40 +0100 Subject: [PATCH 10/12] feat(charts): rescale value axes in legend focus mode --- .../data-app-react/src/ui/ComposedChart.tsx | 46 +++++++++- .../src/ui/chart-primitives.tsx | 4 + tests/public-api/apps-chart-legends.test.ts | 87 ++++++++++--------- tests/public-api/fixtures/chart-legends.tsx | 2 +- 4 files changed, 95 insertions(+), 44 deletions(-) diff --git a/packages/data-app-react/src/ui/ComposedChart.tsx b/packages/data-app-react/src/ui/ComposedChart.tsx index 92e2b100..6f10704a 100644 --- a/packages/data-app-react/src/ui/ComposedChart.tsx +++ b/packages/data-app-react/src/ui/ComposedChart.tsx @@ -26,6 +26,8 @@ import { Bar as NativeBar, Area as NativeArea, Scatter as NativeScatter, + XAxis as NativeXAxis, + YAxis as NativeYAxis, Label, LabelList, ErrorBar, @@ -111,6 +113,7 @@ function applyNativeLegendInteraction( focusedKeys: ReadonlySet | null, hoveredKey: string | null, suppressPlotInspection: boolean, + barAxisIds: ReadonlySet, path = 'root' ): ReactNode { return Children.map(children, (child, index) => { @@ -123,10 +126,31 @@ function applyNativeLegendInteraction( focusedKeys, hoveredKey, suppressPlotInspection, + barAxisIds, `${path}-${child.key ?? index}` ), } as { children: ReactNode }); } + if (child.type === XAxis || child.type === NativeXAxis) { + const axis = child as ReactElement<{ includeHidden?: boolean }>; + return cloneElement(axis, { + includeHidden: axis.props.includeHidden ?? true, + }); + } + if (child.type === YAxis || child.type === NativeYAxis) { + const axis = child as ReactElement<{ + yAxisId?: string | number; + domain?: unknown; + ticks?: unknown; + }>; + if (!focusedKeys || axis.props.domain != null || axis.props.ticks != null) + return child; + return cloneElement(axis, { + domain: barAxisIds.has(axis.props.yAxisId ?? 0) + ? [0, 'auto'] + : ['auto', 'auto'], + }); + } if ( child.type !== NativeLine && child.type !== NativeBar && @@ -152,6 +176,7 @@ function applyNativeLegendInteraction( const excluded = !!(focusedKeys && !focusedKeys.has(key)); return cloneElement(series, { id, + hide: excluded || series.props.hide, opacity: excluded ? 0 : hoveredKey && @@ -174,6 +199,24 @@ function applyNativeLegendInteraction( }); } +function collectBarAxisIds( + children: ReactNode, + ids = new Set() +) { + Children.forEach(children, child => { + if (!isValidElement(child)) return; + if (child.type === Fragment) { + collectBarAxisIds( + (child.props as { children?: ReactNode }).children, + ids + ); + } else if (child.type === Bar || child.type === NativeBar) { + ids.add((child.props as { yAxisId?: string | number }).yAxisId ?? 0); + } + }); + return ids; +} + /** Compose Cartesian series inside VisualizationWidget. Defaults to responsive * full width and 300px height. Children retain native Recharts props and behavior, * including stacking, numeric/time axes, missing values, tooltips, and keyboard @@ -370,7 +413,8 @@ function ComposedChartRoot({ children, focusedLegendKeys, legendHoveredKey, - suppressPlotInspection + suppressPlotInspection, + collectBarAxisIds(children) )} diff --git a/packages/data-app-react/src/ui/chart-primitives.tsx b/packages/data-app-react/src/ui/chart-primitives.tsx index 27ae9e6a..b6f7b2bc 100644 --- a/packages/data-app-react/src/ui/chart-primitives.tsx +++ b/packages/data-app-react/src/ui/chart-primitives.tsx @@ -95,6 +95,7 @@ export function ChartBar( isAnimationActive={false} {...props} id={series.id} + hide={legend.hidden || props.hide} opacity={legend.hidden ? 0 : legend.dimmed ? 0.2 : props.opacity} style={{ ...props.style, @@ -147,6 +148,7 @@ export function ChartLine({ isAnimationActive={false} {...props} id={series.id} + hide={legend.hidden || props.hide} opacity={legend.hidden ? 0 : legend.dimmed ? 0.2 : props.opacity} style={{ ...props.style, @@ -201,6 +203,7 @@ export function ChartArea({ isAnimationActive={false} {...props} id={series.id} + hide={legend.hidden || props.hide} opacity={legend.hidden ? 0 : legend.dimmed ? 0.2 : props.opacity} style={{ ...props.style, @@ -223,6 +226,7 @@ export function ChartScatter( isAnimationActive={false} {...props} id={series.id} + hide={legend.hidden || props.hide} opacity={legend.hidden ? 0 : legend.dimmed ? 0.2 : props.opacity} style={{ ...props.style, diff --git a/tests/public-api/apps-chart-legends.test.ts b/tests/public-api/apps-chart-legends.test.ts index 0f405e10..464f4912 100644 --- a/tests/public-api/apps-chart-legends.test.ts +++ b/tests/public-api/apps-chart-legends.test.ts @@ -43,18 +43,7 @@ test('automatic legend previews, focuses, and adds series', async ({ await expect .poll(async () => legend.locator('[data-legend-excluded]').count()) .toBe((await legend.locator('button[aria-pressed]').count()) - 1); - await expect - .poll(() => - curves.evaluateAll( - paths => - paths.filter( - path => - path.getAttribute('opacity') === '0' || - path.closest('.recharts-line')?.getAttribute('opacity') === '0' - ).length - ) - ) - .toBe(11); + await expect.poll(() => curves.count()).toBe(1); await expect.poll(() => api.getAttribute('aria-pressed')).toBe('true'); await analytics.hover(); await expect @@ -76,18 +65,7 @@ test('automatic legend previews, focuses, and adds series', async ({ await expect .poll(async () => legend.locator('[data-legend-excluded]').count()) .toBe((await legend.locator('button[aria-pressed]').count()) - 2); - await expect - .poll(() => - curves.evaluateAll( - paths => - paths.filter( - path => - path.getAttribute('opacity') === '0' || - path.closest('.recharts-line')?.getAttribute('opacity') === '0' - ).length - ) - ) - .toBe(10); + await expect.poll(() => curves.count()).toBe(2); await api.click(); await analytics.click(); expect((await chart.boundingBox())!.height).toBe(chartHeight); @@ -112,6 +90,41 @@ test('focus removes dots from excluded line series', async ({ page }) => { await expect.poll(() => dots.count()).toBe(4); }); +test('focus rescales the value axis while preserving category positions', async ({ + page, +}) => { + await page.goto('/chart-legends'); + const chart = page.getByRole('region', { + name: 'Response time across twelve services', + exact: true, + }); + const yTicks = chart.locator('svg text').filter({ hasText: /ms$/ }); + const xTicks = chart.locator('svg text').filter({ + hasText: /^(Mon|Tue|Wed|Thu|Fri|Sat|Sun)$/, + }); + const fullY = await yTicks.allTextContents(); + const fullX = await xTicks.evaluateAll(elements => + elements.map(element => ({ + text: element.textContent, + x: element.getBoundingClientRect().x, + })) + ); + await chart.getByRole('button', { name: 'API', exact: true }).click(); + await expect.poll(() => yTicks.allTextContents()).not.toEqual(fullY); + const focusedY = await yTicks.allTextContents(); + expect(focusedY.some(tick => tick.startsWith('0'))).toBe(false); + expect( + await xTicks.evaluateAll(elements => + elements.map(element => ({ + text: element.textContent, + x: element.getBoundingClientRect().x, + })) + ) + ).toEqual(fullX); + await chart.getByRole('button', { name: 'API', exact: true }).click(); + await expect.poll(() => yTicks.allTextContents()).toEqual(fullY); +}); + test('first legend click does not activate a plot tooltip', async ({ page, }) => { @@ -197,6 +210,10 @@ test('four series exit focus when all are re-enabled', async ({ page }) => { exact: true, }); const legend = chart.getByRole('list', { name: 'Chart legend' }); + const yTicks = chart + .locator('svg text') + .filter({ hasText: /^(0|10|20|30|40|50)$/ }); + const fullY = await yTicks.allTextContents(); await expect.poll(() => legend.getByRole('listitem').count()).toBe(4); expect(await chart.getByRole('button', { name: 'Show all' }).count()).toBe(0); const height = (await chart.boundingBox())!.height; @@ -205,6 +222,7 @@ test('four series exit focus when all are re-enabled', async ({ page }) => { await expect .poll(() => legend.locator('[data-legend-excluded]').count()) .toBe(3); + expect(await yTicks.allTextContents()).toEqual(fullY); expect(await legend.getByRole('listitem').count()).toBe(4); expect((await chart.boundingBox())!.height).toBe(height); for (const name of ['Beta', 'Gamma', 'Delta']) { @@ -270,12 +288,8 @@ test('custom tooltip content receives only focused series', async ({ await chart.getByRole('button', { name: 'Alpha', exact: true }).click(); await expect.poll(() => chart.getByRole('tooltip').count()).toBe(0); const plot = chart.getByRole('application'); - await plot.scrollIntoViewIfNeeded(); - const bounds = await plot.boundingBox(); - await page.mouse.move( - bounds!.x + bounds!.width / 2, - bounds!.y + bounds!.height / 2 - ); + await plot.focus(); + await page.keyboard.press('ArrowRight'); const tooltip = chart.getByRole('tooltip'); await expect.poll(() => tooltip.textContent()).toContain('Alpha'); expect(await tooltip.textContent()).not.toContain('Beta'); @@ -363,18 +377,7 @@ test('native function-key series respond to the automatic legend', async ({ await alpha.click(); await expect.poll(() => alpha.getAttribute('aria-pressed')).toBe('true'); await expect - .poll(() => - chart - .locator('.recharts-line-curve') - .evaluateAll( - paths => - paths.filter( - path => - path.getAttribute('opacity') === '0' || - path.closest('.recharts-line')?.getAttribute('opacity') === '0' - ).length - ) - ) + .poll(() => chart.locator('.recharts-line-curve').count()) .toBe(1); await alpha.click(); await expect diff --git a/tests/public-api/fixtures/chart-legends.tsx b/tests/public-api/fixtures/chart-legends.tsx index 87d98665..41cca230 100644 --- a/tests/public-api/fixtures/chart-legends.tsx +++ b/tests/public-api/fixtures/chart-legends.tsx @@ -660,7 +660,7 @@ createRoot(document.getElementById('root')!).render( ariaLabel="Four series plot" > - + From 50c0f313f243e9fe7427d7c6574341dbb32086e8 Mon Sep 17 00:00:00 2001 From: robinvrd Date: Thu, 12 Nov 2026 12:22:02 +0100 Subject: [PATCH 11/12] fix(charts): scale focused axes from visible series --- .../data-app-react/src/ui/ComposedChart.tsx | 205 +++++++++++++++++- .../src/ui/chart-legend-interaction.tsx | 1 + .../src/ui/chart-primitives.tsx | 11 + tests/public-api/apps-chart-legends.test.ts | 91 ++++++++ tests/public-api/fixtures/chart-legends.tsx | 39 ++++ 5 files changed, 336 insertions(+), 11 deletions(-) diff --git a/packages/data-app-react/src/ui/ComposedChart.tsx b/packages/data-app-react/src/ui/ComposedChart.tsx index 6f10704a..f389f959 100644 --- a/packages/data-app-react/src/ui/ComposedChart.tsx +++ b/packages/data-app-react/src/ui/ComposedChart.tsx @@ -7,6 +7,7 @@ import { useState, useCallback, useEffect, + useLayoutEffect, useRef, type PointerEvent, type ComponentProps, @@ -28,6 +29,9 @@ import { Scatter as NativeScatter, XAxis as NativeXAxis, YAxis as NativeYAxis, + Legend as NativeLegend, + useOffset, + useMargin, Label, LabelList, ErrorBar, @@ -113,7 +117,10 @@ function applyNativeLegendInteraction( focusedKeys: ReadonlySet | null, hoveredKey: string | null, suppressPlotInspection: boolean, - barAxisIds: ReadonlySet, + valueAxis: 'x' | 'y', + visibleBarAxisIds: ReadonlySet, + fullAxisSpace: { left: number; right: number } | null, + yAxisSideCounts: { left: number; right: number }, path = 'root' ): ReactNode { return Children.map(children, (child, index) => { @@ -126,29 +133,60 @@ function applyNativeLegendInteraction( focusedKeys, hoveredKey, suppressPlotInspection, - barAxisIds, + valueAxis, + visibleBarAxisIds, + fullAxisSpace, + yAxisSideCounts, `${path}-${child.key ?? index}` ), } as { children: ReactNode }); } if (child.type === XAxis || child.type === NativeXAxis) { - const axis = child as ReactElement<{ includeHidden?: boolean }>; + const axis = child as ReactElement<{ + xAxisId?: string | number; + includeHidden?: boolean; + domain?: unknown; + ticks?: unknown; + }>; + if (valueAxis === 'y') + return cloneElement(axis, { + includeHidden: axis.props.includeHidden ?? true, + }); + if (!focusedKeys || axis.props.domain != null || axis.props.ticks != null) + return child; return cloneElement(axis, { - includeHidden: axis.props.includeHidden ?? true, + domain: visibleBarAxisIds.has(axis.props.xAxisId ?? 0) + ? [0, 'auto'] + : ['auto', 'auto'], }); } if (child.type === YAxis || child.type === NativeYAxis) { const axis = child as ReactElement<{ yAxisId?: string | number; + includeHidden?: boolean; domain?: unknown; ticks?: unknown; + width?: number | 'auto'; + orientation?: 'left' | 'right'; }>; + if (valueAxis === 'x') + return cloneElement(axis, { + includeHidden: axis.props.includeHidden ?? true, + }); if (!focusedKeys || axis.props.domain != null || axis.props.ticks != null) return child; + const side = axis.props.orientation ?? 'left'; + const reservedWidth = + (axis.props.width === 'auto' || + (child.type === YAxis && axis.props.width == null)) && + yAxisSideCounts[side] === 1 + ? fullAxisSpace?.[side] + : undefined; return cloneElement(axis, { - domain: barAxisIds.has(axis.props.yAxisId ?? 0) + domain: visibleBarAxisIds.has(axis.props.yAxisId ?? 0) ? [0, 'auto'] : ['auto', 'auto'], + ...(reservedWidth != null && { width: reservedWidth }), }); } if ( @@ -199,24 +237,113 @@ function applyNativeLegendInteraction( }); } -function collectBarAxisIds( +function collectVisibleNativeBarAxisIds( children: ReactNode, + focusedKeys: ReadonlySet | null, + valueAxis: 'x' | 'y', + path = 'root', ids = new Set() ) { - Children.forEach(children, child => { + Children.forEach(children, (child, index) => { if (!isValidElement(child)) return; if (child.type === Fragment) { - collectBarAxisIds( + collectVisibleNativeBarAxisIds( (child.props as { children?: ReactNode }).children, + focusedKeys, + valueAxis, + `${path}-${child.key ?? index}`, ids ); - } else if (child.type === Bar || child.type === NativeBar) { - ids.add((child.props as { yAxisId?: string | number }).yAxisId ?? 0); + } else if (child.type === NativeBar) { + const props = child.props as { + id?: string; + dataKey?: unknown; + hide?: boolean; + xAxisId?: string | number; + yAxisId?: string | number; + }; + const id = + props.id ?? + (chartLegendSeriesKey(undefined, props.dataKey) == null + ? `atbl-native-${path}-${child.key ?? index}` + : undefined); + const key = chartLegendSeriesKey(id, props.dataKey)!; + if (!props.hide && (!focusedKeys || focusedKeys.has(key))) { + ids.add( + valueAxis === 'x' ? (props.xAxisId ?? 0) : (props.yAxisId ?? 0) + ); + } } }); return ids; } +function inspectAxisLayout( + children: ReactNode, + layout = { left: 0, right: 0, autoYAxis: false, interactiveLegend: false } +) { + Children.forEach(children, child => { + if (!isValidElement(child)) return; + if (child.type === Fragment) { + inspectAxisLayout( + (child.props as { children?: ReactNode }).children, + layout + ); + } else if (child.type === YAxis || child.type === NativeYAxis) { + const props = child.props as { + hide?: boolean; + mirror?: boolean; + orientation?: 'left' | 'right'; + width?: number | 'auto'; + }; + if (!props.hide && !props.mirror) { + layout[props.orientation ?? 'left']++; + if ( + props.width === 'auto' || + (child.type === YAxis && props.width == null) + ) + layout.autoYAxis = true; + } + } else if (child.type === Legend || child.type === NativeLegend) { + const props = child.props as { + position?: string; + align?: string; + layout?: string; + interactive?: boolean; + }; + if (child.type === Legend && props.interactive !== false) + layout.interactiveLegend = true; + const side = + props.position === 'left' || props.position === 'right' + ? props.position + : props.layout === 'vertical' && + (props.align === 'left' || props.align === 'right') + ? props.align + : null; + if (side) layout[side]++; + } + }); + return layout; +} + +function PlotOffsets({ + onChange, +}: { + onChange: (left: number, right: number) => void; +}) { + const offset = useOffset(); + const margin = useMargin(); + const left = offset?.left; + const right = offset?.right; + const marginLeft = margin?.left ?? 5; + const marginRight = margin?.right ?? 5; + useLayoutEffect(() => { + if (left != null && right != null) + onChange(left - marginLeft, right - marginRight); + }, [left, right, marginLeft, marginRight, onChange]); + return null; +} + /** Compose Cartesian series inside VisualizationWidget. Defaults to responsive * full width and 300px height. Children retain native Recharts props and behavior, * including stacking, numeric/time axes, missing values, tooltips, and keyboard @@ -234,6 +361,7 @@ function ComposedChartRoot({ width = '100%', height = 300, responsive = true, + layout = 'horizontal', className, ...props }: ComposedChartProps) { @@ -327,6 +455,51 @@ function ComposedChartRoot({ const [suppressPlotInspection, setSuppressPlotInspection] = useState(false); const [focusedLegendKeys, setFocusedLegendKeys] = useState | null>(null); + const [barAxisByKey, setBarAxisByKey] = useState< + ReadonlyMap + >(() => new Map()); + const registerBarAxis = useCallback( + (key: string, axisId: string | number) => { + setBarAxisByKey(current => { + if (current.get(key) === axisId) return current; + return new Map(current).set(key, axisId); + }); + return () => + setBarAxisByKey(current => { + if (current.get(key) !== axisId) return current; + const next = new Map(current); + next.delete(key); + return next; + }); + }, + [] + ); + const valueAxis = layout === 'vertical' ? 'x' : 'y'; + const [fullAxisSpace, setFullAxisSpace] = useState<{ + left: number; + right: number; + } | null>(null); + const trackPlotOffsets = useCallback( + (left: number, right: number) => { + if (focusedLegendKeys) return; + setFullAxisSpace(current => + current?.left === left && current.right === right + ? current + : { left, right } + ); + }, + [focusedLegendKeys] + ); + const axisLayout = inspectAxisLayout(children); + const visibleBarAxisIds = collectVisibleNativeBarAxisIds( + children, + focusedLegendKeys, + valueAxis + ); + for (const [key, axisId] of barAxisByKey) { + if (!focusedLegendKeys || focusedLegendKeys.has(key)) + visibleBarAxisIds.add(axisId); + } const reconcileLegendKeys = useCallback((keys: readonly string[]) => { setFocusedLegendKeys(current => reconcileLegendFocus(current, keys)); }, []); @@ -350,6 +523,7 @@ function ComposedChartRoot({ }, toggle: toggleLegendKey, reconcile: reconcileLegendKeys, + registerBarAxis, }} > ({ width={width} height={height} responsive={responsive} + layout={layout} aria-label={ariaLabel} > + {valueAxis === 'y' && + axisLayout.autoYAxis && + axisLayout.interactiveLegend && ( + + )} {horizontalGrid && !hasAuthoredGrid(children) && ( )} @@ -414,7 +594,10 @@ function ComposedChartRoot({ focusedLegendKeys, legendHoveredKey, suppressPlotInspection, - collectBarAxisIds(children) + valueAxis, + visibleBarAxisIds, + fullAxisSpace, + axisLayout )} diff --git a/packages/data-app-react/src/ui/chart-legend-interaction.tsx b/packages/data-app-react/src/ui/chart-legend-interaction.tsx index 40755806..1792d2f7 100644 --- a/packages/data-app-react/src/ui/chart-legend-interaction.tsx +++ b/packages/data-app-react/src/ui/chart-legend-interaction.tsx @@ -16,6 +16,7 @@ export type ChartLegendInteraction = { hover: (key: string | null) => void; toggle: (key: string, keys: readonly string[]) => void; reconcile: (keys: readonly string[]) => void; + registerBarAxis: (key: string, axisId: string | number) => () => void; }; export function reconcileLegendFocus( diff --git a/packages/data-app-react/src/ui/chart-primitives.tsx b/packages/data-app-react/src/ui/chart-primitives.tsx index b6f7b2bc..ec6f6132 100644 --- a/packages/data-app-react/src/ui/chart-primitives.tsx +++ b/packages/data-app-react/src/ui/chart-primitives.tsx @@ -17,6 +17,7 @@ import { Scatter, YAxis, useYAxisTicks, + useCartesianChartLayout, CartesianGrid, Tooltip, DefaultTooltipContent, @@ -85,6 +86,16 @@ export function ChartBar( useDateAxisBar(props.xAxisId); const series = useChartSeries(props.id); const legend = useChartLegendSeries(series.id, props.dataKey); + const interaction = useContext(ChartLegendInteractionContext); + const layout = useCartesianChartLayout(); + const registerBarAxis = interaction?.registerBarAxis; + const key = chartLegendSeriesKey(series.id, props.dataKey); + const axisId = + layout === 'vertical' ? (props.xAxisId ?? 0) : (props.yAxisId ?? 0); + useLayoutEffect( + () => (key && !props.hide ? registerBarAxis?.(key, axisId) : undefined), + [registerBarAxis, key, axisId, props.hide] + ); return ( diff --git a/tests/public-api/apps-chart-legends.test.ts b/tests/public-api/apps-chart-legends.test.ts index 464f4912..effd17f0 100644 --- a/tests/public-api/apps-chart-legends.test.ts +++ b/tests/public-api/apps-chart-legends.test.ts @@ -125,6 +125,97 @@ test('focus rescales the value axis while preserving category positions', async await expect.poll(() => yTicks.allTextContents()).toEqual(fullY); }); +test('mixed charts use a zero baseline only while a bar is visible', async ({ + page, +}) => { + await page.goto('/chart-legends'); + const chart = page.getByRole('region', { + name: 'Mixed value-axis plot', + exact: true, + }); + const ticks = chart.locator('.recharts-yAxis-tick-labels text'); + const forecast = chart.getByRole('button', { name: 'Forecast', exact: true }); + const revenue = chart.getByRole('button', { name: 'Revenue', exact: true }); + expect((await ticks.allTextContents()).some(tick => tick === '0k')).toBe( + true + ); + await forecast.click(); + await expect + .poll(async () => { + const values = await ticks.allTextContents(); + return ( + values.length > 0 && values.every(value => Number.parseFloat(value) > 0) + ); + }) + .toBe(true); + await revenue.click(); + await expect.poll(() => ticks.allTextContents()).toContain('0k'); +}); + +test('horizontal bars rescale X and retain category positions', async ({ + page, +}) => { + await page.goto('/chart-legends'); + const chart = page.getByRole('region', { + name: 'Horizontal value-axis plot', + exact: true, + }); + const xTicks = chart.locator('.recharts-xAxis-tick-labels text'); + const yTicks = chart.locator('.recharts-yAxis-tick-labels text'); + const categories = await yTicks.evaluateAll(elements => + elements.map(element => ({ + text: element.textContent, + y: Math.round( + element.getBoundingClientRect().y - + element.closest('svg')!.getBoundingClientRect().y + ), + })) + ); + expect( + Math.max(...(await xTicks.allTextContents()).map(Number.parseFloat)) + ).toBeGreaterThan(200); + await chart.getByRole('button', { name: 'Small', exact: true }).click(); + await expect + .poll(async () => + Math.max(...(await xTicks.allTextContents()).map(Number.parseFloat)) + ) + .toBeLessThan(100); + expect(await xTicks.allTextContents()).toContain('0ms'); + expect( + await yTicks.evaluateAll(elements => + elements.map(element => ({ + text: element.textContent, + y: Math.round( + element.getBoundingClientRect().y - + element.closest('svg')!.getBoundingClientRect().y + ), + })) + ) + ).toEqual(categories); +}); + +test('focus keeps category coordinates with an auto-width value axis', async ({ + page, +}) => { + await page.goto('/chart-legends'); + const chart = page.getByRole('region', { + name: 'Dynamic legend plot', + exact: true, + }); + const ticks = chart.locator('.recharts-xAxis-tick-labels text'); + const positions = await ticks.evaluateAll(elements => + elements.map(element => element.getBoundingClientRect().x) + ); + await chart.getByRole('button', { name: 'Alpha', exact: true }).click(); + await expect + .poll(() => + ticks.evaluateAll(elements => + elements.map(element => element.getBoundingClientRect().x) + ) + ) + .toEqual(positions); +}); + test('first legend click does not activate a plot tooltip', async ({ page, }) => { diff --git a/tests/public-api/fixtures/chart-legends.tsx b/tests/public-api/fixtures/chart-legends.tsx index 41cca230..9f1e258e 100644 --- a/tests/public-api/fixtures/chart-legends.tsx +++ b/tests/public-api/fixtures/chart-legends.tsx @@ -668,6 +668,45 @@ createRoot(document.getElementById('root')!).render( + + + + + + + + + + + + + + + + + + Date: Thu, 12 Nov 2026 13:13:57 +0100 Subject: [PATCH 12/12] fix(charts): focus native series sharing data keys --- .../data-app-react/src/ui/ComposedChart.tsx | 62 +++++++++++++++---- .../src/ui/ComposedChartLegend.tsx | 1 - tests/public-api/apps-chart-legends.test.ts | 22 +++++++ tests/public-api/fixtures/chart-legends.tsx | 15 +++++ 4 files changed, 87 insertions(+), 13 deletions(-) diff --git a/packages/data-app-react/src/ui/ComposedChart.tsx b/packages/data-app-react/src/ui/ComposedChart.tsx index f389f959..ecc3ea72 100644 --- a/packages/data-app-react/src/ui/ComposedChart.tsx +++ b/packages/data-app-react/src/ui/ComposedChart.tsx @@ -112,6 +112,45 @@ function hasAuthoredGrid(children: ReactNode): boolean { ); } +function countNativeSeriesKeys( + children: ReactNode, + counts = new Map() +) { + Children.forEach(children, child => { + if (!isValidElement(child)) return; + if (child.type === Fragment) { + countNativeSeriesKeys( + (child.props as { children?: ReactNode }).children, + counts + ); + } else if ( + child.type === NativeLine || + child.type === NativeBar || + child.type === NativeArea || + child.type === NativeScatter + ) { + const props = child.props as { id?: string; dataKey?: unknown }; + const key = chartLegendSeriesKey(props.id, props.dataKey); + if (key) counts.set(key, (counts.get(key) ?? 0) + 1); + } + }); + return counts; +} + +function nativeSeriesId( + props: { id?: string; dataKey?: unknown }, + child: ReactElement, + index: number, + path: string, + keyCounts: ReadonlyMap +) { + if (props.id != null) return props.id; + const key = chartLegendSeriesKey(undefined, props.dataKey); + return !key || (keyCounts.get(key) ?? 0) > 1 + ? `atbl-native-${path}-${child.key ?? index}` + : undefined; +} + function applyNativeLegendInteraction( children: ReactNode, focusedKeys: ReadonlySet | null, @@ -121,6 +160,7 @@ function applyNativeLegendInteraction( visibleBarAxisIds: ReadonlySet, fullAxisSpace: { left: number; right: number } | null, yAxisSideCounts: { left: number; right: number }, + keyCounts: ReadonlyMap, path = 'root' ): ReactNode { return Children.map(children, (child, index) => { @@ -137,6 +177,7 @@ function applyNativeLegendInteraction( visibleBarAxisIds, fullAxisSpace, yAxisSideCounts, + keyCounts, `${path}-${child.key ?? index}` ), } as { children: ReactNode }); @@ -205,11 +246,7 @@ function applyNativeLegendInteraction( dot?: unknown; activeDot?: unknown; }>; - const id = - series.props.id ?? - (chartLegendSeriesKey(undefined, series.props.dataKey) == null - ? `atbl-native-${path}-${child.key ?? index}` - : undefined); + const id = nativeSeriesId(series.props, child, index, path, keyCounts); const key = chartLegendSeriesKey(id, series.props.dataKey)!; const excluded = !!(focusedKeys && !focusedKeys.has(key)); return cloneElement(series, { @@ -241,6 +278,7 @@ function collectVisibleNativeBarAxisIds( children: ReactNode, focusedKeys: ReadonlySet | null, valueAxis: 'x' | 'y', + keyCounts: ReadonlyMap, path = 'root', ids = new Set() ) { @@ -251,6 +289,7 @@ function collectVisibleNativeBarAxisIds( (child.props as { children?: ReactNode }).children, focusedKeys, valueAxis, + keyCounts, `${path}-${child.key ?? index}`, ids ); @@ -262,11 +301,7 @@ function collectVisibleNativeBarAxisIds( xAxisId?: string | number; yAxisId?: string | number; }; - const id = - props.id ?? - (chartLegendSeriesKey(undefined, props.dataKey) == null - ? `atbl-native-${path}-${child.key ?? index}` - : undefined); + const id = nativeSeriesId(props, child, index, path, keyCounts); const key = chartLegendSeriesKey(id, props.dataKey)!; if (!props.hide && (!focusedKeys || focusedKeys.has(key))) { ids.add( @@ -491,10 +526,12 @@ function ComposedChartRoot({ [focusedLegendKeys] ); const axisLayout = inspectAxisLayout(children); + const nativeKeyCounts = countNativeSeriesKeys(children); const visibleBarAxisIds = collectVisibleNativeBarAxisIds( children, focusedLegendKeys, - valueAxis + valueAxis, + nativeKeyCounts ); for (const [key, axisId] of barAxisByKey) { if (!focusedLegendKeys || focusedLegendKeys.has(key)) @@ -597,7 +634,8 @@ function ComposedChartRoot({ valueAxis, visibleBarAxisIds, fullAxisSpace, - axisLayout + axisLayout, + nativeKeyCounts )} diff --git a/packages/data-app-react/src/ui/ComposedChartLegend.tsx b/packages/data-app-react/src/ui/ComposedChartLegend.tsx index 4750141f..a5cec3f4 100644 --- a/packages/data-app-react/src/ui/ComposedChartLegend.tsx +++ b/packages/data-app-react/src/ui/ComposedChartLegend.tsx @@ -217,7 +217,6 @@ function LegendContent({ } /** Opt in inside ComposedChart to derive the shared legend from its displayed series. - * Give native series unique IDs when they share a data key. * Native positioning, sorting, formatters, callbacks, and custom content remain available. */ export function ComposedChartLegend({ maxVisibleItems, diff --git a/tests/public-api/apps-chart-legends.test.ts b/tests/public-api/apps-chart-legends.test.ts index effd17f0..ff4717d7 100644 --- a/tests/public-api/apps-chart-legends.test.ts +++ b/tests/public-api/apps-chart-legends.test.ts @@ -476,6 +476,28 @@ test('native function-key series respond to the automatic legend', async ({ .toBe(0); }); +test('native series sharing a data key focus without explicit IDs', async ({ + page, +}) => { + await page.goto('/chart-legends'); + const chart = page.getByRole('region', { + name: 'Native shared data key plot', + exact: true, + }); + const alpha = chart.getByRole('button', { name: 'Alpha', exact: true }); + const beta = chart.getByRole('button', { name: 'Beta', exact: true }); + await alpha.click(); + await expect.poll(() => alpha.getAttribute('aria-pressed')).toBe('true'); + await expect + .poll(() => chart.locator('.recharts-line-curve').count()) + .toBe(1); + await beta.click(); + await expect.poll(() => alpha.getAttribute('aria-pressed')).toBe('false'); + await expect + .poll(() => chart.locator('.recharts-line-curve').count()) + .toBe(2); +}); + test('crowded automatic legends reserve a cell for expansion and restore their compact list', async ({ page, }) => { diff --git a/tests/public-api/fixtures/chart-legends.tsx b/tests/public-api/fixtures/chart-legends.tsx index 9f1e258e..f564199e 100644 --- a/tests/public-api/fixtures/chart-legends.tsx +++ b/tests/public-api/fixtures/chart-legends.tsx @@ -618,6 +618,21 @@ createRoot(document.getElementById('root')!).render( + + + + + + + + +