@page "/live"
@page "/live/{Room}"
@inject NavigationManager Navigation
@inject LiveRelay Relay
Live, across tabs · Bcrdt
Live, across tabs
Every other page in this demo keeps its replicas side by side in one tab, talking over the library's
in-memory transport. This one is the real thing: one replica per browser tab, meeting through the demo
server. Open the link below in another tab, another browser or on your phone and type in both.
One replica per tab
This tab is one replica. Share the link, and every tab that opens it is another; a tab opened from the
read-only link follows every change but cannot make one.
@if (Room is null || !RendererInfo.IsInteractive)
{
Connecting…
}
else
{
Opening the document…
This tab could not open the document: @error.Message
Here now:
@* Follows the cascaded document by itself; the page only remembers a deliberate disconnect, for the badge. *@
Connection:
}
The thing worth trying. Take one tab offline, type a paragraph into it, type something
else into another tab, then bring the first one back. Both paragraphs survive, in the same order in every
tab - the handshake sends each side what the other is missing, in both directions. Reload the offline tab
before bringing it back, or close every tab and open the link again: a browser that saved a copy picks up
where it left off. The demo server keeps one more copy, but only in memory - a restart or newer rooms evict
it - so it is a stopgap, not an archive. Then open the read-only link: it follows every edit, and makes none.
The page an application would write
The document comes from the app's own AddBitBcrdtServices registration and is opened by
BcrdtCollaborationScope, which shows LoadingContent while the page is prerendered and
the document opens, ErrorContent if it cannot be opened, and closes it when the page goes away. The
editor is BcrdtTextArea, the list of people is BcrdtPresenceView and the connection, with
its offline switch, is BcrdtSyncStatus. Each tab keeps its copy in the browser's IndexedDB
(UseIndexedDbStore), so a reload - online or not - starts from where it left off; the tabs of one browser also sync directly (UseCrossTabSync), offline too.
On the server, BcrdtHub from Bit.Bcrdt.Server relays each message to the other tabs,
and a BcrdtDocumentHost behind it is one more peer in every room: it loads a document from its store
when the first tab arrives, answers each joining tab with the whole document, writes every change to the store,
and unloads the document UnloadDelay after the last tab leaves. A newcomer to an empty room still
gets everything that was ever typed into it, and server code can read and change a hosted document too
(ReadAsync, EditAsync).
Two relays
The demo server maps both relays Bit.Bcrdt.Server ships: BcrdtHub for the SignalR
transport of Bit.Bcrdt.SignalR, and the WebSocket endpoint for the WebSocket transport built
into Bit.Bcrdt. Tabs only meet on the same relay, so the relay is part of the link you share.
// Demo/Server/Program.cs
builder.Services.AddBitBcrdtHub(); // AddSignalR, with a receive limit sized for sync messages
builder.Services.AddBitBcrdtDocumentHost(_ => new BcrdtDocumentHostOptions
{
Store = new BcrdtInMemoryDocumentStore(maxDocuments: 500), // an app gives it a durable store
UnloadDelay = TimeSpan.FromMinutes(1),
});
// ...
app.UseWebSockets();
app.MapHub<LiveHub>("/hub/bcrdt"); // a BcrdtHub; picks the host up from the container
app.MapBitBcrdtWebSocket("/ws/bcrdt/{documentId}", options: new()
{
DocumentHost = app.Services.GetRequiredService<BcrdtDocumentHost>(),
AuthorizeAccess = (context, documentId) => ValueTask.FromResult(LiveHub.AccessOf(context)),
});
Who may edit
A CRDT makes replicas converge; it says nothing about who may change what. So the server decides, per connection
and document, by overriding BcrdtHub.AuthorizeAccessAsync (or setting the WebSocket endpoint's
AuthorizeAccess): None refuses the join, ReadOnly lets the tab follow the
document and publish presence while the relay drops every change it sends, ReadWrite lets it edit.
The demo's LiveHub grants read-only to a link that asks for it; an application decides from the
signed-in user. The client is told its grant on joining (document.IsReadOnly), and
BcrdtTextArea stops taking input by itself. Rules about what a writer may change go in
BcrdtDocumentHostOptions.ValidateUpdate, which sees every change before anyone else receives it.
@code {
private const string Field = "body";
// Who this tab is. A random name is enough for a demo; an application publishes its signed-in user.
private readonly BcrdtCollaboratorInfo _me = CreateGuest();
private bool _online = true;
/// The room the tabs share. A visit without one is sent to a fresh room.
[Parameter]
public string? Room { get; set; }
/// websocket to meet through the WebSocket endpoint instead of the SignalR hub.
[SupplyParameterFromQuery(Name = "relay")]
public string? RelayName { get; set; }
/// read to ask the relay for read-only access.
[SupplyParameterFromQuery(Name = "access")]
public string? AccessName { get; set; }
private bool ReadOnly => string.Equals(AccessName, "read", StringComparison.OrdinalIgnoreCase);
private LiveRelayKind Kind => string.Equals(RelayName, "websocket", StringComparison.OrdinalIgnoreCase)
? LiveRelayKind.WebSocket
: LiveRelayKind.SignalR;
// The relay is part of the document identifier: a tab on the hub and a tab on the WebSocket endpoint can never
// reach each other, so they must not pretend to be editing the same document.
private string DocumentId => $"live-{Room}-{(Kind == LiveRelayKind.WebSocket ? "ws" : "hub")}";
private string ShareLink => RelayLink(Kind, Room ?? NewRoom(), readOnly: false);
private string ReadOnlyLink => RelayLink(Kind, Room ?? NewRoom(), readOnly: true);
protected override void OnParametersSet()
{
if (!RendererInfo.IsInteractive) return;
if (Room is null || !IsValidRoom(Room))
{
Navigation.NavigateTo(RelayLink(Kind, NewRoom(), ReadOnly), replace: true);
return;
}
// Read when the scope opens the document, which happens after this. Access is a property of the
// connection rather than of the document, so a read-only tab opens the very same document.
Relay.Kind = Kind;
Relay.ReadOnly = ReadOnly;
_online = true;
}
private void Opened(BcrdtCollaborativeDocument document) => _online = true;
private void Toggled(BcrdtCollaborativeDocument document, bool connected)
{
_online = connected;
// Disconnecting withdraws this tab's presence so the others see it leave at once; coming back publishes it
// again.
if (connected) document.Presence.SetUser(_me);
}
// The relay tabs keep the access this tab asked for; the share links name it explicitly.
private string RelayLink(LiveRelayKind kind) => RelayLink(kind, Room ?? NewRoom(), ReadOnly);
private string RelayLink(LiveRelayKind kind, string room, bool readOnly)
{
List query = [];
if (kind == LiveRelayKind.WebSocket) query.Add("relay=websocket");
if (readOnly) query.Add("access=read");
string path = $"live/{room}" + (query.Count > 0 ? "?" + string.Join('&', query) : string.Empty);
return Navigation.ToAbsoluteUri(path).ToString();
}
private string RelayClass(LiveRelayKind kind) => kind == Kind ? "live-relay live-relay-active active" : "live-relay";
private static bool IsValidRoom(string room) =>
room.Length is > 0 and <= 32 && room.All(c => c is (>= 'a' and <= 'z') or (>= '0' and <= '9') or '-');
private static string NewRoom() => Guid.NewGuid().ToString("N")[..10];
private static BcrdtCollaboratorInfo CreateGuest()
{
string id = Guid.NewGuid().ToString("N");
return new BcrdtCollaboratorInfo(id, $"Guest {Random.Shared.Next(100, 1000)}", BcrdtPresenceService.SuggestColor(id));
}
}