Strange behavior with TextSelection

I created a custom command to select all text and bound it to Mod-a.

keymap({
  'Mod-a': (state, dispatch) => {
    const from = 0
    const to = state.doc.content.size
    const selection = TextSelection.create(state.doc, from, to)
    const tr = state.tr.setSelection(selection)
    
    dispatch(tr)
    
    return true
  }
})

This works fine most of the time. But there is one single edge case.

  1. select all text with Mod-a
  2. type a
  3. select all text with Mod-a again
  4. type a
  5. see error: RangeError: Position -1 out of range

This only happens if I replace a single letter with the same single letter. There is no error if I replace a with b for example.

Video:

ezgif-3-1d66780d05

Glitch demo:

I think this is a bug or have I missed something obvious?

TextSelection endpoints must be in textblock positions, so you’re creating an invalid text selection here, which is causing the crash.

Yes, I’m using this which is working fine:

keymap({
  'Mod-a': (state, dispatch) => {
    const from = TextSelection.atStart(state.doc).from
    const to = TextSelection.atEnd(state.doc).to
    const selection = TextSelection.create(state.doc, from, to)
    const tr = state.tr.setSelection(selection)
    
    dispatch(tr)
    
    return true
  }
})

Just stumbled across this weird error described above and thought it’s a bug.