redoc/lib/shared/components/StickySidebar/sticky-sidebar.ts

67 lines
1.8 KiB
TypeScript
Raw Normal View History

2015-12-26 20:44:39 +03:00
'use strict';
import { Directive, ElementRef, Input, OnInit, OnDestroy } from '@angular/core';
2016-05-05 11:05:02 +03:00
import {BrowserDomAdapter} from '@angular/platform-browser/src/browser/browser_adapter';
2015-12-26 20:44:39 +03:00
2016-01-21 01:09:42 +03:00
@Directive({
selector: '[sticky-sidebar]'
2015-12-26 20:44:39 +03:00
})
export class StickySidebar implements OnInit, OnDestroy {
$element: any;
cancelScrollBinding: any;
$redocEl: any;
@Input() scrollParent:any;
@Input() scrollYOffset:any;
2016-06-13 20:54:24 +03:00
constructor(elementRef:ElementRef, private dom:BrowserDomAdapter) {
this.$element = elementRef.nativeElement;
2015-12-26 20:44:39 +03:00
// initial styling
this.dom.setStyle(this.$element, 'position', 'absolute');
this.dom.setStyle(this.$element, 'top', '0');
this.dom.setStyle(this.$element, 'bottom', '0');
this.dom.setStyle(this.$element, 'max-height', '100%');
2015-12-26 20:44:39 +03:00
}
bind() {
2016-01-21 01:09:42 +03:00
this.cancelScrollBinding = this.dom.onAndCancel(this.scrollParent, 'scroll', () => { this.updatePosition(); });
2015-12-26 20:44:39 +03:00
this.updatePosition();
}
unbind() {
2016-06-13 20:54:24 +03:00
if (this.cancelScrollBinding) this.cancelScrollBinding();
2015-12-26 20:44:39 +03:00
}
updatePosition() {
if ( this.scrollY + this.scrollYOffset() >= this.$redocEl.offsetTop) {
2015-12-26 20:44:39 +03:00
this.stick();
} else {
this.unstick();
}
}
stick() {
this.dom.setStyle(this.$element, 'position', 'fixed');
this.dom.setStyle(this.$element, 'top', this.scrollYOffset() + 'px');
2015-12-26 20:44:39 +03:00
}
unstick() {
this.dom.setStyle(this.$element, 'position', 'absolute');
this.dom.setStyle(this.$element, 'top', '0');
2015-12-26 20:44:39 +03:00
}
get scrollY() {
2016-06-13 20:54:24 +03:00
return (this.scrollParent.pageYOffset != undefined) ? this.scrollParent.pageYOffset : this.scrollParent.scrollTop;
2015-12-26 20:44:39 +03:00
}
ngOnInit() {
// FIXME use more reliable code
this.$redocEl = this.$element.offsetParent || this.dom.defaultDoc().body;
2015-12-26 20:44:39 +03:00
this.bind();
}
ngOnDestroy() {
this.unbind();
}
}