Pages and navigation

On this page

A Window changes pages the way any MVVM application does: a ViewModel property holds the current page's ViewModel, and the View renders whatever that property holds. This guide starts with that plain property, which the template uses, then moves to navigation regions, which add Back history, guards against leaving with unsaved changes and per-visit pages. The examples use ReactiveUI, the default; CommunityToolkit.Mvvm follows the same model with its own commands. Words such as region and entry are defined in the glossary.

A page property #

The template's Window ViewModel keeps its page in Main, typed as an interface that every page implements. A command assigns another page:

public WorkspaceViewModel(WelcomeViewModel welcome, CounterViewModel counter)
{
    _main = welcome;
    ShowWelcomeCommand = ReactiveCommand.Create(() => { Main = welcome; });
    ShowCounterCommand = ReactiveCommand.Create(() => { Main = counter; });
}

public IWorkspacePage Main
{
    get => _main;
    private set => this.RaiseAndSetIfChanged(ref _main, value);
}

A ViewModel-typed property is ViewModel content. The frontend receives a typed reference to the page, not its state, and a ViewOutlet renders the View registered for its kind. The registry must cover every page, which the TypeScript compiler checks:

const pages = { counter: CounterPage, welcome: WelcomePage } satisfies ViewRegistry<WorkspaceState["main"]>;
...
<ViewOutlet content={state?.main} registry={pages} fallback={<p>Connecting to the Window…</p>} />

Each page View connects to its own ViewModel. When Main changes, the outlet unmounts the old View and mounts the new one; the ViewModels keep their state, so returning to the counter shows the same count. Keep a page property while the pages are fixed and switching between them is all you need.

A NavigationRegion<TContent> from Runic.Navigation is a page property with history. It adds what a page property leaves to you:

  • Back history, with CanGoBack, BackAsync and a ready-made Back command.
  • Pages created for one visit and disposed when you leave them.
  • Departure guards that can refuse to leave a page, for example while it has unsaved changes, also when the user closes the Window.
  • Typed results: a refused, superseded or failed navigation is a value, not an exception, and a page can return a value to the code that opened it.

The Runic.Navigation guide is the reference for every operation, hook and ownership rule, and the ReactiveUI walkthrough covers the adapter.

The entry context as a constructor parameter, INavigationAware, WhenNavigatedTo, the result commands, ReactiveLeaveConfirmation and GuardClose are new in SDK 0.7.0-preview.7. This guide follows 0.12.0.

Coming from ReactiveUI navigation #

Regions replace ReactiveUI's RoutingState rather than wrap it: pages need no IScreen or IRoutableViewModel, only an interface of your own that the region's pages implement. If you know host-based ReactiveUI navigation from CrissCross, the shape is familiar: you navigate to a ViewModel type, the container builds it, and you go back, ask whether you can, or veto leaving. The differences are that a region is a plain ViewModel property rather than a View host, that each request returns a result you can inspect, and that the navigator, not the View, owns the pages it created.

Task With a region
Show a page built by the container await Main.PushAsync<DocumentViewModel>()
Pass the page an input PushAsync<NoteDetailViewModel, int>(id) and INavigationInitialize<int>
Go back Main.CreateBackCommand(), or await Main.BackAsync()
Enable a Back button Main.WhenCanGoBackChanged(), included in the Back command
Show a busy state Main.WhenIsTransitioningChanged()
Bind a history list or breadcrumb Main.WhenHistoryChanged(), since SDK 0.11.0
Run code each time a page becomes current entry.WhenNavigatedTo(...), or INavigationAware
Refuse to leave a page INavigationDepartureGuard with ReactiveLeaveConfirmation
Return a value to the caller PushForResult<TPage, TResult>() and entry.CreateCompleteCommand()
Ask before the Window closes GuardClose = true on the RunicWindow<T>

An app that keeps an existing RoutingState exposes a content property of its own that follows RoutingState.CurrentViewModel, without guards, results or owned pages.

Set up #

Add the ReactiveUI adapter, which brings Runic.Navigation:

dotnet add package Runic.Navigation.ReactiveUI --version <VERSION>

An app on ReactiveUI's System.Reactive distribution adds Runic.Navigation.ReactiveUI.Reactive instead. Reference one of the two: since SDK 0.11.0, a project whose references contain both gets build warning RUNICNAV002.

Register the navigator with the Window's other services. AddRunicNavigation() adds one navigator per Window scope, on the model context that AddRunicReactiveModelContext() registers. The Reactive Notes example, which this guide follows, registers:

// A window scope owns one execution lane for the whole reactive graph, and
// ReactiveUI commands deliver their notifications on it without a scheduler.
services.AddRunicReactiveModelContext();
// One navigator per window scope, on that model context. It constructs each
// DocumentViewModel from the window's services and owns it.
services.AddRunicNavigation();
services.AddScoped<HomeViewModel>();
services.AddScoped<EditorViewModel>();
services.AddScoped<PreviewViewModel>();
services.AddScoped<ShellViewModel>();

No command in this guide takes a scheduler: the model context is ReactiveUI's main-thread scheduler. In WPF the dispatcher is, once ReactiveUI's WPF platform is built; the WPF ReactiveUI example registers the navigator with AddRunicWpfNavigation():

// ReactiveUI's WPF platform, once per process: commands deliver on the dispatcher, and Views activate.
static App() => RxAppBuilder.CreateReactiveUIBuilder().WithWpf().BuildApp();
// ...
public static IServiceCollection AddNotes(IServiceCollection services) => services
    .AddRunicWpfNavigation(options => options.UseViewNamingConvention()) // NotesListViewModel -> NotesListView
    .AddSingleton<NoteStore>()
    .AddSingleton<AppRegions>();

With ReactiveUI #

A region in the shell #

Create the region in the Window's ViewModel with the injected RunicNavigator, and expose it as a get-only property. The region starts on a borrowed home page; the Window's scope owns that ViewModel, so the navigator never disposes it. The adapter in Runic.Navigation.ReactiveUI turns the region's state into observables and commands:

public ShellViewModel(RunicNavigator navigator, HomeViewModel home, EditorViewModel editor)
{
    // ...
    Main = navigator.CreateRegion<IMainPage>(this, NavigationTarget.Borrow<IMainPage>(home));
    // Back runs the document's leave guard; it is enabled while Main has history.
    OpenHomeCommand = Main.CreateBackCommand();
    OpenDocumentCommand = ReactiveCommand.CreateFromTask(OpenDocumentAsync,
        Main.WhenCurrentChanged().Select(page => page is HomeViewModel));
    // ...
}

public NavigationRegion<IMainPage> Main { get; }
// ...
public ReactiveCommand<RxVoid, NavigationOutcome> OpenHomeCommand { get; }
public ReactiveCommand<RxVoid, RxVoid> OpenDocumentCommand { get; }

CreateBackCommand() can execute while the region has history and no transition is running. Its output is a NavigationOutcome, the kind of result without any .NET content, so the frontend can read it.

The commands need no ThrownExceptions subscription. The generated Bridge observes each bridged command and logs an unexpected exception once, as ReactiveCommandFailed (event 1042) through the Window's logger factory. A declared failure reaches the frontend instead. Typed failures has the details.

They also need no disposal. Like any ReactiveUI subscription, dispose a command only when its canExecute observes an object that outlives the ViewModel. These observe Main, the shell's own region.

A root page that navigates its region #

When the root page pushes into its own region, as a list pushes its detail page, it needs the service that holds the region. That service can't create the region with the page as its initial target, because building the page would need the service again. Create the region empty in the service, and start it in the Window's ViewModel, where both exist:

public sealed class AppNavigation // registered per window scope
{
    public AppNavigation(RunicNavigator navigator) => Main = navigator.CreateRegion<IPage>(this);

    public NavigationRegion<IPage> Main { get; }
}

public sealed class ListViewModel(AppNavigation navigation) : IPage { /* pushes into navigation.Main */ }

public sealed class ShellViewModel
{
    public ShellViewModel(AppNavigation navigation, ListViewModel list)
    {
        Main = navigation.Main;
        Main.Start(NavigationTarget.Borrow<IPage>(list)); // or NavigationTarget.Create<ListViewModel>()
    }

    public NavigationRegion<IPage> Main { get; }
}

NavigationTarget.Create<ListViewModel>() instead builds the list from the Window's services, and the region owns it.

Start commits the root page before it returns, like an initial target of CreateRegion: the page's OnNavigatedTo and the region's change notifications run on the calling thread, and Main.Current is the list when OpenWindowAsync returns. If the page can't be created, Start throws, so OpenWindowAsync fails instead of opening an empty Window. Start is allowed once, before any other navigation of the region; use ResetAsync after that. Don't use _ = Main.ResetAsync(...) in the constructor instead: its failure is only logged, and the region stays empty until a later model turn. Start is new in SDK 0.7.0-preview.8. A CommunityToolkit.Mvvm or ReactiveUI shell calls it the same way.

Navigate in an ordinary ReactiveCommand. PushAsync<TPage>() asks the navigator to build the page from the Window's services; the new entry owns it, and the navigator disposes it when the entry retires. A page that needs an input receives it in INavigationInitialize<TInput>, as the WPF example's note page does:

// The ViewModel type and its typed input are the parameter contract; no string keys.
OpenCommand = ReactiveCommand.CreateFromTask(async token =>
    { await regions.Main.PushAsync<NoteDetailViewModel, int>(Selected!.Id, cancellationToken: token); }, hasSelection);
// Runs once, before the page is shown. A retained page keeps its note and edits.
public ValueTask InitializeAsync(NavigationEntryContext entry, int id, CancellationToken cancellationToken)
{
    _note = _store.Get(id);
    Title = _note.Title;
    return ValueTask.CompletedTask;
}

Other operations replace the current page, go back to an earlier entry, or reset the history. NavigationTarget chooses who owns the page:

  • NavigationTarget.Borrow<TContent>(model) presents a ViewModel that someone else owns, such as a Window-scoped page that keeps its state across visits.
  • NavigationTarget.Own<TContent>(model) hands an existing ViewModel to the entry.
  • NavigationTarget.Create<TContent>(factory) builds the ViewModel during the navigation and hands it to the entry. The factory receives the Window's services and the new entry's context.

Every request returns a NavigationResult<TContent>: Committed, Rejected with a reason such as Guard or NoHistory, Superseded by a later request, or Failed with the exception. Decide in the ViewModel what each one means; a completed command task does not mean the page changed. After the await, the command is back on the Window's model context, so it sets state directly. ViewModel state and threads explains why.

Busy state and history #

Since SDK 0.8.0-preview.5, a region has IsBusy from a request's admission until its task completes, including the retirement of the entries it departed. IsTransitioning ends earlier, in the commit turn. Bind a progress indicator to Main.WhenIsBusyChanged(). Since SDK 0.10.0, RunicNavigator.IsBusy says whether the navigator's WhenIdleAsync() would wait now. It is a snapshot without change notification, so don't bind to it.

Two operations change the history without a new page:

  • BackToAsync(entryId) retires every entry above that entry, which resumes.
  • ClearHistoryAsync() retires the retained entries; the current entry stays.

Both return a NavigationResult<TContent> like the other operations. Since SDK 0.10.0, the non-generic NavigationRegion has them too, returning a NavigationResult<object>, for hosts typed NavigationRegion, such as the WPF NavigationHost.Region. Since SDK 0.11.0, WhenHistoryChanged() emits the retained entries below the current one, bottom to top; a breadcrumb binds to it and goes back with BackToAsync(entry.Id).

The page and its entry #

Each visit is an entry with a NavigationEntryContext: its id, its state, and the operations it performs on itself. A page that the navigator constructs takes it as a constructor parameter, next to its services:

