Getting started
One package, one service registration and one stylesheet - then any IList<TItem>
on an interactively rendered page becomes a list people can put in order by hand.
Install
In a Blazor Web App with an interactive client, the package belongs in the .Client
project, and the services are registered in both projects - the server prerenders the same
components the client runs.
dotnet add package Bit.Bortable
Register the services
It registers one scoped service: the coordinator that holds the drag in progress, so lists
sharing a group can hand an item to each other. Scoped means one per circuit on Blazor Server
and one per application on WebAssembly, so two users never share a drag. Calling it more than once
is harmless; without it, the first list that renders throws, on every host. Only a WebAssembly app that
lazy loads the library goes without, and says so with the
Bit.Bortable.Unregistered runtime switch.
// Program.cs - in every project that renders a list
builder.Services.AddBitBortableServices();Reference the stylesheet
It styles the drag states only - the ghost, the chosen item, the hidden original, the swap
target, the multi-drag selection - and leaves the look of the list to you. It is not injected for
you: link it from the host page, App.razor or index.html. The script module
needs no tag: the lists import it on demand, once for all of them.
<link rel="stylesheet" href="_content/Bit.Bortable/bit-bortable.css" />
And the namespace, in _Imports.razor:
@using Bit.BortableA first list
Each item is wrapped in a <div> that carries the drag handlers;
ItemTemplate renders what goes inside it. Class and Style go
to the list container, ItemClass to every item wrapper. @bind-Items keeps
your field in step: the list is changed in place, so the order a user makes is the order your
code reads back.
<Bortable @bind-Items="_items" TItem="string" Class="todo" ItemClass="todo-item"> <ItemTemplate Context="item">@item</ItemTemplate> </Bortable> @code { private IList<string> _items = new List<string> { "Write the spec", "Review the PR", "Ship it" }; }
Order: Write the spec, Review the PR, Ship it
List<T> or anything else whose
IsReadOnly is false - and the field declared as IList<TItem>,
the parameter's type. Items are rendered with @key, so they must be unique within a list.
An interactive render mode
A list answers a drag only on a page that renders interactively. A statically rendered page shows the items but never drags them; a prerendered one shows them at once and starts dragging as soon as it is interactive.
| Hosting model | Register the services in | Link the stylesheet from |
|---|---|---|
| Blazor WebAssembly | Program.cs | wwwroot/index.html |
| Blazor Server | Program.cs | App.razor |
| Blazor Web App | Both Program.cs files, with the pages in the .Client project for a WebAssembly or Auto render mode | The server's App.razor |
| Blazor Hybrid | MauiProgram.cs | wwwroot/index.html |
On Blazor Server the pointer is followed and measured in the browser, and the circuit carries only what changes: the start of a drag, each new drop position and its end - so a drag stays smooth there too.
App-wide defaults
The same registration takes defaults for every list of the app - the announcements in its language, a longer long press, a slower slide. A default replaces the parameter's own default for every list that does not set the parameter itself; a list that does keeps its value. Several calls add up, in order.
builder.Services.AddBitBortableServices(options =>
{
options.Messages = MyTexts.German; // the texts screen readers hear
options.TouchDelay = 300; // a longer long press
options.Animation = 200; // a slower slide
});
BortableOptions covers Animation, SwapThreshold, Delay,
TouchDelay, DelayTolerance, ForceFallback, Scroll,
ScrollSensitivity, ScrollSpeed, Keyboard, RevertOnSpill,
Messages, and the classes GhostClass, ChosenClass, DragClass,
SwapClass and SelectedClass. A property left null leaves the parameter's
own default.
Lazy loading on WebAssembly
A WebAssembly app can fetch Bortable only when someone opens a part of the app that has a list. Its
Program.cs cannot call AddBitBortableServices then, so the app sets the
Bit.Bortable.Unregistered runtime switch, and the lists create their drag coordinator themselves,
once per application, and share it: lists of a group still hand items to each other. Without the switch a list
that finds no registration throws, so an app that merely forgot it still hears of it. In the project that runs in
the browser, set that switch, mark the assembly as lazy loaded with a switch of your own next to the mark so the
router knows it is there to load, and load it before the first page that uses it renders:
<!-- The browser project's .csproj. -->
<ItemGroup>
<!-- Program.cs leaves AddBitBortableServices out, in every build: the lists create their own coordinator. -->
<RuntimeHostConfigurationOption Include="Bit.Bortable.Unregistered" Value="true" />
</ItemGroup>
<!-- AOT builds load Bit.Bortable with the rest of the app. -->
<ItemGroup Condition=" '$(RunAOTCompilation)' != 'true' ">
<BlazorWebAssemblyLazyLoad Include="Bit.Bortable.wasm" />
<RuntimeHostConfigurationOption Include="MyApp.LazyLoadsBortable" 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.Bortable.wasm is marked: loading an assembly that is not marked throws.
private static readonly bool LazyLoadsBortable = AppContext.TryGetSwitch("MyApp.LazyLoadsBortable", out var on) && on;
private async Task OnNavigateAsync(NavigationContext context)
{
// The pages with lists: fetch Bortable before they render. A second call loads nothing again.
if (LazyLoadsBortable && IsBoardPage(context.Path))
await LazyAssemblyLoader.LoadAssembliesAsync(["Bit.Bortable.wasm"]);
}
// /board and the routes beneath it, such as /Board/2 (routes match regardless of case), but not
// /board-settings. Add every other route that renders a list. The path keeps any query and fragment.
private static bool IsBoardPage(string path)
{
path = path.Split('?', '#')[0];
return path.Equals("board", StringComparison.OrdinalIgnoreCase)
|| path.StartsWith("board/", StringComparison.OrdinalIgnoreCase);
}
}
- Leave
AddBitBortableServicesout of that project'sProgram.cs: calling it references Bortable's types before the assembly is there. For the same reason only what renders after the assembly has loaded may use Bortable's types - the pages it is loaded for and a layout only they use, notApp.razor,Routes.razor, a layout every page shares,Program.csor the method that callsLoadAssembliesAsync. - No public type in an assembly the router reads when the app starts - the app's own assembly first of all - may derive from one of Bortable's, or from a generic type closed over one: no component that inherits
Bortable<TItem>, noBortableMessagessubclass. On WebAssembly such a type fails to load before Bit.Bortable is there, and keeps failing after it has loaded. Make itinternal, or put it in a library that is lazy loaded together with Bit.Bortable. - Without the registration there are no app-wide defaults: set
Messages,TouchDelay,Animationand the classes on the lists themselves. Bit.Bortable.Unregisteredbelongs only in the project that lazy loads. Everywhere else - Blazor Server, Blazor Hybrid, the server project of a Blazor Web App, a WebAssembly app that loads Bortable with the rest - register the services and leave the switch out, so a missing registration throws where it happens.- In a Blazor Web App only the browser lazy loads. Give
RoutestheInteractiveWebAssemblyorInteractiveAutorender mode inApp.razor, so the router - and itsOnNavigateAsync- runs in the browser. The server project loads Bortable with the rest of the app, keeps itsAddBitBortableServices()- it prerenders the lists - and registersLazyAssemblyLoader, whichRoutes.razorinjects there too:builder.Services.AddScoped<LazyAssemblyLoader>(). - 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 - the condition on the secondItemGroupleaves it out, and the router's switch skips the load with it.Bit.Bortable.Unregisteredstays outside the condition: an AOT build runs the sameProgram.cs, without the registration.
When something does not work
- "Bit.Bortable's services are not registered" - call
AddBitBortableServices(), in both projects of a Blazor Web App. A WebAssembly app that lazy loads Bortable sets theBit.Bortable.Unregisteredswitch instead, in the project that runs in the browser and outside theItemGroupan AOT build leaves out. - The items render, but nothing can be dragged - the page is not interactive. Give it, or the app, an interactive render mode.
- The dragged item is not dimmed, and the original does not hide while it is previewed in another list - the stylesheet is missing.
- An item cannot be dropped into another list - both lists need the same
GroupandTItem; the source'sPullmust not beNone; the target must havePut, not beDisabledor full, be mutable, and not already hold an equal item. - An empty list cannot be dropped into - it has no height. Give it a
min-heightor some padding. @bind-Itemsdoes not compile - declare the field asIList<TItem>.