Estensione dell'interfaccia utente di scrittura con le azioni di scrittura

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

Accesso all'interfaccia utente di scrittura del componente aggiuntivo

Esistono due modi per visualizzare l'interfaccia di scrittura di un componente aggiuntivo. Il primo modo è iniziare a scrivere una nuova bozza o una nuova risposta mentre il componente aggiuntivo è già aperto. Il secondo modo è avviare il componente aggiuntivo mentre scrivi una bozza.

In entrambi i casi, il componente aggiuntivo esegue la funzione di attivazione di composizione corrispondente, definita nel manifest del componente aggiuntivo. L'attivatore di scrittura crea l'interfaccia utente di scrittura per l'azione di scrittura, che verrà poi mostrata all'utente da Gmail.

Creazione di un componente aggiuntivo per la scrittura

Puoi aggiungere la funzionalità di scrittura a un componente aggiuntivo seguendo questa procedura generale:

  1. Aggiungi il campo gmail.composeTrigger al manifest del progetto di script del componente aggiuntivo e aggiorna gli ambiti del file manifest in modo da includere quelli necessari per le azioni di scrittura.
  2. Implementare una funzione trigger di scrittura che crei una UI di scrittura quando l'attivatore si attiva. Le funzioni trigger di scrittura restituiscono un singolo oggetto Card o un array di oggetti Card che compongono l'interfaccia utente di scrittura per l'azione di scrittura.
  3. Implementare le funzioni di callback associate necessarie per reagire alle interazioni dell'interfaccia utente di scrittura dell'utente. Queste funzioni non sono l'azione di scrittura stessa (che determina solo la visualizzazione della UI di scrittura), ma le singole funzioni che regolano ciò che accade quando vengono selezionati diversi elementi della UI di scrittura. Ad esempio, una scheda dell'interfaccia utente contenente un pulsante di solito è associata a una funzione di callback che viene eseguita quando un utente fa clic sul pulsante. La funzione di callback per i widget che aggiornano i contenuti della bozza del messaggio dovrebbe restituire un oggetto UpdateDraftActionResponse.

Crea funzione trigger

L'interfaccia utente di scrittura di un componente aggiuntivo è realizzata allo stesso modo dell'interfaccia utente dei messaggi del componente aggiuntivo, utilizzando il servizio di schede di Apps Script per creare schede e inserirle con widget.

Devi implementare il gmail.composeTrigger.selectActions[].runFunction che definisci nel tuo manifest. La funzione trigger di scrittura deve restituire un singolo oggetto Card o un array di oggetti Card che compongono l'interfaccia utente di scrittura per tale azione. Queste funzioni sono molto simili a quelle di attivazione contestuale e dovrebbero creare schede nello stesso modo.

Componi oggetti evento di trigger

Quando è selezionata un'azione di scrittura, questa esegue la funzione di trigger di composizione corrispondente e trasmette la funzione come un oggetto evento sotto forma di parametro. L'oggetto evento può trasferire informazioni sul contesto del componente aggiuntivo e sulla bozza in fase di composizione nella funzione trigger.

Per maggiori dettagli 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 trigger di composizione viene compilato con gli elenchi dei destinatari dell'email che viene composta.

Inserimento di contenuti in bozze attive

In genere, una UI di scrittura del componente aggiuntivo di Google Workspace fornisce le opzioni e i controlli utente che consentono di scrivere un messaggio. Per questi casi d'uso, una volta che l'utente ha effettuato delle selezioni nell'interfaccia utente, il componente aggiuntivo interpreta le selezioni e aggiorna di conseguenza la bozza dell'email di lavoro corrente.

Per semplificare l'aggiornamento della bozza corrente dell'email, il servizio di carte è stato esteso con i seguenti corsi:

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

Esempio 1

Il seguente snippet di codice mostra come creare un'interfaccia utente di scrittura che aggiorni l'oggetto e i destinatari A, Cc e Ccn della bozza dell'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

Lo snippet di codice riportato di seguito mostra come creare un'interfaccia utente di composizione che inserisce immagini nella bozza dell'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 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;
    }