Skip to content
Closed
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 @@ -15,6 +15,7 @@ export default function AdaptiveSelect< Item >(
const { elements } = useElements( {
elements: field.elements,
getElements: field.getElements,
item: props.data,
} );
if ( elements.length >= ELEMENTS_THRESHOLD ) {
return <Combobox { ...props } />;
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -28,6 +28,7 @@ export default function ArrayControl< Item >( {
const { elements, isLoading } = useElements( {
elements: field.elements,
getElements: field.getElements,
item: data,
} );

// Convert stored values to element objects for the token field
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -34,6 +34,7 @@ export default function Combobox< Item >( {
const { elements, isLoading } = useElements( {
elements: field.elements,
getElements: field.getElements,
item: data,
} );

if ( isLoading ) {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -26,6 +26,7 @@ export default function Radio< Item >( {
const { elements, isLoading } = useElements( {
elements: field.elements,
getElements: field.getElements,
item: data,
} );
const value = getValue( { item: data } );

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -36,6 +36,7 @@ export default function Select< Item >( {
const { elements, isLoading } = useElements( {
elements: field.elements,
getElements: field.getElements,
item: data,
} );

if ( isLoading ) {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -38,6 +38,7 @@ export default function ToggleGroup< Item >( {
const { elements, isLoading } = useElements( {
elements: field.elements,
getElements: field.getElements,
item: data,
} );

if ( isLoading ) {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -11,6 +11,7 @@ export default function RenderFromElements< Item >( {
const { elements, isLoading } = useElements( {
elements: field.elements,
getElements: field.getElements,
item,
} );

const value = field.getValue( { item } );
Expand Down
16 changes: 12 additions & 4 deletions packages/dataviews/src/hooks/use-elements.ts
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
/**
* WordPress dependencies
*/
import { useEffect, useState } from '@wordpress/element';
import { useEffect, useRef, useState } from '@wordpress/element';

/**
* Internal dependencies
Expand All @@ -10,19 +10,23 @@ import type { Option } from '../types';

const EMPTY_ARRAY: Option[] = [];

export default function useElements( {
export default function useElements< Item >( {
elements,
getElements,
item,
}: {
elements?: Option[];
getElements?: () => Promise< Option[] >;
getElements?: ( args?: { item: Item } ) => Promise< Option[] >;
item?: Item;
} ) {
const staticElements =
Array.isArray( elements ) && elements.length > 0
? elements
: EMPTY_ARRAY;
const [ records, setRecords ] = useState< Option[] >( staticElements );
const [ isLoading, setIsLoading ] = useState( false );
const itemRef = useRef( item );
itemRef.current = item;

useEffect( () => {
if ( ! getElements ) {
Expand All @@ -32,7 +36,11 @@ export default function useElements( {

let cancelled = false;
setIsLoading( true );
getElements()
getElements(
itemRef.current !== undefined
? { item: itemRef.current }
: undefined
)
.then( ( fetchedElements ) => {
if ( ! cancelled ) {
const dynamicElements =
Expand Down
2 changes: 1 addition & 1 deletion packages/dataviews/src/hooks/use-form-validity.ts
Original file line number Diff line number Diff line change
Expand Up @@ -548,7 +548,7 @@ function validateFormField< Item >(
typeof formField.field.getElements === 'function'
) {
handleElementsValidationAsync(
formField.field.getElements(),
formField.field.getElements( { item } ),
formField,
promiseHandler
);
Expand Down
2 changes: 1 addition & 1 deletion packages/dataviews/src/types/dataviews.ts
Original file line number Diff line number Diff line change
Expand Up @@ -63,7 +63,7 @@ export interface NormalizedFilter {
/**
* Retrieval function to get the elements.
*/
getElements?: () => Promise< Option[] >;
getElements?: ( args?: { item: any } ) => Promise< Option[] >;

/**
* Whether the filter has elements.
Expand Down
2 changes: 1 addition & 1 deletion packages/dataviews/src/types/field-api.ts
Original file line number Diff line number Diff line change
Expand Up @@ -255,7 +255,7 @@ export type Field< Item > = {
/**
* Retrieval function for elements.
*/
getElements?: () => Promise< Option[] >;
getElements?: ( args?: { item: Item } ) => Promise< Option[] >;

/**
* Filter config for the field.
Expand Down
56 changes: 17 additions & 39 deletions packages/edit-site/src/components/post-list/quick-edit-modal.js
Original file line number Diff line number Diff line change
Expand Up @@ -12,13 +12,11 @@ import {
} from '@wordpress/components';
import { useEffect, useMemo, useState } from '@wordpress/element';
import { privateApis as editorPrivateApis } from '@wordpress/editor';
import { privateApis as blockEditorPrivateApis } from '@wordpress/block-editor';

/**
* Internal dependencies
*/
import { unlock } from '../../lock-unlock';
import usePatternSettings from '../page-patterns/use-pattern-settings';

const { usePostFields, PostCardPanel } = unlock( editorPrivateApis );

Expand All @@ -28,17 +26,21 @@ export function QuickEditModal( { postType, postId, closeModal } ) {
const isBulk = postId.length > 1;

const [ localEdits, setLocalEdits ] = useState( {} );
const { record, hasFinishedResolution } = useSelect(
const { record, hasFinishedResolution, isTemplateReadOnly } = useSelect(
( select ) => {
const {
getEditedEntityRecord,
hasFinishedResolution: hasFinished,
} = select( coreDataStore );

const { getPostsPageId } = unlock( select( coreDataStore ) );
const isPostsPage = +getPostsPageId() === +postId[ 0 ];

if ( isBulk ) {
return {
record: null,
hasFinishedResolution: true,
isTemplateReadOnly: isPostsPage,
};
}

Expand All @@ -49,6 +51,7 @@ export function QuickEditModal( { postType, postId, closeModal } ) {
'getEditedEntityRecord',
args
),
isTemplateReadOnly: isPostsPage,
};
},
[ postType, postId, isBulk ]
Expand All @@ -68,9 +71,17 @@ export function QuickEditModal( { postType, postId, closeModal } ) {
),
};
}

if ( field.id === 'template' ) {
return {
...field,
readOnly: isTemplateReadOnly,
};
}

return field;
} ),
[ _fields ]
[ _fields, isTemplateReadOnly ]
);

const form = useMemo( () => {
Expand All @@ -96,14 +107,7 @@ export function QuickEditModal( { postType, postId, closeModal } ) {
label: __( 'Discussion' ),
children: [ 'comment_status', 'ping_status' ],
},
{
label: __( 'Template' ),
id: 'template',
layout: {
type: 'regular',
labelPosition: 'side',
},
},
'template',
];

return {
Expand Down Expand Up @@ -162,32 +166,6 @@ export function QuickEditModal( { postType, postId, closeModal } ) {
closeModal?.();
};

const { ExperimentalBlockEditorProvider } = unlock(
blockEditorPrivateApis
);
const settings = usePatternSettings();

/**
* The template field depends on the block editor settings.
* This is a workaround to ensure that the block editor settings are available.
* For more information, see: https://github.com/WordPress/gutenberg/issues/67521
*/
const fieldsWithDependency = useMemo( () => {
return fields.map( ( field ) => {
if ( field.id === 'template' ) {
return {
...field,
Edit: ( data ) => (
<ExperimentalBlockEditorProvider settings={ settings }>
<field.Edit { ...data } />
</ExperimentalBlockEditorProvider>
),
};
}
return field;
} );
}, [ fields, settings ] );

return (
<Modal
overlayClassName="dataviews-action-modal__quick-edit"
Expand All @@ -207,7 +185,7 @@ export function QuickEditModal( { postType, postId, closeModal } ) {
{ hasFinishedResolution && (
<DataForm
data={ { ...record, ...localEdits } }
fields={ fieldsWithDependency }
fields={ fields }
form={ form }
onChange={ onChange }
/>
Expand Down
88 changes: 84 additions & 4 deletions packages/fields/src/fields/template/index.ts
Original file line number Diff line number Diff line change
@@ -1,20 +1,100 @@
/**
* WordPress dependencies
*/
import type { Field } from '@wordpress/dataviews';
import type { Field, Option } from '@wordpress/dataviews';
import { __ } from '@wordpress/i18n';
import { resolveSelect } from '@wordpress/data';
import type { WpTemplate } from '@wordpress/core-data';
import { store as coreDataStore } from '@wordpress/core-data';
import { decodeEntities } from '@wordpress/html-entities';

/**
* Internal dependencies
*/
import { __ } from '@wordpress/i18n';
import type { BasePost } from '../../types';
import { TemplateEdit } from './template-edit';

const EMPTY_ARRAY: [] = [];

const templateField: Field< BasePost > = {
id: 'template',
type: 'text',
label: __( 'Template' ),
Edit: TemplateEdit,
getElements: async ( args ) => {
// LIST OF CUSTOM TEMPLATES
// This uses the same logic as the editor inspector
// (useAvailableTemplates hook at packages/editor/src/components/post-template/hooks.js).
const templates: WpTemplate[] =
( await resolveSelect( coreDataStore ).getEntityRecords(
'postType',
'wp_template',
{
per_page: -1,
post_type: args?.item?.type || 'page',
}
) ) ?? EMPTY_ARRAY;
const templateElements = templates
.filter(
( template ) => template.is_custom && !! template.content.raw // Skip empty templates.
)
.map( ( { slug, title } ) => ( {
value: slug,
label: title.rendered || slug,
} ) );

// CURRENT TEMPLATE
// This uses the same logic as the editor inspector
// (BlockThemeControl at packages/editor/src/components/post-template/block-theme.js)
let slugToCheck;
const postType = args?.item?.type;
const slug = args?.item?.slug;
// 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 ( slug ) {
slugToCheck =
postType === 'page'
? `${ postType }-${ slug }`
: `single-${ postType }-${ slug }`;
} else {
slugToCheck = postType === 'page' ? 'page' : `single-${ postType }`;
}

let currentTemplateElement: Option | undefined;
if ( postType ) {
// TODO: this template id is computed differently than the templateId in the editor inspector
// Compare with
// https://github.com/WordPress/gutenberg/blob/8c2a7c775f5b5fb19d8dca66a09d18977cf42b7d/packages/editor/src/components/post-template/panel.js#L21
// The editor inspector computes it from the editor store (that we cannot use in this package),
// that ends up being using the getTemplateId private selector from core data.
const templateId = await resolveSelect(
coreDataStore
).getDefaultTemplateId( {
slug: slugToCheck,
} );
Comment on lines +65 to +74

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

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

This has ported the existing logic from template-edit and in doing so it raised a bug: the templateId computed here is different from the one computed in the editor inspector (which ends up using the private selector getTemplateId). As a result, the template for the posts page is "Pages" and not "Blog post".


const currentTemplate = ( await resolveSelect(
coreDataStore
).getEntityRecord( 'postType', 'wp_template', templateId ) ) as
| WpTemplate
| undefined;
if ( currentTemplate ) {
currentTemplateElement = {
// If the template field is empty it means it'll be matched to a template from the hierarchy,
// which is the current template. Instead of using the currentTemplate.slug as value,
// we want to use the empty string so that this element is the one selected in the control.
// And, inversely, when selecting this element, the user will be resetting the template
// to the default value.
value: '',
label: decodeEntities( currentTemplate.title.rendered ),
};
}
}

return [ currentTemplateElement, ...templateElements ].filter(
( item ): item is Option => !! item
);
},
enableSorting: false,
filterBy: false,
};
Expand Down
Loading