テキスト入力に対するオートコンプリートの候補
コレクションでコンテンツを整理
必要に応じて、コンテンツの保存と分類を行います。
テキスト入力 ウィジェットを使用すると、ユーザーが入力したテキストをアドオンが読み取って処理できます。これらのウィジェットを構成して、入力テキストの候補を自動的にユーザーに提示できます。
提供される候補は、指定した文字列の静的リストから取得できます。または、ユーザーがウィジェットに入力したテキストなど、コンテキストから候補を作成することもできます。
候補の設定
テキスト入力の候補を構成するには、次の操作のみが必要です。
- 次の方法で候補のリストを作成します。
- 静的リストの作成、
- コンテキストからそのリストを動的に構築するコールバック関数を使用してアクションを定義します。
- 候補リストやアクションをテキスト入力ウィジェットに接続します。
候補の静的リストとアクションの両方を指定した場合、ユーザーが文字の入力を開始するまで、アプリケーション UI は静的リストを使用します。入力が開始されると、コールバック関数が使用され、静的リストは無視されます。
静的候補
候補の静的リストを提供する手順は次のとおりです。
Suggestions
オブジェクトを作成します。
addSuggestion()
または addSuggestions()
を使用して、各静的候補を追加します。
TextInput.setSuggestions()
を使用して、Suggestions
オブジェクトをウィジェットにアタッチします。
UI には、追加された順序で静的候補が表示されます。また、ユーザーがウィジェットに文字を入力すると、UI は自動的に大文字と小文字を区別しない接頭辞照合を行い、候補リストをフィルタします。
候補のアクション
静的な候補リストを使用していない場合は、候補を動的に作成するアクションを定義する必要があります。手順は次のとおりです。
Action
オブジェクトを作成し、定義したコールバック関数に関連付けます。
- ウィジェットの
TextInput.setSuggestionsAction()
関数を呼び出し、Action
オブジェクトを渡します。
- コールバック関数を実装して候補リストを作成し、作成した
SuggestionsResponse
オブジェクトを返します。
UI は、ユーザーがテキスト入力に文字を入力するたびにコールバック関数を呼び出しますが、ユーザーが入力を停止してから呼び出します。コールバック関数は、開いているカードのウィジェットに関する情報を含むイベント オブジェクトを受け取ります。詳しくは、アクション イベント オブジェクトをご覧ください。
コールバック関数は、表示する候補のリストを含む有効な SuggestionsResponse
オブジェクトを返す必要があります。UI には、追加された順序で候補が表示されます。静的リストとは異なり、UI はユーザー入力に基づいてコールバック候補の自動フィルタリングを行いません。このようなフィルタリングを行うには、イベント オブジェクトからテキスト入力値を読み取り、リストの作成時に候補をフィルタする必要があります。
例
次の Google Workspace アドオンのコード スニペットは、2 つの異なるテキスト入力ウィジェットで候補を構成する方法を示しています。1 つは静的リストを使用、もう 1 つはコールバック関数を使用しています。
// 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 Developers サイトのポリシーをご覧ください。Java は Oracle および関連会社の登録商標です。
最終更新日 2024-12-22 UTC。
[null,null,["最終更新日 2024-12-22 UTC。"],[[["\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."]]