@carbon/react
Version:
React components for the Carbon Design System
68 lines (66 loc) • 2.02 kB
JavaScript
/**
* Copyright IBM Corp. 2016, 2026
*
* This source code is licensed under the Apache-2.0 license found in the
* LICENSE file in the root directory of this source tree.
*/
import { sortStates } from "./sortStates.js";
import { sortRows } from "../tools/sorting.js";
//#region src/components/DataTable/state/sorting.ts
/**
* Copyright IBM Corp. 2016, 2025
*
* This source code is licensed under the Apache-2.0 license found in the
* LICENSE file in the root directory of this source tree.
*/
const initialSortState = 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) => {
if (prevHeader === currentHeader) switch (prevState) {
case sortStates.NONE: return sortStates.ASC;
case sortStates.ASC: return sortStates.DESC;
case sortStates.DESC: return sortStates.NONE;
}
return 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;
return getSortedState(props, state, key, getNextSortDirection(key, sortHeaderKey ?? "", sortDirection));
};
/**
* 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) => {
return {
sortHeaderKey: key,
sortDirection,
rowIds: sortDirection !== sortStates.NONE ? sortRows({
rowIds,
cellsById,
sortDirection,
key,
locale,
sortRow
}) : initialRowOrder
};
};
//#endregion
export { getNextSortState, getSortedState, initialSortState };