workflow-kotlin icon indicating copy to clipboard operation
workflow-kotlin copied to clipboard

Introduce TextController.asMutableTextFieldValueState()

Open rjrjr opened this issue 3 years ago • 0 comments
trafficstars

Oops, forgot to open source this:

/**
 * A wrapper extension for [com.squareup.workflow1.ui.compose.asMutableState] that returns
 * [TextFieldValue].
 */
@Composable
fun TextController.asMutableTextFieldValueState(): MutableState<TextFieldValue> {
  var textControllerValue by asMutableState()

  var textFieldValue by remember(this) {
    mutableStateOf(
      TextFieldValue(
        text = textControllerValue,
        // We need to set the selection manually when creating  new `TextFieldValue` whenever
        // `TextController` changes because the text inside may not be empty. This is to ensure the
        // cursor is set at the end of this new text.
        selection = TextRange(textControllerValue.length)
      )
    )
  }

  // "Bridge" mutable state between the two mutable states above. This also needs to depend on `this`
  // key so that the mutable state is recomputed whenever `textFieldValue` is updated. This ensures the
  // most up-to-date reference to `textFieldValue` used by this bridge mutable state.
  return remember(this) {
    object : MutableState<TextFieldValue> {
      override var value: TextFieldValue
        get() = textFieldValue
        set(newValue) {
          textFieldValue = newValue
          textControllerValue = newValue.text
        }

      override fun component1(): TextFieldValue = value
      override fun component2(): (TextFieldValue) -> Unit = { value = it }
    }
  }
}

rjrjr avatar Apr 19 '22 20:04 rjrjr