Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

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

Open
igordmn opened this issue May 6, 2024 · 0 comments
Open

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

igordmn opened this issue May 6, 2024 · 0 comments
Labels
enhancement New feature or request input Touch, mouse, keyboard input related p:high High priority

Comments

@igordmn
Copy link
Collaborator

igordmn commented May 6, 2024

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:

  • it adds one more API to do one thing (we already have Modifier.onPreviewKeyEvent)
  • there is no way to define it on Screen/Dialog level
  • there is no API in commonMain

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()
    } 
}
@igordmn igordmn added enhancement New feature or request input Touch, mouse, keyboard input related p:high High priority labels May 6, 2024
@igordmn igordmn changed the title A common way to handle global key handlers A common way to handle window-level key handlers May 6, 2024
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
enhancement New feature or request input Touch, mouse, keyboard input related p:high High priority
Projects
None yet
Development

No branches or pull requests

1 participant