@yext/chat-headless
Version:
A state manager library powered by Redux for Yext Chat integrations
67 lines (64 loc) • 2 kB
JavaScript
import { combineReducers, configureStore } from '@reduxjs/toolkit';
import conversationReducer from './slices/conversation.mjs';
import metaReducer from './slices/meta.mjs';
/**
* A Redux-backed implementation of the {@link StateManager} interface. Redux is used to
* manage the state, dispatch events, and register state listeners.
*
* @internal
*/
class ReduxStateManager {
store;
constructor() {
const coreReducer = combineReducers({
conversation: conversationReducer,
meta: metaReducer,
});
this.store = configureStore({
reducer: (state, action) => {
return action.type === "set-state"
? action.payload
: coreReducer(state, action);
},
});
}
/**
* Returns the current state.
*/
getState() {
return this.store.getState();
}
/**
* Returns the Redux store.
*/
getStore() {
return this.store;
}
/**
* Dispatches an event. This can update the {@link State}.
*
* @param action - represents an intention to change the state.
* This includes "type" field for the action type and "payload" field for the data to dispatch
*/
dispatch(action) {
this.store.dispatch(action);
}
/**
* Adds a listener for a specific state value of type T.
*
* @param listener - The state listener to add
* @returns The function for removing the added listener
*/
addListener(listener) {
let previousValue = listener.valueAccessor(this.getState());
return this.store.subscribe(() => {
const currentValue = listener.valueAccessor(this.getState());
if (currentValue !== previousValue) {
previousValue = currentValue;
listener.callback(currentValue);
}
});
}
}
export { ReduxStateManager };
//# sourceMappingURL=ReduxStateManager.mjs.map