State lifecycle
Undo & redo
In-app history over the application state - or the part of it the user is editing - independent of the browser extension.
Setup
Register it once. <BlexProvider> calls Start() for you -
deliberately after rehydration, so the baseline that undo ultimately returns to is
the state the user actually loaded, not the pre-hydration defaults.
builder.Services.AddBitBlexHistory(); // default: 100 entries
builder.Services.AddBitBlexHistory(maxEntries: 50);
// Covering only part of the app - see "Scoping history" below:
builder.Services.AddBitBlexHistory(scope: s => s is not SessionStore);
Registration
| Call | Description |
|---|---|
AddBitBlexHistory(int maxEntries = 100, ServiceLifetime lifetime = Scoped, filter?, groupBy?) |
One history over every store. <BlexProvider> starts it once rehydration finishes. The lifetime must match AddBitBlexServices'. |
AddBitBlexHistory(Func<IBlexStore, bool> scope, int maxEntries = 100, lifetime, filter?, groupBy?) |
The same, covering only the stores the scope admits. See Scoping history. |
AddBitBlexHistory<TStore>(int maxEntries = 100, lifetime, filter?, groupBy?) |
A BlexHistory<TStore> beside (or instead of) the app-wide one, covering every instance of one store type. Starts recording when it is first resolved. |
builder.AddBitBlexHistory(...) |
Native .NET MAUI: the same three, on MauiAppBuilder, as singletons. See .NET MAUI. |
@inject BlexHistory History
<button @onclick="History.Undo" disabled="@(!History.CanUndo)">Undo</button>
<button @onclick="History.Redo" disabled="@(!History.CanRedo)">Redo</button>
History snapshots the whole state tree, so a single Undo steps back through whichever store changed last - counter or contacts.
counter Count = loading
contacts 4 contacts
Interleave the two: increment, add a contact, increment again - then undo three times and watch each store roll back in turn.
Jumping several steps at once
Undo() and Redo() are the one-step cases of Jump(n):
negative walks back, positive walks forward. The intermediate states are never applied - the
stacks are walked first and only the destination is restored, so a ten-step undo costs one
render, one storage write and one Changed raise instead of ten of each.
UndoLabels and RedoLabels name the steps in navigation order, which
is what a history panel renders; JumpToPast / JumpToFuture address
them the way redux-undo does.
History.Jump(-3); // undo three steps, applying only the destination
History.Jump(2); // redo two
History.JumpToPast(0); // the oldest state still retained
History.JumpToFuture(0); // the same state Redo() would reach
// Labels in navigation order, for a history panel:
foreach (var label in History.UndoLabels) // "counter/Increment", "contacts/Add", ...
Console.WriteLine(label);
Pick any point on either stack and land on it directly. Make a few changes below first, then step back through them.
Undo stack 0
Nothing to undo yet.
Redo stack 0
Nothing to redo yet.
Grouping keystrokes into one step
A filter removes an action from the stack entirely. Grouping keeps it but folds it
into the step already open, so a burst of related actions - every keystroke in one field,
every frame of one drag - costs a single undo. Return the same non-null key for
actions that belong together, and null for anything that deserves its own step.
// Every keystroke in one field is one undo step; a different field starts a new one.
builder.Services.AddBitBlexHistory(
groupBy: ctx => ctx.ActionName.StartsWith("Set ") ? ctx.QualifiedName : null);
// Group a whole drag by the store that is churning, regardless of action name:
builder.Services.AddBitBlexHistory(
groupBy: ctx => ctx.Store.Name == "canvas" ? "drag" : null);
Only consecutive actions merge: a differently-keyed action, an ungrouped one, a
Checkpoint, an undo or a redo all close the open group, so the next action
starts a fresh step. That is what stops a step the user has already stepped away from from
quietly absorbing new work.
// groupBy: ctx => ctx.ActionName.StartsWith("Set ") ? ctx.QualifiedName : null
store.Title = "h"; // opens a step
store.Title = "he"; // merges
store.Title = "hel"; // merges
store.Publish(); // its own step (and closes the group)
store.Title = "hello"; // opens a NEW step
// Three steps, not five:
History.Undo(); // -> "hel", still published
History.Undo(); // -> "hel", unpublished
History.Undo(); // -> the title before the first keystroke
This page keeps another history of its own over the counter, grouping direct assignments by what they assign. Press Count += 1 several times: one step. Step += 1 is a different key, so it opens a step of its own; Increment is ungrouped, and closes whatever group was open. Then walk the stack back.
Filter when the action should never be a destination (telemetry, cursor position). Group when a burst of actions is one edit to the user. Checkpoint when only your component knows where the boundary is - a field losing focus, a wizard step completing. They compose: group the keystrokes, checkpoint on blur.
API
BlexHistory
| Member | Description |
|---|---|
new BlexHistory(manager, maxEntries = 100, filter?, groupBy?) |
A history over every store of a manager, outside DI. Call Start(); dispose it when done. |
new BlexHistory(manager, scope, maxEntries = 100, filter?, groupBy?) |
One over the stores scope admits - what each demo on this page builds for itself. |
void Start() |
Captures the baseline and begins recording. Idempotent. Called by <BlexProvider> after rehydration. |
void Undo() |
Restores the previous state. No-op when CanUndo is false. Shorthand for Jump(-1). |
void Redo() |
Re-applies the most recently undone state. No-op when CanRedo is false. Shorthand for Jump(1). |
void Jump(int steps) |
Moves several steps in one restore - negative undoes, positive redoes. Clamped to what the stacks hold; intermediate states are never applied. |
void JumpToPast(int index) |
Jumps to an undo-stack entry, 0 being the oldest retained state. |
void JumpToFuture(int index) |
Jumps to a redo-stack entry, 0 being the state a single Redo() would reach. |
IReadOnlyList<string?> UndoLabels |
Labels of the available undo steps, nearest first - what a history panel renders. |
IReadOnlyList<string?> RedoLabels |
Labels of the available redo steps, nearest first. Item i is JumpToFuture(i). |
void Checkpoint(string? label = null) |
Commits the current state as an undo step, labelled label (default "Checkpoint"). Pairs with a filter: the filter keeps noise out, this marks the boundaries. A checkpoint on unchanged state adds nothing. |
void Clear() |
Drops both stacks and takes the current state as the new baseline. |
bool CanUndo / CanRedo |
Whether there is anything to step to. Bind to a button's disabled. |
int UndoCount / RedoCount |
Stack depths. |
string? NextUndoLabel |
Qualified name of the action Undo() would revert, or null. |
string? NextRedoLabel |
Qualified name of the action Redo() would re-apply, or null. |
int MaxEntries |
Retention cap, set at construction. Default 100. |
bool IsScoped |
Whether the history covers only some stores. |
bool Covers(IBlexStore) |
Whether that store is one the history records and restores. Always true without a scope. |
event Action? Changed |
Raised whenever availability changes - bind button state to it. |
void Dispose() |
Detaches from the manager and stops recording. |
How it works
Start()captures the current global state as the baseline and subscribes to the manager.- After each action, the previous snapshot is pushed onto the undo stack and the new one becomes the present. The redo stack is cleared, because you have branched away from it.
Undo()pushes the present onto the redo stack, pops the undo stack and restores that snapshot the wayRestoreGlobalStatedoes.- Restoring does not record an action, so stepping backwards never pollutes the history you are stepping through.
A snapshot covers every store the history does, but it is taken per store and shared: an action
re-serializes only the stores it changed, and each step refers to the other stores' slices
instead of copying them. Undo and redo work the same way: they restore, notify and persist only the
stores whose state differs from the step they land on. MaxEntries caps how many steps are retained - older ones
are discarded from the bottom of the stack. The default is 100.
Labels
Each entry remembers the qualified name of the action that produced it, so a button can say what it is about to undo rather than just "Undo".
<button @onclick="History.Undo" disabled="@(!History.CanUndo)">
Undo @History.NextUndoLabel @* e.g. "Undo counter/Increment" *@
</button>
If something else changes the state without an action - a DevTools time-travel jump, a
manual RestoreGlobalState, persistence hydration, a change from another tab,
another history's undo - history refreshes its present snapshot so the next undo diffs from
what the user can actually see, rather than from a stale pre-jump state. A restore that
changed nothing the history covers is ignored, so it keeps its labels.
Undo and redo never spend a click on a step that would change nothing in view: one that another history has already undone, or one recorded for a store that has since left the manager, is passed over, and the button names the step it will actually revert.
A restore raises StoreRestored for each store it moves, and the persistor
writes each persisted one back in response. So undoing and then reloading the page keeps
the undone state - the reload cannot resurrect what you just stepped away from.
Choosing what earns an undo step
By default every action becomes its own step. That is rarely what a user means by "undo" once
a text box is involved: typing "hello" into a @bind-ed property records five
actions, so undo walks back one letter at a time. Pass a filter - a predicate over
the action context - to decide which actions get their own step. It is the same idea as
redux-undo's filter.
// Direct property assignments record as "Set X" -- typically one per keystroke.
// Skip them so undo steps between deliberate actions instead.
builder.Services.AddBitBlexHistory(
maxEntries: 100,
filter: ctx => !ctx.ActionName.StartsWith("Set "));
// Or exempt a whole store whose churn is noise (telemetry, live cursor position):
builder.Services.AddBitBlexHistory(filter: ctx => ctx.Store.Name != "presence");
A filtered action still applies, and it still moves the present forward. It simply does not become a separate step, so the next undo reverts it together with the recorded action before it. That is what keeps undo landing on states the user recognizes: never on a half-typed word, and never on a state they never saw.
// filter: ctx => ctx.ActionName != "Add"
counter.Increment(); // recorded -> 1
counter.Add(10); // filtered -> 11 (applies, but no new step)
counter.Increment(); // recorded -> 12
History.Undo(); // -> 11, not 1: the step holds the post-filter state
If the predicate throws, the action is recorded anyway and the exception is reported
through OnError with source "history". Keeping an extra undo
step is a smaller failure than silently losing one the user is about to reach for.
Marking your own boundaries
A filter alone leaves the filtered work with no boundary of its own, so the next recorded
action swallows it: undo would discard the whole typed edit and the button press
after it. Checkpoint(label) commits the current state as an undo step on demand
- call it where the user would expect a boundary: a pause in typing, a field losing focus, a
wizard step completing.
// Registration: keystroke-level writes never get their own step...
builder.Services.AddBitBlexHistory(filter: ctx => !ctx.ActionName.StartsWith("Set "));
// ...so the component marks the boundaries instead.
@inject BlexHistory History
private void OnBlur() => History.Checkpoint("Edit title");
// Or on a pause in typing, via a debounced effect:
[BlexEffect(DebounceMilliseconds = 500)]
private async Task OnSettled()
{
await Task.CompletedTask;
_history.Checkpoint("Edit");
}
Consecutive checkpoints with nothing in between collapse into one, so a "user stopped typing" timer can call it freely without growing the stack while the state sits still.
This page keeps a history of its own over the counter, with direct assignments (Set Count) filtered out. Assign a few times: no step appears. Checkpoint commits them as one step, and a second Checkpoint adds nothing. Increment is a named action, so it is a step of its own.
Scoping history to part of the app
By default BlexHistory covers every store, which is what the demos above show - and
rarely what a user means. Undoing a text edit restores the whole tree, so it can also
sign the user out, switch the theme back, or empty a cart that a background refresh just filled.
The undo stack the user has in mind is about the document they are editing.
Give the history a scope: a predicate over stores. Only the actions of the stores it admits become undo steps, and an undo or redo restores only their slices - every other store is never touched. The predicate is consulted on every action and snapshot, so stores registered later (a lazily loaded feature, a scoped instance) are covered as soon as they match.
// Everything except the stores an undo must never revert:
builder.Services.AddBitBlexHistory(scope: s => s is not SessionStore and not ThemeStore);
// Only the editor:
builder.Services.AddBitBlexHistory(scope: s => s is EditorStore, maxEntries: 200);
// Without DI:
var history = new BlexHistory(manager, scope: s => s.Name.StartsWith("editor"));
history.Start();
// scope: s => s is EditorStore
editor.Rename("Draft 2"); // an undo step
session.SignIn("ada"); // out of scope: no step, and never reverted
History.Undo(); // -> "Draft 1", and still signed in as ada
This site registers an app-wide history and a BlexHistory<CounterStore>. Increment, add a contact, increment again - then compare what each Undo reverts.
BlexHistory 0 steps
BlexHistory<CounterStore> 0 steps
The counter's undo never touches the contacts, however the two were interleaved.
For an undo stack per editor, BlexHistory<TStore> covers every instance of
one store type, scoped instances included. It can sit beside the application-wide history;
inject it by its type. The DI registration starts recording as soon as it is resolved, since a
component typically resolves it after the stores exist - and if that happens before hydration,
hydration is a restore, and the history moves its baseline to the loaded state.
// Program.cs - beside, or instead of, the app-wide AddBitBlexHistory():
builder.Services.AddBitBlexHistory<EditorStore>(filter: ctx => !ctx.ActionName.StartsWith("Set "));
@* Editor.razor *@
@inject BlexHistory<EditorStore> History
<button @onclick="History.Undo" disabled="@(!History.CanUndo)">Undo @History.NextUndoLabel</button>
A predicate that throws is reported through OnError with source
"history" and treated as "not covered". That fails closed on purpose: a store
the history cannot decide about is left alone rather than reverted.
Every step holds a serialized copy of each store that changed in it (unchanged stores are
shared between steps). A store holding a large collection that changes on every action still
costs a copy per step: lower maxEntries, or scope the history to the stores
that need it.