From bc27eccc6d802800b5cbe648131f954d318d35e8 Mon Sep 17 00:00:00 2001 From: Nikhil Date: Thu, 30 Jul 2026 12:44:38 +0530 Subject: [PATCH 1/5] Premium Analytics: link widget titles to detail pages --- .../changelog/fix-widget-post-detail-links | 4 + .../chart-leaderboard/leaderboard-row.tsx | 4 + .../widgets-toolkit/src/components/index.ts | 5 + .../__tests__/leaderboard-post-label.test.tsx | 89 ++++++++++++++ .../leaderboard-post-label/index.ts | 5 + .../leaderboard-post-label.module.scss | 44 +++++++ .../leaderboard-post-label.tsx | 109 ++++++++++++++++++ .../post-title-link.module.scss | 21 ++++ .../post-title-link/post-title-link.tsx | 14 ++- .../packages/widgets-toolkit/src/index.ts | 3 + .../__tests__/build-top-authors-data.test.ts | 5 + .../widgets/authors/build-top-authors-data.ts | 2 + .../widgets/authors/render.tsx | 30 ++--- .../widgets/emails/__tests__/emails.test.tsx | 52 +++++++++ .../widgets/emails/render.tsx | 21 +++- .../emails/stories/emails-widget.stories.tsx | 39 +++++-- .../widgets/emails/style.module.css | 13 --- .../__tests__/latest-post-card.test.tsx | 30 +++-- .../widgets/latest-post/package.json | 1 + .../widgets/latest-post/render.tsx | 48 ++++---- .../stories/latest-post-widget.stories.tsx | 9 +- .../widgets/latest-post/style.module.css | 5 +- .../__tests__/utm-insights.test.tsx | 63 +++++++++- .../widgets/utm-insights/render.tsx | 18 ++- .../widgets/utm-insights/style.module.css | 8 ++ .../widgets/utm-insights/use-utm-insights.ts | 2 + 26 files changed, 557 insertions(+), 87 deletions(-) create mode 100644 projects/packages/premium-analytics/changelog/fix-widget-post-detail-links create mode 100644 projects/packages/premium-analytics/packages/widgets-toolkit/src/components/leaderboard-post-label/__tests__/leaderboard-post-label.test.tsx create mode 100644 projects/packages/premium-analytics/packages/widgets-toolkit/src/components/leaderboard-post-label/index.ts create mode 100644 projects/packages/premium-analytics/packages/widgets-toolkit/src/components/leaderboard-post-label/leaderboard-post-label.module.scss create mode 100644 projects/packages/premium-analytics/packages/widgets-toolkit/src/components/leaderboard-post-label/leaderboard-post-label.tsx create mode 100644 projects/packages/premium-analytics/packages/widgets-toolkit/src/components/post-title-link/post-title-link.module.scss create mode 100644 projects/packages/premium-analytics/widgets/emails/__tests__/emails.test.tsx diff --git a/projects/packages/premium-analytics/changelog/fix-widget-post-detail-links b/projects/packages/premium-analytics/changelog/fix-widget-post-detail-links new file mode 100644 index 000000000000..6450cd87dcd1 --- /dev/null +++ b/projects/packages/premium-analytics/changelog/fix-widget-post-detail-links @@ -0,0 +1,4 @@ +Significance: patch +Type: fixed + +Widgets: link post and email titles to their detail pages instead of showing plain text. diff --git a/projects/packages/premium-analytics/packages/widgets-toolkit/src/components/chart-leaderboard/leaderboard-row.tsx b/projects/packages/premium-analytics/packages/widgets-toolkit/src/components/chart-leaderboard/leaderboard-row.tsx index 0f1cecd67efd..4d10d357c0f3 100644 --- a/projects/packages/premium-analytics/packages/widgets-toolkit/src/components/chart-leaderboard/leaderboard-row.tsx +++ b/projects/packages/premium-analytics/packages/widgets-toolkit/src/components/chart-leaderboard/leaderboard-row.tsx @@ -114,6 +114,10 @@ export function LeaderboardRow( { label, media, action }: LeaderboardRowProps ): /** * Build the label and chart-level interaction props for one leaderboard row. * + * Rows whose label is a post, page, or email use `LeaderboardPostLabel` + * instead: a chart row becomes a button and cannot nest an anchor, so a linked + * title cannot be expressed as an action here. + * * @param props - Leaderboard row content and action. * @return Props to spread onto a `LeaderboardEntry`. */ diff --git a/projects/packages/premium-analytics/packages/widgets-toolkit/src/components/index.ts b/projects/packages/premium-analytics/packages/widgets-toolkit/src/components/index.ts index dcd92986b875..b6f254c0c322 100644 --- a/projects/packages/premium-analytics/packages/widgets-toolkit/src/components/index.ts +++ b/projects/packages/premium-analytics/packages/widgets-toolkit/src/components/index.ts @@ -53,6 +53,11 @@ export { WidgetBackLink, type WidgetBackLinkProps } from './widget-back-link'; export { WidgetFooter, type WidgetFooterProps } from './widget-footer'; export { ReportLink, type ReportLinkProps } from './report-link'; export { PostTitleLink, POST_URL_SEARCH_PARAM, type PostTitleLinkProps } from './post-title-link'; +export { + LeaderboardPostLabel, + type LeaderboardPostLabelProps, + type LeaderboardPostLabelVariant, +} from './leaderboard-post-label'; export { VideoTitleLink, type VideoTitleLinkProps } from './video-title-link'; export { SubscriberList, diff --git a/projects/packages/premium-analytics/packages/widgets-toolkit/src/components/leaderboard-post-label/__tests__/leaderboard-post-label.test.tsx b/projects/packages/premium-analytics/packages/widgets-toolkit/src/components/leaderboard-post-label/__tests__/leaderboard-post-label.test.tsx new file mode 100644 index 000000000000..8c1e2570f7c7 --- /dev/null +++ b/projects/packages/premium-analytics/packages/widgets-toolkit/src/components/leaderboard-post-label/__tests__/leaderboard-post-label.test.tsx @@ -0,0 +1,89 @@ +/** + * External dependencies + */ +import { render, screen } from '@testing-library/react'; +/** + * Internal dependencies + */ +import { useWidgetRootContext } from '../../widget-root'; +import { LeaderboardPostLabel } from '../leaderboard-post-label'; +import type { AnchorHTMLAttributes, ReactNode } from 'react'; + +type MockRouteLinkProps = { + to: string; + params?: Record< string, unknown >; + search?: Record< string, unknown >; + children: ReactNode; +} & Omit< AnchorHTMLAttributes< HTMLAnchorElement >, 'href' >; + +jest.mock( '@wordpress/route', () => ( { + Link: ( { to, params, search, children, ...props }: MockRouteLinkProps ) => { + 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 ( + + { children } + + ); + }, +} ) ); + +jest.mock( '../../widget-root', () => ( { + useWidgetRootContext: jest.fn(), +} ) ); + +const mockUseWidgetRootContext = useWidgetRootContext as jest.Mock; + +beforeEach( () => { + mockUseWidgetRootContext.mockReturnValue( { reportParams: { from: '2026-06-01' } } ); +} ); + +describe( 'LeaderboardPostLabel', () => { + it( 'links a post to its detail route and carries the report window', () => { + render( + + ); + + const link = screen.getByRole( 'link', { name: 'Hello world' } ); + const url = new URL( link.getAttribute( 'href' ) ?? '', 'https://example.com' ); + + expect( url.pathname ).toBe( '/post/12' ); + expect( url.searchParams.get( 'from' ) ).toBe( '2026-06-01' ); + expect( url.searchParams.get( 'post_url' ) ).toBe( 'https://example.com/hello/' ); + expect( link ).not.toHaveAttribute( 'target', '_blank' ); + } ); + + it( 'opens the requested detail tab when a section is given', () => { + render( ); + + expect( screen.getByRole( 'link', { name: 'Newsletter' } ) ).toHaveAttribute( + 'href', + '/post/12?from=2026-06-01§ion=email-opens' + ); + } ); + + it( 'falls back to the public URL when there is no post ID', () => { + render( ); + + const link = screen.getByRole( 'link', { name: /Untracked page/ } ); + expect( link ).toHaveAttribute( 'href', 'https://example.com/untracked/' ); + expect( link ).toHaveAttribute( 'target', '_blank' ); + } ); + + it( 'renders plain text when the row has neither a post ID nor a safe URL', () => { + render( ); + + expect( screen.getByText( 'Untitled' ) ).toBeInTheDocument(); + expect( screen.queryByRole( 'link' ) ).not.toBeInTheDocument(); + } ); +} ); diff --git a/projects/packages/premium-analytics/packages/widgets-toolkit/src/components/leaderboard-post-label/index.ts b/projects/packages/premium-analytics/packages/widgets-toolkit/src/components/leaderboard-post-label/index.ts new file mode 100644 index 000000000000..397012593a4c --- /dev/null +++ b/projects/packages/premium-analytics/packages/widgets-toolkit/src/components/leaderboard-post-label/index.ts @@ -0,0 +1,5 @@ +export { + LeaderboardPostLabel, + type LeaderboardPostLabelProps, + type LeaderboardPostLabelVariant, +} from './leaderboard-post-label'; diff --git a/projects/packages/premium-analytics/packages/widgets-toolkit/src/components/leaderboard-post-label/leaderboard-post-label.module.scss b/projects/packages/premium-analytics/packages/widgets-toolkit/src/components/leaderboard-post-label/leaderboard-post-label.module.scss new file mode 100644 index 000000000000..24a3f1173b5c --- /dev/null +++ b/projects/packages/premium-analytics/packages/widgets-toolkit/src/components/leaderboard-post-label/leaderboard-post-label.module.scss @@ -0,0 +1,44 @@ +.row { + display: flex; + align-items: center; + gap: var(--wpds-dimension-gap-xs); + min-inline-size: 0; +} + +/* Matches the shared `LeaderboardRow` chrome, so a post label sits at the same + height as the rows around it. */ +.compact { + min-block-size: 36px; + padding-inline: var(--wpds-dimension-padding-sm); +} + +/* Block padding sets the overlay bar height, since these rows have no image to + size them. The inline-start inset keeps the text off the bar's rounded edge: + the chart applies it to its own `.label` in overlay mode, but a custom label + element bypasses that rule. */ +.overlay { + padding-block: var(--wpds-dimension-padding-md); + padding-inline-start: var(--wpds-dimension-padding-sm); +} + +/* `flex: 1 1 auto` keeps the whole row clickable, matching the shared + `LeaderboardRow` link, which fills the row with `inline-size: 100%`. + `min-inline-size: 0` lets it shrink below its content width so the ellipsis + applies. */ +.title { + display: inline-flex; + flex: 1 1 auto; + align-items: center; + gap: var(--wpds-dimension-gap-xs); + min-inline-size: 0; +} + +/* `text-overflow` needs an inline formatting context, which the flex containers + above do not give it, so the ellipsis lives on the text. */ +.text { + min-inline-size: 0; + overflow: hidden; + white-space: nowrap; + text-overflow: ellipsis; + font-size: var(--wpds-typography-font-size-sm); +} diff --git a/projects/packages/premium-analytics/packages/widgets-toolkit/src/components/leaderboard-post-label/leaderboard-post-label.tsx b/projects/packages/premium-analytics/packages/widgets-toolkit/src/components/leaderboard-post-label/leaderboard-post-label.tsx new file mode 100644 index 000000000000..b9349264609f --- /dev/null +++ b/projects/packages/premium-analytics/packages/widgets-toolkit/src/components/leaderboard-post-label/leaderboard-post-label.tsx @@ -0,0 +1,109 @@ +/** + * External dependencies + */ +import { pickReportDateParams } from '@jetpack-premium-analytics/routing'; +import clsx from 'clsx'; +import { useMemo } from 'react'; +/** + * Internal dependencies + */ +import { PostTitleLink } from '../post-title-link'; +import { useWidgetRootContext } from '../widget-root'; +import styles from './leaderboard-post-label.module.scss'; +import type { ReactElement } from 'react'; + +/** + * How tall the row sits. + * + * `compact` matches the shared `LeaderboardRow` chrome, so post labels line up + * with the rows around them. `overlay` keeps the taller block padding the + * older overlay-bar leaderboards render at. + */ +export type LeaderboardPostLabelVariant = 'compact' | 'overlay'; + +export type LeaderboardPostLabelProps = { + /** + * Post or page ID. Rows carrying one link to the internal detail route. + */ + id?: number | string; + /** + * Visible row title. + */ + label: string; + /** + * Public URL of the content. Used only when there is no post ID. + */ + link?: string | null; + /** + * Optional detail-page tab to open, e.g. `email-opens`. + */ + section?: string; + /** + * Row height. Defaults to `compact`. + */ + variant?: LeaderboardPostLabelVariant; + /** + * Extra class for the row, for per-widget spacing. + */ + className?: string; +}; + +/** + * A leaderboard row label for a post, page, or email. + * + * Wraps `PostTitleLink` in the row chrome every leaderboard needs: a flex row + * that keeps the title on one line with an ellipsis and leaves the trailing + * external-link icon room. Widgets pass no classes for this — only the + * `variant`, plus a `className` when they need extra spacing. + * + * The report window comes from `WidgetRootContext`, the same way `ReportLink` + * resolves it, so the detail page opens on the range the row was read against + * without every widget threading it down. + * + * Rows that are not linked entities — an avatar and a name, or a drill-down + * into child rows — use `buildLeaderboardRow` instead. + * + * @param props - Component props. + * @param props.id - Post or page ID. + * @param props.label - Visible row title. + * @param props.link - Public URL, used only without a post ID. + * @param props.section - Optional detail-page tab to open. + * @param props.variant - Row height. + * @param props.className - Extra class for the row. + * @return The row label. + */ +export function LeaderboardPostLabel( { + id, + label, + link, + section, + variant = 'compact', + className, +}: LeaderboardPostLabelProps ): ReactElement { + const { reportParams } = useWidgetRootContext(); + const search = useMemo( + () => ( { + ...pickReportDateParams( reportParams ), + ...( section ? { section } : {} ), + } ), + [ reportParams, section ] + ); + + return ( + + + + ); +} diff --git a/projects/packages/premium-analytics/packages/widgets-toolkit/src/components/post-title-link/post-title-link.module.scss b/projects/packages/premium-analytics/packages/widgets-toolkit/src/components/post-title-link/post-title-link.module.scss new file mode 100644 index 000000000000..520856e53652 --- /dev/null +++ b/projects/packages/premium-analytics/packages/widgets-toolkit/src/components/post-title-link/post-title-link.module.scss @@ -0,0 +1,21 @@ +/* Defaults every caller needs. Layout (single-line ellipsis, flex rows) is not + here: `latest-post` clamps its title to three lines, so an `inline-flex` + anchor would break it. Leaderboards get that layer from + `LeaderboardPostLabel`. + + These must stay plain classes. wp-admin colours bare anchors with an element + selector, unlayered, and this package's styles are unlayered too — so a + zero-specificity `:where()` would lose to it and every link would render + admin blue in product while Storybook and Jest, which load no wp-admin CSS, + looked correct. A caller that needs to win a tie against these should use + `:any-link`, as `routes/post-detail/stage.module.scss` does. */ + +.link { + color: inherit; + text-decoration: none; +} + +.link:hover, +.link:focus { + text-decoration: underline; +} diff --git a/projects/packages/premium-analytics/packages/widgets-toolkit/src/components/post-title-link/post-title-link.tsx b/projects/packages/premium-analytics/packages/widgets-toolkit/src/components/post-title-link/post-title-link.tsx index 58eec8e10218..41dffe051f2e 100644 --- a/projects/packages/premium-analytics/packages/widgets-toolkit/src/components/post-title-link/post-title-link.tsx +++ b/projects/packages/premium-analytics/packages/widgets-toolkit/src/components/post-title-link/post-title-link.tsx @@ -4,6 +4,11 @@ import { Link as UiLink } from '@jetpack-premium-analytics/externals'; import { safeHttpUrl } from '@jetpack-premium-analytics/ui'; import { Link } from '@wordpress/route'; +import clsx from 'clsx'; +/** + * Internal dependencies + */ +import styles from './post-title-link.module.scss'; /** * Route search param carrying a row's public URL to the post detail page. @@ -39,8 +44,9 @@ export type PostTitleLinkProps = { search?: Record< string, unknown >; /** - * Optional classes for each rendering branch. `text` applies to the label - * span in every branch, so one rule can ellipsize the title everywhere. + * Optional classes for each rendering branch, applied on top of the + * component's own defaults. `text` applies to the label span in every + * branch, so one rule can ellipsize the title everywhere. */ classNames?: { internal?: string; @@ -94,7 +100,7 @@ export function PostTitleLink( { if ( Number.isInteger( postId ) && postId > 0 ) { return ( { expect( result[ 0 ].posts ).toEqual( [ { id: '12', + postId: 12, title: 'Hello world', link: 'https://example.com/hello', currentValue: 20, @@ -224,6 +225,7 @@ describe( 'buildTopAuthorsData', () => { }, { id: 'post-1', + postId: undefined, title: 'Second post', link: null, currentValue: 10, @@ -312,6 +314,7 @@ describe( 'buildTopAuthorsData', () => { expect( result[ 0 ].posts ).toEqual( [ { id: '1', + postId: 1, title: 'Still popular', link: null, currentValue: 20, @@ -322,6 +325,7 @@ describe( 'buildTopAuthorsData', () => { }, { id: '2', + postId: 2, title: 'New post', link: null, currentValue: 10, @@ -332,6 +336,7 @@ describe( 'buildTopAuthorsData', () => { }, { id: '3', + postId: 3, title: 'Dropped post', link: null, currentValue: 0, diff --git a/projects/packages/premium-analytics/widgets/authors/build-top-authors-data.ts b/projects/packages/premium-analytics/widgets/authors/build-top-authors-data.ts index 7fb25517ab9f..c475ac01ab79 100644 --- a/projects/packages/premium-analytics/widgets/authors/build-top-authors-data.ts +++ b/projects/packages/premium-analytics/widgets/authors/build-top-authors-data.ts @@ -25,6 +25,7 @@ const UNTRACKED_AUTHORS_SENTINEL = 'Untracked Authors'; */ export interface AuthorPost { id: string; + postId?: string | number; title: string; link: string | null; currentValue: number; @@ -89,6 +90,7 @@ function toAuthorPostRows( posts: StatsTopAuthorsPostComparisonItem[] ): AuthorP return { id: post.id != null ? String( post.id ) : post.link ?? `post-${ index }`, + postId: post.id ?? undefined, title: typeof post.label === 'string' ? post.label : String( post.label ?? '' ), link: post.link ?? null, currentValue: post.views, diff --git a/projects/packages/premium-analytics/widgets/authors/render.tsx b/projects/packages/premium-analytics/widgets/authors/render.tsx index ea7756663d7e..417a061688ec 100644 --- a/projects/packages/premium-analytics/widgets/authors/render.tsx +++ b/projects/packages/premium-analytics/widgets/authors/render.tsx @@ -4,6 +4,7 @@ import { useStatsTopAuthors } from '@jetpack-premium-analytics/data'; import { LeaderboardChart, + LeaderboardPostLabel, ReportLink, WidgetBackLink, WidgetFooter, @@ -11,7 +12,6 @@ import { WidgetState, buildLeaderboardRow, formatLegendLabels, - safeHttpUrl, toMaxRows, useWidgetDrillDown, useWidgetRootContext, @@ -127,25 +127,15 @@ export function AuthorsLeaderboard( { // the data layer already aligned current/comparison values, including // posts that only existed in the comparison period. if ( selectedAuthor ) { - return selectedAuthor.posts.map( post => { - // Post permalinks come from report data, so validate the scheme - // before the row becomes a link. - const postHref = safeHttpUrl( post.link ); - - return { - id: post.id, - ...buildLeaderboardRow( { - label: post.title, - media: { kind: 'none' }, - action: postHref ? { kind: 'link', href: postHref } : { kind: 'static' }, - } ), - currentValue: post.currentValue, - previousValue: post.previousValue, - currentShare: post.currentShare, - previousShare: post.previousShare, - delta: post.delta, - }; - } ); + return selectedAuthor.posts.map( post => ( { + id: post.id, + label: , + currentValue: post.currentValue, + previousValue: post.previousValue, + currentShare: post.currentShare, + previousShare: post.previousShare, + delta: post.delta, + } ) ); } // Top authors: name + avatar label, and a click drills into the author's diff --git a/projects/packages/premium-analytics/widgets/emails/__tests__/emails.test.tsx b/projects/packages/premium-analytics/widgets/emails/__tests__/emails.test.tsx new file mode 100644 index 000000000000..8208007f7341 --- /dev/null +++ b/projects/packages/premium-analytics/widgets/emails/__tests__/emails.test.tsx @@ -0,0 +1,52 @@ +/** + * External dependencies + */ +import { WidgetRoot } from '@jetpack-premium-analytics/widgets-toolkit'; +import { render, screen } from '@testing-library/react'; +/** + * Internal dependencies + */ +import { EmailsLeaderboard, type EmailRow } from '../render'; +import type { EmailMetric } from '../widget'; + +jest.mock( '@wordpress/route', () => jest.requireActual( '../../test-utils' ).mockWordPressRoute ); + +const rows: EmailRow[] = [ + { + id: 12, + postId: 12, + link: 'https://example.com/newsletter/', + label: 'Monthly newsletter', + opensRate: 42, + clicksRate: 7, + }, +]; + +function renderLeaderboard( metric: EmailMetric ) { + return render( + + + + ); +} + +describe( 'EmailsLeaderboard', () => { + it.each( [ + [ 'opens', 'email-opens' ], + [ 'clicks', 'email-clicks' ], + ] as const )( 'opens the matching detail tab for the %s metric', ( metric, expectedSection ) => { + renderLeaderboard( metric ); + + const link = screen.getByRole( 'link', { name: 'Monthly newsletter' } ); + const url = new URL( link.getAttribute( 'href' ) ?? '', 'https://example.com' ); + + expect( url.pathname ).toBe( '/post/12' ); + expect( url.searchParams.get( 'from' ) ).toBe( '2026-06-01' ); + expect( url.searchParams.get( 'section' ) ).toBe( expectedSection ); + expect( url.searchParams.get( 'post_url' ) ).toBe( 'https://example.com/newsletter/' ); + } ); +} ); diff --git a/projects/packages/premium-analytics/widgets/emails/render.tsx b/projects/packages/premium-analytics/widgets/emails/render.tsx index f8ddad26787b..ec05900930f6 100644 --- a/projects/packages/premium-analytics/widgets/emails/render.tsx +++ b/projects/packages/premium-analytics/widgets/emails/render.tsx @@ -4,6 +4,7 @@ import { useStatsEmailSummary, type StatsEmailSummary } from '@jetpack-premium-analytics/data'; import { LeaderboardChart, + LeaderboardPostLabel, ReportLink, WidgetFooter, WidgetRoot, @@ -35,6 +36,14 @@ export type EmailRow = { * Stable identifier for the email (post ID or, as a fallback, the array index). */ id: string | number; + /** + * Post ID of the newsletter, when the report carries one. + */ + postId?: string | number; + /** + * Public URL of the newsletter. + */ + link?: string | null; /** * Email subject line. */ @@ -71,9 +80,13 @@ function buildLeaderboardData( rows: EmailRow[], metric: EmailMetric ): Leaderbo return { id: String( row.id ), label: ( - - { row.label } - + ), // `LeaderboardChart` formats the value as a percentage, so the rate // is expressed as a fraction here. @@ -146,6 +159,8 @@ function toEmailRows( report: StatsEmailSummary | undefined, max: number ): Emai // `max = 0 → all rows` convention and a guard against an over-long response. return items.slice( 0, max > 0 ? max : undefined ).map( ( item, index ) => ( { id: item.id ?? index, + postId: item.id, + link: typeof item.link === 'string' ? item.link : null, label: String( item.label ?? '' ), opensRate: item.opens_rate, clicksRate: item.clicks_rate, diff --git a/projects/packages/premium-analytics/widgets/emails/stories/emails-widget.stories.tsx b/projects/packages/premium-analytics/widgets/emails/stories/emails-widget.stories.tsx index 7131fe2f3367..78a11df1aca8 100644 --- a/projects/packages/premium-analytics/widgets/emails/stories/emails-widget.stories.tsx +++ b/projects/packages/premium-analytics/widgets/emails/stories/emails-widget.stories.tsx @@ -7,6 +7,11 @@ * mock `stats/emails/summary` response so it renders populated in product * context. */ +/** + * External dependencies + */ +import { getDefaultQueryParams } from '@jetpack-premium-analytics/data'; +import { WidgetRoot } from '@jetpack-premium-analytics/widgets-toolkit'; /** * Internal dependencies */ @@ -14,7 +19,6 @@ import { registerReportMocks, setReportMockState, } from '../../../packages/widgets-toolkit/src/stories/mocks/register-report-mocks'; -import { withChartTheme } from '../../../packages/widgets-toolkit/src/stories/with-chart-theme'; import { DEFAULT_WIDGET_DASHBOARD_STORY_ARGS, WidgetDashboardWithWidget as WidgetDashboardWithWidgetStory, @@ -47,7 +51,6 @@ const meta: Meta< typeof EmailsLeaderboard > = { }, }, }, - decorators: [ withChartTheme ], }; export default meta; @@ -57,36 +60,48 @@ type Story = StoryObj< typeof EmailsLeaderboard >; const mockRows: EmailRow[] = [ { id: 1, + postId: 1, + link: 'https://example.com/stand-out/', label: '4 Ways to Make Your Website Stand Out', opensRate: 38.1, clicksRate: 3.81, }, { id: 2, + postId: 2, + link: 'https://example.com/develop-locally/', label: 'Develop Locally on Linux with WordPress.com', opensRate: 41.2, clicksRate: 5.98, }, { id: 3, + postId: 3, + link: 'https://example.com/new-themes/', label: '10 Brand-New WordPress.com Themes for 2026', opensRate: 35.7, clicksRate: 7.12, }, { id: 4, + postId: 4, + link: 'https://example.com/languages/', label: 'WordPress.com Is Now Available in More Languages', opensRate: 52.4, clicksRate: 8.93, }, { id: 5, + postId: 5, + link: 'https://example.com/wordcamp-europe/', label: 'WordCamp Europe 2026: What to Expect', opensRate: 47.9, clicksRate: 10.25, }, { id: 6, + postId: 6, + link: 'https://example.com/collaborate/', label: 'Click, Comment, Done: A Better Way to Collaborate', opensRate: 44.3, clicksRate: 10.38, @@ -96,6 +111,8 @@ const mockRows: EmailRow[] = [ const mockLongLabelRows: EmailRow[] = [ { id: 1, + postId: 1, + link: 'https://example.com/long-subject/', label: 'An exhaustively long, keyword-stuffed subject line that almost certainly needs to be truncated before it overflows the row', opensRate: 22.5, @@ -103,12 +120,20 @@ const mockLongLabelRows: EmailRow[] = [ }, { id: 2, + postId: 2, + link: 'https://example.com/monthly-digest/', label: 'Your monthly digest: billing, new features, and what is coming next', opensRate: 33.8, clicksRate: 6.7, }, ]; +const withEmailsWidgetRoot: Decorator = Story => ( + + + +); + /** * Default populated state — latest emails (newest first) with their open rate. */ @@ -116,7 +141,7 @@ export const Default: Story = { args: { rows: mockRows, }, - decorators: [ withWidgetCanvas ], + decorators: [ withWidgetCanvas, withEmailsWidgetRoot, withStoryRouter ], }; /** @@ -127,7 +152,7 @@ export const ByClickRate: Story = { rows: mockRows, metric: 'clicks', }, - decorators: [ withWidgetCanvas ], + decorators: [ withWidgetCanvas, withEmailsWidgetRoot, withStoryRouter ], }; // Renders the data-connected widget with a `max` distinct from the other @@ -189,7 +214,7 @@ export const LongLabels: Story = { args: { rows: mockLongLabelRows, }, - decorators: [ withWidgetCanvas ], + decorators: [ withWidgetCanvas, withEmailsWidgetRoot, withStoryRouter ], }; /** @@ -224,7 +249,7 @@ export const SizeMedium: Story = { args: { rows: mockRows, }, - decorators: [ createSizeDecorator( '448px' ) ], + decorators: [ createSizeDecorator( '448px' ), withEmailsWidgetRoot, withStoryRouter ], }; /** @@ -234,7 +259,7 @@ export const SizeLarge: Story = { args: { rows: mockRows, }, - decorators: [ createSizeDecorator( '576px' ) ], + decorators: [ createSizeDecorator( '576px' ), withEmailsWidgetRoot, withStoryRouter ], }; /** diff --git a/projects/packages/premium-analytics/widgets/emails/style.module.css b/projects/packages/premium-analytics/widgets/emails/style.module.css index 39e717ef1c5b..c1a13158d6c0 100644 --- a/projects/packages/premium-analytics/widgets/emails/style.module.css +++ b/projects/packages/premium-analytics/widgets/emails/style.module.css @@ -33,16 +33,3 @@ min-block-size: 0; overflow: hidden; } - -/* The label fills its row; vertical padding sets the overlay bar height (there - is no image to size it) and the inline padding insets the text from the bar's - rounded left edge. */ -.label { - display: block; - padding-block: var(--wpds-dimension-padding-md); - padding-inline-start: var(--wpds-dimension-padding-sm); - overflow: hidden; - color: inherit; - text-overflow: ellipsis; - white-space: nowrap; -} diff --git a/projects/packages/premium-analytics/widgets/latest-post/__tests__/latest-post-card.test.tsx b/projects/packages/premium-analytics/widgets/latest-post/__tests__/latest-post-card.test.tsx index 91732d9daaa2..1efa530b34b4 100644 --- a/projects/packages/premium-analytics/widgets/latest-post/__tests__/latest-post-card.test.tsx +++ b/projects/packages/premium-analytics/widgets/latest-post/__tests__/latest-post-card.test.tsx @@ -11,6 +11,7 @@ import type { LatestPostWithMetrics } from '../use-latest-post'; jest.mock( '@wordpress/route', () => jest.requireActual( '../../test-utils' ).mockWordPressRoute ); const post = { + id: 12, title: 'Quarterly update', url: 'https://example.com/quarterly-update/', date: '2026-06-05T00:00:00+00:00', @@ -20,20 +21,33 @@ const post = { } as unknown as LatestPostWithMetrics; describe( 'LatestPostCard', () => { - it( 'links the title to the post', () => { - render( ); + it( 'links the title to the post detail page and carries the report window', () => { + render( ); - // `openInNewTab` appends a screen-reader hint to the accessible name. - expect( screen.getByRole( 'link', { name: /^Quarterly update/ } ) ).toHaveAttribute( - 'href', - 'https://example.com/quarterly-update/' - ); + const link = screen.getByRole( 'link', { name: 'Quarterly update' } ); + const url = new URL( link.getAttribute( 'href' ) ?? '', 'https://example.com' ); + + expect( url.pathname ).toBe( '/post/12' ); + expect( url.searchParams.get( 'from' ) ).toBe( '2026-06-01' ); + expect( url.searchParams.get( 'post_url' ) ).toBe( 'https://example.com/quarterly-update/' ); + } ); + + it( 'falls back to the published post when there is no post ID', () => { + render( ); + + const link = screen.getByRole( 'link', { name: /Quarterly update/ } ); + expect( link ).toHaveAttribute( 'href', 'https://example.com/quarterly-update/' ); + expect( link ).toHaveAttribute( 'target', '_blank' ); } ); // The title used to be wrapped in `` unconditionally, so a revert here is plausible. it( 'keeps the title readable as plain text when the post URL is unsafe', () => { render( - + ); expect( screen.getByText( 'Quarterly update' ) ).toBeInTheDocument(); diff --git a/projects/packages/premium-analytics/widgets/latest-post/package.json b/projects/packages/premium-analytics/widgets/latest-post/package.json index ba629d0df495..747b03f02046 100644 --- a/projects/packages/premium-analytics/widgets/latest-post/package.json +++ b/projects/packages/premium-analytics/widgets/latest-post/package.json @@ -5,6 +5,7 @@ "type": "module", "dependencies": { "@jetpack-premium-analytics/data": "link:../../packages/data", + "@jetpack-premium-analytics/routing": "link:../../packages/routing", "@jetpack-premium-analytics/widgets-toolkit": "link:../../packages/widgets-toolkit", "@wordpress/i18n": "^6.9.0", "@wordpress/icons": "^15.0.0", diff --git a/projects/packages/premium-analytics/widgets/latest-post/render.tsx b/projects/packages/premium-analytics/widgets/latest-post/render.tsx index 4a4deef21f22..4f9c68dd9ed0 100644 --- a/projects/packages/premium-analytics/widgets/latest-post/render.tsx +++ b/projects/packages/premium-analytics/widgets/latest-post/render.tsx @@ -1,17 +1,20 @@ /** * External dependencies */ +import { pickReportDateParams } from '@jetpack-premium-analytics/routing'; import { MetricValue, + PostTitleLink, WidgetRoot, WidgetState, - safeHttpUrl, + useWidgetRootContext, type DataFormat, type ReportParamsFieldAttributes, } from '@jetpack-premium-analytics/widgets-toolkit'; +import { useMemo } from '@wordpress/element'; import { __, sprintf } from '@wordpress/i18n'; import { postList } from '@wordpress/icons'; -import { Link, Text } from '@wordpress/ui'; +import { Text } from '@wordpress/ui'; import { format, parseISO } from 'date-fns'; /** * Internal dependencies @@ -36,6 +39,10 @@ type LatestPostCardProps = { * The resolved latest post. */ post: LatestPostWithMetrics; + /** + * Search parameters carried into the post detail route. + */ + detailSearch?: Record< string, unknown >; }; /** @@ -85,8 +92,8 @@ function MetricTile( { label, value }: MetricTileProps ) { /** * Presentational card for the "Latest post" widget: the post title (linking to - * the published post), its publish date, three lifetime metric tiles (views, - * likes, comments), and the post's featured image when present. + * its analytics detail page), its publish date, three lifetime metric tiles + * (views, likes, comments), and the post's featured image when present. * * Renders only the populated state; loading, error, and empty are handled by * `` in `LatestPostReport`. Exported so Storybook can exercise the @@ -95,29 +102,25 @@ function MetricTile( { label, value }: MetricTileProps ) { * @param {LatestPostCardProps} props - The component props. * @return The rendered card. */ -export const LatestPostCard = ( { post }: LatestPostCardProps ) => { +export const LatestPostCard = ( { post, detailSearch = {} }: LatestPostCardProps ) => { const publishDate = formatPublishDate( post.date ); - const postHref = safeHttpUrl( post.url ); return (
}> - { postHref ? ( - - { post.title } - - ) : ( - // `.title` clamps to three lines, so keep the tooltip the link branch carries. - { post.title } - ) } + { publishDate && ( @@ -157,8 +160,11 @@ export const LatestPostCard = ( { post }: LatestPostCardProps ) => { * @return The widget content. */ function LatestPostReport() { + const { reportParams } = useWidgetRootContext(); const { post, isLoading, isFetching, isError, refetch } = useLatestPost(); + const detailSearch = useMemo( () => pickReportDateParams( reportParams ), [ reportParams ] ); + return ( - { post && } + { post && } ); } diff --git a/projects/packages/premium-analytics/widgets/latest-post/stories/latest-post-widget.stories.tsx b/projects/packages/premium-analytics/widgets/latest-post/stories/latest-post-widget.stories.tsx index a5aa9fcb444a..bd8c71f5d259 100644 --- a/projects/packages/premium-analytics/widgets/latest-post/stories/latest-post-widget.stories.tsx +++ b/projects/packages/premium-analytics/widgets/latest-post/stories/latest-post-widget.stories.tsx @@ -25,6 +25,7 @@ import { widgetDashboardWithWidgetArgTypes, type WidgetDashboardWithWidgetControls, } from '../../stories/widget-dashboard-with-widget'; +import { withStoryRouter } from '../../stories/with-story-router'; import { createStoryWidgetType } from '../../stories/create-story-widget-type'; import { withWidgetCanvas } from '../../stories/with-widget-canvas'; import LatestPostRender from '../render'; @@ -171,7 +172,7 @@ type Story = StoryObj< Partial< ComponentProps< typeof LatestPostRender > > >; */ export const Default: Story = { render: renderLatestPost, - decorators: [ withWidgetCanvas ], + decorators: [ withWidgetCanvas, withStoryRouter ], }; /** @@ -182,7 +183,7 @@ export const Loading: Story = { render: () => renderLatestPostOnPreset( 'last-90-days' ), // Off the shared autodocs page — path-keyed override; see forceStatsMockState. tags: [ '!autodocs' ], - decorators: [ withWidgetCanvas ], + decorators: [ withWidgetCanvas, withStoryRouter ], beforeEach: () => forceLatestPostState( 'loading' ), }; @@ -194,7 +195,7 @@ export const Loading: Story = { export const Error: Story = { render: () => renderLatestPostOnPreset( 'last-7-days' ), tags: [ '!autodocs' ], - decorators: [ withWidgetCanvas ], + decorators: [ withWidgetCanvas, withStoryRouter ], beforeEach: () => forceLatestPostState( 'error' ), }; @@ -205,7 +206,7 @@ export const Error: Story = { export const Empty: Story = { render: () => renderLatestPostOnPreset( 'last-365-days' ), tags: [ '!autodocs' ], - decorators: [ withWidgetCanvas ], + decorators: [ withWidgetCanvas, withStoryRouter ], beforeEach: () => forceLatestPostState( 'empty' ), }; diff --git a/projects/packages/premium-analytics/widgets/latest-post/style.module.css b/projects/packages/premium-analytics/widgets/latest-post/style.module.css index a89269ac595f..10ffde846141 100644 --- a/projects/packages/premium-analytics/widgets/latest-post/style.module.css +++ b/projects/packages/premium-analytics/widgets/latest-post/style.module.css @@ -27,7 +27,10 @@ min-width: 0; } -.titleLink { +/* `:any-link` so this beats `PostTitleLink`'s own `color: inherit` default + deterministically — as plain classes the two would tie and the winner would + depend on compiled stylesheet order. Same idiom as the post detail header. */ +.titleLink:any-link { color: var(--wpds-color-foreground-content-neutral); text-decoration: none; } diff --git a/projects/packages/premium-analytics/widgets/utm-insights/__tests__/utm-insights.test.tsx b/projects/packages/premium-analytics/widgets/utm-insights/__tests__/utm-insights.test.tsx index aaff704c780c..b5db1bf8351f 100644 --- a/projects/packages/premium-analytics/widgets/utm-insights/__tests__/utm-insights.test.tsx +++ b/projects/packages/premium-analytics/widgets/utm-insights/__tests__/utm-insights.test.tsx @@ -2,25 +2,33 @@ * External dependencies */ import { render, screen } from '@testing-library/react'; +import userEvent from '@testing-library/user-event'; /** * Internal dependencies */ import UtmInsightsWidget from '../render'; +import type { UtmInsightsRow } from '../use-utm-insights'; jest.mock( '@wordpress/route', () => jest.requireActual( '../../test-utils' ).mockWordPressRoute ); +let mockRows: UtmInsightsRow[] = []; + jest.mock( '../use-utm-insights', () => ( { __esModule: true, default: () => ( { - data: [], + data: mockRows, hasComparison: false, isLoading: false, isFetching: false, - hasData: false, + hasData: mockRows.length > 0, isError: false, } ), } ) ); +beforeEach( () => { + mockRows = []; +} ); + describe( 'UtmInsightsWidget', () => { it( 'links to the UTM report', () => { render( ); @@ -51,4 +59,55 @@ describe( 'UtmInsightsWidget', () => { expect( screen.queryByRole( 'link', { name: 'See report' } ) ).not.toBeInTheDocument(); } ); + + it( 'links a drilled-in post to its detail page and carries the report window', async () => { + const user = userEvent.setup(); + mockRows = [ + { + label: 'jetpack-forms / email', + value: 30, + children: [ + { postId: 12, label: 'Jetpack Forms', value: 20, href: 'https://example.com/forms/' }, + ], + }, + ]; + + render( + + ); + + await user.click( + screen.getByRole( 'button', { name: 'View posts for jetpack-forms / email' } ) + ); + + const titleLink = screen.getByRole( 'link', { name: 'Jetpack Forms' } ); + expect( titleLink ).toHaveAttribute( 'href', expect.stringContaining( '/post/12' ) ); + expect( titleLink ).toHaveAttribute( 'href', expect.stringContaining( 'from=2026-06-01' ) ); + expect( titleLink ).not.toHaveAttribute( 'target', '_blank' ); + } ); + + it( 'falls back to the public URL when a drilled-in post has no ID', async () => { + const user = userEvent.setup(); + mockRows = [ + { + label: 'jetpack-forms / email', + value: 30, + children: [ + { postId: 0, label: 'Untracked page', value: 20, href: 'https://example.com/untracked/' }, + ], + }, + ]; + + render( ); + + await user.click( + screen.getByRole( 'button', { name: 'View posts for jetpack-forms / email' } ) + ); + + const titleLink = screen.getByRole( 'link', { name: /Untracked page/ } ); + expect( titleLink ).toHaveAttribute( 'href', 'https://example.com/untracked/' ); + expect( titleLink ).toHaveAttribute( 'target', '_blank' ); + } ); } ); diff --git a/projects/packages/premium-analytics/widgets/utm-insights/render.tsx b/projects/packages/premium-analytics/widgets/utm-insights/render.tsx index 14ab2532da90..01893d7ee9b5 100644 --- a/projects/packages/premium-analytics/widgets/utm-insights/render.tsx +++ b/projects/packages/premium-analytics/widgets/utm-insights/render.tsx @@ -3,12 +3,13 @@ */ import { useEffect, useMemo } from '@wordpress/element'; import { __, sprintf } from '@wordpress/i18n'; -import { Stack, Text } from '@wordpress/ui'; +import { Text } from '@wordpress/ui'; import { calculateDelta, describeError, getCombinedPeriodMax, LeaderboardChart, + LeaderboardPostLabel, ReportLink, WidgetBackLink, WidgetFooter, @@ -135,13 +136,22 @@ function UtmInsightsInner( { utmDimension, max, showReportLink }: UtmInsightsInn return activeData.map( ( item, index ) => { const previousValue = item.previousValue; + const postRow = 'postId' in item ? item : null; return { id: `${ index }-${ item.label }`, - label: ( - + label: postRow ? ( + + ) : ( + { item.label } - + ), currentValue: item.value, currentShare: sharePercentage( item.value, maxValue ), diff --git a/projects/packages/premium-analytics/widgets/utm-insights/style.module.css b/projects/packages/premium-analytics/widgets/utm-insights/style.module.css index 3500f82c9b30..4feec451730b 100644 --- a/projects/packages/premium-analytics/widgets/utm-insights/style.module.css +++ b/projects/packages/premium-analytics/widgets/utm-insights/style.module.css @@ -20,13 +20,21 @@ margin-block-end: 0; } +/* The UTM value rows. Post rows use `LeaderboardPostLabel` instead and take + only the inline-end inset below. */ .itemLabel { + display: flex; + align-items: center; min-inline-size: 0; padding-block: var(--wpds-dimension-padding-md); padding-inline-start: var(--wpds-dimension-padding-sm); padding-inline-end: var(--wpds-dimension-padding-lg); } +.itemLabelInset { + padding-inline-end: var(--wpds-dimension-padding-lg); +} + .itemLabelText { overflow: hidden; white-space: nowrap; diff --git a/projects/packages/premium-analytics/widgets/utm-insights/use-utm-insights.ts b/projects/packages/premium-analytics/widgets/utm-insights/use-utm-insights.ts index d5b932d68b61..4a09322857eb 100644 --- a/projects/packages/premium-analytics/widgets/utm-insights/use-utm-insights.ts +++ b/projects/packages/premium-analytics/widgets/utm-insights/use-utm-insights.ts @@ -10,6 +10,7 @@ import type { } from '@jetpack-premium-analytics/data'; export interface UtmInsightsChildRow { + postId: number; label: string; value: number; previousValue?: number; @@ -55,6 +56,7 @@ function getLabel( item: { label: unknown } ): string { function toChildRow( item: StatsUtmComparisonTopPostItem ): UtmInsightsChildRow { return { + postId: item.id, label: getLabel( item ), value: item.value, previousValue: item.previousValue, From 6bd0bc358e892bc2d0bb04d5ea4c36fe3eaf98e1 Mon Sep 17 00:00:00 2001 From: Nikhil Date: Thu, 30 Jul 2026 19:16:43 +0530 Subject: [PATCH 2/5] Premium Analytics: strengthen entity detail link tests --- .../authors/__tests__/authors.test.tsx | 43 +++++++++ .../widgets/emails/__tests__/emails.test.tsx | 48 +++++++++- .../__tests__/latest-post-card.test.tsx | 44 +++++++++- .../__tests__/use-utm-insights.test.tsx | 88 +++++++++++++++++++ 4 files changed, 220 insertions(+), 3 deletions(-) create mode 100644 projects/packages/premium-analytics/widgets/utm-insights/__tests__/use-utm-insights.test.tsx diff --git a/projects/packages/premium-analytics/widgets/authors/__tests__/authors.test.tsx b/projects/packages/premium-analytics/widgets/authors/__tests__/authors.test.tsx index 7f44692d397c..a3cccdf80867 100644 --- a/projects/packages/premium-analytics/widgets/authors/__tests__/authors.test.tsx +++ b/projects/packages/premium-analytics/widgets/authors/__tests__/authors.test.tsx @@ -7,6 +7,7 @@ import { queryClient, } from '@jetpack-premium-analytics/data'; import { render, screen, waitFor } from '@testing-library/react'; +import userEvent from '@testing-library/user-event'; import apiFetch from '@wordpress/api-fetch'; import type { AnchorHTMLAttributes, ReactElement, ReactNode } from 'react'; /** @@ -90,4 +91,46 @@ describe( 'AuthorsWidget', () => { expect.stringContaining( '/reports/authors' ) ); } ); + + it( 'links a drilled-down author post to its detail page', async () => { + const user = userEvent.setup(); + mockApiFetch.mockResolvedValue( { + date: '2026-07-17', + period: 'day', + summary: { + authors: [ + { + author_id: 101, + name: 'Jane Cooper', + views: 20, + posts: [ + { + id: 123, + title: 'Quarterly update', + url: 'https://example.com/quarterly-update/', + views: 20, + }, + ], + }, + ], + }, + } ); + + renderInDashboard( + + ); + + await user.click( await screen.findByRole( 'button', { name: 'View posts by Jane Cooper' } ) ); + + const link = screen.getByRole( 'link', { name: 'Quarterly update' } ); + const url = new URL( link.getAttribute( 'href' ) ?? '', 'https://example.com' ); + + expect( url.pathname ).toBe( '/post/123' ); + expect( url.searchParams.get( 'post_url' ) ).toBe( 'https://example.com/quarterly-update/' ); + } ); } ); diff --git a/projects/packages/premium-analytics/widgets/emails/__tests__/emails.test.tsx b/projects/packages/premium-analytics/widgets/emails/__tests__/emails.test.tsx index 8208007f7341..bcf3669bb520 100644 --- a/projects/packages/premium-analytics/widgets/emails/__tests__/emails.test.tsx +++ b/projects/packages/premium-analytics/widgets/emails/__tests__/emails.test.tsx @@ -1,16 +1,21 @@ /** * External dependencies */ +import { getDefaultQueryParams, queryClient } from '@jetpack-premium-analytics/data'; import { WidgetRoot } from '@jetpack-premium-analytics/widgets-toolkit'; import { render, screen } from '@testing-library/react'; +import apiFetch from '@wordpress/api-fetch'; /** * Internal dependencies */ -import { EmailsLeaderboard, type EmailRow } from '../render'; +import Emails, { EmailsLeaderboard, type EmailRow } from '../render'; import type { EmailMetric } from '../widget'; +jest.mock( '@wordpress/api-fetch', () => jest.fn() ); jest.mock( '@wordpress/route', () => jest.requireActual( '../../test-utils' ).mockWordPressRoute ); +const mockApiFetch = apiFetch as unknown as jest.Mock; + const rows: EmailRow[] = [ { id: 12, @@ -35,6 +40,11 @@ function renderLeaderboard( metric: EmailMetric ) { } describe( 'EmailsLeaderboard', () => { + beforeEach( () => { + queryClient.clear(); + mockApiFetch.mockReset(); + } ); + it.each( [ [ 'opens', 'email-opens' ], [ 'clicks', 'email-clicks' ], @@ -49,4 +59,40 @@ describe( 'EmailsLeaderboard', () => { expect( url.searchParams.get( 'section' ) ).toBe( expectedSection ); expect( url.searchParams.get( 'post_url' ) ).toBe( 'https://example.com/newsletter/' ); } ); + + it( 'carries the report post ID and URL into the rendered detail link', async () => { + mockApiFetch.mockResolvedValue( { + date: '2026-06-30', + posts: [ + { + id: 71, + title: 'API newsletter', + href: 'https://example.com/api-newsletter/', + opens: 30, + clicks: 4, + opens_rate: 30, + clicks_rate: 4, + unique_opens: 24, + unique_clicks: 3, + total_sends: 100, + }, + ], + } ); + + render( + + ); + + const link = await screen.findByRole( 'link', { name: 'API newsletter' } ); + const url = new URL( link.getAttribute( 'href' ) ?? '', 'https://example.com' ); + + expect( url.pathname ).toBe( '/post/71' ); + expect( url.searchParams.get( 'post_url' ) ).toBe( 'https://example.com/api-newsletter/' ); + expect( url.searchParams.get( 'section' ) ).toBe( 'email-opens' ); + } ); } ); diff --git a/projects/packages/premium-analytics/widgets/latest-post/__tests__/latest-post-card.test.tsx b/projects/packages/premium-analytics/widgets/latest-post/__tests__/latest-post-card.test.tsx index 1efa530b34b4..feb6374fa350 100644 --- a/projects/packages/premium-analytics/widgets/latest-post/__tests__/latest-post-card.test.tsx +++ b/projects/packages/premium-analytics/widgets/latest-post/__tests__/latest-post-card.test.tsx @@ -5,11 +5,18 @@ import { render, screen } from '@testing-library/react'; /** * Internal dependencies */ -import { LatestPostCard } from '../render'; -import type { LatestPostWithMetrics } from '../use-latest-post'; +import LatestPost, { LatestPostCard } from '../render'; +import { useLatestPost, type LatestPostWithMetrics } from '../use-latest-post'; jest.mock( '@wordpress/route', () => jest.requireActual( '../../test-utils' ).mockWordPressRoute ); +jest.mock( '../use-latest-post', () => ( { + ...jest.requireActual( '../use-latest-post' ), + useLatestPost: jest.fn(), +} ) ); + +const mockUseLatestPost = useLatestPost as jest.MockedFunction< typeof useLatestPost >; + const post = { id: 12, title: 'Quarterly update', @@ -21,6 +28,39 @@ const post = { } as unknown as LatestPostWithMetrics; describe( 'LatestPostCard', () => { + beforeEach( () => { + mockUseLatestPost.mockReset(); + } ); + + it( 'carries the widget report window into the detail link', () => { + mockUseLatestPost.mockReturnValue( { + post, + isLoading: false, + isFetching: false, + isError: false, + refetch: jest.fn(), + } ); + + render( + + ); + + const link = screen.getByRole( 'link', { name: 'Quarterly update' } ); + const url = new URL( link.getAttribute( 'href' ) ?? '', 'https://example.com' ); + + expect( url.pathname ).toBe( '/post/12' ); + expect( url.searchParams.get( 'from' ) ).toBe( '2026-06-01' ); + expect( url.searchParams.get( 'to' ) ).toBe( '2026-06-30' ); + } ); + it( 'links the title to the post detail page and carries the report window', () => { render( ); diff --git a/projects/packages/premium-analytics/widgets/utm-insights/__tests__/use-utm-insights.test.tsx b/projects/packages/premium-analytics/widgets/utm-insights/__tests__/use-utm-insights.test.tsx new file mode 100644 index 000000000000..d77afe2e50bb --- /dev/null +++ b/projects/packages/premium-analytics/widgets/utm-insights/__tests__/use-utm-insights.test.tsx @@ -0,0 +1,88 @@ +/** + * External dependencies + */ +import { + useStatsUtm, + type ReportParams, + type StatsUtmComparisonItem, +} from '@jetpack-premium-analytics/data'; +import { renderHook } from '@testing-library/react'; +/** + * Internal dependencies + */ +import useUtmInsights from '../use-utm-insights'; + +jest.mock( '@jetpack-premium-analytics/data', () => ( { + useStatsUtm: jest.fn(), +} ) ); + +const mockUseStatsUtm = useStatsUtm as jest.MockedFunction< typeof useStatsUtm >; + +const reportParams = { + from: '2026-06-01', + to: '2026-06-30', + interval: 'day', +} as ReportParams; + +describe( 'useUtmInsights', () => { + beforeEach( () => { + mockUseStatsUtm.mockReset(); + } ); + + it( 'maps a UTM child post ID and URL into the widget drill-down row', () => { + const rows: StatsUtmComparisonItem[] = [ + { + label: 'newsletter / email', + value: 18, + children: [ + { + id: 41, + label: 'Landing page', + value: 12, + href: 'https://example.com/landing/', + page: '/stats/post/41', + actions: [], + children: null, + }, + ], + }, + ]; + + mockUseStatsUtm.mockReturnValue( { + comparisonRows: { rows, hasComparison: false }, + hasComparison: false, + isLoading: false, + isFetching: false, + isError: false, + error: null, + refetch: jest.fn(), + } as never ); + + const { result } = renderHook( () => + useUtmInsights( { + reportParams, + utmParam: 'utm_source,utm_medium', + max: 5, + } ) + ); + + expect( result.current.data ).toEqual( [ + expect.objectContaining( { + children: [ + expect.objectContaining( { + postId: 41, + label: 'Landing page', + href: 'https://example.com/landing/', + } ), + ], + } ), + ] ); + expect( mockUseStatsUtm ).toHaveBeenCalledWith( + expect.objectContaining( { + utmParam: 'utm_source,utm_medium', + max: 5, + } ), + { maxRows: 5 } + ); + } ); +} ); From 4dee7d67900f60ea83a741a2a465d27b641ea508 Mon Sep 17 00:00:00 2001 From: Nikhil Date: Mon, 3 Aug 2026 11:39:21 +0530 Subject: [PATCH 3/5] Premium Analytics: fold post links into the shared leaderboard row Adds a postLink action kind to LeaderboardRow, so post titles reuse the shared row chrome instead of a parallel component. LeaderboardPostLabel now only resolves the report window. The row height variant moves to LeaderboardRow. PostTitleLink renders its router link through the design system link, which supplies the unstyled anchor treatment and the unlayered wp-admin guard. Both component stylesheets are dropped. --- .../changelog/fix-widget-post-detail-links | 2 +- .../__tests__/leaderboard-row.test.tsx | 16 ++++ .../src/components/chart-leaderboard/index.ts | 1 + .../leaderboard-label.module.scss | 9 +++ .../chart-leaderboard/leaderboard-row.tsx | 80 +++++++++++++++---- .../widgets-toolkit/src/components/index.ts | 1 + .../leaderboard-post-label.module.scss | 44 ---------- .../leaderboard-post-label.tsx | 49 ++++-------- .../__tests__/post-title-link.test.tsx | 47 ++++++----- .../post-title-link.module.scss | 21 ----- .../post-title-link/post-title-link.tsx | 35 ++++---- .../packages/widgets-toolkit/src/index.ts | 1 + .../widgets/utm-insights/style.module.css | 5 +- 13 files changed, 159 insertions(+), 152 deletions(-) delete mode 100644 projects/packages/premium-analytics/packages/widgets-toolkit/src/components/leaderboard-post-label/leaderboard-post-label.module.scss delete mode 100644 projects/packages/premium-analytics/packages/widgets-toolkit/src/components/post-title-link/post-title-link.module.scss diff --git a/projects/packages/premium-analytics/changelog/fix-widget-post-detail-links b/projects/packages/premium-analytics/changelog/fix-widget-post-detail-links index 6450cd87dcd1..1358a9952c97 100644 --- a/projects/packages/premium-analytics/changelog/fix-widget-post-detail-links +++ b/projects/packages/premium-analytics/changelog/fix-widget-post-detail-links @@ -1,4 +1,4 @@ Significance: patch Type: fixed -Widgets: link post and email titles to their detail pages instead of showing plain text. +Widgets: link post and email titles to their detail pages in the dashboard. diff --git a/projects/packages/premium-analytics/packages/widgets-toolkit/src/components/chart-leaderboard/__tests__/leaderboard-row.test.tsx b/projects/packages/premium-analytics/packages/widgets-toolkit/src/components/chart-leaderboard/__tests__/leaderboard-row.test.tsx index 08bed827350c..b7f1d04a851f 100644 --- a/projects/packages/premium-analytics/packages/widgets-toolkit/src/components/chart-leaderboard/__tests__/leaderboard-row.test.tsx +++ b/projects/packages/premium-analytics/packages/widgets-toolkit/src/components/chart-leaderboard/__tests__/leaderboard-row.test.tsx @@ -90,6 +90,22 @@ describe( 'buildLeaderboardRow', () => { expect( row ).not.toHaveProperty( 'onClick' ); } ); + it( 'keeps a post link out of the chart button props', () => { + const row = buildLeaderboardRow( { + label: 'Pricing', + media: { kind: 'none' }, + action: { kind: 'postLink', href: 'https://example.com/pricing/' }, + } ); + + render( row.label ); + + expect( screen.getByRole( 'link', { name: /Pricing/ } ) ).toHaveAttribute( + 'href', + 'https://example.com/pricing/' + ); + 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( { diff --git a/projects/packages/premium-analytics/packages/widgets-toolkit/src/components/chart-leaderboard/index.ts b/projects/packages/premium-analytics/packages/widgets-toolkit/src/components/chart-leaderboard/index.ts index cc1d14389301..1cc944420dfa 100644 --- a/projects/packages/premium-analytics/packages/widgets-toolkit/src/components/chart-leaderboard/index.ts +++ b/projects/packages/premium-analytics/packages/widgets-toolkit/src/components/chart-leaderboard/index.ts @@ -17,4 +17,5 @@ export type { LeaderboardRowActionOptions, LeaderboardRowChartProps, LeaderboardRowProps, + LeaderboardRowVariant, } from './leaderboard-row'; diff --git a/projects/packages/premium-analytics/packages/widgets-toolkit/src/components/chart-leaderboard/leaderboard-label.module.scss b/projects/packages/premium-analytics/packages/widgets-toolkit/src/components/chart-leaderboard/leaderboard-label.module.scss index 6fcd18567ab1..cc9db3fe17bf 100644 --- a/projects/packages/premium-analytics/packages/widgets-toolkit/src/components/chart-leaderboard/leaderboard-label.module.scss +++ b/projects/packages/premium-analytics/packages/widgets-toolkit/src/components/chart-leaderboard/leaderboard-label.module.scss @@ -72,6 +72,15 @@ gap: var(--wpds-dimension-gap-xs); } +/* Block padding sets the bar height when the label sits on top of the bar, so + the 36px floor is dropped. Doubled with the base class to beat it on + specificity rather than on stylesheet order. */ +.overlay.row, +.overlay.rowLink { + min-block-size: 0; + padding-block: var(--wpds-dimension-padding-md); +} + .rowLink:hover .label, .rowLink:focus .label { text-decoration: underline; diff --git a/projects/packages/premium-analytics/packages/widgets-toolkit/src/components/chart-leaderboard/leaderboard-row.tsx b/projects/packages/premium-analytics/packages/widgets-toolkit/src/components/chart-leaderboard/leaderboard-row.tsx index 4d10d357c0f3..e4172f333ab3 100644 --- a/projects/packages/premium-analytics/packages/widgets-toolkit/src/components/chart-leaderboard/leaderboard-row.tsx +++ b/projects/packages/premium-analytics/packages/widgets-toolkit/src/components/chart-leaderboard/leaderboard-row.tsx @@ -2,15 +2,27 @@ * External dependencies */ import { Link } from '@jetpack-premium-analytics/externals'; +import clsx from 'clsx'; /** * Internal dependencies */ +import { PostTitleLink } from '../post-title-link'; import { LeaderboardLabel, type LeaderboardRowMedia } from './leaderboard-label'; import styles from './leaderboard-label.module.scss'; import type { MouseEvent, ReactElement } from 'react'; export type LeaderboardRowAction = | { kind: 'link'; href: string } + | { + /** A post, page, or email with a detail page inside the dashboard. */ + kind: 'postLink'; + /** Post or page ID. Rows carrying one link to the internal detail route. */ + 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 >; + } | { kind: 'drillDown'; onClick: ( event: MouseEvent< HTMLButtonElement > ) => void; @@ -22,6 +34,13 @@ export type LeaderboardRowAction = } | { kind: 'static' }; +/** + * How tall the row sits. `compact` is the standard 36px row. `overlay` suits + * leaderboards that draw the label on top of the bar, where block padding sets + * the bar height because the row has no image to size it. + */ +export type LeaderboardRowVariant = 'compact' | 'overlay'; + export type LeaderboardRowActionOptions = { /** An external destination used only when the row has no children. */ href?: string; @@ -38,6 +57,10 @@ export type LeaderboardRowProps = { media: LeaderboardRowMedia; /** The mutually exclusive action applied to this chart row. */ action: LeaderboardRowAction; + /** Row height. Defaults to `compact`. */ + variant?: LeaderboardRowVariant; + /** Extra class for the row, for per-widget spacing. */ + className?: string; }; export type LeaderboardRowChartProps = @@ -75,17 +98,50 @@ export function resolveLeaderboardRowAction( /** * Render the shared leaderboard row chrome around a label. * - * Link actions own the anchor and its new-tab affordance. Drill-down actions - * stay non-interactive here because `LeaderboardChart` turns the whole row - * into a button; `buildLeaderboardRow` passes that action to the chart. + * 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. * - * @param props - Component props. - * @param props.label - Label text. - * @param props.media - Media rendered before the label. - * @param props.action - The row action. + * @param props - Component props. + * @param props.label - Label text. + * @param props.media - Media rendered before the label. + * @param props.action - The row action. + * @param props.variant - Row height. + * @param props.className - Extra class for the row. * @return A single label element accepted by `LeaderboardEntry.label`. */ -export function LeaderboardRow( { label, media, action }: LeaderboardRowProps ): ReactElement { +export function LeaderboardRow( { + label, + media, + action, + variant = 'compact', + className, +}: LeaderboardRowProps ): ReactElement { + const variantClass = variant === 'overlay' ? styles.overlay : undefined; + const rowClassName = clsx( styles.row, variantClass, className ); + const linkClassName = clsx( styles.rowLink, variantClass, className ); + + // Post rows carry no media, so the row chrome goes on the anchor itself. + if ( action.kind === 'postLink' ) { + return ( + + ); + } + const content = ( ); @@ -93,7 +149,7 @@ export function LeaderboardRow( { label, media, action }: LeaderboardRowProps ): if ( action.kind === 'link' ) { return ( + { content } ); @@ -114,10 +170,6 @@ export function LeaderboardRow( { label, media, action }: LeaderboardRowProps ): /** * Build the label and chart-level interaction props for one leaderboard row. * - * Rows whose label is a post, page, or email use `LeaderboardPostLabel` - * instead: a chart row becomes a button and cannot nest an anchor, so a linked - * title cannot be expressed as an action here. - * * @param props - Leaderboard row content and action. * @return Props to spread onto a `LeaderboardEntry`. */ diff --git a/projects/packages/premium-analytics/packages/widgets-toolkit/src/components/index.ts b/projects/packages/premium-analytics/packages/widgets-toolkit/src/components/index.ts index b6f254c0c322..00abc68c8966 100644 --- a/projects/packages/premium-analytics/packages/widgets-toolkit/src/components/index.ts +++ b/projects/packages/premium-analytics/packages/widgets-toolkit/src/components/index.ts @@ -39,6 +39,7 @@ export { type LeaderboardRowChartProps, type LeaderboardRowMedia, type LeaderboardRowProps, + type LeaderboardRowVariant, } from './chart-leaderboard'; export { BarChart, type BarChartProps, type BarChartData, type BarChartStyle } from './chart-bar'; export { ChartEmptyState, type ChartEmptyStateProps } from './chart-empty-state'; diff --git a/projects/packages/premium-analytics/packages/widgets-toolkit/src/components/leaderboard-post-label/leaderboard-post-label.module.scss b/projects/packages/premium-analytics/packages/widgets-toolkit/src/components/leaderboard-post-label/leaderboard-post-label.module.scss deleted file mode 100644 index 24a3f1173b5c..000000000000 --- a/projects/packages/premium-analytics/packages/widgets-toolkit/src/components/leaderboard-post-label/leaderboard-post-label.module.scss +++ /dev/null @@ -1,44 +0,0 @@ -.row { - display: flex; - align-items: center; - gap: var(--wpds-dimension-gap-xs); - min-inline-size: 0; -} - -/* Matches the shared `LeaderboardRow` chrome, so a post label sits at the same - height as the rows around it. */ -.compact { - min-block-size: 36px; - padding-inline: var(--wpds-dimension-padding-sm); -} - -/* Block padding sets the overlay bar height, since these rows have no image to - size them. The inline-start inset keeps the text off the bar's rounded edge: - the chart applies it to its own `.label` in overlay mode, but a custom label - element bypasses that rule. */ -.overlay { - padding-block: var(--wpds-dimension-padding-md); - padding-inline-start: var(--wpds-dimension-padding-sm); -} - -/* `flex: 1 1 auto` keeps the whole row clickable, matching the shared - `LeaderboardRow` link, which fills the row with `inline-size: 100%`. - `min-inline-size: 0` lets it shrink below its content width so the ellipsis - applies. */ -.title { - display: inline-flex; - flex: 1 1 auto; - align-items: center; - gap: var(--wpds-dimension-gap-xs); - min-inline-size: 0; -} - -/* `text-overflow` needs an inline formatting context, which the flex containers - above do not give it, so the ellipsis lives on the text. */ -.text { - min-inline-size: 0; - overflow: hidden; - white-space: nowrap; - text-overflow: ellipsis; - font-size: var(--wpds-typography-font-size-sm); -} diff --git a/projects/packages/premium-analytics/packages/widgets-toolkit/src/components/leaderboard-post-label/leaderboard-post-label.tsx b/projects/packages/premium-analytics/packages/widgets-toolkit/src/components/leaderboard-post-label/leaderboard-post-label.tsx index b9349264609f..d3fb9ccb85f9 100644 --- a/projects/packages/premium-analytics/packages/widgets-toolkit/src/components/leaderboard-post-label/leaderboard-post-label.tsx +++ b/projects/packages/premium-analytics/packages/widgets-toolkit/src/components/leaderboard-post-label/leaderboard-post-label.tsx @@ -2,24 +2,16 @@ * External dependencies */ import { pickReportDateParams } from '@jetpack-premium-analytics/routing'; -import clsx from 'clsx'; import { useMemo } from 'react'; /** * Internal dependencies */ -import { PostTitleLink } from '../post-title-link'; +import { LeaderboardRow, type LeaderboardRowVariant } from '../chart-leaderboard/leaderboard-row'; import { useWidgetRootContext } from '../widget-root'; -import styles from './leaderboard-post-label.module.scss'; import type { ReactElement } from 'react'; -/** - * How tall the row sits. - * - * `compact` matches the shared `LeaderboardRow` chrome, so post labels line up - * with the rows around them. `overlay` keeps the taller block padding the - * older overlay-bar leaderboards render at. - */ -export type LeaderboardPostLabelVariant = 'compact' | 'overlay'; +/** How tall the row sits. */ +export type LeaderboardPostLabelVariant = LeaderboardRowVariant; export type LeaderboardPostLabelProps = { /** @@ -51,14 +43,11 @@ export type LeaderboardPostLabelProps = { /** * A leaderboard row label for a post, page, or email. * - * Wraps `PostTitleLink` in the row chrome every leaderboard needs: a flex row - * that keeps the title on one line with an ellipsis and leaves the trailing - * external-link icon room. Widgets pass no classes for this — only the - * `variant`, plus a `className` when they need extra spacing. - * - * The report window comes from `WidgetRootContext`, the same way `ReportLink` - * resolves it, so the detail page opens on the range the row was read against - * without every widget threading it down. + * `LeaderboardRow` renders the row and its `postLink` action; this component + * exists only to resolve the report window. That window comes from + * `WidgetRootContext`, the same way `ReportLink` resolves it, so the detail + * page opens on the range the row was read against without every widget + * threading it down. * * Rows that are not linked entities — an avatar and a name, or a drill-down * into child rows — use `buildLeaderboardRow` instead. @@ -90,20 +79,12 @@ export function LeaderboardPostLabel( { ); return ( - - - + ); } diff --git a/projects/packages/premium-analytics/packages/widgets-toolkit/src/components/post-title-link/__tests__/post-title-link.test.tsx b/projects/packages/premium-analytics/packages/widgets-toolkit/src/components/post-title-link/__tests__/post-title-link.test.tsx index 569f8a922309..afc24178a8e9 100644 --- a/projects/packages/premium-analytics/packages/widgets-toolkit/src/components/post-title-link/__tests__/post-title-link.test.tsx +++ b/projects/packages/premium-analytics/packages/widgets-toolkit/src/components/post-title-link/__tests__/post-title-link.test.tsx @@ -15,27 +15,34 @@ type MockRouteLinkProps = { children: ReactNode; } & Omit< AnchorHTMLAttributes< HTMLAnchorElement >, 'href' >; -jest.mock( '@wordpress/route', () => ( { - Link: ( { to, params, search, children, ...props }: MockRouteLinkProps ) => { - 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(); +// `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 ( - - { children } - - ); - }, -} ) ); + 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 ( + + { children } + + ); + } + ), + }; +} ); describe( 'PostTitleLink', () => { it( 'routes a row with a post ID to the detail page, carrying the report window', () => { diff --git a/projects/packages/premium-analytics/packages/widgets-toolkit/src/components/post-title-link/post-title-link.module.scss b/projects/packages/premium-analytics/packages/widgets-toolkit/src/components/post-title-link/post-title-link.module.scss deleted file mode 100644 index 520856e53652..000000000000 --- a/projects/packages/premium-analytics/packages/widgets-toolkit/src/components/post-title-link/post-title-link.module.scss +++ /dev/null @@ -1,21 +0,0 @@ -/* Defaults every caller needs. Layout (single-line ellipsis, flex rows) is not - here: `latest-post` clamps its title to three lines, so an `inline-flex` - anchor would break it. Leaderboards get that layer from - `LeaderboardPostLabel`. - - These must stay plain classes. wp-admin colours bare anchors with an element - selector, unlayered, and this package's styles are unlayered too — so a - zero-specificity `:where()` would lose to it and every link would render - admin blue in product while Storybook and Jest, which load no wp-admin CSS, - looked correct. A caller that needs to win a tie against these should use - `:any-link`, as `routes/post-detail/stage.module.scss` does. */ - -.link { - color: inherit; - text-decoration: none; -} - -.link:hover, -.link:focus { - text-decoration: underline; -} diff --git a/projects/packages/premium-analytics/packages/widgets-toolkit/src/components/post-title-link/post-title-link.tsx b/projects/packages/premium-analytics/packages/widgets-toolkit/src/components/post-title-link/post-title-link.tsx index 41dffe051f2e..7ec5a7a691b2 100644 --- a/projects/packages/premium-analytics/packages/widgets-toolkit/src/components/post-title-link/post-title-link.tsx +++ b/projects/packages/premium-analytics/packages/widgets-toolkit/src/components/post-title-link/post-title-link.tsx @@ -4,11 +4,6 @@ import { Link as UiLink } from '@jetpack-premium-analytics/externals'; import { safeHttpUrl } from '@jetpack-premium-analytics/ui'; import { Link } from '@wordpress/route'; -import clsx from 'clsx'; -/** - * Internal dependencies - */ -import styles from './post-title-link.module.scss'; /** * Route search param carrying a row's public URL to the post detail page. @@ -44,9 +39,8 @@ export type PostTitleLinkProps = { search?: Record< string, unknown >; /** - * Optional classes for each rendering branch, applied on top of the - * component's own defaults. `text` applies to the label span in every - * branch, so one rule can ellipsize the title everywhere. + * Optional classes for each rendering branch. `text` applies to the label + * span in every branch, so one rule can ellipsize the title everywhere. */ classNames?: { internal?: string; @@ -98,18 +92,25 @@ export function PostTitleLink( { const href = safeHttpUrl( link ); if ( Number.isInteger( postId ) && postId > 0 ) { + // `UiLink` renders the router link so the anchor keeps the design + // system's unlayered guard, without which wp-admin repaints it blue. return ( - + } > { text } - + ); } @@ -118,7 +119,7 @@ export function PostTitleLink( { // carries the same arrow as every other external link in the dashboard. return ( Date: Mon, 3 Aug 2026 13:04:49 +0530 Subject: [PATCH 4/5] Premium Analytics: link Most commented posts rows to the detail page Trunk split the Comments widget into two, which dropped this branch's change to the posts view. Ports it onto most-commented-posts: rows render through LeaderboardPostLabel, so a row with a post ID opens the detail page and only a row without one falls back to the permalink. --- .../__tests__/most-commented-posts.test.tsx | 23 ++++++++++++--- .../widgets/most-commented-posts/render.tsx | 29 ++++++------------- 2 files changed, 28 insertions(+), 24 deletions(-) diff --git a/projects/packages/premium-analytics/widgets/most-commented-posts/__tests__/most-commented-posts.test.tsx b/projects/packages/premium-analytics/widgets/most-commented-posts/__tests__/most-commented-posts.test.tsx index 1614f6d8cd00..1bb66783b183 100644 --- a/projects/packages/premium-analytics/widgets/most-commented-posts/__tests__/most-commented-posts.test.tsx +++ b/projects/packages/premium-analytics/widgets/most-commented-posts/__tests__/most-commented-posts.test.tsx @@ -23,7 +23,11 @@ const posts = [ link: 'https://example.com/hello-world/', }, { - id: 43, + name: 'Untracked page', + comments: 8, + link: 'https://example.com/untracked/', + }, + { name: 'Unsafe permalink', comments: 5, link: 'javascript:alert(1)', @@ -54,11 +58,22 @@ describe( 'MostCommentedPostsWidget', () => { ); } - it( 'links a post to its permalink in a new tab', async () => { + it( 'links a post to its detail page, carrying the permalink along', async () => { + renderWidget(); + + const link = await screen.findByRole( 'link', { name: 'Hello world' } ); + const url = new URL( link.getAttribute( 'href' ) ?? '', 'https://example.com' ); + + expect( url.pathname ).toBe( '/post/42' ); + expect( url.searchParams.get( 'post_url' ) ).toBe( 'https://example.com/hello-world/' ); + expect( link ).not.toHaveAttribute( 'target', '_blank' ); + } ); + + it( 'falls back to the permalink in a new tab when a post has no ID', async () => { renderWidget(); - const link = await screen.findByRole( 'link', { name: /Hello world/ } ); - expect( link ).toHaveAttribute( 'href', 'https://example.com/hello-world/' ); + const link = await screen.findByRole( 'link', { name: /Untracked page/ } ); + expect( link ).toHaveAttribute( 'href', 'https://example.com/untracked/' ); expect( link ).toHaveAttribute( 'target', '_blank' ); } ); diff --git a/projects/packages/premium-analytics/widgets/most-commented-posts/render.tsx b/projects/packages/premium-analytics/widgets/most-commented-posts/render.tsx index b4b7e71bd553..62caedeaaf7b 100644 --- a/projects/packages/premium-analytics/widgets/most-commented-posts/render.tsx +++ b/projects/packages/premium-analytics/widgets/most-commented-posts/render.tsx @@ -4,13 +4,12 @@ import { useStatsCommentsRows } from '@jetpack-premium-analytics/data'; import { LeaderboardChart, + LeaderboardPostLabel, ReportLink, WidgetFooter, WidgetRoot, WidgetState, - buildLeaderboardRow, describeError, - safeHttpUrl, sharePercentage, toMaxRows, type LeaderboardChartData, @@ -59,22 +58,12 @@ function MostCommentedPostsInner( { max }: MostCommentedPostsInnerProps ) { const leaderboardData = useMemo< LeaderboardChartData >( () => { const maxValue = Math.max( ...rows.map( row => row.value ), 0 ); - return rows.map( row => { - // Post permalinks come from report data, so validate the scheme before - // the row becomes a link. - const href = safeHttpUrl( row.link ); - - return { - id: row.id, - ...buildLeaderboardRow( { - label: row.label, - media: { kind: 'none' }, - action: href ? { kind: 'link', href } : { kind: 'static' }, - } ), - currentValue: row.value, - currentShare: sharePercentage( row.value, maxValue ), - }; - } ); + return rows.map( row => ( { + id: row.id, + label: , + currentValue: row.value, + currentShare: sharePercentage( row.value, maxValue ), + } ) ); }, [ rows ] ); return ( @@ -121,8 +110,8 @@ function MostCommentedPostsInner( { max }: MostCommentedPostsInnerProps ) { /** * Most commented posts widget: the posts and pages that receive the most - * comments, ranked by comment count. Each row links to the published post when - * the report reports a permalink for it. + * comments, ranked by comment count. Each row opens the post detail page, and + * falls back to the published post when the report carries no post ID. * * One half of the Jetpack Stats "Comments" module; `jpa/most-commented-authors` * covers the other. Both read the same `stats/comments` response through From cd017e56984efe306ba3b7f1c9a3f1c8eef70f21 Mon Sep 17 00:00:00 2001 From: Nikhil Date: Mon, 3 Aug 2026 14:36:10 +0530 Subject: [PATCH 5/5] Premium Analytics: document the leaderboard postLink row Covers the new postLink action kind, LeaderboardPostLabel as the widget-level entry point, and the variant and className row props. States that the variant follows the sibling rows in the widget, not the chart's withOverlayLabel prop, which only tints the bar fill. --- .../components/chart-leaderboard/README.md | 50 +++++++++++++++++++ 1 file changed, 50 insertions(+) diff --git a/projects/packages/premium-analytics/packages/widgets-toolkit/src/components/chart-leaderboard/README.md b/projects/packages/premium-analytics/packages/widgets-toolkit/src/components/chart-leaderboard/README.md index 7e9cccec370b..05c72ecce185 100644 --- a/projects/packages/premium-analytics/packages/widgets-toolkit/src/components/chart-leaderboard/README.md +++ b/projects/packages/premium-analytics/packages/widgets-toolkit/src/components/chart-leaderboard/README.md @@ -117,6 +117,41 @@ An explicit drill-down `ariaLabel` replaces the accessible name otherwise comput the media alt text and visible label, which can cause a screen reader to announce the label twice. +For a post, page, or email with a detail page inside the dashboard, use the `postLink` action. +`PostTitleLink` chooses the destination: the internal detail route when the row carries a post +ID, the public URL when it does not, and plain text when neither is usable. + +```tsx +const row = { + id: 'post-41', + ...buildLeaderboardRow( { + label: 'Hello world', + media: { kind: 'none' }, + action: { + kind: 'postLink', + id: 41, + href: 'https://example.com/hello-world/', + search: { from: '2026-03-01', to: '2026-03-10' }, + }, + } ), + currentValue: 100, + currentShare: 100, +}; +``` + +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 +the range the row was read against: + +```tsx + +``` + +Pass `section` to open a named tab on the detail page, such as `email-opens`. + `LeaderboardRowMedia` provides five semantic media variants. The variant owns its size, fallback, and default alt-text policy: @@ -135,6 +170,21 @@ childless rows, and static content otherwise. Use `LeaderboardLabel` directly for media plus truncating text outside chart rows, such as a DataViews table cell. It deliberately does not add the chart row's 36px minimum block size. +### Row layout + +`LeaderboardRow` takes two optional layout props. `LeaderboardPostLabel` accepts both and +forwards them. + +| Prop | Default | Description | +| ----------- | ----------- | ----------------------------------------------------------------------------------------------------------- | +| `variant` | `'compact'` | `'compact'` is the standard 36px row. `'overlay'` drops that floor and takes its height from block padding. | +| `className` | - | Extra class on the row, for per-widget spacing. | + +Pick `variant` to match the sibling rows in the same widget, not the chart's `withOverlayLabel` +prop. That prop only tints the bar fill; it sets no row height. Use `'overlay'` where the +neighbouring rows also take their height from block padding, and `'compact'` where they come +from `buildLeaderboardRow`. + ## Props | Prop | Type | Default | Description |