Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Enhancement/6243 loyal visitors #7126

Merged
merged 15 commits into from
Jun 8, 2023
Merged
Show file tree
Hide file tree
Changes from 11 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
14 changes: 12 additions & 2 deletions assets/js/components/ChangeBadge.js
Original file line number Diff line number Diff line change
Expand Up @@ -27,11 +27,20 @@ import classnames from 'classnames';
*/
import { calculateChange, numFmt } from '../util';

export default function ChangeBadge( { previousValue, currentValue } ) {
const change = calculateChange( previousValue, currentValue );
export default function ChangeBadge( props ) {
const { previousValue, currentValue, isAbsolute } = props;

const change = isAbsolute
? currentValue - previousValue
: calculateChange( previousValue, currentValue );
const isNegative = change < 0;
const isZero = change === 0;

// Do not display the change badge if the change value can't be calculated.
if ( change === null ) {
return null;
}

return (
<div
className={ classnames( 'googlesitekit-change-badge', {
Expand All @@ -49,6 +58,7 @@ export default function ChangeBadge( { previousValue, currentValue } ) {
}

ChangeBadge.propTypes = {
isAbsolute: PropTypes.bool,
previousValue: PropTypes.number.isRequired,
currentValue: PropTypes.number.isRequired,
};
Original file line number Diff line number Diff line change
Expand Up @@ -31,17 +31,17 @@ const WidgetWithComponentProps = withWidgetComponentProps(
const Template = () => <WidgetWithComponentProps />;

export const Default = Template.bind( {} );
Default.storyName = 'KeyMetricsSetupCTAWidget';
Default.storyName = 'SetupCTAWidget';
Default.scenario = {
label: 'Global/KeyMetricsSetupCTAWidget',
label: 'KeyMetrics/SetupCTAWidget',
delay: 250,
};
Default.parameters = {
features: [ 'userInput' ],
};

export default {
title: 'Components/KeyMetrics',
title: 'Key Metrics',
decorators: [
( Story ) => {
const setupRegistry = ( registry ) => {
Expand Down
31 changes: 21 additions & 10 deletions assets/js/components/KeyMetrics/MetricTileNumeric.js
Original file line number Diff line number Diff line change
Expand Up @@ -24,18 +24,22 @@ import PropTypes from 'prop-types';
/**
* Internal dependencies
*/
import { numFmt, numFmtOptions } from '../../util';
import ChangeBadge from '../ChangeBadge';
import PreviewBlock from '../PreviewBlock';

export default function MetricTileNumeric( {
Widget,
loading,
title,
metricValue,
subText,
previousValue,
currentValue,
} ) {
export default function MetricTileNumeric( props ) {
const {
Widget,
loading,
title,
metricValue,
metricValueFormat,
subText,
previousValue,
currentValue,
} = props;

if ( loading ) {
return (
<Widget noPadding>
aaemnnosttv marked this conversation as resolved.
Show resolved Hide resolved
Expand All @@ -44,6 +48,8 @@ export default function MetricTileNumeric( {
);
}

const formatOptions = numFmtOptions( metricValueFormat );

return (
<Widget noPadding>
<div className="googlesitekit-km-widget-tile">
Expand All @@ -53,11 +59,12 @@ export default function MetricTileNumeric( {
<div className="googlesitekit-km-widget-tile__body">
<div className="googlesitekit-km-widget-tile__metric-change-container">
<div className="googlesitekit-km-widget-tile__metric">
{ metricValue }
{ numFmt( metricValue, formatOptions ) }
</div>
<ChangeBadge
previousValue={ previousValue }
currentValue={ currentValue }
isAbsolute={ formatOptions?.style === 'percent' }
/>
</div>
<p className="googlesitekit-km-widget-tile__subtext">
Expand All @@ -74,6 +81,10 @@ MetricTileNumeric.propTypes = {
loading: PropTypes.bool,
title: PropTypes.string,
metricValue: PropTypes.oneOfType( [ PropTypes.string, PropTypes.number ] ),
metricValueFormat: PropTypes.oneOfType( [
PropTypes.string,
PropTypes.object,
] ),
subtext: PropTypes.string,
previousValue: PropTypes.number,
currentValue: PropTypes.number,
Expand Down
13 changes: 6 additions & 7 deletions assets/js/components/KeyMetrics/MetricTileNumeric.stories.js
Original file line number Diff line number Diff line change
Expand Up @@ -22,9 +22,8 @@
import MetricTileNumeric from './MetricTileNumeric';
import { withWidgetComponentProps } from '../../googlesitekit/widgets/util';

const WidgetWithComponentProps = withWidgetComponentProps(
'kmAnalyticsNewVisitors'
)( MetricTileNumeric );
const WidgetWithComponentProps =
withWidgetComponentProps( 'test' )( MetricTileNumeric );

const Template = ( { ...args } ) => <WidgetWithComponentProps { ...args } />;

Expand All @@ -38,7 +37,7 @@ Positive.args = {
previousValue: 91,
};
Positive.scenario = {
label: 'Components/KeyMetrics/Widgets/MetricTileNumeric/Positive',
label: 'KeyMetrics/MetricTileNumeric/Positive',
delay: 250,
};

Expand All @@ -52,7 +51,7 @@ Negative.args = {
previousValue: 103,
};
Negative.scenario = {
label: 'Components/KeyMetrics/Widgets/MetricTileNumeric/Negative',
label: 'KeyMetrics/MetricTileNumeric/Negative',
delay: 250,
};

Expand All @@ -66,7 +65,7 @@ ZeroChange.args = {
previousValue: 100,
};
ZeroChange.scenario = {
label: 'Components/KeyMetrics/Widgets/MetricTileNumeric/ZeroChange',
label: 'KeyMetrics/MetricTileNumeric/ZeroChange',
delay: 250,
};

Expand All @@ -77,6 +76,6 @@ Loading.args = {
};

export default {
title: 'Components/KeyMetrics/WidgetTiles/MetricTileNumeric',
title: 'Key Metrics/WidgetTiles/MetricTileNumeric',
component: MetricTileNumeric,
};
Original file line number Diff line number Diff line change
Expand Up @@ -21,27 +21,97 @@
*/
import PropTypes from 'prop-types';

/**
* WordPress dependencies
*/
import { __, sprintf } from '@wordpress/i18n';

/**
* Internal dependencies
*/
import Data from 'googlesitekit-data';
import { CORE_USER } from '../../../../googlesitekit/datastore/user/constants';
import {
DATE_RANGE_OFFSET,
MODULES_ANALYTICS_4,
} from '../../datastore/constants';
import MetricTileNumeric from '../../../../components/KeyMetrics/MetricTileNumeric';

const { useSelect } = Data;
const { useSelect, useInViewSelect } = Data;

export default function LoyalVisitorsWidget( { Widget, WidgetNull } ) {
const keyMetricsWidgetHidden = useSelect( ( select ) =>
select( CORE_USER ).isKeyMetricsWidgetHidden()
);

// One combined select hook is used to prevent unnecessary selects
// if the key metrics widget is hidden.
const [ report, loading ] =
useInViewSelect( ( select ) => {
if ( keyMetricsWidgetHidden !== false ) {
return [];
}

const { getReport, hasFinishedResolution } =
select( MODULES_ANALYTICS_4 );

const reportOptions = {
...select( CORE_USER ).getDateRangeDates( {
offsetDays: DATE_RANGE_OFFSET,
compare: true,
} ),
dimensions: [ 'newVsReturning' ],
metrics: [ { name: 'activeUsers' } ],
};

return [
getReport( reportOptions ),
! hasFinishedResolution( 'getReport', [ reportOptions ] ),
];
} ) || [];

if ( keyMetricsWidgetHidden !== false ) {
return <WidgetNull />;
}

const newVisitors =
parseInt( report?.rows?.[ 1 ]?.metricValues[ 0 ]?.value, 10 ) || 0;
const returningVisitors =
parseInt( report?.rows?.[ 3 ]?.metricValues[ 0 ]?.value, 10 ) || 0;
const totalVisitors = newVisitors + returningVisitors;

const prevNewVisitors =
parseInt( report?.rows?.[ 0 ]?.metricValues[ 0 ]?.value, 10 ) || 0;
const prevReturningVisitors =
parseInt( report?.rows?.[ 2 ]?.metricValues[ 0 ]?.value, 10 ) || 0;
const prevTotalVisitors = prevNewVisitors + prevReturningVisitors;

const currentPercentage =
totalVisitors > 0 ? returningVisitors / totalVisitors : 0;
const prevPercentage =
prevTotalVisitors > 0 ? prevReturningVisitors / prevTotalVisitors : 0;

const format = {
style: 'percent',
signDisplay: 'exceptZero',
maximumFractionDigits: 1,
};

return (
<Widget>
<div>TODO: UI for LoyalVisitorsWidget</div>
</Widget>
<MetricTileNumeric
Widget={ Widget }
title={ __( 'Loyal visitors', 'google-site-kit' ) }
metricValue={ currentPercentage }
metricValueFormat={ format }
subText={ sprintf(
/* translators: %d: Number of total visitors visiting the site. */
__( 'of %d total visitors', 'google-site-kit' ),
totalVisitors
) }
previousValue={ prevPercentage }
currentValue={ currentPercentage }
loading={ loading }
/>
);
}

Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,127 @@
/**
* Site Kit by Google, Copyright 2023 Google LLC
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/

/**
* Internal dependencies
*/
import { CORE_USER } from '../../../../googlesitekit/datastore/user/constants';
import { MODULES_ANALYTICS_4 } from '../../datastore/constants';
import {
provideKeyMetrics,
provideModules,
} from '../../../../../../tests/js/utils';
import { withWidgetComponentProps } from '../../../../googlesitekit/widgets/util';
import WithRegistrySetup from '../../../../../../tests/js/WithRegistrySetup';
import LoyalVisitorsWidget from './LoyalVisitorsWidget';
import {
getAnalytics4MockResponse,
provideAnalytics4MockReport,
} from '../../utils/data-mock';
import { replaceValuesInAnalytics4ReportWithZeroData } from '../../../../../../.storybook/utils/zeroReports';

const reportOptions = {
compareStartDate: '2020-07-14',
compareEndDate: '2020-08-10',
startDate: '2020-08-11',
endDate: '2020-09-07',
dimensions: [ 'newVsReturning' ],
metrics: [
{
name: 'activeUsers',
},
],
};

const WidgetWithComponentProps = withWidgetComponentProps(
'kmAnalyticsLoyalVisitors'
)( LoyalVisitorsWidget );

const Template = ( { setupRegistry, ...args } ) => (
<WithRegistrySetup func={ setupRegistry }>
<WidgetWithComponentProps { ...args } />
</WithRegistrySetup>
);

export const Ready = Template.bind( {} );
Ready.storyName = 'Ready';
Ready.args = {
setupRegistry: ( registry ) => {
provideAnalytics4MockReport( registry, reportOptions );
},
};
Ready.scenario = {
label: 'KeyMetrics/LoyalVisitors/Ready',
delay: 250,
};

export const Loading = Template.bind( {} );
Loading.storyName = 'Loading';
Loading.args = {
setupRegistry: ( { dispatch } ) => {
dispatch( MODULES_ANALYTICS_4 ).startResolution( 'getReport', [
reportOptions,
] );
},
};

export const ZeroData = Template.bind( {} );
ZeroData.storyName = 'Zero Data';
ZeroData.args = {
setupRegistry: ( { dispatch } ) => {
const report = getAnalytics4MockResponse( reportOptions );
const zeroReport =
replaceValuesInAnalytics4ReportWithZeroData( report );

dispatch( MODULES_ANALYTICS_4 ).receiveGetReport( zeroReport, {
options: reportOptions,
} );
},
};
ZeroData.scenario = {
label: 'KeyMetrics/LoyalVisitors/ZeroData',
delay: 250,
};

export default {
title: 'Key Metrics/LoyalVisitors',
decorators: [
( Story, { args } ) => {
const setupRegistry = ( registry ) => {
global._googlesitekitUserData.isUserInputCompleted = false;
provideModules( registry, [
{
slug: 'analytics-4',
active: true,
connected: true,
},
] );

registry.dispatch( CORE_USER ).setReferenceDate( '2020-09-08' );

provideKeyMetrics( registry );

// Call story-specific setup.
args.setupRegistry( registry );
};

return (
<WithRegistrySetup func={ setupRegistry }>
<Story />
</WithRegistrySetup>
);
},
],
};
Loading