Skip to content

Commit

Permalink
Core Data: Move the template lookup to core-data selectors/resolvers (#…
Browse files Browse the repository at this point in the history
  • Loading branch information
youknowriad authored Nov 7, 2023
1 parent 837374e commit 76356ca
Show file tree
Hide file tree
Showing 8 changed files with 151 additions and 17 deletions.
26 changes: 26 additions & 0 deletions docs/reference-guides/data/data-core.md
Original file line number Diff line number Diff line change
Expand Up @@ -150,6 +150,19 @@ _Returns_

- `undefined< 'edit' >`: Current user object.

### getDefaultTemplateId

Returns the default template use to render a given query.

_Parameters_

- _state_ `State`: Data state.
- _query_ `TemplateQuery`: Query.

_Returns_

- `string`: The default template id for the given query.

### getEditedEntityRecord

Returns the specified entity record, merged with its edits.
Expand Down Expand Up @@ -648,6 +661,19 @@ _Returns_

- `Object`: Action object.

### receiveDefaultTemplateId

Returns an action object used to set the template for a given query.

_Parameters_

- _query_ `Object`: The lookup query.
- _templateId_ `string`: The resolved template id.

_Returns_

- `Object`: Action object.

### receiveEntityRecords

Returns an action object used in signalling that entity records have been received.
Expand Down
26 changes: 26 additions & 0 deletions packages/core-data/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -205,6 +205,19 @@ _Returns_

- `Object`: Action object.

### receiveDefaultTemplateId

Returns an action object used to set the template for a given query.

_Parameters_

- _query_ `Object`: The lookup query.
- _templateId_ `string`: The resolved template id.

_Returns_

- `Object`: Action object.

### receiveEntityRecords

Returns an action object used in signalling that entity records have been received.
Expand Down Expand Up @@ -444,6 +457,19 @@ _Returns_

- `undefined< 'edit' >`: Current user object.

### getDefaultTemplateId

Returns the default template use to render a given query.

_Parameters_

- _state_ `State`: Data state.
- _query_ `TemplateQuery`: Query.

_Returns_

- `string`: The default template id for the given query.

### getEditedEntityRecord

Returns the specified entity record, merged with its edits.
Expand Down
16 changes: 16 additions & 0 deletions packages/core-data/src/actions.js
Original file line number Diff line number Diff line change
Expand Up @@ -908,3 +908,19 @@ export function receiveNavigationFallbackId( fallbackId ) {
fallbackId,
};
}

/**
* Returns an action object used to set the template for a given query.
*
* @param {Object} query The lookup query.
* @param {string} templateId The resolved template id.
*
* @return {Object} Action object.
*/
export function receiveDefaultTemplateId( query, templateId ) {
return {
type: 'RECEIVE_DEFAULT_TEMPLATE',
query,
templateId,
};
}
21 changes: 21 additions & 0 deletions packages/core-data/src/reducer.js
Original file line number Diff line number Diff line change
Expand Up @@ -572,6 +572,26 @@ export function themeGlobalStyleRevisions( state = {}, action ) {
return state;
}

/**
* Reducer managing the template lookup per query.
*
* @param {Record<string, string>} state Current state.
* @param {Object} action Dispatched action.
*
* @return {Record<string, string>} Updated state.
*/
export function defaultTemplates( state = {}, action ) {
switch ( action.type ) {
case 'RECEIVE_DEFAULT_TEMPLATE':
return {
...state,
[ JSON.stringify( action.query ) ]: action.templateId,
};
}

return state;
}

export default combineReducers( {
terms,
users,
Expand All @@ -592,4 +612,5 @@ export default combineReducers( {
blockPatternCategories,
userPatternCategories,
navigationFallbackId,
defaultTemplates,
} );
11 changes: 11 additions & 0 deletions packages/core-data/src/resolvers.js
Original file line number Diff line number Diff line change
Expand Up @@ -707,3 +707,14 @@ export const getNavigationFallbackId =
] );
}
};

export const getDefaultTemplateId =
( query ) =>
async ( { dispatch } ) => {
const template = await apiFetch( {
path: addQueryArgs( '/wp/v2/templates/lookup', query ),
} );
if ( template ) {
dispatch.receiveDefaultTemplateId( query, template.id );
}
};
22 changes: 22 additions & 0 deletions packages/core-data/src/selectors.ts
Original file line number Diff line number Diff line change
Expand Up @@ -46,6 +46,7 @@ export interface State {
users: UserState;
navigationFallbackId: EntityRecordKey;
userPatternCategories: Array< UserPatternCategory >;
defaultTemplates: Record< string, string >;
}

