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-298] Fix: Copy markdown to clipboard #6675

Merged
merged 41 commits into from
Mar 24, 2025
Merged

Conversation

VipinDevelops
Copy link
Collaborator

@VipinDevelops VipinDevelops commented Feb 25, 2025

Markdown

Screen.Recording.2025-03-03.at.5.46.33.PM.mov

Triple click

Screen.Recording.2025-02-27.at.12.17.08.PM.mov

Summary by CodeRabbit

  • New Features
    • Introduced enhanced clipboard operations that automatically convert copied and pasted content into Markdown format, offering flexible text handling based on user preferences.
    • Improved table interactions by adding triple-click functionality, allowing users to quickly select an entire line within table cells for efficient editing.
    • Added a new MarkdownClipboard extension to manage clipboard operations within the Tiptap editor framework.
    • Updated the Markdown extension to change how copied text is handled, providing more control over clipboard interactions.
    • Enhanced mention handling by integrating user details retrieval, allowing for display names to be shown when mentions are rendered.

Copy link
Contributor

coderabbitai bot commented Feb 25, 2025

Walkthrough

This pull request introduces a new clipboard extension for the Tiptap editor called MarkdownClipboard. It manages clipboard operations by serializing pasted or copied content into Markdown when appropriate. The extension is integrated into the core editor extensions. Additionally, a new method named handleTripleClickOn has been added to table controls to facilitate triple-click selection on table cells by computing and dispatching the appropriate selection transaction.

Changes

Files Change Summary
packages/editor/src/core/extensions/clipboard.ts
packages/editor/src/core/extensions/extensions.tsx
Added a new MarkdownClipboard extension with options and serialization logic for clipboard operations, and integrated it into the core editor extensions.
packages/editor/src/core/extensions/table/.../table-controls.ts Introduced the handleTripleClickOn method to manage triple-click events on table cells, enabling selection of an entire line of a cell by calculating the necessary boundaries and dispatching a selection transaction.
packages/editor/src/core/extensions/index.ts Added an export statement for the clipboard module to make its functionalities accessible.
packages/editor/src/core/extensions/read-only-extensions.tsx Integrated MarkdownClipboard into read-only extensions and updated the transformCopiedText configuration in the Markdown extension.
packages/editor/src/core/extensions/mentions/... Enhanced mention handling by adding getMentionedEntityDetails methods across various components to retrieve user display names based on IDs, utilizing the new useMember hook.
space/core/components/editor/... Updated mentionHandler in LiteTextEditor, RichTextEditor, LiteTextReadOnlyEditor, and their respective read-only counterparts to include the new getMentionedEntityDetails method for improved mention functionality.
web/core/components/... Introduced useMember hook in editor-body, PagesVersionEditor, and other components to enhance mention handling by fetching user display names dynamically.

Suggested labels

🐛bug, 🌐frontend, ✨feature, 🛠️refactor

Suggested reviewers

  • Palanikannan1437
  • SatishGandham

Poem

I'm a bouncy rabbit, fresh on the scene,
Hopping through code with a whiskered gleam.
Markdown magic turns text to art,
And triple-clicks select every part.
With carrots and code, our journey's bright,
CodeRabbit Inc. makes our changes take flight!
🥕🐇

Tip

⚡🧪 Multi-step agentic review comment chat (experimental)
  • We're introducing multi-step agentic chat in review comments. This experimental feature enhances review discussions with the CodeRabbit agentic chat by enabling advanced interactions, including the ability to create pull requests directly from comments.
    - To enable this feature, set early_access to true under in the settings.

📜 Recent review details

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

📥 Commits

Reviewing files that changed from the base of the PR and between 366ed38 and 17b910a.

📒 Files selected for processing (14)
  • packages/editor/src/core/extensions/extensions.tsx (2 hunks)
  • packages/editor/src/core/extensions/mentions/extension-config.ts (2 hunks)
  • packages/editor/src/core/extensions/mentions/extension.tsx (1 hunks)
  • packages/editor/src/core/extensions/read-only-extensions.tsx (2 hunks)
  • packages/editor/src/core/types/mention.ts (2 hunks)
  • space/core/components/editor/lite-text-read-only-editor.tsx (2 hunks)
  • space/core/components/editor/rich-text-editor.tsx (2 hunks)
  • space/core/components/editor/rich-text-read-only-editor.tsx (2 hunks)
  • web/core/components/editor/lite-text-editor/lite-text-editor.tsx (3 hunks)
  • web/core/components/editor/lite-text-editor/lite-text-read-only-editor.tsx (3 hunks)
  • web/core/components/editor/rich-text-editor/rich-text-editor.tsx (3 hunks)
  • web/core/components/editor/rich-text-editor/rich-text-read-only-editor.tsx (3 hunks)
  • web/core/components/pages/editor/editor-body.tsx (3 hunks)
  • web/core/components/pages/version/editor.tsx (3 hunks)
