Selecionar itens em uma apresentação

A seleção é o conteúdo que tem foco em uma página de apresentação aberta, como um intervalo de texto destacado ou uma tabela. Este guia descreve como acessar e definir a seleção em uma apresentação ativa usando o Apps Script.

Um script só pode acessar a seleção do usuário que o executa.

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

Leia 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).

A enumeração SelectionType representa o tipo específico de objetos selecionados. Por exemplo, se o usuário tiver selecionado algum 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. Por exemplo, 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 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 getSelection() e getCurrentPage() da seguinte maneira:

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

A página atual pode ser um destes tipos:

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

Ler a seleção com base no tipo de seleção

O exemplo a seguir mostra como usar o tipo de seleção para ler a seleção atual de uma 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;
}

Ler seleções de texto

Leia a seleção de texto usando o Selection.getTextRange(). Há dois tipos de seleção de texto:

  • Seleção de intervalo: se uma forma contém o texto "Olá" e "Ol" está selecionado, o intervalo retornado tem startIndex=0 e endIndex=2.
  • Seleção de cursor: se uma forma contém o texto "Olá" e o cursor está depois de "O" ("O|lá"), o intervalo retornado é 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 mudanças de seleção que o script faz na apresentação são refletidas em operações de seleção subsequentes durante a execução do script.

As mudanças de seleção são refletidas no navegador do usuário somente após a conclusão da execução do script 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 selectAsCurrentPage() método. Esse método remove qualquer elemento de página, página ou seleção de texto anterior. Portanto, usar esse método na página atual permite desmarcar 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
//

Selecionar um elemento de página

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

Os métodos select() e select(true) são equivalentes.

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 de página

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

Transformar a seleção

As edições que o script realiza 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 na edição para que apenas a forma B seja selecionada.

O exemplo a seguir mostra como a seleção pode ser transformada pela manipulação de 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]
//

Selecionar texto

O texto contido em uma forma ou em uma célula de tabela pode ser selecionado usando 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 de tabela, essa célula e a tabela delimitadora 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 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");
// 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 em um 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 em um 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 textuais

O exemplo a seguir mostra como a seleção pode ser transformada editando 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
//

Desmarcar

Não há métodos explícitos para desmarcar texto ou elementos de 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 todas 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 de página

O exemplo a seguir mostra como desmarcar todas as seleções atuais em uma página selecionando um elemento de página, removendo assim 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();