metamaps--metamaps/src/Metamaps/GlobalUI/Notifications.js

93 lines
2.5 KiB
JavaScript
Raw Normal View History

2017-10-13 12:13:08 -04:00
/* global $ */
2018-03-07 15:35:27 -05:00
import { findIndex } from 'lodash'
2017-09-22 18:38:38 -04:00
import GlobalUI from './index'
const Notifications = {
2018-03-07 15:35:27 -05:00
notifications: [],
2018-03-07 18:38:53 -05:00
notificationsLoading: false,
2017-09-22 18:38:38 -04:00
unreadNotificationsCount: 0,
init: serverData => {
if (serverData.ActiveMapper) {
Notifications.unreadNotificationsCount = serverData.ActiveMapper.unread_notifications_count
}
2017-09-22 18:38:38 -04:00
},
2018-03-07 15:35:27 -05:00
fetchNotifications: render => {
2018-03-07 18:38:53 -05:00
Notifications.notificationsLoading = true
render()
$.ajax({
url: '/notifications.json',
success: function(data) {
Notifications.notifications = data
2018-03-07 18:38:53 -05:00
Notifications.notificationsLoading = false
render()
2018-03-07 18:38:53 -05:00
},
error: function() {
GlobalUI.notifyUser('There was an error fetching notifications')
}
})
2017-09-22 18:38:38 -04:00
},
2018-03-07 15:35:27 -05:00
fetchNotification: (render, id) => {
$.ajax({
url: `/notifications/${id}.json`,
success: function(data) {
const index = findIndex(Notifications.notifications, n => n.id === data.id)
if (index === -1) {
// notification not loaded yet, insert it at the start
Notifications.notifications.unshift(data)
} else {
// notification there, replace it
Notifications.notifications[index] = data
}
render()
},
error: function() {
GlobalUI.notifyUser('There was an error fetching that notification')
}
})
},
2017-09-25 15:21:04 -04:00
incrementUnread: (render) => {
Notifications.unreadNotificationsCount++
render()
},
decrementUnread: (render) => {
Notifications.unreadNotificationsCount--
render()
},
2017-09-22 18:38:38 -04:00
markAsRead: (render, id) => {
const n = Notifications.notifications.find(n => n.id === id)
$.ajax({
url: `/notifications/${id}/mark_read.json`,
2017-09-22 18:38:38 -04:00
method: 'PUT',
success: function(r) {
if (n) {
2017-09-29 14:05:39 -04:00
Notifications.unreadNotificationsCount--
2017-09-22 18:38:38 -04:00
n.is_read = true
render()
}
},
error: function() {
GlobalUI.notifyUser('There was an error marking that notification as read')
}
})
},
markAsUnread: (render, id) => {
const n = Notifications.notifications.find(n => n.id === id)
$.ajax({
url: `/notifications/${id}/mark_unread.json`,
2017-09-22 18:38:38 -04:00
method: 'PUT',
success: function() {
if (n) {
Notifications.unreadNotificationsCount++
n.is_read = false
render()
}
},
error: function() {
2018-03-07 15:35:27 -05:00
GlobalUI.notifyUser('There was an error marking that notification as unread')
2017-09-22 18:38:38 -04:00
}
})
}
}
export default Notifications