| 114 | * rows from props. In addition, it tracks row selection and manages sort order changes. |
| 115 | */ |
| 116 | export function useTableState<T extends object>(props: TableStateProps<T>): TableState<T> { |
| 117 | let [isKeyboardNavigationDisabled, setKeyboardNavigationDisabled] = useState(false); |
| 118 | let {selectionMode = 'none', showSelectionCheckboxes, showDragButtons, treeColumn = null} = props; |
| 119 | |
| 120 | let context = useMemo( |
| 121 | () => ({ |
| 122 | showSelectionCheckboxes: showSelectionCheckboxes && selectionMode !== 'none', |
| 123 | showDragButtons: showDragButtons, |
| 124 | selectionMode, |
| 125 | columns: [] |
| 126 | }), |
| 127 | // eslint-disable-next-line react-hooks/exhaustive-deps |
| 128 | [props.children, showSelectionCheckboxes, selectionMode, showDragButtons] |
| 129 | ); |
| 130 | |
| 131 | let collection = useCollection<T, ITableCollection<T>>( |
| 132 | props, |
| 133 | useCallback(nodes => new TableCollection(nodes, null, context), [context]), |
| 134 | context |
| 135 | ); |
| 136 | let {disabledKeys, selectionManager} = useGridState({ |
| 137 | ...props, |
| 138 | collection, |
| 139 | disabledBehavior: props.disabledBehavior || 'selection' |
| 140 | }); |
| 141 | |
| 142 | let [expandedKeys, setExpandedKeys] = useControlledState( |
| 143 | props.expandedKeys ? new Set(props.expandedKeys) : undefined, |
| 144 | props.defaultExpandedKeys ? new Set(props.defaultExpandedKeys) : new Set(), |
| 145 | props.onExpandedChange |
| 146 | ); |
| 147 | |
| 148 | return { |
| 149 | collection, |
| 150 | disabledKeys, |
| 151 | selectionManager, |
| 152 | showSelectionCheckboxes: props.showSelectionCheckboxes || false, |
| 153 | sortDescriptor: props.sortDescriptor ?? null, |
| 154 | isKeyboardNavigationDisabled: collection.size === 0 || isKeyboardNavigationDisabled, |
| 155 | setKeyboardNavigationDisabled, |
| 156 | sort(columnKey: Key, direction?: 'ascending' | 'descending') { |
| 157 | props.onSortChange?.({ |
| 158 | column: columnKey, |
| 159 | direction: |
| 160 | direction ?? |
| 161 | (props.sortDescriptor?.column === columnKey |
| 162 | ? OPPOSITE_SORT_DIRECTION[props.sortDescriptor.direction] |
| 163 | : 'ascending') |
| 164 | }); |
| 165 | }, |
| 166 | expandedKeys, |
| 167 | toggleKey(key) { |
| 168 | setExpandedKeys(keys => { |
| 169 | let newKeys = new Set(keys); |
| 170 | if (newKeys.has(key)) { |
| 171 | newKeys.delete(key); |
| 172 | } else { |
| 173 | newKeys.add(key); |