Pantrix UI

Lazy Tree View

A hierarchy of many rows that scrolls in a room of its own: a document's values, a project's files, an outline of thousands of headings. Only the rows in view are composed: a tree of a hundred thousand open rows composes what the screen shows. A tree of a few dozen rows that stands in a page that scrolls is a PantrixTreeView.

import com.pantrixui.components.data.lazytreeview.PantrixLazyTreeView

Examples

A document of ten thousand rows

A hundred items in each of a hundred orders: more than ten thousand rows, of which only those in view are composed. "Go to the chosen one" brings the chosen item into view. "Order 73, item 42" opens that order's branch, chooses the item, and once the tree shows it scrolls there from an effect.

var open by rememberSaveable { mutableStateOf(setOf("orders")) }
var chosen by rememberSaveable { mutableStateOf(setOf(itemKey(order = 2, item = 5))) }
val tree: TreeViewState = rememberTreeViewState()
val scope = rememberCoroutineScope()
// The item whose branch was opened, brought into view once the tree shows it.
var target by remember { mutableStateOf<String?>(null) }
LaunchedEffect(target) {
    target?.let { tree.scrollToKey(it) }
    target = null
}
PantrixLazyTreeView(
    nodes = ORDER_TREE,
    expanded = open,
    onExpandedChange = { open = it },
    modifier = Modifier.fillMaxWidth().height(360.dp),
    state = tree,
    selection = TreeSelection.Single,
    selected = chosen,
    onSelectionChange = { chosen = it },
    guides = true,
    tagKey = "orders"
)
Row(horizontalArrangement = Arrangement.spacedBy(PantrixTheme.spacing.sm)) {
    PantrixButton(
        text = "Go to the chosen one",
        onClick = { scope.launch { chosen.firstOrNull()?.let { tree.scrollToKey(it) } } },
        variant = ButtonVariant.Outline,
        tagKey = "reveal"
    )
    PantrixButton(
        text = "Order 73, item 42",
        onClick = {
            val key = itemKey(order = 73, item = 42)
            open = open + "order73"
            chosen = setOf(key)
            target = key
        },
        variant = ButtonVariant.Outline,
        tagKey = "jump"
    )
}
PantrixText(
    text = "Chosen: ${chosen.firstOrNull() ?: "none"}",
    style = PantrixTheme.typography.footnote,
    color = PantrixTheme.colors.textSecondary
)

private val ORDER_TREE: List<TreeNode> = listOf(
    TreeNode(
        key = "orders",
        label = "Orders",
        children = (1..ORDER_COUNT).map { order ->
            TreeNode(
                key = "order$order",
                label = "Order $order",
                children = (1..ITEMS_EACH).map { item ->
                    TreeNode(
                        key = itemKey(order, item),
                        label = "Item $item",
                        trailing = "${(order * item) % 90 + 10} TL"
                    )
                }
            )
        }
    )
)

private fun itemKey(
    order: Int,
    item: Int
): String = "order$order.item$item"

private const val ORDER_COUNT = 100

private const val ITEMS_EACH = 100

Keys in the code's type, their kinds at the end

A person's JSON document: the keys in the theme's primary colour (styledLabel), the labels in the code's type (TreeViewStyle(labelRole = TypeRole.Code)), and each value's kind at its row's end in a tag (trailing).

The row of the value that is a link has an action (rowAction): the button at its end opens the link and does not choose the row. On a keyboard Shift+Enter on the row that has the focus does the same, and with a screen reader the row's actions. The example opens no link: it writes the address it would open under the tree.

var open by rememberSaveable { mutableStateOf(setOf("$", "$.address")) }
var asked by rememberSaveable { mutableStateOf<String?>(null) }
val key = PantrixTheme.colors.primary.color
val nodes = remember(key) { personOf(key) }
PantrixLazyTreeView(
    nodes = nodes,
    expanded = open,
    onExpandedChange = { open = it },
    modifier = Modifier.fillMaxWidth().height(320.dp),
    guides = true,
    trailing = { node -> KINDS[node.key]?.let { PantrixTag(text = it) } },
    style = TreeViewStyle(labelRole = TypeRole.Code),
    tagKey = "person",
    rowAction = { node ->
        LINKS[node.key]?.let { address ->
            TreeRowAction(icon = PantrixIcons.ExternalLink, label = "Open link") { asked = address }
        }
    }
)
PantrixText(
    text = "Link to open: ${asked ?: "none"}",
    style = PantrixTheme.typography.footnote,
    color = PantrixTheme.colors.textSecondary
)

