Press n or j to go to the next uncovered block, b, p or k for the previous block.
| 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 | 8x 1x 3x 3x 3x 3x 3x 1x 2x 2x 2x 1x 2x 1x 8x 8x 8x 8x 8x 8x 8x 8x 8x 8x 8x 6x 6x 3x 3x 3x 3x 3x 3x 8x 7x 1x 1x 8x | import { getScriptData } from '@automattic/jetpack-script-data';
import {
AnalyticsQueryClientProvider,
useStatsSettings,
type StatsSettings,
} from '@jetpack-premium-analytics/data';
import {
Card,
DataForm,
Link,
Notice,
Spinner,
Stack,
Text,
VisuallyHidden,
type Form,
} from '@jetpack-premium-analytics/externals';
import { useTrackEvent } from '@jetpack-premium-analytics/widgets-toolkit';
import { useDispatch } from '@wordpress/data';
import { createInterpolateElement, useCallback, useMemo } from '@wordpress/element';
import { __, sprintf } from '@wordpress/i18n';
import { PlanUsageCard } from './plan-usage-card';
import { getFields } from './stats-settings-fields';
import styles from './stats-settings.module.scss';
import type { JSX } from 'react';
type CardGroup = { id: string; label: string; children: string[] };
/**
* The form's cards and the fields each one holds.
*
* @return The cards, in order.
*/
const getCardGroups = (): CardGroup[] => [
{
id: 'admin-bar',
label: __( 'Admin bar widget', 'jetpack-premium-analytics-pkg' ),
children: [ 'admin_bar' ],
},
{
id: 'permissions',
label: __( 'Manage permissions', 'jetpack-premium-analytics-pkg' ),
children: [ 'roles', 'count_roles' ],
},
{
id: 'reader',
label: __( 'WordPress.com Reader', 'jetpack-premium-analytics-pkg' ),
children: [ 'wpcom_reader_views_enabled' ],
},
];
// apiFetch writes these itself when the request never reached the site.
const CLIENT_ERROR_CODES = [ 'fetch_error', 'offline_error' ];
/**
* The reason the site gave for refusing a save, when it gave one.
*
* @param error - What apiFetch rejected with: the site's REST error body, or a client-side error.
* @return The site's message, or null.
*/
function getSiteErrorMessage( error: unknown ): string | null {
const { code, message } = ( error ?? {} ) as { code?: unknown; message?: unknown };
return typeof code === 'string' &&
! CLIENT_ERROR_CODES.includes( code ) &&
typeof message === 'string'
? message
: null;
}
type SettingChange = { setting: keyof StatsSettings; enabled: boolean; role?: string };
/**
* Each switch a save flipped and each role it added or removed, in the shape Odyssey Stats records.
*
* @param before - The settings the save changed.
* @param edits - The saved values.
* @return One entry per change.
*/
function getSettingChanges(
before: StatsSettings,
edits: Partial< StatsSettings >
): SettingChange[] {
return ( Object.keys( edits ) as ( keyof StatsSettings )[] ).flatMap( setting => {
const value = edits[ setting ];
if ( ! Array.isArray( value ) ) {
return [ { setting, enabled: Boolean( value ) } ];
}
const previous = before[ setting ] as string[];
return [
...value
.filter( role => ! previous.includes( role ) )
.map( role => ( { setting, enabled: true, role } ) ),
...previous
.filter( role => ! value.includes( role ) )
.map( role => ( { setting, enabled: false, role } ) ),
];
} );
}
/**
* The dashboard's Settings tab: the plan usage, the Stats settings, and where to switch Stats off.
*
* @return The Settings tab content.
*/
export function StatsSettingsPanel(): JSX.Element {
const premiumAnalytics = getScriptData()?.premium_analytics;
const roles = premiumAnalytics?.stats_settings?.roles;
const featuresUrl = premiumAnalytics?.stats_settings?.features_url;
const fields = useMemo( () => getFields( roles ?? [] ), [ roles ] );
const cardGroups = useMemo( getCardGroups, [] );
const formLayout = useMemo< Form >(
() => ( { layout: { type: 'card', isCollapsible: false }, fields: cardGroups } ),
[ cardGroups ]
);
const { settings, isError, saveChange } = useStatsSettings();
const trackEvent = useTrackEvent();
const { createSuccessNotice, createErrorNotice } = useDispatch( 'core/notices' );
const onChange = useCallback(
async ( edits: Partial< StatsSettings > ) => {
try {
await saveChange( edits );
} catch ( error ) {
const reason = getSiteErrorMessage( error );
createErrorNotice(
reason
? sprintf(
/* translators: %s: the reason the site gave. */
__( 'Your Stats settings could not be saved: %s', 'jetpack-premium-analytics-pkg' ),
reason
)
: __( 'Your Stats settings could not be saved.', 'jetpack-premium-analytics-pkg' ),
{ type: 'snackbar' }
);
return;
}
// DataForm only renders once the settings have loaded.
getSettingChanges( settings as StatsSettings, edits ).forEach( change =>
trackEvent( 'jetpack_premium_analytics_settings_changed', change )
);
createSuccessNotice( __( 'Settings saved.', 'jetpack-premium-analytics-pkg' ), {
type: 'snackbar',
} );
},
[ createErrorNotice, createSuccessNotice, saveChange, settings, trackEvent ]
);
let form: JSX.Element;
if ( settings ) {
form = (
<DataForm data={ settings } fields={ fields } form={ formLayout } onChange={ onChange } />
);
} else if ( isError ) {
form = (
<Notice.Root intent="error">
<Notice.Description>
{ __(
'Your Stats settings could not be loaded. Reload the page to try again.',
'jetpack-premium-analytics-pkg'
) }
</Notice.Description>
</Notice.Root>
);
} else E{
// DataForm has no loading state, so draw its cards from the same form config until the data arrives.
form = (
<Stack direction="column" gap="xl" aria-busy="true">
<VisuallyHidden role="status">
{ __( 'Loading your Stats settingsā¦', 'jetpack-premium-analytics-pkg' ) }
</VisuallyHidden>
{ cardGroups.map( group => (
<Card.Root key={ group.id }>
<Card.Header>
<Card.Title>{ group.label }</Card.Title>
</Card.Header>
<Card.Content>
<Spinner />
</Card.Content>
</Card.Root>
) ) }
</Stack>
);
}
return (
<Stack direction="column" gap="xl" className={ styles.root }>
{ /* Outside any widget, so outside the provider `WidgetRoot` mounts for widgets. */ }
<AnalyticsQueryClientProvider>
<PlanUsageCard />
</AnalyticsQueryClientProvider>
{ form }
{ featuresUrl && (
<Card.Root>
<Card.Header>
<Card.Title>{ __( 'Activation', 'jetpack-premium-analytics-pkg' ) }</Card.Title>
</Card.Header>
<Card.Content>
<Text>
{ createInterpolateElement(
__(
'Stats is a Jetpack feature. Activate or deactivate it from <link>Jetpack features</link>.',
'jetpack-premium-analytics-pkg'
),
{ link: <Link href={ featuresUrl } /> }
) }
</Text>
</Card.Content>
</Card.Root>
) }
</Stack>
);
}
|