Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

fix: upload multi files with maxNumberofFiles #247

Merged

Conversation

cycleccc
Copy link
Collaborator

@cycleccc cycleccc commented Oct 12, 2024

Changes Overview

Implementation Approach

Testing Done

Verification Steps

Additional Notes

Checklist

  • I have created a changeset for this PR if necessary.
  • My changes do not break the library.
  • I have added tests where applicable.
  • I have followed the project guidelines.
  • I have fixed any lint issues.

Related Issues

Summary by CodeRabbit

  • New Features

    • Added an autoProceed option for file uploads, allowing users to control when uploads start.
    • Updated demo to support a new repository for image uploads.
    • Enhanced file upload functionality to support multiple file uploads at once for both images and videos.
  • Bug Fixes

    • Improved handling of file uploads to ensure all selected files are processed correctly.

Copy link

changeset-bot bot commented Oct 12, 2024

⚠️ No Changeset found

Latest commit: 80b7b3e

Merging this PR will not cause a version bump for any packages. If these changes should not result in a new version, you're good to go. If these changes should result in a version bump, you need to add a changeset.

Click here to learn what changesets are, and how to add one.

Click here if you're a maintainer who wants to add a changeset to this PR

Copy link
Contributor

coderabbitai bot commented Oct 12, 2024

Walkthrough

The changes involve modifications to several files related to file uploading functionality. The createUploader function now includes an autoProceed option set to false, preventing automatic uploads. The HTML example for image uploads updates a hyperlink and adds a configuration option for maximum file uploads. The upload-images.ts and upload-videos.ts files' uploadFile functions have been altered to accept arrays of files, facilitating batch uploads for both images and videos. Additionally, test files have been updated to reflect these changes.

Changes

File Path Change Summary
packages/core/src/upload/createUploader.ts Added autoProceed: false to Uppy instance configuration; no change in method signature.
packages/editor/examples/upload-image.html Updated hyperlink to a new repository; added maxNumberOfFiles option to editorConfig.
packages/upload-image-module/src/module/upload-images.ts Changed uploadFile to accept an array of File objects; modified logic to handle multiple files for upload.
packages/video-module/src/module/helper/upload-videos.ts Changed uploadFile to accept an array of File objects; modified logic to handle multiple files for upload.
packages/upload-image-module/__tests__/upload-files.test.ts Enhanced mock uploader with addFiles method; updated test cases for uploadImages function.

Poem

In the meadow where uploads play,
A rabbit hops, hip-hip-hooray!
With files in tow, they gather round,
New paths to share, new joys abound.
Auto-upload? Not today!
Let's choose our files and hop away! 🐇✨


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 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
Contributor

@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: 3

📜 Review details

Configuration used: CodeRabbit UI
Review profile: CHILL

📥 Commits

Files that changed from the base of the PR and between 1809d35 and afc4696.

📒 Files selected for processing (3)
  • packages/core/src/upload/createUploader.ts (1 hunks)
  • packages/editor/examples/upload-image.html (3 hunks)
  • packages/upload-image-module/src/module/upload-images.ts (3 hunks)
🧰 Additional context used
🔇 Additional comments (5)
packages/core/src/upload/createUploader.ts (2)

Line range hint 1-124: Overall assessment: The change improves upload control

The modification to set autoProceed: false in the Uppy configuration is the only change in this file. This alteration aligns well with the PR objective of managing multiple file uploads and enforcing a maximum limit. It provides better control over the upload process, which is particularly useful when dealing with multiple files.

The rest of the file remains unchanged, maintaining its existing functionality for error handling, progress tracking, and success callbacks. This focused change minimizes the risk of introducing new issues while achieving the desired improvement in upload control.

To ensure a smooth integration, it's recommended to review any code that directly uses the createUploader function or Uppy's upload methods, as they might need adjustments to manually trigger uploads now that autoProceed is set to false.


58-58: Approve the addition of autoProceed: false

The addition of autoProceed: false to the Uppy configuration is a good change. This prevents automatic file uploads as soon as they are added, which aligns with the PR objective of controlling the upload of multiple files.

This change gives more control to the user interface, allowing for better management of file uploads, especially when dealing with multiple files and enforcing a maximum limit.

To ensure this change doesn't negatively impact the existing codebase, let's verify its usage:

✅ Verification successful

Verified Addition of autoProceed: false

The addition of autoProceed: false to the Uppy configuration has been thoroughly verified across the codebase. No instances were found where this change conflicts with existing usages or disrupts the upload functionality.

🏁 Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Description: Check for any direct calls to `createUploader` that might be affected by this change

# Test: Search for createUploader calls
echo "Searching for createUploader calls:"
rg --type typescript "createUploader\(" -A 5

# Test: Search for Uppy's upload method calls, which might need to be triggered manually now
echo "Searching for Uppy upload method calls:"
rg --type typescript "\.upload\(" -A 5

Length of output: 327


Script:

#!/bin/bash
# Description: Check for any direct calls to `createUploader` that might be affected by this change

# Test: Search for createUploader calls in TypeScript files
echo "Searching for createUploader calls in .ts and .tsx files:"
rg "createUploader\(" -g "*.ts" -g "*.tsx" -A 5

# Test: Search for Uppy's upload method calls in TypeScript files
echo "Searching for Uppy upload method calls in .ts and .tsx files:"
rg "\.upload\(" -g "*.ts" -g "*.tsx" -A 5

Length of output: 10717

packages/editor/examples/upload-image.html (3)

Line range hint 1-124: Summary of changes and alignment with PR objectives.

The changes in this file are minimal and align well with the PR objectives:

  1. The server repository URL has been updated, which may be related to the implementation of the new file upload functionality.
  2. A commented-out maxNumberOfFiles option has been added, directly addressing the objective of limiting the number of files that can be uploaded.

These changes seem to be on track with the PR's goal of fixing multi-file uploads with a maximum file limit. However, please ensure that:

  1. The new server repository is properly set up and documented.
  2. The maxNumberOfFiles feature is fully implemented, tested, and documented before being uncommented.

53-53: Clarify the purpose of the commented-out maxNumberOfFiles option.

A new configuration option maxNumberOfFiles has been added but is currently commented out. This aligns with the PR objective of addressing functionality related to uploading multiple files with a maximum limit. Please clarify:

  1. Is this a new feature that's not yet fully implemented or tested?
  2. Is it meant to be an optional configuration that users can uncomment as needed?
  3. If it's a new feature, has documentation been updated to explain its usage and implications?

Consider adding a comment explaining the purpose and usage of this option, especially if it's a new feature. For example:

// Uncomment and set the value to limit the number of files that can be uploaded
// maxNumberOfFiles: 2,

To check if this option is used elsewhere in the codebase:

#!/bin/bash
# Description: Search for usage of maxNumberOfFiles in the codebase

# Test: Search for maxNumberOfFiles in all files
rg --type-add 'web:*.{html,js,ts}' --type web 'maxNumberOfFiles'

19-19: Verify the repository change and its implications.

The hyperlink has been updated from the original wangeditor-team server repository to a new repository under cycleccc. Please confirm:

  1. Is this change intentional?
  2. Does the new repository contain the necessary server-side functionality?
  3. Are there any implications for users who might be relying on the original repository?

To check if the new repository exists and contains the expected content:

Copy link
Contributor

@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: 1

📜 Review details

Configuration used: CodeRabbit UI
Review profile: CHILL

📥 Commits

Files that changed from the base of the PR and between afc4696 and 26164e3.

📒 Files selected for processing (1)
  • packages/upload-image-module/src/module/upload-images.ts (3 hunks)
🧰 Additional context used
🔇 Additional comments (2)
packages/upload-image-module/src/module/upload-images.ts (2)

130-139: Ensure uploadFile handles empty file arrays to prevent errors

As previously noted, calling uppy.addFiles(uploadList) with an empty uploadList may cause unexpected behavior. Consider adding a check at the start of the uploadFile function to return early if files.length === 0.

This ensures that the function behaves correctly even when an empty array is passed.


173-175: Good practice: Checking for files before uploading

Adding the condition if (uploadFiles.length > 0) before calling uploadFile is a smart move. It prevents unnecessary function calls and potential errors when there are no files to upload.

Copy link
Contributor

@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: 2

🧹 Outside diff range and nitpick comments (3)
packages/upload-image-module/__tests__/upload-files.test.ts (2)

61-61: LGTM! Consider enhancing test coverage.

The addition of the addFiles method to the mock uploader object is a good change. It aligns with the PR objective of supporting multi-file uploads and makes the mock more accurately represent the expected uploader interface.

Consider adding a new test case that specifically verifies the behavior of the addFiles method to ensure it's used correctly in the uploadImages function. This would improve the test coverage for the new multi-file upload functionality.


Line range hint 1-74: Suggest adding a new test case for multi-file uploads

While the addition of the addFiles method to the mock uploader is a good start, it would be beneficial to add a new test case that specifically verifies the behavior of the uploadImages function when multiple files are provided. This would ensure that the new multi-file upload functionality is working as expected.

Consider adding a test case similar to the following:

test('uploadImages should handle multiple files correctly', async () => {
  const editor = createEditor()
  const mockUploader = {
    addFiles: vi.fn(),
    upload: vi.fn(),
  }
  vi.spyOn(core, 'createUploader').mockReturnValue(mockUploader as any)

  const files = [mockFile('test1.jpg'), mockFile('test2.jpg')] as unknown as FileList
  await uploadImages(editor, files)

  expect(mockUploader.addFiles).toHaveBeenCalledWith(files)
  expect(mockUploader.upload).toHaveBeenCalled()
})

This test would verify that the uploadImages function correctly handles multiple files and uses the new addFiles method of the uploader.

packages/upload-image-module/src/module/upload-images.ts (1)

Line range hint 155-173: LGTM: Main function updated to handle multiple file uploads efficiently.

The changes correctly implement batch file uploading and address the previous comment about avoiding unnecessary function calls.

For improved clarity, consider using Array.prototype.filter() to create uploadFileList:

-const uploadFileList : File[] = []
+const uploadFileList = fileList.filter(file => {
+  const size = file.size
+  if (base64LimitSize && size <= base64LimitSize) {
+    insertBase64(editor, file)
+    return false
+  }
+  if (customUpload) {
+    customUpload(file, (src, alt, href) => insertImageNode(editor, src, alt, href))
+    return false
+  }
+  return true
+})

-for await (const file of fileList) {
-  const size = file.size // size kb
-
-  if (base64LimitSize && size <= base64LimitSize) {
-    // 允许 base64 ,而且 size 在 base64 限制之内,则插入 base64 格式
-    await insertBase64(editor, file)
-  } else if (customUpload) {
-    // 自定义上传
-    await customUpload(file, (src, alt, href) => insertImageNode(editor, src, alt, href))
-  } else {
-    // 默认上传
-    uploadFileList.push(file)
-  }
-}

if (uploadFileList.length > 0) { await uploadFile(editor, uploadFileList) }

This approach simplifies the logic and makes the code more declarative.

📜 Review details

Configuration used: CodeRabbit UI
Review profile: CHILL

📥 Commits

Files that changed from the base of the PR and between 26164e3 and 446fb33.

📒 Files selected for processing (3)
  • packages/upload-image-module/tests/upload-files.test.ts (1 hunks)
  • packages/upload-image-module/src/module/upload-images.ts (3 hunks)
  • packages/video-module/src/module/helper/upload-videos.ts (2 hunks)
🧰 Additional context used
🔇 Additional comments (2)
packages/upload-image-module/src/module/upload-images.ts (1)

130-130: LGTM: Function signature updated to support multiple file uploads.

The change from file: File to files: File[] aligns with the PR objective of handling multiple file uploads.

As mentioned in a previous review, please ensure all calls to uploadFile in the codebase have been updated to pass an array of files. Run the following script to verify:

✅ Verification successful

All uploadFile calls correctly pass arrays of files.

  • Verified that uploadFileList is declared as File[] in both upload-images.ts and upload-videos.ts.
🏁 Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Find all calls to `uploadFile` in TypeScript files
rg --type ts -A 2 'uploadFile\('

Length of output: 1045


Script:

#!/bin/bash
# Find declarations of `uploadFileList` in TypeScript files within the specified modules
rg --type ts 'uploadFileList\s*:\s*File\[\]' packages/upload-image-module/src/module/upload-images.ts packages/video-module/src/module/helper/upload-videos.ts

Length of output: 348

packages/video-module/src/module/helper/upload-videos.ts (1)

96-96: Verify all usages of uploadFile have been updated to accept an array of files

The uploadFile function signature has changed to accept an array of File objects. Ensure that all calls to uploadFile within the codebase are updated to match the new signature to prevent any runtime errors.

Use the following script to find all usages of uploadFile:

✅ Verification successful

All usages of uploadFile have been updated successfully

  • Verified that all calls to uploadFile in the codebase now accept an array of files.
🏁 Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Description: Find all calls to `uploadFile` to verify they use the updated signature.

rg --type ts 'uploadFile\(' -A 2

Length of output: 1045

@cycleccc cycleccc force-pushed the 6-bug-上传图片或视频maxnumberoffiles不起作用 branch from 446fb33 to 80b7b3e Compare October 14, 2024 15:26
Copy link
Contributor

@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: 1

🧹 Outside diff range and nitpick comments (2)
packages/video-module/src/module/helper/upload-videos.ts (1)

127-128: Efficient batch upload implementation

The addition of the check for non-empty uploadFileList before calling uploadFile is a good practice. It ensures that the default upload method is only invoked when there are actually files to upload.

Consider using optional chaining for a slightly more concise implementation:

- if (uploadFileList.length > 0) { await uploadFile(editor, uploadFileList) }
+ uploadFileList.length && await uploadFile(editor, uploadFileList);

This change is optional and doesn't affect functionality, but it might align better with modern JavaScript practices.

packages/upload-image-module/src/module/upload-images.ts (1)

