Created
April 13, 2016 21:53
-
-
Save amcdnl/1bb0e8294b480afe07b8c726894dbe2e to your computer and use it in GitHub Desktop.
This file contains hidden or 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
| import { EventEmitter } from 'angular2/core.js'; | |
| /** | |
| * Visibility Observer leveraging new IntersectionObserver API | |
| * Idea from: https://github.com/WICG/IntersectionObserver | |
| */ | |
| export class VisibilityObserver { | |
| onVisible = new EventEmitter(); | |
| constructor(element) { | |
| if(window.IntersectionObserver) { | |
| this.observer = new IntersectionObserver( | |
| ::this.processChanges, { threshold: [0.5] }); | |
| this.observer.observe(element); | |
| } | |
| } | |
| isVisible(boundingClientRect, intersectionRect) { | |
| return ((intersectionRect.width * intersectionRect.height) / | |
| (boundingClientRect.width * boundingClientRect.height) >= 0.5); | |
| } | |
| visibleTimerCallback(element, observer) { | |
| delete element.visibleTimeout; | |
| // Process any pending observations | |
| this.processChanges(observer.takeRecords()); | |
| if ('isVisible' in element) { | |
| delete element.isVisible; | |
| this.onVisible.emit(); | |
| observer.unobserve(element); | |
| } | |
| } | |
| processChanges(changes) { | |
| changes.forEach((changeRecord) => { | |
| var element = changeRecord.target; | |
| element.isVisible = this.isVisible(changeRecord.boundingClientRect, changeRecord.intersectionRect); | |
| if ('isVisible' in element) { | |
| // Transitioned from hidden to visible | |
| element.visibleTimeout = setTimeout(::this.visibleTimerCallback, 1000, element, this.observer); | |
| } else { | |
| // Transitioned from visible to hidden | |
| if ('visibleTimeout' in element) { | |
| clearTimeout(element.visibleTimeout); | |
| delete element.visibleTimeout; | |
| } | |
| } | |
| }); | |
| } | |
| } |
This file contains hidden or 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
| import { Directive, Output, EventEmitter, ElementRef } from 'angular2/core.js'; | |
| import { VisibilityObserver } from './VisibilityObserver.js'; | |
| @Directive({ selector: '[visibility-observer]' }) | |
| export class VisibilityObserverDirective { | |
| @Output() | |
| onVisible = new EventEmitter(); | |
| constructor(element: ElementRef) { | |
| new VisibilityObserver(element.nativeElement) | |
| .onVisible.subscribe(::this.visbilityChange) | |
| } | |
| visbilityChange() { | |
| this.onVisible.emit(true); | |
| } | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment