All files / publisher/hooks useSortTableData.tsx

63.15% Statements 12/19
36.84% Branches 7/19
66.66% Functions 2/3
63.15% Lines 12/19

Press n or j to go to the next uncovered block, b, p or k for the previous block.

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46                    29x 71x 71x 71x   71x 20x                         71x 30x 10x   20x   30x     71x              
import type { SortDirection } from "@canonical/react-components";
import { useState } from "react";
import type { MainTableRow } from "@canonical/react-components/dist/components/MainTable/MainTable";
 
interface Props {
  rows: MainTableRow[];
  defaultSort?: string;
  defaultSortDirection?: SortDirection;
}
 
const useSortTableData = (props: Props) => {
  const { defaultSort, defaultSortDirection = "ascending", rows } = props;
  const [sort, setSort] = useState<string | null | undefined>(defaultSort);
  const [sortDirection, setSortDirection] = useState(defaultSortDirection);
 
  if (sort) {
    rows.sort((a, b) => {
      const aVal = a.sortData ? (a.sortData[sort] as string) : "";
      const bVal = b.sortData ? (b.sortData[sort] as string) : "";
      if (aVal > bVal) {
        return sortDirection === "ascending" ? 1 : -1;
      }
      if (aVal < bVal) {
        return sortDirection === "ascending" ? -1 : 1;
      }
      return 0;
    });
  }
 
  const updateSort = (newSort?: string | null) => {
    if (newSort === sort) {
      setSortDirection("descending");
    } else {
      setSortDirection("ascending");
    }
    setSort(newSort || defaultSort);
  };
 
  return {
    rows,
    updateSort,
  };
};
 
export default useSortTableData;