Drafts, autosave & unsaved changes
A long form owes its user "you were halfway through this - carry on?". BormAutosave writes a
draft a moment after the typing stops, BormDraft.Restore puts it back as unsaved changes, and
BormUnsavedChangesGuard asks before the user walks away from them. Where a draft is kept is
the application's choice; this page keeps it in the browser's local storage.
Nothing saved yet.
The draft in this browser's storage
No draft saved yet.
View source
@page "/drafts"
@inject IJSRuntime JS
<BormView State="_state" OnValidSubmit="HandleSubmit" SubmitText="Apply" ShowResetButton="true" />
<BormAutosave State="_state" OnSave="SaveDraftAsync" OnDiscard="DiscardDraftAsync" DelayMilliseconds="800" />
<BormUnsavedChangesGuard State="_state" />
@code {
private const string DraftKey = "membership-application";
private readonly MembershipApplication _model = new();
private BormState _state = default!;
protected override void OnInitialized()
{
var schema = BormBuilder.For<MembershipApplication>()
.Title("Membership application")
.Version("1") // recorded in every draft
.Field(x => x.FullName, f => f.Required().UpdateOnInput(300))
.Field(x => x.Email, f => f.Required().Email().UpdateOnInput(300))
.Field(x => x.Tier, f => f.AsRadio()
.Options(("standard", "Standard"), ("supporter", "Supporter"), ("patron", "Patron")))
.Field(x => x.Motivation, f => f.AsTextArea(5).Required().MinLength(40).MaxLength(2000).CharacterCount().UpdateOnInput(300))
.Field(x => x.Iban, f => f.Sensitive().UpdateOnInput(300)) // never written to a draft
.Field(x => x.Password, f => f.AsPassword().Required().MinLength(10).UpdateOnInput(300))
.Build();
_state = new BormState(schema, new BormModelDataAccessor(_model));
}
// Storage is the browser's, so the draft is looked for once the page runs there.
protected override async Task OnAfterRenderAsync(bool firstRender)
{
if (!firstRender) return;
if (await JS.InvokeAsync<string?>("localStorage.getItem", DraftKey) is { } json)
{
BormDraft.Restore(_state, json); // back as unsaved changes
StateHasChanged();
}
}
private async Task SaveDraftAsync(string json) => await JS.InvokeVoidAsync("localStorage.setItem", DraftKey, json);
// Reset, or every change undone: a draft would only bring back what the user gave up.
private async Task DiscardDraftAsync() => await JS.InvokeVoidAsync("localStorage.removeItem", DraftKey);
private async Task HandleSubmit(BormState state)
{
// ... send the application ...
await JS.InvokeVoidAsync("localStorage.removeItem", DraftKey); // a submitted form has no draft
state.AcceptChanges(); // and nothing left to warn about
}
public void Dispose() => _state.Dispose();
}What a draft is
- It holds every value the schema binds to, one per path (
Lines[2].Quantity), each repeater's row count, the wizard step or open tab, the form's version and when it was saved. Types come back as they went - enums, dates, a timestamp's offset, a multi-select's list. Computed values are computed again. - It never holds files - a browser file cannot outlive the page that chose it - or sensitive values:
passwords, and fields marked
Sensitive()(x-sensitive), unlessBormDraftOptions.IncludeSensitiveasks.ExcludeHiddenalso leaves out the answers of branches the user hid. - Restoring writes the answers as unsaved changes on top of what the form opened with, so
IsFormDirtyand the guard stay meaningful andReset()takes them away. Change handlers stay silent, and a cascading select keeps the answer it is given.BormDraft.Restorereturns what happened:Restored,SavedAt,Version, and theSkippedpaths the form can no longer hold - shown in the status line above - rather than errors the user never made. - Versions: a draft records
BormDefinition.Version(.Version("1")here,x-versionin JSON Schema). When a newer form meets an older draft,Migratebrings it up to date first:
BormDraft.Restore(state, json, new BormDraftOptions { Migrate = m => { if (m.FromVersion == "1") m.Rename("Phone", "Contact.Phone").Remove("Fax"); } });
BormAutosave saves only while there are unsaved changes, a moment after the last one
(DelayMilliseconds), and once more as the page goes away if a save was waiting; a draft just restored is
not saved again. A text box commits when it is left, so fields whose half-typed answers a draft should keep say
UpdateOnInput(300), as these do. BormUnsavedChangesGuard gives an external navigation the
browser's own "leave site?" prompt, and asks an in-app one through OnConfirm - a dialog of yours - or
the browser's confirm(). A draft is personal data: keep it where the user's other data is kept.