Options
All
  • Public
  • Public/Protected
  • All
Menu

Class CPresence<V>

A map for sharing presence info between present (simultaneously online) replicas, e.g., usernames or shared cursors.

Each replica controls a fixed key: its [[IRuntime.replicaID]]. Its value should be a plain object that contains presence info about itself, such as its user's latest [[Cursor]] location in a collaborative text editor.

To make yourself present and start listening to others, call setOurs followed by connect. To update your value, call updateOurs or setOurs again. If you know you are about to go offline, try to call disconnect to let others know; otherwise, they will infer it from a timeout (default 10 seconds).

CPresence attempts to detect presence accurately on a variety of networks (centralized, peer-to-peer, op-based, state-based). You may prefer a custom solution if you can detect presence more accurately, e.g., by asking a central server who is connected.

Values must be internally immutable; mutating a value internally will not change it on other replicas. Instead, use updateOurs.

See also:

  • CValueMap: for an ordinary collaborative map.
  • [[CMessenger]]: for sending ephemeral messages in general.

Type Parameters

  • V extends Record<string, any>

    The value type: a plain object that contains presence info about a single replica.

Hierarchy

Index

Constructors

  • new CPresence<V>(init: InitToken, options?: { ttlMS?: number; updateSerializer?: Serializer<Partial<V>> }): CPresence<V>
  • Constructs a CPresence.

    Type Parameters

    • V extends Record<string, any>

    Parameters

    • init: InitToken
    • options: { ttlMS?: number; updateSerializer?: Serializer<Partial<V>> } = {}
      • Optional ttlMS?: number

        The time-to-live for users who we have not heard from, after which their entry is deleted. Heartbeats sent twice as often keep present users alive. Default: TTL_MS_DEFAULT.

      • Optional updateSerializer?: Serializer<Partial<V>>

        Serializer for updates (setOurs and updateOurs), which change a subset of V's keys. Defaults to [[DefaultSerializer]].

    Returns CPresence<V>

Properties

name: string

Internal (this/parent) use only.

This Collab's name, which distinguishes it among its siblings in the tree of Collabs.

parent: Parent

Internal (this/parent) use only.

This Collab's parent in the tree of Collabs.

runtime: IRuntime

The ambient [[IRuntime]].

Use this to access utilities like [[IRuntime.replicaID]].

TTL_MS_DEFAULT: 10000 = 10000

The default time-to-live: 10 seconds.

Accessors

  • get connected(): boolean
  • get size(): number

