feat: support meal photo URIs and improve UI events

- Add `photoUris` field to `MealEntry` and update Firestore rules.
- Implement `UiEvent` handling in `MainActivity` for navigation/links.
- Remove sensitive email data from error logs and clean up manifest.
This commit is contained in:
bleackstorm committed 2026-11-08 19:25:03 +01:00
1 parent f0487453c9
commit 87bbb448c2
34 files changed
+2026 -1170

No files matched your search

@@ -0,0 +1,9 @@
package com.example.ui.common
import android.content.Intent
sealed interface UiEvent {
data class ShowSnackbar(val message: String) : UiEvent
data class OpenUrl(val url: String) : UiEvent
data class StartActivity(val intent: Intent) : UiEvent
}
@@ -2,6 +2,7 @@ package com.example.ui.journal
import android.graphics.Bitmap
import androidx.compose.foundation.Image
import coil.compose.AsyncImage
import androidx.compose.foundation.background
import androidx.compose.foundation.clickable
import androidx.compose.foundation.layout.Arrangement
@@ -64,9 +65,10 @@ import com.example.data.model.HungerSatietyScale
import com.example.data.model.MealEntry
import com.example.data.model.MealType
import com.example.util.ImageUtils
import java.text.SimpleDateFormat
import java.util.Calendar
import java.util.Date
import java.time.Instant
import java.time.LocalDate
import java.time.ZoneId
import java.time.format.DateTimeFormatter
import java.util.Locale
@Composable
@@ -115,14 +117,10 @@ fun JournalScreen(
is MealsUiState.Success -> {
val meals = mealsUiState.meals
val todayCalendar = Calendar.getInstance().apply {
set(Calendar.HOUR_OF_DAY, 0)
set(Calendar.MINUTE, 0)
set(Calendar.SECOND, 0)
set(Calendar.MILLISECOND, 0)
}
val todayStartMillis = todayCalendar.timeInMillis
val todayEndMillis = todayStartMillis + (24L * 60 * 60 * 1000) - 1
val zoneId = ZoneId.systemDefault()
val todayLocalDate = LocalDate.now(zoneId)
val todayStartMillis = todayLocalDate.atStartOfDay(zoneId).toInstant().toEpochMilli()
val todayEndMillis = todayLocalDate.plusDays(1).atStartOfDay(zoneId).toInstant().toEpochMilli() - 1
val todayMeals = meals.filter { it.mealTimestamp in todayStartMillis..todayEndMillis }
LazyColumn(
@@ -236,9 +234,9 @@ fun JournalScreen(
@Composable
private fun DailyOverviewCard(todayMeals: List<MealEntry>) {
val dateFormat = remember { SimpleDateFormat("EEEE d MMMM", Locale.FRENCH) }
val dateFormatter = remember { DateTimeFormatter.ofPattern("EEEE d MMMM", Locale.FRENCH) }
val todayFormatted = remember {
dateFormat.format(Date()).replaceFirstChar {
dateFormatter.format(LocalDate.now()).replaceFirstChar {
if (it.isLowerCase()) it.titlecase(Locale.FRENCH) else it.toString()
}
}
@@ -338,7 +336,8 @@ private fun MealCardItem(
) {
var showMenu by remember { mutableStateOf(false) }
var showDeleteDialog by remember { mutableStateOf(false) }
val dateTimeFormat = remember { SimpleDateFormat("EEE d MMM yyyy • HH:mm", Locale.FRENCH) }
val dateTimeFormatter = remember { DateTimeFormatter.ofPattern("EEE d MMM yyyy • HH:mm", Locale.FRENCH) }
val zoneId = remember { ZoneId.systemDefault() }
val mealType = MealType.fromString(meal.mealType)
val parsedFoods = remember(meal.foodItemsSerialized) { meal.parsedFoodItems() }
@@ -397,7 +396,7 @@ private fun MealCardItem(
)
Spacer(modifier = Modifier.width(4.dp))
Text(
text = dateTimeFormat.format(Date(meal.mealTimestamp)).replaceFirstChar {
text = dateTimeFormatter.format(Instant.ofEpochMilli(meal.mealTimestamp).atZone(zoneId)).replaceFirstChar {
if (it.isLowerCase()) it.titlecase(Locale.FRENCH) else it.toString()
},
style = MaterialTheme.typography.bodySmall,
@@ -544,23 +543,20 @@ private fun MealCardItem(
}
// Photos Carousel
if (meal.photosBase64.isNotEmpty()) {
if (meal.displayPhotoUris.isNotEmpty()) {
Spacer(modifier = Modifier.height(14.dp))
LazyRow(
horizontalArrangement = Arrangement.spacedBy(8.dp)
) {
items(meal.photosBase64) { b64 ->
val bitmap: Bitmap? = remember(b64) { ImageUtils.base64ToBitmap(b64) }
if (bitmap != null) {
Image(
bitmap = bitmap.asImageBitmap(),
contentDescription = "Photo assiette",
modifier = Modifier
.size(76.dp)
.clip(RoundedCornerShape(12.dp)),
contentScale = ContentScale.Crop
)
}
items(meal.displayPhotoUris) { photoUri ->
AsyncImage(
model = photoUri,
contentDescription = "Photo du repas",
modifier = Modifier
.size(76.dp)
.clip(RoundedCornerShape(12.dp)),
contentScale = ContentScale.Crop
)
}
}
}
@@ -11,26 +11,33 @@ import com.example.data.model.DefaultFoodCatalog
import com.example.data.model.MealEntry
import com.example.data.model.MealFoodItem
import com.example.data.model.MealType
import com.example.data.repository.MealRepository
import com.example.data.preferences.GoogleSheetsPreferencesManager
import com.example.data.repository.MealRepository
import com.example.domain.CsvExportUseCase
import com.example.domain.GoogleSheetsSyncUseCase
import com.example.domain.SheetsSyncResult
import com.example.notification.MealNotificationManager
import com.example.ui.common.UiEvent
import com.example.ui.theme.AppThemeMode
import com.example.util.CsvExporter
import com.example.util.GoogleSheetsAuthHelper
import com.example.util.GoogleSheetsSyncService
import com.google.android.gms.auth.UserRecoverableAuthException
import com.example.util.CsvImportResult
import com.google.firebase.auth.FirebaseAuth
import com.google.firebase.firestore.FirebaseFirestoreException
import kotlinx.coroutines.CancellationException
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.channels.Channel
import kotlinx.coroutines.flow.MutableStateFlow
import kotlinx.coroutines.flow.SharingStarted
import kotlinx.coroutines.flow.StateFlow
import kotlinx.coroutines.flow.asStateFlow
import kotlinx.coroutines.flow.catch
import kotlinx.coroutines.flow.flowOn
import kotlinx.coroutines.flow.map
import kotlinx.coroutines.flow.receiveAsFlow
import kotlinx.coroutines.flow.stateIn
import kotlinx.coroutines.launch
import java.text.SimpleDateFormat
import java.util.Calendar
import java.time.LocalDate
import java.time.ZoneId
import java.time.format.DateTimeFormatter
import java.util.Locale
sealed interface MealsUiState {
@@ -62,12 +69,36 @@ data class WeeklyStats(
val optimalZonePercentage: Int,
val totalMealsLast7Days: Int,
val mealTypeDistribution: Map<MealType, Int>
)
) {
companion object {
fun empty(): WeeklyStats = WeeklyStats(
dailyStats = emptyList(),
averageSatiety = 0f,
averageHunger = 0f,
optimalZonePercentage = 0,
totalMealsLast7Days = 0,
mealTypeDistribution = emptyMap()
)
}
}
class MealViewModel(application: Application) : AndroidViewModel(application) {
private val repository = MealRepository(application)
private val context = application.applicationContext
private val sheetsPrefs = GoogleSheetsPreferencesManager.getInstance(application)
// Domain Use Cases
private val sheetsSyncUseCase = GoogleSheetsSyncUseCase(context, repository, sheetsPrefs)
private val csvExportUseCase = CsvExportUseCase(context)
// UDF Event Channel
private val _uiEventChannel = Channel<UiEvent>(Channel.BUFFERED)
val uiEvents = _uiEventChannel.receiveAsFlow()
fun emitEvent(event: UiEvent) {
viewModelScope.launch { _uiEventChannel.send(event) }
}
val mealsState: StateFlow<MealsUiState> = repository.observeMeals()
.map<List<MealEntry>, MealsUiState> { meals ->
@@ -87,6 +118,16 @@ class MealViewModel(application: Application) : AndroidViewModel(application) {
initialValue = MealsUiState.Loading
)
// Asynchronous background computation of WeeklyStats via Dispatchers.Default
val weeklyStats: StateFlow<WeeklyStats> = repository.observeMeals()
.map { meals -> computeWeeklyStats(meals) }
.flowOn(Dispatchers.Default)
.stateIn(
scope = viewModelScope,
started = SharingStarted.WhileSubscribed(5000L),
initialValue = WeeklyStats.empty()
)
val customFoods: StateFlow<List<CustomFoodEntry>> = repository.observeCustomFoods()
.catch { error ->
val firestoreError = generateSequence(error) { it.cause }
@@ -104,8 +145,6 @@ class MealViewModel(application: Application) : AndroidViewModel(application) {
private val _themeMode = MutableStateFlow(AppThemeMode.DARK)
val themeMode: StateFlow<AppThemeMode> = _themeMode.asStateFlow()
private val sheetsPrefs = GoogleSheetsPreferencesManager.getInstance(application)
private val _sheetsUiState = MutableStateFlow<GoogleSheetsUiState>(
if (sheetsPrefs.lastSyncTimestamp > 0 && sheetsPrefs.spreadsheetUrl != null) {
GoogleSheetsUiState.Success(
@@ -170,7 +209,8 @@ class MealViewModel(application: Application) : AndroidViewModel(application) {
satietyAfter: Int,
note: String,
foodItems: List<MealFoodItem>,
photosBase64: List<String>,
photoUris: List<String> = emptyList(),
photosBase64: List<String> = emptyList(),
onSuccess: () -> Unit = {},
onError: (String) -> Unit = {}
) {
@@ -183,14 +223,34 @@ class MealViewModel(application: Application) : AndroidViewModel(application) {
satietyAfter = satietyAfter.coerceIn(1, 10),
note = note.trim(),
foodItemsSerialized = foodItems.map { it.serialize() }.take(30),
photosBase64 = photosBase64
photoUris = photoUris.ifEmpty { photosBase64 },
photosBase64 = emptyList()
)
val result = repository.addMeal(entry)
if (result.isSuccess) {
onSuccess()
emitEvent(UiEvent.ShowSnackbar("Repas enregistré avec succès ✨"))
triggerAutoSheetsSyncIfNeeded()
} else {
onError(result.exceptionOrNull()?.localizedMessage ?: "Erreur d'enregistrement")
val err = result.exceptionOrNull()?.localizedMessage ?: "Erreur d'enregistrement"
onError(err)
emitEvent(UiEvent.ShowSnackbar(err))
}
}
}
fun signOut(context: Context, onComplete: () -> Unit = {}) {
viewModelScope.launch {
try {
FirebaseAuth.getInstance().signOut()
val credManager = androidx.credentials.CredentialManager.create(context)
credManager.clearCredentialState(androidx.credentials.ClearCredentialStateRequest())
} catch (e: Exception) {
if (e is CancellationException) throw e
} finally {
disconnectGoogleSheets()
onComplete()
emitEvent(UiEvent.ShowSnackbar("Mode local actif • Déconnecté"))
}
}
}
@@ -211,9 +271,12 @@ class MealViewModel(application: Application) : AndroidViewModel(application) {
val result = repository.updateMeal(sanitizedMeal)
if (result.isSuccess) {
onSuccess()
emitEvent(UiEvent.ShowSnackbar("Repas mis à jour ✨"))
triggerAutoSheetsSyncIfNeeded()
} else {
onError(result.exceptionOrNull()?.localizedMessage ?: "Erreur de mise à jour")
val err = result.exceptionOrNull()?.localizedMessage ?: "Erreur de mise à jour"
onError(err)
emitEvent(UiEvent.ShowSnackbar(err))
}
}
}
@@ -227,9 +290,12 @@ class MealViewModel(application: Application) : AndroidViewModel(application) {
val result = repository.deleteMeal(mealId)
if (result.isSuccess) {
onSuccess()
emitEvent(UiEvent.ShowSnackbar("Repas supprimé"))
triggerAutoSheetsSyncIfNeeded()
} else {
onError(result.exceptionOrNull()?.localizedMessage ?: "Erreur de suppression")
val err = result.exceptionOrNull()?.localizedMessage ?: "Erreur de suppression"
onError(err)
emitEvent(UiEvent.ShowSnackbar(err))
}
}
}
@@ -237,26 +303,9 @@ class MealViewModel(application: Application) : AndroidViewModel(application) {
private fun triggerAutoSheetsSyncIfNeeded() {
if (!sheetsPrefs.isAutoSyncEnabled) return
viewModelScope.launch {
try {
val tokenResult = GoogleSheetsAuthHelper.getAccessToken(context)
val token = tokenResult.getOrNull() ?: return@launch
val sheetResult = GoogleSheetsSyncService.getOrCreateSpreadsheet(token, sheetsPrefs.spreadsheetId)
val (id, url) = sheetResult.getOrNull() ?: return@launch
sheetsPrefs.spreadsheetId = id
sheetsPrefs.spreadsheetUrl = url
_spreadsheetUrl.value = url
val currentMeals = repository.getAllMealsSnapshot()
val syncResult = GoogleSheetsSyncService.syncMeals(token, id, currentMeals)
if (syncResult.isSuccess) {
val res = syncResult.getOrThrow()
sheetsPrefs.lastSyncTimestamp = res.timestamp
sheetsPrefs.lastSyncCount = res.mealsCount
sheetsPrefs.lastSyncStatus = "Synchronisé automatiquement"
_sheetsUiState.value = GoogleSheetsUiState.Success(res.spreadsheetUrl, res.mealsCount, res.timestamp)
}
} catch (_: Exception) {
// Non-blocking background sync
sheetsSyncUseCase.executeAutoSyncQuietly()?.let { res ->
_spreadsheetUrl.value = res.spreadsheetUrl
_sheetsUiState.value = GoogleSheetsUiState.Success(res.spreadsheetUrl, res.mealsCount, res.timestamp)
}
}
}
@@ -267,51 +316,22 @@ class MealViewModel(application: Application) : AndroidViewModel(application) {
) {
viewModelScope.launch {
_sheetsUiState.value = GoogleSheetsUiState.Syncing
val tokenResult = GoogleSheetsAuthHelper.getAccessToken(context)
if (tokenResult.isFailure) {
val exception = tokenResult.exceptionOrNull()
if (exception is UserRecoverableAuthException) {
val intent = exception.intent
_sheetsUiState.value = GoogleSheetsUiState.Error(
"Autorisation requise pour Google Sheets & Drive",
recoverableIntent = intent
)
onError("Autorisation requise pour Google Sheets & Drive", intent)
} else {
val msg = exception?.localizedMessage ?: "Impossible d'obtenir l'autorisation Google"
_sheetsUiState.value = GoogleSheetsUiState.Error(msg)
onError(msg, null)
when (val result = sheetsSyncUseCase.execute()) {
is SheetsSyncResult.Success -> {
_spreadsheetUrl.value = result.url
_sheetsUiState.value = GoogleSheetsUiState.Success(result.url, result.count, result.timestamp)
onSuccess(result.url, result.count)
emitEvent(UiEvent.ShowSnackbar("Synchronisé avec succès vers Google Sheets (${result.count} repas) 📊"))
}
is SheetsSyncResult.RecoverableAuth -> {
_sheetsUiState.value = GoogleSheetsUiState.Error(result.message, result.intent)
onError(result.message, result.intent)
}
is SheetsSyncResult.Failure -> {
_sheetsUiState.value = GoogleSheetsUiState.Error(result.message)
onError(result.message, null)
emitEvent(UiEvent.ShowSnackbar(result.message))
}
return@launch
}
val token = tokenResult.getOrThrow()
val spreadsheetResult = GoogleSheetsSyncService.getOrCreateSpreadsheet(token, sheetsPrefs.spreadsheetId)
if (spreadsheetResult.isFailure) {
val err = spreadsheetResult.exceptionOrNull()?.localizedMessage ?: "Erreur de création de la feuille"
_sheetsUiState.value = GoogleSheetsUiState.Error(err)
onError(err, null)
return@launch
}
val (id, url) = spreadsheetResult.getOrThrow()
sheetsPrefs.spreadsheetId = id
sheetsPrefs.spreadsheetUrl = url
_spreadsheetUrl.value = url
val currentMeals = repository.getAllMealsSnapshot()
val syncResult = GoogleSheetsSyncService.syncMeals(token, id, currentMeals)
if (syncResult.isSuccess) {
val res = syncResult.getOrThrow()
sheetsPrefs.lastSyncTimestamp = res.timestamp
sheetsPrefs.lastSyncCount = res.mealsCount
sheetsPrefs.lastSyncStatus = "Synchronisé avec succès"
_sheetsUiState.value = GoogleSheetsUiState.Success(res.spreadsheetUrl, res.mealsCount, res.timestamp)
onSuccess(res.spreadsheetUrl, res.mealsCount)
} else {
val err = syncResult.exceptionOrNull()?.localizedMessage ?: "Erreur lors de la synchronisation des repas"
_sheetsUiState.value = GoogleSheetsUiState.Error(err)
onError(err, null)
}
}
}
@@ -323,24 +343,47 @@ class MealViewModel(application: Application) : AndroidViewModel(application) {
onError: (String) -> Unit
) {
viewModelScope.launch {
val result = CsvExporter.writeCsvToUri(context, targetUri, meals)
val result = csvExportUseCase.writeToUri(targetUri, meals)
result.fold(
onSuccess = { count -> onSuccess(count) },
onFailure = { err -> onError(err.localizedMessage ?: "Erreur lors de l'export CSV") }
onSuccess = { count ->
onSuccess(count)
emitEvent(UiEvent.ShowSnackbar("Fichier CSV enregistré ($count repas) ✨"))
},
onFailure = { err ->
val msg = err.localizedMessage ?: "Erreur lors de l'export CSV"
onError(msg)
emitEvent(UiEvent.ShowSnackbar(msg))
}
)
}
}
fun importCsvFromUri(
sourceUri: Uri,
onSuccess: (com.example.util.CsvImportResult) -> Unit,
onSuccess: (CsvImportResult) -> Unit,
onError: (String) -> Unit
) {
viewModelScope.launch {
val result = repository.importMealsFromCsv(context, sourceUri)
result.fold(
onSuccess = { importResult -> onSuccess(importResult) },
onFailure = { err -> onError(err.localizedMessage ?: "Erreur lors de l'import du fichier CSV") }
onSuccess = { importResult ->
onSuccess(importResult)
val count = importResult.importedMeals.size
val skipped = importResult.skippedDuplicatesCount
val newFoods = importResult.newFoodItems.size
val msg = buildString {
append("$count repas importé${if (count > 1) "s" else ""}")
if (skipped > 0) append(" ($skipped doublon${if (skipped > 1) "s" else ""} ignoré${if (skipped > 1) "s" else ""})")
if (newFoods > 0) append(" • $newFoods nouvel aliment ajouté")
append(" ✨")
}
emitEvent(UiEvent.ShowSnackbar(msg))
},
onFailure = { err ->
val msg = err.localizedMessage ?: "Erreur lors de l'import du fichier CSV"
onError(msg)
emitEvent(UiEvent.ShowSnackbar(msg))
}
)
}
}
@@ -352,8 +395,15 @@ class MealViewModel(application: Application) : AndroidViewModel(application) {
viewModelScope.launch {
val result = repository.syncCloudToLocal()
result.fold(
onSuccess = { count -> onSuccess(count) },
onFailure = { err -> onError(err.localizedMessage ?: "Erreur lors de la synchronisation") }
onSuccess = { count ->
onSuccess(count)
emitEvent(UiEvent.ShowSnackbar("Compte lié ($count repas Cloud synchronisés) ☁️"))
},
onFailure = { err ->
val msg = err.localizedMessage ?: "Erreur lors de la synchronisation"
onError(msg)
emitEvent(UiEvent.ShowSnackbar(msg))
}
)
}
}
@@ -365,10 +415,16 @@ class MealViewModel(application: Application) : AndroidViewModel(application) {
onError: (String) -> Unit
) {
viewModelScope.launch {
val result = CsvExporter.shareCsvFile(activityContext, meals)
val result = csvExportUseCase.createShareIntent(activityContext, meals)
result.fold(
onSuccess = { chooserIntent -> onIntentReady(chooserIntent) },
onFailure = { err -> onError(err.localizedMessage ?: "Impossible de préparer le partage CSV") }
onSuccess = { chooserIntent ->
onIntentReady(chooserIntent)
},
onFailure = { err ->
val msg = err.localizedMessage ?: "Impossible de préparer le partage CSV"
onError(msg)
emitEvent(UiEvent.ShowSnackbar(msg))
}
)
}
}
@@ -390,85 +446,10 @@ class MealViewModel(application: Application) : AndroidViewModel(application) {
fun triggerTestNotification(mealType: MealType) {
MealNotificationManager.showMealNotification(context, mealType)
emitEvent(UiEvent.ShowSnackbar("Notification de rappel envoyée !"))
}
fun computeWeeklyStats(meals: List<MealEntry>): WeeklyStats {
val now = System.currentTimeMillis()
val sevenDaysAgo = now - (7L * 24 * 60 * 60 * 1000)
val endOfToday = Calendar.getInstance().apply {
set(Calendar.HOUR_OF_DAY, 23)
set(Calendar.MINUTE, 59)
set(Calendar.SECOND, 59)
set(Calendar.MILLISECOND, 999)
}.timeInMillis
val recentMeals = meals.filter { it.mealTimestamp in sevenDaysAgo..endOfToday }
val dayFormat = SimpleDateFormat("EEE", Locale.FRENCH)
val fullDayFormat = SimpleDateFormat("d MMM", Locale.FRENCH)
val daysList = mutableListOf<DayStat>()
for (i in 6 downTo 0) {
val dayCal = Calendar.getInstance().apply {
timeInMillis = now
add(Calendar.DAY_OF_YEAR, -i)
set(Calendar.HOUR_OF_DAY, 0)
set(Calendar.MINUTE, 0)
set(Calendar.SECOND, 0)
set(Calendar.MILLISECOND, 0)
}
val startOfDay = dayCal.timeInMillis
val endOfDay = startOfDay + (24 * 60 * 60 * 1000) - 1
val dayMeals = meals.filter { it.mealTimestamp in startOfDay..endOfDay }
val avgSatiety = if (dayMeals.isNotEmpty()) {
dayMeals.map { it.satietyAfter }.average().toFloat()
} else 0f
val avgHunger = if (dayMeals.isNotEmpty()) {
dayMeals.map { it.hungerBefore }.average().toFloat()
} else 0f
daysList.add(
DayStat(
dayLabel = fullDayFormat.format(dayCal.time),
dayShortName = dayFormat.format(dayCal.time).replace(".", "").replaceFirstChar {
if (it.isLowerCase()) it.titlecase(Locale.FRENCH) else it.toString()
},
timestampMillis = startOfDay,
avgSatiety = avgSatiety,
avgHunger = avgHunger,
mealCount = dayMeals.size
)
)
}
val allRecentSatieties = recentMeals.map { it.satietyAfter }
val allRecentHungers = recentMeals.map { it.hungerBefore }
val avgSatiety = if (allRecentSatieties.isNotEmpty()) allRecentSatieties.average().toFloat() else 0f
val avgHunger = if (allRecentHungers.isNotEmpty()) allRecentHungers.average().toFloat() else 0f
val optimalCount = recentMeals.count { it.satietyAfter in 6..8 }
val optimalPercentage = if (recentMeals.isNotEmpty()) {
((optimalCount.toFloat() / recentMeals.size) * 100).toInt()
} else 0
val distribution = mutableMapOf<MealType, Int>()
MealType.entries.forEach { type ->
distribution[type] = recentMeals.count { it.mealType.equals(type.name, ignoreCase = true) }
}
return WeeklyStats(
dailyStats = daysList,
averageSatiety = avgSatiety,
averageHunger = avgHunger,
optimalZonePercentage = optimalPercentage,
totalMealsLast7Days = recentMeals.size,
mealTypeDistribution = distribution
)
fun computeWeeklyStats(meals: List<MealEntry>, zoneId: ZoneId = ZoneId.systemDefault()): WeeklyStats {
return com.example.domain.WeeklyStatsCalculator.computeWeeklyStats(meals, zoneId)
}
}
@@ -1,67 +1,33 @@
package com.example.ui.meal
import android.graphics.Bitmap
import android.net.Uri
import androidx.activity.compose.rememberLauncherForActivityResult
import androidx.activity.result.PickVisualMediaRequest
import androidx.activity.result.contract.ActivityResultContracts
import androidx.compose.foundation.Image
import androidx.compose.foundation.background
import androidx.compose.foundation.border
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.ExperimentalLayoutApi
import androidx.compose.foundation.layout.FlowRow
import androidx.compose.foundation.layout.Row
import androidx.compose.foundation.layout.Spacer
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.LazyRow
import androidx.compose.foundation.lazy.items
import androidx.compose.foundation.rememberScrollState
import androidx.compose.foundation.shape.CircleShape
import androidx.compose.foundation.shape.RoundedCornerShape
import androidx.compose.foundation.text.KeyboardOptions
import androidx.compose.foundation.verticalScroll
import androidx.compose.material.icons.Icons
import androidx.compose.material.icons.filled.Add
import androidx.compose.material.icons.filled.AddAPhoto
import androidx.compose.material.icons.filled.CalendarMonth
import androidx.compose.material.icons.filled.Close
import androidx.compose.material.icons.filled.RestaurantMenu
import androidx.compose.material.icons.filled.Scale
import androidx.compose.material.icons.filled.Schedule
import androidx.compose.material3.AlertDialog
import androidx.compose.material3.Button
import androidx.compose.material3.ButtonDefaults
import androidx.compose.material3.CircularProgressIndicator
import androidx.compose.material3.DatePicker
import androidx.compose.material3.DatePickerDialog
import androidx.compose.material3.ExperimentalMaterial3Api
import androidx.compose.material3.FilterChip
import androidx.compose.material3.FilterChipDefaults
import androidx.compose.material3.Icon
import androidx.compose.material3.IconButton
import androidx.compose.material3.MaterialTheme
import androidx.compose.material3.ModalBottomSheet
import androidx.compose.material3.OutlinedButton
import androidx.compose.material3.OutlinedTextField
import androidx.compose.material3.Slider
import androidx.compose.material3.SliderDefaults
import androidx.compose.material3.SuggestionChip
import androidx.compose.material3.SuggestionChipDefaults
import androidx.compose.material3.Surface
import androidx.compose.material3.Text
import androidx.compose.material3.TextButton
import androidx.compose.material3.TimePicker
import androidx.compose.material3.rememberDatePickerState
import androidx.compose.material3.rememberModalBottomSheetState
import androidx.compose.material3.rememberTimePickerState
import androidx.compose.runtime.Composable
import androidx.compose.runtime.getValue
import androidx.compose.runtime.mutableIntStateOf
@@ -70,36 +36,30 @@ import androidx.compose.runtime.mutableStateListOf
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.remember
import androidx.compose.runtime.rememberCoroutineScope
import androidx.compose.runtime.saveable.rememberSaveable
import androidx.compose.runtime.setValue
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.draw.clip
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.graphics.asImageBitmap
import androidx.compose.ui.layout.ContentScale
import androidx.compose.ui.platform.LocalContext
import androidx.compose.ui.platform.testTag
import androidx.compose.ui.text.font.FontWeight
import androidx.compose.ui.text.input.KeyboardType
import androidx.compose.ui.text.style.TextAlign
import androidx.compose.ui.unit.dp
import com.example.data.model.CustomFoodEntry
import com.example.data.model.DefaultFoodCatalog
import com.example.data.model.FoodUnit
import com.example.data.model.HungerSatietyScale
import com.example.data.model.MealEntry
import com.example.data.model.MealFoodItem
import com.example.data.model.MealType
import com.example.ui.meal.components.FoodItemBuilderSection
import com.example.ui.meal.components.MealDateTimePicker
import com.example.ui.meal.components.MealHungerSatietySection
import com.example.ui.meal.components.MealPhotosSection
import com.example.ui.meal.components.MealTypeSelector
import com.example.util.ImageUtils
import kotlinx.coroutines.launch
import java.text.SimpleDateFormat
import java.util.Calendar
import java.util.Date
import java.util.Locale
import java.util.TimeZone
import kotlin.math.roundToInt
@OptIn(ExperimentalMaterial3Api::class, ExperimentalLayoutApi::class)
@OptIn(ExperimentalMaterial3Api::class)
@Composable
fun MealEntrySheet(
initialMeal: MealEntry? = null,
@@ -113,21 +73,22 @@ fun MealEntrySheet(
val context = LocalContext.current
val coroutineScope = rememberCoroutineScope()
var selectedType by remember {
var selectedType by rememberSaveable {
mutableStateOf(if (initialMeal != null) MealType.fromString(initialMeal.mealType) else defaultMealType)
}
var mealTimestamp by remember {
var mealTimestamp by rememberSaveable {
mutableLongStateOf(initialMeal?.mealTimestamp ?: System.currentTimeMillis())
}
var hungerLevel by remember {
var hungerLevel by rememberSaveable {
mutableIntStateOf((initialMeal?.hungerBefore ?: 5).coerceIn(1, 10))
}
var satietyLevel by remember {
var satietyLevel by rememberSaveable {
mutableIntStateOf((initialMeal?.satietyAfter ?: 7).coerceIn(1, 10))
}
var globalNoteText by remember {
var globalNoteText by rememberSaveable {
mutableStateOf(initialMeal?.note ?: "")
}
val foodItemsList = remember {
mutableStateListOf<MealFoodItem>().apply {
if (initialMeal != null) {
@@ -135,18 +96,18 @@ fun MealEntrySheet(
}
}
}
val photosBase64List = remember {
val photoUrisList = remember {
mutableStateListOf<String>().apply {
if (initialMeal != null) {
addAll(initialMeal.photosBase64)
addAll(initialMeal.displayPhotoUris)
}
}
}
// Current food builder state
var foodNameInput by remember { mutableStateOf("") }
var foodWeightInput by remember { mutableStateOf("") }
var selectedFoodUnit by remember { mutableStateOf(FoodUnit.G) }
// Current food builder input state
var foodNameInput by rememberSaveable { mutableStateOf("") }
var foodWeightInput by rememberSaveable { mutableStateOf("") }
var selectedFoodUnit by rememberSaveable { mutableStateOf(FoodUnit.G) }
// Combine custom foods (user enriched) + built-in catalog
val mergedCatalog = remember(customFoods) {
@@ -190,7 +151,6 @@ fun MealEntrySheet(
weight = parsedWeight,
unit = selectedFoodUnit
)
// Replace if same food already added, or append
val existingIndex = foodItemsList.indexOfFirst { it.name.equals(cleanName, ignoreCase = true) }
if (existingIndex >= 0) {
foodItemsList[existingIndex] = newItem
@@ -207,8 +167,6 @@ fun MealEntrySheet(
}
var isProcessingPhoto by remember { mutableStateOf(false) }
var showDatePicker by remember { mutableStateOf(false) }
var showTimePicker by remember { mutableStateOf(false) }
val photoPickerLauncher = rememberLauncherForActivityResult(
contract = ActivityResultContracts.PickVisualMedia()
@@ -216,18 +174,15 @@ fun MealEntrySheet(
if (uri != null) {
isProcessingPhoto = true
coroutineScope.launch {
val b64 = ImageUtils.uriToBase64(context, uri)
if (b64 != null && photosBase64List.size < 4) {
photosBase64List.add(b64)
val savedUri = ImageUtils.saveImageToPrivateStorage(context, uri)
if (savedUri != null && photoUrisList.size < 4) {
photoUrisList.add(savedUri)
}
isProcessingPhoto = false
}
}
}
val dateFormat = remember { SimpleDateFormat("EEE d MMM yyyy", Locale.FRENCH) }
val timeFormat = remember { SimpleDateFormat("HH:mm", Locale.FRENCH) }
ModalBottomSheet(
onDismissRequest = onDismiss,
sheetState = sheetState,
@@ -273,518 +228,77 @@ fun MealEntrySheet(
Spacer(modifier = Modifier.height(16.dp))
// Meal Type Chips
Text(
text = "Type de repas",
style = MaterialTheme.typography.labelLarge,
color = MaterialTheme.colorScheme.primary
// Subcomponent 1: Meal Type Chips
MealTypeSelector(
selectedType = selectedType,
onTypeSelected = { selectedType = it }
)
Spacer(modifier = Modifier.height(8.dp))
Row(
modifier = Modifier.fillMaxWidth(),
horizontalArrangement = Arrangement.spacedBy(8.dp)
) {
MealType.entries.forEach { type ->
val isSelected = selectedType == type
FilterChip(
selected = isSelected,
onClick = { selectedType = type },
label = {
Text(
text = type.displayName,
style = MaterialTheme.typography.labelMedium
)
},
colors = FilterChipDefaults.filterChipColors(
selectedContainerColor = MaterialTheme.colorScheme.primaryContainer,
selectedLabelColor = MaterialTheme.colorScheme.onPrimaryContainer
)
)
}
}
Spacer(modifier = Modifier.height(16.dp))
// Date & Time Picker Section
Row(
modifier = Modifier.fillMaxWidth(),
horizontalArrangement = Arrangement.SpaceBetween,
verticalAlignment = Alignment.CenterVertically
) {
Text(
text = "Date et heure du repas",
style = MaterialTheme.typography.labelLarge,
color = MaterialTheme.colorScheme.primary
)
Row(horizontalArrangement = Arrangement.spacedBy(8.dp)) {
Text(
text = "Maintenant",
style = MaterialTheme.typography.labelSmall,
color = MaterialTheme.colorScheme.secondary,
modifier = Modifier
.clip(RoundedCornerShape(6.dp))
.clickable { mealTimestamp = System.currentTimeMillis() }
.padding(horizontal = 6.dp, vertical = 2.dp)
)
Text(
text = "Hier",
style = MaterialTheme.typography.labelSmall,
color = MaterialTheme.colorScheme.secondary,
modifier = Modifier
.clip(RoundedCornerShape(6.dp))
.clickable {
val cal = Calendar.getInstance().apply {
timeInMillis = mealTimestamp
add(Calendar.DAY_OF_YEAR, -1)
}
mealTimestamp = cal.timeInMillis
}
.padding(horizontal = 6.dp, vertical = 2.dp)
)
}
}
Spacer(modifier = Modifier.height(8.dp))
Row(
modifier = Modifier.fillMaxWidth(),
horizontalArrangement = Arrangement.spacedBy(10.dp)
) {
OutlinedButton(
onClick = { showDatePicker = true },
modifier = Modifier
.weight(1.3f)
.testTag("edit_date_button"),
shape = RoundedCornerShape(12.dp)
) {
Icon(
imageVector = Icons.Default.CalendarMonth,
contentDescription = "Changer la date",
modifier = Modifier.size(18.dp),
tint = MaterialTheme.colorScheme.primary
)
Spacer(modifier = Modifier.width(8.dp))
Text(
text = dateFormat.format(Date(mealTimestamp)).replaceFirstChar {
if (it.isLowerCase()) it.titlecase(Locale.FRENCH) else it.toString()
},
style = MaterialTheme.typography.bodyMedium,
color = MaterialTheme.colorScheme.onSurface
)
}
OutlinedButton(
onClick = { showTimePicker = true },
modifier = Modifier
.weight(0.9f)
.testTag("edit_time_button"),
shape = RoundedCornerShape(12.dp)
) {
Icon(
imageVector = Icons.Default.Schedule,
contentDescription = "Changer l'heure",
modifier = Modifier.size(18.dp),
tint = MaterialTheme.colorScheme.primary
)
Spacer(modifier = Modifier.width(8.dp))
Text(
text = timeFormat.format(Date(mealTimestamp)),
style = MaterialTheme.typography.bodyMedium,
color = MaterialTheme.colorScheme.onSurface
)
}
}
// Subcomponent 2: Date & Time Picker
MealDateTimePicker(
mealTimestamp = mealTimestamp,
onTimestampChanged = { mealTimestamp = it }
)
Spacer(modifier = Modifier.height(20.dp))
// Photos Section
Text(
text = "Photos de l'assiette (${photosBase64List.size}/4)",
style = MaterialTheme.typography.labelLarge,
color = MaterialTheme.colorScheme.primary
)
Spacer(modifier = Modifier.height(8.dp))
LazyRow(
horizontalArrangement = Arrangement.spacedBy(10.dp),
verticalAlignment = Alignment.CenterVertically
) {
if (photosBase64List.size < 4) {
item {
Surface(
modifier = Modifier
.size(84.dp)
.clip(RoundedCornerShape(14.dp))
.border(
width = 1.dp,
color = MaterialTheme.colorScheme.outline.copy(alpha = 0.5f),
shape = RoundedCornerShape(14.dp)
)
.clickable(enabled = !isProcessingPhoto) {
photoPickerLauncher.launch(
PickVisualMediaRequest(ActivityResultContracts.PickVisualMedia.ImageOnly)
)
}
.testTag("add_photo_button"),
color = MaterialTheme.colorScheme.surfaceVariant.copy(alpha = 0.4f)
) {
Box(contentAlignment = Alignment.Center) {
if (isProcessingPhoto) {
CircularProgressIndicator(
modifier = Modifier.size(24.dp),
strokeWidth = 2.dp,
color = MaterialTheme.colorScheme.primary
)
} else {
Column(horizontalAlignment = Alignment.CenterHorizontally) {
Icon(
imageVector = Icons.Default.AddAPhoto,
contentDescription = "Ajouter une photo",
tint = MaterialTheme.colorScheme.primary,
modifier = Modifier.size(24.dp)
)
Spacer(modifier = Modifier.height(4.dp))
Text(
text = "Ajouter",
style = MaterialTheme.typography.labelSmall,
color = MaterialTheme.colorScheme.onSurfaceVariant
)
}
}
}
}
}
// Subcomponent 3: Photos Section
MealPhotosSection(
photoUris = photoUrisList,
isProcessingPhoto = isProcessingPhoto,
onAddPhotoClick = {
photoPickerLauncher.launch(
PickVisualMediaRequest(ActivityResultContracts.PickVisualMedia.ImageOnly)
)
},
onDeletePhotoClick = { photoUri ->
ImageUtils.deletePhotoFile(photoUri)
photoUrisList.remove(photoUri)
}
items(photosBase64List) { b64 ->
val bitmap: Bitmap? = remember(b64) { ImageUtils.base64ToBitmap(b64) }
Box(
modifier = Modifier
.size(84.dp)
.clip(RoundedCornerShape(14.dp))
) {
if (bitmap != null) {
Image(
bitmap = bitmap.asImageBitmap(),
contentDescription = "Photo assiette",
modifier = Modifier.matchParentSize(),
contentScale = ContentScale.Crop
)
} else {
Box(
modifier = Modifier
.matchParentSize()
.background(MaterialTheme.colorScheme.surfaceVariant)
)
}
Surface(
modifier = Modifier
.align(Alignment.TopEnd)
.padding(4.dp)
.size(22.dp)
.clip(CircleShape)
.clickable { photosBase64List.remove(b64) },
color = Color.Black.copy(alpha = 0.7f)
) {
Icon(
imageVector = Icons.Default.Close,
contentDescription = "Supprimer photo",
tint = Color.White,
modifier = Modifier.padding(2.dp)
)
}
}
}
}
Spacer(modifier = Modifier.height(22.dp))
// 1. Hunger Stepped Slider (1 to 10)
SteppedScaleTenSlider(
title = "1. Faim avant le repas",
currentValue = hungerLevel,
accentColor = MaterialTheme.colorScheme.secondary,
onValueChange = { hungerLevel = it },
description = HungerSatietyScale.getHungerLabel(hungerLevel),
sliderTag = "hunger_slider_10"
)
Spacer(modifier = Modifier.height(18.dp))
// 2. Satiety Stepped Slider (1 to 10)
SteppedScaleTenSlider(
title = "2. Satiété après le repas",
currentValue = satietyLevel,
accentColor = MaterialTheme.colorScheme.primary,
onValueChange = { satietyLevel = it },
description = HungerSatietyScale.getSatietyLabel(satietyLevel),
sliderTag = "satiety_slider_10"
)
Spacer(modifier = Modifier.height(22.dp))
// 3. Enrichable Food List + Optional Weight Section
Surface(
shape = RoundedCornerShape(18.dp),
color = MaterialTheme.colorScheme.surfaceVariant.copy(alpha = 0.45f),
modifier = Modifier.fillMaxWidth()
) {
Column(
modifier = Modifier
.fillMaxWidth()
.padding(16.dp)
) {
Row(
modifier = Modifier.fillMaxWidth(),
horizontalArrangement = Arrangement.SpaceBetween,
verticalAlignment = Alignment.CenterVertically
) {
Row(verticalAlignment = Alignment.CenterVertically) {
Icon(
imageVector = Icons.Default.RestaurantMenu,
contentDescription = null,
tint = MaterialTheme.colorScheme.primary,
modifier = Modifier.size(18.dp)
)
Spacer(modifier = Modifier.width(8.dp))
Text(
text = "3. Aliments & Poids (optionnel)",
style = MaterialTheme.typography.labelLarge,
color = MaterialTheme.colorScheme.onSurface
)
}
// Subcomponent 4: Hunger & Satiety Sliders (1 to 10)
MealHungerSatietySection(
hungerLevel = hungerLevel,
satietyLevel = satietyLevel,
onHungerChange = { hungerLevel = it },
onSatietyChange = { satietyLevel = it }
)
Text(
text = "${foodItemsList.size} aliment${if (foodItemsList.size > 1) "s" else ""}",
style = MaterialTheme.typography.labelSmall,
color = MaterialTheme.colorScheme.primary,
fontWeight = FontWeight.SemiBold
)
}
Spacer(modifier = Modifier.height(22.dp))
Spacer(modifier = Modifier.height(4.dp))
Text(
text = "Sélectionnez un aliment suggéré ou tapez un nouvel aliment pour enrichir votre catalogue.",
style = MaterialTheme.typography.bodySmall,
color = MaterialTheme.colorScheme.onSurfaceVariant
)
Spacer(modifier = Modifier.height(10.dp))
// Auto-complete / Quick suggestions row
if (matchingSuggestions.isNotEmpty()) {
LazyRow(
horizontalArrangement = Arrangement.spacedBy(8.dp),
modifier = Modifier.fillMaxWidth()
) {
items(matchingSuggestions, key = { it.name }) { suggestion ->
SuggestionChip(
onClick = {
foodNameInput = suggestion.name
selectedFoodUnit = suggestion.defaultUnit
},
label = {
Text(
text = "${suggestion.name} (${suggestion.defaultUnit.label})",
style = MaterialTheme.typography.labelSmall
)
},
colors = SuggestionChipDefaults.suggestionChipColors(
containerColor = MaterialTheme.colorScheme.surface,
labelColor = MaterialTheme.colorScheme.onSurface
)
)
}
}
Spacer(modifier = Modifier.height(10.dp))
}
// Food Name Input
OutlinedTextField(
value = foodNameInput,
onValueChange = { if (it.length <= 80) foodNameInput = it },
modifier = Modifier
.fillMaxWidth()
.testTag("food_name_input"),
placeholder = {
Text("Nom de l'aliment (ex: Riz basmati, Saumon, Pomme...)")
},
singleLine = true,
shape = RoundedCornerShape(12.dp),
trailingIcon = {
if (foodNameInput.isNotEmpty()) {
IconButton(onClick = { foodNameInput = "" }) {
Icon(
imageVector = Icons.Default.Close,
contentDescription = "Effacer",
modifier = Modifier.size(18.dp)
)
}
}
}
)
if (isNewCustomFood) {
Spacer(modifier = Modifier.height(4.dp))
Text(
text = "✨ « ${foodNameInput.trim()} » sera ajouté automatiquement à votre catalogue d'aliments",
style = MaterialTheme.typography.labelSmall,
color = MaterialTheme.colorScheme.secondary
)
}
Spacer(modifier = Modifier.height(10.dp))
// Optional Weight + Unit Selector + Add Button
Row(
modifier = Modifier.fillMaxWidth(),
verticalAlignment = Alignment.CenterVertically,
horizontalArrangement = Arrangement.spacedBy(8.dp)
) {
OutlinedTextField(
value = foodWeightInput,
onValueChange = { input ->
if (input.length <= 7 && input.all { it.isDigit() || it == '.' || it == ',' }) {
foodWeightInput = input
}
},
modifier = Modifier
.weight(1f)
.testTag("food_weight_input"),
placeholder = {
Text("Poids opt.")
},
leadingIcon = {
Icon(
imageVector = Icons.Default.Scale,
contentDescription = null,
modifier = Modifier.size(16.dp),
tint = MaterialTheme.colorScheme.primary
)
},
singleLine = true,
keyboardOptions = KeyboardOptions(keyboardType = KeyboardType.Decimal),
shape = RoundedCornerShape(12.dp)
)
// Unit Selector Chips (g, ml, portion)
Row(horizontalArrangement = Arrangement.spacedBy(4.dp)) {
FoodUnit.entries.forEach { unit ->
val isUnitSelected = selectedFoodUnit == unit
FilterChip(
selected = isUnitSelected,
onClick = { selectedFoodUnit = unit },
label = {
Text(
text = unit.label,
style = MaterialTheme.typography.labelSmall
)
},
colors = FilterChipDefaults.filterChipColors(
selectedContainerColor = MaterialTheme.colorScheme.primaryContainer,
selectedLabelColor = MaterialTheme.colorScheme.onPrimaryContainer
)
)
}
}
}
Spacer(modifier = Modifier.height(10.dp))
Button(
onClick = { addCurrentFoodItem() },
enabled = foodNameInput.trim().isNotEmpty(),
modifier = Modifier
.fillMaxWidth()
.testTag("add_food_item_button"),
shape = RoundedCornerShape(12.dp),
colors = ButtonDefaults.buttonColors(
containerColor = MaterialTheme.colorScheme.primaryContainer,
contentColor = MaterialTheme.colorScheme.onPrimaryContainer
)
) {
Icon(
imageVector = Icons.Default.Add,
contentDescription = null,
modifier = Modifier.size(18.dp)
)
Spacer(modifier = Modifier.width(6.dp))
Text(
text = if (foodWeightInput.isNotBlank()) {
"Ajouter à l'assiette (${foodWeightInput.trim()} ${selectedFoodUnit.label})"
} else {
"Ajouter à l'assiette (sans poids)"
},
style = MaterialTheme.typography.labelLarge
)
}
// Added food items badges
if (foodItemsList.isNotEmpty()) {
Spacer(modifier = Modifier.height(14.dp))
Text(
text = "Aliments dans l'assiette (touchez pour modifier le poids) :",
style = MaterialTheme.typography.labelSmall,
color = MaterialTheme.colorScheme.onSurfaceVariant
)
Spacer(modifier = Modifier.height(8.dp))
FlowRow(
horizontalArrangement = Arrangement.spacedBy(8.dp),
verticalArrangement = Arrangement.spacedBy(8.dp),
modifier = Modifier.fillMaxWidth()
) {
foodItemsList.forEach { item ->
Surface(
shape = RoundedCornerShape(12.dp),
color = MaterialTheme.colorScheme.surface,
modifier = Modifier
.clip(RoundedCornerShape(12.dp))
.clickable {
// Load back into inputs for quick weight edit
foodNameInput = item.name
foodWeightInput = item.weight?.let {
if (it % 1.0 == 0.0) it.toInt().toString() else it.toString()
} ?: ""
selectedFoodUnit = item.unit
foodItemsList.remove(item)
}
) {
Row(
modifier = Modifier.padding(start = 12.dp, end = 6.dp, top = 6.dp, bottom = 6.dp),
verticalAlignment = Alignment.CenterVertically
) {
Text(
text = item.displayBadge(),
style = MaterialTheme.typography.labelMedium,
color = MaterialTheme.colorScheme.primary,
fontWeight = FontWeight.SemiBold
)
Spacer(modifier = Modifier.width(6.dp))
Icon(
imageVector = Icons.Default.Close,
contentDescription = "Retirer ${item.name}",
tint = MaterialTheme.colorScheme.onSurfaceVariant,
modifier = Modifier
.size(18.dp)
.clip(CircleShape)
.clickable { foodItemsList.remove(item) }
.padding(2.dp)
)
}
}
}
}
}
// Subcomponent 5: Food items builder & flow-row chips
FoodItemBuilderSection(
foodItemsList = foodItemsList,
matchingSuggestions = matchingSuggestions,
foodNameInput = foodNameInput,
onFoodNameChange = { foodNameInput = it },
foodWeightInput = foodWeightInput,
onFoodWeightChange = { foodWeightInput = it },
selectedFoodUnit = selectedFoodUnit,
onFoodUnitSelected = { selectedFoodUnit = it },
isNewCustomFood = isNewCustomFood,
onAddFoodItem = { addCurrentFoodItem() },
onItemClickForEdit = { item ->
foodNameInput = item.name
foodWeightInput = item.weight?.let {
if (it % 1.0 == 0.0) it.toInt().toString() else it.toString()
} ?: ""
selectedFoodUnit = item.unit
foodItemsList.remove(item)
},
onRemoveFoodItem = { item ->
foodItemsList.remove(item)
}
}
)
Spacer(modifier = Modifier.height(20.dp))
// 4. Global Note Field
// Global Note Field
Text(
text = "4. Note globale du repas (optionnel)",
style = MaterialTheme.typography.labelLarge,
@@ -827,7 +341,6 @@ fun MealEntrySheet(
Spacer(modifier = Modifier.width(10.dp))
Button(
onClick = {
// Automatically commit any pending typed food name so user input is never lost
if (foodNameInput.trim().isNotEmpty()) {
addCurrentFoodItem()
}
@@ -838,7 +351,7 @@ fun MealEntrySheet(
satietyLevel.coerceIn(1, 10),
globalNoteText,
foodItemsList.toList(),
photosBase64List.toList()
photoUrisList.toList()
)
},
modifier = Modifier
@@ -860,189 +373,4 @@ fun MealEntrySheet(
Spacer(modifier = Modifier.height(16.dp))
}
}
// Material 3 DatePickerDialog
if (showDatePicker) {
val datePickerState = rememberDatePickerState(
initialSelectedDateMillis = mealTimestamp
)
DatePickerDialog(
onDismissRequest = { showDatePicker = false },
confirmButton = {
TextButton(
onClick = {
val selectedUtcMillis = datePickerState.selectedDateMillis
if (selectedUtcMillis != null) {
val utcCal = Calendar.getInstance(TimeZone.getTimeZone("UTC")).apply {
timeInMillis = selectedUtcMillis
}
val localCal = Calendar.getInstance().apply {
timeInMillis = mealTimestamp
set(Calendar.YEAR, utcCal.get(Calendar.YEAR))
set(Calendar.MONTH, utcCal.get(Calendar.MONTH))
set(Calendar.DAY_OF_MONTH, utcCal.get(Calendar.DAY_OF_MONTH))
}
mealTimestamp = localCal.timeInMillis
}
showDatePicker = false
},
modifier = Modifier.testTag("confirm_date_button")
) {
Text("Valider la date")
}
},
dismissButton = {
TextButton(onClick = { showDatePicker = false }) {
Text("Annuler")
}
}
) {
DatePicker(state = datePickerState)
}
}
// Material 3 TimePicker Dialog
if (showTimePicker) {
val currentCal = remember(mealTimestamp) {
Calendar.getInstance().apply { timeInMillis = mealTimestamp }
}
val timePickerState = rememberTimePickerState(
initialHour = currentCal.get(Calendar.HOUR_OF_DAY),
initialMinute = currentCal.get(Calendar.MINUTE),
is24Hour = true
)
AlertDialog(
onDismissRequest = { showTimePicker = false },
title = { Text("Modifier l'heure du repas") },
text = {
Box(
modifier = Modifier.fillMaxWidth(),
contentAlignment = Alignment.Center
) {
TimePicker(state = timePickerState)
}
},
confirmButton = {
TextButton(
onClick = {
val updatedCal = Calendar.getInstance().apply {
timeInMillis = mealTimestamp
set(Calendar.HOUR_OF_DAY, timePickerState.hour)
set(Calendar.MINUTE, timePickerState.minute)
set(Calendar.SECOND, 0)
}
mealTimestamp = updatedCal.timeInMillis
showTimePicker = false
},
modifier = Modifier.testTag("confirm_time_button")
) {
Text("Valider l'heure")
}
},
dismissButton = {
TextButton(onClick = { showTimePicker = false }) {
Text("Annuler")
}
}
)
}
}
@Composable
private fun SteppedScaleTenSlider(
title: String,
currentValue: Int,
accentColor: Color,
onValueChange: (Int) -> Unit,
description: String,
sliderTag: String
) {
Surface(
shape = RoundedCornerShape(18.dp),
color = MaterialTheme.colorScheme.surfaceVariant.copy(alpha = 0.45f),
modifier = Modifier.fillMaxWidth()
) {
Column(
modifier = Modifier
.fillMaxWidth()
.padding(horizontal = 16.dp, vertical = 14.dp)
) {
Row(
modifier = Modifier.fillMaxWidth(),
horizontalArrangement = Arrangement.SpaceBetween,
verticalAlignment = Alignment.CenterVertically
) {
Text(
text = title,
style = MaterialTheme.typography.labelLarge,
color = MaterialTheme.colorScheme.onSurface
)
Surface(
shape = RoundedCornerShape(10.dp),
color = accentColor.copy(alpha = 0.2f)
) {
Text(
text = "$currentValue / 10",
style = MaterialTheme.typography.titleMedium,
color = accentColor,
fontWeight = FontWeight.Bold,
modifier = Modifier.padding(horizontal = 12.dp, vertical = 4.dp)
)
}
}
Spacer(modifier = Modifier.height(6.dp))
Text(
text = description,
style = MaterialTheme.typography.bodySmall,
color = accentColor,
fontWeight = FontWeight.Medium
)
Spacer(modifier = Modifier.height(4.dp))
Slider(
value = currentValue.toFloat(),
onValueChange = { newValue ->
onValueChange(newValue.roundToInt().coerceIn(1, 10))
},
valueRange = 1f..10f,
steps = 8,
colors = SliderDefaults.colors(
thumbColor = accentColor,
activeTrackColor = accentColor,
inactiveTrackColor = MaterialTheme.colorScheme.outlineVariant,
activeTickColor = MaterialTheme.colorScheme.surface,
inactiveTickColor = MaterialTheme.colorScheme.onSurfaceVariant.copy(alpha = 0.4f)
),
modifier = Modifier
.fillMaxWidth()
.testTag(sliderTag)
)
Row(
modifier = Modifier
.fillMaxWidth()
.padding(horizontal = 4.dp),
horizontalArrangement = Arrangement.SpaceBetween
) {
(1..10).forEach { num ->
val isSelected = num == currentValue
Text(
text = num.toString(),
style = MaterialTheme.typography.labelSmall,
fontWeight = if (isSelected) FontWeight.Bold else FontWeight.Normal,
color = if (isSelected) accentColor else MaterialTheme.colorScheme.onSurfaceVariant,
textAlign = TextAlign.Center,
modifier = Modifier
.clip(CircleShape)
.clickable { onValueChange(num) }
.padding(horizontal = 4.dp, vertical = 2.dp)
)
}
}
}
}
}
@@ -0,0 +1,313 @@
package com.example.ui.meal.components
import androidx.compose.foundation.clickable
import androidx.compose.foundation.layout.Arrangement
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.ExperimentalLayoutApi
import androidx.compose.foundation.layout.FlowRow
import androidx.compose.foundation.layout.Row
import androidx.compose.foundation.layout.Spacer
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.LazyRow
import androidx.compose.foundation.lazy.items
import androidx.compose.foundation.shape.CircleShape
import androidx.compose.foundation.shape.RoundedCornerShape
import androidx.compose.foundation.text.KeyboardOptions
import androidx.compose.material.icons.Icons
import androidx.compose.material.icons.filled.Add
import androidx.compose.material.icons.filled.Close
import androidx.compose.material.icons.filled.RestaurantMenu
import androidx.compose.material.icons.filled.Scale
import androidx.compose.material3.Button
import androidx.compose.material3.ButtonDefaults
import androidx.compose.material3.FilterChip
import androidx.compose.material3.FilterChipDefaults
import androidx.compose.material3.Icon
import androidx.compose.material3.IconButton
import androidx.compose.material3.MaterialTheme
import androidx.compose.material3.OutlinedTextField
import androidx.compose.material3.SuggestionChip
import androidx.compose.material3.SuggestionChipDefaults
import androidx.compose.material3.Surface
import androidx.compose.material3.Text
import androidx.compose.runtime.Composable
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.draw.clip
import androidx.compose.ui.platform.testTag
import androidx.compose.ui.text.font.FontWeight
import androidx.compose.ui.text.input.KeyboardType
import androidx.compose.ui.unit.dp
import com.example.data.model.DefaultFoodCatalog
import com.example.data.model.FoodUnit
import com.example.data.model.MealFoodItem
@OptIn(ExperimentalLayoutApi::class)
@Composable
fun FoodItemBuilderSection(
foodItemsList: List<MealFoodItem>,
matchingSuggestions: List<DefaultFoodCatalog.CatalogFood>,
foodNameInput: String,
onFoodNameChange: (String) -> Unit,
foodWeightInput: String,
onFoodWeightChange: (String) -> Unit,
selectedFoodUnit: FoodUnit,
onFoodUnitSelected: (FoodUnit) -> Unit,
isNewCustomFood: Boolean,
onAddFoodItem: () -> Unit,
onItemClickForEdit: (MealFoodItem) -> Unit,
onRemoveFoodItem: (MealFoodItem) -> Unit,
modifier: Modifier = Modifier
) {
Surface(
shape = RoundedCornerShape(18.dp),
color = MaterialTheme.colorScheme.surfaceVariant.copy(alpha = 0.45f),
modifier = modifier.fillMaxWidth()
) {
Column(
modifier = Modifier
.fillMaxWidth()
.padding(16.dp)
) {
Row(
modifier = Modifier.fillMaxWidth(),
horizontalArrangement = Arrangement.SpaceBetween,
verticalAlignment = Alignment.CenterVertically
) {
Row(verticalAlignment = Alignment.CenterVertically) {
Icon(
imageVector = Icons.Default.RestaurantMenu,
contentDescription = null,
tint = MaterialTheme.colorScheme.primary,
modifier = Modifier.size(18.dp)
)
Spacer(modifier = Modifier.width(8.dp))
Text(
text = "3. Aliments & Poids (optionnel)",
style = MaterialTheme.typography.labelLarge,
color = MaterialTheme.colorScheme.onSurface
)
}
Text(
text = "${foodItemsList.size} aliment${if (foodItemsList.size > 1) "s" else ""}",
style = MaterialTheme.typography.labelSmall,
color = MaterialTheme.colorScheme.primary,
fontWeight = FontWeight.SemiBold
)
}
Spacer(modifier = Modifier.height(4.dp))
Text(
text = "Sélectionnez un aliment suggéré ou tapez un nouvel aliment pour enrichir votre catalogue.",
style = MaterialTheme.typography.bodySmall,
color = MaterialTheme.colorScheme.onSurfaceVariant
)
Spacer(modifier = Modifier.height(10.dp))
// Auto-complete / Quick suggestions row
if (matchingSuggestions.isNotEmpty()) {
LazyRow(
horizontalArrangement = Arrangement.spacedBy(8.dp),
modifier = Modifier.fillMaxWidth()
) {
items(matchingSuggestions, key = { it.name }) { suggestion ->
SuggestionChip(
onClick = {
onFoodNameChange(suggestion.name)
onFoodUnitSelected(suggestion.defaultUnit)
},
label = {
Text(
text = "${suggestion.name} (${suggestion.defaultUnit.label})",
style = MaterialTheme.typography.labelSmall
)
},
colors = SuggestionChipDefaults.suggestionChipColors(
containerColor = MaterialTheme.colorScheme.surface,
labelColor = MaterialTheme.colorScheme.onSurface
)
)
}
}
Spacer(modifier = Modifier.height(10.dp))
}
// Food Name Input
OutlinedTextField(
value = foodNameInput,
onValueChange = { if (it.length <= 80) onFoodNameChange(it) },
modifier = Modifier
.fillMaxWidth()
.testTag("food_name_input"),
placeholder = {
Text("Nom de l'aliment (ex: Riz basmati, Saumon, Pomme...)")
},
singleLine = true,
shape = RoundedCornerShape(12.dp),
trailingIcon = {
if (foodNameInput.isNotEmpty()) {
IconButton(onClick = { onFoodNameChange("") }) {
Icon(
imageVector = Icons.Default.Close,
contentDescription = "Effacer",
modifier = Modifier.size(18.dp)
)
}
}
}
)
if (isNewCustomFood) {
Spacer(modifier = Modifier.height(4.dp))
Text(
text = "✨ « ${foodNameInput.trim()} » sera ajouté automatiquement à votre catalogue d'aliments",
style = MaterialTheme.typography.labelSmall,
color = MaterialTheme.colorScheme.secondary
)
}
Spacer(modifier = Modifier.height(10.dp))
// Optional Weight + Unit Selector + Add Button
Row(
modifier = Modifier.fillMaxWidth(),
verticalAlignment = Alignment.CenterVertically,
horizontalArrangement = Arrangement.spacedBy(8.dp)
) {
OutlinedTextField(
value = foodWeightInput,
onValueChange = { input ->
if (input.length <= 7 && input.all { it.isDigit() || it == '.' || it == ',' }) {
onFoodWeightChange(input)
}
},
modifier = Modifier
.weight(1f)
.testTag("food_weight_input"),
placeholder = {
Text("Poids opt.")
},
leadingIcon = {
Icon(
imageVector = Icons.Default.Scale,
contentDescription = null,
modifier = Modifier.size(16.dp),
tint = MaterialTheme.colorScheme.primary
)
},
singleLine = true,
keyboardOptions = KeyboardOptions(keyboardType = KeyboardType.Decimal),
shape = RoundedCornerShape(12.dp)
)
// Unit Selector Chips (g, ml, portion)
Row(horizontalArrangement = Arrangement.spacedBy(4.dp)) {
FoodUnit.entries.forEach { unit ->
val isUnitSelected = selectedFoodUnit == unit
FilterChip(
selected = isUnitSelected,
onClick = { onFoodUnitSelected(unit) },
label = {
Text(
text = unit.label,
style = MaterialTheme.typography.labelSmall
)
},
colors = FilterChipDefaults.filterChipColors(
selectedContainerColor = MaterialTheme.colorScheme.primaryContainer,
selectedLabelColor = MaterialTheme.colorScheme.onPrimaryContainer
)
)
}
}
}
Spacer(modifier = Modifier.height(10.dp))
Button(
onClick = onAddFoodItem,
enabled = foodNameInput.trim().isNotEmpty(),
modifier = Modifier
.fillMaxWidth()
.testTag("add_food_item_button"),
shape = RoundedCornerShape(12.dp),
colors = ButtonDefaults.buttonColors(
containerColor = MaterialTheme.colorScheme.primaryContainer,
contentColor = MaterialTheme.colorScheme.onPrimaryContainer
)
) {
Icon(
imageVector = Icons.Default.Add,
contentDescription = null,
modifier = Modifier.size(18.dp)
)
Spacer(modifier = Modifier.width(6.dp))
Text(
text = if (foodWeightInput.isNotBlank()) {
"Ajouter à l'assiette (${foodWeightInput.trim()} ${selectedFoodUnit.label})"
} else {
"Ajouter à l'assiette (sans poids)"
},
style = MaterialTheme.typography.labelLarge
)
}
// Added food items badges
if (foodItemsList.isNotEmpty()) {
Spacer(modifier = Modifier.height(14.dp))
Text(
text = "Aliments dans l'assiette (touchez pour modifier le poids) :",
style = MaterialTheme.typography.labelSmall,
color = MaterialTheme.colorScheme.onSurfaceVariant
)
Spacer(modifier = Modifier.height(8.dp))
FlowRow(
horizontalArrangement = Arrangement.spacedBy(8.dp),
verticalArrangement = Arrangement.spacedBy(8.dp),
modifier = Modifier.fillMaxWidth()
) {
foodItemsList.forEach { item ->
Surface(
shape = RoundedCornerShape(12.dp),
color = MaterialTheme.colorScheme.surface,
modifier = Modifier
.clip(RoundedCornerShape(12.dp))
.clickable { onItemClickForEdit(item) }
) {
Row(
modifier = Modifier.padding(start = 12.dp, end = 6.dp, top = 6.dp, bottom = 6.dp),
verticalAlignment = Alignment.CenterVertically
) {
Text(
text = item.displayBadge(),
style = MaterialTheme.typography.labelMedium,
color = MaterialTheme.colorScheme.primary,
fontWeight = FontWeight.SemiBold
)
Spacer(modifier = Modifier.width(6.dp))
Icon(
imageVector = Icons.Default.Close,
contentDescription = "Retirer ${item.name}",
tint = MaterialTheme.colorScheme.onSurfaceVariant,
modifier = Modifier
.size(18.dp)
.clip(CircleShape)
.clickable { onRemoveFoodItem(item) }
.padding(2.dp)
)
}
}
}
}
}
}
}
}
@@ -0,0 +1,239 @@
package com.example.ui.meal.components
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.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.shape.RoundedCornerShape
import androidx.compose.material.icons.Icons
import androidx.compose.material.icons.filled.CalendarMonth
import androidx.compose.material.icons.filled.Schedule
import androidx.compose.material3.AlertDialog
import androidx.compose.material3.DatePicker
import androidx.compose.material3.DatePickerDialog
import androidx.compose.material3.ExperimentalMaterial3Api
import androidx.compose.material3.Icon
import androidx.compose.material3.MaterialTheme
import androidx.compose.material3.OutlinedButton
import androidx.compose.material3.Text
import androidx.compose.material3.TextButton
import androidx.compose.material3.TimePicker
import androidx.compose.material3.rememberDatePickerState
import androidx.compose.material3.rememberTimePickerState
import androidx.compose.runtime.Composable
import androidx.compose.runtime.getValue
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.remember
import androidx.compose.runtime.setValue
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.draw.clip
import androidx.compose.ui.platform.testTag
import androidx.compose.ui.unit.dp
import java.time.Instant
import java.time.LocalDate
import java.time.ZoneId
import java.time.ZonedDateTime
import java.time.format.DateTimeFormatter
import java.util.Locale
@OptIn(ExperimentalMaterial3Api::class)
@Composable
fun MealDateTimePicker(
mealTimestamp: Long,
onTimestampChanged: (Long) -> Unit,
modifier: Modifier = Modifier
) {
var showDatePicker by remember { mutableStateOf(false) }
var showTimePicker by remember { mutableStateOf(false) }
val zoneId = remember { ZoneId.systemDefault() }
val zonedDateTime = remember(mealTimestamp) {
Instant.ofEpochMilli(mealTimestamp).atZone(zoneId)
}
val dateFormatter = remember {
DateTimeFormatter.ofPattern("EEE d MMM yyyy", Locale.FRENCH)
}
val timeFormatter = remember {
DateTimeFormatter.ofPattern("HH:mm", Locale.FRENCH)
}
Column(modifier = modifier.fillMaxWidth()) {
Row(
modifier = Modifier.fillMaxWidth(),
horizontalArrangement = Arrangement.SpaceBetween,
verticalAlignment = Alignment.CenterVertically
) {
Text(
text = "Date et heure du repas",
style = MaterialTheme.typography.labelLarge,
color = MaterialTheme.colorScheme.primary
)
Row(horizontalArrangement = Arrangement.spacedBy(8.dp)) {
Text(
text = "Maintenant",
style = MaterialTheme.typography.labelSmall,
color = MaterialTheme.colorScheme.secondary,
modifier = Modifier
.clip(RoundedCornerShape(6.dp))
.clickable { onTimestampChanged(System.currentTimeMillis()) }
.padding(horizontal = 6.dp, vertical = 2.dp)
)
Text(
text = "Hier",
style = MaterialTheme.typography.labelSmall,
color = MaterialTheme.colorScheme.secondary,
modifier = Modifier
.clip(RoundedCornerShape(6.dp))
.clickable {
val yesterdayMillis = zonedDateTime.minusDays(1).toInstant().toEpochMilli()
onTimestampChanged(yesterdayMillis)
}
.padding(horizontal = 6.dp, vertical = 2.dp)
)
}
}
Spacer(modifier = Modifier.height(8.dp))
Row(
modifier = Modifier.fillMaxWidth(),
horizontalArrangement = Arrangement.spacedBy(10.dp)
) {
OutlinedButton(
onClick = { showDatePicker = true },
modifier = Modifier
.weight(1.3f)
.testTag("edit_date_button"),
shape = RoundedCornerShape(12.dp)
) {
Icon(
imageVector = Icons.Default.CalendarMonth,
contentDescription = "Changer la date",
modifier = Modifier.size(18.dp),
tint = MaterialTheme.colorScheme.primary
)
Spacer(modifier = Modifier.width(8.dp))
Text(
text = dateFormatter.format(zonedDateTime).replaceFirstChar {
if (it.isLowerCase()) it.titlecase(Locale.FRENCH) else it.toString()
},
style = MaterialTheme.typography.bodyMedium,
color = MaterialTheme.colorScheme.onSurface
)
}
OutlinedButton(
onClick = { showTimePicker = true },
modifier = Modifier
.weight(0.9f)
.testTag("edit_time_button"),
shape = RoundedCornerShape(12.dp)
) {
Icon(
imageVector = Icons.Default.Schedule,
contentDescription = "Changer l'heure",
modifier = Modifier.size(18.dp),
tint = MaterialTheme.colorScheme.primary
)
Spacer(modifier = Modifier.width(8.dp))
Text(
text = timeFormatter.format(zonedDateTime),
style = MaterialTheme.typography.bodyMedium,
color = MaterialTheme.colorScheme.onSurface
)
}
}
}
// Material 3 DatePickerDialog
if (showDatePicker) {
val datePickerState = rememberDatePickerState(
initialSelectedDateMillis = mealTimestamp
)
DatePickerDialog(
onDismissRequest = { showDatePicker = false },
confirmButton = {
TextButton(
onClick = {
val selectedUtcMillis = datePickerState.selectedDateMillis
if (selectedUtcMillis != null) {
// Extract year, month, day from the UTC date picker
val selectedLocalDate = Instant.ofEpochMilli(selectedUtcMillis)
.atZone(ZoneId.of("UTC"))
.toLocalDate()
val updatedZoned = zonedDateTime
.withYear(selectedLocalDate.year)
.withMonth(selectedLocalDate.monthValue)
.withDayOfMonth(selectedLocalDate.dayOfMonth)
onTimestampChanged(updatedZoned.toInstant().toEpochMilli())
}
showDatePicker = false
},
modifier = Modifier.testTag("confirm_date_button")
) {
Text("Valider la date")
}
},
dismissButton = {
TextButton(onClick = { showDatePicker = false }) {
Text("Annuler")
}
}
) {
DatePicker(state = datePickerState)
}
}
// Material 3 TimePicker Dialog
if (showTimePicker) {
val timePickerState = rememberTimePickerState(
initialHour = zonedDateTime.hour,
initialMinute = zonedDateTime.minute,
is24Hour = true
)
AlertDialog(
onDismissRequest = { showTimePicker = false },
title = { Text("Modifier l'heure du repas") },
text = {
Box(
modifier = Modifier.fillMaxWidth(),
contentAlignment = Alignment.Center
) {
TimePicker(state = timePickerState)
}
},
confirmButton = {
TextButton(
onClick = {
val updatedZoned = zonedDateTime
.withHour(timePickerState.hour)
.withMinute(timePickerState.minute)
.withSecond(0)
onTimestampChanged(updatedZoned.toInstant().toEpochMilli())
showTimePicker = false
},
modifier = Modifier.testTag("confirm_time_button")
) {
Text("Valider l'heure")
}
},
dismissButton = {
TextButton(onClick = { showTimePicker = false }) {
Text("Annuler")
}
}
)
}
}
@@ -0,0 +1,161 @@
package com.example.ui.meal.components
import androidx.compose.foundation.clickable
import androidx.compose.foundation.layout.Arrangement
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.Row
import androidx.compose.foundation.layout.Spacer
import androidx.compose.foundation.layout.fillMaxWidth
import androidx.compose.foundation.layout.height
import androidx.compose.foundation.layout.padding
import androidx.compose.foundation.shape.CircleShape
import androidx.compose.foundation.shape.RoundedCornerShape
import androidx.compose.material3.MaterialTheme
import androidx.compose.material3.Slider
import androidx.compose.material3.SliderDefaults
import androidx.compose.material3.Surface
import androidx.compose.material3.Text
import androidx.compose.runtime.Composable
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.draw.clip
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.platform.testTag
import androidx.compose.ui.text.font.FontWeight
import androidx.compose.ui.text.style.TextAlign
import androidx.compose.ui.unit.dp
import com.example.data.model.HungerSatietyScale
import kotlin.math.roundToInt
@Composable
fun MealHungerSatietySection(
hungerLevel: Int,
satietyLevel: Int,
onHungerChange: (Int) -> Unit,
onSatietyChange: (Int) -> Unit,
modifier: Modifier = Modifier
) {
Column(modifier = modifier.fillMaxWidth()) {
// 1. Hunger Stepped Slider (1 to 10)
SteppedScaleTenSlider(
title = "1. Faim avant le repas",
currentValue = hungerLevel,
accentColor = MaterialTheme.colorScheme.secondary,
onValueChange = onHungerChange,
description = HungerSatietyScale.getHungerLabel(hungerLevel),
sliderTag = "hunger_slider_10"
)
Spacer(modifier = Modifier.height(18.dp))
// 2. Satiety Stepped Slider (1 to 10)
SteppedScaleTenSlider(
title = "2. Satiété après le repas",
currentValue = satietyLevel,
accentColor = MaterialTheme.colorScheme.primary,
onValueChange = onSatietyChange,
description = HungerSatietyScale.getSatietyLabel(satietyLevel),
sliderTag = "satiety_slider_10"
)
}
}
@Composable
fun SteppedScaleTenSlider(
title: String,
currentValue: Int,
accentColor: Color,
onValueChange: (Int) -> Unit,
description: String,
sliderTag: String,
modifier: Modifier = Modifier
) {
Surface(
shape = RoundedCornerShape(18.dp),
color = MaterialTheme.colorScheme.surfaceVariant.copy(alpha = 0.45f),
modifier = modifier.fillMaxWidth()
) {
Column(
modifier = Modifier
.fillMaxWidth()
.padding(horizontal = 16.dp, vertical = 14.dp)
) {
Row(
modifier = Modifier.fillMaxWidth(),
horizontalArrangement = Arrangement.SpaceBetween,
verticalAlignment = Alignment.CenterVertically
) {
Text(
text = title,
style = MaterialTheme.typography.labelLarge,
color = MaterialTheme.colorScheme.onSurface
)
Surface(
shape = RoundedCornerShape(10.dp),
color = accentColor.copy(alpha = 0.2f)
) {
Text(
text = "$currentValue / 10",
style = MaterialTheme.typography.titleMedium,
color = accentColor,
fontWeight = FontWeight.Bold,
modifier = Modifier.padding(horizontal = 12.dp, vertical = 4.dp)
)
}
}
Spacer(modifier = Modifier.height(6.dp))
Text(
text = description,
style = MaterialTheme.typography.bodySmall,
color = accentColor,
fontWeight = FontWeight.Medium
)
Spacer(modifier = Modifier.height(4.dp))
Slider(
value = currentValue.toFloat(),
onValueChange = { newValue ->
onValueChange(newValue.roundToInt().coerceIn(1, 10))
},
valueRange = 1f..10f,
steps = 8,
colors = SliderDefaults.colors(
thumbColor = accentColor,
activeTrackColor = accentColor,
inactiveTrackColor = MaterialTheme.colorScheme.outlineVariant,
activeTickColor = MaterialTheme.colorScheme.surface,
inactiveTickColor = MaterialTheme.colorScheme.onSurfaceVariant.copy(alpha = 0.4f)
),
modifier = Modifier
.fillMaxWidth()
.testTag(sliderTag)
)
Row(
modifier = Modifier
.fillMaxWidth()
.padding(horizontal = 4.dp),
horizontalArrangement = Arrangement.SpaceBetween
) {
(1..10).forEach { num ->
val isSelected = num == currentValue
Text(
text = num.toString(),
style = MaterialTheme.typography.labelSmall,
fontWeight = if (isSelected) FontWeight.Bold else FontWeight.Normal,
color = if (isSelected) accentColor else MaterialTheme.colorScheme.onSurfaceVariant,
textAlign = TextAlign.Center,
modifier = Modifier
.clip(CircleShape)
.clickable { onValueChange(num) }
.padding(horizontal = 4.dp, vertical = 2.dp)
)
}
}
}
}
}
@@ -0,0 +1,133 @@
package com.example.ui.meal.components
import androidx.compose.foundation.border
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.Spacer
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.lazy.LazyRow
import androidx.compose.foundation.lazy.items
import androidx.compose.foundation.shape.CircleShape
import androidx.compose.foundation.shape.RoundedCornerShape
import androidx.compose.material.icons.Icons
import androidx.compose.material.icons.filled.AddAPhoto
import androidx.compose.material.icons.filled.Close
import androidx.compose.material3.CircularProgressIndicator
import androidx.compose.material3.Icon
import androidx.compose.material3.MaterialTheme
import androidx.compose.material3.Surface
import androidx.compose.material3.Text
import androidx.compose.runtime.Composable
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.draw.clip
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.layout.ContentScale
import androidx.compose.ui.platform.testTag
import androidx.compose.ui.unit.dp
import coil.compose.AsyncImage
@Composable
fun MealPhotosSection(
photoUris: List<String>,
isProcessingPhoto: Boolean,
onAddPhotoClick: () -> Unit,
onDeletePhotoClick: (String) -> Unit,
modifier: Modifier = Modifier
) {
Column(modifier = modifier.fillMaxWidth()) {
Text(
text = "Photos de l'assiette (${photoUris.size}/4)",
style = MaterialTheme.typography.labelLarge,
color = MaterialTheme.colorScheme.primary
)
Spacer(modifier = Modifier.height(8.dp))
LazyRow(
horizontalArrangement = Arrangement.spacedBy(10.dp),
verticalAlignment = Alignment.CenterVertically
) {
if (photoUris.size < 4) {
item {
Surface(
modifier = Modifier
.size(84.dp)
.clip(RoundedCornerShape(14.dp))
.border(
width = 1.dp,
color = MaterialTheme.colorScheme.outline.copy(alpha = 0.5f),
shape = RoundedCornerShape(14.dp)
)
.clickable(enabled = !isProcessingPhoto) {
onAddPhotoClick()
}
.testTag("add_photo_button"),
color = MaterialTheme.colorScheme.surfaceVariant.copy(alpha = 0.4f)
) {
Box(contentAlignment = Alignment.Center) {
if (isProcessingPhoto) {
CircularProgressIndicator(
modifier = Modifier.size(24.dp),
strokeWidth = 2.dp,
color = MaterialTheme.colorScheme.primary
)
} else {
Column(horizontalAlignment = Alignment.CenterHorizontally) {
Icon(
imageVector = Icons.Default.AddAPhoto,
contentDescription = "Ajouter une photo",
tint = MaterialTheme.colorScheme.primary,
modifier = Modifier.size(24.dp)
)
Spacer(modifier = Modifier.height(4.dp))
Text(
text = "Ajouter",
style = MaterialTheme.typography.labelSmall,
color = MaterialTheme.colorScheme.onSurfaceVariant
)
}
}
}
}
}
}
items(photoUris) { photoUri ->
Box(
modifier = Modifier
.size(84.dp)
.clip(RoundedCornerShape(14.dp))
) {
AsyncImage(
model = photoUri,
contentDescription = "Photo de l'assiette",
modifier = Modifier.matchParentSize(),
contentScale = ContentScale.Crop
)
Surface(
modifier = Modifier
.align(Alignment.TopEnd)
.padding(4.dp)
.size(22.dp)
.clip(CircleShape)
.clickable { onDeletePhotoClick(photoUri) },
color = Color.Black.copy(alpha = 0.7f)
) {
Icon(
imageVector = Icons.Default.Close,
contentDescription = "Supprimer photo",
tint = Color.White,
modifier = Modifier.padding(2.dp)
)
}
}
}
}
}
}
@@ -0,0 +1,54 @@
package com.example.ui.meal.components
import androidx.compose.foundation.layout.Arrangement
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.Row
import androidx.compose.foundation.layout.Spacer
import androidx.compose.foundation.layout.fillMaxWidth
import androidx.compose.foundation.layout.height
import androidx.compose.material3.FilterChip
import androidx.compose.material3.FilterChipDefaults
import androidx.compose.material3.MaterialTheme
import androidx.compose.material3.Text
import androidx.compose.runtime.Composable
import androidx.compose.ui.Modifier
import androidx.compose.ui.unit.dp
import com.example.data.model.MealType
@Composable
fun MealTypeSelector(
selectedType: MealType,
onTypeSelected: (MealType) -> Unit,
modifier: Modifier = Modifier
) {
Column(modifier = modifier.fillMaxWidth()) {
Text(
text = "Type de repas",
style = MaterialTheme.typography.labelLarge,
color = MaterialTheme.colorScheme.primary
)
Spacer(modifier = Modifier.height(8.dp))
Row(
modifier = Modifier.fillMaxWidth(),
horizontalArrangement = Arrangement.spacedBy(8.dp)
) {
MealType.entries.forEach { type ->
val isSelected = selectedType == type
FilterChip(
selected = isSelected,
onClick = { onTypeSelected(type) },
label = {
Text(
text = type.displayName,
style = MaterialTheme.typography.labelMedium
)
},
colors = FilterChipDefaults.filterChipColors(
selectedContainerColor = MaterialTheme.colorScheme.primaryContainer,
selectedLabelColor = MaterialTheme.colorScheme.onPrimaryContainer
)
)
}
}
}
}
@@ -45,8 +45,9 @@ import androidx.compose.material3.CircularProgressIndicator
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.unit.sp
import com.example.ui.journal.GoogleSheetsUiState
import java.text.SimpleDateFormat
import java.util.Date
import java.time.Instant
import java.time.ZoneId
import java.time.format.DateTimeFormatter
import java.util.Locale
import androidx.compose.material3.Button
import androidx.compose.material3.ButtonDefaults
@@ -357,8 +358,8 @@ fun SettingsScreen(
}
}
is GoogleSheetsUiState.Success -> {
val timeStr = SimpleDateFormat("dd/MM/yyyy à HH:mm", Locale.FRENCH)
.format(Date(sheetsUiState.timestamp))
val timeStr = DateTimeFormatter.ofPattern("dd/MM/yyyy 'à' HH:mm", Locale.FRENCH)
.format(Instant.ofEpochMilli(sheetsUiState.timestamp).atZone(ZoneId.systemDefault()))
Column(
modifier = Modifier
.fillMaxWidth()
@@ -884,16 +885,7 @@ fun SettingsScreen(
Spacer(modifier = Modifier.height(16.dp))
Button(
onClick = {
Firebase.auth.signOut()
CoroutineScope(Dispatchers.IO).launch {
try {
val credManager = CredentialManager.create(context)
credManager.clearCredentialState(ClearCredentialStateRequest())
} catch (_: Exception) {}
}
onSignOut()
},
onClick = onSignOut,
modifier = Modifier
.fillMaxWidth()
.testTag("signout_button"),