🚧 Files skipped from review as they are similar to previous changes (1)
  • packages/editor/src/core/extensions/extensions.tsx
🧰 Additional context used
🧬 Code Definitions (5)
packages/editor/src/core/extensions/read-only-extensions.tsx (1)
packages/editor/src/core/extensions/clipboard.ts (1) (1)
  • MarkdownClipboard (5-89)
packages/editor/src/core/extensions/mentions/extension.tsx (1)
packages/editor/src/core/extensions/mentions/extension-config.ts (1) (1)
  • CustomMentionExtensionConfig (15-61)
space/core/components/editor/rich-text-read-only-editor.tsx (2)
space/helpers/editor.helper.ts (1) (1)
  • getReadOnlyEditorFileHandlers (28-48)
space/core/components/editor/embeds/mentions/root.tsx (1) (1)
  • EditorMentionsRoot (8-17)
space/core/components/editor/lite-text-read-only-editor.tsx (2)
space/helpers/editor.helper.ts (1) (1)
  • getReadOnlyEditorFileHandlers (28-48)
space/core/components/editor/embeds/mentions/root.tsx (1) (1)
  • EditorMentionsRoot (8-17)
packages/editor/src/core/extensions/mentions/extension-config.ts (2)
packages/editor/src/core/types/mention.ts (1) (1)
  • TMentionHandler (26-28)
packages/editor/src/core/extensions/mentions/types.ts (1) (1)
  • TMentionComponentAttributes (10-14)
⏰ Context from checks skipped due to timeout of 90000ms (2)
  • GitHub Check: Analyze (javascript)
  • GitHub Check: Analyze (python)
🔇 Additional comments (27)
packages/editor/src/core/extensions/read-only-extensions.tsx (2)

27-27: Great addition of the MarkdownClipboard extension.

The integration of the MarkdownClipboard extension enhances clipboard functionality by properly serializing content to Markdown during copy operations. Based on the implementation in clipboard.ts, this extension handles complex cases like tables, lists, and nested structures more effectively.

Also applies to: 120-120


118-118: Proper configuration adjustment for clipboard handling.

Setting transformCopiedText: false in the Markdown extension is the correct approach as it prevents conflicts with the newly added MarkdownClipboard extension. This change allows the custom clipboard handler to take full control of text serialization during copy operations.

packages/editor/src/core/types/mention.ts (1)

2-2: Augmented support for entity details in mentions

The addition of IUserLite import and the new optional getMentionedEntityDetails method in the TReadOnlyMentionHandler type enhances the mention system by allowing retrieval of display names for mentioned entities. This is a good improvement that will help with mention rendering consistency.

Also applies to: 23-23

packages/editor/src/core/extensions/mentions/extension.tsx (1)

12-12: Successfully propagated entity details functionality

The changes correctly integrate the new getMentionedEntityDetails method from the component props into the extension options, enabling the feature to be used within the extension.

Also applies to: 18-18

space/core/components/editor/rich-text-editor.tsx (1)

9-10:

✅ Verification successful

Property name mismatch could cause display issues

The implementation uses member__display_name while other implementations use display_name. This inconsistency might be intentional but could lead to unexpected behavior if the property names should be consistent across the codebase.

Also applies to: 21-21, 26-28


🏁 Script executed:

#!/bin/bash
# Check for the different property names used in member objects

echo "Checking for member__display_name usage:"
rg -A 1 -B 1 "member__display_name" --type ts --type tsx

echo -e "\nChecking for display_name usage in similar context:"
rg -A 1 -B 1 "getUserDetails\(.+\)\.display_name" --type ts --type tsx
rg -A 1 -B 1 "getMemberById\(.+\)\.display_name" --type ts --type tsx

Length of output: 495


Please re-run the above script to verify the usage of the member__display_name and display_name properties across the codebase.

