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

[PE-93] refactor: accept generic function to search mentions #6249

Merged
merged 1 commit into from
Dec 20, 2024

Conversation

aaryan610
Copy link
Collaborator

@aaryan610 aaryan610 commented Dec 20, 2024

Description

This PR adds a generic searchEntity callback function for scalability.

Type of Change

  • Code refactoring

Summary by CodeRabbit

  • New Features

    • Introduced a searchMentionCallback in the RichTextEditor for enhanced mention search functionality.
    • Integrated project-related search capabilities across various components.
  • Bug Fixes

    • Improved error handling for file uploads, providing user-friendly messages and logging errors.
  • Documentation

    • Updated type signatures to reflect new properties and methods in relevant components.

@aaryan610 aaryan610 added this to the v0.24.0 milestone Dec 20, 2024
Copy link
Contributor

coderabbitai bot commented Dec 20, 2024

Walkthrough

The pull request introduces a new searchMentionCallback property across multiple components in the web application's editor and issue management system. This callback replaces the direct usage of projectService.searchEntity method with a more flexible function that handles entity search operations. The changes are consistently applied across different components like RichTextEditor, InboxIssueDescription, IssueDescriptionInput, and description-editor.tsx, standardizing the approach to searching and mentioning entities within the application.

Changes

File Change Summary
web/core/components/editor/rich-text-editor/rich-text-editor.tsx Added searchMentionCallback to RichTextEditorWrapperProps interface
web/core/components/inbox/modals/create-modal/issue-description.tsx Added searchMentionCallback using projectService
web/core/components/issues/description-input.tsx Integrated searchMentionCallback with RichTextEditor
web/core/components/issues/issue-modal/components/description-editor.tsx Updated TIssueDescriptionEditorProps and added searchMentionCallback

Sequence Diagram

sequenceDiagram
    participant Editor as RichTextEditor
    participant Service as ProjectService
    participant Callback as SearchMentionCallback

    Editor->>Callback: Request entity search
    Callback->>Service: Perform search with payload
    Service-->>Callback: Return search results
    Callback-->>Editor: Provide search results
Loading

Possibly related PRs

Suggested labels

🧹chore, 🌟enhancement

Suggested reviewers

  • sriramveeraghanta
  • SatishGandham
  • rahulramesha

Poem

🐰 Mentions dance, a rabbit's delight,
Callbacks weave through code so bright,
Searching entities with graceful ease,
No more service chains to seize,
A flexible path, our editor's might! 🌟


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

🧹 Nitpick comments (2)
web/core/components/issues/description-input.tsx (1)

Line range hint 132-144: Extract common error handling logic

The error handling logic for file uploads is duplicated across components.

Consider extracting it into a shared utility:

// utils/file-upload.ts
export const handleProjectAssetUpload = async (
  fileService: FileService,
  workspaceSlug: string,
  projectId: string,
  entityId: string,
  entityType: EFileAssetType,
  file: File
): Promise<string> => {
  try {
    const { asset_id } = await fileService.uploadProjectAsset(
      workspaceSlug,
      projectId,
      {
        entity_identifier: entityId,
        entity_type: entityType,
      },
      file
    );
    return asset_id;
  } catch (error) {
    console.log("Error in uploading issue asset:", error);
    throw new Error("Asset upload failed. Please try again later.");
  }
};
web/core/components/issues/issue-modal/components/description-editor.tsx (1)

193-199: Consider performance and error handling improvements

The searchMentionCallback implementation is correct and aligns with the PR objectives. However, consider these improvements:

+ const searchMentionCallback = useCallback(async (payload) => {
+   try {
      return await projectService.searchEntity(
        workspaceSlug?.toString() ?? "",
        projectId?.toString() ?? "",
        payload
      );
+   } catch (error) {
+     console.error("Error searching mentions:", error);
+     return [];
+   }
+ }, [workspaceSlug, projectId]);

  <RichTextEditor
-   searchMentionCallback={async (payload) =>
-     await projectService.searchEntity(
-       workspaceSlug?.toString() ?? "",
-       projectId?.toString() ?? "",
-       payload
-     )
-   }
+   searchMentionCallback={searchMentionCallback}

This would:

  1. Memoize the callback to prevent unnecessary re-renders
  2. Add error handling to gracefully handle failures
📜 Review details

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

📥 Commits

Reviewing files that changed from the base of the PR and between 00624ea and 8823bf1.

