Composables
Docs Login
Tally

Habit detail

package com.composables.tally

import androidx.compose.foundation.background
import androidx.compose.foundation.layout.Arrangement
import androidx.compose.foundation.layout.Box
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.Row
import androidx.compose.foundation.layout.fillMaxWidth
import androidx.compose.foundation.layout.height
import androidx.compose.foundation.layout.padding
import androidx.compose.foundation.layout.size
import androidx.compose.foundation.layout.width
import androidx.compose.runtime.Composable
import androidx.compose.runtime.getValue
import androidx.compose.runtime.mutableStateListOf
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.remember
import androidx.compose.runtime.setValue
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.draw.clip
import androidx.compose.ui.semantics.clearAndSetSemantics
import androidx.compose.ui.semantics.contentDescription
import androidx.compose.ui.unit.dp
import com.composables.tally.components.Icon
import com.composables.tally.components.IconButton
import com.composables.tally.components.IconButtonVariant
import com.composables.tally.components.MonthCalendar
import com.composables.tally.components.Page
import com.composables.tally.components.SegmentedControl
import com.composables.tally.components.StatCard
import com.composables.tally.components.Text
import com.composables.tally.components.TextField
import com.composables.tally.theme.ChartBar
import com.composables.tally.theme.CheckCircle
import com.composables.tally.theme.Crown
import com.composables.tally.theme.Flame
import com.composables.tally.theme.Icons
import com.composables.tally.theme.NotePencil
import com.composables.tally.theme.PaperPlaneRight
import com.composables.tally.theme.PencilSimple
import com.composables.tally.theme.Space
import com.composables.tally.theme.Theme
import kotlinx.datetime.DatePeriod
import kotlinx.datetime.LocalDate
import kotlinx.datetime.YearMonth
import kotlinx.datetime.minus
import kotlinx.datetime.yearMonth

@Composable
fun HabitDetailScreen(
    navigateBack: () -> Unit,
    navigateToEditHabit: (habitId: Int) -> Unit,
    modifier: Modifier = Modifier,
    habitId: Int = sampleHabits.first().id,
) {
    val habit = remember(habitId) { habitById(habitId) }
    val today = remember { today() }
    val log = remember { sampleLog(today) }
    val notes = remember {
        mutableStateListOf<HabitNote>().apply {
            addAll(sampleNotes(today).filter { it.habitId == habitId })
        }
    }
    var tab by remember { mutableStateOf(0) }
    var month by remember { mutableStateOf(today.yearMonth) }
    var draft by remember { mutableStateOf("") }

    fun addNote() {
        // save the note here
        notes.add(0, HabitNote(habit.id, today, draft.trim()))
        draft = ""
    }

    Page(
        title = habit.name,
        onBack = navigateBack,
        modifier = modifier,
        actions = {
            IconButton(
                onClick = { navigateToEditHabit(habit.id) },
                contentDescription = "Edit habit",
            ) {
                Icon(Icons.PencilSimple, contentDescription = null, modifier = Modifier.size(22.dp))
            }
        },
        bottomBar =
            if (tab == 1) {
                {
                    Row(
                        verticalAlignment = Alignment.CenterVertically,
                        horizontalArrangement = Arrangement.spacedBy(Space * 2),
                    ) {
                        TextField(
                            value = draft,
                            onValueChange = { draft = it },
                            label = "Note your thoughts down",
                            modifier = Modifier.weight(1f),
                        )
                        IconButton(
                            onClick = ::addNote,
                            contentDescription = "Add note",
                            enabled = draft.isNotBlank(),
                            variant = IconButtonVariant.Filled,
                        ) {
                            Icon(
                                Icons.PaperPlaneRight,
                                contentDescription = null,
                                modifier = Modifier.size(20.dp),
                            )
                        }
                    }
                }
            } else null,
    ) {
        SegmentedControl(
            options = listOf("Progress", "Notes"),
            selected = tab,
            onSelect = { tab = it },
        )
        if (tab == 0) HabitProgress(habit, log, today, month) { month = it } else HabitNotes(notes)
    }
}

