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(file): support upload file to server #163

Merged
merged 1 commit into from
Dec 19, 2024
Merged

Conversation

kagol
Copy link
Member

@kagol kagol commented Dec 19, 2024

PR

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 a file upload component in the Fluent Editor.
    • Enhanced toolbar configuration for file handling and text formatting.
    • Added support for uploading files to a server.
  • Documentation

    • Updated documentation to include basic usage and server upload instructions for file uploads.
  • Bug Fixes

    • Improved file upload handling logic to support custom upload functions.
    • Enhanced the handleUploadFile method for better response processing.

Copy link

coderabbitai bot commented Dec 19, 2024

Walkthrough

This pull request introduces a comprehensive file upload feature for the Fluent Editor, encompassing a new Vue demo component, updated documentation, and enhanced file upload handling in the CustomUploader class. The changes enable more flexible file upload mechanisms, allowing developers to customize file upload behavior by providing a custom upload function while maintaining a fallback to default file insertion.

Changes

File Change Summary
packages/docs/fluent-editor/demos/file-upload-to-server.vue Added new Vue component demonstrating file upload to server with Fluent Editor
packages/docs/fluent-editor/docs/file-upload.md Updated documentation with new sections on basic file upload usage and server upload configuration
packages/fluent-editor/src/custom-uploader.ts Modified handleUploadFile method to support custom file upload callbacks and improved upload handling
packages/fluent-editor/src/config/types/editor-config.interface.ts Added fileUpload method to uploadOption in IEditorConfig interface

Possibly related issues

Possibly related PRs

Suggested labels

enhancement, documentation

Poem

🐰 A rabbit's tale of upload delight,
Files dancing with Fluent's might,
Custom handlers, smooth and neat,
Uploading files, a coding treat!
Flexibility leaps with each new height! 🚀


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

@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

🧹 Nitpick comments (3)
packages/docs/fluent-editor/docs/file-upload.md (1)

3-15: Documentation could be enhanced with code examples

While the documentation structure is clear and includes demo references, it would be more helpful to include:

  1. Code examples showing the configuration options directly in the documentation
  2. Description of the uploadOption.fileUpload callback parameters and return values
  3. Error handling scenarios and best practices

Would you like me to help generate the enhanced documentation with these additions?

🧰 Tools
🪛 LanguageTool

[locale-violation] ~14-~14: 'server' é un xenismo. É preferíbel dicir "servidor"
Context: ...到服务器。 :::demo src=demos/file-upload-to-server.vue :::

(GL_BARBARISM_REPLACE)

packages/docs/fluent-editor/demos/file-upload-to-server.vue (1)

19-33: Consider adding TypeScript interfaces for editor options

The editor configuration would benefit from proper TypeScript interfaces to ensure type safety.

Consider adding interfaces:

interface EditorOptions {
  theme: string;
  modules: {
    toolbar: any[];
    file: boolean;
  };
  uploadOption: {
    fileUpload: (params: {
      file: File;
      callback: (response: { fileUrl: string }) => void;
      editor: any;
    }) => void;
  };
}
packages/fluent-editor/src/custom-uploader.ts (1)

108-116: Consider adding upload progress tracking

The current implementation doesn't provide upload progress information to the user.

Add progress tracking:

  this.insertFileToEditor(range, file, {
    code: 0,
+   progress: 0,
    data: {
      title: file.name,
      size: file.size,
      src: res.fileUrl,
    },
  })

Would you like me to provide the complete implementation including the progress tracking UI components?

📜 Review details

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

📥 Commits

Reviewing files that changed from the base of the PR and between 500ae31 and 38240ae.

📒 Files selected for processing (3)
  • packages/docs/fluent-editor/demos/file-upload-to-server.vue (1 hunks)
  • packages/docs/fluent-editor/docs/file-upload.md (1 hunks)
  • packages/fluent-editor/src/custom-uploader.ts (1 hunks)
