Skip to content

Commit

Permalink
Fixes misalignment of Clickable Texts
Browse files Browse the repository at this point in the history
  • Loading branch information
vitorpamplona committed Feb 15, 2024
1 parent ed7dcf9 commit 2159891
Show file tree
Hide file tree
Showing 2 changed files with 165 additions and 97 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -24,7 +24,6 @@ import androidx.compose.foundation.gestures.detectTapGestures
import androidx.compose.foundation.layout.fillMaxSize
import androidx.compose.foundation.layout.padding
import androidx.compose.foundation.text.BasicText
import androidx.compose.foundation.text.ClickableText
import androidx.compose.foundation.text.InlineTextContent
import androidx.compose.foundation.text.appendInlineContent
import androidx.compose.material3.LocalContentColor
Expand Down Expand Up @@ -298,27 +297,24 @@ fun CreateClickableText(
suffix: String?,
maxLines: Int = Int.MAX_VALUE,
overrideColor: Color? = null,
fontWeight: FontWeight = FontWeight.Normal,
fontWeight: FontWeight? = null,
route: String,
nav: (String) -> Unit,
) {
val currentStyle = LocalTextStyle.current
val primaryColor = MaterialTheme.colorScheme.primary
val onBackgroundColor = MaterialTheme.colorScheme.onBackground

val clickablePartStyle =
remember(primaryColor, overrideColor) {
currentStyle
.copy(color = overrideColor ?: primaryColor, fontWeight = fontWeight)
.toSpanStyle()
}
SpanStyle(
color = overrideColor ?: primaryColor,
fontWeight = fontWeight,
)

val nonClickablePartStyle =
remember(onBackgroundColor, overrideColor) {
currentStyle
.copy(color = overrideColor ?: onBackgroundColor, fontWeight = fontWeight)
.toSpanStyle()
}
SpanStyle(
color = overrideColor ?: onBackgroundColor,
fontWeight = fontWeight,
)

val text =
remember(clickablePartStyle, nonClickablePartStyle, clickablePart, suffix) {
Expand All @@ -333,11 +329,45 @@ fun CreateClickableText(
ClickableText(
text = text,
maxLines = maxLines,
style = currentStyle,
onClick = { nav(route) },
)
}

@Composable
fun ClickableText(
text: AnnotatedString,
modifier: Modifier = Modifier,
style: TextStyle = LocalTextStyle.current,
softWrap: Boolean = true,
overflow: TextOverflow = TextOverflow.Clip,
maxLines: Int = Int.MAX_VALUE,
onTextLayout: (TextLayoutResult) -> Unit = {},
onClick: (Int) -> Unit,
) {
val layoutResult = remember { mutableStateOf<TextLayoutResult?>(null) }
val pressIndicator =
Modifier.pointerInput(onClick) {
detectTapGestures { pos ->
layoutResult.value?.let { layoutResult ->
onClick(layoutResult.getOffsetForPosition(pos))
}
}
}

Text(
text = text,
modifier = modifier.then(pressIndicator),
style = style,
softWrap = softWrap,
overflow = overflow,
maxLines = maxLines,
onTextLayout = {
layoutResult.value = it
onTextLayout(it)
},
)
}

@Composable
fun CreateTextWithEmoji(
text: String,
Expand Down
Loading

0 comments on commit 2159891

Please sign in to comment.