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
+63 -132

No files matched your search

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