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

Filter by extension

Filter by extension

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

Top platforms: offer Size alongside Browser and OS in the widget's "View by" control.
Original file line number Diff line number Diff line change
Expand Up @@ -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 }
Expand Down
Original file line number Diff line number Diff line change
@@ -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 )
);
}
);
} );
Original file line number Diff line number Diff line change
@@ -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' ),
};
Original file line number Diff line number Diff line change
Expand Up @@ -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 );
}
Original file line number Diff line number Diff line change
Expand Up @@ -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,
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -150,6 +150,7 @@ export {
buildSalesByUtmData,
formatLegendLabels,
formatDisplayLabel,
SCREEN_SIZE_LABELS,
buildCsv,
buildCsvDateRangeFilename,
saveCsv,
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -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;
}

Expand Down
Original file line number Diff line number Diff line change
@@ -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,
Expand Down Expand Up @@ -45,26 +41,14 @@ 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.
*/
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,
};
Expand Down
Original file line number Diff line number Diff line change
@@ -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( <TopPlatformsWidget attributes={ { platformDimension } } /> );

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( <TopPlatformsWidget attributes={ {} } /> );

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(
<TopPlatformsWidget
attributes={
{ platformDimension: 'client_type' } as unknown as { platformDimension: 'browser' }
}
/>
);

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( <TopPlatformsWidget attributes={ { platformDimension: 'screensize' } } /> );

expect( screen.getByText( '57.8%' ) ).toBeInTheDocument();
} );

it( 'prints Browser rows as counts', () => {
mockUsePlatformViews.mockReturnValue(
stateWith( [ { key: 'chrome', label: 'Chrome', views: 812 } ] )
);

render( <TopPlatformsWidget attributes={ { platformDimension: 'browser' } } /> );

expect( screen.getByText( '812' ) ).toBeInTheDocument();
} );
} );
Original file line number Diff line number Diff line change
@@ -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' );
} );
} );
Original file line number Diff line number Diff line change
@@ -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 );
} );
} );
Loading
Loading