Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
Expand Up @@ -43,6 +43,7 @@ jest.mock( '@wordpress/data', () => ( {
return newState;
} ),
register: jest.fn(),
keyedReducer: jest.fn( () => ( reducer ) => reducer ),
} ) );

const mockSetAttributes = jest.fn();
Expand Down
17 changes: 6 additions & 11 deletions packages/core-data/src/queried-data/reducer.js
Original file line number Diff line number Diff line change
@@ -1,18 +1,13 @@
/**
* WordPress dependencies
*/
import { combineReducers } from '@wordpress/data';
import { combineReducers, keyedReducer } from '@wordpress/data';
import { compose } from '@wordpress/compose';

/**
* Internal dependencies
*/
import {
conservativeMapItem,
ifMatchingAction,
replaceAction,
onSubKey,
} from '../utils';
import { conservativeMapItem, ifMatchingAction, replaceAction } from '../utils';
import { DEFAULT_ENTITY_KEY } from '../entities';
import getQueryParts from './get-query-parts';

Expand Down Expand Up @@ -221,11 +216,11 @@ const receiveQueries = compose( [
// an unhandled action.
ifMatchingAction( ( action ) => 'query' in action ),

// Inject query parts into action for use both in `onSubKey` and reducer.
// Inject query parts into action for use both in `keyedReducer` and reducer.
replaceAction( ( action ) => {
// `ifMatchingAction` still passes on initialization, where state is
// undefined and a query is not assigned. Avoid attempting to parse
// parts. `onSubKey` will omit by lack of `stableKey`.
// parts. `keyedReducer` will omit by lack of `stableKey`.
if ( action.query ) {
return {
...action,
Expand All @@ -236,11 +231,11 @@ const receiveQueries = compose( [
return action;
} ),

onSubKey( 'context' ),
keyedReducer( 'context' ),

// Queries shape is shared, but keyed by query `stableKey` part. Original
// reducer tracks only a single query object.
onSubKey( 'stableKey' ),
keyedReducer( 'stableKey' ),
] )( ( state = {}, action ) => {
if ( action.type !== 'RECEIVE_ITEMS' ) {
return state;
Expand Down
1 change: 0 additions & 1 deletion packages/core-data/src/utils/index.js
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,6 @@ export { default as conservativeMapItem } from './conservative-map-item';
export { default as getNormalizedCommaSeparable } from './get-normalized-comma-separable';
export { default as ifMatchingAction } from './if-matching-action';
export { default as forwardResolver } from './forward-resolver';
export { default as onSubKey } from './on-sub-key';
export { default as replaceAction } from './replace-action';
export { default as withWeakMapCache } from './with-weak-map-cache';
export { default as setNestedValue } from './set-nested-value';
Expand Down
35 changes: 0 additions & 35 deletions packages/core-data/src/utils/on-sub-key.js

This file was deleted.

4 changes: 4 additions & 0 deletions packages/data/CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,10 @@

## Unreleased

### New Features

- Export `keyedReducer` higher-order reducer helper, consolidating duplicated copies previously maintained in `@wordpress/core-data` and `@wordpress/notices` ([#77364](https://github.com/WordPress/gutenberg/pull/77364)).

## 10.44.0 (2026-04-15)

## 10.43.0 (2026-04-01)
Expand Down
26 changes: 26 additions & 0 deletions packages/data/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -506,6 +506,32 @@ _Returns_

- `DispatchReturn< StoreNameOrDescriptor >`: Object containing the action creators.

### keyedReducer

Higher-order reducer creator which creates a combined reducer object, keyed by a property on the action object.

_Usage_

```js
import { keyedReducer } from '@wordpress/data';

const itemsByContext = keyedReducer( 'context' )( ( state = [], action ) => {
switch ( action.type ) {
case 'ADD_ITEM':
return [ ...state, action.item ];
}
return state;
} );
```

_Parameters_

- _actionProperty_ `string`: Action property by which to key object.

_Returns_

- Higher-order reducer.

### plugins

Object of available plugins to use with a registry.
Expand Down
1 change: 1 addition & 0 deletions packages/data/src/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -32,6 +32,7 @@ export { createRegistrySelector, createRegistryControl } from './factory';
export { createSelector } from './create-selector';
export { controls } from './controls';
export { default as createReduxStore } from './redux-store';
export { keyedReducer } from './redux-store/keyed-reducer';
export { dispatch } from './dispatch';
export { select } from './select';

Expand Down
Original file line number Diff line number Diff line change
@@ -1,22 +1,36 @@
/**
* External dependencies
*/
import type { Reducer, Action } from 'redux';
import type { AnyAction, Reducer } from 'redux';

/**
* Higher-order reducer creator which creates a combined reducer object, keyed
* by a property on the action object.
*
* @param actionProperty Action property by which to key object.
*
* @return Higher-order reducer.
*
* @example
* ```js
* import { keyedReducer } from '@wordpress/data';
*
* const itemsByContext = keyedReducer( 'context' )( ( state = [], action ) => {
* switch ( action.type ) {
* case 'ADD_ITEM':
* return [ ...state, action.item ];
* }
* return state;
* } );
* ```
*/
export const onSubKey =
( actionProperty: string ) =>
< S, A extends Action & Record< string, any > >(
reducer: Reducer< S, A >
export const keyedReducer =
< TState extends unknown, TAction extends AnyAction >(
actionProperty: string
) =>
( state: Record< string, S > = {}, action: A ) => {
(
reducer: Reducer< TState, TAction >
): Reducer< Record< string, TState >, TAction > =>
( state: Record< string, TState > = {}, action ) => {
// Retrieve subkey from action. Do not track if undefined; useful for cases
// where reducer is scoped by action shape.
const key = action[ actionProperty ];
Expand All @@ -36,5 +50,3 @@ export const onSubKey =
[ key ]: nextKeyState,
};
};

export default onSubKey;
12 changes: 8 additions & 4 deletions packages/data/src/redux-store/metadata/reducer.ts
Original file line number Diff line number Diff line change
Expand Up @@ -19,7 +19,8 @@ import type {
/**
* Internal dependencies
*/
import { selectorArgsToStateKey, onSubKey } from './utils';
import { keyedReducer } from '../keyed-reducer';
import { selectorArgsToStateKey } from './utils';

type Action =
| ReturnType< typeof startResolution >
Expand All @@ -46,10 +47,13 @@ export type State = EquivalentKeyMap< StateKey, StateValue >;
*
* selectorName -> EquivalentKeyMap<Array,boolean>
*/
const subKeysIsResolved: Reducer< Record< string, State >, Action > = onSubKey<
State,
const subKeysIsResolved: Reducer<
Record< string, State >,
Action
>( 'selectorName' )( ( state = new EquivalentKeyMap(), action: Action ) => {
> = keyedReducer< State, Action >( 'selectorName' )( (
state = new EquivalentKeyMap(),
action: Action
) => {
switch ( action.type ) {
case 'START_RESOLUTION': {
const nextState = new EquivalentKeyMap( state );
Expand Down
39 changes: 1 addition & 38 deletions packages/data/src/redux-store/metadata/test/utils.js
Original file line number Diff line number Diff line change
@@ -1,44 +1,7 @@
/**
* Internal dependencies
*/
import { selectorArgsToStateKey, onSubKey } from '../utils';

describe( 'onSubKey', () => {
function createEnhancedReducer( actionProperty ) {
const enhanceReducer = onSubKey( actionProperty );
return enhanceReducer(
( state, action ) => 'Called by ' + action.caller
);
}

it( 'should default to an empty object', () => {
const reducer = createEnhancedReducer( 'caller' );
const nextState = reducer( undefined, { type: '@@INIT' } );

expect( nextState ).toEqual( {} );
} );

it( 'should ignore actions where property not present', () => {
const state = {};
const reducer = createEnhancedReducer( 'caller' );
const nextState = reducer( state, { type: 'DO_FOO' } );

expect( nextState ).toBe( state );
} );

it( 'should key by action property', () => {
const reducer = createEnhancedReducer( 'caller' );

let state = Object.freeze( {} );
state = reducer( state, { type: 'DO_FOO', caller: 1 } );
state = reducer( state, { type: 'DO_FOO', caller: 2 } );

expect( state ).toEqual( {
1: 'Called by 1',
2: 'Called by 2',
} );
} );
} );
import { selectorArgsToStateKey } from '../utils';

describe( 'selectorArgsToStateKey', () => {
it( 'should default to an empty array', () => {
Expand Down
40 changes: 0 additions & 40 deletions packages/data/src/redux-store/metadata/utils.ts
Original file line number Diff line number Diff line change
@@ -1,43 +1,3 @@
/**
* External dependencies
*/
import type { AnyAction, Reducer } from 'redux';

/**
* Higher-order reducer creator which creates a combined reducer object, keyed
* by a property on the action object.
*
* @param actionProperty Action property by which to key object.
* @return Higher-order reducer.
*/
export const onSubKey =
< TState extends unknown, TAction extends AnyAction >(
actionProperty: string
) =>
(
reducer: Reducer< TState, TAction >
): Reducer< Record< string, TState >, TAction > =>
( state: Record< string, TState > = {}, action ) => {
// Retrieve subkey from action. Do not track if undefined; useful for cases
// where reducer is scoped by action shape.
const key = action[ actionProperty ];
if ( key === undefined ) {
return state;
}

// Avoid updating state if unchanged. Note that this also accounts for a
// reducer which returns undefined on a key which is not yet tracked.
const nextKeyState = reducer( state[ key ], action );
if ( nextKeyState === state[ key ] ) {
return state;
}

return {
...state,
[ key ]: nextKeyState,
};
};

/**
* Normalize selector argument array by defaulting `undefined` value to an empty array
* and removing trailing `undefined` values.
Expand Down
Original file line number Diff line number Diff line change
@@ -1,16 +1,11 @@
/**
* External dependencies
*/
import deepFreeze from 'deep-freeze';

/**
* Internal dependencies
*/
import onSubKey from '../on-sub-key';
import { keyedReducer } from '../keyed-reducer';

describe( 'onSubKey', () => {
describe( 'keyedReducer', () => {
function createEnhancedReducer( actionProperty ) {
const enhanceReducer = onSubKey( actionProperty );
const enhanceReducer = keyedReducer( actionProperty );
return enhanceReducer(
( state, action ) => 'Called by ' + action.caller
);
Expand All @@ -24,7 +19,7 @@ describe( 'onSubKey', () => {
} );

it( 'should ignore actions where property not present', () => {
const state = deepFreeze( {} );
const state = {};
const reducer = createEnhancedReducer( 'caller' );
const nextState = reducer( state, { type: 'DO_FOO' } );

Expand All @@ -34,7 +29,7 @@ describe( 'onSubKey', () => {
it( 'should key by action property', () => {
const reducer = createEnhancedReducer( 'caller' );

let state = deepFreeze( {} );
let state = Object.freeze( {} );
state = reducer( state, { type: 'DO_FOO', caller: 1 } );
state = reducer( state, { type: 'DO_FOO', caller: 2 } );

Expand Down
8 changes: 6 additions & 2 deletions packages/notices/src/store/reducer.ts
Original file line number Diff line number Diff line change
@@ -1,8 +1,12 @@
/**
* WordPress dependencies
*/
import { keyedReducer } from '@wordpress/data';

/**
* Internal dependencies
*/
import type { Notice, ReducerAction } from './types';
import onSubKey from './utils/on-sub-key';

/**
* Reducer returning the next notices state. The notices state is an object
Expand All @@ -13,7 +17,7 @@ import onSubKey from './utils/on-sub-key';
*
* @return Updated state.
*/
const notices = onSubKey( 'context' )< Array< Notice >, ReducerAction >( (
const notices = keyedReducer< Array< Notice >, ReducerAction >( 'context' )( (
state = [],
action
) => {
Expand Down
1 change: 1 addition & 0 deletions routes/connectors-home/test/ai-plugin-callout.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -79,6 +79,7 @@ jest.mock( '@wordpress/data', () => ( {
return newState;
} ),
register: jest.fn(),
keyedReducer: jest.fn( () => ( reducer ) => reducer ),
} ) );

jest.mock( '../default-connectors', () => ( {
Expand Down
Loading