Yex.Doc (y_ex v0.13.0)

Copy Markdown View Source

Document module.

Cross-Process Operations

When a Doc or SharedType operation is performed from a process different from the process that created the Doc, a message like {Yex.Doc, :run, fun} is sent to the creator process via GenServer.call and the processing is delegated to that process. If you encounter a GenServer.call timeout, this delegation mechanism may be the cause. Make sure the worker process can handle the GenServer call messages properly.

It is recommended to start a GenServer process such as Yex.DocServer when executing operations from other processes.

Summary

Functions

Returns whether the document, when used as a subdocument, is loaded automatically.

Returns the client ID of the document.

Returns the collection ID of the document, or an empty string when none was set.

Stop monitoring document updates.

Stop monitoring document updates started with monitor_update_v1/2.

Stop monitoring document updates started with monitor_update_v2/2.

Destroys the document, dropping all of its observers and destroying its subdocuments.

Garbage-collects deleted content now, even when the document was created with skip_gc: true.

Get or insert the array type.

Get or insert the map type.

Returns the pending delete set (v1 encoded) for the document, if any.

Returns the pending update (v1 encoded) for the document, if any.

Get or insert the text type.

Get or insert the xml fragment type.

Returns the globally unique identifier of the document.

Evaluates a JSONPath expression against the current document state.

Requests a subdocument to be loaded.

Monitor subdocument changes.

Monitor document updates. You can pass metadata as an option. This value is passed as the fourth element of the message.If omitted, it will be passed as a structure of Doc itself.

Monitor document updates encoded with the v1 format.

Monitor document updates encoded with the v2 format.

Create a new document.

Returns how text offsets are measured: :bytes (UTF-8 bytes) or :utf16 (UTF-16 code units).

Removes and returns the pending update and pending delete set (v1 encoded, merged into one update) for the document, if any.

Lists every root type the document holds as {name, kind}. Order is unspecified.

Executes the given block in the document's worker process. If the current process is already the worker process, executes directly. Otherwise, delegates execution to the worker process via GenServer.call.

Returns whether the document, when used as a subdocument, should be loaded by the provider.

Returns whether garbage collection of deleted content is disabled for the document.

Create a new document with options.

Types

t()

@type t() :: %Yex.Doc{reference: any(), worker_pid: pid() | nil}

Functions

auto_load(doc)

@spec auto_load(t()) :: boolean()

Returns whether the document, when used as a subdocument, is loaded automatically.

client_id(doc)

@spec client_id(t()) :: integer()

Returns the client ID of the document.

The client ID uniquely identifies this replica when generating updates.

Examples

iex> doc = Yex.Doc.with_options(%Yex.Doc.Options{client_id: 10})
iex> Yex.Doc.client_id(doc)
10

collection_id(doc)

@spec collection_id(t()) :: String.t()

Returns the collection ID of the document, or an empty string when none was set.

demonitor_update(sub)

@spec demonitor_update(reference()) :: :ok | {:error, term()}

Stop monitoring document updates.

demonitor_update_v1(sub)

@spec demonitor_update_v1(reference()) :: :ok | {:error, term()}

Stop monitoring document updates started with monitor_update_v1/2.

demonitor_update_v2(sub)

@spec demonitor_update_v2(reference()) :: :ok | {:error, term()}

Stop monitoring document updates started with monitor_update_v2/2.

destroy(doc)

@spec destroy(t()) :: :ok

Destroys the document, dropping all of its observers and destroying its subdocuments.

When the document is a subdocument, its parent replaces it with a new, unloaded document with the same guid, and emits a subdocs event listing it under :removed and :added. Getting the subdocument from the parent again returns that new document. Use this to free a loaded subdocument.

Raises Yex.TransactionAcqError when called inside a transaction on the document or its parent.

force_gc(doc)

@spec force_gc(t()) :: :ok

Garbage-collects deleted content now, even when the document was created with skip_gc: true.

Deleted items are replaced by lightweight placeholders, so their content can no longer be restored (for example by an Yex.UndoManager or from a snapshot taken before the deletion). Works both inside and outside transaction/3.

