Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- import { Component } from 'preact';
- import styles from './style';
- import classNames from 'classnames';
- import debounce from '../../utils/debounce';
- import root from 'window-or-global';
- export default class slider extends Component {
- state = {
- activeIndex: 0,
- translate: 0,
- touchStartX: undefined,
- touchMoveX: undefined,
- moveX: undefined
- }
- SWIPE_WIDTH = 50;
- SCREEN_LG = 1100;
- SLIDE_WIDTH = 100;
- slideTo(index) {
- this.setState({ activeIndex: index, translate: `${-this.SLIDE_WIDTH * index}` });
- }
- onTouchStart = (e) => {
- this.setState({ touchStartX: e.touches[0].pageX });
- }
- onTouchMove = (e) => {
- const { activeIndex, touchStartX } = this.state;
- let touchMoveX = e.touches[0].pageX;
- let moveX = touchStartX - touchMoveX;
- if (Math.abs(moveX) > this.SWIPE_WIDTH) {
- this.setState({
- touchMoveX: e.touches[0].pageX,
- translate: -((activeIndex * this.SLIDE_WIDTH) + (touchStartX - touchMoveX)),
- moveX
- });
- }
- }
- onTouchEnd = (e) => {
- const { activeIndex, translate, moveX } = this.state;
- const currentTranslate = activeIndex * -this.SLIDE_WIDTH;
- let index = activeIndex;
- if (Math.abs(moveX) > this.SWIPE_WIDTH) {
- if (translate < currentTranslate && activeIndex < (this.props.children.length - 1)) {
- index++;
- }
- else if (translate > currentTranslate && activeIndex > 0) {
- index--;
- }
- this.slideTo(index);
- }
- }
- wrapChildren(child) {
- return <li class={styles.slider__item}>{child}</li>;
- }
- generateSliderDods() {
- const slides = this.props.children;
- return slides.map((item, index) => <div class={this.generateDotClasses(index)} onClick={() => this.slideTo(index)} />);
- }
- generateDotClasses(index) {
- return classNames(styles.slider__dot, { [styles['slider__dot--active']]: index === this.state.activeIndex });
- }
- handleResize = debounce(() => {
- if (root.innerWidth > this.SCREEN_LG) {
- this.setState({ activeIndex: 0, translate: 0 });
- }
- }, 200);
- componentDidMount() {
- root.addEventListener('resize', this.handleResize);
- }
- render() {
- const listTransition = `transform: translate3d(${this.state.translate}%, 0px, 0px); transition-duration: 200ms`;
- return (
- <div class={styles.slider}>
- <div class={styles.slider__content}>
- <div
- onTouchStart={this.onTouchStart}
- onTouchMove={this.onTouchMove}
- onTouchEnd={this.onTouchEnd}
- >
- <ul
- class={styles.slider__list}
- style={listTransition}
- >
- {this.props.children.map(child => this.wrapChildren(child))}
- </ul>
- </div>
- </div>
- <ul class={styles.slider__dots}>{this.generateSliderDods()}</ul>
- </div>
- );
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement