@react-stately/data 3.0.0-nightly-641446f65-240905

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.
@@ -0,0 +1,385 @@
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,
32
+ /** The value object for the tree node. */
33
+ value: T,
34
+ /** Children of the tree node. */
35
+ children: TreeNode<T>[]
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>,
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
+ * Updates an item in the tree.
112
+ * @param key - The key of the item to update.
113
+ * @param newValue - The new value for the item.
114
+ */
115
+ update(key: Key, newValue: T): void
116
+ }
117
+
118
+ /**
119
+ * Manages state for an immutable tree data structure, and provides convenience methods to
120
+ * update the data over time.
121
+ */
122
+ export function useTreeData<T extends object>(options: TreeOptions<T>): TreeData<T> {
123
+ let {
124
+ initialItems = [],
125
+ initialSelectedKeys,
126
+ getKey = (item: any) => item.id ?? item.key,
127
+ getChildren = (item: any) => item.children
128
+ } = options;
129
+
130
+ // We only want to compute this on initial render.
131
+ let [tree, setItems] = useState<{items: TreeNode<T>[], nodeMap: Map<Key, TreeNode<T>>}>(() => buildTree(initialItems, new Map()));
132
+ let {items, nodeMap} = tree;
133
+
134
+ let [selectedKeys, setSelectedKeys] = useState(new Set<Key>(initialSelectedKeys || []));
135
+
136
+ function buildTree(initialItems: T[] | null = [], map: Map<Key, TreeNode<T>>, parentKey?: Key | null) {
137
+ if (initialItems == null) {
138
+ initialItems = [];
139
+ }
140
+ return {
141
+ items: initialItems.map(item => {
142
+ let node: TreeNode<T> = {
143
+ key: getKey(item),
144
+ parentKey: parentKey,
145
+ value: item,
146
+ children: null
147
+ };
148
+
149
+ node.children = buildTree(getChildren(item), map, node.key).items;
150
+ map.set(node.key, node);
151
+ return node;
152
+ }),
153
+ nodeMap: map
154
+ };
155
+ }
156
+
157
+ function updateTree(items: TreeNode<T>[], key: Key, update: (node: TreeNode<T>) => TreeNode<T>, originalMap: Map<Key, TreeNode<T>>) {
158
+ let node = originalMap.get(key);
159
+ if (!node) {
160
+ return {items, nodeMap: originalMap};
161
+ }
162
+ let map = new Map<Key, TreeNode<T>>(originalMap);
163
+
164
+ // Create a new node. If null, then delete the node, otherwise replace.
165
+ let newNode = update(node);
166
+ if (newNode == null) {
167
+ deleteNode(node, map);
168
+ } else {
169
+ addNode(newNode, map);
170
+ }
171
+
172
+ // Walk up the tree and update each parent to refer to the new children.
173
+ while (node.parentKey) {
174
+ let nextParent = map.get(node.parentKey);
175
+ let copy: TreeNode<T> = {
176
+ key: nextParent.key,
177
+ parentKey: nextParent.parentKey,
178
+ value: nextParent.value,
179
+ children: null
180
+ };
181
+
182
+ let children = nextParent.children;
183
+ if (newNode == null) {
184
+ children = children.filter(c => c !== node);
185
+ }
186
+
187
+ copy.children = children.map(child => {
188
+ if (child === node) {
189
+ return newNode;
190
+ }
191
+
192
+ return child;
193
+ });
194
+
195
+ map.set(copy.key, copy);
196
+
197
+ newNode = copy;
198
+ node = nextParent;
199
+ }
200
+
201
+ if (newNode == null) {
202
+ items = items.filter(c => c !== node);
203
+ }
204
+
205
+ return {
206
+ items: items.map(item => {
207
+ if (item === node) {
208
+ return newNode;
209
+ }
210
+
211
+ return item;
212
+ }),
213
+ nodeMap: map
214
+ };
215
+ }
216
+
217
+ function addNode(node: TreeNode<T>, map: Map<Key, TreeNode<T>>) {
218
+ map.set(node.key, node);
219
+ for (let child of node.children) {
220
+ addNode(child, map);
221
+ }
222
+ }
223
+
224
+ function deleteNode(node: TreeNode<T>, map: Map<Key, TreeNode<T>>) {
225
+ map.delete(node.key);
226
+ for (let child of node.children) {
227
+ deleteNode(child, map);
228
+ }
229
+ }
230
+
231
+ return {
232
+ items,
233
+ selectedKeys,
234
+ setSelectedKeys,
235
+ getItem(key: Key) {
236
+ return nodeMap.get(key);
237
+ },
238
+ insert(parentKey: Key | null, index: number, ...values: T[]) {
239
+ setItems(({items, nodeMap: originalMap}) => {
240
+ let {items: newNodes, nodeMap: newMap} = buildTree(values, originalMap, parentKey);
241
+
242
+ // If parentKey is null, insert into the root.
243
+ if (parentKey == null) {
244
+ return {
245
+ items: [
246
+ ...items.slice(0, index),
247
+ ...newNodes,
248
+ ...items.slice(index)
249
+ ],
250
+ nodeMap: newMap
251
+ };
252
+ }
253
+
254
+ // Otherwise, update the parent node and its ancestors.
255
+ return updateTree(items, parentKey, parentNode => ({
256
+ key: parentNode.key,
257
+ parentKey: parentNode.parentKey,
258
+ value: parentNode.value,
259
+ children: [
260
+ ...parentNode.children.slice(0, index),
261
+ ...newNodes,
262
+ ...parentNode.children.slice(index)
263
+ ]
264
+ }), newMap);
265
+ });
266
+ },
267
+ insertBefore(key: Key, ...values: T[]): void {
268
+ let node = nodeMap.get(key);
269
+ if (!node) {
270
+ return;
271
+ }
272
+
273
+ let parentNode = nodeMap.get(node.parentKey);
274
+ let nodes = parentNode ? parentNode.children : items;
275
+ let index = nodes.indexOf(node);
276
+ this.insert(parentNode?.key, index, ...values);
277
+ },
278
+ insertAfter(key: Key, ...values: T[]): void {
279
+ let node = nodeMap.get(key);
280
+ if (!node) {
281
+ return;
282
+ }
283
+
284
+ let parentNode = nodeMap.get(node.parentKey);
285
+ let nodes = parentNode ? parentNode.children : items;
286
+ let index = nodes.indexOf(node);
287
+ this.insert(parentNode?.key, index + 1, ...values);
288
+ },
289
+ prepend(parentKey: Key | null, ...values: T[]) {
290
+ this.insert(parentKey, 0, ...values);
291
+ },
292
+ append(parentKey: Key | null, ...values: T[]) {
293
+ if (parentKey == null) {
294
+ this.insert(null, items.length, ...values);
295
+ } else {
296
+ let parentNode = nodeMap.get(parentKey);
297
+ if (!parentNode) {
298
+ return;
299
+ }
300
+
301
+ this.insert(parentKey, parentNode.children.length, ...values);
302
+ }
303
+ },
304
+ remove(...keys: Key[]) {
305
+ if (keys.length === 0) {
306
+ return;
307
+ }
308
+
309
+ let newItems = items;
310
+ let prevMap = nodeMap;
311
+ let newTree;
312
+ for (let key of keys) {
313
+ newTree = updateTree(newItems, key, () => null, prevMap);
314
+ prevMap = newTree.nodeMap;
315
+ newItems = newTree.items;
316
+ }
317
+
318
+ setItems(newTree);
319
+
320
+ let selection = new Set(selectedKeys);
321
+ for (let key of selectedKeys) {
322
+ if (!newTree.nodeMap.has(key)) {
323
+ selection.delete(key);
324
+ }
325
+ }
326
+
327
+ setSelectedKeys(selection);
328
+ },
329
+ removeSelectedItems() {
330
+ this.remove(...selectedKeys);
331
+ },
332
+ move(key: Key, toParentKey: Key | null, index: number) {
333
+ setItems(({items, nodeMap: originalMap}) => {
334
+ let node = originalMap.get(key);
335
+ if (!node) {
336
+ return {items, nodeMap: originalMap};
337
+ }
338
+
339
+ let {items: newItems, nodeMap: newMap} = updateTree(items, key, () => null, originalMap);
340
+
341
+
342
+ const movedNode = {
343
+ ...node,
344
+ parentKey: toParentKey
345
+ };
346
+
347
+ // If parentKey is null, insert into the root.
348
+ if (toParentKey == null) {
349
+ newMap.set(movedNode.key, movedNode);
350
+ return {items: [
351
+ ...newItems.slice(0, index),
352
+ movedNode,
353
+ ...newItems.slice(index)
354
+ ], nodeMap: newMap};
355
+ }
356
+
357
+ // Otherwise, update the parent node and its ancestors.
358
+ return updateTree(newItems, toParentKey, parentNode => ({
359
+ key: parentNode.key,
360
+ parentKey: parentNode.parentKey,
361
+ value: parentNode.value,
362
+ children: [
363
+ ...parentNode.children.slice(0, index),
364
+ movedNode,
365
+ ...parentNode.children.slice(index)
366
+ ]
367
+ }), newMap);
368
+ });
369
+ },
370
+ update(oldKey: Key, newValue: T) {
371
+ setItems(({items, nodeMap: originalMap}) => updateTree(items, oldKey, oldNode => {
372
+ let node: TreeNode<T> = {
373
+ key: oldNode.key,
374
+ parentKey: oldNode.parentKey,
375
+ value: newValue,
376
+ children: null
377
+ };
378
+
379
+ let tree = buildTree(getChildren(newValue), originalMap, node.key);
380
+ node.children = tree.items;
381
+ return node;
382
+ }, originalMap));
383
+ }
384
+ };
385
+ }