package com.anker.akblebusinessui.pair.firmware.components
import androidx.compose.material.LocalTextStyle
import androidx.compose.material.Text
import androidx.compose.runtime.Composable
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.text.SpanStyle
import androidx.compose.ui.text.TextStyle
import androidx.compose.ui.text.buildAnnotatedString
import androidx.compose.ui.text.font.FontWeight
import androidx.compose.ui.text.withStyle
@Composable
fun HighlightedText(
text: String,
searchQuery: String,
normalColor: Color = Color.Black,
highlightColor: Color = Color.Red,
style: TextStyle =LocalTextStyle.current,
ignoreCase: Boolean =true
) {
val annotatedString =buildAnnotatedString {
if (searchQuery.isEmpty()) {
// 没有搜索词,显示普通文本
withStyle(SpanStyle(color = normalColor)){
append(text)
}
}else {
var currentIndex =0
val searchPattern =if (ignoreCase) {
searchQuery.lowercase()
}else {
searchQuery
}
val textToSearch =if (ignoreCase) {
text.lowercase()
}else {
text
}
// 查找所有匹配的位置
while (currentIndex < text.length) {
val index = textToSearch.indexOf(searchPattern, currentIndex)
if (index == -1) {
// 没有更多匹配,添加剩余文本
withStyle(SpanStyle(color = normalColor)){
append(text.substring(currentIndex))
}
break
}else {
// 添加匹配前的文本
if (index > currentIndex) {
withStyle(SpanStyle(color = normalColor)){
append(text.substring(currentIndex, index))
}
}
// 添加高亮的匹配文本
withStyle(SpanStyle(color = highlightColor,fontWeight = FontWeight.Bold)){
append(text.substring(index, index + searchQuery.length))
}
currentIndex = index + searchQuery.length
}
}
}
}
Text(
text = annotatedString,
style = style
)
}