Manually setting selection

#1

As initially mentioned in this thread, I have a tokenization process that detects "{Token Name}|" (where | is the cursor) and converts it to an atomic node wrapped in a styled <span>. I also have a toolbar button that fires a command that will wrap the current selection in { }, at which point the same tokenization kicks in. This works great for forward selections, where I end up with a token and the cursor to the right. For reversed selections with the head behind the anchor, however, I just get a selection with the extra { } inside. If I then hit the right arrow, the tokenization happens as expected. I thought I could address this by moving the selection directly after the new token myself, but it doesn’t seem to be having an effect. Am I doing it wrong?

const tokenize = (view, tokenData) => {
  const { state } = view;
  const { selection, tr: transaction } = state;

  const token = createToken(state, tokenData);
  const to = selection.to;
  const from = to - tokenData.length;
  transaction.replaceRangeWith(from, to, token);
  transaction.setSelection(TextSelection.create(state.doc, from + 1)); // Is this right?
  view.dispatch(transaction);
};
#2

I don’t know what, exactly, createToken does, but at a glance it looks like from + 1 will be the position directly after the inserted { character.

#3

createToken generates the <span>. Turned out I had to apply the insertion to the state before using it to create the new selection, e.g.

transaction.setSelection(
  TextSelection.create(
    state.apply(transaction).doc,
    from + token.nodeSize
  )
);