You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

43 lines
1.5 KiB

  1. import { CONTEXT_FETCH_SUCCESS } from '../actions/statuses';
  2. import { TIMELINE_DELETE } from '../actions/timelines';
  3. import Immutable from 'immutable';
  4. const initialState = Immutable.Map({
  5. ancestors: Immutable.Map(),
  6. descendants: Immutable.Map(),
  7. });
  8. const normalizeContext = (state, id, ancestors, descendants) => {
  9. const ancestorsIds = ancestors.map(ancestor => ancestor.get('id'));
  10. const descendantsIds = descendants.map(descendant => descendant.get('id'));
  11. return state.withMutations(map => {
  12. map.setIn(['ancestors', id], ancestorsIds);
  13. map.setIn(['descendants', id], descendantsIds);
  14. });
  15. };
  16. const deleteFromContexts = (state, id) => {
  17. state.getIn(['descendants', id], Immutable.List()).forEach(descendantId => {
  18. state = state.updateIn(['ancestors', descendantId], Immutable.List(), list => list.filterNot(itemId => itemId === id));
  19. });
  20. state.getIn(['ancestors', id], Immutable.List()).forEach(ancestorId => {
  21. state = state.updateIn(['descendants', ancestorId], Immutable.List(), list => list.filterNot(itemId => itemId === id));
  22. });
  23. state = state.deleteIn(['descendants', id]).deleteIn(['ancestors', id]);
  24. return state;
  25. };
  26. export default function contexts(state = initialState, action) {
  27. switch(action.type) {
  28. case CONTEXT_FETCH_SUCCESS:
  29. return normalizeContext(state, action.id, Immutable.fromJS(action.ancestors), Immutable.fromJS(action.descendants));
  30. case TIMELINE_DELETE:
  31. return deleteFromContexts(state, action.id);
  32. default:
  33. return state;
  34. }
  35. };