frontend-collective / frontend-collective/react-sortable-tree

changeNodeAtPath function does not work

Open
#458 6 comments 0 reactions 0 assignees View on GitHub
Dominant language
JavaScript
Stars
5k
Forks
914
PR merge metrics
No merged PRs in 30d

Description

export function changeNodeAtPath({
treeData,
path,
newNode,
getNodeKey,
ignoreCollapsed = true,
}) {
const RESULT_MISS = 'RESULT_MISS';
const traverse = ({
isPseudoRoot = false,
node,
currentTreeIndex,
pathIndex,
}) => {
if (
!isPseudoRoot &&
getNodeKey({ node, treeIndex: currentTreeIndex }) !== path[pathIndex]
) {
return RESULT_MISS;
}

if (pathIndex >= path.length - 1) {
// If this is the final location in the path, return its changed form
return typeof newNode === 'function'
? newNode({ node, treeIndex: currentTreeIndex })
: newNode;
}
if (!node.children) {
// If this node is part of the path, but has no children, return the unchanged node
throw new Error('Path referenced children of node with no children.');
}

let nextTreeIndex = currentTreeIndex + 1;
for (let i = 0; i < node.children.length; i += 1) {
const result = traverse({
//["here add is isPseudoRoot"]
node: node.children[i],
currentTreeIndex: nextTreeIndex,
pathIndex: pathIndex + 1,
});

// If the result went down the correct path
if (result !== RESULT_MISS) {
if (result) {
// If the result was truthy (in this case, an object),
// pass it to the next level of recursion up
return {
...node,
children: [
...node.children.slice(0, i),
result,
...node.children.slice(i + 1),
],
};
}
// If the result was falsy (returned from the newNode function), then
// delete the node from the array.
return {
...node,
children: [
...node.children.slice(0, i),
...node.children.slice(i + 1),
],
};
}

nextTreeIndex +=
1 + getDescendantCount({ node: node.children[i], ignoreCollapsed });
}

return RESULT_MISS;
};

// Use a pseudo-root node in the beginning traversal
const result = traverse({
node: { children: treeData },
currentTreeIndex: -1,
pathIndex: -1,
isPseudoRoot: true,
});

if (result === RESULT_MISS) {
throw new Error('No node found at the given path.');
}

return result.children;
}

Recursive function "traverse" dont have the isPseduRoot populated

Contributor guide

No contributing guide indexed for this repository

Research direction

Start with the exported changeNodeAtPath function shown in the issue and inspect how the recursive traverse call handles isPseudoRoot and pathIndex. Reproduce a failing path update, then verify that the function correctly changes or removes the target node without breaking descendant indexing; run the relevant existing test suite if available.

Written by the indexing model from the issue text.

Assessment

Tech stack
javascript
Domain
frontend
Issue type
Bug
Difficulty
2/5
Estimated time
1-3 hours
Activity status
Stale
Clarity
Mostly clear
Newbie friendliness
38/100

Get new issues in your inbox

A short digest of beginner-friendly GitHub issues.