:wave: Trying to capture keyboard events using `M...
# compose-web
b
👋 Trying to capture keyboard events using
Modifier.onKeyEvent
, this seems to work only after the Compose canvas is focused. So I either need to first click on it, or add a bit of JS that finds the canvas and call
focus()
on it... Is this a known issue and/or is there a trick?
w
I've gotten around this by just registering a normal web keyevent listener through the
window
object. I don't think you can avoid the focus issue, or at least I wasn't able to dig up anything.
b
Thanks!
through the
window
object
so in JS?
or through
kotlinx-browser
w
Through the Kotlin API.
b
kotlinx.browser.window
, right?
doing this works too, but it's a bit of a hack 🙂:
Copy code
(document.body!!.shadowRoot!!.querySelectorAll("canvas").item(0) as HTMLElement).focus()
w
Yeah. What are you trying to achieve?
The focus trick might be easier depending on where you need the Modifier. You can do that with the keyevent listener, too, using a DisposableEffect, but I have no idea how that'll interact if you have multiple. Whereas multiple Modifiers should just work.
a
99.99% of the times you want to use compose's focus system. If you don't you risk introducing unexpected behavior because your non compose focus actions will not work with compose.
in Unstyled I used what @Winson Chiu suggested and registered a keyboard listener via js. worked great. this was so that the tooltips get dismissed without messing with other elements on the screen
b
Yeah. What are you trying to achieve?
I'm making a little game 🙂 So yeah keyboard needs to work obviously.
99.99% of the times you want to use compose's focus system.
To be clear, I make my Compose view focused (otherwise
Modifier.onKeyEvent
doesn't work). But it's not enough: the canvas itself needs to be focused via javascript (or by clicking on it), otherwise no events are received. This looks like a bug to be honest. I should report this.