diff --git a/AGENTS.md b/AGENTS.md index d6eab171..7a3d0325 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -1236,6 +1236,15 @@ clutter came from ignoring one of them: - **A goal saved anywhere goes through `GoalSync.afterManualSave`** — it is what stops the field following the coach, sends the step goal to the ring and republishes the widget. +## Logging a food again: suggestions come from the user's own history + +Typing a meal's name in the Log Meal form offers foods logged before (`service/FoodHistory.kt`, +`MealEntryDao.recentReal`): one per food, names compared without case or accents, with the +numbers from its newest log; names starting with the text first, then most-logged, then most +recent. Nothing under two letters, and demo rows never appear. A pick fills name, meal type and +macros, all still editable, and the saved meal keeps the original's provenance (barcode code, +serving, AI-estimate source); changing a number marks it `userEdited`, as a barcode pick does. + ## Type, colour and chrome: one of each role (audit, v2.11.52) - **Type sizes come from `PulseType.SCALE`** (12, 14, 16, 20, 24, 28, 32, 40). 12sp is the floor diff --git a/app/src/main/assets/i18n/pt-BR.json b/app/src/main/assets/i18n/pt-BR.json index ddb629e9..8aa5696e 100644 --- a/app/src/main/assets/i18n/pt-BR.json +++ b/app/src/main/assets/i18n/pt-BR.json @@ -1669,6 +1669,7 @@ "Use location & weather": "Usar localização e clima", "Use the device you already wear": "Use o dispositivo que você já usa", "Use the fitted value": "Usar o valor ajustado", + "Use this food": "Usar este alimento", "Use without a ring": "Usar sem anel", "Use your device's data": "Usar os dados do seu dispositivo", "Use {0}": "Usar {0}", @@ -1852,6 +1853,7 @@ "kg": "kg", "lb": "lb", "less": "menos", + "logged {0} times": "registrado {0} vezes", "lower": "menor", "min": "min", "more": "mais", @@ -1911,6 +1913,7 @@ "{0} in · {1} out": "{0} entrada · {1} saída", "{0} inactive {1} since {2}:00": "{0} {1} sem se mexer desde as {2}:00", "{0} is retiring this model on {1}.": "{0} vai descontinuar este modelo em {1}.", + "{0} kcal · P {1} · C {2} · F {3}": "{0} kcal · P {1} · C {2} · G {3}", "{0} lab markers to review": "{0} marcadores de exame para revisar", "{0} left this week": "Restam {0} esta semana", "{0} markers": "{0} marcadores", diff --git a/app/src/main/java/com/pulseloop/data/dao/Daos.kt b/app/src/main/java/com/pulseloop/data/dao/Daos.kt index 7cfbfb4c..5393d9a1 100644 --- a/app/src/main/java/com/pulseloop/data/dao/Daos.kt +++ b/app/src/main/java/com/pulseloop/data/dao/Daos.kt @@ -607,6 +607,10 @@ interface MealEntryDao { @Query("SELECT * FROM meal_entries WHERE id = :id LIMIT 1") suspend fun byId(id: String): MealEntryEntity? + /** The user's own past meals, newest first, for suggesting a food again (FoodHistory). */ + @Query("SELECT * FROM meal_entries WHERE sourceRaw NOT IN ('demo','mock') ORDER BY timestamp DESC LIMIT :limit") + suspend fun recentReal(limit: Int = 1000): List + @Upsert suspend fun upsert(entry: MealEntryEntity) diff --git a/app/src/main/java/com/pulseloop/service/FoodHistory.kt b/app/src/main/java/com/pulseloop/service/FoodHistory.kt new file mode 100644 index 00000000..48fd8bd2 --- /dev/null +++ b/app/src/main/java/com/pulseloop/service/FoodHistory.kt @@ -0,0 +1,52 @@ +package com.pulseloop.service + +import com.pulseloop.data.entity.MealEntryEntity +import java.text.Normalizer + +/** + * Foods the user has logged before, offered again as they type a meal's name. + * + * One suggestion per food (names compared without case, accents or extra spaces), carrying the + * numbers from its most recent log, so a portion the user corrected last time is the one they + * get back. A name that starts with what was typed ranks first, then a name with a word that + * starts with it; within each, the food logged most often, then most recently. + */ +object FoodHistory { + data class Suggestion( + /** The newest log of this food: its name as last written and its numbers. */ + val entry: MealEntryEntity, + /** How many times it has been logged. */ + val count: Int, + ) + + /** Typed text shorter than this suggests nothing: one letter matches half the history. */ + const val MIN_QUERY = 2 + + fun normalize(text: String): String = + Normalizer.normalize(text.lowercase().trim(), Normalizer.Form.NFD) + .replace(Regex("\\p{Mn}+"), "") + .replace(Regex("\\s+"), " ") + + fun suggest(history: List, query: String, limit: Int = 5): List { + val q = normalize(query) + if (q.length < MIN_QUERY) return emptyList() + val foods = history + .filter { it.name.isNotBlank() && it.calories > 0 } + .groupBy { normalize(it.name) } + return foods.mapNotNull { (key, logs) -> + // Typed in full already: nothing to offer but the same name. + if (key == q) return@mapNotNull null + val rank = when { + key.startsWith(q) -> 0 + key.split(' ', ',', '(', '-', '/').any { it.startsWith(q) } -> 1 + else -> return@mapNotNull null + } + Triple(rank, logs.maxBy { it.timestamp }, logs.size) + } + .sortedWith(compareBy> { it.first } + .thenByDescending { it.third } + .thenByDescending { it.second.timestamp }) + .take(limit) + .map { Suggestion(it.second, it.third) } + } +} diff --git a/app/src/main/java/com/pulseloop/ui/screens/NutritionScreen.kt b/app/src/main/java/com/pulseloop/ui/screens/NutritionScreen.kt index a3781528..c06cdb74 100644 --- a/app/src/main/java/com/pulseloop/ui/screens/NutritionScreen.kt +++ b/app/src/main/java/com/pulseloop/ui/screens/NutritionScreen.kt @@ -4,6 +4,8 @@ import com.pulseloop.ui.i18n.trf import com.pulseloop.ui.i18n.tr +import androidx.compose.foundation.background +import androidx.compose.foundation.clickable import androidx.compose.foundation.layout.* import androidx.compose.foundation.rememberScrollState import androidx.compose.foundation.verticalScroll @@ -17,6 +19,7 @@ import androidx.compose.material.icons.filled.AutoAwesome import androidx.compose.material.icons.filled.ChevronLeft import androidx.compose.material.icons.filled.ChevronRight import androidx.compose.material.icons.filled.Delete +import androidx.compose.material.icons.filled.History import androidx.compose.material.icons.filled.PhotoCamera import androidx.compose.material.icons.filled.QrCodeScanner import androidx.compose.material3.* @@ -24,6 +27,7 @@ import androidx.compose.runtime.* import androidx.compose.ui.Alignment import androidx.compose.ui.Modifier import androidx.compose.ui.draw.alpha +import androidx.compose.ui.draw.clip import androidx.compose.ui.graphics.Color import androidx.compose.ui.text.font.FontWeight import androidx.compose.ui.text.style.TextAlign @@ -413,6 +417,16 @@ fun MealLogDialog( var estimating by remember { mutableStateOf(false) } var aiEstimate by remember { mutableStateOf(null) } var aiNotice by remember { mutableStateOf(null) } + // Foods logged before, offered as the name is typed (FoodHistory). The pick is kept so the + // saved meal carries the original's provenance (barcode, AI estimate, serving) while its + // numbers are unchanged. + val history by androidx.compose.runtime.produceState(emptyList()) { + value = runCatching { db.mealEntryDao().recentReal() }.getOrDefault(emptyList()) + } + var reused by remember { mutableStateOf(null) } + val suggestions = remember(history, name, reused) { + if (reused != null) emptyList() else com.pulseloop.service.FoodHistory.suggest(history, name) + } /** iOS ManualMealForm.fieldText (MealLogSheet.swift:582-584): whole or one decimal. */ fun fieldText(value: Double): String = @@ -517,7 +531,43 @@ fun MealLogDialog( // iOS inlineNotice copy (MealLogSheet.swift:128-130 / :259). Text(it, fontSize = 12.sp, color = PulseColors.warning) } - OutlinedTextField(value = name, onValueChange = { name = it }, label = { Text(tr("Name")) }, placeholder = { if (aiAvailable) Text(tr("e.g. rice, beans and a grilled chicken breast")) }, modifier = Modifier.fillMaxWidth(), maxLines = 3, keyboardOptions = androidx.compose.foundation.text.KeyboardOptions(capitalization = androidx.compose.ui.text.input.KeyboardCapitalization.Sentences)) + OutlinedTextField(value = name, onValueChange = { name = it; if (reused != null && it != reused?.name) reused = null }, label = { Text(tr("Name")) }, placeholder = { if (aiAvailable) Text(tr("e.g. rice, beans and a grilled chicken breast")) }, modifier = Modifier.fillMaxWidth(), maxLines = 3, keyboardOptions = androidx.compose.foundation.text.KeyboardOptions(capitalization = androidx.compose.ui.text.input.KeyboardCapitalization.Sentences)) + // "Log it again": the user's own earlier foods matching what was typed. A tap fills + // the name and the numbers from the food's latest log; every field stays editable. + suggestions.forEach { sug -> + val e = sug.entry + Row( + Modifier + .fillMaxWidth() + .heightIn(min = 48.dp) + .clip(RoundedCornerShape(8.dp)) + .background(PulseColors.cardSoft) + .clickable(role = androidx.compose.ui.semantics.Role.Button, onClickLabel = tr("Use this food")) { + reused = e + pendingProduct = null + aiEstimate = null + name = e.name + type = e.mealTypeRaw + cal = fieldText(e.calories) + protein = fieldText(e.proteinG) + carbs = fieldText(e.carbsG) + fat = fieldText(e.fatG) + } + .padding(horizontal = 12.dp, vertical = 8.dp), + verticalAlignment = Alignment.CenterVertically, + horizontalArrangement = Arrangement.spacedBy(8.dp), + ) { + Icon(Icons.Filled.History, null, tint = PulseColors.textMuted, modifier = Modifier.size(20.dp)) + Column(Modifier.weight(1f)) { + Text(e.name, fontSize = 14.sp, fontWeight = FontWeight.SemiBold, color = PulseColors.textPrimary, maxLines = 1, overflow = TextOverflow.Ellipsis) + Text( + trf("{0} kcal · P {1} · C {2} · F {3}", e.calories.roundToInt(), e.proteinG.roundToInt(), e.carbsG.roundToInt(), e.fatG.roundToInt()) + + if (sug.count > 1) " · " + trf("logged {0} times", sug.count) else "", + fontSize = 12.sp, color = PulseColors.textSecondary, maxLines = 1, overflow = TextOverflow.Ellipsis, + ) + } + } + } if (aiAvailable) { OutlinedButton( onClick = { estimateWithAi() }, @@ -572,6 +622,26 @@ fun MealLogDialog( confidenceRaw = MealAnalysisLogic.confidenceRaw(ai.confidence), notes = ai.assumptions.trim().takeIf { it.isNotEmpty() }, ) + } else if (pp == null && reused != null) { + // A food logged again keeps where its numbers came from (barcode, AI + // estimate, serving); changing them marks it edited, as a barcode pick does. + val r = reused!! + val p = protein.toDoubleOrNull() ?: 0.0 + val c = carbs.toDoubleOrNull() ?: 0.0 + val f = fat.toDoubleOrNull() ?: 0.0 + val edited = kcal != r.calories || p != r.proteinG || c != r.carbsG || f != r.fatG + MealLogSave( + name = name.trim(), type = type, calories = kcal, + proteinG = p, carbsG = c, fatG = f, + sourceRaw = r.sourceRaw, + offProductCode = r.offProductCode, + servingDescription = r.servingDescription, + servingGrams = r.servingGrams, + quantity = r.quantity, + userEdited = r.userEdited || edited, + confidenceRaw = r.confidenceRaw, + notes = r.notes, + ) } else if (pp == null) { MealLogSave( name = name.trim(), type = type, calories = kcal, diff --git a/app/src/test/java/com/pulseloop/service/FoodHistoryTest.kt b/app/src/test/java/com/pulseloop/service/FoodHistoryTest.kt new file mode 100644 index 00000000..acf8089a --- /dev/null +++ b/app/src/test/java/com/pulseloop/service/FoodHistoryTest.kt @@ -0,0 +1,54 @@ +package com.pulseloop.service + +import com.pulseloop.data.entity.MealEntryEntity +import org.junit.Assert.assertEquals +import org.junit.Assert.assertTrue +import org.junit.Test + +/** Suggesting a food again from what the user logged before. */ +class FoodHistoryTest { + private fun meal(name: String, kcal: Double, at: Long) = + MealEntryEntity(date = 0, timestamp = at, name = name, calories = kcal) + + @Test + fun oneSuggestionPerFoodWithItsNewestNumbers() { + val history = listOf( + meal("Pão de queijo", 120.0, at = 1), + meal("pao de queijo ", 150.0, at = 3), + meal("Pão francês", 140.0, at = 2), + ) + val s = FoodHistory.suggest(history, "pao") + assertEquals(2, s.size) + // Accents and case don't split a food; the newest log's numbers come back. + assertEquals(150.0, s.first().entry.calories, 0.0) + assertEquals(2, s.first().count) + } + + @Test + fun aNameThatStartsWithTheTextRanksAboveAWordInside() { + val history = listOf( + meal("Grilled chicken salad", 400.0, at = 5), + meal("Chicken and rice", 600.0, at = 1), + ) + val s = FoodHistory.suggest(history, "chick") + assertEquals(listOf("Chicken and rice", "Grilled chicken salad"), s.map { it.entry.name }) + } + + @Test + fun theMostLoggedComesFirstWithinARank() { + val history = listOf( + meal("Yogurt", 100.0, at = 9), + meal("Yoghurt bowl", 300.0, at = 1), + meal("Yoghurt bowl", 300.0, at = 2), + ) + assertEquals("Yoghurt bowl", FoodHistory.suggest(history, "yo").first().entry.name) + } + + @Test + fun nothingForOneLetterAnExactMatchOrAZeroCalorieLog() { + val history = listOf(meal("Banana", 90.0, at = 1), meal("Bacon", 0.0, at = 2)) + assertTrue(FoodHistory.suggest(history, "b").isEmpty()) + assertTrue(FoodHistory.suggest(history, "banana").isEmpty()) + assertEquals(listOf("Banana"), FoodHistory.suggest(history, "ba").map { it.entry.name }) + } +}