针对文本输入的自动补全建议
使用集合让一切井井有条
根据您的偏好保存内容并对其进行分类。
借助文本输入微件,您的插件可以读取用户提供的文本并对其做出响应。您可以配置这些微件,以便为用户提供输入文本的自动建议。
提供的建议可以来自您提供的静态字符串列表。或者,您也可以根据上下文(例如用户已输入到微件中的文本)构建建议。
配置建议
如需为文本输入配置建议,您只需执行以下操作:
- 您可以通过以下方式创建建议列表:
- 创建静态列表,以及/或者
- 使用一个回调函数定义操作,该回调函数会根据上下文动态构建该列表。
- 将建议列表和/或操作附加到文本输入 widget。
如果您同时提供静态建议列表和操作,应用界面会使用静态列表,直到用户开始输入字符,此时系统会使用回调函数并忽略静态列表。
静态建议
如需提供静态建议列表,您只需执行以下操作:
- 创建一个
Suggestions
对象。
- 使用
addSuggestion()
或 addSuggestions()
将每条静态建议添加到其中。
- 使用
TextInput.setSuggestions()
将 Suggestions
对象附加到 widget。
界面会按添加的顺序显示静态建议。界面还会在用户向 widget 中输入字符时自动执行不区分大小写的前缀匹配并过滤建议列表。
建议操作
如果您不使用静态建议列表,则必须定义一个操作来动态构建建议。您可按以下步骤实现这一目的:
- 创建一个
Action
对象,并将其与您定义的回调函数相关联。
- 调用 widget 的
TextInput.setSuggestionsAction()
函数,为其提供 Action
对象。
- 实现回调函数以构建建议列表,并返回构建的
SuggestionsResponse
对象。
每当用户在文本输入框中输入字符时,界面都会调用回调函数,但仅在用户停止输入一段时间后才会调用。回调函数会接收一个事件对象,其中包含有关打开的卡片的 widget 的信息。如需了解详情,请参阅Action 事件对象。
回调函数必须返回一个有效的 SuggestionsResponse
对象,其中包含要显示的建议列表。界面会按照添加的顺序显示建议。与静态列表不同,界面不会根据用户输入对回调建议进行任何自动过滤。如果您想进行此类过滤,则必须从事件对象读取文本输入值,并在构建列表时过滤建议。
示例
以下 Google Workspace 插件代码段展示了如何在两个不同的文本输入 widget 上配置建议,第一个使用静态列表,第二个使用回调函数:
// Create an input with a static suggestion list.
var textInput1 = CardService.newTextInput()
.setFieldName('colorInput')
.setTitle('Color choice')
.setSuggestions(CardService.newSuggestions()
.addSuggestion('Red')
.addSuggestion('Yellow')
.addSuggestions(['Blue', 'Black', 'Green']));
// Create an input with a dynamic suggestion list.
var action = CardService.newAction()
.setFunctionName('refreshSuggestions');
var textInput2 = CardService.newTextInput()
.setFieldName('emailInput')
.setTitle('Email')
.setSuggestionsAction(action);
// ...
/**
* Build and return a suggestion response. In this case, the suggestions
* are a list of emails taken from the To: and CC: lists of the open
* message in Gmail, filtered by the text that the user has already
* entered. This method assumes the
* add-on extends Gmail; the add-on only calls this method for cards
* displayed when the user has entered a message context.
*
* @param {Object} e the event object containing data associated with
* this text input widget.
* @return {SuggestionsResponse}
*/
function refreshSuggestions(e) {
// Activate temporary Gmail scopes, in this case so that the
// open message metadata can be read.
var accessToken = e.gmail.accessToken;
GmailApp.setCurrentMessageAccessToken(accessToken);
var userInput = e && e.formInput['emailInput'].toLowerCase();
var messageId = e.gmail.messageId;
var message = GmailApp.getMessageById(messageId);
// Combine the comma-separated returned by these methods.
var addresses = message.getTo() + ',' + message.getCc();
// Filter the address list to those containing the text the user
// has already entered.
var suggestionList = [];
addresses.split(',').forEach(function(email) {
if (email.toLowerCase().indexOf(userInput) !== -1) {
suggestionList.push(email);
}
});
suggestionList.sort();
return CardService.newSuggestionsResponseBuilder()
.setSuggestions(CardService.newSuggestions()
.addSuggestions(suggestionList))
.build(); // Don't forget to build the response!
}
建议和 OnChangeAction()
文本输入微件可以定义一个 setOnChangeAction()
处理脚本函数,该函数会在微件失去焦点时执行。如果为同一文本输入启用了此处理脚本和建议,则以下规则定义了文本输入互动行为:
- 在用户选择某条建议后,系统会执行
setOnChangeAction()
处理程序。
- 如果用户按 Enter 键(或以其他方式使文本输入失去焦点),而未修改所选建议,
setOnChangeAction()
不会再次触发。
- 如果用户选择某条建议后对其进行修改,使其不再与列表中的任何建议匹配,
setOnChangeAction()
就会再次触发。
- 如果用户未选择任何建议,则当文本输入框失去焦点时,
setOnChangeAction()
会触发。
如未另行说明,那么本页面中的内容已根据知识共享署名 4.0 许可获得了许可,并且代码示例已根据 Apache 2.0 许可获得了许可。有关详情,请参阅 Google 开发者网站政策。Java 是 Oracle 和/或其关联公司的注册商标。
最后更新时间 (UTC):2024-12-22。
[null,null,["最后更新时间 (UTC):2024-12-22。"],[[["\u003cp\u003eThe Text Input widget enables add-ons to process user-provided text and offer suggestions for input.\u003c/p\u003e\n"],["\u003cp\u003eSuggestions can be statically defined or dynamically generated using an action with a callback function.\u003c/p\u003e\n"],["\u003cp\u003eWhen both static and dynamic suggestions are provided, the static list is used initially, switching to the dynamic list as the user types.\u003c/p\u003e\n"],["\u003cp\u003eDynamic suggestions are built by a callback function triggered by user input and require a SuggestionsResponse object.\u003c/p\u003e\n"],["\u003cp\u003eCombining suggestions with onChangeAction() results in specific interaction behaviors depending on user actions and suggestion selection.\u003c/p\u003e\n"]]],["Text input widgets can be configured with suggestions, either static or dynamic. Static suggestions are created with a `Suggestions` object, populated with `addSuggestion()` or `addSuggestions()`, and attached to the widget using `setSuggestions()`. Dynamic suggestions utilize an `Action` object linked to a callback function via `setSuggestionsAction()`. This callback builds a `SuggestionsResponse` object, and filtering must be implemented manually. A text input can also use a `setOnChangeAction()`. If both the suggestion and `setOnChangeAction()` are enabled, the `setOnChangeAction()` will be executed after a suggestion is selected or if the user modifies the suggestion.\n"],null,["# Autocomplete suggestions for text inputs\n\nThe [Text Input](/apps-script/reference/card-service/text-input) widget\nlets your add-on read and react to text that users provide. You can\nconfigure these widgets to provide users automatic suggestions for\ninput text.\n\nThe suggestions provided can come from a static list of strings you provide.\nAlternatively, you can build the suggestions from context, such as the text\nthe user has already typed into the widget.\n\nConfiguring suggestions\n-----------------------\n\nConfiguring suggestions for a text input only requires that you do the\nfollowing:\n\n- Create a list of suggestions by:\n - Creating a static list, and/or\n - Defining an [action](/workspace/add-ons/concepts/actions) with a callback function that builds that list dynamically from context.\n- Attach the suggestions list and/or action to the text input widget.\n\nIf you provide both a static list of suggestions and an action, the\napplication UI uses the static list until the user starts entering characters,\nwhereupon the callback function is used and the static list is ignored.\n\n### Static suggestions\n\nTo offer a static list of suggestions, you only need to do the following:\n\n1. Create a [`Suggestions`](/apps-script/reference/card-service/suggestions) object.\n2. Add each static suggestion to it using [`addSuggestion()`](/apps-script/reference/card-service/suggestions#addSuggestion(String)) or [`addSuggestions()`](/apps-script/reference/card-service/suggestions#addsuggestionssuggestions).\n3. Attach the [`Suggestions`](/apps-script/reference/card-service/suggestions) object to the widget using [`TextInput.setSuggestions()`](/apps-script/reference/card-service/text-input#setsuggestionssuggestions).\n\nThe UI displays static suggestions in the order in which they were added. The UI\nalso automatically performs case-insensitive prefix matching and filters the\nsuggestion list as the user types characters into the widget.\n\n### Suggestion actions\n\nIf you aren't using a static suggestion list, you must define an action\nto build your suggestions dynamically. You can do this by following these steps:\n\n1. Create an [`Action`](/apps-script/reference/card-service/action) object and associate it with an [callback function](/workspace/add-ons/concepts/actions#callback_functions) you define.\n2. Call the widget's [`TextInput.setSuggestionsAction()`](/apps-script/reference/card-service/text-input#setsuggestionsactionsuggestionsaction) function, providing it the [`Action`](/apps-script/reference/card-service/action) object.\n3. Implement the callback function to build the suggestion list and return a built [`SuggestionsResponse`](/apps-script/reference/card-service/suggestions-response) object.\n\nThe UI calls the callback function whenever the user types a character into the\ntext input, but only after the user has stopped typing for a moment. The\ncallback function receives an *event object* containing information about the\nopen card's widgets. See\n[Action event objects](/workspace/add-ons/concepts/actions#action_event_objects)\nfor details.\n\nThe callback function must return a valid\n[`SuggestionsResponse`](/apps-script/reference/card-service/suggestions-response)\nobject containing the list of suggestions to display. The UI displays\nsuggestions in the order that they are added. Unlike static lists, the UI does\nnot conduct any automatic filtering of callback suggestions based on the user\ninput. If you want to have such filtering, you must read the text input value\nfrom the event object and filter your suggestions as you construct the list.\n\n### Example\n\nThe following Google Workspace add-on code snippet\nshows how to configure suggestions\non two different text input widgets, the first with a static list and the\nsecond using a callback function: \n\n // Create an input with a static suggestion list.\n var textInput1 = CardService.newTextInput()\n .setFieldName('colorInput')\n .setTitle('Color choice')\n .setSuggestions(CardService.newSuggestions()\n .addSuggestion('Red')\n .addSuggestion('Yellow')\n .addSuggestions(['Blue', 'Black', 'Green']));\n\n // Create an input with a dynamic suggestion list.\n var action = CardService.newAction()\n .setFunctionName('refreshSuggestions');\n var textInput2 = CardService.newTextInput()\n .setFieldName('emailInput')\n .setTitle('Email')\n .setSuggestionsAction(action);\n\n // ...\n\n /**\n * Build and return a suggestion response. In this case, the suggestions\n * are a list of emails taken from the To: and CC: lists of the open\n * message in Gmail, filtered by the text that the user has already\n * entered. This method assumes the Google Workspace\n * add-on extends Gmail; the add-on only calls this method for cards\n * displayed when the user has entered a message context.\n *\n * @param {Object} e the event object containing data associated with\n * this text input widget.\n * @return {SuggestionsResponse}\n */\n function refreshSuggestions(e) {\n // Activate temporary Gmail scopes, in this case so that the\n // open message metadata can be read.\n var accessToken = e.gmail.accessToken;\n GmailApp.setCurrentMessageAccessToken(accessToken);\n\n var userInput = e && e.formInput['emailInput'].toLowerCase();\n var messageId = e.gmail.messageId;\n var message = GmailApp.getMessageById(messageId);\n\n // Combine the comma-separated returned by these methods.\n var addresses = message.getTo() + ',' + message.getCc();\n\n // Filter the address list to those containing the text the user\n // has already entered.\n var suggestionList = [];\n addresses.split(',').forEach(function(email) {\n if (email.toLowerCase().indexOf(userInput) !== -1) {\n suggestionList.push(email);\n }\n });\n suggestionList.sort();\n\n return CardService.newSuggestionsResponseBuilder()\n .setSuggestions(CardService.newSuggestions()\n .addSuggestions(suggestionList))\n .build(); // Don't forget to build the response!\n }\n\nSuggestions and `OnChangeAction()`\n----------------------------------\n\nText input widgets can have a\n[`setOnChangeAction()`](/workspace/add-ons/concepts/actions#setOnChangeAction)\nhandler function defined that executes whenever the widget loses focus.\nIf this handler and suggestions are both enabled for the same text input, the\nfollowing rules define the text input interaction behavior:\n\n1. The `setOnChangeAction()` handler executes after a suggestion is selected.\n2. If the user presses Enter (or otherwise makes the text input lose focus) without modifying the selected suggestion, `setOnChangeAction()` doesn't trigger again.\n3. `setOnChangeAction()` does trigger again if the user, after selecting a suggestion, edits it so that it no longer matches any of the suggestions in the list.\n4. If the user doesn't select a suggestion, `setOnChangeAction()` triggers when the text input loses focus."]]