Skip to content

Getting started

One package and one service registration - then any element on an interactively rendered page can spring, fade, follow the pointer or animate out before it is removed. All of the maths runs in C#; the small browser bridge loads itself the first time an animation runs.

Install

The package targets .NET 10 and 11. Its browser bridge, bit-bmotion.js, ships as a static web asset and is imported on demand, so there is no <script> tag to add and no JavaScript to write. In a Blazor Web App the package belongs in the project whose components animate - the .Client project for WebAssembly pages.

dotnet add package Bit.Bmotion

Register the services

A Blazor Web App has two DI containers: the client's components are instantiated once on the server for the prerender pass and again in the browser, so the registration goes in both Program.cs files. This site keeps it in one extension method that both call. A WebAssembly app that is not AOT-compiled can also lazy load the library instead of registering it.

// Program.cs - in every project that renders animations
using Bit.Bmotion;

builder.Services.AddBitBmotionServices();

The options are global. The two worth deciding on day one are how prefers-reduced-motion is honoured - BmReducedMotionMode.User is the recommended setting - and what prerendered markup shows before the runtime takes over:

builder.Services.AddBitBmotionServices(o =>
{
    o.ReducedMotion = BmReducedMotionMode.User;   // follow the OS everywhere
    o.Prerender = BmPrerenderMode.Animate;        // play enter animations from the served HTML
});

The other two are safety switches with sensible defaults. CssSafeMode checks the string values a target carries - colours, sizes, shadows, filters - before they are written into the inline style, and is worth turning on wherever any of them come from user input. InertWhileExiting, on by default, makes content that is playing its exit animation inert, so a closing dialog cannot be clicked, focused or read out a second time.

builder.Services.AddBitBmotionServices(o =>
{
    o.CssSafeMode = BmCssSafeMode.Throw;   // Off (default), Warn or Throw on an unsafe CSS string
    o.InertWhileExiting = true;            // the default: exiting content can't be interacted with
});

Make the components reachable

One line in _Imports.razor, in every project that renders animations. Without it <Bmotion> is not a known component and the build fails with RZ10012.

@using Bit.Bmotion

Pick a render mode

Animations need an interactive render mode. InteractiveWebAssembly supports every feature, because the engine can run its per-frame loop in the browser - it is what this site uses.

On Blazor Server the browser plays the same animations: transforms, opacity, colours, sizes, filters, keyframes, springs, inertia and arcs, on enter, exit, gestures and variants alike. Drag stays under the pointer, with OnDrag a round trip behind. The two things that need the per-frame loop - per-frame callbacks and SVG path morphs - become an instant change. Inject BmotionCapabilities to tell which runtime you are on rather than guessing; the Accessibility page shows it live.

Prerendered enter animations

A prerendered page has no runtime yet, so by default an element is served at its Initial state and animates once the page is interactive - which for Initial="Bm.To(opacity: 0)" means invisible content until the runtime has downloaded. With BmPrerenderMode.Animate the enter animation is compiled to CSS and plays straight from the served HTML; it needs the library's stylesheet in the page head. BmPrerenderMode.Final serves elements at rest instead, with no stylesheet.

<!-- App.razor, in <head> - only needed for BmPrerenderMode.Animate -->
<link rel="stylesheet" href="_content/Bit.Bmotion/bit-bmotion.css" />

The option is the default for every element, and any one element can choose differently with its own Prerender parameter - for instance the headline that must be readable, and indexable, the moment the HTML arrives, on a page whose other content animates in. Whichever mode prerendered it, an element that was served at rest is taken over at rest, so its entrance doesn't play a second time.

<Bmotion Prerender="BmPrerenderMode.Final"
         Initial="Bm.To(opacity: 0, y: 20)" Animate="Bm.To(opacity: 1, y: 0)">
    <h1>Visible in the served HTML</h1>
</Bmotion>

A first animation

<Bmotion> renders no element of its own: it animates the one element inside it. Initial is where that element starts, Animate is where it is going, and Transition says how it gets there. Gesture states such as WhileHover and WhileTap layer on top and revert by themselves.

<Bmotion Initial="Bm.To(opacity: 0, y: 20)"
         Animate="Bm.To(opacity: 1, y: 0)"
         WhileHover="Bm.To(scale: 1.1)"
         WhileTap="Bm.To(scale: 0.95)"
         Transition="Bm.Spring(bounce: 0.4, duration: 0.6)">
    <div class="box">Hello</div>
</Bmotion>
Live · hover it, press it
Hello

