Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
Wrap updates-for-element in an IntersectionObserver (#285)
- Loading branch information
1 parent
58a9799
commit 951d5dc
Showing
3 changed files
with
110 additions
and
3 deletions.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,59 @@ | ||
export class AppearanceObserver { | ||
constructor (delegate, element = null) { | ||
this.delegate = delegate | ||
this.element = element || delegate | ||
this.started = false | ||
this.intersecting = false | ||
|
||
this.intersectionObserver = new IntersectionObserver(this.intersect) | ||
} | ||
|
||
start () { | ||
if (!this.started) { | ||
this.started = true | ||
this.intersectionObserver.observe(this.element) | ||
this.observeVisibility() | ||
} | ||
} | ||
|
||
stop () { | ||
if (this.started) { | ||
this.started = false | ||
this.intersectionObserver.unobserve(this.element) | ||
this.unobserveVisibility() | ||
} | ||
} | ||
|
||
observeVisibility = () => { | ||
document.addEventListener('visibilitychange', this.handleVisibilityChange) | ||
} | ||
|
||
unobserveVisibility = () => { | ||
document.removeEventListener( | ||
'visibilitychange', | ||
this.handleVisibilityChange | ||
) | ||
} | ||
|
||
intersect = entries => { | ||
entries.forEach(entry => { | ||
if (entry.target === this.element) { | ||
if (entry.isIntersecting && document.visibilityState === 'visible') { | ||
this.intersecting = true | ||
this.delegate.appearedInViewport() | ||
} else { | ||
this.intersecting = false | ||
this.delegate.disappearedFromViewport() | ||
} | ||
} | ||
}) | ||
} | ||
|
||
handleVisibilityChange = event => { | ||
if (document.visibilityState === 'visible' && this.intersecting) { | ||
this.delegate.appearedInViewport() | ||
} else { | ||
this.delegate.disappearedFromViewport() | ||
} | ||
} | ||
} |