Source: map/utils/LayerLegend.js

import { Window } from "../../ui/Window.js";
import { WMSLayer } from "../layer/WMSLayer/WMSLayer.js";

export { LayerLegend }

/**
 * @memberof vef.map.layer.utils
 */
class LayerLegend extends Window {

    constructor(target, layerManager) {
        super(target, {
            height: "unset",
            width: "250px",
            open: false,
            draggable: true,
            title: "LEGEND",
            responsive: true
        })

        this.activeLayer_ = null;
        this.activeLegend_ = null;
        this.layerManager_ = layerManager;
    }

    setOptions_() {
        // content height
        this.content_.style.maxHeight = "500px";
        this.content_.style.overflowY = "auto";

        this.setOptions({
            top: (window.innerHeight - this.getElement().clientHeight - 10) + "px",
            left: "480px",
            width: "280px"
        });
        this.getElement().style.visibility = "visible";
    }

    setLayer_(layer, hide) {
        if (this.activeLegend_) this.activeLegend_.remove();

        this.activeLayer_ = layer;
        this.setTitle(layer.title);

        const img = layer.getLegendGraphic();
        img.style = "max-width: 100%;";

        // set image but hide window until the image is loaded
        this.setContent(img);
        if (hide) this.getElement().style.visibility = "hidden";
        super.open();

        // update position on image loading
        if (!img.complete) {
            img.onload = () => this.setOptions_()
        } else {
            this.setOptions_();
        }

        this.activeLegend_ = img;
    }

    open(layer) {
        if (layer instanceof WMSLayer) {

            this.setLayer_(layer, true);

            if (this.layerManager_) {

                const dragover = (e) => {
                    e.dataTransfer.dropEffect = "move";
                    e.preventDefault();
                };

                const drop = (e) => {
                    const id = e.dataTransfer.getData("layer_id");
                    if (id) {
                        const l = this.layerManager_.getLayerById(id);
                        if (l && (l instanceof WMSLayer)) {
                            this.setLayer_(l, false);
                        }
                    }
                };

                this.content_.addEventListener('dragover', dragover);
                this.content_.addEventListener('drop', drop);
            }
        } else {
            this.activeLayer_ = null;
            this.activeLegend_ = null;
            this.close();
        }
    }

    getActiveLayer() {
        return this.activeLayer_;
    }

}