Skip to content

Add Append parameter to BitFileUpload component (#1562)#9887

Merged
msynk merged 2 commits intobitfoundation:developfrom
Cyrus-Sushiant:1562-add-appended-feature-bitfileupload
Feb 13, 2025
Merged

Add Append parameter to BitFileUpload component (#1562)#9887
msynk merged 2 commits intobitfoundation:developfrom
Cyrus-Sushiant:1562-add-appended-feature-bitfileupload

Conversation

@Cyrus-Sushiant
Copy link
Member

@Cyrus-Sushiant Cyrus-Sushiant commented Feb 13, 2025

This closes #1562

Summary by CodeRabbit

  • New Features

    • Added an option that allows users to append files to the current upload list without replacing previously selected items. This enhancement improves file management and ensures smoother, more consistent upload operations with accurate progress and control features.
  • Documentation

    • Updated the demo and section organization to better distinguish between appending functionality and file size limitations, resulting in clearer and more user-friendly demonstrations.

@coderabbitai
Copy link

coderabbitai bot commented Feb 13, 2025

Important

Review skipped

Auto incremental reviews are disabled on this repository.

Please check the settings in the CodeRabbit UI or the .coderabbit.yaml file in this repository. To trigger a single review, invoke the @coderabbitai review command.

You can disable this status message by setting the reviews.review_status to false in the CodeRabbit configuration file.

Walkthrough

This update revises the file upload functionality in both Blazor and JavaScript parts. The BitFileUpload component now maintains an internal _files list instead of using a nullable property and introduces a new Appended parameter to control whether new files replace or append to the existing list. Corresponding changes were made to methods handling uploads, JavaScript setup functions, and demo pages where sections have been renamed and reorganized to reflect the new parameter.

Changes

File(s) Change Summary
src/BlazorUI/.../BitFileUpload.razor.cs Added a private _files field; updated the Files property to always return _files; introduced a public Appended parameter; modified file management methods (Upload, PauseUpload, CancelUpload, RemoveFile, Reset, HandleOnChange) to use the new _files list.
src/BlazorUI/.../BitFileUpload.ts Added an appended parameter to the setup method; updated the BitFileUploader constructor to accept a File instead of an input element; adjusted file indexing and mapping by incorporating the appended state.
src/BlazorUI/.../BitFileUploadJsRuntimeExtensions.cs Added an appended parameter to the BitFileUploadSetup method and updated the JavaScript function invocation accordingly.
src/BlazorUI/Demo/.../BitFileUploadDemo.razor
src/BlazorUI/Demo/.../BitFileUploadDemo.razor.cs
Renamed and reorganized demo sections (introducing an "Appended" section and adding a "MaxSize" section); added a new Appended parameter to the demo component; updated example usages to reflect the revised parameter structure.

Sequence Diagram(s)

sequenceDiagram
    participant U as User
    participant C as BitFileUpload Component
    participant JS as JavaScript Uploader

    U->>C: Select files
    C->>C: Check Appended parameter
    alt Appended is false
        C->>C: Clear _files list
    end
    C->>C: Append new files to _files
    C->>JS: Invoke setup with appended flag
    JS->>JS: Update file indexing & uploader queue
    JS->>C: Return upload progress/status
Loading

Poem

I'm a rabbit hopping through lines of code so neat,
With _files and Appended, my uploads are complete.
Each file joins the dance in a playful, merry way,
While demo pages chirp and showcase the display.
Hopping on the keys with joy and plenty of cheer,
I celebrate these changes—oh, my code is clear!
🐇✨


Thank you for using CodeRabbit. We offer it for free to the OSS community and would appreciate your support in helping us grow. If you find it useful, would you consider giving us a shout-out on your favorite social media?

❤️ Share
🪧 Tips

Chat

There are 3 ways to chat with CodeRabbit:

  • Review comments: Directly reply to a review comment made by CodeRabbit. Example:
    • I pushed a fix in commit <commit_id>, please review it.
    • Generate unit testing code for this file.
    • Open a follow-up GitHub issue for this discussion.
  • Files and specific lines of code (under the "Files changed" tab): Tag @coderabbitai in a new review comment at the desired location with your query. Examples:
    • @coderabbitai generate unit testing code for this file.
    • @coderabbitai modularize this function.
  • PR comments: Tag @coderabbitai in a new PR comment to ask questions about the PR branch. For the best results, please provide a very specific query, as very limited context is provided in this mode. Examples:
    • @coderabbitai gather interesting stats about this repository and render them as a table. Additionally, render a pie chart showing the language distribution in the codebase.
    • @coderabbitai read src/utils.ts and generate unit testing code.
    • @coderabbitai read the files in the src/scheduler package and generate a class diagram using mermaid and a README in the markdown format.
    • @coderabbitai help me debug CodeRabbit configuration file.

Note: Be mindful of the bot's finite context window. It's strongly recommended to break down tasks such as reading entire modules into smaller chunks. For a focused discussion, use review comments to chat about specific files and their changes, instead of using the PR comments.

CodeRabbit Commands (Invoked using PR comments)

  • @coderabbitai pause to pause the reviews on a PR.
  • @coderabbitai resume to resume the paused reviews.
  • @coderabbitai review to trigger an incremental review. This is useful when automatic reviews are disabled for the repository.
  • @coderabbitai full review to do a full review from scratch and review all the files again.
  • @coderabbitai summary to regenerate the summary of the PR.
  • @coderabbitai generate docstrings to generate docstrings for this PR. (Beta)
  • @coderabbitai resolve resolve all the CodeRabbit review comments.
  • @coderabbitai configuration to show the current CodeRabbit configuration for the repository.
  • @coderabbitai help to get help.

Other keywords and placeholders

  • Add @coderabbitai ignore anywhere in the PR description to prevent this PR from being reviewed.
  • Add @coderabbitai summary to generate the high-level summary at a specific location in the PR description.
  • Add @coderabbitai anywhere in the PR title to generate the title automatically.

CodeRabbit Configuration File (.coderabbit.yaml)

  • You can programmatically configure CodeRabbit by adding a .coderabbit.yaml file to the root of your repository.
  • Please see the configuration documentation for more information.
  • If your editor has YAML language server enabled, you can add the path at the top of this file to enable auto-completion and validation: # yaml-language-server: $schema=https://coderabbit.ai/integrations/schema.v2.json

Documentation and Community

  • Visit our Documentation for detailed information on how to use CodeRabbit.
  • Join our Discord Community to get help, request features, and share feedback.
  • Follow us on X/Twitter for updates and announcements.

Copy link

@coderabbitai coderabbitai bot left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Actionable comments posted: 0

🧹 Nitpick comments (8)
src/BlazorUI/Bit.BlazorUI/Components/Inputs/FileUpload/BitFileUpload.ts (3)

17-25: Consider adding validation for file uniqueness.

When appending files, there's no check to prevent duplicate files from being added. Consider adding validation to prevent duplicates based on file name or content.

 const lastIndex = appended ? FileUpload._fileUploaders.length : 0;
 const files = Array.from(inputElement.files!).map((file, index) => ({
     name: file.name,
     size: file.size,
     type: file.type,
     fileId: Utils.uuidv4(),
     file: file,
     index: (index + lastIndex)
 }));
+
+// Add duplicate check when appending
+if (appended) {
+    const existingFileNames = FileUpload._fileUploaders.map(u => u.file.name);
+    files = files.filter(f => !existingFileNames.includes(f.name));
+}

33-34: Consider moving input reset.

The input reset could be moved before the file processing to prevent potential memory issues with large files.

-const files = Array.from(inputElement.files!).map((file, index) => ({
+// Reset input early to free up memory
+const selectedFiles = Array.from(inputElement.files!);
+inputElement.value = '';
+
+const files = selectedFiles.map((file, index) => ({
     name: file.name,
     size: file.size,
     type: file.type,
     fileId: Utils.uuidv4(),
     file: file,
     index: (index + lastIndex)
 }));
-
-inputElement.value = '';

149-152: Consider adding file type validation.

When uploading chunks, consider validating the file type before processing to prevent potential security issues.

 upload(from: number, to: number, uploadUrl: string, headers: Record<string, string>): void {
     const file = this.file;
     if (file === null) return;
+
+    // Validate file type before upload
+    const allowedTypes = ['image/jpeg', 'image/png', 'application/pdf'];
+    if (!allowedTypes.includes(file.type)) {
+        console.error('Invalid file type:', file.type);
+        return;
+    }
src/BlazorUI/Bit.BlazorUI/Components/Inputs/FileUpload/BitFileUpload.razor.cs (3)

41-44: Consider improving parameter documentation.

The documentation for the Appended parameter could be more detailed to explain the behavior and use cases.

     /// <summary>
-    /// Additional files are selected they will be appended to the existing list.
+    /// When set to true, newly selected files will be appended to the existing list instead of replacing them.
+    /// This is useful when you want to allow users to add more files to their current selection.
+    /// Default value is false, which means new selections will replace existing files.
     /// </summary>

437-456: Consider adding file count validation.

The HandleOnChange method should validate the total number of files when appending to prevent potential memory issues.

     private async Task HandleOnChange()
     {
         var url = AddQueryString(UploadUrl, UploadRequestQueryStrings);
 
         if (Appended is false)
         {
             _files.Clear();
         }
+        else
+        {
+            const int maxTotalFiles = 100; // Consider making this configurable
+            if (_files.Count >= maxTotalFiles)
+            {
+                // Consider adding an OnError event to handle this case
+                return;
+            }
+        }
 
         _files.AddRange(await _js.BitFileUploadSetup(UniqueId, _dotnetObj, _inputRef, Appended, url, UploadRequestHttpHeaders));

519-527: Consider adding cancellation token support.

Long-running operations like file uploads should support cancellation tokens for better resource management.

-    private async Task PauseUploadOneFile(int index)
+    private async Task PauseUploadOneFile(int index, CancellationToken cancellationToken = default)
     {
         if (_files.Any() is false) return;
 
-        await _js.BitFileUploadPause(UniqueId, index);
+        await _js.BitFileUploadPause(UniqueId, index).WaitAsync(cancellationToken);
         var file = _files[index];
-        await UpdateStatus(BitFileUploadStatus.Paused, file);
+        await UpdateStatus(BitFileUploadStatus.Paused, file).WaitAsync(cancellationToken);
         file.PauseUploadRequested = false;
     }
src/BlazorUI/Demo/Client/Bit.BlazorUI.Demo.Client.Core/Pages/Components/Inputs/FileUpload/BitFileUploadDemo.razor.cs (2)

22-27: Improve the parameter description for clarity.

The description of the Appended parameter could be more precise and grammatically correct.

-            Description = "Additional files are selected they will be appended to the existing list."
+            Description = "When true, additional selected files will be appended to the existing list instead of replacing them."

584-584: Improve readability of the MaxSize value.

The hardcoded value 1024 * 1024 * 1 could be more readable with a comment indicating the size in MB.

-<BitFileUpload Label="Select or drag and drop files" UploadUrl="@UploadUrl" MaxSize="1024 * 1024 * 1" />
+<BitFileUpload Label="Select or drag and drop files" UploadUrl="@UploadUrl" MaxSize="1024 * 1024 * 1" @* 1MB *@ />
📜 Review details

Configuration used: CodeRabbit UI
Review profile: CHILL
Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between cc729eb and a0fbba4.

📒 Files selected for processing (5)
  • src/BlazorUI/Bit.BlazorUI/Components/Inputs/FileUpload/BitFileUpload.razor.cs (17 hunks)
  • src/BlazorUI/Bit.BlazorUI/Components/Inputs/FileUpload/BitFileUpload.ts (3 hunks)
  • src/BlazorUI/Bit.BlazorUI/Components/Inputs/FileUpload/BitFileUploadJsRuntimeExtensions.cs (1 hunks)
  • src/BlazorUI/Demo/Client/Bit.BlazorUI.Demo.Client.Core/Pages/Components/Inputs/FileUpload/BitFileUploadDemo.razor (3 hunks)
  • src/BlazorUI/Demo/Client/Bit.BlazorUI.Demo.Client.Core/Pages/Components/Inputs/FileUpload/BitFileUploadDemo.razor.cs (4 hunks)
⏰ Context from checks skipped due to timeout of 90000ms (1)
  • GitHub Check: build and test
🔇 Additional comments (10)
src/BlazorUI/Bit.BlazorUI/Components/Inputs/FileUpload/BitFileUploadJsRuntimeExtensions.cs (1)

12-12: LGTM!

The changes correctly integrate the new appended parameter into the BitFileUploadSetup method and its JavaScript invocation.

Also applies to: 16-16

src/BlazorUI/Bit.BlazorUI/Components/Inputs/FileUpload/BitFileUpload.ts (3)

9-15: LGTM: Clear implementation of appended mode.

The conditional clearing of existing uploaders based on the appended parameter is well-implemented.


27-31: LGTM: Clean uploader creation.

The creation of uploaders with the new file reference is well-implemented.


118-118: LGTM: Improved file handling in BitFileUploader.

The change from storing inputElement to storing the File object directly is a good improvement that simplifies the code and reduces dependencies.

Also applies to: 125-131

src/BlazorUI/Bit.BlazorUI/Components/Inputs/FileUpload/BitFileUpload.razor.cs (1)

18-18: LGTM: Improved file state management.

Using a non-nullable list with collection expression syntax is a good choice for maintaining file state.

src/BlazorUI/Demo/Client/Bit.BlazorUI.Demo.Client.Core/Pages/Components/Inputs/FileUpload/BitFileUploadDemo.razor.cs (1)

503-549: LGTM! Well-structured implementation with proper error handling.

The helper methods for calculating upload progress, file size, and handling file type validation are well-implemented with proper edge case handling.

src/BlazorUI/Demo/Client/Bit.BlazorUI.Demo.Client.Core/Pages/Components/Inputs/FileUpload/BitFileUploadDemo.razor (4)

35-38: LGTM! Clear demonstration of the new Appended feature.

The new demo section effectively showcases the Appended feature with a clear description and straightforward example.


40-43: LGTM! MaxSize section properly maintained.

The MaxSize section has been correctly preserved with its functionality intact while being renumbered to accommodate the new Appended section.


45-164: LGTM! Sections properly renumbered.

All subsequent sections have been systematically renumbered while preserving their original content and functionality.


35-164:

Details

❓ Verification inconclusive

Verify code-behind references.

Please ensure that the code-behind file (BitFileUploadDemo.razor.cs) has been updated with the corresponding example code references (example5RazorCode, example5CsharpCode, etc.) for the new and renumbered sections.


🏁 Script executed:

#!/bin/bash
# Description: Check for example code references in the code-behind file

# Search for example code references
rg -A 1 'example[0-9]+[RC]azorCode' src/BlazorUI/Demo/Client/Bit.BlazorUI.Demo.Client.Core/Pages/Components/Inputs/FileUpload/BitFileUploadDemo.razor.cs

Length of output: 1945


Verify code-behind references for both Razor and C# code.

We confirmed that the code-behind file (BitFileUploadDemo.razor.cs) contains updated Razor code references for all demo examples (e.g., example5RazorCode through example13RazorCode). Please ensure that the corresponding C# code references (such as example5CsharpCode, etc.) have also been updated and correctly aligned with the new and renumbered sections.

@msynk msynk changed the title Add the Appended feature to BitFileUpload (#1562) Add Append parameter to BitFileUpload component (#1562) Feb 13, 2025
@msynk msynk merged commit d754998 into bitfoundation:develop Feb 13, 2025
3 checks passed
@Cyrus-Sushiant Cyrus-Sushiant deleted the 1562-add-appended-feature-bitfileupload branch March 22, 2025 17:04
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

One by one file adding support in mutiple BitFileUpload

2 participants