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

[TASK-7268] fix: add attachment to requests #558

Merged
merged 1 commit into from
Dec 4, 2024

Conversation

jjramirezn
Copy link
Contributor

@jjramirezn jjramirezn commented Dec 4, 2024

Summary by CodeRabbit

  • New Features

    • Enhanced file upload capabilities in the payment request process, allowing users to upload files directly.
    • Improved type safety for handling attachment options in the request creation process.
  • Bug Fixes

    • Updated method signatures to ensure proper handling of attachment options.

Copy link

vercel bot commented Dec 4, 2024

The latest updates on your projects. Learn more about Vercel for Git ↗︎

Name Status Preview Comments Updated (UTC)
peanut-ui ✅ Ready (Inspect) Visit Preview 💬 Add feedback Dec 4, 2024 0:15am

@jjramirezn jjramirezn requested a review from Hugo0 December 4, 2024 12:13
Copy link

Copy link
Contributor

coderabbitai bot commented Dec 4, 2024

Walkthrough

The changes in this pull request primarily involve modifications to the IFileUploadInputProps interface in the FileUploadInput component, making it an exported interface. Additionally, the InitialView component has been updated to import this interface, enhancing type safety for the attachmentOptions parameter. The handleOnNext function has been adjusted to incorporate this parameter, allowing for improved handling of file uploads during the payment request process.

Changes

File Path Change Summary
src/components/Global/FileUploadInput/index.tsx Changed IFileUploadInputProps from non-exported to exported interface.
src/components/Request/Create/Views/Initial.view.tsx Imported IFileUploadInputProps, updated handleOnNext to include attachmentOptions, and integrated file upload handling in the payment request process.

Possibly related PRs

Suggested reviewers

  • Hugo0
  • nezz0746

🐰 In the meadow where rabbits play,
A new interface has come our way.
With uploads now, we hop with glee,
Enhancing views for you and me.
So let’s embrace this change so bright,
And share our files with pure delight! 🌼


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

🧹 Outside diff range and nitpick comments (4)
src/components/Global/FileUploadInput/index.tsx (3)

Line range hint 20-27: Add memory cleanup and improve type safety

  1. The URL.createObjectURL() call creates a memory leak as the URL is not revoked
  2. The event type should be properly typed instead of 'any'

Consider this implementation:

-    const handleFileChange = (e: any) => {
+    const handleFileChange = (e: React.ChangeEvent<HTMLInputElement>) => {
         const file = e.target.files[0]
         if (file) {
+            if (attachmentOptions.fileUrl) {
+                URL.revokeObjectURL(attachmentOptions.fileUrl)
+            }
             const url = URL.createObjectURL(file)
             setAttachmentOptions({ message: attachmentOptions.message, fileUrl: url, rawFile: file })
         }
     }
+
+    useEffect(() => {
+        return () => {
+            if (attachmentOptions.fileUrl) {
+                URL.revokeObjectURL(attachmentOptions.fileUrl)
+            }
+        }
+    }, [])

Line range hint 29-41: Optimize file type detection

The current implementation fetches the file to determine its type, which is inefficient as we already have the raw file.

Consider this optimization:

     useEffect(() => {
-        if (attachmentOptions.fileUrl) {
-            fetch(attachmentOptions.fileUrl)
-                .then((response) => response.blob())
-                .then((blob) => {
-                    setFileType(blob.type)
-                })
-                .catch((error) => {
-                    console.log('Error fetching the blob from URL:', error)
-                    setFileType('') // Reset or handle the error state
-                })
+        if (attachmentOptions.rawFile) {
+            setFileType(attachmentOptions.rawFile.type)
         }
-    }, [attachmentOptions.fileUrl])
+    }, [attachmentOptions.rawFile])

Line range hint 47-49: Add file size validation

There's currently no validation for file size, which could lead to issues with large files.

Consider adding size validation:

     <input
         type="file"
         accept="image/*,application/pdf"
