2017-06-11 11:07:35 -04:00
|
|
|
import { CONTEXT_FETCH_SUCCESS } from '../actions/statuses';
|
2017-10-03 19:01:44 -04:00
|
|
|
import { TIMELINE_DELETE, TIMELINE_CONTEXT_UPDATE } from '../actions/timelines';
|
|
|
|
import { Map as ImmutableMap, List as ImmutableList } from 'immutable';
|
2017-06-11 11:07:35 -04:00
|
|
|
|
2017-07-10 19:00:14 -04:00
|
|
|
const initialState = ImmutableMap({
|
|
|
|
ancestors: ImmutableMap(),
|
|
|
|
descendants: ImmutableMap(),
|
2017-06-11 11:07:35 -04:00
|
|
|
});
|
|
|
|
|
|
|
|
const normalizeContext = (state, id, ancestors, descendants) => {
|
2017-10-03 19:01:44 -04:00
|
|
|
const ancestorsIds = ImmutableList(ancestors.map(ancestor => ancestor.id));
|
|
|
|
const descendantsIds = ImmutableList(descendants.map(descendant => descendant.id));
|
2017-06-11 11:07:35 -04:00
|
|
|
|
|
|
|
return state.withMutations(map => {
|
|
|
|
map.setIn(['ancestors', id], ancestorsIds);
|
|
|
|
map.setIn(['descendants', id], descendantsIds);
|
|
|
|
});
|
|
|
|
};
|
|
|
|
|
|
|
|
const deleteFromContexts = (state, id) => {
|
2017-07-10 19:00:14 -04:00
|
|
|
state.getIn(['descendants', id], ImmutableList()).forEach(descendantId => {
|
|
|
|
state = state.updateIn(['ancestors', descendantId], ImmutableList(), list => list.filterNot(itemId => itemId === id));
|
2017-06-11 11:07:35 -04:00
|
|
|
});
|
|
|
|
|
2017-07-10 19:00:14 -04:00
|
|
|
state.getIn(['ancestors', id], ImmutableList()).forEach(ancestorId => {
|
|
|
|
state = state.updateIn(['descendants', ancestorId], ImmutableList(), list => list.filterNot(itemId => itemId === id));
|
2017-06-11 11:07:35 -04:00
|
|
|
});
|
|
|
|
|
|
|
|
state = state.deleteIn(['descendants', id]).deleteIn(['ancestors', id]);
|
|
|
|
|
|
|
|
return state;
|
|
|
|
};
|
|
|
|
|
2017-10-03 19:01:44 -04:00
|
|
|
const updateContext = (state, status, references) => {
|
|
|
|
return state.update('descendants', map => {
|
|
|
|
references.forEach(parentId => {
|
2017-10-07 06:16:39 -04:00
|
|
|
map = map.update(parentId, ImmutableList(), list => {
|
|
|
|
if (list.includes(status.id)) {
|
|
|
|
return list;
|
|
|
|
}
|
|
|
|
|
|
|
|
return list.push(status.id);
|
|
|
|
});
|
2017-10-03 19:01:44 -04:00
|
|
|
});
|
|
|
|
|
|
|
|
return map;
|
|
|
|
});
|
|
|
|
};
|
|
|
|
|
2017-06-11 11:07:35 -04:00
|
|
|
export default function contexts(state = initialState, action) {
|
|
|
|
switch(action.type) {
|
|
|
|
case CONTEXT_FETCH_SUCCESS:
|
2017-10-03 19:01:44 -04:00
|
|
|
return normalizeContext(state, action.id, action.ancestors, action.descendants);
|
2017-06-11 11:07:35 -04:00
|
|
|
case TIMELINE_DELETE:
|
|
|
|
return deleteFromContexts(state, action.id);
|
2017-10-03 19:01:44 -04:00
|
|
|
case TIMELINE_CONTEXT_UPDATE:
|
|
|
|
return updateContext(state, action.status, action.references);
|
2017-06-11 11:07:35 -04:00
|
|
|
default:
|
|
|
|
return state;
|
|
|
|
}
|
|
|
|
};
|