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

[lexical-playground] Fix bug: Insert an image inside another image's caption (#6109) #17

Open
wants to merge 2 commits into
base: main
Choose a base branch
from

Conversation

local-dev-korbit-ai-mentor[bot]
Copy link

@local-dev-korbit-ai-mentor local-dev-korbit-ai-mentor bot commented Aug 15, 2024

Context:
Now users are able to insert an image/GIF/table etc, into another image's caption.

Solution:
This PR limits what the users can insert into the image caption and its nested editor. Excluding some controls from the toolbar if the selection is inside the nested editor that belongs to the image caption.

Closes #6109

Test plan

  1. Open https://playground.lexical.dev/
  2. Insert a sample image with a caption.
  3. Focus on the caption.
  4. Insert a sample image/table/GIF etc.

Before

before-image-caption.mov

After

image-caption.mov

Description by Korbit AI

Note

This feature is in early access. You can enable or disable it in the Korbit Console.

What change is being made?

Fix the bug that allows inserting an image inside another image's caption by updating the ImageComponent, ImageNode, and ToolbarPlugin components to handle nested editors correctly.

Why are these changes being made?

This change addresses a bug where users could inadvertently insert images within the caption of another image, leading to unexpected behavior and layout issues. The solution involves adding necessary nodes to the caption editor and updating the toolbar to recognize when it is operating within a nested editor context, ensuring proper functionality and user experience.

Summary by CodeRabbit

  • New Features

    • Enhanced text editing experience with the addition of new node types including links, emojis, hashtags, and keywords in the editor.
    • Toolbar now dynamically updates based on whether the selection is in an image caption, improving user interface interactions.
  • Bug Fixes

    • Improved initialization of captions in the image component for better predictable behavior.
  • Documentation

    • Added a new utility function to check if an editor is a nested editor, enhancing utility function capabilities.

Copy link
Author

Clone of the PR facebook/lexical#6230

Copy link

korbit-ai bot commented Aug 15, 2024

My review is in progress 📖 - I will have feedback for you in a few minutes!

Copy link

coderabbitai bot commented Aug 15, 2024

Walkthrough

The recent updates enhance the Lexical editor experience by integrating new node types and improving state management in the toolbar. The ImageComponent now supports various content types, allowing for richer captions. The ImageNode initialization has been refined for better behavior when captions are absent. The ToolbarPlugin dynamically adjusts based on the editor context, ensuring a more intuitive interface. Additionally, a utility function for checking nested editors has been added, further enriching the editor's functionality.

Changes

Files Change Summary
.../ImageComponent.tsx Expanded LexicalNestedComposer to include additional nodes for a richer editing experience.
.../ImageNode.tsx Modified __caption initialization to create editors with an empty nodes array when no caption is provided, improving predictability.
.../ToolbarPlugin/index.tsx Introduced new state management for tracking if the selection is within an image caption. Adjusted rendering logic for toolbar elements based on the editor's context.
.../lexical-utils/src/index.ts Added a new function $isEditorIsNestedEditor to check if a Lexical editor instance is a nested editor, complementing existing utilities.

Sequence Diagram(s)

sequenceDiagram
    participant User
    participant ToolbarPlugin
    participant ImageComponent
    participant ImageNode

    User->>ImageComponent: Add image with caption
    ImageComponent->>ImageNode: Initialize with caption
    ImageNode->>ImageNode: Check if caption is provided
    alt No caption
        ImageNode->>ImageNode: Create editor with empty nodes
    end
    ImageNode->>ToolbarPlugin: Update state for caption presence
    ToolbarPlugin->>User: Display appropriate toolbar options
Loading

🐇 In the meadow where ideas bloom,
New features dance, dispelling gloom.
With captions bright and tools that play,
Editing’s fun in a vibrant way!
Hopping along with joy we cheer,
For Lexical’s magic is finally here! ✨


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>.
    • 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 generate interesting stats about this repository and render them as a table.
    • @coderabbitai show all the console.log statements in this repository.
    • @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 as 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.

Additionally, you can add @coderabbitai ignore anywhere in the PR description to prevent this PR from being reviewed.

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

@korbit-ai korbit-ai bot left a comment

Choose a reason for hiding this comment

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

I have reviewed your code and found 2 potential issues.

Comment on lines +156 to +160
this.__caption =
caption ||
createEditor({
nodes: [],
});
Copy link

Choose a reason for hiding this comment

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

category Functionality

The changes to the caption editor initialization might affect its functionality. You've added a 'nodes' parameter set to an empty array when creating the editor. Is this intentional? If so, could you explain the reasoning behind this change? If not, consider removing the 'nodes' parameter or initializing it with the appropriate node types for the caption editor.

Chat with Korbit by mentioning @korbit-ai, and give a 👍 or 👎 to help Korbit improve your reviews.

Comment on lines +610 to +612
export function $isEditorIsNestedEditor(editor: LexicalEditor): boolean {
return editor._parentEditor !== null;
}
Copy link

Choose a reason for hiding this comment

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

category Functionality

The function $isEditorIsNestedEditor is correctly implemented, but its name is redundant and could be improved. Consider renaming it to $isNestedEditor for better readability and consistency with Lexical naming conventions. The function body itself is correct, checking if the editor has a parent editor.

Chat with Korbit by mentioning @korbit-ai, and give a 👍 or 👎 to help Korbit improve your reviews.

@furwellness
Copy link
Owner

