Press n or j to go to the next uncovered block, b, p or k for the previous block.
| 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 | 652x 27x 625x 607x 565x 27x 15x 18x 18x 2382x 6x 6x 6x 2376x 58x 58x 58x 146x 146x 146x 6x 6x 140x 140x 73x 73x 67x 58x 1730x 1730x 1730x 1183x 1730x 1183x 1651x 58x 79x 67x 67x 134x 67x 12x 31x 25x 47x 25x 6x 19x 19x 6x 48x 24x 18x 6x 6x 303x 652x 652x 652x 303x 1890x 1890x 1890x 1514x 28x 1486x 1183x 1183x 1183x 1755x 1755x 1183x 1183x 6x 1177x 1177x 303x | import { formatNumber } from '@automattic/number-formatters';
import { __ } from '@wordpress/i18n';
import { useMemo } from 'react';
import {
useGlobalChartsContext,
type GetElementStylesParams,
type ElementStyles,
} from '../../../providers';
import { formatPercentage } from '../../../utils';
import type {
ComparisonItemLabel,
SeriesData,
DataPointDate,
DataPointPercentageCalculated,
LegendShape,
SeriesChartLegendConfig,
} from '../../../types';
import type { BaseLegendItem } from '../types';
import type { GlyphProps } from '@visx/xychart';
import type { ReactNode } from 'react';
export type LegendValueDisplay = 'percentage' | 'value' | 'valueDisplay' | 'none';
export interface ChartLegendOptions {
withGlyph?: boolean;
glyphSize?: number;
renderGlyph?: < Datum extends object >( props: GlyphProps< Datum > ) => ReactNode;
showValues?: boolean;
legendValueDisplay?: LegendValueDisplay;
legendShape?: LegendShape< SeriesData[], number >;
/**
* Collapse series that share a `group` into a single legend item, labelled by the group's
* primary series. Off by default, so every series gets its own item.
*/
collapseGroups?: boolean;
/**
* Append a static item explaining the comparison overlay whenever a series has
* `options.type === 'comparison'`. Skipped when that series already has its own
* item. Pass a string to replace the default label.
*/
comparisonItem?: SeriesChartLegendConfig[ 'comparisonItem' ];
/** One static item per comparison series instead; see `SeriesChartLegendConfig`. */
comparisonSeriesItems?: SeriesChartLegendConfig[ 'comparisonSeriesItems' ];
/** Color each swatch as `BarChart` fills its bar, with a comparison's tint. Off by default. */
barColors?: boolean;
}
/**
* Formats the value for a data point based on its type and display preference
* @param point - The data point to format
* @param showValues - Whether to show values or return empty string
* @param legendValueDisplay - What type of value to display
* @return Formatted value string
*/
function formatPointValue(
point: DataPointDate | DataPointPercentageCalculated,
showValues: boolean,
legendValueDisplay: LegendValueDisplay = 'percentage'
): string {
if ( ! showValues || legendValueDisplay === 'none' ) {
return '';
}
// Handle DataPointPercentageCalculated (pie chart data with calculated percentage)
if ( 'percentage' in point ) {
switch ( legendValueDisplay ) {
case 'percentage':
return formatPercentage( point.percentage );
case 'value':
return formatNumber( point.value );
case 'valueDisplay':
return point.valueDisplay || formatNumber( point.value );
default:
return '';
}
}
// Handle DataPointDate (time series data)
Eif ( 'value' in point ) {
return point.value !== null ? formatNumber( point.value ) : '';
}
return '';
}
/**
* Applies glyph configuration to a legend item if needed
* @param baseItem - The base legend item
* @param withGlyph - Whether to include glyph rendering
* @param glyph - Glyph component from theme
* @param renderGlyph - Custom glyph render function
* @param glyphSize - Size of the glyph
* @return The legend item with glyph configuration applied if applicable
*/
function applyGlyphToLegendItem(
baseItem: BaseLegendItem,
withGlyph: boolean,
glyph?: < Datum extends object >( props: GlyphProps< Datum > ) => ReactNode,
renderGlyph?: < Datum extends object >( props: GlyphProps< Datum > ) => ReactNode,
glyphSize?: number
): BaseLegendItem {
if ( withGlyph ) {
const glyphToUse = glyph || renderGlyph;
Eif ( glyphToUse ) {
return {
...baseItem,
glyphSize,
renderGlyph: glyphToUse,
};
}
}
return baseItem;
}
type SeriesGroupMember = { series: SeriesData; index: number };
/**
* Buckets series by their `group`, preserving first-appearance order. Series with no group — or a
* group value unique to them — end up in a bucket of their own. Whether a multi-series bucket then
* collapses to a single legend item is decided by the caller: with `collapseGroups` on, every
* multi-member bucket collapses, and the comparison pattern only decides which member represents it.
* @param seriesData - The series data to group
* @return Ordered groups, each holding its member series with their original indices
*/
function groupSeriesForLegend( seriesData: SeriesData[] ): SeriesGroupMember[][] {
const groups: SeriesGroupMember[][] = [];
const groupIndexByKey = new Map< string, number >();
seriesData.forEach( ( series, index ) => {
const member: SeriesGroupMember = { series, index };
const key = series.group;
if ( key === undefined ) {
groups.push( [ member ] );
return;
}
const existing = groupIndexByKey.get( key );
if ( existing === undefined ) {
groupIndexByKey.set( key, groups.length );
groups.push( [ member ] );
} else {
groups[ existing ].push( member );
}
} );
return groups;
}
/**
* Builds a single legend item from a representative series, tagging it with the series it controls
* @param member - The series (with its original index) that provides the label/colour
* @param seriesLabels - Every series label this item toggles (grouped) or just its own
* @param getElementStyles - Function to get element styles
* @param showValues - Whether to show values in legend
* @param withGlyph - Whether to include glyph rendering
* @param glyphSize - Size of the glyph
* @param renderGlyph - Component to render the glyph
* @param legendShape - The shape type for legend items (string literal or React component)
* @return The processed legend item
*/
function buildSeriesLegendItem(
member: SeriesGroupMember,
seriesLabels: string[],
getElementStyles: ( params: GetElementStylesParams ) => ElementStyles,
showValues: boolean,
withGlyph: boolean,
glyphSize: number,
renderGlyph?: < Datum extends object >( props: GlyphProps< Datum > ) => ReactNode,
legendShape?: LegendShape< SeriesData[], number >
): BaseLegendItem {
const { color, glyph, shapeStyles } = getElementStyles( {
data: member.series,
index: member.index,
legendShape,
} );
const baseItem: BaseLegendItem = {
label: member.series.label,
value: showValues ? member.series.data?.length?.toString() || '0' : '',
color,
shapeStyle: shapeStyles,
seriesLabels,
};
return applyGlyphToLegendItem( baseItem, withGlyph, glyph, renderGlyph, glyphSize );
}
/**
* Processes SeriesData into legend items. Every series keeps its own legend entry unless
* `collapseGroups` is set, in which case series sharing a `group` collapse to one item labelled by
* the group's primary (its first non-comparison member).
* @param seriesData - The series data to process
* @param getElementStyles - Function to get element styles
* @param showValues - Whether to show values in legend
* @param withGlyph - Whether to include glyph rendering
* @param glyphSize - Size of the glyph
* @param collapseGroups - Whether series sharing a group collapse to a single item
* @param renderGlyph - Component to render the glyph
* @param legendShape - The shape type for legend items (string literal or React component)
* @return Array of processed legend items
*/
function processSeriesData(
seriesData: SeriesData[],
getElementStyles: ( params: GetElementStylesParams ) => ElementStyles,
showValues: boolean,
withGlyph: boolean,
glyphSize: number,
collapseGroups: boolean,
renderGlyph?: < Datum extends object >( props: GlyphProps< Datum > ) => ReactNode,
legendShape?: LegendShape< SeriesData[], number >
): BaseLegendItem[] {
const buildItem = ( member: SeriesGroupMember, seriesLabels: string[] ) =>
buildSeriesLegendItem(
member,
seriesLabels,
getElementStyles,
showValues,
withGlyph,
glyphSize,
renderGlyph,
legendShape
);
// Without collapsing there is no reason to bucket by group — mapping series directly keeps the
// original order, which matters for charts that already interleave grouped series for colour.
if ( ! collapseGroups ) {
return seriesData.map( ( series, index ) => buildItem( { series, index }, [ series.label ] ) );
}
return groupSeriesForLegend( seriesData ).flatMap( members => {
if ( members.length > 1 ) {
const primary =
members.find( ( { series } ) => series.options?.type !== 'comparison' ) ?? members[ 0 ];
// Primary first so the interactive visibility check reads the series that owns the swatch.
const seriesLabels = [
primary.series.label,
...members.filter( member => member !== primary ).map( ( { series } ) => series.label ),
];
return [ buildItem( primary, seriesLabels ) ];
}
return members.map( member => buildItem( member, [ member.series.label ] ) );
} );
}
/**
* Builds the static item that names the comparison overlay, styled like its first series.
* Skipped when a comparison series already has an item of its own, so nothing is listed twice.
* @param seriesData - The series data to search for a comparison series
* @param items - The legend items already built from the series
* @param label - The item label
* @param getElementStyles - Function to get element styles
* @param legendShape - The shape type for legend items (string literal or React component)
* @return The legend item, or null when it would add nothing
*/
function buildComparisonLegendItem(
seriesData: SeriesData[],
items: BaseLegendItem[],
label: string,
getElementStyles: ( params: GetElementStylesParams ) => ElementStyles,
legendShape?: LegendShape< SeriesData[], number >
): BaseLegendItem | null {
const itemLabels = new Set( items.map( item => item.label ) );
const index = seriesData.findIndex(
series => series.options?.type === 'comparison' && ! itemLabels.has( series.label )
);
if ( index === -1 ) {
return null;
}
const { color, shapeStyles } = getElementStyles( {
data: seriesData[ index ],
index,
legendShape,
} );
return { label, color, shapeStyle: shapeStyles, interactive: false };
}
/**
* Builds one static item per comparison series folded into another series' item, named after
* that item and styled like the comparison series itself.
* @param seriesData - The series data to search for comparison series
* @param items - The legend items already built from the series
* @param formatLabel - Names an item after the label of the item it was folded into
* @param getElementStyles - Function to get element styles
* @param legendShape - The shape type for legend items (string literal or React component)
* @return The legend items, in series order
*/
function buildPerSeriesComparisonItems(
seriesData: SeriesData[],
items: BaseLegendItem[],
formatLabel: ComparisonItemLabel,
getElementStyles: ( params: GetElementStylesParams ) => ElementStyles,
legendShape?: LegendShape< SeriesData[], number >
): BaseLegendItem[] {
return seriesData.flatMap( ( series, index ) => {
const owner = items.find( item => item.seriesLabels?.includes( series.label ) );
if (
series.options?.type !== 'comparison' ||
! owner ||
owner.seriesLabels?.[ 0 ] === series.label
) {
return [];
}
const { color, shapeStyles } = getElementStyles( { data: series, index, legendShape } );
return [
{
label: formatLabel( owner.label ),
color,
shapeStyle: shapeStyles,
interactive: false,
describesSeries: series.label,
},
];
} );
}
/**
* Processes point data into legend items
* @param pointData - The point data to process
* @param getElementStyles - Function to get element styles
* @param showValues - Whether to show values in legend
* @param legendValueDisplay - What type of value to display
* @param withGlyph - Whether to include glyph rendering
* @param glyphSize - Size of the glyph
* @param renderGlyph - Component to render the glyph
* @param legendShape - The shape type for legend items (string literal or React component)
* @return Array of processed legend items
*/
function processPointData(
pointData: ( DataPointDate | DataPointPercentageCalculated )[],
getElementStyles: ( params: GetElementStylesParams ) => ElementStyles,
showValues: boolean,
legendValueDisplay: LegendValueDisplay,
withGlyph: boolean,
glyphSize: number,
renderGlyph?: < Datum extends object >( props: GlyphProps< Datum > ) => ReactNode,
legendShape?: LegendShape< SeriesData[], number >
): BaseLegendItem[] {
const mapper = ( point: DataPointDate | DataPointPercentageCalculated, index: number ) => {
const { color, glyph, shapeStyles } = getElementStyles( {
data: point as DataPointPercentageCalculated,
index,
legendShape,
} );
const baseItem: BaseLegendItem = {
label: point.label,
value: formatPointValue( point, showValues, legendValueDisplay ),
color,
shapeStyle: shapeStyles,
};
return applyGlyphToLegendItem( baseItem, withGlyph, glyph, renderGlyph, glyphSize );
};
return pointData.map( mapper );
}
/**
* Hook to transform chart data into legend items
* @param data - The chart data to transform
* @param options - Configuration options for legend generation
* @param legendShape - The shape type for legend items (string literal or React component)
* @return Array of legend items ready for display
*/
export function useChartLegendItems<
T extends SeriesData[] | DataPointDate[] | DataPointPercentageCalculated[],
>(
data: T,
options: ChartLegendOptions = {},
legendShape?: LegendShape< SeriesData[], number >
): BaseLegendItem[] {
const {
showValues = false,
legendValueDisplay = 'percentage',
withGlyph = false,
glyphSize = 8,
collapseGroups = false,
comparisonItem = false,
comparisonSeriesItems,
barColors: withBarColors = false,
renderGlyph,
} = options;
const { getElementStyles, getBarColors } = useGlobalChartsContext();
return useMemo( () => {
if ( ! data || ! Array.isArray( data ) || data.length === 0 ) {
return [];
}
// Handle SeriesData (multiple series with data points)
if ( 'data' in data[ 0 ] ) {
const seriesData = data as SeriesData[];
const barColors = withBarColors ? getBarColors( seriesData ) : undefined;
const getSwatchStyles = ( params: GetElementStylesParams ): ElementStyles => {
const styles = getElementStyles( params );
return barColors ? { ...styles, color: barColors[ params.index ] } : styles;
};
const items = processSeriesData(
seriesData,
getSwatchStyles,
showValues,
withGlyph,
glyphSize,
collapseGroups,
renderGlyph,
legendShape
);
if ( comparisonSeriesItems ) {
return [
...items,
...buildPerSeriesComparisonItems(
seriesData,
items,
comparisonSeriesItems,
getSwatchStyles,
legendShape
),
];
}
const comparison = comparisonItem
? buildComparisonLegendItem(
seriesData,
items,
typeof comparisonItem === 'string'
? comparisonItem
: __( 'Comparison period', 'jetpack-charts' ),
getSwatchStyles,
legendShape
)
: null;
return comparison ? [ ...items, comparison ] : items;
}
// Handle DataPointDate or DataPointPercentageCalculated (single data points)
return processPointData(
data as ( DataPointDate | DataPointPercentageCalculated )[],
getElementStyles,
showValues,
legendValueDisplay,
withGlyph,
glyphSize,
renderGlyph,
legendShape
);
}, [
data,
getElementStyles,
getBarColors,
showValues,
legendValueDisplay,
withGlyph,
glyphSize,
collapseGroups,
comparisonItem,
comparisonSeriesItems,
withBarColors,
renderGlyph,
legendShape,
] );
}
|