Como selecionar itens em uma apresentação

A seleção é aquela que está selecionada em uma página de apresentação aberta. como um trecho de texto destacado ou uma tabela. Este guia ensina como obter e defina a seleção em uma apresentação ativa usando o Apps Script.

A seleção é um resumo do que era quando o script foi iniciado. Se o usuário e a seleção for alterada enquanto o script estiver em execução, essas alterações não serão refletidas.

Seleções e tipo de seleção

Você pode ler a seleção usando o Seleção . A classe tem vários métodos para buscar os objetos selecionados com base na tipo dos objetos selecionados.

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

Você também pode 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 de delimitação é a página ativa atual; para recuperar a página, use selection.getCurrentPage().

Como ler a seleção

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

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

Como ler a página atual

Para recuperar a Page atual que o está visualizando, use o getSelection() e getCurrentPage() da seguinte forma:

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

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

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

Como ler a seleção com base no tipo

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

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

Você pode ler a seleção de texto usando o Selection.getTextRange(). Há dois tipos de seleção de texto:

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

Modificar a seleção

O script pode modificar a seleção do usuário. Todas as alterações de seleção que o script faz na apresentação são refletidas nas operações de seleção subsequentes durante a execução do script.

As alterações de seleção são refletidas no navegador do usuário somente após o script a execução é concluída ou quando Presentation.saveAndClose() é chamado.

Seleção da página atual

Uma página na apresentação ativa pode ser selecionada como a página atual chamando método selectAsCurrentPage(). Esse método remove qualquer elemento de página, página ou seleção de texto anterior. Então, usando este método na página atual permite que você desmarque todas as seleções atuais 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
//

Seleção de um elemento de página

Para selecionar um elemento em uma página, use o método PageElement.select(). Isso também desmarca todos 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
//

Como selecionar vários elementos de página

Para adicionar outros elementos de página à seleção, use o método PageElement.select(false). Todos os elementos da página 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
//

Como transformar a seleção

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

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

O exemplo a seguir mostra como transformar a seleção ao manipular elementos de página selecionados.

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 célula da tabela pode ser selecionado com o TextRange.select(). Se o texto estiver contido em uma forma, essa forma também será selecionada. Se o texto estiver contido em uma célula da tabela, essa célula e a respectiva célula estão selecionados.

Isso também define a página principal 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 do cursor em uma forma

O exemplo a seguir mostra como fazer uma seleção de cursor 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');
  // 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 da tabela

O exemplo a seguir mostra como fazer uma seleção de intervalo no texto contido em uma célula da 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 do cursor em TableCell

O exemplo a seguir mostra como fazer uma seleção de cursor no texto contido em uma célula da 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 da seleção com edições de texto

O exemplo a seguir mostra como a seleção pode ser transformada editando o 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 desmarcar elementos de texto ou página. No entanto, resultado pode ser alcançado usando o Page.selectAsCurrentPage() ou pageElement.select().

Selecionar uma página atual

O exemplo a seguir mostra como desmarcar qualquer seleção atual em uma página definindo essa página como a página 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();

Selecione um elemento de página

O exemplo a seguir mostra como desmarcar qualquer seleção atual em uma página selecionando um elemento da página e, assim, 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();