🧰 Additional context used
🪛 LanguageTool
packages/docs/fluent-editor/docs/file-upload.md

[locale-violation] ~14-~14: 'server' é un xenismo. É preferíbel dicir "servidor"
Context: ...到服务器。 :::demo src=demos/file-upload-to-server.vue :::

(GL_BARBARISM_REPLACE)

Comment on lines +26 to +31
fileUpload: ({ file, callback }) => {
// Upload file to server, get fileUrl: https://calibre-ebook.com/downloads/demos/demo.docx
callback({
fileUrl: 'https://calibre-ebook.com/downloads/demos/demo.docx',
})
},
Copy link

Choose a reason for hiding this comment

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

⚠️ Potential issue

Improve error handling and user experience in file upload demo

The current implementation has several areas for improvement:

  1. No error handling for failed uploads
  2. No loading state during upload
  3. Using a hardcoded external URL which may not be reliable

Consider implementing proper error handling and loading states:

 fileUpload: ({ file, callback }) => {
+  // Show loading state
+  const loading = true
+  try {
     // Upload file to server, get fileUrl: https://calibre-ebook.com/downloads/demos/demo.docx
-    callback({
-      fileUrl: 'https://calibre-ebook.com/downloads/demos/demo.docx',
-    })
+    // Simulate actual file upload
+    setTimeout(() => {
+      callback({
+        fileUrl: URL.createObjectURL(file)
+      })
+      loading = false
+    }, 1000)
+  } catch (error) {
+    console.error('File upload failed:', error)
+    loading = false
+  }
 },

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

Comment on lines +122 to +130
this.insertFileToEditor(range, files[0], {
code: 0,
data: {
title: files[0].name,
size: files[0].size,
src: files[0].src,
},
})
}
Copy link

Choose a reason for hiding this comment

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

⚠️ Potential issue

Add file type validation in fallback mode

The fallback implementation should validate the file type before insertion.

Add validation:

  else {
+   if (!this.isAllowedFileType(this.options.file, files[0])) {
+     console.error('Invalid file type');
+     this.quill.options.uploadOption?.onError?.(new Error('Invalid file type'));
+     return;
+   }
    this.insertFileToEditor(range, files[0], {
      code: 0,
      data: {
        title: files[0].name,
        size: files[0].size,
        src: files[0].src,
      },
    })
  }

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

Comment on lines +100 to +120
if (this.quill.options.uploadOption?.fileUpload) {
const file = files[0]
const result = {
file,
callback: (res) => {
if (!res) {
return
}
this.insertFileToEditor(range, file, {
code: 0,
data: {
title: file.name,
size: file.size,
src: res.fileUrl,
},
})
},
editor: this.quill,
}
this.quill.options.uploadOption?.fileUpload(result)
}
Copy link

Choose a reason for hiding this comment

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

⚠️ Potential issue

Enhance type safety and error handling in file upload

The file upload implementation could be improved in several areas:

  1. Missing TypeScript types for callback parameters
  2. Basic error handling could be enhanced
  3. No validation of the response fileUrl

Consider these improvements:

+ interface FileUploadResponse {
+   fileUrl: string;
+   error?: string;
+ }

+ interface FileUploadCallback {
+   (response: FileUploadResponse): void;
+ }

