@mongodb-js/mongodb-ui-components
Version:
A collection of frequently used functional UI components found on mongodb properties
99 lines (77 loc) • 2.29 kB
JavaScript
'use strict';
import React, { Component } from 'react';
export default class NavBackground extends Component {
constructor(props) {
super(props);
this.state = {
isOpaque: this.props.isOpaque,
isOpen: this.props.isOpen,
backgroundOpacity: 0.9
};
this.onScroll = this.onScroll.bind(this);
}
componentDidMount() {
window.addEventListener('scroll', () => {
if (this.RafId) return;
this.RafId = window.requestAnimationFrame(this.onScroll);
});
}
onScroll() {
if (this.props.isOpen) {
this.RafId = undefined;
return;
}
const y = window.scrollY || window.pageYOffset;
const { isOpaque } = this.state;
if (y >= 50 && !isOpaque) {
this.setState({ isOpaque: true });
} else if (!this.props.isOpaque && y < 50 && isOpaque) {
this.setState({ isOpaque: false });
}
this.RafId = undefined;
}
componentWillReceiveProps(props) {
const obj = {};
if (props.isOpen) {
obj.isOpen = props.isOpen;
}
if (props.isOpaque) {
const y = window.scrollY || window.pageYOffset;
obj.isOpaque = y < 50 ? props.isOpaque : true;
}
this.setState(obj);
if (!props.isOpen) return;
const listener = this.hasTouch ? 'touchend' : 'mouseup';
const setActiveSection = this.props.setActiveSection;
window.addEventListener(listener, function onWindowPress(e) {
let el = e.target;
let toTrigger = true;
while (el) {
if (el !== undefined && el.className !== undefined && el.className.indexOf !== undefined && el.className.indexOf('m-nav') > -1) {
toTrigger = false;
break;
}
el = el.parentNode;
}
if (toTrigger) {
setActiveSection(-1);
window.removeEventListener(listener, onWindowPress);
}
});
}
render() {
let classnames = 'm-nav-bg m-nav-flex-x';
if (this.props.isOpen) classnames += ' m-nav-bg-open';
if (this.state.isOpaque) classnames += ' m-nav-bg-opaque';
return React.createElement(
'div',
{
ref: el => {
this.root = el;
},
className: classnames,
style: this.props.isTopNavHidden ? { top: '-45px' } : null },
this.props.children
);
}
}