Insert node throws out of range error


I am trying to add new paragraph after adding a table. But I am getting Uncaught RangeError: Position 41 out of range error. How can I fix this?

Below is the insertTable function that I uses to adding a table and inserting paragraph.

const insertTable = (state: EditorState, dispatch: (tr: Transaction) => void): boolean => {
  const offset: number = + 1
  const transaction: Transaction =

  const cell: ProseMirrorNode | null = state.schema.nodes.table_cell.createAndFill()

  if (!cell) {
    return false

  const table: ProseMirrorNode = state.schema.nodes.table.create(
      state.schema.nodes.table_row.create(null, Fragment.fromArray([cell, cell, cell])),
      state.schema.nodes.table_row.create(null, Fragment.fromArray([cell, cell, cell])),

  const paragraphNode = state.schema.nodes.paragraph.create() // Create a new paragraph node

  if (dispatch) {
    const newTransaction = transaction
      .replaceSelectionWith(table) // Replace selection with the table

    // Insert the paragraph after the table in the same transaction
        .insert(offset + table.nodeSize, paragraphNode)
        .setSelection(TextSelection.create(newTransaction.doc, offset + table.nodeSize + 1)) // Set the selection after the paragraph

  return true

@marijn I saw you’re most active on the community. Would you mind providing your thoughts?

As a glance, it may be that replaceSelectionWith is doing more than just inserting the table (it may overwrite an empty paragraph around the cursor, or selected content), and thus your selection position computation might end up outside the document.

Hmm… How can I make sure it’s not replacing empty paragraph and calculated offset is inside the range of document?

Do you have any thoughts to fix this?

Can you provide some solution on this one? This is so tricky issue.