Collaboration
You will learn how several controllers share one live document: each has its own selection and undo history, every change is attributed, and editors show the other participants' carets.
dart
import 'package:vyuh_document/elements.dart';
import 'package:vyuh_document/vyuh_document.dart';
/// A person and an agent editing one live document.
Future<void> main() async {
final configuration = DocumentConfiguration.richText;
final mine = DocumentController(
configuration,
document: Document.of(configuration, [Paragraph('Draft')]).valueOrNull,
author: const Author.person('asha'),
);
final agent = mine.join(author: const Author.agent('reviewer'));
// Every applied change from every participant, attributed.
final subscription = mine.changes.listen((change) {
print('${change.author} ran ${change.command.name} -> r${change.revision}');
});
final paragraph = agent.document.body.first<Paragraph>();
agent.run(InsertText(Position(paragraph, offset: 5), ' (reviewed)'));
// `mine` sees the agent's text at once, but undoes only its own changes.
print(mine.document.plainText); // Draft (reviewed)
print(mine.state.canUndo); // false
await subscription.cancel();
agent.close();
mine.close();
}Participants
| API | Meaning |
|---|---|
Author.person(name), Author.agent(name) | Who a change is attributed to (author.id is person:asha or agent:reviewer) |
DocumentController(config, author:) | The first participant |
controller.join(author:) | Another participant on the same live document |
controller.participantId | Unique per controller, even when two share an author |
controller.changes | Stream<Change> of every applied change from every participant |
controller.othersChanges | The same, without this participant's own |
controller.otherParticipants | Who else is joined, with their mode and status |
controller.close() | Leaves the document; further commands fail with Unsupported |
A Change carries author, participantId, revision, the command and the document after it.
Undo is per participant
Each controller undoes only its own changes, mapped over everyone else's. If both edited the same text, undo fails with Conflict instead of reverting the other person's work.
What each participant owns
The document is shared; everything below belongs to one controller. Each is set in DocumentController(...) or join(author:, ...), changed with its setter, streamed by its ...Changes, and part of controller.state. The types come from package:vyuh_document/participants.dart.
| Capability | Set with | Read | Refusal |
|---|---|---|---|
| Selection and undo | select, run(Undo()) | state.selection, state.canUndo | NotAllowed (nothing to undo), Conflict |
| Mode | mode:, setMode | mode, modeChanges | NotAllowed, found: the mode |
| Grants | grants:, setGrants | grants, grantsChanges | NotAllowed, found: the grant |
| Write scope | writeScope:, setWriteScope | writeScope, canEdit(ref) | NotAllowed, found: outsideWriteScope |
| Turns | turn((t) {...}), beginTurn() | state.inTurn | the failed step's error; Conflict on merge |
| Activity status | publishStatus | others: otherParticipants, otherParticipantsChanges | none: presence only |
| View preferences | viewPreferences:, setViewPreferences | viewPreferences, viewPreferencesChanges | none: this participant's editor only |
| Typing format | the editor's pending bold or italic | the mounted editor | none: never shared |
| Feed of others | othersChanges | state.receivedRevision | none |
The checks run in a fixed order: mode, then grants, then write scope and protection. Each narrows what the one before admitted; none widens it. A refused command changes nothing.
Grants
What a participant may do beyond editing content and its own comments and suggestions (DocumentGrant):
| Grant | Admits |
|---|---|
decideSuggestions | accepting or rejecting another participant's suggestion |
resolveComments | resolving or reopening another's comment |
deleteComments | deleting another's comment |
editComments | editing the text of another's comment |
changeProtection | protection commands and protected areas |
changeSettings | styles, fonts, layout defaults, metadata, section layout |
People get ParticipantGrants.all; ParticipantGrants.contributor grants nothing beyond content, and ParticipantGrants.reviewer adds deciding suggestions and resolving comments. Editing or deleting another's comment stays with its author unless a host adds editComments or deleteComments.
dart
final agent = person.join(
author: const Author.agent('Drafter'),
grants: ParticipantGrants.contributor,
);
agent.run(const AcceptAllSuggestions()); // with the person's suggestions:
// Failed(NotAllowed): {"found": "decideSuggestions", ...}
agent.run(DeleteComment(personsComment));
// Failed(NotAllowed): {"found": "deleteComments", ...}A change is judged by what it does to the document, so the same grants apply to a command, to an edit made in that participant's editor (a typed DocumentEditor judges by its controller's authority; a DocumentEditorController takes an authority: whose actor holds the grants) and to its undo. Without decideSuggestions it can't decide or drop another participant's suggestion; its own are its own to accept or reject, whichever API it uses. No comment command checks the author itself: only these grants do.
Write scope
The only parts of the document a participant may change: whole blocks, the section under a heading (up to the next heading of the same or a higher level), and protected areas.
dart
final summary = person.document.body.heading(text: 'Summary')!;
agent.setWriteScope(WriteScope.section(summary));
agent.run(InsertText(Position(intro, offset: 0), 'x'));
// Failed(NotAllowed): {"found": "outsideWriteScope",
// "where": "write scope (the \"Summary\" section)", ...}The scope is checked by the protection gate, on the document a change produces: a change that crosses its edge (moving content in or out, removing the heading that ends it) is refused whole. Blocks the participant creates inside it (splitting a paragraph, say) are its own. Comments are not content: a scoped participant comments anywhere protection admits. Its editor refuses typing outside the scope up front, and canEdit(ref) answers per block.
Turns
Several commands as one change: one revision, one Turn on the change feed (with its steps and label), one undo step, all or nothing.
dart
agent.turn((turn) {
final note = turn.run(InsertBlock(Paragraph(''), after: summary));
turn.run(SetText(note.valueOrNull!, 'On track for Friday.'));
}, label: 'Write the summary');
agent.run(const Undo()); // reverts both stepsEach step applies to the turn's own document, so a later step can address what an earlier one made. A failed step fails the turn: nothing is applied. beginTurn() keeps a turn open across asynchronous work; commit() merges it with what others changed meanwhile, or fails with Conflict when both changed the same text. While a turn is open the participant's run is refused.
Activity status
Presence beside the caret: idle, typing, thinking, working or custom, each with an optional label. It is never content or history.
dart
agent.publishStatus(const ParticipantStatus.thinking('Reading the intro'));
person.otherParticipants.single.status; // thinking: Reading the introotherParticipants lists who else is joined, with their mode and status. A mounted editor publishes typing while its participant types and restores the earlier status after a short pause.
Editors show it on the collaborator's flag: Reviewer · Reading the intro, or Reviewer · thinking without a label. A participant that is thinking or working keeps its flag even while its caret stays still, so an agent busy in the background never shrinks to a dot. A custom caret builder reads it from ParticipantCaretDetails.status.
View preferences
How this participant's editor shows review markup. Nobody else's view changes.
dart
person.setViewPreferences(const ViewPreferences(showMarkup: false));
person.setViewPreferences(
ViewPreferences(markupAuthors: {const Author.agent('Reviewer')}),
);Hidden markup leaves the suggestions in the document.
Typing format
Bold or italic switched on at a caret, before typing, belongs to that participant's editor. Another participant's typing doesn't pick it up, and their changes don't clear it.
The others' changes
controller.othersChanges delivers only the changes other participants make (by participant, so two controllers sharing an author are still others). state.receivedRevision is the revision of the latest one this participant received.
dart
agent.othersChanges.listen((change) {
if (change.author.isAgent) return;
queueReview(change.document); // react to the person
});In the editor
Two DocumentEditors on joined controllers show each other's edits live and draw each other's caret and selection. Typing is attributed to the editor's controller, and each editor publishes its whole selection: the caret at its extent, with its affinity, and the selected range.
Your caret and the text you are editing own the foreground; collaborators are ambient and yield to it. Where a collaborator is drawn depends on your own caret's visual line:
| Where they are | Active (moved in the last ~2 s) | Idle |
|---|---|---|
| On your line | A small dot below the baseline | A dot |
| On the line directly below yours | The bar alone | A dot |
| Anywhere else | Bar, stem and name flag | A dot |
- The bar is exactly your own caret's height on its baseline, on the visual line the selection's affinity names (the end of a soft-wrapped line or the start of the next). It never extends below that; it stays with the text, clipped to the viewport like your own caret.
- The stem projects up from the bar to a compact flag whose bottom sits at the top of the caret's line. Stems and flags are drawn in the editor's chrome overlay, above the document and below menus, following the bar through scroll and zoom, so a flag on the first line rises above the page instead of being cut off.
- A flag that would cross the visible editor's right edge grows to the left of its stem.
- A collaborator within one character of your caret has its dot moved just past your caret, so nothing covers your caret or the character you are at.
- Crowds: collaborators within three characters of each other on one line are one marker, drawn at the most recently active one: one bar with a flag reading
Name +N, or one dot with a+Nbadge. Flags of separate crowds that would collide on one line sit side by side, each joined to its stem. - Hover a dot or bar to see the full form; hovering a crowd lists every name. On your line a hovered dot only lists the names.
- A selection is tinted lightly in the person's colour, box for box as your own selection is painted, except on your line.
- With reduced motion the forms swap without animating. Nothing is dimmed.
controller.participantId is a ParticipantId (an extension type over String), the same value every Change and caret from that controller carries.
To draw collaborators your own way, such as an avatar, an icon or an effect, set DocumentEditorTheme.participantCaretBuilder. The editor draws the bar and the range tint, decides each caret's form by the rules above, and calls the builder once per drawn caret (once per crowd) with ParticipantCaretDetails: the author, participantId and members it stands for, its color and caretSize, the decision (zone, presentation, idle, hovered, label), and the placement (dotRect, flagRect, flagDirection, flagSize, stemHeight, flagOffset), all relative to the caret box's top-left. The widget is laid out at the caret box, paints outside it and ignores pointers. DocumentParticipantCaret is the default.
dart
DocumentEditorTheme.light().copyWith(
participantCaretBuilder:
(BuildContext context, ParticipantCaretDetails details) =>
switch (details.presentation) {
ParticipantCaretPresentation.full => Stack(
clipBehavior: Clip.none,
children: [
// The stem, from the bar up to the flag.
Positioned(
left: 0,
width: details.caretSize.width,
top: -details.stemHeight,
height: details.stemHeight,
child: ColoredBox(color: details.color),
),
Positioned.fromRect(
rect: details.flagRect,
child: CircleAvatar(
backgroundColor: details.color,
child: Text(details.author.name[0]),
),
),
],
),
ParticipantCaretPresentation.dot => Stack(
clipBehavior: Clip.none,
children: [
Positioned.fromRect(
rect: details.dotRect,
child: DecoratedBox(
decoration: BoxDecoration(
color: details.color,
shape: BoxShape.circle,
),
),
),
],
),
// The editor draws the bar.
ParticipantCaretPresentation.bar => const SizedBox.shrink(),
},
);dart
final mine = DocumentController(notesConfiguration);
final theirs = mine.join(author: const Author.person('sam'));
Row(children: [
Expanded(
child: DocumentEditor(
controller: mine,
extensions: DocumentEditorElements.defaults,
),
),
Expanded(
child: DocumentEditor(
controller: theirs,
extensions: DocumentEditorElements.defaults,
),
),
]);Observing the editor runtime
The editor runtime's own feed, DocumentEditorController.changes, reports each change with its origin, text edits and comment changes. See Observing changes.
Across processes
To carry changes between processes, build on the engine's collaboration envelopes and DocumentCollaborationTransport (engine.dart).
Next
Agents: give an AI agent its own controller.