Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Fix: Copy markdown to clipboard #6675

Open
wants to merge 20 commits into
base: preview
Choose a base branch
from
Open

Fix: Copy markdown to clipboard #6675

wants to merge 20 commits into from

Conversation

VipinDevelops
Copy link
Collaborator

@VipinDevelops VipinDevelops commented Feb 25, 2025

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

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

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.

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
Loading
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
Loading

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!
🥕🐇

✨ Finishing Touches
  • 📝 Generate Docstrings

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

@@ -63,6 +63,7 @@
"lowlight": "^3.0.0",
"lucide-react": "^0.469.0",
"prosemirror-codemark": "^0.4.2",
"prosemirror-model": "^1.24.1",
Copy link
Collaborator

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

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.

Comment on lines 8 to 13
addOptions() {
return {
transformPastedText: false,
transformCopiedText: false,
}
},
Copy link
Contributor

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 the addOptions() method defines transformPastedText and transformCopiedText, 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 and read-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.

Comment on lines 19 to 36
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);
},
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

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.

Suggested change
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);
},

Comment on lines 29 to 32
return slice.content.content.map((node) =>
toPlainText(node, this.editor.schema)
).join('')

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

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.

Suggested change
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('')
: '';
}

@VipinDevelops VipinDevelops marked this pull request as draft February 25, 2025 11:22
@VipinDevelops VipinDevelops marked this pull request as ready for review February 28, 2025 08:09
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: 1

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

20-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;
+            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 implemented

This 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 maintainability

The 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

📥 Commits

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

📒 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 unused

The extension provides configuration options for transforming clipboard content to Markdown, but only transformCopiedText is being used in the implementation while transformPastedText 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 good

The 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 content

The 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 detection

The 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 serialization

The final decision point clearly determines whether to serialize to Markdown or plain text based on the analysis performed throughout the function.

Comment on lines +74 to +90
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
);
}
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

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.

Suggested change
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)

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.

2 participants