Skip to content

Getting Started

One package, one namespace and one stylesheet - no services to register. Then a BlowCanvas in a container that has a height is a working node editor over your own List<BlowNode> and List<BlowEdge>.

Install

The package runs on .NET 10 and 11, in Blazor WebAssembly, Blazor Server, a Blazor Web App and Blazor Hybrid. In a Web App it belongs in the project that holds the pages with a canvas - the .Client project, for pages rendered with InteractiveWebAssembly.

dotnet add package Bit.Blow

Add the namespace to _Imports.razor. Everything in the library - the components, the model, layout, history and the clipboard - lives in it:

@using Bit.Blow

A canvas needs an interactive render mode: a statically rendered page shows its markup but never responds. WebAssembly is the one to choose for editing, since every pointer move of a drag is handled in C# without a network hop; InteractiveAuto works too, and so does Blazor Server, with each move a round trip over the circuit. On WebAssembly, outside AOT builds, the library can also be lazy loaded - but not by a page with its own render mode, like the one below, as it stands: give Routes the render mode instead, or have the page load the assembly itself.

@rendermode InteractiveWebAssembly

Link the stylesheet

From the host page - Components/App.razor in a Blazor Web App, wwwroot/index.html in a standalone WebAssembly or a Hybrid app. The link is required: the library does not inject its stylesheet, so leaving it out gives an unstyled canvas rather than an error. Put your own overrides after it.

<link rel="stylesheet" href="_content/Bit.Blow/bit-blow.css" />

href="@Assets["_content/Bit.Blow/bit-blow.css"]" in App.razor serves the fingerprinted copy. The script module, _content/Bit.Blow/bit-blow.js, needs no tag: the component imports it the first time it needs it.

A first flow

The canvas fills its container (width: 100%; height: 100%), so the container needs a height - or give the canvas one directly with Style="height: 600px". The graph is plain C#: the canvas edits the lists you hand it in place as the user works.

Order placed
Payment
Shipped
bit Blow
<div class="bb-demo-bar">
    <button type="button" class="btn btn-secondary" @onclick="AddStep">Add step</button>
</div>

<div style="height: 22rem">
    <BlowCanvas @ref="_flow" Nodes="_nodes" Edges="_edges" FitViewOnInit="true">
        <BlowBackground />
        <BlowControls />
    </BlowCanvas>
</div>

@code {
    private BlowCanvas? _flow;
    private int _next = 4;

    private List<BlowNode> _nodes =
    [
        new BlowNode { Id = "1", Type = "input", Label = "Order placed", Position = new(0, 0) },
        new BlowNode { Id = "2", Label = "Payment", Position = new(0, 100) },
        new BlowNode { Id = "3", Type = "output", Label = "Shipped", Position = new(0, 200) },
    ];

    private List<BlowEdge> _edges =
    [
        new BlowEdge { Id = "e1-2", Source = "1", Target = "2" },
        new BlowEdge { Id = "e2-3", Source = "2", Target = "3", Animated = true },
    ];

    private async Task AddStep()
    {
        if (_flow is null) return;
        var id = (_next++).ToString();
        _flow.AddNodes(new BlowNode { Id = id, Label = $"Step {id}", Position = new(220, (_next - 5) * 70) });
        await _flow.FitViewAsync(300);
    }
}

That is a working editor. Nodes drag; dragging from a handle to another node connects them; clicking selects, Shift+click adds to the selection and Shift+drag on the background draws a selection box; Delete removes the selection; the wheel zooms toward the cursor, dragging the background pans and two fingers pinch. Tab reaches every node and edge, Enter selects, the arrow keys move the selection and Escape clears it.

Add step goes through the canvas captured with @ref: AddNodes puts a node in the list and FitViewAsync(300) eases the view over 300 milliseconds so the new step is in sight. Adding to _nodes directly works as well - the canvas re-reads the list each time your component renders.

Reacting to edits

Your state is always the graph on screen. What the canvas raises tells you when something worth knowing has happened:

  • NodesChanged and EdgesChanged once an edit is complete - a drag released, a resize ended, a connection made, something deleted, pasted, aligned or nudged with the keyboard. Not on every pointer move.
  • OnNodeDrag, OnNodeResize and OnMove while a gesture runs, for live readouts.
  • OnSelectionChange when the selected set actually changes.
  • OnConnect, OnReconnect and OnDelete for the specific edits. A connection adds its own edge; OnConnect is for side effects.
  • OnGraphChanged once per completed edit of any kind, with what kind it was, who made it and the elements it touched - the one place to persist, validate or broadcast from.

Nodes/NodesChanged and Edges/EdgesChanged are bindable pairs, so @bind-Nodes="_nodes" compiles - but the list instance never changes, so it is mostly a signal to persist.

When your own code changes the graph - adds a node, edits a label, flips Hidden - the usual Blazor rule applies: your component re-renders after its event handler and the canvas re-reads the lists. For a change made outside a render of your component - a timer, a message from a server - call _flow.Refresh(remeasure: true), or InvokeAsync(StateHasChanged) on your component.

Calling the canvas from code

Capture the canvas with @ref for the imperative API - the counterpart of React Flow's useReactFlow():

_flow.FitView();
await _flow.SetCenterAsync(x: 400, y: 200, zoom: 1.5, durationMs: 300);
BlowXYPosition point = _flow.ScreenToFlowPosition(e.ClientX, e.ClientY);

