112 lines
2.8 KiB
TypeScript
Raw Normal View History

2019-12-07 13:28:52 +02:00
import React from 'react';
2017-07-22 18:57:38 +03:00
import { Motion, spring } from 'react-motion';
import MeasureHeight from 'app/components/MeasureHeight';
2017-07-22 18:57:38 +03:00
2017-11-19 20:16:15 +02:00
import styles from './slide-motion.scss';
2017-07-22 18:57:38 +03:00
2019-12-10 09:47:32 +02:00
interface Props {
activeStep: number;
children: React.ReactNode;
}
2019-12-07 13:28:52 +02:00
interface State {
2019-12-10 09:47:32 +02:00
version: string;
prevChildren: React.ReactNode | undefined;
stepsHeights: Record<Props['activeStep'], number>;
2019-12-07 13:28:52 +02:00
}
2019-12-10 09:47:32 +02:00
class SlideMotion extends React.PureComponent<Props, State> {
2019-12-07 13:28:52 +02:00
state: State = {
2019-12-10 09:47:32 +02:00
prevChildren: undefined, // to track version updates
version: `${this.props.activeStep}.0`,
stepsHeights: [],
};
2017-07-22 18:57:38 +03:00
private isHeightMeasured: boolean;
2017-07-22 18:57:38 +03:00
2019-12-10 09:47:32 +02:00
static getDerivedStateFromProps(props: Props, state: State) {
let [, version] = state.version.split('.').map(Number);
if (props.children !== state.prevChildren) {
version++;
}
// mark this view as dirty to re-measure height
2019-12-10 09:47:32 +02:00
return {
prevChildren: props.children,
version: `${props.activeStep}.${version}`,
};
}
2017-07-22 18:57:38 +03:00
render() {
const { activeStep, children } = this.props;
2017-07-22 18:57:38 +03:00
const { version } = this.state;
2017-07-22 18:57:38 +03:00
const activeStepHeight = this.state.stepsHeights[activeStep] || 0;
2017-07-22 18:57:38 +03:00
// a hack to disable height animation on first render
const { isHeightMeasured } = this;
this.isHeightMeasured = isHeightMeasured || activeStepHeight > 0;
2017-07-22 18:57:38 +03:00
const motionStyle = {
transform: spring(activeStep * 100, {
stiffness: 500,
damping: 50,
precision: 0.5,
}),
height: isHeightMeasured
? spring(activeStepHeight, {
stiffness: 500,
damping: 20,
precision: 0.5,
})
: activeStepHeight,
};
2017-07-22 18:57:38 +03:00
return (
<Motion style={motionStyle}>
{(interpolatingStyle) => (
<div
style={{
overflow: 'hidden',
height: `${interpolatingStyle.height}px`,
}}
>
<div
className={styles.container}
style={{
WebkitTransform: `translateX(-${interpolatingStyle.transform}%)`,
transform: `translateX(-${interpolatingStyle.transform}%)`,
}}
>
{React.Children.map(children, (child, index) => (
<MeasureHeight
className={styles.item}
onMeasure={this.onStepMeasure(index)}
state={version}
key={index}
>
{child}
</MeasureHeight>
))}
</div>
</div>
)}
</Motion>
);
}
2017-07-22 18:57:38 +03:00
onStepMeasure = (step: number) => (height: number) => {
this.setState({
stepsHeights: {
...this.state.stepsHeights,
[step]: height,
},
});
};
2017-07-22 18:57:38 +03:00
}
2019-12-07 13:28:52 +02:00
export default SlideMotion;