@douyinfe/semi-ui
Version:
A modern, comprehensive, flexible design system and UI library. Connect DesignOps & DevOps. Quickly build beautiful React apps. Maintained by Douyin-fe team.
76 lines • 2.42 kB
JavaScript
import _get from "lodash/get";
import React, { PureComponent } from 'react';
import PropTypes from 'prop-types';
import { cssClasses } from '@douyinfe/semi-foundation/lib/es/tree/constants';
import ResizeObserver from '../resizeObserver';
const prefixcls = cssClasses.PREFIX;
export default class AutoSizer extends PureComponent {
constructor(props) {
super(props);
this._onResize = entries => {
// observe parent node height
const target = entries && entries[1] && entries[1].target;
if (target) {
const height = _get(target, 'offsetHeight') || 0;
const style = window.getComputedStyle(target) || {};
const paddingTop = parseInt(_get(style, 'paddingTop'), 10) || 0;
const paddingBottom = parseInt(_get(style, 'paddingBottom'), 10) || 0;
const newHeight = height - paddingTop - paddingBottom;
if (this.state.height !== newHeight) {
this.setState({
height: height - paddingTop - paddingBottom
});
}
}
};
this.state = {
height: this.props.defaultHeight || 0
};
}
componentDidMount() {
const {
height
} = this.state;
// if height is a number, pass it directly to virtual-list
if (typeof height === 'number') {
return;
}
}
render() {
const {
children,
defaultWidth,
defaultHeight
} = this.props;
const {
height
} = this.state;
// Avoid rendering children before the initial measurements have been collected.
// At best this would just be wasting cycles. Refer to https://github.com/bvaughn/react-virtualized-auto-sizer/
let bailoutOnChildren = false;
if (height === 0 || typeof height !== 'number') {
bailoutOnChildren = true;
}
return /*#__PURE__*/React.createElement(ResizeObserver, {
observeParent: true,
onResize: this._onResize
}, /*#__PURE__*/React.createElement("div", {
style: {
height: defaultHeight,
overflow: 'visible'
},
className: `${prefixcls}-auto-wrapper`
}, !bailoutOnChildren && children({
height,
width: defaultWidth
})));
}
}
AutoSizer.propTypes = {
defaultHeight: PropTypes.oneOfType([PropTypes.number, PropTypes.string]),
defaultWidth: PropTypes.oneOfType([PropTypes.number, PropTypes.string])
};
AutoSizer.defaultProps = {
defaultHeight: '100%',
defaultWidth: '100%'
};