import { PayloadAction, createSlice } from '@reduxjs/toolkit' import { resetApp } from 'domains/app/actions' import { initializeConfig } from 'domains/config/actions' import { setLocale } from 'domains/i18n/actions' import { I18nState } from 'domains/i18n/i18n.types' const initialState: I18nState = { translations: { 'errors.configError.message': 'We are sorry this happened, please retry at a later time.', 'errors.configError.srText': 'A chat configuration error occurred. Our apologies, please retry at a later time.', 'errors.configError.title': 'Chat configuration error.', 'errors.general.buttonText': 'Restart chat', 'errors.general.message': 'Do you want to start a new chat session?', 'errors.general.srText': 'Something went wrong with the chat session. You can restart the chat.', 'errors.general.title': 'Something went wrong', 'errors.seamlyOffline.message': 'There might be a problem with your or our network connection. The chat session should resume as soon the connection is available again.', 'errors.seamlyOffline.srText': 'The chat has connection issues. There might be a problem with your or our network connection. The chat session should resume as soon as the connection is available again.', 'errors.seamlyOffline.title': 'Connection issues', 'errors.seamlyUnavailable.buttonText': 'Try again', 'errors.seamlyUnavailable.message': 'The server could not be reached. Try again in a little while.', 'errors.seamlyUnavailable.srText': 'The chat server could not be reached. Try again in a little while.', 'errors.seamlyUnavailable.title': 'Server unavailable', }, isLoading: false, initialLocale: undefined, userLocale: undefined, } export const i18nSlice = createSlice({ name: 'app', initialState, reducers: { setInitialLocale: (state, action) => { state.initialLocale = action.payload }, setTranslations: ( state, { payload }: PayloadAction, ) => { state.translations = payload }, }, extraReducers: (builder) => { // Add reducers for additional action types here, and handle loading state as needed builder .addCase(resetApp.pending, () => initialState) .addCase(initializeConfig.fulfilled, (state, { payload }) => { state.initialLocale = payload.defaultUserLocale }) .addCase(setLocale.pending, (state) => { state.isLoading = true }) .addCase(setLocale.rejected, (state) => { state.isLoading = false }) .addCase(setLocale.fulfilled, (state, { payload }) => { state.isLoading = false if (!payload?.translations) { return } state.userLocale = payload.userLocale state.translations = Object.keys(payload.translations) .sort() .reduce((acc, key) => { if (!payload.translations) return acc const translation = payload.translations[key] acc[key] = translation return acc }, {}) }) }, }) export const { setInitialLocale, setTranslations } = i18nSlice.actions export default i18nSlice.reducer