diff --git a/.github/release-notes.md b/.github/release-notes.md index d9307f2..78f9f61 100644 --- a/.github/release-notes.md +++ b/.github/release-notes.md @@ -1,19 +1,21 @@ --- -version: 1.0.0 +version: 2.0.0 --- -# Commandant 1.0.0 - Stable commands +# Commandant 2.0.0 - Help in every reader's language -Commandant 1.0.0 is the first stable release and builds on Keystone 1.0.0. Plugins parse their commands themselves and hand them to `Commandant.process`, which applies definitions, help and pagination; plugins written against 0.0.1 need the upgrade steps below. +Commandant 2.0.0 builds help and pagination from translatable components, so one help page is shown in each reader's language by the translator the plugin registers with Adventure. Plugins that build help need the upgrade steps below. ## Highlights -* Commands are parsed by your own parser and handed to `Commandant.process(command, manager)`, which applies a definition's overrides through a `DefinitionAdapter` before registering them. -* Definitions can declare root aliases, and usage tokens that do not match the command's arguments fail fast. -* Help and pagination are configured through fluent builders; help can list a command once per definition. -* Exception messages format their placeholder values through `ExceptionFormatting`, with built-in formatters for Cloud permissions. -* `CommandantSyntaxFormatter` gives Cloud's syntax messages the argument format of Commandant's help. +* `HelpBuilder.build` returns a `Component` made of translatable keys under a prefix the plugin chooses, with named arguments made by the plugin's `ArgumentFactory`, such as semantica's `TextArgument::of`. +* `HelpBuilder.Text` and `PaginationBuilder.Text` list every key with the named arguments it is given, so a plugin writes its translations in its own wording. +* `TranslatableDescription.of(key)` gives a command a description that the help shows in the reader's language. +* The page arrows run the page command themselves, so translations need no click tags. ## Upgrading -* `Command`, `CommandDefinition` and `CommandRegistrar` are removed; parse commands yourself and register them through `Commandant.process`. +* Replace `HelpMessages` and `PaginationMessages` with translations of each `HelpBuilder.Text` under the help's prefix, for example `arbor.help.title`, and of each `PaginationBuilder.Text` under `.pagination`. Send the `Component` that `HelpBuilder.build` returns instead of deserializing a string. +* Build help with `Help.builder(prefix, arguments).host(name).pageCommand(page -> "/ help " + page)`. `customArgumentNames` is now `argumentNames`, and `itemsPerPage` defaults to 7. Placeholders move from `{previousPage}`/`{nextPage}` to `{page}`, and from `{argument}` to `{name}`. +* A pagination of your own is built with `Pagination.builder(prefix, arguments)`, whose `showIfOnePage`, `showPreviousOnFirst` and `showNextOnLast` replace the flags of `PaginationMessages`. `PaginationBuilder.build` returns the page line, or nothing when it is hidden. +* `CommandantSyntaxFormatter` takes the required and optional argument templates as two strings instead of `HelpMessages.Format`. diff --git a/commandant-api/build.gradle.kts b/commandant-api/build.gradle.kts index 52fbbc3..f07abc7 100644 --- a/commandant-api/build.gradle.kts +++ b/commandant-api/build.gradle.kts @@ -4,6 +4,12 @@ plugins { dependencies { api(libs.keystone) + + testImplementation(libs.adventure.api) + testImplementation(libs.cloud.core) + testImplementation(libs.junit.jupiter) + + testRuntimeOnly(libs.junit.platform) } publishing { diff --git a/commandant-api/src/main/java/me/whereareiam/commandant/builder/ArgumentFactory.java b/commandant-api/src/main/java/me/whereareiam/commandant/builder/ArgumentFactory.java new file mode 100644 index 0000000..a485024 --- /dev/null +++ b/commandant-api/src/main/java/me/whereareiam/commandant/builder/ArgumentFactory.java @@ -0,0 +1,67 @@ +package me.whereareiam.commandant.builder; + +import net.kyori.adventure.text.ComponentLike; +import org.jetbrains.annotations.NotNull; + +/** + * Makes a named argument of a translatable component, so a translation refers to it by name, such as + * {@code {host}}. The plugin's translator decides how a named argument is represented; with semantica it is + * {@code TextArgument::of}. + * + *

The help and the pagination pass a value as a {@link ComponentLike}, a {@link String} or an {@link Integer}, + * so a translation can format numbers, for example in a plural.