@Composable
private fun HabitProgress(
    habit: Habit,
    log: HabitLog,
    today: LocalDate,
    month: YearMonth,
    onMonthChange: (YearMonth) -> Unit,
) {
    val from = today.minus(DatePeriod(days = 89))
    val streaks = log.streaks(habit, from, today)
    val last30 = log.doneDays(habit, today.minus(DatePeriod(days = 29)), today)
    Column(verticalArrangement = Arrangement.spacedBy(Space * 3)) {
        Row(horizontalArrangement = Arrangement.spacedBy(Space * 3)) {
            StatCard(
                "${log.streak(habit, today)} days",
                "Current streak",
                Icons.Flame,
                Theme.colors.ember,
                Modifier.weight(1f),
            )
            StatCard(
                "${streaks.firstOrNull()?.length ?: 0} days",
                "Best streak",
                Icons.Crown,
                Theme.colors.amber,
                Modifier.weight(1f),
            )
        }
        Row(horizontalArrangement = Arrangement.spacedBy(Space * 3)) {
            StatCard(
                "${last30 * 100 / 30}%",
                "Last 30 days",
                Icons.ChartBar,
                Theme.colors.sky,
                Modifier.weight(1f),
            )
            StatCard(
                "${log.doneDays(habit, from, today)} days",
                "Done in 90 days",
                Icons.CheckCircle,
                Theme.colors.meadow,
                Modifier.weight(1f),
            )
        }
    }
    Box(
        Modifier.fillMaxWidth()
            .clip(Theme.shapes.medium)
            .background(Theme.colors.surface)
            .padding(Space * 4)
    ) {
        MonthCalendar(
            month = month,
            today = today,
            isDone = { log.isDone(habit, it) },
            color = habit.color.color,
            onMonthChange = onMonthChange,
        )
    }
    if (streaks.isNotEmpty())
        Column(verticalArrangement = Arrangement.spacedBy(Space * 3)) {
            Text("Best streaks", style = Theme.typography.title)
            val longest = streaks.first().length
            streaks.take(3).forEach { range -> StreakBar(range, longest, habit) }
        }
}

@Composable
private fun StreakBar(range: ClosedRange<LocalDate>, longest: Int, habit: Habit) {
    val label = "${range.start.shortLabel} – ${range.endInclusive.shortLabel}"
    Column(
        Modifier.fillMaxWidth().clearAndSetSemantics {
            contentDescription = "$label, ${range.length} days"
        },
        verticalArrangement = Arrangement.spacedBy(Space),
    ) {
        Row {
            Text(label, style = Theme.typography.caption, modifier = Modifier.weight(1f))
            Text("${range.length} days", style = Theme.typography.caption)
        }
        Box(
            Modifier.fillMaxWidth()
                .height(10.dp)
                .clip(Theme.shapes.fullyRounded)
                .background(Theme.colors.surfaceVariant)
        ) {
            Box(
                Modifier.fillMaxWidth(range.length / longest.toFloat())
                    .height(10.dp)
                    .clip(Theme.shapes.fullyRounded)
                    .background(habit.color.color)
            )
        }
    }
}

@Composable
private fun HabitNotes(notes: List<HabitNote>) {
    if (notes.isEmpty()) {
        Column(
            Modifier.fillMaxWidth().padding(vertical = Space * 12),
            horizontalAlignment = Alignment.CenterHorizontally,
            verticalArrangement = Arrangement.spacedBy(Space * 2),
        ) {
            Icon(
                Icons.NotePencil,
                contentDescription = null,
                modifier = Modifier.size(32.dp),
                tint = Theme.colors.onBackgroundMuted,
            )
            Text("No notes yet", style = Theme.typography.title)
            Text(
                "Write down how today went.",
                color = Theme.colors.onBackgroundMuted,
            )
        }
        return
    }
    Column(verticalArrangement = Arrangement.spacedBy(Space * 3)) {
        notes.forEach { note ->
            Row(horizontalArrangement = Arrangement.spacedBy(Space * 3)) {
                Column(Modifier.width(48.dp), horizontalAlignment = Alignment.CenterHorizontally) {
                    Text(
                        note.date.month.name.take(3),
                        style = Theme.typography.caption,
                        color = Theme.colors.onBackgroundMuted,
                    )
                    Text(note.date.day.toString(), style = Theme.typography.title)
                }
                Text(
                    note.text,
                    modifier =
                        Modifier.weight(1f)
                            .clip(Theme.shapes.medium)
                            .background(Theme.colors.surface)
                            .padding(Space * 4),
                    color = Theme.colors.onSurface,
                )
            }
        }
    }
}

internal val LocalDate.shortLabel: String
    get() = "${month.name.take(3).lowercase().replaceFirstChar { it.uppercase() }} $day"

More screens from Tally

by Alex Styl

Search screens and components

Screen flows

Screens

UI Elements

One Android lesson, every Wednesday

Building Android apps?

What Alex learned building Android apps for 14 years, so you don't have to. Reads in under a minute.

Join 3,500+ Android developers. Unsubscribe any time.

You're subscribed

The next lesson lands in on Wednesday.