rsuite
Version:
A suite of react components
119 lines (103 loc) • 3.26 kB
JavaScript
import _extends from "@babel/runtime/helpers/esm/extends";
import _inheritsLoose from "@babel/runtime/helpers/esm/inheritsLoose";
import * as React from 'react';
import PropTypes from 'prop-types';
import classNames from 'classnames';
import { on, getOffset } from 'dom-lib';
import bindElementResize, { unbind as unbindElementResize } from 'element-resize-event';
import { defaultProps } from '../utils';
var Affix =
/*#__PURE__*/
function (_React$Component) {
_inheritsLoose(Affix, _React$Component);
function Affix(props) {
var _this;
_this = _React$Component.call(this, props) || this;
_this.containerRef = null;
_this.scrollListener = null;
_this.setContainerOffset = function () {
_this.setState(function () {
return {
offset: getOffset(_this.containerRef.current)
};
});
};
_this.updatePosition = function () {
var offset = _this.state.offset;
var _this$props = _this.props,
top = _this$props.top,
onChange = _this$props.onChange;
var scrollY = window.scrollY || window.pageYOffset;
var fixed = scrollY - (offset.top - top) >= 0;
if (fixed !== _this.state.fixed) {
_this.setState({
fixed: fixed
});
onChange && onChange(fixed);
}
};
_this.state = {
offset: null,
fixed: false
};
_this.containerRef = React.createRef();
return _this;
}
var _proto = Affix.prototype;
_proto.componentDidMount = function componentDidMount() {
this.setContainerOffset();
this.scrollListener = on(window, 'scroll', this.updatePosition);
bindElementResize(this.containerRef.current, this.setContainerOffset);
};
_proto.componentWillUnmount = function componentWillUnmount() {
if (this.scrollListener) {
this.scrollListener.off();
}
if (this.containerRef.current) {
unbindElementResize(this.containerRef.current);
}
};
_proto.render = function render() {
var _classNames;
var _this$props2 = this.props,
classPrefix = _this$props2.classPrefix,
children = _this$props2.children,
top = _this$props2.top,
className = _this$props2.className,
style = _this$props2.style;
var _this$state = this.state,
fixed = _this$state.fixed,
offset = _this$state.offset;
var classes = classNames(className, (_classNames = {}, _classNames[classPrefix] = fixed, _classNames));
var placeholderStyles = fixed ? {
width: offset.width,
height: offset.height
} : undefined;
var affixStyle = fixed ? _extends({
position: 'fixed',
top: top,
left: offset.left,
width: offset.width,
zIndex: 10
}, style) : style;
return React.createElement(React.Fragment, null, React.createElement("div", {
className: classes,
style: affixStyle,
ref: this.containerRef
}, children), fixed && React.createElement("div", {
"aria-hidden": "true",
style: placeholderStyles
}));
};
return Affix;
}(React.Component);
Affix.propTypes = {
top: PropTypes.number,
onChange: PropTypes.func
};
Affix.defaultProps = {
top: 0
};
export default defaultProps({
classPrefix: 'affix'
})(Affix);