Lazy loading on WebAssembly

A WebAssembly app can fetch Bmotion only when someone opens a part of the app that animates. It leaves AddBitBmotionServices out and calls IServiceProvider.ConfigureBmotionServices(...) instead, before the first animated element is created: that creates every service Bmotion, BmotionReorderGroup and BmotionInspector need, once per WebAssembly runtime, with the options it sets, and IServiceProvider.GetBmotionService<T>() hands the app's own code the same ones. Mark the assembly as lazy loaded in the project that runs in the browser, and load it before the first page that uses it renders:

<!-- The browser project's .csproj -->
<ItemGroup>
  <BlazorWebAssemblyLazyLoad Include="Bit.Bmotion.wasm" />
</ItemGroup>
@* App.razor - in a Blazor Web App, the client project's Routes.razor: the router waits for
   OnNavigateAsync before it renders the page. *@
@using Microsoft.AspNetCore.Components.WebAssembly.Services
@inject LazyAssemblyLoader LazyAssemblyLoader

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

@code {
    private async Task OnNavigateAsync(NavigationContext context)
    {
        // The pages that animate: fetch Bmotion before they render. A second call loads nothing again.
        if (context.Path.StartsWith("showcase", StringComparison.OrdinalIgnoreCase))
        {
            await LazyAssemblyLoader.LoadAssembliesAsync(["Bit.Bmotion.wasm"]);
        }
    }
}

Those pages, or a layout only they use, hold the animated elements as usual. The layout creates the services, with the options AddBitBmotionServices would have been given - where the services are registered, as on the server of a Blazor Web App prerendering it, the call checks that those are the options given there - and a component that animates from code takes its service from GetBmotionService<T>() instead of injecting it:

@* ShowcaseLayout.razor *@
@inherits LayoutComponentBase
@inject IServiceProvider Services

@Body

@code {
    // Runs before the elements of the page are created.
    protected override void OnInitialized() => Services.ConfigureBmotionServices(o =>
    {
        o.ReducedMotion = BmReducedMotionMode.User;
        o.Prerender = BmPrerenderMode.Animate;
    });
}
@* Counter.razor *@
@inject IServiceProvider Services

@code {
    // Taken once, as an injected service would be.
    private BmotionAnimateService Motion => field ??= Services.GetBmotionService<BmotionAnimateService>();
}
  • Leave AddBitBmotionServices out of that project's Program.cs: calling it references Bmotion's types before the assembly is there. For the same reason only what renders after the assembly has loaded may use Bmotion'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.
  • No type in an assembly the router reads when the app starts - the app's own assembly first of all - may derive from or implement one of Bmotion's: no component that inherits BmotionAnimatePresence or BmotionConfig, no IBmotionInterop of your own. On WebAssembly such a type fails to load before Bit.Bmotion is there, and keeps failing after it has loaded. Put it in a library that is lazy loaded together with Bit.Bmotion.
  • Call ConfigureBmotionServices in every page or layout that holds animated elements, not only in the one a visitor opens first. Until it has run, an element - and GetBmotionService<T>() - throws Bit.Bmotion's services are not registered, as it does wherever the registration is missing: the call is what tells an app that lazy loads Bmotion apart from one that forgot to register it.
  • The options are set once per runtime, by the first call, and shared by every element. Every later call has to set the same ones or it throws, naming the options that differ - so give every call the same configuration, from one shared method. Per element, Prerender and a surrounding <BmotionConfig ReduceMotion> still override them.
  • In a Blazor Web App only the browser lazy loads. Give Routes the InteractiveWebAssembly or InteractiveAuto render mode in App.razor, so the router - and its OnNavigateAsync - runs in the browser. The server project keeps its AddBitBmotionServices(...) and registers LazyAssemblyLoader, which Routes.razor injects while it is prerendered there: builder.Services.AddScoped<LazyAssemblyLoader>(). Give ConfigureBmotionServices the options the server gives AddBitBmotionServices - prerendering the layout, the server throws if they differ - or elements prerendered at rest play their entrance a second time.
  • In a Blazor Web App, also load Bmotion for the page the visitor arrives on in the client's Program.cs, between builder.Build() and RunAsync(). The router renders nothing until OnNavigateAsync has finished, so a download started only there swaps the prerendered page for an empty one until the assembly arrives; started before the app runs, it leaves the prerendered page on screen. The full snippet is in the README.
  • Do not lazy load in an AOT build. 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.

Where to go next

Bmotion 0 el · 0 active ▸
An unhandled error has occurred. Reload 🗙