The original review comment raised a concern that the use of member__display_name (as seen in space/core/components/editor/rich-text-editor.tsx at lines 9–10, and similarly at lines 21 and 26–28) might be inconsistent with the more commonly used display_name (as seen in contexts like getUserDetails(...) and getMemberById(...).display_name). Because the initial verification attempt failed due to the improper file type handling, the updated script above bypasses that issue by explicitly searching in files with .ts and .tsx extensions.

Once you confirm whether the property naming is indeed inconsistent or if the divergence is intentional, please adjust the naming for consistency if needed.


🏁 Script executed:

#!/bin/bash
# Re-run search for member property names without relying on the built-in tsx file type.
echo "Searching for member__display_name in .ts and .tsx files:"
rg -g "*.tsx" -g "*.ts" -A 2 -B 2 "member__display_name"

echo -e "\nSearching for getUserDetails(...).display_name in .ts and .tsx files:"
rg -g "*.tsx" -g "*.ts" -A 2 -B 2 "getUserDetails\(.+\)\.display_name"

echo -e "\nSearching for getMemberById(...).display_name in .ts and .tsx files:"
rg -g "*.tsx" -g "*.ts" -A 2 -B 2 "getMemberById\(.+\)\.display_name"

Length of output: 7362


Consistency Verified: No Action Required

After verifying the codebase, it appears that the usage of member__display_name is consistent across all modules. In cases like the rich-text-editor component, the member’s property (member__display_name) is correctly mapped to the display_name field (e.g., via display_name: getMemberById(id)?.member__display_name ?? ""). This mapping is intentional, and similar patterns are observed in several other files. There is no inconsistency that would lead to display issues.

web/core/components/editor/lite-text-editor/lite-text-editor.tsx (1)

16-17:

❓ Verification inconclusive

Consistent implementation of entity details retrieval

The addition of the getMentionedEntityDetails method here follows the pattern established in other components but uses display_name directly. Make sure this is consistent with the expected data structure.

Also applies to: 62-64, 104-104


🏁 Script executed:

#!/bin/bash
# Check the implementation of getUserDetails to understand its return structure

echo "Checking implementation of getUserDetails:"
rg -A 10 -B 10 "export const useMember" --type ts

echo -e "\nChecking returned properties from getUserDetails:"
rg -A 3 "getUserDetails\(.*\)\?" --type ts --type tsx

Length of output: 3681


Consistent Entity Details Retrieval: Please Verify Data Structure Alignment

The new getMentionedEntityDetails method in web/core/components/editor/lite-text-editor/lite-text-editor.tsx (lines 16–17, as well as lines 62–64 and 104–104) follows a similar pattern as in other components—but it uses display_name directly. The automated check for the getUserDetails return structure (invoked via the useMember hook) yielded output from the TS files, yet the search for TSX files resulted in a file type error. This makes it difficult to conclusively confirm that the properties (including display_name) from getUserDetails match the usage in getMentionedEntityDetails.

Action items:

  • Manually verify that the data structure returned by getUserDetails (via useMember) includes the expected display_name property.
  • Confirm that the use of display_name in the getMentionedEntityDetails method is consistent with how other components process entity details.
  • Double-check consistency across all relevant sections (lines 16–17, 62–64, and 104–104).

Once you’ve confirmed that these usages align with the expected data structure, we can confidently approve the changes.

web/core/components/pages/editor/editor-body.tsx (1)

25-25: Consistent implementation of mention handling across editor components.

The addition of the useMember hook and implementation of getMentionedEntityDetails method provides proper user details retrieval for mentions in the collaborative document editor. This ensures that when content is copied with mentions, the display names are correctly retrieved.

Also applies to: 71-72, 197-197

web/core/components/editor/rich-text-editor/rich-text-editor.tsx (1)

11-12: Implementation enhances mention handling in rich text editor.

The integration of the useMember hook and getMentionedEntityDetails method maintains consistency with the implementation in other editor components, ensuring proper display of user mentions when content is copied.

Also applies to: 36-37, 64-64

web/core/components/pages/version/editor.tsx (1)

15-16: Consistent mention handling in version editor.

The addition of the useMember hook and implementation of getMentionedEntityDetails aligns with the pattern established in other editor components, ensuring proper display of user mentions when copying content.

Also applies to: 30-31, 115-115

space/core/components/editor/lite-text-read-only-editor.tsx (3)

10-11: Import added for user mentions support.

Good addition of the useMember hook, which is necessary for retrieving member information when rendering mentions.


