Skip to content

[WIKI-498] regression: table bugs#7631

Merged
sriramveeraghanta merged 1 commit intopreviewfrom
fix/table-bugs
Aug 25, 2025
Merged

[WIKI-498] regression: table bugs#7631
sriramveeraghanta merged 1 commit intopreviewfrom
fix/table-bugs

Conversation

@aaryan610
Copy link
Member

@aaryan610 aaryan610 commented Aug 22, 2025

Description

This PR fixes the following-

  1. DND not working for tables.
  2. Select column/row not working after any column/row is deleted.

Type of Change

  • Bug fix (non-breaking change which fixes an issue)

Summary by CodeRabbit

  • Bug Fixes

    • Improved reliability of table row/column drag handles, preventing incorrect or stale handles after table edits.
    • Fixed drag/selection behavior for entire tables to ensure accurate positioning during drag operations.
  • Performance

    • Optimized table drag handle updates by reusing valid decorations when structure hasn’t changed, reducing unnecessary recalculations.
  • Refactor

    • Enhanced internal tracking of table structure (size and position) to better detect changes and keep drag handles in sync.

@makeplane
Copy link

makeplane bot commented Aug 22, 2025

Pull Request Linked with Plane Work Items

Comment Automatically Generated by Plane

@coderabbitai
Copy link
Contributor

coderabbitai bot commented Aug 22, 2025

Walkthrough

Adds table structure tracking (width/height and node position) to column/row drag-handle plugins to decide when to reuse or rebuild decorations. Updates drag-handle core to special-case table node selection by adjusting the resolved position and reorders checks to handle tables before blockquotes.

Changes

Cohort / File(s) Summary of changes
Table drag-handle plugins
packages/editor/src/core/extensions/table/plugins/drag-handles/column/plugin.ts, packages/editor/src/core/extensions/table/plugins/drag-handles/row/plugin.ts
Extend plugin state to include table dimensions and node position; add structure-change detection; two-phase staleness check (structure vs. mapped decorations); reuse or rebuild decorations accordingly; always persist updated structure fields. Public types updated to include new optional fields.
Core drag-handle
packages/editor/src/core/plugins/drag-handle.ts
Add table-specific handling in node selection: adjust dragged node position for tables; reorder conditionals to handle tables before blockquotes; no API surface changes.

Sequence Diagram(s)

sequenceDiagram
  autonumber
  actor User
  participant Editor
  participant ColumnPlugin as Column Drag-Handle Plugin
  participant RowPlugin as Row Drag-Handle Plugin

  User->>Editor: Interact with table drag handle
  Editor->>ColumnPlugin: apply(tr, prevState)
  Note right of ColumnPlugin: Compute tableMap, table.pos, width
  ColumnPlugin->>ColumnPlugin: tableStructureChanged = (prev.width,pos) vs current
  alt Structure unchanged
    ColumnPlugin->>ColumnPlugin: Map decorations via tr.mapping
    alt Decorations valid
      ColumnPlugin-->>Editor: Reuse mapped decorations + update width/pos
    else Decorations stale
      ColumnPlugin-->>Editor: Rebuild decorations + update width/pos
    end
  else Structure changed
    ColumnPlugin-->>Editor: Rebuild decorations + update width/pos
  end

  Editor->>RowPlugin: apply(tr, prevState)
  Note right of RowPlugin: Compute tableMap, table.pos, height
  RowPlugin->>RowPlugin: tableStructureChanged = (prev.height,pos) vs current
  alt Structure unchanged
    RowPlugin->>RowPlugin: Map decorations via tr.mapping
    alt Decorations valid
      RowPlugin-->>Editor: Reuse mapped decorations + update height/pos
    else Decorations stale
      RowPlugin-->>Editor: Rebuild decorations + update height/pos
    end
  else Structure changed
    RowPlugin-->>Editor: Rebuild decorations + update height/pos
  end
Loading
sequenceDiagram
  autonumber
  actor User
  participant Editor
  participant DragHandle as handleNodeSelection

  User->>Editor: Drag handle on node
  Editor->>DragHandle: handleNodeSelection(event)
  alt Node is table
    Note right of DragHandle: Adjust draggedNodePos (decrement by 2)
  else Node is blockquote
    DragHandle->>DragHandle: nodePosAtDOMForBlockQuotes(...)
  else Other node
    DragHandle->>DragHandle: Resolve parent position and adjust for lists/tasks
  end
  DragHandle-->>Editor: Final selection/position
Loading

Estimated code review effort

🎯 3 (Moderate) | ⏱️ ~25 minutes

Possibly related PRs

Suggested reviewers

  • Palanikannan1437
  • sriramveeraghanta
  • VipinDevelops

Poem

A nibble of code, a hop through rows,
Columns align where the table grows.
I twitch my whiskers—positions set,
Widths and heights remembered yet.
With gentle paws I drag, I glide—
Fresh decorations by my side.
Thump! The table’s ready to ride. 🐇✨

