diff --git a/projects/packages/premium-analytics/changelog/add-wooa7s-1940-locations-regions-view b/projects/packages/premium-analytics/changelog/add-wooa7s-1940-locations-regions-view
new file mode 100644
index 000000000000..17cc7068bd70
--- /dev/null
+++ b/projects/packages/premium-analytics/changelog/add-wooa7s-1940-locations-regions-view
@@ -0,0 +1,4 @@
+Significance: minor
+Type: added
+
+Top locations: offer Regions in the widget's "View by" control.
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..52ac384e7af4 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
@@ -1100,9 +1100,16 @@ function getLocationRows(
}
if ( geoMode === 'region' ) {
- const countryCode = query.get( 'filter_by_country' ) || 'US';
+ const countryCode = query.get( 'filter_by_country' );
const regionRows = isComparison ? REGION_COMPARISON_ROWS_BY_COUNTRY : REGION_ROWS_BY_COUNTRY;
+ // Unfiltered, the endpoint returns the top regions worldwide.
+ if ( ! countryCode ) {
+ return Object.values( regionRows )
+ .flat()
+ .sort( ( a, b ) => b.views - a.views );
+ }
+
return regionRows[ countryCode ] ?? regionRows.US;
}
diff --git a/projects/packages/premium-analytics/widgets/locations/__tests__/locations.test.tsx b/projects/packages/premium-analytics/widgets/locations/__tests__/locations.test.tsx
index de0948c57cad..27ad7de78475 100644
--- a/projects/packages/premium-analytics/widgets/locations/__tests__/locations.test.tsx
+++ b/projects/packages/premium-analytics/widgets/locations/__tests__/locations.test.tsx
@@ -2,6 +2,7 @@
* External dependencies
*/
import { render, screen } from '@testing-library/react';
+import userEvent from '@testing-library/user-event';
import type { AnchorHTMLAttributes, ReactNode } from 'react';
/**
* Internal dependencies
@@ -38,21 +39,40 @@ jest.mock( '@wordpress/route', () => ( {
useSearch: () => ( {} ),
} ) );
+// Google Charts loads asynchronously and is outside this widget's concern.
+jest.mock( '@jetpack-premium-analytics/widgets-toolkit', () => ( {
+ ...jest.requireActual( '@jetpack-premium-analytics/widgets-toolkit' ),
+ GeoChart: () =>
,
+} ) );
+
+// Typed off the hook so the mocked state and the rows passed to
+// `mockReturnValue` are type-checked rather than cast away.
+type LocationViewsState = ReturnType< typeof import('../use-location-views').default >;
+
+const LOADING_STATE: LocationViewsState = {
+ data: [],
+ hasComparison: false,
+ isLoading: true,
+ isFetching: true,
+ hasData: false,
+ isError: false,
+ isPlaceholderData: false,
+ refetch: () => {},
+};
+
+const mockUseLocationViews = jest.fn( () => LOADING_STATE );
+
jest.mock( '../use-location-views', () => ( {
__esModule: true,
- default: () => ( {
- data: [],
- comparisonData: [],
- hasComparison: false,
- isLoading: true,
- isFetching: true,
- hasData: false,
- isError: false,
- isPlaceholderData: false,
- } ),
+ default: ( ...args: unknown[] ) => mockUseLocationViews( ...( args as [] ) ),
} ) );
describe( 'LocationsWidget', () => {
+ beforeEach( () => {
+ mockUseLocationViews.mockReset();
+ mockUseLocationViews.mockReturnValue( LOADING_STATE );
+ } );
+
it( 'links to the Locations report', () => {
render( );
@@ -61,4 +81,73 @@ describe( 'LocationsWidget', () => {
expect.stringContaining( '/reports/locations' )
);
} );
+
+ it.each( [
+ [ 'default', 'countries' ],
+ [ 'country', 'countries' ],
+ [ 'region', 'regions' ],
+ [ 'city', 'cities' ],
+ ] as const )( 'opens the %s granularity on the %s report tab', ( geoGranularity, section ) => {
+ render(
+
+ );
+
+ expect( screen.getByRole( 'link', { name: 'View all' } ) ).toHaveAttribute(
+ 'href',
+ expect.stringContaining( `section=${ section }` )
+ );
+ } );
+
+ // Regions mode is worldwide; only the country drill-down scopes it.
+ it( 'requests unfiltered region rows in Regions mode', () => {
+ render( );
+
+ expect( mockUseLocationViews ).toHaveBeenLastCalledWith(
+ expect.objectContaining( { geoMode: 'region', countryFilter: undefined } )
+ );
+ } );
+
+ // Without the reset, the drill-down survives the trip through Regions and
+ // Countries mode comes back scoped to one country instead of listing them all.
+ it( 'drops a drilled-down country when switching to Regions', async () => {
+ mockUseLocationViews.mockReturnValue( {
+ ...LOADING_STATE,
+ data: [
+ {
+ key: 'US:United States',
+ label: 'United States',
+ countryCode: 'US',
+ countryFull: 'United States',
+ value: 10,
+ region: '',
+ },
+ ],
+ isLoading: false,
+ isFetching: false,
+ hasData: true,
+ } );
+
+ const { rerender } = render( );
+ await userEvent.click(
+ screen.getByRole( 'button', { name: 'View regions in United States' } )
+ );
+
+ expect( mockUseLocationViews ).toHaveBeenLastCalledWith(
+ expect.objectContaining( { geoMode: 'region', countryFilter: 'US' } )
+ );
+
+ rerender( );
+
+ expect( mockUseLocationViews ).toHaveBeenLastCalledWith(
+ expect.objectContaining( { geoMode: 'region', countryFilter: undefined } )
+ );
+ // Regions mode keeps the map alongside the leaderboard.
+ expect( screen.getByTestId( 'geo-chart' ) ).toBeInTheDocument();
+
+ rerender( );
+
+ expect( mockUseLocationViews ).toHaveBeenLastCalledWith(
+ expect.objectContaining( { geoMode: 'country', countryFilter: undefined } )
+ );
+ } );
} );
diff --git a/projects/packages/premium-analytics/widgets/locations/render.tsx b/projects/packages/premium-analytics/widgets/locations/render.tsx
index 0c8f8f413709..490d21d86a99 100644
--- a/projects/packages/premium-analytics/widgets/locations/render.tsx
+++ b/projects/packages/premium-analytics/widgets/locations/render.tsx
@@ -63,6 +63,18 @@ const MISSING_MAP_ERROR_MESSAGE = 'Requested map does not exist';
// load each country pays the failed draw (a brief error flash) at most once.
const runtimeUnsupportedProvinceMapCountries = new Set< string >();
+type GeoGranularity = NonNullable< LocationsAttributes[ 'geoGranularity' ] >;
+// Tab ids owned by the Locations report; `ReportLink` takes a bare string, so
+// naming them here is what catches a typo at build time.
+type LocationsReportSection = 'countries' | 'regions' | 'cities';
+
+const REPORT_SECTIONS: Record< GeoGranularity, LocationsReportSection > = {
+ country: 'countries',
+ region: 'regions',
+ city: 'cities',
+};
+const DEFAULT_GEO_GRANULARITY: GeoGranularity = 'country';
+
function getGeoChartCountryId( countryCode: string ): string {
if ( countryCode.toUpperCase() === 'TW' ) {
return 'Taiwan';
@@ -91,9 +103,10 @@ function LocationsInner( { max, geoGranularity }: LocationsInnerProps ) {
} = useWidgetDrillDown< DrillDownCountry >();
// The "View by" control lives in the widget host header (the
- // `relevance: 'high'` attribute). City mode disables country drill-down.
+ // `relevance: 'high'` attribute). Only Countries mode drills down, so leaving
+ // the other modes would strand a selected country the user can't clear.
useEffect( () => {
- if ( geoGranularity === 'city' ) {
+ if ( geoGranularity !== 'country' ) {
clearSelectedCountry();
}
}, [ clearSelectedCountry, geoGranularity ] );
@@ -107,7 +120,7 @@ function LocationsInner( { max, geoGranularity }: LocationsInnerProps ) {
reportParams,
max,
geoMode,
- countryFilter: geoMode === 'region' ? activeSelectedCountry?.code : undefined,
+ countryFilter: activeSelectedCountry?.code,
} );
const [ renderLocationState, setRenderLocationState ] = useState< RenderLocationState >( {
geoMode,
@@ -134,11 +147,15 @@ function LocationsInner( { max, geoGranularity }: LocationsInnerProps ) {
const useCountryFallbackMap =
renderGeoMode === 'region' && !! renderSelectedCountry && ! useProvinceMap;
const fallbackCountry = useCountryFallbackMap ? renderSelectedCountry : undefined;
- const useCityCountryMap = renderGeoMode === 'city';
- const cityCountryRows = useMemo( () => {
+ // Cities, and Regions outside a country drill-down, span the whole world.
+ // Google GeoChart can't place either row type on the world map, so both are
+ // summed back up to their country.
+ const useCountrySummaryMap =
+ renderGeoMode === 'city' || ( renderGeoMode === 'region' && ! renderSelectedCountry );
+ const countrySummaryRows = useMemo( () => {
const countryRows = new Map< string, { countryFull: string; value: number } >();
- if ( ! useCityCountryMap ) {
+ if ( ! useCountrySummaryMap ) {
return [];
}
@@ -152,7 +169,7 @@ function LocationsInner( { max, geoGranularity }: LocationsInnerProps ) {
} );
return Array.from( countryRows.entries() );
- }, [ data, useCityCountryMap ] );
+ }, [ data, useCountrySummaryMap ] );
const handleGeoChartError = useCallback(
( error: GeoChartError ) => {
const message = `${ error.message ?? '' } ${ error.detailedMessage ?? '' }`;
@@ -201,9 +218,10 @@ function LocationsInner( { max, geoGranularity }: LocationsInnerProps ) {
);
const geoData = useMemo( (): GeoData => {
- const useLocationHeader = renderGeoMode === 'region' && ! useCountryFallbackMap;
+ // Only the provinces map plots sub-country rows; every other map is
+ // country-scoped, whatever the leaderboard beside it lists.
const header: GoogleDataTableColumn[] = [
- useLocationHeader
+ useProvinceMap
? __( 'Location', 'jetpack-premium-analytics-pkg' )
: __( 'Country', 'jetpack-premium-analytics-pkg' ),
__( 'Views', 'jetpack-premium-analytics-pkg' ),
@@ -227,10 +245,10 @@ function LocationsInner( { max, geoGranularity }: LocationsInnerProps ) {
];
}
- if ( useCityCountryMap ) {
+ if ( useCountrySummaryMap ) {
return [
header,
- ...cityCountryRows.map(
+ ...countrySummaryRows.map(
( [ countryCode, location ] ): GoogleDataTableRow => [
{
v: getGeoChartCountryId( countryCode ),
@@ -244,14 +262,7 @@ function LocationsInner( { max, geoGranularity }: LocationsInnerProps ) {
const rows: GoogleDataTableRow[] = data.map( location => [ location.label, location.value ] );
return [ header, ...rows ];
- }, [
- cityCountryRows,
- data,
- fallbackCountry,
- renderGeoMode,
- useCityCountryMap,
- useCountryFallbackMap,
- ] );
+ }, [ countrySummaryRows, data, fallbackCountry, useCountrySummaryMap, useProvinceMap ] );
const leaderboardData = useMemo( () => {
const maxValue = getCombinedPeriodMax(
@@ -382,17 +393,22 @@ function LocationsInner( { max, geoGranularity }: LocationsInnerProps ) {
*/
export default function Locations( { attributes = {} }: LocationsWidgetProps ) {
const max = attributes?.max ?? 10;
- const geoGranularity = attributes?.geoGranularity ?? 'country';
+ // Attributes are persisted, so a stale layout can carry a granularity this
+ // widget no longer knows. Normalize once, before it becomes both the endpoint
+ // path segment and the report tab.
+ const storedGranularity = attributes?.geoGranularity ?? DEFAULT_GEO_GRANULARITY;
+ // `in` would also accept inherited keys such as `toString`, which would then
+ // reach the endpoint as a path segment.
+ const geoGranularity = Object.prototype.hasOwnProperty.call( REPORT_SECTIONS, storedGranularity )
+ ? storedGranularity
+ : DEFAULT_GEO_GRANULARITY;
return (
-
+
diff --git a/projects/packages/premium-analytics/widgets/locations/stories/locations-widget.stories.tsx b/projects/packages/premium-analytics/widgets/locations/stories/locations-widget.stories.tsx
index 4f3c4d650bc0..f3f8ca112731 100644
--- a/projects/packages/premium-analytics/widgets/locations/stories/locations-widget.stories.tsx
+++ b/projects/packages/premium-analytics/widgets/locations/stories/locations-widget.stories.tsx
@@ -93,7 +93,7 @@ const meta = {
},
geoGranularity: {
control: 'radio',
- options: [ 'country', 'city' ],
+ options: [ 'country', 'region', 'city' ],
description: 'The "View by" toolbar attribute rendered by the widget host.',
},
},
@@ -101,7 +101,7 @@ const meta = {
docs: {
description: {
component:
- 'The "Locations" widget. Shows visitor views by country or city, with country drill-down into regions, using the global dashboard date range. The Countries/Cities view is the `geoGranularity` attribute (`relevance: \'high\'`), exposed as a control by the widget host.',
+ 'The "Locations" widget. Shows visitor views by country, region, or city, with country drill-down into regions, using the global dashboard date range. The Countries/Regions/Cities view is the `geoGranularity` attribute (`relevance: \'high\'`), exposed as a control by the widget host.',
},
},
},
@@ -123,6 +123,14 @@ export const WithComparison: StoryObj< LocationsStoryControls > = {
decorators: [ withWidgetCanvas, withStoryRouter ],
};
+// Regions mode — region rows worldwide in the leaderboard, aggregated by country
+// on the map.
+export const RegionsMode: StoryObj< LocationsStoryControls > = {
+ render: renderLocationsWidget,
+ args: { withComparison: false, geoGranularity: 'region' },
+ decorators: [ withWidgetCanvas, withStoryRouter ],
+};
+
// Cities mode — city rows in the leaderboard, aggregated by country on the map.
export const CitiesMode: StoryObj< LocationsStoryControls > = {
render: renderLocationsWidget,
@@ -190,7 +198,7 @@ export const WidgetDashboardWithWidget: DashboardStory = {
},
geoGranularity: {
control: 'radio',
- options: [ 'country', 'city' ],
+ options: [ 'country', 'region', 'city' ],
description: 'The "View by" toolbar attribute rendered by the widget host.',
},
},
diff --git a/projects/packages/premium-analytics/widgets/locations/widget.ts b/projects/packages/premium-analytics/widgets/locations/widget.ts
index be53c225dcaf..cd8b38bfb20a 100644
--- a/projects/packages/premium-analytics/widgets/locations/widget.ts
+++ b/projects/packages/premium-analytics/widgets/locations/widget.ts
@@ -12,16 +12,16 @@ import { SelectField } from '@jetpack-premium-analytics/fields';
export type LocationsAttributes = {
max?: number;
- geoGranularity?: 'country' | 'city';
+ geoGranularity?: 'country' | 'region' | 'city';
};
/**
* Widget type definition.
*
- * Ported from the Jetpack Stats "Locations" module. v1 ships Countries mode
- * (with region drill-down) and Cities mode via the `location-views/{geoMode}`
- * endpoint. City rows are listed in the leaderboard and summarized on the map
- * by country.
+ * Ported from the Jetpack Stats "Locations" module. Countries, Regions, and
+ * Cities modes all read the `location-views/{geoMode}` endpoint; Countries mode
+ * additionally drills down into one country's regions. Region and city rows are
+ * listed in the leaderboard and summarized on the map by country.
*
* Data: fetched via the PA proxy at `stats/location-views/{country|region|city}`.
* Date range comes from WidgetRoot's reportParams (the shared dashboard date
@@ -49,6 +49,10 @@ export default {
label: __( 'Countries', 'jetpack-premium-analytics-pkg' ),
value: 'country',
},
+ {
+ label: __( 'Regions', 'jetpack-premium-analytics-pkg' ),
+ value: 'region',
+ },
{
label: __( 'Cities', 'jetpack-premium-analytics-pkg' ),
value: 'city',
diff --git a/projects/plugins/premium-analytics/changelog/add-wooa7s-1940-locations-regions-view b/projects/plugins/premium-analytics/changelog/add-wooa7s-1940-locations-regions-view
new file mode 100644
index 000000000000..02c8e48359a8
--- /dev/null
+++ b/projects/plugins/premium-analytics/changelog/add-wooa7s-1940-locations-regions-view
@@ -0,0 +1,4 @@
+Significance: minor
+Type: added
+
+Top locations: add Regions to the "View by" control, listing the top regions worldwide.