translate: save favorites and translation history (#819)
- Commit
569feba634cbb1f9a0947433314ba11ac778c110- Author
- vayun-mathur <[email protected]>
- When
- 2026-10-16 03:59 UTC (1 month ago)
- Parents
7d46515
Diff
translate/build.gradle.kts
diff --git a/translate/build.gradle.kts b/translate/build.gradle.ktsindex 4fceeaf68e..1dbbaab8ec 100644--- a/translate/build.gradle.kts+++ b/translate/build.gradle.kts@@ -29,4 +29,6 @@ dependencies { implementation(libs.androidx.camera.lifecycle) implementation(libs.androidx.camera.view) implementation(libs.androidx.camera.compose)+ implementRoom(libs)+ implementation(project(":library:room")) }
translate/src/main/java/com/vayunmathur/translate/Navigation.kt
diff --git a/translate/src/main/java/com/vayunmathur/translate/Navigation.kt b/translate/src/main/java/com/vayunmathur/translate/Navigation.ktindex 1a72bec55f..e08a4e71aa 100644--- a/translate/src/main/java/com/vayunmathur/translate/Navigation.kt+++ b/translate/src/main/java/com/vayunmathur/translate/Navigation.kt@@ -1,29 +1,51 @@ package com.vayunmathur.translate 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 com.vayunmathur.library.util.DialogPage import com.vayunmathur.library.util.FullscreenPage import com.vayunmathur.library.util.MainNavigation import com.vayunmathur.library.util.rememberNavBackStack+import com.vayunmathur.translate.data.TranslationRecord import com.vayunmathur.translate.platform.TranslateViewModel import com.vayunmathur.translate.ui.CameraTranslateScreen+import com.vayunmathur.translate.ui.HistoryPage import com.vayunmathur.translate.ui.LanguagePickerPage import com.vayunmathur.translate.ui.TextTranslatePage @Composable fun Navigation(viewModel: TranslateViewModel, initialText: String) { val backStack = rememberNavBackStack<Route>(Route.Text)+ // A history row tapped for reuse: consumed once by the text page, which loads+ // the record's source text and language pair, then the stack pops back to Text.+ var reuseRequest by remember { mutableStateOf<TranslationRecord?>(null) } MainNavigation(backStack) { entry<Route.Text> { TextTranslatePage( viewModel = viewModel, initialText = initialText,+ reuseRequest = reuseRequest,+ onReuseConsumed = { reuseRequest = null }, onOpenCamera = { backStack.add(Route.Camera) },+ onOpenHistory = { backStack.add(Route.History) }, onOpenLanguagePicker = { forSource -> backStack.add(Route.LanguagePicker(forSource)) }, ) }+ entry<Route.History> {+ HistoryPage(+ viewModel = viewModel,+ onReuse = { record ->+ reuseRequest = record+ backStack.pop()+ },+ onBack = { backStack.pop() },+ )+ } entry<Route.Camera>(metadata = FullscreenPage()) { CameraTranslateScreen( viewModel = viewModel,
translate/src/main/java/com/vayunmathur/translate/Route.kt
diff --git a/translate/src/main/java/com/vayunmathur/translate/Route.kt b/translate/src/main/java/com/vayunmathur/translate/Route.ktindex e4aa75f26a..96d88ee929 100644--- a/translate/src/main/java/com/vayunmathur/translate/Route.kt+++ b/translate/src/main/java/com/vayunmathur/translate/Route.kt@@ -13,4 +13,7 @@ sealed interface Route : NavKey { @Serializable data class LanguagePicker(val forSource: Boolean) : Route++ @Serializable+ data object History : Route }
translate/src/main/java/com/vayunmathur/translate/data/TranslateDatabase.kt
diff --git a/translate/src/main/java/com/vayunmathur/translate/data/TranslateDatabase.kt b/translate/src/main/java/com/vayunmathur/translate/data/TranslateDatabase.ktnew file mode 100644index 0000000000..a71bd6b921--- /dev/null+++ b/translate/src/main/java/com/vayunmathur/translate/data/TranslateDatabase.kt@@ -0,0 +1,75 @@+package com.vayunmathur.translate.data++import androidx.room3.Dao+import androidx.room3.Database+import androidx.room3.Delete+import androidx.room3.Entity+import androidx.room3.PrimaryKey+import androidx.room3.Query+import androidx.room3.RoomDatabase+import androidx.room3.Upsert+import kotlinx.coroutines.flow.Flow++const val TRANSLATE_DB_NAME = "translate-db"++/**+ * One saved translation: the source text, its translation, and the language pair.+ *+ * A row is created the first time a translation completes and refreshed (same id,+ * bumped [createdAt]) when the same input + pair translates again, so re-translating+ * moves the entry to the top instead of duplicating it. [isFavorite] pins the entry:+ * favorites survive [TranslateRepository.pruneHistory] and sort first in history.+ */+@Entity+data class TranslationRecord(+ @PrimaryKey(autoGenerate = true) val id: Long = 0,+ val sourceText: String,+ val translatedText: String,+ val sourceLang: String,+ val targetLang: String,+ val isFavorite: Boolean = false,+ val createdAt: Long = System.currentTimeMillis(),+)++@Dao+interface TranslationDao {+ @Query("SELECT * FROM TranslationRecord ORDER BY isFavorite DESC, createdAt DESC")+ fun getHistoryFlow(): Flow<List<TranslationRecord>>++ @Query("SELECT * FROM TranslationRecord WHERE isFavorite = 1 ORDER BY createdAt DESC")+ fun getFavoritesFlow(): Flow<List<TranslationRecord>>++ /** The existing row for this exact input + pair, if any (for dedupe on re-translate). */+ @Query(+ "SELECT * FROM TranslationRecord WHERE sourceText = :source AND sourceLang = :src " ++ "AND targetLang = :tgt LIMIT 1",+ )+ suspend fun findDuplicate(source: String, src: String, tgt: String): TranslationRecord?++ @Upsert+ suspend fun upsert(value: TranslationRecord): Long++ @Query("UPDATE TranslationRecord SET isFavorite = :favorite WHERE id = :id")+ suspend fun setFavorite(id: Long, favorite: Boolean)++ @Delete+ suspend fun delete(value: TranslationRecord): Int++ @Query("DELETE FROM TranslationRecord WHERE isFavorite = 0")+ suspend fun clearHistory()++ /** Non-favorites past [keepNewest], oldest first — the prune candidates. */+ @Query(+ "SELECT id FROM TranslationRecord WHERE isFavorite = 0 " ++ "ORDER BY createdAt DESC LIMIT -1 OFFSET :keepNewest",+ )+ suspend fun overflowIds(keepNewest: Int): List<Long>++ @Query("DELETE FROM TranslationRecord WHERE id IN (:ids)")+ suspend fun deleteByIds(ids: List<Long>)+}++@Database(entities = [TranslationRecord::class], version = 1, exportSchema = false)+abstract class TranslateDatabase : RoomDatabase() {+ abstract fun translationDao(): TranslationDao+}
translate/src/main/java/com/vayunmathur/translate/data/TranslateRepository.kt
diff --git a/translate/src/main/java/com/vayunmathur/translate/data/TranslateRepository.kt b/translate/src/main/java/com/vayunmathur/translate/data/TranslateRepository.ktnew file mode 100644index 0000000000..f09a039c9b--- /dev/null+++ b/translate/src/main/java/com/vayunmathur/translate/data/TranslateRepository.kt@@ -0,0 +1,64 @@+package com.vayunmathur.translate.data++import android.content.Context+import androidx.room3.withWriteTransaction+import com.vayunmathur.library.room.RoomRepository+import kotlinx.coroutines.flow.Flow++/** Owns saved translations. Favorites never count toward the history cap. */+class TranslateRepository private constructor(context: Context) :+ RoomRepository<TranslateDatabase>(context, TranslateDatabase::class, TRANSLATE_DB_NAME) {++ private val dao get() = db.translationDao()++ val history: Flow<List<TranslationRecord>> get() = dao.getHistoryFlow()+ val favorites: Flow<List<TranslationRecord>> get() = dao.getFavoritesFlow()++ /** Refresh an existing input/language pair without losing its favorite flag. */+ suspend fun record(source: String, translated: String, src: String, tgt: String) {+ if (source.isBlank() || translated.isBlank()) return+ db.withWriteTransaction {+ val existing = dao.findDuplicate(source, src, tgt)+ dao.upsert(+ existing?.copy(+ translatedText = translated,+ createdAt = System.currentTimeMillis(),+ ) ?: TranslationRecord(+ sourceText = source,+ translatedText = translated,+ sourceLang = src,+ targetLang = tgt,+ ),+ )+ pruneHistory()+ }+ }++ suspend fun setFavorite(id: Long, favorite: Boolean) {+ db.withWriteTransaction {+ dao.setFavorite(id, favorite)+ pruneHistory()+ }+ }++ suspend fun delete(record: TranslationRecord): Int = dao.delete(record)++ /** Removes every non-favorite row. Favorites are kept. */+ suspend fun clearHistory() = dao.clearHistory()++ private suspend fun pruneHistory() {+ val overflow = dao.overflowIds(MAX_HISTORY)+ if (overflow.isNotEmpty()) dao.deleteByIds(overflow)+ }++ companion object {+ const val MAX_HISTORY = 200++ @Volatile private var instance: TranslateRepository? = null++ fun get(context: Context): TranslateRepository =+ instance ?: synchronized(this) {+ instance ?: TranslateRepository(context).also { instance = it }+ }+ }+}
translate/src/main/java/com/vayunmathur/translate/platform/TranslateUiContract.kt
diff --git a/translate/src/main/java/com/vayunmathur/translate/platform/TranslateUiContract.kt b/translate/src/main/java/com/vayunmathur/translate/platform/TranslateUiContract.ktindex 6eb1ce3a07..fa1045ed06 100644--- a/translate/src/main/java/com/vayunmathur/translate/platform/TranslateUiContract.kt+++ b/translate/src/main/java/com/vayunmathur/translate/platform/TranslateUiContract.kt@@ -1,5 +1,6 @@ package com.vayunmathur.translate.platform +import com.vayunmathur.translate.data.TranslationRecord import com.vayunmathur.translate.domain.Language import com.vayunmathur.translate.domain.Languages @@ -37,6 +38,10 @@ data class TextTranslateUiState( val inputText: String = "", val outputText: String = "", val isTranslating: Boolean = false,+ /** True when the current input + pair is already saved as a favorite. */+ val isFavorite: Boolean = false,+ /** Only true once the displayed result has a persisted history row. */+ val canSave: Boolean = false, val micState: MicState = MicState.IDLE, val speechError: String? = null, )@@ -56,7 +61,9 @@ interface TextTranslateActions { fun copyOutput() {} fun speakOutput() {}+ fun toggleFavorite() {} fun openCamera() {}+ fun openHistory() {} fun openLanguagePicker(forSource: Boolean) {} companion object {@@ -86,3 +93,24 @@ interface LanguagePickerActions { val Noop: LanguagePickerActions = object : LanguagePickerActions {} } }++/** Everything the history screen draws, as literal values for previews. */+data class HistoryUiState(+ val records: List<TranslationRecord> = emptyList(),+)++/**+ * History callbacks. Every method has a no-op default so a preview can render the+ * screen without supplying behaviour — [Noop] is the whole implementation a preview needs.+ */+interface HistoryActions {+ fun toggleFavorite(id: Long, favorite: Boolean) {}+ fun delete(record: TranslationRecord) {}+ fun clearHistory() {}+ fun reuse(record: TranslationRecord) {}+ fun goBack() {}++ companion object {+ val Noop: HistoryActions = object : HistoryActions {}+ }+}
translate/src/main/java/com/vayunmathur/translate/platform/TranslateViewModel.kt
diff --git a/translate/src/main/java/com/vayunmathur/translate/platform/TranslateViewModel.kt b/translate/src/main/java/com/vayunmathur/translate/platform/TranslateViewModel.ktindex 48a7a61d57..dd76ebbcc8 100644--- a/translate/src/main/java/com/vayunmathur/translate/platform/TranslateViewModel.kt+++ b/translate/src/main/java/com/vayunmathur/translate/platform/TranslateViewModel.kt@@ -1,6 +1,8 @@ package com.vayunmathur.translate.platform +import com.vayunmathur.translate.data.TranslateRepository import com.vayunmathur.translate.data.TranslateSettings+import com.vayunmathur.translate.data.TranslationRecord import com.vayunmathur.translate.domain.Languages import com.vayunmathur.translate.domain.TranslationEngine @@ -9,8 +11,10 @@ import androidx.lifecycle.AndroidViewModel import androidx.lifecycle.viewModelScope import com.vayunmathur.library.ocr.OcrEngine import kotlinx.coroutines.flow.MutableStateFlow+import kotlinx.coroutines.flow.SharingStarted import kotlinx.coroutines.flow.StateFlow import kotlinx.coroutines.flow.asStateFlow+import kotlinx.coroutines.flow.stateIn import kotlinx.coroutines.launch /**@@ -27,6 +31,7 @@ class TranslateViewModel(app: Application) : AndroidViewModel(app) { val ocr = OcrEngine(app) private val tts = TtsSpeaker(app) private val settings = TranslateSettings(app)+ private val historyRepo = TranslateRepository.get(app) private val _sourceLang = MutableStateFlow(Languages.AUTO.code) val sourceLang: StateFlow<String> = _sourceLang.asStateFlow()@@ -45,6 +50,16 @@ class TranslateViewModel(app: Application) : AndroidViewModel(app) { private val _translationAvailable = MutableStateFlow(false) val translationAvailable: StateFlow<Boolean> = _translationAvailable.asStateFlow() + /** Saved translations, favorites first then newest — for the history screen. */+ val history: StateFlow<List<TranslationRecord>> = historyRepo.history.stateIn(+ viewModelScope, SharingStarted.WhileSubscribed(5_000), emptyList(),+ )++ /** Favorites only, newest first. */+ val favorites: StateFlow<List<TranslationRecord>> = historyRepo.favorites.stateIn(+ viewModelScope, SharingStarted.WhileSubscribed(5_000), emptyList(),+ )+ init { viewModelScope.launch { _sourceLang.value = settings.source()@@ -88,6 +103,31 @@ class TranslateViewModel(app: Application) : AndroidViewModel(app) { return translator.translate(text, from, _targetLang.value) } + /**+ * Save a completed translation to history. Called by the page once the debounced+ * translation lands; the repository dedupes re-translations of the same input.+ *+ * The pair rides along explicitly rather than being re-read here: the language+ * can change between the translate call and this write, and the record must+ * name the pair that was actually translated.+ */+ fun recordHistory(source: String, translated: String, src: String, tgt: String) {+ viewModelScope.launch { historyRepo.record(source, translated, src, tgt) }+ }++ fun setFavorite(id: Long, favorite: Boolean) {+ viewModelScope.launch { historyRepo.setFavorite(id, favorite) }+ }++ fun deleteHistory(record: TranslationRecord) {+ viewModelScope.launch { historyRepo.delete(record) }+ }++ /** Removes every non-favorite row. Favorites are kept. */+ fun clearHistory() {+ viewModelScope.launch { historyRepo.clearHistory() }+ }+ /** * Speak [text] in [languageCode] (defaults to the current target). Nothing is spoken * when the TTS engine has no voice for that language — [onMissingVoice] fires instead,
translate/src/main/java/com/vayunmathur/translate/ui/HistoryPage.kt
diff --git a/translate/src/main/java/com/vayunmathur/translate/ui/HistoryPage.kt b/translate/src/main/java/com/vayunmathur/translate/ui/HistoryPage.ktnew file mode 100644index 0000000000..b8ccc1bfd9--- /dev/null+++ b/translate/src/main/java/com/vayunmathur/translate/ui/HistoryPage.kt@@ -0,0 +1,42 @@+package com.vayunmathur.translate.ui++import androidx.compose.runtime.Composable+import androidx.compose.runtime.collectAsState+import androidx.compose.runtime.getValue+import com.vayunmathur.translate.data.TranslationRecord+import com.vayunmathur.translate.platform.HistoryActions+import com.vayunmathur.translate.platform.HistoryUiState+import com.vayunmathur.translate.platform.TranslateViewModel++/**+ * Binds [TranslateViewModel] to the stateless [HistoryScreen].+ *+ * The ViewModel exposes the history and favorites as hot flows; this page+ * collects them and assembles the actions. [onReuse] loads the record back+ * into the text screen via the navigation back-stack.+ */+@Composable+fun HistoryPage(+ viewModel: TranslateViewModel,+ onReuse: (TranslationRecord) -> Unit,+ onBack: () -> Unit,+) {+ val history by viewModel.history.collectAsState()++ HistoryScreen(+ state = HistoryUiState(records = history),+ actions = object : HistoryActions {+ override fun toggleFavorite(id: Long, favorite: Boolean) =+ viewModel.setFavorite(id, favorite)++ override fun delete(record: TranslationRecord) =+ viewModel.deleteHistory(record)++ override fun clearHistory() = viewModel.clearHistory()++ override fun reuse(record: TranslationRecord) = onReuse(record)++ override fun goBack() = onBack()+ },+ )+}
translate/src/main/java/com/vayunmathur/translate/ui/HistoryScreen.kt
diff --git a/translate/src/main/java/com/vayunmathur/translate/ui/HistoryScreen.kt b/translate/src/main/java/com/vayunmathur/translate/ui/HistoryScreen.ktnew file mode 100644index 0000000000..2e590c987d--- /dev/null+++ b/translate/src/main/java/com/vayunmathur/translate/ui/HistoryScreen.kt@@ -0,0 +1,135 @@+package com.vayunmathur.translate.ui++import androidx.compose.foundation.layout.Arrangement+import androidx.compose.foundation.layout.Column+import androidx.compose.foundation.layout.Row+import androidx.compose.foundation.layout.fillMaxSize+import androidx.compose.foundation.layout.fillMaxWidth+import androidx.compose.foundation.layout.padding+import androidx.compose.foundation.lazy.LazyColumn+import androidx.compose.foundation.lazy.items+import androidx.compose.runtime.Composable+import androidx.compose.ui.Alignment+import androidx.compose.ui.Modifier+import androidx.compose.ui.res.stringResource+import androidx.compose.ui.text.style.TextOverflow+import androidx.compose.ui.unit.dp+import com.vayunmathur.library.ui.AppScaffold+import com.vayunmathur.library.ui.Card+import com.vayunmathur.library.ui.IconButton+import com.vayunmathur.library.ui.IconDelete+import com.vayunmathur.library.ui.IconFavorite+import com.vayunmathur.library.ui.MaterialTheme+import com.vayunmathur.library.ui.Text+import com.vayunmathur.library.ui.TextButton+import com.vayunmathur.library.ui.appBarScrollBehavior+import com.vayunmathur.translate.R+import com.vayunmathur.translate.data.TranslationRecord+import com.vayunmathur.translate.domain.Languages+import com.vayunmathur.translate.platform.HistoryActions+import com.vayunmathur.translate.platform.HistoryUiState++/**+ * Saved translations, favorites first then newest — with a star to pin, a delete+ * per row, and a clear-all for everything unstarred. Tapping a row loads it back+ * into the text screen.+ *+ * Stateless like [TextTranslateScreen]: the binder page collects the flows and the+ * previews render this directly.+ */+@Composable+fun HistoryScreen(state: HistoryUiState, actions: HistoryActions) {+ AppScaffold(+ title = stringResource(R.string.history),+ onNavigateBack = actions::goBack,+ actions = {+ if (state.records.any { !it.isFavorite }) {+ TextButton(onClick = actions::clearHistory) {+ Text(stringResource(R.string.clear_history))+ }+ }+ },+ scrollBehavior = appBarScrollBehavior(),+ ) { padding ->+ if (state.records.isEmpty()) {+ Column(+ modifier = Modifier.fillMaxSize().padding(padding).padding(24.dp),+ verticalArrangement = Arrangement.Center,+ horizontalAlignment = Alignment.CenterHorizontally,+ ) {+ Text(+ text = stringResource(R.string.history_empty),+ color = MaterialTheme.colorScheme.onSurfaceVariant,+ )+ }+ return@AppScaffold+ }+ LazyColumn(+ modifier = Modifier.fillMaxSize().padding(padding).padding(horizontal = 16.dp, vertical = 8.dp),+ verticalArrangement = Arrangement.spacedBy(8.dp),+ ) {+ items(state.records, key = { it.id }) { record ->+ HistoryRow(+ record = record,+ onToggleFavorite = { actions.toggleFavorite(record.id, !record.isFavorite) },+ onDelete = { actions.delete(record) },+ onReuse = { actions.reuse(record) },+ )+ }+ }+ }+}++@Composable+private fun HistoryRow(+ record: TranslationRecord,+ onToggleFavorite: () -> Unit,+ onDelete: () -> Unit,+ onReuse: () -> Unit,+) {+ Card(modifier = Modifier.fillMaxWidth(), onClick = onReuse) {+ Column(+ modifier = Modifier.fillMaxWidth().padding(16.dp),+ verticalArrangement = Arrangement.spacedBy(4.dp),+ ) {+ Row(verticalAlignment = Alignment.CenterVertically) {+ Text(+ text = languagePair(record.sourceLang, record.targetLang),+ style = MaterialTheme.typography.labelMedium,+ color = MaterialTheme.colorScheme.primary,+ modifier = Modifier.weight(1f),+ )+ IconButton(onClick = onToggleFavorite) {+ IconFavorite(+ tint = if (record.isFavorite) {+ MaterialTheme.colorScheme.primary+ } else {+ MaterialTheme.colorScheme.onSurfaceVariant+ },+ )+ }+ IconButton(onClick = onDelete) {+ IconDelete()+ }+ }+ Text(+ text = record.sourceText,+ maxLines = 2,+ overflow = TextOverflow.Ellipsis,+ )+ Text(+ text = record.translatedText,+ maxLines = 2,+ overflow = TextOverflow.Ellipsis,+ color = MaterialTheme.colorScheme.onSurfaceVariant,+ )+ }+ }+}++@Composable+private fun languagePair(source: String, target: String): String {+ val from = Languages.displayName(source)+ val to = Languages.displayName(target)+ return stringResource(R.string.history_language_pair, from, to)+}
translate/src/main/java/com/vayunmathur/translate/ui/TextTranslatePage.kt
diff --git a/translate/src/main/java/com/vayunmathur/translate/ui/TextTranslatePage.kt b/translate/src/main/java/com/vayunmathur/translate/ui/TextTranslatePage.ktindex a7e4554b49..f05baf5313 100644--- a/translate/src/main/java/com/vayunmathur/translate/ui/TextTranslatePage.kt+++ b/translate/src/main/java/com/vayunmathur/translate/ui/TextTranslatePage.kt@@ -21,6 +21,7 @@ import androidx.compose.ui.res.stringResource import com.vayunmathur.library.ui.rememberMessenger import com.vayunmathur.library.ui.rememberPermissionRequest import com.vayunmathur.translate.R+import com.vayunmathur.translate.data.TranslationRecord import com.vayunmathur.translate.domain.Languages import com.vayunmathur.translate.platform.AndroidSpeechRecognizer import com.vayunmathur.translate.platform.MicState@@ -48,7 +49,10 @@ private const val TRANSLATE_DEBOUNCE_MS = 400L fun TextTranslatePage( viewModel: TranslateViewModel, initialText: String,+ reuseRequest: TranslationRecord?,+ onReuseConsumed: () -> Unit, onOpenCamera: () -> Unit,+ onOpenHistory: () -> Unit, onOpenLanguagePicker: (Boolean) -> Unit, ) { val context = LocalContext.current@@ -57,11 +61,22 @@ fun TextTranslatePage( val sourceLang by viewModel.sourceLang.collectAsState() val targetLang by viewModel.targetLang.collectAsState() val translationAvailable by viewModel.translationAvailable.collectAsState()+ val history by viewModel.history.collectAsState() var inputText by remember { mutableStateOf(initialText) } var outputText by remember { mutableStateOf("") } var isTranslating by remember { mutableStateOf(false) } + // A history row tapped for reuse: load its text + pair once, then clear the request.+ LaunchedEffect(reuseRequest) {+ val record = reuseRequest ?: return@LaunchedEffect+ viewModel.setSource(record.sourceLang)+ viewModel.setTarget(record.targetLang)+ inputText = record.sourceText+ outputText = record.translatedText+ onReuseConsumed()+ }+ // --- Live speech-to-text engine --- // The platform SpeechRecognizer, which routes to whichever RecognitionService the user // has selected. Installing the Speech app makes that fully offline (Whisper) without@@ -108,8 +123,18 @@ fun TextTranslatePage( if (!translationAvailable) return@LaunchedEffect delay(TRANSLATE_DEBOUNCE_MS) isTranslating = true- outputText = viewModel.translate(inputText).orEmpty()+ val translated = viewModel.translate(inputText).orEmpty()+ outputText = translated isTranslating = false+ // Save every completed translation; the repository dedupes re-translations.+ // The effect's own captured pair, not a fresh read: the language can change+ // between the translate call and this write.+ if (translated.isNotBlank()) viewModel.recordHistory(inputText, translated, sourceLang, targetLang)+ }++ // Whether the current input + pair is already a favorite (for the star toggle).+ val favoriteRecord = history.firstOrNull {+ it.sourceText == inputText && it.sourceLang == sourceLang && it.targetLang == targetLang } // Read here, not in the callback below: stringResource is @Composable.@@ -127,6 +152,8 @@ fun TextTranslatePage( inputText = inputText, outputText = outputText, isTranslating = isTranslating,+ isFavorite = favoriteRecord?.isFavorite == true,+ canSave = !isTranslating && favoriteRecord?.translatedText == outputText, micState = micState, speechError = speechError, ),@@ -158,6 +185,15 @@ fun TextTranslatePage( override fun copyOutput() = copyToClipboard(context, outputText) + // Star the current translation: if it is already saved, flip its flag;+ // if the translation has not completed yet there is nothing to save.+ override fun toggleFavorite() {+ val record = favoriteRecord+ if (record != null) {+ viewModel.setFavorite(record.id, !record.isFavorite)+ }+ }+ // Say so rather than let the engine read the translation out in the device's // language, and offer the engine's own voice-download screen as the fix. override fun speakOutput() {@@ -172,6 +208,8 @@ fun TextTranslatePage( override fun openCamera() = onOpenCamera() + override fun openHistory() = onOpenHistory()+ override fun openLanguagePicker(forSource: Boolean) = onOpenLanguagePicker(forSource) },
translate/src/main/java/com/vayunmathur/translate/ui/TextTranslateScreen.kt
diff --git a/translate/src/main/java/com/vayunmathur/translate/ui/TextTranslateScreen.kt b/translate/src/main/java/com/vayunmathur/translate/ui/TextTranslateScreen.ktindex b084e6c2a0..bb101090a9 100644--- a/translate/src/main/java/com/vayunmathur/translate/ui/TextTranslateScreen.kt+++ b/translate/src/main/java/com/vayunmathur/translate/ui/TextTranslateScreen.kt@@ -27,6 +27,8 @@ import com.vayunmathur.library.ui.FloatingActionButton import com.vayunmathur.library.ui.IconButton import com.vayunmathur.library.ui.IconCamera import com.vayunmathur.library.ui.IconCopy+import com.vayunmathur.library.ui.IconFavorite+import com.vayunmathur.library.ui.IconHistory import com.vayunmathur.library.ui.IconMic import com.vayunmathur.library.ui.IconSpeak import com.vayunmathur.library.ui.IconStop@@ -52,6 +54,9 @@ fun TextTranslateScreen(state: TextTranslateUiState, actions: TextTranslateActio AppScaffold( title = stringResource(R.string.app_name), actions = {+ IconButton(onClick = actions::openHistory) {+ IconHistory()+ } IconButton(onClick = actions::openCamera) { IconCamera() }@@ -123,8 +128,11 @@ fun TextTranslateScreen(state: TextTranslateUiState, actions: TextTranslateActio translationAvailable = state.translationAvailable, isTranslating = state.isTranslating, outputText = state.outputText,+ isFavorite = state.isFavorite,+ canSave = state.canSave, onCopy = actions::copyOutput, onSpeak = actions::speakOutput,+ onToggleFavorite = actions::toggleFavorite, ) } }@@ -140,8 +148,11 @@ fun TextTranslateScreen(state: TextTranslateUiState, actions: TextTranslateActio translationAvailable = state.translationAvailable, isTranslating = state.isTranslating, outputText = state.outputText,+ isFavorite = state.isFavorite,+ canSave = state.canSave, onCopy = actions::copyOutput, onSpeak = actions::speakOutput,+ onToggleFavorite = actions::toggleFavorite, ) } }@@ -224,8 +235,11 @@ private fun OutputCard( translationAvailable: Boolean, isTranslating: Boolean, outputText: String,+ isFavorite: Boolean,+ canSave: Boolean, onCopy: () -> Unit, onSpeak: () -> Unit,+ onToggleFavorite: () -> Unit, ) { Card(modifier = Modifier.fillMaxWidth()) { Column(@@ -279,6 +293,22 @@ private fun OutputCard( Spacer(Modifier.width(6.dp)) Text(stringResource(R.string.speak)) }+ TextButton(onClick = onToggleFavorite, enabled = canSave) {+ IconFavorite(+ Modifier.size(18.dp),+ tint = if (isFavorite) {+ MaterialTheme.colorScheme.primary+ } else {+ MaterialTheme.colorScheme.onSurfaceVariant+ },+ )+ Spacer(Modifier.width(6.dp))+ Text(+ stringResource(+ if (isFavorite) R.string.saved else R.string.save,+ ),+ )+ } } } }
translate/src/main/res/values/strings.xml
diff --git a/translate/src/main/res/values/strings.xml b/translate/src/main/res/values/strings.xmlindex 076f3ebb2c..b5818e0d0c 100644--- a/translate/src/main/res/values/strings.xml+++ b/translate/src/main/res/values/strings.xml@@ -22,4 +22,16 @@ <string name="all_languages">All languages</string> <!-- Empty state when the search query matches no language; %1$s is the query. --> <string name="no_languages_match">No languages match “%1$s”</string>+ <!-- History screen title (saved translations). -->+ <string name="history">History</string>+ <!-- Empty state when no translations have been saved yet. -->+ <string name="history_empty">Translations you make will appear here</string>+ <!-- Clear-history action: removes every non-favorite entry. -->+ <string name="clear_history">Clear</string>+ <!-- History row subtitle: the language pair; %1$s source, %2$s target. -->+ <string name="history_language_pair">%1$s → %2$s</string>+ <!-- Save-to-favorites action on the translation output card. -->+ <string name="save">Save</string>+ <!-- Saved-state label on the translation output card (already a favorite). -->+ <string name="saved">Saved</string> </resources>
translate/src/screenshotTest/kotlin/com/vayunmathur/translate/ui/MetadataPreviews.kt
diff --git a/translate/src/screenshotTest/kotlin/com/vayunmathur/translate/ui/MetadataPreviews.kt b/translate/src/screenshotTest/kotlin/com/vayunmathur/translate/ui/MetadataPreviews.ktindex ab4ddc7886..820e127f59 100644--- a/translate/src/screenshotTest/kotlin/com/vayunmathur/translate/ui/MetadataPreviews.kt+++ b/translate/src/screenshotTest/kotlin/com/vayunmathur/translate/ui/MetadataPreviews.kt@@ -4,7 +4,10 @@ import androidx.compose.runtime.Composable import androidx.compose.ui.tooling.preview.Preview import com.android.tools.screenshot.PreviewTest import com.vayunmathur.library.ui.DynamicTheme+import com.vayunmathur.translate.data.TranslationRecord import com.vayunmathur.translate.domain.Languages+import com.vayunmathur.translate.platform.HistoryActions+import com.vayunmathur.translate.platform.HistoryUiState import com.vayunmathur.translate.platform.LanguagePickerActions import com.vayunmathur.translate.platform.LanguagePickerUiState import com.vayunmathur.translate.platform.MicState@@ -114,4 +117,34 @@ class MetadataPreviews { ) } }++ @PreviewTest+ @Preview(name = "5-history", device = PHONE, showSystemUi = true)+ @Composable+ fun Preview5History() {+ DynamicTheme(darkTheme = true) {+ HistoryScreen(+ state = HistoryUiState(+ records = listOf(+ TranslationRecord(+ id = 1,+ sourceText = "Where is the nearest train station?",+ translatedText = "¿Dónde está la estación de tren más cercana?",+ sourceLang = "en",+ targetLang = "es",+ isFavorite = true,+ ),+ TranslationRecord(+ id = 2,+ sourceText = "Die Bibliothek schließt um achtzehn Uhr.",+ translatedText = "La bibliothèque ferme à dix-huit heures.",+ sourceLang = "de",+ targetLang = "fr",+ ),+ ),+ ),+ actions = HistoryActions.Noop,+ )+ }+ } }