Files
freeCodeCamp/common/app/Flash/redux/index.js

90 lines
1.8 KiB
JavaScript
Raw Normal View History

2018-01-04 16:24:03 -08:00
import _ from 'lodash/fp';
2018-01-04 16:39:43 -08:00
import {
createTypes,
createAction,
composeReducers,
handleActions
} from 'berkeleys-redux-utils';
2018-01-04 09:18:20 -08:00
2018-01-04 16:24:03 -08:00
import ns from '../ns.json';
export const alertTypes = _.keyBy(_.identity)([
'success',
'info',
'warning',
'danger'
]);
2018-01-08 11:12:00 -08:00
export const normalizeAlertType = _.get(alertTypes, 'info');
2018-01-04 16:24:03 -08:00
export const getFlashAction = _.flow(
_.property('meta'),
_.property('flash')
);
export const isFlashAction = _.flow(
getFlashAction,
Boolean
);
2018-01-08 11:12:00 -08:00
export const types = createTypes([
'clickOnClose',
'messagesFoundOnBoot'
], ns);
export const clickOnClose = createAction(types.clickOnClose, _.noop);
export const messagesFoundOnBoot = createAction(types.messagesFoundOnBoot);
export const expressToStack = _.flow(
_.toPairs,
_.flatMap(([ type, messages ]) => messages.map(({ msg }) => ({
message: msg,
alertType: normalizeAlertType(type)
})))
);
2018-01-04 16:24:03 -08:00
const defaultState = {
2018-01-08 11:12:00 -08:00
stack: [{ alertType: 'danger', message: 'foo nar' }]
2018-01-04 16:24:03 -08:00
};
const getNS = _.property(ns);
export const latestMessageSelector = _.flow(
getNS,
_.property('stack'),
_.head,
2018-01-04 16:39:43 -08:00
_.defaultTo({})
2018-01-04 16:24:03 -08:00
);
export default composeReducers(
ns,
2018-01-04 16:39:43 -08:00
handleActions(
() => ({
[types.clickOnClose]: (state) => ({
...state,
stack: _.tail(state.stack)
2018-01-08 11:12:00 -08:00
}),
[types.messagesFoundOnBoot]: (state, { payload }) => ({
...state,
stack: [...state.stack, ...expressToStack(payload)]
2018-01-04 16:39:43 -08:00
})
}),
defaultState,
),
2018-01-04 16:24:03 -08:00
function metaReducer(state = defaultState, action) {
if (isFlashAction(action)) {
const { payload: { alertType, message } } = getFlashAction(action);
return {
...state,
stack: [
...state.stack,
{
2018-01-08 11:12:00 -08:00
alertType: normalizeAlertType(alertType),
2018-01-04 16:24:03 -08:00
message: _.escape(message)
}
]
};
}
return state;
}
);