diff --git a/.editorconfig b/.editorconfig
index 028900f4..e9cad815 100644
--- a/.editorconfig
+++ b/.editorconfig
@@ -274,8 +274,6 @@ dotnet_naming_style.local_function_style.capitalization = pascal_case
# readonly instance fields are camelCase and begin with underscore
dotnet_naming_symbols.readonly_instance_fields.applicable_kinds = field
dotnet_naming_symbols.readonly_instance_fields.required_modifiers = readonly
-dotnet_naming_symbols.readonly_instance_fields.required_modifiers_style = exclude_any
-dotnet_naming_symbols.readonly_instance_fields.required_modifiers = static
dotnet_naming_style.underscore_camel_case_style.capitalization = camel_case
dotnet_naming_style.underscore_camel_case_style.required_prefix = _
diff --git a/src/Lumina.Application/Common/Mapping/FileManagement/ThumbnailMappingConfig.cs b/src/Lumina.Application/Common/Mapping/FileManagement/ThumbnailMappingConfig.cs
new file mode 100644
index 00000000..abc48722
--- /dev/null
+++ b/src/Lumina.Application/Common/Mapping/FileManagement/ThumbnailMappingConfig.cs
@@ -0,0 +1,27 @@
+#region ========================================================================= USING =====================================================================================
+using Lumina.Contracts.Responses.FileManagement;
+using Lumina.Domain.Core.Aggregates.FileManagement.FileManagementAggregate.ValueObjects;
+using Mapster;
+#endregion
+
+namespace Lumina.Application.Common.Mapping.FileManagement;
+
+///
+/// Mapping configuration for file system thumbnails between the domain object and the presentation object.
+///
+public class ThumbnailMappingConfig : IRegister
+{
+ #region ===================================================================== METHODS ===================================================================================
+ ///
+ /// Registers the mapping configuration.
+ ///
+ /// The type adapter configuration.
+ public void Register(TypeAdapterConfig config)
+ {
+ config.NewConfig()
+ .Map(dest => dest.Type, src => src.Type)
+ .Map(dest => dest.Bytes, src => src.Bytes)
+ .MapToConstructor(true);
+ }
+ #endregion
+}
diff --git a/src/Lumina.Application/Core/FileManagement/Thumbnails/Queries/GetThumbnail/GetThumbnailQuery.cs b/src/Lumina.Application/Core/FileManagement/Thumbnails/Queries/GetThumbnail/GetThumbnailQuery.cs
new file mode 100644
index 00000000..16c725fc
--- /dev/null
+++ b/src/Lumina.Application/Core/FileManagement/Thumbnails/Queries/GetThumbnail/GetThumbnailQuery.cs
@@ -0,0 +1,14 @@
+#region ========================================================================= USING =====================================================================================
+using ErrorOr;
+using Lumina.Contracts.Responses.FileManagement;
+using Mediator;
+#endregion
+
+namespace Lumina.Application.Core.FileManagement.Thumbnails.Queries.GetThumbnail;
+
+///
+/// Query for retrieving the thumbnail of a file at a path.
+///
+/// The file path of the image to generate the thumbnail from.
+/// The desired quality of the thumbnail image (e.g., resolution or compression level).
+public record GetThumbnailQuery(string Path, int Quality) : IRequest>;
diff --git a/src/Lumina.Application/Core/FileManagement/Thumbnails/Queries/GetThumbnail/GetThumbnailQueryHandler.cs b/src/Lumina.Application/Core/FileManagement/Thumbnails/Queries/GetThumbnail/GetThumbnailQueryHandler.cs
new file mode 100644
index 00000000..c43e0f79
--- /dev/null
+++ b/src/Lumina.Application/Core/FileManagement/Thumbnails/Queries/GetThumbnail/GetThumbnailQueryHandler.cs
@@ -0,0 +1,47 @@
+#region ========================================================================= USING =====================================================================================
+using ErrorOr;
+using Lumina.Contracts.Responses.FileManagement;
+using Lumina.Domain.Core.Aggregates.FileManagement.FileManagementAggregate.Services;
+using Lumina.Domain.Core.Aggregates.FileManagement.FileManagementAggregate.ValueObjects;
+using Mapster;
+using Mediator;
+using System.Threading;
+using System.Threading.Tasks;
+#endregion
+
+namespace Lumina.Application.Core.FileManagement.Thumbnails.Queries.GetThumbnail;
+
+///
+/// Handler for the query to get the file thumbnail.
+///
+public class GetThumbnailQueryHandler : IRequestHandler>
+{
+ #region ================================================================== FIELD MEMBERS ================================================================================
+ private readonly IThumbnailService _thumbnailsService;
+ #endregion
+
+ #region ====================================================================== CTOR =====================================================================================
+ ///
+ /// Initializes a new instance of the class.
+ ///
+ /// Injected service for handling thumbnails.
+ public GetThumbnailQueryHandler(IThumbnailService thumbnailsService)
+ {
+ _thumbnailsService = thumbnailsService;
+ }
+ #endregion
+
+ #region ===================================================================== METHODS ===================================================================================
+ ///
+ /// Gets the thumbnail for a file located at the specified path, with the specified quality.
+ ///
+ /// The query to be handled.
+ /// Cancellation token that can be used to stop the execution.
+ /// An containing either a thumbnail, or an error.
+ public async ValueTask> Handle(GetThumbnailQuery request, CancellationToken cancellationToken)
+ {
+ ErrorOr result = await _thumbnailsService.GetThumbnailAsync(request.Path, request.Quality, cancellationToken);
+ return await ValueTask.FromResult(result.Match(values => ErrorOrFactory.From(result.Value.Adapt()), errors => errors));
+ }
+ #endregion
+}
diff --git a/src/Lumina.Contracts/Responses/FileManagement/ThumbnailResponse.cs b/src/Lumina.Contracts/Responses/FileManagement/ThumbnailResponse.cs
new file mode 100644
index 00000000..1ab5d184
--- /dev/null
+++ b/src/Lumina.Contracts/Responses/FileManagement/ThumbnailResponse.cs
@@ -0,0 +1,14 @@
+#region ========================================================================= USING =====================================================================================
+using Lumina.Contracts.Enums.PhotoLibrary;
+using System.Diagnostics;
+#endregion
+
+namespace Lumina.Contracts.Responses.FileManagement;
+
+///
+/// Data transfer object for thumbnails.
+///
+/// The type of the thumbnail image.
+/// The bytes representing the thumbail.
+[DebuggerDisplay("{Type}")]
+public record ThumbnailResponse(ImageType Type, byte[] Bytes);
diff --git a/src/Lumina.Domain/Core/Aggregates/FileManagement/FileManagementAggregate/Services/FileProviderService.cs b/src/Lumina.Domain/Core/Aggregates/FileManagement/FileManagementAggregate/Services/FileProviderService.cs
index c8f96aff..8978437b 100644
--- a/src/Lumina.Domain/Core/Aggregates/FileManagement/FileManagementAggregate/Services/FileProviderService.cs
+++ b/src/Lumina.Domain/Core/Aggregates/FileManagement/FileManagementAggregate/Services/FileProviderService.cs
@@ -105,7 +105,7 @@ internal class FileProviderService : IFileProviderService
// check if the user has access permissions to the provided path
if (!_fileSystemPermissionsService.CanAccessPath(path, FileAccessMode.ReadContents))
return Errors.Permission.UnauthorizedAccess;
- return System.IO.File.ReadAllBytes(path.Path);
+ return File.ReadAllBytes(path.Path);
}
///
diff --git a/src/Lumina.Domain/Core/Aggregates/FileManagement/FileManagementAggregate/Services/FileTypeService.cs b/src/Lumina.Domain/Core/Aggregates/FileManagement/FileManagementAggregate/Services/FileTypeService.cs
index 4e2309d8..27142814 100644
--- a/src/Lumina.Domain/Core/Aggregates/FileManagement/FileManagementAggregate/Services/FileTypeService.cs
+++ b/src/Lumina.Domain/Core/Aggregates/FileManagement/FileManagementAggregate/Services/FileTypeService.cs
@@ -9,6 +9,7 @@ using System;
using System.IO.Abstractions;
using System.Linq;
using System.Text;
+using System.Threading;
using System.Threading.Tasks;
#endregion
@@ -43,18 +44,20 @@ public class FileTypeService : IFileTypeService
/// Determines if is of type image or not, and returns its type.
///
/// The file to determine if it is an image or not.
+ /// Cancellation token that can be used to stop the execution.
/// An containing the type of image or an error.
- public async Task> GetImageTypeAsync(File file)
+ public async Task> GetImageTypeAsync(File file, CancellationToken cancellationToken)
{
- return await GetImageTypeAsync(file.Id).ConfigureAwait(false);
+ return await GetImageTypeAsync(file.Id, cancellationToken).ConfigureAwait(false);
}
///
/// Determines if a file identified by is of type image or not, and returns its type.
///
/// The path of the file to determine if it is an image or not.
+ /// Cancellation token that can be used to stop the execution.
/// An containing the type of image or an error.
- public async Task> GetImageTypeAsync(FileSystemPathId path)
+ public async Task> GetImageTypeAsync(FileSystemPathId path, CancellationToken cancellationToken)
{
// check if the user has access permissions to the provided path
if (!_fileSystemPermissionsService.CanAccessPath(path, FileAccessMode.ReadContents))
@@ -65,7 +68,7 @@ public class FileTypeService : IFileTypeService
if (stream.Length < BUFFER_SIZE)
return ImageType.None;
// read only the first bytes of the file, equal to the buffer size
- await stream.ReadAsync(buffer).ConfigureAwait(false);
+ await stream.ReadAsync(buffer, cancellationToken).ConfigureAwait(false);
byte[] firstBytes = buffer[..BUFFER_SIZE].ToArray();
// check if its a known image type, based on header bytes
ImageType type = IdentifyHeader(firstBytes);
diff --git a/src/Lumina.Domain/Core/Aggregates/FileManagement/FileManagementAggregate/Services/IFileTypeService.cs b/src/Lumina.Domain/Core/Aggregates/FileManagement/FileManagementAggregate/Services/IFileTypeService.cs
index 6ff3f5c7..7d74c0bb 100644
--- a/src/Lumina.Domain/Core/Aggregates/FileManagement/FileManagementAggregate/Services/IFileTypeService.cs
+++ b/src/Lumina.Domain/Core/Aggregates/FileManagement/FileManagementAggregate/Services/IFileTypeService.cs
@@ -1,8 +1,9 @@
-#region ========================================================================= USING =====================================================================================
+#region ========================================================================= USING =====================================================================================
using ErrorOr;
using Lumina.Contracts.Enums.PhotoLibrary;
using Lumina.Domain.Core.Aggregates.FileManagement.FileManagementAggregate.Entities;
using Lumina.Domain.Core.Aggregates.FileManagement.FileManagementAggregate.ValueObjects;
+using System.Threading;
using System.Threading.Tasks;
#endregion
@@ -18,14 +19,16 @@ public interface IFileTypeService
/// Determines if is of type image or not, and returns its type.
///
/// The file to determine if it is an image or not.
+ /// Cancellation token that can be used to stop the execution.
/// An containing the type of image or an error.
- Task> GetImageTypeAsync(File file);
+ Task> GetImageTypeAsync(File file, CancellationToken cancellationToken);
///
/// Determines if a file identified by is of type image or not, and returns its type.
///
/// The path of the file to determine if it is an image or not.
+ /// Cancellation token that can be used to stop the execution.
/// An containing the type of image or an error.
- Task> GetImageTypeAsync(FileSystemPathId path);
+ Task> GetImageTypeAsync(FileSystemPathId path, CancellationToken cancellationToken);
#endregion
-}
\ No newline at end of file
+}
diff --git a/src/Lumina.Domain/Core/Aggregates/FileManagement/FileManagementAggregate/Services/IThumbnailService.cs b/src/Lumina.Domain/Core/Aggregates/FileManagement/FileManagementAggregate/Services/IThumbnailService.cs
index 39dfd506..55e60fd4 100644
--- a/src/Lumina.Domain/Core/Aggregates/FileManagement/FileManagementAggregate/Services/IThumbnailService.cs
+++ b/src/Lumina.Domain/Core/Aggregates/FileManagement/FileManagementAggregate/Services/IThumbnailService.cs
@@ -1,6 +1,7 @@
-#region ========================================================================= USING =====================================================================================
+#region ========================================================================= USING =====================================================================================
using ErrorOr;
using Lumina.Domain.Core.Aggregates.FileManagement.FileManagementAggregate.ValueObjects;
+using System.Threading;
using System.Threading.Tasks;
#endregion
@@ -17,15 +18,17 @@ public interface IThumbnailService
///
/// String representation of the file path.
/// The quality of the thumbnail to get.
+ /// Cancellation token that can be used to stop the execution.
/// An containing either a collection of bytes representing the thumbnail of the file at the specified path or an error.
- Task> GetThumbnailAsync(string path, int quality);
+ Task> GetThumbnailAsync(string path, int quality, CancellationToken cancellationToken);
///
/// Gets the thumbnail of a file at the specified path.
///
/// The path object.
/// The quality of the thumbnail to get.
+ /// Cancellation token that can be used to stop the execution.
/// An containing either a collection of bytes representing the thumbnail of the file at the specified path or an error.
- Task> GetThumbnailAsync(FileSystemPathId path, int quality);
+ Task> GetThumbnailAsync(FileSystemPathId path, int quality, CancellationToken cancellationToken);
#endregion
-}
\ No newline at end of file
+}
diff --git a/src/Lumina.Domain/Core/Aggregates/FileManagement/FileManagementAggregate/Services/ThumbnailService.cs b/src/Lumina.Domain/Core/Aggregates/FileManagement/FileManagementAggregate/Services/ThumbnailService.cs
index adf18776..23252b53 100644
--- a/src/Lumina.Domain/Core/Aggregates/FileManagement/FileManagementAggregate/Services/ThumbnailService.cs
+++ b/src/Lumina.Domain/Core/Aggregates/FileManagement/FileManagementAggregate/Services/ThumbnailService.cs
@@ -10,6 +10,7 @@ using SixLabors.ImageSharp.Formats.Png;
using SixLabors.ImageSharp.Processing;
using System;
using System.IO;
+using System.Threading;
using System.Threading.Tasks;
#endregion
@@ -41,13 +42,14 @@ public class ThumbnailService : IThumbnailService
///
/// String representation of the file path.
/// The quality of the thumbnail to get.
+ /// Cancellation token that can be used to stop the execution.
/// An containing either a collection of bytes representing the thumbnail of the file at the specified path or an error.
- public async Task> GetThumbnailAsync(string path, int quality)
+ public async Task> GetThumbnailAsync(string path, int quality, CancellationToken cancellationToken)
{
ErrorOr fileSystemPathIdResult = FileSystemPathId.Create(path);
if (fileSystemPathIdResult.IsError)
return fileSystemPathIdResult.Errors;
- return await GetThumbnailAsync(fileSystemPathIdResult.Value, quality);
+ return await GetThumbnailAsync(fileSystemPathIdResult.Value, quality, cancellationToken);
}
///
@@ -55,11 +57,12 @@ public class ThumbnailService : IThumbnailService
///
/// The path of the file for which to get the thumbnail.
/// The quality of the thumbnail to get.
+ /// Cancellation token that can be used to stop the execution.
/// An containing either a collection of bytes representing the thumbnail of the file at the specified path or an error.
- public async Task> GetThumbnailAsync(FileSystemPathId path, int quality)
+ public async Task> GetThumbnailAsync(FileSystemPathId path, int quality, CancellationToken cancellationToken)
{
// first, get the type of the image file
- ErrorOr imageTypeResult = await _environmentContext.FileTypeService.GetImageTypeAsync(path);
+ ErrorOr imageTypeResult = await _environmentContext.FileTypeService.GetImageTypeAsync(path, cancellationToken);
if (imageTypeResult.IsError)
return imageTypeResult.Errors;
if (imageTypeResult.Value != ImageType.None)
@@ -74,7 +77,7 @@ public class ThumbnailService : IThumbnailService
if (imageTypeResult.Value is ImageType.JPEG or ImageType.JPEG_CANON or ImageType.JPEG2000
or ImageType.JPEG_UNKNOWN or ImageType.PNG or ImageType.BMP
or ImageType.WEBP or ImageType.GIF or ImageType.TIFF or ImageType.TGA)
- adjustedImage = await AdjustImageResolutionAsync(fileContents, imageTypeResult.Value, quality);
+ adjustedImage = await AdjustImageResolutionAsync(fileContents, imageTypeResult.Value, quality, cancellationToken);
return new Thumbnail(imageTypeResult.Value, adjustedImage ?? fileContents);
}
else
@@ -87,8 +90,9 @@ public class ThumbnailService : IThumbnailService
/// The byte array of the source image.
/// The format of the image whose quality is adjusted.
/// A value between 1 (lowest quality) to 100 (highest quality).
+ /// Cancellation token that can be used to stop the execution.
/// A byte array representing the processed image.
- private static async Task AdjustImageQualityAsync(byte[] imageBytes, ImageType imageType, int quality)
+ private static async Task AdjustImageQualityAsync(byte[] imageBytes, ImageType imageType, int quality, CancellationToken cancellationToken)
{
using MemoryStream inputMemoryStream = new(imageBytes);
using MemoryStream outputMemoryStream = new();
@@ -99,24 +103,24 @@ public class ThumbnailService : IThumbnailService
case ImageType.JPEG_CANON:
case ImageType.JPEG_UNKNOWN:
{
- using Image image = await Image.LoadAsync(inputMemoryStream);
- await image.SaveAsync(outputMemoryStream, new JpegEncoder() { Quality = quality });
+ using Image image = await Image.LoadAsync(inputMemoryStream, cancellationToken);
+ await image.SaveAsync(outputMemoryStream, new JpegEncoder() { Quality = quality }, cancellationToken);
break;
}
case ImageType.PNG:
{
- using Image image = await Image.LoadAsync(inputMemoryStream);
+ using Image image = await Image.LoadAsync(inputMemoryStream, cancellationToken);
// PNG is lossless; quality adjustments don't apply in the same way - we can adjust compression
int compressionLevel = MapRange(quality, 1, 100, 1, 9);
PngEncoder encoder = new()
{ CompressionLevel = (PngCompressionLevel)compressionLevel };
- await image.SaveAsync(outputMemoryStream, encoder);
+ await image.SaveAsync(outputMemoryStream, encoder, cancellationToken);
break;
}
case ImageType.BMP:
{
- using Image image = await Image.LoadAsync(inputMemoryStream);
- await image.SaveAsync(outputMemoryStream, new PngEncoder()); // convert BMP to PNG for compression
+ using Image image = await Image.LoadAsync(inputMemoryStream, cancellationToken);
+ await image.SaveAsync(outputMemoryStream, new PngEncoder(), cancellationToken); // convert BMP to PNG for compression
break;
}
default:
@@ -131,12 +135,13 @@ public class ThumbnailService : IThumbnailService
/// The byte array of the source image.
/// The format of the image whose quality is adjusted.
/// A value between 1 (lowest quality) to 100 (highest quality).
+ /// Cancellation token that can be used to stop the execution.
/// The bytes of the adjusted image.
- private static async Task AdjustImageResolutionAsync(byte[] imageBytes, ImageType imageType, int quality)
+ private static async Task AdjustImageResolutionAsync(byte[] imageBytes, ImageType imageType, int quality, CancellationToken cancellationToken)
{
using MemoryStream inputMemoryStream = new(imageBytes);
using MemoryStream outputMemoryStream = new();
- Image image = await Image.LoadAsync(inputMemoryStream);
+ Image image = await Image.LoadAsync(inputMemoryStream, cancellationToken);
double ratio = quality / 100.0;
int newWidth = (int)(image.Width * ratio);
int newHeight = (int)(image.Height * ratio);
@@ -163,7 +168,7 @@ public class ThumbnailService : IThumbnailService
case ImageType.JPEG2000:
case ImageType.JPEG_CANON:
case ImageType.JPEG_UNKNOWN:
- await image.SaveAsync(outputMemoryStream, image.Metadata.DecodedImageFormat!);
+ await image.SaveAsync(outputMemoryStream, image.Metadata.DecodedImageFormat!, cancellationToken);
break;
default:
return imageBytes; // for unsupported formats, just return the original bytes
diff --git a/src/Lumina.Domain/Core/Aggregates/WrittenContentLibrary/BookLibraryAggregate/ValueObjects/Isbn.cs b/src/Lumina.Domain/Core/Aggregates/WrittenContentLibrary/BookLibraryAggregate/ValueObjects/Isbn.cs
index a2203d4b..d0b2c07c 100644
--- a/src/Lumina.Domain/Core/Aggregates/WrittenContentLibrary/BookLibraryAggregate/ValueObjects/Isbn.cs
+++ b/src/Lumina.Domain/Core/Aggregates/WrittenContentLibrary/BookLibraryAggregate/ValueObjects/Isbn.cs
@@ -17,8 +17,8 @@ namespace Lumina.Domain.Core.Aggregates.WrittenContentLibrary.BookLibraryAggrega
public sealed class Isbn : ValueObject
{
#region ================================================================== FIELD MEMBERS ================================================================================
- private static readonly Regex _isbn10Regex = new(@"^(?:ISBN(?:-10)?:? )?(?=[0-9X]{10}$|(?=(?:[0-9]+[-\ ]){3})[-\ 0-9X]{13}$)[0-9]{1,5}[-\ ]?[0-9]+[-\ ]?[0-9]+[-\ ]?[0-9X]$", RegexOptions.Compiled);
- private static readonly Regex _isbn13Regex = new(@"^(?:ISBN(?:-13)?:? )?(?=[0-9]{13}$|(?=(?:[0-9]+[-\ ]){4})[-\ 0-9]{17}$)97[89][-\ ]?[0-9]{1,5}[-\ ]?[0-9]+[-\ ]?[0-9]+[-\ ]?[0-9]$", RegexOptions.Compiled);
+ private static readonly Regex s_isbn10Regex = new(@"^(?:ISBN(?:-10)?:? )?(?=[0-9X]{10}$|(?=(?:[0-9]+[-\ ]){3})[-\ 0-9X]{13}$)[0-9]{1,5}[-\ ]?[0-9]+[-\ ]?[0-9]+[-\ ]?[0-9X]$", RegexOptions.Compiled);
+ private static readonly Regex s_isbn13Regex = new(@"^(?:ISBN(?:-13)?:? )?(?=[0-9]{13}$|(?=(?:[0-9]+[-\ ]){4})[-\ 0-9]{17}$)97[89][-\ ]?[0-9]{1,5}[-\ ]?[0-9]+[-\ ]?[0-9]+[-\ ]?[0-9]$", RegexOptions.Compiled);
#endregion
#region ==================================================================== PROPERTIES =================================================================================
@@ -83,7 +83,7 @@ public sealed class Isbn : ValueObject
/// if the ISBN-10 is valid, otherwise.
public static bool IsValidIsbn10(string isbn)
{
- if (!_isbn10Regex.IsMatch(isbn))
+ if (!s_isbn10Regex.IsMatch(isbn))
return false;
// remove any hyphens or spaces
isbn = isbn.Replace("-", "").Replace(" ", "").ToUpper();
@@ -105,7 +105,7 @@ public sealed class Isbn : ValueObject
/// if the ISBN-13 is valid, otherwise.
public static bool IsValidIsbn13(string isbn)
{
- if (!_isbn13Regex.IsMatch(isbn))
+ if (!s_isbn13Regex.IsMatch(isbn))
return false;
// remove any hyphens or spaces
isbn = isbn.Replace("-", "").Replace(" ", "");
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/Common/Utilities/MimeTypes.cs b/src/Lumina.Presentation.Api/Common/Utilities/MimeTypes.cs
new file mode 100644
index 00000000..3f0f81a4
--- /dev/null
+++ b/src/Lumina.Presentation.Api/Common/Utilities/MimeTypes.cs
@@ -0,0 +1,46 @@
+#region ========================================================================= USING =====================================================================================
+using Lumina.Contracts.Enums.PhotoLibrary;
+using System.Collections.Frozen;
+using System.Collections.Generic;
+#endregion
+
+namespace Lumina.Presentation.Api.Common.Utilities;
+
+///
+/// Utility class for converting from domain image types to known image mime types.
+///
+public static class MimeTypes
+{
+ #region ================================================================== FIELD MEMBERS ================================================================================
+ private static readonly FrozenDictionary s_imageTypeToMimeType = new Dictionary
+ {
+ { ImageType.BMP, "image/bmp" },
+ { ImageType.GIF, "image/gif" },
+ { ImageType.PNG, "image/png" },
+ { ImageType.TIFF, "image/tiff" },
+ { ImageType.JPEG, "image/jpeg" },
+ { ImageType.JPEG_CANON, "image/jpeg" },
+ { ImageType.JPEG_UNKNOWN, "image/jpeg" },
+ { ImageType.PICT, "image/x-pict" },
+ { ImageType.ICO, "image/x-icon" },
+ { ImageType.PSD, "image/vnd.adobe.photoshop" },
+ { ImageType.JPEG2000, "image/jp2" },
+ { ImageType.AVIF, "image/avif" },
+ { ImageType.WEBP, "image/webp" },
+ { ImageType.TGA, "image/x-tga" },
+ { ImageType.SVG, "image/svg+xml" }
+ }.ToFrozenDictionary();
+ #endregion
+
+ #region ===================================================================== METHODS ===================================================================================
+ ///
+ /// Gets the mime type of .
+ ///
+ /// The domain image type for which to get the mime type.
+ /// The mime type for .
+ public static string GetMimeType(ImageType type)
+ {
+ return s_imageTypeToMimeType.TryGetValue(type, out string? mimeType) ? mimeType : "application/octet-stream";
+ }
+ #endregion
+}
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.Api/Core/Controllers/FileManagement/ThumbnailsController.cs b/src/Lumina.Presentation.Api/Core/Controllers/FileManagement/ThumbnailsController.cs
new file mode 100644
index 00000000..35231a60
--- /dev/null
+++ b/src/Lumina.Presentation.Api/Core/Controllers/FileManagement/ThumbnailsController.cs
@@ -0,0 +1,52 @@
+#region ========================================================================= USING =====================================================================================
+using ErrorOr;
+using Lumina.Application.Core.FileManagement.Thumbnails.Queries.GetThumbnail;
+using Lumina.Contracts.Responses.FileManagement;
+using Lumina.Presentation.Api.Common.ModelBinders;
+using Lumina.Presentation.Api.Common.Utilities;
+using Lumina.Presentation.Api.Core.Controllers.Common;
+using Mediator;
+using Microsoft.AspNetCore.Mvc;
+using System.Threading;
+using System.Threading.Tasks;
+#endregion
+
+namespace Lumina.Presentation.Api.Core.Controllers.FileManagement;
+
+///
+/// Controller for managing file system items thumbnails.
+///
+[ApiVersion("1.0")]
+[Route("api/v{version:apiVersion}/[controller]")]
+public class ThumbnailsController : ApiController
+{
+ #region ================================================================== FIELD MEMBERS ================================================================================
+ private readonly ISender _mediator;
+ #endregion
+
+ #region ====================================================================== CTOR =====================================================================================
+ ///
+ /// Initializes a new instance of the class.
+ ///
+ /// Injected service for mediating commands and queries.
+ public ThumbnailsController(ISender mediator)
+ {
+ _mediator = mediator;
+ }
+ #endregion
+
+ #region ===================================================================== METHODS ===================================================================================
+ ///
+ /// Gets the thumbnail of a file identified by of .
+ ///
+ /// The path of the file for which to get the thumbnail.
+ /// The quality to use for the thumbnail.
+ /// Cancellation token that can be used to stop the execution.
+ [HttpGet("get-thumbnail")]
+ public async Task GetThumbnail([FromQuery, ModelBinder(typeof(UrlStringBinder))] string path, [FromQuery] int quality, CancellationToken cancellationToken)
+ {
+ ErrorOr getResult = await _mediator.Send(new GetThumbnailQuery(path, quality), cancellationToken);
+ return getResult.Match(result => File(result.Bytes, MimeTypes.GetMimeType(result.Type)), errors => Problem(errors));
+ }
+ #endregion
+}
diff --git a/src/Lumina.Presentation.Web/App.razor b/src/Lumina.Presentation.Web/App.razor
deleted file mode 100644
index 623580d0..00000000
--- a/src/Lumina.Presentation.Web/App.razor
+++ /dev/null
@@ -1,12 +0,0 @@
-
-
-
-
-
-
- Not found
-
-
Sorry, there's nothing at this address.
-
-
-
diff --git a/src/Lumina.Presentation.Web/Common/Api/ApiHttpClient.cs b/src/Lumina.Presentation.Web/Common/Api/ApiHttpClient.cs
index eb7095fa..f3be45b5 100644
--- a/src/Lumina.Presentation.Web/Common/Api/ApiHttpClient.cs
+++ b/src/Lumina.Presentation.Web/Common/Api/ApiHttpClient.cs
@@ -3,7 +3,6 @@ using Lumina.Presentation.Web.Common.Exceptions;
using Lumina.Presentation.Web.Common.Models.Common;
using Lumina.Presentation.Web.Common.Models.Configuration;
using Lumina.Presentation.Web.Common.Models.FileManagement;
-using Microsoft.AspNetCore.Components.WebAssembly.Http;
using Microsoft.Extensions.Options;
using System;
using System.Collections.Generic;
@@ -79,13 +78,7 @@ public class ApiHttpClient : IApiHttpClient
/// An object, which allows for asynchronous iteration over the deserialized items.
public async IAsyncEnumerable GetAsyncEnumerable(string endpoint, string? token = null, [EnumeratorCancellation] CancellationToken cancellationToken = default)
{
- using HttpRequestMessage request = new(HttpMethod.Get, endpoint);
- // HttpClient is implemented differently in Blazor WASM, because there are no sockets in the browser, so its BrowserHttpHandler is implemented on top of Fetch API,
- // which can provide response content in one of two forms: BrowserHttpContent, which is based on arrayBuffer method (this means that it will always read the response stream to its completion,
- // before making the content available), and StreamContent that is wrapping WasmHttpReadStream, which is based on readable streams (this one allows for reading response as it comes).
- // WasmHttpReadStream can only work when WebAssemblyEnableStreamingResponse is enabled on request, and only on browsers that support it
- request.SetBrowserResponseStreamingEnabled(true);
-
+ using HttpRequestMessage request = new(HttpMethod.Get, endpoint);
if (!string.IsNullOrEmpty(token))
request.Headers.Authorization = new AuthenticationHeaderValue("Bearer", token);
// send the request and expect only headers initially - this prevents the client from buffering the entire response
diff --git a/src/Lumina.Presentation.Web/Common/DependencyInjection/PresentationWebLayerConfiguration.cs b/src/Lumina.Presentation.Web/Common/DependencyInjection/PresentationWebLayerConfiguration.cs
index 73e4a8bb..bc8d87ef 100644
--- a/src/Lumina.Presentation.Web/Common/DependencyInjection/PresentationWebLayerConfiguration.cs
+++ b/src/Lumina.Presentation.Web/Common/DependencyInjection/PresentationWebLayerConfiguration.cs
@@ -1,6 +1,5 @@
-using Lumina.Presentation.Web.Common.Models.Configuration;
+using Lumina.Presentation.Web.Common.Models.Configuration;
using Lumina.Presentation.Web.Common.Utilities;
-using Microsoft.AspNetCore.Components.WebAssembly.Hosting;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
@@ -12,30 +11,18 @@ namespace Lumina.Presentation.Web.Common.DependencyInjection;
internal static class PresentationWebLayerConfiguration
{
#region ===================================================================== METHODS ===================================================================================
- ///
- /// Extension method for adding the Lumina.Presentation.Web configuration to the .
- ///
- /// The to add the configuration to.
- /// The updated .
- public static WebAssemblyHostBuilder AddConfiguration(this WebAssemblyHostBuilder builder)
- {
- // add the configuration sources to the configuration builder
- builder.Configuration.AddJsonFile("appsettings.json", optional: false, reloadOnChange: true);
- builder.Configuration.AddJsonFile("appsettings.Development.json", optional: true, reloadOnChange: true);
-
- builder.Services.BindConfiguration(builder.Configuration);
-
- return builder;
- }
-
///
/// Extension method for registering the configuration options of the Lumina.Presentation.Web project into the Dependency Injection container.
///
/// The to bind the configuration options to.
/// The configuration to be bound.
/// The updated .
- internal static IServiceCollection BindConfiguration(this IServiceCollection serviceCollection, IConfiguration configuration)
+ internal static IServiceCollection BindConfiguration(this IServiceCollection serviceCollection, IConfigurationManager configuration)
{
+ // add the configuration sources to the configuration builder
+ configuration.AddJsonFile("appsettings.json", optional: false, reloadOnChange: true);
+ configuration.AddJsonFile("appsettings.Development.json", optional: true, reloadOnChange: true);
+
serviceCollection.AddOptions()
.Bind(configuration.GetRequiredSection(ServerConfigurationModel.SECTION_NAME))
.ValidateFluently()
diff --git a/src/Lumina.Presentation.Web/Common/DependencyInjection/PresentationWebLayerServices.cs b/src/Lumina.Presentation.Web/Common/DependencyInjection/PresentationWebLayerServices.cs
index 569cde7c..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,23 +31,25 @@ public static class PresentationWebLayerServices
/// The updated .
public static IServiceCollection AddPresentationWebLayerServices(this IServiceCollection services)
{
+ 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);
@@ -56,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/EnlightenmentButton.razor b/src/Lumina.Presentation.Web/Components/EnlightenmentButton.razor
deleted file mode 100644
index cb40b148..00000000
--- a/src/Lumina.Presentation.Web/Components/EnlightenmentButton.razor
+++ /dev/null
@@ -1,18 +0,0 @@
-
-
-@code {
- [Parameter] public RenderFragment? ChildContent { get; set; }
- [Parameter] public EventCallback OnClick { get; set; }
- [Parameter] public bool IsDisabled { get; set; }
- [Parameter] public bool IsConfirmButton { get; set; } = true;
- [Parameter] public bool UsesPercentForHeight { get; set; }
- [Parameter] public bool UsesPercentForWidth { get; set; }
- [Parameter] public int Width { get; set; } = 100;
- [Parameter] public int Height { get; set; } = 22;
- [Parameter] public string? CssClass { get; set; }
-}
\ No newline at end of file
diff --git a/src/Lumina.Presentation.Web/Components/EnlightenmentCheckbox.razor b/src/Lumina.Presentation.Web/Components/EnlightenmentCheckbox.razor
deleted file mode 100644
index b1bfa83b..00000000
--- a/src/Lumina.Presentation.Web/Components/EnlightenmentCheckbox.razor
+++ /dev/null
@@ -1,27 +0,0 @@
-
-
-@code {
- [Parameter] public bool Checked { get; set; }
- [Parameter] public EventCallback CheckedChanged { get; set; }
- [Parameter] public string? Label { get; set; }
- [Parameter] public bool Disabled { get; set; }
- [Parameter] public string CssClass { get; set; } = "";
-
- ///
- /// Handles the change event.
- ///
- /// The event arguments.
- private async Task OnChangeHandler(ChangeEventArgs e)
- {
- Checked = e?.Value != null ? (bool)e.Value : false;
- await CheckedChanged.InvokeAsync(Checked).ConfigureAwait(false);
- }
-}
\ No newline at end of file
diff --git a/src/Lumina.Presentation.Web/Components/EnlightenmentCheckbox.razor.css b/src/Lumina.Presentation.Web/Components/EnlightenmentCheckbox.razor.css
deleted file mode 100644
index bd4515e1..00000000
--- a/src/Lumina.Presentation.Web/Components/EnlightenmentCheckbox.razor.css
+++ /dev/null
@@ -1,33 +0,0 @@
-.enlightenment-checkbox-label {
- display: flex;
- align-items: center;
- cursor: pointer;
- font-size: 14px;
- color: #6DCBFE;
- user-select: none;
-}
-
-.enlightenment-checkbox-hidden {
- display: none;
-}
-
-.enlightenment-checkbox {
- width: 14px;
- height: 14px;
- border-top: #000000 1px solid;
- border-bottom: #333333 1px solid;
- border-left: #000000 1px solid;
- border-right: #333333 1px solid;
- border-radius: 0;
- margin-right: 10px;
- position: relative;
- background: linear-gradient(to bottom, #111, #222 50%, #333);
-}
-
-.enlightenment-checkbox-hidden:checked + .enlightenment-checkbox {
- background-image: linear-gradient(180deg, #5E5D5D, #505050, #424343);
- border-top: #888888 1px solid;
- border-bottom: #333333 1px solid;
- border-left: #666666 1px solid;
- border-right: #444444 1px solid;
-}
\ No newline at end of file
diff --git a/src/Lumina.Presentation.Web/Components/EnlightenmentCombobox.razor b/src/Lumina.Presentation.Web/Components/EnlightenmentCombobox.razor
deleted file mode 100644
index 1192729b..00000000
--- a/src/Lumina.Presentation.Web/Components/EnlightenmentCombobox.razor
+++ /dev/null
@@ -1,91 +0,0 @@
-@using Lumina.Presentation.Web.Common.Models.UI
-@using Lumina.Presentation.Web.Core.Services.UI
-
-@typeparam TValue
-
-@implements IDisposable
-
-@inject ComboboxService _comboboxService
-@inject IJSRuntime JSRuntime
-
-
-
-
-
-
-
-
SelectItem(null)">No item selected
-
- @for (int i = 0; i < Items?.Count; i++)
- {
- var item = Items[i];
- var cssClass = $"enlightenment-item {(i == Items.Count - 1 ? "last-item" : string.Empty)} {(item.IsEnabled ? string.Empty : "disabled")}";
-
SelectItem(item)">@item.Text
- }
-
-
-
-@code {
- [Parameter] public List> Items { get; set; } = [];
- [Parameter] public ComboboxItem? SelectedItem { get; set; }
- [Parameter] public EventCallback> SelectedItemChanged { get; set; }
- [Parameter] public string? CssClass { get; set; }
-
- private bool IsOpen { get; set; }
- private Guid Id { get; set; } = Guid.NewGuid();
-
- ///
- /// Initializes the component.
- ///
- protected override void OnInitialized()
- {
- _comboboxService.ComboboxOpened += CloseIfNotThisAsync;
- }
-
- ///
- /// Toggles the dropdown state.
- ///
- private async Task ToggleDropdownAsync()
- {
- IsOpen = !IsOpen;
- if (IsOpen)
- {
- _comboboxService.NotifyComboboxOpened("combobox_checkbox_" + Id);
- await JSRuntime.InvokeVoidAsync("adjustDropdownHeight", "combobox_" + Id).ConfigureAwait(false);
- }
- }
-
- ///
- /// Closes the dropdown if the provided is not the current , or if it's .
- ///
- /// The optional id of the combobox that initiated the dropdown state change.
- private async Task CloseIfNotThisAsync(string? openedId)
- {
- if (openedId != "combobox_checkbox_" + Id && IsOpen)
- {
- IsOpen = false;
- await InvokeAsync(StateHasChanged);
- }
- }
-
- ///
- /// Selects the provided .
- ///
- /// The item to select.
- private async Task SelectItem(ComboboxItem? item)
- {
- SelectedItem = item;
- IsOpen = false;
- await SelectedItemChanged.InvokeAsync(item).ConfigureAwait(false);
- }
-
- ///
- /// Disposes the component.
- ///
- public void Dispose()
- {
- _comboboxService.ComboboxOpened -= CloseIfNotThisAsync;
- }
-}
\ No newline at end of file
diff --git a/src/Lumina.Presentation.Web/Components/EnlightenmentInput.razor b/src/Lumina.Presentation.Web/Components/EnlightenmentInput.razor
deleted file mode 100644
index 96979481..00000000
--- a/src/Lumina.Presentation.Web/Components/EnlightenmentInput.razor
+++ /dev/null
@@ -1,77 +0,0 @@
-@inject IJSRuntime JSRuntime
-
-
-
-@code {
- [Parameter] public string? Id { get; set; }
- [Parameter] public string Type { get; set; } = "text";
- [Parameter] public bool UsesPercentForHeight { get; set; }
- [Parameter] public bool UsesPercentForWidth { get; set; } = true;
- [Parameter] public int Width { get; set; } = 100;
- [Parameter] public int Height { get; set; } = 28;
- [Parameter] public string? CssClass { get; set; }
- [Parameter] public string? Name { get; set; }
- [Parameter] public bool AutoComplete { get; set; } = true;
- [Parameter] public string? Value { get; set; }
- [Parameter] public EventCallback ValueChanged { get; set; }
- [Parameter] public EventCallback OnEnterPressed { get; set; }
- [Parameter] public EventCallback OnEscapePressed { get; set; }
- [Parameter] public string? Placeholder { get; set; }
- [Parameter] public bool IsDisabled { get; set; }
- [Parameter] public bool IsReadOnly { get; set; }
- [Parameter] public bool HasError { get; set; }
-
- private ElementReference inputElement;
-
- ///
- /// Handles the event risen after the component was rendered.
- ///
- /// Indicates whether this is the first render or not.
- protected override async Task OnAfterRenderAsync(bool firstRender)
- {
- if (firstRender)
- await JSRuntime.InvokeVoidAsync("windowKeyDownHandler", inputElement, DotNetObjectReference.Create(this)).ConfigureAwait(false);
- }
-
- ///
- /// Handles the input change event.
- ///
- /// The event arguments.
- private async Task OnInputHandlerAsync(ChangeEventArgs e)
- {
- Value = e.Value?.ToString();
- await ValueChanged.InvokeAsync(Value).ConfigureAwait(false);
- }
-
- ///
- /// Handles the key down event.
- ///
- /// The event arguments.
- private async Task OnKeyDownAsync(KeyboardEventArgs e)
- {
- if (e.Key == "Enter" || e.Code == "NumpadEnter")
- await OnEnterPressed.InvokeAsync();
- }
-
- ///
- /// Handles the Escape key pressed.
- ///
- [JSInvokable]
- public void EscapePressed()
- {
- OnEscapePressed.InvokeAsync(Value);
- }
-}
\ No newline at end of file
diff --git a/src/Lumina.Presentation.Web/Components/FileSystemBrowser.razor b/src/Lumina.Presentation.Web/Components/FileSystemBrowser.razor
deleted file mode 100644
index 67bf700c..00000000
--- a/src/Lumina.Presentation.Web/Components/FileSystemBrowser.razor
+++ /dev/null
@@ -1,921 +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
-
-
- @if (pathSegments?.Length > 0)
- {
- for (int i = 0; i < pathSegments.Length; i++)
- {
- var localIndex = i; // capture the current index in a local variable, otherwise it would be evaluated when the loop ends
- var pathSegment = pathSegments[i];
-
@(Id is null ? "Add New Library" : "Edit Library")
-
-
-
-
-
-
-
-
-
- DescriptionTitle
-
-
-
-
-
-
-
- DescriptionLibraryType
-
-
-
-
-
-
-
-
-
-
Column 1
-
Column 2
-
Directories
-
-
-
- @foreach (var item in tableData)
- {
-
-
@item.Column1
-
@item.Column2
-
- @* *@
-
-
- }
-
-
- DescriptionURL
-
-
-
-
-
-
-
- DescriptionPort
-
-
-
-
-
-
-
- DescriptionUsername
-
-
-
-
-
-
-
- DescriptionPassword
-
-
-
-
-
-
- DescriptionPlatform
-
-
-
-
- Cancel
- Save
-
-
-
-
-
-
-
-
-
-
-@code {
- [Parameter]
- public Guid? Id { get; set; }
-
- private LibraryModel dataSource = new();
-
- private List> items = new()
- {
- new ComboboxItem{ Text = nameof(LibraryType.WrittenContent).SplitCamelCase(), IsEnabled = false },
- new ComboboxItem{ Text = nameof(WrittenContentType.Book).SplitCamelCase(), Value = nameof(WrittenContentType.Book) },
- new ComboboxItem{ Text = nameof(WrittenContentType.EBook).SplitCamelCase(), Value = nameof(WrittenContentType.EBook) },
- new ComboboxItem{ Text = nameof(WrittenContentType.BookSeries).SplitCamelCase(), Value = nameof(WrittenContentType.BookSeries) },
- new ComboboxItem{ Text = nameof(WrittenContentType.ComicBook).SplitCamelCase(), Value = nameof(WrittenContentType.ComicBook) },
- new ComboboxItem{ Text = nameof(WrittenContentType.ComicSeries).SplitCamelCase(), Value = nameof(WrittenContentType.ComicSeries) },
- new ComboboxItem{ Text = nameof(WrittenContentType.Magazine).SplitCamelCase(), Value = nameof(WrittenContentType.Magazine) },
- new ComboboxItem{ Text = nameof(WrittenContentType.Manga).SplitCamelCase(), Value = nameof(WrittenContentType.Manga) },
- new ComboboxItem{ Text = nameof(WrittenContentType.GraphicNovel).SplitCamelCase(), Value = nameof(WrittenContentType.GraphicNovel) },
- new ComboboxItem{ Text = nameof(WrittenContentType.AcademicPaper).SplitCamelCase(), Value = nameof(WrittenContentType.AcademicPaper) },
- new ComboboxItem{ Text = nameof(WrittenContentType.SheetMusic).SplitCamelCase(), Value = nameof(WrittenContentType.SheetMusic) },
- new ComboboxItem{ Text = nameof(WrittenContentType.Screenplay).SplitCamelCase(), Value = nameof(WrittenContentType.Screenplay) },
- new ComboboxItem{ Text = nameof(LibraryType.VideoContent).SplitCamelCase(), IsEnabled = false },
- new ComboboxItem{ Text = nameof(VideoContentType.TvShow).SplitCamelCase(), Value = nameof(VideoContentType.TvShow) },
- new ComboboxItem{ Text = nameof(VideoContentType.Movie).SplitCamelCase(), Value = nameof(VideoContentType.Movie) },
- new ComboboxItem{ Text = nameof(VideoContentType.FilmSeries).SplitCamelCase(), Value = nameof(VideoContentType.FilmSeries) },
- new ComboboxItem{ Text = nameof(VideoContentType.FilmFranchise).SplitCamelCase(), Value = nameof(VideoContentType.FilmFranchise) },
- new ComboboxItem{ Text = nameof(VideoContentType.Concert).SplitCamelCase(), Value = nameof(VideoContentType.Concert) },
- new ComboboxItem{ Text = nameof(VideoContentType.Documentary).SplitCamelCase(), Value = nameof(VideoContentType.Documentary) },
- new ComboboxItem{ Text = nameof(VideoContentType.Tutorial).SplitCamelCase(), Value = nameof(VideoContentType.Tutorial) },
- new ComboboxItem{ Text = nameof(VideoContentType.Personal).SplitCamelCase(), Value = nameof(VideoContentType.Personal) },
- new ComboboxItem{ Text = nameof(VideoContentType.Anime).SplitCamelCase(), Value = nameof(VideoContentType.Anime) },
- new ComboboxItem{ Text = nameof(VideoContentType.Youtube).SplitCamelCase(), Value = nameof(VideoContentType.Youtube) },
- new ComboboxItem{ Text = nameof(VideoContentType.Videoclip).SplitCamelCase(), Value = nameof(VideoContentType.Videoclip) },
- new ComboboxItem{ Text = nameof(LibraryType.AudioContent).SplitCamelCase(), IsEnabled = false },
- new ComboboxItem{ Text = nameof(AudioContentType.Music).SplitCamelCase(), Value = nameof(AudioContentType.Music) },
- new ComboboxItem{ Text = nameof(AudioContentType.AudioBook).SplitCamelCase(), Value = nameof(AudioContentType.AudioBook) },
- new ComboboxItem{ Text = nameof(AudioContentType.LivePerformance).SplitCamelCase(), Value = nameof(AudioContentType.LivePerformance) },
- new ComboboxItem{ Text = nameof(AudioContentType.Interview).SplitCamelCase(), Value = nameof(AudioContentType.Interview) },
- new ComboboxItem{ Text = nameof(AudioContentType.Cover).SplitCamelCase(), Value = nameof(AudioContentType.Cover) },
- new ComboboxItem{ Text = nameof(AudioContentType.Remix).SplitCamelCase(), Value = nameof(AudioContentType.Remix) },
- new ComboboxItem{ Text = nameof(AudioContentType.Soundeffect).SplitCamelCase(), Value = nameof(AudioContentType.Soundeffect) },
- new ComboboxItem{ Text = nameof(AudioContentType.Podcast).SplitCamelCase(), Value = nameof(AudioContentType.Podcast) },
- new ComboboxItem{ Text = nameof(AudioContentType.RadioShow).SplitCamelCase(), Value = nameof(AudioContentType.RadioShow) },
- new ComboboxItem{ Text = nameof(LibraryType.VisualContent).SplitCamelCase(), IsEnabled = false },
- new ComboboxItem{ Text = nameof(VisualContentType.PhotoAlbum).SplitCamelCase(), Value = nameof(VisualContentType.PhotoAlbum) },
- new ComboboxItem{ Text = nameof(LibraryType.MiscellaneousContent).SplitCamelCase(), IsEnabled = false },
- new ComboboxItem{ Text = nameof(MiscellaneousContentType.Other).SplitCamelCase(), Value = nameof(MiscellaneousContentType.Other) },
- };
-
- private ComboboxItem? selectedValue;
- private ComboboxItem? selectedValue2;
-
- private bool isSaving = false;
- private bool isCancelling = false;
-
- private async Task SaveData()
- {
- isSaving = true;
- // Perform save operation
- isSaving = false;
- Console.WriteLine("saved");
- await Task.CompletedTask;
- }
-
- private async Task CancelOperation()
- {
- isCancelling = true;
- // Perform cancel operation
- if (!isCancelling)
- isCancelling = false;
- selectedValue2 = new ComboboxItem();
- if (selectedValue2 is not null)
- Console.WriteLine("cancelled");
- await Task.CompletedTask;
- }
-
- private List tableData = new List
- {
- new TableItem { Column1 = "Value 1", Column2 = "Value 2", Directories = new List() },
- new TableItem { Column1 = "Value 3", Column2 = "Value 4", Directories = new List() }
- };
-
- public class TableItem
- {
- public string? Column1 { get; set; }
- public string? Column2 { get; set; }
- public List? Directories { get; set; }
- }
-}
diff --git a/src/Lumina.Presentation.Web/Pages/Library/WrittenContentLibrary/BookLibrary/Books/Index.razor b/src/Lumina.Presentation.Web/Pages/Library/WrittenContentLibrary/BookLibrary/Books/Index.razor
deleted file mode 100644
index 15ac1bde..00000000
--- a/src/Lumina.Presentation.Web/Pages/Library/WrittenContentLibrary/BookLibrary/Books/Index.razor
+++ /dev/null
@@ -1,7 +0,0 @@
-@page "/library/written-content/books-library/books"
-
-
+ Swapping to Development environment will display more detailed information about the error that occurred.
+
+
+ The Development environment shouldn't be enabled for deployed applications.
+ It can result in displaying sensitive information from exceptions to end users.
+ For local debugging, enable the Development environment by setting the ASPNETCORE_ENVIRONMENT environment variable to Development
+ and restarting the app.
+
-
-
-
-
-
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