Skip to content

Latest commit

 

History

History
456 lines (352 loc) · 18.5 KB

shared-types.md

File metadata and controls

456 lines (352 loc) · 18.5 KB

Shared types

A document holds shared types. Each one is a data structure that several replicas can edit at the same time and that merges their edits. ycpp has the same types as Yjs:

ycpp Yjs What it holds
MapRef Y.Map string keys to values
ArrayRef Y.Array an ordered list of values
TextRef Y.Text rich text: characters, embeds, formatting
XmlFragmentRef Y.XmlFragment an ordered list of xml nodes
XmlElementRef Y.XmlElement a tag, attributes and child nodes
XmlTextRef Y.XmlText a text that lives in an xml tree
XmlHookRef Y.XmlHook a named map, for your own structures

Plain values are of type Any, the JSON-like value of lib0 (the encoding library Yjs uses). A document can also hold another whole document: a subdocument.

The type family: Array, Map and Text are the base types; the xml types are built from them; values are Any or a subdocument

Handles

Every type is reached through a handle: MapRef, ArrayRef, TextRef, and so on. A handle is small and cheap to copy. It does not own anything.

  • A handle follows its Doc when the Doc is moved.
  • When the Doc is destroyed, the handle becomes inert. Every call does nothing and returns an empty result. connected() tells you whether a handle still reaches a document.
  • A default-constructed handle is inert too. Lookups that find nothing return one (for example child_array on a key that holds a string).
  • same_as(other) tells whether two handles name the same type.

You get a root type from the Doc by name. It is created on first use:

ycpp::MapRef settings = doc.map("settings");
ycpp::ArrayRef list = doc.array("list");
ycpp::TextRef body = doc.text("body");
ycpp::XmlFragmentRef page = doc.xml_fragment("page");

Every replica that asks for the same name gets the same type. Use a name for one kind of type only: in Yjs too, a root name has one type.

Each write is its own transaction and emits its own update. To group writes, see Events and transactions.

Map

A map from string keys to values. Concurrent writes to different keys all land. Concurrent writes to the same key resolve the same way on every replica: the write of the higher client id wins.

#include <cstdio>
#include <string_view>

#include <ycpp/doc.hpp>
#include <ycpp/map.hpp>

int main() {
  ycpp::Doc doc(1);
  ycpp::MapRef settings = doc.map("settings");

  (void)settings.set("gain", ycpp::Any{0.5});
  (void)settings.set("name", ycpp::Any{"mic"});
  (void)settings.set("muted", ycpp::Any{false});

  if (std::optional<ycpp::Any> gain = settings.get("gain")) {
    std::printf("gain = %g\n", gain->as_real());
  }
  std::printf("%zu keys, has name: %d\n", settings.size(), settings.contains("name"));

  settings.for_each(
      [](void*, std::string_view key, const ycpp::Any& value) {
        std::printf("%.*s = %s\n", static_cast<int>(key.size()), key.data(),
                    ycpp::to_json(value).c_str());
      },
      nullptr);

  (void)settings.erase("muted");                 // true when the key existed
  std::printf("%s\n", settings.to_json().c_str());  // {"gain":0.5,"name":"mic"}
  settings.clear();
}

Things to know:

  • set returns std::expected<void, Error>. It returns Error::too_deep for a value nested deeper than max_any_depth. It returns Error::malformed for a key or a string that is not valid UTF-8. Peers could not read such a value back, so it is never written.
  • Setting a key to the value it already holds is still a write. It emits an update, as in Yjs.
  • to_json() writes the keys sorted, with nested maps, arrays and texts expanded.

A value map, or a nested map?

There are two ways to put a map inside a map. They behave differently.

// 1. A plain value. It is replaced whole: two peers that change different fields concurrently
//    do not merge, one of the two writes wins.
ycpp::AnyMap position;
position.entries.emplace_back("x", ycpp::Any{10});
position.entries.emplace_back("y", ycpp::Any{20});
(void)settings.set("position", ycpp::Any{position});

// 2. A nested shared map. Each key merges on its own, like a root map.
ycpp::MapRef window = settings.map("window");
(void)window.set("width", ycpp::Any{800});
(void)window.set("height", ycpp::Any{600});

Use a nested shared type when peers edit parts of it independently. Use a plain value when it always changes as a whole.

map(key) creates the nested map when the key holds nothing. When the key already holds a value that is not a map, it returns an inert handle. To look without creating, use child(key), which returns std::optional<MapRef>. get(key) on a nested map returns a copy of its current entries as an Any.

Array

