MCPcopy Create free account
hub / github.com/adobe/react-spectrum / moveItems

Function moveItems

packages/react-stately/src/data/useTreeData.ts:485–594  ·  view source on GitHub ↗
(
  state: TreeDataState<T>,
  keys: Iterable<Key>,
  toParent: TreeNode<T> | null,
  toIndex: number,
  updateTree: (
    items: TreeNode<T>[],
    key: Key | null,
    update: (node: TreeNode<T>) => TreeNode<T> | null,
    originalMap: Map<Key, TreeNode<T>>
  ) => TreeDataState<T>,
  addNode: (node: TreeNode<T>, map: Map<Key, TreeNode<T>>) => void
)

Source from the content-addressed store, hash-verified

483}
484
485function 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,

Callers 2

moveBeforeFunction · 0.85
moveAfterFunction · 0.85

Calls 6

traversalFunction · 0.85
addNodeFunction · 0.85
updateTreeFunction · 0.85
sliceMethod · 0.80
hasMethod · 0.65
sortMethod · 0.65

Tested by

no test coverage detected