How to force unfocus of the CodeMirror element in Safari?

If I create a page with a button and a CodeMirror editor (in Safari 17.3), then

  1. click on the editor
  2. click directly onto the button (without clicking on the body first)
  3. type some text

The focus is transferred back to CodeMirror and the text is added there (even though it should be unfocused). Is there any way to prevent this behaviour, and make it so that the keys are ignored when the CodeMirror element is unfocused?

In the demo below, I tried forcing the focus to change with .blur() on the CodeMirror element and .focus() on the button but these didn’t help.

https://codemirror.net/try/?c=aW1wb3J0IHtiYXNpY1NldHVwLCBFZGl0b3JWaWV3fSBmcm9tICJjb2RlbWlycm9yIgppbXBvcnQge2phdmFzY3JpcHR9IGZyb20gIkBjb2RlbWlycm9yL2xhbmctamF2YXNjcmlwdCIKCmNvbnN0IGIgPSBkb2N1bWVudC5jcmVhdGVFbGVtZW50KCJidXR0b24iKTsKYi5pbm5lclRleHQgPSAiaGkiCmRvY3VtZW50LmJvZHkuYXBwZW5kQ2hpbGQoYik7CmIub25jbGljayA9ICgpID0+IHsKICB2aWV3LmNvbnRlbnRET00uYmx1cigpOwogIGIuZm9jdXMoKTsKfQoKY29uc3QgdmlldyA9IG5ldyBFZGl0b3JWaWV3KHsKICBkb2M6ICJjb25zb2xlLmxvZygnaGVsbG8nKVxuIiwKICBleHRlbnNpb25zOiBbYmFzaWNTZXR1cCwgamF2YXNjcmlwdCgpXSwKICBwYXJlbnQ6IGRvY3VtZW50LmJvZHkKfSkK

I found a workaround: Try CodeMirror

I wonder if it would make sense to include a patch like this as part of the editor?

If you click a button, that button receives focus (you can check with document.activeElement). But Safari seems to have added some weird feature where if you start typing in that situation it magically moves focus back into the editor. That is not CodeMirror’s problem and definitely not something CodeMirror should try to work around.