Suggestions API v1.0.5
该库注入到 Minecraft 源码中,负责处理聊天栏中建议(Suggestions)的逻辑,旨在为添加或修改建议提供更便捷的封装。目前,该库包含以下接口:
- 基于用户在文本输入框中输入的文本,同步/异步地添加建议
- 更改建议的渲染方式
- 处理与建议相关的事件:
- 替换由非 Suggestions API 创建的建议
为此,该库提供了如下现成的实现形式:
- 始终显示的建议(带有“始终显示”条件的文本建议)
- 简单建议(带有默认或自定义显示条件的文本建议)
- 图标建议(带有左侧或右侧图标的文本建议,支持默认或自定义显示条件)
- 同步/异步建议注入器(当在输入框中输入文本并匹配指定的正则表达式模式时,动态添加建议)
哪些模组使用了 Suggestions API?
以下模组使用了 Suggestions API:
入门指南
将以下内容与你的 build.gradle 合并。以下是适用于 Fabric 或 Quilt 版本的示例。如果你正在为 Forge 或 NeoForge 开发,请将 fabric 替换为 forge(自 Suggestions API v1.0.4 起生效)。
build.gradle
repositories {
maven {
url = "https://api.modrinth.com/maven"
}
}
dependencies {
modImplementation "maven.modrinth:suggestions-api:1.0.6+fabric"
}
build.gradle.kts
repositories {
maven("https://api.modrinth.com/maven")
}
dependencies {
modImplementation("maven.modrinth", "suggestions-api", "1.0.6+fabric")
}
快速文档
包含库基本知识的快速文档。
有哪些类型的内置建议?
Suggestion 接口位于 io.github.aratakileo.suggestionsapi.suggestion 包中。
该库内置了两种类型的建议。以下是它们的初始化函数:
Suggestion.simple(...) - 简单建议(仅文本)
Suggestion.withIcon(...) - 带图标的建议(将在左侧渲染)
简单建议初始化函数的主要参数是该建议的文本。例如:
final var simpleSuggestion = Suggestion.simple("bonjour!");
要初始化一个带图标的建议,你需要指定两个主要参数:建议的文本和图标的资源。此函数必须在所有游戏纹理加载完成后严格调用,否则游戏会崩溃。此处以屏障方块纹理为例:
final var suggestionWithIcon = Suggestion.withIcon("barrier", new ResourceLocation("minecraft", "textures/item/barrier.png"));
默认情况下,建议在开始输入建议文本后显示。你可以作为最后一个参数提供自己的映射条件(Lambda 表达式)。Lambda 的第一个参数是建议的文本,第二个参数是当前表达式(光标左侧最近空格与光标之间的文本)。在下面的示例中,如果用户完整输入了建议的文本,则该建议将显示:
final var anotherSimpleSuggetion = Suggestion.simple(
"bonjour!",
(suggestionText, currentExpression) -> suggestionText.toLowerCase().equals(currentExpression.toLowerCase())
);
或者
final var anotherSimpleSuggetion = Suggestion.simple("bonjour!", String::equalsIgnoreCase);
Suggestion.simple(...) 和 Suggestion.withIcon(...) 函数的默认条件是 (suggestionText, currentExpression) -> suggestionText.toLowerCase().startsWith(currentExpression.toLowerCase()) 或 Suggestion::DEFAULT_CONDITION。
如果你想让建议无论输入什么文本都始终显示,可以指定条件 (suggestionText, currentExpression) -> true 或 Suggestion::ALWAYS_SHOW_CONDITION。这在使用 Suggestion.alwaysShown(...)(作为 Suggestion.simple(...) 的替代函数)和 Suggestion.alwaysShownWithIcon(...)(作为 Suggestion.withIcon(...) 的替代函数)初始化建议时默认使用:
final var alwaysShownSuggestion = Suggestion.alwaysShown("bonjour!");
如何向游戏中添加新建议?
你可以使用位于 io.github.aratakileo.suggestionsapi.injector 包中的 Injector 接口向游戏添加新建议。
有两种基本的注入器类型:简单注入器和异步注入器。为了初始化它们,库也提供了相应的函数,其第一个参数将是正则表达式模式。
要注册注入器,需要将其作为唯一参数传递给 SuggestionsAPI.registerInjector(...) 函数。
要创建简单注入器,有一个函数 Injector.simple(...) 返回 SuggestionsInjector。让我们添加两个新的简单建议(Injector.ANYTHING_WITHOUT_SPACES_PATTERN 为 Pattern.compile("\\S+$")):
SuggestionsAPI.registerInjector(Injector.simple(
Injector.ANYTHING_WITHOUT_SPACES_PATTERN,
(stringContainer, startOffset) -> List.of(
Suggestion.alwaysShownWithIcon("barrier", new ResourceLocation("minecraft", "textures/item/barrier.png")),
alwaysShownSuggestion
) // 来自上述示例的变量
));
结果如下所示:

如果你希望在输入命令时不显示你的建议,可以按照以下方式更改代码:
SuggestionsAPI.registerInjector(Injector.simple(
Injector.ANYTHING_WITHOUT_SPACES_PATTERN,
(stringContainer, startOffset) -> stringContainer.getContext().isNotCommand() ? List.of(
Suggestion.alwaysShownWithIcon("barrier", new ResourceLocation("minecraft", "textures/item/barrier.png")),
alwaysShownSuggestion
) : null // 来自上述示例的变量
));
作为第二个参数,函数 Injector.simple(...) 接收一个 lambda 表达式,该表达式描述生成建议列表的过程并返回它。同时,该 lambda 具有两个自己的参数:第一个参数包含当前表达式的字符串(即输入字段中右边缘触及光标的文本,并根据指定模式找到);第二个参数包含一个数字,表示当前表达式起始位置与原始表达式起始位置之间的偏移量(即输入字段中最近左侧空格与光标之间的文本)。以下展示了在尝试输入任何数字时添加数字建议的示例:
SuggestionsAPI.registerInjector(Injector.simple(
Pattern.compile(":[A-Za-z0-9]*(:)?$"),
(stringContainer, startOffset) -> Stream.of(
"67487",
"nothing",
"bedrock",
"bedrock_2"
).map(value -> Suggestion.simple(':' + value + ':')).toList()
));
或
SuggestionsAPI.registerInjector(Injector.simple(
Pattern.compile("[A-Za-z0-9]+$"),
(stringContainer, startOffset) -> Stream.of(
"Hi, " + stringContainer.getContent().substring(startOffset) + '!',
'"' + stringContainer.getContent().substring(startOffset) + '"'
).map(Suggestion::alwaysShown).toList()
));
或
SuggestionsAPI.registerInjector(Injector.simple(
Pattern.compile(":[0-9]*(:)?$"),
(stringContainer, startOffset) -> IntStream.rangeClosed(1000, 1010)
.boxed()
.map(Objects::toString)
.map(Suggestion::alwaysShown)
.toList()
));
// 如果上方注入器中的建议已出现,则此注入器的建议将不会出现,
// 因为此注入器的匹配字符串被包含在上方注入器的匹配字符串中
SuggestionsAPI.registerInjector(Injector.simple(
Pattern.compile("[0-9]$"),
(stringContainer, startOffset) -> IntStream.rangeClosed(0, 9)
.boxed()
.map(Objects::toString)
.map(Suggestion::alwaysShown)
.toList()
));
默认情况下,如果根据某个注入器的正则模式检测到的字符串是另一个注入器的正则模式所检测到的字符串的一部分,则嵌套在其中那个注入器的建议将被忽略。可以通过将第三个(最后一个)参数指定为 InputRelatedInjector.NestingStatus.ALL_NESTABLE 来为特定注入器禁用此机制。例如:
SuggestionsAPI.registerInjector(Injector.simple(
Pattern.compile(":[0-9]*(:)?$"),
(stringContainer, startOffset) -> IntStream.rangeClosed(1000, 1010)
.boxed()
.map(Objects::toString)
.map(Suggestion::alwaysShown)
.toList(),
InputRelatedInjector.NestingStatus.ALL_NESTABLE
));
// 如果上方注入器中的建议已出现,则此注入器的建议也将出现
SuggestionsAPI.registerInjector(Injector.simple(
Pattern.compile("[0-9]$"),
(stringContainer, startOffset) -> IntStream.rangeClosed(0, 9)
.boxed()
.map(Objects::toString)
.map(Suggestion::alwaysShown)
.toList(),
InputRelatedInjector.NestingStatus.ALL_NESTABLE
));
该参数还有其他可能的取值:
InputRelatedInjector.NestingStatus.NOT_NESTABLE - 默认使用
InputRelatedInjector.NestingStatus.ONLY_API_NESTABLE - 仅允许通过 Suggestions API 添加的建议进行嵌套
InputRelatedInjector.NestingStatus.ONLY_NON_API_NESTABLE - 仅允许在 Suggestions API 之外添加的建议进行嵌套 [已弃用]
如果你需要建议同步显示,可以使用函数 Injector.async(...) 来初始化异步注入器。以此函数初始化的注入器提供了一种机制:如果收到了新请求且当前进程尚未完成,则可以取消当前的异步进程。此函数与前一个类似,但此次第二个参数(即 lambda)返回一个无参数的 lambda,该 lambda 将作为异步进程启动,并且具有三个参数,其中最后一个参数是一个接受新建议列表的 lambda,应在异步进程的 lambda 内部使用。例如:
SuggestionsAPI.registerInjector(Injector.async(
/* 在此插入你的模式 */,
(stringContainer, startOffset) -> {
/* 在此插入你的异步处理代码 */
return /* 在此插入建议列表 */;
}
));
函数 Injector.async(...) 返回 AsyncInjector。与前一个函数一样,也可以在此函数中指定第三个参数。
我可以用新实例替换建议吗?[已弃用]
Suggestions API 禁止隐式替换建议,但允许替换那些未通过它添加的建议(即由 Minecraft 或其他不使用 Suggestions API 的模组添加的建议)。如果你需要的建议尚未被其他模组替换,你可以使用位于 io.github.aratakileo.suggestionsapi.injector 中的 ReplacementInjector 来替换建议。例如:
// 要验证这一点,请在聊天栏或命令方块中输入指令 `give @s minecraft:barrier`
SuggestionsAPI.registerInjector(Injector.replacement(
nonApiSuggestion -> nonApiSuggestion.equals("minecraft:barrier") ? Suggestion.withIcon(
nonApiSuggestion,
new ResourceLocation("minecraft", "textures/item/barrier.png")
) : null
));
结果将显示如下:

Suggestions API v1.0.5
This library is injected into the Minecraft source code, which is responsible for the logic of Minecraft suggestions in chat, in order to provide a more convenient wrapper for adding or changing suggestions. Currently, the library contains interfaces for:
- adding suggestions synchronous/asynchronous based on the text entered by the user in the text input field
- changing suggestions render
- processing events related to suggestions:
- on session inited
- on suggestion selected
- replacing suggestions created by non Suggestions API
for which the library provides ready-made implementations in the form of:
- always shown suggestion (texted suggestion with condition to always show it)
- simple suggestion (texted suggestion with default or custom showing condition)
- icon suggestion (texted suggestion with icon on the left or on the right with default or custom showing condition)
- synchronous/asynchronous suggestions injector (dynamically adding suggestions when entering text into the input field based on matching the specified pattern of regex)
Which mods use the Suggestions API?
These mods use the Suggestions API:
Getting started
Merge the following with your. Below is an example with a version for Fabric or Quit. If you are developing for Forge or Neoforge, then replace fabric with forge (works this way since Suggestions API v1.0.4)
build.gradle
repositories {
maven {
url = "https://api.modrinth.com/maven"
}
}
dependencies {
modImplementation "maven.modrinth:suggestions-api:1.0.6+fabric"
}
build.gradle.kts
repositories {
maven("https://api.modrinth.com/maven")
}
dependencies {
modImplementation("maven.modrinth", "suggestions-api", "1.0.6+fabric")
}
Quick DOCS
Quick documentation that includes the basics of the library.
What types of embedded suggestions are there?
The Suggestion interface is located in io.github.aratakileo.suggestionsapi.suggestion.
The library has two built-in types of suggestions. Below are the functions for their initialization:
Suggestion.simple(...) - simple (just text)
Suggestion.withIcon(...) - with an icon (will be rendered on the left)
The main argument for the initialization function of a simple suggestion will be the text of this suggestion. For example:
final var simpleSuggestion = Suggestion.simple("bonjour!");
To initialize a suggestion with an icon, you will need to specify two main arguments: the text of the suggestion and the resource of the icon. This function must be called strictly after loading all the textures of the game, otherwise the game will crash. The barrier texture is taken as an example:
final var suggestionWithIcon = Suggestion.withIcon("barrier", new ResourceLocation("minecraft", "textures/item/barrier.png"));
By default, suggestions begin to be shown after the start of entering the text of the suggestion. You can specify your own mapping condition as a lambda function as the last argument. The first argument of the lambda is the text of the suggestion, the second argument is the current expression (the text in the input field between the nearest left space and the cursor). In the example below, the suggestion will be shown if the user fully enters the text of the suggestion:
final var anotherSimpleSuggetion = Suggestion.simple(
"bonjour!",
(suggestionText, currentExpression) -> suggestionText.toLowerCase().equals(currentExpression.toLowerCase())
);
or
final var anotherSimpleSuggetion = Suggestion.simple("bonjour!", String::equalsIgnoreCase);
The default condition for functions Suggestion.simple(...) and Suggestion.withIcon(...) is (suggestionText, currentExpression) -> suggestionText.toLowerCase().startsWith(currentExpression.toLowerCase()) or Suggestion::DEFAULT_CONDITION.
If you want the suggestions to be displayed always, regardless of the entered text, you can specify condition (suggestionText, currentExpression) -> true or Suggestion::ALWAYS_SHOW_CONDITION that is used by default when initializing suggestions in functions Suggestion.alwaysShown(...) (as an alternative to the function Suggestion.simple(...)) and Suggestion.alwaysShownWithIcon(...) (as an alternative to the function Suggestion.withIcon(...)):
final var alwaysShownSuggestion = Suggestion.alwaysShown("bonjour!");
How to add new suggestions to the game?
You can add new suggestions to the game using the Injector interface that is located in io.github.aratakileo.suggestionsapi.injector.
There are two basic types of injectors: simple and asynchronous. To initialize them, the library also provides functions. The first argument of which will be a regex pattern.
To register an injector, it is necessary to pass it to function SuggestionsAPI.registerInjector(...) as a single argument.
To create a simple injector, there is a function Injector.simple(...) that returns SuggestionsInjector. Let's add two new simple suggestions (Injector.ANYTHING_WITHOUT_SPACES_PATTERN is Pattern.compile("\\S+$")):
SuggestionsAPI.registerInjector(Injector.simple(
Injector.ANYTHING_WITHOUT_SPACES_PATTERN,
(stringContainer, startOffset) -> List.of(
Suggestion.alwaysShownWithIcon("barrier", new ResourceLocation("minecraft", "textures/item/barrier.png")),
alwaysShownSuggestion
) // variables from the example above
));
The result will look like this:

