From 4b6ee72fa6781d8bfc488738683a6c9f647769b2 Mon Sep 17 00:00:00 2001 From: Kateryna Kodonenko Date: Wed, 8 Oct 2025 16:16:00 +0200 Subject: [PATCH] Avoid focus loss on switching tabs --- src/components/site-content-tabs.tsx | 27 +++++++++++++++++++++++++-- 1 file changed, 25 insertions(+), 2 deletions(-) diff --git a/src/components/site-content-tabs.tsx b/src/components/site-content-tabs.tsx index ee28a7145..4303e9a2d 100644 --- a/src/components/site-content-tabs.tsx +++ b/src/components/site-content-tabs.tsx @@ -1,5 +1,6 @@ import { TabPanel } from '@wordpress/components'; import { useI18n } from '@wordpress/react-i18n'; +import { useEffect, useRef, useState } from 'react'; import { ContentTabAssistant } from 'src/components/content-tab-assistant'; import { ContentTabImportExport } from 'src/components/content-tab-import-export'; import { ContentTabOverview } from 'src/components/content-tab-overview'; @@ -21,6 +22,24 @@ export function SiteContentTabs() { const { tabs, selectedTab, setSelectedTab } = useContentTabs(); const { __ } = useI18n(); + // Remount: Avoid focus loss on user tab changes (no remount), + // but remount on programmatic changes and site switches so initial tab/content state resets. + const [ keyCounter, setKeyCounter ] = useState( 0 ); + const lastChangeWasUser = useRef( false ); + const isFirstRender = useRef( true ); + + useEffect( () => { + if ( isFirstRender.current ) { + isFirstRender.current = false; + return; + } + if ( lastChangeWasUser.current ) { + lastChangeWasUser.current = false; + return; + } + setKeyCounter( ( k ) => k + 1 ); + }, [ selectedTab ] ); + if ( ! localSites.length ) { return ; } @@ -44,9 +63,13 @@ export function SiteContentTabs() { className={ `mt-6 h-full flex flex-col overflow-hidden ${ MIN_WIDTH_CLASS_TO_MEASURE }` } tabs={ tabs } orientation="horizontal" - onSelect={ ( tabName ) => setSelectedTab( tabName as TabName ) } + onSelect={ ( tabName ) => { + // Mark this as a user-initiated change so we don't remount + lastChangeWasUser.current = true; + setSelectedTab( tabName as TabName ); + } } initialTabName={ selectedTab } - key={ selectedTab + selectedSite.id } + key={ `${ selectedSite.id }-${ keyCounter }` } > { ( { name } ) => (