---
title: "Selecting & copying — Vue"
description: "Let people select text with the pointer or a finger, select text from code, copy it, and show a menu next to the selection."
framework: "Vue"
source: "https://www.embedpdf.com/docs/headless/vue/text/selection"
---

# Selecting & copying

The selection plugin lets people select text with the mouse or a finger, and lets your code select the
same text. Register `interactionPlugin()` and `selectionPlugin()`, and put `<SelectionLayer>`
above the page:

**`App.vue`**

```vue
<script setup lang="ts">
import { DocumentGate, Viewer } from '@embedpdf/vue/runtime';
import type { OpenInput } from '@embedpdf/vue/runtime';
import { Stage, stagePlugin } from '@embedpdf/vue/stage';
import { RenderLayer, renderPlugin } from '@embedpdf/vue/render';
import { interactionPlugin } from '@embedpdf/vue/interaction';
import { SelectionLayer, selectionPlugin } from '@embedpdf/vue/selection';
import { localEngine } from '@embedpdf/engine';
import SelectTitle from './SelectTitle.vue';

import '../basic.css';

const engine = localEngine();
const plugins = [stagePlugin(), renderPlugin(), interactionPlugin(), selectionPlugin()];

const ebook = async (): Promise<OpenInput> => {
  const response = await fetch('https://snippet.embedpdf.com/ebook.pdf');
  return { kind: 'bytes', id: 'ebook', bytes: new Uint8Array(await response.arrayBuffer()) };
};
</script>

<template>
  <Viewer :engine="engine" :plugins="plugins" :initial-documents="[{ source: ebook }]">
    <DocumentGate>
      <template #fallback><p class="loading">Loading…</p></template>
      <SelectTitle />
      <Stage class="stage">
        <template #page>
          <RenderLayer />
          <SelectionLayer />
        </template>
      </Stage>
    </DocumentGate>
  </Viewer>
</template>
```

**`basic.css`**

```css
/* Colors */
:root {
  --muted: #5a6b92;
  --line: #e6eaf2;
  --canvas: #f7f9fc;
  --shadow: rgb(7 32 76 / 0.04);
}

/* The pages */
.stage {
  height: 460px;
  border: 1px solid var(--line);
  border-radius: 14px;
  background: var(--canvas);
  box-shadow:
    0 1px 2px var(--shadow),
    0 18px 40px -28px rgb(7 32 76 / 0.28);
}

.loading {
  margin: 0;
  padding: 24px 0;
  text-align: center;
  font-size: 13px;
  color: var(--muted);
}
```

**`SelectTitle.vue`**

```vue
<script setup lang="ts">
import { computed, watch } from 'vue';
import { usePageList } from '@embedpdf/vue/runtime';
import { useSelection } from '@embedpdf/vue/selection';

// Something to see on load: the title on the cover, selected from code.
const selection = useSelection();
const pages = usePageList();
const cover = computed(() => pages.value[0]?.ref);

watch(
  cover,
  (page) => {
    if (page) selection.select({ page, start: 10, count: 52 });
  },
  { immediate: true },
);
</script>

<template></template>
```

> **Try it:** the cover's title starts out selected from code. Drag over text, double-click a word,
> or triple-click a line. A selection can run from one page onto the next. On a touch screen,
> long-press a word and drag the handles.

`interactionPlugin()` is the input system every tool shares: the Stage passes the pointer to it,
the selection plugin handles it, and `<SelectionLayer>` draws the result. So you can restyle or
replace the highlight without touching how selecting works.

