Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Extract selectors from useResolveEditedEntity hook #67031

Merged
Merged
Show file tree
Hide file tree
Changes from 8 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
147 changes: 147 additions & 0 deletions packages/core-data/src/private-selectors.ts
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,7 @@ import { createSelector, createRegistrySelector } from '@wordpress/data';
*/
import type { State } from './selectors';
import { STORE_NAME } from './name';
import { unlock } from './lock-unlock';

type EntityRecordKey = string | number;

Expand Down Expand Up @@ -105,3 +106,149 @@ export function getEntityRecordPermissions(
export function getRegisteredPostMeta( state: State, postType: string ) {
return state.registeredPostMeta?.[ postType ] ?? {};
}

function normalizePageId( value: number | string | undefined ): string | null {
if ( ! value || ! [ 'number', 'string' ].includes( typeof value ) ) {
return null;
}

// We also need to check if it's not zero (`'0'`).
if ( Number( value ) === 0 ) {
return null;
}

return value.toString();
}

interface SiteData {
show_on_front?: string;
page_on_front?: string | number;
page_for_posts?: string | number;
}

export const getHomePage = createRegistrySelector( ( select ) =>
createSelector(
() => {
const siteData = select( STORE_NAME ).getEntityRecord(
'root',
'site'
) as SiteData | undefined;
if ( ! siteData ) {
return null;
}
const homepageId =
siteData?.show_on_front === 'page'
? normalizePageId( siteData.page_on_front )
: null;
if ( homepageId ) {
return { postType: 'page', postId: homepageId };
}
const frontPageTemplateId = select(
STORE_NAME
).getDefaultTemplateId( {
slug: 'front-page',
} );
return { postType: 'wp_template', postId: frontPageTemplateId };
},
() => [
select( STORE_NAME ).getEntityRecord( 'root', 'site' ),
select( STORE_NAME ).getDefaultTemplateId( {
slug: 'front-page',
} ),
Copy link
Member

Choose a reason for hiding this comment

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

The trouble with this is that the getDefaultTemplateId call triggers the resolver and a wp/v2/templates/lookup REST request. But the actual selector doesn't always call getDefaultTemplateId. If there is a valid homepage, it returns early and the REST request wasn't needed.

Because the select is same-store we can solve this by calling the plain selector function in the get-dependants callback. That's exactly what we need: just read the data from state and don't do any side effects.

I don't know how we would solve this if the select was cross-store. Interesting problem for @ellatrix or @Mamaduka who have plenty of experience working with complex selectors: do we have any existing prior art for this?

Copy link
Contributor Author

Choose a reason for hiding this comment

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

you're right, I updated here to use the selectors directly, I think that's enough.

]
)
);

export const getPostsPageId = createRegistrySelector( ( select ) => () => {
const siteData = select( STORE_NAME ).getEntityRecord( 'root', 'site' ) as
| SiteData
| undefined;
return siteData?.show_on_front === 'page'
? normalizePageId( siteData.page_for_posts )
: null;
} );

export const getTemplateId = createRegistrySelector(
( select ) => ( state, postType, postId ) => {
const homepage = unlock( select( STORE_NAME ) ).getHomePage();

if ( ! homepage ) {
return;
}

// For the front page, we always use the front page template if existing.
if (
postType === 'page' &&
postType === homepage?.postType &&
postId.toString() === homepage?.postId
) {
youknowriad marked this conversation as resolved.
Show resolved Hide resolved
// The /lookup endpoint cannot currently handle a lookup
// when a page is set as the front page, so specifically in
// that case, we want to check if there is a front page
// template, and instead of falling back to the home
// template, we want to fall back to the page template.
const templates = select( STORE_NAME ).getEntityRecords(
'postType',
'wp_template',
{
per_page: -1,
}
);
if ( ! templates ) {
return;
}
const id = templates.find( ( { slug } ) => slug === 'front-page' )
?.id;
if ( id ) {
return id;
}
// If no front page template is found, continue with the
// logic below (fetching the page template).
}

const editedEntity = select( STORE_NAME ).getEditedEntityRecord(
'postType',
postType,
postId
);
if ( ! editedEntity ) {
return;
}
const postsPageId = unlock( select( STORE_NAME ) ).getPostsPageId();
// Check if the current page is the posts page.
if ( postType === 'page' && postsPageId === postId.toString() ) {
return select( STORE_NAME ).getDefaultTemplateId( {
slug: 'home',
} );
}
// First see if the post/page has an assigned template and fetch it.
const currentTemplateSlug = editedEntity.template;
if ( currentTemplateSlug ) {
const currentTemplate = select( STORE_NAME )
.getEntityRecords( 'postType', 'wp_template', {
per_page: -1,
} )
?.find( ( { slug } ) => slug === currentTemplateSlug );
if ( currentTemplate ) {
return currentTemplate.id;
}
}
// If no template is assigned, use the default template.
let slugToCheck;
// In `draft` status we might not have a slug available, so we use the `single`
// post type templates slug(ex page, single-post, single-product etc..).
// Pages do not need the `single` prefix in the slug to be prioritized
// through template hierarchy.
if ( editedEntity.slug ) {
slugToCheck =
postType === 'page'
? `${ postType }-${ editedEntity.slug }`
: `single-${ postType }-${ editedEntity.slug }`;
} else {
slugToCheck = postType === 'page' ? 'page' : `single-${ postType }`;
}
return select( STORE_NAME ).getDefaultTemplateId( {
slug: slugToCheck,
} );
}
);
15 changes: 10 additions & 5 deletions packages/edit-post/src/components/layout/index.js
Original file line number Diff line number Diff line change
Expand Up @@ -399,10 +399,10 @@ function Layout( {
} = useSelect(
( select ) => {
const { get } = select( preferencesStore );
const { isFeatureActive, getEditedPostTemplateId } = unlock(
select( editPostStore )
const { isFeatureActive } = select( editPostStore );
const { canUser, getPostType, getTemplateId } = unlock(
select( coreStore )
);
const { canUser, getPostType } = select( coreStore );

const supportsTemplateMode = settings.supportsTemplateMode;
const isViewable =
Expand Down Expand Up @@ -433,15 +433,20 @@ function Layout( {
isViewable &&
canViewTemplate &&
! isEditingTemplate
? getEditedPostTemplateId()
? getTemplateId( currentPostType, currentPostId )
: null,
enablePaddingAppender:
! isZoomOut() &&
isRenderingPostOnly &&
! DESIGN_POST_TYPES.includes( currentPostType ),
};
},
[ currentPostType, isEditingTemplate, settings.supportsTemplateMode ]
[
currentPostType,
currentPostId,
isEditingTemplate,
settings.supportsTemplateMode,
]
);
const [ paddingAppenderRef, paddingStyle ] = usePaddingAppender(
enablePaddingAppender
Expand Down
3 changes: 0 additions & 3 deletions packages/edit-post/src/store/index.js
Original file line number Diff line number Diff line change
Expand Up @@ -9,9 +9,7 @@ import { createReduxStore, register } from '@wordpress/data';
import reducer from './reducer';
import * as actions from './actions';
import * as selectors from './selectors';
import * as privateSelectors from './private-selectors';
import { STORE_NAME } from './constants';
import { unlock } from '../lock-unlock';

/**
* Store definition for the edit post namespace.
Expand All @@ -26,4 +24,3 @@ export const store = createReduxStore( STORE_NAME, {
selectors,
} );
register( store );
unlock( store ).registerPrivateSelectors( privateSelectors );
61 changes: 0 additions & 61 deletions packages/edit-post/src/store/private-selectors.js

This file was deleted.

11 changes: 7 additions & 4 deletions packages/edit-post/src/store/selectors.js
Original file line number Diff line number Diff line change
Expand Up @@ -14,8 +14,6 @@ import deprecated from '@wordpress/deprecated';
* Internal dependencies
*/
import { unlock } from '../lock-unlock';
import { getEditedPostTemplateId } from './private-selectors';

const { interfaceStore } = unlock( editorPrivateApis );
const EMPTY_ARRAY = [];
const EMPTY_OBJECT = {};
Expand Down Expand Up @@ -555,8 +553,13 @@ export function areMetaBoxesInitialized( state ) {
* @return {Object?} Post Template.
*/
export const getEditedPostTemplate = createRegistrySelector(
( select ) => ( state ) => {
const templateId = getEditedPostTemplateId( state );
( select ) => () => {
const { id: postId, type: postType } =
select( editorStore ).getCurrentPost();
const templateId = unlock( select( coreStore ) ).getTemplateId(
postType,
postId
);
if ( ! templateId ) {
return undefined;
}
Expand Down
Loading
Loading