2. SusRouter —— 导航核心
优先使用 SusApp.UseRouter
该扩展位于 Runtime/SusAppRouterExtensions.cs——它会注册路由,并在 SusApp 完成初始化的正确时机挂载:
SusApp.Create(doc)
.UseTheme(SusTheme.Dark)
.UseRouter(new SusRouter(), r =>
{
r.Register("/", typeof(HomeScreen));
r.Register("/settings", typeof(SettingsScreen));
}, initialPath: "/")
.Run();使用 SusRouteBuilder 的声明式重载:
SusApp.Create(doc)
.UseRouter(new SusRouter(), routes => routes
.Route("/", typeof(HomeScreen)).Name("home")
.Route("/settings", typeof(SettingsScreen)),
initialPath: "/")
.Run();API
public class SusRouter
{
// Registration
public SusRouteRecord Register(string path, Type screenType, SusRouteConfig config = null);
public SusRouteRecord Resolve(string path);
public List<SusRouteRecord> ResolveChain(string path);
public bool HasRoute(string name);
public bool RemoveRoute(string name);
public IReadOnlyList<SusRouteRecord> Routes { get; }
// Navigation
public NavigationResult Push(string path, Dictionary<string, object> props = null);
public NavigationResult Replace(string path, Dictionary<string, object> props = null);
public NavigationResult Back();
public NavigationResult Forward();
public NavigationResult Go(int n);
public void NavigateWithTransition(string path, float duration = 0.3f);
// Named routes
public NavigationResult PushNamed(string name, Dictionary<string, string> pathParams = null, Dictionary<string, object> props = null);
public NavigationResult ReplaceNamed(string name, Dictionary<string, string> pathParams = null, Dictionary<string, object> props = null);
public string ResolvePath(string name, Dictionary<string, string> pathParams = null);
// Async navigation (runs BeforeEachAsync / BeforeResolveAsync, then sync pipeline)
public Task<NavigationResult> PushAsync(string path, Dictionary<string, object> props = null);
public Task<NavigationResult> ReplaceAsync(string path, Dictionary<string, object> props = null);
// Guards
public void BeforeEach(SusRouterGuard guard);
public void AfterEach(SusRouterAfterHook hook);
public void BeforeResolve(SusRouterGuard guard);
public void BeforeEachAsync(SusRouterAsyncGuard guard);
public void BeforeResolveAsync(SusRouterAsyncGuard guard);
// State
public Prop<SusRoute> CurrentRoute { get; }
public bool CanGoBack { get; }
public bool CanGoForward { get; }
public IReadOnlyList<SusRoute> History { get; }
public int HistoryIndex { get; }
public int RouteCount { get; }
public int MaxHistory { get; set; } = 100; // 0 or less = unlimited
public bool KeepAliveIgnoreQuery { get; set; } = false;
public event Action<NavigationError> OnNavigationError;
// Initialization
public void Init(OverlayHost overlayHost);
public NavigationResult Mount(VisualElement container, string initialPath, Dictionary<string, object> props = null);
public NavigationResult Mount(UIDocument uiDocument, string initialPath, Dictionary<string, object> props = null);
}
public enum NavigationResult
{
Success,
Aborted,
NotFound,
CantGoBack,
CantGoForward,
Busy, // concurrent navigation — request dropped (no queue)
}SusRouteConfig
public class SusRouteConfig
{
public string Name; // PushNamed / ReplaceNamed
public bool KeepAlive; // Off-DOM instance cache (see KeepAlive)
public List<string> Alias; // Alternative paths
public List<SusRouteRecord> Children; // Nested routes
public string Redirect; // Redirect target
public Dictionary<string, object> DefaultProps; // Default props
public Func<SusRoute, Dictionary<string, object>> PropsFn; // Functional props (Vue-style)
public Func<SusScreen> LazyFactory; // Lazy creation
public ISusRouteGuard Guard; // Per-route CanEnter/CanLeave
public SusRouterGuard BeforeEnter; // Function beforeEnter (after Guard.CanEnter)
public SusRouteTransition Transition; // Animation
public Dictionary<string, object> Meta; // Metadata
public bool CaseSensitive; // Default false
public bool Strict; // Trailing slash matters
}导航栈
基于游标的历史记录,通过 _historyIndex 实现。通过 MaxHistory(默认 100)限制大小:Push 溢出时,最老的条目会被淘汰。MaxHistory <= 0 表示无限制(dev 构建会对无界增长发出警告)。
- Push(/battle) → [.../home, .../about, .../battle] idx=2
- Back() → [.../home, .../about] idx=1
- Forward() → [.../home, .../about, .../battle] idx=2
- Replace(/settings) → [.../home, .../settings] idx=1
- Push 在 Back 之后会截断 forward 尾部
Guard 管线(10 个步骤)
Step 0: no-op (from.Path == to.Path) Step 0.5: beforeRouteUpdate Step 1: 当前屏幕上的 BeforeLeave Step 2: ISusRouteGuard.CanLeave Step 3: 全局 BeforeEach Step 4: ISusRouteGuard.CanEnter + SusRouteConfig.BeforeEnter Step 5: Left() Step 5.5: BeforeResolve(在创建屏幕之前) Step 6: 创建 / 复用 KeepAlive + BeforeEnter(屏幕) Step 7: 更新栈 Step 8: OnRouteChanged Step 9: Entered() Step 10: CurrentRoute + AfterEach
重入 —— Busy 丢弃(没有等待队列)
当一次导航正在进行时(_isNavigating),并发的 Push / Replace / Back / Forward 会返回 NavigationResult.Busy 并被丢弃。没有 _pendingNavigation 队列。
调用方(例如标签页处理逻辑)不应自动重试;应在当前导航完成后,把 UI 重新同步到 CurrentRoute。
var result = router.Push("/settings");
if (result == NavigationResult.Busy)
{
// Dropped — another navigation is in flight
}异步 guard
BeforeEachAsync / BeforeResolveAsync 只在 PushAsync / ReplaceAsync 中运行。同步的 Push/Replace/Back/Forward 会跳过它们(dev 构建会发出警告)。异步 guard 会先被 await,然后再运行同步管线。
命名路由
router.Register("/battle/:id", typeof(BattleScreen), new SusRouteConfig
{
Name = "battle",
Transition = SusRouteTransition.SlideLeft()
});
router.PushNamed("battle", new() { ["id"] = "42" }, new() { ["mode"] = "ranked" });
router.ReplaceNamed("battle", new() { ["id"] = "99" });
router.HasRoute("battle"); // true
router.RemoveRoute("battle"); // also clears aliases + child routes嵌套路由
router.Register("/settings", typeof(SettingsScreen), new SusRouteConfig
{
Children = new List<SusRouteRecord>
{
new SusRouteRecord("profile", typeof(ProfileScreen)),
new SusRouteRecord("privacy", typeof(PrivacyScreen)),
}
});Redirect、Alias、Query、Lazy
// Redirect
router.Register("/old-menu", typeof(MenuScreen), new SusRouteConfig { Redirect = "/main-menu" });
// Alias
router.Register("/main-menu", typeof(MenuScreen), new SusRouteConfig { Alias = new() { "/menu" } });
// Query
router.Push("/search?q=vue&page=2"); // CurrentRoute.Value.Query["q"] == "vue"
// Lazy
router.Register("/lazy", null, new SusRouteConfig { LazyFactory = () => new MyScreen() });KeepAlive(router 的 off-DOM 缓存)
SusRouteConfig.KeepAlive = true 会把屏幕实例缓存在 SusRouteView / SusScreenOutlet 中,位于 DOM 之外(分离 → 缓存 → 返回时重新挂载)。这不是 core 的 SusKeepAlive(display:none 包装器)。
- 离开:DOM 分离 →
Unmounted();不会调用Left()(实例保持存活)。 - 返回:从缓存中取回 →
Mounted()+Entered()。 - LRU 淘汰 /
ClearKeepAliveCache:OnScreenEvicted→Left()。 - 缓存键:
KeepAliveKey(route)(FullPath,若KeepAliveIgnoreQuery为真则为不含 query 的路径)。