Files
freeCodeCamp/common/app/routes/challenges/redux/reducer.js

100 lines
2.5 KiB
JavaScript
Raw Normal View History

import { handleActions } from 'redux-actions';
2016-05-11 18:38:08 -07:00
import { createPoly } from '../../../../utils/polyvinyl';
import types from './types';
2016-05-13 14:05:29 -07:00
import { BONFIRE, HTML, JS } from '../../../utils/challengeTypes';
2016-05-14 16:46:20 -07:00
import { arrayToString, buildSeed, createTests, getPath } from '../utils';
const initialState = {
challenge: '',
currentStep: 0,
previousStep: -1,
filter: '',
2016-05-11 18:38:08 -07:00
files: {},
superBlocks: []
};
2016-05-11 18:38:08 -07:00
const mainReducer = handleActions(
{
2016-05-10 21:25:12 -07:00
[types.fetchChallengeCompleted]: (state, { payload = '' }) => ({
...state,
challenge: payload
}),
2016-05-10 21:25:12 -07:00
[types.updateCurrentChallenge]: (state, { payload: challenge }) => ({
...state,
2016-05-13 20:04:56 -07:00
refresh: true,
challenge: challenge.dashedName,
2016-05-13 20:04:56 -07:00
path: getPath(challenge),
tests: createTests(challenge)
}),
// map
[types.updateFilter]: (state, { payload = ''}) => ({
...state,
filter: payload
}),
[types.clearFilter]: (state) => ({
...state,
filter: ''
}),
[types.fetchChallengesCompleted]: (state, { payload = [] }) => ({
...state,
superBlocks: payload
}),
// step
[types.resetStep]: () => initialState,
[types.goToStep]: (state, { payload: step = 0 }) => ({
...state,
currentStep: step,
previousStep: state.currentStep
})
},
initialState
);
2016-05-11 18:38:08 -07:00
const filesReducer = handleActions(
{
[types.updateFile]: (state, { payload: file }) => ({
...state,
[file.path]: file
}),
[types.updateFiles]: (state, { payload: files }) => {
return files
.reduce((files, file) => {
files[file.path] = file;
return files;
}, { ...state });
},
[types.updateCurrentChallenge]: (state, { payload: challenge }) => {
if (challenge.type === 'mod') {
return challenge.files;
}
if (
challenge.challengeType !== HTML &&
2016-05-13 14:05:29 -07:00
challenge.challengeType !== JS &&
challenge.challengeType !== BONFIRE
) {
return {};
}
const path = getPath(challenge);
2016-05-11 18:38:08 -07:00
return {
...state,
[path]: createPoly({
path,
2016-05-14 16:46:20 -07:00
contents: buildSeed(challenge),
head: arrayToString(challenge.head),
tail: arrayToString(challenge.tail)
})
2016-05-11 18:38:08 -07:00
};
}
},
{}
);
export default function challengeReducers(state, action) {
const newState = mainReducer(state, action);
const files = filesReducer(state && state.files || {}, action);
return newState.files !== files ? { ...newState, files } : newState;
}