import * as React from 'react'; import { SortingDirection } from './types'; function getNextSortingDirection(direction: SortingDirection): SortingDirection { switch (direction) { case 'asc': return 'desc'; case 'desc': return 'unsorted'; case 'unsorted': default: return 'asc'; } } export function useSortable(sortKey?: string, value?: SortingDirection) { const [state, setState] = React.useState({ sortKey, value }); const getSortingDirection = React.useCallback( id => (state.sortKey === id ? state.value : 'unsorted'), [state.sortKey, state.value], ); const toggleSort = React.useCallback( (id: string) => { if (id === state.sortKey) { const nextDirection = getNextSortingDirection(state.value); setState(prevState => ({ ...prevState, value: nextDirection })); } else { setState(() => ({ sortKey: id, value: 'asc' })); } }, [state.sortKey, state.value], ); const setSort = (key: string, direction: SortingDirection) => setState(() => ({ sortKey: key, value: direction })); return { sortKey: state.sortKey, sortDirection: state.value, getSortingDirection, toggleSort, setSort, }; }