Implements file system path existence check

This commit is contained in:
BinaryAlley committed 2024-09-20 19:40:17 +03:00
1 parent dc47386726
commit c29d829c91
16 files changed
+452 -125

No files matched your search

@@ -0,0 +1,620 @@
@using Lumina.Presentation.Web.Common.Api
@using Lumina.Presentation.Web.Common.Enums.FileSystem
@using Lumina.Presentation.Web.Common.Enums.Notifications
@using Lumina.Presentation.Web.Common.Exceptions
@using Lumina.Presentation.Web.Common.Models.Common
@using Lumina.Presentation.Web.Common.Models.FileManagement
@using Lumina.Presentation.Web.Common.Models.UI
@using Lumina.Presentation.Web.Common.Services
@using Microsoft.AspNetCore.Components
@using System.Text.Json
@using System.Text
@implements IDisposable
@inject IJSRuntime JSRuntime
@inject IApiHttpClient _apiHttpClient
@inject INotificationService _notificationService
<div id="file-system-browser-dialog" class="container-background above-modal">
<div id="file-system-browser-content">
<div id="file-system-browser-header">
<div id="file-system-browser-shine-spark"></div>
<div id="file-system-browser-shine-effect"></div>
<div id="file-system-browser-header-navigation-container">
<!--File System Navigator-->
<div id="navigator-view-mode-container">
<img src="images/ui/list.png" id="navigator-list-view" alt="List View" title="List View" @onclick="@(() => ChangeViewModeAsync(FileSystemViewMode.List))" />
<img src="images/ui/details.png" id="navigator-details-view" alt="Details View" title="Details View" @onclick="@(() => ChangeViewModeAsync(FileSystemViewMode.Details))" />
<img src="images/ui/small-icons.png" id="navigator-small-icons-view" alt="Small Icons View" title="Small Icons View" @onclick="@(() => ChangeIconSize(FileSystemIconSize.Small))" />
<img src="images/ui/medium-icons.png" id="navigator-medium-icons-view" alt="Medium Icons View" title="Medium Icons View" @onclick="@(() => ChangeIconSize(FileSystemIconSize.Medium))" />
<img src="images/ui/large-icons.png" id="navigator-large-icons-view" alt="Large Icons View" title="Large Icons View" @onclick="@(() => ChangeIconSize(FileSystemIconSize.Large))" />
<img src="images/ui/extra-large-icons.png" id="navigator-extra-large-icons-view" alt="Extra Large Icons View" title="Extra Large Icons View" @onclick="@(() => ChangeIconSize(FileSystemIconSize.ExtraLarge))" />
</div>
<div id="navigator-navigation-controls-container">
<div id="navigator-history">
<img src="images/ui/back.svg" class="navigation-icon" alt="Back" title="Back" />
<img src="images/ui/forward.svg" class="navigation-icon" alt="Forward" title="Forward" />
<img src="images/ui/up.svg" class="navigation-icon" alt="Up One Level" title="Up One Level" />
</div>
<img src="images/ui/toggle-tree-view.svg" id="navigator-toggle-tree-view-button" alt="Toggle Tree View" title="Toggle Tree View" class="navigator-icon" />
<img src="images/ui/toggle-thumbnails.svg" id="navigator-toggle-thumbnails-button" alt="Toggle Thumbnails" title="Toggle Thumbanils" class="navigator-icon" />
<img src="images/ui/toggle-hidden.svg" id="navigator-toggle-hidden-button" alt="Toggle Hidden Files" title="Toggle Hidden Files" class="navigator-icon" />
</div>
<div id="navigator-address-bar-container">
<div id="navigator-address-bar-group">
@if (isNavigationPathEditMode)
{
<EnlightenmentInput CssClass="navigator-address-bar-input" Type="text" @bind-Value="@Path" Name="navigator-address-bar-input"
AutoComplete="true" OnEnterPressed="ExitNavigationPathEditModeAsync" OnEscapePressed="HandleNavigatorInputEscapePressed" Id="navigator-address-bar-input" />
}
else
{
<div id="navigator-address-bar">
<ul id="navigator-path-segments" @onclick="EnterNavigationPathEditModeAsync">
@if (pathSegments?.Length > 0)
{
for (int i = 0; i < pathSegments.Length; i++)
{
var localIndex = i; // capture the current index in a local variable, otherwise it would be evaluated when the loop ends
var pathSegment = pathSegments[i];
<li id="path-segment-@i">
<div class="navigator-combobox inline-block">
<div class="shine-effect" style="top: 1px;"></div>
<input type="checkbox" class="navigator-toggle-checkbox" id="segment-toggle-@i" checked="@(expandedPathSegmentIndex == localIndex)"
@onchange="@(e => ToggleNavigatorPathSegment(e, localIndex))" @onclick:stopPropagation />
<label class="navigator-toggle" for="segment-toggle-@i" @onclick:stopPropagation>
<span class="navigator-selected-text" @onclick:stopPropagation>@pathSegment.Path</span>
<span class="navigator-arrow" @onclick:stopPropagation></span>
</label>
</div>
</li>
}
}
</ul>
</div>
}
</div>
<EnlightenmentButton CssClass="navigator-edit-path-button" IsConfirmButton="false" Height="28" Width="35" OnClick="EnterNavigationPathEditModeAsync">
<img src="images/ui/edit.svg" id="navigator-edit-icon" alt="Edit Path" title="Edit Path" />
</EnlightenmentButton>
<EnlightenmentButton CssClass="navigator-navigate-button" Height="28" Width="35" OnClick="ExitNavigationPathEditModeAsync">
<img src="images/ui/check.svg" id="navigator-navigate-icon" alt="Navigate" title="Navigate" />
</EnlightenmentButton>
<EnlightenmentButton CssClass="file-system-browser-content-new-directory" IsConfirmButton="false" Width="35" Height="28">
<img src="images/ui/new-directory.svg" id="navigator-new-directory-icon" alt="New Directory" title="New Directory" />
</EnlightenmentButton>
<EnlightenmentButton CssClass="file-system-browser-content-favorite-directory" IsConfirmButton="false" Width="35" Height="28">
<img src="images/ui/favorite-star.svg" class="navigation-icon favorite-unselected" alt="Favorite directory" title="Favorite directory" />
</EnlightenmentButton>
</div>
<!--End File System Navigator-->
</div>
</div>
<div id="file-system-browser-file-system-container">
<!--File System Tree View-->
<div id="file-system-browser-file-system-treeview-container">
<div id="file-system-browser-file-system-treeview">
<div class="treeview">
@foreach (FileSystemTreeNodeModel node in treeViewRootNodes)
{
<FileSystemTreeViewNode Node="node" OnExpandToggle="ToggleTreeViewNode" OnNodeSelected="NavigateToPathAsync" selectedNodePath="@selectedNodePath" />
}
</div>
</div>
<EnlightenmentCombobox CssClass="file-system-browser-file-system-sources" Items="null" @bind-SelectedItem="selectedValue" />
</div>
<!--End File System Tree View-->
<div id="file-system-browser-file-system-directories-container">
<div id="file-system-browser-file-system-directories">
<div id="file-system-browser-file-system-explorer-container" class="scroll-@(viewMode is FileSystemViewMode.List ? "horizontal" : "vertical")">
<div id="file-system-browser-file-system-explorer-details-header" style="height: @(viewMode is FileSystemViewMode.Details ? 20 : 0)px;">
<span>Name</span>
</div>
<div id="file-system-browser-file-system-explorer" class="@viewMode.ToString().ToLower()" style="flex-direction: @(viewMode is FileSystemViewMode.List or FileSystemViewMode.Details ? "column" : "row");">
@foreach (FileSystemItemModel fileSystemItem in fileSystemItems)
{
string iconSizeClass = "list-icons";
if (viewMode == FileSystemViewMode.Details)
iconSizeClass = "details-icons";
else if (viewMode == FileSystemViewMode.Icons)
{
if (iconSize == FileSystemIconSize.Small)
iconSizeClass = "small-icons";
else if (iconSize == FileSystemIconSize.Medium)
iconSizeClass = "medium-icons";
else if (iconSize == FileSystemIconSize.Large)
iconSizeClass = "large-icons";
else if (iconSize == FileSystemIconSize.ExtraLarge)
iconSizeClass = "extra-large-icons";
}
string itemType = fileSystemItem is FileModel ? "file" : "directory";
<div class="e @iconSizeClass" data-path="@fileSystemItem.Path" data-type="@itemType">
<div class="icon"><img src="/images/icons/Lyra/@(itemType).svg"></div>
<div class="text"><span class="@(itemType == "directory" ? "d" : "f") t">@fileSystemItem.Name</span></div>
<div class="date-modified @(itemType == "directory" ? "d" : "f")" style="display: none;">@fileSystemItem.DateModified</div>
<div class="size @(itemType == "directory" ? "d" : "f")" style="display: none;"> @(itemType == "file" ? (fileSystemItem as FileModel)!.Size : 0)</div>
</div>
}
</div>
</div>
</div>
</div>
</div>
<div id="file-system-browser-actions-container">
<div id="file-system-browser-actions-path-container">
<label class="text-light-one">Directory</label>
<EnlightenmentInput Type="text" Name="selected-directory" IsReadOnly="true" AutoComplete="true" />
</div>
<div id="file-system-browser-actions">
<EnlightenmentButton IsConfirmButton="false">Cancel</EnlightenmentButton>
<EnlightenmentButton>Open</EnlightenmentButton>
</div>
</div>
</div>
@* <div id="divModal"></div>
<label class="text-light-one">Enter new directory name:</label>
<EnlightenmentInput Type="text" Name="newDirectoryName" AutoComplete="true" />
<EnlightenmentButton IsConfirmButton="false">Cancel</EnlightenmentButton>
<EnlightenmentButton>Confirm</EnlightenmentButton> *@
</div>
<!--The drop down for the navigator path segments needs to be absolute, such that it is not affected by the parent clipping-->
@if (showPathSegmentDowpDown && expandedPathSegmentIndex.HasValue && pathSegmentsSubdirectoriesCache.ContainsKey(expandedPathSegmentIndex.Value))
{
<div class="navigator-dropdown opened" id="navigatorDropdown" data-path-segment-id="path-segment-@expandedPathSegmentIndex">
@foreach (var directory in pathSegmentsSubdirectoriesCache[expandedPathSegmentIndex.Value])
{
<div class="navigator-option" data-path="@directory.Path" @onclick="@(() => NavigateToPathAsync(directory.Path))">@directory.Name</div>
}
</div>
}
@code {
[Parameter] public string? Path { get; set; }
[Parameter] public bool IncludeFiles { get; set; }
public EventCallback<string> OnNodeSelected { get; set; }
private List<FileSystemTreeNodeModel> treeViewRootNodes = [];
private List<FileSystemItemModel> fileSystemItems = [];
private FileSystemTypeModel fileSystemType = null!;
private ComboboxItem<string>? selectedValue;
private PathSegmentModel[]? pathSegments;
private string pathSeparator = "/";
private string? selectedNodePath;
private string? _path;
private bool showPathSegmentDowpDown;
private bool isNavigationPathEditMode;
private int? expandedPathSegmentIndex;
private FileSystemViewMode viewMode = FileSystemViewMode.List; // TODO: take from config
private FileSystemIconSize iconSize;
private Dictionary<int, List<FileSystemTreeNodeModel>> pathSegmentsSubdirectoriesCache = [];
private DotNetObjectReference<FileSystemBrowser>? reference;
/// <summary>
/// Initializes the component.
/// </summary>
protected override async Task OnInitializedAsync()
{
await GetFileSystemPropertiesAsync().ConfigureAwait(false);
if (Path is not null)
await NavigateToPathAsync(Path).ConfigureAwait(false);
await ChangeViewModeAsync(viewMode).ConfigureAwait(false);
// make the navigator path segments horizontally scrollable
await JSRuntime.InvokeVoidAsync("addHorizontalScrolling", "navigator-address-bar").ConfigureAwait(false);
}
/// <summary>
/// Handles the event risen after the component was rendered.
/// </summary>
/// <param name="firstRender">Indicates whether this is the first render or not.</param>
protected override async Task OnAfterRenderAsync(bool firstRender)
{
// on first render, subscribe this component to the javascript function that handles window clicks
if (firstRender)
{
reference = DotNetObjectReference.Create(this);
await JSRuntime.InvokeVoidAsync("windowClickHandler", reference);
}
await base.OnAfterRenderAsync(firstRender);
}
/// <summary>
/// Handles the window click event.
/// </summary>
/// <param name="e">The event arguments.</param>
[JSInvokable]
public void OnWindowClick(dynamic e)
{
// parse the event args and get the initiator of the event
var jsonElement = (JsonElement)e;
string? sender = jsonElement.GetProperty("sender").GetString();
// ignore the event if it was initiated by a path segment (don't collapse an element that was just expanded)
if (showPathSegmentDowpDown && sender is not null && !sender.Contains("segment-toggle-"))
{
// otherwise, collapse all path segments
showPathSegmentDowpDown = false;
expandedPathSegmentIndex = null;
}
// exit navigator path edit mode when clicking anywhere outside of it, or on elements that should not exit it
if (sender is null || (sender is not null && !sender.Contains("navigator-path-segments") && !sender.Contains("navigator-edit-icon") && !sender.Contains("navigator-address-bar-input")))
isNavigationPathEditMode = false;
StateHasChanged();
}
/// <summary>
/// Expands or collapses a node in the tree view.
/// </summary>
/// <param name="node">The node to expand or collapse.</param>
private async Task ToggleTreeViewNode(FileSystemTreeNodeModel node)
{
if (!node.IsExpanded && !node.ChildrenLoaded)
{
node.Children = new List<FileSystemTreeNodeModel>();
node.IsExpanded = true;
StateHasChanged();
if (await CheckPathAsync(node.Path).ConfigureAwait(false))
{
try
{
await foreach (FileSystemTreeNodeModel? childNode in _apiHttpClient.GetAsyncEnumerable<FileSystemTreeNodeModel>($"directories/get-tree-directories?path={Uri.EscapeDataString(node.Path)}").ConfigureAwait(false))
{
if (childNode is not null)
{
node.Children.Add(childNode);
StateHasChanged();
}
}
if (IncludeFiles)
{
await foreach (FileSystemTreeNodeModel? childNode in _apiHttpClient.GetAsyncEnumerable<FileSystemTreeNodeModel>($"files/get-tree-files?path={Uri.EscapeDataString(node.Path)}").ConfigureAwait(false))
{
if (childNode is not null)
{
node.Children.Add(childNode);
StateHasChanged();
}
}
}
}
catch (ApiException ex)
{
HandleApiException(ex);
}
finally
{
node.ChildrenLoaded = true;
}
}
}
else
node.IsExpanded = !node.IsExpanded;
StateHasChanged();
}
/// <summary>
/// Handles the change event.
/// </summary>
/// <param name="e">The event arguments.</param>
private async Task ToggleNavigatorPathSegment(ChangeEventArgs e, int toggledIndex)
{
// uncheck all other path segment checkboxes
await JSRuntime.InvokeVoidAsync("uncheckAllExcept", $"segment-toggle-{toggledIndex}").ConfigureAwait(false);
// check if the checkbox is checked
bool isChecked = (bool)e.Value!;
// if it's checked, get the subdirectories for the toggled path segment
if (isChecked && pathSegments?.Length > 0)
{
// initialize the path with the first segment
string concatenatedPath = pathSegments[0].Path;
// concatenate only up to the toggled index
for (int i = 1; i <= toggledIndex; i++)
concatenatedPath = $"{(concatenatedPath != pathSeparator ? concatenatedPath : string.Empty)}{pathSeparator}{pathSegments[i].Path}";
string parentConcatenatedPath = concatenatedPath;
try
{
if (concatenatedPath != pathSeparator) // on UNIX, dont get the parent, if we are at root path
{
List<PathSegmentModel> parentLocation = await _apiHttpClient.GetAsync<List<PathSegmentModel>>($"path/get-path-parent?path={Uri.EscapeDataString(concatenatedPath)}").ConfigureAwait(false);
parentConcatenatedPath = parentLocation[0].Path;
for (int i = 1; i < parentLocation.Count; i++)
parentConcatenatedPath = $"{(parentConcatenatedPath != pathSeparator ? parentConcatenatedPath : string.Empty)}{pathSeparator}{pathSegments[i].Path}";
}
}
catch (ApiException ex)
{
HandleApiException(ex);
}
if (!concatenatedPath.EndsWith(pathSeparator))
concatenatedPath += pathSeparator;
// fetch directories for the expanded path segment
List<FileSystemTreeNodeModel> directories = [
new() { Path = concatenatedPath, Name = ".", }, // current directory
new() { Path = parentConcatenatedPath, Name = ".." } // parent directory
];
// add the rest of the subdirectories of the expanded path node
await foreach (FileSystemTreeNodeModel? directory in _apiHttpClient.GetAsyncEnumerable<FileSystemTreeNodeModel>($"directories/get-tree-directories?path={Uri.EscapeDataString(concatenatedPath)}").ConfigureAwait(false))
if (directory is not null)
directories.Add(directory);
// store the directories for this segment
pathSegmentsSubdirectoriesCache[toggledIndex] = directories;
expandedPathSegmentIndex = toggledIndex;
showPathSegmentDowpDown = true;
StateHasChanged();
// invoke the javascript function that positions the dropdown underneath the toggled path segment
await JSRuntime.InvokeVoidAsync("updateDropdownPosition", $"path-segment-{toggledIndex}").ConfigureAwait(false);
}
else
{
expandedPathSegmentIndex = null;
showPathSegmentDowpDown = false;
StateHasChanged();
}
}
/// <summary>
/// Handles the selection of a node in the tree view.
/// </summary>
/// <param name="path">The path of the selected node.</param>
private async Task NavigateToPathAsync(string path)
{
selectedNodePath = path;
if (await CheckPathAsync(path).ConfigureAwait(false))
{
_path = path;
await GetNavigatorPathAsync(path).ConfigureAwait(false);
await GetFileSystemTreeAsync(path).ConfigureAwait(false);
await GetFileSystemItemsAsync(path).ConfigureAwait(false);
}
else
Path = _path;
await OnNodeSelected.InvokeAsync(path).ConfigureAwait(false);
}
/// <summary>
/// Gets the properties of the file system.
/// </summary>
private async Task GetFileSystemPropertiesAsync()
{
fileSystemType = await _apiHttpClient.GetAsync<FileSystemTypeModel>("file-system/get-type").ConfigureAwait(false);
// ask the API server for the system path separator
PathSeparatorModel apiPathSeparator = await _apiHttpClient.GetAsync<PathSeparatorModel>("path/get-path-separator").ConfigureAwait(false);
pathSeparator = apiPathSeparator.Separator; // TODO: handle error
}
/// <summary>
/// Checks if the specified path is a valid file system path.
/// </summary>
/// <param name="path">The path to check.</param>
/// <returns><see langword="true"/> if the specified path is valid, <see langword="false"/> otherwise.</returns>
private async Task<bool> CheckPathAsync(string path)
{
try
{
var isPathValidResponse = await _apiHttpClient.GetAsync<PathValidModel>($"path/validate?path={Uri.EscapeDataString(path)}").ConfigureAwait(false);
if (!isPathValidResponse.IsValid)
{
_notificationService.Show("Specified path is not valid!", NotificationType.Error); // TODO: should ask error message from server when translation is implemented
Path = _path;
}
PathExistsModel pathExistsResponse = await _apiHttpClient.GetAsync<PathExistsModel>($"path/check-path-exists?path={Uri.EscapeDataString(path)}").ConfigureAwait(false);
if (!pathExistsResponse.Exists)
{
_notificationService.Show("Specified path does not exist!", NotificationType.Error); // TODO: should ask error message from server when translation is implemented
return false;
}
return isPathValidResponse.IsValid;
}
catch (ApiException ex)
{
HandleApiException(ex);
return false;
}
}
/// <summary>
/// Gets the navigator path segments.
/// </summary>
/// <param name="path">The path for which to get the navigator path segments.</param>
private async Task GetNavigatorPathAsync(string path)
{
pathSegments = await _apiHttpClient.GetAsync<PathSegmentModel[]>($"path/split?path={Uri.EscapeDataString(path!)}").ConfigureAwait(false);
StateHasChanged();
}
/// <summary>
/// Gets the file system items that are displayed in the file system tree view pane.
/// </summary>
/// <param name="path">The path for which to get the file system items.</param>
private async Task GetFileSystemTreeAsync(string path)
{
treeViewRootNodes = [];
// on Windows, ask the list of drives
if (fileSystemType?.PlatformType == PlatformType.Windows)
{
List<FileSystemTreeNodeModel> drives = await _apiHttpClient.GetAsync<List<FileSystemTreeNodeModel>>("drives/get-drives").ConfigureAwait(false);
treeViewRootNodes.AddRange(drives);
}
else
{
// on UNIX, just add the root "/"
treeViewRootNodes.Add(new FileSystemTreeNodeModel()
{
Path = pathSeparator!,
IsExpanded = true,
ItemType = FileSystemItemType.Root,
Name = pathSeparator!
});
}
// if there was an initial path saved from a previous session, load the full tree up to that initial path
// ask the whole tree for the saved path
List<FileSystemTreeNodeModel> initialTree = await _apiHttpClient.GetAsync<List<FileSystemTreeNodeModel>>($"directories/get-directory-tree?path={Uri.EscapeDataString(path!)}&includeFiles={IncludeFiles}").ConfigureAwait(false);
if (initialTree is not null && initialTree.Count > 0)
{
// take the root of the retrieved tree, and try to match it against a drive in the retrieved list of drives, on Windows; on Unix, add it as the unique root path
PathSegmentModel pathRoot = await _apiHttpClient.GetAsync<PathSegmentModel>($"path/get-path-root?path={Uri.EscapeDataString(path!)}").ConfigureAwait(false);
if (fileSystemType?.PlatformType == PlatformType.Windows)
{
FileSystemTreeNodeModel? driveNode = treeViewRootNodes.FirstOrDefault(drive => drive.Path.Equals(pathRoot.Path, StringComparison.OrdinalIgnoreCase));
// if a drive was matched, make the retrieved tree a child of it
if (driveNode is not null)
{
int index = treeViewRootNodes.IndexOf(driveNode);
treeViewRootNodes[index] = initialTree[0];
}
}
else
treeViewRootNodes[0] = initialTree[0];
}
}
/// <summary>
/// Retrieves the files and directories for the specified path.
/// </summary>
/// <param name="path">The path for which to get the files and directories.</param>
private async Task GetFileSystemItemsAsync(string path)
{
fileSystemItems.Clear();
try
{
await foreach (DirectoryModel? directory in _apiHttpClient.GetAsyncEnumerable<DirectoryModel>($"directories/get-directories?path={Uri.EscapeDataString(path)}").ConfigureAwait(false))
{
if (directory is not null)
{
fileSystemItems.Add(directory);
StateHasChanged();
}
}
if (IncludeFiles)
{
await foreach (FileModel? file in _apiHttpClient.GetAsyncEnumerable<FileModel>($"files/get-files?path={Uri.EscapeDataString(path)}").ConfigureAwait(false))
{
if (file is not null)
{
fileSystemItems.Add(file);
StateHasChanged();
}
}
}
}
catch (ApiException ex)
{
HandleApiException(ex);
}
}
/// <summary>
/// Changes the current file system explorer view.
/// </summary>
/// <param name="newViewMode">The new explorer view to change to.</param>
private async Task ChangeViewModeAsync(FileSystemViewMode newViewMode)
{
viewMode = newViewMode;
if (viewMode == FileSystemViewMode.List)
await JSRuntime.InvokeVoidAsync("addHorizontalScrolling", "file-system-browser-file-system-explorer").ConfigureAwait(false);
else
await JSRuntime.InvokeVoidAsync("removeHorizontalScrolling", "file-system-browser-file-system-explorer").ConfigureAwait(false);
StateHasChanged();
}
/// <summary>
/// Changes the icon size for the file system items.
/// </summary>
/// <param name="newIconSize">Thew new icon size to change to.</param>
private void ChangeIconSize(FileSystemIconSize newIconSize)
{
viewMode = FileSystemViewMode.Icons;
iconSize = newIconSize;
StateHasChanged();
}
/// <summary>
/// Enters the edit mode where the navigator path can be edited freely.
/// </summary>
private async Task EnterNavigationPathEditModeAsync()
{
isNavigationPathEditMode = true;
StateHasChanged();
await InvokeAsync(async () =>
{
await Task.Delay(50); // a small delay is necessary to ensure the DOM has updated
await SetFocusOnNavigatorAddressInputAsync().ConfigureAwait(false);
});
}
/// <summary>
/// Exits the edit mode where the navigator path can be edited freely.
/// </summary>
private async Task ExitNavigationPathEditModeAsync()
{
isNavigationPathEditMode = false;
StateHasChanged();
if (Path is not null)
await NavigateToPathAsync(Path).ConfigureAwait(false);
}
/// <summary>
/// Handles the Escape key being pressed in the navigator address input.
/// </summary>
private void HandleNavigatorInputEscapePressed()
{
Path = _path;
isNavigationPathEditMode = false;
StateHasChanged();
}
/// <summary>
/// Sets the focus to the navigator address input.
/// </summary>
public async Task SetFocusOnNavigatorAddressInputAsync()
{
await JSRuntime.InvokeVoidAsync("focusNavigatorInputElement");
}
/// <summary>
/// Handles API exceptions, presenting standard problem details in a user friendly way.
/// </summary>
/// <param name="ex">The exception to handle</param>
private void HandleApiException(ApiException ex)
{
StringBuilder errorMessage = new StringBuilder();
if (ex.ProblemDetails is not null)
{
errorMessage.AppendLine($"HTTP {ex.ProblemDetails.Status} {ex.HttpStatusCode}<br>");
if (!string.IsNullOrEmpty(ex.ProblemDetails.Detail))
errorMessage.AppendLine($"<b>{ex.ProblemDetails.Detail}<b>");
if (ex.ProblemDetails.Extensions is not null && ex.ProblemDetails.Extensions.TryGetValue("errors", out var errorsObj))
{
if (errorsObj is JsonElement jsonElement && jsonElement.ValueKind == JsonValueKind.Object)
{
errorMessage.AppendLine("Validation Errors:");
foreach (var error in jsonElement.EnumerateObject())
{
string fieldName = error.Name;
if (error.Value.ValueKind == JsonValueKind.Array)
foreach (var errorValue in error.Value.EnumerateArray())
errorMessage.AppendLine($"- {fieldName}: {errorValue}<br>");
}
}
}
if (ex.ProblemDetails.Extensions is not null)
foreach (var extension in ex.ProblemDetails.Extensions)
if (extension.Key != "errors")
errorMessage.AppendLine($"{extension.Key}: {extension.Value}<br>");
}
else
{
errorMessage.AppendLine($"HTTP {ex.HttpStatusCode}<br>");
errorMessage.AppendLine($"{ex.Message}<br>");
}
_notificationService.Show(errorMessage.ToString(), NotificationType.Error);
}
/// <summary>
/// Disposes this component.
/// </summary>
public void Dispose()
{
reference?.Dispose();
}
}