Merge #107 into release/v1.4.0

# Conflicts:
#	app/src/main/java/de/jeanlucmakiola/agendula/MainActivity.kt
#	app/src/main/java/de/jeanlucmakiola/agendula/data/prefs/SettingsPrefs.kt
#	app/src/main/java/de/jeanlucmakiola/agendula/domain/SavedFilter.kt
#	app/src/main/java/de/jeanlucmakiola/agendula/ui/edit/TaskEditViewModel.kt
#	app/src/test/java/de/jeanlucmakiola/agendula/ui/edit/TaskEditViewModelTest.kt
This commit is contained in:
makiolaj committed 2026-11-18 19:52:43 +01:00
commit c852e3a8d1
21 files changed
+563 -87

No files matched your search

+4
View File
@@ -36,6 +36,10 @@ All notable changes to this project are documented here. The format follows
month, three months or year, from its view options. The home count and
preview and Upcoming widgets follow; tasks due further ahead stay in All
(#128).
- Default due and start dates for new tasks, under Settings → New task form. A new
task can be due today, tomorrow, the day after, in a week or in a month, and
start today, on its due date, or a day or a week before it. The old "Default
start to today" switch carries over (#107).
## [1.3.2] - 2026-11-13
@@ -27,6 +27,7 @@ import androidx.lifecycle.lifecycleScope
import dagger.hilt.android.AndroidEntryPoint
import de.jeanlucmakiola.agendula.data.di.LaunchHook
import de.jeanlucmakiola.agendula.domain.SmartList
import de.jeanlucmakiola.agendula.domain.smartListNamed
import de.jeanlucmakiola.agendula.ui.imports.importIntentUri
import de.jeanlucmakiola.agendula.ui.navigation.AppShortcuts
import de.jeanlucmakiola.agendula.ui.RootScreen
@@ -203,15 +204,25 @@ class MainActivity : ComponentActivity() {
/**
* The launcher shortcut's, Quick Settings tile's and a widget's "New
* task". [listId] preset the list when it names exactly one, [dueToday]
* the due date for a Today widget; the data URI keeps each widget's
* PendingIntent apart from the others.
* task". [listId] preset the list when it names exactly one, [filterId]
* or [smartList] what a widget showing one fills in; the data URI keeps
* each widget's PendingIntent apart from the others.
*/
fun newTaskIntent(context: Context, listId: Long? = null, dueToday: Boolean = false): Intent {
val path = listOfNotNull(listId?.toString(), "today".takeIf { dueToday }).joinToString("/")
fun newTaskIntent(
context: Context,
listId: Long? = null,
smartList: SmartList? = null,
filterId: Long? = null,
): Intent {
val path = listOfNotNull(
listId?.toString(),
smartList?.name?.lowercase(),
filterId?.let { "filter$it" },
).joinToString("/")
return Intent(ACTION_NEW_TASK, path.ifEmpty { null }?.let { "agendula://newtask/$it".toUri() }, context, MainActivity::class.java)
.putExtra(EXTRA_PRESET_LIST_ID, listId ?: -1L)
.putExtra(EXTRA_DUE_TODAY, dueToday)
.putExtra(EXTRA_SMART_LIST, smartList?.name)
.putExtra(EXTRA_FILTER_ID, filterId ?: -1L)
.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK)
}
@@ -247,13 +258,15 @@ class MainActivity : ComponentActivity() {
when (intent.action) {
ACTION_NEW_TASK -> return NavRequest.NewTask(
listId = intent.getLongExtra(EXTRA_PRESET_LIST_ID, -1L).takeIf { it > 0L },
dueToday = intent.getBooleanExtra(EXTRA_DUE_TODAY, false),
filterId = intent.getLongExtra(EXTRA_FILTER_ID, -1L).takeIf { it > 0L },
// Widgets placed before 1.4 still carry the old flag.
smartList = smartListNamed(intent.getStringExtra(EXTRA_SMART_LIST))
?: SmartList.TODAY.takeIf { intent.getBooleanExtra(EXTRA_DUE_TODAY, false) },
returnHome = true,
)
ACTION_TODAY -> return NavRequest.OpenSmart(SmartList.TODAY)
ACTION_OPEN_BACKUP -> return NavRequest.OpenBackup
ACTION_OPEN_SMART -> intent.getStringExtra(EXTRA_SMART_LIST)
?.let { name -> SmartList.entries.firstOrNull { it.name == name } }
ACTION_OPEN_SMART -> smartListNamed(intent.getStringExtra(EXTRA_SMART_LIST))
?.let { return NavRequest.OpenSmart(it) }
ACTION_OPEN_LIST -> intent.getLongExtra(EXTRA_LIST_ID, -1L).takeIf { it > 0L }
?.let { return NavRequest.OpenList(it) }
@@ -10,9 +10,15 @@ import androidx.datastore.preferences.core.stringPreferencesKey
import androidx.datastore.preferences.core.stringSetPreferencesKey
import de.jeanlucmakiola.agendula.data.tasks.ProviderResolver
import de.jeanlucmakiola.agendula.data.tasks.StorageMode
import de.jeanlucmakiola.agendula.domain.DefaultDueDate
import de.jeanlucmakiola.agendula.domain.DefaultStartDate
import de.jeanlucmakiola.agendula.domain.NewTaskDates
import de.jeanlucmakiola.agendula.domain.SavedFilter
import de.jeanlucmakiola.agendula.domain.newTaskDates
import de.jeanlucmakiola.agendula.domain.Task
import de.jeanlucmakiola.agendula.domain.TaskFilter
import de.jeanlucmakiola.agendula.domain.TaskForm
import de.jeanlucmakiola.agendula.domain.calendarDate
import de.jeanlucmakiola.agendula.domain.TaskFormField
import de.jeanlucmakiola.agendula.domain.TaskReminder
import de.jeanlucmakiola.agendula.domain.TaskSection
@@ -32,6 +38,7 @@ import kotlinx.coroutines.flow.Flow
import kotlinx.coroutines.flow.distinctUntilChanged
import java.time.DayOfWeek
import java.time.ZoneId
import java.time.LocalDate
import kotlinx.coroutines.flow.map
import javax.inject.Inject
import javax.inject.Singleton
@@ -124,8 +131,10 @@ data class Settings(
val pushEnabled: Boolean = true,
/** Lists of the current store whose tasks the smart lists (and their counts) leave out. */
val hiddenFromSmartLists: Set<Long> = emptySet(),
/** Pre-fill a new task's start with today's date. */
val defaultStartToday: Boolean = false,
/** The due date a new task's form starts with. */
val defaultDueDate: DefaultDueDate = DefaultDueDate.NONE,
/** The start date a new task's form starts with. */
val defaultStartDate: DefaultStartDate = DefaultStartDate.NONE,
/** Task-list sections folded away; Done starts folded. */
val collapsedSections: Set<TaskSection> = DEFAULT_COLLAPSED_SECTIONS,
/** How far ahead the Upcoming smart list reaches. */
@@ -163,6 +172,39 @@ data class Settings(
fun hasOwnReminders(listId: Long, allDay: Boolean): Boolean =
listId in (if (allDay) perListAllDayReminderOverride else perListReminderOverride)
/**
* The dates a new task starts with, given the [presetDue] of the view it is
* added from and whether that view would [show] it. A subtask takes no
* default due, which could land after its parent's.
*/
fun defaultNewTaskDates(
today: LocalDate,
now: Instant,
presetDue: LocalDate? = null,
subtask: Boolean = false,
show: (NewTaskDates) -> Boolean = { true },
): NewTaskDates =
newTaskDates(if (subtask) DefaultDueDate.NONE else defaultDueDate, defaultStartDate, presetDue, today, now, show)
/** A title-only task for [listId], optionally under [parentId], with the default dates. */
fun quickTask(
title: String,
listId: Long,
parentId: Long? = null,
now: Instant = Clock.System.now(),
today: LocalDate = now.calendarDate(allDay = false),
): TaskForm {
val dates = defaultNewTaskDates(today, now, subtask = parentId != null)
return TaskForm(
title = title,
listId = listId,
parentId = parentId,
start = dates.start,
due = dates.due,
isAllDay = dates.isAllDay,
)
}
/** Whether [listId] has its own default reminders for timed or all-day tasks. */
fun hasOwnReminders(listId: Long): Boolean =
hasOwnReminders(listId, allDay = false) || hasOwnReminders(listId, allDay = true)
@@ -213,7 +255,11 @@ class SettingsPrefs @Inject constructor(
.mapNotNull { entry -> entry.substringAfter("$mode:", "").toLongOrNull() }
.toSet()
},
defaultStartToday = p[DEFAULT_START_TODAY] ?: false,
defaultDueDate = p[DEFAULT_DUE_DATE]?.let { runCatching { DefaultDueDate.valueOf(it) }.getOrNull() }
?: DefaultDueDate.NONE,
// The "start today" switch of earlier versions carries over until a start is picked.
defaultStartDate = p[DEFAULT_START_DATE]?.let { runCatching { DefaultStartDate.valueOf(it) }.getOrNull() }
?: if (p[DEFAULT_START_TODAY] == true) DefaultStartDate.TODAY else DefaultStartDate.NONE,
collapsedSections = p[COLLAPSED_SECTIONS]
?.mapNotNull { name -> runCatching { TaskSection.valueOf(name) }.getOrNull() }
?.toSet()
@@ -243,7 +289,12 @@ class SettingsPrefs @Inject constructor(
suspend fun setAutofocusTitle(enabled: Boolean) = dataStore.edit { it[AUTOFOCUS_TITLE] = enabled }
suspend fun setDefaultStartToday(enabled: Boolean) = dataStore.edit { it[DEFAULT_START_TODAY] = enabled }
suspend fun setDefaultDueDate(due: DefaultDueDate) = dataStore.edit { it[DEFAULT_DUE_DATE] = due.name }
suspend fun setDefaultStartDate(start: DefaultStartDate) = dataStore.edit {
it[DEFAULT_START_DATE] = start.name
it.remove(DEFAULT_START_TODAY)
}
suspend fun setTimeFormat(pref: TimeFormatPref) = dataStore.edit { it[TIME_FORMAT] = pref.name }
@@ -391,6 +442,8 @@ class SettingsPrefs @Inject constructor(
val PUSH_ENABLED = booleanPreferencesKey("push_enabled")
val SMART_LIST_HIDDEN = stringSetPreferencesKey("smart_list_hidden")
val DEFAULT_START_TODAY = booleanPreferencesKey("default_start_today")
val DEFAULT_START_DATE = stringPreferencesKey("default_start_date")
val DEFAULT_DUE_DATE = stringPreferencesKey("default_due_date")
val COLLAPSED_SECTIONS = stringSetPreferencesKey("collapsed_sections")
val UPCOMING_RANGE = stringPreferencesKey("upcoming_range")
val SAVED_FILTERS = stringPreferencesKey("saved_filters")
@@ -172,6 +172,15 @@ data class Task(
get() = if (occurrenceStart == null) "$taskId" else "$taskId@${occurrenceStart.toEpochMilliseconds()}"
}
/** An open, unsaved task with only these dates, to ask a view whether it would show one. */
fun openTaskDated(start: Instant?, due: Instant?, isAllDay: Boolean): Task = Task(
taskId = 0L, listId = 0L, title = "", description = null, location = null, url = null,
priority = Priority.NONE, status = TaskStatus.NEEDS_ACTION, percentComplete = null,
start = start, due = due, isAllDay = isAllDay, timeZone = null, completedAt = null,
listColor = 0, taskColor = null, listName = null, accountName = null, parentId = null,
isRecurring = false, distanceFromCurrent = null, created = null, lastModified = null,
)
/** Detail bundle: a task, its parent (if it's a subtask), and its direct children. */
data class TaskDetail(
val task: Task,
@@ -0,0 +1,87 @@
package de.jeanlucmakiola.agendula.domain
import java.time.LocalDate
import kotlin.time.Instant
/** The due date a new task starts with, counted from the day it is created. */
enum class DefaultDueDate {
NONE, TODAY, TOMORROW, DAY_AFTER_TOMORROW, NEXT_WEEK, NEXT_MONTH;
fun dateFrom(today: LocalDate): LocalDate? = when (this) {
NONE -> null
TODAY -> today
TOMORROW -> today.plusDays(1)
DAY_AFTER_TOMORROW -> today.plusDays(2)
NEXT_WEEK -> today.plusWeeks(1)
NEXT_MONTH -> today.plusMonths(1)
}
}
/** The start date a new task starts with; all but [NONE] and [TODAY] need a due date. */
enum class DefaultStartDate {
NONE, TODAY, DUE_DATE, DAY_BEFORE_DUE, WEEK_BEFORE_DUE;
val needsDue: Boolean get() = this != NONE && this != TODAY
/** The start for a task due on [due], kept between [today] and [due]. */
fun dateFor(due: LocalDate, today: LocalDate): LocalDate? = when (this) {
NONE -> null
TODAY -> today
DUE_DATE -> due
DAY_BEFORE_DUE -> due.minusDays(1)
WEEK_BEFORE_DUE -> due.minusWeeks(1)
}?.let { minOf(maxOf(it, today), due) }
}
/** A new task's dates; whole-day defaults make it all-day once it has a due date. */
data class NewTaskDates(val start: Instant?, val due: Instant?, val isAllDay: Boolean)
/**
* The dates a new task opens with, given its [dueDate] (a preset or the default)
* and the default [start]. Without a due date only [DefaultStartDate.TODAY]
* applies, as a timed start at [now].
*/
fun datesForDue(dueDate: LocalDate?, start: DefaultStartDate, today: LocalDate, now: Instant): NewTaskDates {
if (dueDate == null) {
return NewTaskDates(start = now.takeIf { start == DefaultStartDate.TODAY }, due = null, isAllDay = false)
}
val startDate = start.dateFor(dueDate, today)
return NewTaskDates(start = startDate?.let(::allDayInstantOf), due = allDayInstantOf(dueDate), isAllDay = true)
}
/**
* A new task's dates from the [due] and [start] defaults, or from [presetDue]
* when there is no default due, or when the view the task is added from would
* [show] it with the preset but not with the default.
*/
fun newTaskDates(
due: DefaultDueDate,
start: DefaultStartDate,
presetDue: LocalDate?,
today: LocalDate,
now: Instant,
show: (NewTaskDates) -> Boolean = { true },
): NewTaskDates {
val preset = datesForDue(presetDue, start, today, now)
val dueDate = due.dateFrom(today) ?: return preset
val dated = datesForDue(dueDate, start, today, now)
return listOf(dated, preset).firstOrNull(show) ?: dated
}
/**
* Whether an open task with these dates shows in [smartList], or passes
* [savedFilter]'s due windows; with neither it shows anywhere.
*/
fun NewTaskDates.showsIn(
smartList: SmartList?,
savedFilter: SavedFilter?,
todayStart: Instant,
todayEnd: Instant,
): Boolean {
val probe = openTaskDated(start, due, isAllDay)
return when {
savedFilter != null -> savedFilter.due.isEmpty() || dueWindowOf(probe, todayStart, todayEnd) in savedFilter.due
smartList != null -> TaskFiltering.matches(probe, TaskFilter.Smart(smartList), todayStart, todayEnd)
else -> true
}
}
@@ -68,6 +68,27 @@ fun dueWindowOf(
}
}
/**
* The due date that keeps a new task in a view of these windows: today, then
* tomorrow; a view that admits undated tasks, or only overdue ones, leaves it empty.
*/
fun Set<DueWindow>.presetDue(today: LocalDate): LocalDate? = when {
isEmpty() || DueWindow.NO_DATE in this -> null
DueWindow.TODAY in this -> today
DueWindow.UPCOMING in this -> today.plusDays(1)
else -> null
}
/** The due windows this smart list shows; empty for the lists that don't go by due date. */
val SmartList.dueWindows: Set<DueWindow>
get() = when (this) {
SmartList.TODAY -> setOf(DueWindow.TODAY)
SmartList.UPCOMING -> setOf(DueWindow.UPCOMING)
SmartList.OVERDUE -> setOf(DueWindow.OVERDUE)
SmartList.NO_DATE -> setOf(DueWindow.NO_DATE)
SmartList.ALL, SmartList.COMPLETED -> emptySet()
}
/** [end] as a local instant: a date without a time is read as the start of its day. */
fun Task.wallClock(end: TaskEnd, zone: ZoneId = ZoneId.systemDefault()): Instant? {
if (hasTime(end)) return valueOf(end)
@@ -83,21 +104,13 @@ data class NewTaskPreset(
val priority: Priority = Priority.NONE,
)
/**
* The preset for a new task in this filter. Due prefers today, then tomorrow;
* a filter that admits undated tasks, or only overdue ones, leaves it empty.
*/
/** The preset for a new task in this filter; its due is [presetDue]. */
fun SavedFilter.newTaskPreset(today: LocalDate): NewTaskPreset = NewTaskPreset(
listIds = listIds,
tags = when {
tagMatch == TagMatch.ALL -> tags.sorted()
else -> listOfNotNull(tags.minOrNull())
},
dueDate = when {
due.isEmpty() || DueWindow.NO_DATE in due -> null
DueWindow.TODAY in due -> today
DueWindow.UPCOMING in due -> today.plusDays(1)
else -> null
},
dueDate = due.presetDue(today),
priority = minPriority,
)
@@ -10,6 +10,9 @@ import kotlin.time.Instant
*/
enum class SmartList { ALL, TODAY, UPCOMING, OVERDUE, NO_DATE, COMPLETED }
/** The smart list called [name]; null for none or an unknown one. */
fun smartListNamed(name: String?): SmartList? = SmartList.entries.firstOrNull { it.name == name }
/** What a task screen is showing: one real list, a smart list, or a tag. */
sealed interface TaskFilter {
data class OfList(val listId: Long) : TaskFilter
@@ -28,4 +28,4 @@ enum class UpcomingRange {
/** Whether [task] is due before [end]; an undated task never is. */
fun dueBefore(task: Task, end: Instant, zone: ZoneId = ZoneId.systemDefault()): Boolean =
task.wallClock(task.due, zone)?.let { it < end } ?: false
task.wallClock(TaskEnd.DUE, zone)?.let { it < end } ?: false
@@ -7,12 +7,12 @@ import de.jeanlucmakiola.agendula.data.tasks.TasksRepository
import de.jeanlucmakiola.agendula.data.tasks.recoveringFromProviderFailure
import de.jeanlucmakiola.agendula.domain.Task
import de.jeanlucmakiola.agendula.domain.TaskDetail
import de.jeanlucmakiola.agendula.domain.TaskForm
import kotlinx.coroutines.ExperimentalCoroutinesApi
import kotlinx.coroutines.flow.MutableStateFlow
import kotlinx.coroutines.flow.SharingStarted
import kotlinx.coroutines.flow.StateFlow
import kotlinx.coroutines.flow.filterNotNull
import kotlinx.coroutines.flow.first
import kotlinx.coroutines.flow.flatMapLatest
import kotlinx.coroutines.flow.map
import kotlinx.coroutines.flow.onStart
@@ -94,14 +94,12 @@ class TaskDetailViewModel @Inject constructor(
runCatching { repository.duplicateTask(task.taskId, task.occurrenceStart) }.onSuccess(onCopied)
}
/** Add a subtask (title only) under the currently-shown task. */
/** Add a subtask by title under the currently-shown task, with the default start. */
fun addSubtask(title: String) = viewModelScope.launch {
val parent = (state.value as? TaskDetailUiState.Content)?.detail?.task ?: return@launch
if (title.isBlank()) return@launch
runCatching {
repository.createTask(
TaskForm(title = title.trim(), listId = parent.listId, parentId = parent.taskId),
)
repository.createTask(settingsPrefs.settings.first().quickTask(title.trim(), parent.listId, parent.taskId))
}
}
}
@@ -31,6 +31,13 @@ import java.time.ZoneId
import de.jeanlucmakiola.agendula.domain.populatedFields
import de.jeanlucmakiola.agendula.domain.htmlToPlainText
import de.jeanlucmakiola.agendula.domain.looksLikeHtml
import de.jeanlucmakiola.agendula.domain.DefaultStartDate
import de.jeanlucmakiola.agendula.domain.allDayInstantOf
import de.jeanlucmakiola.agendula.domain.calendarDate
import de.jeanlucmakiola.agendula.domain.dueWindows
import de.jeanlucmakiola.agendula.domain.showsIn
import de.jeanlucmakiola.floret.time.DayWindow
import de.jeanlucmakiola.agendula.domain.presetDue
import de.jeanlucmakiola.agendula.domain.newTaskPreset
import de.jeanlucmakiola.agendula.domain.normalizeTags
import de.jeanlucmakiola.agendula.domain.tagsInUse
@@ -183,6 +190,9 @@ class TaskEditViewModel @Inject constructor(
/** Sections shown by default (a setting); the rest unfold via [revealField]. */
private var defaultFields: Set<TaskFormField> = emptySet()
/** The default start a new task took, kept counted from its due until the start is picked. */
private var startFollowsDue: DefaultStartDate? = null
/** The settings as the form was bound, for the defaults an all-day switch swaps in. */
private var settings: Settings = Settings()
@@ -208,14 +218,18 @@ class TaskEditViewModel @Inject constructor(
/** The reminders the user picked before clearing the task's last date, until a date comes back. */
private val setAside = mutableListOf<SetAside>()
/** Start a fresh task, optionally pre-selecting a list / parent. */
/**
* Start a fresh task, optionally pre-selecting a list / parent. Added from a
* saved filter or [presetSmartList], it takes the default due date where that
* view still shows it, else a due date that keeps it there.
*/
fun bindNew(
presetListId: Long? = null,
parentId: Long? = null,
initialTitle: String? = null,
presetTag: String? = null,
presetFilterId: Long? = null,
presetDueToday: Boolean = false,
presetSmartList: SmartList? = null,
) {
if (bound) return
bound = true
@@ -227,9 +241,16 @@ class TaskEditViewModel @Inject constructor(
this@TaskEditViewModel.settings = settings
defaultFields = settings.defaultEditFields
val lists = runCatching { repository.taskLists().first() }.getOrElse { emptyList() }
val preset = presetFilterId?.let { settingsPrefs.savedFilter(it).first() }
?.newTaskPreset(LocalDate.now())
val presetDue = preset?.dueDate ?: LocalDate.now().takeIf { presetDueToday }
val filter = presetFilterId?.let { settingsPrefs.savedFilter(it).first() }
val now = Clock.System.now()
val today = now.calendarDate(allDay = false)
val preset = filter?.newTaskPreset(today)
val (todayStart, todayEnd) = DayWindow.today(now, ZoneId.systemDefault())
val presetDue = preset?.dueDate ?: presetSmartList?.dueWindows?.presetDue(today)
val dates = settings.defaultNewTaskDates(today, now, presetDue, subtask = parentId != null) {
it.showsIn(presetSmartList, filter, todayStart, todayEnd)
}
startFollowsDue = settings.defaultStartDate.takeIf { dates.start != null && dates.due != null }
// A read-only or vanished default — or a widget's preset list, if it was
// since deleted or turned read-only — would give the task a list it
// cannot be saved to.
@@ -247,16 +268,9 @@ class TaskEditViewModel @Inject constructor(
autofocusTitle = settings.autofocusTitle,
allDayMinuteOfDay = settings.allDayReminderMinuteOfDay,
listId = defaultList,
// A preset due is all-day, so a default start has to be too, or
// today's start would land after a due of today.
start = when {
!settings.defaultStartToday -> null
presetDue != null -> allDayInstantOf(LocalDate.now())
else -> Clock.System.now()
},
// The same all-day value picking the date in the date field gives.
due = presetDue?.let(::allDayInstantOf),
isAllDay = presetDue != null,
start = dates.start,
due = dates.due,
isAllDay = dates.isAllDay,
untimedEnds = repository.supportsUntimedEnds(),
priority = preset?.priority ?: Priority.NONE,
parentId = parentId,
@@ -279,6 +293,7 @@ class TaskEditViewModel @Inject constructor(
bound = true
editingTaskId = taskId
editingOccurrence = occurrenceStart
startFollowsDue = null
setAside.clear()
viewModelScope.launch {
val settings = settingsPrefs.settings.first()
@@ -405,7 +420,10 @@ class TaskEditViewModel @Inject constructor(
* timed end leaves the other one alone without a time, which is all-day.
*/
private fun onValueChange(end: TaskEnd, value: Instant?) = update { s ->
if (end == TaskEnd.START) startIsDefault = false
if (end == TaskEnd.START) {
startIsDefault = false
startFollowsDue = null
}
val withValue = if (end == TaskEnd.START) s.copy(start = value) else s.copy(due = value)
val loneUntimed = value == null && s.untimed == end.other
if (loneUntimed) {
@@ -430,7 +448,11 @@ class TaskEditViewModel @Inject constructor(
val otherValue = s.valueOf(other)
// A new task's untouched "now" start goes along with a due picked without a time.
val otherFollows = end == TaskEnd.DUE && startIsDefault
if (end == TaskEnd.START) startIsDefault = false
val follow = startFollowsDue.takeIf { end == TaskEnd.DUE }
if (end == TaskEnd.START) {
startIsDefault = false
startFollowsDue = null
}
val allDay = time == null && (otherValue == null || !s.hasTime(other) || !s.untimedEnds || otherFollows)
val value = when {
time != null -> localToInstant(date, time)
@@ -450,8 +472,9 @@ class TaskEditViewModel @Inject constructor(
s.isAllDay -> other.takeIf { otherValue != null && s.untimedEnds }
else -> s.untimed.takeUnless { e -> e == end }
}
val followed = follow?.takeIf { allDay }?.dateFor(date, LocalDate.now())?.let(::allDayInstantOf)
val next = s.copy(
start = if (end == TaskEnd.START) value else otherNext,
start = if (end == TaskEnd.START) value else followed ?: otherNext,
due = if (end == TaskEnd.DUE) value else otherNext,
isAllDay = allDay,
untimed = untimed,
@@ -18,7 +18,7 @@ import androidx.compose.material3.MaterialTheme
import androidx.compose.ui.Modifier
import androidx.compose.ui.unit.IntOffset
import androidx.hilt.lifecycle.viewmodel.compose.hiltViewModel
import de.jeanlucmakiola.agendula.domain.SmartList
import de.jeanlucmakiola.agendula.domain.smartListNamed
import de.jeanlucmakiola.agendula.domain.Task
import kotlin.time.Instant
import androidx.navigation.compose.NavHost
@@ -82,7 +82,12 @@ fun AgendulaNavHost(
nav.navigate(Dest.Settings.buildAccount(navRequest.accountId)) { launchSingleTop = true }
is NavRequest.NewTask ->
nav.navigate(
Dest.TaskEdit.buildNew(presetListId = navRequest.listId, title = navRequest.title, dueToday = navRequest.dueToday),
Dest.TaskEdit.buildNew(
presetListId = navRequest.listId,
title = navRequest.title,
filterId = navRequest.filterId,
smartList = navRequest.smartList,
),
)
is NavRequest.OpenSmart -> nav.navigate(Dest.TaskList.build(TaskFilter.Smart(navRequest.list))) {
launchSingleTop = true
@@ -168,7 +173,7 @@ fun AgendulaNavHost(
presetListId = (filter as? TaskFilter.OfList)?.listId,
tag = (filter as? TaskFilter.Tagged)?.tag,
filterId = (filter as? TaskFilter.Saved)?.id,
dueToday = filter == TaskFilter.Smart(SmartList.TODAY),
smartList = (filter as? TaskFilter.Smart)?.list,
),
)
},
@@ -240,7 +245,7 @@ fun AgendulaNavHost(
val title = args?.getString(Dest.TaskEdit.ARG_TITLE)
val tag = args?.getString(Dest.TaskEdit.ARG_TAG)
val filterId = args?.getLong(Dest.TaskEdit.ARG_FILTER_ID)?.takeIf { it != Dest.NO_ID }
val dueToday = args?.getBoolean(Dest.TaskEdit.ARG_DUE_TODAY) ?: false
val smartList = smartListNamed(args?.getString(Dest.TaskEdit.ARG_SMART_LIST))
val vm: TaskEditViewModel = hiltViewModel()
LaunchedEffect(taskId, presetListId, parentId) {
if (taskId != Dest.NO_ID) {
@@ -252,7 +257,7 @@ fun AgendulaNavHost(
initialTitle = title,
presetTag = tag,
presetFilterId = filterId,
presetDueToday = dueToday,
presetSmartList = smartList,
)
}
}
@@ -120,7 +120,7 @@ object Dest {
/**
* The create / edit form. `taskId` set ([NO_ID] otherwise) ⇒ edit; for a new
* task, `presetListId` / `parentId` optionally seed the form, and `filterId`
* (or `dueToday`, for the Today list) fills it so the task lands in that view.
* (or `smartList`) fills it so the task lands in that view.
*/
object TaskEdit {
const val ARG_TASK_ID = "taskId"
@@ -130,7 +130,7 @@ object Dest {
const val ARG_TITLE = "title"
const val ARG_TAG = "tag"
const val ARG_FILTER_ID = "filterId"
const val ARG_DUE_TODAY = "dueToday"
const val ARG_SMART_LIST = "smartList"
const val route =
"taskEdit?$ARG_TASK_ID={$ARG_TASK_ID}" +
"&$ARG_PRESET_LIST_ID={$ARG_PRESET_LIST_ID}" +
@@ -139,7 +139,7 @@ object Dest {
"&$ARG_TITLE={$ARG_TITLE}" +
"&$ARG_TAG={$ARG_TAG}" +
"&$ARG_FILTER_ID={$ARG_FILTER_ID}" +
"&$ARG_DUE_TODAY={$ARG_DUE_TODAY}"
"&$ARG_SMART_LIST={$ARG_SMART_LIST}"
val arguments = listOf(
navArgument(ARG_TASK_ID) { type = NavType.LongType; defaultValue = NO_ID },
@@ -149,7 +149,7 @@ object Dest {
navArgument(ARG_TITLE) { type = NavType.StringType; nullable = true; defaultValue = null },
navArgument(ARG_TAG) { type = NavType.StringType; nullable = true; defaultValue = null },
navArgument(ARG_FILTER_ID) { type = NavType.LongType; defaultValue = NO_ID },
navArgument(ARG_DUE_TODAY) { type = NavType.BoolType; defaultValue = false },
navArgument(ARG_SMART_LIST) { type = NavType.StringType; nullable = true; defaultValue = null },
)
fun buildEdit(taskId: Long, occurrenceStart: Long? = null): String =
@@ -162,7 +162,7 @@ object Dest {
title: String? = null,
tag: String? = null,
filterId: Long? = null,
dueToday: Boolean = false,
smartList: SmartList? = null,
): String {
val params = buildList {
if (presetListId != null) add("$ARG_PRESET_LIST_ID=$presetListId")
@@ -170,7 +170,7 @@ object Dest {
if (!title.isNullOrBlank()) add("$ARG_TITLE=${android.net.Uri.encode(title)}")
if (!tag.isNullOrBlank()) add("$ARG_TAG=${android.net.Uri.encode(tag)}")
if (filterId != null) add("$ARG_FILTER_ID=$filterId")
if (dueToday) add("$ARG_DUE_TODAY=true")
if (smartList != null) add("$ARG_SMART_LIST=${smartList.name}")
}
return if (params.isEmpty()) "taskEdit" else "taskEdit?${params.joinToString("&")}"
}
@@ -31,13 +31,14 @@ sealed interface NavRequest {
/**
* A new task, optionally titled with text shared from another app, or
* preset to a list — a widget's own add button, when it shows one list —
* or due today, from a Today widget.
* or to the saved filter or smart list a widget shows.
* [returnHome] leaves the app once the form is closed (#93).
*/
data class NewTask(
val title: String? = null,
val listId: Long? = null,
val dueToday: Boolean = false,
val filterId: Long? = null,
val smartList: SmartList? = null,
val returnHome: Boolean = false,
) : NavRequest
@@ -23,6 +23,8 @@ import de.jeanlucmakiola.agendula.data.tasks.recoveringFromProviderFailure
import de.jeanlucmakiola.agendula.data.tasks.transfer.ExternalImport
import de.jeanlucmakiola.agendula.data.tasks.transfer.TransferCounts
import de.jeanlucmakiola.agendula.data.tasks.transfer.TransferResult
import de.jeanlucmakiola.agendula.domain.DefaultDueDate
import de.jeanlucmakiola.agendula.domain.DefaultStartDate
import de.jeanlucmakiola.agendula.domain.TaskFormField
import de.jeanlucmakiola.agendula.domain.TaskList
import de.jeanlucmakiola.floret.reminders.ReminderLead
@@ -263,7 +265,8 @@ class SettingsViewModel @Inject constructor(
fun setReminderDescription(pref: ReminderDescription) = viewModelScope.launch { prefs.setReminderDescription(pref) }
fun setShowAddSubtaskRow(show: Boolean) = viewModelScope.launch { prefs.setShowAddSubtaskRow(show) }
fun setBottomAddBar(enabled: Boolean) = viewModelScope.launch { prefs.setBottomAddBar(enabled) }
fun setDefaultStartToday(enabled: Boolean) = viewModelScope.launch { prefs.setDefaultStartToday(enabled) }
fun setDefaultDueDate(due: DefaultDueDate) = viewModelScope.launch { prefs.setDefaultDueDate(due) }
fun setDefaultStartDate(start: DefaultStartDate) = viewModelScope.launch { prefs.setDefaultStartDate(start) }
/** Toggle whether [field] shows by default on a new task's edit form. */
fun setFormFieldDefault(field: TaskFormField, enabled: Boolean) = viewModelScope.launch {
@@ -25,18 +25,21 @@ import androidx.compose.ui.unit.dp
import de.jeanlucmakiola.agendula.R
import de.jeanlucmakiola.agendula.ui.common.icon
import de.jeanlucmakiola.agendula.ui.common.labelRes
import de.jeanlucmakiola.agendula.domain.DefaultDueDate
import de.jeanlucmakiola.agendula.domain.DefaultStartDate
import de.jeanlucmakiola.agendula.domain.TaskFormField
import de.jeanlucmakiola.agendula.domain.TaskList
import de.jeanlucmakiola.floret.components.CollapsingScaffold
import de.jeanlucmakiola.floret.components.GroupedRow
import de.jeanlucmakiola.floret.components.FullScreenPicker
import de.jeanlucmakiola.floret.components.GroupedSectionHeader
import de.jeanlucmakiola.floret.components.OptionPicker
import de.jeanlucmakiola.floret.components.Position
import de.jeanlucmakiola.floret.components.SelectedCheck
import de.jeanlucmakiola.floret.components.pastelize
import de.jeanlucmakiola.floret.components.positionOf
/** What a new task's edit form starts out as: its fields, its list, and the add affordances. */
/** What a new task's edit form starts out as: its fields, its list, its dates, and the add affordances. */
@Composable
internal fun TaskFormScreen(
state: SettingsUiState,
@@ -45,6 +48,8 @@ internal fun TaskFormScreen(
visible: Boolean,
) {
var showDefaultList by remember { mutableStateOf(false) }
var showDefaultDue by remember { mutableStateOf(false) }
var showDefaultStart by remember { mutableStateOf(false) }
CollapsingScaffold(
title = stringResource(R.string.settings_section_task_form),
@@ -81,6 +86,18 @@ internal fun TaskFormScreen(
position = Position.Top,
onClick = { showDefaultList = true },
)
GroupedRow(
title = stringResource(R.string.settings_default_due_date),
summary = stringResource(defaultDueLabel(state.settings.defaultDueDate)),
position = Position.Middle,
onClick = { showDefaultDue = true },
)
GroupedRow(
title = stringResource(R.string.settings_default_start_date),
summary = defaultStartSummary(state.settings.defaultStartDate, state.settings.defaultDueDate),
position = Position.Middle,
onClick = { showDefaultStart = true },
)
GroupedRow(
title = stringResource(R.string.settings_autofocus_title),
summary = stringResource(R.string.settings_autofocus_title_hint),
@@ -105,18 +122,6 @@ internal fun TaskFormScreen(
},
onClick = { viewModel.setShowAddSubtaskRow(!state.settings.showAddSubtaskRow) },
)
GroupedRow(
title = stringResource(R.string.settings_default_start_today),
summary = stringResource(R.string.settings_default_start_today_hint),
position = Position.Middle,
trailing = {
Switch(
checked = state.settings.defaultStartToday,
onCheckedChange = viewModel::setDefaultStartToday,
)
},
onClick = { viewModel.setDefaultStartToday(!state.settings.defaultStartToday) },
)
GroupedRow(
title = stringResource(R.string.settings_bottom_add_bar),
summary = stringResource(R.string.settings_bottom_add_bar_hint),
@@ -139,6 +144,57 @@ internal fun TaskFormScreen(
onDismiss = { showDefaultList = false },
)
}
if (showDefaultDue) {
OptionPicker(
title = stringResource(R.string.settings_default_due_date),
options = DefaultDueDate.entries,
selected = state.settings.defaultDueDate,
label = { stringResource(defaultDueLabel(it)) },
onSelect = viewModel::setDefaultDueDate,
onDismiss = { showDefaultDue = false },
)
}
if (showDefaultStart) {
OptionPicker(
title = stringResource(R.string.settings_default_start_date),
options = DefaultStartDate.entries,
selected = state.settings.defaultStartDate,
label = { stringResource(defaultStartLabel(it)) },
summary = { if (it.needsDue) stringResource(R.string.settings_default_start_needs_due) else null },
onSelect = viewModel::setDefaultStartDate,
onDismiss = { showDefaultStart = false },
)
}
}
private fun defaultDueLabel(due: DefaultDueDate): Int = when (due) {
DefaultDueDate.NONE -> R.string.settings_default_due_none
DefaultDueDate.TODAY -> R.string.settings_default_due_today
DefaultDueDate.TOMORROW -> R.string.settings_default_due_tomorrow
DefaultDueDate.DAY_AFTER_TOMORROW -> R.string.settings_default_due_day_after_tomorrow
DefaultDueDate.NEXT_WEEK -> R.string.settings_default_due_next_week
DefaultDueDate.NEXT_MONTH -> R.string.settings_default_due_next_month
}
/** The start's label, noting when no default due date gives it one to count from. */
@Composable
private fun defaultStartSummary(start: DefaultStartDate, due: DefaultDueDate): String {
val label = stringResource(defaultStartLabel(start))
return if (start.needsDue && due == DefaultDueDate.NONE) {
stringResource(R.string.settings_default_start_without_due, label)
} else {
label
}
}
private fun defaultStartLabel(start: DefaultStartDate): Int = when (start) {
DefaultStartDate.NONE -> R.string.settings_default_start_none
DefaultStartDate.TODAY -> R.string.settings_default_start_today_option
DefaultStartDate.DUE_DATE -> R.string.settings_default_start_due_date
DefaultStartDate.DAY_BEFORE_DUE -> R.string.settings_default_start_day_before_due
DefaultStartDate.WEEK_BEFORE_DUE -> R.string.settings_default_start_week_before_due
}
/**
@@ -14,7 +14,6 @@ import de.jeanlucmakiola.agendula.domain.Task
import de.jeanlucmakiola.agendula.domain.TaskFilter
import de.jeanlucmakiola.agendula.domain.TaskFiltering
import de.jeanlucmakiola.agendula.domain.tagsInUse
import de.jeanlucmakiola.agendula.domain.TaskForm
import de.jeanlucmakiola.agendula.domain.TaskList
import de.jeanlucmakiola.agendula.domain.TaskSection
import de.jeanlucmakiola.agendula.domain.TaskSortOrder
@@ -337,10 +336,10 @@ class TaskListViewModel @Inject constructor(
}
}
/** Inline "add task" — title only, into [listId]. */
/** Inline "add task" — a title into [listId], with the default dates. */
fun quickAdd(title: String, listId: Long) = viewModelScope.launch {
if (title.isBlank() || listId <= 0L) return@launch
runCatching { repository.createTask(TaskForm(title = title, listId = listId)) }
runCatching { repository.createTask(settingsPrefs.settings.first().quickTask(title, listId)) }
}
private val _listWriteFailure = MutableStateFlow<ListWriteFailure?>(null)
@@ -403,9 +402,7 @@ class TaskListViewModel @Inject constructor(
fun quickAddSubtask(parent: Task, title: String) = viewModelScope.launch {
if (title.isBlank() || parent.listId <= 0L) return@launch
runCatching {
repository.createTask(
TaskForm(title = title.trim(), listId = parent.listId, parentId = parent.taskId),
)
repository.createTask(settingsPrefs.settings.first().quickTask(title.trim(), parent.listId, parent.taskId))
}
}
}
@@ -308,7 +308,12 @@ private fun TaskWidgetHeader(title: String, filter: TaskFilter, singleListId: Lo
icon = ImageProvider(GlanceR.drawable.floret_ic_widget_add),
contentDescription = context.getString(R.string.new_task),
action = actionStartActivity(
MainActivity.newTaskIntent(context, singleListId, dueToday = filter == TaskFilter.Smart(SmartList.TODAY)),
MainActivity.newTaskIntent(
context,
singleListId,
smartList = (filter as? TaskFilter.Smart)?.list,
filterId = (filter as? TaskFilter.Saved)?.id,
),
),
)
}
@@ -40,6 +40,7 @@ import androidx.glance.text.TextAlign
import androidx.glance.text.TextStyle
import de.jeanlucmakiola.agendula.MainActivity
import de.jeanlucmakiola.agendula.R
import de.jeanlucmakiola.agendula.domain.SmartList
import de.jeanlucmakiola.agendula.ui.theme.AgendulaDarkFallback
import de.jeanlucmakiola.agendula.ui.theme.AgendulaLightFallback
import de.jeanlucmakiola.floret.glance.FloretGlanceTheme
@@ -100,7 +101,7 @@ private fun TodayWidgetBody(data: WidgetStatsData?, background: WidgetBackground
WidgetHeaderAction(
icon = ImageProvider(GlanceR.drawable.floret_ic_widget_add),
contentDescription = context.getString(R.string.new_task),
action = actionStartActivity(MainActivity.newTaskIntent(context, dueToday = true)),
action = actionStartActivity(MainActivity.newTaskIntent(context, smartList = SmartList.TODAY)),
)
}
Spacer(GlanceModifier.height(HeaderGap))
+17
View File
@@ -524,8 +524,25 @@
<string name="settings_default_list_first">First available list</string>
<string name="settings_add_subtask_row">Show \"add a subtask\" row</string>
<string name="settings_add_subtask_row_hint">An add field at the end of an expanded task\'s subtasks</string>
<!-- Unused since 1.4; kept while translations still carry them, as an extra translation fails the build. -->
<string name="settings_default_start_today">Default start to today</string>
<string name="settings_default_start_today_hint">Pre-fill a new task\'s start with today\'s date</string>
<string name="settings_default_due_date">Default due date</string>
<string name="settings_default_due_none">No due date</string>
<string name="settings_default_due_today">Today</string>
<string name="settings_default_due_tomorrow">Tomorrow</string>
<string name="settings_default_due_day_after_tomorrow">Day after tomorrow</string>
<string name="settings_default_due_next_week">In a week</string>
<string name="settings_default_due_next_month">In a month</string>
<string name="settings_default_start_date">Default start date</string>
<string name="settings_default_start_none">No start date</string>
<string name="settings_default_start_today_option">Today</string>
<string name="settings_default_start_due_date">On the due date</string>
<string name="settings_default_start_day_before_due">A day before the due date</string>
<string name="settings_default_start_week_before_due">A week before the due date</string>
<string name="settings_default_start_needs_due">Only for a task with a due date</string>
<!-- %1$s is the chosen default start, e.g. "A day before the due date" -->
<string name="settings_default_start_without_due">%1$s · only for a task with a due date</string>
<string name="settings_bottom_add_bar">Bottom quick-add bar</string>
<string name="settings_bottom_add_bar_hint">Add tasks from a bar pinned to the bottom of a list, instead of the floating button</string>
@@ -0,0 +1,105 @@
package de.jeanlucmakiola.agendula.domain
import com.google.common.truth.Truth.assertThat
import org.junit.jupiter.api.Test
import java.time.LocalDate
import de.jeanlucmakiola.floret.time.DayWindow
import java.time.ZoneId
import kotlin.time.Instant
class NewTaskDefaultsTest {
private val today = LocalDate.of(2026, 1, 31)
private val now = Instant.fromEpochMilliseconds(1_769_860_800_000)
private val zone = ZoneId.systemDefault()
/** Today where the view tests run, as the smart lists read the device zone. */
private val localToday = now.calendarDate(allDay = false, zone = zone)
@Test
fun `due defaults count from today`() {
assertThat(DefaultDueDate.NONE.dateFrom(today)).isNull()
assertThat(DefaultDueDate.TODAY.dateFrom(today)).isEqualTo(today)
assertThat(DefaultDueDate.TOMORROW.dateFrom(today)).isEqualTo(LocalDate.of(2026, 2, 1))
assertThat(DefaultDueDate.DAY_AFTER_TOMORROW.dateFrom(today)).isEqualTo(LocalDate.of(2026, 2, 2))
assertThat(DefaultDueDate.NEXT_WEEK.dateFrom(today)).isEqualTo(LocalDate.of(2026, 2, 7))
assertThat(DefaultDueDate.NEXT_MONTH.dateFrom(today)).isEqualTo(LocalDate.of(2026, 2, 28))
}
@Test
fun `a start relative to the due date is all-day`() {
val due = today.plusWeeks(2)
val dates = datesForDue(due, DefaultStartDate.WEEK_BEFORE_DUE, today, now)
assertThat(dates).isEqualTo(NewTaskDates(allDayInstantOf(today.plusWeeks(1)), allDayInstantOf(due), true))
assertThat(datesForDue(due, DefaultStartDate.DUE_DATE, today, now).start).isEqualTo(allDayInstantOf(due))
assertThat(datesForDue(due, DefaultStartDate.DAY_BEFORE_DUE, today, now).start)
.isEqualTo(allDayInstantOf(due.minusDays(1)))
}
@Test
fun `a start counted back from the due date never lands before today`() {
val tomorrow = today.plusDays(1)
assertThat(datesForDue(tomorrow, DefaultStartDate.WEEK_BEFORE_DUE, today, now).start)
.isEqualTo(allDayInstantOf(today))
}
@Test
fun `a start today never lands after the due date`() {
val pastDue = today.minusDays(3)
assertThat(datesForDue(pastDue, DefaultStartDate.TODAY, today, now).start).isEqualTo(allDayInstantOf(pastDue))
}
@Test
fun `without a due date only a start today applies`() {
assertThat(datesForDue(null, DefaultStartDate.TODAY, today, now)).isEqualTo(NewTaskDates(now, null, false))
DefaultStartDate.entries.filter { it.needsDue }.forEach {
assertThat(datesForDue(null, it, today, now)).isEqualTo(NewTaskDates(null, null, false))
}
}
@Test
fun `the default due applies where the view still shows the task, else its preset`() {
val (start, end) = DayWindow.today(now, zone)
val upcoming = SmartList.UPCOMING.dueWindows.presetDue(localToday)
fun inUpcoming(due: DefaultDueDate) = newTaskDates(due, DefaultStartDate.NONE, upcoming, localToday, now) {
it.showsIn(SmartList.UPCOMING, null, start, end)
}.due
assertThat(inUpcoming(DefaultDueDate.NEXT_WEEK)).isEqualTo(allDayInstantOf(localToday.plusWeeks(1)))
assertThat(inUpcoming(DefaultDueDate.TODAY)).isEqualTo(allDayInstantOf(localToday.plusDays(1)))
assertThat(inUpcoming(DefaultDueDate.NONE)).isEqualTo(allDayInstantOf(localToday.plusDays(1)))
val noDate = newTaskDates(DefaultDueDate.TOMORROW, DefaultStartDate.NONE, null, localToday, now) {
it.showsIn(SmartList.NO_DATE, null, start, end)
}
assertThat(noDate.due).isNull()
}
@Test
fun `a task starting today keeps its default due in Today`() {
val (start, end) = DayWindow.today(now, zone)
fun inToday(startDefault: DefaultStartDate) =
newTaskDates(DefaultDueDate.NEXT_WEEK, startDefault, localToday, localToday, now) {
it.showsIn(SmartList.TODAY, null, start, end)
}.due
assertThat(inToday(DefaultStartDate.TODAY)).isEqualTo(allDayInstantOf(localToday.plusWeeks(1)))
assertThat(inToday(DefaultStartDate.NONE)).isEqualTo(allDayInstantOf(localToday))
}
@Test
fun `a saved filter checks only its due windows`() {
val (start, end) = DayWindow.today(now, zone)
val filter = SavedFilter(id = 1L, name = "Soon", due = setOf(DueWindow.TODAY), listIds = setOf(9L))
val dates = newTaskDates(DefaultDueDate.TODAY, DefaultStartDate.NONE, localToday, localToday, now)
assertThat(dates.showsIn(null, filter, start, end)).isTrue()
val later = newTaskDates(DefaultDueDate.TOMORROW, DefaultStartDate.NONE, localToday, localToday, now)
assertThat(later.showsIn(null, filter, start, end)).isFalse()
}
@Test
fun `a view no new task shows in keeps the default due`() {
val (start, end) = DayWindow.today(now, zone)
val dates = newTaskDates(DefaultDueDate.TOMORROW, DefaultStartDate.NONE, null, localToday, now) {
it.showsIn(SmartList.OVERDUE, null, start, end)
}
assertThat(dates.due).isEqualTo(allDayInstantOf(localToday.plusDays(1)))
}
}
@@ -2,13 +2,19 @@ package de.jeanlucmakiola.agendula.ui.edit
import androidx.datastore.core.DataStore
import androidx.datastore.preferences.core.Preferences
import androidx.datastore.preferences.core.booleanPreferencesKey
import androidx.datastore.preferences.core.emptyPreferences
import androidx.datastore.preferences.core.preferencesOf
import com.google.common.truth.Truth.assertThat
import de.jeanlucmakiola.agendula.data.prefs.SettingsPrefs
import de.jeanlucmakiola.agendula.data.tasks.ProviderEnvironment
import de.jeanlucmakiola.agendula.data.tasks.ProviderResolver
import de.jeanlucmakiola.agendula.data.tasks.TasksRepository
import de.jeanlucmakiola.agendula.domain.DefaultDueDate
import de.jeanlucmakiola.agendula.domain.DefaultStartDate
import de.jeanlucmakiola.agendula.domain.Priority
import de.jeanlucmakiola.agendula.domain.SmartList
import de.jeanlucmakiola.agendula.domain.allDayInstantOf
import de.jeanlucmakiola.agendula.domain.Task
import de.jeanlucmakiola.agendula.domain.TaskDetail
import de.jeanlucmakiola.agendula.domain.TaskEnd
@@ -28,6 +34,7 @@ import kotlinx.coroutines.flow.flowOf
import kotlinx.coroutines.runBlocking
import kotlinx.coroutines.test.UnconfinedTestDispatcher
import kotlinx.coroutines.test.resetMain
import kotlinx.coroutines.test.runTest
import kotlinx.coroutines.test.setMain
import org.junit.jupiter.api.AfterEach
import org.junit.jupiter.api.BeforeEach
@@ -61,6 +68,74 @@ class TaskEditViewModelTest {
return TaskEditViewModel(repository, settingsPrefs()).apply { bindEdit(TASK_ID) }
}
@Test
fun `a new task opens with the default due and start dates`() = runTest {
val prefs = settingsPrefs().apply {
setDefaultDueDate(DefaultDueDate.TOMORROW)
setDefaultStartDate(DefaultStartDate.DAY_BEFORE_DUE)
}
val vm = TaskEditViewModel(repository, prefs)
val today = aroundToday { vm.bindNew() }
val state = vm.state.value
assertThat(state.due).isIn(today.map { allDayInstantOf(it.plusDays(1)) })
assertThat(state.start).isIn(today.map { allDayInstantOf(it) })
assertThat(state.isAllDay).isTrue()
assertThat(state.isDirty).isFalse()
}
@Test
fun `the Today list's due wins over the default due`() = runTest {
val prefs = settingsPrefs().apply { setDefaultDueDate(DefaultDueDate.NEXT_WEEK) }
val vm = TaskEditViewModel(repository, prefs)
val today = aroundToday { vm.bindNew(presetSmartList = SmartList.TODAY) }
assertThat(vm.state.value.due).isIn(today.map { allDayInstantOf(it) })
}
@Test
fun `no default due for a task added where it would not show`() = runTest {
val prefs = settingsPrefs().apply { setDefaultDueDate(DefaultDueDate.TOMORROW) }
val vm = TaskEditViewModel(repository, prefs).apply { bindNew(presetSmartList = SmartList.NO_DATE) }
assertThat(vm.state.value.due).isNull()
}
@Test
fun `a default start counted from the due moves with it until picked`() = runTest {
val prefs = settingsPrefs().apply {
setDefaultDueDate(DefaultDueDate.NEXT_MONTH)
setDefaultStartDate(DefaultStartDate.WEEK_BEFORE_DUE)
}
val vm = TaskEditViewModel(repository, prefs).apply { bindNew() }
val day = LocalDate.now()
vm.onWhenChange(TaskEnd.DUE, day.plusDays(10), null)
assertThat(vm.state.value.start).isEqualTo(allDayInstantOf(day.plusDays(3)))
vm.onWhenChange(TaskEnd.START, day.plusDays(1), null)
vm.onWhenChange(TaskEnd.DUE, day.plusDays(20), null)
assertThat(vm.state.value.start).isEqualTo(allDayInstantOf(day.plusDays(1)))
}
@Test
fun `a new subtask takes no default due`() = runTest {
val prefs = settingsPrefs().apply { setDefaultDueDate(DefaultDueDate.TOMORROW) }
val vm = TaskEditViewModel(repository, prefs).apply { bindNew(parentId = TASK_ID) }
assertThat(vm.state.value.due).isNull()
}
@Test
fun `the old start-today switch carries over as a timed start`() {
val prefs = settingsPrefs(preferencesOf(booleanPreferencesKey("default_start_today") to true))
val vm = TaskEditViewModel(repository, prefs).apply { bindNew() }
assertThat(vm.state.value.start).isNotNull()
assertThat(vm.state.value.due).isNull()
assertThat(vm.state.value.isAllDay).isFalse()
}
@Test
fun `clearing the last date drops the reminders and the task saves`() {
val vm = editing()
@@ -228,7 +303,7 @@ class TaskEditViewModelTest {
@Test
fun `a new task's untouched start goes all-day with a due picked without a time`() {
val prefs = settingsPrefs().apply { runBlocking { setDefaultStartToday(true) } }
val prefs = settingsPrefs().apply { runBlocking { setDefaultStartDate(DefaultStartDate.TODAY) } }
val vm = TaskEditViewModel(repository, prefs).apply { bindNew() }
val day = LocalDate.now().plusDays(2)
vm.onWhenChange(TaskEnd.DUE, day, null)
@@ -239,7 +314,7 @@ class TaskEditViewModelTest {
@Test
fun `a start the user picked keeps its time beside a due without one`() {
val prefs = settingsPrefs().apply { runBlocking { setDefaultStartToday(true) } }
val prefs = settingsPrefs().apply { runBlocking { setDefaultStartDate(DefaultStartDate.TODAY) } }
val vm = TaskEditViewModel(repository, prefs).apply { bindNew() }
vm.onWhenChange(TaskEnd.START, LocalDate.now(), LocalTime.of(9, 0))
vm.onWhenChange(TaskEnd.DUE, LocalDate.now().plusDays(2), null)
@@ -370,8 +445,8 @@ class TaskEditViewModelTest {
}
}
private class MemoryDataStore : DataStore<Preferences> {
override val data = MutableStateFlow(emptyPreferences())
private class MemoryDataStore(initial: Preferences = emptyPreferences()) : DataStore<Preferences> {
override val data = MutableStateFlow(initial)
override suspend fun updateData(transform: suspend (t: Preferences) -> Preferences) =
transform(data.value).also { data.value = it }
}
@@ -382,7 +457,15 @@ class TaskEditViewModelTest {
override fun appLabel(packageName: String): String? = null
}
private fun settingsPrefs() = SettingsPrefs(MemoryDataStore(), ProviderResolver(NoProviders))
/** The day before and after [block], which differ only when it runs across midnight. */
private inline fun aroundToday(block: () -> Unit): Set<LocalDate> {
val before = LocalDate.now()
block()
return setOf(before, LocalDate.now())
}
private fun settingsPrefs(initial: Preferences = emptyPreferences()) =
SettingsPrefs(MemoryDataStore(initial), ProviderResolver(NoProviders))
private companion object {
const val TASK_ID = 1L