private fun personOf(key: Color): List<TreeNode> {
    fun value(
        at: String,
        name: String,
        value: String = "",
        children: List<TreeNode> = emptyList(),
        tag: String? = null
    ) = TreeNode(
        key = at,
        label = if (value.isEmpty()) name else "$name: $value",
        children = children,
        tagKey = tag,
        styledLabel = buildAnnotatedString {
            withStyle(SpanStyle(color = key)) { append(name) }
            if (value.isNotEmpty()) append(": $value")
        }
    )
    return listOf(
        value(
            "$",
            "person",
            children = listOf(
                value("$.name", "name", "\"Ada\""),
                value("$.web", "web", "\"https://example.com/ada\"", tag = "web"),
                value("$.born", "born", "1815"),
                value(
                    "$.address",
                    "address",
                    children = listOf(
                        value("$.address.city", "city", "\"London\""),
                        value("$.address.zip", "postcode", "\"W1\"")
                    )
                ),
                value("$.tags", "tags", children = listOf(value("$.tags[0]", "0", "\"mathematics\""))),
                value("$.alive", "alive", "false")
            )
        )
    )
}

private val KINDS = mapOf(
    "$" to "object",
    "$.name" to "string",
    "$.web" to "link",
    "$.born" to "number",
    "$.address" to "object",
    "$.address.city" to "string",
    "$.address.zip" to "string",
    "$.tags" to "array",
    "$.tags[0]" to "string",
    "$.alive" to "boolean"
)

private val LINKS = mapOf("$.web" to "https://example.com/ada")

A filter over ten thousand rows

A filter over ten thousand rows: what is typed in the field is looked for in the labels; the items found and the orders they stand in show, and the letters found are marked. Typing "item 42" leaves one item of each of the hundred orders.

val query = rememberTextFieldState()
var open by rememberSaveable { mutableStateOf(setOf("orders")) }
PantrixTextField(
    state = query,
    modifier = Modifier.fillMaxWidth(),
    placeholder = "Search the items",
    showClearButton = true,
    contentDescription = "Search the items",
    tagKey = "order_search"
)
PantrixLazyTreeView(
    nodes = ORDER_TREE,
    expanded = open,
    onExpandedChange = { open = it },
    modifier = Modifier.fillMaxWidth().height(320.dp),
    filter = query.text.toString(),
    tagKey = "orders_filtered"
)

private val ORDER_TREE: List<TreeNode> = listOf(
    TreeNode(
        key = "orders",
        label = "Orders",
        children = (1..ORDER_COUNT).map { order ->
            TreeNode(
                key = "order$order",
                label = "Order $order",
                children = (1..ITEMS_EACH).map { item ->
                    TreeNode(
                        key = itemKey(order, item),
                        label = "Item $item",
                        trailing = "${(order * item) % 90 + 10} TL"
                    )
                }
            )
        }
    )
)

private fun itemKey(
    order: Int,
    item: Int
): String = "order$order.item$item"

private const val ORDER_COUNT = 100

private const val ITEMS_EACH = 100

A hundred thousand records from a source

A hundred thousand records from a source (source, TreeSource): the tree asks the source how many children each open branch has and for each child in turn, and makes a node only as its row is about to be shown; the rows scrolled past are never made. "Go to record 50000" finds where that record stands by the index the source reads from its key (TreeSource.indexOf).

"Archive"'s children are not loaded yet: its node says how many there will be (TreeNode.childCount), and a screen reader hears it on the closed row. Opened, a spinner turns in its place.

val source = remember { RecordsSource(count = 100_000) }
var open by rememberSaveable { mutableStateOf(setOf("records")) }
val tree = rememberTreeViewState()
val scope = rememberCoroutineScope()
PantrixLazyTreeView(
    source = source,
    expanded = open,
    onExpandedChange = { open = it },
    modifier = Modifier.fillMaxWidth().height(320.dp),
    state = tree,
    loading = setOf("archive").intersect(open),
    tagKey = "records"
)
PantrixButton(
    text = "Go to record 50000",
    onClick = { scope.launch { tree.scrollToKey("record/49999") } },
    variant = ButtonVariant.Outline,
    tagKey = "go_to_record"
)

