diff --git a/src/edit.js b/src/edit.js index 538f80c..6f81520 100644 --- a/src/edit.js +++ b/src/edit.js @@ -59,7 +59,11 @@ export default function Edit( { attributes, setAttributes, clientId } ) { businessUnitId, } = attributes; - const [ isGlobalChanged, setIsGlobalChanged ] = useState( false ); + // Tracks which of the global settings the user has edited, so that saving + // promotes only those values and leaves the other globals untouched. + const [ changedGlobals, setChangedGlobals ] = useState( () => new Set() ); + const markGlobalChanged = ( key ) => + setChangedGlobals( ( changed ) => new Set( changed ).add( key ) ); const isActiveContext = useSelect( ( select ) => { @@ -116,12 +120,25 @@ export default function Edit( { attributes, setAttributes, clientId } ) { const { insertBlock } = useDispatch( 'core/block-editor' ); const { saveSite } = useDispatch( 'core' ); - const updateDefaults = ( newPortalId, newRegion, newBusinessUnitId ) => - saveSite( { - hubspot_embed_portal_id: newPortalId, - hubspot_embed_region: newRegion, - hubspot_embed_business_unit_id: newBusinessUnitId || 0, - } ); + + // Build the settings payload from the fields the user actually filled in. + // An empty field means "inherit the global default shown as the + // placeholder", so it must not be sent. Sending every field unconditionally + // broke both ways: a blank ID goes over the wire as null, which the settings + // endpoint rejects with rest_invalid_stored_value once the option holds a + // value, aborting the entire save; and coercing a blank to 0 instead + // overwrote a stored global with an empty value. + const globalUpdates = {}; + if ( changedGlobals.has( 'portalId' ) && portalId ) { + globalUpdates.hubspot_embed_portal_id = portalId; + } + if ( changedGlobals.has( 'businessUnitId' ) && businessUnitId ) { + globalUpdates.hubspot_embed_business_unit_id = businessUnitId; + } + if ( changedGlobals.has( 'region' ) && region ) { + globalUpdates.hubspot_embed_region = region; + } + const hasGlobalUpdates = Object.keys( globalUpdates ).length > 0; return (
@@ -139,7 +156,7 @@ export default function Edit( { attributes, setAttributes, clientId } ) { setAttributes( { portalId: isNaN( parsed ) ? null : parsed, } ); - setIsGlobalChanged( true ); + markGlobalChanged( 'portalId' ); } } required={ ! defaultPortalId } /> @@ -152,7 +169,7 @@ export default function Edit( { attributes, setAttributes, clientId } ) { setAttributes( { businessUnitId: isNaN( parsed ) ? null : parsed, } ); - setIsGlobalChanged( true ); + markGlobalChanged( 'businessUnitId' ); } } /> { setAttributes( { region: newRegion } ); - setIsGlobalChanged( true ); + markGlobalChanged( 'region' ); } } /> - { canSetPortalId && isGlobalChanged && ( + { canSetPortalId && hasGlobalUpdates && (