Skip to content

Commit

Permalink
Update endpoint to only return new data if explicitly requested
Browse files Browse the repository at this point in the history
  • Loading branch information
glendaviesnz committed Nov 6, 2023
1 parent 247ad0c commit 3815ce3
Show file tree
Hide file tree
Showing 16 changed files with 158 additions and 59 deletions.
12 changes: 12 additions & 0 deletions docs/reference-guides/data/data-core.md
Original file line number Diff line number Diff line change
Expand Up @@ -359,6 +359,18 @@ _Returns_

- `any`: The entity record's save error.

### getPatternCategories

Retrieve the core and user pattern categories.

_Parameters_

- _state_ `State`: Data state.

_Returns_

- `Array< unknown >`: User patterns category array.

### getRawEntityRecord

Returns the entity's record object by key, with its attributes mapped to their raw values.
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -25,6 +25,11 @@ class Gutenberg_REST_Block_Pattern_Categories_Controller extends WP_REST_Block_P
* @return WP_Error|WP_REST_Response Response object on success, or WP_Error object on failure.
*/
public function get_items( $request ) {
$valid_query_args = array(
'source' => true,
);

$query_args = array_intersect_key( $request->get_params(), $valid_query_args );
$response = array();
$unique_categories = array();
$categories = WP_Block_Pattern_Categories_Registry::get_instance()->get_all_registered();
Expand All @@ -35,25 +40,30 @@ public function get_items( $request ) {
)
);

