feat: add recipe management support

- Add `LocalRecipeEntity` and database migration 3->4
- Update `LocalCustomFoodEntity` with category support
- Include DAO methods for recipe persistence
This commit is contained in:
bleackstorm committed 2026-11-20 21:10:19 +01:00
1 parent 097d4b521e
commit d4d5d77d71
41 files changed
+5264 -1901

No files matched your search

@@ -1,15 +1,14 @@
package com.example.ui.auth
import android.app.Activity
import android.content.Context
import android.util.Log
import androidx.activity.compose.rememberLauncherForActivityResult
import androidx.activity.result.contract.ActivityResultContracts
import androidx.compose.foundation.background
import androidx.compose.foundation.layout.Arrangement
import androidx.compose.foundation.layout.Box
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.Row
import androidx.compose.foundation.layout.Spacer
import androidx.compose.foundation.layout.fillMaxSize
import androidx.compose.foundation.layout.fillMaxWidth
import androidx.compose.foundation.layout.height
import androidx.compose.foundation.layout.padding
@@ -19,9 +18,9 @@ import androidx.compose.foundation.shape.CircleShape
import androidx.compose.foundation.shape.RoundedCornerShape
import androidx.compose.material.icons.Icons
import androidx.compose.material.icons.filled.CloudDone
import androidx.compose.material.icons.filled.Eco
import androidx.compose.material.icons.filled.Restaurant
import androidx.compose.material.icons.filled.Timeline
import androidx.compose.material.icons.filled.FolderShared
import androidx.compose.material.icons.filled.PhoneAndroid
import androidx.compose.material.icons.filled.TableChart
import androidx.compose.material3.Button
import androidx.compose.material3.ButtonDefaults
import androidx.compose.material3.Card
@@ -49,103 +48,135 @@ import androidx.compose.ui.text.font.FontWeight
import androidx.compose.ui.text.style.TextAlign
import androidx.compose.ui.unit.dp
import androidx.compose.ui.unit.sp
import androidx.credentials.CredentialManager
import androidx.credentials.CustomCredential
import androidx.credentials.GetCredentialRequest
import androidx.credentials.exceptions.GetCredentialCancellationException
import com.example.R
import com.google.android.libraries.identity.googleid.GetSignInWithGoogleOption
import com.google.android.libraries.identity.googleid.GoogleIdTokenCredential
import com.google.android.libraries.identity.googleid.GoogleIdTokenCredential.Companion.TYPE_GOOGLE_ID_TOKEN_CREDENTIAL
import com.google.firebase.Firebase
import com.google.firebase.auth.GoogleAuthProvider
import com.google.firebase.auth.auth
import kotlinx.coroutines.CoroutineScope
import com.example.util.GoogleDriveAccount
import com.example.util.GoogleSheetsAuthHelper
import com.google.android.gms.auth.api.signin.GoogleSignIn
import com.google.android.gms.common.api.ApiException
import kotlinx.coroutines.launch
import kotlinx.coroutines.tasks.await
@Composable
fun AuthScreen(
onAuthSuccess: () -> Unit
onAuthSuccess: (GoogleDriveAccount) -> Unit
) {
val context = LocalContext.current
val coroutineScope = rememberCoroutineScope()
val credentialManager = remember { CredentialManager.create(context) }
var isLoading by remember { mutableStateOf(false) }
val snackbarHostState = remember { SnackbarHostState() }
val signInLauncher = rememberLauncherForActivityResult(
contract = ActivityResultContracts.StartActivityForResult()
) { result ->
isLoading = false
if (result.resultCode == Activity.RESULT_OK) {
try {
val task = GoogleSignIn.getSignedInAccountFromIntent(result.data)
val signedIn = task.getResult(ApiException::class.java)
val email = signedIn?.email
if (!email.isNullOrBlank()) {
onAuthSuccess(
GoogleDriveAccount(
displayName = signedIn.displayName,
email = email
)
)
} else {
val fallback = GoogleSheetsAuthHelper.getSignedInAccount(context)
if (fallback != null) {
onAuthSuccess(fallback)
} else {
coroutineScope.launch {
snackbarHostState.showSnackbar("Impossible de récupérer l'adresse Google")
}
}
}
} catch (e: Exception) {
val fallback = GoogleSheetsAuthHelper.getSignedInAccount(context)
if (fallback != null) {
onAuthSuccess(fallback)
} else {
coroutineScope.launch {
snackbarHostState.showSnackbar(
e.localizedMessage ?: "Échec de connexion au compte Google Drive"
)
}
}
}
} else {
coroutineScope.launch {
snackbarHostState.showSnackbar("Connexion Google Drive annulée")
}
}
}
Box(
modifier = Modifier
.fillMaxSize()
.background(MaterialTheme.colorScheme.background)
.fillMaxWidth()
.background(MaterialTheme.colorScheme.surface)
) {
Column(
modifier = Modifier
.fillMaxSize()
.padding(horizontal = 28.dp, vertical = 32.dp),
.fillMaxWidth()
.padding(horizontal = 24.dp, vertical = 20.dp),
horizontalAlignment = Alignment.CenterHorizontally,
verticalArrangement = Arrangement.SpaceBetween
verticalArrangement = Arrangement.spacedBy(18.dp)
) {
Spacer(modifier = Modifier.height(24.dp))
// Logo & Hero Section
Column(
horizontalAlignment = Alignment.CenterHorizontally
) {
// Hero
Column(horizontalAlignment = Alignment.CenterHorizontally) {
Surface(
modifier = Modifier
.size(88.dp)
.size(72.dp)
.clip(CircleShape),
color = MaterialTheme.colorScheme.primaryContainer
) {
Box(contentAlignment = Alignment.Center) {
Icon(
imageVector = Icons.Default.Restaurant,
contentDescription = "Logo Satiéa",
imageVector = Icons.Default.FolderShared,
contentDescription = "Connexion Google Drive",
tint = MaterialTheme.colorScheme.onPrimaryContainer,
modifier = Modifier.size(44.dp)
modifier = Modifier.size(36.dp)
)
}
}
Spacer(modifier = Modifier.height(20.dp))
Spacer(modifier = Modifier.height(14.dp))
Text(
text = "Satiéa",
style = MaterialTheme.typography.displayMedium,
color = MaterialTheme.colorScheme.primary,
fontWeight = FontWeight.Bold
text = "Sauvegarde sur Google Drive",
style = MaterialTheme.typography.headlineSmall,
color = MaterialTheme.colorScheme.onSurface,
fontWeight = FontWeight.Bold,
textAlign = TextAlign.Center
)
Spacer(modifier = Modifier.height(8.dp))
Spacer(modifier = Modifier.height(6.dp))
Text(
text = "Journal de repas & écoute de soi",
style = MaterialTheme.typography.bodyLarge,
color = MaterialTheme.colorScheme.onBackground.copy(alpha = 0.8f),
text = "Votre compte Google sert uniquement à enregistrer vos données dans votre Drive personnel.",
style = MaterialTheme.typography.bodyMedium,
color = MaterialTheme.colorScheme.onSurfaceVariant,
textAlign = TextAlign.Center
)
}
// Benefits cards
// Benefits
Column(
modifier = Modifier.fillMaxWidth(),
verticalArrangement = Arrangement.spacedBy(14.dp)
verticalArrangement = Arrangement.spacedBy(10.dp)
) {
FeaturePill(
icon = Icons.Default.Eco,
title = "Sensations de faim & satiété",
subtitle = "Évaluez votre ressenti avant et après chaque repas en 10 secondes."
icon = Icons.Default.PhoneAndroid,
title = "100 % local par défaut",
subtitle = "Toutes vos données restent enregistrées sur votre téléphone, sans serveur tiers."
)
FeaturePill(
icon = Icons.Default.Timeline,
title = "Statistiques 7 jours",
subtitle = "Suivez votre équilibre digestif et la régularité de vos habitudes."
icon = Icons.Default.TableChart,
title = "Votre classeur Google Sheets",
subtitle = "3 onglets clairs : Journal des repas, Aliments colorés et Recueil de recettes."
)
FeaturePill(
icon = Icons.Default.CloudDone,
title = "Synchronisation Cloud sécurisée",
subtitle = "Vos repas et photos d'assiettes accessibles sur tous vos appareils."
title = "Photos & restauration faciles",
subtitle = "Vos photos sont archivées dans votre dossier Drive « Satiéa »."
)
}
@@ -157,28 +188,12 @@ fun AuthScreen(
Button(
onClick = {
isLoading = true
onGoogleSignInClicked(
context = context,
credentialManager = credentialManager,
onAuthSuccess = {
isLoading = false
onAuthSuccess()
},
onAuthError = { errorMsg ->
isLoading = false
coroutineScope.launch {
snackbarHostState.showSnackbar(errorMsg)
}
},
scope = coroutineScope,
onAuthCancelled = {
isLoading = false
}
)
val client = GoogleSheetsAuthHelper.getGoogleSignInClient(context)
signInLauncher.launch(client.signInIntent)
},
modifier = Modifier
.fillMaxWidth()
.height(54.dp)
.height(52.dp)
.testTag("google_signin_button"),
shape = RoundedCornerShape(16.dp),
colors = ButtonDefaults.buttonColors(
@@ -189,7 +204,7 @@ fun AuthScreen(
) {
if (isLoading) {
CircularProgressIndicator(
modifier = Modifier.size(24.dp),
modifier = Modifier.size(22.dp),
color = MaterialTheme.colorScheme.onPrimary,
strokeWidth = 2.dp
)
@@ -202,22 +217,24 @@ fun AuthScreen(
)
Spacer(modifier = Modifier.width(10.dp))
Text(
text = "Continuer avec Google",
style = MaterialTheme.typography.titleMedium
text = "Connecter mon compte Google Drive",
style = MaterialTheme.typography.titleSmall
)
}
}
}
Spacer(modifier = Modifier.height(14.dp))
Spacer(modifier = Modifier.height(10.dp))
Text(
text = "Connexion sécurisée via Google • Sans publicité",
text = "Accès limité uniquement aux fichiers créés par Satiéa dans votre Drive",
style = MaterialTheme.typography.bodySmall,
color = MaterialTheme.colorScheme.onBackground.copy(alpha = 0.5f),
color = MaterialTheme.colorScheme.onSurfaceVariant.copy(alpha = 0.7f),
textAlign = TextAlign.Center
)
}
Spacer(modifier = Modifier.height(8.dp))
}
SnackbarHost(
@@ -235,20 +252,20 @@ private fun FeaturePill(
) {
Card(
modifier = Modifier.fillMaxWidth(),
shape = RoundedCornerShape(18.dp),
shape = RoundedCornerShape(16.dp),
colors = CardDefaults.cardColors(
containerColor = MaterialTheme.colorScheme.surfaceVariant.copy(alpha = 0.6f)
containerColor = MaterialTheme.colorScheme.surfaceVariant.copy(alpha = 0.55f)
)
) {
Row(
modifier = Modifier
.fillMaxWidth()
.padding(16.dp),
.padding(14.dp),
verticalAlignment = Alignment.CenterVertically
) {
Surface(
modifier = Modifier.size(40.dp),
shape = RoundedCornerShape(12.dp),
modifier = Modifier.size(38.dp),
shape = RoundedCornerShape(11.dp),
color = MaterialTheme.colorScheme.surface
) {
Box(contentAlignment = Alignment.Center) {
@@ -256,12 +273,12 @@ private fun FeaturePill(
imageVector = icon,
contentDescription = null,
tint = MaterialTheme.colorScheme.primary,
modifier = Modifier.size(22.dp)
modifier = Modifier.size(20.dp)
)
}
}
Spacer(modifier = Modifier.width(14.dp))
Spacer(modifier = Modifier.width(12.dp))
Column {
Text(
@@ -279,48 +296,3 @@ private fun FeaturePill(
}
}
}
fun onGoogleSignInClicked(
context: Context,
credentialManager: CredentialManager,
onAuthSuccess: () -> Unit,
onAuthError: (String) -> Unit,
scope: CoroutineScope,
onAuthCancelled: () -> Unit = {}
) {
val clientId = try {
context.getString(R.string.default_web_client_id)
} catch (e: Exception) {
onAuthError("Configuration Google manquante (default_web_client_id)")
return
}
val signInOption = GetSignInWithGoogleOption.Builder(serverClientId = clientId).build()
val request = GetCredentialRequest.Builder().addCredentialOption(signInOption).build()
scope.launch {
try {
val activity = context as? Activity
if (activity == null) {
onAuthError("Contexte invalide pour la connexion")
return@launch
}
val result = credentialManager.getCredential(activity, request)
val credential = result.credential
if (credential is CustomCredential && credential.type == TYPE_GOOGLE_ID_TOKEN_CREDENTIAL) {
val googleIdToken = GoogleIdTokenCredential.createFrom(credential.data).idToken
val authCredential = GoogleAuthProvider.getCredential(googleIdToken, null)
Firebase.auth.signInWithCredential(authCredential).await()
onAuthSuccess()
} else {
onAuthError("Type d'identifiant non reconnu")
}
} catch (e: GetCredentialCancellationException) {
Log.w("Auth", "Connexion Google annulée: ${e.message}", e)
onAuthCancelled()
} catch (e: Exception) {
Log.e("Auth", "Échec de la connexion Google", e)
onAuthError(e.localizedMessage ?: "Échec de connexion")
}
}
}
@@ -0,0 +1,185 @@
package com.example.ui.common
import androidx.compose.foundation.BorderStroke
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.Row
import androidx.compose.foundation.layout.Spacer
import androidx.compose.foundation.layout.fillMaxWidth
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.material.icons.Icons
import androidx.compose.material.icons.filled.Close
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.graphics.luminance
import androidx.compose.ui.platform.testTag
import androidx.compose.ui.text.font.FontWeight
import androidx.compose.ui.unit.Dp
import androidx.compose.ui.unit.dp
import com.example.data.model.FoodCategory
@Composable
fun isSatieaDarkTheme(): Boolean {
return MaterialTheme.colorScheme.background.luminance() < 0.5f
}
fun FoodCategory.accentColor(isDark: Boolean): Color = dotColor(isDark)
fun FoodCategory.dotFillColor(isDark: Boolean): Color = dotColor(isDark)
fun FoodCategory.badgeContainerColor(isDark: Boolean): Color = containerColor(isDark)
fun FoodCategory.badgeBorderColor(isDark: Boolean): Color = borderColor(isDark)
fun FoodCategory.badgeTextColor(isDark: Boolean): Color = contentColor(isDark)
@Composable
fun FoodCategoryColorDot(
category: FoodCategory,
modifier: Modifier = Modifier,
size: Dp = 10.dp
) {
val isDark = isSatieaDarkTheme()
val fill = category.dotFillColor(isDark)
val borderColor = if (category == FoodCategory.CHEESE) {
if (isDark) Color(0xFFD5D0BE) else Color(0xFF9C947C)
} else {
fill.copy(alpha = 0.85f)
}
Box(
modifier = modifier
.size(size)
.clip(CircleShape)
.background(fill)
.border(width = if (category == FoodCategory.CHEESE) 1.2.dp else 0.5.dp, color = borderColor, shape = CircleShape)
)
}
@Composable
fun FoodCategoryBadge(
text: String,
category: FoodCategory,
modifier: Modifier = Modifier,
onClick: (() -> Unit)? = null,
onRemove: (() -> Unit)? = null
) {
val isDark = isSatieaDarkTheme()
val shape = RoundedCornerShape(11.dp)
Surface(
shape = shape,
color = category.badgeContainerColor(isDark),
border = BorderStroke(1.dp, category.badgeBorderColor(isDark)),
modifier = modifier
.clip(shape)
.then(if (onClick != null) Modifier.clickable(onClick = onClick) else Modifier)
) {
Row(
modifier = Modifier.padding(
start = 9.dp,
end = if (onRemove != null) 6.dp else 10.dp,
top = 5.dp,
bottom = 5.dp
),
verticalAlignment = Alignment.CenterVertically
) {
FoodCategoryColorDot(category = category, size = 8.dp)
Spacer(modifier = Modifier.width(6.dp))
Text(
text = text,
style = MaterialTheme.typography.labelMedium,
color = category.badgeTextColor(isDark),
fontWeight = FontWeight.SemiBold
)
if (onRemove != null) {
Spacer(modifier = Modifier.width(6.dp))
Icon(
imageVector = Icons.Default.Close,
contentDescription = "Retirer $text",
tint = category.badgeTextColor(isDark).copy(alpha = 0.8f),
modifier = Modifier
.size(18.dp)
.clip(CircleShape)
.clickable(onClick = onRemove)
.padding(2.dp)
)
}
}
}
}
@Composable
fun FoodCategorySelectorRow(
selectedCategory: FoodCategory,
onCategorySelected: (FoodCategory) -> Unit,
modifier: Modifier = Modifier
) {
val isDark = isSatieaDarkTheme()
LazyRow(
horizontalArrangement = Arrangement.spacedBy(8.dp),
modifier = modifier
.fillMaxWidth()
.testTag("food_category_selector_row")
) {
items(FoodCategory.entries, key = { it.name }) { category ->
val isSelected = category == selectedCategory
val shape = RoundedCornerShape(12.dp)
val containerColor = if (isSelected) {
category.badgeContainerColor(isDark).copy(alpha = if (isDark) 0.34f else 0.24f)
} else {
MaterialTheme.colorScheme.surface
}
val borderColor = if (isSelected) {
if (category == FoodCategory.CHEESE) {
if (isDark) Color(0xFFF6F4EC) else Color(0xFF7B735B)
} else {
category.accentColor(isDark)
}
} else {
MaterialTheme.colorScheme.outlineVariant.copy(alpha = 0.55f)
}
Surface(
shape = shape,
color = containerColor,
border = BorderStroke(if (isSelected) 1.5.dp else 1.dp, borderColor),
modifier = Modifier
.clip(shape)
.clickable { onCategorySelected(category) }
.testTag("food_category_chip_${category.name.lowercase()}")
) {
Row(
modifier = Modifier.padding(horizontal = 10.dp, vertical = 7.dp),
verticalAlignment = Alignment.CenterVertically
) {
FoodCategoryColorDot(category = category, size = 9.dp)
Spacer(modifier = Modifier.width(6.dp))
Text(
text = category.shortLabel,
style = MaterialTheme.typography.labelSmall,
color = if (isSelected) category.badgeTextColor(isDark) else MaterialTheme.colorScheme.onSurfaceVariant,
fontWeight = if (isSelected) FontWeight.Bold else FontWeight.Medium
)
}
}
}
}
}
@@ -1,8 +1,5 @@
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
@@ -33,7 +30,6 @@ import androidx.compose.material.icons.filled.FileDownload
import androidx.compose.material.icons.filled.MoreVert
import androidx.compose.material.icons.filled.Restaurant
import androidx.compose.material.icons.filled.TableChart
import androidx.compose.ui.graphics.Color
import androidx.compose.material3.AlertDialog
import androidx.compose.material3.Card
import androidx.compose.material3.CardDefaults
@@ -55,16 +51,22 @@ 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.asImageBitmap
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.layout.ContentScale
import androidx.compose.ui.platform.testTag
import androidx.compose.ui.text.font.FontStyle
import androidx.compose.ui.text.font.FontWeight
import androidx.compose.ui.text.style.TextAlign
import androidx.compose.ui.unit.dp
import coil.compose.AsyncImage
import com.example.data.model.CustomFoodEntry
import com.example.data.model.FoodCategory
import com.example.data.model.HungerSatietyScale
import com.example.data.model.MealEntry
import com.example.data.model.MealType
import com.example.util.ImageUtils
import com.example.ui.common.FoodCategoryBadge
import com.example.ui.journal.components.DailyBenchmarksCard
import com.example.ui.journal.components.DietaryGuideSheet
import java.time.Instant
import java.time.LocalDate
import java.time.ZoneId
@@ -74,6 +76,7 @@ import java.util.Locale
@Composable
fun JournalScreen(
mealsUiState: MealsUiState,
customFoods: List<CustomFoodEntry> = emptyList(),
onAddMealClick: () -> Unit,
onEditMeal: (MealEntry) -> Unit,
onDeleteMeal: (String) -> Unit,
@@ -81,6 +84,12 @@ fun JournalScreen(
onSyncSheetsClick: (() -> Unit)? = null,
spreadsheetUrl: String? = null
) {
var showDietaryGuide by remember { mutableStateOf(false) }
val customCategoryLookup = remember(customFoods) {
customFoods.associate { it.name.lowercase(Locale.FRENCH).trim() to it.resolvedCategory() }
}
Box(
modifier = Modifier
.fillMaxSize()
@@ -139,6 +148,14 @@ fun JournalScreen(
DailyOverviewCard(todayMeals = todayMeals)
}
item {
DailyBenchmarksCard(
todayMeals = todayMeals,
customCategoryLookup = customCategoryLookup,
onOpenGuideClick = { showDietaryGuide = true }
)
}
if (meals.isEmpty()) {
item {
EmptyMealsView(onAddMealClick = onAddMealClick)
@@ -167,13 +184,13 @@ fun JournalScreen(
) {
Icon(
imageVector = Icons.Default.TableChart,
contentDescription = "Synchroniser vers Google Sheets",
contentDescription = "Sauvegarder sur Google Sheets",
modifier = Modifier.size(18.dp),
tint = Color(0xFF0F9D58)
)
Spacer(modifier = Modifier.width(4.dp))
Text(
text = "Sheets",
text = "Drive",
style = MaterialTheme.typography.labelLarge,
color = Color(0xFF0F9D58)
)
@@ -204,6 +221,7 @@ fun JournalScreen(
items(meals, key = { it.id.ifEmpty { it.mealTimestamp.toString() } }) { meal ->
MealCardItem(
meal = meal,
customCategoryLookup = customCategoryLookup,
onEdit = { onEditMeal(meal) },
onDelete = { onDeleteMeal(meal.id) }
)
@@ -230,6 +248,10 @@ fun JournalScreen(
)
}
}
if (showDietaryGuide) {
DietaryGuideSheet(onDismiss = { showDietaryGuide = false })
}
}
@Composable
@@ -331,6 +353,7 @@ private fun DailyOverviewCard(todayMeals: List<MealEntry>) {
@Composable
private fun MealCardItem(
meal: MealEntry,
customCategoryLookup: Map<String, FoodCategory>,
onEdit: () -> Unit,
onDelete: () -> Unit
) {
@@ -511,7 +534,7 @@ private fun MealCardItem(
}
}
// Food Items Badges (with optional weights)
// Color-Coded Food Items Badges
if (parsedFoods.isNotEmpty()) {
Spacer(modifier = Modifier.height(12.dp))
Text(
@@ -526,18 +549,10 @@ private fun MealCardItem(
modifier = Modifier.fillMaxWidth()
) {
parsedFoods.forEach { food ->
Surface(
shape = RoundedCornerShape(10.dp),
color = MaterialTheme.colorScheme.primary.copy(alpha = 0.14f)
) {
Text(
text = food.displayBadge(),
style = MaterialTheme.typography.labelMedium,
color = MaterialTheme.colorScheme.primary,
fontWeight = FontWeight.Medium,
modifier = Modifier.padding(horizontal = 10.dp, vertical = 5.dp)
)
}
FoodCategoryBadge(
text = food.displayBadge(),
category = food.resolvedCategory(customCategoryLookup)
)
}
}
}
@@ -568,7 +583,7 @@ private fun MealCardItem(
text = "Note globale : « ${meal.note} »",
style = MaterialTheme.typography.bodyMedium,
color = MaterialTheme.colorScheme.onSurface.copy(alpha = 0.9f),
fontStyle = androidx.compose.ui.text.font.FontStyle.Italic
fontStyle = FontStyle.Italic
)
}
}
@@ -578,7 +593,7 @@ private fun MealCardItem(
AlertDialog(
onDismissRequest = { showDeleteDialog = false },
title = { Text("Supprimer ce repas ?") },
text = { Text("Cette action est irréversible et supprimera le repas de votre historique synchronisé.") },
text = { Text("Cette action supprimera ce repas de votre journal local.") },
confirmButton = {
TextButton(
onClick = {
@@ -633,7 +648,7 @@ private fun EmptyMealsView(onAddMealClick: () -> Unit) {
Spacer(modifier = Modifier.height(8.dp))
Text(
text = "Prenez 15 secondes pour noter vos aliments (avec ou sans poids), votre faim et votre satiété sur 10.",
text = "Prenez 15 secondes pour noter vos aliments (avec leur code couleur), votre faim et votre satiété sur 10.",
style = MaterialTheme.typography.bodyMedium,
color = MaterialTheme.colorScheme.onBackground.copy(alpha = 0.7f),
textAlign = TextAlign.Center
@@ -8,21 +8,24 @@ import androidx.lifecycle.AndroidViewModel
import androidx.lifecycle.viewModelScope
import com.example.data.model.CustomFoodEntry
import com.example.data.model.DefaultFoodCatalog
import com.example.data.model.FoodCategory
import com.example.data.model.FoodUnit
import com.example.data.model.MealEntry
import com.example.data.model.MealFoodItem
import com.example.data.model.MealType
import com.example.data.model.RecipeEntry
import com.example.data.preferences.GoogleSheetsPreferencesManager
import com.example.data.preferences.ThemePreferencesManager
import com.example.data.repository.MealRepository
import com.example.domain.CsvExportUseCase
import com.example.domain.GoogleSheetsSyncUseCase
import com.example.domain.SheetsRestoreResult
import com.example.domain.SheetsSyncResult
import com.example.domain.WeeklyStatsCalculator
import com.example.notification.MealNotificationManager
import com.example.ui.common.UiEvent
import com.example.ui.theme.AppThemeMode
import com.example.util.CsvImportResult
import com.google.firebase.auth.FirebaseAuth
import com.google.firebase.firestore.FirebaseFirestoreException
import com.example.util.GoogleSheetsAuthHelper
import kotlinx.coroutines.CancellationException
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.channels.Channel
@@ -31,14 +34,13 @@ import kotlinx.coroutines.flow.SharingStarted
import kotlinx.coroutines.flow.StateFlow
import kotlinx.coroutines.flow.asStateFlow
import kotlinx.coroutines.flow.catch
import kotlinx.coroutines.flow.combine
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.time.LocalDate
import java.time.ZoneId
import java.time.format.DateTimeFormatter
import java.util.Locale
sealed interface MealsUiState {
@@ -69,7 +71,8 @@ data class WeeklyStats(
val averageHunger: Float,
val optimalZonePercentage: Int,
val totalMealsLast7Days: Int,
val mealTypeDistribution: Map<MealType, Int>
val mealTypeDistribution: Map<MealType, Int>,
val categoryDistribution: Map<FoodCategory, Int> = emptyMap()
) {
companion object {
fun empty(): WeeklyStats = WeeklyStats(
@@ -78,7 +81,8 @@ data class WeeklyStats(
averageHunger = 0f,
optimalZonePercentage = 0,
totalMealsLast7Days = 0,
mealTypeDistribution = emptyMap()
mealTypeDistribution = emptyMap(),
categoryDistribution = emptyMap()
)
}
}
@@ -88,6 +92,7 @@ class MealViewModel(application: Application) : AndroidViewModel(application) {
private val repository = MealRepository(application)
private val context = application.applicationContext
private val sheetsPrefs = GoogleSheetsPreferencesManager.getInstance(application)
private val themePrefs = ThemePreferencesManager(application)
// Domain Use Cases
private val sheetsSyncUseCase = GoogleSheetsSyncUseCase(context, repository, sheetsPrefs)
@@ -106,12 +111,8 @@ class MealViewModel(application: Application) : AndroidViewModel(application) {
MealsUiState.Success(meals)
}
.catch { error ->
val firestoreError = generateSequence(error) { it.cause }
.filterIsInstance<FirebaseFirestoreException>()
.firstOrNull()
if (firestoreError == null && error is CancellationException) throw error
val rootError = firestoreError ?: error
emit(MealsUiState.Error(rootError.message ?: "Impossible de charger les repas"))
if (error is CancellationException) throw error
emit(MealsUiState.Error(error.message ?: "Impossible de charger les repas"))
}
.stateIn(
scope = viewModelScope,
@@ -119,22 +120,9 @@ 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 }
.filterIsInstance<FirebaseFirestoreException>()
.firstOrNull()
if (firestoreError == null && error is CancellationException) throw error
if (error is CancellationException) throw error
emit(emptyList())
}
.stateIn(
@@ -143,7 +131,36 @@ class MealViewModel(application: Application) : AndroidViewModel(application) {
initialValue = emptyList()
)
private val _themeMode = MutableStateFlow(AppThemeMode.DARK)
val recipes: StateFlow<List<RecipeEntry>> = repository.observeRecipes()
.catch { error ->
if (error is CancellationException) throw error
emit(emptyList())
}
.stateIn(
scope = viewModelScope,
started = SharingStarted.WhileSubscribed(5000L),
initialValue = emptyList()
)
// Asynchronous background computation of WeeklyStats including food category diversity
val weeklyStats: StateFlow<WeeklyStats> = combine(
repository.observeMeals(),
repository.observeCustomFoods()
) { meals, foods ->
val lookup = foods.associate { it.name.lowercase(Locale.FRENCH).trim() to it.resolvedCategory() }
WeeklyStatsCalculator.computeWeeklyStats(
meals = meals,
customCategoryLookup = lookup
)
}
.flowOn(Dispatchers.Default)
.stateIn(
scope = viewModelScope,
started = SharingStarted.WhileSubscribed(5000L),
initialValue = WeeklyStats.empty()
)
private val _themeMode = MutableStateFlow(themePrefs.loadThemeMode())
val themeMode: StateFlow<AppThemeMode> = _themeMode.asStateFlow()
// Quick Log Action triggered from Widget or Notification
@@ -178,6 +195,7 @@ class MealViewModel(application: Application) : AndroidViewModel(application) {
val spreadsheetUrl: StateFlow<String?> = _spreadsheetUrl.asStateFlow()
fun setThemeMode(mode: AppThemeMode) {
themePrefs.saveThemeMode(mode)
_themeMode.value = mode
}
@@ -193,25 +211,44 @@ class MealViewModel(application: Application) : AndroidViewModel(application) {
}
private fun enrichCatalogWithFoodItems(foodItems: List<MealFoodItem>) {
val existingBuiltIn = DefaultFoodCatalog.builtInFoods.map { it.name.lowercase(Locale.FRENCH) }.toSet()
val existingCustom = customFoods.value.map { it.name.lowercase(Locale.FRENCH) }.toSet()
val existingBuiltIn = DefaultFoodCatalog.builtInFoods.associate {
it.name.lowercase(Locale.FRENCH) to it.category
}
val existingCustom = customFoods.value.associateBy { it.name.lowercase(Locale.FRENCH) }
viewModelScope.launch {
foodItems.forEach { item ->
val cleanName = item.name.trim()
val normalized = cleanName.lowercase(Locale.FRENCH)
if (cleanName.isNotEmpty() && normalized !in existingBuiltIn && normalized !in existingCustom) {
repository.saveCustomFood(cleanName, item.unit)
if (cleanName.isEmpty()) return@forEach
val chosenCategory = item.category ?: item.resolvedCategory()
val builtInCategory = existingBuiltIn[normalized]
val existingEntry = existingCustom[normalized]
val shouldSave = when {
builtInCategory == null && existingEntry == null -> true
existingEntry != null && existingEntry.resolvedCategory() != chosenCategory -> true
builtInCategory != null && builtInCategory != chosenCategory -> true
else -> false
}
if (shouldSave) {
repository.saveCustomFood(cleanName, item.unit, chosenCategory)
}
}
}
}
fun addCustomFoodDirectly(name: String, unit: com.example.data.model.FoodUnit) {
fun addCustomFoodDirectly(
name: String,
unit: FoodUnit,
category: FoodCategory? = null
) {
val cleanName = name.trim()
if (cleanName.isEmpty()) return
viewModelScope.launch {
repository.saveCustomFood(cleanName, unit)
repository.saveCustomFood(cleanName, unit, category)
}
}
@@ -248,22 +285,6 @@ class MealViewModel(application: Application) : AndroidViewModel(application) {
}
}
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é"))
}
}
}
fun updateMeal(
meal: MealEntry,
foodItems: List<MealFoodItem>
@@ -299,6 +320,58 @@ class MealViewModel(application: Application) : AndroidViewModel(application) {
}
}
// ------------------------------------------------------------------------
// Recipes CRUD
// ------------------------------------------------------------------------
fun saveRecipe(recipe: RecipeEntry) {
val ingredients = recipe.parsedIngredients()
enrichCatalogWithFoodItems(ingredients)
viewModelScope.launch {
val isNew = recipe.id.isBlank()
val result = repository.saveRecipe(recipe)
if (result.isSuccess) {
val msg = if (isNew) "Recette ajoutée au recueil ✨" else "Recette mise à jour ✨"
emitEvent(UiEvent.ShowSnackbar(msg))
triggerAutoSheetsSyncIfNeeded()
} else {
val err = result.exceptionOrNull()?.localizedMessage ?: "Erreur d'enregistrement de la recette"
emitEvent(UiEvent.ShowSnackbar(err))
}
}
}
fun deleteRecipe(recipeId: String) {
viewModelScope.launch {
val result = repository.deleteRecipe(recipeId)
if (result.isSuccess) {
emitEvent(UiEvent.ShowSnackbar("Recette supprimée"))
triggerAutoSheetsSyncIfNeeded()
} else {
val err = result.exceptionOrNull()?.localizedMessage ?: "Erreur de suppression"
emitEvent(UiEvent.ShowSnackbar(err))
}
}
}
// ------------------------------------------------------------------------
// Google Drive Account & Sheets Sync
// ------------------------------------------------------------------------
fun signOut(context: Context, onComplete: () -> Unit = {}) {
viewModelScope.launch {
try {
GoogleSheetsAuthHelper.signOut(context)
} catch (e: Exception) {
if (e is CancellationException) throw e
} finally {
disconnectGoogleSheets()
onComplete()
emitEvent(UiEvent.ShowSnackbar("Compte Google Drive déconnecté • Mode local actif"))
}
}
}
private fun triggerAutoSheetsSyncIfNeeded() {
if (!sheetsPrefs.isAutoSyncEnabled) return
viewModelScope.launch {
@@ -318,8 +391,12 @@ class MealViewModel(application: Application) : AndroidViewModel(application) {
is SheetsSyncResult.Success -> {
_spreadsheetUrl.value = result.url
_sheetsUiState.value = GoogleSheetsUiState.Success(result.url, result.count, result.timestamp)
val foodsInfo = if (result.foodsCount > 0) " et ${result.foodsCount} aliments" else ""
emitEvent(UiEvent.ShowSnackbar("Synchronisé vers Google Sheets (${result.count} repas$foodsInfo) 📊"))
val summaryParts = buildList {
add("${result.count} repas")
if (result.foodsCount > 0) add("${result.foodsCount} aliments")
if (result.recipesCount > 0) add("${result.recipesCount} recettes")
}.joinToString(", ")
emitEvent(UiEvent.ShowSnackbar("Sauvegardé sur Google Drive ($summaryParts) 📊"))
}
is SheetsSyncResult.RecoverableAuth -> {
_sheetsUiState.value = GoogleSheetsUiState.Error(result.message, result.intent)
@@ -347,15 +424,12 @@ class MealViewModel(application: Application) : AndroidViewModel(application) {
when (val result = sheetsSyncUseCase.restoreFromSheets()) {
is SheetsRestoreResult.Success -> {
_sheetsUiState.value = GoogleSheetsUiState.Idle
val msg = buildString {
append("Restauration réussie ✨ : ")
append("${result.mealsCount} repas")
if (result.foodsCount > 0) {
append(" et ${result.foodsCount} aliments")
}
append(" restaurés")
}
emitEvent(UiEvent.ShowSnackbar(msg))
val summaryParts = buildList {
add("${result.mealsCount} repas")
if (result.foodsCount > 0) add("${result.foodsCount} aliments")
if (result.recipesCount > 0) add("${result.recipesCount} recettes")
}.joinToString(", ")
emitEvent(UiEvent.ShowSnackbar("Restauration réussie ✨ : $summaryParts"))
}
is SheetsRestoreResult.RecoverableAuth -> {
_sheetsUiState.value = GoogleSheetsUiState.Error(result.message, result.intent)
@@ -375,6 +449,10 @@ class MealViewModel(application: Application) : AndroidViewModel(application) {
}
}
// ------------------------------------------------------------------------
// CSV Import / Export & Notifications
// ------------------------------------------------------------------------
fun exportCsvToUri(
targetUri: Uri,
meals: List<MealEntry>
@@ -417,29 +495,6 @@ class MealViewModel(application: Application) : AndroidViewModel(application) {
}
}
fun syncCloudToLocal() {
viewModelScope.launch {
val result = repository.syncCloudToLocal()
result.fold(
onSuccess = { count ->
emitEvent(UiEvent.ShowSnackbar("Compte lié ($count repas Cloud synchronisés) ☁️"))
// Trigger uploading any local meals that were created offline
syncLocalToCloud()
},
onFailure = { err ->
val msg = err.localizedMessage ?: "Erreur lors de la synchronisation"
emitEvent(UiEvent.ShowSnackbar(msg))
}
)
}
}
fun syncLocalToCloud() {
viewModelScope.launch {
repository.syncLocalToCloud()
}
}
fun shareCsv(meals: List<MealEntry>) {
viewModelScope.launch {
val result = csvExportUseCase.createShareIntent(meals)
@@ -476,6 +531,7 @@ class MealViewModel(application: Application) : AndroidViewModel(application) {
}
fun computeWeeklyStats(meals: List<MealEntry>, zoneId: ZoneId = ZoneId.systemDefault()): WeeklyStats {
return com.example.domain.WeeklyStatsCalculator.computeWeeklyStats(meals, zoneId)
val lookup = customFoods.value.associate { it.name.lowercase(Locale.FRENCH).trim() to it.resolvedCategory() }
return WeeklyStatsCalculator.computeWeeklyStats(meals, zoneId, lookup)
}
}
@@ -0,0 +1,565 @@
package com.example.ui.journal.components
import androidx.compose.animation.AnimatedVisibility
import androidx.compose.foundation.BorderStroke
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.rememberScrollState
import androidx.compose.foundation.shape.RoundedCornerShape
import androidx.compose.foundation.verticalScroll
import androidx.compose.material.icons.Icons
import androidx.compose.material.icons.automirrored.filled.MenuBook
import androidx.compose.material.icons.filled.Close
import androidx.compose.material.icons.filled.ExpandLess
import androidx.compose.material.icons.filled.ExpandMore
import androidx.compose.material.icons.filled.Scale
import androidx.compose.material.icons.filled.Spa
import androidx.compose.material3.Card
import androidx.compose.material3.CardDefaults
import androidx.compose.material3.ExperimentalMaterial3Api
import androidx.compose.material3.HorizontalDivider
import androidx.compose.material3.Icon
import androidx.compose.material3.IconButton
import androidx.compose.material3.MaterialTheme
import androidx.compose.material3.ModalBottomSheet
import androidx.compose.material3.Surface
import androidx.compose.material3.Text
import androidx.compose.material3.TextButton
import androidx.compose.material3.rememberModalBottomSheetState
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.text.font.FontStyle
import androidx.compose.ui.text.font.FontWeight
import androidx.compose.ui.unit.dp
import com.example.data.model.DietaryReferenceGuide
import com.example.data.model.FoodCategory
import com.example.data.model.FoodUnit
import com.example.data.model.MealEntry
import com.example.ui.common.FoodCategoryColorDot
import com.example.ui.common.badgeBorderColor
import com.example.ui.common.badgeContainerColor
import com.example.ui.common.badgeTextColor
import com.example.ui.common.isSatieaDarkTheme
import java.util.Locale
private data class CategoryDaySummary(
val category: FoodCategory,
val count: Int,
val totalGrams: Double,
val totalPortions: Double
)
@OptIn(ExperimentalLayoutApi::class)
@Composable
fun DailyBenchmarksCard(
todayMeals: List<MealEntry>,
customCategoryLookup: Map<String, FoodCategory>,
onOpenGuideClick: () -> Unit,
modifier: Modifier = Modifier
) {
var expanded by remember { mutableStateOf(false) }
val isDark = isSatieaDarkTheme()
val summariesByCategory = remember(todayMeals, customCategoryLookup) {
val map = mutableMapOf<FoodCategory, CategoryDaySummary>()
todayMeals.forEach { meal ->
meal.parsedFoodItems().forEach { item ->
val cat = item.resolvedCategory(customCategoryLookup)
val current = map[cat] ?: CategoryDaySummary(cat, 0, 0.0, 0.0)
val addG = if (item.unit == FoodUnit.G && item.weight != null) item.weight else 0.0
val addP = if (item.unit == FoodUnit.PORTION && item.weight != null) item.weight else 0.0
map[cat] = current.copy(
count = current.count + 1,
totalGrams = current.totalGrams + addG,
totalPortions = current.totalPortions + addP
)
}
}
map
}
val activeCoreCategories = remember(summariesByCategory) {
FoodCategory.benchmarkCategories.filter { (summariesByCategory[it]?.count ?: 0) > 0 }
}
Card(
modifier = modifier
.fillMaxWidth()
.testTag("daily_benchmarks_card"),
shape = RoundedCornerShape(20.dp),
colors = CardDefaults.cardColors(
containerColor = MaterialTheme.colorScheme.surface
),
border = BorderStroke(1.dp, MaterialTheme.colorScheme.outlineVariant.copy(alpha = 0.35f))
) {
Column(
modifier = Modifier
.fillMaxWidth()
.padding(horizontal = 16.dp, vertical = 14.dp)
) {
Row(
modifier = Modifier
.fillMaxWidth()
.clip(RoundedCornerShape(12.dp))
.clickable { expanded = !expanded }
.padding(vertical = 2.dp),
horizontalArrangement = Arrangement.SpaceBetween,
verticalAlignment = Alignment.CenterVertically
) {
Row(
verticalAlignment = Alignment.CenterVertically,
modifier = Modifier.weight(1f)
) {
Icon(
imageVector = Icons.Default.Spa,
contentDescription = null,
tint = MaterialTheme.colorScheme.primary,
modifier = Modifier.size(18.dp)
)
Spacer(modifier = Modifier.width(8.dp))
Column {
Text(
text = "Mes repères du jour",
style = MaterialTheme.typography.titleSmall,
color = MaterialTheme.colorScheme.onSurface,
fontWeight = FontWeight.Bold
)
Text(
text = if (activeCoreCategories.isEmpty()) {
"Code couleur & familles alimentaires"
} else {
"${activeCoreCategories.size} famille${if (activeCoreCategories.size > 1) "s" else ""} présentes aujourd'hui"
},
style = MaterialTheme.typography.bodySmall,
color = MaterialTheme.colorScheme.onSurfaceVariant
)
}
}
Row(verticalAlignment = Alignment.CenterVertically) {
TextButton(
onClick = onOpenGuideClick,
modifier = Modifier.testTag("open_dietary_guide_button")
) {
Icon(
imageVector = Icons.AutoMirrored.Filled.MenuBook,
contentDescription = "Ouvrir le guide des repères",
modifier = Modifier.size(16.dp),
tint = MaterialTheme.colorScheme.primary
)
Spacer(modifier = Modifier.width(4.dp))
Text(
text = "Guide",
style = MaterialTheme.typography.labelMedium,
color = MaterialTheme.colorScheme.primary
)
}
Icon(
imageVector = if (expanded) Icons.Default.ExpandLess else Icons.Default.ExpandMore,
contentDescription = if (expanded) "Replier les repères" else "Afficher les repères",
tint = MaterialTheme.colorScheme.onSurfaceVariant
)
}
}
// Compact color strip of today's families when collapsed
if (!expanded && activeCoreCategories.isNotEmpty()) {
Spacer(modifier = Modifier.height(10.dp))
FlowRow(
horizontalArrangement = Arrangement.spacedBy(6.dp),
verticalArrangement = Arrangement.spacedBy(6.dp),
modifier = Modifier.fillMaxWidth()
) {
activeCoreCategories.forEach { cat ->
val summary = summariesByCategory[cat]!!
val detail = formatObservedShort(summary)
Surface(
shape = RoundedCornerShape(10.dp),
color = cat.badgeContainerColor(isDark),
border = BorderStroke(1.dp, cat.badgeBorderColor(isDark))
) {
Row(
modifier = Modifier.padding(horizontal = 8.dp, vertical = 4.dp),
verticalAlignment = Alignment.CenterVertically
) {
FoodCategoryColorDot(category = cat, size = 8.dp)
Spacer(modifier = Modifier.width(5.dp))
Text(
text = "${cat.shortLabel} · $detail",
style = MaterialTheme.typography.labelSmall,
color = cat.badgeTextColor(isDark),
fontWeight = FontWeight.Medium
)
}
}
}
}
}
AnimatedVisibility(visible = expanded) {
Column(modifier = Modifier.padding(top = 12.dp)) {
HorizontalDivider(
color = MaterialTheme.colorScheme.outlineVariant.copy(alpha = 0.35f)
)
Spacer(modifier = Modifier.height(10.dp))
FoodCategory.benchmarkCategories.forEach { category ->
val summary = summariesByCategory[category]
Row(
modifier = Modifier
.fillMaxWidth()
.padding(vertical = 5.dp),
verticalAlignment = Alignment.CenterVertically,
horizontalArrangement = Arrangement.SpaceBetween
) {
Row(
verticalAlignment = Alignment.CenterVertically,
modifier = Modifier.weight(1f)
) {
FoodCategoryColorDot(category = category, size = 10.dp)
Spacer(modifier = Modifier.width(10.dp))
Column {
Text(
text = category.displayName,
style = MaterialTheme.typography.labelMedium,
color = MaterialTheme.colorScheme.onSurface,
fontWeight = FontWeight.SemiBold
)
Text(
text = "Repère : ${category.dailyGuide}",
style = MaterialTheme.typography.labelSmall,
color = MaterialTheme.colorScheme.onSurfaceVariant
)
}
}
Spacer(modifier = Modifier.width(8.dp))
if (summary != null && summary.count > 0) {
Surface(
shape = RoundedCornerShape(8.dp),
color = category.badgeContainerColor(isDark),
border = BorderStroke(1.dp, category.badgeBorderColor(isDark))
) {
Text(
text = formatObservedShort(summary),
style = MaterialTheme.typography.labelSmall,
color = category.badgeTextColor(isDark),
fontWeight = FontWeight.SemiBold,
modifier = Modifier.padding(horizontal = 8.dp, vertical = 3.dp)
)
}
} else {
Text(
text = "—",
style = MaterialTheme.typography.labelMedium,
color = MaterialTheme.colorScheme.onSurfaceVariant.copy(alpha = 0.5f)
)
}
}
}
Spacer(modifier = Modifier.height(8.dp))
Text(
text = "Ces repères sont indicatifs et bienveillants : adaptez toujours selon votre faim et votre plaisir.",
style = MaterialTheme.typography.bodySmall,
fontStyle = FontStyle.Italic,
color = MaterialTheme.colorScheme.onSurfaceVariant
)
}
}
}
}
}
private fun formatObservedShort(summary: CategoryDaySummary): String {
return when {
summary.totalGrams > 0.0 -> {
val gStr = if (summary.totalGrams % 1.0 == 0.0) {
summary.totalGrams.toInt().toString()
} else {
String.format(Locale.FRENCH, "%.1f", summary.totalGrams)
}
"${summary.count}× · $gStr g"
}
summary.totalPortions > 0.0 -> {
val pStr = if (summary.totalPortions % 1.0 == 0.0) {
summary.totalPortions.toInt().toString()
} else {
String.format(Locale.FRENCH, "%.1f", summary.totalPortions)
}
"$pStr port."
}
else -> "${summary.count}×"
}
}
@OptIn(ExperimentalMaterial3Api::class)
@Composable
fun DietaryGuideSheet(
onDismiss: () -> Unit
) {
val sheetState = rememberModalBottomSheetState(skipPartiallyExpanded = true)
val isDark = isSatieaDarkTheme()
ModalBottomSheet(
onDismissRequest = onDismiss,
sheetState = sheetState,
containerColor = MaterialTheme.colorScheme.surface,
dragHandle = null
) {
Column(
modifier = Modifier
.fillMaxWidth()
.verticalScroll(rememberScrollState())
.padding(horizontal = 22.dp, vertical = 20.dp)
.testTag("dietary_guide_sheet")
) {
Row(
modifier = Modifier.fillMaxWidth(),
horizontalArrangement = Arrangement.SpaceBetween,
verticalAlignment = Alignment.CenterVertically
) {
Column(modifier = Modifier.weight(1f)) {
Text(
text = "Repères & Équivalences",
style = MaterialTheme.typography.headlineSmall,
color = MaterialTheme.colorScheme.onSurface,
fontWeight = FontWeight.Bold
)
Text(
text = "Votre mémo personnel, sans restriction ni culpabilité",
style = MaterialTheme.typography.bodySmall,
color = MaterialTheme.colorScheme.onSurfaceVariant
)
}
IconButton(
onClick = onDismiss,
modifier = Modifier.testTag("close_dietary_guide_button")
) {
Icon(
imageVector = Icons.Default.Close,
contentDescription = "Fermer le guide"
)
}
}
Spacer(modifier = Modifier.height(16.dp))
// Section 1: Starch Equivalences Card
Surface(
shape = RoundedCornerShape(18.dp),
color = FoodCategory.STARCH.badgeContainerColor(isDark),
border = BorderStroke(1.dp, FoodCategory.STARCH.badgeBorderColor(isDark)),
modifier = Modifier.fillMaxWidth()
) {
Column(modifier = Modifier.padding(16.dp)) {
Row(verticalAlignment = Alignment.CenterVertically) {
Icon(
imageVector = Icons.Default.Scale,
contentDescription = null,
tint = FoodCategory.STARCH.badgeTextColor(isDark),
modifier = Modifier.size(18.dp)
)
Spacer(modifier = Modifier.width(8.dp))
Text(
text = "Équivalences féculents",
style = MaterialTheme.typography.titleSmall,
color = FoodCategory.STARCH.badgeTextColor(isDark),
fontWeight = FontWeight.Bold
)
}
Spacer(modifier = Modifier.height(4.dp))
Text(
text = "Base repère : env. 90 g crus par repas",
style = MaterialTheme.typography.labelSmall,
color = MaterialTheme.colorScheme.onSurfaceVariant
)
Spacer(modifier = Modifier.height(10.dp))
DietaryReferenceGuide.starchEquivalences.forEach { eq ->
Row(
modifier = Modifier
.fillMaxWidth()
.padding(vertical = 3.dp),
horizontalArrangement = Arrangement.SpaceBetween,
verticalAlignment = Alignment.CenterVertically
) {
Text(
text = eq.label,
style = MaterialTheme.typography.bodySmall,
color = MaterialTheme.colorScheme.onSurface,
modifier = Modifier.weight(1f)
)
Spacer(modifier = Modifier.width(8.dp))
Text(
text = eq.amount,
style = MaterialTheme.typography.labelMedium,
color = FoodCategory.STARCH.badgeTextColor(isDark),
fontWeight = FontWeight.Bold
)
}
}
}
}
Spacer(modifier = Modifier.height(18.dp))
// Section 2: Color Code & Daily Benchmarks
Text(
text = "Code couleur & Repères journaliers",
style = MaterialTheme.typography.titleSmall,
color = MaterialTheme.colorScheme.onSurface,
fontWeight = FontWeight.Bold
)
Spacer(modifier = Modifier.height(10.dp))
FoodCategory.benchmarkCategories.forEach { category ->
Surface(
shape = RoundedCornerShape(14.dp),
color = MaterialTheme.colorScheme.surfaceVariant.copy(alpha = 0.4f),
modifier = Modifier
.fillMaxWidth()
.padding(vertical = 4.dp)
) {
Row(
modifier = Modifier
.fillMaxWidth()
.padding(12.dp),
verticalAlignment = Alignment.Top
) {
FoodCategoryColorDot(
category = category,
size = 12.dp,
modifier = Modifier.padding(top = 4.dp)
)
Spacer(modifier = Modifier.width(12.dp))
Column(modifier = Modifier.weight(1f)) {
Row(
modifier = Modifier.fillMaxWidth(),
horizontalArrangement = Arrangement.SpaceBetween,
verticalAlignment = Alignment.CenterVertically
) {
Text(
text = category.displayName,
style = MaterialTheme.typography.labelLarge,
color = MaterialTheme.colorScheme.onSurface,
fontWeight = FontWeight.Bold,
modifier = Modifier.weight(1f)
)
Spacer(modifier = Modifier.width(8.dp))
Text(
text = category.shortLabel,
style = MaterialTheme.typography.labelSmall,
color = category.badgeTextColor(isDark),
fontWeight = FontWeight.SemiBold
)
}
Spacer(modifier = Modifier.height(3.dp))
Text(
text = category.dailyGuide,
style = MaterialTheme.typography.bodySmall,
color = MaterialTheme.colorScheme.onSurface
)
category.alternativeNote?.let { note ->
Spacer(modifier = Modifier.height(2.dp))
Text(
text = note,
style = MaterialTheme.typography.bodySmall,
color = MaterialTheme.colorScheme.onSurfaceVariant
)
}
}
}
}
}
Spacer(modifier = Modifier.height(18.dp))
// Section 3: Sample Day Ideas from PDF
Text(
text = "Exemple de journée type",
style = MaterialTheme.typography.titleSmall,
color = MaterialTheme.colorScheme.onSurface,
fontWeight = FontWeight.Bold
)
Spacer(modifier = Modifier.height(8.dp))
Surface(
shape = RoundedCornerShape(14.dp),
color = MaterialTheme.colorScheme.surfaceVariant.copy(alpha = 0.35f),
modifier = Modifier
.fillMaxWidth()
.padding(vertical = 4.dp)
) {
Column(modifier = Modifier.padding(14.dp)) {
DietaryReferenceGuide.sampleDayExamples.forEach { mealPlan ->
SampleMealRow(
label = mealPlan.mealTitle,
content = mealPlan.items.joinToString(" • ")
)
}
}
}
Spacer(modifier = Modifier.height(14.dp))
// Section 4: Gentle Pleasure Reminder
Surface(
shape = RoundedCornerShape(14.dp),
color = FoodCategory.PLEASURE.badgeContainerColor(isDark),
border = BorderStroke(1.dp, FoodCategory.PLEASURE.badgeBorderColor(isDark)),
modifier = Modifier.fillMaxWidth()
) {
Text(
text = "💜 ${DietaryReferenceGuide.PLEASURE_REMINDER}",
style = MaterialTheme.typography.bodySmall,
color = MaterialTheme.colorScheme.onSurface,
modifier = Modifier.padding(14.dp)
)
}
Spacer(modifier = Modifier.height(24.dp))
}
}
}
@Composable
private fun SampleMealRow(label: String, content: String) {
Row(
modifier = Modifier
.fillMaxWidth()
.padding(vertical = 2.dp)
) {
Text(
text = "$label : ",
style = MaterialTheme.typography.labelSmall,
color = MaterialTheme.colorScheme.onSurface,
fontWeight = FontWeight.SemiBold,
modifier = Modifier.width(56.dp)
)
Text(
text = content,
style = MaterialTheme.typography.bodySmall,
color = MaterialTheme.colorScheme.onSurfaceVariant,
modifier = Modifier.weight(1f)
)
}
}
@@ -48,10 +48,12 @@ import androidx.compose.ui.text.font.FontWeight
import androidx.compose.ui.unit.dp
import com.example.data.model.CustomFoodEntry
import com.example.data.model.DefaultFoodCatalog
import com.example.data.model.FoodCategory
import com.example.data.model.FoodUnit
import com.example.data.model.MealEntry
import com.example.data.model.MealFoodItem
import com.example.data.model.MealType
import com.example.ui.journal.components.DietaryGuideSheet
import com.example.ui.meal.components.FoodItemBuilderSection
import com.example.ui.meal.components.MealDateTimePicker
import com.example.ui.meal.components.MealHungerSatietySection
@@ -85,13 +87,16 @@ fun MealEntrySheet(
initialMeal: MealEntry? = null,
defaultMealType: MealType = MealType.LUNCH,
customFoods: List<CustomFoodEntry> = emptyList(),
onAddCustomFood: (String, FoodUnit) -> Unit = { _, _ -> },
onAddCustomFood: (String, FoodUnit, FoodCategory?) -> Unit = { _, _, _ -> },
onDismiss: () -> Unit,
onSaveMeal: (MealType, Long, Int, Int, String, List<MealFoodItem>, List<String>) -> Unit
) {
val sheetState = rememberModalBottomSheetState(skipPartiallyExpanded = true)
val context = LocalContext.current
val coroutineScope = rememberCoroutineScope()
val isEditingExisting = initialMeal != null && initialMeal.id.isNotBlank()
var showDietaryGuide by remember { mutableStateOf(false) }
var selectedType by rememberSaveable {
mutableStateOf(if (initialMeal != null) MealType.fromString(initialMeal.mealType) else defaultMealType)
@@ -133,17 +138,24 @@ fun MealEntrySheet(
mutableStateListOf<String>()
}
val customCategoryLookup = remember(customFoods) {
customFoods.associate { it.name.lowercase(Locale.FRENCH).trim() to it.resolvedCategory() }
}
// Current food builder input state
var foodNameInput by rememberSaveable { mutableStateOf("") }
var foodWeightInput by rememberSaveable { mutableStateOf("") }
var selectedFoodUnit by rememberSaveable { mutableStateOf(FoodUnit.G) }
var selectedFoodCategory by rememberSaveable { mutableStateOf(FoodCategory.OTHER) }
var hasUserOverriddenCategory by rememberSaveable { mutableStateOf(false) }
// Combine custom foods (user enriched) + built-in catalog
val mergedCatalog = remember(customFoods) {
val customMapped = customFoods.map {
DefaultFoodCatalog.CatalogFood(
name = it.name,
defaultUnit = FoodUnit.fromCode(it.defaultUnit)
defaultUnit = FoodUnit.fromCode(it.defaultUnit),
category = it.resolvedCategory()
)
}
val customLowerSet = customMapped.map { it.name.lowercase(Locale.FRENCH) }.toSet()
@@ -175,10 +187,16 @@ fun MealEntrySheet(
val cleanName = foodNameInput.trim()
if (cleanName.isNotEmpty() && foodItemsList.size < 30) {
val parsedWeight = foodWeightInput.trim().replace(",", ".").toDoubleOrNull()?.takeIf { it > 0.0 }
val resolvedCat = if (hasUserOverriddenCategory) {
selectedFoodCategory
} else {
FoodCategory.inferFromName(cleanName, customCategoryLookup)
}
val newItem = MealFoodItem(
name = cleanName,
weight = parsedWeight,
unit = selectedFoodUnit
unit = selectedFoodUnit,
category = resolvedCat
)
val existingIndex = foodItemsList.indexOfFirst { it.name.equals(cleanName, ignoreCase = true) }
if (existingIndex >= 0) {
@@ -186,12 +204,14 @@ fun MealEntrySheet(
} else {
foodItemsList.add(newItem)
}
if (isNewCustomFood) {
onAddCustomFood(cleanName, selectedFoodUnit)
if (isNewCustomFood || hasUserOverriddenCategory) {
onAddCustomFood(cleanName, selectedFoodUnit, resolvedCat)
}
foodNameInput = ""
foodWeightInput = ""
selectedFoodUnit = FoodUnit.G
selectedFoodCategory = FoodCategory.OTHER
hasUserOverriddenCategory = false
}
}
@@ -214,7 +234,6 @@ fun MealEntrySheet(
}
val handleDismiss = {
// Clean up only uncommitted new photos; do NOT delete existing saved photos
newlyCapturedPhotos.forEach { photoUri ->
ImageUtils.deletePhotoFile(context, photoUri)
}
@@ -239,15 +258,15 @@ fun MealEntrySheet(
horizontalArrangement = Arrangement.SpaceBetween,
verticalAlignment = Alignment.CenterVertically
) {
Column {
Column(modifier = Modifier.weight(1f)) {
Text(
text = if (initialMeal == null) "Noter un repas" else "Modifier / Corriger le repas",
text = if (isEditingExisting) "Modifier / Corriger le repas" else "Noter un repas",
style = MaterialTheme.typography.headlineMedium,
color = MaterialTheme.colorScheme.onSurface,
fontWeight = FontWeight.Bold
)
Text(
text = "Échelle sur 10, aliments pesés (optionnel) et note globale",
text = "Échelle sur 10, aliments colorés (optionnel) et note globale",
style = MaterialTheme.typography.bodySmall,
color = MaterialTheme.colorScheme.onSurfaceVariant
)
@@ -309,16 +328,34 @@ fun MealEntrySheet(
Spacer(modifier = Modifier.height(22.dp))
// Subcomponent 5: Food items builder & flow-row chips
// Subcomponent 5: Color-coded Food items builder & flow-row chips
FoodItemBuilderSection(
foodItemsList = foodItemsList,
matchingSuggestions = matchingSuggestions,
foodNameInput = foodNameInput,
onFoodNameChange = { foodNameInput = it },
onFoodNameChange = { input ->
foodNameInput = input
if (!hasUserOverriddenCategory) {
selectedFoodCategory = if (input.isBlank()) {
FoodCategory.OTHER
} else {
FoodCategory.inferFromName(input, customCategoryLookup)
}
}
if (input.isBlank()) {
hasUserOverriddenCategory = false
selectedFoodCategory = FoodCategory.OTHER
}
},
foodWeightInput = foodWeightInput,
onFoodWeightChange = { foodWeightInput = it },
selectedFoodUnit = selectedFoodUnit,
onFoodUnitSelected = { selectedFoodUnit = it },
selectedFoodCategory = selectedFoodCategory,
onFoodCategorySelected = { category ->
selectedFoodCategory = category
hasUserOverriddenCategory = true
},
isNewCustomFood = isNewCustomFood,
onAddFoodItem = { addCurrentFoodItem() },
onItemClickForEdit = { item ->
@@ -327,11 +364,14 @@ fun MealEntrySheet(
if (it % 1.0 == 0.0) it.toInt().toString() else it.toString()
} ?: ""
selectedFoodUnit = item.unit
selectedFoodCategory = item.resolvedCategory(customCategoryLookup)
hasUserOverriddenCategory = true
foodItemsList.remove(item)
},
onRemoveFoodItem = { item ->
foodItemsList.remove(item)
}
},
onOpenGuideClick = { showDietaryGuide = true }
)
Spacer(modifier = Modifier.height(20.dp))
@@ -382,7 +422,6 @@ fun MealEntrySheet(
if (foodNameInput.trim().isNotEmpty()) {
addCurrentFoodItem()
}
// Physically delete only photos marked for deletion that were not re-added
photosMarkedForDeletion.forEach { photoUri ->
if (!photoUrisList.contains(photoUri)) {
ImageUtils.deletePhotoFile(context, photoUri)
@@ -408,7 +447,7 @@ fun MealEntrySheet(
)
) {
Text(
text = if (initialMeal == null) "Enregistrer le repas" else "Enregistrer le correctif",
text = if (isEditingExisting) "Enregistrer le correctif" else "Enregistrer le repas",
style = MaterialTheme.typography.titleSmall
)
}
@@ -417,4 +456,8 @@ fun MealEntrySheet(
Spacer(modifier = Modifier.height(16.dp))
}
}
if (showDietaryGuide) {
DietaryGuideSheet(onDismiss = { showDietaryGuide = false })
}
}
@@ -1,6 +1,5 @@
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
@@ -14,10 +13,10 @@ 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.automirrored.filled.MenuBook
import androidx.compose.material.icons.filled.Add
import androidx.compose.material.icons.filled.Close
import androidx.compose.material.icons.filled.RestaurantMenu
@@ -34,17 +33,21 @@ 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.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.FoodCategory
import com.example.data.model.FoodUnit
import com.example.data.model.MealFoodItem
import com.example.ui.common.FoodCategoryBadge
import com.example.ui.common.FoodCategoryColorDot
import com.example.ui.common.FoodCategorySelectorRow
@OptIn(ExperimentalLayoutApi::class)
@Composable
@@ -57,10 +60,16 @@ fun FoodItemBuilderSection(
onFoodWeightChange: (String) -> Unit,
selectedFoodUnit: FoodUnit,
onFoodUnitSelected: (FoodUnit) -> Unit,
selectedFoodCategory: FoodCategory,
onFoodCategorySelected: (FoodCategory) -> Unit,
isNewCustomFood: Boolean,
onAddFoodItem: () -> Unit,
onItemClickForEdit: (MealFoodItem) -> Unit,
onRemoveFoodItem: (MealFoodItem) -> Unit,
sectionTitle: String = "3. Aliments & Poids (optionnel)",
addButtonLabelPrefix: String = "Ajouter à l'assiette",
addedListCaption: String = "Aliments dans l'assiette (touchez pour modifier poids ou couleur) :",
onOpenGuideClick: (() -> Unit)? = null,
modifier: Modifier = Modifier
) {
Surface(
@@ -78,7 +87,10 @@ fun FoodItemBuilderSection(
horizontalArrangement = Arrangement.SpaceBetween,
verticalAlignment = Alignment.CenterVertically
) {
Row(verticalAlignment = Alignment.CenterVertically) {
Row(
verticalAlignment = Alignment.CenterVertically,
modifier = Modifier.weight(1f)
) {
Icon(
imageVector = Icons.Default.RestaurantMenu,
contentDescription = null,
@@ -87,31 +99,53 @@ fun FoodItemBuilderSection(
)
Spacer(modifier = Modifier.width(8.dp))
Text(
text = "3. Aliments & Poids (optionnel)",
text = sectionTitle,
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
)
Row(verticalAlignment = Alignment.CenterVertically) {
if (onOpenGuideClick != null) {
TextButton(
onClick = onOpenGuideClick,
modifier = Modifier.testTag("builder_equivalences_button")
) {
Icon(
imageVector = Icons.AutoMirrored.Filled.MenuBook,
contentDescription = "Voir les équivalences",
modifier = Modifier.size(15.dp),
tint = MaterialTheme.colorScheme.primary
)
Spacer(modifier = Modifier.width(4.dp))
Text(
text = "Équivalences",
style = MaterialTheme.typography.labelSmall,
color = MaterialTheme.colorScheme.primary,
fontWeight = FontWeight.SemiBold
)
}
}
Text(
text = "${foodItemsList.size}",
style = MaterialTheme.typography.labelSmall,
color = MaterialTheme.colorScheme.primary,
fontWeight = FontWeight.Bold
)
}
}
Spacer(modifier = Modifier.height(4.dp))
Text(
text = "Sélectionnez un aliment suggéré ou tapez un nouvel aliment pour enrichir votre catalogue.",
text = "Sélectionnez un aliment ou tapez-en un nouveau : sa couleur est détectée automatiquement et modifiable ci-dessous.",
style = MaterialTheme.typography.bodySmall,
color = MaterialTheme.colorScheme.onSurfaceVariant
)
Spacer(modifier = Modifier.height(10.dp))
// Auto-complete / Quick suggestions row
// Auto-complete / Quick suggestions row with color dots
if (matchingSuggestions.isNotEmpty()) {
LazyRow(
horizontalArrangement = Arrangement.spacedBy(8.dp),
@@ -122,6 +156,10 @@ fun FoodItemBuilderSection(
onClick = {
onFoodNameChange(suggestion.name)
onFoodUnitSelected(suggestion.defaultUnit)
onFoodCategorySelected(suggestion.category)
},
icon = {
FoodCategoryColorDot(category = suggestion.category, size = 9.dp)
},
label = {
Text(
@@ -147,7 +185,10 @@ fun FoodItemBuilderSection(
.fillMaxWidth()
.testTag("food_name_input"),
placeholder = {
Text("Nom de l'aliment (ex: Riz basmati, Saumon, Pomme...)")
Text("Nom de l'aliment (ex: Riz basmati, Saumon, Comté...)")
},
leadingIcon = {
FoodCategoryColorDot(category = selectedFoodCategory, size = 11.dp)
},
singleLine = true,
shape = RoundedCornerShape(12.dp),
@@ -167,7 +208,7 @@ fun FoodItemBuilderSection(
if (isNewCustomFood) {
Spacer(modifier = Modifier.height(4.dp))
Text(
text = "✨ « ${foodNameInput.trim()} » sera ajouté automatiquement à votre catalogue d'aliments",
text = "✨ « ${foodNameInput.trim()} » sera mémorisé avec sa couleur dans votre catalogue",
style = MaterialTheme.typography.labelSmall,
color = MaterialTheme.colorScheme.secondary
)
@@ -175,7 +216,21 @@ fun FoodItemBuilderSection(
Spacer(modifier = Modifier.height(10.dp))
// Optional Weight + Unit Selector + Add Button
// Food Category Color Selector
Text(
text = "Famille / Code couleur :",
style = MaterialTheme.typography.labelSmall,
color = MaterialTheme.colorScheme.onSurfaceVariant
)
Spacer(modifier = Modifier.height(6.dp))
FoodCategorySelectorRow(
selectedCategory = selectedFoodCategory,
onCategorySelected = onFoodCategorySelected
)
Spacer(modifier = Modifier.height(10.dp))
// Optional Weight + Unit Selector
Row(
modifier = Modifier.fillMaxWidth(),
verticalAlignment = Alignment.CenterVertically,
@@ -251,19 +306,19 @@ fun FoodItemBuilderSection(
Spacer(modifier = Modifier.width(6.dp))
Text(
text = if (foodWeightInput.isNotBlank()) {
"Ajouter à l'assiette (${foodWeightInput.trim()} ${selectedFoodUnit.label})"
"$addButtonLabelPrefix (${foodWeightInput.trim()} ${selectedFoodUnit.label})"
} else {
"Ajouter à l'assiette (sans poids)"
"$addButtonLabelPrefix (sans poids)"
},
style = MaterialTheme.typography.labelLarge
)
}
// Added food items badges
// Added color-coded food items badges
if (foodItemsList.isNotEmpty()) {
Spacer(modifier = Modifier.height(14.dp))
Text(
text = "Aliments dans l'assiette (touchez pour modifier le poids) :",
text = addedListCaption,
style = MaterialTheme.typography.labelSmall,
color = MaterialTheme.colorScheme.onSurfaceVariant
)
@@ -275,36 +330,12 @@ fun FoodItemBuilderSection(
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)
)
}
}
FoodCategoryBadge(
text = item.displayBadge(),
category = item.resolvedCategory(),
onClick = { onItemClickForEdit(item) },
onRemove = { onRemoveFoodItem(item) }
)
}
}
}
@@ -0,0 +1,473 @@
package com.example.ui.recipes
import androidx.compose.foundation.BorderStroke
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.rememberScrollState
import androidx.compose.foundation.shape.CircleShape
import androidx.compose.foundation.shape.RoundedCornerShape
import androidx.compose.foundation.verticalScroll
import androidx.compose.material.icons.Icons
import androidx.compose.material.icons.filled.Add
import androidx.compose.material.icons.filled.CheckCircle
import androidx.compose.material.icons.filled.Close
import androidx.compose.material.icons.filled.Delete
import androidx.compose.material.icons.filled.Edit
import androidx.compose.material.icons.filled.RadioButtonUnchecked
import androidx.compose.material.icons.filled.Remove
import androidx.compose.material.icons.filled.Restaurant
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.ExperimentalMaterial3Api
import androidx.compose.material3.HorizontalDivider
import androidx.compose.material3.Icon
import androidx.compose.material3.IconButton
import androidx.compose.material3.MaterialTheme
import androidx.compose.material3.ModalBottomSheet
import androidx.compose.material3.Surface
import androidx.compose.material3.Text
import androidx.compose.material3.TextButton
import androidx.compose.material3.rememberModalBottomSheetState
import androidx.compose.runtime.Composable
import androidx.compose.runtime.getValue
import androidx.compose.runtime.mutableIntStateOf
import androidx.compose.runtime.mutableStateListOf
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.layout.ContentScale
import androidx.compose.ui.platform.testTag
import androidx.compose.ui.text.font.FontStyle
import androidx.compose.ui.text.font.FontWeight
import androidx.compose.ui.text.style.TextDecoration
import androidx.compose.ui.unit.dp
import coil.compose.AsyncImage
import com.example.data.model.CustomFoodEntry
import com.example.data.model.RecipeEntry
import com.example.ui.common.FoodCategoryBadge
import java.util.Locale
@OptIn(ExperimentalMaterial3Api::class, ExperimentalLayoutApi::class)
@Composable
fun RecipeDetailSheet(
recipe: RecipeEntry,
customFoods: List<CustomFoodEntry>,
onDismiss: () -> Unit,
onEdit: () -> Unit,
onDelete: () -> Unit,
onLogAsMeal: (RecipeEntry, Int) -> Unit
) {
val sheetState = rememberModalBottomSheetState(skipPartiallyExpanded = true)
var displayServings by remember(recipe.id) { mutableIntStateOf(recipe.servings.coerceAtLeast(1)) }
var eatenServings by remember(recipe.id) { mutableIntStateOf(1) }
var showDeleteConfirm by remember { mutableStateOf(false) }
val checkedSteps = remember(recipe.id) { mutableStateListOf<Int>() }
val customCategoryLookup = remember(customFoods) {
customFoods.associate { it.name.lowercase(Locale.FRENCH).trim() to it.resolvedCategory() }
}
val scaledIngredients = remember(recipe.ingredientsSerialized, displayServings) {
recipe.scaledIngredients(displayServings.toDouble())
}
ModalBottomSheet(
onDismissRequest = onDismiss,
sheetState = sheetState,
containerColor = MaterialTheme.colorScheme.surface,
dragHandle = null
) {
Column(
modifier = Modifier
.fillMaxWidth()
.verticalScroll(rememberScrollState())
.padding(horizontal = 22.dp, vertical = 20.dp)
.testTag("recipe_detail_sheet")
) {
// Top bar: Tag + Edit/Delete/Close
Row(
modifier = Modifier.fillMaxWidth(),
horizontalArrangement = Arrangement.SpaceBetween,
verticalAlignment = Alignment.CenterVertically
) {
Surface(
shape = RoundedCornerShape(10.dp),
color = MaterialTheme.colorScheme.primaryContainer
) {
Text(
text = recipe.categoryEnum().displayName,
style = MaterialTheme.typography.labelMedium,
color = MaterialTheme.colorScheme.onPrimaryContainer,
fontWeight = FontWeight.SemiBold,
modifier = Modifier.padding(horizontal = 10.dp, vertical = 4.dp)
)
}
Row(verticalAlignment = Alignment.CenterVertically) {
IconButton(
onClick = onEdit,
modifier = Modifier.testTag("edit_recipe_button")
) {
Icon(
imageVector = Icons.Default.Edit,
contentDescription = "Modifier la recette",
tint = MaterialTheme.colorScheme.primary
)
}
IconButton(
onClick = { showDeleteConfirm = true },
modifier = Modifier.testTag("delete_recipe_button")
) {
Icon(
imageVector = Icons.Default.Delete,
contentDescription = "Supprimer la recette",
tint = MaterialTheme.colorScheme.error
)
}
IconButton(
onClick = onDismiss,
modifier = Modifier.testTag("close_recipe_detail_button")
) {
Icon(
imageVector = Icons.Default.Close,
contentDescription = "Fermer"
)
}
}
}
if (!recipe.photoUri.isNullOrBlank()) {
Spacer(modifier = Modifier.height(10.dp))
AsyncImage(
model = recipe.photoUri,
contentDescription = "Photo de ${recipe.title}",
modifier = Modifier
.fillMaxWidth()
.height(190.dp)
.clip(RoundedCornerShape(18.dp)),
contentScale = ContentScale.Crop
)
}
Spacer(modifier = Modifier.height(14.dp))
Text(
text = recipe.title,
style = MaterialTheme.typography.headlineSmall,
color = MaterialTheme.colorScheme.onSurface,
fontWeight = FontWeight.Bold
)
Spacer(modifier = Modifier.height(6.dp))
Row(verticalAlignment = Alignment.CenterVertically) {
Icon(
imageVector = Icons.Default.Schedule,
contentDescription = null,
tint = MaterialTheme.colorScheme.primary,
modifier = Modifier.size(16.dp)
)
Spacer(modifier = Modifier.width(6.dp))
Text(
text = "Préparation : ${recipe.formatPrepTimeLabel()}",
style = MaterialTheme.typography.bodySmall,
color = MaterialTheme.colorScheme.onSurfaceVariant
)
}
Spacer(modifier = Modifier.height(18.dp))
// Servings adjuster + Ingredients
Surface(
shape = RoundedCornerShape(16.dp),
color = MaterialTheme.colorScheme.surfaceVariant.copy(alpha = 0.45f),
modifier = Modifier.fillMaxWidth()
) {
Column(modifier = Modifier.padding(16.dp)) {
Row(
modifier = Modifier.fillMaxWidth(),
horizontalArrangement = Arrangement.SpaceBetween,
verticalAlignment = Alignment.CenterVertically
) {
Text(
text = "Ingrédients",
style = MaterialTheme.typography.titleSmall,
color = MaterialTheme.colorScheme.onSurface,
fontWeight = FontWeight.Bold
)
Row(verticalAlignment = Alignment.CenterVertically) {
Surface(
shape = CircleShape,
color = MaterialTheme.colorScheme.surface,
modifier = Modifier
.size(34.dp)
.clip(CircleShape)
.clickable(enabled = displayServings > 1) {
if (displayServings > 1) displayServings--
}
.testTag("recipe_servings_minus")
) {
Box(contentAlignment = Alignment.Center) {
Icon(
imageVector = Icons.Default.Remove,
contentDescription = "Réduire les portions",
modifier = Modifier.size(16.dp)
)
}
}
Text(
text = "$displayServings port.",
style = MaterialTheme.typography.labelLarge,
color = MaterialTheme.colorScheme.primary,
fontWeight = FontWeight.Bold,
modifier = Modifier.padding(horizontal = 12.dp)
)
Surface(
shape = CircleShape,
color = MaterialTheme.colorScheme.surface,
modifier = Modifier
.size(34.dp)
.clip(CircleShape)
.clickable(enabled = displayServings < 20) {
if (displayServings < 20) displayServings++
}
.testTag("recipe_servings_plus")
) {
Box(contentAlignment = Alignment.Center) {
Icon(
imageVector = Icons.Default.Add,
contentDescription = "Augmenter les portions",
modifier = Modifier.size(16.dp)
)
}
}
}
}
Spacer(modifier = Modifier.height(12.dp))
if (scaledIngredients.isEmpty()) {
Text(
text = "Aucun ingrédient renseigné.",
style = MaterialTheme.typography.bodySmall,
color = MaterialTheme.colorScheme.onSurfaceVariant
)
} else {
FlowRow(
horizontalArrangement = Arrangement.spacedBy(8.dp),
verticalArrangement = Arrangement.spacedBy(8.dp),
modifier = Modifier.fillMaxWidth()
) {
scaledIngredients.forEach { item ->
FoodCategoryBadge(
text = item.displayBadge(),
category = item.resolvedCategory(customCategoryLookup)
)
}
}
}
}
}
// Steps checklist
if (recipe.steps.isNotEmpty()) {
Spacer(modifier = Modifier.height(18.dp))
Text(
text = "Étapes de préparation",
style = MaterialTheme.typography.titleSmall,
color = MaterialTheme.colorScheme.onSurface,
fontWeight = FontWeight.Bold
)
Spacer(modifier = Modifier.height(8.dp))
recipe.steps.forEachIndexed { index, step ->
val isChecked = index in checkedSteps
Row(
modifier = Modifier
.fillMaxWidth()
.clip(RoundedCornerShape(12.dp))
.clickable {
if (isChecked) checkedSteps.remove(index) else checkedSteps.add(index)
}
.padding(vertical = 8.dp, horizontal = 4.dp),
verticalAlignment = Alignment.Top
) {
Icon(
imageVector = if (isChecked) Icons.Default.CheckCircle else Icons.Default.RadioButtonUnchecked,
contentDescription = if (isChecked) "Étape terminée" else "Marquer l'étape terminée",
tint = if (isChecked) MaterialTheme.colorScheme.primary else MaterialTheme.colorScheme.onSurfaceVariant,
modifier = Modifier
.padding(top = 2.dp)
.size(20.dp)
)
Spacer(modifier = Modifier.width(10.dp))
Column(modifier = Modifier.weight(1f)) {
Text(
text = "Étape ${index + 1}",
style = MaterialTheme.typography.labelSmall,
color = MaterialTheme.colorScheme.primary,
fontWeight = FontWeight.Bold
)
Text(
text = step,
style = MaterialTheme.typography.bodyMedium,
color = if (isChecked) {
MaterialTheme.colorScheme.onSurfaceVariant.copy(alpha = 0.6f)
} else {
MaterialTheme.colorScheme.onSurface
},
textDecoration = if (isChecked) TextDecoration.LineThrough else TextDecoration.None
)
}
}
}
}
if (recipe.notes.isNotBlank()) {
Spacer(modifier = Modifier.height(16.dp))
Surface(
shape = RoundedCornerShape(14.dp),
color = MaterialTheme.colorScheme.surfaceVariant.copy(alpha = 0.35f),
modifier = Modifier.fillMaxWidth()
) {
Column(modifier = Modifier.padding(14.dp)) {
Text(
text = "Astuces & Notes",
style = MaterialTheme.typography.labelMedium,
color = MaterialTheme.colorScheme.primary,
fontWeight = FontWeight.Bold
)
Spacer(modifier = Modifier.height(4.dp))
Text(
text = recipe.notes,
style = MaterialTheme.typography.bodyMedium,
fontStyle = FontStyle.Italic,
color = MaterialTheme.colorScheme.onSurface
)
}
}
}
Spacer(modifier = Modifier.height(20.dp))
HorizontalDivider(color = MaterialTheme.colorScheme.outlineVariant.copy(alpha = 0.4f))
Spacer(modifier = Modifier.height(16.dp))
// Log recipe directly into Journal
Surface(
shape = RoundedCornerShape(16.dp),
color = MaterialTheme.colorScheme.primaryContainer.copy(alpha = 0.4f),
border = BorderStroke(1.dp, MaterialTheme.colorScheme.primary.copy(alpha = 0.3f)),
modifier = Modifier.fillMaxWidth()
) {
Column(modifier = Modifier.padding(14.dp)) {
Row(
modifier = Modifier.fillMaxWidth(),
horizontalArrangement = Arrangement.SpaceBetween,
verticalAlignment = Alignment.CenterVertically
) {
Text(
text = "Portions mangées :",
style = MaterialTheme.typography.labelLarge,
color = MaterialTheme.colorScheme.onSurface,
fontWeight = FontWeight.SemiBold
)
Row(verticalAlignment = Alignment.CenterVertically) {
IconButton(
onClick = { if (eatenServings > 1) eatenServings-- },
enabled = eatenServings > 1
) {
Icon(
imageVector = Icons.Default.Remove,
contentDescription = "Moins de portions mangées"
)
}
Text(
text = "$eatenServings",
style = MaterialTheme.typography.titleMedium,
color = MaterialTheme.colorScheme.primary,
fontWeight = FontWeight.Bold,
modifier = Modifier.padding(horizontal = 6.dp)
)
IconButton(
onClick = { if (eatenServings < 10) eatenServings++ },
enabled = eatenServings < 10
) {
Icon(
imageVector = Icons.Default.Add,
contentDescription = "Plus de portions mangées"
)
}
}
}
Spacer(modifier = Modifier.height(8.dp))
Button(
onClick = { onLogAsMeal(recipe, eatenServings) },
modifier = Modifier
.fillMaxWidth()
.height(48.dp)
.testTag("log_recipe_as_meal_button"),
shape = RoundedCornerShape(14.dp),
colors = ButtonDefaults.buttonColors(
containerColor = MaterialTheme.colorScheme.primary,
contentColor = MaterialTheme.colorScheme.onPrimary
)
) {
Icon(
imageVector = Icons.Default.Restaurant,
contentDescription = null,
modifier = Modifier.size(18.dp)
)
Spacer(modifier = Modifier.width(8.dp))
Text(
text = "Noter dans mon journal ($eatenServings part${if (eatenServings > 1) "s" else ""})",
style = MaterialTheme.typography.titleSmall
)
}
}
}
Spacer(modifier = Modifier.height(16.dp))
}
}
if (showDeleteConfirm) {
AlertDialog(
onDismissRequest = { showDeleteConfirm = false },
title = { Text("Supprimer cette recette ?") },
text = { Text("« ${recipe.title} » sera retirée de votre recueil local.") },
confirmButton = {
TextButton(
onClick = {
showDeleteConfirm = false
onDelete()
}
) {
Text("Supprimer", color = MaterialTheme.colorScheme.error)
}
},
dismissButton = {
TextButton(onClick = { showDeleteConfirm = false }) {
Text("Annuler")
}
}
)
}
}
@@ -0,0 +1,627 @@
package com.example.ui.recipes
import android.net.Uri
import androidx.activity.compose.rememberLauncherForActivityResult
import androidx.activity.result.PickVisualMediaRequest
import androidx.activity.result.contract.ActivityResultContracts
import androidx.compose.foundation.BorderStroke
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.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.AddPhotoAlternate
import androidx.compose.material.icons.filled.Close
import androidx.compose.material.icons.filled.Delete
import androidx.compose.material3.Button
import androidx.compose.material3.ButtonDefaults
import androidx.compose.material3.CircularProgressIndicator
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.OutlinedTextField
import androidx.compose.material3.Surface
import androidx.compose.material3.Text
import androidx.compose.material3.TextButton
import androidx.compose.material3.rememberModalBottomSheetState
import androidx.compose.runtime.Composable
import androidx.compose.runtime.getValue
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.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.unit.dp
import coil.compose.AsyncImage
import com.example.data.model.CustomFoodEntry
import com.example.data.model.DefaultFoodCatalog
import com.example.data.model.FoodCategory
import com.example.data.model.FoodUnit
import com.example.data.model.MealFoodItem
import com.example.data.model.RecipeCategoryTag
import com.example.data.model.RecipeEntry
import com.example.ui.meal.components.FoodItemBuilderSection
import com.example.util.ImageUtils
import kotlinx.coroutines.launch
import java.util.Locale
@OptIn(ExperimentalMaterial3Api::class)
@Composable
fun RecipeEditorSheet(
initialRecipe: RecipeEntry? = null,
customFoods: List<CustomFoodEntry> = emptyList(),
onAddCustomFood: (String, FoodUnit, FoodCategory?) -> Unit = { _, _, _ -> },
onDismiss: () -> Unit,
onSaveRecipe: (RecipeEntry) -> Unit
) {
val sheetState = rememberModalBottomSheetState(skipPartiallyExpanded = true)
val context = LocalContext.current
val coroutineScope = rememberCoroutineScope()
var title by rememberSaveable { mutableStateOf(initialRecipe?.title ?: "") }
var selectedTag by rememberSaveable {
mutableStateOf(initialRecipe?.categoryEnum() ?: RecipeCategoryTag.MAIN)
}
var prepTimeInput by rememberSaveable {
mutableStateOf(initialRecipe?.prepTimeMinutes?.takeIf { it > 0 }?.toString() ?: "")
}
var servingsInput by rememberSaveable {
mutableStateOf((initialRecipe?.servings ?: 2).toString())
}
var notes by rememberSaveable { mutableStateOf(initialRecipe?.notes ?: "") }
var photoUri by rememberSaveable { mutableStateOf(initialRecipe?.photoUri) }
var newlySavedPhotoUri by rememberSaveable { mutableStateOf<String?>(null) }
var isProcessingPhoto by remember { mutableStateOf(false) }
val ingredientsList = remember(initialRecipe?.id) {
mutableStateListOf<MealFoodItem>().apply {
if (initialRecipe != null) {
addAll(initialRecipe.parsedIngredients())
}
}
}
val stepsList = remember(initialRecipe?.id) {
mutableStateListOf<String>().apply {
if (initialRecipe != null) {
addAll(initialRecipe.steps)
}
}
}
// Ingredient builder state
val customCategoryLookup = remember(customFoods) {
customFoods.associate { it.name.lowercase(Locale.FRENCH).trim() to it.resolvedCategory() }
}
var foodNameInput by rememberSaveable { mutableStateOf("") }
var foodWeightInput by rememberSaveable { mutableStateOf("") }
var selectedFoodUnit by rememberSaveable { mutableStateOf(FoodUnit.G) }
var selectedFoodCategory by rememberSaveable { mutableStateOf(FoodCategory.OTHER) }
var hasUserOverriddenCategory by rememberSaveable { mutableStateOf(false) }
// Step builder state
var stepInput by rememberSaveable { mutableStateOf("") }
val mergedCatalog = remember(customFoods) {
val customMapped = customFoods.map {
DefaultFoodCatalog.CatalogFood(
name = it.name,
defaultUnit = FoodUnit.fromCode(it.defaultUnit),
category = it.resolvedCategory()
)
}
val customLowerSet = customMapped.map { it.name.lowercase(Locale.FRENCH) }.toSet()
val builtInFiltered = DefaultFoodCatalog.builtInFoods.filter {
it.name.lowercase(Locale.FRENCH) !in customLowerSet
}
customMapped + builtInFiltered
}
val matchingSuggestions = remember(foodNameInput, mergedCatalog, ingredientsList.size) {
val addedNames = ingredientsList.map { it.name.lowercase(Locale.FRENCH) }.toSet()
val query = foodNameInput.trim().lowercase(Locale.FRENCH)
if (query.isEmpty()) {
mergedCatalog.filter { it.name.lowercase(Locale.FRENCH) !in addedNames }.take(10)
} else {
mergedCatalog.filter {
it.name.lowercase(Locale.FRENCH).contains(query) &&
it.name.lowercase(Locale.FRENCH) !in addedNames
}.take(8)
}
}
val isNewCustomFood = remember(foodNameInput, mergedCatalog) {
val clean = foodNameInput.trim()
clean.length >= 2 && mergedCatalog.none { it.name.equals(clean, ignoreCase = true) }
}
val addCurrentIngredient = {
val cleanName = foodNameInput.trim()
if (cleanName.isNotEmpty() && ingredientsList.size < 40) {
val parsedWeight = foodWeightInput.trim().replace(",", ".").toDoubleOrNull()?.takeIf { it > 0.0 }
val resolvedCat = if (hasUserOverriddenCategory) {
selectedFoodCategory
} else {
FoodCategory.inferFromName(cleanName, customCategoryLookup)
}
val item = MealFoodItem(
name = cleanName,
weight = parsedWeight,
unit = selectedFoodUnit,
category = resolvedCat
)
val existingIdx = ingredientsList.indexOfFirst { it.name.equals(cleanName, ignoreCase = true) }
if (existingIdx >= 0) {
ingredientsList[existingIdx] = item
} else {
ingredientsList.add(item)
}
if (isNewCustomFood || hasUserOverriddenCategory) {
onAddCustomFood(cleanName, selectedFoodUnit, resolvedCat)
}
foodNameInput = ""
foodWeightInput = ""
selectedFoodUnit = FoodUnit.G
selectedFoodCategory = FoodCategory.OTHER
hasUserOverriddenCategory = false
}
}
val photoPickerLauncher = rememberLauncherForActivityResult(
contract = ActivityResultContracts.PickVisualMedia()
) { uri: Uri? ->
if (uri != null) {
isProcessingPhoto = true
coroutineScope.launch {
val savedUri = ImageUtils.saveImageToPrivateStorage(context, uri)
if (savedUri != null) {
// Delete previous uncommitted new photo if replacing before save
newlySavedPhotoUri?.let { oldUnsaved ->
ImageUtils.deletePhotoFile(context, oldUnsaved)
}
photoUri = savedUri
newlySavedPhotoUri = savedUri
}
isProcessingPhoto = false
}
}
}
val handleDismiss = {
newlySavedPhotoUri?.let { ImageUtils.deletePhotoFile(context, it) }
onDismiss()
}
ModalBottomSheet(
onDismissRequest = handleDismiss,
sheetState = sheetState,
containerColor = MaterialTheme.colorScheme.surface,
dragHandle = null
) {
Column(
modifier = Modifier
.fillMaxWidth()
.verticalScroll(rememberScrollState())
.padding(horizontal = 22.dp, vertical = 20.dp)
.testTag("recipe_editor_sheet")
) {
// Header
Row(
modifier = Modifier.fillMaxWidth(),
horizontalArrangement = Arrangement.SpaceBetween,
verticalAlignment = Alignment.CenterVertically
) {
Column(modifier = Modifier.weight(1f)) {
Text(
text = if (initialRecipe == null) "Nouvelle recette" else "Modifier la recette",
style = MaterialTheme.typography.headlineSmall,
color = MaterialTheme.colorScheme.onSurface,
fontWeight = FontWeight.Bold
)
Text(
text = "Photo, ingrédients colorés et étapes simples",
style = MaterialTheme.typography.bodySmall,
color = MaterialTheme.colorScheme.onSurfaceVariant
)
}
IconButton(onClick = handleDismiss) {
Icon(
imageVector = Icons.Default.Close,
contentDescription = "Fermer"
)
}
}
Spacer(modifier = Modifier.height(14.dp))
// Cover Photo Picker (zero-permission PickVisualMedia)
Surface(
shape = RoundedCornerShape(16.dp),
color = MaterialTheme.colorScheme.surfaceVariant.copy(alpha = 0.45f),
border = BorderStroke(1.dp, MaterialTheme.colorScheme.outlineVariant.copy(alpha = 0.4f)),
modifier = Modifier
.fillMaxWidth()
.height(140.dp)
.clip(RoundedCornerShape(16.dp))
.clickable {
photoPickerLauncher.launch(
PickVisualMediaRequest(ActivityResultContracts.PickVisualMedia.ImageOnly)
)
}
.testTag("recipe_pick_photo_button")
) {
Box(contentAlignment = Alignment.Center) {
if (isProcessingPhoto) {
CircularProgressIndicator(modifier = Modifier.size(28.dp))
} else if (!photoUri.isNullOrBlank()) {
AsyncImage(
model = photoUri,
contentDescription = "Photo de la recette",
modifier = Modifier.fillMaxSize(),
contentScale = ContentScale.Crop
)
Surface(
shape = CircleShape,
color = MaterialTheme.colorScheme.surface.copy(alpha = 0.85f),
modifier = Modifier
.align(Alignment.TopEnd)
.padding(8.dp)
.size(34.dp)
.clip(CircleShape)
.clickable { photoUri = null }
) {
Box(contentAlignment = Alignment.Center) {
Icon(
imageVector = Icons.Default.Delete,
contentDescription = "Retirer la photo",
tint = MaterialTheme.colorScheme.error,
modifier = Modifier.size(18.dp)
)
}
}
} else {
Column(horizontalAlignment = Alignment.CenterHorizontally) {
Icon(
imageVector = Icons.Default.AddPhotoAlternate,
contentDescription = null,
tint = MaterialTheme.colorScheme.primary,
modifier = Modifier.size(30.dp)
)
Spacer(modifier = Modifier.height(6.dp))
Text(
text = "Ajouter une photo de couverture (optionnel)",
style = MaterialTheme.typography.labelMedium,
color = MaterialTheme.colorScheme.onSurfaceVariant
)
}
}
}
}
Spacer(modifier = Modifier.height(14.dp))
// Title
OutlinedTextField(
value = title,
onValueChange = { if (it.length <= 120) title = it },
label = { Text("Nom de la recette *") },
placeholder = { Text("Ex: Dahl de lentilles corail, Bowl saumon avocat...") },
singleLine = true,
shape = RoundedCornerShape(12.dp),
modifier = Modifier
.fillMaxWidth()
.testTag("recipe_title_input")
)
Spacer(modifier = Modifier.height(12.dp))
// Category Tag Chips
Text(
text = "Type de recette",
style = MaterialTheme.typography.labelLarge,
color = MaterialTheme.colorScheme.onSurface
)
Spacer(modifier = Modifier.height(6.dp))
LazyRow(horizontalArrangement = Arrangement.spacedBy(8.dp)) {
items(RecipeCategoryTag.entries, key = { it.name }) { tag ->
FilterChip(
selected = selectedTag == tag,
onClick = { selectedTag = tag },
label = { Text(tag.displayName) },
colors = FilterChipDefaults.filterChipColors(
selectedContainerColor = MaterialTheme.colorScheme.primaryContainer,
selectedLabelColor = MaterialTheme.colorScheme.onPrimaryContainer
)
)
}
}
Spacer(modifier = Modifier.height(12.dp))
// Prep Time & Servings Row
Row(
modifier = Modifier.fillMaxWidth(),
horizontalArrangement = Arrangement.spacedBy(12.dp)
) {
OutlinedTextField(
value = prepTimeInput,
onValueChange = { input ->
if (input.length <= 4 && input.all { it.isDigit() }) {
prepTimeInput = input
}
},
label = { Text("Temps (min)") },
placeholder = { Text("Ex: 25") },
singleLine = true,
keyboardOptions = KeyboardOptions(keyboardType = KeyboardType.Number),
shape = RoundedCornerShape(12.dp),
modifier = Modifier.weight(1f)
)
OutlinedTextField(
value = servingsInput,
onValueChange = { input ->
if (input.length <= 2 && input.all { it.isDigit() }) {
servingsInput = input
}
},
label = { Text("Portions") },
placeholder = { Text("Ex: 2") },
singleLine = true,
keyboardOptions = KeyboardOptions(keyboardType = KeyboardType.Number),
shape = RoundedCornerShape(12.dp),
modifier = Modifier.weight(1f)
)
}
Spacer(modifier = Modifier.height(18.dp))
// Color-Coded Ingredients Builder
FoodItemBuilderSection(
foodItemsList = ingredientsList,
matchingSuggestions = matchingSuggestions,
foodNameInput = foodNameInput,
onFoodNameChange = { input ->
foodNameInput = input
if (!hasUserOverriddenCategory) {
selectedFoodCategory = if (input.isBlank()) {
FoodCategory.OTHER
} else {
FoodCategory.inferFromName(input, customCategoryLookup)
}
}
if (input.isBlank()) {
hasUserOverriddenCategory = false
selectedFoodCategory = FoodCategory.OTHER
}
},
foodWeightInput = foodWeightInput,
onFoodWeightChange = { foodWeightInput = it },
selectedFoodUnit = selectedFoodUnit,
onFoodUnitSelected = { selectedFoodUnit = it },
selectedFoodCategory = selectedFoodCategory,
onFoodCategorySelected = { cat ->
selectedFoodCategory = cat
hasUserOverriddenCategory = true
},
isNewCustomFood = isNewCustomFood,
onAddFoodItem = { addCurrentIngredient() },
onItemClickForEdit = { item ->
foodNameInput = item.name
foodWeightInput = item.weight?.let {
if (it % 1.0 == 0.0) it.toInt().toString() else it.toString()
} ?: ""
selectedFoodUnit = item.unit
selectedFoodCategory = item.resolvedCategory(customCategoryLookup)
hasUserOverriddenCategory = true
ingredientsList.remove(item)
},
onRemoveFoodItem = { item -> ingredientsList.remove(item) },
sectionTitle = "Ingrédients colorés",
addButtonLabelPrefix = "Ajouter l'ingrédient",
addedListCaption = "Ingrédients de la recette (touchez pour modifier poids ou couleur) :"
)
Spacer(modifier = Modifier.height(18.dp))
// Preparation Steps Builder
Surface(
shape = RoundedCornerShape(18.dp),
color = MaterialTheme.colorScheme.surfaceVariant.copy(alpha = 0.45f),
modifier = Modifier.fillMaxWidth()
) {
Column(modifier = Modifier.padding(16.dp)) {
Text(
text = "Étapes de préparation (${stepsList.size})",
style = MaterialTheme.typography.labelLarge,
color = MaterialTheme.colorScheme.onSurface
)
Spacer(modifier = Modifier.height(8.dp))
OutlinedTextField(
value = stepInput,
onValueChange = { if (it.length <= 300) stepInput = it },
placeholder = { Text("Ex: Faire revenir les oignons et les carottes 5 min...") },
maxLines = 3,
shape = RoundedCornerShape(12.dp),
modifier = Modifier
.fillMaxWidth()
.testTag("recipe_step_input")
)
Spacer(modifier = Modifier.height(8.dp))
Button(
onClick = {
val cleanStep = stepInput.trim()
if (cleanStep.isNotEmpty() && stepsList.size < 30) {
stepsList.add(cleanStep)
stepInput = ""
}
},
enabled = stepInput.trim().isNotEmpty(),
modifier = Modifier
.fillMaxWidth()
.testTag("add_recipe_step_button"),
shape = RoundedCornerShape(12.dp),
colors = ButtonDefaults.buttonColors(
containerColor = MaterialTheme.colorScheme.secondaryContainer,
contentColor = MaterialTheme.colorScheme.onSecondaryContainer
)
) {
Icon(
imageVector = Icons.Default.Add,
contentDescription = null,
modifier = Modifier.size(18.dp)
)
Spacer(modifier = Modifier.width(6.dp))
Text("Ajouter l'étape")
}
if (stepsList.isNotEmpty()) {
Spacer(modifier = Modifier.height(12.dp))
stepsList.forEachIndexed { idx, step ->
Surface(
shape = RoundedCornerShape(12.dp),
color = MaterialTheme.colorScheme.surface,
modifier = Modifier
.fillMaxWidth()
.padding(vertical = 4.dp)
) {
Row(
modifier = Modifier
.fillMaxWidth()
.padding(horizontal = 12.dp, vertical = 8.dp),
verticalAlignment = Alignment.CenterVertically
) {
Text(
text = "${idx + 1}.",
style = MaterialTheme.typography.labelLarge,
color = MaterialTheme.colorScheme.primary,
fontWeight = FontWeight.Bold
)
Spacer(modifier = Modifier.width(8.dp))
Text(
text = step,
style = MaterialTheme.typography.bodySmall,
color = MaterialTheme.colorScheme.onSurface,
modifier = Modifier.weight(1f)
)
IconButton(
onClick = { stepsList.removeAt(idx) },
modifier = Modifier.size(32.dp)
) {
Icon(
imageVector = Icons.Default.Close,
contentDescription = "Retirer l'étape ${idx + 1}",
modifier = Modifier.size(16.dp)
)
}
}
}
}
}
}
}
Spacer(modifier = Modifier.height(16.dp))
// Notes
OutlinedTextField(
value = notes,
onValueChange = { if (it.length <= 400) notes = it },
label = { Text("Astuces / Notes (optionnel)") },
placeholder = { Text("Ex: Se conserve 3 jours au frais, délicieux avec du citron...") },
maxLines = 3,
shape = RoundedCornerShape(12.dp),
modifier = Modifier.fillMaxWidth()
)
Spacer(modifier = Modifier.height(22.dp))
// Save / Cancel Actions
Row(
modifier = Modifier.fillMaxWidth(),
horizontalArrangement = Arrangement.End,
verticalAlignment = Alignment.CenterVertically
) {
TextButton(onClick = handleDismiss) {
Text("Annuler")
}
Spacer(modifier = Modifier.width(10.dp))
Button(
onClick = {
if (foodNameInput.trim().isNotEmpty()) {
addCurrentIngredient()
}
if (stepInput.trim().isNotEmpty() && stepsList.size < 30) {
stepsList.add(stepInput.trim())
stepInput = ""
}
val oldPhoto = initialRecipe?.photoUri
if (!oldPhoto.isNullOrBlank() && oldPhoto != photoUri) {
ImageUtils.deletePhotoFile(context, oldPhoto)
}
val recipe = RecipeEntry(
id = initialRecipe?.id ?: "",
title = title.trim(),
categoryTag = selectedTag.name,
prepTimeMinutes = prepTimeInput.toIntOrNull()?.coerceAtLeast(0) ?: 0,
servings = (servingsInput.toIntOrNull() ?: 2).coerceIn(1, 30),
ingredientsSerialized = ingredientsList.map { it.serialize() },
steps = stepsList.toList(),
notes = notes.trim(),
photoUri = photoUri,
updatedAt = System.currentTimeMillis()
)
onSaveRecipe(recipe)
},
enabled = title.trim().isNotEmpty(),
modifier = Modifier
.height(48.dp)
.testTag("save_recipe_button"),
shape = RoundedCornerShape(14.dp),
colors = ButtonDefaults.buttonColors(
containerColor = MaterialTheme.colorScheme.primary,
contentColor = MaterialTheme.colorScheme.onPrimary
)
) {
Text(
text = if (initialRecipe == null) "Enregistrer la recette" else "Mettre à jour",
style = MaterialTheme.typography.titleSmall
)
}
}
Spacer(modifier = Modifier.height(16.dp))
}
}
}
@@ -0,0 +1,483 @@
package com.example.ui.recipes
import androidx.compose.foundation.BorderStroke
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.ExperimentalLayoutApi
import androidx.compose.foundation.layout.FlowRow
import androidx.compose.foundation.layout.PaddingValues
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.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.automirrored.filled.MenuBook
import androidx.compose.material.icons.filled.Add
import androidx.compose.material.icons.filled.Close
import androidx.compose.material.icons.filled.People
import androidx.compose.material.icons.filled.Schedule
import androidx.compose.material.icons.filled.Search
import androidx.compose.material3.Card
import androidx.compose.material3.CardDefaults
import androidx.compose.material3.FilterChip
import androidx.compose.material3.FilterChipDefaults
import androidx.compose.material3.FloatingActionButton
import androidx.compose.material3.Icon
import androidx.compose.material3.IconButton
import androidx.compose.material3.MaterialTheme
import androidx.compose.material3.OutlinedTextField
import androidx.compose.material3.Surface
import androidx.compose.material3.Text
import androidx.compose.material3.TextButton
import androidx.compose.runtime.Composable
import androidx.compose.runtime.getValue
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.remember
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.layout.ContentScale
import androidx.compose.ui.platform.testTag
import androidx.compose.ui.text.font.FontWeight
import androidx.compose.ui.text.style.TextAlign
import androidx.compose.ui.text.style.TextOverflow
import androidx.compose.ui.unit.dp
import coil.compose.AsyncImage
import com.example.data.model.CustomFoodEntry
import com.example.data.model.FoodCategory
import com.example.data.model.RecipeCategoryTag
import com.example.data.model.RecipeEntry
import com.example.ui.common.FoodCategoryColorDot
import com.example.ui.common.badgeBorderColor
import com.example.ui.common.badgeContainerColor
import com.example.ui.common.badgeTextColor
import com.example.ui.common.isSatieaDarkTheme
import java.util.Locale
@Composable
fun RecipesScreen(
recipes: List<RecipeEntry>,
customFoods: List<CustomFoodEntry>,
onAddRecipeClick: () -> Unit,
onRecipeClick: (RecipeEntry) -> Unit
) {
var searchQuery by rememberSaveable { mutableStateOf("") }
var selectedTag by rememberSaveable { mutableStateOf<String?>(null) }
val customCategoryLookup = remember(customFoods) {
customFoods.associate { it.name.lowercase(Locale.FRENCH).trim() to it.resolvedCategory() }
}
val filteredRecipes = remember(recipes, searchQuery, selectedTag) {
val query = searchQuery.trim().lowercase(Locale.FRENCH)
recipes.filter { recipe ->
val matchesTag = selectedTag == null || recipe.categoryTag.equals(selectedTag, ignoreCase = true)
val matchesQuery = query.isBlank() ||
recipe.title.lowercase(Locale.FRENCH).contains(query) ||
recipe.parsedIngredients().any { it.name.lowercase(Locale.FRENCH).contains(query) }
matchesTag && matchesQuery
}
}
Box(
modifier = Modifier
.fillMaxSize()
.background(MaterialTheme.colorScheme.background)
.testTag("recipes_screen")
) {
LazyColumn(
modifier = Modifier
.fillMaxSize()
.testTag("recipes_list"),
contentPadding = PaddingValues(
start = 20.dp,
end = 20.dp,
top = 16.dp,
bottom = 96.dp
),
verticalArrangement = Arrangement.spacedBy(14.dp)
) {
// Header
item {
Column {
Text(
text = "Mon Recueil de Recettes",
style = MaterialTheme.typography.headlineMedium,
color = MaterialTheme.colorScheme.onBackground,
fontWeight = FontWeight.Bold
)
Text(
text = if (recipes.isEmpty()) {
"Conservez vos recettes préférées et notez-les en 1 clic"
} else {
"${recipes.size} recette${if (recipes.size > 1) "s" else ""} • ingrédients colorés & portions ajustables"
},
style = MaterialTheme.typography.bodyMedium,
color = MaterialTheme.colorScheme.onBackground.copy(alpha = 0.7f)
)
}
}
// Search bar & Category filter chips
if (recipes.isNotEmpty()) {
item {
OutlinedTextField(
value = searchQuery,
onValueChange = { if (it.length <= 60) searchQuery = it },
modifier = Modifier
.fillMaxWidth()
.testTag("recipe_search_input"),
placeholder = { Text("Rechercher une recette ou un ingrédient...") },
leadingIcon = {
Icon(
imageVector = Icons.Default.Search,
contentDescription = null,
tint = MaterialTheme.colorScheme.primary
)
},
trailingIcon = {
if (searchQuery.isNotEmpty()) {
IconButton(onClick = { searchQuery = "" }) {
Icon(
imageVector = Icons.Default.Close,
contentDescription = "Effacer la recherche"
)
}
}
},
singleLine = true,
shape = RoundedCornerShape(14.dp)
)
}
item {
LazyRow(
horizontalArrangement = Arrangement.spacedBy(8.dp),
modifier = Modifier.fillMaxWidth()
) {
item {
FilterChip(
selected = selectedTag == null,
onClick = { selectedTag = null },
label = { Text("Toutes") },
colors = FilterChipDefaults.filterChipColors(
selectedContainerColor = MaterialTheme.colorScheme.primaryContainer,
selectedLabelColor = MaterialTheme.colorScheme.onPrimaryContainer
)
)
}
items(RecipeCategoryTag.entries, key = { it.name }) { tag ->
FilterChip(
selected = selectedTag == tag.name,
onClick = {
selectedTag = if (selectedTag == tag.name) null else tag.name
},
label = { Text(tag.displayName) },
colors = FilterChipDefaults.filterChipColors(
selectedContainerColor = MaterialTheme.colorScheme.primaryContainer,
selectedLabelColor = MaterialTheme.colorScheme.onPrimaryContainer
)
)
}
}
}
}
// Content
if (recipes.isEmpty()) {
item {
EmptyRecipesView(onAddRecipeClick = onAddRecipeClick)
}
} else if (filteredRecipes.isEmpty()) {
item {
Surface(
shape = RoundedCornerShape(18.dp),
color = MaterialTheme.colorScheme.surface,
modifier = Modifier.fillMaxWidth()
) {
Column(
modifier = Modifier
.fillMaxWidth()
.padding(24.dp),
horizontalAlignment = Alignment.CenterHorizontally
) {
Text(
text = "Aucune recette ne correspond à ce filtre",
style = MaterialTheme.typography.titleSmall,
color = MaterialTheme.colorScheme.onSurface,
fontWeight = FontWeight.SemiBold
)
Spacer(modifier = Modifier.height(8.dp))
TextButton(
onClick = {
searchQuery = ""
selectedTag = null
}
) {
Text("Réinitialiser les filtres")
}
}
}
}
} else {
items(filteredRecipes, key = { it.id }) { recipe ->
RecipeCardItem(
recipe = recipe,
customCategoryLookup = customCategoryLookup,
onClick = { onRecipeClick(recipe) }
)
}
}
}
FloatingActionButton(
onClick = onAddRecipeClick,
modifier = Modifier
.align(Alignment.BottomEnd)
.padding(24.dp)
.testTag("add_recipe_fab"),
containerColor = MaterialTheme.colorScheme.primary,
contentColor = MaterialTheme.colorScheme.onPrimary,
shape = CircleShape
) {
Icon(
imageVector = Icons.Default.Add,
contentDescription = "Créer une recette",
modifier = Modifier.size(28.dp)
)
}
}
}
@OptIn(ExperimentalLayoutApi::class)
@Composable
private fun RecipeCardItem(
recipe: RecipeEntry,
customCategoryLookup: Map<String, FoodCategory>,
onClick: () -> Unit
) {
val isDark = isSatieaDarkTheme()
val ingredients = remember(recipe.ingredientsSerialized) { recipe.parsedIngredients() }
val dominantCategories = remember(recipe.ingredientsSerialized, customCategoryLookup) {
recipe.dominantCategories(customCategoryLookup).take(4)
}
Card(
modifier = Modifier
.fillMaxWidth()
.clickable(onClick = onClick)
.testTag("recipe_card_${recipe.id}"),
shape = RoundedCornerShape(20.dp),
colors = CardDefaults.cardColors(
containerColor = MaterialTheme.colorScheme.surface
),
border = BorderStroke(1.dp, MaterialTheme.colorScheme.outlineVariant.copy(alpha = 0.3f))
) {
Column(modifier = Modifier.fillMaxWidth()) {
if (!recipe.photoUri.isNullOrBlank()) {
Box(
modifier = Modifier
.fillMaxWidth()
.height(145.dp)
) {
AsyncImage(
model = recipe.photoUri,
contentDescription = "Photo de ${recipe.title}",
modifier = Modifier.fillMaxSize(),
contentScale = ContentScale.Crop
)
Surface(
shape = RoundedCornerShape(10.dp),
color = MaterialTheme.colorScheme.surface.copy(alpha = 0.9f),
modifier = Modifier
.align(Alignment.TopStart)
.padding(12.dp)
) {
Text(
text = recipe.categoryEnum().displayName,
style = MaterialTheme.typography.labelSmall,
color = MaterialTheme.colorScheme.primary,
fontWeight = FontWeight.Bold,
modifier = Modifier.padding(horizontal = 10.dp, vertical = 4.dp)
)
}
}
}
Column(
modifier = Modifier
.fillMaxWidth()
.padding(18.dp)
) {
if (recipe.photoUri.isNullOrBlank()) {
Surface(
shape = RoundedCornerShape(10.dp),
color = MaterialTheme.colorScheme.primaryContainer
) {
Text(
text = recipe.categoryEnum().displayName,
style = MaterialTheme.typography.labelSmall,
color = MaterialTheme.colorScheme.onPrimaryContainer,
fontWeight = FontWeight.SemiBold,
modifier = Modifier.padding(horizontal = 10.dp, vertical = 4.dp)
)
}
Spacer(modifier = Modifier.height(8.dp))
}
Text(
text = recipe.title,
style = MaterialTheme.typography.titleMedium,
color = MaterialTheme.colorScheme.onSurface,
fontWeight = FontWeight.Bold,
maxLines = 2,
overflow = TextOverflow.Ellipsis
)
Spacer(modifier = Modifier.height(8.dp))
// Metadata chips (prep time, servings, ingredient count)
Row(
horizontalArrangement = Arrangement.spacedBy(14.dp),
verticalAlignment = Alignment.CenterVertically
) {
Row(verticalAlignment = Alignment.CenterVertically) {
Icon(
imageVector = Icons.Default.Schedule,
contentDescription = null,
tint = MaterialTheme.colorScheme.onSurfaceVariant,
modifier = Modifier.size(15.dp)
)
Spacer(modifier = Modifier.width(4.dp))
Text(
text = recipe.formatPrepTimeLabel(),
style = MaterialTheme.typography.bodySmall,
color = MaterialTheme.colorScheme.onSurfaceVariant
)
}
Row(verticalAlignment = Alignment.CenterVertically) {
Icon(
imageVector = Icons.Default.People,
contentDescription = null,
tint = MaterialTheme.colorScheme.onSurfaceVariant,
modifier = Modifier.size(15.dp)
)
Spacer(modifier = Modifier.width(4.dp))
Text(
text = "${recipe.servings} portion${if (recipe.servings > 1) "s" else ""}",
style = MaterialTheme.typography.bodySmall,
color = MaterialTheme.colorScheme.onSurfaceVariant
)
}
Text(
text = "${ingredients.size} ingrédient${if (ingredients.size > 1) "s" else ""}",
style = MaterialTheme.typography.bodySmall,
color = MaterialTheme.colorScheme.onSurfaceVariant
)
}
if (dominantCategories.isNotEmpty()) {
Spacer(modifier = Modifier.height(12.dp))
FlowRow(
horizontalArrangement = Arrangement.spacedBy(6.dp),
verticalArrangement = Arrangement.spacedBy(6.dp)
) {
dominantCategories.forEach { cat ->
Surface(
shape = RoundedCornerShape(9.dp),
color = cat.badgeContainerColor(isDark),
border = BorderStroke(1.dp, cat.badgeBorderColor(isDark))
) {
Row(
modifier = Modifier.padding(horizontal = 8.dp, vertical = 4.dp),
verticalAlignment = Alignment.CenterVertically
) {
FoodCategoryColorDot(category = cat, size = 7.dp)
Spacer(modifier = Modifier.width(5.dp))
Text(
text = cat.shortLabel,
style = MaterialTheme.typography.labelSmall,
color = cat.badgeTextColor(isDark),
fontWeight = FontWeight.Medium
)
}
}
}
}
}
}
}
}
}
@Composable
private fun EmptyRecipesView(onAddRecipeClick: () -> Unit) {
Column(
modifier = Modifier
.fillMaxWidth()
.padding(vertical = 44.dp, horizontal = 20.dp),
horizontalAlignment = Alignment.CenterHorizontally
) {
Surface(
modifier = Modifier.size(82.dp),
shape = CircleShape,
color = MaterialTheme.colorScheme.surfaceVariant.copy(alpha = 0.5f)
) {
Box(contentAlignment = Alignment.Center) {
Icon(
imageVector = Icons.AutoMirrored.Filled.MenuBook,
contentDescription = null,
tint = MaterialTheme.colorScheme.primary,
modifier = Modifier.size(38.dp)
)
}
}
Spacer(modifier = Modifier.height(20.dp))
Text(
text = "Votre recueil est prêt",
style = MaterialTheme.typography.titleMedium,
color = MaterialTheme.colorScheme.onBackground,
fontWeight = FontWeight.Bold
)
Spacer(modifier = Modifier.height(8.dp))
Text(
text = "Ajoutez vos plats maison avec photo, ingrédients colorés et étapes, puis notez une portion dans votre journal en un clic.",
style = MaterialTheme.typography.bodyMedium,
color = MaterialTheme.colorScheme.onBackground.copy(alpha = 0.7f),
textAlign = TextAlign.Center
)
Spacer(modifier = Modifier.height(20.dp))
TextButton(
onClick = onAddRecipeClick,
modifier = Modifier.testTag("empty_recipes_add_button")
) {
Text(
text = "+ Créer ma première recette",
style = MaterialTheme.typography.titleSmall,
color = MaterialTheme.colorScheme.primary
)
}
}
}
@@ -24,11 +24,11 @@ import com.example.ui.settings.components.DataExportImportSection
import com.example.ui.settings.components.GoogleSheetsIntegrationSection
import com.example.ui.settings.components.NotificationRemindersSection
import com.example.ui.theme.AppThemeMode
import com.google.firebase.Firebase
import com.google.firebase.auth.auth
import com.example.util.GoogleDriveAccount
@Composable
fun SettingsScreen(
googleAccount: GoogleDriveAccount?,
currentThemeMode: AppThemeMode,
totalMealsCount: Int,
sheetsUiState: GoogleSheetsUiState,
@@ -48,8 +48,6 @@ fun SettingsScreen(
onSignOut: () -> Unit,
modifier: Modifier = Modifier
) {
val currentUser = Firebase.auth.currentUser
LazyColumn(
modifier = modifier
.fillMaxSize()
@@ -70,20 +68,19 @@ fun SettingsScreen(
fontWeight = FontWeight.Bold
)
Text(
text = "Export CSV, rappels personnalisés, thème et compte",
text = "Sauvegarde Google Drive, export CSV, rappels et thème",
style = MaterialTheme.typography.bodyMedium,
color = MaterialTheme.colorScheme.onBackground.copy(alpha = 0.7f)
)
}
}
// 1. Local Database & CSV Management
// 1. Google Drive Account
item {
DataExportImportSection(
totalMealsCount = totalMealsCount,
onImportCsvClick = onImportCsvClick,
onSaveCsvClick = onSaveCsvClick,
onShareCsvClick = onShareCsvClick
AccountAndSecuritySection(
googleAccount = googleAccount,
onSignInClick = onSignInClick,
onSignOut = onSignOut
)
}
@@ -100,7 +97,17 @@ fun SettingsScreen(
)
}
// 3. Reminders
// 3. Local Database & CSV Management
item {
DataExportImportSection(
totalMealsCount = totalMealsCount,
onImportCsvClick = onImportCsvClick,
onSaveCsvClick = onSaveCsvClick,
onShareCsvClick = onShareCsvClick
)
}
// 4. Reminders
item {
NotificationRemindersSection(
onScheduleReminder = onScheduleReminder,
@@ -108,7 +115,7 @@ fun SettingsScreen(
)
}
// 4. Theme Selector
// 5. Theme Selector
item {
AppearanceThemeSection(
currentThemeMode = currentThemeMode,
@@ -116,15 +123,6 @@ fun SettingsScreen(
)
}
// 5. Account & Cloud Sync
item {
AccountAndSecuritySection(
currentUser = currentUser,
onSignInClick = onSignInClick,
onSignOut = onSignOut
)
}
item {
Spacer(modifier = Modifier.height(64.dp))
}
@@ -17,7 +17,7 @@ import androidx.compose.material.icons.automirrored.filled.ExitToApp
import androidx.compose.material.icons.automirrored.filled.Login
import androidx.compose.material.icons.filled.AccountCircle
import androidx.compose.material.icons.filled.CloudDone
import androidx.compose.material.icons.filled.CloudOff
import androidx.compose.material.icons.filled.PhoneAndroid
import androidx.compose.material3.Button
import androidx.compose.material3.ButtonDefaults
import androidx.compose.material3.Card
@@ -32,11 +32,11 @@ import androidx.compose.ui.Modifier
import androidx.compose.ui.platform.testTag
import androidx.compose.ui.text.font.FontWeight
import androidx.compose.ui.unit.dp
import com.google.firebase.auth.FirebaseUser
import com.example.util.GoogleDriveAccount
@Composable
fun AccountAndSecuritySection(
currentUser: FirebaseUser?,
googleAccount: GoogleDriveAccount?,
onSignInClick: () -> Unit,
onSignOut: () -> Unit,
modifier: Modifier = Modifier
@@ -49,7 +49,7 @@ fun AccountAndSecuritySection(
)
) {
Column(modifier = Modifier.padding(20.dp)) {
if (currentUser != null) {
if (googleAccount != null) {
Row(verticalAlignment = Alignment.CenterVertically) {
Surface(
modifier = Modifier.size(40.dp),
@@ -70,13 +70,13 @@ fun AccountAndSecuritySection(
Column {
Text(
text = currentUser.displayName ?: "Compte Google",
text = googleAccount.displayName ?: "Compte Google Drive",
style = MaterialTheme.typography.titleMedium,
color = MaterialTheme.colorScheme.onSurface,
fontWeight = FontWeight.Bold
)
Text(
text = currentUser.email ?: "Synchronisation Cloud Firestore active",
text = googleAccount.email,
style = MaterialTheme.typography.bodySmall,
color = MaterialTheme.colorScheme.onSurfaceVariant
)
@@ -103,7 +103,7 @@ fun AccountAndSecuritySection(
)
Spacer(modifier = Modifier.width(8.dp))
Text(
text = "Base de données cloud sécurisée • Synchronisation continue",
text = "Stockage local actif • Compte Google utilisé uniquement pour votre Google Drive personnel",
style = MaterialTheme.typography.bodySmall,
color = MaterialTheme.colorScheme.onSurfaceVariant
)
@@ -128,7 +128,7 @@ fun AccountAndSecuritySection(
modifier = Modifier.size(18.dp)
)
Spacer(modifier = Modifier.width(8.dp))
Text("Passer en mode local uniquement (Déconnexion)")
Text("Déconnecter Google Drive")
}
} else {
Row(verticalAlignment = Alignment.CenterVertically) {
@@ -139,7 +139,7 @@ fun AccountAndSecuritySection(
) {
Box(contentAlignment = Alignment.Center) {
Icon(
imageVector = Icons.Default.CloudOff,
imageVector = Icons.Default.PhoneAndroid,
contentDescription = null,
tint = MaterialTheme.colorScheme.onSecondaryContainer,
modifier = Modifier.size(22.dp)
@@ -151,13 +151,13 @@ fun AccountAndSecuritySection(
Column {
Text(
text = "Mode hors-ligne local actif",
text = "Stockage 100 % local actif",
style = MaterialTheme.typography.titleMedium,
color = MaterialTheme.colorScheme.onSurface,
fontWeight = FontWeight.Bold
)
Text(
text = "Données stockées sur cet appareil sans aucun compte",
text = "Repas, aliments et recettes enregistrés sur cet appareil",
style = MaterialTheme.typography.bodySmall,
color = MaterialTheme.colorScheme.onSurfaceVariant
)
@@ -167,7 +167,7 @@ fun AccountAndSecuritySection(
Spacer(modifier = Modifier.height(14.dp))
Text(
text = "Vous pouvez utiliser Satiéa librement en local. La connexion Google est optionnelle pour sauvegarder et synchroniser vos repas entre appareils.",
text = "Aucun serveur externe ni base cloud tierce. Connectez votre compte Google uniquement si vous souhaitez sauvegarder et restaurer vos données sur votre propre Google Drive.",
style = MaterialTheme.typography.bodySmall,
color = MaterialTheme.colorScheme.onSurfaceVariant
)
@@ -187,7 +187,7 @@ fun AccountAndSecuritySection(
modifier = Modifier.size(18.dp)
)
Spacer(modifier = Modifier.width(8.dp))
Text("Se connecter avec Google (Optionnel)")
Text("Connecter mon compte Google Drive")
}
}
}
@@ -333,7 +333,7 @@ fun GoogleSheetsIntegrationSection(
OutlinedButton(
onClick = { showRestoreConfirmDialog = true },
enabled = spreadsheetUrl != null && sheetsUiState !is GoogleSheetsUiState.Syncing,
enabled = sheetsUiState !is GoogleSheetsUiState.Syncing,
modifier = Modifier
.fillMaxWidth()
.testTag("restore_sheets_button"),
@@ -345,13 +345,13 @@ fun GoogleSheetsIntegrationSection(
modifier = Modifier.size(18.dp)
)
Spacer(modifier = Modifier.width(6.dp))
Text("Restaurer mes données depuis Google Drive & Sheets")
Text("Restaurer depuis Google Drive & Sheets")
}
Spacer(modifier = Modifier.height(12.dp))
Text(
text = "Un classeur dédié « Satiéa — Journal des Repas » est géré automatiquement dans votre Google Drive personnel avec en-têtes et données ordonnées.",
text = "Votre dossier personnel « Satiéa » sur Google Drive contient vos photos ainsi que le classeur 3 onglets : Journal des repas, Mes plats et aliments, et Mes recettes.",
style = MaterialTheme.typography.bodySmall,
color = MaterialTheme.colorScheme.onSurfaceVariant.copy(alpha = 0.8f)
)
@@ -370,7 +370,7 @@ fun GoogleSheetsIntegrationSection(
},
text = {
Text(
text = "Voulez-vous restaurer vos repas et plats personnalisés depuis votre classeur Google Sheets ?\n\nVos ajouts locaux récents seront conservés et fusionnés sans doublon.",
text = "Voulez-vous restaurer vos repas, aliments colorés et recettes depuis votre classeur Google Sheets personnel ?\n\nVos ajouts locaux récents seront conservés et fusionnés sans doublon.",
style = MaterialTheme.typography.bodyMedium
)
},
@@ -1,13 +1,17 @@
package com.example.ui.stats
import androidx.compose.foundation.BorderStroke
import androidx.compose.foundation.Canvas
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.ExperimentalLayoutApi
import androidx.compose.foundation.layout.FlowRow
import androidx.compose.foundation.layout.PaddingValues
import androidx.compose.foundation.layout.Row
import androidx.compose.foundation.layout.Spacer
import androidx.compose.foundation.layout.fillMaxHeight
import androidx.compose.foundation.layout.fillMaxSize
import androidx.compose.foundation.layout.fillMaxWidth
import androidx.compose.foundation.layout.height
@@ -34,6 +38,7 @@ 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.geometry.Offset
import androidx.compose.ui.geometry.Size
import androidx.compose.ui.graphics.Color
@@ -43,7 +48,14 @@ import androidx.compose.ui.graphics.drawscope.Stroke
import androidx.compose.ui.platform.testTag
import androidx.compose.ui.text.font.FontWeight
import androidx.compose.ui.unit.dp
import com.example.data.model.FoodCategory
import com.example.data.model.MealType
import com.example.ui.common.FoodCategoryColorDot
import com.example.ui.common.badgeBorderColor
import com.example.ui.common.badgeContainerColor
import com.example.ui.common.badgeTextColor
import com.example.ui.common.dotFillColor
import com.example.ui.common.isSatieaDarkTheme
import com.example.ui.journal.DayStat
import com.example.ui.journal.WeeklyStats
import java.util.Locale
@@ -258,6 +270,11 @@ fun WeeklyStatsScreen(
}
}
// Color-coded food diversity over last 7 days
item {
PlateDiversityCard(categoryDistribution = weeklyStats.categoryDistribution)
}
// Meal type breakdown
item {
Card(
@@ -321,6 +338,123 @@ fun WeeklyStatsScreen(
}
}
@OptIn(ExperimentalLayoutApi::class)
@Composable
private fun PlateDiversityCard(
categoryDistribution: Map<FoodCategory, Int>
) {
val isDark = isSatieaDarkTheme()
val sortedEntries = categoryDistribution.entries
.filter { it.value > 0 }
.sortedByDescending { it.value }
val totalItems = sortedEntries.sumOf { it.value }
Card(
modifier = Modifier
.fillMaxWidth()
.testTag("stats_plate_diversity_card"),
shape = RoundedCornerShape(20.dp),
colors = CardDefaults.cardColors(
containerColor = MaterialTheme.colorScheme.surface
)
) {
Column(
modifier = Modifier
.fillMaxWidth()
.padding(20.dp)
) {
Row(
modifier = Modifier.fillMaxWidth(),
horizontalArrangement = Arrangement.SpaceBetween,
verticalAlignment = Alignment.CenterVertically
) {
Text(
text = "Diversité des assiettes (7 jours)",
style = MaterialTheme.typography.titleSmall,
color = MaterialTheme.colorScheme.onSurface,
fontWeight = FontWeight.Bold
)
if (totalItems > 0) {
Text(
text = "${sortedEntries.size} famille${if (sortedEntries.size > 1) "s" else ""}",
style = MaterialTheme.typography.labelSmall,
color = MaterialTheme.colorScheme.primary,
fontWeight = FontWeight.SemiBold
)
}
}
Spacer(modifier = Modifier.height(6.dp))
if (totalItems == 0) {
Text(
text = "Ajoutez des aliments dans vos repas pour visualiser les couleurs de vos assiettes.",
style = MaterialTheme.typography.bodySmall,
color = MaterialTheme.colorScheme.onSurfaceVariant
)
} else {
Text(
text = "Présence des familles alimentaires sur vos repas récents",
style = MaterialTheme.typography.bodySmall,
color = MaterialTheme.colorScheme.onSurfaceVariant
)
Spacer(modifier = Modifier.height(14.dp))
// Segmented proportional color bar
Row(
modifier = Modifier
.fillMaxWidth()
.height(12.dp)
.clip(RoundedCornerShape(6.dp))
.background(MaterialTheme.colorScheme.surfaceVariant),
horizontalArrangement = Arrangement.spacedBy(2.dp)
) {
sortedEntries.forEach { (category, count) ->
val weight = (count.toFloat() / totalItems.toFloat()).coerceAtLeast(0.03f)
Box(
modifier = Modifier
.weight(weight)
.fillMaxHeight()
.background(category.dotFillColor(isDark))
)
}
}
Spacer(modifier = Modifier.height(14.dp))
FlowRow(
horizontalArrangement = Arrangement.spacedBy(8.dp),
verticalArrangement = Arrangement.spacedBy(8.dp),
modifier = Modifier.fillMaxWidth()
) {
sortedEntries.forEach { (category, count) ->
Surface(
shape = RoundedCornerShape(10.dp),
color = category.badgeContainerColor(isDark),
border = BorderStroke(1.dp, category.badgeBorderColor(isDark))
) {
Row(
modifier = Modifier.padding(horizontal = 9.dp, vertical = 5.dp),
verticalAlignment = Alignment.CenterVertically
) {
FoodCategoryColorDot(category = category, size = 8.dp)
Spacer(modifier = Modifier.width(6.dp))
Text(
text = "${category.shortLabel} · $count",
style = MaterialTheme.typography.labelSmall,
color = category.badgeTextColor(isDark),
fontWeight = FontWeight.SemiBold
)
}
}
}
}
}
}
}
}
@Composable
private fun WeeklyChartCard(dailyStats: List<DayStat>) {
val satietyColor = MaterialTheme.colorScheme.primary