以下の内容はhttps://matsudamper.hatenablog.com/entry/2023/03/29/022743より取得しました。


Compose JS WasmでTextFieldの挙動をHTMLに近づける

バージョン

kotlin.version=1.8.10
compose.version=1.3.1

問題

以下のGoogle公式のBackspaceでページを戻るプラグインをCompose Multiplatform JS Wasmで使用していると、TextFieldでBackspaceを押すと前のページに戻ってしまいます。
https://chrome.google.com/webstore/detail/go-back-with-backspace/eekailopagacbcdloonjhbiecobagjci

HTMLでの動作との互換性はComposeでは重視されていないようです。
https://github.com/JetBrains/compose-multiplatform/issues/2917

修正

以下のコードでとりあえずは対応できます。

@Composable
public fun NormalizeInputKeyCapture(content: @Composable () -> Unit) {
    var hasFocus by remember {
        mutableStateOf(false)
    }
    LaunchedEffect(Unit) {
        val target = document.getElementById("ComposeTarget")!!
        target.addEventListener(
            type = "keydown",
            callback = { event ->
                event as KeyboardEvent

                if (hasFocus) {
                    event.stopImmediatePropagation()
                }
            },
        )
    }

    val focusRequester = remember { FocusRequester() }
    Box(
        modifier = Modifier
            .focusTarget()
            .focusRequester(focusRequester)
            .clickable(
                indication = null,
                interactionSource = remember { MutableInteractionSource() },
            ) { focusRequester.freeFocus() }
            .onFocusChanged {
                hasFocus = it.hasFocus
            },
    ) {
        content()
    }
}

おわりに

HTMLとの動作の互換性が重要視されていないようなので、Compose JS Wasmはキオスク端末などでの、ブラウザまで制御できる環境以外では使用しないほうが良さそうです。




以上の内容はhttps://matsudamper.hatenablog.com/entry/2023/03/29/022743より取得しました。
このページはhttp://font.textar.tv/のウェブフォントを使用してます

不具合報告/要望等はこちらへお願いします。
モバイルやる夫Viewer Ver0.14