-
Notifications
You must be signed in to change notification settings - Fork 2k
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: Copy markdown to clipboard #6675
base: preview
Are you sure you want to change the base?
Conversation
WalkthroughThis pull request introduces a new clipboard extension for the Tiptap editor called Changes
Sequence Diagram(s)sequenceDiagram
participant User
participant Editor
participant MarkdownClipboard
participant Serializer
User->>Editor: Trigger copy/paste event
Editor->>MarkdownClipboard: Handle clipboard operation
MarkdownClipboard->>Serializer: Evaluate content & node types
Serializer-->>MarkdownClipboard: Return Markdown or plain text
MarkdownClipboard-->>Editor: Provide processed clipboard content
sequenceDiagram
participant User
participant TableControls
participant EditorView
User->>TableControls: Triple-click on table cell
TableControls->>TableControls: Check if node is a table cell
alt Is table cell
TableControls->>EditorView: Compute line boundaries
TableControls->>EditorView: Dispatch transaction for selection update
else Not table cell
TableControls-->>User: Return false (event unhandled)
end
Poem
✨ Finishing Touches
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? 🪧 TipsChatThere are 3 ways to chat with CodeRabbit:
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)
Other keywords and placeholders
CodeRabbit Configuration File (
|
There was a problem hiding this 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 goodThe 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 usedThe 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 serializationThe 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 scopeThe
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 implementationThe function handles the complexity of extracting text with appropriate block separators. A couple of minor improvements could be made:
- Consider making the blockSeparator configurable through a parameter with a default value
- 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
📒 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 goodThis 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 extensionThe import is properly placed with other related imports.
145-145
: Good placement of the MarkdownClipboard extensionThe extension is strategically positioned after the Markdown extension, which makes sense for the clipboard functionality to work properly with Markdown serialization.
Hey @Palanikannan1437 Can you review this PR? |
packages/editor/package.json
Outdated
@@ -63,6 +63,7 @@ | |||
"lowlight": "^3.0.0", | |||
"lucide-react": "^0.469.0", | |||
"prosemirror-codemark": "^0.4.2", | |||
"prosemirror-model": "^1.24.1", |
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Don't do this, instead import from @tiptap/pm/model
There was a problem hiding this 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
📒 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 5Length 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) usesdoc.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, inpackages/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.
addOptions() { | ||
return { | ||
transformPastedText: false, | ||
transformCopiedText: false, | ||
} | ||
}, |
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
💡 Verification agent
🧩 Analysis chain
Unused configuration options detected.
The extension defines transformPastedText
and transformCopiedText
options that are never actually used in the implementation. Either implement the functionality to use these options or remove them to avoid confusion.
🏁 Script executed:
#!/bin/bash
# Check if these options are used elsewhere in the codebase
rg "transformPastedText|transformCopiedText" --type ts
Length of output: 484
Action: Address Unused Clipboard Configuration Options
- In
packages/editor/src/core/extensions/clipboard.ts
theaddOptions()
method definestransformPastedText
andtransformCopiedText
, but the extension’s implementation does not actually use these options. - We verified via a search that these configuration keys are also referenced externally (e.g., in
extensions.tsx
andread-only-extensions.tsx
), which suggests they are expected to control behavior. - Suggestion: Either implement the logic within the clipboard extension to conditionally transform pasted/copied text based on these options or remove them to avoid confusion.
clipboardTextSerializer: (slice) => { | ||
const isMultiline = slice.content.childCount > 1; | ||
|
||
const copyAsMarkdown = | ||
isMultiline || | ||
slice.content.content.some( | ||
(node) => node.content.content.length > 1 | ||
); | ||
|
||
if (!copyAsMarkdown) { | ||
return slice.content.content.map((node) => | ||
toPlainText(node, this.editor.schema) | ||
).join('') | ||
|
||
} | ||
|
||
return this.editor.storage.markdown.serializer.serialize(slice.content); | ||
}, |
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
🛠️ 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.
- return this.editor.storage.markdown.serializer.serialize(slice.content);
+ if (!this.editor.storage.markdown?.serializer) {
+ console.warn('Markdown serializer not found, falling back to plain text');
+ return slice.content.content.map((node) =>
+ toPlainText(node, this.editor.schema)
+ ).join('');
+ }
+ return this.editor.storage.markdown.serializer.serialize(slice.content);
📝 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.
clipboardTextSerializer: (slice) => { | |
const isMultiline = slice.content.childCount > 1; | |
const copyAsMarkdown = | |
isMultiline || | |
slice.content.content.some( | |
(node) => node.content.content.length > 1 | |
); | |
if (!copyAsMarkdown) { | |
return slice.content.content.map((node) => | |
toPlainText(node, this.editor.schema) | |
).join('') | |
} | |
return this.editor.storage.markdown.serializer.serialize(slice.content); | |
}, | |
clipboardTextSerializer: (slice) => { | |
const isMultiline = slice.content.childCount > 1; | |
const copyAsMarkdown = | |
isMultiline || | |
slice.content.content.some( | |
(node) => node.content.content.length > 1 | |
); | |
if (!copyAsMarkdown) { | |
return slice.content.content.map((node) => | |
toPlainText(node, this.editor.schema) | |
).join(''); | |
} | |
if (!this.editor.storage.markdown?.serializer) { | |
console.warn('Markdown serializer not found, falling back to plain text'); | |
return slice.content.content.map((node) => | |
toPlainText(node, this.editor.schema) | |
).join(''); | |
} | |
return this.editor.storage.markdown.serializer.serialize(slice.content); | |
}, |
return slice.content.content.map((node) => | ||
toPlainText(node, this.editor.schema) | ||
).join('') | ||
|
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
🛠️ Refactor suggestion
Add safeguards for content structure assumptions.
The code assumes certain content structure exists without verification, which could lead to runtime errors.
if (!copyAsMarkdown) {
- return slice.content.content.map((node) =>
+ return Array.isArray(slice.content.content) ? slice.content.content.map((node) =>
toPlainText(node, this.editor.schema)
- ).join('')
+ ).join('') : '';
}
📝 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.
return slice.content.content.map((node) => | |
toPlainText(node, this.editor.schema) | |
).join('') | |
if (!copyAsMarkdown) { | |
return Array.isArray(slice.content.content) | |
? slice.content.content.map((node) => | |
toPlainText(node, this.editor.schema) | |
).join('') | |
: ''; | |
} |
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Actionable comments posted: 1
♻️ Duplicate comments (1)
packages/editor/src/core/extensions/clipboard.ts (1)
20-22
:⚠️ Potential issueAdd 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 (2)
packages/editor/src/core/extensions/table/table/table-controls.ts (1)
19-34
: Triple-click selection handler for table cells is well implementedThis new method enhances the user experience by allowing selection of all text within a table cell when triple-clicked, which is standard behavior in text editors.
However, consider expanding this functionality to also handle tableHeader cells for consistent behavior:
- if (node.type.name === 'tableCell') { + if (node.type.name === 'tableCell' || node.type.name === 'tableHeader') {packages/editor/src/core/extensions/clipboard.ts (1)
35-148
: Consider refactoring complex conditional logic for better maintainabilityThe
clipboardTextSerializer
function contains deep nesting and complex conditional logic that makes it difficult to follow and maintain. Consider extracting some of the logic into separate helper functions with descriptive names.For example, you could create helper functions like:
isComplexTableContent(slice)
containsComplexListInTableCell(cell)
shouldConvertTableToMarkdown(slice)
This would make the main function more readable and easier to maintain.
🧰 Tools
🪛 Biome (1.9.4)
[error] 74-74: Change to an optional chain.
Unsafe fix: Change to an optional chain.
(lint/complexity/useOptionalChain)
[error] 135-135: 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
📒 Files selected for processing (2)
packages/editor/src/core/extensions/clipboard.ts
(1 hunks)packages/editor/src/core/extensions/table/table/table-controls.ts
(1 hunks)
🧰 Additional context used
🪛 Biome (1.9.4)
packages/editor/src/core/extensions/clipboard.ts
[error] 74-74: Change to an optional chain.
Unsafe fix: Change to an optional chain.
(lint/complexity/useOptionalChain)
[error] 135-135: Change to an optional chain.
Unsafe fix: Change to an optional chain.
(lint/complexity/useOptionalChain)
⏰ Context from checks skipped due to timeout of 90000ms (1)
- GitHub Check: Analyze (javascript)
🔇 Additional comments (5)
packages/editor/src/core/extensions/clipboard.ts (5)
5-13
: Extension options configuration looks good, but one option is unusedThe extension provides configuration options for transforming clipboard content to Markdown, but only
transformCopiedText
is being used in the implementation whiletransformPastedText
is defined but never referenced.Either implement the feature for transforming pasted text or remove the unused option to avoid confusion.
24-35
: Table content processing helper function looks goodThe
processTableContent
function elegantly handles serializing table content to Markdown format with tab separation between cells and newlines between rows.
83-90
: Good implementation of type checking for complex contentThe code effectively detects if there are multiple types of nodes and handles them appropriately by serializing to Markdown when needed.
103-122
: Well-structured table complexity detectionThe IIFE pattern used to check for multiple rows or cells in tables is a good approach to encapsulate this logic. The implementation correctly identifies complex tables that should be processed with special handling.
145-148
: Clear decision point for Markdown serializationThe final decision point clearly determines whether to serialize to Markdown or plain text based on the analysis performed throughout the function.
if (tableNode.content.firstChild && tableNode.content.firstChild.content.firstChild) { | ||
const firstTableCell = tableNode.content.firstChild.content.firstChild; | ||
const cellContainsMultipleBlocks = firstTableCell.content.childCount > 1; | ||
let containsComplexList = false; | ||
const listHasMultipleItemsInTable = firstTableCell.content.firstChild!.content!.childCount > 1; | ||
const cellContainsList = firstTableCell.content.content.some( | ||
(node) => listTypes.includes(node.type.name) | ||
); | ||
|
||
const allNodes = firstTableCell.content.content; | ||
const hasMultipleTypes = new Set(allNodes.map(n => n.type.name)).size > 1; | ||
|
||
if (hasMultipleTypes) { | ||
return markdownSerializer.serialize( | ||
slice.content.firstChild.content.firstChild?.content.firstChild?.content | ||
); | ||
} |
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
🛠️ Refactor suggestion
Use optional chaining to prevent potential null reference errors
According to static analysis, there are potential null reference issues in this code block that should be addressed with optional chaining.
- if (tableNode.content.firstChild && tableNode.content.firstChild.content.firstChild) {
+ if (tableNode.content.firstChild?.content?.firstChild) {
const firstTableCell = tableNode.content.firstChild.content.firstChild;
const cellContainsMultipleBlocks = firstTableCell.content.childCount > 1;
let containsComplexList = false;
- const listHasMultipleItemsInTable = firstTableCell.content.firstChild!.content!.childCount > 1;
+ const listHasMultipleItemsInTable = firstTableCell.content.firstChild?.content?.childCount > 1 || false;
Similarly for the other optional chain suggestion at line 135.
📝 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.
if (tableNode.content.firstChild && tableNode.content.firstChild.content.firstChild) { | |
const firstTableCell = tableNode.content.firstChild.content.firstChild; | |
const cellContainsMultipleBlocks = firstTableCell.content.childCount > 1; | |
let containsComplexList = false; | |
const listHasMultipleItemsInTable = firstTableCell.content.firstChild!.content!.childCount > 1; | |
const cellContainsList = firstTableCell.content.content.some( | |
(node) => listTypes.includes(node.type.name) | |
); | |
const allNodes = firstTableCell.content.content; | |
const hasMultipleTypes = new Set(allNodes.map(n => n.type.name)).size > 1; | |
if (hasMultipleTypes) { | |
return markdownSerializer.serialize( | |
slice.content.firstChild.content.firstChild?.content.firstChild?.content | |
); | |
} | |
if (tableNode.content.firstChild?.content?.firstChild) { | |
const firstTableCell = tableNode.content.firstChild.content.firstChild; | |
const cellContainsMultipleBlocks = firstTableCell.content.childCount > 1; | |
let containsComplexList = false; | |
const listHasMultipleItemsInTable = firstTableCell.content.firstChild?.content?.childCount > 1 || false; | |
const cellContainsList = firstTableCell.content.content.some( | |
(node) => listTypes.includes(node.type.name) | |
); | |
const allNodes = firstTableCell.content.content; | |
const hasMultipleTypes = new Set(allNodes.map(n => n.type.name)).size > 1; | |
if (hasMultipleTypes) { | |
return markdownSerializer.serialize( | |
slice.content.firstChild.content.firstChild?.content.firstChild?.content | |
); | |
} |
🧰 Tools
🪛 Biome (1.9.4)
[error] 74-74: Change to an optional chain.
Unsafe fix: Change to an optional chain.
(lint/complexity/useOptionalChain)
Basic Markdown
Screen.Recording.2025-02-25.at.4.05.09.PM.mov
Triple click
Screen.Recording.2025-02-27.at.12.17.08.PM.mov
Table
Screen.Recording.2025-02-28.at.1.38.28.AM.mov
Summary by CodeRabbit