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 uploader message #69

Merged
merged 3 commits into from
Jan 29, 2025
Merged

Feat/file uploader message #69

merged 3 commits into from
Jan 29, 2025

Conversation

Harman-singh-waraich
Copy link
Contributor

@Harman-singh-waraich Harman-singh-waraich commented Jan 23, 2025

PR-Codex overview

This PR primarily updates the version of the @kleros/kleros-app package and enhances file upload functionality across multiple components by integrating role-based restrictions and adjusting UI elements for better user experience.

Detailed summary

  • Updated @kleros/kleros-app from ^2.0.1 to ^2.0.2 in package.json and yarn.lock.
  • Added roleRestrictions and isDesktop hooks in various components.
  • Implemented getFileUploaderMsg to display file upload restrictions.
  • Adjusted margin-bottom for StyledFileUploader.
  • Enhanced messages for file upload instructions in ImageInput, FileInput, Policy, EvidenceUpload, and LogoUpload components.

✨ Ask PR-Codex anything about this PR by commenting with /codex {your question}

Summary by CodeRabbit

Release Notes

  • New Features

    • Enhanced file upload functionality with dynamic messaging based on user roles and device type.
    • Improved file upload guidance with context-specific messages.
  • Improvements

    • Updated file upload components to provide more informative user instructions.
    • Refined responsive design for file upload interfaces, including increased spacing for better layout.
  • Dependency Updates

    • Upgraded @kleros/kleros-app package to version 2.0.2.

Copy link
Contributor

coderabbitai bot commented Jan 23, 2025

Walkthrough

This pull request introduces updates to the package.json file and enhancements to file upload functionality across multiple components in the web application. The primary change in package.json is the version bump of the @kleros/kleros-app dependency. Additionally, components such as EvidenceUpload, FileInput, ImageInput, LogoUpload, and Policy have been modified to include a new utility function getFileUploaderMsg, which generates contextual file upload messages based on role restrictions and device type. These changes improve user guidance during file uploads.

Changes

File Change Summary
web/package.json Upgraded @kleros/kleros-app dependency from ^2.0.1 to ^2.0.2
web/src/components/ActionButton/Modal/EvidenceUpload.tsx Added getFileUploaderMsg import, useIsDesktop hook, increased margin-bottom, modified file uploader message and variant
web/src/pages/SubmitItem/ItemField/FieldInput/FileInput.tsx Added getFileUploaderMsg import, useIsDesktop hook, increased margin-bottom, updated file uploader with role restrictions and desktop-specific variant
web/src/pages/SubmitItem/ItemField/FieldInput/ImageInput.tsx Added getFileUploaderMsg import, useIsDesktop hook, increased margin-bottom, updated file uploader with role restrictions and desktop-specific variant
web/src/pages/SubmitList/ListParameters/LogoUpload.tsx Added getFileUploaderMsg import, useIsDesktop hook, increased margin-bottom, updated file uploader with role restrictions and desktop-specific variant
web/src/pages/SubmitList/ListParameters/Policy.tsx Added getFileUploaderMsg import, useIsDesktop hook, increased margin-bottom, updated file uploader with role restrictions and desktop-specific variant
web/src/utils/index.ts Added new Role type, implemented getFileUploaderMsg function for generating file upload messages

Possibly related PRs

Suggested reviewers

  • alcercu

Poem

🐰 Hop, hop, file upload's new dance,
Responsive messages take their stance,
Desktop or mobile, restrictions clear,
CodeRabbit's magic is now here!
File uploads sing with joyful glee! 🚀


🪧 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. (Beta)
  • @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 or @coderabbitai title 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: 0

🧹 Nitpick comments (7)
web/src/utils/index.ts (2)

13-19: Add JSDoc documentation for the Role type.

Adding documentation will help other developers understand the purpose and structure of this type.

+/**
+ * Represents a role with its associated file upload restrictions.
+ * @property {string} name - The name of the role
+ * @property {Object} restriction - The upload restrictions for this role
+ * @property {number} restriction.maxSize - Maximum allowed file size in bytes
+ * @property {string[]} restriction.allowedMimeTypes - List of allowed MIME types
+ */
 type Role = {
   name: string;
   restriction: {
     maxSize: number;
     allowedMimeTypes: string[];
   };
 };

21-35: Enhance the robustness and readability of the file uploader message generator.

The function could benefit from several improvements:

  1. Handle edge cases for MIME types
  2. Use constants for size conversion
  3. Improve message formatting