type EntityRecordKey = string | number;
Expand Down Expand Up @@ -81,6 +82,12 @@ interface UserState {
byId: Record< EntityRecordKey, ET.User< 'edit' > >;
}

type TemplateQuery = {
slug?: string;
is_custom?: boolean;
ignore_empty?: boolean;
};

export interface UserPatternCategory {
id: number;
name: string;
Expand Down Expand Up @@ -1351,3 +1358,18 @@ export function getCurrentThemeGlobalStylesRevisions(

return state.themeGlobalStyleRevisions[ currentGlobalStylesId ];
}

/**
* Returns the default template use to render a given query.
*
* @param state Data state.
* @param query Query.
*
* @return The default template id for the given query.
*/
export function getDefaultTemplateId(
state: State,
query: TemplateQuery
): string {
return state.defaultTemplates[ JSON.stringify( query ) ];
}
26 changes: 14 additions & 12 deletions packages/edit-site/src/components/start-template-options/index.js
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,7 @@
*/
import { Modal, Flex, FlexItem, Button } from '@wordpress/components';
import { __ } from '@wordpress/i18n';
import { useState, useEffect, useMemo } from '@wordpress/element';
import { useState, useMemo } from '@wordpress/element';
import {
__experimentalBlockPatternsList as BlockPatternsList,
store as blockEditorStore,
Expand All @@ -13,8 +13,6 @@ import { useAsyncList } from '@wordpress/compose';
import { store as preferencesStore } from '@wordpress/preferences';
import { parse } from '@wordpress/blocks';
import { store as coreStore, useEntityBlockEditor } from '@wordpress/core-data';
import apiFetch from '@wordpress/api-fetch';
import { addQueryArgs } from '@wordpress/url';

/**
* Internal dependencies
Expand All @@ -23,18 +21,22 @@ import { store as editSiteStore } from '../../store';
import { TEMPLATE_POST_TYPE } from '../../utils/constants';

function useFallbackTemplateContent( slug, isCustom = false ) {
const [ templateContent, setTemplateContent ] = useState( '' );

useEffect( () => {
apiFetch( {
path: addQueryArgs( '/wp/v2/templates/lookup', {
return useSelect(
( select ) => {
const { getEntityRecord, getDefaultTemplateId } =
select( coreStore );
const templateId = getDefaultTemplateId( {
slug,
is_custom: isCustom,
ignore_empty: true,
} ),
} ).then( ( { content } ) => setTemplateContent( content.raw ) );
}, [ isCustom, slug ] );
return templateContent;
} );
return templateId
? getEntityRecord( 'postType', TEMPLATE_POST_TYPE, templateId )
?.content?.raw
: undefined;
},
[ slug, isCustom ]
);
}

function useStartPatterns( fallbackContent ) {
Expand Down
20 changes: 15 additions & 5 deletions packages/edit-site/src/store/actions.js
Original file line number Diff line number Diff line change
Expand Up @@ -266,12 +266,22 @@ export const setPage =
( page ) =>
async ( { dispatch, registry } ) => {
let template;
const getDefaultTemplate = async ( slug ) =>
apiFetch( {
path: addQueryArgs( '/wp/v2/templates/lookup', {
const getDefaultTemplate = async ( slug ) => {
const templateId = await registry
.resolveSelect( coreStore )
.getDefaultTemplateId( {
slug: `page-${ slug }`,
} ),
} );
} );
return templateId
? await registry
.resolveSelect( coreStore )
.getEntityRecord(
'postType',
TEMPLATE_POST_TYPE,
templateId
)
: undefined;
};

if ( page.path ) {
template = await registry
Expand Down

1 comment on commit 76356ca

@github-actions
Copy link

Choose a reason for hiding this comment

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

Flaky tests detected in 76356ca.
Some tests passed with failed attempts. The failures may not be related to this commit but are still reported for visibility. See the documentation for more information.

🔍 Workflow run URL: https://github.com/WordPress/gutenberg/actions/runs/6784422398
📝 Reported issues:

Please sign in to comment.