From be48daae2abfc825afd5bd1a5cf8e16a08d69b05 Mon Sep 17 00:00:00 2001 From: Marco Ciampini Date: Tue, 8 Oct 2024 14:31:22 +0200 Subject: [PATCH] Global styles: leave screen if current shadow entry gets deleted (#65935) * Global styles: leave screen if current shadow entry gets deleted * Refine approach * Apply feedback --- Co-authored-by: ciampo Co-authored-by: t-hamano Co-authored-by: tyxla Co-authored-by: nith53 Co-authored-by: benniledl --- .../global-styles/shadows-edit-panel.js | 26 +++++++++++++++---- 1 file changed, 21 insertions(+), 5 deletions(-) diff --git a/packages/edit-site/src/components/global-styles/shadows-edit-panel.js b/packages/edit-site/src/components/global-styles/shadows-edit-panel.js index 61bed62cff3d64..af5f3445a51190 100644 --- a/packages/edit-site/src/components/global-styles/shadows-edit-panel.js +++ b/packages/edit-site/src/components/global-styles/shadows-edit-panel.js @@ -35,7 +35,7 @@ import { reset, moreVertical, } from '@wordpress/icons'; -import { useState, useMemo } from '@wordpress/element'; +import { useState, useMemo, useEffect } from '@wordpress/element'; /** * Internal dependencies @@ -73,12 +73,30 @@ const presetShadowMenuItems = [ export default function ShadowsEditPanel() { const { + goBack, params: { category, slug }, - goTo, } = useNavigator(); const [ shadows, setShadows ] = useGlobalSetting( `shadow.presets.${ category }` ); + + useEffect( () => { + const hasCurrentShadow = shadows?.some( + ( shadow ) => shadow.slug === slug + ); + // If the shadow being edited doesn't exist anymore in the global styles setting, navigate back + // to prevent the user from editing a non-existent shadow entry. + // This can happen, for example: + // - when the user deletes the shadow + // - when the user resets the styles while editing a custom shadow + // + // The check on the slug is necessary to prevent a double back navigation when the user triggers + // a backward navigation by interacting with the screen's UI. + if ( !! slug && ! hasCurrentShadow ) { + goBack(); + } + }, [ shadows, slug, goBack ] ); + const [ baseShadows ] = useGlobalSetting( `shadow.presets.${ category }`, undefined, @@ -123,9 +141,7 @@ export default function ShadowsEditPanel() { }; const handleShadowDelete = () => { - const updatedShadows = shadows.filter( ( s ) => s.slug !== slug ); - setShadows( updatedShadows ); - goTo( `/shadows` ); + setShadows( shadows.filter( ( s ) => s.slug !== slug ) ); }; const handleShadowRename = ( newName ) => {