refactor(common): optimize comment entry display

This commit is contained in:
Harsh Shandilya 2022-12-11 12:13:06 +05:30
parent 18d82a5eb3
commit 0083aa69b5
No known key found for this signature in database
2 changed files with 45 additions and 24 deletions

View file

@ -6,8 +6,8 @@
*/ */
package dev.msfjarvis.claw.common.comments package dev.msfjarvis.claw.common.comments
import androidx.compose.foundation.lazy.LazyListScope
import androidx.compose.material3.Divider import androidx.compose.material3.Divider
import androidx.compose.runtime.Composable
import dev.msfjarvis.claw.model.Comment import dev.msfjarvis.claw.model.Comment
data class CommentNode( data class CommentNode(
@ -40,22 +40,6 @@ fun createListNode(comments: List<Comment>): MutableList<CommentNode> {
return commentNodes return commentNodes
} }
@Composable
fun DisplayListNode(
comments: List<CommentNode>,
htmlConverter: HTMLConverter,
updateComments: (CommentNode) -> Unit,
) {
comments.forEach {
CommentEntry(commentNode = it, htmlConverter = htmlConverter, updateComments)
Divider()
if (it.children.isNotEmpty()) {
DisplayListNode(comments = it.children, htmlConverter = htmlConverter, updateComments)
}
}
}
fun toggleAllExpanded(commentNode: CommentNode): CommentNode { fun toggleAllExpanded(commentNode: CommentNode): CommentNode {
commentNode.isExpanded = !commentNode.isExpanded commentNode.isExpanded = !commentNode.isExpanded
@ -64,3 +48,39 @@ fun toggleAllExpanded(commentNode: CommentNode): CommentNode {
} }
return commentNode return commentNode
} }
fun LazyListScope.nodes(
nodes: List<CommentNode>,
htmlConverter: HTMLConverter,
toggleExpanded: (CommentNode) -> Unit,
) {
nodes.forEach { node ->
node(
node = node,
htmlConverter = htmlConverter,
toggleExpanded = toggleExpanded,
)
}
}
fun LazyListScope.node(
node: CommentNode,
htmlConverter: HTMLConverter,
toggleExpanded: (CommentNode) -> Unit,
) {
item {
CommentEntry(
commentNode = node,
htmlConverter = htmlConverter,
toggleExpanded = toggleExpanded,
)
Divider()
}
if (node.children.isNotEmpty()) {
nodes(
node.children,
htmlConverter = htmlConverter,
toggleExpanded = toggleExpanded,
)
}
}

View file

@ -59,19 +59,20 @@ private fun CommentsPageInternal(
) )
} }
item { nodes(
DisplayListNode(comments = commentNodes, htmlConverter = htmlConverter) { node -> nodes = commentNodes,
htmlConverter = htmlConverter,
toggleExpanded = { node ->
val newNode = toggleAllExpanded(node) val newNode = toggleAllExpanded(node)
// TODO(anunaym14): make this search recursive
val index = val index =
commentNodes.indexOf(commentNodes.find { it.comment.url == node.comment.url }) commentNodes.indexOf(commentNodes.find { it.comment.url == node.comment.url })
if (index == -1) { if (index != -1) {
error("Failed to find node for comment: ${node.comment}")
} else {
commentNodes.removeAt(index) commentNodes.removeAt(index)
commentNodes.add(index, newNode) commentNodes.add(index, newNode)
} }
} },
} )
} else { } else {
item { item {
Text( Text(