Skip to content
Merged
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: patch
Type: fixed

GeoChart: Stop an HTML tooltip breaking its lines when it opens near a map edge.
Original file line number Diff line number Diff line change
@@ -0,0 +1,4 @@
Significance: minor
Type: added

Export GoogleDataTableColumnRoleType as a value, so a consumer can build a GeoChart tooltip column.
Original file line number Diff line number Diff line change
@@ -1,3 +1,11 @@
.container {
position: relative;

// Google gives its HTML tooltip no width, so the box shrink-to-fits against
// whatever room is left beside the hovered feature. Near a map edge that
// breaks even a short label across lines. Sizing to content keeps each line
// whole and grows the box instead.
:global(.google-visualization-tooltip) {
white-space: nowrap;
}
}
3 changes: 2 additions & 1 deletion projects/js-packages/charts/src/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,8 @@ export { BarChart, BarChartUnresponsive } from './charts/bar-chart';
export { BarListChart, BarListChartUnresponsive } from './charts/bar-list-chart';
export { ConversionFunnelChart } from './charts/conversion-funnel-chart';
export { GeoChart, GeoChartUnresponsive } from './charts/geo-chart';
// A value export, not a type: building a tooltip column header needs the enum member itself.
export { GoogleDataTableColumnRoleType } from './types';
export {
HeatmapChart,
HeatmapChartUnresponsive,
Expand Down Expand Up @@ -63,7 +65,6 @@ export type {
SeriesChartLegendConfig,
BaseChartProps,
GoogleDataTableColumn,
GoogleDataTableColumnRoleType,
GoogleDataTableRow,
LegendShape,
LegendShapeLabel,
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,4 @@
Significance: minor
Type: added

Locations: Name the regions behind each country total in the Regions map tooltip.
Original file line number Diff line number Diff line change
Expand Up @@ -19,6 +19,7 @@ export {
ConversionFunnelChart,
GeoChart,
GlobalChartsProvider,
GoogleDataTableColumnRoleType,
HeatmapChart,
HeatmapChartUnresponsive,
LeaderboardChartUnresponsive,
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -264,6 +264,7 @@ export type { MetricKey, OrderMetricKey, OrderMetrics, OrdersSummary, DataFormat
export {
GeoChart,
GlobalChartsProvider,
GoogleDataTableColumnRoleType,
HeatmapChart,
HeatmapChartUnresponsive,
Sparkline,
Expand Down
Original file line number Diff line number Diff line change
@@ -1,13 +1,15 @@
/**
* External dependencies
*/
import { formatMetricValue } from '@jetpack-premium-analytics/formatters';
import { render, screen } from '@testing-library/react';
import userEvent from '@testing-library/user-event';
import type { AnchorHTMLAttributes, ReactNode } from 'react';
/**
* Internal dependencies
*/
import LocationsWidget from '../render';
import type { LocationView } from '../use-location-views';

type MockRouteLinkProps = {
to: string;
Expand Down Expand Up @@ -39,10 +41,13 @@ jest.mock( '@wordpress/route', () => ( {
useSearch: () => ( {} ),
} ) );

// Google Charts loads asynchronously and is outside this widget's concern.
// Google Charts loads asynchronously and is outside this widget's concern. The
// map rows are an assertion target, so the stand-in carries its data prop.
jest.mock( '@jetpack-premium-analytics/widgets-toolkit', () => ( {
...jest.requireActual( '@jetpack-premium-analytics/widgets-toolkit' ),
GeoChart: () => <div data-testid="geo-chart" />,
GeoChart: ( { data }: { data: unknown } ) => (
<div data-testid="geo-chart">{ JSON.stringify( data ) }</div>
),
} ) );

// Typed off the hook so the mocked state and the rows passed to
Expand All @@ -66,6 +71,21 @@ jest.mock( '../use-location-views', () => ( {
default: ( ...args: unknown[] ) => mockUseLocationViews( ...( args as [] ) ),
} ) );

function locationView( label: string, countryCode: string, countryFull: string, value: number ) {
return { key: `${ countryCode }:${ label }`, label, countryCode, countryFull, value, region: '' };
}

function viewsState( data: LocationView[] ): LocationViewsState {
return { ...LOADING_STATE, data, isLoading: false, isFetching: false, hasData: data.length > 0 };
}

/**
* Read the rows GeoChart was handed, as `[ header, ...rows ]`.
*/
function readGeoChartData() {
return JSON.parse( screen.getByTestId( 'geo-chart' ).textContent ?? '[]' );
}

describe( 'LocationsWidget', () => {
beforeEach( () => {
mockUseLocationViews.mockReset();
Expand Down Expand Up @@ -149,4 +169,68 @@ describe( 'LocationsWidget', () => {
expect.objectContaining( { geoMode: 'country', countryFilter: undefined } )
);
} );

describe( 'Regions view', () => {
it( 'sums each country regions onto one map row', () => {
mockUseLocationViews.mockReturnValue(
viewsState( [
locationView( 'Maharashtra', 'IN', 'India', 5447 ),
locationView( 'Delhi', 'IN', 'India', 520 ),
locationView( 'Illinois', 'US', 'United States', 2 ),
] )
);

render( <LocationsWidget attributes={ { geoGranularity: 'region' } } /> );
const [ , ...rows ] = readGeoChartData();

expect( rows ).toHaveLength( 2 );
expect( rows ).toContainEqual( [ { v: 'IN', f: 'India' }, 5967, expect.any( String ) ] );
expect( rows ).toContainEqual( [ { v: 'US', f: 'United States' }, 2, expect.any( String ) ] );
} );

it( 'lists a country regions in its tooltip', () => {
mockUseLocationViews.mockReturnValue(
viewsState( [
locationView( 'Maharashtra', 'IN', 'India', 5447 ),
locationView( 'Delhi', 'IN', 'India', 520 ),
] )
);

render( <LocationsWidget attributes={ { geoGranularity: 'region' } } /> );
const [ header, row ] = readGeoChartData();

expect( header[ 2 ] ).toMatchObject( { role: 'tooltip', p: { html: true } } );
expect( row[ 2 ] ).toBe(
`Maharashtra: ${ formatMetricValue( 5447 ) }<br />Delhi: ${ formatMetricValue( 520 ) }`
);
} );

it( 'counts the regions it leaves out of a long tooltip', () => {
mockUseLocationViews.mockReturnValue(
viewsState(
Array.from( { length: 12 }, ( _, index ) =>
locationView( `Region ${ index }`, 'IN', 'India', 12 - index )
)
)
);

render( <LocationsWidget attributes={ { geoGranularity: 'region' } } /> );
const [ , row ] = readGeoChartData();

expect( row[ 2 ].split( '<br />' ) ).toHaveLength( 11 );
expect( row[ 2 ] ).toContain( '…and 2 more locations' );
} );
} );

it( 'gives the Cities view no tooltip column', () => {
mockUseLocationViews.mockReturnValue(
viewsState( [ locationView( 'Mumbai', 'IN', 'India', 900 ) ] )
);

render( <LocationsWidget attributes={ { geoGranularity: 'city' } } /> );
const [ header, row ] = readGeoChartData();

expect( header ).toHaveLength( 2 );
expect( row ).toEqual( [ { v: 'IN', f: 'India' }, 900 ] );
} );
} );
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,7 @@
"dependencies": {
"@jetpack-premium-analytics/data": "link:../../packages/data",
"@jetpack-premium-analytics/externals": "link:../../packages/externals",
"@jetpack-premium-analytics/formatters": "link:../../packages/formatters",
"@jetpack-premium-analytics/icons": "link:../../packages/icons",
"@jetpack-premium-analytics/widgets-toolkit": "link:../../packages/widgets-toolkit",
"@wordpress/element": "8.3.0",
Expand Down
75 changes: 64 additions & 11 deletions projects/packages/premium-analytics/widgets/locations/render.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@
*/
import {
GeoChart,
GoogleDataTableColumnRoleType,
LeaderboardChart,
ReportLink,
WIDGET_ROW_LIMIT,
Expand All @@ -24,15 +25,16 @@ import {
type LeaderboardChartData,
type ReportParamsFieldAttributes,
} from '@jetpack-premium-analytics/widgets-toolkit';
import { formatMetricValue } from '@jetpack-premium-analytics/formatters';
import { location as locationIcon } from '@jetpack-premium-analytics/icons';
import { useCallback, useEffect, useMemo, useState } from '@wordpress/element';
import { __, sprintf } from '@wordpress/i18n';
import { __, _n, sprintf } from '@wordpress/i18n';
import { Stack } from '@jetpack-premium-analytics/externals';
/**
* Internal dependencies
*/
import styles from './style.module.css';
import useLocationViews, { type GeoMode } from './use-location-views';
import useLocationViews, { type GeoMode, type LocationView } from './use-location-views';
import { type LocationsAttributes } from './widget';
/**
* Types
Expand All @@ -42,6 +44,11 @@ import type { WidgetRenderProps } from '@wordpress/widget-primitives';
type LocationsRenderAttributes = LocationsAttributes & Partial< ReportParamsFieldAttributes >;
type LocationsWidgetProps = WidgetRenderProps< LocationsRenderAttributes >;
type DrillDownCountry = { code: string; name: string };
type CountrySummary = {
countryFull: string;
value: number;
locations: LocationView[];
};
type GoogleChartsWindow = Window & {
google?: {
visualization?: {
Expand Down Expand Up @@ -80,6 +87,35 @@ function getGeoChartCountryId( countryCode: string ): string {
return countryCode.toUpperCase();
}

// A GeoChart tooltip is a single cell, so the summed locations share one HTML
// string. The list is capped to keep a tooltip from overflowing the map.
const MAX_TOOLTIP_LOCATIONS = 10;

function buildCountryTooltip( country: CountrySummary ): string {
const listed = country.locations.slice( 0, MAX_TOOLTIP_LOCATIONS );
const lines = listed.map(
location => `${ location.label }: ${ formatMetricValue( location.value ) }`
);
const remaining = country.locations.length - listed.length;

if ( remaining > 0 ) {
lines.push(
sprintf(
/* translators: %d is the number of locations left out of the tooltip list. */
_n(
'…and %d more location',
'…and %d more locations',
remaining,
'jetpack-premium-analytics-pkg'
),
remaining
)
);
}

return lines.join( '<br />' );
}

type LocationsInnerProps = {
geoGranularity: NonNullable< LocationsAttributes[ 'geoGranularity' ] >;
};
Expand Down Expand Up @@ -135,7 +171,7 @@ function LocationsInner( { geoGranularity }: LocationsInnerProps ) {
const useCountrySummaryMap =
geoMode === 'city' || ( geoMode === 'region' && ! activeSelectedCountry );
const countrySummaryRows = useMemo( () => {
const countryRows = new Map< string, { countryFull: string; value: number } >();
const countryRows = new Map< string, CountrySummary >();

if ( ! useCountrySummaryMap ) {
return [];
Expand All @@ -147,6 +183,7 @@ function LocationsInner( { geoGranularity }: LocationsInnerProps ) {
countryRows.set( countryCode, {
countryFull: location.countryFull,
value: ( current?.value ?? 0 ) + location.value,
locations: [ ...( current?.locations ?? [] ), location ],
} );
} );

Expand Down Expand Up @@ -228,23 +265,39 @@ function LocationsInner( { geoGranularity }: LocationsInnerProps ) {
}

if ( useCountrySummaryMap ) {
// A summed country no longer names the regions behind its value, so it
// carries them in a tooltip. Cities keep GeoChart's default tooltip.
const withTooltips = geoMode === 'region';
const summaryHeader: GoogleDataTableColumn[] = withTooltips
? [
...header,
{
type: 'string',
role: GoogleDataTableColumnRoleType.tooltip,
p: { html: true },
},
]
: header;

return [
header,
...countrySummaryRows.map(
( [ countryCode, location ] ): GoogleDataTableRow => [
summaryHeader,
...countrySummaryRows.map( ( [ countryCode, country ] ): GoogleDataTableRow => {
const row: GoogleDataTableRow = [
{
v: getGeoChartCountryId( countryCode ),
f: location.countryFull,
f: country.countryFull,
},
location.value,
]
),
country.value,
];

return withTooltips ? [ ...row, buildCountryTooltip( country ) ] : row;
} ),
];
}

const rows: GoogleDataTableRow[] = data.map( location => [ location.label, location.value ] );
return [ header, ...rows ];
}, [ countrySummaryRows, data, fallbackCountry, useCountrySummaryMap, useProvinceMap ] );
}, [ countrySummaryRows, data, fallbackCountry, geoMode, useCountrySummaryMap, useProvinceMap ] );

const leaderboardData = useMemo( () => {
const maxValue = getCombinedPeriodMax(
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -121,8 +121,8 @@ export const WithComparison: StoryObj< LocationsStoryControls > = {
decorators: [ withWidgetCanvas, withStoryRouter ],
};

// Regions mode — region rows worldwide in the leaderboard, aggregated by country
// on the map.
// Regions mode — region rows worldwide in the leaderboard, summed by country on
// the map, where each country tooltip lists the regions behind its total.
export const RegionsMode: StoryObj< LocationsStoryControls > = {
render: renderLocationsWidget,
args: { withComparison: false, geoGranularity: 'region' },
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,4 @@
Significance: minor
Type: added

Locations: Hover a country in the Regions view to see the regions behind its total.
Loading