_flow.AddNodes(node);
await _flow.DeleteElementsAsync(nodes: [node]);
BlowNode? found = _flow.GetNode("2");

BlowSnapshot snapshot = _flow.ToObject();
await _flow.RestoreAsync(snapshot);

OnInit hands you the same reference once the canvas has rendered and measured for the first time. To drive a flow from a sidebar or a toolbar elsewhere on the page, pass the reference to them; nothing like React Flow's provider is needed (see Provider).

Lazy loading on WebAssembly

Blow registers nothing, so nothing has to be taken out of Program.cs, and a WebAssembly app can fetch it only when someone opens a page with a canvas. Mark the assembly as lazy loaded in the project that runs in the browser, outside AOT builds, with a runtime switch next to the mark so the router knows the assembly is there to load, and load it before that page first renders:

<!-- AOT builds are left out: see below. -->
<ItemGroup Condition=" '$(RunAOTCompilation)' != 'true' ">
  <BlazorWebAssemblyLazyLoad Include="Bit.Blow.wasm" />
  <RuntimeHostConfigurationOption Include="MyApp.LazyLoadsBlow" Value="true" Trim="true" />
</ItemGroup>
@* App.razor - in a Blazor Web App, the client project's Routes.razor: the router waits for OnNavigateAsync
   before it renders the page. typeof(Program) is the project the router's file is in, in either kind of app. *@
@using Microsoft.AspNetCore.Components.WebAssembly.Services
@inject LazyAssemblyLoader LazyAssemblyLoader

<Router AppAssembly="typeof(Program).Assembly" OnNavigateAsync="OnNavigateAsync">
    ...
</Router>

@code {
    // Set only where Bit.Blow.wasm is marked: loading an assembly that is not marked throws.
    private static readonly bool LazyLoadsBlow = AppContext.TryGetSwitch("MyApp.LazyLoadsBlow", out var on) && on;

    private async Task OnNavigateAsync(NavigationContext context)
    {
        // The pages with a canvas: fetch Blow before they render. A second call loads nothing again.
        if (LazyLoadsBlow && IsEditorPage(context.Path))
            await LazyAssemblyLoader.LoadAssembliesAsync(["Bit.Blow.wasm"]);
    }

    // /workflow, /workflows and the routes beneath them, such as /Workflows/42 (routes match regardless of case),
    // but not /workflows-archive. Add every other route that renders Blow. The path keeps any query and fragment.
    private static bool IsEditorPage(string path)
    {
        var page = path.Split('?', '#')[0].Split('/')[0];
        return page.Equals("workflow", StringComparison.OrdinalIgnoreCase)
            || page.Equals("workflows", StringComparison.OrdinalIgnoreCase);
    }
}

The stylesheet is a plain <link>, served whether the assembly has loaded or not, and the canvas imports its script module the first time it renders.

  • Only what renders after the assembly has loaded may use Blow's types - the pages it is loaded for and a layout only they use, not App.razor, Routes.razor, a layout every page shares or Program.cs. Those pages can hold the canvas and fields of Blow's types, structs such as BlowViewport included. The method that calls LoadAssembliesAsync cannot: WebAssembly resolves what a method refers to when the method first runs, which is before the load, and does not retry.
  • No public type in an assembly the router reads in the browser - the app's own assembly first of all, the client project's in a Blazor Web App - may derive from or implement one of Blow's, close a generic type over one or constrain a type parameter to one: no public IBlowEdgeRouter, IBlowLayout, BlowLayoutOptions or IBlowValidationRule, no public BlowNode or BlowEdge subclass, no component that @inherits one of Blow's and none with @typeparam TNode where TNode : BlowNode. The router reads those types when it first builds its route table, after the first navigation's OnNavigateAsync, so such a type fails the app on its first page only when the app is opened away from a canvas: try it from a page without one. An internal class, or a private one nested in a page, is fine; a public one goes in a library of your own, lazy loaded together with Bit.Blow.
  • In a Blazor Web App only the browser lazy loads, so give Routes a render mode in App.razor that brings the router - and its OnNavigateAsync - to the browser, as this demo's <Routes @rendermode="InteractiveWebAssembly" /> does. Under InteractiveAuto the first visit runs over a server circuit and the browser downloads Blow on a later one.
  • With per-page render modes the router renders statically on the server and never loads the assembly in the browser, so a page that renders a canvas fails there with Could not load file or assembly 'Bit.Blow' once it is interactive. Such a page loads Blow itself: it names none of Blow's types, awaits LoadAssembliesAsync in OnInitializedAsync, and only then renders a component of yours that holds the canvas.
  • Every host other than standalone WebAssembly registers LazyAssemblyLoader itself when something it renders injects it - the server project, where Routes.razor runs while it is prerendered and over the circuit under InteractiveAuto, and a Hybrid host that shares the router's file: builder.Services.AddScoped<LazyAssemblyLoader>(). Outside the browser it downloads nothing, but loads each assembly the call names from the ones the app references and throws if one is missing.
  • The condition leaves AOT builds out. AOT compiles every assembly into dotnet.native.wasm, so there is nothing left to download later, and lazy loading an AOT-compiled assembly can fail at startup. The switch is set only where the mark is, so an AOT build skips LoadAssembliesAsync as well: loading an assembly that is not marked throws.

Where to go next

An unhandled error has occurred. Reload 🗙