+ * + *
{@code
+ * HelpBuilder help = Help.builder("arbor.help", TextArgument::of)
+ *         .host("Arbor")
+ *         .build();
+ * }
+ */ +@FunctionalInterface +public interface ArgumentFactory { + /** + * Makes a named argument. + * + * @param name the argument's name, as a translation refers to it + * @param value the argument's value: a {@link ComponentLike}, a {@link String} or an {@link Integer} + * @return the argument, to pass to a translatable component + */ + @NotNull + ComponentLike create(@NotNull String name, @NotNull Object value); + + /** + * Makes a named argument of a number. + * + * @param argument the argument + * @param value its value + * @return the argument, to pass to a translatable component + */ + @NotNull + default ComponentLike create(@NotNull TranslationArgument argument, int value) { + return create(argument.getId(), value); + } + + /** + * Makes a named argument of a text. + * + * @param argument the argument + * @param value its value + * @return the argument, to pass to a translatable component + */ + @NotNull + default ComponentLike create(@NotNull TranslationArgument argument, @NotNull String value) { + return create(argument.getId(), value); + } + + /** + * Makes a named argument of a component. + * + * @param argument the argument + * @param value its value + * @return the argument, to pass to a translatable component + */ + @NotNull + default ComponentLike create(@NotNull TranslationArgument argument, @NotNull ComponentLike value) { + return create(argument.getId(), value); + } +} diff --git a/commandant-api/src/main/java/me/whereareiam/commandant/builder/HelpBuilder.java b/commandant-api/src/main/java/me/whereareiam/commandant/builder/HelpBuilder.java index ea605aa..77fcb12 100644 --- a/commandant-api/src/main/java/me/whereareiam/commandant/builder/HelpBuilder.java +++ b/commandant-api/src/main/java/me/whereareiam/commandant/builder/HelpBuilder.java @@ -1,29 +1,118 @@ package me.whereareiam.commandant.builder; +import lombok.Getter; +import lombok.RequiredArgsConstructor; +import net.kyori.adventure.text.Component; import org.incendo.cloud.Command; import org.jetbrains.annotations.NotNull; import java.util.Collection; +import java.util.Set; /** - * Builder interface for creating help command outputs. - * Formats a list of commands with their arguments and descriptions, - * optionally including pagination. - *

- * This builder is generic and works with any sender type. + * Builds a page of help: a heading, a line for each command with its arguments and description, and a page + * line. The page is made of translatable components with named arguments, so the plugin's translator renders it + * in each reader's language. Each component's key is the help's prefix, a dot and the key of a {@link Text}, such + * as {@code arbor.help.title}; the page line's keys are those of {@link PaginationBuilder.Text} under + * {@code .}{@value #PAGINATION}. * - * @param The sender type (e.g., Actor, DummyPlayer, CommandSender) + *

{@code
+ * Collection> visible = manager.commands().stream()
+ *         .filter(command -> manager.testPermission(sender, command.commandPermission()).allowed())
+ *         .toList();
+ * sender.sendMessage(help.build(visible, page));
+ * }
+ * + * @param the sender type */ -@SuppressWarnings("unused") public interface HelpBuilder { /** - * Builds a help message for the given commands. + * The key under the help's prefix that holds the page line's texts, those of {@link PaginationBuilder.Text}. + */ + String PAGINATION = "pagination"; + + /** + * Builds one page of help for the given commands. A page past the last lists no command and shows the + * {@link Text#EMPTY} line. * - * @param commands Collection of commands to display - * @param page Current page number (1-indexed) - * @return Formatted help message string + * @param commands the commands to list, usually those the reader may use + * @param page the page, from {@code 1} + * @return the page, its lines joined by line breaks */ @NotNull - String build(@NotNull Collection> commands, int page); -} + Component build(@NotNull Collection> commands, int page); + + /** + * A text of the help, with the named arguments it is given. A plugin writes a translation for each under the + * help's prefix. + */ + @Getter + enum Text implements TranslationKey { + /** + * The heading above the commands. + */ + TITLE("title", Argument.HOST), + + /** + * One command's line. Its {@link Argument#ARGUMENTS} is empty or starts with a space. + */ + COMMAND("command", Argument.COMMAND, Argument.ARGUMENTS, Argument.DESCRIPTION), + + /** + * A required argument inside a command's {@link Argument#ARGUMENTS}. + */ + ARGUMENT("argument", Argument.NAME), + + /** + * An optional argument inside a command's {@link Argument#ARGUMENTS}. + */ + OPTIONAL_ARGUMENT("optionalArgument", Argument.NAME), + /** + * The line shown instead of commands when a page has none. + */ + EMPTY("empty"); + + private final String key; + private final Set arguments; + + Text(@NotNull String key, @NotNull Argument... arguments) { + this.key = key; + this.arguments = Set.of(arguments); + } + } + + /** + * A named argument of a {@link Text}. + */ + @Getter + @RequiredArgsConstructor + enum Argument implements TranslationArgument { + /** + * The name of the plugin whose help it is. + */ + HOST("host"), + + /** + * The root command's name. + */ + COMMAND("command"), + + /** + * The command's arguments, each after a space. + */ + ARGUMENTS("arguments"), + + /** + * The command's description. + */ + DESCRIPTION("description"), + + /** + * An argument's name. + */ + NAME("name"); + + private final String id; + } +} diff --git a/commandant-api/src/main/java/me/whereareiam/commandant/builder/PaginationBuilder.java b/commandant-api/src/main/java/me/whereareiam/commandant/builder/PaginationBuilder.java index 683f32a..ed8def6 100644 --- a/commandant-api/src/main/java/me/whereareiam/commandant/builder/PaginationBuilder.java +++ b/commandant-api/src/main/java/me/whereareiam/commandant/builder/PaginationBuilder.java @@ -1,22 +1,94 @@ package me.whereareiam.commandant.builder; +import lombok.Getter; +import lombok.RequiredArgsConstructor; +import net.kyori.adventure.text.Component; import org.jetbrains.annotations.NotNull; +import java.util.Optional; +import java.util.Set; + /** - * Builder interface for creating pagination controls in command outputs. - * Formats navigation elements (previous/next buttons) and page indicators. + * Builds the page line of a paginated list: the current and last page, and arrows to the pages around it. The + * line is a translatable component with named arguments, whose keys are the pagination's prefix, a dot and the key + * of a {@link Text}, such as {@code arbor.help.pagination.line}. */ public interface PaginationBuilder { /** - * Builds pagination by replacing the placeholder in the message. + * Builds the page line for a list. * - * @param message The message containing placeholder - * @param totalItems Total number of items to paginate - * @param currentPage Current page number (1-indexed) - * @param itemsPerPage Number of items per page - * @return The message with the pagination placeholder replaced by formatted controls + * @param totalItems the number of items in the whole list + * @param currentPage the page shown, from {@code 1} + * @param itemsPerPage the number of items on one page + * @return the page line, or empty when the list fits on one page and the pagination hides it then */ @NotNull - String build(@NotNull String message, int totalItems, int currentPage, int itemsPerPage); -} + Optional build(int totalItems, int currentPage, int itemsPerPage); + + /** + * A text of the page line, with the named arguments it is given. A plugin writes a translation for each under + * the pagination's prefix. + */ + @Getter + enum Text implements TranslationKey { + /** + * The page line. Its {@link Argument#PREVIOUS} and {@link Argument#NEXT} are the arrows, or empty where + * there is no page to go to. + */ + LINE("line", Argument.CURRENT, Argument.MAX, Argument.PREVIOUS, Argument.NEXT), + + /** + * The arrow to the previous page. It needs no click tag: when the pagination has a page command, the whole + * arrow runs it. + */ + PREVIOUS("previous", Argument.PAGE), + + /** + * The arrow to the next page. It needs no click tag: when the pagination has a page command, the whole + * arrow runs it. + */ + NEXT("next", Argument.PAGE); + + private final String key; + private final Set arguments; + + Text(@NotNull String key, @NotNull Argument... arguments) { + this.key = key; + this.arguments = Set.of(arguments); + } + } + /** + * A named argument of a {@link Text}. + */ + @Getter + @RequiredArgsConstructor + enum Argument implements TranslationArgument { + /** + * The page shown, a number. + */ + CURRENT("current"), + + /** + * The last page, a number. + */ + MAX("max"), + + /** + * The arrow to the previous page, or empty. + */ + PREVIOUS("previous"), + + /** + * The arrow to the next page, or empty. + */ + NEXT("next"), + + /** + * The page an arrow opens, a number. + */ + PAGE("page"); + + private final String id; + } +} diff --git a/commandant-api/src/main/java/me/whereareiam/commandant/builder/TranslationArgument.java b/commandant-api/src/main/java/me/whereareiam/commandant/builder/TranslationArgument.java new file mode 100644 index 0000000..423128c --- /dev/null +++ b/commandant-api/src/main/java/me/whereareiam/commandant/builder/TranslationArgument.java @@ -0,0 +1,16 @@ +package me.whereareiam.commandant.builder; + +import org.jetbrains.annotations.NotNull; + +/** + * A named argument of a {@link TranslationKey}. + */ +public interface TranslationArgument { + /** + * Returns the name a translation refers to the argument by. + * + * @return the name, such as {@code host} in {@code {host}} + */ + @NotNull + String getId(); +} diff --git a/commandant-api/src/main/java/me/whereareiam/commandant/builder/TranslationKey.java b/commandant-api/src/main/java/me/whereareiam/commandant/builder/TranslationKey.java new file mode 100644 index 0000000..aea5d29 --- /dev/null +++ b/commandant-api/src/main/java/me/whereareiam/commandant/builder/TranslationKey.java @@ -0,0 +1,38 @@ +package me.whereareiam.commandant.builder; + +import org.jetbrains.annotations.NotNull; + +import java.util.Set; + +/** + * A text a builder sends as a translatable component, with the named arguments it is given. A plugin writes a + * translation for each under the builder's prefix. + */ +public interface TranslationKey { + /** + * Returns the key under the builder's prefix. + * + * @return the key, such as {@code title} + */ + @NotNull + String getKey(); + + /** + * Returns the named arguments the text is given. + * + * @return the arguments + */ + @NotNull + Set getArguments(); + + /** + * Returns the full key of this text under a prefix. + * + * @param prefix the builder's prefix, such as {@code arbor.help} + * @return the key, such as {@code arbor.help.title} + */ + @NotNull + default String under(@NotNull String prefix) { + return prefix + '.' + getKey(); + } +} diff --git a/commandant-api/src/main/java/me/whereareiam/commandant/model/TranslatableDescription.java b/commandant-api/src/main/java/me/whereareiam/commandant/model/TranslatableDescription.java new file mode 100644 index 0000000..8befd1b --- /dev/null +++ b/commandant-api/src/main/java/me/whereareiam/commandant/model/TranslatableDescription.java @@ -0,0 +1,80 @@ +package me.whereareiam.commandant.model; + +import lombok.EqualsAndHashCode; +import lombok.Getter; +import lombok.ToString; +import net.kyori.adventure.text.Component; +import net.kyori.adventure.text.ComponentLike; +import org.incendo.cloud.description.Description; +import org.jetbrains.annotations.NotNull; + +import java.util.Objects; + +/** + * A command description that is a translation key, so the help shows it in each reader's language. The help + * renders it as a translatable component of its key; Cloud's text consumers, such as a platform's command + * tree, see the key. + * + *
{@code
+ * manager.commandBuilder("arbor")
+ *         .literal("status")
+ *         .commandDescription(TranslatableDescription.of("arbor.command.status.description"))
+ *         .handler(...);
+ * }
+ * + *

The help renders any {@link Description} that is also a {@link ComponentLike} as that component; this + * class is the one Commandant provides.

+ */ +@Getter +@ToString +@EqualsAndHashCode +public final class TranslatableDescription implements Description, ComponentLike { + private final String key; + + private TranslatableDescription(@NotNull String key) { + this.key = Objects.requireNonNull(key, "key"); + } + + /** + * Creates a description of a translation key. + * + * @param key the key, such as {@code arbor.command.status.description} + * @return the description + */ + @NotNull + public static TranslatableDescription of(@NotNull String key) { + return new TranslatableDescription(key); + } + + /** + * Returns the key, for consumers that only read text. + * + * @return the key + */ + @Override + @NotNull + public String textDescription() { + return key; + } + + /** + * A translatable description is never empty. + * + * @return {@code false} + */ + @Override + public boolean isEmpty() { + return false; + } + + /** + * Returns the translatable component of the key, which a translator renders for its reader. + * + * @return the component + */ + @Override + @NotNull + public Component asComponent() { + return Component.translatable(key); + } +} diff --git a/commandant-api/src/main/java/me/whereareiam/commandant/model/message/HelpMessages.java b/commandant-api/src/main/java/me/whereareiam/commandant/model/message/HelpMessages.java deleted file mode 100644 index b26db5f..0000000 --- a/commandant-api/src/main/java/me/whereareiam/commandant/model/message/HelpMessages.java +++ /dev/null @@ -1,86 +0,0 @@ -package me.whereareiam.commandant.model.message; - -import lombok.Getter; -import lombok.Setter; -import lombok.ToString; - -import java.util.List; - -/** - * Configuration model for help command message and formatting. - * Used by HelpBuilder to format help command outputs. - */ -@Getter -@Setter -@ToString -public class HelpMessages { - /** - * Overall format template for help display. - * Each string represents a line in the help output. - * Placeholders (format defined by caller): - * - commands: List of available commands - * - pagination: Pagination controls - *

- * Example: - * - "Commands" - * - "" - * - "" - * - "" - * - "" - */ - private List format; - - /** - * Format template for individual command entries. - * Placeholders (format defined by caller): - * - command: Command name - * - arguments: Formatted command arguments - * - description: Command description - *

- * Example: "/ - " - */ - private String commandFormat; - - /** - * Message shown when no commands are available. - *

- * Example: "No commands available" - */ - private String noCommands; - - /** - * Format configuration for command arguments. - */ - private Format argumentFormat; - - /** - * Number of commands to display per help page. - *

- * Default: 7 - */ - private int commandsPerPage = 7; - - /** - * Configuration for formatting command arguments. - */ - @Getter - @Setter - @ToString - public static class Format { - /** - * Format template for required arguments. - * Placeholder: argument - the argument name - *

- * Example: "" - */ - private String argument; - - /** - * Format template for optional arguments. - * Placeholder: argument - the argument name - *

- * Example: "[]" - */ - private String optionalArgument; - } -} diff --git a/commandant-api/src/main/java/me/whereareiam/commandant/model/message/PaginationMessages.java b/commandant-api/src/main/java/me/whereareiam/commandant/model/message/PaginationMessages.java deleted file mode 100644 index b04babf..0000000 --- a/commandant-api/src/main/java/me/whereareiam/commandant/model/message/PaginationMessages.java +++ /dev/null @@ -1,57 +0,0 @@ -package me.whereareiam.commandant.model.message; - -import lombok.Getter; -import lombok.Setter; -import lombok.ToString; - -/** - * Configuration model for pagination-related message and behavior. - * Used by PaginationBuilder to format paginated command outputs. - */ -@Getter -@Setter -@ToString -public class PaginationMessages { - /** - * Whether to show pagination when there's only one page. - */ - private boolean showPaginationIfOnePage; - - /** - * Format template for pagination display. - * Placeholders (format defined by caller): - * - previous: Previous page navigation - * - next: Next page navigation - * - current: Current page number - * - max: Total number of pages - *

- * Example: " Page / " - */ - private String format; - - /** - * Whether to show previous page button even on the first page. - */ - private boolean showPreviousEvenIfFirst; - - /** - * Format template for previous page button. - * Placeholder: previousPage - the previous page number - *

- * Example: "'>'>←" - */ - private String previousTagFormat; - - /** - * Whether to show next page button even on the last page. - */ - private boolean showNextEvenIfLast; - - /** - * Format template for next page button. - * Placeholder: nextPage - the next page number - *

- * Example: "'>'>→" - */ - private String nextTagFormat; -} diff --git a/commandant-api/src/test/java/me/whereareiam/commandant/model/TranslatableDescriptionTest.java b/commandant-api/src/test/java/me/whereareiam/commandant/model/TranslatableDescriptionTest.java new file mode 100644 index 0000000..351c5d2 --- /dev/null +++ b/commandant-api/src/test/java/me/whereareiam/commandant/model/TranslatableDescriptionTest.java @@ -0,0 +1,18 @@ +package me.whereareiam.commandant.model; + +import net.kyori.adventure.text.Component; +import org.junit.jupiter.api.Test; + +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertFalse; + +class TranslatableDescriptionTest { + @Test + void rendersAsTheTranslatableComponentOfItsKey() { + TranslatableDescription description = TranslatableDescription.of("arbor.command.status.description"); + + assertEquals(Component.translatable("arbor.command.status.description"), description.asComponent()); + assertEquals("arbor.command.status.description", description.textDescription()); + assertFalse(description.isEmpty()); + } +} diff --git a/commandant-common/build.gradle.kts b/commandant-common/build.gradle.kts index 090e762..d91f234 100644 --- a/commandant-common/build.gradle.kts +++ b/commandant-common/build.gradle.kts @@ -8,8 +8,10 @@ dependencies { compileOnly(libs.cloud.cooldowns) compileOnly(libs.cloud.annotations) - testImplementation(libs.junit.jupiter) + testImplementation(libs.adventure.api) testImplementation(libs.cloud.core) + testImplementation(libs.junit.jupiter) + testRuntimeOnly(libs.junit.platform) } diff --git a/commandant-common/src/main/java/me/whereareiam/commandant/common/DefaultHelpBuilder.java b/commandant-common/src/main/java/me/whereareiam/commandant/common/DefaultHelpBuilder.java index 5cea8eb..ed666bb 100644 --- a/commandant-common/src/main/java/me/whereareiam/commandant/common/DefaultHelpBuilder.java +++ b/commandant-common/src/main/java/me/whereareiam/commandant/common/DefaultHelpBuilder.java @@ -1,246 +1,175 @@ package me.whereareiam.commandant.common; import me.whereareiam.commandant.CommandantKeys; +import me.whereareiam.commandant.builder.ArgumentFactory; import me.whereareiam.commandant.builder.HelpBuilder; import me.whereareiam.commandant.builder.PaginationBuilder; -import me.whereareiam.commandant.model.message.HelpMessages; -import me.whereareiam.keystone.model.SerializerOptions; +import net.kyori.adventure.text.Component; +import net.kyori.adventure.text.ComponentLike; +import net.kyori.adventure.text.JoinConfiguration; import org.incendo.cloud.Command; import org.incendo.cloud.component.CommandComponent; +import org.incendo.cloud.description.Description; import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; -import java.util.*; +import java.util.ArrayList; +import java.util.Collection; +import java.util.Comparator; +import java.util.HashSet; +import java.util.List; +import java.util.Map; +import java.util.Optional; +import java.util.Set; import java.util.stream.Collectors; /** - * Default implementation of HelpBuilder. - * Formats a list of commands with their arguments and descriptions, - * optionally including pagination. - *

- * This builder is generic and works with any sender type. - *

- * Usage example: - *

{@code
- * HelpMessages config = ...; // from your config
- * Map customArgNames = Map.of("page", "page number");
- * PaginationBuilder paginationBuilder = ...; // optional
+ * The standard help: the {@link Text}s under a prefix, as translatable components with named arguments. A
+ * command's description is shown as a component when its {@link Description} is a {@link ComponentLike}, such as
+ * a translatable description, and as text otherwise.
  *
- * HelpBuilder builder = new DefaultHelpBuilder<>(config, customArgNames, paginationBuilder, 10);
- *
- * Collection> commands = commandManager.commands();
- * String helpMessage = builder.build(commands, 1);
- * }
- * - * @param The sender type (e.g., Actor, DummyPlayer, CommandSender) + * @param the sender type */ public class DefaultHelpBuilder implements HelpBuilder { - private final HelpMessages messages; - private final Map customArgumentNames; - private final PaginationBuilder paginationBuilder; + private static final Component SPACE = Component.space(); + + private final String prefix; + private final ArgumentFactory arguments; + private final String host; + private final Map argumentNames; + private final PaginationBuilder pagination; private final int itemsPerPage; private final boolean sortAlphabetically; private final boolean dedupeByDefinitionId; - private final SerializerOptions.PlaceholderFormat placeholderFormat; /** - * Creates a new DefaultHelpBuilder with the given configuration. + * Creates a help. * - * @param messages The help message configuration - * @param customArgumentNames Map of argument names to custom display names (can be null or empty) - * @param paginationBuilder The pagination builder (can be null to disable pagination) - * @param itemsPerPage Number of commands to display per page - * @param sortAlphabetically Whether to sort commands alphabetically by name + * @param prefix the keys' prefix, such as {@code arbor.help} + * @param arguments makes the named arguments of the texts + * @param host the name of the plugin whose help it is, the heading's {@link Argument#HOST} + * @param argumentNames names to show instead of arguments' own names + * @param pagination builds the page line, or {@code null} for none + * @param itemsPerPage the number of commands on one page + * @param sortAlphabetically whether commands are listed by their arguments in alphabetical order + * @param dedupeByDefinitionId whether commands of one definition are listed once */ public DefaultHelpBuilder( - @NotNull HelpMessages messages, - @Nullable Map customArgumentNames, - @Nullable PaginationBuilder paginationBuilder, - int itemsPerPage, - boolean sortAlphabetically - ) { - this(messages, customArgumentNames, paginationBuilder, itemsPerPage, sortAlphabetically, false, - SerializerOptions.PlaceholderFormat.CURLY_BRACES); - } - - public DefaultHelpBuilder( - @NotNull HelpMessages messages, - @Nullable Map customArgumentNames, - @Nullable PaginationBuilder paginationBuilder, + @NotNull String prefix, + @NotNull ArgumentFactory arguments, + @NotNull String host, + @NotNull Map argumentNames, + @Nullable PaginationBuilder pagination, int itemsPerPage, boolean sortAlphabetically, - boolean dedupeByDefinitionId, - @NotNull SerializerOptions.PlaceholderFormat placeholderFormat + boolean dedupeByDefinitionId ) { - this.messages = messages; - this.customArgumentNames = customArgumentNames != null ? customArgumentNames : Map.of(); - this.paginationBuilder = paginationBuilder; + if (itemsPerPage < 1) throw new IllegalArgumentException("itemsPerPage must be at least 1: " + itemsPerPage); + + this.prefix = prefix; + this.arguments = arguments; + this.host = host; + this.argumentNames = Map.copyOf(argumentNames); + this.pagination = pagination; this.itemsPerPage = itemsPerPage; this.sortAlphabetically = sortAlphabetically; this.dedupeByDefinitionId = dedupeByDefinitionId; - this.placeholderFormat = placeholderFormat; } @Override @NotNull - public String build(@NotNull Collection> commands, int page) { - String message = String.join("\n", messages.getFormat()); - Collection> resolvedCommands = dedupeByDefinitionId - ? dedupeCommands(commands) - : commands; + public Component build(@NotNull Collection> commands, int page) { + List> listed = listed(commands); + List lines = new ArrayList<>(); + lines.add(text(Text.TITLE, arguments.create(Argument.HOST, host))); - if (message.contains(token("commands"))) - message = buildCommandList(resolvedCommands, message, page, itemsPerPage); + List commandLines = listed.stream() + .skip((long) (Math.max(1, page) - 1) * itemsPerPage) + .limit(itemsPerPage) + .map(this::line) + .toList(); + lines.addAll(commandLines.isEmpty() ? List.of(text(Text.EMPTY)) : commandLines); - if (message.contains(token("pagination")) && paginationBuilder != null) - message = paginationBuilder.build(message, resolvedCommands.size(), page, itemsPerPage); - else - message = replaceToken(message, "pagination", ""); + pageLine(listed.size(), page).ifPresent(lines::add); - return message; + return Component.join(JoinConfiguration.newlines(), lines); } - /** - * Builds the command list section. - * - * @param commands Collection of commands - * @param message The message template - * @param page Current page number - * @param itemsPerPage Number of items per page - * @return Message with placeholder replaced - */ @NotNull - private String buildCommandList( - @NotNull Collection> commands, - @NotNull String message, - int page, - int itemsPerPage - ) { - if (commands.isEmpty()) - return replaceToken(message, "commands", messages.getNoCommands()); + private Optional pageLine(int totalItems, int page) { + if (pagination == null) return Optional.empty(); - long skip = (long) (page - 1) * itemsPerPage; - - var commandStream = commands.stream(); - if (sortAlphabetically) { - commandStream = commandStream.sorted((c1, c2) -> - buildCommandKey(c1).compareToIgnoreCase(buildCommandKey(c2))); - } + return pagination.build(totalItems, page, itemsPerPage); + } - List commandDescriptions = commandStream - .skip(skip) - .limit(itemsPerPage) - .map(this::formatCommand) - .collect(Collectors.toList()); + @NotNull + private List> listed(@NotNull Collection> commands) { + List> listed = dedupeByDefinitionId ? dedupe(commands) : new ArrayList<>(commands); + if (sortAlphabetically) listed.sort(Comparator.comparing(DefaultHelpBuilder::sortKey, String.CASE_INSENSITIVE_ORDER)); - String commandsString = String.join("\n", commandDescriptions); - return replaceToken(message, "commands", commandsString); + return listed; } @NotNull - private Collection> dedupeCommands(@NotNull Collection> commands) { + private List> dedupe(@NotNull Collection> commands) { List> result = new ArrayList<>(); Set seen = new HashSet<>(); for (Command command : commands) { - String definitionId = command.commandMeta() - .optional(CommandantKeys.DEFINITION_ID) - .orElse(null); - if (definitionId == null) { - result.add(command); - continue; - } - - if (seen.add(definitionId)) - result.add(command); + Optional definitionId = command.commandMeta().optional(CommandantKeys.DEFINITION_ID); + if (definitionId.isEmpty() || seen.add(definitionId.get())) result.add(command); } return result; } - /** - * Formats a single command entry. - * - * @param command The command to format - * @return Formatted command string - */ @NotNull - private String formatCommand(@NotNull Command command) { - String commandName = command.rootComponent().name(); - String arguments = formatCommandArguments(command.nonFlagArguments()); - String description = command.commandDescription().description().textDescription(); - - return replaceToken( - replaceToken( - replaceToken(messages.getCommandFormat(), "command", commandName), - "arguments", - arguments - ), - "description", - description + private Component line(@NotNull Command command) { + return text( + Text.COMMAND, + arguments.create(Argument.COMMAND, command.rootComponent().name()), + arguments.create(Argument.ARGUMENTS, arguments(command.nonFlagArguments())), + arguments.create(Argument.DESCRIPTION, description(command.commandDescription().description())) ); } - /** - * Formats command arguments according to their type (required/optional). - * - * @param arguments List of command components (arguments) - * @return Formatted arguments string - */ + // Every argument after the root command, each after a space. @NotNull - private String formatCommandArguments(@NotNull List> arguments) { - if (arguments.isEmpty()) - return ""; - - HelpMessages.Format format = messages.getArgumentFormat(); - if (format == null) - return ""; // No argument formatting configured - - return arguments.stream() - .skip(1) // Skip the command name itself - .map(argument -> formatSingleArgument(argument, format)) - .collect(Collectors.collectingAndThen( - Collectors.joining(" "), - formattedArguments -> formattedArguments.isEmpty() ? "" : " " + formattedArguments - )); + private Component arguments(@NotNull List> components) { + List parts = new ArrayList<>(); + for (CommandComponent component : components.subList(Math.min(1, components.size()), components.size())) { + parts.add(SPACE); + parts.add(argument(component)); + } + + return Component.join(JoinConfiguration.noSeparators(), parts); } - /** - * Formats a single argument based on its type. - * - * @param argument The argument component - * @param format The format configuration - * @return Formatted argument string - */ @NotNull - private String formatSingleArgument(@NotNull CommandComponent argument, @NotNull HelpMessages.Format format) { - CommandComponent.ComponentType type = argument.type(); - boolean variable = type == CommandComponent.ComponentType.REQUIRED_VARIABLE - || type == CommandComponent.ComponentType.OPTIONAL_VARIABLE; - - String argumentName = variable - ? customArgumentNames.getOrDefault(argument.name(), argument.name()) - : argument.name(); - - return switch (type) { - case REQUIRED_VARIABLE -> replaceToken(format.getArgument(), "argument", argumentName); - case OPTIONAL_VARIABLE -> replaceToken(format.getOptionalArgument(), "argument", argumentName); - default -> argumentName; + private Component argument(@NotNull CommandComponent component) { + String name = argumentNames.getOrDefault(component.name(), component.name()); + + return switch (component.type()) { + case REQUIRED_VARIABLE -> text(Text.ARGUMENT, arguments.create(Argument.NAME, name)); + case OPTIONAL_VARIABLE -> text(Text.OPTIONAL_ARGUMENT, arguments.create(Argument.NAME, name)); + default -> Component.text(component.name()); }; } @NotNull - private String token(@NotNull String placeholder) { - return placeholderFormat.format(placeholder); + private static Component description(@NotNull Description description) { + if (description instanceof ComponentLike component) return component.asComponent(); + + return Component.text(description.textDescription()); } @NotNull - private String replaceToken(@NotNull String message, @NotNull String placeholder, @NotNull String value) { - return message.replace(token(placeholder), value); + private Component text(@NotNull Text text, @NotNull ComponentLike... values) { + return Component.translatable(text.under(prefix), values); } @NotNull - private String buildCommandKey(@NotNull Command command) { + private static String sortKey(@NotNull Command command) { return command.nonFlagArguments().stream() .map(CommandComponent::name) .collect(Collectors.joining(" ")); diff --git a/commandant-common/src/main/java/me/whereareiam/commandant/common/DefaultPaginationBuilder.java b/commandant-common/src/main/java/me/whereareiam/commandant/common/DefaultPaginationBuilder.java index a7a0c56..9085cd5 100644 --- a/commandant-common/src/main/java/me/whereareiam/commandant/common/DefaultPaginationBuilder.java +++ b/commandant-common/src/main/java/me/whereareiam/commandant/common/DefaultPaginationBuilder.java @@ -1,135 +1,93 @@ package me.whereareiam.commandant.common; +import me.whereareiam.commandant.builder.ArgumentFactory; import me.whereareiam.commandant.builder.PaginationBuilder; -import me.whereareiam.commandant.model.message.PaginationMessages; -import me.whereareiam.keystone.model.SerializerOptions; +import net.kyori.adventure.text.Component; +import net.kyori.adventure.text.ComponentLike; +import net.kyori.adventure.text.event.ClickEvent; import org.jetbrains.annotations.NotNull; +import org.jetbrains.annotations.Nullable; + +import java.util.Optional; +import java.util.function.IntFunction; /** - * Default implementation of PaginationBuilder. - * Formats navigation elements (previous/next buttons) and page indicators. - *

- * This builder is generic and can be used across different projects by providing - * a PaginationMessages configuration. - *

- * Usage example: - *

{@code
- * PaginationMessages config = ...; // from your config
- * PaginationBuilder builder = new DefaultPaginationBuilder(config);
- *
- * String message = "Header\n\n";
- * String result = builder.build(message, 25, 2, 10);
- * // Result: "Header\n\n← Page 2/3 →"
- * }
+ * The standard pagination: the {@link Text#LINE} text under a prefix, with the {@link Text#PREVIOUS} and + * {@link Text#NEXT} arrows as its arguments. An arrow runs the page command, when there is one, for the page it + * opens. */ public class DefaultPaginationBuilder implements PaginationBuilder { - private final PaginationMessages messages; - private final SerializerOptions.PlaceholderFormat placeholderFormat; + private final String prefix; + private final ArgumentFactory arguments; + private final IntFunction pageCommand; + private final boolean showIfOnePage; + private final boolean showPreviousOnFirst; + private final boolean showNextOnLast; /** - * Creates a new DefaultPaginationBuilder with the given configuration. + * Creates a pagination. * - * @param messages The pagination message configuration + * @param prefix the keys' prefix, such as {@code arbor.help.pagination} + * @param arguments makes the named arguments of the texts + * @param pageCommand the command that opens a page, such as {@code /arbor help 2}, or {@code null} + * for arrows that run nothing + * @param showIfOnePage whether the line is shown when the list fits on one page + * @param showPreviousOnFirst whether the previous arrow is shown on the first page, opening it again + * @param showNextOnLast whether the next arrow is shown on the last page, opening it again */ - public DefaultPaginationBuilder(@NotNull PaginationMessages messages) { - this(messages, SerializerOptions.PlaceholderFormat.CURLY_BRACES); - } - public DefaultPaginationBuilder( - @NotNull PaginationMessages messages, - @NotNull SerializerOptions.PlaceholderFormat placeholderFormat + @NotNull String prefix, + @NotNull ArgumentFactory arguments, + @Nullable IntFunction pageCommand, + boolean showIfOnePage, + boolean showPreviousOnFirst, + boolean showNextOnLast ) { - this.messages = messages; - this.placeholderFormat = placeholderFormat; + this.prefix = prefix; + this.arguments = arguments; + this.pageCommand = pageCommand; + this.showIfOnePage = showIfOnePage; + this.showPreviousOnFirst = showPreviousOnFirst; + this.showNextOnLast = showNextOnLast; } @Override @NotNull - public String build(@NotNull String message, int totalItems, int currentPage, int itemsPerPage) { - int totalPages = (int) Math.ceil((double) totalItems / itemsPerPage); - - if (totalPages <= 1 && !messages.isShowPaginationIfOnePage()) { - return replaceToken(message, "pagination", ""); - } - - String pagination = formatPagination(currentPage, totalPages); - return replaceToken(message, "pagination", pagination); + public Optional build(int totalItems, int currentPage, int itemsPerPage) { + int perPage = Math.max(1, itemsPerPage); + int totalPages = Math.max(1, (totalItems + perPage - 1) / perPage); + if (totalPages == 1 && !showIfOnePage) return Optional.empty(); + + return Optional.of(Component.translatable( + Text.LINE.under(prefix), + arguments.create(Argument.CURRENT, currentPage), + arguments.create(Argument.MAX, totalPages), + arguments.create(Argument.PREVIOUS, previous(currentPage, totalPages)), + arguments.create(Argument.NEXT, next(currentPage, totalPages)) + )); } - /** - * Formats the pagination controls based on current page and total pages. - * - * @param currentPage Current page number (1-indexed) - * @param totalPages Total number of pages - * @return Formatted pagination string - */ @NotNull - private String formatPagination(int currentPage, int totalPages) { - String previousLink = buildPreviousLink(currentPage); - String nextLink = buildNextLink(currentPage, totalPages); + private Component previous(int currentPage, int totalPages) { + if (currentPage > 1) return arrow(Text.PREVIOUS, Math.min(currentPage - 1, totalPages)); + if (showPreviousOnFirst) return arrow(Text.PREVIOUS, 1); - return replaceToken( - replaceToken( - replaceToken( - replaceToken(messages.getFormat(), "previous", previousLink), - "next", - nextLink - ), - "current", - String.valueOf(currentPage) - ), - "max", - String.valueOf(totalPages) - ); + return Component.empty(); } - /** - * Builds the previous page navigation link. - * - * @param currentPage Current page number - * @return Formatted previous link, or empty string if not applicable - */ @NotNull - private String buildPreviousLink(int currentPage) { - if (currentPage > 1) { - return replaceToken( - messages.getPreviousTagFormat(), - "previousPage", - String.valueOf(currentPage - 1) - ); - } + private Component next(int currentPage, int totalPages) { + if (currentPage < totalPages) return arrow(Text.NEXT, currentPage + 1); + if (showNextOnLast) return arrow(Text.NEXT, totalPages); - return messages.isShowPreviousEvenIfFirst() - ? replaceToken(messages.getPreviousTagFormat(), "previousPage", "1") - : ""; + return Component.empty(); } - /** - * Builds the next page navigation link. - * - * @param currentPage Current page number - * @param totalPages Total number of pages - * @return Formatted next link, or empty string if not applicable - */ @NotNull - private String buildNextLink(int currentPage, int totalPages) { - if (currentPage < totalPages) { - return replaceToken( - messages.getNextTagFormat(), - "nextPage", - String.valueOf(currentPage + 1) - ); - } + private Component arrow(@NotNull Text text, int page) { + Component arrow = Component.translatable(text.under(prefix), arguments.create(Argument.PAGE, page)); + if (pageCommand == null) return arrow; - return messages.isShowNextEvenIfLast() - ? replaceToken(messages.getNextTagFormat(), "nextPage", String.valueOf(totalPages)) - : ""; - } - - @NotNull - private String replaceToken(@NotNull String message, @NotNull String placeholder, @NotNull String value) { - return message.replace(placeholderFormat.format(placeholder), value); + return arrow.clickEvent(ClickEvent.runCommand(pageCommand.apply(page))); } } - - diff --git a/commandant-common/src/test/java/me/whereareiam/commandant/common/DefaultHelpBuilderTest.java b/commandant-common/src/test/java/me/whereareiam/commandant/common/DefaultHelpBuilderTest.java index 8527397..392be89 100644 --- a/commandant-common/src/test/java/me/whereareiam/commandant/common/DefaultHelpBuilderTest.java +++ b/commandant-common/src/test/java/me/whereareiam/commandant/common/DefaultHelpBuilderTest.java @@ -2,24 +2,33 @@ import me.whereareiam.commandant.CommandantKeys; import me.whereareiam.commandant.builder.HelpBuilder; -import me.whereareiam.commandant.model.message.HelpMessages; -import me.whereareiam.commandant.model.message.PaginationMessages; +import net.kyori.adventure.text.Component; +import net.kyori.adventure.text.ComponentLike; import org.incendo.cloud.Command; import org.incendo.cloud.CommandManager; import org.incendo.cloud.description.CommandDescription; +import org.incendo.cloud.description.Description; import org.incendo.cloud.execution.ExecutionCoordinator; import org.incendo.cloud.internal.CommandRegistrationHandler; +import org.jetbrains.annotations.NotNull; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; import java.util.Collection; +import java.util.HashMap; import java.util.List; import java.util.Map; +import java.util.Set; -import static org.junit.jupiter.api.Assertions.assertFalse; +import static me.whereareiam.commandant.builder.HelpBuilder.Text; +import static org.incendo.cloud.parser.standard.IntegerParser.integerParser; +import static org.incendo.cloud.parser.standard.StringParser.stringParser; +import static org.junit.jupiter.api.Assertions.assertEquals; import static org.junit.jupiter.api.Assertions.assertTrue; class DefaultHelpBuilderTest { + private static final String PREFIX = "arbor.help"; + private CommandManager commandManager; @BeforeEach @@ -29,12 +38,94 @@ void setUp() { CommandRegistrationHandler.nullCommandRegistrationHandler() ) { @Override - public boolean hasPermission(TestSender sender, String permission) { + public boolean hasPermission(@NotNull TestSender sender, @NotNull String permission) { return true; } }; } + @Test + void buildsAPageOfTranslatableTexts() { + Command status = commandManager.commandBuilder("arbor") + .literal("status") + .commandDescription(CommandDescription.commandDescription(new KeyDescription("arbor.command.status.description"))) + .handler(context -> {}) + .build(); + Command module = commandManager.commandBuilder("arbor") + .literal("module") + .required("id", stringParser()) + .optional("page", integerParser()) + .commandDescription(CommandDescription.commandDescription("Shows a module")) + .handler(context -> {}) + .build(); + + HelpBuilder help = help(Map.of("id", "module"), null, 7); + + assertEquals( + String.join("\n", + "arbor.help.title(host=Arbor)", + "arbor.help.command(command=arbor, arguments= status, description=arbor.command.status.description())", + "arbor.help.command(command=arbor, arguments= module arbor.help.argument(name=module) " + + "arbor.help.optionalArgument(name=page), description=Shows a module)" + ), + Rendered.of(help.build(List.of(status, module), 1)) + ); + } + + @Test + void everyTextGetsTheArgumentsItDeclares() { + Command module = commandManager.commandBuilder("arbor") + .literal("module") + .required("id", stringParser()) + .optional("page", integerParser()) + .handler(context -> {}) + .build(); + HelpBuilder help = help(Map.of(), null, 7); + + Map> built = new HashMap<>(Rendered.arguments(help.build(List.of(module), 1))); + built.putAll(Rendered.arguments(help.build(List.of(), 1))); + + Map> declared = Rendered.declared(PREFIX, Text.values()); + assertEquals(declared, built); + } + + @Test + void showsTheEmptyLineWhenAPageHasNoCommand() { + HelpBuilder help = help(Map.of(), null, 7); + + assertEquals( + "arbor.help.title(host=Arbor)\narbor.help.empty()", + Rendered.of(help.build(List.of(), 1)) + ); + assertEquals( + "arbor.help.title(host=Arbor)\narbor.help.empty()", + Rendered.of(help.build(List.of(command("alpha", "alpha")), 2)) + ); + } + + @Test + void addsThePageLineUnderTheCommands() { + DefaultPaginationBuilder pagination = new DefaultPaginationBuilder( + PREFIX + ".pagination", + Rendered.ARGUMENTS, + page -> "/arbor help " + page, + false, + false, + false + ); + HelpBuilder help = help(Map.of(), pagination, 1); + + assertEquals( + String.join("\n", + "arbor.help.title(host=Arbor)", + "arbor.help.command(command=bravo, arguments=, description=bravo)", + "arbor.help.pagination.line(current=2, max=2, " + + "previous=arbor.help.pagination.previous(page=1)[click /arbor help 1], next=)" + ), + Rendered.of(help.build(List.of(command("alpha", "alpha"), command("bravo", "bravo")), 2)) + ); + } + @Test void dedupedCommandsDrivePaginationTotals() { Collection> commands = List.of( @@ -53,56 +144,52 @@ void dedupedCommandsDrivePaginationTotals() { command("golf", "golf"), command("golfalias", "golf") ); - - HelpBuilder builder = new DefaultHelpBuilder<>( - helpMessages(), + HelpBuilder help = new DefaultHelpBuilder<>( + PREFIX, + Rendered.ARGUMENTS, + "Arbor", Map.of(), - new DefaultPaginationBuilder(paginationMessages()), + new DefaultPaginationBuilder(PREFIX + ".pagination", Rendered.ARGUMENTS, null, false, false, false), 3, true, - true, - me.whereareiam.keystone.model.SerializerOptions.PlaceholderFormat.CURLY_BRACES + true ); - String secondPage = builder.build(commands, 2); - String thirdPage = builder.build(commands, 3); + String secondPage = Rendered.of(help.build(commands, 2)); + String thirdPage = Rendered.of(help.build(commands, 3)); + + assertTrue(secondPage.contains("current=2, max=3")); + assertTrue(thirdPage.contains("current=3, max=3")); + assertTrue(thirdPage.contains("command=golf")); + } - assertTrue(secondPage.contains("[2/3]")); - assertTrue(thirdPage.contains("[3/3]")); - assertTrue(thirdPage.contains("/golf")); - assertFalse(thirdPage.contains("[3/5]")); + private HelpBuilder help( + Map argumentNames, + DefaultPaginationBuilder pagination, + int itemsPerPage + ) { + return new DefaultHelpBuilder<>(PREFIX, Rendered.ARGUMENTS, "Arbor", argumentNames, pagination, itemsPerPage, false, false); } private Command command(String alias, String definitionId) { return commandManager.commandBuilder(alias) .meta(CommandantKeys.DEFINITION_ID, definitionId) .commandDescription(CommandDescription.commandDescription(definitionId)) - .handler(ctx -> {}) + .handler(context -> {}) .build(); } - private HelpMessages helpMessages() { - HelpMessages helpMessages = new HelpMessages(); - helpMessages.setFormat(List.of( - "Help", - "{commands}", - "{pagination}" - )); - helpMessages.setCommandFormat("/{command} - {description}"); - helpMessages.setNoCommands("No commands"); - helpMessages.setCommandsPerPage(3); - return helpMessages; - } + // A description that is a component, as a translatable description is. + private record KeyDescription(String key) implements Description, ComponentLike { + @Override + public @NotNull String textDescription() { + return key; + } - private PaginationMessages paginationMessages() { - PaginationMessages paginationMessages = new PaginationMessages(); - paginationMessages.setShowPaginationIfOnePage(false); - paginationMessages.setFormat("[{current}/{max}]"); - paginationMessages.setShowPreviousEvenIfFirst(false); - paginationMessages.setPreviousTagFormat("<{previousPage}"); - paginationMessages.setShowNextEvenIfLast(false); - paginationMessages.setNextTagFormat(">{nextPage}"); - return paginationMessages; + @Override + public @NotNull Component asComponent() { + return Component.translatable(key); + } } private static final class TestSender { diff --git a/commandant-common/src/test/java/me/whereareiam/commandant/common/DefaultPaginationBuilderTest.java b/commandant-common/src/test/java/me/whereareiam/commandant/common/DefaultPaginationBuilderTest.java new file mode 100644 index 0000000..1caf85d --- /dev/null +++ b/commandant-common/src/test/java/me/whereareiam/commandant/common/DefaultPaginationBuilderTest.java @@ -0,0 +1,91 @@ +package me.whereareiam.commandant.common; + +import me.whereareiam.commandant.builder.PaginationBuilder; +import org.junit.jupiter.api.Test; + +import java.util.Map; +import java.util.Optional; +import java.util.Set; + +import static me.whereareiam.commandant.builder.PaginationBuilder.Text; +import static org.junit.jupiter.api.Assertions.assertEquals; + +class DefaultPaginationBuilderTest { + private static final String PREFIX = "arbor.help.pagination"; + + @Test + void everyTextGetsTheArgumentsItDeclares() { + PaginationBuilder pagination = pagination(false, false, false); + + Map> declared = Rendered.declared(PREFIX, Text.values()); + assertEquals(declared, Rendered.arguments(pagination.build(20, 2, 7).orElseThrow())); + } + + @Test + void hidesTheLineWhenEverythingFitsOnOnePage() { + PaginationBuilder pagination = pagination(false, false, false); + + assertEquals(Optional.empty(), pagination.build(5, 1, 7)); + } + + @Test + void showsArrowsThatRunThePageCommandOfTheirPage() { + PaginationBuilder pagination = pagination(false, false, false); + + assertEquals( + "arbor.help.pagination.line(current=2, max=3, " + + "previous=arbor.help.pagination.previous(page=1)[click /arbor help 1], " + + "next=arbor.help.pagination.next(page=3)[click /arbor help 3])", + Rendered.of(pagination.build(20, 2, 7).orElseThrow()) + ); + } + + @Test + void leavesOutArrowsWithNoPageToGoTo() { + PaginationBuilder pagination = pagination(false, false, false); + + assertEquals( + "arbor.help.pagination.line(current=1, max=2, previous=, " + + "next=arbor.help.pagination.next(page=2)[click /arbor help 2])", + Rendered.of(pagination.build(10, 1, 7).orElseThrow()) + ); + assertEquals( + "arbor.help.pagination.line(current=2, max=2, " + + "previous=arbor.help.pagination.previous(page=1)[click /arbor help 1], next=)", + Rendered.of(pagination.build(10, 2, 7).orElseThrow()) + ); + } + + @Test + void showsWhatItIsToldToOnASinglePage() { + PaginationBuilder pagination = pagination(true, true, true); + + assertEquals( + "arbor.help.pagination.line(current=1, max=1, " + + "previous=arbor.help.pagination.previous(page=1)[click /arbor help 1], " + + "next=arbor.help.pagination.next(page=1)[click /arbor help 1])", + Rendered.of(pagination.build(0, 1, 7).orElseThrow()) + ); + } + + @Test + void arrowsRunNothingWithoutAPageCommand() { + PaginationBuilder pagination = new DefaultPaginationBuilder(PREFIX, Rendered.ARGUMENTS, null, false, false, false); + + assertEquals( + "arbor.help.pagination.line(current=1, max=2, previous=, next=arbor.help.pagination.next(page=2))", + Rendered.of(pagination.build(10, 1, 7).orElseThrow()) + ); + } + + private PaginationBuilder pagination(boolean showIfOnePage, boolean showPreviousOnFirst, boolean showNextOnLast) { + return new DefaultPaginationBuilder( + PREFIX, + Rendered.ARGUMENTS, + page -> "/arbor help " + page, + showIfOnePage, + showPreviousOnFirst, + showNextOnLast + ); + } +} diff --git a/commandant-common/src/test/java/me/whereareiam/commandant/common/Rendered.java b/commandant-common/src/test/java/me/whereareiam/commandant/common/Rendered.java new file mode 100644 index 0000000..3505958 --- /dev/null +++ b/commandant-common/src/test/java/me/whereareiam/commandant/common/Rendered.java @@ -0,0 +1,82 @@ +package me.whereareiam.commandant.common; + +import me.whereareiam.commandant.builder.ArgumentFactory; +import me.whereareiam.commandant.builder.TranslationArgument; +import me.whereareiam.commandant.builder.TranslationKey; +import net.kyori.adventure.text.Component; +import net.kyori.adventure.text.ComponentLike; +import net.kyori.adventure.text.TextComponent; +import net.kyori.adventure.text.TranslatableComponent; +import net.kyori.adventure.text.event.ClickEvent; + +import java.util.Arrays; +import java.util.HashMap; +import java.util.Map; +import java.util.Set; +import java.util.stream.Collectors; + +/** + * Writes out components as their keys and named arguments, such as {@code a.title(host=Arbor)}, so a test reads + * what a translator is asked for. + */ +final class Rendered { + /** + * Names an argument as {@code name=value}, as a translator's named argument would. + */ + static final ArgumentFactory ARGUMENTS = (name, value) -> Component.text(name + "=").append(value(value)); + + /** + * Collects the translatable components in a tree by key, with the names of the arguments each was given. + */ + static Map> arguments(Component component) { + Map> arguments = new HashMap<>(); + collect(component, arguments); + + return arguments; + } + + /** + * Lists the texts by their full key under a prefix, with the names of the arguments each declares. + */ + static Map> declared(String prefix, TranslationKey... texts) { + return Arrays.stream(texts).collect(Collectors.toMap( + text -> text.under(prefix), + text -> text.getArguments().stream().map(TranslationArgument::getId).collect(Collectors.toSet()) + )); + } + + private static void collect(Component component, Map> arguments) { + if (component instanceof TranslatableComponent translatable) { + arguments.put(translatable.key(), translatable.arguments().stream() + .map(argument -> ((TextComponent) argument.asComponent()).content().replace("=", "")) + .collect(Collectors.toSet())); + translatable.arguments().forEach(argument -> collect(argument.asComponent(), arguments)); + } + + component.children().forEach(child -> collect(child, arguments)); + } + + private static Component value(Object value) { + if (value instanceof ComponentLike component) return component.asComponent(); + + return Component.text(String.valueOf(value)); + } + + static String of(Component component) { + StringBuilder text = new StringBuilder(); + if (component instanceof TranslatableComponent translatable) { + text.append(translatable.key()).append('(') + .append(translatable.arguments().stream().map(argument -> of(argument.asComponent())).collect(Collectors.joining(", "))) + .append(')'); + } else if (component instanceof TextComponent plain) { + text.append(plain.content()); + } + + ClickEvent click = component.clickEvent(); + if (click != null) text.append("[click ").append(click.value()).append(']'); + + component.children().forEach(child -> text.append(of(child))); + + return text.toString(); + } +} diff --git a/commandant/src/main/java/me/whereareiam/commandant/CommandantSyntaxFormatter.java b/commandant/src/main/java/me/whereareiam/commandant/CommandantSyntaxFormatter.java index 88e58f5..3aa4c2d 100644 --- a/commandant/src/main/java/me/whereareiam/commandant/CommandantSyntaxFormatter.java +++ b/commandant/src/main/java/me/whereareiam/commandant/CommandantSyntaxFormatter.java @@ -1,6 +1,5 @@ package me.whereareiam.commandant; -import me.whereareiam.commandant.model.message.HelpMessages; import me.whereareiam.keystone.model.SerializerOptions; import org.incendo.cloud.CommandManager; import org.incendo.cloud.component.CommandComponent; @@ -13,13 +12,18 @@ import java.util.Map; /** - * Cloud syntax formatter that mirrors Commandant help argument formatting. + * Cloud syntax formatter that writes required and optional arguments with templates of their own, such as the + * syntax shown by Commandant's exception messages. Each template holds the {@code argument} placeholder in the + * given placeholder format, for example {@code [{argument}]}. * * @param command sender type */ public class CommandantSyntaxFormatter extends StandardCommandSyntaxFormatter { + private static final String ARGUMENT_PLACEHOLDER = "argument"; + private final Map argumentNames; - private final HelpMessages.Format argumentFormat; + private final String requiredFormat; + private final String optionalFormat; private final SerializerOptions.PlaceholderFormat placeholderFormat; /** @@ -27,49 +31,55 @@ public class CommandantSyntaxFormatter extends StandardCommandSyntaxFormatter * * @param manager command manager * @param argumentNames custom argument display names - * @param argumentFormat configured help argument format - * @param placeholderFormat placeholder format used in message templates + * @param requiredFormat template of a required argument, or {@code null} for its bare name + * @param optionalFormat template of an optional argument, or {@code null} for its bare name + * @param placeholderFormat placeholder format used in the templates */ public CommandantSyntaxFormatter( @NotNull CommandManager manager, @Nullable Map argumentNames, - @Nullable HelpMessages.Format argumentFormat, + @Nullable String requiredFormat, + @Nullable String optionalFormat, @NotNull SerializerOptions.PlaceholderFormat placeholderFormat ) { super(manager); this.argumentNames = argumentNames != null ? argumentNames : Map.of(); - this.argumentFormat = argumentFormat; + this.requiredFormat = requiredFormat != null ? requiredFormat : placeholderFormat.format(ARGUMENT_PLACEHOLDER); + this.optionalFormat = optionalFormat != null ? optionalFormat : placeholderFormat.format(ARGUMENT_PLACEHOLDER); this.placeholderFormat = placeholderFormat; } @Override protected @NotNull FormattingInstance createInstance() { - return new CommandantFormattingInstance(argumentNames, argumentFormat, placeholderFormat); + return new CommandantFormattingInstance(argumentNames, requiredFormat, optionalFormat, placeholderFormat); } private static final class CommandantFormattingInstance extends FormattingInstance { private final Map argumentNames; - private final HelpMessages.Format argumentFormat; + private final String requiredFormat; + private final String optionalFormat; private final SerializerOptions.PlaceholderFormat placeholderFormat; private CommandantFormattingInstance( @NotNull Map argumentNames, - @Nullable HelpMessages.Format argumentFormat, + @NotNull String requiredFormat, + @NotNull String optionalFormat, @NotNull SerializerOptions.PlaceholderFormat placeholderFormat ) { this.argumentNames = argumentNames; - this.argumentFormat = argumentFormat; + this.requiredFormat = requiredFormat; + this.optionalFormat = optionalFormat; this.placeholderFormat = placeholderFormat; } @Override public void appendRequired(@NotNull CommandComponent argument) { - super.appendName(format(argument, requiredTemplate())); + super.appendName(format(argument, requiredFormat)); } @Override public void appendOptional(@NotNull CommandComponent argument) { - super.appendName(format(argument, optionalTemplate())); + super.appendName(format(argument, optionalFormat)); } @Override @@ -77,7 +87,7 @@ public void appendAggregate( @NotNull CommandComponent component, @NotNull AggregateParser parser ) { - String template = component.required() ? requiredTemplate() : optionalTemplate(); + String template = component.required() ? requiredFormat : optionalFormat; Iterator> innerComponents = parser.components().iterator(); while (innerComponents.hasNext()) { CommandComponent innerComponent = innerComponents.next(); @@ -87,25 +97,11 @@ public void appendAggregate( } private @NotNull String format(@NotNull CommandComponent argument, @NotNull String template) { - return template.replace(placeholderFormat.format("argument"), argumentName(argument)); + return template.replace(placeholderFormat.format(ARGUMENT_PLACEHOLDER), argumentName(argument)); } private @NotNull String argumentName(@NotNull CommandComponent argument) { return argumentNames.getOrDefault(argument.name(), argument.name()); } - - private @NotNull String requiredTemplate() { - if (argumentFormat == null || argumentFormat.getArgument() == null) - return placeholderFormat.format("argument"); - - return argumentFormat.getArgument(); - } - - private @NotNull String optionalTemplate() { - if (argumentFormat == null || argumentFormat.getOptionalArgument() == null) - return placeholderFormat.format("argument"); - - return argumentFormat.getOptionalArgument(); - } } } diff --git a/commandant/src/main/java/me/whereareiam/commandant/Help.java b/commandant/src/main/java/me/whereareiam/commandant/Help.java index 5bb4983..6215770 100644 --- a/commandant/src/main/java/me/whereareiam/commandant/Help.java +++ b/commandant/src/main/java/me/whereareiam/commandant/Help.java @@ -1,113 +1,186 @@ package me.whereareiam.commandant; +import me.whereareiam.commandant.builder.ArgumentFactory; import me.whereareiam.commandant.builder.HelpBuilder; import me.whereareiam.commandant.builder.PaginationBuilder; import me.whereareiam.commandant.common.DefaultHelpBuilder; -import me.whereareiam.commandant.model.message.HelpMessages; -import me.whereareiam.commandant.model.message.PaginationMessages; -import me.whereareiam.keystone.model.SerializerOptions; import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; import java.util.Map; +import java.util.Objects; +import java.util.function.IntFunction; /** - * Fluent helper for creating HelpBuilder instances. + * Creates a {@link HelpBuilder}: a help made of translatable components, which the plugin's translator renders in + * each reader's language. The plugin writes a translation of each {@link HelpBuilder.Text} under the prefix, and of + * each {@link me.whereareiam.commandant.builder.PaginationBuilder.Text} under {@code .pagination}. + * + *
{@code
+ * HelpBuilder help = Help.builder("arbor.help", TextArgument::of)
+ *         .host("Arbor")
+ *         .pageCommand(page -> "/arbor help " + page)
+ *         .dedupeByDefinitionId(true)
+ *         .build();
+ *
+ * sender.sendMessage(help.build(visibleCommands, page));
+ * }
*/ @SuppressWarnings("unused") public final class Help { /** - * Creates a fluent builder for HelpBuilder configuration. + * Starts a help. * - * @param helpMessages The help message configuration - * @param The sender type - * @return A new Help builder + * @param prefix the keys' prefix, such as {@code arbor.help} + * @param arguments makes the named arguments of the texts, such as semantica's {@code TextArgument::of} + * @param the sender type + * @return the builder */ @NotNull - public static Builder builder(@NotNull HelpMessages helpMessages) { - return new Builder<>(helpMessages); + public static Builder builder(@NotNull String prefix, @NotNull ArgumentFactory arguments) { + return new Builder<>(prefix, arguments); } /** - * Fluent builder for HelpBuilder configuration. + * Builder of a {@link HelpBuilder}. Without further settings it lists 7 commands per page in the order given, + * with a page line under {@code .pagination} that is hidden when the commands fit on one page. * - * @param The sender type + * @param the sender type */ public static final class Builder { - private final HelpMessages helpMessages; - private Map customArgumentNames; - private PaginationBuilder paginationBuilder; - private PaginationMessages paginationMessages; - private int itemsPerPage; + private static final int DEFAULT_ITEMS_PER_PAGE = 7; + + private final String prefix; + private final ArgumentFactory arguments; + private String host; + private Map argumentNames = Map.of(); + private PaginationBuilder pagination; + private IntFunction pageCommand; + private int itemsPerPage = DEFAULT_ITEMS_PER_PAGE; private boolean sortAlphabetically; private boolean dedupeByDefinitionId; - private SerializerOptions.PlaceholderFormat placeholderFormat = SerializerOptions.PlaceholderFormat.CURLY_BRACES; - private Builder(@NotNull HelpMessages helpMessages) { - this.helpMessages = helpMessages; - this.itemsPerPage = helpMessages.getCommandsPerPage(); + private Builder(@NotNull String prefix, @NotNull ArgumentFactory arguments) { + this.prefix = prefix; + this.arguments = arguments; } + /** + * Sets the name of the plugin whose help it is, the heading's {@code host} argument. Required. + * + * @param host the name, such as {@code Arbor} + * @return this builder + */ @NotNull - public Builder customArgumentNames(@Nullable Map customArgumentNames) { - this.customArgumentNames = customArgumentNames; + public Builder host(@NotNull String host) { + this.host = host; return this; } + /** + * Sets names to show instead of arguments' own names. + * + * @param argumentNames the shown name by argument name + * @return this builder + */ @NotNull - public Builder paginationBuilder(@Nullable PaginationBuilder paginationBuilder) { - this.paginationBuilder = paginationBuilder; + public Builder argumentNames(@NotNull Map argumentNames) { + this.argumentNames = argumentNames; return this; } + /** + * Sets the command the page line's arrows run, for the help's own pagination. + * + * @param pageCommand gives the command that opens a page of help, with its slash, such as + * {@code page -> "/arbor help " + page}; {@code null} for arrows that run nothing + * @return this builder + */ @NotNull - public Builder paginationMessages(@Nullable PaginationMessages paginationMessages) { - this.paginationMessages = paginationMessages; + public Builder pageCommand(@Nullable IntFunction pageCommand) { + this.pageCommand = pageCommand; return this; } + /** + * Replaces the help's own pagination, such as one made by {@link Pagination} with other keys or settings. + * + * @param pagination the pagination, or {@code null} for the help's own + * @return this builder + */ + @NotNull + public Builder pagination(@Nullable PaginationBuilder pagination) { + this.pagination = pagination; + return this; + } + + /** + * Sets the number of commands on one page. + * + * @param itemsPerPage the number, at least {@code 1} + * @return this builder + */ @NotNull public Builder itemsPerPage(int itemsPerPage) { this.itemsPerPage = itemsPerPage; return this; } + /** + * Sets whether commands are listed by their arguments in alphabetical order. + * + * @param sortAlphabetically {@code true} to sort them + * @return this builder + */ @NotNull public Builder sortAlphabetically(boolean sortAlphabetically) { this.sortAlphabetically = sortAlphabetically; return this; } + /** + * Sets whether commands that share a {@link CommandantKeys#DEFINITION_ID}, such as a command and its + * aliases, are listed once. + * + * @param dedupeByDefinitionId {@code true} to list them once + * @return this builder + */ @NotNull public Builder dedupeByDefinitionId(boolean dedupeByDefinitionId) { this.dedupeByDefinitionId = dedupeByDefinitionId; return this; } - @NotNull - public Builder placeholderFormat(@NotNull SerializerOptions.PlaceholderFormat placeholderFormat) { - this.placeholderFormat = placeholderFormat; - return this; - } - + /** + * Builds the help. + * + * @return the help + * @throws NullPointerException when no host was set + * @throws IllegalArgumentException when fewer than one command fits on a page + */ @NotNull public HelpBuilder build() { - PaginationBuilder resolvedPaginationBuilder = paginationBuilder; - if (resolvedPaginationBuilder == null && paginationMessages != null) { - resolvedPaginationBuilder = Pagination.builder(paginationMessages) - .placeholderFormat(placeholderFormat) - .build(); - } + Objects.requireNonNull(host, "host"); return new DefaultHelpBuilder<>( - helpMessages, - customArgumentNames, - resolvedPaginationBuilder, + prefix, + arguments, + host, + argumentNames, + paginationOrDefault(), itemsPerPage, sortAlphabetically, - dedupeByDefinitionId, - placeholderFormat + dedupeByDefinitionId ); } + + @NotNull + private PaginationBuilder paginationOrDefault() { + if (pagination != null) return pagination; + + return Pagination.builder(prefix + '.' + HelpBuilder.PAGINATION, arguments) + .pageCommand(pageCommand) + .build(); + } } } diff --git a/commandant/src/main/java/me/whereareiam/commandant/Pagination.java b/commandant/src/main/java/me/whereareiam/commandant/Pagination.java index aaaeb14..31af548 100644 --- a/commandant/src/main/java/me/whereareiam/commandant/Pagination.java +++ b/commandant/src/main/java/me/whereareiam/commandant/Pagination.java @@ -1,47 +1,121 @@ package me.whereareiam.commandant; +import me.whereareiam.commandant.builder.ArgumentFactory; import me.whereareiam.commandant.builder.PaginationBuilder; import me.whereareiam.commandant.common.DefaultPaginationBuilder; -import me.whereareiam.commandant.model.message.PaginationMessages; -import me.whereareiam.keystone.model.SerializerOptions; import org.jetbrains.annotations.NotNull; +import org.jetbrains.annotations.Nullable; + +import java.util.function.IntFunction; /** - * Fluent helper for creating PaginationBuilder instances. + * Creates a {@link PaginationBuilder}, for a paginated list of a plugin's own. The help makes its own + * pagination; see {@link Help}. The plugin writes a translation of each {@link PaginationBuilder.Text} under the + * prefix. + * + *
{@code
+ * PaginationBuilder pagination = Pagination.builder("arbor.module.list.pagination", TextArgument::of)
+ *         .pageCommand(page -> "/arbor module list " + page)
+ *         .build();
+ *
+ * pagination.build(modules.size(), page, 10).ifPresent(sender::sendMessage);
+ * }
*/ @SuppressWarnings("unused") public final class Pagination { /** - * Creates a fluent builder for PaginationBuilder configuration. + * Starts a pagination. * - * @param paginationMessages The pagination message configuration - * @return A new Pagination builder + * @param prefix the keys' prefix, such as {@code arbor.module.list.pagination} + * @param arguments makes the named arguments of the texts, such as semantica's {@code TextArgument::of} + * @return the builder */ @NotNull - public static Builder builder(@NotNull PaginationMessages paginationMessages) { - return new Builder(paginationMessages); + public static Builder builder(@NotNull String prefix, @NotNull ArgumentFactory arguments) { + return new Builder(prefix, arguments); } /** - * Fluent builder for PaginationBuilder configuration. + * Builder of a {@link PaginationBuilder}. Without further settings the page line is hidden when the list + * fits on one page, arrows are shown only where there is a page to go to, and they run no command. */ public static final class Builder { - private final PaginationMessages paginationMessages; - private SerializerOptions.PlaceholderFormat placeholderFormat = SerializerOptions.PlaceholderFormat.CURLY_BRACES; + private final String prefix; + private final ArgumentFactory arguments; + private IntFunction pageCommand; + private boolean showIfOnePage; + private boolean showPreviousOnFirst; + private boolean showNextOnLast; + + private Builder(@NotNull String prefix, @NotNull ArgumentFactory arguments) { + this.prefix = prefix; + this.arguments = arguments; + } + + /** + * Sets the command an arrow runs. + * + * @param pageCommand gives the command that opens a page, with its slash, such as + * {@code page -> "/arbor help " + page}; {@code null} for arrows that run nothing + * @return this builder + */ + @NotNull + public Builder pageCommand(@Nullable IntFunction pageCommand) { + this.pageCommand = pageCommand; + return this; + } - private Builder(@NotNull PaginationMessages paginationMessages) { - this.paginationMessages = paginationMessages; + /** + * Sets whether the page line is shown when the list fits on one page. + * + * @param showIfOnePage {@code true} to show it always + * @return this builder + */ + @NotNull + public Builder showIfOnePage(boolean showIfOnePage) { + this.showIfOnePage = showIfOnePage; + return this; + } + + /** + * Sets whether the previous arrow is shown on the first page, where it opens the first page again. + * + * @param showPreviousOnFirst {@code true} to show it + * @return this builder + */ + @NotNull + public Builder showPreviousOnFirst(boolean showPreviousOnFirst) { + this.showPreviousOnFirst = showPreviousOnFirst; + return this; } + /** + * Sets whether the next arrow is shown on the last page, where it opens the last page again. + * + * @param showNextOnLast {@code true} to show it + * @return this builder + */ @NotNull - public Builder placeholderFormat(@NotNull SerializerOptions.PlaceholderFormat placeholderFormat) { - this.placeholderFormat = placeholderFormat; + public Builder showNextOnLast(boolean showNextOnLast) { + this.showNextOnLast = showNextOnLast; return this; } + /** + * Builds the pagination. + * + * @return the pagination + */ @NotNull public PaginationBuilder build() { - return new DefaultPaginationBuilder(paginationMessages, placeholderFormat); + return new DefaultPaginationBuilder( + prefix, + arguments, + pageCommand, + showIfOnePage, + showPreviousOnFirst, + showNextOnLast + ); } } }