Como selecionar itens em uma apresentação

A seleção é o que está selecionado no momento em uma página de apresentação aberta, como um trecho de texto destacado ou uma tabela. Este guia mostra como receber e definir a seleção em uma apresentação ativa usando o Apps Script.

A seleção é um instantâneo do que era quando o script foi iniciado. Se o usuário clicar e a seleção mudar enquanto o script estiver em execução, essas mudanças não serão refletidas.

Seleções e tipo de seleção

É possível ler a seleção usando a classe Selection. A classe tem vários métodos para receber os objetos selecionados com base no tipo de objeto(s) selecionado(s).

O enum SelectionType representa o tipo específico de objetos selecionados. Por exemplo, se o usuário tiver selecionado um texto em uma forma, o tipo de seleção será TEXT. Nesse caso, é possível recuperar o intervalo de texto selecionado usando o método selection.getTextRange().

Também é possível recuperar o objeto que contém a seleção. Continuando o exemplo acima, você pode recuperar a forma que contém o texto selecionado usando selection.getPageElementRange().getPageElements()[0]. Da mesma forma, a página que contém a forma delimitadora é a página ativa atual. Para recuperar essa página, use selection.getCurrentPage().

Ler a seleção

Para ler a seleção, use o método Presentation.getSelection() conforme mostrado no exemplo a seguir:

slides/selection/selection.gs
const selection = SlidesApp.getActivePresentation().getSelection();

Ler a página atual

Para recuperar a página atual que o usuário está visualizando, use os métodos getSelection() e getCurrentPage() da seguinte maneira:

slides/selection/selection.gs
const currentPage = SlidesApp.getActivePresentation().getSelection().getCurrentPage();

A página atual pode ser de um dos seguintes tipos:

A página atual pode ter um ou mais objetos selecionados, e o SelectionType determina o tipo de seleção.

Leitura da seleção com base no tipo dela

O exemplo a seguir mostra como usar o tipo de seleção para ler a seleção atual de maneira adequada ao tipo.

slides/selection/selection.gs
const selection = SlidesApp.getActivePresentation().getSelection();
const selectionType = selection.getSelectionType();
let currentPage;
switch (selectionType) {
  case SlidesApp.SelectionType.NONE:
    console.log('Nothing selected');
    break;
  case SlidesApp.SelectionType.CURRENT_PAGE:
    currentPage = selection.getCurrentPage();
    console.log('Selection is a page with ID: ' + currentPage.getObjectId());
    break;
  case SlidesApp.SelectionType.PAGE_ELEMENT:
    const pageElements = selection.getPageElementRange().getPageElements();
    console.log('There are ' + pageElements.length + ' page elements selected.');
    break;
  case SlidesApp.SelectionType.TEXT:
    const tableCellRange = selection.getTableCellRange();
    if (tableCellRange !== null) {
      const tableCell = tableCellRange.getTableCells()[0];
      console.log('Selected text is in a table at row ' +
        tableCell.getRowIndex() + ', column ' +
        tableCell.getColumnIndex());
    }
    const textRange = selection.getTextRange();
    if (textRange.getStartIndex() === textRange.getEndIndex()) {
      console.log('Text cursor position: ' + textRange.getStartIndex());
    } else {
      console.log('Selection is a text range from: ' + textRange.getStartIndex() + ' to: ' +
        textRange.getEndIndex() + ' is selected');
    }
    break;
  case SlidesApp.SelectionType.TABLE_CELL:
    const tableCells = selection.getTableCellRange().getTableCells();
    const table = tableCells[0].getParentTable();
    console.log('There are ' + tableCells.length + ' table cells selected.');
    break;
  case SlidesApp.SelectionType.PAGE:
    const pages = selection.getPageRange().getPages();
    console.log('There are ' + pages.length + ' pages selected.');
    break;
  default:
    break;
}

Leitura de seleções de texto

É possível ler a seleção de texto usando o método Selection.getTextRange(). Há dois tipos de seleção de texto:

  • Seleção de intervalo: se uma forma contiver o texto "Hello" e "He" for selecionado, o intervalo retornado terá startIndex=0 e endIndex=2.
  • Seleção do cursor: se uma forma contiver o texto "Hello" e o cursor estiver depois de "H" ("H|ello"), o intervalo retornado será vazio com startIndex=1 e endIndex=1.

Modificar a seleção

O script pode modificar a seleção do usuário. Todas as mudanças feitas pelo script na apresentação são refletidas em operações de seleção subsequentes durante a execução do script.

As mudanças na seleção são refletidas no navegador do usuário somente depois que a execução do script é concluída ou quando Presentation.saveAndClose() é chamado.

