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

feat(image-upload): support maxSize and add demos #150

Merged
merged 1 commit into from
Dec 13, 2024

Conversation

kagol
Copy link
Member

@kagol kagol commented Dec 13, 2024

PR

主要更新:

  1. uploadOption 增加 maxSize 属性,以支持图片大小限制
  2. 对外暴露 editor.utils.ts 中的工具函数,方便用户对编辑器有更多的控制
  3. 完善 uploadOption 文档,补充图片格式和大小限制的demo
  4. 补充通过 imageUpload 做图片上传前的校验的demo
  5. 补充 uploadOption 的类型文档

补充 demo 文档:
image

补充 API 文档:
image

PR Checklist

Please check if your PR fulfills the following requirements:

  • The commit message follows our Commit Message Guidelines
  • Tests for the changes have been added (for bug fixes / features)
  • Docs have been added / updated (for bug fixes / features)

PR Type

What kind of change does this PR introduce?

  • Bugfix
  • Feature
  • Code style update (formatting, local variables)
  • Refactoring (no functional changes, no api changes)
  • Build related changes
  • CI related changes
  • Documentation content changes
  • Other... Please describe:

What is the current behavior?

Issue Number: N/A

What is the new behavior?

Does this PR introduce a breaking change?

  • Yes
  • No

Other information

Summary by CodeRabbit

  • New Features

    • Introduced new Vue components for image upload functionality in the Fluent Editor.
    • Added a toolbar configuration for text formatting and image insertion.
    • Implemented validation for image uploads, restricting file types (PNG and GIF) and sizes (maximum 1MB).
  • Documentation

    • Expanded documentation on image upload options, including configuration details and examples.
  • Bug Fixes

    • Enhanced upload handling to ensure files meet type and size criteria before uploading.
  • Refactor

    • Updated the editor configuration interface to improve upload functionality.

@kagol kagol added documentation Improvements or additions to documentation enhancement New feature or request labels Dec 13, 2024
Copy link

coderabbitai bot commented Dec 13, 2024

Warning

Rate limit exceeded

@kagol has exceeded the limit for the number of commits or files that can be reviewed per hour. Please wait 8 minutes and 1 seconds before requesting another review.

⌛ How to resolve this issue?

After the wait time has elapsed, a review can be triggered using the @coderabbitai review command as a PR comment. Alternatively, push new commits to this PR.

We recommend that you space out your commits to avoid hitting the rate limit.

🚦 How do rate limits work?

CodeRabbit enforces hourly rate limits for each developer per organization.

Our paid plans have higher rate limits than the trial, open-source and free plans. In all cases, we re-allow further reviews after a brief timeout.

Please see our FAQ for further information.

📥 Commits

Reviewing files that changed from the base of the PR and between 8d8d3ce and d4dd6fe.

📒 Files selected for processing (6)
  • packages/docs/fluent-editor/demos/image-upload-before-upload.vue (1 hunks)
  • packages/docs/fluent-editor/demos/image-upload-option.vue (1 hunks)
  • packages/docs/fluent-editor/docs/image-upload.md (1 hunks)
  • packages/fluent-editor/src/config/index.ts (1 hunks)
  • packages/fluent-editor/src/config/types/editor-config.interface.ts (1 hunks)
  • packages/fluent-editor/src/custom-uploader.ts (3 hunks)

Walkthrough

This pull request introduces new Vue components for image upload functionality in the Fluent Editor, utilizing TypeScript. It includes two components: one for handling image uploads before they are processed and another for providing upload options. The components implement validation for image types and sizes, specifically allowing PNG and GIF formats with a maximum size of 1MB. Additionally, the documentation has been updated to reflect these changes, and the editor configuration interface has been modified to support the new upload options and callbacks.

Changes

