[DRVWEB-4373] Add Suggestion Mode spotlight onboarding modal for docs on drive
[ProtonMail-WebClient.git] / packages / mail / filters / index.ts
blob9dc8b59683408122e2390b2aa7d963fa9c501ca8
1 import { createSlice } from '@reduxjs/toolkit';
3 import { type ModelState, getInitialModelState, serverEvent } from '@proton/account';
4 import type { Filter } from '@proton/components/containers/filters/interfaces';
5 import type { ProtonThunkArguments } from '@proton/redux-shared-store-types';
6 import { createAsyncModelThunk, handleAsyncModel, previousSelector } from '@proton/redux-utilities';
7 import { queryFilters } from '@proton/shared/lib/api/filters';
8 import updateCollection, { sortCollection } from '@proton/shared/lib/helpers/updateCollection';
10 const name = 'filters' as const;
12 interface State {
13     [name]: ModelState<Filter[]>;
16 type SliceState = State[typeof name];
17 type Model = NonNullable<SliceState['value']>;
19 export const selectFilters = (state: State) => state.filters;
21 const modelThunk = createAsyncModelThunk<Model, State, ProtonThunkArguments>(`${name}/fetch`, {
22     miss: async ({ extraArgument }) => {
23         return extraArgument
24             .api<{
25                 Filters: Filter[];
26             }>(queryFilters())
27             .then(({ Filters }) => sortCollection('Priority', [...Filters]));
28     },
29     previous: previousSelector(selectFilters),
30 });
32 const initialState = getInitialModelState<Model>();
33 const slice = createSlice({
34     name,
35     initialState,
36     reducers: {},
37     extraReducers: (builder) => {
38         handleAsyncModel(builder, modelThunk);
39         builder.addCase(serverEvent, (state, action) => {
40             if (state.value && action.payload.Filters) {
41                 state.value = sortCollection(
42                     'Priority',
43                     updateCollection({
44                         model: state.value,
45                         events: action.payload.Filters,
46                         itemKey: 'Filter',
47                     })
48                 );
49             }
50         });
51     },
52 });
54 export const filtersReducer = { [name]: slice.reducer };
55 export const filtersThunk = modelThunk.thunk;