+        data-max-size="5242880"
         onChange={handleFileChange}
         className="hidden"
         id="file-input"
     />

And update the handler:

const handleFileChange = (e: React.ChangeEvent<HTMLInputElement>) => {
    const file = e.target.files?.[0]
    if (!file) return
    
    const maxSize = parseInt(e.target.dataset.maxSize || '5242880', 10) // 5MB default
    if (file.size > maxSize) {
        alert('File is too large. Maximum size is 5MB.')
        return
    }
    
    if (attachmentOptions.fileUrl) {
        URL.revokeObjectURL(attachmentOptions.fileUrl)
    }
    const url = URL.createObjectURL(file)
    setAttachmentOptions({ message: attachmentOptions.message, fileUrl: url, rawFile: file })
}
src/components/Request/Create/Views/Initial.view.tsx (1)

Line range hint 169-179: Reduce code duplication in handleOnNext calls

The same handleOnNext call with identical parameters is duplicated in the component.

Consider extracting the parameters to a function:

const getHandleOnNextParams = () => ({
    recipientAddress,
    tokenAddress: selectedTokenAddress,
    chainId: selectedChainID,
    userBalances: balances,
    tokenValue,
    tokenData: selectedTokenData,
    attachmentOptions,
})

Then use it in both places:

-                        handleOnNext({
-                            recipientAddress,
-                            tokenAddress: selectedTokenAddress,
-                            chainId: selectedChainID,
-                            userBalances: balances,
-                            tokenValue,
-                            tokenData: selectedTokenData,
-                            attachmentOptions,
-                        })
+                        handleOnNext(getHandleOnNextParams())

Also applies to: 199-209

📜 Review details

Configuration used: CodeRabbit UI
Review profile: CHILL

📥 Commits

Reviewing files that changed from the base of the PR and between f810420 and 6e2faff.

📒 Files selected for processing (2)
  • src/components/Global/FileUploadInput/index.tsx (1 hunks)
  • src/components/Request/Create/Views/Initial.view.tsx (4 hunks)
🔇 Additional comments (1)
src/components/Global/FileUploadInput/index.tsx (1)

Line range hint 4-14: LGTM on interface export and structure

The interface is well-structured with clear type definitions for all properties.

Comment on lines +56 to +64
attachmentOptions,
}: {
recipientAddress: string | undefined
tokenAddress: string
chainId: string
userBalances: IUserBalance[]
tokenValue: string | undefined
tokenData: Pick<IToken, 'chainId' | 'address' | 'decimals' | 'symbol'> | undefined
attachmentOptions: IFileUploadInputProps['attachmentOptions']
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

Add validation for attachment data

The attachmentOptions parameter is added but there's no validation before passing to the SDK.

Consider adding validation:

const validateAttachment = (
    attachmentOptions: IFileUploadInputProps['attachmentOptions']
): { isValid: boolean; error?: string } => {
    if (!attachmentOptions) return { isValid: true }
    
    if (attachmentOptions.rawFile && attachmentOptions.rawFile.size > 5242880) {
        return { isValid: false, error: 'Attachment file size exceeds 5MB limit' }
    }
    
    if (attachmentOptions.message && attachmentOptions.message.length > 140) {
        return { isValid: false, error: 'Reference message exceeds 140 characters' }
    }
    
    return { isValid: true }
}

Then use it in handleOnNext:

     try {
+        const { isValid, error } = validateAttachment(attachmentOptions)
+        if (!isValid) {
+            setErrorState({
+                showError: true,
+                errorMessage: error || 'Invalid attachment',
+            })
+            return
+        }
         let inputValue = tokenValue

@Hugo0 Hugo0 merged commit f7d36d1 into develop Dec 4, 2024
4 checks passed
@coderabbitai coderabbitai bot mentioned this pull request Dec 4, 2024
@coderabbitai coderabbitai bot mentioned this pull request Feb 6, 2025
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.

2 participants