132-139: LGTM: Function body updated to handle multiple files.

The changes correctly implement the logic for handling multiple file uploads. However, consider adding a unique id to each file object for better tracking in Uppy:

 const uploadList = files.map((file, index) => ({
+  id: `${file.name}_${Date.now()}_${index}`,
   name: file.name,
   type: file.type,
   size: file.size,
   data: file,
 }))

This modification ensures that each file has a unique id, which can be beneficial for Uppy's internal file tracking and potential debugging.

📜 Review details

Configuration used: CodeRabbit UI
Review profile: CHILL

📥 Commits

Files that changed from the base of the PR and between 446fb33 and 80b7b3e.

📒 Files selected for processing (4)
  • packages/editor/examples/upload-image.html (3 hunks)
  • packages/upload-image-module/tests/upload-files.test.ts (1 hunks)
  • packages/upload-image-module/src/module/upload-images.ts (3 hunks)
  • packages/video-module/src/module/helper/upload-videos.ts (2 hunks)
🚧 Files skipped from review as they are similar to previous changes (2)
  • packages/editor/examples/upload-image.html
  • packages/upload-image-module/tests/upload-files.test.ts
🧰 Additional context used
🔇 Additional comments (3)
packages/video-module/src/module/helper/upload-videos.ts (1)

Line range hint 113-124: Improved flexibility in upload handling

The changes in this section enhance the upload process by introducing more flexibility. The new uploadFileList array and the conditional logic for custom uploads allow for a more versatile approach to handling file uploads. This implementation supports both custom and default upload methods effectively.

packages/upload-image-module/src/module/upload-images.ts (2)

Line range hint 155-173: LGTM: Main function updated to handle multiple file uploads.

The changes correctly implement the logic for handling multiple file uploads, addressing different scenarios such as base64 encoding, custom uploads, and default uploads.

I notice that you've implemented the suggestion from a previous review to avoid calling uploadFile when there are no files to upload:

if (uploadFileList.length > 0) { await uploadFile(editor, uploadFileList) }

This is a good practice to prevent unnecessary function calls.


130-130: LGTM: Function signature updated to handle multiple files.

The change from file: File to files: File[] allows for processing multiple files in a single call, which is a good improvement in functionality.

Please ensure that all calls to uploadFile across the codebase have been updated to pass an array of files. Run the following script to identify any outdated calls:

✅ Verification successful

Verified: All uploadFile calls have been updated to accept an array of files.

🏁 Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Description: Find all calls to `uploadFile` in TypeScript files
rg --type ts 'uploadFile\(' -A 2

Length of output: 1045

Comment on lines +96 to +105
async function uploadFile(editor: IDomEditor, files: File[]) {
const uppy = getUppy(editor)

const { name, type, size } = file

uppy.addFile({
name,
type,
size,
const uploadList = files.map(file => ({
name: file.name,
type: file.type,
size: file.size,
data: file,
})
}))

uppy.addFiles(uploadList)
Copy link
Contributor

Choose a reason for hiding this comment

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

⚠️ Potential issue

Improved batch upload functionality, but consider resetting Uppy instance

The changes to uploadFile function improve its functionality by allowing batch uploads of multiple files. This is a good enhancement that increases efficiency.

However, the previous review comment about resetting the Uppy instance before adding new files is still relevant and should be addressed to prevent potential issues with residual uploads.

Consider applying this diff to reset the Uppy instance before adding new files:

 async function uploadFile(editor: IDomEditor, files: File[]) {
   const uppy = getUppy(editor)
+  uppy.reset()
   const uploadList = files.map(file => ({
     name: file.name,
     type: file.type,
     size: file.size,
     data: file,
   }))
   uppy.addFiles(uploadList)
   await uppy.upload()
 }
📝 Committable suggestion

‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.

Suggested change
async function uploadFile(editor: IDomEditor, files: File[]) {
const uppy = getUppy(editor)
const { name, type, size } = file
uppy.addFile({
name,
type,
size,
const uploadList = files.map(file => ({
name: file.name,
type: file.type,
size: file.size,
data: file,
})
}))
uppy.addFiles(uploadList)
async function uploadFile(editor: IDomEditor, files: File[]) {
const uppy = getUppy(editor)
uppy.reset()
const uploadList = files.map(file => ({
name: file.name,
type: file.type,
size: file.size,
data: file,
}))
uppy.addFiles(uploadList)

@cycleccc cycleccc merged commit c6fa96e into master Oct 14, 2024
2 checks passed
@coderabbitai coderabbitai bot mentioned this pull request Oct 21, 2024
5 tasks
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.

Bug : 上传图片或视频maxNumberofFiles不起作用(已在wangEditor-next 解决)
1 participant