+const BYTES_PER_MB = 1024 * 1024;
+
 export const getFileUploaderMsg = (role: Roles, roleRestrictions?: Role[]) => {
   if (!roleRestrictions) return;
   const restrictions = roleRestrictions.find((supportedRoles) => Roles[supportedRoles.name] === role);

   if (!restrictions) return;
+  if (!restrictions.restriction.allowedMimeTypes.length) return;

+  const formatMimeType = (type: string) => {
+    if (!type.includes('/')) return type;
+    const [prefix, suffix] = type.split('/');
+    return suffix === '*' ? prefix : suffix;
+  };

+  const formattedTypes = restrictions.restriction.allowedMimeTypes
+    .map(formatMimeType)
+    .filter(Boolean)
+    .join(', ');

+  const maxSizeMB = (restrictions.restriction.maxSize / BYTES_PER_MB).toFixed(2);

-  return `Allowed file types: [ ${restrictions.restriction.allowedMimeTypes
-    .map((type) => {
-      const [prefix, suffix] = type.split("/");
-      if (!suffix) return prefix ?? null;
-
-      return suffix === "*" ? prefix : suffix;
-    })
-    .join(", ")} ], Max allowed size: ${(restrictions.restriction.maxSize / (1024 * 1024)).toFixed(2)} MB.`;
+  return `Allowed file types: [${formattedTypes}]\nMax allowed size: ${maxSizeMB} MB`;
 };
web/src/pages/SubmitItem/ItemField/FieldInput/FileInput.tsx (1)

Line range hint 33-44: Improve error handling in file upload.

The error handling could be enhanced:

  1. Remove console.log
  2. Add more specific error messages
   const handleFileUpload = (file: File) => {
     infoToast("Uploading to IPFS...");
     uploadFile(file, Roles.CurateItemFile)
       .then(async (fileURI) => {
         if (!fileURI) return;
         successToast("Uploaded successfully!");
         handleWrite(fileURI);
       })
       .catch((err) => {
-        console.log(err);
-        errorToast(`Upload failed: ${err?.message}`);
+        const errorMessage = err instanceof Error 
+          ? err.message 
+          : "An unexpected error occurred";
+        errorToast(`File upload failed: ${errorMessage}`);
       });
   };
web/src/pages/SubmitItem/ItemField/FieldInput/ImageInput.tsx (1)

Line range hint 34-46: Remove unnecessary .finally() call.

The empty .finally() block can be removed.

   uploadFile(file, Roles.CurateItemImage)
     .then(async (fileURI) => {
       if (!fileURI) return;
       successToast("Uploaded successfully!");
       handleWrite(fileURI);
     })
     .catch((err) => {
       console.log(err);
       errorToast(`Upload failed: ${err?.message}`);
-    })
-    .finally();
+    });
web/src/pages/SubmitList/ListParameters/LogoUpload.tsx (2)

Line range hint 65-82: Enhance image validation robustness.

The aspect ratio validation could be improved by:

  1. Adding size validation
  2. Adding minimum dimensions check
  3. Adding maximum dimensions check
   const handleLoad = (file: File) => {
     const reader = new FileReader();
     reader.onload = (event) => {
       const image = new Image();
       image.onload = () => {
+        const MIN_DIMENSIONS = 200;
+        const MAX_DIMENSIONS = 2000;
+
         if (image.width !== image.height) {
           errorToast("Image aspect ratio must be 1:1");
           return;
         }
+        if (image.width < MIN_DIMENSIONS || image.height < MIN_DIMENSIONS) {
+          errorToast(`Image dimensions must be at least ${MIN_DIMENSIONS}x${MIN_DIMENSIONS} pixels`);
+          return;
+        }
+        if (image.width > MAX_DIMENSIONS || image.height > MAX_DIMENSIONS) {
+          errorToast(`Image dimensions must not exceed ${MAX_DIMENSIONS}x${MAX_DIMENSIONS} pixels`);
+          return;
+        }
         handleFileUpload(file);
       };
       image.src = event.target?.result as string;
     };
     reader.readAsDataURL(file);
   };

87-90: Simplify message concatenation using template literals.

The message concatenation can be simplified and made more readable.

-        msg={
-          "Upload a logo to represent your list. The logo should be a 1:1 aspect ratio image with transparent background, in SVG, or PNG.\n" +
-          (getFileUploaderMsg(Roles.Logo, roleRestrictions) ?? "")
-        }
+        msg={`Upload a logo to represent your list. The logo should be a 1:1 aspect ratio image with transparent background, in SVG, or PNG.
+${getFileUploaderMsg(Roles.Logo, roleRestrictions) ?? ""}`}
web/src/components/ActionButton/Modal/EvidenceUpload.tsx (1)

112-116: Consider improving message formatting.

While the functionality is correct, the message concatenation could be more maintainable:

