| 32 | import java.util.function.Function; |
| 33 | |
| 34 | public class Paginator<E> implements Helper { |
| 35 | |
| 36 | public final List<E> entries; |
| 37 | public int pageSize = 8; |
| 38 | public int page = 1; |
| 39 | |
| 40 | public Paginator(List<E> entries) { |
| 41 | this.entries = entries; |
| 42 | } |
| 43 | |
| 44 | public Paginator(E... entries) { |
| 45 | this.entries = Arrays.asList(entries); |
| 46 | } |
| 47 | |
| 48 | public Paginator<E> setPageSize(int pageSize) { |
| 49 | this.pageSize = pageSize; |
| 50 | return this; |
| 51 | } |
| 52 | |
| 53 | public int getMaxPage() { |
| 54 | return (entries.size() - 1) / pageSize + 1; |
| 55 | } |
| 56 | |
| 57 | public boolean validPage(int page) { |
| 58 | return page > 0 && page <= getMaxPage(); |
| 59 | } |
| 60 | |
| 61 | public Paginator<E> skipPages(int pages) { |
| 62 | page += pages; |
| 63 | return this; |
| 64 | } |
| 65 | |
| 66 | public void display(Function<E, Component> transform, String commandPrefix) { |
| 67 | int offset = (page - 1) * pageSize; |
| 68 | for (int i = offset; i < offset + pageSize; i++) { |
| 69 | if (i < entries.size()) { |
| 70 | logDirect(transform.apply(entries.get(i))); |
| 71 | } else { |
| 72 | logDirect("--", ChatFormatting.DARK_GRAY); |
| 73 | } |
| 74 | } |
| 75 | boolean hasPrevPage = commandPrefix != null && validPage(page - 1); |
| 76 | boolean hasNextPage = commandPrefix != null && validPage(page + 1); |
| 77 | MutableComponent prevPageComponent = Component.literal("<<"); |
| 78 | if (hasPrevPage) { |
| 79 | prevPageComponent.setStyle(prevPageComponent.getStyle() |
| 80 | .withClickEvent(new ClickEvent.RunCommand( |
| 81 | String.format("%s %d", commandPrefix, page - 1) |
| 82 | )) |
| 83 | .withHoverEvent(new HoverEvent.ShowText( |
| 84 | Component.literal("Click to view previous page") |
| 85 | ))); |
| 86 | } else { |
| 87 | prevPageComponent.setStyle(prevPageComponent.getStyle().withColor(ChatFormatting.DARK_GRAY)); |
| 88 | } |
| 89 | MutableComponent nextPageComponent = Component.literal(">>"); |
| 90 | if (hasNextPage) { |
| 91 | nextPageComponent.setStyle(nextPageComponent.getStyle() |
nothing calls this directly
no outgoing calls
no test coverage detected