diff --git a/packages/media-utils/CHANGELOG.md b/packages/media-utils/CHANGELOG.md index 4fdd72a58dd90f..9acd39969b80c9 100644 --- a/packages/media-utils/CHANGELOG.md +++ b/packages/media-utils/CHANGELOG.md @@ -2,6 +2,10 @@ ## Unreleased +### Enhancements + +- `MediaUploadModal`: Query filters on attachment taxonomy fields by the taxonomy. ([#86458](https://github.com/WordPress/gutenberg/pull/86458)) + ## 6.1.0 (2026-11-04) ### Enhancements diff --git a/packages/media-utils/src/components/media-upload-modal/index.tsx b/packages/media-utils/src/components/media-upload-modal/index.tsx index 3dabda5a3b87dd..4b23f9912a3864 100644 --- a/packages/media-utils/src/components/media-upload-modal/index.tsx +++ b/packages/media-utils/src/components/media-upload-modal/index.tsx @@ -46,6 +46,7 @@ import { uploadMedia } from '../../utils/upload-media'; import { unlock } from '../../lock-unlock'; import { UploadStatusPopover } from './upload-status-popover'; import { useInvalidateAttachmentResolutions } from './use-invalidate-attachment-resolutions'; +import { getTaxonomyQueryArgs } from './taxonomy-query'; import { useUploadStatus } from './use-upload-status'; const { useEntityRecordsWithPermissions } = unlock( coreDataPrivateApis ); @@ -281,6 +282,15 @@ export function MediaUploadModal( { [ attachedToPostId, postType ] ); + // The attachment taxonomies, so that a filter on a taxonomy field reaches + // the query. Only requested when attachments have taxonomies at all. + const taxonomies = useSelect( ( select ) => { + const { getPostType, getTaxonomies } = select( coreStore ); + return getPostType( 'attachment' )?.taxonomies?.length + ? getTaxonomies( { type: 'attachment' } ) + : undefined; + }, [] ); + const [ selection, setSelection ] = useState< string[] >( () => getSelectionFromValue( value ) ); @@ -451,9 +461,10 @@ export function MediaUploadModal( { orderby: view.sort?.field, search: view.search, _embed: 'author,wp:attached-to', + ...getTaxonomyQueryArgs( view.filters, taxonomies ?? [] ), ...filters, }; - }, [ view, allowedTypes, attachedToPostId ] ); + }, [ view, allowedTypes, attachedToPostId, taxonomies ] ); // Per-batch completion handler: auto-select uploaded items and refresh the grid. const handleBatchComplete = useCallback( diff --git a/packages/media-utils/src/components/media-upload-modal/taxonomy-query.ts b/packages/media-utils/src/components/media-upload-modal/taxonomy-query.ts new file mode 100644 index 00000000000000..b77655ab79effd --- /dev/null +++ b/packages/media-utils/src/components/media-upload-modal/taxonomy-query.ts @@ -0,0 +1,73 @@ +import type { Filter } from '@wordpress/dataviews'; + +/** + * The parts of a taxonomy record from core-data that the query needs. + */ +type QueryTaxonomy = { + slug: string; + rest_base?: string; +}; + +/** + * Returns the REST query arguments for a view's filters on taxonomy fields. + * + * A taxonomy field is one whose ID is the taxonomy's REST base: the property + * that holds an item's term IDs in its REST record, and the query parameter + * that filters items by them. Filters on other fields are left for the caller. + * + * - `is` and `isAny` match items with any of the terms. + * - `isAll` matches items with every one of the terms. + * - `isNot` and `isNone` match items with none of the terms. + * + * A filter matches the chosen terms only, not their child terms, because the + * REST API's `include_children` defaults to false. A filter with no terms + * leaves the query alone. + * + * The post list route has a copy of this function, so change both together. + * + * @param filters The view's filters. + * @param taxonomies The taxonomies of the entity, as `getTaxonomies()` returns them. + * + * @return The query arguments, such as `{ categories: [ 3, 4 ] }`. + */ +export function getTaxonomyQueryArgs( + filters: Filter[] = [], + taxonomies: QueryTaxonomy[] = [] +): Record< string, unknown > { + const bases = new Set( + taxonomies.map( ( taxonomy ) => taxonomy.rest_base || taxonomy.slug ) + ); + const args: Record< string, unknown > = {}; + + for ( const filter of filters ) { + if ( ! bases.has( filter.field ) ) { + continue; + } + + const terms = ( + Array.isArray( filter.value ) ? filter.value : [ filter.value ] + ).filter( + ( term ) => term !== undefined && term !== null && term !== '' + ); + + if ( ! terms.length ) { + continue; + } + + switch ( filter.operator ) { + case 'is': + case 'isAny': + args[ filter.field ] = terms; + break; + case 'isAll': + args[ filter.field ] = { terms, operator: 'AND' }; + break; + case 'isNot': + case 'isNone': + args[ `${ filter.field }_exclude` ] = terms; + break; + } + } + + return args; +} diff --git a/packages/media-utils/src/components/media-upload-modal/test/index.jsdom.test.tsx b/packages/media-utils/src/components/media-upload-modal/test/index.jsdom.test.tsx index 97baadd683fd90..d42f629db1b9a3 100644 --- a/packages/media-utils/src/components/media-upload-modal/test/index.jsdom.test.tsx +++ b/packages/media-utils/src/components/media-upload-modal/test/index.jsdom.test.tsx @@ -29,8 +29,11 @@ const POST_TYPES: Record< string, unknown > = { page: { labels: { uploaded_to_this_item: 'Uploaded to this page' } }, // A post type that never set the label. cpt: { labels: {} }, + attachment: { labels: {}, taxonomies: [ 'genre' ] }, }; +const TAXONOMIES = [ { slug: 'genre', rest_base: 'genres' } ]; + vi.mock( import( '@wordpress/core-data' ), async () => { const { __dangerousOptInToUnstableAPIsOnlyForCoreModules } = await import( '@wordpress/private-apis' ); @@ -101,6 +104,7 @@ function renderModal( reducer: ( state = {} ) => state, selectors: { getPostType: ( state: unknown, slug: string ) => POST_TYPES[ slug ], + getTaxonomies: () => TAXONOMIES, }, } ); @@ -623,6 +627,27 @@ describe( 'MediaUploadModal', () => { } ); } ); + it( 'queries a filter on a taxonomy field by the taxonomy', async () => { + renderModal( + {}, + { + filters: [ + { field: 'genres', operator: 'isNone', value: [ 3 ] }, + ], + } + ); + + await waitFor( () => { + expect( + mockUseEntityRecordsWithPermissions + ).toHaveBeenLastCalledWith( + 'postType', + 'attachment', + expect.objectContaining( { genres_exclude: [ 3 ] } ) + ); + } ); + } ); + it( 'updates the media query when the picker changes search', async () => { const user = userEvent.setup(); const { registry } = renderModal(); diff --git a/packages/media-utils/src/components/media-upload-modal/test/taxonomy-query.ts b/packages/media-utils/src/components/media-upload-modal/test/taxonomy-query.ts new file mode 100644 index 00000000000000..3e489d4e218b13 --- /dev/null +++ b/packages/media-utils/src/components/media-upload-modal/test/taxonomy-query.ts @@ -0,0 +1,107 @@ +import { describe, expect, it } from 'vitest'; +import { getTaxonomyQueryArgs } from '../taxonomy-query'; + +const TAXONOMIES = [ + { slug: 'category', rest_base: 'categories' }, + { slug: 'post_tag', rest_base: 'tags' }, + { slug: 'genre' }, + { slug: 'place', rest_base: 'places', hierarchical: true }, +]; + +describe( 'getTaxonomyQueryArgs', () => { + it( 'queries items with any of the terms', () => { + expect( + getTaxonomyQueryArgs( + [ { field: 'categories', operator: 'isAny', value: [ 3, 4 ] } ], + TAXONOMIES + ) + ).toEqual( { categories: [ 3, 4 ] } ); + } ); + + it( 'queries items with every one of the terms', () => { + expect( + getTaxonomyQueryArgs( + [ { field: 'tags', operator: 'isAll', value: [ 5, 6 ] } ], + TAXONOMIES + ) + ).toEqual( { tags: { terms: [ 5, 6 ], operator: 'AND' } } ); + } ); + + it( 'queries items with none of the terms', () => { + expect( + getTaxonomyQueryArgs( + [ { field: 'tags', operator: 'isNone', value: [ 7 ] } ], + TAXONOMIES + ) + ).toEqual( { tags_exclude: [ 7 ] } ); + } ); + + it( 'leaves `include_children` at the REST default of false', () => { + expect( + getTaxonomyQueryArgs( + [ + { field: 'places', operator: 'isAny', value: [ 9 ] }, + { field: 'places', operator: 'isNone', value: [ 10 ] }, + ], + TAXONOMIES + ) + ).toEqual( { places: [ 9 ], places_exclude: [ 10 ] } ); + } ); + + it( 'takes a single term for `is` and `isNot`', () => { + expect( + getTaxonomyQueryArgs( + [ + { field: 'categories', operator: 'is', value: 3 }, + { field: 'tags', operator: 'isNot', value: 7 }, + ], + TAXONOMIES + ) + ).toEqual( { categories: [ 3 ], tags_exclude: [ 7 ] } ); + } ); + + it( 'combines filters on several taxonomies', () => { + expect( + getTaxonomyQueryArgs( + [ + { field: 'categories', operator: 'isAny', value: [ 3 ] }, + { field: 'tags', operator: 'isNone', value: [ 7 ] }, + ], + TAXONOMIES + ) + ).toEqual( { categories: [ 3 ], tags_exclude: [ 7 ] } ); + } ); + + it( 'uses the slug of a taxonomy with no REST base', () => { + expect( + getTaxonomyQueryArgs( + [ { field: 'genre', operator: 'isAny', value: [ 8 ] } ], + TAXONOMIES + ) + ).toEqual( { genre: [ 8 ] } ); + } ); + + it( 'leaves the query alone for a filter with no terms', () => { + expect( + getTaxonomyQueryArgs( + [ + { field: 'categories', operator: 'isAny', value: [] }, + { field: 'tags', operator: 'isAny', value: undefined }, + ], + TAXONOMIES + ) + ).toEqual( {} ); + } ); + + it( 'ignores filters on fields that are not taxonomies', () => { + expect( + getTaxonomyQueryArgs( + [ + { field: 'author', operator: 'isAny', value: [ 1 ] }, + { field: 'post_tag', operator: 'isAny', value: [ 5 ] }, + ], + TAXONOMIES + ) + ).toEqual( {} ); + } ); +} ); diff --git a/routes/post-list/route.ts b/routes/post-list/route.ts index cf62fa9478f970..aab2cddbf5196c 100644 --- a/routes/post-list/route.ts +++ b/routes/post-list/route.ts @@ -61,7 +61,15 @@ export const route = { } // Otherwise, fetch the first post from the filtered query - const query = viewToQuery( view, params.type ); + const postType = await resolveSelect( coreStore ).getPostType( + params.type + ); + const taxonomies = postType?.taxonomies?.length + ? await resolveSelect( coreStore ).getTaxonomies( { + type: params.type, + } ) + : []; + const query = viewToQuery( view, params.type, taxonomies ?? [] ); const posts = await resolveSelect( coreStore ).getEntityRecords( 'postType', params.type, diff --git a/routes/post-list/stage.tsx b/routes/post-list/stage.tsx index 3063b8ff69705b..f1c000c47f5711 100644 --- a/routes/post-list/stage.tsx +++ b/routes/post-list/stage.tsx @@ -166,9 +166,19 @@ function PostListView( { } }; + const hasTaxonomies = !! postTypeObject?.taxonomies?.length; + const taxonomies = useSelect( + ( select ) => + hasTaxonomies + ? select( coreStore ).getTaxonomies( { + type: postType, + } ) + : undefined, + [ hasTaxonomies, postType ] + ); const postTypeQuery = useMemo( - () => viewToQuery( view, postType ), - [ view, postType ] + () => viewToQuery( view, postType, taxonomies ?? [] ), + [ view, postType, taxonomies ] ); const { records: posts, diff --git a/routes/post-list/taxonomy-query.ts b/routes/post-list/taxonomy-query.ts new file mode 100644 index 00000000000000..6b24349af56963 --- /dev/null +++ b/routes/post-list/taxonomy-query.ts @@ -0,0 +1,74 @@ +import type { Filter } from '@wordpress/dataviews'; + +/** + * The parts of a taxonomy record from core-data that the query needs. + */ +type QueryTaxonomy = { + slug: string; + rest_base?: string; +}; + +/** + * Returns the REST query arguments for a view's filters on taxonomy fields. + * + * A taxonomy field is one whose ID is the taxonomy's REST base: the property + * that holds an item's term IDs in its REST record, and the query parameter + * that filters items by them. Filters on other fields are left for the caller. + * + * - `is` and `isAny` match items with any of the terms. + * - `isAll` matches items with every one of the terms. + * - `isNot` and `isNone` match items with none of the terms. + * + * A filter matches the chosen terms only, not their child terms, because the + * REST API's `include_children` defaults to false. A filter with no terms + * leaves the query alone. + * + * The media upload modal in `@wordpress/media-utils` has a copy of this + * function, so change both together. + * + * @param filters The view's filters. + * @param taxonomies The taxonomies of the entity, as `getTaxonomies()` returns them. + * + * @return The query arguments, such as `{ categories: [ 3, 4 ] }`. + */ +export function getTaxonomyQueryArgs( + filters: Filter[] = [], + taxonomies: QueryTaxonomy[] = [] +): Record< string, unknown > { + const bases = new Set( + taxonomies.map( ( taxonomy ) => taxonomy.rest_base || taxonomy.slug ) + ); + const args: Record< string, unknown > = {}; + + for ( const filter of filters ) { + if ( ! bases.has( filter.field ) ) { + continue; + } + + const terms = ( + Array.isArray( filter.value ) ? filter.value : [ filter.value ] + ).filter( + ( term ) => term !== undefined && term !== null && term !== '' + ); + + if ( ! terms.length ) { + continue; + } + + switch ( filter.operator ) { + case 'is': + case 'isAny': + args[ filter.field ] = terms; + break; + case 'isAll': + args[ filter.field ] = { terms, operator: 'AND' }; + break; + case 'isNot': + case 'isNone': + args[ `${ filter.field }_exclude` ] = terms; + break; + } + } + + return args; +} diff --git a/routes/post-list/view-utils.ts b/routes/post-list/view-utils.ts index ec70eb592fa146..a144743b366412 100644 --- a/routes/post-list/view-utils.ts +++ b/routes/post-list/view-utils.ts @@ -3,6 +3,7 @@ import { resolveSelect } from '@wordpress/data'; import { store as coreStore } from '@wordpress/core-data'; import type { View, SupportedLayouts } from '@wordpress/dataviews'; import { unlock } from '@wordpress/routes-lock-unlock'; +import { getTaxonomyQueryArgs } from './taxonomy-query'; /** * A layer merged on top of a view. Mirrors the `ViewOverrides` type of @@ -87,7 +88,19 @@ export async function ensureView( queryParams: search, } ); } -export function viewToQuery( view: View, postType: string ) { +/** + * Returns the REST query arguments for a view of a post type's items. + * + * @param view The view. + * @param postType The post type. + * @param taxonomies The post type's taxonomies, so that filters on taxonomy + * fields reach the query. + */ +export function viewToQuery( + view: View, + postType: string, + taxonomies: { slug: string; rest_base?: string }[] = [] +) { const result: Record< string, any > = { _embed: 'author,wp:featuredmedia' }; // Pagination, sorting, search. @@ -168,6 +181,8 @@ export function viewToQuery( view: View, postType: string ) { } } + Object.assign( result, getTaxonomyQueryArgs( view.filters, taxonomies ) ); + // For attachments, also embed the parent (attached to) post to get its title. if ( postType === 'attachment' ) { result._embed = 'author,wp:attached-to';