basecamp / trix

A rich text editor for everyday writing
https://trix-editor.org/
MIT License
19.09k stars 1.12k forks source link

`String.fromCharCode(event.keyCode)` behaving oddly #891

Open fractaledmind opened 3 years ago

fractaledmind commented 3 years ago

I am currently fairly sad because I have hit a wall with the ActionText/Trix editor that seems to be unfixable from my end. I was trying to wire up keyboard shortcuts for all of the Trix editor actions, and I wanted to make ctrl + [ the shortcut for "increase indent level" and ctrl + ] for "decrease indent level". I added data-trix-key="[" to the button, reloaded, and used the keyboard shortcut ... and nothing happened. After digging into the problem and the Trix source, I found this:

if character = String.fromCharCode(event.keyCode).toLowerCase() 

(https://github.com/basecamp/trix/blob/520cc50afff2b90120f49038945eb0cb73d82535/src/trix/controllers/level_0_input_controller.coffee#L100).

In order to determine if a data-trix-key keyboard shortcut has been activated, you take the event.keyCode and use String.fromCharCode to get the corresponding string representation of the key pressed. For reasons that I do not understand, my keyboard (on an US Macbook with a US layout both physically and in software) seems to send different signals than they are expecting. I tested this by adding a simple event listener to log out some data:

document.addEventListener('keydown', event => console.log(event.keyCode, event.key, String.fromCharCode(event.keyCode).toLowerCase())))

And sure enough, these are my logs:

[Log] 189 – "-" – "½" – true
[Log] 187 – "=" – "»" – true
[Log] 219 – "[" – "û" – true
[Log] 221 – "]" – "ý" – true

So, when I press ctrl + [, the Trix code believes I have just pressed crtl + û and therefore doesn't believe I have triggered the keyboard shortcut. I have two questions, [1] is there a way I can resolve this on my end and/or [2] is there is strong reason to use String.fromCharCode(event.keyCode).toLowerCase() instead of event.key (https://caniuse.com/keyboardevent-key)?

stale[bot] commented 3 years ago

This issue has been automatically marked as stale after 90 days of inactivity. It will be closed if no further activity occurs.

fractaledmind commented 3 years ago

I would rather not have this closed, so I'm hoping this comment will keep it open