( collection: Collection<Node<T>>, selectionManager: SelectionManager )
| 103 | } |
| 104 | |
| 105 | function useFocusedKeyReset<T>( |
| 106 | collection: Collection<Node<T>>, |
| 107 | selectionManager: SelectionManager |
| 108 | ) { |
| 109 | // Reset focused key if that item is deleted from the collection. |
| 110 | const cachedCollection = useRef<Collection<Node<T>> | null>(null); |
| 111 | useEffect(() => { |
| 112 | if ( |
| 113 | selectionManager.focusedKey != null && |
| 114 | !collection.getItem(selectionManager.focusedKey) && |
| 115 | cachedCollection.current |
| 116 | ) { |
| 117 | // Walk forward in the old collection to find the next key that still exists in the new collection. |
| 118 | let key = cachedCollection.current.getKeyAfter(selectionManager.focusedKey); |
| 119 | let nextFocusedKey: Key | null = null; |
| 120 | while (key != null) { |
| 121 | let node = collection.getItem(key); |
| 122 | if (node && node.type === 'item' && !selectionManager.isDisabled(key)) { |
| 123 | nextFocusedKey = key; |
| 124 | break; |
| 125 | } |
| 126 | |
| 127 | key = cachedCollection.current.getKeyAfter(key); |
| 128 | } |
| 129 | |
| 130 | // If no such key exists, walk backward. |
| 131 | if (nextFocusedKey == null) { |
| 132 | key = cachedCollection.current.getKeyBefore(selectionManager.focusedKey); |
| 133 | while (key != null) { |
| 134 | let node = collection.getItem(key); |
| 135 | if (node && node.type === 'item' && !selectionManager.isDisabled(key)) { |
| 136 | nextFocusedKey = key; |
| 137 | break; |
| 138 | } |
| 139 | |
| 140 | key = cachedCollection.current.getKeyBefore(key); |
| 141 | } |
| 142 | } |
| 143 | |
| 144 | selectionManager.setFocusedKey(nextFocusedKey); |
| 145 | } |
| 146 | cachedCollection.current = collection; |
| 147 | }, [collection, selectionManager]); |
| 148 | } |
no test coverage detected