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
Expand Up @@ -5,7 +5,6 @@ import { ThemeProvider } from '@wordpress/theme';
import { Button, Icon, Notice, Text } from '@wordpress/ui';
import clsx from 'clsx';
import { useCallback, useRef, useState } from 'react';
import useAnalytics from '../../../../hooks/use-analytics';
import {
CONNECTION_FROM,
CONNECTION_RETURN_URL,
Expand All @@ -14,6 +13,7 @@ import {
startBenefits,
} from '../lib';
import styles from '../styles.module.scss';
import { WIZARD_EVENTS, useWizardTracks } from '../telemetry';
import { markConnecting } from '../use-just-connected';
import { useRestoredConnection } from '../use-restored-connection';

Expand Down Expand Up @@ -45,7 +45,9 @@ export function StartStep( { titleId, title, description }: StartStepProps ) {
redirectUri: CONNECTION_RETURN_URL,
skipPricingPage: true,
} );
const { recordEvent } = useAnalytics();
// The same bundle the rest of the flow carries, so the connection is part of
// the funnel rather than two loose events beside it.
const track = useWizardTracks( 'start' );

// Only registration failures reach the store. Fetching the authorization URL can
// fail too, and that rejection is ours to hold or the screen says nothing.
Expand Down Expand Up @@ -82,8 +84,9 @@ export function StartStep( { titleId, title, description }: StartStepProps ) {
// return to knows to say the connection worked.
markConnecting();

// The name the single-screen flow already reports, so the two are one funnel.
recordEvent( 'jetpack_my_jetpack_onboarding_click', { flow: 'wizard' } );
// `flow` is what tells this run from the single-screen flow, which reports
// the click under the same name.
track( WIZARD_EVENTS.connectClick, { flow: 'wizard' } );

// No success event: this resolves as the browser leaves for WordPress.com,
// which is not the same thing as anyone having connected.
Expand All @@ -92,11 +95,11 @@ export function StartStep( { titleId, title, description }: StartStepProps ) {
setHandoffError( caught );
// The code only: the message interpolates the server's prose, which
// can carry the site's own URL.
recordEvent( 'jetpack_my_jetpack_onboarding_connect_error', {
track( WIZARD_EVENTS.connectError, {
error_code: connectionErrorCode( caught ),
} );
} );
}, [ handleRegisterSite, recordEvent ] );
}, [ handleRegisterSite, track ] );

return (
<div className={ styles.start }>
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,126 @@
import { useCallback, useMemo } from 'react';
import useAnalytics from '../../../hooks/use-analytics';

/*
* Tracks silently drops any name that misses `Jetpack_Tracks_Event::EVENT_NAME_REGEX`.
* Written out in full, not assembled, so a search finds each one.
*/
export const WIZARD_EVENTS = {
stepView: 'jetpack_my_jetpack_onboarding_wizard_step_view',
siteTypeSelect: 'jetpack_my_jetpack_onboarding_wizard_site_type_select',
siteTypeDetail: 'jetpack_my_jetpack_onboarding_wizard_site_type_detail',
moduleToggle: 'jetpack_my_jetpack_onboarding_wizard_module_toggle',
stepComplete: 'jetpack_my_jetpack_onboarding_wizard_step_complete',
applyResult: 'jetpack_my_jetpack_onboarding_wizard_apply_result',
complete: 'jetpack_my_jetpack_onboarding_wizard_complete',
skip: 'jetpack_my_jetpack_onboarding_wizard_skip',
// Shared with the single-screen flow, which `flow` tells apart.
connectClick: 'jetpack_my_jetpack_onboarding_click',
// The wizard's own until the connection package records registration failures (CONNECT-502).
connectError: 'jetpack_my_jetpack_onboarding_connect_error',
} as const;

const FLOW_ID_KEY = 'jetpack-onboarding-flow-id';

/**
* An id for one run through the wizard.
*
* In session storage, so a run that leaves for WordPress.com to connect keeps it.
*
* @return The id, or 'none' where storage cannot be reached.
*/
function flowId(): string {
try {
const held = window.sessionStorage.getItem( FLOW_ID_KEY );

if ( held ) {
return held;
}

const made = makeId();
window.sessionStorage.setItem( FLOW_ID_KEY, made );

return made;
} catch {
// Private browsing and blocked site data throw. A run with no id still reports;
// it just cannot be stitched to its other half, which beats reporting nothing.
return 'none';
}
}

/**
* A random id. `randomUUID()` exists only in secure contexts, and wp-admin can be plain HTTP.
*
* @return The id.
*/
function makeId(): string {
if ( typeof window.crypto.randomUUID === 'function' ) {
return window.crypto.randomUUID();
}

return Array.from( window.crypto.getRandomValues( new Uint8Array( 16 ) ), byte =>
byte.toString( 16 ).padStart( 2, '0' )
).join( '' );
}

/**
* End this run's id, so the next run in the same tab gets its own.
*/
export function forgetFlowId(): void {
try {
window.sessionStorage.removeItem( FLOW_ID_KEY );
} catch {
// Nothing was stored where storage is blocked.
}
}

/**
* How long the free text was, in buckets.
*
* The words never leave the browser: it is the one field that could carry a name or an address.
*
* @param text - What was typed.
* @return A bucket name, never the text.
*/
export function lengthBucket( text: string ): string {
const length = text.trim().length;

if ( length === 0 ) {
return 'empty';
}

if ( length <= 20 ) {
return 'short';
}

return length <= 60 ? 'medium' : 'long';
}

type WizardEvent = ( typeof WIZARD_EVENTS )[ keyof typeof WIZARD_EVENTS ];
type EventProperties = Record< string, string | number | boolean >;

/**
* Reports one run through the wizard, tagging every event with the run's id and the step's slug.
*
* The slug, not the index, because a connected site starts at the second step.
* Nothing is sent before the terms are agreed (`Tracking::should_enable_tracking`).
*
* @param stepId - The slug of the step being reported on.
* @return A recorder bound to this step.
*/
export function useWizardTracks( stepId: string ) {
const { recordEvent } = useAnalytics();

const flow = useMemo( () => flowId(), [] );

return useCallback(
( event: WizardEvent, properties: EventProperties = {} ) => {
recordEvent( event, {
flow_id: flow,
step: stepId,
...properties,
} );
},
[ recordEvent, flow, stepId ]
);
}
Original file line number Diff line number Diff line change
Expand Up @@ -313,11 +313,16 @@ describe( 'Wizard start screen', () => {

expect( mockConnection.handleRegisterSite ).toHaveBeenCalledTimes( 1 );
// One name across both onboarding flows, told apart by the flow property.
expect( mockRecordEvent ).toHaveBeenCalledWith( 'jetpack_my_jetpack_onboarding_click', {
flow: 'wizard',
} );
// And nothing on the way out: the hand-off resolving is not a connection.
expect( mockRecordEvent ).toHaveBeenCalledTimes( 1 );
expect( mockRecordEvent ).toHaveBeenCalledWith(
'jetpack_my_jetpack_onboarding_click',
expect.objectContaining( { flow: 'wizard', step: 'start' } )
);
// The whole list, so the hand-off resolving cannot add an event back:
// it is not the same thing as anyone having connected.
expect( mockRecordEvent.mock.calls.map( ( [ name ] ) => name ) ).toEqual( [
'jetpack_my_jetpack_onboarding_wizard_step_view',
'jetpack_my_jetpack_onboarding_click',
] );
// The browser is on its way to WordPress.com; the step does not move here.
expect( heading() ).toHaveTextContent( 'Start with Jetpack for free' );
} );
Expand Down Expand Up @@ -374,7 +379,7 @@ describe( 'Wizard start screen', () => {
await waitFor( () =>
expect( mockRecordEvent ).toHaveBeenCalledWith(
'jetpack_my_jetpack_onboarding_connect_error',
{ error_code: 'site_inaccessible' }
expect.objectContaining( { error_code: 'site_inaccessible' } )
)
);

Expand Down Expand Up @@ -411,9 +416,10 @@ describe( 'Wizard start screen', () => {
).resolves.toBeInTheDocument();
// No message to show, so the code stands in for it.
expect( screen.getByText( 'JsonParseError' ) ).toBeInTheDocument();
expect( mockRecordEvent ).toHaveBeenCalledWith( 'jetpack_my_jetpack_onboarding_connect_error', {
error_code: 'JsonParseError',
} );
expect( mockRecordEvent ).toHaveBeenCalledWith(
'jetpack_my_jetpack_onboarding_connect_error',
expect.objectContaining( { error_code: 'JsonParseError' } )
);
} );

it( 'names what Jetpack does, one free feature group per row', () => {
Expand Down Expand Up @@ -1254,6 +1260,146 @@ describe( 'What the finish screen claims', () => {
} );
} );

describe( 'What the wizard reports', () => {
/*
* The one thing that must never leave the browser. Asserted over every call
* rather than over the one event that handles it, because the guarantee is
* about the whole flow and a future event could carry it by accident.
*/
it( 'never sends what the user typed about their own site', async () => {
const secret = 'Smith family wiki at smith-family.example';
const { user } = setupWizard( { isUserConnected: true } );

await user.click( screen.getByRole( 'radio', { name: 'Something else…' } ) );
await user.type( screen.getByRole( 'textbox' ), secret );
await user.click( screen.getByRole( 'button', { name: 'Continue' } ) );

const sent = JSON.stringify( mockRecordEvent.mock.calls );

expect( sent ).not.toContain( 'Smith' );
expect( sent ).not.toContain( 'example' );
expect( sent ).toContain( 'length_bucket' );
} );

it( 'reports the site type as a slug, and the run as one id', async () => {
const { user } = setupWizard( { isUserConnected: true } );

await user.click( screen.getByRole( 'radio', { name: 'An online store' } ) );

expect( mockRecordEvent ).toHaveBeenCalledWith(
'jetpack_my_jetpack_onboarding_wizard_site_type_select',
expect.objectContaining( { site_type: 'store', step: 'site-type' } )
);

// One id for the whole run, or the two halves of a connection cannot be joined.
const ids = new Set( mockRecordEvent.mock.calls.map( ( [ , props ] ) => props?.flow_id ) );

expect( ids.size ).toBe( 1 );
} );

// The run is restored on reload, and a second report would double-count the field.
it( 'reports the typed answer once, even across a reload', async () => {
const { user, unmount } = setupWizard( { isUserConnected: true } );
await user.click( screen.getByRole( 'radio', { name: 'Something else…' } ) );
await user.type( screen.getByRole( 'textbox' ), 'A wiki' );
await user.click( screen.getByRole( 'button', { name: 'Continue' } ) );

unmount();
setupWizard( { isUserConnected: true } );

const detail = mockRecordEvent.mock.calls.filter(
( [ name ] ) => name === 'jetpack_my_jetpack_onboarding_wizard_site_type_detail'
);
expect( detail ).toHaveLength( 1 );
} );

// Two of the four mock modules ship on; leaving them on is not switching them on.
it( 'counts only what the run switched on', async () => {
const { user } = setupWizard( { isUserConnected: true } );
await user.click( screen.getByRole( 'radio', { name: 'A blog or publication' } ) );
await user.click( screen.getByRole( 'button', { name: 'Continue' } ) );
await user.click( screen.getByRole( 'switch', { name: 'Downtime Monitor' } ) );
await user.click( screen.getByRole( 'button', { name: 'Continue' } ) );

await waitFor( () =>
expect( mockRecordEvent ).toHaveBeenCalledWith(
'jetpack_my_jetpack_onboarding_wizard_apply_result',
expect.objectContaining( { offered: 4, switched_on: 1, failed: 0 } )
)
);
} );

// Tracks drops an event whose property keys miss its rule, and says nothing.
it( 'sends only property keys Tracks will take', async () => {
const { user } = setupWizard( { isUserConnected: true } );
await user.click( screen.getByRole( 'radio', { name: 'Something else…' } ) );
await user.type( screen.getByRole( 'textbox' ), 'A wiki' );
await user.click( screen.getByRole( 'button', { name: 'Continue' } ) );
await user.click( screen.getByRole( 'switch', { name: 'Downtime Monitor' } ) );
await user.click( screen.getByRole( 'button', { name: 'Continue' } ) );
await user.click( await screen.findByRole( 'link', { name: 'Go to My Jetpack' } ) );

const keys = mockRecordEvent.mock.calls.flatMap( ( [ , props ] ) => Object.keys( props ) );

expect( keys ).toEqual(
expect.arrayContaining( [ 'length_bucket', 'module', 'switched_on' ] )
);
keys.forEach( key => expect( key ).toMatch( /^[a-z_][a-z0-9_]*$/ ) );
} );

// A double click, or both finish links, must not report and settle twice.
it( 'records one exit per run, and ends its id', async () => {
const { user } = setupWizard( { isUserConnected: true } );
await advance( user, 2 );

await user.click( screen.getByRole( 'link', { name: 'Go to My Jetpack' } ) );
await user.click( screen.getByRole( 'link', { name: 'Back to your WordPress site' } ) );

const exits = mockRecordEvent.mock.calls.filter( ( [ name ] ) =>
/_wizard_(complete|skip)$/.test( name )
);
expect( exits ).toHaveLength( 1 );
expect( mockApiFetch ).toHaveBeenCalledTimes( 1 );
expect( window.sessionStorage.getItem( 'jetpack-onboarding-flow-id' ) ).toBeNull();
} );

// randomUUID() exists only in secure contexts, and wp-admin can be plain HTTP.
it( 'still gives the run an id where randomUUID is missing', () => {
const randomUUID = window.crypto.randomUUID;
Object.defineProperty( window.crypto, 'randomUUID', { value: undefined, configurable: true } );

try {
setupWizard( { isUserConnected: true } );
} finally {
Object.defineProperty( window.crypto, 'randomUUID', {
value: randomUUID,
configurable: true,
} );
}

expect( mockRecordEvent ).toHaveBeenCalledWith(
expect.any( String ),
expect.objectContaining( { flow_id: expect.stringMatching( /^[0-9a-f]{32}$/ ) } )
);
} );

// The field is left open by one option only, and the text survives switching
// away from it, so a run that typed and changed its mind used no field.
it( 'says nothing about the field when the answer was not the one that opens it', async () => {
const { user } = setupWizard( { isUserConnected: true } );

await user.click( screen.getByRole( 'radio', { name: 'Something else…' } ) );
await user.type( screen.getByRole( 'textbox' ), 'A wiki' );
await user.click( screen.getByRole( 'radio', { name: 'A blog or publication' } ) );
await user.click( screen.getByRole( 'button', { name: 'Continue' } ) );

expect( mockRecordEvent ).not.toHaveBeenCalledWith(
'jetpack_my_jetpack_onboarding_wizard_site_type_detail',
expect.anything()
);
} );
} );

describe( 'The feature step', () => {
const featureStep = async ( user: UserEvent ) => {
await user.click( screen.getByRole( 'radio', { name: 'A blog or publication' } ) );
Expand Down
Loading
Loading