📒 Files selected for processing (4)
  • web/core/components/editor/rich-text-editor/rich-text-editor.tsx (2 hunks)
  • web/core/components/inbox/modals/create-modal/issue-description.tsx (2 hunks)
  • web/core/components/issues/description-input.tsx (2 hunks)
  • web/core/components/issues/issue-modal/components/description-editor.tsx (3 hunks)
🔇 Additional comments (6)
web/core/components/editor/rich-text-editor/rich-text-editor.tsx (2)

19-19: LGTM! Well-typed callback interface

The searchMentionCallback property is properly typed with TSearchEntityRequestPayload and TSearchResponse, making the contract clear and type-safe.


27-33: LGTM! Clean implementation of the generic search callback

The component correctly implements the dependency injection pattern by:

  1. Accepting the search callback as a prop
  2. Properly forwarding it to the mention hook
  3. Removing direct service dependencies
web/core/components/issues/description-input.tsx (2)

21-23: Consider dependency injection for services

Similar to the previous file, creating service instances at the module level should be avoided.


123-129: Improve null safety in searchMentionCallback

Similar null safety concerns as in the previous file.

web/core/components/issues/issue-modal/components/description-editor.tsx (2)

29-29: LGTM: Service import and instantiation

The ProjectService import and instantiation follow the established pattern in the codebase, properly placed outside the component for optimal performance.

Also applies to: 53-53


Line range hint 31-48: Verify the impact of projectId type change

The type change from string | undefined to string | null is a breaking change that requires verification of all consuming components.

✅ Verification successful

Type change from string | undefined to string | null is safe

The change is safe because:

  1. All usages of projectId in the component are already null-safe with checks like if (!projectId) or projectId?.toString()
  2. The component handles both null and undefined cases similarly in its implementation
  3. The value is only used after null checks, making the type change non-breaking
🏁 Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Search for components using IssueDescriptionEditor to verify type compatibility
rg -l "IssueDescriptionEditor" | while read -r file; do
  echo "=== $file ==="
  rg "projectId.*IssueDescriptionEditor" "$file" -A 2
done

Length of output: 580


Script:

#!/bin/bash
# Let's check how projectId is being used in the form component and any other related files
rg "projectId.*IssueDescriptionEditor" -B 5 -A 2 web/core/components/issues/issue-modal/form.tsx

# Also check for any direct usage of projectId in the description editor
rg "projectId" web/core/components/issues/issue-modal/components/description-editor.tsx -B 2 -A 2

# Let's also check if there are any other components passing projectId
ast-grep --pattern 'projectId={$_}'

Length of output: 2243

Comment on lines +77 to +79
searchMentionCallback={async (payload) =>
await projectService.searchEntity(workspaceSlug?.toString() ?? "", projectId?.toString() ?? "", payload)
}
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

Improve null safety in searchMentionCallback

The current implementation uses optional chaining with toString() which could still result in "undefined" being passed as a string.

Consider this safer implementation:

-      searchMentionCallback={async (payload) =>
-        await projectService.searchEntity(workspaceSlug?.toString() ?? "", projectId?.toString() ?? "", payload)
-      }
+      searchMentionCallback={async (payload) => {
+        if (!workspaceSlug || !projectId) throw new Error("Workspace slug and project ID are required");
+        return await projectService.searchEntity(workspaceSlug.toString(), projectId.toString(), payload);
+      }}
📝 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
searchMentionCallback={async (payload) =>
await projectService.searchEntity(workspaceSlug?.toString() ?? "", projectId?.toString() ?? "", payload)
}
searchMentionCallback={async (payload) => {
if (!workspaceSlug || !projectId) throw new Error("Workspace slug and project ID are required");
return await projectService.searchEntity(workspaceSlug.toString(), projectId.toString(), payload);
}}

Comment on lines +24 to +26
import { ProjectService } from "@/services/project";
const fileService = new FileService();
const projectService = new ProjectService();
Copy link
Contributor

Choose a reason for hiding this comment

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

🛠️ Refactor suggestion

Consider dependency injection for services

Creating service instances at the module level can lead to:

  • Multiple instances across imports
  • Difficulties in testing
  • Potential memory leaks

Consider injecting the service through props or a dependency injection container:

-const projectService = new ProjectService();
+interface Props {
+  projectService: ProjectService;
+  // ... other props
+}

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

@pushya22 pushya22 merged commit d2c0940 into preview Dec 20, 2024
13 of 14 checks passed
@pushya22 pushya22 deleted the refactor/rich-text-mention branch December 20, 2024 10:21
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Projects
None yet
Development

Successfully merging this pull request may close these issues.

3 participants