foreach ( $user_categories as $user_category ) {
$prepared_category = $this->prepare_item_for_response(
array(
'name' => $user_category->slug,
'label' => $user_category->name,
'description' => $user_category->description,
'id' => $user_category->term_id,
),
$request
);
$response[] = $this->prepare_response_for_collection( $prepared_category );
$unique_categories[] = $user_category->name;
if ( is_array( $query_args['source'] ) && in_array( 'user', $query_args['source'], true ) ) {
foreach ( $user_categories as $user_category ) {
$prepared_category = $this->prepare_item_for_response(
array(
'name' => $user_category->slug,
'label' => $user_category->name,
'description' => $user_category->description,
'id' => $user_category->term_id,
),
$request
);
$response[] = $this->prepare_response_for_collection( $prepared_category );
$unique_categories[] = $user_category->name;
}
}
foreach ( $categories as $category ) {
if ( in_array( $category['label'], $unique_categories, true ) || 'query' === $category['name'] ) {
continue;

if ( ! isset( $query_args['source'] ) || in_array( 'core', $query_args['source'], true ) ) {
foreach ( $categories as $category ) {
if ( in_array( $category['label'], $unique_categories, true ) || 'query' === $category['name'] ) {
continue;
}
$prepared_category = $this->prepare_item_for_response( $category, $request );
$response[] = $this->prepare_response_for_collection( $prepared_category );
}
$prepared_category = $this->prepare_item_for_response( $category, $request );
$response[] = $this->prepare_response_for_collection( $prepared_category );
}

return rest_ensure_response( $response );
Expand All @@ -71,14 +81,19 @@ public function get_items( $request ) {
*/
public function prepare_item_for_response( $item, $request ) {
$fields = $this->get_fields_for_response( $request );
$keys = array( 'name', 'label', 'description', 'id' );
$keys = array( 'name', 'label', 'description' );
$data = array();
foreach ( $keys as $key ) {
if ( isset( $item[ $key ] ) && rest_is_field_included( $key, $fields ) ) {
$data[ $key ] = $item[ $key ];
}
}

// For backwards compatibility we only want to include the id if the field is explicitly requested.
if ( rest_is_field_included( 'id', $fields ) && isset( $item['id'] ) ) {
$data['id'] = $item['id'];
}

$context = ! empty( $request['context'] ) ? $request['context'] : 'view';
$data = $this->add_additional_fields_to_object( $data, $request );
$data = $this->filter_response_by_context( $data, $context );
Expand Down Expand Up @@ -123,10 +138,10 @@ public function get_item_schema() {
'context' => array( 'view', 'edit', 'embed' ),
),
'id' => array(
'id' => __( 'An optional category id, currently used to provide id for user wp_pattern_category terms' ),
'type' => 'number',
'readonly' => true,
'context' => array( 'view', 'edit', 'embed' ),
'description' => __( 'An optional category id, currently used to provide id for user wp_pattern_category terms' ),
'type' => 'number',
'readonly' => true,
'context' => array( 'view', 'edit', 'embed' ),
),
),
);
Expand All @@ -135,4 +150,32 @@ public function get_item_schema() {

return $this->add_additional_fields_schema( $this->schema );
}

/**
* Retrieves the search parameters for the block pattern categories.
*
* @since 6.5.0 Added to request.
*
* @return array Collection parameters.
*/
public function get_collection_params() {
$query_params = parent::get_collection_params();

$query_params['source'] = array(
'description' => __( 'Limit result set to comments assigned to specific sources, `core` or `user`' ),
'type' => 'array',
'items' => array(
'type' => 'string',
),
);

/**
* Filter collection parameters for the block pattern categories controller.
*
* @since 5.8.0
*
* @param array $query_params JSON Schema-formatted collection parameters.
*/
return apply_filters( 'rest_pattern_directory_collection_params', $query_params );
}
}
15 changes: 9 additions & 6 deletions packages/block-editor/src/store/selectors.js
Original file line number Diff line number Diff line change
Expand Up @@ -2294,20 +2294,23 @@ const checkAllowListRecursive = ( blocks, allowedBlockTypes ) => {
function getUserPatterns( state ) {
const userPatterns =
state?.settings?.__experimentalReusableBlocks ?? EMPTY_ARRAY;
const userPatternCategories =
state?.settings?.__experimentalUserPatternCategories ?? [];
const patternCategories =
state?.settings?.__experimentalBlockPatternCategories ?? [];
const categories = new Map();
userPatternCategories.forEach( ( userCategory ) =>
categories.set( userCategory.id, userCategory )
);
patternCategories.forEach( ( category ) => {
if ( category.id ) {
categories.set( category.id, category );
}
} );

return userPatterns.map( ( userPattern ) => {
return {
name: `core/block/${ userPattern.id }`,
id: userPattern.id,
title: userPattern.title.raw,
categories: userPattern.wp_pattern_category.map( ( catId ) =>
categories && categories.get( catId )
? categories.get( catId ).slug
? categories.get( catId ).name
: catId
),
content: userPattern.content.raw,
Expand Down
12 changes: 12 additions & 0 deletions packages/core-data/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -653,6 +653,18 @@ _Returns_

- `any`: The entity record's save error.

### getPatternCategories

Retrieve the core and user pattern categories.

_Parameters_

- _state_ `State`: Data state.

_Returns_

- `Array< unknown >`: User patterns category array.

### getRawEntityRecord

Returns the entity's record object by key, with its attributes mapped to their raw values.
Expand Down
9 changes: 9 additions & 0 deletions packages/core-data/src/reducer.js
Original file line number Diff line number Diff line change
Expand Up @@ -543,6 +543,14 @@ export function userPatternCategories( state = [], action ) {
return state;
}

export function patternCategories( state = [], action ) {
switch ( action.type ) {
case 'RECEIVE_PATTERN_CATEGORIES':
return action.patternCategories;
}
return state;
}

export function navigationFallbackId( state = null, action ) {
switch ( action.type ) {
case 'RECEIVE_NAVIGATION_FALLBACK_ID':
Expand Down Expand Up @@ -591,5 +599,6 @@ export default combineReducers( {
blockPatterns,
blockPatternCategories,
userPatternCategories,
patternCategories,
navigationFallbackId,
} );
15 changes: 15 additions & 0 deletions packages/core-data/src/resolvers.js
Original file line number Diff line number Diff line change
Expand Up @@ -668,6 +668,21 @@ export const getUserPatternCategories =
} );
};

export const getPatternCategories =
() =>
async ( { dispatch } ) => {
const patternCategories = await apiFetch( {
path: addQueryArgs( '/wp/v2/block-patterns/categories', {
_fields: 'name,label,description, id',
source: [ 'core', 'user' ],
} ),
} );
dispatch( {
type: 'RECEIVE_PATTERN_CATEGORIES',
patternCategories,
} );
};

export const getNavigationFallbackId =
() =>
async ( { dispatch, select } ) => {
Expand Down
13 changes: 13 additions & 0 deletions packages/core-data/src/selectors.ts
Original file line number Diff line number Diff line change
Expand Up @@ -46,6 +46,7 @@ export interface State {
users: UserState;
navigationFallbackId: EntityRecordKey;
userPatternCategories: Array< UserPatternCategory >;
patternCategories: Array< unknown >;
}

type EntityRecordKey = string | number;
Expand Down Expand Up @@ -1332,6 +1333,18 @@ export function getUserPatternCategories(
return state.userPatternCategories;
}

/**
* Retrieve the core and user pattern categories.
*
* @param state Data state.
*
* @return User patterns category array.
*/

export function getPatternCategories( state: State ): Array< unknown > {
return state.patternCategories;
}

/**
* Returns the revisions of the current global styles theme.
*
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -125,7 +125,7 @@ export default function useSiteEditorSettings() {
return {
restBlockPatterns: select( coreStore ).getBlockPatterns(),
restBlockPatternCategories:
select( coreStore ).getBlockPatternCategories(),
select( coreStore ).getPatternCategories(),
templateSlug: _record.slug,
};
}, [] );
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -42,7 +42,7 @@ export default function DeleteCategoryMenuItem( { category, onClose } ) {

// Prevent the need to refresh the page to get up-to-date categories
// and pattern categorization.
invalidateResolution( 'getBlockPatternCategories' );
invalidateResolution( 'getPatternCategories' );
invalidateResolution( 'getEntityRecords', [
'postType',
PATTERN_TYPES.user,
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -163,7 +163,7 @@ export default function PatternCategories( { post } ) {
const newTerm = await saveEntityRecord( 'taxonomy', slug, term, {
throwOnError: true,
} );
invalidateResolution( 'getBlockPatternCategories' );
invalidateResolution( 'getPatternCategories' );
return unescapeTerm( newTerm );
} catch ( error ) {
if ( error.code !== 'term_exists' ) {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -41,13 +41,12 @@ export default function usePatternDetails( postType, postId ) {
select( editorStore ).__experimentalGetDefaultTemplatePartAreas(),
[]
);
const { currentTheme, userPatternCategories } = useSelect( ( select ) => {
const { getCurrentTheme, getUserPatternCategories } =
select( coreStore );
const { currentTheme, patternCategories } = useSelect( ( select ) => {
const { getCurrentTheme, getPatternCategories } = select( coreStore );

return {
currentTheme: getCurrentTheme(),
userPatternCategories: getUserPatternCategories(),
patternCategories: getPatternCategories(),
};
}, [] );

Expand Down Expand Up @@ -105,14 +104,16 @@ export default function usePatternDetails( postType, postId ) {
} );
}
if ( record.wp_pattern_category?.length > 0 ) {
const patternCategories = new Map();
userPatternCategories.forEach( ( userCategory ) =>
const patternCategoriesMap = new Map();
patternCategories.forEach( ( userCategory ) =>
patternCategories.set( userCategory.id, userCategory )
);

const categories = record.wp_pattern_category
.filter( ( category ) => patternCategories.get( category ) )
.map( ( category ) => patternCategories.get( category ).label );
.filter( ( category ) => patternCategoriesMap.get( category ) )
.map(
( category ) => patternCategoriesMap.get( category ).label
);

details.push( {
label: __( 'Categories' ),
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -22,7 +22,7 @@ export default function useDefaultPatternCategories() {
} );

const restBlockPatternCategories = useSelect( ( select ) =>
select( coreStore ).getBlockPatternCategories()
select( coreStore ).getPatternCategories()
);

return [
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -95,13 +95,11 @@ function useBlockEditorSettings( settings, hasTemplate ) {
pageOnFront,
pageForPosts,
postType,
userPatternCategories,
} = useSelect( ( select ) => {
const { canUserUseUnfilteredHTML, getCurrentPostType } =
select( editorStore );
const isWeb = Platform.OS === 'web';
const { canUser, getEntityRecord, getUserPatternCategories } =
select( coreStore );
const { canUser, getEntityRecord } = select( coreStore );

const siteSettings = canUser( 'read', 'settings' )
? getEntityRecord( 'root', 'site' )
Expand All @@ -121,7 +119,6 @@ function useBlockEditorSettings( settings, hasTemplate ) {
pageOnFront: siteSettings?.page_on_front,
pageForPosts: siteSettings?.page_for_posts,
postType: getCurrentPostType(),
userPatternCategories: getUserPatternCategories(),
};
}, [] );

Expand All @@ -136,7 +133,7 @@ function useBlockEditorSettings( settings, hasTemplate ) {
( select ) => ( {
restBlockPatterns: select( coreStore ).getBlockPatterns(),
restBlockPatternCategories:
select( coreStore ).getBlockPatternCategories(),
select( coreStore ).getPatternCategories(),
} ),
[]
);
Expand Down Expand Up @@ -209,7 +206,6 @@ function useBlockEditorSettings( settings, hasTemplate ) {
__experimentalReusableBlocks: reusableBlocks,
__experimentalBlockPatterns: blockPatterns,
__experimentalBlockPatternCategories: blockPatternCategories,
__experimentalUserPatternCategories: userPatternCategories,
__experimentalFetchLinkSuggestions: ( search, searchOptions ) =>
fetchLinkSuggestions( search, searchOptions, settings ),
inserterMediaCategories,
Expand All @@ -227,7 +223,6 @@ function useBlockEditorSettings( settings, hasTemplate ) {
settings,
hasUploadPermissions,
reusableBlocks,
userPatternCategories,
blockPatterns,
blockPatternCategories,
canUseUnfilteredHTML,
Expand Down
Loading

0 comments on commit 3815ce3

Please sign in to comment.