1
1
import React from 'react' ;
2
2
import PropTypes from 'prop-types' ;
3
+ import findLastIndex from 'lodash/findLastIndex' ;
3
4
4
5
export const NotificationsContext = React . createContext ( { } ) ;
6
+ const maxTransientNotifications = 5 ;
7
+ const maxStoredNotifications = 40 ;
5
8
6
9
export class Notifications extends React . Component {
7
10
constructor ( props ) {
@@ -49,12 +52,16 @@ export class Notifications extends React.Component {
49
52
opts = opts || { } ;
50
53
severity = severity || 'info' ;
51
54
const { notifications, storedNotifications } = this . state ;
52
- const maxNsNotifications = 5 ;
53
55
const notification = { ...opts , message, severity, created : Date . now ( ) } ;
54
- const newNotifications = [ notification , ...notifications ] ;
56
+ const trimmedNotifications =
57
+ notifications >= maxTransientNotifications
58
+ ? this . withoutOldestTransient ( notifications )
59
+ : notifications ;
60
+
61
+ const newNotifications = [ notification , ...trimmedNotifications ] ;
55
62
56
63
storedNotifications . unshift ( notification ) ;
57
- storedNotifications . splice ( 40 ) ;
64
+ storedNotifications . splice ( maxStoredNotifications ) ;
58
65
localStorage . setItem ( 'notifications' , JSON . stringify ( storedNotifications ) ) ;
59
66
60
67
this . setValue (
@@ -64,10 +71,6 @@ export class Notifications extends React.Component {
64
71
} ,
65
72
( ) => {
66
73
if ( ! opts . sticky ) {
67
- if ( notifications . length > maxNsNotifications ) {
68
- this . shift ( ) ;
69
- return ;
70
- }
71
74
setTimeout ( this . shift , 4000 , true ) ;
72
75
}
73
76
} ,
@@ -96,6 +99,15 @@ export class Notifications extends React.Component {
96
99
this . removeNotification ( notifications . findIndex ( n => ! n . sticky ) , delay ) ;
97
100
} ;
98
101
102
+ withoutOldestTransient = notifications => {
103
+ const last = findLastIndex ( notifications , n => ! n . sticky ) ;
104
+
105
+ if ( last ) {
106
+ notifications . splice ( last , 1 ) ;
107
+ }
108
+ return notifications ;
109
+ } ;
110
+
99
111
/*
100
112
* Clear the list of stored notifications
101
113
*/
0 commit comments