Every change to a document happens inside a transaction. When a transaction ends, the document
tells you what changed: observers on the types get events, and on_update handlers get the
update bytes to send to peers.
This page covers how to group writes, how to tag them with an origin, and how to listen.
Each write is its own transaction by default. Three set calls give three updates and three
rounds of events.
To make several writes one transaction, open a guard with doc.transact(). The transaction ends
when the guard is destroyed.
#include <ycpp/doc.hpp>
#include <ycpp/map.hpp>
ycpp::Doc doc(1);
ycpp::MapRef map = doc.map("root");
{
ycpp::Doc::TransactionGuard guard = doc.transact();
(void)map.set("a", ycpp::Any{1});
(void)map.set("b", ycpp::Any{2});
(void)map.set("c", ycpp::Any{3});
} // one update, one map event with the three keysThis is Yjs's doc.transact(() => { ... }), with the end of the scope in place of the end of
the function.
guard.commit()ends the transaction early. A secondcommit()does nothing.- A guard can be moved. The transaction ends when the guard that holds it ends.
- A guard opened inside another one joins the outer transaction, as in Yjs. Nothing is emitted until the outer guard ends.
- A guard that outlives its
Docdoes nothing. apply_updateruns in a transaction too. Called inside a guard, it joins that transaction.
Step by step, when a transaction ends:
- If it changed nothing, it stops. No observer is called and no update is emitted. See Empty transactions.
- The observers run. Map observers first, then text, then array, then xml, then deep observers, then the subdocuments event. Within one kind, types are reported in the order the transaction first touched them.
- If a remote change touched formatted text, the redundant formatting is cleaned up, in a transaction of its own, as Yjs does.
- Undo managers record the transaction.
- Deleted content is thrown away (when
gcis on), and neighbouring items are merged. - The update is encoded, if the transaction added or deleted items. Encoding after the cleanup means content deleted in the same transaction never goes out, as in Yjs.
- The
on_updatehandlers receive the update.
Observers see the transaction before step 6. So the content of what was just deleted is still readable while they run.
An observer may write to the document. That write opens a new transaction, which runs through all the steps after the current one finishes. An observer never sees a half-finished transaction.
An origin is a value you attach to a transaction, to say where it came from. Observers and
handlers read it back with doc.origin(). Typical uses:
- Tell your own edits from a peer's, so you do not send a peer's update back to that peer.
- Tell an undo from a normal edit.
- Decide what an undo manager records.
{
ycpp::Doc::TransactionGuard guard = doc.transact(ycpp::Any{"toolbar"});
(void)map.set("bold", ycpp::Any{true});
}Inside any observer or on_update handler of that transaction, doc.origin() returns
Any{"toolbar"}. Outside a callback it returns null.
transact()without an argument uses a null origin, as Yjs does. A single write outside a guard has a null origin too.- In a nested guard, only the outer guard's origin counts.
- The origin is an
Any, so it is compared by value. Yjs compares origins by object identity; pick values that are distinct enough (a string naming the source, or a number).
apply_update has no origin argument. To give a peer's update an origin, open a guard around
it:
{
ycpp::Doc::TransactionGuard guard = doc.transact(ycpp::Any{"network"});
(void)doc.apply_update(bytes);
}apply_update_v2(bytes, origin) takes the origin directly.
This matters for undo. An undo manager records null-origin transactions by default. A remote update applied without an origin would be recorded as if it were a local edit (Yjs behaves the same way). See Undo.
doc.set_local_origin(origin) sets an origin that every following transaction carries, until
you set it back to null. It wins over the origin given to transact(). It exists for bindings
that hold a group open across several calls, like the Python binding's transaction block.
ycpp::Connection on_update(UpdateHandler handler, void* context = nullptr);
// using UpdateHandler = void (*)(void* context, std::span<const byte> update);The handler is called once per transaction that added or deleted something. It receives that transaction's update, in the Yjs v1 format. The bytes are only valid during the call: copy them if you keep them.
#include <span>
#include <vector>
struct Outbox {
ycpp::Doc* doc;
std::vector<std::vector<ycpp::byte>> pending;
};
Outbox outbox{&doc, {}};
ycpp::Connection sending = doc.on_update(
[](void* context, std::span<const ycpp::byte> update) {
auto* box = static_cast<Outbox*>(context);
// Do not echo a peer's update back to the network.
if (box->doc->origin() == ycpp::Any{"network"}) {
return;
}
box->pending.emplace_back(update.begin(), update.end());
},
&outbox);Handlers are plain function pointers with a void* context. There is no std::function, so
registering one does not allocate a closure. A lambda with no captures converts to the
function pointer.
A handler added while a transaction runs its observers still receives that transaction's update, as in Yjs: the update is sent after the observers.
Each type has observe, for changes to that type only, and observe_deep, for changes to that
type and everything nested in it. Each is called once per transaction, after the transaction,
whether the change was local or came from a peer.
// using MapObserver = void (*)(void* context, std::span<const MapChange> changes);
ycpp::Connection watching = map.observe(
[](void*, std::span<const ycpp::MapChange> changes) {
for (const ycpp::MapChange& change : changes) {
const char* action = change.action == ycpp::MapAction::added ? "added"
: change.action == ycpp::MapAction::updated ? "updated"
: "removed";
std::printf("%s %s\n", change.key.c_str(), action);
if (change.old_value.has_value()) {
std::printf(" was %s\n", ycpp::to_json(*change.old_value).c_str());
}
}
});A MapChange is one key the transaction changed, as Yjs's event.keys:
key: the key.action:added,updatedorremoved.old_value: the value before the transaction. It is empty for an added key. It is also empty when the old value cannot be read back as anAny(a nested type, for example).
Text and array observers receive a delta: the change as a list of operations, as Yjs's
event.delta.
// using TextObserver = void (*)(void* context, std::span<const Any> delta);
// using ArrayObserver = void (*)(void* context, std::span<const Any> delta);
ycpp::Connection typing = text.observe(
[](void*, std::span<const ycpp::Any> delta) {
for (const ycpp::Any& op : delta) {
std::printf("%s\n", ycpp::to_json(op).c_str());
}
});
(void)text.insert(0, "ab");
(void)text.insert(1, "x"); // prints {"retain":1} then {"insert":"x"}A delta walks the type from the start. Each operation is an Any map with one of these keys:
retain: n: skipnunits. Withattributes, it changed the formatting of those units (text only).insert: content inserted here. A string for text, with itsattributesif it has any. An array of values for an array.delete: n:nunits removed here.
A trailing retain is left out. For text, units are UTF-16 code units; for an array, elements. See Shared types for a picture.
Xml observers (XmlFragmentRef::observe, and the same on elements and texts) receive an
XmlEvent:
child_list_changed: children were inserted or deleted.attributes_changed: the attribute keys that changed.keysanddelta: the same key changes and delta as above.
An XmlTextRef reports an XmlEvent too, not a text event, as in Yjs.
// using DeepObserver = void (*)(void* context, std::span<const Event> events);
ycpp::Connection deep = root.observe_deep(
[](void*, std::span<const ycpp::Event> events) {
for (const ycpp::Event& event : events) {
for (const ycpp::PathStep& step : event.path()) {
if (const auto* key = std::get_if<std::pmr::string>(&step)) {
std::printf("/%s", key->c_str());
} else {
std::printf("/%zu", std::get<std::size_t>(step));
}
}
std::printf(" %zu keys, %zu delta ops\n", event.keys().size(), event.delta().size());
}
});A deep observer gets every change below its type, in one call per transaction. Each Event
describes one changed type:
path(): the steps from the observed type to the changed type. A step is a map key (a string) or a list index (asize_t). An empty path means the observed type itself changed.keys(): the key changes, for a map target.delta(): the delta, for an array or text target.target_kind():map,arrayortext.target_type_ref()tells the xml kinds apart too.target_parent()andtarget_name(): which type changed, in the form a handle uses (see Shared types). Pass them todoc.map_handle(...)and friends to get a handle to the changed type.
This is Yjs's observeDeep. As in Yjs, each observer sees paths relative to the type it
observes.
Deep observers exist when the library is built with -Dobserve_deep=enabled (the default).
doc.observe_subdocs(handler, context) is called once per transaction that added, removed or
loaded subdocuments. See Shared types.
A Doc has two callbacks of its own: on_update and observe_subdocs. Yjs's
beforeTransaction, afterTransaction and updateV2 events have no ycpp counterpart. To get
v2 bytes, encode them from the document with encode_state_as_update_v2.
A transaction that changes nothing emits nothing. No observer is called, and no update is sent. This is what Yjs does too.
Examples of transactions that change nothing:
{ ycpp::Doc::TransactionGuard guard = doc.transact(); } // nothing written
(void)map.erase("no-such-key"); // nothing to delete
(void)doc.apply_update(bytes); // a second time: already knownThe update handlers follow a slightly narrower rule: an update is only sent when the transaction added or deleted items. A transaction that only loads a subdocument fires the subdocuments event but sends no update, because there is nothing for peers to apply.
Every observe, observe_deep, on_update and observe_subdocs returns a Connection.
- The observer stays registered until you call
disconnect(), or until theDocis destroyed. - Dropping the
Connectiondoes not unregister the observer. AConnectionis a handle you can use to unregister, not an owner. Keep it if you will need to stop listening. - So the
contextpointer must stay valid as long as the observer is registered. Disconnect before you free what it points to. disconnect()can be called more than once. It is safe after theDocis gone: aConnectiononly holds a weak reference to the document.connected()is true while theDoclives and the connection was not disconnected.- An observer may disconnect itself, or another observer, from inside a callback. A disconnected observer is not called again, even later in the same dispatch.
- An observer added during a dispatch hears only later transactions. (
on_updateis the exception noted above.) - A callback may even destroy the
Doc. The dispatch then stops.
Undo manager observers work the same way but return a number instead of a Connection: see
Undo.