From 1fc1d3a3f0b55b4d171b7767471245d21fa2500d Mon Sep 17 00:00:00 2001 From: Kushagra Gour Date: Mon, 5 Nov 2018 14:52:36 +0530 Subject: [PATCH] SplitPane: refactor to avoid unecessary renders --- src/components/SplitPane.jsx | 56 +++++++++++++++++++----------------- 1 file changed, 29 insertions(+), 27 deletions(-) diff --git a/src/components/SplitPane.jsx b/src/components/SplitPane.jsx index cbd5cb0..96149db 100644 --- a/src/components/SplitPane.jsx +++ b/src/components/SplitPane.jsx @@ -2,42 +2,40 @@ import { h, Component } from 'preact'; import Split from 'split.js'; export class SplitPane extends Component { - // shouldComponentUpdate(nextProps, nextState) { - // return ( - // nextProps.direction !== this.props.direction || - // nextProps.sizes.join('') !== this.props.sizes.join('') - // ); - // } componentDidMount() { this.updateSplit(); } - componentWillUpdate() { - if (this.splitInstance) { - this.splitInstance.destroy(); + + componentDidUpdate(prevProps) { + if (this.hasGutter() && !this.hasPropsChanged(prevProps, this.props)) { + return; } - } - componentDidUpdate() { this.updateSplit(); } + hasGutter() { + return ( + [...this.parent.children].indexOf( + this.parent.querySelector('.gutter') + ) !== -1 + ); + } + hasPropsChanged(a, b) { + return ( + a.direction !== b.direction || + (a.sizes && b.sizes && a.sizes.join('') !== b.sizes.join('')) + ); + } updateSplit() { - const options = { - direction: this.props.direction, - minSize: this.props.minSize, - gutterSize: 6, - sizes: this.props.sizes - }; - if (this.props.onDragEnd) { - options.onDragEnd = this.props.onDragEnd; - } - if (this.props.onDragStart) { - options.onDragStart = this.props.onDragStart; + const { children, ...options } = this.props; + options.gutterSize = 6; + + if (this.splitInstance && this.hasGutter()) { + this.splitInstance.destroy(); } /* eslint-disable new-cap */ - this.splitInstance = Split( - this.props.children.map(node => '#' + node.attributes.id), - options - ); + this.splitInstance = Split([...this.parent.children], options); + /* eslint-enable new-cap */ if (this.props.onSplit) { @@ -49,6 +47,10 @@ export class SplitPane extends Component { const { children, ...props } = this.props; /* eslint-enable no-unused-vars */ - return
{this.props.children}
; + return ( +
(this.parent = el)} {...props}> + {this.props.children} +
+ ); } }