Lists and trees

How arrays and trees identify and order their items so that concurrent inserts and moves merge.

Arrays and trees are the two primitives that hold a varying number of things. Both give every item a stable id and a position key, which is what lets several people insert, move and delete at the same time without overwriting one another. This page explains that model and the operations on each.

Ids and positions

An array item and a tree node each have:

  • an id: a unique string that never changes. Commands address an item by its id, not by its index, so an edit to "the third item" still reaches the right item after someone inserts before it.
  • a position (pos): a string key that defines the order. Items are sorted by position, and items with equal positions by id, so every client and the server compute the same order.

Positions are fractional keys: between any two keys there is always another one. Inserting an item between two neighbors generates a key between theirs and changes no other item. Moving an item only changes that item's key. Two people who insert into the same gap at the same time both succeed; their items end up next to each other.

You rarely handle positions yourself. The operations below take an index, and the library generates the key. The …AtPos variants exist for the cases where you kept a position, for example to restore a deleted item where it was.

Arrays

const Checklist = Primitive.Struct({
  items: Primitive.Array(
    Primitive.Struct({
      text: Primitive.String().required(),
      done: Primitive.Boolean().default(false),
    }),
  ).default([]),
}).required();

In a snapshot, an array is a list of entries in order, each { id, pos, value }.

Inside a transaction, the array's proxy offers:

OperationEffect
push(value)Appends an item and returns its handle
insertAt(index, value)Inserts an item at an index
insertAtPos(pos, value)Inserts an item at a position key
remove(id)Removes an item
move(id, toIndex), moveToPos(id, pos)Moves an item
at(index), first(), last()Returns an item's handle, or undefined
findById(id)Returns an item's handle by id
find, findIndex, map, filter, some, every, forEachRead helpers over the items in order
lengthThe number of items
set(values)Replaces the whole array with new items

An item handle has the item's id and pos, a value proxy for editing the item, and get(), remove(), move(toIndex) and moveToPos(pos).

document.transaction((root) => {
  const item = root.items.push({ text: "Write docs" });
  item.value.done.set(true);
  root.items.move(item.id, 0);
});

Trees

A tree holds nodes of several types in a hierarchy. Each node type declares its data (a struct) and which node types it accepts as children.

const Card = Primitive.TreeNode("card", {
  data: Primitive.Struct({ title: Primitive.String().required() }),
  children: [],
});

const Column = Primitive.TreeNode("column", {
  data: Primitive.Struct({ name: Primitive.String().required() }),
  children: [Card],
});

const Board = Primitive.TreeNode("board", {
  data: Primitive.Struct({ name: Primitive.String().default("My board") }),
  children: [Column],
});

export const BoardDocument = Primitive.Tree({ root: Board });

A node type that may contain itself lists Primitive.TreeNodeSelf among its children. A node's data cannot have fields named type, id or children: those name the node's type, id and nested nodes.

Creating and reading

A tree's input is a list of root nodes, each with its type, its data fields and optional children:

BoardDocument.encode([
  {
    type: "board",
    name: "Roadmap",
    children: [{ type: "column", name: "Todo", children: [] }],
  },
]);

A tree's snapshot is a list of root node snapshots. Each node snapshot is { id, type, parentId, pos, data, children }, with children in order and parentId set to null for a root node. Primitive.TreeNodeSnapshot<typeof Column> is the type of one node's snapshot.

Editing

A tree's proxy has children (the root level) and findByIdAcrossTree(id). A children collection offers insertAt, insertLast, insertAtPos, at, first, last, findById, length and the same read helpers as an array. Inserting a node with nested children inserts the whole subtree as one atomic batch.

A node's proxy has id, type, pos, parentId, data (the proxy of its struct), children, and:

OperationEffect
update(fields)Writes some of the node's data fields
remove()Removes the node and every node below it
moveTo(children, index)Moves the node into another children collection of the tree
moveToPos(parentId, pos)Moves the node under a parent id (null for the root level)
exists()Whether the node still exists
as(NodeType)The same node typed as a specific node type
document.transaction((root) => {
  const board = root.children.first();
  const column = board?.children.insertLast({ type: "column", name: "Doing" });

  const card = root.findByIdAcrossTree(cardId)?.as(Card);
  if (card && column) {
    card.data.title.set("Ship it");
    card.moveTo(column.children, 0);
  }
});

findByIdAcrossTree returns a node whose type is only known at runtime; call as with the node type you expect to get its typed data and children.

Node ids are generated unless the input gives one. A given id must be unique in the tree.

What the tree enforces

  • A node is only accepted under a parent whose type allows it.
  • A move that would put a node inside its own subtree is refused.
  • When edits race, the tree stays a tree: a command whose parent another client removed, or a move that would now create a cycle, is skipped rather than applied. See Transactions.