@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,430 +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, Selection} from '@react-types/shared';
14
- import {useMemo, useState} from 'react';
15
-
16
- export interface ListOptions<T> {
17
- /** Initial items in the list. */
18
- initialItems?: T[],
19
- /** The keys for the initially selected items. */
20
- initialSelectedKeys?: 'all' | Iterable<Key>,
21
- /** The initial text to filter the list by. */
22
- initialFilterText?: string,
23
- /** A function that returns a unique key for an item object. */
24
- getKey?: (item: T) => Key,
25
- /** A function that returns whether a item matches the current filter text. */
26
- filter?: (item: T, filterText: string) => boolean
27
- }
28
-
29
- export interface ListData<T> {
30
- /** The items in the list. */
31
- items: T[],
32
-
33
- /** The keys of the currently selected items in the list. */
34
- selectedKeys: Selection,
35
-
36
- /** Sets the selected keys. */
37
- setSelectedKeys(keys: Selection): void,
38
-
39
- /** Adds the given keys to the current selected keys. */
40
- addKeysToSelection(keys: Selection): void,
41
-
42
- /** Removes the given keys from the current selected keys. */
43
- removeKeysFromSelection(keys: Selection): void,
44
-
45
- /** The current filter text. */
46
- filterText: string,
47
-
48
- /** Sets the filter text. */
49
- setFilterText(filterText: string): void,
50
-
51
- /**
52
- * Gets an item from the list by key.
53
- * @param key - The key of the item to retrieve.
54
- */
55
- getItem(key: Key): T | undefined,
56
-
57
- /**
58
- * Inserts items into the list at the given index.
59
- * @param index - The index to insert into.
60
- * @param values - The values to insert.
61
- */
62
- insert(index: number, ...values: T[]): void,
63
-
64
- /**
65
- * Inserts items into the list before the item at the given key.
66
- * @param key - The key of the item to insert before.
67
- * @param values - The values to insert.
68
- */
69
- insertBefore(key: Key, ...values: T[]): void,
70
-
71
- /**
72
- * Inserts items into the list after the item at the given key.
73
- * @param key - The key of the item to insert after.
74
- * @param values - The values to insert.
75
- */
76
- insertAfter(key: Key, ...values: T[]): void,
77
-
78
- /**
79
- * Appends items to the list.
80
- * @param values - The values to insert.
81
- */
82
- append(...values: T[]): void,
83
-
84
- /**
85
- * Prepends items to the list.
86
- * @param value - The value to insert.
87
- */
88
- prepend(...values: T[]): void,
89
-
90
- /**
91
- * Removes items from the list by their keys.
92
- * @param keys - The keys of the item to remove.
93
- */
94
- remove(...keys: Key[]): void,
95
-
96
- /**
97
- * Removes all items from the list that are currently
98
- * in the set of selected items.
99
- */
100
- removeSelectedItems(): void,
101
-
102
- /**
103
- * Moves an item within the list.
104
- * @param key - The key of the item to move.
105
- * @param toIndex - The index to move the item to.
106
- */
107
- move(key: Key, toIndex: number): void,
108
-
109
- /**
110
- * Moves one or more items before a given key.
111
- * @param key - The key of the item to move the items before.
112
- * @param keys - The keys of the items to move.
113
- */
114
- moveBefore(key: Key, keys: Iterable<Key>): void,
115
-
116
- /**
117
- * Moves one or more items after a given key.
118
- * @param key - The key of the item to move the items after.
119
- * @param keys - The keys of the items to move.
120
- */
121
- moveAfter(key: Key, keys: Iterable<Key>): void,
122
-
123
- /**
124
- * Updates an item in the list.
125
- * @param key - The key of the item to update.
126
- * @param newValue - The new value for the item, or a function that returns the new value based on the previous value.
127
- */
128
- update(key: Key, newValue: T | ((prev: T) => T)): void
129
- }
130
-
131
- export interface ListState<T> {
132
- items: T[],
133
- selectedKeys: Selection,
134
- filterText: string
135
- }
136
-
137
- interface CreateListOptions<T, C> extends ListOptions<T> {
138
- cursor?: C
139
- }
140
-
141
- /**
142
- * Manages state for an immutable list data structure, and provides convenience methods to
143
- * update the data over time.
144
- */
145
- export function useListData<T>(options: ListOptions<T>): ListData<T> {
146
- let {
147
- initialItems = [],
148
- initialSelectedKeys,
149
- getKey = (item: any) => item.id ?? item.key,
150
- filter,
151
- initialFilterText = ''
152
- } = options;
153
-
154
- // Store both items and filteredItems in state so we can go back to the unfiltered list
155
- let [state, setState] = useState<ListState<T>>({
156
- items: initialItems,
157
- selectedKeys: initialSelectedKeys === 'all' ? 'all' : new Set(initialSelectedKeys || []),
158
- filterText: initialFilterText
159
- });
160
-
161
- let filteredItems = useMemo(
162
- () => filter ? state.items.filter(item => filter(item, state.filterText)) : state.items,
163
- [state.items, state.filterText, filter]);
164
-
165
- return {
166
- ...state,
167
- items: filteredItems,
168
- ...createListActions({getKey}, setState),
169
- getItem(key: Key) {
170
- return state.items.find(item => getKey(item) === key);
171
- }
172
- };
173
- }
174
-
175
- export function createListActions<T, C>(opts: CreateListOptions<T, C>, dispatch: (updater: (state: ListState<T>) => ListState<T>) => void): Omit<ListData<T>, 'items' | 'selectedKeys' | 'getItem' | 'filterText'> {
176
- let {cursor, getKey} = opts;
177
- return {
178
- setSelectedKeys(selectedKeys: Selection) {
179
- dispatch(state => ({
180
- ...state,
181
- selectedKeys
182
- }));
183
- },
184
- addKeysToSelection(selectedKeys: Selection) {
185
- dispatch(state => {
186
- if (state.selectedKeys === 'all') {
187
- return state;
188
- }
189
- if (selectedKeys === 'all') {
190
- return {
191
- ...state,
192
- selectedKeys: 'all'
193
- };
194
- }
195
-
196
- return {
197
- ...state,
198
- selectedKeys: new Set([...state.selectedKeys, ...selectedKeys])
199
- };
200
- });
201
- },
202
- removeKeysFromSelection(selectedKeys: Selection) {
203
- dispatch(state => {
204
- if (selectedKeys === 'all') {
205
- return {
206
- ...state,
207
- selectedKeys: new Set()
208
- };
209
- }
210
-
211
- let selection: Selection = state.selectedKeys === 'all' ? new Set(state.items.map(getKey!)) : new Set(state.selectedKeys);
212
- for (let key of selectedKeys) {
213
- selection.delete(key);
214
- }
215
- return {
216
- ...state,
217
- selectedKeys: selection
218
- };
219
- });
220
- },
221
- setFilterText(filterText: string) {
222
- dispatch(state => ({
223
- ...state,
224
- filterText
225
- }));
226
- },
227
- insert(index: number, ...values: T[]) {
228
- dispatch(state => insert(state, index, ...values));
229
- },
230
- insertBefore(key: Key, ...values: T[]) {
231
- dispatch(state => {
232
- let index = state.items.findIndex(item => getKey?.(item) === key);
233
- if (index === -1) {
234
- if (state.items.length === 0) {
235
- index = 0;
236
- } else {
237
- return state;
238
- }
239
- }
240
-
241
- return insert(state, index, ...values);
242
- });
243
- },
244
- insertAfter(key: Key, ...values: T[]) {
245
- dispatch(state => {
246
- let index = state.items.findIndex(item => getKey?.(item) === key);
247
- if (index === -1) {
248
- if (state.items.length === 0) {
249
- index = 0;
250
- } else {
251
- return state;
252
- }
253
- }
254
-
255
- return insert(state, index + 1, ...values);
256
- });
257
- },
258
- prepend(...values: T[]) {
259
- dispatch(state => insert(state, 0, ...values));
260
- },
261
- append(...values: T[]) {
262
- dispatch(state => insert(state, state.items.length, ...values));
263
- },
264
- remove(...keys: Key[]) {
265
- dispatch(state => {
266
- let keySet = new Set(keys);
267
- let items = state.items.filter(item => !keySet.has(getKey!(item)));
268
-
269
- let selection: Selection = 'all';
270
- if (state.selectedKeys !== 'all') {
271
- selection = new Set(state.selectedKeys);
272
- for (let key of keys) {
273
- selection.delete(key);
274
- }
275
- }
276
- if (cursor == null && items.length === 0) {
277
- selection = new Set();
278
- }
279
-
280
- return {
281
- ...state,
282
- items,
283
- selectedKeys: selection
284
- };
285
- });
286
- },
287
- removeSelectedItems() {
288
- dispatch(state => {
289
- if (state.selectedKeys === 'all') {
290
- return {
291
- ...state,
292
- items: [],
293
- selectedKeys: new Set()
294
- };
295
- }
296
-
297
- let selectedKeys = state.selectedKeys;
298
- let items = state.items.filter(item => !selectedKeys.has(getKey!(item)));
299
- return {
300
- ...state,
301
- items,
302
- selectedKeys: new Set()
303
- };
304
- });
305
- },
306
- move(key: Key, toIndex: number) {
307
- dispatch(state => {
308
- let index = state.items.findIndex(item => getKey!(item) === key);
309
- if (index === -1) {
310
- return state;
311
- }
312
-
313
- let copy = state.items.slice();
314
- let [item] = copy.splice(index, 1);
315
- copy.splice(toIndex, 0, item);
316
- return {
317
- ...state,
318
- items: copy
319
- };
320
- });
321
- },
322
- moveBefore(key: Key, keys: Iterable<Key>) {
323
- dispatch(state => {
324
- let toIndex = state.items.findIndex(item => getKey!(item) === key);
325
- if (toIndex === -1) {
326
- return state;
327
- }
328
-
329
- // Find indices of keys to move. Sort them so that the order in the list is retained.
330
- let keyArray = Array.isArray(keys) ? keys : [...keys];
331
- let indices = keyArray.map(key => state.items.findIndex(item => getKey!(item) === key)).sort((a, b) => a - b);
332
- return move(state, indices, toIndex);
333
- });
334
- },
335
- moveAfter(key: Key, keys: Iterable<Key>) {
336
- dispatch(state => {
337
- let toIndex = state.items.findIndex(item => getKey!(item) === key);
338
- if (toIndex === -1) {
339
- return state;
340
- }
341
-
342
- let keyArray = Array.isArray(keys) ? keys : [...keys];
343
- let indices = keyArray.map(key => state.items.findIndex(item => getKey!(item) === key)).sort((a, b) => a - b);
344
- return move(state, indices, toIndex + 1);
345
- });
346
- },
347
- update(key: Key, newValue: T | ((prev: T) => T)) {
348
- dispatch(state => {
349
- let index = state.items.findIndex(item => getKey!(item) === key);
350
- if (index === -1) {
351
- return state;
352
- }
353
-
354
- let updatedValue: T;
355
- if (typeof newValue === 'function') {
356
- updatedValue = (newValue as (prev: T) => T)(state.items[index]);
357
- } else {
358
- updatedValue = newValue;
359
- }
360
-
361
- return {
362
- ...state,
363
- items: [
364
- ...state.items.slice(0, index),
365
- updatedValue,
366
- ...state.items.slice(index + 1)
367
- ]
368
- };
369
- });
370
- }
371
- };
372
- }
373
-
374
- function insert<T>(state: ListState<T>, index: number, ...values: T[]): ListState<T> {
375
- return {
376
- ...state,
377
- items: [
378
- ...state.items.slice(0, index),
379
- ...values,
380
- ...state.items.slice(index)
381
- ]
382
- };
383
- }
384
-
385
- function move<T>(state: ListState<T>, indices: number[], toIndex: number): ListState<T> {
386
- // Shift the target down by the number of items being moved from before the target
387
- toIndex -= indices.filter(index => index < toIndex).length;
388
-
389
- let moves = indices.map(from => ({
390
- from,
391
- to: toIndex++
392
- }));
393
-
394
- // Shift later from indices down if they have a larger index
395
- for (let i = 0; i < moves.length; i++) {
396
- let a = moves[i].from;
397
- for (let j = i; j < moves.length; j++) {
398
- let b = moves[j].from;
399
-
400
- if (b > a) {
401
- moves[j].from--;
402
- }
403
- }
404
- }
405
-
406
- // Interleave the moves so they can be applied one by one rather than all at once
407
- for (let i = 0; i < moves.length; i++) {
408
- let a = moves[i];
409
- for (let j = moves.length - 1; j > i; j--) {
410
- let b = moves[j];
411
-
412
- if (b.from < a.to) {
413
- a.to++;
414
- } else {
415
- b.from++;
416
- }
417
- }
418
- }
419
-
420
- let copy = state.items.slice();
421
- for (let move of moves) {
422
- let [item] = copy.splice(move.from, 1);
423
- copy.splice(move.to, 0, item);
424
- }
425
-
426
- return {
427
- ...state,
428
- items: copy
429
- };
430
- }