diff --git a/REFERENCE.md b/REFERENCE.md index a1629cfb..eb806645 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 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. @@ -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..545be08c 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,9 @@ font: inherit; text-align: left; } +.altertable-chart-legend-action:where(button) { + cursor: pointer; +} .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..81b30c92 100644 --- a/packages/data-app-react/src/ui/ChartLegend.tsx +++ b/packages/data-app-react/src/ui/ChartLegend.tsx @@ -40,7 +40,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 diff --git a/packages/data-app-react/src/ui/ComposedChart.css b/packages/data-app-react/src/ui/ComposedChart.css index 9e658dad..0fae8912 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-heading] + .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/ComposedChart.tsx b/packages/data-app-react/src/ui/ComposedChart.tsx index c6c240ac..ecc3ea72 100644 --- a/packages/data-app-react/src/ui/ComposedChart.tsx +++ b/packages/data-app-react/src/ui/ComposedChart.tsx @@ -3,13 +3,16 @@ import { Children, Fragment, isValidElement, + cloneElement, useState, useCallback, useEffect, + useLayoutEffect, useRef, type PointerEvent, type ComponentProps, type ReactNode, + type ReactElement, } from 'react'; import { ComposedChart as RechartsComposedChart, @@ -20,6 +23,15 @@ import { ReferenceDot, Brush, Cell, + Line as NativeLine, + Bar as NativeBar, + Area as NativeArea, + Scatter as NativeScatter, + XAxis as NativeXAxis, + YAxis as NativeYAxis, + Legend as NativeLegend, + useOffset, + useMargin, Label, LabelList, ErrorBar, @@ -31,6 +43,12 @@ import { ChartInteractionContext, type ChartPoint, } from './chart-interaction.tsx'; +import { + ChartLegendInteractionContext, + chartLegendSeriesKey, + reconcileLegendFocus, + toggleLegendFocus, +} from './chart-legend-interaction.tsx'; import { ChartBar as Bar, ChartDot as Dot, @@ -94,6 +112,273 @@ 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, + hoveredKey: string | null, + suppressPlotInspection: boolean, + valueAxis: 'x' | 'y', + visibleBarAxisIds: ReadonlySet, + fullAxisSpace: { left: number; right: number } | null, + yAxisSideCounts: { left: number; right: number }, + keyCounts: ReadonlyMap, + 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, + suppressPlotInspection, + valueAxis, + visibleBarAxisIds, + fullAxisSpace, + yAxisSideCounts, + keyCounts, + `${path}-${child.key ?? index}` + ), + } as { children: ReactNode }); + } + if (child.type === XAxis || child.type === NativeXAxis) { + 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, { + 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: visibleBarAxisIds.has(axis.props.yAxisId ?? 0) + ? [0, 'auto'] + : ['auto', 'auto'], + ...(reservedWidth != null && { width: reservedWidth }), + }); + } + 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 }; + dot?: unknown; + activeDot?: unknown; + }>; + 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, { + id, + hide: excluded || series.props.hide, + opacity: excluded + ? 0 + : hoveredKey && + (!focusedKeys || focusedKeys.has(hoveredKey)) && + hoveredKey !== key + ? 0.2 + : series.props.opacity, + style: { + ...series.props.style, + pointerEvents: excluded ? 'none' : series.props.style?.pointerEvents, + }, + ...(excluded && (child.type === NativeLine || child.type === NativeArea) + ? { dot: false, activeDot: false } + : {}), + ...(suppressPlotInspection && + (child.type === NativeLine || child.type === NativeArea) + ? { activeDot: false } + : {}), + }); + }); +} + +function collectVisibleNativeBarAxisIds( + children: ReactNode, + focusedKeys: ReadonlySet | null, + valueAxis: 'x' | 'y', + keyCounts: ReadonlyMap, + path = 'root', + ids = new Set() +) { + Children.forEach(children, (child, index) => { + if (!isValidElement(child)) return; + if (child.type === Fragment) { + collectVisibleNativeBarAxisIds( + (child.props as { children?: ReactNode }).children, + focusedKeys, + valueAxis, + keyCounts, + `${path}-${child.key ?? index}`, + ids + ); + } else if (child.type === NativeBar) { + const props = child.props as { + id?: string; + dataKey?: unknown; + hide?: boolean; + xAxisId?: string | number; + yAxisId?: string | number; + }; + const id = nativeSeriesId(props, child, index, path, keyCounts); + 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 @@ -111,6 +396,7 @@ function ComposedChartRoot({ width = '100%', height = 300, responsive = true, + layout = 'horizontal', className, ...props }: ComposedChartProps) { @@ -151,6 +437,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)) { @@ -199,65 +486,163 @@ function ComposedChartRoot({ }); }; }, []); + const [legendHoveredKey, setLegendHoveredKey] = useState(null); + 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 nativeKeyCounts = countNativeSeriesKeys(children); + const visibleBarAxisIds = collectVisibleNativeBarAxisIds( + children, + focusedLegendKeys, + valueAxis, + nativeKeyCounts + ); + 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)); + }, []); + const toggleLegendKey = useCallback( + (key: string, keys: readonly string[]) => { + setSuppressPlotInspection(true); + setFocusedLegendKeys(current => toggleLegendFocus(current, key, keys)); + }, + [] + ); return ( - { + setLegendHoveredKey(key); + if (key) setSuppressPlotInspection(true); + }, + toggle: toggleLegendKey, + reconcile: reconcileLegendKeys, + registerBarAxis, }} > -
{ - setHasPointerFocus(trackPointer(event)); - }} - onPointerOverCapture={trackPointer} - onPointerMoveCapture={trackPointer} - onPointerLeave={event => { - if (event.pointerType !== 'touch') { - resetPointerInspection(); - } - }} - onKeyDownCapture={() => { - setHasPointerFocus(false); - resetPointerInspection(); + { - 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} - - - -
-
+ }} + 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); + resetPointerInspection(); + } + }} + > + + + + {valueAxis === 'y' && + axisLayout.autoYAxis && + axisLayout.interactiveLegend && ( + + )} + {horizontalGrid && !hasAuthoredGrid(children) && ( + + )} + {applyNativeLegendInteraction( + children, + focusedLegendKeys, + legendHoveredKey, + suppressPlotInspection, + valueAxis, + visibleBarAxisIds, + fullAxisSpace, + axisLayout, + nativeKeyCounts + )} + + + +
+
+
); } diff --git a/packages/data-app-react/src/ui/ComposedChartLegend.tsx b/packages/data-app-react/src/ui/ComposedChartLegend.tsx index a392f447..a5cec3f4 100644 --- a/packages/data-app-react/src/ui/ComposedChartLegend.tsx +++ b/packages/data-app-react/src/ui/ComposedChartLegend.tsx @@ -1,11 +1,22 @@ import { KEY_SEPARATOR } from '@altertable/data-app/internal'; -import { useState, type ComponentProps } from 'react'; +import { + useContext, + useLayoutEffect, + 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 one or more series. */ + interactive?: boolean; }; type LegendContentProps = ComposedChartLegendProps & { payload?: readonly LegendPayload[]; @@ -41,11 +52,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,10 +89,24 @@ function LegendContent({ onClick, onMouseEnter, onMouseLeave, + interactive = true, 'aria-label': ariaLabel, }: LegendContentProps) { const [getItemKeys] = useState(createLegendItemKeys); + const interaction = useContext(ChartLegendInteractionContext); const itemKeys = getItemKeys(payload); + const selectableKeys = itemKeys.filter( + (_, index) => payload[index]?.type !== 'none' + ); + useLayoutEffect(() => { + interaction?.reconcile(selectableKeys); + }); + 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' || @@ -133,24 +156,53 @@ function LegendContent({ onMouseEnter(entry, index, event) + data-legend-muted={ + canInteract && + interaction.hoveredKey && + (!interaction.focusedKeys || + interaction.focusedKeys.has(interaction.hoveredKey)) && + interaction.hoveredKey !== itemKeys[index] + ? true : undefined } - onMouseLeave={ - onMouseLeave - ? event => onMouseLeave(entry, index, event) + data-legend-excluded={ + canInteract && + interaction.focusedKeys && + !interaction.focusedKeys.has(itemKeys[index]!) + ? true : undefined } + onMouseEnter={event => { + if (canInteract) interaction.hover(itemKeys[index]!); + onMouseEnter?.(entry, index, event); + }} + onMouseLeave={event => { + if (canInteract) interaction.hover(null); + onMouseLeave?.(entry, index, event); + }} > - {onClick ? ( + {canInteract || onClick ? ( @@ -165,17 +217,22 @@ 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, + 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..a7308aa9 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,16 +179,55 @@ 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 + )} + + )} ))} @@ -253,8 +297,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 +328,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 +367,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..91a60539 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,9 +252,43 @@ export function RetentionChart({ {cohorts.map(item => ( - - - {item.label} + + {interactiveLegend && cohorts.length > 1 ? ( + + ) : ( + <> + + {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 new file mode 100644 index 00000000..1792d2f7 --- /dev/null +++ b/packages/data-app-react/src/ui/chart-legend-interaction.tsx @@ -0,0 +1,92 @@ +import { KEY_SEPARATOR } from '@altertable/data-app/internal'; +import { createContext, useContext, useState } from 'react'; + +export function chartLegendSeriesKey(id: unknown, dataKey: unknown) { + if (typeof id === 'string' || typeof id === 'number') + return ['series', typeof id, id].join(KEY_SEPARATOR); + if (typeof dataKey === 'string' || typeof dataKey === 'number') + return ['data', typeof dataKey, dataKey].join(KEY_SEPARATOR); + return null; +} + +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; + registerBarAxis: (key: string, axisId: string | number) => () => 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[] +) { + 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; +} + +export const ChartLegendInteractionContext = + createContext(null); + +export function useChartLegendSeries(id: unknown, dataKey: unknown) { + const interaction = useContext(ChartLegendInteractionContext); + const key = chartLegendSeriesKey(id, dataKey); + return { + inspectingLegend: !!interaction?.suppressPlotInspection, + 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 focusedIds = reconcileLegendFocus(storedFocusedIds, ids); + function toggle(id: string) { + setStoredFocusedIds(current => toggleLegendFocus(current, id, ids)); + } + return { + hoveredId, + setHoveredId, + focusedIds, + toggle, + 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..ec6f6132 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, @@ -11,9 +17,11 @@ import { Scatter, YAxis, useYAxisTicks, + useCartesianChartLayout, CartesianGrid, Tooltip, DefaultTooltipContent, + type TooltipContentProps, type BarProps, type LineProps, type AreaProps, @@ -25,6 +33,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'; @@ -49,11 +62,12 @@ function NearestChartDot({ }: DotProps & { seriesId: string }) { const interaction = useContext(ChartInteractionContext); const registerPoint = interaction?.registerPoint; + const legend = useChartLegendSeries(seriesId, undefined); useLayoutEffect(() => { - 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 ? ( ( ) { 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 ( @@ -81,6 +106,12 @@ 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, + pointerEvents: legend.hidden ? 'none' : props.style?.pointerEvents, + }} /> ); @@ -95,6 +126,7 @@ export function ChartLine({ ...props }: LineProps) { const series = useChartSeries(props.id); + const legend = useChartLegendSeries(series.id, props.dataKey); return ( @@ -104,25 +136,35 @@ export function ChartLine({ 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 || legend.inspectingLegend + ? false + : activeDot === undefined || activeDot === true + ? ({ cx, cy }) => ( + + ) + : activeDot } isAnimationActive={false} {...props} id={series.id} + hide={legend.hidden || props.hide} + opacity={legend.hidden ? 0 : legend.dimmed ? 0.2 : props.opacity} + style={{ + ...props.style, + pointerEvents: legend.hidden ? 'none' : props.style?.pointerEvents, + }} /> ); @@ -136,6 +178,7 @@ export function ChartArea({ ...props }: AreaProps) { const series = useChartSeries(props.id); + const legend = useChartLegendSeries(series.id, props.dataKey); return ( @@ -148,25 +191,35 @@ 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 || legend.inspectingLegend + ? false + : activeDot === undefined || activeDot === true + ? ({ cx, cy }) => ( + + ) + : activeDot } isAnimationActive={false} {...props} id={series.id} + hide={legend.hidden || props.hide} + opacity={legend.hidden ? 0 : legend.dimmed ? 0.2 : props.opacity} + style={{ + ...props.style, + pointerEvents: legend.hidden ? 'none' : props.style?.pointerEvents, + }} /> ); @@ -176,6 +229,7 @@ export function ChartScatter( props: ComponentProps> ) { const series = useChartSeries(props.id); + const legend = useChartLegendSeries(series.id, props.dataKey); return ( @@ -183,6 +237,12 @@ 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, + pointerEvents: legend.hidden ? 'none' : props.style?.pointerEvents, + }} /> ); @@ -309,23 +369,11 @@ export function ChartTooltipContent( 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 - } - /> - )} position={ interaction?.isPointerInspection && interaction.activePoint ? { y: interaction.activePoint.y } @@ -333,7 +381,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 c97b7e7e..ff4717d7 100644 --- a/tests/public-api/apps-chart-legends.test.ts +++ b/tests/public-api/apps-chart-legends.test.ts @@ -2,6 +2,502 @@ import { expect } from 'vitest'; import { test } from '@/tests/public-api/browser'; +test('automatic legend previews, focuses, and adds series', 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); + expect(await chart.getByRole('button', { name: 'Show all' }).count()).toBe(0); + const chartHeight = (await chart.boundingBox())!.height; + 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(); + 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); + await expect.poll(() => curves.count()).toBe(1); + await expect.poll(() => 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()) + .toBe((await legend.locator('button[aria-pressed]').count()) - 2); + await expect.poll(() => curves.count()).toBe(2); + await api.click(); + await analytics.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); + const alpha = chart.getByRole('button', { name: 'Alpha', exact: true }); + await alpha.click(); + await expect.poll(() => dots.count()).toBe(2); + await alpha.click(); + 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('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, +}) => { + 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); + 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 }) => { + 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('true'); + await expect + .poll(() => chart.locator('[data-legend-excluded]').count()) + .toBe(3); + await page.keyboard.press('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 }); + 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 label = legend.getByText( + 'Alpha — response time in production workspaces across Europe', + { exact: 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; + const alpha = legend.getByRole('button', { + name: 'Alpha — response time in production workspaces across Europe', + }); + await alpha.click(); + await expect + .poll(() => legend.locator('[data-legend-excluded]').count()) + .toBeGreaterThan(0); + expect((await chart.boundingBox())!.height).toBe(chartHeight); + await alpha.click(); + await expect + .poll(() => legend.locator('[data-legend-excluded]').count()) + .toBe(0); +}); + +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', { + name: 'Four series plot', + 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; + const alpha = legend.getByRole('button', { name: 'Alpha', exact: true }); + await alpha.click(); + 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']) { + 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('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.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'); + 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, +}) => { + 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.hover(); + await expect + .poll(() => chart.locator('[data-legend-muted]').count()) + .toBe(0); + await secondButton.click(); + await expect + .poll(() => chart.locator('[data-legend-excluded]').count()) + .toBe(0); + 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').count()) + .toBe(1); + await alpha.click(); + await expect + .poll(() => chart.locator('[data-legend-excluded]').count()) + .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, }) => { @@ -102,7 +598,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 @@ -122,6 +618,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..f564199e 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' @@ -246,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( @@ -548,6 +606,134 @@ createRoot(document.getElementById('root')!).render( ))} + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +