From 8649f93b3596c5efe49a5d41f375217d35e2ec28 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Andr=C3=A9=20Maneiro?= <583546+oandregal@users.noreply.github.com> Date: Wed, 20 Nov 2024 17:53:56 +0100 Subject: [PATCH] usePostFields: take them from the registry --- .../src/components/post-fields/index.ts | 71 +++++++++++-------- 1 file changed, 41 insertions(+), 30 deletions(-) diff --git a/packages/editor/src/components/post-fields/index.ts b/packages/editor/src/components/post-fields/index.ts index 3d675ab763d64c..e93f167f37e03b 100644 --- a/packages/editor/src/components/post-fields/index.ts +++ b/packages/editor/src/components/post-fields/index.ts @@ -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 >[]; @@ -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 {