Composables
Docs Login
Tally

Account

package com.composables.tally

import androidx.compose.foundation.background
import androidx.compose.foundation.interaction.MutableInteractionSource
import androidx.compose.foundation.layout.Arrangement
import androidx.compose.foundation.layout.Box
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.PaddingValues
import androidx.compose.foundation.layout.Row
import androidx.compose.foundation.layout.WindowInsets
import androidx.compose.foundation.layout.WindowInsetsSides
import androidx.compose.foundation.layout.fillMaxSize
import androidx.compose.foundation.layout.fillMaxWidth
import androidx.compose.foundation.layout.only
import androidx.compose.foundation.layout.padding
import androidx.compose.foundation.layout.safeDrawing
import androidx.compose.foundation.layout.size
import androidx.compose.foundation.layout.statusBars
import androidx.compose.foundation.layout.union
import androidx.compose.foundation.layout.widthIn
import androidx.compose.foundation.layout.windowInsetsPadding
import androidx.compose.foundation.rememberScrollState
import androidx.compose.foundation.verticalScroll
import androidx.compose.runtime.Composable
import androidx.compose.runtime.LaunchedEffect
import androidx.compose.runtime.getValue
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.unit.dp
import com.composables.compose.ripple.rememberRippleIndication
import com.composables.tally.components.AlertDialog
import com.composables.tally.components.Button
import com.composables.tally.components.ButtonVariant
import com.composables.tally.components.Destination
import com.composables.tally.components.Icon
import com.composables.tally.components.IconButton
import com.composables.tally.components.MainNavigationScaffold
import com.composables.tally.components.ModalBottomSheet
import com.composables.tally.components.OptionGroup
import com.composables.tally.components.OptionRow
import com.composables.tally.components.OptionToggle
import com.composables.tally.components.Page
import com.composables.tally.components.Section
import com.composables.tally.components.SegmentedControl
import com.composables.tally.components.Text
import com.composables.tally.components.TextField
import com.composables.tally.components.Toast
import com.composables.tally.theme.ArrowCounterClockwise
import com.composables.tally.theme.Bell
import com.composables.tally.theme.CalendarBlank
import com.composables.tally.theme.CaretRight
import com.composables.tally.theme.ChatCircle
import com.composables.tally.theme.Crown
import com.composables.tally.theme.FileText
import com.composables.tally.theme.Icons
import com.composables.tally.theme.ListChecks
import com.composables.tally.theme.Plus
import com.composables.tally.theme.ShieldCheck
import com.composables.tally.theme.SignOut
import com.composables.tally.theme.Space
import com.composables.tally.theme.SpeakerHigh
import com.composables.tally.theme.Theme
import com.composables.tally.theme.Trash
import com.composeunstyled.UnstyledButton
import kotlinx.coroutines.delay
import kotlinx.datetime.DayOfWeek

@Composable
fun SettingsScreen(
    navigateToAccount: () -> Unit,
    navigateToManageHabits: () -> Unit,
    navigateToPro: () -> Unit,
    navigateToHelp: () -> Unit,
    navigateToPrivacyPolicy: () -> Unit,
    navigateToTerms: () -> Unit,
    navigateToHome: () -> Unit,
    navigateToProgress: () -> Unit,
    modifier: Modifier = Modifier,
) {
    MainNavigationScaffold(
        selected = Destination.Settings,
        navigateToHome = navigateToHome,
        navigateToProgress = navigateToProgress,
        navigateToSettings = {},
        modifier = modifier,
    ) { contentPadding ->
        SettingsContent(
            navigateToAccount,
            navigateToManageHabits,
            navigateToPro,
            navigateToHelp,
            navigateToPrivacyPolicy,
            navigateToTerms,
            contentPadding,
        )
    }
}

