All Downloads are FREE. Search and download functionalities are using the official Maven repository.

org.bklab.flow.components.select.MultiSelectMenu Maven / Gradle / Ivy

There is a newer version: 22.0.1
Show newest version
package org.bklab.flow.components.select;

import com.vaadin.flow.component.checkbox.Checkbox;
import com.vaadin.flow.component.contextmenu.MenuItem;
import com.vaadin.flow.component.menubar.MenuBar;
import org.bklab.flow.factory.CheckboxFactory;

import java.util.*;
import java.util.function.Function;

public class MultiSelectMenu extends MenuBar {

    private final Map checkboxMap = new LinkedHashMap<>();
    private final MenuItem root;
    private Function labelGenerator = Objects::toString;

    public MultiSelectMenu() {
        root = addItem("请选择");
    }

    public void labelGenerator(Function captionGenerator) {
        this.labelGenerator = captionGenerator;
    }

    @SafeVarargs
    public final MultiSelectMenu items(T... items) {
        removeAll();
        checkboxMap.clear();
        for (T item : items) {
            addItem(item);
        }
        return this;
    }

    public MultiSelectMenu items(Set items) {
        removeAll();
        checkboxMap.clear();
        items.forEach(this::addItem);
        return this;
    }

    private void addItem(T item) {
        Checkbox checkbox = new CheckboxFactory().labelAsHtml(labelGenerator.apply(item))
                .ariaLabel(labelGenerator.apply(item)).get();
        root.add(checkbox);
        checkboxMap.put(item, checkbox);
    }

    public Set getSelectItems() {
        Set set = new LinkedHashSet<>();
        checkboxMap.forEach((k, v) -> Optional.of(v)
                .filter(Checkbox::getValue).ifPresent(a -> set.add(k)));
        return set;
    }
}




© 2015 - 2025 Weber Informatics LLC | Privacy Policy