/review

Copy link

codiumai-pr-agent-free bot commented Aug 20, 2024

PR Reviewer Guide 🔍

(Review updated until commit 32bfe35)

⏱️ Estimated effort to review: 3 🔵🔵🔵⚪⚪
🧪 No relevant tests
🔒 No security concerns identified
⚡ Key issues to review

Potential Performance Issue
The addition of multiple node types to the initialNodes array in the LexicalNestedComposer might impact performance for image captions. Consider if all these node types are necessary for image captions.

Code Duplication
The $updateToolbar function is called in two separate useEffect hooks. This could potentially lead to unnecessary re-renders. Consider consolidating these calls.

Copy link

Persistent review updated to latest commit 32bfe35

@furwellness furwellness reopened this Aug 21, 2024
@furwellness furwellness changed the base branch from cloned_main_ba9e8 to main August 21, 2024 04:47
Copy link

Persistent review updated to latest commit 32bfe35

@furwellness
Copy link
Owner

@coderabbitai full review

Copy link

PR Code Suggestions ✨

CategorySuggestion                                                                                                                                    Score
Enhancement
Initialize the caption editor with specific node types

Consider initializing the caption editor with specific nodes instead of an empty
array. This ensures that the caption editor has the necessary node types for proper
functionality.

packages/lexical-playground/src/nodes/ImageNode.tsx [156-160]

 this.__caption =
   caption ||
   createEditor({
-    nodes: [],
+    nodes: [TextNode, ParagraphNode, LinkNode, HashtagNode],
   });
 
  • Apply this suggestion
Suggestion importance[1-10]: 7

Why:

7
Simplify boolean conversion using optional chaining and nullish coalescing

Consider using optional chaining and nullish coalescing operators to simplify the
condition for setting isImageCaption.

packages/lexical-playground/src/plugins/ToolbarPlugin/index.tsx [556-559]

 setIsImageCaption(
-  !!rootElement?.parentElement?.classList.contains(
-    'image-caption-container',
-  ),
+  rootElement?.parentElement?.classList.contains('image-caption-container') ?? false
 );
 
  • Apply this suggestion
Suggestion importance[1-10]: 7

Why:

7
Maintainability
Extract image caption logic into a separate function

Consider moving the setIsImageCaption logic into a separate function to improve code
readability and maintainability.

packages/lexical-playground/src/plugins/ToolbarPlugin/index.tsx [554-563]

-if (activeEditor !== editor && $isEditorIsNestedEditor(activeEditor)) {
-  const rootElement = activeEditor.getRootElement();
-  setIsImageCaption(
-    !!rootElement?.parentElement?.classList.contains(
-      'image-caption-container',
-    ),
-  );
-} else {
-  setIsImageCaption(false);
-}
+const updateIsImageCaption = () => {
+  if (activeEditor !== editor && $isEditorIsNestedEditor(activeEditor)) {
+    const rootElement = activeEditor.getRootElement();
+    setIsImageCaption(
+      !!rootElement?.parentElement?.classList.contains(
+        'image-caption-container',
+      ),
+    );
+  } else {
+    setIsImageCaption(false);
+  }
+};
+updateIsImageCaption();
 
  • Apply this suggestion
Suggestion importance[1-10]: 7

Why:

7
Best practice
Use a more descriptive variable name for insert dropdown visibility

Consider using a more descriptive variable name for canViewerSeeInsertDropdown to
better reflect its purpose in controlling the visibility of the insert dropdown
menu.

packages/lexical-playground/src/plugins/ToolbarPlugin/index.tsx [861]

-const canViewerSeeInsertDropdown = !isImageCaption;
+const showInsertDropdown = !isImageCaption;
 
  • Apply this suggestion
Suggestion importance[1-10]: 7

Why:

7

Copy link

coderabbitai bot commented Aug 21, 2024

Actions performed

Full review triggered.

Copy link

@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

Review details

Configuration used: CodeRabbit UI
Review profile: CHILL

Commits

Files that changed from the base of the PR and between 4cbb85f and 32bfe35.

Files selected for processing (4)
  • packages/lexical-playground/src/nodes/ImageComponent.tsx (4 hunks)
  • packages/lexical-playground/src/nodes/ImageNode.tsx (1 hunks)
  • packages/lexical-playground/src/plugins/ToolbarPlugin/index.tsx (9 hunks)
  • packages/lexical-utils/src/index.ts (1 hunks)
Additional comments not posted (2)
packages/lexical-playground/src/nodes/ImageComponent.tsx (1)

18-19: Enhancements to LexicalNestedComposer.

The inclusion of additional node types such as HashtagNode, LinkNode, and EmojiNode enhances the semantic capabilities of the editor, allowing for richer content in image captions. This aligns well with the PR's objective to improve user interaction and content creation.

Also applies to: 45-49, 66-68, 426-437

packages/lexical-playground/src/plugins/ToolbarPlugin/index.tsx (1)

549-549: Improved contextual toolbar functionality.

The introduction of isImageCaption state and the conditional rendering of toolbar elements enhance the toolbar's contextual awareness, ensuring that users have access to relevant options based on the editor's context. This improves the user experience by preventing unnecessary options from cluttering the interface when editing image captions.

Also applies to: 554-564, 672-672, 686-691, 861-862, 973-985, 1064-1232

@furwellness
Copy link
Owner

Zero comments from coderabbit

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.

1 participant