Different behaviors in the same transaction

First of all, thanks for this wonderful project.

I was trying to add a button outside the editor that will mutate the selected text inside the editor. With the same function editor.goBold, the behavior turns out to be different. When it acts as a keyboard event callback, it works as expected. But when it’s called from the click event listener, the text selection is strange after dispatch.

  goBold(view) {
    const mutation = view.state.changeByRange((range) => {
      return {
        changes: [
          { from: range.from, insert: "**" },
          { from: range.to, insert: "**" }
        range: EditorSelection.range(range.from, range.to + 4),

Here’s a minimum reproduction: codemirror6 - vanilla - CodeSandbox

I’m trying to follow the best practice of using this library, would love to know if there’s anything wrong in the code and the best way to implement this feature (and this post may help other newcomers as well).

This is related to the default browser behavior for click, it seems, which moves focus to the button. You can either use a "mousedown" event and call preventDefault to keep focus in the editor, or call editor.view.focus() in your event handler to move focus back to it.

1 Like