@Composable
fun SettingsContent(
    navigateToAccount: () -> Unit,
    navigateToManageHabits: () -> Unit,
    navigateToPro: () -> Unit,
    navigateToHelp: () -> Unit,
    navigateToPrivacyPolicy: () -> Unit,
    navigateToTerms: () -> Unit,
    contentPadding: PaddingValues,
    modifier: Modifier = Modifier,
) {
    var reminders by remember { mutableStateOf(true) }
    var sounds by remember { mutableStateOf(true) }
    var weekStart by remember { mutableStateOf(DayOfWeek.MONDAY) }
    var choosingWeekStart by remember { mutableStateOf(false) }
    var toast by remember { mutableStateOf<String?>(null) }
    LaunchedEffect(toast) {
        if (toast != null) {
            delay(2000)
            toast = null
        }
    }

    fun setReminders(on: Boolean) {
        // save the reminder preference here
        reminders = on
    }

    fun setSounds(on: Boolean) {
        // save the sound preference here
        sounds = on
    }

    fun setWeekStart(day: DayOfWeek) {
        // save the first day of the week here
        weekStart = day
        choosingWeekStart = false
    }

    fun restorePurchases() {
        // restore purchases here
        toast = "Purchases restored"
    }

    Box(modifier.fillMaxSize()) {
        Column(
            Modifier.fillMaxSize()
                .verticalScroll(rememberScrollState())
                .windowInsetsPadding(
                    WindowInsets.statusBars.union(
                        WindowInsets.safeDrawing.only(WindowInsetsSides.Horizontal)
                    )
                )
                .padding(bottom = contentPadding.calculateBottomPadding()),
            horizontalAlignment = Alignment.CenterHorizontally,
        ) {
            Column(
                Modifier.widthIn(max = 560.dp)
                    .fillMaxWidth()
                    .padding(horizontal = Space * 4, vertical = Space * 4),
                verticalArrangement = Arrangement.spacedBy(Space * 6),
            ) {
                Text("Settings", style = Theme.typography.display)
                ProfileCard(onClick = navigateToAccount)
                ProCard(onClick = navigateToPro)
                Section("Habits") {
                    OptionRow(
                        "Manage habits",
                        onClick = navigateToManageHabits,
                        icon = Icons.ListChecks,
                        value = "${sampleHabits.size} active",
                        navigates = true,
                    )
                    OptionRow(
                        "Week starts on",
                        onClick = { choosingWeekStart = true },
                        icon = Icons.CalendarBlank,
                        value = weekStart.name.lowercase().replaceFirstChar { it.uppercase() },
                        navigates = true,
                    )
                }
                Section("Preferences") {
                    OptionToggle(
                        "Reminders",
                        reminders,
                        ::setReminders,
                        description = "A nudge at each habit's time",
                        icon = Icons.Bell,
                    )
                    OptionToggle("Sounds", sounds, ::setSounds, icon = Icons.SpeakerHigh)
                }
                Section("Plan") {
                    OptionRow(
                        "Tally Pro",
                        onClick = navigateToPro,
                        icon = Icons.Crown,
                        navigates = true,
                    )
                    OptionRow(
                        "Restore purchases",
                        onClick = ::restorePurchases,
                        icon = Icons.ArrowCounterClockwise,
                    )
                }
                Section("Support", footer = "Tally 1.0") {
                    OptionRow(
                        "Help and feedback",
                        onClick = navigateToHelp,
                        icon = Icons.ChatCircle,
                        navigates = true,
                    )
                    OptionRow(
                        "Privacy policy",
                        onClick = navigateToPrivacyPolicy,
                        icon = Icons.ShieldCheck,
                        navigates = true,
                    )
                    OptionRow(
                        "Terms of use",
                        onClick = navigateToTerms,
                        icon = Icons.FileText,
                        navigates = true,
                    )
                }
            }
        }
        Toast(
            visible = toast != null,
            message = toast.orEmpty(),
            modifier =
                Modifier.align(Alignment.BottomCenter)
                    .padding(bottom = contentPadding.calculateBottomPadding() + Space * 4),
        )
        ModalBottomSheet(
            visible = choosingWeekStart,
            onDismiss = { choosingWeekStart = false },
            title = "Week starts on",
        ) {
            OptionGroup {
                listOf(DayOfWeek.MONDAY, DayOfWeek.SUNDAY).forEach { day ->
                    OptionRow(
                        day.name.lowercase().replaceFirstChar { it.uppercase() },
                        onClick = { setWeekStart(day) },
                        selected = day == weekStart,
                    )
                }
            }
        }
    }
}

@Composable
private fun ProfileCard(onClick: () -> Unit) {
    UnstyledButton(
        onClick = onClick,
        modifier =
            Modifier.fillMaxWidth().clip(Theme.shapes.medium).background(Theme.colors.surface),
        contentPadding = PaddingValues(Space * 4),
        indication = rememberRippleIndication(color = Theme.colors.onSurface),
        interactionSource = remember { MutableInteractionSource() },
    ) {
        Row(
            verticalAlignment = Alignment.CenterVertically,
            horizontalArrangement = Arrangement.spacedBy(Space * 3),
        ) {
            Avatar(Account.name)
            Column(Modifier.weight(1f)) {
                Text(Account.name, style = Theme.typography.title, color = Theme.colors.onSurface)
                Text(
                    "Account and sign in",
                    style = Theme.typography.caption,
                    color = Theme.colors.onBackgroundMuted,
                )
            }
            Icon(
                Icons.CaretRight,
                contentDescription = null,
                modifier = Modifier.size(16.dp),
                tint = Theme.colors.onBackgroundMuted,
            )
        }
    }
}

@Composable
private fun ProCard(onClick: () -> Unit) {
    Column(
        Modifier.fillMaxWidth()
            .clip(Theme.shapes.medium)
            .background(Theme.colors.amberLight)
            .padding(Space * 4),
        verticalArrangement = Arrangement.spacedBy(Space * 3),
    ) {
        Row(
            verticalAlignment = Alignment.CenterVertically,
            horizontalArrangement = Arrangement.spacedBy(Space * 2),
        ) {
            Icon(
                Icons.Crown,
                contentDescription = null,
                modifier = Modifier.size(20.dp),
                tint = Theme.colors.onBackground,
            )
            Text("Tally Pro", style = Theme.typography.label, color = Theme.colors.onBackground)
        }
        Text(
            "Unlimited habits, your full history and notes on every habit.",
            color = Theme.colors.onBackground,
        )
        Button(onClick = onClick) { Text("Try Tally Pro") }
    }
}

