adrielcafe / bonsai

:deciduous_tree: A multiplatform tree view for Jetpack Compose
MIT License
360 stars 14 forks source link

How do I use it recursively like with a `LazyColumn`? #8

Closed Yash-Garg closed 2 years ago

Yash-Garg commented 2 years ago

I have a custom model class ContentTreeItem which has a parent folder and children list. Furthermore, which can also contain multiple sub folder and files.

I am unable to understand how do I implement it with Bonsai? My LazyColumn implementation is below:

@Composable
fun ContentTreeView(nodes: List<ContentTreeItem>) {
    val expandedItems = remember { mutableStateListOf<ContentTreeItem>() }
    LazyColumn {
        nodes(
            nodes,
            isExpanded = { expandedItems.contains(it) },
            toggleExpanded = {
                if (expandedItems.contains(it)) {
                    expandedItems.remove(it)
                } else {
                    expandedItems.add(it)
                }
            },
        )
    }
}

fun LazyListScope.nodes(
    nodes: List<ContentTreeItem>,
    isExpanded: (ContentTreeItem) -> Boolean,
    toggleExpanded: (ContentTreeItem) -> Unit,
) {
    nodes.forEach { node ->
        node(
            node,
            isExpanded = isExpanded,
            toggleExpanded = toggleExpanded,
        )
    }
}

fun LazyListScope.node(
    node: ContentTreeItem,
    isExpanded: (ContentTreeItem) -> Boolean,
    toggleExpanded: (ContentTreeItem) -> Unit,
) {
    item {
        Text(
            node.name,
            modifier = Modifier
                .fillMaxSize()
                .clickable { toggleExpanded(node) }
                .padding(16.dp)
        )
    }
    if (isExpanded(node)) {
        node.children?.reversed()?.let { childNodes ->
            nodes(
                childNodes,
                isExpanded = isExpanded,
                toggleExpanded = toggleExpanded,
            )
        }
    }
}

The list of files are from an API so I cannot check if it's a Directory or a File.