Cards v2

Карта

Карточный интерфейс, отображаемый в сообщении Google Chat или в дополнении Google Workspace.

Карточки поддерживают заданную структуру, интерактивные элементы пользовательского интерфейса, такие как кнопки, и мультимедийный контент, например изображения. Используйте карточки для представления подробной информации, сбора информации от пользователей и направления пользователей к следующему шагу.

Создавайте и просматривайте карточки с помощью конструктора карточек.

Откройте конструктор карточек.

To learn how to build cards, see the following documentation:

Примечание: В каждую карточку можно добавить до 100 виджетов. Если количество виджетов в разделе превысит 100, весь этот раздел и все последующие разделы будут проигнорированы. Это ограничение применяется как к сообщениям и диалогам в карточках в приложениях Google Chat, так и к карточкам в надстройках Google Workspace.

Пример: Сообщение-открытка для приложения Google Chat

Пример контактной карты

Для создания примера сообщения в Google Chat используйте следующий JSON:

{
  "cardsV2": [
    {
      "cardId": "unique-card-id",
      "card": {
        "header": {
           "title": "Sasha",
           "subtitle": "Software Engineer",
           "imageUrl":
           "https://developers.google.com/workspace/chat/images/quickstart-app-avatar.png",
           "imageType": "CIRCLE",
           "imageAltText": "Avatar for Sasha"
         },
         "sections": [
           {
             "header": "Contact Info",
             "collapsible": true,
             "uncollapsibleWidgetsCount": 1,
             "widgets": [
               {
                 "decoratedText": {
                   "startIcon": {
                     "knownIcon": "EMAIL"
                   },
                   "text": "sasha@example.com"
                 }
               },
               {
                 "decoratedText": {
                   "startIcon": {
                     "knownIcon": "PERSON"
                   },
                   "text": "<font color=\"#80e27e\">Online</font>"
                 }
               },
               {
                 "decoratedText": {
                   "startIcon": {
                     "knownIcon": "PHONE"
                   },
                   "text": "+1 (555) 555-1234"
                 }
               },
               {
                 "buttonList": {
                   "buttons": [
                     {
                       "text": "Share",
                       "onClick": {
                        "openLink": {
                           "url": "https://example.com/share"
                         }
                       }
                     },
                     {
                       "text": "Edit",
                       "onClick": {
                         "action": {
                           "function": "goToView",
                           "parameters": [
                             {
                               "key": "viewType",
                               "value": "EDIT"
                             }
                           ]
                         }
                       }
                     }
                   ]
                 }
               }
             ]
           }
         ]
       }
    }
  ]
}
JSON-представление
{
  "header": {
    object (CardHeader)
  },
  "sections": [
    {
      object (Section)
    }
  ],
  "sectionDividerStyle": enum (DividerStyle),
  "cardActions": [
    {
      object (CardAction)
    }
  ],
  "name": string,
  "fixedFooter": {
    object (CardFixedFooter)
  },
  "displayStyle": enum (DisplayStyle),
  "peekCardHeader": {
    object (CardHeader)
  },
  "expressionData": [
    {
      object (ExpressionData)
    }
  ]
}
Поля
header

object ( CardHeader )

Заголовок карточки. Заголовок обычно содержит основное изображение и заголовок. Заголовки всегда располагаются в верхней части карточки.

sections[]

object ( Section )

Содержит набор виджетов. Каждый раздел имеет свой собственный, необязательный заголовок. Разделы визуально разделены разделительной линией. Пример использования в приложениях Google Chat см. в разделе «Определение раздела карточки» .

sectionDividerStyle

enum ( DividerStyle )

Стиль разделителя между заголовком, разделами и нижним колонтитулом.

cardActions[]

object ( CardAction )

Действия карточки. Действия добавляются в меню панели инструментов карточки.

Доступно для дополнений Google Workspace и недоступно для приложений Google Chat.

Например, следующий JSON-код формирует меню действий в виде карточки с опциями Settings и Send Feedback :

"cardActions": [
  {
    "actionLabel": "Settings",
    "onClick": {
      "action": {
        "functionName": "goToView",
        "parameters": [
          {
            "key": "viewType",
            "value": "SETTING"
         }
        ],
        "loadIndicator": "LoadIndicator.SPINNER"
      }
    }
  },
  {
    "actionLabel": "Send Feedback",
    "onClick": {
      "openLink": {
        "url": "https://example.com/feedback"
      }
    }
  }
]
name

string

Name of the card. Used as a card identifier in card navigation.

Available for Google Workspace add-ons and unavailable for Google Chat apps.

displayStyle

enum ( DisplayStyle )

In Google Workspace add-ons, sets the display properties of the peekCardHeader .

Available for Google Workspace add-ons and unavailable for Google Chat apps.

peekCardHeader

object ( CardHeader )

When displaying contextual content, the peek card header acts as a placeholder so that the user can navigate forward between the homepage cards and the contextual cards.

Available for Google Workspace add-ons and unavailable for Google Chat apps.

expressionData[]

object ( ExpressionData )

Данные выражения для карты.

Доступно для дополнений Google Workspace, расширяющих функциональность Google Workspace Studio. Недоступно для приложений Google Chat.

CardHeader

Represents a card header. For an example in Google Chat apps, see Add a header .

Available for Google Chat apps and Google Workspace add-ons.

JSON-представление
{
  "title": string,
  "subtitle": string,
  "imageType": enum (ImageType),
  "imageUrl": string,
  "imageAltText": string
}
Поля
title

string

Обязательно. Заголовок верхней части карточки. Высота заголовка фиксирована: если указаны и заголовок, и подзаголовок, каждый занимает одну строку. Если указан только заголовок, он занимает обе строки.

subtitle

string

The subtitle of the card header. If specified, appears on its own line below the title .

imageType

enum ( ImageType )

Форма, используемая для обрезки изображения.

Available for Google Chat apps and Google Workspace add-ons.

imageUrl

string

HTTPS-адрес изображения в заголовке карточки.

imageAltText

string

The alternative text of this image that's used for accessibility.

Тип изображения

Форма, используемая для обрезки изображения.

Доступно для приложений Google Chat и дополнений Google Workspace.

Перечисления
SQUARE Default value. Applies a square mask to the image. For example, a 4x3 image becomes 3x3.
CIRCLE Applies a circular mask to the image. For example, a 4x3 image becomes a circle with a diameter of 3.

Раздел

A section contains a collection of widgets that are rendered vertically in the order that they're specified.

Available for Google Chat apps and Google Workspace add-ons.

JSON-представление
{
  "header": string,
  "widgets": [
    {
      object (Widget)
    }
  ],
  "collapsible": boolean,
  "uncollapsibleWidgetsCount": integer,
  "id": string,
  "collapseControl": {
    object (CollapseControl)
  }
}
Поля
header

string

Текст, отображаемый в верхней части раздела. Поддерживается простой HTML-форматированный текст. Для получения дополнительной информации о форматировании текста см. разделы «Форматирование текста в приложениях Google Chat» и «Форматирование текста в надстройках Google Workspace».

widgets[]

object ( Widget )

Все виджеты в разделе. Должен содержать как минимум один виджет.

collapsible

boolean

Указывает, можно ли свернуть этот раздел.

Collapsible sections hide some or all widgets, but users can expand the section to reveal the hidden widgets by clicking Show more . Users can hide the widgets again by clicking Show less .

To determine which widgets are hidden, specify uncollapsibleWidgetsCount .

uncollapsibleWidgetsCount

integer

The number of uncollapsible widgets which remain visible even when a section is collapsed.

Например, если раздел содержит пять виджетов, а параметр uncollapsibleWidgetsCount установлен на 2 , то по умолчанию всегда отображаются первые два виджета, а последние три свернуты. Параметр uncollapsibleWidgetsCount учитывается только тогда, когда collapsible имеет true .

id

string

A unique ID assigned to the section that's used to identify the section to be mutated. The ID has a character limit of 64 characters and should be in the format of [a-zA-Z0-9-]+ .

Доступно для дополнений Google Workspace, расширяющих функциональность Google Workspace Studio. Недоступно для приложений Google Chat.

collapseControl

object ( CollapseControl )

Optional. Define the expand and collapse button of the section. This button will be shown only if the section is collapsible. If this field isn't set, the default button is used.

Виджет

Каждая карточка состоит из виджетов.

A widget is a composite object that can represent one of text, images, buttons, and other object types.

JSON-представление
{
  "horizontalAlignment": enum (HorizontalAlignment),
  "id": string,
  "visibility": enum (Visibility),
  "eventActions": [
    {
      object (EventAction)
    }
  ],

  "textParagraph": {
    object (TextParagraph)
  },
  "image": {
    object (Image)
  },
  "decoratedText": {
    object (DecoratedText)
  },
  "buttonList": {
    object (ButtonList)
  },
  "textInput": {
    object (TextInput)
  },
  "selectionInput": {
    object (SelectionInput)
  },
  "dateTimePicker": {
    object (DateTimePicker)
  },
  "divider": {
    object (Divider)
  },
  "grid": {
    object (Grid)
  },
  "columns": {
    object (Columns)
  },
  "carousel": {
    object (Carousel)
  },
  "chipList": {
    object (ChipList)
  }
}
Поля
horizontalAlignment

enum ( HorizontalAlignment )

Specifies whether widgets align to the left, right, or center of a column.

id

string

A unique ID assigned to the widget that's used to identify the widget to be mutated. The ID has a character limit of 64 characters and should be in the format of [a-zA-Z0-9-]+ .

Доступно для дополнений Google Workspace, расширяющих функциональность Google Workspace Studio. Недоступно для приложений Google Chat.

visibility

enum ( Visibility )

Specifies whether the widget is visible or hidden. The default value is VISIBLE .

Available for Google Workspace add-ons that extend Google Workspace Studio. Unavailable for Google Chat apps.

eventActions[]

object ( EventAction )

Specifies the event actions that can be performed on the widget.

Available for Google Workspace add-ons that extend Google Workspace Studio. Unavailable for Google Chat apps.

Виджет может содержать только один из следующих элементов. Для отображения большего количества элементов можно использовать несколько полей виджета. Ниже приведен список взаимоисключающих полей. В ответе будет установлено не более одного из полей:
textParagraph

object ( TextParagraph )

Отображает абзац текста. Поддерживает простой HTML-форматированный текст. Для получения дополнительной информации о форматировании текста см. разделы «Форматирование текста в приложениях Google Chat» и «Форматирование текста в надстройках Google Workspace».

Например, следующий JSON-код создает текст, выделенный жирным шрифтом:

"textParagraph": {
  "text": "  <b>bold text</b>"
}
image

object ( Image )

Отображает изображение.

Например, следующий JSON-код создает изображение с альтернативным текстом:

"image": {
  "imageUrl":
  "https://developers.google.com/workspace/chat/images/quickstart-app-avatar.png",
  "altText": "Chat app avatar"
}
decoratedText

