Automerge Repo - v2.6.0-alpha.1
    Preparing search index...

    Class DocHandle<T>

    A DocHandle is a wrapper around an Automerge document. It allows you to read and change the document, as well as to subscribe to changes.

    DocHandles are created by the Repo class, generally through repo.find() or repo.create().

    A simple DocHandle is defined by a URL with only a documentId, but it is also possible (via the URL) to specify a specific version via "heads", or to scope the handle to a subtree of the full document with a path.

    Conceptually a handle is just (document, path, range?, heads?):

    • A root handle has no path, range, or heads - it points at the whole live document. Repo only ever hands out root handles.
    • A sub-handle (from DocHandle.sub) has a non-empty path into the document; reads / writes / change events are scoped to that subtree.
    • A view-pinned handle (from DocHandle.view) has fixed heads; it reads at that point in time and rejects mutations.
    • A range handle covers a span of text inside a string-valued sub-handle.

    Handle identity is canonicalised by the per-document registry, so any two calls that name the same (path, range, heads) triple - even via different traversals - return the same DocHandle instance.

    To modify the underlying document use either DocHandle.change or DocHandle.changeAt. These methods will notify the Repo that some change has occured and the Repo handles persisting to your local storage as well as propagating changes to connected peers.

    Type Parameters

    • T
    Index

    Properties

    inState: (states: HandleState[]) => boolean

    Type declaration

      • (states: HandleState[]): boolean
      • Parameters

        Returns boolean

        true if the handle is in one of the given states.

    Will be removed in the next major.

    isDeleted: () => boolean

    Type declaration

      • (): boolean
      • Returns boolean

        true if the document has been marked as deleted.

    isReady: () => boolean

    Type declaration

      • (): boolean
      • Returns boolean

        true if the document has not been deleted. Repo only hands out handles that already have data, so this is true from construction unless delete() is called.

    isUnavailable: () => boolean

    Type declaration

      • (): boolean
      • Returns boolean

        true if the document is currently unavailable.

    Always returns false - find() rejects on unavailable docs rather than returning a handle. Will be removed in the next major.

    isUnloaded: () => boolean

    Type declaration

      • (): boolean
      • Returns boolean

        true if the document has been unloaded.

    Accessors

    • get _handleRetainerSize(): number
      Internal

      Number of handles with at least one listener attached.

      Returns number

    • get _trieNodeCount(): number
      Internal

      Number of nodes in the per-document handle trie. For tests.

      Returns number

    • get documentId(): DocumentId

      Returns DocumentId

    • get path(): ResolvedPathSegment[]

      Snapshot of this handle's segments with their currently-resolved prop values (key string / literal index / matched index). Fresh per call; empty on the root.

      Returns ResolvedPathSegment[]

    • get range(): undefined | CursorRange

      The cursor range for this handle, if any.

      Returns undefined | CursorRange

    • get url(): AutomergeUrl

      This handle's URL. The URL might include a path, or heads, both optionally. like this: automerge:<docId>[/path][#heads];

      Returns AutomergeUrl

    Methods

    • Internal

      Used by DocSynchronizer to deliver inbound ephemerals.

      Parameters

      • senderId: PeerId
      • message: unknown

      Returns void

    • Sends an arbitrary ephemeral message out to all reachable peers who would receive sync messages from you. It has no guarantee of delivery, and is not persisted to the underlying automerge doc in any way. Messages will have a sending PeerId but this is not a useful user identifier (a user could have multiple tabs open and would appear as multiple PeerIds). Every message source must have a unique PeerId.

      Parameters

      • message: unknown

      Returns void

    • All changes to an Automerge document should be made through this method. Inside the callback, the document should be treated as mutable: all edits will be recorded using a Proxy and translated into operations as part of a single recorded "change".

      Note that assignment via ES6 spread operators will result in replacing the object instead of mutating it which will prevent clean merges. This may be what you want, but doc.foo = { ...doc.foo, bar: "baz" } is not equivalent to doc.foo.bar = "baz".

      Local changes will be stored (by the StorageSubsystem) and synchronized (by the DocSynchronizer) to any peers you are sharing it with.

      On sub-handles a non-function callback is shorthand for "replace the value at this path" (e.g. counterSub.change(42)). Function-typed values can't use this shorthand - wrap them in () => yourFunction.

      A function callback's return value is ignored (the document is mutated in place), consistent with root and sub-handles alike - so an accidental arrow-expression return won't replace a scoped object. Use the shorthand form to intentionally overwrite a slot.

      Parameters

      Returns void

    • True if this handle's path is a strict ancestor of other's path, within the same document and view (heads).

      Parameters

      Returns boolean

    • Marks the document deleted and fans delete out to every retained handle (root and subs alike). Calling on a sub-handle deletes the whole document; use DocHandle.remove to remove a subtree. Prefer Repo.delete from user code.

      Returns void

    • Returns a set of Patch operations that will move a materialized document from one state to another if applied.

      Parameters

      Returns Automerge.Patch[]

      Automerge patches that go from one document state to the other

      We allow specifying either:

      • Two sets of heads to compare directly
      • A single set of heads to compare against our current heads
      • Another DocHandle to compare against (which must share history with this document)

      Error if the documents don't share history or if either document is not ready

    • The document (or subtree of one) that this handle is pointing at.

      Returns undefined | Automerge.Doc<T>

      the current Automerge.Doc value

      on deleted documents

      In past releases, this was asynchronous and could be undefined.

    • Emit an event on this handle. Routed through the registry's listener storage. Fires only this handle's listeners; use delete() to fan out the document-level lifecycle events.

      Type Parameters

      Parameters

      Returns boolean

    • True if the other handle has the same URL as this one.

      Parameters

      Returns boolean

    • Names of events with at least one listener attached.

      Returns (keyof DocHandleEvents<T>)[]

    • The whole underlying document (ignoring this handle's path/range), at this handle's fixed heads if it is view-pinned.

      Returns Automerge.Doc<T>

    • Returns the latest known heads for the given peer's storageId, or undefined if we have not received sync info from that peer.

      Parameters

      Returns undefined | UrlHeads

      Use DocHandle.getSyncInfo instead. Will be removed in the next major.

    • Returns the heads and the timestamp of the last update for the storageId.

      Parameters

      Returns undefined | SyncInfo

    • Returns the "heads" of the document, akin to a git commit. This precisely defines the state of a document.

      Returns UrlHeads

      the current document's heads (which may be fixed by .view() or equivalent)

    • Returns an array of all past "heads" for the document in topological order.

      Returns UrlHeads[]

      UrlHeads[] - The individual heads for every change in the document. Each item is a tagged string[1].

      A point-in-time in an automerge document is an array of heads since there may be concurrent edits. This API just returns a topologically sorted history of all edits so every previous entry will be (in some sense) before later ones, but the set of all possible history views would be quite large under concurrency (every thing in each branch against each other). There might be a clever way to think about this, but we haven't found it yet, so for now at least we present a single traversable view which excludes concurrency.

    • True if this handle is a strict descendant of other.

      Parameters

      Returns boolean

    • Check if the document can be change()ed. Currently, documents can be edited unless we are viewing a particular point in time.

      Returns boolean

      boolean indicating whether changes are possible

      It is technically possible to back-date changes using changeAt(), but we block it for usability reasons when viewing a particular point in time. To make changes in the past, use the primary document handle with no heads set.

    • Number of listeners attached for the given event.

      Type Parameters

      Parameters

      • event: E

      Returns number

    • Merges another document into this document. Any peers we are sharing changes with will be notified of the changes resulting from the merge.

      Parameters

      • otherHandle: DocHandle<T>

        the handle of the document to merge into this one

      Returns void

      the merged document.

      if either document is not ready or if otherHandle is unavailable.

    • Returns { numChanges: number; numOps: number }

    • True if this and other are both text-range handles on the same path whose ranges overlap in the current document.

      Parameters

      Returns boolean

    • Returns [startIndex, endIndex] for this handle's cursor range, resolved against the handle's own view of the document, or undefined if this handle has no range.

      Returns undefined | [number, number]

    • Called by the repo to reuse an unloaded handle.

      Returns void

    • Remove the value at this sub-handle's path from the underlying document.

      Returns void

    • Type Parameters

      Parameters

      • Optionalevent: E

      Returns this

    • Experimental

      Create a sub-handle scoped to a location inside this document.

      Returns the same DocHandle instance for the same path, ensuring referential equality via the per-document registry trie.

      This API is experimental and may change in future versions.

      Type Parameters

      Parameters

      • ...segments: [...TPath[]]

      Returns DocHandle<InferSubType<T, TPath>>

      const titleSub = handle.sub('todos', 0, 'title');
      titleSub.doc(); // string | undefined

      const sameSub = handle.sub('todos', 0, 'title');
      titleSub === sameSub; // true
    • Called by the repo to free memory used by the document.

      Returns void

    • Creates a fixed "view" of an automerge document at the given point in time represented by the heads passed in. The return value is the same type as doc() and will return undefined if the object hasn't finished loading.

      Parameters

      Returns DocHandle<T>

      DocHandle at the time of heads

      Note that our Typescript types do not consider change over time and the current version of Automerge doesn't check types at runtime, so if you go back to an old set of heads that doesn't match the heads here, Typescript will not save you.

      heads - The heads to view the document at. See history().

    • Returns a promise that resolves when the handle is in one of the given states (default ["ready"]).

      Parameters

      Returns Promise<void>

      Handles are always ready when handed out by Repo.find / Repo.create. Will be removed in the next major.