Estensione dell'interfaccia utente di scrittura con azioni di scrittura

Oltre a fornire un'interfaccia basata su schede quando un utente legge un messaggio Gmail, i componenti aggiuntivi di Google Workspace che estendono Gmail possono fornire un'altra interfaccia quando l'utente compone nuovi messaggi o risponde a quelli esistenti. In questo modo, i componenti aggiuntivi di Google Workspace possono automatizzare l'attività di composizione delle email per l'utente.

Accedere all'interfaccia utente di composizione del componente aggiuntivo

Esistono due modi per visualizzare l'interfaccia utente di composizione di un componente aggiuntivo. Il primo modo è iniziare a comporre una nuova bozza o una risposta mentre il componente aggiuntivo è già aperto. Il secondo modo è avviare il componente aggiuntivo durante la composizione di una bozza.

In entrambi i casi, il componente aggiuntivo esegue la funzione di attivazione della composizione corrispondente, definita nel manifest del componente aggiuntivo. La funzione di attivazione della composizione crea l'interfaccia utente di composizione per l'azione di composizione, che Gmail mostra all'utente.

Creazione di un componente aggiuntivo per la composizione

Per aggiungere la funzionalità di composizione a un componente aggiuntivo, segui questi passaggi generali:

  1. Aggiungi il campo gmail.composeTrigger al progetto di script del componente aggiuntivo manifest e aggiorna gli ambiti del manifest in modo da includere quelli richiesti per le azioni di composizione.
  2. Implementa una funzione di trigger di composizione che crea un'interfaccia utente di composizione quando viene attivato il trigger. Le funzioni di attivazione di composizione restituiscono un singolo oggetto Card o un array di oggetti Card che compongono l'interfaccia utente di composizione per l'azione di composizione.
  3. Implementa le funzioni di callback associate necessarie per reagire alle interazioni dell'utente con la UI di composizione. Queste funzioni non sono l'azione di composizione in sé (che fa solo apparire l'interfaccia utente di composizione); piuttosto, sono le singole funzioni che regolano ciò che accade quando vengono selezionati diversi elementi dell'interfaccia utente di composizione. Ad esempio, una scheda dell'interfaccia utente contenente un pulsante di solito ha una funzione di callback associata che viene eseguita quando un utente fa clic su quel pulsante. La funzione di callback per i widget che aggiornano il contenuto del messaggio in bozza deve restituire un oggetto UpdateDraftActionResponse.

Funzione di trigger di composizione

L'interfaccia utente di composizione di un componente aggiuntivo viene creata nello stesso modo dell'interfaccia utente del messaggio del componente aggiuntivo, utilizzando il servizio Card di Apps Script per creare schede e riempirle con widget.

Devi implementare gmail.composeTrigger.selectActions[].runFunction che definisci nel manifest. La funzione di trigger di composizione deve restituire un singolo oggetto Card o un array di oggetti Card che compongono la UI di composizione per l'azione. Queste funzioni sono molto simili alle funzioni di attivazione contestuale e devono creare le schede nello stesso modo.

Comporre oggetti evento trigger

Quando viene selezionata un'azione di composizione, viene eseguita la funzione di trigger di composizione corrispondente e viene passato alla funzione un oggetto evento come parametro. L'oggetto evento può contenere informazioni sul contesto del componente aggiuntivo e sulla bozza in fase di composizione nella funzione di attivazione.

Per informazioni dettagliate su come sono organizzate le informazioni nell'oggetto evento, consulta Struttura dell'oggetto evento. Le informazioni contenute nell'oggetto evento sono parzialmente controllate dal valore del campo manifest gmail.composeTrigger.draftAccess:

  • Se il campo manifest gmail.composeTrigger.draftAccess è NONE o non è incluso, l'oggetto evento contiene solo informazioni minime.

  • Se gmail.composeTrigger.draftAccess è impostato su METADATA, l'oggetto evento passato alla funzione di attivazione di composizione viene compilato con gli elenchi dei destinatari dell'email in fase di composizione.

Inserimento di contenuti nelle bozze attive

In genere, l'interfaccia utente di composizione di un componente aggiuntivo di Google Workspace fornisce all'utente le opzioni e il controllo che aiutano a comporre un messaggio. Per questi casi d'uso, una volta che l'utente ha effettuato le selezioni nell'interfaccia utente, il componente aggiuntivo interpreta le selezioni e aggiorna di conseguenza la bozza di email corrente.

Per semplificare l'aggiornamento della bozza di email corrente, il servizio di schede è stato esteso con le seguenti classi:

In genere, l'interfaccia utente di composizione di un componente aggiuntivo include un widget "Salva" o "Inserisci" su cui un utente può fare clic per indicare che ha terminato le selezioni nell'interfaccia utente e vuole che le sue scelte vengano aggiunte all'email che sta componendo. Per aggiungere questa interattività, il widget deve avere un oggetto Action associato che indica al componente aggiuntivo di eseguire una funzione di callback specifica quando si fa clic sul widget. Devi implementare queste funzioni di callback. Ogni funzione di callback deve restituire un oggetto UpdateDraftActionResponse integrato che descrive in dettaglio le modifiche da apportare alla bozza di email corrente.

Esempio 1

Il seguente snippet di codice mostra come creare un'interfaccia utente di composizione che aggiorna l'oggetto e i destinatari A, Cc e Ccn della bozza di email corrente.

    /**
     * Compose trigger function that fires when the compose UI is
     * requested. Builds and returns a compose UI for inserting images.
     *
     * @param {event} e The compose trigger event object. Not used in
     *         this example.
     * @return {Card[]}
     */
    function getComposeUI(e) {
      return [buildComposeCard()];
    }

    /**
     * Build a card to display interactive buttons to allow the user to
     * update the subject, and To, Cc, Bcc recipients.
     *
     * @return {Card}
     */
    function buildComposeCard() {

      var card = CardService.newCardBuilder();
      var cardSection = CardService.newCardSection().setHeader('Update email');
      cardSection.addWidget(
          CardService.newTextButton()
              .setText('Update subject')
              .setOnClickAction(CardService.newAction()
                  .setFunctionName('applyUpdateSubjectAction')));
      cardSection.addWidget(
          CardService.newTextButton()
              .setText('Update To recipients')
              .setOnClickAction(CardService.newAction()
                  .setFunctionName('updateToRecipients')));
      cardSection.addWidget(
          CardService.newTextButton()
              .setText('Update Cc recipients')
              .setOnClickAction(CardService.newAction()
                  .setFunctionName('updateCcRecipients')));
      cardSection.addWidget(
          CardService.newTextButton()
              .setText('Update Bcc recipients')
              .setOnClickAction(CardService.newAction()
                  .setFunctionName('updateBccRecipients')));
      return card.addSection(cardSection).build();
    }

    /**
     * Updates the subject field of the current email when the user clicks
     * on "Update subject" in the compose UI.
     *
     * Note: This is not the compose action that builds a compose UI, but
     * rather an action taken when the user interacts with the compose UI.
     *
     * @return {UpdateDraftActionResponse}
     */
    function applyUpdateSubjectAction() {
      // Get the new subject field of the email.
      // This function is not shown in this example.
      var subject = getSubject();
      var response = CardService.newUpdateDraftActionResponseBuilder()
          .setUpdateDraftSubjectAction(CardService.newUpdateDraftSubjectAction()
              .addUpdateSubject(subject))
          .build();
      return response;
    }

    /**
     * Updates the To recipients of the current email when the user clicks
     * on "Update To recipients" in the compose UI.
     *
     * Note: This is not the compose action that builds a compose UI, but
     * rather an action taken when the user interacts with the compose UI.
     *
     * @return {UpdateDraftActionResponse}
     */
    function applyUpdateToRecipientsAction() {
      // Get the new To recipients of the email.
      // This function is not shown in this example.
      var toRecipients = getToRecipients();
      var response = CardService.newUpdateDraftActionResponseBuilder()
          .setUpdateDraftToRecipientsAction(CardService.newUpdateDraftToRecipientsAction()
              .addUpdateToRecipients(toRecipients))
          .build();
      return response;
    }

    /**
     * Updates the Cc recipients  of the current email when the user clicks
     * on "Update Cc recipients" in the compose UI.
     *
     * Note: This is not the compose action that builds a compose UI, but
     * rather an action taken when the user interacts with the compose UI.
     *
     * @return {UpdateDraftActionResponse}
     */
    function applyUpdateCcRecipientsAction() {
      // Get the new Cc recipients of the email.
      // This function is not shown in this example.
      var ccRecipients = getCcRecipients();
      var response = CardService.newUpdateDraftActionResponseBuilder()
          .setUpdateDraftCcRecipientsAction(CardService.newUpdateDraftCcRecipientsAction()
              .addUpdateToRecipients(ccRecipients))
          .build();
      return response;
    }

    /**
     * Updates the Bcc recipients  of the current email when the user clicks
     * on "Update Bcc recipients" in the compose UI.
     *
     * Note: This is not the compose action that builds a compose UI, but
     * rather an action taken when the user interacts with the compose UI.
     *
     * @return {UpdateDraftActionResponse}
     */
    function applyUpdateBccRecipientsAction() {
      // Get the new Bcc recipients of the email.
      // This function is not shown in this example.
      var bccRecipients = getBccRecipients();
      var response = CardService.newUpdateDraftActionResponseBuilder()
          .setUpdateDraftBccRecipientsAction(CardService.newUpdateDraftBccRecipientsAction()
              .addUpdateToRecipients(bccRecipients))
          .build();
      return response;
    }

Esempio 2

Il seguente snippet di codice mostra come creare un'interfaccia utente di composizione che inserisce immagini nell'email in bozza corrente.

    /**
     * Compose trigger function that fires when the compose UI is
     * requested. Builds and returns a compose UI for inserting images.
     *
     * @param {event} e The compose trigger event object. Not used in
     *         this example.
     * @return {Card[]}
     */
    function getInsertImageComposeUI(e) {
      return [buildImageComposeCard()];
    }

    /**
     * Build a card to display images from a third-party source.
     *
     * @return {Card}
     */
    function buildImageComposeCard() {
      // Get a short list of image URLs to display in the UI.
      // This function is not shown in this example.
      var imageUrls = getImageUrls();

      var card = CardService.newCardBuilder();
      var cardSection = CardService.newCardSection().setHeader('My Images');
      for (var i = 0; i < imageUrls.length; i++) {
        var imageUrl = imageUrls[i];
        cardSection.addWidget(
            CardService.newImage()
                .setImageUrl(imageUrl)
                .setOnClickAction(CardService.newAction()
                      .setFunctionName('applyInsertImageAction')
                      .setParameters({'url' : imageUrl})));
      }
      return card.addSection(cardSection).build();
    }

    /**
     * Adds an image to the current draft email when the image is clicked
     * in the compose UI. The image is inserted at the current cursor
     * location. If any content of the email draft is currently selected,
     * it is deleted and replaced with the image.
     *
     * Note: This is not the compose action that builds a compose UI, but
     * rather an action taken when the user interacts with the compose UI.
     *
     * @param {event} e The incoming event object.
     * @return {UpdateDraftActionResponse}
     */
    function applyInsertImageAction(e) {
      var imageUrl = e.parameters.url;
      var imageHtmlContent = '<img style=\"display: block\" src=\"'
           + imageUrl + '\"/>';
      var response = CardService.newUpdateDraftActionResponseBuilder()
          .setUpdateDraftBodyAction(CardService.newUpdateDraftBodyAction()
              .addUpdateContent(
                  imageHtmlContent,
                  CardService.ContentType.MUTABLE_HTML)
              .setUpdateType(
                  CardService.UpdateDraftBodyType.IN_PLACE_INSERT))
          .build();
      return response;
    }