Skip to content

Instantly share code, notes, and snippets.

@bagus2x
Created February 25, 2023 01:10
Show Gist options
  • Save bagus2x/dcbec3aec597dfe20c26cd8cd37761af to your computer and use it in GitHub Desktop.
Save bagus2x/dcbec3aec597dfe20c26cd8cd37761af to your computer and use it in GitHub Desktop.
Display nested comment system with LazyColumn Jetpack Compose
fun CommentListScreen() {
val comments by produceDummyComments(10000)
Box {
LazyColumn(
modifier = Modifier
.systemBarsPadding()
.fillMaxSize(),
) {
commentList(comments)
}
if (comments.isEmpty()) {
CircularProgressIndicator(modifier = Modifier.align(Alignment.Center))
}
}
}
fun LazyListScope.commentList(comments: List<Comment>, level: Int = 0) {
comments.forEach { comment ->
commentItem(comment, level)
}
}
fun LazyListScope.commentItem(comment: Comment, level: Int) {
item {
val padding = with(LocalDensity.current) { 16.dp.toPx() }
Text(
text = comment.text,
modifier = Modifier
.drawBehind {
repeat(level + 1) {
drawLine(
color = Color.Black,
start = Offset(it * padding, 0f),
end = Offset(it * padding, size.height)
)
}
}
.padding(horizontal = (16.dp * level) + 8.dp, vertical = 4.dp)
)
}
commentList(comment.replies, level + 1)
}
data class Comment(
val id: String = UUID.randomUUID().toString(),
val text: String,
val replies: List<Comment> = emptyList()
)
@Composable
fun produceDummyComments(rootCount: Int): State<List<Comment>> {
return produceState(initialValue = emptyList()) {
value = withContext(Dispatchers.Default) { generateComments(rootCount) }
}
}
fun generateComment(repliesCount: Int, level: Int) = Comment(
text = LoremIpsum(4)
.values
.joinToString(" ")
.replace('\n', ' '),
replies = generateComments(repliesCount, level)
)
fun generateComments(commentsCount: Int, level: Int = 0): List<Comment> = buildList {
if (level < 4) {
repeat(commentsCount) {
add(generateComment((0..3).random(), level + 1))
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment