Skip to content

Commit

Permalink
[ClickableText] Only handle clicks when annotations are present
Browse files Browse the repository at this point in the history
  • Loading branch information
wingio committed Dec 3, 2023
1 parent 8fdff23 commit d3b15c6
Show file tree
Hide file tree
Showing 2 changed files with 25 additions and 2 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -24,6 +24,9 @@ import androidx.compose.ui.text.style.TextOverflow
import androidx.compose.ui.unit.TextUnit
import xyz.wingio.syntakts.compose.clickable.clickableText

internal const val CLICKABLE_ANNOTATION_TAG: String = "xyz.wingio.syntakts.clickable"
internal const val LONG_CLICKABLE_ANNOTATION_TAG: String = "xyz.wingio.syntakts.longclickable"

/**
* Basic Text component that enables support for Syntakts click handling and Material 3 theming
*
Expand Down Expand Up @@ -63,6 +66,9 @@ public fun ClickableText(
maxLines: Int = Int.MAX_VALUE,
inlineContent: Map<String, InlineTextContent> = mapOf()
) {
val isClickable = text.getStringAnnotations(0, text.length).find {
it.tag == CLICKABLE_ANNOTATION_TAG || it.tag == LONG_CLICKABLE_ANNOTATION_TAG
} != null
var layoutResult by remember { mutableStateOf<TextLayoutResult?>(null) }
val textColor = color.takeOrElse {
style.color.takeOrElse {
Expand All @@ -85,7 +91,9 @@ public fun ClickableText(

BasicText(
text = text,
modifier = modifier.clickableText(text, layoutResult),
modifier = modifier.thenIf(isClickable) {
clickableText(text, layoutResult)
},
style = textStyle,
overflow = overflow,
softWrap = softWrap,
Expand All @@ -95,4 +103,8 @@ public fun ClickableText(
layoutResult = it
}
)
}

internal inline fun Modifier.thenIf(predicate: Boolean, block: Modifier.() -> Modifier): Modifier {
return if (predicate) then(block()) else this
}
Original file line number Diff line number Diff line change
Expand Up @@ -68,11 +68,16 @@ public fun ClickableText(
inlineContent: Map<String, InlineTextContent> = mapOf()
) {
var layoutResult by remember { mutableStateOf<TextLayoutResult?>(null) }
val isClickable = text.getStringAnnotations(0, text.length).find {
it.tag == CLICKABLE_ANNOTATION_TAG || it.tag == LONG_CLICKABLE_ANNOTATION_TAG
} != null

val textColor = color.takeOrElse {
style.color.takeOrElse {
Color.White
}
}

val textStyle = style.merge(
TextStyle(
color = textColor,
Expand All @@ -89,7 +94,9 @@ public fun ClickableText(

BasicText(
text = text,
modifier = modifier.clickableText(text, layoutResult),
modifier = modifier.thenIf(isClickable) {
clickableText(text, layoutResult)
},
style = textStyle,
overflow = overflow,
softWrap = softWrap,
Expand Down Expand Up @@ -131,4 +138,8 @@ public fun Modifier.clickableText(annotatedString: AnnotatedString, textLayoutRe
)
}
}
}

internal inline fun Modifier.thenIf(predicate: Boolean, block: Modifier.() -> Modifier): Modifier {
return if (predicate) then(block()) else this
}

0 comments on commit d3b15c6

Please sign in to comment.