下列 Google Workspace 外掛程式碼片段說明如何在兩個不同的文字輸入小工具上設定建議,第一個小工具使用靜態清單,第二個小工具則使用回呼函式:
//Createaninputwithastaticsuggestionlist.vartextInput1=CardService.newTextInput().setFieldName('colorInput').setTitle('Color choice').setSuggestions(CardService.newSuggestions().addSuggestion('Red').addSuggestion('Yellow').addSuggestions(['Blue','Black','Green']));//Createaninputwithadynamicsuggestionlist.varaction=CardService.newAction().setFunctionName('refreshSuggestions');vartextInput2=CardService.newTextInput().setFieldName('emailInput').setTitle('Email').setSuggestionsAction(action);//.../***Buildandreturnasuggestionresponse.Inthiscase,thesuggestions*arealistofemailstakenfromtheTo:andCC:listsoftheopen*messageinGmail,filteredbythetextthattheuserhasalready*entered.Thismethodassumesthe*add-onextendsGmail;theadd-ononlycallsthismethodforcards*displayedwhentheuserhasenteredamessagecontext.**@param{Object}etheeventobjectcontainingdataassociatedwith*thistextinputwidget.*@return{SuggestionsResponse}*/functionrefreshSuggestions(e){//ActivatetemporaryGmailscopes,inthiscasesothatthe//openmessagemetadatacanberead.varaccessToken=e.gmail.accessToken;GmailApp.setCurrentMessageAccessToken(accessToken);varuserInput=e && e.formInput['emailInput'].toLowerCase();varmessageId=e.gmail.messageId;varmessage=GmailApp.getMessageById(messageId);//Combinethecomma-separatedreturnedbythesemethods.varaddresses=message.getTo()+','+message.getCc();//Filtertheaddresslisttothosecontainingthetexttheuser//hasalreadyentered.varsuggestionList=[];addresses.split(',').forEach(function(email){if(email.toLowerCase().indexOf(userInput)!==-1){suggestionList.push(email);}});suggestionList.sort();returnCardService.newSuggestionsResponseBuilder().setSuggestions(CardService.newSuggestions().addSuggestions(suggestionList)).build();//Don't forget to build the response!}
[[["容易理解","easyToUnderstand","thumb-up"],["確實解決了我的問題","solvedMyProblem","thumb-up"],["其他","otherUp","thumb-up"]],[["缺少我需要的資訊","missingTheInformationINeed","thumb-down"],["過於複雜/步驟過多","tooComplicatedTooManySteps","thumb-down"],["過時","outOfDate","thumb-down"],["翻譯問題","translationIssue","thumb-down"],["示例/程式碼問題","samplesCodeIssue","thumb-down"],["其他","otherDown","thumb-down"]],["上次更新時間: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."]]