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