11import { Injectable } from '@angular/core' ;
22import { BehaviorSubject } from 'rxjs' ;
33import { environment } from '../../../environments/environment' ;
4+ import { UUIDService } from '../../core/shared/uuid.service' ;
45
56@Injectable ( {
67 providedIn : 'root' ,
78} )
89export class LiveRegionService {
910
11+ constructor (
12+ protected uuidService : UUIDService ,
13+ ) {
14+ }
15+
1016 /**
1117 * The duration after which the messages disappear in milliseconds
1218 * @protected
1319 */
1420 protected messageTimeOutDurationMs : number = environment . liveRegion . messageTimeOutDurationMs ;
1521
1622 /**
17- * Array containing the messages that should be shown in the live region
23+ * Array containing the messages that should be shown in the live region,
24+ * together with a uuid, so they can be uniquely identified
1825 * @protected
1926 */
20- protected messages : string [ ] = [ ] ;
27+ protected messages : { message : string , uuid : string } [ ] = [ ] ;
2128
2229 /**
2330 * BehaviorSubject emitting the array with messages every time the array updates
@@ -34,27 +41,28 @@ export class LiveRegionService {
3441 /**
3542 * Returns a copy of the array with the current live region messages
3643 */
37- getMessages ( ) {
38- return [ ... this . messages ] ;
44+ getMessages ( ) : string [ ] {
45+ return this . messages . map ( messageObj => messageObj . message ) ;
3946 }
4047
4148 /**
4249 * Returns the BehaviorSubject emitting the array with messages every time the array updates
4350 */
44- getMessages$ ( ) {
51+ getMessages$ ( ) : BehaviorSubject < string [ ] > {
4552 return this . messages$ ;
4653 }
4754
4855 /**
4956 * Adds a message to the live-region messages array
5057 * @param message
58+ * @return The uuid of the message
5159 */
52- addMessage ( message : string ) {
53- this . messages . push ( message ) ;
60+ addMessage ( message : string ) : string {
61+ const uuid = this . uuidService . generate ( ) ;
62+ this . messages . push ( { message, uuid } ) ;
63+ setTimeout ( ( ) => this . clearMessageByUUID ( uuid ) , this . messageTimeOutDurationMs ) ;
5464 this . emitCurrentMessages ( ) ;
55-
56- // Clear the message once the timeOut has passed
57- setTimeout ( ( ) => this . pop ( ) , this . messageTimeOutDurationMs ) ;
65+ return uuid ;
5866 }
5967
6068 /**
@@ -66,12 +74,15 @@ export class LiveRegionService {
6674 }
6775
6876 /**
69- * Removes the longest living message from the array.
77+ * Removes the message with the given UUID from the messages array
78+ * @param uuid The uuid of the message to clear
7079 * @protected
7180 */
72- protected pop ( ) {
73- if ( this . messages . length > 0 ) {
74- this . messages . shift ( ) ;
81+ clearMessageByUUID ( uuid : string ) {
82+ const index = this . messages . findIndex ( messageObj => messageObj . uuid === uuid ) ;
83+
84+ if ( index !== - 1 ) {
85+ this . messages . splice ( index , 1 ) ;
7586 this . emitCurrentMessages ( ) ;
7687 }
7788 }
0 commit comments