Update keyboard visibility to track hasFocus (#7284)

This commit is contained in:
Jenna Vassar
2026-07-28 06:35:27 -07:00
committed by GitHub
parent fe24aeb2ce
commit c2e8676773
@@ -25,25 +25,28 @@ import kotlinx.coroutines.delay
import kotlin.time.Duration.Companion.milliseconds import kotlin.time.Duration.Companion.milliseconds
/** /**
* Keeps the focused field visible above the keyboard. Intended for a field inside a scrollable * Keeps a focused field visible above the keyboard. Intended for a field — or a group that wraps
* container: the field is never clipped by a pinned footer, but the IME is shown only after focus * one — inside a scrollable container: the content is never clipped by a pinned footer, but the IME
* arrives, so we re-request bringIntoView once it is visible to scroll the field back into the * is shown only after focus arrives, so we re-request bringIntoView once it is visible to scroll the
* reduced viewport. * content back into the reduced viewport.
*
* Tracks focus via `hasFocus` rather than `isFocused`, so it also works when applied to a wrapper
* whose child — rather than the wrapper itself — takes focus.
*/ */
@OptIn(ExperimentalLayoutApi::class) @OptIn(ExperimentalLayoutApi::class)
@Composable @Composable
fun Modifier.bringIntoViewOnImeVisible(): Modifier { fun Modifier.bringIntoViewOnImeVisible(): Modifier {
val bringIntoViewRequester = remember { BringIntoViewRequester() } val bringIntoViewRequester = remember { BringIntoViewRequester() }
var isFocused by remember { mutableStateOf(false) } var hasFocus by remember { mutableStateOf(false) }
val isImeVisible = WindowInsets.isImeVisible val isImeVisible = WindowInsets.isImeVisible
LaunchedEffect(isImeVisible, isFocused) { LaunchedEffect(isImeVisible, hasFocus) {
if (isImeVisible && isFocused) { if (isImeVisible && hasFocus) {
// Delay to ensure the keyboard is fully shown before scrolling the field into view. // Delay to ensure the keyboard is fully shown before scrolling the content into view.
delay(100.milliseconds) delay(100.milliseconds)
bringIntoViewRequester.bringIntoView() bringIntoViewRequester.bringIntoView()
} }
} }
return this return this
.bringIntoViewRequester(bringIntoViewRequester) .bringIntoViewRequester(bringIntoViewRequester)
.onFocusChanged { isFocused = it.isFocused } .onFocusChanged { hasFocus = it.hasFocus }
} }