Skip to content

Bidirectional SignalR

H.P. Gansevoort edited this page Nov 27, 2026 · 14 revisions

Bidirectional SignalR Interactive Charts

A browser interaction does one of three things. A mutation event changes the server-side Figure, which is the authoritative copy. A brush-select event goes to a handler you wrote. A hover event queries the server for a response sent back to that caller only. Mutation events shipped in v1.2.0. Notification events shipped in v1.2.2, with the first per-caller response mechanism in the library. Everything is .NET, there is no JavaScript charting library, and the server stays the source of truth.

Why

Earlier versions handled browser gestures (wheel-zoom, drag-pan, legend click) in the browser: an IIFE manipulated the SVG, so the server never knew the zoom level. Every gesture now invokes a ChartHub method with a typed payload. The server mutates the authoritative Figure and pushes the updated SVG back through the existing publish fan-out. Several viewers stay in sync without extra work, because ChartHub.Subscribe already puts each connection in a SignalR group.

Architecture at a glance

┌─ browser ─────────────────────┐           ┌─ .NET server ─────────────────────────┐
│ SVG with embedded IIFE       │           │  ChartHub  ·  FigureRegistry            │
│ server-interaction script    │           │  ┌──────────────────────────────────┐  │
│   wheel → OnZoom ────────────┼─── JS SR ──┼─→│ Publish(chartId, evt)            │  │
│   drag  → OnPan              │           │  │ ↓ Channel<FigureInteractionEvent>│  │
│   Home  → OnReset            │           │  │ ↓                                │  │
│   click → OnLegendToggle     │           │  │ ChartSession.DrainAsync (1 task) │  │
│                              │           │  │ ↓ evt.ApplyTo(figure)            │  │
│ DOM swap ← UpdateChartSvg ◄──┼──── SR ────┼──│ ↓ PublishSvgAsync                │  │
│                              │           │  └──────────────────────────────────┘  │
└──────────────────────────────┘           └───────────────────────────────────────┘

Each chart has one channel and one reader task, so mutations are serial by construction. There is no SemaphoreSlim, no lock and no ConcurrentBag. A hub method takes no longer than the channel write, and rendering happens off the hub call stack. A burst of 50 wheel events in one reader tick coalesces into one re-render.

Event hierarchy

The events are records that apply themselves, in three tiers of stacked inheritance. To add an interaction that changes the figure, write a new subclass: the session applies every event it has no handler for through the event's own ApplyTo, so no switch, visitor or registry grows with it.

using MatPlotLibNet;
using MatPlotLibNet.Interaction;
using MatPlotLibNet.Models;

// The hierarchy, in the namespace MatPlotLibNet.Interaction:
//
//   FigureInteractionEvent(ChartId, AxesIndex)        tier 1, the root: an abstract ApplyTo(Figure)
//   ├── AxisRangeEvent(…, XMin, XMax, YMin, YMax)     tier 2: ONE sealed ApplyTo that overwrites the axis limits
//   │   ├── ZoomEvent                                 tier 3
//   │   └── ResetEvent                                tier 3
//   ├── PanEvent(…, DxData, DyData)                   a different shape: moves the limits by a delta in data units
//   └── LegendToggleEvent(…, SeriesIndex)             flips the visibility of one series

var figure = Plt.Create()
    .Plot([0.0, 1.0, 2.0, 3.0], [0.0, 1.0, 4.0, 9.0])
    .Build();

FigureInteractionEvent[] gestures =
[
    new ZoomEvent("live-1", AxesIndex: 0, XMin: 0.5, XMax: 2.5, YMin: 0, YMax: 6),
    new PanEvent("live-1", AxesIndex: 0, DxData: 0.25, DyData: 0),
    new LegendToggleEvent("live-1", AxesIndex: 0, SeriesIndex: 0),
    new ClearLimitsEvent("live-1", AxesIndex: 0),
];

// Each event applies itself: the loop never looks at its type.
foreach (var gesture in gestures)
{
    gesture.ApplyTo(figure);
}

// A new interaction that changes the figure is a new subclass; nothing that exists changes.
public sealed record ClearLimitsEvent(string ChartId, int AxesIndex) : FigureInteractionEvent(ChartId, AxesIndex)
{
    public override void ApplyTo(Figure figure)
    {
        var axes = TargetAxes(figure);
        axes.XAxis.Min = null;
        axes.XAxis.Max = null;
        axes.YAxis.Min = null;
        axes.YAxis.Max = null;
    }
}

Why self-applying records beat a static mutator or a visitor

  • SOLID-O: a new event type is a new subclass, and no existing code changes.
  • SOLID-L: AxisRangeEvent.ApplyTo is sealed override, so ZoomEvent and ResetEvent cannot diverge from axis-range semantics.
  • DRY: the axis-limit mutation lives in exactly one place.
  • No statics: every event carries instance state, so you can test it against a throwaway Figure without a DI container.

Server side

This code lives in MatPlotLibNet.AspNetCore.

FigureRegistry (public)

using MatPlotLibNet;
using MatPlotLibNet.AspNetCore;
using MatPlotLibNet.Interaction;
using Microsoft.AspNetCore.Builder;
using Microsoft.Extensions.DependencyInjection;

var builder = WebApplication.CreateBuilder(args);
builder.Services.AddMatPlotLibNetSignalR();
var app = builder.Build();

var registry = app.Services.GetRequiredService<FigureRegistry>();
var figure = Plt.Create().Plot([0.0, 1.0, 2.0], [0.0, 1.0, 4.0]).Build();

// Register: one session per chart id. Registering the id again replaces the session.
registry.Register("live-1", figure);

// Publish: the only path that mutates the figure. It queues the event and returns at once;
// false means no chart is registered under that id.
bool queued = registry.Publish("live-1", new ZoomEvent("live-1", 0, XMin: 0.5, XMax: 1.5, YMin: 0, YMax: 2));
Console.WriteLine(queued);

// UnregisterAsync: completes the session's channel, cancels its reader and waits for it to stop.
await registry.UnregisterAsync("live-1");

Its other members: a Register overload that takes handlers for the notification events (see Handler registration), and RegisterStreaming(chartId, streamingFigure), which publishes a Streaming figure each time it asks for a render.

  • It is a concrete class with no interface. An interface is not worth adding until a second implementation needs one.
  • Inside, it holds a ConcurrentDictionary<string, ChartSession>.
  • No TryGet(out Figure): external callers cannot reach the raw figure or race the reader task. Publish is the only path that mutates the figure.
  • services.AddMatPlotLibNetSignalR() registers it as a DI singleton.

ChartSession (internal)

There is one session per registered chart. It owns an unbounded Channel<FigureInteractionEvent> with SingleReader = true, and a background reader task that drains the channel:

using System.Threading.Channels;
using MatPlotLibNet;
using MatPlotLibNet.AspNetCore;
using MatPlotLibNet.Interaction;
using MatPlotLibNet.Models;

// The session's drain loop, run here on a channel of its own so the coalescing can be watched.
var chartId = "live-1";
var figure = Plt.Create().Plot([0.0, 1.0, 2.0], [0.0, 1.0, 4.0]).Build();
var publisher = new CountingPublisher();
var events = Channel.CreateUnbounded<FigureInteractionEvent>(new UnboundedChannelOptions { SingleReader = true });
var reader = events.Reader;
using var cts = new CancellationTokenSource();
var ct = cts.Token;

// A burst of 50 wheel events, all written before the reader wakes.
for (int i = 0; i < 50; i++)
    events.Writer.TryWrite(new ZoomEvent(chartId, 0, XMin: 0, XMax: 10 - i * 0.1, YMin: 0, YMax: 4));
events.Writer.Complete();

while (await reader.WaitToReadAsync(ct))
{
    var dirty = false;
    while (reader.TryRead(out var evt))
    {
        evt.ApplyTo(figure);
        dirty = true;
    }
    if (dirty)
        await publisher.PublishSvgAsync(chartId, figure, ct);
}

Console.WriteLine($"50 events, {publisher.Published} publish");   // 50 events, 1 publish

sealed class CountingPublisher : IChartPublisher
{
    public int Published { get; private set; }

    public Task PublishAsync(string chartId, Figure figure, CancellationToken ct = default) => Task.CompletedTask;

    public Task PublishSvgAsync(string chartId, Figure figure, CancellationToken ct = default)
    {
        Published++;
        return Task.CompletedTask;
    }
}

The outer WaitToReadAsync wakes once per batch. The inner TryRead drains that batch. PublishSvgAsync fires once per batch, and that is what coalesces the events. An event the session cannot apply costs the chart only that event: one that names a subplot the figure does not have is dropped, one that throws is counted, and the reader goes on with the next, so the hub keeps answering. DisposeAsync completes the writer, cancels the reader and awaits shutdown.

Hub methods

ChartHub, mapped by app.MapChartHub(), is what the browser script calls. Each gesture method is one line on the server, _registry.Publish(evt.ChartId, evt). A .NET client calls the same methods:

using MatPlotLibNet.Interaction;
using Microsoft.AspNetCore.SignalR.Client;

await using var connection = new HubConnectionBuilder()
    .WithUrl("http://localhost:5000/charts-hub")
    .Build();

connection.On<string, string>(HubMethodNames.UpdateChartSvg, (chartId, svg) => Console.WriteLine($"{chartId}: {svg.Length} characters"));

await connection.StartAsync();
await connection.InvokeAsync(HubMethodNames.Subscribe, "live-1");          // joins the chart's SignalR group

await connection.InvokeAsync(HubMethodNames.Zoom, new ZoomEvent("live-1", 0, XMin: 0, XMax: 5, YMin: -1, YMax: 1));
await connection.InvokeAsync(HubMethodNames.Pan, new PanEvent("live-1", 0, DxData: 0.5, DyData: 0));
await connection.InvokeAsync(HubMethodNames.Reset, new ResetEvent("live-1", 0, XMin: 0, XMax: 10, YMin: -1, YMax: 1));
await connection.InvokeAsync(HubMethodNames.LegendToggle, new LegendToggleEvent("live-1", 0, SeriesIndex: 0));

The names of the hub's methods are public constants of HubMethodNames: the events a page sends, the messages the server sends a viewer and the subscriptions, the names the library's own clients and scripts use. The four new methods return void instead of async Task. The channel write is synchronous, so the hub call never awaits rendering. Subscribe and Unsubscribe are unchanged from v1.1.x.

Only the parts that changed (v1.30.0)

