- { 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,
+ };
+}