Skip to content

Commit

Permalink
Refactoring NavRouter
Browse files Browse the repository at this point in the history
  • Loading branch information
dyatlov-a committed Sep 24, 2024
1 parent 3fd08f8 commit 2b339a5
Show file tree
Hide file tree
Showing 18 changed files with 86 additions and 63 deletions.
9 changes: 6 additions & 3 deletions src/Inc.TeamAssistant.WebUI/Extensions/JsFunctions.cs
Original file line number Diff line number Diff line change
Expand Up @@ -9,12 +9,15 @@ public static IJsFunction<int> GetTimezone()
return new JsFunction<int>("window.browserJsFunctions.getTimezone", postAction: null, args: null);
}

public static IJsFunction<dynamic> ChangeUrl(this NavRouter navRouter, string url)
public static IJsFunction<dynamic> ChangeUrl(this NavRouter navRouter, NavRoute route)
{
ArgumentNullException.ThrowIfNull(navRouter);
ArgumentException.ThrowIfNullOrWhiteSpace(url);
ArgumentNullException.ThrowIfNull(route);

return new JsFunction<dynamic>("window.browserJsFunctions.changeUrl", () => navRouter.ChangeRoute(url), url);
return new JsFunction<dynamic>(
"window.browserJsFunctions.changeUrl",
() => navRouter.ChangeRoute(route),
route.ToString());
}

private sealed record JsFunction<TResult> : IJsFunction<TResult>
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -10,7 +10,7 @@
<div class="history__body">
@foreach (var item in _items)
{
<a href="@MoveToItem(item)" class="link link_dark history__item">
<a href="@CreateMoveToHistoryLink(item)" class="link link_dark history__item">
@item.AssessmentDate.ToString("dd-MM-yyyy") - @item.StoriesCount @Resources[Messages.GUI_Tasks]
</a>
}
Expand All @@ -24,13 +24,8 @@

private IReadOnlyCollection<AssessmentHistoryDto> _items = Array.Empty<AssessmentHistoryDto>();

private string MoveToItem(AssessmentHistoryDto historyItem)
{
if (historyItem is null)
throw new ArgumentNullException(nameof(historyItem));

return NavRouter.CreateRoute($"assessment-history/{TeamId:N}/{historyItem.AssessmentDate:yyyy-MM-dd}");
}
private string CreateMoveToHistoryLink(AssessmentHistoryDto historyItem)
=> NavRouter.CreateRoute($"assessment-history/{TeamId:N}/{historyItem.AssessmentDate:yyyy-MM-dd}");

protected override Task OnParametersSetAsync() => Load();

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -62,7 +62,7 @@
};

private LoadingState _state = LoadingState.Done();
private IReadOnlyCollection<SelectItem<string>> _breadcrumbs = Array.Empty<SelectItem<string>>();
private IReadOnlyCollection<SelectItem<NavRoute>> _breadcrumbs = Array.Empty<SelectItem<NavRoute>>();
private IReadOnlyCollection<StoryDto> _items = Array.Empty<StoryDto>();

protected override async Task OnParametersSetAsync()
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -87,7 +87,7 @@
};

private LoadingState _state = LoadingState.Done();
private IReadOnlyCollection<SelectItem<string>> _breadcrumbs = Array.Empty<SelectItem<string>>();
private IReadOnlyCollection<SelectItem<NavRoute>> _breadcrumbs = Array.Empty<SelectItem<NavRoute>>();
private GetActiveStoryResult _item = new(string.Empty, string.Empty, Story: null);
private IAsyncDisposable? _eventListener;

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -9,5 +9,5 @@

@code {
[Parameter, EditorRequired]
public IReadOnlyCollection<SelectItem<string>> Items { get; set; } = Array.Empty<SelectItem<string>>();
public IReadOnlyCollection<SelectItem<NavRoute>> Items { get; set; } = Array.Empty<SelectItem<NavRoute>>();
}
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,6 @@
@code {
protected override void OnInitialized()
{
NavRouter.NavigateTo($"/login?returnUrl={NavRouter.CurrentUrl}");
NavRouter.NavigateToRouteSegment($"login?returnUrl={NavRouter.CurrentUrl}");
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -24,7 +24,7 @@
{
<BotCard Icon="@typeof(BotIcon)" Name="@bot.Name">
<Content>
<a href="@MoveToDashboardLink(bot)" class="link link_dark">
<a href="@CreateMoveToDashboardLink(bot)" class="link link_dark">
@Resources[Messages.Dashboard_MoveToDashboard]
</a>
</Content>
Expand Down Expand Up @@ -78,11 +78,11 @@
private void MoveToEdit(Guid? botId)
{
var stage = Stage.CheckBot.ToString().ToLowerInvariant();
var link = botId.HasValue
var routeSegment = botId.HasValue
? $"constructor/{botId.Value:N}/{stage}"
: $"constructor/{stage}";

NavRouter.NavigateToRoute(link);
NavRouter.NavigateToRouteSegment(routeSegment);
}

private void MoveToRemove(BotDto bot)
Expand All @@ -92,7 +92,7 @@
_confirmDialog?.Open();
}

private string MoveToDashboardLink(BotDto bot)
private string CreateMoveToDashboardLink(BotDto bot)
{
var teamId = bot.Teams.FirstOrDefault()?.Id;

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -47,7 +47,7 @@
public StagesState StagesState { get; set; } = default!;

[Parameter, EditorRequired]
public Func<Stage, string> LinkFactory { get; set; } = default!;
public Func<Stage, NavRoute> LinkFactory { get; set; } = default!;

[Parameter, EditorRequired]
public Func<Stage?, Task> MoveToNext { get; set; } = default!;
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -37,7 +37,7 @@
public StagesState StagesState { get; set; } = default!;

[Parameter, EditorRequired]
public Func<Stage, string> LinkFactory { get; set; } = default!;
public Func<Stage, NavRoute> LinkFactory { get; set; } = default!;

[Parameter, EditorRequired]
public Func<Stage?, Task> MoveToNext { get; set; } = default!;
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -82,7 +82,7 @@
public StagesState StagesState { get; set; } = default!;

[Parameter, EditorRequired]
public Func<Stage, string> LinkFactory { get; set; } = default!;
public Func<Stage, NavRoute> LinkFactory { get; set; } = default!;

[Parameter, EditorRequired]
public Func<Stage?, Task> MoveToNext { get; set; } = default!;
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -152,7 +152,7 @@
public StagesState StagesState { get; set; } = default!;

[Parameter, EditorRequired]
public Func<Stage, string> LinkFactory { get; set; } = default!;
public Func<Stage, NavRoute> LinkFactory { get; set; } = default!;

[Parameter, EditorRequired]
public Func<Stage?, Task> MoveToNext { get; set; } = default!;
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -112,28 +112,28 @@
{
if (stage.HasValue)
{
var url = LinkFactory(stage.Value);
var route = LinkFactory(stage.Value);

_currentState = stage.Value;
StateHasChanged();

await JsRuntime.Execute(NavRouter.ChangeUrl(url));
await JsRuntime.Execute(NavRouter.ChangeUrl(route));
return;
}

var notificationsService = ServiceProvider.GetRequiredService<INotificationsService>();

notificationsService.Publish(Notification.Info(Resources[Messages.GUI_DataRefreshed]));

NavRouter.NavigateToRoute("constructor");
NavRouter.NavigateToRouteSegment("constructor");
}

private string LinkFactory(Stage stage)
private NavRoute LinkFactory(Stage stage)
{
var link = _stagesState.Id.HasValue
var routeSegment = _stagesState.Id.HasValue
? $"constructor/{_stagesState.Id.Value:N}/{stage}"
: $"constructor/{stage}";

return NavRouter.CreateRoute(link.ToLowerInvariant());
return NavRouter.CreateRoute(routeSegment.ToLowerInvariant());
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -21,7 +21,7 @@
Title="@Resources[Messages.Dashboard_AssessmentDate]"
Sortable="true"
SortBy="GridSort<AssessmentHistoryDto>.ByAscending(t => t.AssessmentDate)">
<a href="@MoveToItem(context.AssessmentDate)" class="link link_light">
<a href="@CreateMoveToHistoryLink(context.AssessmentDate)" class="link link_light">
@context.AssessmentDate.ToString("dd-MM-yyyy")
</a>
</TemplateColumn>
Expand All @@ -42,7 +42,7 @@
}
</div>
<div class="component-actions">
<a href="@GetAssessmentSessionUrl()" class="button button_dark">
<a href="@CreateAssessmentSessionLink()" class="button button_dark">
@Resources[Messages.Dashboard_GoToCurrentSessionButtonText]
</a>
</div>
Expand Down Expand Up @@ -90,13 +90,15 @@
});
}