Tip

🔌 Remote MCP (Model Context Protocol) integration is now available!

Pro plan users can now connect to remote MCP servers from the Integrations page. Connect with popular remote MCPs such as Notion and Linear to add more context to your reviews and chats.

✨ Finishing Touches
  • 📝 Generate Docstrings
🧪 Generate unit tests
  • Create PR with unit tests
  • Post copyable unit tests in a comment
  • Commit unit tests in branch fix/table-bugs

Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out.

❤️ 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.
    • 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.
  • 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 the files in the src/scheduler package and generate a class diagram using mermaid and a README in the markdown format.

Support

Need help? Create a ticket on our support page for assistance with any issues or questions.

CodeRabbit Commands (Invoked using PR/Issue comments)

Type @coderabbitai help to get the list of available commands.

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

Status, Documentation and Community

  • Visit our Status Page to check the current availability of CodeRabbit.
  • Visit our Documentation for detailed information on how to use CodeRabbit.
  • Join our Discord Community to get help, request features, and share feedback.
  • Follow us on X/Twitter for updates and announcements.

Copy link
Contributor

@coderabbitai coderabbitai bot left a comment

Choose a reason for hiding this comment

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

Actionable comments posted: 0

🧹 Nitpick comments (4)
packages/editor/src/core/extensions/table/plugins/drag-handles/column/plugin.ts (2)

37-61: Avoid double-mapping DecorationSet; compute once and reuse

prev.decorations?.map(tr.mapping, tr.doc) is called in both the staleness check and the non-stale return path. Compute it once to reduce work and ensure consistency.

Apply this refactor:

