The code powering m.abunchtell.com https://m.abunchtell.com
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.
 
 
 
 

80 lines
2.1 KiB

  1. import { Map as ImmutableMap, List as ImmutableList } from 'immutable';
  2. import {
  3. CONVERSATIONS_FETCH_REQUEST,
  4. CONVERSATIONS_FETCH_SUCCESS,
  5. CONVERSATIONS_FETCH_FAIL,
  6. CONVERSATIONS_UPDATE,
  7. } from '../actions/conversations';
  8. import compareId from '../compare_id';
  9. const initialState = ImmutableMap({
  10. items: ImmutableList(),
  11. isLoading: false,
  12. hasMore: true,
  13. });
  14. const conversationToMap = item => ImmutableMap({
  15. id: item.id,
  16. accounts: ImmutableList(item.accounts.map(a => a.id)),
  17. last_status: item.last_status.id,
  18. });
  19. const updateConversation = (state, item) => state.update('items', list => {
  20. const index = list.findIndex(x => x.get('id') === item.id);
  21. const newItem = conversationToMap(item);
  22. if (index === -1) {
  23. return list.unshift(newItem);
  24. } else {
  25. return list.set(index, newItem);
  26. }
  27. });
  28. const expandNormalizedConversations = (state, conversations, next) => {
  29. let items = ImmutableList(conversations.map(conversationToMap));
  30. return state.withMutations(mutable => {
  31. if (!items.isEmpty()) {
  32. mutable.update('items', list => {
  33. list = list.map(oldItem => {
  34. const newItemIndex = items.findIndex(x => x.get('id') === oldItem.get('id'));
  35. if (newItemIndex === -1) {
  36. return oldItem;
  37. }
  38. const newItem = items.get(newItemIndex);
  39. items = items.delete(newItemIndex);
  40. return newItem;
  41. });
  42. list = list.concat(items);
  43. return list.sortBy(x => x.get('last_status'), (a, b) => compareId(a, b) * -1);
  44. });
  45. }
  46. if (!next) {
  47. mutable.set('hasMore', false);
  48. }
  49. mutable.set('isLoading', false);
  50. });
  51. };
  52. export default function conversations(state = initialState, action) {
  53. switch (action.type) {
  54. case CONVERSATIONS_FETCH_REQUEST:
  55. return state.set('isLoading', true);
  56. case CONVERSATIONS_FETCH_FAIL:
  57. return state.set('isLoading', false);
  58. case CONVERSATIONS_FETCH_SUCCESS:
  59. return expandNormalizedConversations(state, action.conversations, action.next);
  60. case CONVERSATIONS_UPDATE:
  61. return updateConversation(state, action.conversation);
  62. default:
  63. return state;
  64. }
  65. };