Merge branch 'renovate/playwright' into 'main'
[ProtonMail-WebClient.git] / packages / account / addresses / index.ts
blob8eb4ec5dc340cd185888804f52b0664439f18090
1 import { createSlice } from '@reduxjs/toolkit';
3 import type { ProtonThunkArguments } from '@proton/redux-shared-store-types';
4 import { createAsyncModelThunk, handleAsyncModel, previousSelector } from '@proton/redux-utilities';
5 import { getAllAddresses } from '@proton/shared/lib/api/addresses';
6 import updateCollection from '@proton/shared/lib/helpers/updateCollection';
7 import type { Address } from '@proton/shared/lib/interfaces';
8 import { sortAddresses } from '@proton/shared/lib/mail/addresses';
10 import { serverEvent } from '../eventLoop';
11 import { initEvent } from '../init';
12 import { getInitialModelState } from '../initialModelState';
13 import type { ModelState } from '../interface';
15 const name = 'addresses' as const;
17 export interface AddressesState {
18     [name]: ModelState<Address[]>;
21 type SliceState = AddressesState[typeof name];
22 type Model = NonNullable<SliceState['value']>;
24 export const selectAddresses = (state: AddressesState) => state[name];
26 const modelThunk = createAsyncModelThunk<Model, AddressesState, ProtonThunkArguments>(`${name}/fetch`, {
27     miss: ({ extraArgument }) => {
28         return getAllAddresses(extraArgument.api).then(sortAddresses);
29     },
30     previous: previousSelector(selectAddresses),
31 });
33 const initialState = getInitialModelState<Model>();
35 const slice = createSlice({
36     name,
37     initialState,
38     reducers: {},
39     extraReducers: (builder) => {
40         handleAsyncModel(builder, modelThunk);
41         builder
42             .addCase(initEvent, (state, action) => {
43                 if (action.payload.Addresses) {
44                     state.value = action.payload.Addresses;
45                 }
46             })
47             .addCase(serverEvent, (state, action) => {
48                 if (state.value && action.payload.Addresses) {
49                     state.value = sortAddresses(
50                         updateCollection({
51                             model: state.value,
52                             events: action.payload.Addresses,
53                             itemKey: 'Address',
54                         })
55                     );
56                 }
57             });
58     },
59 });
61 export const addressesReducer = { [name]: slice.reducer };
62 export const addressesThunk = modelThunk.thunk;