object ( DecoratedText )

Отображает текстовый элемент с декоративным оформлением.

For example, the following JSON creates a decorated text widget showing email address:

"decoratedText": {
  "icon": {
    "knownIcon": "EMAIL"
  },
  "topLabel": "Email Address",
  "text": "sasha@example.com",
  "bottomLabel": "This is a new Email address!",
  "switchControl": {
    "name": "has_send_welcome_email_to_sasha",
    "selected": false,
    "controlType": "CHECKBOX"
  }
}
buttonList

object ( ButtonList )

Список кнопок.

For example, the following JSON creates two buttons. The first is a blue text button and the second is an image button that opens a link:

"buttonList": {
  "buttons": [
    {
      "text": "Edit",
      "color": {
        "red": 0,
        "green": 0,
        "blue": 1,
      },
      "disabled": true,
    },
    {
      "icon": {
        "knownIcon": "INVITE",
        "altText": "check calendar"
      },
      "onClick": {
        "openLink": {
          "url": "https://example.com/calendar"
        }
      }
    }
  ]
}
textInput

object ( TextInput )

Отображает текстовое поле, в которое пользователи могут вводить текст.

For example, the following JSON creates a text input for an email address:

"textInput": {
  "name": "mailing_address",
  "label": "Mailing Address"
}

As another example, the following JSON creates a text input for a programming language with static suggestions:

"textInput": {
  "name": "preferred_programing_language",
  "label": "Preferred Language",
  "initialSuggestions": {
    "items": [
      {
        "text": "C++"
      },
      {
        "text": "Java"
      },
      {
        "text": "JavaScript"
      },
      {
        "text": "Python"
      }
    ]
  }
}
selectionInput

object ( SelectionInput )

Отображает элемент управления выбором, позволяющий пользователям выбирать элементы. В качестве элементов управления выбором могут использоваться флажки, переключатели, переключатели или выпадающие меню.

For example, the following JSON creates a dropdown menu that lets users choose a size:

"selectionInput": {
  "name": "size",
  "label": "Size"
  "type": "DROPDOWN",
  "items": [
    {
      "text": "S",
      "value": "small",
      "selected": false
    },
    {
      "text": "M",
      "value": "medium",
      "selected": true
    },
    {
      "text": "L",
      "value": "large",
      "selected": false
    },
    {
      "text": "XL",
      "value": "extra_large",
      "selected": false
    }
  ]
}
dateTimePicker

object ( DateTimePicker )

Отображает виджет, позволяющий пользователям вводить дату, время или дату и время.

For example, the following JSON creates a date time picker to schedule an appointment:

"dateTimePicker": {
  "name": "appointment_time",
  "label": "Book your appointment at:",
  "type": "DATE_AND_TIME",
  "valueMsEpoch": 796435200000
}
divider

object ( Divider )

Отображает горизонтальную разделительную линию между виджетами.

Например, следующий JSON-код создает разделитель:

"divider": {
}
grid

object ( Grid )

Отображает сетку с набором элементов.

Таблица поддерживает любое количество столбцов и элементов. Количество строк определяется как верхнее значение отношения количества элементов к количеству столбцов. Таблица с 10 элементами и 2 столбцами имеет 5 строк. Таблица с 11 элементами и 2 столбцами имеет 6 строк.

Available for Google Chat apps and Google Workspace add-ons.

Например, следующий JSON-код создает сетку из двух столбцов с одним элементом:

"grid": {
  "title": "A fine collection of items",
  "columnCount": 2,
  "borderStyle": {
    "type": "STROKE",
    "cornerRadius": 4
  },
  "items": [
    {
      "image": {
        "imageUri": "https://www.example.com/image.png",
        "cropStyle": {
          "type": "SQUARE"
        },
        "borderStyle": {
          "type": "STROKE"
        }
      },
      "title": "An item",
      "textAlignment": "CENTER"
    }
  ],
  "onClick": {
    "openLink": {
      "url": "https://www.example.com"
    }
  }
}
columns

object ( Columns )

Отображает до 2 столбцов.

Чтобы добавить более двух столбцов или использовать строки, воспользуйтесь виджетом Grid .

Например, следующий JSON-код создает 2 столбца, каждый из которых содержит текстовые абзацы:

"columns": {
  "columnItems": [
    {
      "horizontalSizeStyle": "FILL_AVAILABLE_SPACE",
      "horizontalAlignment": "CENTER",
      "verticalAlignment": "CENTER",
      "widgets": [
        {
          "textParagraph": {
            "text": "First column text paragraph"
          }
        }
      ]
    },
    {
      "horizontalSizeStyle": "FILL_AVAILABLE_SPACE",
      "horizontalAlignment": "CENTER",
      "verticalAlignment": "CENTER",
      "widgets": [
        {
          "textParagraph": {
            "text": "Second column text paragraph"
          }
        }
      ]
    }
  ]
}
carousel

object ( Carousel )

Карусель содержит набор вложенных виджетов. Например, это JSON-представление карусели, содержащей два текстовых абзаца.

{
  "widgets": [
    {
      "textParagraph": {
        "text": "First text paragraph in the carousel."
      }
    },
    {
      "textParagraph": {
        "text": "Second text paragraph in the carousel."
      }
    }
  ]
}
chipList

object ( ChipList )

Список чипсов.

Например, следующий JSON-код создает два чипа. Первый — текстовый чип, а второй — чип-иконка, открывающий ссылку:

"chipList": {
  "chips": [
    {
      "text": "Edit",
      "disabled": true,
    },
    {
      "icon": {
        "knownIcon": "INVITE",
        "altText": "check calendar"
      },
      "onClick": {
        "openLink": {
          "url": "https://example.com/calendar"
        }
      }
    }
  ]
}
Конец взаимоисключающих областей.

Текстовый абзац

Абзац текста, поддерживающий форматирование. Пример использования в приложениях Google Chat см. в разделе «Добавление абзаца форматированного текста» . Дополнительную информацию о форматировании текста см. в разделах «Форматирование текста в приложениях Google Chat» и «Форматирование текста в надстройках Google Workspace» .

Доступно для приложений Google Chat и дополнений Google Workspace.

JSON-представление
{
  "text": string,
  "maxLines": integer,
  "textSyntax": enum (TextSyntax)
}
Поля
text

string

Текст, отображаемый в виджете.

maxLines

integer

Максимальное количество строк текста, отображаемых в виджете. Если текст превышает указанное максимальное количество строк, лишнее содержимое скрывается за кнопкой «Показать больше» . Если текст равен или короче указанного максимального количества строк, кнопка «Показать больше» не отображается.

The default value is 0, in which case all context is displayed. Negative values are ignored.

textSyntax

enum ( TextSyntax )

Синтаксис текста. Если не задано, текст отображается как HTML.

Доступно для приложений Google Chat, но недоступно для дополнений Google Workspace.

Текстовый синтаксис

Синтаксис, используемый для форматирования текста.

Доступно для приложений Google Chat, но недоступно для дополнений Google Workspace.

Перечисления
TEXT_SYNTAX_UNSPECIFIED Если не указано иное, текст отображается в формате HTML.
HTML Текст отображается в формате HTML. Это значение по умолчанию.
MARKDOWN Текст отображается в формате Markdown.

Изображение

Изображение, заданное по URL-адресу, может иметь действие onClick . Пример см. в разделе «Добавление изображения» .

Доступно для приложений Google Chat и дополнений Google Workspace.

JSON-представление
{
  "imageUrl": string,
  "onClick": {
    object (OnClick)
  },
  "altText": string
}
Поля
imageUrl

string

HTTPS-адрес, на котором размещено изображение.

Например:

https://developers.google.com/workspace/chat/images/quickstart-app-avatar.png
onClick

object ( OnClick )

Когда пользователь щелкает по изображению, этот щелчок запускает данное действие.

altText

string

Альтернативный текст этого изображения, используемый для обеспечения доступности.

OnClick

Описывает, как реагировать, когда пользователи нажимают на интерактивный элемент на карточке, например, на кнопку.

Доступно для приложений Google Chat и дополнений Google Workspace.

JSON-представление
{

  "action": {
    object (Action)
  },
  "openLink": {
    object (OpenLink)
  },
  "openDynamicLinkAction": {
    object (Action)
  },
  "card": {
    object (Card)
  },
  "overflowMenu": {
    object (OverflowMenu)
  }
}
Поля
Ниже приведён список взаимоисключающих полей. В ответе будет установлено не более одного из этих полей:
action

object ( Action )

Если указано иное, действие запускается этим обработчиком onClick .

card

object ( Card )

Если указано иное, после нажатия кнопки новая карточка добавляется в стопку карточек.

Доступно для дополнений Google Workspace и недоступно для приложений Google Chat.

overflowMenu

object ( OverflowMenu )

Если указано, то onClick открывает дополнительное меню.

Конец взаимоисключающих областей.

Действие

Действие, описывающее поведение при отправке формы. Например, вы можете вызвать скрипт Apps Script для обработки формы. Если действие срабатывает, значения формы отправляются на сервер.

Available for Google Chat apps and Google Workspace add-ons.

JSON-представление
{
  "function": string,
  "parameters": [
    {
      object (ActionParameter)
    }
  ],
  "loadIndicator": enum (LoadIndicator),
  "persistValues": boolean,
  "interaction": enum (Interaction),
  "requiredWidgets": [
    string
  ],
  "allWidgetsAreRequired": boolean
}
Поля
function

string

Пользовательская функция, вызываемая при щелчке по содержащему элементу или при его иной активации.

Пример использования см. в разделе «Чтение данных формы» .

parameters[]

object ( ActionParameter )

Список параметров действия.

loadIndicator

enum ( LoadIndicator )

Указывает индикатор загрузки, который отображается при вызове действия.

persistValues

boolean

Указывает, сохраняются ли значения формы после выполнения действия. Значение по умолчанию — false .

Если true , значения формы сохраняются после запуска действия. Чтобы пользователь мог вносить изменения во время обработки действия, установите LoadIndicator в NONE . Для сообщений в виде карточек в чат-приложениях необходимо также установить ResponseType действия в значение UPDATE_MESSAGE и использовать тот же cardId что и карточка, содержащая действие.

Если false , значения формы очищаются при срабатывании действия. Чтобы предотвратить внесение пользователем изменений во время обработки действия, установите для LoadIndicator SPINNER .

interaction

enum ( Interaction )

Необязательно. Обязательно при открытии диалогового окна .

Что делать в ответ на взаимодействие с пользователем, например, когда пользователь нажимает кнопку в сообщении-карточке?

Если параметр не указан, приложение реагирует, выполняя action — например, открывая ссылку или запуская функцию — как обычно.

Указав параметр interaction , приложение может реагировать особыми интерактивными способами. Например, установив interaction на OPEN_DIALOG , приложение может открыть диалоговое окно . При указании этого параметра индикатор загрузки не отображается. Если параметр указан для дополнения, вся карточка удаляется, и на экране клиента ничего не отображается.