-        let isStale = tableStructureChanged;
-
-        // Only do position-based stale check if structure hasn't changed
-        if (!isStale) {
-          const mapped = prev.decorations?.map(tr.mapping, tr.doc);
+        let isStale = tableStructureChanged;
+        let mapped: DecorationSet | undefined;
+        // Only do position-based stale check if structure hasn't changed
+        if (!isStale) {
+          mapped = prev.decorations?.map(tr.mapping, tr.doc);
           for (let col = 0; col < tableMap.width; col++) {
             const pos = getTableCellWidgetDecorationPos(table, tableMap, col);
-            if (mapped?.find(pos, pos + 1)?.length !== 1) {
+            if (mapped?.find(pos, pos + 1)?.length !== 1) {
               isStale = true;
               break;
             }
           }
         }
 
         if (!isStale) {
-          const mapped = prev.decorations?.map(tr.mapping, tr.doc);
           return {
             decorations: mapped,
             tableWidth: tableMap.width,
             tableNodePos: table.pos,
           };
         }

63-84: Lifecycle of ReactRenderer instances for widgets

Each rebuild creates new ReactRenderer(ColumnDragHandle, ...) instances. Unless those are explicitly destroyed when decorations are dropped, you risk retained references. Consider:

  • Adding a stable widget key to help ProseMirror map/retain widgets when possible.
  • Ensuring any prior ReactRenderer is disposed when its decoration disappears (if your ColumnDragHandle encapsulates cleanup, note it).

Optionally, add a stable key:

- decorations.push(Decoration.widget(pos, () => dragHandleComponent.element));
+ decorations.push(
+   Decoration.widget(pos, () => dragHandleComponent.element, {
+     key: `table-col-handle:${table.pos}:${col}`,
+   })
+);

And, if ColumnDragHandle exposes a destroy/cleanup, wire it via your component or by tracking and disposing renderers when the plugin recalculates.

Manually verify (DevTools Performance/Memory) that repeated column add/delete cycles do not grow retained ReactRenderer instances.

packages/editor/src/core/extensions/table/plugins/drag-handles/row/plugin.ts (2)

37-61: Same double-mapping here; compute once and reuse

Mirror the column plugin optimization to avoid mapping the DecorationSet twice.

Apply this refactor:

-        let isStale = tableStructureChanged;
-
-        // Only do position-based stale check if structure hasn't changed
-        if (!isStale) {
-          const mapped = prev.decorations?.map(tr.mapping, tr.doc);
+        let isStale = tableStructureChanged;
+        let mapped: DecorationSet | undefined;
+        // Only do position-based stale check if structure hasn't changed
+        if (!isStale) {
+          mapped = prev.decorations?.map(tr.mapping, tr.doc);
           for (let row = 0; row < tableMap.height; row++) {
             const pos = getTableCellWidgetDecorationPos(table, tableMap, row * tableMap.width);
             if (mapped?.find(pos, pos + 1)?.length !== 1) {
               isStale = true;
               break;
             }
           }
         }
 
         if (!isStale) {
-          const mapped = prev.decorations?.map(tr.mapping, tr.doc);
           return {
             decorations: mapped,
             tableHeight: tableMap.height,
             tableNodePos: table.pos,
           };
         }

80-84: Consider widget keys and renderer cleanup

As with columns, rows create new ReactRenderer(RowDragHandle, ...) instances on rebuild. Add stable keys and ensure cleanup to prevent leaks.

Example:

- decorations.push(Decoration.widget(pos, () => dragHandleComponent.element));
+ decorations.push(
+  Decoration.widget(pos, () => dragHandleComponent.element, {
+    key: `table-row-handle:${table.pos}:${row}`,
+  })
+);

Profile memory while repeatedly adding/removing rows to ensure renderer instances are not retained.

📜 Review details

Configuration used: CodeRabbit UI

Review profile: CHILL

Plan: Pro

💡 Knowledge Base configuration:

  • MCP integration is disabled by default for public repositories
  • Jira integration is disabled by default for public repositories
  • Linear integration is disabled by default for public repositories

You can enable these sources in your CodeRabbit configuration.

📥 Commits

Reviewing files that changed from the base of the PR and between 841388e and 6e9cca2.

📒 Files selected for processing (3)
  • packages/editor/src/core/extensions/table/plugins/drag-handles/column/plugin.ts (3 hunks)
  • packages/editor/src/core/extensions/table/plugins/drag-handles/row/plugin.ts (3 hunks)
  • packages/editor/src/core/plugins/drag-handle.ts (1 hunks)
🧰 Additional context used
🧬 Code graph analysis (2)
packages/editor/src/core/extensions/table/plugins/drag-handles/column/plugin.ts (1)
packages/editor/src/core/extensions/table/table/utilities/helpers.ts (1)
  • getTableCellWidgetDecorationPos (196-197)
packages/editor/src/core/extensions/table/plugins/drag-handles/row/plugin.ts (2)
packages/editor/src/core/extensions/table/table/utilities/helpers.ts (1)
  • getTableCellWidgetDecorationPos (196-197)
packages/editor/src/core/extensions/table/plugins/drag-handles/column/plugin.ts (1)
  • decorations (88-90)
⏰ Context from checks skipped due to timeout of 90000ms. You can increase the timeout in your CodeRabbit configuration to a maximum of 15 minutes (900000ms). (3)
  • GitHub Check: Build and lint web apps
  • GitHub Check: Analyze (javascript)
  • GitHub Check: Build and lint web apps
🔇 Additional comments (3)
packages/editor/src/core/plugins/drag-handle.ts (1)

382-398: Replace magic table offset with structural resolution

Using a hard-coded -2 to back up from the table cell into the table node is brittle—any change to the schema or additional wrappers (callouts, embeds, etc.) will break this offset. Instead, resolve the document position and walk up the tree to find the nearest table node.

• File: packages/editor/src/core/plugins/drag-handle.ts
• Context: lines 382–398

Apply this diff within the existing if (node.matches("table")) { … } branch:

   if (node.matches("table")) {
-    // Magic offset: brittle if structure changes
-    draggedNodePos = draggedNodePos - 2;
+    // Resolve to the true table node start instead of a fixed offset
+    const $pos = view.state.doc.resolve(draggedNodePos);
+    let tableDepth: number | null = null;
+    for (let i = $pos.depth; i >= 0; i--) {
+      if ($pos.node(i).type.name === "table") {
+        tableDepth = i;
+        break;
+      }
+    }
+    if (tableDepth == null) return;  // No table ancestor found
+    draggedNodePos = $pos.before(tableDepth);
   } else if (node.matches("blockquote")) {
     draggedNodePos = nodePosAtDOMForBlockQuotes(node, view);
     if (draggedNodePos === null || draggedNodePos === undefined) return;
   } else {
     // …

• This approach locates the table node structurally, making it resilient to nested wrappers or schema changes.
• Keep the table–blockquote ordering to maintain correct specificity.

Please sanity-check the following scenarios after applying the refactor:

  • Selecting a table as the very first node in the document.
  • Selecting a table nested inside other blocks (e.g., callouts or custom wrappers).
  • Drag-and-drop initiated from inside a cell versus from outside the table entirely.
packages/editor/src/core/extensions/table/plugins/drag-handles/column/plugin.ts (1)

15-20: Good call tracking table structure (width and node position)

Adding tableWidth and tableNodePos to plugin state is a clean way to detect structural changes and avoid unnecessary rebuilds. This should directly address post-delete drift.

packages/editor/src/core/extensions/table/plugins/drag-handles/row/plugin.ts (1)

15-20: Row plugin state tracking looks good

Mirrors the column plugin by tracking tableHeight and tableNodePos. This symmetry simplifies reasoning and should stabilize decoration reuse across row mutations.

@sriramveeraghanta sriramveeraghanta merged commit 34e2312 into preview Aug 25, 2025
7 of 8 checks passed
@sriramveeraghanta sriramveeraghanta deleted the fix/table-bugs branch August 25, 2025 20:43
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Projects

None yet

Development

Successfully merging this pull request may close these issues.

3 participants