К содержимому

2. SusRouter — ядро навигации

Предпочитайте SusApp.UseRouter

Расширение в Runtime/SusAppRouterExtensions.cs — регистрирует маршруты и монтирует в нужной точке финализации SusApp:

csharp
SusApp.Create(doc)
    .UseTheme(SusTheme.Dark)
    .UseRouter(new SusRouter(), r =>
    {
        r.Register("/", typeof(HomeScreen));
        r.Register("/settings", typeof(SettingsScreen));
    }, initialPath: "/")
    .Run();

Декларативная перегрузка с SusRouteBuilder:

csharp
SusApp.Create(doc)
    .UseRouter(new SusRouter(), routes => routes
        .Route("/", typeof(HomeScreen)).Name("home")
        .Route("/settings", typeof(SettingsScreen)),
        initialPath: "/")
    .Run();

API

csharp
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

csharp
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 шагов)

Шаг 0: no-op (from.Path == to.Path) Шаг 0.5: beforeRouteUpdate Шаг 1: BeforeLeave на текущем экране Шаг 2: ISusRouteGuard.CanLeave Шаг 3: глобальный BeforeEach Шаг 4: ISusRouteGuard.CanEnter + SusRouteConfig.BeforeEnter Шаг 5: Left() Шаг 5.5: BeforeResolve (ДО создания экрана) Шаг 6: Create / переиспользование KeepAlive + BeforeEnter (экран) Шаг 7: обновление стека Шаг 8: OnRouteChanged Шаг 9: Entered() Шаг 10: CurrentRoute + AfterEach

Реентерабельность — сброс Busy (без очереди ожидания)

Пока навигация в процессе (_isNavigating), конкурирующий Push / Replace / Back / Forward возвращает NavigationResult.Busy и отбрасывается. Очереди _pendingNavigation нет.

Вызывающему коду (например, обработчикам табов) не следует авто-повторять запрос; синхронизируйте UI с CurrentRoute после завершения активной навигации.

csharp
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-ы дожидаются выполнения первыми, затем идёт синхронный конвейер.

Именованные маршруты

csharp
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

Вложенные маршруты

csharp
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

csharp
// 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 (кэш роутера вне DOM)

SusRouteConfig.KeepAlive = true кэширует инстанс экрана в SusRouteView / SusScreenOutlet вне DOM (detach → кэш → повторный attach при возврате). Это не core SusKeepAlive (обёртка display:none).

  • Уход: DOM-detach → Unmounted(); Left() не вызывается (инстанс остаётся живым).
  • Возврат: извлечение из кэша → Mounted() + Entered().
  • LRU-вытеснение / ClearKeepAliveCache: OnScreenEvictedLeft().
  • Ключ кэша: KeepAliveKey(route) (FullPath, либо путь без query, если KeepAliveIgnoreQuery).