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

Function useGridState

packages/react-stately/src/grid/useGridState.ts:40–138  ·  view source on GitHub ↗
(
  props: GridStateOptions<T, C>
)

Source from the content-addressed store, hash-verified

38 * focusable child if applicable.
39 */
40export function useGridState<T extends object, C extends IGridCollection<T>>(
41 props: GridStateOptions<T, C>
42): GridState<T, C> {
43 let {collection, focusMode} = props;
44 // oxlint-disable-next-line react/react-compiler, react-hooks/rules-of-hooks
45 let selectionState = props.UNSAFE_selectionState || useMultipleSelectionState(props);
46 let disabledKeys = useMemo(
47 () => (props.disabledKeys ? new Set(props.disabledKeys) : new Set<Key>()),
48 [props.disabledKeys]
49 );
50
51 let setFocusedKey = selectionState.setFocusedKey;
52 // oxlint-disable-next-line react/react-compiler
53 selectionState.setFocusedKey = (key, child) => {
54 // If focusMode is cell and an item is focused, focus a child cell instead.
55 if (focusMode === 'cell' && key != null) {
56 let item = collection.getItem(key);
57 if (item?.type === 'item') {
58 let children = getChildNodes(item, collection);
59 if (child === 'last') {
60 key = getLastItem(children)?.key ?? null;
61 } else {
62 key = getFirstItem(children)?.key ?? null;
63 }
64 }
65 }
66
67 setFocusedKey(key, child);
68 };
69
70 let selectionManager = useMemo(
71 () => new SelectionManager(collection, selectionState),
72 [collection, selectionState]
73 );
74
75 // Reset focused key if that item is deleted from the collection.
76 const cachedCollection = useRef<C | null>(null);
77 useEffect(() => {
78 if (
79 selectionState.focusedKey != null &&
80 cachedCollection.current &&
81 !collection.getItem(selectionState.focusedKey)
82 ) {
83 const node = cachedCollection.current.getItem(selectionState.focusedKey);
84 const parentNode =
85 node?.parentKey != null &&
86 (node.type === 'cell' || node.type === 'rowheader' || node.type === 'column')
87 ? cachedCollection.current.getItem(node.parentKey)
88 : node;
89 if (!parentNode) {
90 selectionState.setFocusedKey(null);
91 return;
92 }
93 const cachedRows = cachedCollection.current.rows;
94 const rows = collection.rows;
95 const diff = cachedRows.length - rows.length;
96 let index = Math.min(
97 diff > 1 ? Math.max(parentNode.index - diff + 1, 0) : parentNode.index,

Callers 7

GridFunction · 0.90
DraggableCollectionFunction · 0.90
ReorderableGridFunction · 0.90
DroppableGrid.tsxFile · 0.90
DraggableCollectionFunction · 0.90
useTableStateFunction · 0.90
CardView.tsxFile · 0.90

Calls 8

getChildNodesFunction · 0.90
getLastItemFunction · 0.90
getFirstItemFunction · 0.90
setFocusedKeyFunction · 0.85
getItemMethod · 0.65
setFocusedKeyMethod · 0.65
isDisabledMethod · 0.65

Tested by

no test coverage detected