trix icon indicating copy to clipboard operation
trix copied to clipboard

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

Open fractaledmind opened this issue 3 years ago • 2 comments

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)?

fractaledmind avatar Mar 05 '21 15:03 fractaledmind

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

stale[bot] avatar Jun 11 '21 01:06 stale[bot]

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

fractaledmind avatar Jun 15 '21 15:06 fractaledmind