diff --git a/src/Lumina.Presentation.Api/Common/Errors/CustomProblemDetailsFactory.cs b/src/Lumina.Presentation.Api/Common/Errors/CustomProblemDetailsFactory.cs index 6831a32d..43274c4e 100644 --- a/src/Lumina.Presentation.Api/Common/Errors/CustomProblemDetailsFactory.cs +++ b/src/Lumina.Presentation.Api/Common/Errors/CustomProblemDetailsFactory.cs @@ -28,12 +28,12 @@ public class CustomProblemDetailsFactory : ProblemDetailsFactory /// /// Initializes a new instance of the class. /// - /// Injected service for retrieving . + /// Injected service for retrieving . /// Injected service for retrieving . /// Thrown when the value of options (if any) is . - public CustomProblemDetailsFactory(IOptions options, IOptions? problemDetailsOptions = null) + public CustomProblemDetailsFactory(IOptions apiBehaviorOptions, IOptions? problemDetailsOptions = null) { - _options = options?.Value ?? throw new ArgumentNullException(nameof(options)); + _options = apiBehaviorOptions?.Value ?? throw new ArgumentNullException(nameof(apiBehaviorOptions)); _configure = problemDetailsOptions?.Value?.CustomizeProblemDetails; } #endregion diff --git a/src/Lumina.Presentation.Api/Common/ModelBinders/UrlStringBinder.cs b/src/Lumina.Presentation.Api/Common/ModelBinders/UrlStringBinder.cs index b3065f1d..93fe483c 100644 --- a/src/Lumina.Presentation.Api/Common/ModelBinders/UrlStringBinder.cs +++ b/src/Lumina.Presentation.Api/Common/ModelBinders/UrlStringBinder.cs @@ -1,4 +1,4 @@ -#region ========================================================================= USING ===================================================================================== +#region ========================================================================= USING ===================================================================================== using Microsoft.AspNetCore.Mvc.ModelBinding; using System; using System.Threading.Tasks; @@ -19,8 +19,7 @@ public class UrlStringBinder : IModelBinder /// A task representing the bind operation. public Task BindModelAsync(ModelBindingContext bindingContext) { - if (bindingContext is null) - throw new ArgumentNullException(nameof(bindingContext)); + ArgumentNullException.ThrowIfNull(bindingContext); string modelName = bindingContext.ModelName; // try to fetch the value of the argument by name ValueProviderResult valueProviderResult = bindingContext.ValueProvider.GetValue(modelName); @@ -38,4 +37,4 @@ public class UrlStringBinder : IModelBinder return Task.CompletedTask; } #endregion -} \ No newline at end of file +} diff --git a/src/Lumina.Presentation.Api/Core/Controllers/FileManagement/DirectoriesController.cs b/src/Lumina.Presentation.Api/Core/Controllers/FileManagement/DirectoriesController.cs index c9cbc22b..284e289d 100644 --- a/src/Lumina.Presentation.Api/Core/Controllers/FileManagement/DirectoriesController.cs +++ b/src/Lumina.Presentation.Api/Core/Controllers/FileManagement/DirectoriesController.cs @@ -51,7 +51,7 @@ public class DirectoriesController : ApiController ErrorOr> result = await _mediator.Send(new GetDirectoryTreeQuery(path, includeFiles, includeHiddenElements), cancellationToken).ConfigureAwait(false); if (!result.IsError && result.Value is not null) { - foreach (FileSystemTreeNodeResponse treeNode in result.Value) + foreach (FileSystemTreeNodeResponse treeNode in result.Value ?? []) { if (cancellationToken.IsCancellationRequested) yield break; @@ -73,7 +73,7 @@ public class DirectoriesController : ApiController ErrorOr> result = await _mediator.Send(new GetTreeDirectoriesQuery(path,includeHiddenElements), cancellationToken).ConfigureAwait(false); if (!result.IsError && result.Value is not null) { - foreach (FileSystemTreeNodeResponse directory in result.Value) + foreach (FileSystemTreeNodeResponse directory in result.Value ?? []) { if (cancellationToken.IsCancellationRequested) yield break; @@ -95,7 +95,7 @@ public class DirectoriesController : ApiController ErrorOr> result = await _mediator.Send(new GetDirectoriesQuery(path, includeHiddenElements), cancellationToken).ConfigureAwait(false); if (!result.IsError && result.Value is not null) { - foreach (DirectoryResponse directory in result.Value) + foreach (DirectoryResponse directory in result.Value ?? []) { if (cancellationToken.IsCancellationRequested) yield break; diff --git a/src/Lumina.Presentation.Api/Core/Controllers/FileManagement/FilesController.cs b/src/Lumina.Presentation.Api/Core/Controllers/FileManagement/FilesController.cs index fbeb2a0b..18d23db4 100644 --- a/src/Lumina.Presentation.Api/Core/Controllers/FileManagement/FilesController.cs +++ b/src/Lumina.Presentation.Api/Core/Controllers/FileManagement/FilesController.cs @@ -5,7 +5,6 @@ using Lumina.Application.Core.FileManagement.Files.Queries.GetTreeFiles; using Lumina.Contracts.Responses.FileManagement; using Lumina.Presentation.Api.Common.ModelBinders; using Lumina.Presentation.Api.Core.Controllers.Common; -using MapsterMapper; using Mediator; using Microsoft.AspNetCore.Mvc; using System.Collections.Generic; @@ -49,7 +48,7 @@ public class FilesController : ApiController [FromQuery] bool includeHiddenElements, [EnumeratorCancellation] CancellationToken cancellationToken) { ErrorOr> result = await _mediator.Send(new GetTreeFilesQuery(path, includeHiddenElements), cancellationToken).ConfigureAwait(false); - foreach (FileSystemTreeNodeResponse file in result.Value) + foreach (FileSystemTreeNodeResponse file in result.Value ?? []) { if (cancellationToken.IsCancellationRequested) yield break; @@ -70,7 +69,7 @@ public class FilesController : ApiController ErrorOr> result = await _mediator.Send(new GetFilesQuery(path, includeHiddenElements), cancellationToken).ConfigureAwait(false); if (!result.IsError) { - foreach (FileResponse file in result.Value) + foreach (FileResponse file in result.Value ?? []) { if (cancellationToken.IsCancellationRequested) yield break; diff --git a/src/Lumina.Presentation.Web/Common/DependencyInjection/PresentationWebLayerServices.cs b/src/Lumina.Presentation.Web/Common/DependencyInjection/PresentationWebLayerServices.cs index be130546..12316dae 100644 --- a/src/Lumina.Presentation.Web/Common/DependencyInjection/PresentationWebLayerServices.cs +++ b/src/Lumina.Presentation.Web/Common/DependencyInjection/PresentationWebLayerServices.cs @@ -1,6 +1,8 @@ #region ========================================================================= USING ===================================================================================== using FluentValidation; using Lumina.Presentation.Web.Common.Api; +using Lumina.Presentation.Web.Common.Exceptions; +using Lumina.Presentation.Web.Common.Filters; using Lumina.Presentation.Web.Common.Services; using Lumina.Presentation.Web.Core.Services.UI; using Microsoft.Extensions.DependencyInjection; @@ -11,6 +13,7 @@ using Polly.Wrap; using System; using System.Net; using System.Net.Http; +using System.Text.Json.Serialization; #endregion namespace Lumina.Presentation.Web.Common.DependencyInjection; @@ -28,25 +31,25 @@ public static class PresentationWebLayerServices /// The updated . public static IServiceCollection AddPresentationWebLayerServices(this IServiceCollection services) { - services.AddControllersWithViews(); + services.AddControllersWithViews(options => options.Filters.Add(typeof(ApiExceptionFilter))) + .AddJsonOptions(options => options.JsonSerializerOptions.Converters.Add(new JsonStringEnumConverter())); // scan the current assembly for validators and register them to the DI container services.AddValidatorsFromAssemblyContaining(ServiceLifetime.Singleton); // handle transient errors like network timeouts or intermittent failures - AsyncRetryPolicy retryPolicy = Policy + AsyncRetryPolicy retryPolicy = Policy .Handle() - .OrResult(r => - !r.IsSuccessStatusCode && - r.StatusCode != HttpStatusCode.Forbidden && - r.StatusCode != HttpStatusCode.BadRequest) + .OrInner(ex => + ex.HttpStatusCode != HttpStatusCode.BadRequest && + ex.HttpStatusCode != HttpStatusCode.Forbidden) .WaitAndRetryAsync(3, retryAttempt => TimeSpan.FromSeconds(Math.Pow(2, retryAttempt))); // use a circuit breaker to prevent repeatedly calling a failing service - AsyncCircuitBreakerPolicy circuitBreakerPolicy = Policy + AsyncCircuitBreakerPolicy circuitBreakerPolicy = Policy .Handle() - .OrResult(r => r.StatusCode == HttpStatusCode.InternalServerError) + .OrInner(ex => ex.HttpStatusCode == HttpStatusCode.InternalServerError) .CircuitBreakerAsync(3, TimeSpan.FromSeconds(30)); AsyncPolicyWrap policy = Policy.WrapAsync(retryPolicy, circuitBreakerPolicy); @@ -58,6 +61,7 @@ public static class PresentationWebLayerServices services.AddSingleton(); services.AddScoped(); + services.AddScoped(); return services; } diff --git a/src/Lumina.Presentation.Web/Common/Filters/ApiExceptionFilter.cs b/src/Lumina.Presentation.Web/Common/Filters/ApiExceptionFilter.cs new file mode 100644 index 00000000..bd4efc97 --- /dev/null +++ b/src/Lumina.Presentation.Web/Common/Filters/ApiExceptionFilter.cs @@ -0,0 +1,107 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Presentation.Web.Common.Exceptions; +using Microsoft.AspNetCore.Authentication; +using Microsoft.AspNetCore.Authentication.Cookies; +using Microsoft.AspNetCore.Http; +using Microsoft.AspNetCore.Http.Extensions; +using Microsoft.AspNetCore.Mvc; +using Microsoft.AspNetCore.Mvc.Filters; +using System; +using System.Collections.Generic; +using System.Net; +using System.Text; +using System.Text.Json; +using System.Threading.Tasks; +#endregion + +namespace Lumina.Presentation.Web.Common.Filters; + +/// +/// Filters API exceptions and provides centralized handling for API-related errors. +/// +public class ApiExceptionFilter : IExceptionFilter +{ + #region ===================================================================== METHODS =================================================================================== + /// + /// Called after an action has thrown an Exception. + /// + /// The . + public void OnException(ExceptionContext context) + { + // check if the exception is an ApiException + if (context.Exception is ApiException apiException) + { + // handle unauthorized errors by prompting the user to re-login + if (apiException.HttpStatusCode == HttpStatusCode.Unauthorized) + { + SignOutSynchronously(context.HttpContext); + string currentUrl = context.HttpContext.Request.GetDisplayUrl(); + context.HttpContext.Response.Redirect(currentUrl); // force an entire refresh of the current location, so that header and footer are re-rendered too + } + else + { + StringBuilder errorMessage = new(); + if (apiException.ProblemDetails is not null) + { + errorMessage.AppendLine($"HTTP {apiException.ProblemDetails.Status} {apiException.HttpStatusCode}
"); + if (!string.IsNullOrEmpty(apiException.ProblemDetails.Detail)) + errorMessage.AppendLine($"{apiException.ProblemDetails.Detail}"); + else if (!string.IsNullOrEmpty(apiException.ProblemDetails.Title)) + errorMessage.AppendLine($"{apiException.ProblemDetails.Title}"); + if (apiException.ProblemDetails.Extensions is not null && apiException.ProblemDetails.Extensions.TryGetValue("errors", out JsonElement errorsObj)) + { + if (errorsObj is JsonElement jsonElement && jsonElement.ValueKind == JsonValueKind.Object) + { + errorMessage.AppendLine("Validation Errors:"); + foreach (JsonProperty error in jsonElement.EnumerateObject()) + { + string fieldName = error.Name; + if (error.Value.ValueKind == JsonValueKind.Array) + foreach (JsonElement errorValue in error.Value.EnumerateArray()) + errorMessage.AppendLine($"- {fieldName}: {errorValue}
"); + } + } + } + if (apiException.ProblemDetails.Extensions is not null) + foreach (KeyValuePair extension in apiException.ProblemDetails.Extensions) + if (extension.Key != "errors") + errorMessage.AppendLine($"{extension.Key}: {extension.Value}
"); + } + else + { + errorMessage.AppendLine($"HTTP {apiException.HttpStatusCode}
"); + errorMessage.AppendLine($"{apiException.Message}
"); + } + // return a JSON result with the error details + context.Result = new JsonResult(new + { + success = false, + errorMessage = errorMessage.ToString() + }); + } + } + else + { + // return a JSON result with the error details + context.Result = new JsonResult(new + { + success = false, + errorMessage = context.Exception.Message.ToString() + }); + } + // mark the exception as handled to prevent propagation + context.ExceptionHandled = true; + } + + /// + /// Signs out the user synchronously by deleting the authentication cookie and token. + /// + /// The HttpContext for the current request. + private static void SignOutSynchronously(HttpContext httpContext) + { + Task task = httpContext.SignOutAsync(CookieAuthenticationDefaults.AuthenticationScheme); + task.Wait(); // run the task synchronously + httpContext.Response.Cookies.Delete("Token"); + } + #endregion +} diff --git a/src/Lumina.Presentation.Web/Common/Models/FileManagement/PathSegmentModel.cs b/src/Lumina.Presentation.Web/Common/Models/FileManagement/PathSegmentModel.cs index 19fb1396..1d790f03 100644 --- a/src/Lumina.Presentation.Web/Common/Models/FileManagement/PathSegmentModel.cs +++ b/src/Lumina.Presentation.Web/Common/Models/FileManagement/PathSegmentModel.cs @@ -1,8 +1,13 @@ -namespace Lumina.Presentation.Web.Common.Models.FileManagement; +#region ========================================================================= USING ===================================================================================== +using System.Diagnostics; +#endregion + +namespace Lumina.Presentation.Web.Common.Models.FileManagement; /// /// Represents a response containing a file system path. /// +[DebuggerDisplay("{Path}")] public class PathSegmentModel { #region ==================================================================== PROPERTIES ================================================================================= @@ -11,4 +16,4 @@ public class PathSegmentModel /// public string Path { get; set; } = null!; #endregion -} \ No newline at end of file +} diff --git a/src/Lumina.Presentation.Web/Components/FileSystemBrowser.razor b/src/Lumina.Presentation.Web/Components/FileSystemBrowser.razor deleted file mode 100644 index 18963f11..00000000 --- a/src/Lumina.Presentation.Web/Components/FileSystemBrowser.razor +++ /dev/null @@ -1,1051 +0,0 @@ -@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/Controllers/FileManagement/DirectoriesController.cs b/src/Lumina.Presentation.Web/Controllers/FileManagement/DirectoriesController.cs new file mode 100644 index 00000000..03e1e9d6 --- /dev/null +++ b/src/Lumina.Presentation.Web/Controllers/FileManagement/DirectoriesController.cs @@ -0,0 +1,87 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Presentation.Web.Common.Api; +using Lumina.Presentation.Web.Common.Models.FileManagement; +using Microsoft.AspNetCore.Mvc; +using System; +using System.Collections.Generic; +using System.Runtime.CompilerServices; +using System.Threading; +using System.Threading.Tasks; +#endregion + +namespace Lumina.Presentation.Web.Controllers.FileManagement; + +/// +/// Controller for managing file system directories. +/// +[Route("[controller]")] +public class DirectoriesController : Controller +{ + #region ================================================================== FIELD MEMBERS ================================================================================ + private readonly IApiHttpClient _apiHttpClient; + #endregion + + #region ====================================================================== CTOR ===================================================================================== + /// + /// Initializes a new instance of the class. + /// + /// Injected service for interactions with the API. + public DirectoriesController(IApiHttpClient apiHttpClient) + { + _apiHttpClient = apiHttpClient; + } + #endregion + + #region ===================================================================== METHODS =================================================================================== + /// + /// Gets the directories of . + /// + /// The path for which to get the directories. + /// Whether to include hidden file system elements or not. + /// Cancellation token that can be used to stop the execution. + [HttpGet("get-directories")] + public async IAsyncEnumerable GetDirectories([FromQuery] string path, [FromQuery] bool includeHiddenElements, [EnumeratorCancellation] CancellationToken cancellationToken) + { + IAsyncEnumerable response = _apiHttpClient.GetAsyncEnumerable( + $"directories/get-directories?path={Uri.EscapeDataString(path)}&includeHiddenElements={includeHiddenElements}", cancellationToken: cancellationToken); + await foreach (DirectoryModel? directory in response) + { + if (cancellationToken.IsCancellationRequested) + yield break; + yield return directory; + } + } + + /// + /// Gets the directories of . + /// + /// The path for which to get the directories. + /// Whether to include hidden file system elements or not. + /// Cancellation token that can be used to stop the execution. + [HttpGet("get-tree-directories")] + public async IAsyncEnumerable GetTreeDirectories([FromQuery] string path, [FromQuery] bool includeHiddenElements, [EnumeratorCancellation] CancellationToken cancellationToken) + { + IAsyncEnumerable response = _apiHttpClient.GetAsyncEnumerable( + $"directories/get-tree-directories?path={Uri.EscapeDataString(path)}&includeHiddenElements={includeHiddenElements}", cancellationToken: cancellationToken); + await foreach (FileSystemTreeNodeModel? directory in response) + { + if (cancellationToken.IsCancellationRequested) + yield break; + yield return directory; + } + } + + /// + /// Gets the tree of expanded directories leading up to , with the additional list of drives, and children of the last child directory. + /// + /// The path for which to get the directory tree. + /// Whether to include hidden file system elements or not. + /// Cancellation token that can be used to stop the execution. + [HttpGet("get-directory-tree")] + public async Task GetDirectoryTree([FromQuery] string path, [FromQuery] bool includeFiles, [FromQuery] bool includeHiddenElements, CancellationToken cancellationToken) + { + FileSystemTreeNodeModel[] response = await _apiHttpClient.GetAsync($"directories/get-directory-tree?path={Uri.EscapeDataString(path)}&includeFiles={includeFiles}&includeHiddenElements={includeHiddenElements}", cancellationToken: cancellationToken); + return Json(new { success = true, data = new { tree = response } }); + } + #endregion +} diff --git a/src/Lumina.Presentation.Web/Controllers/FileManagement/DrivesController.cs b/src/Lumina.Presentation.Web/Controllers/FileManagement/DrivesController.cs new file mode 100644 index 00000000..3dc9fe7e --- /dev/null +++ b/src/Lumina.Presentation.Web/Controllers/FileManagement/DrivesController.cs @@ -0,0 +1,44 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Presentation.Web.Common.Api; +using Lumina.Presentation.Web.Common.Models.FileManagement; +using Microsoft.AspNetCore.Mvc; +using System.Threading; +using System.Threading.Tasks; +#endregion + +namespace Lumina.Presentation.Web.Controllers.FileManagement; + +/// +/// Controller for managing file system drives. +/// +[Route("[controller]")] +public class DrivesController : Controller +{ + #region ================================================================== FIELD MEMBERS ================================================================================ + private readonly IApiHttpClient _apiHttpClient; + #endregion + + #region ====================================================================== CTOR ===================================================================================== + /// + /// Initializes a new instance of the class. + /// + /// Injected service for interactions with the API. + public DrivesController(IApiHttpClient apiHttpClient) + { + _apiHttpClient = apiHttpClient; + } + #endregion + + #region ===================================================================== METHODS =================================================================================== + /// + /// Controller action for getting the list of all file system drives. + /// + /// Cancellation token that can be used to stop the execution. + [HttpGet("get-drives")] + public async Task GetDrives(CancellationToken cancellationToken) + { + FileSystemTreeNodeModel[] response = await _apiHttpClient.GetAsync($"drives/get-drives", cancellationToken: cancellationToken); + return Json(new { success = true, data = new { drives = response } }); + } + #endregion +} diff --git a/src/Lumina.Presentation.Web/Controllers/FileManagement/FileSystemController.cs b/src/Lumina.Presentation.Web/Controllers/FileManagement/FileSystemController.cs new file mode 100644 index 00000000..885e6e1b --- /dev/null +++ b/src/Lumina.Presentation.Web/Controllers/FileManagement/FileSystemController.cs @@ -0,0 +1,44 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Presentation.Web.Common.Api; +using Lumina.Presentation.Web.Common.Models.FileManagement; +using Microsoft.AspNetCore.Mvc; +using System.Threading; +using System.Threading.Tasks; +#endregion + +namespace Lumina.Presentation.Web.Controllers.FileManagement; + +/// +/// Controller for managing file systems. +/// +[Route("/file-system")] +public class FileSystemController : Controller +{ + #region ================================================================== FIELD MEMBERS ================================================================================ + private readonly IApiHttpClient _apiHttpClient; + #endregion + + #region ====================================================================== CTOR ===================================================================================== + /// + /// Initializes a new instance of the class. + /// + /// Injected service for interactions with the API. + public FileSystemController(IApiHttpClient apiHttpClient) + { + _apiHttpClient = apiHttpClient; + } + #endregion + + #region ===================================================================== METHODS =================================================================================== + /// + /// Gets the type of the file system. + /// + /// Cancellation token that can be used to stop the execution. + [HttpGet("get-type")] + public async Task GetType(CancellationToken cancellationToken) + { + FileSystemTypeModel response = await _apiHttpClient.GetAsync($"file-system/get-type", cancellationToken: cancellationToken); + return Json(new { success = true, data = new { platformType = response.PlatformType.ToString() } }); + } + #endregion +} diff --git a/src/Lumina.Presentation.Web/Controllers/FileManagement/FilesController.cs b/src/Lumina.Presentation.Web/Controllers/FileManagement/FilesController.cs new file mode 100644 index 00000000..410c3976 --- /dev/null +++ b/src/Lumina.Presentation.Web/Controllers/FileManagement/FilesController.cs @@ -0,0 +1,73 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Presentation.Web.Common.Api; +using Lumina.Presentation.Web.Common.Models.FileManagement; +using Microsoft.AspNetCore.Mvc; +using System; +using System.Collections.Generic; +using System.Runtime.CompilerServices; +using System.Threading; +#endregion + +namespace Lumina.Presentation.Web.Controllers.FileManagement; + +/// +/// Controller for managing file system files. +/// +[Route("[controller]")] +public class FilesController : Controller +{ + #region ================================================================== FIELD MEMBERS ================================================================================ + private readonly IApiHttpClient _apiHttpClient; + #endregion + + #region ====================================================================== CTOR ===================================================================================== + /// + /// Initializes a new instance of the class. + /// + /// Injected service for interactions with the API. + public FilesController(IApiHttpClient apiHttpClient) + { + _apiHttpClient = apiHttpClient; + } + #endregion + + #region ===================================================================== METHODS =================================================================================== + /// + /// Gets the files of . + /// + /// The path for which to get the files. + /// Whether to include hidden file system elements or not. + /// Cancellation token that can be used to stop the execution. + [HttpGet("get-tree-files")] + public async IAsyncEnumerable GetTreeFiles([FromQuery] string path, [FromQuery] bool includeHiddenElements, [EnumeratorCancellation] CancellationToken cancellationToken) + { + IAsyncEnumerable response = _apiHttpClient.GetAsyncEnumerable( + $"files/get-tree-files?path={Uri.EscapeDataString(path)}&includeHiddenElements={includeHiddenElements}", cancellationToken: cancellationToken); + await foreach (FileSystemTreeNodeModel? file in response) + { + if (cancellationToken.IsCancellationRequested) + yield break; + yield return file; + } + } + + /// + /// Gets the files of . + /// + /// The path for which to get the files. + /// Whether to include hidden file system elements or not. + /// Cancellation token that can be used to stop the execution. + [HttpGet("get-files")] + public async IAsyncEnumerable GetFiles([FromQuery] string path, [FromQuery] bool includeHiddenElements, [EnumeratorCancellation] CancellationToken cancellationToken) + { + IAsyncEnumerable response = _apiHttpClient.GetAsyncEnumerable( + $"files/get-files?path={Uri.EscapeDataString(path)}&includeHiddenElements={includeHiddenElements}", cancellationToken: cancellationToken); + await foreach (FileModel? file in response) + { + if (cancellationToken.IsCancellationRequested) + yield break; + yield return file; + } + } + #endregion +} diff --git a/src/Lumina.Presentation.Web/Controllers/FileManagement/PathController.cs b/src/Lumina.Presentation.Web/Controllers/FileManagement/PathController.cs new file mode 100644 index 00000000..9227db57 --- /dev/null +++ b/src/Lumina.Presentation.Web/Controllers/FileManagement/PathController.cs @@ -0,0 +1,105 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Presentation.Web.Common.Api; +using Lumina.Presentation.Web.Common.Models.FileManagement; +using Microsoft.AspNetCore.Mvc; +using System; +using System.Threading; +using System.Threading.Tasks; +#endregion + +namespace Lumina.Presentation.Web.Controllers.FileManagement; + +/// +/// Controller for managing file system paths. +/// +[Route("[controller]")] +public class PathController : Controller +{ + #region ================================================================== FIELD MEMBERS ================================================================================ + private readonly IApiHttpClient _apiHttpClient; + #endregion + + #region ====================================================================== CTOR ===================================================================================== + /// + /// Initializes a new instance of the class. + /// + /// Injected service for interactions with the API. + public PathController(IApiHttpClient apiHttpClient) + { + _apiHttpClient = apiHttpClient; + } + #endregion + + #region ===================================================================== METHODS =================================================================================== + /// + /// Gets the root of . + /// + /// The path for which to get the root. + /// Cancellation token that can be used to stop the execution. + [HttpGet("get-path-root")] + public async Task GetPathRoot([FromQuery] string path, CancellationToken cancellationToken) + { + PathSegmentModel response = await _apiHttpClient.GetAsync($"path/get-path-root?path={Uri.EscapeDataString(path)}", cancellationToken: cancellationToken); + return Json(new { success = true, data = new { root = response } }); + } + + /// + /// Gets the path separator character of the file system. + /// + /// Cancellation token that can be used to stop the execution. + [HttpGet("get-path-separator")] + public async Task GetPathSeparator(CancellationToken cancellationToken) + { + PathSeparatorModel response = await _apiHttpClient.GetAsync($"path/get-path-separator", cancellationToken: cancellationToken); + return Json(new { success = true, data = new { pathSeparator = response.Separator } }); + } + + /// + /// Gets the path separator character of the file system. + /// + /// The path for which to get the parent path. + /// Cancellation token that can be used to stop the execution. + [HttpGet("get-path-parent")] + public async Task GetPathParent([FromQuery] string path, CancellationToken cancellationToken) + { + PathSegmentModel[] response = await _apiHttpClient.GetAsync($"path/get-path-parent?path={Uri.EscapeDataString(path)}", cancellationToken: cancellationToken); + return Json(new { success = true, data = new { pathSegments = response } }); + } + + /// + /// Gets the path components of . + /// + /// The path for which to get the path segments. + /// Cancellation token that can be used to stop the execution. + [HttpGet("split")] + public async Task SplitPath([FromQuery] string path, CancellationToken cancellationToken) + { + PathSegmentModel[] response = await _apiHttpClient.GetAsync($"path/split?path={Uri.EscapeDataString(path)}", cancellationToken: cancellationToken); + return Json(new { success = true, data = new { pathSegments = response } }); + } + + /// + /// Validates the validity of . + /// + /// The path to be validated. + /// Cancellation token that can be used to stop the execution. + [HttpGet("validate")] + public async Task ValidatePath([FromQuery] string path, CancellationToken cancellationToken) + { + PathValidModel response = await _apiHttpClient.GetAsync($"path/validate?path={Uri.EscapeDataString(path)}", cancellationToken: cancellationToken); + return Json(new { success = true, data = new { isValid = response.IsValid } }); + } + + /// + /// Checks whether exists or not. + /// + /// The path to be checked. + /// Cancellation token that can be used to stop the execution. + [HttpGet("check-path-exists")] + public async Task CheckPathExists([FromQuery] string path, CancellationToken cancellationToken) + { + PathExistsModel response = await _apiHttpClient.GetAsync($"path/check-path-exists?path={Uri.EscapeDataString(path)}", cancellationToken: cancellationToken); + return Json(new { success = true, data = new { exists = response.Exists } }); + } + #endregion +} diff --git a/src/Lumina.Presentation.Web/Pages/Home.razor b/src/Lumina.Presentation.Web/Pages/Home.razor deleted file mode 100644 index 9e41e0a8..00000000 --- a/src/Lumina.Presentation.Web/Pages/Home.razor +++ /dev/null @@ -1,17 +0,0 @@ -<<<<<<< Updated upstream -@page "/" - -@using Lumina.Presentation.Web.Components - -Lumina - Home - - -======= -@page "/" - -@using Lumina.Presentation.Web.Components - -Lumina - Home - - ->>>>>>> Stashed changes diff --git a/src/Lumina.Presentation.Web/Program.cs b/src/Lumina.Presentation.Web/Program.cs index 9e985667..c04dba24 100644 --- a/src/Lumina.Presentation.Web/Program.cs +++ b/src/Lumina.Presentation.Web/Program.cs @@ -35,7 +35,7 @@ public class Program app.UseHsts(); } - app.UseHttpsRedirection(); + //app.UseHttpsRedirection(); app.UseStaticFiles(); app.UseRouting(); diff --git a/src/Lumina.Presentation.Web/Properties/launchSettings.json b/src/Lumina.Presentation.Web/Properties/launchSettings.json index 2419c655..72625312 100644 --- a/src/Lumina.Presentation.Web/Properties/launchSettings.json +++ b/src/Lumina.Presentation.Web/Properties/launchSettings.json @@ -4,7 +4,7 @@ "http": { "commandName": "Project", "dotnetRunMessages": true, - "launchBrowser": true, + //"launchBrowser": true, "applicationUrl": "http://localhost:5012", "environmentVariables": { "ASPNETCORE_ENVIRONMENT": "Development" @@ -13,8 +13,8 @@ "https": { "commandName": "Project", "dotnetRunMessages": true, - "launchBrowser": true, - "applicationUrl": "https://localhost:7112;http://localhost:5012", + //"launchBrowser": true, + "applicationUrl": "http://localhost:5012;https://localhost:7112", "environmentVariables": { "ASPNETCORE_ENVIRONMENT": "Development" } diff --git a/src/Lumina.Presentation.Web/ViewComponents/FileSystemBrowserViewComponent.cs b/src/Lumina.Presentation.Web/ViewComponents/FileSystemBrowserViewComponent.cs new file mode 100644 index 00000000..3279c4f5 --- /dev/null +++ b/src/Lumina.Presentation.Web/ViewComponents/FileSystemBrowserViewComponent.cs @@ -0,0 +1,49 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Presentation.Web.Common.Enums.FileSystem; +using Lumina.Presentation.Web.Common.Models.Configuration; +using Microsoft.AspNetCore.Mvc; +using Microsoft.Extensions.Options; +#endregion + +namespace Lumina.Presentation.Web.ViewComponents; + +/// +/// View component for the file system browser. +/// +public class FileSystemBrowserViewComponent : ViewComponent +{ + #region ================================================================== FIELD MEMBERS ================================================================================ + private readonly ServerConfigurationModel _serverConfigurationModel; + #endregion + + #region ====================================================================== CTOR ===================================================================================== + /// + /// Initializes a new instance of the class. + /// + /// Injected service for retrieving . + public FileSystemBrowserViewComponent(IOptions serverConfigurationModelOptions) + { + _serverConfigurationModel = serverConfigurationModelOptions.Value; + } + #endregion + + #region ===================================================================== METHODS =================================================================================== + /// + /// Invokes the view component. + /// + /// + /// An that renders the view with file system browsing configuration. + /// + public IViewComponentResult Invoke() + { + return View(new + { + Path = @"C:\", + ServerBasePath = $"{_serverConfigurationModel.BaseAddress}:{_serverConfigurationModel.Port}/api/v{_serverConfigurationModel.ApiVersion}/", + ClientBasePath = "http://localhost:5012/", // TODO: take from appsettings or environment + ViewMode = FileSystemViewMode.List, + IconSize = FileSystemIconSize.Large + }); + } + #endregion +} diff --git a/src/Lumina.Presentation.Web/Views/Home/Index.cshtml b/src/Lumina.Presentation.Web/Views/Home/Index.cshtml index bcfd79a5..b6c0cc27 100644 --- a/src/Lumina.Presentation.Web/Views/Home/Index.cshtml +++ b/src/Lumina.Presentation.Web/Views/Home/Index.cshtml @@ -1,8 +1 @@ -@{ - ViewData["Title"] = "Home Page"; -} - -
-