Selecionar a página atual

Uma página na apresentação ativa pode ser selecionada como a página atual chamando o método selectAsCurrentPage(). Esse método remove qualquer elemento de página, página ou seleção de texto anterior. Usar esse método na página atual permite cancelar a seleção de qualquer item na página. Exemplo:

slides/selection/selection.gs
// Select the first slide as the current page selection and remove any previous selection.
  const selection = SlidesApp.getActivePresentation().getSelection();
  const slide = SlidesApp.getActivePresentation().getSlides()[0];
  slide.selectAsCurrentPage();
// State of selection
//
// selection.getSelectionType() = SlidesApp.SelectionType.CURRENT_PAGE
// selection.getCurrentPage() = slide
//

Selecionar um elemento da página

Para selecionar um elemento em uma página, use o método PageElement.select(). Isso também desmarca os elementos da página selecionados anteriormente.

Exemplo:

slides/selection/selection.gs
  const slide = SlidesApp.getActivePresentation().getSlides()[0];
  const pageElement = slide.getPageElements()[0];
  // Only select this page element and remove any previous selection.
  pageElement.select();
// State of selection
//
// selection.getSelectionType() = SlidesApp.SelectionType.PAGE_ELEMENT
// selection.getCurrentPage() = slide
// selection.getPageElementRange().getPageElements()[0] = pageElement
//

Selecionar vários elementos da página

Para anexar outros elementos de página à seleção, use o método PageElement.select(false). Todos os elementos precisam estar na página atual.

slides/selection/selection.gs
  const slide = SlidesApp.getActivePresentation().getSlides()[0];
  // First select the slide page, as the current page selection.
  slide.selectAsCurrentPage();
  // Then select all the page elements in the selected slide page.
  const pageElements = slide.getPageElements();
  for (let i = 0; i < pageElements.length; i++) {
    pageElements[i].select(false);
  }
// State of selection
//
// selection.getSelectionType() = SlidesApp.SelectionType.PAGE_ELEMENT
// selection.getCurrentPage() = slide
// selection.getPageElementRange().getPageElements() = pageElements
//

Transformar a seleção

As edições feitas pelo script podem transformar a seleção atual, de modo que o que está selecionado muda como resultado da edição. Exemplo:

  1. Suponha que você tenha duas formas A e B selecionadas.
  2. Em seguida, o script remove a forma A.
  3. Como resultado, a seleção é transformada em relação à edição para que apenas a forma B seja selecionada.

O exemplo a seguir mostra como a seleção pode ser transformada manipulando elementos da página selecionada.

slides/selection/selection.gs
  const slide = SlidesApp.getActivePresentation().getSlides()[0];
  const shape1 = slide.getPageElements()[0].asShape();
  const shape2 = slide.getPageElements()[1].asShape();
  // Select both the shapes.
  shape1.select();
  shape2.select(false);
  // State of selection
  //
  // selection.getSelectionType() = SlidesApp.SelectionType.PAGE_ELEMENT
  // selection.getCurrentPage() = slide
  // selection.getPageElementRange().getPageElements() = [shape1, shape2]
  //
  // Remove one shape.
  shape2.remove();
// State of selection
//
// selection.getSelectionType() = SlidesApp.SelectionType.PAGE_ELEMENT
// selection.getCurrentPage() = slide
// selection.getPageElementRange().getPageElements() = [shape1]
//

Como selecionar texto

O texto contido em uma forma ou em uma célula de tabela pode ser selecionado usando o método TextRange.select(). Se o texto estiver em uma forma, ela também será selecionada. Se o texto estiver em uma célula de tabela, essa célula e a tabela que a contém serão selecionadas.

Isso também define a página mãe como a página atual.

Seleção de intervalo em uma forma

O exemplo a seguir mostra como fazer uma seleção de intervalo no texto contido em uma forma.

slides/selection/selection.gs
  const slide = SlidesApp.getActivePresentation().getSlides()[0];
  const shape = slide.getPageElements()[0].asShape();
  shape.getText().setText('Hello');
  // Range selection: Select the text range 'He'.
  shape.getText().getRange(0, 2).select();
// State of selection
//
// selection.getSelectionType() = SlidesApp.SelectionType.TEXT
// selection.getCurrentPage() = slide
// selection.getPageElementRange().getPageElements()[0] = shape
// selection.getTextRange().getStartIndex() = 0
// selection.getTextRange().getEndIndex() = 2
//

Seleção de cursor em uma forma

O exemplo a seguir mostra como fazer uma seleção de cursor em um texto contido em uma forma.

