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/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/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/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/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/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/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 new file mode 100644 index 000000000000..e2f0853021a6 --- /dev/null +++ b/projects/packages/premium-analytics/widgets/top-platforms/__tests__/top-platforms.test.tsx @@ -0,0 +1,105 @@ +/** + * External dependencies + */ +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. +jest.mock( '@wordpress/route', () => jest.requireActual( '../../test-utils' ).mockWordPressRoute ); + +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 [] ) ), +} ) ); + +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( [ 'screensize', 'browser', 'platform' ] as const )( + 'requests the %s device property', + platformDimension => { + render( ); + + expect( mockUsePlatformViews ).toHaveBeenLastCalledWith( + expect.objectContaining( { deviceProperty: platformDimension } ) + ); + } + ); + + // `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', () => { + 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/__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..1353b1096704 --- /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: 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 }, +}; + +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 () => { + // 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' } ), + { wrapper } + ); + + await waitFor( () => expect( result.current.data.length ).toBeGreaterThan( 0 ) ); + + expect( result.current.data[ 0 ].label ).toBe( 'Vivaldi' ); + } ); +} ); 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 ad7e16e3c7fd..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 from './use-platform-views'; +import usePlatformViews, { + isPlatformDimension, + type PlatformDimension, +} from './use-platform-views'; import { type TopPlatformsAttributes } from './widget'; /** * Types @@ -33,9 +36,16 @@ 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 } }; - -type PlatformMode = 'browser' | 'platform'; +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 TopPlatformsInnerProps = { /** @@ -43,9 +53,9 @@ type TopPlatformsInnerProps = { */ max: number; /** - * Device dimension to rank: browsers or operating systems. + * Device dimension to rank: screen sizes, browsers, or operating systems. */ - platformDimension: PlatformMode; + platformDimension: PlatformDimension; }; function TopPlatformsInner( { max, platformDimension }: TopPlatformsInnerProps ) { @@ -59,6 +69,11 @@ function TopPlatformsInner( { max, platformDimension }: TopPlatformsInnerProps ) } ); + const isShare = platformDimension === 'screensize'; + // 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( data.map( item => item.views ), hasComparison ? data.map( item => item.previousViews ) : [] @@ -73,9 +88,11 @@ function TopPlatformsInner( { max, platformDimension }: TopPlatformsInnerProps ) { item.label } ), - currentValue: item.views, + 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: previousValue === undefined ? undefined : toDisplayValue( previousValue ), previousShare: hasComparison && previousValue !== undefined ? sharePercentage( previousValue, maxViews ) @@ -111,7 +128,7 @@ function TopPlatformsInner( { max, platformDimension }: TopPlatformsInnerProps ) withComparison={ hasComparison } withOverlayLabel showLegend={ false } - dataFormat={ DATA_FORMAT } + dataFormat={ isShare ? PERCENTAGE_DATA_FORMAT : COUNT_DATA_FORMAT } /> @@ -119,13 +136,17 @@ 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'; +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}` + // path segment, which WPCOM rejects with a 400. + 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 2ab6c19ec79a..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 @@ -97,7 +97,7 @@ const meta = { }, platformDimension: { control: 'radio', - options: [ 'browser', 'platform' ], + options: [ 'browser', 'platform', 'screensize' ], 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,22 @@ 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 ], +}; + +// 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, @@ -208,7 +224,7 @@ export const WidgetDashboardWithWidget: DashboardStory = { }, platformDimension: { control: 'radio', - options: [ '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/use-platform-views.ts b/projects/packages/premium-analytics/widgets/top-platforms/use-platform-views.ts index 10a23f8da446..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,8 +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'; + +// 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; @@ -26,9 +35,9 @@ interface UsePlatformViewsArgs { */ max: number; /** - * 'browser' or 'platform' (OS). + * 'screensize' (Size), 'browser', or 'platform' (OS). */ - deviceProperty: 'browser' | 'platform'; + deviceProperty: PlatformDimension; } interface PlatformViewsState { @@ -69,12 +78,27 @@ const PLATFORM_LABELS: Record< string, string > = { other: __( 'Other', 'jetpack-premium-analytics-pkg' ), }; +const LABELS_BY_DIMENSION: Record< PlatformDimension, Record< string, string > > = { + 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: '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, @@ -85,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/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", diff --git a/projects/packages/premium-analytics/widgets/top-platforms/widget.ts b/projects/packages/premium-analytics/widgets/top-platforms/widget.ts index 27b1bea68dc2..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 @@ -16,17 +17,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?: StatsDeviceProperty; }; /** * 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, @@ -41,6 +46,8 @@ 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: __( 'Browser', 'jetpack-premium-analytics-pkg' ), @@ -50,6 +57,10 @@ export default { label: __( 'OS', 'jetpack-premium-analytics-pkg' ), value: 'platform', }, + { + label: __( 'Size', 'jetpack-premium-analytics-pkg' ), + value: 'screensize', + }, ], relevance: 'high', }, 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.