File Path Change Summary
packages/docs/fluent-editor/demos/image-upload-before-upload.vue New Vue component for image upload with validation and toolbar configuration.
packages/docs/fluent-editor/demos/image-upload-option.vue New Vue component for image upload options with callback functions for success and failure.
packages/docs/fluent-editor/docs/image-upload.md Expanded documentation on image upload options and pre-upload hooks, including examples.
packages/fluent-editor/src/config/index.ts Added export statement for editor.utils module.
packages/fluent-editor/src/config/types/editor-config.interface.ts Modified IEditorConfig interface, replacing imageUploadToServer with imageUpload and adding new properties.
packages/fluent-editor/src/custom-uploader.ts Added isAllowedFileSize method and updated upload method to include file validation logic.

Possibly related PRs

  • feat: screenshot #75: Introduces a new Vue component for image upload options, which includes similar image upload functionality and validation checks as the main PR.
  • feat: internal fix screenshot dom display bug #82: This PR modifies the screenshot functionality, including changes to image handling that relate to the image upload process in the main PR.
  • feat: i18n #127: The internationalization (i18n) support introduced in this PR may relate to the user interface aspects of the image upload feature, enhancing usability across different languages.
  • feat: base toolbar tip #128: The addition of tooltips for toolbar icons in this PR complements the new image upload feature by improving user guidance and interaction within the editor.

🐇 In the editor, we now can play,
With images uploaded in a brand new way!
PNGs and GIFs, all within size,
A toolbar to help, oh what a surprise!
With callbacks for success and a fail,
Our image uploads will surely prevail! 🌟


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. (Experiment)
  • @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.

@github-actions github-actions bot removed documentation Improvements or additions to documentation enhancement New feature or request labels Dec 13, 2024
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: 5

🧹 Outside diff range and nitpick comments (6)
packages/fluent-editor/src/config/types/editor-config.interface.ts (1)

17-17: Fix object destructuring spacing

Add spaces within the object destructuring pattern for better readability.

-    imageUpload?: ({ file: File, callback, editor}) => void
+    imageUpload?: ({ file: File, callback, editor }) => void
🧰 Tools
🪛 eslint

[error] 17-17: A space is required before '}'.

(style/object-curly-spacing)


[error] 17-17: A space is required before '}'.

(object-curly-spacing)

packages/docs/fluent-editor/demos/image-upload-option.vue (2)

41-41: Remove empty div element

The empty div element serves no purpose and should be removed.

   <div id="editor-image-upload-option" />
-  <div></div>

24-34: Add trailing commas for better git diffs

Add trailing commas to multiline object literals to reduce git diff noise when new properties are added.

       uploadOption: {
         imageAccept: ['image/png', 'image/gif'],
         maxSize: 1024 * 1024, // 1MB
         success: (file) => {
           showNotification({
             type: 'success',
             message: `Successfully uploaded ${file.name}`
-          })
+          }),
         },
         fail: (file) => {
           showNotification({
             type: 'error',
             message: `Failed to upload ${file.name}`
-          })
+          }),
-        }
+        },
-      }
+      },
     })
🧰 Tools
🪛 eslint

[error] 28-28: Unexpected console statement.

(no-console)


[error] 28-28: Extra semicolon.

(style/semi)


[error] 31-31: Unexpected console statement.

(no-console)


[error] 31-31: Extra semicolon.

(style/semi)


[error] 32-33: Missing trailing comma.

(style/comma-dangle)


[error] 32-33: Missing trailing comma.

(comma-dangle)


[error] 33-34: Missing trailing comma.

(style/comma-dangle)


[error] 33-34: Missing trailing comma.

(comma-dangle)

packages/docs/fluent-editor/demos/image-upload-before-upload.vue (1)

56-59: Remove empty div element

The empty div at the end of the template serves no purpose and should be removed.

 <template>
   <div id="editor-image-upload-before-upload" />
-  <div></div>
 </template>
packages/fluent-editor/src/custom-uploader.ts (2)

65-71: Add JSDoc documentation for isAllowedFileSize method

The new method lacks documentation explaining its purpose and parameters.

Add this documentation:

+ /**
+  * Checks if the file size is within the specified limit
+  * @param maxSize - Maximum allowed file size in bytes
+  * @param file - File to check
+  * @returns boolean indicating if the file size is allowed
+  */
  isAllowedFileSize = (maxSize: number, file: File) => {
    if (isNullOrUndefined(maxSize)) {
      return true
    }

    return file.size <= maxSize
  }

