---
title: "Outline — Svelte"
description: "Show a document's outline (its bookmarks) as a tree, follow its items, mark where the reader is, and let people add, rename, move and delete items."
framework: "Svelte"
source: "https://www.cloudpdf.com/docs/headless/svelte/documents/outline"
---

# Outline

A document's outline is its table of contents: titled items, nested, each going to a place in the
document. Acrobat calls the items bookmarks. Register `outlinePlugin()` to show it in your UI:

**`outline-list.svelte`**

```svelte
<script lang="ts">
  import { useOutline, useOutlineState } from '@embedpdf/svelte/outline';

  const outline = useOutline();
  const state = useOutlineState();
</script>

<ul role="tree">
  {#each state.rows as { item, depth, hasChildren, expanded } (item.ref.objectNumber)}
    <li
      role="treeitem"
      aria-level={depth + 1}
      aria-expanded={hasChildren ? expanded : undefined}
      aria-current={item.ref.objectNumber === state.current?.objectNumber ? 'location' : undefined}
      style:padding-inline-start="{depth * 16}px"
    >
      {#if hasChildren}
        <button onclick={() => outline.toggle(item.ref)}>{expanded ? '▾' : '▸'}</button>
      {/if}
      <button onclick={() => outline.activate(item.ref)}>{item.title}</button>
    </li>
  {/each}
</ul>
```

What `useOutlineState()` gives you updates by itself: after your own changes, and on a shared
document, after someone else's. Nothing is read when a document opens: the outline loads the first
time something asks for it, so a document nobody shows the outline of costs nothing.

## Show the outline

`rows` are the rows a tree shows: every item whose parents are all expanded, depth first. Each row
has the `item`, its `depth` (0 at the top level), `hasChildren`, and whether it's `expanded`.
`items` is every item, folded or not, when you'd rather build the tree yourself.

`toggle(ref)` folds or unfolds an item; `expand(ref)`, `collapse(ref)`, `expandAll()` and
`collapseAll()` do one of them. The items the file opens start expanded, and from then on what's
expanded is the reader's: it doesn't change the document.

An item has its `title`, its `color` (`null` when the file sets none, so draw your own text
colour), and whether it's `bold` or `italic`. `status` says whether the outline hasn't been asked
for yet (`'idle'`), is loading, is there (`'ready'`), or couldn't be read. `incomplete` is `true`
when part of the outline couldn't be read, such as a loop in a damaged file; what could be read is
listed.

## Follow an item