Methods

  • [iterator](): IterableIterator<[string, V]>
  • Returns an iterator for entries in the map.

    The iteration order is NOT eventually consistent: it may differ on replicas with the same value.

    Returns IterableIterator<[string, V]>

  • canGC(): boolean
  • Internal (parent) use only.

    If this Collab is in its initial, post-constructor state, then this method may (but is not required to) return true; otherwise, it returns false.

    By default, this method always returns false; override to change.

    If this method returns true:

    1. The parent may choose to weakly reference this object to save memory (e.g., [[CLazyMap]] does so). If this becomes garbage collected, then is needed later, the parent will recreate it using the same constructor call.
    2. The parent may skip calling save during saving. When loading the resulting saved state, the parent will call load(null, meta). load should process this as if called with the output of save from a garbage-collectable state. For a nontrivial example, see CMultiValueMap.load's implementation.

    Returns boolean

  • connect(): void
  • disconnect(): void
  • Disconnects from the group, marking us as not present.

    If you know the local user is about to go offline, try to call this method to let others know; otherwise, they will infer it from a timeout (default 10 seconds).

    Disconnection affects others' view of us, not our view of them. When disconnected, you may wish to treat others as offline even though CPresence still has their state.

    Returns void

  • emit<K>(eventName: K, event: MapEventsRecord<string, V>[K] & CollabEvent, options?: { skipAnyEvent?: boolean }): void
  • Emits an event, which triggers all the registered event handlers.

    See [[CollabEventsRecord]] for advice on what events to emit.

    This is a wrapper around [[EventEmitter.emit]] that forces events to extend [[CollabEvent]] and also emits an "Any" event.

    Type Parameters

    • K extends keyof MapEventsRecord<string, V>

    Parameters

    • eventName: K
    • event: MapEventsRecord<string, V>[K] & CollabEvent
    • Optional options: { skipAnyEvent?: boolean }
      • Optional skipAnyEvent?: boolean

        Set to true to skip emitting an "Any" event.

    Returns void

  • entries(): IterableIterator<[string, V]>
  • Returns an iterator for entries in the map.

    The iteration order is NOT eventually consistent: it may differ on replicas with the same value.

    Returns IterableIterator<[string, V]>

  • finalize(): void
  • Internal (parent) use only.

    Called by this Collab's parent when it has been deleted from a collection on the local replica and can no longer be used (e.g., due to CSet.delete on this or an ancestor). A Collab implementation can implement this method to clean up external resources, e.g., associated DOM elements.

    finalize has no relation to the JavaScript garbage collector or canGC.

    By default, this method does nothing.

    Returns void

  • forEach(callbackfn: ((value: V, key: string, map: CPresence<V>) => void), thisArg?: any): void
  • Executes a provided function once for each (key, value) pair in the map, in the same order as entries.

    Parameters

    • callbackfn: ((value: V, key: string, map: CPresence<V>) => void)

      Function to execute for each value. Its arguments are the value, key, and this map.

        • (value: V, key: string, map: CPresence<V>): void
        • Parameters

          Returns void

    • Optional thisArg: any

      Value to use as this when executing callbackfn.

    Returns void

  • get(replicaID: string): undefined | V
  • Returns the value associated to key replicaID, or undefined if replicaID is not present.

    Parameters

    • replicaID: string

    Returns undefined | V

  • getOurs(): undefined | V
  • has(replicaID: string): boolean
  • keys(): IterableIterator<string>
  • Returns an iterator for keys (replicaIDs) in the map.

    The iteration order is NOT eventually consistent: it may differ on replicas with the same state.

    Returns IterableIterator<string>

  • load(savedState: null | SavedStateTree, meta: SavedStateMeta): void
  • Parameters

    • savedState: null | SavedStateTree
    • meta: SavedStateMeta

    Returns void

  • loadCRDT(savedState: null | Uint8Array, meta: SavedStateMeta, crdtMeta: CRDTSavedStateMeta): void
  • Called by this Collab's parent to load some saved state. You may assume that the saved state was generated by saveCRDT on some replica of this Collab, possibly in a different collaboration session, with guarantees set by the runtime.

    This method may also be called with savedState = null; you should ignore such calls (i.e., return immediately) unless you override canGC. If you do override canGC, see that method's docs for instructions.

    Parameters

    Returns void

  • loadPrimitive(savedState: null | Uint8Array, meta: SavedStateMeta): void
  • on<K>(eventName: K, handler: ((event: MapEventsRecord<string, V>[K], caller: CPresence<V>) => void), options?: { once?: boolean }): (() => void)
  • Registers an event handler that is triggered when the event happens.

    Type Parameters

    • K extends keyof MapEventsRecord<string, V>

    Parameters

    • eventName: K

      Name of the event to listen on.

    • handler: ((event: MapEventsRecord<string, V>[K], caller: CPresence<V>) => void)

      Callback that handles the event.

        • (event: MapEventsRecord<string, V>[K], caller: CPresence<V>): void
        • Parameters

          • event: MapEventsRecord<string, V>[K]
          • caller: CPresence<V>

          Returns void

    • Optional options: { once?: boolean }
      • Optional once?: boolean

        If true, the event handler is triggered at most once (the next time the event happens), then unsubscribed.

    Returns (() => void)

    An "off" function that removes the event handler when called.

      • (): void
      • Registers an event handler that is triggered when the event happens.

        Returns void

        An "off" function that removes the event handler when called.

  • receive(messageStack: (string | Uint8Array)[], meta: MessageMeta): void
  • Parameters

    • messageStack: (string | Uint8Array)[]
    • meta: MessageMeta

    Returns void

  • receiveCRDT(message: string | Uint8Array, meta: MessageMeta, _crdtMeta: CRDTMessageMeta): void
  • Receives a message sent by sendCRDT on a local or remote replica of this PrimitiveCRDT.

    This method processes the message, changes the local state accordingly, and emits events describing the local changes.

    This method may assume eventual, exactly-once, causal-order message delivery, and it must ensure strong eventual consistency.

    See [[Collab.receive]].

    Parameters

    Returns void

  • receivePrimitive(message: string | Uint8Array, meta: MessageMeta): void
  • save(): SavedStateTree
  • Returns SavedStateTree

  • saveCRDT(): Uint8Array
  • Returns saved state describing the current state of this Collab.

    The saved state may later be passed to loadCRDT on a replica of this Collab, possibly in a different collaboration session, with rules set by the runtime. For example, CRuntime allows load to be called only at the beginning of a session, before sending or receiving any messages.

    saveCRDT may be called at any time, possibly many times while an app is running. Calling saveCRDT should not affect this Collab's user-visible state.

    Returns Uint8Array

    The saved state.

  • savePrimitive(): Uint8Array
  • send(messageStack: (string | Uint8Array)[], metaRequests: MetaRequest[]): void
  • Broadcasts a message to other replicas of this Collab. The message will be delivered to all replicas' receive, including locally.

    For convenience, the message may be expressed as a stack of (Uint8Array | string), instead of just a single Uint8Array. This is useful for parents sending messages on behalf of their children; see the implementation of [[CObject]] for an example.

    Parameters

    • messageStack: (string | Uint8Array)[]

      The message to send, in the form of a stack of Uint8Arrays. Note that this method may mutate it in-place.

    • metaRequests: MetaRequest[]

      A stack of metadata requests. The runtime will use the union of these when creating the [[MessageMeta]] for receive. Note that the stack need not align with messageStack, and this method may mutate it in place.

    Returns void

  • sendCRDT(message: string | Uint8Array, metaRequest?: CRDTMetaRequest): void
  • Broadcasts a message to other replicas of this CRDT. The message will be delivered to all replicas' receiveCRDT, including locally.

    Call this method instead of [[Collab.send]] or [[CPrimitive.sendPrimitive]].

    By default, receiveCRDT's crdtMeta will contain all fields that are accessed during the sender's local call to receiveCRDT. You can request additional fields with metaRequest.

    Parameters

    • message: string | Uint8Array

      The message to send.

    • Optional metaRequest: CRDTMetaRequest

    Returns void

  • sendPrimitive(message: string | Uint8Array, metaRequest?: MetaRequest): void
  • Broadcasts a message to other replicas of this Collab. The message will be delivered to all replicas' receivePrimitive, including locally.

    Call this method instead of [[Collab.send]].

    Parameters

    • message: string | Uint8Array

      The message to send.

    • Optional metaRequest: MetaRequest

      A metadata request. The runtime will use this when creating the [[MessageMeta]] for receivePrimitive.

    Returns void

  • setOurs(value: V): void
  • updateOurs<P>(property: P, propertyValue: V[P]): void
  • Updates a single property in our value, leaving the other properties unchanged.

    Use this method for frequently-changed properties like cursor positions.

    Type Parameters

    • P extends string

    Parameters

    • property: P
    • propertyValue: V[P]

    Returns void

  • values(): IterableIterator<V>
  • Returns an iterator for values in the map.

    The iteration order is NOT eventually consistent: it may differ on replicas with the same state.

    Returns IterableIterator<V>

Generated using TypeDoc