Доступно для приложений Google Chat, но недоступно для дополнений Google Workspace.

requiredWidgets[]

string

Optional. Fill this list with the names of widgets that this Action needs for a valid submission.

Если при вызове этого действия у перечисленных здесь виджетов отсутствует значение, отправка формы будет прервана.

Доступно для приложений Google Chat и дополнений Google Workspace.

allWidgetsAreRequired

boolean

Необязательно. Если это так, то все виджеты считаются обязательными для данного действия.

Доступно для приложений Google Chat и дополнений Google Workspace.

Параметр действия

Список строковых параметров, которые необходимо передать при вызове метода действия. Например, рассмотрим три кнопки отложенного будильника: отложить сейчас, отложить через день или отложить на следующей неделе. Вы можете использовать action method = snooze() , передав тип и время отложенного будильника в списке строковых параметров.

Для получения более подробной информации см. CommonEventObject .

Доступно для приложений Google Chat и дополнений Google Workspace.

JSON-представление
{
  "key": string,
  "value": string
}
Поля
key

string

Название параметра для скрипта действия.

value

string

Значение параметра.

LoadIndicator

Указывает индикатор загрузки, который отображается при вызове действия.

Доступно для приложений Google Chat и дополнений Google Workspace.

Перечисления
SPINNER Отображает индикатор загрузки контента.
NONE Ничего не отображается.

Взаимодействие

Необязательно. Обязательно при открытии диалогового окна .

Что делать в ответ на взаимодействие с пользователем, например, когда пользователь нажимает кнопку в сообщении-карточке?

Если параметр не указан, приложение реагирует, выполняя action — например, открывая ссылку или запуская функцию — как обычно.

Указав тип interaction , приложение может реагировать особыми интерактивными способами. Например, установив interaction на OPEN_DIALOG , приложение может открыть диалоговое окно .

When specified, a loading indicator isn't shown. If specified for an add-on, the entire card is stripped and nothing is shown in the client.

Доступно для приложений Google Chat, но недоступно для дополнений Google Workspace.

Перечисления
INTERACTION_UNSPECIFIED Значение по умолчанию. action выполняется в обычном режиме.
OPEN_DIALOG

Открывает диалоговое окно — оконный интерфейс на основе карточек, который приложения для чата используют для взаимодействия с пользователями.

Поддерживается только в чат-приложениях в ответ на нажатия кнопок в сообщениях-карточках. Если указано для дополнения, вся карточка удаляется, и в клиенте ничего не отображается.

Доступно для приложений Google Chat, но недоступно для дополнений Google Workspace.

OpenAs

Когда действие OnClick открывает ссылку, клиент может открыть её либо как полноразмерное окно (если клиент использует такой фрейм), либо как наложение (например, всплывающее окно). Реализация зависит от возможностей платформы клиента, и выбранное значение может быть проигнорировано, если клиент его не поддерживает. FULL_SIZE поддерживается всеми клиентами.

Доступно для дополнений Google Workspace и недоступно для приложений Google Chat.

