Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
@@ -0,0 +1,4 @@
Significance: patch
Type: changed

Leaderboards: Match the Most viewed and Videos row labels to the other leaderboard widgets.
Original file line number Diff line number Diff line change
Expand Up @@ -142,15 +142,26 @@ const row = {
A `postLink` row carries no media, and never becomes a chart button: a chart row that is a
button cannot nest an anchor.

Inside a widget, use `LeaderboardPostLabel` instead of building the action by hand. It reads the
report window from `WidgetRootContext` and passes it as `search`, so the detail page opens on
Video rows use `videoLink`, which delegates to `VideoTitleLink` so the row reaches the video
detail route instead of the post one. Same constraints: no media, never a chart button.

```tsx
action: { kind: 'videoLink', id: 9, search: { from: '2026-03-01', to: '2026-03-10' } },
```

Inside a widget, use `LeaderboardPostLabel` instead of building a post action by hand. It reads
the report window from `WidgetRootContext` and passes it as `search`, so the detail page opens on
the range the row was read against:

```tsx
<LeaderboardPostLabel id={ row.postId } label={ row.label } link={ row.link } />
```

Pass `section` to open a named tab on the detail page, such as `email-opens`.
Pass `section` to `LeaderboardPostLabel` to open a named tab on the detail page, such as
`email-opens`.

There is no `LeaderboardVideoLabel`, so a widget building a `videoLink` action takes that same
window from `useWidgetNavigationSearch()` and passes it as `search`.

`LeaderboardRowMedia` provides five semantic media variants. The variant owns its size,
fallback, and default alt-text policy:
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,43 @@ import { fireEvent, render, screen } from '@testing-library/react';
*/
import { LeaderboardLabel } from '../leaderboard-label';
import { buildLeaderboardRow, resolveLeaderboardRowAction } from '../leaderboard-row';
import type { AnchorHTMLAttributes, ReactNode } from 'react';

type MockRouteLinkProps = {
to: string;
params?: Record< string, unknown >;
search?: Record< string, unknown >;
children: ReactNode;
} & Omit< AnchorHTMLAttributes< HTMLAnchorElement >, 'href' >;

// `forwardRef`, because the design system link that renders this forwards a ref.
jest.mock( '@wordpress/route', () => {
const { forwardRef } = jest.requireActual( 'react' ) as typeof import('react');

return {
Link: forwardRef< HTMLAnchorElement, MockRouteLinkProps >(
( { to, params, search, children, ...props }, ref ) => {
const path = Object.entries( params ?? {} ).reduce(
( result, [ key, value ] ) => result.replace( `$${ key }`, String( value ) ),
to
);
const query = new URLSearchParams();
Object.entries( search ?? {} ).forEach( ( [ key, value ] ) => {
if ( value !== undefined && value !== null ) {
query.set( key, String( value ) );
}
} );
const queryString = query.toString();

return (
<a ref={ ref } href={ queryString ? `${ path }?${ queryString }` : path } { ...props }>
{ children }
</a>
);
}
),
};
} );

describe( 'LeaderboardLabel', () => {
it( 'renders media and text without adding row actions', () => {
Expand Down Expand Up @@ -94,7 +131,7 @@ describe( 'buildLeaderboardRow', () => {
const row = buildLeaderboardRow( {
label: 'Pricing',
media: { kind: 'none' },
action: { kind: 'postLink', href: 'https://example.com/pricing/' },
action: { kind: 'postLink', href: 'https://example.com/pricing/', search: {} },
} );

render( row.label );
Expand All @@ -106,6 +143,27 @@ describe( 'buildLeaderboardRow', () => {
expect( row ).not.toHaveProperty( 'onClick' );
} );

it( 'routes a video link to the video detail page with the report window', () => {
const row = buildLeaderboardRow( {
label: 'Launch teaser',
media: { kind: 'none' },
action: {
kind: 'videoLink',
id: 9,
href: 'https://example.com/launch-teaser/',
search: { date_start: '2026-08-01', date_end: '2026-08-26' },
},
} );

render( row.label );

expect( screen.getByRole( 'link', { name: /Launch teaser/ } ) ).toHaveAttribute(
'href',
'/video/9?date_start=2026-08-01&date_end=2026-08-26'
);
expect( row ).not.toHaveProperty( 'onClick' );
} );

it( 'returns chart button props for a drill-down without nesting an action', () => {
const onClick = jest.fn();
const row = buildLeaderboardRow( {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -52,6 +52,8 @@
--jpa-leaderboard-image-fit: cover;
}

/* The chart insets its own `.label` in overlay mode, but an element label
* bypasses that rule — and the overlay bar takes its height from this row. */
.row,
.rowLink {
display: flex;
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,7 @@ import { Link } from '@jetpack-premium-analytics/externals';
* Internal dependencies
*/
import { PostTitleLink } from '../post-title-link';
import { VideoTitleLink } from '../video-title-link';
import { LeaderboardLabel, type LeaderboardRowMedia } from './leaderboard-label';
import styles from './leaderboard-label.module.scss';
import type { MouseEvent, ReactElement } from 'react';
Expand All @@ -19,8 +20,24 @@ export type LeaderboardRowAction =
id?: number | string;
/** Public URL. It becomes the link itself when there is no post ID. */
href?: string | null;
/** Search parameters for the detail route, such as the report window. */
search?: Record< string, unknown >;
/**
* Required, so a row cannot silently open the detail page on its own
* default range. Pass `{}` to navigate without a window on purpose.
*/
search: Record< string, unknown >;
}
| {
/** A video with a detail page inside the dashboard. */
kind: 'videoLink';
/** Video ID. Rows carrying one link to the internal detail route. */
id?: number | string;
/** Public URL. It becomes the link itself when there is no video ID. */
href?: string | null;
/**
* Required, so a row cannot silently open the detail page on its own
* default range. Pass `{}` to navigate without a window on purpose.
*/
search: Record< string, unknown >;
}
| {
kind: 'drillDown';
Expand Down Expand Up @@ -85,19 +102,19 @@ export function resolveLeaderboardRowAction(
/**
* Render the shared leaderboard row chrome around a label.
*
* Link actions own the anchor and its new-tab affordance. Post links delegate
* to `PostTitleLink`, which picks the internal detail route, the public URL, or
* plain text for the row. Drill-down actions stay non-interactive here because
* `LeaderboardChart` turns the whole row into a button; `buildLeaderboardRow`
* passes that action to the chart.
* Drill-down actions stay non-interactive here because `LeaderboardChart` turns
* the whole row into a button; `buildLeaderboardRow` passes that action to the
* chart.
*
* @return A single label element accepted by `LeaderboardEntry.label`.
*/
export function LeaderboardRow( { label, media, action }: LeaderboardRowProps ): ReactElement {
// Post rows carry no media, so the row chrome goes on the anchor itself.
if ( action.kind === 'postLink' ) {
// Title-link rows carry no media, so the row chrome goes on the title element.
if ( action.kind === 'postLink' || action.kind === 'videoLink' ) {
const TitleLink = action.kind === 'postLink' ? PostTitleLink : VideoTitleLink;

return (
<PostTitleLink
<TitleLink
id={ action.id }
label={ label }
link={ action.href }
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,6 @@ import '../../packages/widgets-toolkit/src/components/calendar-heatmap/__tests__
import '../../packages/widgets-toolkit/src/components/chart-bar/__tests__/bar-chart-skeleton.test';
import '../../packages/widgets-toolkit/src/components/chart-comparative-line/utils/align-series-dates.test';
import '../../packages/widgets-toolkit/src/components/chart-donut/__tests__/donut-chart-skeleton.test';
import '../../packages/widgets-toolkit/src/components/chart-leaderboard/__tests__/leaderboard-row.test';
import '../../packages/widgets-toolkit/src/components/chart-leaderboard/__tests__/leaderboard-skeleton.test';
import '../../packages/widgets-toolkit/src/components/download-csv/__tests__/to-download-report-params.test';
import '../../packages/widgets-toolkit/src/components/metric-tabs-chart/__tests__/metric-tabs-chart-skeleton.test';
Expand Down
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
// See README.md before adding a suite to this group.

import '../../packages/widgets-toolkit/src/components/chart-leaderboard/__tests__/leaderboard-row.test';
import '../../packages/widgets-toolkit/src/components/post-highlight-card/__tests__/post-highlight-card.test';
import '../../packages/widgets-toolkit/src/components/post-title-link/__tests__/post-title-link.test';
Original file line number Diff line number Diff line change
Expand Up @@ -88,6 +88,7 @@ describe( 'TopPostsWidget', () => {
const titleLink = await screen.findByRole( 'link', { name: /^Hello World Post$/ } );
expect( titleLink ).toHaveAttribute( 'href', expect.stringContaining( '/post/1' ) );
expect( titleLink ).not.toHaveAttribute( 'target' );
expect( titleLink ).toHaveAttribute( 'title', 'Hello World Post' );

// A row with a detail page carries no link out to the live post: the
// external-link icon marks destinations outside the app, and the detail
Expand Down Expand Up @@ -529,6 +530,7 @@ describe( 'TopPostsWidget', () => {
expect( screen.getByText( 'About Page' ) ).toBeInTheDocument();
// The homepage entry has no URL — it must not render as a link.
expect( screen.queryByRole( 'link', { name: /Homepage/ } ) ).not.toBeInTheDocument();
expect( screen.getByTitle( 'Homepage (Latest posts)' ) ).toBeInTheDocument();
} );

it( 'gates archive comparison UI on overlapping archive types', async () => {
Expand Down
85 changes: 36 additions & 49 deletions projects/packages/premium-analytics/widgets/top-posts/render.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -8,31 +8,31 @@ import {
type StatsTopPostsComparisonItem,
} from '@jetpack-premium-analytics/data';
import { reports } from '@jetpack-premium-analytics/icons';
import { pickReportDateParams } from '@jetpack-premium-analytics/routing';
import {
LeaderboardChart,
LeaderboardSkeleton,
PostTitleLink,
ReportLink,
RowsCsvDownloadButton,
WIDGET_ROW_LIMIT,
WidgetBackLink,
WidgetFooter,
WidgetRoot,
WidgetState,
buildLeaderboardRow,
calculateDelta,
getCombinedPeriodMax,
safeHttpUrl,
sharePercentage,
useReportCsvExport,
useWidgetDrillDown,
useWidgetNavigationSearch,
useWidgetRootContext,
type CsvColumn,
type LeaderboardChartData,
type LeaderboardRowAction,
type ReportParamsFieldAttributes,
} from '@jetpack-premium-analytics/widgets-toolkit';
import { __, sprintf } from '@wordpress/i18n';
import { Text } from '@jetpack-premium-analytics/externals';
import { useCallback, useEffect, useMemo } from 'react';
/**
* Internal dependencies
Expand Down Expand Up @@ -87,19 +87,35 @@ type TopPostsWidgetProps = WidgetRenderProps< TopPostsRenderAttributes >;

const DATA_FORMAT = { type: 'number' as const, options: { useMultipliers: true, decimals: 0 } };

/** Pick the one action a top-posts row exposes. */
function resolveRowAction(
row: TopPostRow,
detailSearch: Record< string, unknown >,
onDrillDown?: ( row: TopPostRow ) => void
): LeaderboardRowAction {
if ( ! row.children?.length ) {
return { kind: 'postLink', id: row.postId, href: row.href, search: detailSearch };
}

if ( ! onDrillDown ) {
return { kind: 'static' };
}

return {
kind: 'drillDown',
onClick: () => onDrillDown( row ),
ariaLabel: sprintf(
/* translators: %s is an archive category label, e.g. "Searches". */
__( 'View %s archive pages', 'jetpack-premium-analytics-pkg' ),
row.label
),
};
}

/**
* Maps normalized top-posts rows onto the shape `LeaderboardChart` expects.
* Current shares are computed relative to the most-viewed row so the overlay
* bars are proportional. When `withComparison` is set, previous-period shares
* and per-row deltas are derived from each row's `previousValue`; otherwise
* the comparison fields are zeroed.
*
* Titles route through `PostTitleLink`: post/page rows navigate to the
* internal detail page through the router, and rows without a post ID (the
* Archives view) fall back to the public URL and take the external-link icon.
* Rows with children instead become drill-down rows (per the widget
* drill-down convention they carry no anchors). The label fills its row so
* the leaderboard overlay bar gets its height from it.
* Shares use the largest value across both periods as one denominator, so
* equal-width bars represent equal values.
*/
function buildLeaderboardData(
rows: TopPostRow[],
Expand All @@ -114,34 +130,14 @@ function buildLeaderboardData(

return rows.map( ( row, index ) => {
const previousValue = row.previousValue;
const hasChildren = !! row.children?.length;

return {
id: `${ index }-${ row.href ?? row.label }`,
label: (
<span className={ styles.labelRow }>
{ /* Rows inside a drill-down button cannot carry anchors. */ }
{ hasChildren ? (
<Text className={ styles.labelTitle } title={ row.label }>
<span className={ styles.labelText }>{ row.label }</span>
</Text>
) : (
<PostTitleLink
id={ row.postId }
label={ row.label }
link={ row.href }
search={ detailSearch }
title={ row.label }
classNames={ {
internal: styles.labelTitleLink,
external: styles.labelExternalLink,
plain: styles.labelTitle,
text: styles.labelText,
} }
/>
) }
</span>
),
...buildLeaderboardRow( {
label: row.label,
media: { kind: 'none' },
action: resolveRowAction( row, detailSearch, onDrillDown ),
} ),
currentValue: row.value,
currentShare: sharePercentage( row.value, maxViews ),
// Rows without a comparison-period match keep `undefined` so the chart
Expand All @@ -155,15 +151,6 @@ function buildLeaderboardData(
withComparison && previousValue !== undefined
? calculateDelta( row.value, previousValue )
: undefined,
...( hasChildren &&
onDrillDown && {
onClick: () => onDrillDown( row ),
ariaLabel: sprintf(
/* translators: %s is an archive category label, e.g. "Searches". */
__( 'View %s archive pages', 'jetpack-premium-analytics-pkg' ),
row.label
),
} ),
};
} );
}
Expand Down Expand Up @@ -264,7 +251,7 @@ function TopPostsReport() {
useStatsTopPosts( statsParams, { maxRows: WIDGET_ROW_LIMIT } );

const rows = useMemo( () => toTopPostRows( comparisonRows?.rows ?? [] ), [ comparisonRows ] );
const detailSearch = useMemo( () => pickReportDateParams( reportParams ), [ reportParams ] );
const detailSearch = useWidgetNavigationSearch();
const withComparison = hasComparison;

// Serialize whatever the leaderboard has loaded, mirroring the Jetpack Stats
Expand Down
Loading
Loading