• Stars
    star
    350
  • Rank 121,229 (Top 3 %)
  • Language
    Kotlin
  • License
    MIT License
  • Created over 2 years ago
  • Updated 7 months ago

Reviews

There are no reviews yet. Be the first to send feedback to the community and the maintainers!

Repository Details

🌳 A multiplatform tree view for Jetpack Compose

Maven metadata URL Android API kotlin ktlint License MIT


Bonsai

A batteries-included Tree View for Jetpack Compose

Features

Roadmap

  • iOS support
  • Draggable nodes
  • FileObserver (Android) and/or WatchService (JVM) integration

Import to your project

Add the desired dependencies to your module's build.gradle:

implementation "cafe.adriel.bonsai:bonsai-core:${latest-version}"
implementation "cafe.adriel.bonsai:bonsai-file-system:${latest-version}"
implementation "cafe.adriel.bonsai:bonsai-json:${latest-version}"

Current version: Maven metadata URL

Usage

Bonsai comes with a handy DSL for creating high-performance, customizable trees:

  1. Start by creating a new tree with Tree<T>{}
  2. Create nodes with Leaf<T>() and Branch<T>()
  3. Call Bonsai() to render the tree
@Composable
fun BonsaiExample() {
    val tree = Tree {
        Branch("Mammalia") {
            Branch("Carnivora") {
                Branch("Canidae") {
                    Branch("Canis") {
                        Leaf("Wolf", customIcon = { EmojiIcon("🐺") })
                        Leaf("Dog", customIcon = { EmojiIcon("🐶") })
                    }
                }
                Branch("Felidae") {
                    Branch("Felis") {
                        Leaf("Cat", customIcon = { EmojiIcon("🐱") })
                    }
                    Branch("Panthera") {
                        Leaf("Lion", customIcon = { EmojiIcon("🦁") })
                    }
                }
            }
        }
    }

    Bonsai(tree)
}

Output:

Take a look at the sample app for working examples.

File System integration

Import cafe.adriel.bonsai:bonsai-file-system module to use it.

val tree = FileSystemTree(
    // Also works with java.nio.file.Path and okio.Path
    rootPath = File(path),
    // To show or not the root directory in the tree
    selfInclude = true
)

Bonsai(
    tree = tree,
    // Custom style
    style = FileSystemBonsaiStyle()
)

Output:

JSON integration

Import cafe.adriel.bonsai:bonsai-json module to use it.

val tree = JsonTree(
    // Sample JSON from https://gateway.marvel.com/v1/public/characters
    json = responseJson
)

Bonsai(
    tree = tree,
    // Custom style
    style = JsonBonsaiStyle()
)

Output:

Expanding & Collapsing

Easily control the expanded/collapsed state of your Tree:

  • toggleExpansion(node)
  • collapseRoot() / expandRoot()
  • collapseAll() / expandAll()
  • collapseFrom(depth) / expandUntil(depth)
  • collapseNode(node) / expandNode(node)

Selecting

Selected/Unselected state is also pretty simple to control:

  • selectedNodes
  • toggleSelection(node)
  • selectNode(node) / unselectNode(node)
  • clearSelection()

Click handling

Its also possible to set custom click behaviors for your Tree. Control single, double and long clicks by using the expand and select APIs.

Bonsai(
    tree = tree,
    onClick = { node ->
        tree.clearSelection()
        tree.toggleExpansion(node)
    },
    onDoubleClick = { node -> /* ... */ },
    onLongClick = { node -> /* ... */ }
)

Styling

Change your Tree appearance as you wish. Take a look at BonsaiStyle class for all available customizations.

Bonsai(
    tree = tree,
    style = BonsaiStyle(
        toggleIconRotationDegrees = 0f,
        toggleIcon = { node ->
            rememberVectorPainter(
                if (node is BranchNode && node.isExpanded) Icons.Outlined.UnfoldLess
                else Icons.Outlined.UnfoldMore
            )
        },
        nodeIconSize = 18.dp,
        nodeShape = CutCornerShape(percent = 20),
        nodeCollapsedIcon = { rememberVectorPainter(Icons.Outlined.Circle) },
        nodeExpandedIcon = { rememberVectorPainter(Icons.Outlined.Adjust) },
        nodeNameTextStyle = MaterialTheme.typography.overline
    )
)

Output:

Custom nodes

Need a deeper customization? You can set customIcons and customNames for each Leaf<T>() and Branch<T>() nodes.

Leaf(
    content = "Wolf", 
    customIcon = { EmojiIcon("🐺") }
)

Output:

More Repositories

1

voyager

🛸 A pragmatic navigation library for Jetpack Compose
Kotlin
2,466
star
2

AndroidAudioRecorder

A fancy audio recorder lib for Android. Supports WAV format at 48kHz.
Java
1,622
star
3

AndroidAudioConverter

