Skip to content

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.

Fill in a few answers, wait a second, and reload the page: the browser asks first - that is the guard - and then the answers come back. The IBAN and the password never do. They are sensitive, so no draft holds them, which the draft below shows. Submitting clears the draft, and leaves nothing for the guard to ask about - and so does Reset, which puts the form back where it started.
Live form
Membership application

Membership

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), unless BormDraftOptions.IncludeSensitive asks. ExcludeHidden also 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 IsFormDirty and the guard stay meaningful and Reset() takes them away. Change handlers stay silent, and a cascading select keeps the answer it is given. BormDraft.Restore returns what happened: Restored, SavedAt, Version, and the Skipped paths 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-version in JSON Schema). When a newer form meets an older draft, Migrate brings 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.

An unhandled error has occurred. Reload 🗙