167-167: Add trailing comma for consistency

Add a trailing comma to match the project's style guidelines.

-  editor: this.quill
+  editor: this.quill,
🧰 Tools
🪛 eslint

[error] 167-168: Missing trailing comma.

(style/comma-dangle)


[error] 167-168: Missing trailing comma.

(comma-dangle)

📜 Review details

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

📥 Commits

Reviewing files that changed from the base of the PR and between 7f0cbe2 and 4bc9464.

📒 Files selected for processing (6)
  • packages/docs/fluent-editor/demos/image-upload-before-upload.vue (1 hunks)
  • packages/docs/fluent-editor/demos/image-upload-option.vue (1 hunks)
  • packages/docs/fluent-editor/docs/image-upload.md (1 hunks)
  • packages/fluent-editor/src/config/index.ts (1 hunks)
  • packages/fluent-editor/src/config/types/editor-config.interface.ts (1 hunks)
  • packages/fluent-editor/src/custom-uploader.ts (3 hunks)
🧰 Additional context used
🪛 eslint
packages/docs/fluent-editor/demos/image-upload-option.vue

[error] 28-28: Unexpected console statement.

(no-console)


[error] 28-28: Extra semicolon.

(style/semi)


[error] 31-31: Unexpected console statement.

(no-console)


[error] 31-31: Extra semicolon.

(style/semi)


[error] 32-33: Missing trailing comma.

(style/comma-dangle)


[error] 32-33: Missing trailing comma.

(comma-dangle)


[error] 33-34: Missing trailing comma.

(style/comma-dangle)


[error] 33-34: Missing trailing comma.

(comma-dangle)

packages/fluent-editor/src/custom-uploader.ts

[error] 167-168: Missing trailing comma.

(style/comma-dangle)


[error] 167-168: Missing trailing comma.

(comma-dangle)

packages/fluent-editor/src/config/types/editor-config.interface.ts

[error] 17-17: A space is required before '}'.

(style/object-curly-spacing)


[error] 17-17: A space is required before '}'.

(object-curly-spacing)


[error] 21-21: Prefer using the primitive number as a type name, rather than the upper-cased Number.

(ts/no-wrapper-object-types)

packages/docs/fluent-editor/demos/image-upload-before-upload.vue

[error] 27-27: Unexpected console statement.

(no-console)


[error] 27-27: Extra semicolon.

(style/semi)


[error] 30-30: Unexpected console statement.

(no-console)


[error] 30-30: Extra semicolon.

(style/semi)


[error] 35-35: Unexpected console statement.

(no-console)


[error] 35-35: Extra semicolon.

(style/semi)


[error] 38-38: Trailing spaces not allowed.

(style/no-trailing-spaces)


[error] 38-38: Trailing spaces not allowed.

(no-trailing-spaces)


[error] 41-41: Expected parentheses around arrow function argument having a body with curly braces.

(style/arrow-parens)


[error] 45-46: Missing trailing comma.

(style/comma-dangle)


[error] 45-46: Missing trailing comma.

(comma-dangle)


[error] 46-47: Missing trailing comma.

(style/comma-dangle)


[error] 46-47: Missing trailing comma.

(comma-dangle)


[error] 49-50: Missing trailing comma.

(style/comma-dangle)


[error] 49-50: Missing trailing comma.

(comma-dangle)


[error] 50-51: Missing trailing comma.

(style/comma-dangle)


[error] 50-51: Missing trailing comma.

(comma-dangle)

🪛 Biome (1.9.4)
packages/fluent-editor/src/config/types/editor-config.interface.ts

[error] 21-21: Don't use 'Number' as a type.

Use lowercase primitives for consistency.
Safe fix: Use 'number' instead

(lint/complexity/noBannedTypes)

🔇 Additional comments (1)
packages/fluent-editor/src/config/index.ts (1)

36-36: LGTM! Good practice to expose utility functions

Exporting utility functions promotes code reuse and maintainability.

