From beb66ac65e883b8c329cc07b6a23e7c726b0b5d6 Mon Sep 17 00:00:00 2001 From: Binary Alley Date: Sat, 21 Sep 2024 13:44:34 +0300 Subject: [PATCH] Implements directory browser dialog, part 4: back/forward/up navigation --- .../Services/DirectoryProviderService.cs | 4 +- .../Strategies/Path/UnixPathStrategy.cs | 4 +- .../Strategies/Path/WindowsPathStrategy.cs | 2 +- .../Components/FileSystemBrowser.razor | 170 +++++++++++++++--- .../Components/FileSystemNavigator.razor | 6 +- .../Components/FileSystemTreeViewNode.razor | 2 + .../wwwroot/js/site.js | 9 + 7 files changed, 167 insertions(+), 30 deletions(-) diff --git a/src/Lumina.Domain/Core/Aggregates/FileManagement/FileManagementAggregate/Services/DirectoryProviderService.cs b/src/Lumina.Domain/Core/Aggregates/FileManagement/FileManagementAggregate/Services/DirectoryProviderService.cs index 9fa35e3f..30c470dc 100644 --- a/src/Lumina.Domain/Core/Aggregates/FileManagement/FileManagementAggregate/Services/DirectoryProviderService.cs +++ b/src/Lumina.Domain/Core/Aggregates/FileManagement/FileManagementAggregate/Services/DirectoryProviderService.cs @@ -48,6 +48,7 @@ internal class DirectoryProviderService : IDirectoryProviderService return Errors.Permission.UnauthorizedAccess; return ErrorOrFactory.From(_fileSystem.Directory.GetDirectories(path.Path) .OrderBy(path => path) + .Select(path => path.EndsWith(_fileSystem.Path.DirectorySeparatorChar) ? path : path + _fileSystem.Path.DirectorySeparatorChar) .Select(path => FileSystemPathId.Create(path)) .Where(errorOrPathId => !errorOrPathId.IsError) .Select(errorOrPathId => errorOrPathId.Value) @@ -72,7 +73,8 @@ internal class DirectoryProviderService : IDirectoryProviderService /// An containing either a file name or an error. public ErrorOr GetFileName(FileSystemPathId path) { - return _fileSystem.Path.GetFileName(path.Path); + string inputPath = path.Path.EndsWith(_fileSystem.Path.DirectorySeparatorChar) ? path.Path[..^1] : path.Path; + return _fileSystem.Path.GetFileName(inputPath); } /// 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 4dab1d72..8fd35fd5 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 @@ -82,7 +82,7 @@ public class UnixPathStrategy : IUnixPathStrategy // if the name begins with a directory separator, remove it name = name.TrimStart(PathSeparator); // combine the two parts with the Unix directory separator character - return FileSystemPathId.Create(subpath + PathSeparator + name); + return FileSystemPathId.Create(subpath + PathSeparator + name + PathSeparator); } /// @@ -121,7 +121,7 @@ public class UnixPathStrategy : IUnixPathStrategy return Errors.FileManagement.InvalidPath; // trim trailing slash for consistent processing string tempPath = path.Path; - if (tempPath.EndsWith("/")) + if (tempPath.EndsWith('/')) tempPath = tempPath.TrimEnd(PathSeparator); // find the last occurrence of a slash var lastIndex = tempPath.LastIndexOf(PathSeparator); 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 e179e0ee..02478794 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 @@ -81,7 +81,7 @@ public class WindowsPathStrategy : IWindowsPathStrategy // if the name begins with a directory separator, remove it name = name.TrimStart(PathSeparator); // combine the two parts with the Windows directory separator character - return FileSystemPathId.Create(subpath + PathSeparator + name); + return FileSystemPathId.Create(subpath + PathSeparator + name + PathSeparator); } /// diff --git a/src/Lumina.Presentation.Web/Components/FileSystemBrowser.razor b/src/Lumina.Presentation.Web/Components/FileSystemBrowser.razor index 54623352..80aadc98 100644 --- a/src/Lumina.Presentation.Web/Components/FileSystemBrowser.razor +++ b/src/Lumina.Presentation.Web/Components/FileSystemBrowser.razor @@ -33,9 +33,9 @@ @@ -165,7 +165,7 @@ } @@ -190,6 +190,8 @@ private FileSystemIconSize iconSize; private Dictionary> pathSegmentsSubdirectoriesCache = []; private DotNetObjectReference? reference; + private readonly Stack undoStack = new(); + private readonly Stack redoStack = new(); /// /// Initializes the component. @@ -198,7 +200,11 @@ { await GetFileSystemPropertiesAsync().ConfigureAwait(false); if (Path is not null) - await NavigateToPathAsync(Path).ConfigureAwait(false); + { + if (!Path.EndsWith(pathSeparator)) + Path += pathSeparator; + await NavigateToPathAsync(Path, isForwardNavigation: false, isBackwardNavigation: false).ConfigureAwait(false); + } await ChangeViewModeAsync(viewMode).ConfigureAwait(false); // make the navigator path segments horizontally scrollable await JSRuntime.InvokeVoidAsync("addHorizontalScrolling", "navigator-address-bar").ConfigureAwait(false); @@ -311,13 +317,14 @@ for (int i = 1; i <= toggledIndex; i++) concatenatedPath = $"{(concatenatedPath != pathSeparator ? concatenatedPath : string.Empty)}{pathSeparator}{pathSegments[i].Path}"; string parentConcatenatedPath = concatenatedPath; + // fetch directories for the expanded path segment 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++) + PathSegmentModel[] parentLocationResponse = await _apiHttpClient.GetAsync($"path/get-path-parent?path={Uri.EscapeDataString(concatenatedPath)}").ConfigureAwait(false); + parentConcatenatedPath = parentLocationResponse[0].Path; + for (int i = 1; i < parentLocationResponse.Length; i++) parentConcatenatedPath = $"{(parentConcatenatedPath != pathSeparator ? parentConcatenatedPath : string.Empty)}{pathSeparator}{pathSegments[i].Path}"; } } @@ -327,11 +334,8 @@ } 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 current and parent directories too + List directories = [ new() { Path = concatenatedPath, Name = ".", }, new() { Path = parentConcatenatedPath, Name = ".." } ]; // 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) @@ -356,19 +360,122 @@ /// Handles the selection of a node in the tree view. /// /// The path of the selected node. - private async Task NavigateToPathAsync(string path) + /// Indicates whether the navigation is towards a location in the redo stack or not. + /// Indicates whether the navigation is towards a location in the undo stack or not. + private async Task NavigateToPathAsync(string path, bool isForwardNavigation, bool isBackwardNavigation) { - selectedNodePath = path; if (await CheckPathAsync(path).ConfigureAwait(false)) { - _path = path; + // check if backward navigation is possible + if (isBackwardNavigation) + { + if (undoStack.Count > 0) + { + // get the first path in the backward navigation list + string backwardPath = undoStack.Pop(); + // put the current path in the forward navigationlist, before navigating to the backward path + if (Path is not null) + { + if (!Path.EndsWith(pathSeparator)) + Path += pathSeparator; + redoStack.Push(Path); + } + path = backwardPath; + } + else + return; + } + else if (isForwardNavigation) // check if forward navigation is possible + { + if (redoStack.Count > 0) + { + // get the first path in the forward navigation list + string forwardPath = redoStack.Pop(); + // put the current path in the backward navigation list, before navigating to the forward path + if (Path is not null) + { + if (!Path.EndsWith(pathSeparator)) + Path += pathSeparator; + if (undoStack.Count == 0 || (undoStack.Count > 0 && undoStack.Peek() != Path)) + undoStack.Push(Path); + } + path = forwardPath; + } + else + return; + } + else // navigation to a brand new location (up, directory browse, manual path edit, etc) + { + redoStack.Clear(); + if (Path is not null && Path != path) // when navigating up, Path will be set after navigation + { + if (undoStack.Count == 0 || (undoStack.Count > 0 && undoStack.Peek() != Path)) + undoStack.Push(Path); + } + else if (_path is not null && _path != path) // when editing the address, Path already comes set, check against control value + { + if (undoStack.Count == 0 || (undoStack.Count > 0 && undoStack.Peek() != _path)) + undoStack.Push(_path); + } + } + _path = path; // we are about to navigate to the new path, store its value in the control variable await GetNavigatorPathAsync(path).ConfigureAwait(false); await GetFileSystemTreeAsync(path).ConfigureAwait(false); await GetFileSystemItemsAsync(path).ConfigureAwait(false); } - else - Path = _path; + selectedNodePath = _path; + Path = _path; // also update the navigation input address + if (Path is not null && !Path.EndsWith(pathSeparator)) + Path += pathSeparator; await OnNodeSelected.InvokeAsync(path).ConfigureAwait(false); + StateHasChanged(); + } + + /// + /// Provides backwards navigation. + /// + private async Task NavigateBackAsync() + { + if (Path is not null) + await NavigateToPathAsync(Path, isForwardNavigation: false, isBackwardNavigation: true).ConfigureAwait(false); + } + + /// + /// Provides forwards navigation. + /// + private async Task NavigateForwardAsync() + { + if (Path is not null) + await NavigateToPathAsync(Path, isForwardNavigation: true, isBackwardNavigation: false).ConfigureAwait(false); + } + + /// + /// Provides upwards navigation. + /// + private async Task NavigateUpAsync() + { + try + { + if (Path is not null) + { + // ask the API for the parent path + PathSegmentModel[] parentLocationResponse = await _apiHttpClient.GetAsync($"path/get-path-parent?path={Uri.EscapeDataString(Path)}").ConfigureAwait(false); + // if the answer was valid, and we can navigate up, reconstruct the provided path from its segments, and navigate to it + if (parentLocationResponse is not null) + { + string parentConcatenatedPath = parentLocationResponse[0].Path; + for (int i = 1; i < parentLocationResponse.Length; i++) + parentConcatenatedPath = $"{(parentConcatenatedPath != pathSeparator ? parentConcatenatedPath : string.Empty)}{pathSeparator}{parentLocationResponse[i].Path}"; + if (!parentConcatenatedPath.EndsWith(pathSeparator)) + parentConcatenatedPath += pathSeparator; + await NavigateToPathAsync(parentConcatenatedPath, isForwardNavigation: false, isBackwardNavigation: false).ConfigureAwait(false); + } + } + } + catch (ApiException ex) + { + HandleApiException(ex); + } } /// @@ -396,6 +503,8 @@ { _notificationService.Show("Specified path is not valid!", NotificationType.Error); // TODO: should ask error message from server when translation is implemented Path = _path; + if (Path is not null && !Path.EndsWith(pathSeparator)) + Path += pathSeparator; } PathExistsModel pathExistsResponse = await _apiHttpClient.GetAsync($"path/check-path-exists?path={Uri.EscapeDataString(path)}").ConfigureAwait(false); if (!pathExistsResponse.Exists) @@ -447,7 +556,6 @@ }); } // 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 initialTree = await _apiHttpClient.GetAsync>($"directories/get-directory-tree?path={Uri.EscapeDataString(path!)}&includeFiles={IncludeFiles}").ConfigureAwait(false); if (initialTree is not null && initialTree.Count > 0) { @@ -550,7 +658,27 @@ isNavigationPathEditMode = false; StateHasChanged(); if (Path is not null) - await NavigateToPathAsync(Path).ConfigureAwait(false); + { + if (!Path.EndsWith(pathSeparator)) + Path += pathSeparator; + await NavigateToPathAsync(Path, isForwardNavigation: false, isBackwardNavigation: false).ConfigureAwait(false); + } + } + + /// + /// Handles the selection of a node in the file system tree view. + /// + /// The path of the newly selected node. + private async Task HandleFileSystemTreeViewNodeSelectedAsync(string path) + { + StateHasChanged(); + if (selectedNodePath is not null) + { + Path = path; + if (!Path.EndsWith(pathSeparator)) + Path += pathSeparator; + await NavigateToPathAsync(Path, isForwardNavigation: false, isBackwardNavigation: false).ConfigureAwait(false); + } } /// diff --git a/src/Lumina.Presentation.Web/Components/FileSystemNavigator.razor b/src/Lumina.Presentation.Web/Components/FileSystemNavigator.razor index f1f619fa..9936cce9 100644 --- a/src/Lumina.Presentation.Web/Components/FileSystemNavigator.razor +++ b/src/Lumina.Presentation.Web/Components/FileSystemNavigator.razor @@ -1,4 +1,5 @@ @using Lumina.Presentation.Web.Common.Models.FileManagement + private async Task HandleNodeClick() { + Console.WriteLine("===node selected: " + Node.Path + "; selected node path: " + SelectedNodePath + "; is selected: " + IsSelected); await OnNodeSelected.InvokeAsync(Node.Path).ConfigureAwait(false); + StateHasChanged(); } /// diff --git a/src/Lumina.Presentation.Web/wwwroot/js/site.js b/src/Lumina.Presentation.Web/wwwroot/js/site.js index d1391bb6..dd07c185 100644 --- a/src/Lumina.Presentation.Web/wwwroot/js/site.js +++ b/src/Lumina.Presentation.Web/wwwroot/js/site.js @@ -132,6 +132,10 @@ window.addEventListener('resize', function () { } }); +/** + * Attaches a click event listener to the window, invoking a .NET method when the window is clicked. + * @param {any} dotnetHelper - .NET object to invoke methods asynchronously. + */ window.windowClickHandler = (dotnetHelper) => { window.addEventListener('click', (event) => { dotnetHelper.invokeMethodAsync('OnWindowClick', { @@ -142,6 +146,11 @@ window.windowClickHandler = (dotnetHelper) => { }); }; +/** + * Attaches a keydown event listener to the given element, invoking a .NET method when 'Escape' is pressed. + * @param {HTMLElement} element - The HTML element to attach the keydown listener to. + * @param {any} dotnetHelper - .NET object to invoke methods asynchronously. + */ window.windowKeyDownHandler = (element, dotnetHelper) => { element.addEventListener('keydown', (e) => { if (e.key === 'Escape') {