Перечисления
FULL_SIZE The link opens as a full-size window (if that's the frame used by the client).
OVERLAY Ссылка открывается в виде всплывающего окна или наложения.

OnClose

What the client does when a link opened by an OnClick action is closed.

Реализация зависит от возможностей клиентской платформы. Например, веб-браузер может открывать ссылку во всплывающем окне с обработчиком события OnClose .

If both OnOpen and OnClose handlers are set, and the client platform can't support both values, OnClose takes precedence.

Доступно для дополнений Google Workspace и недоступно для приложений Google Chat.

Перечисления
NOTHING Default value. The card doesn't reload; nothing happens.
RELOAD

Карта пополняется после закрытия дочернего окна.

При использовании совместно с OpenAs.OVERLAY дочернее окно действует как модальное диалоговое окно, а родительская карточка блокируется до закрытия дочернего окна.

OverflowMenu

Виджет, отображающий всплывающее меню с одним или несколькими действиями, которые могут быть вызваны пользователями. Например, для отображения неосновных действий в карточке. Этот виджет можно использовать, когда действия не помещаются в доступное пространство. Для использования укажите этот виджет в действии OnClick виджетов, которые его поддерживают. Например, в Button .

Доступно для приложений Google Chat и дополнений Google Workspace.

JSON-представление
{
  "items": [
    {
      object (OverflowMenuItem)
    }
  ]
}
Поля
items[]

object ( OverflowMenuItem )

Обязательно. Список пунктов меню.

ПереполнениеМенюПункт

Опция, которую пользователи могут вызвать в дополнительном меню.

Available for Google Chat apps and Google Workspace add-ons.

JSON-представление
{
  "startIcon": {
    object (Icon)
  },
  "text": string,
  "onClick": {
    object (OnClick)
  },
  "disabled": boolean
}
Поля
startIcon

object ( Icon )

Значок, отображаемый перед текстом.

text

string

Required. The text that identifies or describes the item to users.

onClick

object ( OnClick )

Required. The action invoked when a menu option is selected. This OnClick cannot contain an OverflowMenu , any specified OverflowMenu is dropped and the menu item disabled.

disabled

boolean

Whether the menu option is disabled. Defaults to false.

Икона

An icon displayed in a widget on a card. For an example in Google Chat apps, see Add an icon .

Поддерживает встроенные и пользовательские значки.

Available for Google Chat apps and Google Workspace add-ons.

JSON-представление
{
  "altText": string,
  "imageType": enum (ImageType),

  "knownIcon": string,
  "iconUrl": string,
  "materialIcon": {
    object (MaterialIcon)
  }
}
Поля
altText

string

Optional. A description of the icon used for accessibility. If unspecified, the default value Button is provided. As a best practice, you should set a helpful description for what the icon displays, and if applicable, what it does. For example, A user's account portrait , or Opens a new browser tab and navigates to the Google Chat developer documentation at https://developers.google.com/workspace/chat .

If the icon is set in a Button , the altText appears as helper text when the user hovers over the button. However, if the button also sets text , the icon's altText is ignored.

imageType

enum ( ImageType )

The crop style applied to the image. In some cases, applying a CIRCLE crop causes the image to be drawn larger than a built-in icon.

The icon displayed in the widget on the card. The following is a list of mutually exclusive fields. At most one of the fields will be set in a response:
knownIcon

string

Display one of the built-in icons provided by Google Workspace.

For example, to display an airplane icon, specify AIRPLANE . For a bus, specify BUS .

For a full list of supported icons, see built-in icons .

iconUrl

string

Отобразить пользовательскую иконку, размещенную по адресу HTTPS.

Например:

"iconUrl":
"https://developers.google.com/workspace/chat/images/quickstart-app-avatar.png"

Поддерживаются файлы следующих форматов: .png и .jpg .

materialIcon

object ( MaterialIcon )

Отобразите один из значков Google Material Icons .

Например, чтобы отобразить значок флажка , используйте

"materialIcon": {
  "name": "check_box"
}

Доступно для приложений Google Chat, но недоступно для дополнений Google Workspace.

Конец взаимоисключающих областей.

MaterialIcon

A Google Material Icon , which includes over 2500+ options.

For example, to display a checkbox icon with customized weight and grade, write the following:

{
  "name": "check_box",
  "fill": true,
  "weight": 300,
  "grade": -25
}

Доступно для приложений Google Chat, но недоступно для дополнений Google Workspace.

JSON-представление
{
  "name": string,
  "fill": boolean,
  "weight": integer,
  "grade": integer
}
Поля
name

string

Имя значка, определенное в Google Material Icon , например, check_box . Любые недопустимые имена отбрасываются и заменяются пустой строкой, что приводит к невозможности отображения значка.

fill

boolean

Whether the icon renders as filled. Default value is false.

To preview different icon settings, go to Google Font Icons and adjust the settings under Customize .

weight

integer

The stroke weight of the icon. Choose from {100, 200, 300, 400, 500, 600, 700}. If absent, default value is 400. If any other value is specified, the default value is used.

To preview different icon settings, go to Google Font Icons and adjust the settings under Customize .

grade

integer

Толщина и градиент влияют на размер символа. Корректировка градиента более точна, чем корректировка толщины, и оказывает незначительное влияние на размер символа. Выберите один из вариантов: {-25, 0, 200}. Если значение отсутствует, используется значение по умолчанию 0. Если указано другое значение, используется значение по умолчанию.

To preview different icon settings, go to Google Font Icons and adjust the settings under Customize .

Декорированный текст

Виджет, отображающий текст с дополнительными элементами оформления, такими как метка над или под текстом, значок перед текстом, виджет выделения или кнопка после текста. Пример использования в приложениях Google Chat см. в разделе «Отображение текста с декоративными элементами» .

Available for Google Chat apps and Google Workspace add-ons.

JSON-представление
{
  "icon": {
    object (Icon)
  },
  "startIcon": {
    object (Icon)
  },
  "startIconVerticalAlignment": enum (VerticalAlignment),
  "topLabel": string,
  "topLabelText": {
    object (TextParagraph)
  },
  "text": string,
  "contentText": {
    object (TextParagraph)
  },
  "wrapText": boolean,
  "bottomLabel": string,
  "bottomLabelText": {
    object (TextParagraph)
  },
  "onClick": {
    object (OnClick)
  },

  "button": {
    object (Button)
  },
  "switchControl": {
    object (SwitchControl)
  },
  "endIcon": {
    object (Icon)
  }
}
Поля
icon
(deprecated)

object ( Icon )

Устарело, вместо него используется startIcon .

startIcon

object ( Icon )

Значок, отображаемый перед текстом.

startIconVerticalAlignment

enum ( VerticalAlignment )

Optional. Vertical alignment of the start icon. If not set, the icon will be vertically centered.

Доступно для приложений Google Chat, но недоступно для дополнений Google Workspace.

topLabel

string

The text that appears above text . Always truncates.

topLabelText

object ( TextParagraph )

TextParagraph equivalent of topLabel . Always truncates. Allows for more complex formatting than topLabel .

Доступно для приложений Google Chat, но недоступно для дополнений Google Workspace.

text

string

Обязательно. Основной текст.

Supports simple formatting. For more information about formatting text, see Formatting text in Google Chat apps and Formatting text in Google Workspace add-ons .

contentText

object ( TextParagraph )

TextParagraph эквивалент text . Позволяет использовать более сложное форматирование, чем text .

Доступно для приложений Google Chat, но недоступно для дополнений Google Workspace.

wrapText

boolean

Параметр переноса текста. Если true , текст переносится и отображается в несколько строк. В противном случае текст обрезается.

Only applies to text , not topLabel and bottomLabel .

bottomLabel

string

Текст, отображаемый ниже text , всегда переносится на следующий текст.

bottomLabelText

object ( TextParagraph )

TextParagraph equivalent of bottomLabel . Always wraps. Allows for more complex formatting than bottomLabel .

Доступно для приложений Google Chat, но недоступно для дополнений Google Workspace.

onClick

object ( OnClick )

This action is triggered when users click topLabel or bottomLabel .

Кнопка, переключатель, флажок или изображение, отображаемое справа от текста в виджете decoratedText . Ниже приведен список взаимоисключающих полей. В ответе будет установлено не более одного из полей:
button

object ( Button )

A button that a user can click to trigger an action.

switchControl

object ( SwitchControl )

A switch widget that a user can click to change its state and trigger an action.

endIcon

object ( Icon )

Значок, отображаемый после текста.

Поддерживает встроенные и пользовательские значки.

Конец взаимоисключающих областей.

Вертикальное выравнивание

Представляет собой атрибут вертикального выравнивания.

Перечисления
VERTICAL_ALIGNMENT_UNSPECIFIED Тип не указан. Не использовать.
TOP Выравнивание по верхнему положению.
MIDDLE Выравнивание по центру.
BOTTOM Выравнивание по нижнему положению.

Кнопка

A text, icon, or text and icon button that users can click. For an example in Google Chat apps, see Add a button .

To make an image a clickable button, specify an Image (not an ImageComponent ) and set an onClick action.

Available for Google Chat apps and Google Workspace add-ons.

JSON-представление
{
  "text": string,
  "icon": {
    object (Icon)
  },
  "color": {
    object (Color)
  },
  "onClick": {
    object (OnClick)
  },
  "disabled": boolean,
  "altText": string,
  "type": enum (Type)
}
Поля
text

string

Текст, отображаемый внутри кнопки.

icon

object ( Icon )

An icon displayed inside the button. If both icon and text are set, then the icon appears before the text.

color

object ( Color )

Необязательный параметр. Цвет кнопки. Если задан, type кнопки устанавливается как FILLED , а цвет text и icon устанавливается на контрастный цвет для лучшей читаемости. Например, если цвет кнопки установлен на синий, любой текст или значки на кнопке будут белыми.

Чтобы задать цвет кнопки, укажите значения для полей red , green и blue . Значение должно быть числом с плавающей запятой от 0 до 1, основанным на цветовой модели RGB, где 0 (0/255) означает отсутствие цвета, а 1 (255/255) — максимальную интенсивность цвета.

Например, следующий код устанавливает цвет на красный с максимальной интенсивностью:

"color": {
   "red": 1,
   "green": 0,
   "blue": 0,
}

The alpha field is unavailable for button color. If specified, this field is ignored.

onClick

object ( OnClick )

Required. The action to perform when a user clicks the button, such as opening a hyperlink or running a custom function.

disabled

boolean

If true , the button is displayed in an inactive state and doesn't respond to user actions.

altText

string

The alternative text that's used for accessibility.

Добавьте описательный текст, который сообщит пользователям, что делает кнопка. Например, если кнопка открывает гиперссылку, вы можете написать: «Открывает новую вкладку браузера и переходит к документации для разработчиков Google Chat по адресу https://developers.google.com/workspace/chat» .

type

enum ( Type )

Optional. The type of a button. If unset, button type defaults to OUTLINED . If the color field is set, the button type is forced to FILLED and any value set for this field is ignored.

Цвет

Представляет цвет в цветовом пространстве RGBA. Это представление разработано для упрощения преобразования в цветовые представления и обратно в различных языках программирования, а не для компактности. Например, поля этого представления можно легко передать конструктору java.awt.Color в Java; его также легко передать методу +colorWithRed:green:blue:alpha класса UIColor в iOS; и, приложив немного усилий, его можно легко отформатировать в строку CSS rgba() в JavaScript.

На этой справочной странице отсутствует информация об абсолютном цветовом пространстве, которое следует использовать для интерпретации значения RGB — например, sRGB, Adobe RGB, DCI-P3 и BT.2020. По умолчанию приложения должны использовать цветовое пространство sRGB.

Когда необходимо определить равенство цветов, в реализациях, если не указано иное, два цвета считаются равными, если значения красного, зеленого, синего и альфа-канала различаются не более чем на 1e-5 .

Пример (Java):

 import com.google.type.Color;

 // ...
 public static java.awt.Color fromProto(Color protocolor) {
   float alpha = protocolor.hasAlpha()
       ? protocolor.getAlpha().getValue()
       : 1.0;

   return new java.awt.Color(
       protocolor.getRed(),
       protocolor.getGreen(),
       protocolor.getBlue(),
       alpha);
 }

 public static Color toProto(java.awt.Color color) {
   float red = (float) color.getRed();
   float green = (float) color.getGreen();
   float blue = (float) color.getBlue();
   float denominator = 255.0;
   Color.Builder resultBuilder =
       Color
           .newBuilder()
           .setRed(red / denominator)
           .setGreen(green / denominator)
           .setBlue(blue / denominator);
   int alpha = color.getAlpha();
   if (alpha != 255) {
     result.setAlpha(
         FloatValue
             .newBuilder()
             .setValue(((float) alpha) / denominator)
             .build());
   }
   return resultBuilder.build();
 }
 // ...

Пример (iOS / Objective-C):

 // ...
 static UIColor* fromProto(Color* protocolor) {
    float red = [protocolor red];
    float green = [protocolor green];
    float blue = [protocolor blue];
    FloatValue* alpha_wrapper = [protocolor alpha];
    float alpha = 1.0;
    if (alpha_wrapper != nil) {
      alpha = [alpha_wrapper value];
    }
    return [UIColor colorWithRed:red green:green blue:blue alpha:alpha];
 }

 static Color* toProto(UIColor* color) {
     CGFloat red, green, blue, alpha;
     if (![color getRed:&red green:&green blue:&blue alpha:&alpha]) {
       return nil;
     }
     Color* result = [[Color alloc] init];
     [result setRed:red];
     [result setGreen:green];
     [result setBlue:blue];
     if (alpha <= 0.9999) {
       [result setAlpha:floatWrapperWithValue(alpha)];
     }
     [result autorelease];
     return result;
}
// ...

Пример (JavaScript):

// ...

var protoToCssColor = function(rgb_color) {
   var redFrac = rgb_color.red || 0.0;
   var greenFrac = rgb_color.green || 0.0;
   var blueFrac = rgb_color.blue || 0.0;
   var red = Math.floor(redFrac * 255);
   var green = Math.floor(greenFrac * 255);
   var blue = Math.floor(blueFrac * 255);

   if (!('alpha' in rgb_color)) {
      return rgbToCssColor(red, green, blue);
   }

   var alphaFrac = rgb_color.alpha.value || 0.0;
   var rgbParams = [red, green, blue].join(',');
   return ['rgba(', rgbParams, ',', alphaFrac, ')'].join('');
};

var rgbToCssColor = function(red, green, blue) {
  var rgbNumber = new Number((red << 16) | (green << 8) | blue);
  var hexString = rgbNumber.toString(16);
  var missingZeros = 6 - hexString.length;
  var resultBuilder = ['#'];
  for (var i = 0; i < missingZeros; i++) {
     resultBuilder.push('0');
  }
  resultBuilder.push(hexString);
  return resultBuilder.join('');
};

// ...
JSON-представление
{
  "red": number,
  "green": number,
  "blue": number,
  "alpha": number
}
Поля
red

number

Количество красного цвета в заданном диапазоне значений находится в интервале [0, 1].

green

number

Количество зеленого цвета в заданном диапазоне значений находится в интервале [0, 1].

blue

number

Количество синего цвета в заданном цвете выражается значением в интервале [0, 1].

alpha

number

Доля этого цвета, которая должна быть применена к пикселю. То есть, окончательный цвет пикселя определяется уравнением:

pixel color = alpha * (this color) + (1.0 - alpha) * (background color)

Это означает, что значение 1,0 соответствует сплошному цвету, а значение 0,0 — полностью прозрачному цвету. Используется оберточное сообщение, а не простое скалярное значение с плавающей запятой, что позволяет различать значение по умолчанию и значение, которое не задано. Если этот параметр опущен, объект цвета отображается как сплошной цвет (как если бы значению альфа-канала было явно присвоено значение 1,0).

Тип

Optional. The type of a button. If color field is set, the type is forced to FILLED .

Доступно для приложений Google Chat, но недоступно для дополнений Google Workspace.

Перечисления
TYPE_UNSPECIFIED Не использовать. Не указано.
OUTLINED Outlined buttons are medium-emphasis buttons. They usually contain actions that are important, but aren't the primary action in a Chat app or an add-on.
FILLED A filled button has a container with a solid color. It has the most visual impact and is recommended for the important and primary action in a Chat app or an add-on.
FILLED_TONAL Заполненная тональная кнопка представляет собой промежуточный вариант между заполненными и обведенными кнопками. Она полезна в ситуациях, когда кнопка с более низким приоритетом требует немного большего акцента, чем кнопка с обведенной рамкой.
BORDERLESS В своем стандартном состоянии кнопка не имеет невидимого контейнера. Она часто используется для действий с самым низким приоритетом, особенно при отображении нескольких вариантов.

SwitchControl

Either a toggle-style switch or a checkbox inside a decoratedText widget.

Available for Google Chat apps and Google Workspace add-ons.

Поддерживается только в виджете decoratedText .

JSON-представление
{
  "name": string,
  "value": string,
  "selected": boolean,
  "onChangeAction": {
    object (Action)
  },
  "controlType": enum (ControlType)
}
Поля
name

string

The name by which the switch widget is identified in a form input event.

For details about working with form inputs, see Receive form data .

value

string

The value entered by a user, returned as part of a form input event.

For details about working with form inputs, see Receive form data .

selected

boolean

Если true , переключатель выбран.

onChangeAction

object ( Action )

The action to perform when the switch state is changed, such as what function to run.

controlType

enum ( ControlType )

Как переключатель отображается в пользовательском интерфейсе.

Available for Google Chat apps and Google Workspace add-ons.

ControlType

Как переключатель отображается в пользовательском интерфейсе.

Available for Google Chat apps and Google Workspace add-ons.

Перечисления
SWITCH Переключатель тумблерного типа.
CHECKBOX Устарело, вместо него используется CHECK_BOX .
CHECK_BOX Флажок.

ButtonList

Список кнопок, расположенных горизонтально. Пример использования в приложениях Google Chat см. в разделе «Добавить кнопку» .

Доступно для приложений Google Chat и дополнений Google Workspace.

JSON-представление
{
  "buttons": [
    {
      object (Button)
    }
  ]
}
Поля
buttons[]

object ( Button )

Набор кнопок.

Текстовое поле

Поле, в которое пользователи могут вводить текст. Поддерживает подсказки и действия при изменении. Поддерживает проверку данных при отправке формы. Если для Action.all_widgets_are_required установлено значение true или этот виджет указан в Action.required_widgets , отправка формы блокируется, если не введено значение. Пример использования в приложениях Google Chat см. в разделе «Добавление поля, в которое пользователь может вводить текст» .

Chat apps receive and can process the value of entered text during form input events. For details about working with form inputs, see Receive form data .

When you need to collect undefined or abstract data from users, use a text input. To collect defined or enumerated data from users, use the SelectionInput widget.

Доступно для приложений Google Chat и дополнений Google Workspace.

JSON-представление
{
  "name": string,
  "label": string,
  "hintText": string,
  "value": string,
  "type": enum (Type),
  "onChangeAction": {
    object (Action)
  },
  "initialSuggestions": {
    object (Suggestions)
  },
  "autoCompleteAction": {
    object (Action)
  },
  "validation": {
    object (Validation)
  },
  "placeholderText": string,

  "hostAppDataSource": {
    object (HostAppDataSourceMarkup)
  }
}
Поля
name

string

Имя, по которому текстовое поле идентифицируется в событии ввода формы.

Подробную информацию о работе с полями ввода формы см. в разделе «Получение данных формы» .

label

string

The text that appears above the text input field in the user interface.

Укажите текст, который поможет пользователю ввести необходимую вашему приложению информацию. Например, если вы спрашиваете имя, но вам нужна именно фамилия, напишите surname вместо name .

Обязательно, если hintText не указан. В противном случае — необязательно.

hintText

string

Текст, отображаемый под полем ввода текста, призван помочь пользователям, предлагая им ввести определенное значение. Этот текст всегда виден.

Обязательно, если label не указана. В противном случае — необязательно.

value

string

Значение, введенное пользователем, возвращается в рамках события ввода данных в форму.

Подробную информацию о работе с полями ввода формы см. в разделе «Получение данных формы» .

type

enum ( Type )

Как текстовое поле ввода отображается в пользовательском интерфейсе. Например, является ли поле однострочным или многострочным.

onChangeAction

object ( Action )

Что делать, если в текстовом поле произошли изменения? Например, пользователь добавил текст в поле или удалил его.

В качестве примеров действий можно привести запуск пользовательской функции или открытие диалога в Google Chat.

initialSuggestions

object ( Suggestions )

Предлагаемые значения, которые могут ввести пользователи. Эти значения появляются при щелчке мышью внутри текстового поля ввода. По мере ввода пользователем предлагаемые значения динамически фильтруются, чтобы соответствовать введенному тексту.

Например, текстовое поле ввода для языка программирования может предлагать Java, JavaScript, Python и C++. Когда пользователь начинает вводить Jav , список подсказок фильтруется, отображая только Java и JavaScript .

Предлагаемые значения помогают пользователям вводить данные, которые ваше приложение сможет распознать. Применительно к JavaScript, одни пользователи могут ввести javascript , а другие java script . Предложение значений JavaScript может стандартизировать взаимодействие пользователей с вашим приложением.

Если указано значение, TextInput.type всегда будет SINGLE_LINE , даже если оно установлено на MULTIPLE_LINE .

Доступно для приложений Google Chat и дополнений Google Workspace.

autoCompleteAction

object ( Action )

Необязательно. Укажите, какое действие следует предпринять, когда текстовое поле ввода предлагает варианты действий пользователям, взаимодействующим с ним.

Если параметр не указан, предложения формируются параметром initialSuggestions и обрабатываются клиентом.

Если указано иное, приложение выполнит указанное здесь действие, например, запустит пользовательскую функцию.

Доступно для дополнений Google Workspace и недоступно для приложений Google Chat.

validation

object ( Validation )

Укажите необходимые параметры проверки формата ввода для этого текстового поля.

Доступно для приложений Google Chat и дополнений Google Workspace.

placeholderText

string

Текст, который отображается в поле ввода текста, когда поле пустое. Используйте этот текст, чтобы предложить пользователям ввести значение. Например: « Enter a number from 0 to 100 .

Доступно для приложений Google Chat, но недоступно для дополнений Google Workspace.

Ниже приведён список взаимоисключающих полей. В ответе будет установлено не более одного из этих полей:
hostAppDataSource

object ( HostAppDataSourceMarkup )

Уникальный для каждого приложения Google Workspace источник данных, например, электронные письма Gmail, события Google Calendar или сообщения Google Chat.

Доступно для дополнений Google Workspace, расширяющих функциональность Google Workspace Studio. Недоступно для приложений Google Chat.

Конец взаимоисключающих областей.

Тип

Как текстовое поле ввода отображается в пользовательском интерфейсе. Например, является ли оно однострочным или многострочным полем ввода. Если указан параметр initialSuggestions , type всегда будет SINGLE_LINE , даже если он установлен на MULTIPLE_LINE .

Доступно для приложений Google Chat и дополнений Google Workspace.

Перечисления
SINGLE_LINE Поле ввода текста имеет фиксированную высоту в одну строку.
MULTIPLE_LINE Поле ввода текста имеет фиксированную высоту и состоит из нескольких строк.

RenderActions

Набор инструкций рендеринга, который указывает карточке выполнить действие, или указывает приложению-хосту дополнения или приложению чата выполнить действие, специфичное для данного приложения.

Доступно для приложений Google Chat и дополнений Google Workspace.

Поля
action

Action

Действие

Поля
navigations[]

Navigation

Выполняет операцию добавления, извлечения или обновления карты.

Дополнения в Google Чат .

Добавить новую карточку в стопку (перейти вперед). Для приложений чата: доступно только на главной странице приложения .

Доступно для приложений Google Chat и дополнений Google Workspace.

navigations: {
  pushCard: CARD
}

Замените верхнюю карточку новой. Доступно только на главной странице приложения для чат-приложений .

Доступно для приложений Google Chat и дополнений Google Workspace.

navigations: {
  updateCard: CARD
}

Предложения

Предлагаемые значения, которые могут ввести пользователи. Эти значения появляются при щелчке мышью внутри текстового поля ввода. По мере ввода пользователем предлагаемые значения динамически фильтруются, чтобы соответствовать введенному тексту.

Например, текстовое поле ввода для языка программирования может предлагать Java, JavaScript, Python и C++. Когда пользователь начинает вводить Jav , список подсказок фильтруется, отображая Java и JavaScript .

Предлагаемые значения помогают пользователям вводить данные, которые ваше приложение сможет распознать. Применительно к JavaScript, одни пользователи могут ввести javascript , а другие java script . Предложение значений JavaScript может стандартизировать взаимодействие пользователей с вашим приложением.

Если указано значение, TextInput.type всегда будет SINGLE_LINE , даже если оно установлено на MULTIPLE_LINE .

Доступно для приложений Google Chat и дополнений Google Workspace.

JSON-представление
{
  "items": [
    {
      object (SuggestionItem)
    }
  ]
}
Поля
items[]

object ( SuggestionItem )

Список подсказок, используемых для автозаполнения в текстовых полях ввода.

Предложение

Одно из предлагаемых значений, которое пользователи могут ввести в текстовое поле ввода.

Доступно для приложений Google Chat и дополнений Google Workspace.

JSON-представление
{

  "text": string
}
Поля
The following is a list of mutually exclusive fields. At most one of the fields will be set in a response:
text

string

The value of a suggested input to a text input field. This is equivalent to what users enter themselves.

End of mutually exclusive fields.

Проверка

Represents the necessary data for validating the widget it's attached to.

Available for Google Chat apps and Google Workspace add-ons.

JSON-представление
{
  "characterLimit": integer,
  "inputType": enum (InputType)
}
Поля
characterLimit

integer

Specify the character limit for text input widgets. Note that this is only used for text input and is ignored for other widgets.

Available for Google Chat apps and Google Workspace add-ons.

inputType

enum ( InputType )

Specify the type of the input widgets.

Available for Google Chat apps and Google Workspace add-ons.

InputType

The type of the input widget.

Перечисления
INPUT_TYPE_UNSPECIFIED Unspecified type. Do not use.
TEXT Regular text that accepts all characters.
INTEGER An integer value.
FLOAT A float value.
EMAIL An email address.
EMOJI_PICKER A emoji selected from system-provided emoji picker.

HostAppDataSourceMarkup

Источник данных из приложения Google Workspace. Источник данных заполняет доступные элементы для виджета.

JSON-представление
{

  "chatDataSource": {
    object (ChatClientDataSourceMarkup)
  },
  "workflowDataSource": {
    object (WorkflowDataSourceMarkup)
  }
}
Поля
The Google Workspace application that populates available items for a widget. The following is a list of mutually exclusive fields. At most one of the fields will be set in a response:
chatDataSource

object ( ChatClientDataSourceMarkup )

Источник данных из Google Chat.

workflowDataSource

object ( WorkflowDataSourceMarkup )

Источник данных из Google Workflow.

End of mutually exclusive fields.

ChatClientDataSourceMarkup

Для виджета SelectionInput , использующего меню с множественным выбором, используется источник данных из Google Chat. Источник данных заполняет элементы выбора в меню с множественным выбором. Например, пользователь может выбрать пространства Google Chat, в которых он состоит.

Доступно для приложений Google Chat, но недоступно для дополнений Google Workspace.

JSON-представление
{

  "spaceDataSource": {
    object (SpaceDataSource)
  }
}
Поля
The Google Chat data source. The following is a list of mutually exclusive fields. At most one of the fields will be set in a response:
spaceDataSource

object ( SpaceDataSource )

Чат-пространства Google, участником которых является пользователь.

End of mutually exclusive fields.

SpaceDataSource

Источник данных, который отображает пространства Google Chat в качестве элементов выбора для меню с множественным выбором. Отображает данные только из тех пространств, в которых состоит пользователь.

Доступно для приложений Google Chat, но недоступно для дополнений Google Workspace.

JSON-представление
{
  "defaultToCurrentSpace": boolean
}
Поля
defaultToCurrentSpace

boolean

Если установлено значение true , то в меню с множественным выбором по умолчанию выбирается текущее пространство чата Google в качестве элемента.

WorkflowDataSourceMarkup

* Поддерживается только в Google Workspace Workflow, но не в приложениях Google Chat или надстройках Google Workspace.

В виджете TextInput или SelectionInput с типом MULTI_SELECT или в элементе DateTimePicker укажите источник данных из Google.

JSON-представление
{
  "includeVariables": boolean,
  "type": enum (Type)
}
Поля
includeVariables

boolean

Следует ли включать переменные из предыдущего шага в источник данных.

type

enum ( Type )

Тип источника данных.

Тип

Перечисление, представляющее тип источника данных рабочего процесса.

Перечисления
UNKNOWN Значение по умолчанию. Не использовать.
USER Пользователи Google Workspace. Пользователь может просматривать и выбирать только пользователей из своей организации Google Workspace.
SPACE Чат-пространства Google, участником которых является пользователь.
USER_WITH_FREE_FORM Пользователи могут просматривать и выбирать существующих участников из своей организации Google Workspace или вручную вводить адрес электронной почты или действительный домен.

SelectionInput

A widget that creates one or more UI items that users can select. Supports form submission validation for dropdown and multiselect menus only. When Action.all_widgets_are_required is set to true or this widget is specified in Action.required_widgets , the submission action is blocked unless a value is selected. For example, a dropdown menu or checkboxes. You can use this widget to collect data that can be predicted or enumerated. For an example in Google Chat apps, see Add selectable UI elements .

Chat apps can process the value of items that users select or input. For details about working with form inputs, see Receive form data .

To collect undefined or abstract data from users, use the TextInput widget.

Available for Google Chat apps and Google Workspace add-ons.

JSON-представление
{
  "name": string,
  "label": string,
  "type": enum (SelectionType),
  "items": [
    {
      object (SelectionItem)
    }
  ],
  "onChangeAction": {
    object (Action)
  },
  "multiSelectMinQueryLength": integer,
  "dataSourceConfigs": [
    {
      object (DataSourceConfig)
    }
  ],
  "multiSelectMaxSelectedItems": integer,
  "hintText": string,

  "externalDataSource": {
    object (Action)
  },
  "platformDataSource": {
    object (PlatformDataSource)
  }
}
Поля
name

string

Required. The name that identifies the selection input in a form input event.

For details about working with form inputs, see Receive form data .

label

string

The text that appears above the selection input field in the user interface.

Specify text that helps the user enter the information your app needs. For example, if users are selecting the urgency of a work ticket from a drop-down menu, the label might be "Urgency" or "Select urgency".

type

enum ( SelectionType )

The type of items that are displayed to users in a SelectionInput widget. Selection types support different types of interactions. For example, users can select one or more checkboxes, but they can only select one value from a dropdown menu.

items[]

object ( SelectionItem )

An array of selectable items. For example, an array of radio buttons or checkboxes. Supports up to 100 items.

onChangeAction

object ( Action )

If specified, the form is submitted when the selection changes. If not specified, you must specify a separate button that submits the form.

For details about working with form inputs, see Receive form data .

multiSelectMinQueryLength

integer

For multiselect menus, the number of text characters that a user inputs before the menu returns suggested selection items.

If unset, the multiselect menu uses the following default values:

  • If the menu uses a static array of SelectionInput items, defaults to 0 characters and immediately populates items from the array.
  • If the menu uses a dynamic data source ( multi_select_data_source ), defaults to 3 characters before querying the data source to return suggested items.
dataSourceConfigs[]

object ( DataSourceConfig )

Optional. The data source configs for the selection control. This field provides more fine-grained control over the data source.

If specified, the multiSelectMaxSelectedItems field, multiSelectMinQueryLength field, externalDataSource field and platformDataSource field are ignored.

Available for Google Workspace add-ons that extend Google Workspace Studio.

Available for the Dropdown widget in Google Chat apps. For the Dropdown widget in Google Chat apps, only one DataSourceConfig is supported. If multiple DataSourceConfig s are set, only the first one is used.

multiSelectMaxSelectedItems

integer

For multiselect menus, the maximum number of items that a user can select. Minimum value is 1 item. If unspecified, defaults to 3 items.

hintText

string

Optional. Text that appears below the selection input field meant to assist users by prompting them to enter a certain value. This text is always visible.

Available for Google Workspace add-ons that extend Google Workspace Studio. Unavailable for Google Chat apps.

For a multiselect menu, a data source that dynamically populates selection items.

Available for Google Chat apps and unavailable for Google Workspace add-ons. The following is a list of mutually exclusive fields. At most one of the fields will be set in a response:

externalDataSource

object ( Action )

An external data source, such as a relational database.

platformDataSource

object ( PlatformDataSource )

A data source from Google Workspace.

End of mutually exclusive fields.

Тип выбора

The format for the items that users can select. Different options support different types of interactions. For example, users can select multiple checkboxes, but can only select one item from a dropdown menu.

Each selection input supports one type of selection. Mixing checkboxes and switches, for example, isn't supported.

Available for Google Chat apps and Google Workspace add-ons.

Перечисления
CHECK_BOX A set of checkboxes. Users can select one or more checkboxes.
RADIO_BUTTON A set of radio buttons. Users can select one radio button.
SWITCH A set of switches. Users can turn on one or more switches.
DROPDOWN

A dropdown menu. Users can select one item from the menu.

For Google Chat apps, you can populate items using a dynamic data source and autosuggest items as users type in the menu. For example, users can start typing the name of a Google Chat space and the widget autosuggests the space. To dynamically populate items for a dropdown menu, use one of the following types of data sources:

  • Google Workspace data: Items are populated using data from Google Workspace, such as Google Workspace users or Google Chat spaces.
  • External data: Items are populated from an external data source outside of Google Workspace.

For examples of how to implement dropdown menus for Chat apps, see Add a dropdown menu and Dynamically populate drop-down menus .

Available for Google Chat apps and Google Workspace add-ons.

MULTI_SELECT

A menu with a text box. Users can type and select one or more items. For Google Workspace add-ons, you must populate items using a static array of SelectionItem objects.

For Google Chat apps, you can also populate items using a dynamic data source and autosuggest items as users type in the menu. For example, users can start typing the name of a Google Chat space and the widget autosuggests the space. To dynamically populate items for a multiselect menu, use one of the following types of data sources:

  • Google Workspace data: Items are populated using data from Google Workspace, such as Google Workspace users or Google Chat spaces.
  • External data: Items are populated from an external data source outside of Google Workspace.

For examples of how to implement multiselect menus for Chat apps, see Add a multiselect menu .

Available for Google Chat apps and Google Workspace add-ons.

SelectionItem

An item that users can select in a selection input, such as a checkbox or switch. Supports up to 100 items.

Available for Google Chat apps and Google Workspace add-ons.

JSON-представление
{
  "text": string,
  "value": string,
  "selected": boolean,
  "bottomText": string,

  "startIconUri": string
}
Поля
text

string

The text that identifies or describes the item to users.

value

string

The value associated with this item. The client should use this as a form input value.

For details about working with form inputs, see Receive form data .

selected

boolean

Whether the item is selected by default. If the selection input only accepts one value (such as for radio buttons or a dropdown menu), only set this field for one item.

bottomText

string

For multiselect menus, a text description or label that's displayed below the item's text field.

For multiselect menus, the URL for the icon displayed next to the item's text field. Supports PNG and JPEG files. Must be an HTTPS URL. For example, https://developers.google.com/workspace/chat/images/quickstart-app-avatar.png . The following is a list of mutually exclusive fields. At most one of the fields will be set in a response:
startIconUri

string

End of mutually exclusive fields.

PlatformDataSource

For a SelectionInput widget that uses a multiselect menu, a data source from Google Workspace. Used to populate items in a multiselect menu.

Доступно для приложений Google Chat, но недоступно для дополнений Google Workspace.

JSON-представление
{

  "commonDataSource": enum (CommonDataSource),
  "hostAppDataSource": {
    object (HostAppDataSourceMarkup)
  }
}
Поля
The data source. The following is a list of mutually exclusive fields. At most one of the fields will be set in a response:
commonDataSource

enum ( CommonDataSource )

A data source shared by all Google Workspace applications, such as users in a Google Workspace organization.

hostAppDataSource

object ( HostAppDataSourceMarkup )

A data source that's unique to a Google Workspace host application, such spaces in Google Chat.

This field supports the Google API Client Libraries but isn't available in the Cloud Client Libraries. To learn more, see Install the client libraries .

End of mutually exclusive fields.

CommonDataSource

A data source shared by all Google Workspace applications .

Доступно для приложений Google Chat, но недоступно для дополнений Google Workspace.

Перечисления
UNKNOWN Значение по умолчанию. Не использовать.
USER Пользователи Google Workspace. Пользователь может просматривать и выбирать только пользователей из своей организации Google Workspace.

DataSourceConfig

A configuration object that helps configure the data sources for a widget.

Available for Google Chat apps and Google Workspace add-ons that extend Google Workspace Studio.

JSON-представление
{

  "remoteDataSource": {
    object (Action)
  },
  "platformDataSource": {
    object (PlatformDataSource)
  }
  "minCharactersTrigger": integer
}
Поля
The data source. The following is a list of mutually exclusive fields. At most one of the fields will be set in a response:
remoteDataSource

object ( Action )

The data is from a remote data provider.

platformDataSource

object ( PlatformDataSource )

The data is from a Google Workspace application.

End of mutually exclusive fields.
minCharactersTrigger

integer

The minimum number of characters the user must enter before this data provider is triggered (ie, before it starts returning results).

DateTimePicker

Lets users input a date, a time, or both a date and a time. Supports form submission validation. When Action.all_widgets_are_required is set to true or this widget is specified in Action.required_widgets , the submission action is blocked unless a value is selected. For an example in Google Chat apps, see Let a user pick a date and time .

Users can input text or use the picker to select dates and times. If users input an invalid date or time, the picker shows an error that prompts users to input the information correctly.

Available for Google Chat apps and Google Workspace add-ons.

JSON-представление
{
  "name": string,
  "label": string,
  "type": enum (DateTimePickerType),
  "valueMsEpoch": string,
  "timezoneOffsetDate": integer,
  "onChangeAction": {
    object (Action)
  },

  "hostAppDataSource": {
    object (HostAppDataSourceMarkup)
  }
}
Поля
name

string

The name by which the DateTimePicker is identified in a form input event.

For details about working with form inputs, see Receive form data .

label

string

The text that prompts users to input a date, a time, or a date and time. For example, if users are scheduling an appointment, use a label such as Appointment date or Appointment date and time .

type

enum ( DateTimePickerType )

Whether the widget supports inputting a date, a time, or the date and time.

valueMsEpoch

string ( int64 format)

The default value displayed in the widget, in milliseconds since Unix epoch time .

Specify the value based on the type of picker ( DateTimePickerType ):

  • DATE_AND_TIME : a calendar date and time in UTC. For example, to represent January 1, 2023 at 12:00 PM UTC, use 1672574400000 .
  • DATE_ONLY : a calendar date at 00:00:00 UTC. For example, to represent January 1, 2023, use 1672531200000 .
  • TIME_ONLY : a time in UTC. For example, to represent 12:00 PM, use 43200000 (or 12 * 60 * 60 * 1000 ).
timezoneOffsetDate

integer

The number representing the time zone offset from UTC, in minutes. If set, the valueMsEpoch is displayed in the specified time zone. If unset, the value defaults to the user's time zone setting.

onChangeAction

object ( Action )

Triggered when the user clicks Save or Clear from the DateTimePicker interface.

The data source specified to represent a date and time. The following is a list of mutually exclusive fields. At most one of the fields will be set in a response:
hostAppDataSource

object ( HostAppDataSourceMarkup )

A data source that's unique to a Google Workspace host application, such as Gmail emails, Google Calendar events, or Google Chat messages.

Available for Google Workspace add-ons that extend Google Workspace Studio. Unavailable for Google Chat apps.

End of mutually exclusive fields.

DateTimePickerType

The format for the date and time in the DateTimePicker widget. Determines whether users can input a date, a time, or both a date and time.

Available for Google Chat apps and Google Workspace add-ons.

Перечисления
DATE_AND_TIME Users input a date and time.
DATE_ONLY Users input a date.
TIME_ONLY Users input a time.

Разделитель

Этот тип не содержит полей.

Displays a divider between widgets as a horizontal line. For an example in Google Chat apps, see Add a horizontal divider between widgets .

Available for Google Chat apps and Google Workspace add-ons.

For example, the following JSON creates a divider:

"divider": {}

Сетка

Displays a grid with a collection of items. Items can only include text or images. For responsive columns, or to include more than text or images, use Columns . For an example in Google Chat apps, see Display a Grid with a collection of items .

A grid supports any number of columns and items. The number of rows is determined by items divided by columns. A grid with 10 items and 2 columns has 5 rows. A grid with 11 items and 2 columns has 6 rows.

Available for Google Chat apps and Google Workspace add-ons.

For example, the following JSON creates a 2 column grid with a single item:

"grid": {
  "title": "A fine collection of items",
  "columnCount": 2,
  "borderStyle": {
    "type": "STROKE",
    "cornerRadius": 4
  },
  "items": [
    {
      "image": {
        "imageUri": "https://www.example.com/image.png",
        "cropStyle": {
          "type": "SQUARE"
        },
        "borderStyle": {
          "type": "STROKE"
        }
      },
      "title": "An item",
      "textAlignment": "CENTER"
    }
  ],
  "onClick": {
    "openLink": {
      "url": "https://www.example.com"
    }
  }
}
JSON-представление
{
  "title": string,
  "items": [
    {
      object (GridItem)
    }
  ],
  "borderStyle": {
    object (BorderStyle)
  },
  "columnCount": integer,
  "onClick": {
    object (OnClick)
  }
}
Поля
title

string

The text that displays in the grid header.

items[]

object ( GridItem )

The items to display in the grid.

borderStyle

object ( BorderStyle )

The border style to apply to each grid item.

columnCount

integer

The number of columns to display in the grid. A default value is used if this field isn't specified, and that default value is different depending on where the grid is shown (dialog versus companion).

onClick

object ( OnClick )

This callback is reused by each individual grid item, but with the item's identifier and index in the items list added to the callback's parameters.

GridItem

Represents an item in a grid layout. Items can contain text, an image, or both text and an image.

Available for Google Chat apps and Google Workspace add-ons.

JSON-представление
{
  "id": string,
  "image": {
    object (ImageComponent)
  },
  "title": string,
  "subtitle": string,
  "layout": enum (GridItemLayout)
}
Поля
id

string

A user-specified identifier for this grid item. This identifier is returned in the parent grid's onClick callback parameters.

image

object ( ImageComponent )

The image that displays in the grid item.

title

string

The grid item's title.

subtitle

string

The grid item's subtitle.

layout

enum ( GridItemLayout )

The layout to use for the grid item.

ImageComponent

Represents an image.

Available for Google Chat apps and Google Workspace add-ons.

JSON-представление
{
  "imageUri": string,
  "altText": string,
  "cropStyle": {
    object (ImageCropStyle)
  },
  "borderStyle": {
    object (BorderStyle)
  }
}
Поля
imageUri

string

The image URL.

altText

string

The accessibility label for the image.

cropStyle

object ( ImageCropStyle )

The crop style to apply to the image.

borderStyle

object ( BorderStyle )

The border style to apply to the image.

ImageCropStyle

Represents the crop style applied to an image.

Available for Google Chat apps and Google Workspace add-ons.

For example, here's how to apply a 16:9 aspect ratio:

cropStyle {
 "type": "RECTANGLE_CUSTOM",
 "aspectRatio": 16/9
}
JSON-представление
{
  "type": enum (ImageCropType),
  "aspectRatio": number
}
Поля
type

enum ( ImageCropType )

The crop type.

aspectRatio

number

The aspect ratio to use if the crop type is RECTANGLE_CUSTOM .

For example, here's how to apply a 16:9 aspect ratio:

cropStyle {
 "type": "RECTANGLE_CUSTOM",
 "aspectRatio": 16/9
}

ImageCropType

Represents the crop style applied to an image.

Available for Google Chat apps and Google Workspace add-ons.

Перечисления
IMAGE_CROP_TYPE_UNSPECIFIED Don't use. Unspecified.
SQUARE Default value. Applies a square crop.
CIRCLE Applies a circular crop.
RECTANGLE_CUSTOM Applies a rectangular crop with a custom aspect ratio. Set the custom aspect ratio with aspectRatio .
RECTANGLE_4_3 Applies a rectangular crop with a 4:3 aspect ratio.

BorderStyle

The style options for the border of a card or widget, including the border type and color.

Available for Google Chat apps and Google Workspace add-ons.

JSON-представление
{
  "type": enum (BorderType),
  "strokeColor": {
    object (Color)
  },
  "cornerRadius": integer
}
Поля
type

enum ( BorderType )

The border type.

strokeColor

object ( Color )

The colors to use when the type is BORDER_TYPE_STROKE .

To set the stroke color, specify a value for the red , green , and blue fields. The value must be a float number between 0 and 1 based on the RGB color value, where 0 (0/255) represents the absence of color and 1 (255/255) represents the maximum intensity of the color.

For example, the following sets the color to red at its maximum intensity:

"color": {
   "red": 1,
   "green": 0,
   "blue": 0,
}

The alpha field is unavailable for stroke color. If specified, this field is ignored.

cornerRadius

integer

The corner radius for the border.

BorderType

Represents the border types applied to widgets.

Available for Google Chat apps and Google Workspace add-ons.

Перечисления
BORDER_TYPE_UNSPECIFIED Don't use. Unspecified.
NO_BORDER Нет границ.
STROKE Default value. Outline.

GridItemLayout

Represents the various layout options available for a grid item.

Available for Google Chat apps and Google Workspace add-ons.

Перечисления
GRID_ITEM_LAYOUT_UNSPECIFIED Don't use. Unspecified.
TEXT_BELOW The title and subtitle are shown below the grid item's image.
TEXT_ABOVE The title and subtitle are shown above the grid item's image.

Колонки

The Columns widget displays up to 2 columns in a card or dialog. You can add widgets to each column; the widgets appear in the order that they are specified. For an example in Google Chat apps, see Display cards and dialogs in columns .

The height of each column is determined by the taller column. For example, if the first column is taller than the second column, both columns have the height of the first column. Because each column can contain a different number of widgets, you can't define rows or align widgets between the columns.

Columns are displayed side-by-side. You can customize the width of each column using the HorizontalSizeStyle field. If the user's screen width is too narrow, the second column wraps below the first:

  • On web, the second column wraps if the screen width is less than or equal to 480 pixels.
  • On iOS devices, the second column wraps if the screen width is less than or equal to 300 pt.
  • On Android devices, the second column wraps if the screen width is less than or equal to 320 dp.

To include more than two columns, or to use rows, use the Grid widget.

Available for Google Chat apps and Google Workspace add-ons. The add-on UIs that support columns include:

  • The dialog displayed when users open the add-on from an email draft.
  • The dialog displayed when users open the add-on from the Add attachment menu in a Google Calendar event.
JSON-представление
{
  "columnItems": [
    {
      object (Column)
    }
  ]
}
Поля
columnItems[]

object ( Column )

An array of columns. You can include up to 2 columns in a card or dialog.

Столбец

A column.

Google Workspace add-ons and Chat apps

JSON-представление
{
  "horizontalSizeStyle": enum (HorizontalSizeStyle),
  "horizontalAlignment": enum (HorizontalAlignment),
  "verticalAlignment": enum (VerticalAlignment),
  "widgets": [
    {
      object (Widgets)
    }
  ]
}
Поля
horizontalSizeStyle

enum ( HorizontalSizeStyle )

Specifies how a column fills the width of the card.

horizontalAlignment

enum ( HorizontalAlignment )

Specifies whether widgets align to the left, right, or center of a column.

verticalAlignment

enum ( VerticalAlignment )

Specifies whether widgets align to the top, bottom, or center of a column.

widgets[]

object ( Widgets )

An array of widgets included in a column. Widgets appear in the order that they are specified.

HorizontalSizeStyle

Specifies how a column fills the width of the card. The width of each column depends on both the HorizontalSizeStyle and the width of the widgets within the column.

Google Workspace add-ons and Chat apps

Перечисления
HORIZONTAL_SIZE_STYLE_UNSPECIFIED Don't use. Unspecified.
FILL_AVAILABLE_SPACE Default value. Column fills the available space, up to 70% of the card's width. If both columns are set to FILL_AVAILABLE_SPACE , each column fills 50% of the space.
FILL_MINIMUM_SPACE Column fills the least amount of space possible and no more than 30% of the card's width.

Горизонтальное выравнивание

Specifies whether widgets align to the left, right, or center of a column.

Доступно для приложений Google Chat, но недоступно для дополнений Google Workspace.

Перечисления
HORIZONTAL_ALIGNMENT_UNSPECIFIED Don't use. Unspecified.
START Default value. Aligns widgets to the start position of the column. For left-to-right layouts, aligns to the left. For right-to-left layouts, aligns to the right.
CENTER Aligns widgets to the center of the column.
END Aligns widgets to the end position of the column. For left-to-right layouts, aligns widgets to the right. For right-to-left layouts, aligns widgets to the left.

Вертикальное выравнивание

Specifies whether widgets align to the top, bottom, or center of a column.

Google Workspace add-ons and Chat apps

Перечисления
VERTICAL_ALIGNMENT_UNSPECIFIED Don't use. Unspecified.
CENTER Default value. Aligns widgets to the center of a column.
TOP Aligns widgets to the top of a column.
BOTTOM Aligns widgets to the bottom of a column.

Виджеты

The supported widgets that you can include in a column.

Google Workspace add-ons and Chat apps

JSON-представление
{

  "textParagraph": {
    object (TextParagraph)
  },
  "image": {
    object (Image)
  },
  "decoratedText": {
    object (DecoratedText)
  },
  "buttonList": {
    object (ButtonList)
  },
  "textInput": {
    object (TextInput)
  },
  "selectionInput": {
    object (SelectionInput)
  },
  "dateTimePicker": {
    object (DateTimePicker)
  },
  "chipList": {
    object (ChipList)
  }
}
Поля
The following is a list of mutually exclusive fields. At most one of the fields will be set in a response:
textParagraph

object ( TextParagraph )

TextParagraph widget.

image

object ( Image )

Image widget.

decoratedText

object ( DecoratedText )

DecoratedText widget.

buttonList

object ( ButtonList )

ButtonList widget.

textInput

object ( TextInput )

TextInput widget.

selectionInput

object ( SelectionInput )

SelectionInput widget.

dateTimePicker

object ( DateTimePicker )

DateTimePicker widget.

chipList

object ( ChipList )

ChipList widget.

End of mutually exclusive fields.

ChipList

A list of chips layed out horizontally, which can either scroll horizontally or wrap to the next line.

Available for Google Chat apps and Google Workspace add-ons.

JSON-представление
{
  "layout": enum (Layout),
  "chips": [
    {
      object (Chip)
    }
  ]
}
Поля
layout

enum ( Layout )

Specified chip list layout.

chips[]

object ( Chip )

An array of chips.

Макет

The chip list layout.

Перечисления
LAYOUT_UNSPECIFIED Don't use. Unspecified.
WRAPPED Default value. The chip list wraps to the next line if there isn't enough horizontal space.
HORIZONTAL_SCROLLABLE The chips scroll horizontally if they don't fit in the available space.

Чип

A text, icon, or text and icon chip that users can click.

Available for Google Chat apps and Google Workspace add-ons.

JSON-представление
{
  "icon": {
    object (Icon)
  },
  "label": string,
  "onClick": {
    object (OnClick)
  },
  "enabled": boolean,
  "disabled": boolean,
  "altText": string
}
Поля
icon

object ( Icon )

The icon image. If both icon and text are set, then the icon appears before the text.

label

string

The text displayed inside the chip.

onClick

object ( OnClick )

Optional. The action to perform when a user clicks the chip, such as opening a hyperlink or running a custom function.

enabled
(deprecated)

boolean

Whether the chip is in an active state and responds to user actions. Defaults to true . Deprecated. Use disabled instead.

disabled

boolean

Whether the chip is in an inactive state and ignores user actions. Defaults to false .

altText

string

The alternative text that's used for accessibility.

Set descriptive text that lets users know what the chip does. For example, if a chip opens a hyperlink, write: "Opens a new browser tab and navigates to the Google Chat developer documentation at https://developers.google.com/workspace/chat" .

A carousel, also known as a slider, rotates and displays a list of widgets in a slideshow format, with buttons navigating to the previous or next widget.

For example, this is a JSON representation of a carousel that contains three text paragraph widgets.

{
  "carouselCards": [
    {
      "widgets": [
        {
          "textParagraph": {
            "text": "First text paragraph in carousel",
          }
        }
      ]
    },
    {
      "widgets": [
        {
          "textParagraph": {
            "text": "Second text paragraph in carousel",
          }
        }
      ]
    },
    {
      "widgets": [
        {
          "textParagraph": {
            "text": "Third text paragraph in carousel",
          }
        }
      ]
    }
  ]
}

Доступно для приложений Google Chat, но недоступно для дополнений Google Workspace.

JSON-представление
{
  "carouselCards": [
    {
      object (CarouselCard)
    }
  ]
}
Поля
carouselCards[]

object ( CarouselCard )

A list of cards included in the carousel.

CarouselCard

A card that can be displayed as a carousel item. Доступно для приложений Google Chat, но недоступно для дополнений Google Workspace.

JSON-представление
{
  "widgets": [
    {
      object (NestedWidget)
    }
  ],
  "footerWidgets": [
    {
      object (NestedWidget)
    }
  ]
}
Поля
widgets[]

object ( NestedWidget )

A list of widgets displayed in the carousel card. The widgets are displayed in the order that they are specified.

footerWidgets[]

object ( NestedWidget )

A list of widgets displayed at the bottom of the carousel card. The widgets are displayed in the order that they are specified.

NestedWidget

A list of widgets that can be displayed in a containing layout, such as a CarouselCard . Доступно для приложений Google Chat, но недоступно для дополнений Google Workspace.

JSON-представление
{

  "textParagraph": {
    object (TextParagraph)
  },
  "buttonList": {
    object (ButtonList)
  },
  "image": {
    object (Image)
  }
}
Поля
The following is a list of mutually exclusive fields. At most one of the fields will be set in a response:
textParagraph

object ( TextParagraph )

A text paragraph widget.

buttonList

object ( ButtonList )

A button list widget.

image

object ( Image )

An image widget.

End of mutually exclusive fields.

Видимость

Specifies whether an UI element is visible or hidden.

Available for Google Workspace add-ons that extend Google Workspace Studio. Unavailable for Google Chat apps.

Перечисления
VISIBILITY_UNSPECIFIED Unspecified visibility. Do not use.
VISIBLE The UI element is visible.
HIDDEN The UI element is hidden.

EventAction

Represents an actionthat can be performed on an ui element.

Available for Google Workspace add-ons that extend Google Workspace Studio. Unavailable for Google Chat apps.

JSON-представление
{
  "actionRuleId": string,
  "postEventTriggers": [
    {
      object (Trigger)
    }
  ],

  "commonWidgetAction": {
    object (CommonWidgetAction)
  }
}
Поля
actionRuleId

string

The unique identifier of the ActionRule.

postEventTriggers[]

object ( Trigger )

The list of triggers that will be triggered after the EventAction is executed.

The action to perform. The following is a list of mutually exclusive fields. At most one of the fields will be set in a response:
commonWidgetAction

object ( CommonWidgetAction )

Common widget action.

End of mutually exclusive fields.

Курок

Represents a trigger.

Available for Google Workspace add-ons that extend Google Workspace Studio. Unavailable for Google Chat apps.

JSON-представление
{
  "actionRuleId": string
}
Поля
actionRuleId

string

The unique identifier of the ActionRule.

CommonWidgetAction

Represents an action that is not specific to a widget.

Available for Google Workspace add-ons that extend Google Workspace Studio. Unavailable for Google Chat apps.

JSON-представление
{

  "updateVisibilityAction": {
    object (UpdateVisibilityAction)
  }
}
Поля
The action to perform. The following is a list of mutually exclusive fields. At most one of the fields will be set in a response:
updateVisibilityAction

object ( UpdateVisibilityAction )

The action to update the visibility of a widget.

End of mutually exclusive fields.

UpdateVisibilityAction

Represents an action that updates the visibility of a widget.

Available for Google Workspace add-ons that extend Google Workspace Studio. Unavailable for Google Chat apps.

JSON-представление
{
  "visibility": enum (Visibility)
}
Поля
visibility

enum ( Visibility )

The new visibility.

CollapseControl

Represent an expand and collapse control.

Available for Google Chat apps and Google Workspace add-ons.

JSON-представление
{
  "horizontalAlignment": enum (HorizontalAlignment),
  "expandButton": {
    object (Button)
  },
  "collapseButton": {
    object (Button)
  }
}
Поля
horizontalAlignment

enum ( HorizontalAlignment )

The horizontal alignment of the expand and collapse button.

expandButton

object ( Button )

Optional. Define a customizable button to expand the section. Both expandButton and collapseButton field must be set. Only one field set will not take into effect. If this field isn't set, the default button is used.

collapseButton

object ( Button )

Optional. Define a customizable button to collapse the section. Both expandButton and collapseButton field must be set. Only one field set will not take into effect. If this field isn't set, the default button is used.

DividerStyle

The divider style of a card. Currently only used for dividers betweens card sections.

Available for Google Chat apps and Google Workspace add-ons.

Перечисления
DIVIDER_STYLE_UNSPECIFIED Don't use. Unspecified.
SOLID_DIVIDER Default option. Render a solid divider.
NO_DIVIDER If set, no divider is rendered. This style completely removes the divider from the layout. The result is equivalent to not adding a divider at all.

CardAction

A card action is the action associated with the card. For example, an invoice card might include actions such as delete invoice, email invoice, or open the invoice in a browser.

Available for Google Workspace add-ons and unavailable for Google Chat apps.

JSON-представление
{
  "actionLabel": string,
  "onClick": {
    object (OnClick)
  }
}
Поля
actionLabel

string

The label that displays as the action menu item.

onClick

object ( OnClick )

The onClick action for this action item.

CardFixedFooter

A persistent (sticky) footer that that appears at the bottom of the card.

Setting fixedFooter without specifying a primaryButton or a secondaryButton causes an error.

For Chat apps, you can use fixed footers in dialogs , but not card messages . For an example in Google Chat apps, see Add a persistent footer .

Available for Google Chat apps and Google Workspace add-ons.

JSON-представление
{
  "primaryButton": {
    object (Button)
  },
  "secondaryButton": {
    object (Button)
  }
}
Поля
primaryButton

object ( Button )

The primary button of the fixed footer. The button must be a text button with text and color set.

secondaryButton

object ( Button )

The secondary button of the fixed footer. The button must be a text button with text and color set. If secondaryButton is set, you must also set primaryButton .

DisplayStyle

In Google Workspace add-ons, determines how a card is displayed.

Available for Google Workspace add-ons and unavailable for Google Chat apps.

Перечисления
DISPLAY_STYLE_UNSPECIFIED Don't use. Unspecified.
PEEK The header of the card appears at the bottom of the sidebar, partially covering the current top card of the stack. Clicking the header pops the card into the card stack. If the card has no header, a generated header is used instead.
REPLACE Default value. The card is shown by replacing the view of the top card in the card stack.

ExpressionData

Represents the data that is used to evaluate an expression.

Available for Google Workspace add-ons that extend Google Workspace Studio. Unavailable for Google Chat apps.

JSON-представление
{
  "id": string,
  "expression": string,
  "conditions": [
    {
      object (Condition)
    }
  ],
  "eventActions": [
    {
      object (EventAction)
    }
  ]
}
Поля
id

string

The unique identifier of the ExpressionData.

expression

string

The uncompiled expression.

conditions[]

object ( Condition )

The list of conditions that are determined by the expression evaluation result.

eventActions[]

object ( EventAction )

The list of actions that the ExpressionData can be used.

Состояние

Represents a condition that can be used to trigger an action.

Available for Google Workspace add-ons that extend Google Workspace Studio. Unavailable for Google Chat apps.

JSON-представление
{
  "actionRuleId": string,

  "expressionDataCondition": {
    object (ExpressionDataCondition)
  }
}
Поля
actionRuleId

string

The unique identifier of the ActionRule.

The condition. The following is a list of mutually exclusive fields. At most one of the fields will be set in a response:
expressionDataCondition

object ( ExpressionDataCondition )

The condition that is determined by the expression data.

End of mutually exclusive fields.

ExpressionDataCondition

Represents a condition that is evaluated using CEL.

Available for Google Workspace add-ons that extend Google Workspace Studio. Unavailable for Google Chat apps.

JSON-представление
{
  "conditionType": enum (ConditionType)
}
Поля
conditionType

enum ( ConditionType )

The type of the condition.

ConditionType

The type of the condition.

Перечисления
CONDITION_TYPE_UNSPECIFIED Unspecified condition type.
EXPRESSION_EVALUATION_SUCCESS The expression evaluation was successful.
EXPRESSION_EVALUATION_FAILURE The expression evaluation was unsuccessful.