Refactor habit display and formatting: update activity type display, enhance name and details formatting, and remove monthly progress toggle

This commit is contained in:
bobbert committed 2026-03-05 16:21:05 +00:00
1 parent b302286990
commit db39671a2f
10 files changed
+59 -128

No files matched your search

@@ -5,9 +5,9 @@ import androidx.room.PrimaryKey
/** /**
* Represents a habit tracked by the user. * Represents a habit tracked by the user.
* [name] is the activity type name chosen from the user-created dropdown (e.g. "Gym"). * [name] is the activity type name in FULL CAPS (e.g. "GYM").
* [details] is optional extra info typed by the user (e.g. "Legs", "5K"). * [details] is optional extra info with first-char uppercase (e.g. "Legs", "5k").
* The display name combines them: "Gym(Legs)" when details is present, or just "Gym". * The display name combines them: "GYM(Legs)" when details is present, or just "GYM".
*/ */
@Entity(tableName = "habits") @Entity(tableName = "habits")
data class Habit( data class Habit(
@@ -22,7 +22,13 @@ data class Habit(
val reminderMinute: Int = 0, val reminderMinute: Int = 0,
val isActive: Boolean = true val isActive: Boolean = true
) { ) {
/** Returns the formatted display name: "Name(Details)" or just "Name". */ /** Returns the formatted display name: "NAME(Details)" or just "NAME". */
val displayName: String val displayName: String
get() = if (details.isBlank()) name else "$name($details)" get() {
val upperName = name.uppercase()
if (details.isBlank()) return upperName
val formattedDetails = if (details.length <= 1) details.uppercase()
else details[0].uppercaseChar() + details.substring(1).lowercase()
return "$upperName($formattedDetails)"
}
} }
@@ -132,7 +132,7 @@ fun AddEditHabitScreen(
} else { } else {
viewModel.addActivityType(newTypeName) { success -> viewModel.addActivityType(newTypeName) { success ->
if (success) { if (success) {
selectedActivityName = HabitViewModel.toTitleCase(newTypeName.trim()) selectedActivityName = HabitViewModel.formatName(newTypeName.trim())
nameError = false nameError = false
showAddTypeDialog = false showAddTypeDialog = false
} else { } else {
@@ -265,10 +265,10 @@ fun AddEditHabitScreen(
// Live preview // Live preview
if (selectedActivityName.isNotBlank()) { if (selectedActivityName.isNotBlank()) {
val previewName = if (details.isBlank()) val previewName = if (details.isBlank())
HabitViewModel.toTitleCase(selectedActivityName.trim()) HabitViewModel.formatName(selectedActivityName.trim())
else else
HabitViewModel.toTitleCase(selectedActivityName.trim()) + HabitViewModel.formatName(selectedActivityName.trim()) +
"(" + HabitViewModel.toTitleCase(details.trim()) + ")" "(" + HabitViewModel.formatDetails(details.trim()) + ")"
Text("Will display as: $previewName", Text("Will display as: $previewName",
style = MaterialTheme.typography.labelMedium, style = MaterialTheme.typography.labelMedium,
color = MaterialTheme.colorScheme.primary, color = MaterialTheme.colorScheme.primary,
@@ -197,7 +197,7 @@ private fun AllActivitiesSwipeCard(
} }
} }
Text( Text(
habit.activityType + " • ${habit.targetFrequency}x/week", "${habit.targetFrequency}x / week",
style = MaterialTheme.typography.bodySmall, style = MaterialTheme.typography.bodySmall,
color = MaterialTheme.colorScheme.onSurfaceVariant.copy(alpha = contentAlpha) color = MaterialTheme.colorScheme.onSurfaceVariant.copy(alpha = contentAlpha)
) )
@@ -295,7 +295,7 @@ private fun StreakCard(habit: Habit, streak: Int, onClick: () -> Unit) {
Column(modifier = Modifier.weight(1f)) { Column(modifier = Modifier.weight(1f)) {
Text(habit.displayName, style = MaterialTheme.typography.titleSmall, Text(habit.displayName, style = MaterialTheme.typography.titleSmall,
fontWeight = FontWeight.SemiBold) fontWeight = FontWeight.SemiBold)
Text(habit.activityType + " • ${habit.targetFrequency}x/week", Text("${habit.targetFrequency}x / week",
style = MaterialTheme.typography.bodySmall, style = MaterialTheme.typography.bodySmall,
color = MaterialTheme.colorScheme.onSurfaceVariant) color = MaterialTheme.colorScheme.onSurfaceVariant)
} }
@@ -24,9 +24,6 @@ import androidx.compose.runtime.Composable
import androidx.compose.runtime.LaunchedEffect import androidx.compose.runtime.LaunchedEffect
import androidx.compose.runtime.collectAsState import androidx.compose.runtime.collectAsState
import androidx.compose.runtime.getValue 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.Alignment
import androidx.compose.ui.Modifier import androidx.compose.ui.Modifier
import androidx.compose.ui.text.font.FontWeight import androidx.compose.ui.text.font.FontWeight
@@ -53,7 +50,6 @@ fun HabitDetailScreen(
val todayLogs by viewModel.todayLogs.collectAsState() val todayLogs by viewModel.todayLogs.collectAsState()
val isCompletedToday = todayLogs.any { it.habitId == habitId && it.completed } val isCompletedToday = todayLogs.any { it.habitId == habitId && it.completed }
var showMonth by remember { mutableStateOf(false) }
Scaffold { padding -> Scaffold { padding ->
@@ -124,32 +120,18 @@ fun HabitDetailScreen(
Modifier.weight(1f)) Modifier.weight(1f))
} }
// Weekly/Monthly progress with toggle // Weekly progress
Card(modifier = Modifier.fillMaxWidth(), elevation = CardDefaults.cardElevation(2.dp)) { Card(modifier = Modifier.fillMaxWidth(), elevation = CardDefaults.cardElevation(2.dp)) {
Column(modifier = Modifier.padding(16.dp)) { Column(modifier = Modifier.padding(16.dp)) {
Row(
modifier = Modifier.fillMaxWidth(),
horizontalArrangement = Arrangement.SpaceBetween,
verticalAlignment = Alignment.CenterVertically
) {
Text( Text(
if (showMonth) "Monthly Progress" else "Weekly Progress", "Weekly Progress",
style = MaterialTheme.typography.titleMedium, style = MaterialTheme.typography.titleMedium,
fontWeight = FontWeight.SemiBold fontWeight = FontWeight.SemiBold
) )
TextButton(onClick = { showMonth = !showMonth }) { val detailProgress by viewModel.weeklyProgress(habitId)
.collectAsState(initial = 0f)
Text( Text(
if (showMonth) "Week ▲" else "Month ▼", "${(detailProgress * 100).toInt()}% of weekly goal",
style = MaterialTheme.typography.labelMedium,
fontWeight = FontWeight.Bold,
color = MaterialTheme.colorScheme.primary
)
}
}
val detailProgress by (if (showMonth) viewModel.monthlyProgress(habitId)
else viewModel.weeklyProgress(habitId)).collectAsState(initial = 0f)
Text(
"${(detailProgress * 100).toInt()}% of ${if (showMonth) "monthly" else "weekly"} goal",
style = MaterialTheme.typography.bodyMedium, style = MaterialTheme.typography.bodyMedium,
color = MaterialTheme.colorScheme.onSurfaceVariant color = MaterialTheme.colorScheme.onSurfaceVariant
) )
@@ -21,7 +21,6 @@ import androidx.compose.material3.CardDefaults
import androidx.compose.material3.MaterialTheme import androidx.compose.material3.MaterialTheme
import androidx.compose.material3.Scaffold import androidx.compose.material3.Scaffold
import androidx.compose.material3.Text import androidx.compose.material3.Text
import androidx.compose.material3.TextButton
import androidx.compose.runtime.Composable import androidx.compose.runtime.Composable
import androidx.compose.runtime.LaunchedEffect import androidx.compose.runtime.LaunchedEffect
import androidx.compose.runtime.collectAsState import androidx.compose.runtime.collectAsState
@@ -55,14 +54,11 @@ fun HomeScreen(
val completedIds = todayLogs.filter { it.completed }.map { it.habitId }.toSet() val completedIds = todayLogs.filter { it.completed }.map { it.habitId }.toSet()
val activeHabits = habits.filter { it.isActive } val activeHabits = habits.filter { it.isActive }
// Toggle between "Week" and "Month" view for the progress dropdown
var showMonth by remember { mutableStateOf(false) }
Scaffold { padding -> Scaffold { padding ->
Column(modifier = Modifier.fillMaxSize().padding(padding)) { Column(modifier = Modifier.fillMaxSize().padding(padding)) {
ScreenHeader(title = "Manage Activities", onBack = onNavigateBack) ScreenHeader(title = "Manage Activities", onBack = onNavigateBack)
// Summary bar // Summary bar – today only
Column( Column(
modifier = Modifier.fillMaxWidth() modifier = Modifier.fillMaxWidth()
.background(MaterialTheme.colorScheme.primaryContainer) .background(MaterialTheme.colorScheme.primaryContainer)
@@ -80,25 +76,6 @@ fun HomeScreen(
fontWeight = FontWeight.Medium, fontWeight = FontWeight.Medium,
color = MaterialTheme.colorScheme.onPrimaryContainer color = MaterialTheme.colorScheme.onPrimaryContainer
) )
// Week / Month toggle
Row(
modifier = Modifier.fillMaxWidth().padding(top = 4.dp),
verticalAlignment = Alignment.CenterVertically
) {
Text(
if (showMonth) "Showing: Month" else "Showing: Week",
style = MaterialTheme.typography.labelMedium,
color = MaterialTheme.colorScheme.onPrimaryContainer
)
TextButton(onClick = { showMonth = !showMonth }) {
Text(
if (showMonth) "Switch to Week ▲" else "Expand to Month ▼",
style = MaterialTheme.typography.labelMedium,
fontWeight = FontWeight.Bold,
color = MaterialTheme.colorScheme.primary
)
}
}
} }
if (activeHabits.isEmpty()) { if (activeHabits.isEmpty()) {
@@ -127,8 +104,7 @@ fun HomeScreen(
onSwipeRight = { viewModel.toggleTodayLog(habit.id) }, onSwipeRight = { viewModel.toggleTodayLog(habit.id) },
onSwipeLeft = { viewModel.disableHabit(habit) }, onSwipeLeft = { viewModel.disableHabit(habit) },
onClick = { onHabitClick(habit.id) }, onClick = { onHabitClick(habit.id) },
viewModel = viewModel, viewModel = viewModel
showMonth = showMonth
) )
} }
} }
@@ -151,17 +127,13 @@ fun HomeScreen(
* Habit card: * Habit card:
* • swipe left→right = mark complete (or undo) * • swipe left→right = mark complete (or undo)
* • swipe right→left = disable * • swipe right→left = disable
* • streak counter (✓ per consecutive day) replaces the old − button * • streak counter (✓ per consecutive day)
*/ */
@Composable @Composable
private fun SwipeHabitCard( private fun SwipeHabitCard(
habit: Habit, completed: Boolean, onSwipeRight: () -> Unit, habit: Habit, completed: Boolean, onSwipeRight: () -> Unit,
onSwipeLeft: () -> Unit, onClick: () -> Unit, viewModel: HabitViewModel, onSwipeLeft: () -> Unit, onClick: () -> Unit, viewModel: HabitViewModel
showMonth: Boolean
) { ) {
val progress by (if (showMonth) viewModel.monthlyProgress(habit.id)
else viewModel.weeklyProgress(habit.id)).collectAsState(initial = 0f)
// Streak counter // Streak counter
var streak by remember { mutableIntStateOf(0) } var streak by remember { mutableIntStateOf(0) }
LaunchedEffect(habit.id, completed) { LaunchedEffect(habit.id, completed) {
@@ -241,15 +213,10 @@ private fun SwipeHabitCard(
Text(habit.displayName, style = MaterialTheme.typography.titleMedium, Text(habit.displayName, style = MaterialTheme.typography.titleMedium,
fontWeight = FontWeight.SemiBold) fontWeight = FontWeight.SemiBold)
Text( Text(
habit.activityType + " • ${habit.targetFrequency}x/week", "${habit.targetFrequency}x / week",
style = MaterialTheme.typography.bodySmall, style = MaterialTheme.typography.bodySmall,
color = MaterialTheme.colorScheme.onSurfaceVariant color = MaterialTheme.colorScheme.onSurfaceVariant
) )
Text(
"${if (showMonth) "Monthly" else "Weekly"}: ${(progress * 100).toInt()}%",
style = MaterialTheme.typography.labelSmall,
color = MaterialTheme.colorScheme.onSurfaceVariant
)
} }
// Streak counter – show ✓ per consecutive day (max 7 visible) // Streak counter – show ✓ per consecutive day (max 7 visible)
val visibleStreak = streak.coerceAtMost(7) val visibleStreak = streak.coerceAtMost(7)
@@ -17,8 +17,6 @@ import androidx.compose.material3.MaterialTheme
import androidx.compose.material3.Text import androidx.compose.material3.Text
import androidx.compose.material3.TextButton import androidx.compose.material3.TextButton
import androidx.compose.runtime.Composable import androidx.compose.runtime.Composable
import androidx.compose.runtime.collectAsState
import androidx.compose.runtime.getValue
import androidx.compose.ui.Alignment import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier import androidx.compose.ui.Modifier
import androidx.compose.ui.text.font.FontWeight import androidx.compose.ui.text.font.FontWeight
@@ -81,9 +79,6 @@ fun HabitCard(
badge: @Composable (() -> Unit)? = null, badge: @Composable (() -> Unit)? = null,
trailing: @Composable (() -> Unit)? = null trailing: @Composable (() -> Unit)? = null
) { ) {
val weeklyProgress by viewModel.weeklyProgress(habit.id)
.collectAsState(initial = 0f)
Card( Card(
onClick = onClick, onClick = onClick,
modifier = Modifier.fillMaxWidth(), modifier = Modifier.fillMaxWidth(),
@@ -127,16 +122,10 @@ fun HabitCard(
} }
Spacer(modifier = Modifier.height(2.dp)) Spacer(modifier = Modifier.height(2.dp))
Text( Text(
text = habit.activityType + " • ${habit.targetFrequency}x/week", text = "${habit.targetFrequency}x / week",
style = MaterialTheme.typography.bodySmall, style = MaterialTheme.typography.bodySmall,
color = MaterialTheme.colorScheme.onSurfaceVariant.copy(alpha = contentAlpha) color = MaterialTheme.colorScheme.onSurfaceVariant.copy(alpha = contentAlpha)
) )
Spacer(modifier = Modifier.height(4.dp))
Text(
text = "Weekly: ${(weeklyProgress * 100).toInt()}%",
style = MaterialTheme.typography.labelSmall,
color = MaterialTheme.colorScheme.onSurfaceVariant.copy(alpha = 0.7f * contentAlpha)
)
} }
if (trailing != null) { if (trailing != null) {
@@ -29,30 +29,29 @@ class HabitViewModel(application: Application) : AndroidViewModel(application) {
companion object { companion object {
/** /**
* Converts text to title-case: lowercase everything, then uppercase * Formats the activity name: FULL CAPS for the main name.
* the first letter of each word. Handles parentheses properly so * e.g. "gym" → "GYM", "running" → "RUNNING"
* "GYM(LEGS)" → "Gym(Legs)" and "gym(legs)" → "Gym(Legs)". */
fun formatName(input: String): String {
return input.trim().uppercase()
}
/**
* Formats the details/type text: first character uppercase, rest lowercase.
* e.g. "LEGS" → "Legs", "upper body" → "Upper body"
*/
fun formatDetails(input: String): String {
val trimmed = input.trim()
if (trimmed.isBlank()) return trimmed
return trimmed[0].uppercaseChar() + trimmed.substring(1).lowercase()
}
/**
* Legacy helper – kept for activity type names which use title-case.
* Converts text so first character is uppercase, rest lowercase.
*/ */
fun toTitleCase(input: String): String { fun toTitleCase(input: String): String {
if (input.isBlank()) return input return formatDetails(input)
val sb = StringBuilder()
var capitalizeNext = true
for (ch in input) {
when {
ch == '(' || ch == ')' || ch == ' ' || ch == '-' -> {
sb.append(ch)
capitalizeNext = true
}
capitalizeNext -> {
sb.append(ch.uppercaseChar())
capitalizeNext = false
}
else -> {
sb.append(ch.lowercaseChar())
}
}
}
return sb.toString()
} }
} }
@@ -65,7 +64,7 @@ class HabitViewModel(application: Application) : AndroidViewModel(application) {
*/ */
fun addActivityType(name: String, onResult: (Boolean) -> Unit = {}) { fun addActivityType(name: String, onResult: (Boolean) -> Unit = {}) {
viewModelScope.launch { viewModelScope.launch {
val formatted = toTitleCase(name.trim()) val formatted = formatName(name.trim())
if (formatted.isBlank()) { if (formatted.isBlank()) {
onResult(false) onResult(false)
return@launch return@launch
@@ -179,18 +178,6 @@ class HabitViewModel(application: Application) : AndroidViewModel(application) {
} }
} }
// ── Monthly progress for a habit ────────────────────────
fun monthlyProgress(habitId: Int): Flow<Float> {
return repository.getLogsForHabit(habitId).map { logs ->
val monthAgo = todayStart - 29 * 86_400_000L
val thisMonthCount = logs.count { it.completed && it.date >= monthAgo }
val habit = repository.getHabitByIdOnce(habitId)
val weeklyTarget = habit?.targetFrequency ?: 7
val monthlyTarget = (weeklyTarget * 4.3).toInt().coerceAtLeast(1)
(thisMonthCount.toFloat() / monthlyTarget).coerceIn(0f, 1f)
}
}
// ── Duplicate check ───────────────────────────────────── // ── Duplicate check ─────────────────────────────────────
suspend fun isDuplicate(name: String, details: String, excludeId: Int? = null): Boolean { suspend fun isDuplicate(name: String, details: String, excludeId: Int? = null): Boolean {
val existing = repository.findDuplicate(name.trim(), details.trim()) val existing = repository.findDuplicate(name.trim(), details.trim())
@@ -210,9 +197,9 @@ class HabitViewModel(application: Application) : AndroidViewModel(application) {
onResult: (Boolean) -> Unit = {} onResult: (Boolean) -> Unit = {}
) { ) {
viewModelScope.launch { viewModelScope.launch {
val formattedName = toTitleCase(name.trim()) val formattedName = formatName(name.trim())
val formattedDetails = toTitleCase(details.trim()) val formattedDetails = formatDetails(details.trim())
val formattedType = toTitleCase(activityType.trim()) val formattedType = formatName(activityType.trim())
if (isDuplicate(formattedName, formattedDetails)) { if (isDuplicate(formattedName, formattedDetails)) {
onResult(false) onResult(false)
@@ -237,9 +224,9 @@ class HabitViewModel(application: Application) : AndroidViewModel(application) {
fun updateHabit(habit: Habit) { fun updateHabit(habit: Habit) {
viewModelScope.launch { viewModelScope.launch {
val updated = habit.copy( val updated = habit.copy(
name = toTitleCase(habit.name.trim()), name = formatName(habit.name.trim()),
details = toTitleCase(habit.details.trim()), details = formatDetails(habit.details.trim()),
activityType = toTitleCase(habit.activityType.trim()) activityType = formatName(habit.activityType.trim())
) )
repository.updateHabit(updated) repository.updateHabit(updated)
} }
+1 -1
View File
@@ -1,5 +1,5 @@
[versions] [versions]
agp = "9.0.1" agp = "9.1.0"
coreKtx = "1.10.1" coreKtx = "1.10.1"
junit = "4.13.2" junit = "4.13.2"
junitVersion = "1.1.5" junitVersion = "1.1.5"
+2 -2
View File
@@ -1,8 +1,8 @@
#Tue Feb 24 22:26:49 GMT 2026 #Tue Feb 24 22:26:49 GMT 2026
distributionBase=GRADLE_USER_HOME distributionBase=GRADLE_USER_HOME
distributionPath=wrapper/dists distributionPath=wrapper/dists
distributionSha256Sum=72f44c9f8ebcb1af43838f45ee5c4aa9c5444898b3468ab3f4af7b6076c5bc3f distributionSha256Sum=b266d5ff6b90eada6dc3b20cb090e3731302e553a27c5d3e4df1f0d76beaff06
distributionUrl=https\://services.gradle.org/distributions/gradle-9.2.1-bin.zip distributionUrl=https\://services.gradle.org/distributions/gradle-9.3.1-bin.zip
networkTimeout=10000 networkTimeout=10000
validateDistributionUrl=true validateDistributionUrl=true
zipStoreBase=GRADLE_USER_HOME zipStoreBase=GRADLE_USER_HOME