/** * @Author: Rostislav Simonik * @Date: 2018-08-10T07:33:33+02:00 * @Email: rostislav.simonik@technologystudio.sk * @Copyright: Technology Studio **/ import { translateOnPath } from '@txo/functional' import { Log } from '@txo/log' import { createReduxAdvanced } from '@txo/redux' import type { Attributes, AttributesAdvanced, Handler, HandlerAction, HandlerWrapper, ReduxHandler, } from '@txo/redux' import type { ContextRedux, ContextState, } from '../../Model/Types' const log = new Log('txo.context-redux.Redux.Model.ContextRedux') export const DEFAULT_CONTEXT = 'default' export const createContextRedux = < INNER_STATE, HANDLER_KEY extends string, // eslint-disable-next-line @typescript-eslint/no-explicit-any HANDLERS extends Record>, // HANDLERS extends ContextHandlers = ContextHandlers // HANDLER_ATTRIBUTES extends Record> | any = any, >(attributes: Attributes): ContextRedux => { type ContextInnerState = ContextState const handlerWrapper: HandlerWrapper< ContextInnerState, INNER_STATE, HandlerAction> & { context?: string } > = > & { context?: string }>( state: ContextInnerState, action: ACTION, handler: Handler | undefined, ) => { let nextState: ContextInnerState = state ?? {} if (handler != null) { const _handler = handler nextState = translateOnPath(action.context ?? DEFAULT_CONTEXT, state as INNER_STATE, (internalState) => { const nextInnerState = _handler(internalState ?? attributes.initialState, action.attributes, action) log.debug('TRANSLATE', { action, state, internalState, attributes, nextInnerState }) return nextInnerState }, { keepEmptyObjectsAtTranlateResult: true, }) ?? {} } return log.debugProxy('HANDLER WRAPPER', nextState, ) } return createReduxAdvanced< ContextInnerState, INNER_STATE, HandlerAction> & { context?: string }, HANDLER_KEY, HANDLERS, AttributesAdvanced< ContextInnerState, INNER_STATE, HandlerAction> & { context?: string }, HANDLER_KEY, HANDLERS > >({ ...attributes, handlerWrapper, }) }