If you want your suggestions not to be displayed when entering a command, you can change the code as follows:
SuggestionsAPI.registerInjector(Injector.simple(
Injector.ANYTHING_WITHOUT_SPACES_PATTERN,
(stringContainer, startOffset) -> stringContainer.getContext().isNotCommand() ? List.of(
Suggestion.alwaysShownWithIcon("barrier", new ResourceLocation("minecraft", "textures/item/barrier.png")),
alwaysShownSuggestion
) : null // variables from the example above
));
As the second argument, function Injector.simple(...) takes a lambda that describes the process of generating a list of suggestions and returns it. At the same time, the lambda has its own two arguments, the first of which contains a string with the current expression (the text in the input field that touches the cursor with the right edge and is found according to the specified pattern), and the second contains a number that is an offset between the beginning of the current expression and the original expression (the text in the input field between the nearest left space and the cursor). As an example, the addition of suggestions of numbers when trying to enter any of them is presented:
SuggestionsAPI.registerInjector(Injector.simple(
Pattern.compile(":[A-Za-z0-9]*(:)?$"),
(stringContainer, startOffset) -> Stream.of(
"67487",
"nothing",
"bedrock",
"bedrock_2"
).map(value -> Suggestion.simple(':' + value + ':')).toList()
));
or
SuggestionsAPI.registerInjector(Injector.simple(
Pattern.compile("[A-Za-z0-9]+$"),
(stringContainer, startOffset) -> Stream.of(
"Hi, " + stringContainer.getContent().substring(startOffset) + '!',
'"' + stringContainer.getContent().substring(startOffset) + '"'
).map(Suggestion::alwaysShown).toList()
));
or
SuggestionsAPI.registerInjector(Injector.simple(
Pattern.compile(":[0-9]*(:)?$"),
(stringContainer, startOffset) -> IntStream.rangeClosed(1000, 1010)
.boxed()
.map(Objects::toString)
.map(Suggestion::alwaysShown)
.toList()
));
// The suggestions of this injector will not appear if the suggestions from the injector above appear,
// because the interaction string of this injector is included in the interaction string of the injector above
SuggestionsAPI.registerInjector(Injector.simple(
Pattern.compile("[0-9]$"),
(stringContainer, startOffset) -> IntStream.rangeClosed(0, 9)
.boxed()
.map(Objects::toString)
.map(Suggestion::alwaysShown)
.toList()
));
By default, if detected string according to the regex pattern of the injector is part of another detected string according to the regex pattern of another injector, then the suggestions of the injector whose string is nested are ignored. This mechanism can be disabled for a specific injector by specifying InputRelatedInjector.NestingStatus.ALL_NESTABLE as the third (last) argument. For example:
SuggestionsAPI.registerInjector(Injector.simple(
Pattern.compile(":[0-9]*(:)?$"),
(stringContainer, startOffset) -> IntStream.rangeClosed(1000, 1010)
.boxed()
.map(Objects::toString)
.map(Suggestion::alwaysShown)
.toList(),
InputRelatedInjector.NestingStatus.ALL_NESTABLE
));
// The suggestions of this injector will appear if the suggestions from the injector above appear
SuggestionsAPI.registerInjector(Injector.simple(
Pattern.compile("[0-9]$"),
(stringContainer, startOffset) -> IntStream.rangeClosed(0, 9)
.boxed()
.map(Objects::toString)
.map(Suggestion::alwaysShown)
.toList(),
InputRelatedInjector.NestingStatus.ALL_NESTABLE
));
There are other possible values for this argument:
InputRelatedInjector.NestingStatus.NOT_NESTABLE - uses by default
InputRelatedInjector.NestingStatus.ONLY_API_NESTABLE - allow nesting only for the suggestions added using the Suggestions API
InputRelatedInjector.NestingStatus.ONLY_NON_API_NESTABLE - allow nesting only for the suggestions added outside the Suggestions API [deprecated]
If you need the suggestions to appear synchronously, you can use the function Injector.async(...) to initialize the asynchronous injector. The injector initialized with this function provides a mechanism for canceling the current asynchronous process if a request for a new one has been received, and the current process has not had time to complete by this time. This function is similar to the previous one, but this time the second argument, namely lambda, returns a lambda without arguments, which will be launched as an asynchronous process, and has three arguments, the last of which is a lambda that accepts a list of new suggestions and should be used inside the lambda of an asynchronous process. For example:
SuggestionsAPI.registerInjector(Injector.async(
/* insert your pattern here */,
(stringContainer, startOffset) -> {
/* insert your async processing code here */
return /* insert list of suggestion here */;
}
));
Function Injector.async(...) returns AsyncInjector. Just as in the case of the previous function, a third argument can be specified in this function.
Can I replace Suggestions with new instances? [deprecated]
The Suggestions API prohibits implicit replacement of suggestions, but it allows you to replace suggestions that were not added using it (that is, suggestions that were added by Minecraft or other mods that do not use the Suggestions API). If the suggestion you need has not yet been replaced by another mod, you can replace the suggestion using the ReplacementInjector that is located in io.github.aratakileo.suggestionsapi.injector. For example:
// To check this, start entering the command `give @s minecraft:barrier` in the chat or in the command block
SuggestionsAPI.registerInjector(Injector.replacement(
nonApiSuggestion -> nonApiSuggestion.equals("minecraft:barrier") ? Suggestion.withIcon(
nonApiSuggestion,
new ResourceLocation("minecraft", "textures/item/barrier.png")
) : null
));
The result will look like this:

评论 0
登录后参与评分
还没有评论,来抢沙发吧