SubscribeToParts joins a chart as a viewer that patches. The server sends it the whole document once, every drawn part in a <g data-mpl-part="…"> group (SvgPartMarker names its attribute, opening and closing; background, axes-0, axes-1, …, overlay), and after that UpdateChartParts with a ChartSvgParts: RootTag (the root's new opening tag, when a zoom moved the view it carries), Background, Overlay and Axes, each ChartSvgAxesPart with its Index and its Markup, the whole element to put in place of the part of the same name. A new title, other scripts or another number of subplots send the whole document again. A viewer subscribed with Subscribe keeps getting the whole SVG; both are sent nothing when nothing changed. The Blazor ChartSubscriptionClient, the React, Vue and Angular packages and the Interactive popup subscribe for parts and still hand your component the whole SVG; against a server without SubscribeToParts they subscribe the old way.

using MatPlotLibNet.AspNetCore;
using MatPlotLibNet.Interaction;
using Microsoft.AspNetCore.SignalR.Client;

await using var connection = new HubConnectionBuilder()
    .WithUrl("http://localhost:5000/charts-hub")
    .Build();

connection.On<string, string>(HubMethodNames.UpdateChartSvg, (chartId, svg) => Console.WriteLine($"{chartId}: the whole document, {svg.Length} characters"));
connection.On<string, ChartSvgParts>(HubMethodNames.UpdateChartParts, (chartId, parts) => Console.WriteLine($"{chartId}: {parts.Axes.Count} subplot(s) changed"));

await connection.StartAsync();
await connection.InvokeAsync(HubMethodNames.SubscribeToParts, "live-1");

Notification events (v1.2.2)

The events in v1.2.0 and v1.2.1 mutate the figure, which triggers a re-render and a broadcast. v1.2.2 adds two events that do not. BrushSelectEvent observes a Shift+drag rubber-band selection. HoverEvent queries the server for tooltip content at a cursor position. Both go to handlers you register with the chart through FigureRegistry.Register, and neither re-renders.

Stacked hierarchy — the tier-2 split

A tier-2 abstract record groups the non-mutating events, in the same way AxisRangeEvent groups the mutation events:

using MatPlotLibNet;
using MatPlotLibNet.Interaction;

// FigureNotificationEvent(ChartId, AxesIndex)        tier 2: ApplyTo is a sealed override with an empty body
// ├── BrushSelectEvent(…, X1, Y1, X2, Y2)            the corners of a Shift+drag selection, in data units
// ├── HoverEvent(…, X, Y, CallerConnectionId)        the cursor position; the server stamps the connection id
// └── DataCursorEvent(…, Annotation)                 a clicked data point

var figure = Plt.Create().Plot([0.0, 1.0, 2.0], [0.0, 1.0, 4.0]).Build();

FigureNotificationEvent[] notifications =
[
    new BrushSelectEvent("live-1", AxesIndex: 0, X1: 0.5, Y1: 0.0, X2: 1.5, Y2: 2.0),
    new HoverEvent("live-1", AxesIndex: 0, X: 1.0, Y: 1.0),
];

foreach (var notification in notifications)
{
    notification.ApplyTo(figure);   // does nothing: a notification never mutates the figure
}

Console.WriteLine(figure.SubPlots[0].XAxis.Min is null);   // True: the limits are untouched

The sealed override matters: notification events cannot override ApplyTo to mutate the figure. ChartSession.DrainAsync switches on the event's type: one case per notification event that has a handler (brush-select, hover, data cursor) runs that handler, a notification event with no handler registered is dropped, and every other event is a mutation, which applies itself and marks the batch for one publish.

Handler registration

A Register overload takes a ChartSessionOptions builder:

using MatPlotLibNet;
using MatPlotLibNet.AspNetCore;
using Microsoft.AspNetCore.Builder;
using Microsoft.Extensions.DependencyInjection;

var builder = WebApplication.CreateBuilder(args);
builder.Services.AddMatPlotLibNetSignalR();
var app = builder.Build();
app.MapChartHub();

var figure = Plt.Create()
    .Plot([0.0, 1.0, 2.0, 3.0], [0.0, 1.0, 4.0, 9.0])
    .WithServerInteraction("live-1", i => i.EnableBrushSelect().EnableHover().EnableDataCursor())
    .Build();

var registry = app.Services.GetRequiredService<FigureRegistry>();
registry.Register("live-1", figure, opts => opts
    .OnBrushSelect(evt =>
    {
        // Fire-and-forget observation — log, filter, trigger downstream work.
        Console.WriteLine($"User selected [{evt.X1}..{evt.X2}] × [{evt.Y1}..{evt.Y2}]");
        return ValueTask.CompletedTask;
    })
    .OnHover(async evt =>
    {
        // Request-response — return HTML fragment, delivered to originating caller only.
        var value = await LookupValueAtAsync(evt.X, evt.Y);
        return $"<b>{value:F3}</b> at ({evt.X:F1}, {evt.Y:F1})";
    })
    .OnDataCursor(async evt =>
    {
        // The reader clicked a point. Fire-and-forget, like brush-select: a click asks about the data.
        await OpenDetailPanelAsync(evt.Annotation.SeriesLabel, evt.Annotation.DataX, evt.Annotation.DataY);
    }));

app.Run();

// Your own lookups; these stand-ins answer at once.
static Task<double> LookupValueAtAsync(double x, double y) => Task.FromResult(x * x + y);

static Task OpenDetailPanelAsync(string? series, double x, double y)
{
    Console.WriteLine($"{series}: ({x}, {y})");
    return Task.CompletedTask;
}

The click has to be opted into on the figure as well, because a branch nobody asked for is weight in every chart that does not want it:

using MatPlotLibNet;

var figure = Plt.Create()
    .Plot([0.0, 1.0, 2.0], [0.0, 1.0, 4.0])
    .WithServerInteraction("live-1", i => i.EnableZoom().EnablePan().EnableDataCursor())
    .Build();

All three handlers run on the session's drain task, so the same single-reader guarantee holds and no locking is needed. The brush-select handler is a Func<BrushSelectEvent, ValueTask> and returns no value; so is the data-cursor handler, a Func<DataCursorEvent, ValueTask>. The hover handler is a Func<HoverEvent, ValueTask<string?>>; return null when there is no tooltip.

A click from the browser names the series exactly — it is read from the group the marker is drawn in — and reports where on the axes the reader clicked, resolved the same way a hover is. A native control reports the same event with the exact data point instead, because it runs the nearest-point search in process.

Caller-only response — ICallerPublisher

A hover response targets a single client. Earlier versions broadcast everything via Clients.Group(chartId). ICallerPublisher.SendTooltipAsync(connectionId, chartId, html) uses Clients.Client(connectionId).ReceiveTooltipContent(...) instead, which keeps ChartSession independent of IHubContext. The server stamps HoverEvent.CallerConnectionId itself, from Context.ConnectionId, so clients cannot spoof another user's connection.

using MatPlotLibNet.AspNetCore;
using MatPlotLibNet.Interaction;
using Microsoft.AspNetCore.SignalR.Client;

await using var connection = new HubConnectionBuilder()
    .WithUrl("http://localhost:5000/charts-hub")
    .Build();

// Only the connection that hovered receives the answer.
connection.On<string, string>("ReceiveTooltipContent", (chartId, html) => Console.WriteLine($"{chartId}: {html}"));

await connection.StartAsync();

// The payload carries no connection id. ChartHub.OnHover builds the HoverEvent and sets
// CallerConnectionId: Context.ConnectionId itself, so a client cannot name another one.
await connection.InvokeAsync("OnHover", new HoverEventPayload("live-1", AxesIndex: 0, X: 2.5, Y: 0.7));

The test SignalRInteractionTests.OnHover_ReturnsTooltip_ToCallerOnly_NotToOtherSubscribers verifies this: it connects two clients, and only the hovering one gets ReceiveTooltipContent.


Fluent opt-in

using MatPlotLibNet;

double[] xs = Enumerable.Range(0, 200).Select(i => i * 0.05).ToArray();
double[] ys = xs.Select(Math.Sin).ToArray();

var figure = Plt.Create()
    .WithTitle("Bidirectional demo")
    .Plot(xs, ys)
    .WithServerInteraction("live-1", i => i
        .EnableZoom()
        .EnablePan()
        .EnableReset()
        .EnableLegendToggle())
    .Build();

// everything, shorter: All() also opts into brush-select, hover and the data cursor
var everything = Plt.Create()
    .Plot(xs, ys)
    .WithServerInteraction("live-1", i => i.All())
    .Build();

What WithServerInteraction does:

  1. It sets Figure.ChartId = "live-1".
  2. It sets Figure.ServerInteraction = true.
  3. For each event type you opted in to, it sets the matching figure flag: zoom, pan or reset sets EnableZoomPan, legend toggle sets EnableLegendToggle, brush-select sets EnableSelection, hover sets EnableRichTooltips, and the data cursor sets EnableDataCursor. The last three decide which branches the dispatcher script carries.
  4. SvgTransform branches on ServerInteraction. When it is true, it emits the server-interaction script and skips the local scripts it replaces: zoom and pan, legend toggle and drag, rich tooltips, and selection. The two paths are mutually exclusive, so nothing is handled twice.

ServerInteractionBuilder is a small public class with fluent EnableZoom() / EnablePan() / EnableReset() / EnableLegendToggle() / EnableBrushSelect() / EnableHover() / EnableDataCursor() / All() methods that return this.

DI registration

using MatPlotLibNet;
using MatPlotLibNet.AspNetCore;
using Microsoft.AspNetCore.Builder;
using Microsoft.Extensions.DependencyInjection;

var builder = WebApplication.CreateBuilder(args);
builder.Services.AddMatPlotLibNetSignalR();   // v1.2.0: now also registers FigureRegistry

var app = builder.Build();
app.MapChartHub();                             // unchanged

var figure = Plt.Create()
    .Plot([0.0, 1.0, 2.0, 3.0], [0.0, 1.0, 4.0, 9.0])
    .WithServerInteraction("live-1", i => i.All())
    .Build();

// register a live figure
var registry = app.Services.GetRequiredService<FigureRegistry>();
registry.Register("live-1", figure);

app.Run();

Browser-side dispatcher script

When Figure.ServerInteraction == true, SvgTransform emits the server-interaction script into the <svg> output. The script is a single IIFE with the marker token mplSignalRInteraction. It does three things:

  1. It finds the HubConnection to send through: the one its chart's host element carries (an MplLiveChart gives its chart a proxy to the connection its client holds, one for each chart, so two live charts on a page cannot reach for the same global), else the page's own window.__mpl_signalr_connection. If there is none, the script does nothing and raises no error.
  2. It reads data-chart-id off the root <svg> element.
  3. It wires these listeners. Each one works on the axes under the pointer, and converts the pointer to data with the range that axes was drawn with:
    • On wheel, it zooms about the data point under the cursor and calls connection.invoke('OnZoom', { chartId, axesIndex, xMin, xMax, yMin, yMax }).
    • On pointerdown, pointermove and pointerup without Shift, it computes a delta in data space and calls connection.invoke('OnPan', { chartId, axesIndex, dxData, dyData, inView }); inView is the range on screen, so an axes that scales itself pans from what the reader sees.
    • On keydown with Home, it calls connection.invoke('OnReset', { chartId, axesIndex, xMin, xMax, yMin, yMax }) for every axes, with the range that axes was first drawn with.
    • On click on a legend entry (an element with data-legend-index), it calls connection.invoke('OnLegendToggle', { chartId, axesIndex, seriesIndex }). A click on a plotted line never toggles it.
    • When opted in: a Shift+drag calls OnBrushSelect with the corners in data units (Escape cancels it), a pointer move calls OnHover with at most one request in flight, and a click on a plotted series calls OnDataCursor with the series' name and the data point under the click.

A page that uses MplLiveChart needs nothing more: the component hands its chart the connection its client already holds, mounts the chart so that its script runs, and mounts a redraw that arrives in the middle of a drag or a band when the chart is idle. A page of your own creates the HubConnection and exposes it as window.__mpl_signalr_connection before it mounts the first SVG: the script reads the global each time it sends an event, and registers its hover-tooltip handler on the connection when it runs. The React, Vue and Angular components mount a chart the same way, and each package exports mountSvg(host, svg, hub).

The script travels inside the SVG, and a browser never runs a <script> that arrives through innerHTML. So the page mounts every SVG, the first one and each update, with a function that puts the markup in place and re-creates its script elements, such as mplMountSvg below. With a plain innerHTML the chart is drawn, but the script never runs and no gesture reaches the server.

<script src="https://cdnjs.cloudflare.com/ajax/libs/microsoft-signalr/8.0.0/signalr.min.js"></script>
<script>
    // Mounts a chart's SVG markup in host and runs the scripts inside it. A <script> that arrives through
    // innerHTML never runs, so each one is replaced by a fresh copy, which the browser runs as it is inserted.
    function mplMountSvg(host, svgMarkup) {
        host.innerHTML = svgMarkup;
        host.querySelectorAll('script').forEach(function (inert) {
            var live = document.createElementNS(inert.namespaceURI, 'script');
            for (var i = 0; i < inert.attributes.length; i++)
                live.setAttribute(inert.attributes[i].name, inert.attributes[i].value);
            live.textContent = inert.textContent;
            inert.parentNode.replaceChild(live, inert);
        });
    }

    const host = document.getElementById('host');
    const conn = new signalR.HubConnectionBuilder()
        .withUrl('/charts-hub')
        .withAutomaticReconnect()
        .build();
    window.__mpl_signalr_connection = conn;
    conn.on('UpdateChartSvg', (id, svg) => {
        if (id === 'live-1') mplMountSvg(host, svg);
    });
    conn.start()
        .then(() => conn.invoke('Subscribe', 'live-1'))
        .then(() => fetch('/api/chart/live.svg'))
        .then(resp => resp.text())
        .then(svg => mplMountSvg(host, svg));
</script>

Mounted this way, the script runs again on every mount and wires the new SVG. The hover tooltip is one element per chart and its handler is registered once per connection, so a redraw never leaves a second tooltip on screen.

Several viewers of one chart

Viewers of one chart share its view through SignalR's group, and the last change wins. The hub stamps every event with the connection it came in on and the name the chart gave that connection ("Viewer 1", "Viewer 2"), over whatever the payload claimed, so a client cannot speak for another viewer. After a batch in which a viewer moved the shared view (a zoom, a pan, a reset or a rotation) every viewer is told who. EnableViewerCursors() on WithServerInteraction has a page send where its pointer is, one position in fifty milliseconds, and draw the others' pointers with their names. A chart says when it is busy (data-mpl-busy on its SVG during a drag or a band) and when it is idle again (mpl:idle); the code that mounts a redraw waits for it, as mplMountSvg above does.

One handler for every event

OnBrushSelect, OnHover and OnDataCursor are callbacks for three kinds of event. ChartSessionOptions.Handle(IChartEventHandler) takes one handler that receives every event once, whichever kind, a zoom, a pan, a legend toggle and a reset included, after the figure has taken it, with a ChartEventContext that names the viewer. It runs inline, so the next event waits for it, and a handler that throws costs only its own event. A brush also gives it a RowSelectionEvent with the keys of the rows the rectangle covers. The native controls take the same handler as their ChartEventHandler property, and ChartEventHandlerFaulted reports one that throws. See Examples for one written out.

Samples

Two runnable samples ship with v1.2.0:

Samples/MatPlotLibNet.Samples.AspNetCore

A bare ASP.NET Core app with a static HTML page. It builds a 200-point sinusoid figure, calls .WithServerInteraction("live-1", i => i.All()), registers the figure and serves /api/chart/live.svg. The page loads @microsoft/signalr from a CDN. The sample is about 150 lines of code in total and has no Blazor or Razor dependency.

dotnet run --project Samples/MatPlotLibNet.Samples.AspNetCore
# → http://localhost:5000

Samples/MatPlotLibNet.Samples.Blazor/Components/Pages/Interactive.razor

The Blazor equivalent, at route /interactive. It is one <MplLiveChart> on a figure with .WithServerInteraction(...) and EnableViewerCursors(): the component hands the chart's script the connection its client holds, so the page writes no JavaScript and sets no window.__mpl_signalr_connection. Open it in a second window to see the other viewer's pointer. It also shows Dispose implemented via UnregisterAsync.

ChartSubscriptionClient lifecycle (v1.13.0 fix)

ChartSubscriptionClient in MatPlotLibNet.Blazor wraps a SignalR HubConnection and subscribes to UpdateChartSvg and UpdateChart. MplChart and MplLiveChart use it under the hood. v1.13.0 fixed two lifecycle bugs and clarified a third:

  • Double-connect is now safe. A second ConnectAsync call used to orphan the prior HubConnection without any warning, and with WithAutomaticReconnect that orphan kept reconnecting forever. ConnectAsync now tears down any existing connection first, through DisposeCurrentHubAsync.
  • Subscription tokens are tracked instead of discarded. The client captures On(...) handler registrations as IDisposable tokens and disposes them on teardown.
  • Teardown races are reported instead of swallowed. If HubConnection.DisposeAsync() throws during a race, the client now catches it and reports it via ChartDiagnostics.Emit(...). Dispose and DisposeAsync still never throw.
  • Shared-client note — MplLiveChart no longer disposes an injected client. The optional Client parameter (IChartSubscriptionClient?) lets MplLiveChart.DisposeAsync() dispose only the client it created itself. Pass your own instance to share one connection across components.

Testing

  • Every event's ApplyTo, the abstractness guards, the inheritance shape, record equality and the PanEvent null-limit no-op are tested in FigureInteractionEventTests.
  • The figure registry is tested against a fake IChartPublisher: a publish to an unknown chart returns false, a single-event mutation publishes, and a burst of 50 events is coalesced into a bounded number of publishes (FigureRegistryTests).
  • The hub is tested with real SignalR round trips, one for each hub method, on TestServer and HubConnectionBuilder, with no mocks (SignalRInteractionTests).
  • The script emission toggle, the data-chart-id attribute and the local scripts being suppressed when the dispatcher takes over are tested on the SVG the figure writes.
  • ServerInteractionBuilder is tested for flag routing, chaining, the default off-state and the return-this semantics.

What shipped after v1.2.0

Item Status Version
Brush-select + hover round-trip Done v1.2.2 — see Notification events above
Clicked data point round-trip Done 1.17.1 — EnableDataCursor() on the figure, OnDataCursor on the session
Native controls (Avalonia 12 + Uno) Done v1.3.0 — see Interactive Controls
3-D round 2 (6 new series) Done v1.3.0 — see Chart Types
MathText completion Done v1.3.0 — see Advanced
Server-mode adapter for native controls Done v1.3.0 — .WithServerInteraction((method, payload) => hub.SendAsync(method, payload)) on the control
Legend toggle in native controls Done v1.3.0 — LegendToggleModifier hit-testing
Rubber-band selection visual Done v1.3.0 — BrushSelectState overlay
Hover tooltip in native controls Done v1.3.0 — NearestPointFinder local lookup
One handler for every event Done 1.27.0 — IChartEventHandler on ChartSessionOptions.Handle and on a native control's ChartEventHandler
Several viewers by design Done 1.27.0 — a viewer stamped on every event, EnableViewerCursors(), and who moved the shared view
A live chart that sends its own gestures Done 1.27.0 — MplLiveChart hands its script the client's connection

Nothing of this page is deferred any more. See Roadmap for what is done.

MatPlotLibNet 1.30.0

On the docs site

Clone this wiki locally