@limetech/lime-elements
Version:
71 lines (70 loc) • 2.19 kB
JavaScript
import React from 'react';
const MAX_COLUMNS = 5;
const MAX_COLUMN_WIDTH = 15;
const PX_PER_REM = 16;
const COLUMN_COUNT = '--number-of-columns';
export class GridLayout extends React.Component {
constructor(props) {
super(props);
this.props = props;
this.handleResize = this.handleResize.bind(this);
this.state = {
maxColumns: MAX_COLUMNS,
};
this.elementRef = React.createRef();
}
componentDidMount() {
this.observer = new ResizeObserver(this.handleResize);
this.observer.observe(this.elementRef.current);
window.addEventListener('resize', this.handleResize, {
capture: true,
passive: true,
});
}
componentWillUnmount() {
this.observer.unobserve(this.elementRef.current);
window.removeEventListener('resize', this.handleResize, {
capture: true,
});
}
handleResize() {
requestAnimationFrame(() => {
const element = this.elementRef.current;
if (!element) {
return;
}
const width = element.getBoundingClientRect().width;
const maxColumns = Math.min(MAX_COLUMNS, Math.max(1, Math.floor(width / (MAX_COLUMN_WIDTH * PX_PER_REM))));
const columns = this.getColumnCount(maxColumns);
if (element.style.getPropertyValue(COLUMN_COUNT) !== `${columns}`) {
element.style.setProperty(COLUMN_COUNT, `${columns}`);
}
if (maxColumns !== this.state.maxColumns) {
this.setState({
maxColumns: maxColumns,
});
}
});
}
render() {
const classes = ['limel-form-layout--grid'];
const columns = this.getColumnCount(this.state.maxColumns);
classes.push(`layout-${columns}-columns`);
if (this.hasAutoFlowDense()) {
classes.push('auto-reorder-to-avoid-empty-cells');
}
return React.createElement('div', {
className: classes.join(' '),
ref: this.elementRef,
}, this.props.children);
}
getColumnCount(maxColumns) {
const layout = this.props.options;
return Math.min(layout.columns || MAX_COLUMNS, maxColumns);
}
hasAutoFlowDense() {
const layout = this.props.options;
return layout.dense !== false;
}
}
//# sourceMappingURL=grid-layout.js.map