22-24: Component structure improved to support user mention details.

Extracting getMemberById from the useMember hook is properly implemented to provide member information to the editor.


33-38: Member details now provided to mention handler.

Great implementation of the getMentionedEntityDetails method which retrieves the member's display name. The fallback to an empty string is a good defensive practice when a member isn't found.

web/core/components/editor/lite-text-editor/lite-text-read-only-editor.tsx (3)

11-12: Import added for user mentions support.

Good addition of the useMember hook, which is necessary for retrieving user information when rendering mentions.


27-28: User details hook properly implemented.

Extracting getUserDetails from the useMember hook is correctly implemented to provide user information to the editor.


46-46: User details now provided to mention handler.

The implementation of getMentionedEntityDetails looks good, consistently using the same pattern as the other editor components. The fallback to an empty string when a user isn't found is a good defensive practice.

space/core/components/editor/rich-text-read-only-editor.tsx (3)

10-11: Import added for user mentions support.

Good addition of the useMember hook, which is necessary for retrieving member information when rendering mentions.


22-24: Component structure improved to support user mention details.

Extracting getMemberById from the useMember hook is properly implemented to provide member information to the editor.


33-38: Member details now provided to mention handler.

Great implementation of the getMentionedEntityDetails method which retrieves the member's display name. The fallback to an empty string is a good defensive practice when a member isn't found.

packages/editor/src/core/extensions/mentions/extension-config.ts (6)

3-4: Added imports for markdown serialization.

Good addition of the necessary imports for markdown serialization, which is essential for implementing the copy-to-clipboard functionality.


8-8: Import updated to include necessary types.

The import for mention component types has been correctly updated to include TMentionComponentAttributes, which is needed for the new functionality.


12-12: Extended options type to support mention entity details.

Good addition of the getMentionedEntityDetails property to the options type, which allows the extension to retrieve and use mention entity details.


46-48: Added text rendering for mentions.

The renderText method is a crucial addition that ensures mentions are properly rendered as text when copied or exported.


50-59: Added markdown serialization for mentions.

Excellent implementation of markdown serialization in the storage. This is a key part of the fix for copying markdown to clipboard, ensuring that mentions are properly converted to text in the markdown format.


63-68: Well-implemented helper function for mention display text.

The getMentionDisplayText function is well-implemented with proper fallbacks:

  1. First tries to get the display name from entity details
  2. Falls back to the ID if display name isn't available
  3. Finally falls back to the entity identifier

This ensures robustness when rendering mentions in different contexts.

web/core/components/editor/rich-text-editor/rich-text-read-only-editor.tsx (3)

11-12: Well-structured import organization.

Adding a dedicated comment section for store hooks improves the code organization and makes it easier to understand the different types of imports being used.


27-29: Clean implementation of useMember hook.

The code follows the established patterns in the codebase with clear section comments and proper spacing.


46-46: Good implementation of getMentionedEntityDetails with robust fallback.

The implementation correctly retrieves user display names for mentions and includes a fallback to an empty string when no display name is found, preventing "undefined" from appearing in the UI.

✨ Finishing Touches
  • 📝 Generate Docstrings

🪧 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.
  • @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.

@VipinDevelops VipinDevelops changed the title Fix copy text Fix: Copy markdown to clipboard Feb 25, 2025
@Palanikannan1437 Palanikannan1437 self-requested a review February 25, 2025 10:48
@VipinDevelops VipinDevelops marked this pull request as ready for review February 25, 2025 10:55
@VipinDevelops VipinDevelops marked this pull request as draft February 25, 2025 10:55
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 (5)
packages/editor/src/core/extensions/clipboard.ts (5)

6-41: The MarkdownClipboard extension implementation looks good

The extension correctly determines when to use Markdown serialization based on content complexity and falls back to plain text when appropriate.

Consider adding a brief comment explaining the criteria used to determine when content should be copied as Markdown (lines 22-26) to make the logic more maintainable.

 const copyAsMarkdown =
+  // Copy as Markdown when content spans multiple lines or contains complex nested structures
   isMultiline ||
   slice.content.content.some(
     (node) => node.content.content.length > 1
   );

28-33: Consider error handling when plain text serialization is used