Selecting uses where the characters are on the page, not the text itself. Nothing reads the page's
text until your code asks for it, and a document can allow selecting while it forbids copying (see
[Permissions](#permissions)).

## Select text from code

`useSelection()` does from code what the pointer does, and the highlight follows:

**`App.vue`**

```vue
<script setup lang="ts">
import { DocumentGate, Viewer } from '@embedpdf/vue/runtime';
import type { OpenInput } from '@embedpdf/vue/runtime';
import { Stage, stagePlugin } from '@embedpdf/vue/stage';
import { RenderLayer, renderPlugin } from '@embedpdf/vue/render';
import { interactionPlugin } from '@embedpdf/vue/interaction';
import { SelectionLayer, selectionPlugin } from '@embedpdf/vue/selection';
import { localEngine } from '@embedpdf/engine';
import SelectionToolbar from './SelectionToolbar.vue';

import '../programmatic.css';

const engine = localEngine();
const plugins = [stagePlugin(), renderPlugin(), interactionPlugin(), selectionPlugin()];

const ebook = async (): Promise<OpenInput> => {
  const response = await fetch('https://snippet.embedpdf.com/ebook.pdf');
  return { kind: 'bytes', id: 'ebook', bytes: new Uint8Array(await response.arrayBuffer()) };
};
</script>

<template>
  <Viewer :engine="engine" :plugins="plugins" :initial-documents="[{ source: ebook }]">
    <DocumentGate>
      <template #fallback><p class="loading">Loading…</p></template>
      <SelectionToolbar />
      <Stage class="stage">
        <template #page>
          <RenderLayer />
          <SelectionLayer />
        </template>
      </Stage>
    </DocumentGate>
  </Viewer>
</template>
```

**`programmatic.css`**

```css
/* Colors */
:root {
  --ink: #1a2748;
  --muted: #5a6b92;
  --line: #e6eaf2;
  --line-strong: #dce8fc;
  --surface: #ffffff;
  --tint: #f3f7fe;
  --canvas: #f7f9fc;
  --focus: #7db6ff;
  --shadow: rgb(7 32 76 / 0.04);
}

/* The buttons, above the pages */
.toolbar {
  display: flex;
  flex-wrap: wrap;
  align-items: center;
  gap: 8px;
  margin-bottom: 14px;
}

.button {
  font: inherit;
  font-size: 13px;
  font-weight: 550;
  line-height: 1;
  color: var(--ink);
  background: var(--surface);
  border: 1px solid var(--line);
  border-radius: 9px;
  padding: 8px 13px;
  cursor: pointer;
  white-space: nowrap;
  box-shadow: 0 1px 2px var(--shadow);
  transition:
    background-color 0.15s ease,
    border-color 0.15s ease;
}

.button:hover {
  background: var(--tint);
  border-color: var(--line-strong);
}

.button:active {
  transform: translateY(1px);
}

.button:focus-visible {
  outline: 2px solid var(--focus);
  outline-offset: 2px;
}

.button:disabled {
  opacity: 0.45;
  cursor: not-allowed;
  transform: none;
}

/* What is selected now, pushed to the right while there's room */
.badge {
  margin-left: auto;
  font-size: 12.5px;
  font-weight: 600;
  color: var(--muted);
  background: var(--tint);
  border: 1px solid var(--line);
  border-radius: 8px;
  padding: 6px 11px;
  white-space: nowrap;
  font-variant-numeric: tabular-nums;
}

/* The pages */
.stage {
  height: 420px;
  border: 1px solid var(--line);
  border-radius: 14px;
  background: var(--canvas);
  box-shadow:
    0 1px 2px var(--shadow),
    0 18px 40px -28px rgb(7 32 76 / 0.28);
}

.loading {
  margin: 0;
  padding: 24px 0;
  text-align: center;
  font-size: 13px;
  color: var(--muted);
}
```

**`SelectionToolbar.vue`**

```vue
<script setup lang="ts">
import { computed, watch } from 'vue';
import { usePageList } from '@embedpdf/vue/runtime';
import { useSelection, useSelectionState } from '@embedpdf/vue/selection';

// On the cover: the characters of its title, and a point on its word "Viewers", in page coordinates.
const TITLE = { start: 10, count: 52 };
const POINT = { x: 260, y: 242 };

// Every button selects on the cover, the first page: by its ref, or by its index, 0.
const selection = useSelection();
const { hasSelection, range, pages } = useSelectionState();
const pageList = usePageList();
const cover = computed(() => pageList.value[0]?.ref);

// The title is selected on load.
watch(
  cover,
  (page) => {
    if (page) selection.select({ page, ...TITLE });
  },
  { immediate: true },
);

function selectTitle() {
  if (cover.value) selection.select({ page: cover.value, ...TITLE });
}

const summary = computed(() => {
  if (pages.value.length > 1) return `On ${pages.value.length} pages`;
  if (range.value) return `${range.value.end.index - range.value.start.index} characters`;
  return 'Nothing selected';
});
</script>

<template>
  <div class="toolbar">
    <button
      type="button"
      class="button"
      :disabled="!selection.canSelect() || !cover"
      @click="selectTitle"
    >
      Title
    </button>
    <button
      type="button"
      class="button"
      :disabled="!selection.canSelect()"
      @click="selection.selectWordAt(0, POINT)"
    >
      Word
    </button>
    <button
      type="button"
      class="button"
      :disabled="!selection.canSelect()"
      @click="selection.selectLineAt(0, POINT)"
    >
      Line
    </button>
    <button
      type="button"
      class="button"
      :disabled="!selection.canSelect()"
      @click="selection.selectPage(0)"
    >
      Page
    </button>
    <button
      type="button"
      class="button"
      :disabled="!selection.canSelect()"
      @click="selection.selectAll()"
    >
      Everything
    </button>
    <button type="button" class="button" :disabled="!hasSelection" @click="selection.clear()">
      Clear
    </button>
    <output class="badge">{{ summary }}</output>
  </div>
</template>
```

```ts
selection.select({ page: page.ref, start: 20, count: 40 }); // 40 characters on one page
selection.selectWordAt(page.ref, { x: 120, y: 80 }); // the word at a point
selection.selectLineAt(page.ref, { x: 120, y: 80 }); // the line at a point
selection.selectPage(page.ref);
selection.selectAll();
selection.clear();
```

A search result is already a range, so selecting it takes no conversion:

```ts
selection.select(hit); // { page, start, count }
```

For a selection across pages, give where it starts and where it ends:

```ts
selection.select({
  start: { page: firstPage.ref, index: 120 },
  end: { page: lastPage.ref, index: 35 },
});
```

Ranges include `start` and stop before `end`, and they count characters as the page stores them,
not JavaScript string positions. `selection.extendTo(page.ref, point)` grows the current selection
to a point on a page, as dragging a handle does. Every method that takes a page takes its ref or its
index: `selection.selectPage(0)` selects the first page.

## Show the selection in your UI

`useSelectionState()` gives you what to show, and your component updates when it
changes:

**`highlight-button.vue`**

```vue
<script setup lang="ts">
import { useSelectionState } from '@embedpdf/vue/selection';

const { hasSelection, isSelecting, pages } = useSelectionState();
</script>

<template>
  <button :disabled="!hasSelection">Highlight</button>
</template>
```

**`App.vue`**

```vue
<script setup lang="ts">
import { DocumentGate, Viewer } from '@embedpdf/vue/runtime';
import type { OpenInput } from '@embedpdf/vue/runtime';
import { Stage, stagePlugin } from '@embedpdf/vue/stage';
import { RenderLayer, renderPlugin } from '@embedpdf/vue/render';
import { interactionPlugin } from '@embedpdf/vue/interaction';
import { SelectionLayer, selectionPlugin } from '@embedpdf/vue/selection';
import { localEngine } from '@embedpdf/engine';
import SelectionStatus from './SelectionStatus.vue';
import SelectTitle from './SelectTitle.vue';

import '../state.css';

const engine = localEngine();
const plugins = [stagePlugin(), renderPlugin(), interactionPlugin(), selectionPlugin()];

const ebook = async (): Promise<OpenInput> => {
  const response = await fetch('https://snippet.embedpdf.com/ebook.pdf');
  return { kind: 'bytes', id: 'ebook', bytes: new Uint8Array(await response.arrayBuffer()) };
};
</script>

<template>
  <Viewer :engine="engine" :plugins="plugins" :initial-documents="[{ source: ebook }]">
    <DocumentGate>
      <template #fallback><p class="loading">Loading…</p></template>
      <SelectTitle />
      <SelectionStatus />
      <Stage class="stage">
        <template #page>
          <RenderLayer />
          <SelectionLayer />
        </template>
      </Stage>
    </DocumentGate>
  </Viewer>
</template>
```

**`state.css`**

```css
/* Colors */
:root {
  --ink: #1a2748;
  --muted: #5a6b92;
  --line: #e6eaf2;
  --surface: #ffffff;
  --tint: #f3f7fe;
  --canvas: #f7f9fc;
  --live: #0876fd;
  --shadow: rgb(7 32 76 / 0.04);
}

/* The state, one field per tile: four in a row, two by two on a phone */
.status {
  display: grid;
  grid-template-columns: repeat(auto-fit, minmax(130px, 1fr));
  gap: 8px;
  margin: 0 0 14px;
}

.field {
  min-width: 0;
  background: var(--surface);
  border: 1px solid var(--line);
  border-radius: 10px;
  padding: 8px 11px;
  box-shadow: 0 1px 2px var(--shadow);
  transition:
    border-color 0.15s ease,
    background-color 0.15s ease;
}

/* isSelecting lights up while the pointer is down */
.field[data-live='true'] {
  background: var(--tint);
  border-color: var(--live);
}

.field dt {
  font-family: ui-monospace, monospace;
  font-size: 11.5px;
  color: var(--muted);
}

.field dd {
  margin: 3px 0 0;
  font-size: 14px;
  font-weight: 600;
  color: var(--ink);
  font-variant-numeric: tabular-nums;
  white-space: nowrap;
  overflow: hidden;
  text-overflow: ellipsis;
}

/* The pages */
.stage {
  height: 420px;
  border: 1px solid var(--line);
  border-radius: 14px;
  background: var(--canvas);
  box-shadow:
    0 1px 2px var(--shadow),
    0 18px 40px -28px rgb(7 32 76 / 0.28);
}

.loading {
  margin: 0;
  padding: 24px 0;
  text-align: center;
  font-size: 13px;
  color: var(--muted);
}
```

**`SelectionStatus.vue`**

```vue
<script setup lang="ts">
import { useSelectionState } from '@embedpdf/vue/selection';

// Every field of the selection's state, as it changes.
const { hasSelection, isSelecting, range, pages } = useSelectionState();
</script>

<template>
  <dl class="status">
    <div class="field">
      <dt>hasSelection</dt>
      <dd>{{ String(hasSelection) }}</dd>
    </div>
    <div class="field" :data-live="isSelecting">
      <dt>isSelecting</dt>
      <dd>{{ String(isSelecting) }}</dd>
    </div>
    <div class="field">
      <dt>pages</dt>
      <dd>{{ pages.length === 1 ? '1 page' : `${pages.length} pages` }}</dd>
    </div>
    <div class="field">
      <dt>range</dt>
      <dd>{{ range ? `${range.start.index} → ${range.end.index}` : 'null' }}</dd>
    </div>
  </dl>
</template>
```

**`SelectTitle.vue`**

```vue
<script setup lang="ts">
import { computed, watch } from 'vue';
import { usePageList } from '@embedpdf/vue/runtime';
import { useSelection } from '@embedpdf/vue/selection';

// Something selected on load: the title on the cover.
const selection = useSelection();
const pages = usePageList();
const cover = computed(() => pages.value[0]?.ref);

watch(
  cover,
  (page) => {
    if (page) selection.select({ page, start: 10, count: 52 });
  },
  { immediate: true },
);
</script>

<template></template>
```

> **Try it:** drag over text. `isSelecting` is `true` until you let go, and `pages` counts the pages
> the selection reaches.

Every field is listed under [State](#state). For drawing your own highlight, `selection.listSegments(page.ref)` gives you each selected line as
four corners, turned with the text, and `selection.listRects(page.ref)` a plain box per line.

## Copy the selected text

Reading the text and using the clipboard are two steps:

```ts
const text = await selection.readText();
```

`readText()` reads only the selected characters and gives them to you; it doesn't touch the
clipboard. Lines on different pages are joined with a new line, and with nothing selected it's an
empty string. `readTextInRange(range)` reads any range without selecting it.

For the clipboard, the Vue package has two helpers. `copySelection()` copies from your own
button:

**`copy-button.vue`**

```vue
<script setup lang="ts">
import { copySelection, useSelection, useSelectionState } from '@embedpdf/vue/selection';

const selection = useSelection();
const { hasSelection } = useSelectionState();
</script>

<template>
  <button :disabled="!hasSelection || !selection.canCopy()" @click="copySelection(selection)">
    Copy
  </button>
</template>
```

`<SelectionClipboard>` makes Ctrl+C and the browser's Copy menu work. Mount it once per document view:

**`clipboard.vue`**

```vue
<script setup lang="ts">
import { SelectionClipboard } from '@embedpdf/vue/selection';
</script>

<template>
  <!-- Once per document view: Ctrl+C / Cmd+C and the browser's Copy menu -->
  <SelectionClipboard />
</template>
```

It reads the text as soon as a selection settles, so the browser's copy can answer at once. Set
`prefetch` to `false` to read text only when someone copies. A selection the user [may not
copy](../concepts/permissions) isn't copied by the keys or by the browser's Copy menu, and
it emits `refused`,
so you can say so.

With more than one viewer on a page, pass `target`, a template ref to the element
around one: Ctrl+C and the Copy menu then copy its selection only while focus is inside it, and the
page keeps its own copying everywhere else.

**`App.vue`**

```vue
<script setup lang="ts">
import { DocumentGate, Viewer } from '@embedpdf/vue/runtime';
import type { OpenInput } from '@embedpdf/vue/runtime';
import { Stage, stagePlugin } from '@embedpdf/vue/stage';
import { RenderLayer, renderPlugin } from '@embedpdf/vue/render';
import { interactionPlugin } from '@embedpdf/vue/interaction';
import { SelectionClipboard, SelectionLayer, selectionPlugin } from '@embedpdf/vue/selection';
import { localEngine } from '@embedpdf/engine';
import CopyButton from './CopyButton.vue';
import SelectedText from './SelectedText.vue';
import SelectTitle from './SelectTitle.vue';

import '../copy.css';

const engine = localEngine();
const plugins = [stagePlugin(), renderPlugin(), interactionPlugin(), selectionPlugin()];

const ebook = async (): Promise<OpenInput> => {
  const response = await fetch('https://snippet.embedpdf.com/ebook.pdf');
  return { kind: 'bytes', id: 'ebook', bytes: new Uint8Array(await response.arrayBuffer()) };
};
</script>

<template>
  <Viewer :engine="engine" :plugins="plugins" :initial-documents="[{ source: ebook }]">
    <DocumentGate>
      <template #fallback><p class="loading">Loading…</p></template>
      <SelectTitle />
      <SelectionClipboard />
      <CopyButton />
      <SelectedText />
      <Stage class="stage">
        <template #page>
          <RenderLayer />
          <SelectionLayer />
        </template>
      </Stage>
    </DocumentGate>
  </Viewer>
</template>
```

**`copy.css`**

```css
/* Colors */
:root {
  --ink: #1a2748;
  --text: #3b4b7a;
  --muted: #5a6b92;
  --line: #e6eaf2;
  --line-strong: #dce8fc;
  --surface: #ffffff;
  --tint: #f3f7fe;
  --canvas: #f7f9fc;
  --focus: #7db6ff;
  --shadow: rgb(7 32 76 / 0.04);
}

/* The copy button, above the pages */
.toolbar {
  display: flex;
  flex-wrap: wrap;
  align-items: center;
  gap: 10px;
  margin-bottom: 10px;
}

.button {
  font: inherit;
  font-size: 13px;
  font-weight: 550;
  line-height: 1;
  color: var(--ink);
  background: var(--surface);
  border: 1px solid var(--line);
  border-radius: 9px;
  padding: 8px 14px;
  cursor: pointer;
  box-shadow: 0 1px 2px var(--shadow);
  transition:
    background-color 0.15s ease,
    border-color 0.15s ease;
}

.button:hover {
  background: var(--tint);
  border-color: var(--line-strong);
}

.button:active {
  transform: translateY(1px);
}

.button:focus-visible {
  outline: 2px solid var(--focus);
  outline-offset: 2px;
}

.button:disabled {
  opacity: 0.45;
  cursor: not-allowed;
  transform: none;
}

.readout {
  font-size: 13px;
  color: var(--muted);
}

/* The text readText() gave, kept to two lines */
.preview {
  display: -webkit-box;
  -webkit-box-orient: vertical;
  -webkit-line-clamp: 2;
  overflow: hidden;
  margin: 0 0 14px;
  min-height: 2.9em;
  font-size: 13px;
  line-height: 1.45;
  color: var(--text);
  background: var(--tint);
  border-left: 3px solid var(--line-strong);
  border-radius: 6px;
  padding: 8px 12px;
}

/* The pages */
.stage {
  height: 400px;
  border: 1px solid var(--line);
  border-radius: 14px;
  background: var(--canvas);
  box-shadow:
    0 1px 2px var(--shadow),
    0 18px 40px -28px rgb(7 32 76 / 0.28);
}

.loading {
  margin: 0;
  padding: 24px 0;
  text-align: center;
  font-size: 13px;
  color: var(--muted);
}
```

**`CopyButton.vue`**

```vue
<script setup lang="ts">
import { ref } from 'vue';
import { copySelection, useSelection, useSelectionState } from '@embedpdf/vue/selection';

const selection = useSelection();
const hasSelection = useSelectionState((state) => state.hasSelection);
const status = ref('');

function copy() {
  copySelection(selection).then(
    (text) => (status.value = `Copied ${text.length} characters`),
    // The browser can refuse the clipboard, for example in a frame that doesn't allow it.
    () => (status.value = "The browser didn't allow copying"),
  );
}
</script>

<template>
  <div class="toolbar">
    <button
      type="button"
      class="button"
      :disabled="!hasSelection || !selection.canCopy()"
      @click="copy"
    >
      Copy
    </button>
    <output class="readout">{{ status || 'Or press Ctrl+C' }}</output>
  </div>
</template>
```

**`SelectedText.vue`**

```vue
<script setup lang="ts">
import { ref, watch } from 'vue';
import { useSelection, useSelectionState } from '@embedpdf/vue/selection';

// The selected text, read with readText() each time the selection settles.
const selection = useSelection();
const { range, isSelecting } = useSelectionState();
const text = ref('');

watch(
  [range, isSelecting],
  ([, selecting], _previous, onCleanup) => {
    if (selecting || !selection.canCopy()) return;
    // A newer selection cancels a read that hasn't finished.
    const controller = new AbortController();
    selection.readText({ signal: controller.signal }).then(
      (read) => (text.value = read),
      () => {},
    );
    onCleanup(() => controller.abort());
  },
  { immediate: true },
);
</script>

<template>
  <p class="preview">{{ text || 'Select some text to read it here.' }}</p>
</template>
```

**`SelectTitle.vue`**

```vue
<script setup lang="ts">
import { computed, watch } from 'vue';
import { usePageList } from '@embedpdf/vue/runtime';
import { useSelection } from '@embedpdf/vue/selection';

// Something selected on load: the title on the cover.
const selection = useSelection();
const pages = usePageList();
const cover = computed(() => pages.value[0]?.ref);

watch(
  cover,
  (page) => {
    if (page) selection.select({ page, start: 10, count: 52 });
  },
  { immediate: true },
);
</script>

<template></template>
```

> **Try it:** select other text: the line above the pages shows what `readText()` reads once the
> selection settles. Then press **Copy**, or Ctrl+C.

## Add a selection menu

`<SelectionMenu>` places your own UI next to the selection. It hides while the user drags and
appears when the selection settles:

**`App.vue`**

```vue
<script setup lang="ts">
import { ref } from 'vue';
import { DocumentGate, Viewer } from '@embedpdf/vue/runtime';
import type { OpenInput } from '@embedpdf/vue/runtime';
import { Stage, stagePlugin } from '@embedpdf/vue/stage';
import { RenderLayer, renderPlugin } from '@embedpdf/vue/render';
import { interactionPlugin } from '@embedpdf/vue/interaction';
import {
  SelectionClipboard,
  SelectionLayer,
  SelectionMenu,
  selectionPlugin,
} from '@embedpdf/vue/selection';
import { localEngine } from '@embedpdf/engine';
import SelectionActions from './SelectionActions.vue';
import SelectTitle from './SelectTitle.vue';

import '../menu.css';

const engine = localEngine();
const plugins = [stagePlugin(), renderPlugin(), interactionPlugin(), selectionPlugin()];

const PLACEMENTS = ['top', 'bottom', 'left', 'right'] as const;
type Placement = (typeof PLACEMENTS)[number];

const ebook = async (): Promise<OpenInput> => {
  const response = await fetch('https://snippet.embedpdf.com/ebook.pdf');
  return { kind: 'bytes', id: 'ebook', bytes: new Uint8Array(await response.arrayBuffer()) };
};

const placement = ref<Placement>('top');
</script>

<template>
  <Viewer :engine="engine" :plugins="plugins" :initial-documents="[{ source: ebook }]">
    <DocumentGate>
      <template #fallback><p class="loading">Loading…</p></template>
      <SelectTitle />
      <SelectionClipboard />
      <div class="toolbar" role="group" aria-label="Where the menu goes">
        <button
          v-for="name in PLACEMENTS"
          :key="name"
          type="button"
          class="segment"
          :aria-pressed="placement === name"
          @click="placement = name"
        >
          {{ name }}
        </button>
      </div>
      <Stage class="stage">
        <template #page>
          <RenderLayer />
          <SelectionLayer />
        </template>
        <template #overlay>
          <SelectionMenu :placement="placement" :gap="8">
            <SelectionActions />
          </SelectionMenu>
        </template>
      </Stage>
    </DocumentGate>
  </Viewer>
</template>
```

**`menu.css`**

```css
/* Colors */
:root {
  --ink: #1a2748;
  --muted: #5a6b92;
  --line: #e6eaf2;
  --line-strong: #dce8fc;
  --surface: #ffffff;
  --tint: #f3f7fe;
  --canvas: #f7f9fc;
  --accent: #054fb3;
  --focus: #7db6ff;
  --shadow: rgb(7 32 76 / 0.04);
}

/* Where the menu goes, above the pages */
.toolbar {
  display: inline-flex;
  flex-wrap: wrap;
  gap: 2px;
  margin-bottom: 14px;
  padding: 3px;
  background: var(--tint);
  border: 1px solid var(--line);
  border-radius: 10px;
}

.segment {
  font: inherit;
  font-size: 13px;
  font-weight: 550;
  line-height: 1;
  text-transform: capitalize;
  color: var(--muted);
  background: transparent;
  border: 0;
  border-radius: 7px;
  padding: 7px 13px;
  cursor: pointer;
}

.segment:hover {
  color: var(--ink);
}

.segment[aria-pressed='true'] {
  color: var(--accent);
  background: var(--surface);
  box-shadow: 0 1px 3px rgb(7 32 76 / 0.12);
}

.segment:focus-visible {
  outline: 2px solid var(--focus);
  outline-offset: 1px;
}

/* The menu that floats next to a selection */
.menu {
  display: flex;
  gap: 6px;
  padding: 6px;
  background: var(--surface);
  border: 1px solid var(--line);
  border-radius: 12px;
  box-shadow: 0 8px 24px rgb(7 32 76 / 0.18);
}

.button {
  font: inherit;
  font-size: 13px;
  font-weight: 550;
  line-height: 1;
  color: var(--ink);
  background: var(--surface);
  border: 1px solid var(--line);
  border-radius: 9px;
  padding: 8px 13px;
  cursor: pointer;
  white-space: nowrap;
  box-shadow: 0 1px 2px var(--shadow);
  transition:
    background-color 0.15s ease,
    border-color 0.15s ease;
}

.button:hover {
  background: var(--tint);
  border-color: var(--line-strong);
}

.button:active {
  transform: translateY(1px);
}

.button:focus-visible {
  outline: 2px solid var(--focus);
  outline-offset: 2px;
}

/* The pages */
.stage {
  height: 460px;
  border: 1px solid var(--line);
  border-radius: 14px;
  background: var(--canvas);
  box-shadow:
    0 1px 2px var(--shadow),
    0 18px 40px -28px rgb(7 32 76 / 0.28);
}

.loading {
  margin: 0;
  padding: 24px 0;
  text-align: center;
  font-size: 13px;
  color: var(--muted);
}
```

**`SelectionActions.vue`**

```vue
<script setup lang="ts">
import { copySelection, useSelection } from '@embedpdf/vue/selection';

// What's in the menu is yours: here, copy and clear.
const selection = useSelection();

function copy() {
  void copySelection(selection).catch(() => {
    // Show your product's clipboard error message here.
  });
}
</script>

<template>
  <div class="menu">
    <button v-if="selection.canCopy()" type="button" class="button" @click="copy">Copy</button>
    <button type="button" class="button" @click="selection.clear()">Clear</button>
  </div>
</template>
```

**`SelectTitle.vue`**

```vue
<script setup lang="ts">
import { computed, watch } from 'vue';
import { usePageList } from '@embedpdf/vue/runtime';
import { useSelection } from '@embedpdf/vue/selection';

// Something selected on load, so the menu shows: the title on the cover.
const selection = useSelection();
const pages = usePageList();
const cover = computed(() => pages.value[0]?.ref);

watch(
  cover,
  (page) => {
    if (page) selection.select({ page, start: 10, count: 52 });
  },
  { immediate: true },
);
</script>

<template></template>
```

> **Try it:** select other text, and the menu follows it. Pick where it goes above the pages.

Mount it in the Stage's `#overlay`
slot, and it stays attached to the text while the user
scrolls and zooms. The menu only places things; what's in it is yours: copy, comment, highlight, redact. `placement`
is `'top'`, `'bottom'`, `'left'` or `'right'`, and `gap` the space in pixels.

## On touch screens

A finger has no text cursor, so selection works as it does elsewhere on a phone: **long-press a word,
then drag the handles.** Add `<SelectionHandles>` next to your menu:

**`selection-handles.vue`**

```vue
<script setup lang="ts">
import { RenderLayer } from '@embedpdf/vue/render';
import { SelectionHandles, SelectionLayer, SelectionMenu } from '@embedpdf/vue/selection';
import { Stage } from '@embedpdf/vue/stage';

import CopyButton from './copy-button.vue';
</script>

<template>
  <Stage>
    <template #page>
      <RenderLayer />
      <SelectionLayer />
    </template>

    <template #overlay>
      <SelectionMenu>
        <CopyButton />
      </SelectionMenu>
      <SelectionHandles />
    </template>
  </Stage>
</template>
```

**`App.vue`**

```vue
<script setup lang="ts">
import { DocumentGate, Viewer } from '@embedpdf/vue/runtime';
import type { OpenInput } from '@embedpdf/vue/runtime';
import { Stage, stagePlugin } from '@embedpdf/vue/stage';
import { RenderLayer, renderPlugin } from '@embedpdf/vue/render';
import { interactionPlugin } from '@embedpdf/vue/interaction';
import {
  SelectionHandles,
  SelectionLayer,
  SelectionMenu,
  selectionPlugin,
} from '@embedpdf/vue/selection';
import { localEngine } from '@embedpdf/engine';
import CopyButton from './CopyButton.vue';
import SelectWord from './SelectWord.vue';

import '../handles.css';

const engine = localEngine();
const plugins = [stagePlugin(), renderPlugin(), interactionPlugin(), selectionPlugin()];

const ebook = async (): Promise<OpenInput> => {
  const response = await fetch('https://snippet.embedpdf.com/ebook.pdf');
  return { kind: 'bytes', id: 'ebook', bytes: new Uint8Array(await response.arrayBuffer()) };
};
</script>

<template>
  <Viewer :engine="engine" :plugins="plugins" :initial-documents="[{ source: ebook }]">
    <DocumentGate>
      <template #fallback><p class="loading">Loading…</p></template>
      <SelectWord />
      <Stage class="stage">
        <template #page>
          <RenderLayer />
          <SelectionLayer />
        </template>
        <template #overlay>
          <!-- Clear of the start handle's grip, which sits above the first line. -->
          <SelectionMenu :gap="20">
            <CopyButton />
          </SelectionMenu>
          <SelectionHandles />
        </template>
      </Stage>
    </DocumentGate>
  </Viewer>
</template>
```

**`handles.css`**

```css
/* Colors */
:root {
  --ink: #1a2748;
  --muted: #5a6b92;
  --line: #e6eaf2;
  --line-strong: #dce8fc;
  --surface: #ffffff;
  --tint: #f3f7fe;
  --canvas: #f7f9fc;
  --focus: #7db6ff;
  --shadow: rgb(7 32 76 / 0.04);
}

/* The menu's one button, floating above the selection */
.button {
  font: inherit;
  font-size: 13px;
  font-weight: 550;
  line-height: 1;
  color: var(--ink);
  background: var(--surface);
  border: 1px solid var(--line);
  border-radius: 10px;
  padding: 9px 15px;
  cursor: pointer;
  box-shadow: 0 8px 24px rgb(7 32 76 / 0.18);
  transition:
    background-color 0.15s ease,
    border-color 0.15s ease;
}

.button:hover {
  background: var(--tint);
  border-color: var(--line-strong);
}

.button:focus-visible {
  outline: 2px solid var(--focus);
  outline-offset: 2px;
}

.button:disabled {
  opacity: 0.45;
  cursor: not-allowed;
}

/* The pages */
.stage {
  height: 460px;
  border: 1px solid var(--line);
  border-radius: 14px;
  background: var(--canvas);
  box-shadow:
    0 1px 2px var(--shadow),
    0 18px 40px -28px rgb(7 32 76 / 0.28);
}

.loading {
  margin: 0;
  padding: 24px 0;
  text-align: center;
  font-size: 13px;
  color: var(--muted);
}
```

**`CopyButton.vue`**

```vue
<script setup lang="ts">
import { copySelection, useSelection } from '@embedpdf/vue/selection';

const selection = useSelection();
</script>

<template>
  <button
    type="button"
    class="button"
    :disabled="!selection.canCopy()"
    @click="copySelection(selection).catch(() => {})"
  >
    Copy
  </button>
</template>
```

**`SelectWord.vue`**

```vue
<script setup lang="ts">
import { computed, watch } from 'vue';
import { usePageList } from '@embedpdf/vue/runtime';
import { useSelection } from '@embedpdf/vue/selection';

// A word selected on load, as a long-press selects one: "Viewers", on the cover.
const selection = useSelection();
const pages = usePageList();
const cover = computed(() => pages.value[0]?.ref);

watch(
  cover,
  (page) => {
    if (page) selection.select({ page, start: 14, count: 7 });
  },
  { immediate: true },
);
</script>

<template></template>
```

> **Try it:** drag a handle's round grip, with a finger or the mouse: the selection grows or shrinks
> from the other end.

Each handle is the selection's own edge, with a round grip. Dragging one grows the selection from the
other end, across pages too. Grabbing a handle never scrolls the page, and everywhere else a finger
still scrolls and pinch-zooms. For the small tick a native app gives on long-press, see
[haptic feedback](../ui/tools#haptic-feedback).

## Methods

Everything `useSelection()` gives you.

| Method                                                        | What it does                                                                                                                                                  |
| :------------------------------------------------------------ | :------------------------------------------------------------------------------------------------------------------------------------------------------------ |
| `select(range)`                                               | Selects `{ page, start, count }` on one page, or `{ start, end }` across pages. An empty range clears. [Select text from code](#select-text-from-code)        |
| `selectWordAt(page, point)`                                   | Selects the word at a point, like a double-click. Returns `false` when there's no text there.                                                                 |
| `selectLineAt(page, point)`                                   | Selects the line at a point, like a triple-click. Returns `false` when there's no text there.                                                                 |
| `selectPage(page)`                                            | Selects every character on a page                                                                                                                             |
| `selectAll()`                                                 | Selects the whole document                                                                                                                                    |
| `extendTo(page, point)`                                       | Grows the selection to a point, as dragging a handle does                                                                                                     |
| `clear()`                                                     | Clears the selection. Always allowed.                                                                                                                         |
| `readText()`                                                  | The selected text, or `''` with nothing selected. Needs permission to copy. [Copy the selected text](#copy-the-selected-text)                                 |
| `readTextInRange(range)`                                      | The text of any range, without selecting it                                                                                                                   |
| `listSegments(page)`                                          | Each selected line on a page, as four corners turned with the text                                                                                            |
| `listRects(page)`                                             | A plain box around each selected line on a page                                                                                                               |
| `getAnchor()`                                                 | Where a menu attaches: `{ page, bounds }` on the page where the selection ends, or `null`. `<SelectionMenu>` uses it.                                         |
| `getSnapshot()`                                               | Everything at once: each page's lines, both ends with their direction, and the range. For drawing your own highlight and handles.                             |
| `canSelect()`, `canCopy()`                                    | Whether selecting, and reading the selected text, are allowed. [Permissions](#permissions)                                                                    |
| `getSettings()`, `updateSettings(changes)`, `resetSettings()` | Reads the settings, changes them while the app runs, or goes back to what you registered. In a component, use `useSelectionSettings()`. [Settings](#settings) |

Every method that returns a promise also takes a `signal` in its options, to cancel it.

## State

Everything `useSelectionState()` gives you, as refs: your template updates when a value changes. The method in the last column reads the same value once.

| Field          | What it is                                                                         | Read once             |
| :------------- | :--------------------------------------------------------------------------------- | :-------------------- |
| `hasSelection` | Whether anything is selected                                                       | `hasSelection()`      |
| `isSelecting`  | Whether the user is still dragging                                                 | `isSelecting()`       |
| `range`        | The selection as `{ start, end }`, to store and pass back to `select()`, or `null` | `getRange()`          |
| `pages`        | The pages the selection is on, in document order                                   | `listSelectedPages()` |

## Settings

Set them when you register the plugin, and change them while the app runs with
`selection.updateSettings({ … })`; `selection.resetSettings()` goes back to what you registered, and
`useSelectionSettings()` gives you the current settings.

| Setting          | What it does                                                | Default                         | From CSS                              |
| :--------------- | :---------------------------------------------------------- | :------------------------------ | :------------------------------------ |
| `dragThreshold`  | How far, in pixels, the pointer moves before a drag selects | `4`                             | —                                     |
| `color`          | The color of selected text                                  | the viewer's accent at 35%      | `--epdf-text-selection`               |
| `handles.color`  | The grips at its ends, on touch screens                     | the viewer's accent             | `--epdf-text-selection-handle`        |
| `handles.shadow` | Their shadow                                                | `'0 1px 4px rgb(0 0 0 / 0.35)'` | `--epdf-text-selection-handle-shadow` |

A CSS variable wins over the setting, for dark mode or a different look per viewer: see
[Colors & theming](../ui/theming).

**`App.vue`**

```vue
<script setup lang="ts">
import { ref } from 'vue';
import { DocumentGate, Viewer } from '@embedpdf/vue/runtime';
import type { OpenInput } from '@embedpdf/vue/runtime';
import { Stage, stagePlugin } from '@embedpdf/vue/stage';
import { RenderLayer, renderPlugin } from '@embedpdf/vue/render';
import { interactionPlugin } from '@embedpdf/vue/interaction';
import { SelectionHandles, SelectionLayer, selectionPlugin } from '@embedpdf/vue/selection';
import { localEngine } from '@embedpdf/engine';
import ColorPicker from './ColorPicker.vue';
import SelectTitle from './SelectTitle.vue';

import '../colors.css';

const engine = localEngine();
const plugins = [
  stagePlugin(),
  renderPlugin(),
  interactionPlugin(),
  selectionPlugin({ handles: { shadow: '0 1px 3px rgb(0 0 0 / 0.3)' } }),
];

const ebook = async (): Promise<OpenInput> => {
  const response = await fetch('https://snippet.embedpdf.com/ebook.pdf');
  return { kind: 'bytes', id: 'ebook', bytes: new Uint8Array(await response.arrayBuffer()) };
};

const fromCss = ref(false);
</script>

<template>
  <Viewer :engine="engine" :plugins="plugins" :initial-documents="[{ source: ebook }]">
    <DocumentGate>
      <template #fallback><p class="loading">Loading…</p></template>
      <SelectTitle />
      <div class="toolbar">
        <ColorPicker />
        <label class="option">
          <input v-model="fromCss" type="checkbox" />
          Override with CSS
        </label>
      </div>
      <Stage :class="fromCss ? 'stage from-css' : 'stage'">
        <template #page>
          <RenderLayer />
          <SelectionLayer />
        </template>
        <template #overlay>
          <SelectionHandles />
        </template>
      </Stage>
    </DocumentGate>
  </Viewer>
</template>
```

**`colors.css`**

```css
/* Colors */
:root {
  --ink: #1a2748;
  --muted: #5a6b92;
  --line: #e6eaf2;
  --line-strong: #dce8fc;
  --surface: #ffffff;
  --tint: #f3f7fe;
  --canvas: #f7f9fc;
  --accent: #054fb3;
  --focus: #7db6ff;
  --shadow: rgb(7 32 76 / 0.04);
}

/* The colors to pick from, above the pages */
.toolbar {
  display: flex;
  flex-wrap: wrap;
  align-items: center;
  gap: 8px;
  margin-bottom: 14px;
}

.swatch {
  width: 32px;
  height: 32px;
  border: 2px solid var(--surface);
  border-radius: 50%;
  padding: 0;
  cursor: pointer;
  box-shadow: 0 0 0 1px var(--line);
  transition: box-shadow 0.15s ease;
}

.swatch:hover {
  box-shadow: 0 0 0 1px var(--focus);
}

.swatch[aria-pressed='true'] {
  box-shadow: 0 0 0 2px var(--accent);
}

.swatch:focus-visible {
  outline: 2px solid var(--focus);
  outline-offset: 2px;
}

.button {
  font: inherit;
  font-size: 13px;
  font-weight: 550;
  line-height: 1;
  color: var(--ink);
  background: var(--surface);
  border: 1px solid var(--line);
  border-radius: 9px;
  padding: 9px 13px;
  cursor: pointer;
  box-shadow: 0 1px 2px var(--shadow);
  transition:
    background-color 0.15s ease,
    border-color 0.15s ease;
}

.button:hover {
  background: var(--tint);
  border-color: var(--line-strong);
}

.button:focus-visible {
  outline: 2px solid var(--focus);
  outline-offset: 2px;
}

/* A checkbox in a pill that lights up while it's on */
.option {
  display: inline-flex;
  align-items: center;
  gap: 7px;
  margin-left: auto;
  font-size: 13px;
  font-weight: 550;
  color: var(--ink);
  background: var(--surface);
  border: 1px solid var(--line);
  border-radius: 9px;
  padding: 7px 11px;
  cursor: pointer;
  user-select: none;
  box-shadow: 0 1px 2px var(--shadow);
}

.option:has(input:checked) {
  color: var(--accent);
  background: var(--tint);
  border-color: var(--focus);
}

.option input {
  margin: 0;
  accent-color: #0876fd;
}

/* The pages */
.stage {
  height: 420px;
  border: 1px solid var(--line);
  border-radius: 14px;
  background: var(--canvas);
  box-shadow:
    0 1px 2px var(--shadow),
    0 18px 40px -28px rgb(7 32 76 / 0.28);
}

/* CSS wins over the settings: an orange selection, whichever color is picked */
.stage.from-css {
  --epdf-text-selection: rgb(249 115 22 / 0.35);
  --epdf-text-selection-handle: #ea580c;
}

.loading {
  margin: 0;
  padding: 24px 0;
  text-align: center;
  font-size: 13px;
  color: var(--muted);
}
```

**`ColorPicker.vue`**

```vue
<script setup lang="ts">
import { useSelection, useSelectionSettings } from '@embedpdf/vue/selection';

// Each: the selected text and its handles. `null` is the viewer's accent: at 35% for the text.
const COLORS = [
  { name: 'Accent', color: null, handles: null, swatch: '#3858e9' },
  { name: 'Yellow', color: 'rgb(250 204 21 / 0.45)', handles: '#ca8a04', swatch: '#facc15' },
  { name: 'Green', color: 'rgb(34 197 94 / 0.35)', handles: '#16a34a', swatch: '#22c55e' },
  { name: 'Pink', color: 'rgb(236 72 153 / 0.3)', handles: '#db2777', swatch: '#ec4899' },
];

const selection = useSelection();
const current = useSelectionSettings((settings) => settings.color);
</script>

<template>
  <button
    v-for="{ name, color, handles, swatch } in COLORS"
    :key="name"
    type="button"
    class="swatch"
    :aria-label="name"
    :aria-pressed="current === color"
    :style="{ background: swatch }"
    @click="selection.updateSettings({ color, handles: { color: handles } })"
  />
  <button type="button" class="button" @click="selection.resetSettings()">Reset</button>
</template>
```

**`SelectTitle.vue`**

```vue
<script setup lang="ts">
import { computed, watch } from 'vue';
import { usePageList } from '@embedpdf/vue/runtime';
import { useSelection } from '@embedpdf/vue/selection';

// Something selected on load: the title on the cover.
const selection = useSelection();
const pages = usePageList();
const cover = computed(() => pages.value[0]?.ref);

watch(
  cover,
  (page) => {
    if (page) selection.select({ page, start: 10, count: 52 });
  },
  { immediate: true },
);
</script>

<template></template>
```

> **Try it:** pick a color, and `selection.updateSettings({ color, handles })` changes the selection
> and its handles at once. Then turn on **Override with CSS**: the CSS variables win over the color
> you picked.

## Events

**`selection-committed.vue`**

```vue
<script setup lang="ts">
import { useSelectionEvent } from '@embedpdf/vue/selection';

import { prefetchTranslation } from './translation';

useSelectionEvent(
  (selection) => selection.onCommitted,
  () => prefetchTranslation(),
);
</script>
```

| Event               | Fires when                                | Carries               |
| :------------------ | :---------------------------------------- | :-------------------- |
| `onChanged`         | The selection changed, while dragging too | `range`, `pages`      |
| `onCommitted`       | A drag or a tap finished selecting        | `range`               |
| `onCleared`         | The selection was cleared                 | —                     |
| `onSettingsChanged` | The settings changed                      | `settings`, `changed` |

Use the change event for things that follow the selection as it grows, and the commit event for
things that should happen once, such as creating a highlight.

## Permissions

Selecting and copying are two permissions:

| Permission        | What it allows                              | Check                   |
| :---------------- | :------------------------------------------ | :---------------------- |
| `doc.text.select` | Selecting text, and highlighting it         | `selection.canSelect()` |
| `doc.text.copy`   | Reading the selected text with `readText()` | `selection.canCopy()`   |

Without `doc.text.select`, pointer selection does nothing and `select()` is refused; `clear()` always
works. Without `doc.text.copy`, people can still select and highlight, but `readText()` is refused
and no page text is sent. So a document can allow markup without copy.

## Good to know

### Characters, not string positions

A range counts characters as the page stores them. Search results, annotations and selections all use
the same counting, so a range from one goes straight into another.

### No HTML text layer

The selection works from where each character is, so there's no hidden HTML text over the page. That
keeps large documents fast, and it's why a document can allow selecting without giving away its text.

### Outside the browser

The selection plugin itself has no clipboard or HTML in it, so `readText()` also works in tests and in
Node. The clipboard is the Vue package's job.