Examples

iex> doc = Yex.Doc.with_options(%Yex.Doc.Options{skip_gc: true})
iex> text = Yex.Doc.get_text(doc, "text")
iex> Yex.Text.insert(text, 0, "Hello World")
iex> Yex.Text.delete(text, 0, 6)
iex> Yex.Doc.force_gc(doc)
:ok
iex> Yex.Text.to_string(text)
"World"

get_array(doc, name)

@spec get_array(t(), String.t()) :: Yex.Array.t()

Get or insert the array type.

get_map(doc, name)

@spec get_map(t(), String.t()) :: Yex.Map.t()

Get or insert the map type.

get_pending_ds(doc)

@spec get_pending_ds(t()) :: {:ok, binary() | nil} | {:error, term()}

Returns the pending delete set (v1 encoded) for the document, if any.

A pending delete set holds deletions that arrived out of order and could not yet be applied. Returns {:ok, binary()} when a pending delete set exists, {:ok, nil} otherwise.

get_pending_update(doc)

@spec get_pending_update(t()) :: {:ok, binary() | nil} | {:error, term()}

Returns the pending update (v1 encoded) for the document, if any.

A pending update accumulates operations that arrived out of order and could not yet be applied because their causal predecessors are missing. Returns {:ok, binary()} when a pending update exists, {:ok, nil} otherwise.

get_text(doc, name)

@spec get_text(t(), String.t()) :: Yex.Text.t()

Get or insert the text type.

get_xml_fragment(doc, name)

Get or insert the xml fragment type.

guid(doc)

@spec guid(t()) :: String.t()

Returns the globally unique identifier of the document.

A random GUID is generated when none was given in Yex.Doc.Options.

Examples

iex> doc = Yex.Doc.with_options(%Yex.Doc.Options{guid: "my-guid"})
iex> Yex.Doc.guid(doc)
"my-guid"

json_path(doc, path)

@spec json_path(t(), binary()) :: {:ok, list()} | {:error, term()}

Evaluates a JSONPath expression against the current document state.

Returns all matched values as a list. The path grammar follows yrs JSONPath support (for example: $.users[*].name, $.users..nick).

load(doc)

@spec load(t()) :: :ok

Requests a subdocument to be loaded.

Sets should_load/1 to true. When the document is a subdocument, its parent emits a subdocs event listing it under :loaded (see monitor_subdocs/2), which providers use to start syncing it.

Raises Yex.TransactionAcqError when called inside a transaction on the document or its parent.

monitor_subdocs(doc, opt \\ [])

@spec monitor_subdocs(
  t(),
  keyword()
) :: {:ok, reference()} | {:error, term()}

Monitor subdocument changes.

The calling process receives {:subdocs, %{added: [Yex.Doc.t()], removed: [Yex.Doc.t()], loaded: [Yex.Doc.t()]}, origin, metadata} messages whenever subdocuments are added to, removed from, or loaded in this document. You can pass metadata as an option; if omitted, the document itself is used.

Use Yex.Subscription.unsubscribe/1 with the returned reference to stop monitoring.

monitor_update(doc, opt \\ [])

@spec monitor_update(
  t(),
  keyword()
) :: {:ok, reference()} | {:error, term()}

Monitor document updates. You can pass metadata as an option. This value is passed as the fourth element of the message.If omitted, it will be passed as a structure of Doc itself.

The third element is the transaction's origin: the term passed to transaction/3, nil when none was given, or the %Yex.UndoManager{} for a transaction committed by Yex.UndoManager.undo/1 or Yex.UndoManager.redo/1.

monitor_update_v1(doc, opt \\ [])

@spec monitor_update_v1(
  t(),
  keyword()
) :: {:ok, reference()} | {:error, term()}

Monitor document updates encoded with the v1 format.

The calling process receives {:update_v1, update, origin, metadata} messages. See monitor_update/2 for the meaning of origin and the :metadata option.

monitor_update_v2(doc, opt \\ [])

@spec monitor_update_v2(
  t(),
  keyword()
) :: {:ok, reference()} | {:error, term()}

Monitor document updates encoded with the v2 format.