+ interface FileUploadResult {
+   file: File;
+   callback: FileUploadCallback;
+   editor: Quill;
+ }

  if (this.quill.options.uploadOption?.fileUpload) {
    const file = files[0]
    const result = {
      file,
      callback: (res) => {
-       if (!res) {
+       if (!res || !res.fileUrl) {
+         console.error('Invalid file upload response:', res);
+         this.quill.options.uploadOption?.onError?.(new Error('Invalid upload response'));
          return;
        }
+       // Validate fileUrl
+       try {
+         new URL(res.fileUrl);
+       } catch (e) {
+         console.error('Invalid file URL:', res.fileUrl);
+         this.quill.options.uploadOption?.onError?.(new Error('Invalid file URL'));
+         return;
+       }
        this.insertFileToEditor(range, file, {
          code: 0,
          data: {
            title: file.name,
            size: file.size,
            src: res.fileUrl,
          },
        })
      },
      editor: this.quill,
    }
    this.quill.options.uploadOption?.fileUpload(result)
  }
📝 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.quill.options.uploadOption?.fileUpload) {
const file = files[0]
const result = {
file,
callback: (res) => {
if (!res) {
return
}
this.insertFileToEditor(range, file, {
code: 0,
data: {
title: file.name,
size: file.size,
src: res.fileUrl,
},
})
},
editor: this.quill,
}
this.quill.options.uploadOption?.fileUpload(result)
}
interface FileUploadResponse {
fileUrl: string;
error?: string;
}
interface FileUploadCallback {
(response: FileUploadResponse): void;
}
interface FileUploadResult {
file: File;
callback: FileUploadCallback;
editor: Quill;
}
if (this.quill.options.uploadOption?.fileUpload) {
const file = files[0]
const result = {
file,
callback: (res) => {
if (!res || !res.fileUrl) {
console.error('Invalid file upload response:', res);
this.quill.options.uploadOption?.onError?.(new Error('Invalid upload response'));
return;
}
// Validate fileUrl
try {
new URL(res.fileUrl);
} catch (e) {
console.error('Invalid file URL:', res.fileUrl);
this.quill.options.uploadOption?.onError?.(new Error('Invalid file URL'));
return;
}
this.insertFileToEditor(range, file, {
code: 0,
data: {
title: file.name,
size: file.size,
src: res.fileUrl,
},
})
},
editor: this.quill,
}
this.quill.options.uploadOption?.fileUpload(result)
}

@kagol kagol force-pushed the kagol/upload-file-to-server branch from 38240ae to e30b660 Compare December 19, 2024 03:47
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: 2

🧹 Nitpick comments (2)
packages/docs/fluent-editor/docs/file-upload.md (1)

3-8: Consider enhancing the basic usage documentation.

While the basic usage section explains how to enable file upload, it would be more helpful to include:

  • A code snippet showing the configuration
  • Supported file types and size limitations
  • Expected behavior when file upload is enabled
packages/fluent-editor/src/config/types/editor-config.interface.ts (1)

Line range hint 16-25: Consider adding error handling and validation types.

The uploadOption interface could benefit from additional types for error handling and file validation:

interface UploadError {
  code: string;
  message: string;
}

interface UploadValidation {
  maxSize?: number;
  allowedTypes?: string[];
  validateCustom?: (file: File) => boolean | Promise<boolean>;
}

This would allow for more robust file upload implementations.

📜 Review details

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

📥 Commits

Reviewing files that changed from the base of the PR and between 38240ae and e30b660.

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

[locale-violation] ~14-~14: 'server' é un xenismo. É preferíbel dicir "servidor"
Context: ...到服务器。 :::demo src=demos/file-upload-to-server.vue :::

(GL_BARBARISM_REPLACE)

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

Line range hint 16-25: Verify the integration with Quill's file handling.

Let's verify how this interfaces with Quill's native file handling capabilities.

✅ Verification successful

The file handling interface is properly integrated with Quill's capabilities

The implementation shows a well-structured integration between the editor config interface and Quill's file handling:

  • The CustomUploader module properly handles file uploads through the fileUpload callback
  • File handling is registered as a core module in FileModule
  • The implementation includes proper type checking, size validation, and error handling
  • The interface correctly supports both single and multi-file uploads
  • File insertion is properly integrated with Quill's Delta operations
🏁 Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Search for Quill's file handling implementations
rg -t ts "file" --glob "node_modules/quill/**/*.ts"

# Search for existing file upload implementations in the codebase
ast-grep --pattern 'fileUpload: ({ file, callback, editor }) => {
  $$$
}'

Length of output: 277


Script:

#!/bin/bash
# Search for file upload related implementations in the codebase
rg -t ts "fileUpload" -A 5

# Search for Quill editor integration with file uploads
rg -t ts "Quill.*file|file.*Quill" -A 5

# Look for file handling in editor configurations
fd -e ts -e js "editor" --exec rg -l "file.*upload|upload.*file" {}

Length of output: 2609


Script:

#!/bin/bash
# Let's check the implementation in fluent-editor.ts
cat packages/fluent-editor/src/fluent-editor.ts

# Check the File format implementation
cat packages/fluent-editor/src/file/index.ts

# Check custom uploader implementation
cat packages/fluent-editor/src/custom-uploader.ts

Length of output: 16060

Comment on lines +10 to +15
## 上传到服务器

配置 `uploadOption.fileUpload` 可以将文件上传到服务器。

:::demo src=demos/file-upload-to-server.vue
:::
Copy link

Choose a reason for hiding this comment

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

🛠️ Refactor suggestion

Documentation needs more details about server upload configuration.

The server upload section could be improved by adding:

  • TypeScript interface for the fileUpload function
  • Example implementation showing how to handle success/failure cases
  • Security considerations for file uploads

Here's a suggested addition:

配置示例:
```typescript
{
  uploadOption: {
    fileUpload: ({ file, callback, editor }) => {
      // Upload implementation
      const formData = new FormData();
      formData.append('file', file);
      
      // Example server upload
      fetch('/upload', {
        method: 'POST',
        body: formData
      })
        .then(response => response.json())
        .then(data => callback(data.url))
        .catch(error => console.error('Upload failed:', error));
    }
  }
}

<details>
<summary>🧰 Tools</summary>

<details>
<summary>🪛 LanguageTool</summary>

[locale-violation] ~14-~14: 'server' é un xenismo. É preferíbel dicir "servidor"
Context: ...到服务器。  :::demo src=demos/file-upload-to-server.vue ::: 

(GL_BARBARISM_REPLACE)

</details>

</details>

<!-- This is an auto-generated comment by CodeRabbit -->

@@ -17,6 +17,7 @@ export interface IEditorConfig extends QuillOptions {
imageUpload?: ({ file: File, callback, editor }) => void
imageAccept?: Array<string>[] | string
fileAccept?: Array<string>[] | string
fileUpload: ({ 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

Consider improving the type definition for better type safety and consistency.

Several improvements could be made to the fileUpload property:

  1. Consider making it optional like imageUpload for backward compatibility
  2. Add proper typing for the callback parameter
  3. Add JSDoc documentation for the parameters

Here's a suggested improvement:

-    fileUpload: ({ file: File, callback, editor }) => void
+    /**
+     * Custom file upload handler
+     * @param options Upload options
+     * @param options.file The file to be uploaded
+     * @param options.callback Callback function to be called with the uploaded file URL
+     * @param options.editor Reference to the editor instance
+     * @returns void
+     */
+    fileUpload?: ({
+      file,
+      callback,
+      editor
+    }: {
+      file: File;
+      callback: (url: string) => void;
+      editor: any;  // Consider using proper Quill type
+    }) => void | Promise<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
fileUpload: ({ file: File, callback, editor }) => void
/**
* Custom file upload handler
* @param options Upload options
* @param options.file The file to be uploaded
* @param options.callback Callback function to be called with the uploaded file URL
* @param options.editor Reference to the editor instance
* @returns void
*/
fileUpload?: ({
file,
callback,
editor
}: {
file: File;
callback: (url: string) => void;
editor: any; // Consider using proper Quill type
}) => void | Promise<void>;

@kagol kagol merged commit 9d90d07 into main Dec 19, 2024
3 checks passed
@kagol kagol added the enhancement New feature or request label Dec 19, 2024
@kagol kagol deleted the kagol/upload-file-to-server 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
enhancement New feature or request
Projects
None yet
Development

Successfully merging this pull request may close these issues.

1 participant