Skip to content

Floating Promise Anti-Pattern & Premature Caret in Multi-Block PasteΒ #3032

Description

@codeCraft-Ritik

4. Floating Promise Anti-Pattern & Premature Caret in Multi-Block Paste

πŸ“ Affected Locations

  • src/components/modules/paste.ts (Lines 251–261)

πŸ” Deep Technical Diagnosis

In src/components/modules/paste.ts:

// src/components/modules/paste.ts: Lines 251-261
const isCurrentBlockDefault = BlockManager.currentBlock && BlockManager.currentBlock.tool.isDefault;
const needToReplaceCurrentBlock = isCurrentBlockDefault && BlockManager.currentBlock.isEmpty;

dataToInsert.map(
  async (content, i) => this.insertBlock(content, i === 0 && needToReplaceCurrentBlock)
);

if (BlockManager.currentBlock) {
  Caret.setToBlock(BlockManager.currentBlock, Caret.positions.END);
}

Flaws:

  1. Misused .map() as .forEach(): .map() allocates a new array of returned Promises that are completely discarded.
  2. Unawaited Floating Promises: The callback is marked async, meaning this.insertBlock(...) returns an unresolved Promise for each item.
  3. Premature Caret Placement: Caret.setToBlock(BlockManager.currentBlock, Caret.positions.END) executes immediately and synchronously on line 259 before the async map operations have resolved.
  4. If any custom tool initializes asynchronously during insertion or yields to the event loop, the caret focuses the wrong block or moves before blocks are even attached to the DOM.

πŸ’‘ Proposed Solution & Patch

src/components/modules/paste.ts

@@ -251,9 +251,9 @@ export default class Paste extends Module {
     const isCurrentBlockDefault = BlockManager.currentBlock && BlockManager.currentBlock.tool.isDefault;
     const needToReplaceCurrentBlock = isCurrentBlockDefault && BlockManager.currentBlock.isEmpty;

-    dataToInsert.map(
-      async (content, i) => this.insertBlock(content, i === 0 && needToReplaceCurrentBlock)
-    );
+    for (let i = 0; i < dataToInsert.length; i++) {
+      this.insertBlock(dataToInsert[i], i === 0 && needToReplaceCurrentBlock);
+    }

     if (BlockManager.currentBlock) {
       Caret.setToBlock(BlockManager.currentBlock, Caret.positions.END);

Activity

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Type

    No type

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions