diff --git a/app/src/main/java/de/jeanlucmakiola/calendula/domain/Recurrence.kt b/app/src/main/java/de/jeanlucmakiola/calendula/domain/Recurrence.kt index 3e55232f..0251ab81 100644 --- a/app/src/main/java/de/jeanlucmakiola/calendula/domain/Recurrence.kt +++ b/app/src/main/java/de/jeanlucmakiola/calendula/domain/Recurrence.kt @@ -3,23 +3,26 @@ package de.jeanlucmakiola.calendula.domain import de.jeanlucmakiola.calendula.domain.ics.parseBasicDate import de.jeanlucmakiola.calendula.domain.ics.parseBasicDateTime import de.jeanlucmakiola.calendula.domain.ics.toUtcBasic +import kotlinx.datetime.DateTimeUnit import kotlinx.datetime.DayOfWeek import kotlinx.datetime.LocalDate import kotlinx.datetime.LocalDateTime import kotlinx.datetime.LocalTime import kotlinx.datetime.TimeZone import kotlinx.datetime.isoDayNumber +import kotlinx.datetime.minus import kotlinx.datetime.number +import kotlinx.datetime.plus import kotlinx.datetime.toInstant import kotlinx.datetime.toLocalDateTime import kotlin.time.Instant /** * The recurrence shapes the simple picker can express (v1.3): a frequency, - * an interval, weekly weekday picks, and an optional end. Anything beyond - * that (ordinal BYDAY like "2TH", BYMONTHDAY, EXDATE rules, …) stays a raw - * RRULE string the picker shows as "custom" and leaves untouched unless the - * user replaces it. + * an interval, weekly weekday picks, a monthly weekday position (#520) and an + * optional end. Anything beyond that (several ordinal days, BYMONTHDAY, + * BYSETPOS, …) stays a raw RRULE string the picker shows as "custom" and + * leaves untouched unless the user replaces it. */ data class SimpleRecurrence( val freq: RecurrenceFreq, @@ -30,8 +33,75 @@ data class SimpleRecurrence( * no BYDAY part — the provider derives the day from DTSTART. */ val byDays: Set = emptySet(), + /** + * Monthly only: repeat on the n-th (or last) weekday of the month + * (RRULE `BYDAY=2TU`). Null repeats on DTSTART's day of the month. + */ + val monthlyWeekday: MonthlyWeekday? = null, ) +/** + * "The [ordinal]-th [day] of the month": [ordinal] is 1..5, or [LAST] (-1). + * A fifth weekday only exists in some months; those without one are skipped. + */ +data class MonthlyWeekday(val ordinal: Int, val day: DayOfWeek) { + init { + require(ordinal in 1..MAX_ORDINAL || ordinal == LAST) { "ordinal $ordinal" } + } + + /** The RRULE BYDAY token, e.g. "2TU" or "-1SA". */ + val token: String get() = "$ordinal${RRULE_DAY_CODES.getValue(day)}" + + /** + * The first date on or after [date] at this position: later in [date]'s + * month, or in the next month that has one (a fifth weekday can be months away). + */ + fun firstOnOrAfter(date: LocalDate): LocalDate { + var month = LocalDate(date.year, date.month, 1) + while (true) { + dateIn(month.year, month.month.number)?.takeIf { it >= date }?.let { return it } + month = month.plus(1, DateTimeUnit.MONTH) + } + } + + /** This weekday's date in [year]/[month], or null when the month has no such day. */ + fun dateIn(year: Int, month: Int): LocalDate? { + val first = LocalDate(year, month, 1) + val offset = (day.isoDayNumber - first.dayOfWeek.isoDayNumber + 7) % 7 + val firstMatch = first.day + offset + val lastDay = first.plus(1, DateTimeUnit.MONTH).minus(1, DateTimeUnit.DAY).day + val dom = if (ordinal == LAST) { + firstMatch + (lastDay - firstMatch) / 7 * 7 + } else { + firstMatch + (ordinal - 1) * 7 + } + return if (dom <= lastDay) LocalDate(year, month, dom) else null + } + + companion object { + const val LAST = -1 + const val MAX_ORDINAL = 5 + + /** Parse a single BYDAY item with an ordinal ("2TU", "+3MO", "-1SA"); else null. */ + fun parse(token: String): MonthlyWeekday? { + val match = TOKEN.matchEntire(token.trim().uppercase()) ?: return null + val ordinal = match.groupValues[1].removePrefix("+").toIntOrNull() ?: return null + if (ordinal !in 1..MAX_ORDINAL && ordinal != LAST) return null + val day = rruleDay(match.groupValues[2]) ?: return null + return MonthlyWeekday(ordinal, day) + } + + /** [date]'s own position: its weekday, counted from the start of its month (1..5). */ + fun of(date: LocalDate): MonthlyWeekday = MonthlyWeekday((date.day - 1) / 7 + 1, date.dayOfWeek) + + /** The position offered for [date]: its own, with a fifth weekday offered as the last one. */ + fun suggestedFor(date: LocalDate): MonthlyWeekday = + of(date).let { if (it.ordinal == MAX_ORDINAL) it.copy(ordinal = LAST) else it } + + private val TOKEN = Regex("""([+-]?\d)(MO|TU|WE|TH|FR|SA|SU)""") + } +} + enum class RecurrenceFreq { Daily, Weekly, @@ -69,12 +139,18 @@ fun parseSimpleRecurrence( ?: return null val interval = parts["INTERVAL"]?.let { it.toIntOrNull()?.takeIf { n -> n >= 1 } ?: return null } ?: 1 - // BYDAY is simple only as plain weekday picks on a weekly rule; ordinal - // forms ("2TH" = second Thursday) and BYDAY on other frequencies are not. - val byDays = parts["BYDAY"]?.let { raw -> - if (freq != RecurrenceFreq.Weekly) return null - raw.split(',').map { token -> rruleDay(token.trim()) ?: return null }.toSet() - } ?: emptySet() + // BYDAY is simple as plain weekday picks on a weekly rule, or as one + // ordinal weekday ("2TH" = second Thursday) on a monthly rule. + var byDays = emptySet() + var monthlyWeekday: MonthlyWeekday? = null + parts["BYDAY"]?.let { raw -> + when (freq) { + RecurrenceFreq.Weekly -> + byDays = raw.split(',').map { token -> rruleDay(token.trim()) ?: return null }.toSet() + RecurrenceFreq.Monthly -> monthlyWeekday = MonthlyWeekday.parse(raw) ?: return null + else -> return null + } + } val until = parts["UNTIL"] val count = parts["COUNT"] @@ -84,7 +160,7 @@ fun parseSimpleRecurrence( count != null -> RecurrenceEnd.Count(count.toIntOrNull()?.takeIf { it >= 1 } ?: return null) else -> RecurrenceEnd.Never } - return SimpleRecurrence(freq, interval, end, byDays) + return SimpleRecurrence(freq, interval, end, byDays, monthlyWeekday) } /** @@ -113,6 +189,10 @@ fun SimpleRecurrence.toRRule(zone: TimeZone = TimeZone.currentSystemDefault()): .joinToString(",") { RRULE_DAY_CODES.getValue(it) }, ) } + if (freq == RecurrenceFreq.Monthly && monthlyWeekday != null) { + append(";BYDAY=") + append(monthlyWeekday.token) + } when (val e = end) { RecurrenceEnd.Never -> Unit is RecurrenceEnd.Until -> { @@ -148,7 +228,7 @@ internal val RRULE_DAY_CODES: Map = mapOf( ) /** Exact two-letter BYDAY token → weekday; ordinal forms ("2TH") return null. */ -private fun rruleDay(token: String): DayOfWeek? = +internal fun rruleDay(token: String): DayOfWeek? = RRULE_DAY_CODES.entries.firstOrNull { it.value == token.uppercase() }?.key /** @@ -178,3 +258,26 @@ private fun parseUntilDate(raw: String, zone: TimeZone): LocalDate? { if (raw.length < 15 || raw[8] != 'T') return date return parseBasicDateTime(raw)?.toInstant(TimeZone.UTC)?.toLocalDateTime(zone)?.date } + +/** + * The form moved forward to the first day its monthly weekday-position rule + * fires on, keeping time of day and length (#520); unchanged for any other rule + * or when the start already matches. + */ +fun EventForm.alignedToRecurrence(deviceZone: TimeZone): EventForm { + val position = rrule?.let { parseSimpleRecurrence(it, deviceZone) }?.monthlyWeekday ?: return this + val target = position.firstOnOrAfter(start.date) + return shiftedByDays((target.toEpochDays() - start.date.toEpochDays()).toInt(), deviceZone) +} + +/** + * The form repeating by [rrule]. The start only moves onto the rule's first day + * when the weekday position is new, so re-confirming a series' own rule never + * shifts its start. + */ +fun EventForm.withRecurrence(rrule: String?, deviceZone: TimeZone): EventForm { + val before = this.rrule?.let { parseSimpleRecurrence(it, deviceZone) }?.monthlyWeekday + val after = rrule?.let { parseSimpleRecurrence(it, deviceZone) }?.monthlyWeekday + val next = copy(rrule = rrule) + return if (after != null && after != before) next.alignedToRecurrence(deviceZone) else next +} diff --git a/app/src/main/java/de/jeanlucmakiola/calendula/domain/RecurrenceOccurrences.kt b/app/src/main/java/de/jeanlucmakiola/calendula/domain/RecurrenceOccurrences.kt index ca434ccb..8444ab05 100644 --- a/app/src/main/java/de/jeanlucmakiola/calendula/domain/RecurrenceOccurrences.kt +++ b/app/src/main/java/de/jeanlucmakiola/calendula/domain/RecurrenceOccurrences.kt @@ -54,16 +54,23 @@ private fun SimpleRecurrence.occurrencesInPeriod(period: Int, start: LocalDate): when (freq) { RecurrenceFreq.Daily -> listOf(start.plus(period * interval, DateTimeUnit.DAY)) RecurrenceFreq.Weekly -> weeklyOccurrences(period, start) - RecurrenceFreq.Monthly -> { - val month = start.plus(period * interval, DateTimeUnit.MONTH) - // plus() clamps into the shorter month, but the rule skips such a - // period — so a clamped date means "not this month". - listOfNotNull(dateOrNull(month.year, month.month.number, start.day)) - } + RecurrenceFreq.Monthly -> monthlyOccurrences(period, start) RecurrenceFreq.Yearly -> listOfNotNull(dateOrNull(start.year + period * interval, start.month.number, start.day)) } +/** One monthly period: the weekday position if set, else the start's day of the month. */ +private fun SimpleRecurrence.monthlyOccurrences(period: Int, start: LocalDate): List { + monthlyWeekday?.let { pos -> + val month = LocalDate(start.year, start.month, 1).plus(period * interval, DateTimeUnit.MONTH) + return listOfNotNull(pos.dateIn(month.year, month.month.number)) + } + val month = start.plus(period * interval, DateTimeUnit.MONTH) + // plus() clamps into the shorter month, but the rule skips such a + // period — so a clamped date means "not this month". + return listOfNotNull(dateOrNull(month.year, month.month.number, start.day)) +} + /** * One weekly block: every picked weekday inside the week that begins * `period * interval` weeks after the start's own week, in weekday order. With diff --git a/app/src/main/java/de/jeanlucmakiola/calendula/ui/common/RecurrenceText.kt b/app/src/main/java/de/jeanlucmakiola/calendula/ui/common/RecurrenceText.kt index 7bc93dc2..b6b1354f 100644 --- a/app/src/main/java/de/jeanlucmakiola/calendula/ui/common/RecurrenceText.kt +++ b/app/src/main/java/de/jeanlucmakiola/calendula/ui/common/RecurrenceText.kt @@ -2,18 +2,21 @@ package de.jeanlucmakiola.calendula.ui.common import android.icu.text.ListFormatter import androidx.compose.runtime.Composable +import androidx.compose.ui.platform.LocalResources import androidx.compose.ui.res.stringResource import androidx.compose.ui.text.AnnotatedString import androidx.compose.ui.text.SpanStyle import androidx.compose.ui.text.buildAnnotatedString import androidx.compose.ui.text.font.FontStyle import de.jeanlucmakiola.calendula.R +import de.jeanlucmakiola.calendula.domain.MonthlyWeekday import de.jeanlucmakiola.calendula.domain.SimpleRecurrence import de.jeanlucmakiola.calendula.domain.occurrencesSpanYears import de.jeanlucmakiola.calendula.domain.rruleParts import de.jeanlucmakiola.calendula.domain.ics.parseBasicDate import de.jeanlucmakiola.calendula.domain.upcomingOccurrences import de.jeanlucmakiola.floret.locale.localizedDateFormatter +import kotlinx.datetime.toJavaDayOfWeek import kotlinx.datetime.toJavaLocalDate import java.time.DayOfWeek import java.time.LocalDate @@ -28,12 +31,23 @@ import java.util.Locale /** * Humanise an RFC 5545 RRULE into a localized phrase, e.g. * "Every week on Tue and Thu until 31 Dec 2026" or "Every day, 10 times". - * Falls back to a generic label for rules we don't render in full (ordinal - * monthly/yearly BYDAY, etc.). Shared by the detail screen and the edit + * Falls back to a generic label for rules we don't render in full (yearly + * or multi-day ordinal BYDAY, etc.). Shared by the detail screen and the edit * form's repeat card. */ @Composable fun recurrenceText(rrule: String, locale: Locale): AnnotatedString { + val resources = LocalResources.current + return describeRecurrence(rrule, locale) { id, args -> resources.getString(id, *args) } +} + +/** [recurrenceText] without Compose; [string] resolves a string resource with format args. */ +internal fun describeRecurrence( + rrule: String, + locale: Locale, + string: (id: Int, args: Array) -> String, +): AnnotatedString { + fun stringResource(id: Int, vararg args: Any): String = string(id, args) val parts = rruleParts(rrule).mapNotNull { part -> part.key?.let { it to part.value } }.toMap() val freq = parts["FREQ"]?.uppercase() @@ -50,13 +64,20 @@ fun recurrenceText(rrule: String, locale: Locale): AnnotatedString { else -> return AnnotatedString(stringResource(R.string.event_detail_recurring)) } - // Weekly + BYDAY → " on "; other BYDAY forms keep just the base. + // Weekly + BYDAY → " on "; monthly + one ordinal BYDAY → + // " on the second "; other BYDAY forms keep just the base. // The day names + their joined block are tracked so only the names (not the // commas/conjunction) can be italicised in the final string. val byDay = parts["BYDAY"] var dayNames: List? = null var joinedDays: String? = null - val main = if (freq == "WEEKLY" && !byDay.isNullOrBlank()) { + val monthlyWeekday = if (freq == "MONTHLY") byDay?.let(MonthlyWeekday::parse) else null + val main = if (monthlyWeekday != null) { + val name = monthlyWeekday.day.toJavaDayOfWeek().getDisplayName(JavaTextStyle.FULL, locale) + dayNames = listOf(name) + joinedDays = name + stringResource(monthlyWeekdaySummary(monthlyWeekday.ordinal), base, name) + } else if (freq == "WEEKLY" && !byDay.isNullOrBlank()) { val days = byDay.split(',').mapNotNull { rruleDayName(it.trim(), locale) } if (days.isNotEmpty()) { val joined = ListFormatter.getInstance(locale).format(days) @@ -129,6 +150,16 @@ fun nextOccurrencesText( /** Enough dates to show a rhythm (and a skipped month), few enough for one line. */ private const val NEXT_OCCURRENCE_COUNT = 3 +/** Summary string for a monthly weekday position (1..5 or [MonthlyWeekday.LAST]). */ +internal fun monthlyWeekdaySummary(ordinal: Int): Int = when (ordinal) { + 1 -> R.string.recurrence_monthly_weekday_first + 2 -> R.string.recurrence_monthly_weekday_second + 3 -> R.string.recurrence_monthly_weekday_third + 4 -> R.string.recurrence_monthly_weekday_fourth + 5 -> R.string.recurrence_monthly_weekday_fifth + else -> R.string.recurrence_monthly_weekday_last +} + /** Map an RRULE BYDAY token (e.g. "TU" or "2TH") to a localized short weekday name. */ private fun rruleDayName(token: String, locale: Locale): String? { val dow = when (token.takeLast(2).uppercase()) { diff --git a/app/src/main/java/de/jeanlucmakiola/calendula/ui/edit/EventEditScreen.kt b/app/src/main/java/de/jeanlucmakiola/calendula/ui/edit/EventEditScreen.kt index 356e6f68..da058e85 100644 --- a/app/src/main/java/de/jeanlucmakiola/calendula/ui/edit/EventEditScreen.kt +++ b/app/src/main/java/de/jeanlucmakiola/calendula/ui/edit/EventEditScreen.kt @@ -138,6 +138,7 @@ import de.jeanlucmakiola.calendula.domain.zoneDescriptor import de.jeanlucmakiola.calendula.domain.timeZoneOptionOf import de.jeanlucmakiola.calendula.domain.EventFormProblem import de.jeanlucmakiola.calendula.domain.RecurrenceEnd +import de.jeanlucmakiola.calendula.domain.MonthlyWeekday import de.jeanlucmakiola.calendula.domain.RecurrenceFreq import de.jeanlucmakiola.calendula.domain.SimpleRecurrence import de.jeanlucmakiola.calendula.domain.parseSimpleRecurrence @@ -1711,10 +1712,11 @@ private enum class RecurrenceEndMode { Never, Until, Count } /** * Recurrence picker, two steps like the reminder picker: the plain * frequencies as a tappable list (one tap applies and closes), with "Custom" - * switching to an interval-plus-unit editor, weekday toggles (weekly only) - * and an end condition — only that step needs an OK button. A rule the - * simple shape can't express (ordinal BYDAY etc.) stays untouched unless the - * user picks something here. + * switching to an interval-plus-unit editor, weekday toggles (weekly only), + * day of month vs. weekday position (monthly only) and an end condition — + * only that step needs an OK button. A rule the simple shape can't express + * (several ordinal weekdays, BYSETPOS etc.) stays untouched unless the user + * picks something here. * * Both steps show the rule as *dates* as well as words: every preset row * carries the next few occurrences it would produce from [startDate], and the @@ -1731,7 +1733,7 @@ private fun RecurrencePickerDialog( val startDay = startDate.dayOfWeek val parsed = remember(current) { current?.let(::parseSimpleRecurrence) } val isPlainPreset = parsed != null && parsed.interval == 1 && - parsed.end == RecurrenceEnd.Never && parsed.byDays.isEmpty() + parsed.end == RecurrenceEnd.Never && parsed.byDays.isEmpty() && parsed.monthlyWeekday == null var customMode by rememberSaveable { mutableStateOf(false) } var intervalText by rememberSaveable { mutableStateOf((parsed?.interval ?: 1).toString()) } var freq by rememberSaveable { mutableStateOf(parsed?.freq ?: RecurrenceFreq.Weekly) } @@ -1741,6 +1743,15 @@ private fun RecurrencePickerDialog( (parsed?.byDays?.takeIf { it.isNotEmpty() } ?: setOf(startDay)).toMask(), ) } + // Monthly: "on day N" or a weekday position, the latter prefilled from the + // rule or else the start date and kept as a BYDAY token ("2TU", "-1SA"). + var byWeekday by rememberSaveable { mutableStateOf(parsed?.monthlyWeekday != null) } + var weekdayToken by rememberSaveable { + mutableStateOf((parsed?.monthlyWeekday ?: MonthlyWeekday.suggestedFor(startDate)).token) + } + val weekdayPosition = MonthlyWeekday.parse(weekdayToken) ?: MonthlyWeekday.suggestedFor(startDate) + var showPositionPicker by rememberSaveable { mutableStateOf(false) } + var showWeekdayPicker by rememberSaveable { mutableStateOf(false) } var endMode by rememberSaveable { mutableStateOf( when (parsed?.end) { @@ -1788,11 +1799,14 @@ private fun RecurrencePickerDialog( interval = interval, end = customEnd, byDays = if (freq == RecurrenceFreq.Weekly) daysMask.toDaySet() else emptySet(), + monthlyWeekday = weekdayPosition.takeIf { freq == RecurrenceFreq.Monthly && byWeekday }, ) } else { null } val customResult: String? = customRule?.toRRule() + // Saving a weekday position moves the start onto its first match, so preview from there. + val previewStart = customRule?.monthlyWeekday?.firstOnOrAfter(startDate) ?: startDate FullScreenPicker( title = stringResource(R.string.event_detail_recurrence), @@ -1863,7 +1877,7 @@ private fun RecurrencePickerDialog( // Rendered even while incomplete (as an empty line), so the // controls below don't shift as it comes and goes. Text( - text = customRule?.let { nextOccurrencesText(it, startDate, locale) }.orEmpty(), + text = customRule?.let { nextOccurrencesText(it, previewStart, locale) }.orEmpty(), style = MaterialTheme.typography.bodyMedium, color = MaterialTheme.colorScheme.onSurfaceVariant, modifier = Modifier @@ -1944,6 +1958,52 @@ private fun RecurrencePickerDialog( } } + // Monthly: same day of the month, or a free weekday position + // whose position and weekday open their own pickers. + AnimatedVisibility( + visible = freq == RecurrenceFreq.Monthly, + enter = expandEnter(), + exit = collapseExit(), + ) { + Column(modifier = Modifier.padding(top = 16.dp)) { + GroupedRow( + title = stringResource(R.string.event_edit_recurrence_monthly_day, startDate.day), + position = Position.Top, + checked = !byWeekday, + onClick = { byWeekday = false }, + ) + GroupedRow( + title = stringResource( + monthlyWeekdayLabel(weekdayPosition.ordinal), + weekdayPosition.day.toJavaDayOfWeek().getDisplayName(JavaTextStyle.FULL, locale), + ), + position = if (byWeekday) Position.Middle else Position.Bottom, + checked = byWeekday, + onClick = { byWeekday = true }, + ) + AnimatedVisibility( + visible = byWeekday, + enter = expandEnter(), + exit = collapseExit(), + ) { + Column { + GroupedRow( + title = stringResource(R.string.event_edit_recurrence_position), + summary = stringResource(weekdayPositionName(weekdayPosition.ordinal)), + position = Position.Middle, + onClick = { showPositionPicker = true }, + ) + GroupedRow( + title = stringResource(R.string.event_edit_recurrence_weekday), + summary = weekdayName(weekdayPosition.day, locale), + position = Position.Bottom, + onClick = { showWeekdayPicker = true }, + ) + } + } + } + } + // Ends: a connected never / on-a-date / after-N group, the count // field folding into the bottom of the run when chosen. Column(modifier = Modifier.padding(top = 16.dp)) { @@ -2013,6 +2073,27 @@ private fun RecurrencePickerDialog( } } + if (showPositionPicker) { + OptionPicker( + title = stringResource(R.string.event_edit_recurrence_position), + options = MONTHLY_POSITIONS, + selected = weekdayPosition.ordinal, + label = { stringResource(weekdayPositionName(it)) }, + onSelect = { weekdayToken = weekdayPosition.copy(ordinal = it).token }, + onDismiss = { showPositionPicker = false }, + ) + } + if (showWeekdayPicker) { + OptionPicker( + title = stringResource(R.string.event_edit_recurrence_weekday), + options = (0 until 7).map { DayOfWeek(((firstDayOfWeek.isoDayNumber - 1 + it) % 7) + 1) }, + selected = weekdayPosition.day, + label = { weekdayName(it, locale) }, + onSelect = { weekdayToken = weekdayPosition.copy(day = it).token }, + onDismiss = { showWeekdayPicker = false }, + ) + } + if (showUntilPicker) { CalendarDatePickerDialog( initial = untilDate @@ -2096,6 +2177,30 @@ private fun recurrencePresetLabel(freq: RecurrenceFreq): Int = when (freq) { RecurrenceFreq.Yearly -> R.string.recurrence_yearly } +private val MONTHLY_POSITIONS = (1..MonthlyWeekday.MAX_ORDINAL).toList() + MonthlyWeekday.LAST + +private fun weekdayName(day: DayOfWeek, locale: Locale): String = + day.toJavaDayOfWeek().getDisplayName(JavaTextStyle.FULL_STANDALONE, locale) + .replaceFirstChar { it.titlecase(locale) } + +private fun weekdayPositionName(ordinal: Int): Int = when (ordinal) { + 1 -> R.string.recurrence_position_first + 2 -> R.string.recurrence_position_second + 3 -> R.string.recurrence_position_third + 4 -> R.string.recurrence_position_fourth + 5 -> R.string.recurrence_position_fifth + else -> R.string.recurrence_position_last +} + +private fun monthlyWeekdayLabel(ordinal: Int): Int = when (ordinal) { + 1 -> R.string.event_edit_recurrence_monthly_weekday_first + 2 -> R.string.event_edit_recurrence_monthly_weekday_second + 3 -> R.string.event_edit_recurrence_monthly_weekday_third + 4 -> R.string.event_edit_recurrence_monthly_weekday_fourth + 5 -> R.string.event_edit_recurrence_monthly_weekday_fifth + else -> R.string.event_edit_recurrence_monthly_weekday_last +} + private fun recurrenceUnitLabel(freq: RecurrenceFreq): Int = when (freq) { RecurrenceFreq.Daily -> R.string.recurrence_unit_days RecurrenceFreq.Weekly -> R.string.recurrence_unit_weeks diff --git a/app/src/main/java/de/jeanlucmakiola/calendula/ui/edit/EventEditViewModel.kt b/app/src/main/java/de/jeanlucmakiola/calendula/ui/edit/EventEditViewModel.kt index 79f487ab..d88a5b77 100644 --- a/app/src/main/java/de/jeanlucmakiola/calendula/ui/edit/EventEditViewModel.kt +++ b/app/src/main/java/de/jeanlucmakiola/calendula/ui/edit/EventEditViewModel.kt @@ -31,6 +31,8 @@ import de.jeanlucmakiola.calendula.domain.EventAttendee import de.jeanlucmakiola.calendula.domain.EventColorOption import de.jeanlucmakiola.calendula.domain.EventDetail import de.jeanlucmakiola.calendula.domain.EventForm +import de.jeanlucmakiola.calendula.domain.alignedToRecurrence +import de.jeanlucmakiola.calendula.domain.withRecurrence import de.jeanlucmakiola.calendula.domain.nextFullHour import de.jeanlucmakiola.calendula.domain.toFormTime import de.jeanlucmakiola.calendula.domain.resolvedZone @@ -758,8 +760,11 @@ class EventEditViewModel @Inject constructor( applyDefault { it.copy(calendarId = shown.calendarId, colorKey = shown.colorKey, color = shown.color) } } - /** Bare RRULE value from the recurrence picker; null = does not repeat. */ - fun setRecurrence(rrule: String?) = edit { it.copy(rrule = rrule) } + /** + * Bare RRULE value from the recurrence picker; null = does not repeat. A new + * monthly weekday position moves the start onto its first matching day (#520). + */ + fun setRecurrence(rrule: String?) = edit { it.withRecurrence(rrule, zoneSource.current()) } fun addReminder(minutes: Int) { _remindersTouched.value = true @@ -1038,8 +1043,10 @@ class EventEditViewModel @Inject constructor( _saveState.value = SaveUiState.Idle } + /** A new start date under a monthly weekday-position rule moves on to the rule's next day (#520). */ private fun moveStart(transform: (LocalDateTime) -> LocalDateTime) = edit { form -> - form.withStart(transform(form.start.dateTime), form.resolvedZone(zoneSource.current()), opened(form)?.start) + val moved = form.withStart(transform(form.start.dateTime), form.resolvedZone(zoneSource.current()), opened(form)?.start) + if (moved.start.date != form.start.date) moved.alignedToRecurrence(zoneSource.current()) else moved } private fun moveEnd(transform: (LocalDateTime) -> LocalDateTime) = edit { form -> diff --git a/app/src/main/res/values/strings.xml b/app/src/main/res/values/strings.xml index fc9dcaab..3dcdebe9 100644 --- a/app/src/main/res/values/strings.xml +++ b/app/src/main/res/values/strings.xml @@ -221,6 +221,24 @@ On a date After a number of times times + + On day %1$d + + On the first %1$s + On the second %1$s + On the third %1$s + On the fourth %1$s + On the fifth %1$s + On the last %1$s + + Position + Weekday + First + Second + Third + Fourth + Fifth + Last Repeats end before the event starts Busy Default @@ -247,6 +265,13 @@ Every %1$d months Every %1$d years %1$s on %2$s + + %1$s on the first %2$s + %1$s on the second %2$s + %1$s on the third %2$s + %1$s on the fourth %2$s + %1$s on the fifth %2$s + %1$s on the last %2$s %1$s until %2$s %1$s, %2$d times This event no longer exists. diff --git a/app/src/test/java/de/jeanlucmakiola/calendula/domain/EventFormTest.kt b/app/src/test/java/de/jeanlucmakiola/calendula/domain/EventFormTest.kt index 6ee95aa2..1a9ee6cf 100644 --- a/app/src/test/java/de/jeanlucmakiola/calendula/domain/EventFormTest.kt +++ b/app/src/test/java/de/jeanlucmakiola/calendula/domain/EventFormTest.kt @@ -93,9 +93,15 @@ class EventFormTest { @Test fun `complex rrules are not validated against the start`() { - // The picker can't have produced this ("second Monday" ordinal BYDAY); - // it is preserved verbatim and never flagged. - assertThat(form().copy(rrule = "FREQ=MONTHLY;BYDAY=2MO;UNTIL=20200101").problems(berlin)).isEmpty() + // The picker can't have produced this (two ordinal weekdays); it is + // preserved verbatim and never flagged. + assertThat(form().copy(rrule = "FREQ=MONTHLY;BYDAY=2MO,4MO;UNTIL=20200101").problems(berlin)).isEmpty() + } + + @Test + fun `a monthly weekday position rule is validated like any simple rule`() { + assertThat(form().copy(rrule = "FREQ=MONTHLY;BYDAY=2MO;UNTIL=20200101").problems(berlin)) + .containsExactly(EventFormProblem.RecurrenceEndsBeforeStart) } @Test diff --git a/app/src/test/java/de/jeanlucmakiola/calendula/domain/MonthlyWeekdayTest.kt b/app/src/test/java/de/jeanlucmakiola/calendula/domain/MonthlyWeekdayTest.kt new file mode 100644 index 00000000..6cc73d23 --- /dev/null +++ b/app/src/test/java/de/jeanlucmakiola/calendula/domain/MonthlyWeekdayTest.kt @@ -0,0 +1,215 @@ +package de.jeanlucmakiola.calendula.domain + +import com.google.common.truth.Truth.assertThat +import kotlinx.datetime.DayOfWeek +import kotlinx.datetime.LocalDate +import kotlinx.datetime.LocalDateTime +import kotlinx.datetime.TimeZone +import org.junit.jupiter.api.Test + +/** Monthly repeats by weekday position (#520). */ +class MonthlyWeekdayTest { + + private val utc = TimeZone.UTC + + @Test + fun `ordinal BYDAY on a monthly rule parses into a weekday position`() { + (1..5).forEach { n -> + assertThat(parseSimpleRecurrence("FREQ=MONTHLY;BYDAY=${n}TU", utc)) + .isEqualTo( + SimpleRecurrence( + RecurrenceFreq.Monthly, + monthlyWeekday = MonthlyWeekday(n, DayOfWeek.TUESDAY), + ), + ) + } + assertThat(parseSimpleRecurrence("FREQ=MONTHLY;BYDAY=-1SA", utc)?.monthlyWeekday) + .isEqualTo(MonthlyWeekday(MonthlyWeekday.LAST, DayOfWeek.SATURDAY)) + assertThat(parseSimpleRecurrence("FREQ=MONTHLY;BYDAY=+2tu", utc)?.monthlyWeekday) + .isEqualTo(MonthlyWeekday(2, DayOfWeek.TUESDAY)) + } + + @Test + fun `round-trips 1 to 5 and last with interval and end`() { + val positions = (1..5).map(Int::toString) + "-1" + val tails = listOf("", ";COUNT=6", ";UNTIL=20301231T235959Z") + positions.forEach { n -> + tails.forEach { tail -> + listOf("FREQ=MONTHLY;BYDAY=${n}SA$tail", "FREQ=MONTHLY;INTERVAL=3;BYDAY=${n}SA$tail") + .forEach { rule -> + assertThat(parseSimpleRecurrence(rule, utc)!!.toRRule(utc)).isEqualTo(rule) + } + } + } + } + + @Test + fun `interval and end survive alongside the weekday position`() { + val parsed = parseSimpleRecurrence("FREQ=MONTHLY;INTERVAL=2;BYDAY=2TU;COUNT=12", utc)!! + assertThat(parsed.interval).isEqualTo(2) + assertThat(parsed.end).isEqualTo(RecurrenceEnd.Count(12)) + + val until = parseSimpleRecurrence("FREQ=MONTHLY;BYDAY=-1FR;UNTIL=20271231T235959Z", utc)!! + assertThat(until.end).isEqualTo(RecurrenceEnd.Until(LocalDate(2027, 12, 31))) + } + + @Test + fun `rules the editor cannot represent stay unparsed`() { + listOf( + "FREQ=MONTHLY;BYDAY=2TU,4TU", + "FREQ=MONTHLY;BYDAY=MO", + "FREQ=MONTHLY;BYDAY=6TU", + "FREQ=MONTHLY;BYDAY=-2TU", + "FREQ=MONTHLY;BYDAY=0TU", + "FREQ=MONTHLY;BYDAY=MO,TU,WE,TH,FR;BYSETPOS=-1", + "FREQ=MONTHLY;BYDAY=2TU;BYMONTH=3", + "FREQ=YEARLY;BYDAY=2TU", + "FREQ=WEEKLY;BYDAY=2TU", + ).forEach { assertThat(parseSimpleRecurrence(it, utc)).isNull() } + } + + @Test + fun `the weekday position is only written on a monthly rule`() { + val rule = SimpleRecurrence( + RecurrenceFreq.Weekly, + monthlyWeekday = MonthlyWeekday(2, DayOfWeek.TUESDAY), + ) + assertThat(rule.toRRule(utc)).isEqualTo("FREQ=WEEKLY") + } + + @Test + fun `prefill is the start date's own position`() { + // 10 Nov 2026 is the second Tuesday; 31 Oct 2026 the fifth Saturday. + assertThat(MonthlyWeekday.of(LocalDate(2026, 11, 10))).isEqualTo(MonthlyWeekday(2, DayOfWeek.TUESDAY)) + assertThat(MonthlyWeekday.of(LocalDate(2026, 10, 31))).isEqualTo(MonthlyWeekday(5, DayOfWeek.SATURDAY)) + assertThat(MonthlyWeekday.of(LocalDate(2026, 11, 1))).isEqualTo(MonthlyWeekday(1, DayOfWeek.SUNDAY)) + } + + @Test + fun `first match on or after a date`() { + val secondTue = MonthlyWeekday(2, DayOfWeek.TUESDAY) + // Already a match: stays. + assertThat(secondTue.firstOnOrAfter(LocalDate(2026, 11, 10))).isEqualTo(LocalDate(2026, 11, 10)) + // Before it in the month: later the same month. + assertThat(secondTue.firstOnOrAfter(LocalDate(2026, 11, 2))).isEqualTo(LocalDate(2026, 11, 10)) + // Past it: next month. + assertThat(secondTue.firstOnOrAfter(LocalDate(2026, 11, 11))).isEqualTo(LocalDate(2026, 12, 8)) + // Fifth Saturday: Nov and Dec 2026 have none, so across the year end to 30 Jan 2027. + assertThat(MonthlyWeekday(5, DayOfWeek.SATURDAY).firstOnOrAfter(LocalDate(2026, 11, 1))) + .isEqualTo(LocalDate(2027, 1, 30)) + // Last Thursday: 31 Dec 2026, then across the year end to 28 Jan 2027. + val lastThu = MonthlyWeekday(MonthlyWeekday.LAST, DayOfWeek.THURSDAY) + assertThat(lastThu.firstOnOrAfter(LocalDate(2026, 12, 20))).isEqualTo(LocalDate(2026, 12, 31)) + assertThat(lastThu.firstOnOrAfter(LocalDate(2027, 1, 1))).isEqualTo(LocalDate(2027, 1, 28)) + } + + private fun form(start: LocalDateTime, end: LocalDateTime, rrule: String, isAllDay: Boolean = false) = + EventForm(calendarId = 1L, isAllDay = isAllDay, start = FormTime(start), end = FormTime(end), rrule = rrule) + + private val berlin = TimeZone.of("Europe/Berlin") + + @Test + fun `a timed start moves to the first matching day keeping time and length`() { + // Thu 3 Dec 2026 10:00–11:30, rule "fifth Saturday" → Sat 30 Jan 2027. + val moved = form( + LocalDateTime(2026, 12, 3, 10, 0), + LocalDateTime(2026, 12, 3, 11, 30), + "FREQ=MONTHLY;BYDAY=5SA", + ).alignedToRecurrence(berlin) + assertThat(moved.start.dateTime).isEqualTo(LocalDateTime(2027, 1, 30, 10, 0)) + assertThat(moved.end.dateTime).isEqualTo(LocalDateTime(2027, 1, 30, 11, 30)) + } + + @Test + fun `an all-day span moves by whole days`() { + // All-day Sat 26 Dec – Sun 27 Dec 2026 (end exclusive Mon 28), rule "last Thursday" → Thu 31 Dec. + val moved = form( + LocalDateTime(2026, 12, 26, 0, 0), + LocalDateTime(2026, 12, 28, 0, 0), + "FREQ=MONTHLY;BYDAY=-1TH", + isAllDay = true, + ).alignedToRecurrence(berlin) + assertThat(moved.start.dateTime).isEqualTo(LocalDateTime(2026, 12, 31, 0, 0)) + assertThat(moved.end.dateTime).isEqualTo(LocalDateTime(2027, 1, 2, 0, 0)) + } + + @Test + fun `a matching start or another rule leaves the form alone`() { + val matching = form( + LocalDateTime(2026, 11, 10, 9, 0), + LocalDateTime(2026, 11, 10, 10, 0), + "FREQ=MONTHLY;INTERVAL=2;BYDAY=2TU;COUNT=5", + ) + assertThat(matching.alignedToRecurrence(berlin)).isEqualTo(matching) + val weekly = matching.copy(rrule = "FREQ=WEEKLY;BYDAY=FR") + assertThat(weekly.alignedToRecurrence(berlin)).isEqualTo(weekly) + val unsupported = matching.copy(rrule = "FREQ=MONTHLY;BYDAY=1MO,3MO") + assertThat(unsupported.alignedToRecurrence(berlin)).isEqualTo(unsupported) + } + + @Test + fun `dateIn resolves positions and skips missing fifths`() { + val sat5 = MonthlyWeekday(5, DayOfWeek.SATURDAY) + assertThat(sat5.dateIn(2026, 10)).isEqualTo(LocalDate(2026, 10, 31)) + assertThat(sat5.dateIn(2026, 11)).isNull() + assertThat(MonthlyWeekday(MonthlyWeekday.LAST, DayOfWeek.SATURDAY).dateIn(2026, 11)) + .isEqualTo(LocalDate(2026, 11, 28)) + assertThat(MonthlyWeekday(1, DayOfWeek.SUNDAY).dateIn(2026, 11)) + .isEqualTo(LocalDate(2026, 11, 1)) + assertThat(MonthlyWeekday(2, DayOfWeek.TUESDAY).dateIn(2026, 12)) + .isEqualTo(LocalDate(2026, 12, 8)) + } + + @Test + fun `occurrences follow the weekday position across months`() { + val rule = SimpleRecurrence( + RecurrenceFreq.Monthly, + monthlyWeekday = MonthlyWeekday(5, DayOfWeek.SATURDAY), + ) + // Fifth Saturdays after 31 Oct 2026: Jan 30 2027, May 29 2027. + assertThat(rule.upcomingOccurrences(LocalDate(2026, 10, 31), limit = 3)) + .containsExactly( + LocalDate(2026, 10, 31), + LocalDate(2027, 1, 30), + LocalDate(2027, 5, 29), + ).inOrder() + + val lastEveryOther = SimpleRecurrence( + RecurrenceFreq.Monthly, + interval = 2, + monthlyWeekday = MonthlyWeekday(MonthlyWeekday.LAST, DayOfWeek.FRIDAY), + end = RecurrenceEnd.Count(2), + ) + assertThat(lastEveryOther.upcomingOccurrences(LocalDate(2026, 11, 27), limit = 5)) + .containsExactly(LocalDate(2026, 11, 27), LocalDate(2027, 1, 29)).inOrder() + } + + @Test + fun `a fifth weekday is suggested as the last one`() { + assertThat(MonthlyWeekday.suggestedFor(LocalDate(2026, 10, 31))) + .isEqualTo(MonthlyWeekday(MonthlyWeekday.LAST, DayOfWeek.SATURDAY)) + assertThat(MonthlyWeekday.suggestedFor(LocalDate(2026, 12, 29))) + .isEqualTo(MonthlyWeekday(MonthlyWeekday.LAST, DayOfWeek.TUESDAY)) + // The fourth Tuesday of December 2026 is not its last, but stays the fourth. + assertThat(MonthlyWeekday.suggestedFor(LocalDate(2026, 12, 22))) + .isEqualTo(MonthlyWeekday(4, DayOfWeek.TUESDAY)) + } + + @Test + fun `withRecurrence aligns only on a new weekday position`() { + // Mon 7 Dec 2026, off the second-Tuesday pattern. + val offPattern = form( + LocalDateTime(2026, 12, 7, 9, 0), + LocalDateTime(2026, 12, 7, 10, 0), + "FREQ=MONTHLY;BYDAY=2TU", + ) + assertThat(offPattern.withRecurrence("FREQ=MONTHLY;BYDAY=2TU;COUNT=3", berlin).start) + .isEqualTo(offPattern.start) + assertThat(offPattern.withRecurrence("FREQ=MONTHLY;BYDAY=3TU", berlin).start.dateTime) + .isEqualTo(LocalDateTime(2026, 12, 15, 9, 0)) + assertThat(offPattern.withRecurrence(null, berlin).start).isEqualTo(offPattern.start) + val plain = offPattern.copy(rrule = "FREQ=MONTHLY") + assertThat(plain.withRecurrence("FREQ=MONTHLY;BYDAY=2TU", berlin).start.dateTime) + .isEqualTo(LocalDateTime(2026, 12, 8, 9, 0)) + } +} diff --git a/app/src/test/java/de/jeanlucmakiola/calendula/ui/common/RecurrenceTextTest.kt b/app/src/test/java/de/jeanlucmakiola/calendula/ui/common/RecurrenceTextTest.kt index 213d31df..3706788b 100644 --- a/app/src/test/java/de/jeanlucmakiola/calendula/ui/common/RecurrenceTextTest.kt +++ b/app/src/test/java/de/jeanlucmakiola/calendula/ui/common/RecurrenceTextTest.kt @@ -1,6 +1,8 @@ package de.jeanlucmakiola.calendula.ui.common import com.google.common.truth.Truth.assertThat +import de.jeanlucmakiola.calendula.R +import java.util.Locale import java.time.LocalDate import java.time.ZoneId import org.junit.jupiter.api.Test @@ -67,3 +69,44 @@ class RecurrenceTextTest { assertThat(untilLocalDate("20261340", berlin)).isNull() } } + +/** Summary phrases for monthly weekday positions (#520). */ +class MonthlyWeekdaySummaryTest { + + private val english = mapOf( + R.string.recurrence_monthly to "Every month", + R.string.recurrence_every_n_months to "Every %1\$d months", + R.string.recurrence_with_count to "%1\$s, %2\$d times", + R.string.recurrence_monthly_weekday_first to "%1\$s on the first %2\$s", + R.string.recurrence_monthly_weekday_second to "%1\$s on the second %2\$s", + R.string.recurrence_monthly_weekday_third to "%1\$s on the third %2\$s", + R.string.recurrence_monthly_weekday_fourth to "%1\$s on the fourth %2\$s", + R.string.recurrence_monthly_weekday_fifth to "%1\$s on the fifth %2\$s", + R.string.recurrence_monthly_weekday_last to "%1\$s on the last %2\$s", + ) + + private fun describe(rule: String) = describeRecurrence(rule, Locale.ENGLISH) { id, args -> + english.getValue(id).format(Locale.ENGLISH, *args) + }.text + + @Test + fun `each position reads as its ordinal`() { + assertThat(describe("FREQ=MONTHLY;BYDAY=1MO")).isEqualTo("Every month on the first Monday") + assertThat(describe("FREQ=MONTHLY;BYDAY=2TU")).isEqualTo("Every month on the second Tuesday") + assertThat(describe("FREQ=MONTHLY;BYDAY=3WE")).isEqualTo("Every month on the third Wednesday") + assertThat(describe("FREQ=MONTHLY;BYDAY=4TH")).isEqualTo("Every month on the fourth Thursday") + assertThat(describe("FREQ=MONTHLY;BYDAY=5SA")).isEqualTo("Every month on the fifth Saturday") + assertThat(describe("FREQ=MONTHLY;BYDAY=-1SU")).isEqualTo("Every month on the last Sunday") + } + + @Test + fun `interval and count wrap the position phrase`() { + assertThat(describe("FREQ=MONTHLY;INTERVAL=2;BYDAY=-1FR;COUNT=4")) + .isEqualTo("Every 2 months on the last Friday, 4 times") + } + + @Test + fun `multi-day ordinal BYDAY keeps the plain frequency`() { + assertThat(describe("FREQ=MONTHLY;BYDAY=2TU,4TU")).isEqualTo("Every month") + } +} diff --git a/app/src/test/java/de/jeanlucmakiola/calendula/ui/edit/EventEditViewModelTest.kt b/app/src/test/java/de/jeanlucmakiola/calendula/ui/edit/EventEditViewModelTest.kt index 8854295a..94857f44 100644 --- a/app/src/test/java/de/jeanlucmakiola/calendula/ui/edit/EventEditViewModelTest.kt +++ b/app/src/test/java/de/jeanlucmakiola/calendula/ui/edit/EventEditViewModelTest.kt @@ -1012,5 +1012,55 @@ class EventEditViewModelTest { assertThat(vm.state.value?.form?.color).isEqualTo(9) job.cancel() } -} + @Test + fun `re-confirming a weekday-position rule keeps an off-pattern start`( + @TempDir tempDir: Path, + ) = runTest(dispatcher) { + // Mon 7 Dec 2026 09:00 Berlin, a series on second Tuesdays (#520). + val begin = Instant.parse("2026-12-07T08:00:00Z") + val end = Instant.parse("2026-12-07T09:00:00Z") + val fake = FakeCalendarDataSource().apply { + calendarsResult = listOf(cal(1L)) + eventDetailResult = { detail(calendarId = 1L, rrule = "FREQ=MONTHLY;BYDAY=2TU", start = begin, end = end) } + } + val vm = viewModel(tempDir, fake, zones = FakeZoneSource(berlin)) + val job = activate(vm) + vm.openForEdit(eventId = 1L, beginMillis = begin.toEpochMilliseconds(), endMillis = end.toEpochMilliseconds()) + advanceUntilIdle() + + vm.setRecurrence("FREQ=MONTHLY;BYDAY=2TU") + vm.setRecurrence("FREQ=MONTHLY;BYDAY=2TU;COUNT=5") + assertThat(vm.state.value!!.form!!.start.dateTime).isEqualTo(LocalDateTime(2026, 12, 7, 9, 0)) + + vm.setRecurrence("FREQ=MONTHLY;BYDAY=-1TU;COUNT=5") + assertThat(vm.state.value!!.form!!.start.dateTime).isEqualTo(LocalDateTime(2026, 12, 29, 9, 0)) + job.cancel() + } + + @Test + fun `a new start date under a weekday-position rule moves on to the rule's next day`( + @TempDir tempDir: Path, + ) = runTest(dispatcher) { + // Tue 8 Dec 2026 09:00–10:30 Berlin, second Tuesdays (#520). + val begin = Instant.parse("2026-12-08T08:00:00Z") + val end = Instant.parse("2026-12-08T09:30:00Z") + val fake = FakeCalendarDataSource().apply { + calendarsResult = listOf(cal(1L)) + eventDetailResult = { detail(calendarId = 1L, rrule = "FREQ=MONTHLY;BYDAY=2TU", start = begin, end = end) } + } + val vm = viewModel(tempDir, fake, zones = FakeZoneSource(berlin)) + val job = activate(vm) + vm.openForEdit(eventId = 1L, beginMillis = begin.toEpochMilliseconds(), endMillis = end.toEpochMilliseconds()) + advanceUntilIdle() + + vm.setStartDate(LocalDate(2026, 12, 16)) + val form = vm.state.value!!.form!! + assertThat(form.start.dateTime).isEqualTo(LocalDateTime(2027, 1, 12, 9, 0)) + assertThat(form.end.dateTime).isEqualTo(LocalDateTime(2027, 1, 12, 10, 30)) + + vm.setStartTime(LocalTime(11, 0)) + assertThat(vm.state.value!!.form!!.start.dateTime).isEqualTo(LocalDateTime(2027, 1, 12, 11, 0)) + job.cancel() + } +}