Add calendar screen and enhance habit logging features: implement logs retrieval for date ranges, update UI components, and manage habit streaks

This commit is contained in:
bobbert committed 2026-03-04 17:45:56 +00:00
1 parent 925f426410
commit 79eb9d4366
18 files changed
+821 -864

No files matched your search

+1 -1
View File
@@ -1,6 +1,6 @@
<project version="4"> <project version="4">
<component name="ExternalStorageConfigurationManager" enabled="true" /> <component name="ExternalStorageConfigurationManager" enabled="true" />
<component name="ProjectRootManager" version="2" languageLevel="JDK_21" default="true" project-jdk-name="jbr-21" project-jdk-type="JavaSDK"> <component name="ProjectRootManager" version="2" languageLevel="JDK_21" default="true" project-jdk-name="21" project-jdk-type="JavaSDK">
<output url="file://$PROJECT_DIR$/build/classes" /> <output url="file://$PROJECT_DIR$/build/classes" />
</component> </component>
<component name="ProjectType"> <component name="ProjectType">
+4
View File
@@ -60,6 +60,10 @@ dependencies {
// ViewModel Compose // ViewModel Compose
implementation(libs.androidx.lifecycle.viewmodel.compose) implementation(libs.androidx.lifecycle.viewmodel.compose)
// Navigation3
implementation(libs.androidx.navigation3)
implementation(libs.androidx.navigation3.ui)
testImplementation(libs.junit) testImplementation(libs.junit)
androidTestImplementation(libs.androidx.junit) androidTestImplementation(libs.androidx.junit)
androidTestImplementation(libs.androidx.espresso.core) androidTestImplementation(libs.androidx.espresso.core)
@@ -1,9 +1,6 @@
package com.example.madwellbeingapp package com.example.madwellbeingapp
import android.app.Application import android.app.Application
import android.app.NotificationChannel
import android.app.NotificationManager
import android.os.Build
import com.example.madwellbeingapp.data.HabitDatabase import com.example.madwellbeingapp.data.HabitDatabase
import com.example.madwellbeingapp.data.repository.HabitRepository import com.example.madwellbeingapp.data.repository.HabitRepository
@@ -17,27 +14,7 @@ class HabitApp : Application() {
HabitRepository(database.habitDao(), database.habitLogDao(), database.activityTypeDao()) HabitRepository(database.habitDao(), database.habitLogDao(), database.activityTypeDao())
} }
override fun onCreate() {
super.onCreate()
createNotificationChannel()
}
private fun createNotificationChannel() {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
val channel = NotificationChannel(
CHANNEL_ID,
"Habit Reminders",
NotificationManager.IMPORTANCE_DEFAULT
).apply {
description = "Daily reminders for your habits"
}
val manager = getSystemService(NotificationManager::class.java)
manager.createNotificationChannel(channel)
}
}
companion object { companion object {
const val CHANNEL_ID = "habit_reminders" const val CHANNEL_ID = "habit_reminders"
} }
} }
@@ -1,22 +1,21 @@
package com.example.madwellbeingapp package com.example.madwellbeingapp
import android.Manifest
import android.content.pm.PackageManager
import android.os.Build
import android.os.Bundle import android.os.Bundle
import androidx.activity.ComponentActivity import androidx.activity.ComponentActivity
import androidx.activity.compose.setContent import androidx.activity.compose.setContent
import androidx.activity.enableEdgeToEdge import androidx.activity.enableEdgeToEdge
import androidx.activity.result.contract.ActivityResultContracts
import androidx.compose.runtime.Composable import androidx.compose.runtime.Composable
import androidx.compose.runtime.collectAsState import androidx.compose.runtime.collectAsState
import androidx.compose.runtime.getValue import androidx.compose.runtime.getValue
import androidx.compose.runtime.mutableStateListOf import androidx.compose.runtime.mutableStateListOf
import androidx.compose.runtime.remember import androidx.compose.runtime.remember
import androidx.lifecycle.viewmodel.compose.viewModel import androidx.lifecycle.viewmodel.compose.viewModel
import androidx.navigation3.runtime.entryProvider
import androidx.navigation3.ui.NavDisplay
import com.example.madwellbeingapp.ui.screens.ActiveOnlyScreen import com.example.madwellbeingapp.ui.screens.ActiveOnlyScreen
import com.example.madwellbeingapp.ui.screens.AddEditHabitScreen import com.example.madwellbeingapp.ui.screens.AddEditHabitScreen
import com.example.madwellbeingapp.ui.screens.AllActivitiesScreen import com.example.madwellbeingapp.ui.screens.AllActivitiesScreen
import com.example.madwellbeingapp.ui.screens.CalendarScreen
import com.example.madwellbeingapp.ui.screens.HabitDetailScreen import com.example.madwellbeingapp.ui.screens.HabitDetailScreen
import com.example.madwellbeingapp.ui.screens.HomeScreen import com.example.madwellbeingapp.ui.screens.HomeScreen
import com.example.madwellbeingapp.ui.screens.LandingScreen import com.example.madwellbeingapp.ui.screens.LandingScreen
@@ -24,126 +23,67 @@ import com.example.madwellbeingapp.ui.theme.MadWellbeingAppTheme
import com.example.madwellbeingapp.ui.viewmodel.HabitViewModel import com.example.madwellbeingapp.ui.viewmodel.HabitViewModel
class MainActivity : ComponentActivity() { class MainActivity : ComponentActivity() {
private val notificationPermissionLauncher =
registerForActivityResult(ActivityResultContracts.RequestPermission()) { /* granted or not */ }
override fun onCreate(savedInstanceState: Bundle?) { override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState) super.onCreate(savedInstanceState)
enableEdgeToEdge() enableEdgeToEdge()
setContent { MadWellbeingAppTheme { HabitNavGraph() } }
// Request notification permission on Android 13+
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.TIRAMISU) {
if (checkSelfPermission(Manifest.permission.POST_NOTIFICATIONS)
!= PackageManager.PERMISSION_GRANTED
) {
notificationPermissionLauncher.launch(Manifest.permission.POST_NOTIFICATIONS)
}
}
setContent {
MadWellbeingAppTheme {
HabitNavGraph()
}
}
} }
} }
/** // ── Screen destinations ─────────────────────────────────────
* Simple sealed class representing each screen destination.
* We avoid using Navigation Compose library and use manual state-based navigation.
*/
sealed class Screen { sealed class Screen {
/** Landing page with 3 navigation buttons — first page the user sees. */
data object Landing : Screen() data object Landing : Screen()
/** All activities — past completed + currently active. */
data object AllActivities : Screen() data object AllActivities : Screen()
/** Manage activities — add new habits, swipe to complete. */
data object Home : Screen() data object Home : Screen()
/** Active only — habits still to-do today. */
data object ActiveOnly : Screen() data object ActiveOnly : Screen()
data object Calendar : Screen()
data object AddHabit : Screen() data object AddHabit : Screen()
data class EditHabit(val habitId: Int) : Screen() data class EditHabit(val habitId: Int) : Screen()
data class HabitDetail(val habitId: Int) : Screen() data class HabitDetail(val habitId: Int) : Screen()
} }
@Composable @Composable
fun HabitNavGraph(viewModel: HabitViewModel = viewModel()) { fun HabitNavGraph(vm: HabitViewModel = viewModel()) {
// Manual back-stack — starts on the Landing screen val backStack = remember { mutableStateListOf<Any>(Screen.Landing) }
val backStack = remember { mutableStateListOf<Screen>(Screen.Landing) }
val currentScreen = backStack.last()
fun navigateTo(screen: Screen) { fun nav(screen: Screen) = backStack.add(screen)
backStack.add(screen) fun back() { if (backStack.size > 1) backStack.removeLast() }
}
fun navigateBack() { NavDisplay(
if (backStack.size > 1) { backStack = backStack,
backStack.removeAt(backStack.lastIndex) entryProvider = entryProvider {
} entry<Screen.Landing> {
} LandingScreen(
onAllActivities = { nav(Screen.AllActivities) },
when (currentScreen) { onManageActivities = { nav(Screen.Home) },
is Screen.Landing -> { onActiveOnly = { nav(Screen.ActiveOnly) },
LandingScreen( onCalendar = { nav(Screen.Calendar) }
onAllActivities = { navigateTo(Screen.AllActivities) },
onManageActivities = { navigateTo(Screen.Home) },
onActiveOnly = { navigateTo(Screen.ActiveOnly) }
)
}
is Screen.AllActivities -> {
AllActivitiesScreen(
viewModel = viewModel,
onNavigateBack = { navigateBack() },
onHabitClick = { id -> navigateTo(Screen.HabitDetail(id)) }
)
}
is Screen.Home -> {
HomeScreen(
viewModel = viewModel,
onAddHabit = { navigateTo(Screen.AddHabit) },
onHabitClick = { id -> navigateTo(Screen.HabitDetail(id)) },
onNavigateBack = { navigateBack() }
)
}
is Screen.ActiveOnly -> {
ActiveOnlyScreen(
viewModel = viewModel,
onNavigateBack = { navigateBack() },
onHabitClick = { id -> navigateTo(Screen.HabitDetail(id)) }
)
}
is Screen.AddHabit -> {
AddEditHabitScreen(
viewModel = viewModel,
existingHabit = null,
onNavigateBack = { navigateBack() }
)
}
is Screen.EditHabit -> {
val allHabits by viewModel.allHabits.collectAsState()
val habit = allHabits.find { it.id == currentScreen.habitId }
if (habit != null) {
AddEditHabitScreen(
viewModel = viewModel,
existingHabit = habit,
onNavigateBack = { navigateBack() }
) )
} }
entry<Screen.AllActivities> {
AllActivitiesScreen(vm, onNavigateBack = ::back, onHabitClick = { nav(Screen.HabitDetail(it)) })
}
entry<Screen.Home> {
HomeScreen(vm, onAddHabit = { nav(Screen.AddHabit) }, onHabitClick = { nav(Screen.HabitDetail(it)) }, onNavigateBack = ::back)
}
entry<Screen.ActiveOnly> {
ActiveOnlyScreen(vm, onNavigateBack = ::back, onHabitClick = { nav(Screen.HabitDetail(it)) })
}
entry<Screen.Calendar> {
CalendarScreen(vm, onNavigateBack = ::back, onHabitClick = { nav(Screen.HabitDetail(it)) })
}
entry<Screen.AddHabit> {
AddEditHabitScreen(vm, existingHabit = null, onNavigateBack = ::back)
}
entry<Screen.EditHabit> { key ->
val allHabits by vm.allHabits.collectAsState()
allHabits.find { it.id == key.habitId }?.let { habit ->
AddEditHabitScreen(vm, existingHabit = habit, onNavigateBack = ::back)
}
}
entry<Screen.HabitDetail> { key ->
HabitDetailScreen(key.habitId, vm, onNavigateBack = ::back, onEditHabit = { nav(Screen.EditHabit(it)) })
}
} }
)
is Screen.HabitDetail -> {
HabitDetailScreen(
habitId = currentScreen.habitId,
viewModel = viewModel,
onNavigateBack = { navigateBack() },
onEditHabit = { id -> navigateTo(Screen.EditHabit(id)) }
)
}
}
} }
@@ -1,7 +1,6 @@
package com.example.madwellbeingapp.data.dao package com.example.madwellbeingapp.data.dao
import androidx.room.Dao import androidx.room.Dao
import androidx.room.Delete
import androidx.room.Query import androidx.room.Query
import androidx.room.Upsert import androidx.room.Upsert
import com.example.madwellbeingapp.data.model.ActivityType import com.example.madwellbeingapp.data.model.ActivityType
@@ -13,8 +12,6 @@ interface ActivityTypeDao {
@Upsert @Upsert
suspend fun upsert(activityType: ActivityType): Long suspend fun upsert(activityType: ActivityType): Long
@Delete
suspend fun delete(activityType: ActivityType): Int
@Query("SELECT * FROM activity_types ORDER BY name ASC") @Query("SELECT * FROM activity_types ORDER BY name ASC")
fun getAll(): Flow<List<ActivityType>> fun getAll(): Flow<List<ActivityType>>
@@ -1,7 +1,6 @@
package com.example.madwellbeingapp.data.dao package com.example.madwellbeingapp.data.dao
import androidx.room.Dao import androidx.room.Dao
import androidx.room.Delete
import androidx.room.Query import androidx.room.Query
import androidx.room.Upsert import androidx.room.Upsert
import com.example.madwellbeingapp.data.model.Habit import com.example.madwellbeingapp.data.model.Habit
@@ -13,8 +12,6 @@ interface HabitDao {
@Upsert @Upsert
suspend fun upsert(habit: Habit): Long suspend fun upsert(habit: Habit): Long
@Delete
suspend fun delete(habit: Habit): Int
@Query("SELECT * FROM habits ORDER BY name ASC") @Query("SELECT * FROM habits ORDER BY name ASC")
fun getAllHabits(): Flow<List<Habit>> fun getAllHabits(): Flow<List<Habit>>
@@ -29,4 +29,7 @@ interface HabitLogDao {
@Query("SELECT * FROM habit_logs WHERE date = :date") @Query("SELECT * FROM habit_logs WHERE date = :date")
fun getLogsForDate(date: Long): Flow<List<HabitLog>> fun getLogsForDate(date: Long): Flow<List<HabitLog>>
@Query("SELECT * FROM habit_logs WHERE date >= :startDate AND date <= :endDate AND completed = 1")
fun getLogsBetween(startDate: Long, endDate: Long): Flow<List<HabitLog>>
} }
@@ -28,7 +28,6 @@ class HabitRepository(
suspend fun updateHabit(habit: Habit) = habitDao.upsert(habit) suspend fun updateHabit(habit: Habit) = habitDao.upsert(habit)
suspend fun deleteHabit(habit: Habit) = habitDao.delete(habit)
/** Returns an existing habit with the same name+details (case-insensitive), or null. */ /** Returns an existing habit with the same name+details (case-insensitive), or null. */
suspend fun findDuplicate(name: String, details: String): Habit? = suspend fun findDuplicate(name: String, details: String): Habit? =
@@ -40,8 +39,6 @@ class HabitRepository(
suspend fun addActivityType(activityType: ActivityType): Long = suspend fun addActivityType(activityType: ActivityType): Long =
activityTypeDao.upsert(activityType) activityTypeDao.upsert(activityType)
suspend fun deleteActivityType(activityType: ActivityType) =
activityTypeDao.delete(activityType)
suspend fun findActivityTypeByName(name: String): ActivityType? = suspend fun findActivityTypeByName(name: String): ActivityType? =
activityTypeDao.findByName(name) activityTypeDao.findByName(name)
@@ -70,4 +67,7 @@ class HabitRepository(
suspend fun getCompletedLogsDesc(habitId: Int): List<HabitLog> = suspend fun getCompletedLogsDesc(habitId: Int): List<HabitLog> =
habitLogDao.getCompletedLogsDesc(habitId) habitLogDao.getCompletedLogsDesc(habitId)
fun getLogsBetween(startDate: Long, endDate: Long): Flow<List<HabitLog>> =
habitLogDao.getLogsBetween(startDate, endDate)
} }
@@ -1,12 +1,7 @@
package com.example.madwellbeingapp.ui.screens package com.example.madwellbeingapp.ui.screens
import android.util.Log
import android.widget.Toast import android.widget.Toast
import androidx.compose.foundation.background
import androidx.compose.foundation.clickable
import androidx.compose.foundation.gestures.detectDragGestures
import androidx.compose.foundation.layout.Arrangement import androidx.compose.foundation.layout.Arrangement
import androidx.compose.foundation.layout.Box
import androidx.compose.foundation.layout.Column import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.Row import androidx.compose.foundation.layout.Row
import androidx.compose.foundation.layout.Spacer import androidx.compose.foundation.layout.Spacer
@@ -18,13 +13,10 @@ import androidx.compose.foundation.layout.size
import androidx.compose.foundation.lazy.LazyColumn import androidx.compose.foundation.lazy.LazyColumn
import androidx.compose.foundation.lazy.items import androidx.compose.foundation.lazy.items
import androidx.compose.foundation.rememberScrollState import androidx.compose.foundation.rememberScrollState
import androidx.compose.foundation.shape.CircleShape
import androidx.compose.foundation.shape.RoundedCornerShape
import androidx.compose.foundation.text.KeyboardOptions import androidx.compose.foundation.text.KeyboardOptions
import androidx.compose.foundation.verticalScroll import androidx.compose.foundation.verticalScroll
import androidx.compose.material3.AlertDialog import androidx.compose.material3.AlertDialog
import androidx.compose.material3.Button import androidx.compose.material3.Button
import androidx.compose.material3.ButtonDefaults
import androidx.compose.material3.Card import androidx.compose.material3.Card
import androidx.compose.material3.CardDefaults import androidx.compose.material3.CardDefaults
import androidx.compose.material3.MaterialTheme import androidx.compose.material3.MaterialTheme
@@ -35,42 +27,20 @@ import androidx.compose.material3.TextButton
import androidx.compose.runtime.Composable import androidx.compose.runtime.Composable
import androidx.compose.runtime.collectAsState import androidx.compose.runtime.collectAsState
import androidx.compose.runtime.getValue import androidx.compose.runtime.getValue
import androidx.compose.runtime.mutableFloatStateOf
import androidx.compose.runtime.mutableIntStateOf
import androidx.compose.runtime.mutableStateOf import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.remember import androidx.compose.runtime.remember
import androidx.compose.runtime.saveable.rememberSaveable
import androidx.compose.runtime.setValue 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.draw.clip
import androidx.compose.ui.geometry.Offset
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.graphics.drawscope.Stroke
import androidx.compose.ui.input.pointer.pointerInput
import androidx.compose.ui.platform.LocalContext import androidx.compose.ui.platform.LocalContext
import androidx.compose.ui.platform.LocalDensity
import androidx.compose.ui.text.font.FontWeight import androidx.compose.ui.text.font.FontWeight
import androidx.compose.ui.text.input.KeyboardType import androidx.compose.ui.text.input.KeyboardType
import androidx.compose.ui.text.style.TextAlign
import androidx.compose.ui.unit.dp import androidx.compose.ui.unit.dp
import com.example.madwellbeingapp.data.model.Habit import com.example.madwellbeingapp.data.model.Habit
import com.example.madwellbeingapp.ui.viewmodel.HabitViewModel import com.example.madwellbeingapp.ui.viewmodel.HabitViewModel
import kotlin.math.PI
import kotlin.math.atan2
import kotlin.math.cos
import kotlin.math.roundToInt
import kotlin.math.sin
/** /**
* Screen for creating or editing a habit. * Screen for creating or editing a habit.
*
* - Activity type is chosen from a dropdown populated by user-created types stored in Room.
* - A "+" button lets the user add new activity types on the fly.
* - Details field lets the user specialise the activity (e.g. "Legs").
* - Reminder time uses a clock-style dial picker instead of typing.
* - All text is title-cased. Duplicates are blocked.
* - rememberSaveable preserves state across rotation.
*/ */
@Composable @Composable
fun AddEditHabitScreen( fun AddEditHabitScreen(
@@ -80,68 +50,57 @@ fun AddEditHabitScreen(
) { ) {
val context = LocalContext.current val context = LocalContext.current
val isEditing = existingHabit != null val isEditing = existingHabit != null
// Activity types from the database
val activityTypes by viewModel.allActivityTypes.collectAsState() val activityTypes by viewModel.allActivityTypes.collectAsState()
// ── Form state (survives rotation) ────────────────────── // Form state
var selectedActivityName by rememberSaveable { mutableStateOf(existingHabit?.name ?: "") } var selectedActivityName by remember { mutableStateOf(existingHabit?.name ?: "") }
var details by rememberSaveable { mutableStateOf(existingHabit?.details ?: "") } var details by remember { mutableStateOf(existingHabit?.details ?: "") }
var targetFrequency by rememberSaveable { var targetFrequency by remember { mutableStateOf((existingHabit?.targetFrequency ?: 7).toString()) }
mutableStateOf((existingHabit?.targetFrequency ?: 7).toString()) var reminderEnabled by remember { mutableStateOf(existingHabit?.reminderEnabled ?: true) }
} var reminderHour by remember { mutableStateOf(existingHabit?.reminderHour ?: 9) }
var reminderEnabled by rememberSaveable { mutableStateOf(existingHabit?.reminderEnabled ?: true) } var reminderMinute by remember { mutableStateOf(existingHabit?.reminderMinute ?: 0) }
var reminderHour by rememberSaveable { mutableIntStateOf(existingHabit?.reminderHour ?: 9) }
var reminderMinute by rememberSaveable { mutableIntStateOf(existingHabit?.reminderMinute ?: 0) }
var nameError by rememberSaveable { mutableStateOf(false) } var nameError by remember { mutableStateOf(false) }
var showActivityDialog by rememberSaveable { mutableStateOf(false) } var showActivityDialog by remember { mutableStateOf(false) }
var showAddTypeDialog by rememberSaveable { mutableStateOf(false) } var showAddTypeDialog by remember { mutableStateOf(false) }
var showTimePicker by rememberSaveable { mutableStateOf(false) } var showTimePicker by remember { mutableStateOf(false) }
// ── Activity type picker dialog ───────────────────────── // Activity type picker dialog
if (showActivityDialog) { if (showActivityDialog) {
AlertDialog( AlertDialog(
onDismissRequest = { showActivityDialog = false }, onDismissRequest = { showActivityDialog = false },
title = { Text("Select Activity Type") }, title = { Text("Select Activity Type") },
text = { text = {
if (activityTypes.isEmpty()) { if (activityTypes.isEmpty()) {
Text( Text("No activity types yet.\nTap the + button to create one.",
"No activity types yet.\nTap the + button to create one.",
style = MaterialTheme.typography.bodyMedium, style = MaterialTheme.typography.bodyMedium,
color = MaterialTheme.colorScheme.onSurfaceVariant color = MaterialTheme.colorScheme.onSurfaceVariant)
)
} else { } else {
LazyColumn { LazyColumn {
items(activityTypes) { type -> items(activityTypes) { type ->
Text( TextButton(onClick = {
text = type.name, selectedActivityName = type.name
modifier = Modifier nameError = false
.fillMaxWidth() showActivityDialog = false
.clickable { }, modifier = Modifier.fillMaxWidth()) {
selectedActivityName = type.name Text(
nameError = false text = type.name,
showActivityDialog = false style = MaterialTheme.typography.bodyLarge,
} fontWeight = if (type.name == selectedActivityName) FontWeight.Bold
.padding(vertical = 12.dp, horizontal = 8.dp), else FontWeight.Normal,
style = MaterialTheme.typography.bodyLarge, color = if (type.name == selectedActivityName) MaterialTheme.colorScheme.primary
fontWeight = if (type.name == selectedActivityName) else MaterialTheme.colorScheme.onSurface
FontWeight.Bold else FontWeight.Normal, )
color = if (type.name == selectedActivityName) }
MaterialTheme.colorScheme.primary
else MaterialTheme.colorScheme.onSurface
)
} }
} }
} }
}, },
confirmButton = { confirmButton = { TextButton(onClick = { showActivityDialog = false }) { Text("Close") } }
TextButton(onClick = { showActivityDialog = false }) { Text("Close") }
}
) )
} }
// ── Add new activity type dialog ──────────────────────── // Add new activity type dialog
if (showAddTypeDialog) { if (showAddTypeDialog) {
var newTypeName by remember { mutableStateOf("") } var newTypeName by remember { mutableStateOf("") }
var typeError by remember { mutableStateOf(false) } var typeError by remember { mutableStateOf(false) }
@@ -157,15 +116,12 @@ fun AddEditHabitScreen(
placeholder = { Text("e.g. Gym, Running, Yoga") }, placeholder = { Text("e.g. Gym, Running, Yoga") },
singleLine = true, singleLine = true,
isError = typeError, isError = typeError,
modifier = Modifier.fillMaxWidth(), modifier = Modifier.fillMaxWidth()
shape = RoundedCornerShape(12.dp)
) )
if (typeError) { if (typeError) {
Text( Text("Name is empty or already exists",
"Name is empty or already exists",
style = MaterialTheme.typography.bodySmall, style = MaterialTheme.typography.bodySmall,
color = MaterialTheme.colorScheme.error color = MaterialTheme.colorScheme.error)
)
} }
} }
}, },
@@ -186,135 +142,85 @@ fun AddEditHabitScreen(
} }
}) { Text("Add") } }) { Text("Add") }
}, },
dismissButton = { dismissButton = { TextButton(onClick = { showAddTypeDialog = false }) { Text("Cancel") } }
TextButton(onClick = { showAddTypeDialog = false }) { Text("Cancel") }
}
) )
} }
// ── Time picker dialog (clock dial) ───────────────────── // Time picker dialog (simple number-based instead of clock dial)
if (showTimePicker) { if (showTimePicker) {
var tempHour by remember { mutableIntStateOf(reminderHour) } var tempHour by remember { mutableStateOf(reminderHour.toString()) }
var tempMinute by remember { mutableIntStateOf(reminderMinute) } var tempMinute by remember { mutableStateOf(reminderMinute.toString()) }
var pickingHour by remember { mutableStateOf(true) }
AlertDialog( AlertDialog(
onDismissRequest = { showTimePicker = false }, onDismissRequest = { showTimePicker = false },
title = { title = { Text("Set Reminder Time") },
Text(
if (pickingHour) "Select Hour" else "Select Minute",
textAlign = TextAlign.Center,
modifier = Modifier.fillMaxWidth()
)
},
text = { text = {
Column( Row(
horizontalAlignment = Alignment.CenterHorizontally, horizontalArrangement = Arrangement.spacedBy(8.dp),
verticalAlignment = Alignment.CenterVertically,
modifier = Modifier.fillMaxWidth() modifier = Modifier.fillMaxWidth()
) { ) {
// Display current selection OutlinedTextField(
Text( value = tempHour,
text = "${tempHour.toString().padStart(2, '0')}:${tempMinute.toString().padStart(2, '0')}", onValueChange = { tempHour = it.filter { c -> c.isDigit() }.take(2) },
style = MaterialTheme.typography.headlineLarge, label = { Text("Hour") },
fontWeight = FontWeight.Bold, keyboardOptions = KeyboardOptions(keyboardType = KeyboardType.Number),
color = MaterialTheme.colorScheme.primary, singleLine = true,
textAlign = TextAlign.Center, modifier = Modifier.weight(1f)
modifier = Modifier.fillMaxWidth()
) )
Spacer(modifier = Modifier.height(4.dp)) Text(":", style = MaterialTheme.typography.headlineMedium,
// Toggle hour/minute fontWeight = FontWeight.Bold)
Row( OutlinedTextField(
horizontalArrangement = Arrangement.Center, value = tempMinute,
modifier = Modifier.fillMaxWidth() onValueChange = { tempMinute = it.filter { c -> c.isDigit() }.take(2) },
) { label = { Text("Min") },
TextButton(onClick = { pickingHour = true }) { keyboardOptions = KeyboardOptions(keyboardType = KeyboardType.Number),
Text( singleLine = true,
"Hour", modifier = Modifier.weight(1f)
fontWeight = if (pickingHour) FontWeight.Bold else FontWeight.Normal,
color = if (pickingHour) MaterialTheme.colorScheme.primary
else MaterialTheme.colorScheme.onSurfaceVariant
)
}
TextButton(onClick = { pickingHour = false }) {
Text(
"Minute",
fontWeight = if (!pickingHour) FontWeight.Bold else FontWeight.Normal,
color = if (!pickingHour) MaterialTheme.colorScheme.primary
else MaterialTheme.colorScheme.onSurfaceVariant
)
}
}
Spacer(modifier = Modifier.height(8.dp))
// Clock dial
ClockDial(
value = if (pickingHour) tempHour else tempMinute,
maxValue = if (pickingHour) 24 else 60,
step = if (pickingHour) 1 else 5,
onValueChange = {
if (pickingHour) tempHour = it else tempMinute = it
},
labels = if (pickingHour) (0..23 step 3).toList()
else (0..55 step 5).toList()
) )
} }
}, },
confirmButton = { confirmButton = {
TextButton(onClick = { TextButton(onClick = {
reminderHour = tempHour reminderHour = (tempHour.toIntOrNull() ?: 9).coerceIn(0, 23)
reminderMinute = tempMinute reminderMinute = (tempMinute.toIntOrNull() ?: 0).coerceIn(0, 59)
showTimePicker = false showTimePicker = false
}) { Text("OK") } }) { Text("OK") }
}, },
dismissButton = { dismissButton = { TextButton(onClick = { showTimePicker = false }) { Text("Cancel") } }
TextButton(onClick = { showTimePicker = false }) { Text("Cancel") }
}
) )
} }
// ── Screen layout ─────────────────────────────────────── // Screen layout
Scaffold { padding -> Scaffold { padding ->
Column( Column(modifier = Modifier.fillMaxSize().padding(padding)) {
modifier = Modifier
.fillMaxSize()
.padding(padding)
) {
ScreenHeader( ScreenHeader(
title = if (isEditing) "Edit Habit" else "New Habit", title = if (isEditing) "Edit Habit" else "New Habit",
onBack = onNavigateBack onBack = onNavigateBack
) )
Column( Column(
modifier = Modifier modifier = Modifier.fillMaxSize().padding(20.dp)
.fillMaxSize()
.padding(20.dp)
.verticalScroll(rememberScrollState()), .verticalScroll(rememberScrollState()),
verticalArrangement = Arrangement.spacedBy(16.dp) verticalArrangement = Arrangement.spacedBy(16.dp)
) { ) {
// ── Activity type dropdown + add button ───────── // Activity type dropdown + add button
Text( Text("Activity Type", style = MaterialTheme.typography.bodyMedium,
text = "Activity Type", color = MaterialTheme.colorScheme.onSurfaceVariant)
style = MaterialTheme.typography.bodyMedium,
color = MaterialTheme.colorScheme.onSurfaceVariant
)
Row( Row(
modifier = Modifier.fillMaxWidth(), modifier = Modifier.fillMaxWidth(),
horizontalArrangement = Arrangement.spacedBy(8.dp), horizontalArrangement = Arrangement.spacedBy(8.dp),
verticalAlignment = Alignment.CenterVertically verticalAlignment = Alignment.CenterVertically
) { ) {
Card( Card(
modifier = Modifier onClick = { showActivityDialog = true },
.weight(1f) modifier = Modifier.weight(1f),
.clickable { showActivityDialog = true },
shape = RoundedCornerShape(12.dp),
elevation = CardDefaults.cardElevation(1.dp), elevation = CardDefaults.cardElevation(1.dp),
colors = if (nameError) CardDefaults.cardColors( colors = if (nameError) CardDefaults.cardColors(
containerColor = MaterialTheme.colorScheme.errorContainer containerColor = MaterialTheme.colorScheme.errorContainer)
) else CardDefaults.cardColors() else CardDefaults.cardColors()
) { ) {
Row( Row(
modifier = Modifier modifier = Modifier.fillMaxWidth().padding(16.dp),
.fillMaxWidth()
.padding(16.dp),
horizontalArrangement = Arrangement.SpaceBetween, horizontalArrangement = Arrangement.SpaceBetween,
verticalAlignment = Alignment.CenterVertically verticalAlignment = Alignment.CenterVertically
) { ) {
@@ -326,41 +232,34 @@ fun AddEditHabitScreen(
MaterialTheme.colorScheme.onSurfaceVariant.copy(alpha = 0.5f) MaterialTheme.colorScheme.onSurfaceVariant.copy(alpha = 0.5f)
else MaterialTheme.colorScheme.onSurface else MaterialTheme.colorScheme.onSurface
) )
Text( Text("▼", style = MaterialTheme.typography.bodySmall,
text = "▼", color = MaterialTheme.colorScheme.onSurfaceVariant)
style = MaterialTheme.typography.bodySmall,
color = MaterialTheme.colorScheme.onSurfaceVariant
)
} }
} }
// "+" button to add a new activity type
Button( Button(
onClick = { showAddTypeDialog = true }, onClick = { showAddTypeDialog = true },
modifier = Modifier.size(52.dp), modifier = Modifier.size(52.dp),
shape = RoundedCornerShape(12.dp),
contentPadding = androidx.compose.foundation.layout.PaddingValues(0.dp) contentPadding = androidx.compose.foundation.layout.PaddingValues(0.dp)
) { ) {
Text("+", style = MaterialTheme.typography.titleLarge, fontWeight = FontWeight.Bold) Text("+", style = MaterialTheme.typography.titleLarge,
fontWeight = FontWeight.Bold)
} }
} }
if (nameError) { if (nameError) {
Text( Text("Please select an activity type",
text = "Please select an activity type",
style = MaterialTheme.typography.bodySmall, style = MaterialTheme.typography.bodySmall,
color = MaterialTheme.colorScheme.error, color = MaterialTheme.colorScheme.error,
modifier = Modifier.padding(start = 4.dp) modifier = Modifier.padding(start = 4.dp))
)
} }
// ── Details text field ────────────────────────── // Details
OutlinedTextField( OutlinedTextField(
value = details, value = details,
onValueChange = { details = it }, onValueChange = { details = it },
label = { Text("Details (optional)") }, label = { Text("Details (optional)") },
placeholder = { Text("e.g. Legs, Upper Body, 5K") }, placeholder = { Text("e.g. Legs, Upper Body, 5K") },
singleLine = true, singleLine = true,
modifier = Modifier.fillMaxWidth(), modifier = Modifier.fillMaxWidth()
shape = RoundedCornerShape(12.dp)
) )
// Live preview // Live preview
@@ -370,65 +269,48 @@ fun AddEditHabitScreen(
else else
HabitViewModel.toTitleCase(selectedActivityName.trim()) + HabitViewModel.toTitleCase(selectedActivityName.trim()) +
"(" + HabitViewModel.toTitleCase(details.trim()) + ")" "(" + HabitViewModel.toTitleCase(details.trim()) + ")"
Text( 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,
modifier = Modifier.padding(start = 4.dp) modifier = Modifier.padding(start = 4.dp))
)
} }
// ── Target frequency ──────────────────────────── // Target frequency
OutlinedTextField( OutlinedTextField(
value = targetFrequency, value = targetFrequency,
onValueChange = { targetFrequency = it.filter { c -> c.isDigit() } }, onValueChange = { targetFrequency = it.filter { c -> c.isDigit() } },
label = { Text("Target (times per week)") }, label = { Text("Target (times per week)") },
keyboardOptions = KeyboardOptions(keyboardType = KeyboardType.Number), keyboardOptions = KeyboardOptions(keyboardType = KeyboardType.Number),
singleLine = true, singleLine = true,
modifier = Modifier.fillMaxWidth(), modifier = Modifier.fillMaxWidth()
shape = RoundedCornerShape(12.dp)
) )
// ── Reminder toggle ───────────────────────────── // Reminder toggle
Row( Row(
modifier = Modifier.fillMaxWidth(), modifier = Modifier.fillMaxWidth(),
verticalAlignment = Alignment.CenterVertically, verticalAlignment = Alignment.CenterVertically,
horizontalArrangement = Arrangement.SpaceBetween horizontalArrangement = Arrangement.SpaceBetween
) { ) {
Text("Daily Reminder", style = MaterialTheme.typography.bodyLarge) Text("Daily Reminder", style = MaterialTheme.typography.bodyLarge)
Button( Button(onClick = { reminderEnabled = !reminderEnabled }) {
onClick = { reminderEnabled = !reminderEnabled },
colors = if (reminderEnabled) ButtonDefaults.buttonColors(
containerColor = MaterialTheme.colorScheme.primary
) else ButtonDefaults.buttonColors(
containerColor = MaterialTheme.colorScheme.surfaceVariant,
contentColor = MaterialTheme.colorScheme.onSurfaceVariant
),
shape = RoundedCornerShape(8.dp)
) {
Text(if (reminderEnabled) "ON" else "OFF") Text(if (reminderEnabled) "ON" else "OFF")
} }
} }
if (reminderEnabled) { if (reminderEnabled) {
// ── Reminder time — clock dial button ───────
Card( Card(
modifier = Modifier onClick = { showTimePicker = true },
.fillMaxWidth() modifier = Modifier.fillMaxWidth(),
.clickable { showTimePicker = true },
shape = RoundedCornerShape(12.dp),
elevation = CardDefaults.cardElevation(1.dp) elevation = CardDefaults.cardElevation(1.dp)
) { ) {
Row( Row(
modifier = Modifier modifier = Modifier.fillMaxWidth().padding(16.dp),
.fillMaxWidth()
.padding(16.dp),
horizontalArrangement = Arrangement.SpaceBetween, horizontalArrangement = Arrangement.SpaceBetween,
verticalAlignment = Alignment.CenterVertically verticalAlignment = Alignment.CenterVertically
) { ) {
Text("Reminder Time", style = MaterialTheme.typography.bodyLarge) Text("Reminder Time", style = MaterialTheme.typography.bodyLarge)
Text( Text(
text = "${reminderHour.toString().padStart(2, '0')}:${reminderMinute.toString().padStart(2, '0')}", "${reminderHour.toString().padStart(2, '0')}:${reminderMinute.toString().padStart(2, '0')}",
style = MaterialTheme.typography.titleMedium, style = MaterialTheme.typography.titleMedium,
fontWeight = FontWeight.Bold, fontWeight = FontWeight.Bold,
color = MaterialTheme.colorScheme.primary color = MaterialTheme.colorScheme.primary
@@ -439,18 +321,15 @@ fun AddEditHabitScreen(
Spacer(modifier = Modifier.height(8.dp)) Spacer(modifier = Modifier.height(8.dp))
// ── Save button ───────────────────────────────── // Save button
Button( Button(
onClick = { onClick = {
if (selectedActivityName.isBlank()) { if (selectedActivityName.isBlank()) { nameError = true; return@Button }
nameError = true
return@Button
}
val freq = targetFrequency.toIntOrNull() ?: 7 val freq = targetFrequency.toIntOrNull() ?: 7
if (isEditing && existingHabit != null) { if (isEditing) {
viewModel.updateHabit( viewModel.updateHabit(
existingHabit.copy( existingHabit!!.copy(
name = selectedActivityName.trim(), name = selectedActivityName.trim(),
details = details.trim(), details = details.trim(),
activityType = selectedActivityName.trim(), activityType = selectedActivityName.trim(),
@@ -460,7 +339,6 @@ fun AddEditHabitScreen(
reminderMinute = reminderMinute reminderMinute = reminderMinute
) )
) )
Log.i("AddEditHabitScreen", "User updated habit: name='${selectedActivityName.trim()}'")
onNavigateBack() onNavigateBack()
} else { } else {
viewModel.addHabit( viewModel.addHabit(
@@ -472,20 +350,13 @@ fun AddEditHabitScreen(
reminderHour = reminderHour, reminderHour = reminderHour,
reminderMinute = reminderMinute, reminderMinute = reminderMinute,
onResult = { success -> onResult = { success ->
if (success) { if (success) onNavigateBack()
Log.i("AddEditHabitScreen", "User created habit: name='${selectedActivityName.trim()}'") else Toast.makeText(context, "This activity already exists!", Toast.LENGTH_SHORT).show()
onNavigateBack()
} else {
Toast.makeText(context, "This activity already exists!", Toast.LENGTH_SHORT).show()
}
} }
) )
} }
}, },
modifier = Modifier modifier = Modifier.fillMaxWidth().height(52.dp)
.fillMaxWidth()
.height(52.dp),
shape = RoundedCornerShape(14.dp)
) { ) {
Text( Text(
if (isEditing) "Update Habit" else "Create Habit", if (isEditing) "Update Habit" else "Create Habit",
@@ -497,139 +368,3 @@ fun AddEditHabitScreen(
} }
} }
} }
// ─────────────────────────────────────────────────────────────
// Clock-style dial picker — pure Compose Canvas, no 3rd-party
// ─────────────────────────────────────────────────────────────
/**
* A circular dial the user drags to pick a value.
* [value] is the current selection, [maxValue] is the range (24 for hours, 60 for minutes).
* [step] snaps to multiples (1 for hours, 5 for minutes).
* [labels] are the numbers drawn around the ring.
*/
@Composable
private fun ClockDial(
value: Int,
maxValue: Int,
step: Int,
onValueChange: (Int) -> Unit,
labels: List<Int>
) {
val sizeDp = 220.dp
val sizePx = with(LocalDensity.current) { sizeDp.toPx() }
val center = sizePx / 2f
val radius = center * 0.82f
val labelRadius = center * 0.68f
val knobRadius = 18f
val primaryColor = MaterialTheme.colorScheme.primary
val surfaceVariantColor = MaterialTheme.colorScheme.surfaceVariant
val onSurfaceColor = MaterialTheme.colorScheme.onSurface
val onPrimaryColor = MaterialTheme.colorScheme.onPrimary
// Convert current value to angle (0 at top = -PI/2)
fun valueToAngle(v: Int): Float {
return (2f * PI.toFloat() * v / maxValue) - (PI.toFloat() / 2f)
}
var currentAngle by remember(value) { mutableFloatStateOf(valueToAngle(value)) }
Box(
modifier = Modifier
.size(sizeDp)
.pointerInput(maxValue, step) {
detectDragGestures { change, _ ->
change.consume()
val pos = change.position
val angle = atan2(pos.y - center, pos.x - center)
currentAngle = angle
// Convert angle back to value
var normalized = angle + (PI.toFloat() / 2f)
if (normalized < 0) normalized += 2f * PI.toFloat()
var raw = (normalized / (2f * PI.toFloat()) * maxValue).roundToInt()
// Snap to step
raw = ((raw.toFloat() / step).roundToInt() * step).coerceIn(0, maxValue - 1)
onValueChange(raw)
}
}
) {
androidx.compose.foundation.Canvas(modifier = Modifier.fillMaxSize()) {
// Outer ring
drawCircle(
color = surfaceVariantColor,
radius = radius,
center = Offset(center, center),
style = Stroke(width = 4f)
)
// Draw labels around the circle
for (lbl in labels) {
val a = valueToAngle(lbl)
val lx = center + labelRadius * cos(a)
val ly = center + labelRadius * sin(a)
drawCircle(
color = if (lbl == value) primaryColor else Color.Transparent,
radius = 16f,
center = Offset(lx, ly)
)
}
// Line from center to knob
val knobAngle = valueToAngle(value)
val kx = center + radius * cos(knobAngle)
val ky = center + radius * sin(knobAngle)
drawLine(
color = primaryColor,
start = Offset(center, center),
end = Offset(kx, ky),
strokeWidth = 3f
)
// Knob
drawCircle(color = primaryColor, radius = knobRadius, center = Offset(kx, ky))
// Center dot
drawCircle(color = primaryColor, radius = 6f, center = Offset(center, center))
}
// Draw text labels on top of canvas using Compose Text
labels.forEach { lbl ->
val a = valueToAngle(lbl)
val lx = center + labelRadius * cos(a)
val ly = center + labelRadius * sin(a)
val offsetXDp = with(LocalDensity.current) { lx.toDp() }
val offsetYDp = with(LocalDensity.current) { ly.toDp() }
Text(
text = lbl.toString().padStart(2, '0'),
modifier = Modifier
.size(32.dp)
.padding(start = (offsetXDp - 16.dp).coerceAtLeast(0.dp))
.padding(top = (offsetYDp - 8.dp).coerceAtLeast(0.dp)),
style = MaterialTheme.typography.labelSmall,
fontWeight = if (lbl == value) FontWeight.Bold else FontWeight.Normal,
color = if (lbl == value) onPrimaryColor else onSurfaceColor,
textAlign = TextAlign.Center
)
}
// Big selected value in the center
Box(modifier = Modifier.fillMaxSize(), contentAlignment = Alignment.Center) {
Box(
modifier = Modifier
.size(52.dp)
.clip(CircleShape)
.background(MaterialTheme.colorScheme.primaryContainer),
contentAlignment = Alignment.Center
) {
Text(
text = value.toString().padStart(2, '0'),
style = MaterialTheme.typography.titleLarge,
fontWeight = FontWeight.Bold,
color = MaterialTheme.colorScheme.onPrimaryContainer
)
}
}
}
}
@@ -5,8 +5,10 @@ import androidx.compose.foundation.layout.Box
import androidx.compose.foundation.layout.Column import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.fillMaxSize import androidx.compose.foundation.layout.fillMaxSize
import androidx.compose.foundation.layout.padding import androidx.compose.foundation.layout.padding
import androidx.compose.foundation.layout.size
import androidx.compose.foundation.lazy.LazyColumn import androidx.compose.foundation.lazy.LazyColumn
import androidx.compose.foundation.lazy.items import androidx.compose.foundation.lazy.items
import androidx.compose.material3.Button
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
@@ -15,6 +17,7 @@ import androidx.compose.runtime.collectAsState
import androidx.compose.runtime.getValue 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.unit.dp import androidx.compose.ui.unit.dp
import com.example.madwellbeingapp.data.model.Habit import com.example.madwellbeingapp.data.model.Habit
import com.example.madwellbeingapp.ui.viewmodel.HabitViewModel import com.example.madwellbeingapp.ui.viewmodel.HabitViewModel
@@ -34,14 +37,16 @@ fun AllActivitiesScreen(
ScreenHeader(title = "All Activities", onBack = onNavigateBack) ScreenHeader(title = "All Activities", onBack = onNavigateBack)
if (habits.isEmpty()) { if (habits.isEmpty()) {
Box(modifier = Modifier.fillMaxSize().padding(32.dp), contentAlignment = Alignment.Center) { Box(modifier = Modifier.fillMaxSize().padding(32.dp),
contentAlignment = Alignment.Center) {
Text("No activities yet. Go to Manage Activities to create one!", Text("No activities yet. Go to Manage Activities to create one!",
style = MaterialTheme.typography.bodyLarge, style = MaterialTheme.typography.bodyLarge,
color = MaterialTheme.colorScheme.onSurfaceVariant) color = MaterialTheme.colorScheme.onSurfaceVariant)
} }
} else { } else {
LazyColumn( LazyColumn(
modifier = Modifier.fillMaxSize().padding(horizontal = 16.dp, vertical = 12.dp), modifier = Modifier.fillMaxSize()
.padding(horizontal = 16.dp, vertical = 12.dp),
verticalArrangement = Arrangement.spacedBy(10.dp) verticalArrangement = Arrangement.spacedBy(10.dp)
) { ) {
items(habits, key = { it.id }) { habit -> items(habits, key = { it.id }) { habit ->
@@ -52,12 +57,39 @@ fun AllActivitiesScreen(
onClick = { onHabitClick(habit.id) }, onClick = { onHabitClick(habit.id) },
circleColor = cardCircleColor(habit, done), circleColor = cardCircleColor(habit, done),
circleText = cardCircleText(habit, done), circleText = cardCircleText(habit, done),
circleTextColor = if (done) MaterialTheme.colorScheme.onPrimary circleTextColor = if (!habit.isActive)
else MaterialTheme.colorScheme.onSurfaceVariant, MaterialTheme.colorScheme.onSurfaceVariant.copy(alpha = 0.5f)
else if (done) MaterialTheme.colorScheme.onPrimary
else MaterialTheme.colorScheme.onSurfaceVariant,
containerColor = cardContainerColor(habit, done), containerColor = cardContainerColor(habit, done),
contentAlpha = if (!habit.isActive) 0.5f else 1f,
badge = if (!habit.isActive) { badge = if (!habit.isActive) {
{ Text("Retired", style = MaterialTheme.typography.labelSmall, color = MaterialTheme.colorScheme.error) } { Text("Disabled", style = MaterialTheme.typography.labelSmall,
} else null color = MaterialTheme.colorScheme.error) }
} else null,
trailing = if (!habit.isActive) {
{
Button(
onClick = { viewModel.enableHabit(habit) },
modifier = Modifier.size(32.dp),
contentPadding = androidx.compose.foundation.layout.PaddingValues(0.dp)
) {
Text("+", fontWeight = FontWeight.Bold,
style = MaterialTheme.typography.titleMedium)
}
}
} else {
{
Button(
onClick = { viewModel.disableHabit(habit) },
modifier = Modifier.size(32.dp),
contentPadding = androidx.compose.foundation.layout.PaddingValues(0.dp)
) {
Text("−", fontWeight = FontWeight.Bold,
style = MaterialTheme.typography.titleMedium)
}
}
}
) )
} }
} }
@@ -66,7 +98,6 @@ fun AllActivitiesScreen(
} }
} }
/** Resolves the circle background colour for a habit card. */
@Composable @Composable
private fun cardCircleColor(habit: Habit, completedToday: Boolean) = when { private fun cardCircleColor(habit: Habit, completedToday: Boolean) = when {
!habit.isActive -> MaterialTheme.colorScheme.outline.copy(alpha = 0.4f) !habit.isActive -> MaterialTheme.colorScheme.outline.copy(alpha = 0.4f)
@@ -0,0 +1,327 @@
package com.example.madwellbeingapp.ui.screens
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.Spacer
import androidx.compose.foundation.layout.aspectRatio
import androidx.compose.foundation.layout.fillMaxSize
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.foundation.lazy.LazyColumn
import androidx.compose.foundation.lazy.items
import androidx.compose.material3.Card
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
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
import androidx.compose.ui.unit.dp
import com.example.madwellbeingapp.data.model.Habit
import com.example.madwellbeingapp.ui.viewmodel.HabitViewModel
import java.text.SimpleDateFormat
import java.util.Calendar
import java.util.Locale
@Composable
fun CalendarScreen(
viewModel: HabitViewModel,
onNavigateBack: () -> Unit,
onHabitClick: (Int) -> Unit
) {
val habits by viewModel.allHabits.collectAsState()
val activeHabits = habits.filter { it.isActive }
// Current displayed month
var displayYear by remember { mutableStateOf(Calendar.getInstance().get(Calendar.YEAR)) }
var displayMonth by remember { mutableStateOf(Calendar.getInstance().get(Calendar.MONTH)) }
// Compute start/end of displayed month
val monthStart = remember(displayYear, displayMonth) {
val cal = Calendar.getInstance()
cal.set(displayYear, displayMonth, 1, 0, 0, 0)
cal.set(Calendar.MILLISECOND, 0)
cal.timeInMillis
}
val monthEnd = remember(displayYear, displayMonth) {
val cal = Calendar.getInstance()
cal.set(displayYear, displayMonth, 1, 0, 0, 0)
cal.set(Calendar.MILLISECOND, 0)
cal.add(Calendar.MONTH, 1)
cal.add(Calendar.MILLISECOND, -1)
cal.timeInMillis
}
// Logs for displayed month
val monthLogs by viewModel.getLogsBetween(monthStart, monthEnd).collectAsState(initial = emptyList())
// Compute which days have completions and how many habits were completed
val dayCompletionMap = remember(monthLogs) {
val map = mutableMapOf<Long, MutableSet<Int>>() // dayMillis -> set of habitIds
for (log in monthLogs) {
val dayMillis = normaliseDay(log.date)
map.getOrPut(dayMillis) { mutableSetOf() }.add(log.habitId)
}
map
}
// Streaks for active habits
val streakMap = remember { mutableMapOf<Int, Int>() }
LaunchedEffect(activeHabits) {
for (habit in activeHabits) {
if (!streakMap.containsKey(habit.id)) {
streakMap[habit.id] = viewModel.computeStreakForHabit(habit.id)
}
}
}
// Calendar grid data
val daysInMonth = remember(displayYear, displayMonth) {
val cal = Calendar.getInstance()
cal.set(displayYear, displayMonth, 1)
cal.getActualMaximum(Calendar.DAY_OF_MONTH)
}
val firstDayOfWeek = remember(displayYear, displayMonth) {
val cal = Calendar.getInstance()
cal.set(displayYear, displayMonth, 1)
// Monday=0, Sunday=6
(cal.get(Calendar.DAY_OF_WEEK) + 5) % 7
}
val monthLabel = remember(displayYear, displayMonth) {
val cal = Calendar.getInstance()
cal.set(displayYear, displayMonth, 1)
SimpleDateFormat("MMMM yyyy", Locale.getDefault()).format(cal.time)
}
// Total active habits count for day intensity
val totalActive = activeHabits.size
Scaffold { padding ->
Column(modifier = Modifier.fillMaxSize().padding(padding)) {
ScreenHeader(title = "Calendar", onBack = onNavigateBack)
LazyColumn(
modifier = Modifier.fillMaxSize().padding(horizontal = 16.dp, vertical = 8.dp),
verticalArrangement = Arrangement.spacedBy(12.dp)
) {
// Month navigation
item {
Row(
modifier = Modifier.fillMaxWidth(),
horizontalArrangement = Arrangement.SpaceBetween,
verticalAlignment = Alignment.CenterVertically
) {
TextButton(onClick = {
if (displayMonth == 0) { displayMonth = 11; displayYear-- }
else displayMonth--
}) {
Text("◀", style = MaterialTheme.typography.titleLarge,
fontWeight = FontWeight.Bold, color = MaterialTheme.colorScheme.primary)
}
Text(monthLabel, style = MaterialTheme.typography.titleMedium,
fontWeight = FontWeight.Bold)
TextButton(onClick = {
if (displayMonth == 11) { displayMonth = 0; displayYear++ }
else displayMonth++
}) {
Text("▶", style = MaterialTheme.typography.titleLarge,
fontWeight = FontWeight.Bold, color = MaterialTheme.colorScheme.primary)
}
}
}
// Weekday headers
item {
Row(modifier = Modifier.fillMaxWidth()) {
listOf("Mo", "Tu", "We", "Th", "Fr", "Sa", "Su").forEach { day ->
Text(
text = day, modifier = Modifier.weight(1f),
style = MaterialTheme.typography.labelSmall,
fontWeight = FontWeight.Bold,
color = MaterialTheme.colorScheme.onSurfaceVariant
)
}
}
}
// Calendar grid rows
val totalCells = firstDayOfWeek + daysInMonth
val rows = (totalCells + 6) / 7
items(rows) { rowIndex ->
Row(modifier = Modifier.fillMaxWidth()) {
for (col in 0..6) {
val cellIndex = rowIndex * 7 + col
val dayNum = cellIndex - firstDayOfWeek + 1
if (dayNum in 1..daysInMonth) {
val dayCal = Calendar.getInstance()
dayCal.set(displayYear, displayMonth, dayNum, 0, 0, 0)
dayCal.set(Calendar.MILLISECOND, 0)
val dayMillis = dayCal.timeInMillis
val count = dayCompletionMap[dayMillis]?.size ?: 0
val today = isToday(dayMillis)
val intensity = if (totalActive > 0) (count.toFloat() / totalActive).coerceIn(0f, 1f) else 0f
Box(
modifier = Modifier.weight(1f).aspectRatio(1f).padding(2.dp)
.background(
when {
today -> MaterialTheme.colorScheme.primaryContainer
count == 0 -> MaterialTheme.colorScheme.surfaceVariant.copy(alpha = 0.3f)
intensity < 0.5f -> MaterialTheme.colorScheme.primary.copy(alpha = 0.3f)
intensity < 1f -> MaterialTheme.colorScheme.primary.copy(alpha = 0.6f)
else -> MaterialTheme.colorScheme.primary
},
shape = androidx.compose.foundation.shape.RoundedCornerShape(6.dp)
),
contentAlignment = Alignment.Center
) {
Column(horizontalAlignment = Alignment.CenterHorizontally) {
Text(
dayNum.toString(),
style = MaterialTheme.typography.labelSmall,
fontWeight = if (today) FontWeight.Bold else FontWeight.Normal,
color = when {
intensity >= 1f -> MaterialTheme.colorScheme.onPrimary
today -> MaterialTheme.colorScheme.primary
else -> MaterialTheme.colorScheme.onSurface
}
)
if (count > 0) {
Text("$count", style = MaterialTheme.typography.labelSmall,
color = if (intensity >= 1f) MaterialTheme.colorScheme.onPrimary.copy(alpha = 0.8f)
else MaterialTheme.colorScheme.primary)
}
}
}
} else {
// Empty cell
Box(modifier = Modifier.weight(1f).aspectRatio(1f))
}
}
}
}
// Legend
item {
Row(
modifier = Modifier.fillMaxWidth().padding(vertical = 4.dp),
horizontalArrangement = Arrangement.Center,
verticalAlignment = Alignment.CenterVertically
) {
Box(modifier = Modifier.size(12.dp).background(
MaterialTheme.colorScheme.surfaceVariant.copy(alpha = 0.3f),
shape = androidx.compose.foundation.shape.RoundedCornerShape(2.dp)))
Text(" None ", style = MaterialTheme.typography.labelSmall)
Box(modifier = Modifier.size(12.dp).background(
MaterialTheme.colorScheme.primary.copy(alpha = 0.3f),
shape = androidx.compose.foundation.shape.RoundedCornerShape(2.dp)))
Text(" Some ", style = MaterialTheme.typography.labelSmall)
Box(modifier = Modifier.size(12.dp).background(
MaterialTheme.colorScheme.primary,
shape = androidx.compose.foundation.shape.RoundedCornerShape(2.dp)))
Text(" All", style = MaterialTheme.typography.labelSmall)
}
}
// Streak section
item {
Spacer(modifier = Modifier.height(8.dp))
Text("Habit Streaks", style = MaterialTheme.typography.titleMedium,
fontWeight = FontWeight.Bold)
}
if (activeHabits.isEmpty()) {
item {
Text("No active habits yet.",
style = MaterialTheme.typography.bodyMedium,
color = MaterialTheme.colorScheme.onSurfaceVariant,
modifier = Modifier.padding(vertical = 8.dp))
}
} else {
items(activeHabits, key = { it.id }) { habit ->
val streak = streakMap[habit.id] ?: 0
StreakCard(habit = habit, streak = streak, onClick = { onHabitClick(habit.id) })
}
}
item { Spacer(modifier = Modifier.height(16.dp)) }
}
}
}
}
@Composable
private fun StreakCard(habit: Habit, streak: Int, onClick: () -> Unit) {
Card(
onClick = onClick,
modifier = Modifier.fillMaxWidth(),
elevation = CardDefaults.cardElevation(2.dp),
colors = CardDefaults.cardColors(
containerColor = if (streak > 0) MaterialTheme.colorScheme.primaryContainer
else MaterialTheme.colorScheme.surface
)
) {
Row(
modifier = Modifier.fillMaxWidth().padding(14.dp),
verticalAlignment = Alignment.CenterVertically
) {
// Fire icon for active streak
Box(
modifier = Modifier.size(40.dp).background(
if (streak > 0) MaterialTheme.colorScheme.primary
else MaterialTheme.colorScheme.surfaceVariant,
shape = androidx.compose.foundation.shape.CircleShape
),
contentAlignment = Alignment.Center
) {
Text(if (streak > 0) "🔥" else "—", style = MaterialTheme.typography.titleMedium)
}
Spacer(modifier = Modifier.width(12.dp))
Column(modifier = Modifier.weight(1f)) {
Text(habit.displayName, style = MaterialTheme.typography.titleSmall,
fontWeight = FontWeight.SemiBold)
Text(habit.activityType + " • ${habit.targetFrequency}x/week",
style = MaterialTheme.typography.bodySmall,
color = MaterialTheme.colorScheme.onSurfaceVariant)
}
Column(horizontalAlignment = Alignment.CenterHorizontally) {
Text("$streak", style = MaterialTheme.typography.headlineSmall,
fontWeight = FontWeight.Bold,
color = if (streak > 0) MaterialTheme.colorScheme.primary
else MaterialTheme.colorScheme.onSurfaceVariant)
Text(if (streak == 1) "day" else "days",
style = MaterialTheme.typography.labelSmall,
color = MaterialTheme.colorScheme.onSurfaceVariant)
}
}
}
}
private fun normaliseDay(millis: Long): Long {
val c = Calendar.getInstance(); c.timeInMillis = millis
c.set(Calendar.HOUR_OF_DAY, 0); c.set(Calendar.MINUTE, 0)
c.set(Calendar.SECOND, 0); c.set(Calendar.MILLISECOND, 0)
return c.timeInMillis
}
private fun isToday(millis: Long): Boolean {
val todayCal = Calendar.getInstance()
todayCal.set(Calendar.HOUR_OF_DAY, 0); todayCal.set(Calendar.MINUTE, 0)
todayCal.set(Calendar.SECOND, 0); todayCal.set(Calendar.MILLISECOND, 0)
return millis == todayCal.timeInMillis
}
@@ -1,9 +1,6 @@
package com.example.madwellbeingapp.ui.screens package com.example.madwellbeingapp.ui.screens
import android.util.Log
import androidx.compose.foundation.background import androidx.compose.foundation.background
import androidx.compose.foundation.clickable
import androidx.compose.foundation.gestures.detectHorizontalDragGestures
import androidx.compose.foundation.layout.Arrangement import androidx.compose.foundation.layout.Arrangement
import androidx.compose.foundation.layout.Box import androidx.compose.foundation.layout.Box
import androidx.compose.foundation.layout.Column import androidx.compose.foundation.layout.Column
@@ -12,20 +9,14 @@ import androidx.compose.foundation.layout.Spacer
import androidx.compose.foundation.layout.fillMaxSize import androidx.compose.foundation.layout.fillMaxSize
import androidx.compose.foundation.layout.fillMaxWidth import androidx.compose.foundation.layout.fillMaxWidth
import androidx.compose.foundation.layout.height import androidx.compose.foundation.layout.height
import androidx.compose.foundation.layout.offset
import androidx.compose.foundation.layout.padding import androidx.compose.foundation.layout.padding
import androidx.compose.foundation.layout.size import androidx.compose.foundation.layout.size
import androidx.compose.foundation.layout.width
import androidx.compose.foundation.lazy.LazyRow
import androidx.compose.foundation.lazy.items
import androidx.compose.foundation.rememberScrollState import androidx.compose.foundation.rememberScrollState
import androidx.compose.foundation.shape.CircleShape
import androidx.compose.foundation.shape.RoundedCornerShape
import androidx.compose.foundation.verticalScroll import androidx.compose.foundation.verticalScroll
import androidx.compose.material3.AlertDialog import androidx.compose.material3.AlertDialog
import androidx.compose.material3.Button
import androidx.compose.material3.Card import androidx.compose.material3.Card
import androidx.compose.material3.CardDefaults import androidx.compose.material3.CardDefaults
import androidx.compose.material3.LinearProgressIndicator
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
@@ -34,24 +25,18 @@ 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.mutableFloatStateOf
import androidx.compose.runtime.mutableStateOf import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.remember import androidx.compose.runtime.remember
import androidx.compose.runtime.setValue 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.draw.clip
import androidx.compose.ui.input.pointer.pointerInput
import androidx.compose.ui.text.font.FontWeight import androidx.compose.ui.text.font.FontWeight
import androidx.compose.ui.text.style.TextAlign
import androidx.compose.ui.unit.IntOffset
import androidx.compose.ui.unit.dp import androidx.compose.ui.unit.dp
import com.example.madwellbeingapp.ui.viewmodel.HabitViewModel import com.example.madwellbeingapp.ui.viewmodel.HabitViewModel
import java.text.SimpleDateFormat import java.text.SimpleDateFormat
import java.util.Calendar import java.util.Calendar
import java.util.Date import java.util.Date
import java.util.Locale import java.util.Locale
import kotlin.math.roundToInt
@Composable @Composable
fun HabitDetailScreen( fun HabitDetailScreen(
@@ -70,22 +55,23 @@ 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 showDeleteDialog by remember { mutableStateOf(false) } var showDisableDialog by remember { mutableStateOf(false) }
if (showDeleteDialog && habit != null) { if (showDisableDialog && habit != null) {
AlertDialog( AlertDialog(
onDismissRequest = { showDeleteDialog = false }, onDismissRequest = { showDisableDialog = false },
title = { Text("Delete Habit") }, title = { Text("Disable Habit") },
text = { Text("Delete \"${habit!!.displayName}\"? All data will be lost.") }, text = { Text("Disable \"${habit!!.displayName}\"? It will be greyed out but data is kept.") },
confirmButton = { confirmButton = {
TextButton(onClick = { TextButton(onClick = {
Log.i("HabitDetail", "DELETE '${habit!!.displayName}' id=${habit!!.id}") viewModel.disableHabit(habit!!)
viewModel.deleteHabit(habit!!) showDisableDialog = false
showDeleteDialog = false
onNavigateBack() onNavigateBack()
}) { Text("Delete", color = MaterialTheme.colorScheme.error) } }) { Text("Disable", color = MaterialTheme.colorScheme.error) }
}, },
dismissButton = { TextButton(onClick = { showDeleteDialog = false }) { Text("Cancel") } } dismissButton = {
TextButton(onClick = { showDisableDialog = false }) { Text("Cancel") }
}
) )
} }
@@ -96,16 +82,28 @@ fun HabitDetailScreen(
onBack = onNavigateBack, onBack = onNavigateBack,
trailing = { trailing = {
Row { Row {
Text("✏️", modifier = Modifier.clickable { onEditHabit(habitId) }.padding(horizontal = 8.dp), TextButton(onClick = { onEditHabit(habitId) }) {
style = MaterialTheme.typography.titleLarge) Text("Edit", color = MaterialTheme.colorScheme.onPrimary)
Text("🗑️", modifier = Modifier.clickable { showDeleteDialog = true }.padding(horizontal = 8.dp), }
style = MaterialTheme.typography.titleLarge) if (habit?.isActive == true) {
TextButton(onClick = { showDisableDialog = true }) {
Text("−", color = MaterialTheme.colorScheme.onPrimary,
fontWeight = FontWeight.Bold)
}
} else {
TextButton(onClick = { if (habit != null) viewModel.enableHabit(habit!!) }) {
Text("+", color = MaterialTheme.colorScheme.onPrimary,
fontWeight = FontWeight.Bold)
}
}
} }
} }
) )
if (habit == null) { if (habit == null) {
Box(modifier = Modifier.fillMaxSize(), contentAlignment = Alignment.Center) { Text("Loading…") } Box(modifier = Modifier.fillMaxSize(), contentAlignment = Alignment.Center) {
Text("Loading…")
}
return@Scaffold return@Scaffold
} }
@@ -117,12 +115,18 @@ fun HabitDetailScreen(
verticalArrangement = Arrangement.spacedBy(16.dp) verticalArrangement = Arrangement.spacedBy(16.dp)
) { ) {
// Info card // Info card
Card(shape = RoundedCornerShape(16.dp), elevation = CardDefaults.cardElevation(2.dp), modifier = Modifier.fillMaxWidth()) { Card(
modifier = Modifier.fillMaxWidth(),
elevation = CardDefaults.cardElevation(2.dp)
) {
Column(modifier = Modifier.padding(16.dp)) { Column(modifier = Modifier.padding(16.dp)) {
Text(h.activityType, style = MaterialTheme.typography.labelLarge, color = MaterialTheme.colorScheme.primary) Text(h.activityType, style = MaterialTheme.typography.labelLarge,
color = MaterialTheme.colorScheme.primary)
Spacer(modifier = Modifier.height(4.dp)) Spacer(modifier = Modifier.height(4.dp))
Text("Started: ${fmt.format(Date(h.startDate))}", style = MaterialTheme.typography.bodyMedium) Text("Started: ${fmt.format(Date(h.startDate))}",
Text("Target: ${h.targetFrequency}x per week", style = MaterialTheme.typography.bodyMedium) style = MaterialTheme.typography.bodyMedium)
Text("Target: ${h.targetFrequency}x per week",
style = MaterialTheme.typography.bodyMedium)
if (h.reminderEnabled) { if (h.reminderEnabled) {
Text("Reminder: ${h.reminderHour.toString().padStart(2, '0')}:${h.reminderMinute.toString().padStart(2, '0')}", Text("Reminder: ${h.reminderHour.toString().padStart(2, '0')}:${h.reminderMinute.toString().padStart(2, '0')}",
style = MaterialTheme.typography.bodyMedium) style = MaterialTheme.typography.bodyMedium)
@@ -130,65 +134,89 @@ fun HabitDetailScreen(
} }
} }
// Swipe bar // Complete/Undo button
SwipeBar(isCompletedToday) { Button(
Log.i("HabitDetail", "Swipe '${h.displayName}' id=${h.id} undo=$isCompletedToday") onClick = { viewModel.toggleTodayLog(habitId) },
viewModel.toggleTodayLog(habitId) modifier = Modifier.fillMaxWidth().height(52.dp)
) {
Text(
if (isCompletedToday) "Undo Today" else "Mark Complete",
style = MaterialTheme.typography.titleMedium,
fontWeight = FontWeight.Bold
)
} }
// Streaks // Streaks
Row(modifier = Modifier.fillMaxWidth(), horizontalArrangement = Arrangement.spacedBy(12.dp)) { Row(modifier = Modifier.fillMaxWidth(), horizontalArrangement = Arrangement.spacedBy(12.dp)) {
StatCard("🔥 Current", "$currentStreak day${if (currentStreak != 1) "s" else ""}", Modifier.weight(1f)) StatCard("Current Streak",
StatCard("🏆 Longest", "$longestStreak day${if (longestStreak != 1) "s" else ""}", Modifier.weight(1f)) "$currentStreak day${if (currentStreak != 1) "s" else ""}",
Modifier.weight(1f))
StatCard("Longest Streak",
"$longestStreak day${if (longestStreak != 1) "s" else ""}",
Modifier.weight(1f))
} }
// Weekly progress // Weekly progress
Card(shape = RoundedCornerShape(16.dp), elevation = CardDefaults.cardElevation(2.dp), modifier = Modifier.fillMaxWidth()) { Card(modifier = Modifier.fillMaxWidth(), elevation = CardDefaults.cardElevation(2.dp)) {
Column(modifier = Modifier.padding(16.dp)) { Column(modifier = Modifier.padding(16.dp)) {
Text("Weekly Progress", style = MaterialTheme.typography.titleMedium, fontWeight = FontWeight.SemiBold) Text("Weekly Progress", style = MaterialTheme.typography.titleMedium,
Spacer(modifier = Modifier.height(12.dp)) fontWeight = FontWeight.SemiBold)
LinearProgressIndicator(progress = { weeklyProgress }, Spacer(modifier = Modifier.height(8.dp))
modifier = Modifier.fillMaxWidth().height(12.dp).clip(RoundedCornerShape(6.dp)))
Spacer(modifier = Modifier.height(6.dp))
Text("${(weeklyProgress * 100).toInt()}% of weekly goal", Text("${(weeklyProgress * 100).toInt()}% of weekly goal",
style = MaterialTheme.typography.bodySmall, color = MaterialTheme.colorScheme.onSurfaceVariant) style = MaterialTheme.typography.bodyMedium,
color = MaterialTheme.colorScheme.onSurfaceVariant)
} }
} }
// Last 14 days // Last 14 days
Text("Last 14 Days", style = MaterialTheme.typography.titleMedium, fontWeight = FontWeight.SemiBold) Text("Last 14 Days", style = MaterialTheme.typography.titleMedium,
fontWeight = FontWeight.SemiBold)
val logDates = logs.filter { it.completed }.map { normalise(it.date) }.toSet() val logDates = logs.filter { it.completed }.map { normalise(it.date) }.toSet()
val today = todayMillis() val today = todayMillis()
LazyRow(horizontalArrangement = Arrangement.spacedBy(6.dp)) { Row(
items((0..13).map { today - it * 86_400_000L }.reversed()) { day -> modifier = Modifier.fillMaxWidth(),
horizontalArrangement = Arrangement.spacedBy(4.dp)
) {
(0..13).map { today - it * 86_400_000L }.reversed().forEach { day ->
val done = logDates.contains(day) val done = logDates.contains(day)
Column(horizontalAlignment = Alignment.CenterHorizontally) { Column(
horizontalAlignment = Alignment.CenterHorizontally,
modifier = Modifier.weight(1f)
) {
Box( Box(
modifier = Modifier.size(36.dp).clip(CircleShape).background( modifier = Modifier.size(24.dp)
if (done) MaterialTheme.colorScheme.primary else MaterialTheme.colorScheme.surfaceVariant), .background(
if (done) MaterialTheme.colorScheme.primary
else MaterialTheme.colorScheme.surfaceVariant,
shape = androidx.compose.foundation.shape.CircleShape
),
contentAlignment = Alignment.Center contentAlignment = Alignment.Center
) { ) {
Text(if (done) "✓" else "", Text(
color = if (done) MaterialTheme.colorScheme.onPrimary else MaterialTheme.colorScheme.onSurfaceVariant, if (done) "✓" else "",
style = MaterialTheme.typography.labelSmall) style = MaterialTheme.typography.labelSmall,
color = if (done) MaterialTheme.colorScheme.onPrimary
else MaterialTheme.colorScheme.onSurfaceVariant
)
} }
Spacer(modifier = Modifier.height(2.dp)) Text(
Text(SimpleDateFormat("dd", Locale.getDefault()).format(Date(day)), SimpleDateFormat("dd", Locale.getDefault()).format(Date(day)),
style = MaterialTheme.typography.labelSmall, textAlign = TextAlign.Center) style = MaterialTheme.typography.labelSmall
)
} }
} }
} }
// Total completions // Total completions
val total = logs.count { it.completed } val total = logs.count { it.completed }
Card(shape = RoundedCornerShape(16.dp), elevation = CardDefaults.cardElevation(2.dp), modifier = Modifier.fillMaxWidth()) { Card(modifier = Modifier.fillMaxWidth(), elevation = CardDefaults.cardElevation(2.dp)) {
Row(modifier = Modifier.padding(16.dp), verticalAlignment = Alignment.CenterVertically) { Row(modifier = Modifier.padding(16.dp), verticalAlignment = Alignment.CenterVertically) {
Text("📊", style = MaterialTheme.typography.headlineMedium)
Spacer(modifier = Modifier.width(12.dp))
Column { Column {
Text("Total Completions", style = MaterialTheme.typography.titleSmall, fontWeight = FontWeight.SemiBold) Text("Total Completions", style = MaterialTheme.typography.titleSmall,
fontWeight = FontWeight.SemiBold)
Text("$total time${if (total != 1) "s" else ""}", Text("$total time${if (total != 1) "s" else ""}",
style = MaterialTheme.typography.bodyMedium, color = MaterialTheme.colorScheme.onSurfaceVariant) style = MaterialTheme.typography.bodyMedium,
color = MaterialTheme.colorScheme.onSurfaceVariant)
} }
} }
} }
@@ -198,60 +226,32 @@ fun HabitDetailScreen(
} }
} }
@Composable
private fun SwipeBar(isCompleted: Boolean, onSwipe: () -> Unit) {
val threshold = 200f
var offsetX by remember { mutableFloatStateOf(0f) }
Box(modifier = Modifier.fillMaxWidth().height(56.dp).clip(RoundedCornerShape(14.dp))) {
Box(
modifier = Modifier.matchParentSize().background(
if (isCompleted) MaterialTheme.colorScheme.primaryContainer else MaterialTheme.colorScheme.primary.copy(alpha = 0.15f)),
contentAlignment = Alignment.Center
) {
Text(if (isCompleted) "Swipe → to Undo" else "Swipe → to Complete",
style = MaterialTheme.typography.bodyMedium, fontWeight = FontWeight.Bold,
color = if (isCompleted) MaterialTheme.colorScheme.onPrimaryContainer else MaterialTheme.colorScheme.primary)
}
Box(
modifier = Modifier.size(80.dp, 56.dp)
.offset { IntOffset(offsetX.roundToInt(), 0) }
.clip(RoundedCornerShape(14.dp))
.background(MaterialTheme.colorScheme.primary)
.pointerInput(isCompleted) {
detectHorizontalDragGestures(
onDragEnd = { if (offsetX > threshold) onSwipe(); offsetX = 0f },
onDragCancel = { offsetX = 0f },
onHorizontalDrag = { _, d -> offsetX = (offsetX + d).coerceIn(0f, threshold + 50f) })
},
contentAlignment = Alignment.Center
) {
Text(if (isCompleted) "✅" else "→", style = MaterialTheme.typography.titleLarge,
color = MaterialTheme.colorScheme.onPrimary, fontWeight = FontWeight.Bold)
}
}
}
@Composable @Composable
private fun StatCard(title: String, value: String, modifier: Modifier = Modifier) { private fun StatCard(title: String, value: String, modifier: Modifier = Modifier) {
Card(modifier = modifier, shape = RoundedCornerShape(16.dp), elevation = CardDefaults.cardElevation(2.dp), Card(
colors = CardDefaults.cardColors(containerColor = MaterialTheme.colorScheme.primaryContainer)) { modifier = modifier,
elevation = CardDefaults.cardElevation(2.dp),
colors = CardDefaults.cardColors(containerColor = MaterialTheme.colorScheme.primaryContainer)
) {
Column(modifier = Modifier.padding(16.dp), horizontalAlignment = Alignment.CenterHorizontally) { Column(modifier = Modifier.padding(16.dp), horizontalAlignment = Alignment.CenterHorizontally) {
Text(title, style = MaterialTheme.typography.labelMedium, textAlign = TextAlign.Center) Text(title, style = MaterialTheme.typography.labelMedium)
Spacer(modifier = Modifier.height(6.dp)) Spacer(modifier = Modifier.height(6.dp))
Text(value, style = MaterialTheme.typography.titleLarge, fontWeight = FontWeight.Bold, Text(value, style = MaterialTheme.typography.titleLarge, fontWeight = FontWeight.Bold,
color = MaterialTheme.colorScheme.primary, textAlign = TextAlign.Center) color = MaterialTheme.colorScheme.primary)
} }
} }
} }
private fun normalise(millis: Long): Long { private fun normalise(millis: Long): Long {
val c = Calendar.getInstance(); c.timeInMillis = millis val c = Calendar.getInstance(); c.timeInMillis = millis
c.set(Calendar.HOUR_OF_DAY, 0); c.set(Calendar.MINUTE, 0); c.set(Calendar.SECOND, 0); c.set(Calendar.MILLISECOND, 0) c.set(Calendar.HOUR_OF_DAY, 0); c.set(Calendar.MINUTE, 0)
c.set(Calendar.SECOND, 0); c.set(Calendar.MILLISECOND, 0)
return c.timeInMillis return c.timeInMillis
} }
private fun todayMillis(): Long { private fun todayMillis(): Long {
val c = Calendar.getInstance() val c = Calendar.getInstance()
c.set(Calendar.HOUR_OF_DAY, 0); c.set(Calendar.MINUTE, 0); c.set(Calendar.SECOND, 0); c.set(Calendar.MILLISECOND, 0) c.set(Calendar.HOUR_OF_DAY, 0); c.set(Calendar.MINUTE, 0)
c.set(Calendar.SECOND, 0); c.set(Calendar.MILLISECOND, 0)
return c.timeInMillis return c.timeInMillis
} }
@@ -1,12 +1,11 @@
package com.example.madwellbeingapp.ui.screens package com.example.madwellbeingapp.ui.screens
import android.util.Log
import androidx.compose.foundation.background import androidx.compose.foundation.background
import androidx.compose.foundation.clickable
import androidx.compose.foundation.gestures.detectHorizontalDragGestures import androidx.compose.foundation.gestures.detectHorizontalDragGestures
import androidx.compose.foundation.layout.Arrangement import androidx.compose.foundation.layout.Arrangement
import androidx.compose.foundation.layout.Box import androidx.compose.foundation.layout.Box
import androidx.compose.foundation.layout.Column import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.PaddingValues
import androidx.compose.foundation.layout.Row import androidx.compose.foundation.layout.Row
import androidx.compose.foundation.layout.Spacer import androidx.compose.foundation.layout.Spacer
import androidx.compose.foundation.layout.fillMaxSize import androidx.compose.foundation.layout.fillMaxSize
@@ -15,27 +14,23 @@ import androidx.compose.foundation.layout.height
import androidx.compose.foundation.layout.offset import androidx.compose.foundation.layout.offset
import androidx.compose.foundation.layout.padding import androidx.compose.foundation.layout.padding
import androidx.compose.foundation.layout.size import androidx.compose.foundation.layout.size
import androidx.compose.foundation.layout.width
import androidx.compose.foundation.lazy.LazyColumn import androidx.compose.foundation.lazy.LazyColumn
import androidx.compose.foundation.lazy.items import androidx.compose.foundation.lazy.items
import androidx.compose.foundation.shape.CircleShape
import androidx.compose.foundation.shape.RoundedCornerShape import androidx.compose.foundation.shape.RoundedCornerShape
import androidx.compose.material3.Button import androidx.compose.material3.Button
import androidx.compose.material3.Card import androidx.compose.material3.Card
import androidx.compose.material3.CardDefaults import androidx.compose.material3.CardDefaults
import androidx.compose.material3.LinearProgressIndicator
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.runtime.Composable import androidx.compose.runtime.Composable
import androidx.compose.runtime.collectAsState import androidx.compose.runtime.collectAsState
import androidx.compose.runtime.getValue import androidx.compose.runtime.getValue
import androidx.compose.runtime.mutableFloatStateOf import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.remember import androidx.compose.runtime.remember
import androidx.compose.runtime.setValue 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.draw.clip
import androidx.compose.ui.input.pointer.pointerInput import androidx.compose.ui.input.pointer.pointerInput
import androidx.compose.ui.text.font.FontWeight import androidx.compose.ui.text.font.FontWeight
import androidx.compose.ui.unit.IntOffset import androidx.compose.ui.unit.IntOffset
@@ -61,59 +56,53 @@ fun HomeScreen(
Scaffold { padding -> Scaffold { padding ->
Column(modifier = Modifier.fillMaxSize().padding(padding)) { Column(modifier = Modifier.fillMaxSize().padding(padding)) {
// Extended header with summary ScreenHeader(title = "Manage Activities", onBack = onNavigateBack)
// Summary bar
Column( Column(
modifier = Modifier.fillMaxWidth() modifier = Modifier.fillMaxWidth()
.background(MaterialTheme.colorScheme.primary) .background(MaterialTheme.colorScheme.primaryContainer)
.padding(horizontal = 20.dp, vertical = 24.dp) .padding(horizontal = 20.dp, vertical = 12.dp)
) { ) {
Row(verticalAlignment = Alignment.CenterVertically) { Text(
Text("←", modifier = Modifier.clickable(onClick = onNavigateBack).padding(end = 16.dp), SimpleDateFormat("EEEE, MMM d", Locale.getDefault()).format(Date()),
style = MaterialTheme.typography.titleLarge,
color = MaterialTheme.colorScheme.onPrimary, fontWeight = FontWeight.Bold)
Text("Manage Activities", style = MaterialTheme.typography.headlineSmall,
color = MaterialTheme.colorScheme.onPrimary, fontWeight = FontWeight.Bold)
}
Spacer(modifier = Modifier.height(4.dp))
Text(SimpleDateFormat("EEEE, MMM d", Locale.getDefault()).format(Date()),
style = MaterialTheme.typography.bodyMedium, style = MaterialTheme.typography.bodyMedium,
color = MaterialTheme.colorScheme.onPrimary.copy(alpha = 0.8f)) color = MaterialTheme.colorScheme.onPrimaryContainer
Spacer(modifier = Modifier.height(12.dp)) )
val done = activeHabits.count { completedIds.contains(it.id) } val done = activeHabits.count { completedIds.contains(it.id) }
val total = activeHabits.size Text(
Text("$done / $total habits completed today", "$done / ${activeHabits.size} habits completed today",
style = MaterialTheme.typography.bodyLarge, style = MaterialTheme.typography.bodyLarge,
color = MaterialTheme.colorScheme.onPrimary, fontWeight = FontWeight.Medium) fontWeight = FontWeight.Medium,
if (total > 0) { color = MaterialTheme.colorScheme.onPrimaryContainer
Spacer(modifier = Modifier.height(8.dp)) )
LinearProgressIndicator(
progress = { done.toFloat() / total },
modifier = Modifier.fillMaxWidth().height(8.dp).clip(RoundedCornerShape(4.dp)),
color = MaterialTheme.colorScheme.onPrimary,
trackColor = MaterialTheme.colorScheme.onPrimary.copy(alpha = 0.3f))
}
} }
// List or empty state
if (activeHabits.isEmpty()) { if (activeHabits.isEmpty()) {
Box(modifier = Modifier.fillMaxSize().weight(1f).padding(32.dp), contentAlignment = Alignment.Center) { Box(
modifier = Modifier.fillMaxSize().weight(1f).padding(32.dp),
contentAlignment = Alignment.Center
) {
Column(horizontalAlignment = Alignment.CenterHorizontally) { Column(horizontalAlignment = Alignment.CenterHorizontally) {
Text("No habits yet!", style = MaterialTheme.typography.titleMedium, color = MaterialTheme.colorScheme.onSurfaceVariant) Text("No habits yet!", style = MaterialTheme.typography.titleMedium)
Spacer(modifier = Modifier.height(8.dp)) Spacer(modifier = Modifier.height(8.dp))
Text("Tap the button below to create your first habit", style = MaterialTheme.typography.bodyMedium, Text("Tap the button below to create your first habit",
color = MaterialTheme.colorScheme.onSurfaceVariant.copy(alpha = 0.7f)) style = MaterialTheme.typography.bodyMedium)
} }
} }
} else { } else {
LazyColumn( LazyColumn(
modifier = Modifier.weight(1f).fillMaxWidth().padding(horizontal = 16.dp, vertical = 12.dp), modifier = Modifier.weight(1f).fillMaxWidth()
.padding(horizontal = 16.dp, vertical = 12.dp),
verticalArrangement = Arrangement.spacedBy(10.dp) verticalArrangement = Arrangement.spacedBy(10.dp)
) { ) {
items(activeHabits, key = { it.id }) { habit -> items(activeHabits, key = { it.id }) { habit ->
val completed = completedIds.contains(habit.id)
SwipeHabitCard( SwipeHabitCard(
habit = habit, habit = habit,
completed = completedIds.contains(habit.id), completed = completed,
onSwipe = { viewModel.toggleTodayLog(habit.id) }, onSwipeRight = { viewModel.toggleTodayLog(habit.id) },
onSwipeLeft = { viewModel.disableHabit(habit) },
onClick = { onHabitClick(habit.id) }, onClick = { onHabitClick(habit.id) },
viewModel = viewModel viewModel = viewModel
) )
@@ -123,91 +112,128 @@ fun HomeScreen(
Button( Button(
onClick = onAddHabit, onClick = onAddHabit,
modifier = Modifier.fillMaxWidth().padding(horizontal = 16.dp, vertical = 12.dp).height(52.dp), modifier = Modifier.fillMaxWidth()
.padding(horizontal = 16.dp, vertical = 12.dp).height(52.dp),
shape = RoundedCornerShape(14.dp) shape = RoundedCornerShape(14.dp)
) { ) {
Text("+ Add New Habit", style = MaterialTheme.typography.titleMedium, fontWeight = FontWeight.Bold) Text("+ Add New Habit", style = MaterialTheme.typography.titleMedium,
fontWeight = FontWeight.Bold)
} }
} }
} }
} }
/** Habit card with swipe-to-complete gesture. */ /** Habit card with swipe-right-to-complete, swipe-left-to-disable, and a − button. */
@Composable @Composable
private fun SwipeHabitCard( private fun SwipeHabitCard(
habit: Habit, completed: Boolean, onSwipe: () -> Unit, habit: Habit, completed: Boolean, onSwipeRight: () -> Unit,
onClick: () -> Unit, viewModel: HabitViewModel onSwipeLeft: () -> Unit, onClick: () -> Unit, viewModel: HabitViewModel
) { ) {
val weeklyProgress by viewModel.weeklyProgress(habit.id).collectAsState(initial = 0f) val weeklyProgress by viewModel.weeklyProgress(habit.id).collectAsState(initial = 0f)
val threshold = 150f val threshold = 150f
var offsetX by remember { mutableFloatStateOf(0f) } var offsetX by remember { mutableStateOf(0f) }
Box(modifier = Modifier.fillMaxWidth().clip(RoundedCornerShape(16.dp))) { Box(
// Swipe background modifier = Modifier.fillMaxWidth(),
contentAlignment = Alignment.Center
) {
// Right-swipe reveal (complete / undo)
Box( Box(
modifier = Modifier.matchParentSize().background( modifier = Modifier.matchParentSize()
if (completed) MaterialTheme.colorScheme.error.copy(alpha = 0.2f) .background(
else MaterialTheme.colorScheme.primary.copy(alpha = 0.2f)), if (completed) MaterialTheme.colorScheme.error.copy(alpha = 0.2f)
else MaterialTheme.colorScheme.primary.copy(alpha = 0.2f),
shape = RoundedCornerShape(16.dp)
),
contentAlignment = Alignment.CenterStart contentAlignment = Alignment.CenterStart
) { ) {
Text( Text(
if (completed) " ← Undo" else " Swipe → to Complete", if (completed) " ← Undo" else " → Complete",
modifier = Modifier.padding(start = 16.dp), modifier = Modifier.padding(start = 16.dp),
style = MaterialTheme.typography.bodyMedium, fontWeight = FontWeight.Bold, style = MaterialTheme.typography.bodyMedium, fontWeight = FontWeight.Bold,
color = if (completed) MaterialTheme.colorScheme.error else MaterialTheme.colorScheme.primary) color = if (completed) MaterialTheme.colorScheme.error
else MaterialTheme.colorScheme.primary
)
} }
// Left-swipe reveal (disable)
Box(
modifier = Modifier.matchParentSize()
.background(
MaterialTheme.colorScheme.error.copy(alpha = 0.15f),
shape = RoundedCornerShape(16.dp)
),
contentAlignment = Alignment.CenterEnd
) {
Text(
"Disable ← ",
modifier = Modifier.padding(end = 16.dp),
style = MaterialTheme.typography.bodyMedium, fontWeight = FontWeight.Bold,
color = MaterialTheme.colorScheme.error
)
}
// Sliding card // Sliding card
Card( Card(
onClick = onClick,
modifier = Modifier.fillMaxWidth() modifier = Modifier.fillMaxWidth()
.offset { IntOffset(offsetX.roundToInt(), 0) } .offset { IntOffset(offsetX.roundToInt(), 0) }
.pointerInput(completed) { .pointerInput(completed) {
detectHorizontalDragGestures( detectHorizontalDragGestures(
onDragEnd = { onDragEnd = {
if (offsetX > threshold) { if (offsetX > threshold) onSwipeRight()
Log.d("SwipeGesture", "Swiped '${habit.displayName}'") else if (offsetX < -threshold) onSwipeLeft()
onSwipe()
}
offsetX = 0f offsetX = 0f
}, },
onDragCancel = { offsetX = 0f }, onDragCancel = { offsetX = 0f },
onHorizontalDrag = { _, d -> offsetX = (offsetX + d).coerceIn(0f, threshold + 50f) } onHorizontalDrag = { _, d ->
offsetX = (offsetX + d).coerceIn(-(threshold + 50f), threshold + 50f)
}
) )
}.clickable(onClick = onClick), },
shape = RoundedCornerShape(16.dp), shape = RoundedCornerShape(16.dp),
elevation = CardDefaults.cardElevation(2.dp), elevation = CardDefaults.cardElevation(2.dp),
colors = CardDefaults.cardColors( colors = CardDefaults.cardColors(
containerColor = if (completed) MaterialTheme.colorScheme.primaryContainer containerColor = if (completed) MaterialTheme.colorScheme.primaryContainer
else MaterialTheme.colorScheme.surface) else MaterialTheme.colorScheme.surface
)
) { ) {
Row(modifier = Modifier.fillMaxWidth().padding(16.dp), verticalAlignment = Alignment.CenterVertically) { Column(modifier = Modifier.padding(16.dp)) {
Box( Row(verticalAlignment = Alignment.CenterVertically) {
modifier = Modifier.size(44.dp).clip(CircleShape).background( Column(modifier = Modifier.weight(1f)) {
if (completed) MaterialTheme.colorScheme.primary else MaterialTheme.colorScheme.surfaceVariant), Text(habit.displayName, style = MaterialTheme.typography.titleMedium,
contentAlignment = Alignment.Center fontWeight = FontWeight.SemiBold)
) { Text(
Text(if (completed) "✓" else "", habit.activityType + " • ${habit.targetFrequency}x/week",
color = if (completed) MaterialTheme.colorScheme.onPrimary else MaterialTheme.colorScheme.onSurfaceVariant, style = MaterialTheme.typography.bodySmall,
fontWeight = FontWeight.Bold, style = MaterialTheme.typography.titleMedium) color = MaterialTheme.colorScheme.onSurfaceVariant
} )
Spacer(modifier = Modifier.width(14.dp)) Text(
Column(modifier = Modifier.weight(1f)) { "Weekly: ${(weeklyProgress * 100).toInt()}%",
Text(habit.displayName, style = MaterialTheme.typography.titleMedium, fontWeight = FontWeight.SemiBold)
Spacer(modifier = Modifier.height(2.dp))
Text(habit.activityType + " • ${habit.targetFrequency}x/week",
style = MaterialTheme.typography.bodySmall, color = MaterialTheme.colorScheme.onSurfaceVariant)
Spacer(modifier = Modifier.height(8.dp))
LinearProgressIndicator(
progress = { weeklyProgress },
modifier = Modifier.fillMaxWidth().height(6.dp).clip(RoundedCornerShape(3.dp)),
color = MaterialTheme.colorScheme.primary, trackColor = MaterialTheme.colorScheme.surfaceVariant)
Spacer(modifier = Modifier.height(2.dp))
Row(modifier = Modifier.fillMaxWidth(), horizontalArrangement = Arrangement.SpaceBetween) {
Text("Weekly: ${(weeklyProgress * 100).toInt()}%",
style = MaterialTheme.typography.labelSmall, style = MaterialTheme.typography.labelSmall,
color = MaterialTheme.colorScheme.onSurfaceVariant.copy(alpha = 0.7f)) color = MaterialTheme.colorScheme.onSurfaceVariant
if (!completed) Text("Swipe → to complete", )
}
// Minus button for quick disable
Button(
onClick = onSwipeLeft,
modifier = Modifier.size(36.dp),
shape = RoundedCornerShape(8.dp),
contentPadding = PaddingValues(0.dp)
) {
Text("−", style = MaterialTheme.typography.titleMedium,
fontWeight = FontWeight.Bold)
}
}
Spacer(modifier = Modifier.height(4.dp))
Row(modifier = Modifier.fillMaxWidth(), horizontalArrangement = Arrangement.SpaceBetween) {
if (!completed) {
Text("→ complete ← disable",
style = MaterialTheme.typography.labelSmall, style = MaterialTheme.typography.labelSmall,
color = MaterialTheme.colorScheme.primary.copy(alpha = 0.6f)) color = MaterialTheme.colorScheme.primary.copy(alpha = 0.6f))
} else {
Text("→ undo",
style = MaterialTheme.typography.labelSmall,
color = MaterialTheme.colorScheme.error.copy(alpha = 0.6f))
} }
} }
} }
@@ -32,7 +32,8 @@ import androidx.compose.ui.unit.dp
fun LandingScreen( fun LandingScreen(
onAllActivities: () -> Unit, onAllActivities: () -> Unit,
onManageActivities: () -> Unit, onManageActivities: () -> Unit,
onActiveOnly: () -> Unit onActiveOnly: () -> Unit,
onCalendar: () -> Unit
) { ) {
Box( Box(
modifier = Modifier modifier = Modifier
@@ -69,6 +70,8 @@ fun LandingScreen(
LandingButton("Manage Activities", onManageActivities) LandingButton("Manage Activities", onManageActivities)
Spacer(modifier = Modifier.height(16.dp)) Spacer(modifier = Modifier.height(16.dp))
LandingButton("Active Only", onActiveOnly) LandingButton("Active Only", onActiveOnly)
Spacer(modifier = Modifier.height(16.dp))
LandingButton("Calendar", onCalendar)
} }
} }
} }
@@ -1,7 +1,6 @@
package com.example.madwellbeingapp.ui.screens package com.example.madwellbeingapp.ui.screens
import androidx.compose.foundation.background import androidx.compose.foundation.background
import androidx.compose.foundation.clickable
import androidx.compose.foundation.layout.Arrangement import androidx.compose.foundation.layout.Arrangement
import androidx.compose.foundation.layout.Box import androidx.compose.foundation.layout.Box
import androidx.compose.foundation.layout.Column import androidx.compose.foundation.layout.Column
@@ -12,30 +11,22 @@ import androidx.compose.foundation.layout.height
import androidx.compose.foundation.layout.padding import androidx.compose.foundation.layout.padding
import androidx.compose.foundation.layout.size import androidx.compose.foundation.layout.size
import androidx.compose.foundation.layout.width import androidx.compose.foundation.layout.width
import androidx.compose.foundation.shape.CircleShape
import androidx.compose.foundation.shape.RoundedCornerShape
import androidx.compose.material3.Card import androidx.compose.material3.Card
import androidx.compose.material3.CardDefaults import androidx.compose.material3.CardDefaults
import androidx.compose.material3.LinearProgressIndicator
import androidx.compose.material3.MaterialTheme import androidx.compose.material3.MaterialTheme
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.collectAsState import androidx.compose.runtime.collectAsState
import androidx.compose.runtime.getValue 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.draw.clip
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.text.font.FontWeight import androidx.compose.ui.text.font.FontWeight
import androidx.compose.ui.unit.dp import androidx.compose.ui.unit.dp
import com.example.madwellbeingapp.data.model.Habit import com.example.madwellbeingapp.data.model.Habit
import com.example.madwellbeingapp.ui.viewmodel.HabitViewModel import com.example.madwellbeingapp.ui.viewmodel.HabitViewModel
// ───────────────────────────────────────────────────────────── /** Standard header bar with a back button and a title. */
// Reusable composables shared across multiple screens.
// ─────────────────────────────────────────────────────────────
/** Standard header bar with a ← back button and a title. */
@Composable @Composable
fun ScreenHeader( fun ScreenHeader(
title: String, title: String,
@@ -46,7 +37,7 @@ fun ScreenHeader(
modifier = Modifier modifier = Modifier
.fillMaxWidth() .fillMaxWidth()
.background(MaterialTheme.colorScheme.primary) .background(MaterialTheme.colorScheme.primary)
.padding(horizontal = 16.dp, vertical = 16.dp) .padding(horizontal = 8.dp, vertical = 8.dp)
) { ) {
Row( Row(
modifier = Modifier.fillMaxWidth(), modifier = Modifier.fillMaxWidth(),
@@ -54,15 +45,14 @@ fun ScreenHeader(
horizontalArrangement = Arrangement.SpaceBetween horizontalArrangement = Arrangement.SpaceBetween
) { ) {
Row(verticalAlignment = Alignment.CenterVertically) { Row(verticalAlignment = Alignment.CenterVertically) {
Text( TextButton(onClick = onBack) {
text = "←", Text(
modifier = Modifier text = "←",
.clickable(onClick = onBack) style = MaterialTheme.typography.titleLarge,
.padding(end = 12.dp), color = MaterialTheme.colorScheme.onPrimary,
style = MaterialTheme.typography.titleLarge, fontWeight = FontWeight.Bold
color = MaterialTheme.colorScheme.onPrimary, )
fontWeight = FontWeight.Bold }
)
Text( Text(
text = title, text = title,
style = MaterialTheme.typography.titleLarge, style = MaterialTheme.typography.titleLarge,
@@ -77,45 +67,39 @@ fun ScreenHeader(
/** /**
* Standard habit card used on list screens. * Standard habit card used on list screens.
*
* Shows a status circle, display name, activity type, frequency, and
* a weekly progress bar. Customisable via [circleColor], [circleText],
* and [containerColor].
*/ */
@Composable @Composable
fun HabitCard( fun HabitCard(
habit: Habit, habit: Habit,
viewModel: HabitViewModel, viewModel: HabitViewModel,
onClick: () -> Unit, onClick: () -> Unit,
circleColor: Color = MaterialTheme.colorScheme.surfaceVariant, circleColor: androidx.compose.ui.graphics.Color = MaterialTheme.colorScheme.surfaceVariant,
circleText: String = "", circleText: String = "",
circleTextColor: Color = MaterialTheme.colorScheme.onSurfaceVariant, circleTextColor: androidx.compose.ui.graphics.Color = MaterialTheme.colorScheme.onSurfaceVariant,
containerColor: Color = MaterialTheme.colorScheme.surface, containerColor: androidx.compose.ui.graphics.Color = MaterialTheme.colorScheme.surface,
badge: @Composable (() -> Unit)? = null contentAlpha: Float = 1f,
badge: @Composable (() -> Unit)? = null,
trailing: @Composable (() -> Unit)? = null
) { ) {
val weeklyProgress by viewModel.weeklyProgress(habit.id) val weeklyProgress by viewModel.weeklyProgress(habit.id)
.collectAsState(initial = 0f) .collectAsState(initial = 0f)
Card( Card(
modifier = Modifier onClick = onClick,
.fillMaxWidth() modifier = Modifier.fillMaxWidth(),
.clickable(onClick = onClick),
shape = RoundedCornerShape(16.dp),
elevation = CardDefaults.cardElevation(defaultElevation = 2.dp), elevation = CardDefaults.cardElevation(defaultElevation = 2.dp),
colors = CardDefaults.cardColors(containerColor = containerColor) colors = CardDefaults.cardColors(containerColor = containerColor)
) { ) {
Row( Row(
modifier = Modifier modifier = Modifier.fillMaxWidth().padding(16.dp),
.fillMaxWidth()
.padding(16.dp),
verticalAlignment = Alignment.CenterVertically verticalAlignment = Alignment.CenterVertically
) { ) {
// Status circle
Box( Box(
modifier = Modifier modifier = Modifier.size(44.dp)
.size(44.dp) .background(
.clip(CircleShape) circleColor.copy(alpha = contentAlpha),
.background(circleColor), shape = androidx.compose.foundation.shape.CircleShape
),
contentAlignment = Alignment.Center contentAlignment = Alignment.Center
) { ) {
Text( Text(
@@ -133,7 +117,8 @@ fun HabitCard(
Text( Text(
text = habit.displayName, text = habit.displayName,
style = MaterialTheme.typography.titleMedium, style = MaterialTheme.typography.titleMedium,
fontWeight = FontWeight.SemiBold fontWeight = FontWeight.SemiBold,
color = MaterialTheme.colorScheme.onSurface.copy(alpha = contentAlpha)
) )
if (badge != null) { if (badge != null) {
Spacer(modifier = Modifier.width(8.dp)) Spacer(modifier = Modifier.width(8.dp))
@@ -144,26 +129,20 @@ fun HabitCard(
Text( Text(
text = habit.activityType + " • ${habit.targetFrequency}x/week", text = habit.activityType + " • ${habit.targetFrequency}x/week",
style = MaterialTheme.typography.bodySmall, style = MaterialTheme.typography.bodySmall,
color = MaterialTheme.colorScheme.onSurfaceVariant color = MaterialTheme.colorScheme.onSurfaceVariant.copy(alpha = contentAlpha)
) )
Spacer(modifier = Modifier.height(8.dp)) Spacer(modifier = Modifier.height(4.dp))
LinearProgressIndicator(
progress = { weeklyProgress },
modifier = Modifier
.fillMaxWidth()
.height(6.dp)
.clip(RoundedCornerShape(3.dp)),
color = MaterialTheme.colorScheme.primary,
trackColor = MaterialTheme.colorScheme.surfaceVariant,
)
Spacer(modifier = Modifier.height(2.dp))
Text( Text(
text = "Weekly: ${(weeklyProgress * 100).toInt()}%", text = "Weekly: ${(weeklyProgress * 100).toInt()}%",
style = MaterialTheme.typography.labelSmall, style = MaterialTheme.typography.labelSmall,
color = MaterialTheme.colorScheme.onSurfaceVariant.copy(alpha = 0.7f) color = MaterialTheme.colorScheme.onSurfaceVariant.copy(alpha = 0.7f * contentAlpha)
) )
} }
if (trailing != null) {
Spacer(modifier = Modifier.width(8.dp))
trailing()
}
} }
} }
} }
@@ -1,22 +1,13 @@
package com.example.madwellbeingapp.ui.viewmodel package com.example.madwellbeingapp.ui.viewmodel
import android.Manifest
import android.app.Application import android.app.Application
import android.app.Notification
import android.app.NotificationManager
import android.content.Context
import android.content.pm.PackageManager
import android.os.Build
import android.util.Log
import androidx.lifecycle.AndroidViewModel import androidx.lifecycle.AndroidViewModel
import androidx.lifecycle.viewModelScope import androidx.lifecycle.viewModelScope
import com.example.madwellbeingapp.HabitApp import com.example.madwellbeingapp.HabitApp
import com.example.madwellbeingapp.R
import com.example.madwellbeingapp.data.model.ActivityType import com.example.madwellbeingapp.data.model.ActivityType
import com.example.madwellbeingapp.data.model.Habit import com.example.madwellbeingapp.data.model.Habit
import com.example.madwellbeingapp.data.model.HabitLog import com.example.madwellbeingapp.data.model.HabitLog
import com.example.madwellbeingapp.data.repository.HabitRepository import com.example.madwellbeingapp.data.repository.HabitRepository
import com.example.madwellbeingapp.notification.HabitNotificationScheduler
import kotlinx.coroutines.ExperimentalCoroutinesApi import kotlinx.coroutines.ExperimentalCoroutinesApi
import kotlinx.coroutines.flow.Flow import kotlinx.coroutines.flow.Flow
import kotlinx.coroutines.flow.MutableStateFlow import kotlinx.coroutines.flow.MutableStateFlow
@@ -37,8 +28,6 @@ class HabitViewModel(application: Application) : AndroidViewModel(application) {
(application as HabitApp).repository (application as HabitApp).repository
companion object { companion object {
private const val TAG = "HabitViewModel"
/** /**
* Converts text to title-case: lowercase everything, then uppercase * Converts text to title-case: lowercase everything, then uppercase
* the first letter of each word. Handles parentheses properly so * the first letter of each word. Handles parentheses properly so
@@ -83,22 +72,14 @@ class HabitViewModel(application: Application) : AndroidViewModel(application) {
} }
val existing = repository.findActivityTypeByName(formatted) val existing = repository.findActivityTypeByName(formatted)
if (existing != null) { if (existing != null) {
Log.w(TAG, "ACTIVITY TYPE DUPLICATE: '$formatted' already exists")
onResult(false) onResult(false)
return@launch return@launch
} }
repository.addActivityType(ActivityType(name = formatted)) repository.addActivityType(ActivityType(name = formatted))
Log.i(TAG, "ACTIVITY TYPE CREATED: '$formatted'")
onResult(true) onResult(true)
} }
} }
fun deleteActivityType(activityType: ActivityType) {
viewModelScope.launch {
repository.deleteActivityType(activityType)
Log.i(TAG, "ACTIVITY TYPE DELETED: '${activityType.name}'")
}
}
// ── All habits ────────────────────────────────────────── // ── All habits ──────────────────────────────────────────
val allHabits: StateFlow<List<Habit>> = repository.allHabits val allHabits: StateFlow<List<Habit>> = repository.allHabits
@@ -153,38 +134,40 @@ class HabitViewModel(application: Application) : AndroidViewModel(application) {
fun selectHabit(habitId: Int) { fun selectHabit(habitId: Int) {
_selectedHabitId.value = habitId _selectedHabitId.value = habitId
computeStreaks(habitId)
}
private fun computeStreaks(habitId: Int) {
viewModelScope.launch { viewModelScope.launch {
val logs = repository.getCompletedLogsDesc(habitId) val (current, longest) = computeStreakPair(habitId)
if (logs.isEmpty()) {
_currentStreak.value = 0
_longestStreak.value = 0
return@launch
}
val days = logs.map { normaliseToDay(it.date) }.distinct().sortedDescending()
var current = 0
val today = todayStart
val yesterday = today - 86_400_000L
if (days.first() == today || days.first() == yesterday) {
var expected = days.first()
for (day in days) {
if (day == expected) { current++; expected -= 86_400_000L } else break
}
}
var longest = 1; var streak = 1
for (i in 1 until days.size) {
if (days[i] == days[i - 1] - 86_400_000L) {
streak++; if (streak > longest) longest = streak
} else streak = 1
}
_currentStreak.value = current _currentStreak.value = current
_longestStreak.value = longest _longestStreak.value = longest
} }
} }
/** Returns (currentStreak, longestStreak) for a habit. */
private suspend fun computeStreakPair(habitId: Int): Pair<Int, Int> {
val logs = repository.getCompletedLogsDesc(habitId)
if (logs.isEmpty()) return 0 to 0
val days = logs.map { normaliseToDay(it.date) }.distinct().sortedDescending()
// Current streak
var current = 0
val today = todayStart
if (days.first() == today || days.first() == today - 86_400_000L) {
var expected = days.first()
for (day in days) {
if (day == expected) { current++; expected -= 86_400_000L } else break
}
}
// Longest streak
var longest = 1; var streak = 1
for (i in 1 until days.size) {
if (days[i] == days[i - 1] - 86_400_000L) {
streak++; if (streak > longest) longest = streak
} else streak = 1
}
return current to longest
}
/** Public accessor for calendar/other screens needing just current streak. */
suspend fun computeStreakForHabit(habitId: Int): Int = computeStreakPair(habitId).first
// ── Weekly progress for a habit ───────────────────────── // ── Weekly progress for a habit ─────────────────────────
fun weeklyProgress(habitId: Int): Flow<Float> { fun weeklyProgress(habitId: Int): Flow<Float> {
return repository.getLogsForHabit(habitId).map { logs -> return repository.getLogsForHabit(habitId).map { logs ->
@@ -220,7 +203,6 @@ class HabitViewModel(application: Application) : AndroidViewModel(application) {
val formattedType = toTitleCase(activityType.trim()) val formattedType = toTitleCase(activityType.trim())
if (isDuplicate(formattedName, formattedDetails)) { if (isDuplicate(formattedName, formattedDetails)) {
Log.w(TAG, "DUPLICATE BLOCKED: '$formattedName($formattedDetails)' already exists")
onResult(false) onResult(false)
return@launch return@launch
} }
@@ -235,13 +217,7 @@ class HabitViewModel(application: Application) : AndroidViewModel(application) {
reminderHour = reminderHour, reminderHour = reminderHour,
reminderMinute = reminderMinute reminderMinute = reminderMinute
) )
val id = repository.insertHabit(habit).toInt() repository.insertHabit(habit)
Log.i(TAG, "HABIT CREATED: name='${habit.displayName}', type='$formattedType', frequency=${targetFrequency}x/week, id=$id")
if (reminderEnabled) {
HabitNotificationScheduler.schedule(
getApplication(), id, habit.displayName, reminderHour, reminderMinute
)
}
onResult(true) onResult(true)
} }
} }
@@ -254,80 +230,35 @@ class HabitViewModel(application: Application) : AndroidViewModel(application) {
activityType = toTitleCase(habit.activityType.trim()) activityType = toTitleCase(habit.activityType.trim())
) )
repository.updateHabit(updated) repository.updateHabit(updated)
Log.i(TAG, "HABIT UPDATED: name='${updated.displayName}', id=${updated.id}, type='${updated.activityType}', frequency=${updated.targetFrequency}x/week")
if (updated.reminderEnabled) {
HabitNotificationScheduler.schedule(
getApplication(), updated.id, updated.displayName,
updated.reminderHour, updated.reminderMinute
)
} else {
HabitNotificationScheduler.cancel(getApplication(), updated.id)
}
} }
} }
fun deleteHabit(habit: Habit) { fun disableHabit(habit: Habit) {
viewModelScope.launch { viewModelScope.launch {
HabitNotificationScheduler.cancel(getApplication(), habit.id) val updated = habit.copy(isActive = false)
repository.deleteHabit(habit) repository.updateHabit(updated)
Log.i(TAG, "HABIT DELETED: name='${habit.displayName}', id=${habit.id}") }
}
fun enableHabit(habit: Habit) {
viewModelScope.launch {
val updated = habit.copy(isActive = true)
repository.updateHabit(updated)
} }
} }
// ── Daily logging ─────────────────────────────────────── // ── Daily logging ───────────────────────────────────────
fun toggleTodayLog(habitId: Int) { fun toggleTodayLog(habitId: Int) {
viewModelScope.launch { viewModelScope.launch {
val existing = repository.getLogForDate(habitId, todayStart)
val habit = repository.getHabitByIdOnce(habitId)
repository.toggleLog(habitId, todayStart) repository.toggleLog(habitId, todayStart)
if (existing == null) { if (_selectedHabitId.value == habitId) {
Log.i(TAG, "HABIT COMPLETED: habit='${habit?.displayName}' (id=$habitId), date=$todayStart") val (c, l) = computeStreakPair(habitId)
} else { _currentStreak.value = c
Log.i(TAG, "HABIT UNCOMPLETION: habit='${habit?.displayName}' (id=$habitId), date=$todayStart") _longestStreak.value = l
} }
if (_selectedHabitId.value == habitId) computeStreaks(habitId)
checkStreakCelebration(habitId)
} }
} }
private suspend fun checkStreakCelebration(habitId: Int) {
val logs = repository.getCompletedLogsDesc(habitId)
if (logs.isEmpty()) return
val days = logs.map { normaliseToDay(it.date) }.distinct().sortedDescending()
if (days.first() != todayStart) return
var streak = 0; var expected = todayStart
for (day in days) {
if (day == expected) { streak++; expected -= 86_400_000L } else break
}
if (streak > 0 && streak % 7 == 0) sendCelebration(habitId, streak)
}
private suspend fun sendCelebration(habitId: Int, streak: Int) {
val habit = repository.getHabitByIdOnce(habitId) ?: return
val ctx = getApplication<HabitApp>()
Log.i(TAG, "STREAK MILESTONE: habit='${habit.displayName}', streak=$streak days!")
val notification = if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
Notification.Builder(ctx, HabitApp.CHANNEL_ID)
.setSmallIcon(R.drawable.ic_launcher_foreground)
.setContentTitle("Streak Milestone!")
.setContentText("$streak-day streak on \"${habit.displayName}\"!")
.setAutoCancel(true).build()
} else {
@Suppress("DEPRECATION")
Notification.Builder(ctx)
.setSmallIcon(R.drawable.ic_launcher_foreground)
.setContentTitle("Streak Milestone!")
.setContentText("$streak-day streak on \"${habit.displayName}\"!")
.setAutoCancel(true).build()
}
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.TIRAMISU) {
if (ctx.checkSelfPermission(Manifest.permission.POST_NOTIFICATIONS)
!= PackageManager.PERMISSION_GRANTED) return
}
val manager = ctx.getSystemService(Context.NOTIFICATION_SERVICE) as NotificationManager
manager.notify(habitId + 10_000, notification)
}
// ── Helpers ────────────────────────────────────────────── // ── Helpers ──────────────────────────────────────────────
private fun normaliseToDay(millis: Long): Long { private fun normaliseToDay(millis: Long): Long {
val cal = Calendar.getInstance() val cal = Calendar.getInstance()
@@ -336,4 +267,8 @@ class HabitViewModel(application: Application) : AndroidViewModel(application) {
cal.set(Calendar.SECOND, 0); cal.set(Calendar.MILLISECOND, 0) cal.set(Calendar.SECOND, 0); cal.set(Calendar.MILLISECOND, 0)
return cal.timeInMillis return cal.timeInMillis
} }
// ── Calendar support ────────────────────────────────────
fun getLogsBetween(startDate: Long, endDate: Long): Flow<List<HabitLog>> =
repository.getLogsBetween(startDate, endDate)
} }
+3
View File
@@ -12,6 +12,7 @@ room = "2.7.1"
lifecycleViewmodelCompose = "2.6.1" lifecycleViewmodelCompose = "2.6.1"
ksp = "2.3.2" ksp = "2.3.2"
coreKtxVersion = "1.17.0" coreKtxVersion = "1.17.0"
navigation3 = "1.0.0"
[libraries] [libraries]
androidx-core-ktx = { group = "androidx.core", name = "core-ktx", version.ref = "coreKtx" } androidx-core-ktx = { group = "androidx.core", name = "core-ktx", version.ref = "coreKtx" }
@@ -33,6 +34,8 @@ androidx-room-ktx = { group = "androidx.room", name = "room-ktx", version.ref =
androidx-room-compiler = { group = "androidx.room", name = "room-compiler", version.ref = "room" } androidx-room-compiler = { group = "androidx.room", name = "room-compiler", version.ref = "room" }
androidx-lifecycle-viewmodel-compose = { group = "androidx.lifecycle", name = "lifecycle-viewmodel-compose", version.ref = "lifecycleViewmodelCompose" } androidx-lifecycle-viewmodel-compose = { group = "androidx.lifecycle", name = "lifecycle-viewmodel-compose", version.ref = "lifecycleViewmodelCompose" }
core-ktx = { group = "androidx.core", name = "core-ktx", version.ref = "coreKtxVersion" } core-ktx = { group = "androidx.core", name = "core-ktx", version.ref = "coreKtxVersion" }
androidx-navigation3 = { group = "androidx.navigation3", name = "navigation3-runtime", version.ref = "navigation3" }
androidx-navigation3-ui = { group = "androidx.navigation3", name = "navigation3-ui", version.ref = "navigation3" }
[plugins] [plugins]
android-application = { id = "com.android.application", version.ref = "agp" } android-application = { id = "com.android.application", version.ref = "agp" }
Vendored Regular → Executable
View File
File mode changed.