JetBrains / compose-multiplatform

Compose Multiplatform, a modern UI framework for Kotlin that makes building performant and beautiful user interfaces easy and enjoyable.
https://jetbrains.com/lp/compose-multiplatform
Apache License 2.0
16.22k stars 1.18k forks source link

A common way to handle window-level key handlers #4764

Closed igordmn closed 1 month ago

igordmn commented 6 months ago

There should be a simple way to handle key presses on window/screen/dialog level.

Desktop currently have and additional API for that:

Window(onPreviewKeyEvent = )

There are issues with it:

Alternatively, we can use this approach, but it is cumbersome:

import androidx.compose.foundation.focusable
import androidx.compose.foundation.layout.Box
import androidx.compose.runtime.Composable
import androidx.compose.runtime.LaunchedEffect
import androidx.compose.runtime.remember
import androidx.compose.ui.ExperimentalComposeUiApi
import androidx.compose.ui.Modifier
import androidx.compose.ui.focus.FocusRequester
import androidx.compose.ui.focus.focusProperties
import androidx.compose.ui.focus.focusRequester
import androidx.compose.ui.input.key.key
import androidx.compose.ui.input.key.onPreviewKeyEvent

@OptIn(ExperimentalComposeUiApi::class)
@Composable
fun App() {
    val focusRequester = remember { FocusRequester() }
    Box(
        Modifier
            .focusRequester(focusRequester)
            .focusProperties{ exit = { focusRequester } }  // make LocalFocusManager.current.clear() to focus this node instead of the root window node
            .focusable()
            .onPreviewKeyEvent {
                println(it.key)
                true
            }
    )

    LaunchedEffect(Unit) {
        focusRequester.requestFocus()
    } 
}
okushnikov commented 2 months ago

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