🌈 Create new beautiful Compose Gradients with our new wesite ->
Interface

TextFieldTextStyles

Provides access to the styles applied to the text within a TextFieldState.

BasicTextFieldTrackedRangeToggleBoldSample

@Sampled
@Composable
fun BasicTextFieldTrackedRangeToggleBoldSample() {
    // This sample demonstrates a realistic rich-text editor scenario using the `TrackedRange` and
    // `TextFieldTextStyles` APIs. It implements a "Toggle Bold" formatting function on the current
    // selection.

    // For simplicity, this sample keeps bold styles non-overlapping and contiguous, assuming they
    // are
    // applied exclusively through this method.
    val state = rememberTextFieldState("Hello World")

    // This derived state calculates whether the current selection is completely covered by
    // bold text styles. This ensures the "Bold" toggle button accurately reflects the
    // state of the selected text.
    val isSelection100PercentBold by remember {
        derivedStateOf {
            val selection = state.selection
            if (selection.collapsed) {
                false
            } else {
                val spanStyles = state.textStyles.getSpanStyles(selection)
                var boldCoverage = 0
                for (style in spanStyles) {
                    if (style.item.fontWeight == FontWeight.Bold) {
                        val overlapStart = maxOf(style.start, selection.min)
                        val overlapEnd = minOf(style.end, selection.max)
                        if (overlapEnd > overlapStart) {
                            boldCoverage += (overlapEnd - overlapStart)
                        }
                    }
                }
                boldCoverage == selection.length
            }
        }
    }

Content updated: