텍스트 입력 자동 완성 추천
컬렉션을 사용해 정리하기
내 환경설정을 기준으로 콘텐츠를 저장하고 분류하세요.
텍스트 입력 위젯을 사용하면 부가기능에서 사용자가 제공한 텍스트를 읽고 이에 반응할 수 있습니다. 이러한 위젯을 구성하여 사용자에게 입력 텍스트를 자동으로 추천할 수 있습니다.
제공된 추천은 개발자가 제공한 정적 문자열 목록에서 가져올 수 있습니다.
또는 사용자가 이미 위젯에 입력한 텍스트와 같은 컨텍스트에서 추천을 빌드할 수 있습니다.
추천 구성
텍스트 입력에 대한 추천을 구성하려면 다음 작업만 하면 됩니다.
- 다음과 같이 추천 목록을 만듭니다.
- 정적 목록 만들기
- 컨텍스트에서 동적으로 목록을 빌드하는 콜백 함수로 작업을 정의합니다.
- 추천 목록 또는 작업을 텍스트 입력 위젯에 연결합니다.
추천의 정적 목록과 작업을 모두 제공하는 경우 애플리케이션 UI는 사용자가 문자 입력을 시작할 때까지 정적 목록을 사용하고, 그러면 콜백 함수가 사용되며 정적 목록은 무시됩니다.
정적 추천
정적 추천 목록을 제공하려면 다음 작업만 하면 됩니다.
Suggestions
객체를 만듭니다.
addSuggestion()
또는 addSuggestions()
를 사용하여 각 정적 추천을 추가합니다.
TextInput.setSuggestions()
를 사용하여 Suggestions
객체를 위젯에 연결합니다.
UI에는 정적 추천이 추가된 순서대로 표시됩니다. 또한 UI는 대소문자를 구분하지 않는 접두사 일치를 자동으로 실행하고 사용자가 위젯에 문자를 입력할 때 추천 목록을 필터링합니다.
추천 작업
정적 추천 목록을 사용하지 않는 경우 추천을 동적으로 빌드하는 작업을 정의해야 합니다. 다음 단계에 따라 무료 사용 기간을 연장할 수 있습니다.
Action
객체를 만들고 정의한 콜백 함수와 연결합니다.
- 위젯의
TextInput.setSuggestionsAction()
함수를 호출하여 Action
객체를 제공합니다.
- 콜백 함수를 구현하여 추천 목록을 빌드하고 빌드된
SuggestionsResponse
객체를 반환합니다.
UI는 사용자가 텍스트 입력란에 문자를 입력할 때마다 콜백 함수를 호출하지만 사용자가 잠시 입력을 중지한 후에만 호출합니다. 콜백 함수는 열린 카드의 위젯에 관한 정보가 포함된 이벤트 객체를 수신합니다. 자세한 내용은 작업 이벤트 객체를 참고하세요.
콜백 함수는 표시할 추천 목록이 포함된 유효한 SuggestionsResponse
객체를 반환해야 합니다. UI에는 추천이 추가된 순서대로 표시됩니다. 정적 목록과 달리 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()
이 트리거됩니다.
달리 명시되지 않는 한 이 페이지의 콘텐츠에는 Creative Commons Attribution 4.0 라이선스에 따라 라이선스가 부여되며, 코드 샘플에는 Apache 2.0 라이선스에 따라 라이선스가 부여됩니다. 자세한 내용은 Google Developers 사이트 정책을 참조하세요. 자바는 Oracle 및/또는 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."]]