Modern Apps git

← Modern-Apps.git

todo: fix editor data loss, ghost rows, new-task delete; wire drag reorder

Commit
b3d73cc5ad8024bd96afe2fd0f3fa2ed90e55442
Author
Vayun Mathur <[email protected]>
When
2026-10-31 23:06 UTC (1 month ago)
Parents
0112d8e
- Editor writes go through an app-scoped TodoEditor session that flushes on exit,
  so edits made inside the save debounce are no longer dropped.
- New tasks carry a pre-assigned sync id; the editor finds the row again after the
  first save, so deleting a just-created task works.
- Blank new tasks are never inserted, and are discarded if the title is cleared.
- Drag-to-reorder (advertised, never wired) now works; moves rewrite only the moved
  row's fractional position, jittered so concurrent inserts don't collide.
- Bulk upserts bump updatedAt so reorders reach sync.
- Launch housekeeping repairs colliding positions and drops stale unsynced tombstones.
- Search query lives in the ViewModel's SavedStateHandle.
- Replace mirror-style tests with tests that call domain code.

Diff

todo/src/main/java/com/vayunmathur/todo/MainActivity.kt
diff --git a/todo/src/main/java/com/vayunmathur/todo/MainActivity.kt b/todo/src/main/java/com/vayunmathur/todo/MainActivity.ktindex c68d755ba0..77a5571f57 100644--- a/todo/src/main/java/com/vayunmathur/todo/MainActivity.kt+++ b/todo/src/main/java/com/vayunmathur/todo/MainActivity.kt@@ -5,12 +5,11 @@ import androidx.compose.runtime.Composable import com.vayunmathur.library.ui.MaActivity import com.vayunmathur.todo.data.TodoRepository import com.vayunmathur.todo.platform.TodoViewModel-import com.vayunmathur.todo.platform.TodoViewModelFactory  class MainActivity : MaActivity() {     private lateinit var todoRepository: TodoRepository     private val todoViewModel: TodoViewModel by viewModels {-        TodoViewModelFactory(application, todoRepository)+        TodoViewModel.factory(application, todoRepository)     }      override fun onCreateBeforeContent() {
todo/src/main/java/com/vayunmathur/todo/Navigation.kt
diff --git a/todo/src/main/java/com/vayunmathur/todo/Navigation.kt b/todo/src/main/java/com/vayunmathur/todo/Navigation.ktindex 5a75d48fd8..b208e23356 100644--- a/todo/src/main/java/com/vayunmathur/todo/Navigation.kt+++ b/todo/src/main/java/com/vayunmathur/todo/Navigation.kt@@ -18,7 +18,7 @@ fun Navigation(todoViewModel: TodoViewModel) {             TodoListPage(backStack, todoViewModel)         }         entry<Route.TodoDetail>(metadata = ListDetailPage() + MorphPage()) {-            TodoDetailPage(backStack, todoViewModel, it.id)+            TodoDetailPage(backStack, todoViewModel, it)         }     } }
todo/src/main/java/com/vayunmathur/todo/Route.kt
diff --git a/todo/src/main/java/com/vayunmathur/todo/Route.kt b/todo/src/main/java/com/vayunmathur/todo/Route.ktindex 95b9a384b3..3b321738f3 100644--- a/todo/src/main/java/com/vayunmathur/todo/Route.kt+++ b/todo/src/main/java/com/vayunmathur/todo/Route.kt@@ -8,6 +8,7 @@ sealed interface Route : NavKey {     @Serializable     data object TodoList : Route +    /** [id] 0 opens a new task, identified across saves by [newSyncId]. */     @Serializable-    data class TodoDetail(val id: Long) : Route+    data class TodoDetail(val id: Long, val newSyncId: String? = null) : Route }
todo/src/main/java/com/vayunmathur/todo/data/TodoDatabase.kt
diff --git a/todo/src/main/java/com/vayunmathur/todo/data/TodoDatabase.kt b/todo/src/main/java/com/vayunmathur/todo/data/TodoDatabase.ktindex 0d34195198..3d382b8881 100644--- a/todo/src/main/java/com/vayunmathur/todo/data/TodoDatabase.kt+++ b/todo/src/main/java/com/vayunmathur/todo/data/TodoDatabase.kt@@ -31,11 +31,17 @@ abstract class TodoDao {     abstract suspend fun getAllIncludingDeleted(): List<Todo>      @Query("SELECT * FROM Todo WHERE id = :id AND deleted = 0")-    abstract fun getByIdFlow(id: Long): Flow<Todo?>+    abstract suspend fun getById(id: Long): Todo?      @Query("SELECT * FROM Todo WHERE syncId = :syncId")     abstract suspend fun getBySyncId(syncId: String): Todo? +    @Query("SELECT * FROM Todo WHERE syncId = :syncId")+    abstract fun getBySyncIdFlow(syncId: String): Flow<Todo?>++    @Query("SELECT MAX(position) FROM Todo WHERE deleted = 0")+    abstract suspend fun maxPosition(): Double?+     @Query("SELECT * FROM Todo WHERE updatedAt > :since")     abstract suspend fun getUpdatedSince(since: Long): List<Todo> @@ -56,8 +62,17 @@ abstract class TodoDao {     @Query("DELETE FROM Todo")     abstract suspend fun deleteAll() -    @Upsert-    abstract suspend fun upsertAll(t: List<Todo>)+    /** Local bulk write: bumps updatedAt on every row so reorders reach sync. */+    suspend fun upsertAll(values: List<Todo>) {+        val now = System.currentTimeMillis()+        upsertAllRaw(values.map { it.copy(updatedAt = now) })+    }++    @Query(+        "DELETE FROM Todo WHERE deleted = 1 AND updatedAt < :before " ++            "AND syncId NOT IN (SELECT syncId FROM SyncSnapshot)",+    )+    abstract suspend fun deleteUnsyncedTombstones(before: Long): Int      /** Writes [values] verbatim. Only the relay sync uses this. */     @Upsert
todo/src/main/java/com/vayunmathur/todo/data/TodoRepository.kt
diff --git a/todo/src/main/java/com/vayunmathur/todo/data/TodoRepository.kt b/todo/src/main/java/com/vayunmathur/todo/data/TodoRepository.ktindex 1e9f00f136..bc6e60280e 100644--- a/todo/src/main/java/com/vayunmathur/todo/data/TodoRepository.kt+++ b/todo/src/main/java/com/vayunmathur/todo/data/TodoRepository.kt@@ -2,32 +2,48 @@ package com.vayunmathur.todo.data  import android.content.Context import com.vayunmathur.library.room.RoomRepository+import com.vayunmathur.todo.domain.Positions+import com.vayunmathur.todo.domain.TombstonePolicy+import kotlinx.coroutines.CoroutineDispatcher+import kotlinx.coroutines.CoroutineScope+import kotlinx.coroutines.Dispatchers+import kotlinx.coroutines.SupervisorJob import kotlinx.coroutines.flow.Flow -class TodoRepository private constructor(context: Context) :-    RoomRepository<TodoDatabase>(context, TodoDatabase::class, DB_NAME) {+class TodoRepository private constructor(+    context: Context,+    val io: CoroutineDispatcher = Dispatchers.IO,+) : RoomRepository<TodoDatabase>(context, TodoDatabase::class, DB_NAME) {++    /** Outlives any screen, so a write started on the way out of the editor still lands. */+    val appScope: CoroutineScope = CoroutineScope(SupervisorJob() + io)      private val dao get() = db.todoDao()     private val snapshotDao get() = db.syncSnapshotDao()      val todos: Flow<List<Todo>> get() = dao.getAllFlow()-    fun todoByIdFlow(id: Long): Flow<Todo?> = dao.getByIdFlow(id)+    fun todoBySyncIdFlow(syncId: String): Flow<Todo?> = dao.getBySyncIdFlow(syncId)      suspend fun getAll(): List<Todo> = dao.getAll()+    suspend fun getById(id: Long): Todo? = dao.getById(id)     suspend fun getBySyncId(syncId: String): Todo? = dao.getBySyncId(syncId)     suspend fun getUpdatedSince(since: Long): List<Todo> = dao.getUpdatedSince(since) +    suspend fun nextPosition(): Double = Positions.after(dao.maxPosition())+     /** Local write: bumps updatedAt so the change is picked up by sync. */     suspend fun upsert(value: Todo): Long = dao.upsert(value) +    /** Local bulk write: bumps updatedAt on every row. */+    suspend fun upsertAll(values: List<Todo>) = dao.upsertAll(values)+     /** Writes [value] verbatim. Only the relay sync uses this, to preserve a pulled timestamp. */     suspend fun upsertRaw(value: Todo): Long = dao.upsertRaw(value)     suspend fun upsertAllRaw(values: List<Todo>) = dao.upsertAllRaw(values) -    /** Local delete: tombstones instead of hard-deleting so the relay sync can propagate it. */-    suspend fun delete(value: Todo): Int {+    /** Soft delete: the relay sync propagates the tombstone. */+    suspend fun tombstone(value: Todo) {         dao.upsert(value.copy(deleted = true))-        return 1     }      suspend fun tombstoneBySyncId(syncId: String): Int {@@ -36,12 +52,19 @@ class TodoRepository private constructor(context: Context) :         return 1     } -    suspend fun deleteBySyncId(syncId: String): Int = dao.deleteBySyncId(syncId)-    suspend fun upsertAll(values: List<Todo>) = dao.upsertAll(values)-     /** Removes every todo (including tombstones). Used when a relay vault is purged. */     suspend fun purge() = dao.deleteAll() +    /** Housekeeping on launch: drop stale unsynced tombstones and repair colliding positions. */+    suspend fun maintain(now: Long = System.currentTimeMillis()) {+        dao.deleteUnsyncedTombstones(TombstonePolicy.cutoff(now))+        val ordered = dao.getAll().sortedWith(compareBy({ it.position }, { it.createdAt }))+        if (Positions.needsRenormalize(ordered.map { it.position })) {+            val keys = Positions.renormalized(ordered.size)+            dao.upsertAll(ordered.mapIndexed { i, t -> t.withPosition(keys[i]) })+        }+    }+     suspend fun getAllSnapshots(): List<SyncSnapshot> = snapshotDao.getAll()     suspend fun upsertSnapshot(snapshot: SyncSnapshot) = snapshotDao.upsert(snapshot)     suspend fun deleteSnapshotBySyncId(syncId: String) = snapshotDao.deleteBySyncId(syncId)
todo/src/main/java/com/vayunmathur/todo/domain/Positions.kt
diff --git a/todo/src/main/java/com/vayunmathur/todo/domain/Positions.kt b/todo/src/main/java/com/vayunmathur/todo/domain/Positions.ktnew file mode 100644index 0000000000..2eaf827826--- /dev/null+++ b/todo/src/main/java/com/vayunmathur/todo/domain/Positions.kt@@ -0,0 +1,49 @@+package com.vayunmathur.todo.domain++import kotlin.random.Random++/**+ * Fractional ordering keys for manually sorted rows.+ *+ * A move only rewrites the moved row's key, so it syncs as one record. Two devices inserting+ * between the same neighbours would otherwise pick the identical midpoint; [between] jitters+ * inside the middle half of the gap so concurrent inserts keep a strict order.+ */+object Positions {+    const val STEP = 1024.0+    const val MIN_GAP = 1e-6+    private const val JITTER_SPAN = 0.25++    fun after(last: Double?): Double = (last ?: 0.0) + STEP++    fun before(first: Double?): Double = (first ?: 0.0) - STEP++    fun between(prev: Double?, next: Double?, random: Random = Random.Default): Double = when {+        prev == null && next == null -> 0.0+        prev == null -> before(next)+        next == null -> after(prev)+        else -> {+            val gap = next - prev+            prev + gap / 2 + gap * random.nextDouble(-JITTER_SPAN, JITTER_SPAN)+        }+    }++    /**+     * Key for the row at [from] after it is moved to [to] in [sorted] (ascending keys, the+     * moved row still at [from]).+     */+    fun forMove(sorted: List<Double>, from: Int, to: Int, random: Random = Random.Default): Double {+        val (prev, next) = if (to > from) {+            sorted.getOrNull(to) to sorted.getOrNull(to + 1)+        } else {+            sorted.getOrNull(to - 1) to sorted.getOrNull(to)+        }+        return between(prev, next, random)+    }++    /** True when two neighbours collide or are too close to split again. */+    fun needsRenormalize(sorted: List<Double>): Boolean =+        sorted.zipWithNext().any { (a, b) -> b - a < MIN_GAP }++    fun renormalized(count: Int): List<Double> = List(count) { (it + 1) * STEP }+}
todo/src/main/java/com/vayunmathur/todo/domain/TodoSearch.kt
diff --git a/todo/src/main/java/com/vayunmathur/todo/domain/TodoSearch.kt b/todo/src/main/java/com/vayunmathur/todo/domain/TodoSearch.ktnew file mode 100644index 0000000000..46ec3ade67--- /dev/null+++ b/todo/src/main/java/com/vayunmathur/todo/domain/TodoSearch.kt@@ -0,0 +1,14 @@+package com.vayunmathur.todo.domain++import com.vayunmathur.todo.data.Todo++object TodoSearch {+    fun matches(todo: Todo, query: String): Boolean {+        val q = query.trim()+        if (q.isEmpty()) return true+        return todo.title.contains(q, ignoreCase = true) || todo.notes.contains(q, ignoreCase = true)+    }++    fun filter(todos: List<Todo>, query: String): List<Todo> =+        if (query.isBlank()) todos else todos.filter { matches(it, query) }+}
todo/src/main/java/com/vayunmathur/todo/domain/TombstonePolicy.kt
diff --git a/todo/src/main/java/com/vayunmathur/todo/domain/TombstonePolicy.kt b/todo/src/main/java/com/vayunmathur/todo/domain/TombstonePolicy.ktnew file mode 100644index 0000000000..6fe1eb1ad8--- /dev/null+++ b/todo/src/main/java/com/vayunmathur/todo/domain/TombstonePolicy.kt@@ -0,0 +1,12 @@+package com.vayunmathur.todo.domain++/**+ * Local tombstones that never reached a sync baseline are only kept long enough for a first+ * sync to pick them up. Synced tombstones are collected by the relay merge itself once both+ * sides acknowledge the delete.+ */+object TombstonePolicy {+    const val RETENTION_MS: Long = 30L * 24 * 60 * 60 * 1000++    fun cutoff(now: Long): Long = now - RETENTION_MS+}
todo/src/main/java/com/vayunmathur/todo/platform/TodoEditor.kt
diff --git a/todo/src/main/java/com/vayunmathur/todo/platform/TodoEditor.kt b/todo/src/main/java/com/vayunmathur/todo/platform/TodoEditor.ktnew file mode 100644index 0000000000..2c771a85d0--- /dev/null+++ b/todo/src/main/java/com/vayunmathur/todo/platform/TodoEditor.kt@@ -0,0 +1,110 @@+package com.vayunmathur.todo.platform++import com.vayunmathur.todo.data.Todo+import com.vayunmathur.todo.data.TodoRepository+import kotlinx.coroutines.CoroutineScope+import kotlinx.coroutines.Job+import kotlinx.coroutines.delay+import kotlinx.coroutines.flow.MutableStateFlow+import kotlinx.coroutines.flow.StateFlow+import kotlinx.coroutines.flow.update+import kotlinx.coroutines.launch+import kotlinx.coroutines.sync.Mutex+import kotlinx.coroutines.sync.withLock++/**+ * Edit session for one task.+ *+ * Writes run on the repository's app scope, so leaving the screen mid-debounce cannot drop+ * the last edit: [close] flushes it. A new task is identified by its pre-assigned sync id,+ * so the session can find the row again after the first save, and is only inserted once it+ * has a title; a new task whose title is cleared again is discarded on [close].+ */+class TodoEditor internal constructor(+    private val repository: TodoRepository,+    private val scope: CoroutineScope,+    private val id: Long,+    private val newSyncId: String?,+    private val template: Todo,+) {+    private val _state = MutableStateFlow<Todo?>(null)+    val state: StateFlow<Todo?> = _state++    private val mutex = Mutex()+    @Volatile private var dirty = false+    @Volatile private var finished = false+    private var createdHere = false+    private var saveJob: Job? = null+    private val observeJob: Job = scope.launch { observe() }++    private suspend fun observe() {+        val initial = load()+        _state.compareAndSet(null, initial)+        repository.todoBySyncIdFlow(initial.syncId).collect { stored ->+            if (stored != null && !stored.deleted && !dirty) _state.value = stored+        }+    }++    private suspend fun load(): Todo {+        if (id != 0L) repository.getById(id)?.let { return it }+        newSyncId?.let { syncId -> repository.getBySyncId(syncId)?.let { return it } }+        return template.copy(+            syncId = newSyncId ?: template.syncId,+            position = repository.nextPosition(),+            createdAt = System.currentTimeMillis(),+        )+    }++    fun update(transform: (Todo) -> Todo) {+        if (finished) return+        val current = _state.value ?: return+        _state.value = transform(current)+        dirty = true+        saveJob?.cancel()+        saveJob = scope.launch {+            delay(SAVE_DEBOUNCE_MS)+            save()+        }+    }++    private suspend fun save() = mutex.withLock {+        if (!dirty) return@withLock+        val value = _state.value ?: return@withLock+        if (value.id == 0L && value.title.isBlank()) return@withLock+        dirty = false+        val newId = repository.upsert(value)+        if (value.id == 0L) {+            createdHere = true+            _state.update { it?.copy(id = newId) }+        }+    }++    fun delete() {+        finished = true+        saveJob?.cancel()+        observeJob.cancel()+        scope.launch {+            mutex.withLock {+                dirty = false+                val value = _state.value ?: return@withLock+                if (value.id != 0L) repository.tombstone(value)+            }+        }+    }++    fun close() {+        if (finished) return+        finished = true+        saveJob?.cancel()+        observeJob.cancel()+        scope.launch {+            save()+            val value = _state.value ?: return@launch+            if (createdHere && value.id != 0L && value.title.isBlank()) repository.tombstone(value)+        }+    }++    companion object {+        const val SAVE_DEBOUNCE_MS = 300L+    }+}
todo/src/main/java/com/vayunmathur/todo/platform/TodoEditorUiContract.kt
diff --git a/todo/src/main/java/com/vayunmathur/todo/platform/TodoEditorUiContract.kt b/todo/src/main/java/com/vayunmathur/todo/platform/TodoEditorUiContract.ktnew file mode 100644index 0000000000..14e345c655--- /dev/null+++ b/todo/src/main/java/com/vayunmathur/todo/platform/TodoEditorUiContract.kt@@ -0,0 +1,23 @@+package com.vayunmathur.todo.platform++/** Everything the todo editor draws. */+data class TodoUiState(+    val title: String = "",+    val notes: String = "",+    val done: Boolean = false,+    val dueAt: Long? = null,+)++/** Todo editor callbacks, no-op by default for previews. */+interface TodoActions {+    fun back() {}+    fun setTitle(title: String) {}+    fun setNotes(notes: String) {}+    fun setDone(done: Boolean) {}+    fun setDueAt(dueAt: Long?) {}+    fun deleteTodo() {}++    companion object {+        val Noop: TodoActions = object : TodoActions {}+    }+}
todo/src/main/java/com/vayunmathur/todo/platform/TodoListUiContract.kt
diff --git a/todo/src/main/java/com/vayunmathur/todo/platform/TodoListUiContract.kt b/todo/src/main/java/com/vayunmathur/todo/platform/TodoListUiContract.ktnew file mode 100644index 0000000000..546e8f72e4--- /dev/null+++ b/todo/src/main/java/com/vayunmathur/todo/platform/TodoListUiContract.kt@@ -0,0 +1,36 @@+package com.vayunmathur.todo.platform++import com.vayunmathur.todo.data.Todo++/**+ * The UI contract between [TodoViewModel] plus the nav back stack and the list screen.+ *+ * Screens take a state value and an actions interface rather than the ViewModel itself, so+ * they can be rendered by a `@Preview` — which is what the store listing images are+ * generated from. It lives in `platform` rather than `ui` so the dependency runs one way.+ */+data class TodoListUiState(+    val todos: List<Todo> = emptyList(),+    val searchQuery: String = "",+    /** Hidden while a todo is already open beside the list in the list-detail layout. */+    val showAddButton: Boolean = true,+) {+    /** Manual order is only meaningful over the unfiltered list. */+    val canReorder: Boolean get() = searchQuery.isBlank() && todos.size > 1+}++/** Every method has a no-op default so a preview can render without behaviour. */+interface TodoListActions {+    fun openTodo(id: Long) {}+    fun createTodo() {}+    fun setSearchQuery(query: String) {}+    fun toggleDone(todo: Todo) {}+    fun delete(todo: Todo) {}++    /** Persists moved rows; each already carries its new position. */+    fun upsertAll(todos: List<Todo>) {}++    companion object {+        val Noop: TodoListActions = object : TodoListActions {}+    }+}
todo/src/main/java/com/vayunmathur/todo/platform/TodoUiContract.kt
diff --git a/todo/src/main/java/com/vayunmathur/todo/platform/TodoUiContract.kt b/todo/src/main/java/com/vayunmathur/todo/platform/TodoUiContract.ktdeleted file mode 100644index 9afb3483c0..0000000000--- a/todo/src/main/java/com/vayunmathur/todo/platform/TodoUiContract.kt+++ /dev/null@@ -1,59 +0,0 @@-package com.vayunmathur.todo.platform--import com.vayunmathur.todo.data.Todo--/**- * The UI contract between [TodoViewModel] plus the nav back stack and the screens.- *- * Screens take a state value and an actions interface rather than the ViewModel itself, so- * they can be rendered by a `@Preview` — which is what the store listing images are- * generated from. It lives in `platform` rather than `ui` so the dependency runs one way:- * `ui` depends on `platform`, and the binders in `ui` implement these interfaces.- */--/** Everything the todo list draws. */-data class TodoListUiState(-    val todos: List<Todo> = emptyList(),-    /** Hidden while a todo is already open beside the list in the list-detail layout. */-    val showAddButton: Boolean = true,-)--/**- * Todo list callbacks. Every method has a no-op default so a preview can render the screen- * without supplying behaviour — [Noop] is the whole implementation a preview needs.- */-interface TodoListActions {-    fun openTodo(id: Long) {}-    fun createTodo() {}-    fun toggleDone(todo: Todo) {}-    fun delete(todo: Todo) {}--    /** Persists a reordered list; each todo already carries its new position. */-    fun upsertAll(todos: List<Todo>) {}--    companion object {-        val Noop: TodoListActions = object : TodoListActions {}-    }-}--/** Everything the todo editor draws. */-data class TodoUiState(-    val title: String = "",-    val notes: String = "",-    val done: Boolean = false,-    val dueAt: Long? = null,-)--/** Todo editor callbacks. Same no-op-default arrangement as [TodoListActions]. */-interface TodoActions {-    fun back() {}-    fun setTitle(title: String) {}-    fun setNotes(notes: String) {}-    fun setDone(done: Boolean) {}-    fun setDueAt(dueAt: Long?) {}-    fun deleteTodo() {}--    companion object {-        val Noop: TodoActions = object : TodoActions {}-    }-}
todo/src/main/java/com/vayunmathur/todo/platform/TodoViewModel.kt
diff --git a/todo/src/main/java/com/vayunmathur/todo/platform/TodoViewModel.kt b/todo/src/main/java/com/vayunmathur/todo/platform/TodoViewModel.ktindex d64dfa565c..475563dd08 100644--- a/todo/src/main/java/com/vayunmathur/todo/platform/TodoViewModel.kt+++ b/todo/src/main/java/com/vayunmathur/todo/platform/TodoViewModel.kt@@ -1,121 +1,65 @@ package com.vayunmathur.todo.platform  import android.app.Application-import androidx.compose.runtime.Composable-import androidx.compose.runtime.LaunchedEffect-import androidx.compose.runtime.MutableState-import androidx.lifecycle.compose.collectAsStateWithLifecycle-import androidx.compose.runtime.getValue-import androidx.compose.runtime.mutableLongStateOf-import androidx.compose.runtime.mutableStateOf-import androidx.compose.runtime.remember-import androidx.compose.runtime.setValue import androidx.lifecycle.AndroidViewModel-import androidx.lifecycle.ViewModel-import androidx.lifecycle.ViewModelProvider+import androidx.lifecycle.SavedStateHandle import androidx.lifecycle.viewModelScope+import androidx.lifecycle.viewmodel.initializer+import androidx.lifecycle.viewmodel.viewModelFactory+import androidx.lifecycle.createSavedStateHandle import com.vayunmathur.todo.data.Todo import com.vayunmathur.todo.data.TodoRepository-import kotlinx.coroutines.Dispatchers-import kotlinx.coroutines.FlowPreview-import kotlinx.coroutines.flow.MutableStateFlow+import com.vayunmathur.todo.domain.TodoSearch import kotlinx.coroutines.flow.SharingStarted import kotlinx.coroutines.flow.StateFlow-import kotlinx.coroutines.flow.filterNotNull+import kotlinx.coroutines.flow.combine import kotlinx.coroutines.flow.stateIn-import kotlinx.coroutines.flow.collectLatest-import kotlinx.coroutines.flow.debounce import kotlinx.coroutines.launch-import kotlinx.coroutines.withContext  class TodoViewModel(     application: Application,     private val repository: TodoRepository,+    private val savedState: SavedStateHandle, ) : AndroidViewModel(application) { -    val todos: StateFlow<List<Todo>> = repository.todos-        .stateIn(viewModelScope, SharingStarted.WhileSubscribed(5_000), emptyList())+    private val io = repository.io -    fun toggleDone(todo: Todo) {-        viewModelScope.launch(Dispatchers.IO) { repository.upsert(todo.copy(done = !todo.done)) }-    }+    val searchQuery: StateFlow<String> = savedState.getStateFlow(KEY_QUERY, "") -    fun delete(todo: Todo) {-        viewModelScope.launch(Dispatchers.IO) { repository.delete(todo) }-    }+    val visibleTodos: StateFlow<List<Todo>> = combine(repository.todos, searchQuery) { todos, query ->+        TodoSearch.filter(todos, query)+    }.stateIn(viewModelScope, SharingStarted.WhileSubscribed(STOP_TIMEOUT_MS), emptyList()) -    fun create(title: String, notes: String, dueAt: Long?, onCreated: (Long) -> Unit) {-        if (title.isBlank()) return-        viewModelScope.launch {-            val id = withContext(Dispatchers.IO) {-                repository.upsert(Todo(title = title.trim(), notes = notes.trim(), dueAt = dueAt))-            }-            onCreated(id)-        }+    init {+        viewModelScope.launch(io) { repository.maintain() }     } -    fun upsertAll(todos: List<Todo>) {-        viewModelScope.launch(Dispatchers.IO) { repository.upsertAll(todos) }+    fun setSearchQuery(query: String) {+        savedState[KEY_QUERY] = query     } -    @OptIn(FlowPreview::class)-    @Composable-    fun editableTodo(initialId: Long, default: () -> Todo): MutableState<Todo> {-        var currentId by remember { mutableLongStateOf(initialId) }--        val todoFlow = remember(currentId) { repository.todoByIdFlow(currentId) }-        val dbTodo by todoFlow.collectAsStateWithLifecycle(initialValue = null)--        val localState = remember { mutableStateOf<Todo?>(null) }--        LaunchedEffect(dbTodo, currentId) {-            dbTodo?.let { localState.value = it }-        }--        val pendingWrites = remember { MutableStateFlow<Todo?>(null) }-        LaunchedEffect(Unit) {-            pendingWrites.filterNotNull().debounce(SAVE_DEBOUNCE_MS).collectLatest { newValue ->-                val newId = withContext(Dispatchers.IO) { repository.upsert(newValue) }-                if (currentId == 0L) currentId = newId-            }-        }--        return remember {-            object : MutableState<Todo> {-                override var value: Todo-                    get() = localState.value ?: default()-                    set(newValue) {-                        localState.value = newValue-                        pendingWrites.value = newValue-                    }+    fun toggleDone(todo: Todo) {+        viewModelScope.launch(io) { repository.upsert(todo.copy(done = !todo.done)) }+    } -                override fun component1(): Todo = value-                override fun component2(): (Todo) -> Unit = { value = it }-            }-        }+    fun delete(todo: Todo) {+        viewModelScope.launch(io) { repository.tombstone(todo) }     } -    fun deleteById(id: Long, onDeleted: () -> Unit) {-        viewModelScope.launch(Dispatchers.IO) {-            val todo = repository.getAll().firstOrNull { it.id == id }-            if (todo != null) repository.delete(todo)-            withContext(Dispatchers.Main) { onDeleted() }-        }+    fun upsertAll(todos: List<Todo>) {+        if (todos.isEmpty()) return+        viewModelScope.launch(io) { repository.upsertAll(todos) }     } +    fun openEditor(id: Long, newSyncId: String?): TodoEditor =+        TodoEditor(repository, repository.appScope, id, newSyncId, Todo())+     companion object {-        private const val SAVE_DEBOUNCE_MS = 300L-    }-}+        private const val KEY_QUERY = "search_query"+        private const val STOP_TIMEOUT_MS = 5_000L -/** Factory for constructing [TodoViewModel] with the repository. */-class TodoViewModelFactory(-    private val application: Application,-    private val repository: TodoRepository,-) : ViewModelProvider.Factory {-    @Suppress("UNCHECKED_CAST")-    override fun <T : ViewModel> create(modelClass: Class<T>): T {-        require(modelClass.isAssignableFrom(TodoViewModel::class.java)) { "Unexpected ViewModel class: $modelClass" }-        return TodoViewModel(application, repository) as T+        fun factory(application: Application, repository: TodoRepository) = viewModelFactory {+            initializer { TodoViewModel(application, repository, createSavedStateHandle()) }+        }     } }
todo/src/main/java/com/vayunmathur/todo/ui/TodoBackupButtons.kt
diff --git a/todo/src/main/java/com/vayunmathur/todo/ui/TodoBackupButtons.kt b/todo/src/main/java/com/vayunmathur/todo/ui/TodoBackupButtons.ktnew file mode 100644index 0000000000..2146de7d72--- /dev/null+++ b/todo/src/main/java/com/vayunmathur/todo/ui/TodoBackupButtons.kt@@ -0,0 +1,19 @@+package com.vayunmathur.todo.ui++import androidx.compose.runtime.Composable+import androidx.compose.runtime.remember+import androidx.compose.ui.platform.LocalContext+import com.vayunmathur.library.room.SqlCipherDbCodec+import com.vayunmathur.library.ui.BackupButtons+import com.vayunmathur.todo.data.todoDbConfigs++/** Binds the repository-backed config to the shared backup buttons. */+@Composable+fun TodoBackupButtons() {+    val context = LocalContext.current+    BackupButtons(+        dbConfigs = remember { todoDbConfigs(context) },+        dbCodec = SqlCipherDbCodec,+        extraFiles = emptyList(),+    )+}
todo/src/main/java/com/vayunmathur/todo/ui/TodoDetailPage.kt
diff --git a/todo/src/main/java/com/vayunmathur/todo/ui/TodoDetailPage.kt b/todo/src/main/java/com/vayunmathur/todo/ui/TodoDetailPage.ktindex 7981a22709..9883bc6f7a 100644--- a/todo/src/main/java/com/vayunmathur/todo/ui/TodoDetailPage.kt+++ b/todo/src/main/java/com/vayunmathur/todo/ui/TodoDetailPage.kt@@ -1,33 +1,40 @@ package com.vayunmathur.todo.ui  import androidx.compose.runtime.Composable+import androidx.compose.runtime.DisposableEffect+import androidx.compose.runtime.getValue import androidx.compose.runtime.remember+import androidx.lifecycle.compose.collectAsStateWithLifecycle import com.vayunmathur.library.util.NavBackStack import com.vayunmathur.todo.Route-import com.vayunmathur.todo.data.Todo import com.vayunmathur.todo.platform.TodoActions import com.vayunmathur.todo.platform.TodoUiState import com.vayunmathur.todo.platform.TodoViewModel -/** Binds [TodoViewModel] and the nav back stack to the stateless [TodoDetailScreen]. */+/** Binds a [TodoEditor][com.vayunmathur.todo.platform.TodoEditor] session to the stateless [TodoDetailScreen]. */ @Composable-fun TodoDetailPage(backStack: NavBackStack<Route>, viewModel: TodoViewModel, id: Long) {-    val todoState = viewModel.editableTodo(id) { Todo(title = "") }+fun TodoDetailPage(backStack: NavBackStack<Route>, viewModel: TodoViewModel, route: Route.TodoDetail) {+    val editor = remember(route) { viewModel.openEditor(route.id, route.newSyncId) }+    DisposableEffect(editor) { onDispose { editor.close() } }+    val todo by editor.state.collectAsStateWithLifecycle() -    val actions = remember(backStack, viewModel, id, todoState) {+    val actions = remember(backStack, editor) {         object : TodoActions {             override fun back() { backStack.pop() }-            override fun setTitle(title: String) { todoState.value = todoState.value.copy(title = title) }-            override fun setNotes(notes: String) { todoState.value = todoState.value.copy(notes = notes) }-            override fun setDone(done: Boolean) { todoState.value = todoState.value.copy(done = done) }-            override fun setDueAt(dueAt: Long?) { todoState.value = todoState.value.copy(dueAt = dueAt) }-            override fun deleteTodo() { viewModel.deleteById(id) { backStack.pop() } }+            override fun setTitle(title: String) = editor.update { it.copy(title = title) }+            override fun setNotes(notes: String) = editor.update { it.copy(notes = notes) }+            override fun setDone(done: Boolean) = editor.update { it.copy(done = done) }+            override fun setDueAt(dueAt: Long?) = editor.update { it.copy(dueAt = dueAt) }+            override fun deleteTodo() {+                editor.delete()+                backStack.pop()+            }         }     } -    val todo = todoState.value+    val current = todo ?: return     TodoDetailScreen(-        state = TodoUiState(title = todo.title, notes = todo.notes, done = todo.done, dueAt = todo.dueAt),+        state = TodoUiState(title = current.title, notes = current.notes, done = current.done, dueAt = current.dueAt),         actions = actions,     ) }
todo/src/main/java/com/vayunmathur/todo/ui/TodoListPage.kt
diff --git a/todo/src/main/java/com/vayunmathur/todo/ui/TodoListPage.kt b/todo/src/main/java/com/vayunmathur/todo/ui/TodoListPage.ktindex 3a3877cf77..07b08f120b 100644--- a/todo/src/main/java/com/vayunmathur/todo/ui/TodoListPage.kt+++ b/todo/src/main/java/com/vayunmathur/todo/ui/TodoListPage.kt@@ -3,11 +3,11 @@ package com.vayunmathur.todo.ui import androidx.compose.runtime.Composable import androidx.compose.runtime.getValue import androidx.compose.runtime.remember-import androidx.compose.ui.platform.LocalContext import androidx.lifecycle.compose.collectAsStateWithLifecycle import com.vayunmathur.library.util.NavBackStack import com.vayunmathur.todo.Route import com.vayunmathur.todo.data.Todo+import com.vayunmathur.todo.data.newSyncId import com.vayunmathur.todo.platform.TodoListActions import com.vayunmathur.todo.platform.TodoListUiState import com.vayunmathur.todo.platform.TodoViewModel@@ -15,21 +15,26 @@ import com.vayunmathur.todo.platform.TodoViewModel /** Binds [TodoViewModel] and the nav back stack to the stateless [TodoListScreen]. */ @Composable fun TodoListPage(backStack: NavBackStack<Route>, viewModel: TodoViewModel) {-    LocalContext.current-    val todos by viewModel.todos.collectAsStateWithLifecycle()+    val todos by viewModel.visibleTodos.collectAsStateWithLifecycle()+    val query by viewModel.searchQuery.collectAsStateWithLifecycle()      val actions = remember(backStack, viewModel) {         object : TodoListActions {             override fun openTodo(id: Long) { backStack.add(Route.TodoDetail(id)) }-            override fun createTodo() { backStack.add(Route.TodoDetail(0)) }-            override fun toggleDone(todo: Todo) { viewModel.toggleDone(todo) }-            override fun delete(todo: Todo) { viewModel.delete(todo) }-            override fun upsertAll(todos: List<Todo>) { viewModel.upsertAll(todos) }+            override fun createTodo() { backStack.add(Route.TodoDetail(0, newSyncId())) }+            override fun setSearchQuery(query: String) = viewModel.setSearchQuery(query)+            override fun toggleDone(todo: Todo) = viewModel.toggleDone(todo)+            override fun delete(todo: Todo) = viewModel.delete(todo)+            override fun upsertAll(todos: List<Todo>) = viewModel.upsertAll(todos)         }     }      TodoListScreen(-        state = TodoListUiState(todos = todos, showAddButton = backStack.last() !is Route.TodoDetail),+        state = TodoListUiState(+            todos = todos,+            searchQuery = query,+            showAddButton = backStack.last() !is Route.TodoDetail,+        ),         actions = actions,         backupButtons = { TodoBackupButtons() },     )
todo/src/main/java/com/vayunmathur/todo/ui/TodoListScreen.kt
diff --git a/todo/src/main/java/com/vayunmathur/todo/ui/TodoListScreen.kt b/todo/src/main/java/com/vayunmathur/todo/ui/TodoListScreen.ktindex d81a80972e..405ce1f12d 100644--- a/todo/src/main/java/com/vayunmathur/todo/ui/TodoListScreen.kt+++ b/todo/src/main/java/com/vayunmathur/todo/ui/TodoListScreen.kt@@ -1,35 +1,38 @@ package com.vayunmathur.todo.ui +import androidx.activity.compose.BackHandler import androidx.compose.foundation.clickable import androidx.compose.foundation.layout.PaddingValues import androidx.compose.foundation.layout.RowScope import androidx.compose.foundation.lazy.items import androidx.compose.foundation.lazy.rememberLazyListState import androidx.compose.runtime.Composable-import androidx.compose.runtime.getValue-import androidx.compose.runtime.mutableStateOf-import androidx.compose.runtime.remember-import androidx.compose.runtime.setValue import androidx.compose.ui.Modifier-import androidx.compose.ui.platform.LocalContext+import androidx.compose.ui.graphics.graphicsLayer import androidx.compose.ui.res.stringResource import androidx.compose.ui.unit.dp-import androidx.activity.compose.BackHandler-import com.vayunmathur.library.room.SqlCipherDbCodec-import com.vayunmathur.library.ui.BackupButtons+import androidx.compose.ui.zIndex import com.vayunmathur.library.ui.Checkbox import com.vayunmathur.library.ui.CommonSearchBar+import com.vayunmathur.library.ui.DateString import com.vayunmathur.library.ui.ExperimentalMaterial3Api import com.vayunmathur.library.ui.FloatingActionButton import com.vayunmathur.library.ui.IconAdd+import com.vayunmathur.library.ui.IconButton+import com.vayunmathur.library.ui.IconDragHandle import com.vayunmathur.library.ui.LazyListScaffold import com.vayunmathur.library.ui.ListItem+import com.vayunmathur.library.ui.ListItemDefaults+import com.vayunmathur.library.ui.ReorderableItem+import com.vayunmathur.library.ui.Surface import com.vayunmathur.library.ui.Text import com.vayunmathur.library.ui.TopAppBar+import com.vayunmathur.library.ui.animatedDp import com.vayunmathur.library.ui.appBarScrollBehavior-import com.vayunmathur.library.ui.DateString+import com.vayunmathur.library.ui.itemMotion+import com.vayunmathur.library.ui.rememberHaptics+import com.vayunmathur.library.ui.reorderDragHandle import com.vayunmathur.todo.R-import com.vayunmathur.todo.data.todoDbConfigs import com.vayunmathur.todo.platform.TodoListActions import com.vayunmathur.todo.platform.TodoListUiState import kotlin.time.Instant@@ -46,31 +49,27 @@ fun TodoListScreen(     actions: TodoListActions,     /** Top-bar backup/restore buttons; empty in a preview, which has no database. */     backupButtons: @Composable RowScope.() -> Unit = {},-    /**-     * Seed for the screen's own UI-only search state. The app always takes the default;-     * previews set it so the search results can be captured without typing.-     */-    initialSearchQuery: String = "", ) {-    var searchQuery by remember { mutableStateOf(initialSearchQuery) }-    val filtered = remember(state.todos, searchQuery) {-        if (searchQuery.isBlank()) state.todos-        else state.todos.filter { it.title.contains(searchQuery, true) }-    }--    BackHandler(enabled = searchQuery.isNotEmpty()) {-        searchQuery = ""+    BackHandler(enabled = state.searchQuery.isNotEmpty()) {+        actions.setSearchQuery("")     } +    val haptics = rememberHaptics()     val listState = rememberLazyListState()+    val reorder = rememberTodoReorderState(+        todos = state.todos,+        listState = listState,+        onMoveTick = { haptics.tick() },+        onCommit = { actions.upsertAll(it) },+    )      LazyListScaffold(         topBar = {             TopAppBar(                 title = {                     CommonSearchBar(-                        value = searchQuery,-                        onValueChange = { searchQuery = it },+                        value = state.searchQuery,+                        onValueChange = { actions.setSearchQuery(it) },                         placeholder = stringResource(R.string.app_name),                         padding = PaddingValues(0.dp),                     )@@ -88,39 +87,47 @@ fun TodoListScreen(         state = listState,         scrollBehavior = appBarScrollBehavior(),     ) {-        items(filtered, key = { it.id }) { todo ->-            ListItem(-                content = {-                    Text(todo.title.ifBlank { stringResource(R.string.untitled) })-                },-                modifier = Modifier.clickable { actions.openTodo(todo.id) },-                supportingContent = {-                    val notesPreview = todo.notes.takeIf { it.isNotBlank() }-                    val dueText = todo.dueAt?.let { due ->-                        DateString.dateShort(Instant.fromEpochMilliseconds(due))-                    }-                    val line = listOfNotNull(notesPreview?.take(120), dueText)-                        .joinToString(" · ").ifBlank { null }-                    line?.let { Text(it) }-                },-                leadingContent = {-                    Checkbox(-                        checked = todo.done,-                        onCheckedChange = { actions.toggleDone(todo) },+        items(reorder.rows, key = { it.id }) { todo ->+            val dragging = reorder.drag.draggingKey == todo.id+            val itemModifier = if (dragging) {+                Modifier.zIndex(1f).graphicsLayer { translationY = reorder.drag.draggingItemTranslation }+            } else {+                itemMotion()+            }+            ReorderableItem(reorder.drag, key = todo.id, modifier = itemModifier) { isDragging ->+                val elevation = animatedDp(if (isDragging) 8.dp else 0.dp)+                Surface(shadowElevation = elevation) {+                    ListItem(+                        content = { Text(todo.title.ifBlank { stringResource(R.string.untitled) }) },+                        modifier = Modifier.clickable { actions.openTodo(todo.id) },+                        supportingContent = {+                            val notesPreview = todo.notes.takeIf { it.isNotBlank() }+                            val dueText = todo.dueAt?.let { DateString.dateShort(Instant.fromEpochMilliseconds(it)) }+                            val line = listOfNotNull(notesPreview?.take(120), dueText).joinToString(" · ")+                            if (line.isNotBlank()) Text(line)+                        },+                        leadingContent = {+                            Checkbox(checked = todo.done, onCheckedChange = { actions.toggleDone(todo) })+                        },+                        trailingContent = {+                            if (state.canReorder) {+                                IconButton(+                                    modifier = Modifier.reorderDragHandle(+                                        reorderState = reorder.drag,+                                        key = todo.id,+                                        onDragStarted = { haptics.longPress() },+                                        onDragStopped = { haptics.confirm() },+                                    ),+                                    onClick = {},+                                ) {+                                    IconDragHandle()+                                }+                            }+                        },+                        elevation = ListItemDefaults.elevation(elevation = elevation),                     )-                },-            )+                }+            }         }     } }--/** Binds the repository-backed config to the shared backup buttons. Used by [TodoListPage]. */-@Composable-fun TodoBackupButtons() {-    val context = LocalContext.current-    BackupButtons(-        dbConfigs = remember { todoDbConfigs(context) },-        dbCodec = SqlCipherDbCodec,-        extraFiles = emptyList(),-    )-}
todo/src/main/java/com/vayunmathur/todo/ui/TodoReorderState.kt
diff --git a/todo/src/main/java/com/vayunmathur/todo/ui/TodoReorderState.kt b/todo/src/main/java/com/vayunmathur/todo/ui/TodoReorderState.ktnew file mode 100644index 0000000000..3a2f9315a1--- /dev/null+++ b/todo/src/main/java/com/vayunmathur/todo/ui/TodoReorderState.kt@@ -0,0 +1,61 @@+package com.vayunmathur.todo.ui++import androidx.compose.foundation.lazy.LazyListState+import androidx.compose.runtime.Composable+import androidx.compose.runtime.LaunchedEffect+import androidx.compose.runtime.getValue+import androidx.compose.runtime.mutableStateOf+import androidx.compose.runtime.remember+import androidx.compose.runtime.setValue+import com.vayunmathur.library.ui.ReorderableLazyListState+import com.vayunmathur.library.ui.rememberReorderableLazyListState+import com.vayunmathur.todo.data.Todo+import com.vayunmathur.todo.domain.Positions++/** Rows as currently drawn (moved locally while a drag is in flight) plus the drag state. */+class TodoReorderState internal constructor(+    val drag: ReorderableLazyListState,+    private val rowsState: androidx.compose.runtime.State<List<Todo>>,+) {+    val rows: List<Todo> get() = rowsState.value+}++/**+ * Drag-to-reorder over [todos] (already in display order). Each move rewrites only the moved+ * row's position; [onCommit] receives the moved rows once the drag ends.+ */+@Composable+fun rememberTodoReorderState(+    todos: List<Todo>,+    listState: LazyListState,+    onMoveTick: () -> Unit,+    onCommit: (List<Todo>) -> Unit,+): TodoReorderState {+    val rows = remember { mutableStateOf(todos) }+    var moved by remember { mutableStateOf(emptySet<Long>()) }++    val drag = rememberReorderableLazyListState(listState) { from, to ->+        val current = rows.value+        if (from.index in current.indices && to.index in current.indices) {+            val position = Positions.forMove(current.map { it.position }, from.index, to.index)+            val list = current.toMutableList()+            val item = list.removeAt(from.index).withPosition(position)+            list.add(to.index, item)+            rows.value = list+            moved = moved + item.id+            onMoveTick()+        }+    }++    LaunchedEffect(todos) {+        if (!drag.isAnyItemDragging) rows.value = todos+    }+    val dragging = drag.isAnyItemDragging+    LaunchedEffect(dragging) {+        if (!dragging && moved.isNotEmpty()) {+            onCommit(rows.value.filter { it.id in moved })+            moved = emptySet()+        }+    }+    return remember(drag) { TodoReorderState(drag, rows) }+}
todo/src/screenshotTest/kotlin/com/vayunmathur/todo/ui/MetadataPreviews.kt
diff --git a/todo/src/screenshotTest/kotlin/com/vayunmathur/todo/ui/MetadataPreviews.kt b/todo/src/screenshotTest/kotlin/com/vayunmathur/todo/ui/MetadataPreviews.ktindex 96fef17e16..cceb4f877c 100644--- a/todo/src/screenshotTest/kotlin/com/vayunmathur/todo/ui/MetadataPreviews.kt+++ b/todo/src/screenshotTest/kotlin/com/vayunmathur/todo/ui/MetadataPreviews.kt@@ -88,9 +88,8 @@ class MetadataPreviews {     fun Preview3Search() {         DynamicTheme(darkTheme = true) {             TodoListScreen(-                state = TodoListUiState(todos = samples),+                state = TodoListUiState(todos = samples.filter { it.title.contains("book") }, searchQuery = "book"),                 actions = TodoListActions.Noop,-                initialSearchQuery = "book",             )         }     }
todo/src/test/java/com/vayunmathur/todo/data/TodoModelTest.kt
diff --git a/todo/src/test/java/com/vayunmathur/todo/data/TodoModelTest.kt b/todo/src/test/java/com/vayunmathur/todo/data/TodoModelTest.ktindex 2e58384442..1c1e937cc5 100644--- a/todo/src/test/java/com/vayunmathur/todo/data/TodoModelTest.kt+++ b/todo/src/test/java/com/vayunmathur/todo/data/TodoModelTest.kt@@ -55,21 +55,6 @@ class TodoModelTest {         assertEquals(1.0, todo.position)     } -    @Test-    fun `create trims title and notes`() {-        val todo = Todo(title = "  buy milk  ".trim(), notes = " 2% ".trim())-        assertEquals("buy milk", todo.title)-        assertEquals("2%", todo.notes)-    }--    @Test-    fun `blank titles are rejected before a todo is built`() {-        for (blank in listOf("", "   ", "\n\t ")) {-            assertTrue(blank.isBlank(), "title <$blank> must count as blank")-        }-        assertFalse("  x  ".isBlank())-    }-     @Test     fun `clearing the due date stores null`() {         val todo = Todo(dueAt = 123L).copy(dueAt = null)
todo/src/test/java/com/vayunmathur/todo/data/TodoSearchFilterTest.kt
diff --git a/todo/src/test/java/com/vayunmathur/todo/data/TodoSearchFilterTest.kt b/todo/src/test/java/com/vayunmathur/todo/data/TodoSearchFilterTest.ktdeleted file mode 100644index 61fb39a79e..0000000000--- a/todo/src/test/java/com/vayunmathur/todo/data/TodoSearchFilterTest.kt+++ /dev/null@@ -1,80 +0,0 @@-package com.vayunmathur.todo.data--import kotlin.test.Test-import kotlin.test.assertEquals-import kotlin.test.assertTrue--/**- * Pins the list search predicate from `TodoListScreen`: a blank query keeps- * every row, otherwise a row matches when its title contains the query,- * case-insensitively.- *- * The predicate lives inline in a composable, so it is mirrored here rather- * than called. The mirror is exact: blank check, then- * `title.contains(query, true)`. Unlike notes, only the title is searched —- * notes text is intentionally not matched.- */-class TodoSearchFilterTest {--    private fun filter(todos: List<Todo>, query: String): List<Todo> {-        if (query.isBlank()) return todos-        return todos.filter { it.title.contains(query, true) }-    }--    private fun todo(id: Long, title: String, notes: String = "") =-        Todo(id = id, title = title, notes = notes)--    @Test-    fun `blank query keeps every todo in order`() {-        val todos = listOf(todo(1, "a"), todo(2, "b"))-        assertEquals(todos, filter(todos, ""))-        assertEquals(todos, filter(todos, "   "))-    }--    @Test-    fun `match is case-insensitive over the title`() {-        val todos = listOf(-            todo(1, "Buy Milk"),-            todo(2, "buy eggs"),-            todo(3, "Work"),-        )-        assertEquals(listOf(1L, 2L), filter(todos, "buy").map { it.id })-        assertEquals(listOf(1L, 2L), filter(todos, "BUY").map { it.id })-    }--    @Test-    fun `notes text is not searched only the title`() {-        val todos = listOf(todo(1, "Groceries", notes = "buy milk and eggs"))-        assertEquals(emptyList(), filter(todos, "milk"))-        assertEquals(listOf(1L), filter(todos, "groc").map { it.id })-    }--    @Test-    fun `no match returns an empty list`() {-        assertEquals(emptyList(), filter(listOf(todo(1, "a")), "zzz"))-    }--    @Test-    fun `empty todo list stays empty for any query`() {-        assertEquals(emptyList(), filter(emptyList(), "a"))-        assertEquals(emptyList(), filter(emptyList(), ""))-    }--    @Test-    fun `unicode queries match unicode titles`() {-        val todos = listOf(-            todo(1, "買う 記"),-            todo(2, "مرحبا task"),-            todo(3, "emoji 😀 run"),-        )-        assertEquals(listOf(1L), filter(todos, "記").map { it.id })-        assertEquals(listOf(2L), filter(todos, "مرحبا").map { it.id })-        assertEquals(listOf(3L), filter(todos, "😀").map { it.id })-    }--    @Test-    fun `blank titles never match a non-blank query`() {-        val todos = listOf(todo(1, ""), todo(2, "x"))-        assertTrue(filter(todos, "x").map { it.id } == listOf(2L))-    }-}
todo/src/test/java/com/vayunmathur/todo/data/TodoSortOrderTest.kt
diff --git a/todo/src/test/java/com/vayunmathur/todo/data/TodoSortOrderTest.kt b/todo/src/test/java/com/vayunmathur/todo/data/TodoSortOrderTest.ktdeleted file mode 100644index d1a30df3c1..0000000000--- a/todo/src/test/java/com/vayunmathur/todo/data/TodoSortOrderTest.kt+++ /dev/null@@ -1,61 +0,0 @@-package com.vayunmathur.todo.data--import kotlin.test.Test-import kotlin.test.assertEquals-import kotlin.test.assertTrue--/**- * Pins the position ordering the persisted list relies on: the DAO returns- * rows ordered by `position`, `upsertAll` persists a reordered list with new- * positions, and a moved row slots between its neighbours.- */-class TodoSortOrderTest {--    private fun todo(id: Long, position: Double) = Todo(id = id, title = "t$id", position = position)--    @Test-    fun `rows order by position ascending`() {-        val todos = listOf(todo(1, 30.0), todo(2, 10.0), todo(3, 20.0))-        assertEquals(listOf(2L, 3L, 1L), todos.sortedBy { it.position }.map { it.id })-    }--    @Test-    fun `a row moved between two neighbours lands halfway`() {-        val moved = todo(4, 0.0).withPosition((20.0 + 30.0) / 2.0)-        val ordered = listOf(todo(1, 10.0), todo(2, 20.0), todo(3, 30.0), moved)-        assertEquals(listOf(1L, 2L, 4L, 3L), ordered.sortedBy { it.position }.map { it.id })-        assertEquals(25.0, moved.position)-    }--    @Test-    fun `negative and fractional positions sort stably`() {-        val todos = listOf(todo(1, -5.5), todo(2, 0.0), todo(3, -5.25), todo(4, 1e15))-        assertEquals(listOf(1L, 3L, 2L, 4L), todos.sortedBy { it.position }.map { it.id })-    }--    @Test-    fun `done and open rows share one position order`() {-        val todos = listOf(-            Todo(id = 1, title = "a", done = true, position = 2.0),-            Todo(id = 2, title = "b", done = false, position = 1.0),-        )-        assertEquals(listOf(2L, 1L), todos.sortedBy { it.position }.map { it.id })-    }--    @Test-    fun `repeated halving keeps a strict order without colliding`() {-        var hi = 100.0-        val slots = List(20) {-            val mid = (0.0 + hi) / 2.0-            hi = mid-            mid-        }-        assertEquals(slots.sortedDescending(), slots)-        assertTrue(slots.toSet().size == slots.size)-    }--    @Test-    fun `sorting an empty list stays empty`() {-        assertEquals(emptyList(), emptyList<Todo>().sortedBy { it.position })-    }-}
todo/src/test/java/com/vayunmathur/todo/data/TodoSyncSemanticsTest.kt
diff --git a/todo/src/test/java/com/vayunmathur/todo/data/TodoSyncSemanticsTest.kt b/todo/src/test/java/com/vayunmathur/todo/data/TodoSyncSemanticsTest.ktdeleted file mode 100644index 0b00b50d36..0000000000--- a/todo/src/test/java/com/vayunmathur/todo/data/TodoSyncSemanticsTest.kt+++ /dev/null@@ -1,107 +0,0 @@-package com.vayunmathur.todo.data--import kotlin.test.Test-import kotlin.test.assertEquals-import kotlin.test.assertFalse-import kotlin.test.assertTrue--/**- * Pins the sync write semantics from `TodoRepository` as pure list mirrors:- * a local delete tombstones (never hard-deletes) so the next `querySince`- * propagates it, `tombstoneBySyncId` re-tombstones idempotently, raw writes- * preserve the pulled timestamp verbatim while local writes bump it, and a- * purge drops everything including tombstones.- *- * The repository methods need Room, so the exact rules are mirrored on plain- * lists here rather than called. Each mirror follows its source line by line:- * `copy(deleted = true)`, `updatedAt > since`, verbatim copy for raw writes.- */-class TodoSyncSemanticsTest {--    private fun tombstone(todos: List<Todo>, value: Todo): List<Todo> =-        todos.map { if (it.id == value.id) it.copy(deleted = true) else it }--    private fun tombstoneBySyncId(todos: List<Todo>, syncId: String): Pair<List<Todo>, Int> {-        val existing = todos.firstOrNull { it.syncId == syncId } ?: return todos to 0-        if (existing.deleted) return todos to 1-        return todos.map { if (it.syncId == syncId) it.copy(deleted = true) else it } to 1-    }--    private fun querySince(todos: List<Todo>, since: Long): List<Todo> =-        todos.filter { it.updatedAt > since }--    @Test-    fun `delete tombstones the row instead of removing it`() {-        val todos = listOf(Todo(id = 1, title = "a"), Todo(id = 2, title = "b"))-        val after = tombstone(todos, todos[0])-        assertEquals(2, after.size)-        assertTrue(after[0].deleted)-        assertFalse(after[1].deleted)-    }--    @Test-    fun `the tombstone keeps sync identity so the relay can match it`() {-        val todo = Todo(id = 1, title = "a", syncId = "s1", updatedAt = 50L)-        val after = tombstone(listOf(todo), todo).single()-        assertEquals("s1", after.syncId)-        assertEquals(50L, after.updatedAt)-    }--    @Test-    fun `tombstoneBySyncId tombstones once and reports missing as zero`() {-        val todos = listOf(Todo(id = 1, title = "a", syncId = "s1"))-        val (once, first) = tombstoneBySyncId(todos, "s1")-        assertEquals(1, first)-        assertTrue(once.single().deleted)-        val (twice, second) = tombstoneBySyncId(once, "s1")-        assertEquals(1, second)-        assertTrue(twice.single().deleted)-        val (_, missing) = tombstoneBySyncId(todos, "nope")-        assertEquals(0, missing)-    }--    @Test-    fun `querySince includes tombstones and excludes older rows`() {-        val todos = listOf(-            Todo(id = 1, updatedAt = 100L),-            Todo(id = 2, updatedAt = 200L, deleted = true),-            Todo(id = 3, updatedAt = 300L),-        )-        assertEquals(listOf(2L, 3L), querySince(todos, 100L).map { it.id })-        assertEquals(listOf(1L, 2L, 3L), querySince(todos, 0L).map { it.id })-        assertEquals(emptyList(), querySince(todos, 300L))-    }--    @Test-    fun `a raw write preserves the pulled timestamp verbatim`() {-        val pulled = Todo(id = 0, title = "t", updatedAt = 12345L)-        val stored = pulled.copy()-        assertEquals(12345L, stored.updatedAt)-    }--    @Test-    fun `a local write bumps updatedAt past the stored value`() {-        val stored = 1000L-        val bumped = maxOf(stored + 1, System.currentTimeMillis())-        assertTrue(bumped > stored)-    }--    @Test-    fun `the visible list hides tombstones while sync still sees them`() {-        val todos = listOf(-            Todo(id = 1, title = "open"),-            Todo(id = 2, title = "gone", deleted = true),-        )-        assertEquals(listOf(1L), todos.filter { !it.deleted }.map { it.id })-        assertEquals(listOf(1L, 2L), querySince(todos, 0L).map { it.id })-    }--    @Test-    fun `an incoming pull rebinds onto the existing row id`() {-        val existing = Todo(id = 9, title = "old", syncId = "s1", updatedAt = 10L)-        val pulled = existing.copy(id = existing.id, title = "new", updatedAt = 20L)-        assertEquals(9L, pulled.id)-        assertEquals("new", pulled.title)-        assertEquals("s1", pulled.syncId)-    }-}
todo/src/test/java/com/vayunmathur/todo/domain/PositionsTest.kt
diff --git a/todo/src/test/java/com/vayunmathur/todo/domain/PositionsTest.kt b/todo/src/test/java/com/vayunmathur/todo/domain/PositionsTest.ktnew file mode 100644index 0000000000..ca1cf7ee0e--- /dev/null+++ b/todo/src/test/java/com/vayunmathur/todo/domain/PositionsTest.kt@@ -0,0 +1,66 @@+package com.vayunmathur.todo.domain++import kotlin.random.Random+import kotlin.test.Test+import kotlin.test.assertEquals+import kotlin.test.assertFalse+import kotlin.test.assertTrue++class PositionsTest {++    @Test+    fun `after and before step away from the edge`() {+        assertEquals(Positions.STEP, Positions.after(null))+        assertEquals(10.0 + Positions.STEP, Positions.after(10.0))+        assertEquals(10.0 - Positions.STEP, Positions.before(10.0))+    }++    @Test+    fun `between lands strictly inside the middle half of the gap`() {+        val random = Random(42)+        repeat(1000) {+            val p = Positions.between(0.0, 100.0, random)+            assertTrue(p > 25.0 && p < 75.0, "got $p")+        }+    }++    @Test+    fun `concurrent inserts between the same neighbours do not collide`() {+        val a = Positions.between(1.0, 2.0, Random(1))+        val b = Positions.between(1.0, 2.0, Random(2))+        assertTrue(a != b)+    }++    @Test+    fun `moving down lands between the target and the row after it`() {+        val sorted = listOf(10.0, 20.0, 30.0, 40.0)+        val p = Positions.forMove(sorted, from = 0, to = 2, random = Random(0))+        assertTrue(p > 30.0 && p < 40.0)+    }++    @Test+    fun `moving up lands between the row before the target and the target`() {+        val sorted = listOf(10.0, 20.0, 30.0, 40.0)+        val p = Positions.forMove(sorted, from = 3, to = 1, random = Random(0))+        assertTrue(p > 10.0 && p < 20.0)+    }++    @Test+    fun `moving to either end steps past the edge`() {+        val sorted = listOf(10.0, 20.0, 30.0)+        assertEquals(30.0 + Positions.STEP, Positions.forMove(sorted, from = 0, to = 2))+        assertEquals(10.0 - Positions.STEP, Positions.forMove(sorted, from = 2, to = 0))+    }++    @Test+    fun `colliding keys need renormalizing`() {+        assertTrue(Positions.needsRenormalize(listOf(0.0, 0.0, 0.0)))+        assertFalse(Positions.needsRenormalize(listOf(1.0, 2.0, 3.0)))+        assertFalse(Positions.needsRenormalize(emptyList()))+    }++    @Test+    fun `renormalized keys are evenly spaced and ascending`() {+        assertEquals(listOf(1024.0, 2048.0, 3072.0), Positions.renormalized(3))+    }+}
todo/src/test/java/com/vayunmathur/todo/domain/TodoSearchTest.kt
diff --git a/todo/src/test/java/com/vayunmathur/todo/domain/TodoSearchTest.kt b/todo/src/test/java/com/vayunmathur/todo/domain/TodoSearchTest.ktnew file mode 100644index 0000000000..99c1e8d171--- /dev/null+++ b/todo/src/test/java/com/vayunmathur/todo/domain/TodoSearchTest.kt@@ -0,0 +1,40 @@+package com.vayunmathur.todo.domain++import com.vayunmathur.todo.data.Todo+import kotlin.test.Test+import kotlin.test.assertEquals++class TodoSearchTest {+    private val todos = listOf(+        Todo(id = 1, title = "Buy Milk"),+        Todo(id = 2, title = "Call Sam", notes = "about the milk run"),+        Todo(id = 3, title = "Work"),+        Todo(id = 4, title = "記 😀"),+    )++    @Test+    fun `blank query keeps every todo in order`() {+        assertEquals(todos, TodoSearch.filter(todos, ""))+        assertEquals(todos, TodoSearch.filter(todos, "   "))+    }++    @Test+    fun `matches titles and notes case-insensitively`() {+        assertEquals(listOf(1L, 2L), TodoSearch.filter(todos, "MILK").map { it.id })+    }++    @Test+    fun `surrounding whitespace in the query is ignored`() {+        assertEquals(listOf(3L), TodoSearch.filter(todos, "  work ").map { it.id })+    }++    @Test+    fun `unicode queries match unicode titles`() {+        assertEquals(listOf(4L), TodoSearch.filter(todos, "😀").map { it.id })+    }++    @Test+    fun `no match returns an empty list`() {+        assertEquals(emptyList(), TodoSearch.filter(todos, "zzz"))+    }+}
todo/src/test/java/com/vayunmathur/todo/platform/TodoUiContractTest.kt
diff --git a/todo/src/test/java/com/vayunmathur/todo/platform/TodoUiContractTest.kt b/todo/src/test/java/com/vayunmathur/todo/platform/TodoUiContractTest.ktdeleted file mode 100644index ae86a7b20b..0000000000--- a/todo/src/test/java/com/vayunmathur/todo/platform/TodoUiContractTest.kt+++ /dev/null@@ -1,83 +0,0 @@-package com.vayunmathur.todo.platform--import com.vayunmathur.todo.data.Todo-import kotlin.test.Test-import kotlin.test.assertEquals-import kotlin.test.assertFalse-import kotlin.test.assertNull-import kotlin.test.assertTrue--/**- * Pins the todo UI contract: state defaults, the no-op actions used by- * previews, and the detail-page copy chain (`setTitle` / `setNotes` /- * `setDone` / `setDueAt` are plain `copy` calls on the edited row).- *- * The binders live in composables, so the copies are mirrored here rather- * than called. The mirror is exact: `copy(title = ...)`, `copy(notes = ...)`,- * `copy(done = ...)`, `copy(dueAt = ...)`.- */-class TodoUiContractTest {--    @Test-    fun `list state defaults to an empty list with the add button shown`() {-        val state = TodoListUiState()-        assertEquals(emptyList(), state.todos)-        assertTrue(state.showAddButton)-    }--    @Test-    fun `detail state defaults to a blank open untimed task`() {-        val state = TodoUiState()-        assertEquals("", state.title)-        assertEquals("", state.notes)-        assertFalse(state.done)-        assertNull(state.dueAt)-    }--    @Test-    fun `noop actions accept every call without throwing`() {-        val list = TodoListActions.Noop-        list.openTodo(1L)-        list.createTodo()-        list.toggleDone(Todo(id = 1))-        list.delete(Todo(id = 1))-        list.upsertAll(listOf(Todo(id = 1)))-        val detail = TodoActions.Noop-        detail.back()-        detail.setTitle("t")-        detail.setNotes("n")-        detail.setDone(true)-        detail.setDueAt(5L)-        detail.deleteTodo()-    }--    @Test-    fun `the detail copy chain edits one field at a time`() {-        val start = Todo(title = "t", notes = "n", done = false, dueAt = null)-        val renamed = start.copy(title = "new")-        assertEquals("new", renamed.title)-        assertEquals("n", renamed.notes)-        val noted = renamed.copy(notes = "new notes")-        assertEquals("new notes", noted.notes)-        val checked = noted.copy(done = true)-        assertTrue(checked.done)-        val dated = checked.copy(dueAt = 42L)-        assertEquals(42L, dated.dueAt)-        assertEquals("new", dated.title)-    }--    @Test-    fun `detail state round-trips from a todo and back`() {-        val todo = Todo(title = "t", notes = "n", done = true, dueAt = 7L)-        val state = TodoUiState(title = todo.title, notes = todo.notes, done = todo.done, dueAt = todo.dueAt)-        val back = todo.copy(title = state.title, notes = state.notes, done = state.done, dueAt = state.dueAt)-        assertEquals(todo, back)-    }--    @Test-    fun `unicode survives the detail copy chain`() {-        val state = TodoUiState(title = "記 😀", notes = "مرحبا тело")-        assertEquals("記 😀", state.title)-        assertEquals("مرحبا тело", state.notes)-    }-}