Source: map/popup/PopupPagination.js

import { UiElement } from "../../ui/UiElement.js";
import "./PopupPagination.css";

/**
 * Pagination helper class for paging of popup metadata
 * @memberof vef.map.popup
 */
class PopupPagination extends UiElement {

    class_ = ["popup-pagination"];
    html_ = `
        <a href="#" class="btn-previous"><i class="fas fa-backward"></i> previous</a>
        <a href="#" class="btn-next">next <i class="fas fa-forward"></i></a>
        <div class="page-count-overlay">
            <div class="page-count"></div>
        </div>
    `;

    pages_ = 1;
    page_ = 1;


    /**
     * Creates an instance of PopupPagination.
     * 
     * @param {HTMLElement} target - The target element to attach the popup pagination.
     * @param {Object} options - The options for the popup pagination.
     * @param {number} [options.pageCount=10] - The total number of pages.
     * @param {number} [options.page=1] - The current page.
     */
    constructor(target, options) {

        options = Object.assign({
            pageCount: 10,
            page: 1
        }, options || {});

        super(target, {
            "change": [],
            "next": [],
            "previous": []
        });

        this.setHtml(this.html_);
        this.setClass(this.class_);

        this.setPageCount(options.pageCount);
        this.setPage(options.page);

        this.query(".btn-previous").addEventListener("click", e => {
            e.preventDefault();
            this.previous()
        });
        this.query(".btn-next").addEventListener("click", e => {
            e.preventDefault();
            this.next();
        });
    }

    /**
     * Sets the total number of pages.
     * @param {number} pages - The total number of pages.
     */
    setPageCount(pages) {
        if (pages < 1) return;
        this.pages_ = pages;
        this.setPage((this.page_ > this.pages_) ? 1 : this.page_);
    }

    /**
     * Sets the current page.
     * @param {number} page - The current page.
     */
    setPage(page) {
        // reduce by 1 to start counting at 0 for modulo
        --page;
        page = ((page % this.pages_) + this.pages_) % this.pages_;
        ++page;

        this.query(".page-count").innerText = page + " / " + this.pages_;
        if (this.page_ != page) {
            this.page_ = page;
            this.fire("change", this.page_);
        }
    }

    /**
     * Goes to the next page.
     */
    next() {
        this.setPage(this.page_ + 1);
        this.fire("next", this.page_);
    }

    /**
     * Goes to the previous page.
     */
    previous() {
        this.setPage(this.page_ - 1);
        this.fire("previous", this.page_);
    }

    /**
     * Gets the current page.
     * @returns {number} The current page.
     */
    getPage() {
        return this.page_;
    }
}

export { PopupPagination };