diff --git a/src/Lumina.Application/Core/FileManagement/Paths/Queries/CheckPathExistsQuery.cs b/src/Lumina.Application/Core/FileManagement/Paths/Queries/CheckPathExistsQuery.cs new file mode 100644 index 00000000..b2c4f3b4 --- /dev/null +++ b/src/Lumina.Application/Core/FileManagement/Paths/Queries/CheckPathExistsQuery.cs @@ -0,0 +1,10 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Contracts.Responses.FileManagement; +using Mediator; +#endregion + +/// +/// Query for retrieving the existence of a file system path. +/// +/// The path for which to check the existence. +public record CheckPathExistsQuery(string Path) : IRequest; \ No newline at end of file diff --git a/src/Lumina.Application/Core/FileManagement/Paths/Queries/CheckPathExistsQueryHandler.cs b/src/Lumina.Application/Core/FileManagement/Paths/Queries/CheckPathExistsQueryHandler.cs new file mode 100644 index 00000000..56358dd0 --- /dev/null +++ b/src/Lumina.Application/Core/FileManagement/Paths/Queries/CheckPathExistsQueryHandler.cs @@ -0,0 +1,45 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Contracts.Responses.FileManagement; +using Lumina.Domain.Core.Aggregates.FileManagement.FileManagementAggregate.Services; +using Mediator; +using System.Threading; +using System.Threading.Tasks; +#endregion + +namespace Lumina.Application.Core.FileManagement.Paths.Queries; + +/// +/// Handler for the query to check the existence a file system path. +/// +public class CheckPathExistsQueryHandler : IRequestHandler +{ + #region ================================================================== FIELD MEMBERS ================================================================================ + private readonly IPathService _pathService; + #endregion + + #region ====================================================================== CTOR ===================================================================================== + /// + /// Initializes a new instance of the class. + /// + /// Injected service for managing file system paths. + public CheckPathExistsQueryHandler(IPathService pathService) + { + _pathService = pathService; + } + #endregion + + #region ===================================================================== METHODS =================================================================================== + /// + /// Checks the existence of the specified file system path. + /// + /// The query containing the request. + /// Cancellation token that can be used to stop the execution. + /// + /// if the specified path exists, otherwise. + /// + public ValueTask Handle(CheckPathExistsQuery request, CancellationToken cancellationToken) + { + return ValueTask.FromResult(new PathExistsResponse(_pathService.Exists(request.Path))); + } + #endregion +} \ No newline at end of file diff --git a/src/Lumina.Application/Core/FileManagement/Paths/Queries/CheckPathExistsQueryValidator.cs b/src/Lumina.Application/Core/FileManagement/Paths/Queries/CheckPathExistsQueryValidator.cs new file mode 100644 index 00000000..bf5f3d11 --- /dev/null +++ b/src/Lumina.Application/Core/FileManagement/Paths/Queries/CheckPathExistsQueryValidator.cs @@ -0,0 +1,22 @@ +#region ========================================================================= USING ===================================================================================== +using FluentValidation; +using Lumina.Domain.Common.Errors; +#endregion + +namespace Lumina.Application.Core.FileManagement.Paths.Queries; + +/// +/// Validates the needed validation rules for . +/// +public class CheckPathExistsQueryValidator : AbstractValidator +{ + #region ====================================================================== CTOR ===================================================================================== + /// + /// Initializes a new instance of the class. + /// + public CheckPathExistsQueryValidator() + { + RuleFor(x => x.Path).NotEmpty().WithMessage(Errors.FileManagement.PathCannotBeEmpty.Code); + } + #endregion +} \ No newline at end of file diff --git a/src/Lumina.Contracts/Responses/FileManagement/PathExistsResponse.cs b/src/Lumina.Contracts/Responses/FileManagement/PathExistsResponse.cs new file mode 100644 index 00000000..17f2ab12 --- /dev/null +++ b/src/Lumina.Contracts/Responses/FileManagement/PathExistsResponse.cs @@ -0,0 +1,14 @@ +#region ========================================================================= USING ===================================================================================== +using System.Diagnostics; +#endregion + +namespace Lumina.Contracts.Responses.FileManagement; + +/// +/// Represents a response to the inquiry about the existence of a file system path. +/// +/// Whether a file system path exists or not. +[DebuggerDisplay("{Exists}")] +public record PathExistsResponse( + bool Exists +); \ No newline at end of file diff --git a/src/Lumina.Domain/Core/Aggregates/FileManagement/FileManagementAggregate/Services/IPathService.cs b/src/Lumina.Domain/Core/Aggregates/FileManagement/FileManagementAggregate/Services/IPathService.cs index aafc1119..a66289d6 100644 --- a/src/Lumina.Domain/Core/Aggregates/FileManagement/FileManagementAggregate/Services/IPathService.cs +++ b/src/Lumina.Domain/Core/Aggregates/FileManagement/FileManagementAggregate/Services/IPathService.cs @@ -27,6 +27,13 @@ public interface IPathService /// if is a valid path, otherwise. bool IsValidPath(string path); + /// + /// Checks if exists. + /// + /// The path to be checked. + /// if exists, otherwise. + bool Exists(string path); + /// /// Tries to combine with . /// diff --git a/src/Lumina.Domain/Core/Aggregates/FileManagement/FileManagementAggregate/Services/PathService.cs b/src/Lumina.Domain/Core/Aggregates/FileManagement/FileManagementAggregate/Services/PathService.cs index 74c3a6a7..df583aff 100644 --- a/src/Lumina.Domain/Core/Aggregates/FileManagement/FileManagementAggregate/Services/PathService.cs +++ b/src/Lumina.Domain/Core/Aggregates/FileManagement/FileManagementAggregate/Services/PathService.cs @@ -51,6 +51,19 @@ public class PathService : IPathService return _platformContext.PathStrategy.IsValidPath(newPathResult.Value); } + /// + /// Checks if exists. + /// + /// The path to be checked. + /// if exists, otherwise. + public bool Exists(string path) + { + ErrorOr newPathResult = FileSystemPathId.Create(path); + if (newPathResult.IsError) + return false; + return _platformContext.PathStrategy.Exists(newPathResult.Value); + } + /// /// Tries to combine with . /// diff --git a/src/Lumina.Domain/Core/Aggregates/FileManagement/FileManagementAggregate/Strategies/Path/IPathStrategy.cs b/src/Lumina.Domain/Core/Aggregates/FileManagement/FileManagementAggregate/Strategies/Path/IPathStrategy.cs index ea850094..b099942e 100644 --- a/src/Lumina.Domain/Core/Aggregates/FileManagement/FileManagementAggregate/Strategies/Path/IPathStrategy.cs +++ b/src/Lumina.Domain/Core/Aggregates/FileManagement/FileManagementAggregate/Strategies/Path/IPathStrategy.cs @@ -23,6 +23,13 @@ public interface IPathStrategy /// if is a valid path, otherwise. bool IsValidPath(FileSystemPathId path); + /// + /// Checks if exists. + /// + /// The path to be checked. + /// if exists, otherwise. + bool Exists(FileSystemPathId path); + /// /// Tries to combine with . /// diff --git a/src/Lumina.Domain/Core/Aggregates/FileManagement/FileManagementAggregate/Strategies/Path/UnixPathStrategy.cs b/src/Lumina.Domain/Core/Aggregates/FileManagement/FileManagementAggregate/Strategies/Path/UnixPathStrategy.cs index 329b785c..4dab1d72 100644 --- a/src/Lumina.Domain/Core/Aggregates/FileManagement/FileManagementAggregate/Strategies/Path/UnixPathStrategy.cs +++ b/src/Lumina.Domain/Core/Aggregates/FileManagement/FileManagementAggregate/Strategies/Path/UnixPathStrategy.cs @@ -4,6 +4,7 @@ using Lumina.Domain.Common.Errors; using Lumina.Domain.Core.Aggregates.FileManagement.FileManagementAggregate.ValueObjects; using System; using System.Collections.Generic; +using System.IO.Abstractions; using System.Linq; using System.Text.RegularExpressions; #endregion @@ -15,6 +16,10 @@ namespace Lumina.Domain.Core.Aggregates.FileManagement.FileManagementAggregate.S /// public class UnixPathStrategy : IUnixPathStrategy { + #region ================================================================== FIELD MEMBERS ================================================================================ + private readonly IFileSystem _fileSystem; + #endregion + #region ==================================================================== PROPERTIES ================================================================================= public char PathSeparator { @@ -22,6 +27,17 @@ public class UnixPathStrategy : IUnixPathStrategy } #endregion + #region ====================================================================== CTOR ===================================================================================== + /// + /// Initializes a new instance of the class. + /// + /// Injected service used to interact with the local filesystem. + public UnixPathStrategy(IFileSystem fileSystem) + { + _fileSystem = fileSystem; + } + #endregion + #region ===================================================================== METHODS =================================================================================== /// /// Checks if is a valid path. @@ -41,6 +57,16 @@ public class UnixPathStrategy : IUnixPathStrategy return Regex.IsMatch(path.Path, pathPattern); } + /// + /// Checks if exists. + /// + /// The path to be checked. + /// if exists, otherwise. + public bool Exists(FileSystemPathId path) + { + return _fileSystem.Path.Exists(path.Path); + } + /// /// Tries to combine with . /// diff --git a/src/Lumina.Domain/Core/Aggregates/FileManagement/FileManagementAggregate/Strategies/Path/WindowsPathStrategy.cs b/src/Lumina.Domain/Core/Aggregates/FileManagement/FileManagementAggregate/Strategies/Path/WindowsPathStrategy.cs index 5926a83e..e179e0ee 100644 --- a/src/Lumina.Domain/Core/Aggregates/FileManagement/FileManagementAggregate/Strategies/Path/WindowsPathStrategy.cs +++ b/src/Lumina.Domain/Core/Aggregates/FileManagement/FileManagementAggregate/Strategies/Path/WindowsPathStrategy.cs @@ -6,6 +6,7 @@ using Lumina.Domain.Common.Errors; using System.Text.RegularExpressions; using Lumina.Domain.Core.Aggregates.FileManagement.FileManagementAggregate.ValueObjects; using System.Linq; +using System.IO.Abstractions; #endregion namespace Lumina.Domain.Core.Aggregates.FileManagement.FileManagementAggregate.Strategies.Path; @@ -15,6 +16,10 @@ namespace Lumina.Domain.Core.Aggregates.FileManagement.FileManagementAggregate.S /// public class WindowsPathStrategy : IWindowsPathStrategy { + #region ================================================================== FIELD MEMBERS ================================================================================ + private readonly IFileSystem _fileSystem; + #endregion + #region ==================================================================== PROPERTIES ================================================================================= public char PathSeparator { @@ -22,6 +27,17 @@ public class WindowsPathStrategy : IWindowsPathStrategy } #endregion + #region ====================================================================== CTOR ===================================================================================== + /// + /// Initializes a new instance of the class. + /// + /// Injected service used to interact with the local filesystem. + public WindowsPathStrategy(IFileSystem fileSystem) + { + _fileSystem = fileSystem; + } + #endregion + #region ===================================================================== METHODS =================================================================================== /// /// Checks if is a valid path. @@ -40,6 +56,16 @@ public class WindowsPathStrategy : IWindowsPathStrategy return Regex.IsMatch(path.Path, pathPattern); } + /// + /// Checks if exists. + /// + /// The path to be checked. + /// if exists, otherwise. + public bool Exists(FileSystemPathId path) + { + return _fileSystem.Path.Exists(path.Path); + } + /// /// Tries to combine with . /// diff --git a/src/Lumina.Presentation.Api/Core/Controllers/FileManagement/PathController.cs b/src/Lumina.Presentation.Api/Core/Controllers/FileManagement/PathController.cs index 26282297..0d7574bf 100644 --- a/src/Lumina.Presentation.Api/Core/Controllers/FileManagement/PathController.cs +++ b/src/Lumina.Presentation.Api/Core/Controllers/FileManagement/PathController.cs @@ -109,5 +109,17 @@ public class PathController : ApiController PathValidResponse result = await _mediator.Send(new ValidatePathQuery(path), cancellationToken).ConfigureAwait(false); return Ok(result); } + + /// + /// Checks whether exists or not. + /// + /// The path to be checked. + /// Cancellation token that can be used to stop the execution. + [HttpGet("check-path-exists")] + public async Task CheckPathExists([FromQuery, ModelBinder(typeof(UrlStringBinder))] string path, CancellationToken cancellationToken) + { + PathExistsResponse result = await _mediator.Send(new CheckPathExistsQuery(path), cancellationToken).ConfigureAwait(false); + return Ok(result); + } #endregion } \ No newline at end of file diff --git a/src/Lumina.Presentation.Web/Common/Models/FileManagement/PathExistsModel.cs b/src/Lumina.Presentation.Web/Common/Models/FileManagement/PathExistsModel.cs new file mode 100644 index 00000000..894f6c03 --- /dev/null +++ b/src/Lumina.Presentation.Web/Common/Models/FileManagement/PathExistsModel.cs @@ -0,0 +1,14 @@ +#region ========================================================================= USING ===================================================================================== +using System.Diagnostics; +#endregion + +namespace Lumina.Presentation.Web.Common.Models.FileManagement; + +/// +/// Represents a response to the inquiry about the existence of a file system path. +/// +/// Whether a file system path exists or not. +[DebuggerDisplay("{Exists}")] +public record PathExistsModel( + bool Exists +); \ No newline at end of file diff --git a/src/Lumina.Presentation.Web/Components/EnlightenmentInput.razor b/src/Lumina.Presentation.Web/Components/EnlightenmentInput.razor index d59ddca6..d7e95aad 100644 --- a/src/Lumina.Presentation.Web/Components/EnlightenmentInput.razor +++ b/src/Lumina.Presentation.Web/Components/EnlightenmentInput.razor @@ -1,20 +1,22 @@ @inject IJSRuntime JSRuntime + data-has-error="@HasError" + id="@Id" /> @code { + [Parameter] public string? Id { get; set; } [Parameter] public string Type { get; set; } = "text"; [Parameter] public bool UsesPercentForHeight { get; set; } [Parameter] public bool UsesPercentForWidth { get; set; } = true; @@ -32,6 +34,18 @@ [Parameter] public bool IsReadOnly { get; set; } [Parameter] public bool HasError { get; set; } + private ElementReference inputElement; + + /// + /// Handles the event risen after the component was rendered. + /// + /// Indicates whether this is the first render or not. + protected override async Task OnAfterRenderAsync(bool firstRender) + { + if (firstRender) + await JSRuntime.InvokeVoidAsync("windowKeyDownHandler", inputElement, DotNetObjectReference.Create(this)); + } + /// /// Handles the input change event. /// @@ -42,23 +56,22 @@ await ValueChanged.InvokeAsync(Value).ConfigureAwait(false); } - /// - /// Handles the key press event. - /// - /// The event arguments. - private async Task OnKeyPressAsync(KeyboardEventArgs e) - { - if (e.Key == "Enter") - await OnEnterPressed.InvokeAsync(); - } - /// /// Handles the key down event. /// /// The event arguments. private async Task OnKeyDownAsync(KeyboardEventArgs e) { - if (e.Key == "Escape") - await OnEscapePressed.InvokeAsync(Value); + if (e.Key == "Enter" || e.Code == "NumpadEnter") + await OnEnterPressed.InvokeAsync(); + } + + /// + /// Handles the Escape key pressed. + /// + [JSInvokable] + public void EscapePressed() + { + OnEscapePressed.InvokeAsync(Value); } } \ No newline at end of file diff --git a/src/Lumina.Presentation.Web/Components/FileSystemBrowserComponent.razor b/src/Lumina.Presentation.Web/Components/FileSystemBrowser.razor similarity index 77% rename from src/Lumina.Presentation.Web/Components/FileSystemBrowserComponent.razor rename to src/Lumina.Presentation.Web/Components/FileSystemBrowser.razor index 4c9fcd84..54623352 100644 --- a/src/Lumina.Presentation.Web/Components/FileSystemBrowserComponent.razor +++ b/src/Lumina.Presentation.Web/Components/FileSystemBrowser.razor @@ -1,13 +1,20 @@ @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
@@ -39,12 +46,12 @@ @if (isNavigationPathEditMode) { + AutoComplete="true" OnEnterPressed="ExitNavigationPathEditModeAsync" OnEscapePressed="HandleNavigatorInputEscapePressed" Id="navigator-address-bar-input" /> } else { @@ -182,6 +189,7 @@ private FileSystemViewMode viewMode = FileSystemViewMode.List; // TODO: take from config private FileSystemIconSize iconSize; private Dictionary> pathSegmentsSubdirectoriesCache = []; + private DotNetObjectReference? reference; /// /// Initializes the component. @@ -196,30 +204,60 @@ await JSRuntime.InvokeVoidAsync("addHorizontalScrolling", "navigator-address-bar").ConfigureAwait(false); } + /// + /// Handles the event risen after the component was rendered. + /// + /// Indicates whether this is the first render or not. + 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); + } + + /// + /// Handles the window click event. + /// + /// The event arguments. + [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(); + } + /// /// Expands or collapses a node in the tree view. /// /// The node to expand or collapse. - private async Task ExpandNode(FileSystemTreeNodeModel node) + private async Task ToggleTreeViewNode(FileSystemTreeNodeModel node) { if (!node.IsExpanded && !node.ChildrenLoaded) { node.Children = new List(); node.IsExpanded = true; StateHasChanged(); - try + if (await CheckPathAsync(node.Path).ConfigureAwait(false)) { - await foreach (FileSystemTreeNodeModel? childNode in _apiHttpClient.GetAsyncEnumerable($"directories/get-tree-directories?path={Uri.EscapeDataString(node.Path)}").ConfigureAwait(false)) + try { - if (childNode is not null) - { - node.Children.Add(childNode); - StateHasChanged(); - } - } - if (IncludeFiles) - { - await foreach (FileSystemTreeNodeModel? childNode in _apiHttpClient.GetAsyncEnumerable($"files/get-tree-files?path={Uri.EscapeDataString(node.Path)}").ConfigureAwait(false)) + await foreach (FileSystemTreeNodeModel? childNode in _apiHttpClient.GetAsyncEnumerable($"directories/get-tree-directories?path={Uri.EscapeDataString(node.Path)}").ConfigureAwait(false)) { if (childNode is not null) { @@ -227,15 +265,26 @@ StateHasChanged(); } } + if (IncludeFiles) + { + await foreach (FileSystemTreeNodeModel? childNode in _apiHttpClient.GetAsyncEnumerable($"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; } - } - catch (Exception ex) - { - Console.Error.WriteLine($"Error expanding node: {ex.Message}"); // TODO: display to the user when notification system is implemented - } - finally - { - node.ChildrenLoaded = true; } } else @@ -243,6 +292,66 @@ StateHasChanged(); } + /// + /// Handles the change event. + /// + /// The event arguments. + 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 parentLocation = await _apiHttpClient.GetAsync>($"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 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($"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(); + } + } + /// /// Handles the selection of a node in the tree view. /// @@ -254,10 +363,11 @@ { _path = path; await GetNavigatorPathAsync(path).ConfigureAwait(false); - await GetFileSystemTreeViewAsync(path).ConfigureAwait(false); + await GetFileSystemTreeAsync(path).ConfigureAwait(false); await GetFileSystemItemsAsync(path).ConfigureAwait(false); - Console.WriteLine($"Selected node: {path}"); } + else + Path = _path; await OnNodeSelected.InvokeAsync(path).ConfigureAwait(false); } @@ -279,13 +389,27 @@ /// if the specified path is valid, otherwise. private async Task CheckPathAsync(string path) { - var isPathValidResponse = await _apiHttpClient.GetAsync($"path/validate?path={Uri.EscapeDataString(path)}").ConfigureAwait(false); - if (!isPathValidResponse.IsValid) + try { - // TODO: display error message to user - Console.WriteLine("specified path is not valid!"); + var isPathValidResponse = await _apiHttpClient.GetAsync($"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($"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; } - return isPathValidResponse.IsValid; } /// @@ -302,7 +426,7 @@ /// Gets the file system items that are displayed in the file system tree view pane. /// /// The path for which to get the file system items. - private async Task GetFileSystemTreeViewAsync(string path) + private async Task GetFileSystemTreeAsync(string path) { treeViewRootNodes = []; // on Windows, ask the list of drives @@ -375,67 +499,10 @@ } catch (ApiException ex) { - Console.Error.WriteLine($"Error expanding node: {ex.Message}"); // TODO: display to the user when notification system is implemented + HandleApiException(ex); } } - /// - /// Handles the change event. - /// - /// The event arguments. - private async Task OnNavigatorPathSegmentCheckChangeHandler(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!; - showPathSegmentDowpDown = isChecked; - expandedPathSegmentIndex = null; - // 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 parentLocation = await _apiHttpClient.GetAsync>($"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) - { - Console.WriteLine(ex.Message); - } - if (!concatenatedPath.EndsWith(pathSeparator)) - concatenatedPath += pathSeparator; - // fetch directories for the expanded path segment - List 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($"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; - StateHasChanged(); - // invoke the javascript function that positions the dropdown underneath the toggled path segment - await JSRuntime.InvokeVoidAsync("updateDropdownPosition", $"path-segment-{toggledIndex}").ConfigureAwait(false); - } - else - StateHasChanged(); - } - /// /// Changes the current file system explorer view. /// @@ -503,4 +570,51 @@ { await JSRuntime.InvokeVoidAsync("focusNavigatorInputElement"); } + + /// + /// Handles API exceptions, presenting standard problem details in a user friendly way. + /// + /// The exception to handle + private void HandleApiException(ApiException ex) + { + StringBuilder errorMessage = new StringBuilder(); + if (ex.ProblemDetails is not null) + { + errorMessage.AppendLine($"HTTP {ex.ProblemDetails.Status} {ex.HttpStatusCode}
"); + if (!string.IsNullOrEmpty(ex.ProblemDetails.Detail)) + errorMessage.AppendLine($"{ex.ProblemDetails.Detail}"); + 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}
"); + } + } + } + if (ex.ProblemDetails.Extensions is not null) + foreach (var extension in ex.ProblemDetails.Extensions) + if (extension.Key != "errors") + errorMessage.AppendLine($"{extension.Key}: {extension.Value}
"); + } + else + { + errorMessage.AppendLine($"HTTP {ex.HttpStatusCode}
"); + errorMessage.AppendLine($"{ex.Message}
"); + } + _notificationService.Show(errorMessage.ToString(), NotificationType.Error); + } + + /// + /// Disposes this component. + /// + public void Dispose() + { + reference?.Dispose(); + } } \ No newline at end of file diff --git a/src/Lumina.Presentation.Web/Components/FileSystemBrowserComponent.razor.css b/src/Lumina.Presentation.Web/Components/FileSystemBrowser.razor.css similarity index 100% rename from src/Lumina.Presentation.Web/Components/FileSystemBrowserComponent.razor.css rename to src/Lumina.Presentation.Web/Components/FileSystemBrowser.razor.css diff --git a/src/Lumina.Presentation.Web/Components/FileSystemTreeViewNode.razor b/src/Lumina.Presentation.Web/Components/FileSystemTreeViewNode.razor index 6ddfa062..66d65761 100644 --- a/src/Lumina.Presentation.Web/Components/FileSystemTreeViewNode.razor +++ b/src/Lumina.Presentation.Web/Components/FileSystemTreeViewNode.razor @@ -19,7 +19,7 @@
@foreach (var childNode in Node.Children) { - + }
} @@ -27,7 +27,7 @@ @code { [Parameter] public FileSystemTreeNodeModel Node { get; set; } = null!; - [Parameter] public EventCallback OnExpand { get; set; } + [Parameter] public EventCallback OnExpandToggle { get; set; } [Parameter] public EventCallback OnNodeSelected { get; set; } [Parameter] public string? SelectedNodePath { get; set; } @@ -38,7 +38,7 @@ ///
private async Task ToggleExpand() { - await OnExpand.InvokeAsync(Node).ConfigureAwait(false); + await OnExpandToggle.InvokeAsync(Node).ConfigureAwait(false); } /// diff --git a/src/Lumina.Presentation.Web/wwwroot/js/site.js b/src/Lumina.Presentation.Web/wwwroot/js/site.js index dc5a4570..d1391bb6 100644 --- a/src/Lumina.Presentation.Web/wwwroot/js/site.js +++ b/src/Lumina.Presentation.Web/wwwroot/js/site.js @@ -132,17 +132,21 @@ window.addEventListener('resize', function () { } }); -/** - * Handles window click events. - * @param {MouseEvent} event - The click event triggered on the window. - */ -window.addEventListener('click', function (event) { - // check if the clicked element is not a checkbox or its label - if (!event.target.closest('.navigator-toggle-checkbox, .navigator-toggle')) { - windowWasClicked = true; - closeNavigatorPathSegments(); - const dropdown = document.getElementById('navigatorDropdown'); - if (dropdown) - dropdown.style.display = 'none'; - } -}); \ No newline at end of file +window.windowClickHandler = (dotnetHelper) => { + window.addEventListener('click', (event) => { + dotnetHelper.invokeMethodAsync('OnWindowClick', { + x: event.clientX, + y: event.clientY, + sender: event.target.getAttribute('id') + }); + }); +}; + +window.windowKeyDownHandler = (element, dotnetHelper) => { + element.addEventListener('keydown', (e) => { + if (e.key === 'Escape') { + e.preventDefault(); + dotnetHelper.invokeMethodAsync('EscapePressed'); + } + }); +}; \ No newline at end of file