From 0ae2cb8e520292f2726fa6c63676b91333819168 Mon Sep 17 00:00:00 2001 From: Michal Date: Fri, 18 Oct 2024 16:53:01 +0100 Subject: [PATCH] iAPI: Add comments to the `deepMerge()` function (#66220) * update comment * Add comments Co-authored-by: michalczaplinski Co-authored-by: DAreRodz --- packages/interactivity/src/proxies/state.ts | 14 ++++++++++++++ 1 file changed, 14 insertions(+) diff --git a/packages/interactivity/src/proxies/state.ts b/packages/interactivity/src/proxies/state.ts index d4d573acba884..f9af257bada2e 100644 --- a/packages/interactivity/src/proxies/state.ts +++ b/packages/interactivity/src/proxies/state.ts @@ -300,6 +300,8 @@ const deepMergeRecursive = ( source: any, override: boolean = true ) => { + // If target is not a plain object and the source is, we don't need to merge + // them because the source will be used as the new value of the target. if ( ! ( isPlainObject( target ) && isPlainObject( source ) ) ) { return; } @@ -317,38 +319,50 @@ const deepMergeRecursive = ( hasPropSignal( proxy, key ) && getPropSignal( proxy, key ); + // Handle getters and setters if ( typeof desc.get === 'function' || typeof desc.set === 'function' ) { if ( override || isNew ) { + // Because we are setting a getter or setter, we need to use + // Object.defineProperty to define the property on the target object. Object.defineProperty( target, key, { ...desc, configurable: true, enumerable: true, } ); + // Update the getter in the property signal if it exists if ( desc.get && propSignal ) { propSignal.setGetter( desc.get ); } } + + // Handle nested objects } else if ( isPlainObject( source[ key ] ) ) { if ( isNew || ( override && ! isPlainObject( target[ key ] ) ) ) { + // Create a new object if the property is new or needs to be overridden target[ key ] = {}; if ( propSignal ) { + // Create a new proxified state for the nested object const ns = getNamespaceFromProxy( proxy ); propSignal.setValue( proxifyState( ns, target[ key ] as Object ) ); } } + // Both target and source are plain objects, merge them recursively if ( isPlainObject( target[ key ] ) ) { deepMergeRecursive( target[ key ], source[ key ], override ); } + + // Handle primitive values and non-plain objects } else if ( override || isNew ) { Object.defineProperty( target, key, desc ); if ( propSignal ) { const { value } = desc; const ns = getNamespaceFromProxy( proxy ); + // Proxify the value if necessary before setting it in the signal propSignal.setValue( shouldProxy( value ) ? proxifyState( ns, value ) : value );