-        msg={
-          "Additionally, you can add an external file in PDF.\n" +
-          (getFileUploaderMsg(Roles.Evidence, roleRestrictions) ?? "")
-        }
+        msg={[
+          "Additionally, you can add an external file in PDF.",
+          getFileUploaderMsg(Roles.Evidence, roleRestrictions)
+        ].filter(Boolean).join("\n")}
📜 Review details

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

📥 Commits

Reviewing files that changed from the base of the PR and between 4c472ac and a039dd2.

⛔ Files ignored due to path filters (1)
  • yarn.lock is excluded by !**/yarn.lock, !**/*.lock
📒 Files selected for processing (7)
  • web/package.json (1 hunks)
  • web/src/components/ActionButton/Modal/EvidenceUpload.tsx (4 hunks)
  • web/src/pages/SubmitItem/ItemField/FieldInput/FileInput.tsx (2 hunks)
  • web/src/pages/SubmitItem/ItemField/FieldInput/ImageInput.tsx (3 hunks)
  • web/src/pages/SubmitList/ListParameters/LogoUpload.tsx (3 hunks)
  • web/src/pages/SubmitList/ListParameters/Policy.tsx (3 hunks)
  • web/src/utils/index.ts (2 hunks)
🔇 Additional comments (9)
web/src/pages/SubmitItem/ItemField/FieldInput/FileInput.tsx (1)

18-21: LGTM! Styling improvements for better message readability.

The white-space and text-align properties ensure proper formatting of multi-line messages.

web/src/pages/SubmitList/ListParameters/Policy.tsx (4)

13-14: LGTM! New imports enhance file upload functionality.

The addition of getFileUploaderMsg and useIsDesktop aligns with the PR's objective of improving file upload messaging and device-specific styling.


36-43: Verify the significant margin increase.

The margin-bottom has been increased from responsiveSize(52, 32) to responsiveSize(150, 72), which is a substantial change. Please ensure this doesn't create excessive whitespace or affect the layout negatively.

The new styles for the small element improve text readability with white-space: pre-line and text-align: start.


48-50: LGTM! Enhanced component with role restrictions and device detection.

The addition of roleRestrictions and isDesktop hook provides necessary context for dynamic messaging and responsive styling.


84-88: LGTM! Improved file uploader with dynamic messaging.

The StyledFileUploader now:

  • Adapts its variant based on the device type
  • Includes role-specific messaging using getFileUploaderMsg
web/src/components/ActionButton/Modal/EvidenceUpload.tsx (3)

8-9: LGTM! Consistent import additions.

The imports match the pattern established in Policy.tsx, maintaining consistency across components.


40-47: Verify consistent margin changes across components.

The margin-bottom increase matches Policy.tsx. The text styling for small elements is also consistent.


66-68: LGTM! Consistent hook usage.

The component follows the same pattern as Policy.tsx for role restrictions and device detection.

web/package.json (1)

73-73: Verify @kleros/kleros-app upgrade impact.

The upgrade from ^2.0.1 to ^2.0.2 is a patch version bump. However, please verify:

  1. Changelog for any breaking changes
  2. Compatibility with other dependencies
  3. Impact on the new file upload message functionality
✅ Verification successful

✓ Safe to proceed with @kleros/kleros-app update

The upgrade from 2.0.1 to 2.0.2 is a safe patch version update with minimal risk. The package is used consistently for authentication, file uploads, and notifications through standard hooks and enums, which are stable interfaces unlikely to be affected by patch-level changes.

🏁 Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Check the changelog and git history for breaking changes
gh api repos/kleros/kleros-app/releases/tags/v2.0.2 --jq '.body' || echo "Release notes not found"

# Check for potential compatibility issues in the codebase
rg -l "@kleros/kleros-app" | xargs rg "import.*from.*@kleros/kleros-app"

Length of output: 1664


Script:

#!/bin/bash
# Check npm registry for package details and changes
npm view @kleros/[email protected] version description
npm view @kleros/[email protected] version description

# Check the actual published dates to understand the timeline
npm view @kleros/kleros-app time --json | jq '."2.0.1", ."2.0.2"'

Length of output: 437

coderabbitai[bot]
coderabbitai bot previously approved these changes Jan 23, 2025
Copy link

netlify bot commented Jan 23, 2025

Deploy Preview for curate-v2 ready!

Name Link
🔨 Latest commit 9e39555
🔍 Latest deploy log https://app.netlify.com/sites/curate-v2/deploys/67935473c0d26a0008a5c5f4
😎 Deploy Preview https://deploy-preview-69--curate-v2.netlify.app
📱 Preview on mobile
Toggle QR Code...

QR Code

Use your smartphone camera to open QR code link.

To edit notification comments on pull requests, go to your Netlify site configuration.

@kemuru kemuru self-requested a review January 23, 2025 17:38
kemuru
kemuru previously approved these changes Jan 23, 2025
Copy link
Contributor

@kemuru kemuru left a comment

Choose a reason for hiding this comment

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

good but just double check the same comments I put in Court V2 and Escrow V2. just in case.

@kemuru kemuru self-requested a review January 24, 2025 08:52
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

🧹 Nitpick comments (3)
web/src/pages/SubmitList/ListParameters/LogoUpload.tsx (1)

86-90: Consider enhancing error handling and user guidance.

While the implementation looks good, consider these improvements:

  1. The null coalescing operator handles missing restrictions, but we could provide more informative fallback text.
  2. The aspect ratio requirement is mentioned in the message but not enforced until the error callback. Consider moving this validation earlier in the process.
  msg={
    "Upload a logo to represent your list. The logo should be a 1:1 aspect ratio image with transparent background.\n" +
-   (getFileUploaderMsg(Roles.Logo, roleRestrictions) ?? "")
+   (getFileUploaderMsg(Roles.Logo, roleRestrictions) ?? "Please ensure your file meets the upload requirements.")
  }
web/src/pages/SubmitList/ListParameters/Policy.tsx (2)

13-14: Consider standardizing import paths.

For consistency, consider using absolute imports (starting with src/) for both imports:

-import { getFileUploaderMsg } from "src/utils";
-import useIsDesktop from "hooks/useIsDesktop";
+import { getFileUploaderMsg } from "src/utils";
+import { useIsDesktop } from "src/hooks/useIsDesktop";

84-88: Consider improving message composition.

While the current implementation works, the message concatenation could be more elegant:

-        msg={"You can add the List Policy file." + (getFileUploaderMsg(Roles.Policy, roleRestrictions) ?? "")}
+        msg={[
+          "You can add the List Policy file.",
+          getFileUploaderMsg(Roles.Policy, roleRestrictions)
+        ].filter(Boolean).join(" ")}

This approach:

  • Improves readability
  • Handles null/undefined values more elegantly
  • Makes it easier to add more message parts in the future
📜 Review details

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

📥 Commits

Reviewing files that changed from the base of the PR and between a039dd2 and 9e39555.

📒 Files selected for processing (4)
  • web/src/components/ActionButton/Modal/EvidenceUpload.tsx (4 hunks)
  • web/src/pages/SubmitList/ListParameters/LogoUpload.tsx (3 hunks)
  • web/src/pages/SubmitList/ListParameters/Policy.tsx (3 hunks)
  • web/src/utils/index.ts (2 hunks)
🚧 Files skipped from review as they are similar to previous changes (2)
  • web/src/utils/index.ts
  • web/src/components/ActionButton/Modal/EvidenceUpload.tsx
⏰ Context from checks skipped due to timeout of 90000ms (4)
  • GitHub Check: Redirect rules - curate-v2
  • GitHub Check: Header rules - curate-v2
  • GitHub Check: Pages changed - curate-v2
  • GitHub Check: Analyze (javascript-typescript)
🔇 Additional comments (5)
web/src/pages/SubmitList/ListParameters/LogoUpload.tsx (3)

12-13: LGTM! New imports align with the PR objectives.

The added imports for file upload messaging and responsive design support the enhanced functionality described in the PR objectives.


31-31: Verify the significant margin increase.

The margin-bottom has been increased substantially from the previous values. While this might improve spacing, please verify that this doesn't create excessive vertical gaps in the UI, especially on smaller screens.

The new text styling for the upload message looks good and will improve readability.

Also applies to: 35-38


44-45: LGTM! Clean implementation of role-based restrictions and responsive design.

The addition of roleRestrictions and isDesktop hooks follows React best practices and supports the enhanced file upload messaging feature.

web/src/pages/SubmitList/ListParameters/Policy.tsx (2)

36-36: Verify the significant margin increase.

The margin-bottom has been increased substantially from the previous values. Please confirm if this large spacing is intentional and necessary for the design.

The new styling for the small element improves text formatting and alignment.

Also applies to: 40-43


48-50: LGTM! Good enhancement of component logic.

The addition of roleRestrictions and isDesktop improves the component's functionality by:

  • Supporting role-based file restrictions
  • Enabling responsive behavior based on device type

@jaybuidl jaybuidl merged commit 10ead81 into master Jan 29, 2025
7 checks passed
@jaybuidl jaybuidl deleted the feat/file-uploader-message branch January 29, 2025 12:43
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