private class RecordsSource(private val count: Int) : TreeSource {
    override fun childCount(parent: TreeNode?): Int = when {
        parent == null -> 2
        parent.key == "records" -> count
        parent.key.startsWith("record/") -> RECORD_FIELDS.size
        else -> 0
    }

    override fun childAt(
        parent: TreeNode?,
        index: Int
    ): TreeNode = when {
        parent == null && index == 0 -> TreeNode("records", "Records", hasChildren = true, trailing = "$count")
        parent == null -> TreeNode("archive", "Archive", hasChildren = true, childCount = 1_200)
        parent.key == "records" -> TreeNode("record/$index", "Record ${index + 1}", hasChildren = true)
        else -> TreeNode("${parent.key}/${RECORD_FIELDS[index]}", RECORD_FIELDS[index])
    }

    override fun indexOf(
        parent: TreeNode?,
        key: String
    ): Int = when {
        parent == null -> listOf("records", "archive").indexOf(key)
        parent.key == "records" -> key.removePrefix("record/").toIntOrNull()?.takeIf { it in 0 until count } ?: -1
        else -> RECORD_FIELDS.indexOf(key.removePrefix("${parent.key}/"))
    }
}

private val RECORD_FIELDS = listOf("name", "city", "amount")

API

nodes

A hierarchy of many rows that scrolls in a room of its own: a document's values, a project's files, an outline of thousands of headings. Only the rows in view are composed: a tree of a hundred thousand open rows composes what the screen shows. A tree of a few dozen rows that stands in a page that scrolls is a PantrixTreeView.

ParameterTypeDefaultWhat it is
nodesList<TreeNode>the nodes at the top of the tree, in the order they are shown. No two nodes of the tree have one key.
expandedSet<String>the keys of the branches that are open.
onExpandedChange(Set<String>) -> Unitcalled with the keys that are to be open after a branch was opened or closed. The tree changes nothing by itself.
modifierModifierModifierthe tree's modifier. The tree is as wide as the room it is given; its height is said above.
stateTreeViewStaterememberTreeViewState()where the rows are scrolled to, for a screen that reads it or brings a row into view.
selectionTreeSelectionTreeSelection.Nonehow rows are chosen: not at all, one at a time, or by checkboxes.
selectedSet<String>emptySet()the keys of the chosen rows, or of the checked ones.
onSelectionChange((Set<String>) -> Unit)?nullcalled with the keys that are to be chosen, or checked, after a press. null leaves the rows as selected has them, and a press on a row opens its branch or closes it.
loadingSet<String>emptySet()the keys of the branches whose children are being loaded: a spinner stands in their twisty's place.
filterString""what the rows' labels are to hold for the rows to be shown, or nothing for all of them.
guidesBooleanfalsewhether a faint line runs down from each open branch's twisty along what it holds.
trailing(@Composable RowScope.(TreeNode) -> Unit)?nullwhat each row draws at its end for its node, after the node's own trailing text, or null for nothing. It is read with the row and takes no press of its own.
styleTreeViewStyle?nullthis call's own style: over every enclosing one and under the density. Only the fields it sets change, on every platform.
colorsTreeViewColors?nullthis tree's own colours, where they are not the theme's: the ones set here, with the theme's for the rest.
rowAction((TreeNode) -> TreeRowAction?)?nullwhat the row of a node does besides being chosen, or null for a row that does nothing more: an icon button at its end, which a press runs without choosing the row, tagged LazyTreeView_<tagKey>.Action_<key>. Shift+Enter on the row runs it, and a screen reader is offered it among the row's actions.
tagKeyString?nullthe tree's automation key: the tree is LazyTreeView_<tagKey>, a row in it LazyTreeView_<tagKey>.Node_<key> and its twisty LazyTreeView_<tagKey>.Twisty_<key>. What a press does is reported as a LazyTreeView event: expand, collapse, select, check, uncheck, and action for a row's action, with the node's key.

source

A PantrixLazyTreeView that takes its nodes from source as it shows them, for a tree too large to be given as a list: a document of a hundred thousand values, a disk's folders. Only the counts of the open branches are asked for as the tree lays itself out, and a node only as its row is about to be shown, so that the rows scrolled past are never made, and a branch of a hundred thousand children costs what the rows on the screen do.

