Compare commits

..
9 changed files with 527 additions and 33 deletions

No files matched your search

@@ -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,71 @@ data class SimpleRecurrence(
* no BYDAY part — the provider derives the day from DTSTART.
*/
val byDays: Set<DayOfWeek> = 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)
private val TOKEN = Regex("""([+-]?\d)(MO|TU|WE|TH|FR|SA|SU)""")
}
}
enum class RecurrenceFreq {
Daily,
Weekly,
@@ -69,12 +135,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<DayOfWeek>()
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 +156,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 +185,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 +224,7 @@ internal val RRULE_DAY_CODES: Map<DayOfWeek, String> = 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 +254,14 @@ 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)
}
@@ -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<LocalDate> {
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
@@ -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<out Any>) -> 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 → "<base> on <days>"; other BYDAY forms keep just the base.
// Weekly + BYDAY → "<base> on <days>"; monthly + one ordinal BYDAY →
// "<base> on the second <day>"; 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<String>? = 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()) {
@@ -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.of(startDate)).token)
}
val weekdayPosition = MonthlyWeekday.parse(weekdayToken) ?: MonthlyWeekday.of(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
@@ -31,6 +31,7 @@ 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.nextFullHour
import de.jeanlucmakiola.calendula.domain.toFormTime
import de.jeanlucmakiola.calendula.domain.resolvedZone
@@ -758,8 +759,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
* monthly weekday-position rule moves the start onto its first matching day (#520).
*/
fun setRecurrence(rrule: String?) = edit { it.copy(rrule = rrule).alignedToRecurrence(zoneSource.current()) }
fun addReminder(minutes: Int) {
_remindersTouched.value = true
+25
View File
@@ -221,6 +221,24 @@
<string name="event_edit_recurrence_end_until">On a date</string>
<string name="event_edit_recurrence_end_count">After a number of times</string>
<string name="event_edit_recurrence_times">times</string>
<!-- Monthly custom rule: repeat on the start date's day of the month, e.g. "On day 14" (#520) -->
<string name="event_edit_recurrence_monthly_day">On day %1$d</string>
<!-- Monthly custom rule by weekday position; %1$s is a full weekday name, e.g. "On the second Tuesday" (#520) -->
<string name="event_edit_recurrence_monthly_weekday_first">On the first %1$s</string>
<string name="event_edit_recurrence_monthly_weekday_second">On the second %1$s</string>
<string name="event_edit_recurrence_monthly_weekday_third">On the third %1$s</string>
<string name="event_edit_recurrence_monthly_weekday_fourth">On the fourth %1$s</string>
<string name="event_edit_recurrence_monthly_weekday_fifth">On the fifth %1$s</string>
<string name="event_edit_recurrence_monthly_weekday_last">On the last %1$s</string>
<!-- Monthly weekday position: picker titles and its options (#520) -->
<string name="event_edit_recurrence_position">Position</string>
<string name="event_edit_recurrence_weekday">Weekday</string>
<string name="recurrence_position_first">First</string>
<string name="recurrence_position_second">Second</string>
<string name="recurrence_position_third">Third</string>
<string name="recurrence_position_fourth">Fourth</string>
<string name="recurrence_position_fifth">Fifth</string>
<string name="recurrence_position_last">Last</string>
<string name="event_edit_error_recurrence_ends_before_start">Repeats end before the event starts</string>
<string name="event_availability_busy">Busy</string>
<string name="event_access_default">Default</string>
@@ -247,6 +265,13 @@
<string name="recurrence_every_n_months">Every %1$d months</string>
<string name="recurrence_every_n_years">Every %1$d years</string>
<string name="recurrence_on_days">%1$s on %2$s</string>
<!-- %1$s is the frequency phrase ("Every month", "Every 2 months"), %2$s a full weekday name (#520) -->
<string name="recurrence_monthly_weekday_first">%1$s on the first %2$s</string>
<string name="recurrence_monthly_weekday_second">%1$s on the second %2$s</string>
<string name="recurrence_monthly_weekday_third">%1$s on the third %2$s</string>
<string name="recurrence_monthly_weekday_fourth">%1$s on the fourth %2$s</string>
<string name="recurrence_monthly_weekday_fifth">%1$s on the fifth %2$s</string>
<string name="recurrence_monthly_weekday_last">%1$s on the last %2$s</string>
<string name="recurrence_with_until">%1$s until %2$s</string>
<string name="recurrence_with_count">%1$s, %2$d times</string>
<string name="event_detail_not_found">This event no longer exists.</string>
@@ -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
@@ -0,0 +1,186 @@
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()
}
}
@@ -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")
}
}