All files / src/redux/slices sort.ts

47.61% Statements 10/21
16.66% Branches 3/18
33.33% Functions 2/6
47.61% Lines 10/21

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 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66        540x         540x       540x                                                                   8x 8x             540x   540x   540x   540x 173x      
import { RootState } from "@redux/types/store";
import { TableParams, SortSliceState, SortingOrder } from "@redux/types/sort";
import { createSlice, PayloadAction } from "@reduxjs/toolkit";
 
const defaultParams: TableParams = {
  attribute: "",
  order: "asc",
};
 
const initialState: SortSliceState = {
  tables: {},
};
 
const sortSlice = createSlice({
  name: "sort",
  initialState,
  reducers: {
    setSorting: (
      state: SortSliceState,
      action: PayloadAction<{
        tableName: string;
        params: Partial<TableParams>;
      }>,
    ) => {
      const { tableName, params } = action.payload;
      const oldState = state.tables[tableName];
      const oldValues = {
        attribute: oldState?.attribute || defaultParams.attribute,
        order: oldState?.order || defaultParams.order,
      };
 
      state.tables[tableName] = {
        attribute: params?.attribute || oldValues.attribute,
        order: params?.order || oldValues.order,
      };
    },
    toggleOrder: (state: SortSliceState, action: PayloadAction<string>) => {
      const tableName = action.payload;
      const currentOrder = state.tables[tableName]?.order;
      const order = (currentOrder === "asc" ? "desc" : "asc") as SortingOrder;
 
      state.tables[tableName] = {
        ...state.tables[tableName],
        order,
      };
    },
    resetSorting: (state: SortSliceState, action: PayloadAction<string>) => {
      const tableName = action.payload;
      Iif (state.tables[tableName]) {
        state.tables[tableName] = defaultParams;
      }
    },
  },
});
 
export const { setSorting, toggleOrder, resetSorting } = sortSlice.actions;
 
export const selectSortAttribute = (state: RootState, tableName: string) =>
  state.sort.tables[tableName]?.attribute || "";
export const selectSortOrder = (state: RootState, tableName: string) =>
  state.sort.tables[tableName]?.order || "asc";
export const selectSorting = (state: RootState, tableName: string) =>
  state.sort.tables[tableName] || defaultParams;
 
export default sortSlice.reducer;