The calling process receives {:update_v2, update, origin, metadata} messages. See monitor_update/2 for the meaning of origin and the :metadata option.

new(worker_pid \\ self())

@spec new(pid()) :: t()

Create a new document.

worker_pid: If there is a possibility of passing the created document to another process, please specify the process responsible for operating the document. This process needs to handle the GenServer handle_call messages as follows:

@impl true
def handle_call(
      {Yex.Doc, :run, fun},
      _from,
      state
    ) do
  {:reply, fun.(), state}
end

offset_kind(doc)

@spec offset_kind(t()) :: :bytes | :utf16

Returns how text offsets are measured: :bytes (UTF-8 bytes) or :utf16 (UTF-16 code units).

prune_pending(doc)

@spec prune_pending(t()) :: {:ok, binary() | nil} | {:error, term()}

Removes and returns the pending update and pending delete set (v1 encoded, merged into one update) for the document, if any.

Pending state holds structs and deletions that arrived before their causal predecessors and are waiting on them. After this returns, both get_pending_update/1 and get_pending_ds/1 return {:ok, nil}, and the pruned content will no longer be integrated when the missing predecessors arrive. The returned binary can be re-applied later, for example once the missing updates have been fetched.

Works both inside and outside transaction/3. Returns {:ok, nil} when nothing is pending. Raises Yex.TransactionAcqError when a transaction held by another process prevents opening one.

root_refs(doc)

@spec root_refs(t()) :: [
  {String.t(),
   :map
   | :array
   | :text
   | :xml_fragment
   | :xml_element
   | :xml_text
   | :weak_link
   | :untyped}
]

Lists every root type the document holds as {name, kind}. Order is unspecified.

A root claimed by a typed getter reports its declared type: :map, :array, :text or :xml_fragment. :xml_element, :xml_text and :weak_link cover the remaining yrs types that can be a root.

A root no typed getter has claimed reports :untyped, whatever it holds. Every root a remote update created starts this way, and keeps it until something calls a typed getter with its name. The kind is not guessed from content: an XML fragment and an array of XML nodes, or a text and an array of strings, can hold the same items.

Examples

iex> doc = Yex.Doc.new()
iex> Yex.Doc.get_text(doc, "text")
iex> Yex.Doc.root_refs(doc)
[{"text", :text}]

run_in_worker_process(doc, list)

(macro)

Executes the given block in the document's worker process. If the current process is already the worker process, executes directly. Otherwise, delegates execution to the worker process via GenServer.call.

Raises if worker_pid is not set.

should_load(doc)

@spec should_load(t()) :: boolean()

Returns whether the document, when used as a subdocument, should be loaded by the provider.

skip_gc(doc)

@spec skip_gc(t()) :: boolean()

Returns whether garbage collection of deleted content is disabled for the document.

transaction(doc, origin \\ nil, exec)

@spec transaction(t(), origin :: term(), fun()) :: term()

Start a transaction.

Raises Yex.TransactionAcqError if a transaction is already in progress.

The transaction is committed when exec returns and also when it raises, throws or exits, like transact in yjs: changes made before the error are kept, their events are emitted, and then the error propagates. There is no rollback.

If the process running exec is killed, the transaction is committed when its resource is freed. That commit keeps the changes and releases the document, but its events cannot be delivered and are dropped.

Examples

iex> doc = Doc.new()
iex> text = Doc.get_text(doc, "text")
iex> Yex.Doc.monitor_update(doc)
iex> Doc.transaction(doc, fn ->
iex>   Text.insert(text, 0, "Hello")
iex>   Text.insert(text, 0, "Hello", %{"bold" => true})
iex> end)
iex> assert_receive {:update_v1, _, nil, _}
iex> refute_receive {:update_v1, _, nil, _}, 10 # only one update message

with_options(option, worker_pid \\ self())

@spec with_options(Yex.Doc.Options.t(), pid()) :: t()

Create a new document with options.

A random client id is used when client_id is nil (the default).

Raises ArgumentError when client_id is outside 0..9007199254740991 (2^53 - 1), the range of yjs client ids.