Modern Apps git

← Modern-Apps.git

flashcards: Anki-style note/card model with .apkg import/export

Commit
0f97552c340c4988e8e01bc3b8e83995020d7f45
Author
Vayun Mathur <[email protected]>
When
2026-08-14 22:57 UTC (3 months ago)
Parents
89f8c22

Diff

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 1e5118fbdf..16f11cca6e 100644--- a/flashcards/src/main/java/com/vayunmathur/flashcards/MainActivity.kt+++ b/flashcards/src/main/java/com/vayunmathur/flashcards/MainActivity.kt@@ -12,13 +12,19 @@ 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.CardTemplateDao import com.vayunmathur.flashcards.data.DB_NAME import com.vayunmathur.flashcards.data.DeckDao import com.vayunmathur.flashcards.data.FlashcardsDatabase+import com.vayunmathur.flashcards.data.NoteDao+import com.vayunmathur.flashcards.data.NoteTypeDao+import com.vayunmathur.flashcards.data.NoteTypeFieldDao 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.NoteEditPage+import com.vayunmathur.flashcards.ui.NoteListPage+import com.vayunmathur.flashcards.ui.NoteTypeEditPage+import com.vayunmathur.flashcards.ui.NoteTypeListPage import com.vayunmathur.flashcards.ui.ReviewPage import com.vayunmathur.flashcards.ui.SettingsPage import com.vayunmathur.flashcards.ui.StatsPage@@ -44,8 +50,15 @@ class MainActivity : ComponentActivity() {     private lateinit var deckDao: DeckDao     private lateinit var cardDao: CardDao     private lateinit var reviewLogDao: ReviewLogDao+    private lateinit var noteTypeDao: NoteTypeDao+    private lateinit var noteTypeFieldDao: NoteTypeFieldDao+    private lateinit var cardTemplateDao: CardTemplateDao+    private lateinit var noteDao: NoteDao     private val viewModel: FlashcardsViewModel by viewModels {-        FlashcardsViewModelFactory(application, deckDao, cardDao, reviewLogDao)+        FlashcardsViewModelFactory(+            application, deckDao, cardDao, reviewLogDao,+            noteTypeDao, noteTypeFieldDao, cardTemplateDao, noteDao,+        )     }      override fun onCreate(savedInstanceState: Bundle?) {@@ -58,6 +71,10 @@ class MainActivity : ComponentActivity() {             deckDao = db.deckDao()             cardDao = db.cardDao()             reviewLogDao = db.reviewLogDao()+            noteTypeDao = db.noteTypeDao()+            noteTypeFieldDao = db.noteTypeFieldDao()+            cardTemplateDao = db.cardTemplateDao()+            noteDao = db.noteDao()             withContext(Dispatchers.Main) { ready.value = true }         } @@ -88,11 +105,17 @@ sealed interface Route : NavKey {     @Serializable     data object Settings : Route +    @Serializable+    data object NoteTypeList : Route++    @Serializable+    data class NoteTypeEdit(val noteTypeId: Long) : Route+     @Serializable     data class CardList(val deckId: Long) : Route      @Serializable-    data class CardEdit(val deckId: Long, val cardId: Long) : Route+    data class NoteEdit(val deckId: Long, val noteId: Long) : Route      @Serializable     data class Review(val deckId: Long) : Route@@ -121,8 +144,10 @@ fun Navigation(viewModel: FlashcardsViewModel) {         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.NoteTypeList> { NoteTypeListPage(backStack, viewModel) }+        entry<Route.NoteTypeEdit> { NoteTypeEditPage(backStack, viewModel, it.noteTypeId) }+        entry<Route.CardList> { NoteListPage(backStack, viewModel, it.deckId) }+        entry<Route.NoteEdit> { NoteEditPage(backStack, viewModel, it.deckId, it.noteId) }         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 76c1418171..d3a7ea1043 100644--- a/flashcards/src/main/java/com/vayunmathur/flashcards/data/Card.kt+++ b/flashcards/src/main/java/com/vayunmathur/flashcards/data/Card.kt@@ -1,6 +1,7 @@ package com.vayunmathur.flashcards.data  import androidx.room.Entity+import androidx.room.Index import androidx.room.PrimaryKey import com.vayunmathur.library.util.ReorderableDatabaseItem import kotlinx.serialization.Serializable@@ -14,24 +15,30 @@ object CardState { }  /**- * A single flashcard plus its FSRS spaced-repetition memory state.+ * A single card generated from a [Note] via one of its note type's templates, 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.+ * The displayed content is *not* stored here: it is rendered on demand from the+ * owning [Note] and the template selected by [templateOrd] (for standard note types+ * this is the template index; for cloze note types it is the cloze number minus one).  *  * 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.+ * for safety and are otherwise unused.  */ @Serializable-@Entity+@Entity(+    indices = [+        Index(value = ["noteId", "templateOrd"], unique = true),+        Index("deckId"),+    ],+) data class Card(     @PrimaryKey(autoGenerate = true) override val id: Long = 0,+    val noteId: Long,+    val templateOrd: Int,     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,
flashcards/src/main/java/com/vayunmathur/flashcards/data/CardTemplate.kt
diff --git a/flashcards/src/main/java/com/vayunmathur/flashcards/data/CardTemplate.kt b/flashcards/src/main/java/com/vayunmathur/flashcards/data/CardTemplate.ktnew file mode 100644index 0000000000..7d8ee42326--- /dev/null+++ b/flashcards/src/main/java/com/vayunmathur/flashcards/data/CardTemplate.kt@@ -0,0 +1,27 @@+package com.vayunmathur.flashcards.data++import androidx.room.Entity+import androidx.room.Index+import androidx.room.PrimaryKey+import kotlinx.serialization.Serializable++/**+ * A card template of a [NoteType]. [qfmt]/[afmt] are the question/answer formats:+ * **markdown** text with `{{Field}}`, `{{FrontSide}}`, `{{cloze:Field}}` and+ * `{{#Field}}…{{/Field}}` / `{{^Field}}…{{/Field}}` placeholders, rendered by+ * `TemplateEngine`. [ord] is the 0-based template index; ([noteTypeId], [ord]) is+ * unique. For cloze note types there is a single template and the effective ord of+ * a generated card is the cloze number minus one.+ */+@Serializable+@Entity(+    indices = [Index(value = ["noteTypeId", "ord"], unique = true)],+)+data class CardTemplate(+    @PrimaryKey(autoGenerate = true) val id: Long = 0,+    val noteTypeId: Long,+    val ord: Int,+    val name: String,+    val qfmt: String,+    val afmt: String,+)
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 4fbef8d2cf..39fd10f4db 100644--- a/flashcards/src/main/java/com/vayunmathur/flashcards/data/FlashcardsDatabase.kt+++ b/flashcards/src/main/java/com/vayunmathur/flashcards/data/FlashcardsDatabase.kt@@ -24,6 +24,9 @@ interface DeckDao {     @Query("SELECT * FROM Deck")     fun getAllFlow(): Flow<List<Deck>> +    @Query("SELECT * FROM Deck")+    suspend fun getAll(): List<Deck>+     @Query("SELECT * FROM Deck WHERE id = :id")     suspend fun getById(id: Long): Deck? @@ -34,6 +37,102 @@ interface DeckDao {     suspend fun delete(value: Deck): Int } +@Dao+interface NoteTypeDao {+    @Query("SELECT * FROM NoteType")+    fun getAllFlow(): Flow<List<NoteType>>++    @Query("SELECT * FROM NoteType")+    suspend fun getAll(): List<NoteType>++    @Query("SELECT * FROM NoteType WHERE id = :id")+    suspend fun getById(id: Long): NoteType?++    @Upsert+    suspend fun upsert(value: NoteType): Long++    @Delete+    suspend fun delete(value: NoteType): Int+}++@Dao+interface NoteTypeFieldDao {+    @Query("SELECT * FROM NoteTypeField")+    fun getAllFlow(): Flow<List<NoteTypeField>>++    @Query("SELECT * FROM NoteTypeField")+    suspend fun getAll(): List<NoteTypeField>++    @Query("SELECT * FROM NoteTypeField WHERE noteTypeId = :noteTypeId ORDER BY ord")+    suspend fun getByNoteType(noteTypeId: Long): List<NoteTypeField>++    @Upsert+    suspend fun upsert(value: NoteTypeField): Long++    @Upsert+    suspend fun upsertAll(values: List<NoteTypeField>)++    @Query("DELETE FROM NoteTypeField WHERE noteTypeId = :noteTypeId")+    suspend fun deleteByNoteType(noteTypeId: Long)+}++@Dao+interface CardTemplateDao {+    @Query("SELECT * FROM CardTemplate")+    fun getAllFlow(): Flow<List<CardTemplate>>++    @Query("SELECT * FROM CardTemplate")+    suspend fun getAll(): List<CardTemplate>++    @Query("SELECT * FROM CardTemplate WHERE noteTypeId = :noteTypeId ORDER BY ord")+    suspend fun getByNoteType(noteTypeId: Long): List<CardTemplate>++    @Upsert+    suspend fun upsert(value: CardTemplate): Long++    @Upsert+    suspend fun upsertAll(values: List<CardTemplate>)++    @Query("DELETE FROM CardTemplate WHERE noteTypeId = :noteTypeId")+    suspend fun deleteByNoteType(noteTypeId: Long)+}++@Dao+interface NoteDao {+    @Query("SELECT * FROM Note")+    fun getAllFlow(): Flow<List<Note>>++    @Query("SELECT * FROM Note")+    suspend fun getAll(): List<Note>++    @Query("SELECT * FROM Note WHERE deckId = :deckId")+    fun getByDeckFlow(deckId: Long): Flow<List<Note>>++    @Query("SELECT * FROM Note WHERE deckId = :deckId")+    suspend fun getByDeck(deckId: Long): List<Note>++    @Query("SELECT * FROM Note WHERE noteTypeId = :noteTypeId")+    suspend fun getByNoteType(noteTypeId: Long): List<Note>++    @Query("SELECT * FROM Note WHERE id = :id")+    suspend fun getById(id: Long): Note?++    @Query("SELECT * FROM Note WHERE id = :id")+    fun getByIdFlow(id: Long): Flow<Note?>++    @Upsert+    suspend fun upsert(value: Note): Long++    @Upsert+    suspend fun upsertAll(values: List<Note>)++    @Delete+    suspend fun delete(value: Note): Int++    @Query("DELETE FROM Note WHERE deckId = :deckId")+    suspend fun deleteByDeck(deckId: Long)+}+ @Dao interface CardDao {     @Query("SELECT * FROM Card")@@ -54,6 +153,9 @@ interface CardDao {     @Query("SELECT * FROM Card WHERE id = :id")     fun getByIdFlow(id: Long): Flow<Card?> +    @Query("SELECT * FROM Card WHERE noteId = :noteId")+    suspend fun getByNote(noteId: Long): List<Card>+     @Upsert     suspend fun upsert(value: Card): Long @@ -65,6 +167,12 @@ interface CardDao {      @Query("DELETE FROM Card WHERE deckId = :deckId")     suspend fun deleteByDeck(deckId: Long)++    @Query("DELETE FROM Card WHERE noteId = :noteId")+    suspend fun deleteByNote(noteId: Long)++    @Query("DELETE FROM Card WHERE noteId = :noteId AND templateOrd NOT IN (:keepOrds)")+    suspend fun deleteRemovedTemplates(noteId: Long, keepOrds: List<Int>) }  @Dao@@ -75,6 +183,9 @@ interface ReviewLogDao {     @Query("SELECT * FROM ReviewLog WHERE deckId = :deckId")     fun getByDeckFlow(deckId: Long): Flow<List<ReviewLog>> +    @Query("SELECT * FROM ReviewLog WHERE cardId = :cardId")+    suspend fun getByCard(cardId: Long): List<ReviewLog>+     @Insert     suspend fun insert(value: ReviewLog): Long @@ -86,14 +197,26 @@ interface ReviewLogDao { }  @Database(-    entities = [Deck::class, Card::class, ReviewLog::class],-    version = 2,+    entities = [+        Deck::class,+        Card::class,+        ReviewLog::class,+        NoteType::class,+        NoteTypeField::class,+        CardTemplate::class,+        Note::class,+    ],+    version = 3,     exportSchema = false, ) abstract class FlashcardsDatabase : RoomDatabase() {     abstract fun deckDao(): DeckDao     abstract fun cardDao(): CardDao     abstract fun reviewLogDao(): ReviewLogDao+    abstract fun noteTypeDao(): NoteTypeDao+    abstract fun noteTypeFieldDao(): NoteTypeFieldDao+    abstract fun cardTemplateDao(): CardTemplateDao+    abstract fun noteDao(): NoteDao      companion object : DatabaseMigrations {         override val migrations = listOf(@@ -123,6 +246,128 @@ abstract class FlashcardsDatabase : RoomDatabase() {                         "state INTEGER NOT NULL)",                 )             },+            MIGRATION_2_3,         )     } }++/**+ * Restructures the flat `Card(front, back, tags, …)` schema into Anki's+ * NoteType / Note / Card model.+ *+ * The DDL below is copied verbatim from Room's generated+ * `schemas/…/FlashcardsDatabase/3.json` `createSql` so it byte-matches what Room+ * validates on open. Each old card becomes a Basic [Note] (id preserved so+ * [ReviewLog.cardId] references stay valid) plus one [Card] pointing at it.+ */+val MIGRATION_2_3 = Migration(2, 3) { db ->+    // 1. New model tables + indices (Room's exact generated DDL).+    db.execSQL(+        "CREATE TABLE IF NOT EXISTS `NoteType` (" ++            "`id` INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL, " ++            "`name` TEXT NOT NULL, " ++            "`type` INTEGER NOT NULL, " ++            "`css` TEXT NOT NULL, " ++            "`mod` INTEGER NOT NULL)",+    )+    db.execSQL(+        "CREATE TABLE IF NOT EXISTS `NoteTypeField` (" ++            "`id` INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL, " ++            "`noteTypeId` INTEGER NOT NULL, " ++            "`ord` INTEGER NOT NULL, " ++            "`name` TEXT NOT NULL)",+    )+    db.execSQL(+        "CREATE UNIQUE INDEX IF NOT EXISTS `index_NoteTypeField_noteTypeId_ord` " ++            "ON `NoteTypeField` (`noteTypeId`, `ord`)",+    )+    db.execSQL(+        "CREATE TABLE IF NOT EXISTS `CardTemplate` (" ++            "`id` INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL, " ++            "`noteTypeId` INTEGER NOT NULL, " ++            "`ord` INTEGER NOT NULL, " ++            "`name` TEXT NOT NULL, " ++            "`qfmt` TEXT NOT NULL, " ++            "`afmt` TEXT NOT NULL)",+    )+    db.execSQL(+        "CREATE UNIQUE INDEX IF NOT EXISTS `index_CardTemplate_noteTypeId_ord` " ++            "ON `CardTemplate` (`noteTypeId`, `ord`)",+    )+    db.execSQL(+        "CREATE TABLE IF NOT EXISTS `Note` (" ++            "`id` INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL, " ++            "`noteTypeId` INTEGER NOT NULL, " ++            "`deckId` INTEGER NOT NULL, " ++            "`guid` TEXT NOT NULL, " ++            "`flds` TEXT NOT NULL, " ++            "`sortField` TEXT NOT NULL, " ++            "`tags` TEXT NOT NULL, " ++            "`mod` INTEGER NOT NULL, " ++            "`position` REAL NOT NULL)",+    )+    db.execSQL("CREATE INDEX IF NOT EXISTS `index_Note_noteTypeId` ON `Note` (`noteTypeId`)")+    db.execSQL("CREATE INDEX IF NOT EXISTS `index_Note_deckId` ON `Note` (`deckId`)")++    // 2. Seed built-in note types with fixed ids.+    db.execSQL(+        "INSERT INTO `NoteType` (`id`, `name`, `type`, `css`, `mod`) VALUES " ++            "(1, 'Basic', 0, '', 0), " ++            "(2, 'Basic (and reversed card)', 0, '', 0), " ++            "(3, 'Cloze', 1, '', 0)",+    )+    db.execSQL(+        "INSERT INTO `NoteTypeField` (`noteTypeId`, `ord`, `name`) VALUES " ++            "(1, 0, 'Front'), (1, 1, 'Back'), " ++            "(2, 0, 'Front'), (2, 1, 'Back'), " ++            "(3, 0, 'Text'), (3, 1, 'Back Extra')",+    )+    db.execSQL(+        "INSERT INTO `CardTemplate` (`noteTypeId`, `ord`, `name`, `qfmt`, `afmt`) VALUES " ++            "(1, 0, 'Card 1', '{{Front}}', '{{FrontSide}}" + "\n\n---\n\n" + "{{Back}}'), " ++            "(2, 0, 'Card 1', '{{Front}}', '{{FrontSide}}" + "\n\n---\n\n" + "{{Back}}'), " ++            "(2, 1, 'Card 2', '{{Back}}', '{{FrontSide}}" + "\n\n---\n\n" + "{{Front}}'), " ++            "(3, 0, 'Cloze', '{{cloze:Text}}', '{{cloze:Text}}" + "\n\n---\n\n" + "{{Back Extra}}')",+    )++    // 3. Convert each old Card into a Basic Note (noteTypeId 1). Note.id = old+    //    Card.id so ReviewLog.cardId references stay valid.+    db.execSQL(+        "INSERT INTO `Note` (`id`, `noteTypeId`, `deckId`, `guid`, `flds`, `sortField`, `tags`, `mod`, `position`) " ++            "SELECT id, 1, deckId, lower(hex(randomblob(8))), front || char(31) || back, front, tags, 0, position FROM Card",+    )++    // 4. Rebuild Card with the new shape, one card per old card (templateOrd 0).+    db.execSQL("ALTER TABLE `Card` RENAME TO `Card_old`")+    db.execSQL(+        "CREATE TABLE IF NOT EXISTS `Card` (" ++            "`id` INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL, " ++            "`noteId` INTEGER NOT NULL, " ++            "`templateOrd` INTEGER NOT NULL, " ++            "`deckId` INTEGER NOT NULL, " ++            "`stability` REAL NOT NULL, " ++            "`difficulty` REAL NOT NULL, " ++            "`state` INTEGER NOT NULL, " ++            "`lastReview` INTEGER NOT NULL, " ++            "`lapses` INTEGER NOT NULL, " ++            "`reps` INTEGER NOT NULL, " ++            "`dueDate` INTEGER NOT NULL, " ++            "`easeFactor` REAL NOT NULL, " ++            "`intervalDays` INTEGER NOT NULL, " ++            "`repetitions` INTEGER NOT NULL, " ++            "`position` REAL NOT NULL)",+    )+    db.execSQL(+        "CREATE UNIQUE INDEX IF NOT EXISTS `index_Card_noteId_templateOrd` " ++            "ON `Card` (`noteId`, `templateOrd`)",+    )+    db.execSQL("CREATE INDEX IF NOT EXISTS `index_Card_deckId` ON `Card` (`deckId`)")+    db.execSQL(+        "INSERT INTO `Card` (`id`, `noteId`, `templateOrd`, `deckId`, `stability`, `difficulty`, " ++            "`state`, `lastReview`, `lapses`, `reps`, `dueDate`, `easeFactor`, `intervalDays`, " ++            "`repetitions`, `position`) " ++            "SELECT id, id, 0, deckId, stability, difficulty, state, lastReview, lapses, reps, " ++            "dueDate, easeFactor, intervalDays, repetitions, position FROM Card_old",+    )+    db.execSQL("DROP TABLE `Card_old`")+}
flashcards/src/main/java/com/vayunmathur/flashcards/data/Note.kt
diff --git a/flashcards/src/main/java/com/vayunmathur/flashcards/data/Note.kt b/flashcards/src/main/java/com/vayunmathur/flashcards/data/Note.ktnew file mode 100644index 0000000000..1999a1a9e3--- /dev/null+++ b/flashcards/src/main/java/com/vayunmathur/flashcards/data/Note.kt@@ -0,0 +1,51 @@+package com.vayunmathur.flashcards.data++import androidx.room.Entity+import androidx.room.Index+import androidx.room.PrimaryKey+import com.vayunmathur.library.util.ReorderableDatabaseItem+import kotlinx.serialization.Serializable++/** The Anki field separator that joins a note's field values in [Note.flds]. */+const val FIELD_SEPARATOR = "\u001f"++/**+ * A note: the authored content that generates one or more [Card]s. It belongs to+ * a [NoteType] (which defines its fields and templates) and a [Deck].+ *+ * [flds] holds the field values joined by [FIELD_SEPARATOR], in field-ord order.+ * [sortField] is a copy of the first field (for the note list / sorting). [tags]+ * are space-separated. [guid] is a stable identifier preserved across `.apkg`+ * round-trips. [mod] is the last-modified epoch seconds (Anki convention).+ */+@Serializable+@Entity(+    indices = [Index("noteTypeId"), Index("deckId")],+)+data class Note(+    @PrimaryKey(autoGenerate = true) override val id: Long = 0,+    val noteTypeId: Long,+    val deckId: Long,+    val guid: String,+    val flds: String,+    val sortField: String,+    val tags: String = "",+    val mod: Long = 0,+    override val position: Double = 0.0,+) : ReorderableDatabaseItem<Note> {+    override fun withPosition(position: Double) = copy(position = position)++    /** The individual field values, split from [flds]. */+    val fieldList: List<String> get() = flds.split(FIELD_SEPARATOR)++    /**+     * Maps the given [fields] (ordered by ord) to this note's values. Extra fields+     * map to empty strings; extra values are dropped.+     */+    fun fieldValues(fields: List<NoteTypeField>): Map<String, String> {+        val values = fieldList+        return fields.sortedBy { it.ord }+            .mapIndexed { index, field -> field.name to (values.getOrNull(index) ?: "") }+            .toMap()+    }+}
flashcards/src/main/java/com/vayunmathur/flashcards/data/NoteType.kt
diff --git a/flashcards/src/main/java/com/vayunmathur/flashcards/data/NoteType.kt b/flashcards/src/main/java/com/vayunmathur/flashcards/data/NoteType.ktnew file mode 100644index 0000000000..7b38a5bec7--- /dev/null+++ b/flashcards/src/main/java/com/vayunmathur/flashcards/data/NoteType.kt@@ -0,0 +1,29 @@+package com.vayunmathur.flashcards.data++import androidx.room.Entity+import androidx.room.PrimaryKey+import kotlinx.serialization.Serializable++/** [NoteType.type] values (mirrors Anki's `models[*].type`). */+object NoteTypeKind {+    const val STANDARD = 0+    const val CLOZE = 1+}++/**+ * A note "model" (in Anki terms): a named set of [NoteTypeField]s plus a set of+ * [CardTemplate]s that turn a [Note]'s field values into rendered cards.+ *+ * [type] is [NoteTypeKind.STANDARD] or [NoteTypeKind.CLOZE]. [css] is the model's+ * stylesheet, carried through `.apkg` import/export but unused by the markdown+ * display pipeline. [mod] is the last-modified epoch seconds (Anki convention).+ */+@Serializable+@Entity+data class NoteType(+    @PrimaryKey(autoGenerate = true) val id: Long = 0,+    val name: String,+    val type: Int = NoteTypeKind.STANDARD,+    val css: String = "",+    val mod: Long = 0,+)
flashcards/src/main/java/com/vayunmathur/flashcards/data/NoteTypeField.kt
diff --git a/flashcards/src/main/java/com/vayunmathur/flashcards/data/NoteTypeField.kt b/flashcards/src/main/java/com/vayunmathur/flashcards/data/NoteTypeField.ktnew file mode 100644index 0000000000..37608feda6--- /dev/null+++ b/flashcards/src/main/java/com/vayunmathur/flashcards/data/NoteTypeField.kt@@ -0,0 +1,22 @@+package com.vayunmathur.flashcards.data++import androidx.room.Entity+import androidx.room.Index+import androidx.room.PrimaryKey+import kotlinx.serialization.Serializable++/**+ * One named field of a [NoteType], e.g. "Front"/"Back" (Basic) or "Text" (Cloze).+ * [ord] is the 0-based position of the field within its note type; the pair+ * ([noteTypeId], [ord]) is unique.+ */+@Serializable+@Entity(+    indices = [Index(value = ["noteTypeId", "ord"], unique = true)],+)+data class NoteTypeField(+    @PrimaryKey(autoGenerate = true) val id: Long = 0,+    val noteTypeId: Long,+    val ord: Int,+    val name: String,+)
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.ktdeleted file mode 100644index 00744a3420..0000000000--- a/flashcards/src/main/java/com/vayunmathur/flashcards/ui/CardEditPage.kt+++ /dev/null@@ -1,161 +0,0 @@-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.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-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.AppScaffold-import com.vayunmathur.library.ui.IconButton-import com.vayunmathur.library.ui.IconDelete-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.Text-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 markdown/tags 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("") }-    var tagsText by remember { mutableStateOf("") }--    LaunchedEffect(dbCard) {-        dbCard?.let {-            frontText = it.front-            backText = it.back-            tagsText = it.tags-        }-    }--    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 setTags(tags: String) { tagsText = tags }-        override fun save() {-            val card = dbCard?.copy(front = frontText, back = backText, tags = tagsText)-                ?: Card(deckId = deckId, front = frontText, back = backText, tags = tagsText)-            viewModel.upsertCard(card)-            backStack.pop()-        }-        override fun deleteCard() {-            dbCard?.let { viewModel.deleteCard(it) }-            backStack.pop()-        }-    }--    CardEditScreen(-        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`. Front/back are markdown, edited- * via [MarkdownEditor] with a shared [MarkdownFormatToolbar] for the focused field.- */-@Composable-fun CardEditScreen(-    state: CardEditUiState,-    actions: CardEditActions,-) {-    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(-            Modifier-                .padding(paddingValues)-                .fillMaxSize()-                .verticalScroll(rememberScrollState())-                .padding(horizontal = 16.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.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/NoteEditPage.kt
diff --git a/flashcards/src/main/java/com/vayunmathur/flashcards/ui/NoteEditPage.kt b/flashcards/src/main/java/com/vayunmathur/flashcards/ui/NoteEditPage.ktnew file mode 100644index 0000000000..bad509d0c3--- /dev/null+++ b/flashcards/src/main/java/com/vayunmathur/flashcards/ui/NoteEditPage.kt@@ -0,0 +1,234 @@+package com.vayunmathur.flashcards.ui++import androidx.compose.foundation.clickable+import androidx.compose.foundation.layout.Box+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.mutableIntStateOf+import androidx.compose.runtime.mutableLongStateOf+import androidx.compose.runtime.mutableStateListOf+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+import com.vayunmathur.flashcards.Route+import com.vayunmathur.flashcards.util.DeckOption+import com.vayunmathur.flashcards.util.FlashcardsViewModel+import com.vayunmathur.flashcards.util.NoteEditActions+import com.vayunmathur.flashcards.util.NoteEditUiState+import com.vayunmathur.flashcards.util.NoteTypeConfig+import com.vayunmathur.library.ui.AppScaffold+import com.vayunmathur.library.ui.DropdownMenu+import com.vayunmathur.library.ui.DropdownMenuItem+import com.vayunmathur.library.ui.IconButton+import com.vayunmathur.library.ui.IconDelete+import com.vayunmathur.library.ui.IconSave+import com.vayunmathur.library.ui.MarkdownEditor+import com.vayunmathur.library.ui.MarkdownFormatToolbar+import com.vayunmathur.library.ui.MaterialTheme+import com.vayunmathur.library.ui.OutlinedTextField+import com.vayunmathur.library.ui.Text+import com.vayunmathur.library.util.NavBackStack++/**+ * Binds the note with [noteId] (0 for a new note) in [deckId] to the stateless+ * [NoteEditScreen]: resolves the available note types + decks and saves via the ViewModel.+ */+@Composable+fun NoteEditPage(+    backStack: NavBackStack<Route>,+    viewModel: FlashcardsViewModel,+    deckId: Long,+    noteId: Long,+) {+    val dbNote by remember(noteId) { viewModel.noteById(noteId) }+        .collectAsStateWithLifecycle(null)+    val noteTypes by viewModel.noteTypes.collectAsStateWithLifecycle()+    val decks by viewModel.decks.collectAsStateWithLifecycle()++    val configs = noteTypes.map { NoteTypeConfig(it.noteType.id, it.noteType.name, it.fields.map { f -> f.name }) }+    val isNew = noteId == 0L++    val actions = remember(backStack, viewModel, deckId, noteId) {+        object : NoteEditActions {+            override fun back() { backStack.pop() }+            override fun save(noteTypeId: Long, deckId: Long, fieldValues: List<String>, tags: String) {+                viewModel.saveNote(noteId, noteTypeId, deckId, fieldValues, tags)+                backStack.pop()+            }+            override fun deleteNote() {+                dbNote?.let { viewModel.deleteNote(it) }+                backStack.pop()+            }+        }+    }++    NoteEditScreen(+        state = NoteEditUiState(+            initialNoteTypeId = dbNote?.noteTypeId ?: configs.firstOrNull()?.id ?: FlashcardsViewModel.BASIC_NOTE_TYPE_ID,+            initialDeckId = dbNote?.deckId ?: deckId,+            initialFieldValues = dbNote?.fieldList ?: emptyList(),+            initialTags = dbNote?.tags.orEmpty(),+            isNew = isNew,+            noteTypes = configs,+            decks = decks.map { DeckOption(it.id, it.name) },+        ),+        actions = actions,+    )+}++/**+ * The note editor, with no dependency on the ViewModel or the back stack so it can be+ * rendered from a `@Preview`. Draws a note-type dropdown, a deck picker, one+ * [MarkdownEditor] per field of the selected type, and a tags field.+ */+@Composable+fun NoteEditScreen(+    state: NoteEditUiState,+    actions: NoteEditActions,+) {+    var typeId by remember { mutableLongStateOf(state.initialNoteTypeId) }+    var deckId by remember { mutableLongStateOf(state.initialDeckId) }+    var tags by remember { mutableStateOf(state.initialTags) }+    var activeField by remember { mutableIntStateOf(-1) }+    // Field values keyed by field name so they survive a note-type switch.+    val values = remember { androidx.compose.runtime.mutableStateMapOf<String, String>() }+    val fieldTfv = remember { mutableStateListOf<TextFieldValue>() }++    fun currentFields(): List<String> = state.noteTypes.firstOrNull { it.id == typeId }?.fieldNames ?: emptyList()++    fun rebuildEditors() {+        val fields = currentFields()+        fieldTfv.clear()+        fields.forEach { name -> fieldTfv.add(TextFieldValue(values[name].orEmpty())) }+    }++    LaunchedEffect(state) {+        typeId = state.initialNoteTypeId+        deckId = state.initialDeckId+        tags = state.initialTags+        values.clear()+        val fields = state.noteTypes.firstOrNull { it.id == typeId }?.fieldNames ?: emptyList()+        fields.forEachIndexed { i, name -> values[name] = state.initialFieldValues.getOrNull(i) ?: "" }+        rebuildEditors()+    }++    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.deleteNote() }) { IconDelete() }+            }+            IconButton(onClick = {+                val fields = currentFields()+                actions.save(typeId, deckId, fields.map { values[it].orEmpty() }, tags)+            }) { IconSave() }+        },+        bottomBar = {+            val index = activeField+            if (index in fieldTfv.indices) {+                MarkdownFormatToolbar(+                    value = fieldTfv[index],+                    onValueChange = {+                        fieldTfv[index] = it+                        values[currentFields()[index]] = it.text+                    },+                )+            }+        },+    ) { paddingValues ->+        Column(+            Modifier+                .padding(paddingValues)+                .fillMaxSize()+                .verticalScroll(rememberScrollState())+                .padding(horizontal = 16.dp),+        ) {+            DropdownField(+                label = stringResource(R.string.note_type),+                selected = state.noteTypes.firstOrNull { it.id == typeId }?.name.orEmpty(),+                options = state.noteTypes,+                optionLabel = { it.name },+                onSelect = { config ->+                    typeId = config.id+                    config.fieldNames.forEach { name -> values.getOrPut(name) { "" } }+                    rebuildEditors()+                    activeField = -1+                },+            )+            DropdownField(+                label = stringResource(R.string.deck),+                selected = state.decks.firstOrNull { it.id == deckId }?.name.orEmpty(),+                options = state.decks,+                optionLabel = { it.name },+                onSelect = { deck -> deck.id?.let { deckId = it } },+            )++            currentFields().forEachIndexed { index, name ->+                if (index in fieldTfv.indices) {+                    Text(name, style = MaterialTheme.typography.labelMedium, modifier = Modifier.padding(top = 12.dp))+                    MarkdownEditor(+                        value = fieldTfv[index],+                        onValueChange = {+                            fieldTfv[index] = it+                            values[name] = it.text+                        },+                        placeholder = name,+                        onFocusChanged = { if (it) activeField = index },+                        modifier = Modifier.fillMaxWidth().padding(top = 4.dp),+                    )+                }+            }++            OutlinedTextField(+                value = tags,+                onValueChange = { tags = it },+                label = { Text(stringResource(R.string.tags)) },+                singleLine = true,+                modifier = Modifier.fillMaxWidth().padding(top = 16.dp, bottom = 16.dp),+            )+        }+    }+}++@Composable+private fun <T> DropdownField(+    label: String,+    selected: String,+    options: List<T>,+    optionLabel: (T) -> String,+    onSelect: (T) -> Unit,+) {+    var expanded by remember { mutableStateOf(false) }+    Box(Modifier.fillMaxWidth().padding(top = 8.dp)) {+        Column(Modifier.fillMaxWidth().clickable { expanded = true }.padding(vertical = 8.dp)) {+            Text(label, style = MaterialTheme.typography.labelMedium)+            Text(selected.ifBlank { "—" }, style = MaterialTheme.typography.bodyLarge)+        }+        DropdownMenu(expanded = expanded, onDismissRequest = { expanded = false }) {+            options.forEach { option ->+                DropdownMenuItem(+                    text = { Text(optionLabel(option)) },+                    onClick = {+                        onSelect(option)+                        expanded = false+                    },+                )+            }+        }+    }+}
flashcards/src/main/java/com/vayunmathur/flashcards/ui/NoteListPage.kt
diff --git a/flashcards/src/main/java/com/vayunmathur/flashcards/ui/CardListPage.kt b/flashcards/src/main/java/com/vayunmathur/flashcards/ui/NoteListPage.ktsimilarity index 61%rename from flashcards/src/main/java/com/vayunmathur/flashcards/ui/CardListPage.ktrename to flashcards/src/main/java/com/vayunmathur/flashcards/ui/NoteListPage.ktindex 63825bd126..b0101653e2 100644--- a/flashcards/src/main/java/com/vayunmathur/flashcards/ui/CardListPage.kt+++ b/flashcards/src/main/java/com/vayunmathur/flashcards/ui/NoteListPage.kt@@ -1,6 +1,7 @@ package com.vayunmathur.flashcards.ui  import android.content.Intent+import android.widget.Toast import androidx.activity.compose.rememberLauncherForActivityResult import androidx.activity.result.contract.ActivityResultContracts import androidx.compose.animation.core.animateDpAsState@@ -30,10 +31,11 @@ import androidx.compose.ui.zIndex 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.data.Note import com.vayunmathur.flashcards.util.FlashcardsViewModel+import com.vayunmathur.flashcards.util.NoteListActions+import com.vayunmathur.flashcards.util.NoteListUiState+import com.vayunmathur.flashcards.util.NoteRow import com.vayunmathur.library.ui.AppScaffold import com.vayunmathur.library.ui.Button import com.vayunmathur.library.ui.CommonSearchBar@@ -54,29 +56,41 @@ 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]. */+/** Binds the deck with [deckId] to the stateless [NoteListScreen]. */ @Composable-fun CardListPage(+fun NoteListPage(     backStack: NavBackStack<Route>,     viewModel: FlashcardsViewModel,     deckId: Long, ) {     val context = LocalContext.current     val decks by viewModel.decks.collectAsStateWithLifecycle()+    val notes by remember(deckId) { viewModel.notesFor(deckId) }+        .collectAsStateWithLifecycle(emptyList())     val cards by remember(deckId) { viewModel.cardsFor(deckId) }         .collectAsStateWithLifecycle(emptyList())      val deckName = decks.firstOrNull { it.id == deckId }?.name ?: ""     val now = System.currentTimeMillis()+    val cardsByNote = cards.groupBy { it.noteId }      val importLauncher = rememberLauncherForActivityResult(         ActivityResultContracts.OpenDocument(),-    ) { uri -> uri?.let { viewModel.importCsv(deckId, it) } }+    ) { uri ->+        uri?.let {+            val name = queryFileName(context, it).orEmpty()+            if (name.endsWith(".apkg", true) || isZip(context, it)) {+                viewModel.importApkg(it)+            } else {+                viewModel.importCsv(deckId, it)+            }+        }+    }      LaunchedEffect(viewModel, deckId) {         viewModel.shareRequests.collect { uri ->             val intent = Intent(Intent.ACTION_SEND).apply {-                type = "application/json"+                type = "application/octet-stream"                 putExtra(Intent.EXTRA_STREAM, uri)                 addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION)             }@@ -85,49 +99,65 @@ fun CardListPage(             )         }     }+    LaunchedEffect(viewModel) {+        viewModel.messages.collect { message ->+            Toast.makeText(context, message, Toast.LENGTH_LONG).show()+        }+    }      val actions = remember(backStack, viewModel, deckId) {-        object : CardListActions {+        object : NoteListActions {             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 openNote(id: Long) { backStack.add(Route.NoteEdit(deckId, id)) }+            override fun addNote() { backStack.add(Route.NoteEdit(deckId, 0)) }+            override fun deleteNote(note: Note) { viewModel.deleteNote(note) }             override fun study() { backStack.add(Route.Review(deckId)) }-            override fun reorder(cards: List<Card>) { viewModel.reorderCards(cards) }+            override fun reorder(notes: List<Note>) { viewModel.reorderNotes(notes) }             override fun openStats() { backStack.add(Route.Stats) }-            override fun share() { viewModel.exportDeck(deckId) }+            override fun share() { viewModel.exportApkg(deckId) }         }     } -    CardListScreen(-        state = CardListUiState(+    NoteListScreen(+        state = NoteListUiState(             deckName = deckName,-            cards = cards.sortedBy { it.position },+            notes = notes.sortedBy { it.position }+                .map { NoteRow(it, cardsByNote[it.id]?.size ?: 0) },             dueCount = cards.count { (!it.isNew && it.dueDate <= now) || it.isNew },         ),         actions = actions,-        onImport = { importLauncher.launch(arrayOf("text/csv", "text/comma-separated-values", "text/plain")) },+        onImport = {+            importLauncher.launch(+                arrayOf(+                    "application/octet-stream",+                    "application/zip",+                    "text/csv",+                    "text/comma-separated-values",+                    "text/plain",+                    "*/*",+                ),+            )+        },     ) }  /**- * The card list for one deck, with no dependency on the ViewModel or the back stack so it+ * The note 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(ExperimentalFoundationApi::class) @Composable-fun CardListScreen(-    state: CardListUiState,-    actions: CardListActions,+fun NoteListScreen(+    state: NoteListUiState,+    actions: NoteListActions,     onImport: () -> Unit = {}, ) {     var query by remember { mutableStateOf("") }     val filtered = if (query.isBlank()) {-        state.cards+        state.notes     } else {-        state.cards.filter {-            it.front.contains(query, true) || it.back.contains(query, true) ||-                it.tags.contains(query, true)+        state.notes.filter {+            it.note.flds.contains(query, true) || it.note.tags.contains(query, true)         }     } @@ -139,7 +169,7 @@ fun CardListScreen(             IconButton(onClick = { actions.share() }) { IconShare() }         },         floatingActionButton = {-            FloatingActionButton(onClick = { actions.addCard() }) { IconAdd() }+            FloatingActionButton(onClick = { actions.addNote() }) { IconAdd() }         },     ) { paddingValues ->         Column(Modifier.fillMaxSize().padding(paddingValues)) {@@ -151,7 +181,7 @@ fun CardListScreen(                     Text(stringResource(R.string.study))                 }             }-            if (state.cards.isNotEmpty()) {+            if (state.notes.isNotEmpty()) {                 CommonSearchBar(                     value = query,                     onValueChange = { query = it },@@ -160,16 +190,16 @@ fun CardListScreen(                 )             }             when {-                state.cards.isEmpty() -> EmptyState(+                state.notes.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)+                query.isBlank() -> ReorderableNoteList(filtered, actions)                 else -> LazyColumn(Modifier.fillMaxSize()) {-                    items(filtered, key = { it.id }) { card ->-                        CardRow(card, onOpen = { actions.openCard(card.id) }, onDelete = { actions.deleteCard(card) })+                    items(filtered, key = { it.note.id }) { row ->+                        NoteRowItem(row, onOpen = { actions.openNote(row.note.id) }, onDelete = { actions.deleteNote(row.note) })                     }                 }             }@@ -179,9 +209,9 @@ fun CardListScreen(  @OptIn(ExperimentalFoundationApi::class) @Composable-private fun ReorderableCardList(cards: List<Card>, actions: CardListActions) {+private fun ReorderableNoteList(rows: List<NoteRow>, actions: NoteListActions) {     val listState = rememberLazyListState()-    var local by remember { mutableStateOf(cards) }+    var local by remember { mutableStateOf(rows) }     var hasDragged by remember { mutableStateOf(false) }     val reorderState = rememberReorderableLazyListState(listState) { from, to ->         if (from.index in local.indices && to.index in local.indices) {@@ -189,30 +219,30 @@ private fun ReorderableCardList(cards: List<Card>, actions: CardListActions) {             hasDragged = true         }     }-    LaunchedEffect(cards) { if (!reorderState.isAnyItemDragging) local = cards }+    LaunchedEffect(rows) { if (!reorderState.isAnyItemDragging) local = rows }     LaunchedEffect(reorderState.isAnyItemDragging) {         if (!reorderState.isAnyItemDragging && hasDragged) {-            actions.reorder(local.mapIndexed { index, c -> c.withPosition(index.toDouble()) })+            actions.reorder(local.mapIndexed { index, r -> r.note.withPosition(index.toDouble()) })             hasDragged = false         }     }      LazyColumn(state = listState, modifier = Modifier.fillMaxSize()) {-        items(local, key = { it.id }) { card ->-            val dragging = reorderState.draggingKey == card.id+        items(local, key = { it.note.id }) { row ->+            val dragging = reorderState.draggingKey == row.note.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")+            ReorderableItem(reorderState, key = row.note.id, modifier = itemModifier) { isDragging ->+                val elevation by animateDpAsState(if (isDragging) 8.dp else 0.dp, label = "noteElevation")                 Surface(shadowElevation = elevation) {-                    CardRow(-                        card = card,-                        onOpen = { actions.openCard(card.id) },-                        onDelete = { actions.deleteCard(card) },-                        dragHandle = Modifier.reorderDragHandle(reorderState, key = card.id),+                    NoteRowItem(+                        row = row,+                        onOpen = { actions.openNote(row.note.id) },+                        onDelete = { actions.deleteNote(row.note) },+                        dragHandle = Modifier.reorderDragHandle(reorderState, key = row.note.id),                     )                 }             }@@ -221,21 +251,25 @@ private fun ReorderableCardList(cards: List<Card>, actions: CardListActions) { }  @Composable-private fun CardRow(-    card: Card,+private fun NoteRowItem(+    row: NoteRow,     onOpen: () -> Unit,     onDelete: () -> Unit,     dragHandle: Modifier? = null, ) {+    val fields = row.note.fieldList     ListItem(         headlineContent = {-            Text(parseMarkdown(card.front.substringBefore('\n').take(60), showMarkers = false))+            Text(parseMarkdown(row.note.sortField.substringBefore('\n').take(60), showMarkers = false))         },         supportingContent = {-            Text(parseMarkdown(card.back.substringBefore('\n').take(60), showMarkers = false))+            Text(parseMarkdown(fields.getOrNull(1).orEmpty().substringBefore('\n').take(60), showMarkers = false))         },         trailingContent = {             Row {+                if (row.cardCount != 1) {+                    Text(stringResource(R.string.card_count_badge, row.cardCount))+                }                 IconButton(onClick = onDelete) { IconDelete() }                 if (dragHandle != null) {                     IconButton(onClick = {}, modifier = dragHandle) { IconDragHandle() }@@ -245,3 +279,17 @@ private fun CardRow(         modifier = Modifier.clickable { onOpen() },     ) }++private fun queryFileName(context: android.content.Context, uri: android.net.Uri): String? =+    context.contentResolver.query(uri, null, null, null, null)?.use { cursor ->+        val index = cursor.getColumnIndex(android.provider.OpenableColumns.DISPLAY_NAME)+        if (index >= 0 && cursor.moveToFirst()) cursor.getString(index) else null+    }++private fun isZip(context: android.content.Context, uri: android.net.Uri): Boolean =+    runCatching {+        context.contentResolver.openInputStream(uri)?.use { input ->+            val header = ByteArray(2)+            input.read(header) == 2 && header[0] == 'P'.code.toByte() && header[1] == 'K'.code.toByte()+        } ?: false+    }.getOrDefault(false)
flashcards/src/main/java/com/vayunmathur/flashcards/ui/NoteTypeEditorPage.kt
diff --git a/flashcards/src/main/java/com/vayunmathur/flashcards/ui/NoteTypeEditorPage.kt b/flashcards/src/main/java/com/vayunmathur/flashcards/ui/NoteTypeEditorPage.ktnew file mode 100644index 0000000000..9966f78855--- /dev/null+++ b/flashcards/src/main/java/com/vayunmathur/flashcards/ui/NoteTypeEditorPage.kt@@ -0,0 +1,353 @@+package com.vayunmathur.flashcards.ui++import androidx.compose.foundation.clickable+import androidx.compose.foundation.layout.Arrangement+import androidx.compose.foundation.layout.Column+import androidx.compose.foundation.layout.Row+import androidx.compose.foundation.layout.fillMaxSize+import androidx.compose.foundation.layout.fillMaxWidth+import androidx.compose.foundation.layout.padding+import androidx.compose.foundation.lazy.LazyColumn+import androidx.compose.foundation.lazy.items+import androidx.compose.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.mutableStateListOf+import androidx.compose.runtime.mutableStateOf+import androidx.compose.runtime.remember+import androidx.compose.runtime.setValue+import androidx.compose.ui.Alignment+import androidx.compose.ui.Modifier+import androidx.compose.ui.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.NoteTypeKind+import com.vayunmathur.flashcards.util.FlashcardsViewModel+import com.vayunmathur.flashcards.util.NoteTypeEditActions+import com.vayunmathur.flashcards.util.NoteTypeEditUiState+import com.vayunmathur.flashcards.util.NoteTypeListActions+import com.vayunmathur.flashcards.util.NoteTypeListUiState+import com.vayunmathur.flashcards.util.NoteTypeSummary+import com.vayunmathur.flashcards.util.TemplateDraft+import com.vayunmathur.flashcards.util.TemplateEngine+import com.vayunmathur.library.ui.AppScaffold+import com.vayunmathur.library.ui.Card+import com.vayunmathur.library.ui.ConfirmDialog+import com.vayunmathur.library.ui.FilterChip+import com.vayunmathur.library.ui.FloatingActionButton+import com.vayunmathur.library.ui.HorizontalDivider+import com.vayunmathur.library.ui.IconAdd+import com.vayunmathur.library.ui.IconButton+import com.vayunmathur.library.ui.IconDelete+import com.vayunmathur.library.ui.ListItem+import com.vayunmathur.library.ui.MaterialTheme+import com.vayunmathur.library.ui.OutlinedButton+import com.vayunmathur.library.ui.OutlinedTextField+import com.vayunmathur.library.ui.Text+import com.vayunmathur.library.util.NavBackStack+import com.vayunmathur.library.util.parseMarkdown++// ---------------------------------------------------------------------------+// Note type list+// ---------------------------------------------------------------------------++/** Binds the note-type manager list. */+@Composable+fun NoteTypeListPage(backStack: NavBackStack<Route>, viewModel: FlashcardsViewModel) {+    val noteTypes by viewModel.noteTypes.collectAsStateWithLifecycle()+    val notes by viewModel.notes.collectAsStateWithLifecycle()+    val countByType = notes.groupingBy { it.noteTypeId }.eachCount()++    val actions = remember(backStack, viewModel) {+        object : NoteTypeListActions {+            override fun back() { backStack.pop() }+            override fun openNoteType(id: Long) { backStack.add(Route.NoteTypeEdit(id)) }+            override fun addNoteType() { backStack.add(Route.NoteTypeEdit(0)) }+            override fun deleteNoteType(id: Long) { viewModel.deleteNoteType(id) }+        }+    }++    NoteTypeListScreen(+        state = NoteTypeListUiState(+            noteTypes = noteTypes.map { cfg ->+                NoteTypeSummary(+                    id = cfg.noteType.id,+                    name = cfg.noteType.name,+                    fieldCount = cfg.fields.size,+                    templateCount = cfg.templates.size,+                    noteCount = countByType[cfg.noteType.id] ?: 0,+                    isCloze = cfg.noteType.type == NoteTypeKind.CLOZE,+                )+            },+        ),+        actions = actions,+    )+}++@Composable+fun NoteTypeListScreen(state: NoteTypeListUiState, actions: NoteTypeListActions) {+    var pendingDelete by remember { mutableStateOf<NoteTypeSummary?>(null) }+    AppScaffold(+        title = stringResource(R.string.manage_note_types),+        onNavigateBack = { actions.back() },+        floatingActionButton = {+            FloatingActionButton(onClick = { actions.addNoteType() }) { IconAdd() }+        },+    ) { paddingValues ->+        LazyColumn(Modifier.fillMaxSize(), contentPadding = paddingValues) {+            items(state.noteTypes, key = { it.id }) { summary ->+                val builtIn = summary.id in FlashcardsViewModel.BUILT_IN_NOTE_TYPE_IDS+                ListItem(+                    headlineContent = { Text(summary.name) },+                    supportingContent = {+                        Text(+                            stringResource(+                                R.string.note_type_summary,+                                summary.fieldCount,+                                summary.templateCount,+                                summary.noteCount,+                            ),+                        )+                    },+                    trailingContent = {+                        if (!builtIn) {+                            IconButton(onClick = { pendingDelete = summary }) { IconDelete() }+                        }+                    },+                    modifier = Modifier.clickable { actions.openNoteType(summary.id) },+                )+            }+        }+    }++    pendingDelete?.let { summary ->+        ConfirmDialog(+            title = stringResource(R.string.delete),+            message = stringResource(R.string.delete_note_type_message, summary.name, summary.noteCount),+            confirmLabel = stringResource(R.string.delete),+            dismissLabel = stringResource(R.string.cancel),+            destructive = true,+            onConfirm = {+                actions.deleteNoteType(summary.id)+                pendingDelete = null+            },+            onDismiss = { pendingDelete = null },+        )+    }+}++// ---------------------------------------------------------------------------+// Note type editor+// ---------------------------------------------------------------------------++/** Binds the editor for the note type with [noteTypeId] (0 for a new one). */+@Composable+fun NoteTypeEditPage(backStack: NavBackStack<Route>, viewModel: FlashcardsViewModel, noteTypeId: Long) {+    val noteTypes by viewModel.noteTypes.collectAsStateWithLifecycle()+    val cfg = noteTypes.firstOrNull { it.noteType.id == noteTypeId }+    val isNew = noteTypeId == 0L++    val actions = remember(backStack, viewModel, noteTypeId) {+        object : NoteTypeEditActions {+            override fun back() { backStack.pop() }+            override fun save(name: String, css: String, type: Int, fields: List<String>, templates: List<TemplateDraft>) {+                viewModel.saveNoteType(noteTypeId, name, css, type, fields, templates)+                backStack.pop()+            }+            override fun delete() {+                viewModel.deleteNoteType(noteTypeId)+                backStack.pop()+            }+        }+    }++    NoteTypeEditScreen(+        state = NoteTypeEditUiState(+            id = noteTypeId,+            name = cfg?.noteType?.name.orEmpty(),+            css = cfg?.noteType?.css.orEmpty(),+            type = cfg?.noteType?.type ?: NoteTypeKind.STANDARD,+            fields = cfg?.fields?.map { it.name } ?: listOf("Front", "Back"),+            templates = cfg?.templates?.map { TemplateDraft(it.name, it.qfmt, it.afmt) }+                ?: listOf(TemplateDraft("Card 1", "{{Front}}", "{{FrontSide}}\n\n---\n\n{{Back}}")),+            isNew = isNew,+        ),+        actions = actions,+    )+}++@Composable+fun NoteTypeEditScreen(state: NoteTypeEditUiState, actions: NoteTypeEditActions) {+    var name by remember(state) { mutableStateOf(state.name) }+    var css by remember(state) { mutableStateOf(state.css) }+    var type by remember(state) { mutableIntStateOf(state.type) }+    val fields = remember(state) { mutableStateListOf(*state.fields.toTypedArray()) }+    val templates = remember(state) { mutableStateListOf(*state.templates.toTypedArray()) }+    val builtIn = state.id in FlashcardsViewModel.BUILT_IN_NOTE_TYPE_IDS++    AppScaffold(+        title = if (state.isNew) stringResource(R.string.new_note_type) else stringResource(R.string.edit_note_type),+        onNavigateBack = { actions.back() },+        actions = {+            IconButton(onClick = {+                actions.save(name.ifBlank { "Note type" }, css, type, fields.toList(), templates.toList())+            }) { com.vayunmathur.library.ui.IconSave() }+        },+    ) { paddingValues ->+        Column(+            Modifier+                .padding(paddingValues)+                .fillMaxSize()+                .verticalScroll(rememberScrollState())+                .padding(16.dp),+        ) {+            OutlinedTextField(+                value = name,+                onValueChange = { name = it },+                label = { Text(stringResource(R.string.name)) },+                singleLine = true,+                modifier = Modifier.fillMaxWidth(),+            )++            Row(Modifier.padding(top = 12.dp), horizontalArrangement = Arrangement.spacedBy(8.dp)) {+                FilterChip(+                    selected = type == NoteTypeKind.STANDARD,+                    onClick = { type = NoteTypeKind.STANDARD },+                    label = { Text(stringResource(R.string.note_type_standard)) },+                    enabled = !builtIn,+                )+                FilterChip(+                    selected = type == NoteTypeKind.CLOZE,+                    onClick = {+                        type = NoteTypeKind.CLOZE+                        while (templates.size > 1) templates.removeAt(templates.lastIndex)+                    },+                    label = { Text(stringResource(R.string.note_type_cloze)) },+                    enabled = !builtIn,+                )+            }++            // Fields+            Text(+                stringResource(R.string.fields),+                style = MaterialTheme.typography.titleMedium,+                modifier = Modifier.padding(top = 16.dp),+            )+            fields.forEachIndexed { index, fieldName ->+                Row(Modifier.fillMaxWidth().padding(top = 4.dp), verticalAlignment = Alignment.CenterVertically) {+                    OutlinedTextField(+                        value = fieldName,+                        onValueChange = { fields[index] = it },+                        singleLine = true,+                        modifier = Modifier.weight(1f),+                    )+                    IconButton(onClick = { if (index > 0) fields.add(index - 1, fields.removeAt(index)) }) {+                        com.vayunmathur.library.ui.IconKeyboardArrowUp()+                    }+                    IconButton(onClick = { if (fields.size > 1) fields.removeAt(index) }) { IconDelete() }+                }+            }+            OutlinedButton(onClick = { fields.add("Field ${fields.size + 1}") }, modifier = Modifier.padding(top = 4.dp)) {+                IconAdd(); Text(stringResource(R.string.add_field))+            }++            // Templates+            Text(+                stringResource(R.string.templates),+                style = MaterialTheme.typography.titleMedium,+                modifier = Modifier.padding(top = 16.dp),+            )+            templates.forEachIndexed { index, draft ->+                TemplateEditor(+                    draft = draft,+                    canDelete = templates.size > 1 && type != NoteTypeKind.CLOZE,+                    onChange = { templates[index] = it },+                    onDelete = { templates.removeAt(index) },+                    fields = fields.toList(),+                    isCloze = type == NoteTypeKind.CLOZE,+                )+            }+            if (type != NoteTypeKind.CLOZE) {+                OutlinedButton(+                    onClick = { templates.add(TemplateDraft("Card ${templates.size + 1}", "{{Front}}", "{{Back}}")) },+                    modifier = Modifier.padding(top = 4.dp),+                ) {+                    IconAdd(); Text(stringResource(R.string.add_template))+                }+            }++            if (!state.isNew && !builtIn) {+                OutlinedButton(onClick = { actions.delete() }, modifier = Modifier.padding(top = 24.dp)) {+                    IconDelete(); Text(stringResource(R.string.delete))+                }+            }+        }+    }+}++@Composable+private fun TemplateEditor(+    draft: TemplateDraft,+    canDelete: Boolean,+    onChange: (TemplateDraft) -> Unit,+    onDelete: () -> Unit,+    fields: List<String>,+    isCloze: Boolean,+) {+    Card(modifier = Modifier.fillMaxWidth().padding(top = 8.dp)) {+        Column(Modifier.padding(12.dp)) {+            Row(verticalAlignment = Alignment.CenterVertically) {+                OutlinedTextField(+                    value = draft.name,+                    onValueChange = { onChange(draft.copy(name = it)) },+                    label = { Text(stringResource(R.string.template_name)) },+                    singleLine = true,+                    modifier = Modifier.weight(1f),+                )+                if (canDelete) {+                    IconButton(onClick = onDelete) { IconDelete() }+                }+            }+            OutlinedTextField(+                value = draft.qfmt,+                onValueChange = { onChange(draft.copy(qfmt = it)) },+                label = { Text(stringResource(R.string.template_front)) },+                modifier = Modifier.fillMaxWidth().padding(top = 8.dp),+            )+            OutlinedTextField(+                value = draft.afmt,+                onValueChange = { onChange(draft.copy(afmt = it)) },+                label = { Text(stringResource(R.string.template_back)) },+                modifier = Modifier.fillMaxWidth().padding(top = 8.dp),+            )+            TemplatePreview(draft, fields, isCloze)+        }+    }+}++@Composable+private fun TemplatePreview(draft: TemplateDraft, fields: List<String>, isCloze: Boolean) {+    val sample = if (isCloze) {+        fields.associateWith { name ->+            if (name.equals("Text", true) || fields.firstOrNull() == name) "The {{c1::answer}} here" else name+        }+    } else {+        fields.associateWith { it }+    }+    val (front, back) = TemplateEngine.render(+        draft.qfmt,+        draft.afmt,+        sample,+        clozeOrd = if (isCloze) 0 else null,+    )+    Column(Modifier.padding(top = 8.dp)) {+        Text(stringResource(R.string.preview), style = MaterialTheme.typography.labelMedium)+        Text(parseMarkdown(front, showMarkers = false), style = MaterialTheme.typography.bodyMedium)+        HorizontalDivider(Modifier.padding(vertical = 6.dp))+        Text(parseMarkdown(back, showMarkers = false), style = MaterialTheme.typography.bodyMedium)+    }+}
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.ktindex 98e737e5b7..5b87df2f3d 100644--- a/flashcards/src/main/java/com/vayunmathur/flashcards/ui/SettingsPage.kt+++ b/flashcards/src/main/java/com/vayunmathur/flashcards/ui/SettingsPage.kt@@ -1,9 +1,11 @@ package com.vayunmathur.flashcards.ui  import android.Manifest+import android.content.Intent import android.os.Build import androidx.activity.compose.rememberLauncherForActivityResult import androidx.activity.result.contract.ActivityResultContracts+import androidx.compose.runtime.LaunchedEffect import androidx.compose.foundation.layout.Arrangement import androidx.compose.foundation.layout.Column import androidx.compose.foundation.layout.Row@@ -18,6 +20,7 @@ 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@@ -44,11 +47,25 @@ import kotlin.math.roundToInt @Composable fun SettingsPage(backStack: NavBackStack<Route>, viewModel: FlashcardsViewModel) {     val settings by viewModel.settings.collectAsStateWithLifecycle()+    val context = LocalContext.current      val permissionLauncher = rememberLauncherForActivityResult(         ActivityResultContracts.RequestPermission(),     ) {} +    LaunchedEffect(viewModel) {+        viewModel.shareRequests.collect { uri ->+            val intent = Intent(Intent.ACTION_SEND).apply {+                type = "application/octet-stream"+                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 = object : SettingsActions {         override fun back() { backStack.pop() }         override fun setDesiredRetention(value: Double) { viewModel.setDesiredRetention(value) }@@ -64,6 +81,8 @@ fun SettingsPage(backStack: NavBackStack<Route>, viewModel: FlashcardsViewModel)         override fun setReminderTime(hour: Int, minute: Int) {             viewModel.setReminderTime(hour, minute)         }+        override fun manageNoteTypes() { backStack.add(Route.NoteTypeList) }+        override fun exportCollection() { viewModel.exportApkg(null) }     }      SettingsScreen(state = settings, actions = actions)@@ -135,6 +154,18 @@ fun SettingsScreen(state: SettingsUiState, actions: SettingsActions) {                     ThemeChip(R.string.theme_dark, ThemeMode.DARK, state.themeMode, actions)                 }             }++            SettingsSection(title = stringResource(R.string.settings_data)) {+                SettingsRow(+                    title = stringResource(R.string.manage_note_types),+                    onClick = { actions.manageNoteTypes() },+                )+                SettingsRow(+                    title = stringResource(R.string.export_collection),+                    supportingText = stringResource(R.string.export_collection_hint),+                    onClick = { actions.exportCollection() },+                )+            }         }     } 
flashcards/src/main/java/com/vayunmathur/flashcards/util/ApkgExport.kt
diff --git a/flashcards/src/main/java/com/vayunmathur/flashcards/util/ApkgExport.kt b/flashcards/src/main/java/com/vayunmathur/flashcards/util/ApkgExport.ktnew file mode 100644index 0000000000..c383e4802b--- /dev/null+++ b/flashcards/src/main/java/com/vayunmathur/flashcards/util/ApkgExport.kt@@ -0,0 +1,329 @@+package com.vayunmathur.flashcards.util++import android.content.ContentValues+import android.content.Context+import android.database.sqlite.SQLiteDatabase+import com.vayunmathur.flashcards.data.Card+import com.vayunmathur.flashcards.data.Deck+import com.vayunmathur.flashcards.data.Note+import com.vayunmathur.flashcards.data.NoteTypeKind+import com.vayunmathur.library.util.BackupHelper+import org.json.JSONArray+import org.json.JSONObject+import java.io.File+import java.security.MessageDigest++/**+ * Writes a legacy **schema-11** `.apkg` (a zip of a plain `collection.anki2`+ * SQLite database plus an empty `media` manifest). Cards are exported as *new*+ * (Anki's SM-2 scheduling differs from our FSRS, so transferring it would be+ * lossy); media is dropped (text-only app).+ */+object ApkgExport {++    /** Builds the `.apkg` for the given data and returns the shareable file. */+    fun write(+        context: Context,+        name: String,+        decks: List<Deck>,+        notes: List<Note>,+        cards: List<Card>,+        noteTypes: List<NoteTypeWithConfig>,+    ): File {+        val work = File(context.cacheDir, "apkg_export_${System.currentTimeMillis()}").apply {+            deleteRecursively(); mkdirs()+        }+        val anki2 = File(work, "collection.anki2")+        val db = SQLiteDatabase.openOrCreateDatabase(anki2, null)+        try {+            createSchema(db)+            writeCollectionRow(db, decks, noteTypes)+            writeNotes(db, notes, noteTypes)+            writeCards(db, cards)+        } finally {+            db.close()+        }+        File(work, "media").writeText("{}")++        val outDir = File(context.cacheDir, "shared_decks").apply { mkdirs() }+        val safeName = name.ifBlank { "collection" }.replace(Regex("[^A-Za-z0-9._-]"), "_")+        val apkg = File(outDir, "$safeName.apkg")+        if (apkg.exists()) apkg.delete()+        apkg.outputStream().use { out ->+            BackupHelper.zipFiles(listOf(File(work, "collection.anki2"), File(work, "media")), work, out)+        }+        work.deleteRecursively()+        return apkg+    }++    private fun createSchema(db: SQLiteDatabase) {+        db.execSQL(+            "CREATE TABLE col (id integer primary key, crt integer not null, mod integer not null, " ++                "scm integer not null, ver integer not null, dty integer not null, usn integer not null, " ++                "ls integer not null, conf text not null, models text not null, decks text not null, " ++                "dconf text not null, tags text not null)",+        )+        db.execSQL(+            "CREATE TABLE notes (id integer primary key, guid text not null, mid integer not null, " ++                "mod integer not null, usn integer not null, tags text not null, flds text not null, " ++                "sfld integer not null, csum integer not null, flags integer not null, data text not null)",+        )+        db.execSQL(+            "CREATE TABLE cards (id integer primary key, nid integer not null, did integer not null, " ++                "ord integer not null, mod integer not null, usn integer not null, type integer not null, " ++                "queue integer not null, due integer not null, ivl integer not null, factor integer not null, " ++                "reps integer not null, lapses integer not null, left integer not null, odue integer not null, " ++                "odid integer not null, flags integer not null, data text not null)",+        )+        db.execSQL(+            "CREATE TABLE revlog (id integer primary key, cid integer not null, usn integer not null, " ++                "ease integer not null, ivl integer not null, lastIvl integer not null, factor integer not null, " ++                "time integer not null, type integer not null)",+        )+        db.execSQL("CREATE TABLE graves (usn integer not null, oid integer not null, type integer not null)")+        db.execSQL("CREATE INDEX ix_notes_csum on notes (csum)")+        db.execSQL("CREATE INDEX ix_cards_nid on cards (nid)")+        db.execSQL("CREATE INDEX ix_cards_sched on cards (did, queue, due)")+        db.execSQL("CREATE INDEX ix_revlog_cid on revlog (cid)")+    }++    private fun writeCollectionRow(+        db: SQLiteDatabase,+        decks: List<Deck>,+        noteTypes: List<NoteTypeWithConfig>,+    ) {+        val now = System.currentTimeMillis()+        val crt = now / 1000++        val models = JSONObject()+        noteTypes.forEach { cfg ->+            val model = JSONObject()+            model.put("id", cfg.noteType.id)+            model.put("name", cfg.noteType.name)+            model.put("type", cfg.noteType.type)+            model.put("mod", cfg.noteType.mod)+            model.put("usn", -1)+            model.put("sortf", 0)+            model.put("did", decks.firstOrNull()?.id ?: 1L)+            model.put("css", cfg.noteType.css)+            model.put("latexPre", "")+            model.put("latexPost", "")++            val flds = JSONArray()+            cfg.fields.forEachIndexed { ord, field ->+                flds.put(+                    JSONObject().apply {+                        put("name", field.name)+                        put("ord", ord)+                        put("sticky", false)+                        put("rtl", false)+                        put("font", "Arial")+                        put("size", 20)+                        put("media", JSONArray())+                    },+                )+            }+            model.put("flds", flds)++            val tmpls = JSONArray()+            cfg.templates.forEachIndexed { ord, tpl ->+                tmpls.put(+                    JSONObject().apply {+                        put("name", tpl.name)+                        put("ord", ord)+                        put("qfmt", HtmlConvert.markdownTemplateToHtml(tpl.qfmt))+                        put("afmt", HtmlConvert.markdownTemplateToHtml(tpl.afmt))+                        put("did", JSONObject.NULL)+                        put("bqfmt", "")+                        put("bafmt", "")+                    },+                )+            }+            model.put("tmpls", tmpls)++            val req = JSONArray()+            if (cfg.noteType.type == NoteTypeKind.STANDARD) {+                val fieldOrds = JSONArray().apply { cfg.fields.indices.forEach { put(it) } }+                cfg.templates.indices.forEach { ord ->+                    req.put(JSONArray().apply { put(ord); put("any"); put(fieldOrds) })+                }+            }+            model.put("req", req)++            models.put(cfg.noteType.id.toString(), model)+        }++        val decksJson = JSONObject()+        val deckList = decks.ifEmpty { listOf(Deck(id = 1, name = "Default")) }+        deckList.forEach { deck ->+            decksJson.put(+                deck.id.toString(),+                JSONObject().apply {+                    put("id", deck.id)+                    put("name", deck.name)+                    put("mod", crt)+                    put("usn", -1)+                    put("lrnToday", JSONArray(listOf(0, 0)))+                    put("revToday", JSONArray(listOf(0, 0)))+                    put("newToday", JSONArray(listOf(0, 0)))+                    put("timeToday", JSONArray(listOf(0, 0)))+                    put("conf", 1)+                    put("desc", "")+                    put("dyn", 0)+                    put("collapsed", false)+                    put("extendNew", 0)+                    put("extendRev", 0)+                },+            )+        }++        val conf = JSONObject().apply {+            put("nextPos", 1)+            put("estTimes", true)+            put("activeDecks", JSONArray(listOf(deckList.first().id)))+            put("sortType", "noteFld")+            put("timeLim", 0)+            put("sortBackwards", false)+            put("addToCur", true)+            put("curDeck", deckList.first().id)+            put("newSpread", 0)+            put("dueCounts", true)+            put("curModel", noteTypes.firstOrNull()?.noteType?.id?.toString() ?: "1")+            put("collapseTime", 1200)+        }++        val dconf = JSONObject().apply {+            put(+                "1",+                JSONObject().apply {+                    put("id", 1)+                    put("name", "Default")+                    put("mod", 0)+                    put("usn", 0)+                    put("maxTaken", 60)+                    put("autoplay", true)+                    put("timer", 0)+                    put("replayq", true)+                    put(+                        "new",+                        JSONObject().apply {+                            put("bury", false)+                            put("delays", JSONArray(listOf(1, 10)))+                            put("initialFactor", 2500)+                            put("ints", JSONArray(listOf(1, 4, 0)))+                            put("order", 1)+                            put("perDay", 20)+                        },+                    )+                    put(+                        "rev",+                        JSONObject().apply {+                            put("bury", false)+                            put("ease4", 1.3)+                            put("ivlFct", 1.0)+                            put("maxIvl", 36500)+                            put("perDay", 200)+                            put("hardFactor", 1.2)+                        },+                    )+                    put(+                        "lapse",+                        JSONObject().apply {+                            put("delays", JSONArray(listOf(10)))+                            put("leechAction", 1)+                            put("leechFails", 8)+                            put("minInt", 1)+                            put("mult", 0.0)+                        },+                    )+                    put("dyn", false)+                },+            )+        }++        val values = ContentValues().apply {+            put("id", 1)+            put("crt", crt)+            put("mod", now)+            put("scm", now)+            put("ver", 11)+            put("dty", 0)+            put("usn", 0)+            put("ls", 0)+            put("conf", conf.toString())+            put("models", models.toString())+            put("decks", decksJson.toString())+            put("dconf", dconf.toString())+            put("tags", "{}")+        }+        db.insert("col", null, values)+    }++    private fun writeNotes(+        db: SQLiteDatabase,+        notes: List<Note>,+        noteTypes: List<NoteTypeWithConfig>,+    ) {+        val now = System.currentTimeMillis() / 1000+        notes.forEach { note ->+            val cfg = noteTypes.firstOrNull { it.noteType.id == note.noteTypeId }+            val fieldMd = note.fieldList+            val fieldHtml = fieldMd.map { HtmlConvert.markdownFieldToHtml(it) }+            val flds = fieldHtml.joinToString("\u001f")+            val sfld = stripHtml(fieldHtml.firstOrNull() ?: note.sortField)+            val values = ContentValues().apply {+                put("id", note.id)+                put("guid", note.guid.ifBlank { FlashcardsViewModel.randomGuid() })+                put("mid", note.noteTypeId)+                put("mod", if (note.mod > 0) note.mod else now)+                put("usn", -1)+                put("tags", if (note.tags.isBlank()) "" else " ${note.tags.trim()} ")+                put("flds", flds)+                put("sfld", sfld)+                put("csum", fieldChecksum(sfld))+                put("flags", 0)+                put("data", "")+            }+            db.insert("notes", null, values)+            // cfg is only needed for validation; suppress unused warning.+            cfg?.let { }+        }+    }++    private fun writeCards(db: SQLiteDatabase, cards: List<Card>) {+        val now = System.currentTimeMillis() / 1000+        cards.forEach { card ->+            val values = ContentValues().apply {+                put("id", card.id)+                put("nid", card.noteId)+                put("did", card.deckId)+                put("ord", card.templateOrd)+                put("mod", now)+                put("usn", -1)+                put("type", 0)+                put("queue", 0)+                put("due", (card.position.toLong()).coerceAtLeast(1))+                put("ivl", 0)+                put("factor", 0)+                put("reps", 0)+                put("lapses", 0)+                put("left", 0)+                put("odue", 0)+                put("odid", 0)+                put("flags", 0)+                put("data", "")+            }+            db.insert("cards", null, values)+        }+    }++    private fun stripHtml(html: String): String =+        Regex("<[^>]+>").replace(html, "").trim()++    /** Anki's field checksum: the first 8 hex digits of sha1(sfld), as an integer. */+    private fun fieldChecksum(sfld: String): Long {+        val digest = MessageDigest.getInstance("SHA-1").digest(sfld.toByteArray(Charsets.UTF_8))+        val hex = digest.joinToString("") { "%02x".format(it) }+        return hex.substring(0, 8).toLong(16)+    }+}
flashcards/src/main/java/com/vayunmathur/flashcards/util/ApkgImport.kt
diff --git a/flashcards/src/main/java/com/vayunmathur/flashcards/util/ApkgImport.kt b/flashcards/src/main/java/com/vayunmathur/flashcards/util/ApkgImport.ktnew file mode 100644index 0000000000..2a46656d81--- /dev/null+++ b/flashcards/src/main/java/com/vayunmathur/flashcards/util/ApkgImport.kt@@ -0,0 +1,244 @@+package com.vayunmathur.flashcards.util++import android.content.Context+import android.database.sqlite.SQLiteDatabase+import android.net.Uri+import com.vayunmathur.flashcards.data.Card+import com.vayunmathur.flashcards.data.CardDao+import com.vayunmathur.flashcards.data.CardTemplate+import com.vayunmathur.flashcards.data.CardTemplateDao+import com.vayunmathur.flashcards.data.Deck+import com.vayunmathur.flashcards.data.DeckDao+import com.vayunmathur.flashcards.data.Note+import com.vayunmathur.flashcards.data.NoteDao+import com.vayunmathur.flashcards.data.NoteType+import com.vayunmathur.flashcards.data.NoteTypeDao+import com.vayunmathur.flashcards.data.NoteTypeField+import com.vayunmathur.flashcards.data.NoteTypeFieldDao+import org.json.JSONObject+import java.io.File+import java.util.zip.ZipInputStream++/**+ * Imports a legacy **schema-11** `.apkg` (a zip of a plain `collection.anki2`).+ * Media is dropped and all imported cards enter as *new* (Anki's SM-2 scheduling+ * is not transferred). Newer zstd-only exports (`collection.anki21b` without a+ * `collection.anki2`) are detected and rejected with a clear message.+ */+object ApkgImport {++    class ApkgFormatException(message: String) : Exception(message)++    suspend fun import(+        context: Context,+        uri: Uri,+        deckDao: DeckDao,+        noteTypeDao: NoteTypeDao,+        fieldDao: NoteTypeFieldDao,+        templateDao: CardTemplateDao,+        noteDao: NoteDao,+        cardDao: CardDao,+    ): String {+        val work = File(context.cacheDir, "apkg_import_${System.currentTimeMillis()}").apply {+            deleteRecursively(); mkdirs()+        }+        try {+            val temp = File(work, "in.apkg")+            context.contentResolver.openInputStream(uri)?.use { input ->+                temp.outputStream().use { input.copyTo(it) }+            } ?: throw ApkgFormatException("Could not open file")++            unzipGuarded(temp, work)++            val anki2 = File(work, "collection.anki2")+            if (!anki2.exists()) {+                val newer = File(work, "collection.anki21b").exists()+                throw ApkgFormatException(+                    if (newer) {+                        "This .apkg uses the newer Anki format. Re-export it with " ++                            "\"Support older Anki versions\" enabled."+                    } else {+                        "Not a valid .apkg file"+                    },+                )+            }++            val db = SQLiteDatabase.openDatabase(anki2.absolutePath, null, SQLiteDatabase.OPEN_READONLY)+            try {+                return importCollection(db, deckDao, noteTypeDao, fieldDao, templateDao, noteDao, cardDao)+            } finally {+                db.close()+            }+        } finally {+            work.deleteRecursively()+        }+    }++    private suspend fun importCollection(+        db: SQLiteDatabase,+        deckDao: DeckDao,+        noteTypeDao: NoteTypeDao,+        fieldDao: NoteTypeFieldDao,+        templateDao: CardTemplateDao,+        noteDao: NoteDao,+        cardDao: CardDao,+    ): String {+        val (modelsJson, decksJson) = db.rawQuery("SELECT models, decks FROM col LIMIT 1", null).use { c ->+            if (!c.moveToFirst()) throw ApkgFormatException("Empty collection")+            JSONObject(c.getString(0)) to JSONObject(c.getString(1))+        }++        val modelIdMap = importNoteTypes(modelsJson, noteTypeDao, fieldDao, templateDao)++        // Raw cards first, so we know which decks are actually used.+        data class RawCard(val id: Long, val nid: Long, val did: Long, val ord: Int)+        val rawCards = mutableListOf<RawCard>()+        db.rawQuery("SELECT id, nid, did, ord FROM cards", null).use { c ->+            while (c.moveToNext()) {+                rawCards.add(RawCard(c.getLong(0), c.getLong(1), c.getLong(2), c.getInt(3)))+            }+        }++        val deckIdMap = importDecks(rawCards.map { it.did }.toSet(), decksJson, deckDao)+        val fallbackDeckId = deckIdMap.values.firstOrNull()+            ?: deckDao.upsert(Deck(name = "Imported"))+        val nidToDid = rawCards.associate { it.nid to it.did }++        // Notes.+        val noteIdMap = HashMap<Long, Long>()+        val positionByDeck = HashMap<Long, Double>()+        var noteCount = 0+        db.rawQuery("SELECT id, guid, mid, tags, flds, mod FROM notes", null).use { c ->+            while (c.moveToNext()) {+                val oldId = c.getLong(0)+                val guid = c.getString(1) ?: FlashcardsViewModel.randomGuid()+                val mid = c.getLong(2)+                val tags = c.getString(3)?.trim().orEmpty()+                val fldsHtml = c.getString(4) ?: ""+                val mod = c.getLong(5)++                val noteTypeId = modelIdMap[mid] ?: continue+                val deckId = deckIdMap[nidToDid[oldId]] ?: fallbackDeckId+                val fieldsMd = fldsHtml.split("\u001f").map { HtmlConvert.htmlToMarkdown(it) }+                val position = positionByDeck.getOrDefault(deckId, 0.0) + 1.0+                positionByDeck[deckId] = position+                val note = Note(+                    noteTypeId = noteTypeId,+                    deckId = deckId,+                    guid = guid,+                    flds = fieldsMd.joinToString("\u001f"),+                    sortField = fieldsMd.firstOrNull().orEmpty(),+                    tags = tags,+                    mod = mod,+                    position = position,+                )+                val newId = noteDao.upsert(note)+                noteIdMap[oldId] = newId+                noteCount+++            }+        }++        // Cards (as new).+        val cardPositionByDeck = HashMap<Long, Double>()+        val newCards = rawCards.mapNotNull { raw ->+            val noteId = noteIdMap[raw.nid] ?: return@mapNotNull null+            val deckId = deckIdMap[raw.did] ?: fallbackDeckId+            val position = cardPositionByDeck.getOrDefault(deckId, 0.0) + 1.0+            cardPositionByDeck[deckId] = position+            Card(noteId = noteId, templateOrd = raw.ord, deckId = deckId, position = position)+        }+        if (newCards.isNotEmpty()) cardDao.upsertAll(newCards)++        return "Imported $noteCount notes and ${newCards.size} cards"+    }++    private suspend fun importNoteTypes(+        modelsJson: JSONObject,+        noteTypeDao: NoteTypeDao,+        fieldDao: NoteTypeFieldDao,+        templateDao: CardTemplateDao,+    ): Map<Long, Long> {+        val map = HashMap<Long, Long>()+        val keys = modelsJson.keys()+        while (keys.hasNext()) {+            val key = keys.next()+            val model = modelsJson.getJSONObject(key)+            val oldId = key.toLongOrNull() ?: model.optLong("id")+            val type = model.optInt("type", 0)+            val newId = noteTypeDao.upsert(+                NoteType(+                    name = model.optString("name", "Imported"),+                    type = type,+                    css = model.optString("css", ""),+                    mod = model.optLong("mod", 0),+                ),+            )+            map[oldId] = newId++            val fldArray = model.getJSONArray("flds")+            val fields = (0 until fldArray.length()).map { i ->+                val fld = fldArray.getJSONObject(i)+                fld.optInt("ord", i) to fld.optString("name", "Field $i")+            }.sortedBy { it.first }+            fieldDao.upsertAll(+                fields.mapIndexed { ord, (_, name) -> NoteTypeField(noteTypeId = newId, ord = ord, name = name) },+            )++            val tmplArray = model.getJSONArray("tmpls")+            val templates = (0 until tmplArray.length()).map { i ->+                val tmpl = tmplArray.getJSONObject(i)+                Triple(+                    tmpl.optInt("ord", i),+                    tmpl.optString("name", "Card ${i + 1}"),+                    HtmlConvert.htmlTemplateToMarkdown(tmpl.optString("qfmt", "")) to+                        HtmlConvert.htmlTemplateToMarkdown(tmpl.optString("afmt", "")),+                )+            }.sortedBy { it.first }+            templateDao.upsertAll(+                templates.mapIndexed { ord, (_, name, fmt) ->+                    CardTemplate(noteTypeId = newId, ord = ord, name = name, qfmt = fmt.first, afmt = fmt.second)+                },+            )+        }+        return map+    }++    private suspend fun importDecks(+        usedDids: Set<Long>,+        decksJson: JSONObject,+        deckDao: DeckDao,+    ): Map<Long, Long> {+        val map = HashMap<Long, Long>()+        usedDids.forEach { did ->+            val name = decksJson.optJSONObject(did.toString())?.optString("name")+                ?.takeIf { it.isNotBlank() }+                ?: "Imported"+            map[did] = deckDao.upsert(Deck(name = name))+        }+        return map+    }++    /** Unzips [zip] into [targetDir], rejecting entries that escape the directory. */+    private fun unzipGuarded(zip: File, targetDir: File) {+        val canonicalTarget = targetDir.canonicalPath+        ZipInputStream(zip.inputStream().buffered()).use { zis ->+            var entry = zis.nextEntry+            while (entry != null) {+                val outFile = File(targetDir, entry.name)+                if (!outFile.canonicalPath.startsWith(canonicalTarget + File.separator) &&+                    outFile.canonicalPath != canonicalTarget+                ) {+                    throw ApkgFormatException("Unsafe zip entry: ${entry.name}")+                }+                if (entry.isDirectory) {+                    outFile.mkdirs()+                } else {+                    outFile.parentFile?.mkdirs()+                    outFile.outputStream().use { zis.copyTo(it) }+                }+                zis.closeEntry()+                entry = zis.nextEntry+            }+        }+    }+}
flashcards/src/main/java/com/vayunmathur/flashcards/util/CardGenerator.kt
diff --git a/flashcards/src/main/java/com/vayunmathur/flashcards/util/CardGenerator.kt b/flashcards/src/main/java/com/vayunmathur/flashcards/util/CardGenerator.ktnew file mode 100644index 0000000000..fc3134ddf3--- /dev/null+++ b/flashcards/src/main/java/com/vayunmathur/flashcards/util/CardGenerator.kt@@ -0,0 +1,79 @@+package com.vayunmathur.flashcards.util++import com.vayunmathur.flashcards.data.Card+import com.vayunmathur.flashcards.data.CardDao+import com.vayunmathur.flashcards.data.CardTemplate+import com.vayunmathur.flashcards.data.Note+import com.vayunmathur.flashcards.data.NoteType+import com.vayunmathur.flashcards.data.NoteTypeField+import com.vayunmathur.flashcards.data.NoteTypeKind++/**+ * Decides which [Card]s a [Note] should generate and keeps the stored cards in+ * sync with its note type's templates. The [findClozeOrds]/[requiredOrds]+ * decisions are pure Kotlin (unit-testable); [regenerate] applies them to the DB.+ */+object CardGenerator {++    private val clozeNumberRegex = Regex("""\{\{c(\d+)::""")++    /** The set of card ords a note requires: cloze indices, or non-empty templates. */+    fun requiredOrds(+        noteType: NoteType,+        templates: List<CardTemplate>,+        fields: List<NoteTypeField>,+        flds: String,+    ): Set<Int> {+        if (noteType.type == NoteTypeKind.CLOZE) return findClozeOrds(flds)++        val note = Note(noteTypeId = noteType.id, deckId = 0, guid = "", flds = flds, sortField = "")+        val values = note.fieldValues(fields)+        return templates+            .filter { template ->+                val (front, _) = TemplateEngine.render(template.qfmt, template.afmt, values, clozeOrd = null)+                front.isNotBlank()+            }+            .map { it.ord }+            .toSet()+    }++    /** Cloze card ords (cloze number − 1) present anywhere in [flds]. */+    fun findClozeOrds(flds: String): Set<Int> =+        clozeNumberRegex.findAll(flds)+            .mapNotNull { it.groupValues[1].toIntOrNull() }+            .filter { it >= 1 }+            .map { it - 1 }+            .toSet()++    /**+     * Regenerates [note]'s cards after a save or a note-type change: inserts cards+     * for newly-required ords (assigning the next deck position), leaves existing+     * cards' scheduling untouched, and deletes cards for ords that are no longer+     * required.+     */+    suspend fun regenerate(+        note: Note,+        noteType: NoteType,+        templates: List<CardTemplate>,+        fields: List<NoteTypeField>,+        cardDao: CardDao,+    ) {+        val required = requiredOrds(noteType, templates, fields, note.flds)+        if (required.isEmpty()) {+            cardDao.deleteByNote(note.id)+            return+        }+        cardDao.deleteRemovedTemplates(note.id, required.toList())++        val existingOrds = cardDao.getByNote(note.id).map { it.templateOrd }.toSet()+        val newOrds = required.filter { it !in existingOrds }.sorted()+        if (newOrds.isNotEmpty()) {+            var position = cardDao.getByDeck(note.deckId).maxOfOrNull { it.position } ?: 0.0+            val newCards = newOrds.map { ord ->+                position += 1.0+                Card(noteId = note.id, templateOrd = ord, deckId = note.deckId, position = position)+            }+            cardDao.upsertAll(newCards)+        }+    }+}
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.ktindex 2960acc5f1..b0e8e86119 100644--- a/flashcards/src/main/java/com/vayunmathur/flashcards/util/DeckIo.kt+++ b/flashcards/src/main/java/com/vayunmathur/flashcards/util/DeckIo.kt@@ -1,29 +1,7 @@ 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). */+/** CSV import for bulk note creation. Per-deck sharing now uses `.apkg` (see [ApkgExport]). */ 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
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 8f6b8ad273..a0f3251e8a 100644--- a/flashcards/src/main/java/com/vayunmathur/flashcards/util/FlashcardsUiContract.kt+++ b/flashcards/src/main/java/com/vayunmathur/flashcards/util/FlashcardsUiContract.kt@@ -1,7 +1,10 @@ package com.vayunmathur.flashcards.util -import com.vayunmathur.flashcards.data.Card+import com.vayunmathur.flashcards.data.CardTemplate import com.vayunmathur.flashcards.data.Deck+import com.vayunmathur.flashcards.data.Note+import com.vayunmathur.flashcards.data.NoteType+import com.vayunmathur.flashcards.data.NoteTypeField  /**  * The UI contract between [FlashcardsViewModel] plus the nav back stack and the screens.@@ -45,56 +48,135 @@ interface DeckListActions { }  // ----------------------------------------------------------------------------// Card list+// Note list // --------------------------------------------------------------------------- -/** Everything the card list draws for a single deck. */-data class CardListUiState(+/** A note plus the number of cards it currently generates, drawn on the note list. */+data class NoteRow(+    val note: Note,+    val cardCount: Int = 1,+)++/** Everything the note list draws for a single deck. */+data class NoteListUiState(     val deckName: String = "",-    val cards: List<Card> = emptyList(),+    val notes: List<NoteRow> = emptyList(),     val dueCount: Int = 0, ) -interface CardListActions {+interface NoteListActions {     fun back() {}-    fun openCard(id: Long) {}-    fun addCard() {}-    fun deleteCard(card: Card) {}+    fun openNote(id: Long) {}+    fun addNote() {}+    fun deleteNote(note: Note) {}     fun study() {}-    fun reorder(cards: List<Card>) {}+    fun reorder(notes: List<Note>) {}     fun openStats() {}     fun share() {}      companion object {-        val Noop: CardListActions = object : CardListActions {}+        val Noop: NoteListActions = object : NoteListActions {}     } }  // ----------------------------------------------------------------------------// Card editor+// Note editor // --------------------------------------------------------------------------- -/** Everything the card editor draws: the two markdown sides plus tags. */-data class CardEditUiState(-    val front: String = "",-    val back: String = "",-    val tags: String = "",+/** A note type and its ordered field names, used to drive the note editor's fields. */+data class NoteTypeConfig(+    val id: Long,+    val name: String,+    val fieldNames: List<String>,+)++/** Everything the note editor draws: the selected note type, its fields, and tags. */+data class NoteEditUiState(+    val initialNoteTypeId: Long = 0,+    val initialDeckId: Long = 0,+    /** Field values in the selected note type's field order. */+    val initialFieldValues: List<String> = emptyList(),+    val initialTags: String = "",+    val isNew: Boolean = true,+    val noteTypes: List<NoteTypeConfig> = emptyList(),+    val decks: List<DeckOption> = emptyList(),+)++interface NoteEditActions {+    fun back() {}+    fun save(noteTypeId: Long, deckId: Long, fieldValues: List<String>, tags: String) {}+    fun deleteNote() {}++    companion object {+        val Noop: NoteEditActions = object : NoteEditActions {}+    }+}++// ---------------------------------------------------------------------------+// Note type list + editor+// ---------------------------------------------------------------------------++/** A note type plus its counts, drawn on the note-type management list. */+data class NoteTypeSummary(+    val id: Long,+    val name: String,+    val fieldCount: Int,+    val templateCount: Int,+    val noteCount: Int,+    val isCloze: Boolean,+)++data class NoteTypeListUiState(+    val noteTypes: List<NoteTypeSummary> = emptyList(),+)++interface NoteTypeListActions {+    fun back() {}+    fun openNoteType(id: Long) {}+    fun addNoteType() {}+    fun deleteNoteType(id: Long) {}++    companion object {+        val Noop: NoteTypeListActions = object : NoteTypeListActions {}+    }+}++/** An editable template draft in the note-type editor. */+data class TemplateDraft(+    val name: String,+    val qfmt: String,+    val afmt: String,+)++/** Everything the note-type editor draws for one note type. */+data class NoteTypeEditUiState(+    val id: Long = 0,+    val name: String = "",+    val css: String = "",+    /** [com.vayunmathur.flashcards.data.NoteTypeKind]. Cloze note types have a fixed single template. */+    val type: Int = 0,+    val fields: List<String> = emptyList(),+    val templates: List<TemplateDraft> = emptyList(),     val isNew: Boolean = true, ) -interface CardEditActions {+interface NoteTypeEditActions {     fun back() {}-    fun setFront(front: String) {}-    fun setBack(back: String) {}-    fun setTags(tags: String) {}-    fun save() {}-    fun deleteCard() {}+    fun save(name: String, css: String, type: Int, fields: List<String>, templates: List<TemplateDraft>) {}+    fun delete() {}      companion object {-        val Noop: CardEditActions = object : CardEditActions {}+        val Noop: NoteTypeEditActions = object : NoteTypeEditActions {}     } } +/** Bundles a note type with its ordered fields and templates for in-memory caching. */+data class NoteTypeWithConfig(+    val noteType: NoteType,+    val fields: List<NoteTypeField>,+    val templates: List<CardTemplate>,+)+ // --------------------------------------------------------------------------- // Review session // ---------------------------------------------------------------------------@@ -187,6 +269,8 @@ interface SettingsActions {     fun setReminderEnabled(enabled: Boolean) {}     fun setReminderTime(hour: Int, minute: Int) {}     fun setThemeMode(mode: Int) {}+    fun manageNoteTypes() {}+    fun exportCollection() {}      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 902d3a4d41..42b584f5fb 100644--- a/flashcards/src/main/java/com/vayunmathur/flashcards/util/FlashcardsViewModel.kt+++ b/flashcards/src/main/java/com/vayunmathur/flashcards/util/FlashcardsViewModel.kt@@ -10,8 +10,18 @@ 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.CardTemplate+import com.vayunmathur.flashcards.data.CardTemplateDao import com.vayunmathur.flashcards.data.Deck import com.vayunmathur.flashcards.data.DeckDao+import com.vayunmathur.flashcards.data.FIELD_SEPARATOR+import com.vayunmathur.flashcards.data.Note+import com.vayunmathur.flashcards.data.NoteDao+import com.vayunmathur.flashcards.data.NoteType+import com.vayunmathur.flashcards.data.NoteTypeDao+import com.vayunmathur.flashcards.data.NoteTypeField+import com.vayunmathur.flashcards.data.NoteTypeFieldDao+import com.vayunmathur.flashcards.data.NoteTypeKind import com.vayunmathur.flashcards.data.ReviewLog import com.vayunmathur.flashcards.data.ReviewLogDao import com.vayunmathur.library.util.DataStoreUtils@@ -27,20 +37,26 @@ import kotlinx.coroutines.flow.combine import kotlinx.coroutines.flow.stateIn import kotlinx.coroutines.launch import kotlinx.coroutines.withContext+import kotlin.random.Random  /**  * ViewModel for the Flashcards app.  *- * 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).+ * Owns the deck/note/card [StateFlow]s collected by the screens, the cached+ * [noteTypes] (Anki-style models), the persisted [settings], and the in-memory+ * [ReviewSession] driving the review screen via [review]. Card content is rendered+ * on demand from a note + its template through [TemplateEngine]. Grading runs the+ * pure [Scheduler], upserts the card, and writes a [ReviewLog] row.  */ class FlashcardsViewModel(     application: Application,     private val deckDao: DeckDao,     private val cardDao: CardDao,     private val reviewLogDao: ReviewLogDao,+    private val noteTypeDao: NoteTypeDao,+    private val noteTypeFieldDao: NoteTypeFieldDao,+    private val cardTemplateDao: CardTemplateDao,+    private val noteDao: NoteDao, ) : AndroidViewModel(application) {      private val ds = DataStoreUtils.getInstance(application)@@ -52,9 +68,34 @@ class FlashcardsViewModel(     val cards: StateFlow<List<Card>> = cardDao.getAllFlow()         .stateIn(viewModelScope, SharingStarted.WhileSubscribed(5_000), emptyList()) -    fun cardsFor(deckId: Long): Flow<List<Card>> = cardDao.getByDeckFlow(deckId)+    /** All notes across every deck; the note-type manager derives per-type counts from this. */+    val notes: StateFlow<List<Note>> = noteDao.getAllFlow()+        .stateIn(viewModelScope, SharingStarted.WhileSubscribed(5_000), emptyList())++    /** Every note type with its ordered fields and templates. */+    val noteTypes: StateFlow<List<NoteTypeWithConfig>> = combine(+        noteTypeDao.getAllFlow(),+        noteTypeFieldDao.getAllFlow(),+        cardTemplateDao.getAllFlow(),+    ) { types, fields, templates ->+        types.map { type ->+            NoteTypeWithConfig(+                noteType = type,+                fields = fields.filter { it.noteTypeId == type.id }.sortedBy { it.ord },+                templates = templates.filter { it.noteTypeId == type.id }.sortedBy { it.ord },+            )+        }+    }.stateIn(viewModelScope, SharingStarted.WhileSubscribed(5_000), emptyList())++    init {+        launchIo { ensureBuiltInNoteTypes() }+    } -    fun cardById(id: Long): Flow<Card?> = cardDao.getByIdFlow(id)+    fun notesFor(deckId: Long): Flow<List<Note>> = noteDao.getByDeckFlow(deckId)++    fun noteById(id: Long): Flow<Note?> = noteDao.getByIdFlow(id)++    fun cardsFor(deckId: Long): Flow<List<Card>> = cardDao.getByDeckFlow(deckId)      fun reviewLogsFor(deckId: Long?): Flow<List<ReviewLog>> =         if (deckId == null) reviewLogDao.getAllFlow() else reviewLogDao.getByDeckFlow(deckId)@@ -103,7 +144,7 @@ class FlashcardsViewModel(         ReviewReminder.update(getApplication(), settings.value.reminderEnabled, hour, minute)     } -    // -- Deck / card writes ------------------------------------------------+    // -- Deck writes -------------------------------------------------------      fun upsertDeck(deck: Deck) = launchIo { deckDao.upsert(deck) } @@ -121,28 +162,113 @@ class FlashcardsViewModel(      fun deleteDeck(deck: Deck) = launchIo {         cardDao.deleteByDeck(deck.id)+        noteDao.deleteByDeck(deck.id)         reviewLogDao.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) }+    // -- Note writes -------------------------------------------------------++    fun saveNote(+        noteId: Long,+        noteTypeId: Long,+        deckId: Long,+        fieldValues: List<String>,+        tags: String,+    ) = launchIo {+        val cfg = noteTypes.value.firstOrNull { it.noteType.id == noteTypeId } ?: return@launchIo+        val flds = fieldValues.joinToString(FIELD_SEPARATOR)+        val sortField = fieldValues.firstOrNull().orEmpty()+        val existing = if (noteId != 0L) noteDao.getById(noteId) else null+        val position = existing?.position+            ?: ((noteDao.getByDeck(deckId).maxOfOrNull { it.position } ?: 0.0) + 1.0)+        val note = Note(+            id = noteId,+            noteTypeId = noteTypeId,+            deckId = deckId,+            guid = existing?.guid ?: randomGuid(),+            flds = flds,+            sortField = sortField,+            tags = tags.trim(),+            mod = nowSeconds(),+            position = position,+        )+        val savedId = noteDao.upsert(note)+        val finalNote = if (noteId == 0L) note.copy(id = savedId) else note+        CardGenerator.regenerate(finalNote, cfg.noteType, cfg.templates, cfg.fields, cardDao)+        // Keep generated cards in the note's deck (handles a note being moved decks).+        val misplaced = cardDao.getByNote(finalNote.id).filter { it.deckId != finalNote.deckId }+        if (misplaced.isNotEmpty()) {+            cardDao.upsertAll(misplaced.map { it.copy(deckId = finalNote.deckId) })+        }+    }++    fun deleteNote(note: Note) = launchIo {+        cardDao.deleteByNote(note.id)+        noteDao.delete(note)+    }++    fun reorderNotes(notes: List<Note>) = launchIo { noteDao.upsertAll(notes) }++    // -- Note type CRUD ---------------------------------------------------- -    fun deleteCard(card: Card) = launchIo { cardDao.delete(card) }+    fun saveNoteType(+        id: Long,+        name: String,+        css: String,+        type: Int,+        fieldNames: List<String>,+        templates: List<TemplateDraft>,+    ) = launchIo {+        val savedId = noteTypeDao.upsert(NoteType(id = id, name = name, type = type, css = css, mod = nowSeconds()))+        val ntId = if (id == 0L) savedId else id -    fun reorderCards(cards: List<Card>) = launchIo { cardDao.upsertAll(cards) }+        noteTypeFieldDao.deleteByNoteType(ntId)+        noteTypeFieldDao.upsertAll(+            fieldNames.mapIndexed { ord, fieldName -> NoteTypeField(noteTypeId = ntId, ord = ord, name = fieldName) },+        )++        cardTemplateDao.deleteByNoteType(ntId)+        val effective = if (type == NoteTypeKind.CLOZE) templates.take(1) else templates+        cardTemplateDao.upsertAll(+            effective.mapIndexed { ord, t ->+                CardTemplate(noteTypeId = ntId, ord = ord, name = t.name, qfmt = t.qfmt, afmt = t.afmt)+            },+        )++        // Regenerate cards for every note of this type against the new templates.+        val nt = noteTypeDao.getById(ntId) ?: return@launchIo+        val newFields = noteTypeFieldDao.getByNoteType(ntId)+        val newTemplates = cardTemplateDao.getByNoteType(ntId)+        noteDao.getByNoteType(ntId).forEach { note ->+            CardGenerator.regenerate(note, nt, newTemplates, newFields, cardDao)+        }+    }++    fun deleteNoteType(id: Long) = launchIo {+        if (id in BUILT_IN_NOTE_TYPE_IDS) return@launchIo+        val notes = noteDao.getByNoteType(id)+        notes.forEach { cardDao.deleteByNote(it.id) }+        notes.forEach { noteDao.delete(it) }+        noteTypeFieldDao.deleteByNoteType(id)+        cardTemplateDao.deleteByNoteType(id)+        noteTypeDao.getById(id)?.let { noteTypeDao.delete(it) }+    }      // -- Review session ----------------------------------------------------      private var session: ReviewSession? = null     private var lastLogId: Long? = null+    private var sessionNotes: Map<Long, Note> = emptyMap()     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)+        sessionNotes = noteDao.getByDeck(deckId).associateBy { it.id }         val now = System.currentTimeMillis()         session = ReviewSession(             cards = cards,@@ -197,9 +323,10 @@ class FlashcardsViewModel(         } else {             val now = System.currentTimeMillis()             val current = s.current+            val (front, back) = current?.let { renderCard(it) } ?: ("" to "")             ReviewUiState(-                front = current?.front.orEmpty(),-                back = current?.back.orEmpty(),+                front = front,+                back = back,                 remaining = s.remaining,                 done = s.done,                 newCount = s.newCount,@@ -212,34 +339,129 @@ class FlashcardsViewModel(         }     } +    /** Renders a card's (front, back) markdown from its note and template. */+    private fun renderCard(card: Card): Pair<String, String> {+        val note = sessionNotes[card.noteId] ?: return "" to ""+        val cfg = noteTypes.value.firstOrNull { it.noteType.id == note.noteTypeId }+            ?: return note.sortField to ""+        val values = note.fieldValues(cfg.fields)+        return if (cfg.noteType.type == NoteTypeKind.CLOZE) {+            val template = cfg.templates.firstOrNull() ?: return note.sortField to ""+            TemplateEngine.render(template.qfmt, template.afmt, values, clozeOrd = card.templateOrd)+        } else {+            val template = cfg.templates.firstOrNull { it.ord == card.templateOrd }+                ?: cfg.templates.firstOrNull()+                ?: return note.sortField to ""+            TemplateEngine.render(template.qfmt, template.afmt, values, clozeOrd = null)+        }+    }+     // -- Import / export / share ------------------------------------------      private val _shareRequests = MutableSharedFlow<Uri>(extraBufferCapacity = 1)     val shareRequests = _shareRequests.asSharedFlow() -    fun exportDeck(deckId: Long) = launchIo {+    private val _messages = MutableSharedFlow<String>(extraBufferCapacity = 4)+    val messages = _messages.asSharedFlow()++    /** Exports [deckId] (or the whole collection when null) as a shareable `.apkg`. */+    fun exportApkg(deckId: Long?) = launchIo {         val context = getApplication<Application>()-        val deck = deckDao.getById(deckId) ?: return@launchIo-        val cards = cardDao.getByDeck(deckId)+        val exportedDecks =+            if (deckId == null) deckDao.getAll() else listOfNotNull(deckDao.getById(deckId))+        val notes = if (deckId == null) noteDao.getAll() else noteDao.getByDeck(deckId)+        val noteIds = notes.map { it.id }.toSet()+        val exportedCards = cardDao.getAll().filter { it.noteId in noteIds }+        val configs = noteTypes.value         val uri = withContext(Dispatchers.IO) {-            val file = DeckIo.writeExport(context, deck, cards)+            val name = exportedDecks.singleOrNull()?.name ?: "collection"+            val file = ApkgExport.write(context, name, exportedDecks, notes, exportedCards, configs)             FileProvider.getUriForFile(context, "${context.packageName}.fileprovider", file)         }         _shareRequests.emit(uri)     } +    fun importApkg(uri: Uri) = launchIo {+        val context = getApplication<Application>()+        val message = withContext(Dispatchers.IO) {+            runCatching {+                ApkgImport.import(+                    context, uri, deckDao, noteTypeDao, noteTypeFieldDao, cardTemplateDao, noteDao, cardDao,+                )+            }.getOrElse { it.message ?: "Import failed" }+        }+        _messages.emit(message)+    }+     fun importCsv(deckId: Long, uri: Uri) = launchIo {         val context = getApplication<Application>()+        val cfg = noteTypes.value.firstOrNull { it.noteType.id == BASIC_NOTE_TYPE_ID } ?: return@launchIo         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) ->+        val rows = DeckIo.parseCsv(text)+        if (rows.isEmpty()) return@launchIo+        var position = noteDao.getByDeck(deckId).maxOfOrNull { it.position } ?: 0.0+        rows.forEach { (front, back) ->             position += 1.0-            Card(deckId = deckId, front = front, back = back, position = position)+            val note = Note(+                noteTypeId = BASIC_NOTE_TYPE_ID,+                deckId = deckId,+                guid = randomGuid(),+                flds = listOf(front, back).joinToString(FIELD_SEPARATOR),+                sortField = front,+                mod = nowSeconds(),+                position = position,+            )+            val id = noteDao.upsert(note)+            CardGenerator.regenerate(note.copy(id = id), cfg.noteType, cfg.templates, cfg.fields, cardDao)         }-        if (newCards.isNotEmpty()) cardDao.upsertAll(newCards)+    }++    // -- Built-in note types ----------------------------------------------++    private suspend fun ensureBuiltInNoteTypes() {+        if (noteTypeDao.getAll().isNotEmpty()) return+        seedNoteType(+            id = BASIC_NOTE_TYPE_ID,+            name = "Basic",+            type = NoteTypeKind.STANDARD,+            fields = listOf("Front", "Back"),+            templates = listOf(TemplateDraft("Card 1", "{{Front}}", "{{FrontSide}}\n\n---\n\n{{Back}}")),+        )+        seedNoteType(+            id = 2,+            name = "Basic (and reversed card)",+            type = NoteTypeKind.STANDARD,+            fields = listOf("Front", "Back"),+            templates = listOf(+                TemplateDraft("Card 1", "{{Front}}", "{{FrontSide}}\n\n---\n\n{{Back}}"),+                TemplateDraft("Card 2", "{{Back}}", "{{FrontSide}}\n\n---\n\n{{Front}}"),+            ),+        )+        seedNoteType(+            id = 3,+            name = "Cloze",+            type = NoteTypeKind.CLOZE,+            fields = listOf("Text", "Back Extra"),+            templates = listOf(+                TemplateDraft("Cloze", "{{cloze:Text}}", "{{cloze:Text}}\n\n---\n\n{{Back Extra}}"),+            ),+        )+    }++    private suspend fun seedNoteType(+        id: Long,+        name: String,+        type: Int,+        fields: List<String>,+        templates: List<TemplateDraft>,+    ) {+        noteTypeDao.upsert(NoteType(id = id, name = name, type = type, mod = nowSeconds()))+        noteTypeFieldDao.upsertAll(fields.mapIndexed { ord, f -> NoteTypeField(noteTypeId = id, ord = ord, name = f) })+        cardTemplateDao.upsertAll(+            templates.mapIndexed { ord, t -> CardTemplate(noteTypeId = id, ord = ord, name = t.name, qfmt = t.qfmt, afmt = t.afmt) },+        )     }      private fun launchIo(block: suspend () -> Unit) =@@ -253,6 +475,16 @@ class FlashcardsViewModel(         const val KEY_REMINDER_ENABLED = "reminder_enabled"         const val KEY_REMINDER_MINUTES = "reminder_minutes" +        const val BASIC_NOTE_TYPE_ID = 1L+        val BUILT_IN_NOTE_TYPE_IDS = setOf(1L, 2L, 3L)++        private fun nowSeconds(): Long = System.currentTimeMillis() / 1000++        /** A 16-hex-char random note guid, matching the migration's format. */+        fun randomGuid(): String = (0 until 8).joinToString("") {+            "%02x".format(Random.nextInt(0, 256))+        }+         /** Mastery = fraction of a deck's cards that have graduated to review. */         fun mastery(cards: List<Card>): Float {             if (cards.isEmpty()) return 0f@@ -267,12 +499,19 @@ class FlashcardsViewModelFactory(     private val deckDao: DeckDao,     private val cardDao: CardDao,     private val reviewLogDao: ReviewLogDao,+    private val noteTypeDao: NoteTypeDao,+    private val noteTypeFieldDao: NoteTypeFieldDao,+    private val cardTemplateDao: CardTemplateDao,+    private val noteDao: NoteDao, ) : 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, reviewLogDao) as T+        return FlashcardsViewModel(+            application, deckDao, cardDao, reviewLogDao,+            noteTypeDao, noteTypeFieldDao, cardTemplateDao, noteDao,+        ) as T     } }
flashcards/src/main/java/com/vayunmathur/flashcards/util/HtmlConvert.kt
diff --git a/flashcards/src/main/java/com/vayunmathur/flashcards/util/HtmlConvert.kt b/flashcards/src/main/java/com/vayunmathur/flashcards/util/HtmlConvert.ktnew file mode 100644index 0000000000..b13c4e0804--- /dev/null+++ b/flashcards/src/main/java/com/vayunmathur/flashcards/util/HtmlConvert.kt@@ -0,0 +1,109 @@+package com.vayunmathur.flashcards.util++/**+ * Best-effort conversion between the app's **markdown** and the HTML that Anki+ * stores in note fields and card templates. Text-only: media is dropped.+ *+ * The conversions are intentionally lossy and lightweight (regex-based) — this is+ * a text flashcard app, not a full HTML engine — but they round-trip the common+ * inline/block constructs (bold, italic, code, links, lists, headings, breaks).+ */+object HtmlConvert {++    private val placeholderRegex = Regex("""\{\{[^}]+\}\}""")+    private val bold = Regex("""\*\*(.+?)\*\*""")+    private val italic = Regex("""(?<!\*)\*(?!\*)(.+?)(?<!\*)\*(?!\*)""")+    private val code = Regex("`(.+?)`")+    private val link = Regex("""\[(.*?)]\((.*?)\)""")++    // -- HTML -> Markdown --------------------------------------------------++    /** Converts an Anki HTML fragment to markdown, dropping media. */+    fun htmlToMarkdown(html: String): String {+        var s = html+        s = Regex("""\[sound:[^]]*]""").replace(s, "")+        // Links before generic tag stripping (needs the href attribute).+        s = Regex("""(?is)<a[^>]*?href="([^"]*)"[^>]*>(.*?)</a>""").replace(s) {+            "[${it.groupValues[2]}](${it.groupValues[1]})"+        }+        // Images -> alt text.+        s = Regex("""(?is)<img[^>]*?alt="([^"]*)"[^>]*>""").replace(s) { it.groupValues[1] }+        s = Regex("""(?is)<img[^>]*>""").replace(s, "")+        s = Regex("""(?i)<br\s*/?>""").replace(s, "\n")+        s = Regex("""(?i)<hr[^>]*/?>""").replace(s, "\n---\n")+        for (level in 1..6) {+            s = Regex("""(?i)<h$level[^>]*>""").replace(s, "#".repeat(level) + " ")+        }+        s = Regex("""(?i)<li[^>]*>""").replace(s, "- ")+        s = Regex("""(?i)</(div|p|li|h[1-6]|blockquote|tr|ul|ol)>""").replace(s, "\n")+        s = Regex("""(?i)</?(b|strong)>""").replace(s, "**")+        s = Regex("""(?i)</?(i|em)>""").replace(s, "*")+        s = Regex("""(?i)</?(code|pre)>""").replace(s, "`")+        // Strip any remaining tags.+        s = Regex("""(?s)<[^>]+>""").replace(s, "")+        s = decodeEntities(s)+        // Collapse excess blank lines.+        s = Regex("""\n{3,}""").replace(s, "\n\n")+        return s.trim()+    }++    /**+     * Converts an Anki template ([qfmt]/[afmt]) HTML into our markdown template+     * syntax, preserving `{{…}}` placeholders (which use the same syntax in Anki).+     */+    fun htmlTemplateToMarkdown(tpl: String): String =+        transformOutsidePlaceholders(tpl) { htmlToMarkdown(it) }++    // -- Markdown -> HTML --------------------------------------------------++    /** Converts a markdown note-field value to HTML for storage in `notes.flds`. */+    fun markdownFieldToHtml(md: String): String = inlineMarkdownToHtml(md).replace("\n", "<br>")++    /**+     * Converts a markdown card template to HTML, preserving `{{…}}` placeholders so+     * Anki can substitute them.+     */+    fun markdownTemplateToHtml(tpl: String): String =+        transformOutsidePlaceholders(tpl) { markdownFieldToHtml(it) }++    // -- helpers -----------------------------------------------------------++    /** Applies [transform] to the literal segments of [text], leaving `{{…}}` intact. */+    private fun transformOutsidePlaceholders(text: String, transform: (String) -> String): String {+        val out = StringBuilder()+        var last = 0+        placeholderRegex.findAll(text).forEach { match ->+            if (match.range.first > last) {+                out.append(transform(text.substring(last, match.range.first)))+            }+            out.append(match.value)+            last = match.range.last + 1+        }+        if (last < text.length) out.append(transform(text.substring(last)))+        return out.toString()+    }++    /** Inline markdown (bold/italic/code/links) -> HTML, escaping the plain text. */+    pri

Diff truncated.