Skip to content

Commit 98386bd

Browse files
talldanandrewserongjeryj
authored
contentOnly unsynced patterns experiment: Ensure a tab is selected when clicking Edit contents (#71987)
* Ensure a tab is selected when clicking Edit contents * Obey the initialTabName * Ensure initialTab is respected in effect * Refine, avoid call to `setSelectedTabId` that is not needed ---- Co-authored-by: talldan <talldanwp@git.wordpress.org> Co-authored-by: andrewserong <andrewserong@git.wordpress.org> Co-authored-by: jeryj <jeryj@git.wordpress.org>
1 parent 052d68c commit 98386bd

File tree

1 file changed

+33
-1
lines changed
  • packages/block-editor/src/components/inspector-controls-tabs

1 file changed

+33
-1
lines changed

packages/block-editor/src/components/inspector-controls-tabs/index.js

Lines changed: 33 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -6,6 +6,7 @@ import {
66
Tooltip,
77
privateApis as componentsPrivateApis,
88
} from '@wordpress/components';
9+
import { useEffect, useState } from '@wordpress/element';
910
import { store as preferencesStore } from '@wordpress/preferences';
1011
import { useSelect } from '@wordpress/data';
1112

@@ -43,9 +44,40 @@ export default function InspectorControlsTabs( {
4344
? TAB_LIST_VIEW.name
4445
: undefined;
4546

47+
const [ selectedTabId, setSelectedTabId ] = useState(
48+
initialTabName ?? tabs[ 0 ]?.name
49+
);
50+
51+
// When the active tab is not amongst the available `tabs`, it indicates
52+
// the list of tabs was changed dynamically with the active one being
53+
// removed. Set the active tab back to the first tab.
54+
useEffect( () => {
55+
// Skip this behavior if `initialTabName` is supplied. In the navigation
56+
// block, the list view tab isn't present in `tabs` initially. The early
57+
// return here prevents the dynamic behavior that follows from overriding
58+
// `initialTabName`.
59+
if ( initialTabName ) {
60+
return;
61+
}
62+
63+
if ( tabs?.length && selectedTabId ) {
64+
const activeTab = tabs.find(
65+
( tab ) => tab.name === selectedTabId
66+
);
67+
if ( ! activeTab ) {
68+
setSelectedTabId( tabs[ 0 ].name );
69+
}
70+
}
71+
}, [ tabs, selectedTabId, initialTabName ] );
72+
4673
return (
4774
<div className="block-editor-block-inspector__tabs">
48-
<Tabs defaultTabId={ initialTabName } key={ clientId }>
75+
<Tabs
76+
defaultTabId={ initialTabName }
77+
selectedTabId={ selectedTabId }
78+
onSelect={ setSelectedTabId }
79+
key={ clientId }
80+
>
4981
<Tabs.TabList>
5082
{ tabs.map( ( tab ) =>
5183
showIconLabels ? (

0 commit comments

Comments
 (0)