aboutsummaryrefslogtreecommitdiff
path: root/src/screens/main/NotificationsScreen.tsx
blob: 219a0be94c19b3bc6b77bd81c76d6f4e545b73c0 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
import AsyncStorage from '@react-native-community/async-storage';
import moment from 'moment';
import React, {useCallback, useEffect, useState} from 'react';
import {
  RefreshControl,
  SectionList,
  StyleSheet,
  Text,
  View,
} from 'react-native';
import {SafeAreaView} from 'react-native-safe-area-context';
import {useDispatch, useSelector} from 'react-redux';
import {Notification} from '../../components/notifications';
import {loadUserNotifications} from '../../store/actions';
import {RootState} from '../../store/rootReducer';
import {NotificationType, ScreenType} from '../../types';
import {getDateAge, SCREEN_HEIGHT} from '../../utils';

const NotificationsScreen: React.FC = () => {
  const {user: loggedInUser} = useSelector((state: RootState) => state.user);
  const {moments: loggedInUserMoments} = useSelector(
    (state: RootState) => state.moments,
  );
  const [refreshing, setRefreshing] = useState(false);
  // used for figuring out which ones are unread
  const [lastViewed, setLastViewed] = useState<moment.Moment | undefined>(
    undefined,
  );
  const {notifications} = useSelector(
    (state: RootState) => state.notifications,
  );
  const [sectionedNotifications, setSectionedNotifications] = useState<
    {title: 'Today' | 'Yesterday' | 'This Week'; data: NotificationType[]}[]
  >([]);

  const dispatch = useDispatch();

  const onRefresh = useCallback(() => {
    const refrestState = async () => {
      dispatch(loadUserNotifications());
    };
    setRefreshing(true);
    refrestState().then(() => {
      setRefreshing(false);
    });
  }, [dispatch]);

  // handles storing and fetching the "previously viewed" information
  useEffect(() => {
    const getAndUpdateLastViewed = async () => {
      const key = 'notificationLastViewed';
      const previousLastViewed = await AsyncStorage.getItem(key);
      setLastViewed(
        previousLastViewed == null
          ? moment.unix(0)
          : moment(previousLastViewed),
      );
      await AsyncStorage.setItem(key, moment().toString());
    };
    getAndUpdateLastViewed();
  }, [notifications]);

  // handles sectioning notifications to "date age"
  // mark notifications as read or unread
  useEffect(() => {
    const sortedNotifications = (notifications ?? [])
      .slice()
      .sort((a, b) => (a.timestamp < b.timestamp ? 1 : -1));
    let todays = [];
    let yesterdays = [];
    let thisWeeks = [];
    for (const n of sortedNotifications) {
      const notificationDate = moment(n.timestamp);
      const dateAge = getDateAge(notificationDate);
      if (dateAge === 'unknown') {
        continue;
      }
      const unread = lastViewed ? lastViewed.diff(notificationDate) < 0 : false;
      const newN = {...n, unread};
      switch (dateAge) {
        case 'today':
          todays.push(newN);
          continue;
        case 'yesterday':
          yesterdays.push(newN);
          continue;
        case 'thisWeek':
          thisWeeks.push(newN);
          continue;
        default:
          continue;
      }
    }
    setSectionedNotifications([
      {title: 'Today', data: todays},
      {title: 'Yesterday', data: yesterdays},
      {title: 'This Week', data: thisWeeks},
    ]);
  }, [lastViewed, notifications]);

  const renderNotification = ({item}: {item: NotificationType}) => (
    <Notification
      item={item}
      screenType={ScreenType.Notifications}
      moments={item.notification_type === 'CMT' ? loggedInUserMoments : []}
    />
  );

  const renderSectionHeader = ({section: {title, data}}) =>
    data.length !== 0 && (
      <View style={styles.sectionHeaderContainer}>
        <Text style={styles.sectionHeader}>{title}</Text>
      </View>
    );

  return (
    <SafeAreaView>
      <View style={styles.header}>
        <Text style={styles.headerText}>Notifications</Text>
        <View style={styles.underline} />
      </View>
      <SectionList
        contentContainerStyle={styles.container}
        sections={sectionedNotifications}
        keyExtractor={(item, index) => index.toString()}
        renderItem={renderNotification}
        renderSectionHeader={renderSectionHeader}
        refreshControl={
          <RefreshControl refreshing={refreshing} onRefresh={onRefresh} />
        }
      />
    </SafeAreaView>
  );
};

const styles = StyleSheet.create({
  header: {
    marginLeft: '8%',
    marginTop: '5%',
    alignSelf: 'flex-start',
    flexDirection: 'column',
  },
  headerText: {
    fontWeight: 'bold',
    fontSize: 16,
  },
  underline: {
    borderWidth: 2,
    borderColor: '#8F01FF',
  },
  container: {
    paddingBottom: '20%',
    minHeight: (SCREEN_HEIGHT * 8) / 10,
  },
  sectionHeaderContainer: {
    width: '100%',
    backgroundColor: '#f3f2f2',
  },
  sectionHeader: {
    marginLeft: '8%',
    marginTop: '5%',
    marginBottom: '2%',
    fontSize: 15,
  },
});

export default NotificationsScreen;