UNPKG

@carbon/react

Version:

React components for the Carbon Design System

94 lines (84 loc) 2.47 kB
/** * Copyright IBM Corp. 2016, 2023 * * This source code is licensed under the Apache-2.0 license found in the * LICENSE file in the root directory of this source tree. */ 'use strict'; var sortStates = require('./sortStates.js'); var sorting = require('../tools/sorting.js'); // eslint-disable-next-line @typescript-eslint/no-explicit-any -- https://github.com/carbon-design-system/carbon/issues/20452 const initialSortState = sortStates.sortStates.NONE; /** * Gets the next sort direction for a header. * * @param prevHeader - Key of the previously sorted header. * @param currentHeader - Key of the currently selected header. * @param prevState - Previous sort direction. */ const getNextSortDirection = (prevHeader, currentHeader, prevState) => { // Cycle for sorting the same header: NONE -> ASC -> DESC -> NONE. if (prevHeader === currentHeader) { switch (prevState) { case sortStates.sortStates.NONE: return sortStates.sortStates.ASC; case sortStates.sortStates.ASC: return sortStates.sortStates.DESC; case sortStates.sortStates.DESC: return sortStates.sortStates.NONE; } } // Sorting a new header starts at ascending order. return sortStates.sortStates.ASC; }; /** * Gets the next sort state. * * @param props - Component props. * @param state - Current table state. * @param key - Header key to sort by. */ const getNextSortState = (props, state, { key }) => { const { sortDirection, sortHeaderKey } = state; const nextSortDirection = getNextSortDirection(key, sortHeaderKey ?? '', sortDirection); return getSortedState(props, state, key, nextSortDirection); }; /** * Gets a sort state update. * * @param props - Component props. * @param state - Current state of the table. * @param key - Header key to sort by. * @param sortDirection - Sort direction to apply. */ const getSortedState = ({ locale, sortRow }, { rowIds, cellsById, initialRowOrder }, key, sortDirection) => { const nextRowIds = sortDirection !== sortStates.sortStates.NONE ? sorting.sortRows({ rowIds, cellsById, sortDirection, key, locale, sortRow }) : initialRowOrder; return { sortHeaderKey: key, sortDirection, rowIds: nextRowIds }; }; exports.getNextSortDirection = getNextSortDirection; exports.getNextSortState = getNextSortState; exports.getSortedState = getSortedState; exports.initialSortState = initialSortState;