自動完成文字輸入建議
透過集合功能整理內容
你可以依據偏好儲存及分類內容。
文字輸入小工具可讓外掛程式讀取使用者提供的文字並做出回應。您可以設定這些小工具,為使用者提供輸入文字的自動建議。
系統提供的建議可來自您提供的靜態字串清單。或者,您也可以根據內容建立建議,例如使用者已輸入小工具的文字。
設定建議
如要設定文字輸入建議,您只需執行下列操作:
- 建立建議清單的方法:
- 建立靜態清單,以及/或者
- 使用回呼函式定義動作,該函式會根據內容動態建構該清單。
- 將建議清單和/或動作附加至文字輸入小工具。
如果您同時提供靜態建議清單和動作,應用程式 UI 會使用靜態清單,直到使用者開始輸入字元為止,屆時系統會使用回呼函式,並忽略靜態清單。
靜態建議
如要提供靜態建議清單,您只需執行下列操作:
- 建立
Suggestions
物件。
- 使用
addSuggestion()
或 addSuggestions()
新增每個靜態建議。
- 使用
TextInput.setSuggestions()
將 Suggestions
物件附加至小工具。
使用者介面會按照新增的順序顯示靜態建議。UI 也會自動執行不區分大小寫的前置字串比對,並在使用者在小工具中輸入字元時篩選建議清單。
建議動作
如果您沒有使用靜態建議清單,就必須定義動作,才能動態建立建議。只要按照以下步驟操作即可:
- 建立
Action
物件,並將其與您定義的回呼函式建立關聯。
- 呼叫小工具的
TextInput.setSuggestionsAction()
函式,並提供 Action
物件。
- 實作回呼函式,以建構建議清單並傳回已建構的
SuggestionsResponse
物件。
每當使用者在文字輸入內容中輸入字元,UI 就會呼叫回呼函式,但只有在使用者停止輸入一段時間後才會呼叫。回呼函式會接收含有開放資訊卡小工具相關資訊的事件物件。詳情請參閱「動作事件物件」。
回呼函式必須傳回有效的 SuggestionsResponse
物件,其中包含要顯示的建議清單。使用者介面會按照建議項目加入的順序顯示。與靜態清單不同,UI 不會根據使用者輸入內容,自動篩選回撥建議。如要進行這類篩選,您必須從事件物件讀取文字輸入值,並在建構清單時篩選建議。
範例
下列 Google Workspace 外掛程式碼片段說明如何在兩個不同的文字輸入小工具上設定建議,第一個小工具使用靜態清單,第二個小工具則使用回呼函式:
// 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()
會在文字輸入內容失去焦點時觸發。
除非另有註明,否則本頁面中的內容是採用創用 CC 姓名標示 4.0 授權,程式碼範例則為阿帕契 2.0 授權。詳情請參閱《Google Developers 網站政策》。Java 是 Oracle 和/或其關聯企業的註冊商標。
上次更新時間:2024-12-22 (世界標準時間)。
[null,null,["上次更新時間: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."]]