# `Yex.UndoManager`
[🔗](https://github.com/satoren/y_ex/blob/main/lib/undo_manager.ex#L58)

Represents a Y.UndoManager instance.

## Scope

`new/2` and `new_with_options/3` take a Text, Array, Map, XmlText, XmlElement or
XmlFragment. `expand_scope/2` also takes a WeakLink. Any other value raises
`FunctionClauseError`.

A scope must belong to the manager's document; one from another document raises
`ArgumentError`. A scope from another `Yex.Doc` of the same subdocument (for example
the struct a parent's `Yex.Map.fetch/2` returns) is accepted. Calls are serialized
only through the manager's `Yex.Doc`, so when a transaction is open through the
scope's `Yex.Doc`, in this process or another, the call raises
`Yex.TransactionAcqError` instead of waiting for it.

## Tracked origins

A transaction's origin is the term passed to `Yex.Doc.transaction/3`, or `nil`
when none was given. The manager only captures changes from origins it tracks:

* With no tracked origins (the default), it captures only transactions whose
  origin is `nil`.
* Once at least one origin is tracked, it captures only transactions with a
  tracked origin, and transactions with a `nil` origin are no longer captured.
  Removing every tracked origin with `exclude_origin/2` goes back to capturing
  only `nil`.

This matches Yjs, where `trackedOrigins` defaults to `new Set([null])`, except that
`nil` cannot be tracked alongside other origins. The manager's own undo and redo
transactions are always tracked, so undone changes can be redone.

To track origins from the moment the manager is created, pass them as
`tracked_origins` in `Yex.UndoManager.Options` instead of calling
`include_origin/2` afterwards; otherwise a `nil`-origin change made in between
is captured.

## Undo and redo origins

Undo and redo commit a transaction whose origin is the manager itself. Update
subscribers (`Yex.Doc.monitor_update/2`) and observers (`Yex.SharedType.observe/2`)
receive that `%Yex.UndoManager{}` as the origin, so it can be matched against the
manager in use:

    receive do
      {:update_v1, _update, ^undo_manager, _doc} -> :undo_or_redo
    end

## Stack events and meta

`observe/2` subscribes the calling process to changes of the undo and redo stacks.
Each captured transaction produces one `Yex.UndoManager.StackItemEvent` (`:added` or
`:updated`), each undo or redo that changes the document produces an `:added` event
for the item pushed onto the other stack followed by a `:popped` event, and `clear/1`
produces a `Yex.UndoManager.StackClearedEvent`. Events for one manager arrive in
commit order, and they are in the mailbox of a subscriber when the call that caused
them returns to it.

Every stack item has an id (`:item`) and a meta term, `nil` until set with
`put_meta/3`. Applications store state to restore on undo, such as a cursor as a
`Yex.StickyIndex`, when an item is added, and read it back from the `:popped` event:

    ref = Yex.UndoManager.observe(undo_manager)
    cursor = Yex.StickyIndex.new(text, 0, :after)
    Yex.Text.insert(text, 0, "a")

    receive do
      {:undo_manager_event, ^ref, %Yex.UndoManager.StackItemEvent{type: :added, item: id}, _} ->
        Yex.UndoManager.put_meta(undo_manager, id, cursor)
    end

Yjs sets meta synchronously inside the event handler. Here the subscriber sets it
after the event arrives, so:

* An undo issued before `put_meta/3` runs pops the item without its meta: the
  `:popped` event carries `nil` and `put_meta/3` returns `{:error, :not_found}`. This
  happens when another process issues the undo, and when the subscriber is the
  document's worker and a call delegated to it runs before it handles the event. Set
  meta in the process that issues undo and redo.
* The state to store is the state before the change, which may have moved on by the
  time the event is handled (for example, a second edit arrived first). Since there
  is exactly one `:added` or `:updated` event per captured transaction, in commit
  order, keep a queue of the state before each edit and take one entry per event.

Meta lives in the stack item and is freed with it. A meta term that holds the undo
manager, directly or through another term such as a `Yex.Subscription`, keeps the
manager alive forever.
Meta that holds the document, such as a `Yex.StickyIndex`, is freed when the manager
is, so it does not keep the document alive.

A subscription keeps its manager alive and capturing until it is removed with
`unobserve/1` or its process exits.

Unlike Yjs, dropping the redo stack because of a new change emits no
`Yex.UndoManager.StackClearedEvent`; `redo_stack_size/1` reports it.

# `t`

```elixir
@type t() :: %Yex.UndoManager{doc: Yex.Doc.t(), reference: reference()}
```

# `can_redo?`

```elixir
@spec can_redo?(t()) :: boolean()
```

Returns whether the redo stack holds at least one item.

# `can_undo?`

```elixir
@spec can_undo?(t()) :: boolean()
```

Returns whether the undo stack holds at least one item.

# `clear`

```elixir
@spec clear(t()) :: :ok | {:error, term()}
```

Clears all StackItems stored within current UndoManager, effectively resetting its state.

## Example:
    text = Doc.get_text(doc, "text")
    undo_manager = UndoManager.new(doc, text)

    Text.insert(text, 0, "Hello")
    Text.insert(text, 5, " World")
    UndoManager.clear(undo_manager)
    # All undo/redo history is now cleared

Subscribers from `observe/2` receive a `Yex.UndoManager.StackClearedEvent` when
either stack held items.

Raises `Yex.TransactionAcqError` instead of blocking when a write
transaction on the document is open, for example inside
`Yex.Doc.transaction/3`.

# `exclude_origin`

Excludes an origin from being tracked by the UndoManager.

This removes an origin added with `include_origin/2` or `tracked_origins`. Origins
that were never included are already not captured, so excluding one has no effect.
Excluding the last tracked origin makes the manager capture `nil`-origin
transactions again.

# `expand_scope`

Expands the scope of the UndoManager to include additional shared types.
See "Scope" in the module documentation for the accepted scopes.

Returns `:ok`, or `{:error, message}` such as
`{:error, "Failed to get branch reference"}` when the scope cannot be accessed.
Raises `Yex.TransactionAcqError` when a transaction on the document is open, and
`ArgumentError` when `scope` belongs to a document other than the manager's.

# `get_meta`

```elixir
@spec get_meta(t(), pos_integer()) :: {:ok, term()} | {:error, :not_found}
```

Returns the meta of the stack item `item`, `nil` when none was set.

Returns `{:error, :not_found}` under the same conditions as `put_meta/3`.

# `include_origin`

Includes an origin to be tracked by the UndoManager.

After the first included origin, transactions with a `nil` origin are no longer
captured. See "Tracked origins" in the module documentation.

# `is_valid_scope`
*macro* 

# `new`

```elixir
@spec new(
  Yex.Doc.t(),
  struct()
) :: {:ok, t()} | {:error, term()}
```

Creates a new UndoManager for the given document and scope with default options.
See "Scope" in the module documentation for the accepted scopes.

## Errors
- Returns `{:error, "NIF error: Failed to get branch reference"}` if there's an error
  accessing the scope
- Raises `Yex.TransactionAcqError` when a transaction on the document is open,
  for example inside `Yex.Doc.transaction/3`
- Raises `ArgumentError` if `scope` belongs to a document other than `doc`

# `new_with_options`

```elixir
@spec new_with_options(Yex.Doc.t(), struct(), Yex.UndoManager.Options.t()) ::
  {:ok, t()} | {:error, term()}
```

Creates a new UndoManager with the given options.

## Options

See `Yex.UndoManager.Options` for available options.

## Errors
- Returns `{:error, "NIF error: <message>"}` if underlying NIF returns an error
- Raises `Yex.TransactionAcqError` when a transaction on the document is open,
  for example inside `Yex.Doc.transaction/3`
- Raises `ArgumentError` if `scope` belongs to a document other than `doc`

# `observe`

```elixir
@spec observe(
  t(),
  keyword()
) :: reference()
```

Subscribes the calling process to stack events of the undo manager.

Messages have the shape:

    {:undo_manager_event, ref, event, metadata}

where `ref` is the returned reference, `event` is a `Yex.UndoManager.StackItemEvent`
or a `Yex.UndoManager.StackClearedEvent`, and `metadata` is the `:metadata` option
(default `nil`). See "Stack events and meta" in the module documentation.

Can be called inside `Yex.Doc.transaction/3`; the changes of that transaction are
delivered when it commits.

## Options
  * `:metadata` - a term attached to every message of this subscription.

# `put_meta`

```elixir
@spec put_meta(t(), pos_integer(), term()) :: :ok | {:error, :not_found}
```

Sets the meta of the stack item `item`, an id from a
`Yex.UndoManager.StackItemEvent`, replacing the previous value.

Returns `{:error, :not_found}` when the item is no longer on either stack: it was
popped, cleared, or dropped from the redo stack by a new change.

# `redo`

```elixir
@spec redo(t()) :: :ok | {:error, term()}
```

Redoes the last undone change.

Returns `:ok` whether or not anything was redone; use `redo_with_result/1`
to learn which. Raises `Yex.TransactionAcqError` when a transaction
on the document is open.

# `redo_stack_size`

```elixir
@spec redo_stack_size(t()) :: non_neg_integer()
```

Returns the number of items on the redo stack.

# `redo_with_result`

```elixir
@spec redo_with_result(t()) :: {:ok, boolean()} | {:error, term()}
```

Redoes the last undone change and reports whether the document changed.

Returns `{:ok, false}` when the redo stack is empty. Raises
`Yex.TransactionAcqError` when a transaction on the document is open,
whether or not the stack is empty.

# `stop_capturing`

Stops capturing changes for the current stack item.
This ensures that the next change will create a new stack item instead of
being merged with the previous one, even if it occurs within the normal timeout window.

## Example:
    text = Doc.get_text(doc, "text")
    undo_manager = UndoManager.new(doc, text)

    Text.insert(text, 0, "a")
    UndoManager.stop_capturing(undo_manager)
    Text.insert(text, 1, "b")
    UndoManager.undo(undo_manager)
    # Text.to_string(text) will be "a" (only "b" was removed)

# `undo`

```elixir
@spec undo(t()) :: :ok | {:error, term()}
```

Undoes the last tracked change.

Returns `:ok` whether or not anything was undone; use `undo_with_result/1`
to learn which. Raises `Yex.TransactionAcqError` when a transaction
on the document is open (for example when called inside
`Yex.Doc.transaction/3`), because undo commits a transaction of its own.

# `undo_stack_size`

```elixir
@spec undo_stack_size(t()) :: non_neg_integer()
```

Returns the number of items on the undo stack.

Changes of a transaction that is still open are captured when it commits, so they
are not counted yet.

# `undo_with_result`

```elixir
@spec undo_with_result(t()) :: {:ok, boolean()} | {:error, term()}
```

Undoes the last tracked change and reports whether the document changed.

Returns `{:ok, false}` when the undo stack is empty. Raises
`Yex.TransactionAcqError` under the same condition as `undo/1`,
whether or not the stack is empty.

# `unobserve`

```elixir
@spec unobserve(reference()) :: :ok
```

Removes a subscription created with `observe/2`. Returns `:ok` also when it was
already removed.

---

*Consult [api-reference.md](api-reference.md) for complete listing*
