Skip to content

Commit

Permalink
usePostFields: take them from the registry
Browse files Browse the repository at this point in the history
  • Loading branch information
oandregal committed Nov 20, 2024
1 parent 7443615 commit 8649f93
Showing 1 changed file with 41 additions and 30 deletions.
71 changes: 41 additions & 30 deletions packages/editor/src/components/post-fields/index.ts
Original file line number Diff line number Diff line change
@@ -1,22 +1,18 @@
/**
* WordPress dependencies
*/
import { useMemo } from '@wordpress/element';
import { useEffect, useMemo } from '@wordpress/element';
import { useEntityRecords } from '@wordpress/core-data';
import { useDispatch, useSelect } from '@wordpress/data';
import type { Field } from '@wordpress/dataviews';
import {
featuredImageField,
slugField,
parentField,
passwordField,
statusField,
commentStatusField,
titleField,
dateField,
authorField,
} from '@wordpress/fields';
import type { BasePostWithEmbeddedAuthor } from '@wordpress/fields';

/**
* Internal dependencies
*/
import { unlock } from '../../lock-unlock';
import { store as editorStore } from '../../store';

interface UsePostFieldsReturn {
isLoading: boolean;
fields: Field< BasePostWithEmbeddedAuthor >[];
Expand All @@ -28,29 +24,44 @@ interface Author {
}

function usePostFields(): UsePostFieldsReturn {
const postType = 'page'; // TODO: this could be page or post (experimental).

const { registerPostTypeFields } = unlock( useDispatch( editorStore ) );
useEffect( () => {
registerPostTypeFields( postType );
}, [ registerPostTypeFields, postType ] );

const { defaultFields } = useSelect(
( select ) => {
const { getEntityFields } = unlock( select( editorStore ) );
return {
defaultFields: getEntityFields( 'postType', postType ),
};
},
[ postType ]
);

const { records: authors, isResolving: isLoadingAuthors } =
useEntityRecords< Author >( 'root', 'user', { per_page: -1 } );

const fields = useMemo(
() =>
[
featuredImageField,
titleField,
{
...authorField,
elements: authors?.map( ( { id, name } ) => ( {
value: id,
label: name,
} ) ),
},
statusField,
dateField,
slugField,
parentField,
commentStatusField,
passwordField,
] as Field< BasePostWithEmbeddedAuthor >[],
[ authors ]
defaultFields.map(
( field: Field< BasePostWithEmbeddedAuthor > ) => {
if ( field.id === 'author' ) {
return {
...field,
elements: authors?.map( ( { id, name } ) => ( {
value: id,
label: name,
} ) ),
};
}

return field;
}
) as Field< BasePostWithEmbeddedAuthor >[],
[ authors, defaultFields ]
);

return {
Expand Down

0 comments on commit 8649f93

Please sign in to comment.