Skip to content

Commit

Permalink
Edit Site: Fetch templates in Template Switcher from REST API
Browse files Browse the repository at this point in the history
  • Loading branch information
ockham committed Jun 4, 2020
1 parent aaccb9f commit 91b0423
Show file tree
Hide file tree
Showing 5 changed files with 114 additions and 63 deletions.
6 changes: 1 addition & 5 deletions lib/edit-site-page.php
Original file line number Diff line number Diff line change
Expand Up @@ -144,8 +144,7 @@ function gutenberg_edit_site_init( $hook ) {
}
$settings['styles'] = gutenberg_get_editor_styles();

$template_ids = array();
$template_part_ids = array();
$template_ids = array();
foreach ( get_template_types() as $template_type ) {
// Skip 'embed' for now because it is not a regular template type.
// Skip 'index' because it's a fallback that we handle differently.
Expand All @@ -156,19 +155,16 @@ function gutenberg_edit_site_init( $hook ) {
$current_template = gutenberg_find_template_post_and_parts( $template_type );
if ( isset( $current_template ) ) {
$template_ids[ $current_template['template_post']->post_name ] = $current_template['template_post']->ID;
$template_part_ids = $template_part_ids + $current_template['template_part_ids'];
}
}

$current_template_id = $template_ids['front-page'];

$settings['editSiteInitialState'] = array();

$settings['editSiteInitialState']['homeTemplateId'] = $current_template_id;
$settings['editSiteInitialState']['templateId'] = $current_template_id;
$settings['editSiteInitialState']['templateType'] = 'wp_template';
$settings['editSiteInitialState']['templateIds'] = array_values( $template_ids );
$settings['editSiteInitialState']['templatePartIds'] = array_values( $template_part_ids );

$settings['editSiteInitialState']['showOnFront'] = get_option( 'show_on_front' );
$settings['editSiteInitialState']['page'] = array(
Expand Down
2 changes: 1 addition & 1 deletion lib/template-loader.php
Original file line number Diff line number Diff line change
Expand Up @@ -321,7 +321,7 @@ function gutenberg_find_template_post_and_parts( $template_type, $template_hiera

if ( $current_template_post ) {
$template_part_ids = array();
if ( is_admin() ) {
if ( is_admin() || defined( 'REST_REQUEST' ) ) {
foreach ( parse_blocks( $current_template_post->post_content ) as $block ) {
$template_part_ids = array_merge( $template_part_ids, create_auto_draft_for_template_part_block( $block ) );
}
Expand Down
29 changes: 26 additions & 3 deletions lib/template-parts.php
Original file line number Diff line number Diff line change
Expand Up @@ -141,14 +141,18 @@ function gutenberg_render_template_part_list_table_column( $column_name, $post_i


/**
* Filter for adding a `theme` parameter to `wp_template_part` queries.
* Filter for adding a `resolved` and a `theme` parameter to `wp_template_part` queries.
*
* @param array $query_params The query parameters.
* @return array Filtered $query_params.
*/
function filter_rest_wp_template_part_collection_params( $query_params ) {
$query_params += array(
'theme' => array(
'resolved' => array(
'description' => __( 'Whether to filter for resolved template parts.', 'gutenberg' ),
'type' => 'boolean',
),
'theme' => array(
'description' => __( 'The theme slug for the theme that created the template part.', 'gutenberg' ),
'type' => 'string',
),
Expand All @@ -158,13 +162,31 @@ function filter_rest_wp_template_part_collection_params( $query_params ) {
apply_filters( 'rest_wp_template_part_collection_params', 'filter_rest_wp_template_part_collection_params', 99, 1 );

/**
* Filter for supporting the `theme` parameter in `wp_template_part` queries.
* Filter for supporting the `resolved` and `theme` parameters in `wp_template_part` queries.
*
* @param array $args The query arguments.
* @param WP_REST_Request $request The request object.
* @return array Filtered $args.
*/
function filter_rest_wp_template_part_query( $args, $request ) {
if ( $request['resolved'] ) {
$template_part_ids = array( 0 ); // Return nothing by default (the 0 is needed for `post__in`).

foreach ( get_template_types() as $template_type ) {
// Skip 'embed' for now because it is not a regular template type.
if ( in_array( $template_type, array( 'embed' ), true ) ) {
continue;
}

$current_template = gutenberg_find_template_post_and_parts( $template_type );
if ( isset( $current_template ) ) {
$template_part_ids = $template_part_ids + $current_template['template_part_ids'];
}
}
$args['post__in'] = $template_part_ids;
$args['post_status'] = array( 'publish', 'auto-draft' );
}

if ( $request['theme'] ) {
$meta_query = isset( $args['meta_query'] ) ? $args['meta_query'] : array();
$meta_query[] = array(
Expand All @@ -174,6 +196,7 @@ function filter_rest_wp_template_part_query( $args, $request ) {

$args['meta_query'] = $meta_query;
}

return $args;
}
add_filter( 'rest_wp_template_part_query', 'filter_rest_wp_template_part_query', 99, 2 );
2 changes: 0 additions & 2 deletions packages/edit-site/src/components/header/index.js
Original file line number Diff line number Diff line change
Expand Up @@ -116,11 +116,9 @@ export default function Header( {
/
</div>
<TemplateSwitcher
templatePartIds={ templatePartIds }
page={ page }
activeId={ templateId }
activeTemplatePartId={ templatePartId }
homeId={ homeTemplateId }
isTemplatePart={ templateType === 'wp_template_part' }
onActiveIdChange={ setTemplate }
onActiveTemplatePartIdChange={ setTemplatePart }
Expand Down
138 changes: 86 additions & 52 deletions packages/edit-site/src/components/template-switcher/index.js
Original file line number Diff line number Diff line change
Expand Up @@ -2,8 +2,9 @@
* WordPress dependencies
*/
import { __ } from '@wordpress/i18n';
import { useSelect } from '@wordpress/data';
import { useState } from '@wordpress/element';
import { addQueryArgs } from '@wordpress/url';
import { resolveSelect, useDispatch, useSelect } from '@wordpress/data';
import { useEffect, useState } from '@wordpress/element';
import {
Tooltip,
DropdownMenu,
Expand All @@ -19,6 +20,11 @@ import { Icon, home, plus, undo } from '@wordpress/icons';
import TemplatePreview from './template-preview';
import ThemePreview from './theme-preview';

/**
* Browser dependencies
*/
const { fetch } = window;

const TEMPLATE_OVERRIDES = {
page: ( slug ) => `page-${ slug }`,
category: ( slug ) => `category-${ slug }`,
Expand Down Expand Up @@ -46,11 +52,9 @@ function TemplateLabel( { template, homeId } ) {
}

export default function TemplateSwitcher( {
templatePartIds,
page,
activeId,
activeTemplatePartId,
homeId,
isTemplatePart,
onActiveIdChange,
onActiveTemplatePartIdChange,
Expand All @@ -70,52 +74,82 @@ export default function TemplateSwitcher( {
setThemePreviewVisible( () => false );
};

const [ homeId, setHomeId ] = useState();

useEffect( () => {
const effect = async () => {
try {
const { success, data } = await fetch(
addQueryArgs( '/', { '_wp-find-template': true } )
).then( ( res ) => res.json() );
if ( success ) {
let newHomeId = data.ID;
if ( newHomeId === null ) {
const { getEntityRecords } = resolveSelect( 'core' );
newHomeId = (
await getEntityRecords( 'postType', 'wp_template', {
resolved: true,
slug: data.post_name,
} )
)[ 0 ].id;
}
setHomeId( newHomeId );
} else {
throw new Error();
}
} catch ( err ) {
setHomeId( null );
}
};
effect();
}, [] );

const { currentTheme, template, templateParts } = useSelect(
( select ) => {
const { getCurrentTheme, getEntityRecord } = select( 'core' );
const _template = getEntityRecord(
'postType',
'wp_template',
activeId
);
( _select ) => {
const {
getCurrentTheme,
getEntityRecord,
getEntityRecords,
} = _select( 'core' );
const theme = getCurrentTheme();

return {
currentTheme: getCurrentTheme(),
template: {
label: _template ? (
<TemplateLabel
template={ _template }
homeId={ homeId }
/>
) : (
__( 'Loading…' )
),
value: activeId,
slug: _template ? _template.slug : __( 'Loading…' ),
content: _template?.content,
},
templateParts: templatePartIds.map( ( id ) => {
const templatePart = getEntityRecord(
'postType',
'wp_template_part',
id
);
return {
label: templatePart ? (
<TemplateLabel template={ templatePart } />
) : (
__( 'Loading…' )
),
value: id,
slug: templatePart
? templatePart.slug
: __( 'Loading…' ),
};
} ),
currentTheme: theme,
template: getEntityRecord(
'postType',
'wp_template',
activeId
),
templateParts: theme
? getEntityRecords( 'postType', 'wp_template_part', {
resolved: true,
theme: theme.stylesheet,
} )
: null,
};
},
[ activeId, templatePartIds, homeId ]
[ activeId ]
);

const templateItem = {
label: template ? (
<TemplateLabel template={ template } homeId={ homeId } />
) : (
__( 'Loading…' )
),
value: activeId,
slug: template ? template.slug : __( 'Loading…' ),
content: template?.content,
};

const templatePartItems = templateParts?.map( ( templatePart ) => ( {
label: <TemplateLabel template={ templatePart } />,
value: templatePart.id,
slug: templatePart.slug,
} ) );

const { saveEntityRecord } = useDispatch( 'core' );

const overwriteSlug =
TEMPLATE_OVERRIDES[ page.type ] &&
page.slug &&
Expand All @@ -125,10 +159,10 @@ export default function TemplateSwitcher( {
slug: overwriteSlug,
title: overwriteSlug,
status: 'publish',
content: template.content.raw,
content: templateItem.content.raw,
} );
const revertToParent = async () => {
onRemoveTemplate( template.value );
onRemoveTemplate( activeId );
};
return (
<>
Expand All @@ -141,8 +175,8 @@ export default function TemplateSwitcher( {
label={ __( 'Switch Template' ) }
toggleProps={ {
children: ( isTemplatePart
? templateParts
: [ template ]
? templatePartItems
: [ templateItem ]
).find(
( choice ) =>
choice.value ===
Expand All @@ -156,18 +190,18 @@ export default function TemplateSwitcher( {
<MenuItem
onClick={ () => onActiveIdChange( activeId ) }
>
{ template.label }
{ templateItem.label }
</MenuItem>
{ overwriteSlug &&
overwriteSlug !== template.slug && (
overwriteSlug !== templateItem.slug && (
<MenuItem
icon={ plus }
onClick={ overwriteTemplate }
>
{ __( 'Overwrite Template' ) }
</MenuItem>
) }
{ overwriteSlug === template.slug && (
{ overwriteSlug === templateItem.slug && (
<MenuItem
icon={ undo }
onClick={ revertToParent }
Expand All @@ -178,7 +212,7 @@ export default function TemplateSwitcher( {
</MenuGroup>
<MenuGroup label={ __( 'Template Parts' ) }>
<MenuItemsChoice
choices={ templateParts }
choices={ templatePartItems }
value={
isTemplatePart
? activeTemplatePartId
Expand Down

0 comments on commit 91b0423

Please sign in to comment.