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

280 lines
7.2 KiB
JavaScript
Raw Normal View History

feat(app): new layout (#14707) * feat(app): Restructure app to be more flexible and redux idiomatic BREAKING CHANGE: Lots of breaking changes * refactor(challenges): Redux to started file structure * fix(app): lint issues due to refactor * fix(settings): Refactor settings to use folder structure * refactor(challenges): Move step redux stuff into step folder * fix(challenges): Remove fetchchallenges actions * refactor(challenges): Move project redux logic into project view subdirectory * refactor(app): %s/sagas/epics/g * refactor(redux): Use new redux-epic with combineEpic and ofType * refactor(app): Move challenge selector to app level * fix(app): Move loading challenge info into challenge route This moves a lot of the logic needed to load challenge info into the challenge app. This decouples the main app from the challenge route * refactor(map): Map is now decoupled from challenges * refactor(challenges): Use selectors everywhere instead of guessing state shape * refactor(client): refactor client epics to use selectors * refactor(app): Refactor userSelector to return user object instead of object.user * refactor(entities): Move entities logic into it's own file * fix(redux): combineTypes should be combineActions * fix(app): reducer namespacing and import * fix(Map): Fix undefined type and update redux-action * fix(redux): Refactor fetchUser to be more declarative Use rxjs methods instead of imperative if/else. Also prevent non-actions from being emitted * fix(redux): toString multi phase action types * fix(redux): typecast multiphase type, fix typo in reducer toString multiphase types in fetch challenge epic. Add epic to epics lists. Fix type in fetch challenge complete handler * fix(redux): updateCurrentChallengelogic should be centerlized Move route changes to one location. * fix(Nav): Prevent event object from hanging around closeDropDown/openDropDown where handing on to the event object. This was causing issues with react since event objects are recycled in React. * fix(Map.Challenge): decouple map selector * fix(Map): Decouple panel selectors from props Panel Selectors no longer need to know the shape of a components props. Refactored component selectors to decouple them entities state shape * fix(Map.redux): Add select challenge epic and connect map epics * fix(redux.analytics): Fix meta creator and nav/map events * fix(redux): Update current challenge ajax * fix(challenges): ssr fetch challenge should update challenge ui Was using an epic to update challenge ui on fetch complete, but this was not working on ssr due to the way ssr disables epics to wait for completion. This commit fixes this by causing the complete to directly update state in the challenge ui * fix(challenges): wrong import of types, refactor epic name * fix(redux): Prevent fetch challenge epic from emitting null to dispatch * fix(redux): prevent executechallenge from emitting null * fix(challenges.redux): testsSelector returns just tests * fix(challenges.redux): Prevent completion challenge from emitting null * refactor(Challenges.Step): Refactor step challenge to release event object * fix(redux): wrap reducers in factories reducers exported from features need to be factories this helps avoid cyclic requires messing up reducer creation We end up with exports from files being undefined as node tries to resolve cyclic dependencies. This prevents that by wrapping the `handleActions` call so that the ref to types imported from parent features are closures and can be resolved by node before we need them. * fix(Map): createUi not working correctly map utils should receive just map ui state, createMapUi needs to add title to challenge * feat(Challenges): Adds Panes and panes backend challenge * fix: Create child container to wrap children Create a ChildContainer comp' to wrap all children that represent the view for the current route. This let's the child route define if they want a full width view or if they want the standard max-width view. * feat(Panes): panes now render dividers * feat(Panes): Get divider to move currectly * fix(Nav): Add top margin to contained childs Move margin-bottom from nav to child container as margin top. This let's the jsbin style views fit snug with navbar * fix(Panes): Should be contained within their borders * feat(Panes): Update navbar height of pane on app mount * feat(Panes): Toggle map on map nav btn click * fix(gulpfile): Ensure nodemon exits on restart On process exit, wait for nodemon to shutdown before process.exit * feat(Panes): Make Panes redux first * fix(Panes): Fix divider positioning * fix(Panes): Update divider moved handler dividerMoved action now uses new panesByName structure * feat(Panes): Pane nav button will hide panes * chore(package-lock): Update package lock * feat(Panes.redux): Recaculate dividers on pane toggle * fix(Challenges): Update challenge on dashedName change This fixes backwards navigation not updating the redux state current challenge * feat(Panes.redux): Clear panes on unmount Clearing panes on unmount will clear bin buttons in nav * refactor(Map): Colocate styles * feat(Map): New map layout * fix(Map): No longer has it's own page * fix: FetchChallenges on appMounted * feat: Normalize fetchChallenge(s) results This allows superblocks to be sent with both fetchChallenge and fetchChallenges so the map is always populated on first load * feat(Map): Show blocks on first load * fix(less): Remove old css * feat(Nav): Reduce nav height * fix(Nav): Render nav after content Render nav after content and use css to reverse again on screen. We do this so the panes can render first and update redux panes state which will then update the nav ui state before nav has a chance to render * fix(Panes): Add container This adds a Panes Container that will allow it to udpate redux state so Panes Component will have redux state ready to actually render panes * feat(Challenges.Classic): Add panes * fix(Challenge.Classic): Editor onchange should not need to know about file * fix(Panes): Index on panes hide should account for hidden pane * fix(Challanges.Classic): Fix panes types * fix(Challenges): Add completion modal to all challenges Change classic modal to completion modal * fix(Panes): Dividers live on top of planes * fix(Challenges): Remove codemirror theme Remove codemirror theme and remove borders from preview frame * fix(Challenges.Classic): Remove old component * feat(Challenges.Step): Add panes to step challenge * feat(Challenges.Project): Add panes to projects * fix(Challenges.Projects): Remove row * fix(Modals): Move modal text color to challenge less This text color is dependent on the actual header color * fix(Map): Use Superblock title for ui * fix(Map): Reduce panel header height * fix(app): Capitalize Toasts folder Feature folders should be campitalized * chore(Map): Remove unused epic file * fix(Step): Fix tests * test(Map): Update createMapUi tests input
2017-07-31 20:04:01 -07:00
import { Observable } from 'rx';
import { createTypes, createAsyncTypes } from 'redux-create-types';
import { combineActions, createAction, handleActions } from 'redux-actions';
import { createSelector } from 'reselect';
import noop from 'lodash/noop';
import identity from 'lodash/identity';
import { entitiesSelector } from '../entities';
import fetchUserEpic from './fetch-user-epic.js';
import updateMyCurrentChallengeEpic from './update-my-challenge-epic.js';
import fetchChallengesEpic from './fetch-challenges-epic.js';
import navSizeEpic from './nav-size-epic.js';
import ns from '../ns.json';
export const epics = [
fetchUserEpic,
fetchChallengesEpic,
updateMyCurrentChallengeEpic,
navSizeEpic
];
feat(app): new layout (#14707) * feat(app): Restructure app to be more flexible and redux idiomatic BREAKING CHANGE: Lots of breaking changes * refactor(challenges): Redux to started file structure * fix(app): lint issues due to refactor * fix(settings): Refactor settings to use folder structure * refactor(challenges): Move step redux stuff into step folder * fix(challenges): Remove fetchchallenges actions * refactor(challenges): Move project redux logic into project view subdirectory * refactor(app): %s/sagas/epics/g * refactor(redux): Use new redux-epic with combineEpic and ofType * refactor(app): Move challenge selector to app level * fix(app): Move loading challenge info into challenge route This moves a lot of the logic needed to load challenge info into the challenge app. This decouples the main app from the challenge route * refactor(map): Map is now decoupled from challenges * refactor(challenges): Use selectors everywhere instead of guessing state shape * refactor(client): refactor client epics to use selectors * refactor(app): Refactor userSelector to return user object instead of object.user * refactor(entities): Move entities logic into it's own file * fix(redux): combineTypes should be combineActions * fix(app): reducer namespacing and import * fix(Map): Fix undefined type and update redux-action * fix(redux): Refactor fetchUser to be more declarative Use rxjs methods instead of imperative if/else. Also prevent non-actions from being emitted * fix(redux): toString multi phase action types * fix(redux): typecast multiphase type, fix typo in reducer toString multiphase types in fetch challenge epic. Add epic to epics lists. Fix type in fetch challenge complete handler * fix(redux): updateCurrentChallengelogic should be centerlized Move route changes to one location. * fix(Nav): Prevent event object from hanging around closeDropDown/openDropDown where handing on to the event object. This was causing issues with react since event objects are recycled in React. * fix(Map.Challenge): decouple map selector * fix(Map): Decouple panel selectors from props Panel Selectors no longer need to know the shape of a components props. Refactored component selectors to decouple them entities state shape * fix(Map.redux): Add select challenge epic and connect map epics * fix(redux.analytics): Fix meta creator and nav/map events * fix(redux): Update current challenge ajax * fix(challenges): ssr fetch challenge should update challenge ui Was using an epic to update challenge ui on fetch complete, but this was not working on ssr due to the way ssr disables epics to wait for completion. This commit fixes this by causing the complete to directly update state in the challenge ui * fix(challenges): wrong import of types, refactor epic name * fix(redux): Prevent fetch challenge epic from emitting null to dispatch * fix(redux): prevent executechallenge from emitting null * fix(challenges.redux): testsSelector returns just tests * fix(challenges.redux): Prevent completion challenge from emitting null * refactor(Challenges.Step): Refactor step challenge to release event object * fix(redux): wrap reducers in factories reducers exported from features need to be factories this helps avoid cyclic requires messing up reducer creation We end up with exports from files being undefined as node tries to resolve cyclic dependencies. This prevents that by wrapping the `handleActions` call so that the ref to types imported from parent features are closures and can be resolved by node before we need them. * fix(Map): createUi not working correctly map utils should receive just map ui state, createMapUi needs to add title to challenge * feat(Challenges): Adds Panes and panes backend challenge * fix: Create child container to wrap children Create a ChildContainer comp' to wrap all children that represent the view for the current route. This let's the child route define if they want a full width view or if they want the standard max-width view. * feat(Panes): panes now render dividers * feat(Panes): Get divider to move currectly * fix(Nav): Add top margin to contained childs Move margin-bottom from nav to child container as margin top. This let's the jsbin style views fit snug with navbar * fix(Panes): Should be contained within their borders * feat(Panes): Update navbar height of pane on app mount * feat(Panes): Toggle map on map nav btn click * fix(gulpfile): Ensure nodemon exits on restart On process exit, wait for nodemon to shutdown before process.exit * feat(Panes): Make Panes redux first * fix(Panes): Fix divider positioning * fix(Panes): Update divider moved handler dividerMoved action now uses new panesByName structure * feat(Panes): Pane nav button will hide panes * chore(package-lock): Update package lock * feat(Panes.redux): Recaculate dividers on pane toggle * fix(Challenges): Update challenge on dashedName change This fixes backwards navigation not updating the redux state current challenge * feat(Panes.redux): Clear panes on unmount Clearing panes on unmount will clear bin buttons in nav * refactor(Map): Colocate styles * feat(Map): New map layout * fix(Map): No longer has it's own page * fix: FetchChallenges on appMounted * feat: Normalize fetchChallenge(s) results This allows superblocks to be sent with both fetchChallenge and fetchChallenges so the map is always populated on first load * feat(Map): Show blocks on first load * fix(less): Remove old css * feat(Nav): Reduce nav height * fix(Nav): Render nav after content Render nav after content and use css to reverse again on screen. We do this so the panes can render first and update redux panes state which will then update the nav ui state before nav has a chance to render * fix(Panes): Add container This adds a Panes Container that will allow it to udpate redux state so Panes Component will have redux state ready to actually render panes * feat(Challenges.Classic): Add panes * fix(Challenge.Classic): Editor onchange should not need to know about file * fix(Panes): Index on panes hide should account for hidden pane * fix(Challanges.Classic): Fix panes types * fix(Challenges): Add completion modal to all challenges Change classic modal to completion modal * fix(Panes): Dividers live on top of planes * fix(Challenges): Remove codemirror theme Remove codemirror theme and remove borders from preview frame * fix(Challenges.Classic): Remove old component * feat(Challenges.Step): Add panes to step challenge * feat(Challenges.Project): Add panes to projects * fix(Challenges.Projects): Remove row * fix(Modals): Move modal text color to challenge less This text color is dependent on the actual header color * fix(Map): Use Superblock title for ui * fix(Map): Reduce panel header height * fix(app): Capitalize Toasts folder Feature folders should be campitalized * chore(Map): Remove unused epic file * fix(Step): Fix tests * test(Map): Update createMapUi tests input
2017-07-31 20:04:01 -07:00
export const types = createTypes([
'appMounted',
'analytics',
'updateTitle',
'updateAppLang',
createAsyncTypes('fetchChallenge'),
createAsyncTypes('fetchChallenges'),
'updateCurrentChallenge',
'fetchUser',
'addUser',
'updateThisUser',
'showSignIn',
'handleError',
// used to hit the server
'hardGoTo',
'delayedRedirect',
// night mode
'toggleNightMode',
'updateTheme',
'addThemeToBody'
], ns);
const throwIfUndefined = () => {
throw new TypeError('Argument must not be of type `undefined`');
};
// createEventMetaCreator({
// category: String,
// action: String,
// label?: String,
// value?: Number
// }) => () => Object
export const createEventMetaCreator = ({
// categories are features or namespaces of the app (capitalized):
// Map, Nav, Challenges, and so on
category = throwIfUndefined,
// can be a one word the event
// click, play, toggle.
// This is not a hard and fast rule
action = throwIfUndefined,
// any additional information
// when in doubt use redux action type
// or a short sentence describing the action
label,
// used to tack some specific value for a GA event
value
} = throwIfUndefined) => () => ({
analytics: {
type: 'event',
category,
action,
label,
value
}
});
export const appMounted = createAction(types.appMounted);
export const fetchChallenge = createAction(
'' + types.fetchChallenge,
(dashedName, block) => ({ dashedName, block })
);
export const fetchChallengeCompleted = createAction(
types.fetchChallenge.complete,
null,
identity
);
export const fetchChallenges = createAction('' + types.fetchChallenges);
export const fetchChallengesCompleted = createAction(
types.fetchChallenges.complete,
(entities, result) => ({ entities, result }),
entities => ({ entities })
);
export const updateCurrentChallenge = createAction(
types.updateCurrentChallenge
);
// updateTitle(title: String) => Action
export const updateTitle = createAction(types.updateTitle);
// fetchUser() => Action
// used in combination with fetch-user-epic
export const fetchUser = createAction(types.fetchUser);
// addUser(
// entities: { [userId]: User }
// ) => Action
export const addUser = createAction(
types.addUser,
noop,
entities => ({ entities })
);
export const updateThisUser = createAction(types.updateThisUser);
export const showSignIn = createAction(types.showSignIn);
export const updateAppLang = createAction(types.updateAppLang);
// used when server needs client to redirect
export const delayedRedirect = createAction(types.delayedRedirect);
// hardGoTo(path: String) => Action
export const hardGoTo = createAction(types.hardGoTo);
export const createErrorObservable = error => Observable.just({
type: types.handleError,
error
});
// doActionOnError(
// actionCreator: (() => Action|Null)
// ) => (error: Error) => Observable[Action]
export const doActionOnError = actionCreator => error => Observable.of(
{
type: types.handleError,
error
},
actionCreator()
);
export const toggleNightMode = createAction(
types.toggleNightMode,
// we use this function to avoid hanging onto the eventObject
// so that react can recycle it
() => null
);
// updateTheme(theme: /night|default/) => Action
export const updateTheme = createAction(types.updateTheme);
// addThemeToBody(theme: /night|default/) => Action
export const addThemeToBody = createAction(types.addThemeToBody);
const initialState = {
title: 'Learn To Code | freeCodeCamp',
isSignInAttempted: false,
user: '',
lang: '',
csrfToken: '',
theme: 'default',
// eventually this should be only in the user object
currentChallenge: '',
superBlocks: []
};
export const getNS = state => state[ns];
export const langSelector = state => getNS(state).lang;
export const csrfSelector = state => getNS(state).csrfToken;
export const themeSelector = state => getNS(state).theme;
export const titleSelector = state => getNS(state).title;
export const currentChallengeSelector = state => getNS(state).currentChallenge;
export const superBlocksSelector = state => getNS(state).superBlocks;
export const signInLoadingSelector = state => !getNS(state).isSignInAttempted;
export const userSelector = createSelector(
state => getNS(state).user,
state => entitiesSelector(state).user,
(username, userMap) => userMap[username] || {}
);
export const challengeSelector = createSelector(
currentChallengeSelector,
state => entitiesSelector(state).challenge,
(challengeName, challengeMap = {}) => {
return challengeMap[challengeName] || {};
}
);
export const firstChallengeSelector = createSelector(
entitiesSelector,
superBlocksSelector,
(
{
challengeMap,
blockMap,
superBlockMap
},
superBlocks
) => {
if (
!challengeMap ||
!blockMap ||
!superBlockMap ||
!superBlocks
) {
return {};
}
try {
return challengeMap[
blockMap[
superBlockMap[
superBlocks[0]
].blocks[0]
].challenges[0]
];
} catch (err) {
console.error(err);
return {};
}
}
);
export default function createReducer() {
const reducer = handleActions(
{
[types.updateTitle]: (state, { payload = 'Learn To Code' }) => ({
...state,
title: payload + ' | freeCodeCamp'
}),
[types.updateThisUser]: (state, { payload: user }) => ({
...state,
user
}),
[types.fetchChallenge.complete]: (state, { payload }) => ({
...state,
currentChallenge: payload.currentChallenge
}),
[combineActions(
types.fetchChallenge.complete,
types.fetchChallenges.complete
)]: (state, { payload }) => ({
...state,
superBlocks: payload.result.superBlocks
}),
[types.updateCurrentChallenge]: (state, { payload = '' }) => ({
...state,
currentChallenge: payload
}),
[types.updateAppLang]: (state, { payload = 'en' }) =>({
...state,
lang: payload
}),
[types.updateTheme]: (state, { payload = 'default' }) => ({
...state,
theme: payload
}),
[combineActions(types.showSignIn, types.updateThisUser)]: state => ({
...state,
isSignInAttempted: true
}),
[types.challengeSaved]: (state, { payload: { points = 0 } }) => ({
...state,
points
}),
[types.delayedRedirect]: (state, { payload }) => ({
...state,
delayedRedirect: payload
})
},
initialState
);
reducer.toString = () => ns;
return reducer;
}