public sealed class DocumentViewModel : ReactiveObject, IMainPage, INavigationDepartureGuard
{
    // ...
    public DocumentViewModel(NavigationEntryContext entry, RunicNavigator navigator, EditorViewModel editor,
        PreviewViewModel preview)
  • The navigator passes the context to the content it constructs: with PushAsync<TPage>(), ReplaceAsync<TPage>(), ResetAsync<TPage>(), PushForResult<TPage, TResult>(), and as the second argument of a NavigationTarget.Create factory. The container never resolves it, so a service that asks for one fails to resolve; pass it on from the page.
  • The page is constructed while its entry is still pending. Keep the context for commands and subscriptions; don't navigate from the constructor.
  • A page you create yourself and pass with Own or Borrow exists before its entry, so it receives the context in INavigationInitialize.InitializeAsync.

entry.WhenNavigatedTo runs each time the entry becomes current: when it is first shown and after every Back to it. Its second argument is a scope that ends when the entry stops being current, so per-visit subscriptions go there. WhenNavigatedTo itself ends when the entry retires:

// Per visit, not per mounted View: follow the window-scoped draft while this entry
// is current. The visit scope ends that subscription when the entry is left.
entry.WhenNavigatedTo((_, visit) => editor.WhenAnyValue(model => model.IsDirty)
    .Subscribe(dirty => Status = dirty ? "Unsaved changes" : "No unsaved changes")
    .DisposeWith(visit));

The WPF example's list refreshes itself whenever the user returns to it:

// Each time the list becomes current again, for example after Back from a note. Ends when the entry retires.
entry.WhenNavigatedTo((_, _) => Notes.ReplaceWith(store.All));

WhenNavigatedFrom() emits each departure. Without the adapter, a page implements INavigationAware, whose OnNavigatedTo and OnNavigatedFrom the navigator calls at the same moments, in the turn that commits the navigation. ReactiveUI's WhenActivated follows a mounted View instead, not the entry: a page that another page covers stays alive with its state while its View is unmounted. Put per-View subscriptions in WhenActivated and per-visit ones in WhenNavigatedTo.

Guard against leaving #

A page that must not be left silently implements INavigationDepartureGuard. The navigator asks it before every exit: Back, a push from code, a parent region leaving and a guarded Window close. ReactiveLeaveConfirmation.WithInteraction implements the common case, asking through a ReactiveUI Interaction when there are unsaved changes:

// Leaving with unsaved edits asks through ConfirmLeave. The edits are reverted
// only when the departure commits; a No, or a superseded departure, keeps them.
_leave = ReactiveLeaveConfirmation.WithInteraction(ConfirmLeave,
    () => new DiscardNoteRequest(editor.Title, editor.Body.Length), () => editor.IsDirty, editor.RevertChanges);
// The web View answers for its Close and the shell's Back. ReactiveUI asks the latest handler
// first, so this fallback answers only when no View is mounted or .NET code starts the departure:
// keep the edits rather than fail it.
ConfirmLeave.RegisterHandler(context => context.SetOutput(false));
// ...
public ValueTask<bool> CanDepartAsync(NavigationDeparture departure, CancellationToken cancellationToken) =>
    _leave.CanDepartAsync(departure, cancellationToken);

A web View answers the interaction with its generated client while it is mounted, for a departure that its own window starts: the page's Close, the shell's Back, or a guarded Window close:

// The leave guard asks here when this window leaves the document with unsaved
// edits: its Close or the shell's Home (Back).
// Answering false keeps the document and its edits.
const removeLeaveHandler = view.interactions.confirmLeave.handle(async (request, { signal }) => {
  if (signal.aborted) throw signal.reason;
  return window.confirm(`Close “${request.title}” and lose its unsaved changes?`);
});

The View registers its handler when it mounts. A departure during the page's first render, such as a Window close just as the page opened, therefore gets the ViewModel's .NET fallback above, which keeps the edits.

A WPF View answers in WhenActivated. Its XAML sets ViewModel="{Binding}", so the ReactiveUI View receives the page that the region presents:

// Answers the ViewModel's leave confirmation while this View is shown.
this.WhenActivated((MultipleDisposable disposables) => ViewModel!.ConfirmDiscard.RegisterHandler(context => context.SetOutput(
    MessageBox.Show(context.Input, "Notes", MessageBoxButton.OKCancel) == MessageBoxResult.OK)).DisposeWith(disposables));

The guard fails closed:

  • Without unsaved changes it doesn't ask, and a push that keeps the page in the history leaves it without asking.
  • With no handler that answers, ReactiveUI's UnhandledInteractionException fails the departure: the result is Failed, the navigator logs event 1060, and the page stays. So does a handler that throws, and so does a question whose View unmounts or disconnects before it answers.
  • The browser is asked only from the page's own window, and never from another window or browser connection. A command of any View in that window, such as the shell's Back, asks the page's View on the connection that invoked it. A guarded Window close asks the page's View when it is the only mounted View with that handler. Navigation that .NET code starts, such as from a timer, never reaches the browser; register a .NET fallback handler, as the example does, to give it an answer. ReactiveUI asks the latest handler first: a mounted web View answers before a fallback registered in the constructor, and a WPF View's WhenActivated handler answers before both.
  • A superseded or cancelled departure ends at once; the browser handler's signal aborts, and a late answer is ignored. The discard runs only when the departure commits.

A question for the whole region rather than one page, such as unsaved work anywhere in the Window, is a region guard that you register with Main.AddDepartureGuard(guard) or navigator.AddDepartureGuard(guard). Since SDK 0.11.0, ReactiveNavigationRegionGuard.WithInteraction(interaction, prompt, hasUnsavedChanges, discard) creates one that asks through an Interaction, with the same fail-closed rules.

Since SDK 0.14.0, RunicModelContext schedules navigator hooks, as WPF's DispatcherModelContext already did: both implement IRunicModelHookScheduler. Factories, departure guards, initialize, resume and arrival hooks, and the disposal of owned content, each run in the model context as an operation of their own: a hook starts in a turn of its own, never inline in the caller or inside a commit turn, and its awaits resume in later turns. No turn is held across a hook's awaits, so commits and Bridge replies run between them. A hook therefore sets its page's state directly, before and after await, like a command body; that is why the WPF note page's InitializeAsync above sets Title directly. Don't block in a hook with Wait(), Thread.Sleep or synchronous I/O, because that blocks the model context; await instead. Under SDK 0.13.0 these hooks ran on the thread pool with RunicModelContext, so a Desktop, served or CS-WebUI application without WPF had to commit their writes with IRunicModelContext.InvokeAsync, which still works and runs inline; a wrapper that implemented IRunicModelHookScheduler to post hooks as turns can be removed. A decorator that wraps a scheduling context must implement and forward the interface, or hooks run outside turns again; see threading. Content that a factory returned for a target the navigator rejected is disposed asynchronously, after WhenIdleAsync.

Return a result #

A caller that needs to know how a visit ended pushes for a result. PushForResult returns a request with two tasks: Transition settles when the page is shown, and Completion when the entry ends. The Notes shell awaits the completion outside its command, so the command ends once the document is shown:

private async Task OpenDocumentAsync()
{
    var request = Main.PushForResult<DocumentViewModel, string>();
    if ((await request.Transition).IsCommitted) _ = ShowResultAsync(request.Completion);
}

// Completion never faults: it ends Dismissed on every path but Save and close,
// including a closing window. The continuation resumes on the model context.
private async Task ShowResultAsync(Task<NavigationCompletion<string>> completion) =>
    _home.LastResult = await completion is NavigationCompletion<string>.Completed(var title)
        ? $"Saved and closed {title}"
        : "Closed the document.";

The page ends its entry with result commands that the View binds like any other command. CreateCompleteCommand produces the result and goes back, and CreateCloseCommand goes back without one; both run the leave guard, and a veto keeps the page and the request open:

// Result commands end the entry: Save and close completes the request with the
// title; Close goes back, asking first when there are unsaved edits.
SaveAndCloseCommand = entry.CreateCompleteCommand(async token =>
{
    await editor.SaveAsync(token);
    return editor.Title;
});
CloseCommand = entry.CreateCloseCommand();

The entry disposes its result commands when it retires, so the page doesn't.

A confirm dialog in a dialog region answers the same way, with CreateDismissCommand for its No, which ends the request at once:

public sealed class ConfirmViewModel(NavigationEntryContext entry, string message) : ReactiveObject
{
    public string Message { get; } = message;
    public ReactiveCommand<RxVoid, NavigationOutcome> YesCommand { get; } = entry.CreateCompleteCommand(_ => Task.FromResult(true));
    public ReactiveCommand<RxVoid, NavigationOutcome> NoCommand { get; } = entry.CreateDismissCommand();
}

Its caller waits for the answer inside the command, so it passes the command's token; cancelling the command then also closes the dialog. Don't pass the token from a command that ends when the push commits, as the Notes shell's does, because cancelling it later would close the page. The // [S2] comments mark the example's second comparison scenario:

var answer = await regions.Dialog.PushForResult<bool>(NavigationTarget.Create<ConfirmViewModel>( // [S2]
    (_, dialog) => new ConfirmViewModel(dialog, $"Delete '{note.Title}'?")), cancellationToken: token).Completion; // [S2]
if (answer is NavigationCompletion<bool>.Completed { Value: true }) // [S2]

Completion never faults. It ends Completed with the value, or Dismissed on every other path, including a closing Window. Await it directly; it needs no conversion and no scheduler.

Since SDK 0.15.0, a result entry whose request already ended, because its caller's token was cancelled or it called DismissAsync while another entry covered it, no longer comes back: the Back of the entry above it retires it too and resumes the entry below. Before, the answered dialog was shown again until its CompleteAsync went back.

Queue dialogs #

A region admits a new request by superseding the earlier ones that have not started committing, unless its Admission is RejectWhileBusy, which refuses the new one. Neither suits a dialog region whose prompts are raised independently, such as an error from a background operation while a confirmation is open. Since SDK 0.15.0, NavigationAdmission.Queue stacks them instead:

Dialog = navigator.CreateRegion<IDialogViewModel>(this,
    options: new NavigationRegionOptions { Admission = NavigationAdmission.Queue });

var confirm = Dialog.PushForResult<bool>(NavigationTarget.Create<IDialogViewModel>(...));
// Meanwhile, elsewhere: waits for the confirmation's push, then stacks above it.
var error = Dialog.PushForResult<bool>(NavigationTarget.Create<IDialogViewModel>(...), cancellationToken: token);
  • A queued request waits until the region's earlier requests have ended, in admission order, and supersedes none of them. It waits for their transitions (guards, preparation, commit), never for a dialog's answer, so the second prompt is pushed above the first, and completing it resumes the first.
  • ExpectedCurrent and the history a Back needs are checked when the request starts. The request's token cancels it while it waits: it ends Rejected(Cancelled) and a PushForResult's Completion ends Dismissed.
  • A request admitted with Supersede, such as a Window close's clear, still supersedes queued requests. NavigationSelectionOptions.Admission and NavigationRequestOptions.Admission take Queue too, the latter for one request in a region that otherwise supersedes.
  • In WPF, NavigationDialogHost dismisses a closed dialog with the region's Queue policy, so closing a dialog doesn't supersede one pushed meanwhile.

See queueing requests for every rule.

Guard the Window close #

Disposing a navigator retires its entries without asking their guards, so by default closing the Window loses unsaved edits. To ask the guards first, set GuardClose on the Window, as the SDK's close-guard tests do:

sealed class GuardedWindow : RunicWindow<GuardedShellModel>
{
    public GuardedWindow() => GuardClose = true;
}
  • Before a close that the user starts, the Window calls CanCloseAsync. Its default clears each region its ViewModel exposes, so the departure guards decide, and a guard that refuses or fails keeps the Window open. Override it to add a check, and call the base method to keep the guards.

  • RequestCloseAsync() closes the Window from code as its close button does, and returns false when the guards kept it open. Keep the Window that OpenWindowAsync returned and call it from a ReactiveCommand:

    CloseEditorCommand = ReactiveCommand.CreateFromTask(async token =>
    {
        if (!await _editor.RequestCloseAsync(token)) StatusText = "The editor has unsaved changes.";
    });
    

    A ViewModel closes its own Window, for example from a Quit command, by taking IRunicWindowContext in its constructor and calling its RequestCloseAsync. AddRunicWindowService() registers it per Window, and it is new in SDK 0.7.0-preview.8; see Closing a ViewModel's own Window.