The current implementation assumes the node can be correctly serialized to plain text, but there might be edge cases.

 if (!copyAsMarkdown) {
-  return slice.content.content.map((node) =>
-    toPlainText(node, this.editor.schema)
-  ).join('')
+  try {
+    return slice.content.content.map((node) =>
+      toPlainText(node, this.editor.schema)
+    ).join('')
+  } catch (error) {
+    console.warn('Error serializing to plain text, falling back to default', error);
+    return '';
+  }
 }

34-35: Add error handling for Markdown serialization

The code assumes this.editor.storage.markdown.serializer always exists and works properly. Adding error handling would make the code more robust.

-return this.editor.storage.markdown.serializer.serialize(slice.content);
+try {
+  return this.editor.storage.markdown.serializer.serialize(slice.content);
+} catch (error) {
+  console.warn('Error serializing to markdown, falling back to plain text', error);
+  // Fall back to plain text
+  return slice.content.textBetween(0, slice.content.size, "\n");
+}

47-53: Utility function looks good, but consider scope

The getTextSerializers function is well-implemented but exported without a clear need for external usage. Consider keeping it as a private function unless it's used elsewhere.

-export function getTextSerializers(schema: Schema) {
+function getTextSerializers(schema: Schema) {

55-96: Well-structured textBetween implementation

The function handles the complexity of extracting text with appropriate block separators. A couple of minor improvements could be made:

  1. Consider making the blockSeparator configurable through a parameter with a default value
  2. The function is exported as default while others aren't, which is inconsistent
-export type PlainTextSerializer = (node: ProsemirrorNode) => string;
-export default function textBetween(
+type PlainTextSerializer = (node: ProsemirrorNode) => string;
+function textBetween(
   doc: ProsemirrorNode,
   from: number,
   to: number,
-  plainTextSerializers: Record<string, PlainTextSerializer | undefined>
+  plainTextSerializers: Record<string, PlainTextSerializer | undefined>,
+  blockSeparator: string = "\n"
 ): string {
   let text = "";
   let first = true;
-  const blockSeparator = "\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 d08bce3 and ec4f4e2.

📒 Files selected for processing (3)
  • packages/editor/package.json (1 hunks)
  • packages/editor/src/core/extensions/clipboard.ts (1 hunks)
  • packages/editor/src/core/extensions/extensions.tsx (2 hunks)
🔇 Additional comments (3)
packages/editor/package.json (1)

66-66: Addition of prosemirror-model dependency looks good

This dependency is correctly added to support the new clipboard functionality for Markdown serialization.

packages/editor/src/core/extensions/extensions.tsx (2)

39-39: Correct import of the new MarkdownClipboard extension

The import is properly placed with other related imports.


145-145: Good placement of the MarkdownClipboard extension

The extension is strategically positioned after the Markdown extension, which makes sense for the clipboard functionality to work properly with Markdown serialization.

@Palanikannan1437 Palanikannan1437 marked this pull request as ready for review February 25, 2025 10:57
@VipinDevelops
Copy link
Collaborator Author

Hey @Palanikannan1437 Can you review this PR?

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

🧹 Nitpick comments (4)
packages/editor/src/core/extensions/clipboard.ts (4)

22-27: Improve readability of the copy condition.

The condition for determining when to copy as Markdown is complex and could benefit from better naming or documentation.

-            const copyAsMarkdown =
-              isMultiline ||
-              slice.content.content.some(
-                (node) => node.content.content.length > 1
-              );
+            // Copy as Markdown if content is multiline or contains complex nodes with nested structure
+            const hasComplexNodes = slice.content.content.some(
+              (node) => node.content.content.length > 1
+            );
+            const copyAsMarkdown = isMultiline || hasComplexNodes;

80-90: Improve readability of block separator logic.

The complex condition for deciding when to add block separators could be extracted into a named helper function for clarity.

+    const shouldAddBlockSeparator = (node: ProsemirrorNode, text: string): boolean => {
+      return node.isBlock && ((node.isLeaf && text) || node.isTextblock) && !!blockSeparator;
+    };

-    if (
-      node.isBlock &&
-      ((node.isLeaf && nodeText) || node.isTextblock) &&
-      blockSeparator
-    ) {
+    if (shouldAddBlockSeparator(node, nodeText)) {
       if (first) {
         first = false;
       } else {
         text += blockSeparator;
       }
     }

63-64: Improve variable name clarity.

The variable first could be more descriptive to better convey its purpose.

-  let first = true;
+  let isFirstBlock = true;

   // And later in the code:
-      if (first) {
-        first = false;
+      if (isFirstBlock) {
+        isFirstBlock = false;

2-3: Inconsistent import styles detected.

There's inconsistency in the import quotes (double vs. single). Maintain consistency with the project's style guide.

import { Extension } from "@tiptap/core";
-import { Schema, Node as ProsemirrorNode } from "@tiptap/pm/model";
-import { Plugin, PluginKey } from '@tiptap/pm/state';
+import { Schema, Node as ProsemirrorNode } from "@tiptap/pm/model";
+import { Plugin, PluginKey } from "@tiptap/pm/state";
📜 Review details

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

📥 Commits

Reviewing files that changed from the base of the PR and between ec4f4e2 and 2dea7e8.

📒 Files selected for processing (1)
  • packages/editor/src/core/extensions/clipboard.ts (1 hunks)
⏰ Context from checks skipped due to timeout of 90000ms (2)
  • GitHub Check: Analyze (javascript)
  • GitHub Check: Analyze (python)
🔇 Additional comments (2)
packages/editor/src/core/extensions/clipboard.ts (2)

1-97: Overall implementation looks sound.

The implementation of the Markdown clipboard functionality is well-structured and provides a good enhancement to the editor's copy/paste capabilities. The extension correctly determines when to serialize content as Markdown versus plain text, with appropriate helper functions to support this functionality.


66-93:

❓ Verification inconclusive

Consider performance optimization for large documents.

The nodesBetween method traverses potentially many nodes, which could be a performance concern for very large documents. Consider adding early return conditions or pagination for extremely large selections.


🏁 Script executed:

#!/bin/bash
# Check if there are any large document handling mechanisms already in place
rg "nodesBetween" --type ts -A 5 -B 5

Length of output: 4306


Performance Optimization Suggestion: Review Node Traversal for Large Documents

The current implementation in packages/editor/src/core/extensions/clipboard.ts (lines 66–93) uses doc.nodesBetween to iterate over all nodes in the selected range. While this approach works well for typical document sizes, it could become a performance concern with very large documents. Similar patterns elsewhere in the codebase (for example, in packages/editor/src/core/helpers/insert-empty-paragraph-at-node-boundary.ts, where an early exit is used) suggest that additional safeguards might be beneficial.

Please evaluate whether introducing an early termination condition or paginating the iteration for extensive selections could help improve performance. Testing with larger document sizes might clarify if this optimization is necessary in the context of your application.

@VipinDevelops VipinDevelops marked this pull request as draft February 25, 2025 11:22
@makeplane makeplane deleted a comment from coderabbitai bot Mar 4, 2025
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

♻️ Duplicate comments (4)
packages/editor/src/core/extensions/clipboard.ts (4)

1-1: 🛠️ Refactor suggestion

Remove unused import.

The serialize import from "node:v8" is not used anywhere in this file and should be removed.

-import { serialize } from "node:v8";

9-14: 🛠️ Refactor suggestion

Address unused clipboard configuration options.

The extension defines transformPastedText and transformCopiedText options but never actually uses them in the implementation. Either implement the functionality to use these options or remove them to avoid confusion.

  addOptions() {
    return {
      transformPastedText: false,
      transformCopiedText: true,
    };
  },

The clipboardTextSerializer should check these options before transforming content:

  clipboardTextSerializer: (slice) => {
+   const { transformCopiedText } = this.options;
+   if (!transformCopiedText) {
+     return null; // Let the default clipboard handler take over
+   }
    const markdownSerializer = this.editor.storage.markdown.serializer;

22-22: ⚠️ Potential issue

Add error handling for missing Markdown serializer.

The code directly accesses this.editor.storage.markdown.serializer without checking if it exists. This could cause runtime errors if the Markdown extension is not loaded or initialized properly.

-            const markdownSerializer = this.editor.storage.markdown.serializer;
+            if (!this.editor.storage.markdown?.serializer) {
+              console.warn('Markdown serializer not found, falling back to default clipboard behavior');
+              return null; // Let the default clipboard handler take over
+            }
+            const markdownSerializer = this.editor.storage.markdown.serializer;

65-67: ⚠️ Potential issue

Add null check and default return value.

The final part of the clipboardTextSerializer lacks proper null checks and a default return value.

-            const targetNode = traverseToParentOfLeaf(slice.content.firstChild, slice.content, slice.openStart);
+            const targetNode = traverseToParentOfLeaf(slice.content.firstChild || null, slice.content, slice.openStart);
             return markdownSerializer.serialize(targetNode);
+            // Default fallback - this code is unreachable but added for completeness
+            return null;
🧹 Nitpick comments (1)
packages/editor/src/core/extensions/clipboard.ts (1)

1-72: Implement feature to handle pasted text transformation.

The extension has an option transformPastedText but doesn't implement any functionality for handling pasted text. This should be implemented to make the option useful.

        props: {
          clipboardTextSerializer: (slice) => {
            // Current implementation handling copied text
          },
+         handlePaste: (view, event, slice) => {
+           const { transformPastedText } = this.options;
+           if (!transformPastedText) {
+             return false; // Let the default paste handler take over
+           }
+           
+           // Handle markdown text pasted into the editor
+           // This is just a skeleton - implement according to your requirements
+           if (event.clipboardData && event.clipboardData.getData('text/plain')) {
+             const text = event.clipboardData.getData('text/plain');
+             // Process the text if needed
+             // Insert the processed content
+             return true; // Signal that the paste was handled
+           }
+           
+           return false; // Let the default paste handler take over
+         },
        },
📜 Review details

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

📥 Commits

Reviewing files that changed from the base of the PR and between c8ee874 and 0eac8a0.

📒 Files selected for processing (1)
  • packages/editor/src/core/extensions/clipboard.ts (1 hunks)
⏰ Context from checks skipped due to timeout of 90000ms (2)
  • GitHub Check: Analyze (javascript)
  • GitHub Check: Analyze (python)

Copy link
Collaborator

Choose a reason for hiding this comment

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

transformCopiedText: true,

you have to make this false right @VipinDevelops

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

♻️ Duplicate comments (1)
packages/editor/src/core/extensions/clipboard.ts (1)

14-14: 🛠️ Refactor suggestion

Add error handling for missing Markdown serializer.

The code directly accesses this.editor.storage.markdown.serializer without checking if it exists. This could cause runtime errors if the Markdown extension is not loaded or initialized properly.

-            const markdownSerializer = this.editor.storage.markdown.serializer;
+            const markdownSerializer = this.editor.storage.markdown?.serializer;
+            if (!markdownSerializer) {
+              console.warn('Markdown serializer not found, falling back to plain text');
+              return slice.content.textBetween(0, slice.content.size, '\n');
+            }
🧹 Nitpick comments (1)
packages/editor/src/core/extensions/clipboard.ts (1)

72-72: Add null check for firstChild access.

The code assumes slice.content.firstChild exists when passing it to traverseToParentOfLeaf. This could lead to runtime errors if the slice has no content.

-              const targetNode = traverseToParentOfLeaf(slice.content.firstChild, slice.content, slice.openStart);
+              const targetNode = traverseToParentOfLeaf(slice.content.firstChild || null, slice.content, slice.openStart);
📜 Review details

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

📥 Commits

Reviewing files that changed from the base of the PR and between 35376d4 and 44bd3c6.

📒 Files selected for processing (4)
  • packages/editor/src/core/extensions/clipboard.ts (1 hunks)
  • packages/editor/src/core/extensions/extensions.tsx (2 hunks)
  • packages/editor/src/core/extensions/index.ts (1 hunks)
  • packages/editor/src/core/extensions/read-only-extensions.tsx (2 hunks)
🚧 Files skipped from review as they are similar to previous changes (1)
  • packages/editor/src/core/extensions/extensions.tsx
⏰ Context from checks skipped due to timeout of 90000ms (2)
  • GitHub Check: Analyze (javascript)
  • GitHub Check: Analyze (python)
🔇 Additional comments (11)
packages/editor/src/core/extensions/index.ts (1)

26-26: Added export for the new clipboard extension.

This change exports the clipboard module, making the MarkdownClipboard extension accessible to other parts of the codebase. This is a necessary addition to support the fix for copying markdown to clipboard.

packages/editor/src/core/extensions/read-only-extensions.tsx (3)

27-27: Added new MarkdownClipboard extension import.

Importing the MarkdownClipboard extension from the extensions directory to use it in the read-only editor configuration.


125-125: Changed Markdown configuration to disable built-in text transformation.

Setting transformCopiedText: false disables the built-in Markdown text transformation when copying, allowing the new MarkdownClipboard extension to handle this functionality instead.


127-127: Added MarkdownClipboard extension to the read-only editor.

Added the MarkdownClipboard extension to the list of extensions for the read-only editor, enabling proper markdown serialization when copying content.

packages/editor/src/core/extensions/clipboard.ts (7)

1-4: Clean import statements for the new clipboard extension.

The imports are correctly specified, importing only the necessary components from Tiptap and ProseMirror.


5-7: New MarkdownClipboard extension.

The extension is properly created with a descriptive name "markdownClipboard".


8-17: Implemented clipboardTextSerializer for markdown support.

The extension adds a ProseMirror plugin with a custom clipboardTextSerializer implementation to handle markdown serialization when copying content.


22-31: Table content processing with proper null checks.

The table content processing function handles serialization of table cells to markdown format. The implementation includes proper null checks using optional chaining, which is good for preventing runtime errors.


33-41: Table row handling with safer property access.

The table row handling now uses proper null checks with optional chaining and default values, which is an improvement over previous implementations. This prevents potential null reference errors when dealing with table structures.


43-67: Improved node traversal function.

The traverseToParentOfLeaf function has been rewritten to use a while loop instead of recursion, which is more efficient and less prone to stack overflow errors. The implementation includes proper null checks and safely navigates the node structure.


69-74: Add default fallback return value.

The function doesn't have a default return value for cases that might fall through all the conditional checks. It's important to add a default return to ensure consistent behavior.

            if (slice.content.childCount > 1) {
              return markdownSerializer.serialize(slice.content);
            } else {
              const targetNode = traverseToParentOfLeaf(slice.content.firstChild, slice.content, slice.openStart);
              return markdownSerializer.serialize(targetNode);
            }
+            // Default fallback - this line should never be reached due to the if/else structure above
+            // but adding it for code safety
+            return markdownSerializer.serialize(slice.content);

@Palanikannan1437 Palanikannan1437 marked this pull request as draft March 18, 2025 05:03
@Palanikannan1437 Palanikannan1437 marked this pull request as ready for review March 18, 2025 08:31
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 (1)
packages/editor/src/core/extensions/clipboard.ts (1)

69-83: Consider optional chaining in line 75.
Replacing explicit checks with optional chaining can simplify the while condition.

- while (currentNode && currentNode.content && currentNode.childCount === 1 && currentNode.firstChild) {
+ while (currentNode?.content && currentNode?.childCount === 1 && currentNode?.firstChild) {
🧰 Tools
🪛 Biome (1.9.4)

[error] 75-75: Change to an optional chain.

Unsafe fix: Change to an optional chain.

(lint/complexity/useOptionalChain)

📜 Review details

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

📥 Commits

Reviewing files that changed from the base of the PR and between 44bd3c6 and 366ed38.

📒 Files selected for processing (1)
  • packages/editor/src/core/extensions/clipboard.ts (1 hunks)
🧰 Additional context used
🪛 Biome (1.9.4)
packages/editor/src/core/extensions/clipboard.ts

[error] 75-75: Change to an optional chain.

Unsafe fix: Change to an optional chain.

(lint/complexity/useOptionalChain)

🔇 Additional comments (7)
packages/editor/src/core/extensions/clipboard.ts (7)

1-4: Imports look good.
No issues identified.


5-7: Extension naming is clear.
Straightforward naming, no concerns.


8-12: Plugin creation is clean.
Well-defined plugin key and setup.


13-21: Add error handling for missing Markdown serializer.
If the Markdown extension is not loaded, this could lead to runtime errors.


22-31: Table content processing logic looks correct.
The optional chaining ensures safe cell content access.


33-41: Table row handling looks well-structured.
Using early returns for single vs. multiple row/cell cases is clear.


43-67: Traverse function is logically sound.
The loop correctly returns the node when certain conditions are met.

@VipinDevelops VipinDevelops changed the title Fix: Copy markdown to clipboard [PE-298] Fix: Copy markdown to clipboard Mar 18, 2025
Copy link

makeplane bot commented Mar 19, 2025

Pull Request Linked with Plane Work Items

Comment Automatically Generated by Plane

@sriramveeraghanta sriramveeraghanta merged commit 6bafdb6 into preview Mar 24, 2025
5 of 6 checks passed
@sriramveeraghanta sriramveeraghanta deleted the fix-copy_text branch March 24, 2025 07:02
@pushya22 pushya22 linked an issue Mar 24, 2025 that may be closed by this pull request
1 task
@hpflatorre
Copy link

Is there any revision release planned for the next days including this fix?

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.

[bug]: Copying text from issue description carries unwanted HTML
4 participants