( props: GridCellProps, state: GridState<T, C>, ref: RefObject<FocusableElement | null> )
| 82 | * @param state - State of the parent grid, as returned by `useGridState`. |
| 83 | */ |
| 84 | export function useGridCell<T, C extends GridCollection<T>>( |
| 85 | props: GridCellProps, |
| 86 | state: GridState<T, C>, |
| 87 | ref: RefObject<FocusableElement | null> |
| 88 | ): GridCellAria { |
| 89 | let { |
| 90 | node, |
| 91 | isVirtualized, |
| 92 | focusMode: focusModeProp, |
| 93 | allowsArrowNavigation, |
| 94 | shouldSelectOnPressUp, |
| 95 | onAction |
| 96 | } = props; |
| 97 | |
| 98 | let {direction} = useLocale(); |
| 99 | let { |
| 100 | keyboardDelegate, |
| 101 | actions: {onCellAction}, |
| 102 | keyboardNavigationBehavior |
| 103 | } = gridMap.get(state)!; |
| 104 | let focusMode = focusModeProp ?? (keyboardNavigationBehavior === 'tab' ? 'cell' : 'child'); |
| 105 | |
| 106 | // We need to track the key of the item at the time it was last focused so that we force |
| 107 | // focus to go to the item when the DOM node is reused for a different item in a virtualizer. |
| 108 | let keyWhenFocused = useRef<Key | null>(null); |
| 109 | |
| 110 | // Tracks the specific focusable child that was last focused within this cell. |
| 111 | let lastFocusedChild = useRef<FocusableElement | null>(null); |
| 112 | |
| 113 | // Handles focusing the cell. If there is a focusable child, |
| 114 | // it is focused, otherwise the cell itself is focused. |
| 115 | let focus = () => { |
| 116 | if (ref.current) { |
| 117 | let treeWalker = getFocusableTreeWalker(ref.current); |
| 118 | if (focusMode === 'child') { |
| 119 | let activeElement = getActiveElement(getOwnerDocument(ref.current)); |
| 120 | |
| 121 | // If focus is already on a focusable child within the cell, early return so we don't shift focus |
| 122 | if (isFocusWithin(ref.current) && ref.current !== activeElement) { |
| 123 | return; |
| 124 | } |
| 125 | |
| 126 | let ownerDocument = getOwnerDocument(ref.current); |
| 127 | let shouldRestoreToLastFocused = |
| 128 | !activeElement || activeElement === ownerDocument.body || activeElement === ref.current; |
| 129 | if (shouldRestoreToLastFocused) { |
| 130 | let lastChild = lastFocusedChild.current; |
| 131 | if ( |
| 132 | lastChild && |
| 133 | keyWhenFocused.current === node.key && |
| 134 | nodeContains(ref.current, lastChild) |
| 135 | ) { |
| 136 | focusSafely(lastChild); |
| 137 | return; |
| 138 | } |
| 139 | } |
| 140 | |
| 141 | let focusable = |
no test coverage detected