flashcards: new spaced-repetition flashcards app
- Commit
2b2522feb52c130431825d1aa69bd4bb4b15e12b- Author
- Vayun Mathur <[email protected]>
- When
- 2026-08-11 20:22 UTC (3 months ago)
- Parents
6e91ae8
Diff
README.md
diff --git a/README.md b/README.mdindex 211bee415b..c09c567102 100644--- a/README.md+++ b/README.md@@ -48,6 +48,7 @@ Though some apps may have exceptions, generally a 64-bit device running at least | **Email** | [Homepage](https://ma.vayunmathur.com/apps/email) | [](https://f-droid.org/packages/com.vayunmathur.email) | [](https://api.vayunmathur.com/obtainium-link?name=Email&packageName=com.vayunmathur.email&apk=email-release.apk) | | **Files** | [Homepage](https://ma.vayunmathur.com/apps/files) | [](https://f-droid.org/packages/com.vayunmathur.files/) | [](https://api.vayunmathur.com/obtainium-link?name=Files&packageName=com.vayunmathur.files&apk=files-release.apk) | | **Find Family** | [Homepage](https://ma.vayunmathur.com/apps/findfamily) | [](https://f-droid.org/packages/com.vayunmathur.findfamily) | [](https://api.vayunmathur.com/obtainium-link?name=Find%20Family&packageName=com.vayunmathur.findfamily&apk=findfamily-release.apk) |+| **Flashcards** | [Homepage](https://ma.vayunmathur.com/apps/flashcards) | [](https://f-droid.org/packages/com.vayunmathur.flashcards/) | [](https://api.vayunmathur.com/obtainium-link?name=Flashcards&packageName=com.vayunmathur.flashcards&apk=flashcards-release.apk) | | **Food Delivery (US only)** | [Homepage](https://ma.vayunmathur.com/apps/fooddelivery) | [](https://f-droid.org/packages/com.vayunmathur.fooddelivery/) | [](https://api.vayunmathur.com/obtainium-link?name=Food%20Delivery&packageName=com.vayunmathur.fooddelivery&apk=fooddelivery-release.apk) | | **Health** | [Homepage](https://ma.vayunmathur.com/apps/health) | [](https://f-droid.org/packages/com.vayunmathur.health/) | [](https://api.vayunmathur.com/obtainium-link?name=Health&packageName=com.vayunmathur.health&apk=health-release.apk) | | **Keyboard** | [Homepage](https://ma.vayunmathur.com/apps/keyboard) | [](https://f-droid.org/packages/com.vayunmathur.keyboard/) | [](https://api.vayunmathur.com/obtainium-link?name=Keyboard&packageName=com.vayunmathur.keyboard&apk=keyboard-release.apk) |
flashcards/build.gradle.kts
diff --git a/flashcards/build.gradle.kts b/flashcards/build.gradle.ktsnew file mode 100644index 0000000000..245bfb914f--- /dev/null+++ b/flashcards/build.gradle.kts@@ -0,0 +1,22 @@+plugins {+ id("common-conventions-app")+ // Listing screenshots come from Compose previews (src/screenshotTest), not from an+ // instrumented test on a device. Same `:flashcards:metadata` task name either way.+ id("common-conventions-preview-metadata")+ alias(libs.plugins.ksp)+}++launcherIcon {+ symbol = "style"+}++android {+ defaultConfig {+ applicationId = "com.vayunmathur.flashcards"+ }+}++dependencies {+ implementRoom(libs)+ implementation(project(":library:room"))+}
flashcards/src/main/AndroidManifest.xml
diff --git a/flashcards/src/main/AndroidManifest.xml b/flashcards/src/main/AndroidManifest.xmlnew file mode 100644index 0000000000..a5e7620c16--- /dev/null+++ b/flashcards/src/main/AndroidManifest.xml@@ -0,0 +1,25 @@+<?xml version="1.0" encoding="utf-8"?>+<manifest xmlns:android="http://schemas.android.com/apk/res/android">++ <application+ android:allowBackup="true"+ android:backupAgent=".util.AppBackupAgent"+ android:dataExtractionRules="@xml/data_extraction_rules"+ android:icon="@mipmap/ic_launcher"+ android:label="@string/app_name"+ android:roundIcon="@mipmap/ic_launcher"+ android:supportsRtl="true"+ android:theme="@style/Theme.General">+ <activity+ android:configChanges="mcc|mnc|colorMode|density|fontScale|fontWeightAdjustment|keyboard|keyboardHidden|layoutDirection|navigation|orientation|screenLayout|screenSize|smallestScreenSize|touchscreen|uiMode"+ android:name=".MainActivity"+ android:exported="true"+ android:theme="@style/Theme.General">+ <intent-filter>+ <action android:name="android.intent.action.MAIN" />+ <category android:name="android.intent.category.LAUNCHER" />+ </intent-filter>+ </activity>+ </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.ktnew file mode 100644index 0000000000..7991c56193--- /dev/null+++ b/flashcards/src/main/java/com/vayunmathur/flashcards/MainActivity.kt@@ -0,0 +1,93 @@+package com.vayunmathur.flashcards++import android.os.Bundle+import androidx.activity.ComponentActivity+import androidx.activity.compose.setContent+import androidx.activity.enableEdgeToEdge+import androidx.activity.viewModels+import androidx.compose.runtime.getValue+import androidx.compose.runtime.mutableStateOf+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.ui.CardEditPage+import com.vayunmathur.flashcards.ui.CardListPage+import com.vayunmathur.flashcards.ui.DeckListPage+import com.vayunmathur.flashcards.ui.ReviewPage+import com.vayunmathur.flashcards.util.FlashcardsViewModel+import com.vayunmathur.flashcards.util.FlashcardsViewModelFactory+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.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+import kotlinx.serialization.Serializable++class MainActivity : ComponentActivity() {+ private lateinit var deckDao: DeckDao+ private lateinit var cardDao: CardDao+ private val viewModel: FlashcardsViewModel by viewModels {+ FlashcardsViewModelFactory(application, deckDao, cardDao)+ }++ override fun onCreate(savedInstanceState: Bundle?) {+ super.onCreate(savedInstanceState)+ enableEdgeToEdge()++ val ready = mutableStateOf(false)+ lifecycleScope.launch(Dispatchers.IO) {+ val db = buildDatabase<FlashcardsDatabase>(dbName = DB_NAME)+ deckDao = db.deckDao()+ cardDao = db.cardDao()+ withContext(Dispatchers.Main) { ready.value = true }+ }++ setContent {+ DynamicTheme {+ if (ready.value) Navigation(viewModel)+ }+ }+ }+}++@Serializable+sealed interface Route : NavKey {+ @Serializable+ data object DeckList : Route++ @Serializable+ data class CardList(val deckId: Long) : Route++ @Serializable+ data class CardEdit(val deckId: Long, val cardId: Long) : Route++ @Serializable+ data class Review(val deckId: Long) : Route+}++@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)+ }+ }+}
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.ktnew file mode 100644index 0000000000..2f46424b13--- /dev/null+++ b/flashcards/src/main/java/com/vayunmathur/flashcards/data/Card.kt@@ -0,0 +1,29 @@+package com.vayunmathur.flashcards.data++import androidx.room.Entity+import androidx.room.PrimaryKey+import com.vayunmathur.library.util.ReorderableDatabaseItem+import kotlinx.serialization.Serializable++/**+ * A single plain-text flashcard plus its SM-2 spaced-repetition state.+ *+ * [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.+ */+@Serializable+@Entity+data class Card(+ @PrimaryKey(autoGenerate = true) override val id: Long = 0,+ val deckId: Long,+ val front: String,+ val back: String,+ 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)+}
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.ktnew file mode 100644index 0000000000..bf135abd3b--- /dev/null+++ b/flashcards/src/main/java/com/vayunmathur/flashcards/data/Deck.kt@@ -0,0 +1,16 @@+package com.vayunmathur.flashcards.data++import androidx.room.Entity+import androidx.room.PrimaryKey+import com.vayunmathur.library.util.ReorderableDatabaseItem+import kotlinx.serialization.Serializable++@Serializable+@Entity+data class Deck(+ @PrimaryKey(autoGenerate = true) override val id: Long = 0,+ val name: String,+ 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.ktnew file mode 100644index 0000000000..dd2e3bdf93--- /dev/null+++ b/flashcards/src/main/java/com/vayunmathur/flashcards/data/FlashcardsDatabase.kt@@ -0,0 +1,65 @@+package com.vayunmathur.flashcards.data++import android.content.Context+import androidx.room.Dao+import androidx.room.Database+import androidx.room.Delete+import androidx.room.Query+import androidx.room.RoomDatabase+import androidx.room.Upsert+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"++/** Backup config shared by [AppBackupAgent] and the in-app backup buttons. */+fun flashcardsDbConfigs(context: Context): List<Pair<String, String>> =+ listOf(DB_NAME to DatabaseHelper(context).getPassphrase())++@Dao+interface DeckDao {+ @Query("SELECT * FROM Deck")+ fun getAllFlow(): Flow<List<Deck>>++ @Upsert+ suspend fun upsert(value: Deck): Long++ @Delete+ suspend fun delete(value: Deck): Int+}++@Dao+interface CardDao {+ @Query("SELECT * FROM Card")+ fun getAllFlow(): Flow<List<Card>>++ @Query("SELECT * FROM Card WHERE deckId = :deckId")+ fun getByDeckFlow(deckId: Long): Flow<List<Card>>++ @Query("SELECT * FROM Card WHERE deckId = :deckId AND dueDate <= :now")+ fun getDueByDeckFlow(deckId: Long, now: Long): Flow<List<Card>>++ @Query("SELECT * FROM Card WHERE id = :id")+ fun getByIdFlow(id: Long): Flow<Card?>++ @Upsert+ suspend fun upsert(value: Card): Long++ @Delete+ suspend fun delete(value: Card): Int++ @Query("DELETE FROM Card WHERE deckId = :deckId")+ suspend fun deleteByDeck(deckId: Long)+}++@Database(entities = [Deck::class, Card::class], version = 1, exportSchema = false)+abstract class FlashcardsDatabase : RoomDatabase() {+ abstract fun deckDao(): DeckDao+ abstract fun cardDao(): CardDao++ companion object : DatabaseMigrations {+ override val migrations = emptyList<Migration>()+ }+}
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.ktnew file mode 100644index 0000000000..b228102e47--- /dev/null+++ b/flashcards/src/main/java/com/vayunmathur/flashcards/ui/CardEditPage.kt@@ -0,0 +1,128 @@+package com.vayunmathur.flashcards.ui++import androidx.compose.foundation.layout.Column+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.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.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.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.IconButton+import com.vayunmathur.library.ui.IconDelete+import com.vayunmathur.library.ui.IconNavigation+import com.vayunmathur.library.ui.IconSave+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.+ */+@Composable+fun CardEditPage(+ backStack: NavBackStack<Route>,+ viewModel: FlashcardsViewModel,+ deckId: Long,+ cardId: Long,+) {+ val dbCard by remember(cardId) { viewModel.cardById(cardId) }+ .collectAsStateWithLifecycle(null)++ var frontText by remember { mutableStateOf("") }+ var backText by remember { mutableStateOf("") }++ LaunchedEffect(dbCard) {+ dbCard?.let {+ frontText = it.front+ backText = it.back+ }+ }++ val actions = object : CardEditActions {+ override fun back() { backStack.pop() }+ override fun setFront(front: String) { frontText = front }+ override fun setBack(back: String) { backText = back }+ override fun save() {+ val card = dbCard?.copy(front = frontText, back = backText)+ ?: Card(deckId = deckId, front = frontText, back = backText)+ viewModel.upsertCard(card)+ backStack.pop()+ }+ override fun deleteCard() {+ dbCard?.let { viewModel.deleteCard(it) }+ backStack.pop()+ }+ }++ CardEditScreen(+ state = CardEditUiState(front = frontText, back = backText, 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].+ */+@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() }+ },+ )+ },+ ) { paddingValues ->+ Column(+ Modifier+ .padding(paddingValues)+ .fillMaxSize()+ .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),+ )+ OutlinedTextField(+ value = state.back,+ onValueChange = { actions.setBack(it) },+ label = { Text(stringResource(R.string.back)) },+ modifier = Modifier.fillMaxWidth().padding(top = 16.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.ktnew file mode 100644index 0000000000..2a9a373324--- /dev/null+++ b/flashcards/src/main/java/com/vayunmathur/flashcards/ui/CardListPage.kt@@ -0,0 +1,124 @@+package com.vayunmathur.flashcards.ui++import androidx.compose.foundation.clickable+import androidx.compose.foundation.layout.Column+import androidx.compose.foundation.layout.fillMaxSize+import androidx.compose.foundation.layout.fillMaxWidth+import androidx.compose.foundation.layout.padding+import androidx.compose.foundation.lazy.LazyColumn+import androidx.compose.foundation.lazy.items+import androidx.compose.runtime.Composable+import androidx.compose.runtime.getValue+import androidx.compose.runtime.remember+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.Card+import com.vayunmathur.flashcards.util.CardListActions+import com.vayunmathur.flashcards.util.CardListUiState+import com.vayunmathur.flashcards.util.FlashcardsViewModel+import com.vayunmathur.library.ui.Button+import com.vayunmathur.library.ui.ExperimentalMaterial3Api+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.ListItem+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 deck with [deckId] to the stateless [CardListScreen]. */+@Composable+fun CardListPage(+ backStack: NavBackStack<Route>,+ viewModel: FlashcardsViewModel,+ deckId: Long,+) {+ val decks by viewModel.decks.collectAsStateWithLifecycle()+ val cards by remember(deckId) { viewModel.cardsFor(deckId) }+ .collectAsStateWithLifecycle(emptyList())++ val deckName = decks.firstOrNull { it.id == deckId }?.name ?: ""+ val now = System.currentTimeMillis()++ val actions = remember(backStack, viewModel, deckId) {+ object : CardListActions {+ override fun back() { backStack.pop() }+ override fun openCard(id: Long) { backStack.add(Route.CardEdit(deckId, id)) }+ 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)) }+ }+ }++ CardListScreen(+ state = CardListUiState(+ deckName = deckName,+ cards = cards,+ dueCount = cards.count { it.dueDate <= now },+ ),+ actions = actions,+ )+}++/**+ * 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)+@Composable+fun CardListScreen(state: CardListUiState, actions: CardListActions) {+ Scaffold(+ topBar = {+ TopAppBar(+ title = { Text(state.deckName) },+ navigationIcon = { IconNavigation { actions.back() } },+ )+ },+ floatingActionButton = {+ FloatingActionButton(onClick = { actions.addCard() }) {+ IconAdd()+ }+ },+ ) { paddingValues ->+ Column(Modifier.fillMaxSize().padding(paddingValues)) {+ if (state.dueCount > 0) {+ Button(+ onClick = { actions.study() },+ modifier = Modifier.fillMaxWidth().padding(horizontal = 16.dp, vertical = 8.dp),+ ) {+ Text(stringResource(R.string.study))+ }+ }+ if (state.cards.isEmpty()) {+ Text(+ stringResource(R.string.no_cards),+ modifier = Modifier.fillMaxWidth().padding(32.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) },+ )+ }+ }+ }+ }+ }+}
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.ktnew file mode 100644index 0000000000..3d7bd3cfb9--- /dev/null+++ b/flashcards/src/main/java/com/vayunmathur/flashcards/ui/DeckListPage.kt@@ -0,0 +1,197 @@+package com.vayunmathur.flashcards.ui++import androidx.activity.compose.BackHandler+import androidx.compose.foundation.ExperimentalFoundationApi+import androidx.compose.foundation.combinedClickable+import androidx.compose.foundation.layout.RowScope+import androidx.compose.foundation.layout.fillMaxSize+import androidx.compose.foundation.layout.fillMaxWidth+import androidx.compose.foundation.layout.padding+import androidx.compose.foundation.lazy.LazyColumn+import androidx.compose.foundation.lazy.items+import androidx.compose.runtime.Composable+import androidx.compose.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.platform.LocalContext+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.Deck+import com.vayunmathur.flashcards.data.flashcardsDbConfigs+import com.vayunmathur.flashcards.util.DeckListActions+import com.vayunmathur.flashcards.util.DeckListUiState+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.BackupButtons+import com.vayunmathur.library.ui.ConfirmDialog+import com.vayunmathur.library.ui.ExperimentalMaterial3Api+import com.vayunmathur.library.ui.FloatingActionButton+import com.vayunmathur.library.ui.IconAdd+import com.vayunmathur.library.ui.IconButton+import com.vayunmathur.library.ui.IconPlay+import com.vayunmathur.library.ui.ListItem+import com.vayunmathur.library.ui.Scaffold+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.util.NavBackStack++/** Binds [FlashcardsViewModel] and the nav back stack to the stateless [DeckListScreen]. */+@Composable+fun DeckListPage(backStack: NavBackStack<Route>, viewModel: FlashcardsViewModel) {+ val context = LocalContext.current+ val decks by viewModel.decks.collectAsStateWithLifecycle()+ val cards by viewModel.cards.collectAsStateWithLifecycle()++ val now = System.currentTimeMillis()+ val summaries = decks.map { deck ->+ val deckCards = cards.filter { it.deckId == deck.id }+ DeckSummary(+ deck = deck,+ dueCount = deckCards.count { it.dueDate <= now },+ totalCount = deckCards.size,+ )+ }++ 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 deleteDeck(deck: Deck) { viewModel.deleteDeck(deck) }+ override fun startReview(deckId: Long) { backStack.add(Route.Review(deckId)) }+ }+ }++ DeckListScreen(+ state = DeckListUiState(decks = summaries),+ actions = actions,+ backupButtons = {+ BackupButtons(+ dbConfigs = remember { flashcardsDbConfigs(context) },+ dbCodec = SqlCipherDbCodec,+ extraFiles = emptyList(),+ )+ },+ )+}++/**+ * The deck list, with no dependency on the ViewModel or the back stack so it can be+ * rendered from a `@Preview` — see `src/screenshotTest`, which is where the store listing+ * images come from.+ */+@OptIn(ExperimentalMaterial3Api::class, ExperimentalFoundationApi::class)+@Composable+fun DeckListScreen(+ state: DeckListUiState,+ actions: DeckListActions,+ /** Top-bar backup/restore buttons; empty in a preview, which has no database. */+ backupButtons: @Composable RowScope.() -> Unit = {},+) {+ 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,+ )+ },+ floatingActionButton = {+ FloatingActionButton(onClick = { showAddDialog = true }) {+ IconAdd()+ }+ },+ ) { paddingValues ->+ LazyColumn(+ 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,+ ),+ )+ },+ 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 },+ ),+ )+ }+ }+ }++ if (showAddDialog) {+ AddDeckDialog(+ onAdd = { actions.addDeck(it) },+ onDismiss = { showAddDialog = false },+ )+ }++ pendingDelete?.let { deck ->+ ConfirmDialog(+ title = stringResource(R.string.delete),+ message = stringResource(R.string.delete_deck_message, deck.name),+ confirmLabel = stringResource(R.string.delete),+ dismissLabel = stringResource(R.string.cancel),+ destructive = true,+ onConfirm = {+ actions.deleteDeck(deck)+ pendingDelete = null+ },+ onDismiss = { pendingDelete = null },+ )+ }+}++@OptIn(ExperimentalMaterial3Api::class)+@Composable+private fun AddDeckDialog(onAdd: (String) -> Unit, onDismiss: () -> Unit) {+ var name by remember { mutableStateOf("") }+ BackHandler { onDismiss() }+ AlertDialog(+ onDismissRequest = onDismiss,+ title = { Text(stringResource(R.string.new_deck)) },+ text = {+ TextField(+ value = name,+ onValueChange = { name = it },+ singleLine = true,+ placeholder = { Text(stringResource(R.string.deck_name)) },+ modifier = Modifier.fillMaxWidth().padding(top = 8.dp),+ )+ },+ confirmButton = {+ TextButton(onClick = {+ if (name.isNotBlank()) onAdd(name.trim())+ onDismiss()+ }) { Text(stringResource(R.string.add)) }+ },+ dismissButton = {+ TextButton(onClick = onDismiss) { Text(stringResource(R.string.cancel)) }+ },+ )+}
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.ktnew file mode 100644index 0000000000..c9d2b5d472--- /dev/null+++ b/flashcards/src/main/java/com/vayunmathur/flashcards/ui/ReviewPage.kt@@ -0,0 +1,172 @@+package com.vayunmathur.flashcards.ui++import androidx.compose.foundation.layout.Arrangement+import androidx.compose.foundation.layout.Box+import androidx.compose.foundation.layout.Column+import androidx.compose.foundation.layout.Row+import androidx.compose.foundation.layout.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.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.Alignment+import androidx.compose.ui.Modifier+import androidx.compose.ui.res.stringResource+import androidx.compose.ui.text.style.TextAlign+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.Grade+import com.vayunmathur.flashcards.util.ReviewActions+import com.vayunmathur.flashcards.util.ReviewUiState+import com.vayunmathur.library.ui.Button+import com.vayunmathur.library.ui.ExperimentalMaterial3Api+import com.vayunmathur.library.ui.HorizontalDivider+import com.vayunmathur.library.ui.IconNavigation+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++/**+ * 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.+ */+@Composable+fun ReviewPage(+ backStack: NavBackStack<Route>,+ viewModel: FlashcardsViewModel,+ deckId: Long,+) {+ val due by remember(deckId) { viewModel.dueCardsFor(deckId) }+ .collectAsStateWithLifecycle(emptyList())++ val current = due.firstOrNull()++ ReviewScreen(+ state = ReviewUiState(+ front = current?.front ?: "",+ back = current?.back ?: "",+ remaining = due.size,+ done = current == null,+ ),+ actions = object : ReviewActions {+ override fun back() { backStack.pop() }+ override fun grade(grade: Grade) {+ current?.let { viewModel.gradeCard(it, grade) }+ }+ },+ )+}++/**+ * A single review card, with no dependency on the ViewModel or the back stack so it can be+ * 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,+ actions: ReviewActions,+ 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,+ ) {+ Text(+ stringResource(R.string.review_done),+ style = MaterialTheme.typography.headlineSmall,+ )+ }+ return@Scaffold+ }++ Column(Modifier.fillMaxSize().padding(paddingValues)) {+ Column(+ Modifier+ .weight(1f)+ .fillMaxWidth()+ .verticalScroll(rememberScrollState())+ .padding(24.dp),+ horizontalAlignment = Alignment.CenterHorizontally,+ verticalArrangement = Arrangement.Center,+ ) {+ Text(+ state.front,+ style = MaterialTheme.typography.headlineSmall,+ textAlign = TextAlign.Center,+ )+ if (revealed) {+ HorizontalDivider(Modifier.padding(vertical = 24.dp))+ Text(+ state.back,+ 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) {+ 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))+ }+}++@Composable+private fun GradeButton(+ labelRes: Int,+ grade: Grade,+ onGrade: (Grade) -> Unit,+ modifier: Modifier = Modifier,+) {+ OutlinedButton(onClick = { onGrade(grade) }, modifier = modifier) {+ Text(stringResource(labelRes))+ }+}
flashcards/src/main/java/com/vayunmathur/flashcards/util/AppBackupAgent.kt
diff --git a/flashcards/src/main/java/com/vayunmathur/flashcards/util/AppBackupAgent.kt b/flashcards/src/main/java/com/vayunmathur/flashcards/util/AppBackupAgent.ktnew file mode 100644index 0000000000..15247fe77a--- /dev/null+++ b/flashcards/src/main/java/com/vayunmathur/flashcards/util/AppBackupAgent.kt@@ -0,0 +1,16 @@+package com.vayunmathur.flashcards.util++import com.vayunmathur.library.room.SqlCipherDbCodec+import com.vayunmathur.library.util.BaseBackupAgent+import com.vayunmathur.flashcards.data.flashcardsDbConfigs+import java.io.File++class AppBackupAgent : BaseBackupAgent() {+ override val dbCodec = SqlCipherDbCodec++ override val dbConfigs: List<Pair<String, String>>+ get() = flashcardsDbConfigs(this)++ override val extraFiles: List<File>+ get() = emptyList()+}
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.ktnew file mode 100644index 0000000000..ce6c9ebf0f--- /dev/null+++ b/flashcards/src/main/java/com/vayunmathur/flashcards/util/FlashcardsUiContract.kt@@ -0,0 +1,94 @@+package com.vayunmathur.flashcards.util++import com.vayunmathur.flashcards.data.Card+import com.vayunmathur.flashcards.data.Deck++/**+ * The UI contract between [FlashcardsViewModel] plus the nav back stack and the screens.+ *+ * Screens take a state value and an actions interface rather than the ViewModel itself, so+ * 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.+ */++/** A deck plus its derived review counts, as drawn on the deck list. */+data class DeckSummary(+ val deck: Deck,+ val dueCount: Int = 0,+ val totalCount: Int = 0,+)++/** Everything the deck list draws. */+data class DeckListUiState(+ val decks: List<DeckSummary> = emptyList(),+)++interface DeckListActions {+ fun openDeck(id: Long) {}+ fun addDeck(name: String) {}+ fun deleteDeck(deck: Deck) {}+ fun startReview(deckId: Long) {}++ companion object {+ val Noop: DeckListActions = object : DeckListActions {}+ }+}++/** Everything the card list draws for a single deck. */+data class CardListUiState(+ val deckName: String = "",+ val cards: List<Card> = emptyList(),+ val dueCount: Int = 0,+)++interface CardListActions {+ fun back() {}+ fun openCard(id: Long) {}+ fun addCard() {}+ fun deleteCard(card: Card) {}+ fun study() {}++ companion object {+ val Noop: CardListActions = object : CardListActions {}+ }+}++/** Everything the card editor draws: the two plain-text sides. */+data class CardEditUiState(+ val front: String = "",+ val back: String = "",+ val isNew: Boolean = true,+)++interface CardEditActions {+ fun back() {}+ fun setFront(front: String) {}+ fun setBack(back: String) {}+ fun save() {}+ fun deleteCard() {}++ companion object {+ val Noop: CardEditActions = object : CardEditActions {}+ }+}++/** 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. */+ val remaining: Int = 0,+ /** True when nothing is due, i.e. the session is complete. */+ val done: Boolean = false,+)++interface ReviewActions {+ fun back() {}+ fun grade(grade: Grade) {}++ companion object {+ val Noop: ReviewActions = object : ReviewActions {}+ }+}
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.ktnew file mode 100644index 0000000000..e1bff7c658--- /dev/null+++ b/flashcards/src/main/java/com/vayunmathur/flashcards/util/FlashcardsViewModel.kt@@ -0,0 +1,90 @@+package com.vayunmathur.flashcards.util++import android.app.Application+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.Deck+import com.vayunmathur.flashcards.data.DeckDao+import kotlinx.coroutines.Dispatchers+import kotlinx.coroutines.flow.Flow+import kotlinx.coroutines.flow.SharingStarted+import kotlinx.coroutines.flow.StateFlow+import kotlinx.coroutines.flow.stateIn+import kotlinx.coroutines.launch++/**+ * 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.+ */+class FlashcardsViewModel(+ application: Application,+ private val deckDao: DeckDao,+ private val cardDao: CardDao,+) : AndroidViewModel(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. */+ 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 deleteDeck(deck: Deck) {+ viewModelScope.launch(Dispatchers.IO) {+ cardDao.deleteByDeck(deck.id)+ deckDao.delete(deck)+ }+ }++ fun upsertCard(card: Card) {+ viewModelScope.launch(Dispatchers.IO) { cardDao.upsert(card) }+ }++ fun deleteCard(card: Card) {+ viewModelScope.launch(Dispatchers.IO) { cardDao.delete(card) }+ }++ fun gradeCard(card: Card, grade: Grade) {+ viewModelScope.launch(Dispatchers.IO) {+ cardDao.upsert(Scheduler.schedule(card, grade, System.currentTimeMillis()))+ }+ }+}++/** Factory for constructing [FlashcardsViewModel] with the DAOs. */+class FlashcardsViewModelFactory(+ private val application: Application,+ private val deckDao: DeckDao,+ private val cardDao: CardDao,+) : 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+ }+}
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.ktnew file mode 100644index 0000000000..3569203a96--- /dev/null+++ b/flashcards/src/main/java/com/vayunmathur/flashcards/util/Scheduler.kt@@ -0,0 +1,57 @@+package com.vayunmathur.flashcards.util++import com.vayunmathur.flashcards.data.Card+import kotlin.math.roundToInt++/**+ * 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).+ */+enum class Grade(val q: Int) {+ AGAIN(2),+ HARD(3),+ GOOD(4),+ EASY(5),+}++/**+ * 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.+ */+object Scheduler {+ const val DAY_MS: Long = 24L * 60 * 60 * 1000++ /** Ease factor is never allowed below this SM-2 floor. */+ const val MIN_EASE = 1.3++ fun schedule(card: Card, grade: Grade, now: Long): Card {+ val q = grade.q++ val repetitions: Int+ val intervalDays: Int+ if (q < 3) {+ // Failed recall: relearn from the start with a one-day interval.+ repetitions = 0+ intervalDays = 1+ } else {+ intervalDays = when (card.repetitions) {+ 0 -> 1+ 1 -> 6+ else -> (card.intervalDays * card.easeFactor).roundToInt()+ }+ repetitions = card.repetitions + 1+ }++ val easeFactor = (card.easeFactor + (0.1 - (5 - q) * (0.08 + (5 - q) * 0.02)))+ .coerceAtLeast(MIN_EASE)++ return card.copy(+ easeFactor = easeFactor,+ intervalDays = intervalDays,+ repetitions = repetitions,+ dueDate = now + intervalDays * DAY_MS,+ )+ }+}
flashcards/src/main/res/values/strings.xml
diff --git a/flashcards/src/main/res/values/strings.xml b/flashcards/src/main/res/values/strings.xmlnew file mode 100644index 0000000000..798323f845--- /dev/null+++ b/flashcards/src/main/res/values/strings.xml@@ -0,0 +1,43 @@+<resources xmlns:xliff="urn:oasis:names:tc:xliff:document:1.2">+ <!-- App name displayed in launcher -->+ <string name="app_name">MA Flashcards</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 / CardListPage: Confirm dialog title before deleting. -->+ <string name="delete">Delete</string>+ <!-- DeckListPage: Confirm dialog message before deleting a deck.+ %1$s = deck name. -->+ <string name="delete_deck_message">Delete \"%1$s\" and all its cards?</string>++ <!-- Generic dialog buttons. -->+ <string name="add">Add</string>+ <string name="cancel">Cancel</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>++ <!-- CardEditPage: Placeholder hint for the front (question) field. Noun. -->+ <string name="front">Front</string>+ <!-- CardEditPage: Placeholder hint for the back (answer) field. Noun. -->+ <string name="back">Back</string>++ <!-- ReviewPage: Button that reveals the answer side of a card. -->+ <string name="show_answer">Show answer</string>+ <!-- ReviewPage: Grade buttons for spaced-repetition scoring. -->+ <string name="grade_again">Again</string>+ <string name="grade_hard">Hard</string>+ <string name="grade_good">Good</string>+ <string name="grade_easy">Easy</string>+ <!-- ReviewPage: Shown when there are no more cards due in the session. -->+ <string name="review_done">All caught up!</string>+</resources>
flashcards/src/main/res/xml/data_extraction_rules.xml
diff --git a/flashcards/src/main/res/xml/data_extraction_rules.xml b/flashcards/src/main/res/xml/data_extraction_rules.xmlnew file mode 100644index 0000000000..88487e520b--- /dev/null+++ b/flashcards/src/main/res/xml/data_extraction_rules.xml@@ -0,0 +1,24 @@+<?xml version="1.0" encoding="utf-8"?>+<!-- Overrides the permissive default in the shared :library module.++ Storage audited:+ database/flashcards-db FlashcardsDatabase (Deck, Card): the user's decks and+ cards plus their spaced-repetition schedule. User content.+ file/datastore_default.preferences_pb app settings.+ sharedpref/secure_prefs keystore-wrapped SQLCipher passphrase.++ Decks and cards are user-authored content worth restoring on a new device, so both+ channels carry the flashcards database. Cloud backup is gated on device encryption+ because card text can contain anything. Caches and the keystore-bound passphrase are+ left out by the allowlist. -->+<data-extraction-rules>+ <cloud-backup disableIfNoEncryptionCapabilities="true">+ <!-- Whole-domain include so the -wal/-shm sidecars travel with the database. -->+ <include domain="database" path="." />+ <include domain="file" path="datastore_default.preferences_pb" />+ </cloud-backup>+ <device-transfer>+ <include domain="database" path="." />+ <include domain="file" path="datastore_default.preferences_pb" />+ </device-transfer>+</data-extraction-rules>
flashcards/src/screenshotTest/kotlin/com/vayunmathur/flashcards/ui/MetadataPreviews.kt
diff --git a/flashcards/src/screenshotTest/kotlin/com/vayunmathur/flashcards/ui/MetadataPreviews.kt b/flashcards/src/screenshotTest/kotlin/com/vayunmathur/flashcards/ui/MetadataPreviews.ktnew file mode 100644index 0000000000..bb3bba33ca--- /dev/null+++ b/flashcards/src/screenshotTest/kotlin/com/vayunmathur/flashcards/ui/MetadataPreviews.kt@@ -0,0 +1,93 @@+package com.vayunmathur.flashcards.ui++import androidx.compose.runtime.Composable+import androidx.compose.ui.tooling.preview.Preview+import com.android.tools.screenshot.PreviewTest+import com.vayunmathur.flashcards.data.Card+import com.vayunmathur.flashcards.data.Deck+import com.vayunmathur.flashcards.util.CardListActions+import com.vayunmathur.flashcards.util.CardListUiState+import com.vayunmathur.flashcards.util.DeckListActions+import com.vayunmathur.flashcards.util.DeckListUiState+import com.vayunmathur.flashcards.util.DeckSummary+import com.vayunmathur.flashcards.util.ReviewActions+import com.vayunmathur.flashcards.util.ReviewUiState+import com.vayunmathur.library.ui.DynamicTheme++/** Phone-shaped, roughly 1080x2340 at xxhdpi — comfortably above the F-Droid minimum. */+private const val PHONE = "spec:width=411dp,height=891dp,dpi=420"++/**+ * Store listing images for `:flashcards`. See `common-conventions-preview-metadata`.+ *+ * Each preview needs @PreviewTest as well as @Preview: @Preview alone renders in Studio but+ * is not collected as a screenshot test. Previews must also be class members, not top-level+ * functions. Order comes from the function names (Preview1…, Preview2…).+ *+ * Everything here is a literal — no ViewModel, no database, no device — which is also what+ * makes the images reproducible from a clean checkout.+ */+class MetadataPreviews {++ private val deckSamples = listOf(+ DeckSummary(Deck(id = 1, name = "Spanish Vocabulary", position = 0.0), dueCount = 12, totalCount = 84),+ DeckSummary(Deck(id = 2, name = "World Capitals", position = 1.0), dueCount = 5, totalCount = 50),+ DeckSummary(Deck(id = 3, name = "Kotlin Idioms", position = 2.0), dueCount = 0, totalCount = 30),+ DeckSummary(Deck(id = 4, name = "Anatomy 101", position = 3.0), dueCount = 23, totalCount = 120),+ DeckSummary(Deck(id = 5, name = "Guitar Chords", position = 4.0), dueCount = 3, totalCount = 18),+ )++ private val cardSamples = listOf(+ Card(id = 1, deckId = 1, front = "la manzana", back = "the apple"),+ Card(id = 2, deckId = 1, front = "el perro", back = "the dog"),+ Card(id = 3, deckId = 1, front = "la biblioteca", back = "the library"),+ Card(id = 4, deckId = 1, front = "el aeropuerto", back = "the airport"),+ Card(id = 5, deckId = 1, front = "la playa", back = "the beach"),+ )++ @PreviewTest+ @Preview(name = "1-decks", device = PHONE, showSystemUi = true)+ @Composable+ fun Preview1Decks() {+ DynamicTheme(darkTheme = true) {+ DeckListScreen(+ state = DeckListUiState(decks = deckSamples),+ actions = DeckListActions.Noop,+ )+ }+ }++ @PreviewTest+ @Preview(name = "2-review", device = PHONE, showSystemUi = true)+ @Composable+ fun Preview2Review() {+ DynamicTheme(darkTheme = true) {+ ReviewScreen(+ state = ReviewUiState(+ front = "la biblioteca",+ back = "the library",+ remaining = 12,+ done = false,+ ),+ actions = ReviewActions.Noop,+ initialRevealed = true,+ )+ }+ }++ @PreviewTest+ @Preview(name = "3-cards", device = PHONE, showSystemUi = true)+ @Composable+ fun Preview3Cards() {+ DynamicTheme(darkTheme = true) {+ CardListScreen(+ state = CardListUiState(+ deckName = "Spanish Vocabulary",+ cards = cardSamples,+ dueCount = 12,+ ),+ actions = CardListActions.Noop,+ )+ }+ }+}
flashcards/src/test/java/com/vayunmathur/flashcards/util/SchedulerTest.kt
diff --git a/flashcards/src/test/java/com/vayunmathur/flashcards/util/SchedulerTest.kt b/flashcards/src/test/java/com/vayunmathur/flashcards/util/SchedulerTest.ktnew file mode 100644index 0000000000..34568b81b4--- /dev/null+++ b/flashcards/src/test/java/com/vayunmathur/flashcards/util/SchedulerTest.kt@@ -0,0 +1,75 @@+package com.vayunmathur.flashcards.util++import com.vayunmathur.flashcards.data.Card+import kotlin.test.Test+import kotlin.test.assertEquals+import kotlin.test.assertTrue++class SchedulerTest {++ private val now = 1_000_000_000_000L++ private fun card(+ easeFactor: Double = 2.5,+ intervalDays: Int = 0,+ repetitions: Int = 0,+ ) = Card(+ id = 1,+ deckId = 1,+ front = "q",+ back = "a",+ easeFactor = easeFactor,+ intervalDays = intervalDays,+ repetitions = repetitions,+ )++ @Test+ fun againResetsIntervalAndRepetitions() {+ val graded = Scheduler.schedule(+ card(intervalDays = 20, repetitions = 5),+ Grade.AGAIN,+ now,+ )+ assertEquals(0, graded.repetitions)+ assertEquals(1, graded.intervalDays)+ assertEquals(now + Scheduler.DAY_MS, graded.dueDate)+ }++ @Test+ fun firstSuccessIsOneDay() {+ val graded = Scheduler.schedule(card(), Grade.GOOD, now)+ assertEquals(1, graded.intervalDays)+ assertEquals(1, graded.repetitions)+ assertEquals(now + Scheduler.DAY_MS, graded.dueDate)+ }++ @Test+ fun secondSuccessIsSixDays() {+ val graded = Scheduler.schedule(card(intervalDays = 1, repetitions = 1), Grade.GOOD, now)+ assertEquals(6, graded.intervalDays)+ assertEquals(2, graded.repetitions)+ }++ @Test+ fun thirdSuccessScalesByEaseFactor() {+ // interval = round(6 * 2.5) = 15+ val graded = Scheduler.schedule(+ card(easeFactor = 2.5, intervalDays = 6, repetitions = 2),+ Grade.GOOD,+ now,+ )+ assertEquals(15, graded.intervalDays)+ assertEquals(3, graded.repetitions)+ }++ @Test+ fun easeFactorIsClampedAtFloor() {+ var c = card(easeFactor = 2.5, intervalDays = 10, repetitions = 3)+ // Repeated failures drive the ease factor down; it must never go below 1.3.+ repeat(10) {+ c = Scheduler.schedule(c, Grade.AGAIN, now)+ assertTrue(c.easeFactor >= Scheduler.MIN_EASE, "ease below floor: ${c.easeFactor}")+ }+ assertEquals(Scheduler.MIN_EASE, c.easeFactor)+ }+}
metadata_data/flashcards.md
diff --git a/metadata_data/flashcards.md b/metadata_data/flashcards.mdnew file mode 100644index 0000000000..6225cd79a1--- /dev/null+++ b/metadata_data/flashcards.md@@ -0,0 +1 @@+A spaced-repetition flashcards app
settings.gradle.kts
diff --git a/settings.gradle.kts b/settings.gradle.ktsindex fdca86ec1f..c967fefb35 100644--- a/settings.gradle.kts+++ b/settings.gradle.kts@@ -48,6 +48,7 @@ include(":pdf") include(":openassistant") include(":passwords") include(":notes")+include(":flashcards") include(":files") include(":photos") include(":health")