|
| 1 | +using Microsoft.AspNetCore.Components; |
| 2 | +using ShellDocs.Core; |
| 3 | +using ShellDocs.Markdown; |
| 4 | + |
| 5 | +namespace ShellDocs.Components; |
| 6 | + |
| 7 | +// Populated by MarkdownContent on each page render, read by DocsLayout's chrome |
| 8 | +// (TOC, PrevNext, Breadcrumb) so those components don't need per-page wiring. |
| 9 | +public sealed class DocsPageState : IDisposable |
| 10 | +{ |
| 11 | + private readonly NavigationGraph _graph; |
| 12 | + private readonly NavigationManager _nav; |
| 13 | + |
| 14 | + public DocsPageState(NavigationGraph graph, NavigationManager nav) |
| 15 | + { |
| 16 | + _graph = graph; |
| 17 | + _nav = nav; |
| 18 | + _nav.LocationChanged += OnLocationChanged; |
| 19 | + } |
| 20 | + |
| 21 | + public RenderedDocument? Document { get; private set; } |
| 22 | + public NavigationNode? CurrentNode { get; private set; } |
| 23 | + public NavigationNode? Prev { get; private set; } |
| 24 | + public NavigationNode? Next { get; private set; } |
| 25 | + public IReadOnlyList<NavigationNode> Breadcrumbs { get; private set; } = Array.Empty<NavigationNode>(); |
| 26 | + |
| 27 | + public event Action? OnChange; |
| 28 | + |
| 29 | + public void SetDocument(RenderedDocument? document) |
| 30 | + { |
| 31 | + Document = document; |
| 32 | + Recompute(); |
| 33 | + } |
| 34 | + |
| 35 | + private void OnLocationChanged(object? sender, Microsoft.AspNetCore.Components.Routing.LocationChangedEventArgs e) |
| 36 | + => Recompute(); |
| 37 | + |
| 38 | + private void Recompute() |
| 39 | + { |
| 40 | + var path = new Uri(_nav.Uri).AbsolutePath; |
| 41 | + CurrentNode = _graph.ResolveByUrl(path); |
| 42 | + if (CurrentNode is null) |
| 43 | + { |
| 44 | + Prev = Next = null; |
| 45 | + Breadcrumbs = Array.Empty<NavigationNode>(); |
| 46 | + } |
| 47 | + else |
| 48 | + { |
| 49 | + (Prev, Next) = _graph.GetPrevNext(CurrentNode); |
| 50 | + Breadcrumbs = _graph.GetBreadcrumb(CurrentNode); |
| 51 | + } |
| 52 | + OnChange?.Invoke(); |
| 53 | + } |
| 54 | + |
| 55 | + public void Dispose() => _nav.LocationChanged -= OnLocationChanged; |
| 56 | +} |
0 commit comments