Skip to content

Instantly share code, notes, and snippets.

@TatuLund
Created January 17, 2023 09:20
Show Gist options
  • Select an option

  • Save TatuLund/e39ccd92bfcd8d4468a471883a1dfed3 to your computer and use it in GitHub Desktop.

Select an option

Save TatuLund/e39ccd92bfcd8d4468a471883a1dfed3 to your computer and use it in GitHub Desktop.
Java API for vaadin-grid-sorter component
package org.vaadin.addons.tatu;
import com.vaadin.flow.component.Component;
import com.vaadin.flow.component.ComponentEvent;
import com.vaadin.flow.component.ComponentEventListener;
import com.vaadin.flow.component.Tag;
import com.vaadin.flow.component.html.Span;
import com.vaadin.flow.data.provider.SortDirection;
import com.vaadin.flow.shared.Registration;
@Tag("vaadin-grid-sorter")
public class GridSorter extends Component {
SortDirection direction;
private Integer order;
public GridSorter(String header) {
Span span = new Span(header);
getElement().appendChild(span.getElement());
direction = getDirection();
getElement().addEventListener("click", e -> {
if (direction == null) {
direction = SortDirection.ASCENDING;
} else if (direction == SortDirection.ASCENDING) {
direction = SortDirection.DESCENDING;
} else {
direction = null;
}
fireEvent(new SorterChangedEvent<>(this, true));
});
}
public void setDirection(SortDirection direction) {
this.direction = direction;
if (direction == SortDirection.ASCENDING) {
getElement().setAttribute("direction", "asc");
} else if (direction == SortDirection.DESCENDING) {
getElement().setAttribute("direction", "desc");
} else {
getElement().removeAttribute("direction");
}
}
public SortDirection getDirection() {
return direction;
}
public void setOrder(Integer order) {
this.order = order;
if (order != null) {
getElement().setProperty("order", order);
} else {
getElement().removeProperty("order");
}
}
public Integer getOrder() {
return order;
}
public Registration addSorterChangedListener(
ComponentEventListener<SorterChangedEvent<GridSorter>> listener) {
return addListener(SorterChangedEvent.class,
(ComponentEventListener) listener);
}
public static class SorterChangedEvent<R extends GridSorter>
extends ComponentEvent<GridSorter> {
public SorterChangedEvent(GridSorter source, boolean fromClient) {
super(source, fromClient);
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment