Remote cursors and presence
The awareness plugin shares a small state per peer (a name, a color, a caret) that is never stored. The text field draws the carets of the other peers on top of the text.
Remote cursors and presenceSource ↗
A relay server that shares who is in each room, and a Flutter note, kept on the device by Hive, that shows the carets of the other peers, with their name and color, as they type.
- server.dart
- presence.dart
- note_page.dart
- main.dart
- Install
import 'dart:io';
import 'package:crdt_socket_sync/web_socket_relay_server.dart';
/// Starts a relay on [port] that also shares the presence of each room.
Future<WebSocketRelayServer> startPresenceRelay({int port = 8080}) async {
final server = WebSocketRelayServer(
serverFactory: () => HttpServer.bind(InternetAddress.anyIPv4, port),
// One instance per server: it keeps who is in which room.
plugins: [ServerAwarenessPlugin()],
);
await server.start();
return server;
}
Future<void> main() async {
final server = await startPresenceRelay();
stdout.writeln('Relay on ws://localhost:${server.port}');
await ProcessSignal.sigint.watch().first;
await server.dispose();
}
import 'package:crdt_lf/crdt_lf.dart';
import 'package:crdt_lf_flutter/crdt_lf_flutter.dart';
import 'package:crdt_lf_hive/crdt_lf_hive.dart';
import 'package:crdt_socket_sync/replica.dart';
import 'package:crdt_socket_sync/web_socket_relay_client.dart';
import 'package:flutter/painting.dart';
/// A note on this device, joined on the relay, with the presence of its peers.
typedef SharedNote =
({
CRDTReplica replica,
ClientAwarenessPlugin presence,
CRDTFugueTextHandler text,
});
/// Opens the note on this device and joins it on the relay at [url], as
/// [name] drawn in [color].
Future<SharedNote> openNote(
String url, {
required String name,
required Color color,
}) async {
// Sent on every connection: who this peer is, before any caret.
final presence = ClientAwarenessPlugin(
initialMetadata: {'name': name, 'color': color.toARGB32()},
);
final replica = await CRDTReplica.open(
documentId: 'note',
storage: CRDTHive.open,
sync:
(document) => WebSocketRelayClient(
url: url,
document: document,
author: document.peerId,
plugins: [presence],
),
);
// The cursors need a Fugue text: its anchors stay valid after any edit.
final text = CRDTFugueTextHandler(replica.document, 'note');
return (replica: replica, presence: presence, text: text);
}
/// Publishes the caret of this peer; `null` [base] takes it away.
void publishCaret(
ClientAwarenessPlugin presence,
FugueElementID? base,
FugueElementID? extent,
) {
presence.updateLocalState({
'cursor':
base == null
? null
: {
'base': base.toJson(),
if (extent != null) 'extent': extent.toJson(),
},
});
}
/// The carets of the other peers in [awareness], ready to draw.
List<CrdtTextCursor> remoteCursors(
ClientAwarenessPlugin presence,
DocumentAwareness awareness,
) {
return [
for (final state in awareness.states.values)
// The states include this peer: leave it out.
if (state.clientId != presence.client.sessionId)
if (state.metadata['cursor']
case {'base': final Map<String, dynamic> base} && final cursor)
CrdtTextCursor(
id: state.clientId,
label: state.metadata['name'] as String?,
color: Color(state.metadata['color'] as int? ?? 0xFF2196F3),
base: FugueElementID.fromJson(base),
extent: switch (cursor['extent']) {
final Map<String, dynamic> extent => FugueElementID.fromJson(
extent,
),
_ => null,
},
),
];
}
import 'dart:async';
import 'package:crdt_lf_flutter/crdt_lf_flutter.dart';
import 'package:crdt_socket_sync/web_socket_relay_client.dart';
import 'package:flutter/material.dart';
import 'presence.dart';
/// A page that edits the note shared through the relay at [url], and shows
/// the carets of the other peers.
class NotePage extends StatefulWidget {
/// Creates the page of the note, for the peer [name] drawn in [color].
const NotePage({
required this.url,
required this.name,
required this.color,
super.key,
});
/// The address of the relay server.
final String url;
/// The name the other peers see next to the caret of this peer.
final String name;
/// The color of the caret of this peer.
final Color color;
State<NotePage> createState() => _NotePageState();
}
class _NotePageState extends State<NotePage> {
late final Future<SharedNote> _note = openNote(
widget.url,
name: widget.name,
color: widget.color,
);
void dispose() {
// Stops the sync, writes what is still waiting, closes the storage.
unawaited(_note.then((note) => note.replica.close()));
super.dispose();
}
Widget build(BuildContext context) {
return FutureBuilder<SharedNote>(
future: _note,
builder:
(context, snapshot) => switch (snapshot.data) {
final note? => _buildNote(note),
null => const Scaffold(
body: Center(child: CircularProgressIndicator()),
),
},
);
}
Widget _buildNote(SharedNote note) {
final presence = note.presence;
return Scaffold(
appBar: AppBar(title: const Text('Note')),
body: CrdtProvider.value(
value: note.replica.document,
child: CrdtTextFieldBuilder(
id: 'note',
// Reported while the field has focus, `null`s when it loses it.
onSelectionAnchorsChanged:
(base, extent) => publishCaret(presence, base, extent),
// The builder does not run again when a remote caret moves: the
// StreamBuilder redraws the cursors.
builder:
(context, controller) => StreamBuilder<DocumentAwareness>(
stream: presence.awarenessStream,
initialData: presence.awareness,
builder:
(context, snapshot) => CrdtTextCursorsOverlay(
id: 'note',
cursors: remoteCursors(presence, snapshot.requireData),
child: TextField(
controller: controller,
maxLines: null,
decoration: const InputDecoration(
hintText: 'Write here',
contentPadding: EdgeInsets.all(16),
),
),
),
),
),
),
);
}
}
import 'package:crdt_lf_hive/crdt_lf_hive.dart';
import 'package:flutter/foundation.dart' show kIsWeb;
import 'package:flutter/material.dart';
import 'package:hive/hive.dart';
import 'package:path_provider/path_provider.dart';
import 'note_page.dart';
Future<void> main() async {
WidgetsFlutterBinding.ensureInitialized();
// On the web Hive uses IndexedDB and needs no path.
if (!kIsWeb) {
Hive.init((await getApplicationDocumentsDirectory()).path);
}
CRDTHive.initialize();
runApp(
MaterialApp(
title: 'Note',
// MaterialApp gives the Overlay the cursors are painted into.
home: NotePage(
// The relay of server.dart. Each peer needs its own storage: run the
// app on two devices, or in two browsers.
url: 'ws://localhost:8080',
name: 'Guest ${DateTime.now().second}',
color:
Colors.primaries[DateTime.now().second % Colors.primaries.length],
),
),
);
}
flutter pub add crdt_lf crdt_lf_flutter crdt_lf_hive crdt_socket_sync hive \
path_provider
Key points
- The awareness plugin runs on both sides:
ServerAwarenessPluginon the server,ClientAwarenessPluginon each client. Presence never enters the document history. CRDTReplica.openrestores the note, then connects: give the plugin to the client it builds insync. The page closes the replica.- Each peer needs its own storage: it keeps the peer id. Two apps on the same storage would write as the same peer.
- Publish the anchors that
onSelectionAnchorsChangedreports as JSON. They arenullwhen the field loses focus, and that takes the caret away. - The awareness states include this peer: leave out its own session id before you draw.
CrdtTextCursorsOverlayneeds a Fugue text handler and anOverlayabove it (MaterialAppgives one).- When a peer disconnects, the server removes its state and sends the new states to the others.