Setting text of a textbox by code messes up Undo/Redo functionality

When I have a textbox, I can set the text of the component from code, but when I do so, Ctrl+Z/Y Undoes/Redoes my typing from before the .text entry as an addendum onto the new text of the textbox:

  1. Launch the Clone below
  2. Enter Test Another in the box (or any text really) with the keyboard
  3. Select that text and delete it
  4. Press the button below the text box
  5. Go through Ctrl+Z/Y in the textbox
  6. See that the text added by button click is never changed and all the previous text is added on.

This may seem like a rare case, and it kind of is, but I discovered this when I was adding the anvil-extras autocomplete in my app. After I saw nothing in their code that could possibly have created the bug, I tested with a vanilla anvil textbox and saw the same bug above.

So the frequency of the bug for actual users might be higher than otherwise expected.

Hmm, this actually seems to be a browser bug:

There are 2 ways I saw to change the text from code, but neither is good for keeping the Ctrl+Z/Y behavior :upside_down_face:

If you want that sort of behaviour you need to tap into the browsers undo stack. The deprecated way to do this is to use the document.execCommand api as your code pen explores. It was made obsolete, browsers have different implementations and there is no current alternative :disappointed:.

You might find that your implementation works differently on different browsers. On iOS the execCommand codepen works as expected and the undo stack is preserved (for me).

If it’s important to your use case it might be worth exploring using execCommand which would work nicely from python.

2 Likes

Yeah, I don’t have a major use case, just thought this was a silly bug in the browser – and more so now that I know it’s on the browser itself rather than any code anyone’s writing on top of it :upside_down_face:

1 Like