Skip to content

Commit

Permalink
Bring deepmerge changes from #44400 to v5.x
Browse files Browse the repository at this point in the history
  • Loading branch information
jukkatupamaki committed Nov 21, 2024
1 parent f6181da commit 9d56911
Show file tree
Hide file tree
Showing 2 changed files with 15 additions and 2 deletions.
9 changes: 9 additions & 0 deletions packages/mui-utils/src/deepmerge/deepmerge.test.ts
Original file line number Diff line number Diff line change
@@ -1,3 +1,4 @@
import * as React from 'react';
import { expect } from 'chai';
import { runInNewContext } from 'vm';
import deepmerge from './deepmerge';
Expand Down Expand Up @@ -122,4 +123,12 @@ describe('deepmerge', () => {
expect(result).to.deep.equal({ foo: { baz: 'new test' } });
expect(foo).to.deep.equal({ foo: { baz: 'test' } });
});

it('should not deep clone React element', () => {
const element = React.createElement('div', {}, React.createElement('span'));
const element2 = React.createElement('a');
const result = deepmerge({ element }, { element: element2 });

expect(result.element).to.equal(element2);
});
});
8 changes: 6 additions & 2 deletions packages/mui-utils/src/deepmerge/deepmerge.ts
Original file line number Diff line number Diff line change
@@ -1,3 +1,5 @@
import * as React from 'react';

// https://github.com/sindresorhus/is-plain-obj/blob/main/index.js
export function isPlainObject(item: unknown): item is Record<keyof any, unknown> {
if (typeof item !== 'object' || item === null) {
Expand All @@ -19,7 +21,7 @@ export interface DeepmergeOptions {
}

function deepClone<T>(source: T): T | Record<keyof any, unknown> {
if (!isPlainObject(source)) {
if (React.isValidElement(source) || !isPlainObject(source)) {
return source;
}

Expand All @@ -41,7 +43,9 @@ export default function deepmerge<T>(

if (isPlainObject(target) && isPlainObject(source)) {
Object.keys(source).forEach((key) => {
if (
if (React.isValidElement(source[key])) {
(output as Record<keyof any, unknown>)[key] = source[key];
} else if (
isPlainObject(source[key]) &&
// Avoid prototype pollution
Object.prototype.hasOwnProperty.call(target, key) &&
Expand Down

0 comments on commit 9d56911

Please sign in to comment.