Skip to main content

A shared outline: nested data, saved and synced

A tree of handlers has two rules that a flat document does not have: every peer must know the kinds the tree is made of, and its root needs an id that every peer agrees on. This recipe keeps both, with storage and sync around the tree. The same tree in a Flutter screen is the todo list recipe.

A shared outline: nested data, saved and syncedSource ↗

A Dart program that keeps a tree (chapters, each with a title and a text) in a SQLite file and syncs it through a relay. Another device rebuilds the same tree, and a restart reads it back.

Dart VMFlutter native✓ tested in CI
import 'package:crdt_lf/crdt_lf.dart';

/// Declares the kinds the outline is made of.
///
/// A peer rebuilds a chapter another peer wrote only when it knows its kinds.
void registerKinds(CRDTDocument document) {
document
..register(CRDTListRefHandler.spec)
..register(CRDTMapRefHandler.spec)
..register(CRDTFugueTextHandler.spec);
}

/// The chapters of [document]: the root of the tree, under a fixed id.
CRDTListRefHandler chaptersOf(CRDTDocument document) {
return document.handler(CRDTListRefHandler.spec, 'chapters');
}

/// Adds a chapter named [title] at the end of [chapters].
CRDTMapRefHandler addChapter(CRDTListRefHandler chapters, String title) {
// One transaction: the other peers get the chapter with both its texts.
return chapters.doc.runInTransaction(() {
final chapter = chapters.insertChild(
chapters.childRefs().length,
CRDTMapRefHandler.spec,
);
chapter.child('title', CRDTFugueTextHandler.spec).insert(0, title);
chapter.child('body', CRDTFugueTextHandler.spec);
return chapter;
});
}

/// The texts of one chapter, each merged character by character.
extension ChapterTexts on CRDTMapRefHandler {
/// The title of the chapter.
CRDTFugueTextHandler get title => child('title', CRDTFugueTextHandler.spec);

/// The text of the chapter.
CRDTFugueTextHandler get body => child('body', CRDTFugueTextHandler.spec);
}

Key points

  • Declare the kinds of the tree (register) in onDocument. Without them, a chapter that comes from the storage or from another peer reads as null.
  • Open the root under a fixed id, with document.handler. Two peers that both start empty and call child(key, …) each create their own child: one wins, and what the other wrote under its child leaves the tree.
  • insertChild always adds a new child, so two peers can add chapters at the same time.
  • Create a chapter and its texts in one transaction: the other peers get the chapter whole.
  • resolved reads the whole tree, every reference followed.
  • Each device needs its own file: it keeps the peer id of the device.