Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

[Block Library - Query Loop]: Add multiple authors support #38024

Merged
merged 5 commits into from
Jan 18, 2022
Merged
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
94 changes: 94 additions & 0 deletions lib/compat/wordpress-6.0/blocks.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,94 @@
<?php
/**
* Temporary compatibility shims for features present in Gutenberg.
*
* @package gutenberg
*/

/**
* Helper function that constructs a WP_Query args array from
* a `Query` block properties.
*
* It's used in QueryLoop, QueryPaginationNumbers and QueryPaginationNext blocks.
*
* `build_query_vars_from_query_block` was introduced in 5.8, for 6.0 we just need
* to update that function and not create a new one.
*
* @param WP_Block $block Block instance.
* @param int $page Current query's page.
*
* @return array Returns the constructed WP_Query arguments.
*/
function gutenberg_build_query_vars_from_query_block( $block, $page ) {
$query = array(
'post_type' => 'post',
'order' => 'DESC',
'orderby' => 'date',
'post__not_in' => array(),
);

if ( isset( $block->context['query'] ) ) {
if ( ! empty( $block->context['query']['postType'] ) ) {
$post_type_param = $block->context['query']['postType'];
if ( is_post_type_viewable( $post_type_param ) ) {
$query['post_type'] = $post_type_param;
}
}
if ( isset( $block->context['query']['sticky'] ) && ! empty( $block->context['query']['sticky'] ) ) {
$sticky = get_option( 'sticky_posts' );
if ( 'only' === $block->context['query']['sticky'] ) {
$query['post__in'] = $sticky;
} else {
$query['post__not_in'] = array_merge( $query['post__not_in'], $sticky );
}
}
if ( ! empty( $block->context['query']['exclude'] ) ) {
$excluded_post_ids = array_map( 'intval', $block->context['query']['exclude'] );
$excluded_post_ids = array_filter( $excluded_post_ids );
$query['post__not_in'] = array_merge( $query['post__not_in'], $excluded_post_ids );
}
if (
isset( $block->context['query']['perPage'] ) &&
is_numeric( $block->context['query']['perPage'] )
) {
$per_page = absint( $block->context['query']['perPage'] );
$offset = 0;

if (
isset( $block->context['query']['offset'] ) &&
is_numeric( $block->context['query']['offset'] )
) {
$offset = absint( $block->context['query']['offset'] );
}

$query['offset'] = ( $per_page * ( $page - 1 ) ) + $offset;
$query['posts_per_page'] = $per_page;
}
if ( ! empty( $block->context['query']['categoryIds'] ) ) {
$term_ids = array_map( 'intval', $block->context['query']['categoryIds'] );
$term_ids = array_filter( $term_ids );
$query['category__in'] = $term_ids;
}
if ( ! empty( $block->context['query']['tagIds'] ) ) {
$term_ids = array_map( 'intval', $block->context['query']['tagIds'] );
$term_ids = array_filter( $term_ids );
$query['tag__in'] = $term_ids;
}
if (
isset( $block->context['query']['order'] ) &&
in_array( strtoupper( $block->context['query']['order'] ), array( 'ASC', 'DESC' ), true )
) {
$query['order'] = strtoupper( $block->context['query']['order'] );
}
if ( isset( $block->context['query']['orderBy'] ) ) {
$query['orderby'] = $block->context['query']['orderBy'];
}
if ( ! empty( $block->context['query']['author'] ) ) {
$query['author'] = $block->context['query']['author'];
}
if ( ! empty( $block->context['query']['search'] ) ) {
$query['s'] = $block->context['query']['search'];
}
}
return $query;
}
1 change: 1 addition & 0 deletions lib/load.php
Original file line number Diff line number Diff line change
Expand Up @@ -127,6 +127,7 @@ function gutenberg_is_experiment_enabled( $name ) {
require __DIR__ . '/compat/wordpress-5.9/rest-active-global-styles.php';
require __DIR__ . '/compat/wordpress-5.9/move-theme-editor-menu-item.php';
require __DIR__ . '/compat/wordpress-6.0/post-lock.php';
require __DIR__ . '/compat/wordpress-6.0/blocks.php';
require __DIR__ . '/compat/experimental/blocks.php';

require __DIR__ . '/blocks.php';
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,78 @@
/**
* WordPress dependencies
*/
import { __ } from '@wordpress/i18n';
import { FormTokenField } from '@wordpress/components';
import { useSelect } from '@wordpress/data';
import { store as coreStore } from '@wordpress/core-data';

/**
* Internal dependencies
*/
import { getEntitiesInfo } from '../../utils';

const AUTHORS_QUERY = {
who: 'authors',
per_page: -1,
_fields: 'id,name',
context: 'view',
};

function AuthorControl( { value, onChange } ) {
const authorsList = useSelect( ( select ) => {
const { getUsers } = select( coreStore );
return getUsers( AUTHORS_QUERY );
}, [] );

if ( ! authorsList ) {
return null;
}
const authorsInfo = getEntitiesInfo( authorsList );
/**
* We need to normalize the value because the block operates on a
* comma(`,`) separated string value and `FormTokenFiels` needs an
* array.
*/
const normalizedValue = ! value ? [] : value.toString().split( ',' );
// Returns only the existing authors ids. This prevents the component
// from crashing in the editor, when non existing ids are provided.
const sanitizedValue = normalizedValue.reduce(
( accumulator, authorId ) => {
const author = authorsInfo.mapById[ authorId ];
if ( author ) {
accumulator.push( {
id: authorId,
value: author.name,
} );
}
return accumulator;
},
[]
);

const getIdByValue = ( entitiesMappedByName, authorValue ) => {
const id = authorValue?.id || entitiesMappedByName[ authorValue ]?.id;
if ( id ) return id;
};
const onAuthorChange = ( newValue ) => {
const ids = Array.from(
newValue.reduce( ( accumulator, author ) => {
// Verify that new values point to existing entities.
const id = getIdByValue( authorsInfo.mapByName, author );
if ( id ) accumulator.add( id );
return accumulator;
}, new Set() )
);
onChange( { author: ids.join( ',' ) } );
};
return (
<FormTokenField
label={ __( 'Authors' ) }
value={ sanitizedValue }
suggestions={ authorsInfo.names }
onChange={ onAuthorChange }
/>
);
}

export default AuthorControl;
Original file line number Diff line number Diff line change
Expand Up @@ -8,7 +8,6 @@ import { debounce } from 'lodash';
*/
import {
PanelBody,
QueryControls,
TextControl,
FormTokenField,
SelectControl,
Expand All @@ -26,7 +25,8 @@ import { store as coreStore } from '@wordpress/core-data';
* Internal dependencies
*/
import OrderControl from './order-control';
import { getTermsInfo, usePostTypes } from '../../utils';
import AuthorControl from './author-control';
import { getEntitiesInfo, usePostTypes } from '../../utils';
import { MAX_FETCHED_TERMS } from '../../constants';

const stickyOptions = [
Expand Down Expand Up @@ -65,7 +65,7 @@ export default function QueryInspectorControls( {
const {
order,
orderBy,
author: selectedAuthorId,
author: authorIds,
postType,
sticky,
inherit,
Expand All @@ -74,7 +74,7 @@ export default function QueryInspectorControls( {
const [ showTags, setShowTags ] = useState( true );
const [ showSticky, setShowSticky ] = useState( postType === 'post' );
const { postTypesTaxonomiesMap, postTypesSelectOptions } = usePostTypes();
const { authorList, categories, tags } = useSelect( ( select ) => {
const { categories, tags } = useSelect( ( select ) => {
const { getEntityRecords } = select( coreStore );
const termsQuery = { per_page: MAX_FETCHED_TERMS };
const _categories = getEntityRecords(
Expand All @@ -84,11 +84,8 @@ export default function QueryInspectorControls( {
);
const _tags = getEntityRecords( 'taxonomy', 'post_tag', termsQuery );
return {
categories: getTermsInfo( _categories ),
tags: getTermsInfo( _tags ),
authorList: getEntityRecords( 'root', 'user', {
per_page: -1,
} ),
categories: getEntitiesInfo( _categories ),
tags: getEntitiesInfo( _tags ),
};
}, [] );
useEffect( () => {
Expand Down Expand Up @@ -237,7 +234,7 @@ export default function QueryInspectorControls( {
</PanelBody>
{ ! inherit && (
<PanelBody title={ __( 'Filters' ) }>
{ showCategories && categories?.terms?.length > 0 && (
{ showCategories && categories?.entities?.length > 0 && (
<FormTokenField
label={ __( 'Categories' ) }
value={ getExistingTermsFormTokenValue(
Expand All @@ -247,7 +244,7 @@ export default function QueryInspectorControls( {
onChange={ onCategoriesChange }
/>
) }
{ showTags && tags?.terms?.length > 0 && (
{ showTags && tags?.entities?.length > 0 && (
<FormTokenField
label={ __( 'Tags' ) }
value={ getExistingTermsFormTokenValue(
Expand All @@ -257,14 +254,7 @@ export default function QueryInspectorControls( {
onChange={ onTagsChange }
/>
) }
<QueryControls
{ ...{ selectedAuthorId, authorList } }
onAuthorChange={ ( value ) =>
setQuery( {
author: value !== '' ? +value : undefined,
} )
}
/>
<AuthorControl value={ authorIds } onChange={ setQuery } />
<TextControl
label={ __( 'Keyword' ) }
value={ querySearch }
Expand Down
10 changes: 6 additions & 4 deletions packages/block-library/src/query/test/utils.js
Original file line number Diff line number Diff line change
Expand Up @@ -2,15 +2,17 @@
* Internal dependencies
*/
import { terms } from './fixtures';
import { getTermsInfo } from '../utils';
import { getEntitiesInfo } from '../utils';

describe( 'Query block utils', () => {
describe( 'getTermsInfo', () => {
describe( 'getEntitiesInfo', () => {
it( 'should return an empty object when no terms provided', () => {
expect( getTermsInfo() ).toEqual( { terms: undefined } );
expect( getEntitiesInfo() ).toEqual( {
terms: undefined,
} );
} );
it( 'should return proper terms info object', () => {
expect( getTermsInfo( terms ) ).toEqual(
expect( getEntitiesInfo( terms ) ).toEqual(
expect.objectContaining( {
mapById: expect.objectContaining( {
4: expect.objectContaining( { name: 'nba' } ),
Expand Down
52 changes: 21 additions & 31 deletions packages/block-library/src/query/utils.js
Original file line number Diff line number Diff line change
Expand Up @@ -6,53 +6,43 @@ import { useMemo } from '@wordpress/element';
import { store as coreStore } from '@wordpress/core-data';

/**
* WordPress term object from REST API.
* Categories ref: https://developer.wordpress.org/rest-api/reference/categories/
* Tags ref: https://developer.wordpress.org/rest-api/reference/tags/
*
* @typedef {Object} WPTerm
* @property {number} id Unique identifier for the term.
* @property {number} count Number of published posts for the term.
* @property {string} description HTML description of the term.
* @property {string} link URL of the term.
* @property {string} name HTML title for the term.
* @property {string} slug An alphanumeric identifier for the term unique to its type.
* @property {string} taxonomy Type attribution for the term.
* @property {Object} meta Meta fields
* @property {number} [parent] The parent term ID.
* @typedef IHasNameAndId
ntsekouras marked this conversation as resolved.
Show resolved Hide resolved
* @property {string|number} id The entity's id.
* @property {string} name The entity's name.
*/

/**
* The object used in Query block that contains info and helper mappings
* from an array of WPTerm.
* from an array of IHasNameAndId objects.
*
* @typedef {Object} QueryTermsInfo
* @property {WPTerm[]} terms The array of terms.
* @property {Object<string, WPTerm>} mapById Object mapping with the term id as key and the term as value.
* @property {Object<string, WPTerm>} mapByName Object mapping with the term name as key and the term as value.
* @property {string[]} names Array with the terms' names.
* @typedef {Object} QueryEntitiesInfo
* @property {IHasNameAndId[]} entities The array of entities.
* @property {Object<string, IHasNameAndId>} mapById Object mapping with the id as key and the entity as value.
* @property {Object<string, IHasNameAndId>} mapByName Object mapping with the name as key and the entity as value.
* @property {string[]} names Array with the entities' names.
*/

/**
* Returns a helper object with mapping from WPTerms.
* Returns a helper object with mapping from Objects that implement
* the `IHasNameAndId` interface. The returned object is used for
* integration with `FormTokenField` component.
*
* @param {WPTerm[]} terms The terms to extract of helper object.
* @return {QueryTermsInfo} The object with the terms information.
* @param {IHasNameAndId[]} entities The entities to extract of helper object.
* @return {QueryEntitiesInfo} The object with the entities information.
*/
export const getTermsInfo = ( terms ) => {
const mapping = terms?.reduce(
( accumulator, term ) => {
export const getEntitiesInfo = ( entities ) => {
const mapping = entities?.reduce(
( accumulator, entity ) => {
const { mapById, mapByName, names } = accumulator;
mapById[ term.id ] = term;
mapByName[ term.name ] = term;
names.push( term.name );
mapById[ entity.id ] = entity;
mapByName[ entity.name ] = entity;
names.push( entity.name );
return accumulator;
},
{ mapById: {}, mapByName: {}, names: [] }
);

return {
terms,
entities,
...mapping,
};
};
Expand Down
Loading