From 4c8517bb0865a0890d98c70cac20c250052fb6af Mon Sep 17 00:00:00 2001 From: Binary Alley Date: Thu, 26 Sep 2024 20:01:59 +0300 Subject: [PATCH] Merge of modifications from previous web presentation implementation --- .editorconfig | 2 - .../Services/FileProviderService.cs | 2 +- .../Services/FileTypeService.cs | 11 +- .../Services/IFileTypeService.cs | 11 +- .../Services/IThumbnailService.cs | 11 +- .../Services/ThumbnailService.cs | 35 +- .../Components/FileSystemBrowser.razor | 1051 +++++++++++++++ .../Components/FileSystemBrowser.razor.css | 1145 +++++++++++++++++ src/Lumina.Presentation.Web/Pages/Home.razor | 7 + .../wwwroot/js/site.js | 217 +++- 10 files changed, 2453 insertions(+), 39 deletions(-) create mode 100644 src/Lumina.Presentation.Web/Components/FileSystemBrowser.razor create mode 100644 src/Lumina.Presentation.Web/Components/FileSystemBrowser.razor.css create mode 100644 src/Lumina.Presentation.Web/Pages/Home.razor diff --git a/.editorconfig b/.editorconfig index 028900f4..e9cad815 100644 --- a/.editorconfig +++ b/.editorconfig @@ -274,8 +274,6 @@ dotnet_naming_style.local_function_style.capitalization = pascal_case # readonly instance fields are camelCase and begin with underscore dotnet_naming_symbols.readonly_instance_fields.applicable_kinds = field dotnet_naming_symbols.readonly_instance_fields.required_modifiers = readonly -dotnet_naming_symbols.readonly_instance_fields.required_modifiers_style = exclude_any -dotnet_naming_symbols.readonly_instance_fields.required_modifiers = static dotnet_naming_style.underscore_camel_case_style.capitalization = camel_case dotnet_naming_style.underscore_camel_case_style.required_prefix = _ diff --git a/src/Lumina.Domain/Core/Aggregates/FileManagement/FileManagementAggregate/Services/FileProviderService.cs b/src/Lumina.Domain/Core/Aggregates/FileManagement/FileManagementAggregate/Services/FileProviderService.cs index c8f96aff..8978437b 100644 --- a/src/Lumina.Domain/Core/Aggregates/FileManagement/FileManagementAggregate/Services/FileProviderService.cs +++ b/src/Lumina.Domain/Core/Aggregates/FileManagement/FileManagementAggregate/Services/FileProviderService.cs @@ -105,7 +105,7 @@ internal class FileProviderService : IFileProviderService // check if the user has access permissions to the provided path if (!_fileSystemPermissionsService.CanAccessPath(path, FileAccessMode.ReadContents)) return Errors.Permission.UnauthorizedAccess; - return System.IO.File.ReadAllBytes(path.Path); + return File.ReadAllBytes(path.Path); } /// diff --git a/src/Lumina.Domain/Core/Aggregates/FileManagement/FileManagementAggregate/Services/FileTypeService.cs b/src/Lumina.Domain/Core/Aggregates/FileManagement/FileManagementAggregate/Services/FileTypeService.cs index 4e2309d8..27142814 100644 --- a/src/Lumina.Domain/Core/Aggregates/FileManagement/FileManagementAggregate/Services/FileTypeService.cs +++ b/src/Lumina.Domain/Core/Aggregates/FileManagement/FileManagementAggregate/Services/FileTypeService.cs @@ -9,6 +9,7 @@ using System; using System.IO.Abstractions; using System.Linq; using System.Text; +using System.Threading; using System.Threading.Tasks; #endregion @@ -43,18 +44,20 @@ public class FileTypeService : IFileTypeService /// Determines if is of type image or not, and returns its type. /// /// The file to determine if it is an image or not. + /// Cancellation token that can be used to stop the execution. /// An containing the type of image or an error. - public async Task> GetImageTypeAsync(File file) + public async Task> GetImageTypeAsync(File file, CancellationToken cancellationToken) { - return await GetImageTypeAsync(file.Id).ConfigureAwait(false); + return await GetImageTypeAsync(file.Id, cancellationToken).ConfigureAwait(false); } /// /// Determines if a file identified by is of type image or not, and returns its type. /// /// The path of the file to determine if it is an image or not. + /// Cancellation token that can be used to stop the execution. /// An containing the type of image or an error. - public async Task> GetImageTypeAsync(FileSystemPathId path) + public async Task> GetImageTypeAsync(FileSystemPathId path, CancellationToken cancellationToken) { // check if the user has access permissions to the provided path if (!_fileSystemPermissionsService.CanAccessPath(path, FileAccessMode.ReadContents)) @@ -65,7 +68,7 @@ public class FileTypeService : IFileTypeService if (stream.Length < BUFFER_SIZE) return ImageType.None; // read only the first bytes of the file, equal to the buffer size - await stream.ReadAsync(buffer).ConfigureAwait(false); + await stream.ReadAsync(buffer, cancellationToken).ConfigureAwait(false); byte[] firstBytes = buffer[..BUFFER_SIZE].ToArray(); // check if its a known image type, based on header bytes ImageType type = IdentifyHeader(firstBytes); diff --git a/src/Lumina.Domain/Core/Aggregates/FileManagement/FileManagementAggregate/Services/IFileTypeService.cs b/src/Lumina.Domain/Core/Aggregates/FileManagement/FileManagementAggregate/Services/IFileTypeService.cs index 6ff3f5c7..7d74c0bb 100644 --- a/src/Lumina.Domain/Core/Aggregates/FileManagement/FileManagementAggregate/Services/IFileTypeService.cs +++ b/src/Lumina.Domain/Core/Aggregates/FileManagement/FileManagementAggregate/Services/IFileTypeService.cs @@ -1,8 +1,9 @@ -#region ========================================================================= USING ===================================================================================== +#region ========================================================================= USING ===================================================================================== using ErrorOr; using Lumina.Contracts.Enums.PhotoLibrary; using Lumina.Domain.Core.Aggregates.FileManagement.FileManagementAggregate.Entities; using Lumina.Domain.Core.Aggregates.FileManagement.FileManagementAggregate.ValueObjects; +using System.Threading; using System.Threading.Tasks; #endregion @@ -18,14 +19,16 @@ public interface IFileTypeService /// Determines if is of type image or not, and returns its type. /// /// The file to determine if it is an image or not. + /// Cancellation token that can be used to stop the execution. /// An containing the type of image or an error. - Task> GetImageTypeAsync(File file); + Task> GetImageTypeAsync(File file, CancellationToken cancellationToken); /// /// Determines if a file identified by is of type image or not, and returns its type. /// /// The path of the file to determine if it is an image or not. + /// Cancellation token that can be used to stop the execution. /// An containing the type of image or an error. - Task> GetImageTypeAsync(FileSystemPathId path); + Task> GetImageTypeAsync(FileSystemPathId path, CancellationToken cancellationToken); #endregion -} \ No newline at end of file +} diff --git a/src/Lumina.Domain/Core/Aggregates/FileManagement/FileManagementAggregate/Services/IThumbnailService.cs b/src/Lumina.Domain/Core/Aggregates/FileManagement/FileManagementAggregate/Services/IThumbnailService.cs index 39dfd506..55e60fd4 100644 --- a/src/Lumina.Domain/Core/Aggregates/FileManagement/FileManagementAggregate/Services/IThumbnailService.cs +++ b/src/Lumina.Domain/Core/Aggregates/FileManagement/FileManagementAggregate/Services/IThumbnailService.cs @@ -1,6 +1,7 @@ -#region ========================================================================= USING ===================================================================================== +#region ========================================================================= USING ===================================================================================== using ErrorOr; using Lumina.Domain.Core.Aggregates.FileManagement.FileManagementAggregate.ValueObjects; +using System.Threading; using System.Threading.Tasks; #endregion @@ -17,15 +18,17 @@ public interface IThumbnailService /// /// String representation of the file path. /// The quality of the thumbnail to get. + /// Cancellation token that can be used to stop the execution. /// An containing either a collection of bytes representing the thumbnail of the file at the specified path or an error. - Task> GetThumbnailAsync(string path, int quality); + Task> GetThumbnailAsync(string path, int quality, CancellationToken cancellationToken); /// /// Gets the thumbnail of a file at the specified path. /// /// The path object. /// The quality of the thumbnail to get. + /// Cancellation token that can be used to stop the execution. /// An containing either a collection of bytes representing the thumbnail of the file at the specified path or an error. - Task> GetThumbnailAsync(FileSystemPathId path, int quality); + Task> GetThumbnailAsync(FileSystemPathId path, int quality, CancellationToken cancellationToken); #endregion -} \ No newline at end of file +} diff --git a/src/Lumina.Domain/Core/Aggregates/FileManagement/FileManagementAggregate/Services/ThumbnailService.cs b/src/Lumina.Domain/Core/Aggregates/FileManagement/FileManagementAggregate/Services/ThumbnailService.cs index adf18776..23252b53 100644 --- a/src/Lumina.Domain/Core/Aggregates/FileManagement/FileManagementAggregate/Services/ThumbnailService.cs +++ b/src/Lumina.Domain/Core/Aggregates/FileManagement/FileManagementAggregate/Services/ThumbnailService.cs @@ -10,6 +10,7 @@ using SixLabors.ImageSharp.Formats.Png; using SixLabors.ImageSharp.Processing; using System; using System.IO; +using System.Threading; using System.Threading.Tasks; #endregion @@ -41,13 +42,14 @@ public class ThumbnailService : IThumbnailService /// /// String representation of the file path. /// The quality of the thumbnail to get. + /// Cancellation token that can be used to stop the execution. /// An containing either a collection of bytes representing the thumbnail of the file at the specified path or an error. - public async Task> GetThumbnailAsync(string path, int quality) + public async Task> GetThumbnailAsync(string path, int quality, CancellationToken cancellationToken) { ErrorOr fileSystemPathIdResult = FileSystemPathId.Create(path); if (fileSystemPathIdResult.IsError) return fileSystemPathIdResult.Errors; - return await GetThumbnailAsync(fileSystemPathIdResult.Value, quality); + return await GetThumbnailAsync(fileSystemPathIdResult.Value, quality, cancellationToken); } /// @@ -55,11 +57,12 @@ public class ThumbnailService : IThumbnailService /// /// The path of the file for which to get the thumbnail. /// The quality of the thumbnail to get. + /// Cancellation token that can be used to stop the execution. /// An containing either a collection of bytes representing the thumbnail of the file at the specified path or an error. - public async Task> GetThumbnailAsync(FileSystemPathId path, int quality) + public async Task> GetThumbnailAsync(FileSystemPathId path, int quality, CancellationToken cancellationToken) { // first, get the type of the image file - ErrorOr imageTypeResult = await _environmentContext.FileTypeService.GetImageTypeAsync(path); + ErrorOr imageTypeResult = await _environmentContext.FileTypeService.GetImageTypeAsync(path, cancellationToken); if (imageTypeResult.IsError) return imageTypeResult.Errors; if (imageTypeResult.Value != ImageType.None) @@ -74,7 +77,7 @@ public class ThumbnailService : IThumbnailService if (imageTypeResult.Value is ImageType.JPEG or ImageType.JPEG_CANON or ImageType.JPEG2000 or ImageType.JPEG_UNKNOWN or ImageType.PNG or ImageType.BMP or ImageType.WEBP or ImageType.GIF or ImageType.TIFF or ImageType.TGA) - adjustedImage = await AdjustImageResolutionAsync(fileContents, imageTypeResult.Value, quality); + adjustedImage = await AdjustImageResolutionAsync(fileContents, imageTypeResult.Value, quality, cancellationToken); return new Thumbnail(imageTypeResult.Value, adjustedImage ?? fileContents); } else @@ -87,8 +90,9 @@ public class ThumbnailService : IThumbnailService /// The byte array of the source image. /// The format of the image whose quality is adjusted. /// A value between 1 (lowest quality) to 100 (highest quality). + /// Cancellation token that can be used to stop the execution. /// A byte array representing the processed image. - private static async Task AdjustImageQualityAsync(byte[] imageBytes, ImageType imageType, int quality) + private static async Task AdjustImageQualityAsync(byte[] imageBytes, ImageType imageType, int quality, CancellationToken cancellationToken) { using MemoryStream inputMemoryStream = new(imageBytes); using MemoryStream outputMemoryStream = new(); @@ -99,24 +103,24 @@ public class ThumbnailService : IThumbnailService case ImageType.JPEG_CANON: case ImageType.JPEG_UNKNOWN: { - using Image image = await Image.LoadAsync(inputMemoryStream); - await image.SaveAsync(outputMemoryStream, new JpegEncoder() { Quality = quality }); + using Image image = await Image.LoadAsync(inputMemoryStream, cancellationToken); + await image.SaveAsync(outputMemoryStream, new JpegEncoder() { Quality = quality }, cancellationToken); break; } case ImageType.PNG: { - using Image image = await Image.LoadAsync(inputMemoryStream); + using Image image = await Image.LoadAsync(inputMemoryStream, cancellationToken); // PNG is lossless; quality adjustments don't apply in the same way - we can adjust compression int compressionLevel = MapRange(quality, 1, 100, 1, 9); PngEncoder encoder = new() { CompressionLevel = (PngCompressionLevel)compressionLevel }; - await image.SaveAsync(outputMemoryStream, encoder); + await image.SaveAsync(outputMemoryStream, encoder, cancellationToken); break; } case ImageType.BMP: { - using Image image = await Image.LoadAsync(inputMemoryStream); - await image.SaveAsync(outputMemoryStream, new PngEncoder()); // convert BMP to PNG for compression + using Image image = await Image.LoadAsync(inputMemoryStream, cancellationToken); + await image.SaveAsync(outputMemoryStream, new PngEncoder(), cancellationToken); // convert BMP to PNG for compression break; } default: @@ -131,12 +135,13 @@ public class ThumbnailService : IThumbnailService /// The byte array of the source image. /// The format of the image whose quality is adjusted. /// A value between 1 (lowest quality) to 100 (highest quality). + /// Cancellation token that can be used to stop the execution. /// The bytes of the adjusted image. - private static async Task AdjustImageResolutionAsync(byte[] imageBytes, ImageType imageType, int quality) + private static async Task AdjustImageResolutionAsync(byte[] imageBytes, ImageType imageType, int quality, CancellationToken cancellationToken) { using MemoryStream inputMemoryStream = new(imageBytes); using MemoryStream outputMemoryStream = new(); - Image image = await Image.LoadAsync(inputMemoryStream); + Image image = await Image.LoadAsync(inputMemoryStream, cancellationToken); double ratio = quality / 100.0; int newWidth = (int)(image.Width * ratio); int newHeight = (int)(image.Height * ratio); @@ -163,7 +168,7 @@ public class ThumbnailService : IThumbnailService case ImageType.JPEG2000: case ImageType.JPEG_CANON: case ImageType.JPEG_UNKNOWN: - await image.SaveAsync(outputMemoryStream, image.Metadata.DecodedImageFormat!); + await image.SaveAsync(outputMemoryStream, image.Metadata.DecodedImageFormat!, cancellationToken); break; default: return imageBytes; // for unsupported formats, just return the original bytes diff --git a/src/Lumina.Presentation.Web/Components/FileSystemBrowser.razor b/src/Lumina.Presentation.Web/Components/FileSystemBrowser.razor new file mode 100644 index 00000000..18963f11 --- /dev/null +++ b/src/Lumina.Presentation.Web/Components/FileSystemBrowser.razor @@ -0,0 +1,1051 @@ +@using Lumina.Presentation.Web.Common.Models.Common +@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.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 + +
+
+
+
+
+
+ + + + + +
+
+
+ +
+
+
+ @foreach (FileSystemTreeNodeModel node in treeViewRootNodes) + { + + } +
+
+ +
+ +
+
+
+
+ Name +
+
+ @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"; +
+
+
@fileSystemItem.Name
+ + +
+ } +
+
+
+
+
+
+
+ + +
+
+ Cancel + Open +
+
+
+ @*
+ + + Cancel + Confirm *@ +
+
+
+ + +@if (showPathSegmentDowpDown && expandedPathSegmentIndex.HasValue && pathSegmentsSubdirectoriesCache.ContainsKey(expandedPathSegmentIndex.Value)) +{ + +} +@code { + [Parameter] public string? Path { get; set; } + [Parameter] public bool IncludeFiles { get; set; } + + public EventCallback OnNodeSelected { get; set; } + + private List treeViewRootNodes = []; + private List fileSystemItems = []; + private FileSystemTypeModel fileSystemType = null!; + private ComboboxItem? selectedValue; + private PathSegmentModel[]? pathSegments; + private string pathSeparator = "/"; + private string? selectedNodePath; + private string? _path; + private bool isSelectionMode; + private bool showThumbnails = true; // TODO: take from config + private bool showHiddenElements; // TODO: take from config + private bool showFileSystemTreeView = true; // TODO: take from config + private bool showPathSegmentDowpDown; + private bool isNavigationPathEditMode; + private int? expandedPathSegmentIndex; + private FileSystemViewMode viewMode = FileSystemViewMode.List; // TODO: take from config + private FileSystemIconSize iconSize; + private Dictionary> pathSegmentsSubdirectoriesCache = []; + private DotNetObjectReference? reference; + private readonly Stack undoStack = []; + private readonly Stack redoStack = []; + + private readonly Dictionary _fileIcons = new() + { + { "ai", "application-postscript.svg" }, + { "apk", "android-package-archive.svg" }, + { "appimage", "application-vnd.appimage.svg" }, + { "atom", "application-atom+xml.svg" }, + { "avif", "application-image.svg" }, + { "bmp", "application-image.svg" }, + { "bz", "application-x-7z-ace.svg" }, + { "chm", "application-vnd.ms-htmlhelp.svg" }, + { "dicom", "application-dicom.svg" }, + { "dll", "application-octet-stream.svg" }, + { "dot", "application-msword-template.svg" }, + { "doc", "application-msword-template.svg" }, + { "docx", "application-msword-template.svg" }, + { "eps", "application-postscript.svg" }, + { "epub", "application-epub+zip.svg" }, + { "exe", "application-octet-stream.svg" }, + { "flac", "application-ogg.svg" }, + { "gif", "application-image.svg" }, + { "gz", "application-x-7z-ace.svg" }, + { "ico", "application-image.svg" }, + { "infopath", "application-vnd.ms-infopath.svg" }, + { "jpeg", "application-image.svg" }, + { "jpg", "application-image.svg" }, + { "json", "application-json.svg" }, + { "mdb", "application-vnd.ms-access.svg" }, + { "mp3", "application-ogg.svg" }, + { "ogg", "application-ogg.svg" }, + { "otp", "application-vnd.oasis.opendocument.presentation-template.svg" }, + { "ods", "application-vnd.oasis.opendocument.spreadsheet-template.svg" }, + { "ots", "application-vnd.oasis.opendocument.spreadsheet-template.svg" }, + { "ott", "application-vnd.oasis.opendocument.text-template.svg" }, + { "otw", "application-vnd.oasis.opendocument.web-template.svg" }, + { "p7s", "application-pgp-signature.svg" }, + { "pdf", "application-pdf.svg" }, + { "pict", "application-image.svg" }, + { "pgp", "application-pgp.svg" }, + { "png", "application-image.svg" }, + { "ppt", "application-vnd.ms-powerpoint.svg" }, + { "ps", "application-postscript.svg" }, + { "psd", "application-photoshop.svg" }, + { "pub", "application-vnd.ms-publisher.svg" }, + { "rar", "application-x-7z-ace.svg" }, + { "ref", "application-vnd.flatpak.ref.svg" }, + { "sendfile", "application-vnd.kde.bluedevil-sendfile.svg" }, + { "snap", "application-vnd.snap.svg" }, + { "stream", "application-octet-stream.svg" }, + { "svg", "application-image.svg" }, + { "sql", "application-sql.svg" }, + { "sqlite", "application-sql.svg" }, + { "tar", "application-x-7z-ace.svg" }, + { "tga", "application-image.svg" }, + { "tiff", "application-image.svg" }, + { "txt", "application-pgp-signature.svg" }, + { "wav", "application-ogg.svg" }, + { "webp", "application-image.svg" }, + { "xdgapp", "application-vnd.xdgapp.svg" }, + { "xls", "application-vnd.ms-excel.svg" }, + { "xlsx", "application-vnd.ms-excel.svg" }, + { "xml", "application-atom+xml.svg" }, + { "zip", "application-x-7z-ace.svg" } + }; + + + /// + /// Initializes the component. + /// + protected override async Task OnInitializedAsync() + { + await GetFileSystemPropertiesAsync().ConfigureAwait(false); + if (Path is not null) + { + if (!Path.EndsWith(pathSeparator)) + Path += pathSeparator; + await NavigateToPathAsync(Path, isForwardNavigation: false, isBackwardNavigation: false).ConfigureAwait(false); + } + await ChangeViewModeAsync(viewMode).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); + // assign the elements of this component instance to javascript variables, for memoization + await JSRuntime.InvokeVoidAsync("initializeFileSystemBrowser", reference).ConfigureAwait(false); + // make the navigator path segments horizontally scrollable + await JSRuntime.InvokeVoidAsync("addHorizontalScrolling", "navigator-address-bar").ConfigureAwait(false); + // subscribe to window clicks + await JSRuntime.InvokeVoidAsync("windowClickHandler", reference).ConfigureAwait(false); + } + await base.OnAfterRenderAsync(firstRender); + } + + /// + /// Handles the window click event. + /// + /// The event arguments. + [JSInvokable] + public async Task OnWindowClickAsync(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; + await InvokeAsync(StateHasChanged).ConfigureAwait(false); + } + + /// + /// Expands or collapses a node in the tree view. + /// + /// The node to expand or collapse. + private async Task ToggleTreeViewNode(FileSystemTreeNodeModel node) + { + if (!node.IsExpanded && !node.ChildrenLoaded) + { + node.Children = new List(); + node.IsExpanded = true; + await InvokeAsync(StateHasChanged).ConfigureAwait(false); + if (await CheckPathAsync(node.Path).ConfigureAwait(false)) + { + try + { + await foreach (FileSystemTreeNodeModel? childNode in _apiHttpClient.GetAsyncEnumerable($"directories/get-tree-directories?path={Uri.EscapeDataString(node.Path)}&includeHiddenElements={showHiddenElements}").ConfigureAwait(false)) + { + if (childNode is not null) + { + node.Children.Add(childNode); + await InvokeAsync(StateHasChanged).ConfigureAwait(false); + } + } + if (IncludeFiles) + { + await foreach (FileSystemTreeNodeModel? childNode in _apiHttpClient.GetAsyncEnumerable($"files/get-tree-files?path={Uri.EscapeDataString(node.Path)}&includeHiddenElements={showHiddenElements}").ConfigureAwait(false)) + { + if (childNode is not null) + { + node.Children.Add(childNode); + await InvokeAsync(StateHasChanged).ConfigureAwait(false); + } + } + } + } + catch (ApiException ex) + { + HandleApiException(ex); + } + finally + { + node.ChildrenLoaded = true; + } + } + } + else + node.IsExpanded = !node.IsExpanded; + await InvokeAsync(StateHasChanged).ConfigureAwait(false); + } + + /// + /// 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; + // fetch directories for the expanded path segment + try + { + if (concatenatedPath != pathSeparator) // on UNIX, dont get the parent, if we are at root path + { + 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}"; + } + } + catch (ApiException ex) + { + HandleApiException(ex); + } + if (!concatenatedPath.EndsWith(pathSeparator)) + concatenatedPath += pathSeparator; + // 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)}&includeHiddenElements={showHiddenElements}").ConfigureAwait(false)) + if (directory is not null) + directories.Add(directory); + // store the directories for this segment + pathSegmentsSubdirectoriesCache[toggledIndex] = directories; + expandedPathSegmentIndex = toggledIndex; + showPathSegmentDowpDown = true; + await InvokeAsync(StateHasChanged).ConfigureAwait(false); + // 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; + await InvokeAsync(StateHasChanged).ConfigureAwait(false); + } + } + + /// + /// Handles the selection of a node in the tree view. + /// + /// The path of the selected node. + /// 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) + { + if (await CheckPathAsync(path).ConfigureAwait(false)) + { + // 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 + try + { + await GetNavigatorPathAsync(path).ConfigureAwait(false); + if (showFileSystemTreeView) + await GetFileSystemTreeAsync(path).ConfigureAwait(false); + await GetFileSystemItemsAsync(path).ConfigureAwait(false); + } + catch (ApiException ex) + { + HandleApiException(ex); + } + } + 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); + await InvokeAsync(StateHasChanged).ConfigureAwait(false); + } + + /// + /// 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); + } + } + + /// + /// Handles the file system directories double click event. + /// + /// The path of the double clicked directory. + [JSInvokable()] + public async Task OnDirectoryDoubleClickAsync(string path) + { + await NavigateToPathAsync(path, isForwardNavigation: false, isBackwardNavigation: false).ConfigureAwait(false); + } + + /// + /// Gets the properties of the file system. + /// + private async Task GetFileSystemPropertiesAsync() + { + fileSystemType = await _apiHttpClient.GetAsync("file-system/get-type").ConfigureAwait(false); + // ask the API server for the system path separator + PathSeparatorModel apiPathSeparator = await _apiHttpClient.GetAsync("path/get-path-separator").ConfigureAwait(false); + pathSeparator = apiPathSeparator.Separator; // TODO: handle error + } + + /// + /// Checks if the specified path is a valid file system path. + /// + /// The path to check. + /// if the specified path is valid, otherwise. + private async Task CheckPathAsync(string path) + { + try + { + 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; + 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) + { + _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; + } + } + + /// + /// Gets the navigator path segments. + /// + /// The path for which to get the navigator path segments. + private async Task GetNavigatorPathAsync(string path) + { + pathSegments = await _apiHttpClient.GetAsync($"path/split?path={Uri.EscapeDataString(path!)}").ConfigureAwait(false); + await InvokeAsync(StateHasChanged).ConfigureAwait(false); + } + + /// + /// 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 GetFileSystemTreeAsync(string path) + { + treeViewRootNodes = []; + // on Windows, ask the list of drives + if (fileSystemType?.PlatformType == PlatformType.Windows) + { + List drives = await _apiHttpClient.GetAsync>("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 + List initialTree = await _apiHttpClient.GetAsync>($"directories/get-directory-tree?path={Uri.EscapeDataString(path!)}&includeFiles={IncludeFiles}&includeHiddenElements={showHiddenElements}").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($"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]; + } + } + + /// + /// Retrieves the files and directories for the specified path. + /// + /// The path for which to get the files and directories. + private async Task GetFileSystemItemsAsync(string path) + { + fileSystemItems.Clear(); + try + { + await foreach (DirectoryModel? directory in _apiHttpClient.GetAsyncEnumerable($"directories/get-directories?path={Uri.EscapeDataString(path)}&includeHiddenElements={showHiddenElements}").ConfigureAwait(false)) + { + if (directory is not null) + { + fileSystemItems.Add(directory); + await InvokeAsync(StateHasChanged).ConfigureAwait(false); + } + } + if (IncludeFiles) + { + await foreach (FileModel? file in _apiHttpClient.GetAsyncEnumerable($"files/get-files?path={Uri.EscapeDataString(path)}&includeHiddenElements={showHiddenElements}").ConfigureAwait(false)) + { + if (file is not null) + { + fileSystemItems.Add(file); + await InvokeAsync(StateHasChanged).ConfigureAwait(false); + } + } + } + } + catch (ApiException ex) + { + HandleApiException(ex); + } + } + + /// + /// Changes the current file system explorer view. + /// + /// The new explorer view to change to. + 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); + await JSRuntime.InvokeVoidAsync("switchViewMode").ConfigureAwait(false); + await InvokeAsync(StateHasChanged).ConfigureAwait(false); + } + + /// + /// Changes the icon size for the file system items. + /// + /// Thew new icon size to change to. + private async Task ChangeIconSizeAsync(FileSystemIconSize newIconSize) + { + viewMode = FileSystemViewMode.Icons; + iconSize = newIconSize; + await InvokeAsync(StateHasChanged).ConfigureAwait(false); + } + + /// + /// Returns the path to an SVG icon based on the file extension. + /// + /// The full name of the file including its extension. + /// The type of the file system item for which to get the item path. + /// The path to the appropriate SVG icon or a default one if not found. + private string GetFileSystemItemIconPath(string? filename, string type) + { + if (filename is not null) + { + // extract file extension from filename manually + var fileExtension = filename.Contains(".") ? filename.Split('.').Last().ToLower() : string.Empty; + // return the appropriate SVG image path or a default one if not found + return _fileIcons.ContainsKey(fileExtension) ? _fileIcons[fileExtension] : type + ".svg"; + } + else + return type + ".svg"; + } + + /// + /// Enters the edit mode where the navigator path can be edited freely. + /// + private async Task EnterNavigationPathEditModeAsync() + { + isNavigationPathEditMode = true; + await InvokeAsync(StateHasChanged).ConfigureAwait(false); + await InvokeAsync(async () => + { + await Task.Delay(50); // a small delay is necessary to ensure the DOM has updated + await SetFocusOnNavigatorAddressInputAsync().ConfigureAwait(false); + }); + } + + /// + /// Exits the edit mode where the navigator path can be edited freely. + /// + private async Task ExitNavigationPathEditModeAsync() + { + isNavigationPathEditMode = false; + await InvokeAsync(StateHasChanged).ConfigureAwait(false); + if (Path is not null) + { + 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) + { + await InvokeAsync(StateHasChanged).ConfigureAwait(false); + if (selectedNodePath is not null) + { + Path = path; + if (!Path.EndsWith(pathSeparator)) + Path += pathSeparator; + await NavigateToPathAsync(Path, isForwardNavigation: false, isBackwardNavigation: false).ConfigureAwait(false); + } + } + + /// + /// Handles the Escape key being pressed in the navigator address input. + /// + private async Task HandleNavigatorInputEscapePressedAsync() + { + Path = _path; + isNavigationPathEditMode = false; + await InvokeAsync(StateHasChanged).ConfigureAwait(false); + } + + /// + /// Sets the focus to the navigator address input. + /// + public async Task SetFocusOnNavigatorAddressInputAsync() + { + await JSRuntime.InvokeVoidAsync("focusNavigatorInputElement").ConfigureAwait(false); + } + + /// + /// Enables or disables selection mode. + /// + private async Task ToggleSelectionModeAsync() + { + isSelectionMode = !isSelectionMode; + await JSRuntime.InvokeVoidAsync("toggleSelectionMode").ConfigureAwait(false); + } + + /// + /// Enables or disables the display of the file system tree view. + /// + private async Task ToggleFileSystemTreeViewAsync() + { + showFileSystemTreeView = !showFileSystemTreeView; + // if file system treeview needs to be displayed, get its file system tree structure from the API + if (showFileSystemTreeView && Path is not null) + { + if (!Path.EndsWith(pathSeparator)) + Path += pathSeparator; + await NavigateToPathAsync(Path, isForwardNavigation: false, isBackwardNavigation: false).ConfigureAwait(false); + } + } + + /// + /// Enables or disables the display of hidden file system files and directories. + /// + private async Task ToggleHiddenElementsModeAsync() + { + showHiddenElements = !showHiddenElements; + if (Path is not null) + { + if (!Path.EndsWith(pathSeparator)) + Path += pathSeparator; + await NavigateToPathAsync(Path, isForwardNavigation: false, isBackwardNavigation: false).ConfigureAwait(false); + } + } + + /// + /// Enables or disables selection mode. + /// + private async Task ToggleThumbnailsAsync() + { + showThumbnails = !showThumbnails; + await Task.CompletedTask; + //await JSRuntime.InvokeVoidAsync("toggleSelectionMode").ConfigureAwait(false); + } + + /// + /// 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(); + } +} diff --git a/src/Lumina.Presentation.Web/Components/FileSystemBrowser.razor.css b/src/Lumina.Presentation.Web/Components/FileSystemBrowser.razor.css new file mode 100644 index 00000000..e468c38f --- /dev/null +++ b/src/Lumina.Presentation.Web/Components/FileSystemBrowser.razor.css @@ -0,0 +1,1145 @@ +#file-system-browser-dialog { + position: absolute; + top: 12.5%; + bottom: 12.5%; + left: 10%; + right: 10%; + padding: 10px; + border: 1px solid var(--border-color-dialog); + box-shadow: 30px 30px 25px var(--shadow-color); + user-select: none; +} + +#file-system-browser-content { + margin: 0px; + height: 100%; + display: flex; + flex-direction: column; + flex-wrap: nowrap; + align-items: center; + align-content: center; + gap: 0px; + flex-grow: 1; + min-height: 0; +} + +#file-system-browser-header { + border-radius: 5px 5px 0 0; + border: 1px solid; + background: linear-gradient(to bottom, #505050 0%, #464646 35%, #404040 55%, #363636 100%); + border-color: var(--border-color-light) var(--border-color-dark) var(--border-color-dark) var(--border-color-light); + height: 40px; + display: flex; + flex-direction: column; + flex-wrap: nowrap; + align-items: stretch; + justify-content: flex-start; + position: relative; + width: 100%; +} + +#file-system-browser-header-navigation-container { + display: flex; + flex-direction: row; + flex-wrap: nowrap; + align-items: center; + align-content: center; + gap: 5px; + flex-grow: 1; + margin: 5px; +} + +#file-system-browser-header-address-bar-container { + display: flex; + flex-direction: row; + flex-wrap: nowrap; + align-items: center; + align-content: center; + gap: 5px; + flex-grow: 1; +} + +.file-system-browser-header-address-bar-url { + flex-grow: 1; + flex-shrink: 1; + min-width: 0; +} + +::deep .file-system-browser-content-new-directory { + min-width: 35px; + flex-basis: 35px; + flex-shrink: 0; + margin-left: 5px; +} + +.navigation-icon { + width: 20px; + cursor: pointer; + transition: background-color 0.3s; +} + + .navigation-icon.disabled { + opacity: 0.7; + cursor: not-allowed; + } + +.file-system-browser-header-navigation { + display: flex; + gap: 5px; +} + +.file-system-browser-header-address-bar-actions { + display: flex; + align-items: center; + gap: 5px; +} + +.favorite-unselected { + filter: grayscale(100%) opacity(50%); +} + +.favorite-unselected, .favorite-selected { + width: 20px; + height: 20px; + transition: filter 0.3s ease; +} + +#file-system-browser-file-system-container { + width: 100%; + flex-grow: 1; + display: flex; + flex-direction: row; + flex-wrap: nowrap; + align-items: stretch; + overflow: hidden; + gap: 0px; + min-height: 0; +} + +#file-system-browser-file-system-treeview-container { + background-color: #131313; + border-top: 1px solid var(--border-color-light); + border-left: 1px solid var(--border-color-light); + border-right: 1px solid var(--border-color-dark); + min-width: 170px; + max-width: 400px; + width: 400px; + height: 100%; + max-height: 100%; + flex-shrink: 0; + display: flex; + flex-direction: column; + flex-wrap: nowrap; + align-items: center; + gap: 0px; + padding: 10px; + overflow: hidden; + min-height: 0; +} + +#file-system-browser-file-system-treeview-container.collapsed { + max-width: 0px; + min-width: 0px; + border: 0px; + padding: 0px; +} + +#file-system-browser-file-system-treeview { + background-color: #131313; + border: 1px solid var(--border-color-light); + border-top: 1px solid var(--border-color-dark); + border-left: 1px solid var(--border-color-dark); + margin-bottom: 10px; + flex-grow: 1; + width: 100%; + box-shadow: inset 2px 2px 5px var(--shadow-color); + overflow: auto; + max-height: 100%; + min-height: 0; +} + +::deep .file-system-browser-file-system-sources { + flex-grow: 0; +} + +#file-system-browser-file-system-directories-container { + background-color: #131313; + border-top: 1px solid var(--border-color-light); + border-left: 1px solid var(--border-color-light-medium); + flex-grow: 1; + min-width: 135px; + padding: 10px; +} + +#file-system-browser-file-system-directories { + background-color: #262626; + border: 1px solid var(--border-color-light); + border-top: 1px solid var(--border-color-dark); + border-left: 1px solid var(--border-color-dark); + width: 100%; + height: 100%; + box-shadow: inset 2px 2px 5px var(--shadow-color); + margin: auto; + width: 100%; + height: 100%; + display: flex; + flex-direction: row; + flex-wrap: nowrap; + justify-content: left; + align-items: stretch; +} + +#file-system-browser-file-system-explorer-container { + background-color: #232323; + margin: auto; + width: 100%; + height: 100%; +} + +#file-system-browser-file-system-explorer-details-header { + color: deepskyblue; +} + +#file-system-browser-file-system-explorer { +} + +div[id^="file-system-browser-file-system-explorer"]:not([id*="container"]) { + margin: 1px; + display: flex; + flex-direction: column; + flex-wrap: wrap; + border: 0px solid black; + padding: 0px; + gap: 0px 10px; +} + +.details { + width: 100% !important; + overflow-x: hidden; + height: auto !important; +} + +.list { + width: auto !important; + overflow-x: auto; + height: 100% !important; +} + +/*filesystem element*/ +.e { + font-family: monospace; + min-height: 16px; + white-space: nowrap; + padding: 1px 5px 1px 1px; + background-color: #191E21; + border-bottom-color: #000000; + border-bottom-style: solid; + border-bottom-width: 1px; + border-top-color: #444444; + border-top-style: solid; + border-top-width: 1px; + border-right-color: #000000; + border-right-style: solid; + border-right-width: 1px; + border-left-color: #444444; + border-left-style: solid; + border-left-width: 1px; + display: flex; + align-items: center; + user-select: none; +} + + .e.details-icons { + width: 100%; + display: flex; + align-items: center; + } + + .e.small-icons { + width: 320px; + align-items: center; + } + + .e.medium-icons { + width: 74px; + height: 115px; + flex-direction: column; + align-items: center; + padding: 5px; + } + + .e.large-icons { + width: 105px; + height: 161px; + flex-direction: column; + align-items: center; + padding: 5px; + } + + .e.extra-large-icons { + width: 270px; + height: 290px; + flex-direction: column; + align-items: center; + padding: 5px; + } + + .e.list-icons .icon { + width: 16px; + height: 16px; + display: flex; + align-items: center; + margin-right: 3px; + } + + .e.details-icons .icon { + width: 16px; + height: 16px; + display: flex; + align-items: center; + margin-right: 3px; + display: flex; + justify-content: center; + } + + .e.small-icons .icon { + width: 16px; + height: 16px; + display: flex; + align-items: center; + margin-right: 3px; + } + + .e.medium-icons .icon { + width: 100%; + height: 48px; + display: flex; + justify-content: center; + align-items: center; + padding-bottom: 5px; + } + + .e.large-icons .icon { + width: 100%; + height: 90px; + display: flex; + justify-content: center; + align-items: center; + padding-bottom: 5px; + } + + .e.extra-large-icons .icon { + width: 100%; + height: 240px; + display: flex; + justify-content: center; + align-items: center; + padding-bottom: 5px; + } + + .e.list-icons .icon img { + height: 16px; + width: 16px; + } + + .e.details-icons .icon img { + height: 16px; + width: 16px; + } + + .e.small-icons .icon img { + height: 16px; + width: 16px; + } + + .e.medium-icons .icon img { + height: 48px; + width: auto; + max-width: 100%; + } + + .e.large-icons .icon img { + height: 90px; + width: auto; + max-width: 100%; + } + + .e.extra-large-icons .icon img { + height: 240px; + width: auto; + max-width: 100%; + } + + .e.small-icons .text { + width: 293px; + display: flex; + align-items: center; + } + + .e.medium-icons .text { + width: 74px; + height: 67px; + display: flex; + justify-content: center; + align-items: center; + overflow: hidden; + white-space: nowrap; + text-overflow: ellipsis; + } + + .e.large-icons .text { + width: 94px; + height: 66px; + display: flex; + justify-content: center; + align-items: center; + overflow: hidden; + white-space: nowrap; + text-overflow: ellipsis; + } + + .e.extra-large-icons .text { + width: 256px; + height: 36px; + display: flex; + justify-content: center; + align-items: center; + overflow: hidden; + white-space: nowrap; + text-overflow: ellipsis; + } + + .e.details-icons .text span { + overflow: hidden; + text-overflow: ellipsis; + } + + .e.small-icons .text span { + overflow: hidden; + text-overflow: ellipsis; + } + + .e.medium-icons .text span { + max-width: 74px; + max-height: 67px; + display: block; + white-space: pre-wrap; + word-wrap: break-word; + } + + .e.large-icons .text span { + max-width: 94px; + max-height: 66px; + display: block; + white-space: pre-wrap; + word-wrap: break-word; + } + + .e.extra-large-icons .text span { + max-width: 256px; + max-height: 36px; + display: block; + white-space: pre-wrap; + word-wrap: break-word; + } + + .e.details-icons .date-modified, + .e.details-icons .type, + .e.details-icons .size { + display: flex; + align-items: center; + padding-left: 10px; + overflow: hidden; + text-overflow: ellipsis; + text-align: right; + white-space: nowrap; + } + + .e.details-icons .text { + flex-grow: 1; + display: flex; + align-items: center; + padding-left: 1px; + } + + .e.details-icons .date-modified { + width: 180px; + padding-left: 10px; + } + + .e.details-icons .type { + width: 200px; + padding-left: 10px; + } + + .e.details-icons .size { + width: 100px; + padding-left: 10px; + padding-right: 10px; + display: flex; + justify-content: flex-end; + } + + .e:nth-child(even) { + background-color: #28292B; + } + + .e:hover { + background-color: #404040; + border-top-color: #999999; + border-left-color: #999999; + } + + .e.selected { + background-color: #4D4D4D; + border-top-color: #999999; + border-left-color: #999999; + } + + .e.selection-hover { + background-color: #0048D7; + } + + .e.cut { + background-color: #19233b; + } + + .e.cut img { + opacity: 30%; + } + +/*directory*/ +.d { + color: #6DCBFE; +} + +/*file*/ +.f { + color: #BBBBBB; +} + +/*filesystem item text*/ +.t { + user-select: none; +} + +#file-system-browser-actions-container { + flex-grow: 0; + display: flex; + flex-direction: column; + flex-wrap: nowrap; + align-items: flex-start; + align-content: center; + gap: 5px; + width: 100%; +} + +#file-system-browser-actions { + flex-grow: 0; + display: flex; + flex-direction: row; + flex-wrap: nowrap; + justify-content: flex-end; + gap: 5px; + width: 100%; +} + +#file-system-browser-actions-path-container { + margin-top: 5px; + display: flex; + flex-direction: row; + flex-wrap: nowrap; + align-items: center; + gap: 5px; + width: 100%; +} + +#file-system-browser-shine-effect { + background: linear-gradient(to right, transparent, #fff, transparent); + width: 100%; + height: 1px; + flex-shrink: 0; + pointer-events: none; /* ensure it doesn't interfere with interactions */ +} + +#file-system-browser-shine-spark { + position: absolute; + top: -2px; + left: -20px; /* start off-screen */ + width: 20px; + height: 5px; + background: radial-gradient(ellipse at center, rgba(255,255,255,1) 0%, rgba(255,255,255,0.8) 50%, rgba(255,255,255,0) 100%); + border-radius: 50%; + filter: blur(1px); + opacity: 0; + animation: spark-animation 30s cubic-bezier(0.25, 0.9, 0.9, 0.1) infinite; +} + + #file-system-browser-shine-spark::before { + content: ''; + position: absolute; + top: 50%; + left: 50%; + width: 10px; + height: 10px; + background: white; + clip-path: polygon(50% 0%, 61% 35%, 98% 35%, 68% 57%, 79% 91%, 50% 70%, 21% 91%, 32% 57%, 2% 35%, 39% 35%); + transform: translate(-50%, -50%); + filter: blur(0.5px); + animation: star-rotation 5s linear infinite; + } + + #file-system-browser-shine-spark::after { + content: ''; + position: absolute; + top: 50%; + left: 50%; + width: 6px; + height: 6px; + background: #FFFFFF; + border-radius: 50%; + transform: translate(-50%, -50%); + } + +@keyframes spark-animation { + 40% { + left: -20px; + opacity: 0; + } + + 50% { + opacity: 1; + } + + 60% { + left: 100%; + opacity: 0; + } +} + +@keyframes star-rotation { + from { + transform: translate(-50%, -50%) rotate(0deg); + } + + to { + transform: translate(-50%, -50%) rotate(360deg); + } +} + +/*File System Navigator*/ +#navigator-navigation-controls-container { + display: flex; + align-items: center; +} + +#navigator-history { + display: flex; + align-items: center; + margin-right: 10px; +} + +#navigator-history, ::deep .navigator-navigate-button, ::deep .navigator-edit-path-button { + flex-shrink: 0; /* don't let them shrink */ +} + + #navigator-history img { + width: 26px; + height: 26px; + margin-left: 5px; + } + +.navigator-icon { + width: 30px; + height: 30px; + cursor: pointer; +} + +.navigator-icon-fill { + color: #039bfc; +} + + .navigator-icon-fill.enabled { + color: #f00; + } + +#navigator-new-directory-icon { + width: 22px; + height: 22px; +} + +#navigator-navigate-icon, +#navigator-edit-icon { + width: 24px; + height: 24px; +} + +::deep .navigator-navigate-button, ::deep .navigator-edit-path-button { + text-align: end !important; + flex-shrink: 0; +} + +::deep .navigator-navigate-button, +::deep .file-system-browser-content-new-directory { + margin: 0px 10px 2px 0px; + flex-shrink: 0; +} + +::deep .file-system-browser-content-favorite-directory { + margin: 0px 2px 2px 0px; + flex-shrink: 0; +} + +::deep .navigator-edit-path-button { + margin: 0px 10px 2px 12px; + flex-shrink: 0; +} + +#navigator-address-bar-container { + flex-grow: 1; + display: flex; + height: 28px; + align-items: center; + overflow-x: hidden; + margin-right: 5px; +} + + + #navigator-address-bar-container::-webkit-scrollbar, + #navigator-address-bar-group::-webkit-scrollbar { + display: none; + width: 0; + } + +#navigator-address-bar-container, +#navigator-address-bar-group { + scrollbar-width: none; /* Firefox 64+ */ +} + +#navigator-address-bar-container, +#navigator-address-bar-group { + -ms-overflow-style: none; /* IE 10+ */ +} + + +/* for Webkit browsers like Chrome, Safari */ +#navigator-address-bar::-webkit-scrollbar { + height: 0; +} + +/* for Internet Explorer and Edge */ +#navigator-address-bar { + -ms-overflow-style: none; /*IE and Edge */ +} + + /* for Firefox */ + #navigator-address-bar ::-moz-scrollbar { + width: 0; + display: none; + } + + +#navigator-address-bar-group { + flex-grow: 1; /* let it take the remaining space */ + display: flex; /* use flex for its children */ + flex-wrap: nowrap; + align-items: center; /* vertically center its children */ + height: 30px; + overflow-x: hidden; +} + + +#navigator-view-mode-container { + display: flex; + margin-right: 0px; + align-items: center; + width: 125px; + margin-left: 5px; +} + + #navigator-view-mode-container img { + margin-right: 5px; + width: 16px; + height: 16px; + cursor: pointer; + } + + +::deep .navigator-address-bar-input { + width: 100%; +} + + +#navigator-address-bar { + background-color: #23232355; + margin-top: -2px; + padding-left: 2px; + vertical-align: middle; + height: 30px; + flex-grow: 1; + overflow-x: auto; + overflow-y: hidden; + -webkit-overflow-scrolling: touch; +} + + #navigator-address-bar ul { + height: 100%; + list-style-type: none; + padding: 0; + display: flex; + align-items: center; + } + +#navigator-path-segments { + margin: 0px !important; +} + +.navigator-combobox { + position: relative; + font-family: Arial, sans-serif; + padding: 0; + margin: 0; + box-sizing: border-box; +} + +.navigator-toggle-checkbox { + display: none; +} + + .navigator-toggle-checkbox:checked + .navigator-toggle + .navigator-dropdown { + display: block; + } + + .navigator-toggle-checkbox:checked + .navigator-toggle .navigator-arrow { + background-size: 9px 11px; + background-position: 3px -2px; + transform: rotate(90deg); + } + +.navigator-toggle { + display: flex; + align-items: center; + justify-content: space-between; + cursor: pointer; + font-family: Arial, sans-serif; + font-size: 14px; + border-top-left-radius: 2px; + border-top-right-radius: 4px; + border-bottom-right-radius: 3px; + border-bottom-left-radius: 3px; + box-shadow: 0 0 3px rgba(0, 0, 0, 0.5); + color: #6DCBFE; + padding: 3px 8px 3px 8px; + width: 100%; + border: none; + outline: none; + appearance: none; + border-top: #989898 1px solid; + border-bottom: #151515 1px solid; + border-left: #878787 1px solid; + border-right: #202020 1px solid; + background-image: linear-gradient(180deg, #606060, #555555, #4C4C4C, #414141); + background-repeat: repeat; + background-position: 0 0; + background-size: 100%; + user-select: none; + box-sizing: border-box; +} + +.navigator-arrow { + display: inline-block; + width: 12px; + height: 9px; + background-image: url('data:image/svg+xml;charset=US-ASCII,%3Csvg%20xmlns%3D%22http%3A%2F%2Fwww.w3.org%2F2000%2Fsvg%22%20viewBox%3D%22545%20-32.5%2027.5%2065%22%3E%3Cpath%20fill%3D%22%23FFF%22%20d%3D%22M568.254,-7.43524%20568.159,-7.34277%20567.977,-7.52246%20546.559,-28.9417%20525.484,-28.9417%20549.787,-4.63446%20557.439,3.01532%20557.619,3.19629%20550.067,10.7549%20525.758,35.0583%20546.834,35.0583%20568.254,13.6429%20578.792,3.10254%20568.254,-7.43524z%22%2F%3E%3C%2Fsvg%3E'); + background-size: 10px 9px; + background-repeat: no-repeat; + background-position: 3px -0px; + transition: transform 0.3s ease; +} + +.navigator-toggle-checkbox:checked + .navigator-toggle .navigator-arrow { + transform: rotate(90deg); +} + +.navigator-selected-text { + flex-grow: 1; + text-align: right; + white-space: nowrap; +} + +.navigator-dropdown { + display: none; + position: absolute; + top: 0; + left: 0; + min-width: 150px; + max-width: 800px; + box-sizing: border-box; + background-image: url('../images/ui/metal-plate.png'), linear-gradient(180deg, #505050, #464646, #404040, #363636); + background-repeat: repeat, no-repeat; + background-position: 3px 3px, 0 0; /* offset the metal-plate image by 3 pixels from the top and left */ + background-clip: content-box, border-box; /* clip the metal-plate image to the content box */ + border-top: #989898 1px solid; + border-bottom: #151515 1px solid; + border-left: #878787 1px solid; + border-right: #202020 1px solid; + padding: 3px; + z-index: 999; + max-height: calc(100vh - 100px); /* Subtracting a small value ensures a little space is left on top and bottom */ + overflow-y: auto; +} + + .navigator-dropdown.opened { + display: block; + } + +.navigator-option { + display: block; + border-left: 1px solid #232323; + border-right: 1px solid #777777; + border-top: 1px solid #232323; + border-bottom: 1px solid #777777; + color: #FFFFFF; + padding: 5px 10px; + min-width: 100%; + box-sizing: border-box; + user-select: none; + cursor: pointer; + text-align: start; + white-space: nowrap; +} + + .navigator-option.first-option { + border-top: 1px solid #232323; + margin-top: -1px; + } + + .navigator-option.last-option { + border-bottom: 1px solid #777777; + } + + .navigator-option.disabled { + color: #AAAAAA; /* Gray color */ + } + + .navigator-option:hover { + background-image: none; + background: linear-gradient(to bottom, #505050, #464646, #404040, #363636); + color: #1D8AF9; + box-shadow: inset 1px 0 0 0 #777777, /* left */ + inset -1px 0 0 0 #232323, /* right */ + inset 0 1px 0 0 #989898, /* top */ + inset 0 -1px 0 0 #151515; /* bottom */ + } + +.navigator-combobox > .shine-effect:first-child { + opacity: 0; + transition: opacity 0.5s; +} + +.navigator-combobox:hover > .shine-effect:first-child { + opacity: 1; +} + +.navigator-combobox > .shine-effect::before, +.navigator-combobox > .shine-effect::after { + content: ""; + position: absolute; + top: -1px; + left: 50%; + transform: translateX(-50%); + opacity: 0; + transition: opacity 0.5s; +} + +.navigator-combobox > .shine-effect::before { + width: 3px; + height: 2px; + border-radius: 5px 5px 0 0; + background-color: #FFFFFF; +} + +.navigator-combobox > .shine-effect::after { + width: 10px; + height: 3px; + border-radius: 5px 5px 0 0; + background-color: #FFFFFF; + filter: blur(3px); +} + +.navigator-combobox:hover > .shine-effect::before, +.navigator-combobox:hover > .shine-effect::after { + opacity: 1; +} + + +#selection-rectangle { + background-color: transparent; + border: 0px; + pointer-events: none; + position: absolute; + top: 0px; + left: 0px; + width: 0px; + height: 0px; +} + +#visible-selection-rectangle { + background-color: #0078D777; + border: 1px solid #0078D7; + pointer-events: none; /* so it doesn't interfere with the mouse events */ + position: absolute; + top: 0px; + left: 0px; + width: 0px; + height: 0px; + visibility: hidden; + z-index: 1000; +} + +.scroll-vertical { + overflow-x: hidden; + overflow-y: auto; +} + +.scroll-horizontal { + overflow-x: auto; + overflow-y: hidden; +} + +@media screen and (max-width: 768px) { + #file-system-browser-dialog { + top: 0; + bottom: 0; + left: 0; + right: 0; + } + + #file-system-browser-header { + height: auto; + } + + #file-system-browser-header-navigation-container { + flex-wrap: wrap; + align-items: flex-start; + } + + #navigator-view-mode-container { + flex-grow: 1; + order: 1; + } + + #navigator-navigation-controls-container { + flex-grow: 1; + order: 2; + /*text-align: right;*/ + justify-content: flex-end; + width: auto; + } + + #navigator-address-bar-container { + flex-basis: 100%; + order: 3; + } + + #file-system-browser-header-address-bar-container { + flex-direction: column; + align-items: stretch; + width: 100%; + } + + .file-system-browser-header-address-bar-url { + width: 100%; + margin-bottom: 5px; + } + + .file-system-browser-header-navigation { + display: flex; + gap: 5px; + margin-bottom: 5px; + } + + .file-system-browser-header-address-bar-actions { + display: flex; + justify-content: space-between; + align-items: center; + width: 100%; + } + + ::deep .file-system-browser-content-new-directory { + min-width: 0; + flex-basis: auto; + margin-right: 10px; + margin-left: 0px; + } + + /*File System Navigator*/ + #navigator-view-mode-container { + height: 26px; + margin-left: 11px; + } + + #navigator-address-bar-container { + width: 100%; + flex-basis: 100%; + } + + #navigator-address-bar-group { + margin-left: 10px; + } + + #navigator-toggle-selection-button { + margin-right: 4px; + } + + #navigator-history { + margin-right: 2px; + } + + #file-system-browser-file-system-treeview-container { + flex-shrink: 1; + } +} + + +@media screen and (max-width: 399px) { + #file-system-browser-dialog { + min-width: 400px + } + + .e.extra-large-icons { + width: 100%; + } + + .e.extra-large-icons .text { + width: calc(100% - 14px); + } + + .e.extra-large-icons .text span { + max-width: 400px; + } + + .e.large-icons { + width: 164px; + } + + .e.large-icons .text { + width: calc(100% - 14px); + } + + .e.large-icons .text span { + width: calc(100% - 14px); + } + + .e.medium-icons { + width: 102px; + } + + .e.medium-icons .text { + width: calc(100% - 14px); + } + + .e.medium-icons .text span { + width: calc(100% - 14px); + } +} diff --git a/src/Lumina.Presentation.Web/Pages/Home.razor b/src/Lumina.Presentation.Web/Pages/Home.razor new file mode 100644 index 00000000..3fe80322 --- /dev/null +++ b/src/Lumina.Presentation.Web/Pages/Home.razor @@ -0,0 +1,7 @@ +@page "/" + +@using Lumina.Presentation.Web.Components + +Lumina - Home + + diff --git a/src/Lumina.Presentation.Web/wwwroot/js/site.js b/src/Lumina.Presentation.Web/wwwroot/js/site.js index 85bc1373..4689be0f 100644 --- a/src/Lumina.Presentation.Web/wwwroot/js/site.js +++ b/src/Lumina.Presentation.Web/wwwroot/js/site.js @@ -11,8 +11,43 @@ let fileSystemExplorerContainer = null; let visibleSelectionRectangle = null; let selectionRectangle = null; +let scrollTimeout; // timeout to delay thumbnail loading after scrolling +let resizeTimeout; // timeout to delay thumbnail loading after resizing +let abortController; // allows the cancellation of thumbnail retrieval jobs +let hasScrolledAfterModeChange = false; // flag to track if scrolling occurred after a mode change +let showThumbnails = true; // whether to show thumbnails or not +let scrollThumbnailRetrievalTimeout = 1000; // the time span to wait after the last scroll, before getting thumbnails +let inspectFileForThumbnails = false; // whether to check the actual header bytes in order to determine if a file is an image, rather than its extension +let thumbnailsRetrievalBatchSize = 20; // the number of thumbnails to ask from the server, concurrently +let imagePreviewsQuality = 70; // the quality used for image thumbnails +let fullImageQuality = 90; // the quality used for full images + // =================== common helper function =================== +/** + * Convert Blob to Base64. + * @param {any} blob The blob to convert. + * @returns The converted Base64 string. + */ +async function blobToBase64(blob) { + return new Promise((resolve, reject) => { + const reader = new FileReader(); + reader.onloadend = () => resolve(reader.result.split(',')[1]); + reader.onerror = reject; + reader.readAsDataURL(blob); + }); +} + +/** + * Determines if the given file path corresponds to an image file. + * @param {string} filePath - The path to the file to be checked. + * @returns {boolean} True if the file path ends with an image file extension, false otherwise. + */ +function isImageFile(filePath) { + // Adjust the regex pattern to match the image file extensions you support + return /\.(jpe?g|png|gif|bmp|svg|ico|webp)$/i.test(filePath); +} + /** * Gets the current time * @returns the current time @@ -217,6 +252,59 @@ function closeNavigatorPathSegments() { checkboxes[i].checked = false; } +/** + * Handles the scroll event for the explorer or explorerContainer. + * Clears any previous timeout and creates a new one to fetch visible items. + */ +function handleFileSystemBrowserScrollEvent() { + // clear any previously set timeouts to debounce the getVisibleItems call + if (scrollTimeout) clearTimeout(scrollTimeout); + // if there's an ongoing operation, abort it + if (abortController) { + abortController.abort(); + abortController = null; + } + // set a timeout to call getVisibleItems once the user stops scrolling + scrollTimeout = setTimeout(() => { + if (showThumbnails) + getVisibleItems(); + }, scrollThumbnailRetrievalTimeout); + hasScrolledAfterModeChange = true; +} + +/** + * Handles the window's resize event. + * Clears any previous timeout and creates a new one to fetch file system browser visible items. + */ +function handleFileSystemBrowserResizeEvent() { + // clear any previously set timeouts to debounce the getVisibleItems call during resize + if (resizeTimeout) clearTimeout(resizeTimeout); + // if there's an ongoing operation, abort it + if (abortController) { + abortController.abort(); + abortController = null; + } + // set a timeout to call getVisibleItems once the user stops resizing + resizeTimeout = setTimeout(() => { + if (showThumbnails) + getVisibleItems(); + }, scrollThumbnailRetrievalTimeout); +} + +/** + * Switches to a different view mode. + */ +function switchViewMode() { + hasScrolledAfterModeChange = false; // reset the flag indicating a mode change + // check if content has been scrolled after the mode change; since scroll is the one triggering thumbnails retrieval, + // and there is no initial scroll when mode is changed, we need to trigger the retrieval manually + setTimeout(() => { + if (!hasScrolledAfterModeChange && showThumbnails) + getVisibleItems(); + }, 50); // wait 50ms to ensure all other events have processed +} + + // =================== file system browser dialog selection =================== /** @@ -231,8 +319,10 @@ function initializeFileSystemBrowser(dotnetHelper) { visibleSelectionRectangle = document.getElementById('visible-selection-rectangle'); if (!fileSystemExplorer) { fileSystemExplorer = document.getElementById('file-system-browser-file-system-explorer'); - if (fileSystemExplorer) - fileSystemExplorer.addEventListener('mouseup', fileSystemExplorerMouseUp); + if (fileSystemExplorer) { + fileSystemExplorer.addEventListener('mouseup', handleFileSystemExplorerMouseUp); + fileSystemExplorer.addEventListener('scroll', handleFileSystemBrowserScrollEvent); + } } // event handlers needed for selection if (!fileSystemExplorerContainer) { @@ -242,6 +332,7 @@ function initializeFileSystemBrowser(dotnetHelper) { fileSystemExplorerContainer.addEventListener('mousemove', updateSelection); fileSystemExplorerContainer.addEventListener('mouseup', endSelection); fileSystemExplorerContainer.addEventListener('wheel', handleSelection); + fileSystemExplorerContainer.addEventListener('scroll', handleFileSystemBrowserScrollEvent); fileSystemExplorerContainer.addEventListener('scroll', handleSelection); } } @@ -273,8 +364,7 @@ function initializeFileSystemBrowser(dotnetHelper) { dotnetHelper.invokeMethodAsync('OnDirectoryDoubleClickAsync', e.currentTarget.dataset.path); return; } - else - { // files + else { // files } // reset the timestamp used to track double clicks @@ -302,8 +392,7 @@ function initializeFileSystemBrowser(dotnetHelper) { for (let i = from; i <= to; i++) allEClassElements[i].classList.add('selected'); } - else - { // when neither CTRL nor SHIFT keys are pressed + else { // when neither CTRL nor SHIFT keys are pressed if (!isSelectionMode) { // get all elements that are selected const selectedElements = allEClassElements.filter(element => element.classList.contains('selected')); @@ -335,10 +424,10 @@ function initializeFileSystemBrowser(dotnetHelper) { * Handler for the mouse up event of the file system browser dialog explorer * @param {MouseEvent} e - The mouseup event object. */ -function fileSystemExplorerMouseUp(e) { +function handleFileSystemExplorerMouseUp(e) { const explorerScrollbars = hasScrollbars(fileSystemExplorer); // check if clicked on the horizontal scrollbar - if (explorerScrollbars.horizontal && e.clientY > fileSystemExplorer.getBoundingClientRect().top + fileSystemExplorer.offsetHeight - scrollbarHeight) + if (explorerScrollbars.horizontal && e.clientY > fileSystemExplorer.getBoundingClientRect().top + fileSystemExplorer.offsetHeight - scrollbarHeight) return; if (!e.ctrlKey && !e.shiftKey && !isSelectionMode) { // deselect all file system elements when their explorer is clicked @@ -504,6 +593,115 @@ function toggleSelectionMode(e) { isSelectionMode = !isSelectionMode; } +// =================== file system browser dialog thumbnails preview =================== + +/** + * Identifies items within the explorerContainer that are either fully or partially visible. + * Items with thumbnails already retrieved are excluded. + * Populates a list of such visible items and passes them for further processing. + */ +function getVisibleItems() { + const containerRect = fileSystemExplorerContainer.getBoundingClientRect(); + const visibleItems = []; + // go through each .e item which has not had its thumbnail retrieved yet + const fileElements = Array.from(fileSystemExplorer.querySelectorAll('.e:not([data-thumbnail-retrieved])[data-type="file"]')); + // if the option for checking file header bytes is disabled, filter images by extension + const itemsToProcess = inspectFileForThumbnails ? fileElements : fileElements.filter(item => isImageFile(item.getAttribute('data-path'))); + itemsToProcess.forEach(item => { + const itemPath = item.getAttribute('data-path'); + const itemRect = item.getBoundingClientRect(); + // check if the item is fully or partially visible horizontally and vertically + const isFullyVisibleHorizontally = itemRect.left >= containerRect.left && itemRect.right <= containerRect.right; + const isFullyVisibleVertically = itemRect.top >= containerRect.top && itemRect.bottom <= containerRect.bottom; + const isPartiallyVisibleHorizontally = itemRect.left < containerRect.right && itemRect.right > containerRect.left; + const isPartiallyVisibleVertically = itemRect.top < containerRect.bottom && itemRect.bottom > containerRect.top; + // if the item is fully or partially visible in both directions, add it to our list + if ((isFullyVisibleHorizontally || isPartiallyVisibleHorizontally) && + (isFullyVisibleVertically || isPartiallyVisibleVertically)) { + const imgElement = item.querySelector('img'); + visibleItems.push({ + path: itemPath, + img: imgElement + }); + } + }); + // process the list of visible items + processVisibleItems(visibleItems); +} + +/** + * Processes a given item by retrieving its thumbnail from an API and updating the item's thumbnail image. + * If there are more items in the visibleItems list, it continues to process the next item. + * If an error occurs during the retrieval process (including an aborted fetch operation), it is handled gracefully. + * @param {Object} item - The item containing its path and corresponding image element. + * @param {Array} visibleItems - List of remaining visible items to process. + * @throws {AbortError} - Indicates the fetch operation was aborted. + * @throws {Error} - Catches and logs other errors that might occur during the thumbnail retrieval. + */ +async function processItem(item, visibleItems) { + try { + const result = await getThumbnailApiCall(item.path, imagePreviewsQuality); + // update the item's thumbnail using the retrieved data + if (typeof result.base64Data !== "undefined") + item.img.src = `data:${result.mimeType};base64,${result.base64Data}`; + item.img.closest('.e').setAttribute('data-thumbnail-retrieved', 'true'); + // continue with next item if there are more in the queue + if (visibleItems.length > 0) { + const nextItem = visibleItems.shift(); + processItem(nextItem, visibleItems); + } + } catch (error) { + if (error.name === 'AbortError') { + // console.log('Fetch operation was aborted.'); + } else { + // on error, revert the icons to the default ones + let itemType = item.img.closest('.e').getAttribute('data-type'); + if (itemType === 'directory') + item.img.src = "http://localhost:5012/images/icons/Lyra/directory.svg"; + else if (itemType === 'file') + item.img.src = "http://localhost:5012/images/icons/Lyra/file.svg"; + console.error('Error processing item:', error); + } + } +} + +/** + * Makes an API call to retrieve a thumbnail for the given item. + * @param {string} path - The path of the item for which the thumbnail needs to be fetched. + * @returns {Promise} - Returns a Promise resolving to an object containing base64Data and mimeType. + * @throws {Error} - Throws an error if the API call fails. + */ +async function getThumbnailApiCall(path, quality) { + // fetch the thumbnail for the given item from the server + const response = await fetch('http://localhost:5214/api/v1/thumbnails/get-thumbnail?path=' + encodeURIComponent(path) + '&quality=' + quality, { + signal: abortController.signal // use the abort signal + }); + if (!response.ok) + throw new Error('Failed to fetch the thumbnail'); + // convert the response to a JSON object + const blob = await response.blob(); + const base64Data = await blobToBase64(blob); + const mimeType = response.headers.get('Content-Type'); + return { + base64Data: base64Data, + mimeType: mimeType + }; +} + +/** + * Initiates the processing of visible items. Processing is batched based on thumbnailsRetrievalBatchSize. * + * @param {Array} visibleItemsList - List of visible items to be processed. + */ +async function processVisibleItems(visibleItemsList) { + const visibleItems = [...visibleItemsList]; + abortController = new AbortController(); // create a new AbortController + // process items in batches determined by thumbnailsRetrievalBatchSize + for (let i = 0; i < Math.min(thumbnailsRetrievalBatchSize, visibleItems.length); i++) { + const item = visibleItems.shift(); + processItem(item, visibleItems); + } +} + // =================== window functions =================== /** @@ -539,6 +737,7 @@ function windowKeyDownHandler(element, dotnetHelper) { */ window.addEventListener('resize', function () { adjustDropdownHeight(); + handleFileSystemBrowserResizeEvent(); // update all dropdowns' positions on resize const dropdown = document.getElementById('navigatorDropdown'); if (dropdown) { @@ -546,4 +745,4 @@ window.addEventListener('resize', function () { if (pathSegmentId) updateDropdownPosition(pathSegmentId); } -}); \ No newline at end of file +});