An ordered list. Concurrent inserts at the same place are all kept, in an order every replica agrees on.

#include <cstdio>
#include <span>
#include <vector>

#include <ycpp/array.hpp>
#include <ycpp/doc.hpp>

int main() {
  ycpp::Doc doc(1);
  ycpp::ArrayRef list = doc.array("list");

  const std::vector<ycpp::Any> first{ycpp::Any{1}, ycpp::Any{2}, ycpp::Any{3}};
  (void)list.insert(0, std::span<const ycpp::Any>(first));  // [1,2,3]
  (void)list.push_back(ycpp::Any{"four"});                  // [1,2,3,"four"]
  (void)list.push_front(ycpp::Any{0});                      // [0,1,2,3,"four"]
  (void)list.erase(1, 2);                                   // [0,3,"four"]

  std::printf("%zu: %s\n", list.length(), list.to_json().c_str());  // 3: [0,3,"four"]
  if (std::optional<ycpp::Any> second = list.get(1)) {
    std::printf("%lld\n", static_cast<long long>(second->as_integer()));  // 3
  }
  for (const ycpp::Any& value : list.slice(-2, 3)) {  // negative counts from the end
    std::printf("%s\n", ycpp::to_json(value).c_str());
  }
}
  • insert, push_back, push_front and erase return false when the index is out of range or a value cannot be written. The array is then left unchanged.
  • Positions count elements. A nested type is one element.
  • insert_map(i), insert_array(i) and insert_text(i) insert a nested shared type and return its handle. child_map(i), child_array(i) and child_text(i) reach one that is already there.

Text