  • The page's web View asks the user, as it does for its Close: the close is the Window's own departure, so the guard's interaction reaches the View mounted in that Window. If the View unmounts during the question, the Window stays open. If the application closes the Window meanwhile (CloseAsync), the question is cancelled and the guard's discard doesn't run. A .NET fallback handler answers only when no View is mounted, which includes a close during the page's first render, before its View has registered its handler.

  • Runic Desktop's embedded window asks. CS-WebUI and a browser window can't keep their window open: the Window opens unguarded and logs warning 1053 WindowCloseGuardUnavailable, and a user close doesn't ask. Save drafts as the user edits where that matters. RequestCloseAsync still asks there.

  • CloseAsync, disposal and a host shutdown don't ask. Since SDK 0.15.0 they tell the page, which then reports its connection as closed, and CloseAsync(timeout) waits for the page's acknowledgement; see wait until the page shows a state.

  • In WPF, set GuardWindowClose="True" on the NavigationHost instead. It also guards a host on an unselected tab. Since SDK 0.11.0, WindowCloseConfirmation.Create and WindowCloseConfirmation.OncePerClose make a region guard that such a close asks once, however many regions it clears.

Render a region #

The frontend sees a region like any page property, except that a region can be empty, so its TypeScript type includes null. Give the ViewOutlet a fallback for that case. Going Back presents the earlier page's reference again, and the outlet mounts a fresh View for its retained ViewModel. Reloading the page or reconnecting never changes the history.

NavigationRequestOptions.RetainView, new in SDK 0.11.0, asks a presentation to keep (true) or rebuild (false) one entry's view while the entry is retained; the entry reports it as NavigationEntry.RetainView. It never changes the entry's lifetime. The WPF NavigationHost reads it in place of its RetainViews. Runic Views pages ignore it, because the frontend owns the DOM.

Tabs that keep their own pages #

Tabs, a navigation rail or a bottom navigation often keep one stack per section, so a tab's pages and drafts stay while another tab is shown. Since SDK 0.12.0, make each tab a region owned by the page, and let a NavigationSelection choose which one is presented:

public sealed class CustomersPage
{
    public CustomersPage(RunicNavigator navigator)
    {
        List = navigator.CreateRegion<IPage>(this, NavigationTarget.Create<CustomerListViewModel>());
        Reports = navigator.CreateRegion<IPage>(this, NavigationTarget.Create<ReportsViewModel>());
        Tabs = navigator.CreateSelection(this, [List, Reports]);
    }

