Pour tout problème contactez-nous par mail : support@froggit.fr | La FAQ :grey_question: | Rejoignez-nous sur le Chat :speech_balloon:

Skip to content
Snippets Groups Projects
image-carousel.js 1.94 KiB
Newer Older
peter_rabbit's avatar
peter_rabbit committed
"use strict";

class ImageCarousel {
    constructor(props) {
        this.props = props;
        this.id = this.props.images.join("").replace(/\s\./g);
peter_rabbit's avatar
peter_rabbit committed
        this.state = {
            showImageIndex: 0,
        };
        this.RUN_INTERVAL = 5000;
peter_rabbit's avatar
peter_rabbit committed
        this.props.images.length > 1 && this.run();
peter_rabbit's avatar
peter_rabbit committed
    }

    run() {
        this.runningInterval = setInterval(() => {
            let { showImageIndex } = this.state;
            const { images } = this.props;
            this.state.showImageIndex = showImageIndex < images.length - 1 ? ++showImageIndex : 0;
            this.refreshImage();
        }, this.RUN_INTERVAL);
    }

    setImageIndex(i) {
        clearInterval(this.runningInterval);
        this.state.showImageIndex = i;
        this.refreshImage();
    }

    refreshImage() {
Pierre Jarriges's avatar
Pierre Jarriges committed
        obj2htm.subRender(this.render(), document.getElementById(this.id), {
peter_rabbit's avatar
peter_rabbit committed
            mode: "replace",
        });
    }

    render() {
        const { showImageIndex } = this.state;
        const { images } = this.props;
        return {
            tag: "div",
            id: this.id,
            class: "image-carousel",
            contents: [
peter_rabbit's avatar
peter_rabbit committed
                {
                    tag: "img",
                    property: "image",
peter_rabbit's avatar
peter_rabbit committed
                    alt: `image carousel ${images[showImageIndex].replace(/\.[A-Za-z]+/, "")}`,
                    src: images[showImageIndex],
                },
peter_rabbit's avatar
peter_rabbit committed
                images.length > 1 && {
peter_rabbit's avatar
peter_rabbit committed
                    tag: "div",
                    class: "carousel-bullets",
                    contents: images.map((_, i) => {
                        const active = showImageIndex === i;
                        return {
                            tag: "span",
                            class: `bullet ${active ? "active" : ""}`,
                            onclick: this.setImageIndex.bind(this, i),
                        };
                    }),
                },
            ],
        };
    }
}

module.exports = ImageCarousel;