Add activity type management and enhance habit tracking features

- Introduced ActivityType model and DAO for user-created activity types
- Updated Habit and HabitRepository to support activity types
- Enhanced HabitReminderReceiver to use native Notification.Builder
- Implemented LandingScreen and AllActivitiesScreen for improved navigation
- Refactored Gradle settings and dependencies for compatibility
This commit is contained in:
bobbert committed 2026-03-02 20:36:33 +00:00
1 parent 67a0579066
commit 7061cf00cc
29 files changed
+1854 -422

No files matched your search

Generated
+1
View File
@@ -0,0 +1 @@
Mad Wellbeing App
+27
View File
@@ -0,0 +1,27 @@
<?xml version="1.0" encoding="UTF-8"?>
<project version="4">
<component name="AppInsightsSettings">
<option name="selectedTabId" value="Firebase Crashlytics" />
<option name="tabSettings">
<map>
<entry key="Firebase Crashlytics">
<value>
<InsightsFilterSettings>
<option name="connection">
<ConnectionSetting>
<option name="appId" value="PLACEHOLDER" />
<option name="mobileSdkAppId" value="" />
<option name="projectId" value="" />
<option name="projectNumber" value="" />
</ConnectionSetting>
</option>
<option name="signal" value="SIGNAL_UNSPECIFIED" />
<option name="timeIntervalDays" value="THIRTY_DAYS" />
<option name="visibilityType" value="ALL" />
</InsightsFilterSettings>
</value>
</entry>
</map>
</option>
</component>
</project>
+6
View File
@@ -0,0 +1,6 @@
<?xml version="1.0" encoding="UTF-8"?>
<project version="4">
<component name="CompilerConfiguration">
<bytecodeTargetLevel target="21" />
</component>
</project>
+6
View File
@@ -0,0 +1,6 @@
<?xml version="1.0" encoding="UTF-8"?>
<project version="4">
<component name="Ask2AgentMigrationStateService">
<option name="migrationStatus" value="COMPLETED" />
</component>
</project>
+13
View File
@@ -0,0 +1,13 @@
<?xml version="1.0" encoding="UTF-8"?>
<project version="4">
<component name="DeviceTable">
<option name="columnSorters">
<list>
<ColumnSorterState>
<option name="column" value="Name" />
<option name="order" value="ASCENDING" />
</ColumnSorterState>
</list>
</option>
</component>
</project>
+18
View File
@@ -0,0 +1,18 @@
<?xml version="1.0" encoding="UTF-8"?>
<project version="4">
<component name="GradleMigrationSettings" migrationVersion="1" />
<component name="GradleSettings">
<option name="linkedExternalProjectsSettings">
<GradleProjectSettings>
<option name="testRunner" value="CHOOSE_PER_TEST" />
<option name="externalProjectPath" value="$PROJECT_DIR$" />
<option name="modules">
<set>
<option value="$PROJECT_DIR$" />
<option value="$PROJECT_DIR$/app" />
</set>
</option>
</GradleProjectSettings>
</option>
</component>
</project>
-2
View File
@@ -56,8 +56,6 @@ dependencies {
implementation(libs.core.ktx) implementation(libs.core.ktx)
ksp(libs.androidx.room.compiler) ksp(libs.androidx.room.compiler)
// Navigation Compose
implementation(libs.androidx.navigation.compose)
// ViewModel Compose // ViewModel Compose
implementation(libs.androidx.lifecycle.viewmodel.compose) implementation(libs.androidx.lifecycle.viewmodel.compose)
@@ -0,0 +1,24 @@
package com.example.madwellbeingapp
import androidx.test.platform.app.InstrumentationRegistry
import androidx.test.ext.junit.runners.AndroidJUnit4
import org.junit.Test
import org.junit.runner.RunWith
import org.junit.Assert.*
/**
* Instrumented test, which will execute on an Android device.
*
* See [testing documentation](http://d.android.com/tools/testing).
*/
@RunWith(AndroidJUnit4::class)
class ExampleInstrumentedTest {
@Test
fun useAppContext() {
// Context of the app under test.
val appContext = InstrumentationRegistry.getInstrumentation().targetContext
assertEquals("com.example.madwellbeingapp", appContext.packageName)
}
}
@@ -14,7 +14,7 @@ class HabitApp : Application() {
val database by lazy { HabitDatabase.getDatabase(this) } val database by lazy { HabitDatabase.getDatabase(this) }
val repository by lazy { val repository by lazy {
HabitRepository(database.habitDao(), database.habitLogDao()) HabitRepository(database.habitDao(), database.habitLogDao(), database.activityTypeDao())
} }
override fun onCreate() { override fun onCreate() {
@@ -11,16 +11,15 @@ 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.core.content.ContextCompat import androidx.compose.runtime.mutableStateListOf
import androidx.compose.runtime.remember
import androidx.lifecycle.viewmodel.compose.viewModel import androidx.lifecycle.viewmodel.compose.viewModel
import androidx.navigation.NavType import com.example.madwellbeingapp.ui.screens.ActiveOnlyScreen
import androidx.navigation.compose.NavHost
import androidx.navigation.compose.composable
import androidx.navigation.compose.rememberNavController
import androidx.navigation.navArgument
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.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.theme.MadWellbeingAppTheme import com.example.madwellbeingapp.ui.theme.MadWellbeingAppTheme
import com.example.madwellbeingapp.ui.viewmodel.HabitViewModel import com.example.madwellbeingapp.ui.viewmodel.HabitViewModel
@@ -35,7 +34,7 @@ class MainActivity : ComponentActivity() {
// Request notification permission on Android 13+ // Request notification permission on Android 13+
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.TIRAMISU) { if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.TIRAMISU) {
if (ContextCompat.checkSelfPermission(this, Manifest.permission.POST_NOTIFICATIONS) if (checkSelfPermission(Manifest.permission.POST_NOTIFICATIONS)
!= PackageManager.PERMISSION_GRANTED != PackageManager.PERMISSION_GRANTED
) { ) {
notificationPermissionLauncher.launch(Manifest.permission.POST_NOTIFICATIONS) notificationPermissionLauncher.launch(Manifest.permission.POST_NOTIFICATIONS)
@@ -50,55 +49,100 @@ class MainActivity : ComponentActivity() {
} }
} }
/**
* Simple sealed class representing each screen destination.
* We avoid using Navigation Compose library and use manual state-based navigation.
*/
sealed class Screen {
/** Landing page with 3 navigation buttons — first page the user sees. */
data object Landing : Screen()
/** All activities — past completed + currently active. */
data object AllActivities : Screen()
/** Manage activities — add new habits, swipe to complete. */
data object Home : Screen()
/** Active only — habits still to-do today. */
data object ActiveOnly : Screen()
data object AddHabit : Screen()
data class EditHabit(val habitId: Int) : Screen()
data class HabitDetail(val habitId: Int) : Screen()
}
@Composable @Composable
fun HabitNavGraph(viewModel: HabitViewModel = viewModel()) { fun HabitNavGraph(viewModel: HabitViewModel = viewModel()) {
val navController = rememberNavController() // Manual back-stack — starts on the Landing screen
val backStack = remember { mutableStateListOf<Screen>(Screen.Landing) }
val currentScreen = backStack.last()
NavHost(navController = navController, startDestination = "home") { fun navigateTo(screen: Screen) {
backStack.add(screen)
}
composable("home") { fun navigateBack() {
HomeScreen( if (backStack.size > 1) {
viewModel = viewModel, backStack.removeAt(backStack.lastIndex)
onAddHabit = { navController.navigate("add_habit") }, }
onHabitClick = { id -> navController.navigate("habit_detail/$id") } }
when (currentScreen) {
is Screen.Landing -> {
LandingScreen(
onAllActivities = { navigateTo(Screen.AllActivities) },
onManageActivities = { navigateTo(Screen.Home) },
onActiveOnly = { navigateTo(Screen.ActiveOnly) }
) )
} }
composable("add_habit") { 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( AddEditHabitScreen(
viewModel = viewModel, viewModel = viewModel,
existingHabit = null, existingHabit = null,
onNavigateBack = { navController.popBackStack() } onNavigateBack = { navigateBack() }
) )
} }
composable( is Screen.EditHabit -> {
route = "edit_habit/{habitId}",
arguments = listOf(navArgument("habitId") { type = NavType.IntType })
) { backStackEntry ->
val habitId = backStackEntry.arguments?.getInt("habitId") ?: return@composable
// Observe the habit so the form is pre-populated
val allHabits by viewModel.allHabits.collectAsState() val allHabits by viewModel.allHabits.collectAsState()
val habit = allHabits.find { it.id == habitId } val habit = allHabits.find { it.id == currentScreen.habitId }
if (habit != null) { if (habit != null) {
AddEditHabitScreen( AddEditHabitScreen(
viewModel = viewModel, viewModel = viewModel,
existingHabit = habit, existingHabit = habit,
onNavigateBack = { navController.popBackStack() } onNavigateBack = { navigateBack() }
) )
} }
} }
composable( is Screen.HabitDetail -> {
route = "habit_detail/{habitId}",
arguments = listOf(navArgument("habitId") { type = NavType.IntType })
) { backStackEntry ->
val habitId = backStackEntry.arguments?.getInt("habitId") ?: return@composable
HabitDetailScreen( HabitDetailScreen(
habitId = habitId, habitId = currentScreen.habitId,
viewModel = viewModel, viewModel = viewModel,
onNavigateBack = { navController.popBackStack() }, onNavigateBack = { navigateBack() },
onEditHabit = { id -> navController.navigate("edit_habit/$id") } onEditHabit = { id -> navigateTo(Screen.EditHabit(id)) }
) )
} }
} }
@@ -1,18 +1,7 @@
package com.example.madwellbeingapp.data package com.example.madwellbeingapp.data
import androidx.room.TypeConverter /**
import com.example.madwellbeingapp.data.model.HabitCategory * Room type converters. Currently empty since HabitCategory enum was removed.
* Kept in case future types need conversion.
class Converters { */
class Converters
@TypeConverter
fun fromCategory(category: HabitCategory): String {
return category.name
}
@TypeConverter
fun toCategory(value: String): HabitCategory {
return HabitCategory.valueOf(value)
}
}
@@ -4,18 +4,23 @@ import android.content.Context
import androidx.room.Database import androidx.room.Database
import androidx.room.Room import androidx.room.Room
import androidx.room.RoomDatabase import androidx.room.RoomDatabase
import androidx.room.TypeConverters import com.example.madwellbeingapp.data.dao.ActivityTypeDao
import com.example.madwellbeingapp.data.dao.HabitDao import com.example.madwellbeingapp.data.dao.HabitDao
import com.example.madwellbeingapp.data.dao.HabitLogDao import com.example.madwellbeingapp.data.dao.HabitLogDao
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
@Database(entities = [Habit::class, HabitLog::class], version = 1, exportSchema = false) @Database(
@TypeConverters(Converters::class) entities = [Habit::class, HabitLog::class, ActivityType::class],
version = 3,
exportSchema = false
)
abstract class HabitDatabase : RoomDatabase() { abstract class HabitDatabase : RoomDatabase() {
abstract fun habitDao(): HabitDao abstract fun habitDao(): HabitDao
abstract fun habitLogDao(): HabitLogDao abstract fun habitLogDao(): HabitLogDao
abstract fun activityTypeDao(): ActivityTypeDao
companion object { companion object {
@Volatile @Volatile
@@ -27,11 +32,12 @@ abstract class HabitDatabase : RoomDatabase() {
context.applicationContext, context.applicationContext,
HabitDatabase::class.java, HabitDatabase::class.java,
"habit_database" "habit_database"
).build() )
.fallbackToDestructiveMigration(true)
.build()
INSTANCE = instance INSTANCE = instance
instance instance
} }
} }
} }
} }
@@ -0,0 +1,26 @@
package com.example.madwellbeingapp.data.dao
import androidx.room.Dao
import androidx.room.Delete
import androidx.room.Query
import androidx.room.Upsert
import com.example.madwellbeingapp.data.model.ActivityType
import kotlinx.coroutines.flow.Flow
@Dao
interface ActivityTypeDao {
@Upsert
suspend fun upsert(activityType: ActivityType): Long
@Delete
suspend fun delete(activityType: ActivityType): Int
@Query("SELECT * FROM activity_types ORDER BY name ASC")
fun getAll(): Flow<List<ActivityType>>
/** Check if an activity type with this name already exists (case-insensitive). */
@Query("SELECT * FROM activity_types WHERE LOWER(name) = LOWER(:name) LIMIT 1")
suspend fun findByName(name: String): ActivityType?
}
@@ -2,21 +2,16 @@ package com.example.madwellbeingapp.data.dao
import androidx.room.Dao import androidx.room.Dao
import androidx.room.Delete import androidx.room.Delete
import androidx.room.Insert
import androidx.room.OnConflictStrategy
import androidx.room.Query import androidx.room.Query
import androidx.room.Update import androidx.room.Upsert
import com.example.madwellbeingapp.data.model.Habit import com.example.madwellbeingapp.data.model.Habit
import kotlinx.coroutines.flow.Flow import kotlinx.coroutines.flow.Flow
@Dao @Dao
interface HabitDao { interface HabitDao {
@Insert(onConflict = OnConflictStrategy.REPLACE) @Upsert
suspend fun insert(habit: Habit): Long suspend fun upsert(habit: Habit): Long
@Update
suspend fun update(habit: Habit): Int
@Delete @Delete
suspend fun delete(habit: Habit): Int suspend fun delete(habit: Habit): Int
@@ -29,4 +24,8 @@ interface HabitDao {
@Query("SELECT * FROM habits WHERE id = :id") @Query("SELECT * FROM habits WHERE id = :id")
suspend fun getHabitByIdOnce(id: Int): Habit? suspend fun getHabitByIdOnce(id: Int): Habit?
/** Check if a habit with the same name+details already exists (case-insensitive). */
@Query("SELECT * FROM habits WHERE LOWER(name) = LOWER(:name) AND LOWER(details) = LOWER(:details) LIMIT 1")
suspend fun findDuplicate(name: String, details: String): Habit?
} }
@@ -1,17 +1,16 @@
package com.example.madwellbeingapp.data.dao package com.example.madwellbeingapp.data.dao
import androidx.room.Dao import androidx.room.Dao
import androidx.room.Insert
import androidx.room.OnConflictStrategy
import androidx.room.Query import androidx.room.Query
import androidx.room.Upsert
import com.example.madwellbeingapp.data.model.HabitLog import com.example.madwellbeingapp.data.model.HabitLog
import kotlinx.coroutines.flow.Flow import kotlinx.coroutines.flow.Flow
@Dao @Dao
interface HabitLogDao { interface HabitLogDao {
@Insert(onConflict = OnConflictStrategy.REPLACE) @Upsert
suspend fun insert(log: HabitLog): Long suspend fun upsert(log: HabitLog): Long
@Query("SELECT * FROM habit_logs WHERE habitId = :habitId ORDER BY date DESC") @Query("SELECT * FROM habit_logs WHERE habitId = :habitId ORDER BY date DESC")
fun getLogsForHabit(habitId: Int): Flow<List<HabitLog>> fun getLogsForHabit(habitId: Int): Flow<List<HabitLog>>
@@ -0,0 +1,15 @@
package com.example.madwellbeingapp.data.model
import androidx.room.Entity
import androidx.room.PrimaryKey
/**
* A user-created activity type (e.g. "Gym", "Running", "Yoga").
* These populate the dropdown when creating a new habit.
*/
@Entity(tableName = "activity_types")
data class ActivityType(
@PrimaryKey(autoGenerate = true) val id: Int = 0,
val name: String
)
@@ -5,23 +5,24 @@ import androidx.room.PrimaryKey
/** /**
* Represents a habit tracked by the user. * Represents a habit tracked by the user.
* [name] is the activity type name chosen from the user-created dropdown (e.g. "Gym").
* [details] is optional extra info typed by the user (e.g. "Legs", "5K").
* The display name combines them: "Gym(Legs)" when details is present, or just "Gym".
*/ */
@Entity(tableName = "habits") @Entity(tableName = "habits")
data class Habit( data class Habit(
@PrimaryKey(autoGenerate = true) val id: Int = 0, @PrimaryKey(autoGenerate = true) val id: Int = 0,
val name: String, val name: String,
val category: HabitCategory, val details: String = "",
val activityType: String = "", // the user-created activity type name
val startDate: Long, // epoch millis – auto-set on creation val startDate: Long, // epoch millis – auto-set on creation
val targetFrequency: Int, // times per week the user wants to complete this habit val targetFrequency: Int, // times per week the user wants to complete this habit
val reminderEnabled: Boolean = true, val reminderEnabled: Boolean = true,
val reminderHour: Int = 9, // default 09:00 val reminderHour: Int = 9, // default 09:00
val reminderMinute: Int = 0 val reminderMinute: Int = 0,
) val isActive: Boolean = true
) {
enum class HabitCategory(val displayName: String) { /** Returns the formatted display name: "Name(Details)" or just "Name". */
HEALTH("Health"), val displayName: String
STUDY("Study"), get() = if (details.isBlank()) name else "$name($details)"
FITNESS("Fitness"),
WELLBEING("Wellbeing")
} }
@@ -1,18 +1,21 @@
package com.example.madwellbeingapp.data.repository package com.example.madwellbeingapp.data.repository
import com.example.madwellbeingapp.data.dao.ActivityTypeDao
import com.example.madwellbeingapp.data.dao.HabitDao import com.example.madwellbeingapp.data.dao.HabitDao
import com.example.madwellbeingapp.data.dao.HabitLogDao import com.example.madwellbeingapp.data.dao.HabitLogDao
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 kotlinx.coroutines.flow.Flow import kotlinx.coroutines.flow.Flow
/** /**
* Single source of truth for habit and log data. * Single source of truth for habit, log, and activity-type data.
* Abstracts the data sources away from the ViewModels. * Abstracts the data sources away from the ViewModels.
*/ */
class HabitRepository( class HabitRepository(
private val habitDao: HabitDao, private val habitDao: HabitDao,
private val habitLogDao: HabitLogDao private val habitLogDao: HabitLogDao,
private val activityTypeDao: ActivityTypeDao
) { ) {
// ── Habits ────────────────────────────────────────────── // ── Habits ──────────────────────────────────────────────
val allHabits: Flow<List<Habit>> = habitDao.getAllHabits() val allHabits: Flow<List<Habit>> = habitDao.getAllHabits()
@@ -21,12 +24,28 @@ class HabitRepository(
suspend fun getHabitByIdOnce(id: Int): Habit? = habitDao.getHabitByIdOnce(id) suspend fun getHabitByIdOnce(id: Int): Habit? = habitDao.getHabitByIdOnce(id)
suspend fun insertHabit(habit: Habit): Long = habitDao.insert(habit) suspend fun insertHabit(habit: Habit): Long = habitDao.upsert(habit)
suspend fun updateHabit(habit: Habit) = habitDao.update(habit) suspend fun updateHabit(habit: Habit) = habitDao.upsert(habit)
suspend fun deleteHabit(habit: Habit) = habitDao.delete(habit) suspend fun deleteHabit(habit: Habit) = habitDao.delete(habit)
/** Returns an existing habit with the same name+details (case-insensitive), or null. */
suspend fun findDuplicate(name: String, details: String): Habit? =
habitDao.findDuplicate(name, details)
// ── Activity Types ──────────────────────────────────────
val allActivityTypes: Flow<List<ActivityType>> = activityTypeDao.getAll()
suspend fun addActivityType(activityType: ActivityType): Long =
activityTypeDao.upsert(activityType)
suspend fun deleteActivityType(activityType: ActivityType) =
activityTypeDao.delete(activityType)
suspend fun findActivityTypeByName(name: String): ActivityType? =
activityTypeDao.findByName(name)
// ── Logs ──────────────────────────────────────────────── // ── Logs ────────────────────────────────────────────────
fun getLogsForHabit(habitId: Int): Flow<List<HabitLog>> = fun getLogsForHabit(habitId: Int): Flow<List<HabitLog>> =
habitLogDao.getLogsForHabit(habitId) habitLogDao.getLogsForHabit(habitId)
@@ -42,7 +61,7 @@ class HabitRepository(
if (existing != null) { if (existing != null) {
habitLogDao.deleteLogForDate(habitId, date) habitLogDao.deleteLogForDate(habitId, date)
} else { } else {
habitLogDao.insert(HabitLog(habitId = habitId, date = date, completed = true)) habitLogDao.upsert(HabitLog(habitId = habitId, date = date, completed = true))
} }
} }
@@ -52,4 +71,3 @@ class HabitRepository(
suspend fun getCompletedLogsDesc(habitId: Int): List<HabitLog> = suspend fun getCompletedLogsDesc(habitId: Int): List<HabitLog> =
habitLogDao.getCompletedLogsDesc(habitId) habitLogDao.getCompletedLogsDesc(habitId)
} }
@@ -1,20 +1,22 @@
package com.example.madwellbeingapp.notification package com.example.madwellbeingapp.notification
import android.Manifest import android.Manifest
import android.app.Notification
import android.app.NotificationManager
import android.app.PendingIntent import android.app.PendingIntent
import android.content.BroadcastReceiver import android.content.BroadcastReceiver
import android.content.Context import android.content.Context
import android.content.Intent import android.content.Intent
import android.content.pm.PackageManager import android.content.pm.PackageManager
import androidx.core.app.NotificationCompat import android.os.Build
import androidx.core.app.NotificationManagerCompat import android.util.Log
import androidx.core.content.ContextCompat
import com.example.madwellbeingapp.HabitApp import com.example.madwellbeingapp.HabitApp
import com.example.madwellbeingapp.MainActivity import com.example.madwellbeingapp.MainActivity
import com.example.madwellbeingapp.R import com.example.madwellbeingapp.R
/** /**
* Receives the alarm broadcast and posts a notification for the habit. * Receives the alarm broadcast and posts a notification for the habit.
* Uses native android.app.Notification.Builder instead of NotificationCompat.
*/ */
class HabitReminderReceiver : BroadcastReceiver() { class HabitReminderReceiver : BroadcastReceiver() {
@@ -22,6 +24,8 @@ class HabitReminderReceiver : BroadcastReceiver() {
val habitId = intent.getIntExtra("habit_id", -1) val habitId = intent.getIntExtra("habit_id", -1)
val habitName = intent.getStringExtra("habit_name") ?: "your habit" val habitName = intent.getStringExtra("habit_name") ?: "your habit"
Log.d("HabitReminder", "Reminder fired for habit '$habitName' (id=$habitId)")
// Tap notification → open app // Tap notification → open app
val tapIntent = Intent(context, MainActivity::class.java).apply { val tapIntent = Intent(context, MainActivity::class.java).apply {
flags = Intent.FLAG_ACTIVITY_NEW_TASK or Intent.FLAG_ACTIVITY_CLEAR_TASK flags = Intent.FLAG_ACTIVITY_NEW_TASK or Intent.FLAG_ACTIVITY_CLEAR_TASK
@@ -31,20 +35,35 @@ class HabitReminderReceiver : BroadcastReceiver() {
PendingIntent.FLAG_UPDATE_CURRENT or PendingIntent.FLAG_IMMUTABLE PendingIntent.FLAG_UPDATE_CURRENT or PendingIntent.FLAG_IMMUTABLE
) )
val notification = NotificationCompat.Builder(context, HabitApp.CHANNEL_ID) val notification = if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
Notification.Builder(context, HabitApp.CHANNEL_ID)
.setSmallIcon(R.drawable.ic_launcher_foreground) .setSmallIcon(R.drawable.ic_launcher_foreground)
.setContentTitle("Habit Reminder 🔔") .setContentTitle("Habit Reminder")
.setContentText("Time to work on \"$habitName\"!")
.setContentIntent(tapPending)
.setAutoCancel(true)
.build()
} else {
@Suppress("DEPRECATION")
Notification.Builder(context)
.setSmallIcon(R.drawable.ic_launcher_foreground)
.setContentTitle("Habit Reminder")
.setContentText("Time to work on \"$habitName\"!") .setContentText("Time to work on \"$habitName\"!")
.setPriority(NotificationCompat.PRIORITY_DEFAULT)
.setContentIntent(tapPending) .setContentIntent(tapPending)
.setAutoCancel(true) .setAutoCancel(true)
.build() .build()
if (ContextCompat.checkSelfPermission(context, Manifest.permission.POST_NOTIFICATIONS)
== PackageManager.PERMISSION_GRANTED
) {
NotificationManagerCompat.from(context).notify(habitId, notification)
} }
// Check permission on Android 13+
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.TIRAMISU) {
if (context.checkSelfPermission(Manifest.permission.POST_NOTIFICATIONS)
!= PackageManager.PERMISSION_GRANTED
) {
return
}
}
val manager = context.getSystemService(Context.NOTIFICATION_SERVICE) as NotificationManager
manager.notify(habitId, notification)
} }
} }
@@ -0,0 +1,198 @@
package com.example.madwellbeingapp.ui.screens
import androidx.compose.foundation.background
import androidx.compose.foundation.clickable
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.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.foundation.shape.CircleShape
import androidx.compose.foundation.shape.RoundedCornerShape
import androidx.compose.material3.Card
import androidx.compose.material3.CardDefaults
import androidx.compose.material3.LinearProgressIndicator
import androidx.compose.material3.MaterialTheme
import androidx.compose.material3.Scaffold
import androidx.compose.material3.Text
import androidx.compose.runtime.Composable
import androidx.compose.runtime.collectAsState
import androidx.compose.runtime.getValue
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.draw.clip
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
/**
* Shows only habits that are still active and NOT yet completed today.
* These are the ones the user still needs to do.
*/
@Composable
fun ActiveOnlyScreen(
viewModel: HabitViewModel,
onNavigateBack: () -> Unit,
onHabitClick: (Int) -> Unit
) {
val activeHabits by viewModel.activeHabitsNotCompletedToday.collectAsState()
Scaffold { padding ->
Column(
modifier = Modifier
.fillMaxSize()
.padding(padding)
) {
// Header
Box(
modifier = Modifier
.fillMaxWidth()
.background(MaterialTheme.colorScheme.tertiary)
.padding(horizontal = 16.dp, vertical = 16.dp)
) {
Row(
modifier = Modifier.fillMaxWidth(),
verticalAlignment = Alignment.CenterVertically
) {
Text(
text = "←",
modifier = Modifier
.clickable(onClick = onNavigateBack)
.padding(end = 16.dp),
style = MaterialTheme.typography.titleLarge,
color = MaterialTheme.colorScheme.onTertiary,
fontWeight = FontWeight.Bold
)
Text(
text = "Active — To Do",
style = MaterialTheme.typography.titleLarge,
color = MaterialTheme.colorScheme.onTertiary,
fontWeight = FontWeight.Bold
)
}
}
if (activeHabits.isEmpty()) {
Box(
modifier = Modifier
.fillMaxSize()
.padding(32.dp),
contentAlignment = Alignment.Center
) {
Column(horizontalAlignment = Alignment.CenterHorizontally) {
Text(
text = "All caught up!",
style = MaterialTheme.typography.titleMedium,
color = MaterialTheme.colorScheme.primary,
fontWeight = FontWeight.Bold
)
Spacer(modifier = Modifier.height(8.dp))
Text(
text = "You've completed all your active habits for today.",
style = MaterialTheme.typography.bodyMedium,
color = MaterialTheme.colorScheme.onSurfaceVariant
)
}
}
} else {
LazyColumn(
modifier = Modifier
.fillMaxSize()
.padding(horizontal = 16.dp, vertical = 12.dp),
verticalArrangement = Arrangement.spacedBy(10.dp)
) {
items(activeHabits, key = { it.id }) { habit ->
ActiveHabitCard(
habit = habit,
onClick = { onHabitClick(habit.id) },
viewModel = viewModel
)
}
}
}
}
}
}
@Composable
private fun ActiveHabitCard(
habit: Habit,
onClick: () -> Unit,
viewModel: HabitViewModel
) {
val weeklyProgress by viewModel.weeklyProgress(habit.id)
.collectAsState(initial = 0f)
Card(
modifier = Modifier
.fillMaxWidth()
.clickable(onClick = onClick),
shape = RoundedCornerShape(16.dp),
elevation = CardDefaults.cardElevation(defaultElevation = 2.dp),
colors = CardDefaults.cardColors(containerColor = MaterialTheme.colorScheme.surface)
) {
Row(
modifier = Modifier
.fillMaxWidth()
.padding(16.dp),
verticalAlignment = Alignment.CenterVertically
) {
Box(
modifier = Modifier
.size(44.dp)
.clip(CircleShape)
.background(MaterialTheme.colorScheme.surfaceVariant),
contentAlignment = Alignment.Center
) {
// First letter of activity type
Text(
text = if (habit.activityType.isNotBlank()) habit.activityType.first().toString() else "•",
style = MaterialTheme.typography.titleMedium,
fontWeight = FontWeight.Bold,
color = MaterialTheme.colorScheme.primary
)
}
Spacer(modifier = Modifier.width(14.dp))
Column(modifier = Modifier.weight(1f)) {
Text(
text = habit.displayName,
style = MaterialTheme.typography.titleMedium,
fontWeight = FontWeight.SemiBold
)
Spacer(modifier = Modifier.height(2.dp))
Text(
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))
Text(
text = "Weekly: ${(weeklyProgress * 100).toInt()}%",
style = MaterialTheme.typography.labelSmall,
color = MaterialTheme.colorScheme.onSurfaceVariant.copy(alpha = 0.7f)
)
}
}
}
}
@@ -1,6 +1,12 @@
package com.example.madwellbeingapp.ui.screens package com.example.madwellbeingapp.ui.screens
import android.util.Log
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
@@ -8,149 +14,396 @@ 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.padding 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.foundation.rememberScrollState import androidx.compose.foundation.rememberScrollState
import androidx.compose.foundation.shape.CircleShape
import androidx.compose.foundation.shape.RoundedCornerShape 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.material.icons.Icons import androidx.compose.material3.AlertDialog
import androidx.compose.material.icons.automirrored.filled.ArrowBack
import androidx.compose.material3.Button import androidx.compose.material3.Button
import androidx.compose.material3.DropdownMenuItem import androidx.compose.material3.ButtonDefaults
import androidx.compose.material3.ExperimentalMaterial3Api import androidx.compose.material3.Card
import androidx.compose.material3.ExposedDropdownMenuBox import androidx.compose.material3.CardDefaults
import androidx.compose.material3.ExposedDropdownMenuDefaults
import androidx.compose.material3.Icon
import androidx.compose.material3.IconButton
import androidx.compose.material3.MaterialTheme import androidx.compose.material3.MaterialTheme
import androidx.compose.material3.OutlinedTextField import androidx.compose.material3.OutlinedTextField
import androidx.compose.material3.Scaffold import androidx.compose.material3.Scaffold
import androidx.compose.material3.Switch
import androidx.compose.material3.Text import androidx.compose.material3.Text
import androidx.compose.material3.TopAppBar import androidx.compose.material3.TextButton
import androidx.compose.material3.TopAppBarDefaults
import androidx.compose.runtime.Composable import androidx.compose.runtime.Composable
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.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.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.data.model.HabitCategory
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.
* When [existingHabit] is provided the form is pre-filled for editing. *
* - 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.
*/ */
@OptIn(ExperimentalMaterial3Api::class)
@Composable @Composable
fun AddEditHabitScreen( fun AddEditHabitScreen(
viewModel: HabitViewModel, viewModel: HabitViewModel,
existingHabit: Habit? = null, existingHabit: Habit? = null,
onNavigateBack: () -> Unit onNavigateBack: () -> Unit
) { ) {
val context = LocalContext.current
val isEditing = existingHabit != null val isEditing = existingHabit != null
var name by remember { mutableStateOf(existingHabit?.name ?: "") } // Activity types from the database
var selectedCategory by remember { val activityTypes by viewModel.allActivityTypes.collectAsState()
mutableStateOf(existingHabit?.category ?: HabitCategory.HEALTH)
} // ── Form state (survives rotation) ──────────────────────
var targetFrequency by remember { var selectedActivityName by rememberSaveable { mutableStateOf(existingHabit?.name ?: "") }
var details by rememberSaveable { mutableStateOf(existingHabit?.details ?: "") }
var targetFrequency by rememberSaveable {
mutableStateOf((existingHabit?.targetFrequency ?: 7).toString()) mutableStateOf((existingHabit?.targetFrequency ?: 7).toString())
} }
var reminderEnabled by remember { mutableStateOf(existingHabit?.reminderEnabled ?: true) } var reminderEnabled by rememberSaveable { mutableStateOf(existingHabit?.reminderEnabled ?: true) }
var reminderHour by remember { mutableIntStateOf(existingHabit?.reminderHour ?: 9) } var reminderHour by rememberSaveable { mutableIntStateOf(existingHabit?.reminderHour ?: 9) }
var reminderMinute by remember { mutableIntStateOf(existingHabit?.reminderMinute ?: 0) } var reminderMinute by rememberSaveable { mutableIntStateOf(existingHabit?.reminderMinute ?: 0) }
var nameError by remember { mutableStateOf(false) } var nameError by rememberSaveable { mutableStateOf(false) }
var showActivityDialog by rememberSaveable { mutableStateOf(false) }
var showAddTypeDialog by rememberSaveable { mutableStateOf(false) }
var showTimePicker by rememberSaveable { mutableStateOf(false) }
Scaffold( // ── Activity type picker dialog ─────────────────────────
topBar = { if (showActivityDialog) {
TopAppBar( AlertDialog(
onDismissRequest = { showActivityDialog = false },
title = { Text("Select Activity Type") },
text = {
if (activityTypes.isEmpty()) {
Text(
"No activity types yet.\nTap the + button to create one.",
style = MaterialTheme.typography.bodyMedium,
color = MaterialTheme.colorScheme.onSurfaceVariant
)
} else {
LazyColumn {
items(activityTypes) { type ->
Text(
text = type.name,
modifier = Modifier
.fillMaxWidth()
.clickable {
selectedActivityName = type.name
nameError = false
showActivityDialog = false
}
.padding(vertical = 12.dp, horizontal = 8.dp),
style = MaterialTheme.typography.bodyLarge,
fontWeight = if (type.name == selectedActivityName)
FontWeight.Bold else FontWeight.Normal,
color = if (type.name == selectedActivityName)
MaterialTheme.colorScheme.primary
else MaterialTheme.colorScheme.onSurface
)
}
}
}
},
confirmButton = {
TextButton(onClick = { showActivityDialog = false }) { Text("Close") }
}
)
}
// ── Add new activity type dialog ────────────────────────
if (showAddTypeDialog) {
var newTypeName by remember { mutableStateOf("") }
var typeError by remember { mutableStateOf(false) }
AlertDialog(
onDismissRequest = { showAddTypeDialog = false },
title = { Text("New Activity Type") },
text = {
Column {
OutlinedTextField(
value = newTypeName,
onValueChange = { newTypeName = it; typeError = false },
label = { Text("Type name") },
placeholder = { Text("e.g. Gym, Running, Yoga") },
singleLine = true,
isError = typeError,
modifier = Modifier.fillMaxWidth(),
shape = RoundedCornerShape(12.dp)
)
if (typeError) {
Text(
"Name is empty or already exists",
style = MaterialTheme.typography.bodySmall,
color = MaterialTheme.colorScheme.error
)
}
}
},
confirmButton = {
TextButton(onClick = {
if (newTypeName.isBlank()) {
typeError = true
} else {
viewModel.addActivityType(newTypeName) { success ->
if (success) {
selectedActivityName = HabitViewModel.toTitleCase(newTypeName.trim())
nameError = false
showAddTypeDialog = false
} else {
typeError = true
}
}
}
}) { Text("Add") }
},
dismissButton = {
TextButton(onClick = { showAddTypeDialog = false }) { Text("Cancel") }
}
)
}
// ── Time picker dialog (clock dial) ─────────────────────
if (showTimePicker) {
var tempHour by remember { mutableIntStateOf(reminderHour) }
var tempMinute by remember { mutableIntStateOf(reminderMinute) }
var pickingHour by remember { mutableStateOf(true) }
AlertDialog(
onDismissRequest = { showTimePicker = false },
title = { title = {
Text( Text(
if (isEditing) "Edit Habit" else "New Habit", if (pickingHour) "Select Hour" else "Select Minute",
fontWeight = FontWeight.Bold textAlign = TextAlign.Center,
modifier = Modifier.fillMaxWidth()
) )
}, },
navigationIcon = { text = {
IconButton(onClick = onNavigateBack) { Column(
Icon(Icons.AutoMirrored.Filled.ArrowBack, contentDescription = "Back") horizontalAlignment = Alignment.CenterHorizontally,
modifier = Modifier.fillMaxWidth()
) {
// Display current selection
Text(
text = "${tempHour.toString().padStart(2, '0')}:${tempMinute.toString().padStart(2, '0')}",
style = MaterialTheme.typography.headlineLarge,
fontWeight = FontWeight.Bold,
color = MaterialTheme.colorScheme.primary,
textAlign = TextAlign.Center,
modifier = Modifier.fillMaxWidth()
)
Spacer(modifier = Modifier.height(4.dp))
// Toggle hour/minute
Row(
horizontalArrangement = Arrangement.Center,
modifier = Modifier.fillMaxWidth()
) {
TextButton(onClick = { pickingHour = true }) {
Text(
"Hour",
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()
)
} }
}, },
colors = TopAppBarDefaults.topAppBarColors( confirmButton = {
containerColor = MaterialTheme.colorScheme.primary, TextButton(onClick = {
titleContentColor = MaterialTheme.colorScheme.onPrimary, reminderHour = tempHour
navigationIconContentColor = MaterialTheme.colorScheme.onPrimary reminderMinute = tempMinute
) showTimePicker = false
}) { Text("OK") }
},
dismissButton = {
TextButton(onClick = { showTimePicker = false }) { Text("Cancel") }
}
) )
} }
) { padding ->
// ── Screen layout ───────────────────────────────────────
Scaffold { padding ->
Column( Column(
modifier = Modifier modifier = Modifier
.fillMaxSize() .fillMaxSize()
.padding(padding) .padding(padding)
) {
// Header bar
Box(
modifier = Modifier
.fillMaxWidth()
.background(MaterialTheme.colorScheme.primary)
.padding(horizontal = 16.dp, vertical = 16.dp)
) {
Row(
modifier = Modifier.fillMaxWidth(),
verticalAlignment = Alignment.CenterVertically
) {
Text(
text = "←",
modifier = Modifier
.clickable(onClick = onNavigateBack)
.padding(end = 16.dp),
style = MaterialTheme.typography.titleLarge,
color = MaterialTheme.colorScheme.onPrimary,
fontWeight = FontWeight.Bold
)
Text(
text = if (isEditing) "Edit Habit" else "New Habit",
style = MaterialTheme.typography.titleLarge,
color = MaterialTheme.colorScheme.onPrimary,
fontWeight = FontWeight.Bold
)
}
}
Column(
modifier = Modifier
.fillMaxSize()
.padding(20.dp) .padding(20.dp)
.verticalScroll(rememberScrollState()), .verticalScroll(rememberScrollState()),
verticalArrangement = Arrangement.spacedBy(16.dp) verticalArrangement = Arrangement.spacedBy(16.dp)
) { ) {
// Name // ── Activity type dropdown + add button ─────────
Text(
text = "Activity Type",
style = MaterialTheme.typography.bodyMedium,
color = MaterialTheme.colorScheme.onSurfaceVariant
)
Row(
modifier = Modifier.fillMaxWidth(),
horizontalArrangement = Arrangement.spacedBy(8.dp),
verticalAlignment = Alignment.CenterVertically
) {
Card(
modifier = Modifier
.weight(1f)
.clickable { showActivityDialog = true },
shape = RoundedCornerShape(12.dp),
elevation = CardDefaults.cardElevation(1.dp),
colors = if (nameError) CardDefaults.cardColors(
containerColor = MaterialTheme.colorScheme.errorContainer
) else CardDefaults.cardColors()
) {
Row(
modifier = Modifier
.fillMaxWidth()
.padding(16.dp),
horizontalArrangement = Arrangement.SpaceBetween,
verticalAlignment = Alignment.CenterVertically
) {
Text(
text = if (selectedActivityName.isBlank()) "Tap to select…"
else selectedActivityName,
style = MaterialTheme.typography.bodyLarge,
color = if (selectedActivityName.isBlank())
MaterialTheme.colorScheme.onSurfaceVariant.copy(alpha = 0.5f)
else MaterialTheme.colorScheme.onSurface
)
Text(
text = "▼",
style = MaterialTheme.typography.bodySmall,
color = MaterialTheme.colorScheme.onSurfaceVariant
)
}
}
// "+" button to add a new activity type
Button(
onClick = { showAddTypeDialog = true },
modifier = Modifier.size(52.dp),
shape = RoundedCornerShape(12.dp),
contentPadding = androidx.compose.foundation.layout.PaddingValues(0.dp)
) {
Text("+", style = MaterialTheme.typography.titleLarge, fontWeight = FontWeight.Bold)
}
}
if (nameError) {
Text(
text = "Please select an activity type",
style = MaterialTheme.typography.bodySmall,
color = MaterialTheme.colorScheme.error,
modifier = Modifier.padding(start = 4.dp)
)
}
// ── Details text field ──────────────────────────
OutlinedTextField( OutlinedTextField(
value = name, value = details,
onValueChange = { onValueChange = { details = it },
name = it label = { Text("Details (optional)") },
nameError = false placeholder = { Text("e.g. Legs, Upper Body, 5K") },
},
label = { Text("Habit Name") },
placeholder = { Text("e.g. Drink 8 glasses of water") },
isError = nameError,
supportingText = if (nameError) {
{ Text("Name cannot be empty") }
} else null,
singleLine = true, singleLine = true,
modifier = Modifier.fillMaxWidth(), modifier = Modifier.fillMaxWidth(),
shape = RoundedCornerShape(12.dp) shape = RoundedCornerShape(12.dp)
) )
// Category dropdown // Live preview
var categoryExpanded by remember { mutableStateOf(false) } if (selectedActivityName.isNotBlank()) {
ExposedDropdownMenuBox( val previewName = if (details.isBlank())
expanded = categoryExpanded, HabitViewModel.toTitleCase(selectedActivityName.trim())
onExpandedChange = { categoryExpanded = !categoryExpanded } else
) { HabitViewModel.toTitleCase(selectedActivityName.trim()) +
OutlinedTextField( "(" + HabitViewModel.toTitleCase(details.trim()) + ")"
value = selectedCategory.displayName, Text(
onValueChange = {}, text = "Will display as: $previewName",
readOnly = true, style = MaterialTheme.typography.labelMedium,
label = { Text("Category") }, color = MaterialTheme.colorScheme.primary,
trailingIcon = { ExposedDropdownMenuDefaults.TrailingIcon(expanded = categoryExpanded) }, modifier = Modifier.padding(start = 4.dp)
modifier = Modifier
.fillMaxWidth()
.menuAnchor(),
shape = RoundedCornerShape(12.dp)
) )
ExposedDropdownMenu(
expanded = categoryExpanded,
onDismissRequest = { categoryExpanded = false }
) {
HabitCategory.entries.forEach { cat ->
DropdownMenuItem(
text = { Text(cat.displayName) },
onClick = {
selectedCategory = cat
categoryExpanded = false
}
)
}
}
} }
// Target frequency // ── Target frequency ────────────────────────────
OutlinedTextField( OutlinedTextField(
value = targetFrequency, value = targetFrequency,
onValueChange = { targetFrequency = it.filter { c -> c.isDigit() } }, onValueChange = { targetFrequency = it.filter { c -> c.isDigit() } },
@@ -161,84 +414,98 @@ fun AddEditHabitScreen(
shape = RoundedCornerShape(12.dp) 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)
Switch( Button(
checked = reminderEnabled, onClick = { reminderEnabled = !reminderEnabled },
onCheckedChange = { reminderEnabled = it } 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")
}
} }
if (reminderEnabled) { if (reminderEnabled) {
// Simple hour/minute pickers as text fields // ── Reminder time — clock dial button ───────
Row( Card(
modifier = Modifier.fillMaxWidth(), modifier = Modifier
horizontalArrangement = Arrangement.spacedBy(12.dp) .fillMaxWidth()
.clickable { showTimePicker = true },
shape = RoundedCornerShape(12.dp),
elevation = CardDefaults.cardElevation(1.dp)
) { ) {
OutlinedTextField( Row(
value = reminderHour.toString().padStart(2, '0'), modifier = Modifier
onValueChange = { .fillMaxWidth()
val h = it.filter { c -> c.isDigit() }.take(2).toIntOrNull() ?: 0 .padding(16.dp),
reminderHour = h.coerceIn(0, 23) horizontalArrangement = Arrangement.SpaceBetween,
}, verticalAlignment = Alignment.CenterVertically
label = { Text("Hour (0-23)") }, ) {
keyboardOptions = KeyboardOptions(keyboardType = KeyboardType.Number), Text("Reminder Time", style = MaterialTheme.typography.bodyLarge)
singleLine = true, Text(
modifier = Modifier.weight(1f), text = "${reminderHour.toString().padStart(2, '0')}:${reminderMinute.toString().padStart(2, '0')}",
shape = RoundedCornerShape(12.dp) style = MaterialTheme.typography.titleMedium,
) fontWeight = FontWeight.Bold,
OutlinedTextField( color = MaterialTheme.colorScheme.primary
value = reminderMinute.toString().padStart(2, '0'),
onValueChange = {
val m = it.filter { c -> c.isDigit() }.take(2).toIntOrNull() ?: 0
reminderMinute = m.coerceIn(0, 59)
},
label = { Text("Minute (0-59)") },
keyboardOptions = KeyboardOptions(keyboardType = KeyboardType.Number),
singleLine = true,
modifier = Modifier.weight(1f),
shape = RoundedCornerShape(12.dp)
) )
} }
} }
}
Spacer(modifier = Modifier.height(8.dp)) Spacer(modifier = Modifier.height(8.dp))
// Save button // ── Save button ─────────────────────────────────
Button( Button(
onClick = { onClick = {
if (name.isBlank()) { if (selectedActivityName.isBlank()) {
nameError = true nameError = true
return@Button return@Button
} }
val freq = targetFrequency.toIntOrNull() ?: 7 val freq = targetFrequency.toIntOrNull() ?: 7
if (isEditing && existingHabit != null) { if (isEditing && existingHabit != null) {
viewModel.updateHabit( viewModel.updateHabit(
existingHabit.copy( existingHabit.copy(
name = name.trim(), name = selectedActivityName.trim(),
category = selectedCategory, details = details.trim(),
activityType = selectedActivityName.trim(),
targetFrequency = freq, targetFrequency = freq,
reminderEnabled = reminderEnabled, reminderEnabled = reminderEnabled,
reminderHour = reminderHour, reminderHour = reminderHour,
reminderMinute = reminderMinute reminderMinute = reminderMinute
) )
) )
Log.i("AddEditHabitScreen", "User updated habit: name='${selectedActivityName.trim()}'")
onNavigateBack()
} else { } else {
viewModel.addHabit( viewModel.addHabit(
name = name.trim(), name = selectedActivityName.trim(),
category = selectedCategory, details = details.trim(),
activityType = selectedActivityName.trim(),
targetFrequency = freq, targetFrequency = freq,
reminderEnabled = reminderEnabled, reminderEnabled = reminderEnabled,
reminderHour = reminderHour, reminderHour = reminderHour,
reminderMinute = reminderMinute reminderMinute = reminderMinute,
onResult = { success ->
if (success) {
Log.i("AddEditHabitScreen", "User created habit: name='${selectedActivityName.trim()}'")
onNavigateBack()
} else {
Toast.makeText(context, "This activity already exists!", Toast.LENGTH_SHORT).show()
}
}
) )
} }
onNavigateBack()
}, },
modifier = Modifier modifier = Modifier
.fillMaxWidth() .fillMaxWidth()
@@ -253,5 +520,141 @@ 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
)
}
}
}
}
@@ -0,0 +1,220 @@
package com.example.madwellbeingapp.ui.screens
import androidx.compose.foundation.background
import androidx.compose.foundation.clickable
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.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.foundation.shape.CircleShape
import androidx.compose.foundation.shape.RoundedCornerShape
import androidx.compose.material3.Card
import androidx.compose.material3.CardDefaults
import androidx.compose.material3.LinearProgressIndicator
import androidx.compose.material3.MaterialTheme
import androidx.compose.material3.Scaffold
import androidx.compose.material3.Text
import androidx.compose.runtime.Composable
import androidx.compose.runtime.collectAsState
import androidx.compose.runtime.getValue
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.draw.clip
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
/**
* Shows ALL activities — both active and past/completed.
* Read-only listing; tapping a card navigates to its detail screen.
*/
@Composable
fun AllActivitiesScreen(
viewModel: HabitViewModel,
onNavigateBack: () -> Unit,
onHabitClick: (Int) -> Unit
) {
val habits by viewModel.allHabits.collectAsState()
val todayLogs by viewModel.todayLogs.collectAsState()
val todayCompletedIds = todayLogs.filter { it.completed }.map { it.habitId }.toSet()
Scaffold { padding ->
Column(
modifier = Modifier
.fillMaxSize()
.padding(padding)
) {
// Header
Box(
modifier = Modifier
.fillMaxWidth()
.background(MaterialTheme.colorScheme.primary)
.padding(horizontal = 16.dp, vertical = 16.dp)
) {
Row(
modifier = Modifier.fillMaxWidth(),
verticalAlignment = Alignment.CenterVertically
) {
Text(
text = "←",
modifier = Modifier
.clickable(onClick = onNavigateBack)
.padding(end = 16.dp),
style = MaterialTheme.typography.titleLarge,
color = MaterialTheme.colorScheme.onPrimary,
fontWeight = FontWeight.Bold
)
Text(
text = "All Activities",
style = MaterialTheme.typography.titleLarge,
color = MaterialTheme.colorScheme.onPrimary,
fontWeight = FontWeight.Bold
)
}
}
if (habits.isEmpty()) {
Box(
modifier = Modifier
.fillMaxSize()
.padding(32.dp),
contentAlignment = Alignment.Center
) {
Text(
text = "No activities yet. Go to Manage Activities to create one!",
style = MaterialTheme.typography.bodyLarge,
color = MaterialTheme.colorScheme.onSurfaceVariant
)
}
} else {
LazyColumn(
modifier = Modifier
.fillMaxSize()
.padding(horizontal = 16.dp, vertical = 12.dp),
verticalArrangement = Arrangement.spacedBy(10.dp)
) {
items(habits, key = { it.id }) { habit ->
AllActivityCard(
habit = habit,
isCompletedToday = todayCompletedIds.contains(habit.id),
onClick = { onHabitClick(habit.id) },
viewModel = viewModel
)
}
}
}
}
}
}
@Composable
private fun AllActivityCard(
habit: Habit,
isCompletedToday: Boolean,
onClick: () -> Unit,
viewModel: HabitViewModel
) {
val weeklyProgress by viewModel.weeklyProgress(habit.id)
.collectAsState(initial = 0f)
Card(
modifier = Modifier
.fillMaxWidth()
.clickable(onClick = onClick),
shape = RoundedCornerShape(16.dp),
elevation = CardDefaults.cardElevation(defaultElevation = 2.dp),
colors = CardDefaults.cardColors(
containerColor = when {
!habit.isActive -> MaterialTheme.colorScheme.surfaceVariant.copy(alpha = 0.5f)
isCompletedToday -> MaterialTheme.colorScheme.primaryContainer
else -> MaterialTheme.colorScheme.surface
}
)
) {
Row(
modifier = Modifier
.fillMaxWidth()
.padding(16.dp),
verticalAlignment = Alignment.CenterVertically
) {
// Status circle
Box(
modifier = Modifier
.size(44.dp)
.clip(CircleShape)
.background(
when {
!habit.isActive -> MaterialTheme.colorScheme.outline.copy(alpha = 0.4f)
isCompletedToday -> MaterialTheme.colorScheme.primary
else -> MaterialTheme.colorScheme.surfaceVariant
}
),
contentAlignment = Alignment.Center
) {
Text(
text = when {
!habit.isActive -> "—"
isCompletedToday -> "✓"
else -> ""
},
color = if (isCompletedToday) MaterialTheme.colorScheme.onPrimary
else MaterialTheme.colorScheme.onSurfaceVariant,
fontWeight = FontWeight.Bold,
style = MaterialTheme.typography.titleMedium
)
}
Spacer(modifier = Modifier.width(14.dp))
Column(modifier = Modifier.weight(1f)) {
Row(verticalAlignment = Alignment.CenterVertically) {
Text(
text = habit.displayName,
style = MaterialTheme.typography.titleMedium,
fontWeight = FontWeight.SemiBold
)
if (!habit.isActive) {
Spacer(modifier = Modifier.width(8.dp))
Text(
text = "Retired",
style = MaterialTheme.typography.labelSmall,
color = MaterialTheme.colorScheme.error
)
}
}
Spacer(modifier = Modifier.height(2.dp))
Text(
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))
Text(
text = "Weekly: ${(weeklyProgress * 100).toInt()}%",
style = MaterialTheme.typography.labelSmall,
color = MaterialTheme.colorScheme.onSurfaceVariant.copy(alpha = 0.7f)
)
}
}
}
}
@@ -1,6 +1,9 @@
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
@@ -9,6 +12,7 @@ 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.layout.width
@@ -18,46 +22,37 @@ import androidx.compose.foundation.rememberScrollState
import androidx.compose.foundation.shape.CircleShape import androidx.compose.foundation.shape.CircleShape
import androidx.compose.foundation.shape.RoundedCornerShape import androidx.compose.foundation.shape.RoundedCornerShape
import androidx.compose.foundation.verticalScroll import androidx.compose.foundation.verticalScroll
import androidx.compose.material.icons.Icons
import androidx.compose.material.icons.automirrored.filled.ArrowBack
import androidx.compose.material.icons.filled.Delete
import androidx.compose.material.icons.filled.Edit
import androidx.compose.material3.AlertDialog import androidx.compose.material3.AlertDialog
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.ExperimentalMaterial3Api
import androidx.compose.material3.Icon
import androidx.compose.material3.IconButton
import androidx.compose.material3.LinearProgressIndicator 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.material3.TextButton import androidx.compose.material3.TextButton
import androidx.compose.material3.TopAppBar
import androidx.compose.material3.TopAppBarDefaults
import androidx.compose.runtime.Composable import androidx.compose.runtime.Composable
import androidx.compose.runtime.LaunchedEffect import androidx.compose.runtime.LaunchedEffect
import androidx.compose.runtime.collectAsState import androidx.compose.runtime.collectAsState
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.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.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.data.model.HabitCategory
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
@OptIn(ExperimentalMaterial3Api::class)
@Composable @Composable
fun HabitDetailScreen( fun HabitDetailScreen(
habitId: Int, habitId: Int,
@@ -81,9 +76,10 @@ fun HabitDetailScreen(
AlertDialog( AlertDialog(
onDismissRequest = { showDeleteDialog = false }, onDismissRequest = { showDeleteDialog = false },
title = { Text("Delete Habit") }, title = { Text("Delete Habit") },
text = { Text("Are you sure you want to delete \"${habit!!.name}\"? All associated data will be lost.") }, text = { Text("Are you sure you want to delete \"${habit!!.displayName}\"? All associated data will be lost.") },
confirmButton = { confirmButton = {
TextButton(onClick = { TextButton(onClick = {
Log.i("HabitDetail", "User confirmed DELETE for habit '${habit!!.displayName}' (id=${habit!!.id})")
viewModel.deleteHabit(habit!!) viewModel.deleteHabit(habit!!)
showDeleteDialog = false showDeleteDialog = false
onNavigateBack() onNavigateBack()
@@ -92,42 +88,68 @@ fun HabitDetailScreen(
} }
}, },
dismissButton = { dismissButton = {
TextButton(onClick = { showDeleteDialog = false }) { TextButton(onClick = { showDeleteDialog = false }) { Text("Cancel") }
Text("Cancel")
}
} }
) )
} }
Scaffold( Scaffold { padding ->
topBar = { Column(
TopAppBar( modifier = Modifier
title = { Text(habit?.name ?: "Habit Detail", fontWeight = FontWeight.Bold) }, .fillMaxSize()
navigationIcon = { .padding(padding)
IconButton(onClick = onNavigateBack) { ) {
Icon(Icons.AutoMirrored.Filled.ArrowBack, contentDescription = "Back") // Custom header bar (replaces TopAppBar which uses material.icons)
} Box(
}, modifier = Modifier
actions = { .fillMaxWidth()
IconButton(onClick = { onEditHabit(habitId) }) { .background(MaterialTheme.colorScheme.primary)
Icon(Icons.Default.Edit, contentDescription = "Edit") .padding(horizontal = 16.dp, vertical = 16.dp)
} ) {
IconButton(onClick = { showDeleteDialog = true }) { Row(
Icon(Icons.Default.Delete, contentDescription = "Delete") modifier = Modifier.fillMaxWidth(),
} verticalAlignment = Alignment.CenterVertically,
}, horizontalArrangement = Arrangement.SpaceBetween
colors = TopAppBarDefaults.topAppBarColors( ) {
containerColor = MaterialTheme.colorScheme.primary, Row(verticalAlignment = Alignment.CenterVertically) {
titleContentColor = MaterialTheme.colorScheme.onPrimary, Text(
navigationIconContentColor = MaterialTheme.colorScheme.onPrimary, text = "←",
actionIconContentColor = MaterialTheme.colorScheme.onPrimary modifier = Modifier
.clickable(onClick = onNavigateBack)
.padding(end = 12.dp),
style = MaterialTheme.typography.titleLarge,
color = MaterialTheme.colorScheme.onPrimary,
fontWeight = FontWeight.Bold
) )
Text(
text = habit?.displayName ?: "Habit Detail",
style = MaterialTheme.typography.titleLarge,
color = MaterialTheme.colorScheme.onPrimary,
fontWeight = FontWeight.Bold
) )
} }
) { padding -> Row {
Text(
text = "✏️",
modifier = Modifier
.clickable { onEditHabit(habitId) }
.padding(horizontal = 8.dp),
style = MaterialTheme.typography.titleLarge
)
Text(
text = "🗑️",
modifier = Modifier
.clickable { showDeleteDialog = true }
.padding(horizontal = 8.dp),
style = MaterialTheme.typography.titleLarge
)
}
}
}
if (habit == null) { if (habit == null) {
Box( Box(
modifier = Modifier.fillMaxSize().padding(padding), modifier = Modifier.fillMaxSize(),
contentAlignment = Alignment.Center contentAlignment = Alignment.Center
) { ) {
Text("Loading…") Text("Loading…")
@@ -141,7 +163,6 @@ fun HabitDetailScreen(
Column( Column(
modifier = Modifier modifier = Modifier
.fillMaxSize() .fillMaxSize()
.padding(padding)
.verticalScroll(rememberScrollState()) .verticalScroll(rememberScrollState())
.padding(20.dp), .padding(20.dp),
verticalArrangement = Arrangement.spacedBy(16.dp) verticalArrangement = Arrangement.spacedBy(16.dp)
@@ -154,7 +175,7 @@ fun HabitDetailScreen(
) { ) {
Column(modifier = Modifier.padding(16.dp)) { Column(modifier = Modifier.padding(16.dp)) {
Text( Text(
text = categoryEmoji(h.category) + " " + h.category.displayName, text = h.activityType,
style = MaterialTheme.typography.labelLarge, style = MaterialTheme.typography.labelLarge,
color = MaterialTheme.colorScheme.primary color = MaterialTheme.colorScheme.primary
) )
@@ -169,33 +190,21 @@ fun HabitDetailScreen(
) )
if (h.reminderEnabled) { if (h.reminderEnabled) {
Text( Text(
text = "Reminder: ${h.reminderHour.toString().padStart(2, '0')}:${ text = "Reminder: ${h.reminderHour.toString().padStart(2, '0')}:${h.reminderMinute.toString().padStart(2, '0')}",
h.reminderMinute.toString().padStart(2, '0')
}",
style = MaterialTheme.typography.bodyMedium style = MaterialTheme.typography.bodyMedium
) )
} }
} }
} }
// Mark today button // Swipe to mark today as complete (or undo)
Button( SwipeToCompleteBar(
onClick = { viewModel.toggleTodayLog(habitId) }, isCompletedToday = isCompletedToday,
modifier = Modifier onSwipeComplete = {
.fillMaxWidth() Log.i("HabitDetail", "Swipe-to-complete triggered for habit '${h.displayName}' (id=${h.id}), isUndo=${isCompletedToday}")
.height(52.dp), viewModel.toggleTodayLog(habitId)
shape = RoundedCornerShape(14.dp),
colors = if (isCompletedToday) ButtonDefaults.buttonColors(
containerColor = MaterialTheme.colorScheme.secondaryContainer,
contentColor = MaterialTheme.colorScheme.onSecondaryContainer
) else ButtonDefaults.buttonColors()
) {
Text(
if (isCompletedToday) "✅ Completed Today — Tap to Undo"
else "Mark Today as Done",
fontWeight = FontWeight.Bold
)
} }
)
// Streak cards // Streak cards
Row( Row(
@@ -319,6 +328,82 @@ fun HabitDetailScreen(
Spacer(modifier = Modifier.height(16.dp)) Spacer(modifier = Modifier.height(16.dp))
} }
} }
}
}
/**
* Swipe-to-complete bar for the detail screen.
* User must swipe right past a threshold to toggle completion.
*/
@Composable
private fun SwipeToCompleteBar(
isCompletedToday: Boolean,
onSwipeComplete: () -> Unit
) {
val swipeThreshold = 200f
var offsetX by remember { mutableFloatStateOf(0f) }
Box(
modifier = Modifier
.fillMaxWidth()
.height(56.dp)
.clip(RoundedCornerShape(14.dp))
) {
// Background
Box(
modifier = Modifier
.matchParentSize()
.background(
if (isCompletedToday) MaterialTheme.colorScheme.secondaryContainer
else MaterialTheme.colorScheme.primary.copy(alpha = 0.15f)
),
contentAlignment = Alignment.Center
) {
Text(
text = if (isCompletedToday) "← Swipe → to Undo"
else "← Swipe → to Complete Today",
style = MaterialTheme.typography.bodyMedium,
fontWeight = FontWeight.Bold,
color = if (isCompletedToday) MaterialTheme.colorScheme.onSecondaryContainer
else MaterialTheme.colorScheme.primary
)
}
// Draggable thumb
Box(
modifier = Modifier
.size(width = 80.dp, height = 56.dp)
.offset { IntOffset(offsetX.roundToInt(), 0) }
.clip(RoundedCornerShape(14.dp))
.background(
if (isCompletedToday) MaterialTheme.colorScheme.secondary
else MaterialTheme.colorScheme.primary
)
.pointerInput(isCompletedToday) {
detectHorizontalDragGestures(
onDragEnd = {
if (offsetX > swipeThreshold) {
Log.d("SwipeGesture", "Detail swipe threshold reached, toggling completion")
onSwipeComplete()
}
offsetX = 0f
},
onDragCancel = { offsetX = 0f },
onHorizontalDrag = { _, dragAmount ->
offsetX = (offsetX + dragAmount).coerceIn(0f, swipeThreshold + 50f)
}
)
},
contentAlignment = Alignment.Center
) {
Text(
text = if (isCompletedToday) "✅" else "→",
style = MaterialTheme.typography.titleLarge,
color = MaterialTheme.colorScheme.onPrimary,
fontWeight = FontWeight.Bold
)
}
}
} }
@Composable @Composable
@@ -353,13 +438,6 @@ private fun StatCard(title: String, value: String, modifier: Modifier = Modifier
} }
} }
private fun categoryEmoji(category: HabitCategory): String = when (category) {
HabitCategory.HEALTH -> "❤️"
HabitCategory.STUDY -> "📚"
HabitCategory.FITNESS -> "💪"
HabitCategory.WELLBEING -> "🧘"
}
private fun normaliseToDay(millis: Long): Long { private fun normaliseToDay(millis: Long): Long {
val cal = Calendar.getInstance() val cal = Calendar.getInstance()
cal.timeInMillis = millis cal.timeInMillis = millis
@@ -378,4 +456,3 @@ private fun todayStartMillis(): Long {
cal.set(Calendar.MILLISECOND, 0) cal.set(Calendar.MILLISECOND, 0)
return cal.timeInMillis return cal.timeInMillis
} }
@@ -1,8 +1,9 @@
package com.example.madwellbeingapp.ui.screens package com.example.madwellbeingapp.ui.screens
import androidx.compose.animation.animateContentSize import android.util.Log
import androidx.compose.foundation.background import androidx.compose.foundation.background
import androidx.compose.foundation.clickable 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
@@ -11,6 +12,7 @@ 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.layout.width
@@ -18,14 +20,9 @@ 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.CircleShape
import androidx.compose.foundation.shape.RoundedCornerShape import androidx.compose.foundation.shape.RoundedCornerShape
import androidx.compose.material.icons.Icons import androidx.compose.material3.Button
import androidx.compose.material.icons.filled.Add
import androidx.compose.material.icons.filled.Check
import androidx.compose.material3.Card import androidx.compose.material3.Card
import androidx.compose.material3.CardDefaults import androidx.compose.material3.CardDefaults
import androidx.compose.material3.FloatingActionButton
import androidx.compose.material3.Icon
import androidx.compose.material3.IconButton
import androidx.compose.material3.LinearProgressIndicator 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
@@ -33,56 +30,71 @@ 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.remember
import androidx.compose.runtime.setValue
import androidx.compose.ui.Alignment import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier import androidx.compose.ui.Modifier
import androidx.compose.ui.draw.clip 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.unit.IntOffset
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.data.model.HabitCategory
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.Date import java.util.Date
import java.util.Locale import java.util.Locale
import kotlin.math.roundToInt
/**
* Manage Activities screen — the user can add a new activity or
* swipe to mark an existing active habit as done.
*/
@Composable @Composable
fun HomeScreen( fun HomeScreen(
viewModel: HabitViewModel, viewModel: HabitViewModel,
onAddHabit: () -> Unit, onAddHabit: () -> Unit,
onHabitClick: (Int) -> Unit onHabitClick: (Int) -> Unit,
onNavigateBack: () -> Unit
) { ) {
val habits by viewModel.allHabits.collectAsState() val habits by viewModel.allHabits.collectAsState()
val todayLogs by viewModel.todayLogs.collectAsState() val todayLogs by viewModel.todayLogs.collectAsState()
val todayCompletedIds = todayLogs.filter { it.completed }.map { it.habitId }.toSet() val todayCompletedIds = todayLogs.filter { it.completed }.map { it.habitId }.toSet()
Scaffold( // Only show active habits on this management screen
floatingActionButton = { val activeHabits = habits.filter { it.isActive }
FloatingActionButton(
onClick = onAddHabit, Scaffold { padding ->
containerColor = MaterialTheme.colorScheme.primary
) {
Icon(Icons.Default.Add, contentDescription = "Add Habit")
}
}
) { padding ->
Column( Column(
modifier = Modifier modifier = Modifier
.fillMaxSize() .fillMaxSize()
.padding(padding) .padding(padding)
) { ) {
// Header // Header with back button
Column( Column(
modifier = Modifier modifier = Modifier
.fillMaxWidth() .fillMaxWidth()
.background(MaterialTheme.colorScheme.primary) .background(MaterialTheme.colorScheme.primary)
.padding(horizontal = 20.dp, vertical = 24.dp) .padding(horizontal = 20.dp, vertical = 24.dp)
) { ) {
Row(verticalAlignment = Alignment.CenterVertically) {
Text( Text(
text = "Smart Habit Companion", text = "←",
modifier = Modifier
.clickable(onClick = onNavigateBack)
.padding(end = 16.dp),
style = MaterialTheme.typography.titleLarge,
color = MaterialTheme.colorScheme.onPrimary,
fontWeight = FontWeight.Bold
)
Text(
text = "Manage Activities",
style = MaterialTheme.typography.headlineSmall, style = MaterialTheme.typography.headlineSmall,
color = MaterialTheme.colorScheme.onPrimary, color = MaterialTheme.colorScheme.onPrimary,
fontWeight = FontWeight.Bold fontWeight = FontWeight.Bold
) )
}
Spacer(modifier = Modifier.height(4.dp)) Spacer(modifier = Modifier.height(4.dp))
val dateFormat = SimpleDateFormat("EEEE, MMM d", Locale.getDefault()) val dateFormat = SimpleDateFormat("EEEE, MMM d", Locale.getDefault())
Text( Text(
@@ -92,8 +104,8 @@ fun HomeScreen(
) )
Spacer(modifier = Modifier.height(12.dp)) Spacer(modifier = Modifier.height(12.dp))
// Quick summary // Quick summary
val completedToday = todayCompletedIds.size val completedToday = activeHabits.count { todayCompletedIds.contains(it.id) }
val total = habits.size val total = activeHabits.size
Text( Text(
text = "$completedToday / $total habits completed today", text = "$completedToday / $total habits completed today",
style = MaterialTheme.typography.bodyLarge, style = MaterialTheme.typography.bodyLarge,
@@ -114,10 +126,11 @@ fun HomeScreen(
} }
} }
if (habits.isEmpty()) { if (activeHabits.isEmpty()) {
Box( Box(
modifier = Modifier modifier = Modifier
.fillMaxSize() .fillMaxSize()
.weight(1f)
.padding(32.dp), .padding(32.dp),
contentAlignment = Alignment.Center contentAlignment = Alignment.Center
) { ) {
@@ -129,7 +142,7 @@ fun HomeScreen(
) )
Spacer(modifier = Modifier.height(8.dp)) Spacer(modifier = Modifier.height(8.dp))
Text( Text(
text = "Tap + to create your first habit", text = "Tap the button below to create your first habit",
style = MaterialTheme.typography.bodyMedium, style = MaterialTheme.typography.bodyMedium,
color = MaterialTheme.colorScheme.onSurfaceVariant.copy(alpha = 0.7f) color = MaterialTheme.colorScheme.onSurfaceVariant.copy(alpha = 0.7f)
) )
@@ -138,40 +151,109 @@ fun HomeScreen(
} else { } else {
LazyColumn( LazyColumn(
modifier = Modifier modifier = Modifier
.fillMaxSize() .weight(1f)
.fillMaxWidth()
.padding(horizontal = 16.dp, vertical = 12.dp), .padding(horizontal = 16.dp, vertical = 12.dp),
verticalArrangement = Arrangement.spacedBy(10.dp) verticalArrangement = Arrangement.spacedBy(10.dp)
) { ) {
items(habits, key = { it.id }) { habit -> items(activeHabits, key = { it.id }) { habit ->
HabitCard( SwipeToCompleteHabitCard(
habit = habit, habit = habit,
isCompletedToday = todayCompletedIds.contains(habit.id), isCompletedToday = todayCompletedIds.contains(habit.id),
onToggle = { viewModel.toggleTodayLog(habit.id) }, onSwipeComplete = { viewModel.toggleTodayLog(habit.id) },
onClick = { onHabitClick(habit.id) }, onClick = { onHabitClick(habit.id) },
viewModel = viewModel viewModel = viewModel
) )
} }
} }
} }
// Add habit button at the bottom
Button(
onClick = onAddHabit,
modifier = Modifier
.fillMaxWidth()
.padding(horizontal = 16.dp, vertical = 12.dp)
.height(52.dp),
shape = RoundedCornerShape(14.dp)
) {
Text(
text = "+ Add New Habit",
style = MaterialTheme.typography.titleMedium,
fontWeight = FontWeight.Bold
)
}
} }
} }
} }
/**
* A habit card that requires a horizontal swipe gesture to mark as complete.
* The user must swipe right past a threshold to toggle completion.
* This prevents accidental taps from marking habits complete.
*/
@Composable @Composable
private fun HabitCard( private fun SwipeToCompleteHabitCard(
habit: Habit, habit: Habit,
isCompletedToday: Boolean, isCompletedToday: Boolean,
onToggle: () -> Unit, onSwipeComplete: () -> Unit,
onClick: () -> Unit, onClick: () -> Unit,
viewModel: HabitViewModel viewModel: HabitViewModel
) { ) {
val weeklyProgress by viewModel.weeklyProgress(habit.id) val weeklyProgress by viewModel.weeklyProgress(habit.id)
.collectAsState(initial = 0f) .collectAsState(initial = 0f)
val swipeThreshold = 150f
var offsetX by remember { mutableFloatStateOf(0f) }
Box(
modifier = Modifier
.fillMaxWidth()
.clip(RoundedCornerShape(16.dp))
) {
// Background revealed on swipe
Box(
modifier = Modifier
.matchParentSize()
.background(
if (isCompletedToday) MaterialTheme.colorScheme.error.copy(alpha = 0.2f)
else MaterialTheme.colorScheme.primary.copy(alpha = 0.2f)
),
contentAlignment = Alignment.CenterStart
) {
Text(
text = if (isCompletedToday) " ← Undo" else " ← Swipe to Complete →",
modifier = Modifier.padding(start = 16.dp),
style = MaterialTheme.typography.bodyMedium,
fontWeight = FontWeight.Bold,
color = if (isCompletedToday) MaterialTheme.colorScheme.error
else MaterialTheme.colorScheme.primary
)
}
// Foreground card that slides
Card( Card(
modifier = Modifier modifier = Modifier
.fillMaxWidth() .fillMaxWidth()
.animateContentSize() .offset { IntOffset(offsetX.roundToInt(), 0) }
.pointerInput(isCompletedToday) {
detectHorizontalDragGestures(
onDragEnd = {
if (offsetX > swipeThreshold) {
Log.d("SwipeGesture", "Swipe threshold reached for habit '${habit.displayName}' (id=${habit.id}), toggling completion")
onSwipeComplete()
}
offsetX = 0f
},
onDragCancel = {
offsetX = 0f
},
onHorizontalDrag = { _, dragAmount ->
// Only allow rightward swipe (positive direction)
offsetX = (offsetX + dragAmount).coerceIn(0f, swipeThreshold + 50f)
}
)
}
.clickable(onClick = onClick), .clickable(onClick = onClick),
shape = RoundedCornerShape(16.dp), shape = RoundedCornerShape(16.dp),
elevation = CardDefaults.cardElevation(defaultElevation = 2.dp), elevation = CardDefaults.cardElevation(defaultElevation = 2.dp),
@@ -187,9 +269,8 @@ private fun HabitCard(
.padding(16.dp), .padding(16.dp),
verticalAlignment = Alignment.CenterVertically verticalAlignment = Alignment.CenterVertically
) { ) {
// Check button // Status indicator circle
IconButton( Box(
onClick = onToggle,
modifier = Modifier modifier = Modifier
.size(44.dp) .size(44.dp)
.clip(CircleShape) .clip(CircleShape)
@@ -198,15 +279,17 @@ private fun HabitCard(
MaterialTheme.colorScheme.primary MaterialTheme.colorScheme.primary
else else
MaterialTheme.colorScheme.surfaceVariant MaterialTheme.colorScheme.surfaceVariant
) ),
contentAlignment = Alignment.Center
) { ) {
Icon( Text(
imageVector = Icons.Default.Check, text = if (isCompletedToday) "✓" else "",
contentDescription = if (isCompletedToday) "Completed" else "Mark complete", color = if (isCompletedToday)
tint = if (isCompletedToday)
MaterialTheme.colorScheme.onPrimary MaterialTheme.colorScheme.onPrimary
else else
MaterialTheme.colorScheme.onSurfaceVariant MaterialTheme.colorScheme.onSurfaceVariant,
fontWeight = FontWeight.Bold,
style = MaterialTheme.typography.titleMedium
) )
} }
@@ -214,14 +297,13 @@ private fun HabitCard(
Column(modifier = Modifier.weight(1f)) { Column(modifier = Modifier.weight(1f)) {
Text( Text(
text = habit.name, text = habit.displayName,
style = MaterialTheme.typography.titleMedium, style = MaterialTheme.typography.titleMedium,
fontWeight = FontWeight.SemiBold fontWeight = FontWeight.SemiBold
) )
Spacer(modifier = Modifier.height(2.dp)) Spacer(modifier = Modifier.height(2.dp))
Text( Text(
text = categoryEmoji(habit.category) + " " + habit.category.displayName + text = habit.activityType + " • ${habit.targetFrequency}x/week",
" • ${habit.targetFrequency}x/week",
style = MaterialTheme.typography.bodySmall, style = MaterialTheme.typography.bodySmall,
color = MaterialTheme.colorScheme.onSurfaceVariant color = MaterialTheme.colorScheme.onSurfaceVariant
) )
@@ -233,32 +315,29 @@ private fun HabitCard(
.fillMaxWidth() .fillMaxWidth()
.height(6.dp) .height(6.dp)
.clip(RoundedCornerShape(3.dp)), .clip(RoundedCornerShape(3.dp)),
color = categoryColor(habit.category), color = MaterialTheme.colorScheme.primary,
trackColor = MaterialTheme.colorScheme.surfaceVariant, trackColor = MaterialTheme.colorScheme.surfaceVariant,
) )
Spacer(modifier = Modifier.height(2.dp)) Spacer(modifier = Modifier.height(2.dp))
Row(
modifier = Modifier.fillMaxWidth(),
horizontalArrangement = Arrangement.SpaceBetween
) {
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)
) )
if (!isCompletedToday) {
Text(
text = "Swipe → to complete",
style = MaterialTheme.typography.labelSmall,
color = MaterialTheme.colorScheme.primary.copy(alpha = 0.6f)
)
}
}
}
} }
} }
} }
} }
private fun categoryEmoji(category: HabitCategory): String = when (category) {
HabitCategory.HEALTH -> "❤️"
HabitCategory.STUDY -> "📚"
HabitCategory.FITNESS -> "💪"
HabitCategory.WELLBEING -> "🧘"
}
@Composable
private fun categoryColor(category: HabitCategory) = when (category) {
HabitCategory.HEALTH -> MaterialTheme.colorScheme.error
HabitCategory.STUDY -> MaterialTheme.colorScheme.tertiary
HabitCategory.FITNESS -> MaterialTheme.colorScheme.primary
HabitCategory.WELLBEING -> MaterialTheme.colorScheme.secondary
}
@@ -0,0 +1,130 @@
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.Spacer
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.statusBarsPadding
import androidx.compose.foundation.shape.RoundedCornerShape
import androidx.compose.material3.Button
import androidx.compose.material3.ButtonDefaults
import androidx.compose.material3.MaterialTheme
import androidx.compose.material3.Text
import androidx.compose.runtime.Composable
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.text.font.FontWeight
import androidx.compose.ui.text.style.TextAlign
import androidx.compose.ui.unit.dp
/**
* Landing screen — the first page the user sees.
* Contains 3 centred buttons:
* 1. All Activities (past + active)
* 2. Manage Activities (add / mark done)
* 3. Active Only (still to-do)
*/
@Composable
fun LandingScreen(
onAllActivities: () -> Unit,
onManageActivities: () -> Unit,
onActiveOnly: () -> Unit
) {
Box(
modifier = Modifier
.fillMaxSize()
.background(MaterialTheme.colorScheme.background)
.statusBarsPadding(),
contentAlignment = Alignment.Center
) {
Column(
horizontalAlignment = Alignment.CenterHorizontally,
verticalArrangement = Arrangement.Center,
modifier = Modifier
.fillMaxWidth()
.padding(horizontal = 32.dp)
) {
// App title
Text(
text = "Smart Habit\n& Wellbeing Companion",
style = MaterialTheme.typography.headlineMedium,
fontWeight = FontWeight.Bold,
color = MaterialTheme.colorScheme.primary,
textAlign = TextAlign.Center
)
Spacer(modifier = Modifier.height(8.dp))
Text(
text = "Track your habits. Build your streaks.",
style = MaterialTheme.typography.bodyMedium,
color = MaterialTheme.colorScheme.onSurfaceVariant,
textAlign = TextAlign.Center
)
Spacer(modifier = Modifier.height(48.dp))
// Top button — All Activities
Button(
onClick = onAllActivities,
modifier = Modifier
.fillMaxWidth()
.height(56.dp),
shape = RoundedCornerShape(16.dp),
colors = ButtonDefaults.buttonColors(
containerColor = MaterialTheme.colorScheme.primary
)
) {
Text(
text = "All Activities",
style = MaterialTheme.typography.titleMedium,
fontWeight = FontWeight.Bold
)
}
Spacer(modifier = Modifier.height(16.dp))
// Middle button — Manage Activities
Button(
onClick = onManageActivities,
modifier = Modifier
.fillMaxWidth()
.height(56.dp),
shape = RoundedCornerShape(16.dp),
colors = ButtonDefaults.buttonColors(
containerColor = MaterialTheme.colorScheme.secondary
)
) {
Text(
text = "Manage Activities",
style = MaterialTheme.typography.titleMedium,
fontWeight = FontWeight.Bold
)
}
Spacer(modifier = Modifier.height(16.dp))
// Bottom button — Active Only
Button(
onClick = onActiveOnly,
modifier = Modifier
.fillMaxWidth()
.height(56.dp),
shape = RoundedCornerShape(16.dp),
colors = ButtonDefaults.buttonColors(
containerColor = MaterialTheme.colorScheme.tertiary
)
) {
Text(
text = "Active Only",
style = MaterialTheme.typography.titleMedium,
fontWeight = FontWeight.Bold
)
}
}
}
}
@@ -1,12 +1,19 @@
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.R
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.HabitCategory
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 com.example.madwellbeingapp.notification.HabitNotificationScheduler
@@ -16,6 +23,7 @@ import kotlinx.coroutines.flow.MutableStateFlow
import kotlinx.coroutines.flow.SharingStarted import kotlinx.coroutines.flow.SharingStarted
import kotlinx.coroutines.flow.StateFlow import kotlinx.coroutines.flow.StateFlow
import kotlinx.coroutines.flow.asStateFlow import kotlinx.coroutines.flow.asStateFlow
import kotlinx.coroutines.flow.combine
import kotlinx.coroutines.flow.flatMapLatest import kotlinx.coroutines.flow.flatMapLatest
import kotlinx.coroutines.flow.flowOf import kotlinx.coroutines.flow.flowOf
import kotlinx.coroutines.flow.map import kotlinx.coroutines.flow.map
@@ -28,6 +36,70 @@ class HabitViewModel(application: Application) : AndroidViewModel(application) {
private val repository: HabitRepository = private val repository: HabitRepository =
(application as HabitApp).repository (application as HabitApp).repository
companion object {
private const val TAG = "HabitViewModel"
/**
* Converts text to title-case: lowercase everything, then uppercase
* the first letter of each word. Handles parentheses properly so
* "GYM(LEGS)" → "Gym(Legs)" and "gym(legs)" → "Gym(Legs)".
*/
fun toTitleCase(input: String): String {
if (input.isBlank()) return input
val sb = StringBuilder()
var capitalizeNext = true
for (ch in input) {
when {
ch == '(' || ch == ')' || ch == ' ' || ch == '-' -> {
sb.append(ch)
capitalizeNext = true
}
capitalizeNext -> {
sb.append(ch.uppercaseChar())
capitalizeNext = false
}
else -> {
sb.append(ch.lowercaseChar())
}
}
}
return sb.toString()
}
}
// ── Activity Types (user-created, stored in Room) ───────
val allActivityTypes: StateFlow<List<ActivityType>> = repository.allActivityTypes
.stateIn(viewModelScope, SharingStarted.WhileSubscribed(5000), emptyList())
/**
* Adds a new activity type. [onResult] returns true on success, false if duplicate.
*/
fun addActivityType(name: String, onResult: (Boolean) -> Unit = {}) {
viewModelScope.launch {
val formatted = toTitleCase(name.trim())
if (formatted.isBlank()) {
onResult(false)
return@launch
}
val existing = repository.findActivityTypeByName(formatted)
if (existing != null) {
Log.w(TAG, "ACTIVITY TYPE DUPLICATE: '$formatted' already exists")
onResult(false)
return@launch
}
repository.addActivityType(ActivityType(name = formatted))
Log.i(TAG, "ACTIVITY TYPE CREATED: '$formatted'")
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
.stateIn(viewModelScope, SharingStarted.WhileSubscribed(5000), emptyList()) .stateIn(viewModelScope, SharingStarted.WhileSubscribed(5000), emptyList())
@@ -46,9 +118,17 @@ class HabitViewModel(application: Application) : AndroidViewModel(application) {
val todayLogs: StateFlow<List<HabitLog>> = repository.getLogsForDate(todayStart) val todayLogs: StateFlow<List<HabitLog>> = repository.getLogsForDate(todayStart)
.stateIn(viewModelScope, SharingStarted.WhileSubscribed(5000), emptyList()) .stateIn(viewModelScope, SharingStarted.WhileSubscribed(5000), emptyList())
/**
* Active habits still to-do today.
*/
val activeHabitsNotCompletedToday: StateFlow<List<Habit>> =
combine(allHabits, todayLogs) { habits, logs ->
val completedIds = logs.filter { it.completed }.map { it.habitId }.toSet()
habits.filter { it.isActive && !completedIds.contains(it.id) }
}.stateIn(viewModelScope, SharingStarted.WhileSubscribed(5000), emptyList())
// ── Selected habit detail ─────────────────────────────── // ── Selected habit detail ───────────────────────────────
private val _selectedHabitId = MutableStateFlow<Int?>(null) private val _selectedHabitId = MutableStateFlow<Int?>(null)
val selectedHabitId = _selectedHabitId.asStateFlow()
@OptIn(ExperimentalCoroutinesApi::class) @OptIn(ExperimentalCoroutinesApi::class)
val selectedHabit: StateFlow<Habit?> = _selectedHabitId val selectedHabit: StateFlow<Habit?> = _selectedHabitId
@@ -84,37 +164,22 @@ class HabitViewModel(application: Application) : AndroidViewModel(application) {
_longestStreak.value = 0 _longestStreak.value = 0
return@launch return@launch
} }
// Normalise dates to day-only & sort descending
val days = logs.map { normaliseToDay(it.date) }.distinct().sortedDescending() val days = logs.map { normaliseToDay(it.date) }.distinct().sortedDescending()
// Current streak: consecutive days ending today or yesterday
var current = 0 var current = 0
val today = todayStart val today = todayStart
val yesterday = today - 86_400_000L val yesterday = today - 86_400_000L
if (days.first() == today || days.first() == yesterday) { if (days.first() == today || days.first() == yesterday) {
var expected = days.first() var expected = days.first()
for (day in days) { for (day in days) {
if (day == expected) { if (day == expected) { current++; expected -= 86_400_000L } else break
current++
expected -= 86_400_000L
} else break
} }
} }
var longest = 1; var streak = 1
// Longest streak for (i in 1 until days.size) {
var longest = 1 if (days[i] == days[i - 1] - 86_400_000L) {
var streak = 1 streak++; if (streak > longest) longest = streak
val sorted = days.sortedDescending() } else streak = 1
for (i in 1 until sorted.size) {
if (sorted[i] == sorted[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
} }
@@ -131,19 +196,39 @@ class HabitViewModel(application: Application) : AndroidViewModel(application) {
} }
} }
// ── Duplicate check ─────────────────────────────────────
suspend fun isDuplicate(name: String, details: String, excludeId: Int? = null): Boolean {
val existing = repository.findDuplicate(name.trim(), details.trim())
return existing != null && existing.id != excludeId
}
// ── CRUD operations ───────────────────────────────────── // ── CRUD operations ─────────────────────────────────────
fun addHabit( fun addHabit(
name: String, name: String,
category: HabitCategory, details: String = "",
activityType: String = "",
targetFrequency: Int, targetFrequency: Int,
reminderEnabled: Boolean = true, reminderEnabled: Boolean = true,
reminderHour: Int = 9, reminderHour: Int = 9,
reminderMinute: Int = 0 reminderMinute: Int = 0,
onResult: (Boolean) -> Unit = {}
) { ) {
viewModelScope.launch { viewModelScope.launch {
val formattedName = toTitleCase(name.trim())
val formattedDetails = toTitleCase(details.trim())
val formattedType = toTitleCase(activityType.trim())
if (isDuplicate(formattedName, formattedDetails)) {
Log.w(TAG, "DUPLICATE BLOCKED: '$formattedName($formattedDetails)' already exists")
onResult(false)
return@launch
}
val habit = Habit( val habit = Habit(
name = name, name = formattedName,
category = category, details = formattedDetails,
activityType = formattedType,
startDate = System.currentTimeMillis(), startDate = System.currentTimeMillis(),
targetFrequency = targetFrequency, targetFrequency = targetFrequency,
reminderEnabled = reminderEnabled, reminderEnabled = reminderEnabled,
@@ -151,24 +236,32 @@ class HabitViewModel(application: Application) : AndroidViewModel(application) {
reminderMinute = reminderMinute reminderMinute = reminderMinute
) )
val id = repository.insertHabit(habit).toInt() val id = repository.insertHabit(habit).toInt()
Log.i(TAG, "HABIT CREATED: name='${habit.displayName}', type='$formattedType', frequency=${targetFrequency}x/week, id=$id")
if (reminderEnabled) { if (reminderEnabled) {
HabitNotificationScheduler.schedule( HabitNotificationScheduler.schedule(
getApplication(), id, name, reminderHour, reminderMinute getApplication(), id, habit.displayName, reminderHour, reminderMinute
) )
} }
onResult(true)
} }
} }
fun updateHabit(habit: Habit) { fun updateHabit(habit: Habit) {
viewModelScope.launch { viewModelScope.launch {
repository.updateHabit(habit) val updated = habit.copy(
if (habit.reminderEnabled) { name = toTitleCase(habit.name.trim()),
details = toTitleCase(habit.details.trim()),
activityType = toTitleCase(habit.activityType.trim())
)
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( HabitNotificationScheduler.schedule(
getApplication(), habit.id, habit.name, getApplication(), updated.id, updated.displayName,
habit.reminderHour, habit.reminderMinute updated.reminderHour, updated.reminderMinute
) )
} else { } else {
HabitNotificationScheduler.cancel(getApplication(), habit.id) HabitNotificationScheduler.cancel(getApplication(), updated.id)
} }
} }
} }
@@ -177,18 +270,22 @@ class HabitViewModel(application: Application) : AndroidViewModel(application) {
viewModelScope.launch { viewModelScope.launch {
HabitNotificationScheduler.cancel(getApplication(), habit.id) HabitNotificationScheduler.cancel(getApplication(), habit.id)
repository.deleteHabit(habit) repository.deleteHabit(habit)
Log.i(TAG, "HABIT DELETED: name='${habit.displayName}', id=${habit.id}")
} }
} }
// ── 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)
// Refresh streaks if currently viewing this habit if (existing == null) {
if (_selectedHabitId.value == habitId) { Log.i(TAG, "HABIT COMPLETED: habit='${habit?.displayName}' (id=$habitId), date=$todayStart")
computeStreaks(habitId) } else {
Log.i(TAG, "HABIT UNCOMPLETION: habit='${habit?.displayName}' (id=$habitId), date=$todayStart")
} }
// Celebrate streak milestones if (_selectedHabitId.value == habitId) computeStreaks(habitId)
checkStreakCelebration(habitId) checkStreakCelebration(habitId)
} }
} }
@@ -197,52 +294,46 @@ class HabitViewModel(application: Application) : AndroidViewModel(application) {
val logs = repository.getCompletedLogsDesc(habitId) val logs = repository.getCompletedLogsDesc(habitId)
if (logs.isEmpty()) return if (logs.isEmpty()) return
val days = logs.map { normaliseToDay(it.date) }.distinct().sortedDescending() val days = logs.map { normaliseToDay(it.date) }.distinct().sortedDescending()
val today = todayStart if (days.first() != todayStart) return
if (days.first() != today) return var streak = 0; var expected = todayStart
var streak = 0
var expected = today
for (day in days) { for (day in days) {
if (day == expected) { if (day == expected) { streak++; expected -= 86_400_000L } else break
streak++
expected -= 86_400_000L
} else break
}
if (streak > 0 && streak % 7 == 0) {
// Send a celebration notification
sendCelebration(habitId, streak)
} }
if (streak > 0 && streak % 7 == 0) sendCelebration(habitId, streak)
} }
private suspend fun sendCelebration(habitId: Int, streak: Int) { private suspend fun sendCelebration(habitId: Int, streak: Int) {
val habit = repository.getHabitByIdOnce(habitId) ?: return val habit = repository.getHabitByIdOnce(habitId) ?: return
val ctx = getApplication<HabitApp>() val ctx = getApplication<HabitApp>()
val notification = androidx.core.app.NotificationCompat.Builder(ctx, HabitApp.CHANNEL_ID) 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) .setSmallIcon(R.drawable.ic_launcher_foreground)
.setContentTitle("🎉 Streak Milestone!") .setContentTitle("Streak Milestone!")
.setContentText("Amazing! You've hit a $streak-day streak on \"${habit.name}\"!") .setContentText("$streak-day streak on \"${habit.displayName}\"!")
.setPriority(androidx.core.app.NotificationCompat.PRIORITY_HIGH) .setAutoCancel(true).build()
.setAutoCancel(true) } else {
.build() @Suppress("DEPRECATION")
Notification.Builder(ctx)
if (androidx.core.content.ContextCompat.checkSelfPermission( .setSmallIcon(R.drawable.ic_launcher_foreground)
ctx, android.Manifest.permission.POST_NOTIFICATIONS .setContentTitle("Streak Milestone!")
) == android.content.pm.PackageManager.PERMISSION_GRANTED .setContentText("$streak-day streak on \"${habit.displayName}\"!")
) { .setAutoCancel(true).build()
androidx.core.app.NotificationManagerCompat.from(ctx)
.notify(habitId + 10_000, notification)
} }
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()
cal.timeInMillis = millis cal.timeInMillis = millis
cal.set(Calendar.HOUR_OF_DAY, 0) cal.set(Calendar.HOUR_OF_DAY, 0); cal.set(Calendar.MINUTE, 0)
cal.set(Calendar.MINUTE, 0) 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
} }
} }
@@ -0,0 +1,17 @@
package com.example.madwellbeingapp
import org.junit.Test
import org.junit.Assert.*
/**
* Example local unit test, which will execute on the development machine (host).
*
* See [testing documentation](http://d.android.com/tools/testing).
*/
class ExampleUnitTest {
@Test
fun addition_isCorrect() {
assertEquals(4, 2 + 2)
}
}
+10
View File
@@ -23,3 +23,13 @@ kotlin.code.style=official
android.nonTransitiveRClass=true android.nonTransitiveRClass=true
# Allow KSP-generated Kotlin source sets with AGP built-in Kotlin # Allow KSP-generated Kotlin source sets with AGP built-in Kotlin
android.disallowKotlinSourceSets=false android.disallowKotlinSourceSets=false
android.defaults.buildfeatures.resvalues=true
android.sdk.defaultTargetSdkToCompileSdkIfUnset=false
android.enableAppCompileTimeRClass=false
android.usesSdkInManifest.disallowed=false
android.uniquePackageNames=false
android.dependency.useConstraints=true
android.r8.strictFullModeForKeepRules=false
android.r8.optimizedResourceShrinking=false
android.builtInKotlin=false
android.newDsl=false
+4 -6
View File
@@ -1,17 +1,16 @@
[versions] [versions]
agp = "8.13.2" agp = "9.0.1"
coreKtx = "1.10.1" coreKtx = "1.10.1"
junit = "4.13.2" junit = "4.13.2"
junitVersion = "1.1.5" junitVersion = "1.1.5"
espressoCore = "3.5.1" espressoCore = "3.5.1"
lifecycleRuntimeKtx = "2.6.1" lifecycleRuntimeKtx = "2.6.1"
activityCompose = "1.8.0" activityCompose = "1.8.0"
kotlin = "2.0.0" kotlin = "2.2.10"
composeBom = "2024.06.00" composeBom = "2024.06.00"
room = "2.6.1" room = "2.7.1"
navigationCompose = "2.7.7"
lifecycleViewmodelCompose = "2.6.1" lifecycleViewmodelCompose = "2.6.1"
ksp = "2.0.0-1.0.21" ksp = "2.3.2"
coreKtxVersion = "1.17.0" coreKtxVersion = "1.17.0"
[libraries] [libraries]
@@ -32,7 +31,6 @@ androidx-compose-material3 = { group = "androidx.compose.material3", name = "mat
androidx-room-runtime = { group = "androidx.room", name = "room-runtime", version.ref = "room" } androidx-room-runtime = { group = "androidx.room", name = "room-runtime", version.ref = "room" }
androidx-room-ktx = { group = "androidx.room", name = "room-ktx", version.ref = "room" } androidx-room-ktx = { group = "androidx.room", name = "room-ktx", version.ref = "room" }
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-navigation-compose = { group = "androidx.navigation", name = "navigation-compose", version.ref = "navigationCompose" }
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" }