79294281

Date: 2024-12-19 12:30:14
Score: 0.5
Natty:
Report link

Use monospace fo digist.

@Composable
fun orderedTextList(
    items: List<String>,
    style: TextStyle = LocalTextStyle.current,
    lineBreak: LineBreak = LineBreak.Paragraph
): AnnotatedString {
    val textMeasurer = rememberTextMeasurer()
    val monospaceStyle = style.copy(
        fontFamily = FontFamily.Monospace
    )

    val markerLen = items.size.toString().length
    val monospaceSize = textMeasurer.measure(text = " ", style = monospaceStyle).size
    val spaceSize =  textMeasurer.measure(text = " ", style = style).size
    val dotSize = textMeasurer.measure(text = ".", style = style).size

    return buildAnnotatedString {
        items.forEachIndexed { index, text ->
            val count = (index+1).toString().length
            val tailLen = markerLen - count
            withStyle(
                style = ParagraphStyle(
                    textIndent = TextIndent( restLine = with(LocalDensity.current) {
                        (monospaceSize.width *markerLen + dotSize.width + spaceSize.width).toSp()
                    }),
                    lineHeight = with(LocalDensity.current) { monospaceSize.height.toSp() },
                    lineBreak = lineBreak
                )
            ){
                withStyle(monospaceStyle.toSpanStyle()){
                    append("${index+1}")
                }
                append(".")
                if(tailLen > 0){
                    withStyle(monospaceStyle.toSpanStyle()){
                        append("".padEnd(tailLen))
                    }
                }
                append(" ")
                append(text)
            }
        }
    }
}

enter image description here

Reasons:
  • Probably link only (1):
  • Long answer (-1):
  • Has code block (-0.5):
  • Low reputation (1):
Posted by: Clor