Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Interactivity API: Add comments to the deepMerge() function #66220

Merged
merged 2 commits into from
Oct 18, 2024
Merged
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
14 changes: 14 additions & 0 deletions packages/interactivity/src/proxies/state.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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;
}
Expand All @@ -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
);
Expand Down
Loading