# `Yex.StickyIndex`
[🔗](https://github.com/satoren/y_ex/blob/main/lib/sticky_index.ex#L1)

A sticky index provides position references that are unaffected by document changes, based on the Yjs model.
It maintains its relative position when placed before or after specific characters or elements.

## Features
- Stable position references unaffected by document changes
- Compatible with shared types like Text, Array, and XML
- Maintains relative positions after insert/delete operations
- Ideal for tracking cursor positions and text selections

## Usage
Numeric indices are unsuitable for tracking user selections because their positions
change when content is inserted or deleted. Sticky indices provide stable references
that maintain their relative positions through such changes:

    iex> alias Yex.{StickyIndex, Doc, Text}
    iex> doc = Doc.new()
    iex> txt = Doc.get_text(doc, "text")
    iex> Doc.transaction(doc, fn ->
    ...>  Text.insert(txt, 0, "abc")
    ...>  # => 'abc'
    ...>  # Create position tracker (marked as . in comments)
    ...>  pos = StickyIndex.new(txt, 2, :after)
    ...>  # => 'ab.c'
    ...>
    ...>  # Modify text
    ...>  Text.insert(txt, 1, "def")
    ...>  # => 'adefb.c'
    ...>  Text.delete(txt, 4, 1)
    ...>  # => 'adef.c'
    ...>
    ...>  # Get current offset index
    ...>  {:ok, a} = StickyIndex.get_offset(pos)
    ...>  # => 4
    ...>  assert a.index == 4
    ...> end)

# `shared_type`

```elixir
@type shared_type() ::
  %Yex.Array{doc: term(), reference: term()}
  | %Yex.Text{doc: term(), reference: term()}
  | %Yex.XmlElement{doc: term(), reference: term()}
  | %Yex.XmlText{doc: term(), reference: term()}
  | %Yex.XmlFragment{doc: term(), reference: term()}
```

# `t`

```elixir
@type t() :: %Yex.StickyIndex{
  assoc: :before | :after,
  doc: Yex.Doc.t(),
  reference: reference()
}
```

# `assoc`

```elixir
@spec assoc(t()) :: -1 | 0
```

Gets the association direction of a StickyIndex.

## Returns

- `-1` for `:before` association
- `0` for `:after` association

# `decode`

```elixir
@spec decode(Yex.Doc.t(), binary()) ::
  t() | {:error, {:encoding_exception, String.t()}}
```

Decodes a StickyIndex from binary format with the given Doc context (v1 - default).

This reverses the encoding done by `encode/1` or `encode_v1/1`. The Doc is required
to associate the decoded StickyIndex with its document context.

Returns `{:error, {:encoding_exception, message}}` when `binary` cannot be decoded.

# `decode_v1`

```elixir
@spec decode_v1(Yex.Doc.t(), binary()) ::
  t() | {:error, {:encoding_exception, String.t()}}
```

Decodes a StickyIndex from binary flexbuffer format (v1).

Returns `{:error, {:encoding_exception, message}}` when `binary` cannot be decoded.

# `decode_v2`

```elixir
@spec decode_v2(Yex.Doc.t(), binary()) ::
  t() | {:error, {:encoding_exception, String.t()}}
```

Decodes a StickyIndex from JSON string format (v2).

This reverses the encoding done by `encode_v2/1`. The Doc is required to associate
the decoded StickyIndex with its document context.

Returns `{:error, {:encoding_exception, message}}` when `binary` cannot be decoded.

# `encode`

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

Encodes a StickyIndex to binary format using flexbuffer encoding (v1 - default).

This provides a compact binary representation suitable for storage or transmission.
The encoded binary can be decoded using `decode/2` or `decode_v1/2`.

# `encode_v1`

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

Encodes a StickyIndex to binary flexbuffer format (v1).

# `encode_v2`

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

Encodes a StickyIndex to JSON string format (v2).

This provides a JSON string representation of the StickyIndex suitable for
interoperability with other systems.

# `from_json`

```elixir
@spec from_json(String.t(), Yex.Doc.t()) :: {:ok, t()} | {:error, atom()}
```

Reconstructs a StickyIndex from JSON representation.

This delegates to the reconstruction NIF (`Yex.Nif.sticky_index_from_json/2`).

## Input constraints

- `json` must be a binary JSON payload in StickyIndex/RelativePosition format.
- `doc` must be a `%Yex.Doc{}` associated with the reconstructed StickyIndex.

## Returns

- `{:ok, sticky_index}` when reconstruction succeeds
- `{:error, reason}` when reconstruction fails (for example `:invalid_json`)

# `get_offset`

```elixir
@spec get_offset(t()) :: {:ok, %{index: integer(), assoc: :before | :after}} | :error
```

Resolves the sticky index to its current numeric position in the shared type.

Returns `{:ok, %{index: index, assoc: assoc}}`, or `:error` when the position
can no longer be resolved (for example, the shared type has been deleted).

# `new`

```elixir
@spec new(shared_type(), integer(), :before | :after) :: t()
```

Creates a sticky index for the given position of a shared type.

`assoc` decides which neighbour the index sticks to:

  * `:after` - the index sticks to the element at `index`, so content inserted
    at that position goes before it.
  * `:before` - the index sticks to the element at `index - 1`, so content
    inserted at that position goes after it.

# `to_json`

```elixir
@spec to_json(t()) :: String.t()
```

Converts a StickyIndex to JSON representation.

Returns a serialized JSON string with StickyIndex position and association information in a format
compatible with Yjs RelativePosition and yffi's ysticky_index_to_json.

## Returns

A JSON string containing an object with:
- Exactly one of `"item"`, `"type"`, or `"tname"`
- `"item"` - `{"client": u64, "clock": u32}` for relative positions in existing content
- `"type"` - `{"client": u64, "clock": u32}` for nested empty-type positions
- `"tname"` - Type name string for root-level empty-type positions
- `"assoc"` - Association value: `-1` for `:before`, `0` for `:after`

---

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