Convert audio files inside your Android app easily. Supported formats: AAC, MP3, M4A, WMA, WAV and FLAC.
Java
1,319
star
4

lyricist

🌎 The missing I18N/L10N (internationalization/localization) multiplatform library for Jetpack Compose!
Kotlin
677
star
5

krumbsview

🍞 The ultimate breadcrumbs view for Android!
Kotlin
186
star
6

chroma

🎶 Chromatic tuner app for Android
Kotlin
111
star
7

pufferdb

🐡 An Android & JVM key-value storage powered by Protobuf and Coroutines
Kotlin
100
star
8

broker

💬 Publish-Subscribe (a.k.a Pub/Sub, EventBus) library for Android and JVM built with Coroutines
Kotlin
95
star
9

AndroidOAuth

A simple way to authenticate with Google and Facebook using OAuth 2.0 in Android
Java
88
star
10

hal

🔴 A non-deterministic finite-state machine for Android & JVM that won't let you down
Kotlin
79
star
11

satchel

🎒 A fast, secure and modular key-value storage with batteries-included for Android and JVM.
Kotlin
71
star
12

KBus

Dead simple EventBus for Android made with Kotlin and RxJava 2
Kotlin
46
star
13

NoMansWallpaperApp

Looking for your next No Man's Sky wallpaper?
Kotlin
38
star
14

kaptain

👨‍✈️ multi-module navigation on Android has never been so easier!
Kotlin
27
star
15

AndroidStreamable

Unofficial https://streamable.com API Wrapper for Android
Java
27
star
16

dalek

🤖 UI driven state machine for Android & JVM that will exterminate your bugs
Kotlin
26
star
17

CrypAndroidApp

A cryptocurrency portfolio tracker app for Android
Kotlin
26
star
18

NMSAlphabetAndroidApp

An unofficial translator app for No Man's Sky
Java
25
star
19

AndroidCoroutineScopes

This lib implements the most common CoroutineScopes used in Android apps.
Kotlin
17
star
20

gwent-wallpapers

🃏🐺Unofficial Android app with more than 1.000 cards from GWENT: The Witcher Card Game as mobile wallpapers
Kotlin
16
star
21

ReadnBuyAndroidApp

Android app developed at the Vanhackathon for Shopify's challenge. Coded with Kotlin, RxJava and MVP.
Kotlin
16
star
22

BeMyEyesXamarinApp

Describes photos via audio to the visually impaired user
C#
13
star
23

VoxRecorderAndroidApp

An audio recorder app for Android built with Kotlin, RxJava and MVP
Kotlin
10
star
24

MoovAndroidApp

Concept Android app
Kotlin
9
star
25

GreenHellCompanionApp

Unofficial companion app for the game Green Hell
Kotlin
4
star
26

gwent-cards

🃏🐺 All cards from GWENT: The Witcher Card Game
4
star
27

RecifeBomDeBola

Versão mobile de https://recifebomdebola.wordpress.com
Java
3
star
28

cryp-website

Cryp app's website
HTML
2
star
29

MinhaEscola

Minha Escola é um aplicativo Android que pode ser usado por qualquer escola para exibir os horários e histórico escolar de seus alunos.
Java
2
star
30

Scryp

REST API powered by Moneywagon: the universal cryptocurrency multichain library
Python
2
star
31

S-Task

Just a simple, beautiful, offline and open source To Do list for Android 4.0.3+
Java
2
star
32

VaiChoverRecife

App para Firefox OS
JavaScript
2
star
33

PlaystationTrophiesConceptApp

Concept Android app
Kotlin
2
star
34

NMSAlphabetWeb

An unofficial Android app for No Man's Sky (WIP)
CSS
2
star
35

LifeBand

An app + wearable device that can change your life
Java
1
star
36

CryptoUtil

Utility class for encryption
C#
1
star
37

responsive-headings.css

Bring responsiveness to HTML headings
CSS
1
star
38

GuiaServicosSP

Guia de Serviços SP é um aplicativo Android que ajuda os cidadãos paulistas a encontrarem informações sobre serviços públicos do estado de São Paulo mais facilmente.
Java
1
star
39

adriel.cafe

1
star
40

MessagesAndroidApp

A simple app to showcase Kotlin, MVP, RxJava, Realm, Moshi
Kotlin
1
star
41

ChuckNorrisFacts

A Chuck Norris facts Android app
Kotlin
1
star
42

GryphonFramework

A Framework for integrating ontologies and relational databases
Web Ontology Language
1
star
43

DissertacaoDeMestrado

Dissertação de Mestrado defendida por Adriel Café no CIn-UFPE em 04/09/15
1
star
44

PlanetaSustentavel

Planeta Sustentável é um aplicativo Android com diversas dicas essências de práticas sustentáveis. Aprenda a consumir menos recursos da natureza e torne-se um cidadão melhor!
Java
1
star