@Composable
private fun Avatar(name: String, large: Boolean = false) {
    Box(
        Modifier.size(if (large) 72.dp else 48.dp)
            .clip(Theme.shapes.fullyRounded)
            .background(Theme.colors.orchidLight),
        contentAlignment = Alignment.Center,
    ) {
        Text(
            name.split(" ").mapNotNull { it.firstOrNull() }.take(2).joinToString(""),
            style = if (large) Theme.typography.title else Theme.typography.label,
            color = Theme.colors.onBackground,
        )
    }
}

@Composable
fun AccountScreen(
    navigateBack: () -> Unit,
    navigateToWelcome: () -> Unit,
    modifier: Modifier = Modifier,
) {
    var name by remember { mutableStateOf(Account.name) }
    var confirm by remember { mutableStateOf<AccountAction?>(null) }

    fun signOut() {
        // sign out here
        navigateToWelcome()
    }

    fun resetData() {
        // reset the habit data here
        navigateBack()
    }

    fun deleteAccount() {
        // delete the account here
        navigateToWelcome()
    }

    Page(
        title = "Account",
        onBack = navigateBack,
        modifier = modifier,
        overlay = {
            val action = confirm
            AlertDialog(
                visible = action != null,
                title = action?.title.orEmpty(),
                message = action?.message.orEmpty(),
                onDismissRequest = { confirm = null },
            ) {
                Button(
                    onClick = {
                        confirm = null
                        when (action) {
                            AccountAction.SignOut -> signOut()
                            AccountAction.Reset -> resetData()
                            AccountAction.Delete -> deleteAccount()
                            null -> {}
                        }
                    },
                    variant =
                        if (action == AccountAction.SignOut) ButtonVariant.Primary
                        else ButtonVariant.Destructive,
                    modifier = Modifier.fillMaxWidth(),
                ) {
                    Text(action?.confirm.orEmpty())
                }
                Button(
                    onClick = { confirm = null },
                    variant = ButtonVariant.Secondary,
                    modifier = Modifier.fillMaxWidth(),
                ) {
                    Text("Cancel")
                }
            }
        },
    ) {
        Column(
            Modifier.fillMaxWidth(),
            horizontalAlignment = Alignment.CenterHorizontally,
            verticalArrangement = Arrangement.spacedBy(Space * 2),
        ) {
            Avatar(name, large = true)
            Text(Account.email, color = Theme.colors.onBackgroundMuted)
            Text(
                "Free plan",
                style = Theme.typography.caption,
                color = Theme.colors.onPrimary,
                modifier =
                    Modifier.clip(Theme.shapes.fullyRounded)
                        .background(Theme.colors.primary)
                        .padding(horizontal = Space * 3, vertical = Space),
            )
        }
        TextField(value = name, onValueChange = { name = it }, label = "Name")
        Section(null) {
            OptionRow(
                "Sign out",
                onClick = { confirm = AccountAction.SignOut },
                icon = Icons.SignOut,
            )
        }
        Section("Danger zone", footer = "Resetting keeps your habits and clears their progress.") {
            OptionRow(
                "Reset habit data",
                onClick = { confirm = AccountAction.Reset },
                icon = Icons.ArrowCounterClockwise,
                destructive = true,
            )
            OptionRow(
                "Delete account",
                onClick = { confirm = AccountAction.Delete },
                icon = Icons.Trash,
                destructive = true,
            )
        }
    }
}

private enum class AccountAction(val title: String, val message: String, val confirm: String) {
    SignOut(
        "Sign out of Tally?",
        "Your habits stay in your account for when you sign back in.",
        "Sign out",
    ),
    Reset(
        "Reset habit data?",
        "Every streak, check-in and note is cleared. Your habits stay.",
        "Reset",
    ),
    Delete(
        "Delete your account?",
        "This deletes your habits and their history. It can't be undone.",
        "Delete account",
    ),
}

@Composable
fun ManageHabitsScreen(
    navigateBack: () -> Unit,
    navigateToEditHabit: (habitId: Int) -> Unit,
    navigateToNewHabit: () -> Unit,
    modifier: Modifier = Modifier,
) {
    var tab by remember { mutableStateOf(0) }
    val habits = if (tab == 0) sampleHabits else archivedHabits
    Page(
        title = "Manage habits",
        onBack = navigateBack,
        modifier = modifier,
        actions = {
            IconButton(onClick = navigateToNewHabit, contentDescription = "New habit") {
                Icon(Icons.Plus, contentDescription = null, modifier = Modifier.size(22.dp))
            }
        },
    ) {
        SegmentedControl(
            options = listOf("Active (${sampleHabits.size})", "Archived (${archivedHabits.size})"),
            selected = tab,
            onSelect = { tab = it },
        )
        OptionGroup {
            habits.forEach { habit ->
                OptionRow(
                    habit.name,
                    onClick = { navigateToEditHabit(habit.id) },
                    description = habit.scheduleLabel,
                    navigates = true,
                )
            }
        }
    }
}

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.