From 281d399db8ddb1346fb739fbec228f45a5d64739 Mon Sep 17 00:00:00 2001 From: Chi-Hsuan Huang Date: Tue, 10 Nov 2026 15:04:14 +0800 Subject: [PATCH 01/28] Charts: Draw a stacked bar chart's comparison series as one total bar --- .../changelog/charts-stacked-comparison | 4 + .../charts/src/charts/bar-chart/bar-chart.tsx | 41 +++--- .../src/charts/bar-chart/private/index.ts | 3 +- .../charts/bar-chart/private/overlap-bars.ts | 10 ++ .../charts/bar-chart/private/stack-layout.ts | 136 +++++++++++++----- .../bar-chart/private/stacked-bar-series.tsx | 10 +- .../private/test/stack-layout.test.ts | 42 +++++- .../charts/bar-chart/private/use-bar-slots.ts | 53 +++++-- .../charts/bar-chart/stories/index.api.mdx | 8 +- .../charts/bar-chart/stories/index.docs.mdx | 5 +- .../bar-chart/stories/index.stories.tsx | 39 +++++ .../bar-chart/test/bar-chart-stacked.test.tsx | 74 ++++++++-- .../test/use-bar-legend-items.test.tsx | 16 ++- .../src/charts/bar-chart/use-bar-colors.ts | 26 ++-- .../charts/bar-chart/use-bar-legend-items.ts | 74 ++++++++-- projects/js-packages/charts/src/types.ts | 2 +- 16 files changed, 433 insertions(+), 110 deletions(-) create mode 100644 projects/js-packages/charts/changelog/charts-stacked-comparison diff --git a/projects/js-packages/charts/changelog/charts-stacked-comparison b/projects/js-packages/charts/changelog/charts-stacked-comparison new file mode 100644 index 000000000000..e6da732eca98 --- /dev/null +++ b/projects/js-packages/charts/changelog/charts-stacked-comparison @@ -0,0 +1,4 @@ +Significance: minor +Type: added + +Bar chart: Sum comparison series into one bar beside each stack in the stacked layout. diff --git a/projects/js-packages/charts/src/charts/bar-chart/bar-chart.tsx b/projects/js-packages/charts/src/charts/bar-chart/bar-chart.tsx index b955120e6bab..2fb165de363f 100644 --- a/projects/js-packages/charts/src/charts/bar-chart/bar-chart.tsx +++ b/projects/js-packages/charts/src/charts/bar-chart/bar-chart.tsx @@ -43,6 +43,8 @@ import { MAX_GROUP_PADDING, COMPARISON_TICK_GAP_FACTOR, BASE_BAND_PADDING_INNER, + COMPARISON_SLOT, + getComparisonTotalLabel, isBarRendered, SlotTooltipMembers, useBarStops, @@ -50,7 +52,6 @@ import { getSelectedSlot, isSameCategory, membersAt, - getDrawnSeries, } from './private'; import { useBarColors } from './use-bar-colors'; import { useBarLegendItems } from './use-bar-legend-items'; @@ -146,12 +147,6 @@ const BarChartInternal: FC< BarChartProps > = ( { 'BarChart: showZeroValues has no effect in a stacked layout.' ); } - if ( layout === 'stacked' && data?.some( series => series.options?.type === 'comparison' ) ) { - warnOnce( - 'bar-chart-stacked-comparison', - 'BarChart: a stacked layout does not draw comparison series yet.' - ); - } const valueScaleOptions = orientation === 'horizontal' ? options.xScale : options.yScale; if ( layout === 'stacked' && valueScaleOptions?.type && valueScaleOptions.type !== 'linear' ) { warnOnce( @@ -189,11 +184,7 @@ const BarChartInternal: FC< BarChartProps > = ( { const theme = useXYChartTheme( data ); const transformedData = useChartDataTransform( data ); - // A stacked layout does not draw comparisons yet, so they must not shade a primary's color or join the legend either. - const dataSorted = useMemo( - () => getDrawnSeries( transformedData, layout ), - [ layout, transformedData ] - ); + const dataSorted = transformedData; // Transform data to add a small value for zero bars to make them visible // For vertical bars, height determines bar pixel height; for horizontal bars, width does @@ -285,7 +276,11 @@ const BarChartInternal: FC< BarChartProps > = ( { [ seriesWithVisibility ] ); - const barSlots = useBarSlots( layout, seriesWithVisibility ); + const barSlots = useBarSlots( + layout, + seriesWithVisibility, + getComparisonTotalLabel( legendComparisonItem ) + ); const chartOptions = useBarChartOptions( dataWithVisibleZeros, @@ -361,7 +356,7 @@ const BarChartInternal: FC< BarChartProps > = ( { ); const comparisonEntries = useMemo( () => { - // An overlap layout draws its comparisons as slotted bars, and a stacked one does not draw them yet. + // An overlap layout draws its comparisons as slotted bars, and a stacked one sums them into one. if ( barSlots ) { return []; } @@ -485,7 +480,7 @@ const BarChartInternal: FC< BarChartProps > = ( { [ chartOptions.tooltip, dataSorted ] ); - // Lists the stack last series first, a null reading as "No data", then the total. + // Lists the stack last series first, a null reading as "No data", then the total and the comparison total. const renderStackedTooltip = useCallback( ( { tooltipData }: RenderTooltipParams< DataPointDate > ) => { const nearestDatum = tooltipData?.nearestDatum?.datum; @@ -498,10 +493,17 @@ const BarChartInternal: FC< BarChartProps > = ( { [] ); - const rows = [ ...barSlots.entries ].reverse().flatMap( ( { series } ) => { + const datumOf = ( { series }: { series: SeriesData } ) => { const datum = datumByKey[ series.label ]?.datum; return datum ? [ { label: series.label, datum } ] : []; - } ); + }; + const isPrimary = ( { series }: { series: SeriesData } ) => + barSlots.slotOf( series.label ) !== COMPARISON_SLOT; + const rows = barSlots.entries.filter( isPrimary ).reverse().flatMap( datumOf ); + const comparisonRows = barSlots.entries + .filter( entry => ! isPrimary( entry ) ) + .flatMap( datumOf ) + .filter( ( { datum } ) => isBarRendered( datum ) ); const readings = rows.filter( ( { datum } ) => isBarRendered( datum ) ).length; const [ negative, positive ] = barSlots.stack.extentAt( nearestDatum ); @@ -518,6 +520,11 @@ const BarChartInternal: FC< BarChartProps > = ( { __( 'Total', 'jetpack-charts' ), formatReading( negative + positive ) ) } + { comparisonRows.map( ( { label, datum } ) => ( + + { renderTooltipRow( label, formatReading( datum.value ) ) } + + ) ) } ); }, diff --git a/projects/js-packages/charts/src/charts/bar-chart/private/index.ts b/projects/js-packages/charts/src/charts/bar-chart/private/index.ts index b847830f367f..cbb6b4e9f635 100644 --- a/projects/js-packages/charts/src/charts/bar-chart/private/index.ts +++ b/projects/js-packages/charts/src/charts/bar-chart/private/index.ts @@ -7,7 +7,6 @@ export { SelectedBarRing, type SelectedBar } from './selected-bar-ring'; export { SlotTooltipMembers, type SlotMember } from './slot-tooltip-members'; export { useBarSlots, getSelectedSlot, membersAt } from './use-bar-slots'; export { isSameCategory } from './category'; -export { getDrawnSeries } from './stack-layout'; export { useBarStops } from './use-bar-stops'; export { ComparisonBars } from './comparison-bars'; export type { ComparisonSeriesEntry } from './comparison-bars'; @@ -21,3 +20,5 @@ export { BASE_BAND_PADDING_INNER } from './use-bar-chart-options'; export { isBarRendered } from './value-domain'; export { BandHighlight } from './band-highlight'; export { BandTooltip } from './band-tooltip'; +export { COMPARISON_SLOT } from './overlap-bars'; +export { getComparisonTotalLabel } from './stack-layout'; diff --git a/projects/js-packages/charts/src/charts/bar-chart/private/overlap-bars.ts b/projects/js-packages/charts/src/charts/bar-chart/private/overlap-bars.ts index 72781d4516f9..ec3145f1eaca 100644 --- a/projects/js-packages/charts/src/charts/bar-chart/private/overlap-bars.ts +++ b/projects/js-packages/charts/src/charts/bar-chart/private/overlap-bars.ts @@ -83,6 +83,16 @@ const awayFrom = ( background: string ): string => const opposite = ( end: string ): string => ( end === '#000000' ? '#ffffff' : '#000000' ); +/** + * The gray nearest the background that keeps 3:1 against it. + * + * @param background - The hex chart background. + * @return A hex color. + */ +export function neutralWithContrast( background: string ): string { + return tintWithContrast( awayFrom( background ), background ); +} + /** * The tone of a color nearest the background that keeps 3:1 against it. * diff --git a/projects/js-packages/charts/src/charts/bar-chart/private/stack-layout.ts b/projects/js-packages/charts/src/charts/bar-chart/private/stack-layout.ts index d0a8d49c4746..e4a351aa9556 100644 --- a/projects/js-packages/charts/src/charts/bar-chart/private/stack-layout.ts +++ b/projects/js-packages/charts/src/charts/bar-chart/private/stack-layout.ts @@ -1,71 +1,93 @@ +import { __ } from '@wordpress/i18n'; import { getTickDecimalsDomain } from '../../private/tick-decimals'; import { categoryKey } from './category'; import { EMPTY_DOMAIN, getBarValue } from './value-domain'; -import type { BarChartLayout, DataPointDate, SeriesData } from '../../../types'; +import type { DataPointDate, SeriesData } from '../../../types'; /** Where a bar runs along the value axis: from where the stack reached before it, to where it ends. */ export type StackSegment = { start: number; end: number }; +/** The comparison series a stacked layout sums into one bar, and the key that bar is drawn under. */ +export type ComparisonTotal = { key: string; series: SeriesData[] }; + /** The one source of a stacked layout's value-axis positions, for its bars, ring, tooltip and domain. */ export type StackLayout = { /** Where a series' bar runs at a datum's category; undefined when that datum has no reading. */ segmentOf: ( key: string, datum: DataPointDate ) => StackSegment | undefined; - /** The lowest negative sum and highest positive sum at the datum's category, both including 0. */ - extentAt: ( category: DataPointDate ) => [ number, number ]; - /** The widest `extentAt` over every category, or null without a finite value. */ + /** The lowest negative sum and highest positive sum at the datum's category, both including 0, of the bar `key` is drawn in. */ + extentAt: ( category: DataPointDate, key?: string ) => [ number, number ]; + /** The widest `extentAt` over every category and bar, or null without a finite value. */ extent: [ number, number ] | null; }; -/** - * The series a layout draws: a stacked layout leaves comparison series out for now. - * - * @param series - The chart's series. - * @param layout - The layout the bars are drawn in. - * @return The drawn series. - */ -export function getDrawnSeries< T extends SeriesData >( - series: T[], - layout?: BarChartLayout -): T[] { - return layout === 'stacked' - ? series.filter( item => item.options?.type !== 'comparison' ) - : series; -} +type Extents = Map< string, [ number, number ] >; /** - * Stacks the series in order at each category: positives upward and negatives downward from zero. + * Sums the series at each category, positives and negatives apart, calling `onSegment` with where each reading runs. * - * @param series - The series to stack, bottom first. - * @return The stack layout. + * @param series - The series to stack, bottom first. + * @param onSegment - Receives each reading's series, category and segment. + * @return The extent at each category. */ -export function getStackLayout( series: SeriesData[] ): StackLayout { - const segments = new Map< string, Map< string, StackSegment > >(); - const extents = new Map< string, [ number, number ] >(); +function stackSeries( + series: SeriesData[], + onSegment?: ( label: string, key: string, segment: StackSegment ) => void +): Extents { + const extents: Extents = new Map(); for ( const { label, data } of series ) { - const byCategory = new Map< string, StackSegment >(); - segments.set( label, byCategory ); + const seen = new Set< string >(); for ( const point of data as DataPointDate[] ) { const value = getBarValue( point ); - if ( ! Number.isFinite( value ) ) { - continue; - } const key = categoryKey( point ); // A repeated category is invalid data; skipping it keeps the bars, total and tooltip in step. - if ( byCategory.has( key ) ) { + if ( ! Number.isFinite( value ) || seen.has( key ) ) { continue; } + seen.add( key ); const extent = extents.get( key ) ?? [ 0, 0 ]; const side = value < 0 ? 0 : 1; const start = extent[ side ]; extent[ side ] = start + value; extents.set( key, extent ); - byCategory.set( key, { start, end: start + value } ); + onSegment?.( label, key, { start, end: start + value } ); } } + return extents; +} + +/** + * Stacks the series in order at each category: positives upward and negatives downward from zero. Comparisons are summed the same way into one bar of their own. + * + * @param series - The series to stack, bottom first. + * @param comparison - The comparison series to sum, and the key their bar is drawn under. + * @return The stack layout. + */ +export function getStackLayout( series: SeriesData[], comparison?: ComparisonTotal ): StackLayout { + const segments = new Map< string, Map< string, StackSegment > >( + series.map( ( { label } ) => [ label, new Map() ] ) + ); + const extents = stackSeries( series, ( label, key, segment ) => + segments.get( label )?.set( key, segment ) + ); + const comparisonExtents: Extents = comparison ? stackSeries( comparison.series ) : new Map(); + + if ( comparison ) { + // One bar spans both sides, so it ends where the positives do, or the negatives without any. + segments.set( + comparison.key, + new Map( + [ ...comparisonExtents ].map( ( [ key, [ low, high ] ] ) => [ + key, + high > 0 ? { start: low, end: high } : { start: 0, end: low }, + ] ) + ) + ); + } + let extent: [ number, number ] | null = null; - for ( const [ low, high ] of extents.values() ) { + for ( const [ low, high ] of [ ...extents.values(), ...comparisonExtents.values() ] ) { extent = extent ? [ Math.min( extent[ 0 ], low ), Math.max( extent[ 1 ], high ) ] : [ low, high ]; @@ -73,14 +95,58 @@ export function getStackLayout( series: SeriesData[] ): StackLayout { return { segmentOf: ( key, datum ) => segments.get( key )?.get( categoryKey( datum ) ), - extentAt: category => { - const [ low, high ] = extents.get( categoryKey( category ) ) ?? [ 0, 0 ]; + extentAt: ( category, key ) => { + const byCategory = key !== undefined && key === comparison?.key ? comparisonExtents : extents; + const [ low, high ] = byCategory.get( categoryKey( category ) ) ?? [ 0, 0 ]; return [ low, high ]; }, extent, }; } +/** + * Names a stacked layout's comparison total after the legend's comparison item, or as that item is named by default. + * + * @param comparisonItem - The legend's `comparisonItem` option. + * @return The label. + */ +export function getComparisonTotalLabel( comparisonItem?: boolean | string ): string { + return typeof comparisonItem === 'string' + ? comparisonItem + : __( 'Comparison period', 'jetpack-charts' ); +} + +/** + * The series of a comparison total: at each category the comparisons have a reading, the net of their readings. + * + * @param comparisons - The comparison series to sum. + * @param label - The total's label. + * @return The total, a comparison series named `label`. + */ +export function getComparisonTotalSeries( comparisons: SeriesData[], label: string ): SeriesData { + const totals = new Map< string, DataPointDate >(); + + for ( const { data } of comparisons ) { + const seen = new Set< string >(); + for ( const point of data as DataPointDate[] ) { + const key = categoryKey( point ); + const value = getBarValue( point ); + if ( seen.has( key ) ) { + continue; + } + seen.add( key ); + const total = totals.get( key ); + if ( ! total ) { + totals.set( key, { ...point, value: Number.isFinite( value ) ? value : null } ); + } else if ( Number.isFinite( value ) ) { + total.value = ( total.value ?? 0 ) + value; + } + } + } + + return { label, data: [ ...totals.values() ], options: { type: 'comparison' } }; +} + /** * The value domain of a computed stack, falling back to an empty chart's domain. * diff --git a/projects/js-packages/charts/src/charts/bar-chart/private/stacked-bar-series.tsx b/projects/js-packages/charts/src/charts/bar-chart/private/stacked-bar-series.tsx index 7da2077aeba5..bc971356148b 100644 --- a/projects/js-packages/charts/src/charts/bar-chart/private/stacked-bar-series.tsx +++ b/projects/js-packages/charts/src/charts/bar-chart/private/stacked-bar-series.tsx @@ -31,6 +31,7 @@ type Props = Pick< * The side a segment rounds when it ends its drawn stack: the far end of the positives or of the negatives. * * @param stack - The stack layout. + * @param key - The series the segment is drawn for. * @param segment - The segment. * @param category - A datum at the segment's category. * @param horizontal - Whether the bars run horizontally. @@ -39,6 +40,7 @@ type Props = Pick< */ function getStackEnd( stack: StackLayout, + key: string, segment: StackSegment, category: DataPointDate, horizontal: boolean, @@ -48,7 +50,7 @@ function getStackEnd( if ( start === end ) { return undefined; } - const extent = stack.extentAt( category ).map( clamp ); + const extent = stack.extentAt( category, key ).map( clamp ); if ( segment.end > 0 && end === extent[ 1 ] ) { return horizontal ? 'right' : 'top'; } @@ -87,10 +89,10 @@ const StackedBarSeries = ( { // The positive end, or the negative end when nothing is positive; clamped so a caller domain keeps it on the drawn bar. const stackEnd = useCallback( ( datum: DataPointDate ) => { - const [ low, high ] = stack.extentAt( datum ); + const [ low, high ] = stack.extentAt( datum, dataKey ); return clamp( high > 0 ? high : low ); }, - [ stack, clamp ] + [ stack, dataKey, clamp ] ); const renderGlyph = useCallback( ( { datum, color }: GlyphProps< DataPointDate > ) => { @@ -110,7 +112,7 @@ const StackedBarSeries = ( { diff --git a/projects/js-packages/charts/src/charts/bar-chart/private/test/stack-layout.test.ts b/projects/js-packages/charts/src/charts/bar-chart/private/test/stack-layout.test.ts index 17d601e71d0b..5ab279783f28 100644 --- a/projects/js-packages/charts/src/charts/bar-chart/private/test/stack-layout.test.ts +++ b/projects/js-packages/charts/src/charts/bar-chart/private/test/stack-layout.test.ts @@ -1,4 +1,4 @@ -import { getStackLayout, getStackedValueDomain } from '../stack-layout'; +import { getComparisonTotalSeries, getStackLayout, getStackedValueDomain } from '../stack-layout'; import type { DataPointDate, SeriesData } from '../../../../types'; const s = ( @@ -67,12 +67,52 @@ describe( 'getStackLayout', () => { } ); } ); + it.each( [ + [ 'positive', [ 300, 150 ], { start: 0, end: 450 }, [ 0, 450 ] ], + [ 'negative', [ -30, -20 ], { start: 0, end: -50 }, [ -50, 0 ] ], + [ 'mixed', [ 30, -20 ], { start: -20, end: 30 }, [ -20, 30 ] ], + ] )( + 'sums %s comparisons into one segment of their own bar', + ( _sign, values, segment, extent ) => { + const layout = getStackLayout( SERIES, { + key: 'Previous', + series: values.map( ( value, index ) => s( `P${ index }`, [ value ] ) ), + } ); + expect( layout.segmentOf( 'Previous', at( 'Mon' ) ) ).toEqual( segment ); + expect( layout.extentAt( at( 'Mon' ), 'Previous' ) ).toEqual( extent ); + expect( layout.extentAt( at( 'Mon' ) ) ).toEqual( [ 0, 180 ] ); + } + ); + + it( 'spans the taller of the stack and its comparison total', () => { + const layout = getStackLayout( SERIES, { key: 'Previous', series: [ s( 'P', [ 500 ] ) ] } ); + expect( layout.extent ).toEqual( [ 0, 500 ] ); + } ); + it( 'spans the widest category, or nothing without a reading', () => { expect( getStackLayout( SERIES ).extent ).toEqual( [ 0, 180 ] ); expect( getStackLayout( [ s( 'A', [ null ] ) ] ).extent ).toBeNull(); } ); } ); +describe( 'getComparisonTotalSeries', () => { + it( 'nets the readings at each category, and keeps a category without one as no data', () => { + const total = getComparisonTotalSeries( + [ + s( 'A', [ 30, null, null ], [ 'Mon', 'Tue', 'Wed' ] ), + s( 'B', [ -10, 5 ], [ 'Mon', 'Tue' ] ), + ], + 'Previous' + ); + expect( total.label ).toBe( 'Previous' ); + expect( total.data.map( ( { label, value } ) => [ label, value ] ) ).toEqual( [ + [ 'Mon', 20 ], + [ 'Tue', 5 ], + [ 'Wed', null ], + ] ); + } ); +} ); + describe( 'getStackedValueDomain', () => { it( 'reads 0 to 1 with nothing to stack', () => { expect( getStackedValueDomain( getStackLayout( [ s( 'A', [ null ] ) ] ) ) ).toEqual( [ 0, 1 ] ); diff --git a/projects/js-packages/charts/src/charts/bar-chart/private/use-bar-slots.ts b/projects/js-packages/charts/src/charts/bar-chart/private/use-bar-slots.ts index 143713e0740c..6315c708f18a 100644 --- a/projects/js-packages/charts/src/charts/bar-chart/private/use-bar-slots.ts +++ b/projects/js-packages/charts/src/charts/bar-chart/private/use-bar-slots.ts @@ -1,7 +1,7 @@ import { useMemo } from 'react'; import { categoryKey, isSameCategory } from './category'; import { COMPARISON_SLOT, PRIMARY_SLOT, getOverlapPlacements } from './overlap-bars'; -import { getStackLayout } from './stack-layout'; +import { getComparisonTotalSeries, getStackLayout } from './stack-layout'; import { isBarRendered } from './value-domain'; import type { SelectedBar } from './selected-bar-ring'; import type { SlotMember } from './slot-tooltip-members'; @@ -32,16 +32,20 @@ export type StopPosition = { export type SelectedSlot = SelectedBar & { members: SlotMember[] }; +const isComparison = ( series: SeriesData ) => series.options?.type === 'comparison'; + /** - * Lays out the visible series in slots: overlap layers primaries and comparisons in two, stacked puts every primary in one. + * Lays out the visible series in slots: overlap layers primaries and comparisons in two, stacked puts every primary in one and sums the comparisons into a bar in a second. * * @param layout - How the chart places its series in a category. * @param seriesWithVisibility - Every series, with its index and whether it is visible. + * @param comparisonLabel - The label of a stacked layout's comparison total. * @return The slots, or undefined for a grouped layout. */ export function useBarSlots( layout: BarChartLayout, - seriesWithVisibility: ( SeriesEntry & { isVisible: boolean } )[] + seriesWithVisibility: ( SeriesEntry & { isVisible: boolean } )[], + comparisonLabel = '' ): BarSlots | undefined { return useMemo( () => { if ( layout === 'grouped' ) { @@ -52,12 +56,43 @@ export function useBarSlots( if ( layout === 'stacked' ) { // Bottom to top, so the top segment names each keyboard stop. - const entries = visible.map( ( { series, index } ) => ( { series, index } ) ); - const slotKeys = [ PRIMARY_SLOT ]; - const slotOf = () => PRIMARY_SLOT; + const primaries = visible.filter( ( { series } ) => ! isComparison( series ) ); + const visibleGroups = new Set( primaries.map( ( { series } ) => series.group ) ); + const hiddenGroups = new Set( + seriesWithVisibility.flatMap( ( { series, isVisible } ) => + isVisible || isComparison( series ) ? [] : [ series.group ] + ) + ); + // A comparison leaves the total with the primary it is paired with, so both bars sum the same series. + const comparisons = visible.filter( + ( { series } ) => + isComparison( series ) && + ( visibleGroups.has( series.group ) || ! hiddenGroups.has( series.group ) ) + ); + const total = comparisons.length + ? { + series: getComparisonTotalSeries( + comparisons.map( ( { series } ) => series ), + comparisonLabel + ), + index: comparisons[ 0 ].index, + } + : undefined; + const entries = [ ...primaries, ...( total ? [ total ] : [] ) ].map( + ( { series, index } ) => ( { series, index } ) + ); + const slotKeys = total ? [ PRIMARY_SLOT, COMPARISON_SLOT ] : [ PRIMARY_SLOT ]; + const slotOf = ( key: string ) => + total && key === total.series.label ? COMPARISON_SLOT : PRIMARY_SLOT; return { kind: 'stacked', - stack: getStackLayout( entries.map( ( { series } ) => series ) ), + stack: getStackLayout( + primaries.map( ( { series } ) => series ), + total && { + key: total.series.label, + series: comparisons.map( ( { series } ) => series ), + } + ), entries, keys: entries.map( ( { series } ) => series.label ), slotKeys, @@ -99,7 +134,7 @@ export function useBarSlots( thicknessOf, positions: getStopPositions( entries, slotKeys, slotOf ), }; - }, [ layout, seriesWithVisibility ] ); + }, [ layout, seriesWithVisibility, comparisonLabel ] ); } /** @@ -206,6 +241,6 @@ export function getSelectedSlot( slotKey, thickness: Math.max( ...slotBars.map( ( { key } ) => slots.thicknessOf( key ) ) ), members, - ...( slots.kind === 'stacked' && { valueExtent: slots.stack.extentAt( category ) } ), + ...( slots.kind === 'stacked' && { valueExtent: slots.stack.extentAt( category, stopKey ) } ), }; } diff --git a/projects/js-packages/charts/src/charts/bar-chart/stories/index.api.mdx b/projects/js-packages/charts/src/charts/bar-chart/stories/index.api.mdx index 525f4000d2ec..aea05989c7e1 100644 --- a/projects/js-packages/charts/src/charts/bar-chart/stories/index.api.mdx +++ b/projects/js-packages/charts/src/charts/bar-chart/stories/index.api.mdx @@ -19,7 +19,7 @@ Main chart component with responsive behavior by default. | `height` | `number` | `400` | Chart height in pixels | | `aspectRatio` | `number` | - | Height-to-width ratio (e.g. `0.4`) for responsive charts; the chart is contained within its parent on both axes. Used when `width`/`height` are omitted. | | `orientation` | `'vertical' \| 'horizontal'` | `'vertical'` | Bar orientation | -| `layout` | `'grouped' \| 'overlap' \| 'stacked'` | `'grouped'` | How series share a category. `overlap` draws every primary series in one slot and every `type: 'comparison'` series in a second, with each `group` a narrower, opaque bar in front of the one before it. `stacked` draws every primary series of a category as one bar, the first series at the bottom, and does not draw comparison series yet. See [overlap layout](./?path=/docs/js-packages-charts-library-charts-bar-chart--docs#overlap-layout) and [stacked layout](./?path=/docs/js-packages-charts-library-charts-bar-chart--docs#stacked-layout). | +| `layout` | `'grouped' \| 'overlap' \| 'stacked'` | `'grouped'` | How series share a category. `overlap` draws every primary series in one slot and every `type: 'comparison'` series in a second, with each `group` a narrower, opaque bar in front of the one before it. `stacked` draws every primary series of a category as one bar, the first series at the bottom, and sums the comparison series into one bar beside it. See [overlap layout](./?path=/docs/js-packages-charts-library-charts-bar-chart--docs#overlap-layout) and [stacked layout](./?path=/docs/js-packages-charts-library-charts-bar-chart--docs#stacked-layout). | | `withTooltips` | `boolean` | `false` | Enable interactive tooltips | | `withBandHighlight` | `boolean` | `false` | Highlight the active band across the plot; requires tooltips. Uses the `--a8c-charts-color-surface-secondary` catalog role. | | `onBandHighlightChange` | `(selection: BandHighlightSelection \| null) => void` | - | Receive datum, series `key`, rendered point `index`, and `x`, `y`, `width`, `height` in SVG coordinates; requires tooltips, but not the built-in highlight. Emits initial selection on mount and null on dismissal or unmount. | @@ -113,9 +113,9 @@ Comparison styling applies to the `grouped` layout only. An `overlap` layout dra ## Bar colors -`useBarColors()` returns a function, `( series, { layout } ) => string[]`, that gives the color `BarChart` fills each series with in that layout, by index. Use it to color a custom tooltip's swatches. In `stacked`, comparison series are not drawn and take no palette slot, so they do not shift the colors of the series after them. +`useBarColors()` returns a function, `( series, { layout } ) => string[]`, that gives the color `BarChart` fills each series with in that layout, by index. Use it to color a custom tooltip's swatches. In `stacked`, comparison series take no palette slot, so they do not shift the colors of the series after them, and all take the color of the one bar they are summed into. -`useBarLegendItems( data, { layout, ...legendOptions }, legendShape? )` builds the legend items `BarChart` registers for its own and composition legends, for a custom legend. It takes the `useChartLegendItems` options plus `layout`. With a layout, every swatch takes its bar's color; in `overlap` the swatches are opaque and, without `collapseGroups`, the items are in slot order: every primary, then every comparison; in `grouped`, a collapsed group's swatch takes its comparison's tint. In `stacked`, comparison series get no item. Without a layout, it returns `useChartLegendItems`' items unchanged. +`useBarLegendItems( data, { layout, ...legendOptions }, legendShape? )` builds the legend items `BarChart` registers for its own and composition legends, for a custom legend. It takes the `useChartLegendItems` options plus `layout`. With a layout, every swatch takes its bar's color; in `overlap` the swatches are opaque and, without `collapseGroups`, the items are in slot order: every primary, then every comparison; in `grouped`, a collapsed group's swatch takes its comparison's tint. In `stacked`, comparison series get no item; `comparisonItem` adds one static item for the bar they are summed into, and `comparisonSeriesItems` is ignored. Without a layout, it returns `useChartLegendItems`' items unchanged. ## DataPointDate Type @@ -180,7 +180,7 @@ type SeriesChartLegendConfig = { collapseGroups?: boolean; // Append a static "Comparison period" item styled like the `type: 'comparison'` series // (a string replaces the label). Only added when those series have no item of their own. - // A stacked bar chart draws no comparison series, so it adds no item. + // A stacked bar chart names the bar it sums the comparisons into with it, in the legend and tooltip. comparisonItem?: boolean | string; // Append one static item per comparison series instead, named from the label of the item it // was folded into and left out while that series is hidden. Not added by a stacked bar chart either. diff --git a/projects/js-packages/charts/src/charts/bar-chart/stories/index.docs.mdx b/projects/js-packages/charts/src/charts/bar-chart/stories/index.docs.mdx index eb9ee80d4723..60feb68e3583 100644 --- a/projects/js-packages/charts/src/charts/bar-chart/stories/index.docs.mdx +++ b/projects/js-packages/charts/src/charts/bar-chart/stories/index.docs.mdx @@ -267,9 +267,12 @@ Set `layout="stacked"` to draw every series of a category as one bar, each serie - The tooltip covers the whole stack: every series, last series first, with a `null` reading as "No data", then the total when there is more than one reading. It sits at the end of the positive values, or of the negative ones when the category has no positive value. - Arrow keys step one category at a time, and the selected stack is outlined as a whole. Enter hands `onDatumActivate` the top segment, while pointer callbacks report the segment under the pointer. - A bar radius (`--a8c-charts-border-radius-bar-chart`) rounds only the outer end of each stack, so the seams between segments stay flush. An outer segment shorter than the radius rounds only as far as its own length. -- `type: 'comparison'` series are left out of this layout for now, from the bars and the legend alike, and `showZeroValues` has no effect; both warn once in development. +- `type: 'comparison'` series are summed into one bar beside each stack: the comparison period's total, comparing totals rather than segments. Hiding a series also drops the comparison of its `group` from that total. The bar takes the first comparison's `options.stroke`, or else a gray that keeps 3:1 against the background. The tooltip lists it after the total, and the legend names it with one static item when `legend.comparisonItem` is set; both use that string as its name, or "Comparison period". +- `showZeroValues` has no effect, and warns once in development. - Works with `orientation="horizontal"`, where the first series is the left-most segment. + + ## Visual Features diff --git a/projects/js-packages/charts/src/charts/bar-chart/stories/index.stories.tsx b/projects/js-packages/charts/src/charts/bar-chart/stories/index.stories.tsx index 84a8fe492435..883142dfbe57 100644 --- a/projects/js-packages/charts/src/charts/bar-chart/stories/index.stories.tsx +++ b/projects/js-packages/charts/src/charts/bar-chart/stories/index.stories.tsx @@ -959,6 +959,45 @@ export const Stacked: Story = { }, }; +// The same devices over the four weeks before, each paired with its current series by `group`. +const deviceViewsWithPrevious: SeriesData[] = [ + ...deviceViewsData.map( series => ( { ...series, group: series.label } ) ), + ...deviceViewsData.map( ( series, index ) => ( { + label: `${ series.label } (previous)`, + group: series.label, + options: { type: 'comparison' as const }, + data: series.data.map( ( point, day ) => ( { + ...point, + value: Math.round( Number( point.value ) * ( 0.75 + ( ( day + index ) % 5 ) * 0.1 ) ), + } ) ), + } ) ), +]; + +export const StackedComparison: Story = { + args: { + ...Default.args, + layout: 'stacked', + data: deviceViewsWithPrevious, + showLegend: true, + legendInteractive: true, + gridVisibility: 'x', + }, + render: args => ( + + ), + parameters: { + docs: { + description: { + story: + "A stacked chart with a `type: 'comparison'` series per device. The comparisons are summed into one bar beside each stack, the previous period's total, in a gray that keeps 3:1 against the background; `legend.comparisonItem` names it in the legend and the tooltip. Hide a device from the legend and its previous period leaves the total too, so both bars sum the same devices.", + }, + }, + }, +}; + export const StackedHorizontal: Story = { args: { ...Default.args, diff --git a/projects/js-packages/charts/src/charts/bar-chart/test/bar-chart-stacked.test.tsx b/projects/js-packages/charts/src/charts/bar-chart/test/bar-chart-stacked.test.tsx index d0593d7ccf0e..2f3b6e1c8d89 100644 --- a/projects/js-packages/charts/src/charts/bar-chart/test/bar-chart-stacked.test.tsx +++ b/projects/js-packages/charts/src/charts/bar-chart/test/bar-chart-stacked.test.tsx @@ -294,25 +294,77 @@ describe( 'BarChart stacked layout', () => { } ); } ); - it( 'leaves comparison series out of the bars, colors and legend, and says so', () => { - const warn = jest.spyOn( console, 'warn' ).mockImplementation( () => {} ); + // Each series' previous period, paired by group; Mon sums to 500 against a 180 stack. + const WITH_PREVIOUS: SeriesData[] = [ + ...DATA.map( series => ( { ...series, group: series.label } ) ), + ...[ + [ 'Desktop', 300, 40 ], + [ 'Mobile', 150, 20 ], + [ 'Tablet', 50, null ], + ].map( ( [ label, mon, tue ] ) => ( { + label: `${ label } (prev)`, + group: label as string, + options: { type: 'comparison' as const }, + data: [ day( 'Mon', mon as number ), day( 'Tue', tue as number | null ) ], + } ) ), + ]; + // The five primary bars come first, then the comparison total at Mon and Tue. + const previousBar = ( category = 0, primaryBars = 5 ) => + geometry( barRects()[ primaryBars + category ] ); + + it( 'sums the comparisons into one bar beside each stack, in one color, scaled with the stack', () => { const fills = () => barRects().map( bar => bar.getAttribute( 'fill' ) ); - const { unmount } = renderStacked( { showLegend: true } ); + const { unmount } = renderStacked(); const plainFills = fills(); unmount(); + renderStacked( { data: WITH_PREVIOUS } ); + + expect( barRects() ).toHaveLength( 7 ); + const desktop = barIn( WITH_PREVIOUS, 'Desktop' ); + expect( previousBar().x ).toBeGreaterThanOrEqual( desktop.x + desktop.width ); + expect( previousBar().height / desktop.height ).toBeCloseTo( 500 / 100 ); + expect( fills().slice( 0, 5 ) ).toEqual( plainFills ); + expect( new Set( fills().slice( 5 ) ).size ).toBe( 1 ); + } ); + + it( 'lists the comparison total after the stack total, named by the legend comparison item', async () => { renderStacked( { + data: WITH_PREVIOUS, showLegend: true, - data: [ - ...DATA, - { label: 'Previous', options: { type: 'comparison' }, data: [ day( 'Mon', 500 ) ] }, - ], + legend: { comparisonItem: 'Prev. 7 days' }, } ); - expect( fills() ).toEqual( plainFills ); - expect( screen.queryByText( 'Previous' ) ).not.toBeInTheDocument(); - expect( warn ).toHaveBeenCalledWith( expect.stringContaining( 'comparison series' ) ); - warn.mockRestore(); + pointer( 'pointermove', center( previousBar() ) ); + const tooltip = await screen.findByRole( 'tooltip' ); + expect( tooltip ).toHaveTextContent( + /Mon.*Tablet: 20.*Mobile: 60.*Desktop: 100.*Total: 180.*Prev\. 7 days: 500/ + ); + expect( screen.getByText( 'Prev. 7 days' ) ).toBeInTheDocument(); + } ); + + it( 'stops on the comparison total after its stack, and rings it', async () => { + const user = userEvent.setup(); + renderStacked( { data: WITH_PREVIOUS } ); + + await user.tab(); + await user.keyboard( '{ArrowRight}{ArrowRight}' ); + expect( screen.getByTestId( 'chart-tooltip-1' ) ).toHaveTextContent( + /Mon.*Total: 180.*Comparison period: 500/ + ); + expect( rounded( selectedRing() ) ).toEqual( rounded( previousBar() ) ); + } ); + + it( "drops a hidden series' comparison from the total", async () => { + const user = userEvent.setup(); + renderStacked( { data: WITH_PREVIOUS, showLegend: true, legend: { interactive: true } } ); + + await user.click( screen.getByRole( 'button', { name: /Mobile/ } ) ); + const desktop = barIn( + WITH_PREVIOUS.filter( series => series.label !== 'Mobile' ), + 'Desktop' + ); + expect( previousBar( 0, 4 ).height / desktop.height ).toBeCloseTo( 350 / 100 ); } ); it( 'ignores showZeroValues, so a zero adds nothing to the stack, and says so', () => { diff --git a/projects/js-packages/charts/src/charts/bar-chart/test/use-bar-legend-items.test.tsx b/projects/js-packages/charts/src/charts/bar-chart/test/use-bar-legend-items.test.tsx index 139e29cbb540..615d1870e541 100644 --- a/projects/js-packages/charts/src/charts/bar-chart/test/use-bar-legend-items.test.tsx +++ b/projects/js-packages/charts/src/charts/bar-chart/test/use-bar-legend-items.test.tsx @@ -66,8 +66,7 @@ describe( 'useBarLegendItems', () => { ); } ); - test( 'colors and lists only the series a stacked chart draws', () => { - const drawn = twoMetricData.filter( series => series.options?.type !== 'comparison' ); + test( 'lists the stacked primaries, then one static item in the comparison total color', () => { const { result } = renderHook( () => ( { items: useBarLegendItems( twoMetricData, { layout: 'stacked', comparisonItem: true } ), @@ -75,13 +74,16 @@ describe( 'useBarLegendItems', () => { } ), { wrapper } ); - const chartColors = result.current.getBarColors( drawn, { layout: 'stacked' } ); const colors = result.current.getBarColors( twoMetricData, { layout: 'stacked' } ); - expect( [ colors[ 0 ], colors[ 2 ] ] ).toEqual( chartColors ); - expect( result.current.items.map( item => [ item.label, item.color ] ) ).toEqual( - drawn.map( ( series, index ) => [ series.label, chartColors[ index ] ] ) - ); + expect( colors[ 1 ] ).toBe( colors[ 3 ] ); + expect( + result.current.items.map( item => [ item.label, item.color, item.interactive !== false ] ) + ).toEqual( [ + [ 'Views', colors[ 0 ], true ], + [ 'Visitors', colors[ 2 ], true ], + [ 'Comparison period', colors[ 1 ], false ], + ] ); } ); test( "returns the chart legend's own items without a layout", () => { diff --git a/projects/js-packages/charts/src/charts/bar-chart/use-bar-colors.ts b/projects/js-packages/charts/src/charts/bar-chart/use-bar-colors.ts index a2d522cbba25..2e4077c34270 100644 --- a/projects/js-packages/charts/src/charts/bar-chart/use-bar-colors.ts +++ b/projects/js-packages/charts/src/charts/bar-chart/use-bar-colors.ts @@ -1,9 +1,9 @@ import { useCallback } from 'react'; import { useGlobalChartsContext } from '../../providers/chart-context/hooks/use-global-charts-context'; import { BACKGROUND_FALLBACK } from '../../providers/chart-context/private/catalog-pointers'; +import { isValidHexColor } from '../../utils/color-utils'; import { getGroupedBarColors } from './private/grouped-bars'; -import { getOverlapBarColors } from './private/overlap-bars'; -import { getDrawnSeries } from './private/stack-layout'; +import { getOverlapBarColors, neutralWithContrast } from './private/overlap-bars'; import type { BarChartLayout, SeriesData } from '../../types'; export type GetBarColors = ( @@ -29,14 +29,20 @@ export function useBarColors(): GetBarColors { const colors = series.map( ( data, index ) => getElementStyles( { data, index } ).color ); if ( layout === 'stacked' ) { - // Undrawn comparisons must not take a palette slot, so the drawn series are colored as the chart colors them. - const drawn = getDrawnSeries( series, layout ); - return series.map( ( data, index ) => { - const drawnIndex = drawn.indexOf( data ); - return drawnIndex === -1 - ? colors[ index ] - : getElementStyles( { data, index: drawnIndex } ).color; - } ); + const isComparison = ( data: SeriesData ) => data.options?.type === 'comparison'; + // Comparisons share one bar, so they take no palette slot and one color: the first one given, or a gray. + const primaries = series.filter( data => ! isComparison( data ) ); + const stroked = series.findIndex( data => isComparison( data ) && data.options?.stroke ); + const firstComparison = series.findIndex( isComparison ); + const comparisonColor = + stroked === -1 && isValidHexColor( backgroundColor ) + ? neutralWithContrast( backgroundColor ) + : colors[ stroked === -1 ? firstComparison : stroked ]; + return series.map( data => + isComparison( data ) + ? comparisonColor + : getElementStyles( { data, index: primaries.indexOf( data ) } ).color + ); } if ( layout !== 'overlap' ) { diff --git a/projects/js-packages/charts/src/charts/bar-chart/use-bar-legend-items.ts b/projects/js-packages/charts/src/charts/bar-chart/use-bar-legend-items.ts index c991eac8e267..c834604c47be 100644 --- a/projects/js-packages/charts/src/charts/bar-chart/use-bar-legend-items.ts +++ b/projects/js-packages/charts/src/charts/bar-chart/use-bar-legend-items.ts @@ -1,6 +1,6 @@ import { useMemo } from 'react'; import { useChartLegendItems } from '../../components/legend/hooks/use-chart-legend-items'; -import { getDrawnSeries } from './private/stack-layout'; +import { getComparisonTotalLabel } from './private/stack-layout'; import { useBarColors } from './use-bar-colors'; import type { ChartLegendOptions } from '../../components/legend/hooks/use-chart-legend-items'; import type { BaseLegendItem } from '../../components/legend/types'; @@ -15,7 +15,41 @@ const isComparison = ( data: SeriesData[], label: string | undefined ) => data.some( series => series.label === label && series.options?.type === 'comparison' ); /** - * Applies what a bar layout changes about a legend: overlap lists every primary before every comparison, as it draws their slots, with every swatch opaque like its bar; a collapsed grouped item takes its comparison's tint, the wider bar that frames the group. + * The series a stacked layout's legend lists: every primary, then, with a comparison item, the comparison total it draws. + * + * @param data - The chart's series. + * @param comparisonItem - The legend's `comparisonItem` option. + * @return The series, and each one's index in `data`. + */ +function getStackedLegendSeries( + data: SeriesData[], + comparisonItem: BarLegendOptions[ 'comparisonItem' ] +): { series: SeriesData[]; indexes: number[] } { + const indexes = data.flatMap( ( series, index ) => + series.options?.type === 'comparison' ? [] : [ index ] + ); + const comparison = data.findIndex( series => series.options?.type === 'comparison' ); + const series = indexes.map( index => data[ index ] ); + + if ( ! comparisonItem || comparison === -1 ) { + return { series, indexes }; + } + + return { + series: [ + ...series, + { + label: getComparisonTotalLabel( comparisonItem ), + data: [], + options: { type: 'comparison' }, + }, + ], + indexes: [ ...indexes, comparison ], + }; +} + +/** + * Applies what a bar layout changes about a legend: a stacked comparison total is a static item; overlap lists every primary before every comparison, as it draws their slots, with every swatch opaque like its bar; a collapsed grouped item takes its comparison's tint, the wider bar that frames the group. * * @param data - The series the items were built from. * @param items - The legend items. @@ -29,6 +63,15 @@ function forBarLayout( layout: BarChartLayout, seriesColors: string[] ): BaseLegendItem[] { + if ( layout === 'stacked' ) { + // The comparison total is not a series to toggle: hiding a primary already drops its comparison from it. + return items.map( item => + isComparison( data, item.seriesLabels?.[ 0 ] ) + ? { ...item, seriesLabels: undefined, interactive: false } + : item + ); + } + if ( layout === 'overlap' ) { const opaque = items.map( item => item.shapeStyle ? { ...item, shapeStyle: { ...item.shapeStyle, opacity: undefined } } : item @@ -70,15 +113,28 @@ export function useBarLegendItems( legendShape?: LegendShape< SeriesData[], number > ): BaseLegendItem[] { const { layout } = options; - const data = useMemo( () => getDrawnSeries( allData, layout ), [ allData, layout ] ); - const getBarColors = useBarColors(); - const seriesColors = useMemo( - () => ( layout ? getBarColors( data, { layout } ) : undefined ), - [ data, layout, getBarColors ] + const stacked = useMemo( + () => + layout === 'stacked' ? getStackedLegendSeries( allData, options.comparisonItem ) : undefined, + [ allData, layout, options.comparisonItem ] ); + const data = stacked?.series ?? allData; + const getBarColors = useBarColors(); + const seriesColors = useMemo( () => { + if ( ! layout ) { + return undefined; + } + const colors = getBarColors( allData, { layout } ); + return stacked ? stacked.indexes.map( index => colors[ index ] ) : colors; + }, [ allData, stacked, layout, getBarColors ] ); const chartLegendOptions = useMemo( - (): ChartLegendOptions => ( { ...options, seriesColors } ), - [ options, seriesColors ] + (): ChartLegendOptions => ( { + ...options, + // A stacked layout lists its comparison total itself. + ...( stacked && { comparisonItem: false, comparisonSeriesItems: undefined } ), + seriesColors, + } ), + [ options, stacked, seriesColors ] ); const items = useChartLegendItems( data, chartLegendOptions, legendShape ); diff --git a/projects/js-packages/charts/src/types.ts b/projects/js-packages/charts/src/types.ts index 79d42e405cd7..ced4212703c2 100644 --- a/projects/js-packages/charts/src/types.ts +++ b/projects/js-packages/charts/src/types.ts @@ -317,7 +317,7 @@ export type BarStyles = { }; /** - * How a bar chart places its series in a category. `grouped` puts each primary series in a slot of its own; `overlap` puts every primary in one slot and every comparison in a second, and overlaps the `group`s within each slot; `stacked` stacks every primary in one bar, the first series at the bottom. + * How a bar chart places its series in a category. `grouped` puts each primary series in a slot of its own; `overlap` puts every primary in one slot and every comparison in a second, and overlaps the `group`s within each slot; `stacked` stacks every primary in one bar, the first series at the bottom, and sums every comparison into one bar in a second slot. */ export type BarChartLayout = 'grouped' | 'overlap' | 'stacked'; From 1c17394f90a4dcb46f9d8735646e1d11f75bc22b Mon Sep 17 00:00:00 2001 From: Chi-Hsuan Huang Date: Tue, 10 Nov 2026 17:25:55 +0800 Subject: [PATCH 02/28] Charts: Show the empty state and round both ends of stacked comparison totals --- .../charts/bar-chart/bar-chart.module.scss | 4 ++ .../charts/src/charts/bar-chart/bar-chart.tsx | 15 ++-- .../src/charts/bar-chart/private/index.ts | 1 - .../charts/bar-chart/private/stack-layout.ts | 13 ---- .../bar-chart/private/stacked-bar-series.tsx | 7 +- .../charts/bar-chart/stories/index.docs.mdx | 4 +- .../bar-chart/test/bar-chart-stacked.test.tsx | 69 +++++++++++++++++++ .../test/use-bar-legend-items.test.tsx | 37 ++++++++++ .../charts/bar-chart/use-bar-legend-items.ts | 26 ++++--- .../legend/hooks/use-chart-legend-items.ts | 16 ++++- 10 files changed, 155 insertions(+), 37 deletions(-) diff --git a/projects/js-packages/charts/src/charts/bar-chart/bar-chart.module.scss b/projects/js-packages/charts/src/charts/bar-chart/bar-chart.module.scss index 996b82984424..2a642ad937e3 100644 --- a/projects/js-packages/charts/src/charts/bar-chart/bar-chart.module.scss +++ b/projects/js-packages/charts/src/charts/bar-chart/bar-chart.module.scss @@ -69,6 +69,10 @@ clip-path: inset(0 round 0 0 var(--a8c-charts-border-radius-bar-chart) var(--a8c-charts-border-radius-bar-chart)); } + &--stacked :global(.visx-bar-group) rect[data-stack-end="both"] { + clip-path: inset(0 round var(--a8c-charts-border-radius-bar-chart)); + } + &--stacked :global(.visx-bar-group) rect[data-stack-end="left"] { clip-path: inset(0 round var(--a8c-charts-border-radius-bar-chart) 0 0 var(--a8c-charts-border-radius-bar-chart)); } diff --git a/projects/js-packages/charts/src/charts/bar-chart/bar-chart.tsx b/projects/js-packages/charts/src/charts/bar-chart/bar-chart.tsx index 2fb165de363f..34b4f443a477 100644 --- a/projects/js-packages/charts/src/charts/bar-chart/bar-chart.tsx +++ b/projects/js-packages/charts/src/charts/bar-chart/bar-chart.tsx @@ -4,6 +4,7 @@ import { __, sprintf } from '@wordpress/i18n'; import clsx from 'clsx'; import { Fragment, useCallback, useContext, useState, useRef, useMemo } from 'react'; import { Legend } from '../../components/legend'; +import { getComparisonItemLabel } from '../../components/legend/hooks/use-chart-legend-items'; import { XYChartTooltip, useKeyboardNavigation } from '../../components/tooltip'; import { useXYChartTheme, @@ -44,7 +45,6 @@ import { COMPARISON_TICK_GAP_FACTOR, BASE_BAND_PADDING_INNER, COMPARISON_SLOT, - getComparisonTotalLabel, isBarRendered, SlotTooltipMembers, useBarStops, @@ -262,11 +262,6 @@ const BarChartInternal: FC< BarChartProps > = ( { [ dataWithVisibleZeros, isSeriesRendered ] ); - // Check if all series are hidden - const allSeriesHidden = useMemo( () => { - return seriesWithVisibility.every( ( { isVisible } ) => ! isVisible ); - }, [ seriesWithVisibility ] ); - // Derive primary vs comparison entries for comparison mode support. const primaryEntries = useMemo( () => @@ -279,9 +274,15 @@ const BarChartInternal: FC< BarChartProps > = ( { const barSlots = useBarSlots( layout, seriesWithVisibility, - getComparisonTotalLabel( legendComparisonItem ) + getComparisonItemLabel( legendComparisonItem ) ); + // A stack's comparisons leave with their primaries, so it is empty once it draws nothing. + const allSeriesHidden = + barSlots?.kind === 'stacked' + ? barSlots.entries.length === 0 + : seriesWithVisibility.every( ( { isVisible } ) => ! isVisible ); + const chartOptions = useBarChartOptions( dataWithVisibleZeros, horizontal, diff --git a/projects/js-packages/charts/src/charts/bar-chart/private/index.ts b/projects/js-packages/charts/src/charts/bar-chart/private/index.ts index cbb6b4e9f635..3f4ea5a66758 100644 --- a/projects/js-packages/charts/src/charts/bar-chart/private/index.ts +++ b/projects/js-packages/charts/src/charts/bar-chart/private/index.ts @@ -21,4 +21,3 @@ export { isBarRendered } from './value-domain'; export { BandHighlight } from './band-highlight'; export { BandTooltip } from './band-tooltip'; export { COMPARISON_SLOT } from './overlap-bars'; -export { getComparisonTotalLabel } from './stack-layout'; diff --git a/projects/js-packages/charts/src/charts/bar-chart/private/stack-layout.ts b/projects/js-packages/charts/src/charts/bar-chart/private/stack-layout.ts index e4a351aa9556..7a6658cce264 100644 --- a/projects/js-packages/charts/src/charts/bar-chart/private/stack-layout.ts +++ b/projects/js-packages/charts/src/charts/bar-chart/private/stack-layout.ts @@ -1,4 +1,3 @@ -import { __ } from '@wordpress/i18n'; import { getTickDecimalsDomain } from '../../private/tick-decimals'; import { categoryKey } from './category'; import { EMPTY_DOMAIN, getBarValue } from './value-domain'; @@ -104,18 +103,6 @@ export function getStackLayout( series: SeriesData[], comparison?: ComparisonTot }; } -/** - * Names a stacked layout's comparison total after the legend's comparison item, or as that item is named by default. - * - * @param comparisonItem - The legend's `comparisonItem` option. - * @return The label. - */ -export function getComparisonTotalLabel( comparisonItem?: boolean | string ): string { - return typeof comparisonItem === 'string' - ? comparisonItem - : __( 'Comparison period', 'jetpack-charts' ); -} - /** * The series of a comparison total: at each category the comparisons have a reading, the net of their readings. * diff --git a/projects/js-packages/charts/src/charts/bar-chart/private/stacked-bar-series.tsx b/projects/js-packages/charts/src/charts/bar-chart/private/stacked-bar-series.tsx index bc971356148b..8a34f1626618 100644 --- a/projects/js-packages/charts/src/charts/bar-chart/private/stacked-bar-series.tsx +++ b/projects/js-packages/charts/src/charts/bar-chart/private/stacked-bar-series.tsx @@ -28,7 +28,7 @@ type Props = Pick< }; /** - * The side a segment rounds when it ends its drawn stack: the far end of the positives or of the negatives. + * The side a segment rounds when it ends its drawn stack: the far end of the positives or of the negatives, or both for a comparison total that spans zero. * * @param stack - The stack layout. * @param key - The series the segment is drawn for. @@ -45,12 +45,15 @@ function getStackEnd( category: DataPointDate, horizontal: boolean, clamp: ( value: number ) => number -): 'top' | 'bottom' | 'left' | 'right' | undefined { +): 'top' | 'bottom' | 'left' | 'right' | 'both' | undefined { const [ start, end ] = [ segment.start, segment.end ].map( clamp ); if ( start === end ) { return undefined; } const extent = stack.extentAt( category, key ).map( clamp ); + if ( segment.start < 0 && segment.end > 0 && start === extent[ 0 ] && end === extent[ 1 ] ) { + return 'both'; + } if ( segment.end > 0 && end === extent[ 1 ] ) { return horizontal ? 'right' : 'top'; } diff --git a/projects/js-packages/charts/src/charts/bar-chart/stories/index.docs.mdx b/projects/js-packages/charts/src/charts/bar-chart/stories/index.docs.mdx index 60feb68e3583..48081d9d4a25 100644 --- a/projects/js-packages/charts/src/charts/bar-chart/stories/index.docs.mdx +++ b/projects/js-packages/charts/src/charts/bar-chart/stories/index.docs.mdx @@ -265,9 +265,9 @@ Set `layout="stacked"` to draw every series of a category as one bar, each serie - A series with no reading at a category is skipped there, and the segment above it starts where the one below ends. - Hiding a series from the legend closes the stacks up and rescales the axis. - The tooltip covers the whole stack: every series, last series first, with a `null` reading as "No data", then the total when there is more than one reading. It sits at the end of the positive values, or of the negative ones when the category has no positive value. -- Arrow keys step one category at a time, and the selected stack is outlined as a whole. Enter hands `onDatumActivate` the top segment, while pointer callbacks report the segment under the pointer. +- Arrow keys step one category at a time, and the selected stack is outlined as a whole. Enter hands `onDatumActivate` the top segment, while pointer callbacks report the segment under the pointer. With comparisons, each category has a second stop on the comparison total after its stack; there the callbacks get the total's label as `key` and the summed point as the datum, not a series from `data`. - A bar radius (`--a8c-charts-border-radius-bar-chart`) rounds only the outer end of each stack, so the seams between segments stay flush. An outer segment shorter than the radius rounds only as far as its own length. -- `type: 'comparison'` series are summed into one bar beside each stack: the comparison period's total, comparing totals rather than segments. Hiding a series also drops the comparison of its `group` from that total. The bar takes the first comparison's `options.stroke`, or else a gray that keeps 3:1 against the background. The tooltip lists it after the total, and the legend names it with one static item when `legend.comparisonItem` is set; both use that string as its name, or "Comparison period". +- `type: 'comparison'` series are summed into one bar beside each stack: the comparison period's total, comparing totals rather than segments. Hiding a series also drops the comparison of its `group` from that total. The bar takes the `options.stroke` of the first comparison that sets one, or else a gray that keeps 3:1 against the background. Its legend item leaves the legend while the first comparison is hidden, so to drop the comparison period, leave the comparison series out of `data`. The tooltip lists it after the total, and the legend names it with one static item when `legend.comparisonItem` is set; both use that string as its name, or "Comparison period". - `showZeroValues` has no effect, and warns once in development. - Works with `orientation="horizontal"`, where the first series is the left-most segment. diff --git a/projects/js-packages/charts/src/charts/bar-chart/test/bar-chart-stacked.test.tsx b/projects/js-packages/charts/src/charts/bar-chart/test/bar-chart-stacked.test.tsx index 2f3b6e1c8d89..70b40229deef 100644 --- a/projects/js-packages/charts/src/charts/bar-chart/test/bar-chart-stacked.test.tsx +++ b/projects/js-packages/charts/src/charts/bar-chart/test/bar-chart-stacked.test.tsx @@ -355,6 +355,75 @@ describe( 'BarChart stacked layout', () => { expect( rounded( selectedRing() ) ).toEqual( rounded( previousBar() ) ); } ); + it.each( [ + [ 'vertical', [ 300, 150, 50 ], 'top' ], + [ 'horizontal', [ 300, 150, 50 ], 'right' ], + [ 'vertical', [ -30, -20, 0 ], 'bottom' ], + [ 'vertical', [ 30, -20, 0 ], 'both' ], + ] as const )( + 'rounds the outer end of a %s comparison total of %p as %s', + ( orientation, monday, end ) => { + const data = WITH_PREVIOUS.map( series => + series.options?.type === 'comparison' + ? { + ...series, + data: [ + day( + 'Mon', + monday[ [ 'Desktop', 'Mobile', 'Tablet' ].indexOf( series.group as string ) ] + ), + ], + } + : series + ); + renderStacked( { data, orientation } ); + + expect( barRects()[ 5 ] ).toHaveAttribute( 'data-stack-end', end ); + } + ); + + it( 'shows the empty state once every stacked series is hidden, comparisons and all', () => { + renderStacked( { + data: WITH_PREVIOUS, + showLegend: true, + legend: { interactive: true }, + defaultHiddenSeries: DATA.map( series => series.label ), + } ); + + expect( screen.queryAllByTestId( 'bar-chart-stacked-bar' ) ).toHaveLength( 0 ); + expect( screen.getByText( /All series are hidden/ ) ).toBeInTheDocument(); + } ); + + it( 'leaves the comparison item out of the legend while the comparisons are hidden', () => { + renderStacked( { + data: WITH_PREVIOUS, + showLegend: true, + legend: { comparisonItem: 'Prev. 7 days' }, + defaultHiddenSeries: WITH_PREVIOUS.slice( 3 ).map( series => series.label ), + } ); + + expect( barRects() ).toHaveLength( 5 ); + expect( screen.queryByText( 'Prev. 7 days' ) ).not.toBeInTheDocument(); + } ); + + it( 'keeps a comparison in the total while a primary of its group is shown', async () => { + const user = userEvent.setup(); + const data: SeriesData[] = [ + { label: 'Posts', group: 'web', data: [ day( 'Mon', 100 ) ] }, + { label: 'Pages', group: 'web', data: [ day( 'Mon', 50 ) ] }, + { + label: 'Web (prev)', + group: 'web', + options: { type: 'comparison' }, + data: [ day( 'Mon', 300 ) ], + }, + ]; + renderStacked( { data, showLegend: true, legend: { interactive: true } } ); + + await user.click( screen.getByRole( 'button', { name: /Pages/ } ) ); + expect( previousBar( 0, 1 ).height / barIn( data, 'Posts' ).height ).toBeCloseTo( 300 / 100 ); + } ); + it( "drops a hidden series' comparison from the total", async () => { const user = userEvent.setup(); renderStacked( { data: WITH_PREVIOUS, showLegend: true, legend: { interactive: true } } ); diff --git a/projects/js-packages/charts/src/charts/bar-chart/test/use-bar-legend-items.test.tsx b/projects/js-packages/charts/src/charts/bar-chart/test/use-bar-legend-items.test.tsx index 615d1870e541..08a6f6e99f9a 100644 --- a/projects/js-packages/charts/src/charts/bar-chart/test/use-bar-legend-items.test.tsx +++ b/projects/js-packages/charts/src/charts/bar-chart/test/use-bar-legend-items.test.tsx @@ -1,6 +1,8 @@ import { renderHook } from '@testing-library/react'; import { useChartLegendItems } from '../../../components/legend'; import { GlobalChartsProvider } from '../../../providers'; +import { useGlobalChartsContext } from '../../../providers/chart-context/hooks/use-global-charts-context'; +import { neutralWithContrast } from '../private/overlap-bars'; import { useBarColors } from '../use-bar-colors'; import { useBarLegendItems } from '../use-bar-legend-items'; import type { SeriesData } from '../../../types'; @@ -86,6 +88,41 @@ describe( 'useBarLegendItems', () => { ] ); } ); + test.each( [ undefined, false ] )( + 'lists only the stacked primaries with comparisonItem %p', + comparisonItem => { + const { result } = renderHook( + () => useBarLegendItems( twoMetricData, { layout: 'stacked', comparisonItem } ), + { wrapper } + ); + + expect( result.current.map( item => item.label ) ).toEqual( [ 'Views', 'Visitors' ] ); + } + ); + + test.each( [ + [ 'a gray with 3:1 against the background', undefined ], + [ "the first comparison's own stroke", '#aa3355' ], + ] )( 'colors every stacked comparison in %s', ( _case, stroke ) => { + const data = twoMetricData.map( series => + series.label === 'Visitors — previous' && stroke + ? { ...series, options: { ...series.options, stroke } } + : series + ); + const { result } = renderHook( + () => ( { + colors: useBarColors()( data, { layout: 'stacked' } ), + background: useGlobalChartsContext().backgroundColor ?? '#ffffff', + } ), + { wrapper } + ); + const { colors, background } = result.current; + + expect( [ colors[ 1 ], colors[ 3 ] ] ).toEqual( + Array( 2 ).fill( stroke ?? neutralWithContrast( background ) ) + ); + } ); + test( "returns the chart legend's own items without a layout", () => { const options = { collapseGroups: true }; const { result } = renderHook( diff --git a/projects/js-packages/charts/src/charts/bar-chart/use-bar-legend-items.ts b/projects/js-packages/charts/src/charts/bar-chart/use-bar-legend-items.ts index c834604c47be..5c5203908edd 100644 --- a/projects/js-packages/charts/src/charts/bar-chart/use-bar-legend-items.ts +++ b/projects/js-packages/charts/src/charts/bar-chart/use-bar-legend-items.ts @@ -1,6 +1,8 @@ import { useMemo } from 'react'; -import { useChartLegendItems } from '../../components/legend/hooks/use-chart-legend-items'; -import { getComparisonTotalLabel } from './private/stack-layout'; +import { + useChartLegendItems, + getComparisonItemLabel, +} from '../../components/legend/hooks/use-chart-legend-items'; import { useBarColors } from './use-bar-colors'; import type { ChartLegendOptions } from '../../components/legend/hooks/use-chart-legend-items'; import type { BaseLegendItem } from '../../components/legend/types'; @@ -19,12 +21,12 @@ const isComparison = ( data: SeriesData[], label: string | undefined ) => * * @param data - The chart's series. * @param comparisonItem - The legend's `comparisonItem` option. - * @return The series, and each one's index in `data`. + * @return The series, each one's index in `data`, and the comparison the total's item is shown with. */ function getStackedLegendSeries( data: SeriesData[], comparisonItem: BarLegendOptions[ 'comparisonItem' ] -): { series: SeriesData[]; indexes: number[] } { +): { series: SeriesData[]; indexes: number[]; describes?: string } { const indexes = data.flatMap( ( series, index ) => series.options?.type === 'comparison' ? [] : [ index ] ); @@ -39,12 +41,13 @@ function getStackedLegendSeries( series: [ ...series, { - label: getComparisonTotalLabel( comparisonItem ), + label: getComparisonItemLabel( comparisonItem ), data: [], options: { type: 'comparison' }, }, ], indexes: [ ...indexes, comparison ], + describes: data[ comparison ].label, }; } @@ -55,19 +58,21 @@ function getStackedLegendSeries( * @param items - The legend items. * @param layout - The layout the bars are drawn in. * @param seriesColors - Each series' bar color, by index. + * @param describes - The comparison a stacked total's item leaves the legend with while it is hidden. * @return The legend items. */ function forBarLayout( data: SeriesData[], items: BaseLegendItem[], layout: BarChartLayout, - seriesColors: string[] + seriesColors: string[], + describes?: string ): BaseLegendItem[] { if ( layout === 'stacked' ) { // The comparison total is not a series to toggle: hiding a primary already drops its comparison from it. return items.map( item => isComparison( data, item.seriesLabels?.[ 0 ] ) - ? { ...item, seriesLabels: undefined, interactive: false } + ? { ...item, seriesLabels: undefined, interactive: false, describesSeries: describes } : item ); } @@ -139,7 +144,10 @@ export function useBarLegendItems( const items = useChartLegendItems( data, chartLegendOptions, legendShape ); return useMemo( - () => ( layout && seriesColors ? forBarLayout( data, items, layout, seriesColors ) : items ), - [ data, items, layout, seriesColors ] + () => + layout && seriesColors + ? forBarLayout( data, items, layout, seriesColors, stacked?.describes ) + : items, + [ data, items, layout, seriesColors, stacked ] ); } diff --git a/projects/js-packages/charts/src/components/legend/hooks/use-chart-legend-items.ts b/projects/js-packages/charts/src/components/legend/hooks/use-chart-legend-items.ts index e9409e25274f..78787805ae22 100644 --- a/projects/js-packages/charts/src/components/legend/hooks/use-chart-legend-items.ts +++ b/projects/js-packages/charts/src/components/legend/hooks/use-chart-legend-items.ts @@ -46,6 +46,18 @@ export interface ChartLegendOptions { seriesColors?: string[]; } +/** + * Names the comparison: the `comparisonItem` string, or "Comparison period". + * + * @param comparisonItem - The legend's `comparisonItem` option. + * @return The label. + */ +export function getComparisonItemLabel( comparisonItem?: boolean | string ): string { + return typeof comparisonItem === 'string' && comparisonItem + ? comparisonItem + : __( 'Comparison period', 'jetpack-charts' ); +} + /** * Wraps `getElementStyles` so a swatch takes the color given for its series. * @param getElementStyles - Function to get element styles @@ -441,9 +453,7 @@ export function useChartLegendItems< ? buildComparisonLegendItem( seriesData, items, - typeof comparisonItem === 'string' - ? comparisonItem - : __( 'Comparison period', 'jetpack-charts' ), + getComparisonItemLabel( comparisonItem ), getElementStyles, legendShape ) From b81eb1833cc242b350a6cf1c9838ecb3e347e94e Mon Sep 17 00:00:00 2001 From: Chi-Hsuan Huang Date: Wed, 11 Nov 2026 11:29:28 +0800 Subject: [PATCH 03/28] Premium Analytics: Add a stacked bar view to the Devices widget --- .../changelog/pa-devices-stacked | 4 + .../packages/data/src/hooks/index.ts | 2 +- .../data/src/hooks/use-stats-devices.ts | 33 +++++- .../stats/__tests__/time-series.test.ts | 27 +++++ .../queries/__tests__/stats-queries.test.ts | 23 +++- .../packages/data/src/queries/index.ts | 2 +- .../data/src/queries/stats-devices-query.ts | 43 +++++++- .../packages/icons/README.md | 8 +- .../icons/src/chart-half-ring/index.tsx | 13 +++ .../packages/icons/src/library.ts | 1 + .../packages/icons/src/resolve.ts | 2 + ...arative-bar-chart-previous-period.test.tsx | 44 +++++++- .../comparative-bar-chart.tsx | 82 ++++++++++++-- .../packages/widgets-toolkit/src/index.ts | 2 + .../src/stories/mocks/register-stats-mocks.ts | 59 ++++++++++ .../widgets/devices/render.tsx | 103 +++++++++++++++++- .../stories/devices-widget.stories.tsx | 14 +++ .../devices/use-device-views-over-time.ts | 94 ++++++++++++++++ .../widgets/devices/use-device-views.ts | 2 +- .../widgets/devices/widget.json | 25 ++++- .../widgets/devices/widget.ts | 52 +++++++++ .../widgets/traffic-chart/render.tsx | 6 +- .../use-previous-period-shown.ts | 16 ++- .../jetpack/changelog/pa-devices-stacked | 4 + .../changelog/pa-devices-stacked | 4 + .../stats/changelog/pa-devices-stacked | 4 + 26 files changed, 622 insertions(+), 47 deletions(-) create mode 100644 projects/packages/premium-analytics/changelog/pa-devices-stacked create mode 100644 projects/packages/premium-analytics/packages/icons/src/chart-half-ring/index.tsx create mode 100644 projects/packages/premium-analytics/widgets/devices/use-device-views-over-time.ts create mode 100644 projects/packages/premium-analytics/widgets/devices/widget.ts rename projects/packages/premium-analytics/widgets/{traffic-chart => }/use-previous-period-shown.ts (57%) create mode 100644 projects/plugins/jetpack/changelog/pa-devices-stacked create mode 100644 projects/plugins/premium-analytics/changelog/pa-devices-stacked create mode 100644 projects/plugins/stats/changelog/pa-devices-stacked diff --git a/projects/packages/premium-analytics/changelog/pa-devices-stacked b/projects/packages/premium-analytics/changelog/pa-devices-stacked new file mode 100644 index 000000000000..203bba8d5ab7 --- /dev/null +++ b/projects/packages/premium-analytics/changelog/pa-devices-stacked @@ -0,0 +1,4 @@ +Significance: minor +Type: added + +Devices: Add a bar chart of views by device over time, with the previous period's total beside each bar. diff --git a/projects/packages/premium-analytics/packages/data/src/hooks/index.ts b/projects/packages/premium-analytics/packages/data/src/hooks/index.ts index 08d8fbfe3adb..fc41ac9761a6 100644 --- a/projects/packages/premium-analytics/packages/data/src/hooks/index.ts +++ b/projects/packages/premium-analytics/packages/data/src/hooks/index.ts @@ -131,7 +131,7 @@ export { useStatsUtm, type StatsUtmParams, type StatsUtmResponse } from './use-s export { useStatsHighlights } from './use-stats-highlights'; export type { StatsHighlightsParams, StatsHighlightsResponse } from './use-stats-highlights'; export { useStatsTags, type StatsTagsParams, type StatsTagsResponse } from './use-stats-tags'; -export { useStatsDevices } from './use-stats-devices'; +export { useStatsDevices, useStatsDevicesPeriods } from './use-stats-devices'; export { useStatsAppSiteHasNeverPublishedPost, type StatsAppSiteHasNeverPublishedPostParams, diff --git a/projects/packages/premium-analytics/packages/data/src/hooks/use-stats-devices.ts b/projects/packages/premium-analytics/packages/data/src/hooks/use-stats-devices.ts index 153c07eb7679..57bd7f58d1b3 100644 --- a/projects/packages/premium-analytics/packages/data/src/hooks/use-stats-devices.ts +++ b/projects/packages/premium-analytics/packages/data/src/hooks/use-stats-devices.ts @@ -2,13 +2,23 @@ * Internal dependencies */ import { mergeStatsDevicesComparisonRows } from '../processing/stats'; -import { statsDevicesQuery, type StatsDeviceProperty } from '../queries/stats-devices-query'; -import { createStatsListReportHook, splitStatsListOptions } from './use-stats-report'; +import { + statsDevicesPeriodsQuery, + statsDevicesQuery, + type StatsDeviceProperty, + type StatsDevicesParams as StatsDevicesQueryParams, +} from '../queries/stats-devices-query'; +import { + createStatsListReportHook, + splitStatsListOptions, + useStatsReport, +} from './use-stats-report'; import type { UseStatsOptions } from './use-stats-report'; import type { StatsDevicesComparisonItem, StatsDevicesItem, StatsNormalizedReport, + StatsTimeSeriesReport, } from '../processing/stats'; import type { StatsReportParams } from '../queries/stats-query'; import type { ReportParams } from '../utils/search'; @@ -37,3 +47,22 @@ export function useStatsDevices( params: StatsDevicesParams, options?: StatsDevi options ); } + +/** + * Views per device value in each `period` bucket of the range, and of the comparison range when it is on. + * + * @param params - The report params, with the bucket size as `period`. + * @param options - Query options. + * @return The primary and comparison reports. + */ +export function useStatsDevicesPeriods( + params: ReportParams & Pick< StatsDevicesQueryParams, 'deviceProperty' | 'period' >, + options?: UseStatsOptions +) { + return useStatsReport< StatsDevicesQueryParams, StatsTimeSeriesReport >( + statsDevicesPeriodsQuery, + params as StatsDevicesQueryParams, + [ 'stats', 'devices-periods', '__comparison__', 'disabled' ], + options + ); +} diff --git a/projects/packages/premium-analytics/packages/data/src/processing/stats/__tests__/time-series.test.ts b/projects/packages/premium-analytics/packages/data/src/processing/stats/__tests__/time-series.test.ts index c66e8d273678..1ffb28f6ea41 100644 --- a/projects/packages/premium-analytics/packages/data/src/processing/stats/__tests__/time-series.test.ts +++ b/projects/packages/premium-analytics/packages/data/src/processing/stats/__tests__/time-series.test.ts @@ -226,6 +226,33 @@ describe( 'Stats time-series normalizer', () => { ] ); } ); + // The `stats/devices` `unit` mode: one record of counts per period, keyed by its first day. + it( 'reads a field per key of a days map, clipping the first week to the range', () => { + const result = sanitizeStatsTimeSeriesResponse( + { + date: '2026-06-16', + unit: 'week', + days: { + '2026-06-08': { desktop: 40, mobile: 12 }, + '2026-06-15': { desktop: 20, mobile: 6, tablet: 1 }, + }, + utc_offset: 0, + }, + { start_date: '2026-06-10', date: '2026-06-16' } + ); + + expect( result.summary ).toEqual( + expect.objectContaining( { desktop: 60, mobile: 18, tablet: 1 } ) + ); + expect( result.summary ).not.toHaveProperty( 'utc_offset' ); + expect( + result.data.map( ( { date_start, desktop, mobile } ) => [ date_start, desktop, mobile ] ) + ).toEqual( [ + [ '2026-06-10T00:00:00', 40, 12 ], + [ '2026-06-15T00:00:00', 20, 6 ], + ] ); + } ); + it( 'normalizes email opens timelines nested under the timeline key', () => { const result = sanitizeStatsEmailTimeSeriesResponse( emailOpensTimeSeriesFixture, { period: 'day', diff --git a/projects/packages/premium-analytics/packages/data/src/queries/__tests__/stats-queries.test.ts b/projects/packages/premium-analytics/packages/data/src/queries/__tests__/stats-queries.test.ts index 07a6e2b553d9..64c8c5f1474e 100644 --- a/projects/packages/premium-analytics/packages/data/src/queries/__tests__/stats-queries.test.ts +++ b/projects/packages/premium-analytics/packages/data/src/queries/__tests__/stats-queries.test.ts @@ -18,7 +18,7 @@ import { statsArchivesQuery } from '../stats-archives-query'; import { statsAuthorAllTimeOrApproximateQuery, statsAuthorQuery } from '../stats-author-query'; import { statsClicksQuery } from '../stats-clicks-query'; import { statsCountryViewsQuery } from '../stats-country-views-query'; -import { statsDevicesQuery } from '../stats-devices-query'; +import { statsDevicesPeriodsQuery, statsDevicesQuery } from '../stats-devices-query'; import { statsEmailClicksBreakdownQuery, statsEmailOpensBreakdownQuery, @@ -774,6 +774,27 @@ describe( 'Stats query factories', () => { ); } ); + // A shared key would hand the semi-circle's totals to the bars, and `summarize` would collapse the buckets. + it( 'asks devices for buckets of the interval under a key of their own', () => { + const query = statsDevicesPeriodsQuery( { + from: '2026-01-01', + to: '2026-06-07', + interval: 'week', + } ); + + expect( query.queryKey ).toEqual( [ + 'stats', + 'devices-screensize-periods', + '1.1', + 'stats/devices/screensize', + 'GET', + { unit: 'week', date: '2026-06-07', start_date: '2026-01-01' }, + undefined, + 'timeSeries', + 'UTC', + ] ); + } ); + it( 'keeps list reports day-bucketed when the dashboard interval is coarser', () => { const query = statsTopPostsQuery( { from: '2026-01-01', diff --git a/projects/packages/premium-analytics/packages/data/src/queries/index.ts b/projects/packages/premium-analytics/packages/data/src/queries/index.ts index e7839b503f31..86bcb00ba6a8 100644 --- a/projects/packages/premium-analytics/packages/data/src/queries/index.ts +++ b/projects/packages/premium-analytics/packages/data/src/queries/index.ts @@ -58,7 +58,7 @@ export { statsInsightsQuery } from './stats-insights-query'; export { statsUtmQuery } from './stats-utm-query'; export { statsHighlightsQuery } from './stats-highlights-query'; export { statsTagsQuery } from './stats-tags-query'; -export { statsDevicesQuery } from './stats-devices-query'; +export { statsDevicesQuery, statsDevicesPeriodsQuery } from './stats-devices-query'; export { statsAppSiteHasNeverPublishedPostQuery, type StatsAppSiteHasNeverPublishedPostParams, diff --git a/projects/packages/premium-analytics/packages/data/src/queries/stats-devices-query.ts b/projects/packages/premium-analytics/packages/data/src/queries/stats-devices-query.ts index a2fb2cc779e1..9cc31a70b76f 100644 --- a/projects/packages/premium-analytics/packages/data/src/queries/stats-devices-query.ts +++ b/projects/packages/premium-analytics/packages/data/src/queries/stats-devices-query.ts @@ -1,13 +1,20 @@ /** * Internal dependencies */ -import { statsReportQuery, type StatsReportParams } from './stats-query'; +import { reportParamsToStatsQueryParams, statsQueryParamsToApiParams } from '../utils/stats-params'; +import { + statsProxyQuery, + statsReportQuery, + type StatsReportParams, + type StatsReportQueryOptions, +} from './stats-query'; +import type { StatsProxyParams } from '../api'; export type StatsDeviceProperty = 'screensize' | 'browser' | 'platform' | 'client_type'; -export const statsDevicesQuery = ( - params: StatsReportParams & { deviceProperty?: StatsDeviceProperty } -) => { +export type StatsDevicesParams = StatsReportParams & { deviceProperty?: StatsDeviceProperty }; + +export const statsDevicesQuery = ( params: StatsDevicesParams ) => { const deviceProperty = params.deviceProperty ?? 'screensize'; return statsReportQuery( @@ -17,3 +24,31 @@ export const statsDevicesQuery = ( 'devices' ); }; + +/** + * Views per device value in each `period` bucket of the range, from the endpoint's `unit` mode. + * + * @param params - The report range, its `period`, and the device property. + * @return The query options. + */ +export const statsDevicesPeriodsQuery = ( + params: StatsDevicesParams +): StatsReportQueryOptions< 'timeSeries' > => { + const deviceProperty = params.deviceProperty ?? 'screensize'; + const apiParams = statsQueryParamsToApiParams( reportParamsToStatsQueryParams( params ) ); + // `start_date` + `date` bound the window, as for `stats/visits`; `summarize` would collapse the buckets. + const periodsParams: StatsProxyParams = { + unit: apiParams.period, + date: apiParams.date, + start_date: apiParams.start_date, + }; + + return statsProxyQuery( { + name: `devices-${ deviceProperty }-periods`, + version: '1.1', + endpoint: `stats/devices/${ deviceProperty }`, + params: periodsParams, + sanitizer: 'timeSeries', + enabled: !! ( periodsParams.date || periodsParams.start_date ), + } ); +}; diff --git a/projects/packages/premium-analytics/packages/icons/README.md b/projects/packages/premium-analytics/packages/icons/README.md index 6db0be5bfec0..ea9a49f05486 100644 --- a/projects/packages/premium-analytics/packages/icons/README.md +++ b/projects/packages/premium-analytics/packages/icons/README.md @@ -5,9 +5,9 @@ lookup that turns the `jpa/` reference a `widget.json` carries into one of ## The dashboard's own icons -Branded multi-fill illustrations, fills driven by `var(--wpds-color-*)` tokens, plus two glyphs -upstream lacks: `chartLine`, drawn as the pair of `chartBar`, and `jetpack`, the logo in its -brand colors. They are intentionally distinct from the 24×24 monochrome glyphs of +Branded multi-fill illustrations, fills driven by `var(--wpds-color-*)` tokens, plus the glyphs +upstream lacks: `chartLine` and `chartHalfRing`, drawn as pairs of `chartBar`, and `jetpack`, the +logo in its brand colors. They are intentionally distinct from the 24×24 monochrome glyphs of `@wordpress/icons`. Where one of those is enough, import it from `@wordpress/icons` rather than re-exporting it here. @@ -45,7 +45,7 @@ lookupWidgetIcon( 'core/calendar' ); // null ## Exports -Icons: `calendar`, `channel`, `chartLine`, `coupon`, `customer`, `device`, `goal`, `jetpack`, +Icons: `calendar`, `channel`, `chartHalfRing`, `chartLine`, `coupon`, `customer`, `device`, `goal`, `jetpack`, `location`, `megaphone`, `payment`, `paymentReturn`, `productBlouse`, `reports`, `search`, `tag`. Lookup: `lookupWidgetIcon`, `resolveWidgetIcon`. diff --git a/projects/packages/premium-analytics/packages/icons/src/chart-half-ring/index.tsx b/projects/packages/premium-analytics/packages/icons/src/chart-half-ring/index.tsx new file mode 100644 index 000000000000..019164330ed9 --- /dev/null +++ b/projects/packages/premium-analytics/packages/icons/src/chart-half-ring/index.tsx @@ -0,0 +1,13 @@ +/** + * External dependencies + */ +import { SVG, Path } from '@wordpress/primitives'; + +/** + * A semi-circle chart, as a 24px control glyph on the `chartBar` grid, to pair with it in a control. + */ +export const chartHalfRing = ( + + + +); diff --git a/projects/packages/premium-analytics/packages/icons/src/library.ts b/projects/packages/premium-analytics/packages/icons/src/library.ts index 4c9ec5310d44..2be0988e97dc 100644 --- a/projects/packages/premium-analytics/packages/icons/src/library.ts +++ b/projects/packages/premium-analytics/packages/icons/src/library.ts @@ -13,4 +13,5 @@ export { search } from './search'; export { payment } from './payment'; export { tag } from './tag'; export { jetpack } from './jetpack'; +export { chartHalfRing } from './chart-half-ring'; export { chartLine } from './chart-line'; diff --git a/projects/packages/premium-analytics/packages/icons/src/resolve.ts b/projects/packages/premium-analytics/packages/icons/src/resolve.ts index d19f805f62b9..f387cf5354e7 100644 --- a/projects/packages/premium-analytics/packages/icons/src/resolve.ts +++ b/projects/packages/premium-analytics/packages/icons/src/resolve.ts @@ -41,6 +41,7 @@ import { */ import { channel, + chartHalfRing, chartLine, coupon, customer, @@ -98,6 +99,7 @@ const ICONS: Record< string, ReactElement > = { video, wordpress, channel, + 'chart-half-ring': chartHalfRing, 'chart-line': chartLine, coupon, customer, diff --git a/projects/packages/premium-analytics/packages/widgets-toolkit/src/components/chart-comparative-bar/__tests__/comparative-bar-chart-previous-period.test.tsx b/projects/packages/premium-analytics/packages/widgets-toolkit/src/components/chart-comparative-bar/__tests__/comparative-bar-chart-previous-period.test.tsx index 1ccfb50c3ef6..7c91370744de 100644 --- a/projects/packages/premium-analytics/packages/widgets-toolkit/src/components/chart-comparative-bar/__tests__/comparative-bar-chart-previous-period.test.tsx +++ b/projects/packages/premium-analytics/packages/widgets-toolkit/src/components/chart-comparative-bar/__tests__/comparative-bar-chart-previous-period.test.tsx @@ -122,10 +122,19 @@ describe( 'ComparativeBarChart previous-period toggle', () => { const setupUser = () => userEvent.setup( { advanceTimers: jest.advanceTimersByTime } ); - it.each( [ false, true ] )( - 'draws the previous period only when previousPeriodShown is true (%s)', - shown => { - renderChart( { previousPeriodShown: shown, onPreviousPeriodShownChange: jest.fn() } ); + it.each( [ + [ false, 'overlap' ], + [ true, 'overlap' ], + [ false, 'stacked' ], + [ true, 'stacked' ], + ] as const )( + 'draws the previous period only when previousPeriodShown is %s, in a %s layout', + ( shown, layout ) => { + renderChart( { + layout, + previousPeriodShown: shown, + onPreviousPeriodShownChange: jest.fn(), + } ); expect( previousPeriodItem() ).toHaveAttribute( 'aria-pressed', String( shown ) ); expect( drawnLabels() ).toEqual( @@ -232,6 +241,33 @@ describe( 'ComparativeBarChart previous-period toggle', () => { ] ); } ); + it( "totals a stack's rows in its tooltip, without the chart's own previous-total entry", () => { + renderChart( { layout: 'stacked', previousPeriodShown: true } ); + + const entry = ( key: string, value: number ) => ( { datum: { date: JULY_1, value }, key } ); + /* eslint-disable testing-library/render-result-naming-convention -- + `renderTooltip` is the chart's prop, not testing-library's `render()`. */ + const tooltip = lastBarChart().renderTooltip( { + tooltipData: { + nearestDatum: entry( 'Views', 100 ), + datumByKey: { + Views: { ...entry( 'Views', 100 ), index: 0 }, + Visitors: { ...entry( 'Visitors', 40 ), index: 1 }, + 'Comparison period': { ...entry( 'Comparison period', 110 ), index: 2 }, + }, + }, + } ); + /* eslint-enable testing-library/render-result-naming-convention */ + + expect( + tooltip?.props.model.rows.map( row => [ row.name, row.value, row.previous?.value ] ) + ).toEqual( [ + [ 'Views', 100, 80 ], + [ 'Visitors', 40, 30 ], + [ 'Total', 140, 110 ], + ] ); + } ); + it( 'keeps the current-period bar colors when the previous period is toggled', () => { const view = renderChart( { previousPeriodShown: false } ); const hiddenColors = [ colorOf( 'Views' ), colorOf( 'Visitors' ) ]; diff --git a/projects/packages/premium-analytics/packages/widgets-toolkit/src/components/chart-comparative-bar/comparative-bar-chart.tsx b/projects/packages/premium-analytics/packages/widgets-toolkit/src/components/chart-comparative-bar/comparative-bar-chart.tsx index a67b347a26b8..933c2338f3a5 100644 --- a/projects/packages/premium-analytics/packages/widgets-toolkit/src/components/chart-comparative-bar/comparative-bar-chart.tsx +++ b/projects/packages/premium-analytics/packages/widgets-toolkit/src/components/chart-comparative-bar/comparative-bar-chart.tsx @@ -14,6 +14,7 @@ import { formatMetricValue, type DateFormatName, } from '@jetpack-premium-analytics/formatters'; +import { __ } from '@wordpress/i18n'; import clsx from 'clsx'; import { useCallback, useId, useMemo } from 'react'; /** @@ -37,7 +38,7 @@ import styles from './comparative-bar-chart.module.scss'; import type { ComparativeBarChartSeries } from './types'; import type { DataFormat } from '../../types'; import type { ComparativeDatePointDate, TooltipExtraSeries } from '../chart-comparative-line/types'; -import type { TooltipStyle } from '../chart-tooltip'; +import type { DatedTooltipModel, TooltipStyle } from '../chart-tooltip'; import type { ComponentProps } from 'react'; type BarChartProps = ComponentProps< typeof BarChart >; @@ -114,14 +115,14 @@ export type ComparativeBarChartProps = { tooltipExtras?: TooltipExtraSeries[]; /** - * The bar chart's layout. `overlap` draws each `group` inside the one before it, with the previous period in a slot beside the current one; the tooltip and legend swatches then take the chart's bar colors, and one legend item names the previous period. + * The bar chart's layout. `overlap` draws each `group` inside the one before it, with the previous period in a slot beside the current one; `stacked` stacks the groups and draws the previous period's total beside them, and its tooltip adds a Total row. In both, the tooltip and legend swatches take the chart's bar colors, and one legend item names the previous period. */ layout?: BarChartLayout; /** Label of the series the reader picked, when it is not the first one drawn. Its legend item comes first and stays locked. */ primarySeries?: string; - /** Overlap layout only. Whether the previous period is drawn; with `onPreviousPeriodShownChange`, its legend item becomes a toggle. See the README. */ + /** Overlap and stacked layouts only. Whether the previous period is drawn; with `onPreviousPeriodShownChange`, its legend item becomes a toggle. See the README. */ previousPeriodShown?: boolean; /** Called with the new value when the reader presses the previous-period legend item. */ @@ -137,6 +138,45 @@ export type ComparativeBarChartProps = { onDatumActivate?: BarChartProps[ 'onDatumActivate' ]; }; +/** + * Appends a Total row to a stack's tooltip, summing its series rows and, beside them, their previous values. + * + * @param model - The tooltip model. + * @param dataFormat - How the values are formatted. + * @return The model with a Total row when more than one series has a reading. + */ +function withStackTotal( model: DatedTooltipModel, dataFormat: DataFormat ): DatedTooltipModel { + const series = model.rows.filter( row => row.indicator.kind === 'series' ); + const sum = ( values: ( number | null | undefined )[] ) => { + const readings = values.filter( ( value ): value is number => typeof value === 'number' ); + return readings.length ? readings.reduce( ( total, value ) => total + value, 0 ) : null; + }; + + if ( series.filter( row => row.value !== null ).length < 2 ) { + return model; + } + + const blank = { kind: 'blank' } as const; + const hasPrevious = series.some( row => row.previous ); + + return { + ...model, + rows: [ + ...model.rows, + { + key: '__stack_total', + name: __( 'Total', 'jetpack-premium-analytics-pkg' ), + dataFormat, + indicator: blank, + value: sum( series.map( row => row.value ) ), + ...( hasPrevious && { + previous: { value: sum( series.map( row => row.previous?.value ) ), indicator: blank }, + } ), + }, + ], + }; +} + /** * A date-keyed bar chart with previous-period comparison, built on * `@automattic/charts` `BarChart`. Styling is left to the theme, whose @@ -174,8 +214,8 @@ export function ComparativeBarChart( { const chartId = providedChartId ?? fallbackChartId; const { isSeriesVisible } = useGlobalChartsContext(); const getBarColors = useBarColors(); - const overlapLayout = layout === 'overlap' ? layout : undefined; - const previousPeriodToggle = overlapLayout !== undefined && previousPeriodShown !== undefined; + const slotLayout = layout === 'overlap' || layout === 'stacked' ? layout : undefined; + const previousPeriodToggle = slotLayout !== undefined && previousPeriodShown !== undefined; const interactiveLegend = legendInteractive || ( previousPeriodToggle && onPreviousPeriodShownChange !== undefined ); @@ -264,9 +304,9 @@ export function ComparativeBarChart( { return labels; }, [ alignedSeries ] ); - // Overlap paints the previous period as one slot, so one item names it, in the color of the picked metric's previous bar, or else of its widest shown bar. + // Overlap and stacked paint the previous period as one slot, so one item names it, in the color of the picked metric's previous bar, or else of its widest shown bar. const legendItems = useMemo( () => { - if ( ! overlapLayout ) { + if ( ! slotLayout ) { return comparativeLegendItems; } @@ -325,7 +365,7 @@ export function ComparativeBarChart( { }, ]; }, [ - overlapLayout, + slotLayout, comparativeLegendItems, previousPeriodToggle, pickedComparisonIndex, @@ -366,6 +406,16 @@ export function ComparativeBarChart( { const hoveredTime = hovered.date.getTime(); const augmented = { ...datumByKey }; + // A stack's previous-period total is the chart's own bar, not a series; each group's previous value is read out instead. + if ( layout === 'stacked' ) { + const labels = new Set( alignedSeries.map( ( { label } ) => label ) ); + for ( const key of Object.keys( augmented ) ) { + if ( ! labels.has( key ) ) { + delete augmented[ key ]; + } + } + } + for ( const [ index, seriesData ] of alignedSeries.entries() ) { if ( seriesData.options?.type !== 'comparison' || augmented[ seriesData.label ] ) { continue; @@ -395,7 +445,7 @@ export function ComparativeBarChart( { return { ...tooltipData, datumByKey: augmented }; }, - [ alignedSeries, primarySeriesByGroup ] + [ alignedSeries, primarySeriesByGroup, layout ] ); const renderTooltip = useCallback( @@ -410,9 +460,17 @@ export function ComparativeBarChart( { formatDate: formatTooltipBucket, } ); - return model && ; + return ( + model && ( + + ) + ); }, [ + layout, dataFormat, seriesStyles, alignedSeries, @@ -467,8 +525,8 @@ export function ComparativeBarChart( { compactWhenShort={ compactWhenShort } resizeDebounceTime={ RESIZE_DEBOUNCE_MS } // A zero-value bar has no height, so a quiet day would otherwise read as - // missing data. This draws it as a hairline stub instead. - showZeroValues + // missing data. This draws it as a hairline stub instead; a stack has no stubs. + showZeroValues={ layout !== 'stacked' } showLegend={ false } withTooltips={ hasTooltipRows } renderTooltip={ renderTooltip } diff --git a/projects/packages/premium-analytics/packages/widgets-toolkit/src/index.ts b/projects/packages/premium-analytics/packages/widgets-toolkit/src/index.ts index 7367ae759934..67d39fc47b97 100644 --- a/projects/packages/premium-analytics/packages/widgets-toolkit/src/index.ts +++ b/projects/packages/premium-analytics/packages/widgets-toolkit/src/index.ts @@ -303,6 +303,8 @@ export { toDay, defaultPeriodForInterval, buildMetricTab, + formatComparisonSeriesLabel, + getComparisonPeriodLabel, pairComparisonBuckets, type ComparisonPeriodStarts, siteChartFormatting, diff --git a/projects/packages/premium-analytics/packages/widgets-toolkit/src/stories/mocks/register-stats-mocks.ts b/projects/packages/premium-analytics/packages/widgets-toolkit/src/stories/mocks/register-stats-mocks.ts index e5482267fb80..f7f2c5e4aa01 100644 --- a/projects/packages/premium-analytics/packages/widgets-toolkit/src/stories/mocks/register-stats-mocks.ts +++ b/projects/packages/premium-analytics/packages/widgets-toolkit/src/stories/mocks/register-stats-mocks.ts @@ -1136,6 +1136,62 @@ function isComparisonRequest( path: string ): boolean { return daysFromToday > 1; } +/** + * The first day of the `unit` bucket a day falls in, as `stats/devices` keys its `days`. + * + * @param day - A UTC date. + * @param unit - The bucket size. + * @return The bucket's first day, Y-m-d. + */ +function devicesBucketStart( day: Date, unit: string ): string { + const start = new Date( day ); + if ( unit === 'week' ) { + start.setUTCDate( start.getUTCDate() - ( ( start.getUTCDay() + 6 ) % 7 ) ); + } else if ( unit === 'month' || unit === 'quarter' || unit === 'year' ) { + const month = { + month: start.getUTCMonth(), + quarter: start.getUTCMonth() - ( start.getUTCMonth() % 3 ), + year: 0, + }[ unit ]; + start.setUTCMonth( month, 1 ); + } + return start.toISOString().slice( 0, 10 ); +} + +/** + * A `stats/devices/screensize?unit=` response: views per screen size in each bucket of the window. + * + * @param query - The request's query. + * @param isComparison - Whether this is the previous period's request. + * @return The response. + */ +function buildDevicesPeriodsResponse( query: URLSearchParams, isComparison: boolean ) { + const unit = query.get( 'unit' ) || 'day'; + // The dashboard sends offset-bearing timestamps; the endpoint reads their calendar day. + const dayOf = ( value: string ) => new Date( `${ value.slice( 0, 10 ) }T00:00:00Z` ); + const end = dayOf( getRequestDate( query ) ); + const start = dayOf( query.get( 'start_date' ) || getRequestDate( query ) ); + const days: Record< string, Record< string, number > > = {}; + + for ( + let day = new Date( start ), index = 0; + day <= end; + day.setUTCDate( day.getUTCDate() + 1 ), index++ + ) { + const bucket = ( days[ devicesBucketStart( day, unit ) ] ??= { + desktop: 0, + mobile: 0, + tablet: 0, + } ); + const scale = isComparison ? 0.85 : 1; + bucket.desktop += Math.round( ( 1800 + ( ( index * 137 ) % 600 ) ) * scale ); + bucket.mobile += Math.round( ( 1400 + ( ( index * 89 ) % 500 ) ) * scale ); + bucket.tablet += Math.round( ( 200 + ( ( index * 53 ) % 150 ) ) * scale ); + } + + return { date: getRequestDate( query ).slice( 0, 10 ), unit, days, utc_offset: 0 }; +} + function getRequestDate( query: URLSearchParams ) { return query.get( 'date' ) || new Date().toISOString().slice( 0, 10 ); } @@ -1257,6 +1313,9 @@ export function getStatsMock( path: string ): unknown | null { return { top_utm_values: {}, top_posts: {} }; } + if ( subPath.startsWith( '/devices/screensize' ) && query.get( 'unit' ) ) { + return buildDevicesPeriodsResponse( query, isComparison ); + } if ( subPath.startsWith( '/devices/screensize' ) ) { return isComparison ? MOCK_DEVICES_SCREENSIZE_COMPARISON : MOCK_DEVICES_SCREENSIZE; } diff --git a/projects/packages/premium-analytics/widgets/devices/render.tsx b/projects/packages/premium-analytics/widgets/devices/render.tsx index 9e43d3e38efe..349bac23f998 100644 --- a/projects/packages/premium-analytics/widgets/devices/render.tsx +++ b/projects/packages/premium-analytics/widgets/devices/render.tsx @@ -2,12 +2,20 @@ * WordPress dependencies */ import { __ } from '@wordpress/i18n'; +import { chartInterval, useScopeLockedIntervals } from '@jetpack-premium-analytics/data'; import { + BarChartSkeleton, + ComparativeBarChart, Donut, + HEADLINE_COUNT_FORMAT, WIDGET_ROW_LIMIT, + WidgetState, describeError, + formatComparisonSeriesLabel, + getComparisonPeriodLabel, WidgetRoot, useWidgetRootContext, + type ComparativeBarChartSeries, type DonutSegmentInput, type ReportParamsFieldAttributes, } from '@jetpack-premium-analytics/widgets-toolkit'; @@ -16,14 +24,17 @@ import { useMemo } from 'react'; * Internal dependencies */ import { useNoViewsEmptyState } from '../use-no-views-empty-state'; +import { usePreviousPeriodShown } from '../use-previous-period-shown'; import useDeviceViews from './use-device-views'; +import useDeviceViewsOverTime from './use-device-views-over-time'; +import { DEVICES_PERIODS } from './widget'; +import type { DevicesAttributes, DevicesChartGranularity } from './widget'; /** * Types */ import type { WidgetRenderProps } from '@wordpress/widget-primitives'; -/** No configurable attributes; the empty record allows host-provided fields. */ -export type DevicesAttributes = Record< never, never >; +export type { DevicesAttributes } from './widget'; type DevicesRenderAttributes = DevicesAttributes & Partial< ReportParamsFieldAttributes >; type DevicesWidgetProps = WidgetRenderProps< DevicesRenderAttributes >; @@ -33,6 +44,9 @@ const PERCENTAGE_DATA_FORMAT = { options: { decimals: 1, signDisplay: 'auto' as const }, }; +const NO_VIEWS = () => + __( 'You don’t have devices recorded yet.', 'jetpack-premium-analytics-pkg' ); + function toRatio( percentage: number ) { return percentage / 100; } @@ -57,7 +71,7 @@ function DevicesInner() { ); const emptyState = useNoViewsEmptyState( { isLoading, isError, isEmpty: segments.every( segment => ! segment.value ) }, - __( 'You don’t have devices recorded yet.', 'jetpack-premium-analytics-pkg' ) + NO_VIEWS() ); return ( @@ -86,12 +100,91 @@ function DevicesInner() { } /** - * Shows screen size breakdown (Desktop / Mobile / Tablet) as a semi-circle chart. + * Views by screen size in each bucket of the range, stacked, with the previous period's total beside each stack. + * + * @param props - Component props. + * @param props.interval - The saved bucket size, if any. + * @return The chart. + */ +function DevicesBarChart( { interval }: { interval?: DevicesChartGranularity } ) { + const { reportParams } = useWidgetRootContext(); + const lockedIntervals = useScopeLockedIntervals(); + const [ previousPeriodShown, setPreviousPeriodShown ] = usePreviousPeriodShown( + 'devicesChartPreviousPeriod' + ); + const period = chartInterval( { ...reportParams, interval }, DEVICES_PERIODS, lockedIntervals ); + const { devices, isLoading, isFetching, isError, refetch } = useDeviceViewsOverTime( + reportParams, + period + ); + + const series = useMemo< ComparativeBarChartSeries[] >( + () => + devices.flatMap( device => [ + { label: device.label, group: device.key, data: device.current }, + ...( device.previous?.length + ? [ + { + label: formatComparisonSeriesLabel( device.label ), + group: device.key, + data: device.previous, + ...( device.previousAligned ? { aligned: true } : {} ), + options: { type: 'comparison' as const }, + }, + ] + : [] ), + ] ), + [ devices ] + ); + const isEmpty = devices.every( device => ! device.value ); + const emptyState = useNoViewsEmptyState( { isLoading, isError, isEmpty }, NO_VIEWS() ); + + return ( + } + > + + + ); +} + +/** + * Shows screen size breakdown (Desktop / Mobile / Tablet) as a semi-circle chart, or as stacked bars over time. */ export default function DevicesWidget( { attributes = {} }: DevicesWidgetProps ) { return ( - + { attributes.chartType === 'bar' ? ( + + ) : ( + + ) } ); } diff --git a/projects/packages/premium-analytics/widgets/devices/stories/devices-widget.stories.tsx b/projects/packages/premium-analytics/widgets/devices/stories/devices-widget.stories.tsx index 0fe5df9dae22..41c1c37bccbb 100644 --- a/projects/packages/premium-analytics/widgets/devices/stories/devices-widget.stories.tsx +++ b/projects/packages/premium-analytics/widgets/devices/stories/devices-widget.stories.tsx @@ -93,6 +93,20 @@ export const WithComparison: StoryObj< DevicesStoryControls > = { decorators: [ withWidgetCanvas ], }; +/** + * The bar view: views by screen size in each bucket of the range, stacked. Its legend can show the + * previous period's total beside each stack. + */ +export const BarChart: StoryObj< DevicesStoryControls > = { + render: ( { withComparison } ) => ( + + ), + args: { withComparison: true }, + decorators: [ withWidgetCanvas ], +}; + /** * First load: the fetch is in flight, so the widget shows its loading state. The * mock is forced to never resolve for the duration of this story. diff --git a/projects/packages/premium-analytics/widgets/devices/use-device-views-over-time.ts b/projects/packages/premium-analytics/widgets/devices/use-device-views-over-time.ts new file mode 100644 index 000000000000..729366c46549 --- /dev/null +++ b/projects/packages/premium-analytics/widgets/devices/use-device-views-over-time.ts @@ -0,0 +1,94 @@ +/** + * External dependencies + */ +import { useStatsDevicesPeriods } from '@jetpack-premium-analytics/data'; +import { buildMetricTab, formatDisplayLabel } from '@jetpack-premium-analytics/widgets-toolkit'; +import { useMemo } from 'react'; +import type { ReportParams, StatsTimeSeriesReport } from '@jetpack-premium-analytics/data'; +import type { MetricTab } from '@jetpack-premium-analytics/widgets-toolkit'; +/** + * Internal dependencies + */ +import { DEVICE_LABELS } from './use-device-views'; +import type { DevicesChartGranularity } from './widget'; + +/** Stacked bottom up in this order; any other device follows, largest first. */ +const DEVICE_ORDER = [ 'desktop', 'mobile', 'tablet' ]; + +const RANGE_FIELDS = new Set( [ 'date_start', 'date_end' ] ); + +interface DeviceViewsOverTimeState { + /** One tab per device, its views in each bucket and, with comparison on, the previous period's. */ + devices: MetricTab[]; + isLoading: boolean; + isFetching: boolean; + isError: boolean; + refetch: () => void; +} + +/** + * The devices a report counted, in stacking order. + * + * @param report - The current period's report. + * @return The device keys. + */ +function getDeviceKeys( report: StatsTimeSeriesReport | undefined ): string[] { + const totals = Object.entries( report?.summary ?? {} ).filter( + ( entry ): entry is [ string, number ] => + ! RANGE_FIELDS.has( entry[ 0 ] ) && typeof entry[ 1 ] === 'number' + ); + const rank = ( key: string ) => { + const index = DEVICE_ORDER.indexOf( key ); + return index === -1 ? DEVICE_ORDER.length : index; + }; + + return totals + .sort( ( [ a, aTotal ], [ b, bTotal ] ) => rank( a ) - rank( b ) || bTotal - aTotal ) + .map( ( [ key ] ) => key ); +} + +/** + * Screen-size views in each bucket of the range, for the Devices bar chart. + * + * @param reportParams - The dashboard range and comparison. + * @param period - The bucket size. + * @return The devices and the request state. + */ +export default function useDeviceViewsOverTime( + reportParams: ReportParams, + period: DevicesChartGranularity +): DeviceViewsOverTimeState { + const params = useMemo( + () => ( { ...reportParams, period, deviceProperty: 'screensize' as const } ), + [ reportParams, period ] + ); + const report = useStatsDevicesPeriods( params ); + const primary = report.primary.data as StatsTimeSeriesReport | undefined; + const comparison = report.comparison.data as StatsTimeSeriesReport | undefined; + const { hasComparison, timezone, periodStarts } = report; + + const devices = useMemo( + () => + getDeviceKeys( primary ).map( key => + buildMetricTab( { + primary, + comparison, + hasComparison, + field: key, + label: formatDisplayLabel( key, DEVICE_LABELS ), + zone: timezone, + periodStarts, + } ) + ), + [ primary, comparison, hasComparison, timezone, periodStarts ] + ); + + return { + devices, + isLoading: report.isLoading, + isFetching: report.isFetching, + // Placeholder data keeps the last range's bars through a failed refetch. + isError: report.isError && ! primary?.data?.length, + refetch: report.refetch, + }; +} diff --git a/projects/packages/premium-analytics/widgets/devices/use-device-views.ts b/projects/packages/premium-analytics/widgets/devices/use-device-views.ts index b45845427a29..a937ea22fd93 100644 --- a/projects/packages/premium-analytics/widgets/devices/use-device-views.ts +++ b/projects/packages/premium-analytics/widgets/devices/use-device-views.ts @@ -50,7 +50,7 @@ interface DeviceViewsState { * Maps raw API device keys to human-readable display labels. * Keys not in this map are title-cased as a fallback. */ -const DEVICE_LABELS: Record< string, string > = { +export const DEVICE_LABELS: Record< string, string > = { desktop: __( 'Desktop', 'jetpack-premium-analytics-pkg' ), mobile: __( 'Mobile', 'jetpack-premium-analytics-pkg' ), tablet: __( 'Tablet', 'jetpack-premium-analytics-pkg' ), diff --git a/projects/packages/premium-analytics/widgets/devices/widget.json b/projects/packages/premium-analytics/widgets/devices/widget.json index 1a55fc4ae571..1f8a2abaa9b7 100644 --- a/projects/packages/premium-analytics/widgets/devices/widget.json +++ b/projects/packages/premium-analytics/widgets/devices/widget.json @@ -13,5 +13,28 @@ ] }, "category": "traffic", - "presentation": "framed" + "presentation": "framed", + "attributes": [ + { + "id": "chartInterval" + }, + { + "id": "chartType", + "type": "jpa/toggle-group", + "label": "Chart type", + "relevance": "high", + "elements": [ + { + "value": "half-ring", + "label": "Semi-circle chart", + "icon": "jpa/chart-half-ring" + }, + { + "value": "bar", + "label": "Bar chart", + "icon": "jpa/chart-bar" + } + ] + } + ] } diff --git a/projects/packages/premium-analytics/widgets/devices/widget.ts b/projects/packages/premium-analytics/widgets/devices/widget.ts new file mode 100644 index 000000000000..fb6cc4cd67fa --- /dev/null +++ b/projects/packages/premium-analytics/widgets/devices/widget.ts @@ -0,0 +1,52 @@ +/** + * External dependencies + */ +import { + chartIntervalAttributeField, + chartIntervalElements, + type ChartIntervalFieldAttributes, +} from '@jetpack-premium-analytics/fields'; +import { createElement, type ComponentType } from 'react'; +import type { StatsPeriod } from '@jetpack-premium-analytics/data'; +import type { WidgetAttributeField } from '@wordpress/widget-primitives'; + +/** The bucket sizes the bar chart draws; the devices endpoint has no hourly data. */ +export const DEVICES_PERIODS = [ + 'day', + 'week', + 'month', + 'quarter', + 'year', +] as const satisfies readonly StatsPeriod[]; + +export type DevicesChartGranularity = ( typeof DEVICES_PERIODS )[ number ]; + +/** The share of each device over the range, or its views in each bucket of the range. */ +export type DevicesChartType = 'half-ring' | 'bar'; + +/** + * @property chartType - How the views are drawn. Defaults to `half-ring`. + * @property chartInterval - The bar chart's bucket size. Defaults to the one the date range suggests. + */ +export type DevicesAttributes = ChartIntervalFieldAttributes< DevicesChartGranularity > & { + chartType?: DevicesChartType; +}; + +const intervalField = chartIntervalAttributeField< DevicesAttributes >(); +type IntervalEditProps = { data: DevicesAttributes } & Record< string, unknown >; +const IntervalEdit = intervalField.Edit as ComponentType< IntervalEditProps >; + +export default { + attributes: [ + { + ...intervalField, + elements: chartIntervalElements( DEVICES_PERIODS ), + // The semi-circle reads the whole range, so only the bars have a bucket to pick. + Edit: ( props: IntervalEditProps ) => + props.data.chartType === 'bar' ? createElement( IntervalEdit, props ) : null, + }, + ] as WidgetAttributeField< DevicesAttributes >[], + example: { + attributes: {}, + }, +}; diff --git a/projects/packages/premium-analytics/widgets/traffic-chart/render.tsx b/projects/packages/premium-analytics/widgets/traffic-chart/render.tsx index 37a2245d724d..6901fc67cb9f 100644 --- a/projects/packages/premium-analytics/widgets/traffic-chart/render.tsx +++ b/projects/packages/premium-analytics/widgets/traffic-chart/render.tsx @@ -25,9 +25,9 @@ import { useMemo } from 'react'; * Internal dependencies */ import { useNoPublishedPosts } from '../use-no-published-posts'; +import { usePreviousPeriodShown } from '../use-previous-period-shown'; import { trafficIntervalExtension } from './interval-extension'; import styles from './style.module.css'; -import { usePreviousPeriodShown } from './use-previous-period-shown'; import useTrafficChart from './use-traffic-chart'; import { TRAFFIC_PERIODS, defaultChartType } from './widget'; import type { TrafficChartAttributes, TrafficChartGranularity, TrafficChartType } from './widget'; @@ -63,7 +63,9 @@ function TrafficChartInner( { chartType, interval }: TrafficChartInnerProps ) { // A host without a period to set leaves the bars inert. const { openPeriod } = useReportScope(); const lockedIntervals = useScopeLockedIntervals(); - const [ previousPeriodShown, setPreviousPeriodShown ] = usePreviousPeriodShown(); + const [ previousPeriodShown, setPreviousPeriodShown ] = usePreviousPeriodShown( + 'trafficChartPreviousPeriod' + ); const period: TrafficChartGranularity = chartInterval( { ...reportParams, interval }, TRAFFIC_PERIODS, diff --git a/projects/packages/premium-analytics/widgets/traffic-chart/use-previous-period-shown.ts b/projects/packages/premium-analytics/widgets/use-previous-period-shown.ts similarity index 57% rename from projects/packages/premium-analytics/widgets/traffic-chart/use-previous-period-shown.ts rename to projects/packages/premium-analytics/widgets/use-previous-period-shown.ts index b347d3c56c4b..669dc7b408f4 100644 --- a/projects/packages/premium-analytics/widgets/traffic-chart/use-previous-period-shown.ts +++ b/projects/packages/premium-analytics/widgets/use-previous-period-shown.ts @@ -6,18 +6,16 @@ import { useDispatch, useSelect } from '@wordpress/data'; import { store as preferencesStore } from '@wordpress/preferences'; import { useCallback } from 'react'; -const PREVIOUS_PERIOD_KEY = 'trafficChartPreviousPeriod'; - /** - * Whether the reader switched the previous period on from the chart legend. + * Whether the reader switched the previous period on from a chart's legend. * + * @param key - The dashboard preference the chart keeps it under. * @return Tuple `[ shown, setShown ]`; unset means off. */ -export function usePreviousPeriodShown(): [ boolean, ( shown: boolean ) => void ] { +export function usePreviousPeriodShown( key: string ): [ boolean, ( shown: boolean ) => void ] { const shown = useSelect( - select => - select( preferencesStore ).get( DASHBOARD_PREFERENCES_SCOPE, PREVIOUS_PERIOD_KEY ) === true, - [] + select => select( preferencesStore ).get( DASHBOARD_PREFERENCES_SCOPE, key ) === true, + [ key ] ); const { set } = useDispatch( preferencesStore ); @@ -25,10 +23,10 @@ export function usePreviousPeriodShown(): [ boolean, ( shown: boolean ) => void const setShown = useCallback( ( next: boolean ) => { if ( next !== shown ) { - void set( DASHBOARD_PREFERENCES_SCOPE, PREVIOUS_PERIOD_KEY, next ); + void set( DASHBOARD_PREFERENCES_SCOPE, key, next ); } }, - [ shown, set ] + [ shown, set, key ] ); return [ shown, setShown ]; diff --git a/projects/plugins/jetpack/changelog/pa-devices-stacked b/projects/plugins/jetpack/changelog/pa-devices-stacked new file mode 100644 index 000000000000..48c8dccfcfc4 --- /dev/null +++ b/projects/plugins/jetpack/changelog/pa-devices-stacked @@ -0,0 +1,4 @@ +Significance: minor +Type: enhancement + +Premium Analytics: Add a bar chart of views by device over time to the Devices widget, with the previous period's total beside each bar. diff --git a/projects/plugins/premium-analytics/changelog/pa-devices-stacked b/projects/plugins/premium-analytics/changelog/pa-devices-stacked new file mode 100644 index 000000000000..203bba8d5ab7 --- /dev/null +++ b/projects/plugins/premium-analytics/changelog/pa-devices-stacked @@ -0,0 +1,4 @@ +Significance: minor +Type: added + +Devices: Add a bar chart of views by device over time, with the previous period's total beside each bar. diff --git a/projects/plugins/stats/changelog/pa-devices-stacked b/projects/plugins/stats/changelog/pa-devices-stacked new file mode 100644 index 000000000000..203bba8d5ab7 --- /dev/null +++ b/projects/plugins/stats/changelog/pa-devices-stacked @@ -0,0 +1,4 @@ +Significance: minor +Type: added + +Devices: Add a bar chart of views by device over time, with the previous period's total beside each bar. From b0552419fd9b75c8b63417e6a861c4c570655d9f Mon Sep 17 00:00:00 2001 From: Chi-Hsuan Huang Date: Wed, 11 Nov 2026 11:29:44 +0800 Subject: [PATCH 04/28] Premium Analytics: Name the Devices bar chart from the widget title --- projects/packages/premium-analytics/widgets/devices/render.tsx | 1 - 1 file changed, 1 deletion(-) diff --git a/projects/packages/premium-analytics/widgets/devices/render.tsx b/projects/packages/premium-analytics/widgets/devices/render.tsx index 349bac23f998..ee5fce33c165 100644 --- a/projects/packages/premium-analytics/widgets/devices/render.tsx +++ b/projects/packages/premium-analytics/widgets/devices/render.tsx @@ -162,7 +162,6 @@ function DevicesBarChart( { interval }: { interval?: DevicesChartGranularity } ) Date: Wed, 11 Nov 2026 11:52:03 +0800 Subject: [PATCH 05/28] Premium Analytics: Count devices from both periods and fail on responses without buckets --- .../stats/__tests__/devices.test.ts | 19 ++++- .../data/src/processing/stats/devices.ts | 18 +++++ .../data/src/processing/stats/index.ts | 6 +- .../queries/__tests__/stats-queries.test.ts | 2 +- .../data/src/queries/stats-devices-query.ts | 4 +- .../packages/data/src/queries/stats-query.ts | 2 + .../chart-comparative-bar/README.md | 8 ++- .../src/default-dashboard-sections.php | 2 +- .../widgets/devices/__tests__/render.test.tsx | 52 ++++++++++++++ .../use-device-views-over-time.test.tsx | 72 +++++++++++++++++++ .../widgets/devices/render.tsx | 2 +- .../stories/devices-widget.stories.tsx | 42 ++++++++++- .../devices/use-device-views-over-time.ts | 24 ++++--- .../stats/changelog/pa-devices-stacked | 2 +- 14 files changed, 234 insertions(+), 21 deletions(-) create mode 100644 projects/packages/premium-analytics/widgets/devices/__tests__/render.test.tsx create mode 100644 projects/packages/premium-analytics/widgets/devices/__tests__/use-device-views-over-time.test.tsx diff --git a/projects/packages/premium-analytics/packages/data/src/processing/stats/__tests__/devices.test.ts b/projects/packages/premium-analytics/packages/data/src/processing/stats/__tests__/devices.test.ts index de05a38250be..c6aef78e984a 100644 --- a/projects/packages/premium-analytics/packages/data/src/processing/stats/__tests__/devices.test.ts +++ b/projects/packages/premium-analytics/packages/data/src/processing/stats/__tests__/devices.test.ts @@ -1,4 +1,8 @@ -import { mergeStatsDevicesComparisonRows, sanitizeStatsDevicesResponse } from '..'; +import { + mergeStatsDevicesComparisonRows, + sanitizeStatsDevicesPeriodsResponse, + sanitizeStatsDevicesResponse, +} from '..'; import { devicesEmptyFixture, devicesFixture } from '../__fixtures__/devices'; import type { StatsDevicesItem, StatsNormalizedReport } from '..'; @@ -75,3 +79,16 @@ describe( 'Stats devices normalizer', () => { } ); } ); } ); + +describe( 'sanitizeStatsDevicesPeriodsResponse', () => { + // An endpoint that ignored `unit` must surface as an error, not as a range with no views. + it( 'rejects a response without per-period views', () => { + expect( () => + sanitizeStatsDevicesPeriodsResponse( { top_values: { desktop: 62.3 } } ) + ).toThrow(); + } ); + + it( 'reads an empty days map as a range with no views', () => { + expect( sanitizeStatsDevicesPeriodsResponse( { unit: 'day', days: {} } ).data ).toEqual( [] ); + } ); +} ); diff --git a/projects/packages/premium-analytics/packages/data/src/processing/stats/devices.ts b/projects/packages/premium-analytics/packages/data/src/processing/stats/devices.ts index ff5e4ec6d824..ed43661d14cc 100644 --- a/projects/packages/premium-analytics/packages/data/src/processing/stats/devices.ts +++ b/projects/packages/premium-analytics/packages/data/src/processing/stats/devices.ts @@ -2,6 +2,7 @@ * Internal dependencies */ import { safeParseFloat } from '../../utils/parsing'; +import { sanitizeStatsTimeSeriesResponse } from './time-series'; import { coerceStatsRecord, createStatsListDataPoint, @@ -98,3 +99,20 @@ export function mergeStatsDevicesComparisonRows( } ); } + +/** + * Normalize a `stats/devices/{property}?unit=` response: views per device in each bucket. + * + * A response without `days` comes from an endpoint that ignored `unit`, so it is an error, not an empty range. + * + * @param response - The endpoint's response. + * @param query - The request's query params. + * @return The time series, a field per device. + */ +export function sanitizeStatsDevicesPeriodsResponse( response: unknown, query?: StatsQueryParams ) { + if ( ! ( 'days' in coerceStatsRecord( response ) ) ) { + throw new Error( 'stats/devices returned no per-period views.' ); + } + + return sanitizeStatsTimeSeriesResponse( response, query ); +} diff --git a/projects/packages/premium-analytics/packages/data/src/processing/stats/index.ts b/projects/packages/premium-analytics/packages/data/src/processing/stats/index.ts index afd6772d4177..d474c44e256a 100644 --- a/projects/packages/premium-analytics/packages/data/src/processing/stats/index.ts +++ b/projects/packages/premium-analytics/packages/data/src/processing/stats/index.ts @@ -63,7 +63,11 @@ export { } from './subscribers'; export { sanitizeStatsStreakResponse } from './streak'; export { sanitizeStatsTagsResponse } from './tags'; -export { mergeStatsDevicesComparisonRows, sanitizeStatsDevicesResponse } from './devices'; +export { + mergeStatsDevicesComparisonRows, + sanitizeStatsDevicesPeriodsResponse, + sanitizeStatsDevicesResponse, +} from './devices'; export { sanitizeStatsWordAdsStatsResponse, sanitizeStatsWordAdsEarningsResponse } from './wordads'; export { sanitizeStatsSingleVideoResponse } from './single-video'; export { sanitizeStatsAuthorResponse } from './author'; diff --git a/projects/packages/premium-analytics/packages/data/src/queries/__tests__/stats-queries.test.ts b/projects/packages/premium-analytics/packages/data/src/queries/__tests__/stats-queries.test.ts index 64c8c5f1474e..1b843a088657 100644 --- a/projects/packages/premium-analytics/packages/data/src/queries/__tests__/stats-queries.test.ts +++ b/projects/packages/premium-analytics/packages/data/src/queries/__tests__/stats-queries.test.ts @@ -790,7 +790,7 @@ describe( 'Stats query factories', () => { 'GET', { unit: 'week', date: '2026-06-07', start_date: '2026-01-01' }, undefined, - 'timeSeries', + 'devicesPeriods', 'UTC', ] ); } ); diff --git a/projects/packages/premium-analytics/packages/data/src/queries/stats-devices-query.ts b/projects/packages/premium-analytics/packages/data/src/queries/stats-devices-query.ts index 9cc31a70b76f..ba597a43b33d 100644 --- a/projects/packages/premium-analytics/packages/data/src/queries/stats-devices-query.ts +++ b/projects/packages/premium-analytics/packages/data/src/queries/stats-devices-query.ts @@ -33,7 +33,7 @@ export const statsDevicesQuery = ( params: StatsDevicesParams ) => { */ export const statsDevicesPeriodsQuery = ( params: StatsDevicesParams -): StatsReportQueryOptions< 'timeSeries' > => { +): StatsReportQueryOptions< 'devicesPeriods' > => { const deviceProperty = params.deviceProperty ?? 'screensize'; const apiParams = statsQueryParamsToApiParams( reportParamsToStatsQueryParams( params ) ); // `start_date` + `date` bound the window, as for `stats/visits`; `summarize` would collapse the buckets. @@ -48,7 +48,7 @@ export const statsDevicesPeriodsQuery = ( version: '1.1', endpoint: `stats/devices/${ deviceProperty }`, params: periodsParams, - sanitizer: 'timeSeries', + sanitizer: 'devicesPeriods', enabled: !! ( periodsParams.date || periodsParams.start_date ), } ); }; diff --git a/projects/packages/premium-analytics/packages/data/src/queries/stats-query.ts b/projects/packages/premium-analytics/packages/data/src/queries/stats-query.ts index 519593c3bb9d..5d2c7c6b317a 100644 --- a/projects/packages/premium-analytics/packages/data/src/queries/stats-query.ts +++ b/projects/packages/premium-analytics/packages/data/src/queries/stats-query.ts @@ -6,6 +6,7 @@ import { } from '../api'; import { sanitizeStatsClicksResponse, + sanitizeStatsDevicesPeriodsResponse, sanitizeStatsDevicesResponse, sanitizeStatsFileDownloadsResponse, sanitizeStatsHighlightsResponse, @@ -93,6 +94,7 @@ const statsSanitizers = { followers: sanitizeStatsFollowersResponse, comments: sanitizeStatsCommentsResponse, devices: sanitizeStatsDevicesResponse, + devicesPeriods: sanitizeStatsDevicesPeriodsResponse, insights: sanitizeStatsInsightsResponse, streak: sanitizeStatsStreakResponse, tags: sanitizeStatsTagsResponse, diff --git a/projects/packages/premium-analytics/packages/widgets-toolkit/src/components/chart-comparative-bar/README.md b/projects/packages/premium-analytics/packages/widgets-toolkit/src/components/chart-comparative-bar/README.md index d07ffc76a23d..0f045c6cc1fe 100644 --- a/projects/packages/premium-analytics/packages/widgets-toolkit/src/components/chart-comparative-bar/README.md +++ b/projects/packages/premium-analytics/packages/widgets-toolkit/src/components/chart-comparative-bar/README.md @@ -46,9 +46,9 @@ second current-period series keeps its own dates. | `defaultHiddenSeries` | `readonly string[]` | No | Labels of series hidden until revealed from the legend. Applied once per `chartId`, so only useful with `legendInteractive` or `previousPeriodShown` | | `legendInteractive` | `boolean` | No | Let the reader click legend items to show and hide series; the first item stays locked. Defaults to `false` | | `comparisonLabel` | `string` | No | Names the comparison in each metric's previous-period legend item, e.g. "Prev. 30 days". Defaults to "Previous period" | -| `layout` | `'grouped' \| 'overlap'` | No | The bar chart's layout; see below. Defaults to `grouped` | +| `layout` | `'grouped' \| 'overlap' \| 'stacked'` | No | The bar chart's layout; see below. Defaults to `grouped` | | `primarySeries` | `string` | No | Label of the series the reader picked, when it is not the first one drawn. Its legend item comes first and stays locked | -| `previousPeriodShown` | `boolean` | No | Overlap layout only. Whether the previous period is drawn; with `onPreviousPeriodShownChange`, its legend item becomes a toggle. See below. Omit it to keep the previous period always drawn | +| `previousPeriodShown` | `boolean` | No | Overlap and stacked layouts only. Whether the previous period is drawn; with `onPreviousPeriodShownChange`, its legend item becomes a toggle. See below. Omit it to keep the previous period always drawn | | `onPreviousPeriodShownChange` | `( shown: boolean ) => void` | No | Called with the new value when the reader presses the previous-period legend item | ## Overlap layout @@ -57,6 +57,10 @@ With `layout="overlap"`, the chart draws each `group` inside the one before it, With both `previousPeriodShown` and `onPreviousPeriodShownChange`, that item becomes a toggle and the legend is interactive. The consumer owns the value: a press calls `onPreviousPeriodShownChange` with the opposite value, and the chart draws whatever the prop says. With `previousPeriodShown` alone the item is static and shows only while the previous period is drawn. A metric's legend item hides and shows its previous bar with it, so the bar is drawn only while both that metric and the previous period are shown. +## Stacked layout + +With `layout="stacked"`, the chart stacks the `group`s into one bar per bucket and draws the previous period's total in a slot beside it, in one gray. The legend item and its toggle work as in the overlap layout. The tooltip lists each `group` with its previous value, then a Total row, and zero values draw no stub. + ## Date alignment and tooltips Comparison dates are aligned onto the primary series' dates so both land in the same band slot; the diff --git a/projects/packages/premium-analytics/src/default-dashboard-sections.php b/projects/packages/premium-analytics/src/default-dashboard-sections.php index b1aa600806f6..effb3d87bdfa 100644 --- a/projects/packages/premium-analytics/src/default-dashboard-sections.php +++ b/projects/packages/premium-analytics/src/default-dashboard-sections.php @@ -310,7 +310,7 @@ function register_default_dashboard_sections( $registry = null ) { 'label' => __( 'Traffic', 'jetpack-premium-analytics-pkg' ), 'title' => __( 'Site traffic', 'jetpack-premium-analytics-pkg' ), 'order' => 10, - // Only the Traffic summary groups by interval, and it saves its own. + // The charts that group by interval (Traffic summary, Devices bars) save their own. 'date_filter_options' => array( 'with_header_interval_control' => false, ), diff --git a/projects/packages/premium-analytics/widgets/devices/__tests__/render.test.tsx b/projects/packages/premium-analytics/widgets/devices/__tests__/render.test.tsx new file mode 100644 index 000000000000..9008398e5ea8 --- /dev/null +++ b/projects/packages/premium-analytics/widgets/devices/__tests__/render.test.tsx @@ -0,0 +1,52 @@ +/** + * External dependencies + */ +import { render } from '@testing-library/react'; +/** + * Internal dependencies + */ +import DevicesRender from '../render'; +import useDeviceViews from '../use-device-views'; +import useDeviceViewsOverTime from '../use-device-views-over-time'; +import type { ReportParams } from '@jetpack-premium-analytics/data'; + +jest.mock( '@wordpress/route', () => jest.requireActual( '../../test-utils' ).mockWordPressRoute ); +jest.mock( '../use-device-views' ); +jest.mock( '../use-device-views-over-time' ); +jest.mock( '@jetpack-premium-analytics/widgets-toolkit', () => ( { + ...jest.requireActual( '@jetpack-premium-analytics/widgets-toolkit' ), + Donut: () => null, + ComparativeBarChart: () => null, +} ) ); + +const mockUseDeviceViews = jest.mocked( useDeviceViews ); +const mockUseDeviceViewsOverTime = jest.mocked( useDeviceViewsOverTime ); +const reportParams = { from: '2026-06-01', to: '2026-06-30' } as ReportParams; +const state = { isLoading: false, isFetching: false, isError: false, refetch: jest.fn() }; + +beforeEach( () => { + jest.clearAllMocks(); + mockUseDeviceViews.mockReturnValue( { + ...state, + data: [ { label: 'desktop', displayLabel: 'Desktop', percentage: 100 } ], + hasComparison: false, + error: null, + } ); + mockUseDeviceViewsOverTime.mockReturnValue( { + ...state, + devices: [ { key: 'desktop', label: 'Desktop', value: 10, current: [] } ], + } ); +} ); + +describe( 'DevicesWidget', () => { + // Saved dashboards have no chart type, and must keep the semi-circle and its request. + it.each( [ + [ 'the semi-circle without a chart type', {}, true ], + [ 'the bars for the bar chart type', { chartType: 'bar' as const }, false ], + ] )( 'draws %s', ( _case, attributes, semiCircle ) => { + render( ); + + expect( mockUseDeviceViews.mock.calls.length > 0 ).toBe( semiCircle ); + expect( mockUseDeviceViewsOverTime.mock.calls.length > 0 ).toBe( ! semiCircle ); + } ); +} ); diff --git a/projects/packages/premium-analytics/widgets/devices/__tests__/use-device-views-over-time.test.tsx b/projects/packages/premium-analytics/widgets/devices/__tests__/use-device-views-over-time.test.tsx new file mode 100644 index 000000000000..5f655a621c40 --- /dev/null +++ b/projects/packages/premium-analytics/widgets/devices/__tests__/use-device-views-over-time.test.tsx @@ -0,0 +1,72 @@ +/** + * External dependencies + */ +import { useStatsDevicesPeriods } from '@jetpack-premium-analytics/data'; +import { renderHook } from '@testing-library/react'; +/** + * Internal dependencies + */ +import useDeviceViewsOverTime from '../use-device-views-over-time'; +import type { ReportParams } from '@jetpack-premium-analytics/data'; + +jest.mock( '@jetpack-premium-analytics/data', () => ( { + ...jest.requireActual( '@jetpack-premium-analytics/data' ), + useStatsDevicesPeriods: jest.fn(), +} ) ); + +const mockUseStatsDevicesPeriods = jest.mocked( useStatsDevicesPeriods ); +const PARAMS = { from: '2026-06-01', to: '2026-06-07' } as ReportParams; +const ROW = { date_start: '2026-06-01T00:00:00', date_end: '2026-06-01T23:59:59' }; + +function mockReport( { + primary, + comparison, + isError = false, +}: { + primary?: Record< string, unknown >; + comparison?: Record< string, unknown >; + isError?: boolean; +} ) { + mockUseStatsDevicesPeriods.mockReturnValue( { + primary: { data: primary }, + comparison: { data: comparison }, + hasComparison: !! comparison, + timezone: 'UTC', + periodStarts: undefined, + isLoading: false, + isFetching: false, + isError, + refetch: jest.fn(), + } as unknown as ReturnType< typeof useStatsDevicesPeriods > ); +} + +describe( 'useDeviceViewsOverTime', () => { + // A device the current period never saw still adds its previous views to the previous total. + it( 'stacks desktop, mobile and tablet first, then the rest by views, from either period', () => { + mockReport( { + primary: { summary: { tablet: 5, other: 9, mobile: 20, desktop: 40, ...ROW }, data: [] }, + comparison: { summary: { phone: 3, desktop: 30, ...ROW }, data: [] }, + } ); + + const { result } = renderHook( () => useDeviceViewsOverTime( PARAMS, 'day' ) ); + + expect( result.current.devices.map( device => device.key ) ).toEqual( [ + 'desktop', + 'mobile', + 'tablet', + 'other', + 'phone', + ] ); + } ); + + it.each( [ + [ 'keeps the bars when a refetch of drawn data fails', [ { ...ROW, desktop: 1 } ], false ], + [ 'reports an error when there is nothing drawn', [], true ], + ] )( '%s', ( _case, data, isError ) => { + mockReport( { primary: { summary: { desktop: 1, ...ROW }, data }, isError: true } ); + + const { result } = renderHook( () => useDeviceViewsOverTime( PARAMS, 'day' ) ); + + expect( result.current.isError ).toBe( isError ); + } ); +} ); diff --git a/projects/packages/premium-analytics/widgets/devices/render.tsx b/projects/packages/premium-analytics/widgets/devices/render.tsx index ee5fce33c165..bc2d19b91e35 100644 --- a/projects/packages/premium-analytics/widgets/devices/render.tsx +++ b/projects/packages/premium-analytics/widgets/devices/render.tsx @@ -136,7 +136,7 @@ function DevicesBarChart( { interval }: { interval?: DevicesChartGranularity } ) ] ), [ devices ] ); - const isEmpty = devices.every( device => ! device.value ); + const isEmpty = devices.every( device => ! device.value && ! device.previousValue ); const emptyState = useNoViewsEmptyState( { isLoading, isError, isEmpty }, NO_VIEWS() ); return ( diff --git a/projects/packages/premium-analytics/widgets/devices/stories/devices-widget.stories.tsx b/projects/packages/premium-analytics/widgets/devices/stories/devices-widget.stories.tsx index 41c1c37bccbb..b7e9ada30081 100644 --- a/projects/packages/premium-analytics/widgets/devices/stories/devices-widget.stories.tsx +++ b/projects/packages/premium-analytics/widgets/devices/stories/devices-widget.stories.tsx @@ -11,6 +11,7 @@ import { registerReportMocks } from '../../../packages/widgets-toolkit/src/stori import { registerStatsMocks } from '../../../packages/widgets-toolkit/src/stories/mocks/register-stats-mocks'; import { forceStatsMockState } from '../../stories/force-stats-mock-state'; import DevicesRender from '../render'; +import widgetDefinition from '../widget'; import widgetManifest from '../widget.json'; import type { Meta, StoryObj } from '@storybook/react'; import type { WidgetRenderProps } from '@wordpress/widget-primitives'; @@ -23,7 +24,7 @@ const DEVICES_RENDER_MODULE = 'storybook/devices'; // Carry the widget's metadata. `presentation` comes from widget.json ( 'framed' ), // so the host frames the widget and renders its identity (title + icon). -const storyWidgetType = createStoryWidgetType( widgetManifest ); +const storyWidgetType = createStoryWidgetType( widgetManifest, widgetDefinition ); interface DevicesStoryControls { withComparison: boolean; @@ -179,3 +180,42 @@ export const WidgetDashboardWithWidget: DashboardStory = { }, }, }; + +const renderBarOnPreset = ( preset: PresetType ) => ( + +); + +/** The bar view's first load. */ +export const BarChartLoading: StoryObj< DevicesStoryControls > = { + render: () => renderBarOnPreset( 'last-90-days' ), + tags: [ '!autodocs' ], + decorators: [ withWidgetCanvas ], + beforeEach: () => { + forceStatsMockState( 'stats/devices/screensize', 'loading' ); + return () => forceStatsMockState( 'stats/devices/screensize', null ); + }, +}; + +/** The bar view's request failed: its error state offers a Retry. */ +export const BarChartError: StoryObj< DevicesStoryControls > = { + render: () => renderBarOnPreset( 'last-7-days' ), + tags: [ '!autodocs' ], + decorators: [ withWidgetCanvas ], + beforeEach: () => { + forceStatsMockState( 'stats/devices/screensize', 'error-retryable' ); + return () => forceStatsMockState( 'stats/devices/screensize', null ); + }, +}; + +/** No device views in the range: the bar view's empty state. */ +export const BarChartEmpty: StoryObj< DevicesStoryControls > = { + render: () => renderBarOnPreset( 'last-30-days' ), + tags: [ '!autodocs' ], + decorators: [ withWidgetCanvas ], + beforeEach: () => { + forceStatsMockState( 'stats/devices/screensize', 'empty' ); + return () => forceStatsMockState( 'stats/devices/screensize', null ); + }, +}; diff --git a/projects/packages/premium-analytics/widgets/devices/use-device-views-over-time.ts b/projects/packages/premium-analytics/widgets/devices/use-device-views-over-time.ts index 729366c46549..4bbdfc5f3c57 100644 --- a/projects/packages/premium-analytics/widgets/devices/use-device-views-over-time.ts +++ b/projects/packages/premium-analytics/widgets/devices/use-device-views-over-time.ts @@ -27,22 +27,26 @@ interface DeviceViewsOverTimeState { } /** - * The devices a report counted, in stacking order. + * The devices either period counted, in stacking order: a device with no views in one period is left out of its buckets. * - * @param report - The current period's report. + * @param reports - The current and previous periods' reports. * @return The device keys. */ -function getDeviceKeys( report: StatsTimeSeriesReport | undefined ): string[] { - const totals = Object.entries( report?.summary ?? {} ).filter( - ( entry ): entry is [ string, number ] => - ! RANGE_FIELDS.has( entry[ 0 ] ) && typeof entry[ 1 ] === 'number' - ); +function getDeviceKeys( reports: ( StatsTimeSeriesReport | undefined )[] ): string[] { + const totals = new Map< string, number >(); + for ( const report of reports ) { + for ( const [ key, total ] of Object.entries( report?.summary ?? {} ) ) { + if ( ! RANGE_FIELDS.has( key ) && typeof total === 'number' ) { + totals.set( key, ( totals.get( key ) ?? 0 ) + total ); + } + } + } const rank = ( key: string ) => { const index = DEVICE_ORDER.indexOf( key ); return index === -1 ? DEVICE_ORDER.length : index; }; - return totals + return [ ...totals ] .sort( ( [ a, aTotal ], [ b, bTotal ] ) => rank( a ) - rank( b ) || bTotal - aTotal ) .map( ( [ key ] ) => key ); } @@ -69,7 +73,7 @@ export default function useDeviceViewsOverTime( const devices = useMemo( () => - getDeviceKeys( primary ).map( key => + getDeviceKeys( [ primary, hasComparison ? comparison : undefined ] ).map( key => buildMetricTab( { primary, comparison, @@ -87,7 +91,7 @@ export default function useDeviceViewsOverTime( devices, isLoading: report.isLoading, isFetching: report.isFetching, - // Placeholder data keeps the last range's bars through a failed refetch. + // A failed background refetch of the same range keeps its bars. isError: report.isError && ! primary?.data?.length, refetch: report.refetch, }; diff --git a/projects/plugins/stats/changelog/pa-devices-stacked b/projects/plugins/stats/changelog/pa-devices-stacked index 203bba8d5ab7..f74c03f46635 100644 --- a/projects/plugins/stats/changelog/pa-devices-stacked +++ b/projects/plugins/stats/changelog/pa-devices-stacked @@ -1,4 +1,4 @@ Significance: minor Type: added -Devices: Add a bar chart of views by device over time, with the previous period's total beside each bar. +Premium Analytics: Add a bar chart of views by device over time to the Devices widget, with the previous period's total beside each bar. From 85adc1c42d9a318f69e6060cac838a7d6beac278 Mon Sep 17 00:00:00 2001 From: Chi-Hsuan Huang Date: Mon, 23 Nov 2026 17:24:24 +0800 Subject: [PATCH 06/28] Premium Analytics: Download the Devices bar chart's views per bucket as CSV --- .../devices/__tests__/devices.test.tsx | 87 ++++++++++++++++++- .../widgets/devices/__tests__/render.test.tsx | 3 + .../widgets/devices/render.tsx | 41 ++++++++- .../devices/use-device-views-over-time.ts | 6 ++ 4 files changed, 130 insertions(+), 7 deletions(-) diff --git a/projects/packages/premium-analytics/widgets/devices/__tests__/devices.test.tsx b/projects/packages/premium-analytics/widgets/devices/__tests__/devices.test.tsx index fd95f7387155..82b3179dd62a 100644 --- a/projects/packages/premium-analytics/widgets/devices/__tests__/devices.test.tsx +++ b/projects/packages/premium-analytics/widgets/devices/__tests__/devices.test.tsx @@ -1,7 +1,11 @@ /** * External dependencies */ -import { useStatsDevices, useStatsSite } from '@jetpack-premium-analytics/data'; +import { + useStatsDevices, + useStatsDevicesPeriods, + useStatsSite, +} from '@jetpack-premium-analytics/data'; /** * Internal dependencies */ @@ -15,6 +19,7 @@ jest.mock( '@wordpress/route', () => jest.requireActual( '../../test-utils' ).mo jest.mock( '@jetpack-premium-analytics/data', () => ( { ...jest.requireActual( '@jetpack-premium-analytics/data' ), useStatsDevices: jest.fn(), + useStatsDevicesPeriods: jest.fn(), useStatsSite: jest.fn(), } ) ); @@ -48,8 +53,27 @@ function devicesResult( rows: unknown[], overrides: Record< string, unknown > = } as unknown as ReturnType< typeof useStatsDevices >; } -function renderWidget() { - return renderWithActionsHost( ); +function devicesPeriodsResult( primary: Record< string, unknown >, comparison = {} ) { + return { + primary: { data: primary, isError: false, isPlaceholderData: false }, + comparison: { data: comparison }, + hasComparison: true, + timezone: 'UTC', + periodStarts: undefined, + isLoading: false, + isFetching: false, + isError: false, + refetch: jest.fn(), + } as unknown as ReturnType< typeof useStatsDevicesPeriods >; +} + +const BUCKET = { date_start: '2026-07-01T00:00:00', date_end: '2026-07-01T23:59:59' }; +const RANGE = { date_start: '2026-07-01', date_end: '2026-07-31' }; + +function renderWidget( attributes = {} ) { + return renderWithActionsHost( + + ); } describe( 'DevicesWidget CSV download', () => { @@ -112,3 +136,60 @@ describe( 'DevicesWidget CSV download', () => { await expect( findDeclaredAction( 'download-csv' ) ).resolves.toBeDefined(); } ); } ); + +describe( 'DevicesWidget bar chart CSV download', () => { + let downloads: ReturnType< typeof captureCsvDownloads > | undefined; + + beforeEach( () => { + jest.useFakeTimers(); + jest.mocked( useStatsDevicesPeriods ).mockReset(); + jest.mocked( useStatsSite ).mockReturnValue( { + isLoading: false, + isError: false, + data: undefined, + } as unknown as ReturnType< typeof useStatsSite > ); + } ); + + afterEach( () => { + downloads?.restore(); + downloads = undefined; + jest.useRealTimers(); + } ); + + it( 'saves each bucket with its views per screen size, without the previous period', async () => { + downloads = captureCsvDownloads(); + jest.mocked( useStatsDevicesPeriods ).mockReturnValue( + devicesPeriodsResult( + { + summary: { desktop: 40, mobile: 20, ...RANGE }, + data: [ { ...BUCKET, desktop: 40, mobile: 20 } ], + }, + { summary: { desktop: 30, ...RANGE }, data: [ { ...BUCKET, desktop: 30 } ] } + ) + ); + + const { findDeclaredAction } = renderWidget( { chartType: 'bar' } ); + await downloads.runAndSave( await findDeclaredAction( 'download-csv' ) ); + + expect( downloads.files[ 0 ].filename ).toBe( 'devices-over-time-2026-07-01_2026-07-31.csv' ); + await expect( downloads.lines() ).resolves.toEqual( [ + '"Date","Desktop","Mobile"', + '"2026-07-01","40","20"', + ] ); + } ); + + it( 'offers no download when only the previous period recorded views', () => { + jest + .mocked( useStatsDevicesPeriods ) + .mockReturnValue( + devicesPeriodsResult( + { summary: { ...RANGE }, data: [ { ...BUCKET } ] }, + { summary: { desktop: 30, ...RANGE }, data: [ { ...BUCKET, desktop: 30 } ] } + ) + ); + + const { declaredAction } = renderWidget( { chartType: 'bar' } ); + + expect( declaredAction( 'download-csv' ) ).toBeUndefined(); + } ); +} ); diff --git a/projects/packages/premium-analytics/widgets/devices/__tests__/render.test.tsx b/projects/packages/premium-analytics/widgets/devices/__tests__/render.test.tsx index 13b6ef0a2778..53a25cb10e60 100644 --- a/projects/packages/premium-analytics/widgets/devices/__tests__/render.test.tsx +++ b/projects/packages/premium-analytics/widgets/devices/__tests__/render.test.tsx @@ -37,6 +37,9 @@ beforeEach( () => { mockUseDeviceViewsOverTime.mockReturnValue( { ...state, devices: [ { key: 'desktop', label: 'Desktop', value: 10, current: [] } ], + csvIsError: false, + csvIsPlaceholderData: false, + timezone: 'UTC', } ); } ); diff --git a/projects/packages/premium-analytics/widgets/devices/render.tsx b/projects/packages/premium-analytics/widgets/devices/render.tsx index 317f1d83b9dc..be56a07cce01 100644 --- a/projects/packages/premium-analytics/widgets/devices/render.tsx +++ b/projects/packages/premium-analytics/widgets/devices/render.tsx @@ -13,6 +13,7 @@ import { describeError, formatComparisonSeriesLabel, getComparisonPeriodLabel, + metricTabsToCsv, WidgetRoot, useReportActions, useWidgetRootContext, @@ -146,10 +147,16 @@ function DevicesBarChart( { interval }: { interval?: DevicesChartGranularity } ) 'devicesChartPreviousPeriod' ); const period = chartInterval( { ...reportParams, interval }, DEVICES_PERIODS, lockedIntervals ); - const { devices, isLoading, isFetching, isError, refetch } = useDeviceViewsOverTime( - reportParams, - period - ); + const { + devices, + isLoading, + isFetching, + isError, + csvIsError, + csvIsPlaceholderData, + timezone, + refetch, + } = useDeviceViewsOverTime( reportParams, period ); const series = useMemo< ComparativeBarChartSeries[] >( () => @@ -172,6 +179,32 @@ function DevicesBarChart( { interval }: { interval?: DevicesChartGranularity } ) const isEmpty = devices.every( device => ! device.value && ! device.previousValue ); const emptyState = useNoViewsEmptyState( { isLoading, isError, isEmpty }, NO_VIEWS() ); + // Like the semi-circle's, the file holds the current period only. + const csv = useMemo( + () => + devices.some( device => device.value ) + ? metricTabsToCsv( devices, { + zone: timezone, + withTime: false, + dateLabel: __( 'Date', 'jetpack-premium-analytics-pkg' ), + } ) + : undefined, + [ devices, timezone ] + ); + useReportActions( { + csv: csv && { + ...csv, + filenamePrefix: 'devices-over-time', + hasDateRange: true, + status: { + isLoading, + isFetching, + isError: csvIsError, + isPlaceholderData: csvIsPlaceholderData, + }, + }, + } ); + return ( void; } @@ -93,6 +96,9 @@ export default function useDeviceViewsOverTime( isFetching: report.isFetching, // A failed background refetch of the same range keeps its bars. isError: report.isError && ! primary?.data?.length, + csvIsError: report.primary.isError, + csvIsPlaceholderData: report.primary.isPlaceholderData, + timezone, refetch: report.refetch, }; } From af03437d79a1151a0ab9ab17605ffbbd3842a0ca Mon Sep 17 00:00:00 2001 From: Chi-Hsuan Huang Date: Tue, 24 Nov 2026 16:27:45 +0800 Subject: [PATCH 07/28] Premium Analytics: Read device counts from each bucket's views --- .../stats/__tests__/devices.test.ts | 24 +++++++++++++++++++ .../data/src/processing/stats/devices.ts | 13 ++++++++-- .../src/stories/mocks/register-stats-mocks.ts | 14 +++++++++-- 3 files changed, 47 insertions(+), 4 deletions(-) diff --git a/projects/packages/premium-analytics/packages/data/src/processing/stats/__tests__/devices.test.ts b/projects/packages/premium-analytics/packages/data/src/processing/stats/__tests__/devices.test.ts index c6aef78e984a..fe1a1051c62b 100644 --- a/projects/packages/premium-analytics/packages/data/src/processing/stats/__tests__/devices.test.ts +++ b/projects/packages/premium-analytics/packages/data/src/processing/stats/__tests__/devices.test.ts @@ -91,4 +91,28 @@ describe( 'sanitizeStatsDevicesPeriodsResponse', () => { it( 'reads an empty days map as a range with no views', () => { expect( sanitizeStatsDevicesPeriodsResponse( { unit: 'day', days: {} } ).data ).toEqual( [] ); } ); + + it( 'reads each bucket’s device counts from its views', () => { + const { summary, data } = sanitizeStatsDevicesPeriodsResponse( { + unit: 'year', + days: { + '2026-01-01': { + views: { desktop: 10, tablet: 5, mobile: 3, other: 2 }, + other_views: 0, + total_views: 20, + }, + }, + } ); + + expect( summary ).toEqual( { + desktop: 10, + tablet: 5, + mobile: 3, + other: 2, + date_start: expect.any( String ), + date_end: expect.any( String ), + } ); + expect( data ).toHaveLength( 1 ); + expect( data[ 0 ] ).toMatchObject( { desktop: 10, tablet: 5, mobile: 3, other: 2 } ); + } ); } ); diff --git a/projects/packages/premium-analytics/packages/data/src/processing/stats/devices.ts b/projects/packages/premium-analytics/packages/data/src/processing/stats/devices.ts index ed43661d14cc..30f88113090a 100644 --- a/projects/packages/premium-analytics/packages/data/src/processing/stats/devices.ts +++ b/projects/packages/premium-analytics/packages/data/src/processing/stats/devices.ts @@ -110,9 +110,18 @@ export function mergeStatsDevicesComparisonRows( * @return The time series, a field per device. */ export function sanitizeStatsDevicesPeriodsResponse( response: unknown, query?: StatsQueryParams ) { - if ( ! ( 'days' in coerceStatsRecord( response ) ) ) { + const payload = coerceStatsRecord( response ); + if ( ! ( 'days' in payload ) ) { throw new Error( 'stats/devices returned no per-period views.' ); } - return sanitizeStatsTimeSeriesResponse( response, query ); + // Each bucket's `other_views` and `total_views` sit beside its devices, so only `views` becomes fields. + const days = Object.fromEntries( + Object.entries( coerceStatsRecord( payload.days ) ).map( ( [ period, bucket ] ) => [ + period, + coerceStatsRecord( coerceStatsRecord( bucket ).views ), + ] ) + ); + + return sanitizeStatsTimeSeriesResponse( { ...payload, days }, query ); } diff --git a/projects/packages/premium-analytics/packages/widgets-toolkit/src/stories/mocks/register-stats-mocks.ts b/projects/packages/premium-analytics/packages/widgets-toolkit/src/stories/mocks/register-stats-mocks.ts index f7f2c5e4aa01..b7aaf6b72fca 100644 --- a/projects/packages/premium-analytics/packages/widgets-toolkit/src/stories/mocks/register-stats-mocks.ts +++ b/projects/packages/premium-analytics/packages/widgets-toolkit/src/stories/mocks/register-stats-mocks.ts @@ -1171,14 +1171,14 @@ function buildDevicesPeriodsResponse( query: URLSearchParams, isComparison: bool const dayOf = ( value: string ) => new Date( `${ value.slice( 0, 10 ) }T00:00:00Z` ); const end = dayOf( getRequestDate( query ) ); const start = dayOf( query.get( 'start_date' ) || getRequestDate( query ) ); - const days: Record< string, Record< string, number > > = {}; + const views: Record< string, Record< string, number > > = {}; for ( let day = new Date( start ), index = 0; day <= end; day.setUTCDate( day.getUTCDate() + 1 ), index++ ) { - const bucket = ( days[ devicesBucketStart( day, unit ) ] ??= { + const bucket = ( views[ devicesBucketStart( day, unit ) ] ??= { desktop: 0, mobile: 0, tablet: 0, @@ -1188,6 +1188,16 @@ function buildDevicesPeriodsResponse( query: URLSearchParams, isComparison: bool bucket.mobile += Math.round( ( 1400 + ( ( index * 89 ) % 500 ) ) * scale ); bucket.tablet += Math.round( ( 200 + ( ( index * 53 ) % 150 ) ) * scale ); } + const days = Object.fromEntries( + Object.entries( views ).map( ( [ period, counts ] ) => [ + period, + { + views: counts, + other_views: 0, + total_views: counts.desktop + counts.mobile + counts.tablet, + }, + ] ) + ); return { date: getRequestDate( query ).slice( 0, 10 ), unit, days, utc_offset: 0 }; } From ebea9a3612c0b299b4a18bcf9fcec989a6d4b18b Mon Sep 17 00:00:00 2001 From: Chi-Hsuan Huang Date: Wed, 25 Nov 2026 14:54:03 +0800 Subject: [PATCH 08/28] Charts: Keep a stacked comparison item in step with its total bar List the legend item only while the total bar is drawn, draw no total without a primary so the empty state shows, and warn that comparisonSeriesItems is ignored in a stacked layout. --- .../charts/src/charts/bar-chart/bar-chart.tsx | 42 +++++++++----- .../charts/bar-chart/private/use-bar-slots.ts | 20 ++++--- .../bar-chart/test/bar-chart-stacked.test.tsx | 55 ++++++++++++++++--- .../charts/bar-chart/use-bar-legend-items.ts | 23 ++++---- 4 files changed, 97 insertions(+), 43 deletions(-) diff --git a/projects/js-packages/charts/src/charts/bar-chart/bar-chart.tsx b/projects/js-packages/charts/src/charts/bar-chart/bar-chart.tsx index d0d28efda908..10b57c26ffde 100644 --- a/projects/js-packages/charts/src/charts/bar-chart/bar-chart.tsx +++ b/projects/js-packages/charts/src/charts/bar-chart/bar-chart.tsx @@ -161,6 +161,13 @@ const BarChartInternal: FC< BarChartProps > = ( { ); } + if ( layout === 'stacked' && legend.comparisonSeriesItems ) { + warnOnce( + 'bar-chart-stacked-comparison-series-items', + 'BarChart: a stacked layout sums its comparisons into one bar, so legend.comparisonSeriesItems is ignored; name that bar with legend.comparisonItem.' + ); + } + if ( ! withTooltips && ( withBandHighlight || onBandHighlightChange ) ) { warnOnce( 'bar-chart-band-highlight-without-tooltips', @@ -183,8 +190,7 @@ const BarChartInternal: FC< BarChartProps > = ( { ); const theme = useXYChartTheme( data ); - const transformedData = useChartDataTransform( data ); - const dataSorted = transformedData; + const dataSorted = useChartDataTransform( data ); // Transform data to add a small value for zero bars to make them visible // For vertical bars, height determines bar pixel height; for horizontal bars, width does @@ -193,18 +199,6 @@ const BarChartInternal: FC< BarChartProps > = ( { valueAxisLength: horizontal ? width : height, } ); - // Create legend items using the reusable hook - const legendOptions = useMemo( - () => ( { - collapseGroups: legendCollapseGroups, - comparisonItem: legendComparisonItem, - comparisonSeriesItems: legendComparisonSeriesItems, - layout, - } ), - [ legendCollapseGroups, legendComparisonItem, legendComparisonSeriesItems, layout ] - ); - const legendItems = useBarLegendItems( dataSorted, legendOptions ); - const { getElementStyles, theme: providerTheme } = useGlobalChartsContext(); const getBarColors = useBarColors(); const barColors = useMemo( @@ -283,6 +277,26 @@ const BarChartInternal: FC< BarChartProps > = ( { ? barSlots.entries.length === 0 : seriesWithVisibility.every( ( { isVisible } ) => ! isVisible ); + // A stack's comparison item names its total bar, so it leaves the legend whenever that bar does. + const hasComparisonTotal = !! barSlots?.slotKeys.includes( COMPARISON_SLOT ); + const legendOptions = useMemo( + () => ( { + collapseGroups: legendCollapseGroups, + comparisonItem: isStacked && ! hasComparisonTotal ? false : legendComparisonItem, + comparisonSeriesItems: legendComparisonSeriesItems, + layout, + } ), + [ + legendCollapseGroups, + legendComparisonItem, + legendComparisonSeriesItems, + layout, + isStacked, + hasComparisonTotal, + ] + ); + const legendItems = useBarLegendItems( dataSorted, legendOptions ); + const chartOptions = useBarChartOptions( dataWithVisibleZeros, horizontal, diff --git a/projects/js-packages/charts/src/charts/bar-chart/private/use-bar-slots.ts b/projects/js-packages/charts/src/charts/bar-chart/private/use-bar-slots.ts index 6315c708f18a..1dd76f1002be 100644 --- a/projects/js-packages/charts/src/charts/bar-chart/private/use-bar-slots.ts +++ b/projects/js-packages/charts/src/charts/bar-chart/private/use-bar-slots.ts @@ -69,15 +69,17 @@ export function useBarSlots( isComparison( series ) && ( visibleGroups.has( series.group ) || ! hiddenGroups.has( series.group ) ) ); - const total = comparisons.length - ? { - series: getComparisonTotalSeries( - comparisons.map( ( { series } ) => series ), - comparisonLabel - ), - index: comparisons[ 0 ].index, - } - : undefined; + // Without a primary there is no stack to compare with, so the chart shows its empty state. + const total = + primaries.length && comparisons.length + ? { + series: getComparisonTotalSeries( + comparisons.map( ( { series } ) => series ), + comparisonLabel + ), + index: comparisons[ 0 ].index, + } + : undefined; const entries = [ ...primaries, ...( total ? [ total ] : [] ) ].map( ( { series, index } ) => ( { series, index } ) ); diff --git a/projects/js-packages/charts/src/charts/bar-chart/test/bar-chart-stacked.test.tsx b/projects/js-packages/charts/src/charts/bar-chart/test/bar-chart-stacked.test.tsx index 70b40229deef..ca4ebee841ce 100644 --- a/projects/js-packages/charts/src/charts/bar-chart/test/bar-chart-stacked.test.tsx +++ b/projects/js-packages/charts/src/charts/bar-chart/test/bar-chart-stacked.test.tsx @@ -382,9 +382,18 @@ describe( 'BarChart stacked layout', () => { } ); - it( 'shows the empty state once every stacked series is hidden, comparisons and all', () => { + const UNPAIRED: SeriesData = { + label: 'All (prev)', + options: { type: 'comparison' }, + data: [ day( 'Mon', 300 ) ], + }; + + it.each( [ + [ 'paired comparisons', WITH_PREVIOUS ], + [ 'a comparison no primary shares a group with', [ ...WITH_PREVIOUS.slice( 0, 3 ), UNPAIRED ] ], + ] )( 'shows the empty state once every primary is hidden, with %s', ( _case, data ) => { renderStacked( { - data: WITH_PREVIOUS, + data, showLegend: true, legend: { interactive: true }, defaultHiddenSeries: DATA.map( series => series.label ), @@ -394,16 +403,48 @@ describe( 'BarChart stacked layout', () => { expect( screen.getByText( /All series are hidden/ ) ).toBeInTheDocument(); } ); - it( 'leaves the comparison item out of the legend while the comparisons are hidden', () => { + it( 'keeps a comparison no primary shares a group with in the total', () => { + const data = [ ...WITH_PREVIOUS.slice( 0, 3 ), UNPAIRED ]; + renderStacked( { data } ); + + expect( previousBar( 0 ).height / barIn( data, 'Desktop' ).height ).toBeCloseTo( 300 / 100 ); + } ); + + it.each( [ + [ 'every comparison', WITH_PREVIOUS, WITH_PREVIOUS.slice( 3 ), false ], + [ 'every primary', WITH_PREVIOUS, DATA, false ], + [ + 'the primary of the only comparison', + [ ...WITH_PREVIOUS.slice( 0, 2 ), WITH_PREVIOUS[ 3 ] ], + DATA.slice( 0, 1 ), + false, + ], + [ 'only the first comparison', WITH_PREVIOUS, WITH_PREVIOUS.slice( 3, 4 ), true ], + ] )( + 'lists the comparison item only while the total is drawn, hiding %s', + ( _case, data, hidden, listed ) => { + renderStacked( { + data, + showLegend: true, + legend: { comparisonItem: 'Prev. 7 days' }, + defaultHiddenSeries: hidden.map( series => series.label ), + } ); + + expect( screen.queryByText( 'Prev. 7 days' ) !== null ).toBe( listed ); + } + ); + + it( 'ignores legend.comparisonSeriesItems, and says so', () => { + const warn = jest.spyOn( console, 'warn' ).mockImplementation( () => {} ); renderStacked( { data: WITH_PREVIOUS, showLegend: true, - legend: { comparisonItem: 'Prev. 7 days' }, - defaultHiddenSeries: WITH_PREVIOUS.slice( 3 ).map( series => series.label ), + legend: { comparisonSeriesItems: label => `${ label } before` }, } ); - expect( barRects() ).toHaveLength( 5 ); - expect( screen.queryByText( 'Prev. 7 days' ) ).not.toBeInTheDocument(); + expect( screen.queryByText( /before/ ) ).not.toBeInTheDocument(); + expect( warn ).toHaveBeenCalledWith( expect.stringContaining( 'comparisonSeriesItems' ) ); + warn.mockRestore(); } ); it( 'keeps a comparison in the total while a primary of its group is shown', async () => { diff --git a/projects/js-packages/charts/src/charts/bar-chart/use-bar-legend-items.ts b/projects/js-packages/charts/src/charts/bar-chart/use-bar-legend-items.ts index 5c5203908edd..ae62fa4c3e36 100644 --- a/projects/js-packages/charts/src/charts/bar-chart/use-bar-legend-items.ts +++ b/projects/js-packages/charts/src/charts/bar-chart/use-bar-legend-items.ts @@ -21,12 +21,12 @@ const isComparison = ( data: SeriesData[], label: string | undefined ) => * * @param data - The chart's series. * @param comparisonItem - The legend's `comparisonItem` option. - * @return The series, each one's index in `data`, and the comparison the total's item is shown with. + * @return The series, and each one's index in `data` for its color. */ function getStackedLegendSeries( data: SeriesData[], comparisonItem: BarLegendOptions[ 'comparisonItem' ] -): { series: SeriesData[]; indexes: number[]; describes?: string } { +): { series: SeriesData[]; indexes: number[] } { const indexes = data.flatMap( ( series, index ) => series.options?.type === 'comparison' ? [] : [ index ] ); @@ -47,36 +47,35 @@ function getStackedLegendSeries( }, ], indexes: [ ...indexes, comparison ], - describes: data[ comparison ].label, }; } /** - * Applies what a bar layout changes about a legend: a stacked comparison total is a static item; overlap lists every primary before every comparison, as it draws their slots, with every swatch opaque like its bar; a collapsed grouped item takes its comparison's tint, the wider bar that frames the group. + * Applies what a bar layout changes about a legend: its swatch colors, and the order and kind of its comparison items. * * @param data - The series the items were built from. * @param items - The legend items. * @param layout - The layout the bars are drawn in. * @param seriesColors - Each series' bar color, by index. - * @param describes - The comparison a stacked total's item leaves the legend with while it is hidden. * @return The legend items. */ function forBarLayout( data: SeriesData[], items: BaseLegendItem[], layout: BarChartLayout, - seriesColors: string[], - describes?: string + seriesColors: string[] ): BaseLegendItem[] { if ( layout === 'stacked' ) { // The comparison total is not a series to toggle: hiding a primary already drops its comparison from it. return items.map( item => isComparison( data, item.seriesLabels?.[ 0 ] ) - ? { ...item, seriesLabels: undefined, interactive: false, describesSeries: describes } + ? { ...item, seriesLabels: undefined, interactive: false } : item ); } + // Overlap lists every primary before every comparison, as it draws their slots, with opaque swatches. + if ( layout === 'overlap' ) { const opaque = items.map( item => item.shapeStyle ? { ...item, shapeStyle: { ...item.shapeStyle, opacity: undefined } } : item @@ -92,6 +91,7 @@ function forBarLayout( ]; } + // A collapsed grouped item takes its comparison's tint, the wider bar that frames the group. return items.map( item => { if ( ( item.seriesLabels?.length ?? 0 ) < 2 ) { return item; @@ -144,10 +144,7 @@ export function useBarLegendItems( const items = useChartLegendItems( data, chartLegendOptions, legendShape ); return useMemo( - () => - layout && seriesColors - ? forBarLayout( data, items, layout, seriesColors, stacked?.describes ) - : items, - [ data, items, layout, seriesColors, stacked ] + () => ( layout && seriesColors ? forBarLayout( data, items, layout, seriesColors ) : items ), + [ data, items, layout, seriesColors ] ); } From 60e3165b0b542a01889d16c24a02f9e7bb531fbe Mon Sep 17 00:00:00 2001 From: Chi-Hsuan Huang Date: Wed, 25 Nov 2026 14:55:48 +0800 Subject: [PATCH 09/28] Charts: Cover the stacked comparison total's guards and colors in tests --- .../private/test/stack-layout.test.ts | 8 +++ .../bar-chart/test/bar-chart-stacked.test.tsx | 1 + .../test/use-bar-legend-items.test.tsx | 63 +++++++++++-------- .../test/use-chart-legend-items.test.tsx | 12 +++- 4 files changed, 58 insertions(+), 26 deletions(-) diff --git a/projects/js-packages/charts/src/charts/bar-chart/private/test/stack-layout.test.ts b/projects/js-packages/charts/src/charts/bar-chart/private/test/stack-layout.test.ts index 5ab279783f28..4db7ac461ab3 100644 --- a/projects/js-packages/charts/src/charts/bar-chart/private/test/stack-layout.test.ts +++ b/projects/js-packages/charts/src/charts/bar-chart/private/test/stack-layout.test.ts @@ -111,6 +111,14 @@ describe( 'getComparisonTotalSeries', () => { [ 'Wed', null ], ] ); } ); + + it( 'keeps the first reading of a category a comparison repeats, as the bar does', () => { + const total = getComparisonTotalSeries( + [ s( 'A', [ 30, 99 ], [ 'Mon', 'Mon' ] ) ], + 'Previous' + ); + expect( total.data.map( ( { value } ) => value ) ).toEqual( [ 30 ] ); + } ); } ); describe( 'getStackedValueDomain', () => { diff --git a/projects/js-packages/charts/src/charts/bar-chart/test/bar-chart-stacked.test.tsx b/projects/js-packages/charts/src/charts/bar-chart/test/bar-chart-stacked.test.tsx index ca4ebee841ce..7816f3f29e39 100644 --- a/projects/js-packages/charts/src/charts/bar-chart/test/bar-chart-stacked.test.tsx +++ b/projects/js-packages/charts/src/charts/bar-chart/test/bar-chart-stacked.test.tsx @@ -326,6 +326,7 @@ describe( 'BarChart stacked layout', () => { expect( previousBar().height / desktop.height ).toBeCloseTo( 500 / 100 ); expect( fills().slice( 0, 5 ) ).toEqual( plainFills ); expect( new Set( fills().slice( 5 ) ).size ).toBe( 1 ); + expect( plainFills ).not.toContain( fills()[ 5 ] ); } ); it( 'lists the comparison total after the stack total, named by the legend comparison item', async () => { diff --git a/projects/js-packages/charts/src/charts/bar-chart/test/use-bar-legend-items.test.tsx b/projects/js-packages/charts/src/charts/bar-chart/test/use-bar-legend-items.test.tsx index 08a6f6e99f9a..44cba1045a5c 100644 --- a/projects/js-packages/charts/src/charts/bar-chart/test/use-bar-legend-items.test.tsx +++ b/projects/js-packages/charts/src/charts/bar-chart/test/use-bar-legend-items.test.tsx @@ -2,7 +2,7 @@ import { renderHook } from '@testing-library/react'; import { useChartLegendItems } from '../../../components/legend'; import { GlobalChartsProvider } from '../../../providers'; import { useGlobalChartsContext } from '../../../providers/chart-context/hooks/use-global-charts-context'; -import { neutralWithContrast } from '../private/overlap-bars'; +import { contrastRatio } from '../../../providers/chart-context/private/perceptual-color'; import { useBarColors } from '../use-bar-colors'; import { useBarLegendItems } from '../use-bar-legend-items'; import type { SeriesData } from '../../../types'; @@ -88,39 +88,52 @@ describe( 'useBarLegendItems', () => { ] ); } ); - test.each( [ undefined, false ] )( - 'lists only the stacked primaries with comparisonItem %p', - comparisonItem => { - const { result } = renderHook( - () => useBarLegendItems( twoMetricData, { layout: 'stacked', comparisonItem } ), - { wrapper } - ); - - expect( result.current.map( item => item.label ) ).toEqual( [ 'Views', 'Visitors' ] ); - } - ); - test.each( [ - [ 'a gray with 3:1 against the background', undefined ], - [ "the first comparison's own stroke", '#aa3355' ], - ] )( 'colors every stacked comparison in %s', ( _case, stroke ) => { - const data = twoMetricData.map( series => - series.label === 'Visitors — previous' && stroke - ? { ...series, options: { ...series.options, stroke } } - : series - ); + [ 'comparisonItem unset', twoMetricData, undefined ], + [ 'comparisonItem false', twoMetricData, false ], + [ + 'nothing to compare', + twoMetricData.filter( series => series.options?.type !== 'comparison' ), + true, + ], + ] )( 'lists only the stacked primaries with %s', ( _case, data, comparisonItem ) => { const { result } = renderHook( + () => useBarLegendItems( data, { layout: 'stacked', comparisonItem } ), + { wrapper } + ); + + expect( result.current.map( item => item.label ) ).toEqual( [ 'Views', 'Visitors' ] ); + } ); + + const stackedColors = ( data: SeriesData[] ) => + renderHook( () => ( { colors: useBarColors()( data, { layout: 'stacked' } ), background: useGlobalChartsContext().backgroundColor ?? '#ffffff', } ), { wrapper } - ); - const { colors, background } = result.current; + ).result.current; + + test( 'colors every stacked comparison in the gray nearest the background that keeps 3:1', () => { + const { colors, background } = stackedColors( twoMetricData ); + const [ red, green, blue ] = colors[ 1 ].slice( 1 ).match( /../g ) ?? []; - expect( [ colors[ 1 ], colors[ 3 ] ] ).toEqual( - Array( 2 ).fill( stroke ?? neutralWithContrast( background ) ) + expect( colors[ 3 ] ).toBe( colors[ 1 ] ); + expect( [ green, blue ] ).toEqual( [ red, red ] ); + expect( contrastRatio( colors[ 1 ], background ) ).toBeGreaterThanOrEqual( 3 ); + expect( contrastRatio( colors[ 1 ], background ) ).toBeLessThan( 3.2 ); + } ); + + test( "colors every stacked comparison in the first comparison's own stroke", () => { + const { colors } = stackedColors( + twoMetricData.map( series => + series.label === 'Visitors — previous' + ? { ...series, options: { ...series.options, stroke: '#aa3355' } } + : series + ) ); + + expect( [ colors[ 1 ], colors[ 3 ] ] ).toEqual( [ '#aa3355', '#aa3355' ] ); } ); test( "returns the chart legend's own items without a layout", () => { diff --git a/projects/js-packages/charts/src/components/legend/hooks/test/use-chart-legend-items.test.tsx b/projects/js-packages/charts/src/components/legend/hooks/test/use-chart-legend-items.test.tsx index db516b70f5af..0e57b0ff020e 100644 --- a/projects/js-packages/charts/src/components/legend/hooks/test/use-chart-legend-items.test.tsx +++ b/projects/js-packages/charts/src/components/legend/hooks/test/use-chart-legend-items.test.tsx @@ -1,6 +1,6 @@ import { renderHook } from '@testing-library/react'; import { GlobalChartsProvider } from '../../../../providers'; -import { useChartLegendItems } from '../use-chart-legend-items'; +import { getComparisonItemLabel, useChartLegendItems } from '../use-chart-legend-items'; import type { DataPointPercentageCalculated, DataPointDate, SeriesData } from '../../../../types'; import type { ReactNode } from 'react'; @@ -622,3 +622,13 @@ describe( 'useChartLegendItems', () => { } ); } ); } ); + +describe( 'getComparisonItemLabel', () => { + it.each( [ + [ 'Prev. 7 days', 'Prev. 7 days' ], + [ true, 'Comparison period' ], + [ '', 'Comparison period' ], + ] )( 'names a comparisonItem of %p %p', ( comparisonItem, label ) => { + expect( getComparisonItemLabel( comparisonItem ) ).toBe( label ); + } ); +} ); From 2425e9135454515cd9c824c892fc06fe0046f9ae Mon Sep 17 00:00:00 2001 From: Chi-Hsuan Huang Date: Wed, 25 Nov 2026 14:56:47 +0800 Subject: [PATCH 10/28] Charts: Tighten the stacked comparison docs and share its comparison check --- .../charts/bar-chart/private/overlap-bars.ts | 2 ++ .../charts/bar-chart/private/stack-layout.ts | 4 ++-- .../bar-chart/private/stacked-bar-series.tsx | 2 +- .../charts/bar-chart/private/use-bar-slots.ts | 15 +++++++++------ .../charts/bar-chart/stories/index.api.mdx | 4 ++-- .../charts/bar-chart/stories/index.docs.mdx | 8 +++++--- .../bar-chart/stories/index.stories.tsx | 2 +- .../src/charts/bar-chart/use-bar-colors.ts | 19 ++++++++++++------- projects/js-packages/charts/src/types.ts | 3 ++- 9 files changed, 36 insertions(+), 23 deletions(-) diff --git a/projects/js-packages/charts/src/charts/bar-chart/private/overlap-bars.ts b/projects/js-packages/charts/src/charts/bar-chart/private/overlap-bars.ts index ec3145f1eaca..2cb9f5cd81b5 100644 --- a/projects/js-packages/charts/src/charts/bar-chart/private/overlap-bars.ts +++ b/projects/js-packages/charts/src/charts/bar-chart/private/overlap-bars.ts @@ -8,6 +8,8 @@ export const COMPARISON_SLOT = 'comparison'; const OVERLAP_SLOTS = [ PRIMARY_SLOT, COMPARISON_SLOT ] as const; +export const isComparisonSeries = ( series: SeriesData ) => series.options?.type === 'comparison'; + /** Thickness of the front-most layer, as a share of its slot. */ const FRONT_THICKNESS = 0.5; diff --git a/projects/js-packages/charts/src/charts/bar-chart/private/stack-layout.ts b/projects/js-packages/charts/src/charts/bar-chart/private/stack-layout.ts index 7a6658cce264..366db0d4a2a9 100644 --- a/projects/js-packages/charts/src/charts/bar-chart/private/stack-layout.ts +++ b/projects/js-packages/charts/src/charts/bar-chart/private/stack-layout.ts @@ -13,7 +13,7 @@ export type ComparisonTotal = { key: string; series: SeriesData[] }; export type StackLayout = { /** Where a series' bar runs at a datum's category; undefined when that datum has no reading. */ segmentOf: ( key: string, datum: DataPointDate ) => StackSegment | undefined; - /** The lowest negative sum and highest positive sum at the datum's category, both including 0, of the bar `key` is drawn in. */ + /** The lowest negative and highest positive sum at the datum's category, both including 0; with `key`, those of its bar. */ extentAt: ( category: DataPointDate, key?: string ) => [ number, number ]; /** The widest `extentAt` over every category and bar, or null without a finite value. */ extent: [ number, number ] | null; @@ -57,7 +57,7 @@ function stackSeries( } /** - * Stacks the series in order at each category: positives upward and negatives downward from zero. Comparisons are summed the same way into one bar of their own. + * Stacks the series in order at each category, positives up and negatives down from zero, and sums comparisons into one bar. * * @param series - The series to stack, bottom first. * @param comparison - The comparison series to sum, and the key their bar is drawn under. diff --git a/projects/js-packages/charts/src/charts/bar-chart/private/stacked-bar-series.tsx b/projects/js-packages/charts/src/charts/bar-chart/private/stacked-bar-series.tsx index 8a34f1626618..da54c13b5d82 100644 --- a/projects/js-packages/charts/src/charts/bar-chart/private/stacked-bar-series.tsx +++ b/projects/js-packages/charts/src/charts/bar-chart/private/stacked-bar-series.tsx @@ -28,7 +28,7 @@ type Props = Pick< }; /** - * The side a segment rounds when it ends its drawn stack: the far end of the positives or of the negatives, or both for a comparison total that spans zero. + * The side a segment rounds when it ends its drawn stack, or `both` for a comparison total that spans zero. * * @param stack - The stack layout. * @param key - The series the segment is drawn for. diff --git a/projects/js-packages/charts/src/charts/bar-chart/private/use-bar-slots.ts b/projects/js-packages/charts/src/charts/bar-chart/private/use-bar-slots.ts index 1dd76f1002be..1b63f6a05da6 100644 --- a/projects/js-packages/charts/src/charts/bar-chart/private/use-bar-slots.ts +++ b/projects/js-packages/charts/src/charts/bar-chart/private/use-bar-slots.ts @@ -1,6 +1,11 @@ import { useMemo } from 'react'; import { categoryKey, isSameCategory } from './category'; -import { COMPARISON_SLOT, PRIMARY_SLOT, getOverlapPlacements } from './overlap-bars'; +import { + COMPARISON_SLOT, + PRIMARY_SLOT, + getOverlapPlacements, + isComparisonSeries, +} from './overlap-bars'; import { getComparisonTotalSeries, getStackLayout } from './stack-layout'; import { isBarRendered } from './value-domain'; import type { SelectedBar } from './selected-bar-ring'; @@ -32,8 +37,6 @@ export type StopPosition = { export type SelectedSlot = SelectedBar & { members: SlotMember[] }; -const isComparison = ( series: SeriesData ) => series.options?.type === 'comparison'; - /** * Lays out the visible series in slots: overlap layers primaries and comparisons in two, stacked puts every primary in one and sums the comparisons into a bar in a second. * @@ -56,17 +59,17 @@ export function useBarSlots( if ( layout === 'stacked' ) { // Bottom to top, so the top segment names each keyboard stop. - const primaries = visible.filter( ( { series } ) => ! isComparison( series ) ); + const primaries = visible.filter( ( { series } ) => ! isComparisonSeries( series ) ); const visibleGroups = new Set( primaries.map( ( { series } ) => series.group ) ); const hiddenGroups = new Set( seriesWithVisibility.flatMap( ( { series, isVisible } ) => - isVisible || isComparison( series ) ? [] : [ series.group ] + isVisible || isComparisonSeries( series ) ? [] : [ series.group ] ) ); // A comparison leaves the total with the primary it is paired with, so both bars sum the same series. const comparisons = visible.filter( ( { series } ) => - isComparison( series ) && + isComparisonSeries( series ) && ( visibleGroups.has( series.group ) || ! hiddenGroups.has( series.group ) ) ); // Without a primary there is no stack to compare with, so the chart shows its empty state. diff --git a/projects/js-packages/charts/src/charts/bar-chart/stories/index.api.mdx b/projects/js-packages/charts/src/charts/bar-chart/stories/index.api.mdx index aea05989c7e1..cdb288fea87b 100644 --- a/projects/js-packages/charts/src/charts/bar-chart/stories/index.api.mdx +++ b/projects/js-packages/charts/src/charts/bar-chart/stories/index.api.mdx @@ -115,7 +115,7 @@ Comparison styling applies to the `grouped` layout only. An `overlap` layout dra `useBarColors()` returns a function, `( series, { layout } ) => string[]`, that gives the color `BarChart` fills each series with in that layout, by index. Use it to color a custom tooltip's swatches. In `stacked`, comparison series take no palette slot, so they do not shift the colors of the series after them, and all take the color of the one bar they are summed into. -`useBarLegendItems( data, { layout, ...legendOptions }, legendShape? )` builds the legend items `BarChart` registers for its own and composition legends, for a custom legend. It takes the `useChartLegendItems` options plus `layout`. With a layout, every swatch takes its bar's color; in `overlap` the swatches are opaque and, without `collapseGroups`, the items are in slot order: every primary, then every comparison; in `grouped`, a collapsed group's swatch takes its comparison's tint. In `stacked`, comparison series get no item; `comparisonItem` adds one static item for the bar they are summed into, and `comparisonSeriesItems` is ignored. Without a layout, it returns `useChartLegendItems`' items unchanged. +`useBarLegendItems( data, { layout, ...legendOptions }, legendShape? )` builds the legend items `BarChart` registers for its own and composition legends, for a custom legend. It takes the `useChartLegendItems` options plus `layout`. With a layout, every swatch takes its bar's color; in `overlap` the swatches are opaque and, without `collapseGroups`, the items are in slot order: every primary, then every comparison; in `grouped`, a collapsed group's swatch takes its comparison's tint. In `stacked`, comparison series get no item; `comparisonItem` adds one static item for the bar they are summed into, which `BarChart` leaves out while that bar is not drawn, and `comparisonSeriesItems` is ignored. Without a layout, it returns `useChartLegendItems`' items unchanged. ## DataPointDate Type @@ -183,7 +183,7 @@ type SeriesChartLegendConfig = { // A stacked bar chart names the bar it sums the comparisons into with it, in the legend and tooltip. comparisonItem?: boolean | string; // Append one static item per comparison series instead, named from the label of the item it - // was folded into and left out while that series is hidden. Not added by a stacked bar chart either. + // was folded into and left out while that series is hidden. A stacked bar chart ignores it. comparisonSeriesItems?: ( seriesLabel: string ) => string; itemClassName?: string; itemStyles?: LegendItemStyles; diff --git a/projects/js-packages/charts/src/charts/bar-chart/stories/index.docs.mdx b/projects/js-packages/charts/src/charts/bar-chart/stories/index.docs.mdx index 48081d9d4a25..bc67f7e50f7a 100644 --- a/projects/js-packages/charts/src/charts/bar-chart/stories/index.docs.mdx +++ b/projects/js-packages/charts/src/charts/bar-chart/stories/index.docs.mdx @@ -261,14 +261,16 @@ Set `layout="stacked"` to draw every series of a category as one bar, each serie **Notes:** -- Unless the caller sets a domain, the value axis includes zero and covers the tallest stack. Negative values stack downward from zero, apart from the positives, and extend the axis below it. The value axis is always linear and starts every stack at zero, so another scale `type` or `zero: false` is ignored, with a warning in development. +- Unless the caller sets a domain, the value axis includes zero and covers the tallest stack or comparison total. Negative values stack downward from zero, apart from the positives, and extend the axis below it. The value axis is always linear and starts every stack at zero, so another scale `type` or `zero: false` is ignored, with a warning in development. - A series with no reading at a category is skipped there, and the segment above it starts where the one below ends. - Hiding a series from the legend closes the stacks up and rescales the axis. - The tooltip covers the whole stack: every series, last series first, with a `null` reading as "No data", then the total when there is more than one reading. It sits at the end of the positive values, or of the negative ones when the category has no positive value. - Arrow keys step one category at a time, and the selected stack is outlined as a whole. Enter hands `onDatumActivate` the top segment, while pointer callbacks report the segment under the pointer. With comparisons, each category has a second stop on the comparison total after its stack; there the callbacks get the total's label as `key` and the summed point as the datum, not a series from `data`. - A bar radius (`--a8c-charts-border-radius-bar-chart`) rounds only the outer end of each stack, so the seams between segments stay flush. An outer segment shorter than the radius rounds only as far as its own length. -- `type: 'comparison'` series are summed into one bar beside each stack: the comparison period's total, comparing totals rather than segments. Hiding a series also drops the comparison of its `group` from that total. The bar takes the `options.stroke` of the first comparison that sets one, or else a gray that keeps 3:1 against the background. Its legend item leaves the legend while the first comparison is hidden, so to drop the comparison period, leave the comparison series out of `data`. The tooltip lists it after the total, and the legend names it with one static item when `legend.comparisonItem` is set; both use that string as its name, or "Comparison period". -- `showZeroValues` has no effect, and warns once in development. +- `type: 'comparison'` series are summed into one bar beside each stack, comparing totals rather than segments; hiding a series also drops the comparison of its `group`, and the bar is gone while no primary is shown. +- The total bar takes the `options.stroke` of the first comparison that sets one, or else a gray that keeps 3:1 against the background. +- The tooltip lists the total after the stack's, and `legend.comparisonItem` adds one static legend item while the bar is drawn; both are named by that string, or "Comparison period". +- `showZeroValues` and `legend.comparisonSeriesItems` have no effect, and warn once in development. - Works with `orientation="horizontal"`, where the first series is the left-most segment. diff --git a/projects/js-packages/charts/src/charts/bar-chart/stories/index.stories.tsx b/projects/js-packages/charts/src/charts/bar-chart/stories/index.stories.tsx index 883142dfbe57..791f809b09f1 100644 --- a/projects/js-packages/charts/src/charts/bar-chart/stories/index.stories.tsx +++ b/projects/js-packages/charts/src/charts/bar-chart/stories/index.stories.tsx @@ -992,7 +992,7 @@ export const StackedComparison: Story = { docs: { description: { story: - "A stacked chart with a `type: 'comparison'` series per device. The comparisons are summed into one bar beside each stack, the previous period's total, in a gray that keeps 3:1 against the background; `legend.comparisonItem` names it in the legend and the tooltip. Hide a device from the legend and its previous period leaves the total too, so both bars sum the same devices.", + 'The previous period of each device is summed into one bar beside each stack, named by `legend.comparisonItem`; hiding a device drops its previous period from that bar too.', }, }, }, diff --git a/projects/js-packages/charts/src/charts/bar-chart/use-bar-colors.ts b/projects/js-packages/charts/src/charts/bar-chart/use-bar-colors.ts index 2e4077c34270..b330d7ecb4bb 100644 --- a/projects/js-packages/charts/src/charts/bar-chart/use-bar-colors.ts +++ b/projects/js-packages/charts/src/charts/bar-chart/use-bar-colors.ts @@ -3,7 +3,11 @@ import { useGlobalChartsContext } from '../../providers/chart-context/hooks/use- import { BACKGROUND_FALLBACK } from '../../providers/chart-context/private/catalog-pointers'; import { isValidHexColor } from '../../utils/color-utils'; import { getGroupedBarColors } from './private/grouped-bars'; -import { getOverlapBarColors, neutralWithContrast } from './private/overlap-bars'; +import { + getOverlapBarColors, + isComparisonSeries, + neutralWithContrast, +} from './private/overlap-bars'; import type { BarChartLayout, SeriesData } from '../../types'; export type GetBarColors = ( @@ -29,17 +33,18 @@ export function useBarColors(): GetBarColors { const colors = series.map( ( data, index ) => getElementStyles( { data, index } ).color ); if ( layout === 'stacked' ) { - const isComparison = ( data: SeriesData ) => data.options?.type === 'comparison'; - // Comparisons share one bar, so they take no palette slot and one color: the first one given, or a gray. - const primaries = series.filter( data => ! isComparison( data ) ); - const stroked = series.findIndex( data => isComparison( data ) && data.options?.stroke ); - const firstComparison = series.findIndex( isComparison ); + // Comparisons share one bar: no palette slot, and the first stroke set among them, else a contrast gray. + const primaries = series.filter( data => ! isComparisonSeries( data ) ); + const stroked = series.findIndex( + data => isComparisonSeries( data ) && data.options?.stroke + ); + const firstComparison = series.findIndex( isComparisonSeries ); const comparisonColor = stroked === -1 && isValidHexColor( backgroundColor ) ? neutralWithContrast( backgroundColor ) : colors[ stroked === -1 ? firstComparison : stroked ]; return series.map( data => - isComparison( data ) + isComparisonSeries( data ) ? comparisonColor : getElementStyles( { data, index: primaries.indexOf( data ) } ).color ); diff --git a/projects/js-packages/charts/src/types.ts b/projects/js-packages/charts/src/types.ts index ced4212703c2..3bd4e71e8c47 100644 --- a/projects/js-packages/charts/src/types.ts +++ b/projects/js-packages/charts/src/types.ts @@ -804,7 +804,8 @@ export type BaseChartProps< T = DataPoint | DataPointDate | LeaderboardEntry > = /** * Callback for Enter or Space on the point keyboard navigation has selected: * the keyboard counterpart of a click. `index` is the point's position in its - * series and `key` the series label. + * series and `key` the series label. A stacked bar chart's comparison total reports its own + * label and summed point, which name no series in `data`. */ onDatumActivate?: ( params: { datum: DataPoint | DataPointDate; From 2a2259756dbfeceb3e18e5f296a7acf79265a0d1 Mon Sep 17 00:00:00 2001 From: Chi-Hsuan Huang Date: Wed, 25 Nov 2026 15:02:28 +0800 Subject: [PATCH 11/28] Charts: Name the stacked comparison story's series like the other comparison stories --- .../charts/src/charts/bar-chart/stories/index.stories.tsx | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/projects/js-packages/charts/src/charts/bar-chart/stories/index.stories.tsx b/projects/js-packages/charts/src/charts/bar-chart/stories/index.stories.tsx index 791f809b09f1..5be29c245f90 100644 --- a/projects/js-packages/charts/src/charts/bar-chart/stories/index.stories.tsx +++ b/projects/js-packages/charts/src/charts/bar-chart/stories/index.stories.tsx @@ -963,7 +963,7 @@ export const Stacked: Story = { const deviceViewsWithPrevious: SeriesData[] = [ ...deviceViewsData.map( series => ( { ...series, group: series.label } ) ), ...deviceViewsData.map( ( series, index ) => ( { - label: `${ series.label } (previous)`, + label: `Previous ${ series.label.toLowerCase() }`, group: series.label, options: { type: 'comparison' as const }, data: series.data.map( ( point, day ) => ( { @@ -992,7 +992,7 @@ export const StackedComparison: Story = { docs: { description: { story: - 'The previous period of each device is summed into one bar beside each stack, named by `legend.comparisonItem`; hiding a device drops its previous period from that bar too.', + "Each device is paired by `group` with its previous four weeks, and those are summed into one bar beside each stack, in a gray that keeps 3:1 against the background. Hover a bar, or tab in and use the arrow keys, to read each device, the total, then the previous period's total; each day has a second stop on the gray bar. Hide a device from the legend and its previous period leaves the gray bar too, so both bars sum the same devices; `legend.comparisonItem` names that bar in the legend and the tooltip.", }, }, }, From b67beee27860f1999e39654b7d68c7d3a2c3ff8c Mon Sep 17 00:00:00 2001 From: Chi-Hsuan Huang Date: Wed, 25 Nov 2026 15:06:15 +0800 Subject: [PATCH 12/28] Charts: Report a stacked comparison total under a fixed key The total used the translated legend label as its key, so callbacks saw a string that changed with the locale and a primary of the same name was drawn in its place. Export COMPARISON_TOTAL_KEY and keep the label for the tooltip and legend only. --- .../changelog/charts-stacked-comparison | 2 +- .../charts/src/charts/bar-chart/bar-chart.tsx | 11 ++--- .../charts/src/charts/bar-chart/index.ts | 1 + .../charts/bar-chart/private/overlap-bars.ts | 3 ++ .../charts/bar-chart/private/stack-layout.ts | 2 +- .../charts/bar-chart/private/use-bar-slots.ts | 9 ++-- .../charts/bar-chart/stories/index.docs.mdx | 2 +- .../bar-chart/test/bar-chart-stacked.test.tsx | 46 +++++++++++++++++-- .../charts/bar-chart/use-bar-legend-items.ts | 26 ++++++++--- projects/js-packages/charts/src/index.ts | 1 + projects/js-packages/charts/src/types.ts | 4 +- 11 files changed, 79 insertions(+), 28 deletions(-) diff --git a/projects/js-packages/charts/changelog/charts-stacked-comparison b/projects/js-packages/charts/changelog/charts-stacked-comparison index e6da732eca98..211fd9b72b5b 100644 --- a/projects/js-packages/charts/changelog/charts-stacked-comparison +++ b/projects/js-packages/charts/changelog/charts-stacked-comparison @@ -1,4 +1,4 @@ Significance: minor Type: added -Bar chart: Sum comparison series into one bar beside each stack in the stacked layout. +Bar chart: Sum comparison series into one bar beside each stack in the stacked layout, which callbacks report as `COMPARISON_TOTAL_KEY`. diff --git a/projects/js-packages/charts/src/charts/bar-chart/bar-chart.tsx b/projects/js-packages/charts/src/charts/bar-chart/bar-chart.tsx index 10b57c26ffde..b54894b0ed66 100644 --- a/projects/js-packages/charts/src/charts/bar-chart/bar-chart.tsx +++ b/projects/js-packages/charts/src/charts/bar-chart/bar-chart.tsx @@ -265,11 +265,7 @@ const BarChartInternal: FC< BarChartProps > = ( { [ seriesWithVisibility ] ); - const barSlots = useBarSlots( - layout, - seriesWithVisibility, - getComparisonItemLabel( legendComparisonItem ) - ); + const barSlots = useBarSlots( layout, seriesWithVisibility ); // A stack's comparisons leave with their primaries, so it is empty once it draws nothing. const allSeriesHidden = @@ -495,6 +491,7 @@ const BarChartInternal: FC< BarChartProps > = ( { [ chartOptions.tooltip, dataSorted ] ); + const comparisonTotalLabel = getComparisonItemLabel( legendComparisonItem ); // Lists the stack last series first, a null reading as "No data", then the total and the comparison total. const renderStackedTooltip = useCallback( ( { tooltipData }: RenderTooltipParams< DataPointDate > ) => { @@ -537,13 +534,13 @@ const BarChartInternal: FC< BarChartProps > = ( { ) } { comparisonRows.map( ( { label, datum } ) => ( - { renderTooltipRow( label, formatReading( datum.value ) ) } + { renderTooltipRow( comparisonTotalLabel, formatReading( datum.value ) ) } ) ) } ); }, - [ chartOptions.tooltip, barSlots ] + [ chartOptions.tooltip, barSlots, comparisonTotalLabel ] ); const renderDefaultTooltip = useCallback( diff --git a/projects/js-packages/charts/src/charts/bar-chart/index.ts b/projects/js-packages/charts/src/charts/bar-chart/index.ts index 7acc640199ca..d294c9cd1c1e 100644 --- a/projects/js-packages/charts/src/charts/bar-chart/index.ts +++ b/projects/js-packages/charts/src/charts/bar-chart/index.ts @@ -1,5 +1,6 @@ export { default as BarChart, BarChartUnresponsive } from './bar-chart'; export { useBarColors } from './use-bar-colors'; +export { COMPARISON_TOTAL_KEY } from './private/overlap-bars'; export { useBarLegendItems } from './use-bar-legend-items'; export type { BarLegendOptions } from './use-bar-legend-items'; export type { BarChartProps, BandHighlightSelection } from './types'; diff --git a/projects/js-packages/charts/src/charts/bar-chart/private/overlap-bars.ts b/projects/js-packages/charts/src/charts/bar-chart/private/overlap-bars.ts index 2cb9f5cd81b5..48f3ae470a74 100644 --- a/projects/js-packages/charts/src/charts/bar-chart/private/overlap-bars.ts +++ b/projects/js-packages/charts/src/charts/bar-chart/private/overlap-bars.ts @@ -6,6 +6,9 @@ import type { SeriesData } from '../../../types'; export const PRIMARY_SLOT = 'primary'; export const COMPARISON_SLOT = 'comparison'; +/** The `key` a stacked layout draws its comparison total under, and hands to its callbacks. */ +export const COMPARISON_TOTAL_KEY = 'a8c-charts-comparison-total'; + const OVERLAP_SLOTS = [ PRIMARY_SLOT, COMPARISON_SLOT ] as const; export const isComparisonSeries = ( series: SeriesData ) => series.options?.type === 'comparison'; diff --git a/projects/js-packages/charts/src/charts/bar-chart/private/stack-layout.ts b/projects/js-packages/charts/src/charts/bar-chart/private/stack-layout.ts index 366db0d4a2a9..b51b6e875998 100644 --- a/projects/js-packages/charts/src/charts/bar-chart/private/stack-layout.ts +++ b/projects/js-packages/charts/src/charts/bar-chart/private/stack-layout.ts @@ -107,7 +107,7 @@ export function getStackLayout( series: SeriesData[], comparison?: ComparisonTot * The series of a comparison total: at each category the comparisons have a reading, the net of their readings. * * @param comparisons - The comparison series to sum. - * @param label - The total's label. + * @param label - The total's key. * @return The total, a comparison series named `label`. */ export function getComparisonTotalSeries( comparisons: SeriesData[], label: string ): SeriesData { diff --git a/projects/js-packages/charts/src/charts/bar-chart/private/use-bar-slots.ts b/projects/js-packages/charts/src/charts/bar-chart/private/use-bar-slots.ts index 1b63f6a05da6..74995d88def4 100644 --- a/projects/js-packages/charts/src/charts/bar-chart/private/use-bar-slots.ts +++ b/projects/js-packages/charts/src/charts/bar-chart/private/use-bar-slots.ts @@ -2,6 +2,7 @@ import { useMemo } from 'react'; import { categoryKey, isSameCategory } from './category'; import { COMPARISON_SLOT, + COMPARISON_TOTAL_KEY, PRIMARY_SLOT, getOverlapPlacements, isComparisonSeries, @@ -42,13 +43,11 @@ export type SelectedSlot = SelectedBar & { members: SlotMember[] }; * * @param layout - How the chart places its series in a category. * @param seriesWithVisibility - Every series, with its index and whether it is visible. - * @param comparisonLabel - The label of a stacked layout's comparison total. * @return The slots, or undefined for a grouped layout. */ export function useBarSlots( layout: BarChartLayout, - seriesWithVisibility: ( SeriesEntry & { isVisible: boolean } )[], - comparisonLabel = '' + seriesWithVisibility: ( SeriesEntry & { isVisible: boolean } )[] ): BarSlots | undefined { return useMemo( () => { if ( layout === 'grouped' ) { @@ -78,7 +77,7 @@ export function useBarSlots( ? { series: getComparisonTotalSeries( comparisons.map( ( { series } ) => series ), - comparisonLabel + COMPARISON_TOTAL_KEY ), index: comparisons[ 0 ].index, } @@ -139,7 +138,7 @@ export function useBarSlots( thicknessOf, positions: getStopPositions( entries, slotKeys, slotOf ), }; - }, [ layout, seriesWithVisibility, comparisonLabel ] ); + }, [ layout, seriesWithVisibility ] ); } /** diff --git a/projects/js-packages/charts/src/charts/bar-chart/stories/index.docs.mdx b/projects/js-packages/charts/src/charts/bar-chart/stories/index.docs.mdx index bc67f7e50f7a..6eb22d585fbe 100644 --- a/projects/js-packages/charts/src/charts/bar-chart/stories/index.docs.mdx +++ b/projects/js-packages/charts/src/charts/bar-chart/stories/index.docs.mdx @@ -265,7 +265,7 @@ Set `layout="stacked"` to draw every series of a category as one bar, each serie - A series with no reading at a category is skipped there, and the segment above it starts where the one below ends. - Hiding a series from the legend closes the stacks up and rescales the axis. - The tooltip covers the whole stack: every series, last series first, with a `null` reading as "No data", then the total when there is more than one reading. It sits at the end of the positive values, or of the negative ones when the category has no positive value. -- Arrow keys step one category at a time, and the selected stack is outlined as a whole. Enter hands `onDatumActivate` the top segment, while pointer callbacks report the segment under the pointer. With comparisons, each category has a second stop on the comparison total after its stack; there the callbacks get the total's label as `key` and the summed point as the datum, not a series from `data`. +- Arrow keys step one category at a time, and the selected stack is outlined as a whole. Enter hands `onDatumActivate` the top segment, while pointer callbacks report the segment under the pointer. With comparisons, each category has a second stop on the comparison total after its stack; there the callbacks get `COMPARISON_TOTAL_KEY`, exported by the package, as `key` and the summed point as the datum, whatever `legend.comparisonItem` names it. - A bar radius (`--a8c-charts-border-radius-bar-chart`) rounds only the outer end of each stack, so the seams between segments stay flush. An outer segment shorter than the radius rounds only as far as its own length. - `type: 'comparison'` series are summed into one bar beside each stack, comparing totals rather than segments; hiding a series also drops the comparison of its `group`, and the bar is gone while no primary is shown. - The total bar takes the `options.stroke` of the first comparison that sets one, or else a gray that keeps 3:1 against the background. diff --git a/projects/js-packages/charts/src/charts/bar-chart/test/bar-chart-stacked.test.tsx b/projects/js-packages/charts/src/charts/bar-chart/test/bar-chart-stacked.test.tsx index 7816f3f29e39..418e5ea1750b 100644 --- a/projects/js-packages/charts/src/charts/bar-chart/test/bar-chart-stacked.test.tsx +++ b/projects/js-packages/charts/src/charts/bar-chart/test/bar-chart-stacked.test.tsx @@ -1,5 +1,6 @@ import { fireEvent, render, screen } from '@testing-library/react'; import userEvent from '@testing-library/user-event'; +import { COMPARISON_TOTAL_KEY } from '..'; import { GlobalChartsProvider } from '../../../providers'; import { selectedBarRingBounds as selectedRing } from '../../../test-utils/selected-bar-ring'; import { BarChartUnresponsive } from '../bar-chart'; @@ -344,18 +345,55 @@ describe( 'BarChart stacked layout', () => { expect( screen.getByText( 'Prev. 7 days' ) ).toBeInTheDocument(); } ); - it( 'stops on the comparison total after its stack, and rings it', async () => { + it( 'stops on the comparison total after its stack, rings it, and activates it by its fixed key', async () => { const user = userEvent.setup(); - renderStacked( { data: WITH_PREVIOUS } ); + const onDatumActivate = jest.fn(); + renderStacked( { + data: WITH_PREVIOUS, + legend: { comparisonItem: 'Prev. 7 days' }, + onDatumActivate, + } ); await user.tab(); - await user.keyboard( '{ArrowRight}{ArrowRight}' ); + await user.keyboard( '{ArrowRight}{ArrowRight}{Enter}' ); expect( screen.getByTestId( 'chart-tooltip-1' ) ).toHaveTextContent( - /Mon.*Total: 180.*Comparison period: 500/ + /Mon.*Total: 180.*Prev\. 7 days: 500/ ); expect( rounded( selectedRing() ) ).toEqual( rounded( previousBar() ) ); + expect( onDatumActivate ).toHaveBeenCalledWith( + expect.objectContaining( { + key: COMPARISON_TOTAL_KEY, + datum: expect.objectContaining( { value: 500 } ), + } ) + ); } ); + it.each( [ undefined, 'Prev' ] )( + 'keeps a primary named like the comparison item in its stack, with comparisonItem %p', + comparisonItem => { + const label = comparisonItem ?? 'Comparison period'; + const data: SeriesData[] = [ + { label: 'Desktop', group: 'd', data: [ day( 'Mon', 100 ) ] }, + { label, group: 'm', data: [ day( 'Mon', 60 ) ] }, + { + label: 'Desktop (prev)', + group: 'd', + options: { type: 'comparison' }, + data: [ day( 'Mon', 300 ) ], + }, + ]; + renderStacked( { data, showLegend: true, legend: { comparisonItem, interactive: true } } ); + + const desktop = barIn( data, 'Desktop' ); + const named = barIn( data, label ); + expect( named.x ).toBeCloseTo( desktop.x ); + expect( named.height / desktop.height ).toBeCloseTo( 60 / 100 ); + expect( + screen.getByRole( 'button', { name: new RegExp( `^${ label }:` ) } ) + ).toBeInTheDocument(); + } + ); + it.each( [ [ 'vertical', [ 300, 150, 50 ], 'top' ], [ 'horizontal', [ 300, 150, 50 ], 'right' ], diff --git a/projects/js-packages/charts/src/charts/bar-chart/use-bar-legend-items.ts b/projects/js-packages/charts/src/charts/bar-chart/use-bar-legend-items.ts index ae62fa4c3e36..a2303cd6a81b 100644 --- a/projects/js-packages/charts/src/charts/bar-chart/use-bar-legend-items.ts +++ b/projects/js-packages/charts/src/charts/bar-chart/use-bar-legend-items.ts @@ -3,6 +3,7 @@ import { useChartLegendItems, getComparisonItemLabel, } from '../../components/legend/hooks/use-chart-legend-items'; +import { COMPARISON_TOTAL_KEY } from './private/overlap-bars'; import { useBarColors } from './use-bar-colors'; import type { ChartLegendOptions } from '../../components/legend/hooks/use-chart-legend-items'; import type { BaseLegendItem } from '../../components/legend/types'; @@ -41,7 +42,7 @@ function getStackedLegendSeries( series: [ ...series, { - label: getComparisonItemLabel( comparisonItem ), + label: COMPARISON_TOTAL_KEY, data: [], options: { type: 'comparison' }, }, @@ -57,25 +58,26 @@ function getStackedLegendSeries( * @param items - The legend items. * @param layout - The layout the bars are drawn in. * @param seriesColors - Each series' bar color, by index. + * @param totalLabel - The name of a stacked layout's comparison total. * @return The legend items. */ function forBarLayout( data: SeriesData[], items: BaseLegendItem[], layout: BarChartLayout, - seriesColors: string[] + seriesColors: string[], + totalLabel: string ): BaseLegendItem[] { if ( layout === 'stacked' ) { // The comparison total is not a series to toggle: hiding a primary already drops its comparison from it. return items.map( item => - isComparison( data, item.seriesLabels?.[ 0 ] ) - ? { ...item, seriesLabels: undefined, interactive: false } + item.seriesLabels?.[ 0 ] === COMPARISON_TOTAL_KEY + ? { ...item, label: totalLabel, seriesLabels: undefined, interactive: false } : item ); } // Overlap lists every primary before every comparison, as it draws their slots, with opaque swatches. - if ( layout === 'overlap' ) { const opaque = items.map( item => item.shapeStyle ? { ...item, shapeStyle: { ...item.shapeStyle, opacity: undefined } } : item @@ -143,8 +145,18 @@ export function useBarLegendItems( ); const items = useChartLegendItems( data, chartLegendOptions, legendShape ); + const { comparisonItem } = options; return useMemo( - () => ( layout && seriesColors ? forBarLayout( data, items, layout, seriesColors ) : items ), - [ data, items, layout, seriesColors ] + () => + layout && seriesColors + ? forBarLayout( + data, + items, + layout, + seriesColors, + getComparisonItemLabel( comparisonItem ) + ) + : items, + [ data, items, layout, seriesColors, comparisonItem ] ); } diff --git a/projects/js-packages/charts/src/index.ts b/projects/js-packages/charts/src/index.ts index 2b3eabd4359d..3d3afeef1712 100644 --- a/projects/js-packages/charts/src/index.ts +++ b/projects/js-packages/charts/src/index.ts @@ -3,6 +3,7 @@ export { AreaChart, AreaChartUnresponsive } from './charts/area-chart'; export { BarChart, BarChartUnresponsive, + COMPARISON_TOTAL_KEY, useBarColors, useBarLegendItems, } from './charts/bar-chart'; diff --git a/projects/js-packages/charts/src/types.ts b/projects/js-packages/charts/src/types.ts index 3bd4e71e8c47..438e61e81dfb 100644 --- a/projects/js-packages/charts/src/types.ts +++ b/projects/js-packages/charts/src/types.ts @@ -804,8 +804,8 @@ export type BaseChartProps< T = DataPoint | DataPointDate | LeaderboardEntry > = /** * Callback for Enter or Space on the point keyboard navigation has selected: * the keyboard counterpart of a click. `index` is the point's position in its - * series and `key` the series label. A stacked bar chart's comparison total reports its own - * label and summed point, which name no series in `data`. + * series and `key` the series label. A stacked bar chart's comparison total reports + * `COMPARISON_TOTAL_KEY` and its summed point. */ onDatumActivate?: ( params: { datum: DataPoint | DataPointDate; From 66bcd6a4c610d2f768fb06085fa0deadf20f122d Mon Sep 17 00:00:00 2001 From: Chi-Hsuan Huang Date: Wed, 25 Nov 2026 15:09:10 +0800 Subject: [PATCH 13/28] Premium Analytics: Read the stacked previous-period total by the chart's fixed key Strip COMPARISON_TOTAL_KEY from the Devices tooltip instead of every key outside the data, and stop handing a stacked chart comparisonSeriesItems, which it ignores and now warns about. --- .../packages/externals/src/index.ts | 1 + ...arative-bar-chart-previous-period.test.tsx | 8 +++++-- .../comparative-bar-chart.tsx | 12 +++------- .../src/hooks/use-comparative-legend.ts | 23 ++++++++++++------- 4 files changed, 25 insertions(+), 19 deletions(-) diff --git a/projects/packages/premium-analytics/packages/externals/src/index.ts b/projects/packages/premium-analytics/packages/externals/src/index.ts index a942c0a80cd0..1f5073f7ae5a 100644 --- a/projects/packages/premium-analytics/packages/externals/src/index.ts +++ b/projects/packages/premium-analytics/packages/externals/src/index.ts @@ -16,6 +16,7 @@ import '@automattic/jetpack-components/jetpack-footer/style.scss'; */ export { BarChart, + COMPARISON_TOTAL_KEY, ConversionFunnelChart, GeoChart, GlobalChartsProvider, diff --git a/projects/packages/premium-analytics/packages/widgets-toolkit/src/components/chart-comparative-bar/__tests__/comparative-bar-chart-previous-period.test.tsx b/projects/packages/premium-analytics/packages/widgets-toolkit/src/components/chart-comparative-bar/__tests__/comparative-bar-chart-previous-period.test.tsx index 7c91370744de..6bed2bfe4ee0 100644 --- a/projects/packages/premium-analytics/packages/widgets-toolkit/src/components/chart-comparative-bar/__tests__/comparative-bar-chart-previous-period.test.tsx +++ b/projects/packages/premium-analytics/packages/widgets-toolkit/src/components/chart-comparative-bar/__tests__/comparative-bar-chart-previous-period.test.tsx @@ -1,7 +1,11 @@ /** * External dependencies */ -import { GlobalChartsProvider, useGlobalChartsContext } from '@jetpack-premium-analytics/externals'; +import { + COMPARISON_TOTAL_KEY, + GlobalChartsProvider, + useGlobalChartsContext, +} from '@jetpack-premium-analytics/externals'; import { render, screen } from '@testing-library/react'; import userEvent from '@testing-library/user-event'; /** @@ -253,7 +257,7 @@ describe( 'ComparativeBarChart previous-period toggle', () => { datumByKey: { Views: { ...entry( 'Views', 100 ), index: 0 }, Visitors: { ...entry( 'Visitors', 40 ), index: 1 }, - 'Comparison period': { ...entry( 'Comparison period', 110 ), index: 2 }, + [ COMPARISON_TOTAL_KEY ]: { ...entry( COMPARISON_TOTAL_KEY, 110 ), index: 2 }, }, }, } ); diff --git a/projects/packages/premium-analytics/packages/widgets-toolkit/src/components/chart-comparative-bar/comparative-bar-chart.tsx b/projects/packages/premium-analytics/packages/widgets-toolkit/src/components/chart-comparative-bar/comparative-bar-chart.tsx index 8986ee283ef5..ffd844f8fa3a 100644 --- a/projects/packages/premium-analytics/packages/widgets-toolkit/src/components/chart-comparative-bar/comparative-bar-chart.tsx +++ b/projects/packages/premium-analytics/packages/widgets-toolkit/src/components/chart-comparative-bar/comparative-bar-chart.tsx @@ -3,6 +3,7 @@ */ import { BarChart, + COMPARISON_TOTAL_KEY, Stack, getBucketInfo, useBarColors, @@ -407,14 +408,7 @@ export function ComparativeBarChart( { const augmented = { ...datumByKey }; // A stack's previous-period total is the chart's own bar, not a series; each group's previous value is read out instead. - if ( layout === 'stacked' ) { - const labels = new Set( alignedSeries.map( ( { label } ) => label ) ); - for ( const key of Object.keys( augmented ) ) { - if ( ! labels.has( key ) ) { - delete augmented[ key ]; - } - } - } + delete augmented[ COMPARISON_TOTAL_KEY ]; for ( const [ index, seriesData ] of alignedSeries.entries() ) { if ( seriesData.options?.type !== 'comparison' || augmented[ seriesData.label ] ) { @@ -445,7 +439,7 @@ export function ComparativeBarChart( { return { ...tooltipData, datumByKey: augmented }; }, - [ alignedSeries, primarySeriesByGroup, layout ] + [ alignedSeries, primarySeriesByGroup ] ); const renderTooltip = useCallback( diff --git a/projects/packages/premium-analytics/packages/widgets-toolkit/src/hooks/use-comparative-legend.ts b/projects/packages/premium-analytics/packages/widgets-toolkit/src/hooks/use-comparative-legend.ts index 4d841f7a3c0d..03cc0097c437 100644 --- a/projects/packages/premium-analytics/packages/widgets-toolkit/src/hooks/use-comparative-legend.ts +++ b/projects/packages/premium-analytics/packages/widgets-toolkit/src/hooks/use-comparative-legend.ts @@ -35,15 +35,22 @@ export function useComparativeLegend( () => ( { collapseGroups: true, interactive, - comparisonSeriesItems: ( metric: string ) => - sprintf( - /* translators: 1: metric name, e.g. "Views"; 2: comparison period, e.g. "Prev. 30 days". */ - _x( '%1$s (%2$s)', 'metric with its comparison period', 'jetpack-premium-analytics-pkg' ), - metric, - comparisonLabel - ), + // A stack sums its comparisons into one bar, so there is no per-metric item to name. + ...( barLayout !== 'stacked' && { + comparisonSeriesItems: ( metric: string ) => + sprintf( + /* translators: 1: metric name, e.g. "Views"; 2: comparison period, e.g. "Prev. 30 days". */ + _x( + '%1$s (%2$s)', + 'metric with its comparison period', + 'jetpack-premium-analytics-pkg' + ), + metric, + comparisonLabel + ), + } ), } ), - [ interactive, comparisonLabel ] + [ interactive, comparisonLabel, barLayout ] ); const itemOptions = useMemo( () => ( { ...config, layout: barLayout } ), [ config, barLayout ] ); const items = useLockedPrimaryLegendItems( series, itemOptions, shape, primaryLabel ); From 0d9987c145d834772773146d4c917e366eb4767f Mon Sep 17 00:00:00 2001 From: Chi-Hsuan Huang Date: Wed, 25 Nov 2026 15:19:57 +0800 Subject: [PATCH 14/28] Charts: Color a stacked comparison total from a themeable catalog role Add --a8c-charts-color-comparison, mapped to the WPDS neutral-weak foreground, and tone it to 3:1 against the background, as the grouped and overlap layouts tone their palette colors. --- projects/js-packages/charts/TOKENS.md | 1 + .../changelog/charts-stacked-comparison | 2 +- .../charts/bar-chart/private/overlap-bars.ts | 10 ------- .../charts/bar-chart/stories/index.docs.mdx | 2 +- .../bar-chart/stories/index.stories.tsx | 2 +- .../test/use-bar-legend-items.test.tsx | 28 +++++++++++++------ .../src/charts/bar-chart/use-bar-colors.ts | 22 +++++++-------- .../chart-context/global-charts-provider.tsx | 7 +++++ .../chart-context/private/catalog-pointers.ts | 2 ++ .../chart-context/stories/index.api.mdx | 1 + .../chart-context/stories/index.docs.mdx | 3 ++ .../src/providers/chart-context/types.ts | 2 ++ .../charts/src/styles/chart-scope.scss | 2 ++ 13 files changed, 51 insertions(+), 33 deletions(-) diff --git a/projects/js-packages/charts/TOKENS.md b/projects/js-packages/charts/TOKENS.md index beb5cc8aecd8..f24160c15697 100644 --- a/projects/js-packages/charts/TOKENS.md +++ b/projects/js-packages/charts/TOKENS.md @@ -91,6 +91,7 @@ The scope element is the wrapper a chart is rendered into, which sits **above** | `--a8c-charts-color-trend-up` | `--wpds-color-foreground-content-success-weak` | `#008030` | | `--a8c-charts-color-trend-down` | `--wpds-color-foreground-content-error-weak` | `#cc1818` | | `--a8c-charts-color-trend-neutral` | `--wpds-color-foreground-content-neutral-weak` | `#707070` | +| `--a8c-charts-color-comparison` | `--wpds-color-foreground-content-neutral-weak` | `#707070` | | `--a8c-charts-color-background` | `--wpds-color-background-surface-neutral-strong` | `#fff` | | `--a8c-charts-color-surface` | `--wpds-color-background-surface-neutral-strong` | `#fff` | | `--a8c-charts-color-surface-secondary` | `--wpds-color-background-surface-neutral-weak` | `#f4f4f4` | diff --git a/projects/js-packages/charts/changelog/charts-stacked-comparison b/projects/js-packages/charts/changelog/charts-stacked-comparison index 211fd9b72b5b..57d41ba6d8e4 100644 --- a/projects/js-packages/charts/changelog/charts-stacked-comparison +++ b/projects/js-packages/charts/changelog/charts-stacked-comparison @@ -1,4 +1,4 @@ Significance: minor Type: added -Bar chart: Sum comparison series into one bar beside each stack in the stacked layout, which callbacks report as `COMPARISON_TOTAL_KEY`. +Bar chart: Sum comparison series into one bar beside each stack in the stacked layout, keyed `COMPARISON_TOTAL_KEY` and colored by the new `--a8c-charts-color-comparison` role. diff --git a/projects/js-packages/charts/src/charts/bar-chart/private/overlap-bars.ts b/projects/js-packages/charts/src/charts/bar-chart/private/overlap-bars.ts index 48f3ae470a74..c8da2ebc2aaf 100644 --- a/projects/js-packages/charts/src/charts/bar-chart/private/overlap-bars.ts +++ b/projects/js-packages/charts/src/charts/bar-chart/private/overlap-bars.ts @@ -88,16 +88,6 @@ const awayFrom = ( background: string ): string => const opposite = ( end: string ): string => ( end === '#000000' ? '#ffffff' : '#000000' ); -/** - * The gray nearest the background that keeps 3:1 against it. - * - * @param background - The hex chart background. - * @return A hex color. - */ -export function neutralWithContrast( background: string ): string { - return tintWithContrast( awayFrom( background ), background ); -} - /** * The tone of a color nearest the background that keeps 3:1 against it. * diff --git a/projects/js-packages/charts/src/charts/bar-chart/stories/index.docs.mdx b/projects/js-packages/charts/src/charts/bar-chart/stories/index.docs.mdx index 6eb22d585fbe..d2d92ea7fccc 100644 --- a/projects/js-packages/charts/src/charts/bar-chart/stories/index.docs.mdx +++ b/projects/js-packages/charts/src/charts/bar-chart/stories/index.docs.mdx @@ -268,7 +268,7 @@ Set `layout="stacked"` to draw every series of a category as one bar, each serie - Arrow keys step one category at a time, and the selected stack is outlined as a whole. Enter hands `onDatumActivate` the top segment, while pointer callbacks report the segment under the pointer. With comparisons, each category has a second stop on the comparison total after its stack; there the callbacks get `COMPARISON_TOTAL_KEY`, exported by the package, as `key` and the summed point as the datum, whatever `legend.comparisonItem` names it. - A bar radius (`--a8c-charts-border-radius-bar-chart`) rounds only the outer end of each stack, so the seams between segments stay flush. An outer segment shorter than the radius rounds only as far as its own length. - `type: 'comparison'` series are summed into one bar beside each stack, comparing totals rather than segments; hiding a series also drops the comparison of its `group`, and the bar is gone while no primary is shown. -- The total bar takes the `options.stroke` of the first comparison that sets one, or else a gray that keeps 3:1 against the background. +- The total bar takes the `options.stroke` of the first comparison that sets one, or else the `--a8c-charts-color-comparison` role, a gray by default, toned to keep 3:1 against the background. - The tooltip lists the total after the stack's, and `legend.comparisonItem` adds one static legend item while the bar is drawn; both are named by that string, or "Comparison period". - `showZeroValues` and `legend.comparisonSeriesItems` have no effect, and warn once in development. - Works with `orientation="horizontal"`, where the first series is the left-most segment. diff --git a/projects/js-packages/charts/src/charts/bar-chart/stories/index.stories.tsx b/projects/js-packages/charts/src/charts/bar-chart/stories/index.stories.tsx index 5be29c245f90..d34287dc69d1 100644 --- a/projects/js-packages/charts/src/charts/bar-chart/stories/index.stories.tsx +++ b/projects/js-packages/charts/src/charts/bar-chart/stories/index.stories.tsx @@ -992,7 +992,7 @@ export const StackedComparison: Story = { docs: { description: { story: - "Each device is paired by `group` with its previous four weeks, and those are summed into one bar beside each stack, in a gray that keeps 3:1 against the background. Hover a bar, or tab in and use the arrow keys, to read each device, the total, then the previous period's total; each day has a second stop on the gray bar. Hide a device from the legend and its previous period leaves the gray bar too, so both bars sum the same devices; `legend.comparisonItem` names that bar in the legend and the tooltip.", + "Each device is paired by `group` with its previous four weeks, and those are summed into one bar beside each stack, in the `--a8c-charts-color-comparison` role toned to keep 3:1 against the background. Hover a bar, or tab in and use the arrow keys, to read each device, the total, then the previous period's total; each day has a second stop on the gray bar. Hide a device from the legend and its previous period leaves the gray bar too, so both bars sum the same devices; `legend.comparisonItem` names that bar in the legend and the tooltip.", }, }, }, diff --git a/projects/js-packages/charts/src/charts/bar-chart/test/use-bar-legend-items.test.tsx b/projects/js-packages/charts/src/charts/bar-chart/test/use-bar-legend-items.test.tsx index 44cba1045a5c..d6d2fdd14d4f 100644 --- a/projects/js-packages/charts/src/charts/bar-chart/test/use-bar-legend-items.test.tsx +++ b/projects/js-packages/charts/src/charts/bar-chart/test/use-bar-legend-items.test.tsx @@ -114,15 +114,25 @@ describe( 'useBarLegendItems', () => { { wrapper } ).result.current; - test( 'colors every stacked comparison in the gray nearest the background that keeps 3:1', () => { - const { colors, background } = stackedColors( twoMetricData ); - const [ red, green, blue ] = colors[ 1 ].slice( 1 ).match( /../g ) ?? []; - - expect( colors[ 3 ] ).toBe( colors[ 1 ] ); - expect( [ green, blue ] ).toEqual( [ red, red ] ); - expect( contrastRatio( colors[ 1 ], background ) ).toBeGreaterThanOrEqual( 3 ); - expect( contrastRatio( colors[ 1 ], background ) ).toBeLessThan( 3.2 ); - } ); + test.each( [ + [ 'the default gray', undefined, true ], + [ 'a themed role', '#3858e9', false ], + ] )( + 'colors every stacked comparison in the comparison role toned to 3:1, from %s', + ( _case, role, gray ) => { + if ( role ) { + document.documentElement.style.setProperty( '--a8c-charts-color-comparison', role ); + } + const { colors, background } = stackedColors( twoMetricData ); + document.documentElement.style.removeProperty( '--a8c-charts-color-comparison' ); + const [ red, green, blue ] = colors[ 1 ].slice( 1 ).match( /../g ) ?? []; + + expect( colors[ 3 ] ).toBe( colors[ 1 ] ); + expect( red === green && green === blue ).toBe( gray ); + expect( contrastRatio( colors[ 1 ], background ) ).toBeGreaterThanOrEqual( 3 ); + expect( contrastRatio( colors[ 1 ], background ) ).toBeLessThan( 3.2 ); + } + ); test( "colors every stacked comparison in the first comparison's own stroke", () => { const { colors } = stackedColors( diff --git a/projects/js-packages/charts/src/charts/bar-chart/use-bar-colors.ts b/projects/js-packages/charts/src/charts/bar-chart/use-bar-colors.ts index b330d7ecb4bb..472556d31a0e 100644 --- a/projects/js-packages/charts/src/charts/bar-chart/use-bar-colors.ts +++ b/projects/js-packages/charts/src/charts/bar-chart/use-bar-colors.ts @@ -1,13 +1,12 @@ import { useCallback } from 'react'; import { useGlobalChartsContext } from '../../providers/chart-context/hooks/use-global-charts-context'; -import { BACKGROUND_FALLBACK } from '../../providers/chart-context/private/catalog-pointers'; +import { + BACKGROUND_FALLBACK, + COMPARISON_FALLBACK, +} from '../../providers/chart-context/private/catalog-pointers'; import { isValidHexColor } from '../../utils/color-utils'; import { getGroupedBarColors } from './private/grouped-bars'; -import { - getOverlapBarColors, - isComparisonSeries, - neutralWithContrast, -} from './private/overlap-bars'; +import { getOverlapBarColors, isComparisonSeries, tintWithContrast } from './private/overlap-bars'; import type { BarChartLayout, SeriesData } from '../../types'; export type GetBarColors = ( @@ -24,6 +23,7 @@ export function useBarColors(): GetBarColors { const { getElementStyles, backgroundColor = BACKGROUND_FALLBACK, + comparisonColor = COMPARISON_FALLBACK, theme, } = useGlobalChartsContext(); const comparisonOpacity = theme.barChart?.barStyles?.comparison?.opacity; @@ -33,19 +33,19 @@ export function useBarColors(): GetBarColors { const colors = series.map( ( data, index ) => getElementStyles( { data, index } ).color ); if ( layout === 'stacked' ) { - // Comparisons share one bar: no palette slot, and the first stroke set among them, else a contrast gray. + // Comparisons share one bar: no palette slot, and the first stroke set among them, else the comparison role. const primaries = series.filter( data => ! isComparisonSeries( data ) ); const stroked = series.findIndex( data => isComparisonSeries( data ) && data.options?.stroke ); const firstComparison = series.findIndex( isComparisonSeries ); - const comparisonColor = + const totalColor = stroked === -1 && isValidHexColor( backgroundColor ) - ? neutralWithContrast( backgroundColor ) + ? tintWithContrast( comparisonColor, backgroundColor ) : colors[ stroked === -1 ? firstComparison : stroked ]; return series.map( data => isComparisonSeries( data ) - ? comparisonColor + ? totalColor : getElementStyles( { data, index: primaries.indexOf( data ) } ).color ); } @@ -64,6 +64,6 @@ export function useBarColors(): GetBarColors { backgroundColor ); }, - [ getElementStyles, backgroundColor, comparisonOpacity ] + [ getElementStyles, backgroundColor, comparisonColor, comparisonOpacity ] ); } diff --git a/projects/js-packages/charts/src/providers/chart-context/global-charts-provider.tsx b/projects/js-packages/charts/src/providers/chart-context/global-charts-provider.tsx index 26e2ed849d33..8f6c30bfb0a6 100644 --- a/projects/js-packages/charts/src/providers/chart-context/global-charts-provider.tsx +++ b/projects/js-packages/charts/src/providers/chart-context/global-charts-provider.tsx @@ -28,6 +28,7 @@ import { ChartScopeContext } from '../chart-scope/chart-scope-context'; import { BACKGROUND_FALLBACK, CATALOG_POINTERS, + COMPARISON_FALLBACK, LABEL_FALLBACK, LABEL_INVERSE_FALLBACK, } from './private/catalog-pointers'; @@ -42,6 +43,7 @@ import type { FC, ReactNode } from 'react'; interface ColorCache { colors: string[]; background: string; + comparison: string; labelColors: string[]; colorAt: ( index: number ) => string; } @@ -103,6 +105,7 @@ export const GlobalChartsProvider: FC< GlobalChartsProviderProps > = ( { const [ colorCache, setColorCache ] = useState< ColorCache >( () => ( { colors: [], background: BACKGROUND_FALLBACK, + comparison: COMPARISON_FALLBACK, labelColors: PLACEHOLDER_LABEL_COLORS, colorAt: createPaletteGenerator( [ SERIES_SLOT_1_FALLBACK ], @@ -144,6 +147,8 @@ export const GlobalChartsProvider: FC< GlobalChartsProviderProps > = ( { setColorCache( { colors: resolvedColors, background: backgroundHex, + comparison: + resolveOpaqueHex( CATALOG_POINTERS.comparison, resolveAtWrapper ) ?? COMPARISON_FALLBACK, labelColors, colorAt: createPaletteGenerator( resolvedColors, backgroundHex, labelColors ), } ); @@ -372,6 +377,7 @@ export const GlobalChartsProvider: FC< GlobalChartsProviderProps > = ( { formatting, getElementStyles, backgroundColor: colorCache.background, + comparisonColor: colorCache.comparison, toggleSeriesVisibility, setSeriesVisibility, setChartHiddenSeries, @@ -390,6 +396,7 @@ export const GlobalChartsProvider: FC< GlobalChartsProviderProps > = ( { formatting, getElementStyles, colorCache.background, + colorCache.comparison, toggleSeriesVisibility, setSeriesVisibility, setChartHiddenSeries, diff --git a/projects/js-packages/charts/src/providers/chart-context/private/catalog-pointers.ts b/projects/js-packages/charts/src/providers/chart-context/private/catalog-pointers.ts index 65cc9e7ac6e1..3f5159bf9023 100644 --- a/projects/js-packages/charts/src/providers/chart-context/private/catalog-pointers.ts +++ b/projects/js-packages/charts/src/providers/chart-context/private/catalog-pointers.ts @@ -8,6 +8,7 @@ import { SERIES_PALETTE_POINTERS } from './series-palette'; export const BACKGROUND_FALLBACK = '#ffffff'; export const LABEL_FALLBACK = '#1e1e1e'; export const LABEL_INVERSE_FALLBACK = '#f0f0f0'; +export const COMPARISON_FALLBACK = '#707070'; export const CATALOG_POINTERS = { background: `var(--a8c-charts-color-background, ${ BACKGROUND_FALLBACK })`, @@ -22,6 +23,7 @@ export const CATALOG_POINTERS = { axisY: 'var(--a8c-charts-color-axis-y, none)', tickY: 'var(--a8c-charts-color-tick-y, none)', annotation: 'var(--a8c-charts-color-annotation, #1e1e1e)', + comparison: `var(--a8c-charts-color-comparison, ${ COMPARISON_FALLBACK })`, surface: 'var(--a8c-charts-color-surface, #fff)', surfaceSecondary: 'var(--a8c-charts-color-surface-secondary, #f4f4f4)', track: 'var(--a8c-charts-color-track, #f0f0f0)', diff --git a/projects/js-packages/charts/src/providers/chart-context/stories/index.api.mdx b/projects/js-packages/charts/src/providers/chart-context/stories/index.api.mdx index 6f2c7e04b1fc..6ca3dfe4e8c0 100644 --- a/projects/js-packages/charts/src/providers/chart-context/stories/index.api.mdx +++ b/projects/js-packages/charts/src/providers/chart-context/stories/index.api.mdx @@ -75,6 +75,7 @@ interface GlobalChartsContextValue { | Member | Note | | ------ | ---- | | `backgroundColor` | The chart background as an opaque hex, for colors that must keep contrast against it. Optional on the type, so a hand-built context value without it still type-checks; `GlobalChartsProvider` always supplies it. | +| `comparisonColor` | The `--a8c-charts-color-comparison` role as an opaque hex. A stacked bar chart tones it to keep 3:1 against `backgroundColor` for the bar it sums comparison series into. | | `seedChartHiddenSeries` | Backs the `defaultHiddenSeries` prop. The provider records which chart IDs it has seeded, so a chart that unmounts and comes back keeps whatever the reader had shown or hidden. | | `isColorPaletteResolved` | `false` until the color cache has resolved from the DOM and painted. Use it to defer transitions that would otherwise interpolate from a fallback color. | | `formatting` | `{ locale?: string; timeZone?: string }`, from the provider's props. Read it with `useChartFormatting()`, which returns the runtime's own defaults outside a provider rather than throwing. | diff --git a/projects/js-packages/charts/src/providers/chart-context/stories/index.docs.mdx b/projects/js-packages/charts/src/providers/chart-context/stories/index.docs.mdx index 7750d01ec062..bc9ad4c52f4a 100644 --- a/projects/js-packages/charts/src/providers/chart-context/stories/index.docs.mdx +++ b/projects/js-packages/charts/src/providers/chart-context/stories/index.docs.mdx @@ -215,6 +215,9 @@ Chart color defaults use `--a8c-charts-color-*` catalog roles, declared anywhere --a8c-charts-color-trend-neutral: #707070; --a8c-charts-color-trend-down: #cc1818; + /* A stacked bar chart's comparison total, toned to 3:1 against the background */ + --a8c-charts-color-comparison: #707070; + /* Floating surfaces: the funnel plate, the geo dataless fill */ --a8c-charts-color-surface-secondary: #f4f4f4; }` } diff --git a/projects/js-packages/charts/src/providers/chart-context/types.ts b/projects/js-packages/charts/src/providers/chart-context/types.ts index 929ee132a633..1efa438c3ceb 100644 --- a/projects/js-packages/charts/src/providers/chart-context/types.ts +++ b/projects/js-packages/charts/src/providers/chart-context/types.ts @@ -43,6 +43,8 @@ export interface GlobalChartsContextValue { getElementStyles: ( params: GetElementStylesParams ) => ElementStyles; /** The chart background as an opaque hex, for colors that must keep contrast against it. Optional so a hand-built context value still type-checks. */ backgroundColor?: string; + /** The `--a8c-charts-color-comparison` role as an opaque hex, which a stacked bar chart tones to 3:1 for its comparison total. */ + comparisonColor?: string; // Series visibility management shared by charts, legends, and programmatic controls. toggleSeriesVisibility: ( chartId: string, seriesLabel: string ) => void; setSeriesVisibility: ( chartId: string, seriesLabel: string, visible: boolean ) => void; diff --git a/projects/js-packages/charts/src/styles/chart-scope.scss b/projects/js-packages/charts/src/styles/chart-scope.scss index f07a8d4f3b06..3c4e69506b74 100644 --- a/projects/js-packages/charts/src/styles/chart-scope.scss +++ b/projects/js-packages/charts/src/styles/chart-scope.scss @@ -50,6 +50,8 @@ --a8c-charts-color-trend-up: var(--wpds-color-foreground-content-success-weak); --a8c-charts-color-trend-down: var(--wpds-color-foreground-content-error-weak); --a8c-charts-color-trend-neutral: var(--wpds-color-foreground-content-neutral-weak); + // A stacked bar chart's comparison total, toned to 3:1 against the background. + --a8c-charts-color-comparison: var(--wpds-color-foreground-content-neutral-weak); --a8c-charts-color-background: var(--wpds-color-background-surface-neutral-strong); // Surfaces floating over the chart — the annotation label, the zoom-reset // control. Same WPDS token as --a8c-charts-color-background but From efbf5100f57a2fb9ff22fd89869179810f56a50d Mon Sep 17 00:00:00 2001 From: Chi-Hsuan Huang Date: Wed, 25 Nov 2026 15:29:49 +0800 Subject: [PATCH 15/28] Charts: Keep a stacked total whole and pattern stacks like their colors A comparison hidden on its own left the total a partial sum that a stack offers no control to restore, so only its primary's group decides now. Patterns follow the primaries' order, as colors do, so a comparison listed between primaries no longer shifts the patterns after it. --- .../charts/src/charts/bar-chart/bar-chart.tsx | 16 ++++++- .../src/charts/bar-chart/private/index.ts | 2 +- .../charts/bar-chart/private/use-bar-slots.ts | 5 +- .../charts/bar-chart/stories/index.docs.mdx | 2 +- .../bar-chart/test/bar-chart-stacked.test.tsx | 47 ++++++++++++++++++- 5 files changed, 64 insertions(+), 8 deletions(-) diff --git a/projects/js-packages/charts/src/charts/bar-chart/bar-chart.tsx b/projects/js-packages/charts/src/charts/bar-chart/bar-chart.tsx index b54894b0ed66..3be4d75773e0 100644 --- a/projects/js-packages/charts/src/charts/bar-chart/bar-chart.tsx +++ b/projects/js-packages/charts/src/charts/bar-chart/bar-chart.tsx @@ -45,6 +45,7 @@ import { COMPARISON_TICK_GAP_FACTOR, BASE_BAND_PADDING_INNER, COMPARISON_SLOT, + isComparisonSeries, isBarRendered, SlotTooltipMembers, useBarStops, @@ -587,9 +588,20 @@ const BarChartInternal: FC< BarChartProps > = ( { [ chartOptions.tooltip, comparisonEntries ] ); + // A stack patterns its primaries by their place among the primaries, as it colors them, and its total next. + const patternTypes = useMemo( () => { + const primaries = dataSorted.filter( series => ! isComparisonSeries( series ) ); + return dataSorted.map( ( series, index ) => { + if ( ! isStacked ) { + return index; + } + return isComparisonSeries( series ) ? primaries.length : primaries.indexOf( series ); + } ); + }, [ dataSorted, isStacked ] ); + const renderPattern = useCallback( ( index: number, color: string ) => { - const patternType = index % 4; + const patternType = ( patternTypes[ index ] ?? index ) % 4; const id = getPatternId( chartId, index ); const commonProps = { id, @@ -620,7 +632,7 @@ const BarChartInternal: FC< BarChartProps > = ( { return ; } }, - [ chartId ] + [ chartId, patternTypes ] ); const createPatternBorderStyle = useCallback( diff --git a/projects/js-packages/charts/src/charts/bar-chart/private/index.ts b/projects/js-packages/charts/src/charts/bar-chart/private/index.ts index 3f4ea5a66758..d998d966ecd3 100644 --- a/projects/js-packages/charts/src/charts/bar-chart/private/index.ts +++ b/projects/js-packages/charts/src/charts/bar-chart/private/index.ts @@ -20,4 +20,4 @@ export { BASE_BAND_PADDING_INNER } from './use-bar-chart-options'; export { isBarRendered } from './value-domain'; export { BandHighlight } from './band-highlight'; export { BandTooltip } from './band-tooltip'; -export { COMPARISON_SLOT } from './overlap-bars'; +export { COMPARISON_SLOT, isComparisonSeries } from './overlap-bars'; diff --git a/projects/js-packages/charts/src/charts/bar-chart/private/use-bar-slots.ts b/projects/js-packages/charts/src/charts/bar-chart/private/use-bar-slots.ts index 74995d88def4..09ee8f10c1b7 100644 --- a/projects/js-packages/charts/src/charts/bar-chart/private/use-bar-slots.ts +++ b/projects/js-packages/charts/src/charts/bar-chart/private/use-bar-slots.ts @@ -65,8 +65,9 @@ export function useBarSlots( isVisible || isComparisonSeries( series ) ? [] : [ series.group ] ) ); - // A comparison leaves the total with the primary it is paired with, so both bars sum the same series. - const comparisons = visible.filter( + // A comparison leaves the total with the primary it is paired with, so both bars sum the same series; + // its own hidden state is ignored, since a stack offers no control to show it again. + const comparisons = seriesWithVisibility.filter( ( { series } ) => isComparisonSeries( series ) && ( visibleGroups.has( series.group ) || ! hiddenGroups.has( series.group ) ) diff --git a/projects/js-packages/charts/src/charts/bar-chart/stories/index.docs.mdx b/projects/js-packages/charts/src/charts/bar-chart/stories/index.docs.mdx index d2d92ea7fccc..b9a5c2492b25 100644 --- a/projects/js-packages/charts/src/charts/bar-chart/stories/index.docs.mdx +++ b/projects/js-packages/charts/src/charts/bar-chart/stories/index.docs.mdx @@ -267,7 +267,7 @@ Set `layout="stacked"` to draw every series of a category as one bar, each serie - The tooltip covers the whole stack: every series, last series first, with a `null` reading as "No data", then the total when there is more than one reading. It sits at the end of the positive values, or of the negative ones when the category has no positive value. - Arrow keys step one category at a time, and the selected stack is outlined as a whole. Enter hands `onDatumActivate` the top segment, while pointer callbacks report the segment under the pointer. With comparisons, each category has a second stop on the comparison total after its stack; there the callbacks get `COMPARISON_TOTAL_KEY`, exported by the package, as `key` and the summed point as the datum, whatever `legend.comparisonItem` names it. - A bar radius (`--a8c-charts-border-radius-bar-chart`) rounds only the outer end of each stack, so the seams between segments stay flush. An outer segment shorter than the radius rounds only as far as its own length. -- `type: 'comparison'` series are summed into one bar beside each stack, comparing totals rather than segments; hiding a series also drops the comparison of its `group`, and the bar is gone while no primary is shown. +- `type: 'comparison'` series are summed into one bar beside each stack, comparing totals rather than segments; hiding a series also drops the comparison of its `group`, and the bar is gone while no primary is shown. A comparison's own hidden state does not apply, since the stack offers no control to show it again; to drop the comparison period, leave those series out of `data`. - The total bar takes the `options.stroke` of the first comparison that sets one, or else the `--a8c-charts-color-comparison` role, a gray by default, toned to keep 3:1 against the background. - The tooltip lists the total after the stack's, and `legend.comparisonItem` adds one static legend item while the bar is drawn; both are named by that string, or "Comparison period". - `showZeroValues` and `legend.comparisonSeriesItems` have no effect, and warn once in development. diff --git a/projects/js-packages/charts/src/charts/bar-chart/test/bar-chart-stacked.test.tsx b/projects/js-packages/charts/src/charts/bar-chart/test/bar-chart-stacked.test.tsx index 418e5ea1750b..8757ea3af8d0 100644 --- a/projects/js-packages/charts/src/charts/bar-chart/test/bar-chart-stacked.test.tsx +++ b/projects/js-packages/charts/src/charts/bar-chart/test/bar-chart-stacked.test.tsx @@ -450,7 +450,26 @@ describe( 'BarChart stacked layout', () => { } ); it.each( [ - [ 'every comparison', WITH_PREVIOUS, WITH_PREVIOUS.slice( 3 ), false ], + [ 'one comparison', WITH_PREVIOUS.slice( 3, 4 ) ], + [ 'every comparison', WITH_PREVIOUS.slice( 3 ) ], + ] )( + 'keeps %s hidden on its own in the total, which a stack offers no control to show again', + ( _case, hidden ) => { + renderStacked( { + data: WITH_PREVIOUS, + showLegend: true, + legend: { comparisonItem: 'Prev. 7 days' }, + defaultHiddenSeries: hidden.map( series => series.label ), + } ); + + expect( previousBar().height / barIn( WITH_PREVIOUS, 'Desktop' ).height ).toBeCloseTo( + 500 / 100 + ); + expect( screen.getByText( 'Prev. 7 days' ) ).toBeInTheDocument(); + } + ); + + it.each( [ [ 'every primary', WITH_PREVIOUS, DATA, false ], [ 'the primary of the only comparison', @@ -458,7 +477,6 @@ describe( 'BarChart stacked layout', () => { DATA.slice( 0, 1 ), false, ], - [ 'only the first comparison', WITH_PREVIOUS, WITH_PREVIOUS.slice( 3, 4 ), true ], ] )( 'lists the comparison item only while the total is drawn, hiding %s', ( _case, data, hidden, listed ) => { @@ -473,6 +491,31 @@ describe( 'BarChart stacked layout', () => { } ); + it( 'patterns each stacked series by its place among the primaries, as it colors them', () => { + const desktop: SeriesData = { label: 'Desktop', data: [ day( 'Mon', 100 ) ] }; + const mobile: SeriesData = { label: 'Mobile', data: [ day( 'Mon', 60 ) ] }; + const previous = ( series: SeriesData ): SeriesData => ( { + ...series, + label: `${ series.label } (prev)`, + options: { type: 'comparison' }, + } ); + const mobilePattern = ( data: SeriesData[] ) => { + const { unmount } = renderStacked( { data, withPatterns: true } ); + const id = + barRects()[ 1 ] + .getAttribute( 'fill' ) + ?.match( /url\(#(.+)\)/ )?.[ 1 ] ?? ''; + // eslint-disable-next-line testing-library/no-node-access -- visx patterns carry no test id. + const markup = document.getElementById( id )?.innerHTML; + unmount(); + return markup; + }; + + expect( mobilePattern( [ desktop, previous( desktop ), mobile, previous( mobile ) ] ) ).toBe( + mobilePattern( [ desktop, mobile, previous( desktop ), previous( mobile ) ] ) + ); + } ); + it( 'ignores legend.comparisonSeriesItems, and says so', () => { const warn = jest.spyOn( console, 'warn' ).mockImplementation( () => {} ); renderStacked( { From 32dba7af82e43d5382b8271134adef2fd991af31 Mon Sep 17 00:00:00 2001 From: Chi-Hsuan Huang Date: Thu, 26 Nov 2026 12:52:29 +0800 Subject: [PATCH 16/28] Premium Analytics: Treat a devices response without buckets as an unusable response --- .../data/src/processing/stats/__tests__/devices.test.ts | 3 ++- .../packages/data/src/processing/stats/devices.ts | 3 ++- 2 files changed, 4 insertions(+), 2 deletions(-) diff --git a/projects/packages/premium-analytics/packages/data/src/processing/stats/__tests__/devices.test.ts b/projects/packages/premium-analytics/packages/data/src/processing/stats/__tests__/devices.test.ts index fe1a1051c62b..85ac6f478dfb 100644 --- a/projects/packages/premium-analytics/packages/data/src/processing/stats/__tests__/devices.test.ts +++ b/projects/packages/premium-analytics/packages/data/src/processing/stats/__tests__/devices.test.ts @@ -3,6 +3,7 @@ import { sanitizeStatsDevicesPeriodsResponse, sanitizeStatsDevicesResponse, } from '..'; +import { StatsResponseShapeError } from '../../../utils/api-error'; import { devicesEmptyFixture, devicesFixture } from '../__fixtures__/devices'; import type { StatsDevicesItem, StatsNormalizedReport } from '..'; @@ -85,7 +86,7 @@ describe( 'sanitizeStatsDevicesPeriodsResponse', () => { it( 'rejects a response without per-period views', () => { expect( () => sanitizeStatsDevicesPeriodsResponse( { top_values: { desktop: 62.3 } } ) - ).toThrow(); + ).toThrow( StatsResponseShapeError ); } ); it( 'reads an empty days map as a range with no views', () => { diff --git a/projects/packages/premium-analytics/packages/data/src/processing/stats/devices.ts b/projects/packages/premium-analytics/packages/data/src/processing/stats/devices.ts index 30f88113090a..cbb0ed70c056 100644 --- a/projects/packages/premium-analytics/packages/data/src/processing/stats/devices.ts +++ b/projects/packages/premium-analytics/packages/data/src/processing/stats/devices.ts @@ -1,6 +1,7 @@ /** * Internal dependencies */ +import { StatsResponseShapeError } from '../../utils/api-error'; import { safeParseFloat } from '../../utils/parsing'; import { sanitizeStatsTimeSeriesResponse } from './time-series'; import { @@ -112,7 +113,7 @@ export function mergeStatsDevicesComparisonRows( export function sanitizeStatsDevicesPeriodsResponse( response: unknown, query?: StatsQueryParams ) { const payload = coerceStatsRecord( response ); if ( ! ( 'days' in payload ) ) { - throw new Error( 'stats/devices returned no per-period views.' ); + throw new StatsResponseShapeError( 'stats/devices returned no per-period views.' ); } // Each bucket's `other_views` and `total_views` sit beside its devices, so only `views` becomes fields. From 4c9492047aad953a9d21ddd7126006d26ad72b42 Mon Sep 17 00:00:00 2001 From: Chi-Hsuan Huang Date: Thu, 26 Nov 2026 12:52:32 +0800 Subject: [PATCH 17/28] Premium Analytics: Map the Devices bar chart's errors like the semi-circle's --- .../devices/__tests__/devices.test.tsx | 28 ++++++++++++++++- .../widgets/devices/render.tsx | 31 +++++++------------ .../devices/use-device-views-over-time.ts | 8 +++-- 3 files changed, 44 insertions(+), 23 deletions(-) diff --git a/projects/packages/premium-analytics/widgets/devices/__tests__/devices.test.tsx b/projects/packages/premium-analytics/widgets/devices/__tests__/devices.test.tsx index 82b3179dd62a..570e761324fa 100644 --- a/projects/packages/premium-analytics/widgets/devices/__tests__/devices.test.tsx +++ b/projects/packages/premium-analytics/widgets/devices/__tests__/devices.test.tsx @@ -6,6 +6,7 @@ import { useStatsDevicesPeriods, useStatsSite, } from '@jetpack-premium-analytics/data'; +import { screen } from '@testing-library/react'; /** * Internal dependencies */ @@ -53,7 +54,11 @@ function devicesResult( rows: unknown[], overrides: Record< string, unknown > = } as unknown as ReturnType< typeof useStatsDevices >; } -function devicesPeriodsResult( primary: Record< string, unknown >, comparison = {} ) { +function devicesPeriodsResult( + primary: Record< string, unknown >, + comparison = {}, + overrides: Record< string, unknown > = {} +) { return { primary: { data: primary, isError: false, isPlaceholderData: false }, comparison: { data: comparison }, @@ -63,7 +68,9 @@ function devicesPeriodsResult( primary: Record< string, unknown >, comparison = isLoading: false, isFetching: false, isError: false, + error: null, refetch: jest.fn(), + ...overrides, } as unknown as ReturnType< typeof useStatsDevicesPeriods >; } @@ -192,4 +199,23 @@ describe( 'DevicesWidget bar chart CSV download', () => { expect( declaredAction( 'download-csv' ) ).toBeUndefined(); } ); + + it.each( [ + [ + 'offers no Retry for a permission-gated 403', + { status: 403, code: 'rest_forbidden' }, + false, + ], + [ 'offers Retry for a failure that can heal', { status: 403, code: 'no_connection' }, true ], + ] )( '%s', ( _case, error, retry ) => { + jest + .mocked( useStatsDevicesPeriods ) + .mockReturnValue( + devicesPeriodsResult( { summary: { ...RANGE }, data: [] }, {}, { isError: true, error } ) + ); + + renderWidget( { chartType: 'bar' } ); + + expect( Boolean( screen.queryByRole( 'button', { name: 'Retry' } ) ) ).toBe( retry ); + } ); } ); diff --git a/projects/packages/premium-analytics/widgets/devices/render.tsx b/projects/packages/premium-analytics/widgets/devices/render.tsx index be56a07cce01..717398efd059 100644 --- a/projects/packages/premium-analytics/widgets/devices/render.tsx +++ b/projects/packages/premium-analytics/widgets/devices/render.tsx @@ -50,6 +50,12 @@ const PERCENTAGE_DATA_FORMAT = { const NO_VIEWS = () => __( 'You don’t have devices recorded yet.', 'jetpack-premium-analytics-pkg' ); +const RETRY_DESCRIPTION = () => + __( + "We couldn't load device data. Please try again in a moment.", + 'jetpack-premium-analytics-pkg' + ); + const DEVICE_COLUMNS: CsvColumn< DeviceView >[] = [ { label: __( 'Screen size', 'jetpack-premium-analytics-pkg' ), @@ -118,13 +124,7 @@ function DevicesInner() { hasComparison, refetch, } } - error={ describeError( error, { - retryDescription: __( - "We couldn't load device data. Please try again in a moment.", - 'jetpack-premium-analytics-pkg' - ), - onRetry: refetch, - } ) } + error={ describeError( error, { retryDescription: RETRY_DESCRIPTION(), onRetry: refetch } ) } empty={ emptyState.empty } format={ PERCENTAGE_DATA_FORMAT } variant="half-ring" @@ -134,7 +134,7 @@ function DevicesInner() { } /** - * Views by screen size in each bucket of the range, stacked, with the previous period's total beside each stack. + * Views by screen size in each bucket of the range, stacked; the legend can add the previous period's total beside each stack. * * @param props - Component props. * @param props.interval - The saved bucket size, if any. @@ -152,6 +152,7 @@ function DevicesBarChart( { interval }: { interval?: DevicesChartGranularity } ) isLoading, isFetching, isError, + error, csvIsError, csvIsPlaceholderData, timezone, @@ -210,19 +211,9 @@ function DevicesBarChart( { interval }: { interval?: DevicesChartGranularity } ) isLoading={ emptyState.isLoading } isFetching={ isFetching } isError={ isError } - error={ { - description: __( - "We couldn't load device data. Please try again in a moment.", - 'jetpack-premium-analytics-pkg' - ), - actions: [ { label: __( 'Retry', 'jetpack-premium-analytics-pkg' ), onClick: refetch } ], - } } + error={ describeError( error, { retryDescription: RETRY_DESCRIPTION(), onRetry: refetch } ) } isEmpty={ isEmpty } - empty={ - emptyState.empty ?? { - description: __( 'No device views in this period.', 'jetpack-premium-analytics-pkg' ), - } - } + empty={ emptyState.empty } renderLoading={ } > Date: Thu, 26 Nov 2026 12:55:20 +0800 Subject: [PATCH 18/28] Premium Analytics: Cover the Devices bar chart's guards and drop a duplicate render test --- ...arative-bar-chart-previous-period.test.tsx | 55 ++++++++++++------ .../__tests__/use-comparative-legend.test.ts | 9 +++ .../widgets/devices/__tests__/render.test.tsx | 57 ------------------- .../use-device-views-over-time.test.tsx | 40 +++++++++++-- .../widgets/devices/__tests__/widget.test.tsx | 34 +++++++++++ 5 files changed, 115 insertions(+), 80 deletions(-) delete mode 100644 projects/packages/premium-analytics/widgets/devices/__tests__/render.test.tsx create mode 100644 projects/packages/premium-analytics/widgets/devices/__tests__/widget.test.tsx diff --git a/projects/packages/premium-analytics/packages/widgets-toolkit/src/components/chart-comparative-bar/__tests__/comparative-bar-chart-previous-period.test.tsx b/projects/packages/premium-analytics/packages/widgets-toolkit/src/components/chart-comparative-bar/__tests__/comparative-bar-chart-previous-period.test.tsx index 6bed2bfe4ee0..925a5299018d 100644 --- a/projects/packages/premium-analytics/packages/widgets-toolkit/src/components/chart-comparative-bar/__tests__/comparative-bar-chart-previous-period.test.tsx +++ b/projects/packages/premium-analytics/packages/widgets-toolkit/src/components/chart-comparative-bar/__tests__/comparative-bar-chart-previous-period.test.tsx @@ -245,31 +245,52 @@ describe( 'ComparativeBarChart previous-period toggle', () => { ] ); } ); - it( "totals a stack's rows in its tooltip, without the chart's own previous-total entry", () => { - renderChart( { layout: 'stacked', previousPeriodShown: true } ); - - const entry = ( key: string, value: number ) => ( { datum: { date: JULY_1, value }, key } ); + it.each( [ + [ + 'beside the previous period, without the chart’s own previous-total entry', + SERIES, + [ 'Views', 'Visitors', COMPARISON_TOTAL_KEY ], + [ + [ 'Views', 100, 80 ], + [ 'Visitors', 40, 30 ], + [ 'Total', 140, 110 ], + ], + ], + [ + 'with no comparison', + CURRENT_SERIES, + [ 'Views', 'Visitors' ], + [ + [ 'Views', 100, undefined ], + [ 'Visitors', 40, undefined ], + [ 'Total', 140, undefined ], + ], + ], + [ 'only for more than one reading', SERIES, [ 'Views' ], [ [ 'Views', 100, 80 ] ] ], + ] )( "totals a stack's rows in its tooltip %s", ( _case, chartSeries, keys, rows ) => { + renderChart( { layout: 'stacked', series: chartSeries, previousPeriodShown: true } ); + + const values: Record< string, number > = { + Views: 100, + Visitors: 40, + [ COMPARISON_TOTAL_KEY ]: 110, + }; + const datumByKey = Object.fromEntries( + keys.map( ( key, index ) => [ + key, + { datum: { date: JULY_1, value: values[ key ] }, key, index }, + ] ) + ); /* eslint-disable testing-library/render-result-naming-convention -- `renderTooltip` is the chart's prop, not testing-library's `render()`. */ const tooltip = lastBarChart().renderTooltip( { - tooltipData: { - nearestDatum: entry( 'Views', 100 ), - datumByKey: { - Views: { ...entry( 'Views', 100 ), index: 0 }, - Visitors: { ...entry( 'Visitors', 40 ), index: 1 }, - [ COMPARISON_TOTAL_KEY ]: { ...entry( COMPARISON_TOTAL_KEY, 110 ), index: 2 }, - }, - }, + tooltipData: { nearestDatum: datumByKey.Views, datumByKey }, } ); /* eslint-enable testing-library/render-result-naming-convention */ expect( tooltip?.props.model.rows.map( row => [ row.name, row.value, row.previous?.value ] ) - ).toEqual( [ - [ 'Views', 100, 80 ], - [ 'Visitors', 40, 30 ], - [ 'Total', 140, 110 ], - ] ); + ).toEqual( rows ); } ); it( 'keeps the current-period bar colors when the previous period is toggled', () => { diff --git a/projects/packages/premium-analytics/packages/widgets-toolkit/src/hooks/__tests__/use-comparative-legend.test.ts b/projects/packages/premium-analytics/packages/widgets-toolkit/src/hooks/__tests__/use-comparative-legend.test.ts index 3fbfc6c45f11..e1bf85983b9d 100644 --- a/projects/packages/premium-analytics/packages/widgets-toolkit/src/hooks/__tests__/use-comparative-legend.test.ts +++ b/projects/packages/premium-analytics/packages/widgets-toolkit/src/hooks/__tests__/use-comparative-legend.test.ts @@ -29,4 +29,13 @@ describe( 'useComparativeLegend', () => { 'line' ); } ); + + // The charts warn when a stacked bar chart is handed per-metric comparison items it cannot draw. + it( 'names no per-metric comparison item for a stacked bar chart', () => { + const { result } = renderHook( () => + useComparativeLegend( SERIES, true, undefined, undefined, 'stacked' ) + ); + + expect( result.current.config ).not.toHaveProperty( 'comparisonSeriesItems' ); + } ); } ); diff --git a/projects/packages/premium-analytics/widgets/devices/__tests__/render.test.tsx b/projects/packages/premium-analytics/widgets/devices/__tests__/render.test.tsx deleted file mode 100644 index 53a25cb10e60..000000000000 --- a/projects/packages/premium-analytics/widgets/devices/__tests__/render.test.tsx +++ /dev/null @@ -1,57 +0,0 @@ -/** - * External dependencies - */ -import { render } from '@testing-library/react'; -/** - * Internal dependencies - */ -import DevicesRender from '../render'; -import useDeviceViews from '../use-device-views'; -import useDeviceViewsOverTime from '../use-device-views-over-time'; -import type { ReportParams } from '@jetpack-premium-analytics/data'; - -jest.mock( '@wordpress/route', () => jest.requireActual( '../../test-utils' ).mockWordPressRoute ); -jest.mock( '../use-device-views' ); -jest.mock( '../use-device-views-over-time' ); -jest.mock( '@jetpack-premium-analytics/widgets-toolkit', () => ( { - ...jest.requireActual( '@jetpack-premium-analytics/widgets-toolkit' ), - Donut: () => null, - ComparativeBarChart: () => null, -} ) ); - -const mockUseDeviceViews = jest.mocked( useDeviceViews ); -const mockUseDeviceViewsOverTime = jest.mocked( useDeviceViewsOverTime ); -const reportParams = { from: '2026-06-01', to: '2026-06-30' } as ReportParams; -const state = { isLoading: false, isFetching: false, isError: false, refetch: jest.fn() }; - -beforeEach( () => { - jest.clearAllMocks(); - mockUseDeviceViews.mockReturnValue( { - ...state, - data: [ { label: 'desktop', displayLabel: 'Desktop', percentage: 100 } ], - hasComparison: false, - error: null, - csvIsError: false, - csvIsPlaceholderData: false, - } ); - mockUseDeviceViewsOverTime.mockReturnValue( { - ...state, - devices: [ { key: 'desktop', label: 'Desktop', value: 10, current: [] } ], - csvIsError: false, - csvIsPlaceholderData: false, - timezone: 'UTC', - } ); -} ); - -describe( 'DevicesWidget', () => { - // Saved dashboards have no chart type, and must keep the semi-circle and its request. - it.each( [ - [ 'the semi-circle without a chart type', {}, true ], - [ 'the bars for the bar chart type', { chartType: 'bar' as const }, false ], - ] )( 'draws %s', ( _case, attributes, semiCircle ) => { - render( ); - - expect( mockUseDeviceViews.mock.calls.length > 0 ).toBe( semiCircle ); - expect( mockUseDeviceViewsOverTime.mock.calls.length > 0 ).toBe( ! semiCircle ); - } ); -} ); diff --git a/projects/packages/premium-analytics/widgets/devices/__tests__/use-device-views-over-time.test.tsx b/projects/packages/premium-analytics/widgets/devices/__tests__/use-device-views-over-time.test.tsx index 5f655a621c40..db665260379c 100644 --- a/projects/packages/premium-analytics/widgets/devices/__tests__/use-device-views-over-time.test.tsx +++ b/projects/packages/premium-analytics/widgets/devices/__tests__/use-device-views-over-time.test.tsx @@ -18,24 +18,29 @@ const mockUseStatsDevicesPeriods = jest.mocked( useStatsDevicesPeriods ); const PARAMS = { from: '2026-06-01', to: '2026-06-07' } as ReportParams; const ROW = { date_start: '2026-06-01T00:00:00', date_end: '2026-06-01T23:59:59' }; +const ERROR = { status: 500 }; + function mockReport( { primary, comparison, + hasComparison = !! comparison, isError = false, }: { primary?: Record< string, unknown >; comparison?: Record< string, unknown >; + hasComparison?: boolean; isError?: boolean; } ) { mockUseStatsDevicesPeriods.mockReturnValue( { primary: { data: primary }, comparison: { data: comparison }, - hasComparison: !! comparison, + hasComparison, timezone: 'UTC', periodStarts: undefined, isLoading: false, isFetching: false, isError, + error: isError ? ERROR : null, refetch: jest.fn(), } as unknown as ReturnType< typeof useStatsDevicesPeriods > ); } @@ -44,7 +49,10 @@ describe( 'useDeviceViewsOverTime', () => { // A device the current period never saw still adds its previous views to the previous total. it( 'stacks desktop, mobile and tablet first, then the rest by views, from either period', () => { mockReport( { - primary: { summary: { tablet: 5, other: 9, mobile: 20, desktop: 40, ...ROW }, data: [] }, + primary: { + summary: { tablet: 5, tv: 1, other: 9, mobile: 20, desktop: 40, ...ROW }, + data: [], + }, comparison: { summary: { phone: 3, desktop: 30, ...ROW }, data: [] }, } ); @@ -56,17 +64,37 @@ describe( 'useDeviceViewsOverTime', () => { 'tablet', 'other', 'phone', + 'tv', ] ); } ); + it( 'stacks no device from the previous period while comparison is off', () => { + mockReport( { + primary: { summary: { desktop: 40, ...ROW }, data: [] }, + comparison: { summary: { phone: 3, ...ROW }, data: [] }, + hasComparison: false, + } ); + + const { result } = renderHook( () => useDeviceViewsOverTime( PARAMS, 'day' ) ); + + expect( result.current.devices.map( device => device.key ) ).toEqual( [ 'desktop' ] ); + } ); + it.each( [ - [ 'keeps the bars when a refetch of drawn data fails', [ { ...ROW, desktop: 1 } ], false ], - [ 'reports an error when there is nothing drawn', [], true ], - ] )( '%s', ( _case, data, isError ) => { - mockReport( { primary: { summary: { desktop: 1, ...ROW }, data }, isError: true } ); + [ + 'keeps the bars when a refetch of drawn data fails', + [ { ...ROW, desktop: 1 } ], + true, + false, + ], + [ 'reports an error when there is nothing drawn', [], true, true ], + [ 'reports no error for an empty range that loaded', [], false, false ], + ] )( '%s', ( _case, data, reportIsError, isError ) => { + mockReport( { primary: { summary: { desktop: 1, ...ROW }, data }, isError: reportIsError } ); const { result } = renderHook( () => useDeviceViewsOverTime( PARAMS, 'day' ) ); expect( result.current.isError ).toBe( isError ); + expect( result.current.error ).toBe( isError ? ERROR : null ); } ); } ); diff --git a/projects/packages/premium-analytics/widgets/devices/__tests__/widget.test.tsx b/projects/packages/premium-analytics/widgets/devices/__tests__/widget.test.tsx new file mode 100644 index 000000000000..0e20540e27fa --- /dev/null +++ b/projects/packages/premium-analytics/widgets/devices/__tests__/widget.test.tsx @@ -0,0 +1,34 @@ +/** + * External dependencies + */ +import { render, screen } from '@testing-library/react'; +/** + * Internal dependencies + */ +import { setMockRouteSearch } from '../../../tests/js/route-test-utils'; +import widget, { type DevicesAttributes } from '../widget'; +import type { ComponentType } from 'react'; + +jest.mock( '@wordpress/route', () => jest.requireActual( '../../test-utils' ).mockWordPressRoute ); + +describe( 'Devices interval menu', () => { + afterEach( () => setMockRouteSearch( {} ) ); + + it.each( [ + [ 'hides', { chartType: 'half-ring' as const }, false ], + [ 'hides', {}, false ], + [ 'shows', { chartType: 'bar' as const }, true ], + ] )( '%s the menu for %j', ( _verb, data: DevicesAttributes, shown ) => { + setMockRouteSearch( { preset: 'last-30-days' } ); + const field = widget.attributes.find( attribute => attribute.id === 'chartInterval' ); + const Menu = field?.Edit as unknown as ComponentType< { + data: DevicesAttributes; + field: typeof field; + onChange: () => void; + } >; + + render( ); + + expect( Boolean( screen.queryByRole( 'button', { name: /^By / } ) ) ).toBe( shown ); + } ); +} ); From 148f9a22dbc8a616dafd5f16825226183eb8873b Mon Sep 17 00:00:00 2001 From: Chi-Hsuan Huang Date: Thu, 26 Nov 2026 12:56:11 +0800 Subject: [PATCH 19/28] Premium Analytics: Require a devices bucket the endpoint accepts --- .../packages/data/src/hooks/use-stats-devices.ts | 5 +++-- .../premium-analytics/packages/data/src/index.ts | 1 + .../data/src/queries/stats-devices-query.ts | 12 ++++++++++++ .../premium-analytics/widgets/devices/render.tsx | 13 ++++++++++--- .../premium-analytics/widgets/devices/widget.ts | 15 +++------------ 5 files changed, 29 insertions(+), 17 deletions(-) diff --git a/projects/packages/premium-analytics/packages/data/src/hooks/use-stats-devices.ts b/projects/packages/premium-analytics/packages/data/src/hooks/use-stats-devices.ts index 57bd7f58d1b3..0abde15895cf 100644 --- a/projects/packages/premium-analytics/packages/data/src/hooks/use-stats-devices.ts +++ b/projects/packages/premium-analytics/packages/data/src/hooks/use-stats-devices.ts @@ -7,6 +7,7 @@ import { statsDevicesQuery, type StatsDeviceProperty, type StatsDevicesParams as StatsDevicesQueryParams, + type StatsDevicesPeriod, } from '../queries/stats-devices-query'; import { createStatsListReportHook, @@ -56,12 +57,12 @@ export function useStatsDevices( params: StatsDevicesParams, options?: StatsDevi * @return The primary and comparison reports. */ export function useStatsDevicesPeriods( - params: ReportParams & Pick< StatsDevicesQueryParams, 'deviceProperty' | 'period' >, + params: ReportParams & { period: StatsDevicesPeriod; deviceProperty?: StatsDeviceProperty }, options?: UseStatsOptions ) { return useStatsReport< StatsDevicesQueryParams, StatsTimeSeriesReport >( statsDevicesPeriodsQuery, - params as StatsDevicesQueryParams, + params, [ 'stats', 'devices-periods', '__comparison__', 'disabled' ], options ); diff --git a/projects/packages/premium-analytics/packages/data/src/index.ts b/projects/packages/premium-analytics/packages/data/src/index.ts index b878cd022703..9dca95ebaaae 100644 --- a/projects/packages/premium-analytics/packages/data/src/index.ts +++ b/projects/packages/premium-analytics/packages/data/src/index.ts @@ -18,6 +18,7 @@ export { } from './providers/period-change-signal'; export * from './hooks'; export { STATS_SITE_SUMMARY_FIELDS } from './queries/stats-site-query'; +export { STATS_DEVICES_PERIODS, type StatsDevicesPeriod } from './queries/stats-devices-query'; export { ensureDashboardEntities } from './entities/dashboard-entities'; export { latestPostQuery, postContentQuery, postsContentQuery } from './queries/latest-post-query'; export type { LatestPost, LatestPostResponse } from './processing/latest-post'; diff --git a/projects/packages/premium-analytics/packages/data/src/queries/stats-devices-query.ts b/projects/packages/premium-analytics/packages/data/src/queries/stats-devices-query.ts index ba597a43b33d..698922c7bdd0 100644 --- a/projects/packages/premium-analytics/packages/data/src/queries/stats-devices-query.ts +++ b/projects/packages/premium-analytics/packages/data/src/queries/stats-devices-query.ts @@ -9,9 +9,21 @@ import { type StatsReportQueryOptions, } from './stats-query'; import type { StatsProxyParams } from '../api'; +import type { StatsPeriod } from '../utils/stats-params'; export type StatsDeviceProperty = 'screensize' | 'browser' | 'platform' | 'client_type'; +/** The buckets the endpoint's `unit` mode accepts; it has no hourly data. */ +export const STATS_DEVICES_PERIODS = [ + 'day', + 'week', + 'month', + 'quarter', + 'year', +] as const satisfies readonly StatsPeriod[]; + +export type StatsDevicesPeriod = ( typeof STATS_DEVICES_PERIODS )[ number ]; + export type StatsDevicesParams = StatsReportParams & { deviceProperty?: StatsDeviceProperty }; export const statsDevicesQuery = ( params: StatsDevicesParams ) => { diff --git a/projects/packages/premium-analytics/widgets/devices/render.tsx b/projects/packages/premium-analytics/widgets/devices/render.tsx index 717398efd059..b9b0241906e3 100644 --- a/projects/packages/premium-analytics/widgets/devices/render.tsx +++ b/projects/packages/premium-analytics/widgets/devices/render.tsx @@ -2,7 +2,11 @@ * WordPress dependencies */ import { __ } from '@wordpress/i18n'; -import { chartInterval, useScopeLockedIntervals } from '@jetpack-premium-analytics/data'; +import { + STATS_DEVICES_PERIODS, + chartInterval, + useScopeLockedIntervals, +} from '@jetpack-premium-analytics/data'; import { BarChartSkeleton, ComparativeBarChart, @@ -30,7 +34,6 @@ import { useNoViewsEmptyState } from '../use-no-views-empty-state'; import { usePreviousPeriodShown } from '../use-previous-period-shown'; import useDeviceViews, { type DeviceView } from './use-device-views'; import useDeviceViewsOverTime from './use-device-views-over-time'; -import { DEVICES_PERIODS } from './widget'; import type { DevicesAttributes, DevicesChartGranularity } from './widget'; /** * Types @@ -146,7 +149,11 @@ function DevicesBarChart( { interval }: { interval?: DevicesChartGranularity } ) const [ previousPeriodShown, setPreviousPeriodShown ] = usePreviousPeriodShown( 'devicesChartPreviousPeriod' ); - const period = chartInterval( { ...reportParams, interval }, DEVICES_PERIODS, lockedIntervals ); + const period = chartInterval( + { ...reportParams, interval }, + STATS_DEVICES_PERIODS, + lockedIntervals + ); const { devices, isLoading, diff --git a/projects/packages/premium-analytics/widgets/devices/widget.ts b/projects/packages/premium-analytics/widgets/devices/widget.ts index fb6cc4cd67fa..445517105f26 100644 --- a/projects/packages/premium-analytics/widgets/devices/widget.ts +++ b/projects/packages/premium-analytics/widgets/devices/widget.ts @@ -7,19 +7,10 @@ import { type ChartIntervalFieldAttributes, } from '@jetpack-premium-analytics/fields'; import { createElement, type ComponentType } from 'react'; -import type { StatsPeriod } from '@jetpack-premium-analytics/data'; +import { STATS_DEVICES_PERIODS, type StatsDevicesPeriod } from '@jetpack-premium-analytics/data'; import type { WidgetAttributeField } from '@wordpress/widget-primitives'; -/** The bucket sizes the bar chart draws; the devices endpoint has no hourly data. */ -export const DEVICES_PERIODS = [ - 'day', - 'week', - 'month', - 'quarter', - 'year', -] as const satisfies readonly StatsPeriod[]; - -export type DevicesChartGranularity = ( typeof DEVICES_PERIODS )[ number ]; +export type DevicesChartGranularity = StatsDevicesPeriod; /** The share of each device over the range, or its views in each bucket of the range. */ export type DevicesChartType = 'half-ring' | 'bar'; @@ -40,7 +31,7 @@ export default { attributes: [ { ...intervalField, - elements: chartIntervalElements( DEVICES_PERIODS ), + elements: chartIntervalElements( STATS_DEVICES_PERIODS ), // The semi-circle reads the whole range, so only the bars have a bucket to pick. Edit: ( props: IntervalEditProps ) => props.data.chartType === 'bar' ? createElement( IntervalEdit, props ) : null, From a2d14ccbe7c19ac14f22fd44a93bdb66bd6208b0 Mon Sep 17 00:00:00 2001 From: Chi-Hsuan Huang Date: Thu, 26 Nov 2026 12:56:35 +0800 Subject: [PATCH 20/28] Premium Analytics: Note the stacked tooltip Total row in the changelog --- .../packages/premium-analytics/changelog/pa-devices-stacked | 2 +- projects/plugins/jetpack/changelog/pa-devices-stacked | 2 +- projects/plugins/premium-analytics/changelog/pa-devices-stacked | 2 +- projects/plugins/stats/changelog/pa-devices-stacked | 2 +- 4 files changed, 4 insertions(+), 4 deletions(-) diff --git a/projects/packages/premium-analytics/changelog/pa-devices-stacked b/projects/packages/premium-analytics/changelog/pa-devices-stacked index 203bba8d5ab7..3a82c24990f3 100644 --- a/projects/packages/premium-analytics/changelog/pa-devices-stacked +++ b/projects/packages/premium-analytics/changelog/pa-devices-stacked @@ -1,4 +1,4 @@ Significance: minor Type: added -Devices: Add a bar chart of views by device over time, with the previous period's total beside each bar. +Devices: Add a bar chart of views by device over time, with the previous period's total beside each bar. Stacked bar tooltips, such as Requests by source, now end with a Total row. diff --git a/projects/plugins/jetpack/changelog/pa-devices-stacked b/projects/plugins/jetpack/changelog/pa-devices-stacked index 48c8dccfcfc4..6017498e8919 100644 --- a/projects/plugins/jetpack/changelog/pa-devices-stacked +++ b/projects/plugins/jetpack/changelog/pa-devices-stacked @@ -1,4 +1,4 @@ Significance: minor Type: enhancement -Premium Analytics: Add a bar chart of views by device over time to the Devices widget, with the previous period's total beside each bar. +Premium Analytics: Add a bar chart of views by device over time to the Devices widget, with the previous period's total beside each bar. Stacked bar tooltips, such as Requests by source, now end with a Total row. diff --git a/projects/plugins/premium-analytics/changelog/pa-devices-stacked b/projects/plugins/premium-analytics/changelog/pa-devices-stacked index 203bba8d5ab7..3a82c24990f3 100644 --- a/projects/plugins/premium-analytics/changelog/pa-devices-stacked +++ b/projects/plugins/premium-analytics/changelog/pa-devices-stacked @@ -1,4 +1,4 @@ Significance: minor Type: added -Devices: Add a bar chart of views by device over time, with the previous period's total beside each bar. +Devices: Add a bar chart of views by device over time, with the previous period's total beside each bar. Stacked bar tooltips, such as Requests by source, now end with a Total row. diff --git a/projects/plugins/stats/changelog/pa-devices-stacked b/projects/plugins/stats/changelog/pa-devices-stacked index f74c03f46635..645e78a30412 100644 --- a/projects/plugins/stats/changelog/pa-devices-stacked +++ b/projects/plugins/stats/changelog/pa-devices-stacked @@ -1,4 +1,4 @@ Significance: minor Type: added -Premium Analytics: Add a bar chart of views by device over time to the Devices widget, with the previous period's total beside each bar. +Premium Analytics: Add a bar chart of views by device over time to the Devices widget, with the previous period's total beside each bar. Stacked bar tooltips, such as Requests by source, now end with a Total row. From f6b38d3e93d94703832ae24d41b1b6e92a568978 Mon Sep 17 00:00:00 2001 From: Chi-Hsuan Huang Date: Thu, 26 Nov 2026 14:21:36 +0800 Subject: [PATCH 21/28] Charts: Hide a bounded tooltip until it is placed for its current content --- .../charts/changelog/pa-devices-stacked | 4 ++ .../tooltip/private/bounded-tooltip.tsx | 22 ++++++++--- .../tooltip/test/bounded-tooltip.test.tsx | 37 +++++++++++++++++++ 3 files changed, 57 insertions(+), 6 deletions(-) create mode 100644 projects/js-packages/charts/changelog/pa-devices-stacked diff --git a/projects/js-packages/charts/changelog/pa-devices-stacked b/projects/js-packages/charts/changelog/pa-devices-stacked new file mode 100644 index 000000000000..e80f7348488d --- /dev/null +++ b/projects/js-packages/charts/changelog/pa-devices-stacked @@ -0,0 +1,4 @@ +Significance: patch +Type: fixed + +Tooltips: Stop a tooltip near the edge of a scrolling card from flashing scrollbars that resize the chart as it appears or changes. diff --git a/projects/js-packages/charts/src/components/tooltip/private/bounded-tooltip.tsx b/projects/js-packages/charts/src/components/tooltip/private/bounded-tooltip.tsx index d4f16d31a0e2..7536d3983ded 100644 --- a/projects/js-packages/charts/src/components/tooltip/private/bounded-tooltip.tsx +++ b/projects/js-packages/charts/src/components/tooltip/private/bounded-tooltip.tsx @@ -170,7 +170,17 @@ export const BoundedTooltip = ( { }: BoundedTooltipProps ) => { const nodeRef = useRef< HTMLDivElement >( null ); const clipRef = useRef< { wrapper: Element; clip: Element | null } | null >( null ); - const [ position, setPosition ] = useState< { x: number; y: number } | null >( null ); + const [ position, setPosition ] = useState< { + x: number; + y: number; + inputs: unknown[]; + } | null >( null ); + const inputs = [ left, top, offsetLeft, offsetTop, children, placement ]; + // A position fits only the content and anchor it was measured for; left in place, newer content can overflow a scrolling card. + const placed = + position && position.inputs.every( ( input, index ) => Object.is( input, inputs[ index ] ) ) + ? position + : null; useLayoutEffect( () => { const node = nodeRef.current; @@ -204,14 +214,13 @@ export const BoundedTooltip = ( { bottom: clipRect.bottom - wrapperRect.top, }, } ); - setPosition( current => - current && current.x === next.x && current.y === next.y ? current : next - ); + setPosition( { ...next, inputs: [ left, top, offsetLeft, offsetTop, children, placement ] } ); // `children` re-runs the measurement when the content, and so the box size, changes. }, [ left, top, offsetLeft, offsetTop, children, placement ] ); - const x = position?.x ?? left + offsetLeft; - const y = position?.y ?? top + ( placement === 'below-axis' ? POINTER_HEIGHT : offsetTop ); + // Unplaced, the box waits hidden at the origin, which is also where the effect above measures it. + const x = placed?.x ?? 0; + const y = placed?.y ?? 0; return ( { } ); + // A box left where older content fit can overflow a scrolling card and flash a scrollbar under the chart. + test( 'keeps the box hidden at the wrapper origin until it is placed for its current content', () => { + const seen: string[] = []; + // Lays out before the box is placed, as another part's layout effect can. + const Probe = ( { label }: { label: string } ) => { + useLayoutEffect( () => { + const box = screen.getByTestId( 'box' ); + seen.push( `${ box.style.transform } ${ box.style.visibility }` ); + } ); + return <>{ label }; + }; + jest.spyOn( Element.prototype, 'getBoundingClientRect' ).mockImplementation( function ( + this: Element + ) { + return this.classList.contains( 'visx-tooltip' ) + ? rect( 0, 0, 208, 36 ) + : rect( 0, 0, 400, 200 ); + } ); + const tooltip = ( label: string ) => ( +
+
+ + + +
+
+ ); + + const { rerender } = render( tooltip( 'November 10' ) ); + rerender( tooltip( 'November 18' ) ); + + expect( seen ).toEqual( [ 'translate(0px) hidden', 'translate(0px) hidden' ] ); + expect( screen.getByTestId( 'box' ) ).toHaveStyle( { transform: 'translate(110px, 60px)' } ); + expect( screen.getByTestId( 'box' ) ).not.toHaveStyle( { visibility: 'hidden' } ); + } ); + test( 'falls back to the viewport when nothing clips', () => { jest.spyOn( Element.prototype, 'getBoundingClientRect' ).mockImplementation( function ( this: Element From 4232d18650889961dbd615f31d3e48edda0b3f85 Mon Sep 17 00:00:00 2001 From: Chi-Hsuan Huang Date: Thu, 26 Nov 2026 15:05:09 +0800 Subject: [PATCH 22/28] Charts: Type a bounded tooltip's placement inputs as one tuple --- .../tooltip/private/bounded-tooltip.tsx | 5 +- .../tooltip/test/bounded-tooltip.test.tsx | 74 +++++++++++-------- 2 files changed, 46 insertions(+), 33 deletions(-) diff --git a/projects/js-packages/charts/src/components/tooltip/private/bounded-tooltip.tsx b/projects/js-packages/charts/src/components/tooltip/private/bounded-tooltip.tsx index 7536d3983ded..a8c776a8d9ac 100644 --- a/projects/js-packages/charts/src/components/tooltip/private/bounded-tooltip.tsx +++ b/projects/js-packages/charts/src/components/tooltip/private/bounded-tooltip.tsx @@ -5,6 +5,7 @@ import type { TooltipBoxProps } from '../tooltip-box'; import type { ReactNode } from 'react'; type Bounds = { left: number; top: number; right: number; bottom: number }; +type PlacementInputs = readonly [ number, number, number, number, ReactNode, TooltipPlacement ]; type Size = { width: number; height: number }; export type BoundedTooltipProps = Omit< TooltipBoxProps, 'children' > & { @@ -173,9 +174,9 @@ export const BoundedTooltip = ( { const [ position, setPosition ] = useState< { x: number; y: number; - inputs: unknown[]; + inputs: PlacementInputs; } | null >( null ); - const inputs = [ left, top, offsetLeft, offsetTop, children, placement ]; + const inputs: PlacementInputs = [ left, top, offsetLeft, offsetTop, children, placement ]; // A position fits only the content and anchor it was measured for; left in place, newer content can overflow a scrolling card. const placed = position && position.inputs.every( ( input, index ) => Object.is( input, inputs[ index ] ) ) diff --git a/projects/js-packages/charts/src/components/tooltip/test/bounded-tooltip.test.tsx b/projects/js-packages/charts/src/components/tooltip/test/bounded-tooltip.test.tsx index ea49f07f90c2..8765f37d5a25 100644 --- a/projects/js-packages/charts/src/components/tooltip/test/bounded-tooltip.test.tsx +++ b/projects/js-packages/charts/src/components/tooltip/test/bounded-tooltip.test.tsx @@ -1,6 +1,7 @@ import { render, screen } from '@testing-library/react'; import { useLayoutEffect } from 'react'; import { BoundedTooltip, getBoundedPosition } from '../private/bounded-tooltip'; +import type { BoundedTooltipProps } from '../private/bounded-tooltip'; const BOX = { width: 208, height: 36 }; const OFFSETS = { offsetLeft: 10, offsetTop: 10 }; @@ -300,41 +301,52 @@ describe( 'BoundedTooltip', () => { } ); - // A box left where older content fit can overflow a scrolling card and flash a scrollbar under the chart. - test( 'keeps the box hidden at the wrapper origin until it is placed for its current content', () => { - const seen: string[] = []; - // Lays out before the box is placed, as another part's layout effect can. - const Probe = ( { label }: { label: string } ) => { - useLayoutEffect( () => { - const box = screen.getByTestId( 'box' ); - seen.push( `${ box.style.transform } ${ box.style.visibility }` ); + // A box left where older inputs fit can overflow a scrolling card and flash a scrollbar under the chart. + test.each( [ + [ 'content', { children: 'November 18' }, 'translate(110px, 60px)' ], + [ 'left', { left: 140 }, 'translate(150px, 60px)' ], + [ 'top', { top: 70 }, 'translate(110px, 80px)' ], + [ 'offsetLeft', { offsetLeft: 20 }, 'translate(120px, 60px)' ], + [ 'offsetTop', { offsetTop: 20 }, 'translate(110px, 70px)' ], + [ 'placement', { placement: 'beside' as const }, 'translate(110px, 50px)' ], + ] )( + 'keeps the box hidden at the wrapper origin until it is placed for its current %s', + ( _input, change, placedAt ) => { + const seen: string[] = []; + // Lays out before the box is placed, as another part's layout effect can. + const Probe = () => { + useLayoutEffect( () => { + const box = screen.getByTestId( 'box' ); + seen.push( `${ box.style.transform } ${ box.style.visibility }` ); + } ); + return null; + }; + jest.spyOn( Element.prototype, 'getBoundingClientRect' ).mockImplementation( function ( + this: Element + ) { + return this.classList.contains( 'visx-tooltip' ) + ? rect( 0, 0, 208, 36 ) + : rect( 0, 0, 400, 200 ); } ); - return <>{ label }; - }; - jest.spyOn( Element.prototype, 'getBoundingClientRect' ).mockImplementation( function ( - this: Element - ) { - return this.classList.contains( 'visx-tooltip' ) - ? rect( 0, 0, 208, 36 ) - : rect( 0, 0, 400, 200 ); - } ); - const tooltip = ( label: string ) => ( -
-
- - - + const tooltip = ( props: BoundedTooltipProps ) => ( +
+
+ + { props.children ?? 'November 10' } + + +
-
- ); + ); - const { rerender } = render( tooltip( 'November 10' ) ); - rerender( tooltip( 'November 18' ) ); + const { rerender } = render( tooltip( {} ) ); + rerender( tooltip( change ) ); - expect( seen ).toEqual( [ 'translate(0px) hidden', 'translate(0px) hidden' ] ); - expect( screen.getByTestId( 'box' ) ).toHaveStyle( { transform: 'translate(110px, 60px)' } ); - expect( screen.getByTestId( 'box' ) ).not.toHaveStyle( { visibility: 'hidden' } ); - } ); + expect( seen ).toEqual( [ 'translate(0px) hidden', 'translate(0px) hidden' ] ); + expect( screen.getByTestId( 'box' ) ).toHaveStyle( { transform: placedAt } ); + expect( screen.getByTestId( 'box' ) ).not.toHaveStyle( { visibility: 'hidden' } ); + } + ); test( 'falls back to the viewport when nothing clips', () => { jest.spyOn( Element.prototype, 'getBoundingClientRect' ).mockImplementation( function ( From 326bb7aa13716f95829f19b9f21fb9a6782881dd Mon Sep 17 00:00:00 2001 From: Chi-Hsuan Huang Date: Thu, 26 Nov 2026 15:06:14 +0800 Subject: [PATCH 23/28] Premium Analytics: Narrow the devices periods query and drop dead guards --- .../data/src/hooks/use-stats-devices.ts | 7 +++-- .../stats/__tests__/time-series.test.ts | 27 ------------------- .../queries/__tests__/stats-queries.test.ts | 1 + .../data/src/queries/stats-devices-query.ts | 4 ++- .../packages/icons/README.md | 5 ++-- .../comparative-bar-chart.tsx | 9 +++---- .../devices/__tests__/devices.test.tsx | 2 +- .../devices/use-device-views-over-time.ts | 8 +++--- .../widgets/devices/widget.ts | 2 +- 9 files changed, 19 insertions(+), 46 deletions(-) diff --git a/projects/packages/premium-analytics/packages/data/src/hooks/use-stats-devices.ts b/projects/packages/premium-analytics/packages/data/src/hooks/use-stats-devices.ts index 0abde15895cf..569c4d80d59a 100644 --- a/projects/packages/premium-analytics/packages/data/src/hooks/use-stats-devices.ts +++ b/projects/packages/premium-analytics/packages/data/src/hooks/use-stats-devices.ts @@ -6,8 +6,7 @@ import { statsDevicesPeriodsQuery, statsDevicesQuery, type StatsDeviceProperty, - type StatsDevicesParams as StatsDevicesQueryParams, - type StatsDevicesPeriod, + type StatsDevicesPeriodsParams, } from '../queries/stats-devices-query'; import { createStatsListReportHook, @@ -57,10 +56,10 @@ export function useStatsDevices( params: StatsDevicesParams, options?: StatsDevi * @return The primary and comparison reports. */ export function useStatsDevicesPeriods( - params: ReportParams & { period: StatsDevicesPeriod; deviceProperty?: StatsDeviceProperty }, + params: ReportParams & Pick< StatsDevicesPeriodsParams, 'period' | 'deviceProperty' >, options?: UseStatsOptions ) { - return useStatsReport< StatsDevicesQueryParams, StatsTimeSeriesReport >( + return useStatsReport< StatsDevicesPeriodsParams, StatsTimeSeriesReport >( statsDevicesPeriodsQuery, params, [ 'stats', 'devices-periods', '__comparison__', 'disabled' ], diff --git a/projects/packages/premium-analytics/packages/data/src/processing/stats/__tests__/time-series.test.ts b/projects/packages/premium-analytics/packages/data/src/processing/stats/__tests__/time-series.test.ts index 9bfcd7fac03c..e1625f463078 100644 --- a/projects/packages/premium-analytics/packages/data/src/processing/stats/__tests__/time-series.test.ts +++ b/projects/packages/premium-analytics/packages/data/src/processing/stats/__tests__/time-series.test.ts @@ -227,33 +227,6 @@ describe( 'Stats time-series normalizer', () => { ] ); } ); - // The `stats/devices` `unit` mode: one record of counts per period, keyed by its first day. - it( 'reads a field per key of a days map, clipping the first week to the range', () => { - const result = sanitizeStatsTimeSeriesResponse( - { - date: '2026-06-16', - unit: 'week', - days: { - '2026-06-08': { desktop: 40, mobile: 12 }, - '2026-06-15': { desktop: 20, mobile: 6, tablet: 1 }, - }, - utc_offset: 0, - }, - { start_date: '2026-06-10', date: '2026-06-16' } - ); - - expect( result.summary ).toEqual( - expect.objectContaining( { desktop: 60, mobile: 18, tablet: 1 } ) - ); - expect( result.summary ).not.toHaveProperty( 'utc_offset' ); - expect( - result.data.map( ( { date_start, desktop, mobile } ) => [ date_start, desktop, mobile ] ) - ).toEqual( [ - [ '2026-06-10T00:00:00', 40, 12 ], - [ '2026-06-15T00:00:00', 20, 6 ], - ] ); - } ); - it( 'normalizes email opens timelines nested under the timeline key', () => { const result = sanitizeStatsEmailTimeSeriesResponse( emailOpensTimeSeriesFixture, { period: 'day', diff --git a/projects/packages/premium-analytics/packages/data/src/queries/__tests__/stats-queries.test.ts b/projects/packages/premium-analytics/packages/data/src/queries/__tests__/stats-queries.test.ts index 8a47b9981a70..470937cf9388 100644 --- a/projects/packages/premium-analytics/packages/data/src/queries/__tests__/stats-queries.test.ts +++ b/projects/packages/premium-analytics/packages/data/src/queries/__tests__/stats-queries.test.ts @@ -814,6 +814,7 @@ describe( 'Stats query factories', () => { from: '2026-01-01', to: '2026-06-07', interval: 'week', + period: 'week', } ); expect( query.queryKey ).toEqual( [ diff --git a/projects/packages/premium-analytics/packages/data/src/queries/stats-devices-query.ts b/projects/packages/premium-analytics/packages/data/src/queries/stats-devices-query.ts index 698922c7bdd0..f33b8bacd7a1 100644 --- a/projects/packages/premium-analytics/packages/data/src/queries/stats-devices-query.ts +++ b/projects/packages/premium-analytics/packages/data/src/queries/stats-devices-query.ts @@ -26,6 +26,8 @@ export type StatsDevicesPeriod = ( typeof STATS_DEVICES_PERIODS )[ number ]; export type StatsDevicesParams = StatsReportParams & { deviceProperty?: StatsDeviceProperty }; +export type StatsDevicesPeriodsParams = StatsDevicesParams & { period: StatsDevicesPeriod }; + export const statsDevicesQuery = ( params: StatsDevicesParams ) => { const deviceProperty = params.deviceProperty ?? 'screensize'; @@ -44,7 +46,7 @@ export const statsDevicesQuery = ( params: StatsDevicesParams ) => { * @return The query options. */ export const statsDevicesPeriodsQuery = ( - params: StatsDevicesParams + params: StatsDevicesPeriodsParams ): StatsReportQueryOptions< 'devicesPeriods' > => { const deviceProperty = params.deviceProperty ?? 'screensize'; const apiParams = statsQueryParamsToApiParams( reportParamsToStatsQueryParams( params ) ); diff --git a/projects/packages/premium-analytics/packages/icons/README.md b/projects/packages/premium-analytics/packages/icons/README.md index ea9a49f05486..f0925a466a0d 100644 --- a/projects/packages/premium-analytics/packages/icons/README.md +++ b/projects/packages/premium-analytics/packages/icons/README.md @@ -45,8 +45,9 @@ lookupWidgetIcon( 'core/calendar' ); // null ## Exports -Icons: `calendar`, `channel`, `chartHalfRing`, `chartLine`, `coupon`, `customer`, `device`, `goal`, `jetpack`, -`location`, `megaphone`, `payment`, `paymentReturn`, `productBlouse`, `reports`, `search`, `tag`. +Icons: `calendar`, `channel`, `chartHalfRing`, `chartLine`, `coupon`, `customer`, `device`, `goal`, +`jetpack`, `location`, `megaphone`, `payment`, `paymentReturn`, `productBlouse`, `reports`, `search`, +`tag`. Lookup: `lookupWidgetIcon`, `resolveWidgetIcon`. diff --git a/projects/packages/premium-analytics/packages/widgets-toolkit/src/components/chart-comparative-bar/comparative-bar-chart.tsx b/projects/packages/premium-analytics/packages/widgets-toolkit/src/components/chart-comparative-bar/comparative-bar-chart.tsx index 9e0b3aea48c4..7d4e9476bb4c 100644 --- a/projects/packages/premium-analytics/packages/widgets-toolkit/src/components/chart-comparative-bar/comparative-bar-chart.tsx +++ b/projects/packages/premium-analytics/packages/widgets-toolkit/src/components/chart-comparative-bar/comparative-bar-chart.tsx @@ -151,15 +151,14 @@ export type ComparativeBarChartProps = { */ function withStackTotal( model: DatedTooltipModel, dataFormat: DataFormat ): DatedTooltipModel { const series = model.rows.filter( row => row.indicator.kind === 'series' ); - const sum = ( values: ( number | null | undefined )[] ) => { - const readings = values.filter( ( value ): value is number => typeof value === 'number' ); - return readings.length ? readings.reduce( ( total, value ) => total + value, 0 ) : null; - }; - if ( series.filter( row => row.value !== null ).length < 2 ) { return model; } + const sum = ( values: ( number | null | undefined )[] ) => { + const readings = values.filter( ( value ): value is number => typeof value === 'number' ); + return readings.length ? readings.reduce( ( total, value ) => total + value, 0 ) : null; + }; const blank = { kind: 'blank' } as const; const hasPrevious = series.some( row => row.previous ); diff --git a/projects/packages/premium-analytics/widgets/devices/__tests__/devices.test.tsx b/projects/packages/premium-analytics/widgets/devices/__tests__/devices.test.tsx index 570e761324fa..9f2cf9e8e9b6 100644 --- a/projects/packages/premium-analytics/widgets/devices/__tests__/devices.test.tsx +++ b/projects/packages/premium-analytics/widgets/devices/__tests__/devices.test.tsx @@ -144,7 +144,7 @@ describe( 'DevicesWidget CSV download', () => { } ); } ); -describe( 'DevicesWidget bar chart CSV download', () => { +describe( 'DevicesWidget bar chart', () => { let downloads: ReturnType< typeof captureCsvDownloads > | undefined; beforeEach( () => { diff --git a/projects/packages/premium-analytics/widgets/devices/use-device-views-over-time.ts b/projects/packages/premium-analytics/widgets/devices/use-device-views-over-time.ts index e4e45bfc5612..9bfb870c1adc 100644 --- a/projects/packages/premium-analytics/widgets/devices/use-device-views-over-time.ts +++ b/projects/packages/premium-analytics/widgets/devices/use-device-views-over-time.ts @@ -15,8 +15,6 @@ import type { DevicesChartGranularity } from './widget'; /** Stacked bottom up in this order; any other device follows, largest first. */ const DEVICE_ORDER = [ 'desktop', 'mobile', 'tablet' ]; -const RANGE_FIELDS = new Set( [ 'date_start', 'date_end' ] ); - interface DeviceViewsOverTimeState { /** One tab per device, its views in each bucket and, with comparison on, the previous period's. */ devices: MetricTab[]; @@ -40,7 +38,7 @@ function getDeviceKeys( reports: ( StatsTimeSeriesReport | undefined )[] ): stri const totals = new Map< string, number >(); for ( const report of reports ) { for ( const [ key, total ] of Object.entries( report?.summary ?? {} ) ) { - if ( ! RANGE_FIELDS.has( key ) && typeof total === 'number' ) { + if ( typeof total === 'number' ) { totals.set( key, ( totals.get( key ) ?? 0 ) + total ); } } @@ -71,8 +69,8 @@ export default function useDeviceViewsOverTime( [ reportParams, period ] ); const report = useStatsDevicesPeriods( params ); - const primary = report.primary.data as StatsTimeSeriesReport | undefined; - const comparison = report.comparison.data as StatsTimeSeriesReport | undefined; + const primary = report.primary.data; + const comparison = report.comparison.data; const { hasComparison, timezone, periodStarts } = report; const devices = useMemo( diff --git a/projects/packages/premium-analytics/widgets/devices/widget.ts b/projects/packages/premium-analytics/widgets/devices/widget.ts index 445517105f26..b40fb25bdd5d 100644 --- a/projects/packages/premium-analytics/widgets/devices/widget.ts +++ b/projects/packages/premium-analytics/widgets/devices/widget.ts @@ -36,7 +36,7 @@ export default { Edit: ( props: IntervalEditProps ) => props.data.chartType === 'bar' ? createElement( IntervalEdit, props ) : null, }, - ] as WidgetAttributeField< DevicesAttributes >[], + ] satisfies WidgetAttributeField< DevicesAttributes >[], example: { attributes: {}, }, From 824e76430fadfa9732896965b5b83fa7989d0534 Mon Sep 17 00:00:00 2001 From: Chi-Hsuan Huang Date: Thu, 26 Nov 2026 17:03:08 +0800 Subject: [PATCH 24/28] Charts: Focus a keyboard tooltip once it is placed --- .../use-pie-keyboard-navigation.ts | 5 +++- .../tooltip/test/xy-chart-tooltip.test.tsx | 26 +++++++++++++++++++ .../components/tooltip/xy-chart-tooltip.tsx | 9 +++++-- 3 files changed, 37 insertions(+), 3 deletions(-) diff --git a/projects/js-packages/charts/src/charts/private/pie-keyboard-navigation/use-pie-keyboard-navigation.ts b/projects/js-packages/charts/src/charts/private/pie-keyboard-navigation/use-pie-keyboard-navigation.ts index d456225ae0a0..ed7ed939034d 100644 --- a/projects/js-packages/charts/src/charts/private/pie-keyboard-navigation/use-pie-keyboard-navigation.ts +++ b/projects/js-packages/charts/src/charts/private/pie-keyboard-navigation/use-pie-keyboard-navigation.ts @@ -67,12 +67,15 @@ export const usePieKeyboardNavigation = < Arc extends { data: DataPointPercentag [ focusTooltip ] ); - // Arrow keys mount the next tooltip in the same commit, so focus only reaches the body when the selection's tooltip went away. + // Arrow keys mount the next tooltip in the same commit, and it takes focus once placed, so only a removed selection hands focus back. useLayoutEffect( () => { if ( ! tooltipLostFocus.current ) { return; } tooltipLostFocus.current = false; + if ( keyboardTooltip.current?.isConnected ) { + return; + } const { activeElement, body } = chartRef.current?.ownerDocument ?? document; if ( activeElement === null || activeElement === body ) { chartRef.current?.focus(); diff --git a/projects/js-packages/charts/src/components/tooltip/test/xy-chart-tooltip.test.tsx b/projects/js-packages/charts/src/components/tooltip/test/xy-chart-tooltip.test.tsx index 218af6bd77fb..02028785bb92 100644 --- a/projects/js-packages/charts/src/components/tooltip/test/xy-chart-tooltip.test.tsx +++ b/projects/js-packages/charts/src/components/tooltip/test/xy-chart-tooltip.test.tsx @@ -135,6 +135,32 @@ describe( 'XYChartTooltip', () => { } } ); + // A browser refuses focus to a hidden box, and focusing it unplaced would scroll to the wrong spot. + it.each( [ 'auto', 'below-axis' ] as const )( + 'focuses a %s keyboard tooltip only once its box is placed', + async placement => { + const hiddenOnFocus: boolean[] = []; + const recordVisibility = ( event: FocusEvent ) => { + if ( ( event.target as HTMLElement ).getAttribute( 'role' ) === 'tooltip' ) { + hiddenOnFocus.push( + screen.getByTestId( 'bounded-tooltip' ).style.visibility === 'hidden' + ); + } + }; + document.addEventListener( 'focusin', recordVisibility ); + try { + renderChart( undefined, placement ); + await openTooltip(); + await userEvent.setup().keyboard( '{ArrowRight}' ); + + expect( screen.getByTestId( 'chart-tooltip-1' ) ).toHaveFocus(); + expect( hiddenOnFocus ).toEqual( [ false, false ] ); + } finally { + document.removeEventListener( 'focusin', recordVisibility ); + } + } + ); + it.each( [ [ 'Tab', '{Tab}' ], [ 'Escape', '{Escape}' ], diff --git a/projects/js-packages/charts/src/components/tooltip/xy-chart-tooltip.tsx b/projects/js-packages/charts/src/components/tooltip/xy-chart-tooltip.tsx index 49da61aec99e..68c1a5bb3188 100644 --- a/projects/js-packages/charts/src/components/tooltip/xy-chart-tooltip.tsx +++ b/projects/js-packages/charts/src/components/tooltip/xy-chart-tooltip.tsx @@ -276,11 +276,16 @@ export const useKeyboardNavigation = ( { [ preventTooltipScroll ] ); - // Focus the tooltip as soon as it is rendered + // A new tooltip is hidden, so unfocusable, until BoundedTooltip's layout effect places it. + // React commits that placement before the current commit returns, so a microtask sees the placed box. const tooltipRef = useCallback( ( element: HTMLDivElement | null ) => { if ( element && selectedIndex !== undefined ) { - focusWithoutScrollIfNeeded( element ); + queueMicrotask( () => { + if ( element.isConnected ) { + focusWithoutScrollIfNeeded( element ); + } + } ); } }, [ focusWithoutScrollIfNeeded, selectedIndex ] From 658b8331a0ad738b687a5f1cd27be135d67f4d4b Mon Sep 17 00:00:00 2001 From: Chi-Hsuan Huang Date: Fri, 27 Nov 2026 11:47:05 +0800 Subject: [PATCH 25/28] Charts: Round a tooltip pinned to an edge inward so it never scrolls its card --- .../charts/changelog/pa-devices-stacked | 2 +- .../tooltip/private/bounded-tooltip.tsx | 17 +++++++++-------- .../tooltip/test/bounded-tooltip.test.tsx | 14 ++++++++++++++ 3 files changed, 24 insertions(+), 9 deletions(-) diff --git a/projects/js-packages/charts/changelog/pa-devices-stacked b/projects/js-packages/charts/changelog/pa-devices-stacked index e80f7348488d..599198ccbaee 100644 --- a/projects/js-packages/charts/changelog/pa-devices-stacked +++ b/projects/js-packages/charts/changelog/pa-devices-stacked @@ -1,4 +1,4 @@ Significance: patch Type: fixed -Tooltips: Stop a tooltip near the edge of a scrolling card from flashing scrollbars that resize the chart as it appears or changes. +Tooltips: Stop a tooltip at the edge of a scrolling card from adding scrollbars that resize the chart, as it appears, changes, or sits flush with the edge. diff --git a/projects/js-packages/charts/src/components/tooltip/private/bounded-tooltip.tsx b/projects/js-packages/charts/src/components/tooltip/private/bounded-tooltip.tsx index a8c776a8d9ac..02235bc3ac3f 100644 --- a/projects/js-packages/charts/src/components/tooltip/private/bounded-tooltip.tsx +++ b/projects/js-packages/charts/src/components/tooltip/private/bounded-tooltip.tsx @@ -24,8 +24,12 @@ export const DEFAULT_OFFSET = 10; export const TOOLTIP_Z_INDEX = 3; const POINTER_HEIGHT = 6; +// Whole pixels, rounded inward: rounding out by a fraction is enough to scroll a card the box sits flush in. const clamp = ( position: number, min: number, max: number, size: number ) => - Math.min( Math.max( position, min ), Math.max( min, max - size ) ); + Math.min( + Math.max( Math.round( position ), Math.ceil( min ) ), + Math.max( Math.ceil( min ), Math.floor( max - size ) ) + ); const isClipping = ( element: Element ) => { const { overflow, overflowX, overflowY } = getComputedStyle( element ); @@ -98,7 +102,7 @@ export const getBoundedPosition = ( { } ) => { if ( placement === 'below-axis' ) { return { - x: Math.round( clamp( left - box.width / 2, bounds.left, bounds.right, box.width ) ), + x: clamp( left - box.width / 2, bounds.left, bounds.right, box.width ), y: top + POINTER_HEIGHT, }; } @@ -115,7 +119,7 @@ export const getBoundedPosition = ( { const leftX = left - offsetLeft - box.width; const rightOverflow = rightX + box.width - fit.right; const leftOverflow = fit.left - leftX; - let x = rightOverflow > 0 && rightOverflow > leftOverflow ? leftX : rightX; + const x = rightOverflow > 0 && rightOverflow > leftOverflow ? leftX : rightX; const downY = top + offsetTop; const upY = top - offsetTop - box.height; @@ -126,12 +130,9 @@ export const getBoundedPosition = ( { y = downOverflow > 0 && downOverflow > upOverflow ? upY : downY; } - x = clamp( x, bounds.left, bounds.right, box.width ); - y = clamp( y, bounds.top, bounds.bottom, box.height ); - return { - x: Math.round( x ), - y: Math.round( y ), + x: clamp( x, bounds.left, bounds.right, box.width ), + y: clamp( y, bounds.top, bounds.bottom, box.height ), }; }; diff --git a/projects/js-packages/charts/src/components/tooltip/test/bounded-tooltip.test.tsx b/projects/js-packages/charts/src/components/tooltip/test/bounded-tooltip.test.tsx index 8765f37d5a25..f86ba2cbb780 100644 --- a/projects/js-packages/charts/src/components/tooltip/test/bounded-tooltip.test.tsx +++ b/projects/js-packages/charts/src/components/tooltip/test/bounded-tooltip.test.tsx @@ -65,6 +65,20 @@ describe( 'getBoundedPosition', () => { ).toEqual( { x: 138, y: 60 } ); } ); + test( 'rounds a box pinned to a fractional edge inward, so it never pokes past it', () => { + // Rounded to the nearest pixel, 85.59 would end the box 0.41px past the edge and scroll the card. + expect( + getBoundedPosition( { + left: 100, + top: 50, + ...OFFSETS, + box: { width: 302.59, height: 100 }, + wrapper: { left: 0, top: 0, right: 388.18, bottom: 300 }, + bounds: { left: 0, top: 0, right: 388.18, bottom: 300 }, + } ) + ).toEqual( { x: 85, y: 60 } ); + } ); + test( 'may leave the wrapper as long as it stays inside the clipping ancestor', () => { // Neither side fits the 346px wrapper, and the clipping card ends 14px // past its right edge, so the box keeps the near side and stops there. From dc71ac4bba7af8e6d3dde2039b6830aa43bb9b58 Mon Sep 17 00:00:00 2001 From: Chi-Hsuan Huang Date: Fri, 27 Nov 2026 11:47:15 +0800 Subject: [PATCH 26/28] Premium Analytics: Shorten tooltip dates in narrow cards and let only the dates wrap --- .../changelog/pa-devices-stacked | 2 +- .../comparative-bar-chart.tsx | 5 ++-- .../comparative-line-chart.tsx | 6 ++--- .../chart-stacked-area/stacked-area-chart.tsx | 6 ++--- .../src/components/chart-tooltip/README.md | 7 +++-- .../__tests__/dated-tooltip-model.test.tsx | 23 ++++++++++++++++ .../chart-tooltip/dated-tooltip-model.ts | 26 +++++++++++++++--- .../chart-tooltip/dated-tooltip.module.scss | 22 +++++++++++++++ .../chart-tooltip/dated-tooltip.tsx | 27 ++++++++++++++++--- .../format-bucket-tooltip-date.test.ts | 8 ++++++ .../src/helpers/format-bucket-tooltip-date.ts | 16 ++++++++--- .../widgets-toolkit/src/helpers/index.ts | 2 +- .../jetpack/changelog/pa-devices-stacked | 2 +- .../changelog/pa-devices-stacked | 2 +- .../stats/changelog/pa-devices-stacked | 2 +- 15 files changed, 132 insertions(+), 24 deletions(-) diff --git a/projects/packages/premium-analytics/changelog/pa-devices-stacked b/projects/packages/premium-analytics/changelog/pa-devices-stacked index 3a82c24990f3..d52324a64f62 100644 --- a/projects/packages/premium-analytics/changelog/pa-devices-stacked +++ b/projects/packages/premium-analytics/changelog/pa-devices-stacked @@ -1,4 +1,4 @@ Significance: minor Type: added -Devices: Add a bar chart of views by device over time, with the previous period's total beside each bar. Stacked bar tooltips, such as Requests by source, now end with a Total row. +Devices: Add a bar chart of views by device over time, with the previous period's total beside each bar. Stacked bar tooltips, such as Requests by source, now end with a Total row. Chart tooltips in narrow cards now shorten their dates and stay inside the card instead of adding a scrollbar. diff --git a/projects/packages/premium-analytics/packages/widgets-toolkit/src/components/chart-comparative-bar/comparative-bar-chart.tsx b/projects/packages/premium-analytics/packages/widgets-toolkit/src/components/chart-comparative-bar/comparative-bar-chart.tsx index 7d4e9476bb4c..9003fabab023 100644 --- a/projects/packages/premium-analytics/packages/widgets-toolkit/src/components/chart-comparative-bar/comparative-bar-chart.tsx +++ b/projects/packages/premium-analytics/packages/widgets-toolkit/src/components/chart-comparative-bar/comparative-bar-chart.tsx @@ -29,6 +29,7 @@ import { formatBucketTooltipDate, toTickResolution, type BucketResolution, + type TooltipDateForm, } from '../../helpers'; import { resolvePrimarySeriesByGroup } from '../../helpers/resolve-series-names'; import { useChartName } from '../../hooks/use-chart-name'; @@ -385,8 +386,8 @@ export function ComparativeBarChart( { ] ); const formatTooltipBucket = useCallback( - ( point: ComparativeDatePointDate ) => - formatBucketTooltipDate( point, displayResolution, tickResolution ), + ( point: ComparativeDatePointDate, form?: TooltipDateForm ) => + formatBucketTooltipDate( point, displayResolution, tickResolution, form ), [ displayResolution, tickResolution ] ); diff --git a/projects/packages/premium-analytics/packages/widgets-toolkit/src/components/chart-comparative-line/comparative-line-chart.tsx b/projects/packages/premium-analytics/packages/widgets-toolkit/src/components/chart-comparative-line/comparative-line-chart.tsx index ba06d86f275b..3aa1800d751e 100644 --- a/projects/packages/premium-analytics/packages/widgets-toolkit/src/components/chart-comparative-line/comparative-line-chart.tsx +++ b/projects/packages/premium-analytics/packages/widgets-toolkit/src/components/chart-comparative-line/comparative-line-chart.tsx @@ -36,7 +36,7 @@ import type { TooltipExtraSeries, ComparativeDatePointDate, } from './types'; -import type { BucketResolution, ChartBaseline } from '../../helpers'; +import type { BucketResolution, ChartBaseline, TooltipDateForm } from '../../helpers'; import type { DataFormat } from '../../types'; /** Series styles, with the explicit `styles` prop taking priority over `series[].options`. */ @@ -192,8 +192,8 @@ export function ComparativeLineChart( { ); const formatTooltipBucket = useCallback( - ( point: ComparativeDatePointDate ) => - formatBucketTooltipDate( point, displayResolution, tickResolution ), + ( point: ComparativeDatePointDate, form?: TooltipDateForm ) => + formatBucketTooltipDate( point, displayResolution, tickResolution, form ), [ displayResolution, tickResolution ] ); diff --git a/projects/packages/premium-analytics/packages/widgets-toolkit/src/components/chart-stacked-area/stacked-area-chart.tsx b/projects/packages/premium-analytics/packages/widgets-toolkit/src/components/chart-stacked-area/stacked-area-chart.tsx index a9ce291bfc81..e31fef0d8807 100644 --- a/projects/packages/premium-analytics/packages/widgets-toolkit/src/components/chart-stacked-area/stacked-area-chart.tsx +++ b/projects/packages/premium-analytics/packages/widgets-toolkit/src/components/chart-stacked-area/stacked-area-chart.tsx @@ -19,7 +19,7 @@ import { useChartName } from '../../hooks/use-chart-name'; import { useSeriesStyles } from '../../hooks/use-series-styles'; import { DatedTooltip, buildDatedTooltipModel } from '../chart-tooltip'; import styles from './stacked-area-chart.module.scss'; -import type { BucketResolution } from '../../helpers'; +import type { BucketResolution, TooltipDateForm } from '../../helpers'; import type { DataFormat } from '../../types'; import type { ComparativeDatePointDate, @@ -81,8 +81,8 @@ export function StackedAreaChart( { const seriesStyles = useSeriesStyles( series ); const formatTooltipBucket = useCallback( - ( point: ComparativeDatePointDate ) => - formatBucketTooltipDate( point, displayResolution, tickResolution ), + ( point: ComparativeDatePointDate, form?: TooltipDateForm ) => + formatBucketTooltipDate( point, displayResolution, tickResolution, form ), [ displayResolution, tickResolution ] ); diff --git a/projects/packages/premium-analytics/packages/widgets-toolkit/src/components/chart-tooltip/README.md b/projects/packages/premium-analytics/packages/widgets-toolkit/src/components/chart-tooltip/README.md index c3f1ccb9e7a0..2f84b3b86ec0 100644 --- a/projects/packages/premium-analytics/packages/widgets-toolkit/src/components/chart-tooltip/README.md +++ b/projects/packages/premium-analytics/packages/widgets-toolkit/src/components/chart-tooltip/README.md @@ -122,7 +122,8 @@ const renderTooltip = params => { seriesStyles, extras: tooltipExtras, dataFormat, - formatDate: point => formatBucketTooltipDate( point, displayResolution ), + formatDate: ( point, form ) => + formatBucketTooltipDate( point, displayResolution, undefined, form ), } ); return model && ; @@ -131,12 +132,14 @@ const renderTooltip = params => { ## Model -`buildDatedTooltipModel()` groups the reported rows: a comparison series joins its group's current-period row as `previous` (one with no current series in its group, or no group, joins the first series). A comparison whose metric the chart did not report (a series the legend hid) is dropped with it. Extras are read at the hovered date from their own `data` and `previous` points; an extra with a reading in either period gets a row, and one that names a drawn series keeps that series' row. The header reads a current-period point's axis `date`, so a nearer comparison point cannot swap in its own; the `realDate` of a comparison point on the hovered bucket heads the comparison column, named by `formatDate`, which the charts point at `formatBucketTooltipDate` so a week reads as its span. +`buildDatedTooltipModel()` groups the reported rows: a comparison series joins its group's current-period row as `previous` (one with no current series in its group, or no group, joins the first series). A comparison whose metric the chart did not report (a series the legend hid) is dropped with it. Extras are read at the hovered date from their own `data` and `previous` points; an extra with a reading in either period gets a row, and one that names a drawn series keeps that series' row. The header reads a current-period point's axis `date`, so a nearer comparison point cannot swap in its own; the `realDate` of a comparison point on the hovered bucket heads the comparison column, named by `formatDate`, which the charts point at `formatBucketTooltipDate` so a week reads as its span. `formatDate` is asked for a `compact` form too, kept as `compactDate` and `compactPreviousDate` where it is shorter; a widget narrower than the `md` breakpoint shows those instead. A date that still does not fit wraps, at its dash where it can. | Field | Type | Description | | ---------------- | --------------------------------------- | ---------------------------------------------------------------------------------------- | | `date` | `string` | The hovered bucket's date, formatted | | `previousDate` | `string \| undefined` | The comparison bucket's date, when a comparison point sits on the hovered bucket | +| `compactDate` | `string \| undefined` | `date` with abbreviated months, when that is shorter | +| `compactPreviousDate` | `string \| undefined` | `previousDate` with abbreviated months, when that is shorter | | `rows[].name` | `string` | The metric's name, read as the value's unit | | `rows[].countLabel` | `CountLabel \| undefined` | The metric's plural-aware unit, from the series or extra | | `rows[].dataFormat` | `DataFormat` | The extra's own format, else the chart's | diff --git a/projects/packages/premium-analytics/packages/widgets-toolkit/src/components/chart-tooltip/__tests__/dated-tooltip-model.test.tsx b/projects/packages/premium-analytics/packages/widgets-toolkit/src/components/chart-tooltip/__tests__/dated-tooltip-model.test.tsx index 1b410a9eebe1..04350e767f65 100644 --- a/projects/packages/premium-analytics/packages/widgets-toolkit/src/components/chart-tooltip/__tests__/dated-tooltip-model.test.tsx +++ b/projects/packages/premium-analytics/packages/widgets-toolkit/src/components/chart-tooltip/__tests__/dated-tooltip-model.test.tsx @@ -91,6 +91,29 @@ describe( 'buildDatedTooltipModel', () => { ] ); } ); + it( 'keeps a compact form of each header date only where it is shorter', () => { + const model = buildDatedTooltipModel( { + tooltipData: { + datumByKey: Object.fromEntries( [ + entry( 'Views', { date: JULY_1, value: 100 } ), + entry( 'Views · previous period', COMPARISON_POINT ), + ] ), + }, + series: SERIES, + seriesStyles: STYLES, + dataFormat: DATA_FORMAT, + formatDate: ( point, form ) => + form === 'compact' && ! point.realDate ? 'Jul 1' : formatDate( point ), + } ); + + expect( model ).toMatchObject( { + date: '2026-07-01', + compactDate: 'Jul 1', + previousDate: '2026-06-01', + } ); + expect( model ).not.toHaveProperty( 'compactPreviousDate' ); + } ); + // A shorter comparison period has no point for the last bucket, so visx hands over // the dashed line's nearest point from the bucket before. it( 'reads a comparison point from another bucket as no data, under the current date', () => { diff --git a/projects/packages/premium-analytics/packages/widgets-toolkit/src/components/chart-tooltip/dated-tooltip-model.ts b/projects/packages/premium-analytics/packages/widgets-toolkit/src/components/chart-tooltip/dated-tooltip-model.ts index c818642f5629..c975404add53 100644 --- a/projects/packages/premium-analytics/packages/widgets-toolkit/src/components/chart-tooltip/dated-tooltip-model.ts +++ b/projects/packages/premium-analytics/packages/widgets-toolkit/src/components/chart-tooltip/dated-tooltip-model.ts @@ -4,6 +4,7 @@ import { resolvePrimarySeriesByGroup } from '../../helpers/resolve-series-names'; import { isChartDatumEntry } from './utils'; import type { TooltipStyle } from './chart-tooltip'; +import type { TooltipDateForm } from '../../helpers'; import type { CountLabel, DataFormat } from '../../types'; import type { ComparativeDatePointDate, @@ -42,6 +43,9 @@ export type DatedTooltipModel = { * sits on the hovered bucket, though a row may still carry an empty comparison. */ previousDate?: string; + /** `date` and `previousDate` with abbreviated months, set when that is shorter, for narrow cards. */ + compactDate?: string; + compactPreviousDate?: string; rows: DatedTooltipRow[]; /** Why the bucket has no reading, from the first hovered point that says so. */ note?: string; @@ -60,11 +64,20 @@ export type DatedTooltipModelOptions = { extras?: readonly TooltipExtraSeries[]; dataFormat: DataFormat; /** Names a point's bucket: the hovered current point for the header, a comparison point for its column. */ - formatDate: ( point: ComparativeDatePointDate ) => string; + formatDate: ( point: ComparativeDatePointDate, form?: TooltipDateForm ) => string; }; type Point = Partial< ComparativeDatePointDate >; +function formatBothForms( + formatDate: DatedTooltipModelOptions[ 'formatDate' ], + point: Point +): [ string, string | undefined ] { + const full = formatDate( point as ComparativeDatePointDate ); + const compact = formatDate( point as ComparativeDatePointDate, 'compact' ); + return [ full, compact.length < full.length ? compact : undefined ]; +} + function readingOf( point: Point | undefined ): number | null { return point?.missing ? null : ( point?.value ?? null ); } @@ -180,9 +193,16 @@ export function buildDatedTooltipModel( previousPoint ??= previous; } ); + const [ date, compactDate ] = formatBothForms( formatDate, hoveredPoint ); + const [ previousDate, compactPreviousDate ] = previousPoint + ? formatBothForms( formatDate, previousPoint ) + : []; + return { - date: formatDate( hoveredPoint as ComparativeDatePointDate ), - previousDate: previousPoint && formatDate( previousPoint as ComparativeDatePointDate ), + date, + previousDate, + ...( compactDate !== undefined && { compactDate } ), + ...( compactPreviousDate !== undefined && { compactPreviousDate } ), rows: [ ...rows.values() ], note, }; diff --git a/projects/packages/premium-analytics/packages/widgets-toolkit/src/components/chart-tooltip/dated-tooltip.module.scss b/projects/packages/premium-analytics/packages/widgets-toolkit/src/components/chart-tooltip/dated-tooltip.module.scss index 13227bc886f0..e1588abc9435 100644 --- a/projects/packages/premium-analytics/packages/widgets-toolkit/src/components/chart-tooltip/dated-tooltip.module.scss +++ b/projects/packages/premium-analytics/packages/widgets-toolkit/src/components/chart-tooltip/dated-tooltip.module.scss @@ -1,3 +1,5 @@ +@use "../../styles/widget-container" as *; + // A table, so each metric's current and comparison readings share a row and // the two dates head their columns. .table { @@ -22,6 +24,26 @@ .header { padding-block-end: var(--wpds-dimension-gap-xs); font-weight: var(--wpds-typography-font-weight-emphasis); + // Only the dates wrap, where a narrow chart cannot fit them; balanced, a range + // breaks at its dash. + white-space: normal; + text-wrap: balance; +} + +.compactDate { + display: none; +} + +// Below this, two full spans side by side outgrow the card. +@include widget-query( md, max-width ) { + + .fullDate { + display: none; + } + + .compactDate { + display: inline; + } } .table tr + tr th, diff --git a/projects/packages/premium-analytics/packages/widgets-toolkit/src/components/chart-tooltip/dated-tooltip.tsx b/projects/packages/premium-analytics/packages/widgets-toolkit/src/components/chart-tooltip/dated-tooltip.tsx index c032755b8dc2..ebedc4a58936 100644 --- a/projects/packages/premium-analytics/packages/widgets-toolkit/src/components/chart-tooltip/dated-tooltip.tsx +++ b/projects/packages/premium-analytics/packages/widgets-toolkit/src/components/chart-tooltip/dated-tooltip.tsx @@ -54,6 +54,19 @@ function NoData() { ); } +/** A header date; a narrow card swaps in the compact form, and only the shown one is read out. */ +function DateLabel( { full, compact }: { full?: string; compact?: string } ) { + if ( compact === undefined ) { + return <>{ full }; + } + return ( + <> + { full } + { compact } + + ); +} + function formatValue( row: DatedTooltipRow, value: number ): string { const format = exactFormatOf( row.dataFormat ); return formatMetricValue( value, format.type, format.options ); @@ -112,7 +125,9 @@ export function DatedTooltip( { model, indicatorType }: DatedTooltipProps ) { if ( noteOnly ) { return (
-
{ model.date }
+
+ +
{ model.note }
); @@ -122,8 +137,14 @@ export function DatedTooltip( { model, indicatorType }: DatedTooltipProps ) { - - { hasPrevious && } + + { hasPrevious && ( + + ) } diff --git a/projects/packages/premium-analytics/packages/widgets-toolkit/src/helpers/__tests__/format-bucket-tooltip-date.test.ts b/projects/packages/premium-analytics/packages/widgets-toolkit/src/helpers/__tests__/format-bucket-tooltip-date.test.ts index 6f0726d86883..e52af96718ef 100644 --- a/projects/packages/premium-analytics/packages/widgets-toolkit/src/helpers/__tests__/format-bucket-tooltip-date.test.ts +++ b/projects/packages/premium-analytics/packages/widgets-toolkit/src/helpers/__tests__/format-bucket-tooltip-date.test.ts @@ -62,6 +62,14 @@ describe( 'formatBucketTooltipDate', () => { expect( formatBucketTooltipDate( datum, resolution ) ).toBe( expected ); } ); + it( 'abbreviates the months of a span in its compact form', () => { + const datum = { date: at( '2026-10-29T00:00:00' ), endDate: at( '2026-11-01T23:59:59' ) }; + + expect( formatBucketTooltipDate( datum, 'day', undefined, 'compact' ) ).toBe( + `Oct 29${ SEP }Nov 1, 2026` + ); + } ); + it( 'names the days of a quarter the range cuts to one whole month', () => { const datum = { date: at( '2025-12-01T00:00:00' ), endDate: at( '2025-12-31T23:59:59' ) }; diff --git a/projects/packages/premium-analytics/packages/widgets-toolkit/src/helpers/format-bucket-tooltip-date.ts b/projects/packages/premium-analytics/packages/widgets-toolkit/src/helpers/format-bucket-tooltip-date.ts index 26cbe829968d..3bd54aab670a 100644 --- a/projects/packages/premium-analytics/packages/widgets-toolkit/src/helpers/format-bucket-tooltip-date.ts +++ b/projects/packages/premium-analytics/packages/widgets-toolkit/src/helpers/format-bucket-tooltip-date.ts @@ -2,7 +2,12 @@ * External dependencies */ import { isRepeatedHour, localTZDate } from '@jetpack-premium-analytics/datetime'; -import { formatDate, formatDateRange, isWholePeriod } from '@jetpack-premium-analytics/formatters'; +import { + formatDate, + formatDateRange, + formatDateRangeCompact, + isWholePeriod, +} from '@jetpack-premium-analytics/formatters'; import { __, sprintf } from '@wordpress/i18n'; /** * Internal dependencies @@ -13,6 +18,9 @@ import type { BucketInfo } from '@jetpack-premium-analytics/externals'; type BucketDatum = { date: Date; realDate?: Date; endDate?: Date }; +/** `compact` abbreviates the months of a span, for a tooltip in a narrow card. */ +export type TooltipDateForm = 'full' | 'compact'; + /** * The date a tooltip row names for a point: the days its own bucket covers when a * date-labelled bucket spans several (a week, a quarter) or the range cuts a month or @@ -21,12 +29,14 @@ type BucketDatum = { date: Date; realDate?: Date; endDate?: Date }; * @param datum - The point; a comparison point's own dates are in `realDate`. * @param displayResolution - The resolution the chart labels its buckets at. * @param bucket - The chart's declared bucket size, when it has one. + * @param form - How long a span reads. * @return The formatted date or span. */ export function formatBucketTooltipDate( datum: BucketDatum, displayResolution: BucketInfo[ 'displayResolution' ], - bucket?: BucketResolution + bucket?: BucketResolution, + form: TooltipDateForm = 'full' ): string { const start = datum.realDate ?? datum.date; const { endDate } = datum; @@ -41,7 +51,7 @@ export function formatBucketTooltipDate( ( ( displayResolution === 'month' || displayResolution === 'year' ) && ! isWholePeriod( range, displayResolution ) ) ) { - return formatDateRange( range ); + return form === 'compact' ? formatDateRangeCompact( range ) : formatDateRange( range ); } } diff --git a/projects/packages/premium-analytics/packages/widgets-toolkit/src/helpers/index.ts b/projects/packages/premium-analytics/packages/widgets-toolkit/src/helpers/index.ts index 918b3ca1394c..1d9780eabec7 100644 --- a/projects/packages/premium-analytics/packages/widgets-toolkit/src/helpers/index.ts +++ b/projects/packages/premium-analytics/packages/widgets-toolkit/src/helpers/index.ts @@ -67,5 +67,5 @@ export { monthlyHeatmapLifeStart } from './monthly-heatmap-life-start'; export { bucketRange, monthRange, yearRange, type PeriodBounds } from './period-range'; export { siteChartFormatting } from './site-chart-formatting'; export { formatComparisonSeriesLabel } from './format-comparison-series-label'; -export { formatBucketTooltipDate } from './format-bucket-tooltip-date'; +export { formatBucketTooltipDate, type TooltipDateForm } from './format-bucket-tooltip-date'; export { toTickResolution, type BucketResolution } from './bucket-resolution'; diff --git a/projects/plugins/jetpack/changelog/pa-devices-stacked b/projects/plugins/jetpack/changelog/pa-devices-stacked index 6017498e8919..f1d0495a27fb 100644 --- a/projects/plugins/jetpack/changelog/pa-devices-stacked +++ b/projects/plugins/jetpack/changelog/pa-devices-stacked @@ -1,4 +1,4 @@ Significance: minor Type: enhancement -Premium Analytics: Add a bar chart of views by device over time to the Devices widget, with the previous period's total beside each bar. Stacked bar tooltips, such as Requests by source, now end with a Total row. +Premium Analytics: Add a bar chart of views by device over time to the Devices widget, with the previous period's total beside each bar. Stacked bar tooltips, such as Requests by source, now end with a Total row. Chart tooltips in narrow cards now shorten their dates and stay inside the card instead of adding a scrollbar. diff --git a/projects/plugins/premium-analytics/changelog/pa-devices-stacked b/projects/plugins/premium-analytics/changelog/pa-devices-stacked index 3a82c24990f3..d52324a64f62 100644 --- a/projects/plugins/premium-analytics/changelog/pa-devices-stacked +++ b/projects/plugins/premium-analytics/changelog/pa-devices-stacked @@ -1,4 +1,4 @@ Significance: minor Type: added -Devices: Add a bar chart of views by device over time, with the previous period's total beside each bar. Stacked bar tooltips, such as Requests by source, now end with a Total row. +Devices: Add a bar chart of views by device over time, with the previous period's total beside each bar. Stacked bar tooltips, such as Requests by source, now end with a Total row. Chart tooltips in narrow cards now shorten their dates and stay inside the card instead of adding a scrollbar. diff --git a/projects/plugins/stats/changelog/pa-devices-stacked b/projects/plugins/stats/changelog/pa-devices-stacked index 645e78a30412..5e650888f0aa 100644 --- a/projects/plugins/stats/changelog/pa-devices-stacked +++ b/projects/plugins/stats/changelog/pa-devices-stacked @@ -1,4 +1,4 @@ Significance: minor Type: added -Premium Analytics: Add a bar chart of views by device over time to the Devices widget, with the previous period's total beside each bar. Stacked bar tooltips, such as Requests by source, now end with a Total row. +Premium Analytics: Add a bar chart of views by device over time to the Devices widget, with the previous period's total beside each bar. Stacked bar tooltips, such as Requests by source, now end with a Total row. Chart tooltips in narrow cards now shorten their dates and stay inside the card instead of adding a scrollbar. From e5d751a49480d77800d582d8165d9fcc52de76b5 Mon Sep 17 00:00:00 2001 From: Chi-Hsuan Huang Date: Fri, 27 Nov 2026 11:47:18 +0800 Subject: [PATCH 27/28] Premium Analytics: Split the half-ring chart type icon into two segments --- .../packages/icons/src/chart-half-ring/index.tsx | 6 +++++- 1 file changed, 5 insertions(+), 1 deletion(-) diff --git a/projects/packages/premium-analytics/packages/icons/src/chart-half-ring/index.tsx b/projects/packages/premium-analytics/packages/icons/src/chart-half-ring/index.tsx index 019164330ed9..fc52862e8a06 100644 --- a/projects/packages/premium-analytics/packages/icons/src/chart-half-ring/index.tsx +++ b/projects/packages/premium-analytics/packages/icons/src/chart-half-ring/index.tsx @@ -8,6 +8,10 @@ import { SVG, Path } from '@wordpress/primitives'; */ export const chartHalfRing = ( - + ); From de6105ea064a23d146941b02e56f8bd4f48dfc51 Mon Sep 17 00:00:00 2001 From: Chi-Hsuan Huang Date: Fri, 27 Nov 2026 12:07:13 +0800 Subject: [PATCH 28/28] Premium Analytics: Drop the CSV status field trunk removed from the Devices bar chart --- projects/packages/premium-analytics/widgets/devices/render.tsx | 1 - 1 file changed, 1 deletion(-) diff --git a/projects/packages/premium-analytics/widgets/devices/render.tsx b/projects/packages/premium-analytics/widgets/devices/render.tsx index 0de2afb43989..fbf9d8c39f93 100644 --- a/projects/packages/premium-analytics/widgets/devices/render.tsx +++ b/projects/packages/premium-analytics/widgets/devices/render.tsx @@ -205,7 +205,6 @@ function DevicesBarChart( { interval }: { interval?: DevicesChartGranularity } ) hasDateRange: true, status: { isLoading, - isFetching, isError: csvIsError, isPlaceholderData: csvIsPlaceholderData, },
{ model.date }{ model.previousDate } + + + +