From 90dc22e969afd61617434a1de9892d385215722b Mon Sep 17 00:00:00 2001 From: Chi-Hsuan Huang Date: Wed, 22 Jul 2026 15:32:56 +0800 Subject: [PATCH 1/3] refactor: share Stats widget error descriptions --- projects/packages/premium-analytics/AGENTS.md | 16 +++--- .../premium-analytics/changelog/wooa7s-1649 | 4 ++ .../helpers/__tests__/describe-error.test.ts | 38 ++++++++++++++ .../src/helpers/describe-error.ts | 51 +++++++++++++++++++ .../widgets-toolkit/src/helpers/index.ts | 1 + .../packages/widgets-toolkit/src/index.ts | 1 + .../widgets/devices/render.tsx | 14 +++-- .../widgets/devices/use-device-views.ts | 4 +- .../widgets/top-platforms/render.tsx | 24 ++++----- .../top-platforms/use-platform-views.ts | 4 +- .../widgets/utm-insights/render.tsx | 14 +++-- .../widgets/utm-insights/use-utm-insights.ts | 8 +-- 12 files changed, 138 insertions(+), 41 deletions(-) create mode 100644 projects/packages/premium-analytics/changelog/wooa7s-1649 create mode 100644 projects/packages/premium-analytics/packages/widgets-toolkit/src/helpers/__tests__/describe-error.test.ts create mode 100644 projects/packages/premium-analytics/packages/widgets-toolkit/src/helpers/describe-error.ts diff --git a/projects/packages/premium-analytics/AGENTS.md b/projects/packages/premium-analytics/AGENTS.md index 743f46b0031b..37a93e0518bb 100644 --- a/projects/packages/premium-analytics/AGENTS.md +++ b/projects/packages/premium-analytics/AGENTS.md @@ -532,7 +532,9 @@ the query factory — do not do it in the widget or the view hook. Render these states through `` 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 offer Retry: ```tsx @@ -566,8 +568,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 ``, > `isLoading && data.length === 0`, and `LeaderboardChart`'s `emptyStateText`. They are being > migrated to `` — 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** diff --git a/projects/packages/premium-analytics/changelog/wooa7s-1649 b/projects/packages/premium-analytics/changelog/wooa7s-1649 new file mode 100644 index 000000000000..0e9700489ed6 --- /dev/null +++ b/projects/packages/premium-analytics/changelog/wooa7s-1649 @@ -0,0 +1,4 @@ +Significance: patch +Type: changed + +Use consistent access and retry error states across Stats widgets. diff --git a/projects/packages/premium-analytics/packages/widgets-toolkit/src/helpers/__tests__/describe-error.test.ts b/projects/packages/premium-analytics/packages/widgets-toolkit/src/helpers/__tests__/describe-error.test.ts new file mode 100644 index 000000000000..d83394d0b8cd --- /dev/null +++ b/projects/packages/premium-analytics/packages/widgets-toolkit/src/helpers/__tests__/describe-error.test.ts @@ -0,0 +1,38 @@ +/** + * Internal dependencies + */ +import { describeError } from '../describe-error'; + +describe( 'describeError', () => { + it( 'describes a 403 as a neutral error without actions', () => { + const descriptor = describeError( + { error: 'unauthorized', status: 403 }, + { subject: 'device data', onRetry: jest.fn() } + ); + + expect( descriptor ).toEqual( { + description: "You don't have access to this data.", + } ); + expect( descriptor ).not.toHaveProperty( 'actions' ); + } ); + + it( 'describes a generic failure with subject copy and a retry action', () => { + const onRetry = jest.fn(); + const descriptor = describeError( { status: 500 }, { subject: 'platform data', onRetry } ); + + expect( descriptor.description ).toBe( + "We couldn't load platform data. Please try again in a moment." + ); + expect( descriptor.actions ).toEqual( [ { label: 'Retry', onClick: onRetry } ] ); + + descriptor.actions?.[ 0 ].onClick(); + expect( onRetry ).toHaveBeenCalledTimes( 1 ); + } ); + + it( 'keeps an unexpected 404 retryable', () => { + const onRetry = jest.fn(); + const descriptor = describeError( { status: 404 }, { subject: 'UTM data', onRetry } ); + + expect( descriptor.actions ).toEqual( [ { label: 'Retry', onClick: onRetry } ] ); + } ); +} ); diff --git a/projects/packages/premium-analytics/packages/widgets-toolkit/src/helpers/describe-error.ts b/projects/packages/premium-analytics/packages/widgets-toolkit/src/helpers/describe-error.ts new file mode 100644 index 000000000000..499c8dcbc171 --- /dev/null +++ b/projects/packages/premium-analytics/packages/widgets-toolkit/src/helpers/describe-error.ts @@ -0,0 +1,51 @@ +/** + * External dependencies + */ +import { getApiErrorStatus } from '@jetpack-premium-analytics/data'; +/** + * WordPress dependencies + */ +import { __, sprintf } from '@wordpress/i18n'; +/** + * Types + */ +import type { WidgetStateError } from '../components/widget-state'; + +interface DescribeErrorOptions { + subject: string; + onRetry: () => void; +} + +/** + * Map an API error to a Stats widget error descriptor. + * + * @param error - The failed query error. + * @param options - Error-state copy and retry options. + * @param options.subject - The data subject used in the retryable error copy. + * @param options.onRetry - Callback used by the retry action. + * @return The widget error descriptor. + */ +export function describeError( + error: unknown, + { subject, onRetry }: DescribeErrorOptions +): WidgetStateError { + if ( getApiErrorStatus( error ) === 403 ) { + return { + description: __( "You don't have access to this data.", 'jetpack-premium-analytics' ), + }; + } + + return { + description: sprintf( + /* translators: %s is the type of data that could not be loaded. */ + __( "We couldn't load %s. Please try again in a moment.", 'jetpack-premium-analytics' ), + subject + ), + actions: [ + { + label: __( 'Retry', 'jetpack-premium-analytics' ), + onClick: onRetry, + }, + ], + }; +} diff --git a/projects/packages/premium-analytics/packages/widgets-toolkit/src/helpers/index.ts b/projects/packages/premium-analytics/packages/widgets-toolkit/src/helpers/index.ts index 378ff0365980..8162c19f97d0 100644 --- a/projects/packages/premium-analytics/packages/widgets-toolkit/src/helpers/index.ts +++ b/projects/packages/premium-analytics/packages/widgets-toolkit/src/helpers/index.ts @@ -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'; diff --git a/projects/packages/premium-analytics/packages/widgets-toolkit/src/index.ts b/projects/packages/premium-analytics/packages/widgets-toolkit/src/index.ts index 773ac93a25bb..60e7242d13ef 100644 --- a/projects/packages/premium-analytics/packages/widgets-toolkit/src/index.ts +++ b/projects/packages/premium-analytics/packages/widgets-toolkit/src/index.ts @@ -131,6 +131,7 @@ export { getVideoKey, getVideoLabel, toMaxRows, + describeError, summaryCount, toDay, defaultPeriodForInterval, diff --git a/projects/packages/premium-analytics/widgets/devices/render.tsx b/projects/packages/premium-analytics/widgets/devices/render.tsx index fabf16b32ed7..4fdf2448af1f 100644 --- a/projects/packages/premium-analytics/widgets/devices/render.tsx +++ b/projects/packages/premium-analytics/widgets/devices/render.tsx @@ -9,6 +9,7 @@ import { device } from '@jetpack-premium-analytics/icons'; import { __ } from '@wordpress/i18n'; import { Legend, + describeError, SemiCircleChart, WidgetRoot, WidgetState, @@ -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', @@ -94,13 +95,10 @@ function DevicesInner( { max }: DevicesInnerProps ) { isFetching={ isFetching } isError={ isError } isEmpty={ data.length === 0 } - error={ { - description: __( - "We couldn't load device data. Please try again in a moment.", - 'jetpack-premium-analytics' - ), - actions: [ { label: __( 'Retry', 'jetpack-premium-analytics' ), onClick: refetch } ], - } } + error={ describeError( error, { + subject: __( 'device data', 'jetpack-premium-analytics' ), + onRetry: refetch, + } ) } empty={ { icon: device, description: __( 'No device data in this period.', 'jetpack-premium-analytics' ), diff --git a/projects/packages/premium-analytics/widgets/devices/use-device-views.ts b/projects/packages/premium-analytics/widgets/devices/use-device-views.ts index c61f35ad993c..d03a7c7e1706 100644 --- a/projects/packages/premium-analytics/widgets/devices/use-device-views.ts +++ b/projects/packages/premium-analytics/widgets/devices/use-device-views.ts @@ -41,6 +41,7 @@ interface DeviceViewsState { isLoading: boolean; isFetching: boolean; isError: boolean; + error: unknown; refetch: () => void; } @@ -88,7 +89,7 @@ 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 ); @@ -103,6 +104,7 @@ export default function useDeviceViews( { // 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, + error, refetch, }; } diff --git a/projects/packages/premium-analytics/widgets/top-platforms/render.tsx b/projects/packages/premium-analytics/widgets/top-platforms/render.tsx index 75519979c801..272ce2b4fbfc 100644 --- a/projects/packages/premium-analytics/widgets/top-platforms/render.tsx +++ b/projects/packages/premium-analytics/widgets/top-platforms/render.tsx @@ -9,6 +9,7 @@ import { __ } from '@wordpress/i18n'; import { Stack, Text } from '@wordpress/ui'; import { calculateDelta, + describeError, LeaderboardChart, sharePercentage, WidgetRoot, @@ -55,11 +56,13 @@ type TopPlatformsInnerProps = { function TopPlatformsInner( { max, platformDimension }: TopPlatformsInnerProps ) { const { reportParams } = useWidgetRootContext(); - const { data, hasComparison, isLoading, isFetching, isError, refetch } = usePlatformViews( { - reportParams, - max, - deviceProperty: platformDimension, - } ); + const { data, hasComparison, isLoading, isFetching, isError, error, refetch } = usePlatformViews( + { + reportParams, + max, + deviceProperty: platformDimension, + } + ); const maxViews = Math.max( ...data.map( d => d.views ), 0 ); const maxComparisonViews = Math.max( ...data.map( d => d.previousViews ?? 0 ), 0 ); @@ -95,13 +98,10 @@ function TopPlatformsInner( { max, platformDimension }: TopPlatformsInnerProps ) isFetching={ isFetching } isError={ isError } isEmpty={ data.length === 0 } - error={ { - description: __( - "We couldn't load platform data. Please try again in a moment.", - 'jetpack-premium-analytics' - ), - actions: [ { label: __( 'Retry', 'jetpack-premium-analytics' ), onClick: refetch } ], - } } + error={ describeError( error, { + subject: __( 'platform data', 'jetpack-premium-analytics' ), + onRetry: refetch, + } ) } empty={ { icon: device, description: __( 'No platform data in this period.', 'jetpack-premium-analytics' ), diff --git a/projects/packages/premium-analytics/widgets/top-platforms/use-platform-views.ts b/projects/packages/premium-analytics/widgets/top-platforms/use-platform-views.ts index 022e2ebc882b..cb42875de8bb 100644 --- a/projects/packages/premium-analytics/widgets/top-platforms/use-platform-views.ts +++ b/projects/packages/premium-analytics/widgets/top-platforms/use-platform-views.ts @@ -37,6 +37,7 @@ interface PlatformViewsState { isLoading: boolean; isFetching: boolean; isError: boolean; + error: unknown; refetch: () => void; } @@ -99,7 +100,7 @@ export default function usePlatformViews( { deviceProperty, }; - const { comparisonRows, hasComparison, isLoading, isFetching, isError, refetch } = + const { comparisonRows, hasComparison, isLoading, isFetching, isError, error, refetch } = useStatsDevices( statsParams, { maxRows: max } ); const rows = ( comparisonRows?.rows ?? [] ).map( item => toPlatformView( item, deviceProperty ) ); @@ -114,6 +115,7 @@ export default function usePlatformViews( { // 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: rows.length === 0 && isError, + error, refetch, }; } diff --git a/projects/packages/premium-analytics/widgets/utm-insights/render.tsx b/projects/packages/premium-analytics/widgets/utm-insights/render.tsx index 0c3541fe30a4..820cb0cd5532 100644 --- a/projects/packages/premium-analytics/widgets/utm-insights/render.tsx +++ b/projects/packages/premium-analytics/widgets/utm-insights/render.tsx @@ -6,6 +6,7 @@ import { __, sprintf } from '@wordpress/i18n'; import { Stack, Text } from '@wordpress/ui'; import { calculateDelta, + describeError, LeaderboardChart, ReportLink, WidgetBackLink, @@ -92,7 +93,7 @@ function UtmInsightsInner( { utmDimension, max }: UtmInsightsInnerProps ) { clearSelectedUtm(); }, [ clearSelectedUtm, utmDimension ] ); - const { data, hasComparison, isLoading, isFetching, isError, refetch } = useUtmInsights( { + const { data, hasComparison, isLoading, isFetching, isError, error, refetch } = useUtmInsights( { reportParams, utmParam: utmDimension, max, @@ -177,13 +178,10 @@ function UtmInsightsInner( { utmDimension, max }: UtmInsightsInnerProps ) { isFetching={ isFetching } isError={ isError } isEmpty={ data.length === 0 } - error={ { - description: __( - "We couldn't load UTM data. Please try again in a moment.", - 'jetpack-premium-analytics' - ), - actions: [ { label: __( 'Retry', 'jetpack-premium-analytics' ), onClick: refetch } ], - } } + error={ describeError( error, { + subject: __( 'UTM data', 'jetpack-premium-analytics' ), + onRetry: refetch, + } ) } empty={ { icon: megaphone, description: __( 'No UTM data in this period.', 'jetpack-premium-analytics' ), diff --git a/projects/packages/premium-analytics/widgets/utm-insights/use-utm-insights.ts b/projects/packages/premium-analytics/widgets/utm-insights/use-utm-insights.ts index 8c998b3282a3..f841cbf32c86 100644 --- a/projects/packages/premium-analytics/widgets/utm-insights/use-utm-insights.ts +++ b/projects/packages/premium-analytics/widgets/utm-insights/use-utm-insights.ts @@ -45,6 +45,7 @@ interface UtmInsightsState { isLoading: boolean; isFetching: boolean; isError: boolean; + error: unknown; refetch: () => void; } @@ -83,10 +84,8 @@ export default function useUtmInsights( { max, }: UseUtmInsightsArgs ): UtmInsightsState { const params = { ...reportParams, utmParam, max } as Parameters< typeof useStatsUtm >[ 0 ]; - const { comparisonRows, hasComparison, isLoading, isFetching, isError, refetch } = useStatsUtm( - params, - { maxRows: max } - ); + const { comparisonRows, hasComparison, isLoading, isFetching, isError, error, refetch } = + useStatsUtm( params, { maxRows: max } ); const rows = ( comparisonRows?.rows ?? [] ).map( toUtmRow ); return { @@ -97,6 +96,7 @@ export default function useUtmInsights( { // Stats queries keep previous data via `placeholderData`, so a failed // range refetch should not replace populated rows with the error state. isError: rows.length === 0 && isError, + error, refetch, }; } From 2c2dc9e23cc9d5d7883059c5062dc08f68998bb2 Mon Sep 17 00:00:00 2001 From: Chi-Hsuan Huang Date: Wed, 22 Jul 2026 16:03:25 +0800 Subject: [PATCH 2/3] fix: keep no_connection 403 retryable, gate hook errors, use full-sentence retry copy --- projects/packages/premium-analytics/AGENTS.md | 9 +++- .../helpers/__tests__/describe-error.test.ts | 46 +++++++++++++++---- .../src/helpers/describe-error.ts | 28 +++++------ .../widgets/devices/render.tsx | 5 +- .../widgets/devices/use-device-views.ts | 15 +++--- .../__tests__/search-terms.test.tsx | 1 + .../widgets/search-terms/render.tsx | 18 ++++---- .../search-terms/use-search-term-views.ts | 16 +++++-- .../widgets/top-platforms/render.tsx | 5 +- .../top-platforms/use-platform-views.ts | 15 +++--- .../widgets/utm-insights/render.tsx | 5 +- .../widgets/utm-insights/use-utm-insights.ts | 11 +++-- 12 files changed, 117 insertions(+), 57 deletions(-) diff --git a/projects/packages/premium-analytics/AGENTS.md b/projects/packages/premium-analytics/AGENTS.md index 37a93e0518bb..56afc5276560 100644 --- a/projects/packages/premium-analytics/AGENTS.md +++ b/projects/packages/premium-analytics/AGENTS.md @@ -534,7 +534,9 @@ Render these states through `` from `@jetpack-premium-analytics/wid rather than hand-rolling `if ( isError )` / empty branches or a `WidgetLoadingOverlay`. Map the 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 offer Retry: +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 { it( 'describes a 403 as a neutral error without actions', () => { const descriptor = describeError( { error: 'unauthorized', status: 403 }, - { subject: 'device data', onRetry: jest.fn() } + { retryDescription: RETRY_DESCRIPTION, onRetry: jest.fn() } ); expect( descriptor ).toEqual( { @@ -16,23 +18,49 @@ describe( 'describeError', () => { expect( descriptor ).not.toHaveProperty( 'actions' ); } ); - it( 'describes a generic failure with subject copy and a retry action', () => { + it( 'keeps a no_connection 403 retryable — a broken connection can heal', () => { const onRetry = jest.fn(); - const descriptor = describeError( { status: 500 }, { subject: 'platform data', onRetry } ); - - expect( descriptor.description ).toBe( - "We couldn't load platform data. Please try again in a moment." + 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 } + ); - descriptor.actions?.[ 0 ].onClick(); - expect( onRetry ).toHaveBeenCalledTimes( 1 ); + 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 }, { subject: 'UTM data', onRetry } ); + 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 } ] ); + } + } ); } ); diff --git a/projects/packages/premium-analytics/packages/widgets-toolkit/src/helpers/describe-error.ts b/projects/packages/premium-analytics/packages/widgets-toolkit/src/helpers/describe-error.ts index 499c8dcbc171..bc949f4ef762 100644 --- a/projects/packages/premium-analytics/packages/widgets-toolkit/src/helpers/describe-error.ts +++ b/projects/packages/premium-analytics/packages/widgets-toolkit/src/helpers/describe-error.ts @@ -1,46 +1,46 @@ /** * External dependencies */ -import { getApiErrorStatus } from '@jetpack-premium-analytics/data'; +import { getApiErrorCode, getApiErrorStatus } from '@jetpack-premium-analytics/data'; /** * WordPress dependencies */ -import { __, sprintf } from '@wordpress/i18n'; +import { __ } from '@wordpress/i18n'; /** * Types */ import type { WidgetStateError } from '../components/widget-state'; interface DescribeErrorOptions { - subject: string; + retryDescription: string; onRetry: () => void; } /** * Map an API error to a Stats widget error descriptor. * - * @param error - The failed query error. - * @param options - Error-state copy and retry options. - * @param options.subject - The data subject used in the retryable error copy. - * @param options.onRetry - Callback used by the retry action. + * 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, - { subject, onRetry }: DescribeErrorOptions + { retryDescription, onRetry }: DescribeErrorOptions ): WidgetStateError { - if ( getApiErrorStatus( error ) === 403 ) { + if ( getApiErrorStatus( error ) === 403 && getApiErrorCode( error ) !== 'no_connection' ) { return { description: __( "You don't have access to this data.", 'jetpack-premium-analytics' ), }; } return { - description: sprintf( - /* translators: %s is the type of data that could not be loaded. */ - __( "We couldn't load %s. Please try again in a moment.", 'jetpack-premium-analytics' ), - subject - ), + description: retryDescription, actions: [ { label: __( 'Retry', 'jetpack-premium-analytics' ), diff --git a/projects/packages/premium-analytics/widgets/devices/render.tsx b/projects/packages/premium-analytics/widgets/devices/render.tsx index 4fdf2448af1f..96d3295de328 100644 --- a/projects/packages/premium-analytics/widgets/devices/render.tsx +++ b/projects/packages/premium-analytics/widgets/devices/render.tsx @@ -96,7 +96,10 @@ function DevicesInner( { max }: DevicesInnerProps ) { isError={ isError } isEmpty={ data.length === 0 } error={ describeError( error, { - subject: __( 'device data', 'jetpack-premium-analytics' ), + retryDescription: __( + "We couldn't load device data. Please try again in a moment.", + 'jetpack-premium-analytics' + ), onRetry: refetch, } ) } empty={ { diff --git a/projects/packages/premium-analytics/widgets/devices/use-device-views.ts b/projects/packages/premium-analytics/widgets/devices/use-device-views.ts index d03a7c7e1706..c93cb8887b60 100644 --- a/projects/packages/premium-analytics/widgets/devices/use-device-views.ts +++ b/projects/packages/premium-analytics/widgets/devices/use-device-views.ts @@ -94,17 +94,20 @@ export default function useDeviceViews( { 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, - error, + isError: showError, + error: showError ? error : null, refetch, }; } diff --git a/projects/packages/premium-analytics/widgets/search-terms/__tests__/search-terms.test.tsx b/projects/packages/premium-analytics/widgets/search-terms/__tests__/search-terms.test.tsx index 5f9f999bc53c..c544078dfad9 100644 --- a/projects/packages/premium-analytics/widgets/search-terms/__tests__/search-terms.test.tsx +++ b/projects/packages/premium-analytics/widgets/search-terms/__tests__/search-terms.test.tsx @@ -21,6 +21,7 @@ describe( 'SearchTermsWidget', () => { isLoading: false, isFetching: false, isError: false, + error: null, hasComparison: false, refetch: jest.fn(), } ); diff --git a/projects/packages/premium-analytics/widgets/search-terms/render.tsx b/projects/packages/premium-analytics/widgets/search-terms/render.tsx index d02512af889f..59a132194605 100644 --- a/projects/packages/premium-analytics/widgets/search-terms/render.tsx +++ b/projects/packages/premium-analytics/widgets/search-terms/render.tsx @@ -3,6 +3,7 @@ */ import { calculateDelta, + describeError, LeaderboardChart, ReportLink, WidgetFooter, @@ -37,10 +38,11 @@ type SearchTermsWidgetProps = WidgetRenderProps< SearchTermsRenderAttributes >; function SearchTermsInner( { max = 10 }: SearchTermsAttributes ) { const { reportParams } = useWidgetRootContext(); - const { data, isLoading, isFetching, isError, hasComparison, refetch } = useSearchTermViews( { - reportParams, - max, - } ); + const { data, isLoading, isFetching, isError, error, hasComparison, refetch } = + useSearchTermViews( { + reportParams, + max, + } ); const leaderboardData = useMemo< LeaderboardChartData >( () => { const maxValue = Math.max( ...data.map( t => t.views ), 0 ); @@ -79,13 +81,13 @@ function SearchTermsInner( { max = 10 }: SearchTermsAttributes ) { isFetching={ isFetching } isError={ isError } isEmpty={ data.length === 0 } - error={ { - description: __( + error={ describeError( error, { + retryDescription: __( "We couldn't load search terms. Please try again in a moment.", 'jetpack-premium-analytics' ), - actions: [ { label: __( 'Retry', 'jetpack-premium-analytics' ), onClick: refetch } ], - } } + onRetry: refetch, + } ) } empty={ { icon: search, description: __( 'No search terms in this period.', 'jetpack-premium-analytics' ), diff --git a/projects/packages/premium-analytics/widgets/search-terms/use-search-term-views.ts b/projects/packages/premium-analytics/widgets/search-terms/use-search-term-views.ts index bf1c3f5d89fd..74dc55f75a80 100644 --- a/projects/packages/premium-analytics/widgets/search-terms/use-search-term-views.ts +++ b/projects/packages/premium-analytics/widgets/search-terms/use-search-term-views.ts @@ -26,6 +26,7 @@ interface SearchTermViewsState { isLoading: boolean; isFetching: boolean; isError: boolean; + error: unknown; hasComparison: boolean; refetch: () => void; } @@ -51,6 +52,7 @@ export default function useSearchTermViews( { isLoading, isFetching, isError: hasError, + error, refetch, } = useStatsSearchTerms( reportParams as Parameters< typeof useStatsSearchTerms >[ 0 ], { maxRows: max, @@ -63,15 +65,19 @@ export default function useSearchTermViews( { previousViews: comparisonUsable ? item.previousViews : undefined, } ) ); + // 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 && hasError; + return { data: items, 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 && hasError, + isError: showError, + error: showError ? error : null, hasComparison: comparisonUsable, refetch, }; diff --git a/projects/packages/premium-analytics/widgets/top-platforms/render.tsx b/projects/packages/premium-analytics/widgets/top-platforms/render.tsx index 272ce2b4fbfc..d15ef562936c 100644 --- a/projects/packages/premium-analytics/widgets/top-platforms/render.tsx +++ b/projects/packages/premium-analytics/widgets/top-platforms/render.tsx @@ -99,7 +99,10 @@ function TopPlatformsInner( { max, platformDimension }: TopPlatformsInnerProps ) isError={ isError } isEmpty={ data.length === 0 } error={ describeError( error, { - subject: __( 'platform data', 'jetpack-premium-analytics' ), + retryDescription: __( + "We couldn't load platform data. Please try again in a moment.", + 'jetpack-premium-analytics' + ), onRetry: refetch, } ) } empty={ { diff --git a/projects/packages/premium-analytics/widgets/top-platforms/use-platform-views.ts b/projects/packages/premium-analytics/widgets/top-platforms/use-platform-views.ts index cb42875de8bb..94c8472f5c1b 100644 --- a/projects/packages/premium-analytics/widgets/top-platforms/use-platform-views.ts +++ b/projects/packages/premium-analytics/widgets/top-platforms/use-platform-views.ts @@ -105,17 +105,20 @@ export default function usePlatformViews( { const rows = ( comparisonRows?.rows ?? [] ).map( item => toPlatformView( item, deviceProperty ) ); + // 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 = rows.length === 0 && isError; + return { data: rows, 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: rows.length === 0 && isError, - error, + isError: showError, + error: showError ? error : null, refetch, }; } diff --git a/projects/packages/premium-analytics/widgets/utm-insights/render.tsx b/projects/packages/premium-analytics/widgets/utm-insights/render.tsx index 820cb0cd5532..9b789f28d3f5 100644 --- a/projects/packages/premium-analytics/widgets/utm-insights/render.tsx +++ b/projects/packages/premium-analytics/widgets/utm-insights/render.tsx @@ -179,7 +179,10 @@ function UtmInsightsInner( { utmDimension, max }: UtmInsightsInnerProps ) { isError={ isError } isEmpty={ data.length === 0 } error={ describeError( error, { - subject: __( 'UTM data', 'jetpack-premium-analytics' ), + retryDescription: __( + "We couldn't load UTM data. Please try again in a moment.", + 'jetpack-premium-analytics' + ), onRetry: refetch, } ) } empty={ { diff --git a/projects/packages/premium-analytics/widgets/utm-insights/use-utm-insights.ts b/projects/packages/premium-analytics/widgets/utm-insights/use-utm-insights.ts index f841cbf32c86..d5b932d68b61 100644 --- a/projects/packages/premium-analytics/widgets/utm-insights/use-utm-insights.ts +++ b/projects/packages/premium-analytics/widgets/utm-insights/use-utm-insights.ts @@ -88,15 +88,18 @@ export default function useUtmInsights( { useStatsUtm( params, { maxRows: max } ); const rows = ( comparisonRows?.rows ?? [] ).map( toUtmRow ); + // Stats queries keep previous data via `placeholderData`, so a failed + // range refetch should not replace populated rows with the error state. + // `error` is gated by the same predicate so it is populated iff `isError` is true. + const showError = rows.length === 0 && isError; + return { data: rows, hasComparison, isLoading, isFetching, - // Stats queries keep previous data via `placeholderData`, so a failed - // range refetch should not replace populated rows with the error state. - isError: rows.length === 0 && isError, - error, + isError: showError, + error: showError ? error : null, refetch, }; } From edc25636808c9453c64df2bf0bd825c3d5202c11 Mon Sep 17 00:00:00 2001 From: Chi-Hsuan Huang Date: Mon, 27 Jul 2026 11:09:32 +0800 Subject: [PATCH 3/3] test: add retryable error stories for the shared Stats error mapper --- projects/packages/premium-analytics/AGENTS.md | 14 ++++++++----- .../stories/mocks/register-report-mocks.ts | 21 +++++++++++++++---- .../stories/devices-widget.stories.tsx | 20 ++++++++++++++++-- .../stories/search-terms-widget.stories.tsx | 20 ++++++++++++++++-- .../widgets/stories/force-stats-mock-state.ts | 18 ++++++++++++++-- .../stories/top-platforms-widget.stories.tsx | 20 ++++++++++++++++-- .../stories/utm-insights-widget.stories.tsx | 20 ++++++++++++++++-- 7 files changed, 114 insertions(+), 19 deletions(-) diff --git a/projects/packages/premium-analytics/AGENTS.md b/projects/packages/premium-analytics/AGENTS.md index 56afc5276560..9e8e1bae10c9 100644 --- a/projects/packages/premium-analytics/AGENTS.md +++ b/projects/packages/premium-analytics/AGENTS.md @@ -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( '', '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( '', '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 diff --git a/projects/packages/premium-analytics/packages/widgets-toolkit/src/stories/mocks/register-report-mocks.ts b/projects/packages/premium-analytics/packages/widgets-toolkit/src/stories/mocks/register-report-mocks.ts index f2c28e34fe54..6123d7a0b551 100644 --- a/projects/packages/premium-analytics/packages/widgets-toolkit/src/stories/mocks/register-report-mocks.ts +++ b/projects/packages/premium-analytics/packages/widgets-toolkit/src/stories/mocks/register-report-mocks.ts @@ -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 >(); @@ -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.', diff --git a/projects/packages/premium-analytics/widgets/devices/stories/devices-widget.stories.tsx b/projects/packages/premium-analytics/widgets/devices/stories/devices-widget.stories.tsx index 7e0c553bbb9b..96d1dd29fd56 100644 --- a/projects/packages/premium-analytics/widgets/devices/stories/devices-widget.stories.tsx +++ b/projects/packages/premium-analytics/widgets/devices/stories/devices-widget.stories.tsx @@ -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' ), @@ -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."). diff --git a/projects/packages/premium-analytics/widgets/search-terms/stories/search-terms-widget.stories.tsx b/projects/packages/premium-analytics/widgets/search-terms/stories/search-terms-widget.stories.tsx index 5a78e2400040..50af05f66b2e 100644 --- a/projects/packages/premium-analytics/widgets/search-terms/stories/search-terms-widget.stories.tsx +++ b/projects/packages/premium-analytics/widgets/search-terms/stories/search-terms-widget.stories.tsx @@ -104,8 +104,9 @@ export const Loading: Story = { }; /** - * 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: Story = { render: () => renderSearchTermsOnPreset( 'last-7-days' ), @@ -117,6 +118,21 @@ export const Error: Story = { }, }; +/** + * 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: Story = { + render: () => renderSearchTermsOnPreset( 'last-12-months' ), + tags: [ '!autodocs' ], + decorators: [ withWidgetCanvas, withStoryRouter ], + beforeEach: () => { + setReportMockState( 'stats/search-terms', 'error-retryable' ); + return () => setReportMockState( 'stats/search-terms', null ); + }, +}; + /** * Resolved with no rows: the widget shows its empty state (the neutral search * glyph and "No search terms in this period."). diff --git a/projects/packages/premium-analytics/widgets/stories/force-stats-mock-state.ts b/projects/packages/premium-analytics/widgets/stories/force-stats-mock-state.ts index 791d76bf864f..8829267f4491 100644 --- a/projects/packages/premium-analytics/widgets/stories/force-stats-mock-state.ts +++ b/projects/packages/premium-analytics/widgets/stories/force-stats-mock-state.ts @@ -4,7 +4,7 @@ import apiFetch from '@wordpress/api-fetch'; import type { APIFetchMiddleware, APIFetchOptions } from '@wordpress/api-fetch'; -type ForcedMockState = 'error' | 'loading' | 'empty'; +type ForcedMockState = 'error' | 'error-retryable' | 'loading' | 'empty'; const stateOverrides = new Map< string, ForcedMockState >(); @@ -24,8 +24,19 @@ const forcedStateMiddleware: 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 }, + } ); + } // A 403 is not retried by `shouldRetryApiError`, so the error UI shows at - // once instead of after the query's retry backoff. + // once instead of after the query's retry backoff. Widgets on `describeError` + // read this as a permission gate and drop their Retry action. return Promise.reject( { code: 'stats_mock_error', message: 'Mocked error response for Storybook.', @@ -64,6 +75,9 @@ const forcedStateMiddleware: APIFetchMiddleware = async ( options: APIFetchOptio * key carries no date params, a distinct preset can't isolate it — evict the * query from the shared client on enter and cleanup instead (see the * `latest-post` stories). + * - `'error'` mocks a permission-gated 403 and `'error-retryable'` the proxy's + * `no_connection` 403. Widgets on `describeError` render a Retry action only + * for the latter, so give those widgets a story for each. * * @param pathFragment - Substring matched against the request path (e.g. `stats/clicks`). * @param state - The forced state, or `null` to clear. diff --git a/projects/packages/premium-analytics/widgets/top-platforms/stories/top-platforms-widget.stories.tsx b/projects/packages/premium-analytics/widgets/top-platforms/stories/top-platforms-widget.stories.tsx index 888b375d5241..a9ea42a7a17a 100644 --- a/projects/packages/premium-analytics/widgets/top-platforms/stories/top-platforms-widget.stories.tsx +++ b/projects/packages/premium-analytics/widgets/top-platforms/stories/top-platforms-widget.stories.tsx @@ -154,8 +154,9 @@ export const Loading: StoryObj< TopPlatformsStoryControls > = { }; /** - * 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< TopPlatformsStoryControls > = { render: () => renderTopPlatformsOnPreset( 'last-7-days' ), @@ -167,6 +168,21 @@ export const Error: StoryObj< TopPlatformsStoryControls > = { }, }; +/** + * 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< TopPlatformsStoryControls > = { + render: () => renderTopPlatformsOnPreset( 'last-12-months' ), + tags: [ '!autodocs' ], + decorators: [ withWidgetCanvas ], + beforeEach: () => { + forceStatsMockState( 'stats/devices', 'error-retryable' ); + return () => forceStatsMockState( 'stats/devices', null ); + }, +}; + /** * Resolved with no rows: the widget shows its empty state (the neutral device * glyph and "No platform data in this period."). diff --git a/projects/packages/premium-analytics/widgets/utm-insights/stories/utm-insights-widget.stories.tsx b/projects/packages/premium-analytics/widgets/utm-insights/stories/utm-insights-widget.stories.tsx index 11fff2047c27..367fbcae889a 100644 --- a/projects/packages/premium-analytics/widgets/utm-insights/stories/utm-insights-widget.stories.tsx +++ b/projects/packages/premium-analytics/widgets/utm-insights/stories/utm-insights-widget.stories.tsx @@ -119,8 +119,9 @@ export const Loading: Story = { }; /** - * 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: Story = { render: () => renderUtmInsightsOnPreset( 'last-7-days' ), @@ -132,6 +133,21 @@ export const Error: Story = { }, }; +/** + * 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: Story = { + render: () => renderUtmInsightsOnPreset( 'last-12-months' ), + tags: [ '!autodocs' ], + decorators: [ withWidgetCanvas, withStoryRouter ], + beforeEach: () => { + forceStatsMockState( 'stats/utm', 'error-retryable' ); + return () => forceStatsMockState( 'stats/utm', null ); + }, +}; + /** * Resolved with no rows: the widget shows its empty state (the neutral megaphone * glyph and "No UTM data in this period.").