Skip to main content

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.

Flutter nativeFlutter web✓ tested in CI
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();
}

Key points

  • The awareness plugin runs on both sides: ServerAwarenessPlugin on the server, ClientAwarenessPlugin on each client. Presence never enters the document history.
  • CRDTReplica.open restores the note, then connects: give the plugin to the client it builds in sync. 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 onSelectionAnchorsChanged reports as JSON. They are null when 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.
  • CrdtTextCursorsOverlay needs a Fugue text handler and an Overlay above it (MaterialApp gives one).
  • When a peer disconnects, the server removes its state and sends the new states to the others.