imageAccept?: Array<string>[] | string
fileAccept?: Array<string>[] | string
isVideoPlay?: boolean
maxSize?: Number
Copy link

Choose a reason for hiding this comment

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

🛠️ Refactor suggestion

Use primitive 'number' type instead of 'Number'

Use lowercase primitive types for consistency with TypeScript best practices.

-    maxSize?: Number
+    maxSize?: number
📝 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
maxSize?: Number
maxSize?: number
🧰 Tools
🪛 Biome (1.9.4)

[error] 21-21: Don't use 'Number' as a type.

Use lowercase primitives for consistency.
Safe fix: Use 'number' instead

(lint/complexity/noBannedTypes)

🪛 eslint

[error] 21-21: Prefer using the primitive number as a type name, rather than the upper-cased Number.

(ts/no-wrapper-object-types)

Comment on lines 39 to 47
```typescript
interface uploadOption {
imageUpload?: ({ file: File, callback, editor}) => void
imageAccept?: string[] | string
maxSize?: Number
success?: (file: File) => void
fail?: (file: File) => void
}
```
Copy link

Choose a reason for hiding this comment

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

🛠️ Refactor suggestion

Update API documentation types

The interface definition in the documentation should match the source code:

  1. Use primitive number type instead of Number
  2. Add spaces in the imageUpload parameter destructuring
 interface uploadOption {
-  imageUpload?: ({ file: File, callback, editor}) => void
+  imageUpload?: ({ file: File, callback, editor }) => void
   imageAccept?: string[] | string
-  maxSize?: Number
+  maxSize?: number
   success?: (file: File) => void
   fail?: (file: File) => void
 }

Comment on lines +27 to +32
success: (file) => {
console.log('upload successfully!');
},
fail: (file) => {
console.log('upload failed!');
}
Copy link

Choose a reason for hiding this comment

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

🛠️ Refactor suggestion

Replace console.log with proper user feedback

The success/fail callbacks should provide visual feedback to users instead of logging to console.

Consider using a notification system or status message:

         success: (file) => {
-          console.log('upload successfully!');
+          // Use your UI framework's notification system
+          showNotification({
+            type: 'success',
+            message: `Successfully uploaded ${file.name}`
+          })
         },
         fail: (file) => {
-          console.log('upload failed!');
+          showNotification({
+            type: 'error',
+            message: `Failed to upload ${file.name}`
+          })
         }

Committable suggestion skipped: line range outside the PR's diff.

🧰 Tools
🪛 eslint

[error] 28-28: Unexpected console statement.

(no-console)


[error] 28-28: Extra semicolon.

(style/semi)


[error] 31-31: Unexpected console statement.

(no-console)


[error] 31-31: Extra semicolon.

(style/semi)

Comment on lines 26 to 47
imageUpload: ({ file, editor }) => {
console.log('file', file);

if (file.type === 'image/gif') {
console.log('Do not support uploading images in GIF format.');
return
}

if (file.size > 1024 * 1024) {
console.log('The image size must not exceed 1MB.');
return
}

const range = editor.getSelection()

imageFileToUrl(file).then(imageUrl => {
editor.uploader.insertImageToEditor(range, {
code: 0,
data: {
imageUrl
}
})
})
}
Copy link

Choose a reason for hiding this comment

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

🛠️ Refactor suggestion

Improve error handling and user feedback in imageUpload function

The current implementation has several areas for improvement:

  1. Console.log statements should be replaced with proper error handling
  2. Magic number (1024 * 1024) should be extracted as a constant
  3. Missing type safety for the callback parameters

Consider this implementation:

