From 455995872442cf610fa046b77e9ba53f5efabcf4 Mon Sep 17 00:00:00 2001 From: Evsyukov Denis Date: Mon, 30 Nov 2026 11:50:06 +0300 Subject: [PATCH] feat(tasks): sync sorting in lists and Today Expose all five sort modes in the clients. Order tasks in the core and keep the manual arrangement of each Today group in its own register. Use the effective due date for Overdue across the native and web views. Cover sort modes, manual moves, undo, and sync in the store and clients. Document the Today behavior and its CalDAV metadata. --- README.md | 2 + .../main/java/org/evsyukov/lists/ui/Editor.kt | 2 +- .../java/org/evsyukov/lists/ui/MainScreen.kt | 58 ++++- .../org/evsyukov/lists/ui/MainViewModel.kt | 47 +++- .../java/org/evsyukov/lists/ui/Reorder.kt | 32 ++- .../app/src/main/res/values-ru/strings.xml | 1 + .../src/main/res/values-zh-rCN/strings.xml | 1 + android/app/src/main/res/values/strings.xml | 1 + .../java/org/evsyukov/lists/ui/ReorderTest.kt | 2 + apple/App/AppModel.swift | 54 ++++- apple/App/MainWindow.swift | 35 ++- apple/App/TaskTable.swift | 59 ++++- apple/Shared/Reorder.swift | 5 + apple/Shared/en.lproj/Localizable.strings | 2 + apple/Shared/ru.lproj/Localizable.strings | 1 + .../Shared/zh-Hans.lproj/Localizable.strings | 1 + apple/Tests/SharedTests.swift | 6 + core/Cargo.lock | 78 ++++++ core/Cargo.toml | 3 +- core/src/model.rs | 30 ++- core/src/store.rs | 227 ++++++++++++++---- core/tests/caldav.rs | 26 ++ core/tests/import.rs | 2 +- core/tests/store.rs | 122 ++++++++++ core/tests/sync.rs | 30 +++ docs/architecture.md | 2 + docs/specs/caldav.md | 1 + docs/specs/product.md | 10 +- docs/specs/sync.md | 3 +- docs/usage.md | 6 +- web/Cargo.lock | 78 ++++++ web/src/index.html | 41 +++- web/src/lib.rs | 69 ++++-- web/tests/api.rs | 66 +++++ 34 files changed, 979 insertions(+), 124 deletions(-) diff --git a/README.md b/README.md index 0373042a..17322390 100644 --- a/README.md +++ b/README.md @@ -7,6 +7,8 @@ A local-first to-do list with native apps for macOS and Android, a self-hosted w Lists covers the part of 2Do that a single person uses every day. A task has a list, dates, a priority, tags, a repeat, a reminder, notes in Markdown, attachments and subtasks, which are plain lines with a title; tasks group into projects, and saved filters cut across the lists. A task is closed as done or as "won't do", and stays in view for a few seconds before it leaves. Attachments open inside the app, can be saved or shared, and work in the web interface. The apps for macOS and Android show the calendar events of the day in Today, remind with a sound you choose and keep automatic local backups. Everything works offline; edits made on two devices to different fields of the same task are both kept. +Inbox, each list and Today have their own sort mode. The mode and manual order sync across devices. + The interface is in English with Russian and Chinese (Simplified) localizations and follows the system language. ## Screenshots diff --git a/android/app/src/main/java/org/evsyukov/lists/ui/Editor.kt b/android/app/src/main/java/org/evsyukov/lists/ui/Editor.kt index c7732d88..ea5e5505 100644 --- a/android/app/src/main/java/org/evsyukov/lists/ui/Editor.kt +++ b/android/app/src/main/java/org/evsyukov/lists/ui/Editor.kt @@ -1055,7 +1055,7 @@ fun ListDialog(list: TaskList?, model: MainViewModel, onDismiss: () -> Unit) { var dueToday by remember { mutableStateOf(list?.defaultDueToday ?: false) } var archived by remember { mutableStateOf(list?.archived ?: false) } var confirmDelete by remember { mutableStateOf(false) } - val sorts = listOf(SortMode.MANUAL to str(R.string.sort_manual), SortMode.DUE to str(R.string.sort_due), SortMode.PRIORITY to str(R.string.sort_priority), SortMode.TITLE to str(R.string.sort_title)) + val sorts = listOf(SortMode.MANUAL to str(R.string.sort_manual), SortMode.DUE to str(R.string.sort_due), SortMode.START to str(R.string.sort_start), SortMode.PRIORITY to str(R.string.sort_priority), SortMode.TITLE to str(R.string.sort_title)) FormDialog( title = if (list == null) str(R.string.new_list) else list.displayName(), diff --git a/android/app/src/main/java/org/evsyukov/lists/ui/MainScreen.kt b/android/app/src/main/java/org/evsyukov/lists/ui/MainScreen.kt index 156785a9..2be3a3da 100644 --- a/android/app/src/main/java/org/evsyukov/lists/ui/MainScreen.kt +++ b/android/app/src/main/java/org/evsyukov/lists/ui/MainScreen.kt @@ -78,6 +78,7 @@ import androidx.compose.material.icons.outlined.MoreVert import androidx.compose.material.icons.outlined.Repeat import androidx.compose.material.icons.outlined.Search import androidx.compose.material.icons.outlined.Settings +import androidx.compose.material.icons.outlined.Sort import androidx.compose.material.icons.outlined.Tag import androidx.compose.material3.AlertDialog import androidx.compose.material3.CircularProgressIndicator @@ -207,8 +208,10 @@ import uniffi.lists_core.Priority import uniffi.lists_core.QuickParse import uniffi.lists_core.SavedFilter import uniffi.lists_core.Scope +import uniffi.lists_core.SortMode import uniffi.lists_core.TaskItem import uniffi.lists_core.TaskList +import uniffi.lists_core.TodayGroup import java.time.Duration import java.time.LocalDateTime import kotlin.math.abs @@ -402,7 +405,7 @@ fun MainScreen(model: MainViewModel, onReminderSet: () -> Unit) { val eventsShown = state.effectiveScope == Scope.Today && events.isNotEmpty() if (state.loaded && state.sections.all { it.tasks.isEmpty() }) { Column(Modifier.fillMaxSize()) { - if (state.search == null) ViewTitle(state) + if (state.search == null) ViewTitle(state, model::setHeaderSort) // R78: the events of the day are shown on a day without tasks as well. if (eventsShown) EventsBlock(events) EmptyState(state.effectiveScope) @@ -413,15 +416,15 @@ fun MainScreen(model: MainViewModel, onReminderSet: () -> Unit) { val reorderable = state.reorderable() LaunchedEffect(state.sections) { reorder.forget() } // While a row is dragged, a row held at an edge scrolls the column, frame by frame. - LaunchedEffect(reorder.dragging) { - val section = state.sections.firstOrNull() ?: return@LaunchedEffect + LaunchedEffect(reorder.dragging, reorder.orderGroup) { + val section = state.sections.firstOrNull { it.key == reorder.orderGroup } ?: return@LaunchedEffect while (reorder.dragging != null) { withFrameNanos {} reorder.autoscroll(rows) { rowKey(section.key, it) } } } LazyColumn(Modifier.fillMaxSize(), state = rows, contentPadding = PaddingValues(bottom = 88.dp)) { - if (state.search == null) item(key = "title") { ViewTitle(state) } + if (state.search == null) item(key = "title") { ViewTitle(state, model::setHeaderSort) } if (eventsShown) item(key = "events") { EventsBlock(events) } for (section in state.sections) { section.title?.let { title -> @@ -429,16 +432,25 @@ fun MainScreen(model: MainViewModel, onReminderSet: () -> Unit) { GroupHeading(title, alert = section.key == "overdue") } } - val shown = reorder.order?.takeIf { reorderable } + val shown = reorder.order?.takeIf { reorderable && reorder.orderGroup == section.key } ?.mapNotNull { id -> section.tasks.firstOrNull { it.id == id } } ?.takeIf { it.size == section.tasks.size } ?: section.tasks val last = shown.lastIndex itemsIndexed(shown, key = { _, task -> rowKey(section.key, task.id) }) { index, task -> val drag = if (reorderable) { RowDrag( - onStart = { reorder.start(task.id, section.tasks.map { it.id }) }, + onStart = { reorder.start(task.id, section.tasks.map { it.id }, section.key) }, onDrag = { dy -> reorder.drag(dy, rows) { rowKey(section.key, it) } }, - onEnd = { slop -> reorder.drop(slop).also { if (it is Dropped.Moved) model.moveTask(it.id, it.after) } }, + onEnd = { slop -> + reorder.drop(slop).also { drop -> + if (drop is Dropped.Moved) { + if (state.effectiveScope == Scope.Today) { + val group = if (drop.group == "overdue") TodayGroup.OVERDUE else TodayGroup.CURRENT + model.moveTodayTasks(group, listOf(drop.id), drop.after) + } else model.moveTask(drop.id, drop.after) + } + } + }, onCancel = reorder::cancel, ) } else null @@ -1538,7 +1550,7 @@ private fun ProjectMark(done: UInt, total: UInt, tint: Color, onComplete: () -> /** R95: the large title of the view with its icon, at the top of the content. */ @Composable -private fun ViewTitle(state: UiState) { +private fun ViewTitle(state: UiState, onSetSort: (SortMode) -> Unit) { val plain = MaterialTheme.colorScheme.onSurfaceVariant val (icon, tint) = when (val scope = state.scope) { Scope.Inbox -> Icons.Filled.Inbox to viewTint(ViewTint.Blue) @@ -1554,6 +1566,15 @@ private fun ViewTitle(state: UiState) { is Scope.Tag -> Icons.Outlined.Tag to plain is Scope.Search -> Icons.Outlined.Search to plain } + var sortExpanded by remember(state.scope) { mutableStateOf(false) } + val sort = state.headerSort + val sortModes = listOf( + SortMode.MANUAL to R.string.sort_manual, + SortMode.DUE to R.string.sort_due, + SortMode.START to R.string.sort_start, + SortMode.PRIORITY to R.string.sort_priority, + SortMode.TITLE to R.string.sort_title, + ) Row(Modifier.fillMaxWidth().padding(start = Space.xxl, end = Space.xxl, top = Space.l, bottom = Space.l), verticalAlignment = Alignment.CenterVertically) { // R159: the icon stands on a tile of its colour. Box(Modifier.size(Sizes.viewTile).background(tint.copy(alpha = 0.15f), Corners.viewTile), contentAlignment = Alignment.Center) { @@ -1561,11 +1582,30 @@ private fun ViewTitle(state: UiState) { } Text( state.title, - Modifier.padding(start = Space.l).semantics { heading() }, + Modifier.weight(1f).padding(start = Space.l).semantics { heading() }, style = MaterialTheme.typography.viewTitle, maxLines = 2, overflow = TextOverflow.Ellipsis, ) + if (sort != null) { + Box { + IconButton(onClick = { sortExpanded = true }, modifier = Modifier.semantics { contentDescription = str(R.string.sorting) }) { + Icon(Icons.Outlined.Sort, contentDescription = null) + } + DropdownMenu(expanded = sortExpanded, onDismissRequest = { sortExpanded = false }) { + for ((mode, label) in sortModes) { + DropdownMenuItem( + text = { Text(str(label)) }, + onClick = { + sortExpanded = false + if (mode != sort) onSetSort(mode) + }, + trailingIcon = if (mode == sort) ({ Icon(Icons.Outlined.Check, null) }) else null, + ) + } + } + } + } } } diff --git a/android/app/src/main/java/org/evsyukov/lists/ui/MainViewModel.kt b/android/app/src/main/java/org/evsyukov/lists/ui/MainViewModel.kt index ad0e1dfd..a773a66f 100644 --- a/android/app/src/main/java/org/evsyukov/lists/ui/MainViewModel.kt +++ b/android/app/src/main/java/org/evsyukov/lists/ui/MainViewModel.kt @@ -21,7 +21,6 @@ import org.evsyukov.lists.dateLabel import org.evsyukov.lists.dayHeading import org.evsyukov.lists.dayOf import org.evsyukov.lists.displayName -import org.evsyukov.lists.dueDayPassed import org.evsyukov.lists.logError import org.evsyukov.lists.logged import org.evsyukov.lists.str @@ -32,6 +31,7 @@ import uniffi.lists_core.KeepDone import uniffi.lists_core.NewTask import uniffi.lists_core.SavedFilter import uniffi.lists_core.Scope +import uniffi.lists_core.SortMode import uniffi.lists_core.Store import uniffi.lists_core.SyncConfig import uniffi.lists_core.SyncSide @@ -39,6 +39,8 @@ import uniffi.lists_core.SyncStatus import uniffi.lists_core.TagCount import uniffi.lists_core.TaskItem import uniffi.lists_core.TaskList +import uniffi.lists_core.TodayGroup +import uniffi.lists_core.TodaySections data class TaskSection(val key: String, val title: String?, val tasks: List) @@ -80,6 +82,7 @@ data class UiState( val selection: Set? = null, /** R131: whether the menu of the bar offers Undo. */ val canUndo: Boolean = false, + val todaySort: SortMode = SortMode.DUE, ) { val effectiveScope: Scope get() = search?.takeIf { it.isNotBlank() }?.let { Scope.Search(it) } ?: scope @@ -94,6 +97,15 @@ data class UiState( /** The tasks of the view in the order of their rows. */ val shownIds: List get() = sections.flatMap { section -> section.tasks.map { it.id } } + /** Sort mode offered by the header of Inbox, a list, or Today. */ + val headerSort: SortMode? + get() = if (search != null || selection != null) null else when (val view = scope) { + Scope.Inbox -> list("inbox")?.sort + is Scope.List -> list(view.id)?.sort + Scope.Today -> todaySort + else -> null + } + val title: String get() = when (val s = scope) { Scope.Inbox -> str(R.string.inbox) @@ -195,10 +207,12 @@ class MainViewModel : ViewModel() { else -> shown } val base = current.copy(lists = lists, tags = tags, projects = projects, filters = filters, scope = scope) - val tasks = store.tasks(base.effectiveScope) + val today = if (base.effectiveScope == Scope.Today) store.todaySections() else null + val tasks = today?.let { it.overdue + it.current } ?: store.tasks(base.effectiveScope) base.copy( counts = store.counts(), - sections = group(base, tasks), + sections = group(base, tasks, today), + todaySort = store.todaySort(), found = found(store, base.effectiveScope, tasks), editing = editingId?.let { id -> load(store, id) }, sync = store.syncStatus(), @@ -246,12 +260,13 @@ class MainViewModel : ViewModel() { .filterValues { it.isNotEmpty() } } - private fun group(state: UiState, tasks: List): List = when (state.effectiveScope) { + private fun group(state: UiState, tasks: List, today: TodaySections?): List = when (state.effectiveScope) { Scope.Today -> { - // R125: a task of a project goes by the project's due date when it has none of its own. - val (overdue, rest) = tasks.partition { dueDayPassed(it.effectiveDue) } - if (overdue.isEmpty()) listOf(TaskSection("today", null, rest)) - else listOf(TaskSection("overdue", str(R.string.overdue), overdue), TaskSection("today", str(R.string.today), rest)).filter { it.tasks.isNotEmpty() } + val sections = checkNotNull(today) + val overdue = sections.overdue + val current = sections.current + if (overdue.isEmpty()) listOf(TaskSection("current", null, current)) + else listOf(TaskSection("overdue", str(R.string.overdue), overdue), TaskSection("current", str(R.string.today), current)).filter { it.tasks.isNotEmpty() } } Scope.Upcoming -> runs(tasks, { dayOf(it.effectiveDue ?: it.effectiveStart ?: "") }, ::dayHeading) Scope.All -> runs(tasks, { it.listId }, { id -> state.list(id)?.displayName().orEmpty() }) @@ -274,6 +289,22 @@ class MainViewModel : ViewModel() { /** R157: a row dragged to another place of a view sorted by hand; it goes right after [after], or first. */ fun moveTask(id: String, after: String?) = act { it.moveTask(id, null, null, after) } + /** R165: moves a task within its manually ordered Today group without changing its list position. */ + fun moveTodayTasks(group: TodayGroup, ids: List, after: String?) = act { it.moveTodayTasks(group, ids, after) } + + /** R165: the sort choice for the Today view is shared by synced devices. */ + fun setHeaderSort(sort: SortMode) { + val view = _state.value.scope + act { store -> + when (view) { + Scope.Inbox -> store.setListSort("inbox", sort) + is Scope.List -> store.setListSort(view.id, sort) + Scope.Today -> store.setTodaySort(sort) + else -> return@act + } + } + } + /** R157: a list dragged to another place in the panel of lists; it goes right after [after], or first. */ fun moveList(id: String, after: String?) = act { it.moveList(id, after) } diff --git a/android/app/src/main/java/org/evsyukov/lists/ui/Reorder.kt b/android/app/src/main/java/org/evsyukov/lists/ui/Reorder.kt index de5e25db..5710f371 100644 --- a/android/app/src/main/java/org/evsyukov/lists/ui/Reorder.kt +++ b/android/app/src/main/java/org/evsyukov/lists/ui/Reorder.kt @@ -25,18 +25,18 @@ internal fun List.moved(from: Int, to: Int): List = */ internal fun UiState.reorderable(): Boolean { if (selection != null || !search.isNullOrBlank()) return false - val list = when (val s = scope) { - Scope.Inbox -> list("inbox") - is Scope.List -> list(s.id) - else -> null + return when (val view = scope) { + Scope.Inbox -> list("inbox")?.sort == SortMode.MANUAL + is Scope.List -> list(view.id)?.sort == SortMode.MANUAL + Scope.Today -> todaySort == SortMode.MANUAL + else -> false } - return list?.sort == SortMode.MANUAL } /** How a drag of a row ended (R157). */ sealed interface Dropped { /** The row went to another place: right after [after], or first. */ - data class Moved(val id: String, val after: String?) : Dropped + data class Moved(val id: String, val after: String?, val group: String? = null) : Dropped /** The finger let go where it pressed: the long press opens what it opened before (the menu). */ data object Still : Dropped @@ -56,6 +56,10 @@ class Reorder { var order by mutableStateOf?>(null) private set + /** The section whose independent manual order is being changed. */ + var orderGroup by mutableStateOf(null) + private set + /** How far the dragged row is drawn from its place in the column, in pixels. */ var offset by mutableFloatStateOf(0f) private set @@ -64,9 +68,10 @@ class Reorder { private var travel = 0f private var initial: List = emptyList() - fun start(id: String, ids: List) { + fun start(id: String, ids: List, group: String? = null) { dragging = id order = ids + orderGroup = group initial = ids offset = 0f moved = false @@ -124,7 +129,7 @@ class Reorder { val now = order val result = when { // Taken away and brought back is no move. - id != null && now != null && moved && now != initial -> Dropped.Moved(id, placedAfter(now, id)) + id != null && now != null && moved && now != initial -> Dropped.Moved(id, placedAfter(now, id), orderGroup) travel < slop -> Dropped.Still else -> Dropped.Kept } @@ -133,18 +138,25 @@ class Reorder { moved = false travel = 0f // A moved row stays where it was put until the view is read again with it there (see [forget]). - if (result !is Dropped.Moved) order = null + if (result !is Dropped.Moved) { + order = null + orderGroup = null + } return result } /** The view was read again: the order of the store is shown from here on. */ fun forget() { - if (dragging == null) order = null + if (dragging == null) { + order = null + orderGroup = null + } } fun cancel() { dragging = null order = null + orderGroup = null offset = 0f moved = false travel = 0f diff --git a/android/app/src/main/res/values-ru/strings.xml b/android/app/src/main/res/values-ru/strings.xml index 9fef33d2..4aaaba32 100644 --- a/android/app/src/main/res/values-ru/strings.xml +++ b/android/app/src/main/res/values-ru/strings.xml @@ -137,6 +137,7 @@ Вручную По сроку По приоритету + По дате начала По названию Показывать выполненные Новые задачи diff --git a/android/app/src/main/res/values-zh-rCN/strings.xml b/android/app/src/main/res/values-zh-rCN/strings.xml index 0a502710..fb10e49d 100644 --- a/android/app/src/main/res/values-zh-rCN/strings.xml +++ b/android/app/src/main/res/values-zh-rCN/strings.xml @@ -137,6 +137,7 @@ 手动 按到期日 按优先级 + 按开始日期 按标题 显示已完成 新建任务 diff --git a/android/app/src/main/res/values/strings.xml b/android/app/src/main/res/values/strings.xml index 5ce4d9b1..43c1aa82 100644 --- a/android/app/src/main/res/values/strings.xml +++ b/android/app/src/main/res/values/strings.xml @@ -138,6 +138,7 @@ Manually By due date By priority + By start date By title Show completed New tasks diff --git a/android/app/src/test/java/org/evsyukov/lists/ui/ReorderTest.kt b/android/app/src/test/java/org/evsyukov/lists/ui/ReorderTest.kt index 9d5a1dee..49d269b0 100644 --- a/android/app/src/test/java/org/evsyukov/lists/ui/ReorderTest.kt +++ b/android/app/src/test/java/org/evsyukov/lists/ui/ReorderTest.kt @@ -20,6 +20,7 @@ class ReorderTest { assertTrue(state.copy(scope = Scope.List("home")).reorderable()) assertFalse("a list sorted by due date", state.copy(scope = Scope.List("work")).reorderable()) assertFalse(state.copy(scope = Scope.Today).reorderable()) + assertTrue(state.copy(scope = Scope.Today, todaySort = SortMode.MANUAL).reorderable()) assertFalse(state.copy(scope = Scope.Project("trip")).reorderable()) assertFalse(state.copy(scope = Scope.Inbox, search = "milk").reorderable()) assertFalse(state.copy(scope = Scope.Inbox, selection = emptySet()).reorderable()) @@ -32,6 +33,7 @@ class ReorderTest { assertEquals(listOf("d", "a", "b", "c"), order.moved(3, 0)) assertEquals(order, order.moved(1, 1)) assertEquals("c", placedAfter(order.moved(0, 2), "a")) + assertEquals("current", (Dropped.Moved("a", "c", "current") as Dropped.Moved).group) assertEquals("first: after nothing", null, placedAfter(order.moved(3, 0), "d")) } diff --git a/apple/App/AppModel.swift b/apple/App/AppModel.swift index 798c1b35..81ee18b4 100644 --- a/apple/App/AppModel.swift +++ b/apple/App/AppModel.swift @@ -43,6 +43,7 @@ final class AppModel { var sections: [TaskSection] = [] /// Minutes a completed task stays in its view; shared by all devices (R68). private(set) var keepDone: KeepDone = .seconds(seconds: 5) + private(set) var todaySort: SortMode = .due var children: [String: [TaskItem]] = [:] /// R22: the subtasks a search found a task by, shown as lines under its row. var found: [String: [TaskItem]] = [:] @@ -677,10 +678,31 @@ final class AppModel { switch scope { case .inbox: return list("inbox")?.sort == .manual case .list(let id): return list(id)?.sort == .manual + case .today: return todaySort == .manual default: return false } } + var currentSort: SortMode? { + switch effectiveScope { + case .inbox: return list("inbox")?.sort + case .list(let id): return list(id)?.sort + case .today: return todaySort + default: return nil + } + } + + func setSort(_ sort: SortMode) { + perform { store in + switch effectiveScope { + case .inbox: try store.setListSort(id: "inbox", sort: sort) + case .list(let id): try store.setListSort(id: id, sort: sort) + case .today: try store.setTodaySort(sort: sort) + default: break + } + } + } + func setKeepDone(_ keep: KeepDone) { perform { try $0.setKeepDone(keep: keep) } } @@ -696,6 +718,7 @@ final class AppModel { applyDockCount() syncStatus = try store.syncStatus() keepDone = try store.keepDone() + todaySort = try store.todaySort() newTaskList = try store.newTaskList() newTaskStart = try store.newTaskStart() inboxHidden = try store.inboxHidden() @@ -712,7 +735,11 @@ final class AppModel { filters = try store.filters() if case .project(let id) = scope, !projects.contains(where: { $0.id == id }) { scope = .inbox } if case .filter(let id) = scope, !filters.contains(where: { $0.id == id }) { scope = .inbox } - sections = group(try store.tasks(view: effectiveScope)) + if case .today = effectiveScope { + sections = todaySections(try store.todaySections()) + } else { + sections = group(try store.tasks(view: effectiveScope)) + } var loaded: [String: [TaskItem]] = [:] for id in expanded { loaded[id] = try store.subtasks(parentId: id) @@ -736,17 +763,7 @@ final class AppModel { private func group(_ tasks: [TaskItem]) -> [TaskSection] { switch effectiveScope { case .today: - let today = Moment.today() - // R84: overdue is a due date that has passed. A start date in the past only makes the task available. - // R125: a task of a project goes by the project's due date when it has none of its own. - let isOverdue: (TaskItem) -> Bool = { task in task.effectiveDue.map { Moment.day($0) < today } ?? false } - let overdue = tasks.filter(isOverdue) - let rest = tasks.filter { !isOverdue($0) } - if overdue.isEmpty { return [TaskSection(id: "today", title: nil, tasks: rest)] } - return [ - TaskSection(id: "overdue", title: L("Overdue"), tasks: overdue), - TaskSection(id: "today", title: L("Today"), tasks: rest), - ].filter { !$0.tasks.isEmpty } + return [TaskSection(id: "today", title: nil, tasks: tasks)] case .upcoming: return sectioned(tasks, key: { Moment.day($0.effectiveDue ?? $0.effectiveStart ?? "") }, title: Moment.heading) case .all: @@ -758,6 +775,13 @@ final class AppModel { } } + private func todaySections(_ today: TodaySections) -> [TaskSection] { + [ + TaskSection(id: "overdue", title: L("Overdue"), tasks: today.overdue), + TaskSection(id: "today", title: today.overdue.isEmpty ? nil : L("Today"), tasks: today.current), + ].filter { !$0.tasks.isEmpty } + } + /// Splits an already ordered list into runs with the same key. private func sectioned(_ tasks: [TaskItem], key: (TaskItem) -> String, title: (String) -> String) -> [TaskSection] { var out: [TaskSection] = [] @@ -1314,6 +1338,7 @@ final class AppModel { /// Reorders within the single section of a manually sorted list. /// R123: the tasks put together before the task at `destination` of the list, in the order of the view; one undo. func move(_ ids: [String], to destination: Int) { + if case .today = effectiveScope { return } guard canReorder, let tasks = visibleSections.first?.tasks else { return } let moves = Reorder.moves(tasks.map(\.id), moving: ids, to: destination) guard !moves.isEmpty else { return } @@ -1322,6 +1347,11 @@ final class AppModel { } } + func moveToday(_ ids: [String], group: TodayGroup, after: String?) { + guard canReorder, case .today = effectiveScope else { return } + perform { try $0.moveTodayTasks(group: group, ids: ids, after: after) } + } + // MARK: Import /// Asks for a file exported from another task manager and imports it. diff --git a/apple/App/MainWindow.swift b/apple/App/MainWindow.swift index 1b4bc5c3..e0f9196e 100644 --- a/apple/App/MainWindow.swift +++ b/apple/App/MainWindow.swift @@ -128,11 +128,43 @@ private extension View { struct ViewTitle: View { @Environment(AppModel.self) private var model + private func sortTitle(_ sort: SortMode) -> String { + switch sort { + case .manual: L("Manually") + case .due: L("By due date") + case .start: L("By start date") + case .priority: L("By priority") + case .title: L("By title") + } + } + var body: some View { let icon = model.scopeIcon HStack(spacing: 8) { Image(systemName: icon.symbol).foregroundStyle(icon.tint) Text(model.scopeTitle).lineLimit(1) + if !model.isSearching && !model.searchOpen, let sort = model.currentSort { + Menu { + ForEach([SortMode.manual, .due, .start, .priority, .title], id: \.self) { mode in + Button { + model.setSort(mode) + } label: { + if mode == sort { + Label(sortTitle(mode), systemImage: "checkmark") + } else { + Text(sortTitle(mode)) + } + } + } + } label: { + Image(systemName: "arrow.up.arrow.down") + .font(AppFont.style(.body, weight: .medium)) + .foregroundStyle(.secondary) + } + .menuStyle(.borderlessButton) + .fixedSize() + .accessibilityLabel(L("Sort")) + } Spacer(minLength: 8) if model.searchOpen || model.isSearching { SearchField().font(AppFont.style(.body)) } } @@ -140,7 +172,7 @@ struct ViewTitle: View { .padding(.horizontal, 20) .padding(.top, 4) .padding(.bottom, 8) - .accessibilityElement(children: .combine) + .accessibilityElement(children: .contain) .accessibilityAddTraits(.isHeader) } } @@ -353,6 +385,7 @@ struct ListEditor: View { Picker(L("Sort"), selection: $sort) { Text(L("Manually")).tag(SortMode.manual) Text(L("By due date")).tag(SortMode.due) + Text(L("By start date")).tag(SortMode.start) Text(L("By priority")).tag(SortMode.priority) Text(L("By title")).tag(SortMode.title) } diff --git a/apple/App/TaskTable.swift b/apple/App/TaskTable.swift index 87e55784..db339146 100644 --- a/apple/App/TaskTable.swift +++ b/apple/App/TaskTable.swift @@ -498,7 +498,11 @@ struct TaskTable: NSViewRepresentable { /// A drop between rows moves the dragged tasks in a list sorted by hand, when all of them are tasks of the list /// rather than subtasks or tasks of a project; anywhere else the table takes nothing. func tableView(_ tableView: NSTableView, validateDrop info: any NSDraggingInfo, proposedRow row: Int, proposedDropOperation operation: NSTableView.DropOperation) -> NSDragOperation { - guard model.canReorder, info.draggingSource as AnyObject === tableView, operation == .above, ordered(dragged(info)) else { return [] } + let ids = dragged(info) + guard model.canReorder, info.draggingSource as AnyObject === tableView, operation == .above, ordered(ids) else { return [] } + if case .today = model.effectiveScope { + guard let source = todayGroup(ids), todayGroup(at: row, from: source) == source else { return [] } + } return .move } @@ -512,14 +516,65 @@ struct TaskTable: NSViewRepresentable { /// Whether all of the tasks stand in the order of the list sorted by hand. private func ordered(_ ids: [String]) -> Bool { + guard !ids.isEmpty, Set(ids).count == ids.count else { return false } + if case .today = model.effectiveScope { return todayGroup(ids) != nil } let tasks = Set((model.visibleSections.first?.tasks ?? []).map(\.id)) - return !ids.isEmpty && ids.allSatisfy(tasks.contains) + return ids.allSatisfy(tasks.contains) + } + + private func todayGroup(_ ids: [String]) -> TodayGroup? { + let wanted = Set(ids) + for section in model.visibleSections where wanted.isSubset(of: Set(section.tasks.map(\.id))) { + switch section.id { + case "overdue": return .overdue + case "today": return .current + default: return nil + } + } + return nil + } + + private func todayGroup(at row: Int, from source: TodayGroup) -> TodayGroup? { + if row >= rows.count { return model.visibleSections.last.flatMap { todayGroup($0.id) } } + guard rows.indices.contains(row) else { return nil } + switch rows[row] { + case .heading("today", _): return Reorder.todayDropGroup(at: .current, from: source) + case .heading(let id, _): return todayGroup(id) + case .task(let state) where state.depth == 0: return todayGroup([state.task.id]) + default: return nil + } + } + + private func todayGroup(_ id: String) -> TodayGroup? { + switch id { + case "overdue": return .overdue + case "today": return .current + default: return nil + } } /// Moves the tasks to the place before the row with that index, the way a drop between rows does. @discardableResult func move(_ ids: [String], toRow row: Int) -> Bool { guard ordered(ids) else { return false } + if case .today = model.effectiveScope { + guard let group = todayGroup(ids), todayGroup(at: row, from: group) == group, + let section = model.visibleSections.first(where: { todayGroup($0.id) == group }) else { return false } + let groupIds = section.tasks.map(\.id) + let groupSet = Set(groupIds) + let above = Set(rows.prefix(max(row, 0)).compactMap(\.taskId).filter(groupSet.contains)) + let moves = Reorder.moves(groupIds, moving: ids, to: groupIds.filter(above.contains).count) + guard !moves.isEmpty else { return true } + var order = groupIds + for move in moves { + order.removeAll { $0 == move.id } + order.insert(move.id, at: move.after.flatMap { order.firstIndex(of: $0).map { $0 + 1 } } ?? 0) + } + let moved = order.filter(Set(ids).contains) + let after = order.firstIndex(of: moved[0]).flatMap { $0 > 0 ? order[$0 - 1] : nil } + model.moveToday(moved, group: group, after: after) + return true + } // The order of the list counts its tasks alone: the rows of the view above the place that are its tasks. let tasks = model.visibleSections.first?.tasks ?? [] let above = Set(rows.prefix(max(row, 0)).compactMap(\.taskId)) diff --git a/apple/Shared/Reorder.swift b/apple/Shared/Reorder.swift index 093b19ce..35bfd500 100644 --- a/apple/Shared/Reorder.swift +++ b/apple/Shared/Reorder.swift @@ -1,5 +1,10 @@ /// R123: moving tasks to another place of a list sorted by hand. enum Reorder { + /// Dropping above the Today heading ends the Overdue group when dragging from Overdue. + static func todayDropGroup(at boundary: TodayGroup, from source: TodayGroup) -> TodayGroup { + boundary == .current && source == .overdue ? .overdue : boundary + } + /// The moves that put `moving` together before the place `destination` of `order`, keeping their order in `order`: /// each task goes after the one named, or first for none. Made one after the other, they give the new order. static func moves(_ order: [String], moving: [String], to destination: Int) -> [(id: String, after: String?)] { diff --git a/apple/Shared/en.lproj/Localizable.strings b/apple/Shared/en.lproj/Localizable.strings index 5c5c2f55..4e21cff9 100644 --- a/apple/Shared/en.lproj/Localizable.strings +++ b/apple/Shared/en.lproj/Localizable.strings @@ -1 +1,3 @@ /* English is the language of the keys; nothing to override. */ + +"By start date" = "By start date"; diff --git a/apple/Shared/ru.lproj/Localizable.strings b/apple/Shared/ru.lproj/Localizable.strings index c6329773..81724446 100644 --- a/apple/Shared/ru.lproj/Localizable.strings +++ b/apple/Shared/ru.lproj/Localizable.strings @@ -134,6 +134,7 @@ "Sort" = "Сортировка"; "Manually" = "Вручную"; "By due date" = "По сроку"; +"By start date" = "По дате начала"; "By priority" = "По приоритету"; "By title" = "По названию"; "Keep completed tasks in this list" = "Оставлять выполненные задачи в списке"; diff --git a/apple/Shared/zh-Hans.lproj/Localizable.strings b/apple/Shared/zh-Hans.lproj/Localizable.strings index 13647e89..b1b7b5e9 100644 --- a/apple/Shared/zh-Hans.lproj/Localizable.strings +++ b/apple/Shared/zh-Hans.lproj/Localizable.strings @@ -134,6 +134,7 @@ "Sort" = "排序"; "Manually" = "手动"; "By due date" = "按到期日"; +"By start date" = "按开始日期"; "By priority" = "按优先级"; "By title" = "按标题"; "Keep completed tasks in this list" = "在此清单中保留已完成的任务"; diff --git a/apple/Tests/SharedTests.swift b/apple/Tests/SharedTests.swift index 020d5f6e..b20edcef 100644 --- a/apple/Tests/SharedTests.swift +++ b/apple/Tests/SharedTests.swift @@ -160,6 +160,12 @@ final class ReorderTests: XCTestCase { XCTAssertEqual(apply(order, Reorder.moves(order, moving: ["a", "e"], to: 2)), ["b", "a", "e", "c", "d"]) } + func testTodayBoundaryKeepsTheDraggedTasksInTheirGroup() { + XCTAssertEqual(Reorder.todayDropGroup(at: .current, from: .overdue), .overdue) + XCTAssertEqual(Reorder.todayDropGroup(at: .current, from: .current), .current) + XCTAssertEqual(Reorder.todayDropGroup(at: .overdue, from: .current), .overdue) + } + func testADropWhereTheTasksStandMovesNothing() { let order = ["a", "b", "c", "d"] XCTAssertTrue(Reorder.moves(order, moving: ["b", "c"], to: 1).isEmpty) diff --git a/core/Cargo.lock b/core/Cargo.lock index 754f2dd0..3bfbdbf7 100644 --- a/core/Cargo.lock +++ b/core/Cargo.lock @@ -597,6 +597,31 @@ dependencies = [ "typenum", ] +[[package]] +name = "icu_collator" +version = "2.3.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "08984ed58ac439ebf3e13d2cf26b0c46a60afcd21721c1d14087c0b240344dda" +dependencies = [ + "icu_collator_data", + "icu_collections", + "icu_locale_core", + "icu_locale_fallback", + "icu_normalizer", + "icu_properties", + "icu_provider", + "smallvec", + "utf16_iter", + "utf8_iter", + "zerovec", +] + +[[package]] +name = "icu_collator_data" +version = "2.3.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f7d7e54efdddeb1208c08dd5d32b53a879ac00d2d3d051b2255fd26821d16368" + [[package]] name = "icu_collections" version = "2.3.0" @@ -619,11 +644,32 @@ checksum = "d56e28588da92eee5c3201a6eff33fabdd49b62269c8938d4ff050ce4d900deb" dependencies = [ "displaydoc", "litemap", + "serde", "tinystr", "writeable", "zerovec", ] +[[package]] +name = "icu_locale_fallback" +version = "2.3.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "251af8e57c9400e3eb58242fe5b8b1152b2a64fdf4cf632f923c38ccee6f2fa9" +dependencies = [ + "icu_locale_core", + "icu_locale_fallback_data", + "icu_provider", + "potential_utf", + "tinystr", + "zerovec", +] + +[[package]] +name = "icu_locale_fallback_data" +version = "2.3.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "decf2a22ec8fa68f1a0c1129a3f8583f8f8bc24e8b9ccbe98ead99f62a4dc3a8" + [[package]] name = "icu_normalizer" version = "2.3.0" @@ -635,6 +681,9 @@ dependencies = [ "icu_properties", "icu_provider", "smallvec", + "utf16_iter", + "utf8_iter", + "write16", "zerovec", ] @@ -673,6 +722,8 @@ checksum = "d27bbb9d3abbefac45d55f647c9de1d44aafcd1186eb91879afef17c396c3e73" dependencies = [ "displaydoc", "icu_locale_core", + "serde", + "stable_deref_trait", "writeable", "yoke", "zerofrom", @@ -823,6 +874,7 @@ dependencies = [ "chacha20poly1305", "flate2", "hmac", + "icu_collator", "jiff", "pulldown-cmark", "roxmltree", @@ -978,6 +1030,8 @@ version = "0.1.6" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "d83eb9bc6d8e5cf568e7a1101d60ee05e81ed50ea106026f3d18deeb046d7661" dependencies = [ + "serde_core", + "writeable", "zerovec", ] @@ -1408,6 +1462,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "b1e27c91459209c2986af3dcf603a5a74a4368754ce37414f59acc971167f643" dependencies = [ "displaydoc", + "serde_core", "zerovec", ] @@ -1665,12 +1720,27 @@ dependencies = [ "serde", ] +[[package]] +name = "utf16_iter" +version = "1.1.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1c7de35d9d8757dbc1f5125dc8b51438c68b4430546a735c3a9b91aaaaf9a18a" +dependencies = [ + "utf_types", +] + [[package]] name = "utf8_iter" version = "1.0.4" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "b6c140620e7ffbb22c2dee59cafe6084a59b5ffc27a8859a5f0d494b5d52b6be" +[[package]] +name = "utf_types" +version = "1.0.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "3a3b425286980a367278453f3b6d28cdcb134b574e5a35824a6ff5eebad50bb6" + [[package]] name = "uuid" version = "1.29.3" @@ -1873,6 +1943,12 @@ dependencies = [ "memchr", ] +[[package]] +name = "write16" +version = "1.0.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d1890f4022759daae28ed4fe62859b1236caebfc61ede2f63ed4e695f3f6d936" + [[package]] name = "writeable" version = "0.6.4" @@ -1952,6 +2028,7 @@ dependencies = [ "displaydoc", "yoke", "zerofrom", + "zerovec", ] [[package]] @@ -1960,6 +2037,7 @@ version = "0.11.8" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "bb0464e17806c1d976d5cba29399c7f08e516e279e2ba493f63123b5fca67dd8" dependencies = [ + "serde", "yoke", "zerofrom", "zerovec-derive", diff --git a/core/Cargo.toml b/core/Cargo.toml index e95c341f..7c8a078a 100644 --- a/core/Cargo.toml +++ b/core/Cargo.toml @@ -25,10 +25,11 @@ base64 = "0.23" chacha20poly1305 = "0.11" flate2 = "1" hmac = "0.13" +icu_collator = "~2.3.0" jiff = "1" pulldown-cmark = { version = "0.13", default-features = false } roxmltree = "0.21" -rusqlite = { version = "0.43", features = ["bundled", "fallible_uint"] } +rusqlite = { version = "0.43", features = ["bundled", "collation", "fallible_uint"] } serde = { version = "1", features = ["derive"] } serde_json = "1" sha2 = "0.11" diff --git a/core/src/model.rs b/core/src/model.rs index 1c835c32..7d6bd84d 100644 --- a/core/src/model.rs +++ b/core/src/model.rs @@ -47,15 +47,22 @@ pub enum SortMode { Due, Priority, Title, + Start, } impl SortMode { pub fn parse(s: &str) -> Self { + Self::from_key(s).unwrap_or_default() + } + + pub(crate) fn from_key(s: &str) -> Option { match s { - "due" => SortMode::Due, - "priority" => SortMode::Priority, - "title" => SortMode::Title, - _ => SortMode::Manual, + "manual" => Some(SortMode::Manual), + "due" => Some(SortMode::Due), + "priority" => Some(SortMode::Priority), + "title" => Some(SortMode::Title), + "start" => Some(SortMode::Start), + _ => None, } } pub fn as_str(self) -> &'static str { @@ -64,6 +71,7 @@ impl SortMode { SortMode::Due => "due", SortMode::Priority => "priority", SortMode::Title => "title", + SortMode::Start => "start", } } } @@ -168,6 +176,20 @@ pub struct TaskItem { pub undoable: bool, } +/// Which group of Today a task is in. +#[derive(Debug, Clone, Copy, PartialEq, Eq, uniffi::Enum)] +pub enum TodayGroup { + Overdue, + Current, +} + +/// Today as displayed by the clients, with each group in its selected order. +#[derive(Debug, Clone, PartialEq, uniffi::Record)] +pub struct TodaySections { + pub overdue: Vec, + pub current: Vec, +} + #[derive(Debug, Clone, Default, uniffi::Record)] pub struct NewTask { pub title: String, diff --git a/core/src/store.rs b/core/src/store.rs index 44635ba1..3c4a3428 100644 --- a/core/src/store.rs +++ b/core/src/store.rs @@ -1,12 +1,15 @@ //! The object the apps talk to. Every public method is synchronous and safe //! to call from any thread; apps call them off the main thread. +use std::collections::{HashMap, HashSet}; use std::io::{Read, Write}; use std::path::{Path, PathBuf}; use std::sync::atomic::{AtomicU64, Ordering}; use std::sync::{Arc, Mutex, MutexGuard}; use std::time::{Duration, Instant}; +use icu_collator::options::{CollatorOptions, Strength}; +use icu_collator::Collator; use jiff::civil::{time, Date, DateTime, Time}; use jiff::tz::{AmbiguousOffset, Offset, TimeZone}; use jiff::{SignedDuration, Timestamp, ToSpan}; @@ -27,6 +30,8 @@ use crate::undo::Step; use crate::{order, quickadd, recur, subtasks}; const MOMENT_FMT: &str = "%Y-%m-%dT%H:%M"; +const TODAY_SORT: &str = "today_sort"; +const TITLE_ORDER: &str = "t.title COLLATE lists_title"; /// R140: where the limits of this device are kept in `meta`, next to the level of the log. const MAX_FILE_KEY: &str = "max_file_bytes"; @@ -141,6 +146,7 @@ pub(crate) struct Writer<'a> { pub tx: &'a Connection, clock: &'a mut Clock, now_ms: u64, + fixed_clock: bool, pub now: DateTime, touched: Touched, /// What an action that undo can take back has written so far (R131). @@ -400,6 +406,18 @@ fn fixed_millis(local: DateTime, offset: Offset) -> u64 { millis.max(0) as u64 } +/// A moment of this device's local time on the clock of the stamps. +fn local_millis(local: DateTime, fixed_clock: bool) -> u64 { + match zone() { + Some(offset) => fixed_millis(local, offset), + None if fixed_clock => fixed_millis(local, Offset::UTC), + None => local_day_boundary(&system_time_zone(), local) + .unwrap_or_else(Timestamp::now) + .as_millisecond() + .max(0) as u64, + } +} + impl Inner { pub fn now(&self) -> DateTime { match (self.now, zone()) { @@ -418,20 +436,6 @@ impl Inner { } } - /// A moment of this device's local time on the clock of the stamps. - fn ms_of(&self, local: DateTime) -> u64 { - match (self.now, zone()) { - // A zone given by its offset has no hour that the clocks skip. - (_, Some(offset)) => fixed_millis(local, offset), - // The clock of the tests has no time zone. - (Some(_), None) => fixed_millis(local, Offset::UTC), - (None, None) => local_day_boundary(&system_time_zone(), local) - .unwrap_or_else(Timestamp::now) - .as_millisecond() - .max(0) as u64, - } - } - pub fn write(&mut self, f: impl FnOnce(&mut Writer) -> Result) -> Result { self.write_with(None, f).map(|(out, _)| out) } @@ -457,6 +461,7 @@ impl Inner { tx: &tx, clock: &mut self.clock, now_ms, + fixed_clock: self.now.is_some(), now, touched: Touched::new(), noted, @@ -581,18 +586,22 @@ fn keep_done_to_value(keep: KeepDone) -> Value { } } -/// One field of the shared settings (S32); none when it is not there or does not parse. -fn setting(conn: &Connection, field: &str) -> Result> { +fn register_value(conn: &Connection, kind: &str, id: &str, field: &str) -> Result> { let stored: Option = conn .query_row( "SELECT value FROM fields WHERE kind = ?1 AND id = ?2 AND field = ?3", - [KIND_SETTINGS, SETTINGS_ID, field], + [kind, id, field], |r| r.get(0), ) .optional()?; Ok(stored.and_then(|v| serde_json::from_str::(&v).ok())) } +/// One field of the shared settings (S32); none when it is not there or does not parse. +fn setting(conn: &Connection, field: &str) -> Result> { + register_value(conn, KIND_SETTINGS, SETTINGS_ID, field) +} + fn keep_done(conn: &Connection) -> Result { Ok(setting(conn, "keep_done")? .and_then(|v| keep_done_from_value(&v)) @@ -697,22 +706,26 @@ struct Recent { impl Recent { fn at(inner: &Inner) -> Result { - let Some(Kept { window, .. }) = kept(inner)? else { - return Ok(Recent { + Ok(Self::from_kept(kept(inner)?)) + } + + fn from_kept(kept: Option) -> Self { + let Some(Kept { window, .. }) = kept else { + return Recent { open: "t.done IS NULL".into(), settled: "t.done IS NOT NULL".into(), live: LIVE.into(), project_records: "0".into(), - }); + }; }; - Ok(Recent { + Recent { open: format!("(t.done IS NULL OR {window})"), settled: format!("(t.done IS NOT NULL AND NOT {window})"), live: format!("t.eff_deleted = 0 AND (t.log_of IS NULL OR {window})"), project_records: format!( "(t.eff_deleted = 0 AND {window} AND t.log_of IN (SELECT id FROM tasks WHERE eff_parent = ?1))" ), - }) + } } } @@ -730,7 +743,10 @@ struct Kept { /// The value of `done` has to agree with it to the minute, so that tasks whose completion was only /// recorded now (an import, a calendar read for the first time) are not taken for just completed. fn kept(inner: &Inner) -> Result> { - let (now, now_ms) = (inner.now(), inner.now_ms()); + kept_at(&inner.conn, inner.now(), inner.now_ms(), inner.now.is_some()) +} + +fn kept_at(conn: &Connection, now: DateTime, now_ms: u64, fixed_clock: bool) -> Result> { let window = |stamps: (u64, u64), done: (DateTime, DateTime)| { format!( "(substr(t.done_stamp, 1, 12) BETWEEN '{:012x}' AND '{:012x}' AND t.done BETWEEN '{}' AND '{}')", @@ -740,7 +756,7 @@ fn kept(inner: &Inner) -> Result> { done.1.strftime(MOMENT_FMT) ) }; - Ok(match keep_done(&inner.conn)? { + Ok(match keep_done(conn)? { KeepDone::Seconds { seconds: 0 } => None, KeepDone::Seconds { seconds } => { let span_ms = u64::from(seconds) * 1000; @@ -757,7 +773,8 @@ fn kept(inner: &Inner) -> Result> { KeepDone::EndOfDay => { let midnight = now.date().to_datetime(Time::MIN); let next = midnight.saturating_add(1.day()); - let (from_ms, until_ms) = (inner.ms_of(midnight), inner.ms_of(next)); + let from_ms = local_millis(midnight, fixed_clock); + let until_ms = local_millis(next, fixed_clock); Some(Kept { window: window( (from_ms, until_ms.saturating_sub(1)), @@ -1132,6 +1149,12 @@ impl Store { let database = dir.join("lists.sqlite"); let conn = Connection::open(&database)?; private_file(&database)?; + let mut collation = CollatorOptions::default(); + collation.strength = Some(Strength::Secondary); + let titles = Collator::try_new(Default::default(), collation).map_err(|err| AppError::Storage { + msg: format!("could not initialize title collation: {err}"), + })?; + conn.create_collation("lists_title", move |a, b| titles.compare(a, b))?; crate::backup::close_backups(&dir.join("backups"))?; // R92: a database of an earlier schema is backed up as it is, before anything in it is changed. let outdated = db::schema_version(&conn)?.is_some_and(|stored| stored < db::SCHEMA_VERSION); @@ -1252,6 +1275,57 @@ impl Store { self.list_field(id, "sort", json!(sort.as_str())) } + /// The sort mode used inside each of Today's two groups (R165). + pub fn today_sort(&self) -> Result { + today_sort(&self.lock().conn) + } + + pub fn set_today_sort(&self, sort: SortMode) -> Result<()> { + self.write(|w| w.list(INBOX_ID, TODAY_SORT, json!(sort.as_str()))) + } + + pub fn today_sections(&self) -> Result { + let inner = self.lock(); + let today = inner.now().date().strftime(DATE_FMT).to_string(); + today_sections(&inner.conn, &today, &Recent::at(&inner)?, today_sort(&inner.conn)?) + } + + /// Move tasks within one group of Today, after the given task or to the top. + pub fn move_today_tasks(&self, group: TodayGroup, ids: Vec, after: Option) -> Result<()> { + self.act(|w| { + if today_sort(w.tx)? != SortMode::Manual { + return Err(AppError::invalid("Today must be sorted manually")); + } + let today = w.now.date().strftime(DATE_FMT).to_string(); + let recent = Recent::from_kept(kept_at(w.tx, w.now, w.now_ms, w.fixed_clock)?); + let sections = today_sections(w.tx, &today, &recent, SortMode::Manual)?; + let tasks = match group { + TodayGroup::Overdue => sections.overdue, + TodayGroup::Current => sections.current, + }; + let original: Vec = tasks.into_iter().map(|task| task.id).collect(); + let requested: HashSet<&str> = ids.iter().map(String::as_str).collect(); + let (moving, mut order): (Vec<_>, Vec<_>) = + original.iter().cloned().partition(|id| requested.contains(id.as_str())); + if moving.is_empty() || moving.len() != ids.len() { + return Err(AppError::invalid("the moved tasks must be in the same Today group")); + } + let index = match after { + Some(after) => order + .iter() + .position(|id| id == &after) + .map(|index| index + 1) + .ok_or_else(|| AppError::invalid("the destination must be in the same Today group"))?, + None => 0, + }; + order.splice(index..index, moving); + if order != original { + w.list(INBOX_ID, today_order_field(group), json!(order))?; + } + Ok(()) + }) + } + pub fn set_list_show_done(&self, id: String, show: bool) -> Result<()> { self.list_field(id, "show_done", json!(show)) } @@ -1475,16 +1549,10 @@ impl Store { match view { Scope::Inbox => list_tasks(conn, INBOX_ID, &recent), Scope::List { id } => list_tasks(conn, &id, &recent), - Scope::Today => query_tasks( - conn, - &format!( - "WHERE {live} AND {NOT_ARCHIVED} AND {NOT_PROJECT} AND {open} - AND substr({EFF_DATE}, 1, 10) <= ?1 - AND ({EFF_START} IS NULL OR substr({EFF_START}, 1, 10) <= ?1) - ORDER BY {EFF_DATE}, t.priority DESC, t.pos, t.id" - ), - &[&today], - ), + Scope::Today => { + let sections = today_sections(conn, &today, &recent, today_sort(conn)?)?; + Ok(sections.overdue.into_iter().chain(sections.current).collect()) + } Scope::Upcoming => query_tasks( conn, &format!( @@ -1659,13 +1727,14 @@ impl Store { )?) }; let open = format!("{LIVE} AND {NOT_ARCHIVED} AND {NOT_PROJECT} AND t.done IS NULL"); + let in_today = today_condition(); Ok(Counts { inbox: count(&format!("{LIVE} AND t.done IS NULL AND t.eff_list = 'inbox' AND t.eff_parent IS NULL AND t.project = 0"), &[])?, today: count( - &format!("{open} AND substr({EFF_DATE}, 1, 10) <= ?1 AND ({EFF_START} IS NULL OR substr({EFF_START}, 1, 10) <= ?1)"), + &format!("{open} AND {in_today}"), &[&today], )?, - overdue: count(&format!("{open} AND substr({EFF_DUE}, 1, 10) < ?1"), &[&today])?, + overdue: count(&format!("{open} AND {in_today} AND substr({EFF_DUE}, 1, 10) < ?1"), &[&today])?, upcoming: count( &format!("{open} AND (substr({EFF_DATE}, 1, 10) > ?1 OR ({EFF_START} IS NOT NULL AND substr({EFF_START}, 1, 10) > ?1))"), &[&today], @@ -2651,13 +2720,87 @@ pub(crate) fn complete_in(w: &mut Writer, id: &str, wont: bool) -> Result Result { + let mode = register_value(conn, KIND_LIST, INBOX_ID, TODAY_SORT)?; + Ok(mode + .as_ref() + .and_then(Value::as_str) + .and_then(SortMode::from_key) + .unwrap_or(SortMode::Due)) +} + +fn today_order_field(group: TodayGroup) -> &'static str { + match group { + TodayGroup::Overdue => "today_order_overdue", + TodayGroup::Current => "today_order_current", + } +} + +fn today_condition() -> String { + format!("substr({EFF_DATE}, 1, 10) <= ?1 AND ({EFF_START} IS NULL OR substr({EFF_START}, 1, 10) <= ?1)") +} + +fn today_sections(conn: &Connection, today: &str, recent: &Recent, sort: SortMode) -> Result { + let order = match sort { + SortMode::Start => format!("{EFF_START} IS NULL, {EFF_START}, {EFF_DATE}, t.priority DESC"), + SortMode::Priority => format!("t.priority DESC, {EFF_DATE}"), + SortMode::Title => format!("{TITLE_ORDER}, {EFF_DATE}, t.priority DESC"), + SortMode::Manual | SortMode::Due => format!("{EFF_DATE}, t.priority DESC"), + }; + let tasks = query_tasks( + conn, + &format!( + "WHERE {} AND {NOT_ARCHIVED} AND {NOT_PROJECT} AND {} AND {} ORDER BY {order}, t.pos, t.id", + recent.live, + recent.open, + today_condition() + ), + &[today], + )?; + let (mut overdue, mut current): (Vec<_>, Vec<_>) = tasks.into_iter().partition(|task| { + task.effective_due + .as_deref() + .and_then(|due| due.get(..10)) + .is_some_and(|due| due < today) + }); + if sort == SortMode::Manual { + apply_today_order(conn, TodayGroup::Overdue, &mut overdue)?; + apply_today_order(conn, TodayGroup::Current, &mut current)?; + } + Ok(TodaySections { overdue, current }) +} + +fn apply_today_order(conn: &Connection, group: TodayGroup, tasks: &mut [TaskItem]) -> Result<()> { + let Some(Value::Array(order)) = register_value(conn, KIND_LIST, INBOX_ID, today_order_field(group))? else { + return Ok(()); + }; + let mut ranks: HashMap = order + .into_iter() + .enumerate() + .filter_map(|(index, id)| id.as_str().map(|id| (id.to_owned(), index))) + .collect(); + // R68: a completed repeat keeps the former occurrence's place while it is visible. + for task in tasks.iter().filter(|task| task.is_log) { + if !ranks.contains_key(&task.id) { + let original: Option = + conn.query_row("SELECT log_of FROM tasks WHERE id = ?1", [&task.id], |row| row.get(0))?; + if let Some(rank) = original.as_ref().and_then(|id| ranks.get(id)).copied() { + ranks.insert(task.id.clone(), rank); + } + } + } + tasks.sort_by_key(|task| ranks.get(&task.id).copied().unwrap_or(usize::MAX)); + Ok(()) +} + fn list_tasks(conn: &Connection, list_id: &str, recent: &Recent) -> Result> { let list = get_list(conn, list_id)?; let order = match list.sort { - SortMode::Manual => "t.pos, t.id", - SortMode::Due => "coalesce(t.due, t.start) IS NULL, coalesce(t.due, t.start), t.pos, t.id", - SortMode::Priority => "t.priority DESC, t.pos, t.id", - SortMode::Title => "t.title COLLATE NOCASE, t.pos, t.id", + SortMode::Manual => "", + SortMode::Due => "coalesce(t.due, t.start) IS NULL, coalesce(t.due, t.start), ", + SortMode::Start => "t.start IS NULL, t.start, ", + SortMode::Priority => "t.priority DESC, ", + SortMode::Title => "t.title COLLATE lists_title, ", }; let (open, settled) = (&recent.open, &recent.settled); let done = if list.show_done { @@ -2668,7 +2811,7 @@ fn list_tasks(conn: &Connection, list_id: &str, recent: &Recent) -> Result serde_json::Value { fn r155_i11_an_export_imported_into_an_empty_device_gives_the_same_data_and_a_second_import_changes_nothing() { let a = device(); let home = a.create_list("Дом".into()).unwrap(); - a.set_list_sort(home.id.clone(), SortMode::Due).unwrap(); + a.set_list_sort(home.id.clone(), SortMode::Start).unwrap(); a.set_list_color(home.id.clone(), "#379417".into()).unwrap(); let old = a.create_list("Архив".into()).unwrap(); let x = a diff --git a/core/tests/store.rs b/core/tests/store.rs index 015ba18c..d60d561a 100644 --- a/core/tests/store.rs +++ b/core/tests/store.rs @@ -81,6 +81,128 @@ fn r2_list_settings_are_stored_and_applied() { assert_eq!(d.list(list.id).unwrap().open_count, 1); } +#[test] +fn r165_list_sort_uses_dates_and_case_insensitive_unicode_titles() { + let d = device(); + let work = d.create_list("Work".into()).unwrap(); + let add = |title: &str, start: Option<&str>| { + d.create_task(NewTask { + title: title.into(), + list_id: Some(work.id.clone()), + start: start.map(str::to_owned), + ..NewTask::default() + }) + .unwrap() + }; + add("Жук", None); + let beta = add("бета", Some("2026-10-05T09:30")); + add("Alpha", Some("2026-10-05T11:00")); + let beta_upper = add("Бета", Some("2026-10-05T09:30")); + add("Ёж", Some("2026-10-05")); + add("apple", None); + + let scope = Scope::List { id: work.id.clone() }; + let manual = view(&d, scope.clone()); + d.set_list_sort(work.id.clone(), SortMode::Start).unwrap(); + assert_eq!(view(&d, scope.clone()), ["Ёж", "бета", "Бета", "Alpha", "Жук", "apple"]); + d.set_list_sort(work.id.clone(), SortMode::Title).unwrap(); + let tasks = d.tasks(scope.clone()).unwrap(); + assert_eq!(titles(&tasks), ["Alpha", "apple", "бета", "Бета", "Ёж", "Жук"]); + assert_eq!((&tasks[2].id, &tasks[3].id), (&beta.id, &beta_upper.id)); + d.set_list_sort(work.id, SortMode::Manual).unwrap(); + assert_eq!(view(&d, scope), manual); +} + +#[test] +fn r165_today_orders_each_group_and_keeps_the_list_order() { + let d = device(); + let (project, child) = project_with(&d, &[("Inherited", None, None)]); + d.set_due(project.id, Some("2026-10-03".into())).unwrap(); + let overdue = d + .create_task(NewTask { + title: "Budget".into(), + start: Some("2026-10-02".into()), + due: Some("2026-10-04".into()), + priority: Some(Priority::High), + ..NewTask::default() + }) + .unwrap(); + let today = add(&d, "Альфа"); + d.set_due(today.id.clone(), Some("2026-10-05".into())).unwrap(); + d.set_priority(today.id.clone(), Priority::High).unwrap(); + let start_only = add(&d, "бета"); + d.set_start(start_only.id.clone(), Some("2026-10-04".into())).unwrap(); + let postponed = add(&d, "Postponed"); + d.set_due(postponed.id.clone(), Some("2026-10-01".into())).unwrap(); + d.set_start(postponed.id, Some("2026-10-06".into())).unwrap(); + let order = || { + let sections = d.today_sections().unwrap(); + ( + sections.overdue.into_iter().map(|t| t.title).collect::>(), + sections.current.into_iter().map(|t| t.title).collect::>(), + ) + }; + let (late, current) = order(); + assert_eq!(d.today_sort().unwrap(), SortMode::Due); + assert_eq!(late, ["Inherited", "Budget"]); + assert_eq!(current, ["бета", "Альфа"]); + assert_eq!(view(&d, Scope::Today), ["Inherited", "Budget", "бета", "Альфа"]); + assert_eq!(d.counts().unwrap().overdue, 2); + + let inbox = view(&d, Scope::Inbox); + assert!(d + .move_today_tasks(TodayGroup::Current, vec![today.id.clone()], None) + .is_err()); + d.set_today_sort(SortMode::Start).unwrap(); + assert_eq!(order().0, ["Budget", "Inherited"]); + assert_eq!(order().1, ["бета", "Альфа"]); + d.set_today_sort(SortMode::Priority).unwrap(); + assert_eq!(order().0, ["Budget", "Inherited"]); + assert_eq!(order().1, ["Альфа", "бета"]); + d.set_today_sort(SortMode::Title).unwrap(); + assert_eq!(order().0, ["Budget", "Inherited"]); + assert_eq!(order().1, ["Альфа", "бета"]); + + d.set_today_sort(SortMode::Manual).unwrap(); + assert!(d + .move_today_tasks(TodayGroup::Overdue, vec![overdue.id.clone()], Some(start_only.id)) + .is_err()); + d.move_today_tasks(TodayGroup::Overdue, vec![overdue.id], None).unwrap(); + assert_eq!(order().0, ["Budget", "Inherited"]); + assert_eq!(order().1, ["бета", "Альфа"]); + d.set_today_sort(SortMode::Due).unwrap(); + assert_eq!(order().0, late); + d.set_today_sort(SortMode::Manual).unwrap(); + assert_eq!(order().0, ["Budget", "Inherited"]); + assert_eq!(d.undo().unwrap(), 1); + assert_eq!(order().0, late); + d.move_today_tasks(TodayGroup::Overdue, vec![child[0].id.clone()], None) + .unwrap(); + assert_eq!(view(&d, Scope::Inbox), inbox); + + d.set_now_for_tests("2026-10-06T10:00"); + let (late, current) = order(); + assert_eq!(late, ["Postponed", "Inherited", "Budget", "Альфа"]); + assert_eq!(current, ["бета"]); +} + +#[test] +fn r165_a_completed_repeat_keeps_its_manual_place_in_today() { + let d = device(); + let morning = add(&d, "Morning"); + d.set_due(morning.id, Some("2026-10-05T08:00".into())).unwrap(); + let repeat = add(&d, "Repeat"); + d.set_due(repeat.id.clone(), Some("2026-10-05T16:00".into())).unwrap(); + d.set_repeat(repeat.id.clone(), Some(weekly())).unwrap(); + d.set_today_sort(SortMode::Manual).unwrap(); + d.move_today_tasks(TodayGroup::Current, vec![repeat.id.clone()], None) + .unwrap(); + d.complete_task(repeat.id).unwrap(); + let tasks = d.today_sections().unwrap().current; + assert_eq!(titles(&tasks), ["Repeat", "Morning"]); + assert!(tasks[0].is_log); +} + #[test] fn r164_a_new_task_gets_the_start_of_the_settings() { let d = device(); diff --git a/core/tests/sync.rs b/core/tests/sync.rs index 4677306a..ffc70e04 100644 --- a/core/tests/sync.rs +++ b/core/tests/sync.rs @@ -239,6 +239,36 @@ fn s4_concurrent_inserts_end_up_in_the_same_order() { assert_eq!(view(&a, Scope::Inbox), view(&b, Scope::Inbox)); } +#[test] +fn s63_today_orders_merge_independently_and_reach_a_new_device() { + let storage = tempfile::tempdir().unwrap(); + let (a, b) = (device(), device()); + let add = |title: &str, due: &str| { + a.create_task(NewTask { + title: title.into(), + due: Some(due.into()), + ..NewTask::default() + }) + .unwrap() + }; + add("Oldest", "2026-10-01"); + let late = add("Late", "2026-10-02"); + add("Morning", "2026-10-05T08:00"); + let today = add("Afternoon", "2026-10-05T14:00"); + a.set_today_sort(SortMode::Manual).unwrap(); + settle(&a, &b, &storage); + a.move_today_tasks(TodayGroup::Overdue, vec![late.id], None).unwrap(); + b.move_today_tasks(TodayGroup::Current, vec![today.id], None).unwrap(); + settle(&a, &b, &storage); + let c = device(); + sync(&c, &storage); + for d in [&a, &b, &c] { + assert_eq!(d.today_sort().unwrap(), SortMode::Manual); + assert_eq!(view(d, Scope::Today), ["Late", "Oldest", "Afternoon", "Morning"]); + assert_eq!(view(d, Scope::Inbox), ["Oldest", "Late", "Morning", "Afternoon"]); + } +} + #[test] fn s5_concurrent_moves_into_each_other_do_not_leave_a_cycle() { let storage = tempfile::tempdir().unwrap(); diff --git a/docs/architecture.md b/docs/architecture.md index da175001..75a2ca19 100644 --- a/docs/architecture.md +++ b/docs/architecture.md @@ -22,6 +22,8 @@ Both Rust workspaces use Jiff for calendar arithmetic and time zone conversion. | macOS | Swift, SwiftUI and AppKit (task list, cards, sidebar) | windows, menu bar, global hotkey, Share Extension, quick entry helper, system calendar events (EventKit) | | Android | Kotlin, Jetpack Compose | screens, share target, Quick Settings tile, shortcuts, system calendar events (`CalendarContract`) | +The Rust core orders tasks and assigns them to Overdue and Today. It uses the same bundled Unicode collation for task titles on each client. + The core is connected to both shells through UniFFI: it generates Swift and Kotlin bindings from annotations in the Rust code. On macOS, while the task table is attached to the window, it watches left mouse-down events in that window for clicks that close an open card (R44). The table handles its own clicks. Scrollbars and popovers keep their own event handling. diff --git a/docs/specs/caldav.md b/docs/specs/caldav.md index c66e1baa..139b2363 100644 --- a/docs/specs/caldav.md +++ b/docs/specs/caldav.md @@ -76,6 +76,7 @@ A run with nothing to transfer costs one request where the server allows it. Eac - An object larger than 32 MB, written by the app before the limit appeared, does not shrink on its own: it is rewritten at the next edit of the task on the device that wrote it. - The servers' own limits on object size have not been checked: a server with a threshold below 28 MB refuses the write, and that is a run error. - A server that does not keep the custom property of the collection (C1) does not carry the deletion of a list either while the calendar is not empty: on the other devices the list stays empty until the calendar disappears. +- The Today sort choice and each group’s manual order travel in the Inbox calendar metadata (S63 in [sync.md](sync.md)). - The shared settings of the app (S32 in [sync.md](sync.md)) are not carried over CalDAV: the time a completed task stays in a view (R68 in [product.md](product.md)) is set on each device. - A foreign calendar becomes a new list after a move: its identifier is computed from the full address (C10), so a move cannot be told from one calendar being deleted and another appearing. The tasks move to a new list with the same name, and the old one is deleted. - The Trash is not shared: a task deleted on one device goes to the Trash on the others too, but each device empties its Trash on its own. For the same reason, what is cleared from "Completed" on one device ends up in the Trash on the others instead of disappearing. diff --git a/docs/specs/product.md b/docs/specs/product.md index ff784a6f..b1a4520f 100644 --- a/docs/specs/product.md +++ b/docs/specs/product.md @@ -16,7 +16,7 @@ Out of scope: shared lists, location reminders, "call/message" actions, duration ### Lists - R1. A task belongs to one list. The "Inbox" list always exists; it cannot be deleted, but it can be hidden (R121); everything without a list goes there, except new tasks and import while "Inbox" is hidden (R40, R121). -- R2. A list has these settings: name, colour, icon, sorting (manual, by due date, by priority, by name), showing completed tasks, defaults for new tasks (priority, due date "today" or empty). The settings sync. +- R2. A list has these settings: name, colour, icon, sorting (manual, by due date, by start date, by priority, by title), showing completed tasks, defaults for new tasks (priority, due date "today" or empty). The settings sync. - R3. Lists are ordered manually; a list can be archived and restored. - R136. macOS, Android and the web interface: deleting a list asks for confirmation (#319, #330): macOS and Android ask "Delete the list “Work” and move its tasks to the trash?" with the name of the list, the web interface asks "Delete the list and move its tasks to the trash?". The list is deleted only after "Delete"; "Cancel", Esc and, on Android, Back change nothing; on Android the settings of the list stay open after a refusal. Deleting a list cannot be undone (R131): its tasks are restored from the trash one by one. - R121. macOS and Android: "Inbox" can be hidden (#255). The "Show Inbox" switch is in the settings, in the "General" section: on macOS in the "Sidebar" group (R93), on Android as a row of its own. The flag is shared by all devices and syncs (S32 in [sync.md](sync.md)). Turning it off opens a dialog with a choice of a list among those not archived. If there are no such lists, the dialog says "To hide Inbox, create a list first.", and the switch stays on. If "Inbox" has open tasks, the dialog names their number and offers two buttons: "Move and hide" and "Hide without moving". Moving sends the open top-level tasks and the open projects of "Inbox", together with their subtasks, to the end of the chosen list; completed tasks stay where they are. Without open tasks there is one button, "Hide". "Cancel" leaves everything as it was. Hiding sets the default list for new tasks (R40) to "last used", and the list chosen in the dialog becomes the last used list on this device. If "Inbox" is open at that moment, the app goes to the chosen list. A single undo (⌘Z on macOS, "Undo" in the snackbar on Android, where the settings close for it) returns the moved tasks to "Inbox", shows "Inbox" again and restores the previous choice of R40. While "Inbox" is hidden, it has no row either in the macOS sidebar or in the Android panel of lists, except while it holds open tasks. Such tasks arrive by sync from a device the flag has not reached yet, from the "Inbox" calendar over CalDAV, or after "Hide without moving"; the row is then shown with a counter and disappears when no open tasks are left in "Inbox". Tasks from "Inbox" are never moved anywhere silently. Import puts tasks without a list into the default list (R40). Turning the switch on returns the row and does not change the choice of R40. The web interface shows "Inbox" as before. @@ -91,10 +91,12 @@ Out of scope: shared lists, location reminders, "call/message" actions, duration - R33. A saved filter is a named view with conditions: date (any, overdue, today, the next N days together with overdue, no date), lists, tags (all at once), priority not lower than a given one, status (open, completed, won't do, all), words in the name or the note. The date of a task of a project is the effective one (R125). All the conditions set must hold. Ready-made presets: "Next 7 days", "Overdue", "High priority", "No date". - R34. Filters sync like the rest of the data. Over CalDAV they are stored as a property of the "Inbox" calendar and are not carried over if the server does not store such properties. - R72. The row of a task in a list on macOS and Android has the same content on both platforms, on Android with the differences of appearance from R159; it is one line of text, and where lists are mixed, two: the name of the list stands under the title. The mark comes first, slightly smaller than the height of the text. On macOS it is a circle and stands at the middle of the title line, so in a row of two lines it goes with the title and not with the list name under it; the project icon and the due date stand on the title line too (#427). On Android it is as in R159. After the mark comes the priority as a thin vertical bar the full height of the row's text: red for high, orange for medium, blue for low; a task without priority has no bar, but the space for it remains, so the titles of all tasks start on one vertical line. On macOS the mark, the bar and the title stand close: 3 points from the mark to the bar and 4 from the bar to the title. There are no "!" signs in the row. The project icon (R30) stands before the title when there is one. After the title come icons without text or numbers, only those the task has, in one order: repeat, note (present when the note is not empty), attachments, subtasks. In a view where lists are mixed — "Today", "Upcoming", "All", a tag view, search, a filter, "Completed", "Won't do", the Trash — the name of the task's list stands under the task title in small type, in the colour of that list, without an icon; for a task of a project (R31) it is followed by a dash and the name of the project in a muted colour: "List – Project". "Inbox" is such a list too: its task shows "Inbox" in the colour of the app, because "Inbox" has no colour of its own. In the view of one list, including "Inbox", and in the view of a project, the name is not repeated. The task title and the line under it are each truncated to their own width and do not crowd each other. The due date stands at the right edge; the overdue due date of an open task is red and always includes the date. A due date taken from the project (R125) stands in the same place in a muted colour with the project icon before it. When the day of the due date is already named by a group heading — "Today" in the "Today" view, a day in "Upcoming" — the day is not written: the time remains, and a due date without time leaves the right side empty. The start date, tags, the subtask counter, the number of attachments and the reminder are not shown in the row: they are in the card of the task. Rows are spaced more loosely than before. In the web interface the mark is a square centred on the height of the row, the priority bar is the same, and under the title, as before, stand the due date, the icons and the name of the list; there too the due date of the project is muted and shown with the project icon. -- R84. In "Today" on macOS and Android tasks are divided into the groups "Overdue" and "Today" when there are overdue tasks. An overdue task is an open task whose due date is before today. The start date does not put a task in the "Overdue" group: a task without a due date or with a due date today or later whose start has already passed stands in the "Today" group. The "Overdue" group and the red counter of "Today" count the same tasks. +- R84. In "Today" on macOS, Android and the web tasks are divided into the groups "Overdue" and "Today" when there are overdue tasks. Of the tasks shown in this view, those with an effective due date before today (R125) appear in Overdue. A task with a past start and no due date appears in Today. The red counter counts open tasks in Overdue. - R73. The title of a task in a list row on macOS and Android takes one line. A title that does not fit the width is truncated at the end with an ellipsis, and the height of the row does not depend on the length of the title. The full title is in the title field of the card of the task: a title that does not fit the width wraps there onto the following lines and is visible in full; the height of the field is not limited. A title has no line breaks: Return in the field ends editing, as before, and pasted text of several lines becomes one line. - R78. "Today" on macOS and Android shows the events of the current day from the system calendars: as a block above the tasks, read-only. The setting "Show calendar events in Today" turns this on; by default it is off, belongs to the device and is not synced. The app asks the system for access to the calendars when the setting is turned on, and not before. The system grants access to all calendars at once; which of them to show is chosen in the settings of the app: under the switch stands the list of system calendars with a checkmark at each. The device stores the cleared checkmarks, so a new calendar is shown until it is cleared. When there is no access, there is no block, and the settings say so in a line that opens the system access settings. An event is one line: a bar in the colour of the calendar, the start time, the title. An all-day event and an event that started before today have no time. Events without time come first, then events with time by start time; on a tie, by title. An event that has already ended today stays in the block until the end of the day. The block is muted: a background with rounded corners across the width of the list, grey text smaller than the task title; an event has no mark. An event is not a task: it cannot be completed, changed or moved, and it is not part of the "Today" counter, search or sync. A tap on Android opens the event in the calendar app. A click on macOS opens "Calendar": there is no documented way to open it at the event or at the day, so the app opens as it is. The block is shown also when there are no tasks for today; when there are no events, there is no block. The block is reread when the system calendars change, when the app returns to the screen and when the next day begins. The other views and the web have no events. +- R165. The header of Inbox, each user-created list and Today has a sort menu that marks the current mode (#491). The five modes are manual, due date, start date, priority and title. Dates sort from earliest to latest. Due date uses the start when there is no due date, and start date uses the start alone. Tasks with no matching date go last. Title uses the same case-insensitive Unicode collation on all devices. Today starts in due-date order. One choice applies within both of its groups, and Overdue always comes first. In manual mode, drag within a group on macOS and Android, or use Move up and Move down on the web. Tasks with no saved position appear after the arranged tasks, in due-date order. A move changes only that group’s arrangement, and Undo restores it. Switching modes preserves each manual arrangement. See S63 in [sync.md](sync.md). + ### Quick entry - R23. One line of text becomes a task. Understood are: `#tag`, `@list`, `!`, `!!`, `!!!` for priority, the words «сегодня» (today), «завтра» (tomorrow), «послезавтра» (the day after tomorrow), days of the week, the date `DD.MM` and `DD.MM.YYYY`, the time `HH:MM`; the same in English. What is recognised is removed from the title and shown as chips before saving; each chip can be removed. @@ -258,6 +260,8 @@ Android: one screen with the task list, a slide-out panel with the lists, and a ## Verification scenarios +- R165: place two tasks in Today, two in Overdue and one with a past start and no due date. Change Today from due date to manual, move a task within Overdue and sync. Each client shows the same two groups with the new order, the start-only task remains in Today and its source list keeps its order. Switch Today to title, then back to manual, and undo a subsequent move. The saved order is restored in both cases. + Scenarios of the core are checked by tests in `core/tests/`; test names match the requirement identifiers where possible. - R5: a task with a start date of tomorrow → the "Today" query does not contain it; after the date changes to today it does. @@ -386,6 +390,8 @@ Scenarios of the core are checked by tests in `core/tests/`; test names match th State as of 2026-10-05, version 0.1.0. +**Task sorting** (R165, #491) — store, sync and web API tests cover the five sort modes, group membership and manual order. The web controls were checked in a headless browser with a start-only task in Today, a manual move in both directions in Overdue and Undo. The macOS boundary test exercises the drop rule. The physical drag gesture on macOS was not checked. + **Core** — all requirements R1–R23, R26, R28, R29 (test `password_is_kept_out_of_the_database_and_asked_for_again_after_restart`) and the rules of [sync.md](sync.md). Verified by the tests `core/tests/store.rs`, `core/tests/sync.rs`, `core/tests/webdav.rs` and the unit tests in `core/src` (`make test`). **macOS** — lists and their settings, tasks expanding in place, subtasks as rows with a title (R10), repeats, tags, attachments, search, the Trash, undo of deletion and completion, the quick-entry window on a global shortcut, the menu bar icon, the "Share" extension, an item in the "Services" menu, reminders, sync settings (WebDAV and folder). Verified by running: the app builds and starts, tasks are created by the link `lists://add`, the quick-entry line is parsed, the window with a list and an expanded task looks as intended, sync with Android through a local WebDAV server works both ways, the password is read from the keychain at start, the Russian localisation is picked up from the system language. Not verified by pressing: the global shortcut, the "Share" extension (the system has registered it), the "Services" menu, notifications, drag and drop. diff --git a/docs/specs/sync.md b/docs/specs/sync.md index 6b9a1e3a..c11a7b55 100644 --- a/docs/specs/sync.md +++ b/docs/specs/sync.md @@ -15,7 +15,7 @@ Entities: `list`, `task`, `attachment`, `settings`. The identifier is a UUID ver Each field of an entity is stored as a separate row: kind, identifier, field name, value in JSON, timestamp. The tables `lists`, `tasks`, `task_tags`, `attachments`, which the queries of the interface use, are derived from these rows and rebuilt for an entity on every change of its fields. Task fields: `list`, `parent`, `title`, `notes`, `start`, `due`, `priority`, `repeat`, `remind`, `pos`, `done`, `wont`, `deleted`, `project`, `log_of`, and one field `tag:` per tag with the value `true` or `false`. The tag field fits the key limit: the prefix `tag:` and the name together are no longer than 200 bytes (S51). -List fields: `name`, `color`, `icon`, `sort`, `show_done`, `default_priority`, `default_due`, `pos`, `archived`, `deleted`. +List fields: `name`, `color`, `icon`, `sort`, `show_done`, `default_priority`, `default_due`, `pos`, `archived`, `deleted`. Inbox also carries `today_sort`, `today_order_overdue` and `today_order_current` (S63). Attachment fields: `task`, `name`, `mime`, `size`, `sha256`, `deleted`. Settings fields: `keep_done`. There is one entity, with the identifier `app`. The `blob` field: `gone` — the content with this hash is deleted from the storage (S48). The identifier is the SHA-256 of the content, not a UUID. @@ -36,6 +36,7 @@ Dates are strings `YYYY-MM-DD` or `YYYY-MM-DDTHH:MM` without a time zone. - S32. Settings shared by all devices are the `settings` entity with the fixed identifier `app`; its fields merge by S2 like any others. There are four fields. `inbox_hidden` — whether "Inbox" is hidden (R121 in [product.md](product.md)): `true` or `false`, without the field — `false`. `new_task_list` — the default list for new tasks (R40): the string `"inbox"`, `"last"` (the last used one) or a list identifier; without the field or with any other value — `"inbox"`. Which list was the last used one is not written to the storage. `new_task_start` — the start date of a new task (R164 in [product.md](product.md)): a number of days from 0 to 365 counted from the day of creation; without the field, with `null` or with any other value — "Never", no start. `keep_done` — how long a completed task stays in the view (R68 in [product.md](product.md)). The value is a number of minutes (0 — "at once", more than 1440 reads as 1440) or a string: a number of seconds with the letter `s` (`"5s"`, `"15s"`; more than a day reads as a day) or `"day"` — until the end of the day. A whole number of minutes is written as a number, so that a version that knows only minutes understands it. While the field is absent or its value cannot be parsed, 5 seconds applies. A version that knows only minutes does not parse the string and applies its own default, 5 minutes; a time chosen in it is written as a number, wins by S2 and applies on all devices as minutes. A version of the app that does not know this entity or field keeps its fields and passes them on, but does not apply them: a version before #255 shows "Inbox" and takes the default list from its own setting on the device. Settings are not transferred through CalDAV. - S33. The outcome "won't do" (R69 in [product.md](product.md)) is the `wont` field next to `done`. When a task is marked, the same moment is written into both fields; the task counts as "won't do" while both fields are set and equal. Completion writes only `done`, reopening clears both fields. The fields merge by S2 separately: if one device completed the task and another, while offline, marked it "won't do", the outcome is decided by the `done` record with the greater timestamp; if both moments fall into the same minute, the task stays "won't do". A version of the app that does not know the `wont` field keeps it and passes it on, and shows the task as completed. Its reopening clears only `done`, and the task is open on all devices; its completing again writes a new moment, which differs from `wont`, and the task is completed on all devices. The exception is completing again in the same minute in which the mark was set: the moments coincide, and the task stays "won't do". Such a version cannot parse a saved filter with the state "won't do" and shows it as a filter without conditions. The storage format number (S14) does not change. - S4. The order within a list and within a parent is set by the `pos` field — a string such that a third value can be built between any two values. With equal `pos`, the order is decided by the identifier. +- S63. The sort choice for Today (`today_sort`) and the manual order of each group (`today_order_overdue` and `today_order_current`) are separate registers of Inbox. The orders contain task identifiers from the group at the time of a move. The view considers only tasks in its current group. An unranked task follows the ranked ones. Each register merges under S2, including through the metadata of the Inbox calendar in CalDAV. Older clients can keep the registers without applying them. - S5. If after a merge the chain of parents forms a cycle, every device breaks it the same way: for the task in the cycle whose `parent` field has the greatest timestamp, the parent counts as empty. The stored fields are not rewritten on merge; the break is written into the field on the next local move of any task, so that the suppressed parent does not "come back to life" after it. - S6. A task whose list is deleted or unknown is shown in "Inbox". - S7. The record of a completed repeat gets an identifier computed from the task identifier and the due date of the repeat. Two devices that completed the same repeat while offline create one record, not two. diff --git a/docs/usage.md b/docs/usage.md index 7a179268..5bc0aac7 100644 --- a/docs/usage.md +++ b/docs/usage.md @@ -8,14 +8,16 @@ A task belongs to one list. Inbox always exists and takes everything that has no People who do not use Inbox can hide it: Settings → General → Show Inbox, on macOS in the Sidebar group. Hiding asks for a list. When Inbox holds open tasks, Move and Hide sends them, with their subtasks, to the end of that list, and Hide Without Moving leaves them where they are. Hiding also sets the list for new tasks to the list used last and makes the chosen list the one used last; Edit → Undo on macOS or Undo in the notice on Android takes all of it back. Hiding needs at least one list that is not archived. The setting syncs to all devices. While Inbox is hidden its row is gone, except when open tasks reach it anyway (from another device, over CalDAV, or after Hide Without Moving): then the row shows with its counter until they are moved out. An import puts tasks without a list into the default list for new tasks. The web interface keeps showing Inbox. -Each list has a name, a colour, an icon, a sort order (manual, by due date, by priority, by title), a switch for showing completed tasks, and defaults for new tasks: a priority and an optional due date of today. Lists can be archived and brought back. These settings sync with the tasks. A list is created with the "+" next to the heading Lists, or from the File menu on macOS, and the lists are put in order by hand. +Each list has a name, a colour, an icon, a sort order (manual, by due date, by start date, by priority, by title), a switch for showing completed tasks, and defaults for new tasks: a priority and an optional due date of today. Lists can be archived and brought back. These settings sync with the tasks. A list is created with the "+" next to the heading Lists, or from the File menu on macOS, and the lists are put in order by hand. + +Use the sort menu in the header of Inbox, a list or Today to choose its order. Today applies the choice within Overdue and Today separately. For manual order, drag tasks within a group on macOS and Android. In Today on the web, use Move up and Move down. The chosen mode and manual order sync. The fixed views next to the lists: | View | Shows | |---|---| | Inbox | tasks without a list | -| Today | tasks due today or earlier, and tasks without a due date whose start date has come; on macOS and Android in two groups, Overdue for the tasks whose due date has passed and Today for the rest | +| Today | tasks due today or earlier, and tasks without a due date whose start date has come; in two groups, Overdue for the tasks whose due date has passed and Today for the rest | | Upcoming | tasks with a future date, by day | | All | every open task | | Completed | finished tasks and the record of each finished repeat, tasks marked "won't do" among them; Clear… at the bottom removes those older than a month, older than a year, or all of them | diff --git a/web/Cargo.lock b/web/Cargo.lock index 24fd817f..330ce6a5 100644 --- a/web/Cargo.lock +++ b/web/Cargo.lock @@ -704,6 +704,31 @@ dependencies = [ "zeroize", ] +[[package]] +name = "icu_collator" +version = "2.3.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "08984ed58ac439ebf3e13d2cf26b0c46a60afcd21721c1d14087c0b240344dda" +dependencies = [ + "icu_collator_data", + "icu_collections", + "icu_locale_core", + "icu_locale_fallback", + "icu_normalizer", + "icu_properties", + "icu_provider", + "smallvec", + "utf16_iter", + "utf8_iter", + "zerovec", +] + +[[package]] +name = "icu_collator_data" +version = "2.3.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f7d7e54efdddeb1208c08dd5d32b53a879ac00d2d3d051b2255fd26821d16368" + [[package]] name = "icu_collections" version = "2.3.0" @@ -726,11 +751,32 @@ checksum = "d56e28588da92eee5c3201a6eff33fabdd49b62269c8938d4ff050ce4d900deb" dependencies = [ "displaydoc", "litemap", + "serde", "tinystr", "writeable", "zerovec", ] +[[package]] +name = "icu_locale_fallback" +version = "2.3.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "251af8e57c9400e3eb58242fe5b8b1152b2a64fdf4cf632f923c38ccee6f2fa9" +dependencies = [ + "icu_locale_core", + "icu_locale_fallback_data", + "icu_provider", + "potential_utf", + "tinystr", + "zerovec", +] + +[[package]] +name = "icu_locale_fallback_data" +version = "2.3.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "decf2a22ec8fa68f1a0c1129a3f8583f8f8bc24e8b9ccbe98ead99f62a4dc3a8" + [[package]] name = "icu_normalizer" version = "2.3.0" @@ -742,6 +788,9 @@ dependencies = [ "icu_properties", "icu_provider", "smallvec", + "utf16_iter", + "utf8_iter", + "write16", "zerovec", ] @@ -780,6 +829,8 @@ checksum = "d27bbb9d3abbefac45d55f647c9de1d44aafcd1186eb91879afef17c396c3e73" dependencies = [ "displaydoc", "icu_locale_core", + "serde", + "stable_deref_trait", "writeable", "yoke", "zerofrom", @@ -931,6 +982,7 @@ dependencies = [ "chacha20poly1305", "flate2", "hmac", + "icu_collator", "jiff", "pulldown-cmark", "roxmltree", @@ -1155,6 +1207,8 @@ version = "0.1.6" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "d83eb9bc6d8e5cf568e7a1101d60ee05e81ed50ea106026f3d18deeb046d7661" dependencies = [ + "serde_core", + "writeable", "zerovec", ] @@ -1669,6 +1723,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "b1e27c91459209c2986af3dcf603a5a74a4368754ce37414f59acc971167f643" dependencies = [ "displaydoc", + "serde_core", "zerovec", ] @@ -1926,12 +1981,27 @@ dependencies = [ "serde", ] +[[package]] +name = "utf16_iter" +version = "1.1.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1c7de35d9d8757dbc1f5125dc8b51438c68b4430546a735c3a9b91aaaaf9a18a" +dependencies = [ + "utf_types", +] + [[package]] name = "utf8_iter" version = "1.0.4" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "b6c140620e7ffbb22c2dee59cafe6084a59b5ffc27a8859a5f0d494b5d52b6be" +[[package]] +name = "utf_types" +version = "1.0.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "3a3b425286980a367278453f3b6d28cdcb134b574e5a35824a6ff5eebad50bb6" + [[package]] name = "uuid" version = "1.29.3" @@ -2146,6 +2216,12 @@ dependencies = [ "primefield", ] +[[package]] +name = "write16" +version = "1.0.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d1890f4022759daae28ed4fe62859b1236caebfc61ede2f63ed4e695f3f6d936" + [[package]] name = "writeable" version = "0.6.4" @@ -2225,6 +2301,7 @@ dependencies = [ "displaydoc", "yoke", "zerofrom", + "zerovec", ] [[package]] @@ -2233,6 +2310,7 @@ version = "0.11.8" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "bb0464e17806c1d976d5cba29399c7f08e516e279e2ba493f63123b5fca67dd8" dependencies = [ + "serde", "yoke", "zerofrom", "zerovec-derive", diff --git a/web/src/index.html b/web/src/index.html index f26500dd..c1fa6709 100644 --- a/web/src/index.html +++ b/web/src/index.html @@ -166,7 +166,7 @@ "No tasks": "Задач нет", "Nothing found": "Ничего не найдено", "Synced": "Синхронизировано", "Sync failed": "Синхронизация не удалась", "waiting": "ожидает отправки", "Deleted": "Удалено", "Undo": "Отменить", "Created": "Создано", "Task completed": "Выполнено", "Moved to the next occurrence": "Перенесено на следующий повтор", "not downloaded yet": "ещё не загружено", "downloading…": "загружается…", "could not download, try later": "не удалось загрузить, попробуйте позже", "Attachments waiting to sync": "Вложения ждут синхронизации", "Download": "Скачать", "Close": "Закрыть", "from": "с", "Delete list": "Удалить список", "Delete this list and move its tasks to the trash?": "Удалить список и отправить его задачи в корзину?", - "Sort": "Сортировка", "Manually": "Вручную", "By due date": "По сроку", "By priority": "По приоритету", "By title": "По названию", "Rename": "Переименовать", "time": "время", + "Sort": "Сортировка", "Manually": "Вручную", "By due date": "По сроку", "By start date": "По дате начала", "By priority": "По приоритету", "By title": "По названию", "Rename": "Переименовать", "time": "время", "Move up": "Переместить выше", "Move down": "Переместить ниже", "Manual order": "Ручной порядок", "Sign in with single sign-on": "Войти через единый вход", "Import…": "Импорт…", "tasks": "задач", "attachments": "вложений", "Projects": "Проекты", "Filters": "Фильтры", "New filter": "Новый фильтр", "Make it a project": "Сделать проектом", "Turn back into a task": "Сделать обычной задачей", "Complete project": "Выполнить проект", "Project completed": "Проект выполнен", "Filter": "Фильтр", "Date": "Дата", "Any": "Любой", "The coming days": "Ближайшие дни", "No date": "Без даты", "Days": "Дней", "Priority at least": "Приоритет не ниже", @@ -210,7 +210,7 @@ "All done for today": "今天的都完成了", "No tasks": "没有任务", "Nothing found": "没有找到结果", "Synced": "已同步", "Sync failed": "同步失败", "waiting": "项等待上传", "Deleted": "已删除", "Undo": "撤销", "Created": "已创建", "Task completed": "任务已完成", "Moved to the next occurrence": "已移到下一次", "not downloaded yet": "尚未下载", "downloading…": "正在下载…", "could not download, try later": "下载失败,请稍后再试", "Attachments waiting to sync": "等待同步的附件", "Download": "下载", "Close": "关闭", "from": "从", "Delete list": "删除清单", "Delete this list and move its tasks to the trash?": "要删除此清单并把其中的任务移到回收站吗?", "Sort": "排序", - "Manually": "手动", "By due date": "按到期日", "By priority": "按优先级", "By title": "按标题", "Rename": "重命名", "time": "时间", "Sign in with single sign-on": "使用单点登录", + "Manually": "手动", "By due date": "按到期日", "By start date": "按开始日期", "By priority": "按优先级", "By title": "按标题", "Rename": "重命名", "time": "时间", "Move up": "上移", "Move down": "下移", "Manual order": "手动排序", "Sign in with single sign-on": "使用单点登录", "Import…": "导入…", "tasks": "任务", "attachments": "附件", "Projects": "项目", "Filters": "筛选器", "New filter": "新建筛选器", "Make it a project": "转为项目", "Turn back into a task": "改回任务", "Complete project": "完成项目", "Project completed": "项目已完成", "Filter": "筛选器", "Date": "日期", "Any": "任意", "The coming days": "未来几天", "No date": "无日期", "Days": "天", "Priority at least": "优先级不低于", "Status": "状态", "Open": "未完成", "Contains": "包含", "Save": "保存", @@ -379,7 +379,7 @@ } // R131: what changes a task can be taken back; the bar comes after every such action but an edit of a text. const UNDONE = new Set(["quickAdd", "addSubtask", "duplicate", "setStart", "setDue", "setRemind", "setPriority", "setRepeat", "addTag", "removeTag", - "complete", "wontDo", "reopen", "delete", "restore", "moveToList", "moveToProject", "setProject", "removeAttachment"]); + "complete", "wontDo", "reopen", "delete", "restore", "moveToList", "moveToProject", "setProject", "removeAttachment", "moveTodayTasks"]); const CREATED = new Set(["quickAdd", "addSubtask", "duplicate"]); const undo = () => call("undo").then(load); const act = async (op, args, note) => { @@ -401,8 +401,8 @@ const tasks = state.tasks, s = state.search ? "search" : state.scope; const runs = (key, title) => { const out = []; for (const x of tasks) { const k = key(x); if (out.length && out.at(-1).key === k) out.at(-1).tasks.push(x); else out.push({ key: k, title: title(k), tasks: [x] }); } return out; }; if (s === "today") { - const late = tasks.filter(x => dayOf(x.effectiveDue || x.effectiveStart || today()) < today()), rest = tasks.filter(x => !late.includes(x)); - return late.length ? [{ key: "late", title: t("Overdue"), bad: true, tasks: late }, { key: "today", title: t("Today"), tasks: rest }].filter(x => x.tasks.length) : [{ key: "today", tasks: rest }]; + const overdue = tasks.filter(x => x.todayGroup === "overdue"), current = tasks.filter(x => x.todayGroup === "current"); + return overdue.length ? [{ key: "overdue", title: t("Overdue"), bad: true, tasks: overdue }, { key: "current", title: t("Today"), tasks: current }].filter(x => x.tasks.length) : [{ key: "current", tasks: current }]; } if (s === "upcoming") return runs(x => dayOf(x.effectiveDue || x.effectiveStart), k => { const d = parseDay(k).toLocaleDateString(locale, { weekday: "long", day: "numeric", month: "long" }); return k === plus(1) ? `${t("Tomorrow")} · ${d}` : d; }); if (s === "all") return runs(x => x.list, listName); @@ -486,7 +486,7 @@ state.more ? [date("Start", "start"), $("span", { class: "chip" }, prio), tag, button("Won't do", "wontDo", "Completed")] : null); } -function taskNode(x, origin) { +function taskNode(x, origin, section, index) { // R118: in the selection mode the whole row only selects; it opens no card and its mark completes nothing. if (state.sel) { const on = state.sel.has(x.id); @@ -518,7 +518,10 @@ open ? null : summary(x, origin))); // The subtasks a search found the task by (R22); an open task shows all of its subtasks instead. const found = !open && x.found && x.found.length ? $("div", { class: "sub" }, x.found.map(s => subLine(s, true))) : null; - return $("div", { class: "task" + (open ? " open" : "") }, row, found, open && state.details[x.id] ? editor(state.details[x.id]) : null); + const reorder = state.scope === "today" && state.overview.todaySort === "manual" && section?.key === x.todayGroup ? $("div", { class: "chips", "aria-label": t("Manual order") }, + $("button", { class: "link", "aria-label": t("Move up"), disabled: index === 0, onclick: () => moveTodayTask(x.id, x.todayGroup, -1) }, "↑ " + t("Move up")), + $("button", { class: "link", "aria-label": t("Move down"), disabled: index === section.tasks.length - 1, onclick: () => moveTodayTask(x.id, x.todayGroup, 1) }, "↓ " + t("Move down"))) : null; + return $("div", { class: "task" + (open ? " open" : "") }, row, reorder, found, open && state.details[x.id] ? editor(state.details[x.id]) : null); } function commit(el, op, id, current) { @@ -762,12 +765,29 @@ function listTools(l) { const sort = $("select", { "aria-label": t("Sort"), onchange: e => act("setListSort", { id: l.id, value: e.target.value }) }, - [["manual", "Manually"], ["due", "By due date"], ["priority", "By priority"], ["title", "By title"]].map(([v, n]) => $("option", { value: v, selected: l.sort === v }, t(n)))); + sortChoices.map(([v, n]) => $("option", { value: v, selected: l.sort === v }, t(n)))); return [$("span", { class: "chip" }, sort), l.id === "inbox" ? null : $("button", { class: "link", onclick: () => { const name = prompt(t("List name"), l.name); if (name && name.trim()) act("renameList", { id: l.id, value: name.trim() }); } }, t("Rename")), l.id === "inbox" ? null : $("button", { class: "link danger", onclick: () => { if (confirm(t("Delete this list and move its tasks to the trash?"))) { state.scope = "inbox"; act("deleteList", { id: l.id }); } } }, t("Delete list"))]; } +const sortChoices = [["manual", "Manually"], ["due", "By due date"], ["start", "By start date"], ["priority", "By priority"], ["title", "By title"]]; + +function todayTools(o) { + const sort = $("select", { "aria-label": t("Sort"), onchange: e => act("setTodaySort", { value: e.target.value }) }, + sortChoices.map(([v, n]) => $("option", { value: v, selected: o.todaySort === v }, t(n)))); + return $("span", { class: "chip" }, sort); +} + +function moveTodayTask(id, group, direction) { + const section = sections().find(s => s.key === group), index = section?.tasks.findIndex(x => x.id === id) ?? -1; + if (!section || index < 0) return; + const target = section.tasks[index + direction]; + if (!target) return; + const after = direction < 0 ? section.tasks[index - 2]?.id || null : target.id; + act("moveTodayTasks", { group, ids: [id], after }, t("Changed")); +} + // The filter form replaces the task list while a filter is being created or edited. function filterForm(f) { const spec = f.spec || {}, due = spec.due || { kind: "any" }; @@ -863,12 +883,13 @@ $("button", { id: "sync", class: o.sync.lastError ? "bad" : "", title: o.sync.lastError || "", onclick: () => call("sync").then(load, load) }, syncText), search), state.filterEdit ? $("div", { id: "tasks" }, filterForm(state.filterEdit)) : state.notifyEdit ? $("div", { id: "tasks" }, notifyForm()) : state.tokensEdit ? $("div", { id: "tasks" }, tokensForm()) : state.exportEdit ? $("div", { id: "tasks" }, exportForm()) : $("div", { id: "tasks" }, state.scope.startsWith("filter:") && !state.search ? $("div", { class: "chips", style: "padding:8px 10px 0" }, $("button", { class: "link", onclick: () => { state.filterEdit = o.filters.find(f => "filter:" + f.id === state.scope); render(); } }, t("Edit"))) : null, - current && !state.search ? $("div", { class: "chips", style: "padding:8px 10px 0" }, listTools(current)) : null, + current && !state.search ? $("div", { class: "chips", style: "padding:8px 10px 0" }, listTools(current)) : + state.scope === "today" && !state.search ? $("div", { class: "chips", style: "padding:8px 10px 0" }, todayTools(o)) : null, // R126 and R32: the project is completed here, and an empty one turns back into a task, since a project is not a row of its list (R120). project && !state.search ? $("div", { class: "chips", style: "padding:8px 10px 0" }, $("button", { class: "link", onclick: () => completeProject(project) }, t("Complete project")), project.subtasks ? null : $("button", { class: "link", onclick: async () => { await call("setProject", { id: project.id, value: false }); state.scope = project.list === "inbox" ? "inbox" : "list:" + project.list; toast(t("Changed"), undo); load(); } }, t("Turn back into a task"))) : null, empty ? $("div", { class: "empty" }, t(state.search ? "Nothing found" : state.scope === "today" ? "All done for today" : "No tasks")) - : secs.map(s => [s.title ? $("div", { class: "section" + (s.bad ? " bad" : "") }, s.title) : null, s.tasks.map(x => taskNode(x, origin))]), + : secs.map(s => [s.title ? $("div", { class: "section" + (s.bad ? " bad" : "") }, s.title) : null, s.tasks.map((x, i) => taskNode(x, origin, s, i))]), state.scope === "trash" && !empty ? $("div", { style: "text-align:right;padding:14px" }, $("button", { class: "link danger", onclick: () => confirm(t("Delete everything in the trash for good?")) && act("emptyTrash") }, t("Empty Trash"))) : null, state.scope === "completed" && !state.search && !empty ? $("div", { style: "text-align:right;padding:14px" }, clearCompleted()) : null), state.sel ? selectionBar() : readOnly() || state.filterEdit || state.notifyEdit || state.tokensEdit || state.exportEdit || state.scope.startsWith("filter:") ? null : $("div", { id: "add" }, $("span", { style: "color:var(--muted)" }, "+"), add)))); diff --git a/web/src/lib.rs b/web/src/lib.rs index 5cabaa7f..bc451b66 100644 --- a/web/src/lib.rs +++ b/web/src/lib.rs @@ -22,7 +22,7 @@ pub use oidc::OidcConfig; use lists_core::{ markdown_layout, AppError, Attachment, AttachmentLimits, FilterSpec, KeepDone, MarkdownAlign, MarkdownKind, - NewTask, Priority, Repeat, Scope, SortMode, Store, SyncConfig, TaskItem, TaskList, DEFAULT_MAX_FILE, + NewTask, Priority, Repeat, Scope, SortMode, Store, SyncConfig, TaskItem, TaskList, TodayGroup, DEFAULT_MAX_FILE, DEFAULT_MAX_TASK, }; use serde_json::{json, Value}; @@ -170,15 +170,6 @@ fn priority_to(p: Priority) -> i64 { } } -fn sort_name(sort: SortMode) -> &'static str { - match sort { - SortMode::Manual => "manual", - SortMode::Due => "due", - SortMode::Priority => "priority", - SortMode::Title => "title", - } -} - fn task_json(t: &TaskItem) -> Value { json!({ "id": t.id, "list": t.list_id, "parent": t.parent_id, "parentTitle": t.parent_title, @@ -246,7 +237,7 @@ fn markdown_json(notes: &str) -> (Value, Value) { fn list_json(l: &TaskList) -> Value { json!({ - "id": l.id, "name": l.name, "color": l.color, "icon": l.icon, "sort": sort_name(l.sort), + "id": l.id, "name": l.name, "color": l.color, "icon": l.icon, "sort": l.sort.as_str(), "showDone": l.show_done, "defaultPriority": priority_to(l.default_priority), "defaultDueToday": l.default_due_today, "archived": l.archived, "open": l.open_count, }) @@ -367,6 +358,7 @@ impl App { "counts": { "inbox": counts.inbox, "today": counts.today, "overdue": counts.overdue, "upcoming": counts.upcoming, "trash": counts.trash }, "sync": { "configured": status.configured, "pending": status.pending, "attachmentsWaiting": status.attachments_waiting, "lastOk": status.last_ok, "lastError": status.last_error }, // Seconds, or "day" for the end of the day (R68). + "todaySort": s.today_sort()?.as_str(), "keepDone": match s.keep_done()? { KeepDone::Seconds { seconds } => json!(seconds), KeepDone::EndOfDay => json!("day"), @@ -574,14 +566,41 @@ impl App { a.get("value").and_then(Value::as_str).unwrap_or_default().to_string(), ) .map(|_| done)?, - "setListSort" => { - let sort = match text_arg(a, "value")?.as_str() { - "due" => SortMode::Due, - "priority" => SortMode::Priority, - "title" => SortMode::Title, - _ => SortMode::Manual, + "setListSort" => s + .set_list_sort(id()?, SortMode::parse(&text_arg(a, "value")?)) + .map(|_| done)?, + "setTodaySort" => { + let key = text_arg(a, "value")?; + let sort = SortMode::parse(&key); + if sort.as_str() != key { + return Err(AppError::invalid("value")); + } + s.set_today_sort(sort).map(|_| done)? + } + "moveTodayTasks" => { + let group = match text_arg(a, "group")?.as_str() { + "overdue" => TodayGroup::Overdue, + "current" => TodayGroup::Current, + _ => return Err(AppError::invalid("group")), + }; + let ids = a + .get("ids") + .and_then(Value::as_array) + .ok_or_else(|| AppError::invalid("ids"))? + .iter() + .map(|value| { + value + .as_str() + .map(str::to_string) + .ok_or_else(|| AppError::invalid("ids")) + }) + .collect::, _>>()?; + let after = match a.get("after") { + None | Some(Value::Null) => None, + Some(Value::String(id)) if !id.is_empty() => Some(id.clone()), + _ => return Err(AppError::invalid("after")), }; - s.set_list_sort(id()?, sort).map(|_| done)? + s.move_today_tasks(group, ids, after).map(|_| done)? } "setListShowDone" => s .set_list_show_done(id()?, a.get("value").and_then(Value::as_bool).unwrap_or(false)) @@ -972,6 +991,20 @@ impl App { Scope::Search { text } => Some(text.clone()), _ => None, }; + if scope == Scope::Today { + let sections = self.store.today_sections()?; + let rows = [("overdue", sections.overdue), ("current", sections.current)] + .into_iter() + .flat_map(|(group, tasks)| { + tasks.into_iter().map(move |task| { + let mut row = task_json(&task); + row["todayGroup"] = json!(group); + row + }) + }) + .collect(); + return Ok(json_reply(200, Value::Array(rows))); + } let mut rows = Vec::new(); for task in self.store.tasks(scope)? { let mut row = task_json(&task); diff --git a/web/tests/api.rs b/web/tests/api.rs index 8f237256..f77632ec 100644 --- a/web/tests/api.rs +++ b/web/tests/api.rs @@ -1943,3 +1943,69 @@ fn r162_the_sidebar_has_the_icons_of_the_apps_and_a_settings_heading() { assert!(!page.contains("text-transform: uppercase")); assert!(page.contains("@media (min-width: 721px) { body { font-size: 14px; } }")); } + +#[test] +fn r165_today_sorting_keeps_overdue_group_first_and_reorders_within_it() { + let web = web(None); + let past_start = call( + &web, + "", + json!({ "op": "quickAdd", "text": "началось", "scope": "inbox" }), + ); + call( + &web, + "", + json!({ "op": "setStart", "id": past_start["id"], "value": "2000-01-01" }), + ); + let beta = call(&web, "", json!({ "op": "quickAdd", "text": "Б", "scope": "inbox" })); + call( + &web, + "", + json!({ "op": "setDue", "id": beta["id"], "value": "2000-01-01" }), + ); + let alpha = call(&web, "", json!({ "op": "quickAdd", "text": "А", "scope": "inbox" })); + call( + &web, + "", + json!({ "op": "setDue", "id": alpha["id"], "value": "2000-01-01" }), + ); + + let overview = get(&web, "", "/api/overview"); + assert_eq!(overview["todaySort"], "due"); + call(&web, "", json!({ "op": "setTodaySort", "value": "title" })); + let tasks = get(&web, "", "/api/tasks?scope=today"); + assert_eq!(tasks[0]["title"], "А"); + assert_eq!(tasks[0]["todayGroup"], "overdue"); + assert_eq!(tasks[1]["title"], "Б"); + assert_eq!(tasks[1]["todayGroup"], "overdue"); + assert_eq!(tasks[2]["title"], "началось"); + assert_eq!(tasks[2]["todayGroup"], "current"); + + call(&web, "", json!({ "op": "setTodaySort", "value": "manual" })); + call( + &web, + "", + json!({ "op": "moveTodayTasks", "group": "overdue", "ids": [beta["id"]], "after": null }), + ); + let moved = get(&web, "", "/api/tasks?scope=today"); + assert_eq!(moved[0]["id"], beta["id"]); + assert_eq!(moved[0]["todayGroup"], "overdue"); + assert_eq!(moved[1]["id"], alpha["id"]); + assert_eq!(moved[2]["todayGroup"], "current"); + call(&web, "", json!({ "op": "undo" })); + assert_eq!(get(&web, "", "/api/tasks?scope=today")[0]["id"], alpha["id"]); + call( + &web, + "", + json!({ "op": "moveTodayTasks", "group": "overdue", "ids": [alpha["id"]], "after": beta["id"] }), + ); + let moved_down = get(&web, "", "/api/tasks?scope=today"); + assert_eq!(moved_down[0]["id"], beta["id"]); + assert_eq!(moved_down[1]["id"], alpha["id"]); + call( + &web, + "", + json!({ "op": "moveTodayTasks", "group": "overdue", "ids": [beta["id"]], "after": null }), + ); + assert_eq!(get(&web, "", "/api/tasks?scope=today")[0]["id"], beta["id"]); +}