slides/selection/selection.gs
  const slide = SlidesApp.getActivePresentation().getSlides()[0];
  const shape = slide.getPageElements()[0].asShape();
  shape.getText().setText('Hello');
  // Cursor selection: Place the cursor after 'H' like 'H|ello'.
  shape.getText().getRange(1, 1).select();
// State of selection
//
// selection.getSelectionType() = SlidesApp.SelectionType.TEXT
// selection.getCurrentPage() = slide
// selection.getPageElementRange().getPageElements()[0] = shape
// selection.getTextRange().getStartIndex() = 1
// selection.getTextRange().getEndIndex() = 1
//

Seleção de intervalo em uma célula de tabela

O exemplo a seguir mostra como fazer uma seleção de intervalo no texto contido em uma célula de tabela.

slides/selection/selection.gs
  const slide = SlidesApp.getActivePresentation().getSlides()[0];
  const table = slide.getPageElements()[0].asTable();
  const tableCell = table.getCell(0, 1);
  tableCell.getText().setText('Hello');
  // Range selection: Select the text range 'He'.
  tableCell.getText().getRange(0, 2).select();
// State of selection
//
// selection.getSelectionType() = SlidesApp.SelectionType.TEXT
// selection.getCurrentPage() = slide
// selection.getPageElementRange().getPageElements()[0] = table
// selection.getTableCellRange().getTableCells()[0] = tableCell
// selection.getTextRange().getStartIndex() = 0
// selection.getTextRange().getEndIndex() = 2
//

Seleção de cursor em TableCell

O exemplo a seguir mostra como fazer uma seleção de cursor no texto contido em uma célula de tabela.

slides/selection/selection.gs
  const slide = SlidesApp.getActivePresentation().getSlides()[0];
  const table = slide.getPageElements()[0].asTable();
  const tableCell = table.getCell(0, 1);
  tableCell.getText().setText('Hello');
  // Cursor selection: Place the cursor after 'H' like 'H|ello'.
  tableCell.getText().getRange(1, 1).select();
// State of selection
//
// selection.getSelectionType() = SlidesApp.SelectionType.TEXT
// selection.getCurrentPage() = slide
// selection.getPageElementRange().getPageElements()[0] = table
// selection.getTableCellRange().getTableCells()[0] = tableCell
// selection.getTextRange().getStartIndex() = 1
// selection.getTextRange().getEndIndex() = 1
//

Transformação de seleção com edições de texto

O exemplo a seguir mostra como a seleção pode ser transformada ao editar o texto selecionado.

slides/selection/selection.gs
  const slide = SlidesApp.getActivePresentation().getSlides()[0];
  const shape = slide.getPageElements()[0].asShape();
  const textRange = shape.getText();
  textRange.setText('World');
  // Select all the text 'World'.
  textRange.select();
  // State of selection
  //
  // selection.getSelectionType() = SlidesApp.SelectionType.TEXT
  // selection.getCurrentPage() = slide
  // selection.getPageElementRange().getPageElements()[0] = shape
  // selection.getTextRange().getStartIndex() = 0
  // selection.getTextRange().getEndIndex() = 6
  //
  // Add some text to the shape, and the selection will be transformed.
  textRange.insertText(0, 'Hello ');

// State of selection
//
// selection.getSelectionType() = SlidesApp.SelectionType.TEXT
// selection.getCurrentPage() = slide
// selection.getPageElementRange().getPageElements()[0] = shape
// selection.getTextRange().getStartIndex() = 0
// selection.getTextRange().getEndIndex() = 12
//

Desmarcando

Não há métodos explícitos para cancelar a seleção de texto ou elementos da página. No entanto, esse resultado pode ser alcançado usando os métodos Page.selectAsCurrentPage() ou pageElement.select().

Selecionar uma página atual

O exemplo a seguir mostra como desmarcar as seleções atuais em uma página definindo essa página como a atual.

slides/selection/selection.gs
// Unselect one or more page elements already selected.
//
// In case one or more page elements in the first slide are selected, setting the
// same (or any other) slide page as the current page would do the unselect.
//
  const slide = SlidesApp.getActivePresentation().getSlides()[0];
  slide.selectAsCurrentPage();

Selecionar um elemento da página

O exemplo a seguir mostra como cancelar a seleção de uma página ao selecionar um elemento dela, removendo todos os outros itens da seleção.

slides/selection/selection.gs
// Unselect one or more page elements already selected.
//
// In case one or more page elements in the first slide are selected,
// selecting any pageElement in the first slide (or any other pageElement) would
// do the unselect and select that pageElement.
//
  const slide = SlidesApp.getActivePresentation().getSlides()[0];
  slide.getPageElements()[0].select();