| 483 | } |
| 484 | |
| 485 | function moveItems<T extends object>( |
| 486 | state: TreeDataState<T>, |
| 487 | keys: Iterable<Key>, |
| 488 | toParent: TreeNode<T> | null, |
| 489 | toIndex: number, |
| 490 | updateTree: ( |
| 491 | items: TreeNode<T>[], |
| 492 | key: Key | null, |
| 493 | update: (node: TreeNode<T>) => TreeNode<T> | null, |
| 494 | originalMap: Map<Key, TreeNode<T>> |
| 495 | ) => TreeDataState<T>, |
| 496 | addNode: (node: TreeNode<T>, map: Map<Key, TreeNode<T>>) => void |
| 497 | ): TreeDataState<T> { |
| 498 | let {items, nodeMap} = state; |
| 499 | |
| 500 | let parent = toParent; |
| 501 | let removeKeys = new Set(keys); |
| 502 | while (parent != null) { |
| 503 | if (removeKeys.has(parent.key)) { |
| 504 | throw new Error('Cannot move an item to be a child of itself.'); |
| 505 | } |
| 506 | parent = parent.parentKey != null ? (nodeMap.get(parent.parentKey) ?? null) : null; |
| 507 | } |
| 508 | |
| 509 | let originalToIndex = toIndex; |
| 510 | |
| 511 | let keyArray = Array.isArray(keys) ? keys : [...keys]; |
| 512 | // depth first search to put keys in order |
| 513 | let inOrderKeys: Map<Key, number> = new Map(); |
| 514 | let removedItems: Array<TreeNode<T>> = []; |
| 515 | let newItems = items; |
| 516 | let newMap = nodeMap; |
| 517 | let i = 0; |
| 518 | |
| 519 | function traversal(node, {inorder, postorder}) { |
| 520 | inorder?.(node); |
| 521 | if (node != null) { |
| 522 | for (let child of node.children ?? []) { |
| 523 | traversal(child, {inorder, postorder}); |
| 524 | postorder?.(child); |
| 525 | } |
| 526 | } |
| 527 | } |
| 528 | |
| 529 | function inorder(child) { |
| 530 | // in-order so we add items as we encounter them in the tree, then we can insert them in expected order later |
| 531 | if (keyArray.includes(child.key)) { |
| 532 | inOrderKeys.set(child.key, i++); |
| 533 | } |
| 534 | } |
| 535 | |
| 536 | function postorder(child) { |
| 537 | // remove items and update the tree from the leaves and work upwards toward the root, this way |
| 538 | // we don't copy child node references from parents inadvertently |
| 539 | if (keyArray.includes(child.key)) { |
| 540 | removedItems.push({...newMap.get(child.key)!, parentKey: toParent?.key ?? null}); |
| 541 | let {items: nextItems, nodeMap: nextMap} = updateTree( |
| 542 | newItems, |