@react-stately/data 3.15.1 → 3.16.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -1,540 +0,0 @@
1
- /*
2
- * Copyright 2020 Adobe. All rights reserved.
3
- * This file is licensed to you under the Apache License, Version 2.0 (the "License");
4
- * you may not use this file except in compliance with the License. You may obtain a copy
5
- * of the License at http://www.apache.org/licenses/LICENSE-2.0
6
- *
7
- * Unless required by applicable law or agreed to in writing, software distributed under
8
- * the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR REPRESENTATIONS
9
- * OF ANY KIND, either express or implied. See the License for the specific language
10
- * governing permissions and limitations under the License.
11
- */
12
-
13
- import {Key} from '@react-types/shared';
14
- import {useState} from 'react';
15
-
16
- export interface TreeOptions<T extends object> {
17
- /** Initial root items in the tree. */
18
- initialItems?: T[],
19
- /** The keys for the initially selected items. */
20
- initialSelectedKeys?: Iterable<Key>,
21
- /** A function that returns a unique key for an item object. */
22
- getKey?: (item: T) => Key,
23
- /** A function that returns the children for an item object. */
24
- getChildren?: (item: T) => T[]
25
- }
26
-
27
- interface TreeNode<T extends object> {
28
- /** A unique key for the tree node. */
29
- key: Key,
30
- /** The key of the parent node. */
31
- parentKey?: Key | null,
32
- /** The value object for the tree node. */
33
- value: T,
34
- /** Children of the tree node. */
35
- children: TreeNode<T>[] | null
36
- }
37
-
38
- export interface TreeData<T extends object> {
39
- /** The root nodes in the tree. */
40
- items: TreeNode<T>[],
41
-
42
- /** The keys of the currently selected items in the tree. */
43
- selectedKeys: Set<Key>,
44
-
45
- /** Sets the selected keys. */
46
- setSelectedKeys(keys: Set<Key>): void,
47
-
48
- /**
49
- * Gets a node from the tree by key.
50
- * @param key - The key of the item to retrieve.
51
- */
52
- getItem(key: Key): TreeNode<T> | undefined,
53
-
54
- /**
55
- * Inserts an item into a parent node as a child.
56
- * @param parentKey - The key of the parent item to insert into. `null` for the root.
57
- * @param index - The index within the parent to insert into.
58
- * @param value - The value to insert.
59
- */
60
- insert(parentKey: Key | null, index: number, ...values: T[]): void,
61
-
62
- /**
63
- * Inserts items into the list before the item at the given key.
64
- * @param key - The key of the item to insert before.
65
- * @param values - The values to insert.
66
- */
67
- insertBefore(key: Key, ...values: T[]): void,
68
-
69
- /**
70
- * Inserts items into the list after the item at the given key.
71
- * @param key - The key of the item to insert after.
72
- * @param values - The values to insert.
73
- */
74
- insertAfter(key: Key, ...values: T[]): void,
75
-
76
- /**
77
- * Appends an item into a parent node as a child.
78
- * @param parentKey - The key of the parent item to insert into. `null` for the root.
79
- * @param value - The value to insert.
80
- */
81
- append(parentKey: Key | null, ...values: T[]): void,
82
-
83
- /**
84
- * Prepends an item into a parent node as a child.
85
- * @param parentKey - The key of the parent item to insert into. `null` for the root.
86
- * @param value - The value to insert.
87
- */
88
- prepend(parentKey: Key | null, ...value: T[]): void,
89
-
90
- /**
91
- * Removes an item from the tree by its key.
92
- * @param key - The key of the item to remove.
93
- */
94
- remove(...keys: Key[]): void,
95
-
96
- /**
97
- * Removes all items from the tree that are currently
98
- * in the set of selected items.
99
- */
100
- removeSelectedItems(): void,
101
-
102
- /**
103
- * Moves an item within the tree.
104
- * @param key - The key of the item to move.
105
- * @param toParentKey - The key of the new parent to insert into. `null` for the root.
106
- * @param index - The index within the new parent to insert at.
107
- */
108
- move(key: Key, toParentKey: Key | null, index: number): void,
109
-
110
- /**
111
- * Moves one or more items before a given key.
112
- * @param key - The key of the item to move the items before.
113
- * @param keys - The keys of the items to move.
114
- */
115
- moveBefore(key: Key, keys: Iterable<Key>): void,
116
-
117
- /**
118
- * Moves one or more items after a given key.
119
- * @param key - The key of the item to move the items after.
120
- * @param keys - The keys of the items to move.
121
- */
122
- moveAfter(key: Key, keys: Iterable<Key>): void,
123
-
124
- /**
125
- * Updates an item in the tree.
126
- * @param key - The key of the item to update.
127
- * @param newValue - The new value for the item.
128
- */
129
- update(key: Key, newValue: T): void
130
- }
131
-
132
- interface TreeDataState<T extends object> {
133
- items: TreeNode<T>[],
134
- nodeMap: Map<Key, TreeNode<T>>
135
- }
136
-
137
- /**
138
- * Manages state for an immutable tree data structure, and provides convenience methods to
139
- * update the data over time.
140
- */
141
- export function useTreeData<T extends object>(options: TreeOptions<T>): TreeData<T> {
142
- let {
143
- initialItems = [],
144
- initialSelectedKeys,
145
- getKey = (item: any) => item.id ?? item.key,
146
- getChildren = (item: any) => item.children
147
- } = options;
148
-
149
- // We only want to compute this on initial render.
150
- let [tree, setItems] = useState<TreeDataState<T>>(() => buildTree(initialItems, new Map()));
151
- let {items, nodeMap} = tree;
152
-
153
- let [selectedKeys, setSelectedKeys] = useState(new Set<Key>(initialSelectedKeys || []));
154
-
155
- function buildTree(initialItems: T[] | null = [], map: Map<Key, TreeNode<T>>, parentKey?: Key | null) {
156
- if (initialItems == null) {
157
- initialItems = [];
158
- }
159
- return {
160
- items: initialItems.map(item => {
161
- let node: TreeNode<T> = {
162
- key: getKey(item),
163
- parentKey: parentKey ?? null,
164
- value: item,
165
- children: null
166
- };
167
-
168
- node.children = buildTree(getChildren(item), map, node.key).items;
169
- map.set(node.key, node);
170
- return node;
171
- }),
172
- nodeMap: map
173
- };
174
- }
175
-
176
- function updateTree(items: TreeNode<T>[], key: Key | null, update: (node: TreeNode<T>) => TreeNode<T> | null, originalMap: Map<Key, TreeNode<T>>) {
177
- let node = key == null ? null : originalMap.get(key);
178
- if (node == null) {
179
- return {items, nodeMap: originalMap};
180
- }
181
- let map = new Map<Key, TreeNode<T>>(originalMap);
182
-
183
- // Create a new node. If null, then delete the node, otherwise replace.
184
- let newNode = update(node);
185
- if (newNode == null) {
186
- deleteNode(node, map);
187
- } else {
188
- addNode(newNode, map);
189
- }
190
-
191
- // Walk up the tree and update each parent to refer to the new children.
192
- while (node && node.parentKey) {
193
- let nextParent = map.get(node.parentKey)!;
194
- let copy: TreeNode<T> = {
195
- key: nextParent.key,
196
- parentKey: nextParent.parentKey,
197
- value: nextParent.value,
198
- children: null
199
- };
200
-
201
- let children = nextParent.children;
202
- if (newNode == null && children) {
203
- children = children.filter(c => c !== node);
204
- }
205
-
206
- copy.children = children?.map(child => {
207
- if (child === node) {
208
- // newNode cannot be null here due to the above filter.
209
- return newNode!;
210
- }
211
-
212
- return child;
213
- }) ?? null;
214
-
215
- map.set(copy.key, copy);
216
-
217
- newNode = copy;
218
- node = nextParent;
219
- }
220
-
221
- if (newNode == null) {
222
- items = items.filter(c => c !== node);
223
- }
224
-
225
- return {
226
- items: items.map(item => {
227
- if (item === node) {
228
- // newNode cannot be null here due to the above filter.
229
- return newNode!;
230
- }
231
-
232
- return item;
233
- }),
234
- nodeMap: map
235
- };
236
- }
237
-
238
- function addNode(node: TreeNode<T>, map: Map<Key, TreeNode<T>>) {
239
- map.set(node.key, node);
240
- if (node.children) {
241
- for (let child of node.children) {
242
- addNode(child, map);
243
- }
244
- }
245
- }
246
-
247
- function deleteNode(node: TreeNode<T>, map: Map<Key, TreeNode<T>>) {
248
- map.delete(node.key);
249
- if (node.children) {
250
- for (let child of node.children) {
251
- deleteNode(child, map);
252
- }
253
- }
254
- }
255
- return {
256
- items,
257
- selectedKeys,
258
- setSelectedKeys,
259
- getItem(key: Key) {
260
- return nodeMap.get(key);
261
- },
262
- insert(parentKey: Key | null, index: number, ...values: T[]) {
263
- setItems(({items, nodeMap: originalMap}) => {
264
- let {items: newNodes, nodeMap: newMap} = buildTree(values, originalMap, parentKey);
265
-
266
- // If parentKey is null, insert into the root.
267
- if (parentKey == null) {
268
- return {
269
- items: [
270
- ...items.slice(0, index),
271
- ...newNodes,
272
- ...items.slice(index)
273
- ],
274
- nodeMap: newMap
275
- };
276
- }
277
-
278
- // Otherwise, update the parent node and its ancestors.
279
- return updateTree(items, parentKey, parentNode => ({
280
- key: parentNode.key,
281
- parentKey: parentNode.parentKey,
282
- value: parentNode.value,
283
- children: [
284
- ...parentNode.children!.slice(0, index),
285
- ...newNodes,
286
- ...parentNode.children!.slice(index)
287
- ]
288
- }), newMap);
289
- });
290
- },
291
- insertBefore(key: Key, ...values: T[]): void {
292
- let node = nodeMap.get(key);
293
- if (!node) {
294
- return;
295
- }
296
-
297
- let parentNode = nodeMap.get(node.parentKey!);
298
- let nodes = parentNode ? parentNode.children : items;
299
- let index = nodes!.indexOf(node);
300
- this.insert(parentNode?.key ?? null, index, ...values);
301
- },
302
- insertAfter(key: Key, ...values: T[]): void {
303
- let node = nodeMap.get(key);
304
- if (!node) {
305
- return;
306
- }
307
-
308
- let parentNode = nodeMap.get(node.parentKey!);
309
- let nodes = parentNode ? parentNode.children : items;
310
- let index = nodes!.indexOf(node);
311
- this.insert(parentNode?.key ?? null, index + 1, ...values);
312
- },
313
- prepend(parentKey: Key | null, ...values: T[]) {
314
- this.insert(parentKey, 0, ...values);
315
- },
316
- append(parentKey: Key | null, ...values: T[]) {
317
- if (parentKey == null) {
318
- this.insert(null, items.length, ...values);
319
- } else {
320
- let parentNode = nodeMap.get(parentKey);
321
- if (!parentNode) {
322
- return;
323
- }
324
-
325
- this.insert(parentKey, parentNode.children!.length, ...values);
326
- }
327
- },
328
- remove(...keys: Key[]) {
329
- if (keys.length === 0) {
330
- return;
331
- }
332
-
333
- let newItems = items;
334
- let prevMap = nodeMap;
335
- let newTree;
336
- for (let key of keys) {
337
- newTree = updateTree(newItems, key, () => null, prevMap);
338
- prevMap = newTree.nodeMap;
339
- newItems = newTree.items;
340
- }
341
-
342
- setItems(newTree);
343
-
344
- let selection = new Set(selectedKeys);
345
- for (let key of selectedKeys) {
346
- if (!newTree.nodeMap.has(key)) {
347
- selection.delete(key);
348
- }
349
- }
350
-
351
- setSelectedKeys(selection);
352
- },
353
- removeSelectedItems() {
354
- this.remove(...selectedKeys);
355
- },
356
- move(key: Key, toParentKey: Key | null, index: number) {
357
- setItems(({items, nodeMap: originalMap}) => {
358
- let node = originalMap.get(key);
359
- if (!node) {
360
- return {items, nodeMap: originalMap};
361
- }
362
-
363
- let {items: newItems, nodeMap: newMap} = updateTree(items, key, () => null, originalMap);
364
-
365
-
366
- const movedNode = {
367
- ...node,
368
- parentKey: toParentKey
369
- };
370
-
371
- // If parentKey is null, insert into the root.
372
- if (toParentKey == null) {
373
- addNode(movedNode, newMap);
374
- return {items: [
375
- ...newItems.slice(0, index),
376
- movedNode,
377
- ...newItems.slice(index)
378
- ], nodeMap: newMap};
379
- }
380
-
381
- // Otherwise, update the parent node and its ancestors.
382
- return updateTree(newItems, toParentKey, parentNode => ({
383
- key: parentNode.key,
384
- parentKey: parentNode.parentKey,
385
- value: parentNode.value,
386
- children: [
387
- ...parentNode.children!.slice(0, index),
388
- movedNode,
389
- ...parentNode.children!.slice(index)
390
- ]
391
- }), newMap);
392
- });
393
- },
394
- moveBefore(key: Key, keys: Iterable<Key>) {
395
- setItems((prevState) => {
396
- let {items, nodeMap} = prevState;
397
- let node = nodeMap.get(key);
398
- if (!node) {
399
- return prevState;
400
- }
401
- let toParentKey = node.parentKey ?? null;
402
- let parent: null | TreeNode<T> = null;
403
- if (toParentKey != null) {
404
- parent = nodeMap.get(toParentKey) ?? null;
405
- }
406
- let toIndex = parent?.children ? parent.children.indexOf(node) : items.indexOf(node);
407
- return moveItems(prevState, keys, parent, toIndex, updateTree, addNode);
408
- });
409
- },
410
- moveAfter(key: Key, keys: Iterable<Key>) {
411
- setItems((prevState) => {
412
- let {items, nodeMap} = prevState;
413
- let node = nodeMap.get(key);
414
- if (!node) {
415
- return prevState;
416
- }
417
- let toParentKey = node.parentKey ?? null;
418
- let parent: null | TreeNode<T> = null;
419
- if (toParentKey != null) {
420
- parent = nodeMap.get(toParentKey) ?? null;
421
- }
422
- let toIndex = parent?.children ? parent.children.indexOf(node) : items.indexOf(node);
423
- toIndex++;
424
- return moveItems(prevState, keys, parent, toIndex, updateTree, addNode);
425
- });
426
- },
427
- update(oldKey: Key, newValue: T) {
428
- setItems(({items, nodeMap: originalMap}) => updateTree(items, oldKey, oldNode => {
429
- let node: TreeNode<T> = {
430
- key: oldNode.key,
431
- parentKey: oldNode.parentKey,
432
- value: newValue,
433
- children: null
434
- };
435
-
436
- let tree = buildTree(getChildren(newValue), originalMap, node.key);
437
- node.children = tree.items;
438
- return node;
439
- }, originalMap));
440
- }
441
- };
442
- }
443
-
444
- function moveItems<T extends object>(
445
- state: TreeDataState<T>,
446
- keys: Iterable<Key>,
447
- toParent: TreeNode<T> | null,
448
- toIndex: number,
449
- updateTree: (
450
- items: TreeNode<T>[],
451
- key: Key | null,
452
- update: (node: TreeNode<T>) => TreeNode<T> | null,
453
- originalMap: Map<Key, TreeNode<T>>
454
- ) => TreeDataState<T>,
455
- addNode: (node: TreeNode<T>, map: Map<Key, TreeNode<T>>) => void
456
- ): TreeDataState<T> {
457
- let {items, nodeMap} = state;
458
-
459
- let parent = toParent;
460
- let removeKeys = new Set(keys);
461
- while (parent?.parentKey != null) {
462
- if (removeKeys.has(parent.key)) {
463
- throw new Error('Cannot move an item to be a child of itself.');
464
- }
465
- parent = nodeMap.get(parent.parentKey!) ?? null;
466
- }
467
-
468
- let originalToIndex = toIndex;
469
-
470
- let keyArray = Array.isArray(keys) ? keys : [...keys];
471
- // depth first search to put keys in order
472
- let inOrderKeys: Map<Key, number> = new Map();
473
- let removedItems: Array<TreeNode<T>> = [];
474
- let newItems = items;
475
- let newMap = nodeMap;
476
- let i = 0;
477
-
478
- function traversal(node, {inorder, postorder}) {
479
- inorder?.(node);
480
- if (node != null) {
481
- for (let child of node.children ?? []) {
482
- traversal(child, {inorder, postorder});
483
- postorder?.(child);
484
- }
485
- }
486
- }
487
-
488
- function inorder(child) {
489
- // in-order so we add items as we encounter them in the tree, then we can insert them in expected order later
490
- if (keyArray.includes(child.key)) {
491
- inOrderKeys.set(child.key, i++);
492
- }
493
- }
494
-
495
- function postorder(child) {
496
- // remove items and update the tree from the leaves and work upwards toward the root, this way
497
- // we don't copy child node references from parents inadvertently
498
- if (keyArray.includes(child.key)) {
499
- removedItems.push({...newMap.get(child.key)!, parentKey: toParent?.key ?? null});
500
- let {items: nextItems, nodeMap: nextMap} = updateTree(newItems, child.key, () => null, newMap);
501
- newItems = nextItems;
502
- newMap = nextMap;
503
- }
504
- // decrement the index if the child being removed is in the target parent and before the target index
505
- // the root node is special, it is null, and will not have a key, however, a parentKey can still point to it
506
- if ((child.parentKey === toParent
507
- || child.parentKey === toParent?.key)
508
- && keyArray.includes(child.key)
509
- && (toParent?.children ? toParent.children.indexOf(child) : items.indexOf(child)) < originalToIndex) {
510
- toIndex--;
511
- }
512
- }
513
-
514
- traversal({children: items}, {inorder, postorder});
515
-
516
- let inOrderItems = removedItems.sort((a, b) => inOrderKeys.get(a.key)! > inOrderKeys.get(b.key)! ? 1 : -1);
517
- // If parentKey is null, insert into the root.
518
- if (!toParent || toParent.key == null) {
519
- inOrderItems.forEach(movedNode => {
520
- addNode(movedNode, newMap);
521
- });
522
- return {items: [
523
- ...newItems.slice(0, toIndex),
524
- ...inOrderItems,
525
- ...newItems.slice(toIndex)
526
- ], nodeMap: newMap};
527
- }
528
-
529
- // Otherwise, update the parent node and its ancestors.
530
- return updateTree(newItems, toParent.key, parentNode => ({
531
- key: parentNode.key,
532
- parentKey: parentNode.parentKey,
533
- value: parentNode.value,
534
- children: [
535
- ...parentNode.children!.slice(0, toIndex),
536
- ...inOrderItems,
537
- ...parentNode.children!.slice(toIndex)
538
- ]
539
- }), newMap);
540
- }