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: allow send image only #5599

Merged

Conversation

Dogtiti
Copy link
Member

@Dogtiti Dogtiti commented Oct 8, 2024

💻 变更类型 | Change Type

  • feat
  • fix
  • refactor
  • perf
  • style
  • test
  • docs
  • ci
  • chore
  • build

🔀 变更说明 | Description of Change

📝 补充信息 | Additional Information

Summary by CodeRabbit

  • New Features

    • Enhanced user input validation to prevent submission with empty input and no attached images.
    • Added support for pasting images directly from the clipboard.
    • Improved image upload functionality to allow multiple images (up to three).
  • Bug Fixes

    • Streamlined handling of user input and attached images for better message processing.

@Dogtiti Dogtiti requested a review from lloydzhou October 8, 2024 13:31
Copy link
Contributor

coderabbitai bot commented Oct 8, 2024

Walkthrough

The changes in this pull request involve modifications to the chat component and its associated store. In app/components/chat.tsx, user input handling and image attachment functionality are enhanced, including checks for empty submissions and support for pasting images. The app/store/chat.ts file sees a refactor in the onUserInput method, improving how user input and attached images are processed and stored. The overall structure remains consistent while enhancing user interaction and message management.

Changes

File Change Summary
app/components/chat.tsx - Added import for isEmpty from lodash-es.
- Updated doSubmit to check for empty input and attachments.
- Modified handlePaste to support image pasting.
- Enhanced uploadImage to allow multiple image uploads (max three).
app/store/chat.ts - Refactored onUserInput to conditionally construct mContent based on userContent.
- Streamlined handling of attached images using the spread operator.
- Created userMessage and botMessage with updated content structure.

Possibly related PRs

Suggested reviewers

  • mayfwl
  • lloydzhou

Poem

🐰 In the chat where words take flight,
Pasting images brings delight.
With checks for empty, we now can see,
A vibrant chat, as fun as can be!
So hop along, let's share and play,
In our chat, brightening the day! 🌼


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

vercel bot commented Oct 8, 2024

@Dogtiti is attempting to deploy a commit to the NextChat Team on Vercel.

A member of the Team first needs to authorize it.

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: 0

🧹 Outside diff range and nitpick comments (4)
app/store/chat.ts (1)

340-349: LGTM! Improved handling of multimodal content.

The changes effectively support text-only, image-only, and combined text-and-image inputs, aligning with the PR objective. The implementation is correct and maintains backwards compatibility.

Consider adding a brief comment explaining the structure of mContent for better code readability. For example:

// mContent structure:
// - For text-only: string
// - For image-only or text+image: MultimodalContent[]
let mContent: string | MultimodalContent[] = userContent;
app/components/chat.tsx (3)

1021-1022: Improved input validation

The addition of the isEmpty(attachImages) check is a good improvement. It prevents submission when both text input and image attachments are empty, enhancing the user experience.

Consider extracting this condition into a separate function for better readability:

const isInputEmpty = (input: string, images: string[]) => 
  input.trim() === "" && isEmpty(images);

if (isInputEmpty(userInput, attachImages)) return;

This would make the code more self-documenting and easier to maintain.


Line range hint 1482-1528: Enhanced paste functionality for image support

The changes to handlePaste function add support for pasting images directly into the chat, which is a great usability improvement. However, there are a few points to consider:

  1. Error Handling: Consider adding error handling for the image upload process. Currently, if an error occurs during upload, it's caught but not handled or reported to the user.

  2. File Type Checking: The function checks if the item type starts with "image/", but it might be more robust to have a whitelist of accepted image formats.

  3. Image Limit: The code limits the number of images to 3, but this limit is not communicated to the user. Consider adding a user-facing message when this limit is reached.

  4. Performance: For large images, the upload process might take a while. Consider adding a loading indicator or progress bar for better user feedback.

  5. Accessibility: Ensure that this feature is accessible to keyboard users and screen readers.

Here's a suggestion for improved error handling and user feedback:

async function uploadImage(file: File): Promise<string> {
  try {
    setUploading(true);
    return await uploadImageRemote(file);
  } catch (error) {
    console.error("Image upload failed:", error);
    showToast("Image upload failed. Please try again.");
    throw error;
  } finally {
    setUploading(false);
  }
}

// In handlePaste function:
if (file) {
  if (attachImages.length >= 3) {
    showToast("Maximum of 3 images allowed.");
    return;
  }
  try {
    const dataUrl = await uploadImage(file);
    setAttachImages(prev => [...prev, dataUrl].slice(0, 3));
  } catch {
    // Error already handled in uploadImage
  }
}

This approach provides better error handling and user feedback.


Line range hint 1530-1570: Multiple image upload functionality added

The changes to the uploadImage function add support for multiple image uploads, which is a great feature. However, there are some similarities with the handlePaste function that could be addressed:

  1. Code Duplication: The image processing and limiting logic is similar in both functions. Consider extracting this into a shared utility function.

  2. Consistency: The error handling and user feedback could be made more consistent between the two functions.

  3. Type Safety: Consider using TypeScript's type system more effectively, especially for the event handling.

Here's a suggestion for refactoring:

// In a separate utility file
export async function processAndLimitImages(
  newImages: File[],
  existingImages: string[],
  maxImages: number = 3
): Promise<string[]> {
  const processedImages: string[] = [...existingImages];
  for (const file of newImages) {
    if (processedImages.length >= maxImages) {
      showToast(`Maximum of ${maxImages} images allowed.`);
      break;
    }
    try {
      const dataUrl = await uploadImage(file);
      processedImages.push(dataUrl);
    } catch (error) {
      console.error("Image upload failed:", error);
      showToast("Image upload failed. Please try again.");
    }
  }
  return processedImages;
}

// In your component
async function uploadImage() {
  const fileInput = document.createElement("input");
  fileInput.type = "file";
  fileInput.accept = "image/png, image/jpeg, image/webp, image/heic, image/heif";
  fileInput.multiple = true;
  fileInput.onchange = async (event: Event) => {
    const files = (event.target as HTMLInputElement).files;
    if (files) {
      setUploading(true);
      const newImages = await processAndLimitImages(Array.from(files), attachImages);
      setAttachImages(newImages);
      setUploading(false);
    }
  };
  fileInput.click();
}

This refactoring would make the code more DRY, consistent, and easier to maintain.

📜 Review details

Configuration used: CodeRabbit UI
Review profile: CHILL

📥 Commits

Files that changed from the base of the PR and between 8ad63a6 and 7d55a6d.

📒 Files selected for processing (2)
  • app/components/chat.tsx (2 hunks)
  • app/store/chat.ts (1 hunks)
🧰 Additional context used
📓 Learnings (1)
app/components/chat.tsx (1)
Learnt from: Dakai
PR: ChatGPTNextWeb/ChatGPT-Next-Web#5585
File: app/components/chat.tsx:1482-1528
Timestamp: 2024-10-06T07:59:31.943Z
Learning: In `app/components/chat.tsx`, maintain similarity between `uploadDocument()` and `uploadImage()` functions to aid future maintenance.
🔇 Additional comments (1)
app/components/chat.tsx (1)

122-123: New import added

A new import for the isEmpty function from lodash-es has been added. This is a good practice as it allows for a more robust empty check.

Copy link
Contributor

github-actions bot commented Oct 8, 2024

Your build has completed!

Preview deployment

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.

3 participants