From 5cd63f0753d3a7f8a92fba89109f4804e152c039 Mon Sep 17 00:00:00 2001 From: Jasper Kang Date: Fri, 14 Aug 2026 15:52:17 +1200 Subject: [PATCH 1/7] Premium Analytics: add Size to the Top platforms "View by" control MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit The widget exposed two of the three properties stats/devices/{property} serves — browser and platform — so the screen-size breakdown was unreachable from it. Size needs its own formatting: WPCOM special-cases screensize and returns percentage shares, while browser and platform return view counts. The leaderboard prints the two units accordingly; bar widths stay relative to the largest visible value either way. Also drop client_type from StatsDeviceProperty. It is not one of the three properties the endpoint accepts, so a request naming it is rejected with a 400 before any query runs. Nothing called it. --- .../add-wooa7s-1940-top-platforms-size | 4 + .../data/src/queries/stats-devices-query.ts | 4 +- .../src/stories/mocks/register-stats-mocks.ts | 2 +- .../__tests__/top-platforms.test.tsx | 89 +++++++++++++++++++ .../widgets/top-platforms/render.tsx | 51 ++++++++--- .../stories/top-platforms-widget.stories.tsx | 13 ++- .../top-platforms/use-platform-views.ts | 25 +++++- .../widgets/top-platforms/widget.ts | 18 ++-- 8 files changed, 181 insertions(+), 25 deletions(-) create mode 100644 projects/packages/premium-analytics/changelog/add-wooa7s-1940-top-platforms-size create mode 100644 projects/packages/premium-analytics/widgets/top-platforms/__tests__/top-platforms.test.tsx diff --git a/projects/packages/premium-analytics/changelog/add-wooa7s-1940-top-platforms-size b/projects/packages/premium-analytics/changelog/add-wooa7s-1940-top-platforms-size new file mode 100644 index 000000000000..eb007957db89 --- /dev/null +++ b/projects/packages/premium-analytics/changelog/add-wooa7s-1940-top-platforms-size @@ -0,0 +1,4 @@ +Significance: minor +Type: added + +Top platforms: offer Size alongside Browser and OS in the widget's "View by" control. diff --git a/projects/packages/premium-analytics/packages/data/src/queries/stats-devices-query.ts b/projects/packages/premium-analytics/packages/data/src/queries/stats-devices-query.ts index a2fb2cc779e1..0dd004cbff58 100644 --- a/projects/packages/premium-analytics/packages/data/src/queries/stats-devices-query.ts +++ b/projects/packages/premium-analytics/packages/data/src/queries/stats-devices-query.ts @@ -3,7 +3,9 @@ */ import { statsReportQuery, type StatsReportParams } from './stats-query'; -export type StatsDeviceProperty = 'screensize' | 'browser' | 'platform' | 'client_type'; +// The only three properties `stats/devices/{property}` accepts; anything else +// is rejected with a 400 before the query runs. +export type StatsDeviceProperty = 'screensize' | 'browser' | 'platform'; export const statsDevicesQuery = ( params: StatsReportParams & { deviceProperty?: StatsDeviceProperty } diff --git a/projects/packages/premium-analytics/packages/widgets-toolkit/src/stories/mocks/register-stats-mocks.ts b/projects/packages/premium-analytics/packages/widgets-toolkit/src/stories/mocks/register-stats-mocks.ts index dff09b6a89ea..185aae6e3836 100644 --- a/projects/packages/premium-analytics/packages/widgets-toolkit/src/stories/mocks/register-stats-mocks.ts +++ b/projects/packages/premium-analytics/packages/widgets-toolkit/src/stories/mocks/register-stats-mocks.ts @@ -1191,7 +1191,7 @@ export function getStatsMock( path: string ): unknown | null { if ( subPath.startsWith( '/devices/browser' ) ) { return isComparison ? MOCK_DEVICES_BROWSER_COMPARISON : MOCK_DEVICES_BROWSER; } - if ( subPath.startsWith( '/devices/client_type' ) || subPath.startsWith( '/devices/platform' ) ) { + if ( subPath.startsWith( '/devices/platform' ) ) { return isComparison ? MOCK_DEVICES_PLATFORM_COMPARISON : MOCK_DEVICES_PLATFORM; } diff --git a/projects/packages/premium-analytics/widgets/top-platforms/__tests__/top-platforms.test.tsx b/projects/packages/premium-analytics/widgets/top-platforms/__tests__/top-platforms.test.tsx new file mode 100644 index 000000000000..ffc12fa1aa2e --- /dev/null +++ b/projects/packages/premium-analytics/widgets/top-platforms/__tests__/top-platforms.test.tsx @@ -0,0 +1,89 @@ +/** + * External dependencies + */ +import { render, screen } from '@testing-library/react'; +/** + * Internal dependencies + */ +import TopPlatformsWidget from '../render'; + +// WidgetRoot reads URL search params as a fallback for report params; outside +// a matched route the real hook warns and throws. +jest.mock( '@wordpress/route', () => jest.requireActual( '../../test-utils' ).mockWordPressRoute ); + +const mockUsePlatformViews = jest.fn(); + +jest.mock( '../use-platform-views', () => ( { + __esModule: true, + default: ( ...args: unknown[] ) => mockUsePlatformViews( ...( args as [] ) ), +} ) ); + +function stateWith( rows: { key: string; label: string; views: number }[] ) { + return { + data: rows, + hasComparison: false, + isLoading: false, + isFetching: false, + isError: false, + error: null, + refetch: () => {}, + }; +} + +describe( 'TopPlatformsWidget', () => { + beforeEach( () => { + mockUsePlatformViews.mockReset(); + mockUsePlatformViews.mockReturnValue( stateWith( [] ) ); + } ); + + it.each( [ [ undefined, 'browser' ], [ 'screensize' ], [ 'browser' ], [ 'platform' ] ] as const )( + 'requests the %s device property', + ( platformDimension, expected = platformDimension ) => { + render( + + ); + + expect( mockUsePlatformViews ).toHaveBeenLastCalledWith( + expect.objectContaining( { deviceProperty: expected } ) + ); + } + ); + + // A stale layout can name a dimension the widget no longer knows; unchecked it + // becomes the endpoint path segment, which WPCOM rejects with a 400. + it( 'falls back to Browser for a dimension outside the supported set', () => { + render( + + ); + + expect( mockUsePlatformViews ).toHaveBeenLastCalledWith( + expect.objectContaining( { deviceProperty: 'browser' } ) + ); + } ); + + // WPCOM returns `screensize` as percentage shares and the other two as view + // counts, so the same leaderboard has to print two different units. + it( 'prints Size rows as percentages', () => { + mockUsePlatformViews.mockReturnValue( + stateWith( [ { key: 'desktop', label: 'Desktop', views: 57.8 } ] ) + ); + + render( ); + + expect( screen.getByText( '57.8%' ) ).toBeInTheDocument(); + } ); + + it( 'prints Browser rows as counts', () => { + mockUsePlatformViews.mockReturnValue( + stateWith( [ { key: 'chrome', label: 'Chrome', views: 812 } ] ) + ); + + render( ); + + expect( screen.getByText( '812' ) ).toBeInTheDocument(); + } ); +} ); diff --git a/projects/packages/premium-analytics/widgets/top-platforms/render.tsx b/projects/packages/premium-analytics/widgets/top-platforms/render.tsx index ad7e16e3c7fd..f4673ea37ecf 100644 --- a/projects/packages/premium-analytics/widgets/top-platforms/render.tsx +++ b/projects/packages/premium-analytics/widgets/top-platforms/render.tsx @@ -23,7 +23,7 @@ import { * Internal dependencies */ import styles from './style.module.css'; -import usePlatformViews from './use-platform-views'; +import usePlatformViews, { type PlatformDimension } from './use-platform-views'; import { type TopPlatformsAttributes } from './widget'; /** * Types @@ -33,9 +33,24 @@ import type { WidgetRenderProps } from '@wordpress/widget-primitives'; type TopPlatformsRenderAttributes = TopPlatformsAttributes & Partial< ReportParamsFieldAttributes >; type TopPlatformsWidgetProps = WidgetRenderProps< TopPlatformsRenderAttributes >; -const DATA_FORMAT = { type: 'number' as const, options: { useMultipliers: true, decimals: 0 } }; +const COUNT_DATA_FORMAT = { + type: 'number' as const, + options: { useMultipliers: true, decimals: 0 }, +}; +// WPCOM returns `screensize` as percentage shares rather than view counts, and +// the shared percentage formatter takes a 0-1 ratio. +const PERCENTAGE_DATA_FORMAT = { + type: 'percentage' as const, + options: { decimals: 1, signDisplay: 'auto' as const }, +}; -type PlatformMode = 'browser' | 'platform'; +type PlatformMode = PlatformDimension; + +const SUPPORTED_DIMENSIONS: Record< PlatformMode, true > = { + screensize: true, + browser: true, + platform: true, +}; type TopPlatformsInnerProps = { /** @@ -43,7 +58,7 @@ type TopPlatformsInnerProps = { */ max: number; /** - * Device dimension to rank: browsers or operating systems. + * Device dimension to rank: screen sizes, browsers, or operating systems. */ platformDimension: PlatformMode; }; @@ -59,6 +74,11 @@ function TopPlatformsInner( { max, platformDimension }: TopPlatformsInnerProps ) } ); + const isShare = platformDimension === 'screensize'; + // Bar widths stay relative to the largest visible value either way; only the + // number printed on the row changes unit. + const toDisplayValue = ( value: number ) => ( isShare ? value / 100 : value ); + const maxViews = getCombinedPeriodMax( data.map( item => item.views ), hasComparison ? data.map( item => item.previousViews ) : [] @@ -73,9 +93,9 @@ function TopPlatformsInner( { max, platformDimension }: TopPlatformsInnerProps ) { item.label } ), - currentValue: item.views, + currentValue: toDisplayValue( item.views ), currentShare: sharePercentage( item.views, maxViews ), - previousValue, + previousValue: previousValue === undefined ? undefined : toDisplayValue( previousValue ), previousShare: hasComparison && previousValue !== undefined ? sharePercentage( previousValue, maxViews ) @@ -111,7 +131,7 @@ function TopPlatformsInner( { max, platformDimension }: TopPlatformsInnerProps ) withComparison={ hasComparison } withOverlayLabel showLegend={ false } - dataFormat={ DATA_FORMAT } + dataFormat={ isShare ? PERCENTAGE_DATA_FORMAT : COUNT_DATA_FORMAT } /> @@ -119,13 +139,22 @@ function TopPlatformsInner( { max, platformDimension }: TopPlatformsInnerProps ) } /** - * Browser or OS breakdown as a ranked leaderboard. The active dimension is the - * `platformDimension` attribute (`relevance: 'high'`), exposed as a control by - * the widget host. + * Screen size, browser, or OS breakdown as a ranked leaderboard. The active + * dimension is the `platformDimension` attribute (`relevance: 'high'`), exposed + * as a control by the widget host. */ export default function TopPlatformsWidget( { attributes }: TopPlatformsWidgetProps ) { const max = attributes?.max ?? 10; - const platformDimension = attributes?.platformDimension ?? 'browser'; + // Attributes are persisted, so a stale layout can name a dimension this + // widget no longer knows. Unchecked it becomes the `stats/devices/{property}` + // path segment, which WPCOM rejects with a 400. + const storedDimension = attributes?.platformDimension ?? 'browser'; + const platformDimension = Object.prototype.hasOwnProperty.call( + SUPPORTED_DIMENSIONS, + storedDimension + ) + ? storedDimension + : 'browser'; return ( diff --git a/projects/packages/premium-analytics/widgets/top-platforms/stories/top-platforms-widget.stories.tsx b/projects/packages/premium-analytics/widgets/top-platforms/stories/top-platforms-widget.stories.tsx index 2ab6c19ec79a..e6f41d78282f 100644 --- a/projects/packages/premium-analytics/widgets/top-platforms/stories/top-platforms-widget.stories.tsx +++ b/projects/packages/premium-analytics/widgets/top-platforms/stories/top-platforms-widget.stories.tsx @@ -97,7 +97,7 @@ const meta = { }, platformDimension: { control: 'radio', - options: [ 'browser', 'platform' ], + options: [ 'screensize', 'browser', 'platform' ], description: 'The "View by" toolbar attribute rendered by the widget host.', }, }, @@ -105,7 +105,7 @@ const meta = { docs: { description: { component: - 'The "Top Platforms" widget. Shows browser and OS breakdown as a ranked leaderboard. The active dimension is the `platformDimension` attribute (`relevance: \'high\'`), exposed as a control by the widget host.', + 'The "Top Platforms" widget. Shows the screen size, browser, and OS breakdowns as a ranked leaderboard. The active dimension is the `platformDimension` attribute (`relevance: \'high\'`), exposed as a control by the widget host. Screen size is returned by WordPress.com as percentage shares, so it is formatted as a percentage rather than a view count.', }, }, }, @@ -127,6 +127,13 @@ export const WithComparison: StoryObj< TopPlatformsStoryControls > = { decorators: [ withWidgetCanvas ], }; +// Size view — screen sizes, the one dimension returned as percentage shares. +export const BySize: StoryObj< TopPlatformsStoryControls > = { + render: renderTopPlatformsWidget, + args: { withComparison: false, platformDimension: 'screensize' }, + decorators: [ withWidgetCanvas ], +}; + // OS view — the `platformDimension` attribute set to operating systems. export const ByOS: StoryObj< TopPlatformsStoryControls > = { render: renderTopPlatformsWidget, @@ -208,7 +215,7 @@ export const WidgetDashboardWithWidget: DashboardStory = { }, platformDimension: { control: 'radio', - options: [ 'browser', 'platform' ], + options: [ 'screensize', 'browser', 'platform' ], description: 'The "View by" toolbar attribute rendered by the widget host.', }, }, diff --git a/projects/packages/premium-analytics/widgets/top-platforms/use-platform-views.ts b/projects/packages/premium-analytics/widgets/top-platforms/use-platform-views.ts index 10a23f8da446..cb572cdd3f28 100644 --- a/projects/packages/premium-analytics/widgets/top-platforms/use-platform-views.ts +++ b/projects/packages/premium-analytics/widgets/top-platforms/use-platform-views.ts @@ -9,6 +9,8 @@ import { useStatsDevices } from '@jetpack-premium-analytics/data'; import { formatDisplayLabel } from '@jetpack-premium-analytics/widgets-toolkit'; import type { ReportParams, StatsDevicesComparisonItem } from '@jetpack-premium-analytics/data'; +export type PlatformDimension = 'screensize' | 'browser' | 'platform'; + export interface PlatformView { key: string; label: string; @@ -26,9 +28,9 @@ interface UsePlatformViewsArgs { */ max: number; /** - * 'browser' or 'platform' (OS). + * 'screensize' (Size), 'browser', or 'platform' (OS). */ - deviceProperty: 'browser' | 'platform'; + deviceProperty: PlatformDimension; } interface PlatformViewsState { @@ -54,6 +56,15 @@ const BROWSER_LABELS: Record< string, string > = { other: __( 'Other', 'jetpack-premium-analytics-pkg' ), }; +const SCREENSIZE_LABELS: Record< string, string > = { + desktop: __( 'Desktop', 'jetpack-premium-analytics-pkg' ), + mobile: __( 'Mobile', 'jetpack-premium-analytics-pkg' ), + tablet: __( 'Tablet', 'jetpack-premium-analytics-pkg' ), + phone: __( 'Phone', 'jetpack-premium-analytics-pkg' ), + other: __( 'Other', 'jetpack-premium-analytics-pkg' ), + unknown: __( 'Unknown', 'jetpack-premium-analytics-pkg' ), +}; + const PLATFORM_LABELS: Record< string, string > = { windows: __( 'Windows', 'jetpack-premium-analytics-pkg' ), mac: __( 'macOS', 'jetpack-premium-analytics-pkg' ), @@ -69,12 +80,18 @@ const PLATFORM_LABELS: Record< string, string > = { other: __( 'Other', 'jetpack-premium-analytics-pkg' ), }; +const LABELS_BY_DIMENSION: Record< PlatformDimension, Record< string, string > > = { + screensize: SCREENSIZE_LABELS, + browser: BROWSER_LABELS, + platform: PLATFORM_LABELS, +}; + function toPlatformView( item: StatsDevicesComparisonItem, - deviceProperty: 'browser' | 'platform' + deviceProperty: PlatformDimension ): PlatformView { const key = String( item.label ?? '' ); - const labels = deviceProperty === 'browser' ? BROWSER_LABELS : PLATFORM_LABELS; + const labels = LABELS_BY_DIMENSION[ deviceProperty ]; return { key, diff --git a/projects/packages/premium-analytics/widgets/top-platforms/widget.ts b/projects/packages/premium-analytics/widgets/top-platforms/widget.ts index 27b1bea68dc2..633103c0d2df 100644 --- a/projects/packages/premium-analytics/widgets/top-platforms/widget.ts +++ b/projects/packages/premium-analytics/widgets/top-platforms/widget.ts @@ -16,17 +16,21 @@ export type TopPlatformsAttributes = { */ max?: number; /** - * Device dimension to rank: browsers or operating systems. + * Device dimension to rank: screen sizes, browsers, or operating systems. */ - platformDimension?: 'browser' | 'platform'; + platformDimension?: 'screensize' | 'browser' | 'platform'; }; /** * Top Platforms widget type definition. * - * Shows Browser and OS breakdown as a ranked leaderboard. The active - * dimension is the `platformDimension` attribute (`relevance: 'high'`), - * so the widget host renders its control. + * Shows the Size, Browser, and OS breakdowns as a ranked leaderboard — the + * three properties `stats/devices/{property}` exposes. The active dimension is + * the `platformDimension` attribute (`relevance: 'high'`), so the widget host + * renders its control. + * + * Size is the odd one out: WPCOM returns it as percentage shares while the + * other two are view counts, so it is formatted as a percentage. */ export default { icon: desktop, @@ -42,6 +46,10 @@ export default { type: 'text', Edit: SelectField, elements: [ + { + label: __( 'Size', 'jetpack-premium-analytics-pkg' ), + value: 'screensize', + }, { label: __( 'Browser', 'jetpack-premium-analytics-pkg' ), value: 'browser', From f7f8c3ab71348450f9b76d9876504c422b33fcd2 Mon Sep 17 00:00:00 2001 From: Jasper Kang Date: Fri, 14 Aug 2026 15:59:14 +1200 Subject: [PATCH 2/7] Address review: describe all three dimensions in the widget metadata widget.json is the registered widget's catalog and help copy, and it still described only browsers and operating systems. --- .../premium-analytics/widgets/top-platforms/widget.json | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/projects/packages/premium-analytics/widgets/top-platforms/widget.json b/projects/packages/premium-analytics/widgets/top-platforms/widget.json index 9ee7c10b84f6..fab553d443ed 100644 --- a/projects/packages/premium-analytics/widgets/top-platforms/widget.json +++ b/projects/packages/premium-analytics/widgets/top-platforms/widget.json @@ -1,9 +1,9 @@ { "name": "jpa/top-platforms", "title": "Top platforms", - "description": "Top browsers and operating systems your visitors use.", + "description": "Top screen sizes, browsers, and operating systems your visitors use.", "help": { - "content": "A breakdown of the operating systems and browsers your visitors used, sorted by views.", + "content": "A breakdown of the screen sizes, browsers, and operating systems your visitors used. Screen sizes are shown as a share of all views; browsers and operating systems are sorted by views.", "links": [ { "label": "Learn more", From 80b9db05439ce98727e760c76a37ae21b5bddfb0 Mon Sep 17 00:00:00 2001 From: Jasper Kang Date: Fri, 14 Aug 2026 16:08:36 +1200 Subject: [PATCH 3/7] Address review: keep Browser as the first offered dimension SelectField renders the first element when the attribute is unset, so listing Size first made an unconfigured widget label itself "Size" while still fetching browser data. Size moves to the end, matching the render default, and a test pins the first element to the default so the two cannot drift. --- .../__tests__/top-platforms.test.tsx | 15 +++++++++++++++ .../stories/top-platforms-widget.stories.tsx | 4 ++-- .../widgets/top-platforms/widget.ts | 10 ++++++---- 3 files changed, 23 insertions(+), 6 deletions(-) diff --git a/projects/packages/premium-analytics/widgets/top-platforms/__tests__/top-platforms.test.tsx b/projects/packages/premium-analytics/widgets/top-platforms/__tests__/top-platforms.test.tsx index ffc12fa1aa2e..ea5c5c40ac54 100644 --- a/projects/packages/premium-analytics/widgets/top-platforms/__tests__/top-platforms.test.tsx +++ b/projects/packages/premium-analytics/widgets/top-platforms/__tests__/top-platforms.test.tsx @@ -6,6 +6,7 @@ import { render, screen } from '@testing-library/react'; * Internal dependencies */ import TopPlatformsWidget from '../render'; +import widgetDefinition from '../widget'; // WidgetRoot reads URL search params as a fallback for report params; outside // a matched route the real hook warns and throws. @@ -49,6 +50,20 @@ describe( 'TopPlatformsWidget', () => { } ); + // `SelectField` renders the first element when the attribute is unset, so the + // control would otherwise name a dimension the widget is not fetching. + it( 'defaults to the first offered dimension', () => { + const firstElement = widgetDefinition.attributes.find( + field => field.id === 'platformDimension' + )?.elements?.[ 0 ]; + + render( ); + + expect( mockUsePlatformViews ).toHaveBeenLastCalledWith( + expect.objectContaining( { deviceProperty: firstElement?.value } ) + ); + } ); + // A stale layout can name a dimension the widget no longer knows; unchecked it // becomes the endpoint path segment, which WPCOM rejects with a 400. it( 'falls back to Browser for a dimension outside the supported set', () => { diff --git a/projects/packages/premium-analytics/widgets/top-platforms/stories/top-platforms-widget.stories.tsx b/projects/packages/premium-analytics/widgets/top-platforms/stories/top-platforms-widget.stories.tsx index e6f41d78282f..95808c871cc8 100644 --- a/projects/packages/premium-analytics/widgets/top-platforms/stories/top-platforms-widget.stories.tsx +++ b/projects/packages/premium-analytics/widgets/top-platforms/stories/top-platforms-widget.stories.tsx @@ -97,7 +97,7 @@ const meta = { }, platformDimension: { control: 'radio', - options: [ 'screensize', 'browser', 'platform' ], + options: [ 'browser', 'platform', 'screensize' ], description: 'The "View by" toolbar attribute rendered by the widget host.', }, }, @@ -215,7 +215,7 @@ export const WidgetDashboardWithWidget: DashboardStory = { }, platformDimension: { control: 'radio', - options: [ 'screensize', 'browser', 'platform' ], + options: [ 'browser', 'platform', 'screensize' ], description: 'The "View by" toolbar attribute rendered by the widget host.', }, }, diff --git a/projects/packages/premium-analytics/widgets/top-platforms/widget.ts b/projects/packages/premium-analytics/widgets/top-platforms/widget.ts index 633103c0d2df..a1edd2ebc860 100644 --- a/projects/packages/premium-analytics/widgets/top-platforms/widget.ts +++ b/projects/packages/premium-analytics/widgets/top-platforms/widget.ts @@ -45,11 +45,9 @@ export default { label: __( 'View by', 'jetpack-premium-analytics-pkg' ), type: 'text', Edit: SelectField, + // Browser stays first: `SelectField` shows the first element when the + // attribute is unset, so it has to match the render default. elements: [ - { - label: __( 'Size', 'jetpack-premium-analytics-pkg' ), - value: 'screensize', - }, { label: __( 'Browser', 'jetpack-premium-analytics-pkg' ), value: 'browser', @@ -58,6 +56,10 @@ export default { label: __( 'OS', 'jetpack-premium-analytics-pkg' ), value: 'platform', }, + { + label: __( 'Size', 'jetpack-premium-analytics-pkg' ), + value: 'screensize', + }, ], relevance: 'high', }, From 281043087fbf76eeba4a05a29a53eda5472fac4e Mon Sep 17 00:00:00 2001 From: Jasper Kang Date: Fri, 14 Aug 2026 16:13:58 +1200 Subject: [PATCH 4/7] Default attributes at the render boundary, per the widget contract --- .../packages/premium-analytics/widgets/top-platforms/render.tsx | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/projects/packages/premium-analytics/widgets/top-platforms/render.tsx b/projects/packages/premium-analytics/widgets/top-platforms/render.tsx index f4673ea37ecf..c7894b1b01c5 100644 --- a/projects/packages/premium-analytics/widgets/top-platforms/render.tsx +++ b/projects/packages/premium-analytics/widgets/top-platforms/render.tsx @@ -143,7 +143,7 @@ function TopPlatformsInner( { max, platformDimension }: TopPlatformsInnerProps ) * dimension is the `platformDimension` attribute (`relevance: 'high'`), exposed * as a control by the widget host. */ -export default function TopPlatformsWidget( { attributes }: TopPlatformsWidgetProps ) { +export default function TopPlatformsWidget( { attributes = {} }: TopPlatformsWidgetProps ) { const max = attributes?.max ?? 10; // Attributes are persisted, so a stale layout can name a dimension this // widget no longer knows. Unchecked it becomes the `stats/devices/{property}` From d58012b7cfb4f69a1e4910410de67f1e3c06d49f Mon Sep 17 00:00:00 2001 From: Jasper Kang Date: Fri, 14 Aug 2026 16:38:36 +1200 Subject: [PATCH 5/7] Address review: share the device vocabulary and the dimension list - PlatformDimension aliases StatsDeviceProperty instead of restating it, so the label map stays exhaustive when the endpoint's property set changes. - Hoist the screen-size labels into widgets-toolkit; Devices and Top platforms were translating the same six strings separately. - Derive the supported-dimension guard from that label map rather than keeping a second copy of the list. - Cover the guard directly, drop the it.each row that duplicated the defaults test, and add a Size-with-comparison story for the one Size state nothing exercised. - Correct a docblock that still described two dimensions. - Add the plugins/premium-analytics changelog entry the package-only entry should have been paired with. --- .../src/helpers/device-labels.ts | 20 +++++++++++ .../widgets-toolkit/src/helpers/index.ts | 1 + .../packages/widgets-toolkit/src/index.ts | 1 + .../widgets/devices/use-device-views.ts | 20 ++--------- .../__tests__/top-platforms.test.tsx | 13 +++---- .../__tests__/use-platform-views.test.ts | 16 +++++++++ .../widgets/top-platforms/render.tsx | 32 +++++++---------- .../stories/top-platforms-widget.stories.tsx | 9 +++++ .../top-platforms/use-platform-views.ts | 36 +++++++++++-------- .../add-wooa7s-1940-top-platforms-size | 4 +++ 10 files changed, 94 insertions(+), 58 deletions(-) create mode 100644 projects/packages/premium-analytics/packages/widgets-toolkit/src/helpers/device-labels.ts create mode 100644 projects/packages/premium-analytics/widgets/top-platforms/__tests__/use-platform-views.test.ts create mode 100644 projects/plugins/premium-analytics/changelog/add-wooa7s-1940-top-platforms-size diff --git a/projects/packages/premium-analytics/packages/widgets-toolkit/src/helpers/device-labels.ts b/projects/packages/premium-analytics/packages/widgets-toolkit/src/helpers/device-labels.ts new file mode 100644 index 000000000000..e763ba2157f3 --- /dev/null +++ b/projects/packages/premium-analytics/packages/widgets-toolkit/src/helpers/device-labels.ts @@ -0,0 +1,20 @@ +/** + * WordPress dependencies + */ +import { __ } from '@wordpress/i18n'; + +/** + * Display labels for the keys `stats/devices/screensize` returns. + * + * Shared so the two widgets that render this property — Devices and Top + * platforms — cannot drift apart, and so translators see each string once. + * Keys outside this map are title-cased by `formatDisplayLabel`. + */ +export const SCREEN_SIZE_LABELS: Record< string, string > = { + desktop: __( 'Desktop', 'jetpack-premium-analytics-pkg' ), + mobile: __( 'Mobile', 'jetpack-premium-analytics-pkg' ), + tablet: __( 'Tablet', 'jetpack-premium-analytics-pkg' ), + phone: __( 'Phone', 'jetpack-premium-analytics-pkg' ), + other: __( 'Other', 'jetpack-premium-analytics-pkg' ), + unknown: __( 'Unknown', 'jetpack-premium-analytics-pkg' ), +}; diff --git a/projects/packages/premium-analytics/packages/widgets-toolkit/src/helpers/index.ts b/projects/packages/premium-analytics/packages/widgets-toolkit/src/helpers/index.ts index d821f55ffe57..109d01fdd00a 100644 --- a/projects/packages/premium-analytics/packages/widgets-toolkit/src/helpers/index.ts +++ b/projects/packages/premium-analytics/packages/widgets-toolkit/src/helpers/index.ts @@ -46,6 +46,7 @@ export { export { flagUrl } from './flag-url'; export { isEmptyChartData, isEmptyPieChartData, getEmptyChartDomain } from './chart-empty-state'; export { getFixedYAxis, type FixedYAxis } from './fixed-y-axis'; +export { SCREEN_SIZE_LABELS } from './device-labels'; export { formatDisplayLabel } from './format-display-label'; export { buildCsv, diff --git a/projects/packages/premium-analytics/packages/widgets-toolkit/src/index.ts b/projects/packages/premium-analytics/packages/widgets-toolkit/src/index.ts index d072a31f60b8..a390e6838cc8 100644 --- a/projects/packages/premium-analytics/packages/widgets-toolkit/src/index.ts +++ b/projects/packages/premium-analytics/packages/widgets-toolkit/src/index.ts @@ -150,6 +150,7 @@ export { buildSalesByUtmData, formatLegendLabels, formatDisplayLabel, + SCREEN_SIZE_LABELS, buildCsv, buildCsvDateRangeFilename, saveCsv, diff --git a/projects/packages/premium-analytics/widgets/devices/use-device-views.ts b/projects/packages/premium-analytics/widgets/devices/use-device-views.ts index 8b7f3aa42eb4..65e5551fad0d 100644 --- a/projects/packages/premium-analytics/widgets/devices/use-device-views.ts +++ b/projects/packages/premium-analytics/widgets/devices/use-device-views.ts @@ -1,12 +1,8 @@ -/** - * WordPress dependencies - */ -import { __ } from '@wordpress/i18n'; /** * Internal dependencies */ import { useStatsDevices } from '@jetpack-premium-analytics/data'; -import { formatDisplayLabel } from '@jetpack-premium-analytics/widgets-toolkit'; +import { formatDisplayLabel, SCREEN_SIZE_LABELS } from '@jetpack-premium-analytics/widgets-toolkit'; import type { ReportParams, StatsDevicesComparisonItem, @@ -45,18 +41,6 @@ interface DeviceViewsState { refetch: () => void; } -/** - * Maps raw API device keys to human-readable display labels. - * Keys not in this map are title-cased as a fallback. - */ -const DEVICE_LABELS: Record< string, string > = { - desktop: __( 'Desktop', 'jetpack-premium-analytics-pkg' ), - mobile: __( 'Mobile', 'jetpack-premium-analytics-pkg' ), - tablet: __( 'Tablet', 'jetpack-premium-analytics-pkg' ), - phone: __( 'Phone', 'jetpack-premium-analytics-pkg' ), - unknown: __( 'Unknown', 'jetpack-premium-analytics-pkg' ), -}; - /** * Converts a StatsDevicesItem from the data layer to the widget's DeviceView shape. */ @@ -64,7 +48,7 @@ function toDeviceView( item: StatsDevicesComparisonItem ): DeviceView { const key = typeof item.label === 'string' ? item.label : String( item.label ); return { label: key, - displayLabel: formatDisplayLabel( key, DEVICE_LABELS ), + displayLabel: formatDisplayLabel( key, SCREEN_SIZE_LABELS ), percentage: item.value, previousPercentage: item.previousValue, }; diff --git a/projects/packages/premium-analytics/widgets/top-platforms/__tests__/top-platforms.test.tsx b/projects/packages/premium-analytics/widgets/top-platforms/__tests__/top-platforms.test.tsx index ea5c5c40ac54..e2f0853021a6 100644 --- a/projects/packages/premium-analytics/widgets/top-platforms/__tests__/top-platforms.test.tsx +++ b/projects/packages/premium-analytics/widgets/top-platforms/__tests__/top-platforms.test.tsx @@ -14,7 +14,10 @@ jest.mock( '@wordpress/route', () => jest.requireActual( '../../test-utils' ).mo const mockUsePlatformViews = jest.fn(); +// Only the hook itself is stubbed; `isPlatformDimension` stays real so the +// guard below exercises the shipped implementation. jest.mock( '../use-platform-views', () => ( { + ...jest.requireActual( '../use-platform-views' ), __esModule: true, default: ( ...args: unknown[] ) => mockUsePlatformViews( ...( args as [] ) ), } ) ); @@ -37,15 +40,13 @@ describe( 'TopPlatformsWidget', () => { mockUsePlatformViews.mockReturnValue( stateWith( [] ) ); } ); - it.each( [ [ undefined, 'browser' ], [ 'screensize' ], [ 'browser' ], [ 'platform' ] ] as const )( + it.each( [ 'screensize', 'browser', 'platform' ] as const )( 'requests the %s device property', - ( platformDimension, expected = platformDimension ) => { - render( - - ); + platformDimension => { + render( ); expect( mockUsePlatformViews ).toHaveBeenLastCalledWith( - expect.objectContaining( { deviceProperty: expected } ) + expect.objectContaining( { deviceProperty: platformDimension } ) ); } ); diff --git a/projects/packages/premium-analytics/widgets/top-platforms/__tests__/use-platform-views.test.ts b/projects/packages/premium-analytics/widgets/top-platforms/__tests__/use-platform-views.test.ts new file mode 100644 index 000000000000..6ba74fd46471 --- /dev/null +++ b/projects/packages/premium-analytics/widgets/top-platforms/__tests__/use-platform-views.test.ts @@ -0,0 +1,16 @@ +/** + * Internal dependencies + */ +import { isPlatformDimension } from '../use-platform-views'; + +describe( 'isPlatformDimension', () => { + // The three properties `stats/devices/{property}` accepts. Anything else is + // rejected upstream with a 400, so it must never reach the request. + it.each( [ 'screensize', 'browser', 'platform' ] )( 'accepts %s', dimension => { + expect( isPlatformDimension( dimension ) ).toBe( true ); + } ); + + it.each( [ 'client_type', 'toString', 'constructor', '' ] )( 'rejects %s', dimension => { + expect( isPlatformDimension( dimension ) ).toBe( false ); + } ); +} ); diff --git a/projects/packages/premium-analytics/widgets/top-platforms/render.tsx b/projects/packages/premium-analytics/widgets/top-platforms/render.tsx index c7894b1b01c5..92a4cbb16e01 100644 --- a/projects/packages/premium-analytics/widgets/top-platforms/render.tsx +++ b/projects/packages/premium-analytics/widgets/top-platforms/render.tsx @@ -23,7 +23,10 @@ import { * Internal dependencies */ import styles from './style.module.css'; -import usePlatformViews, { type PlatformDimension } from './use-platform-views'; +import usePlatformViews, { + isPlatformDimension, + type PlatformDimension, +} from './use-platform-views'; import { type TopPlatformsAttributes } from './widget'; /** * Types @@ -44,14 +47,6 @@ const PERCENTAGE_DATA_FORMAT = { options: { decimals: 1, signDisplay: 'auto' as const }, }; -type PlatformMode = PlatformDimension; - -const SUPPORTED_DIMENSIONS: Record< PlatformMode, true > = { - screensize: true, - browser: true, - platform: true, -}; - type TopPlatformsInnerProps = { /** * Max rows to display. @@ -60,7 +55,7 @@ type TopPlatformsInnerProps = { /** * Device dimension to rank: screen sizes, browsers, or operating systems. */ - platformDimension: PlatformMode; + platformDimension: PlatformDimension; }; function TopPlatformsInner( { max, platformDimension }: TopPlatformsInnerProps ) { @@ -75,8 +70,8 @@ function TopPlatformsInner( { max, platformDimension }: TopPlatformsInnerProps ) ); const isShare = platformDimension === 'screensize'; - // Bar widths stay relative to the largest visible value either way; only the - // number printed on the row changes unit. + // Only the number printed on the row changes unit; the percentage formatter + // takes a 0-1 ratio while WPCOM sends screensize as 0-100. const toDisplayValue = ( value: number ) => ( isShare ? value / 100 : value ); const maxViews = getCombinedPeriodMax( @@ -94,6 +89,8 @@ function TopPlatformsInner( { max, platformDimension }: TopPlatformsInnerProps ) ), currentValue: toDisplayValue( item.views ), + // Bar widths come from the raw values on purpose: the ratio to `maxViews` + // is the same before and after the unit conversion. currentShare: sharePercentage( item.views, maxViews ), previousValue: previousValue === undefined ? undefined : toDisplayValue( previousValue ), previousShare: @@ -144,17 +141,12 @@ function TopPlatformsInner( { max, platformDimension }: TopPlatformsInnerProps ) * as a control by the widget host. */ export default function TopPlatformsWidget( { attributes = {} }: TopPlatformsWidgetProps ) { - const max = attributes?.max ?? 10; + const max = attributes.max ?? 10; // Attributes are persisted, so a stale layout can name a dimension this // widget no longer knows. Unchecked it becomes the `stats/devices/{property}` // path segment, which WPCOM rejects with a 400. - const storedDimension = attributes?.platformDimension ?? 'browser'; - const platformDimension = Object.prototype.hasOwnProperty.call( - SUPPORTED_DIMENSIONS, - storedDimension - ) - ? storedDimension - : 'browser'; + const storedDimension = attributes.platformDimension ?? 'browser'; + const platformDimension = isPlatformDimension( storedDimension ) ? storedDimension : 'browser'; return ( diff --git a/projects/packages/premium-analytics/widgets/top-platforms/stories/top-platforms-widget.stories.tsx b/projects/packages/premium-analytics/widgets/top-platforms/stories/top-platforms-widget.stories.tsx index 95808c871cc8..11e0b8705af4 100644 --- a/projects/packages/premium-analytics/widgets/top-platforms/stories/top-platforms-widget.stories.tsx +++ b/projects/packages/premium-analytics/widgets/top-platforms/stories/top-platforms-widget.stories.tsx @@ -134,6 +134,15 @@ export const BySize: StoryObj< TopPlatformsStoryControls > = { decorators: [ withWidgetCanvas ], }; +// Size with comparison — the one Size state where two percentages sit side by +// side: the share itself and `calculateDelta`'s relative change against the +// previous period. Worth a look when reviewing the copy. +export const BySizeWithComparison: StoryObj< TopPlatformsStoryControls > = { + render: renderTopPlatformsWidget, + args: { withComparison: true, platformDimension: 'screensize' }, + decorators: [ withWidgetCanvas ], +}; + // OS view — the `platformDimension` attribute set to operating systems. export const ByOS: StoryObj< TopPlatformsStoryControls > = { render: renderTopPlatformsWidget, diff --git a/projects/packages/premium-analytics/widgets/top-platforms/use-platform-views.ts b/projects/packages/premium-analytics/widgets/top-platforms/use-platform-views.ts index cb572cdd3f28..e0b6f6a28660 100644 --- a/projects/packages/premium-analytics/widgets/top-platforms/use-platform-views.ts +++ b/projects/packages/premium-analytics/widgets/top-platforms/use-platform-views.ts @@ -6,10 +6,17 @@ import { __ } from '@wordpress/i18n'; * Internal dependencies */ import { useStatsDevices } from '@jetpack-premium-analytics/data'; -import { formatDisplayLabel } from '@jetpack-premium-analytics/widgets-toolkit'; -import type { ReportParams, StatsDevicesComparisonItem } from '@jetpack-premium-analytics/data'; +import { formatDisplayLabel, SCREEN_SIZE_LABELS } from '@jetpack-premium-analytics/widgets-toolkit'; +import type { + ReportParams, + StatsDeviceProperty, + StatsDevicesComparisonItem, +} from '@jetpack-premium-analytics/data'; -export type PlatformDimension = 'screensize' | 'browser' | 'platform'; +// The endpoint's own property set. Aliasing rather than restating it keeps +// LABELS_BY_DIMENSION exhaustive: adding a property upstream breaks the build +// here instead of silently falling through to an undefined label map. +export type PlatformDimension = StatsDeviceProperty; export interface PlatformView { key: string; @@ -56,15 +63,6 @@ const BROWSER_LABELS: Record< string, string > = { other: __( 'Other', 'jetpack-premium-analytics-pkg' ), }; -const SCREENSIZE_LABELS: Record< string, string > = { - desktop: __( 'Desktop', 'jetpack-premium-analytics-pkg' ), - mobile: __( 'Mobile', 'jetpack-premium-analytics-pkg' ), - tablet: __( 'Tablet', 'jetpack-premium-analytics-pkg' ), - phone: __( 'Phone', 'jetpack-premium-analytics-pkg' ), - other: __( 'Other', 'jetpack-premium-analytics-pkg' ), - unknown: __( 'Unknown', 'jetpack-premium-analytics-pkg' ), -}; - const PLATFORM_LABELS: Record< string, string > = { windows: __( 'Windows', 'jetpack-premium-analytics-pkg' ), mac: __( 'macOS', 'jetpack-premium-analytics-pkg' ), @@ -81,11 +79,20 @@ const PLATFORM_LABELS: Record< string, string > = { }; const LABELS_BY_DIMENSION: Record< PlatformDimension, Record< string, string > > = { - screensize: SCREENSIZE_LABELS, + screensize: SCREEN_SIZE_LABELS, browser: BROWSER_LABELS, platform: PLATFORM_LABELS, }; +/** + * Whether a persisted attribute names a dimension this widget can fetch. + * + * Keyed off the label map so the supported set is spelled out once. + */ +export function isPlatformDimension( value: string ): value is PlatformDimension { + return Object.prototype.hasOwnProperty.call( LABELS_BY_DIMENSION, value ); +} + function toPlatformView( item: StatsDevicesComparisonItem, deviceProperty: PlatformDimension @@ -102,7 +109,8 @@ function toPlatformView( } /** - * Fetch platform views (browser or OS) via the shared Stats data layer. + * Fetch platform views (screen size, browser, or OS) via the shared Stats data + * layer. */ export default function usePlatformViews( { reportParams, diff --git a/projects/plugins/premium-analytics/changelog/add-wooa7s-1940-top-platforms-size b/projects/plugins/premium-analytics/changelog/add-wooa7s-1940-top-platforms-size new file mode 100644 index 000000000000..7179d1524afc --- /dev/null +++ b/projects/plugins/premium-analytics/changelog/add-wooa7s-1940-top-platforms-size @@ -0,0 +1,4 @@ +Significance: minor +Type: added + +Top platforms: add Size to the "View by" control, showing the Desktop, Mobile and Tablet split. From 63779e2402b7540f1eae20ab8549dc85cf259a96 Mon Sep 17 00:00:00 2001 From: Jasper Kang Date: Fri, 14 Aug 2026 16:56:04 +1200 Subject: [PATCH 6/7] Address review: close the last union copy and the label-map lookup hole - The attribute type was the one place still restating the endpoint's property set; it aliases StatsDeviceProperty like the hook does, so the guard and the attribute type cannot diverge. - Cover the per-dimension label mapping, which the render tests could not reach because they stub the hook wholesale. - formatDisplayLabel looked up plain-object keys unguarded, so a key named toString returned an inherited function where a string was expected. No API vocabulary triggers it, but this change points a second widget at that lookup. --- .../__tests__/format-display-label.test.ts | 28 ++++++++ .../src/helpers/format-display-label.ts | 7 +- .../use-platform-views-labels.test.tsx | 72 +++++++++++++++++++ .../widgets/top-platforms/widget.ts | 3 +- 4 files changed, 108 insertions(+), 2 deletions(-) create mode 100644 projects/packages/premium-analytics/packages/widgets-toolkit/src/helpers/__tests__/format-display-label.test.ts create mode 100644 projects/packages/premium-analytics/widgets/top-platforms/__tests__/use-platform-views-labels.test.tsx diff --git a/projects/packages/premium-analytics/packages/widgets-toolkit/src/helpers/__tests__/format-display-label.test.ts b/projects/packages/premium-analytics/packages/widgets-toolkit/src/helpers/__tests__/format-display-label.test.ts new file mode 100644 index 000000000000..4956694e0857 --- /dev/null +++ b/projects/packages/premium-analytics/packages/widgets-toolkit/src/helpers/__tests__/format-display-label.test.ts @@ -0,0 +1,28 @@ +/** + * Internal dependencies + */ +import { formatDisplayLabel } from '../format-display-label'; + +describe( 'formatDisplayLabel', () => { + it( 'prefers a mapped label, matching case-insensitively', () => { + expect( formatDisplayLabel( 'Desktop', { desktop: 'Desktop screen' } ) ).toBe( + 'Desktop screen' + ); + } ); + + it( 'title-cases an unmapped key', () => { + expect( formatDisplayLabel( 'vivaldi', { chrome: 'Chrome' } ) ).toBe( 'Vivaldi' ); + expect( formatDisplayLabel( 'chrome' ) ).toBe( 'Chrome' ); + } ); + + // The map is a plain object, so an inherited member would otherwise be + // returned where a string is expected. + it.each( [ 'toString', 'constructor', 'hasOwnProperty' ] )( + 'does not return the inherited %s member', + key => { + expect( formatDisplayLabel( key, { chrome: 'Chrome' } ) ).toBe( + key.charAt( 0 ).toUpperCase() + key.slice( 1 ) + ); + } + ); +} ); diff --git a/projects/packages/premium-analytics/packages/widgets-toolkit/src/helpers/format-display-label.ts b/projects/packages/premium-analytics/packages/widgets-toolkit/src/helpers/format-display-label.ts index f258337535b3..9119ebc11e90 100644 --- a/projects/packages/premium-analytics/packages/widgets-toolkit/src/helpers/format-display-label.ts +++ b/projects/packages/premium-analytics/packages/widgets-toolkit/src/helpers/format-display-label.ts @@ -7,6 +7,11 @@ */ export function formatDisplayLabel( key: string, labels: Record< string, string > = {} ): string { const normalized = key.toLowerCase(); + // Own-property only: a key such as `toString` would otherwise resolve to an + // inherited `Object.prototype` member and return a function. + if ( Object.prototype.hasOwnProperty.call( labels, normalized ) ) { + return labels[ normalized ]; + } - return labels[ normalized ] ?? key.charAt( 0 ).toUpperCase() + key.slice( 1 ); + return key.charAt( 0 ).toUpperCase() + key.slice( 1 ); } diff --git a/projects/packages/premium-analytics/widgets/top-platforms/__tests__/use-platform-views-labels.test.tsx b/projects/packages/premium-analytics/widgets/top-platforms/__tests__/use-platform-views-labels.test.tsx new file mode 100644 index 000000000000..2c37c6db0251 --- /dev/null +++ b/projects/packages/premium-analytics/widgets/top-platforms/__tests__/use-platform-views-labels.test.tsx @@ -0,0 +1,72 @@ +/** + * External dependencies + */ +import { queryClient, type ReportParams } from '@jetpack-premium-analytics/data'; +import { renderHook, waitFor } from '@testing-library/react'; +import apiFetch from '@wordpress/api-fetch'; +/** + * Internal dependencies + */ +import { queryClientWrapper as wrapper } from '../../test-utils'; +import usePlatformViews from '../use-platform-views'; + +jest.mock( '@wordpress/api-fetch' ); + +const mockApiFetch = apiFetch as jest.MockedFunction< typeof apiFetch >; + +const reportParams = { from: '2026-06-01', to: '2026-06-30' } as ReportParams; + +// `stats/devices/{property}` answers with a flat key/value map; the keys are the +// raw API vocabulary each dimension uses. +const RESPONSES: Record< string, Record< string, number > > = { + screensize: { desktop: 57.8, mobile: 37, tablet: 5.2 }, + browser: { chrome: 812, miui: 190 }, + platform: { mac: 402, android_tablet: 65 }, +}; + +type MockedFetchArgs = { path?: string; url?: string }; + +beforeEach( () => { + queryClient.clear(); + mockApiFetch.mockImplementation( ( { path = '', url = '' }: MockedFetchArgs ) => { + const target = path || url; + const property = Object.keys( RESPONSES ).find( key => target.includes( `devices/${ key }` ) ); + + return Promise.resolve( { top_values: property ? RESPONSES[ property ] : {} } ); + } ); +} ); + +describe( 'usePlatformViews labels', () => { + // Each dimension has its own vocabulary, so the row label depends on which + // map the hook picks — the thing that silently breaks if the mapping drifts. + it.each( [ + [ 'screensize', 'desktop', 'Desktop' ], + [ 'browser', 'miui', 'Mi Browser' ], + [ 'platform', 'android_tablet', 'Android Tablet' ], + ] as const )( 'maps the %s key %s to %s', async ( deviceProperty, key, expected ) => { + const { result } = renderHook( + () => usePlatformViews( { reportParams, max: 10, deviceProperty } ), + { wrapper } + ); + + await waitFor( () => expect( result.current.data.length ).toBeGreaterThan( 0 ) ); + + expect( result.current.data.find( row => row.key === key )?.label ).toBe( expected ); + } ); + + // Keys outside the map are title-cased rather than dropped. + it( 'falls back to title case for an unmapped key', async () => { + RESPONSES.browser = { vivaldi: 12 }; + + const { result } = renderHook( + () => usePlatformViews( { reportParams, max: 10, deviceProperty: 'browser' } ), + { wrapper } + ); + + await waitFor( () => expect( result.current.data.length ).toBeGreaterThan( 0 ) ); + + expect( result.current.data[ 0 ].label ).toBe( 'Vivaldi' ); + + RESPONSES.browser = { chrome: 812, miui: 190 }; + } ); +} ); diff --git a/projects/packages/premium-analytics/widgets/top-platforms/widget.ts b/projects/packages/premium-analytics/widgets/top-platforms/widget.ts index a1edd2ebc860..008f501787d1 100644 --- a/projects/packages/premium-analytics/widgets/top-platforms/widget.ts +++ b/projects/packages/premium-analytics/widgets/top-platforms/widget.ts @@ -4,6 +4,7 @@ import { __ } from '@wordpress/i18n'; import { desktop } from '@wordpress/icons'; import type { WidgetAttributeField } from '@wordpress/widget-primitives'; +import type { StatsDeviceProperty } from '@jetpack-premium-analytics/data'; /** * Internal dependencies @@ -18,7 +19,7 @@ export type TopPlatformsAttributes = { /** * Device dimension to rank: screen sizes, browsers, or operating systems. */ - platformDimension?: 'screensize' | 'browser' | 'platform'; + platformDimension?: StatsDeviceProperty; }; /** From 3f17a5d1f65fa68fecbcec3e0585d271fbccb54f Mon Sep 17 00:00:00 2001 From: Jasper Kang Date: Fri, 14 Aug 2026 17:09:54 +1200 Subject: [PATCH 7/7] Address review: stop the fallback test mutating a shared fixture A failing assertion would have skipped the restore on the line below it and leaked the override into whatever test was appended next. The override is local to the mock now, and the fixture map is readonly so it cannot drift back. --- .../__tests__/use-platform-views-labels.test.tsx | 8 ++++---- 1 file changed, 4 insertions(+), 4 deletions(-) diff --git a/projects/packages/premium-analytics/widgets/top-platforms/__tests__/use-platform-views-labels.test.tsx b/projects/packages/premium-analytics/widgets/top-platforms/__tests__/use-platform-views-labels.test.tsx index 2c37c6db0251..1353b1096704 100644 --- a/projects/packages/premium-analytics/widgets/top-platforms/__tests__/use-platform-views-labels.test.tsx +++ b/projects/packages/premium-analytics/widgets/top-platforms/__tests__/use-platform-views-labels.test.tsx @@ -18,7 +18,7 @@ const reportParams = { from: '2026-06-01', to: '2026-06-30' } as ReportParams; // `stats/devices/{property}` answers with a flat key/value map; the keys are the // raw API vocabulary each dimension uses. -const RESPONSES: Record< string, Record< string, number > > = { +const RESPONSES: Readonly< Record< string, Record< string, number > > > = { screensize: { desktop: 57.8, mobile: 37, tablet: 5.2 }, browser: { chrome: 812, miui: 190 }, platform: { mac: 402, android_tablet: 65 }, @@ -56,7 +56,9 @@ describe( 'usePlatformViews labels', () => { // Keys outside the map are title-cased rather than dropped. it( 'falls back to title case for an unmapped key', async () => { - RESPONSES.browser = { vivaldi: 12 }; + // A local implementation rather than a reassignment of RESPONSES: a + // failing assertion below must not leak a fixture into the next test. + mockApiFetch.mockImplementation( () => Promise.resolve( { top_values: { vivaldi: 12 } } ) ); const { result } = renderHook( () => usePlatformViews( { reportParams, max: 10, deviceProperty: 'browser' } ), @@ -66,7 +68,5 @@ describe( 'usePlatformViews labels', () => { await waitFor( () => expect( result.current.data.length ).toBeGreaterThan( 0 ) ); expect( result.current.data[ 0 ].label ).toBe( 'Vivaldi' ); - - RESPONSES.browser = { chrome: 812, miui: 190 }; } ); } );