Rich text: characters, embeds, and formatting attributes over them. It is the type behind collaborative editors (Yjs's y-quill, y-prosemirror and others write it).

#include <cstdio>

#include <ycpp/doc.hpp>
#include <ycpp/text.hpp>

int main() {
  ycpp::Doc doc(1);
  ycpp::TextRef body = doc.text("body");

  (void)body.insert(0, "Hello world");

  ycpp::AnyMap bold;
  bold.entries.emplace_back("bold", ycpp::Any{true});
  (void)body.format(6, 5, bold);  // "world" is bold

  ycpp::AnyMap image;
  image.entries.emplace_back("image", ycpp::Any{"a.png"});
  (void)body.insert_embed(11, ycpp::Any{image});

  std::printf("%s\n", body.to_string().c_str());  // Hello world   (embeds are not characters)
  std::printf("%zu\n", body.length());            // 12            (an embed counts as 1)
  for (const ycpp::Any& op : body.to_delta()) {
    std::printf("%s\n", ycpp::to_json(op).c_str());
  }
  // {"insert":"Hello "}
  // {"insert":"world","attributes":{"bold":true}}
  // {"insert":{"image":"a.png"}}

  body.erase(0, 6);  // "world" + embed
}

Formatting attributes

An attribute is a key with an Any value, like bold: true or link: "https://...". A null value (Any{nullptr}) removes the attribute.

  • format(index, length, attributes) sets attributes over a range.
  • insert(index, text) without attributes takes the attributes in force at index. Typing inside a bold word stays bold.
  • insert(index, text, attributes) uses exactly the attributes given. An empty map turns every attribute off for the new text.
  • insert_embed never inherits attributes, as in Yjs. Give them explicitly if you want them.
  • cleanup_formatting() removes formatting marks that no longer change anything, and returns how many it removed. Remote changes trigger this cleanup on their own, as in Yjs.

Deltas

A delta is the text as a list of operations, in the format of Quill (a rich text editor). to_delta() returns the whole text as insert operations. Text observers receive a change as a delta of retain, insert and delete operations (see Events).

A text as a delta: one insert per run of equal attributes; a format change as a retain with attributes

apply_delta writes a delta into the text. An easy way to build one is to parse JSON:

#include <ycpp/json.hpp>

auto delta = ycpp::parse_json(R"([{"retain":6},{"insert":"big ","attributes":{"bold":true}}])");
if (delta.has_value()) {
  (void)body.apply_delta(delta->as_array().items);
}

apply_delta checks the whole delta first. If one operation is invalid (a negative retain, for example), it returns Error::malformed and writes nothing.

Positions are UTF-16, storage is UTF-8

Every position and length in a text counts UTF-16 code units. That is what JavaScript counts, so a position means the same thing on a ycpp peer and on a Yjs peer. Strings go in and come out as UTF-8, and are stored as UTF-8.

For ASCII text, units, bytes and characters are the same. They differ for other characters. A character outside the Basic Multilingual Plane, like most emoji, is 4 bytes in UTF-8 and 2 units in UTF-16:

The string a, grinning face, b: 6 UTF-8 bytes, 4 UTF-16 units; position 2 sits between the two halves of the emoji

(void)body.insert(0, "a\U0001F600b");  // "a😀b": 6 bytes
// body.length() == 4
(void)body.insert(3, "!");             // after the emoji: "a😀!b"
body.erase(1, 2);                      // removes the emoji: "a!b"

Rules of thumb:

  • Never put a position between the two units of a pair. A split there turns both halves into U+FFFD (the replacement character), as it does in Yjs.
  • To turn a UTF-8 string into a length in units, use ycpp::utf8::utf16_length(text) from <ycpp/utf8.hpp>. It returns nothing when the bytes are not valid UTF-8.
  • insert refuses bytes that are not valid UTF-8 with Error::malformed.
  • A position past the end is clamped to the end, as in Yjs.

Nested types and shared positions

A text can hold a shared type as an embed: insert_map(i), insert_text(i) and insert_array(i) insert one, and child_map(i) and friends reach it again. In to_delta() the embedded type shows up as an insert of its value. runs() returns the same walk as to_delta(), but keeps the id of an embedded type so you can make a handle to it.

sticky_index(i) returns a position that later edits carry along. See Sync for relative positions.

Xml

The xml types hold a tree of nodes. Editors that use ProseMirror or similar models (through Yjs's y-prosemirror) store their documents this way.

  • XmlFragmentRef: a list of nodes. A root fragment comes from doc.xml_fragment(name).
  • XmlElementRef: a node with a tag name, attributes and children.
  • XmlTextRef: a text node. Its text() is a full TextRef with formatting.
  • XmlHookRef: a named map, for an integration that stores its own structure.
  • XmlNodeRef: any node, as you read it from a list. kind() says which kind it is, and as_element, as_text, as_hook and as_fragment turn it into the typed handle.
#include <cstdio>

#include <ycpp/doc.hpp>
#include <ycpp/xml.hpp>

int main() {
  ycpp::Doc doc(1);
  ycpp::XmlFragmentRef page = doc.xml_fragment("page");

  std::optional<ycpp::XmlElementRef> p = page.insert_element(0, "p");
  (void)p->set_attribute("class", ycpp::Any{"intro"});
  std::optional<ycpp::XmlTextRef> words = p->insert_text(0);
  (void)words->text().insert(0, "Hello");

  std::printf("%s\n", page.to_string().c_str());  // <p class="intro">Hello</p>

  for (const ycpp::XmlNodeRef& node : page.to_array()) {
    if (node.kind() == ycpp::XmlKind::element) {
      ycpp::XmlElementRef element = ycpp::as_element(node);
      std::printf("<%s> with %zu children\n", element.node_name().c_str(), element.length());
    }
  }
}
  • The insert functions return an empty std::optional when the index is past the end.
  • insert_element_after(node, name) and insert_text_after(node) insert next to a node you already hold.
  • next_sibling(), prev_sibling(), first_child() and parent_node() walk the tree.
  • to_string() renders the tree like Yjs's toString(). Tags are lowercased and attributes are sorted by key. Like Yjs, it does not escape text or attribute values, so the result is a rendering, not well-formed xml.
  • Formatting on an XmlTextRef renders as nested elements: a bold run renders as <bold>...</bold>.
  • An xml fragment can also sit under a map key (make_xml_fragment) or in an array element (insert_xml_fragment).

The xml types need -Dtext=enabled and -Darray=enabled (both are on by default).

Nested types

Map, array and text can hold each other, to any depth. Together they form a tree under the root types.

#include <ycpp/array.hpp>
#include <ycpp/doc.hpp>
#include <ycpp/map.hpp>
#include <ycpp/text.hpp>

ycpp::Doc doc(1);
ycpp::MapRef project = doc.map("project");
(void)project.set("title", ycpp::Any{"Demo"});  // item 1:0, a plain value
ycpp::ArrayRef tasks = project.array("tasks");  // item 1:1 holds the array
ycpp::MapRef first = tasks.insert_map(0);       // item 1:2 holds this map
(void)first.set("done", ycpp::Any{false});      // item 1:3
ycpp::TextRef notes = first.text("notes");      // item 1:4 holds this text
ycpp::MapRef second = tasks.insert_map(1);      // item 1:5
(void)notes.insert(0, "draft");

The tree built by the example: root map project, with a plain value under title and an array under tasks; the array holds two maps; the first map holds a text

Every nested type is held by an item, and that item's id names it. A handle stores that id, not a path. So a handle stays on its type when other entries move around it. If another peer deletes the item that holds the type, the type is gone: its handle reads as empty.

scope_parent() and scope_name() return that name: the holding item's id for a nested type, or the root name for a root type. The undo manager takes a scope in that form. When you already have that pair (for example from an event), doc.map_handle(parent, name), doc.array_handle(...) and doc.text_handle(...) turn it back into a handle.

Subdocuments

A subdocument is a whole Doc stored as a value in a map or an array. It is how an application splits a big workspace into documents that load on demand: a folder of notes, one document per note.

The parent stores only the subdocument's guid and options. The subdocument's own content is not part of the parent's updates. You sync each subdocument as its own document, with its own on_update.

#include <memory>

#include <ycpp/doc.hpp>
#include <ycpp/map.hpp>

ycpp::Doc workspace(1);
workspace.observe_subdocs(
    [](void*, const ycpp::SubdocsEvent& event) {
      // event.added, event.removed, event.loaded: std::vector<std::shared_ptr<Doc>>
    },
    nullptr);

auto note = std::make_shared<ycpp::Doc>(1);
note->set_guid("note-42");  // ycpp does not invent a guid: always set one
note->load();

ycpp::MapRef notes = workspace.map("notes");
(void)notes.set_doc("42", note);

std::shared_ptr<ycpp::Doc> same = notes.child_doc("42");
(void)same->text("body").insert(0, "Hello");  // edits the note, not the workspace
  • set_doc(key, doc) and ArrayRef::insert_doc(index, doc) store a document. They refuse to store a document inside itself or inside its own subtree.
  • child_doc(key) returns the stored document, or null when the key holds something else.
  • A peer that receives the parent gets a Doc for each subdocument, with the same guid. It appears in get_subdocs() and in the added list of a subdocs event.
  • load() marks a subdocument as wanted, and its parent reports it in loaded. Your sync layer loads its content then. set_auto_load(true) asks peers to load it as soon as they see it.
  • destroy() detaches a subdocument from its parent. The parent keeps a fresh, empty document under the same guid in that place.
  • Deleting the entry (erase) removes and destroys the subdocument. A shared_ptr you still hold keeps working on its own.

Unlike Yjs, ycpp does not generate a random guid for a new document. The guid is empty until you call set_guid.

The Any value

ycpp::Any is a plain value: what you store in a map, an array or a text embed. It has the kinds of lib0's Any, which maps to JSON plus a few extras:

AnyKind Build it with Read it with
undefined Any{} kind()
null Any{nullptr} kind()
boolean Any{true} as_bool()
integer Any{42} (any integer type) as_integer()
real Any{0.5} as_real()
big_int Any{ycpp::BigInt{n}} as_big_int()
string Any{"text"}, Any{std::string_view} as_string()
binary Any{ycpp::Binary{bytes}} as_binary()
array Any{ycpp::AnyArray{...}} as_array().items
map Any{ycpp::AnyMap{...}} as_map().entries
#include <ycpp/any.hpp>
#include <ycpp/json.hpp>

ycpp::AnyMap user;
user.entries.emplace_back("name", ycpp::Any{"Ada"});
user.entries.emplace_back("age", ycpp::Any{36});
ycpp::AnyArray tags;
tags.items.push_back(ycpp::Any{"admin"});
user.entries.emplace_back("tags", ycpp::Any{tags});

const ycpp::Any value{user};
std::string json = ycpp::to_json(value);  // {"name":"Ada","age":36,"tags":["admin"]}

// The same value from JSON text.
auto parsed = ycpp::parse_json(R"({"name":"Ada","age":36,"tags":["admin"]})");

Things to know:

  • Check kind() before calling an accessor. The library is built without exceptions, so the wrong accessor ends the program.
  • An AnyMap keeps its entries in the order you add them. to_json of an Any writes them in JavaScript's order, like JSON.stringify: keys that look like array indexes first, in numeric order, then the others in the order you added them. A key whose value is undefined is left out. MapRef::to_json() is different: it sorts the keys of the shared map.
  • JavaScript has one number type. A number written by a JavaScript peer can arrive as integer or as real depending on its value, so accept both when you read numbers.
  • to_json writes undefined as null, since JSON has no undefined.
  • ycpp::any_writable(value, limit) tells you, before writing, why a value would be refused: too deep, or a string that is not valid UTF-8.
  • Containers in an Any use std::pmr vectors and strings, so they can live in your memory resource.