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

fix: cover image update fix for project and user profile #6075

Merged
merged 3 commits into from
Nov 19, 2024

Conversation

aaryan610
Copy link
Collaborator

@aaryan610 aaryan610 commented Nov 19, 2024

Summary by CodeRabbit

Release Notes

  • New Features

    • Expanded allowed file types for asset uploads to include GIFs.
    • Introduced a new method for bulk asset management to update project cover images.
  • Improvements

    • Enhanced error handling for invalid entity and file types across endpoints.
    • Updated logic for handling cover images in user profiles and project forms, ensuring correct management based on the source of the image.
  • Bug Fixes

    • Corrected project cover image association to ensure accurate project identification.
  • Documentation

    • Updated interface definitions to reflect changes in cover image properties for projects and users.

Copy link
Contributor

coderabbitai bot commented Nov 19, 2024

Walkthrough

The changes in this pull request enhance asset management functionality across various components. The allowed_types for uploads now include "image/gif," and methods for handling project cover images have been updated to ensure correct associations. A new method for saving project cover images has been introduced, and error handling for invalid types has been standardized. Additionally, modifications to the IProject and IUser interfaces improve the management of cover image properties, while updates to several components ensure consistent handling of cover images during form submissions.

Changes

File Path Change Summary
apiserver/plane/app/views/asset/v2.py - Expanded allowed_types to include "image/gif" in ProjectAssetEndpoint and WorkspaceFileAssetEndpoint.
- Updated entity_asset_save to use asset.project_id.
- Added save_project_cover method in ProjectBulkAssetEndpoint.
- Standardized error handling for invalid entity and file types.
packages/types/src/project/projects.d.ts - Changed cover_image_url to readonly string.
- Added optional properties: cover_image_asset (null) and cover_image (string).
packages/types/src/users.d.ts - Changed cover_image_url to `readonly (string
web/app/profile/page.tsx - Modified onSubmit to check if cover_image_url starts with "http" and updated payload accordingly.
web/ce/components/projects/create/root.tsx - Updated onSubmit to handle cover_image_url similarly to the profile page.
web/core/components/project/form.tsx - Updated onSubmit to check if cover_image_url starts with "http" and added validation for project identifier availability.

Possibly related PRs

Suggested labels

🌟enhancement, ⚙️backend

Suggested reviewers

  • SatishGandham

Poem

🐇 In the land where assets play,
New formats join the fray!
Cover images, bright and clear,
With each change, we cheer!
Uploads now a breeze,
Hopping through with ease! 🌼


📜 Recent review details

Configuration used: CodeRabbit UI
Review profile: CHILL

📥 Commits

Reviewing files that changed from the base of the PR and between 77790b3 and 259e35b.

📒 Files selected for processing (1)
  • apiserver/plane/app/views/asset/v2.py (6 hunks)
🚧 Files skipped from review as they are similar to previous changes (1)
  • apiserver/plane/app/views/asset/v2.py

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.

@aaryan610 aaryan610 added 🐛bug Something isn't working 🌐frontend labels Nov 19, 2024
@aaryan610 aaryan610 added this to the v0.24.0 milestone Nov 19, 2024
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: 4

🧹 Outside diff range and nitpick comments (5)
packages/types/src/project/projects.d.ts (1)

21-25: Consider architectural implications of cover image handling

The current implementation suggests a separation between upload and rendering concerns, which is good. However, there are some architectural considerations:

  1. The frontend components check if URLs start with "http" to determine the source of the cover image. Consider moving this logic into a type guard or utility function to ensure consistent handling across components.

  2. The separation between cover_image_url (readonly) and the upload-related properties (cover_image_asset, cover_image) helps prevent accidental modifications to the display URL, but this contract should be documented more explicitly.

Consider adding JSDoc comments to better document the lifecycle and relationships between these properties:

interface IProject {
  /**
   * Temporary property used during cover image upload process.
   * Set to null when using an external URL.
   */
  cover_image_asset?: null;

  /**
   * External URL for the cover image.
   * Only set when not using an asset upload.
   */
  cover_image?: string;

  /**
   * The resolved URL for displaying the cover image.
   * This is a computed property based on either the uploaded asset or external URL.
   * @readonly
   */
  cover_image_url: readonly string;
}
web/ce/components/projects/create/root.tsx (1)

77-81: Consider adding URL validation and handling additional edge cases.

While the logic for handling external URLs is sound, consider these improvements:

  1. Add URL validation to ensure the URL is well-formed
  2. Handle cases where the URL might not start with "http" but is still valid (e.g., "https")
  3. Consider adding a comment explaining why we null the asset when using external URLs

Here's a suggested improvement:

-    if (coverImage?.startsWith("http")) {
+    // When using external URLs (from Unsplash or predefined sources), 
+    // we clear any uploaded asset to prevent storage conflicts
+    if (coverImage?.toLowerCase().startsWith("http")) {
       formData.cover_image = coverImage;
       formData.cover_image_asset = null;
+    } else if (coverImage) {
+      // Handle non-URL cover images (uploaded assets)
+      formData.cover_image = null;
+      formData.cover_image_asset = coverImage;
     }
web/core/components/project/form.tsx (2)

Line range hint 292-301: Enhance project identifier validation

The current regex /^[ÇŞĞIİÖÜA-Z0-9]+$/ allows specific non-ASCII characters. Consider:

  1. Documenting why these specific characters are allowed
  2. Adding a more restrictive pattern if these characters aren't necessary
  3. Adding a helpful validation message explaining allowed characters
 validate: (value) =>
-  /^[ÇŞĞIİÖÜA-Z0-9]+$/.test(value.toUpperCase()) ||
-  "Only Alphanumeric & Non-latin characters are allowed.",
+  /^[A-Z0-9]+$/.test(value.toUpperCase()) ||
+  "Only uppercase letters (A-Z) and numbers (0-9) are allowed.",

Line range hint 166-170: Improve loading state management

The arbitrary 300ms timeout for resetting the loading state could lead to a poor user experience. Consider:

  1. Removing the setTimeout and directly setting loading state to false after the operation completes
  2. Using the Promise's finally block for more reliable state management
- setTimeout(() => {
-   setIsLoading(false);
- }, 300);
+ try {
+   if (project.identifier !== formData.identifier) {
+     // ... existing identifier check logic
+   } else {
+     await handleUpdateChange(payload);
+   }
+ } finally {
+   setIsLoading(false);
+ }
web/app/profile/page.tsx (1)

Line range hint 182-196: Improve cover image configuration and error handling

  1. Move the default cover image URL to a constants file
  2. Add error handling for image upload failures

Consider these improvements:

+ // In constants/images.ts
+ export const DEFAULT_COVER_IMAGE = "https://images.unsplash.com/photo-1506383796573-caf02b4a79ab";

+ // In the component
+ import { DEFAULT_COVER_IMAGE } from "@/constants/images";

- src={userCover ? getFileURL(userCover) : "https://images.unsplash.com/photo-1506383796573-caf02b4a79ab"}
+ src={userCover ? getFileURL(userCover) : DEFAULT_COVER_IMAGE}

Also, consider adding error handling for the ImagePickerPopover:

 <ImagePickerPopover
   label={"Change cover"}
-  onChange={(imageUrl) => onChange(imageUrl)}
+  onChange={(imageUrl) => {
+    try {
+      onChange(imageUrl);
+    } catch (error) {
+      setToast({
+        type: TOAST_TYPE.ERROR,
+        title: "Error!",
+        message: "Failed to update cover image. Please try again.",
+      });
+    }
+  }}
   control={control}
   value={value ?? DEFAULT_COVER_IMAGE}
   isProfileCover
 />
📜 Review details

Configuration used: CodeRabbit UI
Review profile: CHILL

📥 Commits

Reviewing files that changed from the base of the PR and between 6f497b0 and 77790b3.

📒 Files selected for processing (6)
  • apiserver/plane/app/views/asset/v2.py (5 hunks)
  • packages/types/src/project/projects.d.ts (1 hunks)
  • packages/types/src/users.d.ts (2 hunks)
  • web/app/profile/page.tsx (1 hunks)
  • web/ce/components/projects/create/root.tsx (1 hunks)
  • web/core/components/project/form.tsx (1 hunks)
🔇 Additional comments (8)
packages/types/src/project/projects.d.ts (1)

21-25: 🛠️ Refactor suggestion

Review the type definition of cover image properties

A few concerns about the current implementation:

  1. The type cover_image_asset?: null seems unusual as it can only be null or undefined. Consider using a more meaningful type that represents the actual asset data structure.

  2. Having three separate properties (cover_image_asset, cover_image, cover_image_url) for managing cover images could lead to inconsistent states. Consider using a single property with a union type or a more structured approach.

Consider refactoring to one of these approaches:

// Approach 1: Using discriminated union
type ProjectCoverImage = 
  | { type: 'asset'; asset: IAsset }
  | { type: 'url'; url: string };

interface IProject {
  // ... other properties
  cover_image: ProjectCoverImage;
  readonly cover_image_url: string; // derived from cover_image
}

// Approach 2: Using a structured type
interface ProjectCoverImage {
  asset: IAsset | null;
  url: string | null;
  display_url: string; // readonly, derived from asset or url
}

interface IProject {
  // ... other properties
  cover_image: ProjectCoverImage;
}

Let's verify how these properties are used in the codebase:

web/ce/components/projects/create/root.tsx (1)

Line range hint 84-89: Verify cover image status update timing.

The cover image status is updated after project creation. Ensure this sequence is intentional and handles failures appropriately.

packages/types/src/users.d.ts (2)

158-165: LGTM! Improved readability

The multi-line formatting of the Pick type improves code readability while maintaining the same functionality.


16-20: Verify consistent usage of cover image properties

Let's ensure these type changes are consistently implemented across the codebase.

✅ Verification successful

Let me try a different approach to search for the cover image usages.


Based on the search results, I can now provide a conclusive response about the cover image properties usage across the codebase.

Cover image type definitions are consistently implemented

The type changes in users.d.ts align with the implementation across the codebase:

  • The separation between storage (cover_image, cover_image_asset) and rendering (cover_image_url) properties is consistently maintained in both frontend and backend
  • The pattern is similarly implemented in related entities (User, Project) with the same property structure
  • The frontend components correctly use cover_image_url for rendering and handle the asset/URL logic appropriately during form submissions
  • The backend models and migrations support this structure with proper database fields and asset relationships
🏁 Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Search for usage of cover image properties to verify consistent implementation
echo "Searching for cover image property usage..."
rg -t typescript -t typescriptreact "cover_image(_url|_asset)?" -B 2 -A 2

# Search for type definitions to ensure consistency
echo "Searching for related interface definitions..."
ast-grep --pattern 'interface $INTERFACE { 
  $$$
  cover_image$_?: $TYPE
  $$$
}'

Length of output: 395


Script:

#!/bin/bash
# Search for cover image related properties in all files
echo "Searching for cover image properties..."
rg "cover_image" -B 2 -A 2

# Search for interface definitions containing cover_image
echo "Searching for type definitions..."
rg "interface.*\{[\s\S]*?cover_image[\s\S]*?\}" -B 1 -A 5

Length of output: 25922

web/core/components/project/form.tsx (1)

151-155: Consider adding URL validation for external cover images

While the distinction between external URLs and uploaded assets is good, accepting any URL that starts with "http" could pose security risks. Consider:

  1. Validating URLs against a whitelist of trusted domains
  2. Implementing URL sanitization
  3. Adding length constraints for URLs

Let's check if URL validation exists elsewhere in the codebase:

web/app/profile/page.tsx (1)

77-81: Verify consistent cover image handling across components

According to the AI summary, similar changes were made in other components. Let's verify the consistency of the implementation.

✅ Verification successful

Note: Removed the --type tsx flag since it's not recognized. The commands will now search across all files.


Cover image handling is consistent across components

The verification shows consistent implementation of cover image handling across the codebase:

  • The same pattern of handling HTTP URLs and asset nullification is present in multiple components:
    • web/app/profile/page.tsx
    • web/core/components/project/form.tsx
    • web/ce/components/projects/create/root.tsx
  • All components use the shared ImagePickerPopover component for cover image selection
  • The backend models (project.py and user.py) properly support both cover_image and cover_image_asset fields
  • The implementation in the review aligns with the project-wide pattern of handling external URLs and asset management
🏁 Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Search for similar cover image handling patterns across components
echo "Searching for cover image handling patterns..."
rg -l "cover_image.*startsWith.*http" --type tsx

# Search for ImagePickerPopover usage
echo "Checking ImagePickerPopover implementations..."
rg -A 5 "ImagePickerPopover" --type tsx

# Look for potential inconsistencies in cover image handling
echo "Checking for potential inconsistencies..."
rg "cover_image(_url|_asset)?\s*=\s*" --type tsx

Length of output: 524


Script:

#!/bin/bash
# Search for similar cover image handling patterns across components
echo "Searching for cover image handling patterns..."
rg -l "cover_image.*startsWith.*http"

# Search for ImagePickerPopover usage
echo "Checking ImagePickerPopover implementations..."
rg -A 5 "ImagePickerPopover"

# Look for potential inconsistencies in cover image handling
echo "Checking for potential inconsistencies..."
rg "cover_image(_url|_asset)?\s*=\s*"

Length of output: 5441

apiserver/plane/app/views/asset/v2.py (2)

Line range hint 326-335: LGTM: Project cover image handling is now correct

The implementation properly manages project cover images by:

  1. Using the correct project_id field
  2. Cleaning up previous cover images
  3. Updating the cover_image_asset_id field

Line range hint 326-335: Verify project cover image handling across the codebase

Let's ensure that all project cover image related code is consistent.

Also applies to: 753-757

✅ Verification successful

Based on the results, I can now generate the final response as we have sufficient information about the cover image handling across the codebase.

Project cover image handling is consistent across the codebase

The verification shows that cover image handling is consistent throughout the codebase:

  • All instances properly manage the cover_image_asset_id field
  • The deletion of previous assets is handled correctly
  • The same pattern is followed for both project and user cover images
🏁 Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Check for any inconsistencies in project cover image handling

# Look for other occurrences of cover_image_asset_id
echo "Checking for other cover_image_asset_id usages:"
rg "cover_image_asset_id" -A 3

# Look for potential places where project cover images are handled
echo "Checking for other project cover image handlers:"
ast-grep --pattern 'def $_(self, $_, project_id$_):
  $$$
  project.$_ = $_
  $$$
'

Length of output: 2344

packages/types/src/users.d.ts Show resolved Hide resolved
web/app/profile/page.tsx Show resolved Hide resolved
apiserver/plane/app/views/asset/v2.py Outdated Show resolved Hide resolved
apiserver/plane/app/views/asset/v2.py Show resolved Hide resolved
@sriramveeraghanta sriramveeraghanta merged commit d5a55de into preview Nov 19, 2024
13 of 14 checks passed
@sriramveeraghanta sriramveeraghanta deleted the fix/cover-image branch November 19, 2024 12:58
@pushya22 pushya22 linked an issue Nov 22, 2024 that may be closed by this pull request
1 task
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
Projects
None yet
Development

Successfully merging this pull request may close these issues.

[bug]: Setting Cover Images Fails Without Error
4 participants