import { PayloadAction, createSlice } from '@reduxjs/toolkit' import { defaultConfig } from 'config' import type { Config } from 'config.types' import { initializeConfig, resetConfig } from 'domains/config/actions' import type { ChannelEvent } from 'domains/store/store.types' import { pick } from 'ui/utils/general-utils' export const initialConfigState: Config = { ...defaultConfig, alwaysShowEntryLabel: false, api: { domain: '', key: '', secure: true, sendEnvironment: true, }, context: {}, notificationAudioURL: undefined, hideOnNoUserResponse: false, connectWhenInView: true, showDisclaimer: false, showSuggestions: true, useMultilineUserInput: false, preChat: { enterDelay: 1000, exitAfter: 4000, }, continueChat: { enterDelay: 0, exitAfter: 2000, }, customComponents: {}, defaults: { visible: null, }, preChatEvents: [], parentElement: undefined, layoutMode: 'window', } const configKeys: (keyof Config)[] = [ 'alwaysShowEntryLabel', 'hideOnNoUserResponse', 'connectWhenInView', 'showDisclaimer', 'showSuggestions', 'useMultilineUserInput', 'continueChat', 'preChat', 'namespace', 'customComponents', 'defaults', 'layoutMode', 'api', 'zIndex', 'context', 'appContainerClassNames', 'messages', 'visible', 'visibilityCallback', 'errorCallback', 'agentParticipant', 'userParticipant', 'startChatIcon', 'notificationAudioURL', ] const updateState = (state, config: Partial): Config => { const { messages, ...partialConfig } = pick(config, configKeys) let newState = state if (Object.keys(partialConfig).length > 0) { newState = { ...newState, ...partialConfig, } } if (messages) { newState = { ...newState, messages: { ...newState.messages, ...messages, }, } } return newState } export const configSlice = createSlice({ name: 'config', initialState: initialConfigState, reducers: { setConfig: (state, { payload }: PayloadAction) => updateState(state, payload), updateConfig: (state, { payload }: PayloadAction>) => updateState(state, payload), setPreChatEvents: (state, { payload }: PayloadAction) => { state.preChatEvents = payload }, }, extraReducers: (builder) => { builder .addCase(resetConfig.fulfilled, (config) => config) .addCase( initializeConfig.fulfilled, ( state, { payload: { preChat, agentParticipant, userParticipant, startChatIcon, defaultContentLocale, defaultUserLocale, }, }, ) => { // @ts-ignore state.preChatEvents = preChat.map((payload) => ({ type: 'message', payload, })) state.context.contentLocale = defaultContentLocale state.context.userLocale = defaultUserLocale state.agentParticipant = agentParticipant state.userParticipant = userParticipant state.startChatIcon = startChatIcon || '' }, ) }, }) export const { setConfig, updateConfig, setPreChatEvents } = configSlice.actions export default configSlice.reducer