Created
June 26, 2023 14:43
-
-
Save Luehrsen/15c0c7e485a971c321d601da34189b81 to your computer and use it in GitHub Desktop.
WordPress Block Editor: How to avoid switching to the block sidebar when a block is selected.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/** | |
* We want to open the document sidebar when the block is selected. | |
* We want this behavior for our meta block, as all relevant settings | |
* are in the document sidebar. The block sidebar is useless, empty and | |
* distracting. | |
*/ | |
/** | |
* Import dispatch function from the core/edit-post store. | |
*/ | |
const { openGeneralSidebar } = useDispatch('core/edit-post'); | |
/** | |
* Get the current active general sidebar name and the editor sidebar state. | |
* We need to check if the editor sidebar is opened, because we don't want | |
* to open the document sidebar when the editor sidebar is closed. | |
* We also need to check if the block sidebar is opened, because we don't | |
* want to spam the editor with sidebar changes if it is already opened. | |
*/ | |
const { getActiveGeneralSidebarName, isEditorSidebarOpened } = useSelect( | |
(select) => { | |
return { | |
getActiveGeneralSidebarName: | |
select('core/edit-post').getActiveGeneralSidebarName, | |
isEditorSidebarOpened: | |
select('core/edit-post').isEditorSidebarOpened, | |
}; | |
} | |
); | |
/** | |
* Use an effect to open the document sidebar when the block is selected. | |
* We need to check if the block is selected, because this effect will also | |
* run when the block is deselected. We don't want to open the document | |
* sidebar when the block is deselected. | |
* We also need to check if the block sidebar is opened, because we don't | |
* want to spam the editor with sidebar changes if it is already opened. | |
* We also need to check if the document sidebar is already opened, because | |
* we don't want to spam the editor with sidebar changes if it is already | |
* opened. | |
*/ | |
useEffect(() => { | |
/** | |
* Get the name of the current active general sidebar and compare it | |
* to the block sidebar name. | |
*/ | |
const blockSidebarOpened = | |
getActiveGeneralSidebarName() === 'edit-post/block'; | |
/** | |
* If this block is selected AND the block sidebar is active AND the | |
* editor sidebar is opened in general, open the document sidebar. | |
*/ | |
if (isSelected && blockSidebarOpened && isEditorSidebarOpened()) { | |
openGeneralSidebar('edit-post/document'); | |
} | |
}, [ | |
isSelected, | |
openGeneralSidebar, | |
getActiveGeneralSidebarName, | |
isEditorSidebarOpened, | |
]); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment