Notifications.jsx 2.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172
  1. /*
  2. Copyright (C) 2017 Cloudbase Solutions SRL
  3. This program is free software: you can redistribute it and/or modify
  4. it under the terms of the GNU Affero General Public License as
  5. published by the Free Software Foundation, either version 3 of the
  6. License, or (at your option) any later version.
  7. This program is distributed in the hope that it will be useful,
  8. but WITHOUT ANY WARRANTY; without even the implied warranty of
  9. MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  10. GNU Affero General Public License for more details.
  11. You should have received a copy of the GNU Affero General Public License
  12. along with this program. If not, see <http://www.gnu.org/licenses/>.
  13. */
  14. // @flow
  15. import React from 'react'
  16. import { observer } from 'mobx-react'
  17. import styled, { injectGlobal } from 'styled-components'
  18. import NotificationSystem from 'react-notification-system'
  19. import { observe } from 'mobx'
  20. import notificationStore from '../../../stores/NotificationStore'
  21. import type { AlertInfo } from '../../../types/NotificationItem'
  22. import NotificationsStyle from './style.js'
  23. injectGlobal`
  24. ${NotificationsStyle}
  25. `
  26. const Wrapper = styled.div``
  27. @observer
  28. class Notifications extends React.Component<{}> {
  29. notificationSystem: NotificationSystem
  30. notificationsCount = 0
  31. componentDidMount() {
  32. observe(notificationStore.alerts, change => {
  33. this.handleStoreChange(change.object)
  34. })
  35. }
  36. handleStoreChange(alerts: AlertInfo[]) {
  37. if (!alerts.length || alerts.length <= this.notificationsCount) {
  38. return
  39. }
  40. let lastNotification = alerts[alerts.length - 1]
  41. this.notificationSystem.addNotification({
  42. title: lastNotification.title || lastNotification.message,
  43. message: lastNotification.title ? lastNotification.message : null,
  44. level: lastNotification.level || 'info',
  45. position: 'br',
  46. autoDismiss: lastNotification.message.length < 150 ? 10 : 30,
  47. action: lastNotification.options ? lastNotification.options.action : null,
  48. })
  49. this.notificationsCount = alerts.length
  50. }
  51. render() {
  52. return (
  53. <Wrapper>
  54. <NotificationSystem ref={(n) => { this.notificationSystem = n }} />
  55. </Wrapper>
  56. )
  57. }
  58. }
  59. export default Notifications