ParameterTypeDefaultWhat it is
sourceTreeSourcewhat the tree takes its nodes from. Another source, one not equal to this one, is a tree laid out afresh: what changes in the nodes is given as another source.
expandedSet<String>the keys of the branches that are open.
onExpandedChange(Set<String>) -> Unitcalled with the keys that are to be open after a branch was opened or closed. The tree changes nothing by itself.
modifierModifierModifierthe tree's modifier. The tree is as wide as the room it is given; it is as tall as its open rows up to the room it is given, or as tall as this makes it.
stateTreeViewStaterememberTreeViewState()where the rows are scrolled to, for a screen that reads it or brings a row into view.
selectionTreeSelectionTreeSelection.Nonehow rows are chosen: not at all, or one at a time. TreeSelection.Checkbox is refused.
selectedSet<String>emptySet()the keys of the chosen rows.
onSelectionChange((Set<String>) -> Unit)?nullcalled with the keys that are to be chosen after a press. null leaves the rows as selected has them, and a press on a row opens its branch or closes it.
loadingSet<String>emptySet()the keys of the branches whose children are being loaded: a spinner stands in their twisty's place.
guidesBooleanfalsewhether a faint line runs down from each open branch's twisty along what it holds.
trailing(@Composable RowScope.(TreeNode) -> Unit)?nullwhat each row draws at its end for its node, after the node's own trailing text, or null for nothing. It is read with the row and takes no press of its own.
styleTreeViewStyle?nullthis call's own style: over every enclosing one and under the density. Only the fields it sets change, on every platform.
colorsTreeViewColors?nullthis tree's own colours, where they are not the theme's: the ones set here, with the theme's for the rest.
rowAction((TreeNode) -> TreeRowAction?)?nullwhat the row of a node does besides being chosen, or null for a row that does nothing more: an icon button at its end, as in the tree of nodes.
tagKeyString?nullthe tree's automation key: the tree is LazyTreeView_<tagKey>, a row in it LazyTreeView_<tagKey>.Node_<key> and its twisty LazyTreeView_<tagKey>.Twisty_<key>. What a press does is reported as a LazyTreeView event, as in the tree of nodes.

TreeViewStyle

PantrixTreeView's geometry, and a PantrixLazyTreeView's: how tall a row is, how far each level steps in, how large the twisty is, and the type the labels are set in.

ParameterTypeDefaultWhat it is
shapeShapeSpecShapeSpec.UnspecifiedThe corners of a chosen row's fill: a step of the brand's shape scale, or a fixed shape.
rowHeightDpDp.UnspecifiedThe least height of a row. It is raised to the platform's touch target where it is lower: a row asked to be 36dp tall is 48dp on Android and on a page used by touch, 44pt on iOS, and 36dp under a pointer. A larger type makes it taller.
indentDpDp.UnspecifiedHow far a level steps in from the one it stands under.
iconSizeDpDp.UnspecifiedThe width and height of the twisty, of a node's own icon and of the spinner of a branch that loads.
gapDpDp.UnspecifiedBetween the twisty, the checkbox, the icon, the label and what stands at the row's end.
horizontalPaddingDpDp.UnspecifiedThe room between a row's sides and what it holds.
guideWidthDpDp.UnspecifiedThe width of the lines that run down from an open branch where the tree draws them.
labelRoleTypeRole?nullThe type the rows' labels are set in: the body on every platform, and the code's for the keys of a document, which stand under one another letter by letter.

TreeViewColors

What a PantrixTreeView or a PantrixLazyTreeView is painted with, for a tree that does not take the theme's colours: a colour that is set is used, and one that is left out stays the theme's.

ParameterTypeDefaultWhat it is
containerColorColor.UnspecifiedThe fill behind the rows. None: the tree stands on what is behind it.
contentColorColor.UnspecifiedA row's label and its icon. The theme's textPrimary, or on a fill that is not the tree's, the colour that fill gives what stands on it. The twisty and what stands at a row's end are the theme's textSecondary on the theme's own grounds, and this colour elsewhere and where it is given.
selectedContainerColorColor.UnspecifiedThe fill behind the chosen row. The primary role's container.
selectedContentColorColor.UnspecifiedThe chosen row's label, icon and twisty: the colour that reads on selectedContainer. The primary role's onContainer.
guideColorColor.UnspecifiedThe lines that run down from an open branch. The theme's divider on the theme's own grounds. On a fill, where that line would not read, a share of content.
matchColorColor.UnspecifiedWhat is laid behind the letters a filter found. The theme's warning role softened, written in what the theme pairs with it; on a fill a share of what is written there, under letters that keep their colour. A row that cannot be chosen lays a share of it under letters that keep the row's faint colour.

Accessibility