chowa
Version:
UI component library based on React
112 lines (111 loc) • 3.54 kB
JavaScript
/**
* @license chowa v1.1.3
*
* Copyright (c) Chowa Techonlogies Co.,Ltd.(http://www.chowa.cn).
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/
;
Object.defineProperty(exports, "__esModule", { value: true });
const React = require("react");
const PropTypes = require("prop-types");
const classnames_1 = require("classnames");
const utils_1 = require("../utils");
const icon_1 = require("../icon");
const transition_1 = require("../transition");
class BackTop extends React.PureComponent {
constructor(props) {
super(props);
this.state = {
visible: false,
rolling: false
};
[
'onClickHandler',
'onScrollHandler'
].forEach((fn) => {
this[fn] = this[fn].bind(this);
});
}
getScrollTop() {
const { target } = this.props;
if (target() === window) {
return document.body.scrollTop || document.documentElement.scrollTop;
}
else {
return target().scrollTop;
}
}
setScrollTop(val) {
const { target } = this.props;
if (target() === window) {
document.body.scrollTop = val;
document.documentElement.scrollTop = val;
}
else {
target().scrollTop = val;
}
}
onScrollHandler() {
const scrollTop = this.getScrollTop();
const visible = scrollTop !== 0;
if (visible === this.state.visible) {
return;
}
this.setState({
visible,
rolling: false
});
}
componentDidMount() {
const { target } = this.props;
const listeners = () => {
utils_1.doms.on(target(), 'scroll', this.onScrollHandler);
this.onScrollHandler();
};
if (!target()) {
setTimeout(listeners, 200);
}
else {
listeners();
}
}
componentWillUnmount() {
utils_1.doms.off(this.props.target(), 'scroll', this.onScrollHandler);
}
onClickHandler() {
const scrollTop = this.getScrollTop();
this.setState({
rolling: true
}, () => {
utils_1.easeIn(scrollTop, (value) => {
this.setScrollTop(scrollTop - value);
});
});
}
render() {
const { children, className, style } = this.props;
const { visible, rolling } = this.state;
const componentClass = classnames_1.default({
[utils_1.preClass('back-top')]: true,
[className]: utils_1.isExist(className)
});
return (React.createElement(transition_1.default, { visible: visible },
React.createElement("button", { disabled: rolling || !visible, className: componentClass, onClick: this.onClickHandler, style: style },
utils_1.isExist(children) &&
React.createElement("span", { className: utils_1.preClass('back-top-custom') }, children),
!utils_1.isExist(children) &&
React.createElement("span", { className: utils_1.preClass('back-top-icon') },
React.createElement(icon_1.default, { type: 'rocket' })))));
}
}
BackTop.propTypes = {
className: PropTypes.string,
style: PropTypes.object,
target: PropTypes.func
};
BackTop.defaultProps = {
target: () => window
};
exports.default = BackTop;