compose-multiplatform icon indicating copy to clipboard operation
compose-multiplatform copied to clipboard

TextField does not stop key event propagation to parent/window event handlers

Open dzirbel opened this issue 3 years ago • 2 comments

Typing a key into a TextField will continue to propagate the key event to any parent composables using onKeyEvent or the window onKeyEvent, as far as I can tell. An example can be found here. The documentation for Window()'s onKeyEvent parameter seems to suggest that individual UI elements can consume key events before it reaches the window-level handler and it is explicitly stated in Modifier.onKeyEvent(), but this doesn't work for TextField input (and others as well, although TextField is the only one I've seen it with).

For my specific use case, I'd like to capture space key events anywhere in the application to play/pause audio, but only if the user doesn't have a TextField focused. I haven't been able to find a way to do this with either of these methods - composable or window-based - since it's a terrible experience to play/pause audio if the user adds a space to a text field.

dzirbel avatar Mar 03 '22 03:03 dzirbel

Not very friendly indeed

akurasov avatar Mar 05 '22 20:03 akurasov

individual UI elements can consume key events before it reaches the window-level handler and it is explicitly stated in Modifier.onKeyEvent()

In your example, there is no Modifier.onKeyEvent { true } declared for the TextFields.

TextField(
     modifier = Modifier.onKeyEvent { true },
     ....

If it's declared, the input events do not propagate up.

Does it help when you try it?

eymar avatar Aug 22 '22 13:08 eymar

Sorry for the very late response - yes, adding onKeyEvent { true } does seem to fix the problem. I'm not sure why I was returning false in the example I linked. So this is a workaround, but it seems like it should be the default behavior for TextFields to avoid requiring this in every text field.

The logic appears to be coming from TextFieldKeyInput which for example seems to only consume KeyDown events (although many KeyDown events from typing still make it to my global key event handler).

dzirbel avatar Nov 17 '22 00:11 dzirbel

The .onKeyEvent { true } works but prevents the Tab key to switch to the next input.

.onKeyEvent { it.key != Key.Tab } may do the trick.

mahozad avatar Oct 28 '23 06:10 mahozad

Please check the following ticket on YouTrack for follow-ups to this issue. GitHub issues will be closed in the coming weeks.

okushnikov avatar Jul 14 '24 16:07 okushnikov