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
35 changes: 23 additions & 12 deletions projects/packages/premium-analytics/AGENTS.md
Original file line number Diff line number Diff line change
Expand Up @@ -463,13 +463,17 @@ module has a special failure mode. Prefer adding those shapes to the widget's ex
over creating one-off state stories unless the state needs direct review.

To review a widget's loading / error / empty state directly, force it with
`setReportMockState( '<endpoint>', 'loading' | 'error' | 'empty' )` in the story's `beforeEach`,
clearing it in the returned cleanup. Keep such stories off the shared autodocs page
(`tags: [ '!autodocs' ]`, since the override is keyed by path and would otherwise force the
sibling stories into the same state) and give each one a date preset distinct from the other
stories so it hits the mock fresh instead of reading their cached success. See
`setReportMockState( '<endpoint>', 'loading' | 'error' | 'error-retryable' | 'empty' )` in the
story's `beforeEach`, clearing it in the returned cleanup. Keep such stories off the shared
autodocs page (`tags: [ '!autodocs' ]`, since the override is keyed by path and would otherwise
force the sibling stories into the same state) and give each one a date preset distinct from the
other stories so it hits the mock fresh instead of reading their cached success. See
`widgets/search-terms/stories/` for the reference.

`error` mocks a permission-gated 403 and `error-retryable` the proxy's `no_connection` 403. A
widget that maps its error through `describeError` renders a Retry action only for the latter, so
give it a story for each; both mocks are 403s, so neither waits out the query's retry backoff.

### Widget pitfalls

- Putting new widgets under `packages/widgets-toolkit/src/widgets/*` — that path is for the
Expand Down Expand Up @@ -532,7 +536,11 @@ the query factory — do not do it in the widget or the view hook.

Render these states through `<WidgetState>` from `@jetpack-premium-analytics/widgets-toolkit`
rather than hand-rolling `if ( isError )` / empty branches or a `WidgetLoadingOverlay`. Map the
data/view hook's result to its four signals and pass generic descriptors:
data/view hook's result to its four signals. For Stats API errors, pass the raw `error` to the
shared `describeError()` mapper so 403 access failures have neutral copy and no retry action,
while other failures — including the proxy's `no_connection` 403, which can heal after
reconnecting — offer Retry. Pass the retryable copy as a full sentence (not a fragment
interpolated into a shared frame) so translators see the whole sentence:

```tsx
<WidgetState
Expand All @@ -541,10 +549,10 @@ data/view hook's result to its four signals and pass generic descriptors:
isEmpty={ data.length === 0 }
// isFetching is optional: a background refetch shows a non-blocking busy overlay
// over the existing rows instead of hiding them.
error={ {
description: __( "We couldn't load this data. Please try again in a moment.", 'jetpack-premium-analytics' ),
actions: [ { label: __( 'Retry', 'jetpack-premium-analytics' ), onClick: refetch } ],
} }
error={ describeError( error, {
retryDescription: __( "We couldn't load search terms. Please try again in a moment.", 'jetpack-premium-analytics' ),
onRetry: refetch,
} ) }
empty={ { icon: search, description: __( 'No search terms in this period.', 'jetpack-premium-analytics' ) } }
>
<LeaderboardChart … />
Expand All @@ -555,6 +563,9 @@ data/view hook's result to its four signals and pass generic descriptors:
`isFetching` and data are shown) and swaps only the content area. Notes:

- Expose `refetch` from the data/view hook so the error state's Retry can re-run the query.
- When a view hook masks `isError` (e.g. `rows.length === 0 && isError` to keep placeholder
rows), gate `error` with the same predicate (`error: showError ? error : null`) so the two
fields can't disagree.
- Give `empty.icon` a neutral glyph distinct from the error icon — the widget's own glyph from
`@jetpack-premium-analytics/icons` (e.g. `search`, `customer`); omit it for no icon. Don't use
a caution glyph: empty is not an error.
Expand All @@ -566,8 +577,8 @@ data/view hook's result to its four signals and pass generic descriptors:
> Many Stats widgets predate this and still hand-roll loading/empty via `<WidgetLoadingOverlay>`,
> `isLoading && data.length === 0`, and `LeaderboardChart`'s `emptyStateText`. They are being
> migrated to `<WidgetState>` — follow the contract above, not those widgets.
> `widgets/search-terms/render.tsx` is the reference. (A `describeError` mapper and a
> `ReportWidget` wrapper that remove the per-widget error/retry boilerplate are planned follow-ups.)
> `widgets/search-terms/render.tsx` is the reference. (A `ReportWidget` wrapper that removes the
> remaining per-widget state boilerplate is a planned follow-up.)

**Comparison data**

Expand Down
4 changes: 4 additions & 0 deletions projects/packages/premium-analytics/changelog/wooa7s-1649
Original file line number Diff line number Diff line change
@@ -0,0 +1,4 @@
Significance: patch
Type: changed

Use consistent access and retry error states across Stats widgets.
Original file line number Diff line number Diff line change
@@ -0,0 +1,66 @@
/**
* Internal dependencies
*/
import { describeError } from '../describe-error';

const RETRY_DESCRIPTION = "We couldn't load device data. Please try again in a moment.";

describe( 'describeError', () => {
it( 'describes a 403 as a neutral error without actions', () => {
const descriptor = describeError(
{ error: 'unauthorized', status: 403 },
{ retryDescription: RETRY_DESCRIPTION, onRetry: jest.fn() }
);

expect( descriptor ).toEqual( {
description: "You don't have access to this data.",
} );
expect( descriptor ).not.toHaveProperty( 'actions' );
} );

it( 'keeps a no_connection 403 retryable — a broken connection can heal', () => {
const onRetry = jest.fn();
const descriptor = describeError(
{ error: 'no_connection', status: 403 },
{ retryDescription: RETRY_DESCRIPTION, onRetry }
);

expect( descriptor.description ).toBe( RETRY_DESCRIPTION );
expect( descriptor.actions ).toEqual( [ { label: 'Retry', onClick: onRetry } ] );
} );

it( 'describes a generic failure with the retryable copy and a retry action', () => {
const onRetry = jest.fn();
const descriptor = describeError(
{ status: 500 },
{ retryDescription: RETRY_DESCRIPTION, onRetry }
);

expect( descriptor.description ).toBe( RETRY_DESCRIPTION );
expect( descriptor.actions ).toEqual( [ { label: 'Retry', onClick: onRetry } ] );
} );

it( 'keeps an unexpected 404 retryable', () => {
const onRetry = jest.fn();
const descriptor = describeError(
{ status: 404 },
{ retryDescription: RETRY_DESCRIPTION, onRetry }
);

expect( descriptor.actions ).toEqual( [ { label: 'Retry', onClick: onRetry } ] );
} );

it( 'returns the retryable descriptor when there is no error — widgets call it on every render', () => {
const onRetry = jest.fn();

for ( const noError of [ null, undefined ] ) {
const descriptor = describeError( noError, {
retryDescription: RETRY_DESCRIPTION,
onRetry,
} );

expect( descriptor.description ).toBe( RETRY_DESCRIPTION );
expect( descriptor.actions ).toEqual( [ { label: 'Retry', onClick: onRetry } ] );
}
} );
} );
Original file line number Diff line number Diff line change
@@ -0,0 +1,51 @@
/**
* External dependencies
*/
import { getApiErrorCode, getApiErrorStatus } from '@jetpack-premium-analytics/data';
/**
* WordPress dependencies
*/
import { __ } from '@wordpress/i18n';
/**
* Types
*/
import type { WidgetStateError } from '../components/widget-state';

interface DescribeErrorOptions {
retryDescription: string;
onRetry: () => void;
}

/**
* Map an API error to a Stats widget error descriptor.
*
* A 403 is a deterministic access failure, so it gets neutral copy and no retry
* action — except the proxy's `no_connection` 403, which flags a broken Jetpack
* connection that can heal, so it stays retryable like any other failure.
*
* @param error - The failed query error.
* @param options - Error-state copy and retry options.
* @param options.retryDescription - The full-sentence copy for the retryable error state.
* @param options.onRetry - Callback used by the retry action.
* @return The widget error descriptor.
*/
export function describeError(
error: unknown,
{ retryDescription, onRetry }: DescribeErrorOptions
): WidgetStateError {
if ( getApiErrorStatus( error ) === 403 && getApiErrorCode( error ) !== 'no_connection' ) {

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Non-blocking: The Storybook error mocks return a 403, so these stories no longer show Retry as their descriptions claim. Maybe update the descriptions and add a retryable 500/no_connection story?

@chihsuan chihsuan Jul 27, 2026 •

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Good catch — confirmed. Both mock helpers reject with a 403 whose code isn't no_connection, so those four stories were rendering the neutral no-access copy while their descriptions still promised a Retry.

Fixed in edc2563

return {
description: __( "You don't have access to this data.", 'jetpack-premium-analytics' ),
};
}

return {
description: retryDescription,
actions: [
{
label: __( 'Retry', 'jetpack-premium-analytics' ),
onClick: onRetry,
},
],
};
}
Original file line number Diff line number Diff line change
Expand Up @@ -50,6 +50,7 @@ export { buildCsv, buildCsvDateRangeFilename, saveCsv, type CsvColumn } from './
export { sharePercentage } from './share-percentage';
export { getVideoKey, getVideoLabel } from './video-plays';
export { toMaxRows } from './to-max-rows';
export { describeError } from './describe-error';
export { summaryCount } from './summary-count';
export { toDay } from './to-day';
export { defaultPeriodForInterval } from './default-period-for-interval';
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -131,6 +131,7 @@ export {
getVideoKey,
getVideoLabel,
toMaxRows,
describeError,
summaryCount,
toDay,
defaultPeriodForInterval,
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -156,11 +156,13 @@ const requestCounters: Record< string, number > = {};

/**
* Forced response state for a request path fragment, so stories can exercise a
* widget's loading, error, and empty UI. `error` rejects the request; `loading`
* returns a promise that never settles; `empty` resolves with a valid response
* that has no rows.
* widget's loading, error, and empty UI. `error` rejects the request with a
* permission-gated 403; `error-retryable` rejects it with the proxy's
* `no_connection` 403, which widgets on `describeError` render with a Retry
* action; `loading` returns a promise that never settles; `empty` resolves with
* a valid response that has no rows.
*/
type ReportMockState = 'error' | 'loading' | 'empty';
type ReportMockState = 'error' | 'error-retryable' | 'loading' | 'empty';

const mockStateOverrides = new Map< string, ReportMockState >();

Expand Down Expand Up @@ -1255,9 +1257,20 @@ const reportMocksMiddleware: APIFetchMiddleware = async ( options: APIFetchOptio
// (`summary` / `days` / `data`), so the widget resolves to its empty state.
return { date: '2026-01-01', period: 'day', summary: {}, days: {}, data: [] };
}
if ( state === 'error-retryable' ) {
// The local proxy's `no_connection` shape. Still a 403, so the error UI
// shows at once, but `describeError` keeps it retryable: a broken Jetpack
// connection can heal, unlike a permission gate.
return Promise.reject( {
code: 'no_connection',
message: 'Mocked connection failure for Storybook.',
data: { status: 403 },
} );
}
// The WPCOM pass-through error envelope, with the status attached the way
// the fetch layer attaches it. A 403 is not retried by `shouldRetryApiError`,
// so the error UI shows at once instead of after the query's retry backoff.
// Widgets on `describeError` read it as a permission gate and drop Retry.
return Promise.reject( {
error: 'unauthorized',
message: 'Mocked error response for Storybook.',
Expand Down
11 changes: 6 additions & 5 deletions projects/packages/premium-analytics/widgets/devices/render.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,7 @@ import { device } from '@jetpack-premium-analytics/icons';
import { __ } from '@wordpress/i18n';
import {
Legend,
describeError,
SemiCircleChart,
WidgetRoot,
WidgetState,
Expand Down Expand Up @@ -56,7 +57,7 @@ type DevicesInnerProps = {
*/
function DevicesInner( { max }: DevicesInnerProps ) {
const { reportParams } = useWidgetRootContext();
const { data, hasComparison, isLoading, isFetching, isError, refetch } = useDeviceViews( {
const { data, hasComparison, isLoading, isFetching, isError, error, refetch } = useDeviceViews( {
reportParams,
max,
deviceProperty: 'screensize',
Expand Down Expand Up @@ -94,13 +95,13 @@ function DevicesInner( { max }: DevicesInnerProps ) {
isFetching={ isFetching }
isError={ isError }
isEmpty={ data.length === 0 }
error={ {
description: __(
error={ describeError( error, {
retryDescription: __(
"We couldn't load device data. Please try again in a moment.",
'jetpack-premium-analytics'
),
actions: [ { label: __( 'Retry', 'jetpack-premium-analytics' ), onClick: refetch } ],
} }
onRetry: refetch,
} ) }
empty={ {
icon: device,
description: __( 'No device data in this period.', 'jetpack-premium-analytics' ),
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -122,8 +122,9 @@ export const Loading: StoryObj< DevicesStoryControls > = {
};

/**
* The fetch failed: the widget shows its error state with a Retry action (which
* re-runs the query — still mocked as failing while this story is active).
* The fetch failed with a permission-gated 403: the widget shows the neutral
* "You don't have access to this data." copy and no Retry action, since a
* permission gate is deterministic and retrying cannot clear it.
*/
export const Error: StoryObj< DevicesStoryControls > = {
render: () => renderDevicesOnPreset( 'last-7-days' ),
Expand All @@ -135,6 +136,21 @@ export const Error: StoryObj< DevicesStoryControls > = {
},
};

/**
* The fetch failed in a way that can heal — the proxy's `no_connection` 403: the
* widget shows its retryable copy with a Retry action, which re-runs the query
* (still mocked as failing while this story is active).
*/
export const ErrorRetryable: StoryObj< DevicesStoryControls > = {
render: () => renderDevicesOnPreset( 'last-12-months' ),
tags: [ '!autodocs' ],
decorators: [ withWidgetCanvas ],
beforeEach: () => {
forceStatsMockState( 'stats/devices/screensize', 'error-retryable' );
return () => forceStatsMockState( 'stats/devices/screensize', null );
},
};

/**
* Resolved with no rows: the widget shows its empty state (the neutral device
* glyph and "No device data in this period.").
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -41,6 +41,7 @@ interface DeviceViewsState {
isLoading: boolean;
isFetching: boolean;
isError: boolean;
error: unknown;
refetch: () => void;
}

Expand Down Expand Up @@ -88,21 +89,25 @@ export default function useDeviceViews( {
deviceProperty,
};

const { comparisonRows, hasComparison, isLoading, isFetching, isError, refetch } =
const { comparisonRows, hasComparison, isLoading, isFetching, isError, error, refetch } =
useStatsDevices( statsParams, { maxRows: max } );

const items = ( comparisonRows?.rows ?? [] ).map( toDeviceView );

// The Stats queries carry `placeholderData: previousData => previousData`, so a
// failed range change keeps the prior period's rows in `data` while `isError`
// flips true. Only surface the error when there's nothing to show, so a transient
// refetch failure doesn't replace populated rows with the error state. `error` is
// gated by the same predicate so it is populated iff `isError` is true.
const showError = items.length === 0 && isError;

return {
data: items,
hasComparison,
isLoading,
isFetching,
// The Stats queries carry `placeholderData: previousData => previousData`, so a
// failed range change keeps the prior period's rows in `data` while `isError`
// flips true. Only surface the error when there's nothing to show, so a transient
// refetch failure doesn't replace populated rows with the error state.
isError: items.length === 0 && isError,
isError: showError,
error: showError ? error : null,
refetch,
};
}
Original file line number Diff line number Diff line change
Expand Up @@ -21,6 +21,7 @@ describe( 'SearchTermsWidget', () => {
isLoading: false,
isFetching: false,
isError: false,
error: null,
hasComparison: false,
refetch: jest.fn(),
} );
Expand Down
Loading