- imageUpload: ({ file, editor }) => {
+ const MAX_FILE_SIZE = 1024 * 1024; // 1MB
+ imageUpload: ({ file, editor }: { file: File; editor: any }) => {
   if (file.type === 'image/gif') {
-    console.log('Do not support uploading images in GIF format.');
+    throw new Error('GIF format is not supported');
     return
   }

-  if (file.size > 1024 * 1024) {
+  if (file.size > MAX_FILE_SIZE) {
-    console.log('The image size must not exceed 1MB.');
+    throw new Error(`Image size must not exceed ${MAX_FILE_SIZE / (1024 * 1024)}MB`);
     return
   }

Committable suggestion skipped: line range outside the PR's diff.

🧰 Tools
🪛 eslint

[error] 27-27: Unexpected console statement.

(no-console)


[error] 27-27: Extra semicolon.

(style/semi)


[error] 30-30: Unexpected console statement.

(no-console)


[error] 30-30: Extra semicolon.

(style/semi)


[error] 35-35: Unexpected console statement.

(no-console)


[error] 35-35: Extra semicolon.

(style/semi)


[error] 38-38: Trailing spaces not allowed.

(style/no-trailing-spaces)


[error] 38-38: Trailing spaces not allowed.

(no-trailing-spaces)


[error] 41-41: Expected parentheses around arrow function argument having a body with curly braces.

(style/arrow-parens)


[error] 45-46: Missing trailing comma.

(style/comma-dangle)


[error] 45-46: Missing trailing comma.

(comma-dangle)


[error] 46-47: Missing trailing comma.

(style/comma-dangle)


[error] 46-47: Missing trailing comma.

(comma-dangle)

Comment on lines +51 to 59
if (this.isAllowedFileType(accept, file) && this.isAllowedFileSize(uploadOption?.maxSize, file)) {
uploads.push(file)
fileFlags.push(fileFlag)
uploadOption?.success?.(file)
}
else {
rejectFlags[fileType] = true
uploadOption?.fail?.(file)
}
Copy link

Choose a reason for hiding this comment

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

🛠️ Refactor suggestion

Improve type safety and error handling in upload method

The current implementation could benefit from better type safety and error handling:

  1. Optional chaining could lead to silent failures
  2. Success/fail callbacks lack type definitions

Consider this implementation:

- if (this.isAllowedFileType(accept, file) && this.isAllowedFileSize(uploadOption?.maxSize, file)) {
+ if (this.isAllowedFileType(accept, file) && this.isAllowedFileSize(uploadOption?.maxSize ?? Infinity, file)) {
   uploads.push(file)
   fileFlags.push(fileFlag)
-  uploadOption?.success?.(file)
+  uploadOption?.success?.(file as File)
 } else {
   rejectFlags[fileType] = true
-  uploadOption?.fail?.(file)
+  uploadOption?.fail?.(file as File)
 }
📝 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
if (this.isAllowedFileType(accept, file) && this.isAllowedFileSize(uploadOption?.maxSize, file)) {
uploads.push(file)
fileFlags.push(fileFlag)
uploadOption?.success?.(file)
}
else {
rejectFlags[fileType] = true
uploadOption?.fail?.(file)
}
if (this.isAllowedFileType(accept, file) && this.isAllowedFileSize(uploadOption?.maxSize ?? Infinity, file)) {
uploads.push(file)
fileFlags.push(fileFlag)
uploadOption?.success?.(file as File)
}
else {
rejectFlags[fileType] = true
uploadOption?.fail?.(file as File)
}

@kagol kagol force-pushed the kagol/image-upload-support-max-size branch from 4bc9464 to 8d8d3ce Compare December 13, 2024 09:35
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: 1

🧹 Outside diff range and nitpick comments (5)
packages/fluent-editor/src/config/types/editor-config.interface.ts (1)

21-23: Add JSDoc comments for new properties

The new properties would benefit from documentation explaining their purpose and usage.

+    /** Maximum allowed file size in bytes */
     maxSize?: number
+    /** Callback invoked when file upload succeeds */
     success?: (file: File) => void
+    /** Callback invoked when file upload fails */
     fail?: (file: File) => void
🧰 Tools
🪛 Biome (1.9.4)

[error] 21-21: Don't use 'Number' as a type.

Use lowercase primitives for consistency.
Safe fix: Use 'number' instead

(lint/complexity/noBannedTypes)

🪛 eslint

[error] 21-21: Prefer using the primitive number as a type name, rather than the upper-cased Number.

(ts/no-wrapper-object-types)

packages/docs/fluent-editor/demos/image-upload-option.vue (1)

40-42: Remove empty div element

The empty div at the end of the template serves no purpose and should be removed.

 <template>
   <div id="editor-image-upload-option" />
-  <div></div>
 </template>
packages/docs/fluent-editor/demos/image-upload-before-upload.vue (1)

39-47: Add error handling for image URL conversion

The imageFileToUrl promise chain should include error handling.

-imageFileToUrl(file).then(imageUrl => {
+imageFileToUrl(file).then((imageUrl) => {
   editor.uploader.insertImageToEditor(range, {
     code: 0,
     data: {
       imageUrl,
     },
   });
+}).catch((error) => {
+  console.error('Failed to convert file to URL:', error);
+  throw new Error('Failed to process image');
 });
🧰 Tools
🪛 eslint

[error] 39-39: Expected parentheses around arrow function argument having a body with curly braces.

(style/arrow-parens)


[error] 43-44: Missing trailing comma.

(style/comma-dangle)


[error] 43-44: Missing trailing comma.

(comma-dangle)


[error] 44-45: Missing trailing comma.

(style/comma-dangle)


[error] 44-45: Missing trailing comma.

(comma-dangle)

packages/fluent-editor/src/custom-uploader.ts (2)

65-71: Add documentation and improve validation

The size validation logic should be more robust and well-documented.

+ /**
+  * Validates if the file size is within the specified limit
+  * @param maxSize - Maximum file size in bytes. If null/undefined, no size limit is applied
+  * @param file - The file to validate
+  * @returns boolean indicating if the file size is acceptable
+  */
  isAllowedFileSize = (maxSize: number, file: File) => {
    if (isNullOrUndefined(maxSize)) {
      return true
    }

+   // Ensure maxSize is a positive number
+   if (maxSize <= 0) {
+     console.warn('Invalid maxSize: must be a positive number')
+     return false
+   }

    return file.size <= maxSize
  }

167-167: Fix: Add missing trailing comma

Add trailing comma to maintain consistent code style.

-        editor: this.quill
+        editor: this.quill,
🧰 Tools
🪛 eslint

[error] 167-168: Missing trailing comma.

(style/comma-dangle)


[error] 167-168: Missing trailing comma.

(comma-dangle)

📜 Review details

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

📥 Commits

Reviewing files that changed from the base of the PR and between 4bc9464 and 8d8d3ce.

📒 Files selected for processing (6)
  • packages/docs/fluent-editor/demos/image-upload-before-upload.vue (1 hunks)
  • packages/docs/fluent-editor/demos/image-upload-option.vue (1 hunks)
  • packages/docs/fluent-editor/docs/image-upload.md (1 hunks)
  • packages/fluent-editor/src/config/index.ts (1 hunks)
  • packages/fluent-editor/src/config/types/editor-config.interface.ts (1 hunks)
  • packages/fluent-editor/src/custom-uploader.ts (3 hunks)
🚧 Files skipped from review as they are similar to previous changes (2)
  • packages/fluent-editor/src/config/index.ts
  • packages/docs/fluent-editor/docs/image-upload.md
🧰 Additional context used
🪛 eslint
packages/fluent-editor/src/custom-uploader.ts

[error] 167-168: Missing trailing comma.

(style/comma-dangle)


[error] 167-168: Missing trailing comma.

(comma-dangle)

packages/docs/fluent-editor/demos/image-upload-before-upload.vue

[error] 28-28: Unexpected console statement.

(no-console)


[error] 28-28: Extra semicolon.

(style/semi)


[error] 33-33: Unexpected console statement.

(no-console)


[error] 33-33: Extra semicolon.

(style/semi)


[error] 36-36: Trailing spaces not allowed.

(style/no-trailing-spaces)


[error] 36-36: Trailing spaces not allowed.

(no-trailing-spaces)


[error] 39-39: Expected parentheses around arrow function argument having a body with curly braces.

(style/arrow-parens)


[error] 43-44: Missing trailing comma.

(style/comma-dangle)


[error] 43-44: Missing trailing comma.

(comma-dangle)


[error] 44-45: Missing trailing comma.

(style/comma-dangle)


[error] 44-45: Missing trailing comma.

(comma-dangle)


[error] 47-48: Missing trailing comma.

(style/comma-dangle)


[error] 47-48: Missing trailing comma.

(comma-dangle)


[error] 48-49: Missing trailing comma.

(style/comma-dangle)


[error] 48-49: Missing trailing comma.

(comma-dangle)

packages/docs/fluent-editor/demos/image-upload-option.vue

[error] 28-28: Unexpected console statement.

(no-console)


[error] 28-28: Extra semicolon.

(style/semi)


[error] 31-31: Unexpected console statement.

(no-console)


[error] 31-31: Extra semicolon.

(style/semi)


[error] 32-33: Missing trailing comma.

(style/comma-dangle)


[error] 32-33: Missing trailing comma.

(comma-dangle)


[error] 33-34: Missing trailing comma.

(style/comma-dangle)


[error] 33-34: Missing trailing comma.

(comma-dangle)

packages/fluent-editor/src/config/types/editor-config.interface.ts

[error] 17-17: A space is required before '}'.

(style/object-curly-spacing)


[error] 17-17: A space is required before '}'.

(object-curly-spacing)


[error] 21-21: Prefer using the primitive number as a type name, rather than the upper-cased Number.

(ts/no-wrapper-object-types)

🪛 Biome (1.9.4)
packages/fluent-editor/src/config/types/editor-config.interface.ts

[error] 21-21: Don't use 'Number' as a type.

Use lowercase primitives for consistency.
Safe fix: Use 'number' instead

(lint/complexity/noBannedTypes)

🔇 Additional comments (6)
packages/docs/fluent-editor/demos/image-upload-option.vue (1)

24-33: 🛠️ Refactor suggestion

Improve upload option configuration

Several improvements needed in the upload configuration:

  1. Extract magic number to a named constant
  2. Replace console.log with proper user feedback
  3. Add error messages for validation failures
+const MAX_FILE_SIZE = 1024 * 1024; // 1MB
+
 uploadOption: {
   imageAccept: ['image/png', 'image/gif'],
-  maxSize: 1024 * 1024, // 1MB
+  maxSize: MAX_FILE_SIZE,
   success: (file) => {
-    console.log('upload successfully!');
+    // Use your UI framework's notification system
+    showNotification({
+      type: 'success',
+      message: `Successfully uploaded ${file.name}`
+    });
   },
   fail: (file) => {
-    console.log('upload failed!');
+    showNotification({
+      type: 'error',
+      message: `Failed to upload ${file.name}`
+    });
   }
 }

Likely invalid or redundant comment.

🧰 Tools
🪛 eslint

[error] 28-28: Unexpected console statement.

(no-console)


[error] 28-28: Extra semicolon.

(style/semi)


[error] 31-31: Unexpected console statement.

(no-console)


[error] 31-31: Extra semicolon.

(style/semi)


[error] 32-33: Missing trailing comma.

(style/comma-dangle)


[error] 32-33: Missing trailing comma.

(comma-dangle)

packages/docs/fluent-editor/demos/image-upload-before-upload.vue (2)

54-57: Remove empty div element

The empty div at the end of the template serves no purpose and should be removed.

 <template>
   <div id="editor-image-upload-before-upload" />
-  <div></div>
 </template>

26-35: 🛠️ Refactor suggestion

Improve validation and error handling

The current implementation has several areas for improvement:

  1. Use uploadOption.maxSize instead of hard-coded value
  2. Add proper error handling
  3. Improve type safety
+const MAX_FILE_SIZE = 1024 * 1024; // 1MB
+interface EditorUploadParams {
+  file: File;
+  editor: any;
+}

-imageUpload: ({ file, editor }) => {
+imageUpload: ({ file, editor }: EditorUploadParams) => {
   if (file.type === 'image/gif') {
-    console.log('Do not support uploading images in GIF format.');
+    throw new Error('GIF format is not supported');
     return;
   }

-  if (file.size > 1024 * 1024) {
+  if (file.size > MAX_FILE_SIZE) {
-    console.log('The image size must not exceed 1MB.');
+    throw new Error(`Image size must not exceed ${MAX_FILE_SIZE / (1024 * 1024)}MB`);
     return;
   }

Likely invalid or redundant comment.

🧰 Tools
🪛 eslint

[error] 28-28: Unexpected console statement.

(no-console)


[error] 28-28: Extra semicolon.

(style/semi)


[error] 33-33: Unexpected console statement.

(no-console)


[error] 33-33: Extra semicolon.

(style/semi)

packages/fluent-editor/src/custom-uploader.ts (3)

8-10: LGTM: Clean import of utility function

The addition of isNullOrUndefined utility import is well-structured and aligns with the PR objective of exposing editor utilities.


167-167: LGTM: Editor context enhancement

The addition of the editor reference in the result object enhances the upload callback context, allowing more flexibility in image handling.

🧰 Tools
🪛 eslint

[error] 167-168: Missing trailing comma.

(style/comma-dangle)


[error] 167-168: Missing trailing comma.

(comma-dangle)


51-59: 🛠️ Refactor suggestion

Enhance error handling and type safety

While the implementation has improved, consider these additional enhancements:

  1. Add type information for callback parameters
  2. Include error context in fail callback
  3. Handle maxSize more explicitly
+ interface UploadCallbacks {
+   success?: (file: File) => void;
+   fail?: (file: File, error: { type: 'size' | 'type', message: string }) => void;
+ }

- if (this.isAllowedFileType(accept, file) && this.isAllowedFileSize(uploadOption?.maxSize, file)) {
+ const sizeValid = this.isAllowedFileSize(uploadOption?.maxSize, file);
+ const typeValid = this.isAllowedFileType(accept, file);
+ if (typeValid && sizeValid) {
   uploads.push(file)
   fileFlags.push(fileFlag)
-  uploadOption?.success?.(file)
+  uploadOption?.success?.(file as File)
 } else {
   rejectFlags[fileType] = true
-  uploadOption?.fail?.(file)
+  uploadOption?.fail?.(file as File, {
+    type: !sizeValid ? 'size' : 'type',
+    message: !sizeValid ? 'File exceeds maximum size' : 'Invalid file type'
+  })
 }

Likely invalid or redundant comment.

@@ -14,10 +14,13 @@ export interface IEditorConfig extends QuillOptions {
autoProtocol?: boolean | string
editorPaste?: any
uploadOption?: {
imageUploadToServer?: boolean
imageUpload?: ({ file: File, callback, editor}) => void
Copy link

Choose a reason for hiding this comment

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

🛠️ Refactor suggestion

Add parameter types for callback function

The imageUpload callback should have properly typed parameters for better type safety.

-    imageUpload?: ({ file: File, callback, editor}) => void
+    imageUpload?: ({ 
+      file: File, 
+      callback: (success: boolean, url?: string) => void,
+      editor: any 
+    }) => void
📝 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
imageUpload?: ({ file: File, callback, editor}) => void
imageUpload?: ({
file: File,
callback: (success: boolean, url?: string) => void,
editor: any
}) => void
🧰 Tools
🪛 eslint

[error] 17-17: A space is required before '}'.

(style/object-curly-spacing)


[error] 17-17: A space is required before '}'.

(object-curly-spacing)

@kagol kagol force-pushed the kagol/image-upload-support-max-size branch from 8d8d3ce to 00a3ff9 Compare December 13, 2024 09:39
@kagol kagol force-pushed the kagol/image-upload-support-max-size branch from 00a3ff9 to d4dd6fe Compare December 13, 2024 09:40
@kagol kagol merged commit ae8ad55 into main Dec 13, 2024
1 of 2 checks passed
@kagol kagol added documentation Improvements or additions to documentation enhancement New feature or request labels Dec 13, 2024
@kagol kagol deleted the kagol/image-upload-support-max-size branch January 17, 2025 03:12
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
documentation Improvements or additions to documentation enhancement New feature or request
Projects
None yet
Development

Successfully merging this pull request may close these issues.

1 participant