`activate(ref)` goes where the item goes, as a click does: a page moves the view, a website opens,
and an item that runs a script runs it, through the [actions plugin](https://www.cloudpdf.com/docs/headless/svelte/documents/actions)
when you've registered it. It returns what happened at once, so a website can still open from the
reader's click.

`current` is the item for where the reader is: the last item, in reading order, that goes to a place
at or above the top of the view. Mark its row, and the reader always sees where they are in the
outline:

```ts
const isCurrent = row.item.ref.objectNumber === current?.objectNumber;
```

**`App.svelte`**

```svelte
<script lang="ts" module>
  import { DocumentGate, Viewer, type OpenInput } from '@embedpdf/svelte/runtime';
  import { RenderLayer, renderPlugin } from '@embedpdf/svelte/render';
  import { Stage, stagePlugin } from '@embedpdf/svelte/stage';
  import { outlinePlugin } from '@embedpdf/svelte/outline';
  import { cloudEngine } from '@cloudpdf/engine';
  import Bookmarks from './Bookmarks.svelte';

  import '../bookmarks.css';

  const engine = cloudEngine();
  const plugins = [stagePlugin(), renderPlugin(), outlinePlugin()];

  const welcome: OpenInput = { kind: 'grant', grant: 'shr_gvpJcG1ULUMon19C0D1wODSY' };
</script>

<Viewer {engine} {plugins} initialDocuments={[{ source: welcome }]}>
  <DocumentGate>
    {#snippet fallback()}
      <p class="loading">Loading…</p>
    {/snippet}
    <div class="layout">
      <Bookmarks />
      <Stage class="stage">
        <RenderLayer />
      </Stage>
    </div>
  </DocumentGate>
</Viewer>
```

**`bookmarks.css`**

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

/* The bookmarks beside the pages */
.layout {
  display: grid;
  grid-template-columns: 220px 1fr;
  gap: 14px;
}

.bookmarks {
  display: flex;
  flex-direction: column;
  height: 420px;
  border: 1px solid var(--line);
  border-radius: 14px;
  background: var(--surface);
  box-shadow: 0 1px 2px var(--shadow);
  overflow: hidden;
}

.bookmarks-header {
  display: flex;
  align-items: center;
  justify-content: space-between;
  padding: 10px 10px 10px 14px;
  border-bottom: 1px solid var(--line);
}

.bookmarks-title {
  margin: 0;
  font-size: 13px;
  font-weight: 650;
  color: var(--ink);
}

.empty {
  margin: 0;
  padding: 18px 14px;
  font-size: 12.5px;
  color: var(--muted);
}

/* One row per bookmark: the one being read is marked, the picked one tinted */
.list {
  margin: 0;
  padding: 6px;
  list-style: none;
  overflow-y: auto;
}

.row {
  position: relative;
  display: flex;
  align-items: center;
  border-radius: 8px;
}

.row[data-selected] {
  background: var(--tint);
}

.row[data-current]::before {
  content: '';
  position: absolute;
  inset: 6px auto 6px 0;
  width: 3px;
  border-radius: 3px;
  background: var(--accent);
}

.row-title {
  flex: 1;
  min-width: 0;
  font: inherit;
  font-size: 13px;
  text-align: start;
  color: var(--ink);
  background: none;
  border: 0;
  padding: 7px 10px;
  cursor: pointer;
  overflow: hidden;
  text-overflow: ellipsis;
  white-space: nowrap;
}

.row-delete {
  font: inherit;
  font-size: 16px;
  line-height: 1;
  color: var(--muted);
  background: none;
  border: 0;
  border-radius: 6px;
  padding: 4px 8px;
  cursor: pointer;
  opacity: 0;
}

.row:hover .row-delete,
.row-delete:focus-visible {
  opacity: 1;
}

.row-delete:hover {
  color: var(--ink);
  background: var(--line);
}

.button {
  font: inherit;
  font-size: 12px;
  font-weight: 600;
  color: var(--ink);
  background: var(--surface);
  border: 1px solid var(--line);
  border-radius: 9px;
  padding: 6px 12px;
  cursor: pointer;
  box-shadow: 0 1px 2px var(--shadow);
}

.button.primary {
  color: #ffffff;
  background: var(--accent);
  border-color: var(--accent);
}

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

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

/* 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);
}
```

**`Bookmarks.svelte`**

```svelte
<!-- Bookmarks the reader adds: each one goes to the place in view when it's added. -->
<script lang="ts">
  import { useStageState } from '@embedpdf/svelte/stage';
  import { useOutline, useOutlineState, type OutlineItem } from '@embedpdf/svelte/outline';

  const outline = useOutline();
  const state = useOutlineState();
  const stage = useStageState();
  const selectedNumber = $derived(state.selected[0]?.objectNumber);

  function follow(item: OutlineItem) {
    outline.select([item.ref]);
    outline.activate(item.ref);
  }
</script>

<aside class="bookmarks">
  <header class="bookmarks-header">
    <h3 class="bookmarks-title">Bookmarks</h3>
    <button
      type="button"
      class="button primary"
      disabled={!state.canEdit}
      onclick={() =>
        outline.create({ title: `Page ${stage.currentPageIndex + 1}` }, { select: true })}
    >
      Add
    </button>
  </header>
  {#if state.rows.length === 0}
    <p class="empty">Scroll to a page, then add a bookmark.</p>
  {:else}
    <ul class="list">
      {#each state.rows as { item } (item.ref.objectNumber)}
        <li
          class="row"
          data-current={item.ref.objectNumber === state.current?.objectNumber || undefined}
          data-selected={item.ref.objectNumber === selectedNumber || undefined}
        >
          <button type="button" class="row-title" onclick={() => follow(item)}>{item.title}</button>
          <button
            type="button"
            class="row-delete"
            aria-label={`Delete ${item.title}`}
            disabled={!state.canEdit}
            onclick={() => outline.delete([item.ref])}
          >
            ×
          </button>
        </li>
      {/each}
    </ul>
  {/if}
</aside>
```

## Change the outline

`create()` adds an item. Leave out where it goes and it goes to the place in view; leave out its
title and it takes the selected text, or "Untitled" in the viewer's language. It shows at once, and
`select: true` selects it and unfolds the items it sits under, so it's ready to rename:

```ts
await outline.create({ parent: chapter.ref, position: 'end' }, { select: true });
```

`update(ref, changes)` changes the fields you pass: a `title`, a `target`, a `color`, `bold`,
`italic`, or `open` (whether it's expanded when the document opens). `null` removes a target or a
colour. `move(refs, parent, position)` moves items, with the items under them, to their new place,
and `delete(refs)` deletes items with the items under them.

Each of these shows at once, is one step to undo, and resolves once the engine has it. A place is
a neighbour, not a number: `'start'`, `'end'`, `{ before: ref }` or `{ after: ref }` among the
parent's children.

**`App.svelte`**

```svelte
<script lang="ts" module>
  import { DocumentGate, Viewer, type OpenInput } from '@embedpdf/svelte/runtime';
  import { outlinePlugin } from '@embedpdf/svelte/outline';
  import { cloudEngine } from '@cloudpdf/engine';
  import OutlineEditor from './OutlineEditor.svelte';

  import '../nesting.css';

  const engine = cloudEngine();
  const plugins = [outlinePlugin()];

  const welcome: OpenInput = { kind: 'grant', grant: 'shr_gvpJcG1ULUMon19C0D1wODSY' };
</script>

<Viewer {engine} {plugins} initialDocuments={[{ source: welcome }]}>
  <DocumentGate>
    {#snippet fallback()}
      <p class="loading">Loading…</p>
    {/snippet}
    <OutlineEditor />
  </DocumentGate>
</Viewer>
```

**`nesting.css`**

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

/* The title to add or rename with, and what to do with the picked item */
.toolbar {
  display: flex;
  flex-wrap: wrap;
  align-items: center;
  gap: 8px;
  margin-bottom: 14px;
}

.field {
  width: 160px;
  font: inherit;
  font-size: 13px;
  color: var(--ink);
  background: var(--surface);
  border: 1px solid var(--line);
  border-radius: 9px;
  padding: 7px 10px;
}

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

.button {
  font: inherit;
  font-size: 12px;
  font-weight: 600;
  color: var(--ink);
  background: var(--surface);
  border: 1px solid var(--line);
  border-radius: 9px;
  padding: 7px 12px;
  cursor: pointer;
  box-shadow: 0 1px 2px var(--shadow);
}

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

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

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

/* The tree: each level indented, a parent with a chevron that folds it */
.tree {
  margin: 0;
  padding: 6px;
  list-style: none;
  min-height: 220px;
  border: 1px solid var(--line);
  border-radius: 14px;
  background: var(--surface);
  box-shadow: 0 1px 2px var(--shadow);
}

.row {
  display: flex;
  align-items: center;
  gap: 2px;
  border-radius: 8px;
}

.row[aria-selected='true'] {
  background: var(--tint);
}

.chevron {
  display: grid;
  place-items: center;
  width: 22px;
  height: 22px;
  color: var(--muted);
  background: none;
  border: 0;
  border-radius: 6px;
  cursor: pointer;
  transition: transform 0.15s ease;
}

/* Drawn rather than typed, so it's the same size in every font: a right-pointing chevron */
.chevron::before {
  content: '';
  width: 6px;
  height: 6px;
  border-right: 1.5px solid currentColor;
  border-bottom: 1.5px solid currentColor;
  transform: translateX(-1px) rotate(-45deg);
}

.chevron:disabled {
  visibility: hidden;
}

.chevron[data-expanded] {
  transform: rotate(90deg);
}

.row-title {
  flex: 1;
  min-width: 0;
  font: inherit;
  font-size: 13px;
  text-align: start;
  color: var(--ink);
  background: none;
  border: 0;
  padding: 7px 8px;
  cursor: pointer;
}

.empty {
  margin: 0;
  padding: 18px;
  font-size: 12.5px;
  color: var(--muted);
  border: 1px dashed var(--line-strong);
  border-radius: 14px;
}

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

**`OutlineEditor.svelte`**

```svelte
<!-- An outline being built: add items, nest them, fold them, rename and delete them. -->
<script lang="ts">
  import {
    useOutline,
    useOutlineState,
    type OutlineItem,
    type OutlineItemRef,
  } from '@embedpdf/svelte/outline';

  const outline = useOutline();
  const tree = useOutlineState();
  let title = $state('Chapter');

  const same = (left: OutlineItemRef | null, right: OutlineItemRef | null) =>
    left?.objectNumber === right?.objectNumber;
  const item = $derived(
    tree.items.find((each) => same(each.ref, tree.selected[0] ?? null)) ?? null,
  );
  // The item before the picked one among its parent's children: where an indent puts it.
  const previous = $derived.by(() => {
    if (!item) return null;
    const siblings = tree.items.filter((each) => same(each.parent, item.parent));
    return siblings[siblings.indexOf(item) - 1] ?? null;
  });
  const parent = $derived(tree.items.find((each) => same(each.ref, item?.parent ?? null)) ?? null);

  // After the picked item, or at the end.
  function add(inside: boolean) {
    void outline.create(
      inside && item
        ? { title, parent: item.ref }
        : { title, parent: item?.parent ?? null, position: item ? { after: item.ref } : 'end' },
      { select: true },
    );
  }

  // The move shows at once, so read `previous` before it: after it, the item has none.
  function indent() {
    const picked = item;
    const before = previous;
    if (!picked || !before) return;
    void outline.move([picked.ref], before.ref, 'end');
    outline.expand(before.ref);
  }

  function outdent() {
    if (item && parent) void outline.move([item.ref], parent.parent, { after: parent.ref });
  }

  function pick(row: OutlineItem) {
    outline.select([row.ref]);
    title = row.title;
  }
</script>

<div class="editor">
  <div class="toolbar">
    <input class="field" aria-label="Title" bind:value={title} />
    <button type="button" class="button" disabled={!tree.canEdit} onclick={() => add(false)}>
      Add
    </button>
    <button
      type="button"
      class="button"
      disabled={!tree.canEdit || !item}
      onclick={() => add(true)}
    >
      Add inside
    </button>
    <button type="button" class="button" disabled={!tree.canEdit || !previous} onclick={indent}>
      Indent
    </button>
    <button type="button" class="button" disabled={!tree.canEdit || !parent} onclick={outdent}>
      Outdent
    </button>
    <button
      type="button"
      class="button"
      disabled={!tree.canEdit || !item}
      onclick={() => item && outline.update(item.ref, { title })}
    >
      Rename
    </button>
    <button
      type="button"
      class="button"
      disabled={!tree.canEdit || !item}
      onclick={() => item && outline.delete([item.ref])}
    >
      Delete
    </button>
  </div>
  {#if tree.rows.length === 0}
    <p class="empty">This document has no outline yet. Add an item.</p>
  {:else}
    <ul class="tree" role="tree">
      {#each tree.rows as row (row.item.ref.objectNumber)}
        <li
          class="row"
          role="treeitem"
          aria-level={row.depth + 1}
          aria-expanded={row.hasChildren ? row.expanded : undefined}
          aria-selected={row.item.ref.objectNumber === item?.ref.objectNumber}
          style:padding-inline-start="{6 + row.depth * 18}px"
        >
          <button
            type="button"
            class="chevron"
            aria-label={row.expanded ? 'Collapse' : 'Expand'}
            disabled={!row.hasChildren}
            data-expanded={row.expanded || undefined}
            onclick={() => outline.toggle(row.item.ref)}
          ></button>
          <button type="button" class="row-title" onclick={() => pick(row.item)}>
            {row.item.title}
          </button>
        </li>
      {/each}
    </ul>
  {/if}
</div>
```

## Select items

`select(refs)` makes items the selection, and `selected` lists them. The selection is the
reader's, like what's expanded: show it, and act on it with your own buttons.

```ts
outline.select([row.item.ref]);
await outline.delete(selected);
```

## Methods

Everything `useOutline()` gives you.

| Method                         | What it does                                                                                               |
| :----------------------------- | :--------------------------------------------------------------------------------------------------------- |
| `get(ref)`                     | One item, or `null`.                                                                                       |
| `getChildren(parent)`          | An item's children in order, or the top level's for `null`.                                                |
| `isExpanded(ref)`              | Whether an item's children show. [Show the outline](#show-the-outline)                                     |
| `toggle(ref)`                  | Folds an expanded item, unfolds a folded one.                                                              |
| `expand(ref)`, `collapse(ref)` | Unfolds or folds one item.                                                                                 |
| `expandAll()`, `collapseAll()` | Unfolds or folds every item.                                                                               |
| `reveal(ref)`                  | Unfolds every item `ref` sits under, so its row shows.                                                     |
| `select(refs)`                 | Makes these items the selection; `[]` clears it. [Select items](#select-items)                             |
| `activate(ref)`                | Goes where the item goes, as a click does, and returns what happened. [Follow an item](#follow-an-item)    |
| `getCurrentViewTarget()`       | Where the view is, as a target: the page at its top and the spot at its top-left. What a new item goes to. |
| `create(item, options)`        | Adds an item; `select: true` selects it. Resolves `{ item }`. [Change the outline](#change-the-outline)    |
| `update(ref, changes)`         | Changes the fields you pass; `null` removes a target or a colour. Resolves `{ item }`.                     |
| `move(refs, parent, position)` | Moves items, with the items under them, to their new place.                                                |
| `delete(refs)`                 | Deletes items with the items under them, as one change.                                                    |
| `ensureLoaded()`               | Reads the outline from the file, unless it's loaded or loading. Resolves once it's there.                  |
| `refresh()`                    | Reads the outline again. Rarely needed: it stays up to date by itself.                                     |

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

## State

Everything `useOutlineState()` gives you, as one reactive object: read its fields, and your markup updates when they change. The method in the last column reads the same value once.

| Field        | What it is                                                                                    | Read once          |
| :----------- | :-------------------------------------------------------------------------------------------- | :----------------- |
| `items`      | Every item, depth first, with your changes shown before the engine answers                    | `list()`           |
| `rows`       | The rows a tree shows: `item`, `depth`, `hasChildren`, `expanded`                             | `listRows()`       |
| `current`    | The item for where the reader is, or `null`                                                   | `getCurrentItem()` |
| `selected`   | The selected items, in the order they were selected                                           | `getSelected()`    |
| `status`     | `'idle'` until something asks for it, then `'loading'`, `'ready'`, `'forbidden'` or `'error'` | `getStatus()`      |
| `incomplete` | Part of the outline couldn't be read                                                          | `isIncomplete()`   |
| `canEdit`    | Whether changing the outline is allowed                                                       | `canEdit()`        |

## Events

**`outline-changed.svelte`**

```svelte
<script lang="ts">
  import { useOutlineEvent } from '@embedpdf/svelte/outline';

  let notice = $state('');

  useOutlineEvent(
    (outline) => outline.onChanged,
    ({ type, items, origin }) => {
      if (origin.kind === 'remote') notice = `Someone ${type} ${items.length} bookmark(s)`;
    },
  );
</script>

<p role="status">{notice}</p>
```

| Event        | Fires when                                                                                                                   | Carries                   |
| :----------- | :--------------------------------------------------------------------------------------------------------------------------- | :------------------------ |
| `onChanged`  | Items were created, updated, moved, deleted or restored, by you or by someone else                                           | `type`, `items`, `origin` |
| `onResynced` | The outline was read from the file: the first time it's asked for, after `refresh()`, or to catch up after a lost connection | `outline`                 |

`type` is `'created'`, `'updated'`, `'moved'`, `'deleted'` or `'restored'`, and `items` names the
items it touched; for a delete, the item first, then the items under it.

## Permissions

| Permission           | What it allows                              | Check               |
| :------------------- | :------------------------------------------ | :------------------ |
| `doc.open`           | Reading the outline                         | none: it opened     |
| `doc.outline.modify` | Adding, changing, moving and deleting items | `outline.canEdit()` |

## Good to know

### Expanded, and open

What's expanded is the reader's view, not the document: folding an item doesn't change the file.
An item's `open` is the file's own setting, whether its children show when the document opens, and
the outline starts from it. Change it with `update(ref, { open })`.

### Pages that are gone

Deleting a page doesn't delete the items that go to it: their target reads `unsupported`, and
`activate()` reports it rather than going anywhere. See
[Outline](https://www.cloudpdf.com/docs/engine/documents/outline#pages-that-are-gone).

### The ready-made viewer

The viewer's Outline panel is built on this plugin. See
[Panels](https://www.cloudpdf.com/docs/viewer/svelte/customize/panels).