    public NavigationRegion<IPage> List { get; }
    public NavigationRegion<IPage> Reports { get; }
    public NavigationSelection Tabs { get; }
}

var result = await page.Tabs.SelectAsync(page.Reports); // a guarded switch
  • SelectAsync is a transition with NavigationOperation.Select. It asks the current page of the tab left, and of the regions below it, as Retain, so an editor can ask "Save, discard or cancel?" before another tab is shown. A veto, failure, cancellation or supersession keeps the selection. LeaveConfirmation and ReactiveLeaveConfirmation ask on a tab switch only with askOnRetain: true.
  • A committed switch changes no stack: the tab left keeps its pages, and coming back presents the same entry without running its arrival hooks again.
  • Add(region) adds a tab, such as a document tab, and RemoveAsync(region) closes one, asking its pages as Retire. Retiring the page asks every page of every tab, whichever is selected, so own the regions and the selection by a page entry, not by the Window's ViewModel: then a guarded Window close asks every tab.
  • A request whose Requester is a page in a tab that isn't selected is rejected as NotCurrent, so a late operation in a hidden tab doesn't navigate the page the user is looking at.
  • The selection has its own IsTransitioning, IsBusy and WhenIdleAsync. A later SelectAsync supersedes an earlier one, so the last tab chosen wins, unless NavigationSelectionOptions.Admission is RejectWhileBusy or, since SDK 0.15.0, Queue.

A push that covers the page asks only the page, and its tabs keep their pages without being asked. Since SDK 0.15.0, when the shown tab's page should be asked too, for example because it holds unsaved work or a lock, set AskOnParentRetain on the tab regions:

var options = new NavigationRegionOptions { AskOnParentRetain = true };
Customers = navigator.CreateRegion<IPage>(this, NavigationTarget.Create<CustomerListViewModel>(), options);
Orders = navigator.CreateRegion<IPage>(this, NavigationTarget.Create<OrderListViewModel>(), options);
Tabs = navigator.CreateSelection(this, [Customers, Orders]);

A push over the page then asks the current entry of the selected tab, and of the regions below it, as Retain, before the page's own guard. Work that ends what a page shows without navigating, such as switching the signed-in account, asks the page's guards with ConfirmDepartureAsync and does the work in the same model turn:

var result = await page.Customers.ConfirmDepartureAsync(NavigationDepartureKind.Retire,
    onConfirmed: () => session.SwitchAccount(account));
if (result.Outcome.Kind != NavigationOutcomeKind.Committed) return; // a guard said no, or the page changed meanwhile

It asks what that departure of the region's current entry would ask, as a transition of the region with NavigationOperation.Confirm, and changes nothing. When every guard agrees, its commit turn runs the guards' OnCommitted actions, such as a discard, and then onConfirmed. Do the agreed work there, not after the await, because by then another entry may be current. Guards that switch on NavigationOperation handle Confirm in their default arm. Both replace a CanLeaveTabAsync() of your own beside the pages' guards; see asking without navigating.

With ReactiveUI, ReactiveNavigationSelectionExtensions observes the selection and creates its command:

SelectTab = Tabs.CreateSelectCommand(); // ReactiveCommand<int, NavigationOutcome>

Tabs.WhenSelectedIndexChanged()    // int, -1 without regions, on the commit turn
    .Subscribe(index => SelectedTab = index);

WhenSelectedChanged(), WhenIsTransitioningChanged() and WhenIsBusyChanged() complete the set. The command's output is the NavigationOutcome: a veto of the tab left is Rejected (Guard).

In Runic Views, a get-only NavigationSelection property is state, not a content slot: the frontend receives its SelectedIndex, typed number | null, and each tab's region stays a content slot. A selection with a public setter is RUNICBRIDGE008. The frontend selects through the command and shows the slot at the selected index:

function CustomersPage({ view, state }: { view: CustomersPageClient; state: CustomersPageState }) {
  const tabs = [state.list, state.reports];
  return (
    <>
      <nav>
        <button aria-pressed={state.tabs === 0} onClick={() => void view.selectTab(0)}>Customers</button>
        <button aria-pressed={state.tabs === 1} onClick={() => void view.selectTab(1)}>Reports</button>
      </nav>
      <ViewOutlet content={state.tabs === null ? null : tabs[state.tabs]} registry={pages} />

Don't move the highlighted tab before the command settles: state.tabs changes only when the switch commits, so the tab bar shows the kept tab after a veto. Here the tab set is fixed; for tabs that open and close at run time, see document tabs. In WPF, NavigationSelector.Selection binds a TabControl to the selection; see incremental WPF adoption. The Runic.Navigation guide lists every rule.

With CommunityToolkit.Mvvm #

The navigator is the same; only the commands differ. A Toolkit app registers AddRunicNavigation(), which also provides the model context, creates regions the same way, and binds [RelayCommand] availability to region state. Region changes arrive as PropertyChanged inside model turns, so a handler can refresh CanExecute directly:

public WorkspaceNavigation(RunicNavigator navigator, HomeViewModel home)
{
    Main = navigator.CreateRegion<IMainViewModel>(this, NavigationTarget.Borrow<IMainViewModel>(home));
    Dialog = navigator.CreateRegion<IDialogViewModel>(this);
}
// ...
// The confirm dialog is modal: while it asks, or while a page navigation is in flight,
// nothing else navigates. Commands bind their CanExecute to this, and the methods check it
// again, so a caller that skips CanExecute can't supersede the Back that asks.
public bool CanNavigate => Dialog.Current is null && !Main.IsTransitioning;

// ExpectedCurrent makes a repeated click a no-op instead of a second document. The navigator
// builds the document from the window's services and owns it.
public Task OpenNotesAsync() => !CanNavigate || Main.Current is DocumentViewModel
    ? Task.CompletedTask
    : Main.PushAsync<DocumentViewModel>(new NavigationRequestOptions(Main.CurrentEntry?.Id)).AsTask();

NavigationRequestOptions.ExpectedCurrent, the entry id passed here, makes a request conditional: a double click, or an answer that arrives after the user moved on, is rejected instead of opening a second page. NavigationRequestOptions.Requester, new in SDK 0.11.0, names the entry a request is made for, such as a page whose operation completes and then opens a page in a parent region. The request is rejected as NotCurrent unless that entry, and every entry whose content owns its region up to a root region, is current at admission and at commit. Since SDK 0.12.0, an entry in a tab that isn't selected is not current either.

CommunityToolkit.Mvvm has no interaction type, so the leave guard asks in the dialog region with LeaveConfirmation.InDialog. The confirm dialog takes its entry context in its constructor, as the ReactiveUI pages do, and answers with CompleteAsync and DismissAsync; see Ask the user from a ViewModel. Toolkit pages implement INavigationAware instead of the adapter's WhenNavigatedTo, and use GuardClose the same way. A [RelayCommand] closes a kept Window with RequestCloseAsync:

[RelayCommand]
private async Task CloseEditorAsync()
{
    if (!await _editor.RequestCloseAsync()) StatusText = "The editor has unsaved changes.";
}

Document tabs #

Tabs that keep their own pages have a fixed set of tabs in a web View. Since SDK 0.16.0, mark a get-only NavigationSelection with [RunicRegionCollection(typeof(TContent))] when the ViewModel opens tabs at run time, such as documents that each keep their own back stack. The ViewModel adds a region with Add:

public sealed partial class EditorWindowViewModel(RunicNavigator navigator) : ObservableObject
{
    [RunicRegionCollection(typeof(IDocumentPage))]
    public NavigationSelection Documents { get; } = navigator.CreateSelection(this, []);

    [RelayCommand]
    private async Task<NavigationOutcome> OpenAsync(string path)
    {
        var tab = navigator.CreateRegion<IDocumentPage>(this, NavigationTarget.Create<DocumentViewModel, string>(path));
        Documents.Add(tab);
        return (await Documents.SelectAsync(tab)).Outcome;
    }
}

The page receives { regions, selected }, where each region is { key, content }, and the generated client selects and closes tabs by key:

readonly documents: RegionCollection<DocumentPageReference | DocumentInfoPageReference>;
// { regions: readonly { key: string; content: R | null }[]; selected: number | null }
selectDocuments(key: string): Promise<RegionOutcome>;
closeDocuments(key: string): Promise<RegionOutcome>;
  • A key stays the same while its tab exists and is never reused in the Window, so key each tab's component by it. A push inside a tab changes content and keeps key.
  • select{Name}(key) is SelectAsync: the tab left is asked as Retain. close{Name}(key) is RemoveAsync: every page of the tab is asked as Retire. Both resolve with the NavigationOutcome; a veto is Rejected with Guard. selected changes only when a switch commits.
  • A second close of a tab whose close is pending joins it, so the guards ask once. A select while a close is pending supersedes the close, and the tab stays.
  • PageCanClose = false generates no close{Name}; the ViewModel closes such tabs itself.
  • A guarded Window close removes the tabs one by one. The tabs before the first one that refuses are closed, and the Window stays open. To decide for every tab at once, own the tabs and the selection by a page entry in a region slot: the clear of that slot asks every tab in one transition.
  • RUNICBRIDGE070 reports the attribute on another property type, with a setter or with a content type without a View; RUNICBRIDGE071 reports a generated method that collides with another client member.
  • A page and a host that don't both list region-collections/1 keep the 0.15 behaviour.

The React, Vue, Svelte and Angular adapters render the tabs with RegionOutlets, which by default keeps hidden tabs mounted, so each tab keeps its DOM; mode: "selected" unmounts them. panelProps(entry) adds tab-panel attributes, and regionEntries() lists the tabs for a tab bar:

<nav>
  {regionEntries(state.documents).map(tab => (
    <span key={tab.key}>
      <button aria-pressed={tab.selected} onClick={() => void view.selectDocuments(tab.key)}>Tab {tab.index + 1}</button>
      <button onClick={() => void view.closeDocuments(tab.key)}>×</button>
    </span>
  ))}
</nav>
<RegionOutlets collection={state.documents} registry={pages} />

With ReactiveUI, WhenRegionsChanged() emits the selection's Regions after each Add and committed RemoveAsync, and CreateCloseCommand() takes a region and outputs the NavigationOutcome of RemoveAsync. In a test, state.Regions(...) reads the tabs, and SelectRegionAsync and CloseRegionAsync send the page's requests:

var tabs = (await host.Root.SnapshotAsync()).Regions(vm => vm.Documents);
// tabs.Keys, tabs.Regions[i].Content (a PageReference or null), tabs.SelectedIndex
var closed = await host.Root.CloseRegionAsync(vm => vm.Documents, tabs.Keys[0]);
// closed.RegionOutcome: Committed, or Rejected with Guard when a page refused

In page tests, a mock's regions handler stands in for the guards; see testing frontends. The document tabs example uses all of it, and region collections lists every rule.

Save and restore navigation #

Since SDK 0.16.0, a route map names pages with paths such as customers/42/invoices/7. With it, the navigator saves a Window's navigation, rebuilds it after a restart and opens deep links. Register the routes with the Window's services; every AddRunicNavigationRoutes call adds to one map, so a feature can register its own:

services.AddRunicNavigationRoutes(routes => routes
    .Map<CustomerListViewModel>("customers")                       // Create<T>()
    .Map<CustomerViewModel, int>("customers/{id:int}")              // Create<T, int>(id)
    .Map<InvoiceViewModel, InvoiceRef>("customers/{id:int}/invoices/{invoice:int}",
        values => new InvoiceRef(values.GetInt32("id"), values.GetInt32("invoice")),
        invoice => new NavigationRouteValues().Set("id", invoice.Customer).Set("invoice", invoice.Invoice))

A template has literal segments and typed parameters: {name} (a string), :int, :long, :guid or :bool. A route path is at most 2048 characters without control characters. A string parameter comes from a link, an address bar or a saved file: treat it as untrusted text, such as a key to look up.

navigator.GetPath() returns a NavigationPath: each region's entries by route, the regions and selections below them, and the selected tabs. NavigationPath.ToJson and FromJson store it wherever the application keeps its state:

// When the window closes: next to the window placement, in the application's own store.
File.WriteAllText(statePath, navigator.GetPath().ToJson());

// After the window opened at the next start, with saving switched off until it returns:
var result = await navigator.RestoreAsync(NavigationPath.FromJson(File.ReadAllText(statePath)));
foreach (var issue in result.Issues) logger.LogInformation("Not restored: {Location} ({Kind})", issue.Location, issue.Kind);
  • RestoreAsync uses ordinary navigation requests, so guards and hooks run. It keeps the entries that already match, and lists what it left out in NavigationRestoreResult.Issues instead of failing.
  • A region stops at its first page that no longer has a route, unless NavigationRestoreOptions.UnmappedEntries is Skip. A restore takes at most 256 entries per region and 256 tabs per selection.
  • Don't save while RestoreAsync runs, or a partial restore overwrites the saved path. Store the application's version beside the path and discard a path that another version wrote.
  • Document tabs are restored by position: NavigationSelectionOptions.RestoreRegion creates each missing tab. A tab that nothing could be restored into is discarded; RunicNavigator.DiscardRegionAsync does the same for a tab the application created and then didn't add.

region.OpenRouteAsync(route, mode) opens a route path from a link, a notification or a second launch, and returns null when no route matches. NavigationRouteOpen.Stack builds the history from the route's prefixes, so customers/42/invoices/7 gives Customers, Customer 42 and Invoice 7. NavigationRouteLinks.TryGetRoute reads the route of a myapp://… or an https link of the application's hosts:

async Task OpenLinksAsync(IEnumerable<Uri> links)
{
    foreach (var link in links)
        if (NavigationRouteLinks.TryGetRoute(link, ["myapp"], out var route))
            await shell.Main.OpenRouteAsync(route, NavigationRouteOpen.Stack); // the window's region, from any thread
}

A link is untrusted input: only the map's routes open, so check that the record a route names exists, and confirm anything destructive in the page. The document tabs example reopens its tabs after a restart and opens document-tabs:// links. A restart test saves with SavePath() and restores with RestorePathAsync(saved):

var restore = await restarted.ServiceProvider.GetRequiredService<RunicNavigator>().RestorePathAsync(saved);
await Assert.That(restore.IsExact).IsTrue(); // otherwise restore.Result.Issues says what was left out

See routes, saved paths and deep links for the matching and restore rules.

Back and the URL #

Since SDK 0.16.0, a web View page can go back in its Window and keep its URL in step with the Window's navigation, on Runic Desktop and CS-WebUI alike. installBackNavigation() makes the mouse's Back button, Alt+Left, Cmd+[ on macOS and the Browser Back key run RunicNavigator.BackAsync(). That goes back in the innermost presented region that can, such as the selected tab or an open dialog, through its departure guards; navigateBack() does the same from code. For the URL, choose the Window's path region and give its pages routes:

public ShellViewModel(RunicNavigator navigator)
{
    Main = navigator.CreateRegion<IPage>(this, NavigationTarget.Create<CustomerListViewModel>());
    _path = RunicPresentation.SyncNavigationPath(Main); // uses the registered INavigationRouteMap
}
import { installBackNavigation, installNavigationPath } from "@runic-artifex/views";
installNavigationPath(); // #/customers/42 follows Main; Back, Forward and the address bar open their paths
  • The URL follows the region's current page, such as #/customers/42/invoices/7. The browser's Back and Forward and the address bar open their path through the guards; a refused change puts the URL back. History entries keep their index and path across a reload.
  • A path in the URL when the page loads opens as a deep link, also when the Window chooses its path region later.
  • With both installs, the Back keys go back in the page's history, so a Back runs once. Several pages of one Window follow the same path region, and the last change wins. A second SyncNavigationPath for the navigator throws until the first is disposed.
  • For a router of the page's own, such as SvelteKit's, use openNavigationPath(path) and onNavigationPath(listener). The framework adapters re-export these functions.
  • A page and a host that don't both list navigation-path/1 keep the earlier behaviour: the page's navigation calls fail with a failed BridgeError.

In page tests, createMockBridge({ navigation }) answers the navigation requests and pushNavigationPath stands in for a change in .NET. In .NET tests, NavigateBackAsync() sends the Window's Back, OpenNavigationPathAsync(path) acts as the browser's Back, Forward or address bar, and NavigationPathPushes lists what the page was told:

using var path = RunicPresentation.SyncNavigationPath(shell.Main);
var refused = await host.OpenNavigationPathAsync("home");   // a browser Back that a dirty editor refuses
await Assert.That(refused.Outcome?.Rejection).IsEqualTo(NavigationRejection.Guard);
await Assert.That(refused.Path).IsEqualTo("editors/a");     // the URL the page puts back
await Assert.That(host.NavigationPathPushes[^1]).IsEqualTo(new RunicNavigationPathPush("editors/a", "push"));

See Back and the URL and the window's Back.

Shared clients #

Since SDK 0.17.0, ViewModels that publish the same members can share one generated client, so one web component renders all of them, such as read-only result pages with a table and an action each. Declare the members on an interface, mark it [RunicSharedClient], and implement it in each ViewModel:

/// <summary>A read-only result page with one action per element.</summary>
[RunicSharedClient]
public interface IResultPage
{
    /// <summary>The table the page shows.</summary>
    ResultTable Page { get; }

    /// <summary>Runs the action of the element with the id.</summary>
    IAsyncRelayCommand<string> RunActionCommand { get; }
}

Besides each ViewModel's own module, the generator writes resultPage.ts, named after the interface without its leading I, with ResultPageState, ResultPageClient, ResultPagePageReference and resultPageKinds. Each implementing ViewModel's page reference extends the shared one, so a component written against the shared types takes any of them without a cast, and registryEntries from @runic-artifex/views registers it for every kind:

function ResultPage({ page }: { readonly page: ResultPagePageReference }) {
  const { state, client } = useView(page); // a ResultPageClient
  return <ResultTableView table={state?.page} onAction={id => void client?.runAction(id)} />;
}

const pages = { ...registryEntries(resultPageKinds, ResultPage), settings: SettingsPage }
  satisfies ViewRegistry<MainState["main"]>;
  • A content slot or NavigationRegion typed as the interface presents any of the implementing ViewModels, and RunicWindowTestHost's View<IResultPage>(vm => vm.Main) drives whichever one it presents.
  • The shared client has the interface's properties: state, setters, commands with their operations, query collections and region collections, and validation errors when every implementing ViewModel has them. Methods, events, field descriptors, interactions and view requests stay with each ViewModel's own client.
  • Only the TypeScript types change. The wire contract and the contract fingerprint stay the same, and a ViewModel that implements no [RunicSharedClient] interface generates what it did before.
  • Every implementing ViewModel must publish each member alike, with the same nullability, wire name, type and command input, or the build fails with RUNICBRIDGE036.

See Shared clients in the Views README for the generated types and the matching rules.

Commands scoped to their page #

A wizard's Next, clicked twice before the second page arrived, must not skip a page. Since SDK 0.15.0, mark such a command [RunicPresentationScoped], on the command property or on its CommunityToolkit [RelayCommand] method, and renew the presentation where the command changes the page:

public sealed partial class SetupViewModel : ObservableObject
{
    [ObservableProperty]
    public partial int Step { get; private set; } = 1;

    [RelayCommand]
    [RunicPresentationScoped]
    private void Next()
    {
        Step++;
        RunicPresentation.Renew(this);
    }
}

The page sends a scoped command with the epoch of the state it showed when the user clicked, and the Bridge runs it only while that epoch is current. The second Next was clicked on the first page, whose epoch Renew ended, so it doesn't run; the call resolves with the current state and no error, so useCommand and the other command bindings show nothing. In development, the dock (the Vite DevTools dock) lists such calls on its Superseded commands card; see debugging.

  • An epoch also begins with a route's first state, so a new page in a navigation region, or content presented again, needs no Renew. Call RunicPresentation.Renew(viewModel) where the page changes without a new presentation, such as Next and Back, or after a cancelled dialog returned to its page. It renews every route that presents the ViewModel, in every window, and publishes a full state, also when nothing changed.
  • The generated client lists the commands in scopedCommands, and adding or removing the attribute changes the View's contract fingerprint. On any other member the attribute is warning RUNICBRIDGE034. Setters, checked writes and operation starts are not scoped.
  • The feature is presentation-epoch/1, negotiated in hello: with a page or host of SDK 0.14, scoped commands run as plain commands. It replaces a presentation number kept in state and compared in each command.

In page tests, mock.renew() renews a mock's route as Renew does; see testing frontends.

Wait until the page shows a state #

Since SDK 0.15.0, RunicPresentation.WaitForPresentedAsync(viewModel, timeout) completes with true once a page rendered the ViewModel's state including every change made before the call, for example before a result page is captured or a Window closes after showing a summary:

Page = result;
if (!await RunicPresentation.WaitForPresentedAsync(result, TimeSpan.FromSeconds(2)))
    logger.LogDebug("No page showed the result in time.");

It returns false at the timeout, also when no page uses the presented/1 feature, such as a page of SDK 0.14. Only a wait asks the page to report, so an idle or typing page sends nothing extra.

Every close that the application starts (CloseAsync, RequestCloseAsync once it decided, disposal and a host shutdown) tells the Window's pages: the page renders its last state and reports the connection state closed instead of reconnecting or lost. A CS-WebUI tab left open after the application exited therefore says that the application closed it. CloseAsync(timeout) also waits, within its timeout and at most 5 seconds, until each page acknowledged the close:

var closed = await window.CloseAsync(TimeSpan.FromSeconds(10));
if (!closed.PagesAcknowledged) logger.LogInformation("A page did not confirm the close.");

PagesAcknowledged is true when every page acknowledged, also when no page uses the feature. A close that ends before every page replied is logged at Debug as event 1026 (WindowCloseUnacknowledged). These replace a UiRendered command that a page called after an animation frame, and a close token with an acknowledgement command of your own. See waiting until the page shows a state.

Next steps #