basecamp / basecamp/trix

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

Open
#891 2 comments 0 reactions 0 assignees View on GitHub
Dominant language
JavaScript
Stars
20k
Forks
1.1k
Avg merge
3d 12h
Merged PRs (30d)
13

Description

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:
```js
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:

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

Contributor guide

No contributing guide indexed for this repository

Research direction

Start at src/trix/controllers/level_0_input_controller.coffee around line 100 and reproduce the reported keydown values for bracket shortcuts in the Trix editor. Compare the shortcut matching inputs described in the issue, and consider the documented browser behavior before deciding on a direction. Done means ctrl+[ and ctrl+] reliably activate their configured shortcuts without breaking existing keyboard handling.

Written by the indexing model from the issue text.

Assessment

Tech stack
javascript
Domain
frontend
Issue type
Bug
Difficulty
4/5
Estimated time
3-5 days
Activity status
Stale
Clarity
Mostly clear
Newbie friendliness
35/100

Get new issues in your inbox

A short digest of beginner-friendly GitHub issues.