From 0af5cfd89baa05653979ef7b3c5e97b2c90d35dc Mon Sep 17 00:00:00 2001 From: Jeremy Herve Date: Tue, 20 Oct 2026 14:56:27 +0200 Subject: [PATCH 1/4] Sharing & Likes: Move the React settings screen off TanStack Query The screen now keeps status, settings and services in one @wordpress/data store, following Newsletter's settings screen: plain apiFetch calls, no TanStack Query and no core-data. wp-data already loads as a shared script, whereas TanStack was bundled into the route, and core-data would have pulled the block editor's scripts onto the page. What TanStack did for the screen is rebuilt in the store: - Every write goes through one queue per registry, so requests reach the server one at a time, in order, rereads included. - Saves stay optimistic. A refused save rolls back only its own value, and a response landing while another save of the same kind waits leaves that save's value alone. - Each local change bumps a version, so a read already in flight is dropped instead of landing on top of it. - A pending-write count drives the unsaved-changes warning. The hooks keep their names and return shapes, so sections and the services manager are unchanged. The route bundle loses about 35 KB minified (9 KB gzipped). --- pnpm-lock.yaml | 3 - projects/packages/sharing-likes/AGENTS.md | 8 +- .../update-sharing-likes-drop-tanstack | 4 + projects/packages/sharing-likes/package.json | 1 - .../routes/settings/package.json | 1 - .../sharing-likes/routes/settings/stage.tsx | 14 +- .../src/settings-app/data/queries.ts | 89 ++-- .../src/settings-app/data/store.ts | 228 ++++++++++ .../settings-app/data/use-custom-service.ts | 143 +----- .../settings-app/data/use-feature-action.ts | 85 +--- .../settings-app/data/use-save-services.ts | 123 +----- .../src/settings-app/data/use-save-setting.ts | 65 +-- .../src/settings-app/data/writes.ts | 415 ++++++++++++++++++ .../src/settings-app/settings-screen.tsx | 5 +- .../test/comment-likes-section.test.tsx | 3 +- .../test/feature-variant.test.tsx | 3 +- .../src/settings-app/test/helpers.tsx | 90 ++-- .../test/like-buttons-section.test.tsx | 2 - .../test/placement-section.test.tsx | 10 +- .../test/services-manager.test.tsx | 11 +- .../test/settings-screen.test.tsx | 3 +- .../test/sharing-buttons-section.test.tsx | 10 +- .../settings-app/test/text-setting.test.tsx | 15 +- .../test/use-custom-service.test.tsx | 23 +- .../test/use-feature-action.test.tsx | 114 ++--- .../test/use-save-services.test.tsx | 51 +-- .../test/use-save-setting.test.tsx | 45 +- 27 files changed, 889 insertions(+), 675 deletions(-) create mode 100644 projects/packages/sharing-likes/changelog/update-sharing-likes-drop-tanstack create mode 100644 projects/packages/sharing-likes/src/settings-app/data/store.ts create mode 100644 projects/packages/sharing-likes/src/settings-app/data/writes.ts diff --git a/pnpm-lock.yaml b/pnpm-lock.yaml index 2efea0aa4984..3019d5f5b11e 100644 --- a/pnpm-lock.yaml +++ b/pnpm-lock.yaml @@ -5219,9 +5219,6 @@ importers: '@jetpack-sharing-likes/init': specifier: link:packages/init version: link:packages/init - '@tanstack/react-query': - specifier: 5.102.8 - version: 5.102.8(react@18.3.1) '@wordpress/admin-ui': specifier: 2.12.0 version: 2.12.0(@types/react-dom@18.3.7(@types/react@18.3.31))(@types/react@18.3.31)(react-dom@18.3.1(react@18.3.1))(react@18.3.1) diff --git a/projects/packages/sharing-likes/AGENTS.md b/projects/packages/sharing-likes/AGENTS.md index ff9078468c1f..a8feda79219d 100644 --- a/projects/packages/sharing-likes/AGENTS.md +++ b/projects/packages/sharing-likes/AGENTS.md @@ -54,10 +54,14 @@ The React screen is the exception: behind `rsm_jetpack_ui_modernization_sharing_ `routes/` and `packages/init/` sit at the root, where wp-build requires them); a later JS surface gets its own sibling directory. The screen takes Newsletter's Jetpack chrome on purpose. It reads `JetpackScriptData.sharing_likes` for its first -render and saves through `src/rest/`. +render and saves through `src/rest/`. Its data lives in one `@wordpress/data` store +(`data/store.ts`), and every write goes through the queue in `data/writes.ts`, so +requests reach the server one at a time, in order. Like Newsletter's settings, it +uses neither TanStack Query nor `@wordpress/core-data`, which would load the block +editor's scripts onto the page. Its services manager, under `src/settings-app/services/`, saves the enabled lists -through `useSaveServices`, in the same write scope as every other save. Removing +through `useSaveServices`, in the same write queue as every other save. Removing the last service on a block theme hands the section to the block with no way back, which is why that one removal asks first instead of offering Undo. Deleting a custom service leaves its ID in `sharing-services`, so `useCustomService` saves diff --git a/projects/packages/sharing-likes/changelog/update-sharing-likes-drop-tanstack b/projects/packages/sharing-likes/changelog/update-sharing-likes-drop-tanstack new file mode 100644 index 000000000000..7e07c82d5801 --- /dev/null +++ b/projects/packages/sharing-likes/changelog/update-sharing-likes-drop-tanstack @@ -0,0 +1,4 @@ +Significance: patch +Type: changed + +Settings: Keep the React Sharing screen's data in a WordPress data store instead of TanStack Query. diff --git a/projects/packages/sharing-likes/package.json b/projects/packages/sharing-likes/package.json index 7fb0799274e9..44ed37141c5c 100644 --- a/projects/packages/sharing-likes/package.json +++ b/projects/packages/sharing-likes/package.json @@ -40,7 +40,6 @@ "@automattic/jetpack-components": "workspace:*", "@automattic/jetpack-script-data": "workspace:*", "@jetpack-sharing-likes/init": "link:packages/init", - "@tanstack/react-query": "5.102.8", "@wordpress/admin-ui": "2.12.0", "@wordpress/api-fetch": "7.57.0", "@wordpress/base-styles": "13.3.0", diff --git a/projects/packages/sharing-likes/routes/settings/package.json b/projects/packages/sharing-likes/routes/settings/package.json index 5f900896c756..dfcce55e12cd 100644 --- a/projects/packages/sharing-likes/routes/settings/package.json +++ b/projects/packages/sharing-likes/routes/settings/package.json @@ -4,7 +4,6 @@ "dependencies": { "@automattic/jetpack-components": "workspace:*", "@automattic/jetpack-script-data": "workspace:*", - "@tanstack/react-query": "5.102.8", "@types/react": "18.3.31", "@wordpress/api-fetch": "7.57.0", "@wordpress/components": "42.0.0", diff --git a/projects/packages/sharing-likes/routes/settings/stage.tsx b/projects/packages/sharing-likes/routes/settings/stage.tsx index 800e1fc0a67c..950704438e49 100644 --- a/projects/packages/sharing-likes/routes/settings/stage.tsx +++ b/projects/packages/sharing-likes/routes/settings/stage.tsx @@ -1,14 +1,12 @@ -import { QueryClientProvider } from '@tanstack/react-query'; -import { createQueryClient, seedQueryClient } from '../../src/settings-app/data/queries'; +import { dispatch } from '@wordpress/data'; +import { store } from '../../src/settings-app/data/store'; import { getSharingLikesScriptData } from '../../src/settings-app/script-data'; import { SettingsScreen } from '../../src/settings-app/settings-screen'; import '../../src/settings-app/style.scss'; -const queryClient = createQueryClient(); - const scriptData = getSharingLikesScriptData(); if ( scriptData ) { - seedQueryClient( queryClient, scriptData ); + dispatch( store ).seed( scriptData ); } /** @@ -16,10 +14,6 @@ if ( scriptData ) { * * @return The settings screen. */ -const Stage = () => ( - - - -); +const Stage = () => ; export { Stage as stage }; diff --git a/projects/packages/sharing-likes/src/settings-app/data/queries.ts b/projects/packages/sharing-likes/src/settings-app/data/queries.ts index f89fa430b257..53b3052227b6 100644 --- a/projects/packages/sharing-likes/src/settings-app/data/queries.ts +++ b/projects/packages/sharing-likes/src/settings-app/data/queries.ts @@ -1,51 +1,6 @@ -import { QueryClient, useQuery } from '@tanstack/react-query'; -import { fetchServices, fetchSettings, fetchStatus } from './api'; -import type { Settings, SharingLikesScriptData, Status } from '../types'; - -export const queryKeys = { - status: [ 'sharing-likes', 'status' ] as const, - settings: [ 'sharing-likes', 'settings' ] as const, - services: [ 'sharing-likes', 'services' ] as const, -}; - -// Every write shares this scope, so requests reach the server one at a time, in order. -export const MUTATION_SCOPE = { id: 'sharing-likes' }; - -export const SAVE_SETTING_KEY = [ 'sharing-likes', 'save-setting' ] as const; - -export const SAVE_SERVICES_KEY = [ 'sharing-likes', 'save-services' ] as const; - -export const CUSTOM_SERVICE_KEY = [ 'sharing-likes', 'custom-service' ] as const; - -export const FEATURE_ACTION_KEY = [ 'sharing-likes', 'feature-action' ] as const; - -// Matches every write by prefix, saves and feature actions alike. -export const WRITES_KEY = [ 'sharing-likes' ] as const; - -/** - * The screen's query client. - * - * @return Query client. - */ -export function createQueryClient(): QueryClient { - return new QueryClient( { - defaultOptions: { - // Writes wait on their rereads, and a paused read only resumes once every queued write has finished. - queries: { refetchOnWindowFocus: false, retry: false, networkMode: 'always' }, - }, - } ); -} - -/** - * Start the cache from the script data, so the first render waits on no request. - * - * @param queryClient - Query client. - * @param scriptData - The page's script data. - */ -export function seedQueryClient( queryClient: QueryClient, scriptData: SharingLikesScriptData ) { - queryClient.setQueryData( queryKeys.status, scriptData.status ); - queryClient.setQueryData( queryKeys.settings, scriptData.settings ); -} +import { useSelect } from '@wordpress/data'; +import { store } from './store'; +import type { Services, Settings, Status } from '../types'; /** * Which variant each section renders. @@ -53,7 +8,7 @@ export function seedQueryClient( queryClient: QueryClient, scriptData: SharingLi * @return Status, once known. */ export function useStatus(): Status | undefined { - return useQuery( { queryKey: queryKeys.status, queryFn: fetchStatus, staleTime: Infinity } ).data; + return useSelect( select => select( store ).getStatus(), [] ); } /** @@ -62,22 +17,36 @@ export function useStatus(): Status | undefined { * @return Settings, once known. */ export function useSettings(): Settings | undefined { - return useQuery( { queryKey: queryKeys.settings, queryFn: fetchSettings, staleTime: Infinity } ) - .data; + return useSelect( select => select( store ).getSettings(), [] ); } /** * The enabled services. The route answers 409 unless the Sharing section configures. * * @param enabled - Whether to fetch. - * @return The services query. + * @return The services, and whether the first read is still to come. + */ +export function useServices( enabled: boolean ): { + data: Services | undefined; + isPending: boolean; +} { + return useSelect( + select => { + if ( ! enabled ) { + return { data: undefined, isPending: true }; + } + const data = select( store ).getServices(); + return { data, isPending: ! data && ! select( store ).hasResolutionFailed( 'getServices' ) }; + }, + [ enabled ] + ); +} + +/** + * Whether any write is queued or in flight. + * + * @return Whether something is saving. */ -export function useServices( enabled: boolean ) { - return useQuery( { - queryKey: queryKeys.services, - queryFn: fetchServices, - enabled, - staleTime: Infinity, - retry: false, - } ); +export function useIsSaving(): boolean { + return useSelect( select => select( store ).getPendingWrites() > 0, [] ); } diff --git a/projects/packages/sharing-likes/src/settings-app/data/store.ts b/projects/packages/sharing-likes/src/settings-app/data/store.ts new file mode 100644 index 000000000000..bfa4a49aa2b8 --- /dev/null +++ b/projects/packages/sharing-likes/src/settings-app/data/store.ts @@ -0,0 +1,228 @@ +import { createReduxStore, register } from '@wordpress/data'; +import { fetchServices, fetchSettings, fetchStatus } from './api'; +import * as writes from './writes'; +import type { Services, Settings, SharingLikesScriptData, Status } from '../types'; + +export const STORE_NAME = 'jetpack-sharing-likes/settings'; + +export type Slice = 'status' | 'settings' | 'services'; + +export type WriteKind = 'setting' | 'services' | 'custom-service' | 'feature-action'; + +interface Slices { + status: Status; + settings: Settings; + services: Services; +} + +export interface State { + status?: Status; + settings?: Settings; + services?: Services; + // Bumped by every local change to a slice, so a read that started before it is dropped when it lands. + versions: Record< Slice, number >; + // Writes queued or in flight, by kind. + pending: Record< WriteKind, number >; +} + +type Action = + | { type: 'RECEIVE'; slice: Slice; value: Slices[ Slice ]; since?: number } + | { type: 'DISCARD_READS'; slice: Slice } + | { type: 'WRITE_STARTED' | 'WRITE_SETTLED'; kind: WriteKind }; + +const DEFAULT_STATE: State = { + versions: { status: 0, settings: 0, services: 0 }, + pending: { setting: 0, services: 0, 'custom-service': 0, 'feature-action': 0 }, +}; + +/** + * Store reducer. + * + * @param state - State. + * @param action - Action. + * @return New state. + */ +function reducer( state: State = DEFAULT_STATE, action: Action ): State { + switch ( action.type ) { + case 'RECEIVE': + if ( action.since === undefined ) { + return { + ...state, + [ action.slice ]: action.value, + versions: { ...state.versions, [ action.slice ]: state.versions[ action.slice ] + 1 }, + }; + } + return action.since === state.versions[ action.slice ] + ? { ...state, [ action.slice ]: action.value } + : state; + case 'DISCARD_READS': + return { + ...state, + versions: { ...state.versions, [ action.slice ]: state.versions[ action.slice ] + 1 }, + }; + case 'WRITE_STARTED': + case 'WRITE_SETTLED': + return { + ...state, + pending: { + ...state.pending, + [ action.kind ]: + state.pending[ action.kind ] + ( action.type === 'WRITE_STARTED' ? 1 : -1 ), + }, + }; + default: + return state; + } +} + +const actions = { + /** + * Store a slice. Without `since` it is a local change; with it, a read that started at that version. + * + * @param slice - Slice. + * @param value - Value. + * @param since - The slice's version when the read started. + * @return Action. + */ + receive< S extends Slice >( slice: S, value: Slices[ S ], since?: number ): Action { + return { type: 'RECEIVE', slice, value, since }; + }, + + /** + * Drop whatever reads of a slice are in flight when they land. + * + * @param slice - Slice. + * @return Action. + */ + discardReads( slice: Slice ): Action { + return { type: 'DISCARD_READS', slice }; + }, + + /** + * Count a write as queued. + * + * @param kind - Write kind. + * @return Action. + */ + writeStarted( kind: WriteKind ): Action { + return { type: 'WRITE_STARTED', kind }; + }, + + /** + * Count a write as done. + * + * @param kind - Write kind. + * @return Action. + */ + writeSettled( kind: WriteKind ): Action { + return { type: 'WRITE_SETTLED', kind }; + }, + + /** + * Start from the script data, so the first render waits on no request. + * + * @param scriptData - The page's script data. + * @return Thunk. + */ + seed: + ( scriptData: Pick< SharingLikesScriptData, 'status' | 'settings' > ) => + ( { dispatch }: { dispatch: ThunkDispatch } ) => { + dispatch.receive( 'status', scriptData.status ); + dispatch.receive( 'settings', scriptData.settings ); + dispatch.finishResolution( 'getStatus', [] ); + dispatch.finishResolution( 'getSettings', [] ); + }, + + ...writes, +}; + +const selectors = { + /** + * Which variant each section renders. + * + * @param state - State. + * @return Status, once known. + */ + getStatus: ( state: State ): Status | undefined => state.status, + + /** + * Every setting the screen shows on this site. + * + * @param state - State. + * @return Settings, once known. + */ + getSettings: ( state: State ): Settings | undefined => state.settings, + + /** + * The enabled services. The route answers 409 unless the Sharing section configures. + * + * @param state - State. + * @return Services, once known. + */ + getServices: ( state: State ): Services | undefined => state.services, + + /** + * Writes queued or in flight. + * + * @param state - State. + * @param kind - Only this kind, or every write. + * @return Count. + */ + getPendingWrites: ( state: State, kind?: WriteKind ): number => + kind + ? state.pending[ kind ] + : Object.values( state.pending ).reduce( ( sum, count ) => sum + count, 0 ), + + /** + * A slice's version, which every local change bumps. + * + * @param state - State. + * @param slice - Slice. + * @return Version. + */ + getVersion: ( state: State, slice: Slice ): number => state.versions[ slice ], +}; + +/** + * A resolver that stores what it read unless the slice changed locally meanwhile. + * + * @param slice - Slice. + * @param fetch - Request. + * @return Resolver. + */ +function read< S extends Slice >( slice: S, fetch: () => Promise< Slices[ S ] > ) { + return () => + async ( { select, dispatch }: { select: ThunkSelect; dispatch: ThunkDispatch } ) => { + const since = select.getVersion( slice ); + dispatch.receive( slice, await fetch(), since ); + }; +} + +const resolvers = { + getStatus: read( 'status', fetchStatus ), + getSettings: read( 'settings', fetchSettings ), + getServices: read( 'services', fetchServices ), +}; + +export type ThunkSelect = { + [ K in keyof typeof selectors ]: ( typeof selectors )[ K ] extends ( + state: State, + ...args: infer A + ) => infer R + ? ( ...args: A ) => R + : never; +}; + +export type ThunkDispatch = { + receive: < S extends Slice >( slice: S, value: Slices[ S ], since?: number ) => void; + discardReads: ( slice: Slice ) => void; + writeStarted: ( kind: WriteKind ) => void; + writeSettled: ( kind: WriteKind ) => void; + invalidateResolution: ( selector: string, args: unknown[] ) => void; + finishResolution: ( selector: string, args: unknown[] ) => void; + saveServices: ( ...args: Parameters< typeof writes.saveServices > ) => Promise< unknown >; +}; + +export const store = createReduxStore( STORE_NAME, { reducer, actions, selectors, resolvers } ); + +register( store ); diff --git a/projects/packages/sharing-likes/src/settings-app/data/use-custom-service.ts b/projects/packages/sharing-likes/src/settings-app/data/use-custom-service.ts index 83d3f29c75d5..3b90ee14ea0d 100644 --- a/projects/packages/sharing-likes/src/settings-app/data/use-custom-service.ts +++ b/projects/packages/sharing-likes/src/settings-app/data/use-custom-service.ts @@ -1,44 +1,7 @@ -import { useMutation, useQueryClient } from '@tanstack/react-query'; import { useDispatch } from '@wordpress/data'; -import { useCallback, useMemo } from '@wordpress/element'; -import { __ } from '@wordpress/i18n'; -import { store as noticesStore } from '@wordpress/notices'; -import { createCustomService, deleteCustomService, updateCustomService } from './api'; -import { errorMessage } from './error-message'; -import { CUSTOM_SERVICE_KEY, MUTATION_SCOPE, queryKeys } from './queries'; -import { useSaveServices, type ServiceLists } from './use-save-services'; -import type { CustomServiceFields, Service, ServiceRow, Services } from '../types'; - -/** - * A custom-service write in the screen's write scope, with its error snackbar. - * - * @param mutationFn - Request. - * @param fallback - Message when the error carries none. - * @return Mutate function. - */ -function useCustomServiceMutation< Variables, Result >( - mutationFn: ( variables: Variables ) => Promise< Result >, - fallback: string -) { - const { createErrorNotice } = useDispatch( noticesStore ); - return useMutation( { - mutationKey: CUSTOM_SERVICE_KEY, - scope: MUTATION_SCOPE, - mutationFn, - onError: error => createErrorNotice( errorMessage( error, fallback ), { type: 'snackbar' } ), - } ).mutateAsync; -} - -/** - * Change the arguments of `updateCustomService()` into one mutation variable. - * - * @param change - Change. - * @param change.id - Service ID. - * @param change.fields - New fields. - * @return The service as saved. - */ -const updateService = ( { id, fields }: { id: string; fields: CustomServiceFields } ) => - updateCustomService( id, fields ); +import { useMemo } from '@wordpress/element'; +import { store } from './store'; +import type { CustomServiceFields, ServiceRow } from '../types'; /** * Create, edit and delete custom services. @@ -46,90 +9,20 @@ const updateService = ( { id, fields }: { id: string; fields: CustomServiceField * @return Operations, each resolving to whether it went through. */ export function useCustomService() { - const queryClient = useQueryClient(); - const saveLists = useSaveServices(); - const { createSuccessNotice } = useDispatch( noticesStore ); - const notSaved = __( 'The custom service could not be saved.', 'jetpack-sharing-likes' ); - const createMutation = useCustomServiceMutation( createCustomService, notSaved ); - const updateMutation = useCustomServiceMutation( updateService, notSaved ); - const deleteMutation = useCustomServiceMutation( - deleteCustomService, - __( 'The custom service could not be deleted.', 'jetpack-sharing-likes' ) - ); - - const cached = useCallback( - () => queryClient.getQueryData< Services >( queryKeys.services ), - [ queryClient ] - ); - const setServices = useCallback( - ( update: ( list: Service[] ) => Service[] ) => - queryClient.setQueryData< Services >( - queryKeys.services, - data => data && { ...data, services: update( data.services ) } - ), - [ queryClient ] - ); - const notifySaved = useCallback( - () => - createSuccessNotice( __( 'Settings have been saved', 'jetpack-sharing-likes' ), { - type: 'snackbar', - } ), - [ createSuccessNotice ] - ); - - const create = useCallback( - async ( fields: CustomServiceFields, row: ServiceRow ) => { - let service: Service; - try { - service = await createMutation( fields ); - } catch { - return false; - } - setServices( list => [ ...list, service ] ); - // Read now rather than before the request: moves made meanwhile are already in the cache. - const data = cached(); - const lists: ServiceLists = { visible: data?.visible ?? [], hidden: data?.hidden ?? [] }; - await saveLists( { ...lists, [ row ]: [ ...lists[ row ], service.id ] } ); - return true; - }, - [ cached, createMutation, saveLists, setServices ] + const { createCustomService, updateCustomService, deleteCustomService } = useDispatch( store ); + + return useMemo( + () => ( { + create: createCustomService as ( + fields: CustomServiceFields, + row: ServiceRow + ) => Promise< boolean >, + update: updateCustomService as ( + id: string, + fields: CustomServiceFields + ) => Promise< boolean >, + remove: deleteCustomService as ( id: string ) => Promise< boolean >, + } ), + [ createCustomService, updateCustomService, deleteCustomService ] ); - - const update = useCallback( - async ( id: string, fields: CustomServiceFields ) => { - try { - const service = await updateMutation( { id, fields } ); - setServices( list => list.map( item => ( item.id === id ? service : item ) ) ); - notifySaved(); - return true; - } catch { - return false; - } - }, - [ notifySaved, setServices, updateMutation ] - ); - - const remove = useCallback( - async ( id: string ) => { - try { - await deleteMutation( id ); - } catch { - return false; - } - setServices( list => list.filter( item => item.id !== id ) ); - const data = cached(); - if ( data && ( data.visible.includes( id ) || data.hidden.includes( id ) ) ) { - await saveLists( { - visible: data.visible.filter( other => other !== id ), - hidden: data.hidden.filter( other => other !== id ), - } ); - } else { - notifySaved(); - } - return true; - }, - [ cached, deleteMutation, notifySaved, saveLists, setServices ] - ); - - return useMemo( () => ( { create, update, remove } ), [ create, update, remove ] ); } diff --git a/projects/packages/sharing-likes/src/settings-app/data/use-feature-action.ts b/projects/packages/sharing-likes/src/settings-app/data/use-feature-action.ts index f17c09becd1c..2d9fee7550b3 100644 --- a/projects/packages/sharing-likes/src/settings-app/data/use-feature-action.ts +++ b/projects/packages/sharing-likes/src/settings-app/data/use-feature-action.ts @@ -1,88 +1,29 @@ -import { useMutation, useQueryClient } from '@tanstack/react-query'; import { useDispatch } from '@wordpress/data'; -import { useCallback } from '@wordpress/element'; -import { __ } from '@wordpress/i18n'; -import { store as noticesStore } from '@wordpress/notices'; -import { configures, type Feature, type Status } from '../types'; -import { runFeatureAction, type FeatureAction } from './api'; -import { errorMessage } from './error-message'; -import { - FEATURE_ACTION_KEY, - MUTATION_SCOPE, - SAVE_SERVICES_KEY, - SAVE_SETTING_KEY, - queryKeys, -} from './queries'; -import type { QueryClient } from '@tanstack/react-query'; +import { useCallback, useState } from '@wordpress/element'; +import { store } from './store'; +import type { FeatureAction } from './api'; +import type { Feature } from '../types'; export type { FeatureAction }; -/** - * Whether the cached status has the Sharing section showing its options. - * - * @param queryClient - Query client. - * @return Whether it configures. - */ -function sharingConfigures( queryClient: QueryClient ): boolean { - const state = queryClient.getQueryData< Status >( queryKeys.status )?.sharing.state; - return !! state && configures( state ); -} - /** * "Switch to the … block" and "Turn on …". * * @return Run function, and whether this instance's action is in flight. */ export function useFeatureAction() { - const queryClient = useQueryClient(); - const { createSuccessNotice, createErrorNotice } = useDispatch( noticesStore ); + const { runFeatureAction } = useDispatch( store ); + const [ pending, setPending ] = useState( 0 ); - const { mutate, isPending } = useMutation( { - mutationKey: FEATURE_ACTION_KEY, - scope: MUTATION_SCOPE, - mutationFn: ( { feature, action }: { feature: Feature; action: FeatureAction } ) => - runFeatureAction( feature, action ), - onSuccess: status => { - queryClient.setQueryData( queryKeys.status, status ); - createSuccessNotice( __( 'Settings have been saved', 'jetpack-sharing-likes' ), { - type: 'snackbar', - } ); - }, - onError: error => { - createErrorNotice( - errorMessage( - error, - __( 'This action is not available on this site right now.', 'jetpack-sharing-likes' ) - ), - { type: 'snackbar' } + const run = useCallback( + ( feature: Feature, action: FeatureAction ) => { + setPending( count => count + 1 ); + ( runFeatureAction( feature, action ) as Promise< void > ).finally( () => + setPending( count => count - 1 ) ); }, - // Which settings are offered follows the section variants; returned so the reads finish inside the scope. - onSettled: ( _status, error ) => - Promise.all( [ - error ? queryClient.invalidateQueries( { queryKey: queryKeys.status } ) : undefined, - // A pending save's response brings fresh settings, and this read could land after it. - queryClient.isMutating( { mutationKey: SAVE_SETTING_KEY } ) > 0 - ? undefined - : queryClient.invalidateQueries( { queryKey: queryKeys.settings } ), - // The list is still mounted until React re-renders, and the route answers 409 once Sharing stops configuring. - // A pending services save brings fresh lists too, as with settings above. - queryClient.invalidateQueries( { - queryKey: queryKeys.services, - refetchType: - ! error && - sharingConfigures( queryClient ) && - queryClient.isMutating( { mutationKey: SAVE_SERVICES_KEY } ) === 0 - ? 'active' - : 'none', - } ), - ] ), - } ); - - const run = useCallback( - ( feature: Feature, action: FeatureAction ) => mutate( { feature, action } ), - [ mutate ] + [ runFeatureAction ] ); - return { run, isPending }; + return { run, isPending: pending > 0 }; } diff --git a/projects/packages/sharing-likes/src/settings-app/data/use-save-services.ts b/projects/packages/sharing-likes/src/settings-app/data/use-save-services.ts index d63467aa6deb..2e855c6f6894 100644 --- a/projects/packages/sharing-likes/src/settings-app/data/use-save-services.ts +++ b/projects/packages/sharing-likes/src/settings-app/data/use-save-services.ts @@ -1,133 +1,20 @@ -import { useMutation, useQueryClient } from '@tanstack/react-query'; import { useDispatch } from '@wordpress/data'; -import { useCallback } from '@wordpress/element'; -import { __ } from '@wordpress/i18n'; -import { store as noticesStore } from '@wordpress/notices'; -import { saveServices } from './api'; -import { errorMessage } from './error-message'; -import { MUTATION_SCOPE, SAVE_SERVICES_KEY, SAVE_SETTING_KEY, queryKeys } from './queries'; -import type { ServiceRow, Services } from '../types'; +import { store } from './store'; +import type { SaveServicesOptions, ServiceLists } from './writes'; +import type { Services } from '../types'; -export interface ServiceLists { - visible: string[]; - hidden: string[]; -} - -interface SaveServicesOptions { - message?: string; - // Where a removed service sat, so Undo can put it back without reverting anything saved since. - undo?: { id: string; row: ServiceRow; index: number }; -} +export type { ServiceLists }; type SaveServices = ( lists: ServiceLists, options?: SaveServicesOptions ) => Promise< Services | undefined >; -interface ServicesChange extends ServiceLists { - previous: ServiceLists; -} - -// One snackbar for a run of moves, rather than one per tap. -const SAVED_NOTICE_ID = 'sharing-likes-services-saved'; - -/** - * Whether two pairs of lists hold the same services in the same order. - * - * @param a - Lists. - * @param b - Lists. - * @return Whether they match. - */ -function sameLists( a: ServiceLists, b: ServiceLists ): boolean { - return JSON.stringify( [ a.visible, a.hidden ] ) === JSON.stringify( [ b.visible, b.hidden ] ); -} - /** * Save the enabled services optimistically, rolling back if the server refuses. * * @return Save function, resolving to the saved services or undefined on failure. */ export function useSaveServices(): SaveServices { - const queryClient = useQueryClient(); - const { createSuccessNotice, createErrorNotice, removeNotice } = useDispatch( noticesStore ); - const isLastSave = () => queryClient.isMutating( { mutationKey: SAVE_SERVICES_KEY } ) <= 1; - - const { mutateAsync } = useMutation( { - mutationKey: SAVE_SERVICES_KEY, - scope: MUTATION_SCOPE, - mutationFn: ( { visible, hidden }: ServicesChange ) => saveServices( visible, hidden ), - onSuccess: saved => { - // Each response carries both lists, so one landing while another save waits would undo that save's order. - if ( isLastSave() ) { - queryClient.cancelQueries( { queryKey: queryKeys.services } ); - queryClient.setQueryData( queryKeys.services, saved ); - } - }, - onError: ( error, { visible, hidden, previous } ) => { - // A later change replaced these lists, and its own save settles them. - queryClient.setQueryData< Services >( queryKeys.services, current => - current && sameLists( current, { visible, hidden } ) ? { ...current, ...previous } : current - ); - createErrorNotice( - errorMessage( - error, - __( 'Your sharing buttons could not be saved.', 'jetpack-sharing-likes' ) - ), - { type: 'snackbar' } - ); - if ( isLastSave() ) { - queryClient.invalidateQueries( { queryKey: queryKeys.services } ); - } - }, - // A refusal usually means the screen is stale, and an empty list hands a block theme's section to the block. - onSettled: ( _saved, error, { visible, hidden } ) => - ! error && visible.length + hidden.length > 0 - ? undefined - : Promise.all( [ - queryClient.invalidateQueries( { queryKey: queryKeys.status } ), - queryClient.isMutating( { mutationKey: SAVE_SETTING_KEY } ) > 0 - ? undefined - : queryClient.invalidateQueries( { queryKey: queryKeys.settings } ), - ] ), - } ); - - return useCallback( - async function save( lists: ServiceLists, { message, undo }: SaveServicesOptions = {} ) { - // An Undo offered before this change would now revert it. - removeNotice( SAVED_NOTICE_ID ); - // An in-flight read would land on top of the optimistic lists. - queryClient.cancelQueries( { queryKey: queryKeys.services } ); - const current = queryClient.getQueryData< Services >( queryKeys.services ); - const previous = { visible: current?.visible ?? [], hidden: current?.hidden ?? [] }; - queryClient.setQueryData< Services >( - queryKeys.services, - data => data && { ...data, ...lists } - ); - - const restore = () => { - const latest = queryClient.getQueryData< Services >( queryKeys.services ); - if ( ! undo || ! latest || [ ...latest.visible, ...latest.hidden ].includes( undo.id ) ) { - return; - } - const ids = [ ...latest[ undo.row ] ]; - ids.splice( Math.min( undo.index, ids.length ), 0, undo.id ); - save( { visible: latest.visible, hidden: latest.hidden, [ undo.row ]: ids } ); - }; - - try { - const saved = await mutateAsync( { ...lists, previous } ); - createSuccessNotice( message ?? __( 'Settings have been saved', 'jetpack-sharing-likes' ), { - id: SAVED_NOTICE_ID, - type: 'snackbar', - actions: undo - ? [ { label: __( 'Undo', 'jetpack-sharing-likes' ), onClick: restore } ] - : undefined, - } ); - return saved; - } catch { - return undefined; - } - }, - [ createSuccessNotice, mutateAsync, queryClient, removeNotice ] - ); + return useDispatch( store ).saveServices as SaveServices; } diff --git a/projects/packages/sharing-likes/src/settings-app/data/use-save-setting.ts b/projects/packages/sharing-likes/src/settings-app/data/use-save-setting.ts index 395e7ac0af14..327a4ada86f3 100644 --- a/projects/packages/sharing-likes/src/settings-app/data/use-save-setting.ts +++ b/projects/packages/sharing-likes/src/settings-app/data/use-save-setting.ts @@ -1,19 +1,7 @@ -import { useMutation, useQueryClient } from '@tanstack/react-query'; import { useDispatch } from '@wordpress/data'; -import { useCallback } from '@wordpress/element'; -import { __ } from '@wordpress/i18n'; -import { store as noticesStore } from '@wordpress/notices'; -import { saveSetting } from './api'; -import { errorMessage } from './error-message'; -import { MUTATION_SCOPE, SAVE_SETTING_KEY, queryKeys } from './queries'; +import { store } from './store'; import type { SettingKey, Settings } from '../types'; -interface SettingChange { - key: SettingKey; - value: Settings[ SettingKey ]; - previous: Settings[ SettingKey ]; -} - export type SaveSetting = < K extends SettingKey >( key: K, value: Settings[ K ] @@ -25,54 +13,5 @@ export type SaveSetting = < K extends SettingKey >( * @return Save function, resolving to the saved settings or undefined on failure. */ export function useSaveSetting(): SaveSetting { - const queryClient = useQueryClient(); - const { createSuccessNotice, createErrorNotice } = useDispatch( noticesStore ); - const isLastSave = () => queryClient.isMutating( { mutationKey: SAVE_SETTING_KEY } ) <= 1; - - const { mutateAsync } = useMutation( { - mutationKey: SAVE_SETTING_KEY, - scope: MUTATION_SCOPE, - mutationFn: ( { key, value }: SettingChange ) => saveSetting( key, value ), - onSuccess: saved => { - // Each response carries every setting, so one landing while another save waits would undo that save's value. - if ( isLastSave() ) { - queryClient.cancelQueries( { queryKey: queryKeys.settings } ); - queryClient.setQueryData( queryKeys.settings, saved ); - } - createSuccessNotice( __( 'Settings have been saved', 'jetpack-sharing-likes' ), { - type: 'snackbar', - } ); - }, - onError: ( error, { key, value, previous } ) => { - // A later edit of the same setting replaced this value, and its own save settles it. - queryClient.setQueryData< Settings >( queryKeys.settings, current => - current && current[ key ] === value ? { ...current, [ key ]: previous } : current - ); - createErrorNotice( - errorMessage( error, __( 'Your settings could not be saved.', 'jetpack-sharing-likes' ) ), - { type: 'snackbar' } - ); - // A refused save usually means the screen is out of date: another tab, or a host forcing a module. - // A queued save's response refreshes the cache instead, without racing its optimistic value. - if ( isLastSave() ) { - queryClient.invalidateQueries( { queryKey: queryKeys.settings } ); - } - }, - // Saving Comment Likes can change which sections configure, and so which settings are offered. - onSettled: () => queryClient.invalidateQueries( { queryKey: queryKeys.status } ), - } ); - - return useCallback( - ( key: SettingKey, value: Settings[ SettingKey ] ) => { - // An in-flight read would land on top of the optimistic value. - queryClient.cancelQueries( { queryKey: queryKeys.settings } ); - const previous = queryClient.getQueryData< Settings >( queryKeys.settings )?.[ key ]; - queryClient.setQueryData< Settings >( queryKeys.settings, current => ( { - ...current, - [ key ]: value, - } ) ); - return mutateAsync( { key, value, previous } ).catch( () => undefined ); - }, - [ mutateAsync, queryClient ] - ) as SaveSetting; + return useDispatch( store ).saveSetting as SaveSetting; } diff --git a/projects/packages/sharing-likes/src/settings-app/data/writes.ts b/projects/packages/sharing-likes/src/settings-app/data/writes.ts new file mode 100644 index 000000000000..7fcf53898d1d --- /dev/null +++ b/projects/packages/sharing-likes/src/settings-app/data/writes.ts @@ -0,0 +1,415 @@ +import { __ } from '@wordpress/i18n'; +import { store as noticesStore } from '@wordpress/notices'; +import { configures } from '../types'; +import * as api from './api'; +import { errorMessage } from './error-message'; +import type { Slice, ThunkDispatch, ThunkSelect, WriteKind } from './store'; +import type { + CustomServiceFields, + Feature, + Service, + ServiceRow, + Services, + SettingKey, + Settings, +} from '../types'; +import type { dispatch as registryDispatch } from '@wordpress/data'; + +interface ThunkArgs { + select: ThunkSelect; + dispatch: ThunkDispatch; + resolveSelect: Record< 'getStatus' | 'getSettings' | 'getServices', () => Promise< unknown > >; + registry: { dispatch: typeof registryDispatch }; +} + +export interface ServiceLists { + visible: string[]; + hidden: string[]; +} + +export interface SaveServicesOptions { + message?: string; + // Where a removed service sat, so Undo can put it back without reverting anything saved since. + undo?: { id: string; row: ServiceRow; index: number }; +} + +const READERS = { status: 'getStatus', settings: 'getSettings', services: 'getServices' } as const; + +// One snackbar for a run of moves, rather than one per tap. +const SAVED_NOTICE_ID = 'sharing-likes-services-saved'; + +// The tail of each registry's write queue: every write waits for the one before it, rereads included. +const queues = new WeakMap< object, Promise< unknown > >(); + +/** + * Run a write once every write queued before it has finished, so requests reach the server in order. + * + * @param args - Thunk arguments. + * @param kind - Write kind, counted while queued or in flight. + * @param task - Request, and whatever must finish before the next write starts. + * @return What the task returns. + */ +async function queued< T >( args: ThunkArgs, kind: WriteKind, task: () => Promise< T > ) { + args.dispatch.writeStarted( kind ); + const run = ( queues.get( args.registry ) ?? Promise.resolve() ).then( task ); + queues.set( + args.registry, + run.catch( () => undefined ) + ); + try { + return await run; + } finally { + args.dispatch.writeSettled( kind ); + } +} + +/** + * Read a slice again, dropping any read of it already in flight. + * + * @param args - Thunk arguments. + * @param slice - Slice. + * @return Resolves once the read lands or fails. + */ +async function reread( args: ThunkArgs, slice: Slice ) { + args.dispatch.discardReads( slice ); + args.dispatch.invalidateResolution( READERS[ slice ], [] ); + try { + await args.resolveSelect[ READERS[ slice ] ](); + } catch { + // The screen keeps what it has. + } +} + +/** + * Notices dispatcher. + * + * @param args - Thunk arguments. + * @return Bound notices actions. + */ +const notices = ( args: ThunkArgs ) => args.registry.dispatch( noticesStore ); + +/** + * Save one setting optimistically, rolling it back if the server refuses. + * + * @param key - Setting. + * @param value - New value. + * @return Thunk resolving to the saved settings, or undefined on failure. + */ +export const saveSetting = + < K extends SettingKey >( key: K, value: Settings[ K ] ) => + ( args: ThunkArgs ): Promise< Settings | undefined > => { + const { select, dispatch } = args; + const previous = select.getSettings()?.[ key ]; + dispatch.receive( 'settings', { ...select.getSettings(), [ key ]: value } ); + const isLastSave = () => select.getPendingWrites( 'setting' ) <= 1; + + return queued( args, 'setting', async () => { + let saved: Settings | undefined; + try { + saved = await api.saveSetting( key, value ); + // Each response carries every setting, so one landing while another save waits would undo that save's value. + if ( isLastSave() ) { + dispatch.receive( 'settings', saved ); + } + notices( args ).createSuccessNotice( + __( 'Settings have been saved', 'jetpack-sharing-likes' ), + { type: 'snackbar' } + ); + } catch ( error ) { + // A later edit of the same setting replaced this value, and its own save settles it. + const current = select.getSettings(); + if ( current && current[ key ] === value ) { + dispatch.receive( 'settings', { ...current, [ key ]: previous } ); + } + notices( args ).createErrorNotice( + errorMessage( error, __( 'Your settings could not be saved.', 'jetpack-sharing-likes' ) ), + { type: 'snackbar' } + ); + // A refused save usually means the screen is out of date: another tab, or a host forcing a module. + // A queued save's response refreshes the settings instead, without racing its optimistic value. + if ( isLastSave() ) { + reread( args, 'settings' ); + } + } + // Saving Comment Likes can change which sections configure, and so which settings are offered. + await reread( args, 'status' ); + return saved; + } ); + }; + +/** + * Whether two pairs of lists hold the same services in the same order. + * + * @param a - Lists. + * @param b - Lists. + * @return Whether they match. + */ +function sameLists( a: ServiceLists, b: ServiceLists ): boolean { + return JSON.stringify( [ a.visible, a.hidden ] ) === JSON.stringify( [ b.visible, b.hidden ] ); +} + +/** + * Save the enabled services optimistically, rolling back if the server refuses. + * + * @param lists - Both lists, in order. + * @param options - Options. + * @param options.message - Snackbar message. + * @param options.undo - What Undo puts back. + * @return Thunk resolving to the saved services, or undefined on failure. + */ +export const saveServices = + ( lists: ServiceLists, { message, undo }: SaveServicesOptions = {} ) => + async ( args: ThunkArgs ): Promise< Services | undefined > => { + const { select, dispatch } = args; + // An Undo offered before this change would now revert it. + notices( args ).removeNotice( SAVED_NOTICE_ID ); + const current = select.getServices(); + const previous = { visible: current?.visible ?? [], hidden: current?.hidden ?? [] }; + if ( current ) { + dispatch.receive( 'services', { ...current, ...lists } ); + } else { + dispatch.discardReads( 'services' ); + } + const isLastSave = () => select.getPendingWrites( 'services' ) <= 1; + + const restore = () => { + const latest = select.getServices(); + if ( ! undo || ! latest || [ ...latest.visible, ...latest.hidden ].includes( undo.id ) ) { + return; + } + const ids = [ ...latest[ undo.row ] ]; + ids.splice( Math.min( undo.index, ids.length ), 0, undo.id ); + dispatch.saveServices( { + visible: latest.visible, + hidden: latest.hidden, + [ undo.row ]: ids, + } ); + }; + + let saved: Services; + try { + saved = await queued( args, 'services', async () => { + let refused: unknown; + let response: Services | undefined; + try { + response = await api.saveServices( lists.visible, lists.hidden ); + // Each response carries both lists, so one landing while another save waits would undo that save's order. + if ( isLastSave() ) { + dispatch.receive( 'services', response ); + } + } catch ( error ) { + refused = error ?? new Error(); + // A later change replaced these lists, and its own save settles them. + const latest = select.getServices(); + if ( latest && sameLists( latest, lists ) ) { + dispatch.receive( 'services', { ...latest, ...previous } ); + } + notices( args ).createErrorNotice( + errorMessage( + error, + __( 'Your sharing buttons could not be saved.', 'jetpack-sharing-likes' ) + ), + { type: 'snackbar' } + ); + if ( isLastSave() ) { + reread( args, 'services' ); + } + } + // A refusal usually means the screen is stale, and an empty list hands a block theme's section to the block. + if ( refused || lists.visible.length + lists.hidden.length === 0 ) { + await Promise.all( [ + reread( args, 'status' ), + select.getPendingWrites( 'setting' ) > 0 ? undefined : reread( args, 'settings' ), + ] ); + } + if ( refused ) { + throw refused; + } + return response as Services; + } ); + } catch { + return undefined; + } + + notices( args ).createSuccessNotice( + message ?? __( 'Settings have been saved', 'jetpack-sharing-likes' ), + { + id: SAVED_NOTICE_ID, + type: 'snackbar', + actions: undo + ? [ { label: __( 'Undo', 'jetpack-sharing-likes' ), onClick: restore } ] + : undefined, + } + ); + return saved; + }; + +/** + * A custom-service request in the write queue, with its error snackbar. + * + * @param args - Thunk arguments. + * @param request - Request. + * @param fallback - Message when the error carries none. + * @return What the request returns; rejects when it fails. + */ +function customServiceWrite< T >( args: ThunkArgs, request: () => Promise< T >, fallback: string ) { + return queued( args, 'custom-service', async () => { + try { + return await request(); + } catch ( error ) { + notices( args ).createErrorNotice( errorMessage( error, fallback ), { type: 'snackbar' } ); + throw error; + } + } ); +} + +/** + * Change the cached service list, when there is one. + * + * @param args - Thunk arguments. + * @param update - New list from the old one. + */ +function updateServiceList( args: ThunkArgs, update: ( list: Service[] ) => Service[] ) { + const data = args.select.getServices(); + if ( data ) { + args.dispatch.receive( 'services', { ...data, services: update( data.services ) } ); + } +} + +/** + * The "Settings have been saved" snackbar. + * + * @param args - Thunk arguments. + */ +function notifySaved( args: ThunkArgs ) { + notices( args ).createSuccessNotice( __( 'Settings have been saved', 'jetpack-sharing-likes' ), { + type: 'snackbar', + } ); +} + +const notSaved = () => __( 'The custom service could not be saved.', 'jetpack-sharing-likes' ); + +/** + * Create a custom service, then save it at the end of a row. + * + * @param fields - Name, sharing URL and icon URL. + * @param row - Row to add it to. + * @return Thunk resolving to whether it went through. + */ +export const createCustomService = + ( fields: CustomServiceFields, row: ServiceRow ) => + async ( args: ThunkArgs ): Promise< boolean > => { + let service: Service; + try { + service = await customServiceWrite( + args, + () => api.createCustomService( fields ), + notSaved() + ); + } catch { + return false; + } + updateServiceList( args, list => [ ...list, service ] ); + // Read now rather than before the request: moves made meanwhile are already in the store. + const data = args.select.getServices(); + const lists: ServiceLists = { visible: data?.visible ?? [], hidden: data?.hidden ?? [] }; + await args.dispatch.saveServices( { ...lists, [ row ]: [ ...lists[ row ], service.id ] } ); + return true; + }; + +/** + * Change a custom service. + * + * @param id - Service ID. + * @param fields - Name, sharing URL and icon URL. + * @return Thunk resolving to whether it went through. + */ +export const updateCustomService = + ( id: string, fields: CustomServiceFields ) => + async ( args: ThunkArgs ): Promise< boolean > => { + try { + const service = await customServiceWrite( + args, + () => api.updateCustomService( id, fields ), + notSaved() + ); + updateServiceList( args, list => list.map( item => ( item.id === id ? service : item ) ) ); + notifySaved( args ); + return true; + } catch { + return false; + } + }; + +/** + * Delete a custom service, then save the lists without it. + * + * @param id - Service ID. + * @return Thunk resolving to whether it went through. + */ +export const deleteCustomService = + ( id: string ) => + async ( args: ThunkArgs ): Promise< boolean > => { + try { + await customServiceWrite( + args, + () => api.deleteCustomService( id ), + __( 'The custom service could not be deleted.', 'jetpack-sharing-likes' ) + ); + } catch { + return false; + } + updateServiceList( args, list => list.filter( item => item.id !== id ) ); + const data = args.select.getServices(); + if ( data && ( data.visible.includes( id ) || data.hidden.includes( id ) ) ) { + await args.dispatch.saveServices( { + visible: data.visible.filter( other => other !== id ), + hidden: data.hidden.filter( other => other !== id ), + } ); + } else { + notifySaved( args ); + } + return true; + }; + +/** + * "Switch to the … block" and "Turn on …". + * + * @param feature - Feature. + * @param action - Action. + * @return Thunk resolving once the action and its rereads are done. + */ +export const runFeatureAction = + ( feature: Feature, action: api.FeatureAction ) => + ( args: ThunkArgs ): Promise< void > => + queued( args, 'feature-action', async () => { + const { select, dispatch } = args; + let failed = false; + try { + dispatch.receive( 'status', await api.runFeatureAction( feature, action ) ); + notifySaved( args ); + } catch ( error ) { + failed = true; + notices( args ).createErrorNotice( + errorMessage( + error, + __( 'This action is not available on this site right now.', 'jetpack-sharing-likes' ) + ), + { type: 'snackbar' } + ); + } + const sharing = select.getStatus()?.sharing.state; + // Which settings are offered follows the section variants; awaited so the next write waits for them. + await Promise.all( [ + failed ? reread( args, 'status' ) : undefined, + // A pending save's response brings fresh settings, and this read could land after it. + select.getPendingWrites( 'setting' ) > 0 ? undefined : reread( args, 'settings' ), + // The route answers 409 once Sharing stops configuring, and a pending services save brings fresh lists. + ! failed && + !! sharing && + configures( sharing ) && + select.getPendingWrites( 'services' ) === 0 + ? reread( args, 'services' ) + : undefined, + ] ); + } ); diff --git a/projects/packages/sharing-likes/src/settings-app/settings-screen.tsx b/projects/packages/sharing-likes/src/settings-app/settings-screen.tsx index 15af8ccdce12..30da7e425bb5 100644 --- a/projects/packages/sharing-likes/src/settings-app/settings-screen.tsx +++ b/projects/packages/sharing-likes/src/settings-app/settings-screen.tsx @@ -1,10 +1,9 @@ import AdminPage from '@automattic/jetpack-components/admin-page'; import { getSiteData } from '@automattic/jetpack-script-data'; -import { useIsMutating } from '@tanstack/react-query'; import { createInterpolateElement } from '@wordpress/element'; import { __ } from '@wordpress/i18n'; import { Link, Notice, Stack } from '@wordpress/ui'; -import { WRITES_KEY, useSettings, useStatus } from './data/queries'; +import { useIsSaving, useSettings, useStatus } from './data/queries'; import { useScrollToHash } from './hooks/use-scroll-to-hash'; import { useUnsavedChangesWarning } from './hooks/use-unsaved-changes-warning'; import { getSharingLikesScriptData } from './script-data'; @@ -81,7 +80,7 @@ export function SettingsScreen(): JSX.Element { const scriptData = getSharingLikesScriptData(); const siteData = getSiteData(); // The browser can abort a write still in flight when the page unloads. - useUnsavedChangesWarning( useIsMutating( { mutationKey: WRITES_KEY } ) > 0 ); + useUnsavedChangesWarning( useIsSaving() ); return ( ; beforeEach( () => { mockApiFetch.mockReset(); - resetNotices(); setScriptData(); } ); diff --git a/projects/packages/sharing-likes/src/settings-app/test/feature-variant.test.tsx b/projects/packages/sharing-likes/src/settings-app/test/feature-variant.test.tsx index 518f27b0767f..9df3f9217d3d 100644 --- a/projects/packages/sharing-likes/src/settings-app/test/feature-variant.test.tsx +++ b/projects/packages/sharing-likes/src/settings-app/test/feature-variant.test.tsx @@ -3,7 +3,7 @@ import userEvent from '@testing-library/user-event'; import apiFetch from '@wordpress/api-fetch'; import { FeatureVariant } from '../components/feature-variant'; import { SECTION_GAP } from '../components/section-card'; -import { apiCalls, baseStatus, renderWithData, resetNotices } from './helpers'; +import { apiCalls, baseStatus, renderWithData } from './helpers'; import type { Feature, SectionState } from '../types'; jest.mock( '@wordpress/api-fetch' ); @@ -12,7 +12,6 @@ const mockApiFetch = apiFetch as jest.MockedFunction< typeof apiFetch >; beforeEach( () => { mockApiFetch.mockReset(); mockApiFetch.mockResolvedValue( baseStatus ); - resetNotices(); } ); describe( 'FeatureVariant', () => { diff --git a/projects/packages/sharing-likes/src/settings-app/test/helpers.tsx b/projects/packages/sharing-likes/src/settings-app/test/helpers.tsx index e56509a6f09d..69ffeaa488ef 100644 --- a/projects/packages/sharing-likes/src/settings-app/test/helpers.tsx +++ b/projects/packages/sharing-likes/src/settings-app/test/helpers.tsx @@ -1,10 +1,9 @@ -import { QueryClientProvider, type QueryClient } from '@tanstack/react-query'; import { render } from '@testing-library/react'; import apiFetch from '@wordpress/api-fetch'; -import { dispatch, select } from '@wordpress/data'; +import { createRegistry, RegistryProvider } from '@wordpress/data'; import { store as noticesStore } from '@wordpress/notices'; -import { createQueryClient, queryKeys } from '../data/queries'; -import type { PlacementChoice, Settings, SharingLikesScriptData, Status } from '../types'; +import { store } from '../data/store'; +import type { PlacementChoice, Services, Settings, SharingLikesScriptData, Status } from '../types'; import type { APIFetchOptions } from '@wordpress/api-fetch'; import type { ReactNode } from 'react'; @@ -51,72 +50,83 @@ export function setScriptData( overrides: Partial< SharingLikesScriptData > = {} }; } +type Registry = ReturnType< typeof createRegistry >; + +interface StoreContents { + status?: Status; + settings?: Settings; + services?: Services; +} + +// The registry the last render used, which is where its snackbars land. +let current: Registry | undefined; + /** - * A query client seeded like the stage seeds it. + * A registry with the store seeded like the stage seeds it, and services when given. * - * @param data - Cache contents. + * @param data - Store contents. * @param data.status - Status. * @param data.settings - Settings. - * @return Query client. + * @param data.services - Services; read from the route when omitted. + * @return Registry. */ -export function createTestQueryClient( { +export function createTestRegistry( { status = baseStatus, settings = baseSettings, -}: { status?: Status; settings?: Settings } = {} ) { - const queryClient = createQueryClient(); - queryClient.setQueryData( queryKeys.status, status ); - queryClient.setQueryData( queryKeys.settings, settings ); - return queryClient; + services, +}: StoreContents = {} ): Registry { + const registry = createRegistry(); + registry.register( noticesStore ); + registry.register( store ); + registry.dispatch( store ).seed( { status, settings } ); + if ( services ) { + registry.dispatch( store ).receive( 'services', services ); + registry.dispatch( store ).finishResolution( 'getServices', [] ); + } + current = registry; + return registry; } /** * Wrapper for `renderHook`. * - * @param queryClient - Query client. + * @param registry - Registry. * @return Wrapper component. */ -export function wrapperFor( queryClient: QueryClient ) { +export function wrapperFor( registry: Registry ) { return function Wrapper( { children }: { children: ReactNode } ) { - return { children }; + return { children }; }; } /** - * Render inside a seeded query client. + * Render inside a seeded registry. * - * @param ui - Element. - * @param data - Cache contents. - * @param data.status - Status. - * @param data.settings - Settings. - * @return Render result plus the query client. + * @param ui - Element. + * @param data - Store contents. + * @return Render result plus the registry. */ -export function renderWithData( - ui: ReactNode, - data: { status?: Status; settings?: Settings } = {} -) { - const queryClient = createTestQueryClient( data ); - return { queryClient, ...render( ui, { wrapper: wrapperFor( queryClient ) } ) }; +export function renderWithData( ui: ReactNode, data: StoreContents = {} ) { + const registry = createTestRegistry( data ); + return { registry, ...render( ui, { wrapper: wrapperFor( registry ) } ) }; } /** - * Text of every notice in the store. + * Every notice the last render's registry holds. * - * @return Messages. + * @return Notices. */ -export function snackbarMessages(): string[] { - return select( noticesStore ) - .getNotices() - .map( notice => String( notice.content ) ); +export function notices() { + return current?.select( noticesStore ).getNotices() ?? []; } /** - * Clear the notices store between tests. + * Text of every notice the last render's registry holds. + * + * @return Messages. */ -export function resetNotices() { - const { removeNotice } = dispatch( noticesStore ); - select( noticesStore ) - .getNotices() - .forEach( notice => removeNotice( notice.id ) ); +export function snackbarMessages(): string[] { + return notices().map( notice => String( notice.content ) ); } /** diff --git a/projects/packages/sharing-likes/src/settings-app/test/like-buttons-section.test.tsx b/projects/packages/sharing-likes/src/settings-app/test/like-buttons-section.test.tsx index 7e1a24524da7..0fab5fda5dfd 100644 --- a/projects/packages/sharing-likes/src/settings-app/test/like-buttons-section.test.tsx +++ b/projects/packages/sharing-likes/src/settings-app/test/like-buttons-section.test.tsx @@ -8,7 +8,6 @@ import { baseSettings, baseStatus, renderWithData, - resetNotices, setScriptData, snackbarMessages, } from './helpers'; @@ -22,7 +21,6 @@ beforeEach( () => { mockApiFetch.mockImplementation( ( { method } ) => Promise.resolve( method === 'PUT' ? baseSettings : baseStatus ) ); - resetNotices(); setScriptData(); } ); diff --git a/projects/packages/sharing-likes/src/settings-app/test/placement-section.test.tsx b/projects/packages/sharing-likes/src/settings-app/test/placement-section.test.tsx index fe4163931c0f..0c97266277a6 100644 --- a/projects/packages/sharing-likes/src/settings-app/test/placement-section.test.tsx +++ b/projects/packages/sharing-likes/src/settings-app/test/placement-section.test.tsx @@ -2,14 +2,7 @@ import { screen, waitFor, within } from '@testing-library/react'; import userEvent from '@testing-library/user-event'; import apiFetch from '@wordpress/api-fetch'; import { PlacementSection } from '../sections/placement-section'; -import { - apiCalls, - baseSettings, - baseStatus, - renderWithData, - resetNotices, - setScriptData, -} from './helpers'; +import { apiCalls, baseSettings, baseStatus, renderWithData, setScriptData } from './helpers'; jest.mock( '@wordpress/api-fetch' ); const mockApiFetch = apiFetch as jest.MockedFunction< typeof apiFetch >; @@ -19,7 +12,6 @@ beforeEach( () => { mockApiFetch.mockImplementation( ( { method } ) => Promise.resolve( method === 'PUT' ? baseSettings : baseStatus ) ); - resetNotices(); setScriptData(); } ); diff --git a/projects/packages/sharing-likes/src/settings-app/test/services-manager.test.tsx b/projects/packages/sharing-likes/src/settings-app/test/services-manager.test.tsx index 32cae6dd6667..266086352587 100644 --- a/projects/packages/sharing-likes/src/settings-app/test/services-manager.test.tsx +++ b/projects/packages/sharing-likes/src/settings-app/test/services-manager.test.tsx @@ -1,16 +1,14 @@ import { act, screen, waitFor, within } from '@testing-library/react'; import userEvent from '@testing-library/user-event'; import apiFetch from '@wordpress/api-fetch'; -import { select } from '@wordpress/data'; import { resetLocaleData, setLocaleData } from '@wordpress/i18n'; -import { store as noticesStore } from '@wordpress/notices'; import { ServicesManager } from '../services/services-manager'; import { apiCalls, baseSettings, baseStatus, + notices, renderWithData, - resetNotices, setScriptData, } from './helpers'; import type { Services, Settings, Status } from '../types'; @@ -77,7 +75,7 @@ function respond( list: Services = services ) { /** * Render the manager once its services have loaded. * - * @param data - Cache contents. + * @param data - Store contents. * @param data.status - Status. * @param data.settings - Settings. * @return Render result. @@ -122,7 +120,6 @@ async function runToolbarAction( beforeEach( () => { mockApiFetch.mockReset(); - resetNotices(); setScriptData(); respond(); } ); @@ -190,9 +187,7 @@ describe( 'ServicesManager', () => { await runToolbarAction( user, 'X', 'Remove' ); await waitFor( () => expect( apiCalls( 'PUT' ) ).toHaveLength( 1 ) ); - const notice = select( noticesStore ) - .getNotices() - .find( ( { content } ) => content === 'X removed.' ); + const notice = notices().find( ( { content } ) => content === 'X removed.' ); await act( async () => notice?.actions?.[ 0 ]?.onClick?.() ); await waitFor( () => diff --git a/projects/packages/sharing-likes/src/settings-app/test/settings-screen.test.tsx b/projects/packages/sharing-likes/src/settings-app/test/settings-screen.test.tsx index dd87d52381ad..d882913fd18d 100644 --- a/projects/packages/sharing-likes/src/settings-app/test/settings-screen.test.tsx +++ b/projects/packages/sharing-likes/src/settings-app/test/settings-screen.test.tsx @@ -4,7 +4,7 @@ import { LIKES_ANCHOR } from '../anchors'; import { useFeatureAction } from '../data/use-feature-action'; import { useSaveSetting } from '../data/use-save-setting'; import { SettingsScreen } from '../settings-screen'; -import { baseStatus, renderWithData, resetNotices, setScriptData } from './helpers'; +import { baseStatus, renderWithData, setScriptData } from './helpers'; import type { ReactNode } from 'react'; jest.mock( '@wordpress/api-fetch' ); @@ -35,7 +35,6 @@ function leavingPrompts(): boolean { beforeEach( () => { mockApiFetch.mockReset(); mockApiFetch.mockImplementation( () => new Promise( () => {} ) ); - resetNotices(); setScriptData(); window.location.hash = ''; scrollIntoView.mockReset(); diff --git a/projects/packages/sharing-likes/src/settings-app/test/sharing-buttons-section.test.tsx b/projects/packages/sharing-likes/src/settings-app/test/sharing-buttons-section.test.tsx index 856e0632443f..e5d9e4f42b5a 100644 --- a/projects/packages/sharing-likes/src/settings-app/test/sharing-buttons-section.test.tsx +++ b/projects/packages/sharing-likes/src/settings-app/test/sharing-buttons-section.test.tsx @@ -2,14 +2,7 @@ import { screen, waitFor } from '@testing-library/react'; import userEvent from '@testing-library/user-event'; import apiFetch from '@wordpress/api-fetch'; import { SharingButtonsSection } from '../sections/sharing-buttons-section'; -import { - apiCalls, - baseSettings, - baseStatus, - renderWithData, - resetNotices, - setScriptData, -} from './helpers'; +import { apiCalls, baseSettings, baseStatus, renderWithData, setScriptData } from './helpers'; import type { Services, Settings } from '../types'; jest.mock( '@wordpress/api-fetch' ); @@ -45,7 +38,6 @@ function servicesRespond( list: Services ) { beforeEach( () => { mockApiFetch.mockReset(); - resetNotices(); setScriptData(); } ); diff --git a/projects/packages/sharing-likes/src/settings-app/test/text-setting.test.tsx b/projects/packages/sharing-likes/src/settings-app/test/text-setting.test.tsx index b41566cfb5e7..360b62548a63 100644 --- a/projects/packages/sharing-likes/src/settings-app/test/text-setting.test.tsx +++ b/projects/packages/sharing-likes/src/settings-app/test/text-setting.test.tsx @@ -2,14 +2,8 @@ import { act, screen, waitFor } from '@testing-library/react'; import userEvent from '@testing-library/user-event'; import apiFetch from '@wordpress/api-fetch'; import { TextSetting } from '../components/text-setting'; -import { - apiCalls, - baseSettings, - baseStatus, - renderWithData, - resetNotices, - snackbarMessages, -} from './helpers'; +import { store } from '../data/store'; +import { apiCalls, baseSettings, baseStatus, renderWithData, snackbarMessages } from './helpers'; jest.mock( '@wordpress/api-fetch' ); const mockApiFetch = apiFetch as jest.MockedFunction< typeof apiFetch >; @@ -27,7 +21,6 @@ function leavingPrompts(): boolean { beforeEach( () => { mockApiFetch.mockReset(); - resetNotices(); } ); describe( 'TextSetting', () => { @@ -91,7 +84,7 @@ describe( 'TextSetting', () => { } return Promise.resolve( path?.endsWith( '/status' ) ? baseStatus : baseSettings ); } ); - const { queryClient } = renderWithData( + const { registry } = renderWithData( ); const input = screen.getByLabelText( 'Twitter Site Tag' ); @@ -103,7 +96,7 @@ describe( 'TextSetting', () => { await waitFor( () => expect( save ).toHaveAttribute( 'aria-disabled', 'true' ) ); await act( async () => refuse( { message: 'Nope.' } ) ); await waitFor( () => expect( snackbarMessages() ).toContain( 'Nope.' ) ); - await waitFor( () => expect( queryClient.isFetching() ).toBe( 0 ) ); + await waitFor( () => expect( registry.select( store ).hasResolvingSelectors() ).toBe( false ) ); expect( input ).toHaveValue( '@jetpack' ); expect( save ).not.toHaveAttribute( 'aria-disabled', 'true' ); diff --git a/projects/packages/sharing-likes/src/settings-app/test/use-custom-service.test.tsx b/projects/packages/sharing-likes/src/settings-app/test/use-custom-service.test.tsx index a929f39e8ee4..fdf18259c9ae 100644 --- a/projects/packages/sharing-likes/src/settings-app/test/use-custom-service.test.tsx +++ b/projects/packages/sharing-likes/src/settings-app/test/use-custom-service.test.tsx @@ -1,14 +1,7 @@ import { act, renderHook } from '@testing-library/react'; import apiFetch from '@wordpress/api-fetch'; -import { queryKeys, useServices } from '../data/queries'; import { useCustomService } from '../data/use-custom-service'; -import { - apiCalls, - createTestQueryClient, - resetNotices, - snackbarMessages, - wrapperFor, -} from './helpers'; +import { apiCalls, createTestRegistry, snackbarMessages, wrapperFor } from './helpers'; import type { Service, Services } from '../types'; jest.mock( '@wordpress/api-fetch' ); @@ -63,25 +56,17 @@ function respond( } /** - * Render the hook beside an active services query. + * Render the hook in a registry seeded with the services. * * @return Render result. */ function renderCustom() { - const queryClient = createTestQueryClient(); - queryClient.setQueryData( queryKeys.services, services ); - return renderHook( - () => { - useServices( true ); - return useCustomService(); - }, - { wrapper: wrapperFor( queryClient ) } - ); + const registry = createTestRegistry( { services } ); + return renderHook( () => useCustomService(), { wrapper: wrapperFor( registry ) } ); } beforeEach( () => { mockApiFetch.mockReset(); - resetNotices(); } ); describe( 'useCustomService', () => { diff --git a/projects/packages/sharing-likes/src/settings-app/test/use-feature-action.test.tsx b/projects/packages/sharing-likes/src/settings-app/test/use-feature-action.test.tsx index fa290716bae9..bb48ef5aeb70 100644 --- a/projects/packages/sharing-likes/src/settings-app/test/use-feature-action.test.tsx +++ b/projects/packages/sharing-likes/src/settings-app/test/use-feature-action.test.tsx @@ -1,6 +1,7 @@ import { act, renderHook, waitFor } from '@testing-library/react'; import apiFetch from '@wordpress/api-fetch'; -import { queryKeys, useServices, useSettings, useStatus } from '../data/queries'; +import { useServices } from '../data/queries'; +import { store } from '../data/store'; import { useFeatureAction } from '../data/use-feature-action'; import { useSaveServices } from '../data/use-save-services'; import { useSaveSetting } from '../data/use-save-setting'; @@ -8,8 +9,7 @@ import { apiCalls, baseSettings, baseStatus, - createTestQueryClient, - resetNotices, + createTestRegistry, snackbarMessages, wrapperFor, } from './helpers'; @@ -21,25 +21,18 @@ const mockApiFetch = apiFetch as jest.MockedFunction< typeof apiFetch >; const switched: Status = { ...baseStatus, sharing: { state: 'block_call_to_action' } }; /** - * Render the action hook alongside an active settings query, which is what gets refetched. + * Render the action hook in a seeded registry. * - * @return Hook result and query client. + * @return Hook result and registry. */ function renderAction() { - const queryClient = createTestQueryClient(); - const { result } = renderHook( - () => { - useSettings(); - return useFeatureAction(); - }, - { wrapper: wrapperFor( queryClient ) } - ); - return { result, queryClient }; + const registry = createTestRegistry(); + const { result } = renderHook( () => useFeatureAction(), { wrapper: wrapperFor( registry ) } ); + return { result, registry }; } beforeEach( () => { mockApiFetch.mockReset(); - resetNotices(); } ); describe( 'useFeatureAction', () => { @@ -47,14 +40,12 @@ describe( 'useFeatureAction', () => { mockApiFetch.mockImplementation( ( { method } ) => Promise.resolve( method === 'POST' ? switched : baseSettings ) ); - const { result, queryClient } = renderAction(); + const { result, registry } = renderAction(); act( () => result.current.run( 'sharing', 'switch-to-block' ) ); await waitFor( () => - expect( queryClient.getQueryData< Status >( queryKeys.status )?.sharing.state ).toBe( - 'block_call_to_action' - ) + expect( registry.select( store ).getStatus()?.sharing.state ).toBe( 'block_call_to_action' ) ); expect( apiCalls( 'POST' ) ).toEqual( [ { path: '/wpcom/v2/sharing-likes/sharing/switch-to-block', method: 'POST' }, @@ -93,13 +84,13 @@ describe( 'useFeatureAction', () => { ? post() : Promise.resolve( { visible: [ 'x' ], hidden: [], services: [] } ) ); - const queryClient = createTestQueryClient(); + const registry = createTestRegistry(); const { result } = renderHook( () => { useServices( true ); return useFeatureAction(); }, - { wrapper: wrapperFor( queryClient ) } + { wrapper: wrapperFor( registry ) } ); await waitFor( () => expect( apiCalls() ).toHaveLength( 1 ) ); @@ -107,7 +98,9 @@ describe( 'useFeatureAction', () => { await waitFor( () => expect( snackbarMessages() ).toContain( notice ) ); await waitFor( () => expect( result.current.isPending ).toBe( false ) ); - expect( apiCalls() ).toEqual( [ { path: '/wpcom/v2/sharing-likes/services' } ] ); + expect( apiCalls().filter( ( { path } ) => path?.endsWith( '/services' ) ) ).toHaveLength( + 1 + ); } ); @@ -122,14 +115,8 @@ describe( 'useFeatureAction', () => { } return path?.endsWith( '/status' ) ? statusRead : Promise.resolve( baseSettings ); } ); - const queryClient = createTestQueryClient(); - const { result } = renderHook( - () => { - useStatus(); - return useFeatureAction(); - }, - { wrapper: wrapperFor( queryClient ) } - ); + const registry = createTestRegistry(); + const { result } = renderHook( () => useFeatureAction(), { wrapper: wrapperFor( registry ) } ); act( () => { result.current.run( 'likes', 'activate' ); @@ -143,9 +130,7 @@ describe( 'useFeatureAction', () => { await act( async () => resolveStatus( baseStatus ) ); await waitFor( () => - expect( queryClient.getQueryData< Status >( queryKeys.status )?.sharing.state ).toBe( - 'block_call_to_action' - ) + expect( registry.select( store ).getStatus()?.sharing.state ).toBe( 'block_call_to_action' ) ); } ); @@ -158,13 +143,10 @@ describe( 'useFeatureAction', () => { } return method === 'PUT' ? put : Promise.resolve( baseSettings ); } ); - const queryClient = createTestQueryClient(); + const registry = createTestRegistry(); const { result } = renderHook( - () => { - useSettings(); - return { action: useFeatureAction(), save: useSaveSetting() }; - }, - { wrapper: wrapperFor( queryClient ) } + () => ( { action: useFeatureAction(), save: useSaveSetting() } ), + { wrapper: wrapperFor( registry ) } ); let saved: Promise< unknown > = Promise.resolve(); @@ -174,7 +156,7 @@ describe( 'useFeatureAction', () => { } ); await waitFor( () => expect( apiCalls( 'PUT' ) ).toHaveLength( 1 ) ); - expect( queryClient.getQueryData< Settings >( queryKeys.settings ) ).toMatchObject( { + expect( registry.select( store ).getSettings() ).toMatchObject( { button_style: 'icon', } ); @@ -184,6 +166,42 @@ describe( 'useFeatureAction', () => { } ); } ); + it( "drops a settings read that lands after a save's optimistic value", async () => { + let resolveRead!: ( value: Settings ) => void; + const read = new Promise< Settings >( resolve => ( resolveRead = resolve ) ); + let resolvePut!: ( value: Settings ) => void; + const put = new Promise< Settings >( resolve => ( resolvePut = resolve ) ); + mockApiFetch.mockImplementation( ( { method } ) => { + if ( method === 'POST' ) { + return Promise.resolve( switched ); + } + return method === 'PUT' ? put : read; + } ); + const registry = createTestRegistry(); + const { result } = renderHook( + () => ( { action: useFeatureAction(), save: useSaveSetting() } ), + { wrapper: wrapperFor( registry ) } + ); + + act( () => result.current.action.run( 'sharing', 'switch-to-block' ) ); + await waitFor( () => + expect( apiCalls() ).toContainEqual( { path: '/wpcom/v2/sharing-likes/settings' } ) + ); + let saved: Promise< unknown > = Promise.resolve(); + act( () => { + saved = result.current.save( 'button_style', 'icon' ); + } ); + await act( async () => resolveRead( baseSettings ) ); + + expect( registry.select( store ).getSettings()?.button_style ).toBe( 'icon' ); + + await waitFor( () => expect( apiCalls( 'PUT' ) ).toHaveLength( 1 ) ); + await act( async () => { + resolvePut( { ...baseSettings, button_style: 'icon' } ); + await saved; + } ); + } ); + it( 'keeps a queued order when the action before it reads services again', async () => { const services: Services = { visible: [ 'facebook', 'x' ], @@ -204,15 +222,10 @@ describe( 'useFeatureAction', () => { } return Promise.resolve( path?.endsWith( '/services' ) ? services : baseSettings ); } ); - const queryClient = createTestQueryClient(); - queryClient.setQueryData( queryKeys.services, services ); + const registry = createTestRegistry( { services } ); const { result } = renderHook( - () => { - useSettings(); - useServices( true ); - return { action: useFeatureAction(), save: useSaveServices() }; - }, - { wrapper: wrapperFor( queryClient ) } + () => ( { action: useFeatureAction(), save: useSaveServices() } ), + { wrapper: wrapperFor( registry ) } ); let saved: Promise< unknown > = Promise.resolve(); @@ -222,10 +235,7 @@ describe( 'useFeatureAction', () => { } ); await waitFor( () => expect( apiCalls( 'PUT' ) ).toHaveLength( 1 ) ); - expect( queryClient.getQueryData< Services >( queryKeys.services )?.visible ).toEqual( [ - 'x', - 'facebook', - ] ); + expect( registry.select( store ).getServices()?.visible ).toEqual( [ 'x', 'facebook' ] ); await act( async () => { resolvePut( { ...services, visible: [ 'x', 'facebook' ] } ); diff --git a/projects/packages/sharing-likes/src/settings-app/test/use-save-services.test.tsx b/projects/packages/sharing-likes/src/settings-app/test/use-save-services.test.tsx index 1c9bd23a01b5..bd80c64542f8 100644 --- a/projects/packages/sharing-likes/src/settings-app/test/use-save-services.test.tsx +++ b/projects/packages/sharing-likes/src/settings-app/test/use-save-services.test.tsx @@ -1,15 +1,13 @@ import { act, renderHook, waitFor } from '@testing-library/react'; import apiFetch from '@wordpress/api-fetch'; -import { select } from '@wordpress/data'; -import { store as noticesStore } from '@wordpress/notices'; -import { queryKeys, useServices, useSettings, useStatus } from '../data/queries'; +import { store } from '../data/store'; import { useSaveServices } from '../data/use-save-services'; import { apiCalls, baseSettings, baseStatus, - createTestQueryClient, - resetNotices, + createTestRegistry, + notices, snackbarMessages, wrapperFor, } from './helpers'; @@ -29,23 +27,14 @@ const services: Services = { }; /** - * Render the hook beside active status, settings and services queries, as the screen does. + * Render the hook in a registry seeded with the services. * - * @return Hook result and query client. + * @return Hook result and registry. */ function renderSave() { - const queryClient = createTestQueryClient(); - queryClient.setQueryData( queryKeys.services, services ); - const { result } = renderHook( - () => { - useStatus(); - useSettings(); - useServices( true ); - return useSaveServices(); - }, - { wrapper: wrapperFor( queryClient ) } - ); - return { result, queryClient }; + const registry = createTestRegistry( { services } ); + const { result } = renderHook( () => useSaveServices(), { wrapper: wrapperFor( registry ) } ); + return { result, registry }; } /** @@ -65,7 +54,6 @@ function deferred< T >() { beforeEach( () => { mockApiFetch.mockReset(); - resetNotices(); } ); describe( 'useSaveServices', () => { @@ -74,7 +62,7 @@ describe( 'useSaveServices', () => { mockApiFetch.mockImplementation( ( { method } ) => Promise.resolve( method === 'PUT' ? saved : services ) ); - const { result, queryClient } = renderSave(); + const { result, registry } = renderSave(); await act( () => result.current( { visible: [ 'x', 'facebook' ], hidden: [ 'email' ] } ) ); @@ -85,7 +73,7 @@ describe( 'useSaveServices', () => { data: { visible: [ 'x', 'facebook' ], hidden: [ 'email' ] }, }, ] ); - expect( queryClient.getQueryData( queryKeys.services ) ).toEqual( saved ); + expect( registry.select( store ).getServices() ).toEqual( saved ); expect( snackbarMessages() ).toContain( 'Settings have been saved' ); } ); @@ -102,14 +90,11 @@ describe( 'useSaveServices', () => { } return Promise.resolve( path?.endsWith( '/status' ) ? baseStatus : baseSettings ); } ); - const { result, queryClient } = renderSave(); + const { result, registry } = renderSave(); await act( () => result.current( { visible: [ 'x', 'facebook' ], hidden: [ 'email' ] } ) ); - expect( queryClient.getQueryData< Services >( queryKeys.services )?.visible ).toEqual( [ - 'facebook', - 'x', - ] ); + expect( registry.select( store ).getServices()?.visible ).toEqual( [ 'facebook', 'x' ] ); expect( snackbarMessages() ).toContain( 'Sharing buttons are not available on this site right now.' ); @@ -129,7 +114,7 @@ describe( 'useSaveServices', () => { puts += 1; return puts === 1 ? first.promise : second.promise; } ); - const { result, queryClient } = renderSave(); + const { result, registry } = renderSave(); let saves: Promise< unknown >[] = []; act( () => { @@ -140,7 +125,7 @@ describe( 'useSaveServices', () => { } ); await act( async () => first.resolve( { ...services, visible: [ 'x', 'facebook' ] } ) ); - expect( queryClient.getQueryData< Services >( queryKeys.services )?.visible ).toEqual( [ + expect( registry.select( store ).getServices()?.visible ).toEqual( [ 'x', 'email', 'facebook', @@ -178,9 +163,7 @@ describe( 'useSaveServices', () => { { message: 'X removed.', undo: { id: 'x', row: 'visible', index: 1 } } ) ); - const notice = select( noticesStore ) - .getNotices() - .find( ( { content } ) => content === 'X removed.' ); + const notice = notices().find( ( { content } ) => content === 'X removed.' ); await act( () => result.current( { visible: [ 'facebook', 'email' ], hidden: [] } ) ); await act( async () => notice?.actions?.[ 0 ]?.onClick?.() ); @@ -203,10 +186,12 @@ describe( 'useSaveServices', () => { { message: 'X removed.', undo: { id: 'x', row: 'visible', index: 1 } } ) ); + let next: Promise< unknown > = Promise.resolve(); act( () => { - result.current( { visible: [ 'facebook', 'email' ], hidden: [] } ); + next = result.current( { visible: [ 'facebook', 'email' ], hidden: [] } ); } ); expect( snackbarMessages() ).not.toContain( 'X removed.' ); + await act( () => next ); } ); } ); diff --git a/projects/packages/sharing-likes/src/settings-app/test/use-save-setting.test.tsx b/projects/packages/sharing-likes/src/settings-app/test/use-save-setting.test.tsx index 2305fd291e3d..b7ac5112cd4f 100644 --- a/projects/packages/sharing-likes/src/settings-app/test/use-save-setting.test.tsx +++ b/projects/packages/sharing-likes/src/settings-app/test/use-save-setting.test.tsx @@ -1,13 +1,12 @@ import { act, renderHook, waitFor } from '@testing-library/react'; import apiFetch from '@wordpress/api-fetch'; -import { queryKeys, useSettings, useStatus } from '../data/queries'; +import { store } from '../data/store'; import { useSaveSetting } from '../data/use-save-setting'; import { apiCalls, baseSettings, baseStatus, - createTestQueryClient, - resetNotices, + createTestRegistry, snackbarMessages, wrapperFor, } from './helpers'; @@ -17,21 +16,14 @@ jest.mock( '@wordpress/api-fetch' ); const mockApiFetch = apiFetch as jest.MockedFunction< typeof apiFetch >; /** - * Render the save hook alongside active status and settings queries, as the screen does. + * Render the save hook in a seeded registry. * - * @return Hook result and query client. + * @return Hook result and registry. */ function renderSave() { - const queryClient = createTestQueryClient(); - const { result } = renderHook( - () => { - useStatus(); - useSettings(); - return useSaveSetting(); - }, - { wrapper: wrapperFor( queryClient ) } - ); - return { result, queryClient }; + const registry = createTestRegistry(); + const { result } = renderHook( () => useSaveSetting(), { wrapper: wrapperFor( registry ) } ); + return { result, registry }; } /** @@ -51,7 +43,6 @@ function deferred< T >() { beforeEach( () => { mockApiFetch.mockReset(); - resetNotices(); } ); describe( 'useSaveSetting', () => { @@ -72,17 +63,17 @@ describe( 'useSaveSetting', () => { expect( snackbarMessages() ).toContain( 'Settings have been saved' ); } ); - it( 'replaces the cached settings with the response', async () => { + it( 'replaces the stored settings with the response', async () => { // Saving can change which settings are offered, so keys come and go. const saved: Settings = { likes_enabled: true, reblogs_enabled: true, button_style: 'icon' }; mockApiFetch.mockImplementation( ( { method } ) => Promise.resolve( method === 'PUT' ? saved : baseStatus ) ); - const { result, queryClient } = renderSave(); + const { result, registry } = renderSave(); await act( () => result.current( 'button_style', 'icon' ) ); - expect( queryClient.getQueryData< Settings >( queryKeys.settings ) ).toEqual( saved ); + expect( registry.select( store ).getSettings() ).toEqual( saved ); } ); it( 'rolls back and shows the server message when a save fails', async () => { @@ -96,11 +87,11 @@ describe( 'useSaveSetting', () => { // A settings read that never lands, so only the rollback can restore the value. return path?.endsWith( '/status' ) ? Promise.resolve( baseStatus ) : new Promise( () => {} ); } ); - const { result, queryClient } = renderSave(); + const { result, registry } = renderSave(); await act( () => result.current( 'comment_likes_enabled', true ) ); - expect( queryClient.getQueryData< Settings >( queryKeys.settings ) ).toMatchObject( { + expect( registry.select( store ).getSettings() ).toMatchObject( { comment_likes_enabled: false, } ); expect( snackbarMessages() ).toContain( @@ -132,7 +123,7 @@ describe( 'useSaveSetting', () => { } return 'likes_enabled' in ( data as object ) ? first.promise : second.promise; } ); - const { result, queryClient } = renderSave(); + const { result, registry } = renderSave(); let saves: Promise< unknown >[] = []; act( () => { @@ -149,7 +140,7 @@ describe( 'useSaveSetting', () => { } ); await waitFor( () => expect( apiCalls( 'PUT' ) ).toHaveLength( 2 ) ); - expect( queryClient.getQueryData< Settings >( queryKeys.settings ) ).toMatchObject( { + expect( registry.select( store ).getSettings() ).toMatchObject( { likes_enabled: likesEnabled, button_style: 'icon', } ); @@ -171,7 +162,7 @@ describe( 'useSaveSetting', () => { } return apiCalls( 'PUT' ).length === 1 ? first.promise : second.promise; } ); - const { result, queryClient } = renderSave(); + const { result, registry } = renderSave(); let saves: Promise< unknown >[] = []; act( () => { @@ -185,9 +176,7 @@ describe( 'useSaveSetting', () => { await saves[ 0 ]; } ); - expect( queryClient.getQueryData< Settings >( queryKeys.settings )?.button_style ).toBe( - 'text' - ); + expect( registry.select( store ).getSettings()?.button_style ).toBe( 'text' ); await act( async () => { second.resolve( { ...baseSettings, button_style: 'text' } ); @@ -195,7 +184,7 @@ describe( 'useSaveSetting', () => { } ); } ); - it( 'sends a queued save without waiting on retries of a failed status read', async () => { + it( 'sends a queued save after a failed status read', async () => { mockApiFetch.mockImplementation( ( { method, path } ) => { if ( method === 'PUT' ) { return Promise.resolve( baseSettings ); From 71929828a96f33c9d503bbe9d01b86061c1292b4 Mon Sep 17 00:00:00 2001 From: Jeremy Herve Date: Tue, 20 Oct 2026 15:22:43 +0200 Subject: [PATCH 2/4] Sharing & Likes: Keep the services 409 note in one place --- projects/packages/sharing-likes/src/settings-app/data/store.ts | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/projects/packages/sharing-likes/src/settings-app/data/store.ts b/projects/packages/sharing-likes/src/settings-app/data/store.ts index bfa4a49aa2b8..685a2ffc547d 100644 --- a/projects/packages/sharing-likes/src/settings-app/data/store.ts +++ b/projects/packages/sharing-likes/src/settings-app/data/store.ts @@ -154,7 +154,7 @@ const selectors = { getSettings: ( state: State ): Settings | undefined => state.settings, /** - * The enabled services. The route answers 409 unless the Sharing section configures. + * The enabled services. * * @param state - State. * @return Services, once known. From cf6fa11278aff94ea62031a18ff64737cc1697c6 Mon Sep 17 00:00:00 2001 From: Jeremy Herve Date: Tue, 20 Oct 2026 15:35:47 +0200 Subject: [PATCH 3/4] Sharing & Likes: Keep rereads ordered and their failures current Rereads went through @wordpress/data's resolver metadata, which cannot cancel a read already in flight. An earlier read finishing late could then mark a newer, failed read as done, leaving the services list on a spinner for good, and a reread took its version only once the resolver started, a tick after it was asked for, so it could land on top of an optimistic value made in between. Reads now record their own failures, versioned like their data, and reread takes its version when it is called. A services list that could not be loaded reads again when it next appears, as it did before. Also covers two guarantees no test held: the queue keeps going after a refused write, and the leave-page warning turns off once writes settle. --- .../src/settings-app/data/queries.ts | 13 ++- .../src/settings-app/data/store.ts | 105 ++++++++++++++---- .../src/settings-app/data/writes.ts | 59 ++++------ .../test/settings-screen.test.tsx | 25 ++++- .../src/settings-app/test/store.test.ts | 71 ++++++++++++ .../test/use-save-services.test.tsx | 26 +++++ .../settings-app/test/use-services.test.tsx | 26 +++++ 7 files changed, 262 insertions(+), 63 deletions(-) create mode 100644 projects/packages/sharing-likes/src/settings-app/test/store.test.ts create mode 100644 projects/packages/sharing-likes/src/settings-app/test/use-services.test.tsx diff --git a/projects/packages/sharing-likes/src/settings-app/data/queries.ts b/projects/packages/sharing-likes/src/settings-app/data/queries.ts index 53b3052227b6..9340e39a4e46 100644 --- a/projects/packages/sharing-likes/src/settings-app/data/queries.ts +++ b/projects/packages/sharing-likes/src/settings-app/data/queries.ts @@ -1,4 +1,5 @@ -import { useSelect } from '@wordpress/data'; +import { useRegistry, useSelect } from '@wordpress/data'; +import { useEffect } from '@wordpress/element'; import { store } from './store'; import type { Services, Settings, Status } from '../types'; @@ -30,13 +31,21 @@ export function useServices( enabled: boolean ): { data: Services | undefined; isPending: boolean; } { + const registry = useRegistry(); + // A list that could not be loaded tries again when it next appears. + useEffect( () => { + if ( enabled && registry.select( store ).hasReadFailed( 'services' ) ) { + registry.dispatch( store ).reread( 'services' ); + } + }, [ enabled, registry ] ); + return useSelect( select => { if ( ! enabled ) { return { data: undefined, isPending: true }; } const data = select( store ).getServices(); - return { data, isPending: ! data && ! select( store ).hasResolutionFailed( 'getServices' ) }; + return { data, isPending: ! data && ! select( store ).hasReadFailed( 'services' ) }; }, [ enabled ] ); diff --git a/projects/packages/sharing-likes/src/settings-app/data/store.ts b/projects/packages/sharing-likes/src/settings-app/data/store.ts index 685a2ffc547d..8010e9f4a301 100644 --- a/projects/packages/sharing-likes/src/settings-app/data/store.ts +++ b/projects/packages/sharing-likes/src/settings-app/data/store.ts @@ -3,7 +3,7 @@ import { fetchServices, fetchSettings, fetchStatus } from './api'; import * as writes from './writes'; import type { Services, Settings, SharingLikesScriptData, Status } from '../types'; -export const STORE_NAME = 'jetpack-sharing-likes/settings'; +const STORE_NAME = 'jetpack-sharing-likes/settings'; export type Slice = 'status' | 'settings' | 'services'; @@ -21,6 +21,8 @@ export interface State { services?: Services; // Bumped by every local change to a slice, so a read that started before it is dropped when it lands. versions: Record< Slice, number >; + // Whether the latest read of a slice failed. + failed: Record< Slice, boolean >; // Writes queued or in flight, by kind. pending: Record< WriteKind, number >; } @@ -28,10 +30,12 @@ export interface State { type Action = | { type: 'RECEIVE'; slice: Slice; value: Slices[ Slice ]; since?: number } | { type: 'DISCARD_READS'; slice: Slice } + | { type: 'READ_FAILED'; slice: Slice; since: number } | { type: 'WRITE_STARTED' | 'WRITE_SETTLED'; kind: WriteKind }; const DEFAULT_STATE: State = { versions: { status: 0, settings: 0, services: 0 }, + failed: { status: false, settings: false, services: false }, pending: { setting: 0, services: 0, 'custom-service': 0, 'feature-action': 0 }, }; @@ -45,21 +49,28 @@ const DEFAULT_STATE: State = { function reducer( state: State = DEFAULT_STATE, action: Action ): State { switch ( action.type ) { case 'RECEIVE': - if ( action.since === undefined ) { - return { - ...state, - [ action.slice ]: action.value, - versions: { ...state.versions, [ action.slice ]: state.versions[ action.slice ] + 1 }, - }; + if ( action.since !== undefined && action.since !== state.versions[ action.slice ] ) { + return state; } - return action.since === state.versions[ action.slice ] - ? { ...state, [ action.slice ]: action.value } - : state; + return { + ...state, + [ action.slice ]: action.value, + versions: + action.since === undefined + ? { ...state.versions, [ action.slice ]: state.versions[ action.slice ] + 1 } + : state.versions, + failed: { ...state.failed, [ action.slice ]: false }, + }; case 'DISCARD_READS': return { ...state, versions: { ...state.versions, [ action.slice ]: state.versions[ action.slice ] + 1 }, + failed: { ...state.failed, [ action.slice ]: false }, }; + case 'READ_FAILED': + return action.since === state.versions[ action.slice ] + ? { ...state, failed: { ...state.failed, [ action.slice ]: true } } + : state; case 'WRITE_STARTED': case 'WRITE_SETTLED': return { @@ -98,6 +109,30 @@ const actions = { return { type: 'DISCARD_READS', slice }; }, + /** + * Record that a read which started at that version failed. + * + * @param slice - Slice. + * @param since - The slice's version when the read started. + * @return Action. + */ + readFailed( slice: Slice, since: number ): Action { + return { type: 'READ_FAILED', slice, since }; + }, + + /** + * Read a slice again, dropping any read of it already in flight. + * + * @param slice - Slice. + * @return Thunk resolving once the read lands or fails. + */ + reread: + ( slice: Slice ) => + ( { select, dispatch }: { select: ThunkSelect; dispatch: ThunkDispatch } ) => { + dispatch.discardReads( slice ); + return load( dispatch, slice, select.getVersion( slice ) ); + }, + /** * Count a write as queued. * @@ -181,27 +216,54 @@ const selectors = { * @return Version. */ getVersion: ( state: State, slice: Slice ): number => state.versions[ slice ], + + /** + * Whether the latest read of a slice failed. + * + * @param state - State. + * @param slice - Slice. + * @return Whether it failed. + */ + hasReadFailed: ( state: State, slice: Slice ): boolean => state.failed[ slice ], }; +const FETCHERS: { [ S in Slice ]: () => Promise< Slices[ S ] > } = { + status: fetchStatus, + settings: fetchSettings, + services: fetchServices, +}; + +/** + * Read a slice, keeping the answer or the failure only while the slice is still at `since`. + * + * @param dispatch - Thunk dispatch. + * @param slice - Slice. + * @param since - The slice's version when the read started. + */ +async function load( dispatch: ThunkDispatch, slice: Slice, since: number ) { + try { + dispatch.receive( slice, await FETCHERS[ slice ](), since ); + } catch { + dispatch.readFailed( slice, since ); + } +} + /** - * A resolver that stores what it read unless the slice changed locally meanwhile. + * A resolver that reads its slice at the slice's current version. * * @param slice - Slice. - * @param fetch - Request. * @return Resolver. */ -function read< S extends Slice >( slice: S, fetch: () => Promise< Slices[ S ] > ) { +function read( slice: Slice ) { return () => - async ( { select, dispatch }: { select: ThunkSelect; dispatch: ThunkDispatch } ) => { - const since = select.getVersion( slice ); - dispatch.receive( slice, await fetch(), since ); - }; + ( { select, dispatch }: { select: ThunkSelect; dispatch: ThunkDispatch } ) => + load( dispatch, slice, select.getVersion( slice ) ); } const resolvers = { - getStatus: read( 'status', fetchStatus ), - getSettings: read( 'settings', fetchSettings ), - getServices: read( 'services', fetchServices ), + getStatus: read( 'status' ), + getSettings: read( 'settings' ), + getServices: read( 'services' ), }; export type ThunkSelect = { @@ -216,9 +278,10 @@ export type ThunkSelect = { export type ThunkDispatch = { receive: < S extends Slice >( slice: S, value: Slices[ S ], since?: number ) => void; discardReads: ( slice: Slice ) => void; + readFailed: ( slice: Slice, since: number ) => void; + reread: ( slice: Slice ) => Promise< void >; writeStarted: ( kind: WriteKind ) => void; writeSettled: ( kind: WriteKind ) => void; - invalidateResolution: ( selector: string, args: unknown[] ) => void; finishResolution: ( selector: string, args: unknown[] ) => void; saveServices: ( ...args: Parameters< typeof writes.saveServices > ) => Promise< unknown >; }; diff --git a/projects/packages/sharing-likes/src/settings-app/data/writes.ts b/projects/packages/sharing-likes/src/settings-app/data/writes.ts index 7fcf53898d1d..e19eaf9149e5 100644 --- a/projects/packages/sharing-likes/src/settings-app/data/writes.ts +++ b/projects/packages/sharing-likes/src/settings-app/data/writes.ts @@ -3,7 +3,7 @@ import { store as noticesStore } from '@wordpress/notices'; import { configures } from '../types'; import * as api from './api'; import { errorMessage } from './error-message'; -import type { Slice, ThunkDispatch, ThunkSelect, WriteKind } from './store'; +import type { ThunkDispatch, ThunkSelect, WriteKind } from './store'; import type { CustomServiceFields, Feature, @@ -18,7 +18,6 @@ import type { dispatch as registryDispatch } from '@wordpress/data'; interface ThunkArgs { select: ThunkSelect; dispatch: ThunkDispatch; - resolveSelect: Record< 'getStatus' | 'getSettings' | 'getServices', () => Promise< unknown > >; registry: { dispatch: typeof registryDispatch }; } @@ -33,8 +32,6 @@ export interface SaveServicesOptions { undo?: { id: string; row: ServiceRow; index: number }; } -const READERS = { status: 'getStatus', settings: 'getSettings', services: 'getServices' } as const; - // One snackbar for a run of moves, rather than one per tap. const SAVED_NOTICE_ID = 'sharing-likes-services-saved'; @@ -64,21 +61,16 @@ async function queued< T >( args: ThunkArgs, kind: WriteKind, task: () => Promis } /** - * Read a slice again, dropping any read of it already in flight. + * Whether this is the only write of its kind queued or in flight. + * + * Each save response carries its whole slice, so storing one while a later save of its kind waits would undo that save. * - * @param args - Thunk arguments. - * @param slice - Slice. - * @return Resolves once the read lands or fails. + * @param args - Thunk arguments. + * @param kind - Write kind. + * @return Whether it is the last. */ -async function reread( args: ThunkArgs, slice: Slice ) { - args.dispatch.discardReads( slice ); - args.dispatch.invalidateResolution( READERS[ slice ], [] ); - try { - await args.resolveSelect[ READERS[ slice ] ](); - } catch { - // The screen keeps what it has. - } -} +const isLastWrite = ( args: ThunkArgs, kind: WriteKind ) => + args.select.getPendingWrites( kind ) <= 1; /** * Notices dispatcher. @@ -101,14 +93,12 @@ export const saveSetting = const { select, dispatch } = args; const previous = select.getSettings()?.[ key ]; dispatch.receive( 'settings', { ...select.getSettings(), [ key ]: value } ); - const isLastSave = () => select.getPendingWrites( 'setting' ) <= 1; return queued( args, 'setting', async () => { let saved: Settings | undefined; try { saved = await api.saveSetting( key, value ); - // Each response carries every setting, so one landing while another save waits would undo that save's value. - if ( isLastSave() ) { + if ( isLastWrite( args, 'setting' ) ) { dispatch.receive( 'settings', saved ); } notices( args ).createSuccessNotice( @@ -127,12 +117,12 @@ export const saveSetting = ); // A refused save usually means the screen is out of date: another tab, or a host forcing a module. // A queued save's response refreshes the settings instead, without racing its optimistic value. - if ( isLastSave() ) { - reread( args, 'settings' ); + if ( isLastWrite( args, 'setting' ) ) { + dispatch.reread( 'settings' ); } } // Saving Comment Likes can change which sections configure, and so which settings are offered. - await reread( args, 'status' ); + await dispatch.reread( 'status' ); return saved; } ); }; @@ -170,7 +160,6 @@ export const saveServices = } else { dispatch.discardReads( 'services' ); } - const isLastSave = () => select.getPendingWrites( 'services' ) <= 1; const restore = () => { const latest = select.getServices(); @@ -193,13 +182,11 @@ export const saveServices = let response: Services | undefined; try { response = await api.saveServices( lists.visible, lists.hidden ); - // Each response carries both lists, so one landing while another save waits would undo that save's order. - if ( isLastSave() ) { + if ( isLastWrite( args, 'services' ) ) { dispatch.receive( 'services', response ); } } catch ( error ) { refused = error ?? new Error(); - // A later change replaced these lists, and its own save settles them. const latest = select.getServices(); if ( latest && sameLists( latest, lists ) ) { dispatch.receive( 'services', { ...latest, ...previous } ); @@ -211,15 +198,15 @@ export const saveServices = ), { type: 'snackbar' } ); - if ( isLastSave() ) { - reread( args, 'services' ); + if ( isLastWrite( args, 'services' ) ) { + dispatch.reread( 'services' ); } } - // A refusal usually means the screen is stale, and an empty list hands a block theme's section to the block. + // A refusal, or an empty list on a block theme, can change which sections configure. if ( refused || lists.visible.length + lists.hidden.length === 0 ) { await Promise.all( [ - reread( args, 'status' ), - select.getPendingWrites( 'setting' ) > 0 ? undefined : reread( args, 'settings' ), + dispatch.reread( 'status' ), + select.getPendingWrites( 'setting' ) > 0 ? undefined : dispatch.reread( 'settings' ), ] ); } if ( refused ) { @@ -401,15 +388,15 @@ export const runFeatureAction = const sharing = select.getStatus()?.sharing.state; // Which settings are offered follows the section variants; awaited so the next write waits for them. await Promise.all( [ - failed ? reread( args, 'status' ) : undefined, + failed ? dispatch.reread( 'status' ) : undefined, // A pending save's response brings fresh settings, and this read could land after it. - select.getPendingWrites( 'setting' ) > 0 ? undefined : reread( args, 'settings' ), - // The route answers 409 once Sharing stops configuring, and a pending services save brings fresh lists. + select.getPendingWrites( 'setting' ) > 0 ? undefined : dispatch.reread( 'settings' ), + // Services only read while Sharing configures (see `useServices()`), and a pending services save brings fresh lists. ! failed && !! sharing && configures( sharing ) && select.getPendingWrites( 'services' ) === 0 - ? reread( args, 'services' ) + ? dispatch.reread( 'services' ) : undefined, ] ); } ); diff --git a/projects/packages/sharing-likes/src/settings-app/test/settings-screen.test.tsx b/projects/packages/sharing-likes/src/settings-app/test/settings-screen.test.tsx index d882913fd18d..cbbd621401a3 100644 --- a/projects/packages/sharing-likes/src/settings-app/test/settings-screen.test.tsx +++ b/projects/packages/sharing-likes/src/settings-app/test/settings-screen.test.tsx @@ -4,7 +4,7 @@ import { LIKES_ANCHOR } from '../anchors'; import { useFeatureAction } from '../data/use-feature-action'; import { useSaveSetting } from '../data/use-save-setting'; import { SettingsScreen } from '../settings-screen'; -import { baseStatus, renderWithData, setScriptData } from './helpers'; +import { baseSettings, baseStatus, renderWithData, setScriptData } from './helpers'; import type { ReactNode } from 'react'; jest.mock( '@wordpress/api-fetch' ); @@ -85,9 +85,23 @@ describe( 'SettingsScreen', () => { ); it.each( [ - [ 'a save', ( write: Writes ) => write.save( 'likes_enabled', false ) ], - [ 'a feature action', ( write: Writes ) => write.action( 'sharing', 'switch-to-block' ) ], - ] )( 'warns before leaving while %s is in flight', async ( _, start ) => { + [ 'a save', ( write: Writes ) => write.save( 'likes_enabled', false ), baseSettings ], + [ + 'a feature action', + ( write: Writes ) => write.action( 'sharing', 'switch-to-block' ), + baseStatus, + ], + ] )( 'warns before leaving only while %s is in flight', async ( _, start, response ) => { + let finish!: ( value: unknown ) => void; + mockApiFetch.mockImplementation( ( { method, path } ) => { + if ( method ) { + return new Promise( resolve => ( finish = resolve ) ); + } + if ( path?.endsWith( '/services' ) ) { + return Promise.resolve( { visible: [], hidden: [], services: [] } ); + } + return Promise.resolve( path?.endsWith( '/status' ) ? baseStatus : baseSettings ); + } ); let writes: Writes | undefined; /** * Renders the screen and exposes its writes to the test. @@ -106,5 +120,8 @@ describe( 'SettingsScreen', () => { } ); await waitFor( () => expect( leavingPrompts() ).toBe( true ) ); + + act( () => finish( response ) ); + await waitFor( () => expect( leavingPrompts() ).toBe( false ) ); } ); } ); diff --git a/projects/packages/sharing-likes/src/settings-app/test/store.test.ts b/projects/packages/sharing-likes/src/settings-app/test/store.test.ts new file mode 100644 index 000000000000..f52c4663ddfa --- /dev/null +++ b/projects/packages/sharing-likes/src/settings-app/test/store.test.ts @@ -0,0 +1,71 @@ +import { act } from '@testing-library/react'; +import apiFetch from '@wordpress/api-fetch'; +import { store } from '../data/store'; +import { baseSettings, createTestRegistry } from './helpers'; +import type { Services } from '../types'; + +jest.mock( '@wordpress/api-fetch' ); +const mockApiFetch = apiFetch as jest.MockedFunction< typeof apiFetch >; + +/** + * A promise and the functions that settle it. + * + * @return Deferred. + */ +function deferred< T >() { + let resolve!: ( value: T ) => void; + let reject!: ( reason: unknown ) => void; + const promise = new Promise< T >( ( res, rej ) => { + resolve = res; + reject = rej; + } ); + return { promise, resolve, reject }; +} + +beforeEach( () => { + mockApiFetch.mockReset(); +} ); + +describe( 'store reads', () => { + it( 'drops a reread that lands after a local change made right after it was asked for', async () => { + const read = deferred< unknown >(); + mockApiFetch.mockImplementation( () => read.promise ); + const registry = createTestRegistry(); + + const reread = registry.dispatch( store ).reread( 'settings' ); + registry.dispatch( store ).receive( 'settings', { ...baseSettings, button_style: 'icon' } ); + await act( async () => { + read.resolve( baseSettings ); + await reread; + } ); + + expect( registry.select( store ).getSettings()?.button_style ).toBe( 'icon' ); + } ); + + it( 'keeps the latest services read failing when an earlier read lands after it', async () => { + const first = deferred< Services >(); + const second = deferred< Services >(); + let reads = 0; + mockApiFetch.mockImplementation( () => { + reads += 1; + return reads === 1 ? first.promise : second.promise; + } ); + const registry = createTestRegistry(); + + await act( async () => { + registry.select( store ).getServices(); + // Resolvers start on the next tick. + await new Promise( resolve => setTimeout( resolve ) ); + } ); + const reread = registry.dispatch( store ).reread( 'services' ); + await act( async () => { + second.reject( { message: 'Gone.' } ); + await reread; + first.resolve( { visible: [ 'x' ], hidden: [], services: [] } ); + } ); + + expect( reads ).toBe( 2 ); + expect( registry.select( store ).getServices() ).toBeUndefined(); + expect( registry.select( store ).hasReadFailed( 'services' ) ).toBe( true ); + } ); +} ); diff --git a/projects/packages/sharing-likes/src/settings-app/test/use-save-services.test.tsx b/projects/packages/sharing-likes/src/settings-app/test/use-save-services.test.tsx index bd80c64542f8..84dd261847d2 100644 --- a/projects/packages/sharing-likes/src/settings-app/test/use-save-services.test.tsx +++ b/projects/packages/sharing-likes/src/settings-app/test/use-save-services.test.tsx @@ -137,6 +137,32 @@ describe( 'useSaveServices', () => { } ); } ); + it( 'sends a queued save once the save before it is refused', async () => { + let puts = 0; + mockApiFetch.mockImplementation( ( { method, path } ) => { + if ( method === 'PUT' ) { + puts += 1; + return puts === 1 ? Promise.reject( { message: 'Refused.' } ) : Promise.resolve( services ); + } + const reads: Record< string, unknown > = { + status: baseStatus, + settings: baseSettings, + services, + }; + return Promise.resolve( reads[ path?.split( '/' ).pop() ?? '' ] ); + } ); + const { result } = renderSave(); + + await act( () => + Promise.all( [ + result.current( { visible: [ 'x', 'facebook' ], hidden: [ 'email' ] } ), + result.current( { visible: [ 'x', 'email', 'facebook' ], hidden: [] } ), + ] ) + ); + + expect( apiCalls( 'PUT' ) ).toHaveLength( 2 ); + } ); + it( 'rereads status and settings once no service is left', async () => { mockApiFetch.mockImplementation( ( { method } ) => Promise.resolve( method === 'PUT' ? { ...services, visible: [], hidden: [] } : baseStatus ) diff --git a/projects/packages/sharing-likes/src/settings-app/test/use-services.test.tsx b/projects/packages/sharing-likes/src/settings-app/test/use-services.test.tsx new file mode 100644 index 000000000000..49dac729a000 --- /dev/null +++ b/projects/packages/sharing-likes/src/settings-app/test/use-services.test.tsx @@ -0,0 +1,26 @@ +import { renderHook, waitFor } from '@testing-library/react'; +import apiFetch from '@wordpress/api-fetch'; +import { useServices } from '../data/queries'; +import { createTestRegistry, wrapperFor } from './helpers'; +import type { Services } from '../types'; + +jest.mock( '@wordpress/api-fetch' ); +const mockApiFetch = apiFetch as jest.MockedFunction< typeof apiFetch >; + +const services: Services = { visible: [ 'x' ], hidden: [], services: [] }; + +describe( 'useServices', () => { + it( 'reads the services again when a list that could not be loaded appears again', async () => { + mockApiFetch.mockReset(); + mockApiFetch.mockRejectedValueOnce( { message: 'Gone.' } ).mockResolvedValue( services ); + const wrapper = wrapperFor( createTestRegistry() ); + + const { result: failed, unmount } = renderHook( () => useServices( true ), { wrapper } ); + await waitFor( () => expect( failed.current.isPending ).toBe( false ) ); + expect( failed.current.data ).toBeUndefined(); + unmount(); + + const { result } = renderHook( () => useServices( true ), { wrapper } ); + await waitFor( () => expect( result.current.data ).toEqual( services ) ); + } ); +} ); From 031b7827a4b71a8d308835b918880dda73d3dc07 Mon Sep 17 00:00:00 2001 From: Jeremy Herve Date: Tue, 20 Oct 2026 15:36:38 +0200 Subject: [PATCH 4/4] Sharing & Likes: Clarify when the feature action rereads services --- projects/packages/sharing-likes/src/settings-app/data/writes.ts | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/projects/packages/sharing-likes/src/settings-app/data/writes.ts b/projects/packages/sharing-likes/src/settings-app/data/writes.ts index e19eaf9149e5..0571254dd401 100644 --- a/projects/packages/sharing-likes/src/settings-app/data/writes.ts +++ b/projects/packages/sharing-likes/src/settings-app/data/writes.ts @@ -391,7 +391,7 @@ export const runFeatureAction = failed ? dispatch.reread( 'status' ) : undefined, // A pending save's response brings fresh settings, and this read could land after it. select.getPendingWrites( 'setting' ) > 0 ? undefined : dispatch.reread( 'settings' ), - // Services only read while Sharing configures (see `useServices()`), and a pending services save brings fresh lists. + // Services can only be read while Sharing configures (see `useServices()`); a pending services save brings fresh lists. ! failed && !! sharing && configures( sharing ) &&