Skip to content

Commit

Permalink
Fix Tree copy by doing a shallow copy of the value (#5081)
Browse files Browse the repository at this point in the history
* Fix Tree copy by doing a shallow copy of the value

* Update cloneValue implementation to be recursive
  • Loading branch information
hugo-vrijswijk authored Oct 12, 2023
1 parent 9841460 commit 8f3e493
Showing 1 changed file with 25 additions and 2 deletions.
27 changes: 25 additions & 2 deletions components/lib/tree/Tree.js
Original file line number Diff line number Diff line change
Expand Up @@ -58,9 +58,32 @@ export const Tree = React.memo(
dragState.current = null;
};

/**
* Deep copy a value. If the value has a data property, it will be shallow copied.
* Values that are not plain objects or arrays are returned as-is.
*/
const cloneValue = (value) => {
if (Array.isArray(value)) {
return value.map(cloneValue);
} else if (!!value && Object.getPrototypeOf(value) === Object.prototype) {
const result = {};

// Leave data property alone and clone children
for (let key in value) {
if (key !== 'data') {
result[key] = cloneValue(value[key]);
} else {
result[key] = value[key];
}
}

return result;
} else return value;
};

const onDrop = (event) => {
if (validateDropNode(dragState.current.path, event.path)) {
let value = JSON.parse(JSON.stringify(props.value));
const value = cloneValue(props.value);
let dragPaths = dragState.current.path.split('-');

dragPaths.pop();
Expand Down Expand Up @@ -89,7 +112,7 @@ export const Tree = React.memo(

const onDropPoint = (event) => {
if (validateDropPoint(event)) {
let value = JSON.parse(JSON.stringify(props.value));
const value = cloneValue(props.value);
let dragPaths = dragState.current.path.split('-');

dragPaths.pop();
Expand Down

0 comments on commit 8f3e493

Please sign in to comment.