diff --git a/packages/block-editor/src/components/inserter/block-patterns-tab/index.tsx b/packages/block-editor/src/components/inserter/block-patterns-tab/index.tsx index 58694ce2266979..9d02c57326b078 100644 --- a/packages/block-editor/src/components/inserter/block-patterns-tab/index.tsx +++ b/packages/block-editor/src/components/inserter/block-patterns-tab/index.tsx @@ -1,32 +1,31 @@ import { useState } from '@wordpress/element'; -import { useViewportMatch } from '@wordpress/compose'; import { Button } from '@wordpress/components'; import { Spinner } from '@wordpress/ui'; import { useSelect } from '@wordpress/data'; import { __ } from '@wordpress/i18n'; import PatternsExplorerModal from '../block-patterns-explorer'; -import MobileTabNavigation from '../mobile-tab-navigation'; -import { PatternCategoryPreviews } from './pattern-category-previews'; +import PatternsGrid from './patterns-grid'; import { usePatternCategories } from './use-pattern-categories'; -import CategoryTabs from '../category-tabs'; import InserterNoResults from '../no-results'; import { store as blockEditorStore } from '../../../store'; import { unlock } from '../../../lock-unlock'; import type { BlockPatternsTabProps } from '../types'; +/** + * The inserter's Patterns tab: one sidebar with a search, a settings menu, the + * pattern categories as tabs and the patterns of the selected one, starting on + * "All". It browses like the Media tab. + */ function BlockPatternsTab( { onSelectCategory, selectedCategory, onInsert, rootClientId, - children, }: BlockPatternsTabProps ) { const [ showPatternsExplorer, setShowPatternsExplorer ] = useState( false ); const categories = usePatternCategories( rootClientId ); - const isMobile = useViewportMatch( 'medium', '<' ); - const isResolvingPatterns = useSelect( ( select ) => unlock( select( blockEditorStore ) ).isResolvingPatterns(), @@ -45,15 +44,13 @@ function BlockPatternsTab( { return ( <> - { ! isMobile && ( -
- - { children } - + { __( 'Explore all patterns' ) } -
- ) } - { isMobile && ( - - { ( category ) => ( -
- -
- ) } -
- ) } + } + /> { showPatternsExplorer && ( {}; - -export function PatternCategoryPreviews( { - rootClientId, - onInsert, - onHover = noop, - category, - showTitlesAsTooltip, -}: PatternCategoryPreviewsProps ) { - const [ allPatterns, , onClickPattern ] = usePatternsState( - onInsert, - rootClientId, - category?.name - ); - const [ patternSyncFilter, setPatternSyncFilter ] = useState( 'all' ); - const [ patternSourceFilter, setPatternSourceFilter ] = useState( 'all' ); - const [ patternAuthorFilter, setPatternAuthorFilter ] = useState( 'all' ); - - // The author filter only applies while only user patterns are listed, so - // it doesn't linger unseen in categories where it isn't shown. - const isUserSource = - category.name === sitePatternsCategory.name || - patternSourceFilter === INSERTER_PATTERN_TYPES.user; - const currentPatternAuthorFilter = isUserSource - ? patternAuthorFilter - : 'all'; - - const availableCategories = usePatternCategories( - rootClientId, - patternSourceFilter - ); - const scrollContainerRef = useRef< HTMLDivElement >( null ); - const currentCategoryPatterns = useMemo( - () => - allPatterns.filter( ( pattern: BlockPattern ) => { - if ( - isPatternFiltered( - pattern, - patternSourceFilter, - patternSyncFilter, - currentPatternAuthorFilter - ) - ) { - return false; - } - - if ( category.name === allPatternsCategory.name ) { - return true; - } - - if ( - category.name === sitePatternsCategory.name && - pattern.type === INSERTER_PATTERN_TYPES.user - ) { - return true; - } - - if ( - category.name === starterPatternsCategory.name && - pattern.blockTypes?.includes( 'core/post-content' ) - ) { - return true; - } - - if ( category.name === 'uncategorized' ) { - // The uncategorized category should show all the patterns without any category... - if ( ! pattern.categories ) { - return true; - } - - // ...or with no available category. - return ! pattern.categories.some( ( catName ) => - availableCategories.some( ( c ) => c.name === catName ) - ); - } - - return pattern.categories?.includes( category.name ); - } ), - [ - allPatterns, - availableCategories, - category.name, - patternSourceFilter, - patternSyncFilter, - currentPatternAuthorFilter, - ] - ); - - const pagingProps = usePatternsPaging( - currentCategoryPatterns, - category, - scrollContainerRef - ); - const { changePage } = pagingProps; - - // Hide block pattern preview on unmount. - useEffect( () => () => onHover( null ), [] ); - - const onSetPatternSyncFilter = useCallback( - ( value: string ) => { - setPatternSyncFilter( value ); - changePage( 1 ); - }, - [ setPatternSyncFilter, changePage ] - ); - const onSetPatternSourceFilter = useCallback( - ( value: string ) => { - setPatternSourceFilter( value ); - changePage( 1 ); - }, - [ setPatternSourceFilter, changePage ] - ); - const onSetPatternAuthorFilter = useCallback( - ( value: string ) => { - setPatternAuthorFilter( value ); - changePage( 1 ); - }, - [ setPatternAuthorFilter, changePage ] - ); - - return ( - <> - - - - - { category.label } - - - - - { ! currentCategoryPatterns.length && ( - - { __( 'No results found' ) } - - ) } - - { currentCategoryPatterns.length > 0 && ( - <> - - { __( 'Drag and drop patterns into the canvas.' ) } - - - - ) } - - ); -} diff --git a/packages/block-editor/src/components/inserter/block-patterns-tab/patterns-filter.tsx b/packages/block-editor/src/components/inserter/block-patterns-tab/patterns-filter.tsx deleted file mode 100644 index ddc19da8657fe9..00000000000000 --- a/packages/block-editor/src/components/inserter/block-patterns-tab/patterns-filter.tsx +++ /dev/null @@ -1,211 +0,0 @@ -import { - SVG, - Path, - DropdownMenu, - MenuGroup, - MenuItemsChoice, - ExternalLink, -} from '@wordpress/components'; -import { __, _x } from '@wordpress/i18n'; -import { Icon } from '@wordpress/icons'; -import { useMemo, createInterpolateElement } from '@wordpress/element'; -import { - sitePatternsCategory, - INSERTER_SYNC_TYPES, - INSERTER_PATTERN_TYPES, - INSERTER_AUTHOR_TYPES, -} from './utils'; -import type { PatternCategory, PatternsFilterProps } from '../types'; - -const getShouldDisableSyncFilter = ( sourceFilter: string ) => - sourceFilter !== 'all' && sourceFilter !== 'user'; -const getShouldHideSourcesFilter = ( category: PatternCategory ) => { - return category.name === sitePatternsCategory.name; -}; - -const PATTERN_SOURCE_MENU_OPTIONS = [ - { - value: 'all', - label: _x( 'All', 'patterns' ), - }, - { - value: INSERTER_PATTERN_TYPES.directory, - label: __( 'Pattern Directory' ), - }, - { - value: INSERTER_PATTERN_TYPES.theme, - label: __( 'Theme & Plugins' ), - }, - { - value: INSERTER_PATTERN_TYPES.user, - label: __( 'User' ), - }, -]; - -const PATTERN_AUTHOR_MENU_OPTIONS = [ - { - value: 'all', - label: _x( 'All', 'patterns' ), - }, - { - value: INSERTER_AUTHOR_TYPES.currentUser, - label: __( 'My patterns' ), - }, -]; - -export function PatternsFilter( { - setPatternSyncFilter, - setPatternSourceFilter, - setPatternAuthorFilter, - patternSyncFilter, - patternSourceFilter, - patternAuthorFilter, - scrollContainerRef, - category, -}: PatternsFilterProps ) { - // If the category is `sitePatterns` then we need to set the source filter to `user`, but - // we do this by deriving from props rather than calling setPatternSourceFilter otherwise - // the user may be confused when switching to another category if the haven't explicitly set - // this filter themselves. - const currentPatternSourceFilter = - category.name === sitePatternsCategory.name - ? INSERTER_PATTERN_TYPES.user - : patternSourceFilter; - - // We need to disable the sync filter option if the source filter is not 'all' or 'user' - // otherwise applying them will just result in no patterns being shown. - const shouldDisableSyncFilter = getShouldDisableSyncFilter( - currentPatternSourceFilter - ); - - // We also hide the directory and theme source filter if the category is `sitePatterns` - // otherwise there will only be one option available. - const shouldHideSourcesFilter = getShouldHideSourcesFilter( category ); - - // The author filter is only shown while only user patterns are listed, as - // they're the only ones with an author on this site. - const shouldShowAuthorFilter = - currentPatternSourceFilter === INSERTER_PATTERN_TYPES.user; - - const patternSyncMenuOptions = useMemo( - () => [ - { - value: 'all', - label: _x( 'All', 'patterns' ), - }, - { - value: INSERTER_SYNC_TYPES.full, - label: _x( 'Synced', 'patterns' ), - disabled: shouldDisableSyncFilter, - }, - { - value: INSERTER_SYNC_TYPES.unsynced, - label: _x( 'Not synced', 'patterns' ), - disabled: shouldDisableSyncFilter, - }, - ], - [ shouldDisableSyncFilter ] - ); - - function handleSetSourceFilterChange( newSourceFilter: string ) { - setPatternSourceFilter( newSourceFilter ); - if ( getShouldDisableSyncFilter( newSourceFilter ) ) { - setPatternSyncFilter( 'all' ); - } - } - - return ( - <> - - - - } - /> - } - > - { () => ( - <> - { ! shouldHideSourcesFilter && ( - - { - handleSetSourceFilterChange( value ); - scrollContainerRef.current?.scrollTo( - 0, - 0 - ); - } } - value={ currentPatternSourceFilter } - /> - - ) } - { shouldShowAuthorFilter && ( - - { - setPatternAuthorFilter( value ); - scrollContainerRef.current?.scrollTo( - 0, - 0 - ); - } } - value={ patternAuthorFilter } - /> - - ) } - - { - setPatternSyncFilter( value ); - scrollContainerRef.current?.scrollTo( - 0, - 0 - ); - } } - value={ patternSyncFilter } - /> - -
- { createInterpolateElement( - __( - 'Patterns are available from the WordPress.org Pattern Directory, bundled in the active theme, or created by users on this site. Only patterns created on this site can be synced.' - ), - { - Link: ( - // @ts-expect-error `createInterpolateElement` fills in the children. - - ), - } - ) } -
- - ) } -
- - ); -} diff --git a/packages/block-editor/src/components/inserter/block-patterns-tab/patterns-grid.tsx b/packages/block-editor/src/components/inserter/block-patterns-tab/patterns-grid.tsx new file mode 100644 index 00000000000000..12bf96c28534a0 --- /dev/null +++ b/packages/block-editor/src/components/inserter/block-patterns-tab/patterns-grid.tsx @@ -0,0 +1,532 @@ +import type { ReactNode } from 'react'; +import { + useCallback, + useEffect, + useMemo, + useRef, + useState, +} from '@wordpress/element'; +import { __, _x, sprintf } from '@wordpress/i18n'; +import { cloneBlock } from '@wordpress/blocks'; +import type { Block } from '@wordpress/blocks'; +import { getScrollContainer } from '@wordpress/dom'; +import { DataViews } from '@wordpress/dataviews'; +import type { Field, View } from '@wordpress/dataviews'; +import { Stack } from '@wordpress/ui'; +import BlockPreview from '../../block-preview'; +import InserterDraggableBlocks from '../../inserter-draggable-blocks'; +import { searchItems } from '../../../utils/search-ranking'; +import usePatternsState from '../hooks/use-patterns-state'; +import MediaSearch from '../media-tab/media-search'; +import InserterNoResults from '../no-results'; +import { + allPatternsCategory, + getCategoriesBySource, + isPatternInCategory, + isPatternInSource, + INSERTER_PATTERN_TYPES, + INSERTER_SYNC_TYPES, + MY_PATTERNS_SOURCE, +} from './utils'; +import type { BlockPattern } from '../../../store/types'; +import type { InsertPattern, PatternCategory } from '../types'; + +type PatternsGridProps = { + /** + * The categories with patterns, "All" included. + */ + categories: PatternCategory[]; + /** + * The category to start on. The grid owns the selection afterwards and + * reports it through `onSelectCategory`. + */ + initialCategory?: PatternCategory | null; + onSelectCategory: ( category: PatternCategory | undefined ) => void; + onInsert: InsertPattern; + rootClientId?: string | null; + /** + * Rendered beneath the pager (the "Explore all patterns" button). + */ + footer?: ReactNode; +}; + +// The same page size as the paged list this grid replaces. +const PATTERNS_PER_PAGE = 20; + +// Wider than half the sidebar, so the grid has a single column of previews. +const GRID_LAYOUT = { previewSize: 230 } as const; +const DEFAULT_LAYOUTS = { grid: { layout: GRID_LAYOUT } }; + +// The categories are shown as tabs, so the menu leaves them out. A source is +// always selected, so its group in the menu has no "All" option. +const MENU_EXCLUDED_FIELDS = [ 'category' ]; +const MENU_REQUIRED_FIELDS = [ 'source' ]; + +// Where patterns come from, from the farthest from the person editing to the +// closest. The patterns that themes and plugins register are one source, +// whatever registered them, and the default one. The last option is not a +// place of its own: it is the part of the site's patterns that the current +// user made. +const getSourceOptions = () => [ + { + value: INSERTER_PATTERN_TYPES.directory, + label: __( 'Pattern Directory' ), + }, + { + value: INSERTER_PATTERN_TYPES.theme, + label: __( 'Theme & Plugins' ), + }, + { + value: INSERTER_PATTERN_TYPES.user, + label: __( 'Site patterns' ), + }, + { + value: MY_PATTERNS_SOURCE, + label: __( 'My patterns' ), + }, +]; + +// The sources whose patterns are made on the site, the only ones that can be +// synced. +const isSiteSource = ( source: string | undefined ) => + source === INSERTER_PATTERN_TYPES.user || source === MY_PATTERNS_SOURCE; + +const NO_CATEGORIES: PatternCategory[] = []; + +type Filters = NonNullable< View[ 'filters' ] >; + +const getFilterValue = ( filters: Filters | undefined, field: string ) => + filters?.find( ( filter ) => filter.field === field )?.value; + +/** + * With a category selected, the inserted blocks keep only that category in + * their metadata, as the list this grid replaces did: pattern shuffling reads + * it to stay within the category the pattern was picked from. + * + * @param blocks The blocks of the pattern. + * @param category The name of the selected category, or none for "All". + * @return The blocks to insert. + */ +function getBlocksForCategory( + blocks: Block[] | undefined, + category: string | undefined +) { + if ( ! category ) { + return blocks ?? []; + } + return ( blocks ?? [] ).map( ( block ) => { + const clonedBlock = cloneBlock( block ); + const metadata = clonedBlock.attributes.metadata as + { categories?: string[] } | undefined; + if ( metadata?.categories?.includes( category ) ) { + metadata.categories = [ category ]; + } + return clonedBlock; + } ); +} + +function PatternPreview( { + pattern, + category, +}: { + pattern: BlockPattern; + category?: string; +} ) { + const draggedBlocks = useMemo( + () => getBlocksForCategory( pattern.blocks, category ), + [ pattern.blocks, category ] + ); + + // The card's media area is the click-to-insert target (a DataViews click + // wrapper); the preview inside it is what gets dragged onto the canvas. + return ( + + { ( { draggable, onDragStart, onDragEnd } ) => ( +
+ + } + > + + +
+ ) } +
+ ); +} + +/** + * The Patterns tab body: one DataViews grid with the search and the settings + * menu above, the pattern categories as tabs, and a pager below. It is composed + * from the same DataViews sub-components as the Media tab, so the two tabs + * browse alike: a source is chosen in the menu, with one of them as the + * default, and the tabs are what that source holds. + * + * Everything shown is what is registered: the patterns and the categories that + * themes and plugins add reach the grid and the tabs with no further work. + */ +export default function PatternsGrid( { + categories, + initialCategory, + onSelectCategory, + onInsert, + rootClientId, + footer, +}: PatternsGridProps ) { + const panelRef = useRef< HTMLDivElement >( null ); + const [ search, setSearch ] = useState( '' ); + const [ page, setPage ] = useState( 1 ); + // What the menu and the tabs last asked for. What is shown is worked out + // below, since a selection can stop being available. + const [ selectedSource, setSelectedSource ] = useState< string >( + INSERTER_PATTERN_TYPES.theme + ); + const [ selectedCategory, setSelectedCategory ] = useState< + string | undefined + >( initialCategory?.name ); + const [ selectedType, setSelectedType ] = useState< string >(); + + const [ allPatterns, , onClickPattern ] = usePatternsState( + onInsert, + rootClientId + ); + + // The sources with patterns, and the categories each of them fills. A + // source without patterns isn't offered, and a category shows as a tab only + // under the sources that have patterns in it, so no choice leads to an + // empty list. + const { sources, categoriesBySource } = useMemo( () => { + const bySource = getCategoriesBySource( allPatterns, categories ); + return { + sources: getSourceOptions().filter( ( { value } ) => + bySource.has( value ) + ), + categoriesBySource: bySource, + }; + }, [ allPatterns, categories ] ); + + // The default source is "Theme & Plugins", or the first one with patterns. + const source: string | undefined = ( + sources.find( ( { value } ) => value === selectedSource ) ?? + sources[ 0 ] + )?.value; + const hasSources = sources.length > 1; + const tabCategories = + ( source && categoriesBySource.get( source ) ) || NO_CATEGORIES; + // Without a category, or with one the source doesn't have, the tab is + // "All". + const category = tabCategories.some( + ( { name } ) => name === selectedCategory + ) + ? selectedCategory + : undefined; + // Only the patterns made on this site can be synced. + const hasTypes = isSiteSource( source ); + const syncStatus = hasTypes ? selectedType : undefined; + + // The grid only shows what it is given: the filtering keeps the rules + // and the search ranking the inserter already had for patterns. + const patterns = useMemo( () => { + const inCategory = allPatterns.filter( + ( pattern: BlockPattern ) => + isPatternInSource( + pattern, + source ?? 'all', + syncStatus ?? 'all' + ) && isPatternInCategory( pattern, category, categories ) + ); + return search ? searchItems( inCategory, search ) : inCategory; + }, [ allPatterns, source, syncStatus, category, categories, search ] ); + + const totalPages = Math.max( + 1, + Math.ceil( patterns.length / PATTERNS_PER_PAGE ) + ); + const currentPage = Math.min( page, totalPages ); + const pagePatterns = useMemo( + () => + patterns.slice( + ( currentPage - 1 ) * PATTERNS_PER_PAGE, + currentPage * PATTERNS_PER_PAGE + ), + [ patterns, currentPage ] + ); + const paginationInfo = useMemo( + () => ( { totalItems: patterns.length, totalPages } ), + [ patterns.length, totalPages ] + ); + + const view: View = useMemo( + () => ( { + type: 'grid', + page: currentPage, + perPage: PATTERNS_PER_PAGE, + search, + filters: [ + ...( hasSources && source + ? [ + { + field: 'source', + operator: 'is' as const, + value: source, + }, + ] + : [] ), + ...( category + ? [ + { + field: 'category', + operator: 'isAny' as const, + value: [ category ], + }, + ] + : [] ), + ...( syncStatus + ? [ + { + field: 'syncStatus', + operator: 'is' as const, + value: syncStatus, + }, + ] + : [] ), + ], + fields: [], + titleField: 'title', + mediaField: 'preview', + showTitle: false, + showMedia: true, + layout: GRID_LAYOUT, + } ), + [ currentPage, search, hasSources, source, category, syncStatus ] + ); + + const fields: Field< BlockPattern >[] = useMemo( + () => [ + { + id: 'preview', + label: __( 'Preview' ), + type: 'media', + render: ( { item } ) => ( + + ), + enableSorting: false, + }, + { + // Hidden from the card but used as its accessible name. + id: 'title', + label: __( 'Title' ), + type: 'text', + getValue: ( { item } ) => item.title ?? item.name, + enableSorting: false, + enableGlobalSearch: false, + filterBy: false, + }, + // The source, category and type are modelled as filters so they + // live in the view, where the menu and the tabs read and change + // them. The filtering itself happens above. + { + id: 'source', + label: __( 'Source' ), + type: 'text', + getValue: ( { item } ) => item.source ?? '', + elements: hasSources ? sources : undefined, + filterBy: hasSources ? { operators: [ 'is' ] } : false, + enableSorting: false, + enableGlobalSearch: false, + }, + { + id: 'category', + label: __( 'Categories' ), + type: 'array', + getValue: ( { item } ) => item.categories ?? [], + elements: tabCategories.map( ( { name, label } ) => ( { + value: name, + label, + } ) ), + filterBy: { operators: [ 'isAny' ] }, + enableSorting: false, + enableGlobalSearch: false, + }, + { + id: 'syncStatus', + label: __( 'Type' ), + type: 'text', + getValue: ( { item } ) => item.syncStatus ?? '', + elements: hasTypes + ? [ + { + value: INSERTER_SYNC_TYPES.full, + label: _x( 'Synced', 'patterns' ), + }, + { + value: INSERTER_SYNC_TYPES.unsynced, + label: _x( 'Not synced', 'patterns' ), + }, + ] + : undefined, + filterBy: hasTypes ? { operators: [ 'is' ] } : false, + enableSorting: false, + enableGlobalSearch: false, + }, + ], + [ hasSources, sources, tabCategories, hasTypes, category ] + ); + + // Start from the top whenever the results change (another page, tab, + // filter or search), rather than wherever the previous ones were scrolled + // to. It runs once the new results are in place, so nothing they do while + // rendering moves the list again. The patterns scroll inside the panel, in + // whichever element around the grid does the scrolling. `scrollTo` is + // guarded because jsdom leaves it undefined. + useEffect( () => { + const grid = panelRef.current?.querySelector< HTMLElement >( + '.block-editor-inserter__media-grid' + ); + getScrollContainer( grid ?? panelRef.current )?.scrollTo?.( 0, 0 ); + }, [ currentPage, category, source, syncStatus, search ] ); + + const onChangeView = useCallback( + ( nextView: View ) => { + const nextSource: string | undefined = + getFilterValue( nextView.filters, 'source' ) ?? source; + // A category the next source doesn't have falls back to "All". + const requestedCategory: string | undefined = getFilterValue( + nextView.filters, + 'category' + )?.[ 0 ]; + const nextCategory = ( + ( nextSource && categoriesBySource.get( nextSource ) ) || + NO_CATEGORIES + ).some( ( { name } ) => name === requestedCategory ) + ? requestedCategory + : undefined; + + if ( nextSource ) { + setSelectedSource( nextSource ); + } + setSelectedCategory( nextCategory ); + setSelectedType( + isSiteSource( nextSource ) + ? getFilterValue( nextView.filters, 'syncStatus' ) + : undefined + ); + setPage( nextView.page ?? 1 ); + + if ( nextCategory !== category ) { + onSelectCategory( + categories.find( + ( { name } ) => + name === + ( nextCategory ?? allPatternsCategory.name ) + ) + ); + } + }, + [ source, category, categories, categoriesBySource, onSelectCategory ] + ); + + const onChangeSearch = useCallback( ( value: string ) => { + setSearch( value ); + setPage( 1 ); + }, [] ); + + const showPagination = totalPages > 1; + const hasFooter = showPagination || !! footer; + const firstItem = ( currentPage - 1 ) * PATTERNS_PER_PAGE + 1; + + return ( +
+ pattern.name } + onClickItem={ ( pattern ) => + onClickPattern( + pattern, + getBlocksForCategory( pattern.blocks, category ) + ) + } + empty={ } + > + + + + + + + + { hasFooter && ( + + { showPagination && ( + + + { sprintf( + /* translators: 1: The first item shown on the page. 2: The last item shown on the page. 3: The total number of items. */ + __( '%1$d–%2$d of %3$d' ), + firstItem, + Math.min( + currentPage * PATTERNS_PER_PAGE, + patterns.length + ), + patterns.length + ) } + + + + ) } + { footer } + + ) } + +
+ ); +} diff --git a/packages/block-editor/src/components/inserter/block-patterns-tab/test/utils.ts b/packages/block-editor/src/components/inserter/block-patterns-tab/test/utils.ts new file mode 100644 index 00000000000000..ab1acc885f6081 --- /dev/null +++ b/packages/block-editor/src/components/inserter/block-patterns-tab/test/utils.ts @@ -0,0 +1,238 @@ +import { describe, expect, it } from 'vitest'; +import { + allPatternsCategory, + getCategoriesBySource, + isPatternInSource, + sitePatternsCategory, + INSERTER_PATTERN_TYPES, + INSERTER_SYNC_TYPES, + MY_PATTERNS_SOURCE, +} from '../utils'; +import type { BlockPattern } from '../../../../store/types'; +import type { PatternCategory } from '../../types'; + +const pattern = ( props: Partial< BlockPattern > & { name: string } ) => + ( { content: '', ...props } ) as BlockPattern; + +// A theme, a plugin, the Pattern Directory and the site itself, each with a +// pattern of its own. +const themeHero = pattern( { + name: 'theme/hero', + source: 'theme', + categories: [ 'banner' ], +} ); +const pluginPricing = pattern( { + name: 'my-plugin/pricing', + source: 'plugin', + categories: [ 'my-plugin' ], +} ); +const directoryGallery = pattern( { + name: 'core/gallery', + source: 'pattern-directory/core', + categories: [ 'gallery' ], +} ); +const sitePattern = pattern( { + name: 'core/block/12', + type: INSERTER_PATTERN_TYPES.user, + source: 'user', + categories: [ 'banner' ], + syncStatus: 'unsynced', +} ); +// A pattern the current user made on the site, synced. +const myPattern = pattern( { + name: 'core/block/13', + type: INSERTER_PATTERN_TYPES.user, + source: 'user', + categories: [ 'gallery' ], + syncStatus: '', + isCurrentUserPattern: true, +} ); + +// What the inserter hands over: the categories with patterns, of any source. +const categories: PatternCategory[] = [ + allPatternsCategory, + sitePatternsCategory, + { name: 'banner', label: 'Banners' }, + { name: 'gallery', label: 'Gallery' }, + { name: 'my-plugin', label: 'My plugin' }, +]; + +const names = ( list: PatternCategory[] | undefined ) => + list?.map( ( { name } ) => name ); + +describe( 'getCategoriesBySource', () => { + it( 'lists each category under the sources that have patterns in it', () => { + const categoriesBySource = getCategoriesBySource( + [ themeHero, pluginPricing, directoryGallery, sitePattern ], + categories + ); + + expect( + names( categoriesBySource.get( INSERTER_PATTERN_TYPES.theme ) ) + ).toEqual( [ 'banner', 'my-plugin' ] ); + expect( + names( categoriesBySource.get( INSERTER_PATTERN_TYPES.directory ) ) + ).toEqual( [ 'gallery' ] ); + expect( + names( categoriesBySource.get( INSERTER_PATTERN_TYPES.user ) ) + ).toEqual( [ 'banner' ] ); + } ); + + it( 'offers the sources in a fixed order, from the farthest to the closest', () => { + const categoriesBySource = getCategoriesBySource( + [ myPattern, sitePattern, themeHero, directoryGallery ], + categories + ); + + expect( [ ...categoriesBySource.keys() ] ).toEqual( [ + INSERTER_PATTERN_TYPES.directory, + INSERTER_PATTERN_TYPES.theme, + INSERTER_PATTERN_TYPES.user, + MY_PATTERNS_SOURCE, + ] ); + } ); + + it( 'offers the patterns of the current user while they are some of the patterns of the site', () => { + const categoriesBySource = getCategoriesBySource( + [ sitePattern, myPattern ], + categories + ); + + expect( + names( categoriesBySource.get( INSERTER_PATTERN_TYPES.user ) ) + ).toEqual( [ 'banner', 'gallery' ] ); + expect( names( categoriesBySource.get( MY_PATTERNS_SOURCE ) ) ).toEqual( + [ 'gallery' ] + ); + } ); + + it( 'leaves out the patterns of the current user when they are all the patterns of the site', () => { + const categoriesBySource = getCategoriesBySource( + [ themeHero, myPattern ], + categories + ); + + expect( [ ...categoriesBySource.keys() ] ).toEqual( [ + INSERTER_PATTERN_TYPES.theme, + INSERTER_PATTERN_TYPES.user, + ] ); + } ); + + it( 'leaves out the patterns of the current user when there are none, or the user is not known', () => { + const categoriesBySource = getCategoriesBySource( + [ themeHero, sitePattern ], + categories + ); + + expect( [ ...categoriesBySource.keys() ] ).toEqual( [ + INSERTER_PATTERN_TYPES.theme, + INSERTER_PATTERN_TYPES.user, + ] ); + } ); + + it( 'leaves out a source without patterns', () => { + const categoriesBySource = getCategoriesBySource( + [ directoryGallery, sitePattern ], + categories + ); + + expect( [ ...categoriesBySource.keys() ] ).toEqual( [ + INSERTER_PATTERN_TYPES.directory, + INSERTER_PATTERN_TYPES.user, + ] ); + } ); + + it( 'keeps the category of a pattern that a plugin registers, under the theme and plugins source', () => { + const categoriesBySource = getCategoriesBySource( + [ pluginPricing ], + categories + ); + + expect( [ ...categoriesBySource.keys() ] ).toEqual( [ + INSERTER_PATTERN_TYPES.theme, + ] ); + expect( + names( categoriesBySource.get( INSERTER_PATTERN_TYPES.theme ) ) + ).toEqual( [ 'my-plugin' ] ); + } ); + + it( 'lists a pattern without a registered category under "Uncategorized"', () => { + const categoriesBySource = getCategoriesBySource( + [ + pattern( { name: 'theme/loose', source: 'theme' } ), + sitePattern, + ], + [ ...categories, { name: 'uncategorized', label: 'Uncategorized' } ] + ); + + expect( + names( categoriesBySource.get( INSERTER_PATTERN_TYPES.theme ) ) + ).toEqual( [ 'uncategorized' ] ); + expect( + names( categoriesBySource.get( INSERTER_PATTERN_TYPES.user ) ) + ).toEqual( [ 'banner' ] ); + } ); +} ); + +describe( 'isPatternInSource', () => { + it( 'keeps each pattern in the source it comes from', () => { + const inSource = ( source: string ) => + [ + themeHero, + pluginPricing, + directoryGallery, + sitePattern, + myPattern, + ] + .filter( ( item ) => isPatternInSource( item, source ) ) + .map( ( { name } ) => name ); + + expect( inSource( INSERTER_PATTERN_TYPES.directory ) ).toEqual( [ + 'core/gallery', + ] ); + expect( inSource( INSERTER_PATTERN_TYPES.theme ) ).toEqual( [ + 'theme/hero', + 'my-plugin/pricing', + ] ); + expect( inSource( INSERTER_PATTERN_TYPES.user ) ).toEqual( [ + 'core/block/12', + 'core/block/13', + ] ); + } ); + + it( 'keeps only the patterns the current user made', () => { + expect( isPatternInSource( myPattern, MY_PATTERNS_SOURCE ) ).toBe( + true + ); + expect( isPatternInSource( sitePattern, MY_PATTERNS_SOURCE ) ).toBe( + false + ); + expect( isPatternInSource( themeHero, MY_PATTERNS_SOURCE ) ).toBe( + false + ); + } ); + + it( 'narrows the patterns of the site down to the synced or the not synced ones', () => { + expect( + isPatternInSource( + myPattern, + MY_PATTERNS_SOURCE, + INSERTER_SYNC_TYPES.full + ) + ).toBe( true ); + expect( + isPatternInSource( + myPattern, + MY_PATTERNS_SOURCE, + INSERTER_SYNC_TYPES.unsynced + ) + ).toBe( false ); + expect( + isPatternInSource( + sitePattern, + INSERTER_PATTERN_TYPES.user, + INSERTER_SYNC_TYPES.unsynced + ) + ).toBe( true ); + } ); +} ); diff --git a/packages/block-editor/src/components/inserter/block-patterns-tab/utils.ts b/packages/block-editor/src/components/inserter/block-patterns-tab/utils.ts index d91dc9c9a239ce..9eee4cc03cb301 100644 --- a/packages/block-editor/src/components/inserter/block-patterns-tab/utils.ts +++ b/packages/block-editor/src/components/inserter/block-patterns-tab/utils.ts @@ -147,3 +147,128 @@ export function isPatternFiltered( return false; } + +/** + * Whether a pattern belongs to a category, including the ones that aren't + * registered categories: "All", the site's own patterns, starter content and + * the patterns left without a category. + * + * @param pattern The pattern to check. + * @param category The name of the category, or none for "All". + * @param categories The categories with patterns. + * @return Whether the pattern belongs to the category. + */ +export function isPatternInCategory( + pattern: BlockPattern, + category: string | undefined, + categories: PatternCategory[] +) { + if ( ! category || category === allPatternsCategory.name ) { + return true; + } + if ( category === sitePatternsCategory.name ) { + return pattern.type === INSERTER_PATTERN_TYPES.user; + } + if ( category === starterPatternsCategory.name ) { + return !! pattern.blockTypes?.includes( 'core/post-content' ); + } + if ( category === 'uncategorized' ) { + return ! pattern.categories?.some( ( name ) => + categories.some( ( { name: available } ) => available === name ) + ); + } + return !! pattern.categories?.includes( category ); +} + +/** + * The source for the patterns the current user made. Unlike the others it is + * not a place patterns come from, but a part of the site's own patterns. + */ +export const MY_PATTERNS_SOURCE = 'currentUser'; + +// The sources in the order they are offered: from the farthest from the person +// editing to the closest. +const PATTERN_SOURCES = [ + INSERTER_PATTERN_TYPES.directory, + INSERTER_PATTERN_TYPES.theme, + INSERTER_PATTERN_TYPES.user, + MY_PATTERNS_SOURCE, +]; + +/** + * Whether a pattern belongs to a source, and to the type selected within it. + * + * @param pattern The pattern to check. + * @param source The source, or anything else for all of them. + * @param syncFilter The type of pattern to keep, synced or not, if any. + * @return Whether the pattern belongs to the source. + */ +export function isPatternInSource( + pattern: BlockPattern, + source: string, + syncFilter?: string +) { + return source === MY_PATTERNS_SOURCE + ? ! isPatternFiltered( + pattern, + INSERTER_PATTERN_TYPES.user, + syncFilter, + INSERTER_AUTHOR_TYPES.currentUser + ) + : ! isPatternFiltered( pattern, source, syncFilter ); +} + +/** + * Returns the sources that have patterns, each with the categories it fills, + * in the order the sources are offered. + * + * A source without patterns is left out, and a category is listed only under + * the sources that have patterns in it, so that neither choice leads to an + * empty list. Whatever themes and plugins register lands here by itself: their + * patterns are the "theme" source, and their categories follow the patterns. + * The site's own patterns are the "user" source, so the category that stands + * for them isn't listed again. + * + * The current user's patterns are a source only while they are some of the + * site's patterns and not all of them. Otherwise the two sources would list + * the same, which is the case on every site with a single author. + * + * @param patterns The patterns that can be inserted. + * @param categories The categories with patterns, of any source. + * @return The categories of each source. + */ +export function getCategoriesBySource( + patterns: BlockPattern[], + categories: PatternCategory[] +): Map< string, PatternCategory[] > { + const categoriesBySource = new Map< string, PatternCategory[] >(); + const sitePatternCount = patterns.filter( ( pattern ) => + isPatternInSource( pattern, INSERTER_PATTERN_TYPES.user ) + ).length; + PATTERN_SOURCES.forEach( ( source ) => { + const sourcePatterns = patterns.filter( ( pattern ) => + isPatternInSource( pattern, source ) + ); + if ( ! sourcePatterns.length ) { + return; + } + if ( + source === MY_PATTERNS_SOURCE && + sourcePatterns.length === sitePatternCount + ) { + return; + } + categoriesBySource.set( + source, + categories.filter( + ( { name } ) => + name !== allPatternsCategory.name && + name !== sitePatternsCategory.name && + sourcePatterns.some( ( pattern ) => + isPatternInCategory( pattern, name, categories ) + ) + ) + ); + } ); + return categoriesBySource; +} diff --git a/packages/block-editor/src/components/inserter/media-tab/media-grid.tsx b/packages/block-editor/src/components/inserter/media-tab/media-grid.tsx index 0d7ffafb1dd182..83d76f7c24bd16 100644 --- a/packages/block-editor/src/components/inserter/media-tab/media-grid.tsx +++ b/packages/block-editor/src/components/inserter/media-tab/media-grid.tsx @@ -4,11 +4,11 @@ import { __, sprintf } from '@wordpress/i18n'; import { DataViews } from '@wordpress/dataviews'; import type { Action, Field, View } from '@wordpress/dataviews'; import { Spinner as WCSpinner } from '@wordpress/components'; -import { Stack, Tabs } from '@wordpress/ui'; +import { Stack } from '@wordpress/ui'; import InserterDraggableBlocks from '../../inserter-draggable-blocks'; import MediaSearch from './media-search'; import { getBlockAndPreviewFromMedia, getItemId } from './utils'; -import type { MediaItem, MediaType } from './types'; +import type { MediaItem, MediaSource, MediaType } from './types'; type MediaGridProps = { // Results. @@ -25,10 +25,15 @@ type MediaGridProps = { search: string; onChangeSearch: ( search: string ) => void; searchLabel: string; + + // Source, chosen in the menu beside the search input. /** - * Rendered beside the search input (the source menu). + * Fewer than two offers no choice, since there is nothing to switch + * between. */ - sourceMenu?: ReactNode; + sources?: MediaSource[]; + source?: string; + onChangeSource?: ( source: string ) => void; // Media-type tabs. /** @@ -79,6 +84,11 @@ const GRID_LAYOUT = { } as const; const DEFAULT_LAYOUTS = { grid: { layout: GRID_LAYOUT } }; +// The media type is shown as tabs, so the menu leaves it out. A source is +// always selected, so its group in the menu has no "All" option. +const MENU_EXCLUDED_FIELDS = [ 'mediaType' ]; +const MENU_REQUIRED_FIELDS = [ 'source' ]; + const getTitle = ( item: MediaItem ) => typeof item.title === 'string' ? item.title @@ -163,7 +173,9 @@ export default function MediaGrid( { search, onChangeSearch, searchLabel, - sourceMenu, + sources, + source, + onChangeSource, mediaTypes, mediaType, onChangeMediaType, @@ -176,6 +188,9 @@ export default function MediaGrid( { onChangePage, footer, }: MediaGridProps ) { + const hasTabs = !! mediaTypes && mediaTypes.length > 1; + const hasSources = !! sources && sources.length > 1 && !! source; + const fields: Field< MediaItem >[] = useMemo( () => [ { @@ -198,9 +213,47 @@ export default function MediaGrid( { getValue: ( { item } ) => getTitle( item ), enableSorting: false, enableGlobalSearch: false, + filterBy: false, + }, + // The source and the media type decide what the panel fetches, + // rather than narrowing down what is already on screen. They are + // modelled as filters so they live in the view, where the menu + // and the tabs read and change them. + { + id: 'source', + label: __( 'Source' ), + type: 'text', + getValue: () => source, + elements: hasSources + ? sources.map( ( { name, label } ) => ( { + value: name, + label, + } ) ) + : undefined, + filterBy: hasSources ? { operators: [ 'is' ] } : false, + enableSorting: false, + enableGlobalSearch: false, + }, + { + id: 'mediaType', + label: __( 'Media type' ), + type: 'text', + getValue: () => mediaType, + elements: hasTabs ? mediaTypes : undefined, + filterBy: hasTabs ? { operators: [ 'is' ] } : false, + enableSorting: false, + enableGlobalSearch: false, }, ], - [ mediaType, insertingId ] + [ + mediaType, + insertingId, + hasSources, + sources, + source, + hasTabs, + mediaTypes, + ] ); const view: View = useMemo( @@ -215,21 +268,59 @@ export default function MediaGrid( { showTitle: false, showMedia: true, layout: GRID_LAYOUT, + filters: [ + ...( hasSources + ? [ + { + field: 'source', + operator: 'is' as const, + value: source, + }, + ] + : [] ), + ...( hasTabs + ? [ + { + field: 'mediaType', + operator: 'is' as const, + value: mediaType, + }, + ] + : [] ), + ], } ), - [ page, perPage, search ] + [ page, perPage, search, hasSources, source, hasTabs, mediaType ] ); - // The panel owns the page, so changes are forwarded to it rather than - // stored here. Search comes in through `MediaSearch`, not the view, so - // paging is the only thing `DataViews` changes. + // The tab and the panel own the source, the media type and the page, so + // changes are forwarded to them rather than stored here. Search comes in + // through `MediaSearch`, not the view. const onChangeView = useCallback( ( nextView: View ) => { + const getFilterValue = ( field: string ) => + nextView.filters?.find( ( filter ) => filter.field === field ) + ?.value; + const nextSource = getFilterValue( 'source' ); + if ( nextSource !== undefined && nextSource !== source ) { + onChangeSource?.( nextSource ); + } + const nextMediaType = getFilterValue( 'mediaType' ); + if ( nextMediaType !== undefined && nextMediaType !== mediaType ) { + onChangeMediaType?.( nextMediaType ); + } const nextPage = nextView.page ?? 1; if ( nextPage !== page ) { onChangePage( nextPage ); } }, - [ page, onChangePage ] + [ + source, + onChangeSource, + mediaType, + onChangeMediaType, + page, + onChangePage, + ] ); const paginationInfo = useMemo( @@ -240,7 +331,6 @@ export default function MediaGrid( { [ totalItems, totalPages ] ); const showPagination = paginationInfo.totalPages > 1; - const hasTabs = !! mediaTypes && mediaTypes.length > 1; const hasFooter = showPagination || !! footer; const itemRange = getItemRange( { page, @@ -273,37 +363,16 @@ export default function MediaGrid( { defaultValue={ search } onChange={ onChangeSearch } /> - { sourceMenu } + - { hasTabs ? ( - -
- - { mediaTypes.map( ( type ) => ( - - { type.label } - - ) ) } - -
- { /* One panel per tab, as `Tabs` requires the counts to match. - Only the selected one mounts, so a single grid renders. */ } - { mediaTypes.map( ( type ) => ( - - - - ) ) } -
- ) : ( + { /* Without media types to switch between, this is the grid alone. */ } + - ) } + { hasFooter && ( ( null ); @@ -181,7 +183,9 @@ export function MediaCategoryPanel( { { emptyMessage } ) } - sourceMenu={ sourceMenu } + sources={ sources } + source={ source } + onChangeSource={ onChangeSource } mediaTypes={ mediaTypes } mediaType={ mediaType } onChangeMediaType={ onChangeMediaType } diff --git a/packages/block-editor/src/components/inserter/media-tab/media-tab.tsx b/packages/block-editor/src/components/inserter/media-tab/media-tab.tsx index 24907c5319e343..9a593220406a32 100644 --- a/packages/block-editor/src/components/inserter/media-tab/media-tab.tsx +++ b/packages/block-editor/src/components/inserter/media-tab/media-tab.tsx @@ -5,7 +5,6 @@ import { useMediaCategories } from './hooks'; import { getBlockAndPreviewFromMedia } from './utils'; import { MediaCategoryPanel } from './media-panel'; import MediaLibraryButton from './media-library-button'; -import SourceMenu from './source-menu'; import InserterNoResults from '../no-results'; import type { MediaCategory, MediaType } from './types'; @@ -13,9 +12,10 @@ const ALLOWED_MEDIA_TYPES = [ 'image', 'video', 'audio' ]; // The categories that together make up the media library: one per media type, // shown as tabs rather than as separate sources. Everything else a category -// can be — the post's attached images, Openverse, anything registered through -// the public API — is a source of its own. So a source is not a category: this -// set collapses into the one "Media library" source. +// can be — the post's attached images, Openverse, anything a plugin registers +// with `registerInserterMediaCategory` — is a source of its own, listed in the +// menu in the order it was registered and however many there are. So a source +// is not a category: this set collapses into the one "Media library" source. // TODO: `InserterMediaCategory` has no notion of grouping, so this matches by // name. A `group` property on the registration API would do this properly. const LIBRARY_CATEGORIES = [ 'images', 'videos', 'audio' ]; @@ -24,8 +24,8 @@ const LIBRARY_SOURCE = 'media-library'; const DEFAULT_MEDIA_TYPE: MediaType = 'image'; /** - * The inserter's Media tab: one search, a source menu, and a tab per media - * type when browsing the library. The selection resolves to a single + * The inserter's Media tab: one search, a menu to choose the source, and a tab + * per media type when browsing the library. The selection resolves to a single * registered category, which the panel below fetches and renders. */ function MediaTab( { @@ -120,12 +120,16 @@ function MediaTab( { sources[ 0 ]; const isLibrary = activeSource?.name === LIBRARY_SOURCE; - const mediaTypes = isLibrary - ? libraryCategories.map( ( category ) => ( { - value: category.mediaType, - label: category.label, - } ) ) - : []; + const mediaTypes = useMemo( + () => + isLibrary + ? libraryCategories.map( ( category ) => ( { + value: category.mediaType, + label: category.label, + } ) ) + : [], + [ isLibrary, libraryCategories ] + ); const category = isLibrary ? ( libraryCategories.find( @@ -150,15 +154,9 @@ function MediaTab( { mediaTypes={ mediaTypes } mediaType={ category.mediaType } onChangeMediaType={ setMediaType } - sourceMenu={ - sources.length > 1 ? ( - - ) : undefined - } + sources={ sources } + source={ activeSource.name } + onChangeSource={ setSourceName } footer={ void; -} ) { - return ( - - - } - /> - - onChange( next ) } - > - { sources.map( ( source ) => ( - - { source.label } - - ) ) } - - - - ); -} diff --git a/packages/block-editor/src/components/inserter/media-tab/types.ts b/packages/block-editor/src/components/inserter/media-tab/types.ts index 25ea1e41c40144..06be3960c16e0d 100644 --- a/packages/block-editor/src/components/inserter/media-tab/types.ts +++ b/packages/block-editor/src/components/inserter/media-tab/types.ts @@ -34,6 +34,15 @@ export type MediaItem = { date?: string; }; +/** + * Where the tab's media comes from: the media library, the post's attached + * images, or any other registered category such as Openverse. + */ +export type MediaSource = { + name: string; + label: string; +}; + export interface MediaCategoryPanelProps { onInsert: ( block: import( '@wordpress/blocks' ).Block ) => void; category: MediaCategory; @@ -43,8 +52,11 @@ export interface MediaCategoryPanelProps { mediaTypes?: { value: MediaType; label: string }[]; mediaType: MediaType; onChangeMediaType?: ( mediaType: MediaType ) => void; - /** Rendered beside the search input. */ - sourceMenu?: import( 'react' ).ReactNode; + /** Fewer than two offers no choice of source. */ + sources?: MediaSource[]; + /** The name of the source being browsed. */ + source?: string; + onChangeSource?: ( source: string ) => void; /** Rendered beneath the pager. */ footer?: import( 'react' ).ReactNode; } diff --git a/packages/block-editor/src/components/inserter/menu.tsx b/packages/block-editor/src/components/inserter/menu.tsx index 90436ff8ab53b5..211a12aec822b3 100644 --- a/packages/block-editor/src/components/inserter/menu.tsx +++ b/packages/block-editor/src/components/inserter/menu.tsx @@ -19,7 +19,6 @@ import Tips from './tips'; import InserterPreviewPanel from './preview-panel'; import BlockTypesTab from './block-types-tab'; import BlockPatternsTab from './block-patterns-tab'; -import { PatternCategoryPreviews } from './block-patterns-tab/pattern-category-previews'; import { MediaTab } from './media-tab'; import InserterSearchResults from './search-results'; import useInsertionPoint from './hooks/use-insertion-point'; @@ -89,9 +88,6 @@ function InserterMenu( const [ selectedPatternCategory, setSelectedPatternCategory ] = useState< PatternCategory | null | undefined >( __experimentalInitialCategory ); - const [ patternFilter, setPatternFilter ] = useState< string | undefined >( - 'all' - ); const isLargeViewport = useViewportMatch( 'large' ); const isMobileViewport = useViewportMatch( 'medium', '<' ); const maybeCloseInserter = isMobileViewport ? onClose : NOOP; @@ -201,19 +197,13 @@ function InserterMenu( ); const onClickPatternCategory = useCallback( - ( patternCategory: PatternCategory | undefined, filter?: string ) => { + ( patternCategory: PatternCategory | undefined ) => { setSelectedPatternCategory( patternCategory ); - setPatternFilter( filter ); onPatternCategorySelection?.(); }, [ setSelectedPatternCategory, onPatternCategorySelection ] ); - const showPatternPanel = - selectedTab === 'patterns' && - ! delayedFilterValue && - !! selectedPatternCategory; - const [ isScrolled, setIsScrolled ] = useState( false ); const blocksPanelRef = useRef< HTMLDivElement >( null ); const patternsPanelRef = useRef< HTMLDivElement >( null ); @@ -243,7 +233,8 @@ function InserterMenu( }, [] ); const inserterSearch = useMemo( () => { - if ( selectedTab === 'media' ) { + // The Patterns and Media tabs have a search of their own. + if ( selectedTab === 'media' || selectedTab === 'patterns' ) { return null; } @@ -335,27 +326,13 @@ function InserterMenu( onInsert={ onInsertPattern } onSelectCategory={ onClickPatternCategory } selectedCategory={ selectedPatternCategory } - > - { showPatternPanel && ( - - ) } - + /> ); }, [ destinationRootClientId, onInsertPattern, onClickPatternCategory, - patternFilter, selectedPatternCategory, - showPatternPanel, ] ); const mediaTab = useMemo( () => { @@ -406,7 +383,6 @@ function InserterMenu( return (
- { inserterSearch } { selectedTab === 'patterns' && - ! delayedFilterValue && patternsTab } ), diff --git a/packages/block-editor/src/components/inserter/style.scss b/packages/block-editor/src/components/inserter/style.scss index b68f3e81cf0e33..a6e57406a01f47 100644 --- a/packages/block-editor/src/components/inserter/style.scss +++ b/packages/block-editor/src/components/inserter/style.scss @@ -476,7 +476,7 @@ $media-grid-loading-min-height: 500px; // A tab bar below supplies its own separation, so the field sits // closer to it than it would to the grid. - &:has(+ .block-editor-inserter__media-grid__tabs) { + &:has(+ .dataviews-filter-tabs) { padding-bottom: 0; } @@ -487,28 +487,11 @@ $media-grid-loading-min-height: 500px; } } - .block-editor-inserter__media-grid__tabs { - display: flex; - flex-direction: column; - flex: 1; - min-height: 0; - } - - // `Tabs.List` is only as wide as its tabs, so this wrapper carries the - // column gutter and the space beneath. - .block-editor-inserter__media-grid__tablist { - flex-shrink: 0; + // The media-type tabs take the sidebar's gutter, like the search field + // above and the grid below, rather than the wider one DataViews uses on + // full pages. + .dataviews-filter-tabs__list { padding: 0 $grid-unit-20; - margin-bottom: $grid-unit-15; - } - - // The selected tab panel is the grid, so it carries the same fill as - // the untabbed layout would. - .block-editor-inserter__media-grid__tabs [role="tabpanel"] { - display: flex; - flex-direction: column; - flex: 1; - min-height: 0; } .dataviews-view-grid { @@ -613,6 +596,36 @@ $media-grid-loading-min-height: 500px; // The "Detach" action's confirmation, rendered inside the DataViews action // modal. +// The Patterns tab shares the panel styles of the Media tab above, so the two +// tabs browse alike. What follows is only what differs for patterns. +.block-editor-inserter__patterns-panel { + // A page of patterns is taller than the sidebar, unlike a page of media. + // The panel takes the height of the tab and the patterns scroll inside + // it, so the search, the tabs and the footer stay in place. + flex: 1 1 0; + + // Pattern previews keep their own height: boxing them into one shape, as + // the grid does for media, would crop or shrink what they show. + .dataviews-view-grid .dataviews-view-grid__media { + aspect-ratio: auto; + } + + .block-editor-inserter__patterns-grid__preview { + width: 100%; + } + + // Holds the place of a preview until it renders. + .block-editor-inserter__patterns-grid__placeholder { + min-height: $grid-unit-80 + $grid-unit-40; + background-color: $gray-100; + } + + // The footer already spaces the button from the pager. + .block-editor-inserter__patterns-explore-button.components-button { + margin-top: 0; + } +} + .block-editor-inserter__media-panel-detach-actions { display: flex; justify-content: flex-end; diff --git a/packages/block-editor/src/components/inserter/types.ts b/packages/block-editor/src/components/inserter/types.ts index 9ded0935102d5e..95bc1aa75aad5e 100644 --- a/packages/block-editor/src/components/inserter/types.ts +++ b/packages/block-editor/src/components/inserter/types.ts @@ -155,26 +155,6 @@ export interface BlockPatternsTabProps { selectedCategory?: PatternCategory | null; onInsert: InsertPattern; rootClientId?: string | null; - children?: ReactNode; -} - -export interface PatternCategoryPreviewsProps { - rootClientId?: string | null; - onInsert: InsertPattern; - onHover?: ( pattern: BlockPattern | null ) => void; - category: PatternCategory; - showTitlesAsTooltip?: boolean; -} - -export interface PatternsFilterProps { - setPatternSyncFilter: ( value: string ) => void; - setPatternSourceFilter: ( value: string ) => void; - setPatternAuthorFilter: ( value: string ) => void; - patternSyncFilter: string; - patternSourceFilter: string; - patternAuthorFilter: string; - scrollContainerRef: PatternsScrollContainerRef; - category: PatternCategory; } export interface PatternsExplorerProps { diff --git a/packages/dataviews/CHANGELOG.md b/packages/dataviews/CHANGELOG.md index 99b2119b98ec49..2439368247c8fd 100644 --- a/packages/dataviews/CHANGELOG.md +++ b/packages/dataviews/CHANGELOG.md @@ -4,6 +4,7 @@ ### Enhancements +- Add a `narrow` option to the `grid` and `pickerGrid` layouts: an alternative to the default UI for narrow containers such as a sidebar, with a single settings button in place of the filters and the view options buttons. Its two parts are also available through free composition: `DataViews.ViewMenu`, a settings menu with the filters that work as menu items and sorting, and `DataViews.FilterTabs`, one filter shown as minimal tabs ([#87393](https://github.com/WordPress/gutenberg/pull/87393)). - Fade the edges of a table layout, including the lines between rows, into each row's background while there are more columns to scroll to on that side, including tables without actions. The divider before the sticky actions column is now shown with CSS, and the `dataviews-view-table__actions-column--stuck` and `dataviews-view-table__actions-column--sticky` classes are removed: target `dataviews-view-table__actions-column` instead ([#86829](https://github.com/WordPress/gutenberg/pull/86829)). - Name the selection checkboxes "Select [title]" instead of the item title alone ([#87220](https://github.com/WordPress/gutenberg/pull/87220)). diff --git a/packages/dataviews/README.md b/packages/dataviews/README.md index 988980c8295b6c..a9b31ca0051761 100644 --- a/packages/dataviews/README.md +++ b/packages/dataviews/README.md @@ -259,6 +259,7 @@ Properties: | `previewSize` | | | ✓ | ✓ | | | | `aspectRatio` | ✓ | | ✓ | | | | | `mediaFit` | | | ✓ | ✓ | | | +| `narrow` | | | ✓ | ✓ | | | `table` and `pickerTable` layouts: @@ -277,6 +278,7 @@ Right-align (`'end'`) whenever the cell value is fundamentally quantitative—nu - `previewSize`: a `number` representing the size of the preview. - `aspectRatio` (`grid` only): one of the preset ratios `'1/1'`, `'4/3'`, `'3/4'`, `'3/2'`, `'2/3'`, `'16/9'`, or `'9/16'`, applied uniformly to every item preview, keeping rows aligned. Defaults to `'1/1'`. - `mediaFit`: how the media field fills the preview box, either `'cover'` (crop it to fill) or `'contain'` (fit the whole media inside, letterboxing it so its own aspect ratio stays visible). The box keeps the shape set by `aspectRatio` either way, so rows stay aligned, and takes a neutral background under `'contain'` so a letterboxed preview still reads as a single item. Defaults to `'cover'`. To let users switch this themselves, pass `config={ { mediaFitControl: true } }` to `DataViews` or `DataViewsPicker`, which adds an "Original aspect ratio" toggle to the view options. +- `narrow`: `true`, or `{ tabsField?: string, showSort?: boolean }`. Renders the UI for narrow containers in place of the default UI, with a single settings button in place of the filters and the view options buttons. See [Narrow UI](#narrow-ui). `list` layout: @@ -563,6 +565,8 @@ The following components are available directly under `DataViews`: - `DataViews.Pagination` - `DataViews.BulkActionToolbar` (deprecated) - `DataViews.ViewConfig` +- `DataViews.ViewMenu` +- `DataViews.FilterTabs` Bulk actions are now rendered within the built-in table and grid layouts ([#82730](https://github.com/WordPress/gutenberg/pull/82730)). `DataViews.BulkActionToolbar` remains available for compatibility but renders nothing, so you can remove it from custom compositions. @@ -597,6 +601,69 @@ const CustomLayout = () => { > You can render only the pieces you need, rearrange them freely, or combine them with custom components. +### Narrow UI + +The grid layout has a `narrow` option: an alternative to the default UI for narrow, single-purpose containers, such as a sidebar. DataViews takes the same `data`, `fields` and `view`, and renders them in an opinionated layout with a single settings button in place of the filters and the view options buttons. `header` is not rendered. + +Its rows, from top to bottom: + +1. Search and the settings button. +2. Optionally, one field as tabs: the main way to browse the content, such as a category or a type. +3. The grid. +4. The footer, with the pagination. + +It is set in the `layout` of the view, by the consumer: + +```jsx +const view = { + type: 'grid', + layout: { narrow: { tabsField: 'type' } }, + // ... +}; +``` + +`narrow` is `true`, or an object to adjust it: + +- `tabsField`: the id of a field to show as tabs above the content. That field is left out of the settings menu. +- `showSort`: whether the settings menu offers sorting. Defaults to `true`. + +The `pickerGrid` layout of `DataViewsPicker` has the same option. There, the footer keeps the selection, the pagination and the actions, with the actions on a line of their own. + +The option is ignored in free composition. The narrow UI is made of two subcomponents, which are also available there, for a container that needs its own search, footer or spacing. + +#### `DataViews.ViewMenu` + +A single settings button that opens a menu built from the fields and the view. It renders nothing when the menu would be empty. The menu holds: + +- **Filters.** Each filter that is set by picking among a fixed list of options, shown as the field defines it: radio items with an "All" item when it takes one value (the `is` operator), or checkboxes when it takes several (`isAny`). The length of the list doesn't count, so a list that plugins add to never drops out of the menu. A filter is left out when it needs another kind of control (a date, a number, free text), loads its options with `getElements`, or is locked. +- **Sort.** The field to sort by and the order, when `showSort` is set. It lists the fields with sorting enabled, as the view options do. +- **Extra items.** The `children`, such as a link to a help page. + +When the groups hold more than 10 options in all, each group moves to a submenu. A long list scrolls, and a group on its own stays in the menu, where a submenu would only add a step. + +The menu has no "Reset view" item. `onReset` is meant for saved views and comes with the "modified" indicator of the view options button, which the settings button doesn't have. A consumer that needs one can add it through `children`. + +Properties: + +- `excludeFields`: `string[]`. Ids of fields to leave out of the menu, such as the one shown with `DataViews.FilterTabs`. +- `requiredFields`: `string[]`. Ids of single-choice fields that always filter by one value. Their group has no "All" item, and the view is expected to start with a filter for each of them. +- `showSort`: `boolean`. Whether the menu offers sorting. Defaults to `false`. +- `size`: `'compact' | 'default'`. The size of the settings button: `compact` to sit next to `DataViews.Search`, or `default` to sit next to a 40px control. Defaults to `compact`. +- `children`: React node. Extra menu items, rendered at the end of the menu. + +#### `DataViews.FilterTabs` + +Shows one filter as a row of minimal tabs, which scrolls sideways when the tabs don't fit. Choosing a tab filters the view by that option and goes back to the first page; the "All" tab removes the filter. The field needs a fixed list of `elements` and to support the `is` operator, or `isAny` when its value is a list. + +It renders the content inside its tab panel, so don't render `DataViews.Layout` next to it. + +Properties: + +- `field`: `string`. The id of the field to show as tabs. +- `allLabel`: `string`. The label of the tab that shows every item. Defaults to "All". +- `showAll`: `boolean`. Whether to add the "All" tab. Defaults to `true`. Without it, the view is expected to always filter by the field. +- `children`: React node. The content the tabs switch. Defaults to ``. + ### Accessibility considerations All `DataViews` subcomponents are designed with accessibility in mind — including keyboard interactions, focus management, and semantic roles. Components like `Search`, `Pagination`, `FiltersToggle`, and `FiltersToggled` already handle these responsibilities internally and can be safely used in custom layouts. diff --git a/packages/dataviews/src/components/dataviews-filter-tabs/index.tsx b/packages/dataviews/src/components/dataviews-filter-tabs/index.tsx new file mode 100644 index 00000000000000..cd3e73f18b5437 --- /dev/null +++ b/packages/dataviews/src/components/dataviews-filter-tabs/index.tsx @@ -0,0 +1,154 @@ +import type { ReactNode } from 'react'; +import { __ } from '@wordpress/i18n'; +import { useContext } from '@wordpress/element'; +import { Tabs } from '@wordpress/ui'; +import { OPERATOR_IS } from '../../constants'; +import getSelectionOperator from '../../utils/get-selection-operator'; +import setFieldFilter from '../../utils/set-field-filter'; +import DataViewsContext from '../dataviews-context'; +import DataViewsLayout from '../dataviews-layout'; +import { getActiveOption } from './utils'; + +const ALL = 'all'; +const getTabValue = ( index: number ) => `option-${ index }`; + +export interface FilterTabsProps { + /** + * The id of the field to show as tabs. The field needs a fixed list of + * options (`elements`) and to be filterable by `is` or `isAny`. + */ + field: string; + + /** + * The label of the tab that shows every item. + * + * @default "All" + */ + allLabel?: string; + + /** + * Whether to add a first tab that shows every item, by removing the + * field's filter. Without it, the view is expected to always filter by + * the field. + * + * @default true + */ + showAll?: boolean; + + /** + * The content the tabs switch. Defaults to ``. + */ + children?: ReactNode; +} + +/** + * Shows one filter as a row of minimal tabs above the content: the main way to + * browse it, such as a category or a type. Choosing a tab filters the view by + * that option; the "All" tab removes the filter. + * + * It renders the layout itself, inside the tab panel, so don't also render + * `` next to it. + */ +export default function DataViewsFilterTabs( { + field, + allLabel, + showAll = true, + children, +}: FilterTabsProps ) { + const { view, onChangeView, filters, data } = + useContext( DataViewsContext ); + const content = children ?? ; + const filter = filters.find( ( { field: id } ) => id === field ); + const operator = filter ? getSelectionOperator( filter ) : undefined; + const elements = filter?.elements ?? []; + const tabs = [ + ...( showAll + ? [ { value: ALL, label: allLabel ?? __( 'All' ) } ] + : [] ), + ...elements.map( ( element, index ) => ( { + value: getTabValue( index ), + label: element.label, + } ) ), + ]; + + // Without a filter the user can change, or with nothing to switch + // between, there is no tab bar. + if ( ! filter || ! operator || filter.isLocked || tabs.length < 2 ) { + return <>{ content }; + } + + const activeOption = getActiveOption( view, field, elements ); + let activeValue: string | null = null; + if ( activeOption === 'all' ) { + activeValue = showAll ? ALL : null; + } else if ( activeOption !== null ) { + activeValue = getTabValue( activeOption ); + } + + return ( + { + // Only follow the user's choice, not the automatic fallbacks + // `Tabs` makes when the selected tab goes away. + if ( eventDetails.reason !== 'none' ) { + return; + } + const index = elements.findIndex( + ( _element, i ) => getTabValue( i ) === nextValue + ); + if ( index === -1 ) { + onChangeView( setFieldFilter( view, field ) ); + return; + } + const { value } = elements[ index ]; + onChangeView( + setFieldFilter( view, field, { + operator, + value: operator === OPERATOR_IS ? value : [ value ], + } ) + ); + } } + > +
+ + { tabs.map( ( tab ) => ( + + { tab.label } + + ) ) } + +
+ { /* + * One panel holds the content and follows the selected tab, so + * the layout stays mounted when the tab changes. `Tabs` asks for + * one panel per tab, so the other tabs get an empty panel, which + * renders nothing while its tab isn't selected. + */ } + { activeValue !== null && ( + 0 ? -1 : undefined } + > + { content } + + ) } + { tabs + .filter( ( tab ) => tab.value !== activeValue ) + .map( ( tab ) => ( + + ) ) } + { /* No tab matches the current filter: show the content as is. */ } + { activeValue === null && content } +
+ ); +} diff --git a/packages/dataviews/src/components/dataviews-filter-tabs/style.scss b/packages/dataviews/src/components/dataviews-filter-tabs/style.scss new file mode 100644 index 00000000000000..4e8e759f66883a --- /dev/null +++ b/packages/dataviews/src/components/dataviews-filter-tabs/style.scss @@ -0,0 +1,27 @@ +// The tabs and the content they switch fill the room the layout would take. +.dataviews-filter-tabs, +.dataviews-filter-tabs__panel { + display: flex; + flex-direction: column; + flex: 1; + min-height: 0; + background-color: inherit; +} + +.dataviews-filter-tabs { + gap: var(--wpds-dimension-gap-lg); +} + +// `Tabs.List` is only as wide as its tabs, so this wrapper carries the gutter +// and the line the tabs sit on. +.dataviews-filter-tabs__list { + box-sizing: border-box; + flex-shrink: 0; + padding: 0 var(--wpds-dimension-padding-2xl); + border-bottom: var(--wpds-border-width-xs) solid var(--wpds-color-stroke-surface-neutral-weak); +} + +// Kept within the panel, so the tabs scroll sideways when they don't fit. +.dataviews-filter-tabs__tablist { + max-width: 100%; +} diff --git a/packages/dataviews/src/components/dataviews-filter-tabs/test/index.jsdom.test.tsx b/packages/dataviews/src/components/dataviews-filter-tabs/test/index.jsdom.test.tsx new file mode 100644 index 00000000000000..f14c3c8efb9ed6 --- /dev/null +++ b/packages/dataviews/src/components/dataviews-filter-tabs/test/index.jsdom.test.tsx @@ -0,0 +1,169 @@ +import { render, screen } from '@testing-library/react'; +import userEvent from '@testing-library/user-event'; +import { describe, expect, it, vi } from 'vitest'; +import DataViews from '../../../dataviews'; +import type { Field, View } from '../../../types'; + +globalThis.wpVitest.mockMatchMedia(); +globalThis.wpVitest.mockPointerEvent(); +globalThis.wpVitest.mockCSSSupports(); +// `Tabs.List` watches its size to know when the tabs overflow. +globalThis.wpVitest.mockResizeObserver(); + +type Item = { + id: number; + title: string; + mediaType: string; + categories: string[]; +}; + +const data: Item[] = [ + { id: 1, title: 'Sunset', mediaType: 'image', categories: [ 'banners' ] }, + { + id: 2, + title: 'Interview', + mediaType: 'video', + categories: [ 'about', 'banners' ], + }, +]; + +const fields: Field< Item >[] = [ + { id: 'title', label: 'Title', type: 'text', filterBy: false }, + { + id: 'mediaType', + label: 'Media type', + type: 'text', + elements: [ + { value: 'image', label: 'Images' }, + { value: 'video', label: 'Videos' }, + ], + filterBy: { operators: [ 'is' ] }, + }, + { + id: 'category', + label: 'Category', + type: 'array', + getValue: ( { item } ) => item.categories, + elements: [ + { value: 'about', label: 'About' }, + { value: 'banners', label: 'Banners' }, + ], + filterBy: { operators: [ 'isAny' ] }, + }, +]; + +const DEFAULT_VIEW: View = { + type: 'list', + page: 3, + perPage: 10, + titleField: 'title', + filters: [], +}; + +function renderFilterTabs( + props: { field: string; showAll?: boolean }, + view: View = DEFAULT_VIEW +) { + const onChangeView = vi.fn(); + render( + item.id.toString() } + > + + + ); + return { onChangeView }; +} + +describe( 'DataViews.FilterTabs', () => { + it( 'filters the view by the chosen tab and goes back to the first page', async () => { + const user = userEvent.setup(); + const { onChangeView } = renderFilterTabs( { field: 'mediaType' } ); + + await user.click( screen.getByRole( 'tab', { name: 'Videos' } ) ); + + expect( onChangeView ).toHaveBeenCalledWith( + expect.objectContaining( { + page: 1, + filters: [ + { field: 'mediaType', operator: 'is', value: 'video' }, + ], + } ) + ); + } ); + + it( 'matches a list of values when the field holds several', async () => { + const user = userEvent.setup(); + const { onChangeView } = renderFilterTabs( { field: 'category' } ); + + await user.click( screen.getByRole( 'tab', { name: 'Banners' } ) ); + + expect( onChangeView ).toHaveBeenCalledWith( + expect.objectContaining( { + filters: [ + { + field: 'category', + operator: 'isAny', + value: [ 'banners' ], + }, + ], + } ) + ); + } ); + + it( 'selects the tab of the active filter and removes it with the "All" tab', async () => { + const user = userEvent.setup(); + const { onChangeView } = renderFilterTabs( + { field: 'mediaType' }, + { + ...DEFAULT_VIEW, + search: 'sun', + filters: [ + { field: 'mediaType', operator: 'is', value: 'video' }, + { + field: 'category', + operator: 'isAny', + value: [ 'about' ], + }, + ], + } + ); + + expect( screen.getByRole( 'tab', { name: 'Videos' } ) ).toHaveAttribute( + 'aria-selected', + 'true' + ); + + await user.click( screen.getByRole( 'tab', { name: 'All' } ) ); + + // Only the tab's own filter goes: the rest of the view stays. + expect( onChangeView ).toHaveBeenCalledWith( + expect.objectContaining( { + search: 'sun', + filters: [ + { + field: 'category', + operator: 'isAny', + value: [ 'about' ], + }, + ], + } ) + ); + } ); + + it( 'has no "All" tab when `showAll` is false', async () => { + renderFilterTabs( { field: 'mediaType', showAll: false } ); + + expect( + ( await screen.findAllByRole( 'tab' ) ).map( + ( tab ) => tab.textContent + ) + ).toEqual( [ 'Images', 'Videos' ] ); + } ); +} ); diff --git a/packages/dataviews/src/components/dataviews-filter-tabs/utils.ts b/packages/dataviews/src/components/dataviews-filter-tabs/utils.ts new file mode 100644 index 00000000000000..2d4e2055b685b3 --- /dev/null +++ b/packages/dataviews/src/components/dataviews-filter-tabs/utils.ts @@ -0,0 +1,54 @@ +import { OPERATOR_IS, OPERATOR_IS_ANY } from '../../constants'; +import type { Option, View } from '../../types'; + +/** + * Returns which option the view currently filters the field by. + * + * @param view The current view. + * @param field The id of the field shown as tabs. + * @param elements The options of the field. + * @return The index of the option; `'all'` when the field isn't filtered; or + * `null` when the field is filtered in a way a single tab can't show + * (several values, another operator, or a value that isn't an option). + */ +export function getActiveOption( + view: View, + field: string, + elements: Option[] +): number | 'all' | null { + const fieldFilters = ( view.filters ?? [] ).filter( + ( filter ) => filter.field === field + ); + if ( fieldFilters.length === 0 ) { + return 'all'; + } + if ( fieldFilters.length > 1 ) { + return null; + } + + const { operator, value } = fieldFilters[ 0 ]; + if ( + value === undefined || + ( Array.isArray( value ) && value.length === 0 ) + ) { + return 'all'; + } + + let activeValue; + if ( operator === OPERATOR_IS ) { + activeValue = value; + } else if ( + operator === OPERATOR_IS_ANY && + Array.isArray( value ) && + value.length === 1 + ) { + activeValue = value[ 0 ]; + } else { + return null; + } + + const index = elements.findIndex( + ( element ) => element.value === activeValue + ); + return index === -1 ? null : index; +} diff --git a/packages/dataviews/src/components/dataviews-narrow-ui/index.tsx b/packages/dataviews/src/components/dataviews-narrow-ui/index.tsx new file mode 100644 index 00000000000000..e5a457e1a4ee82 --- /dev/null +++ b/packages/dataviews/src/components/dataviews-narrow-ui/index.tsx @@ -0,0 +1,75 @@ +import type { ReactNode } from 'react'; +import { Stack } from '@wordpress/ui'; +import type { NarrowOptions } from '../../types'; +import DataViewsFilterTabs from '../dataviews-filter-tabs'; +import DataViewsLayout from '../dataviews-layout'; +import DataViewsSearch from '../dataviews-search'; +import DataViewsViewMenu from '../dataviews-view-menu'; + +interface NarrowUIProps extends NarrowOptions { + search?: boolean; + searchLabel?: string; + footer: ReactNode; +} + +/** + * Reads the `narrow` option of a grid layout. + * + * @param narrow The value of the option. + * @return The options of the narrow UI, or `undefined` when it is off. + */ +export function getNarrowOptions( + narrow: boolean | NarrowOptions | undefined +): NarrowOptions | undefined { + if ( ! narrow ) { + return undefined; + } + return narrow === true ? {} : narrow; +} + +/** + * The UI for narrow, single-purpose containers such as a sidebar, rendered in + * place of the default UI when the grid layout has the `narrow` option. It + * takes the same data, fields and view, in an opinionated layout with a single + * settings button in place of the filters and the view options buttons. + * + * The rows, from top to bottom: search and the settings button; optionally one + * field as tabs; the content; the footer. + */ +export default function NarrowUI( { + search = true, + searchLabel, + tabsField, + showSort = true, + footer, +}: NarrowUIProps ) { + return ( + <> + + + { search && } + + + + { tabsField ? ( + + ) : ( + + ) } + { footer } + + ); +} diff --git a/packages/dataviews/src/components/dataviews-narrow-ui/style.scss b/packages/dataviews/src/components/dataviews-narrow-ui/style.scss new file mode 100644 index 00000000000000..53bff932703001 --- /dev/null +++ b/packages/dataviews/src/components/dataviews-narrow-ui/style.scss @@ -0,0 +1,19 @@ +// The search takes the room left beside the settings button. +.dataviews-narrow-ui__actions .dataviews-search { + flex: 1; +} + +// The picker's footer holds the selection, the pagination and the actions, +// which don't fit on one line here: the actions take a line of their own. +.dataviews-picker-wrapper.is-narrow .dataviews-footer { + flex-wrap: wrap; + + .dataviews-picker-footer__actions { + flex-basis: 100%; + + // The buttons sit in a row of their own, kept at the end of the line. + > * { + justify-content: flex-end; + } + } +} diff --git a/packages/dataviews/src/components/dataviews-narrow-ui/test/index.jsdom.test.tsx b/packages/dataviews/src/components/dataviews-narrow-ui/test/index.jsdom.test.tsx new file mode 100644 index 00000000000000..ad7df38811d7d6 --- /dev/null +++ b/packages/dataviews/src/components/dataviews-narrow-ui/test/index.jsdom.test.tsx @@ -0,0 +1,174 @@ +import { render, screen } from '@testing-library/react'; +import userEvent from '@testing-library/user-event'; +import { describe, expect, it, vi } from 'vitest'; +import DataViews from '../../../dataviews'; +import DataViewsPicker from '../../../dataviews-picker'; +import type { Field, NarrowOptions, View } from '../../../types'; + +globalThis.wpVitest.mockMatchMedia(); +globalThis.wpVitest.mockPointerEvent(); +globalThis.wpVitest.mockCSSSupports(); +// `Tabs.List` watches its size to know when the tabs overflow. +globalThis.wpVitest.mockResizeObserver(); + +type Item = { + id: number; + title: string; + type: string; + status: string; +}; + +const data: Item[] = [ + { id: 1, title: 'Earth', type: 'planet', status: 'visited' }, + { id: 2, title: 'Moon', type: 'satellite', status: 'visited' }, +]; + +const fields: Field< Item >[] = [ + { + id: 'title', + label: 'Title', + type: 'text', + filterBy: false, + enableSorting: false, + }, + { + id: 'type', + label: 'Type', + type: 'text', + elements: [ + { value: 'planet', label: 'Planet' }, + { value: 'satellite', label: 'Satellite' }, + ], + filterBy: { operators: [ 'is', 'isNot' ] }, + enableSorting: false, + }, + { + id: 'status', + label: 'Status', + type: 'text', + elements: [ + { value: 'visited', label: 'Visited' }, + { value: 'unvisited', label: 'Unvisited' }, + ], + filterBy: { operators: [ 'is', 'isNot' ] }, + enableSorting: false, + }, +]; + +const getView = ( + type: 'grid' | 'pickerGrid', + narrow?: boolean | NarrowOptions +): View => ( { + type, + page: 1, + perPage: 10, + titleField: 'title', + filters: [], + layout: { narrow }, +} ); + +function renderDataViews( narrow?: boolean | NarrowOptions ) { + render( + item.id.toString() } + /> + ); +} + +describe( 'The `narrow` option of the grid layout', () => { + it( 'keeps the default UI when it is off', async () => { + renderDataViews(); + + expect( + await screen.findByRole( 'button', { name: 'Add filter' } ) + ).toBeInTheDocument(); + expect( screen.queryByRole( 'tab' ) ).not.toBeInTheDocument(); + } ); + + it( 'replaces the filters and view options buttons with a single settings menu', async () => { + const user = userEvent.setup(); + renderDataViews( true ); + + expect( screen.getByRole( 'searchbox' ) ).toBeInTheDocument(); + expect( + screen.queryByRole( 'button', { name: 'Add filter' } ) + ).not.toBeInTheDocument(); + expect( screen.queryByRole( 'tab' ) ).not.toBeInTheDocument(); + + await user.click( + screen.getByRole( 'button', { name: 'View options' } ) + ); + + expect( + await screen.findByRole( 'group', { name: 'Type' } ) + ).toBeInTheDocument(); + expect( + screen.getByRole( 'group', { name: 'Status' } ) + ).toBeInTheDocument(); + } ); + + it( 'shows one field as tabs and leaves it out of the settings menu', async () => { + const user = userEvent.setup(); + renderDataViews( { tabsField: 'type' } ); + + expect( + ( await screen.findAllByRole( 'tab' ) ).map( + ( tab ) => tab.textContent + ) + ).toEqual( [ 'All', 'Planet', 'Satellite' ] ); + + await user.click( + screen.getByRole( 'button', { name: 'View options' } ) + ); + + expect( + await screen.findByRole( 'group', { name: 'Status' } ) + ).toBeInTheDocument(); + // The field shown as tabs isn't repeated in the menu. + expect( + screen.queryByRole( 'group', { name: 'Type' } ) + ).not.toBeInTheDocument(); + } ); + + it( 'applies to the grid of the picker, which keeps its own footer', async () => { + render( + item.id.toString() } + selection={ [] } + onChangeSelection={ vi.fn() } + actions={ [ + { + id: 'confirm', + label: 'Confirm', + isPrimary: true, + supportsBulk: false, + callback: vi.fn(), + }, + ] } + itemListLabel="Space objects" + /> + ); + + expect( + await screen.findByRole( 'button', { name: 'View options' } ) + ).toBeInTheDocument(); + expect( + screen.queryByRole( 'button', { name: 'Add filter' } ) + ).not.toBeInTheDocument(); + expect( + screen.getByRole( 'button', { name: 'Confirm' } ) + ).toBeInTheDocument(); + } ); +} ); diff --git a/packages/dataviews/src/components/dataviews-view-menu/index.tsx b/packages/dataviews/src/components/dataviews-view-menu/index.tsx new file mode 100644 index 00000000000000..d21a5480b4bb19 --- /dev/null +++ b/packages/dataviews/src/components/dataviews-view-menu/index.tsx @@ -0,0 +1,413 @@ +import type { ReactNode } from 'react'; +import { Button } from '@wordpress/components'; +import { __, _x } from '@wordpress/i18n'; +import { Children, Fragment, useContext } from '@wordpress/element'; +import { settings } from '@wordpress/icons'; +import { + // eslint-disable-next-line @wordpress/use-recommended-components -- Intentional early adoption of the new Menu, pending WordPress/gutenberg#76135. + Menu, +} from '@wordpress/ui'; +import { + OPERATOR_IS, + OPERATOR_IS_ANY, + SORTING_DIRECTIONS, + sortLabels, +} from '../../constants'; +import type { NormalizedFilter } from '../../types'; +import getSelectionOperator from '../../utils/get-selection-operator'; +import setFieldFilter from '../../utils/set-field-filter'; +import DataViewsContext from '../dataviews-context'; +import { getMenuFilters, MAX_INLINE_OPTIONS } from './utils'; + +// Radio values that don't stand for one of the filter's options. +const ALL = 'all'; +const NONE = 'none'; +const getOptionValue = ( index: number ) => `option-${ index }`; + +export interface ViewMenuProps { + /** + * Ids of fields to leave out of the menu. Use it for a field that is + * already shown elsewhere, such as the one in `DataViews.FilterTabs`. + */ + excludeFields?: string[]; + + /** + * Ids of single-choice fields that always filter by one value. Their group + * has no "All" item. The view is expected to start with a filter for each + * of them. + */ + requiredFields?: string[]; + + /** + * Whether the menu offers sorting: the field to sort by and the order. + * + * @default false + */ + showSort?: boolean; + + /** + * The size of the settings button: `compact` to sit next to + * `DataViews.Search`, or `default` to sit next to a 40px control. + * + * @default 'compact' + */ + size?: 'compact' | 'default'; + + /** + * Extra menu items, added at the end of the menu. For example, a + * `Menu.LinkItem` pointing to a help page. + */ + children?: ReactNode; +} + +function FilterRadioGroup( { + filter, + isRequired, + showLabel, +}: { + filter: NormalizedFilter; + isRequired: boolean; + showLabel: boolean; +} ) { + const { view, onChangeView } = useContext( DataViewsContext ); + const elements = filter.elements ?? []; + const activeFilter = view.filters?.find( + ( { field } ) => field === filter.field + ); + + let value = isRequired ? NONE : ALL; + if ( activeFilter && activeFilter.value !== undefined ) { + const index = + activeFilter.operator === OPERATOR_IS + ? elements.findIndex( + ( element ) => element.value === activeFilter.value + ) + : -1; + // A filter set elsewhere that the menu can't represent (another + // operator, or a value that isn't in the list) leaves nothing checked. + value = index === -1 ? NONE : getOptionValue( index ); + } + + return ( + { + const index = elements.findIndex( + ( _element, i ) => getOptionValue( i ) === nextValue + ); + onChangeView( + setFieldFilter( + view, + filter.field, + index === -1 + ? undefined + : { + operator: OPERATOR_IS, + value: elements[ index ].value, + } + ) + ); + } } + > + { showLabel && { filter.name } } + { ! isRequired && ( + + { __( 'All' ) } + + ) } + { elements.map( ( element, index ) => ( + + { element.label } + + ) ) } + + ); +} + +function FilterCheckboxGroup( { + filter, + showLabel, +}: { + filter: NormalizedFilter; + showLabel: boolean; +} ) { + const { view, onChangeView } = useContext( DataViewsContext ); + const elements = filter.elements ?? []; + const activeFilter = view.filters?.find( + ( { field, operator } ) => + field === filter.field && operator === OPERATOR_IS_ANY + ); + const activeValues: unknown[] = Array.isArray( activeFilter?.value ) + ? activeFilter.value + : []; + + return ( + + { showLabel && { filter.name } } + { elements.map( ( element, index ) => ( + { + const nextValues = checked + ? [ ...activeValues, element.value ] + : activeValues.filter( + ( value ) => value !== element.value + ); + onChangeView( + setFieldFilter( + view, + filter.field, + // With nothing checked, the field isn't filtered. + nextValues.length > 0 + ? { + operator: OPERATOR_IS_ANY, + value: nextValues, + } + : undefined + ) + ); + } } + > + { element.label } + + ) ) } + + ); +} + +/** + * The options of one filter, following the filter the field defines: radio + * items when it takes one value, checkboxes when it takes several. + */ +function FilterOptions( { + filter, + isRequired, + showLabel, +}: { + filter: NormalizedFilter; + isRequired: boolean; + showLabel: boolean; +} ) { + if ( getSelectionOperator( filter ) === OPERATOR_IS_ANY ) { + return ( + + ); + } + return ( + + ); +} + +function SortFieldRadioGroup() { + const { view, fields, onChangeView } = useContext( DataViewsContext ); + const sortableFields = fields.filter( + ( field ) => field.enableSorting !== false + ); + return ( + { + onChangeView( { + ...view, + sort: { + direction: view.sort?.direction || 'desc', + field, + }, + showLevels: false, + } ); + } } + > + { __( 'Sort by' ) } + { sortableFields.map( ( field ) => ( + + { field.label } + + ) ) } + + ); +} + +function SortDirectionRadioGroup() { + const { view, fields, onChangeView } = useContext( DataViewsContext ); + let value: string | undefined = view.sort?.direction; + if ( ! value ) { + value = view.sort?.field ? 'desc' : NONE; + } + return ( + { + if ( direction !== 'asc' && direction !== 'desc' ) { + return; + } + onChangeView( { + ...view, + sort: { + direction, + field: + view.sort?.field || + // Without a field to sort by yet, use the first sortable one. + fields.find( + ( field ) => field.enableSorting !== false + )?.id || + '', + }, + showLevels: false, + } ); + } } + > + { __( 'Order' ) } + { SORTING_DIRECTIONS.map( ( direction ) => ( + + { sortLabels[ direction ] } + + ) ) } + + ); +} + +/** + * A single settings button, in place of the filters and the view options + * buttons of the default UI. It opens a menu with the filters that have a + * fixed list of choices, sorting and any extra items. + * + * It is meant for narrow, single-purpose panels, where the filters bar and the + * view options popover don't fit. It builds itself from the fields and the + * view, as the default UI does, and renders nothing when the menu would be + * empty. + */ +export default function DataViewsViewMenu( { + excludeFields, + requiredFields = [], + showSort = false, + size = 'compact', + children, +}: ViewMenuProps ) { + const { fields, filters } = useContext( DataViewsContext ); + const menuFilters = getMenuFilters( filters, fields, excludeFields ); + const sortableFields = fields.filter( + ( field ) => field.enableSorting !== false + ); + const hasSort = showSort && sortableFields.length > 0; + const hasChildren = Children.toArray( children ).length > 0; + + if ( ! menuFilters.length && ! hasSort && ! hasChildren ) { + return null; + } + + const sections: { key: string; content: ReactNode }[] = []; + + // With many options in all, each group moves to a submenu. A group on its + // own stays in the menu, which scrolls: a submenu would only add a step. + const groupCount = menuFilters.length + ( hasSort ? 1 : 0 ); + const optionCount = + menuFilters.reduce( + ( count, filter ) => count + ( filter.elements?.length ?? 0 ), + 0 + ) + ( hasSort ? sortableFields.length + SORTING_DIRECTIONS.length : 0 ); + + if ( optionCount > MAX_INLINE_OPTIONS && groupCount > 1 ) { + sections.push( { + key: 'submenus', + content: ( + <> + { menuFilters.map( ( filter ) => ( + + + { filter.name } + + + + + + ) ) } + { hasSort && ( + + + + { __( 'Sort' ) } + + + + + + + + + ) } + + ), + } ); + } else { + menuFilters.forEach( ( filter ) => { + sections.push( { + key: `filter-${ filter.field }`, + content: ( + + ), + } ); + } ); + if ( hasSort ) { + sections.push( + { key: 'sort-field', content: }, + { key: 'sort-direction', content: } + ); + } + } + + if ( hasChildren ) { + sections.push( { key: 'extra', content: children } ); + } + + return ( + + + } + /> + }> + { sections.map( ( section, index ) => ( + + { index > 0 && } + { section.content } + + ) ) } + + + ); +} diff --git a/packages/dataviews/src/components/dataviews-view-menu/test/index.jsdom.test.tsx b/packages/dataviews/src/components/dataviews-view-menu/test/index.jsdom.test.tsx new file mode 100644 index 00000000000000..a012ec8504333d --- /dev/null +++ b/packages/dataviews/src/components/dataviews-view-menu/test/index.jsdom.test.tsx @@ -0,0 +1,365 @@ +import { render, screen } from '@testing-library/react'; +import userEvent from '@testing-library/user-event'; +import { describe, expect, it, vi } from 'vitest'; +import DataViews from '../../../dataviews'; +import type { Field, View } from '../../../types'; + +globalThis.wpVitest.mockMatchMedia(); +globalThis.wpVitest.mockPointerEvent(); +globalThis.wpVitest.mockCSSSupports(); + +type Item = { + id: number; + title: string; + status: string; + author: string; + date: string; + tags: string[]; +}; + +const data: Item[] = [ + { + id: 1, + title: 'Hello', + status: 'draft', + author: 'author-1', + date: '2025-01-15T09:00:00', + tags: [ 'news' ], + }, +]; + +const fields: Field< Item >[] = [ + { + id: 'title', + label: 'Title', + type: 'text', + filterBy: false, + enableSorting: false, + }, + { + id: 'status', + label: 'Status', + type: 'text', + elements: [ + { value: 'draft', label: 'Draft' }, + { value: 'published', label: 'Published' }, + ], + filterBy: { operators: [ 'is' ] }, + enableSorting: false, + }, + { + // Options loaded on demand, which a menu can't list. + id: 'author', + label: 'Author', + type: 'text', + getElements: async () => [ { value: 'author-1', label: 'Author 1' } ], + filterBy: { operators: [ 'is' ] }, + enableSorting: false, + }, + { + // Not a list of choices. + id: 'date', + label: 'Date', + type: 'datetime', + enableSorting: false, + }, + { + // Several values at once, as array fields are filtered by default. + id: 'tags', + label: 'Tags', + type: 'array', + elements: [ + { value: 'news', label: 'News' }, + { value: 'guides', label: 'Guides' }, + ], + enableSorting: false, + }, +]; + +const DEFAULT_VIEW: View = { + type: 'list', + page: 3, + perPage: 10, + titleField: 'title', + filters: [], +}; + +function renderViewMenu( { + menuProps, + view = DEFAULT_VIEW, +}: { + menuProps?: React.ComponentProps< typeof DataViews.ViewMenu >; + view?: View; +} = {} ) { + const onChangeView = vi.fn(); + render( + item.id.toString() } + > + + + ); + return { onChangeView }; +} + +const openMenu = ( user: ReturnType< typeof userEvent.setup > ) => + user.click( screen.getByRole( 'button', { name: 'View options' } ) ); + +describe( 'DataViews.ViewMenu', () => { + it( 'lists only the filters that work as menu items', async () => { + const user = userEvent.setup(); + renderViewMenu(); + + await openMenu( user ); + + expect( + ( await screen.findAllByRole( 'menuitemradio' ) ).map( + ( item ) => item.textContent + ) + ).toEqual( [ 'All', 'Draft', 'Published' ] ); + expect( + screen + .getAllByRole( 'menuitemcheckbox' ) + .map( ( item ) => item.textContent ) + ).toEqual( [ 'News', 'Guides' ] ); + expect( + screen.getByRole( 'group', { name: 'Status' } ) + ).toBeInTheDocument(); + expect( + screen.getByRole( 'group', { name: 'Tags' } ) + ).toBeInTheDocument(); + expect( + screen.queryByRole( 'group', { name: 'Author' } ) + ).not.toBeInTheDocument(); + expect( + screen.queryByRole( 'group', { name: 'Date' } ) + ).not.toBeInTheDocument(); + } ); + + it( 'filters the view by the chosen option and goes back to the first page', async () => { + const user = userEvent.setup(); + const { onChangeView } = renderViewMenu(); + + await openMenu( user ); + await user.click( + await screen.findByRole( 'menuitemradio', { name: 'Published' } ) + ); + + expect( onChangeView ).toHaveBeenCalledWith( + expect.objectContaining( { + page: 1, + filters: [ + { field: 'status', operator: 'is', value: 'published' }, + ], + } ) + ); + } ); + + it( 'checks the option of the active filter and removes it with "All"', async () => { + const user = userEvent.setup(); + const { onChangeView } = renderViewMenu( { + view: { + ...DEFAULT_VIEW, + filters: [ + { field: 'status', operator: 'is', value: 'draft' }, + ], + }, + } ); + + await openMenu( user ); + + expect( + await screen.findByRole( 'menuitemradio', { name: 'Draft' } ) + ).toBeChecked(); + + await user.click( + screen.getByRole( 'menuitemradio', { name: 'All' } ) + ); + + expect( onChangeView ).toHaveBeenCalledWith( + expect.objectContaining( { filters: [] } ) + ); + } ); + + it( 'adds and removes values of a filter that takes several', async () => { + const user = userEvent.setup(); + const { onChangeView } = renderViewMenu( { + view: { + ...DEFAULT_VIEW, + filters: [ + { field: 'tags', operator: 'isAny', value: [ 'news' ] }, + ], + }, + } ); + + await openMenu( user ); + + expect( + await screen.findByRole( 'menuitemcheckbox', { name: 'News' } ) + ).toBeChecked(); + + await user.click( + screen.getByRole( 'menuitemcheckbox', { name: 'Guides' } ) + ); + + expect( onChangeView ).toHaveBeenLastCalledWith( + expect.objectContaining( { + page: 1, + filters: [ + { + field: 'tags', + operator: 'isAny', + value: [ 'news', 'guides' ], + }, + ], + } ) + ); + + // With its last value unchecked, the filter goes away. + await user.click( + screen.getByRole( 'menuitemcheckbox', { name: 'News' } ) + ); + + expect( onChangeView ).toHaveBeenLastCalledWith( + expect.objectContaining( { filters: [] } ) + ); + } ); + + it( 'has no "All" option for a field that always needs a value', async () => { + const user = userEvent.setup(); + renderViewMenu( { menuProps: { requiredFields: [ 'status' ] } } ); + + await openMenu( user ); + + expect( + ( await screen.findAllByRole( 'menuitemradio' ) ).map( + ( item ) => item.textContent + ) + ).toEqual( [ 'Draft', 'Published' ] ); + } ); + + it( 'keeps a long list of options, in a submenu', async () => { + const user = userEvent.setup(); + // As many options as plugins care to register. + const sources = Array.from( { length: 14 }, ( _source, index ) => ( { + value: `source-${ index }`, + label: `Source ${ index }`, + } ) ); + render( + 'source-0', + elements: sources, + filterBy: { operators: [ 'is' ] }, + enableSorting: false, + }, + ] } + view={ { + ...DEFAULT_VIEW, + filters: [ + { field: 'source', operator: 'is', value: 'source-0' }, + ], + } } + onChangeView={ vi.fn() } + paginationInfo={ { totalItems: data.length, totalPages: 1 } } + defaultLayouts={ { list: {} } } + getItemId={ ( item ) => item.id.toString() } + > + + + ); + + await openMenu( user ); + await user.click( + await screen.findByRole( 'menuitem', { name: 'Source' } ) + ); + + const options = await screen.findAllByRole( 'menuitemradio', { + name: /^Source/, + } ); + expect( options ).toHaveLength( 14 ); + expect( options[ 0 ] ).toBeChecked(); + } ); + + it( 'keeps a long list in the menu when it is the only group', async () => { + const user = userEvent.setup(); + const sources = Array.from( { length: 14 }, ( _source, index ) => ( { + value: `source-${ index }`, + label: `Source ${ index }`, + } ) ); + const onChangeView = vi.fn(); + render( + 'source-0', + elements: sources, + filterBy: { operators: [ 'is' ] }, + enableSorting: false, + }, + ] } + view={ { + ...DEFAULT_VIEW, + titleField: undefined, + filters: [ + { field: 'source', operator: 'is', value: 'source-0' }, + ], + } } + onChangeView={ onChangeView } + paginationInfo={ { totalItems: data.length, totalPages: 1 } } + defaultLayouts={ { list: {} } } + getItemId={ ( item ) => item.id.toString() } + > + + + ); + + await openMenu( user ); + + expect( + await screen.findAllByRole( 'menuitemradio', { name: /^Source/ } ) + ).toHaveLength( 14 ); + expect( + screen.queryByRole( 'menuitem', { name: 'Source' } ) + ).not.toBeInTheDocument(); + + await user.click( + screen.getByRole( 'menuitemradio', { name: 'Source 13' } ) + ); + + expect( onChangeView ).toHaveBeenCalledWith( + expect.objectContaining( { + page: 1, + filters: [ + { field: 'source', operator: 'is', value: 'source-13' }, + ], + } ) + ); + } ); + + it( 'renders nothing when the menu would be empty', () => { + renderViewMenu( { + menuProps: { excludeFields: [ 'status', 'tags' ] }, + } ); + + expect( + screen.queryByRole( 'button', { name: 'View options' } ) + ).not.toBeInTheDocument(); + } ); +} ); diff --git a/packages/dataviews/src/components/dataviews-view-menu/test/utils.ts b/packages/dataviews/src/components/dataviews-view-menu/test/utils.ts new file mode 100644 index 00000000000000..a00f8649895b84 --- /dev/null +++ b/packages/dataviews/src/components/dataviews-view-menu/test/utils.ts @@ -0,0 +1,128 @@ +import { describe, expect, it } from 'vitest'; +import { getMenuFilters, isMenuFilter } from '../utils'; +import type { NormalizedField, NormalizedFilter, Option } from '../../../types'; + +type Item = Record< string, unknown >; + +const options = ( count: number ): Option[] => + Array.from( { length: count }, ( _option, index ) => ( { + value: `option-${ index }`, + label: `Option ${ index }`, + } ) ); + +function filter( + field: string, + props: Partial< NormalizedFilter > = {} +): NormalizedFilter { + return { + field, + name: field, + elements: options( 3 ), + hasElements: true, + singleSelection: true, + operators: [ 'is' ], + isVisible: false, + isPrimary: false, + isLocked: false, + ...props, + }; +} + +const field = ( id: string ) => + ( { id, label: id } ) as NormalizedField< Item >; + +describe( 'isMenuFilter', () => { + it( 'accepts a filter with a fixed list where one value is chosen', () => { + expect( isMenuFilter( filter( 'status' ) ) ).toBe( true ); + } ); + + it( 'accepts a filter with a fixed list where several values are chosen', () => { + expect( + isMenuFilter( + filter( 'tags', { + singleSelection: false, + operators: [ 'isAny', 'isNone' ], + } ) + ) + ).toBe( true ); + } ); + + it( 'accepts a fixed list however long, and rejects an empty one', () => { + expect( + isMenuFilter( filter( 'author', { elements: options( 40 ) } ) ) + ).toBe( true ); + expect( isMenuFilter( filter( 'author', { elements: [] } ) ) ).toBe( + false + ); + } ); + + it( 'rejects a filter that has no list of options, such as a date', () => { + expect( + isMenuFilter( + filter( 'date', { + elements: undefined, + hasElements: false, + operators: [ 'on', 'before', 'after' ], + } ) + ) + ).toBe( false ); + } ); + + it( 'rejects a filter whose options are loaded on demand', () => { + expect( + isMenuFilter( + filter( 'format', { + elements: undefined, + getElements: async () => options( 3 ), + } ) + ) + ).toBe( false ); + } ); + + it( 'rejects a filter that is not set by picking among its options', () => { + expect( + isMenuFilter( + filter( 'tags', { + singleSelection: false, + operators: [ 'isNone', 'isAll' ], + } ) + ) + ).toBe( false ); + } ); + + it( 'rejects a filter the user cannot change', () => { + expect( isMenuFilter( filter( 'status', { isLocked: true } ) ) ).toBe( + false + ); + } ); +} ); + +describe( 'getMenuFilters', () => { + it( 'keeps the eligible filters in the order their fields were declared', () => { + const filters = [ + filter( 'author', { isLocked: true } ), + filter( 'source' ), + filter( 'type' ), + ]; + const fields = [ + field( 'type' ), + field( 'author' ), + field( 'source' ), + ]; + + expect( + getMenuFilters( filters, fields ).map( ( { field: id } ) => id ) + ).toEqual( [ 'type', 'source' ] ); + } ); + + it( 'leaves out the excluded fields', () => { + const filters = [ filter( 'category' ), filter( 'source' ) ]; + const fields = [ field( 'category' ), field( 'source' ) ]; + + expect( + getMenuFilters( filters, fields, [ 'category' ] ).map( + ( { field: id } ) => id + ) + ).toEqual( [ 'source' ] ); + } ); +} ); diff --git a/packages/dataviews/src/components/dataviews-view-menu/utils.ts b/packages/dataviews/src/components/dataviews-view-menu/utils.ts new file mode 100644 index 00000000000000..4422d3301aecc4 --- /dev/null +++ b/packages/dataviews/src/components/dataviews-view-menu/utils.ts @@ -0,0 +1,73 @@ +import getSelectionOperator from '../../utils/get-selection-operator'; +import type { NormalizedField, NormalizedFilter } from '../../types'; + +/** + * How many options the menu shows at once. With more, each group of options + * moves to its own submenu, so the menu stays short. A group on its own stays + * in the menu however long it is. + */ +export const MAX_INLINE_OPTIONS = 10; + +/** + * Whether a filter can be shown in the view menu as a group of menu items. + * + * The menu follows the filter the field already defines, and only holds what + * works as menu items. A filter is eligible when: + * + * - its options are a fixed list (`elements`), not loaded on demand + * (`getElements`); + * - it is filtered by picking among those options: one of them (the `is` + * operator, shown as radio items) or several (`isAny`, shown as checkboxes); + * - the user can change it (it is not locked). + * + * The length of the list doesn't count. A list is often open to extension (the + * sources or categories that plugins register, for example), and a filter + * that left the menu once its list grew past some size would leave the user + * with no way to change it. A long list moves to a submenu, which scrolls. + * + * Everything else (dates, numbers, free text, remote lists) needs a control a + * menu can't hold, and is left to the regular filters UI. + * + * @param filter The filter to check. + * @return Whether the filter is eligible. + */ +export function isMenuFilter( filter: NormalizedFilter ): boolean { + return ( + ! filter.isLocked && + typeof filter.getElements !== 'function' && + Array.isArray( filter.elements ) && + filter.elements.length > 0 && + getSelectionOperator( filter ) !== undefined + ); +} + +/** + * Returns the filters to show in the view menu, in the order their fields were + * declared. + * + * @param filters The filters available in the view. + * @param fields The fields of the view. They set the order. + * @param excludeFields Ids of fields to leave out, for example a field that is + * already shown as tabs. + * @return The eligible filters. + */ +export function getMenuFilters( + filters: NormalizedFilter[], + fields: NormalizedField< any >[], + excludeFields: string[] = [] +): NormalizedFilter[] { + const position = new Map( + fields.map( ( field, index ) => [ field.id, index ] ) + ); + return filters + .filter( + ( filter ) => + ! excludeFields.includes( filter.field ) && + isMenuFilter( filter ) + ) + .sort( + ( a, b ) => + ( position.get( a.field ) ?? 0 ) - + ( position.get( b.field ) ?? 0 ) + ); +} diff --git a/packages/dataviews/src/dataviews-picker/index.tsx b/packages/dataviews/src/dataviews-picker/index.tsx index c33a192d47732a..aaa0a49e93966c 100644 --- a/packages/dataviews/src/dataviews-picker/index.tsx +++ b/packages/dataviews/src/dataviews-picker/index.tsx @@ -17,6 +17,7 @@ import { FiltersToggle, } from '../components/dataviews-filters'; import DataViewsLayout from '../components/dataviews-layout'; +import DataViewsFilterTabs from '../components/dataviews-filter-tabs'; import { DataViewsPickerFooter, DataViewsPickerBulkActionToolbar, @@ -32,6 +33,9 @@ import DataViewsViewConfig, { DataviewsViewConfigDropdown, ViewTypeMenu, } from '../components/dataviews-view-config'; +import DataViewsViewMenu from '../components/dataviews-view-menu'; +import NarrowUI, { getNarrowOptions } from '../components/dataviews-narrow-ui'; +import { LAYOUT_PICKER_GRID } from '../constants'; import normalizeFields from '../field-types'; import useContainerWidth from '../hooks/use-container-width'; import useData from '../hooks/use-data'; @@ -329,6 +333,12 @@ function DataViewsPicker< Item >( { return null; } + // The narrow UI is an option of the grid layout. + const narrowOptions = + view.type === LAYOUT_PICKER_GRID + ? getNarrowOptions( view.layout?.narrow ) + : undefined; + return ( ( { intersectionObserver, } } > -
- { children ?? ( - - ) } +
+ { children ?? + ( narrowOptions ? ( + } + { ...narrowOptions } + /> + ) : ( + + ) ) }
); @@ -381,6 +406,7 @@ const DataViewsPickerSubComponents = BulkActionToolbar: typeof DataViewsPickerBulkActionToolbar; Footer: typeof DataViewsPickerFooter; Filters: typeof Filters; + FilterTabs: typeof DataViewsFilterTabs; FiltersToggled: typeof FiltersToggled; FiltersToggle: typeof FiltersToggle; Layout: typeof DataViewsLayout; @@ -390,6 +416,7 @@ const DataViewsPickerSubComponents = Pagination: typeof DataViewsPagination; Search: typeof DataViewsSearch; ViewConfig: typeof DataviewsViewConfigDropdown; + ViewMenu: typeof DataViewsViewMenu; }; DataViewsPickerSubComponents.Actions = PickerActions; @@ -397,6 +424,7 @@ DataViewsPickerSubComponents.BulkActionToolbar = DataViewsPickerBulkActionToolbar; DataViewsPickerSubComponents.Footer = DataViewsPickerFooter; DataViewsPickerSubComponents.Filters = Filters; +DataViewsPickerSubComponents.FilterTabs = DataViewsFilterTabs; DataViewsPickerSubComponents.FiltersToggled = FiltersToggled; DataViewsPickerSubComponents.FiltersToggle = FiltersToggle; DataViewsPickerSubComponents.Layout = DataViewsLayout; @@ -406,5 +434,6 @@ DataViewsPickerSubComponents.PageSelect = DataViewsPageSelect; DataViewsPickerSubComponents.Pagination = DataViewsPagination; DataViewsPickerSubComponents.Search = DataViewsSearch; DataViewsPickerSubComponents.ViewConfig = DataviewsViewConfigDropdown; +DataViewsPickerSubComponents.ViewMenu = DataViewsViewMenu; export default DataViewsPickerSubComponents; diff --git a/packages/dataviews/src/dataviews-picker/stories/index.story.tsx b/packages/dataviews/src/dataviews-picker/stories/index.story.tsx index 8dfb11b6af1e80..bb62a988f437c7 100644 --- a/packages/dataviews/src/dataviews-picker/stories/index.story.tsx +++ b/packages/dataviews/src/dataviews-picker/stories/index.story.tsx @@ -8,6 +8,12 @@ import filterSortAndPaginate from '../../utils/filter-sort-and-paginate'; import type { ActionButton, MediaFit, View } from '../../types'; import FreeCompositionComponent from './free-composition'; import { data, fields, type SpaceObject } from './fixtures'; +import { + getNarrowOption, + narrowArgs, + narrowArgTypes, + type NarrowTabsField, +} from '../../dataviews/stories/narrow'; const meta = { tags: [ 'manifest' ], @@ -65,6 +71,8 @@ interface PickerContentProps { infiniteScrollEnabled: boolean; mediaFit?: MediaFit; mediaFitControl?: boolean; + narrow?: boolean; + narrowTabsField?: NarrowTabsField; actions?: ActionButton< SpaceObject >[]; selection?: string[]; } @@ -76,6 +84,8 @@ const DataViewsPickerContent = ( { infiniteScrollEnabled, mediaFit = 'cover', mediaFitControl = true, + narrow = false, + narrowTabsField = 'type', actions: customActions, selection: customSelection, }: PickerContentProps ) => { @@ -122,7 +132,11 @@ const DataViewsPickerContent = ( { infiniteScrollEnabled, // Spread the previous layout so a change made through the // view options popover survives an unrelated arg change. - layout: { ...prevView.layout, mediaFit }, + layout: { + ...prevView.layout, + mediaFit, + narrow: getNarrowOption( narrow, narrowTabsField ), + }, }; if ( infiniteScrollEnabled ) { @@ -143,7 +157,13 @@ const DataViewsPickerContent = ( { startPosition: undefined, } as View; } ); - }, [ isGrouped, infiniteScrollEnabled, mediaFit ] ); + }, [ + isGrouped, + infiniteScrollEnabled, + mediaFit, + narrow, + narrowTabsField, + ] ); const [ selection, setSelection ] = useState< string[] >( customSelection || [] @@ -186,6 +206,15 @@ const DataViewsPickerContent = ( { } ` } ) } + { narrow && ( + // Contained, to show the narrow UI at the width it is + // meant for. + + ) } ( ); -Default.args = storyArgs; -Default.argTypes = storyArgTypes; +Default.args = { ...storyArgs, ...narrowArgs }; +Default.argTypes = { ...storyArgTypes, ...narrowArgTypes }; Default.parameters = { // FIXME: Picker UI nests interactive controls (nested-interactive). // See: https://github.com/WordPress/gutenberg/issues/81596 diff --git a/packages/dataviews/src/dataviews/index.tsx b/packages/dataviews/src/dataviews/index.tsx index 527bebdb04f4b3..dce65f7aed9853 100644 --- a/packages/dataviews/src/dataviews/index.tsx +++ b/packages/dataviews/src/dataviews/index.tsx @@ -10,6 +10,7 @@ import { Stack, useEnableWpCompatOverlaySlot } from '@wordpress/ui'; import deprecated from '@wordpress/deprecated'; import DataViewsContext from '../components/dataviews-context'; import { VIEW_LAYOUTS } from '../components/dataviews-layouts'; +import { LAYOUT_GRID } from '../constants'; import { Filters, FiltersToggled, @@ -17,6 +18,8 @@ import { FiltersToggle, } from '../components/dataviews-filters'; import DataViewsLayout from '../components/dataviews-layout'; +import DataViewsFilterTabs from '../components/dataviews-filter-tabs'; +import NarrowUI, { getNarrowOptions } from '../components/dataviews-narrow-ui'; import DataViewsFooter from '../components/dataviews-footer'; import DataViewsSearch from '../components/dataviews-search'; import { DataViewsPagination } from '../components/dataviews-pagination'; @@ -24,6 +27,7 @@ import DataViewsViewConfig, { DataviewsViewConfigDropdown, ViewTypeMenu, } from '../components/dataviews-view-config'; +import DataViewsViewMenu from '../components/dataviews-view-menu'; import normalizeFields from '../field-types'; import useContainerWidth from '../hooks/use-container-width'; import useData from '../hooks/use-data'; @@ -217,6 +221,12 @@ function DataViews< Item >( { return null; } + // The narrow UI is an option of the grid layout. + const narrowOptions = + view.type === LAYOUT_GRID + ? getNarrowOptions( view.layout?.narrow ) + : undefined; + return ( ( { intersectionObserver, } } > -
- { children ?? ( - - ) } +
+ { children ?? + ( narrowOptions ? ( + } + { ...narrowOptions } + /> + ) : ( + + ) ) }
); @@ -272,6 +294,7 @@ function DataViews< Item >( { const DataViewsSubComponents = DataViews as typeof DataViews & { BulkActionToolbar: () => React.JSX.Element; Filters: typeof Filters; + FilterTabs: typeof DataViewsFilterTabs; FiltersToggle: typeof FiltersToggle; FiltersToggled: typeof FiltersToggled; Layout: typeof DataViewsLayout; @@ -279,6 +302,7 @@ const DataViewsSubComponents = DataViews as typeof DataViews & { Pagination: typeof DataViewsPagination; Search: typeof DataViewsSearch; ViewConfig: typeof DataviewsViewConfigDropdown; + ViewMenu: typeof DataViewsViewMenu; Footer: typeof DataViewsFooter; }; @@ -290,6 +314,7 @@ DataViewsSubComponents.BulkActionToolbar = return <>; }; DataViewsSubComponents.Filters = Filters; +DataViewsSubComponents.FilterTabs = DataViewsFilterTabs; DataViewsSubComponents.FiltersToggled = FiltersToggled; DataViewsSubComponents.FiltersToggle = FiltersToggle; DataViewsSubComponents.Layout = DataViewsLayout; @@ -297,6 +322,7 @@ DataViewsSubComponents.LayoutSwitcher = ViewTypeMenu; DataViewsSubComponents.Pagination = DataViewsPagination; DataViewsSubComponents.Search = DataViewsSearch; DataViewsSubComponents.ViewConfig = DataviewsViewConfigDropdown; +DataViewsSubComponents.ViewMenu = DataViewsViewMenu; DataViewsSubComponents.Footer = DataViewsFooter; export default DataViewsSubComponents; diff --git a/packages/dataviews/src/dataviews/stories/index.story.tsx b/packages/dataviews/src/dataviews/stories/index.story.tsx index dcd4dba0f13f2c..40f300199ae425 100644 --- a/packages/dataviews/src/dataviews/stories/index.story.tsx +++ b/packages/dataviews/src/dataviews/stories/index.story.tsx @@ -13,6 +13,7 @@ import FreeCompositionComponent from './free-composition'; import MinimalUIComponent from './minimal-ui'; import EmptyComponent from './empty'; import LargePageCountComponent from './large-page-count'; +import { narrowArgs, narrowArgTypes } from './narrow'; const meta = { tags: [ 'manifest' ], @@ -100,6 +101,7 @@ export const LayoutGrid = { }, render: LayoutGridComponent, args: { + ...narrowArgs, groupBy: false, groupByLabel: true, hasClickableItems: true, @@ -109,6 +111,7 @@ export const LayoutGrid = { showMedia: true, }, argTypes: { + ...narrowArgTypes, backgroundColor: { control: 'color', description: 'Background color of the DataViews component', diff --git a/packages/dataviews/src/dataviews/stories/layout-grid.tsx b/packages/dataviews/src/dataviews/stories/layout-grid.tsx index 92184672f22821..b201335b45f67b 100644 --- a/packages/dataviews/src/dataviews/stories/layout-grid.tsx +++ b/packages/dataviews/src/dataviews/stories/layout-grid.tsx @@ -4,6 +4,7 @@ import { LAYOUT_GRID } from '../../constants'; import filterSortAndPaginate from '../../utils/filter-sort-and-paginate'; import type { MediaFit, View } from '../../types'; import { actions, data, fields, type SpaceObject } from './fixtures'; +import { getNarrowOption, type NarrowTabsField } from './narrow'; export const LayoutTableComponent = ( { backgroundColor, @@ -12,6 +13,8 @@ export const LayoutTableComponent = ( { groupByLabel = true, mediaFit = 'cover', mediaFitControl = true, + narrow = false, + narrowTabsField = 'type', perPageSizes = [ 10, 25, 50, 100 ], showMedia = true, }: { @@ -21,6 +24,8 @@ export const LayoutTableComponent = ( { groupByLabel?: boolean; mediaFit?: MediaFit; mediaFitControl?: boolean; + narrow?: boolean; + narrowTabsField?: NarrowTabsField; perPageSizes?: number[]; showMedia?: boolean; } ) => { @@ -52,10 +57,21 @@ export const LayoutTableComponent = ( { showMedia, // Spread the previous layout so a change made through the // view options popover survives an unrelated arg change. - layout: { ...prevView.layout, mediaFit }, + layout: { + ...prevView.layout, + mediaFit, + narrow: getNarrowOption( narrow, narrowTabsField ), + }, } as View; } ); - }, [ groupBy, groupByLabel, mediaFit, showMedia ] ); + }, [ + groupBy, + groupByLabel, + mediaFit, + showMedia, + narrow, + narrowTabsField, + ] ); const { data: shownData, paginationInfo } = useMemo( () => { return filterSortAndPaginate( data, view, fields ); @@ -64,6 +80,9 @@ export const LayoutTableComponent = ( {
diff --git a/packages/dataviews/src/dataviews/stories/narrow.ts b/packages/dataviews/src/dataviews/stories/narrow.ts new file mode 100644 index 00000000000000..c47a1a50f6bf35 --- /dev/null +++ b/packages/dataviews/src/dataviews/stories/narrow.ts @@ -0,0 +1,36 @@ +export type NarrowTabsField = 'none' | 'type' | 'categories'; + +/** + * Turns the story controls into the value of the grid layout's `narrow` + * option. + * + * @param narrow Whether the narrow UI is on. + * @param tabsField The field to show as tabs, or `none`. + * @return The value of the `narrow` option. + */ +export function getNarrowOption( narrow: boolean, tabsField: NarrowTabsField ) { + if ( ! narrow ) { + return false; + } + return tabsField === 'none' ? true : { tabsField }; +} + +export const narrowArgs = { + narrow: false, + narrowTabsField: 'type', +}; + +export const narrowArgTypes = { + narrow: { + control: 'boolean', + description: + 'Whether the grid layout renders the UI for narrow containers (`layout.narrow`), shown in a 400px wide container: a single settings button replaces the filters and the view options buttons', + }, + narrowTabsField: { + control: 'select', + options: [ 'none', 'type', 'categories' ], + description: + 'With `narrow`, the field shown as tabs above the content. It is left out of the settings menu', + if: { arg: 'narrow' }, + }, +}; diff --git a/packages/dataviews/src/style.scss b/packages/dataviews/src/style.scss index c83a5f1000c17a..f97d162ad5dc0d 100644 --- a/packages/dataviews/src/style.scss +++ b/packages/dataviews/src/style.scss @@ -2,6 +2,8 @@ @use "./components/dataviews-bulk-actions/style.scss" as *; @use "./components/dataviews-layout/style.scss" as *; @use "./components/dataviews-filters/style.scss" as *; +@use "./components/dataviews-filter-tabs/style.scss" as *; +@use "./components/dataviews-narrow-ui/style.scss" as *; @use "./components/dataviews-footer/style.scss" as *; @use "./components/dataviews-pagination/style.scss" as *; @use "./components/dataviews-item-actions/style.scss" as *; diff --git a/packages/dataviews/src/types/dataviews.ts b/packages/dataviews/src/types/dataviews.ts index f0522585506645..db1aa0b23849a0 100644 --- a/packages/dataviews/src/types/dataviews.ts +++ b/packages/dataviews/src/types/dataviews.ts @@ -504,6 +504,25 @@ export interface ViewActivity extends ViewBase { }; } +/** + * Adjusts the UI for narrow containers of the grid layouts. + */ +export interface NarrowOptions { + /** + * The id of a field to show as tabs above the content: the main way to + * browse it, such as a category or a type. It is left out of the settings + * menu. + */ + tabsField?: string; + + /** + * Whether the settings menu offers sorting. + * + * @default true + */ + showSort?: boolean; +} + export interface ViewGrid extends ViewBase { /** * The layout discriminant: a grid view. @@ -543,6 +562,14 @@ export interface ViewGrid extends ViewBase { * either way, so rows stay aligned. Defaults to `'cover'`. */ mediaFit?: MediaFit; + + /** + * Renders the UI for narrow, single-purpose containers, such as a + * sidebar, in place of the default UI: a single settings button + * replaces the filters and the view options buttons. It is meant + * to be set by the consumer, not changed by the user. + */ + narrow?: boolean | NarrowOptions; }; } @@ -578,6 +605,14 @@ export interface ViewPickerGrid extends ViewBase { * aligned. Defaults to `'cover'`. */ mediaFit?: MediaFit; + + /** + * Renders the UI for narrow, single-purpose containers, such as a + * sidebar, in place of the default UI: a single settings button + * replaces the filters and the view options buttons. It is meant + * to be set by the consumer, not changed by the user. + */ + narrow?: boolean | NarrowOptions; }; } diff --git a/packages/dataviews/src/utils/get-selection-operator.ts b/packages/dataviews/src/utils/get-selection-operator.ts new file mode 100644 index 00000000000000..5a1a96b2a9e01a --- /dev/null +++ b/packages/dataviews/src/utils/get-selection-operator.ts @@ -0,0 +1,22 @@ +import { OPERATOR_IS, OPERATOR_IS_ANY } from '../constants'; +import type { NormalizedFilter } from '../types'; + +type SelectionOperator = typeof OPERATOR_IS | typeof OPERATOR_IS_ANY; + +/** + * Returns the operator to filter a field with when the user only picks among + * its options, with no control to choose an operator: `is` to pick one value, + * or `isAny` to pick several. It is the first of the two that the field + * lists, as when a filter is added from the filters UI. + * + * @param filter The filter of the field. + * @return The operator, or `undefined` when the field supports neither. + */ +export default function getSelectionOperator( + filter: Pick< NormalizedFilter, 'operators' > +): SelectionOperator | undefined { + return filter.operators.find( + ( operator ): operator is SelectionOperator => + operator === OPERATOR_IS || operator === OPERATOR_IS_ANY + ); +} diff --git a/packages/dataviews/src/utils/set-field-filter.ts b/packages/dataviews/src/utils/set-field-filter.ts new file mode 100644 index 00000000000000..e3d88b56c3c184 --- /dev/null +++ b/packages/dataviews/src/utils/set-field-filter.ts @@ -0,0 +1,32 @@ +import type { Filter, View } from '../types'; + +/** + * Returns a copy of the view where the given field is filtered by a single + * filter, or by none. Any previous filter for that field is replaced, and the + * view goes back to the first page. + * + * @param view The current view. + * @param field The id of the field to filter by. + * @param filter The operator and value to filter by. Leave it out to remove + * the field's filter. + * @return The updated view. + */ +export default function setFieldFilter< T extends View >( + view: T, + field: string, + filter?: Pick< Filter, 'operator' | 'value' > +): T { + const otherFilters = ( view.filters ?? [] ).filter( + ( viewFilter ) => viewFilter.field !== field + ); + return { + ...view, + page: 1, + filters: filter + ? [ + ...otherFilters, + { field, operator: filter.operator, value: filter.value }, + ] + : otherFilters, + }; +}