Fix third review round of repeat from completion (#79)
This commit is contained in:
1 parent
d59d4a3d44
commit
ce39c6aec0
10 files changed
+214
-107
No files matched your search
@@ -34,7 +34,8 @@ object RoomTaskMapper {
|
||||
/**
|
||||
* One occurrence of [row]. [occurrenceStart] is the occurrence's
|
||||
* `RECURRENCE-ID` anchor and `null` for a task that does not recur;
|
||||
* [start] / [due] are that occurrence's resolved times.
|
||||
* [start] / [due] are that occurrence's resolved times. [series] is the
|
||||
* master the series-wide fields come from, an override's rather than its own.
|
||||
*/
|
||||
fun task(
|
||||
row: TaskRow,
|
||||
@@ -42,10 +43,9 @@ object RoomTaskMapper {
|
||||
start: Instant? = row.task.dtstart,
|
||||
due: Instant? = row.task.due,
|
||||
distanceFromCurrent: Int? = null,
|
||||
seriesId: Long? = if (row.task.isRecurring) row.task.id else null,
|
||||
recurrenceRule: String? = row.task.rrule,
|
||||
repeatFromCompletion: Boolean = row.task.repeatsFromCompletion,
|
||||
hasRecurrenceDates: Boolean = !row.task.rdate.isNullOrBlank(),
|
||||
series: TaskEntity = row.task,
|
||||
seriesId: Long? = if (series.isRecurring) series.id else null,
|
||||
repeatFromCompletion: Boolean = series.repeatsFromCompletion,
|
||||
): Task = Task(
|
||||
taskId = row.task.id,
|
||||
listId = row.task.listId,
|
||||
@@ -73,9 +73,9 @@ object RoomTaskMapper {
|
||||
created = row.task.createdAt,
|
||||
lastModified = row.task.lastModified,
|
||||
seriesId = seriesId,
|
||||
recurrenceRule = recurrenceRule,
|
||||
recurrenceRule = series.rrule,
|
||||
repeatFromCompletion = repeatFromCompletion,
|
||||
hasRecurrenceDates = hasRecurrenceDates,
|
||||
hasRecurrenceDates = !series.rdate.isNullOrBlank(),
|
||||
isReadOnly = row.listReadOnly,
|
||||
)
|
||||
|
||||
@@ -107,13 +107,9 @@ object RoomTaskMapper {
|
||||
val TaskEntity.isRecurring: Boolean
|
||||
get() = !rrule.isNullOrBlank() || !rdate.isNullOrBlank()
|
||||
|
||||
/**
|
||||
* The series moves on from its completion rather than its schedule (#79).
|
||||
* Only where a tick moves the series at all: not with `RDATE`s, nor for a
|
||||
* recurring sub-task, which keep the override model.
|
||||
*/
|
||||
/** The series moves on from its completion rather than its schedule (#79), where it [RepeatFromCompletion.applies]. */
|
||||
val TaskEntity.repeatsFromCompletion: Boolean
|
||||
get() = !rrule.isNullOrBlank() && rdate.isNullOrBlank() && parentId == null &&
|
||||
get() = RepeatFromCompletion.applies(rrule, !rdate.isNullOrBlank(), parentId != null) &&
|
||||
RepeatFromCompletion.isSet(unknownProperties)
|
||||
|
||||
/** Completed or cancelled. */
|
||||
|
||||
+45
-33
@@ -33,7 +33,6 @@ import javax.inject.Inject
|
||||
import javax.inject.Singleton
|
||||
import kotlin.time.Clock
|
||||
import kotlin.time.Duration.Companion.days
|
||||
import kotlin.time.Duration.Companion.seconds
|
||||
import kotlin.time.Instant
|
||||
|
||||
/** How far either side of now a series is expanded. */
|
||||
@@ -163,17 +162,12 @@ class RoomTasksDataSource @Inject constructor(
|
||||
}
|
||||
}
|
||||
|
||||
private fun overrideTask(row: TaskRow, anchor: Instant): Task {
|
||||
val master = row.task.masterId?.let { tasks.entity(it) }
|
||||
return RoomTaskMapper.task(
|
||||
row,
|
||||
occurrenceStart = anchor,
|
||||
seriesId = row.task.masterId,
|
||||
recurrenceRule = master?.rrule,
|
||||
repeatFromCompletion = master?.repeatsFromCompletion == true,
|
||||
hasRecurrenceDates = !master?.rdate.isNullOrBlank(),
|
||||
)
|
||||
}
|
||||
private fun overrideTask(row: TaskRow, anchor: Instant): Task = RoomTaskMapper.task(
|
||||
row,
|
||||
occurrenceStart = anchor,
|
||||
series = row.task.masterId?.let { tasks.entity(it) } ?: row.task,
|
||||
seriesId = row.task.masterId,
|
||||
)
|
||||
|
||||
override fun subtasks(parentTaskId: Long): List<Task> {
|
||||
val now = clock.now()
|
||||
@@ -227,10 +221,8 @@ class RoomTasksDataSource @Inject constructor(
|
||||
start = occurrence.start,
|
||||
due = occurrence.due,
|
||||
distanceFromCurrent = occurrence.distance,
|
||||
seriesId = row.task.id,
|
||||
recurrenceRule = row.task.rrule,
|
||||
series = row.task,
|
||||
repeatFromCompletion = fromCompletion,
|
||||
hasRecurrenceDates = !row.task.rdate.isNullOrBlank(),
|
||||
)
|
||||
} else {
|
||||
RoomTaskMapper.task(
|
||||
@@ -646,33 +638,41 @@ class RoomTasksDataSource @Inject constructor(
|
||||
val newAnchor: Instant
|
||||
val spent: Int
|
||||
val toDetach: List<Pair<Instant, TaskEntity>>
|
||||
// Which EXDATEs the moved series keeps; the rest are recorded, to come back with an undo.
|
||||
val keepsExdate: (Instant) -> Boolean
|
||||
// Where the cycle the tick closes ends on the schedule, which measures it for the sub-tasks.
|
||||
var cycleEnd: Instant? = null
|
||||
// Expansion drops the anchor's sub-second part; the series keeps it.
|
||||
val subSecond = spec.anchor - wholeSecond(spec.anchor)
|
||||
if (fromCompletion) {
|
||||
spent = spentBefore(spec, wholeSecond(anchor)) + 1
|
||||
val left = TaskFormWriter.countOf(rule)?.let { it - spent }
|
||||
val next = RepeatFromCompletion.nextAnchor(spec, now, ZoneId.of(zone()), after = anchor)
|
||||
if (next == null || (left != null && left < 1)) return true.also { closeSeries(master, override, close) }
|
||||
newAnchor = next
|
||||
if (left != null && left < 1) return true.also { closeSeries(master, override, close) }
|
||||
val floating = ZoneId.of(zone())
|
||||
// A rule lib-recur cannot follow keeps the override model rather than ending the series.
|
||||
fun nextAfter(at: Instant) = runCatching { RepeatFromCompletion.nextAnchor(spec, now, floating, after = at) }
|
||||
var next = nextAfter(anchor).getOrElse { return false } ?: return true.also { closeSeries(master, override, close) }
|
||||
// An occurrence already ticked on its own is no place to move to.
|
||||
var hops = 0
|
||||
while (closedAt(next) && hops++ < overrides.size) {
|
||||
next = nextAfter(next).getOrElse { return false } ?: return true.also { closeSeries(master, override, close) }
|
||||
}
|
||||
newAnchor = next + subSecond
|
||||
cycleEnd = leading.getOrNull(index + 1)
|
||||
// The old schedule's exceptions go; overrides the new one still generates stay.
|
||||
val others = overrides.values.filter { it.id != override?.id && it.recurrenceId != null }
|
||||
val generated = others.maxOfOrNull { it.recurrenceId!! }?.takeIf { it >= newAnchor }?.let { last ->
|
||||
val moved = spec.copy(rrule = TaskFormWriter.remainingCount(rule, spent), exdate = null, anchor = newAnchor)
|
||||
RecurrenceExpander.expand(
|
||||
moved,
|
||||
ExpansionWindow(from = newAnchor, until = last + 1.seconds, maxOccurrences = SPLIT_COUNT_CEILING),
|
||||
ZoneId.of(zone()),
|
||||
).mapTo(HashSet()) { it.epochSeconds }
|
||||
}.orEmpty()
|
||||
toDetach = others.filter { it.recurrenceId!!.epochSeconds !in generated }.map { it.recurrenceId!! to it }
|
||||
val moved = spec.copy(rrule = TaskFormWriter.remainingCount(rule, spent), exdate = null, anchor = newAnchor)
|
||||
fun onMoved(at: Instant) = at >= newAnchor && RepeatFromCompletion.onSchedule(moved, at, floating)
|
||||
// What the moved schedule still generates stays with it; the rest of the old one goes.
|
||||
keepsExdate = ::onMoved
|
||||
toDetach = overrides.values
|
||||
.filter { it.id != override?.id && it.recurrenceId != null && !onMoved(it.recurrenceId) }
|
||||
.map { it.recurrenceId!! to it }
|
||||
} else {
|
||||
var nextIndex = index + 1
|
||||
while (nextIndex < leading.size && closedAt(leading[nextIndex])) nextIndex++
|
||||
val next = leading.getOrNull(nextIndex) ?: return true.also { closeSeries(master, override, close) }
|
||||
// Expansion drops the anchor's sub-second part; the series keeps it.
|
||||
newAnchor = next + (spec.anchor - wholeSecond(spec.anchor))
|
||||
newAnchor = next + subSecond
|
||||
spent = spentBefore(spec, next)
|
||||
keepsExdate = { it >= newAnchor }
|
||||
toDetach = (leading.take(index) + leading.subList(index + 1, nextIndex)).map { at ->
|
||||
at to overrides.getValue(at.epochSeconds)
|
||||
}
|
||||
@@ -685,7 +685,7 @@ class RoomTasksDataSource @Inject constructor(
|
||||
dtstart = start,
|
||||
due = due,
|
||||
rrule = ruleAfter,
|
||||
exdate = if (fromCompletion) null else TaskFormWriter.valuesFrom(master.exdate, newAnchor, zone),
|
||||
exdate = TaskFormWriter.valuesWhere(master.exdate, zone, keepsExdate),
|
||||
status = TaskStatus.NEEDS_ACTION,
|
||||
percentComplete = null,
|
||||
completedAt = null,
|
||||
@@ -694,7 +694,7 @@ class RoomTasksDataSource @Inject constructor(
|
||||
),
|
||||
)
|
||||
val (reset, resetLists) = resetSubtasks(master, newAnchor, now, cycleEnd ?: newAnchor)
|
||||
val dropped = TaskFormWriter.instantsBefore(master.exdate, if (fromCompletion) Instant.DISTANT_FUTURE else newAnchor, zone)
|
||||
val dropped = TaskFormWriter.instantsWhere(master.exdate, zone) { !keepsExdate(it) }
|
||||
val copyId = if (override != null) {
|
||||
detach(override, now, close)
|
||||
} else {
|
||||
@@ -865,6 +865,16 @@ class RoomTasksDataSource @Inject constructor(
|
||||
val detached = advanced.detachedFor(row.id).map { it.anchor to it.taskId?.let(tasks::entity) }
|
||||
detached.forEach { (at, task) -> if (!returns(task)) back = TaskFormWriter.excepting(back, at, now, zone, dirty = synced) }
|
||||
tasks.update(back)
|
||||
// Moved from completion, the series may have taken overrides the schedule it returns to never generates.
|
||||
back.recurrenceSpec()?.let { spec ->
|
||||
val floating = ZoneId.of(zone())
|
||||
tasks.overrides(back.id)
|
||||
.filter {
|
||||
it.recurrenceId != null && it.recurrenceId >= spec.anchor &&
|
||||
!RepeatFromCompletion.onSchedule(spec.copy(exdate = null), it.recurrenceId, floating)
|
||||
}
|
||||
.forEach { detach(it, now) }
|
||||
}
|
||||
detached.forEach { (at, task) -> if (returns(task)) toOverride(task!!, back, at, now) }
|
||||
advanced.delete(row.id)
|
||||
val plain = reopened.status == TaskStatus.NEEDS_ACTION && reopened.percentComplete == null
|
||||
@@ -964,6 +974,8 @@ class RoomTasksDataSource @Inject constructor(
|
||||
exdate = null,
|
||||
href = null,
|
||||
etag = null,
|
||||
// The series' own setting, not the occurrence's.
|
||||
unknownProperties = RepeatFromCompletion.withoutMarker(master.unknownProperties),
|
||||
)
|
||||
|
||||
/**
|
||||
|
||||
@@ -76,7 +76,7 @@ object TaskFormWriter {
|
||||
* cannot (see [repeatsFromCompletion]). Only ever a master or a
|
||||
* plain task: an override carries no rule of its own.
|
||||
*/
|
||||
fun withRule(current: TaskEntity, rrule: String?, fromCompletion: Boolean = false): TaskEntity {
|
||||
fun withRule(current: TaskEntity, rrule: String?, fromCompletion: Boolean): TaskEntity {
|
||||
val rule = rrule?.trim()?.removePrefix("RRULE:")?.ifEmpty { null }
|
||||
if (current.masterId != null) return current
|
||||
val ruled = when {
|
||||
@@ -85,7 +85,7 @@ object TaskFormWriter {
|
||||
rule == null -> current.copy(rrule = null, rdate = null, exdate = null)
|
||||
else -> current.copy(rrule = rule)
|
||||
}
|
||||
val flagged = rule != null && fromCompletion && ruled.parentId == null && ruled.rdate.isNullOrBlank()
|
||||
val flagged = fromCompletion && RepeatFromCompletion.applies(rule, !ruled.rdate.isNullOrBlank(), ruled.parentId != null)
|
||||
if (RepeatFromCompletion.isSet(ruled.unknownProperties) == flagged) return ruled
|
||||
return ruled.copy(unknownProperties = RepeatFromCompletion.applied(ruled.unknownProperties, flagged))
|
||||
}
|
||||
@@ -129,14 +129,18 @@ object TaskFormWriter {
|
||||
fun valuesBefore(values: String?, cut: Instant, zone: String): String? =
|
||||
mapValues(values, zone) { it.takeIf { at -> at < cut } }
|
||||
|
||||
/** The instants of an `EXDATE`/`RDATE` list before [cut]; values it cannot read are left out. */
|
||||
fun instantsBefore(values: String?, cut: Instant, zone: String): List<Instant> =
|
||||
parsed(values, zone).mapNotNull { it.second }.filter { it < cut }
|
||||
|
||||
/** The values of an `EXDATE`/`RDATE` list at or after [cut]. */
|
||||
fun valuesFrom(values: String?, cut: Instant, zone: String): String? =
|
||||
mapValues(values, zone) { it.takeIf { at -> at >= cut } }
|
||||
|
||||
/** The values of an `EXDATE`/`RDATE` list [keep] takes; values it cannot read stay. */
|
||||
fun valuesWhere(values: String?, zone: String, keep: (Instant) -> Boolean): String? =
|
||||
mapValues(values, zone) { it.takeIf(keep) }
|
||||
|
||||
/** The instants of an `EXDATE`/`RDATE` list [take] takes; values it cannot read are left out. */
|
||||
fun instantsWhere(values: String?, zone: String, take: (Instant) -> Boolean): List<Instant> =
|
||||
parsed(values, zone).mapNotNull { it.second }.filter(take)
|
||||
|
||||
private fun mapValues(values: String?, zone: String, map: (Instant) -> Instant?): String? {
|
||||
if (values == null) return null
|
||||
return parsed(values, zone).mapNotNull { (raw, at) ->
|
||||
|
||||
+103
-33
@@ -1,10 +1,14 @@
|
||||
package de.jeanlucmakiola.agendula.domain.recurrence
|
||||
|
||||
import de.jeanlucmakiola.agendula.domain.ical.ICalParser
|
||||
import org.dmfs.rfc5545.DateTime
|
||||
import org.dmfs.rfc5545.recur.RecurrenceRule
|
||||
import java.time.LocalDateTime
|
||||
import java.time.ZoneId
|
||||
import java.time.ZoneOffset
|
||||
import java.util.TimeZone
|
||||
import kotlin.time.Duration.Companion.days
|
||||
import kotlin.time.Duration.Companion.seconds
|
||||
import kotlin.time.Instant
|
||||
|
||||
/**
|
||||
@@ -26,14 +30,33 @@ object RepeatFromCompletion {
|
||||
/** Only bounds the search for the next occurrence, so a rule that never fires again cannot hold a tick for long. */
|
||||
private val LOOKAHEAD = (366 * 100).days
|
||||
|
||||
private val SUB_DAY = setOf("HOURLY", "MINUTELY", "SECONDLY")
|
||||
/** Bounds stepping past the occurrence ticked. */
|
||||
private const val MAX_STEPS = 100_000
|
||||
|
||||
private val SUB_DAY_SECONDS = mapOf("HOURLY" to 3600L, "MINUTELY" to 60L, "SECONDLY" to 1L)
|
||||
private val CALENDAR_FREQS = setOf("DAILY", "WEEKLY", "MONTHLY", "YEARLY")
|
||||
|
||||
/**
|
||||
* Whether a task can repeat from completion: only where a tick moves its
|
||||
* series on — one without `RDATE`s, and not a sub-task's.
|
||||
*/
|
||||
fun possible(hasRecurrenceDates: Boolean, isSubtask: Boolean): Boolean = !hasRecurrenceDates && !isSubtask
|
||||
|
||||
/** [possible], for a task that has a rule [rrule]. */
|
||||
fun applies(rrule: String?, hasRecurrenceDates: Boolean, isSubtask: Boolean): Boolean =
|
||||
!rrule.isNullOrBlank() && possible(hasRecurrenceDates, isSubtask)
|
||||
|
||||
/** Whether the stored residue [residue] marks its series as repeating from completion. */
|
||||
fun isSet(residue: String?): Boolean {
|
||||
if (residue == null || !residue.contains(PROPERTY, ignoreCase = true)) return false
|
||||
// Parsed as VTodoMapper parses the residue: folded lines joined, nested components their own.
|
||||
val parsed = runCatching { ICalParser.parse("BEGIN:VTODO\r\n$residue\r\nEND:VTODO\r\n") }.getOrNull() ?: return false
|
||||
return parsed.properties(PROPERTY).any { it.value.trim().equals(COMPLETION, ignoreCase = true) }
|
||||
var depth = 0
|
||||
return ICalParser.unfold(residue).any { line ->
|
||||
when {
|
||||
line.startsWith("BEGIN:", ignoreCase = true) -> { depth++; false }
|
||||
line.startsWith("END:", ignoreCase = true) -> { depth--; false }
|
||||
else -> depth == 0 && isMarker(line) && line.substringAfter(':').trim().equals(COMPLETION, ignoreCase = true)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/** [residue] with the marker set or cleared; null once nothing is left. */
|
||||
@@ -61,13 +84,16 @@ object RepeatFromCompletion {
|
||||
}
|
||||
|
||||
/**
|
||||
* The anchor [spec]'s series moves to once completed at [completedAt]: the
|
||||
* first occurrence of its rule after the day it was completed, at the
|
||||
* series' own time of day — or, for a rule repeating within a day, after the
|
||||
* completion itself. Ticked early, it is still the first such occurrence
|
||||
* after [after], the occurrence ticked, so a tick always moves the series
|
||||
* on. `COUNT` is the caller's to spend. Null when the rule has nothing
|
||||
* left, an `UNTIL` passed, or there is no `RRULE`.
|
||||
* The anchor [spec]'s series moves to once completed at [completedAt],
|
||||
* counted from the day it was completed at the series' own time of day —
|
||||
* or, for a rule repeating within a day, from the completion itself.
|
||||
*
|
||||
* A plain rule steps its `INTERVAL` on from there, the last day of a short
|
||||
* month standing in for a day it lacks, as tasks.org does. A rule with
|
||||
* `BY…` parts takes its first match after all but the last step. Ticked
|
||||
* early, the series still moves past [after], the occurrence ticked.
|
||||
* `COUNT` is the caller's to spend. Null when an `UNTIL` passed, the rule
|
||||
* has nothing left, or there is no `RRULE`.
|
||||
*
|
||||
* [floatingZone] is the user's zone: the day an all-day series was
|
||||
* completed on, and the zone of a timed series without one of its own.
|
||||
@@ -76,29 +102,73 @@ object RepeatFromCompletion {
|
||||
val parts = spec.rrule?.trim()?.removePrefix("RRULE:")?.split(';')
|
||||
?.map(String::trim)?.filter(String::isNotEmpty)
|
||||
?.takeIf { it.isNotEmpty() } ?: return null
|
||||
val freq = parts.firstOrNull { it.substringBefore('=').equals("FREQ", ignoreCase = true) }
|
||||
?.substringAfter('=')?.trim()?.uppercase() ?: return null
|
||||
val rule = parts.filterNot { it.substringBefore('=').trim().equals("COUNT", ignoreCase = true) }.joinToString(";")
|
||||
val zone = if (spec.isAllDay) floatingZone else dateZone(false, spec.timeZone, floatingZone)
|
||||
val completedDay = java.time.Instant.ofEpochMilli(completedAt.toEpochMilliseconds()).atZone(zone).toLocalDate()
|
||||
val base = when {
|
||||
freq in SUB_DAY -> Instant.fromEpochSeconds(completedAt.epochSeconds)
|
||||
spec.isAllDay -> Instant.fromEpochSeconds(completedDay.atStartOfDay(ZoneOffset.UTC).toEpochSecond())
|
||||
else -> {
|
||||
val time = java.time.Instant.ofEpochSecond(spec.anchor.epochSeconds).atZone(zone).toLocalTime()
|
||||
Instant.fromEpochSeconds(LocalDateTime.of(completedDay, time).atZone(zone).toEpochSecond())
|
||||
}
|
||||
fun value(key: String) = parts.firstOrNull { it.substringBefore('=').trim().equals(key, ignoreCase = true) }
|
||||
?.substringAfter('=')?.trim()
|
||||
val freq = value("FREQ")?.uppercase()?.takeIf { it in CALENDAR_FREQS || it in SUB_DAY_SECONDS } ?: return null
|
||||
val interval = (value("INTERVAL")?.toIntOrNull() ?: 1).coerceAtLeast(1)
|
||||
val byParts = parts.any { it.substringBefore('=').trim().uppercase().startsWith("BY") }
|
||||
|
||||
// An all-day series' dates are UTC midnights; the user's zone says which day it is.
|
||||
val zone = if (spec.isAllDay) ZoneOffset.UTC else dateZone(false, spec.timeZone, floatingZone)
|
||||
val dayZone = if (spec.isAllDay) floatingZone else zone
|
||||
val completedDay = java.time.Instant.ofEpochMilli(completedAt.toEpochMilliseconds()).atZone(dayZone).toLocalDate()
|
||||
val base: LocalDateTime = when {
|
||||
freq in SUB_DAY_SECONDS -> LocalDateTime.ofInstant(java.time.Instant.ofEpochSecond(completedAt.epochSeconds), zone)
|
||||
spec.isAllDay -> completedDay.atStartOfDay()
|
||||
else -> LocalDateTime.of(completedDay, java.time.Instant.ofEpochSecond(spec.anchor.epochSeconds).atZone(zone).toLocalTime())
|
||||
}
|
||||
val floor = after?.let { maxOf(base, Instant.fromEpochSeconds(it.epochSeconds)) } ?: base
|
||||
val fresh = spec.copy(rrule = rule, rdate = null, exdate = null, anchor = base)
|
||||
// lib-recur gives up on a rule that keeps matching nothing; that rule has nothing left.
|
||||
return runCatching {
|
||||
RecurrenceExpander.expand(
|
||||
fresh,
|
||||
ExpansionWindow(from = floor, until = floor + LOOKAHEAD, maxOccurrences = 2),
|
||||
floatingZone,
|
||||
)
|
||||
}.getOrDefault(emptyList()).firstOrNull { it > floor }
|
||||
fun steps(n: Int): LocalDateTime = when (freq) {
|
||||
"DAILY" -> base.plusDays(n.toLong())
|
||||
"WEEKLY" -> base.plusWeeks(n.toLong())
|
||||
"MONTHLY" -> base.plusMonths(n.toLong())
|
||||
"YEARLY" -> base.plusYears(n.toLong())
|
||||
else -> base.plusSeconds(n * SUB_DAY_SECONDS.getValue(freq))
|
||||
}
|
||||
fun LocalDateTime.instant() = Instant.fromEpochSeconds(atZone(zone).toEpochSecond())
|
||||
val floor = after?.let { Instant.fromEpochSeconds(it.epochSeconds) }
|
||||
|
||||
if (!byParts) {
|
||||
val until = untilOf(parts.joinToString(";"), zone)
|
||||
var k = 1
|
||||
var candidate = steps(interval).instant()
|
||||
while (floor != null && candidate <= floor && k < MAX_STEPS) candidate = steps(interval * ++k).instant()
|
||||
return candidate.takeUnless { until != null && it > until }
|
||||
}
|
||||
val search = parts.filterNot {
|
||||
val key = it.substringBefore('=').trim()
|
||||
key.equals("COUNT", ignoreCase = true) || key.equals("INTERVAL", ignoreCase = true)
|
||||
}.joinToString(";")
|
||||
val from = maxOf(steps(interval - 1).instant(), floor ?: base.instant())
|
||||
val fresh = spec.copy(rrule = search, rdate = null, exdate = null, anchor = base.instant())
|
||||
return RecurrenceExpander.expand(
|
||||
fresh,
|
||||
ExpansionWindow(from = from, until = from + LOOKAHEAD, maxOccurrences = 2),
|
||||
floatingZone,
|
||||
).firstOrNull { it > from }
|
||||
}
|
||||
|
||||
/** Whether [spec]'s schedule has an occurrence at [at], to the second. */
|
||||
fun onSchedule(spec: RecurrenceSpec, at: Instant, floatingZone: ZoneId): Boolean {
|
||||
val second = Instant.fromEpochSeconds(at.epochSeconds)
|
||||
return RecurrenceExpander.expand(spec, ExpansionWindow(from = second, until = second + 1.seconds, maxOccurrences = 1), floatingZone)
|
||||
.isNotEmpty()
|
||||
}
|
||||
|
||||
/** The last instant [rule]'s `UNTIL` admits, read as [RecurrenceExpander] reads it; null without one. */
|
||||
private fun untilOf(rule: String, zone: ZoneId): Instant? {
|
||||
val until = runCatching { RecurrenceRule(rule).until }.getOrNull() ?: return null
|
||||
if (!until.isFloating) return Instant.fromEpochMilliseconds(until.timestamp)
|
||||
val date = until.isAllDay
|
||||
val local = DateTime(
|
||||
TimeZone.getTimeZone(zone),
|
||||
until.year,
|
||||
until.month,
|
||||
until.dayOfMonth,
|
||||
if (date) 23 else until.hours,
|
||||
if (date) 59 else until.minutes,
|
||||
if (date) 59 else until.seconds,
|
||||
)
|
||||
return Instant.fromEpochMilliseconds(local.timestamp)
|
||||
}
|
||||
|
||||
/** Whether [line] is a [PROPERTY] content line. */
|
||||
|
||||
@@ -74,9 +74,9 @@ private enum class RecurrenceEndMode { Never, Until, Count }
|
||||
* [current] is the bare RRULE value (or null for none); [startDate] anchors the
|
||||
* "Next: …" previews — for a task, its start date or else its due date.
|
||||
* [onSelect] gets the new RRULE value, or null for "Does not repeat".
|
||||
* [fromCompletion], when not null, offers "Repeat from" (#79): below a chosen
|
||||
* rule it applies at once through [onFromCompletionChange], in the custom step
|
||||
* together with its rule on OK.
|
||||
* [fromCompletion], when not null, offers "Repeat from" (#79): below the
|
||||
* presets it applies at once through [onFromCompletionChange], in the custom
|
||||
* step together with its rule on OK.
|
||||
*/
|
||||
@Composable
|
||||
fun RecurrencePicker(
|
||||
@@ -176,8 +176,8 @@ fun RecurrencePicker(
|
||||
customMode = true
|
||||
},
|
||||
)
|
||||
// Applies at once, to the rule already chosen.
|
||||
if (current != null) fromCompletion?.let { RepeatFromSection(it, onFromCompletionChange) }
|
||||
// Applies at once: to the rule already chosen, or to the one picked next.
|
||||
fromCompletion?.let { RepeatFromSection(it, onFromCompletionChange) }
|
||||
} else {
|
||||
Column(modifier = Modifier.fillMaxWidth()) {
|
||||
// Live read-out of exactly what OK would save; minLines keeps the
|
||||
|
||||
@@ -420,7 +420,7 @@ private fun EditContent(
|
||||
)
|
||||
Text(
|
||||
text = stringResource(
|
||||
if (state.repeatsFromCompletion) {
|
||||
if (state.savesFromCompletion) {
|
||||
R.string.recurrence_from_completion_note
|
||||
} else {
|
||||
R.string.edit_recurrence_label
|
||||
@@ -794,7 +794,7 @@ private fun EditContent(
|
||||
firstDayOfWeek = LocalFirstDayOfWeek.current.toKotlinDayOfWeek(),
|
||||
onSelect = { viewModel.onRecurrenceChange(it); showRecurrencePicker = false },
|
||||
onDismiss = { showRecurrencePicker = false },
|
||||
fromCompletion = state.repeatFromCompletion.takeIf { state.repeatFromOffered },
|
||||
fromCompletion = state.fromCompletionChoice.takeIf { state.repeatFromOffered },
|
||||
onFromCompletionChange = viewModel::onRepeatFromCompletionChange,
|
||||
)
|
||||
}
|
||||
|
||||
@@ -30,6 +30,7 @@ import de.jeanlucmakiola.agendula.domain.tagsInUse
|
||||
import de.jeanlucmakiola.agendula.domain.rebasedForAllDay
|
||||
import de.jeanlucmakiola.agendula.domain.readableDescription
|
||||
import de.jeanlucmakiola.agendula.domain.recurrence.RecurringScope
|
||||
import de.jeanlucmakiola.agendula.domain.recurrence.RepeatFromCompletion
|
||||
import kotlinx.coroutines.flow.MutableStateFlow
|
||||
import kotlinx.coroutines.flow.StateFlow
|
||||
import kotlinx.coroutines.flow.asStateFlow
|
||||
@@ -77,8 +78,8 @@ data class TaskEditUiState(
|
||||
val tagSuggestions: List<String> = emptyList(),
|
||||
val rrule: String? = null,
|
||||
/** The next occurrence counts from completion rather than the schedule (#79). */
|
||||
val repeatFromCompletion: Boolean = false,
|
||||
/** [repeatFromCompletion] as loaded. */
|
||||
val fromCompletionChoice: Boolean = false,
|
||||
/** [savesFromCompletion] as loaded. */
|
||||
val originalFromCompletion: Boolean = false,
|
||||
/** Whether the active store can repeat from completion. */
|
||||
val repeatFromAvailable: Boolean = false,
|
||||
@@ -111,14 +112,15 @@ data class TaskEditUiState(
|
||||
/** Lists a task can be saved into: read-only shares drop out, except the one it is already in. */
|
||||
val writableLists: List<TaskList> get() = lists.filter { it.acceptsWrites || it.id == listId }
|
||||
|
||||
/** Whether the picker offers "Repeat from": not where a tick never moves the series, a sub-task or one with `RDATE`s. */
|
||||
val repeatFromOffered: Boolean get() = repeatFromAvailable && parentId == null && !hasRecurrenceDates
|
||||
/** Whether the picker offers "Repeat from": see [RepeatFromCompletion.possible]. */
|
||||
val repeatFromOffered: Boolean
|
||||
get() = repeatFromAvailable && RepeatFromCompletion.possible(hasRecurrenceDates, isSubtask = parentId != null)
|
||||
|
||||
/** [repeatFromCompletion] as it will be saved. */
|
||||
val repeatsFromCompletion: Boolean get() = rrule != null && repeatFromCompletion && repeatFromOffered
|
||||
/** [fromCompletionChoice] as it will be saved. */
|
||||
val savesFromCompletion: Boolean get() = rrule != null && fromCompletionChoice && repeatFromOffered
|
||||
|
||||
val recurrenceChanged: Boolean
|
||||
get() = rrule != originalRule || repeatsFromCompletion != originalFromCompletion
|
||||
get() = rrule != originalRule || savesFromCompletion != originalFromCompletion
|
||||
}
|
||||
|
||||
@HiltViewModel
|
||||
@@ -279,7 +281,7 @@ class TaskEditViewModel @Inject constructor(
|
||||
tags = task.tags,
|
||||
rrule = task.recurrenceRule,
|
||||
originalRule = task.recurrenceRule,
|
||||
repeatFromCompletion = task.repeatFromCompletion,
|
||||
fromCompletionChoice = task.repeatFromCompletion,
|
||||
originalFromCompletion = task.repeatFromCompletion,
|
||||
repeatFromAvailable = repository.supportsRepeatFromCompletion(),
|
||||
hasRecurrenceDates = task.hasRecurrenceDates,
|
||||
@@ -517,9 +519,9 @@ class TaskEditViewModel @Inject constructor(
|
||||
fun removeTag(name: String) = update { it.copy(tags = it.tags - name) }
|
||||
/** "Does not repeat" also forgets "Repeat from", so a rule picked after it starts from the schedule. */
|
||||
fun onRecurrenceChange(rrule: String?) = update {
|
||||
it.copy(rrule = rrule, repeatFromCompletion = rrule != null && it.repeatFromCompletion, errors = emptySet())
|
||||
it.copy(rrule = rrule, fromCompletionChoice = rrule != null && it.fromCompletionChoice, errors = emptySet())
|
||||
}
|
||||
fun onRepeatFromCompletionChange(value: Boolean) = update { it.copy(repeatFromCompletion = value) }
|
||||
fun onRepeatFromCompletionChange(value: Boolean) = update { it.copy(fromCompletionChoice = value) }
|
||||
|
||||
/** Dismiss the conflict prompt without saving (the user keeps editing). */
|
||||
fun dismissConflict() = update { it.copy(saveConflict = false) }
|
||||
@@ -610,7 +612,7 @@ private fun TaskEditUiState.toForm(): TaskForm = TaskForm(
|
||||
url = url.ifBlank { null },
|
||||
tags = withDraft(tagDraft),
|
||||
rrule = rrule,
|
||||
repeatFromCompletion = repeatsFromCompletion,
|
||||
repeatFromCompletion = savesFromCompletion,
|
||||
)
|
||||
|
||||
private fun TaskEditUiState.withDraft(draft: String): List<String> = normalizeTags(tags + draft.split(','))
|
||||
+2
-2
@@ -68,7 +68,7 @@ class TaskFormWriterSeriesTest {
|
||||
fun `dropping the rule ends the series and its exceptions`() {
|
||||
val withExceptions = master.copy(exdate = "20260905T090000Z")
|
||||
|
||||
val plain = TaskFormWriter.withRule(withExceptions, null)
|
||||
val plain = TaskFormWriter.withRule(withExceptions, null, fromCompletion = false)
|
||||
|
||||
assertThat(plain.rrule).isNull()
|
||||
assertThat(plain.exdate).isNull()
|
||||
@@ -78,7 +78,7 @@ class TaskFormWriterSeriesTest {
|
||||
fun `an override never takes a rule`() {
|
||||
val override = master.copy(id = 9, masterId = 7, rrule = null)
|
||||
|
||||
assertThat(TaskFormWriter.withRule(override, "FREQ=DAILY").rrule).isNull()
|
||||
assertThat(TaskFormWriter.withRule(override, "FREQ=DAILY", fromCompletion = false).rrule).isNull()
|
||||
}
|
||||
|
||||
@Test
|
||||
|
||||
+23
@@ -78,6 +78,29 @@ class RepeatFromCompletionTest {
|
||||
assertThat(next(spec, "2026-03-10T12:00:00Z")).isEqualTo("2026-03-12T00:00:00Z")
|
||||
}
|
||||
|
||||
@Test
|
||||
fun `a month on from the 31st is the last day of a short month`() {
|
||||
val spec = allDay("FREQ=MONTHLY", "2026-01-05T00:00:00Z")
|
||||
|
||||
assertThat(next(spec, "2026-01-31T12:00:00Z")).isEqualTo("2026-02-28T00:00:00Z")
|
||||
}
|
||||
|
||||
@Test
|
||||
fun `weekdays every other week wait out all but the last week`() {
|
||||
val spec = allDay("FREQ=WEEKLY;INTERVAL=2;BYDAY=FR", "2026-03-06T00:00:00Z")
|
||||
|
||||
// Done Wednesday 11 March: a week on is the 18th, and the Friday after it the 20th.
|
||||
assertThat(next(spec, "2026-03-11T12:00:00Z")).isEqualTo("2026-03-20T00:00:00Z")
|
||||
}
|
||||
|
||||
@Test
|
||||
fun `an occurrence is on a schedule only where it generates one`() {
|
||||
val spec = allDay("FREQ=WEEKLY", "2026-03-02T00:00:00Z")
|
||||
|
||||
assertThat(RepeatFromCompletion.onSchedule(spec, at("2026-03-16T00:00:00Z"), berlin)).isTrue()
|
||||
assertThat(RepeatFromCompletion.onSchedule(spec, at("2026-03-17T00:00:00Z"), berlin)).isFalse()
|
||||
}
|
||||
|
||||
@Test
|
||||
fun `COUNT is left to the caller`() {
|
||||
val spec = allDay("FREQ=DAILY;COUNT=1", "2026-03-02T00:00:00Z")
|
||||
|
||||
@@ -176,7 +176,7 @@ class TaskEditViewModelTest {
|
||||
vm.onRecurrenceChange(null)
|
||||
vm.onRecurrenceChange("FREQ=WEEKLY")
|
||||
|
||||
assertThat(vm.state.value.repeatsFromCompletion).isFalse()
|
||||
assertThat(vm.state.value.savesFromCompletion).isFalse()
|
||||
}
|
||||
|
||||
@Test
|
||||
@@ -186,7 +186,7 @@ class TaskEditViewModelTest {
|
||||
vm.onRepeatFromCompletionChange(true)
|
||||
|
||||
assertThat(vm.state.value.repeatFromOffered).isFalse()
|
||||
assertThat(vm.state.value.repeatsFromCompletion).isFalse()
|
||||
assertThat(vm.state.value.savesFromCompletion).isFalse()
|
||||
|
||||
repository.task = task(null, due).copy(isRecurring = true, recurrenceRule = "FREQ=DAILY", parentId = 3)
|
||||
val sub = TaskEditViewModel(repository, settingsPrefs()).apply { bindEdit(TASK_ID) }
|
||||
|
||||
Reference in new issue
Block a user