Welcome

-

Learn about building Web apps with ASP.NET Core.

-
+@await Component.InvokeAsync("FileSystemBrowser") diff --git a/src/Lumina.Presentation.Web/Views/Shared/Components/FileSystemBrowser/Default.cshtml b/src/Lumina.Presentation.Web/Views/Shared/Components/FileSystemBrowser/Default.cshtml new file mode 100644 index 00000000..ed22f10b --- /dev/null +++ b/src/Lumina.Presentation.Web/Views/Shared/Components/FileSystemBrowser/Default.cshtml @@ -0,0 +1,537 @@ +@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 + +@inject IApiHttpClient _apiHttpClient +@inject INotificationService _notificationService + +
+
+
+
+
+
+ + + + + + +
+
+
+ +
+
+
+
+
+
+ +
+
+
+
+ Name +
+
+
+
+
+
+
+
+
+ + +
+
+ + +
+
+
+ @*
+ + + Cancel + Confirm *@ +
+
+
+ + diff --git a/src/Lumina.Presentation.Web/Views/Shared/_Layout.cshtml b/src/Lumina.Presentation.Web/Views/Shared/_Layout.cshtml index 1e4f48b4..d954e569 100644 --- a/src/Lumina.Presentation.Web/Views/Shared/_Layout.cshtml +++ b/src/Lumina.Presentation.Web/Views/Shared/_Layout.cshtml @@ -1,49 +1,36 @@ - + - - - - @ViewData["Title"] - Lumina.Presentation.Web - - - - - -
- -
-
-
- @RenderBody() -
-
- -
-
- © 2024 - Lumina.Presentation.Web - Privacy + + + + @ViewData["Title"] - Lumina + + + + + + + + + + + + +
+
+ @await Html.PartialAsync("_NavMenu") +
+
+
+ @RenderBody() +
+
-
- - - - @await RenderSectionAsync("Scripts", required: false) - + + + + + + @await RenderSectionAsync("Scripts", required: false) + diff --git a/src/Lumina.Presentation.Web/Views/Shared/_NavMenu.cshtml b/src/Lumina.Presentation.Web/Views/Shared/_NavMenu.cshtml new file mode 100644 index 00000000..362d39a6 --- /dev/null +++ b/src/Lumina.Presentation.Web/Views/Shared/_NavMenu.cshtml @@ -0,0 +1,118 @@ + + + diff --git a/src/Lumina.Presentation.Web/wwwroot/css/blazor.css b/src/Lumina.Presentation.Web/wwwroot/css/blazor.css deleted file mode 100644 index 4191a6f1..00000000 --- a/src/Lumina.Presentation.Web/wwwroot/css/blazor.css +++ /dev/null @@ -1,61 +0,0 @@ -#blazor-error-ui { - background: lightyellow; - bottom: 0; - box-shadow: 0 -1px 2px rgba(0, 0, 0, 0.2); - display: none; - left: 0; - padding: 0.6rem 1.25rem 0.7rem 1.25rem; - position: fixed; - width: 100%; - z-index: 1000; -} - - #blazor-error-ui .dismiss { - cursor: pointer; - position: absolute; - right: 0.75rem; - top: 0.5rem; - } - -.blazor-error-boundary { - background: url(data:image/svg+xml;base64,PHN2ZyB3aWR0aD0iNTYiIGhlaWdodD0iNDkiIHhtbG5zPSJodHRwOi8vd3d3LnczLm9yZy8yMDAwL3N2ZyIgeG1sbnM6eGxpbms9Imh0dHA6Ly93d3cudzMub3JnLzE5OTkveGxpbmsiIG92ZXJmbG93PSJoaWRkZW4iPjxkZWZzPjxjbGlwUGF0aCBpZD0iY2xpcDAiPjxyZWN0IHg9IjIzNSIgeT0iNTEiIHdpZHRoPSI1NiIgaGVpZ2h0PSI0OSIvPjwvY2xpcFBhdGg+PC9kZWZzPjxnIGNsaXAtcGF0aD0idXJsKCNjbGlwMCkiIHRyYW5zZm9ybT0idHJhbnNsYXRlKC0yMzUgLTUxKSI+PHBhdGggZD0iTTI2My41MDYgNTFDMjY0LjcxNyA1MSAyNjUuODEzIDUxLjQ4MzcgMjY2LjYwNiA1Mi4yNjU4TDI2Ny4wNTIgNTIuNzk4NyAyNjcuNTM5IDUzLjYyODMgMjkwLjE4NSA5Mi4xODMxIDI5MC41NDUgOTIuNzk1IDI5MC42NTYgOTIuOTk2QzI5MC44NzcgOTMuNTEzIDI5MSA5NC4wODE1IDI5MSA5NC42NzgyIDI5MSA5Ny4wNjUxIDI4OS4wMzggOTkgMjg2LjYxNyA5OUwyNDAuMzgzIDk5QzIzNy45NjMgOTkgMjM2IDk3LjA2NTEgMjM2IDk0LjY3ODIgMjM2IDk0LjM3OTkgMjM2LjAzMSA5NC4wODg2IDIzNi4wODkgOTMuODA3MkwyMzYuMzM4IDkzLjAxNjIgMjM2Ljg1OCA5Mi4xMzE0IDI1OS40NzMgNTMuNjI5NCAyNTkuOTYxIDUyLjc5ODUgMjYwLjQwNyA1Mi4yNjU4QzI2MS4yIDUxLjQ4MzcgMjYyLjI5NiA1MSAyNjMuNTA2IDUxWk0yNjMuNTg2IDY2LjAxODNDMjYwLjczNyA2Ni4wMTgzIDI1OS4zMTMgNjcuMTI0NSAyNTkuMzEzIDY5LjMzNyAyNTkuMzEzIDY5LjYxMDIgMjU5LjMzMiA2OS44NjA4IDI1OS4zNzEgNzAuMDg4N0wyNjEuNzk1IDg0LjAxNjEgMjY1LjM4IDg0LjAxNjEgMjY3LjgyMSA2OS43NDc1QzI2Ny44NiA2OS43MzA5IDI2Ny44NzkgNjkuNTg3NyAyNjcuODc5IDY5LjMxNzkgMjY3Ljg3OSA2Ny4xMTgyIDI2Ni40NDggNjYuMDE4MyAyNjMuNTg2IDY2LjAxODNaTTI2My41NzYgODYuMDU0N0MyNjEuMDQ5IDg2LjA1NDcgMjU5Ljc4NiA4Ny4zMDA1IDI1OS43ODYgODkuNzkyMSAyNTkuNzg2IDkyLjI4MzcgMjYxLjA0OSA5My41Mjk1IDI2My41NzYgOTMuNTI5NSAyNjYuMTE2IDkzLjUyOTUgMjY3LjM4NyA5Mi4yODM3IDI2Ny4zODcgODkuNzkyMSAyNjcuMzg3IDg3LjMwMDUgMjY2LjExNiA4Ni4wNTQ3IDI2My41NzYgODYuMDU0N1oiIGZpbGw9IiNGRkU1MDAiIGZpbGwtcnVsZT0iZXZlbm9kZCIvPjwvZz48L3N2Zz4=) no-repeat 1rem/1.8rem, #b32121; - padding: 1rem 1rem 1rem 3.7rem; - color: white; -} - - .blazor-error-boundary::after { - content: "An error has occurred." - } - -.loading-progress { - position: relative; - display: block; - width: 8rem; - height: 8rem; - margin: 20vh auto 1rem auto; -} - - .loading-progress circle { - fill: none; - stroke: #e0e0e0; - stroke-width: 0.6rem; - transform-origin: 50% 50%; - transform: rotate(-90deg); - } - - .loading-progress circle:last-child { - stroke: #1b6ec2; - stroke-dasharray: calc(3.141 * var(--blazor-load-percentage, 0%) * 0.8), 500%; - transition: stroke-dasharray 0.05s ease-in-out; - } - -.loading-progress-text { - position: absolute; - text-align: center; - font-weight: bold; - inset: calc(20vh + 3.25rem) 0 auto 0.2rem; -} - - .loading-progress-text:after { - content: var(--blazor-load-percentage-text, "Loading"); - } \ No newline at end of file diff --git a/src/Lumina.Presentation.Web/wwwroot/css/button.css b/src/Lumina.Presentation.Web/wwwroot/css/button.css new file mode 100644 index 00000000..f74643a3 --- /dev/null +++ b/src/Lumina.Presentation.Web/wwwroot/css/button.css @@ -0,0 +1,161 @@ +.abort-button { + text-decoration: none; + border-radius: 4px; + border: solid 1px; + border-color: #006666 #004030 #003020 #006666; + background: linear-gradient(to bottom, #90AEA6 0%, #336659 50%, #004030 50%, #004030 100%); + color: #999999; + position: relative; + overflow: hidden; + transition: all 0.3s; + cursor: pointer; + outline: none; + box-shadow: 0 4px 4px rgba(0, 0, 0, 0.5); + z-index: 1; +} + + .abort-button:before { + content: ""; + position: absolute; + bottom: 0; + left: 0; + right: 0; + height: 50%; + background: radial-gradient(circle at center, #00FF00, transparent); + background-size: 120% 100%; + transform: translateY(100%); + background-position: center; + transition: transform 0.3s, opacity 0.8s; + pointer-events: none; + opacity: 0; + filter: blur(8px); + } + + .abort-button:hover { + color: #fff; + } + + .abort-button:hover:before { + transform: translateY(50%); + opacity: 1; + } + + .abort-button:active { + background: #CC009F58; + font-style: italic; + } + + .abort-button:disabled { + background: #333333; + border-color: #333333; + color: #777; + cursor: not-allowed; + } + + .abort-button:disabled:hover:before { + transform: translateY(100%); + opacity: 0; + } + + .abort-button:disabled:active { + font-style: normal; + } + + .abort-button[disabled] { + background: #333333; + border-color: #333333; + color: #777; + cursor: not-allowed; + pointer-events: none; + text-decoration: none; + } + + .abort-button[disabled]:hover:before { + transform: translateY(100%); + opacity: 0; + } + + .abort-button[disabled]:active { + font-style: normal; + } + +.confirm-button { + text-decoration: none; + border-radius: 4px; + border: solid 1px; + border-color: #363636 #000 #000 #363636; + background: linear-gradient(to bottom, #AAAAAA 0%, #363636 50%, #000 50%, #000 100%); + color: #AAAAAA; + position: relative; + overflow: hidden; + transition: all 0.3s; + cursor: pointer; + outline: none; + box-shadow: 0 4px 4px rgba(0, 0, 0, 0.5); + z-index: 1; +} + + .confirm-button:before { + content: ""; + position: absolute; + bottom: 0; + left: 0; + right: 0; + height: 50%; + background: radial-gradient(circle at center, #00FF8B, transparent); + background-size: 120% 100%; + transform: translateY(100%); + background-position: center; + transition: transform 0.3s, opacity 0.8s; + pointer-events: none; + opacity: 0; + filter: blur(8px); + } + + .confirm-button:hover { + color: #fff; + } + + .confirm-button:hover:before { + transform: translateY(50%); + opacity: 1; + } + + .confirm-button:active { + background: #CC000000; + font-style: italic; + } + + .confirm-button:disabled { + background: #333333; + border-color: #333333; + color: #777; + cursor: not-allowed; + } + + .confirm-button:disabled:hover:before { + transform: translateY(100%); + opacity: 0; + } + + .confirm-button:disabled:active { + font-style: normal; + } + +confirm-button[disabled] { + background: #333333; + border-color: #333333; + color: #777; + cursor: not-allowed; + pointer-events: none; + text-decoration: none; +} + +.confirm-button[disabled]:hover:before { + transform: translateY(100%); + opacity: 0; +} + +.confirm-button[disabled]:active { + font-style: normal; +} diff --git a/src/Lumina.Presentation.Web/wwwroot/css/checkbox.css b/src/Lumina.Presentation.Web/wwwroot/css/checkbox.css new file mode 100644 index 00000000..f0eb9f70 --- /dev/null +++ b/src/Lumina.Presentation.Web/wwwroot/css/checkbox.css @@ -0,0 +1,6 @@ +namespace Lumina.Presentation.Web.wwwroot.css +{ + public class checkbox + { + } +} diff --git a/src/Lumina.Presentation.Web/wwwroot/css/combobox.css b/src/Lumina.Presentation.Web/wwwroot/css/combobox.css new file mode 100644 index 00000000..a0b534ab --- /dev/null +++ b/src/Lumina.Presentation.Web/wwwroot/css/combobox.css @@ -0,0 +1,154 @@ +.enlightenment-combobox { + position: relative; + font-family: Arial, sans-serif; + padding: 0; + margin: 0; + box-sizing: border-box; +} + +.enlightenment-toggle-checkbox { + display: none; +} + +.enlightenment-toggle { + display: flex; + align-items: center; + justify-content: space-between; + cursor: pointer; + font-family: Arial, sans-serif; + font-size: 14px; + border-radius: 3px; + box-shadow: 0 0 3px rgba(0, 0, 0, 0.5); + color: #6DCBFE; + padding: 3px 24px 3px 18px; + 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: url('data:image/svg+xml;charset=US-ASCII,%3Csvg%20xmlns%3D%22http%3A%2F%2Fwww.w3.org%2F2000%2Fsvg%22%20width%3D%2212%22%20height%3D%225%22%3E%3Cpath%20fill%3D%22none%22%20stroke%3D%22%23fff%22%20stroke-width%3D%222%22%20d%3D%22M2%2C0L6%2C4L10%2C0%22%2F%3E%3C%2Fsvg%3E'), url('../images/ui/scrollbar_dots_v.png'), linear-gradient(180deg, #606060, #555555, #4C4C4C, #414141); + background-repeat: no-repeat, no-repeat, repeat; + background-position: right 10px top 50%, left 7px top 50%, 0 0; + background-size: 12px 6px, 3px auto, 100%; + user-select: none; + box-sizing: border-box; +} + + .enlightenment-toggle:hover { + background-image: url('data:image/svg+xml;charset=US-ASCII,%3Csvg%20xmlns%3D%22http%3A%2F%2Fwww.w3.org%2F2000%2Fsvg%22%20width%3D%2212%22%20height%3D%225%22%3E%3Cpath%20fill%3D%22none%22%20stroke%3D%22%23fff%22%20stroke-width%3D%222%22%20d%3D%22M2%2C0L6%2C4L10%2C0%22%2F%3E%3C%2Fsvg%3E'), url('../images/ui/scrollbar_dots_lit_v.png'), linear-gradient(180deg, #606060, #555555, #4C4C4C, #414141); + background-repeat: no-repeat, no-repeat, repeat; + background-position: right 10px top 50%, left 7px top 50%, 0 0; + background-size: 12px 6px, 3px auto, 100%; + } + +.enlightenment-selected-text { + flex: 1; + text-align: right; +} + +.enlightenment-dropdown { + display: none; + position: absolute; + top: 100%; + left: 0; + width: 100%; + 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: none; + overflow-y: auto; +} + + .enlightenment-dropdown > .shine-effect:first-child { + top: -4px; + } + +.enlightenment-item { + 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; + width: 100%; + box-sizing: border-box; + user-select: none; + cursor: pointer; +} + + .enlightenment-item.first-item { + border-top: 1px solid #232323; + margin-top: -1px; + } + + .enlightenment-item.last-item { + border-bottom: 1px solid #777777; + } + + .enlightenment-item.disabled { + color: #AAAAAA; + } + + .enlightenment-item:hover { + background-image: none; + background: linear-gradient(to bottom, #505050, #464646, #404040, #363636); + color: #1D8AF9; + box-shadow: inset 1px 0 0 0 #777777, inset -1px 0 0 0 #232323, inset 0 1px 0 0 #989898, inset 0 -1px 0 0 #151515; + } + +.enlightenment-combobox.open .enlightenment-dropdown { + display: block; +} + +.enlightenment-combobox > .shine-effect:first-child { + top: 1px; + opacity: 0; + transition: opacity 0.5s; +} + +.enlightenment-combobox:hover > .shine-effect:first-child { + opacity: 1; +} + +.enlightenment-combobox > .shine-effect::before, +.enlightenment-combobox > .shine-effect::after { + content: ""; + position: absolute; + top: -1px; + left: 50%; + transform: translateX(-50%); + opacity: 0; + transition: opacity 0.5s; +} + +.enlightenment-combobox > .shine-effect::before { + width: 3px; + height: 2px; + border-radius: 5px 5px 0 0; + background-color: #FFFFFF; +} + +.enlightenment-combobox > .shine-effect::after { + width: 10px; + height: 3px; + border-radius: 5px 5px 0 0; + background-color: #FFFFFF; + filter: blur(3px); +} + +.enlightenment-combobox:hover > .shine-effect::before, +.enlightenment-combobox:hover > .shine-effect::after { + opacity: 1; +} diff --git a/src/Lumina.Presentation.Web/Components/FileSystemBrowser.razor.css b/src/Lumina.Presentation.Web/wwwroot/css/file-system-browser.css similarity index 95% rename from src/Lumina.Presentation.Web/Components/FileSystemBrowser.razor.css rename to src/Lumina.Presentation.Web/wwwroot/css/file-system-browser.css index e468c38f..11516f9f 100644 --- a/src/Lumina.Presentation.Web/Components/FileSystemBrowser.razor.css +++ b/src/Lumina.Presentation.Web/wwwroot/css/file-system-browser.css @@ -1,9 +1,10 @@ #file-system-browser-dialog { + display: none; position: absolute; top: 12.5%; bottom: 12.5%; - left: 10%; - right: 10%; + left: 8%; + right: 8%; padding: 10px; border: 1px solid var(--border-color-dialog); box-shadow: 30px 30px 25px var(--shadow-color); @@ -65,7 +66,7 @@ min-width: 0; } -::deep .file-system-browser-content-new-directory { +.file-system-browser-content-new-directory { min-width: 35px; flex-basis: 35px; flex-shrink: 0; @@ -137,12 +138,12 @@ 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-container.collapsed { + max-width: 0px; + min-width: 0px; + border: 0px; + padding: 0px; + } #file-system-browser-file-system-treeview { background-color: #131313; @@ -158,7 +159,7 @@ min-height: 0; } -::deep .file-system-browser-file-system-sources { +.file-system-browser-file-system-sources { flex-grow: 0; } @@ -198,6 +199,7 @@ #file-system-browser-file-system-explorer-details-header { color: deepskyblue; + background-color: #232323; } #file-system-browser-file-system-explorer { @@ -247,6 +249,7 @@ div[id^="file-system-browser-file-system-explorer"]:not([id*="container"]) { display: flex; align-items: center; user-select: none; + box-sizing: content-box; } .e.details-icons { @@ -629,6 +632,7 @@ div[id^="file-system-browser-file-system-explorer"]:not([id*="container"]) { /*File System Navigator*/ #navigator-navigation-controls-container { + width: 225px; display: flex; align-items: center; } @@ -639,7 +643,7 @@ div[id^="file-system-browser-file-system-explorer"]:not([id*="container"]) { margin-right: 10px; } -#navigator-history, ::deep .navigator-navigate-button, ::deep .navigator-edit-path-button { +#navigator-history, .navigator-navigate-button, .navigator-edit-path-button { flex-shrink: 0; /* don't let them shrink */ } @@ -674,23 +678,23 @@ div[id^="file-system-browser-file-system-explorer"]:not([id*="container"]) { height: 24px; } -::deep .navigator-navigate-button, ::deep .navigator-edit-path-button { +.navigator-navigate-button, .navigator-edit-path-button { text-align: end !important; flex-shrink: 0; } -::deep .navigator-navigate-button, -::deep .file-system-browser-content-new-directory { +.navigator-navigate-button, +.file-system-browser-content-new-directory { margin: 0px 10px 2px 0px; flex-shrink: 0; } -::deep .file-system-browser-content-favorite-directory { +.file-system-browser-content-favorite-directory { margin: 0px 2px 2px 0px; flex-shrink: 0; } -::deep .navigator-edit-path-button { +.navigator-edit-path-button { margin: 0px 10px 2px 12px; flex-shrink: 0; } @@ -753,7 +757,7 @@ div[id^="file-system-browser-file-system-explorer"]:not([id*="container"]) { display: flex; margin-right: 0px; align-items: center; - width: 125px; + width: 175px; margin-left: 5px; } @@ -765,7 +769,7 @@ div[id^="file-system-browser-file-system-explorer"]:not([id*="container"]) { } -::deep .navigator-address-bar-input { +.navigator-address-bar-input { width: 100%; } @@ -885,7 +889,7 @@ div[id^="file-system-browser-file-system-explorer"]:not([id*="container"]) { 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 */ + max-height: calc(100vh - 12.5vh - 60px); /* subtracting a small value ensures a little space is left on top and bottom; -12.5% because parent has "top: 12.5%;" */ overflow-y: auto; } @@ -1066,7 +1070,7 @@ div[id^="file-system-browser-file-system-explorer"]:not([id*="container"]) { width: 100%; } - ::deep .file-system-browser-content-new-directory { + .file-system-browser-content-new-directory { min-width: 0; flex-basis: auto; margin-right: 10px; @@ -1102,9 +1106,9 @@ div[id^="file-system-browser-file-system-explorer"]:not([id*="container"]) { } -@media screen and (max-width: 399px) { +@media screen and (max-width: 449px) { #file-system-browser-dialog { - min-width: 400px + min-width: 450px } .e.extra-large-icons { @@ -1116,7 +1120,7 @@ div[id^="file-system-browser-file-system-explorer"]:not([id*="container"]) { } .e.extra-large-icons .text span { - max-width: 400px; + max-width: 450px; } .e.large-icons { diff --git a/src/Lumina.Presentation.Web/wwwroot/css/file-system-tree-view-node.css b/src/Lumina.Presentation.Web/wwwroot/css/file-system-tree-view-node.css new file mode 100644 index 00000000..206d88d4 --- /dev/null +++ b/src/Lumina.Presentation.Web/wwwroot/css/file-system-tree-view-node.css @@ -0,0 +1,78 @@ +.tree-node { + padding: 2px 0; +} + +.node-content { + display: flex; + align-items: flex-start; + cursor: pointer; + padding: 0px; + border-radius: 2px; + border: 1px solid transparent; + flex-wrap: wrap; + min-width: 100%; + display: inline-block; + white-space: nowrap; +} + + .node-content:hover { + 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); + background-color: var(--container-background); + } + + .node-content.selected { + background-color: #131313; + border-bottom: 1px solid var(--border-color-light); + border-right: 1px solid var(--border-color-light); + border-left: 1px solid var(--border-color-dark); + background-color: var(--container-background); + } + +.node-icon { + margin-right: 5px; + width: 16px; + text-align: center; + flex-shrink: 0; +} + +.node-icon, .expand-button { + flex-shrink: 0; + align-self: center; +} + +.child-nodes { + padding-left: 20px; + border-left: 1px dotted #ccc; + margin-left: 7px; +} + +.expand-button { + display: inline-flex; + width: 10px; + height: 10px; + margin-right: 5px; + background-image: url("data:image/svg+xml;utf8,"); + background-size: contain; + transition: transform 0.2s ease; +} + + .expand-button.expanded { + background-image: url("data:image/svg+xml;utf8,"); + transform: rotate(90deg); + } + +.spacer { + display: inline-block; + width: 15px; +} + +.node-name { + margin-left: 3px; + overflow-wrap: break-word; + word-break: break-all; + flex: 1; + align-self: end; +} diff --git a/src/Lumina.Presentation.Web/wwwroot/css/navigation-menu.css b/src/Lumina.Presentation.Web/wwwroot/css/navigation-menu.css new file mode 100644 index 00000000..bb66b6d8 --- /dev/null +++ b/src/Lumina.Presentation.Web/wwwroot/css/navigation-menu.css @@ -0,0 +1,344 @@ +.overlay { + position: fixed; + top: 0; + left: 0; + width: 100%; + height: 100%; + opacity: 0; + visibility: hidden; + transition: opacity 0.50s, visibility 0.50s, height 0.50s; + -webkit-transition: opacity 0.50s, visibility 0.50s, height 0.50s; + overflow: hidden; + background: black; + z-index: -1; +} + +#hamburger-input { + display: none; +} + +#hamburger-menu { + cursor: pointer; + position: fixed; + border-radius: 4px; + border: 1px solid #777777; + border-bottom-color: #000000; + border-right-color: #000000; + top: 10px; + left: 10px; + width: 46px; + height: 46px; + display: none; + z-index: 2; + padding: 5px 0; + margin: 0px; + font-family: 'Cabin', Sans-serif; + background: linear-gradient(to top, #424343 0%, #505050 50%, #5E5D5D 100%); +} + + #hamburger-menu > span { + display: block; + width: 30px; + height: 4px; + margin: 6px auto; + background: linear-gradient(to bottom, rgba(0, 0, 0, 0.6), rgba(0, 0, 0, 0.4)); + border-radius: 2px; + box-shadow: inset 0 1px 0 rgba(0, 0, 0, 0.2), 0 1px 0 rgba(255, 255, 255, 0.2); + } + + #hamburger-menu:hover { + background: linear-gradient(to top, #505050 0%, #5E5D5D 50%, #6A6969 100%); + } + + #hamburger-menu:hover > span { + background: linear-gradient(to bottom, rgba(0, 0, 0, 0.7), rgba(0, 0, 0, 0.5)); + box-shadow: inset 0 1px 0 rgba(0, 0, 0, 0.3), 0 1px 0 rgba(255, 255, 255, 0.3); + } + + #hamburger-menu #mobile-menu { + visibility: hidden; + position: fixed; + margin: 0px; + top: 0; + left: -100%; + width: 100%; + border: 1px solid #777777; + border-bottom-color: #000000; + border-right-color: #000000; + overflow: auto; + color: #6DCBFE; + text-align: center; + background: #4F4F4F; + transition: 0.50s; + -webkit-transition: 0.50s; + padding: 0px 10px; + box-sizing: border-box; + } + +#mobile-menu-content { + border: 1px solid #777777; + border-top-color: #000000; + border-left-color: #000000; + margin-top: 4px; + margin-left: -6px; + margin-right: -5px; + margin-bottom: 3px; + color: #6DCBFE; + text-align: center; + font-size: 18px; + font-family: 'Trebuchet MS', 'Lucida Grande', Verdana, Arial, Sans-Serif; + font-weight: bold; + text-shadow: 0px 0px 2px rgba(0,0,0,1); + /*background: #000 url(../images/metal-plate.png);*/ +} + +.mobile-menu-heading { + height: 35px; + font-size: 28px; + background: rgb(10, 11, 11); + border: 1px solid #777777; + border-bottom-color: #000000; + border-right-color: #000000; + width: 100%; + background-image: linear-gradient(180deg, #505050, #464646, #404040, #363636); +} + +#hamburger-menu ul { + margin-left: 0px; + margin-top: 0px; + margin-bottom: 0px; + padding: 0px; + width: 100%; +} + +#hamburger-menu li { + width: 100%; + list-style-type: none; + line-height: 2rem; + display: flex; + font-weight: normal; + font-size: 10px; + text-shadow: none; + text-align: left; + border: 1px solid #333333; + border-bottom-color: #000000; + border-right-color: #000000; +} + + #hamburger-menu li:nth-child(even) { + background-color: #191E21; + } + + #hamburger-menu li:nth-child(odd) { + background-color: #28292B; + } + +#hamburger-menu a { + padding-left: 5px; + width: 100%; + color: #6DCBFE; + font-weight: normal; + font-size: 18px; + font-family: 'Arial'; + text-decoration: none; + display: inline-block; + margin-left: 0.3em; +} + + #hamburger-menu a:focus, + #hamburger-menu a:active { + color: #7CACF8; + } + + #hamburger-menu a:hover { + color: #FFFFFF; + background: rgb(10, 11, 11); + background-image: linear-gradient(180deg, #505050, #464646, #404040, #363636); + } + +#hamburger-input:checked + #hamburger-menu { + background: linear-gradient(to bottom, #424343 0%, #505050 50%, #5E5D5D 100%); + border: 1px solid #777777; + border-top: 1px solid #000000; + border-left: 1px solid #000000; +} + + #hamburger-input:checked + #hamburger-menu #mobile-menu { + visibility: visible; + left: 0; + top: 71px; + } + +#hamburger-input:checked + #hamburger-menu { + z-index: 2; +} + +#hamburger-input:checked ~ .overlay { + visibility: visible; + opacity: 0.5; + z-index: 1; +} + +.menubar { + background: linear-gradient( to bottom, #505050 0%, #464646 35%, #404040 55%, #363636 100% ); + padding: 0; + position: fixed; + top: 0px; + left: 0px; + width: 100%; + z-index: 900; +} + + .menubar ul { + list-style-type: none; + margin: 0; + padding: 0; + } + + .menubar > ul > li { + display: inline-block; + position: relative; + } + + .menubar label, + .menubar a { + display: block; + padding: 2px 10px; + text-decoration: none; + cursor: default; + color: #6DCBFE; + position: relative; + user-select: none; + border: 1px solid transparent; + } + + .menubar > ul > li > label:hover, + .menubar > ul > li > a:hover { + background: linear-gradient( to bottom, #505050 0%, #464646 35%, #404040 55%, #363636 100% ); + border-left: 1px solid #777777; + border-right: 1px solid #000000; + border-top: 1px solid #505050; + border-bottom: 1px solid #222222; + color: #FFFFFF; + } + + .menubar input[type="radio"] { + display: none; + } + + .menubar ul ul { + display: none; + position: absolute; + top: 100%; + left: 0; + min-width: 150px; + background: #4F4F4F; + border: 1px solid #777777; + border-bottom-color: #000000; + border-right-color: #000000; + padding-top: 4px; + padding-left: 4px; + padding-bottom: 4px; + padding-right: 4px; + } + + .menubar ul ul li { + background: #232323; + border-left: 1px solid #000000; + border-right: 1px solid #777777; + position: relative; + } + + .menubar ul ul li:first-child { + border-top: 1px solid #000000; + } + + .menubar ul ul li:last-child { + border-bottom: 1px solid #777777; + } + + .menubar ul ul li > label:hover, + .menubar ul ul li > a:hover { + background: linear-gradient( to bottom, #505050 0%, #464646 35%, #404040 55%, #363636 100% ); + border: 1px solid #777777; + border-right-color: #000000; + border-bottom-color: #000000; + color: #FFFFFF; + } + + .menubar ul ul ul { + left: 100%; + top: 0; + } + + .menubar li:focus-within > ul { + display: block; + outline: none; + } + + .menubar > ul > li:focus-within > label, + .menubar > ul > li:focus-within > a { + background-color: #28292B; + background: radial-gradient( 115% 115% at 68% 70%, #30303088 0%, #20202044 50%, #101010 100% ); + border: 1px solid #777777; + border-top: 1px solid #000000; + border-left: 1px solid #000000; + color: #FFFFFF; + } + + .menubar .has-submenu > label::after, + .menubar .has-submenu > a::after { + content: " ▶"; + font-size: 0.6em; + position: absolute; + right: 5px; + top: 50%; + transform: translateY(-50%); + transition: transform 0.3s ease; + } + + .menubar .has-submenu:focus-within > label, + .menubar .has-submenu:focus-within > a { + background: linear-gradient( to bottom, #505050 0%, #464646 35%, #404040 55%, #363636 100% ); + border: 1px solid #777777; + border-right-color: #000000; + border-bottom-color: #000000; + } + + .menubar .has-submenu:focus-within > label::after, + .menubar .has-submenu:focus-within > a::after { + content: " ▼"; + color: #FF0000; + transform: translateY(-50%) rotate(0deg); + } + + .menubar .has-submenu:focus-within > label, + .menubar .has-submenu:focus-within > a { + color: #7CACF8; + } + +/* For phones */ +@media only screen and (max-width: 768px) { + .menubar { + visibility: hidden; + } + + #hamburger-menu { + display: block; + } + + #mobile-menu { + height: calc(100% - 70px); + } +} + +/* For desktop: */ +@media only screen and (min-width: 768px) { + .menubar { + visibility: visible; + } + + .overlay { + visibility: hidden !important; + } +} diff --git a/src/Lumina.Presentation.Web/wwwroot/css/notification.css b/src/Lumina.Presentation.Web/wwwroot/css/notification.css new file mode 100644 index 00000000..f2095ab6 --- /dev/null +++ b/src/Lumina.Presentation.Web/wwwroot/css/notification.css @@ -0,0 +1,106 @@ +.notification-container { + position: fixed; + bottom: 10px; + left: 20px; + z-index: 1000; + width: 300px; + max-height: calc(100vh - 40px); /* full viewport height minus 40px */ + overflow-y: auto; /* add vertical scrollbar if content exceeds max-height */ +} + +.notification { + border-radius: 4px; + margin-bottom: 10px; + margin-right: 10px; + display: flex; + flex-direction: row; /* stack content horizontally */ + align-items: flex-start; /* align items to the top */ + background: linear-gradient(135deg, #404040, #232323) !important; + border-top: 1px solid #505050 !important; + border-left: 1px solid #505050 !important; + border-right: 1px solid #000 !important; + border-bottom: 1px solid #000 !important; + box-shadow: 5px 5px 5px var(--shadow-color); + animation: fadeIn 0.3s, fadeOut 0.3s 4.7s; + flex-direction: column; + flex-wrap: nowrap; + align-items: stretch; + justify-content: flex-start; + position: relative; +} + +.notification-body { + padding: 15px; + display: flex; + flex-direction: row; /* stack content horizontally */ + align-items: flex-start; /* align items to the top */ + word-wrap: break-word; /* allow long words to break and wrap */ + overflow-wrap: break-word; /* modern browsers */ + word-break: break-word; /* for very long words or URLs */ +} + +.notification-message { + flex-grow: 1; /* allow message to take up available space */ + margin-right: 3px; /* add some space between message and close button */ + overflow-wrap: break-word; /* modern browsers */ + word-break: break-word; /* for very long words or URLs */ + hyphens: auto; /* enable automatic hyphenation */ + white-space: pre-wrap; /* preserve line breaks */ + font-family: monospace; +} + +.close-button { + background: none; + color: var(--text-foreground); + border: none; + font-size: 20px; + cursor: pointer; + padding: 0; + line-height: 1; + flex-shrink: 0; /* prevent button from shrinking */ +} + +.shine-effect { + background: linear-gradient(to right, transparent, #fff, transparent); + width: 100%; + top: -1px; + height: 1px; + flex-shrink: 0; + pointer-events: none; /* ensure it doesn't interfere with interactions */ +} + +.info { + color: #2196F3; +} + +.success { + color: #4CAF50; +} + +.warning { + color: #FFC107; +} + +.error { + color: #F44336; +} + +@keyframes fadeIn { + from { + opacity: 0; + } + + to { + opacity: 1; + } +} + +@keyframes fadeOut { + from { + opacity: 1; + } + + to { + opacity: 0; + } +} diff --git a/src/Lumina.Presentation.Web/wwwroot/css/site.css b/src/Lumina.Presentation.Web/wwwroot/css/site.css index ce0c1791..12899d10 100644 --- a/src/Lumina.Presentation.Web/wwwroot/css/site.css +++ b/src/Lumina.Presentation.Web/wwwroot/css/site.css @@ -52,6 +52,7 @@ main { } #modal-background { + display: none; z-index: 998; position: absolute; top: 0px; @@ -1244,4 +1245,4 @@ main { /* For desktop: */ @media only screen and (min-width: 768px) { -} \ No newline at end of file +} diff --git a/src/Lumina.Presentation.Web/wwwroot/css/textbox.css b/src/Lumina.Presentation.Web/wwwroot/css/textbox.css new file mode 100644 index 00000000..941d7f34 --- /dev/null +++ b/src/Lumina.Presentation.Web/wwwroot/css/textbox.css @@ -0,0 +1,56 @@ +.enlightenment-input { + font-size: 14px; + padding: 5px; + border: 1px solid; + border-color: var(--border-color-dark) var(--border-color-light) var(--border-color-light) var(--border-color-dark); + border-radius: 3px; + background: linear-gradient(0deg, #90c247, #509c00); + transition: background 0.3s, color 0.3s; + color: #000; + outline: none; + position: relative; + box-sizing: border-box; +} + + .enlightenment-input:hover { + background: var(--window-button-over-color); + } + + .enlightenment-input:not(:focus) { + background: linear-gradient(0deg, #6b7579, #576b65); + color: #000; + } + + .enlightenment-input:focus { + font-style: italic; + color: #333; + background: linear-gradient(0deg, #6AAFF8, #82E9F7); + box-shadow: inset 4px 6px 8px rgba(0,0,0,0.6); + border-color: var(--border-color-dark) var(--border-color-light) var(--border-color-light) var(--border-color-dark); + outline: none; + } + + .enlightenment-input::placeholder { + color: #999; + } + + .enlightenment-input:disabled { + color: #999; + background: var(--container-background); + } + + .enlightenment-input[readonly] { + color: #999; + background: var(--container-background); + border-color: var(--border-color-light) var(--border-color-dark) var(--border-color-dark) var(--border-color-light); + } + + .enlightenment-input[data-has-error="true"] { + border-color: #f00; + color: #FFF; + background: #700; + } + +textarea { + resize: none; +} diff --git a/src/Lumina.Presentation.Web/wwwroot/js/file-system-browser-dialog.js b/src/Lumina.Presentation.Web/wwwroot/js/file-system-browser-dialog.js new file mode 100644 index 00000000..29c4120c --- /dev/null +++ b/src/Lumina.Presentation.Web/wwwroot/js/file-system-browser-dialog.js @@ -0,0 +1,1683 @@ +//+======================================================================================+ +//| DOM Elements | +//+======================================================================================+ + +const modalBackground = document.getElementById('modal-background'); +const fileSystemBrowserDialog = document.getElementById('file-system-browser-dialog'); +const fileSystemBrowserTreeview = document.getElementById('file-system-browser-treeview'); +const pathSegmentsContainer = document.getElementById('navigator-path-segments'); + +const fileSystemTreeViewContainer = document.getElementById('file-system-browser-file-system-treeview-container'); +const fileSystemExplorerContainer = document.getElementById('file-system-browser-file-system-explorer-container'); +const fileSystemExplorer = document.getElementById('file-system-browser-file-system-explorer'); +const fileSystemDetailsHeader = document.getElementById('file-system-browser-file-system-explorer-details-header'); + +const addressBarInput = document.getElementById('navigator-address-bar-input'); +const addressBar = document.getElementById('navigator-address-bar'); + +const btnNavigatorNavigateBack = document.getElementById('navigator-navigate-back'); +const btnNavigatorNavigateForward = document.getElementById('navigator-navigate-forward'); +const btnNavigatorNavigateUp = document.getElementById('navigator-navigate-up'); + +const btnNavigatorToggleTreeView = document.getElementById('navigator-toggle-tree-view-button'); +const btnNavigatorToggleSelectionMode = document.getElementById('navigator-toggle-selection-button'); +const btnNavigatorHiddenElements = document.getElementById('navigator-toggle-hidden-button'); +const btnEditPath = document.getElementById('navigator-edit-path-button'); + +const svgTreeView = document.querySelectorAll('.navigator-icon-fill.tree-view'); +const svgSelectionMode = document.querySelectorAll('.navigator-icon-fill.selection-mode'); +const svgHiddenElements = document.querySelectorAll('.navigator-icon-fill.hidden-elements'); +const svgListView = document.querySelectorAll('.navigator-icon-fill.list'); +const svgDetailsView = document.querySelectorAll('.navigator-icon-fill.details'); +const svgSmallIconsView = document.querySelectorAll('.navigator-icon-fill.small-icons'); +const svgMediumIconsView = document.querySelectorAll('.navigator-icon-fill.medium-icons'); +const svgLargeIconsView = document.querySelectorAll('.navigator-icon-fill.large-icons'); +const svgExtraLargeIconsView = document.querySelectorAll('.navigator-icon-fill.extra-large-icons'); + +const btnListView = document.getElementById('navigator-list-view'); +const btnDetailsView = document.getElementById('navigator-details-view'); +const btnSmallIconsView = document.getElementById('navigator-small-icons-view'); +const btnMediumIconsView = document.getElementById('navigator-medium-icons-view'); +const btnLargeIconsView = document.getElementById('navigator-large-icons-view'); +const btnExtraLargeIconsView = document.getElementById('navigator-extra-large-icons-view'); + +const btnFileSystemBrowserEditPath = document.getElementById('navigator-edit-path-button'); +const btnFileSystemBrowserSubmitPath = document.getElementById('navigator-navigate-button'); +const btnFileSystemBrowserConfirm = document.getElementById('file-system-browser-confirm-button'); + +const selectedFileSystemElementsInput = document.getElementById('file-system-browser-selected-element'); + +const selectionRectangle = document.getElementById('selection-rectangle'); +const visibleSelectionRectangle = document.getElementById('visible-selection-rectangle'); + +//+======================================================================================+ +//| Variables | +//+======================================================================================+ + +// current icon pack theme +const CURRENT_ICON_THEME = "Lyra"; +// mapping of file extensions to SVG image paths +const FILE_ICONS = { + "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" +}; + +let serverBasePath; +let clientBasePath; +let _path; +let pathSeparator = '/'; +let platformType = 'Unix'; +let showFileSystemTreeView = true; // TODO: take from config +let showHiddenElements = true; // TODO: take from config +let includeFiles = true; // TODO: take from config +let viewMode = 'list-icons'; // TODO: take from config +let undoStack = []; +let redoStack = []; + +let selectionStartPosition = { x: 0, y: 0 }; +let currentMousePosition = { x: 0, y: 0 }; +let isSelecting = false; +let isSelectionMode = false; + +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 + + +//+======================================================================================+ +//| Initialization | +//+======================================================================================+ + +/** + * Initializes the values needed by the file sytem browser. + * @param {any} serverBasePathValue The base path of the server API. + * @param {any} clientBasePathValue The base path of the client app API. + * @param {any} initialPath The initial path of the file system browser. + * @param {any} viewModeValue The initial view mode of he file system browser. + * @param {any} iconSizeValue The initial icon size of the file system browser. + */ +async function initFileSystemBrowser(serverBasePathValue, clientBasePathValue, initialPath, viewModeValue, iconSizeValue) { + serverBasePath = serverBasePathValue; + clientBasePath = clientBasePathValue; + await getFileSystemPropertiesAsync(); + if (!initialPath.endsWith(pathSeparator)) + initialPath += pathSeparator; + + _path = initialPath; + addressBarInput.value = initialPath; + showFileSystemTreeView = true; // TODO: take from config + + addHorizontalScrolling(addressBar); + //switchViewMode('list', null, true); + switchViewMode(viewModeValue, viewModeValue === 'list' ? null : iconSizeValue, true); + + // TODO: to be removed: + showFileSystemBrowserDialogAsync(initialPath, true); +} + +/** + * Shows the file system browser dialog. + */ +async function showFileSystemBrowserDialogAsync(path, showHiddenElementsValue) { + if (path !== undefined && path !== null) { + showHiddenElements = showHiddenElementsValue; + modalBackground.style.display = 'block'; + fileSystemBrowserDialog.style.display = 'block'; + if (!path.endsWith(pathSeparator)) + path += pathSeparator; + addressBarInput.value = path; + await toggleShowFileSystemHiddenElementsAsync(false); + await toggleFileSystemTreeViewAsync(false); + await navigateToPathAsync(path, false, false); + } else + notificationService.Show("Path cannot be null!", NotificationType.ERROR); // TODO: should ask error message from server when translation is implemented +} + +/** + * Hides the file system browser dialog. + */ +function hideFileSystemBrowserDialog() { + modalBackground.style.display = 'block'; + fileSystemBrowserDialog.style.display = 'block'; +} + +/** + * Retrieves file system properties from the server, asynchronously. + * @returns {Promise} A promise that resolves once the properties have been fetched. + */ +async function getFileSystemPropertiesAsync() { + // call the API to get the file system type (platform type) + const fileSystemTypeResponse = await callApiGetAsync(`${clientBasePath}file-system/get-type`); + if (fileSystemTypeResponse !== undefined) + platformType = fileSystemTypeResponse.platformType; + // call the API to get the path separator for the file system + const pathSeparatorResponse = await callApiGetAsync(`${clientBasePath}path/get-path-separator`); + if (pathSeparatorResponse !== undefined) + pathSeparator = pathSeparatorResponse.pathSeparator; +} + +/** + * Checks if the specified path is a valid file system path, and exists. + * @param {any} path The path to validate and check. + * @returns {Promise} A promise that resolves to whether the path is valid and exists, or not. + */ +async function checkPathAsync(path) { + const pathValidResponse = await callApiGetAsync(`${clientBasePath}path/validate?path=${encodeURIComponent(path)}`); + if (pathValidResponse !== undefined) { + if (!pathValidResponse.isValid) { + notificationService.show("Specified path is not valid!", NotificationType.ERROR); // TODO: should ask error message from server when translation is implemented + addressBarInput.value = _path; + if (addressBarInput.value !== null && !addressBarInput.value.endsWith(pathSeparator)) + addressBarInput.value += pathSeparator; + } else { + const pathExistsResponse = await callApiGetAsync(`${clientBasePath}path/check-path-exists?path=${encodeURIComponent(path)}`); + if (pathExistsResponse !== undefined && !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 pathValidResponse.isValid; + } +} + +/** + * Navigates to the specified path, + * @param {any} path The path o navigate to. + * @param {any} isForwardNavigation Whether the Forward button was clicked, and navigation is done to a history location or not. + * @param {any} isBackwardNavigation Whether the Back button was clicked, and navigation is done to a history location or not. + */ +async function navigateToPathAsync(path, isForwardNavigation, isBackwardNavigation) { + if (await checkPathAsync(path)) { + // if there was a job for thumbnails retrieval, cancel it first + if (abortController) { + abortController.abort(); + abortController = null; + } + // check if backward navigation is possible + if (isBackwardNavigation) { + if (undoStack.length > 0) { + // get the first path in the backward navigation list + const backwardPath = undoStack.pop(); + // put the current path in the forward navigationlist, before navigating to the backward path + if (addressBarInput.value !== null) { + if (!addressBarInput.value.endsWith(pathSeparator)) + addressBarInput.value += pathSeparator; + redoStack.push(addressBarInput.value); + } + path = backwardPath; + } else + return; + } else if (isForwardNavigation) { // check if forward navigation is possible + if (redoStack.length > 0) { + // get the first path in the forward navigation list + const forwardPath = redoStack.pop(); + // put the current path in the backward navigation list, before navigating to the forward path + if (addressBarInput.value !== null) { + if (!addressBarInput.value.endsWith(pathSeparator)) + addressBarInput.value += pathSeparator; + if (undoStack.length === 0 || (undoStack.length > 0 && undoStack[undoStack.length - 1] !== addressBarInput.value)) + undoStack.push(addressBarInput.value); + } + path = forwardPath; + } else + return; + } else { // navigation to a brand new location (up, directory browse, manual path edit, etc) + redoStack = []; + if (addressBarInput.value !== null && addressBarInput.value !== path) { // when navigating up, addressBarInput.value will be set after navigation + if (undoStack.length === 0 || (undoStack.length > 0 && undoStack[undoStack.length - 1] !== addressBarInput.value)) + undoStack.push(addressBarInput.value); + } else if (_path !== null && _path !== path) { // when editing the address, addressBarInput.value already comes set, check against control value + if (undoStack.length === 0 || (undoStack.length > 0 && undoStack[undoStack.length - 1] !== _path)) + undoStack.push(_path); + } + } + _path = path; // we are about to navigate to the new path, store its value in the control variable + addressBarInput.style.display = 'none'; // hide #address-bar-input + addressBar.style.display = 'block'; // show #address-bar + await getNavigatorPathAsync(path); + await getFileSystemItemsAsync(path); + if (showFileSystemTreeView) + await getFileSystemTreeViewAsync(path); + getFileSystemVisibleItems(); + } + addressBarInput.value = _path; + if (addressBarInput.value !== null && !addressBarInput.value.endsWith(pathSeparator)) + addressBarInput.value += pathSeparator; +} + +/** + * Navigates up one level from the current path + */ +async function navigateUpAsync() { + if (addressBarInput.value !== null) { + // ask the API for the parent path + const parentLocationResponse = await callApiGetAsync(`${clientBasePath}path/get-path-parent?path=${encodeURIComponent(addressBarInput.value)}`); + if (parentLocationResponse !== undefined && parentLocationResponse.pathSegments !== null) { + // if the answer was valid, and we can navigate up, reconstruct the provided path from its segments, and navigate to it + platformType = parentLocationResponse.pathSegments; + let parentConcatenatedPath = parentLocationResponse.pathSegments[0].path; + for (var i = 1; i < parentLocationResponse.pathSegments.length; i++) + parentConcatenatedPath = (parentConcatenatedPath !== pathSeparator ? parentConcatenatedPath : '') + pathSeparator + parentLocationResponse.pathSegments[i].path; + if (!parentConcatenatedPath.endsWith(pathSeparator)) + parentConcatenatedPath += pathSeparator; + await navigateToPathAsync(parentConcatenatedPath, false, false); + } + } +} + + +//+======================================================================================+ +//| Navigator | +//+======================================================================================+ + +/** + * Gets the navigator path segments. + * @param {any} path The path for which to get the navigator path segments. + */ +async function getNavigatorPathAsync(path) { + const pathSplitResponse = await callApiGetAsync(`${clientBasePath}path/split?path=${encodeURIComponent(path)}`); + if (pathSplitResponse !== undefined) + renderAddressBar(pathSplitResponse.pathSegments); +} + +/** + * Render the address bar based on the provided path segments. + * @param {Array} pathSegments - An array of path segments. + */ +function renderAddressBar(pathSegments) { + pathSegmentsContainer.removeEventListener('change', handlePathSegmentComboboxChangeAsync); // remove previous listeners + pathSegmentsContainer.addEventListener('change', handlePathSegmentComboboxChangeAsync); // add new listener + pathSegmentsContainer.innerHTML = ""; // clear existing segments + if (pathSegments !== null) { + pathSegments.forEach((segment, index) => { + const li = document.createElement("li"); + li.id = `path-segment-${index}`; + // create the combobox + const combobox = document.createElement("div"); + combobox.className = "navigator-combobox inline-block"; + // the shine effect + const shineEffect = document.createElement("div"); + shineEffect.className = "shine-effect"; + shineEffect.style.top = "1px"; + combobox.appendChild(shineEffect); + const toggleCheckbox = document.createElement("input"); + toggleCheckbox.type = "checkbox"; + toggleCheckbox.className = "navigator-toggle-checkbox"; + toggleCheckbox.id = `segment-toggle-${index}`; + combobox.appendChild(toggleCheckbox); + const toggleLabel = document.createElement("label"); + toggleLabel.className = "navigator-toggle"; + toggleLabel.htmlFor = `segment-toggle-${index}`; + const span = document.createElement("span"); + span.className = "navigator-selected-text"; + span.innerText = segment.path; + toggleLabel.appendChild(span); + // add the arrow element + const arrowSpan = document.createElement("span"); + arrowSpan.className = "navigator-arrow"; + toggleLabel.appendChild(arrowSpan); + combobox.appendChild(toggleLabel); + const dropdown = document.createElement("div"); + dropdown.className = "navigator-dropdown"; + dropdown.id = `navigator-dropdown-${index}`; + dropdown.setAttribute('data-path-segment-id', `path-segment-${index}`); + // get the segments from start to the current one (on UNIX, start with path separator char!) + const concatenatedPath = (platformType === "Unix" ? '/' : '') + pathSegments.slice(0, index + 1).map(seg => seg.path).join(pathSeparator); + combobox.setAttribute('data-path', concatenatedPath + (!concatenatedPath.endsWith(pathSeparator) ? pathSeparator : '')); + combobox.appendChild(dropdown); + li.appendChild(combobox); + pathSegmentsContainer.appendChild(li); + }); + } else + pathSegmentsContainer.querySelectorAll('li').forEach(li => li.remove()); // no address, clear path segments +} + +/** + * Handle the change event for the comboboxes inside the path-segments. + * This function is triggered when any of the comboboxes (checkboxes) in the navigation bar is toggled. + * @param {Event} event - The change event object. + */ +async function handlePathSegmentComboboxChangeAsync(e) { + // ensure the event was triggered by an element with the 'navigator-toggle-checkbox' class + if (e.target.classList.contains('navigator-toggle-checkbox')) { + const comboboxId = e.target.id; + const dropdownId = comboboxId.replace('segment-toggle-', 'navigator-dropdown-'); + const dropdown = document.getElementById(dropdownId); + reattachDropdown(); + if (!e.target.checked) + return; + const comboboxElement = e.target.closest('.navigator-combobox'); // get the closest parent (or self) with the specified class + const pathValue = comboboxElement.getAttribute('data-path'); // retrieve the data-path attribute value + // clear any existing dropdown elements + dropdown.innerHTML = ""; + showBusyIndicator(); + setupDropdown(dropdown, e.target); + + // add combobox entry for current directory + addDirectoryOption(dropdown, pathValue, ".", async () => { + addressBarInput.value = pathValue; + await navigateToPathAsync(pathValue, false, false); + }); + + // add combobox entry for parent directory + addDirectoryOption(dropdown, pathValue, "..", async () => { + addressBarInput.value = pathValue; + await navigateUpAsync(); + }); + + // fetch directory data for the path + try { + await streamFileSystemDirectoriesAsync(pathValue, (parsedItem) => { + addDirectoryOption(dropdown, pathValue, parsedItem.name, async () => { + const newPath = pathValue + (!pathValue.endsWith(pathSeparator) ? pathSeparator : '') + parsedItem.name + pathSeparator; + addressBarInput.value = newPath; + await navigateToPathAsync(newPath, false, false); + }); + }); + } catch (error) { + console.error('Error:', error); + notificationService.show(error, NotificationType.ERROR); + } finally { + hideBusyIndicator(); + } + } +} + +/** + * Configures and positions the dropdown for directory navigation. + * @param {HTMLElement} dropdown - The dropdown element to set up. + * @param {HTMLElement} toggleElement - The element that triggered the dropdown. + */ +function setupDropdown(dropdown, toggleElement) { + // when drop down opens, need to show address bar overflow, otherwise clipping of drop down occurs + // store the id of the parent combobox of the dropdown - the dropdown will be reparented + // because of manadatory "overflow hidden" of scrollable area and clipping isues + dropdown.setAttribute('data-parent', toggleElement.id); + dropdown.setAttribute('data-detached', true); + const position = toggleElement.closest('.navigator-combobox').getBoundingClientRect(); + // detach dropdown and reposition + document.body.appendChild(dropdown); + dropdown.style.position = 'absolute'; + dropdown.style.top = `${position.bottom}px`; + dropdown.style.left = `${position.left}px`; + dropdown.style.display = 'block'; + // handle addressBar scroll to adjust dropdown position + addressBar.addEventListener('scroll', adjustDropdownPosition); +} + +/** + * Adds a directory option to the dropdown. + * @param {HTMLElement} dropdown - The dropdown to add the option to. + * @param {string} pathValue - The current path. + * @param {string} name - The name of the directory option. + * @param {Function} clickHandler - Function to call when the option is clicked. + */ +function addDirectoryOption(dropdown, pathValue, name, clickHandler) { + const directoryDiv = document.createElement('div'); + directoryDiv.className = "navigator-option"; + directoryDiv.dataset.value = pathValue + (name !== "." && name !== ".." ? name : ""); + directoryDiv.textContent = name; + directoryDiv.addEventListener('click', clickHandler); + dropdown.appendChild(directoryDiv); +} + +/** + * Re-attaches the detached visible drop down to the path segment or platform combobox it originally belonged to + */ +function reattachDropdown() { + // when the combobox closes, re-attach the detached dropdown + const dropdown = document.querySelector('.navigator-dropdown[data-detached="true"], .enlightenment-dropdown[data-detached="true"]'); + if (dropdown) { + // reset its absolute positioning and stuff + dropdown.style.position = ''; + dropdown.style.top = ''; + dropdown.style.left = ''; + dropdown.style.display = ''; + // re-attach it to original parent + const dataParent = dropdown.getAttribute('data-parent'); + dropdown.removeAttribute('data-detached'); + const originalParent = document.getElementById(dataParent).parentNode; + if (originalParent) + originalParent.appendChild(dropdown); + // remove scroll event listener from the addressBar + addressBar.removeEventListener('scroll', adjustDropdownPosition); + } +} + +/** + * Adjusts the position of a detached drop down, such that it is always just under its original + * path segment combobox, even when this parent is moved through scrolling + */ +function adjustDropdownPosition() { + const dropdown = document.querySelector('.navigator-dropdown[data-detached="true"]'); + if (dropdown) { + const comboboxElement = document.getElementById(dropdown.getAttribute('data-parent')); // get the related combobox + const position = comboboxElement.parentNode.getBoundingClientRect(); + dropdown.style.top = position.bottom + 'px'; + dropdown.style.left = position.left + 'px'; + } +} + +/** + * Updates the position and height of the dropdown relative to the specified path segment. + * @param {string} pathSegmentId - The ID of the path segment element to position the dropdown relative to. + */ +function updateDropdownPosition(pathSegmentId, dropdown) { + const element = document.getElementById(pathSegmentId); + if (element && dropdown) { + const rect = getElementOffset(pathSegmentId); + dropdown.style.top = `${rect.top + rect.height}px`; + dropdown.style.left = `${rect.left}px`; + } +} + +//+======================================================================================+ +//| Tree View | +//+======================================================================================+ + +/** + * Gets the file system tree view + * @param {string} initialPath - The initial path to expand in the tree view (optional). + * @returns {Promise} + */ +async function getFileSystemTreeViewAsync(initialPath) { + // clear the existing tree view + fileSystemBrowserTreeview.innerHTML = ''; + // fetch available drives asynchronously + const drives = await getFileSystemDrivesAsync(); + // iterate through each drive and add it to the tree view as root node + for (const drive of drives) { + // create a tree node for the drive + const driveNode = createFileSystemTreeViewTreeNode(drive); + // append the drive node to the tree view + fileSystemBrowserTreeview.appendChild(driveNode); + // if the initial path starts with this drive's path, expand the tree view to show the initial path + if (initialPath.toLowerCase().startsWith(drive.path.toLowerCase())) + await expandInitialTreeViewPathAsync(driveNode, initialPath); + } +} + +/** + * Asynchronously fetches the list of available drives from the server. + * @returns {Promise|undefined>} A promise that resolves to an array of drive objects, or undefined if the API call fails. + */ +async function getFileSystemDrivesAsync() { + const getDrivesResponse = await callApiGetAsync(`${clientBasePath}drives/get-drives`); + if (getDrivesResponse !== undefined) + return getDrivesResponse.drives; +} + +/** + * Creates a tree node element for the file system tree view. + * @param {Object} nodeData - Data for the node (path, itemType, name). + * @returns {HTMLElement} The created tree node element. + */ +function createFileSystemTreeViewTreeNode(nodeData) { + const treeNodeDiv = document.createElement("div"); + treeNodeDiv.className = "tree-node"; + treeNodeDiv.setAttribute('data-path', nodeData.path); + + const nodeContent = document.createElement("span"); + nodeContent.className = "node-content"; + nodeContent.addEventListener('click', handleNodeClickAsync); + + const expandButton = document.createElement("span"); + expandButton.className = nodeData.itemType !== 'File' ? "expand-button" : "spacer"; + expandButton.addEventListener('click', toggleFileSysemTreeViewNodeExpandAsync); + + const nodeIcon = document.createElement("span"); + nodeIcon.className = "node-icon"; + nodeIcon.textContent = getNodeIcon(nodeData); + + const nodeName = document.createElement("span"); + nodeName.className = "node-name"; + nodeName.textContent = nodeData.name; + + // assemble the node structure + nodeContent.appendChild(expandButton); + nodeContent.appendChild(nodeIcon); + nodeContent.appendChild(nodeName); + treeNodeDiv.appendChild(nodeContent); + + const childNodes = document.createElement("div"); + childNodes.className = "child-nodes"; + treeNodeDiv.appendChild(childNodes); + + return treeNodeDiv; +} + +/** + * Handles click events on tree nodes. + * @param {Event} e - The click event object. + */ +async function handleNodeClickAsync(e) { + // get the node that was clicked + const treeNode = e.target.closest('.tree-node'); + // retrieve the path stored on the clicked node + selectedPath = treeNode.getAttribute('data-path'); + if (selectedPath !== null) { + // ensure path ends with separator + if (!selectedPath.endsWith(pathSeparator)) + selectedPath += pathSeparator; + // set the retrieved path as the navigator path, and navigate to it + addressBarInput.value = selectedPath; + await navigateToPathAsync(selectedPath, false, false); + } +} + +/** + * Toggles the expansion of a file system tree view node. + * @param {Event} e - The click event on the expand button. + */ +async function toggleFileSysemTreeViewNodeExpandAsync(e) { + e.stopPropagation(); + // get the node that was clicked + const treeNode = e.target.closest('.tree-node'); + const treeNodeIcon = treeNode.querySelector('.node-icon'); + const nodeData = { itemType: 'Directory' }; + + const expandButton = e.target; + // get the div that hosts child nodes in tthe clicked node + const childNodes = treeNode.querySelector('.child-nodes'); + const path = treeNode.getAttribute('data-path'); + // get the current expanded state of the clicked node, and toggle it + const isExpanded = expandButton.classList.contains('expanded'); + nodeData.isExpanded = !isExpanded; + treeNodeIcon.textContent = getNodeIcon(nodeData); + // expand or collapse the node + if (isExpanded) { + expandButton.classList.remove('expanded'); + childNodes.style.display = 'none'; + } else { + expandButton.classList.add('expanded'); + childNodes.style.display = 'block'; + // if node is expanded and child nodes are not yet loaded, load them + if (childNodes.children.length === 0) + await loadFileSystemTreeViewChildNodesAsync(treeNode, path); + } +} + +/** + * Loads child nodes for a given parent node in the file system tree view. + * @param {HTMLElement} parentNode - The parent node element in the tree view. + * @param {string} path - The file system path to load children from. + */ +async function loadFileSystemTreeViewChildNodesAsync(parentNode, path) { + // get the div that hosts child nodes + const childNodes = parentNode.querySelector('.child-nodes'); + // clear existing child nodes + childNodes.innerHTML = ''; + try { + showBusyIndicator(); + // stream directory information and create nodes for each + await streamFileSystemDirectoriesAsync(path, (dir) => { + dir.itemType = 'Directory'; + const dirNode = createFileSystemTreeViewTreeNode(dir); + childNodes.appendChild(dirNode); + }); + } catch (error) { + console.error('Error:', error); + notificationService.show(error, NotificationType.ERROR); + } finally { + hideBusyIndicator(); + } +} + +/** + * Streams directory information from the server for a given path. + * @param {string} path - The path to get directories from. + * @param {Function} callback - Function to call for each directory received. + */ +async function streamFileSystemDirectoriesAsync(path, callback) { + await streamJsonDataAsync(`${clientBasePath}directories/get-directories?path=${encodeURIComponent(path)}&includeHiddenElements=${showHiddenElements}`, callback, 'Directory'); +} + +/** + * Streams file information from the server for a given path. + * @param {string} path - The path to get files from. + * @param {Function} callback - Function to call for each file received. + */ +async function streamFileSystemFilesAsync(path, callback) { + await streamJsonDataAsync(`${clientBasePath}files/get-tree-files?path=${encodeURIComponent(path)}&includeHiddenElements=${showHiddenElements}`, callback, 'File'); +} + +/** + * Streams JSON data from a given URL and processes it item by item. + * This function handles potentially large datasets by processing the data as it arrives, + * rather than waiting for the entire response to load. + * + * @param {string} url - The URL to fetch JSON data from. + * @param {Function} callback - Function to call for each processed item. + * @param {string} itemType - Type of item being processed ('File' or 'Directory'). + */ +async function streamJsonDataAsync(url, callback, itemType) { + // initiate the fetch request from the API + const response = await fetch(url); + // get a reader for the response body stream + const reader = response.body.getReader(); + // create a decoder to convert the incoming byte stream to text + const decoder = new TextDecoder(); + let buffer = ''; // buffer to hold incoming data that hasn't been fully processed yet + // function to process the buffer and extract complete JSON objects + function processBuffer() { + let startIndex = 0; + let endIndex; + // look for complete JSON objects (ending with '},') + while ((endIndex = buffer.indexOf('},', startIndex)) !== -1) { + // extract a single JSON object + let itemJson = buffer.substring(startIndex, endIndex + 1); + // remove leading comma if present (from array structure) + if (itemJson.startsWith(',')) itemJson = itemJson.substring(1); + // remove surrounding square brackets (array indicators) + itemJson = itemJson.replace(/^\[|\]$/g, ''); + // parse the JSON string into an object + var item = JSON.parse(itemJson); + // manually specify he type of to the parsed object + item.itemType = itemType; + // call the provided callback function with the processed item + callback(item); + // move the start index to the beginning of the next item + startIndex = endIndex + 2; + } + // keep any incomplete JSON data in the buffer for the next processing cycle + buffer = buffer.slice(startIndex); + } + // main loop to read the stream + while (true) { + // read a chunk from the stream + const { done, value } = await reader.read(); + // if the stream is finished, break the loop + if (done) + break; + // decode the chunk and add it to the buffer + buffer += decoder.decode(value, { stream: true }); + // process the updated buffer + processBuffer(); + } + // process any remaining data in the buffer after the stream is complete + if (buffer.trim()) { + let finalJson = buffer.trim(); + if (finalJson.startsWith(',')) finalJson = finalJson.substring(1); + finalJson = finalJson.replace(/^\[|\]$/g, ''); + if (finalJson !== '') { + var item = JSON.parse(finalJson); + item.itemType = itemType; + callback(item); + } + } +} + +/** + * Expands the tree view to a specific target path. + * @param {HTMLElement} node - The starting node in the tree view. + * @param {string} targetPath - The full path to expand to. + */ +async function expandInitialTreeViewPathAsync(node, targetPath) { + const nodePath = node.getAttribute('data-path'); + // exit if the target path doesn't start with the node path + if (!targetPath.toLowerCase().startsWith(nodePath.toLowerCase())) + return; + // expand the current node if it's not already expanded + const expandButton = node.querySelector('.expand-button'); + if (expandButton && !expandButton.classList.contains('expanded')) + await toggleFileSysemTreeViewNodeExpandAsync({ target: expandButton, stopPropagation: () => { } }); + // split the remaining path into segments + const pathSegments = targetPath.slice(nodePath.length).split('\\').filter(Boolean); + let currentNode = node; + // iterate through each path segment + for (let i = 0; i < pathSegments.length; i++) { + const segment = pathSegments[i]; + const childNodes = currentNode.querySelector('.child-nodes'); + let found = false; + // search for the child node matching the current path segment + for (const childNode of childNodes.children) { + if (childNode.querySelector('.node-name').textContent.toLowerCase() === segment.toLowerCase()) { + currentNode = childNode; + found = true; + if (i === pathSegments.length - 1) { + // if this is the last segment (target node) + childNode.scrollIntoView(); // bring it into view, if its not already + // mark it as selected + childNode.querySelector('.node-content').classList.add('selected'); + // toggle this last node, because all its children will be loaded + const expandChildButton = childNode.querySelector('.expand-button'); + if (expandChildButton) + await toggleFileSysemTreeViewNodeExpandAsync({ target: expandChildButton, stopPropagation: () => { } }); + // load the node's children + await loadFileSystemTreeViewChildNodesAsync(childNode, childNode.getAttribute('data-path')); + } + else { + // if this is an intermediate node, expand it if necessary + const childExpandButton = childNode.querySelector('.expand-button'); + if (childExpandButton && !childExpandButton.classList.contains('expanded')) + await toggleFileSysemTreeViewNodeExpandAsync({ target: childExpandButton, stopPropagation: () => { } }); + } + break; + } + } + // if the current segment wasn't found, stop expanding + if (!found) + break; + } +} + +//+======================================================================================+ +//| File System | +//+======================================================================================+ + +/** + * Fetches and displays file system items for a given path. + * @param {string} path - The path to fetch items from. + */ +async function getFileSystemItemsAsync(path) { + // clear the current contents of the file system explorer + fileSystemExplorer.innerHTML = ''; + + try { + showBusyIndicator(); + // stream file system items and create explorer items for each + await streamFileSystemItemsAsync(path, (item) => { + const newItem = createFileSystemExplorerItem(item); + fileSystemExplorer.appendChild(newItem); + }); + } catch (error) { + console.error('Error:', error); + notificationService.show(error, NotificationType.ERROR); + } finally { + hideBusyIndicator(); + } +} + +/** + * Streams both directories and files from a specified path. + * @param {string} path - The file system path to stream items from. + * @param {Function} callback - Function to call for each item (directory or file) received. + */ +async function streamFileSystemItemsAsync(path, callback) { + await streamFileSystemDirectoriesAsync(path, callback); + await streamFileSystemFilesAsync(path, callback); +} + +/** + * Creates a DOM element representing a file system item (file or directory). + * @param {Object} item - The file system item data. + * @returns {HTMLElement} The created DOM element for the file system item. + */ +function createFileSystemExplorerItem(item) { + const itemDiv = document.createElement('div'); + const itemType = item.itemType; + // set up the main item div with appropriate classes and data attributes + itemDiv.className = `e ${viewMode}`; + itemDiv.setAttribute('data-path', item.path); + itemDiv.setAttribute('data-type', itemType); + // create and set up the icon div + const iconDiv = document.createElement('div'); + iconDiv.className = 'icon'; + iconDiv.innerHTML = ``; + // create and set up the text div + const textDiv = document.createElement('div'); + textDiv.className = 'text'; + // use different class for directory ('d') and file ('f') + textDiv.innerHTML = `${item.name}`; + // assemble the item structure + itemDiv.appendChild(iconDiv); + itemDiv.appendChild(textDiv); + // add event listeners for mouse interactions + itemDiv.onmouseup = handleFileSystemEntityMouseUpAsync; + itemDiv.onmousedown = handleFileSystemEntityMouseDown; + return itemDiv; +} + +/** + * Handles mouse up events on file system entities in the explorer view. + * Manages selection, double-click actions, and navigation. + * @param {MouseEvent} e - The mouse event. + */ +async function handleFileSystemEntityMouseUpAsync(e) { + e.preventDefault(); + if (!isSelecting) + e.stopPropagation(); + const allEClassElements = Array.from(fileSystemExplorer.querySelectorAll('.e')); + const currentIndex = allEClassElements.indexOf(e.currentTarget); + + // if a previous click timestamp exists, check the time difference + const previousTime = parseInt(e.currentTarget.dataset.selectionStartTime || 0); + const currentTime = new Date().getTime(); + const timeDifference = currentTime - previousTime; + + // TODO: needs to account for when the element is already selected, and a double click occurs - on first click it would check the difference and go to rename - + // maybe just wait half second before performing action + + // if time difference is less than 300ms, treat it as a double-click + if (timeDifference < 300) { + if (e.currentTarget.dataset.type === 'Directory') { // directories + addressBarInput.value = e.currentTarget.dataset.path; + await navigateToPathAsync(addressBarInput.value, false, false); // TODO: add to undo + return; + } else { // files + + } + // reset the timestamp used to track double clicks + e.currentTarget.dataset.selectionStartTime = 0; + return; + } + else + e.currentTarget.dataset.selectionStartTime = currentTime; // element was single clicked, update the selection start time to now + if (e.ctrlKey || isSelectionMode) { // when CTRL key is pressed + // toggle selection for the current clicked item + e.currentTarget.classList.toggle('selected'); + // set the selection start if it's not already set + if (fileSystemExplorer.dataset.selectionStart === undefined) + fileSystemExplorer.dataset.selectionStart = currentIndex; + } + else if ((e.shiftKey && fileSystemExplorer.dataset.selectionStart !== undefined) || isSelectionMode) { // when SHIFT key is pressed + const start = parseInt(fileSystemExplorer.dataset.selectionStart); + // remove all selections + allEClassElements.forEach(elem => { + elem.classList.remove('selected'); + }); + // define the range to select items from and to + const [from, to] = start < currentIndex ? [start, currentIndex] : [currentIndex, start]; + // add the 'selected' class to items in the range + for (let i = from; i <= to; i++) + allEClassElements[i].classList.add('selected'); + } + 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')); + // add 'selected' class to the current clicked item + e.currentTarget.classList.add('selected'); + // if there are no selected elements, or if there are more than one, deselect all of them, and select just the clicked one + if ((selectedElements.length === 1 && e.currentTarget !== selectedElements[0]) || selectedElements.length !== 1) { + // deselect all items + selectedElements.forEach(elem => { + if (elem !== e.currentTarget) { + elem.classList.remove('selected'); + // remove selectionStartTime from all items + delete elem.dataset.selectionStartTime; + } + }); + // set the current item as the selection start + fileSystemExplorer.dataset.selectionStart = currentIndex; + // store the current timestamp for future double-click checks + e.currentTarget.dataset.selectionStartTime = currentTime; + } + } + else // if its selection mode, just toggle selection of item, when clicked + e.currentTarget.classList.toggle('selected'); + } + const selectedElements = document.querySelectorAll('.e.selected'); + btnFileSystemBrowserConfirm.disabled = selectedElements.length === 0; // disable Confirm button if no item is selected + if (selectedElements.length > 0) { + var selectedPaths = '"'; + selectedElements.forEach((element) => { + selectedPaths += element.dataset.path + '","'; + }); + selectedFileSystemElementsInput.value = selectedPaths.substring(0, selectedPaths.length - 2); + } + else + selectedFileSystemElementsInput.value = ''; +} + +/** + * Handler for the mouse down event of file system browser dialog files and directories elements. + * @param {any} event + */ +function handleFileSystemEntityMouseDown(e) { + // stop the event from bubbling up to the explorer - we dont want to start selection rectangles when clicking files or directories + e.stopPropagation(); +} + +//+======================================================================================+ +//| View Mode | +//+======================================================================================+ + +/** + * Switches to a different view mode. + * @param {string} mode - The view mode to switch to ('list', 'details', or 'icons'). + * @param {string|null} iconSize - The icon size for 'icons' mode ('small', 'medium', 'large', 'extra-large'). Use null for non-icon modes. + * @param {boolean} isManualSet - Indicates whether the mode change is triggered manually (by clicking a mode change icon) or automatically. + */ +function switchViewMode(mode, iconSize, isManualSet) { + hasScrolledAfterModeChange = false; // reset the flag indicating a mode change + setViewMode(mode, iconSize); + // 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 && isManualSet) getFileSystemVisibleItems(); + }, 50); // wait 50ms to ensure all other events have processed +} + +/** + * Sets the explorer view mode. + * @param {string} mode - View mode ('list', 'details', or 'icons'). + * @param {string} [iconSize] - Icon size for 'icons' mode ('small', 'medium', 'large', 'extra-large'). + */ +function setViewMode(mode, iconSize) { + if (!fileSystemExplorer) + return; + const isIconMode = mode === 'icons'; + const viewClass = isIconMode ? 'details' : mode; + const iconClass = isIconMode ? `${iconSize}-icons` : `${mode}-icons`; + viewMode = iconClass; + fileSystemExplorer.className = `${viewClass}`; + fileSystemExplorer.style.flexDirection = mode === 'list' ? 'column' : isIconMode ? 'row' : 'column'; + + fileSystemExplorerContainer.classList.toggle('scroll-horizontal', mode === 'list'); + fileSystemExplorerContainer.classList.toggle('scroll-vertical', mode !== 'list'); + + fileSystemDetailsHeader.style.height = mode === 'details' ? '20px' : '0px'; + fileSystemDetailsHeader.style.position = mode === 'details' ? 'sticky' : 'static'; + fileSystemDetailsHeader.style.top = mode === 'details' ? '-1px' : ''; + + setEnabledViewModeIcon(isIconMode ? `${iconSize}-icons` : mode); + mode === 'list' ? addHorizontalScrolling(fileSystemExplorer) : removeHorizontalScrolling(fileSystemExplorer); + + fileSystemExplorer.querySelectorAll('.e').forEach(el => { + el.className = `e ${iconClass}`; + }); + mode === 'details' ? showExtraDetails() : hideExtraDetails(); +} + +/** + * Hides additional item details such as date modified, type, and size. + */ +function hideExtraDetails() { + fileSystemExplorer.querySelectorAll('.date-modified, .type, .size').forEach(el => { + el.style.display = 'none'; + }); +} + +/** + * Shows additional item details such as date modified, type, and size. + */ +function showExtraDetails() { + fileSystemExplorer.querySelectorAll('.date-modified, .type, .size').forEach(el => { + el.style.display = 'flex'; + }); +} + +/** + * Sets the enabled view mode icon. + * @param {string} viewType - The type of view to enable ('list', 'details', 'small-icons', 'medium-icons', 'large-icons', 'extra-large-icons'). + */ +function setEnabledViewModeIcon(viewType) { + const allViews = [ + svgListView, + svgDetailsView, + svgSmallIconsView, + svgMediumIconsView, + svgLargeIconsView, + svgExtraLargeIconsView + ]; + + allViews.forEach((view, index) => { + view.forEach(element => { + if (index === ['list', 'details', 'small-icons', 'medium-icons', 'large-icons', 'extra-large-icons'].indexOf(viewType)) + element.classList.add('enabled'); + else + element.classList.remove('enabled'); + }); + }); +} + +//+======================================================================================+ +//| Selection | +//+======================================================================================+ + +/** + * Handler for the file system browser dialog selection start. + * @param {MouseEvent} e - The mousedown event object. + */ +function startSelection(e) { + const explorerScrollbars = hasScrollbars(fileSystemExplorer); + const containerExplorerScrollbars = hasScrollbars(fileSystemExplorerContainer); + // check if clicked on the horizontal or vertical scrollbar + if (explorerScrollbars.horizontal && e.clientY > fileSystemExplorer.getBoundingClientRect().top + fileSystemExplorer.offsetHeight - scrollbarHeight) + return; + if (containerExplorerScrollbars.vertical && e.clientX > fileSystemExplorerContainer.getBoundingClientRect().left + fileSystemExplorerContainer.offsetWidth - scrollbarWidth) + return; + // store information about selection start + isSelecting = true; + document.body.style.overflowY = 'hidden'; // needed in order to not put a vertical scrollbar on the document, while in vertical layout selection + document.documentElement.style.overflowY = 'hidden'; + selectionStartPosition.x = e.pageX + fileSystemExplorer.scrollLeft; + selectionStartPosition.y = e.pageY + fileSystemExplorerContainer.scrollTop; // not a mistake - in vertical mode, this is the overflow container! + // place the selection rectangle at the clicked location (relative to the whole page, and taking into account scroll offset), with 0 size + visibleSelectionRectangle.style.left = e.pageX + 'px'; + visibleSelectionRectangle.style.top = e.pageY + 'px'; + visibleSelectionRectangle.style.width = '0px'; + visibleSelectionRectangle.style.height = '0px'; + visibleSelectionRectangle.style.visibility = 'visible'; + + selectionRectangle.style.left = e.pageX + 'px'; + selectionRectangle.style.top = e.pageY + 'px'; + selectionRectangle.style.width = '0px'; + selectionRectangle.style.height = '0px'; +} + +/** + * Handler for the file system browser dialog selection update. + * @param {MouseEvent} e - The mousemove event object. + */ +function updateSelection(e) { + if (!isSelecting) + return; + currentMousePosition.x = e.pageX; + currentMousePosition.y = e.pageY; + handleSelection(); +} + +/** + * Handler for the file system browser dialog selection end. + */ +function endSelection() { + // selection ended, hide the selection rectangle + isSelecting = false; + document.body.style.removeProperty('overflow-y'); + document.documentElement.style.removeProperty('overflow-y'); + + visibleSelectionRectangle.style.visibility = 'hidden'; + selectionRectangle.style.visibility = 'hidden'; + + selectionRectangle.style.left = '0px'; + selectionRectangle.style.top = '0px'; + selectionRectangle.style.width = '0px'; + selectionRectangle.style.height = '0px'; + visibleSelectionRectangle.style.left = '0px'; + visibleSelectionRectangle.style.top = '0px'; + visibleSelectionRectangle.style.width = '0px'; + visibleSelectionRectangle.style.height = '0px'; + // go through each .e item that was inside the selection rectangle, and mark it as selected + fileSystemExplorer.querySelectorAll('.e.selection-hover').forEach(item => { + item.classList.add('selected'); + item.classList.remove('selection-hover'); + }); + const selectedElements = document.querySelectorAll('.e.selected'); + btnFileSystemBrowserConfirm.disabled = selectedElements.length === 0; // disable Confirm button if no item is selected + if (selectedElements.length > 0) { + var selectedPaths = '"'; + selectedElements.forEach((element) => { + selectedPaths += element.dataset.path + '","'; + }); + selectedFileSystemElementsInput.value = selectedPaths.substring(0, selectedPaths.length - 2); + } + else + selectedFileSystemElementsInput.value = ''; +} + +/** + * Function for handling the file system browser dialog selection. + */ +function handleSelection() { + if (!isSelecting) // only relevant when we have a selection initialized + return; + // calculate dimensions of the selection rectangle + const currentX = currentMousePosition.x; + const currentY = currentMousePosition.y; + const width = currentX - (selectionStartPosition.x - fileSystemExplorer.scrollLeft); + const height = currentY - (selectionStartPosition.y - fileSystemExplorerContainer.scrollTop); + + // update selection rectangle dimensions + visibleSelectionRectangle.style.width = Math.abs(width) + 'px'; + visibleSelectionRectangle.style.height = Math.abs(height) + 'px'; + selectionRectangle.style.width = Math.abs(width) + 'px'; + selectionRectangle.style.height = Math.abs(height) + 'px'; + + // adjust position based on selection direction + if (width < 0) { + selectionRectangle.style.left = currentX + 'px'; + visibleSelectionRectangle.style.left = currentX + 'px'; + } else { + selectionRectangle.style.left = (selectionStartPosition.x - fileSystemExplorer.scrollLeft) + 'px'; + visibleSelectionRectangle.style.left = (selectionStartPosition.x - fileSystemExplorer.scrollLeft) + 'px'; + } + if (height < 0) { + selectionRectangle.style.top = currentY + 'px'; + visibleSelectionRectangle.style.top = currentY + 'px'; + } else { + selectionRectangle.style.top = (selectionStartPosition.y - fileSystemExplorerContainer.scrollTop) + 'px'; + visibleSelectionRectangle.style.top = (selectionStartPosition.y - fileSystemExplorerContainer.scrollTop) + 'px'; + } + + // do not let the selection rectangle go outside of explorer container, clip it if needed + const containerRect = fileSystemExplorerContainer.getBoundingClientRect(); + const left = parseFloat(visibleSelectionRectangle.style.left); + const top = parseFloat(visibleSelectionRectangle.style.top) + 1; + const right = left + parseFloat(visibleSelectionRectangle.style.width); + const bottom = top + parseFloat(visibleSelectionRectangle.style.height); + + if (left < containerRect.left) { + const difference = containerRect.left - left; + visibleSelectionRectangle.style.width = (parseFloat(visibleSelectionRectangle.style.width) - difference) + 'px'; + visibleSelectionRectangle.style.left = containerRect.left + 'px'; + } + if (right > containerRect.right) + visibleSelectionRectangle.style.width = (containerRect.right - left) + 'px'; + + if (top < containerRect.top) { + const difference = containerRect.top - top; + visibleSelectionRectangle.style.height = (parseFloat(visibleSelectionRectangle.style.height) - difference) + 'px'; + visibleSelectionRectangle.style.top = containerRect.top + 'px'; + } + if (bottom > containerRect.bottom) + visibleSelectionRectangle.style.height = (containerRect.bottom - top) + 'px'; + + // change color of items that fall within selection rectangle + const selectionRect = selectionRectangle.getBoundingClientRect(); + // go through each .e item which has not had its thumbnail retrieved yet + fileSystemExplorer.querySelectorAll('.e').forEach(item => { + const itemRect = item.getBoundingClientRect(); + // check if the item is fully or partially visible horizontally and vertically + const isFullyVisibleHorizontally = itemRect.left >= selectionRect.left && itemRect.right <= selectionRect.right; + const isFullyVisibleVertically = itemRect.top >= selectionRect.top && itemRect.bottom <= selectionRect.bottom; + const isPartiallyVisibleHorizontally = itemRect.left < selectionRect.right && itemRect.right > selectionRect.left; + const isPartiallyVisibleVertically = itemRect.top < selectionRect.bottom && itemRect.bottom > selectionRect.top; + // if the item is fully or partially visible in both directions, add it to our list + if ((isFullyVisibleHorizontally || isPartiallyVisibleHorizontally) && (isFullyVisibleVertically || isPartiallyVisibleVertically)) + item.classList.add('selection-hover'); + else + item.classList.remove('selection-hover'); + }); +} + +/** + * Enables or disables the display of the file system tree view. + * @param {MouseEvent} e - The mouseup event object. + */ +function toggleFileSystemSelectionMode(e) { + isSelectionMode = !isSelectionMode; + e.preventDefault(); + e.stopPropagation(); + + svgSelectionMode.forEach(element => { + isSelectionMode ? element.classList.add('enabled') : element.classList.remove('enabled'); + }); +} + +/** + * Handler for the mouse up event of the file system browser dialog explorer + * @param {MouseEvent} e - The mouseup event object. + */ +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) + return; + if (!e.ctrlKey && !e.shiftKey && !isSelectionMode) { + // deselect all file system elements when their explorer is clicked + fileSystemExplorer.querySelectorAll('.e.selected').forEach(item => { + item.classList.remove('selected'); + }); + // do not store information about what item was clicked first, in context of Shift-selection + fileSystemExplorer.removeAttribute('data-selection-start'); + btnFileSystemBrowserConfirm.disabled = document.querySelectorAll('.e.selected').length === 0; // disable Confirm button if no item is selected + } +} + +/** + * 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 getFileSystemVisibleItems call + if (scrollTimeout) clearTimeout(scrollTimeout); + // if there's an ongoing operation, abort it + if (abortController) { + abortController.abort(); + abortController = null; + } + // set a timeout to call getFileSystemVisibleItems once the user stops scrolling + scrollTimeout = setTimeout(() => { + if (showThumbnails) + getFileSystemVisibleItems(); + }, 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 getFileSystemVisibleItems 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 getFileSystemVisibleItems once the user stops resizing + resizeTimeout = setTimeout(() => { + if (showThumbnails) + getFileSystemVisibleItems(); + }, scrollThumbnailRetrievalTimeout); +} + +//+======================================================================================+ +//| Thumbnails | +//+======================================================================================+ + +/** + * 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 getFileSystemVisibleItems() { + 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 = clientBasePath + "images/icons/" + CURRENT_ICON_THEME + "/directory.svg"; + else if (itemType === 'file') + item.img.src = clientBasePath + "images/icons/" + CURRENT_ICON_THEME + "/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(`${serverBasePath}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); + } +} + + +/** + * Returns the path to an SVG icon based on the file extension. + * @param {string} filename - The full name of the file including its extension. + * @returns {string} - The path to the appropriate SVG icon or a default one if not found. + */ +function getIconPathForFile(filename, type) { + // extract file extension from filename + const fileExtension = filename.split('.').pop().toLowerCase(); + // return the appropriate SVG image path or a default one if not found + return FILE_ICONS[fileExtension] || (type === "File" ? "file.svg" : "directory.svg"); +} + +//+======================================================================================+ +//| Miscellaneous | +//+======================================================================================+ + +/** + * Enables or disables the display of the file system tree view. + * @param {boolean} isManualSet - Indicates whether the toggle is triggered manually (by clicking on the icon) or automatically. + */ +async function toggleFileSystemTreeViewAsync(isManualSet) { + if (isManualSet) + showFileSystemTreeView = !showFileSystemTreeView; + + showFileSystemTreeView ? fileSystemTreeViewContainer.classList.remove('collapsed') : fileSystemTreeViewContainer.classList.add('collapsed'); + svgTreeView.forEach(element => { + showFileSystemTreeView ? element.classList.add('enabled') : element.classList.remove('enabled'); + }); + showFileSystemTreeView ? fileSystemTreeViewContainer.classList.remove('collapsed') : fileSystemTreeViewContainer.classList.add('collapsed'); + // if file system treeview needs to be displayed, get its file system tree structure from the API + if (showFileSystemTreeView && isManualSet && addressBarInput.value !== null) { + if (!addressBarInput.value.endsWith(pathSeparator)) + addressBarInput.value += pathSeparator; + await navigateToPathAsync(addressBarInput.value, false, false); + } +} + +/** + * Enables or disables the display of hidden file system elements. + * @param {boolean} isManualSet - Indicates whether the toggle is triggered manually (by clicking on the icon) or automatically. + */ +async function toggleShowFileSystemHiddenElementsAsync(isManualSet) { + if (isManualSet) + showHiddenElements = !showHiddenElements; + + svgHiddenElements.forEach(element => { + showHiddenElements ? element.classList.add('enabled') : element.classList.remove('enabled'); + }); + if (isManualSet && addressBarInput.value !== null) { + if (!addressBarInput.value.endsWith(pathSeparator)) + addressBarInput.value += pathSeparator; + await navigateToPathAsync(addressBarInput.value, false, false); + } +} + +/** + * Closes all comboboxes except for the one passed as an argument. + * @param {HTMLElement} exceptionCheckbox - The checkbox of the combobox that should remain open. + */ +function closeAllComboboxesExcept(exceptionCheckbox) { + const checkedCheckboxes = document.querySelectorAll('.enlightenment-toggle-checkbox:checked, .navigator-toggle-checkbox:checked'); + checkedCheckboxes.forEach(function (checkbox) { + if (!exceptionCheckbox || checkbox.id !== exceptionCheckbox.id) + checkbox.checked = false; + }); +} + +/** + * Gets the icon of the node, based on it type. + * @param {any} node The node for which to get the icon. + * @returns The icon on the node. + */ +function getNodeIcon(node) { + switch (node.itemType) { + case "Root": + return "💿"; + case "Directory": + return node.isExpanded ? "📂" : "📁"; + case "File": + return "📄"; + default: + return "❓"; + } +} + +//+======================================================================================+ +//| Event Handlers | +//+======================================================================================+ + +// event handlers for changing file system view modes +btnListView.addEventListener('click', () => switchViewMode('list', null, true)); +btnDetailsView.addEventListener('click', () => switchViewMode('details', null, true)); +btnSmallIconsView.addEventListener('click', () => switchViewMode('icons', 'small', true)); +btnMediumIconsView.addEventListener('click', () => switchViewMode('icons', 'medium', true)); +btnLargeIconsView.addEventListener('click', () => switchViewMode('icons', 'large', true)); +btnExtraLargeIconsView.addEventListener('click', () => switchViewMode('icons', 'extra-large', true)); + +btnNavigatorToggleTreeView.addEventListener('click', async () => await toggleFileSystemTreeViewAsync(true)); +btnNavigatorToggleSelectionMode.addEventListener('click', toggleFileSystemSelectionMode); +btnNavigatorHiddenElements.addEventListener('click', async () => await toggleShowFileSystemHiddenElementsAsync(true)); +btnNavigatorNavigateUp.addEventListener('click', navigateUpAsync); + +fileSystemExplorer.addEventListener('mouseup', handleFileSystemExplorerMouseUp); +fileSystemExplorer.addEventListener('scroll', handleFileSystemBrowserScrollEvent); + +fileSystemExplorerContainer.addEventListener('mousedown', startSelection); +fileSystemExplorerContainer.addEventListener('mousemove', updateSelection); +fileSystemExplorerContainer.addEventListener('mouseup', endSelection); +fileSystemExplorerContainer.addEventListener('wheel', handleSelection, { passive: true }); +fileSystemExplorerContainer.addEventListener('scroll', handleSelection); + +fileSystemExplorerContainer.addEventListener('scroll', handleSelection); + +/** + * Event handler for the address bar input navigate button Click event. + */ +btnFileSystemBrowserSubmitPath.addEventListener('click', async function () { + await navigateToPathAsync(addressBarInput.value, false, false); + addressBarInput.style.display = 'none'; + addressBar.style.display = 'block'; +}); + +/** + * Event handler for the address bar input edit button Click event. + */ +btnFileSystemBrowserEditPath.addEventListener('click', function () { + addressBarInput.style.display = 'block'; + addressBarInput.focus(); + addressBar.style.display = 'none'; +}); + +/** + * Event handler for the navigator back button Click event. + */ +btnNavigatorNavigateBack.addEventListener('click', async function () { + if (addressBarInput.value !== null) + await navigateToPathAsync(addressBarInput.value, false, true); +}); + +/** + * Event handler for the navigator address bar input KeyDown event. + */ +addressBarInput.addEventListener('keydown', async function (e) { + if (e.key === 'Escape') { + e.preventDefault(); + addressBarInput.style.display = 'none'; + addressBar.style.display = 'block'; + } else if (e.key === 'Enter') + await navigateToPathAsync(addressBarInput.value, false, false); +}); + +/** + * Event handler for the addressbar Click event. + */ +addressBar.addEventListener('click', function (e) { + // if the clicked element is the ul itself or one of its direct children (but not deeper nested children) + if (e.target === e.currentTarget || e.target.parentElement === e.currentTarget) { + this.style.display = 'none'; // hide #addressBar + addressBarInput.style.display = 'block'; // show #addressBarInput + addressBarInput.focus(); // focus on the input + } +}); + +/** + * Detects changes on any combobox checkbox. If a combobox is opened, this will ensure all other comboboxes are closed. + */ +document.addEventListener('change', function (e) { + if (e.target.matches('.enlightenment-toggle-checkbox, .navigator-toggle-checkbox')) + if (e.target.checked) + closeAllComboboxesExcept(e.target); +}); + +/** + * Event handler for when an option in the combobox is clicked. + * This updates the displayed value of the combobox to the clicked option and closes the dropdown. + */ +document.addEventListener('click', function (e) { + if (e.target.matches('.enlightenment-option')) { + var text = e.target.textContent; + var combobox = e.target.closest('.enlightenment-combobox'); + + var selectedText = combobox.querySelector('.enlightenment-selected-text'); + if (selectedText) + selectedText.textContent = text; + + var toggleCheckbox = combobox.querySelector('.enlightenment-toggle-checkbox'); + if (toggleCheckbox) + toggleCheckbox.checked = false; + } +}); + +/** + * Global click event for the entire document. Closes all combobox dropdowns if the clicked target is outside any combobox. + */ +document.addEventListener('click', function (e) { + // enlightenment combobox logic + if (!e.target.closest('.enlightenment-combobox')) { + const checkbox = document.querySelector('.enlightenment-toggle-checkbox:checked'); + if (checkbox) + checkbox.checked = false; + } + // navigator combobox logic + if (!e.target.closest('.navigator-combobox') && addressBar) { + const checkbox = document.querySelector('.navigator-toggle-checkbox:checked'); + if (checkbox) + checkbox.checked = false; + // when drop down closes, hide address bar overflow + addressBar.style.overflowX = 'auto'; + addressBar.style.overflowY = 'hidden'; + reattachDropdown(); + } +}); + +/** + * Event handler for navigation combobox drop down item clicks. + */ +document.addEventListener("click", function (e) { + if (e.target.matches('.navigator-option')) { + // the address bar drop downs may be destroyed when an option is clicked - they are regenerated each time anyway + addressBar.removeEventListener('scroll', adjustDropdownPosition); + + var parentElement = e.target.parentElement; + if (parentElement) + parentElement.remove(); + } +}); + +/** + * Prevents the global document click event from propagating when clicking on a combobox. + * This ensures the dropdown doesn't close unintentionally. + */ +document.addEventListener('click', function (e) { + if (e.target.closest('.enlightenment-combobox, .navigator-combobox')) + e.stopPropagation(); +}); + +/** + * Handles the window resize event. + */ +window.addEventListener('resize', function () { + handleFileSystemBrowserResizeEvent(); + // update all dropdowns' positions on resize + const dropdown = document.querySelector('.navigator-dropdown[data-detached="true"]'); + if (dropdown) { + const pathSegmentId = dropdown.getAttribute('data-path-segment-id'); + if (pathSegmentId) + updateDropdownPosition(pathSegmentId, dropdown); + } +}); diff --git a/src/Lumina.Presentation.Web/wwwroot/js/notifications.js b/src/Lumina.Presentation.Web/wwwroot/js/notifications.js new file mode 100644 index 00000000..656ea76b --- /dev/null +++ b/src/Lumina.Presentation.Web/wwwroot/js/notifications.js @@ -0,0 +1,107 @@ +/** + * Enum-like object for notification types. + * @readonly + * @enum {string} + */ +const NotificationType = { + INFO: 'info', + SUCCESS: 'success', + WARNING: 'warning', + ERROR: 'error' +}; + +/** + * Manages the creation, display, and removal of notifications. + */ +class NotificationService { + /** + * Creates an instance of NotificationService. + * Initializes the notification container and appends it to the document body. + */ + constructor() { + this.notifications = []; + this.container = document.createElement('div'); + this.container.className = 'notification-container'; + document.body.appendChild(this.container); + } + + /** + * Displays a new notification. + * @param {string} message - The message to display in the notification. + * @param {NotificationType} type - The type of notification. + */ + show(message, type) { + const notification = { + id: Date.now().toString(), + message, + type + }; + + this.addNotification(notification); + } + + /** + * Adds a notification to the list and displays it. + * @param {Object} notification - The notification object to add. + * @param {string} notification.id - Unique identifier for the notification. + * @param {string} notification.message - The notification message. + * @param {NotificationType} notification.type - The type of notification. + */ + addNotification(notification) { + this.notifications.push(notification); + this.displayNotification(notification); + + // log the notification to the console + const message = `${notification.type.charAt(0).toUpperCase() + notification.type.slice(1)}: ${notification.message}`; + if (notification.type === 'info') + console.info(message); + else if (notification.type === 'warning') + console.warn(message); + else if (notification.type === 'error') + console.error(message); + else + console.log(message); + + // set a timeout to remove the notification after 5 seconds + setTimeout(() => this.removeNotification(notification.id), 5000); + } + + /** + * Removes a notification from the list and the DOM. + * @param {string} id - The ID of the notification to remove. + */ + removeNotification(id) { + const index = this.notifications.findIndex(n => n.id === id); + if (index !== -1) { + this.notifications.splice(index, 1); + const element = document.getElementById(`notification-${id}`); + if (element) { + element.remove(); + } + } + } + + /** + * Creates and displays a notification element in the DOM. + * @param {Object} notification - The notification object to display. + * @param {string} notification.id - Unique identifier for the notification. + * @param {string} notification.message - The notification message. + * @param {NotificationType} notification.type - The type of notification. + */ + displayNotification(notification) { + const notificationElement = document.createElement('div'); + notificationElement.id = `notification-${notification.id}`; + notificationElement.className = `notification ${notification.type}`; + notificationElement.innerHTML = ` +
+
+ ${notification.message} + +
+ `; + this.container.appendChild(notificationElement); + } +} + +// create a global instance of the NotificationService +const notificationService = new NotificationService(); diff --git a/src/Lumina.Presentation.Web/wwwroot/js/site.js b/src/Lumina.Presentation.Web/wwwroot/js/site.js index 4689be0f..7ff86336 100644 --- a/src/Lumina.Presentation.Web/wwwroot/js/site.js +++ b/src/Lumina.Presentation.Web/wwwroot/js/site.js @@ -1,28 +1,89 @@ const scrollbarHeight = getScrollbarHeight(); const scrollbarWidth = getScrollbarWidth(); +const progressIndicator = document.getElementById('progress-indicator'); +const progressIndicatorValue = document.getElementById('progress-indicator-value'); +const progressIndicatorValueShadow = document.getElementById('progress-indicator-value-shadow'); +const progressIndicatorValueText = document.getElementById('progress-indicator-value-text'); -let selectionStartPosition = { x: 0, y: 0 }; -let currentMousePosition = { x: 0, y: 0 }; -let isSelecting = false; -let isSelectionMode = false; -let fileSystemExplorer = null; -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 +let enableConsoleDebugMessages = false; // whether to display debug messages at the developer console, or not -// =================== common helper function =================== +var ajaxCallCounter = 0; + + +//+======================================================================================+ +//| API interaction | +//+======================================================================================+ + +/** + * Performs a GET request to the specified API endpoint. + * @param {string} url - The API endpoint URL. + * @returns {Promise} The response data if successful, undefined otherwise. + */ +async function callApiGetAsync(url) { + try { + // create the URL for the API endpoint + const response = await fetch(url); // call the API + if (!response.ok) + throw new Error('Network response was not ok'); + const jsonResponse = await response.json(); + if (jsonResponse.success) + return jsonResponse.data; + else + notificationService.show(jsonResponse.errorMessage, NotificationType.ERROR); + } catch (error) { + console.error('Error:', error); + notificationService.show(error, NotificationType.ERROR); + } +} + +//+======================================================================================+ +//| Common Helper Functions | +//+======================================================================================+ + +/** + * Starts progress indicator + */ +function showBusyIndicator() { + //if (ajaxCallCounter === 0) + //progressIndicator.classList.remove('hidden'); + ajaxCallCounter++; +} + +/** + * Hides progress indicator + */ +function hideBusyIndicator() { + ajaxCallCounter--; + //if (ajaxCallCounter === 0) + //progressIndicator.classList.add('hidden'); +} + +/** + * Shows the elements that display a progress operation + */ +function showOperationProgress() { + progressIndicatorValueShadow.classList.remove('hidden'); + progressIndicatorValue.classList.remove('hidden'); +} + +/** + * Hides the elements that display a progress operation + */ +function hideOperationProgress() { + progressIndicatorValueShadow.classList.add('hidden'); + progressIndicatorValue.classList.add('hidden'); +} + +/** + * Updates the progress indicator + * @param {int} completed - Number of completed elements + * @param {int} total - Number of total elements + */ +function updateOperationProgress(completed, total) { + progressIndicatorValueText.innerText = completed + '/' + total; +} /** * Convert Blob to Base64. @@ -117,23 +178,40 @@ function getScrollbarWidth() { } /** - * Enables horizontal scrolling to the element identified by the specified id. + * Handles the wheel event for horizontal scrolling. + * @param {WheelEvent} event - The wheel event object. */ -function addHorizontalScrolling(id) { - document.getElementById(id).addEventListener('wheel', function (e) { - e.preventDefault(); - this.scrollLeft += (e.deltaY > 0 ? 1 : -1) * 80; - }, { passive: false }); +const scrollHandler = function (event) { + event.preventDefault(); + this.scrollLeft += (event.deltaY > 0 ? 1 : -1) * 80; +}; + +/** + * Enables horizontal scrolling to the element identified by the specified id or element. + * @param {string|HTMLElement} idOrElement - The id of the element or the element itself. + */ +function addHorizontalScrolling(idOrElement) { + let element = idOrElement; + if (typeof idOrElement === 'string') + element = document.getElementById(idOrElement); + if (element instanceof HTMLElement) + element.addEventListener('wheel', scrollHandler, { passive: false }); + else + console.error('Invalid input: Expected an element ID or HTMLElement'); } /** - * Disables horizontal scrolling to the element identified by the specified id. + * Disables horizontal scrolling for the element identified by the specified id or element. + * @param {string|HTMLElement} idOrElement - The id of the element or the element itself. */ -function removeHorizontalScrolling(id) { - document.getElementById(id).removeEventListener('wheel', function (e) { - e.preventDefault(); - this.scrollLeft += (e.deltaY > 0 ? 1 : -1) * 80; - }, { passive: false }); +function removeHorizontalScrolling(idOrElement) { + let element = idOrElement; + if (typeof idOrElement === 'string') + element = document.getElementById(idOrElement); + if (element instanceof HTMLElement) + element.removeEventListener('wheel', scrollHandler, { passive: false }); + else + console.error('Invalid input: Expected an element ID or HTMLElement'); } /** @@ -159,590 +237,3 @@ function getElementOffset(id) { height: 0 }; } - -/** - * Get the position and size of an HTML element. - * @param {string} id - The id of the element to get the rectangle of. - * @returns {object} An object containing the element's X (left), Y (top), Width, and Height in pixels. - */ -function getElementRectangle(id) { - const element = document.getElementById(id); - const rect = element.getBoundingClientRect(); - return { - x: rect.left, - y: rect.top, - width: rect.width, - height: rect.height - }; -} - -// =================== file system browser dialog =================== - -/** - * Adjusts the height of a dropdown identified by `comboboxId` to fit in the available space. - * @param {string} comboboxId The Id of the combobox whose dropdown should be adjusted. - */ -function adjustDropdownHeight(comboboxId = null) { - const comboboxes = comboboxId - ? [document.getElementById(comboboxId)] // if comboboxId is provided, use only that element - : document.querySelectorAll('[id^="combobox_"]:not([id^="combobox_checkbox_"])'); // otherwise, select all dropdowns - if (comboboxes) { - comboboxes.forEach(combobox => { - if (!combobox) return; // skip if no element is found - const dropdown = combobox.querySelector('.enlightenment-dropdown'); - if (!dropdown) return; // skip if there's no dropdown inside - // get the bounds of the combobox and the height of the viewport - const comboboxRect = combobox.getBoundingClientRect(); - const viewportHeight = window.innerHeight; - // calculate the space available between the combobox and the bottom of the viewport, with a 10px margin - const dropdownTopPosition = comboboxRect.top + comboboxRect.height; - const availableSpace = viewportHeight - dropdownTopPosition - 10; // 10px margin - // adjust the dropdown height - dropdown.style.maxHeight = `${availableSpace}px`; - }); - } -} - -/** - * Updates the position and height of the dropdown relative to the specified path segment. - * @param {string} pathSegmentId - The ID of the path segment element to position the dropdown relative to. - */ -function updateDropdownPosition(pathSegmentId) { - const element = document.getElementById(pathSegmentId); - const dropdown = document.getElementById('navigatorDropdown'); - if (element && dropdown) { - const rect = getElementOffset(pathSegmentId); - dropdown.style.top = `${rect.top + rect.height}px`; - dropdown.style.left = `${rect.left}px`; - // calculate the available height between the dropdown and the bottom of the viewport - const viewportHeight = window.innerHeight; - const availableHeight = viewportHeight - (rect.top + rect.height) - 10; // 10 px margin - // set the dropdown's max height, ensuring it doesn't exceed the available height - dropdown.style.maxHeight = `${availableHeight}px`; - } -} - -/** - * Focuses the navigator address bar input. - */ -function focusNavigatorInputElement() { - const elements = document.getElementsByClassName('navigator-address-bar-input'); - if (elements.length > 0) - elements[0].focus(); -} - -/** - * Unchecks all checkboxes except the one with the specified Id. - * @param {string} id - The Id of the checkbox to leave checked. - */ -function uncheckAllExcept(id) { - const checkboxes = document.querySelectorAll('.navigator-toggle-checkbox'); - checkboxes.forEach((checkbox) => { - if (checkbox.id !== id) - checkbox.checked = false; - }); -} - -/** - * Closes all navigator path segments. - */ -function closeNavigatorPathSegments() { - const checkboxes = document.getElementsByClassName('navigator-toggle-checkbox'); - for (let i = 0; i < checkboxes.length; i++) - 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 =================== - -/** - * Function called at the initialization of fle system browser dialog - * @param {any} dotnetHelper - .NET object to invoke methods asynchronously. - */ -function initializeFileSystemBrowser(dotnetHelper) { - // cache frequently accessed elements - if (!selectionRectangle) - selectionRectangle = document.getElementById('selection-rectangle'); - if (!visibleSelectionRectangle) - visibleSelectionRectangle = document.getElementById('visible-selection-rectangle'); - if (!fileSystemExplorer) { - fileSystemExplorer = document.getElementById('file-system-browser-file-system-explorer'); - if (fileSystemExplorer) { - fileSystemExplorer.addEventListener('mouseup', handleFileSystemExplorerMouseUp); - fileSystemExplorer.addEventListener('scroll', handleFileSystemBrowserScrollEvent); - } - } - // event handlers needed for selection - if (!fileSystemExplorerContainer) { - fileSystemExplorerContainer = document.getElementById('file-system-browser-file-system-explorer-container'); - if (fileSystemExplorerContainer) { - fileSystemExplorerContainer.addEventListener('mousedown', startSelection); - fileSystemExplorerContainer.addEventListener('mousemove', updateSelection); - fileSystemExplorerContainer.addEventListener('mouseup', endSelection); - fileSystemExplorerContainer.addEventListener('wheel', handleSelection); - fileSystemExplorerContainer.addEventListener('scroll', handleFileSystemBrowserScrollEvent); - fileSystemExplorerContainer.addEventListener('scroll', handleSelection); - } - } - // handler for the mouse down event of file system browser dialog files and directories elements - window.handleFileSystemEntityMouseDown = function (e) { - // stop the event from bubbling up to the explorer - we dont want to start selection rectangles when clicking files or directories - e.stopPropagation(); - }; - - // handler for the mouse up event of file system browser dialog files and directories elements - window.handleFileSystemEntityMouseUp = function (e) { - e.preventDefault(); - if (!isSelecting) - e.stopPropagation(); - const allEClassElements = Array.from(fileSystemExplorer.querySelectorAll('.e')); - const currentIndex = allEClassElements.indexOf(e.currentTarget); - - // If a previous click timestamp exists, check the time difference - const previousTime = parseInt(e.currentTarget.dataset.selectionStartTime || 0); - const currentTime = new Date().getTime(); - const timeDifference = currentTime - previousTime; - - // TODO: needs to account for when the element is already selected, and a double click occurs - on first click it would check the difference and go to rename - - // maybe just wait half second before performing action - - // if time difference is less than 300ms, treat it as a double-click - if (timeDifference < 300) { - if (e.currentTarget.dataset.type === 'directory') { // directories - dotnetHelper.invokeMethodAsync('OnDirectoryDoubleClickAsync', e.currentTarget.dataset.path); - return; - } - else { // files - - } - // reset the timestamp used to track double clicks - e.currentTarget.dataset.selectionStartTime = 0; - return; - } - else - e.currentTarget.dataset.selectionStartTime = currentTime; // element was single clicked, update the selection start time to now - if (e.ctrlKey || isSelectionMode) { // when CTRL key is pressed - // toggle selection for the current clicked item - e.currentTarget.classList.toggle('selected'); - // set the selection start if it's not already set - if (fileSystemExplorer.dataset.selectionStart === undefined) - fileSystemExplorer.dataset.selectionStart = currentIndex; - } - else if ((e.shiftKey && fileSystemExplorer.dataset.selectionStart !== undefined) || isSelectionMode) { // when SHIFT key is pressed - const start = parseInt(fileSystemExplorer.dataset.selectionStart); - // remove all selections - allEClassElements.forEach(elem => { - elem.classList.remove('selected'); - }); - // define the range to select items from and to - const [from, to] = start < currentIndex ? [start, currentIndex] : [currentIndex, start]; - // add the 'selected' class to items in the range - for (let i = from; i <= to; i++) - allEClassElements[i].classList.add('selected'); - } - 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')); - // add 'selected' class to the current clicked item - e.currentTarget.classList.add('selected'); - // if there are no selected elements, or if there are more than one, deselect all of them, and select just the clicked one - if ((selectedElements.length === 1 && e.currentTarget !== selectedElements[0]) || selectedElements.length !== 1) { - // deselect all items - selectedElements.forEach(elem => { - if (elem !== e.currentTarget) { - elem.classList.remove('selected'); - // remove selectionStartTime from all items - delete elem.dataset.selectionStartTime; - } - }); - // set the current item as the selection start - fileSystemExplorer.dataset.selectionStart = currentIndex; - // store the current timestamp for future double-click checks - e.currentTarget.dataset.selectionStartTime = currentTime; - } - } - else // if its selection mode, just toggle selection of item, when clicked - e.currentTarget.classList.toggle('selected'); - } - }; -} - -/** - * Handler for the mouse up event of the file system browser dialog explorer - * @param {MouseEvent} e - The mouseup event object. - */ -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) - return; - if (!e.ctrlKey && !e.shiftKey && !isSelectionMode) { - // deselect all file system elements when their explorer is clicked - fileSystemExplorer.querySelectorAll('.e.selected').forEach(item => { - item.classList.remove('selected'); - }); - // do not store information about what item was clicked first, in context of Shift-selection - fileSystemExplorer.removeAttribute('data-selection-start'); - } -} - -/** - * Handler for the file system browser dialog selection start. - * @param {MouseEvent} e - The mousedown event object. - */ -function startSelection(e) { - const explorerScrollbars = hasScrollbars(fileSystemExplorer); - const containerExplorerScrollbars = hasScrollbars(fileSystemExplorerContainer); - // check if clicked on the horizontal or vertical scrollbar - if (explorerScrollbars.horizontal && e.clientY > fileSystemExplorer.getBoundingClientRect().top + fileSystemExplorer.offsetHeight - scrollbarHeight) - return; - if (containerExplorerScrollbars.vertical && e.clientX > fileSystemExplorerContainer.getBoundingClientRect().left + fileSystemExplorerContainer.offsetWidth - scrollbarWidth) - return; - // store information about selection start - isSelecting = true; - document.body.style.overflowY = 'hidden'; // needed in order to not put a vertical scrollbar on the document, while in vertical layout selection - document.documentElement.style.overflowY = 'hidden'; - selectionStartPosition.x = e.pageX + fileSystemExplorer.scrollLeft; - selectionStartPosition.y = e.pageY + fileSystemExplorerContainer.scrollTop; // not a mistake - in vertical mode, this is the overflow container! - // place the selection rectangle at the clicked location (relative to the whole page, and taking into account scroll offset), with 0 size - visibleSelectionRectangle.style.left = e.pageX + 'px'; - visibleSelectionRectangle.style.top = e.pageY + 'px'; - visibleSelectionRectangle.style.width = '0px'; - visibleSelectionRectangle.style.height = '0px'; - visibleSelectionRectangle.style.visibility = 'visible'; - - selectionRectangle.style.left = e.pageX + 'px'; - selectionRectangle.style.top = e.pageY + 'px'; - selectionRectangle.style.width = '0px'; - selectionRectangle.style.height = '0px'; -} - -/** - * Handler for the file system browser dialog selection update. - * @param {MouseEvent} e - The mousemove event object. - */ -function updateSelection(e) { - if (!isSelecting) - return; - currentMousePosition.x = e.pageX; - currentMousePosition.y = e.pageY; - handleSelection(); -} - -/** - * Handler for the file system browser dialog selection end. - * @param {MouseEvent} e - The mouseup event object. - */ -function endSelection(e) { - // selection ended, hide the selection rectangle - isSelecting = false; - document.body.style.removeProperty('overflow-y'); - document.documentElement.style.removeProperty('overflow-y'); - - visibleSelectionRectangle.style.visibility = 'hidden'; - selectionRectangle.style.visibility = 'hidden'; - - selectionRectangle.style.left = '0px'; - selectionRectangle.style.top = '0px'; - selectionRectangle.style.width = '0px'; - selectionRectangle.style.height = '0px'; - visibleSelectionRectangle.style.left = '0px'; - visibleSelectionRectangle.style.top = '0px'; - visibleSelectionRectangle.style.width = '0px'; - visibleSelectionRectangle.style.height = '0px'; - // go through each .e item that was inside the selection rectangle, and mark it as selected - fileSystemExplorer.querySelectorAll('.e.selection-hover').forEach(item => { - item.classList.add('selected'); - item.classList.remove('selection-hover'); - }); -} - -/** - * Function for handling the file system browser dialog selection. - */ -function handleSelection() { - if (!isSelecting) // only relevant when we have a selection initialized - return; - // calculate dimensions of the selection rectangle - const currentX = currentMousePosition.x; - const currentY = currentMousePosition.y; - const width = currentX - (selectionStartPosition.x - fileSystemExplorer.scrollLeft); - const height = currentY - (selectionStartPosition.y - fileSystemExplorerContainer.scrollTop); - - // update selection rectangle dimensions - visibleSelectionRectangle.style.width = Math.abs(width) + 'px'; - visibleSelectionRectangle.style.height = Math.abs(height) + 'px'; - selectionRectangle.style.width = Math.abs(width) + 'px'; - selectionRectangle.style.height = Math.abs(height) + 'px'; - - // adjust position based on selection direction - if (width < 0) { - selectionRectangle.style.left = currentX + 'px'; - visibleSelectionRectangle.style.left = currentX + 'px'; - } else { - selectionRectangle.style.left = (selectionStartPosition.x - fileSystemExplorer.scrollLeft) + 'px'; - visibleSelectionRectangle.style.left = (selectionStartPosition.x - fileSystemExplorer.scrollLeft) + 'px'; - } - if (height < 0) { - selectionRectangle.style.top = currentY + 'px'; - visibleSelectionRectangle.style.top = currentY + 'px'; - } else { - selectionRectangle.style.top = (selectionStartPosition.y - fileSystemExplorerContainer.scrollTop) + 'px'; - visibleSelectionRectangle.style.top = (selectionStartPosition.y - fileSystemExplorerContainer.scrollTop) + 'px'; - } - - // do not let the selection rectangle go outside of explorer container, clip it if needed - const containerRect = fileSystemExplorerContainer.getBoundingClientRect(); - const left = parseFloat(visibleSelectionRectangle.style.left); - const top = parseFloat(visibleSelectionRectangle.style.top) + 1; - const right = left + parseFloat(visibleSelectionRectangle.style.width); - const bottom = top + parseFloat(visibleSelectionRectangle.style.height); - - if (left < containerRect.left) { - const difference = containerRect.left - left; - visibleSelectionRectangle.style.width = (parseFloat(visibleSelectionRectangle.style.width) - difference) + 'px'; - visibleSelectionRectangle.style.left = containerRect.left + 'px'; - } - if (right > containerRect.right) - visibleSelectionRectangle.style.width = (containerRect.right - left) + 'px'; - - if (top < containerRect.top) { - const difference = containerRect.top - top; - visibleSelectionRectangle.style.height = (parseFloat(visibleSelectionRectangle.style.height) - difference) + 'px'; - visibleSelectionRectangle.style.top = containerRect.top + 'px'; - } - if (bottom > containerRect.bottom) - visibleSelectionRectangle.style.height = (containerRect.bottom - top) + 'px'; - - // change color of items that fall within selection rectangle - const selectionRect = selectionRectangle.getBoundingClientRect(); - // go through each .e item which has not had its thumbnail retrieved yet - fileSystemExplorer.querySelectorAll('.e').forEach(item => { - const itemRect = item.getBoundingClientRect(); - // check if the item is fully or partially visible horizontally and vertically - const isFullyVisibleHorizontally = itemRect.left >= selectionRect.left && itemRect.right <= selectionRect.right; - const isFullyVisibleVertically = itemRect.top >= selectionRect.top && itemRect.bottom <= selectionRect.bottom; - const isPartiallyVisibleHorizontally = itemRect.left < selectionRect.right && itemRect.right > selectionRect.left; - const isPartiallyVisibleVertically = itemRect.top < selectionRect.bottom && itemRect.bottom > selectionRect.top; - // if the item is fully or partially visible in both directions, add it to our list - if ((isFullyVisibleHorizontally || isPartiallyVisibleHorizontally) && (isFullyVisibleVertically || isPartiallyVisibleVertically)) - item.classList.add('selection-hover'); - else - item.classList.remove('selection-hover'); - }); -} - -/** - * Toggles the state of selection mode. - * @param {MouseEvent} e - The mouseup event object. - */ -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 =================== - -/** - * 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. - */ -function windowClickHandler(dotnetHelper) { - window.addEventListener('click', (e) => { - dotnetHelper.invokeMethodAsync('OnWindowClickAsync', { - x: e.clientX, - y: e.clientY, - sender: e.target.getAttribute('id') - }); - }); -} - -/** - * 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. - */ -function windowKeyDownHandler(element, dotnetHelper) { - element.addEventListener('keydown', (e) => { - if (e.key === 'Escape') { - e.preventDefault(); - dotnetHelper.invokeMethodAsync('EscapePressed'); - } - }); -} - -/** - * Handles the window resize event. - */ -window.addEventListener('resize', function () { - adjustDropdownHeight(); - handleFileSystemBrowserResizeEvent(); - // update all dropdowns' positions on resize - const dropdown = document.getElementById('navigatorDropdown'); - if (dropdown) { - const pathSegmentId = dropdown.getAttribute('data-path-segment-id'); - if (pathSegmentId) - updateDropdownPosition(pathSegmentId); - } -}); diff --git a/src/Lumina.sln b/src/Lumina.sln index 5acf55a3..74a02b02 100644 --- a/src/Lumina.sln +++ b/src/Lumina.sln @@ -82,7 +82,7 @@ Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "templates", "templates", "{ ..\docs\technical\templates\PULL_REQUEST_TEMPLATE.md = ..\docs\technical\templates\PULL_REQUEST_TEMPLATE.md EndProjectSection EndProject -Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "Lumina.Presentation.Web", "Lumina.Presentation.Web\Lumina.Presentation.Web.csproj", "{613C74E8-720C-4205-8BA7-85B23D2E7881}" +Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "Lumina.Presentation.Web", "Lumina.Presentation.Web\Lumina.Presentation.Web.csproj", "{613C74E8-720C-4205-8BA7-85B23D2E7881}" EndProject Global GlobalSection(SolutionConfigurationPlatforms) = preSolution