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

Function useTreeData

packages/react-stately/src/data/useTreeData.ts:152–475  ·  view source on GitHub ↗
(options: TreeOptions<T>)

Source from the content-addressed store, hash-verified

150 * update the data over time.
151 */
152export function useTreeData<T extends object>(options: TreeOptions<T>): TreeData<T> {
153 let {
154 initialItems = [],
155 initialSelectedKeys,
156 getKey = (item: any) => item.id ?? item.key,
157 getChildren = (item: any) => item.children
158 } = options;
159
160 // We only want to compute this on initial render.
161 let [tree, setItems] = useState<TreeDataState<T>>(() => buildTree(initialItems, new Map()));
162 let {items, nodeMap} = tree;
163
164 let [selectedKeys, setSelectedKeys] = useState(new Set<Key>(initialSelectedKeys || []));
165
166 // oxlint-disable-next-line react/react-compiler
167 function buildTree(
168 initialItems: T[] | null = [],
169 map: Map<Key, TreeNode<T>>,
170 parentKey?: Key | null
171 ) {
172 if (initialItems == null) {
173 initialItems = [];
174 }
175 return {
176 items: initialItems.map(item => {
177 let node: TreeNode<T> = {
178 key: getKey(item),
179 parentKey: parentKey ?? null,
180 value: item,
181 children: null
182 };
183
184 node.children = buildTree(getChildren(item), map, node.key).items;
185 map.set(node.key, node);
186 return node;
187 }),
188 nodeMap: map
189 };
190 }
191
192 function updateTree(
193 items: TreeNode<T>[],
194 key: Key | null,
195 update: (node: TreeNode<T>) => TreeNode<T> | null,
196 originalMap: Map<Key, TreeNode<T>>
197 ) {
198 let node = key == null ? null : originalMap.get(key);
199 if (node == null) {
200 return {items, nodeMap: originalMap};
201 }
202 let map = new Map<Key, TreeNode<T>>(originalMap);
203
204 // Create a new node. If null, then delete the node, otherwise replace.
205 let newNode = update(node);
206 if (newNode == null) {
207 deleteNode(node, map);
208 } else {
209 addNode(newNode, map);

Callers 15

DnDTreeFunction · 0.90
TableSectionDndFunction · 0.90
TreeGridTableDndFunction · 0.90
ShellExampleFunction · 0.90
TreeExampleDynamicRenderFunction · 0.90
WithLinksRenderFunction · 0.90
LoadingStoryDepOnTopFunction · 0.90
ButtonLoadingIndicatorFunction · 0.90
TreeDragAndDropExampleFunction · 0.90

Calls 1

buildTreeFunction · 0.85

Tested by 1

DnDTreeFunction · 0.72