diff --git a/packages/dataviews/CHANGELOG.md b/packages/dataviews/CHANGELOG.md index b52548d92b17fc..9e048d33df073c 100644 --- a/packages/dataviews/CHANGELOG.md +++ b/packages/dataviews/CHANGELOG.md @@ -5,6 +5,7 @@ ### Bug Fixes - DataForm: Translate the "(Required)" and "(Optional)" suffixes of date and date time field labels together with the label, so translators can change their order ([#87487](https://github.com/WordPress/gutenberg/pull/87487)). +- Keep focus in the view when an action, such as moving items to the trash, removes the control that had it. Focus moves to the "Select all" checkbox, or to the next item in the list layout, or to the search when no items are left, rather than to the document body ([#87248](https://github.com/WordPress/gutenberg/pull/87248)). ### Internal diff --git a/packages/dataviews/src/components/dataviews-bulk-actions/index.tsx b/packages/dataviews/src/components/dataviews-bulk-actions/index.tsx index 0b05f7159cf39d..669fedda637561 100644 --- a/packages/dataviews/src/components/dataviews-bulk-actions/index.tsx +++ b/packages/dataviews/src/components/dataviews-bulk-actions/index.tsx @@ -166,6 +166,8 @@ function ActionTrigger< Item >( { size="compact" disabled={ !! action.disabled || isBusy } loading={ isBusy } + // Tells the focus handling after the action that it holds focus. + data-dataviews-busy={ isBusy || undefined } onClick={ onClick } aria-haspopup={ 'RenderModal' in action ? 'dialog' : undefined } > @@ -314,6 +316,9 @@ function renderBulkActionsContent< Item >( tone="neutral" size="compact" loading={ !! actionInProgress } + data-dataviews-busy={ + !! actionInProgress || undefined + } > { __( 'Actions' ) } @@ -345,7 +350,8 @@ function BulkActionsContent< Item >( { onActionInProgressChange, onClearSelection, }: ToolbarContentProps< Item > ) { - const { paginationInfo } = useContext( DataViewsContext ); + const { paginationInfo, requestFocusAfterAction } = + useContext( DataViewsContext ); const [ pendingContent, setPendingContent ] = useState< React.JSX.Element >(); const registry = useRegistry(); @@ -354,6 +360,7 @@ function BulkActionsContent< Item >( { items: Item[]; } | null >( null ); const onAction = async ( action: Action< Item >, items: Item[] ) => { + requestFocusAfterAction?.(); if ( 'RenderModal' in action ) { setActiveModal( { action, items } ); return; diff --git a/packages/dataviews/src/components/dataviews-context/index.ts b/packages/dataviews/src/components/dataviews-context/index.ts index dd002fb5785feb..ff0a7e4617f232 100644 --- a/packages/dataviews/src/components/dataviews-context/index.ts +++ b/packages/dataviews/src/components/dataviews-context/index.ts @@ -47,6 +47,11 @@ type DataViewsContextType< Item > = { itemListLabel?: string; onReset?: ( () => void ) | false; intersectionObserver?: IntersectionObserver | null; + /** + * Asks to keep focus in the view once the action being run has removed + * the control that had it. + */ + requestFocusAfterAction?: () => void; }; const DataViewsContext = createContext< DataViewsContextType< any > >( { diff --git a/packages/dataviews/src/components/dataviews-item-actions/index.tsx b/packages/dataviews/src/components/dataviews-item-actions/index.tsx index 7a50273a48172b..fa84737f592b77 100644 --- a/packages/dataviews/src/components/dataviews-item-actions/index.tsx +++ b/packages/dataviews/src/components/dataviews-item-actions/index.tsx @@ -1,7 +1,7 @@ import type { MouseEventHandler } from 'react'; import { Button, Modal } from '@wordpress/components'; import { __ } from '@wordpress/i18n'; -import { useMemo, useState } from '@wordpress/element'; +import { useContext, useMemo, useState } from '@wordpress/element'; import { moreVertical } from '@wordpress/icons'; import { useRegistry } from '@wordpress/data'; import { useViewportMatch } from '@wordpress/compose'; @@ -13,6 +13,7 @@ import { import { kebabCase } from '@wordpress/kebab-case'; import type { Action, ActionModal as ActionModalType } from '../../types'; import getActionLabel from '../../utils/get-action-label'; +import DataViewsContext from '../dataviews-context'; export interface ActionTriggerProps< Item > { action: Action< Item >; @@ -127,6 +128,7 @@ export function ActionsMenuGroup< Item >( { registry, setActiveModalAction, }: ActionsMenuGroupProps< Item > ) { + const { requestFocusAfterAction } = useContext( DataViewsContext ); const { primaryActions, regularActions } = useMemo( () => { return actions.reduce( ( acc, action ) => { @@ -149,6 +151,7 @@ export function ActionsMenuGroup< Item >( { key={ action.id } action={ action } onClick={ () => { + requestFocusAfterAction?.(); if ( 'RenderModal' in action ) { setActiveModalAction( action ); return; @@ -280,6 +283,7 @@ export function PrimaryActions< Item >( { registry, buttonVariant, }: PrimaryActionsProps< Item > ) { + const { requestFocusAfterAction } = useContext( DataViewsContext ); const [ activeModalAction, setActiveModalAction ] = useState( null as any ); const isMobileViewport = useViewportMatch( 'medium', '<' ); @@ -297,6 +301,7 @@ export function PrimaryActions< Item >( { key={ action.id } action={ action } onClick={ () => { + requestFocusAfterAction?.(); if ( 'RenderModal' in action ) { setActiveModalAction( action ); return; diff --git a/packages/dataviews/src/components/dataviews-layouts/list/index.tsx b/packages/dataviews/src/components/dataviews-layouts/list/index.tsx index 71017536b20a69..4e01d6d192c99f 100644 --- a/packages/dataviews/src/components/dataviews-layouts/list/index.tsx +++ b/packages/dataviews/src/components/dataviews-layouts/list/index.tsx @@ -72,6 +72,7 @@ function PrimaryActionGridCell< Item >( { item: Item; } ) { const registry = useRegistry(); + const { requestFocusAfterAction } = useContext( DataViewsContext ); const [ isModalOpen, setIsModalOpen ] = useState( false ); const compositeItemId = generatePrimaryActionCompositeId( @@ -92,7 +93,10 @@ function PrimaryActionGridCell< Item >( { text={ label } size="small" aria-haspopup="dialog" - onClick={ () => setIsModalOpen( true ) } + onClick={ () => { + requestFocusAfterAction?.(); + setIsModalOpen( true ); + } } /> } > @@ -115,6 +119,7 @@ function PrimaryActionGridCell< Item >( { accessibleWhenDisabled size="small" onClick={ () => { + requestFocusAfterAction?.(); primaryAction.callback( [ item ], { registry } ); } } > diff --git a/packages/dataviews/src/dataviews/index.tsx b/packages/dataviews/src/dataviews/index.tsx index 527bebdb04f4b3..1f8f38fe308cab 100644 --- a/packages/dataviews/src/dataviews/index.tsx +++ b/packages/dataviews/src/dataviews/index.tsx @@ -27,6 +27,7 @@ import DataViewsViewConfig, { import normalizeFields from '../field-types'; import useContainerWidth from '../hooks/use-container-width'; import useData from '../hooks/use-data'; +import useFocusAfterAction from '../hooks/use-focus-after-action'; import { useInfiniteScroll } from '../hooks/use-infinite-scroll'; import usePageClamp from '../hooks/use-page-clamp'; import type { SupportedLayouts, DataViewsProps, ItemWithId } from '../types'; @@ -213,6 +214,14 @@ function DataViews< Item >( { [ defaultLayoutsProperty ] ); + const { ref: wrapperRef, request: requestFocusAfterAction } = + useFocusAfterAction( { + layoutRef: containerRef, + data: displayData, + getItemId, + isLoading, + } ); + if ( ! defaultLayouts[ view.type ] ) { return null; } @@ -248,9 +257,10 @@ function DataViews< Item >( { hasInitiallyLoaded, onReset, intersectionObserver, + requestFocusAfterAction, } } > -
+
{ children ?? ( { + // Wide enough for the primary actions to show next to each item. + await page.viewport( 1280, 900 ); +} ); +afterEach( async () => { + await page.viewport( initialViewport.width, initialViewport.height ); +} ); + +type Post = { id: string; title: string; isLocked?: boolean }; +const initialPosts: Post[] = [ + { id: '1', title: 'First post' }, + { id: '2', title: 'Second post' }, + { id: '3', title: 'Third post' }, +]; +const fields: Field< Post >[] = [ + { id: 'title', label: 'Title', type: 'text' }, +]; + +function TrashableView( { + type = 'table', + posts: startPosts = initialPosts, + perPage = 10, +}: { + type?: 'table' | 'list'; + posts?: Post[]; + perPage?: number; +} ) { + const [ posts, setPosts ] = useState( startPosts ); + // Like the trash action of the editor, which closes its dialog once the + // items are gone. + const closeAfterRemovalRef = useRef< ( () => void ) | null >( null ); + useEffect( () => { + closeAfterRemovalRef.current?.(); + closeAfterRemovalRef.current = null; + }, [ posts ] ); + // Like a store: the items go after a refetch, during which the layout is + // inert. + const [ removing, setRemoving ] = useState< string[] | null >( null ); + useEffect( () => { + if ( ! removing ) { + return; + } + const timeout = setTimeout( () => { + setPosts( ( current ) => + current.filter( ( post ) => ! removing.includes( post.id ) ) + ); + setRemoving( null ); + }, 50 ); + return () => clearTimeout( timeout ); + }, [ removing ] ); + // Like a store that drops the items, then refetches while the dialog + // closes. + const [ phase, setPhase ] = useState< + 'idle' | 'removed' | 'refetching' | 'closed' + >( 'idle' ); + const closeDuringRefetchRef = useRef< ( () => void ) | null >( null ); + useEffect( () => { + if ( phase === 'removed' ) { + setPhase( 'refetching' ); + } else if ( phase === 'refetching' ) { + closeDuringRefetchRef.current?.(); + setPhase( 'closed' ); + } else if ( phase === 'closed' ) { + const timeout = setTimeout( () => setPhase( 'idle' ), 50 ); + return () => clearTimeout( timeout ); + } + return undefined; + }, [ phase ] ); + // Like a store that drops the items without a refetch. + const [ quietlyRemoving, setQuietlyRemoving ] = useState< string[] | null >( + null + ); + useEffect( () => { + if ( ! quietlyRemoving ) { + return; + } + const timeout = setTimeout( () => { + setPosts( ( current ) => + current.filter( + ( post ) => ! quietlyRemoving.includes( post.id ) + ) + ); + setQuietlyRemoving( null ); + }, 50 ); + return () => clearTimeout( timeout ); + }, [ quietlyRemoving ] ); + const [ view, setView ] = useState< View >( { + type, + titleField: 'title', + page: 1, + perPage, + } as View ); + // Stable, so the dialogs keep their focus across renders. + const actions = useMemo< Action< Post >[] >( () => { + const removeLater = ( ids: string[] ) => setRemoving( ids ); + const removeNow = ( ids: string[] ) => + setPosts( ( current ) => + current.filter( ( post ) => ! ids.includes( post.id ) ) + ); + return [ + { + id: 'trash', + label: 'Trash', + isPrimary: true, + supportsBulk: true, + isEligible: ( post ) => ! post.isLocked, + RenderModal: ( { items, closeModal } ) => ( + <> + + + + + ), + }, + { + id: 'remove-now', + label: 'Remove now', + callback: ( items ) => + removeLater( items.map( ( item ) => item.id ) ), + }, + { + id: 'remove-slowly', + label: 'Remove slowly', + supportsBulk: true, + isEligible: ( post ) => ! post.isLocked, + // Drops the items, then finishes while its busy button shows. + callback: async ( items ) => { + removeNow( items.map( ( item ) => item.id ) ); + await new Promise( ( resolve ) => + window.requestAnimationFrame( () => + window.requestAnimationFrame( resolve ) + ) + ); + }, + }, + { + id: 'remove-quietly', + label: 'Remove quietly', + callback: ( items ) => + setQuietlyRemoving( items.map( ( item ) => item.id ) ), + }, + { + id: 'archive', + label: 'Archive', + supportsBulk: true, + disabled: true, + callback: () => {}, + }, + { + id: 'noop', + label: 'Do nothing', + supportsBulk: true, + callback: () => {}, + }, + ]; + }, [] ); + const { data, paginationInfo } = filterSortAndPaginate( + posts, + view, + fields + ); + return ( + <> + + + + ); +} + +const selectAll = () => + page.getByRole( 'checkbox', { name: 'Select all', exact: true } ); +const row = ( title: string ) => + page.getByRole( 'row' ).filter( { hasText: title } ); + +it( 'moves focus to "Select all" when a modal action removes the item', async () => { + const user = userEvent.setup(); + await render( ); + await user.click( + row( 'First post' ).getByRole( 'button', { name: /^Trash/ } ) + ); + await user.click( page.getByRole( 'button', { name: 'Confirm' } ) ); + + await expect + .element( page.getByText( 'First post' ) ) + .not.toBeInTheDocument(); + await expect.element( selectAll() ).toHaveFocus(); +} ); + +it( 'moves focus to "Select all" when an action from the menu removes the item', async () => { + const user = userEvent.setup(); + await render( ); + await user.click( + row( 'Second post' ).getByRole( 'button', { name: 'Actions' } ) + ); + await user.click( page.getByRole( 'menuitem', { name: 'Remove now' } ) ); + + await expect + .element( page.getByText( 'Second post' ) ) + .not.toBeInTheDocument(); + await expect.element( selectAll() ).toHaveFocus(); +} ); + +it( 'moves focus to the search when a bulk action removes every item', async () => { + const user = userEvent.setup(); + await render( ); + await user.click( selectAll() ); + const toolbar = page.elementLocator( + document.querySelector( '.dataviews-bulk-actions' )! + ); + await user.click( toolbar.getByRole( 'button', { name: /^Trash/ } ) ); + await user.click( page.getByRole( 'button', { name: 'Confirm' } ) ); + + await expect + .element( page.getByText( 'Third post' ) ) + .not.toBeInTheDocument(); + await expect.element( page.getByRole( 'searchbox' ) ).toHaveFocus(); +} ); + +it( 'moves focus to "Select all" when a dialog closes after its items went', async () => { + const user = userEvent.setup(); + await render( + + ); + // The locked post keeps the toolbar, but not its Trash button, once the + // first post is gone. + await user.click( row( 'First post' ).getByRole( 'checkbox' ) ); + await user.click( row( 'Locked post' ).getByRole( 'checkbox' ) ); + const toolbar = page.elementLocator( + document.querySelector( '.dataviews-bulk-actions' )! + ); + await user.click( toolbar.getByRole( 'button', { name: /^Trash/ } ) ); + await user.click( + page.getByRole( 'button', { name: 'Confirm and wait' } ) + ); + + await expect + .element( page.getByText( 'First post' ) ) + .not.toBeInTheDocument(); + await expect.element( selectAll() ).toHaveFocus(); +} ); + +it( 'waits for the items to load when a dialog closes during a refetch', async () => { + const user = userEvent.setup(); + await render( + + ); + await user.click( row( 'First post' ).getByRole( 'checkbox' ) ); + await user.click( row( 'Locked post' ).getByRole( 'checkbox' ) ); + const toolbar = page.elementLocator( + document.querySelector( '.dataviews-bulk-actions' )! + ); + await user.click( toolbar.getByRole( 'button', { name: /^Trash/ } ) ); + await user.click( + page.getByRole( 'button', { name: 'Confirm and refetch' } ) + ); + + await expect + .element( page.getByText( 'First post' ) ) + .not.toBeInTheDocument(); + // Not the search, which it would be while the layout is inert. + await expect.element( selectAll() ).toHaveFocus(); +} ); + +it( 'moves focus to "Select all" once the busy button of an action goes', async () => { + const user = userEvent.setup(); + await render( + + ); + await user.click( row( 'First post' ).getByRole( 'checkbox' ) ); + await user.click( row( 'Locked post' ).getByRole( 'checkbox' ) ); + const toolbar = page.elementLocator( + document.querySelector( '.dataviews-bulk-actions' )! + ); + await user.click( + toolbar.getByRole( 'button', { name: 'Remove slowly' } ) + ); + + await expect + .element( page.getByText( 'First post' ) ) + .not.toBeInTheDocument(); + await expect.element( selectAll() ).toHaveFocus(); +} ); + +it( 'moves focus to the search once an action with a busy button removes every item', async () => { + const user = userEvent.setup(); + await render( ); + await user.click( selectAll() ); + const toolbar = page.elementLocator( + document.querySelector( '.dataviews-bulk-actions' )! + ); + // The toolbar goes with the items once the action ends. + await user.click( + toolbar.getByRole( 'button', { name: 'Remove slowly' } ) + ); + + await expect + .element( page.getByText( 'Third post' ) ) + .not.toBeInTheDocument(); + await expect.element( page.getByRole( 'searchbox' ) ).toHaveFocus(); +} ); + +it( 'moves focus to the first item of a list when no checkbox is left', async () => { + const user = userEvent.setup(); + await render( ); + await user.click( + page.getByRole( 'button', { name: 'First post', exact: true } ) + ); + await user.click( page.getByRole( 'button', { name: /^Trash/ } ).first() ); + await user.click( page.getByRole( 'button', { name: 'Confirm' } ) ); + + await expect + .element( page.getByText( 'First post' ) ) + .not.toBeInTheDocument(); + await expect + .element( + page.getByRole( 'button', { name: 'Second post', exact: true } ) + ) + .toHaveFocus(); +} ); + +it( 'leaves focus alone when the action keeps the item', async () => { + const user = userEvent.setup(); + await render( ); + const actionsButton = row( 'First post' ).getByRole( 'button', { + name: 'Actions', + } ); + await user.click( actionsButton ); + await user.click( page.getByRole( 'menuitem', { name: 'Do nothing' } ) ); + + await expect.element( actionsButton ).toHaveFocus(); +} ); + +it( 'stops waiting once the user moved to another control in the view', async () => { + const user = userEvent.setup(); + await render( ); + await user.click( + row( 'First post' ).getByRole( 'button', { name: 'Actions' } ) + ); + await user.click( page.getByRole( 'menuitem', { name: 'Remove now' } ) ); + // Before the item goes. + const search = page.getByRole( 'searchbox' ); + await user.click( search ); + await expect + .element( page.getByText( 'First post' ) ) + .not.toBeInTheDocument(); + await expect.element( search ).toHaveFocus(); + + // Later, focus is lost for another reason and the page changes. + ( search.element() as HTMLElement ).blur(); + document.body.append( document.createElement( 'div' ) ); + await new Promise( ( resolve ) => setTimeout( resolve, 100 ) ); + + await expect.element( selectAll() ).not.toHaveFocus(); +} ); + +it( 'stops waiting once focus is on a disabled control the action does not hold', async () => { + const user = userEvent.setup(); + await render( ); + await user.click( + row( 'First post' ).getByRole( 'button', { name: 'Actions' } ) + ); + await user.click( page.getByRole( 'menuitem', { name: 'Do nothing' } ) ); + // The items of the first page go from the view, and the button is + // disabled on the last page. + const next = page.getByRole( 'button', { name: 'Next page' } ); + await user.click( next ); + await expect.element( page.getByText( 'Third post' ) ).toBeVisible(); + + ( next.element() as HTMLElement ).blur(); + document.body.append( document.createElement( 'div' ) ); + await new Promise( ( resolve ) => setTimeout( resolve, 100 ) ); + + await expect.element( selectAll() ).not.toHaveFocus(); +} ); + +it( 'waits for the busy actions menu of a small screen', async () => { + await page.viewport( 600, 900 ); + const user = userEvent.setup(); + await render( ); + await user.click( selectAll() ); + const toolbar = page.elementLocator( + document.querySelector( '.dataviews-bulk-actions' )! + ); + await user.click( toolbar.getByRole( 'button', { name: 'Actions' } ) ); + await user.click( page.getByRole( 'menuitem', { name: 'Remove slowly' } ) ); + + await expect + .element( page.getByText( 'Third post' ) ) + .not.toBeInTheDocument(); + await expect.element( page.getByRole( 'searchbox' ) ).toHaveFocus(); +} ); + +it( 'stops waiting once focus is on a disabled bulk action that is not busy', async () => { + const user = userEvent.setup(); + await render( + + ); + await user.click( row( 'Locked post' ).getByRole( 'checkbox' ) ); + await user.click( + row( 'First post' ).getByRole( 'button', { name: 'Actions' } ) + ); + await user.click( + page.getByRole( 'menuitem', { name: 'Remove quietly' } ) + ); + // Before the item goes, focus moves to an action that's just disabled. + const toolbar = page.elementLocator( + document.querySelector( '.dataviews-bulk-actions' )! + ); + const archive = toolbar.getByRole( 'button', { name: 'Archive' } ); + ( archive.element() as HTMLElement ).focus(); + await expect + .element( page.getByText( 'First post' ) ) + .not.toBeInTheDocument(); + + ( archive.element() as HTMLElement ).blur(); + document.body.append( document.createElement( 'div' ) ); + await new Promise( ( resolve ) => setTimeout( resolve, 100 ) ); + + await expect.element( selectAll() ).not.toHaveFocus(); +} ); + +it( 'does not take focus back once the user moved it elsewhere', async () => { + const user = userEvent.setup(); + await render( ); + await user.click( + row( 'First post' ).getByRole( 'button', { name: /^Trash/ } ) + ); + await user.click( page.getByRole( 'button', { name: 'Confirm' } ) ); + await user.click( page.getByRole( 'button', { name: 'Outside' } ) ); + + await expect + .element( page.getByText( 'First post' ) ) + .not.toBeInTheDocument(); + await expect + .element( page.getByRole( 'button', { name: 'Outside' } ) ) + .toHaveFocus(); +} ); diff --git a/packages/dataviews/src/hooks/use-focus-after-action.ts b/packages/dataviews/src/hooks/use-focus-after-action.ts new file mode 100644 index 00000000000000..cca8aaf282e810 --- /dev/null +++ b/packages/dataviews/src/hooks/use-focus-after-action.ts @@ -0,0 +1,214 @@ +import type { RefObject } from 'react'; +import { useRefEffect } from '@wordpress/compose'; +import { useCallback, useLayoutEffect, useRef } from '@wordpress/element'; + +const FOCUSABLE_SELECTOR = + 'button, input, select, textarea, a[href], [tabindex]'; + +// Items of a composite grid (the list and grid layouts) take turns being +// tabbable, so none may be right after the one that was removed. +const ROVING_ITEM_SELECTOR = '[role="grid"] [tabindex="-1"][id]'; + +const DIALOG_SELECTOR = '[role="dialog"], [role="alertdialog"]'; + +function isAvailable( element: HTMLElement ) { + return ( + ! element.hasAttribute( 'disabled' ) && + element.getAttribute( 'aria-disabled' ) !== 'true' && + ! element.closest( '[inert]' ) && + element.getClientRects().length > 0 + ); +} + +function getTabbables( root: HTMLElement ) { + return Array.from( + root.querySelectorAll< HTMLElement >( FOCUSABLE_SELECTOR ) + ).filter( ( element ) => element.tabIndex >= 0 && isAvailable( element ) ); +} + +function getRovingItem( root: HTMLElement ) { + return Array.from( + root.querySelectorAll< HTMLElement >( ROVING_ITEM_SELECTOR ) + ).find( isAvailable ); +} + +function isCheckbox( element: HTMLElement ) { + return ( + ( element as HTMLInputElement ).type === 'checkbox' || + element.getAttribute( 'role' ) === 'checkbox' + ); +} + +// Whether focus is on what the action still holds: its dialog or menu, or +// its busy button in the bulk actions toolbar. +function isHeldByAction( element: Element ) { + return !! element.closest( + `${ DIALOG_SELECTOR }, [role="menu"], [data-dataviews-busy]` + ); +} + +function isFocusLost( ownerDocument: Document ) { + const { activeElement, body } = ownerDocument; + return ! activeElement || activeElement === body; +} + +/** + * Keeps focus in the view when an action removes the control that had it, + * e.g. moving items to the trash removes their rows, along with the action + * buttons and any dialog rendered from them. Focus would otherwise fall back + * to the document body. + * + * Like the bulk actions focus, this only acts on request: running an action + * asks for it, and the request stands until items are removed or the user + * moves focus elsewhere. Once items are gone and the view is done loading (the + * layouts are inert while loading), if focus is lost, it moves to the "Select + * all" checkbox, or else the first control or item of the layout, or else the + * first control of the view, such as the search when no items are left. The + * list then moves it on to the item that followed the removed one. + * + * Some actions remove the items before they end, while focus is still on + * their dialog or busy button. Focus is then lost only once that goes, which + * may be without a render of the view, e.g. when the bulk actions toolbar + * goes too. So until focus lands somewhere, the document is watched for it. + * + * @param options Options. + * @param options.layoutRef The element wrapping the layout. + * @param options.data The items shown. + * @param options.getItemId Returns the ID of an item. + * @param options.isLoading Whether the items are loading. + * + * @return A ref for the element wrapping the whole view, and a function that + * asks to keep focus in the view after an action. + */ +export default function useFocusAfterAction< Item >( { + layoutRef, + data, + getItemId, + isLoading, +}: { + layoutRef: RefObject< HTMLElement | null >; + data: Item[]; + getItemId: ( item: Item ) => string; + isLoading?: boolean; +} ) { + const wrapperRef = useRef< HTMLElement | null >( null ); + // The IDs of the items shown when the action ran. + const requestedIdsRef = useRef< Set< string > | null >( null ); + const isLoadingRef = useRef( isLoading ); + // Watches for focus to be lost once the items went while it was still on + // a control, until it lands somewhere. + const observerRef = useRef< MutationObserver | null >( null ); + + const stopWaiting = useCallback( () => { + observerRef.current?.disconnect(); + observerRef.current = null; + }, [] ); + + const moveFocus = useCallback( () => { + const wrapper = wrapperRef.current; + if ( ! wrapper || ! isFocusLost( wrapper.ownerDocument ) ) { + return; + } + const layout = layoutRef.current; + const layoutControls = layout ? getTabbables( layout ) : []; + const target = + layoutControls.find( isCheckbox ) ?? + layoutControls[ 0 ] ?? + ( layout && getRovingItem( layout ) ) ?? + getTabbables( wrapper )[ 0 ]; + target?.focus(); + }, [ layoutRef ] ); + + // Moves focus if it's lost and the view is done loading. Keeps waiting + // while the action still holds focus, and stops once focus is elsewhere. + const settle = useCallback( () => { + const wrapper = wrapperRef.current; + if ( ! wrapper ) { + return; + } + const { activeElement } = wrapper.ownerDocument; + if ( ! isFocusLost( wrapper.ownerDocument ) ) { + if ( activeElement && ! isHeldByAction( activeElement ) ) { + stopWaiting(); + } + return; + } + if ( isLoadingRef.current ) { + return; + } + stopWaiting(); + moveFocus(); + }, [ moveFocus, stopWaiting ] ); + + const ref = useRefEffect( + ( wrapper: HTMLElement ) => { + wrapperRef.current = wrapper; + const { ownerDocument } = wrapper; + const onFocusIn = ( event: FocusEvent ) => { + const target = event.target as Element; + // Focus landed somewhere once the action ended. + if ( target instanceof Element && ! isHeldByAction( target ) ) { + stopWaiting(); + } + // The request stands while focus is in the view, or in a + // dialog or menu the action opened. + if ( + wrapper.contains( target ) || + target.closest?.( `${ DIALOG_SELECTOR }, [role="menu"]` ) + ) { + return; + } + requestedIdsRef.current = null; + }; + ownerDocument.addEventListener( 'focusin', onFocusIn ); + return () => { + ownerDocument.removeEventListener( 'focusin', onFocusIn ); + stopWaiting(); + wrapperRef.current = null; + }; + }, + [ stopWaiting ] + ); + + // Layout effects run before the effects of ancestors, such as a router + // that moves focus when a navigation removes the focused element. + useLayoutEffect( () => { + isLoadingRef.current = isLoading; + const wrapper = wrapperRef.current; + if ( ! wrapper || isLoading ) { + return; + } + if ( observerRef.current ) { + settle(); + return; + } + const requestedIds = requestedIdsRef.current; + if ( ! requestedIds ) { + return; + } + const ids = new Set( data.map( getItemId ) ); + if ( ! [ ...requestedIds ].some( ( id ) => ! ids.has( id ) ) ) { + return; + } + requestedIdsRef.current = null; + if ( isFocusLost( wrapper.ownerDocument ) ) { + moveFocus(); + return; + } + const { ownerDocument } = wrapper; + const observer = new MutationObserver( settle ); + observer.observe( ownerDocument.body, { + childList: true, + subtree: true, + } ); + observerRef.current = observer; + settle(); + }, [ data, getItemId, isLoading, moveFocus, settle ] ); + + const request = useCallback( () => { + stopWaiting(); + requestedIdsRef.current = new Set( data.map( getItemId ) ); + }, [ data, getItemId, stopWaiting ] ); + + return { ref, request }; +} diff --git a/test/e2e/specs/site-editor/page-list.spec.js b/test/e2e/specs/site-editor/page-list.spec.js index 7ee2e596d65849..f5d24cbc607a95 100644 --- a/test/e2e/specs/site-editor/page-list.spec.js +++ b/test/e2e/specs/site-editor/page-list.spec.js @@ -650,6 +650,39 @@ test.describe( 'Page List', () => { } ); } ); + test.describe( 'Trash', () => { + test.afterAll( async ( { requestUtils } ) => { + await requestUtils.deleteAllPages(); + await createPages( requestUtils ); + } ); + + test( 'keeps focus in the list after trashing a page', async ( { + page, + } ) => { + await page.getByRole( 'button', { name: 'Layout' } ).click(); + await page.getByRole( 'menuitemradio', { name: 'Table' } ).click(); + const table = page.getByRole( 'table' ); + const row = table + .getByRole( 'row' ) + .filter( { hasText: 'Sample Page' } ); + await row + .getByRole( 'button', { name: 'Trash', exact: true } ) + .click(); + await page + .getByRole( 'dialog' ) + .getByRole( 'button', { name: 'Trash', exact: true } ) + .click(); + + await expect( row ).toBeHidden(); + await expect( + table.getByRole( 'checkbox', { + name: 'Select all', + exact: true, + } ) + ).toBeFocused(); + } ); + } ); + test.describe( 'Quick Edit Date Timezone Consistency', () => { const PAGE_DATE_GMT = '2026-02-15T17:30:00'; const PAGE_TITLE = 'Timezone Test Page';