private string GetAssessmentSessionUrl() => NavRouter.CreateRoute($"assessment-session/{TeamId:N}");

private string MoveToItem(DateOnly date) => NavRouter.CreateRoute($"assessment-history/{TeamId:N}/{date:yyyy-MM-dd}");
private string CreateAssessmentSessionLink() => NavRouter.CreateRoute($"assessment-session/{TeamId:N}");

private string CreateMoveToHistoryLink(DateOnly date)
=> NavRouter.CreateRoute($"assessment-history/{TeamId:N}/{date:yyyy-MM-dd}");

private async Task Changed(DateOnly date)
{
_date = date;

await Load();
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -15,7 +15,6 @@
@inject IBotService BotService
@inject ResourcesManager Resources
@inject RequestProcessor RequestProcessor
@inject IJSRuntime JsRuntime
@inject NavRouter NavRouter

<MetaDataModule
Expand Down Expand Up @@ -117,18 +116,18 @@

private Type ToWidgetType(string type) => _widgetsLookup[type];

private async Task ChangeTeamContext((Guid? BotId, Guid? TeamId) botContext)
private void ChangeTeamContext((Guid? BotId, Guid? TeamId) botContext)
{
var url = (botContext.BotId.HasValue, botContext.TeamId.HasValue) switch
var routeSegment = (botContext.BotId.HasValue, botContext.TeamId.HasValue) switch
{
(true, true) => $"dashboard/{botContext.BotId:N}/{botContext.TeamId:N}",
(true, false) => $"dashboard/{botContext.BotId:N}",
_ => "dashboard"
};

_botId = botContext.BotId;
_teamId = botContext.TeamId;

await JsRuntime.Execute(NavRouter.ChangeUrl(url));
NavRouter.NavigateToRouteSegment(routeSegment);
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -37,7 +37,7 @@
StateHasChanged();
}

private void MoveTo(string path) => NavRouter.NavigateTo(path, forceLoad: true);
private void MoveTo(string path) => NavRouter.NavigateToPath(path);

public void Dispose() => _routerScope?.Dispose();
}
8 changes: 3 additions & 5 deletions src/Inc.TeamAssistant.WebUI/Features/Layouts/MainNavbar.razor
Original file line number Diff line number Diff line change
Expand Up @@ -26,10 +26,10 @@
<a href="@MainUrl" class="link navbar__item"><HomeIcon Size="40px" /></a>
<CultureSelector/>
<div class="navbar__divider"></div>
@if (!CurrentUrl.Contains("/login"))
@if (!NavRouter.CurrentUrl.Contains("/login"))
{
<a
href="@NavRouter.CreateRoute($"login?returnUrl={CurrentUrl}")"
href="@NavRouter.CreateRoute($"login?returnUrl={NavRouter.CurrentUrl}")"
class="link link_light navbar__item">
@Resources[Messages.Navigation_Login]
</a>
Expand All @@ -42,10 +42,8 @@
@code {
private IDisposable? _routerScope;

private string CurrentUrl => NavRouter.CurrentUrl;

private string MainUrl => NavRouter.CreateRoute(null);
private string LogoutUrl => $"accounts/logout?returnUrl={CurrentUrl}";
private string LogoutUrl => $"accounts/logout?returnUrl={NavRouter.CurrentUrl}";

protected override void OnInitialized()
{
Expand Down
21 changes: 21 additions & 0 deletions src/Inc.TeamAssistant.WebUI/Services/ClientCore/NavRoute.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,21 @@
using Inc.TeamAssistant.Primitives.Languages;

namespace Inc.TeamAssistant.WebUI.Services.ClientCore;

public sealed record NavRoute(
LanguageId? LanguageId,
string RouteSegment)
{
public override string ToString()
{
var languageSegment = LanguageId is null
? string.Empty
: $"/{LanguageId.Value}";

return RouteSegment.StartsWith('/')
? $"{languageSegment}{RouteSegment}"
: $"{languageSegment}/{RouteSegment}";
}

public static implicit operator string(NavRoute counter) => counter.ToString();
}
39 changes: 22 additions & 17 deletions src/Inc.TeamAssistant.WebUI/Services/ClientCore/NavRouter.cs
Original file line number Diff line number Diff line change
Expand Up @@ -31,28 +31,36 @@ public string GetRouteWithoutLanguage()
return routeWithoutLanguage;
}

public string CreateRoute(string? relativeUrl)
public NavRoute CreateRoute(string? routeSegment)
{
var link = string.IsNullOrWhiteSpace(relativeUrl) ? "/" : $"/{relativeUrl}";
var link = string.IsNullOrWhiteSpace(routeSegment) ? "/" : routeSegment;
var languageContext = _renderContext.GetLanguageContext();
var selectedLanguage = languageContext.Selected ? languageContext.CurrentLanguage : null;

return languageContext.Selected
? $"/{languageContext.CurrentLanguage.Value}{link}"
: link;
return new NavRoute(selectedLanguage, link);
}

public void NavigateTo(string uri, bool forceLoad = false, bool replace = false)
public void NavigateToPath(string uri)
{
ArgumentException.ThrowIfNullOrWhiteSpace(uri);

_navigationManager.NavigateTo(uri, forceLoad, replace);
_navigationManager.NavigateTo(uri, forceLoad: true);
}

public void NavigateToRoute(string uri, bool forceLoad = false, bool replace = false)
public void NavigateToRouteSegment(string routeSegment)
{
ArgumentException.ThrowIfNullOrWhiteSpace(uri);
ArgumentException.ThrowIfNullOrWhiteSpace(routeSegment);

var route = CreateRoute(routeSegment);

_navigationManager.NavigateTo(CreateRoute(uri), forceLoad, replace);
NavigateToRoute(route);
}

public void NavigateToRoute(NavRoute route)
{
ArgumentNullException.ThrowIfNull(route);

_navigationManager.NavigateTo(route);
}

public IDisposable OnRouteChanged(Action onRouteChanged)
Expand All @@ -62,11 +70,11 @@ public IDisposable OnRouteChanged(Action onRouteChanged)
return new RouterScope(() => _onRouteChanged -= onRouteChanged);
}

public void ChangeRoute(string uri)
public void ChangeRoute(NavRoute route)
{
ArgumentNullException.ThrowIfNull(uri);
ArgumentNullException.ThrowIfNull(route);

ChangeRouteCore(_navigationManager.ToAbsoluteUri(uri).ToString());
ChangeRouteCore(_navigationManager.ToAbsoluteUri(route).ToString());
}

private void ChangeRouteCore(string uri)
Expand All @@ -79,8 +87,5 @@ private void ChangeRouteCore(string uri)

private void OnLocationChanged(object? sender, LocationChangedEventArgs e) => ChangeRouteCore(e.Location);

public void Dispose()
{
_navigationManager.LocationChanged -= OnLocationChanged;
}
public void Dispose() => _navigationManager.LocationChanged -= OnLocationChanged;
}

0 comments on commit 2b339a5

Please sign in to comment.