1
1
import React from 'react' ;
2
2
import PropTypes from 'prop-types' ;
3
+ import PageVisibility from 'react-page-visibility' ;
3
4
4
5
const DELAY = 500 ;
5
6
@@ -15,7 +16,8 @@ export default class Visualizer extends React.PureComponent {
15
16
baseColour : 'rgb(10, 10, 35)' ,
16
17
translucent : 'rgba(10, 10, 35, 0.6)' ,
17
18
multiplier : 0.7529
18
- }
19
+ } ,
20
+ isTabVisible : true ,
19
21
} ;
20
22
}
21
23
@@ -24,21 +26,31 @@ export default class Visualizer extends React.PureComponent {
24
26
// of the audio context stuff AFTER the audio has been triggered.
25
27
// We can't see it until
26
28
// then anyway so it makes no difference to desktop.
27
- componentDidUpdate ( prevProps ) {
28
- if ( prevProps . playing !== this . props . playing ) {
29
- if ( this . props . playing ) {
29
+ componentDidUpdate ( prevProps , prevState ) {
30
+ if ( prevProps . playing === this . props . playing && prevState . isTabVisible === this . state . isTabVisible ) {
31
+ return
32
+ }
33
+
34
+ // If the player is playing and the tab is being active,
35
+ // draw the visualization
36
+ if ( this . props . playing && this . state . isTabVisible ) {
37
+ // Create a new audio context if there isn't one available
38
+ if ( ! this . state . eq . context ) {
30
39
this . initiateEQ ( ) ;
31
- this . createVisualizer ( ) ;
32
- this . startDrawing ( ) ;
33
- } else {
34
- // Workaround componentWillUnmount to delay the clean up and achieve fadeout animation
35
- setTimeout ( ( ) => {
36
- // Note: Order matters.
37
- // Stop the drawing loop first (using this.rafId), then set the ID to null
38
- this . stopDrawing ( ) ;
39
- this . reset ( ) ;
40
- } , DELAY ) ;
41
40
}
41
+ this . createVisualizer ( ) ;
42
+ this . startDrawing ( ) ;
43
+ }
44
+ // If the player is not playing or the tab is running in the background,
45
+ // stop the animation
46
+ else {
47
+ // Workaround for componentWillUnmount to delay the clean up and achieve fadeout animation
48
+ setTimeout ( ( ) => {
49
+ // Note: Order matters.
50
+ // Stop the drawing loop first (using this.rafId), then set the ID to null
51
+ this . stopDrawing ( ) ;
52
+ this . reset ( ) ;
53
+ } , DELAY ) ;
42
54
}
43
55
}
44
56
@@ -167,11 +179,17 @@ export default class Visualizer extends React.PureComponent {
167
179
this . visualizer . ctx . fill ( ) ;
168
180
}
169
181
182
+ handleVisibilityChange = isTabVisible => {
183
+ this . setState ( { isTabVisible } ) ;
184
+ }
185
+
170
186
render ( ) {
171
187
return (
172
- < div id = 'visualizer' >
173
- < canvas aria-label = 'visualizer' ref = { a => ( this . _canvas = a ) } />
174
- </ div >
188
+ < PageVisibility onChange = { this . handleVisibilityChange } >
189
+ < div id = 'visualizer' >
190
+ < canvas aria-label = 'visualizer' ref = { a => ( this . _canvas = a ) } />
191
+ </ div >
192
+ </ PageVisibility >
175
193
) ;
176
194
}
177
195
}
0 commit comments