Modern Apps git

← Modern-Apps.git

flashcards: overhaul

Commit
89f8c22868b6ff7f9534e59704a265f4b03f2f45
Author
Vayun Mathur <[email protected]>
When
2026-08-14 21:30 UTC (3 months ago)
Parents
8184f96

Diff

flashcards/build.gradle.kts
diff --git a/flashcards/build.gradle.kts b/flashcards/build.gradle.ktsindex 245bfb914f..c7b62a5515 100644--- a/flashcards/build.gradle.kts+++ b/flashcards/build.gradle.kts@@ -19,4 +19,5 @@ android { dependencies {     implementRoom(libs)     implementation(project(":library:room"))+    implementation(libs.androidx.work.runtime.ktx) }
flashcards/src/main/AndroidManifest.xml
diff --git a/flashcards/src/main/AndroidManifest.xml b/flashcards/src/main/AndroidManifest.xmlindex a5e7620c16..0af7329715 100644--- a/flashcards/src/main/AndroidManifest.xml+++ b/flashcards/src/main/AndroidManifest.xml@@ -1,6 +1,8 @@ <?xml version="1.0" encoding="utf-8"?> <manifest xmlns:android="http://schemas.android.com/apk/res/android"> +    <uses-permission android:name="android.permission.POST_NOTIFICATIONS" />+     <application         android:allowBackup="true"         android:backupAgent=".util.AppBackupAgent"@@ -20,6 +22,16 @@                 <category android:name="android.intent.category.LAUNCHER" />             </intent-filter>         </activity>++        <provider+            android:name="androidx.core.content.FileProvider"+            android:authorities="${applicationId}.fileprovider"+            android:exported="false"+            android:grantUriPermissions="true">+            <meta-data+                android:name="android.support.FILE_PROVIDER_PATHS"+                android:resource="@xml/file_paths" />+        </provider>     </application>  </manifest>
flashcards/src/main/java/com/vayunmathur/flashcards/MainActivity.kt
diff --git a/flashcards/src/main/java/com/vayunmathur/flashcards/MainActivity.kt b/flashcards/src/main/java/com/vayunmathur/flashcards/MainActivity.ktindex 7991c56193..1e5118fbdf 100644--- a/flashcards/src/main/java/com/vayunmathur/flashcards/MainActivity.kt+++ b/flashcards/src/main/java/com/vayunmathur/flashcards/MainActivity.kt@@ -5,27 +5,36 @@ import androidx.activity.ComponentActivity import androidx.activity.compose.setContent import androidx.activity.enableEdgeToEdge import androidx.activity.viewModels+import androidx.compose.runtime.Composable import androidx.compose.runtime.getValue import androidx.compose.runtime.mutableStateOf+import androidx.compose.ui.res.stringResource+import androidx.lifecycle.compose.collectAsStateWithLifecycle import androidx.lifecycle.lifecycleScope import com.vayunmathur.flashcards.data.CardDao import com.vayunmathur.flashcards.data.DB_NAME import com.vayunmathur.flashcards.data.DeckDao import com.vayunmathur.flashcards.data.FlashcardsDatabase+import com.vayunmathur.flashcards.data.ReviewLogDao import com.vayunmathur.flashcards.ui.CardEditPage import com.vayunmathur.flashcards.ui.CardListPage import com.vayunmathur.flashcards.ui.DeckListPage import com.vayunmathur.flashcards.ui.ReviewPage+import com.vayunmathur.flashcards.ui.SettingsPage+import com.vayunmathur.flashcards.ui.StatsPage import com.vayunmathur.flashcards.util.FlashcardsViewModel import com.vayunmathur.flashcards.util.FlashcardsViewModelFactory+import com.vayunmathur.flashcards.util.ThemeMode import com.vayunmathur.library.room.buildDatabase import com.vayunmathur.library.ui.DynamicTheme-import com.vayunmathur.library.util.ListDetailPage-import com.vayunmathur.library.util.ListPage+import com.vayunmathur.library.ui.IconDashboard+import com.vayunmathur.library.ui.IconSettings+import com.vayunmathur.library.ui.IconStyle+import com.vayunmathur.library.util.BottomBarItem+import com.vayunmathur.library.util.BottomNavBar import com.vayunmathur.library.util.MainNavigation import com.vayunmathur.library.util.NavKey import com.vayunmathur.library.util.rememberNavBackStack-import androidx.compose.runtime.Composable import kotlinx.coroutines.Dispatchers import kotlinx.coroutines.launch import kotlinx.coroutines.withContext@@ -34,8 +43,9 @@ import kotlinx.serialization.Serializable class MainActivity : ComponentActivity() {     private lateinit var deckDao: DeckDao     private lateinit var cardDao: CardDao+    private lateinit var reviewLogDao: ReviewLogDao     private val viewModel: FlashcardsViewModel by viewModels {-        FlashcardsViewModelFactory(application, deckDao, cardDao)+        FlashcardsViewModelFactory(application, deckDao, cardDao, reviewLogDao)     }      override fun onCreate(savedInstanceState: Bundle?) {@@ -47,12 +57,21 @@ class MainActivity : ComponentActivity() {             val db = buildDatabase<FlashcardsDatabase>(dbName = DB_NAME)             deckDao = db.deckDao()             cardDao = db.cardDao()+            reviewLogDao = db.reviewLogDao()             withContext(Dispatchers.Main) { ready.value = true }         }          setContent {-            DynamicTheme {-                if (ready.value) Navigation(viewModel)+            if (ready.value) {+                val settings by viewModel.settings.collectAsStateWithLifecycle()+                val darkTheme = when (settings.themeMode) {+                    ThemeMode.LIGHT -> false+                    ThemeMode.DARK -> true+                    else -> null+                }+                DynamicTheme(darkTheme = darkTheme) { Navigation(viewModel) }+            } else {+                DynamicTheme {}             }         }     }@@ -63,6 +82,12 @@ sealed interface Route : NavKey {     @Serializable     data object DeckList : Route +    @Serializable+    data object Stats : Route++    @Serializable+    data object Settings : Route+     @Serializable     data class CardList(val deckId: Long) : Route @@ -76,18 +101,28 @@ sealed interface Route : NavKey { @Composable fun Navigation(viewModel: FlashcardsViewModel) {     val backStack = rememberNavBackStack<Route>(Route.DeckList)-    MainNavigation(backStack) {-        entry<Route.DeckList>(metadata = ListPage()) {-            DeckListPage(backStack, viewModel)-        }-        entry<Route.CardList>(metadata = ListDetailPage()) {-            CardListPage(backStack, viewModel, it.deckId)-        }-        entry<Route.CardEdit>(metadata = ListDetailPage()) {-            CardEditPage(backStack, viewModel, it.deckId, it.cardId)-        }-        entry<Route.Review>(metadata = ListDetailPage()) {-            ReviewPage(backStack, viewModel, it.deckId)-        }+    MainNavigation(+        backStack = backStack,+        bottomBar = {+            val current = backStack.last()+            if (current is Route.DeckList || current is Route.Stats || current is Route.Settings) {+                BottomNavBar(+                    backStack = backStack,+                    pages = listOf(+                        BottomBarItem(stringResource(R.string.nav_decks), Route.DeckList) { IconStyle() },+                        BottomBarItem(stringResource(R.string.nav_stats), Route.Stats) { IconDashboard() },+                        BottomBarItem(stringResource(R.string.nav_settings), Route.Settings) { IconSettings() },+                    ),+                    currentPage = current,+                )+            }+        },+    ) {+        entry<Route.DeckList> { DeckListPage(backStack, viewModel) }+        entry<Route.Stats> { StatsPage(backStack, viewModel) }+        entry<Route.Settings> { SettingsPage(backStack, viewModel) }+        entry<Route.CardList> { CardListPage(backStack, viewModel, it.deckId) }+        entry<Route.CardEdit> { CardEditPage(backStack, viewModel, it.deckId, it.cardId) }+        entry<Route.Review> { ReviewPage(backStack, viewModel, it.deckId) }     } }
flashcards/src/main/java/com/vayunmathur/flashcards/data/Card.kt
diff --git a/flashcards/src/main/java/com/vayunmathur/flashcards/data/Card.kt b/flashcards/src/main/java/com/vayunmathur/flashcards/data/Card.ktindex 2f46424b13..76c1418171 100644--- a/flashcards/src/main/java/com/vayunmathur/flashcards/data/Card.kt+++ b/flashcards/src/main/java/com/vayunmathur/flashcards/data/Card.kt@@ -5,12 +5,24 @@ import androidx.room.PrimaryKey import com.vayunmathur.library.util.ReorderableDatabaseItem import kotlinx.serialization.Serializable +/** FSRS learning states stored in [Card.state]. */+object CardState {+    const val NEW = 0+    const val LEARNING = 1+    const val REVIEW = 2+    const val RELEARNING = 3+}+ /**- * A single plain-text flashcard plus its SM-2 spaced-repetition state.+ * A single flashcard plus its FSRS spaced-repetition memory state.+ *+ * [front]/[back] are treated as **markdown** (rendered via `parseMarkdown`).+ * [dueDate] is epoch millis; `0` means the card is new and always due.  *- * [dueDate] is epoch millis; `0` means the card is new / never studied and is- * therefore always due. [easeFactor], [intervalDays] and [repetitions] are the- * SM-2 bookkeeping updated by `Scheduler.schedule` each time the card is graded.+ * FSRS bookkeeping ([stability], [difficulty], [state], [lastReview], [lapses],+ * [reps]) is updated by `Scheduler.schedule` each time the card is graded. The+ * legacy SM-2 columns ([easeFactor], [intervalDays], [repetitions]) are retained+ * across the v1 -> v2 migration for safety and are otherwise unused.  */ @Serializable @Entity@@ -19,11 +31,21 @@ data class Card(     val deckId: Long,     val front: String,     val back: String,+    val tags: String = "",+    val stability: Double = 0.0,+    val difficulty: Double = 0.0,+    val state: Int = CardState.NEW,+    val lastReview: Long = 0,+    val lapses: Int = 0,+    val reps: Int = 0,+    val dueDate: Long = 0,     val easeFactor: Double = 2.5,     val intervalDays: Int = 0,     val repetitions: Int = 0,-    val dueDate: Long = 0,     override val position: Double = 0.0, ) : ReorderableDatabaseItem<Card> {     override fun withPosition(position: Double) = copy(position = position)++    /** True while the card has never been graded. */+    val isNew: Boolean get() = state == CardState.NEW }
flashcards/src/main/java/com/vayunmathur/flashcards/data/Deck.kt
diff --git a/flashcards/src/main/java/com/vayunmathur/flashcards/data/Deck.kt b/flashcards/src/main/java/com/vayunmathur/flashcards/data/Deck.ktindex bf135abd3b..ee4f8ca7a2 100644--- a/flashcards/src/main/java/com/vayunmathur/flashcards/data/Deck.kt+++ b/flashcards/src/main/java/com/vayunmathur/flashcards/data/Deck.kt@@ -5,11 +5,21 @@ import androidx.room.PrimaryKey import com.vayunmathur.library.util.ReorderableDatabaseItem import kotlinx.serialization.Serializable +/**+ * A deck of [Card]s plus its per-deck study configuration.+ *+ * [newPerDay]/[maxReviewsPerDay] cap how many cards a session introduces, and+ * [desiredRetention] (0..1) is the FSRS target recall probability that drives the+ * scheduled intervals.+ */ @Serializable @Entity data class Deck(     @PrimaryKey(autoGenerate = true) override val id: Long = 0,     val name: String,+    val newPerDay: Int = 20,+    val maxReviewsPerDay: Int = 200,+    val desiredRetention: Double = 0.9,     override val position: Double = 0.0, ) : ReorderableDatabaseItem<Deck> {     override fun withPosition(position: Double) = copy(position = position)
flashcards/src/main/java/com/vayunmathur/flashcards/data/FlashcardsDatabase.kt
diff --git a/flashcards/src/main/java/com/vayunmathur/flashcards/data/FlashcardsDatabase.kt b/flashcards/src/main/java/com/vayunmathur/flashcards/data/FlashcardsDatabase.ktindex dd2e3bdf93..4fbef8d2cf 100644--- a/flashcards/src/main/java/com/vayunmathur/flashcards/data/FlashcardsDatabase.kt+++ b/flashcards/src/main/java/com/vayunmathur/flashcards/data/FlashcardsDatabase.kt@@ -4,12 +4,13 @@ import android.content.Context import androidx.room.Dao import androidx.room.Database import androidx.room.Delete+import androidx.room.Insert import androidx.room.Query import androidx.room.RoomDatabase import androidx.room.Upsert+import androidx.room.migration.Migration import com.vayunmathur.library.util.DatabaseHelper import com.vayunmathur.library.util.DatabaseMigrations-import androidx.room.migration.Migration import kotlinx.coroutines.flow.Flow  const val DB_NAME = "flashcards-db"@@ -23,6 +24,9 @@ interface DeckDao {     @Query("SELECT * FROM Deck")     fun getAllFlow(): Flow<List<Deck>> +    @Query("SELECT * FROM Deck WHERE id = :id")+    suspend fun getById(id: Long): Deck?+     @Upsert     suspend fun upsert(value: Deck): Long @@ -35,9 +39,15 @@ interface CardDao {     @Query("SELECT * FROM Card")     fun getAllFlow(): Flow<List<Card>> +    @Query("SELECT * FROM Card")+    suspend fun getAll(): List<Card>+     @Query("SELECT * FROM Card WHERE deckId = :deckId")     fun getByDeckFlow(deckId: Long): Flow<List<Card>> +    @Query("SELECT * FROM Card WHERE deckId = :deckId")+    suspend fun getByDeck(deckId: Long): List<Card>+     @Query("SELECT * FROM Card WHERE deckId = :deckId AND dueDate <= :now")     fun getDueByDeckFlow(deckId: Long, now: Long): Flow<List<Card>> @@ -47,6 +57,9 @@ interface CardDao {     @Upsert     suspend fun upsert(value: Card): Long +    @Upsert+    suspend fun upsertAll(values: List<Card>)+     @Delete     suspend fun delete(value: Card): Int @@ -54,12 +67,62 @@ interface CardDao {     suspend fun deleteByDeck(deckId: Long) } -@Database(entities = [Deck::class, Card::class], version = 1, exportSchema = false)+@Dao+interface ReviewLogDao {+    @Query("SELECT * FROM ReviewLog")+    fun getAllFlow(): Flow<List<ReviewLog>>++    @Query("SELECT * FROM ReviewLog WHERE deckId = :deckId")+    fun getByDeckFlow(deckId: Long): Flow<List<ReviewLog>>++    @Insert+    suspend fun insert(value: ReviewLog): Long++    @Query("DELETE FROM ReviewLog WHERE id = :id")+    suspend fun deleteById(id: Long)++    @Query("DELETE FROM ReviewLog WHERE deckId = :deckId")+    suspend fun deleteByDeck(deckId: Long)+}++@Database(+    entities = [Deck::class, Card::class, ReviewLog::class],+    version = 2,+    exportSchema = false,+) abstract class FlashcardsDatabase : RoomDatabase() {     abstract fun deckDao(): DeckDao     abstract fun cardDao(): CardDao+    abstract fun reviewLogDao(): ReviewLogDao      companion object : DatabaseMigrations {-        override val migrations = emptyList<Migration>()+        override val migrations = listOf(+            Migration(1, 2) { db ->+                // FSRS + content columns on Card. DEFAULTs populate legacy rows.+                db.execSQL("ALTER TABLE Card ADD COLUMN tags TEXT NOT NULL DEFAULT ''")+                db.execSQL("ALTER TABLE Card ADD COLUMN stability REAL NOT NULL DEFAULT 0")+                db.execSQL("ALTER TABLE Card ADD COLUMN difficulty REAL NOT NULL DEFAULT 0")+                db.execSQL("ALTER TABLE Card ADD COLUMN state INTEGER NOT NULL DEFAULT 0")+                db.execSQL("ALTER TABLE Card ADD COLUMN lastReview INTEGER NOT NULL DEFAULT 0")+                db.execSQL("ALTER TABLE Card ADD COLUMN lapses INTEGER NOT NULL DEFAULT 0")+                db.execSQL("ALTER TABLE Card ADD COLUMN reps INTEGER NOT NULL DEFAULT 0")+                // Per-deck study config.+                db.execSQL("ALTER TABLE Deck ADD COLUMN newPerDay INTEGER NOT NULL DEFAULT 20")+                db.execSQL("ALTER TABLE Deck ADD COLUMN maxReviewsPerDay INTEGER NOT NULL DEFAULT 200")+                db.execSQL("ALTER TABLE Deck ADD COLUMN desiredRetention REAL NOT NULL DEFAULT 0.9")+                // Review history.+                db.execSQL(+                    "CREATE TABLE IF NOT EXISTS ReviewLog (" ++                        "id INTEGER NOT NULL PRIMARY KEY AUTOINCREMENT, " ++                        "cardId INTEGER NOT NULL, " ++                        "deckId INTEGER NOT NULL, " ++                        "reviewedAt INTEGER NOT NULL, " ++                        "grade INTEGER NOT NULL, " ++                        "elapsedDays REAL NOT NULL, " ++                        "scheduledDays REAL NOT NULL, " ++                        "state INTEGER NOT NULL)",+                )+            },+        )     } }
flashcards/src/main/java/com/vayunmathur/flashcards/data/ReviewLog.kt
diff --git a/flashcards/src/main/java/com/vayunmathur/flashcards/data/ReviewLog.kt b/flashcards/src/main/java/com/vayunmathur/flashcards/data/ReviewLog.ktnew file mode 100644index 0000000000..d1cbf60af7--- /dev/null+++ b/flashcards/src/main/java/com/vayunmathur/flashcards/data/ReviewLog.kt@@ -0,0 +1,26 @@+package com.vayunmathur.flashcards.data++import androidx.room.Entity+import androidx.room.PrimaryKey+import kotlinx.serialization.Serializable++/**+ * One row per grade, written whenever a card is reviewed. Powers the statistics+ * screen (review counts, retention, streak) and any future FSRS optimization.+ *+ * [grade] is the 1..4 FSRS grade, [elapsedDays] the time since the previous+ * review, [scheduledDays] the interval assigned by this review, and [state] the+ * card's resulting FSRS state.+ */+@Serializable+@Entity+data class ReviewLog(+    @PrimaryKey(autoGenerate = true) val id: Long = 0,+    val cardId: Long,+    val deckId: Long,+    val reviewedAt: Long,+    val grade: Int,+    val elapsedDays: Double,+    val scheduledDays: Double,+    val state: Int,+)
flashcards/src/main/java/com/vayunmathur/flashcards/ui/CardEditPage.kt
diff --git a/flashcards/src/main/java/com/vayunmathur/flashcards/ui/CardEditPage.kt b/flashcards/src/main/java/com/vayunmathur/flashcards/ui/CardEditPage.ktindex b228102e47..00744a3420 100644--- a/flashcards/src/main/java/com/vayunmathur/flashcards/ui/CardEditPage.kt+++ b/flashcards/src/main/java/com/vayunmathur/flashcards/ui/CardEditPage.kt@@ -9,11 +9,14 @@ import androidx.compose.foundation.verticalScroll import androidx.compose.runtime.Composable import androidx.compose.runtime.LaunchedEffect import androidx.compose.runtime.getValue+import androidx.compose.runtime.mutableIntStateOf import androidx.compose.runtime.mutableStateOf import androidx.compose.runtime.remember import androidx.compose.runtime.setValue import androidx.compose.ui.Modifier import androidx.compose.ui.res.stringResource+import androidx.compose.ui.text.TextRange+import androidx.compose.ui.text.input.TextFieldValue import androidx.compose.ui.unit.dp import androidx.lifecycle.compose.collectAsStateWithLifecycle import com.vayunmathur.flashcards.R@@ -22,20 +25,19 @@ import com.vayunmathur.flashcards.data.Card import com.vayunmathur.flashcards.util.CardEditActions import com.vayunmathur.flashcards.util.CardEditUiState import com.vayunmathur.flashcards.util.FlashcardsViewModel-import com.vayunmathur.library.ui.ExperimentalMaterial3Api+import com.vayunmathur.library.ui.AppScaffold import com.vayunmathur.library.ui.IconButton import com.vayunmathur.library.ui.IconDelete-import com.vayunmathur.library.ui.IconNavigation import com.vayunmathur.library.ui.IconSave+import com.vayunmathur.library.ui.MarkdownEditor+import com.vayunmathur.library.ui.MarkdownFormatToolbar import com.vayunmathur.library.ui.OutlinedTextField-import com.vayunmathur.library.ui.Scaffold import com.vayunmathur.library.ui.Text-import com.vayunmathur.library.ui.TopAppBar import com.vayunmathur.library.util.NavBackStack  /**  * Binds the card with [cardId] (0 for a new card) in [deckId] to the stateless- * [CardEditScreen]: holds the editable front/back text and saves via the ViewModel.+ * [CardEditScreen]: holds the editable markdown/tags and saves via the ViewModel.  */ @Composable fun CardEditPage(@@ -49,11 +51,13 @@ fun CardEditPage(      var frontText by remember { mutableStateOf("") }     var backText by remember { mutableStateOf("") }+    var tagsText by remember { mutableStateOf("") }      LaunchedEffect(dbCard) {         dbCard?.let {             frontText = it.front             backText = it.back+            tagsText = it.tags         }     } @@ -61,9 +65,10 @@ fun CardEditPage(         override fun back() { backStack.pop() }         override fun setFront(front: String) { frontText = front }         override fun setBack(back: String) { backText = back }+        override fun setTags(tags: String) { tagsText = tags }         override fun save() {-            val card = dbCard?.copy(front = frontText, back = backText)-                ?: Card(deckId = deckId, front = frontText, back = backText)+            val card = dbCard?.copy(front = frontText, back = backText, tags = tagsText)+                ?: Card(deckId = deckId, front = frontText, back = backText, tags = tagsText)             viewModel.upsertCard(card)             backStack.pop()         }@@ -74,34 +79,51 @@ fun CardEditPage(     }      CardEditScreen(-        state = CardEditUiState(front = frontText, back = backText, isNew = cardId == 0L),+        state = CardEditUiState(+            front = frontText,+            back = backText,+            tags = tagsText,+            isNew = cardId == 0L,+        ),         actions = actions,     ) }  /**  * The card editor, with no dependency on the ViewModel or the back stack so it can be- * rendered from a `@Preview` — see `src/screenshotTest`. Edits are hoisted through- * [CardEditActions]; a preview supplies [CardEditActions.Noop].+ * rendered from a `@Preview` — see `src/screenshotTest`. Front/back are markdown, edited+ * via [MarkdownEditor] with a shared [MarkdownFormatToolbar] for the focused field.  */-@OptIn(ExperimentalMaterial3Api::class) @Composable fun CardEditScreen(     state: CardEditUiState,     actions: CardEditActions, ) {-    Scaffold(-        topBar = {-            TopAppBar(-                title = {},-                navigationIcon = { IconNavigation { actions.back() } },-                actions = {-                    if (!state.isNew) {-                        IconButton(onClick = { actions.deleteCard() }) { IconDelete() }-                    }-                    IconButton(onClick = { actions.save() }) { IconSave() }-                },-            )+    var front by remember { mutableStateOf(TextFieldValue(state.front)) }+    var back by remember { mutableStateOf(TextFieldValue(state.back)) }+    var activeField by remember { mutableIntStateOf(-1) }++    LaunchedEffect(state.front) {+        if (state.front != front.text) front = TextFieldValue(state.front, TextRange(state.front.length))+    }+    LaunchedEffect(state.back) {+        if (state.back != back.text) back = TextFieldValue(state.back, TextRange(state.back.length))+    }++    AppScaffold(+        title = if (state.isNew) stringResource(R.string.new_card) else stringResource(R.string.edit_card),+        onNavigateBack = { actions.back() },+        actions = {+            if (!state.isNew) {+                IconButton(onClick = { actions.deleteCard() }) { IconDelete() }+            }+            IconButton(onClick = { actions.save() }) { IconSave() }+        },+        bottomBar = {+            when (activeField) {+                0 -> MarkdownFormatToolbar(value = front, onValueChange = { front = it; actions.setFront(it.text) })+                1 -> MarkdownFormatToolbar(value = back, onValueChange = { back = it; actions.setBack(it.text) })+            }         },     ) { paddingValues ->         Column(@@ -111,17 +133,28 @@ fun CardEditScreen(                 .verticalScroll(rememberScrollState())                 .padding(horizontal = 16.dp),         ) {-            OutlinedTextField(-                value = state.front,-                onValueChange = { actions.setFront(it) },-                label = { Text(stringResource(R.string.front)) },-                modifier = Modifier.fillMaxWidth().padding(top = 8.dp),+            Text(stringResource(R.string.front), style = com.vayunmathur.library.ui.MaterialTheme.typography.labelMedium)+            MarkdownEditor(+                value = front,+                onValueChange = { front = it; actions.setFront(it.text) },+                placeholder = stringResource(R.string.front),+                onFocusChanged = { if (it) activeField = 0 },+                modifier = Modifier.fillMaxWidth().padding(top = 4.dp, bottom = 16.dp),+            )+            Text(stringResource(R.string.back), style = com.vayunmathur.library.ui.MaterialTheme.typography.labelMedium)+            MarkdownEditor(+                value = back,+                onValueChange = { back = it; actions.setBack(it.text) },+                placeholder = stringResource(R.string.back),+                onFocusChanged = { if (it) activeField = 1 },+                modifier = Modifier.fillMaxWidth().padding(top = 4.dp, bottom = 16.dp),             )             OutlinedTextField(-                value = state.back,-                onValueChange = { actions.setBack(it) },-                label = { Text(stringResource(R.string.back)) },-                modifier = Modifier.fillMaxWidth().padding(top = 16.dp),+                value = state.tags,+                onValueChange = { actions.setTags(it) },+                label = { Text(stringResource(R.string.tags)) },+                singleLine = true,+                modifier = Modifier.fillMaxWidth().padding(top = 8.dp),             )         }     }
flashcards/src/main/java/com/vayunmathur/flashcards/ui/CardListPage.kt
diff --git a/flashcards/src/main/java/com/vayunmathur/flashcards/ui/CardListPage.kt b/flashcards/src/main/java/com/vayunmathur/flashcards/ui/CardListPage.ktindex 2a9a373324..63825bd126 100644--- a/flashcards/src/main/java/com/vayunmathur/flashcards/ui/CardListPage.kt+++ b/flashcards/src/main/java/com/vayunmathur/flashcards/ui/CardListPage.kt@@ -1,18 +1,32 @@ package com.vayunmathur.flashcards.ui +import android.content.Intent+import androidx.activity.compose.rememberLauncherForActivityResult+import androidx.activity.result.contract.ActivityResultContracts+import androidx.compose.animation.core.animateDpAsState+import androidx.compose.foundation.ExperimentalFoundationApi import androidx.compose.foundation.clickable import androidx.compose.foundation.layout.Column+import androidx.compose.foundation.layout.PaddingValues+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.foundation.lazy.rememberLazyListState import androidx.compose.runtime.Composable+import androidx.compose.runtime.LaunchedEffect import androidx.compose.runtime.getValue+import androidx.compose.runtime.mutableStateOf import androidx.compose.runtime.remember+import androidx.compose.runtime.setValue import androidx.compose.ui.Modifier+import androidx.compose.ui.graphics.graphicsLayer+import androidx.compose.ui.platform.LocalContext import androidx.compose.ui.res.stringResource import androidx.compose.ui.unit.dp+import androidx.compose.ui.zIndex import androidx.lifecycle.compose.collectAsStateWithLifecycle import com.vayunmathur.flashcards.R import com.vayunmathur.flashcards.Route@@ -20,18 +34,25 @@ import com.vayunmathur.flashcards.data.Card import com.vayunmathur.flashcards.util.CardListActions import com.vayunmathur.flashcards.util.CardListUiState import com.vayunmathur.flashcards.util.FlashcardsViewModel+import com.vayunmathur.library.ui.AppScaffold import com.vayunmathur.library.ui.Button-import com.vayunmathur.library.ui.ExperimentalMaterial3Api+import com.vayunmathur.library.ui.CommonSearchBar+import com.vayunmathur.library.ui.EmptyState import com.vayunmathur.library.ui.FloatingActionButton import com.vayunmathur.library.ui.IconAdd import com.vayunmathur.library.ui.IconButton import com.vayunmathur.library.ui.IconDelete-import com.vayunmathur.library.ui.IconNavigation+import com.vayunmathur.library.ui.IconDragHandle+import com.vayunmathur.library.ui.IconShare+import com.vayunmathur.library.ui.IconUpload import com.vayunmathur.library.ui.ListItem-import com.vayunmathur.library.ui.Scaffold+import com.vayunmathur.library.ui.ReorderableItem+import com.vayunmathur.library.ui.Surface import com.vayunmathur.library.ui.Text-import com.vayunmathur.library.ui.TopAppBar+import com.vayunmathur.library.ui.rememberReorderableLazyListState+import com.vayunmathur.library.ui.reorderDragHandle import com.vayunmathur.library.util.NavBackStack+import com.vayunmathur.library.util.parseMarkdown  /** Binds the deck with [deckId] to the stateless [CardListScreen]. */ @Composable@@ -40,6 +61,7 @@ fun CardListPage(     viewModel: FlashcardsViewModel,     deckId: Long, ) {+    val context = LocalContext.current     val decks by viewModel.decks.collectAsStateWithLifecycle()     val cards by remember(deckId) { viewModel.cardsFor(deckId) }         .collectAsStateWithLifecycle(emptyList())@@ -47,6 +69,23 @@ fun CardListPage(     val deckName = decks.firstOrNull { it.id == deckId }?.name ?: ""     val now = System.currentTimeMillis() +    val importLauncher = rememberLauncherForActivityResult(+        ActivityResultContracts.OpenDocument(),+    ) { uri -> uri?.let { viewModel.importCsv(deckId, it) } }++    LaunchedEffect(viewModel, deckId) {+        viewModel.shareRequests.collect { uri ->+            val intent = Intent(Intent.ACTION_SEND).apply {+                type = "application/json"+                putExtra(Intent.EXTRA_STREAM, uri)+                addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION)+            }+            context.startActivity(+                Intent.createChooser(intent, context.getString(R.string.share_deck)),+            )+        }+    }+     val actions = remember(backStack, viewModel, deckId) {         object : CardListActions {             override fun back() { backStack.pop() }@@ -54,16 +93,20 @@ fun CardListPage(             override fun addCard() { backStack.add(Route.CardEdit(deckId, 0)) }             override fun deleteCard(card: Card) { viewModel.deleteCard(card) }             override fun study() { backStack.add(Route.Review(deckId)) }+            override fun reorder(cards: List<Card>) { viewModel.reorderCards(cards) }+            override fun openStats() { backStack.add(Route.Stats) }+            override fun share() { viewModel.exportDeck(deckId) }         }     }      CardListScreen(         state = CardListUiState(             deckName = deckName,-            cards = cards,-            dueCount = cards.count { it.dueDate <= now },+            cards = cards.sortedBy { it.position },+            dueCount = cards.count { (!it.isNew && it.dueDate <= now) || it.isNew },         ),         actions = actions,+        onImport = { importLauncher.launch(arrayOf("text/csv", "text/comma-separated-values", "text/plain")) },     ) } @@ -71,20 +114,32 @@ fun CardListPage(  * The card list for one deck, with no dependency on the ViewModel or the back stack so it  * can be rendered from a `@Preview` — see `src/screenshotTest`.  */-@OptIn(ExperimentalMaterial3Api::class)+@OptIn(ExperimentalFoundationApi::class) @Composable-fun CardListScreen(state: CardListUiState, actions: CardListActions) {-    Scaffold(-        topBar = {-            TopAppBar(-                title = { Text(state.deckName) },-                navigationIcon = { IconNavigation { actions.back() } },-            )+fun CardListScreen(+    state: CardListUiState,+    actions: CardListActions,+    onImport: () -> Unit = {},+) {+    var query by remember { mutableStateOf("") }+    val filtered = if (query.isBlank()) {+        state.cards+    } else {+        state.cards.filter {+            it.front.contains(query, true) || it.back.contains(query, true) ||+                it.tags.contains(query, true)+        }+    }++    AppScaffold(+        title = state.deckName,+        onNavigateBack = { actions.back() },+        actions = {+            IconButton(onClick = onImport) { IconUpload() }+            IconButton(onClick = { actions.share() }) { IconShare() }         },         floatingActionButton = {-            FloatingActionButton(onClick = { actions.addCard() }) {-                IconAdd()-            }+            FloatingActionButton(onClick = { actions.addCard() }) { IconAdd() }         },     ) { paddingValues ->         Column(Modifier.fillMaxSize().padding(paddingValues)) {@@ -96,29 +151,97 @@ fun CardListScreen(state: CardListUiState, actions: CardListActions) {                     Text(stringResource(R.string.study))                 }             }-            if (state.cards.isEmpty()) {-                Text(-                    stringResource(R.string.no_cards),-                    modifier = Modifier.fillMaxWidth().padding(32.dp),+            if (state.cards.isNotEmpty()) {+                CommonSearchBar(+                    value = query,+                    onValueChange = { query = it },+                    placeholder = stringResource(R.string.search_cards),+                    padding = PaddingValues(horizontal = 16.dp, vertical = 4.dp),                 )-            } else {-                LazyColumn(Modifier.fillMaxSize()) {-                    items(state.cards, key = { it.id }) { card ->-                        ListItem(-                            headlineContent = { Text(card.front.substringBefore('\n').take(60)) },-                            supportingContent = {-                                Text(card.back.substringBefore('\n').take(60))-                            },-                            trailingContent = {-                                IconButton(onClick = { actions.deleteCard(card) }) {-                                    IconDelete()-                                }-                            },-                            modifier = Modifier.clickable { actions.openCard(card.id) },-                        )+            }+            when {+                state.cards.isEmpty() -> EmptyState(+                    title = stringResource(R.string.no_cards),+                    message = stringResource(R.string.no_cards_hint),+                    icon = { IconAdd() },+                    modifier = Modifier.fillMaxSize(),+                )+                query.isBlank() -> ReorderableCardList(filtered, actions)+                else -> LazyColumn(Modifier.fillMaxSize()) {+                    items(filtered, key = { it.id }) { card ->+                        CardRow(card, onOpen = { actions.openCard(card.id) }, onDelete = { actions.deleteCard(card) })                     }                 }             }         }     } }++@OptIn(ExperimentalFoundationApi::class)+@Composable+private fun ReorderableCardList(cards: List<Card>, actions: CardListActions) {+    val listState = rememberLazyListState()+    var local by remember { mutableStateOf(cards) }+    var hasDragged by remember { mutableStateOf(false) }+    val reorderState = rememberReorderableLazyListState(listState) { from, to ->+        if (from.index in local.indices && to.index in local.indices) {+            local = local.toMutableList().apply { add(to.index, removeAt(from.index)) }+            hasDragged = true+        }+    }+    LaunchedEffect(cards) { if (!reorderState.isAnyItemDragging) local = cards }+    LaunchedEffect(reorderState.isAnyItemDragging) {+        if (!reorderState.isAnyItemDragging && hasDragged) {+            actions.reorder(local.mapIndexed { index, c -> c.withPosition(index.toDouble()) })+            hasDragged = false+        }+    }++    LazyColumn(state = listState, modifier = Modifier.fillMaxSize()) {+        items(local, key = { it.id }) { card ->+            val dragging = reorderState.draggingKey == card.id+            val itemModifier = if (dragging) {+                Modifier.zIndex(1f).graphicsLayer { translationY = reorderState.draggingItemTranslation }+            } else {+                Modifier.animateItem()+            }+            ReorderableItem(reorderState, key = card.id, modifier = itemModifier) { isDragging ->+                val elevation by animateDpAsState(if (isDragging) 8.dp else 0.dp, label = "cardElevation")+                Surface(shadowElevation = elevation) {+                    CardRow(+                        card = card,+                        onOpen = { actions.openCard(card.id) },+                        onDelete = { actions.deleteCard(card) },+                        dragHandle = Modifier.reorderDragHandle(reorderState, key = card.id),+                    )+                }+            }+        }+    }+}++@Composable+private fun CardRow(+    card: Card,+    onOpen: () -> Unit,+    onDelete: () -> Unit,+    dragHandle: Modifier? = null,+) {+    ListItem(+        headlineContent = {+            Text(parseMarkdown(card.front.substringBefore('\n').take(60), showMarkers = false))+        },+        supportingContent = {+            Text(parseMarkdown(card.back.substringBefore('\n').take(60), showMarkers = false))+        },+        trailingContent = {+            Row {+                IconButton(onClick = onDelete) { IconDelete() }+                if (dragHandle != null) {+                    IconButton(onClick = {}, modifier = dragHandle) { IconDragHandle() }+                }+            }+        },+        modifier = Modifier.clickable { onOpen() },+    )+}
flashcards/src/main/java/com/vayunmathur/flashcards/ui/DeckListPage.kt
diff --git a/flashcards/src/main/java/com/vayunmathur/flashcards/ui/DeckListPage.kt b/flashcards/src/main/java/com/vayunmathur/flashcards/ui/DeckListPage.ktindex 3d7bd3cfb9..d0880aee74 100644--- a/flashcards/src/main/java/com/vayunmathur/flashcards/ui/DeckListPage.kt+++ b/flashcards/src/main/java/com/vayunmathur/flashcards/ui/DeckListPage.kt@@ -1,23 +1,30 @@ package com.vayunmathur.flashcards.ui  import androidx.activity.compose.BackHandler+import androidx.compose.animation.core.animateDpAsState import androidx.compose.foundation.ExperimentalFoundationApi import androidx.compose.foundation.combinedClickable import androidx.compose.foundation.layout.RowScope+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.layout.size import androidx.compose.foundation.lazy.LazyColumn import androidx.compose.foundation.lazy.items+import androidx.compose.foundation.lazy.rememberLazyListState import androidx.compose.runtime.Composable+import androidx.compose.runtime.LaunchedEffect import androidx.compose.runtime.getValue import androidx.compose.runtime.mutableStateOf import androidx.compose.runtime.remember import androidx.compose.runtime.setValue import androidx.compose.ui.Modifier+import androidx.compose.ui.graphics.graphicsLayer import androidx.compose.ui.platform.LocalContext import androidx.compose.ui.res.stringResource import androidx.compose.ui.unit.dp+import androidx.compose.ui.zIndex import androidx.lifecycle.compose.collectAsStateWithLifecycle import com.vayunmathur.flashcards.R import com.vayunmathur.flashcards.Route@@ -29,20 +36,26 @@ import com.vayunmathur.flashcards.util.DeckSummary import com.vayunmathur.flashcards.util.FlashcardsViewModel import com.vayunmathur.library.room.SqlCipherDbCodec import com.vayunmathur.library.ui.AlertDialog+import com.vayunmathur.library.ui.AppScaffold import com.vayunmathur.library.ui.BackupButtons import com.vayunmathur.library.ui.ConfirmDialog-import com.vayunmathur.library.ui.ExperimentalMaterial3Api+import com.vayunmathur.library.ui.EmptyState import com.vayunmathur.library.ui.FloatingActionButton import com.vayunmathur.library.ui.IconAdd import com.vayunmathur.library.ui.IconButton+import com.vayunmathur.library.ui.IconDragHandle import com.vayunmathur.library.ui.IconPlay+import com.vayunmathur.library.ui.IconStyle import com.vayunmathur.library.ui.ListItem-import com.vayunmathur.library.ui.Scaffold+import com.vayunmathur.library.ui.ReorderableItem+import com.vayunmathur.library.ui.Surface import com.vayunmathur.library.ui.Text import com.vayunmathur.library.ui.TextButton import com.vayunmathur.library.ui.TextField-import com.vayunmathur.library.ui.TopAppBar+import com.vayunmathur.library.ui.rememberReorderableLazyListState+import com.vayunmathur.library.ui.reorderDragHandle import com.vayunmathur.library.util.NavBackStack+import kotlin.math.roundToInt  /** Binds [FlashcardsViewModel] and the nav back stack to the stateless [DeckListScreen]. */ @Composable@@ -52,21 +65,24 @@ fun DeckListPage(backStack: NavBackStack<Route>, viewModel: FlashcardsViewModel)     val cards by viewModel.cards.collectAsStateWithLifecycle()      val now = System.currentTimeMillis()-    val summaries = decks.map { deck ->+    val summaries = decks.sortedBy { it.position }.map { deck ->         val deckCards = cards.filter { it.deckId == deck.id }         DeckSummary(             deck = deck,-            dueCount = deckCards.count { it.dueDate <= now },+            dueCount = deckCards.count { !it.isNew && it.dueDate <= now },+            newCount = deckCards.count { it.isNew },             totalCount = deckCards.size,+            mastery = FlashcardsViewModel.mastery(deckCards),         )     }      val actions = remember(backStack, viewModel) {         object : DeckListActions {             override fun openDeck(id: Long) { backStack.add(Route.CardList(id)) }-            override fun addDeck(name: String) { viewModel.upsertDeck(Deck(name = name)) }+            override fun addDeck(name: String) { viewModel.addDeck(name) }             override fun deleteDeck(deck: Deck) { viewModel.deleteDeck(deck) }             override fun startReview(deckId: Long) { backStack.add(Route.Review(deckId)) }+            override fun reorder(decks: List<Deck>) { viewModel.reorderDecks(decks) }         }     } @@ -88,7 +104,7 @@ fun DeckListPage(backStack: NavBackStack<Route>, viewModel: FlashcardsViewModel)  * rendered from a `@Preview` — see `src/screenshotTest`, which is where the store listing  * images come from.  */-@OptIn(ExperimentalMaterial3Api::class, ExperimentalFoundationApi::class)+@OptIn(ExperimentalFoundationApi::class) @Composable fun DeckListScreen(     state: DeckListUiState,@@ -99,47 +115,65 @@ fun DeckListScreen(     var showAddDialog by remember { mutableStateOf(false) }     var pendingDelete by remember { mutableStateOf<Deck?>(null) } -    Scaffold(-        topBar = {-            TopAppBar(-                title = { Text(stringResource(R.string.app_name)) },-                actions = backupButtons,-            )-        },+    val listState = rememberLazyListState()+    var localDecks by remember { mutableStateOf(state.decks) }+    var hasDragged by remember { mutableStateOf(false) }+    val reorderState = rememberReorderableLazyListState(listState) { from, to ->+        if (from.index in localDecks.indices && to.index in localDecks.indices) {+            localDecks = localDecks.toMutableList().apply { add(to.index, removeAt(from.index)) }+            hasDragged = true+        }+    }+    LaunchedEffect(state.decks) {+        if (!reorderState.isAnyItemDragging) localDecks = state.decks+    }+    LaunchedEffect(reorderState.isAnyItemDragging) {+        if (!reorderState.isAnyItemDragging && hasDragged) {+            actions.reorder(localDecks.mapIndexed { index, s -> s.deck.withPosition(index.toDouble()) })+            hasDragged = false+        }+    }++    AppScaffold(+        title = stringResource(R.string.app_name),+        actions = backupButtons,         floatingActionButton = {-            FloatingActionButton(onClick = { showAddDialog = true }) {-                IconAdd()-            }+            FloatingActionButton(onClick = { showAddDialog = true }) { IconAdd() }         },     ) { paddingValues ->+        if (localDecks.isEmpty()) {+            EmptyState(+                title = stringResource(R.string.no_decks),+                message = stringResource(R.string.no_decks_hint),+                icon = { IconStyle() },+                modifier = Modifier.fillMaxSize().padding(paddingValues),+            )+            return@AppScaffold+        }         LazyColumn(+            state = listState,             modifier = Modifier.fillMaxSize(),             contentPadding = paddingValues,         ) {-            items(state.decks, key = { it.deck.id }) { summary ->-                ListItem(-                    headlineContent = { Text(summary.deck.name) },-                    supportingContent = {-                        Text(-                            stringResource(-                                R.string.deck_summary,-                                summary.dueCount,-                                summary.totalCount,-                            ),+            items(localDecks, key = { it.deck.id }) { summary ->+                val dragging = reorderState.draggingKey == summary.deck.id+                val itemModifier = if (dragging) {+                    Modifier.zIndex(1f).graphicsLayer { translationY = reorderState.draggingItemTranslation }+                } else {+                    Modifier.animateItem()+                }+                ReorderableItem(reorderState, key = summary.deck.id, modifier = itemModifier) { isDragging ->+                    val elevation by animateDpAsState(if (isDragging) 8.dp else 0.dp, label = "deckElevation")+                    Surface(shadowElevation = elevation) {+                        DeckRow(+                            summary = summary,+                            onOpen = { actions.openDeck(summary.deck.id) },+                            onLongPress = { pendingDelete = summary.deck },+                            onReview = { actions.startReview(summary.deck.id) },+                            dragHandle = Modifier.reorderDragHandle(reorderState, key = summary.deck.id),                         )-                    },-                    trailingContent = {-                        if (summary.dueCount > 0) {-                            IconButton(onClick = { actions.startReview(summary.deck.id) }) {-                                IconPlay()-                            }-                        }-                    },-                    modifier = Modifier.combinedClickable(-                        onClick = { actions.openDeck(summary.deck.id) },-                        onLongClick = { pendingDelete = summary.deck },-                    ),-                )+                    }+                }             }         }     }@@ -167,7 +201,47 @@ fun DeckListScreen(     } } -@OptIn(ExperimentalMaterial3Api::class)+@OptIn(ExperimentalFoundationApi::class)+@Composable+private fun DeckRow(+    summary: DeckSummary,+    onOpen: () -> Unit,+    onLongPress: () -> Unit,+    onReview: () -> Unit,+    dragHandle: Modifier,+) {+    ListItem(+        leadingContent = {+            MetricRing(+                progress = summary.mastery,+                label = "",+                value = "${(summary.mastery * 100).roundToInt()}%",+                modifier = Modifier.size(48.dp),+            )+        },+        headlineContent = { Text(summary.deck.name) },+        supportingContent = {+            Text(+                stringResource(+                    R.string.deck_summary,+                    summary.dueCount,+                    summary.newCount,+                    summary.totalCount,+                ),+            )+        },+        trailingContent = {+            Row {+                if (summary.dueCount > 0 || summary.newCount > 0) {+                    IconButton(onClick = onReview) { IconPlay() }+                }+                IconButton(onClick = {}, modifier = dragHandle) { IconDragHandle() }+            }+        },+        modifier = Modifier.combinedClickable(onClick = onOpen, onLongClick = onLongPress),+    )+}+ @Composable private fun AddDeckDialog(onAdd: (String) -> Unit, onDismiss: () -> Unit) {     var name by remember { mutableStateOf("") }
flashcards/src/main/java/com/vayunmathur/flashcards/ui/FlashcardsCharts.kt
diff --git a/flashcards/src/main/java/com/vayunmathur/flashcards/ui/FlashcardsCharts.kt b/flashcards/src/main/java/com/vayunmathur/flashcards/ui/FlashcardsCharts.ktnew file mode 100644index 0000000000..55c0dec4bb--- /dev/null+++ b/flashcards/src/main/java/com/vayunmathur/flashcards/ui/FlashcardsCharts.kt@@ -0,0 +1,273 @@+package com.vayunmathur.flashcards.ui++import androidx.compose.foundation.Canvas+import androidx.compose.foundation.gestures.detectTapGestures+import androidx.compose.foundation.layout.Box+import androidx.compose.foundation.layout.BoxScope+import androidx.compose.foundation.layout.BoxWithConstraints+import androidx.compose.foundation.layout.Column+import androidx.compose.foundation.layout.fillMaxSize+import androidx.compose.foundation.layout.fillMaxWidth+import androidx.compose.foundation.layout.height+import androidx.compose.foundation.layout.offset+import androidx.compose.foundation.layout.padding+import androidx.compose.foundation.layout.width+import androidx.compose.runtime.Composable+import androidx.compose.runtime.getValue+import androidx.compose.runtime.mutableIntStateOf+import androidx.compose.runtime.remember+import androidx.compose.runtime.setValue+import androidx.compose.ui.Alignment+import androidx.compose.ui.Modifier+import androidx.compose.ui.geometry.CornerRadius+import androidx.compose.ui.geometry.Offset+import androidx.compose.ui.geometry.Size+import androidx.compose.ui.graphics.Color+import androidx.compose.ui.graphics.StrokeCap+import androidx.compose.ui.graphics.drawscope.DrawScope+import androidx.compose.ui.graphics.drawscope.Stroke+import androidx.compose.ui.input.pointer.pointerInput+import androidx.compose.ui.layout.layout+import androidx.compose.ui.platform.LocalDensity+import androidx.compose.ui.text.font.FontWeight+import androidx.compose.ui.unit.Density+import androidx.compose.ui.unit.Dp+import androidx.compose.ui.unit.dp+import androidx.compose.ui.unit.sp+import com.vayunmathur.library.ui.LocalContentColor+import com.vayunmathur.library.ui.MaterialTheme+import com.vayunmathur.library.ui.Text++/**+ * A single progress ring with a label + value stacked inside. Adapted from+ * `health`'s `MetricRing`. Arc starts at the top and sweeps `360 * progress`.+ */+@Composable+fun MetricRing(+    progress: Float,+    label: String,+    value: String,+    modifier: Modifier = Modifier,+    color: Color = MaterialTheme.colorScheme.primary,+    strokeWidth: Dp = 8.dp,+) {+    val trackColor = color.copy(alpha = 0.18f)+    val clamped = progress.coerceIn(0f, 1f)+    Box(modifier = modifier, contentAlignment = Alignment.Center) {+        Canvas(modifier = Modifier.fillMaxSize()) {+            val stroke = Stroke(width = strokeWidth.toPx(), cap = StrokeCap.Round)+            val inset = strokeWidth.toPx() / 2f+            val arcSize = Size(size.width - inset * 2f, size.height - inset * 2f)+            val topLeft = Offset(inset, inset)+            drawArc(+                color = trackColor,+                startAngle = 0f,+                sweepAngle = 360f,+                useCenter = false,+                topLeft = topLeft,+                size = arcSize,+                style = stroke,+            )+            drawArc(+                color = color,+                startAngle = -90f,+                sweepAngle = 360f * clamped,+                useCenter = false,+                topLeft = topLeft,+                size = arcSize,+                style = stroke,+            )+        }+        Column(horizontalAlignment = Alignment.CenterHorizontally) {+            if (value.isNotEmpty()) {+                Text(+                    text = value,+                    style = MaterialTheme.typography.titleSmall,+                    color = MaterialTheme.colorScheme.onSurface,+                    fontWeight = FontWeight.SemiBold,+                )+            }+            if (label.isNotEmpty()) {+                Text(+                    text = label,+                    style = MaterialTheme.typography.labelSmall,+                    color = MaterialTheme.colorScheme.onSurfaceVariant,+                )+            }+        }+    }+}++/**+ * A simple bar chart of `(label, value)` pairs. Adapted from `health`'s+ * `GenericBarChart`, trimmed to what the stats screen needs: tap a bar to see its+ * value, decimated X labels, and a max/0 Y axis.+ */+@Composable+fun ReviewBarChart(+    data: List<Pair<String, Double>>,+    modifier: Modifier = Modifier,+    barColor: Color = MaterialTheme.colorScheme.primary,+) {+    val maxValue = (data.maxOfOrNull { it.second } ?: 0.0).coerceAtLeast(1.0)+    val labelColor = LocalContentColor.current.copy(alpha = 0.6f)+    var selectedIndex by remember(data) { mutableIntStateOf(-1) }++    val chartHeight = 180.dp+    val xAxisHeight = 22.dp+    val sideLabelWidth = 36.dp+    val tooltipHeight = 20.dp++    BoxWithConstraints(+        modifier = modifier+            .fillMaxWidth()+            .height(chartHeight + tooltipHeight),+    ) {+        val density = LocalDensity.current+        val fullWidthPx = with(density) { maxWidth.toPx() }+        val sideLabelWidthPx = with(density) { sideLabelWidth.toPx() }+        val chartWidthPx = fullWidthPx - sideLabelWidthPx+        val count = data.size.coerceAtLeast(1)+        val barWidth = (chartWidthPx / count * 0.6f).coerceIn(2f, with(density) { 16.dp.toPx() })+        val spacing = (chartWidthPx - count * barWidth) / (count + 1)++        if (selectedIndex in data.indices) {+            val pair = data[selectedIndex]+            val barCenterX = spacing + selectedIndex * (barWidth + spacing) + barWidth / 2+            Text(+                text = pair.second.toLong().toString(),+                color = barColor,+                fontSize = 11.sp,+                fontWeight = FontWeight.SemiBold,+                modifier = Modifier+                    .align(Alignment.TopStart)+                    .offset(x = with(density) { barCenterX.toDp() })+                    .layout { measurable, constraints ->+                        val placeable = measurable.measure(constraints)+                        layout(placeable.width, placeable.height) {+                            placeable.placeRelative(-(placeable.width / 2), 0)+                        }+                    },+            )+        }++        Canvas(+            modifier = Modifier+                .fillMaxWidth()+                .height(chartHeight)+                .align(Alignment.BottomStart)+                .padding(end = sideLabelWidth, bottom = xAxisHeight)+                .pointerInput(data) {+                    detectTapGestures { offset ->+                        val matched = data.indices.firstOrNull { idx ->+                            val left = spacing + idx * (barWidth + spacing)+                            offset.x >= left - spacing / 2 && offset.x <= left + barWidth + spacing / 2+                        } ?: -1+                        selectedIndex = if (matched == selectedIndex) -1 else matched+                    }+                },+        ) {+            gridLines(labelColor)+            data.forEachIndexed { index, pair ->+                val barHeight = (pair.second.toFloat() / maxValue.toFloat() * size.height)+                    .coerceIn(if (pair.second > 0) 3f else 0f, size.height)+                val x = spacing + index * (barWidth + spacing)+                val y = size.height - barHeight+                val drawColor = if (selectedIndex < 0 || selectedIndex == index) {+                    barColor+                } else {+                    barColor.copy(alpha = 0.5f)+                }+                drawRoundRect(+                    color = drawColor,+                    topLeft = Offset(x, y),+                    size = Size(barWidth, barHeight),+                    cornerRadius = CornerRadius(2.dp.toPx(), 2.dp.toPx()),+                )+            }+        }++        xAxisLabels(+            labels = data.map { it.first },+            color = labelColor,+            density = density,+        ) { index -> spacing + index * (barWidth + spacing) + barWidth / 2 }++        val actualChartHeightPx = with(density) { (chartHeight - xAxisHeight).toPx() }+        val topOffsetPx = with(density) { tooltipHeight.toPx() }+        yAxisLabel(maxValue.toLong().toString(), labelColor, sideLabelWidth, topOffsetPx, density)+        yAxisLabel("0", labelColor, sideLabelWidth, topOffsetPx + actualChartHeightPx, density)+    }+}++private fun DrawScope.gridLines(color: Color) {+    listOf(0.25f, 0.5f, 0.75f, 1f).forEach { frac ->+        drawLine(+            color = color.copy(alpha = 0.10f),+            start = Offset(0f, size.height * (1f - frac)),+            end = Offset(size.width, size.height * (1f - frac)),+            strokeWidth = 1.dp.toPx(),+        )+    }+}++private fun decimationStep(count: Int): Int = when {+    count <= 8 -> 1+    count <= 16 -> 2+    count <= 24 -> 3+    else -> count / 6+}++@Composable+private fun BoxScope.xAxisLabels(+    labels: List<String>,+    color: Color,+    density: Density,+    xForIndex: (Int) -> Float,+) {+    val step = decimationStep(labels.size).coerceAtLeast(1)+    labels.forEachIndexed { index, label ->+        if (label.isNotEmpty() && index % step == 0) {+            Text(+                text = label,+                color = color,+                fontSize = 10.sp,+                modifier = Modifier+                    .align(Alignment.BottomStart)+                    .offset(x = with(density) { xForIndex(index).toDp() })+                    .layout { measurable, constraints ->+                        val placeable = measurable.measure(constraints)+                        layout(placeable.width, placeable.height) {+                            placeable.placeRelative(-(placeable.width / 2), 0)+                        }+                    },+            )+        }+    }+}++@Composable+private fun BoxScope.yAxisLabel(+    text: String,+    color: Color,+    sideLabelWidth: Dp,+    yPx: Float,+    density: Density,+) {+    Text(+        text = text,+        color = color,+        fontSize = 10.sp,+        modifier = Modifier+            .align(Alignment.TopEnd)+            .width(sideLabelWidth)+            .offset(y = with(density) { yPx.toDp() })+            .layout { measurable, constraints ->+                val placeable = measurable.measure(constraints)+                layout(placeable.width, placeable.height) {+                    placeable.placeRelative(0, -(placeable.height / 2))+                }+            }+            .padding(start = 4.dp),+    )+}
flashcards/src/main/java/com/vayunmathur/flashcards/ui/ReviewPage.kt
diff --git a/flashcards/src/main/java/com/vayunmathur/flashcards/ui/ReviewPage.kt b/flashcards/src/main/java/com/vayunmathur/flashcards/ui/ReviewPage.ktindex c9d2b5d472..ef3fa7da01 100644--- a/flashcards/src/main/java/com/vayunmathur/flashcards/ui/ReviewPage.kt+++ b/flashcards/src/main/java/com/vayunmathur/flashcards/ui/ReviewPage.kt@@ -1,5 +1,8 @@ package com.vayunmathur.flashcards.ui +import androidx.compose.animation.core.animateFloatAsState+import androidx.compose.animation.core.tween+import androidx.compose.foundation.clickable import androidx.compose.foundation.layout.Arrangement import androidx.compose.foundation.layout.Box import androidx.compose.foundation.layout.Column@@ -17,6 +20,8 @@ import androidx.compose.runtime.remember import androidx.compose.runtime.setValue import androidx.compose.ui.Alignment import androidx.compose.ui.Modifier+import androidx.compose.ui.graphics.Color+import androidx.compose.ui.graphics.graphicsLayer import androidx.compose.ui.res.stringResource import androidx.compose.ui.text.style.TextAlign import androidx.compose.ui.unit.dp@@ -27,45 +32,35 @@ import com.vayunmathur.flashcards.util.FlashcardsViewModel import com.vayunmathur.flashcards.util.Grade import com.vayunmathur.flashcards.util.ReviewActions import com.vayunmathur.flashcards.util.ReviewUiState+import com.vayunmathur.library.ui.AppScaffold import com.vayunmathur.library.ui.Button-import com.vayunmathur.library.ui.ExperimentalMaterial3Api+import com.vayunmathur.library.ui.ButtonDefaults+import com.vayunmathur.library.ui.EmptyState import com.vayunmathur.library.ui.HorizontalDivider-import com.vayunmathur.library.ui.IconNavigation+import com.vayunmathur.library.ui.IconButton+import com.vayunmathur.library.ui.IconUndo+import com.vayunmathur.library.ui.LinearProgressIndicator import com.vayunmathur.library.ui.MaterialTheme-import com.vayunmathur.library.ui.OutlinedButton-import com.vayunmathur.library.ui.Scaffold import com.vayunmathur.library.ui.Text-import com.vayunmathur.library.ui.TopAppBar import com.vayunmathur.library.util.NavBackStack+import com.vayunmathur.library.util.parseMarkdown -/**- * Binds a review session over the due cards of [deckId] to the stateless [ReviewScreen].- * The due-cards flow uses a fixed `now` cutoff, so grading a card advances its due date- * past the cutoff and it drops out of the queue, revealing the next card.- */+/** Binds an in-memory review session over [deckId] to the stateless [ReviewScreen]. */ @Composable fun ReviewPage(     backStack: NavBackStack<Route>,     viewModel: FlashcardsViewModel,     deckId: Long, ) {-    val due by remember(deckId) { viewModel.dueCardsFor(deckId) }-        .collectAsStateWithLifecycle(emptyList())--    val current = due.firstOrNull()+    LaunchedEffect(deckId) { viewModel.startSession(deckId) }+    val state by viewModel.review.collectAsStateWithLifecycle()      ReviewScreen(-        state = ReviewUiState(-            front = current?.front ?: "",-            back = current?.back ?: "",-            remaining = due.size,-            done = current == null,-        ),+        state = state,         actions = object : ReviewActions {             override fun back() { backStack.pop() }-            override fun grade(grade: Grade) {-                current?.let { viewModel.gradeCard(it, grade) }-            }+            override fun grade(grade: Grade) { viewModel.gradeCurrent(grade) }+            override fun undo() { viewModel.undoReview() }         },     ) }@@ -75,7 +70,6 @@ fun ReviewPage(  * rendered from a `@Preview` — see `src/screenshotTest`. [initialRevealed] seeds the  * answer-visible state so a preview can capture the graded state without tapping.  */-@OptIn(ExperimentalMaterial3Api::class) @Composable fun ReviewScreen(     state: ReviewUiState,@@ -83,90 +77,162 @@ fun ReviewScreen(     initialRevealed: Boolean = false, ) {     var revealed by remember { mutableStateOf(initialRevealed) }-    // Reset to the question side whenever a new card comes up.     LaunchedEffect(state.front, state.done) { revealed = initialRevealed } -    Scaffold(-        topBar = {-            TopAppBar(-                title = { if (!state.done) Text(state.remaining.toString()) },-                navigationIcon = { IconNavigation { actions.back() } },-            )-        },-    ) { paddingValues ->-        if (state.done) {-            Box(-                Modifier.fillMaxSize().padding(paddingValues),-                contentAlignment = Alignment.Center,-            ) {+    AppScaffold(+        title = {+            if (!state.done) {                 Text(-                    stringResource(R.string.review_done),-                    style = MaterialTheme.typography.headlineSmall,+                    stringResource(+                        R.string.review_counts,+                        state.newCount,+                        state.learningCount,+                        state.reviewCount,+                    ),+                    style = MaterialTheme.typography.titleMedium,                 )             }-            return@Scaffold+        },+        onNavigateBack = { actions.back() },+        actions = {+            if (state.canUndo) {+                IconButton(onClick = { actions.undo() }) { IconUndo() }+            }+        },+    ) { paddingValues ->+        if (state.done) {+            EmptyState(+                title = stringResource(R.string.review_done),+                message = stringResource(R.string.review_done_hint),+                modifier = Modifier.fillMaxSize().padding(paddingValues),+            )+            return@AppScaffold         }          Column(Modifier.fillMaxSize().padding(paddingValues)) {-            Column(-                Modifier-                    .weight(1f)-                    .fillMaxWidth()-                    .verticalScroll(rememberScrollState())-                    .padding(24.dp),-                horizontalAlignment = Alignment.CenterHorizontally,-                verticalArrangement = Arrangement.Center,-            ) {+            LinearProgressIndicator(+                progress = { state.progress },+                modifier = Modifier.fillMaxWidth(),+            )+            FlipCard(+                front = state.front,+                back = state.back,+                revealed = revealed,+                modifier = Modifier.weight(1f).fillMaxWidth().clickable { revealed = true },+            )+            if (revealed) {+                GradeButtons(state = state, onGrade = { actions.grade(it) })+            } else {+                Button(+                    onClick = { revealed = true },+                    modifier = Modifier.fillMaxWidth().padding(16.dp),+                ) {+                    Text(stringResource(R.string.show_answer))+                }+            }+        }+    }+}++@Composable+private fun FlipCard(+    front: String,+    back: String,+    revealed: Boolean,+    modifier: Modifier = Modifier,+) {+    val rotation by animateFloatAsState(+        targetValue = if (revealed) 180f else 0f,+        animationSpec = tween(durationMillis = 400),+        label = "flip",+    )+    Box(+        modifier = modifier.graphicsLayer {+            rotationY = rotation+            cameraDistance = 12f * density+        },+        contentAlignment = Alignment.Center,+    ) {+        if (rotation <= 90f) {+            CardFace {                 Text(-                    state.front,+                    parseMarkdown(front, showMarkers = false),                     style = MaterialTheme.typography.headlineSmall,                     textAlign = TextAlign.Center,                 )-                if (revealed) {-                    HorizontalDivider(Modifier.padding(vertical = 24.dp))+            }+        } else {+            // Counter-rotate so the back face reads correctly.+            Box(Modifier.graphicsLayer { rotationY = 180f }) {+                CardFace {                     Text(-                        state.back,+                        parseMarkdown(front, showMarkers = false),+                        style = MaterialTheme.typography.titleMedium,+                        textAlign = TextAlign.Center,+                    )+                    HorizontalDivider(Modifier.padding(vertical = 20.dp))+                    Text(+                        parseMarkdown(back, showMarkers = false),                         style = MaterialTheme.typography.bodyLarge,                         textAlign = TextAlign.Center,                     )                 }             }--            if (revealed) {-                GradeButtons(onGrade = { actions.grade(it) })-            } else {-                Button(-                    onClick = { revealed = true },-                    modifier = Modifier.fillMaxWidth().padding(16.dp),-                ) {-                    Text(stringResource(R.string.show_answer))-                }-            }         }     } }  @Composable-private fun GradeButtons(onGrade: (Grade) -> Unit) {+private fun CardFace(content: @Composable () -> Unit) {+    Column(+        Modifier+            .fillMaxSize()+            .verticalScroll(rememberScrollState())+            .padding(24.dp),+        horizontalAlignment = Alignment.CenterHorizontally,+        verticalArrangement = Arrangement.Center,+    ) {+        content()+    }+}++@Composable+private fun GradeButtons(state: ReviewUiState, onGrade: (Grade) -> Unit) {     Row(         Modifier.fillMaxWidth().padding(horizontal = 8.dp, vertical = 16.dp),         horizontalArrangement = Arrangement.spacedBy(8.dp),     ) {-        GradeButton(R.string.grade_again, Grade.AGAIN, onGrade, Modifier.weight(1f))-        GradeButton(R.string.grade_hard, Grade.HARD, onGrade, Modifier.weight(1f))-        GradeButton(R.string.grade_good, Grade.GOOD, onGrade, Modifier.weight(1f))-        GradeButton(R.string.grade_easy, Grade.EASY, onGrade, Modifier.weight(1f))+        GradeButton(R.string.grade_again, GRADE_AGAIN_COLOR, state.label(Grade.AGAIN), Grade.AGAIN, onGrade, Modifier.weight(1f))+        GradeButton(R.string.grade_hard, GRADE_HARD_COLOR, state.label(Grade.HARD), Grade.HARD, onGrade, Modifier.weight(1f))+        GradeButton(R.string.grade_good, GRADE_GOOD_COLOR, state.label(Grade.GOOD), Grade.GOOD, onGrade, Modifier.weight(1f))+        GradeButton(R.string.grade_easy, GRADE_EASY_COLOR, state.label(Grade.EASY), Grade.EASY, onGrade, Modifier.weight(1f))     } }  @Composable private fun GradeButton(     labelRes: Int,+    color: Color,+    interval: String,     grade: Grade,     onGrade: (Grade) -> Unit,     modifier: Modifier = Modifier, ) {-    OutlinedButton(onClick = { onGrade(grade) }, modifier = modifier) {-        Text(stringResource(labelRes))+    Button(+        onClick = { onGrade(grade) },+        modifier = modifier,+        colors = ButtonDefaults.buttonColors(containerColor = color, contentColor = Color.White),+    ) {+        Column(horizontalAlignment = Alignment.CenterHorizontally) {+            Text(stringResource(labelRes), style = MaterialTheme.typography.labelLarge)+            if (interval.isNotEmpty()) {+                Text(interval, style = MaterialTheme.typography.labelSmall)+            }+        }     } }++private val GRADE_AGAIN_COLOR = Color(0xFFD32F2F)+private val GRADE_HARD_COLOR = Color(0xFFF57C00)+private val GRADE_GOOD_COLOR = Color(0xFF388E3C)+private val GRADE_EASY_COLOR = Color(0xFF1976D2)
flashcards/src/main/java/com/vayunmathur/flashcards/ui/SettingsPage.kt
diff --git a/flashcards/src/main/java/com/vayunmathur/flashcards/ui/SettingsPage.kt b/flashcards/src/main/java/com/vayunmathur/flashcards/ui/SettingsPage.ktnew file mode 100644index 0000000000..98e737e5b7--- /dev/null+++ b/flashcards/src/main/java/com/vayunmathur/flashcards/ui/SettingsPage.kt@@ -0,0 +1,207 @@+package com.vayunmathur.flashcards.ui++import android.Manifest+import android.os.Build+import androidx.activity.compose.rememberLauncherForActivityResult+import androidx.activity.result.contract.ActivityResultContracts+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.rememberScrollState+import androidx.compose.foundation.verticalScroll+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.Modifier+import androidx.compose.ui.res.stringResource+import androidx.compose.ui.unit.dp+import androidx.lifecycle.compose.collectAsStateWithLifecycle+import com.vayunmathur.flashcards.R+import com.vayunmathur.flashcards.Route+import com.vayunmathur.flashcards.util.FlashcardsViewModel+import com.vayunmathur.flashcards.util.SettingsActions+import com.vayunmathur.flashcards.util.SettingsUiState+import com.vayunmathur.flashcards.util.ThemeMode+import com.vayunmathur.library.ui.AlertDialog+import com.vayunmathur.library.ui.AppScaffold+import com.vayunmathur.library.ui.FilterChip+import com.vayunmathur.library.ui.SettingsRow+import com.vayunmathur.library.ui.SettingsSection+import com.vayunmathur.library.ui.SettingsSwitchRow+import com.vayunmathur.library.ui.Slider+import com.vayunmathur.library.ui.Text+import com.vayunmathur.library.ui.TextButton+import com.vayunmathur.library.ui.rememberTimePickerState+import com.vayunmathur.library.util.NavBackStack+import kotlin.math.roundToInt++/** Binds persisted settings to the stateless [SettingsScreen]. */+@Composable+fun SettingsPage(backStack: NavBackStack<Route>, viewModel: FlashcardsViewModel) {+    val settings by viewModel.settings.collectAsStateWithLifecycle()++    val permissionLauncher = rememberLauncherForActivityResult(+        ActivityResultContracts.RequestPermission(),+    ) {}++    val actions = object : SettingsActions {+        override fun back() { backStack.pop() }+        override fun setDesiredRetention(value: Double) { viewModel.setDesiredRetention(value) }+        override fun setNewPerDay(value: Int) { viewModel.setNewPerDay(value) }+        override fun setMaxReviews(value: Int) { viewModel.setMaxReviews(value) }+        override fun setThemeMode(mode: Int) { viewModel.setThemeMode(mode) }+        override fun setReminderEnabled(enabled: Boolean) {+            if (enabled && Build.VERSION.SDK_INT >= Build.VERSION_CODES.TIRAMISU) {+                permissionLauncher.launch(Manifest.permission.POST_NOTIFICATIONS)+            }+            viewModel.setReminderEnabled(enabled)+        }+        override fun setReminderTime(hour: Int, minute: Int) {+            viewModel.setReminderTime(hour, minute)+        }+    }++    SettingsScreen(state = settings, actions = actions)+}++/** The settings screen. ViewModel-free so previews can render it. */+@Composable+fun SettingsScreen(state: SettingsUiState, actions: SettingsActions) {+    var showTimePicker by remember { mutableStateOf(false) }++    AppScaffold(+        title = stringResource(R.string.nav_settings),+        onNavigateBack = { actions.back() },+    ) { paddingValues ->+        Column(+            Modifier+                .fillMaxSize()+                .padding(paddingValues)+                .verticalScroll(rememberScrollState()),+        ) {+            SettingsSection(title = stringResource(R.string.settings_study)) {+                SliderRow(+                    title = stringResource(R.string.setting_retention),+                    value = "${(state.desiredRetention * 100).roundToInt()}%",+                    sliderValue = state.desiredRetention.toFloat(),+                    range = 0.70f..0.98f,+                    steps = 13,+                    onChange = { actions.setDesiredRetention(it.toDouble()) },+                )+                SliderRow(+                    title = stringResource(R.string.setting_new_per_day),+                    value = state.newPerDay.toString(),+                    sliderValue = state.newPerDay.toFloat(),+                    range = 0f..50f,+                    steps = 49,+                    onChange = { actions.setNewPerDay(it.roundToInt()) },+                )+                SliderRow(+                    title = stringResource(R.string.setting_max_reviews),+                    value = state.maxReviews.toString(),+                    sliderValue = state.maxReviews.toFloat(),+                    range = 0f..500f,+                    steps = 0,+                    onChange = { actions.setMaxReviews((it / 10).roundToInt() * 10) },+                )+            }++            SettingsSection(title = stringResource(R.string.settings_reminders)) {+                SettingsSwitchRow(+                    title = stringResource(R.string.setting_reminder_enabled),+                    checked = state.reminderEnabled,+                    onCheckedChange = { actions.setReminderEnabled(it) },+                )+                SettingsRow(+                    title = stringResource(R.string.setting_reminder_time),+                    supportingText = "%02d:%02d".format(state.reminderHour, state.reminderMinute),+                    enabled = state.reminderEnabled,+                    onClick = { showTimePicker = true },+                )+            }++            SettingsSection(title = stringResource(R.string.settings_appearance)) {+                Row(+                    Modifier.fillMaxWidth().padding(horizontal = 16.dp, vertical = 8.dp),+                    horizontalArrangement = Arrangement.spacedBy(8.dp),+                ) {+                    ThemeChip(R.string.theme_system, ThemeMode.SYSTEM, state.themeMode, actions)+                    ThemeChip(R.string.theme_light, ThemeMode.LIGHT, state.themeMode, actions)+                    ThemeChip(R.string.theme_dark, ThemeMode.DARK, state.themeMode, actions)+                }+            }+        }+    }++    if (showTimePicker) {+        TimePickerDialog(+            initialHour = state.reminderHour,+            initialMinute = state.reminderMinute,+            onConfirm = { hour, minute ->+                actions.setReminderTime(hour, minute)+                showTimePicker = false+            },+            onDismiss = { showTimePicker = false },+        )+    }+}++@Composable+private fun ThemeChip(labelRes: Int, mode: Int, selected: Int, actions: SettingsActions) {+    FilterChip(+        selected = selected == mode,+        onClick = { actions.setThemeMode(mode) },+        label = { Text(stringResource(labelRes)) },+    )+}++@Composable+private fun SliderRow(+    title: String,+    value: String,+    sliderValue: Float,+    range: ClosedFloatingPointRange<Float>,+    steps: Int,+    onChange: (Float) -> Unit,+) {+    Column(Modifier.fillMaxWidth().padding(horizontal = 16.dp, vertical = 4.dp)) {+        Row(Modifier.fillMaxWidth(), horizontalArrangement = Arrangement.SpaceBetween) {+            Text(title)+            Text(value)+        }+        Slider(+            value = sliderValue.coerceIn(range.start, range.endInclusive),+            onValueChange = onChange,+            valueRange = range,+            steps = steps,+        )+    }+}++@Composable+private fun TimePickerDialog(+    initialHour: Int,+    initialMinute: Int,+    onConfirm: (Int, Int) -> Unit,+    onDismiss: () -> Unit,+) {+    val timeState = rememberTimePickerState(initialHour = initialHour, initialMinute = initialMinute)+    AlertDialog(+        onDismissRequest = onDismiss,+        title = { Text(stringResource(R.string.setting_reminder_time)) },+        text = { androidx.compose.material3.TimePicker(state = timeState) },+        confirmButton = {+            TextButton(onClick = { onConfirm(timeState.hour, timeState.minute) }) {+                Text(stringResource(R.string.save))+            }+        },+        dismissButton = {+            TextButton(onClick = onDismiss) { Text(stringResource(R.string.cancel)) }+        },+    )+}
flashcards/src/main/java/com/vayunmathur/flashcards/ui/StatsPage.kt
diff --git a/flashcards/src/main/java/com/vayunmathur/flashcards/ui/StatsPage.kt b/flashcards/src/main/java/com/vayunmathur/flashcards/ui/StatsPage.ktnew file mode 100644index 0000000000..f75171daa9--- /dev/null+++ b/flashcards/src/main/java/com/vayunmathur/flashcards/ui/StatsPage.kt@@ -0,0 +1,199 @@+package com.vayunmathur.flashcards.ui++import androidx.compose.foundation.horizontalScroll+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.layout.size+import androidx.compose.foundation.rememberScrollState+import androidx.compose.foundation.verticalScroll+import androidx.compose.runtime.Composable+import androidx.compose.runtime.getValue+import androidx.compose.runtime.mutableIntStateOf+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.res.stringResource+import androidx.compose.ui.unit.dp+import androidx.lifecycle.compose.collectAsStateWithLifecycle+import com.vayunmathur.flashcards.R+import com.vayunmathur.flashcards.Route+import com.vayunmathur.flashcards.data.CardState+import com.vayunmathur.flashcards.util.DailyStat+import com.vayunmathur.flashcards.util.DeckOption+import com.vayunmathur.flashcards.util.FlashcardsViewModel+import com.vayunmathur.flashcards.util.StatsActions+import com.vayunmathur.flashcards.util.StatsUiState+import com.vayunmathur.library.ui.EmptyState+import com.vayunmathur.library.ui.FilterChip+import com.vayunmathur.library.ui.AppScaffold+import com.vayunmathur.library.ui.MaterialTheme+import com.vayunmathur.library.ui.SecondaryTabRow+import com.vayunmathur.library.ui.Tab+import com.vayunmathur.library.ui.Text+import com.vayunmathur.library.util.NavBackStack+import java.time.LocalDate++/** Binds review history for the selected deck to the stateless [StatsScreen]. */+@Composable+fun StatsPage(backStack: NavBackStack<Route>, viewModel: FlashcardsViewModel) {+    val decks by viewModel.decks.collectAsStateWithLifecycle()+    val cards by viewModel.cards.collectAsStateWithLifecycle()+    var selectedDeckId by remember { mutableStateOf<Long?>(null) }+    val logs by remember(selectedDeckId) { viewModel.reviewLogsFor(selectedDeckId) }+        .collectAsStateWithLifecycle(emptyList())++    val deckOptions = buildList {+        add(DeckOption(null, stringResource(R.string.all_decks)))+        decks.sortedBy { it.position }.forEach { add(DeckOption(it.id, it.name)) }+    }++    val zone = java.time.ZoneId.systemDefault()+    val byDay = logs.groupBy {+        java.time.Instant.ofEpochMilli(it.reviewedAt).atZone(zone).toLocalDate().toEpochDay()+    }+    val daily = byDay.map { (day, entries) -> DailyStat(day, entries.size) }.sortedBy { it.epochDay }++    // Retention over genuine recall attempts (cards previously seen).+    val recalls = logs.filter { it.elapsedDays > 0 }+    val retentionPct = if (recalls.isEmpty()) 0 else {+        (recalls.count { it.grade > 1 } * 100) / recalls.size+    }++    val today = LocalDate.now().toEpochDay()+    var streak = 0+    while (byDay.containsKey(today - streak)) streak++++    val deckCards = if (selectedDeckId == null) cards else cards.filter { it.deckId == selectedDeckId }++    StatsScreen(+        state = StatsUiState(+            deckOptions = deckOptions,+            selectedDeckId = selectedDeckId,+            daily = daily,+            totalReviews = logs.size,+            retentionPct = retentionPct,+            streakDays = streak,+            matureCards = deckCards.count { it.state == CardState.REVIEW },+            totalCards = deckCards.size,+        ),+        actions = object : StatsActions {+            override fun back() { backStack.pop() }+            override fun selectDeck(id: Long?) { selectedDeckId = id }+        },+    )+}++/** Statistics for the selected deck. ViewModel-free so previews can render it. */+@Composable+fun StatsScreen(state: StatsUiState, actions: StatsActions) {+    var period by remember { mutableIntStateOf(1) }+    val windowDays = when (period) {+        0 -> 7+        1 -> 30+        else -> 365+    }++    AppScaffold(+        title = stringResource(R.string.nav_stats),+        onNavigateBack = { actions.back() },+    ) { paddingValues ->+        Column(+            Modifier+                .fillMaxSize()+                .padding(paddingValues)+                .verticalScroll(rememberScrollState()),+        ) {+            if (state.deckOptions.size > 1) {+                Row(+                    Modifier.fillMaxWidth().horizontalScroll(rememberScrollState()).padding(horizontal = 12.dp),+                    horizontalArrangement = Arrangement.spacedBy(8.dp),+                ) {+                    state.deckOptions.forEach { option ->+                        FilterChip(+                            selected = option.id == state.selectedDeckId,+                            onClick = { actions.selectDeck(option.id) },+                            label = { Text(option.name) },+                        )+                    }+                }+            }++            SummaryRow(state)++            SecondaryTabRow(selectedTabIndex = period) {+                PeriodTab(R.string.period_week, 0, period) { period = 0 }+                PeriodTab(R.string.period_month, 1, period) { period = 1 }+                PeriodTab(R.string.period_year, 2, period) { period = 2 }+            }++            if (state.totalReviews == 0) {+                EmptyState(+                    title = stringResource(R.string.no_reviews),+                    message = stringResource(R.string.no_reviews_hint),+                    modifier = Modifier.fillMaxWidth().padding(top = 48.dp),+                )+            } else {+                ReviewBarChart(+                    data = windowedData(state.daily, windowDays),+                    modifier = Modifier.fillMaxWidth().padding(16.dp),+                )+            }+        }+    }+}++@Composable+private fun SummaryRow(state: StatsUiState) {+    Row(+        Modifier.fillMaxWidth().padding(16.dp),+        horizontalArrangement = Arrangement.spacedBy(12.dp),+    ) {+        MetricRing(+            progress = state.retentionPct / 100f,+            label = stringResource(R.string.stat_retention),+            value = "${state.retentionPct}%",+            modifier = Modifier.size(84.dp),+        )+        Column(Modifier.weight(1f), verticalArrangement = Arrangement.spacedBy(4.dp)) {+            StatLine(stringResource(R.string.stat_reviews), state.totalReviews.toString())+            StatLine(stringResource(R.string.stat_streak), stringResource(R.string.days_value, state.streakDays))+            StatLine(+                stringResource(R.string.stat_mature),+                "${state.matureCards} / ${state.totalCards}",+            )+        }+    }+}++@Composable+private fun StatLine(label: String, value: String) {+    Row(Modifier.fillMaxWidth(), horizontalArrangement = Arrangement.SpaceBetween) {+        Text(label, style = MaterialTheme.typography.bodyMedium, color = MaterialTheme.colorScheme.onSurfaceVariant)+        Text(value, style = MaterialTheme.typography.titleMedium)+    }+}++@Composable+private fun PeriodTab(labelRes: Int, index: Int, selected: Int, onClick: () -> Unit) {+    Tab(+        selected = selected == index,+        onClick = onClick,+        text = { Text(stringResource(labelRes)) },+    )+}++private fun windowedData(daily: List<DailyStat>, windowDays: Int): List<Pair<String, Double>> {+    val counts = daily.associate { it.epochDay to it.count }+    val today = LocalDate.now().toEpochDay()+    return (0 until windowDays).map { offset ->+        val day = today - (windowDays - 1 - offset)+        val date = LocalDate.ofEpochDay(day)+        date.dayOfMonth.toString() to (counts[day] ?: 0).toDouble()+    }+}
flashcards/src/main/java/com/vayunmathur/flashcards/util/DeckIo.kt
diff --git a/flashcards/src/main/java/com/vayunmathur/flashcards/util/DeckIo.kt b/flashcards/src/main/java/com/vayunmathur/flashcards/util/DeckIo.ktnew file mode 100644index 0000000000..2960acc5f1--- /dev/null+++ b/flashcards/src/main/java/com/vayunmathur/flashcards/util/DeckIo.kt@@ -0,0 +1,71 @@+package com.vayunmathur.flashcards.util++import android.content.Context+import com.vayunmathur.flashcards.data.Card+import com.vayunmathur.flashcards.data.Deck+import java.io.File+import kotlinx.serialization.Serializable+import kotlinx.serialization.encodeToString+import kotlinx.serialization.json.Json++/** A deck plus its cards, the unit of per-deck JSON export/import. */+@Serializable+data class DeckExport(val deck: Deck, val cards: List<Card>)++/** Per-deck JSON export (for share) and CSV import (for bulk card creation). */+object DeckIo {+    private val json = Json { prettyPrint = true; ignoreUnknownKeys = true }++    /** Writes [deck] + [cards] as JSON to a cache file and returns it. */+    fun writeExport(context: Context, deck: Deck, cards: List<Card>): File {+        val dir = File(context.cacheDir, "shared_decks").apply { mkdirs() }+        val safeName = deck.name.ifBlank { "deck" }.replace(Regex("[^A-Za-z0-9._-]"), "_")+        val file = File(dir, "$safeName.json")+        file.writeText(json.encodeToString(DeckExport(deck, cards)))+        return file+    }++    /**+     * Parses CSV text into (front, back) pairs. Accepts two columns per row; a+     * standard-quoted first line of `front,back` is skipped as a header. Handles+     * double-quoted fields with embedded commas and escaped quotes.+     */+    fun parseCsv(text: String): List<Pair<String, String>> {+        val rows = mutableListOf<Pair<String, String>>()+        text.lineSequence().forEachIndexed { index, raw ->+            if (raw.isBlank()) return@forEachIndexed+            val fields = splitCsvLine(raw)+            if (fields.size < 2) return@forEachIndexed+            val front = fields[0].trim()+            val back = fields[1].trim()+            if (index == 0 && front.equals("front", true) && back.equals("back", true)) {+                return@forEachIndexed+            }+            if (front.isNotEmpty() || back.isNotEmpty()) rows.add(front to back)+        }+        return rows+    }++    private fun splitCsvLine(line: String): List<String> {+        val out = mutableListOf<String>()+        val sb = StringBuilder()+        var inQuotes = false+        var i = 0+        while (i < line.length) {+            val c = line[i]+            when {+                inQuotes && c == '"' && line.getOrNull(i + 1) == '"' -> {+                    sb.append('"'); i+++                }+                c == '"' -> inQuotes = !inQuotes+                c == ',' && !inQuotes -> {+                    out.add(sb.toString()); sb.clear()+                }+                else -> sb.append(c)+            }+            i+++        }+        out.add(sb.toString())+        return out+    }+}
flashcards/src/main/java/com/vayunmathur/flashcards/util/FlashcardsUiContract.kt
diff --git a/flashcards/src/main/java/com/vayunmathur/flashcards/util/FlashcardsUiContract.kt b/flashcards/src/main/java/com/vayunmathur/flashcards/util/FlashcardsUiContract.ktindex ce6c9ebf0f..8f6b8ad273 100644--- a/flashcards/src/main/java/com/vayunmathur/flashcards/util/FlashcardsUiContract.kt+++ b/flashcards/src/main/java/com/vayunmathur/flashcards/util/FlashcardsUiContract.kt@@ -10,14 +10,21 @@ import com.vayunmathur.flashcards.data.Deck  * they can be rendered by a `@Preview` — which is what the store listing images are  * generated from. It lives in `util` rather than `ui` so the dependency runs one way:  * `ui` depends on `util`, and the binders in `ui` implement these interfaces. Every actions- * method has a no-op default so a preview can use the [Noop] implementation with no VM.+ * method has a no-op default so a preview can use the `Noop` implementation with no VM.  */ +// ---------------------------------------------------------------------------+// Deck list+// ---------------------------------------------------------------------------+ /** A deck plus its derived review counts, as drawn on the deck list. */ data class DeckSummary(     val deck: Deck,     val dueCount: Int = 0,+    val newCount: Int = 0,     val totalCount: Int = 0,+    /** Fraction of cards that have graduated to the review state (0..1). */+    val mastery: Float = 0f, )  /** Everything the deck list draws. */@@ -30,12 +37,17 @@ interface DeckListActions {     fun addDeck(name: String) {}     fun deleteDeck(deck: Deck) {}     fun startReview(deckId: Long) {}+    fun reorder(decks: List<Deck>) {}      companion object {         val Noop: DeckListActions = object : DeckListActions {}     } } +// ---------------------------------------------------------------------------+// Card list+// ---------------------------------------------------------------------------+ /** Everything the card list draws for a single deck. */ data class CardListUiState(     val deckName: String = "",@@ -49,16 +61,24 @@ interface CardListActions {     fun addCard() {}     fun deleteCard(card: Card) {}     fun study() {}+    fun reorder(cards: List<Card>) {}+    fun openStats() {}+    fun share() {}      companion object {         val Noop: CardListActions = object : CardListActions {}     } } -/** Everything the card editor draws: the two plain-text sides. */+// ---------------------------------------------------------------------------+// Card editor+// ---------------------------------------------------------------------------++/** Everything the card editor draws: the two markdown sides plus tags. */ data class CardEditUiState(     val front: String = "",     val back: String = "",+    val tags: String = "",     val isNew: Boolean = true, ) @@ -66,6 +86,7 @@ interface CardEditActions {     fun back() {}     fun setFront(front: String) {}     fun setBack(back: String) {}+    fun setTags(tags: String) {}     fun save() {}     fun deleteCard() {} @@ -74,21 +95,100 @@ interface CardEditActions {     } } +// ---------------------------------------------------------------------------+// Review session+// ---------------------------------------------------------------------------+ /** Everything a review session draws for the current card. */ data class ReviewUiState(     val front: String = "",     val back: String = "",-    /** Cards still due in this session, including the one shown. */+    /** Cards still queued in this session, including the one shown. */     val remaining: Int = 0,-    /** True when nothing is due, i.e. the session is complete. */+    /** True when the queue is empty, i.e. the session is complete. */     val done: Boolean = false,-)+    val newCount: Int = 0,+    val learningCount: Int = 0,+    val reviewCount: Int = 0,+    val progress: Float = 0f,+    /** Predicted next-interval label per grade button (e.g. "10m", "4d"). */+    val intervalLabels: Map<Grade, String> = emptyMap(),+    val canUndo: Boolean = false,+) {+    fun label(grade: Grade): String = intervalLabels[grade] ?: ""+}  interface ReviewActions {     fun back() {}     fun grade(grade: Grade) {}+    fun undo() {}      companion object {         val Noop: ReviewActions = object : ReviewActions {}     } }++// ---------------------------------------------------------------------------+// Statistics+// ---------------------------------------------------------------------------++/** A single deck choice (plus an "All decks" option with a null id) in the stats picker. */+data class DeckOption(val id: Long?, val name: String)++/** One day of review history. [epochDay] is days since the Unix epoch (local). */+data class DailyStat(val epochDay: Long, val count: Int)++data class StatsUiState(+    val deckOptions: List<DeckOption> = emptyList(),+    val selectedDeckId: Long? = null,+    /** Chronological daily review counts covering roughly the last year. */+    val daily: List<DailyStat> = emptyList(),+    val totalReviews: Int = 0,+    val retentionPct: Int = 0,+    val streakDays: Int = 0,+    val matureCards: Int = 0,+    val totalCards: Int = 0,+)++interface StatsActions {+    fun back() {}+    fun selectDeck(id: Long?) {}++    companion object {+        val Noop: StatsActions = object : StatsActions {}+    }+}++// ---------------------------------------------------------------------------+// Settings+// ---------------------------------------------------------------------------++object ThemeMode {+    const val SYSTEM = 0+    const val LIGHT = 1+    const val DARK = 2+}++data class SettingsUiState(+    val desiredRetention: Double = 0.9,+    val newPerDay: Int = 20,+    val maxReviews: Int = 200,+    val reminderEnabled: Boolean = false,+    val reminderHour: Int = 20,+    val reminderMinute: Int = 0,+    val themeMode: Int = ThemeMode.SYSTEM,+)++interface SettingsActions {+    fun back() {}+    fun setDesiredRetention(value: Double) {}+    fun setNewPerDay(value: Int) {}+    fun setMaxReviews(value: Int) {}+    fun setReminderEnabled(enabled: Boolean) {}+    fun setReminderTime(hour: Int, minute: Int) {}+    fun setThemeMode(mode: Int) {}++    companion object {+        val Noop: SettingsActions = object : SettingsActions {}+    }+}
flashcards/src/main/java/com/vayunmathur/flashcards/util/FlashcardsViewModel.kt
diff --git a/flashcards/src/main/java/com/vayunmathur/flashcards/util/FlashcardsViewModel.kt b/flashcards/src/main/java/com/vayunmathur/flashcards/util/FlashcardsViewModel.ktindex e1bff7c658..902d3a4d41 100644--- a/flashcards/src/main/java/com/vayunmathur/flashcards/util/FlashcardsViewModel.kt+++ b/flashcards/src/main/java/com/vayunmathur/flashcards/util/FlashcardsViewModel.kt@@ -1,75 +1,262 @@ package com.vayunmathur.flashcards.util  import android.app.Application+import android.net.Uri+import androidx.core.content.FileProvider import androidx.lifecycle.AndroidViewModel import androidx.lifecycle.ViewModel import androidx.lifecycle.ViewModelProvider import androidx.lifecycle.viewModelScope import com.vayunmathur.flashcards.data.Card import com.vayunmathur.flashcards.data.CardDao+import com.vayunmathur.flashcards.data.CardState import com.vayunmathur.flashcards.data.Deck import com.vayunmathur.flashcards.data.DeckDao+import com.vayunmathur.flashcards.data.ReviewLog+import com.vayunmathur.flashcards.data.ReviewLogDao+import com.vayunmathur.library.util.DataStoreUtils import kotlinx.coroutines.Dispatchers import kotlinx.coroutines.flow.Flow+import kotlinx.coroutines.flow.MutableSharedFlow+import kotlinx.coroutines.flow.MutableStateFlow import kotlinx.coroutines.flow.SharingStarted import kotlinx.coroutines.flow.StateFlow+import kotlinx.coroutines.flow.asSharedFlow+import kotlinx.coroutines.flow.asStateFlow+import kotlinx.coroutines.flow.combine import kotlinx.coroutines.flow.stateIn import kotlinx.coroutines.launch+import kotlinx.coroutines.withContext  /**  * ViewModel for the Flashcards app.  *- * Owns the deck and card [StateFlow]s collected by the screens plus IO-dispatched- * write helpers. [gradeCard] runs the pure [Scheduler] then upserts the result, so- * a graded card's due date advances and it leaves the deck's due queue.+ * Owns the deck/card [StateFlow]s collected by the screens, the persisted+ * [settings], and the in-memory [ReviewSession] driving the review screen via+ * [review]. Grading runs the pure [Scheduler], upserts the card, and writes a+ * [ReviewLog] row (which the stats screen reads back).  */ class FlashcardsViewModel(     application: Application,     private val deckDao: DeckDao,     private val cardDao: CardDao,+    private val reviewLogDao: ReviewLogDao, ) : AndroidViewModel(application) { +    private val ds = DataStoreUtils.getInstance(application)+     val decks: StateFlow<List<Deck>> = deckDao.getAllFlow()         .stateIn(viewModelScope, SharingStarted.WhileSubscribed(5_000), emptyList()) -    /** All cards across every deck; the deck list derives per-deck due counts from this. */+    /** All cards across every deck; the deck list derives per-deck counts from this. */     val cards: StateFlow<List<Card>> = cardDao.getAllFlow()         .stateIn(viewModelScope, SharingStarted.WhileSubscribed(5_000), emptyList())      fun cardsFor(deckId: Long): Flow<List<Card>> = cardDao.getByDeckFlow(deckId) -    /**-     * Cards currently due in [deckId]. The `now` cutoff is captured once when the-     * flow is created (a review session), so grading a card pushes its due date-     * past the cutoff and drops it from the emitted list.-     */-    fun dueCardsFor(deckId: Long): Flow<List<Card>> =-        cardDao.getDueByDeckFlow(deckId, System.currentTimeMillis())-     fun cardById(id: Long): Flow<Card?> = cardDao.getByIdFlow(id) -    fun upsertDeck(deck: Deck) {-        viewModelScope.launch(Dispatchers.IO) { deckDao.upsert(deck) }+    fun reviewLogsFor(deckId: Long?): Flow<List<ReviewLog>> =+        if (deckId == null) reviewLogDao.getAllFlow() else reviewLogDao.getByDeckFlow(deckId)++    // -- Persisted settings ------------------------------------------------++    val settings: StateFlow<SettingsUiState> = combine(+        ds.doubleFlow(KEY_RETENTION),+        ds.longFlow(KEY_NEW_PER_DAY, 20L),+        ds.longFlow(KEY_MAX_REVIEWS, 200L),+        ds.longFlow(KEY_THEME_MODE, 0L),+    ) { retention, newPerDay, maxReviews, theme ->+        arrayOf<Any>(retention, newPerDay, maxReviews, theme)+    }+        .combine(ds.booleanFlow(KEY_REMINDER_ENABLED)) { core, enabled -> core to enabled }+        .combine(ds.longFlow(KEY_REMINDER_MINUTES, 20L * 60)) { (core, enabled), minutes ->+            SettingsUiState(+                desiredRetention = (core[0] as Double).takeIf { it > 0.0 } ?: 0.9,+                newPerDay = (core[1] as Long).toInt(),+                maxReviews = (core[2] as Long).toInt(),+                themeMode = (core[3] as Long).toInt(),+                reminderEnabled = enabled,+                reminderHour = (minutes / 60).toInt(),+                reminderMinute = (minutes % 60).toInt(),+            )+        }+        .stateIn(viewModelScope, SharingStarted.WhileSubscribed(5_000), SettingsUiState())++    fun setDesiredRetention(value: Double) =+        launchIo { ds.setDouble(KEY_RETENTION, value) }++    fun setNewPerDay(value: Int) = launchIo { ds.setLong(KEY_NEW_PER_DAY, value.toLong()) }++    fun setMaxReviews(value: Int) = launchIo { ds.setLong(KEY_MAX_REVIEWS, value.toLong()) }++    fun setThemeMode(mode: Int) = launchIo { ds.setLong(KEY_THEME_MODE, mode.toLong()) }++    fun setReminderEnabled(enabled: Boolean) = launchIo {+        ds.setBoolean(KEY_REMINDER_ENABLED, enabled)+        val current = settings.value+        ReviewReminder.update(getApplication(), enabled, current.reminderHour, current.reminderMinute)+    }++    fun setReminderTime(hour: Int, minute: Int) = launchIo {+        ds.setLong(KEY_REMINDER_MINUTES, (hour * 60 + minute).toLong())+        ReviewReminder.update(getApplication(), settings.value.reminderEnabled, hour, minute)+    }++    // -- Deck / card writes ------------------------------------------------++    fun upsertDeck(deck: Deck) = launchIo { deckDao.upsert(deck) }++    fun addDeck(name: String) = launchIo {+        val s = settings.value+        deckDao.upsert(+            Deck(+                name = name,+                newPerDay = s.newPerDay,+                maxReviewsPerDay = s.maxReviews,+                desiredRetention = s.desiredRetention,+            ),+        )+    }++    fun deleteDeck(deck: Deck) = launchIo {+        cardDao.deleteByDeck(deck.id)+        reviewLogDao.deleteByDeck(deck.id)+        deckDao.delete(deck)     } -    fun deleteDeck(deck: Deck) {-        viewModelScope.launch(Dispatchers.IO) {-            cardDao.deleteByDeck(deck.id)-            deckDao.delete(deck)+    fun reorderDecks(decks: List<Deck>) = launchIo { decks.forEach { deckDao.upsert(it) } }++    fun upsertCard(card: Card) = launchIo { cardDao.upsert(card) }++    fun deleteCard(card: Card) = launchIo { cardDao.delete(card) }++    fun reorderCards(cards: List<Card>) = launchIo { cardDao.upsertAll(cards) }++    // -- Review session ----------------------------------------------------++    private var session: ReviewSession? = null+    private var lastLogId: Long? = null+    private val _review = MutableStateFlow(ReviewUiState())+    val review: StateFlow<ReviewUiState> = _review.asStateFlow()++    fun startSession(deckId: Long) = launchIo {+        val deck = deckDao.getById(deckId) ?: return@launchIo+        val cards = cardDao.getByDeck(deckId)+        val now = System.currentTimeMillis()+        session = ReviewSession(+            cards = cards,+            newPerDay = deck.newPerDay,+            maxReviews = deck.maxReviewsPerDay,+            now = now,+            desiredRetention = deck.desiredRetention,+        )+        lastLogId = null+        publishReview()+    }++    fun gradeCurrent(grade: Grade) = launchIo {+        val s = session ?: return@launchIo+        val original = s.current ?: return@launchIo+        val now = System.currentTimeMillis()+        val prevLastReview = original.lastReview+        val updated = s.grade(grade, now) ?: return@launchIo+        cardDao.upsert(updated)+        val elapsedDays =+            if (prevLastReview > 0) (now - prevLastReview).toDouble() / Scheduler.DAY_MS else 0.0+        val scheduledDays = (updated.dueDate - now).toDouble() / Scheduler.DAY_MS+        lastLogId = reviewLogDao.insert(+            ReviewLog(+                cardId = original.id,+                deckId = original.deckId,+                reviewedAt = now,+                grade = grade.value,+                elapsedDays = elapsedDays,+                scheduledDays = scheduledDays,+                state = updated.state,+            ),+        )+        publishReview()+    }++    fun undoReview() = launchIo {+        val s = session ?: return@launchIo+        val restored = s.undo() ?: return@launchIo+        cardDao.upsert(restored)+        lastLogId?.let {+            reviewLogDao.deleteById(it)+            lastLogId = null         }+        publishReview()     } -    fun upsertCard(card: Card) {-        viewModelScope.launch(Dispatchers.IO) { cardDao.upsert(card) }+    private fun publishReview() {+        val s = session+        _review.value = if (s == null) {+            ReviewUiState(done = true)+        } else {+            val now = System.currentTimeMillis()+            val current = s.current+            ReviewUiState(+                front = current?.front.orEmpty(),+                back = current?.back.orEmpty(),+                remaining = s.remaining,+                done = s.done,+                newCount = s.newCount,+                learningCount = s.learningCount,+                reviewCount = s.reviewCount,+                progress = s.progress,+                intervalLabels = s.previewLabels(now),+                canUndo = s.canUndo,+            )+        }     } -    fun deleteCard(card: Card) {-        viewModelScope.launch(Dispatchers.IO) { cardDao.delete(card) }+    // -- Import / export / share ------------------------------------------++    private val _shareRequests = MutableSharedFlow<Uri>(extraBufferCapacity = 1)+    val shareRequests = _shareRequests.asSharedFlow()++    fun exportDeck(deckId: Long) = launchIo {+        val context = getApplication<Application>()+        val deck = deckDao.getById(deckId) ?: return@launchIo+        val cards = cardDao.getByDeck(deckId)+        val uri = withContext(Dispatchers.IO) {+            val file = DeckIo.writeExport(context, deck, cards)+            FileProvider.getUriForFile(context, "${context.packageName}.fileprovider", file)+        }+        _shareRequests.emit(uri)     } -    fun gradeCard(card: Card, grade: Grade) {-        viewModelScope.launch(Dispatchers.IO) {-            cardDao.upsert(Scheduler.schedule(card, grade, System.currentTimeMillis()))+    fun importCsv(deckId: Long, uri: Uri) = launchIo {+        val context = getApplication<Application>()+        val text = withContext(Dispatchers.IO) {+            context.contentResolver.openInputStream(uri)?.bufferedReader()?.use { it.readText() }+        } ?: return@launchIo+        val existing = cardDao.getByDeck(deckId)+        var position = (existing.maxOfOrNull { it.position } ?: 0.0)+        val newCards = DeckIo.parseCsv(text).map { (front, back) ->+            position += 1.0+            Card(deckId = deckId, front = front, back = back, position = position)+        }+        if (newCards.isNotEmpty()) cardDao.upsertAll(newCards)+    }++    private fun launchIo(block: suspend () -> Unit) =+        viewModelScope.launch(Dispatchers.IO) { block() }++    companion object {+        const val KEY_RETENTION = "desired_retention"+        const val KEY_NEW_PER_DAY = "new_per_day"+        const val KEY_MAX_REVIEWS = "max_reviews"+        const val KEY_THEME_MODE = "theme_mode"+        const val KEY_REMINDER_ENABLED = "reminder_enabled"+        const val KEY_REMINDER_MINUTES = "reminder_minutes"++        /** Mastery = fraction of a deck's cards that have graduated to review. */+        fun mastery(cards: List<Card>): Float {+            if (cards.isEmpty()) return 0f+            return cards.count { it.state == CardState.REVIEW }.toFloat() / cards.size         }     } }@@ -79,12 +266,13 @@ class FlashcardsViewModelFactory(     private val application: Application,     private val deckDao: DeckDao,     private val cardDao: CardDao,+    private val reviewLogDao: ReviewLogDao, ) : ViewModelProvider.Factory {     @Suppress("UNCHECKED_CAST")     override fun <T : ViewModel> create(modelClass: Class<T>): T {         require(modelClass.isAssignableFrom(FlashcardsViewModel::class.java)) {             "Unexpected ViewModel class: $modelClass"         }-        return FlashcardsViewModel(application, deckDao, cardDao) as T+        return FlashcardsViewModel(application, deckDao, cardDao, reviewLogDao) as T     } }
flashcards/src/main/java/com/vayunmathur/flashcards/util/ReviewReminderWorker.kt
diff --git a/flashcards/src/main/java/com/vayunmathur/flashcards/util/ReviewReminderWorker.kt b/flashcards/src/main/java/com/vayunmathur/flashcards/util/ReviewReminderWorker.ktnew file mode 100644index 0000000000..092418ded2--- /dev/null+++ b/flashcards/src/main/java/com/vayunmathur/flashcards/util/ReviewReminderWorker.kt@@ -0,0 +1,108 @@+package com.vayunmathur.flashcards.util++import android.Manifest+import android.app.NotificationManager+import android.app.PendingIntent+import android.content.Context+import android.content.Intent+import android.content.pm.PackageManager+import androidx.core.app.NotificationCompat+import androidx.core.app.NotificationManagerCompat+import androidx.core.content.ContextCompat+import androidx.work.CoroutineWorker+import androidx.work.ExistingPeriodicWorkPolicy+import androidx.work.PeriodicWorkRequestBuilder+import androidx.work.WorkManager+import androidx.work.WorkerParameters+import com.vayunmathur.flashcards.MainActivity+import com.vayunmathur.flashcards.R+import com.vayunmathur.flashcards.data.CardState+import com.vayunmathur.flashcards.data.DB_NAME+import com.vayunmathur.flashcards.data.FlashcardsDatabase+import com.vayunmathur.library.room.buildDatabase+import com.vayunmathur.library.util.ensureNotificationChannel+import java.util.Calendar+import java.util.concurrent.TimeUnit++/** Schedules/cancels the daily "cards are due" reminder via WorkManager. */+object ReviewReminder {+    private const val WORK_NAME = "flashcards_review_reminder"+    const val CHANNEL_ID = "review_reminders"++    fun update(context: Context, enabled: Boolean, hour: Int, minute: Int) {+        val wm = WorkManager.getInstance(context)+        if (!enabled) {+            wm.cancelUniqueWork(WORK_NAME)+            return+        }+        val request = PeriodicWorkRequestBuilder<ReviewReminderWorker>(1, TimeUnit.DAYS)+            .setInitialDelay(initialDelayMinutes(hour, minute), TimeUnit.MINUTES)+            .build()+        wm.enqueueUniquePeriodicWork(WORK_NAME, ExistingPeriodicWorkPolicy.UPDATE, request)+    }++    /** Minutes from now until the next occurrence of [hour]:[minute] (local). */+    private fun initialDelayMinutes(hour: Int, minute: Int): Long {+        val now = Calendar.getInstance()+        val next = Calendar.getInstance().apply {+            set(Calendar.HOUR_OF_DAY, hour)+            set(Calendar.MINUTE, minute)+            set(Calendar.SECOND, 0)+            set(Calendar.MILLISECOND, 0)+            if (before(now)) add(Calendar.DAY_OF_MONTH, 1)+        }+        return ((next.timeInMillis - now.timeInMillis) / 60_000L).coerceAtLeast(1)+    }+}++/** Posts a notification when cards are due for review. */+class ReviewReminderWorker(+    appContext: Context,+    params: WorkerParameters,+) : CoroutineWorker(appContext, params) {++    override suspend fun doWork(): Result {+        val now = System.currentTimeMillis()+        val db = applicationContext.buildDatabase<FlashcardsDatabase>(dbName = DB_NAME)+        val cards = db.cardDao().getAll()+        val due = cards.count { it.state != CardState.NEW && it.dueDate <= now } ++            cards.count { it.state == CardState.NEW }+        if (due > 0) notify(due)+        return Result.success()+    }++    private fun notify(due: Int) {+        val context = applicationContext+        if (ContextCompat.checkSelfPermission(context, Manifest.permission.POST_NOTIFICATIONS) !=+            PackageManager.PERMISSION_GRANTED+        ) {+            return+        }+        context.ensureNotificationChannel(+            id = ReviewReminder.CHANNEL_ID,+            name = context.getString(R.string.reminder_channel_name),+            importance = NotificationManager.IMPORTANCE_DEFAULT,+            description = context.getString(R.string.reminder_channel_description),+        )+        val intent = Intent(context, MainActivity::class.java)+            .addFlags(Intent.FLAG_ACTIVITY_NEW_TASK or Intent.FLAG_ACTIVITY_CLEAR_TOP)+        val pending = PendingIntent.getActivity(+            context,+            0,+            intent,+            PendingIntent.FLAG_UPDATE_CURRENT or PendingIntent.FLAG_IMMUTABLE,+        )+        val notification = NotificationCompat.Builder(context, ReviewReminder.CHANNEL_ID)+            .setSmallIcon(android.R.drawable.ic_dialog_info)+            .setContentTitle(context.getString(R.string.reminder_title))+            .setContentText(context.resources.getQuantityString(R.plurals.reminder_text, due, due))+            .setAutoCancel(true)+            .setContentIntent(pending)+            .build()+        NotificationManagerCompat.from(context).notify(REMINDER_NOTIFICATION_ID, notification)+    }++    companion object {+        private const val REMINDER_NOTIFICATION_ID = 4201+    }+}
flashcards/src/main/java/com/vayunmathur/flashcards/util/ReviewSession.kt
diff --git a/flashcards/src/main/java/com/vayunmathur/flashcards/util/ReviewSession.kt b/flashcards/src/main/java/com/vayunmathur/flashcards/util/ReviewSession.ktnew file mode 100644index 0000000000..d74c1181af--- /dev/null+++ b/flashcards/src/main/java/com/vayunmathur/flashcards/util/ReviewSession.kt@@ -0,0 +1,99 @@+package com.vayunmathur.flashcards.util++import com.vayunmathur.flashcards.data.Card+import com.vayunmathur.flashcards.data.CardState++/**+ * An in-memory review queue for a single study session. Pure Kotlin (no Android+ * dependency) so it can be unit-tested directly.+ *+ * The queue is seeded from the deck's due cards, capped at [newPerDay] new cards+ * and [maxReviews] review cards. Grading runs the [Scheduler]; cards that land in+ * a learning/relearning step (e.g. after `AGAIN`) are re-inserted a few positions+ * back so they resurface later in *this* session instead of dropping out, while+ * graduated cards leave the queue and count towards [progress].+ */+class ReviewSession(+    cards: List<Card>,+    private val newPerDay: Int,+    private val maxReviews: Int,+    now: Long,+    private val desiredRetention: Double,+) {+    private val queue = ArrayDeque<Card>()++    /** Distinct cards this session started with. */+    val totalCards: Int+    private var completed = 0++    private data class Undo(val card: Card, val queue: List<Card>, val completed: Int)+    private val undoStack = ArrayDeque<Undo>()++    init {+        val newCards = cards+            .filter { it.state == CardState.NEW }+            .sortedBy { it.position }+            .take(newPerDay.coerceAtLeast(0))+        val reviewCards = cards+            .filter { it.state != CardState.NEW && it.dueDate <= now }+            .sortedBy { it.dueDate }+            .take(maxReviews.coerceAtLeast(0))+        queue.addAll(reviewCards)+        queue.addAll(newCards)+        totalCards = queue.size+    }++    val current: Card? get() = queue.firstOrNull()+    val remaining: Int get() = queue.size+    val done: Boolean get() = queue.isEmpty()++    val newCount: Int get() = queue.count { it.state == CardState.NEW }+    val learningCount: Int+        get() = queue.count { it.state == CardState.LEARNING || it.state == CardState.RELEARNING }+    val reviewCount: Int get() = queue.count { it.state == CardState.REVIEW }++    val progress: Float get() = if (totalCards == 0) 1f else completed.toFloat() / totalCards+    val canUndo: Boolean get() = undoStack.isNotEmpty()++    /**+     * Grades the current card and advances the queue. Returns the updated card to+     * persist, or null if the queue was empty.+     */+    fun grade(grade: Grade, now: Long): Card? {+        val card = queue.firstOrNull() ?: return null+        undoStack.addLast(Undo(card, queue.toList(), completed))+        queue.removeFirst()++        val updated = Scheduler.schedule(card, grade, now, desiredRetention)+        if (updated.state == CardState.LEARNING || updated.state == CardState.RELEARNING) {+            queue.add(minOf(RE_QUEUE_GAP, queue.size), updated)+        } else {+            completed+++        }+        return updated+    }++    /**+     * Reverts the last [grade]. Returns the card whose pre-grade state must be+     * restored in the database, or null if there is nothing to undo.+     */+    fun undo(): Card? {+        val entry = undoStack.removeLastOrNull() ?: return null+        queue.clear()+        queue.addAll(entry.queue)+        completed = entry.completed+        return entry.card+    }++    /** Predicted interval label for each grade on the current card. */+    fun previewLabels(now: Long): Map<Grade, String> {+        val card = current ?: return emptyMap()+        return Grade.entries.associateWith {+            Scheduler.previewLabel(card, it, now, desiredRetention)+        }+    }++    companion object {+        private const val RE_QUEUE_GAP = 3+    }+}
flashcards/src/main/java/com/vayunmathur/flashcards/util/Scheduler.kt
diff --git a/flashcards/src/main/java/com/vayunmathur/flashcards/util/Scheduler.kt b/flashcards/src/main/java/com/vayunmathur/flashcards/util/Scheduler.ktindex 3569203a96..c72c81a141 100644--- a/flashcards/src/main/java/com/vayunmathur/flashcards/util/Scheduler.kt+++ b/flashcards/src/main/java/com/vayunmathur/flashcards/util/Scheduler.kt@@ -1,57 +1,199 @@ package com.vayunmathur.flashcards.util  import com.vayunmathur.flashcards.data.Card-import kotlin.math.roundToInt+import com.vayunmathur.flashcards.data.CardState+import kotlin.math.exp+import kotlin.math.pow+import kotlin.math.roundToLong  /**- * SM-2 grades. [q] is the SuperMemo quality-of-recall score (0–5); we expose the- * four Anki-style buttons and map them onto the passing/failing halves of that- * scale (q < 3 fails and resets the card, q >= 3 passes).+ * The four Anki-style review buttons, mapped onto the FSRS 1..4 grade scale.  */-enum class Grade(val q: Int) {-    AGAIN(2),-    HARD(3),-    GOOD(4),-    EASY(5),+enum class Grade(val value: Int) {+    AGAIN(1),+    HARD(2),+    GOOD(3),+    EASY(4), }  /**- * Pure SM-2 spaced-repetition scheduler. Kept free of Android dependencies so it- * can be unit-tested directly. [schedule] returns a copy of [card] with updated- * ease factor, interval, repetition count and due date; it never mutates input.+ * Pure FSRS (v5, 19-weight) spaced-repetition scheduler. Kept free of Android+ * dependencies so it can be unit-tested directly. [schedule] returns a copy of+ * [card] with an updated memory state and due date; it never mutates its input.+ *+ * Cards that fail (`AGAIN`) or are still in a learning/relearning step get a+ * short sub-day interval so they resurface within the same session; graduated+ * cards get the long-term FSRS interval derived from their stability and the+ * deck's desired retention.  */ object Scheduler {     const val DAY_MS: Long = 24L * 60 * 60 * 1000+    private const val MINUTE_MS: Long = 60L * 1000 -    /** Ease factor is never allowed below this SM-2 floor. */-    const val MIN_EASE = 1.3+    /** FSRS-5 default parameters (19 weights). */+    val DEFAULT_W = doubleArrayOf(+        0.40255, 1.18385, 3.173, 15.69105, 7.1949, 0.5345, 1.4604, 0.0046,+        1.54575, 0.1192, 1.01925, 1.9395, 0.11, 0.29605, 2.2698, 0.2315,+        2.9898, 0.51655, 0.6621,+    ) -    fun schedule(card: Card, grade: Grade, now: Long): Card {-        val q = grade.q+    const val DECAY = -0.5+    /** `FACTOR = 0.9^(1/DECAY) - 1` so that `interval == stability` at 90% retention. */+    val FACTOR = 0.9.pow(1.0 / DECAY) - 1.0 -        val repetitions: Int-        val intervalDays: Int-        if (q < 3) {-            // Failed recall: relearn from the start with a one-day interval.-            repetitions = 0-            intervalDays = 1+    private const val MIN_STABILITY = 0.01+    private const val MAX_STABILITY = 36500.0+    private const val MIN_DIFFICULTY = 1.0+    private const val MAX_DIFFICULTY = 10.0++    private const val AGAIN_STEP_MS = MINUTE_MS+    private const val HARD_STEP_MS = 6 * MINUTE_MS++    /** Probability of recall after [elapsedDays] given [stability] (in days). */+    fun retrievability(elapsedDays: Double, stability: Double): Double {+        if (stability <= 0.0) return 0.0+        return (1.0 + FACTOR * elapsedDays / stability).pow(DECAY)+    }++    /** Days until recall probability decays to [desiredRetention]. */+    fun nextIntervalDays(stability: Double, desiredRetention: Double): Double {+        val r = desiredRetention.coerceIn(0.01, 0.999)+        return (stability / FACTOR) * (r.pow(1.0 / DECAY) - 1.0)+    }++    private fun clampStability(s: Double) = s.coerceIn(MIN_STABILITY, MAX_STABILITY)+    private fun clampDifficulty(d: Double) = d.coerceIn(MIN_DIFFICULTY, MAX_DIFFICULTY)++    private fun initialStability(w: DoubleArray, grade: Grade) =+        clampStability(w[grade.value - 1])++    private fun initialDifficulty(w: DoubleArray, grade: Grade) =+        clampDifficulty(w[4] - exp(w[5] * (grade.value - 1)) + 1.0)++    private fun nextDifficulty(w: DoubleArray, difficulty: Double, grade: Grade): Double {+        val deltaD = -w[6] * (grade.value - 3)+        val dampened = difficulty + deltaD * (10.0 - difficulty) / 9.0+        val d0Easy = w[4] - exp(w[5] * (Grade.EASY.value - 1)) + 1.0+        return clampDifficulty(w[7] * d0Easy + (1.0 - w[7]) * dampened)+    }++    private fun stabilityAfterRecall(+        w: DoubleArray,+        difficulty: Double,+        stability: Double,+        retrievability: Double,+        grade: Grade,+    ): Double {+        val hardPenalty = if (grade == Grade.HARD) w[15] else 1.0+        val easyBonus = if (grade == Grade.EASY) w[16] else 1.0+        val increment = exp(w[8]) *+            (11.0 - difficulty) *+            stability.pow(-w[9]) *+            (exp(w[10] * (1.0 - retrievability)) - 1.0) *+            hardPenalty *+            easyBonus+        return clampStability(stability * (increment + 1.0))+    }++    private fun stabilityAfterForget(+        w: DoubleArray,+        difficulty: Double,+        stability: Double,+        retrievability: Double,+    ): Double {+        val forgotten = w[11] *+            difficulty.pow(-w[12]) *+            ((stability + 1.0).pow(w[13]) - 1.0) *+            exp(w[14] * (1.0 - retrievability))+        // Post-lapse stability can never exceed the prior value.+        return clampStability(minOf(forgotten, stability))+    }++    /**+     * Returns [card] updated for [grade] applied at [now] (epoch millis), using+     * [desiredRetention] (0..1) to size the next interval.+     */+    fun schedule(+        card: Card,+        grade: Grade,+        now: Long,+        desiredRetention: Double = 0.9,+    ): Card {+        val w = DEFAULT_W+        val firstReview = card.reps == 0 || card.state == CardState.NEW+        val elapsedDays =+            if (card.lastReview > 0) (now - card.lastReview).toDouble() / DAY_MS else 0.0++        val newDifficulty: Double+        val newStability: Double+        if (firstReview) {+            newDifficulty = initialDifficulty(w, grade)+            newStability = initialStability(w, grade)         } else {-            intervalDays = when (card.repetitions) {-                0 -> 1-                1 -> 6-                else -> (card.intervalDays * card.easeFactor).roundToInt()+            val r = retrievability(elapsedDays, card.stability)+            newDifficulty = nextDifficulty(w, clampDifficulty(card.difficulty), grade)+            newStability = if (grade == Grade.AGAIN) {+                stabilityAfterForget(w, newDifficulty, card.stability, r)+            } else {+                stabilityAfterRecall(w, newDifficulty, card.stability, r, grade)             }-            repetitions = card.repetitions + 1         } -        val easeFactor = (card.easeFactor + (0.1 - (5 - q) * (0.08 + (5 - q) * 0.02)))-            .coerceAtLeast(MIN_EASE)+        val wasReview = card.state == CardState.REVIEW+        val inLearning = card.state == CardState.LEARNING || card.state == CardState.RELEARNING+        val relearn = wasReview || card.state == CardState.RELEARNING++        val newState: Int+        val due: Long+        when {+            grade == Grade.AGAIN -> {+                newState = if (relearn) CardState.RELEARNING else CardState.LEARNING+                due = now + AGAIN_STEP_MS+            }+            grade == Grade.HARD && (firstReview || inLearning) -> {+                newState = if (relearn) CardState.RELEARNING else CardState.LEARNING+                due = now + HARD_STEP_MS+            }+            else -> {+                newState = CardState.REVIEW+                val days = nextIntervalDays(newStability, desiredRetention)+                    .roundToLong()+                    .coerceAtLeast(1)+                due = now + days * DAY_MS+            }+        }++        val lapses = card.lapses + if (grade == Grade.AGAIN && wasReview) 1 else 0          return card.copy(-            easeFactor = easeFactor,-            intervalDays = intervalDays,-            repetitions = repetitions,-            dueDate = now + intervalDays * DAY_MS,+            stability = newStability,+            difficulty = newDifficulty,+            state = newState,+            lastReview = now,+            lapses = lapses,+            reps = card.reps + 1,+            dueDate = due,         )     }++    /** A short human label for the interval [grade] would assign to [card]. */+    fun previewLabel(+        card: Card,+        grade: Grade,+        now: Long,+        desiredRetention: Double = 0.9,+    ): String = formatDuration(schedule(card, grade, now, desiredRetention).dueDate - now)++    private fun formatDuration(ms: Long): String {+        val minutes = ms / MINUTE_MS+        if (minutes < 60) return "${minutes.coerceAtLeast(1)}m"+        val hours = ms / (60 * MINUTE_MS)+        if (hours < 24) return "${hours}h"+        val days = ms / DAY_MS+        return when {+            days < 30 -> "${days}d"+            days < 365 -> "${days / 30}mo"+            else -> "${days / 365}y"+        }+    } }
flashcards/src/main/res/values/strings.xml
diff --git a/flashcards/src/main/res/values/strings.xml b/flashcards/src/main/res/values/strings.xmlindex 4350135590..d84ff342ea 100644--- a/flashcards/src/main/res/values/strings.xml+++ b/flashcards/src/main/res/values/strings.xml@@ -2,15 +2,21 @@     <!-- App name displayed in launcher -->     <string name="app_name">Flashcards</string> +    <!-- Bottom navigation tab labels. -->+    <string name="nav_decks">Decks</string>+    <string name="nav_stats">Stats</string>+    <string name="nav_settings">Settings</string>+     <!-- DeckListPage: FAB / dialog title to create a deck. Verb phrase. -->     <string name="new_deck">New deck</string>     <!-- DeckListPage: Placeholder hint for the deck name field. Noun. -->     <string name="deck_name">Deck name</string>-    <!-- DeckListPage: Subtitle summarising a deck's due and total card counts.-         %1$d = cards due for review, %2$d = total cards in the deck. -->-    <string name="deck_summary">%1$d due · %2$d cards</string>-    <!-- DeckListPage: Content description for the button that starts a review of a deck. -->-    <string name="review_deck">Review deck</string>+    <!-- DeckListPage: Subtitle summarising a deck's due, new and total card counts.+         %1$d = cards due for review, %2$d = new cards, %3$d = total cards. -->+    <string name="deck_summary">%1$d due · %2$d new · %3$d cards</string>+    <!-- DeckListPage: Empty state when no decks exist. -->+    <string name="no_decks">No decks yet</string>+    <string name="no_decks_hint">Tap + to create your first deck</string>     <!-- DeckListPage / CardListPage: Confirm dialog title before deleting. -->     <string name="delete">Delete</string>     <!-- DeckListPage: Confirm dialog message before deleting a deck.@@ -20,16 +26,25 @@     <!-- Generic dialog buttons. -->     <string name="add">Add</string>     <string name="cancel">Cancel</string>+    <string name="save">Save</string>      <!-- CardListPage: Button that starts a study session. Verb. -->     <string name="study">Study</string>     <!-- CardListPage: Empty state when a deck has no cards yet. -->     <string name="no_cards">No cards yet</string>+    <string name="no_cards_hint">Tap + to add a card, or import a CSV</string>+    <!-- CardListPage: Search field placeholder. -->+    <string name="search_cards">Search cards</string>+    <!-- CardListPage: Share sheet title when exporting a deck. -->+    <string name="share_deck">Share deck</string> -    <!-- CardEditPage: Placeholder hint for the front (question) field. Noun. -->+    <!-- CardEditPage: Titles for the editor. -->+    <string name="new_card">New card</string>+    <string name="edit_card">Edit card</str

Diff truncated.