barbatos-aquarius-router
Navigation with Barbatos.Wpf.AquariusRouter (Vue Router port) - RouteRecord tables, IOnBeforeRouteLeave/IOnBeforeRouteUpdate and BeforeEach guards, RouterView, RouterLink, RouteTo, modal routes via Ro
SKILL.md.claude/skills/barbatos-aquarius-router/SKILL.md
GitHubNavigation with Barbatos.Wpf.AquariusRouter
A port of Vue Router onto Aquarius: a RouteRecord table, a Router that runs a full guard
pipeline before committing, RouterView outlets, RouterLink triggers. Router never touches
Window or Application (only RouterWindows opens windows), so the whole pipeline runs headless
in tests. It is not a browser router: no URL history, scroll behaviour, transitions on
RouterView, or route-level keep-alive. Switching Views inside one screen is aq:Component
(barbatos-aquarius-view).
Every namespace (.Matching, .Routing, .Searching, .Xaml) maps to
xmlns:aqr="http://schemas.barbatos.co/aquariusrouter/2026/xaml".
Sources of truth
- Concepts and rationale: README (Dialog windows, The Full Pipeline Order); signatures: API-REFERENCE.
- The code beats the docs.
RunGuardPipeline/NavigateWithRedirectinRouting/Router.csare the pipeline;Matching/RouteMatcher.csis resolution, index children, aliases and registration-time validation;Xaml/RouterWindows.csis modal-route open/close. - Sample
samples/Barbatos.Wpf.AquariusRouter.Sample:WpfProgram.cs(wiring),Routing/AppRoutes.cs(every guard placement, index child, alias, redirect, catch-all, modal children),Routing/AppNavigationGuards*.cs,Routing/LoginRedirect.cs,MainWindow.xaml(nav bar,IsActivetrigger, named outlet, search box),Views/Dialog/. - Tests in
tests/Barbatos.Wpf.AquariusRouter.UnitTests:RouterNavigationGuardOrderTests(the order contract),RouterRedirectAndFailureTests,DefaultChildRouteTests,RouteRecordViewModel*Tests,RouterModalRouteTests,RouterDialogWindowTests,RouterLinkTests,RouterLeakTests,RouteMatcherTests. - reference.md - read when you need the full
RouteRecordmember table, path syntax and ranking, exactRouteLocationRawresolution (name param seeding, relative targets), history, theRouterLinkactive-state algorithm, search ranking/folding, or what holds a View alive.
Wiring
From the sample's WpfProgram.cs:
builder.Services.AddSingleton<AuthState>();
builder.Services.AddAquarius();
builder.Services.AddAquariusRouter(sp => AppRoutes.Build(sp.GetRequiredService<AuthState>()));
builder.Services.AddTransient<InspectorWindow>(); // a modal-route Window
builder.Services.AddTransient<DashboardViewModel>(); // routed ViewModel with ctor dependencies
builder.ConfigureAppNavigationGuards(); // global guards, via IWpfInitializeService
var app = builder.Build();
app.Services.UseAquarius(); // Setup.ServiceProvider = this container
app.Services.UseAquariusRouter(); // Router.Current = the Router singleton (also returned)
Then once, at startup (MainWindow.OnSourceInitialized in the sample):
await Router.Current!.Start("/");
routesis a factory, called once whenRouteris first resolved, so a per-routeBeforeEntercan close over a DI service. Optional second argument:options => options.PathOptions = new PathParserOptions { Strict = true }- set it in code; nothing in the package bindsRouterOptionsfrom configuration (itsSectionNameis only a name). For a settings file, addbuilder.Services.Configure<RouterOptions>(builder.Configuration.GetSection(RouterOptions.SectionName))afterAddAquariusRouter. Without DI:new Router(routes)+Router.Current = router.RouterandIRouterHistorygo in withTryAddSingleton: register your own first to win.- Routed Views and ViewModels are transient.
Routerresolves a fresh instance on every genuine (re-)entry throughSetup.Resolve(container first,Activator.CreateInstancefallback); a singleton fights that and is never released. Register only types with constructor dependencies - parameterless ones need nothing. Start(initial)isPushthat replaces the seed history entry. There is no default top-level route and no ambient URL. A cold-start protocol URImyapp://users/42?ref=mail#detailisStart(RouteLocationRaw.Parse($"/{uri.Host}{uri.PathAndQuery}{uri.Fragment}"))-System.Urireadsusersas the host, soPathAndQueryalone is/42?ref=mail; for the empty-authority formmyapp:///users/42it isuri.PathAndQuery + uri.Fragment. AFullPaththe app stored itself (e.g. in a toast'sArguments) isRouteLocationRaw.Parse(text).- Register global guards from an
IWpfInitializeService(sample:AppNavigationGuardsInitializer).BeforeEach/BeforeResolve/AfterEachreturn anIDisposable; dispose it when the registering object is shorter-lived than the router.
The route table
Keep it in one place - Routing/AppRoutes.cs, the router/index.ts of the app:
new RouteRecord
{
Path = "/settings", Name = "settings", View = typeof(SettingsShellView),
Meta = new Dictionary<string, object?> { ["requiresAuth"] = true, ["requiresPremium"] = true },
Children =
[
new RouteRecord { Path = "", Name = "settings-profile", View = typeof(SettingsProfileView) },
new RouteRecord { Path = "security", Name = "settings-security", View = typeof(SettingsSecurityView) },
],
},
new RouteRecord { Path = "/old-home", Redirect = _ => "/" },
new RouteRecord { Path = "/:pathMatch(.*)*", Name = "not-found", View = typeof(NotFoundView) },
- Top-level paths start with
/, or registration throwsArgumentException. Children are relative unless they start with/. Path = ""is the index child. Targeting the parent by path or by name descends to it, keeping the location at/settings. It has no path of its own (/settings/profileis not it) - reach it by name (ShortcutRouting.csdoes). Without an index child/settingsrenders the shell with an empty inner outlet. The alternative,Redirect = _ => "/settings/security"on the parent, changes the location and resolves before any guard.- Name every navigable record.
{aqr:RouteTo Name=...},RouteSearchResult.Toand a modal window's [X] all navigate by name. A second record with the same name takes over the name; the first stays reachable by path. A record with noName, View orRedirectis a pure grouping record: its children match, its own path never does (it falls to the catch-all or throwsNo route matches). Metamerges root-to-leaf on every resolve (child wins), so one flag on a parent protects the subtree through a single globalBeforeEach. The catch-all ranks last wherever declared.Aliaspaths resolve to the same record (sharedInstances), by path only, without its children.View+Views,ViewModel+ViewModels, or a ViewModel for an outlet with no View throwInvalidOperationExceptionat registration.RouteRecordis a reference type on purpose - identity is what makes a route "the same route" across navigations. Never make it arecord, never share one table between two routers, and compare locations withRouteLocation.IsSameLocation, not==.
Pairing a View with its ViewModel
| Situation | Use |
|---|---|
You own the View, names follow Ns.FooView -> Ns.FooViewModel |
aq:Setup.Enable="True" in the View |
| You own the View, namespace or name differs | aq:Setup.ViewModel="{x:Type ...}" |
| You own neither (both ship in libraries) | RouteRecord.ViewModel / ViewModels (sample: /accounts/:id) |
- A routed View must resolve its own
DataContext.Routerruns route hooks against the View'sDataContextright after constructing it, before it is in any tree - an inheritedDataContextis not there yet, so no enter hook or enter guard fires (and later leave/update guards hit whatever outer ViewModel it inherits once mounted). - The convention matches the namespace-qualified name; another assembly is fine (if loaded),
another namespace or suffix is not, and failure leaves
DataContextnull silently. Make it loud withAddAquarius(o => o.ThrowOnUnresolvedViewModels = true)-UseAquarius()overwrites a hand-setSetup.ThrowOnUnresolvedwith that option. RouteRecord.ViewModelis assigned after construction and overrides the View's ownaq:Setup. The paired ViewModel gets every route hook and guard, but Aquarius mount hooks (IOnMounted,IOnBeforeUnmount, ...) only if the View itself setsaq:Lifecycle.Enable- if you cannot edit the View, load fromIOnRouteEnter.
Navigating from code
await router.Push("/users/42"); // literal path
await router.Push(new RouteLocationRaw { Name = "user", Params = new Dictionary<string, object?> { ["id"] = "42" } });
await router.Push(RouteLocationRaw.Parse("/search?q=hello#results")); // a serialized FullPath
await router.Replace("/login"); // no new history entry
await router.Back(); // Go(-1); Forward() = Go(1)
- A string is always a literal
Path."/x?y=1"is not split - a/:paramroute can swallowx?y=1as its value, otherwise it falls to the catch-all or throws. UseQuery, orRouteLocationRaw.Parsefor anything that was aFullPath(history, a stored redirect target, a protocol URI). PathignoresParams; build from parts withName+Params.ParamsisIReadOnlyDictionary<string, object?>andQueryisIReadOnlyDictionary<string, string?>- writenew Dictionary<string, object?> { ... }/new Dictionary<string, string?> { ... }; target-typednew() { ... }does not compile against an interface. By name, required params the current location already has carry over (from/users/7/...,{ Name = "user-overview" }stays on user 7).- Results:
nullon success, else aNavigationFailure. An unmatched path or unknown name is not a failure -ResolvethrowsInvalidOperationExceptionout ofPush. - Same location again returns
Duplicatedwithout running guards;Force = truere-runs the pipeline as an update (same instance).Go/Back/Forwardrun the guards but skip steps 1-2 below; out of range is a silentnullwith noAfterEach. - Navigate on the UI thread.
Pushconstructs Views synchronously. Marshal callbacks from thread-pool timers orTask.Runthrough the Dispatcher first.INotificationService.ActivatedandIPushNotificationService.RouteRequestedalready arrive on the UI thread, so a toast handler canPushdirectly; so are input-system actions, global hotkeys included, in a normal startup, which is why the sample'sShortcutRoutingpushes directly.
Guards
Interface (on the View's DataContext) |
Fires | Can cancel |
|---|---|---|
IOnBeforeRouteLeave |
its record leaves the matched chain | yes |
IOnRouteUpdate then IOnBeforeRouteUpdate |
its record stays matched across a param/query change | update guard only |
IOnRouteEnter then IOnBeforeRouteEnter |
its record is newly entered (fresh instance) | enter guard only |
Guards are always async and return NavigationGuardResult.Continue, .Cancel or
.Redirect(raw); a bool converts implicitly. Unlike Vue Router, IOnBeforeRouteEnter runs on
the real instance - to.Params is right there, no next(vm => ...).
Pipeline order (Router.NavigateWithRedirect + RunGuardPipeline; pinned by
RouterNavigationGuardOrderTests):
- Static
Redirecton the resolved leaf - followed again while the new leaf redirects; each hop counts toward the 30-hop redirect limit. - Duplicate check ->
DuplicatedunlessForce. IOnBeforeRouteLeave, deepest child first.- Global
BeforeEach, registration order. - Every updating record's
IOnRouteUpdate, then everyIOnBeforeRouteUpdate, root first. - Per-route
BeforeEnteron entering records, root first. - Entering Views constructed (their
aq:SetupresolvesDataContext), then everyIOnRouteEnter, then everyIOnBeforeRouteEnter, root first. - Global
BeforeResolve. - Leaving records'
Instancescleared; history pushed (replaced forReplaceor the first navigation);CurrentRouteswapped; everyRouterViewreacts. AfterEach(to, from, failure)for every outcome - success,Aborted,Cancelled,Duplicated- except a redirect in progress.
- A guard's
Cancel->Aborted(4); a newer navigation started meanwhile ->Cancelled(8), checked at the end of every stage;Duplicatedis 16. Real flags, soNavigationFailures.IsNavigationFailure(f, NavigationFailureType.Aborted | NavigationFailureType.Cancelled)tests both. - A guard's
Redirectrestarts at the new target. Static and guard redirects share one limit of 30 chained hops per navigation; past itPushthrowsInvalidOperationException("Infinite redirect loop detected...") and commits nothing - unlike Vue Router, which only counts guard redirects. - A guard that throws is not a failure: the exception leaves
Pushas-is (RouterLinkrethrows it on the Dispatcher). Like a refusal it commits nothing and releases any View built in step 7, so a retry constructs fresh ones. Still say no withCancel/Redirect: a throw reaches the caller as an error, not as aNavigationFailure. - Data hooks (
IOnRouteEnter/IOnRouteUpdate) run before their stage's guards and before every later stage, and are never rolled back. Do not start subscriptions or timers there - an entering instance can be discarded unmounted; use the Aquarius mount hooks.
Where to put a check (the sample shows each): protection by Meta + one global BeforeEach
(/preferences, /settings - one guard checks requiresAuth and requiresPremium); a rule
owned by the route, BeforeEnter (/admin); a rule owned by the screen, IOnBeforeRouteEnter
(DashboardViewModel); unsaved changes, leave + update guards. Redirect to login with the
intended target in the query (LoginRedirect.To(to)), and push it back with
RouteLocationRaw.Parse.
Unsaved changes - leave and update
/users/1/settings -> /users/2/settings is an update (same record, same instance), not a
leave, so a leave guard alone lets the edit vanish. And because step 5 runs IOnRouteUpdate
first, a ViewModel whose IOnRouteUpdate reloads state destroys the edit before its own update
guard can see it. Load inside the guard, after the decision - the sample's
UserSettingsViewModel does exactly this:
public sealed partial class UserSettingsViewModel : ObservableObject,
IOnRouteEnter, IOnBeforeRouteLeave, IOnBeforeRouteUpdate // deliberately no IOnRouteUpdate
{
public void OnRouteEnter(RouteLocation to, RouteLocation from) => Load((string)to.Params["id"]!);
public Task<NavigationGuardResult> OnBeforeRouteLeave(RouteLocation to, RouteLocation from) =>
Task.FromResult<NavigationGuardResult>(!IsDirty || ConfirmDiscard());
public Task<NavigationGuardResult> OnBeforeRouteUpdate(RouteLocation to, RouteLocation from)
{
if (IsDirty && !ConfirmDiscard())
return Task.FromResult(NavigationGuardResult.Cancel);
Load((string)to.Params["id"]!); // Load/IsDirty/ConfirmDiscard are the app's own
return Task.FromResult(NavigationGuardResult.Continue);
}
}
Steps 6-8 can still refuse after that Load; where they might, reload once the navigation
commits instead. A ViewModel with nothing to protect implements IOnRouteUpdate to refresh on a
param change - without it a reused screen shows the previous record's data.
XAML surface
<aqr:RouterView /> <!-- default outlet; Content is managed - never set it -->
<aqr:RouterView OutletName="sidebar" /> <!-- fed by RouteRecord.Views["sidebar"] -->
<Button aqr:RouterLink.To="/about" Content="About" />
<Button aqr:RouterLink.To="{aqr:RouteTo Name=user, Params='id=2'}" Content="User 2" />
<Button aqr:RouterLink.To="{Binding SettingsTarget}" aqr:RouterLink.Replace="True" />
- A nested outlet is just
<aqr:RouterView />inside a routed View; depth comes from walking ancestorRouterViews atLoaded, skipping records without Views. RouterLink.Totakes astringorRouteLocationRaw, only onButtonBaseorHyperlink(anything else throws).RouterLink.IsActive(the target or one of its descendants is current, so a link to a parent stays active on any child) andIsExactActive(exact, params included) are read-only - style with<DataTrigger Binding="{Binding (aqr:RouterLink.IsActive), RelativeSource={RelativeSource Self}}" Value="True">(MainWindow.xaml).{aqr:RouteTo}is evaluated once at parse:Params/Queryare;-separatedkey=value, a comma inside a value makes a repeatable param's list;Name+Pathtogether or neither throws. For a target that changes, bindToto a ViewModelRouteLocationRawproperty (UserLayoutViewModel.SettingsTarget).- Which router: explicit
Routeron the control, then inheritedRouterScope.Router, then (outlets only) the ancestor outlet's, thenRouter.Current- soRouterView.Routernever reaches links; useRouterScope. See reference.md.
Dialog windows - two shapes
Modal route - the default. The dialog is a route, so links, Push, shortcuts, search and deep
links all reach it with nothing extra:
new RouteRecord
{
Path = "/dashboard", Name = "dashboard", View = typeof(DashboardView),
Children =
[
new RouteRecord { Path = "inspector", Name = "inspector", Window = typeof(InspectorWindow),
Views = new Dictionary<string, Type> { ["inspector"] = typeof(InspectorOverviewView) } },
],
}
aqr:RouterWindows.Enable="True" once on the main Window; the dialog hosts
<aqr:RouterView OutletName="inspector" /> and ordinary RouterLinks (it gets RouterScope.Router
automatically).
- Declare it as a child of the route that stays visible behind it - that parent keeps rendering in the main window.
- Prefer a named outlet: a plain
Viewis also claimed by any main-window outlet that reaches that depth. The sample's plainViewworks only becauseDashboardViewhas no nested outlet. - Register the
Windowtransient - a closed WPFWindowcannot be shown again. It is resolved throughSetup.Resolve, owned by the main window, and opened withShow(): modal in routing terms only, the main window stays usable. - One history:
Backcloses it; leaving the record closes it; closing the host closes all. Sibling records naming the sameWindowtype share one window and swap its outlet. - (or
Close()) becomes a navigation:Pushto the parent by name (a new entry, current params kept), orBackif the parent has no name. The window goes once it commits and stays open if a guard refuses, throws, or a newer navigation supersedes it - so an unsaved-changes leave guard on a modal ViewModel works. An async guard keeps the window up until it decides. A throw is rethrown on the Dispatcher, as for aRouterLinkclick. - Name the parent. Unnamed, [X] is
Back, a no-op when the app started on the modal route: the window still closes, but the route stays on the modal record and re-pushing it isDuplicated. - Your own
Window.Closinghandler on the dialog runs on every attempt, and again when a later commit closes the window - put once-only work inClosed. If it cancels, no navigation starts - provided it runs beforeRouterWindows' (attach it in XAML or the constructor, or cancel in anOnClosingoverride before the base call). An owner closing or app shutdown cannot be vetoed: the dialog goes, its guards are asked once.
Independent stack - a window that is a second application surface: a second Router with its
own route table, set once with aqr:RouterScope.Router on the Window (inheritance stops at
the window boundary, so it cannot drive the main router). Call Start on it. A container
resolves one Router per type, so expose the second through a holder type (README: InspectorRouter),
and scope it to the dialog: the last routed View - and through it the closed dialog - stays
alive until that router navigates elsewhere (RouterDialogWindowTests).
Rules that bite
RouterView.ContentandRouteRecord.Instancesbelong to the router - never assign them.Routernever disposes Views or ViewModels; it drops them. Release resources in Aquarius unmount hooks, and dispose anyWatch.On(router.CurrentRoute, ...)there - an app-lifetime router pins every watcher.- Never wrap
<aqr:RouterView>in<aq:KeepAlive>: the router owns routed View lifetimes so guards run against the mounted instance. Keep-alive inside one screen isaq:Component+aq:KeepAlive. Nor in aTransition: it is driven by its booleanShow, not by a content swap - animate inside the routed View instead.
Symptom -> cause -> fix
| Symptom | Cause | Fix |
|---|---|---|
Edit lost switching /users/1 -> /users/2, no prompt |
Update, not leave; or IOnRouteUpdate reloads before the update guard |
Unsaved changes pattern |
| Reused screen shows the previous record's data | Same record = same instance, only update hooks run | Implement IOnRouteUpdate (or load in the update guard) |
| Routed screen blank, no hooks fire | DataContext null: convention missed, or the View relies on an inherited one |
aq:Setup.ViewModel or RouteRecord.ViewModel; ThrowOnUnresolvedViewModels to surface it |
/settings shows the shell, inner outlet empty |
No index child | Add a Path = "" child, or Redirect on the parent |
InvalidOperationException "No route matches path" from Push/a click |
No catch-all, a pure grouping path, or a ?query inside a string |
Catch-all; Query or RouteLocationRaw.Parse |
Clicking the current link does nothing; AfterEach logs Duplicated |
Same location | Force = true to re-run as an update |
| Dispatcher exception "No Router is available" | UseAquariusRouter/Router.Current not set before the window loaded |
Call UseAquariusRouter() right after Build() |
| Every outlet empty, no error | Start never called - CurrentRoute is still RouteLocation.Start |
await router.Start("/") once at startup |
InvalidOperationException "Infinite redirect loop" |
A guard redirects to a target it also redirects, or static Redirects form a cycle (30 hops in all) |
Exempt the target (/login) from the guard; break the static cycle |
| Link inside a dialog navigates the main window | No RouterScope.Router on the dialog (or only RouterView.Router set) |
aqr:RouterScope.Router on the Window |
| Dialog outlet shows the top-level route's View | RouterView in a window without RouterWindows/RouterScope is depth 0 |
Modal route, or an independent stack |
| Modal dialog opens once, then throws on the next open | Window registered singleton |
AddTransient<TWindow>() |
| Dialog stays open after [X] | A leave guard refused (or is still awaiting) the navigation away, or your own Closing handler cancelled |
Intended - the route still claims the window; answer the guard |
Dialog closed, but its link does nothing (Duplicated) |
Parent record unnamed and no earlier history entry, so [X]'s Back went nowhere |
Give the modal route's parent a Name |
RouteSearchResult.To throws, or pushing it throws "Missing required param" |
Record has no Name, or needs a param the current location lacks |
Name it; only make param-free routes searchable |
| A left screen is never collected, or memory grows per navigation | Singleton View/ViewModel, or an undisposed CurrentRoute watch |
Transient registrations; dispose watches |
InvalidOperationException about thread/STA during Push |
Navigating from a background callback | Marshal through the Dispatcher |
Checklist - adding a screen
- Add the
RouteRecordtoAppRouteswith aName; nest it under the layout that hosts its outlet. - The View resolves its own
DataContext(aq:Setup.Enable/Setup.ViewModel) or the record pairs one (RouteRecord.ViewModel). AddTransientthe ViewModel only if it has constructor dependencies.- Read params in
IOnRouteEnter; addIOnRouteUpdateif the record can be reused across param changes; leave + update guards if it edits data. - Protect it with
Metaand the existing globalBeforeEach, not a new guard per screen. - Nav entry:
aqr:RouterLink.To+ theIsActivetrigger;RouteSearchEntryitems if searchable. A dialog:Window+ named outlet on a child record, transient window registration.
Changing the library itself: barbatos-package-authoring; keep the README "The Full Pipeline
Order" list, RouterNavigationGuardOrderTests and Router's remarks in step; tests per TFM via
barbatos-wpf-testing; both docs via barbatos-docs-sync.
Out of scope - do not add
Route-level keep-alive or KeepAlive/Transition around RouterView (above); a RouterLink
"open in a window" property (the window belongs on the record); a shipped search-box control
(RouteSearchIndex is the engine only); HTML5/hash history, scroll behaviour, Vue Router's
props binding, data loaders.
Changing Barbatos.Wpf.AquariusRouter itself
Load barbatos-package-authoring. Router never touches Window or Application, so keep new
pipeline logic headless; a new XAML control follows the Loaded-guard and leak/XAML-test rules in
.claude/rules/library-code.md; tests that call UseAquariusRouter save and restore
Router.Current; a change to the guard order changes RouterNavigationGuardOrderTests and the
README pipeline table together.
Related skills
barbatos-aquarius-view (the routed View/ViewModel, aq:Setup, lifecycle hooks, aq:Component),
barbatos-wpf-host (WpfAppBuilder, IWpfInitializeService, toast activation, global hotkeys),
barbatos-valee-form (the form inside a guarded screen), barbatos-templates (the
barbatos-wpf-app router scaffold), barbatos-wpf-testing, barbatos-package-authoring,
barbatos-docs-sync.