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);
30 previous: previousSelector(selectAddresses),
33 const initialState = getInitialModelState<Model>();
35 const slice = createSlice({
39 extraReducers: (builder) => {
40 handleAsyncModel(builder, modelThunk);
42 .addCase(initEvent, (state, action) => {
43 if (action.payload.Addresses) {
44 state.value = action.payload.Addresses;
47 .addCase(serverEvent, (state, action) => {
48 if (state.value && action.payload.Addresses) {
49 state.value = sortAddresses(
52 events: action.payload.Addresses,
61 export const addressesReducer = { [name]: slice.reducer };
62 export const addressesThunk = modelThunk.thunk;