todo: accessibility, shared-element title, listing refresh, detekt-clean
- Commit
905d6dedb70a0d6274613d2ab8eba3c578b14672- Author
- Vayun Mathur <[email protected]>
- When
- 2026-11-01 00:08 UTC (1 month ago)
- Parents
7ef3bf5
- List title morphs into the editor title (shared element). - Store listing: new summary and features; previews for Today, editor, views drawer, all tasks, search and a tablet three-pane layout. - Split TodoRepository's list and relay surfaces into extension files and reduce parser/query/format complexity so :todo passes detekt. - Instrumented tests follow the new launch view, editor chips and completed section. - AGENTS.md describes the new structure and gotchas.
Diff
metadata_data/photos/todo/phone/1.png
diff --git a/metadata_data/photos/todo/phone/1.png b/metadata_data/photos/todo/phone/1.pngindex f17075de50..65e07a8689 100644Binary files a/metadata_data/photos/todo/phone/1.png and b/metadata_data/photos/todo/phone/1.png differ
metadata_data/photos/todo/phone/2.png
diff --git a/metadata_data/photos/todo/phone/2.png b/metadata_data/photos/todo/phone/2.pngindex ddb2adba0d..bf47af23f8 100644Binary files a/metadata_data/photos/todo/phone/2.png and b/metadata_data/photos/todo/phone/2.png differ
metadata_data/photos/todo/phone/3.png
diff --git a/metadata_data/photos/todo/phone/3.png b/metadata_data/photos/todo/phone/3.pngindex 610eb65d8c..d21f5c39de 100644Binary files a/metadata_data/photos/todo/phone/3.png and b/metadata_data/photos/todo/phone/3.png differ
metadata_data/photos/todo/phone/4.png
diff --git a/metadata_data/photos/todo/phone/4.png b/metadata_data/photos/todo/phone/4.pngnew file mode 100644index 0000000000..a5c141b087Binary files /dev/null and b/metadata_data/photos/todo/phone/4.png differ
metadata_data/photos/todo/phone/5.png
diff --git a/metadata_data/photos/todo/phone/5.png b/metadata_data/photos/todo/phone/5.pngnew file mode 100644index 0000000000..f8ff092ea5Binary files /dev/null and b/metadata_data/photos/todo/phone/5.png differ
metadata_data/photos/todo/tablet/1.png
diff --git a/metadata_data/photos/todo/tablet/1.png b/metadata_data/photos/todo/tablet/1.pngnew file mode 100644index 0000000000..528b1962dbBinary files /dev/null and b/metadata_data/photos/todo/tablet/1.png differ
metadata_data/todo.md
diff --git a/metadata_data/todo.md b/metadata_data/todo.mdindex 8647a68448..aa43dd570f 100644--- a/metadata_data/todo.md+++ b/metadata_data/todo.md@@ -1,9 +1,14 @@-A simple task list with due dates+Tasks, lists, reminders and repeats with natural-language quick add Features:-- Create tasks with optional due dates-- Check tasks off as you go-- Reorder tasks by dragging+- Type "Pay rent every 1st #home !1 tomorrow 9am" and it is understood+- Smart views: Today, Upcoming, Priority, plus your own lists and tags+- Subtasks, priorities, due times, start dates and repeating tasks+- Reminders with snooze, and an optional daily summary+- Swipe to complete or delete with undo; drag to reorder; bulk edit+- Home-screen widgets, quick settings tile, and share-to-task+- Show due tasks in any calendar app+- Import and export todo.txt, CSV and iCalendar - Local backup and restore - Encrypted end-to-end sync via EverySync
todo/AGENTS.md
diff --git a/todo/AGENTS.md b/todo/AGENTS.mdindex 8496d86517..9e0fd59b0c 100644--- a/todo/AGENTS.md+++ b/todo/AGENTS.md@@ -3,50 +3,45 @@ > Scoped supplement. Global rules in root `AGENTS.md` apply. Stay inside `todo/` + allowed shared modules. Do not root-scan. _Install: ./install todo (dev by default)._-<!-- last-reviewed: 2026-10-16 -->+<!-- last-reviewed: 2026-11-01 --> - Gradle: :todo / dir: todo/-- Package roots present: ui, data, platform, sync-- Entry files: MainActivity.kt, Route.kt, Navigation.kt-- Deps: :library:room+- Package roots present: ui, data, domain, platform, sync, notifications, widget, service, intents+- Entry files: MainActivity.kt, Route.kt, Navigation.kt, TodoApplication.kt+- Deps: :library:room, :library:widgets - Metadata: metadata_data/todo.md (present) - Rust: no / screenshotTest: yes ## Overview-**Purpose:** Offline task list with due dates, drag reorder, backup/restore, and E2EE sync via EverySync (`sync/RelayTodoProvider`).-**Key features:**-- Tasks with due dates, check-off, drag-to-reorder list + detail screens-- Local backup/restore via `AppBackupAgent`; relay sync snapshots consumed by everysync (`TodoSink`/`TodoIpcSink` side)-- `TodoUiContract` + `TodoViewModel` over Room (`Todo`, `TodoDatabase`, `TodoRepository`)-**Architecture / data-flow:** `ui/` list/detail → `platform/TodoViewModel` → `data/TodoRepository` over Room; `sync/RelayTodoProvider` exposes the relay surface everysync syncs.-**Entry points + reading order:** `Route` → `MainActivity.kt` → `Navigation.kt` → `ui/TodoListScreen.kt` → `platform/TodoViewModel.kt` → `data/TodoRepository.kt` → `sync/RelayTodoProvider.kt`.+**Purpose:** Offline task manager: lists, smart views, subtasks, priorities, timed due dates, repeats, reminders, natural-language quick add, widgets, calendar mirror, import/export, and E2EE sync via EverySync.+**Architecture / data-flow:** `ui/` (stateless `*Screen` + binding `*Page`) → `platform/TodoViewModel` / `platform/TodoEditor` → `data/TodoRepository` over Room (`Todo`, `TodoList`, `SyncSnapshot`). Pure logic lives in `domain/` (no Android): `TodoQuery` (views/sort/groups), `QuickAddParser`, `Recurrence`, `Completion`, `Positions`, `DueDates`, `format/` (todo.txt, CSV, VTODO). `platform/TodoBackground` (started by `TodoApplication`) reacts to any data change: reminder alarms, digest, per-list channels, widgets, calendar mirror.+**Entry points + reading order:** `Route` → `Navigation.kt` → `ui/TodoShell` → `ui/TodoListPage` → `platform/TodoViewModel` → `domain/TodoQuery` → `data/TodoRepository` → `sync/RelayTodoProvider`. **Gotchas:**-- `settings.gradle.kts` lists `:todo` twice — harmless Gradle quirk, indexed once everywhere-- Relay schema changes must stay compatible with everysync's `TodoKind` adapter — update both sides together+- Relay envelopes (`sync/RelayEnvelopes.kt`) mirror everysync's `RemoteTodo` / `RemoteTodoList` field-for-field. Never rename a key; new fields need defaults (encodeDefaults is off, so legacy hashes stay identical). Update both sides together.+- Lists sync on their own `todolists:<vault>` channel so pre-list builds never see them as tasks.+- All-day `dueAt` is **local** midnight. The Material date picker speaks UTC midnight — go through `DueDates.fromPickerMillis` / `toPickerMillis` (or `ui/TodoDatePickerDialog`).+- Editor writes run on `TodoRepository.appScope` and flush on close; a new task is only inserted once it has a title (`platform/TodoEditor`).+- Completing a repeating task rolls the same row forward (`domain/Completion`), it does not create a copy.+- `exportSchema = true`: bump the DB version and commit `schemas/…/<n>.json` with every schema change; extend `TodoMigrationTest`.+- `settings.gradle.kts` lists `:todo` twice — harmless Gradle quirk. ## Key files-### Root — entry + navigation-- com/vayunmathur/todo/MainActivity.kt-- com/vayunmathur/todo/Navigation.kt-- com/vayunmathur/todo/Route.kt-### data/ — Room store-- com/vayunmathur/todo/data/TodoDatabase.kt-- com/vayunmathur/todo/data/TodoRepository.kt-- com/vayunmathur/todo/data/Todo.kt-### platform/ — ViewModel, contract, backup-- com/vayunmathur/todo/platform/TodoViewModel.kt-- com/vayunmathur/todo/platform/TodoUiContract.kt-- com/vayunmathur/todo/platform/AppBackupAgent.kt-### sync/ — everysync relay surface-- com/vayunmathur/todo/sync/RelayTodoProvider.kt-### ui/ — list + detail-- com/vayunmathur/todo/ui/TodoListScreen.kt-- com/vayunmathur/todo/ui/TodoListPage.kt-- com/vayunmathur/todo/ui/TodoDetailScreen.kt-- com/vayunmathur/todo/ui/TodoDetailPage.kt+### Root+- MainActivity.kt (intent capture → `platform/IntentRouter`), Navigation.kt, Route.kt, TodoApplication.kt+### data/+- Todo.kt, TodoList.kt, TodoDatabase.kt (DAOs), TodoMigrations.kt, TodoRepository.kt, TodoSettings.kt (DataStore)+### domain/+- TodoQuery.kt, TodoView.kt, QuickAddParser.kt + QuickAddWords.kt, Recurrence.kt, Completion.kt, DueDates.kt, DueBuckets.kt, Positions.kt, Reminders.kt, format/+### platform/+- TodoViewModel.kt, TodoEditor.kt, TodoListUiContract.kt, TodoEditorUiContract.kt, TodoBackground.kt, IntentRouter.kt, TodoDataTransfer.kt, AppBackupAgent.kt+### sync/+- RelayTodoProvider.kt, RelayEnvelopes.kt, CalendarMirror.kt+### notifications/ widget/ service/ intents/+- ReminderScheduler, ReminderReceiver, ReminderActionReceiver, BootReceiver, DigestScheduler; TodayWidget, QuickAddWidget; QuickAddTileService; Get/Insert/CompleteTodoIntent (openassistant tools) ## Verify (this module only) ```-./gradlew :todo:compileDevKotlin-./gradlew :todo:lint-./gradlew :todo:checkMetadata+./gradlew :todo:compileDevKotlin :todo:testDevUnitTest :todo:lint+./gradlew checkMetadata+./gradlew :todo:metadata # regenerate listing screenshots after UI changes ```+Relay changes: also `./gradlew :everysync:testDevUnitTest`.
todo/src/androidTest/java/com/vayunmathur/todo/ui/TodoAddTest.kt
diff --git a/todo/src/androidTest/java/com/vayunmathur/todo/ui/TodoAddTest.kt b/todo/src/androidTest/java/com/vayunmathur/todo/ui/TodoAddTest.ktindex 7724b3c91d..7a557252e1 100644--- a/todo/src/androidTest/java/com/vayunmathur/todo/ui/TodoAddTest.kt+++ b/todo/src/androidTest/java/com/vayunmathur/todo/ui/TodoAddTest.kt@@ -125,7 +125,8 @@ class TodoAddTest { private const val SAVE_SETTLE_MS = 1_000L private const val SEARCH_PLACEHOLDER = "Search Today" private const val EDITOR_NOTES_LABEL = "Notes"- private const val NO_DUE_DATE = "Due date"+ // Tasks created from Today are due today, so check a chip that is always unset.+ private const val NO_DUE_DATE = "Repeat" private const val ADD_DESCRIPTION = "Add" private const val EDIT_TEXT_CLASS = "android.widget.EditText" private const val TASK_TITLE = "Journey Todo Alpha"
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 decc9d080a..b0ab998e09 100644--- a/todo/src/main/java/com/vayunmathur/todo/data/TodoDatabase.kt+++ b/todo/src/main/java/com/vayunmathur/todo/data/TodoDatabase.kt@@ -14,7 +14,7 @@ import kotlinx.coroutines.flow.Flow const val DB_NAME = "todo-db" -/** Backup config shared by [AppBackupAgent][com.vayunmathur.todo.platform.AppBackupAgent] and the in-app backup buttons. */+/** Backup config shared by the backup agent and the in-app backup buttons. */ fun todoDbConfigs(context: Context): List<Pair<String, String>> = listOf(DB_NAME to DatabaseHelper(context).getPassphrase())
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 c8935f2001..83b03c4825 100644--- a/todo/src/main/java/com/vayunmathur/todo/data/TodoRepository.kt+++ b/todo/src/main/java/com/vayunmathur/todo/data/TodoRepository.kt@@ -13,6 +13,10 @@ import kotlinx.coroutines.SupervisorJob import kotlinx.coroutines.flow.Flow import kotlinx.datetime.TimeZone +/**+ * The single owner of the todo database. Task operations live here; list operations are in+ * `TodoRepositoryLists.kt` and the relay-only surface in `TodoRepositoryRelay.kt`.+ */ class TodoRepository private constructor( context: Context, val io: CoroutineDispatcher = Dispatchers.IO,@@ -21,9 +25,9 @@ class TodoRepository private constructor( /** 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 listDao get() = db.todoListDao()- private val snapshotDao get() = db.syncSnapshotDao()+ internal val dao get() = db.todoDao()+ internal val listDao get() = db.todoListDao()+ internal val snapshotDao get() = db.syncSnapshotDao() val todos: Flow<List<Todo>> get() = dao.getAllFlow() val lists: Flow<List<TodoList>> get() = listDao.getAllFlow()@@ -39,7 +43,6 @@ class TodoRepository private constructor( suspend fun getById(id: Long): Todo? = dao.getById(id) suspend fun getBySyncId(syncId: String): Todo? = dao.getBySyncId(syncId) suspend fun getSubtasks(parentSyncId: String): List<Todo> = dao.getSubtasks(parentSyncId)- suspend fun getUpdatedSince(since: Long): List<Todo> = dao.getUpdatedSince(since) suspend fun nextPosition(): Double = Positions.after(dao.maxPosition()) @@ -49,9 +52,6 @@ class TodoRepository private constructor( /** 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)- /** Soft delete: the relay sync propagates the tombstone. Subtasks go with their parent. */ suspend fun tombstone(value: Todo) = inTransaction { dao.upsert(value.copy(deleted = true))@@ -62,18 +62,16 @@ class TodoRepository private constructor( dao.upsert(value.copy(deleted = false)) } - suspend fun tombstoneBySyncId(syncId: String): Int {- val existing = dao.getBySyncId(syncId) ?: return 0- if (!existing.deleted) dao.upsert(existing.copy(deleted = true))- return 1- }- /** * Sets the done state. Completing a repeating task rolls it to the next occurrence and * reopens its subtasks; returns the stored row. */ suspend fun setDone(todo: Todo, done: Boolean, now: Long = System.currentTimeMillis()): Todo = inTransaction {- val updated = if (done) Completion.complete(todo, now, TimeZone.currentSystemDefault()) else Completion.uncomplete(todo)+ val updated = if (done) {+ Completion.complete(todo, now, TimeZone.currentSystemDefault())+ } else {+ Completion.uncomplete(todo)+ } dao.upsert(updated) if (Completion.rolledForward(todo, updated)) { dao.upsertAll(dao.getSubtasks(todo.syncId).filter { it.done }.map { Completion.uncomplete(it) })@@ -115,34 +113,6 @@ class TodoRepository private constructor( copy.copy(id = id) } - /** Removes every todo (including tombstones). Used when a relay vault is purged. */- suspend fun purge() = dao.deleteAll()-- // --- Lists ----- suspend fun getLists(): List<TodoList> = listDao.getAll()- suspend fun getListBySyncId(syncId: String): TodoList? = listDao.getBySyncId(syncId)- suspend fun getListsUpdatedSince(since: Long): List<TodoList> = listDao.getUpdatedSince(since)- suspend fun nextListPosition(): Double = Positions.after(listDao.maxPosition())-- suspend fun upsertList(value: TodoList): Long = listDao.upsert(value)- suspend fun upsertLists(values: List<TodoList>) = listDao.upsertAll(values)- suspend fun upsertListRaw(value: TodoList): Long = listDao.upsertRaw(value)-- /** Deletes a list; its tasks move to the Inbox. */- suspend fun tombstoneList(list: TodoList) = inTransaction {- listDao.upsert(list.copy(deleted = true))- dao.upsertAll(dao.getInList(list.syncId).map { it.copy(listSyncId = null, section = null) })- }-- suspend fun tombstoneListBySyncId(syncId: String): Int {- val existing = listDao.getBySyncId(syncId) ?: return 0- if (!existing.deleted) listDao.upsert(existing.copy(deleted = true))- return 1- }-- suspend fun purgeLists() = listDao.deleteAll()- // --- Housekeeping --- /** On launch: drop stale unsynced tombstones and repair colliding positions. */@@ -155,15 +125,6 @@ class TodoRepository private constructor( } } - // --- Relay snapshots ----- suspend fun getTodoSnapshots(): List<SyncSnapshot> = snapshotDao.getAllExcept(SyncSnapshot.KIND_LIST)- suspend fun getListSnapshots(): List<SyncSnapshot> = snapshotDao.getByKind(SyncSnapshot.KIND_LIST)- suspend fun upsertSnapshot(snapshot: SyncSnapshot) = snapshotDao.upsert(snapshot)- suspend fun deleteSnapshotBySyncId(syncId: String) = snapshotDao.deleteBySyncId(syncId)- suspend fun deleteTodoSnapshots() = snapshotDao.deleteAllExcept(SyncSnapshot.KIND_LIST)- suspend fun deleteListSnapshots() = snapshotDao.deleteByKind(SyncSnapshot.KIND_LIST)- companion object { @Volatile private var instance: TodoRepository? = null fun get(context: Context): TodoRepository =
todo/src/main/java/com/vayunmathur/todo/data/TodoRepositoryLists.kt
diff --git a/todo/src/main/java/com/vayunmathur/todo/data/TodoRepositoryLists.kt b/todo/src/main/java/com/vayunmathur/todo/data/TodoRepositoryLists.ktnew file mode 100644index 0000000000..a2808a22b7--- /dev/null+++ b/todo/src/main/java/com/vayunmathur/todo/data/TodoRepositoryLists.kt@@ -0,0 +1,15 @@+package com.vayunmathur.todo.data++import com.vayunmathur.todo.domain.Positions++suspend fun TodoRepository.getLists(): List<TodoList> = listDao.getAll()+suspend fun TodoRepository.getListBySyncId(syncId: String): TodoList? = listDao.getBySyncId(syncId)+suspend fun TodoRepository.nextListPosition(): Double = Positions.after(listDao.maxPosition())+suspend fun TodoRepository.upsertList(value: TodoList): Long = listDao.upsert(value)+suspend fun TodoRepository.upsertLists(values: List<TodoList>) = listDao.upsertAll(values)++/** Deletes a list; its tasks move to the Inbox. */+suspend fun TodoRepository.tombstoneList(list: TodoList) = inTransaction {+ listDao.upsert(list.copy(deleted = true))+ dao.upsertAll(dao.getInList(list.syncId).map { it.copy(listSyncId = null, section = null) })+}
todo/src/main/java/com/vayunmathur/todo/data/TodoRepositoryRelay.kt
diff --git a/todo/src/main/java/com/vayunmathur/todo/data/TodoRepositoryRelay.kt b/todo/src/main/java/com/vayunmathur/todo/data/TodoRepositoryRelay.ktnew file mode 100644index 0000000000..093239419a--- /dev/null+++ b/todo/src/main/java/com/vayunmathur/todo/data/TodoRepositoryRelay.kt@@ -0,0 +1,36 @@+package com.vayunmathur.todo.data++// The relay provider's surface: raw writes that keep pulled timestamps, tombstones by sync id,+// purges, and the snapshot baseline. Nothing else should call these.++suspend fun TodoRepository.getUpdatedSince(since: Long): List<Todo> = dao.getUpdatedSince(since)++/** Writes [value] verbatim, preserving a pulled timestamp. */+suspend fun TodoRepository.upsertRaw(value: Todo): Long = dao.upsertRaw(value)++suspend fun TodoRepository.tombstoneBySyncId(syncId: String): Int {+ val existing = dao.getBySyncId(syncId) ?: return 0+ if (!existing.deleted) dao.upsert(existing.copy(deleted = true))+ return 1+}++/** Removes every todo (including tombstones). Used when a relay vault is purged. */+suspend fun TodoRepository.purge() = dao.deleteAll()++suspend fun TodoRepository.getListsUpdatedSince(since: Long): List<TodoList> = listDao.getUpdatedSince(since)+suspend fun TodoRepository.upsertListRaw(value: TodoList): Long = listDao.upsertRaw(value)++suspend fun TodoRepository.tombstoneListBySyncId(syncId: String): Int {+ val existing = listDao.getBySyncId(syncId) ?: return 0+ if (!existing.deleted) listDao.upsert(existing.copy(deleted = true))+ return 1+}++suspend fun TodoRepository.purgeLists() = listDao.deleteAll()++suspend fun TodoRepository.getTodoSnapshots(): List<SyncSnapshot> = snapshotDao.getAllExcept(SyncSnapshot.KIND_LIST)+suspend fun TodoRepository.getListSnapshots(): List<SyncSnapshot> = snapshotDao.getByKind(SyncSnapshot.KIND_LIST)+suspend fun TodoRepository.upsertSnapshot(snapshot: SyncSnapshot) = snapshotDao.upsert(snapshot)+suspend fun TodoRepository.deleteSnapshotBySyncId(syncId: String) = snapshotDao.deleteBySyncId(syncId)+suspend fun TodoRepository.deleteTodoSnapshots() = snapshotDao.deleteAllExcept(SyncSnapshot.KIND_LIST)+suspend fun TodoRepository.deleteListSnapshots() = snapshotDao.deleteByKind(SyncSnapshot.KIND_LIST)
todo/src/main/java/com/vayunmathur/todo/data/TodoSettings.kt
diff --git a/todo/src/main/java/com/vayunmathur/todo/data/TodoSettings.kt b/todo/src/main/java/com/vayunmathur/todo/data/TodoSettings.ktindex ac118863f3..77f6b91afa 100644--- a/todo/src/main/java/com/vayunmathur/todo/data/TodoSettings.kt+++ b/todo/src/main/java/com/vayunmathur/todo/data/TodoSettings.kt@@ -13,7 +13,8 @@ import kotlinx.coroutines.flow.onStart class TodoSettings(context: Context) { private val store = DataStoreUtils.getInstance(context.applicationContext) - private fun string(key: String, default: String): Flow<String> = store.stringFlow(key).onStart { emit(store.getString(key) ?: default) }+ private fun string(key: String, default: String): Flow<String> =+ store.stringFlow(key).onStart { emit(store.getString(key) ?: default) } val defaultView: Flow<TodoView> = string(KEY_DEFAULT_VIEW, TodoView.Today.key).map { TodoView.fromKey(it) } val defaultSort: Flow<SortMode> = string(KEY_DEFAULT_SORT, SortMode.MANUAL.name)
todo/src/main/java/com/vayunmathur/todo/domain/QuickAddWords.kt
diff --git a/todo/src/main/java/com/vayunmathur/todo/domain/QuickAddWords.kt b/todo/src/main/java/com/vayunmathur/todo/domain/QuickAddWords.ktindex 17f67070ab..32e5b5f310 100644--- a/todo/src/main/java/com/vayunmathur/todo/domain/QuickAddWords.kt+++ b/todo/src/main/java/com/vayunmathur/todo/domain/QuickAddWords.kt@@ -27,7 +27,7 @@ internal object RecurrenceWords { "yearly" to Recurrence.Yearly(), "annually" to Recurrence.Yearly(), )- private val WORKDAYS = setOf(DayOfWeek.MONDAY, DayOfWeek.TUESDAY, DayOfWeek.WEDNESDAY, DayOfWeek.THURSDAY, DayOfWeek.FRIDAY)+ private val WORKDAYS = DayOfWeek.entries.filter { it != DayOfWeek.SATURDAY && it != DayOfWeek.SUNDAY }.toSet() private val ORDINAL = Regex("^(\\d{1,2})(st|nd|rd|th)$") fun parse(state: State) {@@ -42,18 +42,19 @@ internal object RecurrenceWords { } } + private fun simpleEvery(word: String, afterCompletion: Boolean): Recurrence? = when (word) {+ "day" -> unitRecurrence(DateTimeUnit.DAY, 1, afterCompletion)+ "week" -> unitRecurrence(DateTimeUnit.WEEK, 1, afterCompletion)+ "month" -> Recurrence.Monthly()+ "year" -> Recurrence.Yearly()+ "weekday" -> Recurrence.Weekly(1, WORKDAYS)+ "weekend" -> Recurrence.Weekly(1, setOf(DayOfWeek.SATURDAY, DayOfWeek.SUNDAY))+ else -> null+ }+ private fun parseEvery(state: State, i: Int, afterCompletion: Boolean) { val next = state.text(i + 1) ?: return- val simple = when (next) {- "day" -> unitRecurrence(DateTimeUnit.DAY, 1, afterCompletion)- "week" -> unitRecurrence(DateTimeUnit.WEEK, 1, afterCompletion)- "month" -> Recurrence.Monthly()- "year" -> Recurrence.Yearly()- "weekday" -> Recurrence.Weekly(1, WORKDAYS)- "weekend" -> Recurrence.Weekly(1, setOf(DayOfWeek.SATURDAY, DayOfWeek.SUNDAY))- else -> null- }- if (simple != null) return set(state, simple, i, 2)+ simpleEvery(next, afterCompletion)?.let { return set(state, it, i, 2) } val unitAfter = state.text(i + 2)?.let { UNITS[it] } val count = if (next == "other") 2 else next.toIntOrNull() if (count != null && count > 0 && unitAfter != null) {@@ -73,7 +74,8 @@ internal object RecurrenceWords { private fun unitRecurrence(unit: DateTimeUnit, n: Int, afterCompletion: Boolean): Recurrence = when (unit) { DateTimeUnit.DAY -> if (afterCompletion) Recurrence.AfterCompletion(n) else Recurrence.Daily(n)- DateTimeUnit.WEEK -> if (afterCompletion) Recurrence.AfterCompletion(n * DAYS_PER_WEEK) else Recurrence.Weekly(n)+ DateTimeUnit.WEEK ->+ if (afterCompletion) Recurrence.AfterCompletion(n * DAYS_PER_WEEK) else Recurrence.Weekly(n) DateTimeUnit.MONTH -> Recurrence.Monthly(n) else -> Recurrence.Yearly(n) }@@ -109,7 +111,12 @@ internal object RecurrenceWords { recurrence.days.minOfOrNull { QuickAddParser.nextOnOrAfter(today, it) } ?: today is Recurrence.Monthly -> { val day = recurrence.dayOfMonth- if (day == null) today else monthDay(today, day).let { if (it >= today) it else monthDay(firstOfNextMonth(today), day) }+ val thisMonth = day?.let { monthDay(today, it) }+ when {+ day == null || thisMonth == null -> today+ thisMonth >= today -> thisMonth+ else -> monthDay(firstOfNextMonth(today), day)+ } } else -> today }@@ -119,7 +126,8 @@ internal object RecurrenceWords { private fun monthDay(inMonth: LocalDate, day: Int): LocalDate { val first = LocalDate(inMonth.year, inMonth.month.number, 1) val last = first.plus(1, DateTimeUnit.MONTH).minus(1, DateTimeUnit.DAY).day- return LocalDate(first.year, first.month.number, if (day == Recurrence.LAST_DAY) last else day.coerceAtMost(last))+ val target = if (day == Recurrence.LAST_DAY) last else day.coerceAtMost(last)+ return LocalDate(first.year, first.month.number, target) } private const val DAYS_PER_WEEK = 7@@ -208,16 +216,27 @@ internal object DateWords { private fun absolute(state: State, i: Int): Pair<LocalDate, Int>? { val t = state.text(i) ?: return null+ return numeric(state, t) ?: monthFirst(state, i, t) ?: dayFirst(state, i, t)+ }++ /** "2026-03-05", "3/5", "3/5/27". */+ private fun numeric(state: State, t: String): Pair<LocalDate, Int>? { ISO.find(t)?.destructured?.let { (y, m, d) -> return date(y.toInt(), m.toInt(), d.toInt())?.to(1) }- SLASH.find(t)?.groupValues?.let { g ->- val year = g[3].takeIf { it.isNotEmpty() }?.toInt()?.let { if (it < CENTURY) it + 2000 else it }- return dated(state, g[1].toInt(), g[2].toInt(), year)?.to(1)- }- MONTHS[t]?.let { month ->- val day = state.text(i + 1)?.let { DAY_NUM.find(it) }?.groupValues?.get(1)?.toInt() ?: return null- val year = state.text(i + 2)?.takeIf { YEAR.matches(it) }?.toInt()- return dated(state, month.number, day, year)?.to(if (year != null) 3 else 2)- }+ val g = SLASH.find(t)?.groupValues ?: return null+ val year = g[3].takeIf { it.isNotEmpty() }?.toInt()?.let { if (it < CENTURY) it + 2000 else it }+ return dated(state, g[1].toInt(), g[2].toInt(), year)?.to(1)+ }++ /** "jan 5", "january 5th 2027". */+ private fun monthFirst(state: State, i: Int, t: String): Pair<LocalDate, Int>? {+ val month = MONTHS[t] ?: return null+ val day = state.text(i + 1)?.let { DAY_NUM.find(it) }?.groupValues?.get(1)?.toInt() ?: return null+ val year = state.text(i + 2)?.takeIf { YEAR.matches(it) }?.toInt()+ return dated(state, month.number, day, year)?.to(if (year != null) 3 else 2)+ }++ /** "5 jan", "5th january 2027". */+ private fun dayFirst(state: State, i: Int, t: String): Pair<LocalDate, Int>? { val day = DAY_NUM.find(t)?.groupValues?.get(1)?.toInt() ?: return null val month = state.text(i + 1)?.let { MONTHS[it] } ?: return null val year = state.text(i + 2)?.takeIf { YEAR.matches(it) }?.toInt()
todo/src/main/java/com/vayunmathur/todo/domain/Recurrence.kt
diff --git a/todo/src/main/java/com/vayunmathur/todo/domain/Recurrence.kt b/todo/src/main/java/com/vayunmathur/todo/domain/Recurrence.ktindex 2f06e82430..23f476b4e3 100644--- a/todo/src/main/java/com/vayunmathur/todo/domain/Recurrence.kt+++ b/todo/src/main/java/com/vayunmathur/todo/domain/Recurrence.kt@@ -71,6 +71,7 @@ sealed interface Recurrence { const val LAST_DAY = -1 private const val X_FROM = "X-FROM" private const val MAX_INTERVAL = 999+ private const val MAX_DAY = 31 private val DAY_CODES = mapOf( DayOfWeek.MONDAY to "MO", DayOfWeek.TUESDAY to "TU", DayOfWeek.WEDNESDAY to "WE",@@ -89,12 +90,15 @@ sealed interface Recurrence { return when (parts["FREQ"]?.uppercase()) { "DAILY" -> if (parts[X_FROM].equals("COMPLETION", true)) AfterCompletion(interval) else Daily(interval) "WEEKLY" -> Weekly(interval, parseDays(parts["BYDAY"]))- "MONTHLY" -> Monthly(interval, parts["BYMONTHDAY"]?.toIntOrNull()?.takeIf { it == LAST_DAY || it in 1..31 })+ "MONTHLY" -> Monthly(interval, parseMonthDay(parts["BYMONTHDAY"])) "YEARLY" -> Yearly(interval) else -> null } } + private fun parseMonthDay(raw: String?): Int? =+ raw?.toIntOrNull()?.takeIf { it == LAST_DAY || it in 1..MAX_DAY }+ private fun parseDays(raw: String?): Set<DayOfWeek> = raw.orEmpty().split(',').mapNotNull { CODE_DAYS[it.trim().takeLast(2).uppercase()] }.toSet() }
todo/src/main/java/com/vayunmathur/todo/domain/TodoQuery.kt
diff --git a/todo/src/main/java/com/vayunmathur/todo/domain/TodoQuery.kt b/todo/src/main/java/com/vayunmathur/todo/domain/TodoQuery.ktindex 2e953dc242..1d4c615470 100644--- a/todo/src/main/java/com/vayunmathur/todo/domain/TodoQuery.kt+++ b/todo/src/main/java/com/vayunmathur/todo/domain/TodoQuery.kt@@ -89,26 +89,42 @@ object TodoQuery { private fun inView(row: TodoRow, input: Input): Boolean { val todo = row.todo- val started = todo.startAt == null || todo.startAt <= input.now- return when (val view = input.view) {- TodoView.Inbox -> todo.listSyncId == null && started- TodoView.Today -> started && !row.blocked && (todo.done || DueBuckets.isDueByToday(todo, input.now, input.zone)) &&- (!todo.done || completedToday(todo, input))- TodoView.Upcoming -> started && todo.dueAt != null && !row.overdue- TodoView.Priority -> started && todo.priority != Todo.PRIORITY_NONE+ val view = input.view+ if (hidesDeferred(view) && (todo.startAt ?: 0L) > input.now) return false+ return when (view) {+ TodoView.Inbox -> todo.listSyncId == null+ TodoView.Today -> inToday(row, input)+ TodoView.Upcoming -> todo.dueAt != null && !row.overdue+ TodoView.Priority -> todo.priority != Todo.PRIORITY_NONE TodoView.All -> true TodoView.Completed -> todo.done is TodoView.InList -> todo.listSyncId == view.listSyncId- is TodoView.Tagged -> started && todo.tags.any { it.equals(view.tag, ignoreCase = true) }+ is TodoView.Tagged -> todo.tags.any { it.equals(view.tag, ignoreCase = true) } } } + /** Tasks with a future start date stay out of the focus views until then. */+ private fun hidesDeferred(view: TodoView) =+ view !is TodoView.InList && view != TodoView.All && view != TodoView.Completed++ /** Open and due by today, or completed today; never while blocked. */+ private fun inToday(row: TodoRow, input: Input): Boolean {+ val todo = row.todo+ if (row.blocked) return false+ return if (todo.done) completedToday(todo, input) else DueBuckets.isDueByToday(todo, input.now, input.zone)+ }+ private fun completedToday(todo: Todo, input: Input): Boolean { val at = todo.completedAt ?: return false return DueBuckets.dayDelta(at, input.now, input.zone) == 0 } - private fun group(rows: List<TodoRow>, input: Input, listsById: Map<String, TodoList>, searching: Boolean): List<TodoGroup> {+ private fun group(+ rows: List<TodoRow>,+ input: Input,+ listsById: Map<String, TodoList>,+ searching: Boolean,+ ): List<TodoGroup> { if (searching) return listOf(TodoGroup(GroupKey.None, rows)) val byBucket = input.sort == SortMode.DUE || input.view == TodoView.Today || input.view == TodoView.Upcoming val view = input.view@@ -126,7 +142,8 @@ object TodoQuery { val bySection = rows.groupBy { row -> row.todo.section?.takeIf { it in sections } } val unsectioned = bySection[null].orEmpty() val named = sections.map { TodoGroup(GroupKey.Section(it), bySection[it].orEmpty()) }- return (if (unsectioned.isEmpty()) emptyList() else listOf(TodoGroup(GroupKey.Section(null), unsectioned))) + named+ val head = if (unsectioned.isEmpty()) emptyList() else listOf(TodoGroup(GroupKey.Section(null), unsectioned))+ return head + named } fun comparator(sort: SortMode): Comparator<TodoRow> {@@ -138,7 +155,8 @@ object TodoQuery { SortMode.PRIORITY -> compareBy<TodoRow> { priorityRank(it.todo) } .then(compareBy(nullsLast()) { it.todo.dueAt }).then(byPosition) SortMode.CREATED -> compareByDescending<TodoRow> { it.todo.createdAt }- SortMode.TITLE -> compareBy<TodoRow, String>(String.CASE_INSENSITIVE_ORDER) { it.todo.title }.then(byPosition)+ SortMode.TITLE -> compareBy<TodoRow, String>(String.CASE_INSENSITIVE_ORDER) { it.todo.title }+ .then(byPosition) } }
todo/src/main/java/com/vayunmathur/todo/domain/format/TodoCsv.kt
diff --git a/todo/src/main/java/com/vayunmathur/todo/domain/format/TodoCsv.kt b/todo/src/main/java/com/vayunmathur/todo/domain/format/TodoCsv.ktindex 49759f98da..2f48568c3e 100644--- a/todo/src/main/java/com/vayunmathur/todo/domain/format/TodoCsv.kt+++ b/todo/src/main/java/com/vayunmathur/todo/domain/format/TodoCsv.kt@@ -20,7 +20,8 @@ object TodoCsv { t.notes, if (t.done) "yes" else "no", t.dueAt?.let { DueDates.localDate(it, zone).toString() }.orEmpty(),- t.dueAt?.takeIf { !t.dueAllDay }?.let { DueDates.localTime(it, zone).toString().take(HHMM) }.orEmpty(),+ t.dueAt?.takeIf { !t.dueAllDay }?.let { DueDates.localTime(it, zone).toString().take(HHMM) }+ .orEmpty(), t.priority.takeIf { it > 0 }?.toString().orEmpty(), source.listName(t).orEmpty(), t.section.orEmpty(),@@ -36,63 +37,108 @@ object TodoCsv { return (listOf(HEADER) + rows).joinToString("\r\n") { row -> row.joinToString(",") { quote(it) } } + "\r\n" } + private val SPECIAL = setOf(',', '"', '\n', '\r')+ private fun quote(field: String): String =- if (field.any { it == ',' || it == '"' || it == '\n' || it == '\r' }) "\"" + field.replace("\"", "\"\"") + "\"" else field+ if (field.any { it in SPECIAL }) "\"" + field.replace("\"", "\"\"") + "\"" else field fun parse(text: String, zone: TimeZone): List<ImportedTask> { val rows = readRows(text) val header = rows.firstOrNull()?.map { it.trim().lowercase() } ?: return emptyList()- fun col(row: List<String>, name: String) = header.indexOf(name.lowercase()).takeIf { it >= 0 }?.let { row.getOrNull(it) }.orEmpty()- return rows.drop(1).filter { row -> row.any { it.isNotBlank() } }.map { row ->- val dueDate = col(row, "Due date").takeIf { it.isNotBlank() }?.let { runCatching { LocalDate.parse(it) }.getOrNull() }- val dueTime = col(row, "Due time").takeIf { it.isNotBlank() }?.let { runCatching { LocalTime.parse(it) }.getOrNull() }- ImportedTask(- title = col(row, "Title"),- notes = col(row, "Notes"),- done = col(row, "Done").lowercase() in setOf("yes", "true", "1", "x"),- dueAt = dueDate?.let { d -> if (dueTime != null) DueDates.at(d, dueTime, zone) else DueDates.startOfDay(d, zone) },- dueAllDay = dueTime == null,- priority = col(row, "Priority").toIntOrNull()?.takeIf { it in 1..Todo.PRIORITY_MAX } ?: 0,- listName = col(row, "List").ifBlank { null },- section = col(row, "Section").ifBlank { null },- tags = col(row, "Tags").split(' ', ',').map { it.trim().removePrefix("#") }.filter { it.isNotEmpty() },- recurrence = col(row, "Repeat").ifBlank { null },- startAt = date(col(row, "Start date"), zone),- createdAt = date(col(row, "Created"), zone),- completedAt = date(col(row, "Completed"), zone),- ref = col(row, "Id").ifBlank { null },- parentRef = col(row, "Parent id").ifBlank { null },- )- }+ return rows.drop(1).filter { row -> row.any { it.isNotBlank() } }.map { row -> toTask(Row(header, row), zone) } } + private class Row(private val header: List<String>, private val fields: List<String>) {+ operator fun get(name: String): String =+ header.indexOf(name.lowercase()).takeIf { it >= 0 }?.let { fields.getOrNull(it) }.orEmpty()+ }++ private fun toTask(row: Row, zone: TimeZone): ImportedTask {+ val dueDate = row["Due date"].parseOrNull { LocalDate.parse(it) }+ val dueTime = row["Due time"].parseOrNull { LocalTime.parse(it) }+ return ImportedTask(+ title = row["Title"],+ notes = row["Notes"],+ done = row["Done"].lowercase() in setOf("yes", "true", "1", "x"),+ dueAt = dueDate?.let { d -> dueTime?.let { DueDates.at(d, it, zone) } ?: DueDates.startOfDay(d, zone) },+ dueAllDay = dueTime == null,+ priority = row["Priority"].toIntOrNull()?.takeIf { it in 1..Todo.PRIORITY_MAX } ?: 0,+ listName = row["List"].ifBlank { null },+ section = row["Section"].ifBlank { null },+ tags = row["Tags"].split(' ', ',').map { it.trim().removePrefix("#") }.filter { it.isNotEmpty() },+ recurrence = row["Repeat"].ifBlank { null },+ startAt = date(row["Start date"], zone),+ createdAt = date(row["Created"], zone),+ completedAt = date(row["Completed"], zone),+ ref = row["Id"].ifBlank { null },+ parentRef = row["Parent id"].ifBlank { null },+ )+ }++ private fun <T> String.parseOrNull(parse: (String) -> T): T? =+ takeIf { it.isNotBlank() }?.let { runCatching { parse(it) }.getOrNull() }+ private fun date(raw: String, zone: TimeZone): Long? =- raw.takeIf { it.isNotBlank() }?.let { runCatching { DueDates.startOfDay(LocalDate.parse(it), zone) }.getOrNull() }+ raw.parseOrNull { DueDates.startOfDay(LocalDate.parse(it), zone) } /** Splits CSV into rows of fields, honouring quoted commas, quotes and newlines. */ internal fun readRows(text: String): List<List<String>> {- val rows = mutableListOf<List<String>>()- var row = mutableListOf<String>()- val field = StringBuilder()- var quoted = false+ val reader = RowReader() var i = 0- while (i < text.length) {- val c = text[i]- when {- quoted && c == '"' && text.getOrNull(i + 1) == '"' -> { field.append('"'); i++ }- c == '"' -> quoted = !quoted- !quoted && c == ',' -> { row += field.toString(); field.clear() }- !quoted && (c == '\n' || c == '\r') -> {- if (c == '\r' && text.getOrNull(i + 1) == '\n') i++- row += field.toString(); field.clear()- rows += row; row = mutableListOf()+ while (i < text.length) i += reader.step(text[i], text.getOrNull(i + 1))+ return reader.finish()+ }++ private class RowReader {+ private val rows = mutableListOf<List<String>>()+ private var row = mutableListOf<String>()+ private val field = StringBuilder()+ private var quoted = false++ /** Consumes [c] (peeking at [next]) and returns how many characters were used. */+ fun step(c: Char, next: Char?): Int {+ if (quoted) return quotedStep(c, next)+ when (c) {+ '"' -> quoted = true+ ',' -> endField()+ '\n' -> endRow()+ '\r' -> {+ endRow()+ if (next == '\n') return 2 } else -> field.append(c) }- i+++ return 1+ }++ private fun quotedStep(c: Char, next: Char?): Int {+ if (c != '"') {+ field.append(c)+ return 1+ }+ if (next == '"') {+ field.append('"')+ return 2+ }+ quoted = false+ return 1+ }++ private fun endField() {+ row += field.toString()+ field.clear()+ }++ private fun endRow() {+ endField()+ rows += row+ row = mutableListOf()+ }++ fun finish(): List<List<String>> {+ if (field.isNotEmpty() || row.isNotEmpty()) endRow()+ return rows }- if (field.isNotEmpty() || row.isNotEmpty()) { row += field.toString(); rows += row }- return rows } private const val HHMM = 5
todo/src/main/java/com/vayunmathur/todo/domain/format/TodoTxt.kt
diff --git a/todo/src/main/java/com/vayunmathur/todo/domain/format/TodoTxt.kt b/todo/src/main/java/com/vayunmathur/todo/domain/format/TodoTxt.ktindex 649ab287e8..2b9358f2a2 100644--- a/todo/src/main/java/com/vayunmathur/todo/domain/format/TodoTxt.kt+++ b/todo/src/main/java/com/vayunmathur/todo/domain/format/TodoTxt.kt@@ -20,8 +20,9 @@ object TodoTxt { private val REC = Regex("^(\\+?)(\\d+)([dwmy])$") private const val DAYS_PER_WEEK = 7 - fun export(source: ExportSource, zone: TimeZone): String =- source.todos.filter { !it.deleted && it.parentSyncId == null }.joinToString("\n") { line(it, source, zone) } + "\n"+ fun export(source: ExportSource, zone: TimeZone): String = source.todos+ .filter { !it.deleted && it.parentSyncId == null }+ .joinToString("\n") { line(it, source, zone) } + "\n" private fun line(todo: Todo, source: ExportSource, zone: TimeZone): String { val parts = mutableListOf<String>()@@ -77,7 +78,7 @@ object TodoTxt { } } - private fun parseBody(words: List<String>, zone: TimeZone): ImportedTask {+ private class Body { val title = mutableListOf<String>() val tags = mutableListOf<String>() var list: String? = null@@ -85,29 +86,47 @@ object TodoTxt { var start: Long? = null var recurrence: String? = null var priority = 0- for (w in words) {- val value = w.substringAfter(':', "")- when {- w.startsWith("+") && w.length > 1 && list == null -> list = w.drop(1).replace('_', ' ')- w.startsWith("@") && w.length > 1 -> tags += w.drop(1)- w.startsWith("due:") && value.matches(DATE) -> due = toMs(value, zone)- w.startsWith("t:") && value.matches(DATE) -> start = toMs(value, zone)- w.startsWith("rec:") -> recurrence = parseRec(value)- w.startsWith("pri:") && value.length == 1 && value[0] in 'A'..'D' -> priority = value[0] - 'A' + 1- else -> title += w- }- }+ }++ private fun parseBody(words: List<String>, zone: TimeZone): ImportedTask {+ val body = Body()+ for (w in words) if (!applyMarker(body, w, zone)) body.title += w return ImportedTask(- title = title.joinToString(" "),- dueAt = due,- priority = priority,- listName = list,- tags = tags,- recurrence = recurrence,- startAt = start,+ title = body.title.joinToString(" "),+ dueAt = body.due,+ priority = body.priority,+ listName = body.list,+ tags = body.tags,+ recurrence = body.recurrence,+ startAt = body.start, ) } + /** Applies `+project`, `@context` and `key:value` words; false for plain title words. */+ private fun applyMarker(body: Body, w: String, zone: TimeZone): Boolean = when {+ w.length > 1 && w[0] == '+' && body.list == null -> {+ body.list = w.drop(1).replace('_', ' ')+ true+ }+ w.length > 1 && w[0] == '@' -> {+ body.tags += w.drop(1)+ true+ }+ ':' in w -> applyKeyValue(body, w.substringBefore(':'), w.substringAfter(':'), zone)+ else -> false+ }++ private fun applyKeyValue(body: Body, key: String, value: String, zone: TimeZone): Boolean {+ when {+ key == "due" && value.matches(DATE) -> body.due = toMs(value, zone)+ key == "t" && value.matches(DATE) -> body.start = toMs(value, zone)+ key == "rec" -> body.recurrence = parseRec(value)+ key == "pri" && value.length == 1 && value[0] in 'A'..'D' -> body.priority = value[0] - 'A' + 1+ else -> return false+ }+ return true+ }+ private fun parseRec(value: String): String? { val (strict, n, unit) = REC.find(value)?.destructured ?: return null val count = n.toInt().coerceAtLeast(1)
todo/src/main/java/com/vayunmathur/todo/domain/format/VTodo.kt
diff --git a/todo/src/main/java/com/vayunmathur/todo/domain/format/VTodo.kt b/todo/src/main/java/com/vayunmathur/todo/domain/format/VTodo.ktindex 4337ba24db..02e7061f39 100644--- a/todo/src/main/java/com/vayunmathur/todo/domain/format/VTodo.kt+++ b/todo/src/main/java/com/vayunmathur/todo/domain/format/VTodo.kt@@ -4,6 +4,7 @@ import com.vayunmathur.todo.data.Todo import com.vayunmathur.todo.domain.DueDates import kotlinx.datetime.LocalDate import kotlinx.datetime.LocalDateTime+import kotlinx.datetime.LocalTime import kotlinx.datetime.TimeZone import kotlinx.datetime.toInstant import kotlinx.datetime.toLocalDateTime@@ -19,6 +20,7 @@ object VTodo { private const val PRODID = "-//Modern Apps//Todo//EN" private const val UID_HOST = "@com.vayunmathur.todo" private val ICAL_PRIORITY = mapOf(1 to 1, 2 to 3, 3 to 5, 4 to 7)+ private const val ICAL_LOWEST = 9 fun export(source: ExportSource): String { val out = StringBuilder()@@ -38,11 +40,11 @@ object VTodo { out.line("LAST-MODIFIED:${utc(t.updatedAt)}") out.line("SUMMARY:${escape(t.title)}") if (t.notes.isNotBlank()) out.line("DESCRIPTION:${escape(t.notes)}")+ val zone = TimeZone.currentSystemDefault() t.dueAt?.let { due ->- if (t.dueAllDay) out.line("DUE;VALUE=DATE:${basicDate(DueDates.localDate(due, TimeZone.currentSystemDefault()))}")- else out.line("DUE:${utc(due)}")+ if (t.dueAllDay) out.line("DUE;VALUE=DATE:${localDate(due, zone)}") else out.line("DUE:${utc(due)}") }- t.startAt?.let { out.line("DTSTART;VALUE=DATE:${basicDate(DueDates.localDate(it, TimeZone.currentSystemDefault()))}") }+ t.startAt?.let { out.line("DTSTART;VALUE=DATE:${localDate(it, zone)}") } out.line("STATUS:${if (t.done) "COMPLETED" else "NEEDS-ACTION"}") t.completedAt?.takeIf { t.done }?.let { out.line("COMPLETED:${utc(it)}") } ICAL_PRIORITY[t.priority]?.let { out.line("PRIORITY:$it") }@@ -71,36 +73,49 @@ object VTodo { private fun toTask(p: Map<String, Pair<Map<String, String>, String>>, zone: TimeZone): ImportedTask { fun v(name: String) = p[name]?.second- val due = p["DUE"]?.let { (params, value) -> parseDateTime(value, params, zone) }- val icalPriority = v("PRIORITY")?.toIntOrNull() ?: 0+ fun at(name: String) = p[name]?.let { (params, value) -> parseDateTime(value, params, zone) }+ val due = at("DUE") return ImportedTask( title = unescape(v("SUMMARY").orEmpty()), notes = unescape(v("DESCRIPTION").orEmpty()), done = v("STATUS").equals("COMPLETED", true) || v("COMPLETED") != null, dueAt = due?.first, dueAllDay = due?.second ?: true,- priority = ICAL_PRIORITY.entries.firstOrNull { icalPriority in 1..9 && icalPriority <= it.value }?.key- ?: if (icalPriority in 1..9) Todo.PRIORITY_MAX else 0,+ priority = fromIcalPriority(v("PRIORITY")?.toIntOrNull() ?: 0), listName = v("X-TODO-LIST")?.let { unescape(it) }, section = v("X-TODO-SECTION")?.let { unescape(it) }, tags = v("CATEGORIES")?.split(',')?.map { unescape(it).trim() }?.filter { it.isNotEmpty() }.orEmpty(), recurrence = v("X-TODO-RECURRENCE") ?: v("RRULE"),- startAt = p["DTSTART"]?.let { (params, value) -> parseDateTime(value, params, zone)?.first },- createdAt = v("CREATED")?.let { parseDateTime(it, emptyMap(), zone)?.first },- completedAt = v("COMPLETED")?.let { parseDateTime(it, emptyMap(), zone)?.first },+ startAt = at("DTSTART")?.first,+ createdAt = at("CREATED")?.first,+ completedAt = at("COMPLETED")?.first, ref = v("UID")?.substringBefore(UID_HOST), parentRef = v("RELATED-TO")?.substringBefore(UID_HOST), ) } + /** iCalendar 1 (highest) … 9 onto 1 … 4; 0 is undefined. */+ private fun fromIcalPriority(ical: Int): Int = when (ical) {+ 1 -> 1+ in 2..3 -> 2+ in 4..5 -> 3+ in 6..ICAL_LOWEST -> Todo.PRIORITY_MAX+ else -> 0+ }+ /** Epoch ms plus whether it is a date-only (all-day) value. */- private fun parseDateTime(value: String, params: Map<String, String>, zone: TimeZone): Pair<Long, Boolean>? = runCatching {+ private fun parseDateTime(+ value: String,+ params: Map<String, String>,+ zone: TimeZone,+ ): Pair<Long, Boolean>? = runCatching { if (params["VALUE"].equals("DATE", true) || value.length == BASIC_DATE_LEN) { DueDates.startOfDay(parseBasicDate(value), zone) to true } else { val date = parseBasicDate(value.take(BASIC_DATE_LEN)) val t = value.drop(BASIC_DATE_LEN + 1)- val ldt = LocalDateTime(date.year, date.month, date.day, t.take(2).toInt(), t.substring(2, 4).toInt(), t.substring(4, 6).toInt())+ val time = LocalTime(t.take(2).toInt(), t.substring(2, 4).toInt(), t.substring(4, 6).toInt())+ val ldt = LocalDateTime(date, time) val tz = when { value.endsWith("Z") -> TimeZone.UTC params["TZID"] != null -> runCatching { TimeZone.of(params.getValue("TZID")) }.getOrDefault(zone)@@ -113,7 +128,9 @@ object VTodo { private fun parseProperty(line: String): Triple<String, Map<String, String>, String>? { val colon = line.indexOf(':').takeIf { it > 0 } ?: return null val head = line.substring(0, colon).split(';')- val params = head.drop(1).mapNotNull { kv -> kv.split('=', limit = 2).takeIf { it.size == 2 }?.let { it[0].uppercase() to it[1] } }.toMap()+ val params = head.drop(1).mapNotNull { kv ->+ kv.split('=', limit = 2).takeIf { it.size == 2 }?.let { it[0].uppercase() to it[1] }+ }.toMap() return Triple(head[0].uppercase(), params, line.substring(colon + 1)) } @@ -154,7 +171,12 @@ object VTodo { } private fun escape(s: String) = s.replace("\\", "\\\\").replace(";", "\\;").replace(",", "\\,").replace("\n", "\\n")- private fun unescape(s: String) = s.replace("\\n", "\n").replace("\\N", "\n").replace("\\,", ",").replace("\\;", ";").replace("\\\\", "\\")+ private fun unescape(s: String) = s+ .replace("\\n", "\n")+ .replace("\\N", "\n")+ .replace("\\,", ",")+ .replace("\\;", ";")+ .replace("\\\\", "\\") private fun utc(ms: Long): String { val t = Instant.fromEpochMilliseconds(ms).toLocalDateTime(TimeZone.UTC)@@ -162,6 +184,7 @@ object VTodo { } private fun basicDate(d: LocalDate) = d.toString().replace("-", "")+ private fun localDate(ms: Long, zone: TimeZone) = basicDate(DueDates.localDate(ms, zone)) private fun parseBasicDate(s: String) = LocalDate.parse("${s.take(4)}-${s.substring(4, 6)}-${s.substring(6, 8)}") private fun Int.pad() = toString().padStart(2, '0') private const val BASIC_DATE_LEN = 8
todo/src/main/java/com/vayunmathur/todo/intents/CompleteTodoIntent.kt
diff --git a/todo/src/main/java/com/vayunmathur/todo/intents/CompleteTodoIntent.kt b/todo/src/main/java/com/vayunmathur/todo/intents/CompleteTodoIntent.ktindex 80db7839e3..157d6076cc 100644--- a/todo/src/main/java/com/vayunmathur/todo/intents/CompleteTodoIntent.kt+++ b/todo/src/main/java/com/vayunmathur/todo/intents/CompleteTodoIntent.kt@@ -6,7 +6,10 @@ import com.vayunmathur.todo.data.TodoRepository import kotlinx.serialization.builtins.serializer /** Assistant tool `complete_todo`: by sync id, or by exact (case-insensitive) title. */-class CompleteTodoIntent : AssistantIntent<CompleteTodoData, Boolean>(CompleteTodoData.serializer(), Boolean.serializer()) {+class CompleteTodoIntent : AssistantIntent<CompleteTodoData, Boolean>(+ CompleteTodoData.serializer(),+ Boolean.serializer(),+) { override suspend fun performCalculation(input: CompleteTodoData): Boolean { val repo = TodoRepository.get(this) val todo = input.id.takeIf { it.isNotBlank() }?.let { repo.getBySyncId(it) }?.takeIf { !it.deleted }
todo/src/main/java/com/vayunmathur/todo/intents/GetTodosIntent.kt
diff --git a/todo/src/main/java/com/vayunmathur/todo/intents/GetTodosIntent.kt b/todo/src/main/java/com/vayunmathur/todo/intents/GetTodosIntent.ktindex cfe97b301f..76127286cb 100644--- a/todo/src/main/java/com/vayunmathur/todo/intents/GetTodosIntent.kt+++ b/todo/src/main/java/com/vayunmathur/todo/intents/GetTodosIntent.kt@@ -1,5 +1,6 @@ package com.vayunmathur.todo.intents +import com.vayunmathur.todo.data.getLists import com.vayunmathur.library.intents.todo.GetTodosQuery import com.vayunmathur.library.intents.todo.TodoData import com.vayunmathur.library.util.AssistantIntent@@ -22,9 +23,9 @@ class GetTodosIntent : AssistantIntent<GetTodosQuery, List<TodoData>>( "all" -> TodoView.All else -> TodoView.Today }- val model = TodoQuery.build(- TodoQuery.Input(repo.getAll(), lists, view, now = System.currentTimeMillis(), zone = TimeZone.currentSystemDefault()),- )+ val now = System.currentTimeMillis()+ val zone = TimeZone.currentSystemDefault()+ val model = TodoQuery.build(TodoQuery.Input(repo.getAll(), lists, view, now = now, zone = zone)) return model.groups.flatMap { it.rows }.take(MAX_RESULTS).map { row -> val t = row.todo TodoData(t.syncId, t.title, t.notes, t.dueAt, t.done, t.priority, row.list?.name)
todo/src/main/java/com/vayunmathur/todo/intents/InsertTodoIntent.kt
diff --git a/todo/src/main/java/com/vayunmathur/todo/intents/InsertTodoIntent.kt b/todo/src/main/java/com/vayunmathur/todo/intents/InsertTodoIntent.ktindex c18fcfdba6..97250492e7 100644--- a/todo/src/main/java/com/vayunmathur/todo/intents/InsertTodoIntent.kt+++ b/todo/src/main/java/com/vayunmathur/todo/intents/InsertTodoIntent.kt@@ -1,5 +1,6 @@ package com.vayunmathur.todo.intents +import com.vayunmathur.todo.data.getLists import com.vayunmathur.library.intents.todo.InsertTodoData import com.vayunmathur.library.util.AssistantIntent import com.vayunmathur.todo.data.Todo
todo/src/main/java/com/vayunmathur/todo/notifications/NotificationChannels.kt
diff --git a/todo/src/main/java/com/vayunmathur/todo/notifications/NotificationChannels.kt b/todo/src/main/java/com/vayunmathur/todo/notifications/NotificationChannels.ktindex 89afe91436..b6fff740c4 100644--- a/todo/src/main/java/com/vayunmathur/todo/notifications/NotificationChannels.kt+++ b/todo/src/main/java/com/vayunmathur/todo/notifications/NotificationChannels.kt@@ -17,21 +17,23 @@ object NotificationChannels { private const val LIST_PREFIX = "todo_list_" const val INBOX = "todo_inbox" const val DIGEST = "todo_digest"+ private const val HIGH = NotificationManager.IMPORTANCE_HIGH+ private const val DEFAULT = NotificationManager.IMPORTANCE_DEFAULT fun forList(listSyncId: String?): String = listSyncId?.let { LIST_PREFIX + it } ?: INBOX fun ensureInbox(context: Context) =- context.ensureNotificationChannel(INBOX, context.getString(R.string.view_inbox), NotificationManager.IMPORTANCE_HIGH)+ context.ensureNotificationChannel(INBOX, context.getString(R.string.view_inbox), HIGH) fun ensureDigest(context: Context) =- context.ensureNotificationChannel(DIGEST, context.getString(R.string.digest_channel), NotificationManager.IMPORTANCE_DEFAULT)+ context.ensureNotificationChannel(DIGEST, context.getString(R.string.digest_channel), DEFAULT) /** Creates/renames a channel per list and removes channels of deleted lists. */ fun syncLists(context: Context, lists: List<TodoList>) { ensureInbox(context) val wanted = lists.associateBy { forList(it.syncId) } wanted.forEach { (id, list) ->- context.ensureNotificationChannel(id, list.name.ifBlank { context.getString(R.string.untitled) }, NotificationManager.IMPORTANCE_HIGH)+ context.ensureNotificationChannel(id, list.name.ifBlank { context.getString(R.string.untitled) }, HIGH) } context.getSystemService<NotificationManager>()?.notificationChannels.orEmpty() .map { it.id }
todo/src/main/java/com/vayunmathur/todo/notifications/ReminderActionReceiver.kt
diff --git a/todo/src/main/java/com/vayunmathur/todo/notifications/ReminderActionReceiver.kt b/todo/src/main/java/com/vayunmathur/todo/notifications/ReminderActionReceiver.ktindex 9e2c67d696..d63431bd7e 100644--- a/todo/src/main/java/com/vayunmathur/todo/notifications/ReminderActionReceiver.kt+++ b/todo/src/main/java/com/vayunmathur/todo/notifications/ReminderActionReceiver.kt@@ -24,7 +24,10 @@ class ReminderActionReceiver : BroadcastReceiver() { val todo = repo.getBySyncId(syncId) ?: return@launch when (intent.action) { ACTION_COMPLETE -> repo.setDone(todo, true)- ACTION_SNOOZE -> repo.upsert(todo.copy(reminderAt = snoozeUntil(intent.getIntExtra(EXTRA_SNOOZE, SNOOZE_HOUR))))+ ACTION_SNOOZE -> {+ val until = snoozeUntil(intent.getIntExtra(EXTRA_SNOOZE, SNOOZE_HOUR))+ repo.upsert(todo.copy(reminderAt = until))+ } } } finally { pending.finish()
todo/src/main/java/com/vayunmathur/todo/notifications/ReminderNotifications.kt
diff --git a/todo/src/main/java/com/vayunmathur/todo/notifications/ReminderNotifications.kt b/todo/src/main/java/com/vayunmathur/todo/notifications/ReminderNotifications.ktindex cf8853e0a8..1f6df768aa 100644--- a/todo/src/main/java/com/vayunmathur/todo/notifications/ReminderNotifications.kt+++ b/todo/src/main/java/com/vayunmathur/todo/notifications/ReminderNotifications.kt@@ -18,6 +18,10 @@ import kotlinx.datetime.TimeZone /** Builds and posts the reminder and digest notifications. */ object ReminderNotifications { private const val DIGEST_ID = 0x7D16E5+ private const val COMPLETE = ReminderActionReceiver.ACTION_COMPLETE+ private const val SNOOZE = ReminderActionReceiver.ACTION_SNOOZE+ private const val IN_HOUR = ReminderActionReceiver.SNOOZE_HOUR+ private const val TOMORROW = ReminderActionReceiver.SNOOZE_TOMORROW fun notificationId(syncId: String): Int = syncId.hashCode() @@ -39,9 +43,13 @@ object ReminderNotifications { .setCategory(NotificationCompat.CATEGORY_REMINDER) .setPriority(NotificationCompat.PRIORITY_HIGH) .setAutoCancel(true)- .addAction(0, context.getString(R.string.complete_action), action(context, todo.syncId, ReminderActionReceiver.ACTION_COMPLETE, 0))- .addAction(0, context.getString(R.string.snooze_hour), action(context, todo.syncId, ReminderActionReceiver.ACTION_SNOOZE, ReminderActionReceiver.SNOOZE_HOUR))- .addAction(0, context.getString(R.string.snooze_tomorrow), action(context, todo.syncId, ReminderActionReceiver.ACTION_SNOOZE, ReminderActionReceiver.SNOOZE_TOMORROW))+ .addAction(0, context.getString(R.string.complete_action), action(context, todo.syncId, COMPLETE, 0))+ .addAction(0, context.getString(R.string.snooze_hour), action(context, todo.syncId, SNOOZE, IN_HOUR))+ .addAction(+ 0,+ context.getString(R.string.snooze_tomorrow),+ action(context, todo.syncId, SNOOZE, TOMORROW),+ ) } } @@ -66,7 +74,8 @@ object ReminderNotifications { } } - fun cancel(context: Context, syncId: String) = NotificationManagerCompat.from(context).cancel(notificationId(syncId))+ fun cancel(context: Context, syncId: String) =+ NotificationManagerCompat.from(context).cancel(notificationId(syncId)) fun openTaskIntent(context: Context, syncId: String): Intent = Intent(context, MainActivity::class.java)@@ -87,6 +96,7 @@ object ReminderNotifications { val due = todo.dueAt ?: return null val zone = TimeZone.currentSystemDefault() val date = DateString.dateWeekdayNoYear(DueDates.localDate(due, zone))- return if (todo.dueAllDay) date else date + " " + DateString.time(DueDates.localTime(due, zone), is24Hour(context))+ if (todo.dueAllDay) return date+ return date + " " + DateString.time(DueDates.localTime(due, zone), is24Hour(context)) } }
todo/src/main/java/com/vayunmathur/todo/notifications/ReminderReceiver.kt
diff --git a/todo/src/main/java/com/vayunmathur/todo/notifications/ReminderReceiver.kt b/todo/src/main/java/com/vayunmathur/todo/notifications/ReminderReceiver.ktindex 7e20ed9677..3223505a79 100644--- a/todo/src/main/java/com/vayunmathur/todo/notifications/ReminderReceiver.kt+++ b/todo/src/main/java/com/vayunmathur/todo/notifications/ReminderReceiver.kt@@ -1,5 +1,6 @@ package com.vayunmathur.todo.notifications +import com.vayunmathur.todo.data.getListBySyncId import android.content.BroadcastReceiver import android.content.Context import android.content.Intent@@ -18,7 +19,8 @@ class ReminderReceiver : BroadcastReceiver() { repo.appScope.launch { try { when (intent.action) {- ReminderScheduler.ACTION_REMINDER -> remind(app, repo, intent.getStringExtra(ReminderScheduler.EXTRA_SYNC_ID))+ ReminderScheduler.ACTION_REMINDER ->+ remind(app, repo, intent.getStringExtra(ReminderScheduler.EXTRA_SYNC_ID)) DigestScheduler.ACTION_DIGEST -> digest(app, repo) } } finally {@@ -32,7 +34,8 @@ class ReminderReceiver : BroadcastReceiver() { val at = todo.reminderAt ?: return // A reminder that moved later since this alarm was set is re-armed by reconcile. if (todo.done || todo.deleted || at > System.currentTimeMillis() + EARLY_SLACK_MS) return- val channelName = todo.listSyncId?.let { repo.getListBySyncId(it)?.name } ?: context.getString(com.vayunmathur.todo.R.string.view_inbox)+ val channelName = todo.listSyncId?.let { repo.getListBySyncId(it)?.name }+ ?: context.getString(com.vayunmathur.todo.R.string.view_inbox) ReminderNotifications.postReminder(context, todo, channelName) } @@ -42,7 +45,7 @@ class ReminderReceiver : BroadcastReceiver() { val zone = TimeZone.currentSystemDefault() val open = repo.getAll().filter { !it.done && it.parentSyncId == null } val overdue = open.count { DueBuckets.isOverdue(it, now, zone) }- val today = open.count { it.dueAt != null && !DueBuckets.isOverdue(it, now, zone) && DueBuckets.isDueByToday(it, now, zone) }+ val today = open.count { DueBuckets.isDueByToday(it, now, zone) } - overdue if (today + overdue > 0) ReminderNotifications.postDigest(context, today, overdue) DigestScheduler.schedule(context, settings.digestEnabledNow(), settings.digestMinutesNow(), now + 1) }
todo/src/main/java/com/vayunmathur/todo/platform/TodoBackground.kt
diff --git a/todo/src/main/java/com/vayunmathur/todo/platform/TodoBackground.kt b/todo/src/main/java/com/vayunmathur/todo/platform/TodoBackground.ktindex 50b92897d5..c9549c6d9f 100644--- a/todo/src/main/java/com/vayunmathur/todo/platform/TodoBackground.kt+++ b/todo/src/main/java/com/vayunmathur/todo/platform/TodoBackground.kt@@ -37,7 +37,9 @@ object TodoBackground { val settings = TodoSettings(app) repo.appScope.launch { repo.todos- .map { todos -> todos.filter { it.reminderAt != null }.map { ReminderKey(it.syncId, it.reminderAt, it.done) } }+ .map { todos ->+ todos.filter { it.reminderAt != null }.map { ReminderKey(it.syncId, it.reminderAt, it.done) }+ } .distinctUntilChanged() .debounce(SETTLE_MS) .collect { ReminderScheduler.reconcile(app, repo.getAll()) }
todo/src/main/java/com/vayunmathur/todo/platform/TodoDataTransfer.kt
diff --git a/todo/src/main/java/com/vayunmathur/todo/platform/TodoDataTransfer.kt b/todo/src/main/java/com/vayunmathur/todo/platform/TodoDataTransfer.ktindex 2272f62d6b..d32fa2ef0d 100644--- a/todo/src/main/java/com/vayunmathur/todo/platform/TodoDataTransfer.kt+++ b/todo/src/main/java/com/vayunmathur/todo/platform/TodoDataTransfer.kt@@ -1,5 +1,8 @@ package com.vayunmathur.todo.platform +import com.vayunmathur.todo.data.getLists+import com.vayunmathur.todo.data.nextListPosition+import com.vayunmathur.todo.data.upsertList import android.content.Context import android.net.Uri import com.vayunmathur.todo.data.Todo@@ -31,12 +34,12 @@ class TodoDataTransfer(private val context: Context, private val repo: TodoRepos /** Reads a file and picks the format from its content. */ fun read(uri: Uri): List<ImportedTask> {- val text = context.contentResolver.openInputStream(uri)?.use { it.readBytes().toString(Charsets.UTF_8) }.orEmpty()- .removePrefix("\uFEFF")+ val bytes = context.contentResolver.openInputStream(uri)?.use { it.readBytes() } ?: ByteArray(0)+ val text = bytes.toString(Charsets.UTF_8).removePrefix("\uFEFF") val zone = TimeZone.currentSystemDefault() return when { text.contains("BEGIN:VCALENDAR", ignoreCase = true) -> VTodo.parse(text, zone)- text.lineSequence().firstOrNull()?.startsWith("Title,", ignoreCase = true) == true -> TodoCsv.parse(text, zone)+ text.lineSequence().firstOrNull().orEmpty().startsWith("Title,", true) -> TodoCsv.parse(text, zone) else -> TodoTxt.parse(text, zone) }.filter { it.title.isNotBlank() } }
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.ktindex 380d4aca05..1fbeabdac0 100644--- a/todo/src/main/java/com/vayunmathur/todo/platform/TodoEditor.kt+++ b/todo/src/main/java/com/vayunmathur/todo/platform/TodoEditor.kt@@ -83,7 +83,11 @@ class TodoEditor internal constructor( fun setDone(done: Boolean) { val before = _state.value ?: return val now = System.currentTimeMillis()- val after = if (done) Completion.complete(before, now, TimeZone.currentSystemDefault()) else Completion.uncomplete(before)+ val after = if (done) {+ Completion.complete(before, now, TimeZone.currentSystemDefault())+ } else {+ Completion.uncomplete(before)+ } update { after } if (Completion.rolledForward(before, after)) scope.launch { repository.reopenSubtasks(before.syncId) } }
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 c2b4b5ce97..b630865659 100644--- a/todo/src/main/java/com/vayunmathur/todo/platform/TodoViewModel.kt+++ b/todo/src/main/java/com/vayunmathur/todo/platform/TodoViewModel.kt@@ -1,5 +1,10 @@ package com.vayunmathur.todo.platform +import com.vayunmathur.todo.data.getLists+import com.vayunmathur.todo.data.nextListPosition+import com.vayunmathur.todo.data.upsertList+import com.vayunmathur.todo.data.upsertLists+import com.vayunmathur.todo.data.tombstoneList import android.app.Application import androidx.lifecycle.AndroidViewModel import androidx.lifecycle.SavedStateHandle@@ -66,10 +71,16 @@ class TodoViewModel( private val params = combine(view, searchQuery, sort, clock) { v, q, s, now -> Params(v, q, s, now) } - val model: StateFlow<Pair<TodoListModel, Long>> = combine(todos, lists, params, settings.showCompleted) { todos, lists, p, showDone ->- val built = TodoQuery.build(TodoQuery.Input(todos, lists, p.view, p.query, p.sort, p.now, TimeZone.currentSystemDefault()))- (if (showDone) built else built.copy(completed = emptyList())) to p.now- }.stateIn(viewModelScope, SharingStarted.WhileSubscribed(STOP_TIMEOUT_MS), TodoListModel() to System.currentTimeMillis())+ val model: StateFlow<Pair<TodoListModel, Long>> =+ combine(todos, lists, params, settings.showCompleted) { todos, lists, p, showDone ->+ val zone = TimeZone.currentSystemDefault()+ val built = TodoQuery.build(TodoQuery.Input(todos, lists, p.view, p.query, p.sort, p.now, zone))+ (if (showDone) built else built.copy(completed = emptyList())) to p.now+ }.stateIn(+ viewModelScope,+ SharingStarted.WhileSubscribed(STOP_TIMEOUT_MS),+ TodoListModel() to System.currentTimeMillis(),+ ) /** Open-task counts per view, for the drawer badges. */ val counts: StateFlow<Map<TodoView, Int>> = combine(todos, lists, clock) { todos, lists, now ->
todo/src/main/java/com/vayunmathur/todo/sync/CalendarMirror.kt
diff --git a/todo/src/main/java/com/vayunmathur/todo/sync/CalendarMirror.kt b/todo/src/main/java/com/vayunmathur/todo/sync/CalendarMirror.ktindex 47415fb436..790147a14b 100644--- a/todo/src/main/java/com/vayunmathur/todo/sync/CalendarMirror.kt+++ b/todo/src/main/java/com/vayunmathur/todo/sync/CalendarMirror.kt@@ -33,8 +33,10 @@ object CalendarMirror { private const val TIMED_LENGTH_MS = 30 * 60_000L private const val DAY_MS = 86_400_000L - fun hasPermission(context: Context): Boolean = listOf(Manifest.permission.READ_CALENDAR, Manifest.permission.WRITE_CALENDAR)- .all { ContextCompat.checkSelfPermission(context, it) == PackageManager.PERMISSION_GRANTED }+ private val PERMISSIONS = listOf(Manifest.permission.READ_CALENDAR, Manifest.permission.WRITE_CALENDAR)++ fun hasPermission(context: Context): Boolean =+ PERMISSIONS.all { ContextCompat.checkSelfPermission(context, it) == PackageManager.PERMISSION_GRANTED } // Broad catch: the calendar provider throws undocumented runtime exceptions, and a mirror // failure must never break the app.@@ -43,11 +45,14 @@ object CalendarMirror { if (!hasPermission(context)) return try { if (!enabled) {- findCalendar(context)?.let { context.contentResolver.delete(asSync(ContentUris.withAppendedId(Calendars.CONTENT_URI, it)), null, null) }+ findCalendar(context)?.let { id ->+ val uri = asSync(ContentUris.withAppendedId(Calendars.CONTENT_URI, id))+ context.contentResolver.delete(uri, null, null)+ } return } val calendarId = findCalendar(context) ?: createCalendar(context) ?: return- write(context, calendarId, todos.filter { !it.done && !it.deleted && it.dueAt != null && it.parentSyncId == null })+ write(context, calendarId, todos.filter { it.isMirrored() }) } catch (e: Exception) { Log.error(TAG, "reconcile failed", e) }@@ -70,13 +75,14 @@ object CalendarMirror { val fingerprint = values.getAsString(Events.SYNC_DATA1) val current = existing.remove(todo.syncId) when {- current == null -> ops += ContentProviderOperation.newInsert(asSync(Events.CONTENT_URI)).withValues(values).build()- current.second != fingerprint -> ops += ContentProviderOperation- .newUpdate(asSync(ContentUris.withAppendedId(Events.CONTENT_URI, current.first))).withValues(values).build()+ current == null -> ops += ContentProviderOperation.newInsert(asSync(Events.CONTENT_URI))+ .withValues(values).build()+ current.second != fingerprint -> ops += ContentProviderOperation.newUpdate(eventUri(current.first))+ .withValues(values).build() } } existing.values.forEach { (id, _) ->- ops += ContentProviderOperation.newDelete(asSync(ContentUris.withAppendedId(Events.CONTENT_URI, id))).build()+ ops += ContentProviderOperation.newDelete(eventUri(id)).build() } if (ops.isNotEmpty()) context.contentResolver.applyBatch(android.provider.CalendarContract.AUTHORITY, ops) }@@ -103,7 +109,9 @@ object CalendarMirror { putNull(Events.RRULE) putNull(Events.DURATION) }- put(Events.SYNC_DATA1, listOf(todo.title, todo.notes, start, todo.dueAllDay, rrule, zone.id).joinToString("\u0000").hashCode().toString())+ val fingerprint = listOf(todo.title, todo.notes, start, todo.dueAllDay, rrule, zone.id)+ .joinToString("\u0000")+ put(Events.SYNC_DATA1, fingerprint.hashCode().toString()) } } @@ -130,6 +138,10 @@ object CalendarMirror { return context.contentResolver.insert(asSync(Calendars.CONTENT_URI), values)?.let { ContentUris.parseId(it) } } + private fun Todo.isMirrored() = !done && !deleted && dueAt != null && parentSyncId == null++ private fun eventUri(id: Long) = asSync(ContentUris.withAppendedId(Events.CONTENT_URI, id))+ private fun asSync(uri: Uri): Uri = uri.buildUpon() .appendQueryParameter(android.provider.CalendarContract.CALLER_IS_SYNCADAPTER, "true") .appendQueryParameter(Calendars.ACCOUNT_NAME, ACCOUNT)
todo/src/main/java/com/vayunmathur/todo/sync/RelayTodoProvider.kt
diff --git a/todo/src/main/java/com/vayunmathur/todo/sync/RelayTodoProvider.kt b/todo/src/main/java/com/vayunmathur/todo/sync/RelayTodoProvider.ktindex d77affeda0..c871ced8e4 100644--- a/todo/src/main/java/com/vayunmathur/todo/sync/RelayTodoProvider.kt+++ b/todo/src/main/java/com/vayunmathur/todo/sync/RelayTodoProvider.kt@@ -1,5 +1,20 @@ package com.vayunmathur.todo.sync +import com.vayunmathur.todo.data.getListBySyncId+import com.vayunmathur.todo.data.getUpdatedSince+import com.vayunmathur.todo.data.upsertRaw+import com.vayunmathur.todo.data.tombstoneBySyncId+import com.vayunmathur.todo.data.purge+import com.vayunmathur.todo.data.getListsUpdatedSince+import com.vayunmathur.todo.data.upsertListRaw+import com.vayunmathur.todo.data.tombstoneListBySyncId+import com.vayunmathur.todo.data.purgeLists+import com.vayunmathur.todo.data.getTodoSnapshots+import com.vayunmathur.todo.data.getListSnapshots+import com.vayunmathur.todo.data.upsertSnapshot+import com.vayunmathur.todo.data.deleteSnapshotBySyncId+import com.vayunmathur.todo.data.deleteTodoSnapshots+import com.vayunmathur.todo.data.deleteListSnapshots import android.content.ContentProvider import android.content.ContentProviderOperation import android.content.ContentProviderResult@@ -142,7 +157,9 @@ class RelayTodoProvider : ContentProvider() { override fun insert(uri: Uri, values: ContentValues?): Uri? { val v = values ?: return null- return guarded("insert", uri, null) { repo -> handleUpsert(repo, uri, v)?.let { Uri.withAppendedPath(uri, it) } }+ return guarded("insert", uri, null) { repo ->+ handleUpsert(repo, uri, v)?.let { Uri.withAppendedPath(uri, it) }+ } } override fun bulkInsert(uri: Uri, values: Array<out ContentValues>): Int =@@ -207,7 +224,8 @@ class RelayTodoProvider : ContentProvider() { selection: String?, selectionArgs: Array<out String>?, ): Int {- val syncId = selectionArgs?.firstOrNull()?.takeIf { selection != null || uriMatcher.match(uri) == CODE_SNAPSHOTS }+ val bySelection = selection != null || uriMatcher.match(uri) == CODE_SNAPSHOTS+ val syncId = selectionArgs?.firstOrNull()?.takeIf { bySelection } return when (uriMatcher.match(uri)) { CODE_TODOS_PURGE -> purgeTodos(repo) CODE_LISTS_PURGE -> purgeLists(repo)
todo/src/main/java/com/vayunmathur/todo/ui/BulkActionBar.kt
diff --git a/todo/src/main/java/com/vayunmathur/todo/ui/BulkActionBar.kt b/todo/src/main/java/com/vayunmathur/todo/ui/BulkActionBar.ktindex def6a720b8..8278f4a612 100644--- a/todo/src/main/java/com/vayunmathur/todo/ui/BulkActionBar.kt+++ b/todo/src/main/java/com/vayunmathur/todo/ui/BulkActionBar.kt@@ -64,7 +64,7 @@ fun BulkActionBar(count: Int, lists: List<TodoList>, actions: BulkActions) { } item(R.string.pick_date) { pickDate = true } HorizontalDivider()- (1..Todo.PRIORITY_MAX).forEach { p ->+ for (p in 1..Todo.PRIORITY_MAX) { DropdownMenuItem(text = { Text(stringResource(R.string.priority_n, p)) }, onClick = { menu = false actions.setPriority(p)
todo/src/main/java/com/vayunmathur/todo/ui/EditorChips.kt
diff --git a/todo/src/main/java/com/vayunmathur/todo/ui/EditorChips.kt b/todo/src/main/java/com/vayunmathur/todo/ui/EditorChips.ktindex af3bf15fa0..daeda74256 100644--- a/todo/src/main/java/com/vayunmathur/todo/ui/EditorChips.kt+++ b/todo/src/main/java/com/vayunmathur/todo/ui/EditorChips.kt@@ -107,7 +107,7 @@ private fun PriorityChip(priority: Int, onSet: (Int) -> Unit) { leadingIcon = { IconFlag(Modifier.size(18.dp), tint = priorityColor(priority) ?: Color.Unspecified) }, ) DropdownMenu(expanded = open, onDismissRequest = { open = false }) {- (1..Todo.PRIORITY_MAX).forEach { p ->+ for (p in 1..Todo.PRIORITY_MAX) { DropdownMenuItem( text = { Text(stringResource(R.string.priority_n, p)) }, leadingIcon = { IconFlag(tint = priorityColor(p) ?: Color.Unspecified) },
todo/src/main/java/com/vayunmathur/todo/ui/TodoDetailScreen.kt
diff --git a/todo/src/main/java/com/vayunmathur/todo/ui/TodoDetailScreen.kt b/todo/src/main/java/com/vayunmathur/todo/ui/TodoDetailScreen.ktindex 25a706fdc4..3450b5383f 100644--- a/todo/src/main/java/com/vayunmathur/todo/ui/TodoDetailScreen.kt+++ b/todo/src/main/java/com/vayunmathur/todo/ui/TodoDetailScreen.kt@@ -36,6 +36,7 @@ import com.vayunmathur.library.ui.Text import com.vayunmathur.library.ui.TextField import com.vayunmathur.library.ui.TextFieldDefaults import com.vayunmathur.library.ui.appBarScrollBehavior+import com.vayunmathur.library.util.sharedContainer import com.vayunmathur.todo.R import com.vayunmathur.todo.platform.TodoActions import com.vayunmathur.todo.platform.TodoUiState@@ -94,7 +95,8 @@ fun TodoDetailScreen(state: TodoUiState, actions: TodoActions) { TextField( value = todo.title, onValueChange = { title -> actions.update { it.copy(title = title) } },- modifier = Modifier.weight(1f).focusRequester(titleFocus),+ modifier = Modifier.weight(1f).focusRequester(titleFocus)+ .then(if (todo.id != 0L) Modifier.sharedContainer(sharedTitleKey(todo.id)) else Modifier), placeholder = { Text(stringResource(R.string.todo_title)) }, textStyle = MaterialTheme.typography.headlineSmall.copy( textDecoration = if (todo.done) TextDecoration.LineThrough else null,
todo/src/main/java/com/vayunmathur/todo/ui/TodoRowItem.kt
diff --git a/todo/src/main/java/com/vayunmathur/todo/ui/TodoRowItem.kt b/todo/src/main/java/com/vayunmathur/todo/ui/TodoRowItem.ktindex 9ee68564cd..20e71d23c8 100644--- a/todo/src/main/java/com/vayunmathur/todo/ui/TodoRowItem.kt+++ b/todo/src/main/java/com/vayunmathur/todo/ui/TodoRowItem.kt@@ -21,6 +21,7 @@ import com.vayunmathur.library.ui.ListItem import com.vayunmathur.library.ui.ListItemDefaults import com.vayunmathur.library.ui.MaterialTheme import com.vayunmathur.library.ui.Text+import com.vayunmathur.library.util.sharedText import com.vayunmathur.todo.R import com.vayunmathur.todo.domain.TodoRow @@ -96,11 +97,14 @@ fun TodoRowItem( query = query, maxLines = 2, textDecoration = if (done) TextDecoration.LineThrough else null,- modifier = Modifier.alpha(if (done) DONE_ALPHA else 1f),+ modifier = Modifier.sharedText(sharedTitleKey(todo.id)).alpha(if (done) DONE_ALPHA else 1f), ) } } +/** Shared-element key tying a row's title to the editor's title field. */+internal fun sharedTitleKey(id: Long) = "todo-title-$id"+ private const val DONE_ALPHA = 0.6f private const val BLOCKED_ALPHA = 0.55f
todo/src/main/java/com/vayunmathur/todo/widget/QuickAddWidget.kt
diff --git a/todo/src/main/java/com/vayunmathur/todo/widget/QuickAddWidget.kt b/todo/src/main/java/com/vayunmathur/todo/widget/QuickAddWidget.ktindex a68f662782..3b23b0d77f 100644--- a/todo/src/main/java/com/vayunmathur/todo/widget/QuickAddWidget.kt+++ b/todo/src/main/java/com/vayunmathur/todo/widget/QuickAddWidget.kt@@ -39,7 +39,10 @@ class QuickAddWidget : MaWidget<Unit>() { ) { Image(ImageProvider(R.drawable.ic_add), contentDescription = null) Spacer(GlanceModifier.width(8.dp))- Text(context.getString(R.string.add_task_hint), style = TextStyle(color = GlanceTheme.colors.onPrimaryContainer))+ Text(+ context.getString(R.string.add_task_hint),+ style = TextStyle(color = GlanceTheme.colors.onPrimaryContainer),+ ) } } }
todo/src/main/java/com/vayunmathur/todo/widget/TodayWidget.kt
diff --git a/todo/src/main/java/com/vayunmathur/todo/widget/TodayWidget.kt b/todo/src/main/java/com/vayunmathur/todo/widget/TodayWidget.ktindex 889d3b51e8..468ce118c0 100644--- a/todo/src/main/java/com/vayunmathur/todo/widget/TodayWidget.kt+++ b/todo/src/main/java/com/vayunmathur/todo/widget/TodayWidget.kt@@ -1,5 +1,6 @@ package com.vayunmathur.todo.widget +import com.vayunmathur.todo.data.getLists import android.annotation.SuppressLint import android.content.Context import android.content.Intent@@ -53,7 +54,8 @@ class TodayWidget : MaWidget<TodayWidgetData>() { val repo = TodoRepository.get(context) val now = System.currentTimeMillis() val zone = TimeZone.currentSystemDefault()- val model = TodoQuery.build(TodoQuery.Input(repo.getAll(), repo.getLists(), TodoView.Today, now = now, zone = zone))+ val input = TodoQuery.Input(repo.getAll(), repo.getLists(), TodoView.Today, now = now, zone = zone)+ val model = TodoQuery.build(input) val rows = model.groups.flatMap { it.rows }.map { row -> TodayWidgetRow(row.todo.syncId, row.todo.title, DueBuckets.isOverdue(row.todo, now, zone)) }@@ -97,31 +99,46 @@ private fun TodayContent(data: TodayWidgetData) { horizontalPadding = 0.dp, ) { if (data.rows.isEmpty()) {- Box(GlanceModifier.fillMaxSize().background(GlanceTheme.colors.surface), contentAlignment = Alignment.Center) {- Text(context.getString(R.string.all_done), style = TextStyle(color = GlanceTheme.colors.onSurfaceVariant))+ Box(+ GlanceModifier.fillMaxSize().background(GlanceTheme.colors.surface),+ contentAlignment = Alignment.Center,+ ) {+ Text(+ context.getString(R.string.all_done),+ style = TextStyle(color = GlanceTheme.colors.onSurfaceVariant),+ ) } return@Scaffold } LazyColumn(GlanceModifier.fillMaxSize().background(GlanceTheme.colors.surface)) {- items(data.rows, itemId = { it.syncId.hashCode().toLong() }) { row ->- Row(GlanceModifier.fillMaxWidth().padding(horizontal = 8.dp), verticalAlignment = Alignment.CenterVertically) {- CheckBox(- checked = false,- onCheckedChange = actionRunCallback<CompleteTaskAction>(actionParametersOf(CompleteTaskAction.SYNC_ID to row.syncId)),- )- Column(- GlanceModifier.defaultWeight().clickable(- actionStartActivity(ReminderNotifications.openTaskIntent(context, row.syncId)),- ),- ) {- Text(- row.title.ifBlank { context.getString(R.string.untitled) },- maxLines = 2,- style = TextStyle(color = if (row.overdue) GlanceTheme.colors.error else GlanceTheme.colors.onSurface),- )- }- }- }+ items(data.rows, itemId = { it.syncId.hashCode().toLong() }) { row -> TodayRow(row) }+ }+ }+}++@Composable+private fun TodayRow(row: TodayWidgetRow) {+ val context = LocalContext.current+ Row(+ GlanceModifier.fillMaxWidth().padding(horizontal = 8.dp),+ verticalAlignment = Alignment.CenterVertically,+ ) {+ CheckBox(+ checked = false,+ onCheckedChange = actionRunCallback<CompleteTaskAction>(+ actionParametersOf(CompleteTaskAction.SYNC_ID to row.syncId),+ ),+ )+ Column(+ GlanceModifier.defaultWeight().clickable(+ actionStartActivity(ReminderNotifications.openTaskIntent(context, row.syncId)),+ ),+ ) {+ Text(+ row.title.ifBlank { context.getString(R.string.untitled) },+ maxLines = 2,+ style = TextStyle(color = if (row.overdue) GlanceTheme.colors.error else GlanceTheme.colors.onSurface),+ ) } } }
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 5d1b65dec9..e72b5c33d8 100644--- a/todo/src/screenshotTest/kotlin/com/vayunmathur/todo/ui/MetadataPreviews.kt+++ b/todo/src/screenshotTest/kotlin/com/vayunmathur/todo/ui/MetadataPreviews.kt@@ -1,23 +1,45 @@ package com.vayunmathur.todo.ui +import androidx.compose.foundation.layout.Row+import androidx.compose.foundation.layout.fillMaxHeight+import androidx.compose.foundation.layout.width import androidx.compose.runtime.Composable+import androidx.compose.ui.Modifier import androidx.compose.ui.tooling.preview.Preview+import androidx.compose.ui.unit.dp import com.android.tools.screenshot.PreviewTest import com.vayunmathur.library.ui.DynamicTheme+import com.vayunmathur.library.ui.Surface import com.vayunmathur.todo.data.Todo+import com.vayunmathur.todo.data.TodoList+import com.vayunmathur.todo.domain.DueDates+import com.vayunmathur.todo.domain.Recurrence+import com.vayunmathur.todo.domain.TodoQuery+import com.vayunmathur.todo.domain.TodoView import com.vayunmathur.todo.platform.TodoActions import com.vayunmathur.todo.platform.TodoListActions import com.vayunmathur.todo.platform.TodoListUiState import com.vayunmathur.todo.platform.TodoUiState-import com.vayunmathur.todo.domain.TodoQuery-import com.vayunmathur.todo.domain.TodoView+import kotlinx.datetime.DateTimeUnit+import kotlinx.datetime.LocalDate+import kotlinx.datetime.plus+import kotlinx.datetime.LocalTime import kotlinx.datetime.TimeZone /** Phone-shaped, roughly 1080x2340 at xxhdpi - comfortably above the F-Droid minimum. */ private const val PHONE = "spec:width=411dp,height=891dp,dpi=420"+private const val TABLET = "spec:width=1280dp,height=800dp,dpi=240" -/** 2026-10-14 09:00 UTC, so relative due labels render the same on every run. */-private const val NOW = 1_791_968_400_000L+/**+ * 2026-10-14 09:00 in the rendering machine's zone: the labels are computed in the system zone,+ * so the samples must be too for "Today" to read as today on every run.+ */+private val ZONE = TimeZone.currentSystemDefault()+private val NOW = DueDates.at(LocalDate(2026, 10, 14), LocalTime(9, 0), ZONE)++private val TODAY = LocalDate(2026, 10, 14)+private fun day(offset: Int) = DueDates.startOfDay(TODAY.plus(offset, DateTimeUnit.DAY), ZONE)+private fun at(offset: Int, h: Int, m: Int = 0) = DueDates.at(TODAY.plus(offset, DateTimeUnit.DAY), LocalTime(h, m), ZONE) /** * Store listing images for `:todo`. See `common-conventions-preview-metadata`.@@ -30,52 +52,62 @@ private const val NOW = 1_791_968_400_000L * makes the images reproducible from a clean checkout. */ class MetadataPreviews {+ private val work = TodoList(id = 1, syncId = "work", name = "Work", color = 0xFF1E88E5.toInt(), icon = "work")+ private val home = TodoList(id = 2, syncId = "home", name = "Home", color = 0xFF43A047.toInt(), icon = "home")+ private val lists = listOf(work, home)+ private val samples = listOf(+ Todo(id = 1, syncId = "a", title = "Renew passport", dueAt = day(-2), priority = 1, position = 1.0, createdAt = day(-9)), Todo(- id = 1,- title = "Buy oat milk and sourdough",- done = false,- position = 0.0,- ),- Todo(- id = 2,- title = "Call Sam about Saturday",- done = true,- position = 1.0,+ id = 2, syncId = "b", title = "Finish the quarterly report", dueAt = at(0, 15), dueAllDay = false,+ priority = 2, listSyncId = "work", reminderAt = at(0, 14), position = 2.0, createdAt = day(-3), ), Todo(- id = 3,- title = "Finish the book for Sunday",- done = false,- position = 2.0,- dueAt = 1_791_907_200_000L,+ id = 3, syncId = "c", title = "Water the plants", dueAt = day(0), recurrence = Recurrence.Daily(3).serialize(),+ listSyncId = "home", position = 3.0, createdAt = day(-30), ), Todo(- id = 4,- title = "Water the plants",- done = false,- position = 3.0,- dueAt = 1_791_820_800_000L,+ id = 4, syncId = "d", title = "Buy oat milk and sourdough", dueAt = day(0), tags = listOf("errands"),+ notes = "The bakery on 5th closes at 6", position = 4.0, createdAt = day(-1), ),+ Todo(id = 5, syncId = "e", title = "Book dentist", dueAt = day(1), listSyncId = "home", position = 5.0, createdAt = day(-1)),+ Todo(id = 6, syncId = "f", title = "Call Sam about Saturday", done = true, completedAt = NOW - 3_600_000L, dueAt = day(0), position = 6.0),+ Todo(id = 7, syncId = "g", title = "Outline", parentSyncId = "b", done = true, position = 7.0),+ Todo(id = 8, syncId = "h", title = "Charts", parentSyncId = "b", position = 8.0),+ Todo(id = 9, syncId = "i", title = "Plan the team offsite", dueAt = day(6), listSyncId = "work", priority = 3, position = 9.0), ) - private fun listState(query: String = "") = TodoListUiState(- model = TodoQuery.build(- TodoQuery.Input(samples, emptyList(), TodoView.Inbox, query, now = NOW, zone = TimeZone.UTC),- ),+ private fun listState(view: TodoView = TodoView.Today, query: String = "") = TodoListUiState(+ view = view,+ model = TodoQuery.build(TodoQuery.Input(samples, lists, view, query, now = NOW, zone = ZONE)),+ lists = lists, searchQuery = query, now = NOW, ) + private val editorState = TodoUiState(+ todo = samples[1].copy(+ notes = "Numbers are in the shared folder\n- revenue by region\n- **headcount** plan",+ updatedAt = NOW - 3_600_000L,+ ),+ subtasks = samples.filter { it.parentSyncId == "b" },+ lists = lists,+ now = NOW,+ )++ private val drawerState = DrawerUiState(+ view = TodoView.Today,+ counts = TodoQuery.counts(samples, lists, NOW, ZONE),+ lists = lists,+ tags = listOf("errands"),+ )+ @PreviewTest- @Preview(name = "1-todos", device = PHONE, group = "phone", showSystemUi = true)+ @Preview(name = "1-today", device = PHONE, group = "phone", showSystemUi = true) @Composable- fun Preview1Todos() {+ fun Preview1Today() { DynamicTheme(darkTheme = true) {- TodoListScreen(- state = listState(),- actions = TodoListActions.Noop,- )+ TodoListScreen(state = listState(), actions = TodoListActions.Noop) } } @@ -84,39 +116,49 @@ class MetadataPreviews { @Composable fun Preview2Editor() { DynamicTheme(darkTheme = true) {- TodoDetailScreen(- state = TodoUiState(- todo = Todo(- title = "Finish the book for Sunday",- notes = "Chapters 8-10\n- bring notes to book club\n- https://example.org/reading-guide",- dueAt = 1_791_907_200_000L,- priority = 2,- tags = listOf("reading"),- recurrence = "FREQ=WEEKLY",- createdAt = NOW - 86_400_000L,- updatedAt = NOW,- ),- subtasks = listOf(- Todo(id = 10, title = "Chapter 8", done = true),- Todo(id = 11, title = "Chapter 9"),- Todo(id = 12, title = "Chapter 10"),- ),- now = NOW,- ),- actions = TodoActions.Noop,- )+ TodoDetailScreen(state = editorState, actions = TodoActions.Noop)+ }+ }++ @PreviewTest+ @Preview(name = "3-views", device = PHONE, group = "phone", showSystemUi = true)+ @Composable+ fun Preview3Views() {+ DynamicTheme(darkTheme = true) {+ Surface { ViewDrawerContent(drawerState, object : DrawerActions {}) }+ }+ }++ @PreviewTest+ @Preview(name = "4-list", device = PHONE, group = "phone", showSystemUi = true)+ @Composable+ fun Preview4List() {+ DynamicTheme(darkTheme = true) {+ TodoListScreen(state = listState(TodoView.All, query = ""), actions = TodoListActions.Noop)+ }+ }++ @PreviewTest+ @Preview(name = "5-search", device = PHONE, group = "phone", showSystemUi = true)+ @Composable+ fun Preview5Search() {+ DynamicTheme(darkTheme = true) {+ TodoListScreen(state = listState(query = "the"), actions = TodoListActions.Noop) } } @PreviewTest- @Preview(name = "3-search", device = PHONE, group = "phone", showSystemUi = true)+ @Preview(name = "1-tablet", device = TABLET, group = "tablet", showSystemUi = true) @Composable- fun Preview3Search() {+ fun Preview6Tablet() { DynamicTheme(darkTheme = true) {- TodoListScreen(- state = listState(query = "book"),- actions = TodoListActions.Noop,- )+ Row {+ Surface(Modifier.width(280.dp).fillMaxHeight()) { ViewDrawerContent(drawerState, object : DrawerActions {}) }+ Surface(Modifier.width(500.dp).fillMaxHeight()) {+ TodoListScreen(state = listState().copy(showAddButton = false), actions = TodoListActions.Noop, showMenu = false)+ }+ Surface(Modifier.fillMaxHeight()) { TodoDetailScreen(state = editorState, actions = TodoActions.Noop) }+ } } } }