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.

81 lines
2.4 KiB

  1. import {
  2. NOTIFICATIONS_UPDATE,
  3. NOTIFICATIONS_REFRESH_SUCCESS,
  4. NOTIFICATIONS_EXPAND_SUCCESS,
  5. NOTIFICATIONS_REFRESH_REQUEST,
  6. NOTIFICATIONS_EXPAND_REQUEST,
  7. NOTIFICATIONS_REFRESH_FAIL,
  8. NOTIFICATIONS_EXPAND_FAIL
  9. } from '../actions/notifications';
  10. import { ACCOUNT_BLOCK_SUCCESS } from '../actions/accounts';
  11. import Immutable from 'immutable';
  12. const initialState = Immutable.Map({
  13. items: Immutable.List(),
  14. next: null,
  15. loaded: false,
  16. isLoading: true
  17. });
  18. const notificationToMap = notification => Immutable.Map({
  19. id: notification.id,
  20. type: notification.type,
  21. account: notification.account.id,
  22. status: notification.status ? notification.status.id : null
  23. });
  24. const normalizeNotification = (state, notification) => {
  25. return state.update('items', list => list.unshift(notificationToMap(notification)));
  26. };
  27. const normalizeNotifications = (state, notifications, next) => {
  28. let items = Immutable.List();
  29. const loaded = state.get('loaded');
  30. notifications.forEach((n, i) => {
  31. items = items.set(i, notificationToMap(n));
  32. });
  33. return state
  34. .update('items', list => loaded ? list.unshift(...items) : list.push(...items))
  35. .set('next', next)
  36. .set('loaded', true)
  37. .set('isLoading', false);
  38. };
  39. const appendNormalizedNotifications = (state, notifications, next) => {
  40. let items = Immutable.List();
  41. notifications.forEach((n, i) => {
  42. items = items.set(i, notificationToMap(n));
  43. });
  44. return state
  45. .update('items', list => list.push(...items))
  46. .set('next', next)
  47. .set('isLoading', false);
  48. };
  49. const filterNotifications = (state, relationship) => {
  50. return state.update('items', list => list.filterNot(item => item.get('account') === relationship.id));
  51. };
  52. export default function notifications(state = initialState, action) {
  53. switch(action.type) {
  54. case NOTIFICATIONS_REFRESH_REQUEST:
  55. case NOTIFICATIONS_EXPAND_REQUEST:
  56. case NOTIFICATIONS_REFRESH_FAIL:
  57. case NOTIFICATIONS_EXPAND_FAIL:
  58. return state.set('isLoading', true);
  59. case NOTIFICATIONS_UPDATE:
  60. return normalizeNotification(state, action.notification);
  61. case NOTIFICATIONS_REFRESH_SUCCESS:
  62. return normalizeNotifications(state, action.notifications, action.next);
  63. case NOTIFICATIONS_EXPAND_SUCCESS:
  64. return appendNormalizedNotifications(state, action.notifications, action.next);
  65. case ACCOUNT_BLOCK_SUCCESS:
  66. return filterNotifications(state, action.relationship);
  67. default:
  68. return state;
  69. }
  70. };