diff --git a/CHANGELOG.md b/CHANGELOG.md index 0a7c7cc6..7bb7f86a 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -7,6 +7,35 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0 ## [Unreleased] +## [2.23.0] — 2026-10-21 + +### Added +- **Long press an event to select it.** In the day, 3-day and week views, a long press lifts the event and selects it. Keep your finger down and move to drag it straight away. A selected event has handles at its top and bottom: drag them to change when it starts or ends, in 15-minute steps and across midnight if you want. The bar at the top edits, duplicates, shares or deletes it, and tapping elsewhere or going back deselects it. The bar shows the new times while you move or resize. Read-only events can be selected but not moved or resized ([#141]). +- **Long press an empty slot to draft an event.** In the day, 3-day and week views, a long press on free time drops a block of your default event length there. Move it while still holding, or let go and drag it or its handles into place, then tap the tick to open a new event at that time. The ✕, a tap elsewhere or going back throws the draft away ([#153]). +- **Tap a phone number in an event to call it.** Phone numbers in an event's title, location and description are now links. Tapping one opens your phone app with the number filled in, ready to call. A conference dial-in like "+1 646 558 8656,,850123#" brings its meeting ID along. Meeting IDs and PINs on their own, dates, times and amounts stay plain text. Long-pressing a field copies it, even when you press on a link ([#339]). +- **Formatted event descriptions read properly.** Descriptions from Outlook, Exchange and Google Calendar are often stored as HTML, which used to show up as a wall of tags. The event view now shows them as formatted text: bold, italics, lists and links work, table rows sit on one line each, and the fonts and colours the sender picked are left out so the text matches the app. Search matches the text you see. The edit form still shows the original, so saving an event never changes its formatting ([#271]). +- **Scroll back to earlier days in the agenda.** Scroll up past today to see earlier days' events, loaded a month at a time. Past days follow the past-events setting: Dim fades them, and with Hide the agenda still starts at today ([#367]). +- **Create an event from shared or selected text.** Share text to Calendula, or select text in another app and pick Create event from the selection menu, and the new-event form opens with it filled in. A shared subject becomes the title, otherwise the first line does, and the rest goes into the description. The event starts at the next full hour with your default length; Calendula doesn't try to read a date out of the text. If Calendula was opened just for this, saving or closing the form takes you back to the app you came from ([#306]). +- **Tapping an event can open the edit form.** Settings → Views → Events → Tapping an event opens can now be set to Edit form instead of Details. Taps in the views and in search then go straight to the editor for events you can edit; read-only events, reminder notifications and widgets still open the details. The editor has Duplicate, Share and Delete in its menu, and going back with unsaved changes asks whether to save, discard or keep editing ([#178]). +- **A black theme for AMOLED screens.** Settings → Appearance → Theme now has Black next to System, Light and Dark. It's the dark theme with pure black backgrounds, which saves battery on AMOLED screens and makes event colours stand out more. Day cells and the hour grid stay a shade above black so the grid lines still show, and sheets and menus still stand out from the page. It works with Material You colours too. The home-screen widgets aren't affected ([#181]). +- **Donate through Liberapay.** Settings → Support development now offers Liberapay for recurring donations next to Ko-fi for one-off tips. +- **More haptic feedback.** Swiping between days in the split month pane ticks, and dropping a moved or resized event gives a short buzz ([#116]). + +### Changed +- **The editor says Create for a new event.** New events, duplicates, shared text, imported .ics files and long-press drafts show Create instead of Save, so a duplicate no longer looks like you're editing the original ([#141]). + +### Fixed +- **Event colours follow the theme you picked in Calendula.** With the app set to Dark on a phone in light mode, or the other way round, events took their colours from the phone's setting, so they could come out too pale or too dark. They now match the app's theme. Starting the app with a theme set in Calendula also no longer flashes the phone's light or dark background first ([#181]). +- **Events on the day the clocks change show at their real time.** In the day, 3-day and week views, events later on the day of a daylight saving change were drawn an hour off, so a 14:45 event showed at 15:45. They now sit at their own time. When the clocks go back, 02:00 to 03:00 happens twice: an event in that hour now stays in the right one when you move, resize or edit it, and the editor and event details add the zone, like CEST or CET, so you can tell the two apart ([#387]). +- **The agenda always starts today.** Coming from the month or day view, the agenda used to start at the day you had open there, so "Next 30 days" could show the 1st to the 30th of the month. It now opens on today with your chosen range. Backing out of a day you opened from the agenda still returns you to where you were ([#367]). +- **Multi-day events dim on the days already behind you.** With past events dimmed, an event running over several days stayed at full strength on its earlier days until it ended. Those days now dim in the agenda, month, week and day views ([#367]). +- **Moving a recurring event to another calendar keeps the occurrences you changed.** Deleted occurrences used to come back after the move, and edited ones showed up twice. They now stay deleted or edited, and keep their colour. +- **Sharing an .ics file to Calendula opens the import,** even when the email app adds a subject line as text. +- **Rotating the phone no longer throws away an open import, duplicate or picker.** +- **The repeat-until date picker opens on today.** Near midnight it used to open on yesterday or tomorrow. +- **Tap ripples on week numbers, split-view day cells and the split-view handle stay inside their rounded shape** ([#413]). +- **The export calendar picker previews the back gesture** like the other full-screen pickers. + ## [2.22.5] — 2026-10-07 ### Fixed @@ -1848,4 +1877,15 @@ automatically, with zero telemetry and no internet permission. [#361]: https://codeberg.org/jlmakiola/calendula/issues/361 [#363]: https://codeberg.org/jlmakiola/calendula/issues/363 [#364]: https://codeberg.org/jlmakiola/calendula/issues/364 +[#367]: https://codeberg.org/jlmakiola/calendula/issues/367 [#373]: https://codeberg.org/jlmakiola/calendula/issues/373 +[#141]: https://codeberg.org/jlmakiola/calendula/issues/141 +[#153]: https://codeberg.org/jlmakiola/calendula/issues/153 +[#339]: https://codeberg.org/jlmakiola/calendula/issues/339 +[#387]: https://codeberg.org/jlmakiola/calendula/issues/387 +[#271]: https://codeberg.org/jlmakiola/calendula/issues/271 +[#181]: https://codeberg.org/jlmakiola/calendula/issues/181 +[#306]: https://codeberg.org/jlmakiola/calendula/issues/306 +[#178]: https://codeberg.org/jlmakiola/calendula/issues/178 +[#116]: https://codeberg.org/jlmakiola/calendula/issues/116 +[#413]: https://codeberg.org/jlmakiola/calendula/issues/413 diff --git a/app/build.gradle.kts b/app/build.gradle.kts index 156b73fc..16ea6ab2 100644 --- a/app/build.gradle.kts +++ b/app/build.gradle.kts @@ -32,8 +32,8 @@ android { // (up to 2.22.3: 2.22.3 -> 22203; from 2.22.4: 2.23.0-beta.1 -> 2230001, // 2.22.4 -> 2220499), and CI fails if the committed one doesn't match. // See docs/RELEASING.md. - versionCode = 2220599 - versionName = "2.22.5" + versionCode = 2230099 + versionName = "2.23.0" testInstrumentationRunner = "androidx.test.runner.AndroidJUnitRunner" } @@ -175,7 +175,10 @@ dependencies { implementation("de.jeanlucmakiola.floret:core-time") implementation("de.jeanlucmakiola.floret:core-locale") implementation("de.jeanlucmakiola.floret:core-crash") + implementation("de.jeanlucmakiola.floret:core-di") + implementation("de.jeanlucmakiola.floret:core-prefs") implementation("de.jeanlucmakiola.floret:core-reminders") + implementation("de.jeanlucmakiola.floret:core-android") implementation("de.jeanlucmakiola.floret:identity") implementation("de.jeanlucmakiola.floret:components") implementation(libs.kotlinx.coroutines.core) diff --git a/app/src/androidTest/java/de/jeanlucmakiola/calendula/data/calendar/MoveEventExceptionsTest.kt b/app/src/androidTest/java/de/jeanlucmakiola/calendula/data/calendar/MoveEventExceptionsTest.kt new file mode 100644 index 00000000..c9668d5c --- /dev/null +++ b/app/src/androidTest/java/de/jeanlucmakiola/calendula/data/calendar/MoveEventExceptionsTest.kt @@ -0,0 +1,91 @@ +package de.jeanlucmakiola.calendula.data.calendar + +import android.Manifest +import android.content.ContentUris +import android.content.ContentValues +import android.provider.CalendarContract +import androidx.test.ext.junit.runners.AndroidJUnit4 +import androidx.test.platform.app.InstrumentationRegistry +import androidx.test.rule.GrantPermissionRule +import com.google.common.truth.Truth.assertThat +import de.jeanlucmakiola.calendula.domain.toEditForm +import kotlinx.datetime.TimeZone +import org.junit.Rule +import org.junit.Test +import org.junit.runner.RunWith + +/** + * Moving a synced series keeps its deleted and edited occurrences, although the + * moved row has no `_sync_id` for exception rows to attach to. + */ +@RunWith(AndroidJUnit4::class) +class MoveEventExceptionsTest { + + @get:Rule + val permissionRule: GrantPermissionRule = GrantPermissionRule.grant( + Manifest.permission.READ_CALENDAR, + Manifest.permission.WRITE_CALENDAR, + ) + + private val context = InstrumentationRegistry.getInstrumentation().targetContext + private val resolver = context.contentResolver + private val ds = AndroidCalendarDataSource(context) + private val zone = TimeZone.currentSystemDefault() + + private val day = 86_400_000L + private val start = 1_893_492_000_000L // 2030-01-01T10:00Z + private val hour = 3_600_000L + + /** "day offset:title" of every instance on [calendarId]. */ + private fun occurrences(calendarId: Long): List = + ds.instances(start - day, start + 10 * day) + .filter { it.calendarId == calendarId } + .map { "${(it.start.toEpochMilliseconds() - start) / day}:${it.title}" } + .sorted() + + @Test + fun movedSeriesKeepsCancelledAndModifiedOccurrences() { + val a = ds.createLocalCalendar("move-test-a", 0xFF336699.toInt(), null) + val b = ds.createLocalCalendar("move-test-b", 0xFF993366.toInt(), null) + try { + val src = insertSyncedSeries(a) + ds.deleteOccurrence(src, start + 2 * day) + val occurrence = ds.eventDetail(src, 540)!!.toEditForm(start + 3 * day, start + 3 * day + hour, zone) + ds.updateOccurrence(src, start + 3 * day, occurrence, occurrence.copy(title = "edited"), 540) + val expected = listOf("0:series", "1:series", "3:edited", "4:series") + assertThat(occurrences(a)).isEqualTo(expected) + + val form = ds.eventDetail(src, 540)!!.toEditForm(start, start + hour, zone) + ds.moveEvent(src, b, form, form, 540) + + assertThat(occurrences(a)).isEmpty() + assertThat(occurrences(b)).isEqualTo(expected) + } finally { + ds.deleteCalendar(a) + ds.deleteCalendar(b) + } + } + + /** A daily series carrying a `_sync_id`, so its exceptions are real exception rows. */ + private fun insertSyncedSeries(calendarId: Long): Long { + val accountName = resolver.query( + ContentUris.withAppendedId(CalendarContract.Calendars.CONTENT_URI, calendarId), + arrayOf(CalendarContract.Calendars.ACCOUNT_NAME), null, null, null, + )!!.use { it.moveToFirst(); it.getString(0) } + val uri = CalendarContract.Events.CONTENT_URI.buildUpon() + .appendQueryParameter(CalendarContract.CALLER_IS_SYNCADAPTER, "true") + .appendQueryParameter(CalendarContract.Calendars.ACCOUNT_NAME, accountName) + .appendQueryParameter(CalendarContract.Calendars.ACCOUNT_TYPE, CalendarContract.ACCOUNT_TYPE_LOCAL) + .build() + val values = ContentValues().apply { + put(CalendarContract.Events.CALENDAR_ID, calendarId) + put(CalendarContract.Events.TITLE, "series") + put(CalendarContract.Events.DTSTART, start) + put(CalendarContract.Events.DURATION, "P3600S") + put(CalendarContract.Events.RRULE, "FREQ=DAILY;COUNT=5") + put(CalendarContract.Events.EVENT_TIMEZONE, "UTC") + put(CalendarContract.Events._SYNC_ID, "move-test-series") + } + return ContentUris.parseId(resolver.insert(uri, values)!!) + } +} diff --git a/app/src/androidTest/java/de/jeanlucmakiola/calendula/ui/detail/PhoneLinksPlatformTest.kt b/app/src/androidTest/java/de/jeanlucmakiola/calendula/ui/detail/PhoneLinksPlatformTest.kt new file mode 100644 index 00000000..254ae5e3 --- /dev/null +++ b/app/src/androidTest/java/de/jeanlucmakiola/calendula/ui/detail/PhoneLinksPlatformTest.kt @@ -0,0 +1,101 @@ +package de.jeanlucmakiola.calendula.ui.detail + +import androidx.test.ext.junit.runners.AndroidJUnit4 +import com.google.common.truth.Truth.assertThat +import org.junit.Test +import org.junit.runner.RunWith + +/** + * The platform phone matcher on real text. It reads the region off the SIM, + * so these stick to international numbers and to text that must never match + * anywhere — domestic formats depend on the device they run on. + */ +@RunWith(AndroidJUnit4::class) +class PhoneLinksPlatformTest { + + private fun numbers(text: String) = findPhoneLinks(text).map { it.number } + + @Test + fun internationalNumbers_areFound() { + assertThat(numbers("Call +49 30 1234567 or +1 646-558-8656")) + .containsExactly("+49301234567", "+16465588656") + .inOrder() + } + + @Test + fun trunkZero_isDroppedWithOrWithoutSpace() { + assertThat(numbers("+49 (0)151 2345678")).containsExactly("+491512345678") + assertThat(numbers("+49 (0) 151 2345678")).containsExactly("+491512345678") + } + + @Test + fun neighbouringNumbers_doNotJoinTheNumber() { + assertThat(numbers("Start 10:00 +49 151 2345678")).containsExactly("+491512345678") + assertThat(numbers("Call +49 151 2345678 2 times")).containsExactly("+491512345678") + } + + @Test + fun conferenceDialIn_keepsMeetingId() { + assertThat(numbers("One tap mobile: +16465588656,,85012345678# US")) + .containsExactly("+16465588656,,85012345678#") + } + + @Test + fun meetingIds_areNotNumbers() { + assertThat(numbers("Meeting ID: 850 1234 5678")).isEmpty() + assertThat(numbers("Conference ID: 123 456 789#")).isEmpty() + } + + @Test + fun datesAndTimes_areNotNumbers() { + assertThat(numbers("2026-10-14 10:00")).isEmpty() + assertThat(numbers("Am 14.10.2026 10:00 Uhr")).isEmpty() + assertThat(numbers("14.10.26 - 16.10.26")).isEmpty() + assertThat(numbers("10:00 - 11:30")).isEmpty() + assertThat(numbers("Schuljahr 2025/2026, Season 2025-2026")).isEmpty() + assertThat(numbers("1.10.2026 - 3.10.2026")).isEmpty() + } + + @Test + fun amounts_areNotNumbers() { + assertThat(numbers("Budget 1.250.000 EUR, 1 250 000 EUR")).isEmpty() + } + + @Test + fun isbn_isNotANumber() { + assertThat(numbers("ISBN 978-3-16-148410-0")).isEmpty() + } + + @Test + fun extension_becomesAPause() { + assertThat(numbers("+1 212 555 1234 ext. 567")).containsExactly("+12125551234,567") + } + + @Test + fun webexAccessCode_isNotANumber() { + assertThat(numbers("Meeting number (access code): 2732 123 4567")).isEmpty() + } + + @Test + fun commaSeparatedNumbers_stayApart() { + assertThat(numbers("+49 30 1234567,+49 151 2345678")) + .containsExactly("+49301234567", "+491512345678") + .inOrder() + } + + @Test + fun dottedTimes_areNotNumbers() { + assertThat(numbers("Beginn 9.30 – 12.00 Uhr")).isEmpty() + assertThat(numbers("10.00-11.30")).isEmpty() + } + + @Test + fun schemelessUrlDigits_areNotNumbers() { + assertThat(numbers("zoom.us/j/85012345678")).isEmpty() + } + + @Test + fun webLinkDigits_areNotNumbers() { + assertThat(numbers("https://zoom.us/j/85012345678?pwd=1")).isEmpty() + } +} diff --git a/app/src/main/AndroidManifest.xml b/app/src/main/AndroidManifest.xml index a7e97b68..b7cf5c55 100644 --- a/app/src/main/AndroidManifest.xml +++ b/app/src/main/AndroidManifest.xml @@ -151,6 +151,19 @@ + + + + + + + + + + + + ", lt + 4) + return if (end < 0) html.length else end + 3 + } + if (html.startsWith("', lt) + return if (end < 0) html.length else end + 1 + } + val closing = html.getOrNull(lt + 1) == '/' + val nameStart = if (closing) lt + 2 else lt + 1 + if (html.getOrNull(nameStart)?.isLetter() != true) { + text("<") + return lt + 1 + } + val end = tagEnd(lt) + if (end < 0) { + text("<") + return lt + 1 + } + if (!closing && isAutolink(html.substring(nameStart, end))) { + text(html.substring(lt, end + 1)) + return end + 1 + } + var nameEnd = nameStart + while (nameEnd < end && (html[nameEnd].isLetterOrDigit() || html[nameEnd] == ':')) nameEnd++ + val name = html.substring(nameStart, nameEnd).lowercase() + val attrs = html.substring(nameEnd, end) + if (closing) { + close(name) + } else if (name in SKIPPED_TAGS && !attrs.trimEnd().endsWith("/")) { + // Never closed (an omitted is valid): just ignore the tag. + val closeAt = html.indexOf("', closeAt) + return if (closeEnd < 0) html.length else closeEnd + 1 + } else { + open(name, attrs) + } + return end + 1 + } + + /** An angle-bracketed URL or address (``, ``), kept as text. */ + private fun isAutolink(inner: String): Boolean = + LINK_SCHEMES.any { inner.startsWith(it, ignoreCase = true) } || + ('@' in inner && inner.none { it.isWhitespace() || it == '=' }) + + /** The `>` closing the tag at [lt], skipping any inside quoted attributes. */ + private fun tagEnd(lt: Int): Int { + var quote: Char? = null + for (j in lt + 1 until html.length) { + val c = html[j] + when { + quote != null -> if (c == quote) quote = null + c == '"' || c == '\'' -> quote = c + c == '>' -> return j + c == '<' -> return -1 + } + } + return -1 + } + + private fun open(name: String, attrs: String) { + when (name) { + "br" -> newline() + "li" -> { + markerEnd = -1 + cellNeedsSeparator = false + lineBreak() + val list = lists.lastOrNull() + out.append("$NBSP$NBSP".repeat((lists.size - 1).coerceAtLeast(0))) + if (list?.ordered == true) { + list.count++ + out.append("${list.count}. ") + } else { + out.append("• ") + } + markerEnd = out.length + } + "ul", "ol" -> { + cellNeedsSeparator = false + lineBreak() + val start = startRegex.find(attrs)?.groupValues?.get(1)?.toIntOrNull() ?: 1 + lists += ListState(ordered = name == "ol", count = start - 1) + } + "tr" -> { + lineBreak() + rowStart = out.length + cellNeedsSeparator = false + } + "td", "th" -> { + // An empty spacer cell leaves nothing behind, not even its  . + if (rowStart <= out.length && (rowStart until out.length).none { out[it].isContent() }) { + cut(rowStart) + } else { + cellNeedsSeparator = true + } + } + "a" -> { + closeLink() + hrefRegex.find(attrs) + ?.groupValues?.drop(1)?.firstOrNull { it.isNotEmpty() } + ?.let(::decodeEntities) + ?.trim() + ?.let { href -> + val scheme = LINK_SCHEMES.firstOrNull { href.startsWith(it, ignoreCase = true) } + ?: return@let + // Intent filters match the scheme case-sensitively. + openLink = scheme + href.substring(scheme.length) to out.length + } + } + else -> if (name in BLOCK_TAGS) lineBreak() + } + if (name == "pre") preDepth++ + STYLE_TAGS[name]?.let { openStyles += name to out.length } + } + + private fun close(name: String) { + // A row's last cell, if empty, leaves a separator pending; it ends with the row. + if (name == "tr" || name == "table") cellNeedsSeparator = false + val index = openStyles.indexOfLast { it.first == name } + if (index >= 0) { + val (_, start) = openStyles.removeAt(index) + if (out.length > start) styles += StyleRange(start, out.length, STYLE_TAGS.getValue(name)) + } + if (name == "pre") preDepth = (preDepth - 1).coerceAtLeast(0) + if (name == "li" || name == "ul" || name == "ol") { + if (out.length == markerEnd) cut(out.lastIndexOf("\n") + 1) + markerEnd = -1 + } + when (name) { + "ul", "ol" -> { + lists.removeLastOrNull() + lineBreak() + } + "a" -> closeLink() + else -> if (name in BLOCK_TAGS) lineBreak() + } + } + + private fun closeLink() { + val (url, start) = openLink ?: return + if (out.length > start) links += LinkRange(start, out.length, url) + openLink = null + } + + private fun text(raw: String) { + val decoded = decodeEntities(raw) + if (preDepth > 0) { + out.append(decoded.replace("\r\n", "\n")) + return + } + for (c in decoded) { + if (c == '\n' && keepNewlines) { + newline() + } else if (c == ' ' || c == '\n' || c == '\t' || c == '\r' || c == '\u000C') { + if (out.isNotEmpty() && out.last() != ' ' && out.last() != '\n') out.append(' ') + } else { + if (cellNeedsSeparator && c.isContent()) separateCell() + out.append(c) + } + } + } + + /** Put this cell's text beside the row's last, even after a block in that cell ended its line. */ + private fun separateCell() { + cellNeedsSeparator = false + var end = out.length + while (end > rowStart && !out[end - 1].isContent()) end-- + cut(end) + out.append(CELL_SEPARATOR) + openStyles.replaceAll { (name, start) -> name to if (start >= end) out.length else start } + openLink = openLink?.let { (url, start) -> url to if (start >= end) out.length else start } + } + + private fun Char.isContent() = !isWhitespace() && this != NBSP + + private fun newline() { + trimTrailingSpaces() + out.append('\n') + } + + /** End the current line, unless it's already ended or holds just a bullet. */ + private fun lineBreak() { + if (out.length == markerEnd) return + trimTrailingSpaces() + if (out.isNotEmpty() && out.last() != '\n') out.append('\n') + } + + private fun trimTrailingSpaces() { + while (out.isNotEmpty() && out.last() == ' ') out.setLength(out.length - 1) + } + + /** Drop the output from [length] on, with whatever formatting lay only there. */ + private fun cut(length: Int) { + if (length >= out.length) return + out.setLength(length) + styles.replaceAll { it.copy(end = minOf(it.end, length)) } + styles.removeAll { it.end <= it.start } + links.replaceAll { it.copy(end = minOf(it.end, length)) } + links.removeAll { it.end <= it.start } + openStyles.replaceAll { (name, start) -> name to minOf(start, length) } + openLink = openLink?.let { (url, start) -> url to minOf(start, length) } + } + + /** + * Tidy the rendered text: no-break spaces become plain, lines lose trailing + * blanks, runs of empty lines shrink to one and the ends are trimmed. Spans + * move with the text they cover. + */ + private fun normalize(): RichText { + closeLink() + for ((name, start) in openStyles) { + if (out.length > start) styles += StyleRange(start, out.length, STYLE_TAGS.getValue(name)) + } + val src = out.toString().replace(NBSP, ' ') + val map = IntArray(src.length + 1) + val result = StringBuilder() + var i = 0 + while (i < src.length) { + var lineEnd = src.indexOf('\n', i) + if (lineEnd < 0) lineEnd = src.length + var contentEnd = lineEnd + while (contentEnd > i && src[contentEnd - 1].isWhitespace()) contentEnd-- + for (j in i until lineEnd) { + map[j] = result.length + if (j < contentEnd) result.append(src[j]) + } + if (lineEnd < src.length) { + map[lineEnd] = result.length + if (!result.endsWith("\n\n")) result.append('\n') + } + i = lineEnd + 1 + } + map[src.length] = result.length + val leading = result.length - result.trimStart().length + val text = result.trim().toString() + fun at(index: Int) = (map[index] - leading).coerceIn(0, text.length) + return RichText( + text = text, + styles = styles.mapNotNull { r -> StyleRange(at(r.start), at(r.end), r.style).takeIf { it.end > it.start } }, + links = links.mapNotNull { r -> LinkRange(at(r.start), at(r.end), r.url).takeIf { it.end > it.start } }, + ) + } +} + +private val startRegex = Regex("""(?:^|\s)start\s*=\s*["']?(-?\d{1,6})""", RegexOption.IGNORE_CASE) +private val hrefRegex = Regex("""(?:^|\s)href\s*=\s*(?:"([^"]*)"|'([^']*)'|([^\s>]+))""", RegexOption.IGNORE_CASE) + +// Latin-1 (  … ÿ) in code point order, then the common extras. +private val LATIN1_ENTITIES = ("nbsp iexcl cent pound curren yen brvbar sect uml copy ordf laquo not shy reg macr " + + "deg plusmn sup2 sup3 acute micro para middot cedil sup1 ordm raquo frac14 frac12 frac34 iquest " + + "Agrave Aacute Acirc Atilde Auml Aring AElig Ccedil Egrave Eacute Ecirc Euml Igrave Iacute Icirc Iuml " + + "ETH Ntilde Ograve Oacute Ocirc Otilde Ouml times Oslash Ugrave Uacute Ucirc Uuml Yacute THORN szlig " + + "agrave aacute acirc atilde auml aring aelig ccedil egrave eacute ecirc euml igrave iacute icirc iuml " + + "eth ntilde ograve oacute ocirc otilde ouml divide oslash ugrave uacute ucirc uuml yacute thorn yuml").split(' ') + +private val ENTITIES: Map = LATIN1_ENTITIES.withIndex() + .associate { (i, name) -> name to (0xA0 + i).toChar().toString() } + mapOf( + "amp" to "&", "lt" to "<", "gt" to ">", "quot" to "\"", "apos" to "'", + "ndash" to "–", "mdash" to "—", "hellip" to "…", "bull" to "•", + "lsquo" to "‘", "rsquo" to "’", "ldquo" to "“", "rdquo" to "”", "sbquo" to "‚", "bdquo" to "„", + "euro" to "€", "trade" to "™", "OElig" to "Œ", "oelig" to "œ", "Scaron" to "Š", "scaron" to "š", + "zwnj" to "\u200C", "zwj" to "\u200D", "ensp" to "\u2002", "emsp" to "\u2003", "thinsp" to "\u2009", +) + +// A named reference needs its ";": "?id=5®=eu" in a link is a query, not "®". +private val entityRegex = Regex("""&(?:(#[0-9]{1,7}|#[xX][0-9a-fA-F]{1,6});?|([a-zA-Z][a-zA-Z0-9]{1,31});)""") + +/** Decode character references; an unknown name is left as written. */ +internal fun decodeEntities(text: String): String { + if ('&' !in text) return text + return entityRegex.replace(text) { match -> + val name = match.groupValues[2] + if (name.isNotEmpty()) return@replace ENTITIES[name] ?: match.value + val body = match.groupValues[1] + val code = when { + body.startsWith("#x", ignoreCase = true) -> body.substring(2).toIntOrNull(16) + else -> body.substring(1).toIntOrNull() + } + if (code == null || code == 0 || !Character.isValidCodePoint(code)) "�" else String(Character.toChars(code)) + } +} diff --git a/app/src/main/java/de/jeanlucmakiola/calendula/domain/InsertEventForm.kt b/app/src/main/java/de/jeanlucmakiola/calendula/domain/InsertEventForm.kt index 2dd0db8d..0a6c0c18 100644 --- a/app/src/main/java/de/jeanlucmakiola/calendula/domain/InsertEventForm.kt +++ b/app/src/main/java/de/jeanlucmakiola/calendula/domain/InsertEventForm.kt @@ -1,10 +1,6 @@ package de.jeanlucmakiola.calendula.domain -import kotlinx.datetime.LocalDate -import kotlinx.datetime.LocalDateTime -import kotlinx.datetime.LocalTime import kotlinx.datetime.TimeZone -import kotlinx.datetime.toInstant import kotlinx.datetime.toLocalDateTime import kotlin.time.Duration.Companion.hours import kotlin.time.Instant @@ -25,37 +21,27 @@ import kotlin.time.Instant * the extras lives in `MainActivity.insertFormOrNull`. */ fun buildInsertEventForm( - beginMillis: Long?, - endMillis: Long?, - isAllDay: Boolean, + beginMillis: Long? = null, + endMillis: Long? = null, + isAllDay: Boolean = false, title: String?, description: String?, - location: String?, - rrule: String?, + location: String? = null, + rrule: String? = null, zone: TimeZone, now: Instant, ): EventForm { val (start, end) = if (isAllDay) { - // All-day provider times are UTC midnights with an exclusive end; show - // the last covered day and keep placeholder wall-clock times in case the - // user switches the event to timed (mirrors EventDetail.toEditForm). val startDate = beginMillis ?.let { Instant.fromEpochMilliseconds(it).toLocalDateTime(TimeZone.UTC).date } ?: now.toLocalDateTime(zone).date - val endDate = endMillis - ?.let { Instant.fromEpochMilliseconds(it).toLocalDateTime(TimeZone.UTC).date } - ?.let { exclusive -> maxOf(startDate, LocalDate.fromEpochDays(exclusive.toEpochDays() - 1)) } - ?: startDate - LocalDateTime(startDate, LocalTime(9, 0)) to LocalDateTime(endDate, LocalTime(10, 0)) + val endExclusive = endMillis?.let { Instant.fromEpochMilliseconds(it).toLocalDateTime(TimeZone.UTC).date } + allDayFormTimes(startDate, endExclusive) } else { - val startTime = beginMillis - ?.let { Instant.fromEpochMilliseconds(it).toLocalDateTime(zone) } - ?: nextFullHour(now, zone) - val endTime = endMillis - ?.let { Instant.fromEpochMilliseconds(it).toLocalDateTime(zone) } - ?.takeIf { it >= startTime } - ?: (startTime.toInstant(zone) + 1.hours).toLocalDateTime(zone) - startTime to endTime + val startAt = beginMillis?.let(Instant::fromEpochMilliseconds) ?: nextFullHour(now) + val endAt = endMillis?.let(Instant::fromEpochMilliseconds)?.takeIf { it >= startAt } + ?: (startAt + 1.hours) + startAt.toFormTime(zone) to endAt.toFormTime(zone) } return EventForm( calendarId = null, @@ -67,12 +53,38 @@ fun buildInsertEventForm( description = description.orEmpty(), // Bare RRULE value (Events.RRULE convention); tolerate a leading "RRULE:" // some callers include. - rrule = rrule?.removePrefix("RRULE:")?.takeIf { it.isNotBlank() }, + rrule = rrule.normalizedRrule(), ) } -private fun nextFullHour(now: Instant, zone: TimeZone): LocalDateTime { +/** The first full hour after [now]: may roll into the next day before midnight. */ +internal fun nextFullHour(now: Instant): Instant { val hourMillis = 3_600_000L - val rounded = (now.toEpochMilliseconds() / hourMillis + 1) * hourMillis - return Instant.fromEpochMilliseconds(rounded).toLocalDateTime(zone) + return Instant.fromEpochMilliseconds((now.toEpochMilliseconds() / hourMillis + 1) * hourMillis) +} + +/** Title and description for text shared or selected into the app (#306). */ +data class SharedText(val title: String, val description: String) + +/** + * Split shared text into an event title and description: the share's subject + * becomes the title and the text the description. Without a subject the text's + * first non-blank line is the title and the rest the description. A title longer + * than [maxTitle] is cut, and the full text then stays in the description. + * Null when there is nothing to use. + */ +fun sharedTextOrNull(subject: String?, text: String?, maxTitle: Int = 255): SharedText? { + val body = text?.trim().orEmpty() + val given = subject?.trim()?.takeIf { it.isNotEmpty() } + val (title, rest) = if (given != null) { + given to body + } else { + val lines = body.lines() + val first = lines.firstOrNull()?.trim()?.takeIf { it.isNotEmpty() } ?: return null + first to lines.drop(1).joinToString("\n").trim() + } + if (title.length <= maxTitle) return SharedText(title, rest) + val cut = title.take(maxTitle).let { if (it.last().isHighSurrogate()) it.dropLast(1) else it } + val full = if (given != null) listOf(given, body).filter { it.isNotEmpty() }.joinToString("\n\n") else body + return SharedText(cut.trimEnd(), full) } diff --git a/app/src/main/java/de/jeanlucmakiola/calendula/domain/Models.kt b/app/src/main/java/de/jeanlucmakiola/calendula/domain/Models.kt index 89f086ad..0dad2ed6 100644 --- a/app/src/main/java/de/jeanlucmakiola/calendula/domain/Models.kt +++ b/app/src/main/java/de/jeanlucmakiola/calendula/domain/Models.kt @@ -165,6 +165,17 @@ data class EventDetail( val isException: Boolean = false, ) +/** + * This event on one occurrence's times. The Events row holds the series start, + * so a recurring event needs the tapped occurrence pinned to render and share right. + */ +fun EventDetail.atOccurrence(beginMillis: Long, endMillis: Long): EventDetail = copy( + instance = instance.copy( + start = Instant.fromEpochMilliseconds(beginMillis), + end = Instant.fromEpochMilliseconds(endMillis), + ), +) + /** * One selectable event colour published by a calendar's account * (`CalendarContract.Colors`, `TYPE_EVENT`): [key] is the account-scoped 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 7b6ecdea..3e55232f 100644 --- a/app/src/main/java/de/jeanlucmakiola/calendula/domain/Recurrence.kt +++ b/app/src/main/java/de/jeanlucmakiola/calendula/domain/Recurrence.kt @@ -1,5 +1,8 @@ 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.DayOfWeek import kotlinx.datetime.LocalDate import kotlinx.datetime.LocalDateTime @@ -57,24 +60,13 @@ fun parseSimpleRecurrence( rrule: String, zone: TimeZone = TimeZone.currentSystemDefault(), ): SimpleRecurrence? { - val parts = rrule.removePrefix("RRULE:").split(';') - .filter { it.isNotBlank() } - .associate { token -> - val eq = token.indexOf('=') - if (eq <= 0) return null - token.substring(0, eq).uppercase() to token.substring(eq + 1) - } + val parts = rruleParts(rrule).associate { part -> (part.key ?: return null) to part.value } if (parts.keys.any { it !in setOf("FREQ", "INTERVAL", "UNTIL", "COUNT", "WKST", "BYDAY") }) { return null } - val freq = when (parts["FREQ"]?.uppercase()) { - "DAILY" -> RecurrenceFreq.Daily - "WEEKLY" -> RecurrenceFreq.Weekly - "MONTHLY" -> RecurrenceFreq.Monthly - "YEARLY" -> RecurrenceFreq.Yearly - else -> return null - } + val freq = RecurrenceFreq.entries.firstOrNull { it.name.equals(parts["FREQ"], ignoreCase = true) } + ?: 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 @@ -124,20 +116,27 @@ fun SimpleRecurrence.toRRule(zone: TimeZone = TimeZone.currentSystemDefault()): when (val e = end) { RecurrenceEnd.Never -> Unit is RecurrenceEnd.Until -> { - val utc = LocalDateTime(e.date, LocalTime(23, 59, 59)) - .toInstant(zone) - .toLocalDateTime(TimeZone.UTC) - append( - ";UNTIL=%04d%02d%02dT%02d%02d%02dZ".format( - utc.year, utc.month.number, utc.day, - utc.hour, utc.minute, utc.second, - ), - ) + append(";UNTIL=") + append(LocalDateTime(e.date, LocalTime(23, 59, 59)).toInstant(zone).toUtcBasic()) } is RecurrenceEnd.Count -> append(";COUNT=${e.times}") } } +/** One `;`-separated part of an RRULE as written; [key] is null when it has no `KEY=`. */ +internal class RrulePart(val raw: String) { + private val eq = raw.indexOf('=') + val key: String? = if (eq > 0) raw.substring(0, eq).uppercase() else null + val value: String = if (eq > 0) raw.substring(eq + 1) else "" +} + +/** + * [rule]'s non-blank parts, after an optional leading "RRULE:". What to do + * with a malformed one (reject, repair or skip) is the caller's call. + */ +internal fun rruleParts(rule: String): List = + rule.removePrefix("RRULE:").split(';').filter { it.isNotBlank() }.map(::RrulePart) + internal val RRULE_DAY_CODES: Map = mapOf( DayOfWeek.MONDAY to "MO", DayOfWeek.TUESDAY to "TU", @@ -165,11 +164,7 @@ fun rruleTruncatedAt(rrule: String, untilUtcMillis: Long): String { val key = part.substringBefore('=').trim().uppercase() key == "UNTIL" || key == "COUNT" } - val until = Instant.fromEpochMilliseconds(untilUtcMillis).toLocalDateTime(TimeZone.UTC) - val untilPart = "UNTIL=%04d%02d%02dT%02d%02d%02dZ".format( - until.year, until.month.number, until.day, - until.hour, until.minute, until.second, - ) + val untilPart = "UNTIL=" + Instant.fromEpochMilliseconds(untilUtcMillis).toUtcBasic() return (kept + untilPart).joinToString(";") } @@ -178,20 +173,8 @@ fun rruleTruncatedAt(rrule: String, untilUtcMillis: Long): String { * forms are UTC (RFC 5545); the date is taken after converting into [zone] so * a [toRRule]-rendered value round-trips to the day the user picked. */ -private fun parseUntilDate(raw: String, zone: TimeZone): LocalDate? = runCatching { - val date = LocalDate( - raw.substring(0, 4).toInt(), - raw.substring(4, 6).toInt(), - raw.substring(6, 8).toInt(), - ) - if (raw.length >= 15 && raw[8] == 'T') { - val time = LocalTime( - raw.substring(9, 11).toInt(), - raw.substring(11, 13).toInt(), - raw.substring(13, 15).toInt(), - ) - LocalDateTime(date, time).toInstant(TimeZone.UTC).toLocalDateTime(zone).date - } else { - date - } -}.getOrNull() +private fun parseUntilDate(raw: String, zone: TimeZone): LocalDate? { + val date = parseBasicDate(raw) ?: return null + if (raw.length < 15 || raw[8] != 'T') return date + return parseBasicDateTime(raw)?.toInstant(TimeZone.UTC)?.toLocalDateTime(zone)?.date +} diff --git a/app/src/main/java/de/jeanlucmakiola/calendula/domain/RecurrenceRealign.kt b/app/src/main/java/de/jeanlucmakiola/calendula/domain/RecurrenceRealign.kt index b55db7d2..205e2a2c 100644 --- a/app/src/main/java/de/jeanlucmakiola/calendula/domain/RecurrenceRealign.kt +++ b/app/src/main/java/de/jeanlucmakiola/calendula/domain/RecurrenceRealign.kt @@ -19,30 +19,30 @@ import kotlinx.datetime.LocalDate fun realignRecurrence(rrule: String, oldStart: LocalDate, newStart: LocalDate): String? { if (oldStart == newStart) return rrule val prefix = if (rrule.startsWith("RRULE:")) "RRULE:" else "" - val parts = rrule.removePrefix("RRULE:").split(';').filter { it.isNotBlank() } + val parts = rruleParts(rrule) if (parts.isEmpty()) return null + var freq = false var weekly = false + var byDay = false val rebuilt = parts.map { part -> - val eq = part.indexOf('=') - if (eq <= 0) return null - val key = part.substring(0, eq).uppercase() - val value = part.substring(eq + 1).trim() - when (key) { + val value = part.value.trim() + when (part.key) { "FREQ" -> { + freq = true weekly = value.equals("WEEKLY", ignoreCase = true) - part + part.raw } "BYDAY" -> { + byDay = true val old = RRULE_DAY_CODES[oldStart.dayOfWeek] ?: return null if (!value.equals(old, ignoreCase = true)) return null "BYDAY=${RRULE_DAY_CODES.getValue(newStart.dayOfWeek)}" } - "INTERVAL", "COUNT", "UNTIL", "WKST" -> part + "INTERVAL", "COUNT", "UNTIL", "WKST" -> part.raw else -> return null } } // BYDAY is only simple on a weekly rule, matching parseSimpleRecurrence. - if (!weekly && parts.any { it.substringBefore('=').trim().uppercase() == "BYDAY" }) return null - if (parts.none { it.substringBefore('=').trim().uppercase() == "FREQ" }) return null + if (!freq || (byDay && !weekly)) return null return prefix + rebuilt.joinToString(";") } diff --git a/app/src/main/java/de/jeanlucmakiola/calendula/domain/TimeZoneCatalog.kt b/app/src/main/java/de/jeanlucmakiola/calendula/domain/TimeZoneCatalog.kt index d19e483d..af6dca01 100644 --- a/app/src/main/java/de/jeanlucmakiola/calendula/domain/TimeZoneCatalog.kt +++ b/app/src/main/java/de/jeanlucmakiola/calendula/domain/TimeZoneCatalog.kt @@ -157,14 +157,36 @@ fun timeZoneOptionOf( * the offset isn't stated twice in ICU's spelling and ours. */ fun zoneDescriptor(option: TimeZoneOption): String { - val abbrev = option.shortName - return when { - abbrev == "UTC" -> "UTC" - abbrev.startsWith("GMT") -> formatGmtOffset(option.offsetMinutes) - else -> "$abbrev · ${formatGmtOffset(option.offsetMinutes)}" - } + val name = zoneAbbreviation(option) + val statesOffset = option.shortName == "UTC" || option.shortName.startsWith("GMT") + return if (statesOffset) name else "$name · ${formatGmtOffset(option.offsetMinutes)}" } +/** + * [option]'s short name on its own — "CEST", "UTC" — with an offset-shaped one + * normalised to our GMT form, as [zoneDescriptor] spells it. + */ +fun zoneAbbreviation(option: TimeZoneOption): String = abbreviation(option.shortName, option.offsetMinutes) + +/** + * Zone [id]'s abbreviation [at] an instant, as [zoneAbbreviation] spells it, + * without the localized long name a whole [TimeZoneOption] would look up. Null + * for an id the tz database can't parse. + */ +fun zoneAbbreviationAt( + id: String, + locale: Locale, + at: Instant, + regionOf: (String) -> String? = { null }, +): String? { + val zone = runCatching { ZoneId.of(id) }.getOrNull() ?: return null + val shortName = resolveAbbreviation(zone.id, zone.rules.isDaylightSavings(at), locale, regionOf) + return abbreviation(shortName, zone.rules.getOffset(at).totalSeconds / 60) +} + +private fun abbreviation(shortName: String, offsetMinutes: Int): String = + if (shortName.startsWith("GMT")) formatGmtOffset(offsetMinutes) else shortName + /** * [options] matching [query], best matches first; a blank query returns the list * unchanged. Matching is accent- and case-insensitive and treats underscores as diff --git a/app/src/main/java/de/jeanlucmakiola/calendula/domain/ics/BasicFormat.kt b/app/src/main/java/de/jeanlucmakiola/calendula/domain/ics/BasicFormat.kt new file mode 100644 index 00000000..324a1534 --- /dev/null +++ b/app/src/main/java/de/jeanlucmakiola/calendula/domain/ics/BasicFormat.kt @@ -0,0 +1,47 @@ +package de.jeanlucmakiola.calendula.domain.ics + +import kotlinx.datetime.LocalDate +import kotlinx.datetime.LocalDateTime +import kotlinx.datetime.LocalTime +import kotlinx.datetime.TimeZone +import kotlinx.datetime.format +import kotlinx.datetime.format.char +import kotlinx.datetime.toLocalDateTime +import kotlin.time.Instant + +/** RFC 5545 basic format, `yyyyMMddTHHmmss`. */ +private val BASIC_DATE_TIME = LocalDateTime.Format { + date(LocalDate.Formats.ISO_BASIC) + char('T') + hour() + minute() + second() +} + +/** `yyyyMMdd`. */ +internal fun LocalDate.toBasic(): String = format(LocalDate.Formats.ISO_BASIC) + +/** `yyyyMMddTHHmmss`, floating. */ +internal fun LocalDateTime.toBasic(): String = format(BASIC_DATE_TIME) + +/** `yyyyMMddTHHmmssZ`, the instant in UTC. */ +internal fun Instant.toUtcBasic(): String = toLocalDateTime(TimeZone.UTC).toBasic() + "Z" + +/** + * The date in the first eight characters of a basic-format value; whatever + * follows (a time, a `Z`) is ignored. Null when those aren't a valid date. + */ +internal fun parseBasicDate(s: String): LocalDate? = runCatching { + LocalDate(s.substring(0, 4).toInt(), s.substring(4, 6).toInt(), s.substring(6, 8).toInt()) +}.getOrNull() + +/** `yyyyMMddTHHmm[ss]`; the separator isn't checked and missing seconds read as zero. */ +internal fun parseBasicDateTime(s: String): LocalDateTime? = runCatching { + val date = parseBasicDate(s) ?: return null + val time = LocalTime( + s.substring(9, 11).toInt(), + s.substring(11, 13).toInt(), + if (s.length >= 15) s.substring(13, 15).toInt() else 0, + ) + LocalDateTime(date, time) +}.getOrNull() diff --git a/app/src/main/java/de/jeanlucmakiola/calendula/domain/ics/IcsParser.kt b/app/src/main/java/de/jeanlucmakiola/calendula/domain/ics/IcsParser.kt index 0c958216..75d40206 100644 --- a/app/src/main/java/de/jeanlucmakiola/calendula/domain/ics/IcsParser.kt +++ b/app/src/main/java/de/jeanlucmakiola/calendula/domain/ics/IcsParser.kt @@ -2,19 +2,17 @@ package de.jeanlucmakiola.calendula.domain.ics import de.jeanlucmakiola.calendula.domain.Availability import de.jeanlucmakiola.calendula.domain.EventStatus -import kotlinx.datetime.LocalDate +import de.jeanlucmakiola.calendula.domain.zoneOrNull import kotlinx.datetime.LocalDateTime -import kotlinx.datetime.LocalTime import kotlinx.datetime.TimeZone import kotlinx.datetime.atStartOfDayIn -import kotlinx.datetime.number import kotlinx.datetime.toInstant import kotlinx.datetime.toLocalDateTime import kotlin.math.ceil +import kotlin.time.Duration.Companion.days +import kotlin.time.Duration.Companion.milliseconds import kotlin.time.Instant -/** Milliseconds in a calendar day; all-day times are UTC midnights, so this is exact. */ -private const val DAY_MILLIS = 86_400_000L private const val MINUTES_PER_DAY = 1_440 /** @@ -318,13 +316,9 @@ class IcsParser(private val deviceZone: TimeZone = TimeZone.currentSystemDefault dtEnd: IcsDateTime?, duration: String?, ): Instant { - val explicit = dtEnd?.instant ?: duration?.let { - Instant.fromEpochMilliseconds( - start.instant.toEpochMilliseconds() + parseRfc2445DurationMillis(it), - ) - } + val explicit = dtEnd?.instant ?: duration?.let { start.instant + parseRfc2445DurationMillis(it).milliseconds } if (!start.isAllDay) return explicit ?: start.instant - return explicit?.takeIf { it > start.instant } ?: start.instant.plusDays(1) + return explicit?.takeIf { it > start.instant } ?: (start.instant + 1.days) } /** @@ -343,17 +337,17 @@ class IcsParser(private val deviceZone: TimeZone = TimeZone.currentSystemDefault */ private fun normalizeExDates(lines: List, start: IcsDateTime): List { if (lines.isEmpty()) return emptyList() - val startZone = runCatching { TimeZone.of(start.zoneId) }.getOrNull() ?: deviceZone + val startZone = zoneOrNull(start.zoneId) ?: deviceZone val startTime = start.instant.toLocalDateTime(startZone).time return lines .flatMap { line -> line.value.split(',').map { line to it.trim() } } .mapNotNull { (line, token) -> when { token.isEmpty() -> null - start.isAllDay -> parseBasicDate(token.substringBefore('T'))?.let(::dayCode) - token.contains('T') -> parseExDateTime(token, line, startZone)?.let(::utcStamp) + start.isAllDay -> parseBasicDate(token.substringBefore('T'))?.toBasic() + token.contains('T') -> parseExDateTime(token, line, startZone)?.toUtcBasic() else -> parseBasicDate(token) - ?.let { utcStamp(LocalDateTime(it, startTime).toInstant(startZone)) } + ?.let { LocalDateTime(it, startTime).toInstant(startZone).toUtcBasic() } } } .distinct() @@ -373,7 +367,7 @@ class IcsParser(private val deviceZone: TimeZone = TimeZone.currentSystemDefault val ldt = parseBasicDateTime(token.removeSuffix("Z")) ?: return null val zone = when { token.endsWith("Z") -> TimeZone.UTC - else -> line.params["TZID"]?.let { runCatching { TimeZone.of(it) }.getOrNull() } + else -> line.params["TZID"]?.let(::zoneOrNull) ?: startZone } return ldt.toInstant(zone) @@ -409,7 +403,7 @@ class IcsParser(private val deviceZone: TimeZone = TimeZone.currentSystemDefault if (isUtc) return IcsDateTime(ldt.toInstant(TimeZone.UTC), isAllDay = false, zoneId = "UTC") val tzid = line.params["TZID"] - val resolved = tzid?.let { id -> runCatching { TimeZone.of(id) }.getOrNull()?.let { id to it } } + val resolved = tzid?.let { id -> zoneOrNull(id)?.let { id to it } } if (tzid != null && resolved == null) warnings.add(IcsParseWarning.UnknownTimezone) val (zoneId, zone) = resolved ?: (deviceZone.id to deviceZone) return IcsDateTime(ldt.toInstant(zone), isAllDay = false, zoneId = zoneId) @@ -421,16 +415,6 @@ class IcsParser(private val deviceZone: TimeZone = TimeZone.currentSystemDefault fun IcsContentLine.isBegin(component: String) = name == "BEGIN" && value.trim().equals(component, true) - fun Instant.plusDays(days: Int): Instant = - Instant.fromEpochMilliseconds(toEpochMilliseconds() + days * DAY_MILLIS) - - fun dayCode(date: LocalDate): String = - "%04d%02d%02d".format(date.year, date.month.number, date.day) - - fun utcStamp(instant: Instant): String = with(instant.toLocalDateTime(TimeZone.UTC)) { - "%04d%02d%02dT%02d%02d%02dZ".format(year, month.number, day, hour, minute, second) - } - /** * A single-valued `CATEGORIES`, which is what the Fossify family writes * for the source calendar's name. A multi-item list is a tag list and @@ -449,59 +433,26 @@ class IcsParser(private val deviceZone: TimeZone = TimeZone.currentSystemDefault .takeIf { it.isNotEmpty() && !it.equals("null", true) } } - /** Index of the matching `END:` at/after [from], or list end. */ /** * Where an unterminated component's body has to stop: the next top-level * `VEVENT` / `VTODO` in `[from, end)`, or [end] when there is none. A * nested `VALARM` is part of the body and is not a boundary. */ - fun indexOfNextComponent(lines: List, from: Int, end: Int): Int { - var i = from - while (i < end) { + fun indexOfNextComponent(lines: List, from: Int, end: Int): Int = + (from until end).firstOrNull { i -> val line = parseContentLine(lines[i]) - if (line != null && (line.isBegin("VEVENT") || line.isBegin("VTODO"))) { - return i - } - i++ - } - return end - } + line != null && (line.isBegin("VEVENT") || line.isBegin("VTODO")) + } ?: end - fun indexOfEnd(lines: List, from: Int, component: String): Int { - var i = from - while (i < lines.size) { + /** Index of the matching `END:` at/after [from], or list end. */ + fun indexOfEnd(lines: List, from: Int, component: String): Int = + (from until lines.size).firstOrNull { i -> val line = parseContentLine(lines[i]) - if (line != null && line.name == "END" && - line.value.trim().equals(component, true) - ) { - return i - } - i++ - } - return lines.size - } + line != null && line.name == "END" && line.value.trim().equals(component, true) + } ?: lines.size - fun mapIcsStatus(value: String): EventStatus = when (value.trim().uppercase()) { - "TENTATIVE" -> EventStatus.Tentative - "CANCELLED" -> EventStatus.Cancelled - else -> EventStatus.Confirmed - } - - fun parseBasicDate(s: String): LocalDate? = runCatching { - LocalDate(s.substring(0, 4).toInt(), s.substring(4, 6).toInt(), s.substring(6, 8).toInt()) - }.getOrNull() - - fun parseBasicDateTime(s: String): LocalDateTime? = runCatching { - val date = LocalDate( - s.substring(0, 4).toInt(), s.substring(4, 6).toInt(), s.substring(6, 8).toInt(), - ) - // Format is YYYYMMDD 'T' HHMMSS; seconds optional. - val time = LocalTime( - s.substring(9, 11).toInt(), - s.substring(11, 13).toInt(), - if (s.length >= 15) s.substring(13, 15).toInt() else 0, - ) - LocalDateTime(date, time) - }.getOrNull() + fun mapIcsStatus(value: String): EventStatus = + EventStatus.entries.firstOrNull { it.name.equals(value.trim(), ignoreCase = true) } + ?: EventStatus.Confirmed } } diff --git a/app/src/main/java/de/jeanlucmakiola/calendula/domain/ics/IcsRecurrence.kt b/app/src/main/java/de/jeanlucmakiola/calendula/domain/ics/IcsRecurrence.kt index 7f67573d..e8ccdaef 100644 --- a/app/src/main/java/de/jeanlucmakiola/calendula/domain/ics/IcsRecurrence.kt +++ b/app/src/main/java/de/jeanlucmakiola/calendula/domain/ics/IcsRecurrence.kt @@ -1,5 +1,7 @@ package de.jeanlucmakiola.calendula.domain.ics +import de.jeanlucmakiola.calendula.domain.rruleParts + private val VALID_FREQ = setOf( "SECONDLY", "MINUTELY", "HOURLY", "DAILY", "WEEKLY", "MONTHLY", "YEARLY", ) @@ -64,7 +66,9 @@ data class SanitizedRrule(val rule: String?, val repaired: Boolean) * rule at all — gives up entirely. */ fun sanitizeRrule(raw: String?): SanitizedRrule { - val rule = raw?.trim()?.removePrefix("RRULE:")?.trim().orEmpty() + val rule = raw?.trim() + ?.let { if (it.startsWith("RRULE:", ignoreCase = true)) it.drop("RRULE:".length) else it } + ?.trim().orEmpty() if (rule.isEmpty()) return SanitizedRrule(rule = null, repaired = false) var freqSeen = false @@ -79,13 +83,12 @@ fun sanitizeRrule(raw: String?): SanitizedRrule { return kept.takeIf { it.isNotEmpty() }?.joinToString(",") } - for (part in rule.split(';')) { - // A stray separator ("FREQ=DAILY;") normalises away; nothing was lost. - // A part that carries text but no '=' ("FREQ=WEEKLY;BYDAY") is a part - // being dropped, so it falls through and marks the rule repaired. - if (part.isBlank()) continue - val key = part.substringBefore('=', "").trim().uppercase() - val value = if ('=' in part) part.substringAfter('=').trim() else "" + // A stray separator ("FREQ=DAILY;") normalises away; nothing was lost. + // A part that carries text but no '=' ("FREQ=WEEKLY;BYDAY") is a part + // being dropped, so it falls through and marks the rule repaired. + for (part in rruleParts(rule)) { + val key = part.key?.trim()?.uppercase().orEmpty() + val value = part.value.trim() val kept = when { key.isEmpty() || value.isEmpty() -> null key == "FREQ" -> diff --git a/app/src/main/java/de/jeanlucmakiola/calendula/domain/ics/IcsWriter.kt b/app/src/main/java/de/jeanlucmakiola/calendula/domain/ics/IcsWriter.kt index c26dd9ce..2d5ee6ba 100644 --- a/app/src/main/java/de/jeanlucmakiola/calendula/domain/ics/IcsWriter.kt +++ b/app/src/main/java/de/jeanlucmakiola/calendula/domain/ics/IcsWriter.kt @@ -2,9 +2,8 @@ package de.jeanlucmakiola.calendula.domain.ics import de.jeanlucmakiola.calendula.domain.Availability import de.jeanlucmakiola.calendula.domain.EventStatus -import kotlinx.datetime.LocalDateTime +import de.jeanlucmakiola.calendula.domain.zoneOrNull import kotlinx.datetime.TimeZone -import kotlinx.datetime.number import kotlinx.datetime.toLocalDateTime import kotlin.time.Instant @@ -41,7 +40,7 @@ class IcsWriter(private val prodId: String = ICS_PROD_ID) { private fun MutableList.appendEvent(event: IcsEvent, dtStamp: Instant) { add("BEGIN:VEVENT") add("UID:${event.uid}") - add("DTSTAMP:${utcStamp(dtStamp)}") + add("DTSTAMP:${dtStamp.toUtcBasic()}") add("SUMMARY:${escapeText(event.summary)}") appendTimes(event) event.recurrenceRule?.takeIf { it.isNotBlank() } @@ -63,24 +62,24 @@ class IcsWriter(private val prodId: String = ICS_PROD_ID) { private fun MutableList.appendTimes(event: IcsEvent) = when { event.isAllDay -> { - add("DTSTART;VALUE=DATE:${utcDate(event.start)}") - add("DTEND;VALUE=DATE:${utcDate(event.end)}") + add("DTSTART;VALUE=DATE:${event.start.toLocalDateTime(TimeZone.UTC).date.toBasic()}") + add("DTEND;VALUE=DATE:${event.end.toLocalDateTime(TimeZone.UTC).date.toBasic()}") } // Recurring: anchor to wall-clock in the event's own zone. event.recurrenceRule?.isNotBlank() == true -> { - val zone = runCatching { TimeZone.of(event.zoneId) }.getOrNull() + val zone = zoneOrNull(event.zoneId) if (zone != null) { - add("DTSTART;TZID=${event.zoneId}:${localStamp(event.start, zone)}") - add("DTEND;TZID=${event.zoneId}:${localStamp(event.end, zone)}") + add("DTSTART;TZID=${event.zoneId}:${event.start.toLocalDateTime(zone).toBasic()}") + add("DTEND;TZID=${event.zoneId}:${event.end.toLocalDateTime(zone).toBasic()}") } else { // Unknown zone id → fall back to plain UTC instants. - add("DTSTART:${utcStamp(event.start)}") - add("DTEND:${utcStamp(event.end)}") + add("DTSTART:${event.start.toUtcBasic()}") + add("DTEND:${event.end.toUtcBasic()}") } } else -> { - add("DTSTART:${utcStamp(event.start)}") - add("DTEND:${utcStamp(event.end)}") + add("DTSTART:${event.start.toUtcBasic()}") + add("DTEND:${event.end.toUtcBasic()}") } } @@ -120,20 +119,5 @@ class IcsWriter(private val prodId: String = ICS_PROD_ID) { // A lead time of 0 fires at start (PT0M); anything positive is "before". fun triggerValue(minutes: Int): String = if (minutes <= 0) "PT0M" else "-PT${minutes}M" - - fun utcStamp(instant: Instant): String = - basic(instant.toLocalDateTime(TimeZone.UTC)) + "Z" - - fun localStamp(instant: Instant, zone: TimeZone): String = - basic(instant.toLocalDateTime(zone)) - - fun utcDate(instant: Instant): String { - val dt = instant.toLocalDateTime(TimeZone.UTC) - return "%04d%02d%02d".format(dt.year, dt.month.number, dt.day) - } - - fun basic(dt: LocalDateTime): String = "%04d%02d%02dT%02d%02d%02d".format( - dt.year, dt.month.number, dt.day, dt.hour, dt.minute, dt.second, - ) } } diff --git a/app/src/main/java/de/jeanlucmakiola/calendula/domain/ics/ParsedIcsForm.kt b/app/src/main/java/de/jeanlucmakiola/calendula/domain/ics/ParsedIcsForm.kt index d2609a9f..1467e048 100644 --- a/app/src/main/java/de/jeanlucmakiola/calendula/domain/ics/ParsedIcsForm.kt +++ b/app/src/main/java/de/jeanlucmakiola/calendula/domain/ics/ParsedIcsForm.kt @@ -1,9 +1,9 @@ package de.jeanlucmakiola.calendula.domain.ics import de.jeanlucmakiola.calendula.domain.EventForm -import kotlinx.datetime.LocalDate -import kotlinx.datetime.LocalDateTime -import kotlinx.datetime.LocalTime +import de.jeanlucmakiola.calendula.domain.allDayFormTimes +import de.jeanlucmakiola.calendula.domain.normalizedRrule +import de.jeanlucmakiola.calendula.domain.toFormTime import kotlinx.datetime.TimeZone import kotlinx.datetime.toLocalDateTime @@ -21,12 +21,9 @@ import kotlinx.datetime.toLocalDateTime */ fun ParsedIcsEvent.toEventForm(zone: TimeZone): EventForm { val (start, end) = if (isAllDay) { - val startDate = this.start.toLocalDateTime(TimeZone.UTC).date - val endExclusive = this.end.toLocalDateTime(TimeZone.UTC).date - val endDate = maxOf(startDate, LocalDate.fromEpochDays(endExclusive.toEpochDays() - 1)) - LocalDateTime(startDate, LocalTime(9, 0)) to LocalDateTime(endDate, LocalTime(10, 0)) + allDayFormTimes(this.start.toLocalDateTime(TimeZone.UTC).date, this.end.toLocalDateTime(TimeZone.UTC).date) } else { - this.start.toLocalDateTime(zone) to this.end.toLocalDateTime(zone) + this.start.toFormTime(zone) to this.end.toFormTime(zone) } return EventForm( calendarId = null, @@ -38,6 +35,6 @@ fun ParsedIcsEvent.toEventForm(zone: TimeZone): EventForm { description = description.orEmpty(), reminders = semanticReminderMinutes(), availability = availability, - rrule = recurrenceRule?.removePrefix("RRULE:")?.takeIf { it.isNotBlank() }, + rrule = recurrenceRule.normalizedRrule(), ) } diff --git a/app/src/main/java/de/jeanlucmakiola/calendula/ui/CalendarHost.kt b/app/src/main/java/de/jeanlucmakiola/calendula/ui/CalendarHost.kt index 727a933f..07349082 100644 --- a/app/src/main/java/de/jeanlucmakiola/calendula/ui/CalendarHost.kt +++ b/app/src/main/java/de/jeanlucmakiola/calendula/ui/CalendarHost.kt @@ -4,8 +4,10 @@ import androidx.activity.compose.BackHandler import androidx.activity.compose.PredictiveBackHandler import androidx.compose.animation.AnimatedContent import androidx.compose.animation.AnimatedVisibility +import androidx.compose.animation.AnimatedVisibilityScope import androidx.compose.animation.ExperimentalSharedTransitionApi import androidx.compose.animation.SharedTransitionLayout +import androidx.compose.animation.core.MutableTransitionState import androidx.compose.animation.core.SeekableTransitionState import androidx.compose.animation.core.rememberTransition import androidx.compose.animation.fadeIn @@ -19,6 +21,7 @@ import androidx.compose.material3.Scaffold import androidx.compose.material3.TopAppBarDefaults import androidx.compose.material3.rememberDrawerState import androidx.compose.runtime.getValue +import androidx.compose.runtime.key import androidx.compose.runtime.setValue import androidx.compose.runtime.Composable import androidx.compose.runtime.CompositionLocalProvider @@ -27,9 +30,12 @@ import androidx.compose.runtime.mutableStateOf import androidx.compose.runtime.mutableIntStateOf import androidx.compose.runtime.remember import androidx.compose.runtime.rememberCoroutineScope +import androidx.compose.runtime.saveable.Saver import androidx.compose.runtime.saveable.listSaver import androidx.compose.runtime.saveable.rememberSaveable +import androidx.compose.ui.platform.LocalContext import androidx.compose.ui.Modifier +import de.jeanlucmakiola.calendula.ui.common.rememberHeld import de.jeanlucmakiola.calendula.ui.common.screen import de.jeanlucmakiola.calendula.ui.common.ViewScreen import androidx.compose.ui.layout.onGloballyPositioned @@ -37,6 +43,7 @@ import androidx.compose.ui.layout.positionInWindow import androidx.compose.ui.platform.LocalDensity import androidx.hilt.navigation.compose.hiltViewModel import androidx.lifecycle.compose.collectAsStateWithLifecycle +import de.jeanlucmakiola.calendula.data.time.currentDate import de.jeanlucmakiola.calendula.domain.EventForm import de.jeanlucmakiola.calendula.domain.EventInstance import de.jeanlucmakiola.calendula.ui.agenda.AgendaScreen @@ -55,7 +62,13 @@ import de.jeanlucmakiola.floret.identity.fadeThrough import de.jeanlucmakiola.floret.identity.predictiveBackExit import de.jeanlucmakiola.floret.identity.rememberReduceMotion import de.jeanlucmakiola.calendula.ui.common.CalendarView +import de.jeanlucmakiola.calendula.ui.common.EventActionsViewModel import de.jeanlucmakiola.calendula.ui.common.EventMoveHost +import de.jeanlucmakiola.calendula.ui.common.EventSelectionHost +import de.jeanlucmakiola.calendula.ui.common.eventActionFailureMessage +import de.jeanlucmakiola.calendula.ui.common.rememberFabSelection +import de.jeanlucmakiola.calendula.ui.common.canWriteCalendar +import de.jeanlucmakiola.calendula.ui.common.rememberWriteAction import de.jeanlucmakiola.calendula.ui.common.EventMoveScope import de.jeanlucmakiola.calendula.ui.common.LocalEventMove import de.jeanlucmakiola.calendula.ui.common.LocalManageCalendars @@ -76,6 +89,7 @@ import de.jeanlucmakiola.calendula.ui.common.rememberCalendarSlideSpec import de.jeanlucmakiola.calendula.ui.common.selectView import de.jeanlucmakiola.calendula.ui.common.viewBaseStack import de.jeanlucmakiola.calendula.ui.detail.EventDetailScreen +import de.jeanlucmakiola.calendula.ui.edit.EventEditViewModel import de.jeanlucmakiola.calendula.ui.edit.EventEditScreen import de.jeanlucmakiola.calendula.ui.edit.ImportSource import de.jeanlucmakiola.calendula.ui.imports.ImportScreen @@ -90,7 +104,7 @@ import kotlinx.datetime.LocalDate import kotlinx.datetime.TimeZone import kotlinx.datetime.toLocalDateTime import kotlin.coroutines.cancellation.CancellationException -import kotlin.time.Clock +import kotlin.time.Instant /** * Holds the top-level view back stack (spec M1) and swaps between the calendar @@ -106,28 +120,18 @@ import kotlin.time.Clock * view remains. So back from a widget-opened screen returns to that widget's * view, then home; and back through pill switches walks the views in reverse. * - * [requestedDetailKey] is an externally requested occurrence (a tapped - * reminder notification routed through MainActivity): it opens the detail - * overlay exactly like an event tap and is cleared via [onDetailKeyConsumed] - * so a later recomposition can't re-open it. (A widget event tap instead arrives - * as [WidgetNavRequest.OpenEvent], which also roots the back stack in the - * widget's view.) + * [requests] carries what notifications, widgets and other apps asked to + * open. A tapped reminder's occurrence opens the detail overlay exactly like an + * event tap; each request is cleared once acted on so a later recomposition + * can't re-open it. (A widget event tap instead arrives as + * [WidgetNavRequest.OpenEvent], which also roots the back stack in the widget's + * view.) */ @OptIn(ExperimentalSharedTransitionApi::class) @Composable fun CalendarHost( + requests: ExternalRequests, modifier: Modifier = Modifier, - requestedDetailKey: LongArray? = null, - onDetailKeyConsumed: () -> Unit = {}, - widgetNavRequest: WidgetNavRequest? = null, - onWidgetNavConsumed: () -> Unit = {}, - requestedImportUri: android.net.Uri? = null, - onImportConsumed: () -> Unit = {}, - requestedInsertForm: EventForm? = null, - requestedInsertSource: ImportSource = ImportSource.Insert, - onInsertConsumed: () -> Unit = {}, - requestedEditKey: LongArray? = null, - onEditKeyConsumed: () -> Unit = {}, viewModel: CalendarHostViewModel = hiltViewModel(), ) { // Wait for the persisted default view before seeding the stack, so the app @@ -146,10 +150,13 @@ fun CalendarHost( mutableStateOf(listOf(defaultView)) } var navigationVersion by remember { mutableIntStateOf(0) } + // True after backing out of a day opened from the view now shown, so the + // agenda returns to where it was instead of today (#367). + var returnedFromDay by remember { mutableStateOf(false) } val view = viewStack.last() // The date every view opens on and carries along (#184); tapping a day // anywhere focuses it and opens the day view there. - val focus = rememberSaveable(saver = ViewFocusSaver) { ViewFocus(localToday()) } + val focus = rememberSaveable(saver = ViewFocusSaver) { ViewFocus(currentDate()) } // A focus still on yesterday follows the date over, so the next view opened // doesn't land on the old day (#373); one moved elsewhere stays put. val today = viewModel.today.collectAsStateWithLifecycle().value @@ -163,6 +170,7 @@ fun CalendarHost( val switchScope = rememberCoroutineScope() val switchTo: ((List) -> List) -> Unit = { move -> navigationVersion++ + returnedFromDay = false viewStack = move(viewStack) } val onSelectView: (CalendarView) -> Unit = { target -> switchTo { it.selectView(target) } } @@ -179,27 +187,17 @@ fun CalendarHost( // it overlays whichever calendar view is active. We forward the tapped // occurrence's own times (eventId + begin + end, packed as a saveable // long[]) so recurring events show the correct date, not the series start. - // [heldKey] keeps the last shown key alive through the slide-out (when - // [detailKey] is cleared); it is set in the tap callback — never a [0,0,0] - // placeholder — so the destination never loads a bogus id=0 on first frame. + // Like every overlay below, it draws its last key through the slide-out + // ([rememberHeld]) rather than a placeholder. var detailKey by rememberSaveable { mutableStateOf(null) } - var heldKey by remember { mutableStateOf(null) } - val onEventClick: (EventInstance) -> Unit = { event -> - val key = longArrayOf( - event.eventId, - event.start.toEpochMilliseconds(), - event.end.toEpochMilliseconds(), - ) - heldKey = key - detailKey = key - } + val onOpenDetail: (EventInstance) -> Unit = { event -> detailKey = event.occurrenceKey() } // A tapped reminder notification asks for a specific occurrence. + val requestedDetailKey = requests.detailKey LaunchedEffect(requestedDetailKey) { if (requestedDetailKey != null) { - heldKey = requestedDetailKey detailKey = requestedDetailKey - onDetailKeyConsumed() + requests.detailKey = null } } @@ -223,19 +221,17 @@ fun CalendarHost( // calendar list rather than by preferences. Reached from both. var showBackup by rememberSaveable { mutableStateOf(false) } - // Event form (v1.2 create) — same held-key pattern as the detail screen: - // [heldCreateIso] keeps the prefill date alive through the slide-out. - // [createStartMinutes] is the tapped slot's start (minutes from midnight) - // when the form is opened from a day/week grid tap; null from the FAB. - var createDateIso by rememberSaveable { mutableStateOf(null) } - var heldCreateIso by remember { mutableStateOf(null) } - var createStartMinutes by rememberSaveable { mutableStateOf(null) } - var heldCreateMinutes by remember { mutableStateOf(null) } - val onCreateEvent: (LocalDate, Int?) -> Unit = { date, startMinutes -> - heldCreateIso = date.toString() - createDateIso = date.toString() - heldCreateMinutes = startMinutes - createStartMinutes = startMinutes + // Event form (v1.2 create), opened on a date, a tapped slot or a drafted block. + var createRequest by rememberSaveable(stateSaver = createRequestSaver) { + mutableStateOf(null) + } + fun openCreate(dateIso: String, startMinutes: Int? = null, draftMillis: LongArray? = null) { + createRequest = CreateRequest(dateIso, startMinutes, draftMillis) + } + val onCreateEvent: (LocalDate, Int?) -> Unit = { date, startMinutes -> openCreate(date.toString(), startMinutes) } + val onCreateDraft: (Instant, Instant) -> Unit = { start, end -> + val date = start.toLocalDateTime(TimeZone.currentSystemDefault()).date + openCreate(date.toString(), draftMillis = longArrayOf(start.toEpochMilliseconds(), end.toEpochMilliseconds())) } // Edit form (v1.3) — reuses the detail screen's occurrence key; for @@ -245,21 +241,57 @@ fun CalendarHost( // falling back to the auto-refreshing calendar is the only honest // destination. var editKey by rememberSaveable { mutableStateOf(null) } - var heldEditKey by remember { mutableStateOf(null) } // An opened/received .ics file. [ImportScreen] parses it and either opens // the prefilled create form (one event → [importForm]) or its own bulk // picker (many). A plain conditional overlay (no slide) — it's transient. - var importUri by remember { mutableStateOf(null) } - var importForm by remember { mutableStateOf(null) } + var importUri by rememberSaveable { mutableStateOf(null) } + val importViewModel: EventEditViewModel = hiltViewModel(key = "import") + // Saved as "open"; a recreation takes the form back from the ViewModel, which + // still holds the user's edits. + var importForm by rememberSaveable( + stateSaver = Saver( + save = { it != null }, + restore = { open -> if (open) importViewModel.currentForm() else null }, + ), + ) { mutableStateOf(null) } // Which channel filled [importForm]: an .ics file (prompt to apply the default // reminder) or an ACTION_INSERT intent (apply it automatically) — #49. - var importFormSource by remember { mutableStateOf(ImportSource.File) } + var importFormSource by rememberSaveable { mutableStateOf(ImportSource.File) } + // Bumped per open, so even an equal prefill starts a fresh form. + var importFormId by rememberSaveable { mutableIntStateOf(0) } + // Whether [importForm] came from an external create request (#30, #306); + // closing it then hands control back to whoever asked. + var importFromRequest by rememberSaveable { mutableStateOf(false) } + // A second external request that arrived while a prefilled form was open: + // it waits behind that form's unsaved-changes prompt, then opens. + var pendingInsert by remember { mutableStateOf?>(null) } + val createViewModel: EventEditViewModel = hiltViewModel(key = "create") + val editViewModel: EventEditViewModel = hiltViewModel(key = "edit") + fun openImportForm(form: EventForm, source: ImportSource, fromRequest: Boolean = false) { + importFormSource = source + importForm = form + importFormId++ + importFromRequest = fromRequest + } + fun closeImportForm() { + val next = pendingInsert + pendingInsert = null + if (next != null) { + openImportForm(next.first, next.second, fromRequest = true) + } else { + importForm = null + if (importFromRequest) { + importFromRequest = false + requests.onExternalFormClosed() + } + } + } // A restore (in-app "Restore from .ics" button) always runs the full import // flow — picker + summary — even for a single-event file, because the intent // is "restore a backup", not "add this one event". An externally opened .ics // keeps routing a single event straight into the prefilled create form. - var importForceMany by remember { mutableStateOf(false) } + var importForceMany by rememberSaveable { mutableStateOf(false) } // Where a restore came from, so closing the import puts it back: the import // overlays are declared under Backup & restore and the manager, so starting // one has to close them — without this, finishing a restore drops you on the @@ -270,81 +302,113 @@ fun CalendarHost( // what tells it a *re-import of the same file* is new work and not the run // it already finished; a rotation keeps the number and keeps the result. var importSession by rememberSaveable { mutableStateOf(0) } + // A recreation re-reads the launch intent; when the import it carries came + // back with the saved state, that replay is the same work, not a new one. + fun isReplayOfRestoredImport(): Boolean { + val replay = requests.replayed && (importUri != null || importForm != null) + requests.replayed = false + return replay + } + val requestedImportUri = requests.importUri LaunchedEffect(requestedImportUri) { if (requestedImportUri != null) { + if (isReplayOfRestoredImport()) { + requests.importUri = null + return@LaunchedEffect + } importUri = requestedImportUri importForceMany = false importSession++ - onImportConsumed() + requests.importUri = null } } // An external ACTION_INSERT launch (another app/widget creating an event, // issue #30) arrives already prefilled — open it in the same create form the // single-event .ics path uses. [importForm] is the topmost overlay, so it // reveals on top of whatever was open without extra dismissal. - LaunchedEffect(requestedInsertForm) { - if (requestedInsertForm != null) { - importFormSource = requestedInsertSource - importForm = requestedInsertForm - onInsertConsumed() + val requestedInsert = requests.insert + LaunchedEffect(requestedInsert) { + if (requestedInsert != null) { + if (isReplayOfRestoredImport()) { + requests.insert = null + return@LaunchedEffect + } + if (importForm == null) { + openImportForm(requestedInsert.form, requestedInsert.source, fromRequest = true) + } else { + pendingInsert = requestedInsert.form to requestedInsert.source + } + requests.insert = null } } // Close every overlay that can sit over the calendar, so an externally // requested destination (a widget/shortcut/QS-tile launch) is revealed on - // top instead of underneath whatever the user had open. - fun dismissCoveringOverlays() { + // top instead of underneath whatever the user had open. The create form, + // declared under the edit form, can stay for an edit to open over it. + fun dismissCoveringOverlays(keepCreate: Boolean = false) { showSettings = false + showSearch = false showCalendars = false showBackup = false detailKey = null editKey = null + if (!keepCreate) createRequest = null importUri = null importForm = null + if (importFromRequest) { + importFromRequest = false + requests.onExternalFormClosed() + } + pendingInsert = null + importViewModel.reset() } // An external "edit this event" (ACTION_EDIT, e.g. an assistant/task app or // widget) opens the occurrence straight in the edit form. Drop any covering // overlay first — the edit overlay sits below Settings/import in the Box, so - // without this it would open hidden underneath them. Same held-key pattern as - // a detail-screen "Edit" tap; a saved edit just returns to the calendar. + // without this it would open hidden underneath them. A saved edit just + // returns to the calendar. + val requestedEditKey = requests.editKey LaunchedEffect(requestedEditKey) { if (requestedEditKey != null) { - dismissCoveringOverlays() - heldEditKey = requestedEditKey + // An open edit form stays on screen, so it starts over here rather + // than once it has slid away. + if (editKey != null) editViewModel.reset() + dismissCoveringOverlays(keepCreate = true) editKey = requestedEditKey - onEditKeyConsumed() + requests.editKey = null } } // A home-screen widget launch asks to open a date (→ day view), open an // event's detail, or start a create. Handled once and cleared, mirroring - // [requestedDetailKey]. Date/event opens root the stack in the widget's own + // the detail request. Date/event opens root the stack in the widget's own // view so backing out returns there (then home), not to the default. + val widgetNavRequest = requests.nav LaunchedEffect(widgetNavRequest) { - if (widgetNavRequest != null) navigationVersion++ + if (widgetNavRequest != null) { + navigationVersion++ + returnedFromDay = false + } when (val req = widgetNavRequest) { is WidgetNavRequest.OpenDate -> { // Drill the day view in over the widget's view: drop any overlay // that would cover it, so the open doesn't land under Settings/form. dismissCoveringOverlays() - createDateIso = null focus.navigateTo(LocalDate.parse(req.dateIso)) // No widget source (an external date tap) roots over the default // home view, so backing out of the day returns home then exits. viewStack = viewBaseStack(defaultView, req.source ?: defaultView).drillToDay() - onWidgetNavConsumed() + requests.nav = null } is WidgetNavRequest.OpenEvent -> { // Root the stack in the widget's view, then open the occurrence // detail over it (same key shape as a tapped event / reminder). dismissCoveringOverlays() - createDateIso = null viewStack = viewBaseStack(defaultView, req.source) - val key = longArrayOf(req.eventId, req.beginMillis, req.endMillis) - heldKey = key - detailKey = key - onWidgetNavConsumed() + detailKey = longArrayOf(req.eventId, req.beginMillis, req.endMillis) + requests.nav = null } is WidgetNavRequest.OpenView -> { // A widget header tap: land on a top-level view with no date @@ -352,24 +416,19 @@ fun CalendarHost( // the stack on the target (null → the default home) over the // default home — so backing out returns to the default, then exits. dismissCoveringOverlays() - createDateIso = null - focus.navigateTo(localToday()) + focus.navigateTo(currentDate()) viewStack = viewBaseStack(defaultView, req.view ?: defaultView) - onWidgetNavConsumed() + requests.nav = null } is WidgetNavRequest.Create -> { // External "new event" entries (QS tile / launcher shortcut / // widget) must land on top of whatever is open — the form overlay // sits below Settings/calendars in the Box, so without this it // would open hidden underneath them. + if (createRequest != null) createViewModel.reset() dismissCoveringOverlays() - val iso = req.dateIso ?: Clock.System.now() - .toLocalDateTime(TimeZone.currentSystemDefault()).date.toString() - heldCreateIso = iso - createDateIso = iso - heldCreateMinutes = null - createStartMinutes = null - onWidgetNavConsumed() + openCreate(req.dateIso ?: currentDate().toString()) + requests.nav = null } null -> {} } @@ -379,14 +438,44 @@ fun CalendarHost( // survives view switches; the calendar surfaces read it out of LocalEventMove. val reschedule: RescheduleViewModel = hiltViewModel() val movableCalendarIds by reschedule.movableCalendarIds.collectAsStateWithLifecycle() - val onEditEvent: (EventInstance) -> Unit = { event -> - val key = longArrayOf( - event.eventId, - event.start.toEpochMilliseconds(), - event.end.toEpochMilliseconds(), - ) - heldEditKey = key - editKey = key + val eventActions: EventActionsViewModel = hiltViewModel() + val moveOutcome by reschedule.outcome.collectAsStateWithLifecycle() + val selectionFailure by eventActions.failure.collectAsStateWithLifecycle() + val onEditEvent: (EventInstance) -> Unit = { event -> editKey = event.occurrenceKey() } + // A tap opens the edit form instead of the detail screen when the user chose + // so (#178) — only for events whose calendar takes writes. Both are read at + // tap time, so a tap before they've loaded still routes right. + val tapScope = rememberCoroutineScope() + val tapContext = LocalContext.current + // A refused write upgrade is asked once; later taps just open the details. + var tapWriteRefused by rememberSaveable { mutableStateOf(false) } + // The tap waiting on the WRITE_CALENDAR prompt, saved so a rotation keeps it. + var tapAwaitingWrite by rememberSaveable { mutableStateOf(null) } + val editAwaitingTap = rememberWriteAction( + onDenied = { + tapAwaitingWrite?.let { key -> + tapWriteRefused = true + detailKey = key + } + tapAwaitingWrite = null + }, + ) { + tapAwaitingWrite?.let { editKey = it } + tapAwaitingWrite = null + } + val onEventClick: (EventInstance) -> Unit = { event -> + tapScope.launch { + val toEditor = viewModel.tapOpensEditor() && eventActions.canModify(event.calendarId) + when { + !toEditor -> onOpenDetail(event) + tapContext.canWriteCalendar() -> onEditEvent(event) + tapWriteRefused -> onOpenDetail(event) + else -> { + tapAwaitingWrite = event.occurrenceKey() + editAwaitingTap() + } + } + } } // Off by preference (#173) switches off the gesture, not the scope: blocks // register no drag, while the edit form and its TalkBack action stay put. @@ -403,15 +492,10 @@ fun CalendarHost( ) } - val slideSpec = rememberCalendarSlideSpec() - // Overlays leave from the predictive-back preview (#184): shrinking on from - // where the gesture let go instead of snapping back and sliding off. - val overlayExit = predictiveBackExit() - // Base-level back: pop the view stack while no overlay covers it (each overlay // owns its own BackHandler and takes precedence). Disabled at the home view, // so back there falls through to the system and exits the app. - val anyOverlayVisible = showSearch || detailKey != null || createDateIso != null || + val anyOverlayVisible = showSearch || detailKey != null || createRequest != null || editKey != null || showSettings || showCalendars || showBackup || importUri != null || importForm != null // The view switch runs on a seekable transition, so a back gesture can scrub @@ -424,11 +508,14 @@ fun CalendarHost( if (reduceMotion) { BackHandler(enabled = viewBackEnabled) { navigationVersion++ + returnedFromDay = viewStack.last() == CalendarView.Day viewStack = viewStack.dropLast(1) } } else { PredictiveBackHandler(enabled = viewBackEnabled) { events -> val previous = viewStack[viewStack.size - 2] + // Set before the seek, which already composes the previous view. + returnedFromDay = viewStack.last() == CalendarView.Day try { events.collect { viewTransition.seekTo(it.progress, targetState = previous) } navigationVersion++ @@ -517,7 +604,24 @@ fun CalendarHost( showTodayButton = todayInToolbar, ) }, - floatingActionButton = { CalendarFab(chromeHost, todayInToolbar) }, + floatingActionButton = { + // While an event is selected the FAB is its action bar's toggle (#141). + val fabSelection = rememberFabSelection( + host = chromeHost, + viewModel = eventActions, + onEdit = onEditEvent, + onDuplicate = { form -> + // A fresh event, like a duplicate from the detail screen (#52). + openImportForm(form, ImportSource.Insert) + }, + chipShown = moveOutcome != null || selectionFailure != null, + onDismissChip = { + reschedule.consumeOutcome() + eventActions.consumeFailure() + }, + ) + CalendarFab(chromeHost, todayInToolbar, fabSelection) + }, ) { innerPadding -> SharedTransitionLayout( Modifier @@ -548,6 +652,7 @@ fun CalendarHost( onOpenDay = onOpenDay, onEventClick = onEventClick, onCreateEvent = onCreateEvent, + onCreateDraft = onCreateDraft, ) ViewScreen.Month -> MonthScreen( onOpenDay = onOpenDay, @@ -560,6 +665,7 @@ fun CalendarHost( onEventClick = onEventClick, onCreateEvent = onCreateEvent, quickSwitchViews = quickSwitchViews, + restorePosition = returnedFromDay, ) } } @@ -571,15 +677,19 @@ fun CalendarHost( // Scope prompt + confirmation/undo snackbar for a dropped event, declared // right after the calendar views so later overlays cover it. - EventMoveHost(reschedule, modifier = Modifier.fillMaxSize()) + EventMoveHost( + reschedule, + modifier = Modifier.fillMaxSize(), + actionFailure = eventActionFailureMessage(selectionFailure), + onActionFailureShown = eventActions::consumeFailure, + ) + + // The delete prompt and failure chip of a selected event's actions (#141). + EventSelectionHost(host = chromeHost, viewModel = eventActions) // Search overlay — below detail/edit in the Box so a tapped result's // detail screen draws on top, and closing it returns to the results. - AnimatedVisibility( - visible = showSearch, - enter = slideInHorizontally(slideSpec) { it } + fadeIn(), - exit = overlayExit, - ) { + SlideOverlay(visible = showSearch) { SearchScreen( onBack = { showSearch = false }, onEventClick = onEventClick, @@ -587,29 +697,20 @@ fun CalendarHost( ) } - // Prefer the live key; fall back to the held one only while sliding out. - val activeKey = detailKey ?: heldKey - AnimatedVisibility( - visible = detailKey != null, - enter = slideInHorizontally(slideSpec) { it } + fadeIn(), - exit = overlayExit, - ) { - activeKey?.let { key -> + val shownDetailKey = rememberHeld(detailKey) + SlideOverlay(visible = detailKey != null) { + shownDetailKey?.let { key -> EventDetailScreen( eventId = key[0], beginMillis = key[1], endMillis = key[2], onBack = { detailKey = null }, - onEdit = { - heldEditKey = key - editKey = key - }, + onEdit = { editKey = key }, onDuplicate = { form -> // Reuse the prefilled-create overlay: a duplicate is a // fresh event, so it applies the default reminder like an // in-app new event (#52). - importFormSource = ImportSource.Insert - importForm = form + openImportForm(form, ImportSource.Insert) detailKey = null }, visible = detailKey != null, @@ -618,30 +719,28 @@ fun CalendarHost( } // Event form (v1.2) — full-screen destination, slides over the calendar. - AnimatedVisibility( - visible = createDateIso != null, - enter = slideInHorizontally(slideSpec) { it } + fadeIn(), - exit = overlayExit, - ) { - (createDateIso ?: heldCreateIso)?.let { iso -> - EventEditScreen( - initialDateIso = iso, - initialStartMinutes = createStartMinutes ?: heldCreateMinutes, - onClose = { createDateIso = null }, - onSaved = { createDateIso = null }, - onManageCalendars = { showCalendars = true }, - visible = createDateIso != null, - ) + val shownCreate = rememberHeld(createRequest) + SlideOverlay(visible = createRequest != null, onHidden = createViewModel::reset) { + shownCreate?.let { create -> + key(create) { + EventEditScreen( + initialDateIso = create.dateIso, + initialStartMinutes = create.startMinutes, + initialDraft = create.draftMillis, + onClose = { createRequest = null }, + onSaved = { createRequest = null }, + onManageCalendars = { showCalendars = true }, + visible = createRequest != null, + viewModel = createViewModel, + ) + } } } // Edit form (v1.3) — slides over the detail screen. - AnimatedVisibility( - visible = editKey != null, - enter = slideInHorizontally(slideSpec) { it } + fadeIn(), - exit = overlayExit, - ) { - (editKey ?: heldEditKey)?.let { key -> + val shownEditKey = rememberHeld(editKey) + SlideOverlay(visible = editKey != null, onHidden = editViewModel::reset) { + shownEditKey?.let { key -> EventEditScreen( initialDateIso = null, editKey = key, @@ -651,17 +750,23 @@ fun CalendarHost( detailKey = null }, onManageCalendars = { showCalendars = true }, + onDuplicate = { form -> + openImportForm(form, ImportSource.Insert) + }, + // Opened straight from a tap (#178) there's no detail screen + // below to show why, so open it. + onLoadFailed = { + editKey = null + if (detailKey == null) detailKey = key + }, visible = editKey != null, + viewModel = editViewModel, ) } } // Settings (M4) — full-screen destination, slides over the calendar. - AnimatedVisibility( - visible = showSettings, - enter = slideInHorizontally(slideSpec) { it } + fadeIn(), - exit = overlayExit, - ) { + SlideOverlay(visible = showSettings) { SettingsScreen( onBack = { showSettings = false }, onManageCalendars = { showCalendars = true }, @@ -697,29 +802,29 @@ fun CalendarHost( importUri = null calendarsAfterImport = false backupAfterImport = false - importFormSource = ImportSource.File - importForm = form + openImportForm(form, ImportSource.File) }, ) } importForm?.let { form -> - EventEditScreen( - initialDateIso = null, - initialForm = form, - initialFormSource = importFormSource, - onClose = { importForm = null }, - onSaved = { importForm = null }, - onManageCalendars = { showCalendars = true }, - ) + key(importFormId) { + EventEditScreen( + initialDateIso = null, + initialForm = form, + initialFormSource = importFormSource, + onClose = ::closeImportForm, + onSaved = ::closeImportForm, + onManageCalendars = { showCalendars = true }, + leaveRequested = pendingInsert != null, + onLeaveDeclined = { pendingInsert = null }, + viewModel = importViewModel, + ) + } } // Declared last so it covers every overlay that can open it: Settings, // both event forms, and the .ics import picker (#76). - AnimatedVisibility( - visible = showCalendars, - enter = slideInHorizontally(slideSpec) { it } + fadeIn(), - exit = overlayExit, - ) { + SlideOverlay(visible = showCalendars) { CalendarsScreen( onBack = { showCalendars = false }, onOpenBackup = { showBackup = true }, @@ -728,11 +833,7 @@ fun CalendarHost( } // Backup & restore — over the manager, since the manager links into it. - AnimatedVisibility( - visible = showBackup, - enter = slideInHorizontally(slideSpec) { it } + fadeIn(), - exit = overlayExit, - ) { + SlideOverlay(visible = showBackup) { // Settings can open this screen without the manager underneath, so // its failure states' "Manage calendars" way out has to open the // manager rather than just pop — popping alone lands on Settings @@ -771,5 +872,48 @@ private val viewStackSaver = listSaver, Int>( restore = { ordinals -> ordinals.map { CalendarView.entries[it] } }, ) -private fun localToday(): LocalDate = - Clock.System.now().toLocalDateTime(TimeZone.currentSystemDefault()).date +/** + * An overlay's slide-in from the end edge, leaving from the predictive-back + * preview (#184): shrinking on from where the gesture let go instead of + * snapping back and sliding off. + */ +@Composable +private fun SlideOverlay( + visible: Boolean, + onHidden: () -> Unit = {}, + content: @Composable AnimatedVisibilityScope.() -> Unit, +) { + val state = remember { MutableTransitionState(visible) } + state.targetState = visible + val hidden = state.isIdle && !state.currentState + LaunchedEffect(hidden) { + if (hidden) onHidden() + } + AnimatedVisibility( + visibleState = state, + enter = slideInHorizontally(rememberCalendarSlideSpec()) { it } + fadeIn(), + exit = predictiveBackExit(), + content = content, + ) +} + +/** The detail and edit overlays' key for one occurrence: eventId, begin, end. */ +private fun EventInstance.occurrenceKey(): LongArray = + longArrayOf(eventId, start.toEpochMilliseconds(), end.toEpochMilliseconds()) + +/** + * A create-form open: its date, plus the tapped slot's start (minutes from + * midnight) from a day/week grid tap, or a drafted block's start and end (#153) + * as epoch millis. Instants rather than minutes into a day, so the form opens at + * the times drawn even across a DST change (#387). + */ +private class CreateRequest( + val dateIso: String, + val startMinutes: Int?, + val draftMillis: LongArray?, +) + +private val createRequestSaver = Saver>( + save = { request -> request?.let { listOf(it.dateIso, it.startMinutes, it.draftMillis) } }, + restore = { CreateRequest(it[0] as String, it[1] as Int?, it[2] as LongArray?) }, +) diff --git a/app/src/main/java/de/jeanlucmakiola/calendula/ui/CalendarHostViewModel.kt b/app/src/main/java/de/jeanlucmakiola/calendula/ui/CalendarHostViewModel.kt index 789e9a71..cba2890c 100644 --- a/app/src/main/java/de/jeanlucmakiola/calendula/ui/CalendarHostViewModel.kt +++ b/app/src/main/java/de/jeanlucmakiola/calendula/ui/CalendarHostViewModel.kt @@ -8,10 +8,10 @@ import de.jeanlucmakiola.calendula.data.time.TodaySource import de.jeanlucmakiola.calendula.data.time.currentDate import de.jeanlucmakiola.calendula.ui.common.CalendarView import de.jeanlucmakiola.calendula.ui.common.IMPLEMENTED_VIEWS -import kotlinx.coroutines.flow.SharingStarted +import de.jeanlucmakiola.floret.android.stateWhileSubscribed import kotlinx.coroutines.flow.StateFlow import kotlinx.coroutines.flow.map -import kotlinx.coroutines.flow.stateIn +import kotlinx.coroutines.flow.first import kotlinx.datetime.LocalDate import javax.inject.Inject @@ -28,40 +28,35 @@ class CalendarHostViewModel @Inject constructor( ) : ViewModel() { /** Today, kept current across midnight so the shared focus can follow it (#373). */ - val today: StateFlow = todaySource.today.stateIn( + val today: StateFlow = todaySource.today.stateWhileSubscribed( scope = viewModelScope, - started = SharingStarted.WhileSubscribed(5_000L), initialValue = currentDate(), ) - val defaultView: StateFlow = prefs.defaultView.stateIn( + val defaultView: StateFlow = prefs.defaultView.stateWhileSubscribed( scope = viewModelScope, - started = SharingStarted.WhileSubscribed(5_000L), initialValue = null, ) /** Views the top-bar quick-switch pill cycles through, in the user's order (#24). */ val quickSwitchViews: StateFlow> = prefs.quickSwitchConfig .map { it.cycle } - .stateIn( + .stateWhileSubscribed( scope = viewModelScope, - started = SharingStarted.WhileSubscribed(5_000L), initialValue = IMPLEMENTED_VIEWS, ) /** Order of the views in the navigation drawer (#24); every view always shown. */ val drawerViewOrder: StateFlow> = prefs.drawerViewOrder - .stateIn( + .stateWhileSubscribed( scope = viewModelScope, - started = SharingStarted.WhileSubscribed(5_000L), initialValue = IMPLEMENTED_VIEWS, ) /** Whether each view's jump-to-today control lives in the top bar, not the FAB (#60). */ val todayButtonInToolbar: StateFlow = prefs.todayButtonInToolbar - .stateIn( + .stateWhileSubscribed( scope = viewModelScope, - started = SharingStarted.WhileSubscribed(5_000L), initialValue = false, ) @@ -73,9 +68,13 @@ class CalendarHostViewModel @Inject constructor( * switched off to be rid of. */ val dragToReschedule: StateFlow = prefs.dragToReschedule - .stateIn( + .stateWhileSubscribed( scope = viewModelScope, - started = SharingStarted.WhileSubscribed(5_000L), initialValue = false, ) + + private val tapOpensEditorPref = prefs.tapOpensEditor + + /** Whether tapping an event opens the edit form rather than the detail screen (#178). */ + suspend fun tapOpensEditor(): Boolean = tapOpensEditorPref.first() } diff --git a/app/src/main/java/de/jeanlucmakiola/calendula/ui/ExternalRequests.kt b/app/src/main/java/de/jeanlucmakiola/calendula/ui/ExternalRequests.kt new file mode 100644 index 00000000..8993e10a --- /dev/null +++ b/app/src/main/java/de/jeanlucmakiola/calendula/ui/ExternalRequests.kt @@ -0,0 +1,45 @@ +package de.jeanlucmakiola.calendula.ui + +import android.net.Uri +import androidx.compose.runtime.Stable +import androidx.compose.runtime.getValue +import androidx.compose.runtime.mutableStateOf +import androidx.compose.runtime.setValue +import de.jeanlucmakiola.calendula.domain.EventForm +import de.jeanlucmakiola.calendula.ui.edit.ImportSource + +/** + * What a notification, widget, shortcut or another app asked the running app to + * open. MainActivity fills it from each intent (singleTop + onNewIntent route a + * new one into the running activity); CalendarHost acts on a request and clears + * it, so a later recomposition can't act on it twice. + * + * [onExternalFormClosed] runs when a form opened for [insert] closes, so the + * activity can hand control back to the app that asked. + */ +@Stable +class ExternalRequests(val onExternalFormClosed: () -> Unit = {}) { + /** A tapped reminder notification's occurrence (eventId, begin, end), for the detail screen. */ + var detailKey by mutableStateOf(null) + + /** A home-screen widget, shortcut or tile navigation (open a date, an event, a view, or create). */ + var nav by mutableStateOf(null) + + /** An .ics file opened or shared into the app (ACTION_VIEW/SEND). */ + var importUri by mutableStateOf(null) + + /** + * A prefilled new-event form from an external ACTION_INSERT launch (#30) or + * shared text (#306), opened in the create form for review. + */ + var insert by mutableStateOf(null) + + /** An external "edit this event" (ACTION_EDIT), in the detail key's shape. */ + var editKey by mutableStateOf(null) + + /** Whether these came from re-reading the launch intent on a recreation. */ + var replayed = false +} + +/** A prefilled create form from an external launch, with the source it came from. */ +data class InsertRequest(val form: EventForm, val source: ImportSource) diff --git a/app/src/main/java/de/jeanlucmakiola/calendula/ui/RootScreen.kt b/app/src/main/java/de/jeanlucmakiola/calendula/ui/RootScreen.kt index 9b24e6ba..033377c2 100644 --- a/app/src/main/java/de/jeanlucmakiola/calendula/ui/RootScreen.kt +++ b/app/src/main/java/de/jeanlucmakiola/calendula/ui/RootScreen.kt @@ -1,7 +1,5 @@ package de.jeanlucmakiola.calendula.ui -import android.Manifest -import android.content.pm.PackageManager import androidx.compose.animation.AnimatedContent import androidx.compose.animation.fadeIn import androidx.compose.animation.fadeOut @@ -20,11 +18,11 @@ import androidx.compose.ui.platform.LocalContext import androidx.hilt.navigation.compose.hiltViewModel import androidx.lifecycle.compose.LocalLifecycleOwner import androidx.lifecycle.compose.collectAsStateWithLifecycle -import androidx.core.content.ContextCompat import androidx.lifecycle.Lifecycle import androidx.lifecycle.LifecycleEventObserver import de.jeanlucmakiola.calendula.data.contacts.SpecialDatesScheduler import de.jeanlucmakiola.calendula.data.contacts.hasContactsPermission +import de.jeanlucmakiola.calendula.ui.common.canReadCalendar import de.jeanlucmakiola.calendula.ui.common.rememberCalendarFadeSpec import de.jeanlucmakiola.calendula.ui.onboarding.OnboardingStep import de.jeanlucmakiola.calendula.ui.onboarding.OnboardingSteps @@ -43,26 +41,12 @@ private sealed interface RootTarget { @Composable fun RootScreen( + requests: ExternalRequests, modifier: Modifier = Modifier, - requestedDetailKey: LongArray? = null, - onDetailKeyConsumed: () -> Unit = {}, - widgetNavRequest: WidgetNavRequest? = null, - onWidgetNavConsumed: () -> Unit = {}, - requestedImportUri: android.net.Uri? = null, - onImportConsumed: () -> Unit = {}, - requestedInsertForm: de.jeanlucmakiola.calendula.domain.EventForm? = null, - requestedInsertSource: de.jeanlucmakiola.calendula.ui.edit.ImportSource = - de.jeanlucmakiola.calendula.ui.edit.ImportSource.Insert, - onInsertConsumed: () -> Unit = {}, - requestedEditKey: LongArray? = null, - onEditKeyConsumed: () -> Unit = {}, ) { val context = LocalContext.current var hasPermission by remember { - mutableStateOf( - ContextCompat.checkSelfPermission(context, Manifest.permission.READ_CALENDAR) - == PackageManager.PERMISSION_GRANTED - ) + mutableStateOf(context.canReadCalendar()) } // A launch scan already covers the app coming up with the permission, so @@ -73,9 +57,7 @@ fun RootScreen( DisposableEffect(lifecycle) { val obs = LifecycleEventObserver { _, event -> if (event == Lifecycle.Event.ON_RESUME) { - hasPermission = ContextCompat.checkSelfPermission( - context, Manifest.permission.READ_CALENDAR - ) == PackageManager.PERMISSION_GRANTED + hasPermission = context.canReadCalendar() // Refresh the contact special-dates mirror on foreground (the // worker is debounced and no-ops when the feature is off). Gated // on the permission so users without the opt-in never enqueue it. @@ -145,18 +127,8 @@ fun RootScreen( when (shown) { RootTarget.Loading -> Unit RootTarget.App -> CalendarHost( + requests = requests, modifier = modifier, - requestedDetailKey = requestedDetailKey, - onDetailKeyConsumed = onDetailKeyConsumed, - widgetNavRequest = widgetNavRequest, - onWidgetNavConsumed = onWidgetNavConsumed, - requestedImportUri = requestedImportUri, - onImportConsumed = onImportConsumed, - requestedInsertForm = requestedInsertForm, - requestedInsertSource = requestedInsertSource, - onInsertConsumed = onInsertConsumed, - requestedEditKey = requestedEditKey, - onEditKeyConsumed = onEditKeyConsumed, ) // Both halves of a transition read their position out of the live // plan; the one the outgoing step was drawn with is already gone. diff --git a/app/src/main/java/de/jeanlucmakiola/calendula/ui/agenda/AgendaRange.kt b/app/src/main/java/de/jeanlucmakiola/calendula/ui/agenda/AgendaRange.kt index a8e5f397..645a93e3 100644 --- a/app/src/main/java/de/jeanlucmakiola/calendula/ui/agenda/AgendaRange.kt +++ b/app/src/main/java/de/jeanlucmakiola/calendula/ui/agenda/AgendaRange.kt @@ -3,8 +3,9 @@ package de.jeanlucmakiola.calendula.ui.agenda import de.jeanlucmakiola.floret.locale.localizedDateFormatter import kotlinx.datetime.DayOfWeek import kotlinx.datetime.LocalDate -import java.time.YearMonth import java.util.Locale +import kotlinx.datetime.toJavaLocalDate +import kotlinx.datetime.yearMonth /** * How far ahead the agenda (screen or widget) shows events, starting at today. @@ -50,7 +51,7 @@ fun AgendaRange.dayCount(anchor: LocalDate, weekStart: DayOfWeek): Int = when (t DAYS_PER_WEEK - sinceWeekStart } AgendaRange.ThisMonth -> { - val daysInMonth = YearMonth.of(anchor.year, anchor.month.ordinal + 1).lengthOfMonth() + val daysInMonth = anchor.yearMonth.numberOfDays daysInMonth - anchor.day + 1 } is AgendaRange.Custom -> days.coerceIn(AgendaRange.MIN_CUSTOM_DAYS, AgendaRange.MAX_CUSTOM_DAYS) @@ -105,8 +106,8 @@ fun agendaRangeWindowSummary( locale: Locale, monthAsSpan: Boolean = false, ): String { - val javaStart = java.time.LocalDate.of(start.year, start.month.ordinal + 1, start.day) - val javaEnd = java.time.LocalDate.of(end.year, end.month.ordinal + 1, end.day) + val javaStart = start.toJavaLocalDate() + val javaEnd = end.toJavaLocalDate() val dayMonth = localizedDateFormatter(locale, "dMMM") val dayMonthYear = localizedDateFormatter(locale, "dMMMy") return when { diff --git a/app/src/main/java/de/jeanlucmakiola/calendula/ui/agenda/AgendaRows.kt b/app/src/main/java/de/jeanlucmakiola/calendula/ui/agenda/AgendaRows.kt index 31ac272e..0859bebd 100644 --- a/app/src/main/java/de/jeanlucmakiola/calendula/ui/agenda/AgendaRows.kt +++ b/app/src/main/java/de/jeanlucmakiola/calendula/ui/agenda/AgendaRows.kt @@ -1,8 +1,9 @@ package de.jeanlucmakiola.calendula.ui.agenda +import androidx.annotation.StringRes +import androidx.compose.foundation.ExperimentalFoundationApi import androidx.compose.foundation.background import androidx.compose.foundation.clickable -import androidx.compose.foundation.isSystemInDarkTheme import androidx.compose.foundation.layout.Box import androidx.compose.foundation.layout.Column import androidx.compose.foundation.layout.Spacer @@ -10,6 +11,8 @@ import androidx.compose.foundation.layout.fillMaxWidth import androidx.compose.foundation.layout.height import androidx.compose.foundation.layout.padding import androidx.compose.foundation.layout.size +import androidx.compose.foundation.lazy.LazyListScope +import androidx.compose.foundation.lazy.itemsIndexed import androidx.compose.foundation.shape.RoundedCornerShape import androidx.compose.material.icons.Icons import androidx.compose.material.icons.filled.Coffee @@ -31,22 +34,25 @@ import de.jeanlucmakiola.calendula.R import de.jeanlucmakiola.calendula.domain.EventInstance import de.jeanlucmakiola.calendula.domain.isDeclined import de.jeanlucmakiola.calendula.ui.common.EventDimAlpha +import de.jeanlucmakiola.calendula.ui.common.ViewMorphKey import de.jeanlucmakiola.calendula.ui.common.declinedTitle import de.jeanlucmakiola.calendula.ui.common.LocalSoftenColors import de.jeanlucmakiola.calendula.ui.common.LocalUse24HourFormat import de.jeanlucmakiola.calendula.ui.common.eventAccent -import de.jeanlucmakiola.calendula.ui.common.eventFill import de.jeanlucmakiola.calendula.ui.common.formatTimeOfDay +import de.jeanlucmakiola.calendula.ui.common.morphEvent import de.jeanlucmakiola.floret.components.GroupedRow import de.jeanlucmakiola.floret.components.Position +import de.jeanlucmakiola.floret.components.positionOf +import de.jeanlucmakiola.floret.identity.LocalFloretDarkTheme +import de.jeanlucmakiola.floret.identity.animateItemMotion import de.jeanlucmakiola.floret.locale.currentLocale import de.jeanlucmakiola.floret.locale.localizedDateFormatter import kotlinx.datetime.DateTimeUnit import kotlinx.datetime.LocalDate import kotlinx.datetime.TimeZone import kotlinx.datetime.plus -import kotlinx.datetime.toLocalDateTime -import kotlin.time.Instant +import kotlinx.datetime.toJavaLocalDate import java.util.Locale // The agenda's row vocabulary, split out of AgendaScreen so the month view's @@ -127,7 +133,7 @@ internal fun AgendaEventRow( modifier: Modifier = Modifier, onClick: () -> Unit, ) { - val dark = isSystemInDarkTheme() + val dark = LocalFloretDarkTheme.current val soften = LocalSoftenColors.current val title = event.title.ifBlank { stringResource(R.string.event_untitled) } GroupedRow( @@ -177,34 +183,74 @@ internal fun agendaTimeSummary(event: EventInstance, day: LocalDate, zone: TimeZ AgendaTimeLabel.AllDay -> stringResource(R.string.event_detail_all_day) is AgendaTimeLabel.Starts -> stringResource( R.string.agenda_span_starts, - formatTime(label.start, zone, is24Hour, locale), + formatTimeOfDay(label.start, zone, is24Hour, locale), ) is AgendaTimeLabel.Ends -> stringResource( R.string.agenda_span_ends, - formatTime(label.end, zone, is24Hour, locale), + formatTimeOfDay(label.end, zone, is24Hour, locale), ) - is AgendaTimeLabel.Range -> "${formatTime(label.start, zone, is24Hour, locale)} – " + - formatTime(label.end, zone, is24Hour, locale) + is AgendaTimeLabel.Range -> "${formatTimeOfDay(label.start, zone, is24Hour, locale)} – " + + formatTimeOfDay(label.end, zone, is24Hour, locale) } val location = event.location?.takeIf { it.isNotBlank() } return if (location != null) "$time · $location" else time } -private fun formatTime( - instant: Instant, - zone: TimeZone, - is24Hour: Boolean, - locale: Locale, -): String { - val t = instant.toLocalDateTime(zone).time - return formatTimeOfDay(t.hour, t.minute, is24Hour, locale) -} - private fun formatAgendaDate(date: LocalDate): String { val locale = Locale.getDefault() - val java = java.time.LocalDate.of(date.year, date.month.ordinal + 1, date.day) + val java = date.toJavaLocalDate() // Weekday + date in the locale's own field order (e.g. "Wed, Jun 17, 2026" // vs "Mi., 17. Juni 2026") rather than a hardcoded day-month-year layout. return localizedDateFormatter(locale, "EEEdMMMy").format(java) } + +/** + * The agenda's day-by-day list body: a sticky header per day, its events or a + * placeholder row for an event-less day, then a gap. Shared by the Agenda screen + * and the month view's split pane so both lists read the same. + */ +@OptIn(ExperimentalFoundationApi::class) +internal fun LazyListScope.agendaDays( + days: List, + today: LocalDate, + zone: TimeZone, + @StringRes emptyText: Int, + onEmptyClick: (LocalDate) -> Unit, + dimmed: (EventInstance, LocalDate) -> Boolean, + onOpenDay: (LocalDate) -> Unit, + onEventClick: (EventInstance) -> Unit, +) { + days.forEach { day -> + stickyHeader(key = "header-${day.date}") { + AgendaDayHeader(date = day.date, today = today, onOpenDay = onOpenDay) + } + if (day.events.isEmpty()) { + item(key = "placeholder-${day.date}") { + AgendaEmptyDayRow( + text = stringResource(emptyText), + onClick = { onEmptyClick(day.date) }, + ) + } + } else { + itemsIndexed( + items = day.events, + // Scope the key by day: a multi-day event appears under every + // day it spans, so its instanceId alone is not unique across + // the list (LazyColumn requires unique keys). + key = { _, event -> "${day.date}-${event.instanceId}" }, + ) { index, event -> + AgendaEventRow( + event = event, + day = day.date, + zone = zone, + position = positionOf(index, day.events.size), + dimmed = dimmed(event, day.date), + modifier = animateItemMotion().morphEvent(ViewMorphKey.event(event, day.date)), + onClick = { onEventClick(event) }, + ) + } + } + item(key = "gap-${day.date}") { Spacer(Modifier.height(8.dp)) } + } +} diff --git a/app/src/main/java/de/jeanlucmakiola/calendula/ui/agenda/AgendaScreen.kt b/app/src/main/java/de/jeanlucmakiola/calendula/ui/agenda/AgendaScreen.kt index 737b0239..1b2871e7 100644 --- a/app/src/main/java/de/jeanlucmakiola/calendula/ui/agenda/AgendaScreen.kt +++ b/app/src/main/java/de/jeanlucmakiola/calendula/ui/agenda/AgendaScreen.kt @@ -5,15 +5,11 @@ import de.jeanlucmakiola.calendula.ui.common.ScreenActions import de.jeanlucmakiola.calendula.ui.common.ScreenBody import de.jeanlucmakiola.calendula.ui.common.ScreenChrome import de.jeanlucmakiola.calendula.ui.common.LocalViewFocus -import de.jeanlucmakiola.calendula.ui.common.EnterOnFocus import kotlinx.coroutines.flow.drop import androidx.compose.runtime.getValue import androidx.compose.runtime.setValue import androidx.compose.runtime.snapshotFlow import androidx.compose.runtime.rememberUpdatedState -import de.jeanlucmakiola.calendula.ui.common.ViewMorphKey -import de.jeanlucmakiola.calendula.ui.common.morphEvent -import androidx.compose.foundation.ExperimentalFoundationApi import androidx.compose.foundation.layout.Arrangement import androidx.compose.foundation.layout.Box import androidx.compose.foundation.layout.Column @@ -27,7 +23,6 @@ import androidx.compose.foundation.layout.padding import androidx.compose.foundation.layout.size import androidx.compose.foundation.lazy.LazyColumn import androidx.compose.foundation.lazy.LazyListState -import androidx.compose.foundation.lazy.itemsIndexed import androidx.compose.foundation.lazy.rememberLazyListState import androidx.compose.material.icons.Icons import androidx.compose.material.icons.filled.Coffee @@ -38,7 +33,16 @@ import androidx.compose.material3.Icon import androidx.compose.material3.MaterialTheme import androidx.compose.material3.Text import androidx.compose.runtime.Composable +import androidx.compose.runtime.DisposableEffect import androidx.compose.runtime.LaunchedEffect +import androidx.compose.runtime.MutableIntState +import androidx.compose.runtime.SideEffect +import androidx.compose.runtime.mutableIntStateOf +import androidx.compose.runtime.saveable.rememberSaveable +import androidx.compose.ui.geometry.Offset +import androidx.compose.ui.input.nestedscroll.NestedScrollConnection +import androidx.compose.ui.input.nestedscroll.NestedScrollSource +import androidx.compose.ui.input.nestedscroll.nestedScroll import androidx.compose.runtime.derivedStateOf import androidx.compose.runtime.mutableStateOf import androidx.compose.runtime.remember @@ -53,16 +57,14 @@ import androidx.lifecycle.compose.collectAsStateWithLifecycle import de.jeanlucmakiola.calendula.R import de.jeanlucmakiola.calendula.data.prefs.PastEventDisplay import de.jeanlucmakiola.calendula.domain.EventInstance -import de.jeanlucmakiola.calendula.domain.hasEnded +import de.jeanlucmakiola.calendula.ui.common.isPastOn import de.jeanlucmakiola.calendula.ui.common.AgendaRangePicker import de.jeanlucmakiola.calendula.ui.common.AppBarSpacing import de.jeanlucmakiola.calendula.ui.common.QuickSwitchConfig import de.jeanlucmakiola.calendula.ui.common.agendaRangeLabel -import de.jeanlucmakiola.floret.identity.animateItemMotion import de.jeanlucmakiola.calendula.ui.common.CalendarFailure import de.jeanlucmakiola.calendula.ui.common.CalendarView import de.jeanlucmakiola.calendula.ui.common.IMPLEMENTED_VIEWS -import de.jeanlucmakiola.floret.components.positionOf import de.jeanlucmakiola.calendula.ui.common.rememberCurrentMinute import de.jeanlucmakiola.floret.locale.currentLocale import kotlinx.coroutines.launch @@ -82,11 +84,23 @@ fun AgendaScreen( onCreateEvent: (LocalDate, Int?) -> Unit, quickSwitchViews: List = IMPLEMENTED_VIEWS, modifier: Modifier = Modifier, + restorePosition: Boolean = false, viewModel: AgendaViewModel = hiltViewModel(), ) { - // Opens on the focused date and hands back the day scrolled to the top. + // Opens on today, not on the day another view was on (#367). Backing out of + // a day opened from here, or a recreated screen, returns to the day last at + // the top. The top day still goes back to the shared focus. val focus = LocalViewFocus.current - EnterOnFocus(viewModel) { if (it != viewModel.anchor.value) viewModel.goToDate(it) } + val opened = rememberSaveable { mutableStateOf(false) } + val restoreTop = remember(viewModel) { + if (restorePosition || opened.value) { + viewModel.lastTopDate + } else { + viewModel.goToToday() + null + } + } + SideEffect { opened.value = true } val state by viewModel.state.collectAsStateWithLifecycle() val anchor by viewModel.anchor.collectAsStateWithLifecycle() val pastDisplay by viewModel.pastEventDisplay.collectAsStateWithLifecycle() @@ -106,20 +120,19 @@ fun AgendaScreen( // list scroll, not an anchor change — "today" has to bring the list back to // the top as well, and stay offered while it is scrolled away (#305). val listState = rememberLazyListState() + // Past days load above the anchor (#367), so the anchor's row counts as the + // start of the list. + val anchorIndex = remember { mutableIntStateOf(0) } val scrolledAway by remember { derivedStateOf { - listState.firstVisibleItemIndex > 0 || listState.firstVisibleItemScrollOffset > 0 + listState.firstVisibleItemIndex != anchorIndex.intValue || + listState.firstVisibleItemScrollOffset > 0 } } - // A new window is rendered from its first day, so the list belongs at the - // top. Keyed on the anchor the days arrived with, not the one just - // requested: scrolling before the new rows compose leaves the list keyed to - // a row that reappears further down, and it follows it there. - LaunchedEffect(successState?.anchor) { listState.scrollToItem(0) } val jumpToToday: () -> Unit = { - // Off today, moving the anchor is what resets the list (above); on today + // Off today, moving the anchor is what repositions the list; on today // the window doesn't change, so the scroll back is the whole action. - if (isOnToday) scope.launch { listState.animateScrollToItem(0) } + if (isOnToday) scope.launch { listState.animateScrollToItem(anchorIndex.intValue) } viewModel.goToToday() (state as? AgendaUiState.Success)?.today?.let { focus?.date = it } } @@ -188,11 +201,17 @@ fun AgendaScreen( pastDisplay = pastDisplay, showToday = showToday, listState = listState, + anchorIndex = anchorIndex, + initialTopDate = restoreTop, + onLoadEarlier = viewModel::loadEarlier, onRetry = viewModel::goToToday, onEventClick = onEventClick, onOpenDay = onOpenDay, onTopDay = if (successState?.anchor == anchor) { - { focus?.date = it } + { + focus?.date = it + viewModel.rememberTopDay(it) + } } else null, modifier = Modifier .weight(1f) @@ -294,6 +313,9 @@ internal fun AgendaContent( onOpenDay: (LocalDate) -> Unit, modifier: Modifier = Modifier, listState: LazyListState = rememberLazyListState(), + anchorIndex: MutableIntState = remember { mutableIntStateOf(0) }, + initialTopDate: LocalDate? = null, + onLoadEarlier: () -> Unit = {}, onTopDay: ((LocalDate) -> Unit)? = null, ) { when (state) { @@ -308,28 +330,34 @@ internal fun AgendaContent( // away (or fade) as they end while the screen stays open. val filtered = if (pastDisplay == PastEventDisplay.HIDE) { state.days.mapNotNull { day -> - val remaining = day.events.filterNot { it.hasEnded(now) } + val remaining = day.events.filterNot { it.isPastOn(day.date, now, state.zone) } if (remaining.isEmpty()) null else day.copy(events = remaining) } } else { state.days } // Anchor today with a "nothing left today" placeholder — but only when - // the window actually starts on today; a jumped-to date has no today in - // it, so anchoring there would be misleading (#35). + // the agenda actually opens on today; a jumped-to date has no today + // in it, so anchoring there would be misleading (#35). val days = anchorTodayIfMissing( days = filtered, today = state.today, enabled = showToday && state.anchor == state.today, ) - if (days.isEmpty()) { + // Past days alone don't count as anything coming up. + if (days.none { it.date >= state.anchor }) { // Nothing to scroll: drop the position a previous list left, so // the today FAB doesn't linger over an empty screen. LaunchedEffect(Unit) { listState.scrollToItem(0) } + SideEffect { anchorIndex.intValue = 0 } AgendaEmpty(modifier) } else { AgendaList( days = days, + anchor = state.anchor, + anchorIndex = anchorIndex, + initialTopDate = initialTopDate, + onLoadEarlier = onLoadEarlier, today = state.today, zone = state.zone, listState = listState, @@ -345,10 +373,13 @@ internal fun AgendaContent( } } -@OptIn(ExperimentalFoundationApi::class) @Composable private fun AgendaList( days: List, + anchor: LocalDate, + anchorIndex: MutableIntState, + initialTopDate: LocalDate?, + onLoadEarlier: () -> Unit, today: LocalDate, zone: TimeZone, listState: LazyListState, @@ -359,59 +390,67 @@ private fun AgendaList( onTopDay: ((LocalDate) -> Unit)?, modifier: Modifier = Modifier, ) { + val itemDates = agendaItemDates(days) + val anchorRow = itemDates.indexOfFirst { it >= anchor }.coerceAtLeast(0) + SideEffect { anchorIndex.intValue = anchorRow } + // A new anchor opens on its row from the first frame; keyed on the anchor + // the days arrived with, not the one requested. The first run may restore. + val pendingRestore = remember { arrayOf(initialTopDate) } + DisposableEffect(anchor) { + val target = pendingRestore[0] + pendingRestore[0] = null + val index = target?.let { date -> itemDates.indexOfFirst { it >= date } } + ?.takeIf { it >= 0 } + ?: anchorRow + listState.requestScrollToItem(index) + onDispose {} + } + // Scrolling up near the first loaded day loads earlier days. + val currentLoadEarlier by rememberUpdatedState(onLoadEarlier) + val loadOnScrollUp = remember(listState) { + object : NestedScrollConnection { + override fun onPreScroll(available: Offset, source: NestedScrollSource): Offset { + if (available.y > 0 && listState.firstVisibleItemIndex < LOAD_EARLIER_WITHIN) { + currentLoadEarlier() + } + return Offset.Zero + } + } + } if (onTopDay != null) { - val itemDates by rememberUpdatedState(agendaItemDates(days)) + val currentItemDates by rememberUpdatedState(itemDates) val currentOnTopDay by rememberUpdatedState(onTopDay) // The day the list opened on is where the view already is; only a // scroll moves it on. LaunchedEffect(listState) { snapshotFlow { listState.firstVisibleItemIndex } .drop(1) - .collect { index -> itemDates.getOrNull(index)?.let(currentOnTopDay) } + .collect { index -> currentItemDates.getOrNull(index)?.let(currentOnTopDay) } } } LazyColumn( - modifier = modifier, + modifier = modifier.nestedScroll(loadOnScrollUp), state = listState, // Bottom inset clears the FAB stack so the last row stays tappable. contentPadding = PaddingValues(top = 8.dp, bottom = 96.dp), ) { - days.forEach { day -> - stickyHeader(key = "header-${day.date}") { - AgendaDayHeader(date = day.date, today = today, onOpenDay = onOpenDay) - } - if (day.events.isEmpty()) { - // An anchored, event-less today (#35) — "nothing left today". - item(key = "placeholder-${day.date}") { - AgendaEmptyDayRow( - text = stringResource(R.string.agenda_no_more_today), - onClick = { onOpenDay(day.date) }, - ) - } - } else { - itemsIndexed( - items = day.events, - // Scope the key by day: a multi-day event appears under every - // day it spans, so its instanceId alone is not unique across - // the list (LazyColumn requires unique keys). - key = { _, event -> "${day.date}-${event.instanceId}" }, - ) { index, event -> - AgendaEventRow( - event = event, - day = day.date, - zone = zone, - position = positionOf(index, day.events.size), - dimmed = dimPast && event.hasEnded(now), - modifier = animateItemMotion().morphEvent(ViewMorphKey.event(event, day.date)), - onClick = { onEventClick(event) }, - ) - } - } - item(key = "gap-${day.date}") { Spacer(Modifier.height(8.dp)) } - } + agendaDays( + days = days, + today = today, + zone = zone, + // An anchored, event-less today (#35) — "nothing left today". + emptyText = R.string.agenda_no_more_today, + onEmptyClick = onOpenDay, + dimmed = { event, day -> dimPast && event.isPastOn(day, now, zone) }, + onOpenDay = onOpenDay, + onEventClick = onEventClick, + ) } } +/** How close to the first loaded row an upward scroll starts loading earlier days. */ +private const val LOAD_EARLIER_WITHIN = 10 + /** The day of each item [AgendaList] lays out for [days], in its order. */ internal fun agendaItemDates(days: List): List = days.flatMap { day -> diff --git a/app/src/main/java/de/jeanlucmakiola/calendula/ui/agenda/AgendaUiState.kt b/app/src/main/java/de/jeanlucmakiola/calendula/ui/agenda/AgendaUiState.kt index f38a34df..e67e78b0 100644 --- a/app/src/main/java/de/jeanlucmakiola/calendula/ui/agenda/AgendaUiState.kt +++ b/app/src/main/java/de/jeanlucmakiola/calendula/ui/agenda/AgendaUiState.kt @@ -93,22 +93,21 @@ fun groupAgendaDays( } /** - * Ensure [today] surfaces as the first agenda day even when it carries no - * (remaining) events, by prepending an empty-event [AgendaDay] the agenda widget + * Ensure [today] surfaces in the agenda even when it carries no (remaining) + * events, by inserting an empty-event [AgendaDay] in date order that the agenda * renders as a "nothing left today" placeholder. A no-op unless [enabled], and - * when today already has its own day in [days]. Keeps today anchored at the top - * so a glance tells today's events apart from a future day's (issue #35). + * when today already has its own day in [days]. Keeps today anchored so a glance + * tells today's events apart from a future day's (issue #35). */ fun anchorTodayIfMissing( days: List, today: LocalDate, enabled: Boolean, -): List = - if (enabled && days.none { it.date == today }) { - listOf(AgendaDay(today, emptyList())) + days - } else { - days - } +): List { + if (!enabled || days.any { it.date == today }) return days + val at = days.indexOfFirst { it.date > today }.let { if (it < 0) days.size else it } + return days.take(at) + AgendaDay(today, emptyList()) + days.drop(at) +} /** * State for the Agenda view: a flat, forward-looking list of upcoming events @@ -118,8 +117,10 @@ sealed interface AgendaUiState { data object Loading : AgendaUiState data class Failure(val reason: FailureReason) : AgendaUiState data class Success( - /** First day of the loaded window (today, or a jumped-to date). */ + /** The day the agenda opens on (today, or a jumped-to date). */ val anchor: LocalDate, + /** First loaded day, before [anchor] once past days are loaded (#367). */ + val windowStart: LocalDate, val today: LocalDate, val days: List, /** The range currently in effect — the saved default or a session override. */ diff --git a/app/src/main/java/de/jeanlucmakiola/calendula/ui/agenda/AgendaViewModel.kt b/app/src/main/java/de/jeanlucmakiola/calendula/ui/agenda/AgendaViewModel.kt index ae372712..3832eaf8 100644 --- a/app/src/main/java/de/jeanlucmakiola/calendula/ui/agenda/AgendaViewModel.kt +++ b/app/src/main/java/de/jeanlucmakiola/calendula/ui/agenda/AgendaViewModel.kt @@ -1,19 +1,22 @@ package de.jeanlucmakiola.calendula.ui.agenda +import de.jeanlucmakiola.calendula.ui.common.dayRange import androidx.lifecycle.ViewModel import androidx.lifecycle.viewModelScope import dagger.hilt.android.lifecycle.HiltViewModel import de.jeanlucmakiola.calendula.data.calendar.CalendarRepository -import de.jeanlucmakiola.calendula.data.di.IoDispatcher import de.jeanlucmakiola.calendula.data.prefs.PastEventDisplay import de.jeanlucmakiola.calendula.data.prefs.SettingsPrefs import de.jeanlucmakiola.calendula.data.prefs.firstDayOfWeek import de.jeanlucmakiola.calendula.data.time.TodaySource import de.jeanlucmakiola.calendula.data.time.currentDate +import de.jeanlucmakiola.calendula.data.time.stateFollowingDays import de.jeanlucmakiola.calendula.domain.CalendarSource import de.jeanlucmakiola.calendula.domain.EventInstance import de.jeanlucmakiola.calendula.domain.FailureReason import de.jeanlucmakiola.calendula.domain.calendarListFailure +import de.jeanlucmakiola.floret.android.stateWhileSubscribed +import de.jeanlucmakiola.floret.di.IoDispatcher import kotlinx.coroutines.CoroutineDispatcher import kotlinx.coroutines.ExperimentalCoroutinesApi import kotlinx.coroutines.flow.MutableStateFlow @@ -23,16 +26,14 @@ import kotlinx.coroutines.flow.catch import kotlinx.coroutines.flow.combine import kotlinx.coroutines.flow.flatMapLatest import kotlinx.coroutines.flow.flowOn -import kotlinx.coroutines.flow.onEach +import kotlinx.coroutines.flow.map import kotlinx.coroutines.flow.stateIn import kotlinx.datetime.DateTimeUnit import kotlinx.datetime.DayOfWeek import kotlinx.datetime.LocalDate import kotlinx.datetime.TimeZone -import kotlinx.datetime.atStartOfDayIn -import kotlinx.datetime.atTime +import kotlinx.datetime.minus import kotlinx.datetime.plus -import kotlinx.datetime.toInstant import kotlin.time.Instant import javax.inject.Inject @@ -64,9 +65,8 @@ class AgendaViewModel @Inject constructor( * the screen combines it with a per-minute "now" to fade or drop past rows. */ val pastEventDisplay: StateFlow = settingsPrefs.pastEventDisplay - .stateIn( + .stateWhileSubscribed( scope = viewModelScope, - started = SharingStarted.WhileSubscribed(5_000L), initialValue = PastEventDisplay.SHOW, ) @@ -77,9 +77,8 @@ class AgendaViewModel @Inject constructor( * alongside the data state like [pastEventDisplay] rather than re-querying. */ val showToday: StateFlow = settingsPrefs.agendaShowToday - .stateIn( + .stateWhileSubscribed( scope = viewModelScope, - started = SharingStarted.WhileSubscribed(5_000L), initialValue = true, ) @@ -88,22 +87,25 @@ class AgendaViewModel @Inject constructor( private val todayDate: LocalDate get() = currentDate() - private val _anchor = MutableStateFlow(todayDate) - val anchor: StateFlow = _anchor + // The anchor and how many days before it are loaded, moved together so a + // jump never queries a window that pairs the new anchor with the old span. + private val _window = MutableStateFlow(AgendaWindow(todayDate, PAST_CHUNK_DAYS)) + val anchor: StateFlow = _window + .map { it.anchor } + .stateIn(viewModelScope, SharingStarted.Eagerly, todayDate) - private var lastToday = todayDate + /** The day last scrolled to the top, so a return to the agenda lands back on it. */ + var lastTopDate: LocalDate? = null + private set /** * Today, kept current across midnight (#373). An agenda still starting on * yesterday moves on to the new day; one jumped elsewhere stays put. */ - private val today: StateFlow = todaySource.today - .onEach { date -> - val old = lastToday - lastToday = date - if (old != date && _anchor.value == old) _anchor.value = date + private val today: StateFlow = + todaySource.today.stateFollowingDays(viewModelScope, todayDate) { old, date -> + if (_window.value.anchor == old) _window.value = _window.value.copy(anchor = date) } - .stateIn(viewModelScope, SharingStarted.WhileSubscribed(5_000L), todayDate) // A transient, in-view override of the saved agenda range. Held in memory // (not persisted), so it survives view switches and rotation within the @@ -111,9 +113,17 @@ class AgendaViewModel @Inject constructor( private val _rangeOverride = MutableStateFlow(null) val state: StateFlow = - combine(_anchor, agendaSettings, _rangeOverride, weekStart) { anchor, settings, override, weekStart -> + combine( + _window, + agendaSettings, + _rangeOverride, + weekStart, + settingsPrefs.pastEventDisplay, + ) { window, settings, override, weekStart, pastDisplay -> AgendaParams( - anchor = anchor, + anchor = window.anchor, + // Hidden past events leave nothing to scroll back to (#367). + pastDays = if (pastDisplay == PastEventDisplay.HIDE) 0 else window.pastDays, range = override ?: settings.range, rangeIsOverride = override != null && override != settings.range, weekStart = weekStart, @@ -122,8 +132,8 @@ class AgendaViewModel @Inject constructor( } .flatMapLatest { params -> val window = agendaRange( - params.anchor, - params.range.dayCount(params.anchor, params.weekStart) - 1, + params.windowStart, + params.pastDays + params.range.dayCount(params.anchor, params.weekStart) - 1, zone, ) combine( @@ -136,19 +146,38 @@ class AgendaViewModel @Inject constructor( } .catch { emit(AgendaUiState.Failure(FailureReason.ProviderUnavailable)) } .flowOn(io) - .stateIn( + .stateWhileSubscribed( scope = viewModelScope, - started = SharingStarted.WhileSubscribed(5_000L), initialValue = AgendaUiState.Loading, ) fun goToToday() { - _anchor.value = todayDate + goToDate(todayDate) } /** Jump the agenda window to start on a specific date (drawer jump-to-date). */ fun goToDate(date: LocalDate) { - _anchor.value = date + if (_window.value.anchor == date) return + _window.value = AgendaWindow(date, PAST_CHUNK_DAYS) + lastTopDate = null + } + + /** + * Extend the window further back (#367), doubling what's loaded (at least + * [PAST_CHUNK_DAYS], at most [MAX_PAST_STEP_DAYS]) so a long scroll back + * re-queries only a few times. Ignored while the previous extension is + * still loading. + */ + fun loadEarlier() { + val loaded = (state.value as? AgendaUiState.Success)?.windowStart ?: return + val window = _window.value + if (loaded != window.start) return + val step = window.pastDays.coerceIn(PAST_CHUNK_DAYS, MAX_PAST_STEP_DAYS) + _window.value = window.copy(pastDays = window.pastDays + step) + } + + fun rememberTopDay(date: LocalDate) { + lastTopDate = date } /** Temporarily override the agenda range for this session (the bottom-left pill). */ @@ -161,13 +190,20 @@ class AgendaViewModel @Inject constructor( val showBar: Boolean, ) + private data class AgendaWindow(val anchor: LocalDate, val pastDays: Int) { + val start: LocalDate get() = anchor.minus(pastDays, DateTimeUnit.DAY) + } + private data class AgendaParams( val anchor: LocalDate, + val pastDays: Int, val range: AgendaRange, val rangeIsOverride: Boolean, val weekStart: DayOfWeek, val showRangeBar: Boolean, - ) + ) { + val windowStart: LocalDate get() = anchor.minus(pastDays, DateTimeUnit.DAY) + } private fun buildState( params: AgendaParams, @@ -181,9 +217,10 @@ class AgendaViewModel @Inject constructor( params.range.dayCount(anchor, params.weekStart) - 1, DateTimeUnit.DAY, ) - val days = groupAgendaDays(anchor, rangeEnd, instances, zone) + val days = groupAgendaDays(params.windowStart, rangeEnd, instances, zone) return AgendaUiState.Success( anchor = anchor, + windowStart = params.windowStart, today = today, days = days, range = params.range, @@ -195,9 +232,12 @@ class AgendaViewModel @Inject constructor( } } +/** How many days each scroll back into the past loads (#367). */ +internal const val PAST_CHUNK_DAYS = 30 + +/** The most one scroll back adds, so an empty past grows the window by years, not exponentially. */ +internal const val MAX_PAST_STEP_DAYS = 365 + /** Inclusive instant range from the start of [anchor] through [days] days ahead. */ -internal fun agendaRange(anchor: LocalDate, days: Int, zone: TimeZone): ClosedRange { - val from = anchor.atStartOfDayIn(zone) - val to = anchor.plus(days, DateTimeUnit.DAY).atTime(23, 59, 59).toInstant(zone) - return from..to -} +internal fun agendaRange(anchor: LocalDate, days: Int, zone: TimeZone): ClosedRange = + dayRange(anchor, anchor.plus(days, DateTimeUnit.DAY), zone) diff --git a/app/src/main/java/de/jeanlucmakiola/calendula/ui/agenda/AgendaViewPreview.kt b/app/src/main/java/de/jeanlucmakiola/calendula/ui/agenda/AgendaViewPreview.kt index e6249fea..452c8482 100644 --- a/app/src/main/java/de/jeanlucmakiola/calendula/ui/agenda/AgendaViewPreview.kt +++ b/app/src/main/java/de/jeanlucmakiola/calendula/ui/agenda/AgendaViewPreview.kt @@ -6,8 +6,8 @@ import androidx.compose.runtime.remember import androidx.compose.ui.Modifier import androidx.compose.ui.unit.Dp import de.jeanlucmakiola.calendula.data.prefs.PastEventDisplay -import de.jeanlucmakiola.calendula.ui.common.ScaledViewPreview import de.jeanlucmakiola.calendula.ui.common.sampleAgendaEvents +import de.jeanlucmakiola.floret.components.ScaledViewPreview import kotlinx.datetime.DateTimeUnit import kotlinx.datetime.LocalDate import kotlinx.datetime.TimeZone @@ -51,6 +51,7 @@ private fun sampleAgendaState(today: LocalDate, zone: TimeZone): AgendaUiState.S val windowEnd = today.plus(PREVIEW_WINDOW_DAYS, DateTimeUnit.DAY) return AgendaUiState.Success( anchor = today, + windowStart = today, today = today, days = groupAgendaDays(today, windowEnd, sampleAgendaEvents(today, zone), zone), range = AgendaRange.Custom(PREVIEW_WINDOW_DAYS), diff --git a/app/src/main/java/de/jeanlucmakiola/calendula/ui/calendars/BackupScreen.kt b/app/src/main/java/de/jeanlucmakiola/calendula/ui/calendars/BackupScreen.kt index 2da55f13..d319ff0c 100644 --- a/app/src/main/java/de/jeanlucmakiola/calendula/ui/calendars/BackupScreen.kt +++ b/app/src/main/java/de/jeanlucmakiola/calendula/ui/calendars/BackupScreen.kt @@ -1,7 +1,6 @@ package de.jeanlucmakiola.calendula.ui.calendars import android.net.Uri -import android.text.format.DateUtils import androidx.activity.compose.rememberLauncherForActivityResult import androidx.activity.result.contract.ActivityResultContracts import androidx.compose.foundation.layout.Box @@ -54,13 +53,17 @@ import de.jeanlucmakiola.calendula.ui.common.CalendarColorChip import de.jeanlucmakiola.calendula.ui.common.CalendarFailure import de.jeanlucmakiola.calendula.ui.common.LeadingAvatar import de.jeanlucmakiola.calendula.ui.common.LocalManageCalendars +import de.jeanlucmakiola.calendula.ui.common.orUnnamed import de.jeanlucmakiola.floret.components.CollapsingScaffold import de.jeanlucmakiola.floret.components.DialogAmountField import de.jeanlucmakiola.floret.components.DialogUnitDropdown import de.jeanlucmakiola.floret.components.FullScreenPicker +import de.jeanlucmakiola.floret.components.GroupedHint import de.jeanlucmakiola.floret.components.GroupedRow +import de.jeanlucmakiola.floret.components.GroupedSectionHeader import de.jeanlucmakiola.floret.components.Position import de.jeanlucmakiola.floret.components.positionOf +import de.jeanlucmakiola.floret.locale.relativeTimeAgo import java.time.LocalDate // SAF mime filter for the restore picker. Source apps hand `.ics` files out @@ -222,8 +225,8 @@ private fun BackupContent( val onRestoreClick = if (canImport) onRestore else (manageCalendars ?: onRestore) if (exportable.isEmpty()) { - SectionHeader(stringResource(R.string.calendars_restore_header)) - HintText(restoreSummary) + GroupedSectionHeader(stringResource(R.string.calendars_restore_header)) + GroupedHint(restoreSummary, style = MaterialTheme.typography.bodySmall) GroupedRow( title = stringResource(R.string.calendars_restore_action), position = Position.Alone, @@ -233,7 +236,7 @@ private fun BackupContent( return } - HintText(stringResource(R.string.calendars_backup_hint)) + GroupedHint(stringResource(R.string.calendars_backup_hint), style = MaterialTheme.typography.bodySmall) GroupedRow( title = stringResource(R.string.calendars_backup_action), position = Position.Top, @@ -272,7 +275,7 @@ private fun BackupContent( position = Position.Bottom, onClick = onEditInterval, ) - HintText(backupStatusText(autoBackup.status)) + GroupedHint(backupStatusText(autoBackup.status), style = MaterialTheme.typography.bodySmall) } } @@ -309,12 +312,13 @@ private fun ExportCalendarPicker( FullScreenPicker( title = stringResource(R.string.calendars_export_title), onDismiss = onDismiss, + predictiveBack = true, ) { - HintText(stringResource(R.string.calendars_export_hint)) + GroupedHint(stringResource(R.string.calendars_export_hint), style = MaterialTheme.typography.bodySmall) calendars.forEachIndexed { index, calendar -> val isSelected = calendar.id in selected GroupedRow( - title = calendar.displayName.ifBlank { stringResource(R.string.calendar_unnamed) }, + title = calendar.displayName.orUnnamed(), summary = calendar.description, position = positionOf(index, calendars.size), leading = { CalendarColorChip(calendar.color) }, @@ -376,9 +380,7 @@ private fun backupIntervalLabel(minutes: Long): String { @Composable private fun backupStatusText(status: BackupStatus): String { if (status.lastRun == 0L) return stringResource(R.string.calendars_auto_backup_status_never) - val relative = DateUtils.getRelativeTimeSpanString( - status.lastRun, System.currentTimeMillis(), DateUtils.MINUTE_IN_MILLIS, - ).toString() + val relative = relativeTimeAgo(status.lastRun) return if (status.lastSuccess) { stringResource(R.string.calendars_auto_backup_status_ok, relative) } else { diff --git a/app/src/main/java/de/jeanlucmakiola/calendula/ui/calendars/CalendarsScreen.kt b/app/src/main/java/de/jeanlucmakiola/calendula/ui/calendars/CalendarsScreen.kt index 1c3f66f4..5be7aacf 100644 --- a/app/src/main/java/de/jeanlucmakiola/calendula/ui/calendars/CalendarsScreen.kt +++ b/app/src/main/java/de/jeanlucmakiola/calendula/ui/calendars/CalendarsScreen.kt @@ -6,34 +6,27 @@ import android.content.Intent import android.provider.Settings import androidx.compose.animation.AnimatedVisibility import androidx.compose.foundation.background -import androidx.compose.foundation.isSystemInDarkTheme import androidx.compose.foundation.layout.Arrangement import androidx.compose.foundation.layout.Box import androidx.compose.foundation.layout.Column import androidx.compose.foundation.layout.ColumnScope import androidx.compose.foundation.layout.Row import androidx.compose.foundation.layout.Spacer -import androidx.compose.foundation.layout.fillMaxSize import androidx.compose.foundation.layout.fillMaxWidth import androidx.compose.foundation.layout.height import androidx.compose.foundation.layout.padding import androidx.compose.foundation.layout.size import androidx.compose.foundation.layout.width -import androidx.compose.foundation.rememberScrollState import androidx.compose.foundation.shape.RoundedCornerShape -import androidx.compose.foundation.verticalScroll import androidx.compose.material.icons.Icons import androidx.compose.material.icons.automirrored.filled.KeyboardArrowRight -import androidx.compose.material.icons.automirrored.filled.Notes import androidx.compose.material.icons.automirrored.filled.OpenInNew import androidx.compose.material.icons.filled.Add import androidx.compose.material.icons.filled.Backup import androidx.compose.material.icons.filled.CalendarMonth -import androidx.compose.material.icons.filled.Close import androidx.compose.material.icons.filled.Delete import androidx.compose.material.icons.filled.Info import androidx.compose.material.icons.filled.MoreVert -import androidx.compose.material.icons.filled.Palette import androidx.compose.material.icons.filled.PhoneAndroid import androidx.compose.material.icons.filled.Visibility import androidx.compose.material.icons.filled.VisibilityOff @@ -41,20 +34,14 @@ import androidx.compose.material3.AlertDialog import androidx.compose.material3.Button import androidx.compose.material3.DropdownMenu import androidx.compose.material3.DropdownMenuItem -import androidx.compose.material3.ExperimentalMaterial3Api import androidx.compose.material3.HorizontalDivider import androidx.compose.material3.Icon import androidx.compose.material3.IconButton import androidx.compose.material3.MaterialTheme -import androidx.compose.material3.Scaffold import androidx.compose.material3.SnackbarHost import androidx.compose.material3.SnackbarHostState -import androidx.compose.material3.Surface -import androidx.compose.material3.Switch import androidx.compose.material3.Text import androidx.compose.material3.TextButton -import androidx.compose.material3.TopAppBar -import androidx.compose.material3.TopAppBarDefaults import androidx.compose.runtime.Composable import androidx.compose.runtime.LaunchedEffect import androidx.compose.runtime.getValue @@ -85,6 +72,7 @@ import de.jeanlucmakiola.calendula.domain.stateLabels import de.jeanlucmakiola.calendula.data.calendar.CalendarColorPalette import de.jeanlucmakiola.calendula.ui.common.AccountKey import de.jeanlucmakiola.calendula.ui.common.CalendarColorChip +import de.jeanlucmakiola.calendula.ui.common.CalendarVisibilitySwitch import de.jeanlucmakiola.calendula.ui.common.accountGroupTitle import de.jeanlucmakiola.calendula.ui.common.groupByAccount import de.jeanlucmakiola.calendula.ui.common.LocalSoftenColors @@ -94,11 +82,14 @@ import de.jeanlucmakiola.calendula.ui.common.eventInk import de.jeanlucmakiola.calendula.ui.common.LeadingAvatar import de.jeanlucmakiola.calendula.ui.common.SourceLogo import de.jeanlucmakiola.calendula.ui.common.curatedSourcePackage +import de.jeanlucmakiola.calendula.ui.common.orUnnamed import de.jeanlucmakiola.floret.components.CollapsingScaffold +import de.jeanlucmakiola.floret.components.GroupedHint +import de.jeanlucmakiola.floret.components.GroupedSectionHeader +import de.jeanlucmakiola.floret.identity.LocalFloretDarkTheme import de.jeanlucmakiola.floret.identity.collapseExit import de.jeanlucmakiola.floret.identity.expandEnter import de.jeanlucmakiola.floret.identity.predictiveBack -import de.jeanlucmakiola.floret.components.GroupedListInset import de.jeanlucmakiola.floret.components.GroupedRow import de.jeanlucmakiola.floret.components.InlineTextField import de.jeanlucmakiola.floret.components.Position @@ -224,7 +215,7 @@ private fun CalendarsList( visible = visible, ) { // What the per-calendar / per-account switches below actually do. - HintText(stringResource(R.string.calendars_visibility_hint)) + GroupedHint(stringResource(R.string.calendars_visibility_hint), style = MaterialTheme.typography.bodySmall) // Local (device-only) calendars — one collapsible group. The header's // "+" adds a calendar; the switch enables/disables them all at once; @@ -245,24 +236,13 @@ private fun CalendarsList( onToggleAll = { enabled -> onSetAccountVisible(local.map { it.id }, enabled) }, ) { if (local.isEmpty()) { - HintText(stringResource(R.string.calendars_local_empty)) + GroupedHint(stringResource(R.string.calendars_local_empty), style = MaterialTheme.typography.bodySmall) } else { local.forEachIndexed { index, calendar -> - val disabled = !calendar.isVisibleInSystem - GroupedRow( - title = calendar.displayName.ifBlank { stringResource(R.string.calendar_unnamed) }, - summary = calendarRowSummary(calendar), - position = if (index == local.lastIndex) Position.Bottom else Position.Middle, - container = MaterialTheme.colorScheme.surfaceContainerHighest, - dimmed = disabled, - leading = { CalendarColorChip(calendar.color, dimIf(disabled)) }, - trailing = { - EnableSwitch( - calendarName = calendar.displayName.ifBlank { stringResource(R.string.calendar_unnamed) }, - enabled = !disabled, - onToggle = { enabled -> onSetVisible(calendar.id, enabled) }, - ) - }, + CalendarManagerRow( + calendar = calendar, + last = index == local.lastIndex, + onSetVisible = onSetVisible, onClick = { onEdit(calendar) }, ) } @@ -291,8 +271,8 @@ private fun CalendarsList( // Synced calendars — read-only, grouped by account. Each account is a // collapsible group whose header opens the source app (icon) and toggles // all of its calendars at once (switch). - SectionHeader(stringResource(R.string.calendars_synced_header)) - HintText(stringResource(R.string.calendars_synced_hint)) + GroupedSectionHeader(stringResource(R.string.calendars_synced_header)) + GroupedHint(stringResource(R.string.calendars_synced_hint), style = MaterialTheme.typography.bodySmall) synced .groupByAccount() .forEach { group -> @@ -333,27 +313,10 @@ private fun CalendarsList( // bottom, dimmed and switchless. val ordered = cals.orderedForManager() ordered.forEachIndexed { index, calendar -> - val disabled = !calendar.isVisibleInSystem || calendar.isNotSynced - GroupedRow( - title = calendar.displayName.ifBlank { stringResource(R.string.calendar_unnamed) }, - summary = calendarRowSummary(calendar), - position = if (index == ordered.lastIndex) Position.Bottom else Position.Middle, - container = MaterialTheme.colorScheme.surfaceContainerHighest, - dimmed = disabled, - leading = { CalendarColorChip(calendar.color, dimIf(disabled)) }, - trailing = if (calendar.hasVisibilitySwitch) { - { - EnableSwitch( - calendarName = calendar.displayName.ifBlank { stringResource(R.string.calendar_unnamed) }, - enabled = calendar.isVisibleInSystem, - onToggle = { enabled -> - onSetVisible(calendar.id, enabled) - }, - ) - } - } else { - null - }, + CalendarManagerRow( + calendar = calendar, + last = index == ordered.lastIndex, + onSetVisible = onSetVisible, ) } } @@ -478,7 +441,7 @@ private fun CalendarNameField( onNameChange: (String) -> Unit, onImeAction: () -> Unit, ) { - val dark = isSystemInDarkTheme() + val dark = LocalFloretDarkTheme.current val soften = LocalSoftenColors.current GroupedSurface(position = Position.Alone, modifier = Modifier.padding(horizontal = 16.dp)) { Row( @@ -522,7 +485,7 @@ private fun CalendarNameField( */ @Composable private fun CalendarColorGrid(selected: Int, onSelect: (Int) -> Unit) { - val dark = isSystemInDarkTheme() + val dark = LocalFloretDarkTheme.current val soften = LocalSoftenColors.current GroupedSurface(position = Position.Alone, modifier = Modifier.padding(horizontal = 16.dp)) { Column( @@ -692,17 +655,37 @@ private fun calendarRowSummary(calendar: CalendarSource): String? { * `Calendars.VISIBLE`. Unchecked drops the calendar out of every surface and * stops its reminders. Carries its own content description. */ +/** + * One calendar in a group: dimmed while switched off or not syncing, with the + * visibility switch only where it can change anything. + */ @Composable -private fun EnableSwitch( - calendarName: String, - enabled: Boolean, - onToggle: (Boolean) -> Unit, +private fun CalendarManagerRow( + calendar: CalendarSource, + last: Boolean, + onSetVisible: (Long, Boolean) -> Unit, + onClick: (() -> Unit)? = null, ) { - val label = stringResource(R.string.calendars_visibility_a11y, calendarName) - Switch( - checked = enabled, - onCheckedChange = onToggle, - modifier = Modifier.semantics { contentDescription = label }, + val disabled = !calendar.isVisibleInSystem || calendar.isNotSynced + GroupedRow( + title = calendar.displayName.orUnnamed(), + summary = calendarRowSummary(calendar), + position = if (last) Position.Bottom else Position.Middle, + container = MaterialTheme.colorScheme.surfaceContainerHighest, + dimmed = disabled, + leading = { CalendarColorChip(calendar.color, dimIf(disabled)) }, + trailing = if (calendar.hasVisibilitySwitch) { + { + CalendarVisibilitySwitch( + calendarName = calendar.displayName.orUnnamed(), + enabled = calendar.isVisibleInSystem, + onToggle = { enabled -> onSetVisible(calendar.id, enabled) }, + ) + } + } else { + null + }, + onClick = onClick, ) } @@ -841,33 +824,6 @@ private fun CalendarGroupMenu( } -@Composable -internal fun SectionHeader(text: String) { - Text( - text = text, - style = MaterialTheme.typography.labelLarge, - color = MaterialTheme.colorScheme.primary, - // The cards' own edge, so header and group share a left margin. - modifier = Modifier.padding( - start = GroupedListInset, - end = GroupedListInset, - top = 16.dp, - bottom = 4.dp, - ), - ) -} - -@Composable -internal fun HintText(text: String) { - Text( - text = text, - style = MaterialTheme.typography.bodySmall, - color = MaterialTheme.colorScheme.onSurfaceVariant, - modifier = Modifier.padding(horizontal = GroupedListInset, vertical = 4.dp), - ) -} - - /** * Pick the app to open for managing a synced calendar's account. The account's * own authenticator package (resolved from [AccountManager], no permission diff --git a/app/src/main/java/de/jeanlucmakiola/calendula/ui/calendars/CalendarsViewModel.kt b/app/src/main/java/de/jeanlucmakiola/calendula/ui/calendars/CalendarsViewModel.kt index 38eadec5..861f4525 100644 --- a/app/src/main/java/de/jeanlucmakiola/calendula/ui/calendars/CalendarsViewModel.kt +++ b/app/src/main/java/de/jeanlucmakiola/calendula/ui/calendars/CalendarsViewModel.kt @@ -9,16 +9,16 @@ import dagger.hilt.android.lifecycle.HiltViewModel import dagger.hilt.android.qualifiers.ApplicationContext import de.jeanlucmakiola.calendula.data.backup.BackupScheduler import de.jeanlucmakiola.calendula.data.calendar.CalendarRepository -import de.jeanlucmakiola.calendula.data.di.IoDispatcher import de.jeanlucmakiola.calendula.data.ics.IcsExporter import de.jeanlucmakiola.calendula.data.prefs.BackupStatus import de.jeanlucmakiola.calendula.data.prefs.SettingsPrefs import de.jeanlucmakiola.calendula.domain.CalendarSource import de.jeanlucmakiola.calendula.domain.FailureReason import de.jeanlucmakiola.calendula.domain.ics.IcsWriter +import de.jeanlucmakiola.floret.android.stateWhileSubscribed +import de.jeanlucmakiola.floret.di.IoDispatcher import kotlinx.coroutines.CoroutineDispatcher import kotlinx.coroutines.flow.MutableStateFlow -import kotlinx.coroutines.flow.SharingStarted import kotlinx.coroutines.flow.StateFlow import kotlinx.coroutines.flow.asStateFlow import kotlinx.coroutines.flow.catch @@ -26,7 +26,6 @@ import kotlinx.coroutines.flow.combine import kotlinx.coroutines.flow.first import kotlinx.coroutines.flow.flowOn import kotlinx.coroutines.flow.map -import kotlinx.coroutines.flow.stateIn import kotlinx.coroutines.launch import kotlinx.coroutines.withContext import kotlin.coroutines.cancellation.CancellationException @@ -52,9 +51,8 @@ class CalendarsViewModel @Inject constructor( repository.calendars() .catch { emit(emptyList()) } .flowOn(io) - .stateIn( + .stateWhileSubscribed( scope = viewModelScope, - started = SharingStarted.WhileSubscribed(5_000L), initialValue = emptyList(), ) @@ -68,9 +66,8 @@ class CalendarsViewModel @Inject constructor( .map { backupUiState(it) } .catch { emit(BackupUiState.Failure(FailureReason.ProviderUnavailable)) } .flowOn(io) - .stateIn( + .stateWhileSubscribed( scope = viewModelScope, - started = SharingStarted.WhileSubscribed(5_000L), initialValue = BackupUiState.Loading, ) @@ -84,9 +81,8 @@ class CalendarsViewModel @Inject constructor( AutoBackupUiState(enabled, interval, folder, status) } .flowOn(io) - .stateIn( + .stateWhileSubscribed( scope = viewModelScope, - started = SharingStarted.WhileSubscribed(5_000L), initialValue = AutoBackupUiState(), ) @@ -103,9 +99,8 @@ class CalendarsViewModel @Inject constructor( if (!enabled) emptySet() else sources.filter { it.isManaged }.map { it.id }.toSet() } .flowOn(io) - .stateIn( + .stateWhileSubscribed( scope = viewModelScope, - started = SharingStarted.WhileSubscribed(5_000L), initialValue = emptySet(), ) diff --git a/app/src/main/java/de/jeanlucmakiola/calendula/ui/common/AccountGroups.kt b/app/src/main/java/de/jeanlucmakiola/calendula/ui/common/AccountGroups.kt index 7ec3dfdc..c92c1ce3 100644 --- a/app/src/main/java/de/jeanlucmakiola/calendula/ui/common/AccountGroups.kt +++ b/app/src/main/java/de/jeanlucmakiola/calendula/ui/common/AccountGroups.kt @@ -57,7 +57,7 @@ fun List.groupByAccount(): List { */ @Composable fun accountGroupTitle(group: CalendarAccountGroup): String { - val label = group.label.ifBlank { stringResource(R.string.calendar_unnamed) } + val label = group.label.orUnnamed() return if (!group.ambiguous) { label } else { diff --git a/app/src/main/java/de/jeanlucmakiola/calendula/ui/common/BlockPlacement.kt b/app/src/main/java/de/jeanlucmakiola/calendula/ui/common/BlockPlacement.kt index 923726ad..9ec316c1 100644 --- a/app/src/main/java/de/jeanlucmakiola/calendula/ui/common/BlockPlacement.kt +++ b/app/src/main/java/de/jeanlucmakiola/calendula/ui/common/BlockPlacement.kt @@ -278,12 +278,23 @@ data class BlockPlacement(val xFraction: Float, val widthFraction: Float, val y: * A pinch-zoom rewrites the hour height every pointer frame, and the gutter and * grid lines follow it instantly — so the tween stands down for the gesture * rather than leaving the blocks trailing the ruler they are measured against. + * A [landing] block, under a dropped copy, moves without the spring's bounce. */ @OptIn(ExperimentalMaterial3ExpressiveApi::class) @Composable -fun animatedBlockPlacement(xFraction: Float, widthFraction: Float, y: Dp, height: Dp): BlockPlacement { +fun animatedBlockPlacement( + xFraction: Float, + widthFraction: Float, + y: Dp, + height: Dp, + landing: Boolean = false, +): BlockPlacement { val still = rememberReduceMotion() || LocalTimelineZoom.current.isPinching - val dpSpec: FiniteAnimationSpec = if (still) snap() else MaterialTheme.motionScheme.fastSpatialSpec() + val dpSpec: FiniteAnimationSpec = when { + still -> snap() + landing -> MaterialTheme.motionScheme.fastEffectsSpec() + else -> MaterialTheme.motionScheme.fastSpatialSpec() + } val shareSpec: FiniteAnimationSpec = if (still) snap() else MaterialTheme.motionScheme.fastSpatialSpec() val animatedX by animateFloatAsState(xFraction, shareSpec, label = "block-x") val animatedWidth by animateFloatAsState(widthFraction, shareSpec, label = "block-width") diff --git a/app/src/main/java/de/jeanlucmakiola/calendula/ui/common/CalendarChrome.kt b/app/src/main/java/de/jeanlucmakiola/calendula/ui/common/CalendarChrome.kt index 173d29d2..56a3a1ab 100644 --- a/app/src/main/java/de/jeanlucmakiola/calendula/ui/common/CalendarChrome.kt +++ b/app/src/main/java/de/jeanlucmakiola/calendula/ui/common/CalendarChrome.kt @@ -1,5 +1,14 @@ package de.jeanlucmakiola.calendula.ui.common +import androidx.compose.animation.AnimatedContent +import androidx.compose.animation.AnimatedVisibility +import androidx.compose.animation.slideInVertically +import androidx.compose.animation.slideOutVertically +import androidx.compose.animation.togetherWith +import androidx.compose.animation.fadeIn +import androidx.compose.animation.fadeOut +import androidx.compose.animation.scaleIn +import androidx.compose.animation.scaleOut import androidx.compose.foundation.background import androidx.compose.foundation.layout.Box import androidx.compose.foundation.layout.PaddingValues @@ -16,6 +25,9 @@ import androidx.compose.material3.TopAppBarDefaults import androidx.compose.runtime.getValue import androidx.compose.runtime.setValue import androidx.compose.runtime.Composable +import androidx.compose.runtime.DisposableEffect +import androidx.compose.runtime.remember +import androidx.compose.runtime.rememberUpdatedState import androidx.compose.runtime.Immutable import androidx.compose.runtime.SideEffect import androidx.compose.runtime.Stable @@ -24,6 +36,7 @@ import androidx.compose.runtime.staticCompositionLocalOf import androidx.compose.ui.Modifier import androidx.compose.ui.res.stringResource import de.jeanlucmakiola.calendula.R +import de.jeanlucmakiola.calendula.domain.EventInstance import kotlinx.datetime.LocalDate /** @@ -53,12 +66,39 @@ class ScreenActions( val onCreate: () -> Unit, ) +/** + * An event a long press left selected (#141), which the host answers with the + * action bar in place of the FAB. [dismiss] clears it on the screen that owns it. + * [create] is set for a block drafted on an empty slot (#153), which has no + * event yet, so the bar offers to create one. + */ +@Stable +class EventSelection( + val event: EventInstance, + val dismiss: () -> Unit, + val create: (() -> Unit)? = null, + /** The event at the times an ongoing move or resize would give it, else null. */ + val preview: () -> EventInstance? = { null }, +) + /** The screen on show's [ScreenChrome] and [ScreenActions], for the host to draw. */ @Stable class ChromeHost { var chrome by mutableStateOf(null) private set + var selection by mutableStateOf(null) + internal set + + /** Whether the selected event is being dragged or resized right now. */ + var selectionBusy by mutableStateOf(false) + internal set + + /** Whether the bar would cover the selected event, and so draws compact. */ + var selectionCompact by mutableStateOf(false) + internal set + + var actions: ScreenActions? = null private set @@ -80,8 +120,54 @@ fun PublishChrome(chrome: ScreenChrome, actions: ScreenActions) { if (slot.current) SideEffect { slot.host.publish(chrome, actions) } } -/** The top bar every calendar screen shares. */ -@OptIn(ExperimentalMaterial3Api::class) +/** Hands the screen's selected [event] to the host, for as long as it stays selected. */ +@Composable +fun PublishSelection( + event: EventInstance?, + busy: Boolean, + compact: Boolean, + onDismiss: () -> Unit, + onCreate: (() -> Unit)? = null, + preview: () -> EventInstance? = { null }, +) { + val slot = LocalChromeSlot.current ?: return + val currentDismiss by rememberUpdatedState(onDismiss) + val currentCreate by rememberUpdatedState(onCreate) + val currentPreview by rememberUpdatedState(preview) + val drafted = onCreate != null + val selection = remember(event, drafted) { + event?.let { + EventSelection( + event = it, + dismiss = { currentDismiss() }, + create = if (drafted) ({ currentCreate?.invoke() }) else null, + preview = { currentPreview() }, + ) + } + } + val host = slot.host + val current = slot.current + DisposableEffect(host, selection, current) { + if (current) host.selection = selection + onDispose { + if (host.selection === selection) host.selection = null + // Left mid-drag, nothing else would clear these for the other views. + host.selectionBusy = false + host.selectionCompact = false + } + } + if (current) { + SideEffect { + host.selectionBusy = busy && selection != null + host.selectionCompact = compact && selection != null + } + } +} + +/** + * The top bar every calendar screen shares — or, while an event is selected, + * the selection's own bar in its place (#141). + */ @Composable fun CalendarTopBar( host: ChromeHost, @@ -91,6 +177,43 @@ fun CalendarTopBar( onOpenDrawer: () -> Unit, onOpenSearch: () -> Unit, showTodayButton: Boolean, +) { + val effects = MaterialTheme.motionScheme.fastEffectsSpec() + AnimatedContent( + targetState = host.selection, + contentKey = { it != null }, + transitionSpec = { + (fadeIn(effects) + slideInVertically { -it / 4 }) + .togetherWith(fadeOut(effects) + slideOutVertically { -it / 4 }) + }, + label = "top-bar", + ) { selection -> + if (selection != null) { + SelectionTopBar(selection) + } else { + ViewTopBar( + host = host, + selectedView = selectedView, + quickSwitchViews = quickSwitchViews, + onCycleView = onCycleView, + onOpenDrawer = onOpenDrawer, + onOpenSearch = onOpenSearch, + showTodayButton = showTodayButton, + ) + } + } +} + +@OptIn(ExperimentalMaterial3Api::class) +@Composable +private fun ViewTopBar( + host: ChromeHost, + selectedView: CalendarView, + quickSwitchViews: List, + onCycleView: () -> Unit, + onOpenDrawer: () -> Unit, + onOpenSearch: () -> Unit, + showTodayButton: Boolean, ) { val chrome = host.chrome TopAppBar( @@ -136,16 +259,26 @@ fun CalendarTopBar( ) } -/** The FAB column every calendar screen shares. */ +/** + * The FAB column every calendar screen shares. While an event is selected the + * FAB is [selection]'s toggle instead, and it steps aside mid-gesture. + */ @Composable -fun CalendarFab(host: ChromeHost, todayInToolbar: Boolean) { +fun CalendarFab(host: ChromeHost, todayInToolbar: Boolean, selection: FabSelection? = null) { val chrome = host.chrome ?: return - CalendarFabColumn( - todayVisible = chrome.awayFromToday && !todayInToolbar, - todayText = chrome.todayText, - onToday = { host.actions?.onToday?.invoke() }, - onCreate = { host.actions?.onCreate?.invoke() }, - ) + AnimatedVisibility( + visible = !host.selectionBusy, + enter = scaleIn(MaterialTheme.motionScheme.fastSpatialSpec()) + fadeIn(), + exit = scaleOut(MaterialTheme.motionScheme.fastSpatialSpec()) + fadeOut(), + ) { + CalendarFabColumn( + todayVisible = chrome.awayFromToday && !todayInToolbar, + todayText = chrome.todayText, + onToday = { host.actions?.onToday?.invoke() }, + onCreate = { host.actions?.onCreate?.invoke() }, + selection = selection, + ) + } } /** diff --git a/app/src/main/java/de/jeanlucmakiola/calendula/ui/common/CalendarColors.kt b/app/src/main/java/de/jeanlucmakiola/calendula/ui/common/CalendarColors.kt index b37b64ad..87122c4a 100644 --- a/app/src/main/java/de/jeanlucmakiola/calendula/ui/common/CalendarColors.kt +++ b/app/src/main/java/de/jeanlucmakiola/calendula/ui/common/CalendarColors.kt @@ -1,7 +1,6 @@ package de.jeanlucmakiola.calendula.ui.common import androidx.compose.foundation.background -import androidx.compose.foundation.isSystemInDarkTheme import androidx.compose.foundation.layout.Box import androidx.compose.foundation.layout.size import androidx.compose.foundation.shape.CircleShape @@ -14,6 +13,7 @@ import androidx.compose.ui.Alignment import androidx.compose.ui.Modifier import androidx.compose.ui.draw.clip import androidx.compose.ui.unit.dp +import de.jeanlucmakiola.floret.identity.LocalFloretDarkTheme /** * Leading avatar for a calendar: a neutral chip holding a calendar glyph tinted @@ -23,7 +23,7 @@ import androidx.compose.ui.unit.dp */ @Composable fun CalendarColorChip(color: Int, modifier: Modifier = Modifier) { - val dark = isSystemInDarkTheme() + val dark = LocalFloretDarkTheme.current val soften = LocalSoftenColors.current Box( modifier = modifier diff --git a/app/src/main/java/de/jeanlucmakiola/calendula/ui/common/CalendarFabColumn.kt b/app/src/main/java/de/jeanlucmakiola/calendula/ui/common/CalendarFabColumn.kt index bc686171..18a8fa64 100644 --- a/app/src/main/java/de/jeanlucmakiola/calendula/ui/common/CalendarFabColumn.kt +++ b/app/src/main/java/de/jeanlucmakiola/calendula/ui/common/CalendarFabColumn.kt @@ -1,11 +1,20 @@ package de.jeanlucmakiola.calendula.ui.common import androidx.compose.animation.AnimatedVisibility +import androidx.compose.animation.core.animateFloatAsState +import androidx.compose.animation.expandHorizontally +import androidx.compose.animation.fadeIn +import androidx.compose.animation.fadeOut import androidx.compose.animation.scaleIn import androidx.compose.animation.scaleOut +import androidx.compose.animation.shrinkHorizontally import androidx.compose.foundation.layout.Arrangement +import androidx.compose.foundation.layout.Box import androidx.compose.foundation.layout.Column +import androidx.compose.foundation.layout.Row +import androidx.compose.foundation.layout.height import androidx.compose.material.icons.Icons +import androidx.compose.material.icons.automirrored.filled.KeyboardArrowRight import androidx.compose.material.icons.filled.Add import androidx.compose.material.icons.filled.Refresh import androidx.compose.material3.ExperimentalMaterial3ExpressiveApi @@ -15,15 +24,36 @@ import androidx.compose.material3.Icon import androidx.compose.material3.MaterialTheme import androidx.compose.material3.Text import androidx.compose.runtime.Composable +import androidx.compose.runtime.Stable +import androidx.compose.runtime.getValue import androidx.compose.ui.Alignment +import androidx.compose.ui.Modifier +import androidx.compose.ui.graphics.graphicsLayer +import androidx.compose.ui.semantics.contentDescription +import androidx.compose.ui.semantics.semantics import androidx.compose.ui.res.stringResource import androidx.compose.ui.unit.dp import de.jeanlucmakiola.calendula.R +/** The standard FAB's size, shared by the selection bar that unrolls from it (#141). */ +val FabSize = 56.dp + +/** What the FAB is while an event is selected (#141): the toggle for its action bar. */ +@Stable +class FabSelection( + val expanded: Boolean, + val onToggle: () -> Unit, + val bar: @Composable () -> Unit, +) + + + /** * The FAB stack shared by the three calendar views: a persistent "+" to * create an event, with the jump-to-today pill appearing above it whenever - * the view isn't anchored on today. + * the view isn't anchored on today. While an event is selected the same FAB, + * in the same spot, opens and folds the selection's action bar, which unrolls + * from it towards the start. */ @OptIn(ExperimentalMaterial3ExpressiveApi::class) @Composable @@ -32,13 +62,14 @@ fun CalendarFabColumn( todayText: String, onToday: () -> Unit, onCreate: () -> Unit, + selection: FabSelection? = null, ) { Column( horizontalAlignment = Alignment.End, verticalArrangement = Arrangement.spacedBy(16.dp), ) { AnimatedVisibility( - visible = todayVisible, + visible = todayVisible && selection == null, enter = scaleIn(MaterialTheme.motionScheme.fastSpatialSpec()), exit = scaleOut(MaterialTheme.motionScheme.fastSpatialSpec()), ) { @@ -48,11 +79,70 @@ fun CalendarFabColumn( text = { Text(todayText) }, ) } - FloatingActionButton(onClick = onCreate) { - Icon( - imageVector = Icons.Default.Add, - contentDescription = stringResource(R.string.event_edit_new_title), + // Held past the selection clearing, so the bar has something to fold away. + val heldBar = rememberHeld(selection?.bar) + // Held at the FAB's height so the taller bar can't shift the FAB. + Row( + modifier = Modifier.height(FabSize), + verticalAlignment = Alignment.CenterVertically, + horizontalArrangement = Arrangement.spacedBy(8.dp), + ) { + AnimatedVisibility( + visible = selection?.expanded == true, + enter = expandHorizontally( + animationSpec = MaterialTheme.motionScheme.fastSpatialSpec(), + expandFrom = Alignment.End, + ) + fadeIn(), + exit = shrinkHorizontally( + animationSpec = MaterialTheme.motionScheme.fastSpatialSpec(), + shrinkTowards = Alignment.End, + ) + fadeOut(), + ) { + heldBar?.invoke() + } + val label = stringResource( + when { + selection == null -> R.string.event_edit_new_title + selection.expanded -> R.string.event_selection_hide + else -> R.string.event_selection_actions + }, ) + FloatingActionButton( + onClick = selection?.onToggle ?: onCreate, + modifier = Modifier.semantics { contentDescription = label }, + ) { + FabGlyph(selecting = selection != null, expanded = selection?.expanded == true) + } } } } + +/** "+", or with an event selected a chevron that turns to open and fold the bar. */ +@Composable +private fun FabGlyph(selecting: Boolean, expanded: Boolean) { + val spatial = MaterialTheme.motionScheme.fastSpatialSpec() + val swap by animateFloatAsState(if (selecting) 1f else 0f, spatial, label = "fab-swap") + val turn by animateFloatAsState(if (expanded) 0f else 180f, spatial, label = "fab-turn") + Box(contentAlignment = Alignment.Center) { + Icon( + imageVector = Icons.Default.Add, + contentDescription = null, + modifier = Modifier.graphicsLayer { + rotationZ = 90f * swap + scaleX = 1f - 0.5f * swap + scaleY = 1f - 0.5f * swap + alpha = (1f - swap).coerceIn(0f, 1f) + }, + ) + Icon( + imageVector = Icons.AutoMirrored.Filled.KeyboardArrowRight, + contentDescription = null, + modifier = Modifier.graphicsLayer { + rotationZ = turn - 90f * (1f - swap) + scaleX = 0.5f + 0.5f * swap + scaleY = 0.5f + 0.5f * swap + alpha = swap.coerceIn(0f, 1f) + }, + ) + } +} diff --git a/app/src/main/java/de/jeanlucmakiola/calendula/ui/common/CalendarPickerGroups.kt b/app/src/main/java/de/jeanlucmakiola/calendula/ui/common/CalendarPickerGroups.kt index 802bbb8e..af5c46df 100644 --- a/app/src/main/java/de/jeanlucmakiola/calendula/ui/common/CalendarPickerGroups.kt +++ b/app/src/main/java/de/jeanlucmakiola/calendula/ui/common/CalendarPickerGroups.kt @@ -34,7 +34,6 @@ import de.jeanlucmakiola.calendula.R import de.jeanlucmakiola.calendula.domain.CalendarSource import de.jeanlucmakiola.floret.components.GroupedRow import de.jeanlucmakiola.floret.components.Position -import de.jeanlucmakiola.floret.components.SelectedCheck /** * The app's single "which calendar" selection list, shared by the event editor @@ -114,17 +113,11 @@ private fun CalendarPickerGroup( leading = leading, ) calendars.forEachIndexed { index, calendar -> - val isSelected = calendar.id == selectedId GroupedRow( - title = calendar.displayName.ifBlank { stringResource(R.string.calendar_unnamed) }, + title = calendar.displayName.orUnnamed(), position = if (index == calendars.lastIndex) Position.Bottom else Position.Middle, - selected = isSelected, + checked = calendar.id == selectedId, leading = { CalendarColorChip(calendar.color) }, - trailing = if (isSelected) { - { SelectedCheck() } - } else { - null - }, onClick = { onSelect(calendar.id) }, ) } diff --git a/app/src/main/java/de/jeanlucmakiola/calendula/ui/common/CalendarText.kt b/app/src/main/java/de/jeanlucmakiola/calendula/ui/common/CalendarText.kt index cec15809..bbf01f26 100644 --- a/app/src/main/java/de/jeanlucmakiola/calendula/ui/common/CalendarText.kt +++ b/app/src/main/java/de/jeanlucmakiola/calendula/ui/common/CalendarText.kt @@ -3,10 +3,12 @@ package de.jeanlucmakiola.calendula.ui.common import androidx.compose.runtime.Composable import androidx.compose.runtime.remember import androidx.compose.ui.platform.LocalDensity +import androidx.compose.ui.res.stringResource import androidx.compose.ui.text.TextStyle import androidx.compose.ui.text.rememberTextMeasurer import androidx.compose.ui.text.style.LineHeightStyle import androidx.compose.ui.unit.Dp +import de.jeanlucmakiola.calendula.R /** * The calendar surfaces' line-height treatment. Material wraps an 11sp glyph in @@ -55,3 +57,7 @@ fun rememberTrimmedLineHeight(style: TextStyle): Dp { with(density) { measurer.measure(LINE_SAMPLE, style.trimmedLines()).size.height.toDp() } } } + +/** A calendar or account name, or the "unnamed" label when it is blank. */ +@Composable +fun String.orUnnamed(): String = ifBlank { stringResource(R.string.calendar_unnamed) } diff --git a/app/src/main/java/de/jeanlucmakiola/calendula/ui/common/CalendarVisibilitySwitch.kt b/app/src/main/java/de/jeanlucmakiola/calendula/ui/common/CalendarVisibilitySwitch.kt new file mode 100644 index 00000000..ca213600 --- /dev/null +++ b/app/src/main/java/de/jeanlucmakiola/calendula/ui/common/CalendarVisibilitySwitch.kt @@ -0,0 +1,24 @@ +package de.jeanlucmakiola.calendula.ui.common + +import androidx.compose.material3.Switch +import androidx.compose.runtime.Composable +import androidx.compose.ui.Modifier +import androidx.compose.ui.res.stringResource +import androidx.compose.ui.semantics.contentDescription +import androidx.compose.ui.semantics.semantics +import de.jeanlucmakiola.calendula.R + +/** The per-row switch writing the device's own `Calendars.VISIBLE`, as Settings does (#75). */ +@Composable +fun CalendarVisibilitySwitch( + calendarName: String, + enabled: Boolean, + onToggle: (Boolean) -> Unit, +) { + val label = stringResource(R.string.calendars_visibility_a11y, calendarName) + Switch( + checked = enabled, + onCheckedChange = onToggle, + modifier = Modifier.semantics { contentDescription = label }, + ) +} diff --git a/app/src/main/java/de/jeanlucmakiola/calendula/ui/common/CopyToClipboard.kt b/app/src/main/java/de/jeanlucmakiola/calendula/ui/common/CopyToClipboard.kt index f8920c57..8163de64 100644 --- a/app/src/main/java/de/jeanlucmakiola/calendula/ui/common/CopyToClipboard.kt +++ b/app/src/main/java/de/jeanlucmakiola/calendula/ui/common/CopyToClipboard.kt @@ -2,14 +2,16 @@ package de.jeanlucmakiola.calendula.ui.common import android.content.ClipData import android.os.Build -import androidx.compose.foundation.combinedClickable -import androidx.compose.foundation.gestures.detectTapGestures +import androidx.compose.foundation.clickable +import androidx.compose.foundation.gestures.awaitEachGesture +import androidx.compose.foundation.gestures.awaitFirstDown import androidx.compose.material3.SnackbarHostState import androidx.compose.runtime.Composable import androidx.compose.runtime.remember import androidx.compose.runtime.rememberCoroutineScope import androidx.compose.ui.Modifier import androidx.compose.ui.hapticfeedback.HapticFeedbackType +import androidx.compose.ui.input.pointer.PointerEventPass import androidx.compose.ui.input.pointer.pointerInput import androidx.compose.ui.platform.ClipEntry import androidx.compose.ui.platform.LocalClipboard @@ -67,9 +69,12 @@ fun rememberFieldCopier(snackbarHostState: SnackbarHostState): FieldCopier { * * [onTap] carries a field's existing tap action through, announced as * [onTapLabel]; a field without one stays unclickable rather than growing a - * ripple that leads nowhere, and gets its long press announced through semantics instead. That branch merges the - * node it sits on, so a screen reader lands on the field itself and finds the - * action there — a bare container is never focused. + * ripple that leads nowhere. The long press is announced through semantics, + * merging the node it sits on, so a screen reader lands on the field itself + * and finds the action there — a bare container is never focused. + * + * The press is caught ahead of the field's children, so a long press on a + * link inside the text copies too instead of leaving that stretch dead. */ @Composable fun Modifier.copyOnLongPress( @@ -80,27 +85,45 @@ fun Modifier.copyOnLongPress( onTapLabel: String? = null, ): Modifier { val actionLabel = stringResource(R.string.field_copy_action) - return if (onTap != null) { - combinedClickable( - onClick = onTap, - onClickLabel = onTapLabel, - onLongClickLabel = actionLabel, - onLongClick = { copy(label, text) }, - ) - } else { - val haptics = LocalHapticFeedback.current - pointerInput(label, text, copy) { - detectTapGestures( - onLongPress = { - haptics.performHapticFeedback(HapticFeedbackType.LongPress) - copy(label, text) - }, - ) - }.semantics(mergeDescendants = true) { + val haptics = LocalHapticFeedback.current + return longPressAheadOfChildren(label, text, copy) { + haptics.performHapticFeedback(HapticFeedbackType.LongPress) + copy(label, text) + } + .then(if (onTap != null) Modifier.clickable(onClickLabel = onTapLabel, onClick = onTap) else Modifier) + .semantics(mergeDescendants = true) { onLongClick(actionLabel) { copy(label, text) true } } - } } + +/** + * Run [onLongPress] once a press has held still for the long-press timeout, + * watching on the initial pass — before the children see the events — and + * then swallow the rest of that press, so neither a link under the finger nor + * a tap handler fires on release. + */ +private fun Modifier.longPressAheadOfChildren(vararg keys: Any?, onLongPress: () -> Unit): Modifier = + pointerInput(*keys) { + awaitEachGesture { + val down = awaitFirstDown(requireUnconsumed = false, pass = PointerEventPass.Initial) + val endedEarly = withTimeoutOrNull(viewConfiguration.longPressTimeoutMillis) { + while (true) { + val change = awaitPointerEvent(PointerEventPass.Initial).changes + .firstOrNull { it.id == down.id } + val moved = change != null && + (change.position - down.position).getDistance() > viewConfiguration.touchSlop + if (change == null || !change.pressed || moved) break + } + true + } + if (endedEarly != null) return@awaitEachGesture + onLongPress() + do { + val event = awaitPointerEvent(PointerEventPass.Initial) + event.changes.forEach { it.consume() } + } while (event.changes.any { it.pressed }) + } + } diff --git a/app/src/main/java/de/jeanlucmakiola/calendula/ui/common/DayRange.kt b/app/src/main/java/de/jeanlucmakiola/calendula/ui/common/DayRange.kt new file mode 100644 index 00000000..27ea2d0f --- /dev/null +++ b/app/src/main/java/de/jeanlucmakiola/calendula/ui/common/DayRange.kt @@ -0,0 +1,22 @@ +package de.jeanlucmakiola.calendula.ui.common + +import kotlinx.datetime.DateTimeUnit +import kotlinx.datetime.DayOfWeek +import kotlinx.datetime.LocalDate +import kotlinx.datetime.TimeZone +import kotlinx.datetime.atStartOfDayIn +import kotlinx.datetime.atTime +import kotlinx.datetime.minus +import kotlinx.datetime.toInstant +import kotlin.time.Instant + +/** Instant range from the start of [first] through the last second of [last] in [zone]. */ +internal fun dayRange(first: LocalDate, last: LocalDate, zone: TimeZone): ClosedRange = + first.atStartOfDayIn(zone)..last.atTime(23, 59, 59).toInstant(zone) + +/** Beginning of the week (at [weekStart]) that contains this date. */ +internal fun LocalDate.startOfWeek(weekStart: DayOfWeek): LocalDate { + // DayOfWeek.ordinal: MONDAY=0..SUNDAY=6 → identical to ISO ordering. + val offset = ((dayOfWeek.ordinal - weekStart.ordinal) + 7) % 7 + return minus(offset, DateTimeUnit.DAY) +} diff --git a/app/src/main/java/de/jeanlucmakiola/calendula/ui/common/EventActions.kt b/app/src/main/java/de/jeanlucmakiola/calendula/ui/common/EventActions.kt new file mode 100644 index 00000000..43de3e10 --- /dev/null +++ b/app/src/main/java/de/jeanlucmakiola/calendula/ui/common/EventActions.kt @@ -0,0 +1,201 @@ +package de.jeanlucmakiola.calendula.ui.common + +import android.Manifest +import android.content.Context +import android.content.Intent +import android.net.Uri +import android.util.Log +import androidx.activity.compose.rememberLauncherForActivityResult +import androidx.activity.result.contract.ActivityResultContracts +import androidx.compose.foundation.layout.Arrangement +import androidx.compose.foundation.layout.Column +import androidx.compose.material3.AlertDialog +import androidx.compose.material3.MaterialTheme +import androidx.compose.material3.Text +import androidx.compose.material3.TextButton +import androidx.compose.runtime.Composable +import androidx.compose.runtime.getValue +import androidx.compose.runtime.mutableStateOf +import androidx.compose.runtime.remember +import androidx.compose.runtime.rememberUpdatedState +import androidx.compose.runtime.saveable.rememberSaveable +import androidx.compose.runtime.setValue +import androidx.compose.ui.platform.LocalContext +import androidx.compose.ui.res.stringResource +import androidx.compose.ui.unit.dp +import de.jeanlucmakiola.calendula.R +import de.jeanlucmakiola.calendula.data.calendar.CalendarRepository +import de.jeanlucmakiola.calendula.data.calendar.NoSuchEventException +import de.jeanlucmakiola.calendula.data.ics.IcsExporter +import de.jeanlucmakiola.calendula.domain.EventDetail +import de.jeanlucmakiola.calendula.domain.RecurringWriteScope +import de.jeanlucmakiola.calendula.domain.ics.IcsWriter +import de.jeanlucmakiola.calendula.domain.ics.toShareIcsEvent +import de.jeanlucmakiola.floret.android.hasPermission +import de.jeanlucmakiola.floret.components.OptionCard +import kotlin.coroutines.cancellation.CancellationException +import kotlin.time.Clock + +/** + * Serialise [detail] to a cache `.ics` and return a shareable content Uri for an + * `ACTION_SEND`, or null when the write fails. Exported as a one-off (see + * [toShareIcsEvent]). Blocking — call it off the main thread. + */ +fun IcsExporter.stageEventShare(detail: EventDetail): Uri? = runCatching { + val ics = IcsWriter().writeCalendar( + events = listOf(detail.toShareIcsEvent()), + dtStamp = Clock.System.now(), + ) + stageShareFile(shareFileName(detail.instance.title), ics) +}.getOrNull() + +/** Open the system chooser for a staged `.ics`; false when nothing could take it. */ +fun Context.sendEventShare(uri: Uri, chooserTitle: String): Boolean = runCatching { + val send = Intent(Intent.ACTION_SEND).apply { + type = "text/calendar" + putExtra(Intent.EXTRA_STREAM, uri) + addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION) + } + startActivity(Intent.createChooser(send, chooserTitle)) +}.isSuccess + +/** Delete an event, or as much of its series as [scope] reaches from the occurrence at [beginMillis]. */ +suspend fun CalendarRepository.deleteEvent( + eventId: Long, + beginMillis: Long, + scope: RecurringWriteScope, +) = when (scope) { + RecurringWriteScope.AllEvents -> deleteEvent(eventId) + RecurringWriteScope.ThisEvent -> deleteOccurrence(eventId, beginMillis) + RecurringWriteScope.ThisAndFollowing -> deleteEventFromOccurrence(eventId, beginMillis) +} + +/** How a [tryDeleteEvent] ended. */ +enum class DeleteOutcome { Deleted, Gone, NeedsPermission, Failed } + +/** Whether this install may read the calendar at all. */ +fun Context.canReadCalendar(): Boolean = + hasPermission(Manifest.permission.READ_CALENDAR) + +/** Whether this install may write to the calendar; v1.0 installs only hold read access. */ +fun Context.canWriteCalendar(): Boolean = + hasPermission(Manifest.permission.WRITE_CALENDAR) + +/** [deleteEvent], with the provider's failures mapped to a [DeleteOutcome]. */ +suspend fun CalendarRepository.tryDeleteEvent( + eventId: Long, + beginMillis: Long, + scope: RecurringWriteScope, +): DeleteOutcome = try { + deleteEvent(eventId, beginMillis, scope) + DeleteOutcome.Deleted +} catch (e: CancellationException) { + throw e +} catch (e: SecurityException) { + DeleteOutcome.NeedsPermission +} catch (e: NoSuchEventException) { + DeleteOutcome.Gone +} catch (e: Exception) { + Log.w("EventActions", "Delete failed (scope=$scope, eventId=$eventId)", e) + DeleteOutcome.Failed +} + +/** + * [action], which writes to the calendar, as a handler that asks for + * `WRITE_CALENDAR` first where the install only holds read access (v1.0 + * installs). A grant continues into [action], also when it returns after a + * rotation; a refusal runs [onDenied]. + */ +@Composable +fun rememberWriteAction(onDenied: () -> Unit = {}, action: () -> Unit): () -> Unit { + val context = LocalContext.current + val currentAction by rememberUpdatedState(action) + val currentDenied by rememberUpdatedState(onDenied) + val launcher = rememberLauncherForActivityResult( + contract = ActivityResultContracts.RequestPermission(), + ) { granted -> + if (granted) currentAction() else currentDenied() + } + return remember(context, launcher) { + { + if (context.canWriteCalendar()) { + currentAction() + } else { + launcher.launch(Manifest.permission.WRITE_CALENDAR) + } + } + } +} + +/** + * Delete confirmation. Recurring events choose between cancelling just the + * tapped occurrence (default), truncating the series from it onwards, and + * removing the whole series. + */ +@Composable +fun DeleteEventDialog( + isRecurring: Boolean, + onConfirm: (RecurringWriteScope) -> Unit, + onDismiss: () -> Unit, +) { + var scope by rememberSaveable { mutableStateOf(RecurringWriteScope.ThisEvent) } + AlertDialog( + onDismissRequest = onDismiss, + title = { + Text( + stringResource( + if (isRecurring) R.string.event_delete_recurring_title + else R.string.event_delete_title, + ), + ) + }, + text = { + if (isRecurring) { + Column(verticalArrangement = Arrangement.spacedBy(8.dp)) { + OptionCard( + label = stringResource(R.string.event_delete_option_occurrence), + onClick = { scope = RecurringWriteScope.ThisEvent }, + selected = scope == RecurringWriteScope.ThisEvent, + ) + OptionCard( + label = stringResource(R.string.event_delete_option_following), + onClick = { scope = RecurringWriteScope.ThisAndFollowing }, + selected = scope == RecurringWriteScope.ThisAndFollowing, + ) + OptionCard( + label = stringResource(R.string.event_delete_option_series), + onClick = { scope = RecurringWriteScope.AllEvents }, + selected = scope == RecurringWriteScope.AllEvents, + ) + } + } else { + Text(stringResource(R.string.event_delete_body)) + } + }, + confirmButton = { + TextButton( + onClick = { onConfirm(if (isRecurring) scope else RecurringWriteScope.AllEvents) }, + ) { + Text( + text = stringResource(R.string.event_detail_delete), + color = MaterialTheme.colorScheme.error, + ) + } + }, + dismissButton = { + TextButton(onClick = onDismiss) { + Text(stringResource(R.string.dialog_cancel)) + } + }, + ) +} + +/** A filesystem-safe `.ics` file name from an event title (or a fallback). */ +private fun shareFileName(title: String): String { + val base = title.trim() + .replace(Regex("""[^\p{L}\p{Nd} _-]"""), "") + .replace(' ', '_') + .take(40) + .ifBlank { "event" } + return "$base.ics" +} diff --git a/app/src/main/java/de/jeanlucmakiola/calendula/ui/common/EventActionsViewModel.kt b/app/src/main/java/de/jeanlucmakiola/calendula/ui/common/EventActionsViewModel.kt new file mode 100644 index 00000000..333c25de --- /dev/null +++ b/app/src/main/java/de/jeanlucmakiola/calendula/ui/common/EventActionsViewModel.kt @@ -0,0 +1,138 @@ +package de.jeanlucmakiola.calendula.ui.common + +import android.net.Uri +import androidx.lifecycle.ViewModel +import androidx.lifecycle.viewModelScope +import dagger.hilt.android.lifecycle.HiltViewModel +import de.jeanlucmakiola.calendula.data.calendar.CalendarRepository +import de.jeanlucmakiola.calendula.data.calendar.NoSuchEventException +import de.jeanlucmakiola.calendula.data.ics.IcsExporter +import de.jeanlucmakiola.calendula.data.time.ZoneSource +import de.jeanlucmakiola.calendula.domain.CalendarSource +import de.jeanlucmakiola.calendula.domain.EventDetail +import de.jeanlucmakiola.calendula.domain.EventForm +import de.jeanlucmakiola.calendula.domain.EventInstance +import de.jeanlucmakiola.calendula.domain.RecurringWriteScope +import de.jeanlucmakiola.calendula.domain.atOccurrence +import de.jeanlucmakiola.calendula.domain.toDuplicateForm +import de.jeanlucmakiola.floret.android.stateWhileSubscribed +import de.jeanlucmakiola.floret.di.IoDispatcher +import kotlinx.coroutines.CoroutineDispatcher +import kotlinx.coroutines.flow.MutableStateFlow +import kotlinx.coroutines.flow.StateFlow +import kotlinx.coroutines.flow.asStateFlow +import kotlinx.coroutines.flow.catch +import kotlinx.coroutines.flow.first +import kotlinx.coroutines.flow.flowOn +import kotlinx.coroutines.flow.map +import kotlinx.coroutines.launch +import kotlinx.coroutines.withContext +import kotlin.coroutines.cancellation.CancellationException +import javax.inject.Inject + +/** A delete waiting on its confirmation dialog. */ +data class DeletePrompt(val event: EventInstance, val isRecurring: Boolean) + +/** How an action on a selected event ended, when it has something to say. */ +enum class EventActionFailure { LoadFailed, ShareFailed, DeleteFailed, WriteDenied, Gone } + +/** Duplicate, share and delete for a selected event (#141), loading it on demand. */ +@HiltViewModel +class EventActionsViewModel @Inject constructor( + private val repository: CalendarRepository, + private val icsExporter: IcsExporter, + @IoDispatcher private val io: CoroutineDispatcher, + private val zoneSource: ZoneSource, +) : ViewModel() { + + /** Every calendar by id, for what a selected event's bar may offer. */ + val calendars: StateFlow> = repository.calendars() + .map { list -> list.associateBy { it.id } } + .catch { emit(emptyMap()) } + .flowOn(io) + .stateWhileSubscribed( + scope = viewModelScope, + initialValue = emptyMap(), + ) + + private val _deletePrompt = MutableStateFlow(null) + val deletePrompt: StateFlow = _deletePrompt.asStateFlow() + + private val _failure = MutableStateFlow(null) + val failure: StateFlow = _failure.asStateFlow() + + /** A create form copying [event], or null when it can't be read. */ + suspend fun duplicateForm(event: EventInstance): EventForm? { + val detail = load(event) ?: return null + val canModify = calendars.value[event.calendarId]?.canModifyContents == true + return detail.toDuplicateForm(canModify, zoneSource.current()) + } + + /** A staged `.ics` for [event], or null — reported — when it can't be built. */ + suspend fun shareUri(event: EventInstance): Uri? { + val uri = load(event)?.let { withContext(io) { icsExporter.stageEventShare(it) } } + if (uri == null && _failure.value == null) _failure.value = EventActionFailure.ShareFailed + return uri + } + + /** Ask to delete [event]; the dialog it needs depends on whether it recurs. */ + fun requestDelete(event: EventInstance) { + viewModelScope.launch { + val detail = load(event) ?: return@launch + _deletePrompt.value = DeletePrompt(event, isRecurring = !detail.rrule.isNullOrBlank()) + } + } + + fun confirmDelete(scope: RecurringWriteScope) { + val prompt = _deletePrompt.value ?: return + _deletePrompt.value = null + viewModelScope.launch { + val event = prompt.event + _failure.value = when (repository.tryDeleteEvent(event.eventId, event.start.toEpochMilliseconds(), scope)) { + DeleteOutcome.Deleted -> null + DeleteOutcome.Gone -> EventActionFailure.Gone + DeleteOutcome.NeedsPermission -> EventActionFailure.WriteDenied + DeleteOutcome.Failed -> EventActionFailure.DeleteFailed + } + } + } + + fun cancelDelete() { + _deletePrompt.value = null + } + + /** The chooser itself couldn't open — nothing on the device takes an `.ics`. */ + fun reportShareFailed() { + _failure.value = EventActionFailure.ShareFailed + } + + fun consumeFailure() { + _failure.value = null + } + + /** Whether [calendarId] takes writes, asking the provider while [calendars] hasn't loaded yet. */ + suspend fun canModify(calendarId: Long): Boolean { + val calendar = calendars.value[calendarId] ?: try { + repository.calendars().first().firstOrNull { it.id == calendarId } + } catch (e: CancellationException) { + throw e + } catch (e: Exception) { + null + } + return calendar?.canModifyContents == true + } + + private suspend fun load(event: EventInstance): EventDetail? = try { + // The row holds the series start; the actions work on this occurrence. + repository.eventDetail(event.eventId) + .atOccurrence(event.start.toEpochMilliseconds(), event.end.toEpochMilliseconds()) + } catch (e: CancellationException) { + throw e + } catch (e: NoSuchEventException) { + _failure.value = EventActionFailure.Gone + null + } catch (e: Exception) { + _failure.value = EventActionFailure.LoadFailed + null + } +} diff --git a/app/src/main/java/de/jeanlucmakiola/calendula/ui/common/EventDrag.kt b/app/src/main/java/de/jeanlucmakiola/calendula/ui/common/EventDrag.kt index 12bf70f7..5b786f9c 100644 --- a/app/src/main/java/de/jeanlucmakiola/calendula/ui/common/EventDrag.kt +++ b/app/src/main/java/de/jeanlucmakiola/calendula/ui/common/EventDrag.kt @@ -24,38 +24,57 @@ import androidx.compose.ui.unit.dp /** How far the finger may wander during the hold — well under touch slop. */ private val PICKUP_TOLERANCE = 6.dp +/** What a long press on a block turned into. */ +enum class PickUp { + /** Nothing to pick up; the gesture is left alone. */ + None, + + /** Lifted and following the finger. */ + Drag, + + /** Held but not movable — the gesture is swallowed until the finger lifts. */ + Hold, +} + /** * Pick an event block up with a long press and drag it, without * `detectDragGesturesAfterLongPress`: the stock detector cancels as soon as an * ancestor consumes or the finger leaves the block, which a * `MIN_EVENT_FRACTION`-tall block loses immediately. Movement before the timeout * is deliberately not consumed, so a scroll starting on top of a block survives. + * + * [onRelease] is the long press that never moved: the finger lifted within touch + * slop of where it was picked up, or a [PickUp.Hold] ended. Without it, such a + * release is a drop like any other. [immediate] also lifts the block as soon as + * the finger moves past touch slop, with no hold — for a block already selected. */ @Composable fun rememberEventDragSource( enabled: Boolean, key: Any?, - onPickUp: (pointerInRoot: Offset, blockInRoot: Offset, size: IntSize) -> Unit, + onPickUp: (pointerInRoot: Offset, blockInRoot: Offset, size: IntSize) -> PickUp, onMove: (pointerInRoot: Offset) -> Unit, onDrop: () -> Unit, onCancel: () -> Unit, -): Modifier = rememberDragSurface( + onRelease: (() -> Unit)? = null, + immediate: Boolean = false, +): Modifier = rememberPickUpSurface( enabled = enabled, key = key, - onPickUp = { _, pointerInRoot, nodeInRoot, size -> - onPickUp(pointerInRoot, nodeInRoot, size) - true - }, + immediate = immediate, + onPickUp = { _, pointerInRoot, nodeInRoot, size -> onPickUp(pointerInRoot, nodeInRoot, size) }, onMove = onMove, onDrop = onDrop, onCancel = onCancel, + onRelease = onRelease, ) /** * The same pickup, for a surface that carries many draggable pieces rather than * being one itself — the month grid, whose chips are covered by a full-bleed tap * layer. [onPickUp] receives the press position local to this node and answers - * whether anything is there; false abandons the gesture. + * whether anything is there; false abandons the gesture. [skipClaimedDown] leaves + * a press a descendant already consumed alone. */ @Composable fun rememberDragSurface( @@ -65,6 +84,33 @@ fun rememberDragSurface( onMove: (pointerInRoot: Offset) -> Unit, onDrop: () -> Unit, onCancel: () -> Unit, + onRelease: (() -> Unit)? = null, + skipClaimedDown: Boolean = false, +): Modifier = rememberPickUpSurface( + enabled = enabled, + key = key, + immediate = false, + onPickUp = { local, pointer, node, size -> + if (onPickUp(local, pointer, node, size)) PickUp.Drag else PickUp.None + }, + onMove = onMove, + onDrop = onDrop, + onCancel = onCancel, + onRelease = onRelease, + skipClaimedDown = skipClaimedDown, +) + +@Composable +private fun rememberPickUpSurface( + enabled: Boolean, + key: Any?, + immediate: Boolean, + onPickUp: (local: Offset, pointerInRoot: Offset, nodeInRoot: Offset, size: IntSize) -> PickUp, + onMove: (pointerInRoot: Offset) -> Unit, + onDrop: () -> Unit, + onCancel: () -> Unit, + onRelease: (() -> Unit)?, + skipClaimedDown: Boolean = false, ): Modifier { if (!enabled) return Modifier val holdMillis = LocalViewConfiguration.current.longPressTimeoutMillis @@ -74,27 +120,44 @@ fun rememberDragSurface( val currentMove by rememberUpdatedState(onMove) val currentDrop by rememberUpdatedState(onDrop) val currentCancel by rememberUpdatedState(onCancel) + val currentRelease by rememberUpdatedState(onRelease) + // Not a key: the pickup changes it, and a restart would cancel the drag. + val currentImmediate by rememberUpdatedState(immediate) return Modifier .onGloballyPositioned { coordinates[0] = it } .pointerInput(key) { + val slop = viewConfiguration.touchSlop awaitEachGesture { val down = awaitFirstDown(requireUnconsumed = false) + // A child that took the press, such as a resize handle, keeps it. + if (skipClaimedDown && down.isConsumed) return@awaitEachGesture val origin = down.position - val heldStill = withTimeoutOrNull(holdMillis) { - while (true) { + val immediate = currentImmediate + // Null: held still. True: an immediate pickup past slop. False: abandoned. + val outcome = withTimeoutOrNull(holdMillis) { + var result: Boolean? = null + while (result == null) { val main = awaitPointerEvent() - val change = main.changes.firstOrNull { it.id == down.id } ?: break - if (!change.pressed) break - if (main.changes.count { it.pressed } > 1) break - if ((change.position - origin).getDistance() > tolerance) break - // An ancestor's claim only becomes visible once the whole - // main pass has run, so look again on the final pass. - val final = awaitPointerEvent(PointerEventPass.Final) - if (final.changes.any { it.isConsumed }) break + val change = main.changes.firstOrNull { it.id == down.id } + val distance = change?.let { (it.position - origin).getDistance() } ?: 0f + result = when { + change == null || !change.pressed -> false + main.changes.count { it.pressed } > 1 -> false + immediate && distance > slop && !change.isConsumed -> { + change.consume() + true + } + !immediate && distance > tolerance -> false + // An ancestor's claim only becomes visible once the + // whole main pass has run, so look again on the final pass. + awaitPointerEvent(PointerEventPass.Final).changes.any { it.isConsumed } -> false + else -> null + } } - } == null - if (!heldStill) return@awaitEachGesture + result + } + if (outcome == false) return@awaitEachGesture val layout = coordinates[0]?.takeIf { it.isAttached } ?: return@awaitEachGesture val took = currentPickUp( @@ -103,8 +166,11 @@ fun rememberDragSurface( layout.positionInRoot(), layout.size, ) - if (!took) return@awaitEachGesture + if (took == PickUp.None) return@awaitEachGesture + // Moved already, for an immediate pickup: it can't be a release. + var moved = outcome == true var dropped = false + var released = false try { // Driven on the initial pass, which runs parent → child: an // ancestor that outranks us (the pinch) has already consumed @@ -116,28 +182,51 @@ fun rememberDragSurface( if (change.isConsumed) break if (!change.pressed) { change.consume() - dropped = true + if (took == PickUp.Hold || (!moved && currentRelease != null)) { + released = true + } else { + dropped = true + } break } if (event.changes.count { it.pressed } > 1) break change.consume() + if (took == PickUp.Hold) continue + if ((change.position - origin).getDistance() > slop) moved = true coordinates[0]?.takeIf { it.isAttached } ?.let { currentMove(it.localToRoot(change.position)) } } } finally { // Also reached when the pointer node is disposed mid-drag — // a cancel, not a drop, and must never write. - if (dropped) currentDrop() else currentCancel() + when { + released -> { + if (took == PickUp.Drag) currentCancel() + currentRelease?.invoke() + } + dropped -> currentDrop() + took == PickUp.Drag -> currentCancel() + } } } } } -/** A lift on pickup, then a tick every time the drop target snaps to a new slot. */ +/** + * A lift on pickup, a tick every time the drop target snaps to a new slot, and a + * confirm each time [drops] counts a real drop. + */ @Composable -fun DragSnapHaptics(slot: Any?) { +fun DragSnapHaptics(slot: Any?, drops: Int) { val haptics = LocalHapticFeedback.current val previous = remember { arrayOfNulls(1) } + val dropsSeen = remember { intArrayOf(drops) } + LaunchedEffect(drops) { + if (drops != dropsSeen[0]) { + dropsSeen[0] = drops + haptics.performHapticFeedback(HapticFeedbackType.Confirm) + } + } LaunchedEffect(slot) { val had = previous[0] previous[0] = slot diff --git a/app/src/main/java/de/jeanlucmakiola/calendula/ui/common/EventMoveHost.kt b/app/src/main/java/de/jeanlucmakiola/calendula/ui/common/EventMoveHost.kt index 2bed9342..abf39782 100644 --- a/app/src/main/java/de/jeanlucmakiola/calendula/ui/common/EventMoveHost.kt +++ b/app/src/main/java/de/jeanlucmakiola/calendula/ui/common/EventMoveHost.kt @@ -48,7 +48,12 @@ private val FAB_BAND = 88.dp * a pill on the FAB's band, leaving the calendar visible behind it. */ @Composable -fun EventMoveHost(viewModel: RescheduleViewModel, modifier: Modifier = Modifier) { +fun EventMoveHost( + viewModel: RescheduleViewModel, + modifier: Modifier = Modifier, + actionFailure: String? = null, + onActionFailureShown: () -> Unit = {}, +) { val prompt by viewModel.scopePrompt.collectAsStateWithLifecycle() val outcome by viewModel.outcome.collectAsStateWithLifecycle() val undoTick by viewModel.undoStarted.collectAsStateWithLifecycle() @@ -58,7 +63,9 @@ fun EventMoveHost(viewModel: RescheduleViewModel, modifier: Modifier = Modifier) prompt?.let { pending -> RecurringScopeDialog( - title = stringResource(R.string.event_move_recurring_title), + title = stringResource( + if (pending.resize) R.string.event_resize_recurring_title else R.string.event_move_recurring_title, + ), onSelect = viewModel::moveWithScope, onDismiss = viewModel::cancelScope, allowSeries = !pending.occurrenceOnly, @@ -69,9 +76,17 @@ fun EventMoveHost(viewModel: RescheduleViewModel, modifier: Modifier = Modifier) val moved = outcome as? MoveOutcome.Moved val movedLabel = moved?.let { formatMovedTo(it.startMillis, it.isAllDay, use24Hour, locale) } + val resizedLabel = moved?.endMillis?.let { end -> + "$movedLabel–${formatTime(end, use24Hour, locale)}" + } + // A failed selection action (#141) shares the chip rather than stacking on it. val message = when (outcome) { - null -> null - is MoveOutcome.Moved -> stringResource(R.string.event_move_done, movedLabel.orEmpty()) + null -> actionFailure + is MoveOutcome.Moved -> if (resizedLabel != null) { + stringResource(R.string.event_resize_done, resizedLabel) + } else { + stringResource(R.string.event_move_done, movedLabel.orEmpty()) + } MoveOutcome.Undone -> stringResource(R.string.event_move_undone) MoveOutcome.WriteDenied -> stringResource(R.string.event_move_write_denied) MoveOutcome.Gone -> stringResource(R.string.event_move_gone) @@ -96,6 +111,12 @@ fun EventMoveHost(viewModel: RescheduleViewModel, modifier: Modifier = Modifier) delay(if (outcome == MoveOutcome.Undone) UNDONE_CHIP_MILLIS else CHIP_MILLIS) viewModel.consumeOutcome() } + // A failure waits for the chip to be free, then has its own turn. + LaunchedEffect(actionFailure, outcome == null) { + if (actionFailure == null || outcome != null) return@LaunchedEffect + delay(CHIP_MILLIS) + onActionFailureShown() + } BoxWithConstraints(modifier = modifier.fillMaxSize()) { val chipMaxWidth = maxWidth - FAB_BAND @@ -113,7 +134,7 @@ fun EventMoveHost(viewModel: RescheduleViewModel, modifier: Modifier = Modifier) // write anyway, so offering it would be a button that does nothing. val undo = content.undo?.takeIf { !writeInFlight } SnackChip( - visible = outcome != null, + visible = outcome != null || actionFailure != null, message = content.message, maxWidth = chipMaxWidth, actionLabel = stringResource(R.string.event_move_undo).takeIf { undo != null }, @@ -142,3 +163,7 @@ private fun formatMovedTo( return localizedDateFormatter(locale, skeleton) .format(Instant.ofEpochMilli(startMillis).atZone(zone)) } + +/** "10:30" — the end of a resized event, read in the device zone like its start. */ +private fun formatTime(millis: Long, use24Hour: Boolean, locale: Locale): String = + timeOfDayFormatter(use24Hour, locale).format(Instant.ofEpochMilli(millis).atZone(ZoneId.systemDefault())) diff --git a/app/src/main/java/de/jeanlucmakiola/calendula/ui/common/EventMoveScope.kt b/app/src/main/java/de/jeanlucmakiola/calendula/ui/common/EventMoveScope.kt index c49456b8..92b8eae1 100644 --- a/app/src/main/java/de/jeanlucmakiola/calendula/ui/common/EventMoveScope.kt +++ b/app/src/main/java/de/jeanlucmakiola/calendula/ui/common/EventMoveScope.kt @@ -131,6 +131,13 @@ fun eventDragAllowed(event: EventInstance): Boolean { return move.dragEnabled && move.allows(event) } +/** + * Whether a long press may select events at all (#141) — the gesture setting, + * whatever the event's calendar allows. A read-only event is selected but stays put. + */ +@Composable +fun eventSelectAllowed(): Boolean = LocalEventMove.current?.dragEnabled == true + /** * A TalkBack action that opens [event] in the edit form, so rescheduling isn't * pointer-only. Null when this event can't be moved. diff --git a/app/src/main/java/de/jeanlucmakiola/calendula/ui/common/EventSelectionBar.kt b/app/src/main/java/de/jeanlucmakiola/calendula/ui/common/EventSelectionBar.kt new file mode 100644 index 00000000..66ae7beb --- /dev/null +++ b/app/src/main/java/de/jeanlucmakiola/calendula/ui/common/EventSelectionBar.kt @@ -0,0 +1,82 @@ +package de.jeanlucmakiola.calendula.ui.common + +import androidx.compose.foundation.layout.Row +import androidx.compose.foundation.layout.height +import androidx.compose.foundation.layout.padding +import androidx.compose.foundation.shape.CircleShape +import androidx.compose.material.icons.Icons +import androidx.compose.material.icons.filled.Check +import androidx.compose.material.icons.filled.Close +import androidx.compose.material.icons.filled.ContentCopy +import androidx.compose.material.icons.filled.Delete +import androidx.compose.material.icons.filled.Edit +import androidx.compose.material.icons.filled.Share +import androidx.compose.material3.Icon +import androidx.compose.material3.IconButton +import androidx.compose.material3.MaterialTheme +import androidx.compose.material3.Surface +import androidx.compose.runtime.Composable +import androidx.compose.ui.Alignment +import androidx.compose.ui.Modifier +import androidx.compose.ui.graphics.vector.ImageVector +import androidx.compose.ui.res.stringResource +import androidx.compose.ui.unit.dp +import de.jeanlucmakiola.calendula.R + +/** The selected event's action bar (#141); Edit and Delete only where its calendar allows. */ +@Composable +fun EventSelectionBar( + canEdit: Boolean, + canDelete: Boolean, + onEdit: () -> Unit, + onDuplicate: () -> Unit, + onShare: () -> Unit, + onDelete: () -> Unit, + modifier: Modifier = Modifier, +) { + // The FAB's height and colours, so the two read as one control. + Surface( + shape = CircleShape, + color = MaterialTheme.colorScheme.primaryContainer, + contentColor = MaterialTheme.colorScheme.onPrimaryContainer, + shadowElevation = 6.dp, + modifier = modifier.height(FabSize), + ) { + Row( + verticalAlignment = Alignment.CenterVertically, + modifier = Modifier.padding(horizontal = 4.dp), + ) { + if (canEdit) BarAction(Icons.Default.Edit, R.string.event_detail_edit, onEdit) + BarAction(Icons.Default.ContentCopy, R.string.event_detail_duplicate, onDuplicate) + BarAction(Icons.Default.Share, R.string.event_detail_share, onShare) + if (canDelete) BarAction(Icons.Default.Delete, R.string.event_detail_delete, onDelete) + } + } +} + +/** A drafted block's bar (#153): create the event, or let the draft go. */ +@Composable +fun DraftSelectionBar(onCreate: () -> Unit, onDiscard: () -> Unit, modifier: Modifier = Modifier) { + Surface( + shape = CircleShape, + color = MaterialTheme.colorScheme.primaryContainer, + contentColor = MaterialTheme.colorScheme.onPrimaryContainer, + shadowElevation = 6.dp, + modifier = modifier.height(FabSize), + ) { + Row( + verticalAlignment = Alignment.CenterVertically, + modifier = Modifier.padding(horizontal = 4.dp), + ) { + BarAction(Icons.Default.Close, R.string.event_draft_discard, onDiscard) + BarAction(Icons.Default.Check, R.string.event_draft_create, onCreate) + } + } +} + +@Composable +private fun BarAction(icon: ImageVector, label: Int, onClick: () -> Unit) { + IconButton(onClick = onClick) { + Icon(imageVector = icon, contentDescription = stringResource(label)) + } +} diff --git a/app/src/main/java/de/jeanlucmakiola/calendula/ui/common/EventSelectionHost.kt b/app/src/main/java/de/jeanlucmakiola/calendula/ui/common/EventSelectionHost.kt new file mode 100644 index 00000000..d2a1a6b2 --- /dev/null +++ b/app/src/main/java/de/jeanlucmakiola/calendula/ui/common/EventSelectionHost.kt @@ -0,0 +1,138 @@ +package de.jeanlucmakiola.calendula.ui.common + +import androidx.compose.runtime.Composable +import androidx.compose.runtime.getValue +import androidx.compose.runtime.mutableStateOf +import androidx.compose.runtime.remember +import androidx.compose.runtime.rememberCoroutineScope +import androidx.compose.runtime.rememberUpdatedState +import androidx.compose.runtime.setValue +import androidx.compose.ui.platform.LocalContext +import androidx.compose.ui.res.stringResource +import androidx.lifecycle.compose.collectAsStateWithLifecycle +import de.jeanlucmakiola.calendula.R +import de.jeanlucmakiola.calendula.domain.EventForm +import de.jeanlucmakiola.calendula.domain.EventInstance +import de.jeanlucmakiola.floret.components.SnackChipMargin +import kotlinx.coroutines.launch + +/** The bottom band the selection bar and FAB cover, margin included. */ +val SelectionBarClearance = FabSize + SnackChipMargin + +/** The FAB's role while an event is selected (#141): its action bar's toggle. Null otherwise. */ +@Composable +fun rememberFabSelection( + host: ChromeHost, + viewModel: EventActionsViewModel, + onEdit: (EventInstance) -> Unit, + onDuplicate: (EventForm) -> Unit, + chipShown: Boolean, + onDismissChip: () -> Unit, +): FabSelection? { + val calendars by viewModel.calendars.collectAsStateWithLifecycle() + val context = LocalContext.current + val scope = rememberCoroutineScope() + val chooserTitle = stringResource(R.string.event_share_chooser_title) + + // What the FAB has been told for this selection, over what the coverage says. + var chosen by remember(host.selection?.event) { mutableStateOf(null) } + // Folded while a chip is up, which then sits beside the FAB as usual. + val expanded = !chipShown && (chosen ?: !host.selectionCompact) + + val currentEdit by rememberUpdatedState(onEdit) + val currentDuplicate by rememberUpdatedState(onDuplicate) + val currentDismissChip by rememberUpdatedState(onDismissChip) + // Each reads the selection at grant time, which may come after a rotation. + val onCreate = rememberWriteAction { host.selection?.create?.invoke() } + val onEditSelected = rememberWriteAction { + host.selection?.takeIf { it.create == null }?.let { selected -> + selected.dismiss() + currentEdit(selected.event) + } + } + val onDuplicateSelected = rememberWriteAction { + val selected = host.selection?.takeIf { it.create == null } ?: return@rememberWriteAction + scope.launch { + val form = viewModel.duplicateForm(selected.event) ?: return@launch + selected.dismiss() + currentDuplicate(form) + } + } + val onDeleteSelected = rememberWriteAction { + host.selection?.takeIf { it.create == null }?.let { viewModel.requestDelete(it.event) } + } + + val selection = host.selection ?: return null + if (selection.create != null) { + return remember(selection, expanded, chipShown) { + FabSelection( + expanded = expanded, + onToggle = { + if (chipShown) currentDismissChip() + chosen = !expanded + }, + bar = { + DraftSelectionBar( + onCreate = onCreate, + onDiscard = selection.dismiss, + ) + }, + ) + } + } + val event = selection.event + val calendar = calendars[event.calendarId] + val canEdit = calendar?.canModifyContents == true + val canDelete = canEdit && calendar?.isManaged == false + return remember(selection, expanded, chipShown, canEdit, canDelete) { + FabSelection( + expanded = expanded, + onToggle = { + if (chipShown) currentDismissChip() + chosen = !expanded + }, + bar = { + EventSelectionBar( + canEdit = canEdit, + canDelete = canDelete, + onEdit = onEditSelected, + onDuplicate = onDuplicateSelected, + onShare = { + scope.launch { + val uri = viewModel.shareUri(event) ?: return@launch + if (!context.sendEventShare(uri, chooserTitle)) viewModel.reportShareFailed() + } + }, + onDelete = onDeleteSelected, + ) + }, + ) + } +} + +/** What a failed action on a selected event says, for the move host's chip to show (#141). */ +@Composable +fun eventActionFailureMessage(failure: EventActionFailure?): String? = when (failure) { + null -> null + EventActionFailure.LoadFailed -> stringResource(R.string.event_action_load_failed) + EventActionFailure.ShareFailed -> stringResource(R.string.event_share_failed) + EventActionFailure.DeleteFailed -> stringResource(R.string.event_delete_failed) + EventActionFailure.WriteDenied -> stringResource(R.string.event_delete_write_denied) + EventActionFailure.Gone -> stringResource(R.string.event_move_gone) +} + +/** The delete confirmation a selected event's Delete brings up (#141). */ +@Composable +fun EventSelectionHost(host: ChromeHost, viewModel: EventActionsViewModel) { + val deletePrompt by viewModel.deletePrompt.collectAsStateWithLifecycle() + deletePrompt?.let { prompt -> + DeleteEventDialog( + isRecurring = prompt.isRecurring, + onConfirm = { writeScope -> + host.selection?.takeIf { it.event == prompt.event }?.dismiss() + viewModel.confirmDelete(writeScope) + }, + onDismiss = viewModel::cancelDelete, + ) + } +} diff --git a/app/src/main/java/de/jeanlucmakiola/calendula/ui/common/HourGutter.kt b/app/src/main/java/de/jeanlucmakiola/calendula/ui/common/HourGutter.kt index 67c944cc..c7f0aefe 100644 --- a/app/src/main/java/de/jeanlucmakiola/calendula/ui/common/HourGutter.kt +++ b/app/src/main/java/de/jeanlucmakiola/calendula/ui/common/HourGutter.kt @@ -19,12 +19,14 @@ import androidx.compose.runtime.Composable import androidx.compose.runtime.derivedStateOf import androidx.compose.runtime.getValue import androidx.compose.runtime.remember +import androidx.compose.ui.graphics.graphicsLayer import androidx.compose.ui.Alignment import androidx.compose.ui.Modifier import androidx.compose.ui.platform.LocalDensity import androidx.compose.ui.semantics.clearAndSetSemantics import androidx.compose.ui.unit.Dp import androidx.compose.ui.unit.dp +import de.jeanlucmakiola.calendula.ui.week.MINUTES_PER_DAY import de.jeanlucmakiola.floret.locale.currentLocale /** Width of the hour gutter down the start edge of the day and week timelines. */ @@ -67,7 +69,7 @@ fun HourGutter( val locale = currentLocale() // Derived: the drag is rewritten every frame, its snapped start once a slot. val dragStartMin by remember(dragController) { - derivedStateOf { dragController.drag?.startMin } + derivedStateOf { dragController.drag?.markerMin } } val hourAlpha by animateFloatAsState( targetValue = if (dragStartMin != null) DIMMED_HOUR_ALPHA else 1f, @@ -107,12 +109,24 @@ fun HourGutter( } } } - dragStartMin?.let { startMin -> + // Held while it fades, so it goes out where it was rather than blinking off. + val badgeMin = rememberHeld(dragStartMin) + val badgeIn by animateFloatAsState( + targetValue = if (dragStartMin != null) 1f else 0f, + animationSpec = MaterialTheme.motionScheme.fastEffectsSpec(), + label = "gutterBadge", + ) + badgeMin?.takeIf { badgeIn > 0f }?.let { startMin -> val top = (hourHeight * (startMin / 60f) - BADGE_HEIGHT / 2).coerceAtLeast(0.dp) Box( modifier = Modifier .align(Alignment.TopCenter) .offset(y = top) + .graphicsLayer { + alpha = badgeIn + scaleX = 0.8f + 0.2f * badgeIn + scaleY = 0.8f + 0.2f * badgeIn + } .height(BADGE_HEIGHT) .background(MaterialTheme.colorScheme.primary, CircleShape) .padding(horizontal = 4.dp) @@ -121,7 +135,8 @@ fun HourGutter( contentAlignment = Alignment.Center, ) { Text( - text = formatGutterTime(startMin, use24Hour, locale), + // A resized end can sit on midnight: 00:00, not a clamped 23:59. + text = formatGutterTime(startMin % MINUTES_PER_DAY, use24Hour, locale), style = MaterialTheme.typography.labelSmall, color = MaterialTheme.colorScheme.onPrimary, maxLines = 1, diff --git a/app/src/main/java/de/jeanlucmakiola/calendula/ui/common/OutOfViewEdges.kt b/app/src/main/java/de/jeanlucmakiola/calendula/ui/common/OutOfViewEdges.kt index 7954e3c4..67cd7227 100644 --- a/app/src/main/java/de/jeanlucmakiola/calendula/ui/common/OutOfViewEdges.kt +++ b/app/src/main/java/de/jeanlucmakiola/calendula/ui/common/OutOfViewEdges.kt @@ -195,15 +195,20 @@ class OutOfViewEdges internal constructor( } } + /** Whether a press at [y] (content px) lands on an edge bar (#153). */ + fun covers(y: Float): Boolean = edgeAt(y) != null + + private fun edgeAt(y: Float) = tappedEdge( + events = events, + y = y, + viewportTop = scrollState.value.toFloat(), + viewportPx = scrollState.viewportSize, + reachPx = reachPx, + ) + /** Reveals the hidden event if a tap at [y] (content px) lands on a bar. */ fun tap(y: Float): Boolean { - val edge = tappedEdge( - events = events, - y = y, - viewportTop = scrollState.value.toFloat(), - viewportPx = scrollState.viewportSize, - reachPx = reachPx, - ) ?: return false + val edge = edgeAt(y) ?: return false reveal(edge) return true } diff --git a/app/src/main/java/de/jeanlucmakiola/calendula/ui/common/PageStateCache.kt b/app/src/main/java/de/jeanlucmakiola/calendula/ui/common/PageStateCache.kt index 8358820a..5e92a836 100644 --- a/app/src/main/java/de/jeanlucmakiola/calendula/ui/common/PageStateCache.kt +++ b/app/src/main/java/de/jeanlucmakiola/calendula/ui/common/PageStateCache.kt @@ -1,10 +1,10 @@ package de.jeanlucmakiola.calendula.ui.common +import de.jeanlucmakiola.floret.android.stateWhileSubscribed import kotlinx.coroutines.CoroutineScope import kotlinx.coroutines.Job import kotlinx.coroutines.SupervisorJob import kotlinx.coroutines.flow.Flow -import kotlinx.coroutines.flow.SharingStarted import kotlinx.coroutines.flow.StateFlow import kotlinx.coroutines.flow.stateIn import kotlinx.coroutines.plus @@ -45,7 +45,7 @@ class PageStateCache( return entries.getOrPut(key) { val job = SupervisorJob(scope.coroutineContext[Job]) Entry( - state = load(key).stateIn(scope + job, SharingStarted.WhileSubscribed(5_000L), initial), + state = load(key).stateWhileSubscribed(scope + job, initial), job = job, ) }.state diff --git a/app/src/main/java/de/jeanlucmakiola/calendula/ui/common/PastEvents.kt b/app/src/main/java/de/jeanlucmakiola/calendula/ui/common/PastEvents.kt index cf988c10..e827a1a9 100644 --- a/app/src/main/java/de/jeanlucmakiola/calendula/ui/common/PastEvents.kt +++ b/app/src/main/java/de/jeanlucmakiola/calendula/ui/common/PastEvents.kt @@ -5,6 +5,11 @@ import androidx.compose.ui.text.AnnotatedString import androidx.compose.ui.text.SpanStyle import androidx.compose.ui.text.buildAnnotatedString import androidx.compose.ui.text.style.TextDecoration +import de.jeanlucmakiola.calendula.domain.EventInstance +import de.jeanlucmakiola.calendula.domain.hasEnded +import kotlinx.datetime.LocalDate +import kotlinx.datetime.TimeZone +import kotlinx.datetime.toLocalDateTime import kotlin.time.Instant /** @@ -16,6 +21,17 @@ import kotlin.time.Instant */ val LocalDimCutoff = compositionLocalOf { null } +/** + * Whether [this] counts as past where it's drawn on [day]: once it has ended, + * or on any day before the one [now] falls in, so a multi-day event still + * running doesn't stay undimmed on the days already behind it. + */ +fun EventInstance.isPastOn( + day: LocalDate, + now: Instant, + zone: TimeZone = TimeZone.currentSystemDefault(), +): Boolean = hasEnded(now) || day < now.toLocalDateTime(zone).date + /** Opacity applied to a completed/past event chip when it is dimmed. */ const val EventDimAlpha = 0.4f diff --git a/app/src/main/java/de/jeanlucmakiola/calendula/ui/common/Picker.kt b/app/src/main/java/de/jeanlucmakiola/calendula/ui/common/Picker.kt index 6c25a2c0..f2505b2e 100644 --- a/app/src/main/java/de/jeanlucmakiola/calendula/ui/common/Picker.kt +++ b/app/src/main/java/de/jeanlucmakiola/calendula/ui/common/Picker.kt @@ -1,14 +1,8 @@ package de.jeanlucmakiola.calendula.ui.common -import androidx.compose.animation.AnimatedVisibility import androidx.compose.foundation.layout.Spacer import androidx.compose.foundation.layout.height -import androidx.compose.foundation.layout.padding -import androidx.compose.material.icons.Icons import androidx.compose.material3.Checkbox -import androidx.compose.material3.Icon -import androidx.compose.material3.MaterialTheme -import androidx.compose.material3.Text import androidx.compose.runtime.Composable import androidx.compose.runtime.LaunchedEffect import androidx.compose.runtime.getValue @@ -22,17 +16,16 @@ import androidx.compose.ui.res.stringResource import androidx.compose.ui.unit.dp import de.jeanlucmakiola.calendula.R import de.jeanlucmakiola.floret.components.CustomAmountEditor +import de.jeanlucmakiola.floret.components.CustomExpandRow import de.jeanlucmakiola.floret.components.FullScreenPicker -import de.jeanlucmakiola.floret.components.GroupedListInset +import de.jeanlucmakiola.floret.components.GroupedHint import de.jeanlucmakiola.floret.components.GroupedRow import de.jeanlucmakiola.floret.components.Position -import de.jeanlucmakiola.floret.components.SelectedCheck import de.jeanlucmakiola.floret.components.positionOf -import de.jeanlucmakiola.floret.identity.collapseExit -import de.jeanlucmakiola.floret.identity.expandEnter import de.jeanlucmakiola.floret.locale.currentLocale import de.jeanlucmakiola.floret.reminders.ReminderOverride import de.jeanlucmakiola.floret.reminders.ReminderUnit +import de.jeanlucmakiola.floret.reminders.minutesOrEmpty import de.jeanlucmakiola.floret.reminders.reminderOverrideForMinutes import de.jeanlucmakiola.calendula.ui.agenda.AgendaRange import de.jeanlucmakiola.calendula.ui.agenda.agendaRangeWindowSummary @@ -90,7 +83,7 @@ fun ReminderDefaultPicker( } val inherits = current is ReminderOverride.Inherit val isNone = current is ReminderOverride.None - val selectedMinutes = (current as? ReminderOverride.Minutes)?.minutes.orEmpty() + val selectedMinutes = current.minutesOrEmpty() // Custom (non-preset) lead times seen this session, so unchecking one keeps // its row (unchecked) until the picker closes instead of vanishing mid-tap, // which would strand a hand-entered value with no way to re-check it. @@ -121,24 +114,14 @@ fun ReminderDefaultPicker( GroupedRow( title = stringResource(R.string.reminder_use_default), position = Position.Top, - selected = inherits, - trailing = if (inherits) { - { SelectedCheck() } - } else { - null - }, + checked = inherits, onClick = { apply(ReminderOverride.Inherit) }, ) } GroupedRow( title = stringResource(R.string.reminder_none), position = if (allowInherit) Position.Bottom else Position.Alone, - selected = isNone, - trailing = if (isNone) { - { SelectedCheck() } - } else { - null - }, + checked = isNone, onClick = { apply(ReminderOverride.None) }, ) Spacer(Modifier.height(24.dp)) @@ -154,17 +137,11 @@ fun ReminderDefaultPicker( onClick = { toggle(minute) }, ) } - // When expanded, the Custom row connects downward into the editor card - // so the two read as one grouped container (the per-calendar pattern). - GroupedRow( + CustomExpandRow( title = stringResource(R.string.event_edit_reminder_custom), - position = if (customExpanded) Position.Top else positionOf(rows.size, rowCount), - onClick = { customExpanded = !customExpanded }, - ) - AnimatedVisibility( - visible = customExpanded, - enter = expandEnter(), - exit = collapseExit(), + position = positionOf(rows.size, rowCount), + expanded = customExpanded, + onExpandedChange = { customExpanded = it }, ) { CustomReminderEditor( amountText = amountText, @@ -212,19 +189,6 @@ private fun CustomReminderEditor( ) } -/** A short explanatory paragraph shown under a picker's title, above the rows, - * on the same left margin as the rows themselves. */ -@Composable -internal fun PickerDescription(text: String) { - Text( - text = text, - style = MaterialTheme.typography.bodyMedium, - color = MaterialTheme.colorScheme.onSurfaceVariant, - modifier = Modifier.padding(horizontal = GroupedListInset, vertical = 8.dp), - ) -} - - /** * Agenda-range picker, full-screen. Two grouped lists — the calendar-aligned * options (today / this week / this month) and the rolling windows (next 7 / 30 @@ -265,17 +229,11 @@ fun AgendaRangePicker( } val rangeRow: @Composable (AgendaRange, Position) -> Unit = { option, position -> - val isSelected = option == selected GroupedRow( title = agendaRangeLabel(option), summary = windowSummary(option), position = position, - selected = isSelected, - trailing = if (isSelected) { - { SelectedCheck() } - } else { - null - }, + checked = option == selected, onClick = { onSelect(option) onDismiss() @@ -284,7 +242,7 @@ fun AgendaRangePicker( } FullScreenPicker(title = title, onDismiss = onDismiss) { - PickerDescription(description) + GroupedHint(description, verticalPadding = 8.dp) // Calendar-aligned windows. calendarAligned.forEachIndexed { index, option -> @@ -297,7 +255,7 @@ fun AgendaRangePicker( rolling.forEachIndexed { index, option -> rangeRow(option, positionOf(index, rollingRowCount)) } - GroupedRow( + CustomExpandRow( title = if (customSelected) { agendaRangeLabel(selected) } else { @@ -306,19 +264,10 @@ fun AgendaRangePicker( // An unset custom window has no day count yet, so the row stays // single-line until it does. summary = if (customSelected) windowSummary(selected) else null, - position = if (customExpanded) Position.Top else positionOf(rolling.size, rollingRowCount), - selected = customSelected, - trailing = if (customSelected) { - { SelectedCheck() } - } else { - null - }, - onClick = { customExpanded = !customExpanded }, - ) - AnimatedVisibility( - visible = customExpanded, - enter = expandEnter(), - exit = collapseExit(), + position = positionOf(rolling.size, rollingRowCount), + expanded = customExpanded, + onExpandedChange = { customExpanded = it }, + checked = customSelected, ) { CustomDaysEditor( amountText = amountText, @@ -396,17 +345,12 @@ fun DurationPicker( } FullScreenPicker(title = title, onDismiss = onDismiss, predictiveBack = true) { - if (description != null) PickerDescription(description) + if (description != null) GroupedHint(description, verticalPadding = 8.dp) if (inheritLabel != null) { GroupedRow( title = inheritLabel, position = Position.Alone, - selected = inherits, - trailing = if (inherits) { - { SelectedCheck() } - } else { - null - }, + checked = inherits, onClick = { onSelect(null) onDismiss() @@ -415,39 +359,22 @@ fun DurationPicker( Spacer(Modifier.height(24.dp)) } presets.forEachIndexed { index, minute -> - val isSelected = minute == selected GroupedRow( title = label(minute), position = positionOf(index, rowCount), - selected = isSelected, - trailing = if (isSelected) { - { SelectedCheck() } - } else { - null - }, + checked = minute == selected, onClick = { onSelect(minute) onDismiss() }, ) } - // The Custom row connects downward into the editor card when expanded, so - // the two read as one grouped container (the shared custom-expand pattern). - GroupedRow( + CustomExpandRow( title = custom?.let { label(it) } ?: stringResource(R.string.event_edit_reminder_custom), - position = if (customExpanded) Position.Top else positionOf(presets.size, rowCount), - selected = custom != null, - trailing = if (custom != null) { - { SelectedCheck() } - } else { - null - }, - onClick = { customExpanded = !customExpanded }, - ) - AnimatedVisibility( - visible = customExpanded, - enter = expandEnter(), - exit = collapseExit(), + position = positionOf(presets.size, rowCount), + expanded = customExpanded, + onExpandedChange = { customExpanded = it }, + checked = custom != null, ) { CustomDurationEditor( amountText = amountText, 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 252bc9e1..7bc93dc2 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 @@ -10,6 +10,8 @@ import androidx.compose.ui.text.font.FontStyle import de.jeanlucmakiola.calendula.R 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.toJavaLocalDate @@ -32,10 +34,7 @@ import java.util.Locale */ @Composable fun recurrenceText(rrule: String, locale: Locale): AnnotatedString { - val parts = rrule.removePrefix("RRULE:").split(';').mapNotNull { token -> - val eq = token.indexOf('=') - if (eq <= 0) null else token.substring(0, eq).uppercase() to token.substring(eq + 1) - }.toMap() + val parts = rruleParts(rrule).mapNotNull { part -> part.key?.let { it to part.value } }.toMap() val freq = parts["FREQ"]?.uppercase() val interval = parts["INTERVAL"]?.toIntOrNull() ?: 1 @@ -171,12 +170,5 @@ internal fun untilLocalDate(raw: String, zone: ZoneId = ZoneId.systemDefault()): .atOffset(ZoneOffset.UTC) .atZoneSameInstant(zone) .toLocalDate() - }.recoverCatching { - val digits = value.takeWhile { it.isDigit() } - LocalDate.of( - digits.substring(0, 4).toInt(), - digits.substring(4, 6).toInt(), - digits.substring(6, 8).toInt(), - ) - }.getOrNull() + }.getOrNull() ?: parseBasicDate(value.takeWhile { it.isDigit() })?.toJavaLocalDate() } diff --git a/app/src/main/java/de/jeanlucmakiola/calendula/ui/common/RememberHeld.kt b/app/src/main/java/de/jeanlucmakiola/calendula/ui/common/RememberHeld.kt new file mode 100644 index 00000000..a401271a --- /dev/null +++ b/app/src/main/java/de/jeanlucmakiola/calendula/ui/common/RememberHeld.kt @@ -0,0 +1,22 @@ +package de.jeanlucmakiola.calendula.ui.common + +import androidx.compose.runtime.Composable +import androidx.compose.runtime.remember + +/** + * [live], or after it goes null the last value it had, so an overlay keeps + * drawing what it showed through its slide-out instead of flashing empty. Never + * a placeholder: until [live] is first set this is null, so a destination never + * loads a bogus key on its first frame. Not saved — after a recreation the + * saveable [live] is the value again. + */ +@Composable +fun rememberHeld(live: T?): T? { + val held = remember { HeldValue() } + if (live != null) held.value = live + return live ?: held.value +} + +private class HeldValue { + var value: T? = null +} diff --git a/app/src/main/java/de/jeanlucmakiola/calendula/ui/common/RescheduleViewModel.kt b/app/src/main/java/de/jeanlucmakiola/calendula/ui/common/RescheduleViewModel.kt index 003506ba..ba1f2451 100644 --- a/app/src/main/java/de/jeanlucmakiola/calendula/ui/common/RescheduleViewModel.kt +++ b/app/src/main/java/de/jeanlucmakiola/calendula/ui/common/RescheduleViewModel.kt @@ -3,9 +3,9 @@ package de.jeanlucmakiola.calendula.ui.common import androidx.lifecycle.ViewModel import androidx.lifecycle.viewModelScope import dagger.hilt.android.lifecycle.HiltViewModel +import de.jeanlucmakiola.calendula.data.time.ZoneSource import de.jeanlucmakiola.calendula.data.calendar.CalendarRepository import de.jeanlucmakiola.calendula.data.calendar.NoSuchEventException -import de.jeanlucmakiola.calendula.data.di.IoDispatcher import de.jeanlucmakiola.calendula.domain.EventDetail import de.jeanlucmakiola.calendula.domain.EventForm import de.jeanlucmakiola.calendula.domain.EventFormProblem @@ -15,26 +15,28 @@ import de.jeanlucmakiola.calendula.domain.allowsEventMove import de.jeanlucmakiola.calendula.domain.parseSimpleRecurrence import de.jeanlucmakiola.calendula.domain.problems import de.jeanlucmakiola.calendula.domain.realignRecurrence +import de.jeanlucmakiola.calendula.domain.resizedTo +import de.jeanlucmakiola.calendula.domain.endInstant +import de.jeanlucmakiola.calendula.domain.startInstant import de.jeanlucmakiola.calendula.domain.resolvedZone import de.jeanlucmakiola.calendula.domain.shiftedByDays import de.jeanlucmakiola.calendula.domain.shiftedTo import de.jeanlucmakiola.calendula.domain.toEditForm +import de.jeanlucmakiola.floret.android.stateWhileSubscribed +import de.jeanlucmakiola.floret.di.IoDispatcher import kotlinx.coroutines.CoroutineDispatcher import kotlinx.coroutines.flow.MutableStateFlow -import kotlinx.coroutines.flow.SharingStarted import kotlinx.coroutines.flow.StateFlow import kotlinx.coroutines.flow.asStateFlow import kotlinx.coroutines.flow.catch import kotlinx.coroutines.flow.flowOn import kotlinx.coroutines.flow.map -import kotlinx.coroutines.flow.stateIn import kotlinx.coroutines.launch import kotlinx.datetime.DateTimeUnit import kotlinx.datetime.LocalDate import kotlinx.datetime.TimeZone import kotlinx.datetime.atStartOfDayIn import kotlinx.datetime.plus -import kotlinx.datetime.toInstant import kotlinx.datetime.toLocalDateTime import kotlin.coroutines.cancellation.CancellationException import kotlin.time.Instant @@ -54,6 +56,9 @@ sealed interface MoveTarget { * disagree by a day over which zone the event's first day is resolved in. */ data class ByDays(val days: Int) : MoveTarget + + /** New start and end instants — a timeline resize, which changes the length. */ + data class Span(val start: Instant, val end: Instant) : MoveTarget } /** @@ -74,7 +79,7 @@ data class MoveRequest( * re-derive (`BYDAY=MO,WE`, `2TH`, …), or the shift wouldn't carry the anchor * across the same midnights the occurrence crossed. */ -data class MoveScopePrompt(val occurrenceOnly: Boolean) +data class MoveScopePrompt(val occurrenceOnly: Boolean, val resize: Boolean = false) /** The inverse of a completed move, for the undo action. */ data class MoveUndo( @@ -88,12 +93,14 @@ data class MoveUndo( sealed interface MoveOutcome { /** * Written. [startMillis] is where the dragged occurrence now begins, for the - * confirmation message; [undo] is null when the write has no clean inverse. + * confirmation message, and [endMillis] where it ends — set only for a resize, + * whose message names both; [undo] is null when the write has no clean inverse. */ data class Moved( val startMillis: Long, val isAllDay: Boolean, val undo: MoveUndo?, + val endMillis: Long? = null, ) : MoveOutcome data object Undone : MoveOutcome @@ -122,6 +129,7 @@ sealed interface MoveOutcome { class RescheduleViewModel @Inject constructor( private val repository: CalendarRepository, @IoDispatcher private val io: CoroutineDispatcher, + private val zoneSource: ZoneSource, ) : ViewModel() { private val _scopePrompt = MutableStateFlow(null) @@ -179,9 +187,8 @@ class RescheduleViewModel @Inject constructor( .map { calendars -> calendars.filter { it.allowsEventMove }.map { it.id }.toSet() } .catch { emit(emptySet()) } .flowOn(io) - .stateIn( + .stateWhileSubscribed( scope = viewModelScope, - started = SharingStarted.WhileSubscribed(5_000L), initialValue = emptySet(), ) @@ -226,7 +233,10 @@ class RescheduleViewModel @Inject constructor( } else { // Still busy: the scope dialog is now the thing in flight. pending = prepared - _scopePrompt.value = MoveScopePrompt(occurrenceOnly = !prepared.canRealign) + _scopePrompt.value = MoveScopePrompt( + occurrenceOnly = !prepared.canRealign, + resize = request.target is MoveTarget.Span, + ) } } return true @@ -308,18 +318,19 @@ class RescheduleViewModel @Inject constructor( return null } - val zone = TimeZone.currentSystemDefault() + val zone = zoneSource.current() val original = detail.toEditForm(request.beginMillis, request.endMillis, zone) val shifted = when (val target = request.target) { is MoveTarget.Start -> original.shiftedTo(target.instant, zone) is MoveTarget.ByDays -> original.shiftedByDays(target.days, zone) + is MoveTarget.Span -> original.resizedTo(target.start, target.end, zone) } // A zero-distance drop is not a write. if (shifted == original) return null // The UNTIL check is deferred to the write, which knows how far the move // reaches and so which date has to clear it. - if ((shifted.problems() - EventFormProblem.RecurrenceEndsBeforeStart).isNotEmpty()) { + if ((shifted.problems(zone) - EventFormProblem.RecurrenceEndsBeforeStart).isNotEmpty()) { _outcome.value = MoveOutcome.Failed return null } @@ -396,6 +407,7 @@ class RescheduleViewModel @Inject constructor( startMillis = movedStartMillis(prepared), isAllDay = prepared.updated.isAllDay, undo = undoFor(prepared, scope), + endMillis = resizedEndMillis(prepared), ) } catch (e: CancellationException) { throw e @@ -480,6 +492,13 @@ class RescheduleViewModel @Inject constructor( null } + /** Where a resized occurrence now ends; null for a move, which keeps its length. */ + private fun resizedEndMillis(prepared: PreparedMove): Long? { + if (prepared.request.target !is MoveTarget.Span) return null + val form = prepared.updated + return form.endInstant(form.resolvedZone(zoneSource.current())).toEpochMilliseconds() + } + /** * Where the dragged occurrence now begins, in the same anchoring the views * read dates back in: UTC midnight for an all-day event. @@ -489,8 +508,7 @@ class RescheduleViewModel @Inject constructor( return if (form.isAllDay) { form.start.date.atStartOfDayIn(TimeZone.UTC).toEpochMilliseconds() } else { - form.start.toInstant(form.resolvedZone(TimeZone.currentSystemDefault())) - .toEpochMilliseconds() + form.startInstant(form.resolvedZone(zoneSource.current())).toEpochMilliseconds() } } diff --git a/app/src/main/java/de/jeanlucmakiola/calendula/ui/common/ResizeHandle.kt b/app/src/main/java/de/jeanlucmakiola/calendula/ui/common/ResizeHandle.kt new file mode 100644 index 00000000..429d81c5 --- /dev/null +++ b/app/src/main/java/de/jeanlucmakiola/calendula/ui/common/ResizeHandle.kt @@ -0,0 +1,102 @@ +package de.jeanlucmakiola.calendula.ui.common + +import androidx.compose.foundation.background +import androidx.compose.foundation.border +import androidx.compose.foundation.gestures.awaitEachGesture +import androidx.compose.foundation.gestures.awaitFirstDown +import androidx.compose.foundation.layout.Box +import androidx.compose.foundation.layout.size +import androidx.compose.foundation.shape.CircleShape +import androidx.compose.material3.MaterialTheme +import androidx.compose.runtime.Composable +import androidx.compose.runtime.getValue +import androidx.compose.runtime.remember +import androidx.compose.runtime.rememberUpdatedState +import androidx.compose.ui.Alignment +import androidx.compose.ui.Modifier +import androidx.compose.ui.geometry.Offset +import androidx.compose.ui.graphics.Color +import androidx.compose.ui.input.pointer.pointerInput +import androidx.compose.ui.layout.LayoutCoordinates +import androidx.compose.ui.layout.onGloballyPositioned +import androidx.compose.ui.semantics.clearAndSetSemantics +import androidx.compose.ui.unit.dp + +/** The handle's touch target, centred on the edge it moves. */ +val ResizeHandleTarget = 48.dp + +private val HANDLE_DOT = 16.dp +private val HANDLE_RING = 2.dp + +/** + * A grip on one edge of a selected event (#141), dragged without a hold. No + * semantics: TalkBack resizes through the event's edit action. + */ +@Composable +fun ResizeHandle( + color: Color, + enabled: Boolean, + onStart: (pointerInRoot: Offset) -> Unit, + onMove: (pointerInRoot: Offset) -> Unit, + onEnd: () -> Unit, + onCancel: () -> Unit, + modifier: Modifier = Modifier, +) { + val coordinates = remember { arrayOfNulls(1) } + val currentStart by rememberUpdatedState(onStart) + val currentMove by rememberUpdatedState(onMove) + val currentEnd by rememberUpdatedState(onEnd) + val currentCancel by rememberUpdatedState(onCancel) + // Not a key: turning it off mid-resize must not cancel that resize. + val currentEnabled by rememberUpdatedState(enabled) + Box( + contentAlignment = Alignment.Center, + modifier = modifier + .size(ResizeHandleTarget) + .clearAndSetSemantics { } + .onGloballyPositioned { coordinates[0] = it } + .pointerInput(Unit) { + awaitEachGesture { + val down = awaitFirstDown() + if (!currentEnabled) return@awaitEachGesture + down.consume() + var started = false + var ended = false + try { + while (true) { + val event = awaitPointerEvent() + val change = event.changes.firstOrNull { it.id == down.id } ?: break + // Claimed by an ancestor that outranks us — the pinch. + if (change.isConsumed) break + if (event.changes.count { it.pressed } > 1) break + change.consume() + if (!change.pressed) { + ended = started + break + } + val root = coordinates[0]?.takeIf { it.isAttached } + ?.localToRoot(change.position) ?: break + if (started) { + currentMove(root) + } else { + started = true + currentStart(root) + } + } + } finally { + when { + ended -> currentEnd() + started -> currentCancel() + } + } + } + }, + ) { + Box( + Modifier + .size(HANDLE_DOT) + .background(color, CircleShape) + .border(HANDLE_RING, MaterialTheme.colorScheme.surface, CircleShape), + ) + } +} diff --git a/app/src/main/java/de/jeanlucmakiola/calendula/ui/common/SelectionTopBar.kt b/app/src/main/java/de/jeanlucmakiola/calendula/ui/common/SelectionTopBar.kt new file mode 100644 index 00000000..d9d69b71 --- /dev/null +++ b/app/src/main/java/de/jeanlucmakiola/calendula/ui/common/SelectionTopBar.kt @@ -0,0 +1,96 @@ +package de.jeanlucmakiola.calendula.ui.common + +import androidx.compose.foundation.layout.Column +import androidx.compose.material.icons.Icons +import androidx.compose.material.icons.filled.Close +import androidx.compose.material3.ExperimentalMaterial3Api +import androidx.compose.material3.Icon +import androidx.compose.material3.IconButton +import androidx.compose.material3.MaterialTheme +import androidx.compose.material3.Text +import androidx.compose.material3.TopAppBar +import androidx.compose.material3.TopAppBarDefaults +import androidx.compose.runtime.Composable +import androidx.compose.runtime.derivedStateOf +import androidx.compose.runtime.getValue +import androidx.compose.runtime.remember +import androidx.compose.ui.res.stringResource +import androidx.compose.ui.text.style.TextOverflow +import de.jeanlucmakiola.calendula.R +import de.jeanlucmakiola.calendula.domain.EventInstance +import de.jeanlucmakiola.floret.locale.currentLocale +import de.jeanlucmakiola.floret.locale.localizedDateFormatter +import java.time.ZoneId +import java.util.Locale +import kotlin.time.toJavaInstant + +/** + * The top bar while an event is selected (#141): says which, and when, with a + * way out — the selection otherwise only shows on the grid and in the FAB. + */ +@OptIn(ExperimentalMaterial3Api::class) +@Composable +fun SelectionTopBar(selection: EventSelection) { + val event = selection.event + // Follows a move or resize, so the times stay readable under the finger. + val preview by remember(selection) { derivedStateOf { selection.preview() } } + val shown = preview ?: event + val use24Hour = LocalUse24HourFormat.current + val locale = currentLocale() + val whenText = remember(shown.start, shown.end, use24Hour, locale) { + formatSelectionWhen(shown, use24Hour, locale) + } + TopAppBar( + navigationIcon = { + IconButton(onClick = selection.dismiss) { + Icon( + imageVector = Icons.Default.Close, + contentDescription = stringResource( + if (selection.create != null) R.string.event_draft_discard else R.string.event_selection_close, + ), + ) + } + }, + title = { + Column { + Text( + text = event.title.ifBlank { stringResource(R.string.event_untitled) }, + style = MaterialTheme.typography.titleMedium, + maxLines = 1, + overflow = TextOverflow.Ellipsis, + ) + Text( + text = whenText, + style = MaterialTheme.typography.bodyMedium, + color = MaterialTheme.colorScheme.onSurfaceVariant, + maxLines = 1, + overflow = TextOverflow.Ellipsis, + ) + } + }, + // The header's own surface, as the view's bar has (#186). + colors = TopAppBarDefaults.topAppBarColors( + containerColor = MaterialTheme.colorScheme.surface, + scrolledContainerColor = MaterialTheme.colorScheme.surface, + ), + ) +} + +/** + * "Fri, 9 Oct · 09:00–10:00", or with both days named for an event that runs + * into another: "Fri, 9 Oct, 22:00 – Sat, 10 Oct, 02:00". + */ +private fun formatSelectionWhen(event: EventInstance, use24Hour: Boolean, locale: Locale): String { + val zone = ZoneId.systemDefault() + val start = event.start.toJavaInstant().atZone(zone) + val end = event.end.toJavaInstant().atZone(zone) + val day = localizedDateFormatter(locale, "EEEdMMM") + val time = timeOfDayFormatter(use24Hour, locale) + val endsSameDay = end.toLocalDate() == start.toLocalDate() || + (end.toLocalTime().toSecondOfDay() == 0 && end.toLocalDate() == start.toLocalDate().plusDays(1)) + return if (endsSameDay) { + "${day.format(start)} · ${time.format(start)}–${time.format(end)}" + } else { + "${day.format(start)}, ${time.format(start)} – ${day.format(end)}, ${time.format(end)}" + } +} diff --git a/app/src/main/java/de/jeanlucmakiola/calendula/ui/common/TimeFormat.kt b/app/src/main/java/de/jeanlucmakiola/calendula/ui/common/TimeFormat.kt index fb6262a3..c5b00dc0 100644 --- a/app/src/main/java/de/jeanlucmakiola/calendula/ui/common/TimeFormat.kt +++ b/app/src/main/java/de/jeanlucmakiola/calendula/ui/common/TimeFormat.kt @@ -1,9 +1,15 @@ package de.jeanlucmakiola.calendula.ui.common import androidx.compose.runtime.staticCompositionLocalOf +import de.jeanlucmakiola.calendula.domain.inRepeatedHour +import de.jeanlucmakiola.calendula.domain.zoneAbbreviationAt +import kotlinx.datetime.TimeZone import java.time.LocalTime +import kotlin.time.Instant +import kotlin.time.toJavaInstant import java.time.format.DateTimeFormatter import java.util.Locale +import kotlinx.datetime.toLocalDateTime /** * The resolved clock convention for the whole UI: `true` = 24-hour ("14:00"), @@ -32,6 +38,12 @@ fun formatTimeOfDay(hour: Int, minute: Int, is24Hour: Boolean, locale: Locale): LocalTime.of(hour.coerceIn(0, 23), minute.coerceIn(0, 59)) .format(timeOfDayFormatter(is24Hour, locale)) +/** [instant]'s wall-clock time in [zone], as [formatTimeOfDay] renders it. */ +fun formatTimeOfDay(instant: Instant, zone: TimeZone, is24Hour: Boolean, locale: Locale): String { + val time = instant.toLocalDateTime(zone).time + return formatTimeOfDay(time.hour, time.minute, is24Hour, locale) +} + /** * Format minutes-from-midnight (0..1440) as a time label. The end-of-day value * 1440 renders as "24:00" in 24h (its established reading) and as midnight @@ -68,3 +80,15 @@ fun formatHourLabel(hour: Int, is24Hour: Boolean, locale: Locale): String = } private const val MINUTES_PER_DAY = 1_440 + +/** + * [formatted] — [instant]'s time in [zone] — with the zone's abbreviation after + * it ("2:30 AM CEST") when the fall-back hour repeats that time, the one case + * where the time alone doesn't say which instant it is (#387). + */ +fun withRepeatedHourZone(formatted: String, instant: Instant, zone: TimeZone, locale: Locale): String { + if (!instant.inRepeatedHour(zone)) return formatted + val abbreviation = zoneAbbreviationAt(zone.id, locale, instant.toJavaInstant(), ::icuTimeZoneRegion) + ?: return formatted + return "$formatted $abbreviation" +} diff --git a/app/src/main/java/de/jeanlucmakiola/calendula/ui/common/TimeZonePicker.kt b/app/src/main/java/de/jeanlucmakiola/calendula/ui/common/TimeZonePicker.kt index fad9d510..dc055fcf 100644 --- a/app/src/main/java/de/jeanlucmakiola/calendula/ui/common/TimeZonePicker.kt +++ b/app/src/main/java/de/jeanlucmakiola/calendula/ui/common/TimeZonePicker.kt @@ -1,6 +1,5 @@ package de.jeanlucmakiola.calendula.ui.common -import androidx.compose.foundation.layout.Column import androidx.compose.foundation.layout.PaddingValues import androidx.compose.foundation.layout.Row import androidx.compose.foundation.layout.fillMaxWidth @@ -39,11 +38,10 @@ import de.jeanlucmakiola.calendula.domain.timeZoneOptionOf import de.jeanlucmakiola.calendula.domain.timeZoneOptions import de.jeanlucmakiola.calendula.domain.zoneDescriptor import de.jeanlucmakiola.floret.components.FullScreenPicker -import de.jeanlucmakiola.floret.components.GroupedListInset import de.jeanlucmakiola.floret.components.GroupedRow +import de.jeanlucmakiola.floret.components.GroupedSectionHeader import de.jeanlucmakiola.floret.components.InlineTextField import de.jeanlucmakiola.floret.components.Position -import de.jeanlucmakiola.floret.components.SelectedCheck import de.jeanlucmakiola.floret.components.positionOf import de.jeanlucmakiola.floret.locale.currentLocale import kotlinx.coroutines.Dispatchers @@ -118,19 +116,14 @@ fun TimeZonePickerDialog( title = stringResource(R.string.event_edit_timezone_device), summary = deviceSummary, position = Position.Alone, - selected = selected == null, + checked = selected == null, leading = { Icon(Icons.Default.Public, contentDescription = null) }, - trailing = if (selected == null) { - { SelectedCheck() } - } else { - null - }, onClick = { choose(null) }, ) } if (recentZones.isNotEmpty()) { item(key = "recent_header") { - SectionHeader(stringResource(R.string.event_edit_timezone_recent)) + GroupedSectionHeader(stringResource(R.string.event_edit_timezone_recent)) } itemsIndexed( items = recentZones, @@ -145,7 +138,7 @@ fun TimeZonePickerDialog( } } item(key = "all_header") { - SectionHeader(stringResource(R.string.event_edit_timezone_all)) + GroupedSectionHeader(stringResource(R.string.event_edit_timezone_all)) } } @@ -234,23 +227,6 @@ private fun SearchField( } } -/** A small primary-coloured group label, matching the settings screens. */ -@Composable -private fun SectionHeader(text: String) { - Text( - text = text, - style = MaterialTheme.typography.labelLarge, - color = MaterialTheme.colorScheme.primary, - modifier = Modifier.padding( - start = GroupedListInset, - end = GroupedListInset, - top = 16.dp, - bottom = 4.dp, - ), - ) -} - - @Composable private fun ZoneRow( zone: TimeZoneOption, @@ -262,12 +238,7 @@ private fun ZoneRow( title = zone.label, summary = zoneDescriptor(zone), position = position, - selected = selected, - trailing = if (selected) { - { SelectedCheck() } - } else { - null - }, + checked = selected, onClick = onClick, ) } diff --git a/app/src/main/java/de/jeanlucmakiola/calendula/ui/common/TimelineDrag.kt b/app/src/main/java/de/jeanlucmakiola/calendula/ui/common/TimelineDrag.kt index 0f2fae46..73c5db79 100644 --- a/app/src/main/java/de/jeanlucmakiola/calendula/ui/common/TimelineDrag.kt +++ b/app/src/main/java/de/jeanlucmakiola/calendula/ui/common/TimelineDrag.kt @@ -1,11 +1,10 @@ package de.jeanlucmakiola.calendula.ui.common import androidx.compose.animation.core.animateFloatAsState +import androidx.compose.animation.core.Animatable import androidx.compose.animation.core.tween import androidx.compose.foundation.ScrollState import androidx.compose.foundation.MutatePriority -import androidx.compose.foundation.background -import androidx.compose.foundation.isSystemInDarkTheme import androidx.compose.foundation.layout.Box import androidx.compose.foundation.layout.Column import androidx.compose.foundation.layout.fillMaxSize @@ -19,7 +18,10 @@ import androidx.compose.material3.Text import androidx.compose.runtime.Composable import androidx.compose.runtime.LaunchedEffect import androidx.compose.runtime.Stable +import androidx.compose.runtime.derivedStateOf import androidx.compose.runtime.getValue +import androidx.compose.runtime.mutableStateListOf +import androidx.compose.runtime.mutableIntStateOf import androidx.compose.runtime.mutableStateOf import androidx.compose.runtime.remember import androidx.compose.runtime.setValue @@ -27,6 +29,7 @@ import androidx.compose.runtime.withFrameNanos import androidx.compose.ui.Modifier import androidx.compose.ui.draw.clipToBounds import androidx.compose.ui.geometry.Offset +import androidx.compose.ui.graphics.Shape import androidx.compose.ui.graphics.TransformOrigin import androidx.compose.ui.graphics.graphicsLayer import androidx.compose.ui.layout.LayoutCoordinates @@ -35,14 +38,25 @@ import androidx.compose.ui.semantics.clearAndSetSemantics import androidx.compose.ui.layout.onGloballyPositioned import androidx.compose.ui.layout.positionInRoot import androidx.compose.ui.platform.LocalDensity +import androidx.compose.ui.platform.LocalViewConfiguration import androidx.compose.ui.res.stringResource import androidx.compose.ui.unit.IntOffset import androidx.compose.ui.unit.IntSize import androidx.compose.ui.unit.dp import de.jeanlucmakiola.calendula.R +import de.jeanlucmakiola.calendula.data.prefs.SettingsPrefs import de.jeanlucmakiola.calendula.domain.EventInstance +import de.jeanlucmakiola.calendula.domain.instantIn +import de.jeanlucmakiola.calendula.domain.repeatedHourOffsetAt +import de.jeanlucmakiola.calendula.domain.repicked +import de.jeanlucmakiola.calendula.domain.toFormTime +import de.jeanlucmakiola.calendula.domain.resolveIn import de.jeanlucmakiola.calendula.ui.week.MINUTES_PER_DAY import de.jeanlucmakiola.calendula.ui.week.TimedBlock +import de.jeanlucmakiola.calendula.ui.week.minutesPast +import de.jeanlucmakiola.calendula.ui.week.wallClockEndMinutes +import de.jeanlucmakiola.calendula.ui.week.wallClockMinutes +import de.jeanlucmakiola.floret.identity.LocalFloretDarkTheme import de.jeanlucmakiola.floret.identity.rememberReduceMotion import de.jeanlucmakiola.floret.locale.currentLocale import kotlinx.coroutines.delay @@ -50,13 +64,15 @@ import kotlinx.coroutines.flow.StateFlow import kotlinx.datetime.DateTimeUnit import kotlinx.datetime.LocalDate import kotlinx.datetime.atStartOfDayIn +import kotlinx.datetime.UtcOffset import kotlinx.datetime.plus import kotlinx.datetime.LocalDateTime import kotlinx.datetime.LocalTime import kotlinx.datetime.TimeZone -import kotlinx.datetime.toInstant import kotlinx.datetime.toLocalDateTime import kotlin.math.roundToInt +import kotlin.time.Duration +import kotlin.time.Duration.Companion.minutes import kotlin.time.Instant /** Start granularity a dragged block snaps to, matching the big calendar apps. */ @@ -97,11 +113,28 @@ data class TimelineDrag( * drop lands, so it is dropped once the gesture ends ([finish]). */ val edgeOnly: Boolean = false, + /** + * The minute of its day the gutter badge names — the top edge, or for a + * bottom-edge resize the end being dragged (#141). + */ + val markerMin: Int = startMin, ) { - /** What the snap haptics key off: one tick per changed slot, not per frame. */ - val slot: Pair get() = date to startMin + /** + * What the snap haptics key off: one tick per changed slot, not per frame. + * Carries the length, which is all a bottom-edge resize changes. + */ + val slot: Triple get() = Triple(date, startMin, eventSpanMin) } +/** The event a long press left selected (#141). */ +data class TimelineSelection( + val event: EventInstance, + /** Set from a move or resize of it until the grid shows where it landed. */ + val moved: Boolean = false, + /** Selected by letting go of a lifted block, which then keeps that lift as it is. */ + val fromLift: Boolean = false, +) + /** * One day column's share of a dragged event, ready to draw. Both halves of an * event crossing midnight are previewed, whichever half the finger picked up: @@ -248,6 +281,142 @@ data class TimelineDrop( val clipOffsetMin: Int = 0, ) +/** The id a drafted block's stand-in event carries, which no provider row has (#153). */ +private const val DRAFT_ID = Long.MIN_VALUE + +/** Whether this is the stand-in for a block drafted on an empty slot, not a real event. */ +val EventInstance.isDraft: Boolean get() = instanceId == DRAFT_ID + +/** A drafted block's stand-in event, [minutes] long from [start]. */ +fun draftEvent(title: String, color: Int, start: Instant, minutes: Int): EventInstance = EventInstance( + instanceId = DRAFT_ID, + eventId = DRAFT_ID, + calendarId = DRAFT_ID, + title = title, + start = start, + end = start + minutes.minutes, + isAllDay = false, + color = color, + location = null, +) + +/** Where a long press [minutes] down the column starts its draft, snapped down to the slot. */ +internal fun draftStartMin(minutes: Float): Int = + (minutes / DRAG_SNAP_MINUTES).toInt().times(DRAG_SNAP_MINUTES) + .coerceIn(0, MINUTES_PER_DAY - DRAG_SNAP_MINUTES) + +/** The part of [draft] on [date] as a full-width block, or null if none of it falls there. */ +internal fun draftBlock(draft: EventInstance, date: LocalDate, zone: TimeZone): TimedBlock? { + // Clipped to the day the way the grid lays out events, so it's drawn the same across a DST change (#387). + // The end is exclusive, so a draft ending at midnight belongs to the day before. + val start = maxOf(draft.start, date.atStartOfDayIn(zone)) + val end = minOf(draft.end, date.plus(1, DateTimeUnit.DAY).atStartOfDayIn(zone)) + if (end <= start) return null + val startMin = wallClockMinutes(start, date, zone) + val endMin = wallClockEndMinutes(startMin, start, end, date, zone).coerceAtMost(MINUTES_PER_DAY) + return TimedBlock(draft, startMin, endMin, lane = 0, laneCount = 1) +} + +/** Which end of an event a resize handle moves (#141). */ +enum class ResizeEdge { Top, Bottom } + +/** Where a finished resize asks its event to begin and end. */ +data class TimelineResizeDrop(val event: EventInstance, val start: Instant, val end: Instant) + +/** + * [event] resized by its [edge] to the span [startMin]..+[spanMin] from [date]'s + * midnight. Only the held edge moves. The other keeps its own instant rather than + * a round trip through the grid, where an end in the fall-back hour's repeat is + * drawn to that hour's end, not at its own time (#387). In a repeated hour, the + * held edge takes the pass that matches the direction it was dragged from where + * it was drawn (see [repicked]). An end takes a pass the grid draws at the drop + * point, so the block settles under the finger. + */ +internal fun resizedDrop( + event: EventInstance, + edge: ResizeEdge?, + date: LocalDate, + startMin: Int, + spanMin: Int, + zone: TimeZone, +): TimelineResizeDrop { + val drawn = wallClockSpan(event, zone) + return TimelineResizeDrop( + event = event, + start = if (edge == ResizeEdge.Top) { + event.start.toFormTime(zone).repicked( + wallClockTime(date, startMin), + zone, + shownAt = wallClockTime(drawn.day, drawn.startMin), + notAfter = event.end, + ).instantIn(zone) + } else { + event.start + }, + end = if (edge == ResizeEdge.Bottom) { + val picked = wallClockTime(date, startMin + spanMin) + val pickedMin = (picked.date.toEpochDays() - drawn.day.toEpochDays()).toInt() * MINUTES_PER_DAY + + picked.time.toSecondOfDay() / 60 + event.end.toFormTime(zone).repicked( + picked, + zone, + shownAt = wallClockTime(drawn.day, drawn.endMin), + notBefore = event.start, + drawable = { wallClockEndMinutes(drawn.startMin, event.start, it, drawn.day, zone) == pickedMin }, + ).instantIn(zone) + } else { + event.end + }, + ) +} + +/** + * The span after dragging [edge] to [edgeMin] in day [edgeDay], in minutes from the + * start day's midnight. Snapped, and at least one snap step long. + */ +internal fun resizedSpan( + edge: ResizeEdge, + startMin: Int, + endMin: Int, + edgeMin: Float, + edgeDay: Int? = null, +): Pair { + // An edge dragged into a day past the other end changes nothing. + if (edgeDay != null) { + val endDay = (endMin - 1).floorDiv(MINUTES_PER_DAY).coerceAtLeast(0) + val wrongWay = when (edge) { + ResizeEdge.Top -> edgeDay > endDay + ResizeEdge.Bottom -> edgeDay < startMin.floorDiv(MINUTES_PER_DAY) + } + if (wrongWay) return startMin to endMin + } + val snapped = snapToSlot(edgeMin) + return when (edge) { + ResizeEdge.Top -> minOf(snapped, endMin - DRAG_SNAP_MINUTES) to endMin + ResizeEdge.Bottom -> startMin to maxOf(snapped, startMin + DRAG_SNAP_MINUTES) + } +} + +/** [minutes] rounded to the nearest [DRAG_SNAP_MINUTES] slot. */ +internal fun snapToSlot(minutes: Float): Int = (minutes / DRAG_SNAP_MINUTES).roundToInt() * DRAG_SNAP_MINUTES + +/** [minutes] snapped, kept at [held] until three quarters of a step away. */ +internal fun stickySnap(minutes: Float, held: Int?): Int { + if (held != null && kotlin.math.abs(minutes - held) < DRAG_SNAP_MINUTES * 0.75f) return held + return snapToSlot(minutes) +} + +/** How far past its column's side the finger has to go before a resize changes day. */ +private const val COLUMN_HYSTERESIS = 0.25f + +/** The column under [position], kept at [held] until [COLUMN_HYSTERESIS] into another. */ +internal fun stickyColumn(position: Float, held: Int?, lastIndex: Int): Int { + val under = position.toInt().coerceIn(0, lastIndex) + if (held == null) return under + val stays = position >= held - COLUMN_HYSTERESIS && position < held + 1 + COLUMN_HYSTERESIS + return if (stays) held else under +} + /** * The timeline's live geometry, republished on every layout. Plain fields rather * than snapshot state: it changes on every scroll frame, and the drag loop reads @@ -302,6 +471,10 @@ class TimelineDragController { var settling: TimelineDrag? by mutableStateOf(null) private set + /** How many real drops this controller has handed back. */ + var drops by mutableIntStateOf(0) + private set + /** * Which block is lifted, and whether anything is. Separate snapshot state * from [drag], which changes every frame, so blocks that only need "am I the @@ -320,10 +493,92 @@ class TimelineDragController { */ private var settledOrigin: Pair? by mutableStateOf(null) + /** How long a block drafted on an empty slot starts out, in minutes (#153). */ + var draftMinutes: Int = SettingsPrefs.DEFAULT_EVENT_DURATION + + /** The selected event, if any — see [TimelineSelection]. */ + var selection: TimelineSelection? by mutableStateOf(null) + private set + + fun select(event: EventInstance, moved: Boolean = false, fromLift: Boolean = false) { + if (selection?.event?.instanceId != event.instanceId) selectionCovered = false + selection = TimelineSelection(event, moved, fromLift) + } + + fun deselect() { + if (selection?.event?.isDraft == true && settling?.event?.isDraft == true) release() + selection = null + selectionCovered = false + } + + /** The events of the blocks on screen that show the selection; none for a while ends it. */ + val selectedCandidates = mutableStateListOf() + + fun noteSelectedBlock(event: EventInstance, shown: Boolean) { + if (shown) selectedCandidates.add(event) else selectedCandidates.remove(event) + } + + /** + * Once a move of the selected event has settled, point the selection at the + * row it landed as. A new event id wins: a single moved occurrence is written + * as an exception, and another occurrence of its series may share its time. + */ + fun settleMovedSelection() { + val current = selection?.takeIf { it.moved } ?: return + if (isDragging || settling != null) return + val landed = selectedCandidates.filter { it.instanceId != current.event.instanceId } + // Only the original row left: the move was abandoned, and it still stands. + val chosen = landed.firstOrNull { it.eventId != current.event.eventId } + ?: landed.firstOrNull() ?: selectedCandidates.firstOrNull() ?: return + selection = current.copy(event = chosen, moved = false) + } + + /** Whether the selected block's bottom sits where the action bar would cover it. */ + var selectionCovered: Boolean by mutableStateOf(false) + private set + + /** + * Whether [block] is the selected event: by instance, by series and start, and + * just after a move by title and times, since a moved occurrence gets new ids. + */ + fun isSelected(block: TimedBlock): Boolean { + val current = selection ?: return false + val selected = current.event + val event = block.event + return event.instanceId == selected.instanceId || + (event.eventId == selected.eventId && event.start == selected.start) || + ( + current.moved && + event.calendarId == selected.calendarId && + event.title.isNotBlank() && + event.title == selected.title && + event.start == selected.start && + event.end == selected.end + ) + } + + /** Point the selection at [block]'s event, so the bar acts on the row now there. */ + fun adoptSelection(block: TimedBlock) { + val current = selection?.takeIf { !it.moved } ?: return + if (current.event != block.event) selection = current.copy(event = block.event) + } + /** Whether a finger is on a block right now — [settling] is not dragging. */ var isDragging: Boolean by mutableStateOf(false) private set + /** Whether the finger has moved since the pickup; only then may the view auto-scroll. */ + var pointerMoved: Boolean by mutableStateOf(false) + private set + + /** Touch slop, past which the finger counts as having moved. */ + var slopPx: Float = 0f + + private var pickupPointer = Offset.Zero + + /** The end a settling resize asked for, which the grid has to show before it settles. */ + private var settledEnd: Instant? = null + /** * Whether the grid itself now draws the settled drop at its landing slot. * The copy may only be handed back once this is true, or the source ghost @@ -332,6 +587,10 @@ class TimelineDragController { var settledOnGrid: Boolean by mutableStateOf(false) private set + /** Whether the settling drop is the selected event, whose block lands still lifted. */ + var settlingSelected: Boolean = false + private set + /** * The abandoned-move counter, read at the drop so the mark can't be a * composition behind the tick it is compared against. @@ -353,6 +612,10 @@ class TimelineDragController { * finger is on; this is what turns where it lands back into an event start. */ private var clipOffsetMin = 0 + private var dragZone: TimeZone? = null + private var dragDuration = Duration.ZERO + /** The dragged event's pass of a repeated hour, worked out once per drag (#387). */ + private var dragKept: UtcOffset? = null /** What the picked-up block drew its title over — see [TimelineDrag.titleLines]. */ private var titleLines = 0 @@ -361,44 +624,73 @@ class TimelineDragController { * The slot the block already occupied when it was picked up — not the same * as its start, since the target snaps to the grid (09:07 lifts to 09:00). */ - private var originSlot: Pair? = null + private var originSlot: Triple? = null + + /** The resize in progress, or null for a plain drag (#141). */ + private var resize: ResizeSession? = null fun begin( block: TimedBlock, clipOffsetMin: Int, + zone: TimeZone, titleLines: Int, pointerInRoot: Offset, blockInRoot: Offset, ) { + // The selected event keeps its selection through a drag; any other ends it. + if (!isSelected(block)) deselect() source = block this.clipOffsetMin = clipOffsetMin + dragZone = zone + dragDuration = (block.event.end - block.event.start).coerceAtLeast(Duration.ZERO) + dragKept = zone.repeatedHourOffsetAt(block.event.start) this.titleLines = titleLines settling = null isDragging = true liftedInstanceId = block.event.instanceId grab = pointerInRoot - blockInRoot pointer = pointerInRoot + pickupPointer = pointerInRoot + pointerMoved = false originSlot = null recompute() originSlot = drag?.slot } + /** + * Draft a block on an empty slot and lift it at once (#153). It is selected + * from the start, so it keeps its handles and bar once the finger lets go. + */ + fun beginDraft(block: TimedBlock, zone: TimeZone, pointerInRoot: Offset, blockInRoot: Offset) { + deselect() + select(block.event) + begin(block, clipOffsetMin = 0, zone, titleLines = 1, pointerInRoot = pointerInRoot, blockInRoot = blockInRoot) + } + fun move(pointerInRoot: Offset) { pointer = pointerInRoot + if (!pointerMoved && (pointerInRoot - pickupPointer).getDistance() > slopPx) pointerMoved = true recompute() } fun cancel() { + resize = null source = null clipOffsetMin = 0 + dragZone = null + dragDuration = Duration.ZERO + dragKept = null titleLines = 0 isDragging = false + pointerMoved = false liftedInstanceId = null originSlot = null drag = null settling = null settledOnGrid = false settledOrigin = null + settledEnd = null + settlingSelected = false } /** @@ -429,8 +721,11 @@ class TimelineDragController { val offset = (date.toEpochDays() - landed.date.toEpochDays()).toInt() val slice = dragSlices(landed.eventStartMin, landed.eventSpanMin, offset..offset) .firstOrNull() ?: return + val end = settledEnd settledOnGrid = blocks.any { block -> block.startMin == slice.startMin && + // A resize may keep its start, so its end has to have landed too. + (end == null || block.event.end == end) && ( block.event.eventId == landed.event.eventId || ( @@ -452,6 +747,15 @@ class TimelineDragController { val clipOffset = clipOffsetMin cancel() if (landed == null || landed.slot == origin) return null + // A draft dropped on a day off screen would vanish, so it stays where it was (#153). + if (landed.edgeOnly && landed.event.isDraft) return null + settle(landed) + return TimelineDrop(landed.event, landed.date, landed.startMin, clipOffset) + } + + /** Keep [landed]'s copy on the target as [settling] until [release]; [end] is a resize's. */ + private fun settle(landed: TimelineDrag, end: Instant? = null) { + settlingSelected = selection?.event?.instanceId == landed.event.instanceId // An edge piece is a hint for the finger, not a preview of the landing // slot: the event belongs to a day this timeline has no column for, so // [noteGrid] can never seat it and it would sit at the top of today for @@ -460,7 +764,139 @@ class TimelineDragController { liftedInstanceId = landed.event.instanceId settledOrigin = landed.event.eventId to landed.event.start settledAbandonedMark = abandonedTicks?.value ?: 0 - return TimelineDrop(landed.event, landed.date, landed.startMin, clipOffset) + settledEnd = end + drops++ + } + + /** + * Grab one edge of [block] to resize it (#141). The edge follows the finger + * across days as a drag does; the other stays where it is. + */ + fun beginResize( + block: TimedBlock, + edge: ResizeEdge, + zone: TimeZone, + titleLines: Int, + pointerInRoot: Offset, + ) { + val span = wallClockSpan(block.event, zone) + val session = ResizeSession(edge, span.day, span.startMin, span.endMin) + source = block + resize = session + clipOffsetMin = 0 + this.titleLines = titleLines + settling = null + isDragging = true + pointerMoved = true + liftedInstanceId = block.event.instanceId + pointer = pointerInRoot + // Measured from the edge's own column: the handle overhangs into the next. + val edgeDay = if (edge == ResizeEdge.Top) 0 else (session.endMin - 1).floorDiv(MINUTES_PER_DAY).coerceAtLeast(0) + val edgeIndex = geometry.days.indexOf(span.day.plus(edgeDay, DateTimeUnit.DAY)) + session.column = edgeIndex.takeIf { it >= 0 } + ?.let { column(it) } + session.grabMin = (pointerResizeMinutes(session) ?: 0f) - + if (edge == ResizeEdge.Top) session.startMin else session.endMin + originSlot = null + recompute() + originSlot = drag?.slot + } + + /** The slot the gesture would land on, changing once per snap rather than per frame. */ + private val landingSlot by derivedStateOf { drag?.slot } + + /** + * The dragged event at the times letting go now would give it, worked out as + * [finish] and [finishResize] do. Null while it is still on its own slot (#141). + */ + fun preview(zone: TimeZone): EventInstance? { + val (date, startMin, spanMin) = landingSlot?.takeIf { it != originSlot } ?: return null + val event = source?.event ?: return null + val edge = resize?.edge + if (edge != null) { + val drop = resizedDrop(event, edge, date, startMin, spanMin, zone) + return event.copy(start = drop.start, end = drop.end) + } + val start = TimelineDrop(event, date, startMin, clipOffsetMin).startInstant(zone) + return event.copy(start = start, end = start + dragDuration) + } + + /** + * End a resize, handing back the event's new span — null when it never + * resolved or came back to the length it started at. Settles as [finish] does. + */ + fun finishResize(zone: TimeZone): TimelineResizeDrop? { + val landed = drag + val origin = originSlot + val edge = resize?.edge + cancel() + if (landed == null || landed.slot == origin) return null + val drop = resizedDrop(landed.event, edge, landed.date, landed.eventStartMin, landed.eventSpanMin, zone) + settle(landed, end = drop.end) + return drop + } + + /** + * Where the finger is, in minutes from the resized event's start day — + * past 1440 in a later column, negative in an earlier one. + */ + private fun pointerResizeMinutes(session: ResizeSession): Float? { + val grid = geometry.grid?.takeIf { it.isAttached } ?: return null + val hourPx = geometry.hourPx + val columnPx = geometry.columnWidthPx + val days = geometry.days + if (hourPx <= 0f || columnPx <= 0f || days.isEmpty()) return null + val origin = grid.positionInRoot() + val held = stickyColumn( + position = (pointer.x - origin.x) / columnPx, + held = session.column, + lastIndex = days.lastIndex, + ) + session.column = held + val dayOffset = (days[column(held)].toEpochDays() - session.day.toEpochDays()).toInt() + session.edgeDay = dayOffset + return dayOffset * MINUTES_PER_DAY + (pointer.y - origin.y) / hourPx * 60f + } + + private fun recomputeResize(session: ResizeSession) { + val block = source ?: return + val edge = session.edge + val day = session.day + val raw = pointerResizeMinutes(session) ?: return + val slot = stickySnap(raw - session.grabMin, session.slot) + session.slot = slot + val (start, end) = resizedSpan(edge, session.startMin, session.endMin, slot.toFloat(), session.edgeDay) + val days = geometry.days + val origin = geometry.grid?.takeIf { it.isAttached }?.positionInRoot() ?: return + // Which column the start day sits in, possibly off either end of the view. + val startIndex = (day.toEpochDays() - days.first().toEpochDays()).toInt() + val visible = -startIndex..days.lastIndex - startIndex + val slices = dragSlices(start, end - start, within = visible) + drag = TimelineDrag( + event = block.event, + date = day, + startMin = start, + eventStartMin = start, + eventSpanMin = end - start, + titleLines = titleLines, + pieces = pieces(slices, startIndex, origin), + edgeOnly = slices.isEmpty(), + markerMin = if (edge == ResizeEdge.Top) { + start.mod(MINUTES_PER_DAY) + } else { + end - (end - 1).floorDiv(MINUTES_PER_DAY) * MINUTES_PER_DAY + }, + ) + } + + /** Note whether the action bar would cover the selected block's bottom handle (#141). */ + fun noteSelectedBottom(block: LayoutCoordinates, extraPx: Float, clearancePx: Float) { + val viewport = geometry.viewport?.takeIf { it.isAttached } ?: return + if (!block.isAttached) return + val port = viewport.boundsInRoot() + val bottom = block.positionInRoot().y + block.size.height + extraPx + val covered = bottom > port.bottom - clearancePx + if (covered != selectionCovered) selectionCovered = covered } /** @@ -477,6 +913,8 @@ class TimelineDragController { fun release() { settling = null settledOnGrid = false + settledEnd = null + settlingSelected = false handOver() } @@ -486,6 +924,10 @@ class TimelineDragController { * no move events while auto-scroll walks the content underneath it. */ fun recompute() { + resize?.let { + recomputeResize(it) + return + } val block = source ?: return val grid = geometry.grid?.takeIf { it.isAttached } ?: return val hourPx = geometry.hourPx @@ -495,14 +937,22 @@ class TimelineDragController { val origin = grid.positionInRoot() val rawMinutes = (pointer.y - grab.y - origin.y) / hourPx * 60f - val snapped = (rawMinutes / DRAG_SNAP_MINUTES).roundToInt() * DRAG_SNAP_MINUTES - val eventSpan = (block.event.end - block.event.start).inWholeMinutes.toInt() - .coerceAtLeast(0) - val floor = dragFloorMin(clipOffsetMin, eventSpan) - val startMin = snapped.coerceIn(floor, MINUTES_PER_DAY - DRAG_SNAP_MINUTES) - val eventStartMin = startMin - clipOffsetMin - val column = ((pointer.x - origin.x) / columnPx).toInt().coerceIn(0, days.lastIndex) - val dayIndex = if (geometry.isRtl) days.lastIndex - column else column + val snapped = snapToSlot(rawMinutes) + val zone = dragZone ?: return + val dayIndex = column(((pointer.x - origin.x) / columnPx).toInt().coerceIn(0, days.lastIndex)) + val target = days[dayIndex] + val keep = dragKept + // Measured where it would land: the drop keeps the real duration, which in + // wall clock gains or loses the hour of a DST change it crosses (#387). + val floor = dragFloorMin( + clipOffsetMin, + wallClockSpanMinutes(target, snapped - clipOffsetMin, dragDuration, zone, keep), + ) + val held = snapped.coerceIn(floor, MINUTES_PER_DAY - DRAG_SNAP_MINUTES) - clipOffsetMin + // A start in the spring-forward gap lands an hour on; show it there. + val eventStartMin = wallClockInstant(target, held, zone, keep).minutesPast(target, zone) + val startMin = (eventStartMin + clipOffsetMin).coerceAtMost(MINUTES_PER_DAY - DRAG_SNAP_MINUTES) + val eventSpan = wallClockSpanMinutes(target, eventStartMin, dragDuration, zone, keep) val visible = -dayIndex..days.lastIndex - dayIndex val onGrid = dragSlices(eventStartMin, eventSpan, within = visible) val slices = onGrid.ifEmpty { @@ -517,28 +967,34 @@ class TimelineDragController { titleLines = titleLines, // Bounded to the columns this timeline actually shows: a day it // doesn't has no piece to draw. The write is unaffected. - pieces = slices - .map { slice -> - val day = dayIndex + slice.dayOffset - val col = if (geometry.isRtl) days.lastIndex - day else day - val bounds = dragPieceBounds(slice, hourPx, geometry.blockInsetPx) - TimelineDragPiece( - topLeftInRoot = Offset( - x = origin.x + col * columnPx, - y = origin.y + bounds.top, - ), - sizePx = IntSize( - (columnPx - geometry.columnGapPx).roundToInt(), - bounds.height.roundToInt(), - ), - continuesBefore = slice.continuesBefore, - continuesAfter = slice.continuesAfter, - ) - }, + pieces = pieces(slices, dayIndex, origin), edgeOnly = onGrid.isEmpty(), ) } + /** [slices] as floating pieces, the first slice's day being [dayIndex] in the shown days. */ + private fun pieces(slices: List, dayIndex: Int, origin: Offset): List { + val columnPx = geometry.columnWidthPx + return slices.map { slice -> + val bounds = dragPieceBounds(slice, geometry.hourPx, geometry.blockInsetPx) + TimelineDragPiece( + topLeftInRoot = Offset( + x = origin.x + column(dayIndex + slice.dayOffset) * columnPx, + y = origin.y + bounds.top, + ), + sizePx = IntSize( + (columnPx - geometry.columnGapPx).roundToInt(), + bounds.height.roundToInt(), + ), + continuesBefore = slice.continuesBefore, + continuesAfter = slice.continuesAfter, + ) + } + } + + /** The on-screen column of a day index, and back: right-to-left lays the days out mirrored. */ + private fun column(index: Int): Int = if (geometry.isRtl) geometry.days.lastIndex - index else index + /** * Hold the scroll for the whole drag and nudge it once per frame while the * finger sits near an edge. One `scroll` call, since a loop of @@ -571,12 +1027,34 @@ class TimelineDragController { } } +/** One resize gesture (#141): the edge it drags, and the edges as minutes from [day]'s midnight. */ +private class ResizeSession( + val edge: ResizeEdge, + /** The day the resized event starts on. */ + val day: LocalDate, + val startMin: Int, + val endMin: Int, +) { + /** How far the finger sits past the edge it grabbed, so the edge doesn't jump to it. */ + var grabMin = 0f + + /** The column the resized edge is in, held until the finger is well into another. */ + var column: Int? = null + + /** The slot the resized edge sits on, held against a finger trembling between two. */ + var slot: Int? = null + + /** The day, counted from the event's start day, the finger is resizing in. */ + var edgeDay = 0 +} + @Composable fun rememberTimelineDragController(): TimelineDragController { val controller = remember { TimelineDragController() } val density = LocalDensity.current controller.geometry.edgePx = with(density) { AUTO_SCROLL_EDGE.toPx() } controller.geometry.stepPx = with(density) { AUTO_SCROLL_STEP.toPx() } + controller.slopPx = LocalViewConfiguration.current.touchSlop controller.abandonedTicks = LocalEventMove.current?.abandoned return controller } @@ -589,10 +1067,7 @@ fun rememberTimelineDragController(): TimelineDragController { * so the offset has to come back off at the drop (#253). */ fun TimedBlock.clipOffsetMinutes(day: LocalDate, zone: TimeZone): Int { - val start = event.start.toLocalDateTime(zone) - val days = (day.toEpochDays() - start.date.toEpochDays()).toInt() - val minutes = days * MINUTES_PER_DAY + startMin - start.time.toSecondOfDay() / 60 - return minutes.coerceAtLeast(0) + return (startMin - event.start.minutesPast(day, zone)).coerceAtLeast(0) } /** @@ -613,15 +1088,58 @@ fun TimedBlock.continuesAfter(day: LocalDate, zone: TimeZone): Boolean = * of its own; `toInstant` resolves it forward by the missing hour, and the block * visibly settles there. */ -fun TimelineDrop.startInstant(zone: TimeZone): Instant { - // Wall clock throughout, and past this day at either end: a block's top edge - // can be dragged above its midnight and a tail's below the next one, so the - // start is resolved as a day plus a minute of it rather than as an offset - // from an instant — which would shift by an hour across a DST boundary. - val fromMidnight = startMin - clipOffsetMin - val day = date.plus(fromMidnight.floorDiv(MINUTES_PER_DAY), DateTimeUnit.DAY) - val minute = fromMidnight.mod(MINUTES_PER_DAY) - return LocalDateTime(day, LocalTime(minute / 60, minute % 60)).toInstant(zone) +fun TimelineDrop.startInstant(zone: TimeZone): Instant = + wallClockInstant(date, startMin - clipOffsetMin, zone, kept = zone.repeatedHourOffsetAt(event.start)) + +/** + * The wall-clock minutes an event lasting [duration] covers when it starts + * [startMin] past [date]'s midnight in [zone] — its real length, give or take a + * DST change in between (#387). + */ +internal fun wallClockSpanMinutes( + date: LocalDate, + startMin: Int, + duration: Duration, + zone: TimeZone, + kept: UtcOffset? = null, +): Int { + val start = wallClockInstant(date, startMin, zone, kept) + return wallClockEndMinutes(startMin, start, start + duration, date, zone) - startMin +} + +/** + * [minutes] past [date]'s midnight, either way past it, as wall clock in [zone] + * (DST-safe). A time the fall-back hour repeats lands on its earlier pass, unless + * [kept] is its later one: an event there stays on it (#387). Pass + * [repeatedHourOffsetAt] of the event's time, which is null outside the hour — + * such an instant says nothing about which pass the grid slot means, so a drop + * never depends on the season the event came from. + */ +fun wallClockInstant(date: LocalDate, minutes: Int, zone: TimeZone, kept: UtcOffset? = null): Instant = + wallClockTime(date, minutes).resolveIn(zone, kept) + +/** The wall-clock time [minutes] past [date]'s midnight, on a later day past 1440. */ +fun wallClockTime(date: LocalDate, minutes: Int): LocalDateTime { + val day = date.plus(minutes.floorDiv(MINUTES_PER_DAY), DateTimeUnit.DAY) + val minute = minutes.mod(MINUTES_PER_DAY) + return LocalDateTime(day, LocalTime(minute / 60, minute % 60)) +} + +/** An event's span as wall-clock minutes from its start day's midnight. */ +data class WallClockSpan(val day: LocalDate, val startMin: Int, val endMin: Int) + +/** + * [event]'s [WallClockSpan], its end past 1440 when it ends on a later day + * (DST-safe). One ending in the fall-back hour's repeat ends where that hour does. + */ +fun wallClockSpan(event: EventInstance, zone: TimeZone): WallClockSpan { + val start = event.start.toLocalDateTime(zone) + val startMin = start.time.toSecondOfDay() / 60 + return WallClockSpan( + start.date, + startMin, + wallClockEndMinutes(startMin, event.start, event.end, start.date, zone), + ) } /** @@ -651,7 +1169,7 @@ const val SETTLE_FADE_MILLIS: Int = 250 fun TimelineDragOverlay(controller: TimelineDragController, modifier: Modifier = Modifier) { var origin by remember { mutableStateOf(Offset.Zero) } val density = LocalDensity.current - val dark = isSystemInDarkTheme() + val dark = LocalFloretDarkTheme.current val use24Hour = LocalUse24HourFormat.current val locale = currentLocale() val reduceMotion = rememberReduceMotion() @@ -659,9 +1177,11 @@ fun TimelineDragOverlay(controller: TimelineDragController, modifier: Modifier = // Both live here rather than beside the controller: they read [drag], which // changes every frame, and this composable is the one that is meant to. - DragSnapHaptics(controller.drag?.slot) - LaunchedEffect(controller.isDragging) { - if (controller.isDragging) controller.autoScroll() + DragSnapHaptics(controller.drag?.slot, controller.drops) + // Only once the finger has moved: a long press held near an edge must not + // scroll the drop target out from under a finger that only means to select. + LaunchedEffect(controller.isDragging && controller.pointerMoved) { + if (controller.isDragging && controller.pointerMoved) controller.autoScroll() } // Hold the landed copy until the write is done — including the time a // recurring drop's scope dialog is up — and then until the grid draws the @@ -693,7 +1213,8 @@ fun TimelineDragOverlay(controller: TimelineDragController, modifier: Modifier = // Landed: the copy sinks back to the grid's own plane while the write runs. val landed = controller.drag == null val lift by animateFloatAsState( - targetValue = if (landed || reduceMotion) 0f else 1f, + // A selected event's block is lifted too: sinking first made it shrink, then grow back. + targetValue = if (reduceMotion || (landed && !controller.settlingSelected)) 0f else 1f, label = "drag-lift", ) val copyAlpha by animateFloatAsState( @@ -870,7 +1391,7 @@ private fun DragCopy( Text( text = label, // As the block it lifted off sets its own time (#219). - style = MaterialTheme.typography.labelSmall.asEventTime(), + style = rememberPackedLines(MaterialTheme.typography.labelSmall.asEventTime()), maxLines = timeMaxLines, overflow = overflow.overflow, softWrap = overflow.softWrap, @@ -880,3 +1401,30 @@ private fun DragCopy( } } } + +/** How far a selected block is lifted, 0 to 1 (#141); [snap] takes it over at once. */ +@Composable +fun selectionLift(selected: Boolean, snap: Boolean = false): Float { + val reduceMotion = rememberReduceMotion() + val spec = MaterialTheme.motionScheme.fastSpatialSpec() + val raise = remember { Animatable(if (selected) 1f else 0f) } + LaunchedEffect(selected) { + val target = if (selected) 1f else 0f + if (reduceMotion || (selected && snap)) raise.snapTo(target) else raise.animateTo(target, spec) + } + // The effect runs a frame late, and that frame would show the block unlifted. + return if (selected && snap) 1f else raise.value +} + +/** + * A selected block raised off the grid, the way a dragged copy is: scaled from + * its top edge so the text doesn't creep, with a shadow in the block's shape. + */ +fun Modifier.selectionLift(raise: Float, shape: Shape): Modifier = graphicsLayer { + transformOrigin = TransformOrigin(0.5f, 0f) + scaleX = 1f + 0.02f * raise + scaleY = 1f + 0.02f * raise + shadowElevation = 6.dp.toPx() * raise + this.shape = shape + clip = false +} diff --git a/app/src/main/java/de/jeanlucmakiola/calendula/ui/common/TimelineHours.kt b/app/src/main/java/de/jeanlucmakiola/calendula/ui/common/TimelineHours.kt index 1efb9869..56ab4c61 100644 --- a/app/src/main/java/de/jeanlucmakiola/calendula/ui/common/TimelineHours.kt +++ b/app/src/main/java/de/jeanlucmakiola/calendula/ui/common/TimelineHours.kt @@ -16,8 +16,6 @@ data class TimelineHours( val startHour: Int = DEFAULT_START_HOUR, val endHour: Int = DEFAULT_END_HOUR, ) { - val span: Int get() = endHour - startHour - companion object { const val DEFAULT_START_HOUR = 7 const val DEFAULT_END_HOUR = 22 diff --git a/app/src/main/java/de/jeanlucmakiola/calendula/ui/common/ViewPreview.kt b/app/src/main/java/de/jeanlucmakiola/calendula/ui/common/ViewPreview.kt deleted file mode 100644 index 670734e5..00000000 --- a/app/src/main/java/de/jeanlucmakiola/calendula/ui/common/ViewPreview.kt +++ /dev/null @@ -1,145 +0,0 @@ -package de.jeanlucmakiola.calendula.ui.common - -import androidx.compose.animation.Crossfade -import androidx.compose.animation.core.snap -import androidx.compose.animation.core.tween -import androidx.compose.foundation.background -import androidx.compose.foundation.layout.Box -import androidx.compose.foundation.layout.Column -import androidx.compose.foundation.layout.fillMaxSize -import androidx.compose.foundation.layout.fillMaxWidth -import androidx.compose.foundation.layout.padding -import androidx.compose.foundation.shape.RoundedCornerShape -import androidx.compose.material3.MaterialTheme -import androidx.compose.runtime.Composable -import androidx.compose.ui.Alignment -import androidx.compose.ui.Modifier -import androidx.compose.ui.draw.clip -import androidx.compose.ui.draw.clipToBounds -import androidx.compose.ui.graphics.TransformOrigin -import androidx.compose.ui.graphics.graphicsLayer -import androidx.compose.ui.input.pointer.PointerEventPass -import androidx.compose.ui.input.pointer.pointerInput -import androidx.compose.ui.layout.layout -import androidx.compose.ui.platform.LocalConfiguration -import androidx.compose.ui.semantics.clearAndSetSemantics -import androidx.compose.ui.unit.Constraints -import androidx.compose.ui.unit.Dp -import androidx.compose.ui.unit.dp -import de.jeanlucmakiola.floret.components.GroupedListInset -import de.jeanlucmakiola.floret.identity.rememberReduceMotion -import kotlin.math.roundToInt - -/** - * The viewport a view preview pretends to be: a phone's width by the height a - * calendar view gets under the top bar. Scaling every preview from one fixed - * height keeps them comparable — each shows the same slice of screen. - */ -internal val PREVIEW_VIEWPORT_HEIGHT = 440.dp - -/** - * Renders [content] at a full phone viewport and shrinks the finished layout - * into a box [height] tall, for the settings and onboarding choosers. Callers - * pass the *real* view composables, so a preview cannot drift from what it - * depicts. - * - * The [layout] below ignores the incoming constraints so the view measures at a - * phone viewport, and a [graphicsLayer] scale shrinks the result. - * `Modifier.requiredSize` is the obvious alternative but *centres* content that - * overflows its constraints, leaving only the bottom-right corner in the clip. - */ -@Composable -internal fun ScaledViewPreview( - height: Dp, - modifier: Modifier = Modifier, - content: @Composable () -> Unit, -) { - val screenWidth = LocalConfiguration.current.screenWidthDp.dp - val scale = height.value / PREVIEW_VIEWPORT_HEIGHT.value - - Box( - modifier = modifier - .clipToBounds() - .background(MaterialTheme.colorScheme.surface) - // A preview is a picture, not a control: swallow touches before the - // view's own clickables see them, and give screen readers one label - // instead of six weeks of day cells. - .pointerInput(Unit) { - awaitPointerEventScope { - while (true) { - awaitPointerEvent(PointerEventPass.Initial).changes - .forEach { it.consume() } - } - } - } - .clearAndSetSemantics { } - // Measure at a full phone viewport but report the scaled size, so the - // node occupies exactly what it draws. - .layout { measurable, _ -> - val fullWidth = screenWidth.roundToPx() - val fullHeight = PREVIEW_VIEWPORT_HEIGHT.roundToPx() - val placeable = measurable.measure(Constraints.fixed(fullWidth, fullHeight)) - layout((fullWidth * scale).roundToInt(), (fullHeight * scale).roundToInt()) { - placeable.place(0, 0) - } - } - .graphicsLayer { - scaleX = scale - scaleY = scale - transformOrigin = TransformOrigin(0f, 0f) - }, - ) { - Column(Modifier.fillMaxSize()) { content() } - } -} - -/** - * The stage every preview picker sets its preview on, cross-fading as [selected] - * changes. A preview draws the app's own surface, so a tonal plate gives it the - * edge it would otherwise lack on a chooser screen; the plate takes the width - * and outer radius of the grouped rows underneath so the two read as one stack. - * - * Only vertical spacing is the caller's to pass — the horizontal inset is the - * rows' own, and the alignment is the point. - */ -@Composable -internal fun ViewPreviewFrame( - selected: T, - label: String, - modifier: Modifier = Modifier, - content: @Composable (T) -> Unit, -) { - val reduceMotion = rememberReduceMotion() - Box( - modifier = modifier - .fillMaxWidth() - .padding(horizontal = GroupedListInset) - .clip(FRAME_SHAPE) - .background(MaterialTheme.colorScheme.surfaceContainerHigh) - .padding(FRAME_INSET), - contentAlignment = Alignment.Center, - ) { - Crossfade( - targetState = selected, - animationSpec = if (reduceMotion) snap() else tween(durationMillis = 250), - label = label, - ) { shown -> - // Each preview renders the real view at phone size and scales it - // down, so its own corners are square — the plate rounds them. - Box( - modifier = Modifier - .clip(PREVIEW_SHAPE) - .background(MaterialTheme.colorScheme.surface) - .clipToBounds(), - ) { - content(shown) - } - } - } -} - -private val FRAME_INSET = 8.dp - -/** The grouped rows' own outer radius, so the stack shares one silhouette. */ -private val FRAME_SHAPE = RoundedCornerShape(22.dp) -private val PREVIEW_SHAPE = RoundedCornerShape(12.dp) diff --git a/app/src/main/java/de/jeanlucmakiola/calendula/ui/day/DayPaging.kt b/app/src/main/java/de/jeanlucmakiola/calendula/ui/day/DayPaging.kt deleted file mode 100644 index b932d7df..00000000 --- a/app/src/main/java/de/jeanlucmakiola/calendula/ui/day/DayPaging.kt +++ /dev/null @@ -1,22 +0,0 @@ -package de.jeanlucmakiola.calendula.ui.day - -import kotlinx.datetime.DateTimeUnit -import kotlinx.datetime.LocalDate -import kotlinx.datetime.daysUntil -import kotlinx.datetime.plus - -/** Pages the day pager spans — a little under four centuries, centred on [PAGE_EPOCH]. */ -internal const val DAY_PAGE_COUNT: Int = 140_000 - -private const val EPOCH_PAGE = DAY_PAGE_COUNT / 2 - -/** The day at [EPOCH_PAGE]; any date works, it only has to stay fixed. */ -private val PAGE_EPOCH = LocalDate(2000, 1, 1) - -/** The day shown on pager [page]. */ -internal fun dayForPage(page: Int): LocalDate = - PAGE_EPOCH.plus(page - EPOCH_PAGE, DateTimeUnit.DAY) - -/** The pager page showing [date]. */ -internal fun dayPageFor(date: LocalDate): Int = - (EPOCH_PAGE + PAGE_EPOCH.daysUntil(date)).coerceIn(0, DAY_PAGE_COUNT - 1) diff --git a/app/src/main/java/de/jeanlucmakiola/calendula/ui/detail/EventDetailScreen.kt b/app/src/main/java/de/jeanlucmakiola/calendula/ui/detail/EventDetailScreen.kt index 5c5c7dcb..fc723aca 100644 --- a/app/src/main/java/de/jeanlucmakiola/calendula/ui/detail/EventDetailScreen.kt +++ b/app/src/main/java/de/jeanlucmakiola/calendula/ui/detail/EventDetailScreen.kt @@ -1,19 +1,13 @@ package de.jeanlucmakiola.calendula.ui.detail -import android.Manifest import android.content.Context import android.content.Intent -import android.content.pm.PackageManager import android.net.Uri import android.widget.Toast -import androidx.activity.compose.rememberLauncherForActivityResult -import androidx.activity.result.contract.ActivityResultContracts import androidx.compose.foundation.background -import androidx.compose.foundation.isSystemInDarkTheme import androidx.compose.foundation.layout.Arrangement import androidx.compose.foundation.layout.Box import androidx.compose.foundation.layout.Column -import androidx.compose.foundation.layout.ColumnScope import androidx.compose.foundation.layout.ExperimentalLayoutApi import androidx.compose.foundation.layout.FlowRow import androidx.compose.foundation.layout.Row @@ -22,7 +16,6 @@ import androidx.compose.foundation.layout.fillMaxSize import androidx.compose.foundation.layout.fillMaxWidth import androidx.compose.foundation.layout.height import androidx.compose.foundation.layout.padding -import androidx.compose.foundation.layout.size import androidx.compose.foundation.layout.width import androidx.compose.foundation.rememberScrollState import androidx.compose.foundation.shape.RoundedCornerShape @@ -41,7 +34,6 @@ import androidx.compose.material.icons.filled.Public import androidx.compose.material.icons.filled.Repeat import androidx.compose.material.icons.filled.Schedule import androidx.compose.material.icons.filled.Share -import androidx.compose.material3.AlertDialog import androidx.compose.material3.ExperimentalMaterial3Api import androidx.compose.material3.Icon import androidx.compose.material3.IconButton @@ -51,7 +43,6 @@ import androidx.compose.material3.SnackbarHost import androidx.compose.material3.SnackbarHostState import androidx.compose.material3.Surface import androidx.compose.material3.Text -import androidx.compose.material3.TextButton import androidx.compose.material3.TopAppBar import androidx.compose.material3.TopAppBarDefaults import androidx.compose.runtime.Composable @@ -65,19 +56,21 @@ import androidx.compose.runtime.setValue import androidx.compose.ui.Alignment import androidx.compose.ui.Modifier import androidx.compose.ui.graphics.Color -import androidx.compose.ui.graphics.vector.ImageVector import androidx.compose.ui.platform.LocalContext -import androidx.core.content.ContextCompat import androidx.compose.ui.res.stringResource import androidx.compose.ui.text.AnnotatedString import androidx.compose.ui.text.LinkAnnotation import androidx.compose.ui.text.SpanStyle import androidx.compose.ui.text.TextLinkStyles import androidx.compose.ui.text.buildAnnotatedString +import androidx.compose.ui.text.font.FontFamily +import androidx.compose.ui.text.font.FontStyle import androidx.compose.ui.text.font.FontWeight +import androidx.compose.ui.text.style.BaselineShift import androidx.compose.ui.text.style.TextDecoration import androidx.compose.ui.unit.Dp import androidx.compose.ui.unit.dp +import androidx.compose.ui.unit.em import androidx.hilt.navigation.compose.hiltViewModel import androidx.lifecycle.compose.collectAsStateWithLifecycle import de.jeanlucmakiola.calendula.R @@ -90,24 +83,30 @@ import de.jeanlucmakiola.calendula.domain.Availability import de.jeanlucmakiola.calendula.domain.EventForm import de.jeanlucmakiola.calendula.domain.EventInstance import de.jeanlucmakiola.calendula.domain.EventStatus -import de.jeanlucmakiola.calendula.domain.RecurringWriteScope -import de.jeanlucmakiola.calendula.domain.Reminder +import de.jeanlucmakiola.calendula.domain.InlineStyle +import de.jeanlucmakiola.calendula.domain.RichText import de.jeanlucmakiola.calendula.domain.TimeZoneOption import de.jeanlucmakiola.calendula.domain.timeZoneOptionOf import de.jeanlucmakiola.calendula.domain.zoneDescriptor +import de.jeanlucmakiola.calendula.domain.zoneOrNull +import de.jeanlucmakiola.calendula.ui.common.orUnnamed +import de.jeanlucmakiola.floret.components.IconInfoCard +import de.jeanlucmakiola.floret.identity.LocalFloretDarkTheme import de.jeanlucmakiola.floret.identity.predictiveBack import de.jeanlucmakiola.calendula.ui.common.CalendarFailure +import de.jeanlucmakiola.calendula.ui.common.DeleteEventDialog +import de.jeanlucmakiola.calendula.ui.common.rememberWriteAction +import de.jeanlucmakiola.calendula.ui.common.sendEventShare import de.jeanlucmakiola.calendula.ui.common.FieldCopier import de.jeanlucmakiola.calendula.ui.common.copyOnLongPress import de.jeanlucmakiola.calendula.ui.common.rememberFieldCopier import de.jeanlucmakiola.calendula.ui.common.icuTimeZoneRegion import de.jeanlucmakiola.calendula.ui.common.LocalSoftenColors import de.jeanlucmakiola.calendula.ui.common.eventAccent -import de.jeanlucmakiola.calendula.ui.common.eventFill -import de.jeanlucmakiola.floret.components.OptionCard import de.jeanlucmakiola.floret.locale.currentLocale import de.jeanlucmakiola.calendula.ui.common.LocalUse24HourFormat import de.jeanlucmakiola.calendula.ui.common.timeOfDayFormatter +import de.jeanlucmakiola.calendula.ui.common.withRepeatedHourZone import de.jeanlucmakiola.calendula.ui.common.recurrenceText import de.jeanlucmakiola.calendula.ui.common.reminderLeadTimeLabel import kotlinx.coroutines.launch @@ -162,50 +161,19 @@ fun EventDetailScreen( val onShareClick = { scope.launch { val uri = viewModel.shareUri() - val sent = uri != null && runCatching { - val send = Intent(Intent.ACTION_SEND).apply { - type = "text/calendar" - putExtra(Intent.EXTRA_STREAM, uri) - addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION) - } - context.startActivity(Intent.createChooser(send, shareChooserTitle)) - }.isSuccess + val sent = uri != null && context.sendEventShare(uri, shareChooserTitle) if (!sent) snackbarHostState.showSnackbar(shareFailedMessage) } Unit } // v1.0 installs only hold READ_CALENDAR; the first write asks for the - // upgrade in place. Granting continues straight into the tapped action — - // edit, delete, or duplicate — held here until the result comes back. - var pendingWrite by remember { mutableStateOf<(() -> Unit)?>(null) } - val writePermissionLauncher = rememberLauncherForActivityResult( - contract = ActivityResultContracts.RequestPermission(), - ) { granted -> - if (granted) pendingWrite?.invoke() - pendingWrite = null - } - val hasWritePermission = { - ContextCompat.checkSelfPermission( - context, - Manifest.permission.WRITE_CALENDAR, - ) == PackageManager.PERMISSION_GRANTED - } - val requireWrite: (() -> Unit) -> Unit = { action -> - if (hasWritePermission()) { - action() - } else { - pendingWrite = action - writePermissionLauncher.launch(Manifest.permission.WRITE_CALENDAR) - } - } - val onDeleteClick = { requireWrite { showDeleteDialog = true } } - val onEditClick = { requireWrite(onEdit) } + // upgrade in place and continues straight into the tapped action. + val onDeleteClick = rememberWriteAction { showDeleteDialog = true } + val onEditClick = rememberWriteAction(action = onEdit) // Duplicate reads the loaded detail into a create form and hands it up; the // create still needs WRITE_CALENDAR even when the source is read-only. - val onDuplicateClick = { - requireWrite { viewModel.duplicateForm()?.let(onDuplicate) } - } + val onDuplicateClick = rememberWriteAction { viewModel.duplicateForm()?.let(onDuplicate) } val deleteFailedMessage = stringResource(R.string.event_delete_failed) val writeDeniedMessage = stringResource(R.string.event_delete_write_denied) @@ -322,70 +290,6 @@ fun EventDetailScreen( } } -/** - * Delete confirmation. Recurring events choose between cancelling just the - * tapped occurrence (default), truncating the series from it onwards, and - * removing the whole series. - */ -@Composable -private fun DeleteEventDialog( - isRecurring: Boolean, - onConfirm: (RecurringWriteScope) -> Unit, - onDismiss: () -> Unit, -) { - var scope by rememberSaveable { mutableStateOf(RecurringWriteScope.ThisEvent) } - AlertDialog( - onDismissRequest = onDismiss, - title = { - Text( - stringResource( - if (isRecurring) R.string.event_delete_recurring_title - else R.string.event_delete_title, - ), - ) - }, - text = { - if (isRecurring) { - Column(verticalArrangement = Arrangement.spacedBy(8.dp)) { - OptionCard( - label = stringResource(R.string.event_delete_option_occurrence), - onClick = { scope = RecurringWriteScope.ThisEvent }, - selected = scope == RecurringWriteScope.ThisEvent, - ) - OptionCard( - label = stringResource(R.string.event_delete_option_following), - onClick = { scope = RecurringWriteScope.ThisAndFollowing }, - selected = scope == RecurringWriteScope.ThisAndFollowing, - ) - OptionCard( - label = stringResource(R.string.event_delete_option_series), - onClick = { scope = RecurringWriteScope.AllEvents }, - selected = scope == RecurringWriteScope.AllEvents, - ) - } - } else { - Text(stringResource(R.string.event_delete_body)) - } - }, - confirmButton = { - TextButton( - onClick = { onConfirm(if (isRecurring) scope else RecurringWriteScope.AllEvents) }, - ) { - Text( - text = stringResource(R.string.event_detail_delete), - color = MaterialTheme.colorScheme.error, - ) - } - }, - dismissButton = { - TextButton(onClick = onDismiss) { - Text(stringResource(R.string.dialog_cancel)) - } - }, - ) -} - - @Composable private fun EventDetailContent( state: EventDetailUiState.Success, @@ -394,8 +298,8 @@ private fun EventDetailContent( ) { val detail = state.detail val instance = detail.instance - val dark = isSystemInDarkTheme() - val locale = currentDetailLocale() + val dark = LocalFloretDarkTheme.current + val locale = currentLocale() val accent = eventAccent(instance.color, dark, LocalSoftenColors.current) Column( @@ -409,15 +313,26 @@ private fun EventDetailContent( // cancelled event strikes through its title. Row(verticalAlignment = Alignment.Top) { val titleLabel = stringResource(R.string.event_detail_title) + val titleDecoration = if (detail.status == EventStatus.Cancelled) { + TextDecoration.LineThrough + } else { + null + } Text( - text = instance.title.ifBlank { stringResource(R.string.event_untitled) }, + // A phone number in the title ("Call Anna 0151 …") dials too. + text = if (instance.title.isBlank()) { + AnnotatedString(stringResource(R.string.event_untitled)) + } else { + linkify( + instance.title, + state.phoneLinks.title, + MaterialTheme.colorScheme.primary, + titleDecoration, + ) + }, style = MaterialTheme.typography.headlineMedium, fontWeight = FontWeight.SemiBold, - textDecoration = if (detail.status == EventStatus.Cancelled) { - TextDecoration.LineThrough - } else { - null - }, + textDecoration = titleDecoration, modifier = Modifier .weight(1f) .then( @@ -464,8 +379,8 @@ private fun EventDetailContent( val gap = 12.dp // "When" — date/all-day plus the time range. - val (whenPrimary, whenSecondary) = formatWhen(instance, TimeZone.currentSystemDefault(), locale) - DetailCard(icon = Icons.Default.Schedule, iconContentDescription = null) { + val (whenPrimary, whenSecondary) = rememberWhen(instance, TimeZone.currentSystemDefault(), locale) + IconInfoCard(icon = Icons.Default.Schedule, iconContentDescription = null) { Text(text = whenPrimary, style = MaterialTheme.typography.titleMedium) if (whenSecondary != null) { Spacer(Modifier.height(2.dp)) @@ -490,7 +405,7 @@ private fun EventDetailContent( } foreignZone?.let { zoneOption -> Spacer(Modifier.height(gap)) - DetailCard( + IconInfoCard( icon = Icons.Default.Public, iconContentDescription = stringResource(R.string.event_detail_timezone), ) { @@ -503,8 +418,8 @@ private fun EventDetailContent( // — which a cross-zone event easily does — carries the whole span // in the primary instead, so fall back to it. If the zone can't be // read back at all, drop to just the abbreviation + offset. - val originalTime = runCatching { TimeZone.of(zoneOption.id) }.getOrNull() - ?.let { formatWhen(instance, it, locale) } + val originalTime = zoneOrNull(zoneOption.id) + ?.let { rememberWhen(instance, it, locale) } ?.let { (primary, secondary) -> secondary ?: primary } Spacer(Modifier.height(2.dp)) Text( @@ -522,29 +437,30 @@ private fun EventDetailContent( // Calendar — icon tinted in the calendar colour conveys identity, so no // separate colour dot is needed. Spacer(Modifier.height(gap)) - DetailCard( + IconInfoCard( icon = Icons.Default.CalendarMonth, iconTint = accent, iconContentDescription = stringResource(R.string.event_detail_calendar), ) { Text( - text = state.calendarName?.ifBlank { stringResource(R.string.calendar_unnamed) } + text = state.calendarName?.orUnnamed() ?: stringResource(R.string.event_detail_calendar_unknown), style = MaterialTheme.typography.titleMedium, ) } - // Location (conditional). URLs open in the browser, the rest in maps. + // Location (conditional). URLs open in the browser, phone numbers in the + // dialer, the rest in maps. instance.location?.takeIf { it.isNotBlank() }?.let { location -> val context = LocalContext.current val locationLabel = stringResource(R.string.event_detail_location) Spacer(Modifier.height(gap)) - DetailCard( + IconInfoCard( icon = Icons.Default.Place, iconContentDescription = locationLabel, ) { Text( - text = linkifyUrls(location, MaterialTheme.colorScheme.primary), + text = linkify(location, state.phoneLinks.location, MaterialTheme.colorScheme.primary), style = MaterialTheme.typography.titleMedium, color = MaterialTheme.colorScheme.primary, modifier = Modifier @@ -561,20 +477,21 @@ private fun EventDetailContent( } } - // Description (conditional). URLs are auto-linked. - detail.description?.takeIf { it.isNotBlank() }?.let { description -> + // Description (conditional). HTML is rendered (#271); URLs and phone + // numbers are auto-linked. + state.description?.let { description -> val descriptionLabel = stringResource(R.string.event_detail_description) Spacer(Modifier.height(gap)) - DetailCard( + IconInfoCard( icon = Icons.AutoMirrored.Filled.Notes, iconContentDescription = descriptionLabel, // The gesture sits on the card so the icon and padding answer // it too: every linkified URL owns the pointer over its own // glyphs, which leaves the text itself a patchy target. - modifier = Modifier.copyOnLongPress(descriptionLabel, description, copyField), + modifier = Modifier.copyOnLongPress(descriptionLabel, description.copyText(), copyField), ) { Text( - text = linkifyUrls(description, MaterialTheme.colorScheme.primary), + text = linkify(description, state.phoneLinks.description, MaterialTheme.colorScheme.primary), style = MaterialTheme.typography.bodyMedium, ) } @@ -584,7 +501,7 @@ private fun EventDetailContent( // each attendee with their role and reply. detail.attendees.takeIf { it.isNotEmpty() }?.let { attendees -> Spacer(Modifier.height(gap)) - DetailCard( + IconInfoCard( icon = Icons.Default.People, iconContentDescription = stringResource(R.string.event_detail_attendees), ) { @@ -606,7 +523,7 @@ private fun EventDetailContent( // Reminders (conditional) — list each lead time before the event. detail.reminders.takeIf { it.isNotEmpty() }?.let { reminders -> Spacer(Modifier.height(gap)) - DetailCard( + IconInfoCard( icon = Icons.Default.Notifications, iconContentDescription = stringResource(R.string.event_detail_reminders), ) { @@ -615,7 +532,7 @@ private fun EventDetailContent( .sortedBy { it.minutes } .forEach { reminder -> Text( - text = reminderLeadText(reminder), + text = reminderLeadTimeLabel(reminder.minutes), style = MaterialTheme.typography.titleMedium, modifier = Modifier.padding(vertical = 2.dp), ) @@ -626,7 +543,7 @@ private fun EventDetailContent( // Recurrence (conditional) — humanised from the RRULE. detail.rrule?.takeIf { it.isNotBlank() }?.let { rrule -> Spacer(Modifier.height(gap)) - DetailCard( + IconInfoCard( icon = Icons.Default.Repeat, iconContentDescription = stringResource(R.string.event_detail_recurrence), ) { @@ -639,36 +556,6 @@ private fun EventDetailContent( } } -/** One info card: tonal container, leading icon in the gutter, value to the right. */ -@Composable -private fun DetailCard( - icon: ImageVector, - iconContentDescription: String?, - modifier: Modifier = Modifier, - iconTint: Color = MaterialTheme.colorScheme.onSurfaceVariant, - content: @Composable ColumnScope.() -> Unit, -) { - Surface( - color = MaterialTheme.colorScheme.surfaceContainerHigh, - shape = RoundedCornerShape(16.dp), - modifier = modifier.fillMaxWidth(), - ) { - Row( - modifier = Modifier.padding(16.dp), - verticalAlignment = Alignment.CenterVertically, - ) { - Icon( - imageVector = icon, - contentDescription = iconContentDescription, - tint = iconTint, - modifier = Modifier.size(24.dp), - ) - Spacer(Modifier.width(16.dp)) - Column(modifier = Modifier.weight(1f), content = content) - } - } -} - @Composable private fun AttendeeRow(attendee: Attendee) { Row( @@ -792,11 +679,6 @@ private fun SkeletonBar(widthFraction: Float, height: Dp) { // --- helpers ------------------------------------------------------------- -// Observable locale read (shared helper) — avoids NonObservableLocale / -// LocalContextConfigurationRead lint by going through LocalConfiguration. -@Composable -private fun currentDetailLocale(): Locale = currentLocale() - private fun attendeeStatusLabel(status: AttendeeStatus): Int = when (status) { AttendeeStatus.Accepted -> R.string.event_attendee_accepted AttendeeStatus.Declined -> R.string.event_attendee_declined @@ -816,10 +698,6 @@ private fun attendeeRoleLabel(attendee: Attendee): Int? = when { else -> null } -/** Humanise a reminder's lead time, e.g. "10 minutes before" / "At time of event". */ -@Composable -private fun reminderLeadText(reminder: Reminder): String = reminderLeadTimeLabel(reminder.minutes) - /** * [tz] resolved as a [TimeZoneOption], but only when the event is timed and * pinned to a zone different from the device's — the cases where showing it @@ -847,45 +725,114 @@ private fun foreignTimeZone( ) } -/** Wrap http(s) URLs in [text] as links tinted [linkColor] that open in the browser. */ +/** + * Wrap http(s) URLs in [text] as links that open in the browser, and its + * [phoneLinks] as links that open the dialer, both tinted [linkColor]. A + * link's underline joins [textDecoration] rather than replacing it, so a + * cancelled title stays struck through across its links. + */ @Composable -private fun linkifyUrls(text: String, linkColor: Color): AnnotatedString { +private fun linkify( + text: String, + phoneLinks: List, + linkColor: Color, + textDecoration: TextDecoration? = null, +): AnnotatedString = linkify(RichText(text), phoneLinks, linkColor, textDecoration) + +/** + * [linkify] for text rendered from HTML: its own formatting and `` + * links come along, and a URL or number already inside one isn't linked again. + */ +@Composable +private fun linkify( + text: RichText, + phoneLinks: List, + linkColor: Color, + textDecoration: TextDecoration? = null, +): AnnotatedString { val context = LocalContext.current - return remember(text, linkColor, context) { - val styles = TextLinkStyles( - style = SpanStyle(color = linkColor, textDecoration = TextDecoration.Underline), - ) + return remember(text, phoneLinks, linkColor, textDecoration, context) { + // Decorations go on separately so overlapping ones add up: a span's + // textDecoration replaces whatever sits under it. + val styles = TextLinkStyles(style = SpanStyle(color = linkColor)) + val decorations = mutableListOf>() + textDecoration?.let { decorations += Triple(0, text.text.length, it) } + for (range in text.styles) { + when (range.style) { + InlineStyle.Underline -> decorations += Triple(range.start, range.end, TextDecoration.Underline) + InlineStyle.Strikethrough -> decorations += Triple(range.start, range.end, TextDecoration.LineThrough) + else -> Unit + } + } + fun linked(start: Int, end: Int) = text.links.any { start < it.end && it.start < end } buildAnnotatedString { - append(text) - for (link in findWebLinks(text)) { - addLink( - LinkAnnotation.Url(link.url, styles) { openWebLink(context, link.url) }, - link.start, - link.end, - ) + append(text.text) + for (range in text.styles) range.style.toSpanStyle()?.let { addStyle(it, range.start, range.end) } + fun link(url: String, start: Int, end: Int, onClick: () -> Unit) { + addLink(LinkAnnotation.Url(url, styles) { onClick() }, start, end) + decorations += Triple(start, end, TextDecoration.Underline) + } + for (link in text.links) { + if (link.url.startsWith("tel:")) { + link(link.url, link.start, link.end) { dial(context, Uri.decode(link.url.substring(4))) } + } else { + link(link.url, link.start, link.end) { openWebLink(context, link.url) } + } + } + for (link in findWebLinks(text.text)) { + if (linked(link.start, link.end)) continue + link(link.url, link.start, link.end) { openWebLink(context, link.url) } + } + for (link in phoneLinks) { + if (linked(link.start, link.end)) continue + link("tel:${link.number}", link.start, link.end) { dial(context, link.number) } + } + val bounds = decorations.flatMap { listOf(it.first, it.second) }.distinct().sorted() + for ((start, end) in bounds.zipWithNext()) { + val covering = decorations.filter { it.first <= start && end <= it.second }.map { it.third }.distinct() + if (covering.isNotEmpty()) addStyle(SpanStyle(textDecoration = TextDecoration.combine(covering)), start, end) } } } } +private fun InlineStyle.toSpanStyle(): SpanStyle? = when (this) { + InlineStyle.Bold -> SpanStyle(fontWeight = FontWeight.Bold) + InlineStyle.Italic -> SpanStyle(fontStyle = FontStyle.Italic) + InlineStyle.Superscript -> SpanStyle(baselineShift = BaselineShift.Superscript, fontSize = 0.75.em) + InlineStyle.Subscript -> SpanStyle(baselineShift = BaselineShift.Subscript, fontSize = 0.75.em) + InlineStyle.Monospace -> SpanStyle(fontFamily = FontFamily.Monospace) + InlineStyle.Underline, InlineStyle.Strikethrough -> null +} + /** * Format an event's time into a primary line (date, or "All day") and an * optional secondary line (time range). Multi-day timed events collapse into a * single primary line spanning both ends. */ @Composable +private fun rememberWhen(instance: EventInstance, zone: TimeZone, locale: Locale): Pair { + val use24Hour = LocalUse24HourFormat.current + val allDayLabel = stringResource(R.string.event_detail_all_day) + // Remembered: a time in the repeated hour looks up its zone abbreviation (#387). + return remember(instance, zone, locale, use24Hour, allDayLabel) { + formatWhen(instance, zone, locale, use24Hour, allDayLabel) + } +} + private fun formatWhen( instance: EventInstance, zone: TimeZone, locale: Locale, + use24Hour: Boolean, + allDayLabel: String, ): Pair { val zid = ZoneId.of(zone.id) val dateFull = DateTimeFormatter.ofLocalizedDate(FormatStyle.FULL).withLocale(locale) val dateMedium = DateTimeFormatter.ofLocalizedDate(FormatStyle.MEDIUM).withLocale(locale) - val timeShort = timeOfDayFormatter(LocalUse24HourFormat.current, locale) + val timeShort = timeOfDayFormatter(use24Hour, locale) val startLdt = instance.start.toJavaLocalDateTime(zid) - val allDayLabel = stringResource(R.string.event_detail_all_day) if (instance.isAllDay) { // All-day events live at UTC midnights with an exclusive end. Resolve @@ -905,12 +852,13 @@ private fun formatWhen( } val endLdt = instance.end.toJavaLocalDateTime(zid) + val startTime = withRepeatedHourZone(timeShort.format(startLdt), instance.start, zone, locale) + val endTime = withRepeatedHourZone(timeShort.format(endLdt), instance.end, zone, locale) return if (startLdt.toLocalDate() == endLdt.toLocalDate()) { - dateFull.format(startLdt.toLocalDate()) to - "${timeShort.format(startLdt)} – ${timeShort.format(endLdt)}" + dateFull.format(startLdt.toLocalDate()) to "$startTime – $endTime" } else { - val start = "${dateMedium.format(startLdt.toLocalDate())} ${timeShort.format(startLdt)}" - val end = "${dateMedium.format(endLdt.toLocalDate())} ${timeShort.format(endLdt)}" + val start = "${dateMedium.format(startLdt.toLocalDate())} $startTime" + val end = "${dateMedium.format(endLdt.toLocalDate())} $endTime" "$start – $end" to null } } @@ -920,7 +868,15 @@ private fun Instant.toJavaLocalDateTime(zid: ZoneId): java.time.LocalDateTime = /** Open [url] in a browsable app, or say so when none can take it. */ private fun openWebLink(context: Context, url: String) { - val intent = Intent(Intent.ACTION_VIEW, Uri.parse(url)).addCategory(Intent.CATEGORY_BROWSABLE) + startOrSayNoApp(context, Intent(Intent.ACTION_VIEW, Uri.parse(url)).addCategory(Intent.CATEGORY_BROWSABLE)) +} + +/** Open the dialer with [number] filled in, or say so when none can take it. */ +private fun dial(context: Context, number: String) { + startOrSayNoApp(context, Intent(Intent.ACTION_DIAL, Uri.fromParts("tel", number, null))) +} + +private fun startOrSayNoApp(context: Context, intent: Intent) { if (runCatching { context.startActivity(intent) }.isFailure) { Toast.makeText(context, R.string.link_open_failed, Toast.LENGTH_SHORT).show() } diff --git a/app/src/main/java/de/jeanlucmakiola/calendula/ui/detail/EventDetailUiState.kt b/app/src/main/java/de/jeanlucmakiola/calendula/ui/detail/EventDetailUiState.kt index 6f6dd970..18c278cf 100644 --- a/app/src/main/java/de/jeanlucmakiola/calendula/ui/detail/EventDetailUiState.kt +++ b/app/src/main/java/de/jeanlucmakiola/calendula/ui/detail/EventDetailUiState.kt @@ -2,6 +2,7 @@ package de.jeanlucmakiola.calendula.ui.detail import de.jeanlucmakiola.calendula.domain.EventDetail import de.jeanlucmakiola.calendula.domain.FailureReason +import de.jeanlucmakiola.calendula.domain.RichText /** * UI state for the event-detail screen (spec S4). @@ -21,6 +22,10 @@ sealed interface EventDetailUiState { * the sync would just resurrect it. Contact dates are removed at the source. */ val isManaged: Boolean = false, + /** Phone numbers to link in the title, location and description. */ + val phoneLinks: EventPhoneLinks = EventPhoneLinks(), + /** The description as drawn — HTML rendered (#271); null when there is none. */ + val description: RichText? = null, ) : EventDetailUiState } diff --git a/app/src/main/java/de/jeanlucmakiola/calendula/ui/detail/EventDetailViewModel.kt b/app/src/main/java/de/jeanlucmakiola/calendula/ui/detail/EventDetailViewModel.kt index cd068cbf..066ad4ad 100644 --- a/app/src/main/java/de/jeanlucmakiola/calendula/ui/detail/EventDetailViewModel.kt +++ b/app/src/main/java/de/jeanlucmakiola/calendula/ui/detail/EventDetailViewModel.kt @@ -6,20 +6,23 @@ import androidx.lifecycle.viewModelScope import dagger.hilt.android.lifecycle.HiltViewModel import de.jeanlucmakiola.calendula.data.calendar.CalendarRepository import de.jeanlucmakiola.calendula.data.calendar.NoSuchEventException -import de.jeanlucmakiola.calendula.data.di.IoDispatcher import de.jeanlucmakiola.calendula.data.ics.IcsExporter +import de.jeanlucmakiola.calendula.data.time.ZoneSource import de.jeanlucmakiola.calendula.domain.EventForm import de.jeanlucmakiola.calendula.domain.FailureReason import de.jeanlucmakiola.calendula.domain.RecurringWriteScope -import de.jeanlucmakiola.calendula.domain.ics.IcsWriter -import de.jeanlucmakiola.calendula.domain.ics.toShareIcsEvent -import de.jeanlucmakiola.calendula.domain.toEditForm +import de.jeanlucmakiola.calendula.domain.atOccurrence +import de.jeanlucmakiola.calendula.domain.descriptionRichText +import de.jeanlucmakiola.calendula.domain.toDuplicateForm +import de.jeanlucmakiola.calendula.ui.common.DeleteOutcome +import de.jeanlucmakiola.calendula.ui.common.tryDeleteEvent +import de.jeanlucmakiola.calendula.ui.common.stageEventShare +import de.jeanlucmakiola.floret.android.stateWhileSubscribed +import de.jeanlucmakiola.floret.di.IoDispatcher import kotlinx.coroutines.CoroutineDispatcher import kotlinx.coroutines.withContext -import kotlin.time.Clock import kotlinx.coroutines.ExperimentalCoroutinesApi import kotlinx.coroutines.flow.MutableStateFlow -import kotlinx.coroutines.flow.SharingStarted import kotlinx.coroutines.flow.StateFlow import kotlinx.coroutines.flow.asStateFlow import kotlinx.coroutines.flow.combine @@ -28,11 +31,8 @@ import kotlinx.coroutines.flow.flatMapLatest import kotlinx.coroutines.flow.flow import kotlinx.coroutines.flow.flowOf import kotlinx.coroutines.flow.flowOn -import kotlinx.coroutines.flow.stateIn import kotlinx.coroutines.launch -import kotlinx.datetime.TimeZone import kotlin.coroutines.cancellation.CancellationException -import kotlin.time.Instant import javax.inject.Inject /** @@ -45,6 +45,7 @@ class EventDetailViewModel @Inject constructor( private val repository: CalendarRepository, private val icsExporter: IcsExporter, @IoDispatcher private val io: CoroutineDispatcher, + private val zoneSource: ZoneSource, ) : ViewModel() { private val _target = MutableStateFlow(null) @@ -75,9 +76,8 @@ class EventDetailViewModel @Inject constructor( } } .flowOn(io) - .stateIn( + .stateWhileSubscribed( scope = viewModelScope, - started = SharingStarted.WhileSubscribed(5_000L), initialValue = EventDetailUiState.Loading, ) @@ -112,22 +112,11 @@ class EventDetailViewModel @Inject constructor( if (_deleteState.value == DeleteUiState.Deleting) return viewModelScope.launch { _deleteState.value = DeleteUiState.Deleting - _deleteState.value = try { - when (scope) { - RecurringWriteScope.AllEvents -> - repository.deleteEvent(target.eventId) - RecurringWriteScope.ThisEvent -> - repository.deleteOccurrence(target.eventId, target.beginMillis) - RecurringWriteScope.ThisAndFollowing -> - repository.deleteEventFromOccurrence(target.eventId, target.beginMillis) - } - DeleteUiState.Deleted - } catch (e: CancellationException) { - throw e - } catch (e: SecurityException) { - DeleteUiState.NeedsPermission - } catch (e: Exception) { - DeleteUiState.Failed + _deleteState.value = when (repository.tryDeleteEvent(target.eventId, target.beginMillis, scope)) { + // Already gone is what a delete wants anyway. + DeleteOutcome.Deleted, DeleteOutcome.Gone -> DeleteUiState.Deleted + DeleteOutcome.NeedsPermission -> DeleteUiState.NeedsPermission + DeleteOutcome.Failed -> DeleteUiState.Failed } } } @@ -144,66 +133,46 @@ class EventDetailViewModel @Inject constructor( */ suspend fun shareUri(): Uri? { val detail = (state.value as? EventDetailUiState.Success)?.detail ?: return null - return runCatching { - withContext(io) { - val ics = IcsWriter().writeCalendar( - events = listOf(detail.toShareIcsEvent()), - dtStamp = Clock.System.now(), - ) - icsExporter.stageShareFile(shareFileName(detail.instance.title), ics) - } - }.getOrNull() + return withContext(io) { icsExporter.stageEventShare(detail) } } /** - * Build a create form seeded from the open event so the user can save a - * copy as a new, independent event (#52). Returns null when nothing is - * loaded. - * - * The recurrence is dropped — a duplicate is a single event; anyone who - * wants a series can re-add one in the edit form that opens. The source - * calendar is kept only when it's writable, otherwise the id is cleared so - * the create resolves to the last-used/first-writable calendar — which lets - * a read-only event (a WebCal subscription, a birthday) be copied into an - * editable calendar. The occurrence's own times carry over unchanged. + * A create form seeded from the open event, to save a copy as a new event + * (#52) — see [toDuplicateForm]. Null when nothing is loaded. */ fun duplicateForm(): EventForm? { val loaded = state.value as? EventDetailUiState.Success ?: return null - val detail = loaded.detail - return detail.toEditForm( - beginMillis = detail.instance.start.toEpochMilliseconds(), - endMillis = detail.instance.end.toEpochMilliseconds(), - zone = TimeZone.currentSystemDefault(), - ).copy( - rrule = null, - calendarId = detail.instance.calendarId.takeIf { loaded.canModify }, - ) + return loaded.detail.toDuplicateForm(loaded.canModify, zoneSource.current()) } private suspend fun loadDetail(target: Target): EventDetailUiState = try { val detail = repository.eventDetail(target.eventId) - // The Events row holds the series start; replace it with this - // occurrence's time so recurring events render correctly. An external - // "open event" that names no occurrence ([NO_OCCURRENCE_TIME] — e.g. a - // bare content://.../events/ VIEW intent, issue #48) keeps the row's - // own DTSTART/DTEND instead of overriding it to the epoch. + // An external "open event" that names no occurrence ([NO_OCCURRENCE_TIME] — + // e.g. a bare content://.../events/ VIEW intent, issue #48) keeps the + // row's own DTSTART/DTEND instead of overriding it to the epoch. val corrected = if (target.beginMillis == NO_OCCURRENCE_TIME) { detail } else { - detail.copy( - instance = detail.instance.copy( - start = Instant.fromEpochMilliseconds(target.beginMillis), - end = Instant.fromEpochMilliseconds(target.endMillis), - ), - ) + detail.atOccurrence(target.beginMillis, target.endMillis) } val calendar = repository.calendars().first() .firstOrNull { it.id == corrected.instance.calendarId } + val description = corrected.description + ?.let(::descriptionRichText) + ?.takeIf { it.text.isNotBlank() } EventDetailUiState.Success( detail = corrected, calendarName = calendar?.displayName, canModify = calendar?.canModifyContents == true, isManaged = calendar?.isManaged == true, + // Found here, off the main thread and once per load: the platform + // matcher loads its metadata on first use. + phoneLinks = findEventPhoneLinks( + title = corrected.instance.title, + location = corrected.instance.location, + description = description?.text, + ), + description = description, ) } catch (e: CancellationException) { throw e @@ -228,13 +197,3 @@ class EventDetailViewModel @Inject constructor( const val NO_OCCURRENCE_TIME: Long = Long.MIN_VALUE } } - -/** A filesystem-safe `.ics` file name from an event title (or a fallback). */ -private fun shareFileName(title: String): String { - val base = title.trim() - .replace(Regex("""[^\p{L}\p{Nd} _-]"""), "") - .replace(' ', '_') - .take(40) - .ifBlank { "event" } - return "$base.ics" -} diff --git a/app/src/main/java/de/jeanlucmakiola/calendula/ui/detail/PhoneLinks.kt b/app/src/main/java/de/jeanlucmakiola/calendula/ui/detail/PhoneLinks.kt new file mode 100644 index 00000000..ed562f95 --- /dev/null +++ b/app/src/main/java/de/jeanlucmakiola/calendula/ui/detail/PhoneLinks.kt @@ -0,0 +1,202 @@ +package de.jeanlucmakiola.calendula.ui.detail + +import android.text.SpannableString +import android.text.style.URLSpan +import android.text.util.Linkify + +/** + * A phone number found in free text, spanning [start] until [end] (exclusive). + * [number] is what the dialer gets: digits, a leading `+`, and any `,`/`#` + * dial-in suffix — the separators that only made it readable are gone. + */ +data class PhoneLink(val start: Int, val end: Int, val number: String) + +/** The phone numbers in an event's free-text fields, each against its own text. */ +data class EventPhoneLinks( + val title: List = emptyList(), + val location: List = emptyList(), + val description: List = emptyList(), +) + +/** Where the platform matcher saw a phone number: [start] until [end] (exclusive). */ +internal data class PhoneMatch(val start: Int, val end: Int) + +// A conference dial-in's pauses and meeting id right after the number: +// "+16465588656,,85012345678#" or Zoom's ",,850…#,,,,*123456#". It opens on a +// double comma or closes on "#", so "030 1234567,0151 2345678" stays a list. +private val dialSuffixRegex = Regex("""^(?:,,+[\d*]+#?|,[\d*]+#)(?:,+[\d*]+#?)*""") + +// Whitespace as invites write it: Java's \s misses the no-break space and the +// invisible direction marks Meet and Outlook wrap around numbers. +private const val GAP = """\s\u00A0\u200E\u200F\u202A-\u202E\u2066-\u2069""" + +// A number right after one of these labels is an id to type in, not one to +// call. English and German cover the Zoom/Teams/Meet/Webex invites seen so far. +// "Conference number" is left out: invites use it for the dial-in itself. +private val notAPhoneLabelRegex = Regex( + """(?:(?:meeting|webinar|besprechungs)[ -]?(?:id|number|nummer)|(?:conference|konferenz)[ -]?id|""" + + """\bpin|passcode|password|passwort|kenncode|access code|zugangscode)[$GAP:#.()]*$""", + RegexOption.IGNORE_CASE, +) + +// A day.month.year (or year-month-day, or US month/day/year) date: exactly +// three groups, so a French "01.23.45.67.89" chain doesn't read as one. +private val dateRegex = Regex("""(? = + refinePhoneMatches(text, platformPhoneMatches(text), findWebLinks(text)) + +/** [findPhoneLinks] for each of an event's free-text fields. */ +internal fun findEventPhoneLinks(title: String, location: String?, description: String?) = EventPhoneLinks( + title = findPhoneLinks(title), + location = location?.let(::findPhoneLinks).orEmpty(), + description = description?.let(::findPhoneLinks).orEmpty(), +) + +// The matcher reads the region off the SIM, which throws on a device without +// telephony; a field then just goes without phone links. +private fun platformPhoneMatches(text: String): List = runCatching { + val spannable = SpannableString(text) + if (!Linkify.addLinks(spannable, Linkify.PHONE_NUMBERS)) return emptyList() + spannable.getSpans(0, spannable.length, URLSpan::class.java) + .map { PhoneMatch(spannable.getSpanStart(it), spannable.getSpanEnd(it)) } +}.getOrDefault(emptyList()) + +/** + * Turn the platform's [matches] in [text] into dialable links. The matcher is + * lenient, so a match is dropped when it sits inside one of the [webLinks], + * follows a meeting id or PIN label, holds a date, reads as an amount or is + * too short. What's kept loses a stray count off its end, regains an + * international "+49 (0)" prefix the matcher left behind, and carries a + * conference dial-in suffix along. + */ +internal fun refinePhoneMatches( + text: String, + matches: List, + webLinks: List, +): List { + val links = mutableListOf() + for (match in matches.sortedBy { it.start }) { + var start = match.start + var end = match.end + val matched = text.substring(start, end) + if (webLinks.any { start < it.end && it.start < end }) continue + if (gluedIntoAWord(text, start, end)) continue + val lineBefore = text.window(lineStart(text, start).coerceAtLeast(start - LOOK_BEHIND), start) + if (notAPhoneLabelRegex.containsMatchIn(lineBefore)) continue + if (dateRegex.findAll(matched).any { it.isDate() }) continue + if (isDottedTimes(matched)) continue + if (isAmount(text, start, end)) continue + strayTailRegex.find(matched)?.let { tail -> + if (wordAfterRegex.matchesAt(text, end)) end = start + tail.range.first + } + // "+49 (0)151 …": a matcher that stops at the "(0)" leaves the domestic + // tail, which would dial without the country code. + strandedCountryCodeRegex.find(text.window(start - LOOK_BEHIND, start)) + ?.let { start -= it.value.length } + val number = dialable(text.substring(start, end)) + if (number.count { it.isDigit() } < MIN_DIGITS) continue + val suffix = dialSuffixRegex.find(text.window(end, end + LOOK_AHEAD))?.value.orEmpty() + // A suffix swallowed what the matcher saw as the next number. + if (links.lastOrNull()?.let { start < it.end } == true) continue + links += PhoneLink(start, end + suffix.length, number + dialable(suffix)) + } + return links +} + +// How far around a match the label, prefix, currency and suffix checks look. +// Enough for any of them, and it keeps a long invite from being re-read whole +// for every number in it. +private const val LOOK_BEHIND = 40 +private const val LOOK_AHEAD = 60 + +private fun String.window(from: Int, to: Int): String = + substring(from.coerceAtLeast(0), to.coerceAtMost(length)) + +/** + * Digits run straight into a letter or a URL path — "zoom.us/j/850…" without + * its https:// — which no web link covered. A phone number stands apart. + */ +private fun gluedIntoAWord(text: String, start: Int, end: Int): Boolean { + val before = text.getOrNull(start - 1) + val after = text.getOrNull(end) + return (before != null && (before.isLetter() || before in "/=?&")) || + (after != null && (after.isLetter() || after == '/')) +} + +private fun isDottedTimes(matched: String): Boolean { + val times = dottedTimesRegex.matchEntire(matched) ?: return false + return times.groupValues.drop(1).chunked(2).all { (hour, minute) -> + hour.isEmpty() || (hour.toInt() in 0..24 && minute.toInt() in 0..59) + } +} + +private fun isAmount(text: String, start: Int, end: Int): Boolean { + val matched = text.substring(start, end) + if (shortLeadAmountRegex.matches(matched)) return true + return amountRegex.matches(matched) && + (currencyBeforeRegex.containsMatchIn(text.window(start - LOOK_BEHIND, start)) || + currencyAfterRegex.containsMatchIn(text.window(end, end + LOOK_AHEAD))) +} + +private fun MatchResult.isDate(): Boolean { + val (a, _, b, c) = destructured + val first = a.toInt() + val second = b.toInt() + val last = c.toInt() + return when { + a.length == 4 -> second in 1..12 && last in 1..31 && c.length <= 2 + a.length > 2 -> false + // Day first (most of the world) or month first (US). + else -> (first in 1..31 && second in 1..12) || (first in 1..12 && second in 1..31) + } +} + +private fun lineStart(text: String, index: Int): Int = text.lastIndexOf('\n', index - 1) + 1 + +/** + * Strip [raw] down to what a dialer takes. An international number's "(0)" + * trunk prefix — "+49 (0) 151 …" — is a domestic-only hint and would break the + * call, so it goes too; an extension becomes a pause. + */ +private fun dialable(raw: String): String { + val international = raw.trimStart('(').startsWith("+") + val withoutTrunk = if (international) raw.replace(trunkPrefixRegex, "") else raw + return withoutTrunk.replace(extensionRegex, ",") + .filter { it.isDigit() || it == '+' || it == ',' || it == '#' || it == '*' } +} 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 90dff7a1..d920b15a 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 @@ -4,7 +4,6 @@ import android.Manifest import android.app.Activity import android.content.Context import android.content.Intent -import android.content.pm.PackageManager import android.net.Uri import android.provider.ContactsContract import android.util.Patterns @@ -13,7 +12,6 @@ import androidx.activity.result.contract.ActivityResultContracts import androidx.compose.animation.AnimatedVisibility import androidx.compose.foundation.background import androidx.compose.foundation.clickable -import androidx.compose.foundation.isSystemInDarkTheme import androidx.compose.foundation.layout.Box import androidx.compose.foundation.layout.Column import androidx.compose.foundation.layout.ColumnScope @@ -31,11 +29,25 @@ import androidx.compose.foundation.rememberScrollState import androidx.compose.foundation.layout.Arrangement import androidx.compose.foundation.shape.CircleShape import androidx.compose.foundation.shape.RoundedCornerShape -import androidx.compose.foundation.text.BasicTextField import androidx.compose.foundation.verticalScroll import androidx.compose.material.icons.Icons import androidx.compose.material.icons.automirrored.filled.Notes import androidx.compose.material.icons.filled.Add +import androidx.compose.runtime.getValue +import androidx.compose.runtime.setValue +import de.jeanlucmakiola.calendula.ui.common.orUnnamed +import de.jeanlucmakiola.floret.components.IconInfoCard +import de.jeanlucmakiola.floret.identity.LocalFloretDarkTheme +import kotlinx.coroutines.launch +import de.jeanlucmakiola.calendula.ui.common.sendEventShare +import de.jeanlucmakiola.calendula.ui.common.canWriteCalendar +import de.jeanlucmakiola.calendula.ui.common.rememberWriteAction +import de.jeanlucmakiola.calendula.ui.common.DeleteEventDialog +import androidx.compose.runtime.rememberCoroutineScope +import androidx.compose.material.icons.filled.Share +import androidx.compose.material.icons.filled.MoreVert +import androidx.compose.material.icons.filled.Delete +import androidx.compose.material.icons.filled.ContentCopy import androidx.compose.material.icons.filled.ArrowDropDown import androidx.compose.material.icons.filled.CalendarMonth import androidx.compose.material.icons.filled.Close @@ -76,18 +88,14 @@ import androidx.compose.material3.TopAppBar import androidx.compose.material3.TopAppBarDefaults import androidx.compose.runtime.Composable import androidx.compose.runtime.LaunchedEffect -import androidx.compose.runtime.getValue import androidx.compose.runtime.mutableStateOf import androidx.compose.runtime.remember import androidx.compose.runtime.saveable.rememberSaveable -import androidx.compose.runtime.setValue import androidx.compose.ui.Alignment import androidx.compose.ui.Modifier import androidx.compose.ui.focus.FocusRequester import androidx.compose.ui.focus.focusRequester import androidx.compose.ui.graphics.Color -import androidx.compose.ui.graphics.SolidColor -import androidx.compose.ui.graphics.isSpecified import androidx.compose.ui.graphics.Shape import androidx.compose.ui.graphics.vector.ImageVector import androidx.compose.ui.platform.LocalContext @@ -106,7 +114,6 @@ import androidx.compose.ui.text.input.KeyboardCapitalization import androidx.compose.ui.text.input.KeyboardType import androidx.compose.ui.unit.Dp import androidx.compose.ui.unit.dp -import androidx.core.content.ContextCompat import androidx.hilt.navigation.compose.hiltViewModel import androidx.lifecycle.compose.collectAsStateWithLifecycle import de.jeanlucmakiola.calendula.R @@ -116,14 +123,16 @@ import de.jeanlucmakiola.calendula.domain.CalendarSource import de.jeanlucmakiola.calendula.domain.EventAttendee import de.jeanlucmakiola.calendula.domain.EventColorOption import de.jeanlucmakiola.calendula.domain.EventForm +import de.jeanlucmakiola.calendula.domain.startInstant +import de.jeanlucmakiola.calendula.domain.endInstant +import de.jeanlucmakiola.calendula.domain.resolvedZone +import de.jeanlucmakiola.calendula.domain.isPinnedAwayFrom import de.jeanlucmakiola.calendula.domain.EventFormField import de.jeanlucmakiola.calendula.domain.zoneDescriptor import de.jeanlucmakiola.calendula.domain.timeZoneOptionOf -import de.jeanlucmakiola.calendula.domain.timesIn import de.jeanlucmakiola.calendula.domain.EventFormProblem import de.jeanlucmakiola.calendula.domain.RecurrenceEnd import de.jeanlucmakiola.calendula.domain.RecurrenceFreq -import de.jeanlucmakiola.calendula.domain.RecurringWriteScope import de.jeanlucmakiola.calendula.domain.SimpleRecurrence import de.jeanlucmakiola.calendula.domain.parseSimpleRecurrence import de.jeanlucmakiola.calendula.domain.toRRule @@ -148,12 +157,10 @@ import de.jeanlucmakiola.calendula.ui.common.eventFormFieldLabel import de.jeanlucmakiola.floret.components.FullScreenPicker import de.jeanlucmakiola.floret.components.GroupedRow import de.jeanlucmakiola.floret.components.GroupedSurface -import de.jeanlucmakiola.calendula.ui.common.MILLIS_PER_DAY import de.jeanlucmakiola.floret.components.InlineTextField import de.jeanlucmakiola.floret.components.OptionCard import de.jeanlucmakiola.floret.components.OptionPicker import de.jeanlucmakiola.floret.components.Position -import de.jeanlucmakiola.floret.components.SelectedCheck import de.jeanlucmakiola.floret.components.groupedShape as floretGroupedShape import de.jeanlucmakiola.floret.components.positionOf import de.jeanlucmakiola.calendula.ui.common.REMINDER_PRESETS @@ -161,7 +168,9 @@ import de.jeanlucmakiola.calendula.ui.common.TimePickerAlert import de.jeanlucmakiola.floret.reminders.ReminderUnit import de.jeanlucmakiola.floret.locale.currentLocale import de.jeanlucmakiola.calendula.ui.common.LocalUse24HourFormat +import de.jeanlucmakiola.calendula.ui.common.formatTimeOfDay import de.jeanlucmakiola.calendula.ui.common.timeOfDayFormatter +import de.jeanlucmakiola.calendula.ui.common.withRepeatedHourZone import de.jeanlucmakiola.calendula.ui.common.reminderLeadTimeLabel import de.jeanlucmakiola.calendula.ui.common.reminderUnitLabel import de.jeanlucmakiola.calendula.ui.common.nextOccurrencesText @@ -169,12 +178,10 @@ import de.jeanlucmakiola.calendula.ui.common.recurrenceText 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.toJavaDayOfWeek import kotlinx.datetime.toJavaLocalDate -import kotlinx.datetime.toInstant import kotlinx.datetime.toJavaLocalTime import kotlinx.datetime.toLocalDateTime import kotlin.time.toJavaInstant @@ -184,6 +191,7 @@ import java.time.format.FormatStyle import java.time.format.TextStyle as JavaTextStyle import java.util.Locale import kotlin.time.Clock +import kotlin.time.Instant /** * Full-screen event form: create (v1.2, from the FAB's anchor date) and edit @@ -192,6 +200,10 @@ import kotlin.time.Clock * first asks how far the change reaches (this occurrence / this and * following / whole series) — then closes. The calendar picker offers only * writable calendars; when editing, the calendar is fixed. + * + * Leaving with unsaved changes asks to save, discard or keep editing (#178). + * While editing, the overflow menu offers Duplicate (the form as it stands, + * handed to [onDuplicate] as a new event), Share and Delete. */ @OptIn(ExperimentalMaterial3Api::class) @Composable @@ -201,13 +213,21 @@ fun EventEditScreen( onSaved: () -> Unit, editKey: LongArray? = null, initialStartMinutes: Int? = null, + initialDraft: LongArray? = null, initialForm: EventForm? = null, initialFormSource: ImportSource = ImportSource.File, onManageCalendars: (() -> Unit)? = null, + onDuplicate: ((EventForm) -> Unit)? = null, + onDeleted: () -> Unit = onSaved, + onLoadFailed: () -> Unit = onClose, + leaveRequested: Boolean = false, + onLeaveDeclined: () -> Unit = {}, visible: Boolean = true, viewModel: EventEditViewModel = hiltViewModel(), ) { - LaunchedEffect(initialDateIso, editKey, initialForm) { + // Keyed on every input that decides the form, so a second draft or slot on + // the same day opens its own form even when the composition is kept alive. + LaunchedEffect(initialDateIso, editKey, initialForm, initialDraft, initialStartMinutes) { when { // A prefilled open: a single-event .ics for review, or an external // ACTION_INSERT intent. The source drives how reminders are seeded. @@ -217,9 +237,14 @@ fun EventEditScreen( beginMillis = editKey[1], endMillis = editKey[2], ) + // A block drafted on the timeline (#153): its own start and end. + initialDraft != null -> viewModel.openDraft( + start = Instant.fromEpochMilliseconds(initialDraft[0]), + end = Instant.fromEpochMilliseconds(initialDraft[1]), + ) else -> { val date = initialDateIso?.let { runCatching { LocalDate.parse(it) }.getOrNull() } - ?: Clock.System.now().toLocalDateTime(TimeZone.currentSystemDefault()).date + ?: Clock.System.now().toLocalDateTime(viewModel.zone.value).date viewModel.openNew(date, initialStartMinutes) } } @@ -235,41 +260,89 @@ fun EventEditScreen( viewModel.reset() onClose() } - // The event vanished between the detail screen and the edit tap — fall - // back to the detail screen, which shows its own failure state. + val hasUnsavedChanges by viewModel.hasUnsavedChanges.collectAsStateWithLifecycle() + var showLeavePrompt by rememberSaveable { mutableStateOf(false) } + var showDeleteDialog by rememberSaveable { mutableStateOf(false) } + // A running save or delete can't be called back, so leaving waits for it; + // its result then closes the form or reports why it didn't. + val requestClose = { + when { + state?.saveState == SaveUiState.Saving -> Unit + hasUnsavedChanges -> showLeavePrompt = true + else -> close() + } + } + // Something else wants this form's place, e.g. a second share (#306). + LaunchedEffect(leaveRequested) { + if (leaveRequested) requestClose() + } + // The event vanished before the form could load it — fall back to the + // detail screen, which shows its own failure state. LaunchedEffect(loadFailed) { - if (loadFailed) close() + if (loadFailed) { + viewModel.reset() + onLoadFailed() + } } val context = LocalContext.current val snackbarHostState = remember { SnackbarHostState() } - // Contextual WRITE_CALENDAR upgrade for v1.0 installs, like delete. - val writePermissionLauncher = rememberLauncherForActivityResult( + val scope = rememberCoroutineScope() + // Save keeps its own launcher: its result calls straight into the ViewModel, + // so a save waiting on the permission dialog survives a rotation. + val savePermissionLauncher = rememberLauncherForActivityResult( contract = ActivityResultContracts.RequestPermission(), ) { granted -> if (granted) viewModel.save() } val onSaveClick = { - val granted = ContextCompat.checkSelfPermission( - context, - Manifest.permission.WRITE_CALENDAR, - ) == PackageManager.PERMISSION_GRANTED - if (granted) { + if (context.canWriteCalendar()) { viewModel.save() } else { - writePermissionLauncher.launch(Manifest.permission.WRITE_CALENDAR) + savePermissionLauncher.launch(Manifest.permission.WRITE_CALENDAR) } } + val shareFailedMessage = stringResource(R.string.event_share_failed) + val shareChooserTitle = stringResource(R.string.event_share_chooser_title) + val onShareClick: () -> Unit = { + scope.launch { + val uri = viewModel.shareUri() + val sent = uri != null && context.sendEventShare(uri, shareChooserTitle) + if (!sent) snackbarHostState.showSnackbar(shareFailedMessage) + } + } + // The copy opens over this form; a form with nothing to lose steps aside. + val onDuplicateClick = rememberWriteAction { + viewModel.duplicateForm()?.let { form -> + onDuplicate?.invoke(form) + if (!hasUnsavedChanges) close() + } + } + val onDeleteClick = rememberWriteAction { showDeleteDialog = true } val saveFailedMessage = stringResource(R.string.event_edit_save_failed) val writeDeniedMessage = stringResource(R.string.event_edit_write_denied) + val deleteFailedMessage = stringResource(R.string.event_delete_failed) + val deleteDeniedMessage = stringResource(R.string.event_delete_write_denied) LaunchedEffect(state?.saveState) { when (state?.saveState) { SaveUiState.Saved -> { viewModel.reset() onSaved() } + SaveUiState.Deleted -> { + viewModel.reset() + onDeleted() + } + SaveUiState.DeleteFailed -> { + viewModel.consumeSaveResult() + snackbarHostState.showSnackbar(deleteFailedMessage, duration = SnackbarDuration.Long) + } + SaveUiState.DeleteDenied -> { + viewModel.consumeSaveResult() + snackbarHostState.showSnackbar(deleteDeniedMessage, duration = SnackbarDuration.Long) + } // A failed save leaves the form looking unchanged, so the snackbar is // the only sign anything happened — long rather than the default // flash (Codeberg #234: it read as "nothing happens at all"). @@ -286,8 +359,11 @@ fun EventEditScreen( } } + // From the inputs, not the loaded state, so the label never flips mid-load. + val opensForEdit = initialForm == null && editKey != null + Scaffold( - modifier = Modifier.predictiveBack(onBack = close, visible = visible), + modifier = Modifier.predictiveBack(onBack = requestClose, visible = visible), snackbarHost = { SnackbarHost(snackbarHostState) }, topBar = { TopAppBar( @@ -295,7 +371,7 @@ fun EventEditScreen( // matching the detail screen's bare top bar. title = {}, navigationIcon = { - IconButton(onClick = close) { + IconButton(onClick = requestClose) { Icon( imageVector = Icons.Default.Close, contentDescription = stringResource(R.string.event_edit_close), @@ -303,12 +379,25 @@ fun EventEditScreen( } }, actions = { + if (state?.isEditing == true) { + EditActionsMenu( + canDelete = state?.isManaged == false, + canDuplicate = onDuplicate != null, + onDuplicate = onDuplicateClick, + onShare = onShareClick, + onDelete = onDeleteClick, + ) + } Button( onClick = onSaveClick, enabled = state != null && state?.saveState != SaveUiState.Saving, modifier = Modifier.padding(end = 12.dp), ) { - Text(stringResource(R.string.event_edit_save)) + Text( + stringResource( + if (opensForEdit) R.string.event_edit_save else R.string.event_edit_create, + ), + ) } }, colors = TopAppBarDefaults.topAppBarColors( @@ -329,11 +418,43 @@ fun EventEditScreen( } } + if (showLeavePrompt) { + UnsavedChangesDialog( + onSave = { + showLeavePrompt = false + onSaveClick() + }, + onDiscard = { + showLeavePrompt = false + close() + }, + onDismiss = { + showLeavePrompt = false + if (leaveRequested) onLeaveDeclined() + }, + ) + } + + val recurs = viewModel.editedEventRecurs() + if (showDeleteDialog && recurs != null) { + DeleteEventDialog( + isRecurring = recurs, + onConfirm = { deleteScope -> + showDeleteDialog = false + viewModel.delete(deleteScope) + }, + onDismiss = { showDeleteDialog = false }, + ) + } + if (state?.saveState == SaveUiState.AwaitingScope) { - SaveScopeDialog( - recurrenceChanged = state?.recurrenceChanged == true, + // A changed rule rules out the single occurrence — an exception row + // can't carry its own rule. + RecurringScopeDialog( + title = stringResource(R.string.event_edit_recurring_title), onSelect = viewModel::saveWithScope, onDismiss = viewModel::consumeSaveResult, + allowOccurrence = state?.recurrenceChanged != true, ) } @@ -373,6 +494,90 @@ fun EventEditScreen( } } +/** Duplicate, Share and Delete for the event being edited, behind an overflow button. */ +@Composable +private fun EditActionsMenu( + canDelete: Boolean, + canDuplicate: Boolean, + onDuplicate: () -> Unit, + onShare: () -> Unit, + onDelete: () -> Unit, +) { + var open by remember { mutableStateOf(false) } + Box { + IconButton(onClick = { open = true }) { + Icon( + imageVector = Icons.Default.MoreVert, + contentDescription = stringResource(R.string.event_edit_more_actions), + ) + } + DropdownMenu(expanded = open, onDismissRequest = { open = false }) { + if (canDuplicate) { + DropdownMenuItem( + text = { Text(stringResource(R.string.event_detail_duplicate)) }, + leadingIcon = { Icon(Icons.Default.ContentCopy, contentDescription = null) }, + onClick = { + open = false + onDuplicate() + }, + ) + } + DropdownMenuItem( + text = { Text(stringResource(R.string.event_detail_share)) }, + leadingIcon = { Icon(Icons.Default.Share, contentDescription = null) }, + onClick = { + open = false + onShare() + }, + ) + // Managed special-dates events have no delete, as on the detail screen. + if (canDelete) { + DropdownMenuItem( + text = { Text(stringResource(R.string.event_detail_delete)) }, + leadingIcon = { Icon(Icons.Default.Delete, contentDescription = null) }, + onClick = { + open = false + onDelete() + }, + ) + } + } + } +} + +/** + * Asked when leaving the form with unsaved changes (#178). Dismissing keeps + * editing; a form with nothing changed closes without asking. + */ +@Composable +private fun UnsavedChangesDialog( + onSave: () -> Unit, + onDiscard: () -> Unit, + onDismiss: () -> Unit, +) { + AlertDialog( + onDismissRequest = onDismiss, + title = { Text(stringResource(R.string.event_edit_unsaved_title)) }, + text = { + Column(verticalArrangement = Arrangement.spacedBy(8.dp)) { + OptionCard( + label = stringResource(R.string.event_edit_unsaved_save), + onClick = onSave, + ) + OptionCard( + label = stringResource(R.string.event_edit_unsaved_discard), + onClick = onDiscard, + ) + } + }, + confirmButton = { + TextButton(onClick = onDismiss) { + Text(stringResource(R.string.event_edit_unsaved_keep)) + } + }, + ) +} + /** * Offer to apply the settings default reminder to an event opened from a `.ics` * file. The file's own reminders are kept unless the user accepts. A plain @@ -450,28 +655,47 @@ private fun SaveConflictDialog( } } -/** - * Scope choice when saving a dirty recurring event: one tap writes just the - * tapped occurrence, it and everything after (series split), or the whole - * series. A changed recurrence rule rules out the single occurrence — an - * exception row can't carry its own rule. - */ -@Composable -private fun SaveScopeDialog( - recurrenceChanged: Boolean, - onSelect: (RecurringWriteScope) -> Unit, - onDismiss: () -> Unit, -) { - RecurringScopeDialog( - title = stringResource(R.string.event_edit_recurring_title), - onSelect = onSelect, - onDismiss = onDismiss, - allowOccurrence = !recurrenceChanged, - ) -} - private enum class PickerTarget { StartDate, StartTime, EndDate, EndTime } +/** A picker card's value over its label, with the drop-down arrow when it opens a picker. */ +@Composable +private fun PickerCardBody( + title: String, + subtitle: String, + showArrow: Boolean = true, + extra: @Composable ColumnScope.() -> Unit = {}, +) = PickerCardBody(AnnotatedString(title), subtitle, showArrow, extra) + +@Composable +private fun PickerCardBody( + title: AnnotatedString, + subtitle: String, + showArrow: Boolean = true, + extra: @Composable ColumnScope.() -> Unit = {}, +) { + Row( + verticalAlignment = Alignment.CenterVertically, + modifier = Modifier.fillMaxWidth(), + ) { + Column(modifier = Modifier.weight(1f)) { + Text(text = title, style = MaterialTheme.typography.titleMedium) + Text( + text = subtitle, + style = MaterialTheme.typography.bodySmall, + color = MaterialTheme.colorScheme.onSurfaceVariant, + ) + extra() + } + if (showArrow) { + Icon( + imageVector = Icons.Default.ArrowDropDown, + contentDescription = null, + tint = MaterialTheme.colorScheme.onSurfaceVariant, + ) + } + } +} + /** * Wrapper for an optional form section: fields added via "more fields" * spring open with the expressive spatial spec instead of popping in. @@ -491,6 +715,9 @@ private fun OptionalFormSection( } } +/** The one full-screen picker the form has open, if any. */ +private enum class EditSheet { Calendar, Reminder, Recurrence, Visibility, Color, Timezone, Field } + @OptIn(ExperimentalMaterial3Api::class) @Composable private fun EventEditContent( @@ -501,24 +728,15 @@ private fun EventEditContent( ) { val form = state.form val locale = currentLocale() + val deviceZone by viewModel.zone.collectAsStateWithLifecycle() val firstDayOfWeek by viewModel.firstDayOfWeek.collectAsStateWithLifecycle() - val dark = isSystemInDarkTheme() + val dark = LocalFloretDarkTheme.current // The title, date and recurrence are managed by the special-dates sync, so // they're locked here; everything else (reminders, location, notes) is the // user's to edit. val locked = state.isManaged - // Read in the form's own window, not the picker's: the focused field lives - // here, so this is the controller that can put its keyboard away. - val focusManager = LocalFocusManager.current - val keyboardController = LocalSoftwareKeyboardController.current var picker by remember { mutableStateOf(null) } - var showCalendarPicker by rememberSaveable { mutableStateOf(false) } - var showReminderPicker by rememberSaveable { mutableStateOf(false) } - var showRecurrencePicker by rememberSaveable { mutableStateOf(false) } - var showVisibilityPicker by rememberSaveable { mutableStateOf(false) } - var showColorPicker by rememberSaveable { mutableStateOf(false) } - var showTimezonePicker by rememberSaveable { mutableStateOf(false) } - var showFieldPicker by rememberSaveable { mutableStateOf(false) } + var sheet by rememberSaveable { mutableStateOf(null) } // Pick a guest from contacts: a one-shot system picker returning the chosen // email row (email + display name). No READ_CONTACTS — the result Intent @@ -559,17 +777,6 @@ private fun EventEditContent( ?: MaterialTheme.colorScheme.primary val gap = 12.dp - // Issue #10: on a fresh create form (setting on, nothing typed yet) focus the - // title and raise the keyboard so the user can type straight away. Keyed on - // Unit so it runs once per open — not on every keystroke — and guarded so - // editing or an imported/prefilled form never grabs focus. - val titleFocusRequester = remember { FocusRequester() } - LaunchedEffect(Unit) { - if (state.autofocusTitle && !state.isEditing && form.title.isBlank()) { - runCatching { titleFocusRequester.requestFocus() } - } - } - // Per-event colour applicability for the resolved calendar: // - palette calendars (Google, …) and local calendars always support it; // - synced calendars with no palette only when the user opted in, and even @@ -589,129 +796,22 @@ private fun EventEditContent( .verticalScroll(rememberScrollState()) .padding(start = 24.dp, end = 24.dp, top = 8.dp, bottom = 40.dp), ) { - // Title: borderless headline, mirroring the detail screen's title + - // accent bar instead of a boxed Material text field. Multi-line so long - // titles wrap instead of scrolling off one line (#33); newlines are - // stripped in setTitle, so this stays a single logical line — the Enter - // key just has no effect. - InlineField( - value = form.title, - onValueChange = viewModel::setTitle, - placeholder = stringResource(R.string.event_edit_title_hint), - textStyle = MaterialTheme.typography.headlineMedium - .copy(fontWeight = FontWeight.SemiBold), - singleLine = false, - enabled = !locked, - modifier = Modifier - .fillMaxWidth() - // Ease the height change as the title wraps to another line - // instead of letting the accent bar + cards below jump. - .animateContentSizeMotion() - .padding(vertical = 4.dp) - .focusRequester(titleFocusRequester), + TitleSection( + state = state, + onTitleChange = viewModel::setTitle, + accent = accent, + calendarName = selectedCalendar?.displayName, ) - FieldLengthCounter( - length = form.title.length, - max = MAX_SINGLE_LINE_FIELD, - modifier = Modifier.fillMaxWidth(), - ) - Spacer(Modifier.height(10.dp)) - Box( - modifier = Modifier - .width(48.dp) - .height(3.dp) - .background(accent, RoundedCornerShape(2.dp)), - ) - if (locked) { - Spacer(Modifier.height(10.dp)) - Text( - text = stringResource( - R.string.event_edit_managed_hint, - selectedCalendar?.displayName - ?.ifBlank { stringResource(R.string.calendar_unnamed) } - .orEmpty(), - ), - style = MaterialTheme.typography.bodySmall, - color = MaterialTheme.colorScheme.onSurfaceVariant, - ) - } Spacer(Modifier.height(20.dp)) - // "When" card: the icon centres on the all-day row (header); the - // start/end rows continue below in the same text column. - EditCard( - icon = Icons.Default.Schedule, - iconContentDescription = null, - header = { - Row( - verticalAlignment = Alignment.CenterVertically, - modifier = Modifier.fillMaxWidth(), - ) { - Text( - text = stringResource(R.string.event_detail_all_day), - style = MaterialTheme.typography.titleMedium, - modifier = Modifier.weight(1f), - ) - Switch( - checked = form.isAllDay, - onCheckedChange = viewModel::setAllDay, - enabled = !locked, - ) - } - }, - ) { - Spacer(Modifier.height(4.dp)) - ScheduleRow( - label = stringResource(R.string.event_edit_starts), - dateTime = form.start, - isAllDay = form.isAllDay, - locale = locale, - onDateClick = { picker = PickerTarget.StartDate }, - onTimeClick = { picker = PickerTarget.StartTime }, - enabled = !locked, - ) - ScheduleRow( - label = stringResource(R.string.event_edit_ends), - dateTime = form.end, - isAllDay = form.isAllDay, - locale = locale, - onDateClick = { picker = PickerTarget.EndDate }, - onTimeClick = { picker = PickerTarget.EndTime }, - isError = EventFormProblem.EndBeforeStart in state.problems, - enabled = !locked, - ) - if (EventFormProblem.EndBeforeStart in state.problems) { - Spacer(Modifier.height(2.dp)) - Text( - text = stringResource(R.string.event_edit_error_end_before_start), - style = MaterialTheme.typography.bodySmall, - color = MaterialTheme.colorScheme.error, - ) - } - // The rows above edit a pinned event in *its own* zone, which is the - // time it was set at — but that says nothing about when it lands for - // whoever is reading it. Spell the local equivalent out rather than - // leaving the user to do the offset arithmetic. Absent (null) unless - // the event is pinned somewhere other than here. - // Keyed rather than recomputed: this sits in the same Column as the - // title field, so it would otherwise re-parse the zone on every - // keystroke. - val localTimes = remember(form.timezone, form.start, form.end, form.isAllDay) { - form.timesIn(TimeZone.currentSystemDefault()) - } - localTimes?.let { (localStart, localEnd) -> - Spacer(Modifier.height(2.dp)) - Text( - text = stringResource( - R.string.event_edit_timezone_local_time, - formatTimeRange(localStart, localEnd, locale), - ), - style = MaterialTheme.typography.bodySmall, - color = MaterialTheme.colorScheme.onSurfaceVariant, - ) - } - } + WhenCard( + state = state, + deviceZone = deviceZone, + locale = locale, + onAllDayChange = viewModel::setAllDay, + onPick = { picker = it }, + ) Spacer(Modifier.height(gap)) @@ -719,160 +819,47 @@ private fun EventEditContent( // different one while editing *moves* the event (copy+delete on save, // since CALENDAR_ID can't be updated in place). Managed special-dates // events stay locked: the contact sync owns their calendar. - EditCard( - icon = Icons.Default.CalendarMonth, - iconContentDescription = stringResource(R.string.event_detail_calendar), - iconTint = accent, - onClick = { showCalendarPicker = true } + CalendarCard( + calendar = selectedCalendar, + accent = accent, + onClick = { sheet = EditSheet.Calendar } .takeIf { state.calendars.isNotEmpty() && !state.isManaged }, - ) { - Text( - text = selectedCalendar?.displayName - ?.ifBlank { stringResource(R.string.calendar_unnamed) } - ?: stringResource(R.string.event_edit_error_no_calendar), - style = MaterialTheme.typography.titleMedium, - color = if (selectedCalendar == null) { - MaterialTheme.colorScheme.error - } else { - Color.Unspecified - }, - ) - selectedCalendar?.accountName?.takeIf { it.isNotBlank() }?.let { account -> - Text( - text = account, - style = MaterialTheme.typography.bodySmall, - color = MaterialTheme.colorScheme.onSurfaceVariant, - ) - } - } + ) // Optional sections: which ones render by default is a setting; the // rest unfold behind the "more fields" button below. OptionalFormSection(visible = EventFormField.Timezone in state.visibleFields) { Spacer(Modifier.height(gap)) - EditCard( - icon = Icons.Default.Public, - iconContentDescription = null, - onClick = { showTimezonePicker = true }, - ) { - Row( - verticalAlignment = Alignment.CenterVertically, - modifier = Modifier.fillMaxWidth(), - ) { - // Resolved at the event's own start, not at "now": the - // abbreviation and offset shown ("CEST · GMT+02:00") must be - // the ones that apply when the event actually happens. - val pinned = remember(form.timezone, form.start, locale) { - form.timezone - ?.let { id -> runCatching { id to TimeZone.of(id) }.getOrNull() } - ?.let { (id, zone) -> - timeZoneOptionOf( - id, - locale, - at = form.start.toInstant(zone).toJavaInstant(), - regionOf = ::icuTimeZoneRegion, - ) - } - } - Column(modifier = Modifier.weight(1f)) { - Text( - text = pinned?.label - ?: stringResource(R.string.event_edit_timezone_device), - style = MaterialTheme.typography.titleMedium, - ) - Text( - text = pinned?.let { zoneDescriptor(it) } - ?: stringResource(R.string.event_edit_timezone_device_summary), - style = MaterialTheme.typography.bodySmall, - color = MaterialTheme.colorScheme.onSurfaceVariant, - ) - } - Icon( - imageVector = Icons.Default.ArrowDropDown, - contentDescription = null, - tint = MaterialTheme.colorScheme.onSurfaceVariant, - ) - } - } + TimezoneCard(form = form, locale = locale, onClick = { sheet = EditSheet.Timezone }) } OptionalFormSection(visible = EventFormField.Location in state.visibleFields) { Spacer(Modifier.height(gap)) - EditCard( - icon = Icons.Default.Place, - iconContentDescription = stringResource(R.string.event_detail_location), - iconAtTop = true, - ) { - Row(verticalAlignment = Alignment.Top) { - Column(modifier = Modifier.weight(1f)) { - InlineField( - value = form.location, - onValueChange = viewModel::setLocation, - placeholder = stringResource(R.string.event_detail_location), - // A location is as often a meeting URL as an address, - // and "Zoom.us/j/123" reads wrong (#146). - capitalization = KeyboardCapitalization.None, - // Multi-line so a long address or meeting URL wraps and - // the card grows instead of scrolling off one line - // (#273). The field holds no newlines of its own, so - // the IME's action key closes the keyboard rather than - // inserting a break setLocation would only fold away. - singleLine = false, - imeAction = ImeAction.Done, - modifier = Modifier - .fillMaxWidth() - .animateContentSizeMotion() - .padding(vertical = 4.dp), - ) - FieldLengthCounter( - length = form.location.length, - max = MAX_SINGLE_LINE_FIELD, + LocationCard( + location = form.location, + onLocationChange = viewModel::setLocation, + onPickContact = { + runCatching { + pickContactAddress.launch( + Intent( + Intent.ACTION_PICK, + ContactsContract.CommonDataKinds.StructuredPostal.CONTENT_URI, + ), ) } - // The box is exactly one text line tall, so the button - // centres on the first line without making a single-line - // card taller than its text; requiredSize keeps the - // button's own 40dp ripple. - Box( - modifier = Modifier.height(firstLineHeight()), - contentAlignment = Alignment.Center, - ) { - IconButton( - onClick = { - runCatching { - pickContactAddress.launch( - Intent( - Intent.ACTION_PICK, - ContactsContract.CommonDataKinds.StructuredPostal - .CONTENT_URI, - ), - ) - } - }, - modifier = Modifier.requiredSize(40.dp), - ) { - Icon( - imageVector = Icons.Default.Contacts, - contentDescription = stringResource( - R.string.event_edit_location_from_contacts, - ), - tint = MaterialTheme.colorScheme.onSurfaceVariant, - modifier = Modifier.size(22.dp), - ) - } - } - } - } + }, + ) } OptionalFormSection(visible = EventFormField.Description in state.visibleFields) { Spacer(Modifier.height(gap)) - EditCard( + IconInfoCard( icon = Icons.AutoMirrored.Filled.Notes, iconContentDescription = stringResource(R.string.event_detail_description), - iconAtTop = true, + iconAlignment = Alignment.Top, + iconTopPadding = ((firstLineHeight() - 24.dp) / 2).coerceAtLeast(0.dp), ) { - InlineField( + InlineTextField( value = form.description, onValueChange = viewModel::setDescription, placeholder = stringResource(R.string.event_detail_description), @@ -884,206 +871,58 @@ private fun EventEditContent( OptionalFormSection(visible = EventFormField.Reminders in state.visibleFields) { Spacer(Modifier.height(gap)) - // A grouped list like guests: each reminder is its own tonal card - // with connected corners, the last row being "Add reminder". - val reminders = form.reminders - val rows = reminders.size + 1 - reminders.forEachIndexed { index, minutes -> - GroupedItemCard( - position = positionOf(index, rows), - icon = Icons.Default.Notifications, - title = reminderLabel(minutes), - removeContentDescription = stringResource(R.string.event_edit_remove_reminder), - onRemove = { viewModel.removeReminder(minutes) }, - ) - } - AddActionCard( - label = stringResource(R.string.event_edit_add_reminder), - position = positionOf(reminders.size, rows), - onClick = { showReminderPicker = true }, + RemindersSection( + reminders = form.reminders, + onRemove = viewModel::removeReminder, + onAdd = { sheet = EditSheet.Reminder }, ) } OptionalFormSection(visible = EventFormField.Recurrence in state.visibleFields) { Spacer(Modifier.height(gap)) - EditCard( - icon = Icons.Default.Repeat, - iconContentDescription = null, - onClick = if (locked) null else ({ showRecurrencePicker = true }), - ) { - Row( - verticalAlignment = Alignment.CenterVertically, - modifier = Modifier.fillMaxWidth(), - ) { - Column(modifier = Modifier.weight(1f)) { - Text( - text = form.rrule?.let { recurrenceText(it, locale) } - ?: AnnotatedString(stringResource(R.string.event_edit_recurrence_none)), - style = MaterialTheme.typography.titleMedium, - ) - Text( - text = stringResource(R.string.event_detail_recurrence), - style = MaterialTheme.typography.bodySmall, - color = MaterialTheme.colorScheme.onSurfaceVariant, - ) - } - Icon( - imageVector = Icons.Default.ArrowDropDown, - contentDescription = null, - tint = MaterialTheme.colorScheme.onSurfaceVariant, - ) - } - if (EventFormProblem.RecurrenceEndsBeforeStart in state.problems) { - Spacer(Modifier.height(2.dp)) - Text( - text = stringResource(R.string.event_edit_error_recurrence_ends_before_start), - style = MaterialTheme.typography.bodySmall, - color = MaterialTheme.colorScheme.error, - ) - } - } + RecurrenceCard( + state = state, + locale = locale, + onClick = if (locked) null else ({ sheet = EditSheet.Recurrence }), + ) } OptionalFormSection(visible = EventFormField.Availability in state.visibleFields) { Spacer(Modifier.height(gap)) - EditCard( - icon = Icons.Default.EventAvailable, - iconContentDescription = null, - header = { - Text( - text = stringResource(R.string.event_edit_availability), - style = MaterialTheme.typography.titleMedium, - ) - }, - ) { - Spacer(Modifier.height(8.dp)) - SingleChoiceSegmentedButtonRow(modifier = Modifier.fillMaxWidth()) { - SegmentedButton( - selected = form.availability == Availability.Busy, - onClick = { viewModel.setAvailability(Availability.Busy) }, - shape = SegmentedButtonDefaults.itemShape(index = 0, count = 2), - ) { Text(stringResource(R.string.event_availability_busy)) } - SegmentedButton( - selected = form.availability == Availability.Free, - onClick = { viewModel.setAvailability(Availability.Free) }, - shape = SegmentedButtonDefaults.itemShape(index = 1, count = 2), - ) { Text(stringResource(R.string.event_availability_free)) } - } - } + AvailabilityCard(availability = form.availability, onSelect = viewModel::setAvailability) } OptionalFormSection(visible = EventFormField.Visibility in state.visibleFields) { Spacer(Modifier.height(gap)) - EditCard( + IconInfoCard( icon = Icons.Default.Lock, iconContentDescription = null, - onClick = { showVisibilityPicker = true }, + onClick = { sheet = EditSheet.Visibility }, ) { - Row( - verticalAlignment = Alignment.CenterVertically, - modifier = Modifier.fillMaxWidth(), - ) { - Column(modifier = Modifier.weight(1f)) { - Text( - text = stringResource(accessLevelLabel(form.accessLevel)), - style = MaterialTheme.typography.titleMedium, - ) - Text( - text = stringResource(R.string.event_edit_visibility), - style = MaterialTheme.typography.bodySmall, - color = MaterialTheme.colorScheme.onSurfaceVariant, - ) - } - Icon( - imageVector = Icons.Default.ArrowDropDown, - contentDescription = null, - tint = MaterialTheme.colorScheme.onSurfaceVariant, - ) - } + PickerCardBody( + title = stringResource(accessLevelLabel(form.accessLevel)), + subtitle = stringResource(R.string.event_edit_visibility), + ) } } OptionalFormSection(visible = EventFormField.Color in state.visibleFields) { Spacer(Modifier.height(gap)) - // The swatch the event will paint with: its own colour, else the - // calendar's. The Palette icon takes that colour as a preview. - val swatch = form.color ?: selectedCalendar?.color - EditCard( - icon = Icons.Default.Palette, - iconContentDescription = stringResource(R.string.event_edit_color), - iconTint = if (colorSupported && swatch != null) { - eventFill(swatch, dark, soften) - } else { - MaterialTheme.colorScheme.onSurfaceVariant - }, - onClick = { showColorPicker = true }.takeIf { colorSupported }, - ) { - Row( - verticalAlignment = Alignment.CenterVertically, - modifier = Modifier.fillMaxWidth(), - ) { - Column(modifier = Modifier.weight(1f)) { - Text( - text = stringResource( - when { - !colorSupported -> R.string.event_edit_color_unsupported - form.color != null -> R.string.event_edit_color_custom - else -> R.string.event_edit_color_default - }, - ), - style = MaterialTheme.typography.titleMedium, - ) - Text( - text = stringResource( - if (colorSupported) { - R.string.event_edit_color - } else { - R.string.event_edit_color_unsupported_hint - }, - ), - style = MaterialTheme.typography.bodySmall, - color = MaterialTheme.colorScheme.onSurfaceVariant, - ) - if (colorSyncRisk) { - Spacer(Modifier.height(2.dp)) - Text( - text = stringResource(R.string.event_edit_color_sync_warning), - style = MaterialTheme.typography.bodySmall, - color = MaterialTheme.colorScheme.onSurfaceVariant, - ) - } - } - if (colorSupported) { - Icon( - imageVector = Icons.Default.ArrowDropDown, - contentDescription = null, - tint = MaterialTheme.colorScheme.onSurfaceVariant, - ) - } - } - } + ColorCard( + color = form.color, + calendarColor = selectedCalendar?.color, + supported = colorSupported, + syncRisk = colorSyncRisk, + onClick = { sheet = EditSheet.Color }.takeIf { colorSupported }, + ) } OptionalFormSection(visible = EventFormField.Attendees in state.visibleFields) { Spacer(Modifier.height(gap)) - // Guests are an inline grouped list: each is a tonal card with a - // role toggle + remove, and the trailing card is an inline email - // field — type an address, press Done, it commits. Below sits an - // honest note — Calendula never sends invitations, so whether a - // guest is notified is the calendar backend's call. - val guests = form.attendees - val rows = guests.size + 1 - guests.forEachIndexed { index, attendee -> - GuestCard( - attendee = attendee, - position = positionOf(index, rows), - onToggleOptional = { viewModel.setAttendeeOptional(attendee, it) }, - onRemove = { viewModel.removeAttendee(attendee) }, - ) - } - AddGuestInlineCard( - position = positionOf(guests.size, rows), - onAdd = { viewModel.addAttendee(it) }, + GuestsSection( + guests = form.attendees, + isLocalCalendar = isLocalCalendar, + viewModel = viewModel, onPickContact = { runCatching { pickContact.launch( @@ -1095,25 +934,12 @@ private fun EventEditContent( } }, ) - Spacer(Modifier.height(8.dp)) - Text( - text = stringResource( - if (isLocalCalendar) { - R.string.event_edit_attendees_note_local - } else { - R.string.event_edit_attendees_note_synced - }, - ), - style = MaterialTheme.typography.bodySmall, - color = MaterialTheme.colorScheme.onSurfaceVariant, - modifier = Modifier.padding(horizontal = 4.dp), - ) } OptionalFormSection(visible = state.hiddenFields.isNotEmpty()) { Spacer(Modifier.height(20.dp)) TextButton( - onClick = { showFieldPicker = true }, + onClick = { sheet = EditSheet.Field }, modifier = Modifier.align(Alignment.CenterHorizontally), ) { Icon( @@ -1151,112 +977,564 @@ private fun EventEditContent( null -> Unit } - // A full-screen picker is a change of place, so the keyboard shouldn't - // follow it. The field keeps its text; only focus and the IME go. - LaunchedEffect(showCalendarPicker) { - if (showCalendarPicker) { - focusManager.clearFocus(force = true) - keyboardController?.hide() - } - } - - if (showCalendarPicker) { - CalendarPicker( - calendars = state.calendars, - selectedId = form.calendarId, - onSelect = { - viewModel.setCalendar(it) - showCalendarPicker = false - }, - // Close the picker first: it is a Compose Dialog in its own window, - // always above the activity's content, so the manager would - // otherwise open behind it and the tap would look dead. - onManageCalendars = onManageCalendars?.let { openManager -> - { - showCalendarPicker = false - openManager() - } - }, - onDismiss = { showCalendarPicker = false }, + sheet?.let { open -> + EditSheetHost( + sheet = open, + state = state, + viewModel = viewModel, + firstDayOfWeek = firstDayOfWeek, + colorSyncRisk = colorSyncRisk, + onManageCalendars = onManageCalendars, + onClose = { sheet = null }, ) } +} - if (showReminderPicker) { - ReminderPickerDialog( +/** + * The borderless title over the accent bar, mirroring the detail screen's title + * instead of a boxed Material text field. Locked events say which calendar owns + * them. + */ +@Composable +private fun TitleSection( + state: EventEditUiState, + onTitleChange: (String) -> Unit, + accent: Color, + calendarName: String?, +) { + val form = state.form + // Issue #10: on a fresh create form (setting on, nothing typed yet) focus the + // title and raise the keyboard so the user can type straight away. Keyed on + // Unit so it runs once per open — not on every keystroke — and guarded so + // editing or an imported/prefilled form never grabs focus. + val titleFocusRequester = remember { FocusRequester() } + LaunchedEffect(Unit) { + if (state.autofocusTitle && !state.isEditing && form.title.isBlank()) { + runCatching { titleFocusRequester.requestFocus() } + } + } + // Multi-line so long titles wrap instead of scrolling off one line (#33); + // newlines are stripped in setTitle, so this stays a single logical line — + // the Enter key just has no effect. + InlineTextField( + value = form.title, + onValueChange = onTitleChange, + placeholder = stringResource(R.string.event_edit_title_hint), + textStyle = MaterialTheme.typography.headlineMedium + .copy(fontWeight = FontWeight.SemiBold), + singleLine = false, + enabled = !state.isManaged, + modifier = Modifier + .fillMaxWidth() + // Ease the height change as the title wraps to another line + // instead of letting the accent bar + cards below jump. + .animateContentSizeMotion() + .padding(vertical = 4.dp) + .focusRequester(titleFocusRequester), + ) + FieldLengthCounter( + length = form.title.length, + max = MAX_SINGLE_LINE_FIELD, + modifier = Modifier.fillMaxWidth(), + ) + Spacer(Modifier.height(10.dp)) + Box( + modifier = Modifier + .width(48.dp) + .height(3.dp) + .background(accent, RoundedCornerShape(2.dp)), + ) + if (state.isManaged) { + Spacer(Modifier.height(10.dp)) + Text( + text = stringResource( + R.string.event_edit_managed_hint, + calendarName?.orUnnamed().orEmpty(), + ), + style = MaterialTheme.typography.bodySmall, + color = MaterialTheme.colorScheme.onSurfaceVariant, + ) + } +} + +/** + * "When" card: the icon centres on the all-day row (header); the start/end rows + * continue below in the same text column. + */ +@Composable +private fun WhenCard( + state: EventEditUiState, + deviceZone: TimeZone, + locale: Locale, + onAllDayChange: (Boolean) -> Unit, + onPick: (PickerTarget) -> Unit, +) { + val form = state.form + val locked = state.isManaged + IconInfoCard( + icon = Icons.Default.Schedule, + iconContentDescription = null, + header = { + Row( + verticalAlignment = Alignment.CenterVertically, + modifier = Modifier.fillMaxWidth(), + ) { + Text( + text = stringResource(R.string.event_detail_all_day), + style = MaterialTheme.typography.titleMedium, + modifier = Modifier.weight(1f), + ) + Switch( + checked = form.isAllDay, + onCheckedChange = onAllDayChange, + enabled = !locked, + ) + } + }, + ) { + Spacer(Modifier.height(4.dp)) + val formZone = remember(form.timezone, deviceZone) { form.resolvedZone(deviceZone) } + val startAt = remember(form.start, formZone) { form.startInstant(formZone) } + val endAt = remember(form.end, formZone) { form.endInstant(formZone) } + ScheduleRow( + label = stringResource(R.string.event_edit_starts), + dateTime = form.start.dateTime, + instant = startAt, + zone = formZone, + isAllDay = form.isAllDay, + locale = locale, + onDateClick = { onPick(PickerTarget.StartDate) }, + onTimeClick = { onPick(PickerTarget.StartTime) }, + enabled = !locked, + ) + ScheduleRow( + label = stringResource(R.string.event_edit_ends), + dateTime = form.end.dateTime, + instant = endAt, + zone = formZone, + isAllDay = form.isAllDay, + locale = locale, + onDateClick = { onPick(PickerTarget.EndDate) }, + onTimeClick = { onPick(PickerTarget.EndTime) }, + isError = EventFormProblem.EndBeforeStart in state.problems, + enabled = !locked, + ) + if (EventFormProblem.EndBeforeStart in state.problems) { + Spacer(Modifier.height(2.dp)) + Text( + text = stringResource(R.string.event_edit_error_end_before_start), + style = MaterialTheme.typography.bodySmall, + color = MaterialTheme.colorScheme.error, + ) + } + // A pinned event's local equivalent, shown only when pinned elsewhere. + val pinnedAway = remember(form.timezone, form.isAllDay, deviceZone) { + form.isPinnedAwayFrom(deviceZone) + } + if (pinnedAway) { + Spacer(Modifier.height(2.dp)) + Text( + text = stringResource( + R.string.event_edit_timezone_local_time, + formatTimeRange(startAt, endAt, deviceZone, locale), + ), + style = MaterialTheme.typography.bodySmall, + color = MaterialTheme.colorScheme.onSurfaceVariant, + ) + } + } +} + +@Composable +private fun CalendarCard(calendar: CalendarSource?, accent: Color, onClick: (() -> Unit)?) { + IconInfoCard( + icon = Icons.Default.CalendarMonth, + iconContentDescription = stringResource(R.string.event_detail_calendar), + iconTint = accent, + onClick = onClick, + ) { + Text( + text = calendar?.displayName + ?.orUnnamed() + ?: stringResource(R.string.event_edit_error_no_calendar), + style = MaterialTheme.typography.titleMedium, + color = if (calendar == null) { + MaterialTheme.colorScheme.error + } else { + Color.Unspecified + }, + ) + calendar?.accountName?.takeIf { it.isNotBlank() }?.let { account -> + Text( + text = account, + style = MaterialTheme.typography.bodySmall, + color = MaterialTheme.colorScheme.onSurfaceVariant, + ) + } + } +} + +@Composable +private fun TimezoneCard(form: EventForm, locale: Locale, onClick: () -> Unit) { + IconInfoCard( + icon = Icons.Default.Public, + iconContentDescription = null, + onClick = onClick, + ) { + // Resolved at the event's own start, not at "now": the + // abbreviation and offset shown ("CEST · GMT+02:00") must be + // the ones that apply when the event actually happens. + val pinned = remember(form.timezone, form.start, locale) { + form.timezone + ?.let { id -> runCatching { id to TimeZone.of(id) }.getOrNull() } + ?.let { (id, zone) -> + timeZoneOptionOf( + id, + locale, + at = form.startInstant(zone).toJavaInstant(), + regionOf = ::icuTimeZoneRegion, + ) + } + } + PickerCardBody( + title = pinned?.label ?: stringResource(R.string.event_edit_timezone_device), + subtitle = pinned?.let { zoneDescriptor(it) } + ?: stringResource(R.string.event_edit_timezone_device_summary), + ) + } +} + +@Composable +private fun LocationCard( + location: String, + onLocationChange: (String) -> Unit, + onPickContact: () -> Unit, +) { + IconInfoCard( + icon = Icons.Default.Place, + iconContentDescription = stringResource(R.string.event_detail_location), + iconAlignment = Alignment.Top, + iconTopPadding = ((firstLineHeight() - 24.dp) / 2).coerceAtLeast(0.dp), + ) { + Row(verticalAlignment = Alignment.Top) { + Column(modifier = Modifier.weight(1f)) { + InlineTextField( + value = location, + onValueChange = onLocationChange, + placeholder = stringResource(R.string.event_detail_location), + // A location is as often a meeting URL as an address, + // and "Zoom.us/j/123" reads wrong (#146). + capitalization = KeyboardCapitalization.None, + // Multi-line so a long address or meeting URL wraps and + // the card grows instead of scrolling off one line + // (#273). The field holds no newlines of its own, so + // the IME's action key closes the keyboard rather than + // inserting a break setLocation would only fold away. + singleLine = false, + imeAction = ImeAction.Done, + modifier = Modifier + .fillMaxWidth() + .animateContentSizeMotion() + .padding(vertical = 4.dp), + ) + FieldLengthCounter( + length = location.length, + max = MAX_SINGLE_LINE_FIELD, + ) + } + // The box is exactly one text line tall, so the button + // centres on the first line without making a single-line + // card taller than its text; requiredSize keeps the + // button's own 40dp ripple. + Box( + modifier = Modifier.height(firstLineHeight()), + contentAlignment = Alignment.Center, + ) { + IconButton( + onClick = onPickContact, + modifier = Modifier.requiredSize(40.dp), + ) { + Icon( + imageVector = Icons.Default.Contacts, + contentDescription = stringResource( + R.string.event_edit_location_from_contacts, + ), + tint = MaterialTheme.colorScheme.onSurfaceVariant, + modifier = Modifier.size(22.dp), + ) + } + } + } + } +} + +/** + * A grouped list like guests: each reminder is its own tonal card with + * connected corners, the last row being "Add reminder". + */ +@Composable +private fun RemindersSection(reminders: List, onRemove: (Int) -> Unit, onAdd: () -> Unit) { + val rows = reminders.size + 1 + reminders.forEachIndexed { index, minutes -> + GroupedItemCard( + position = positionOf(index, rows), + icon = Icons.Default.Notifications, + title = reminderLeadTimeLabel(minutes), + removeContentDescription = stringResource(R.string.event_edit_remove_reminder), + onRemove = { onRemove(minutes) }, + ) + } + AddActionCard( + label = stringResource(R.string.event_edit_add_reminder), + position = positionOf(reminders.size, rows), + onClick = onAdd, + ) +} + +@Composable +private fun RecurrenceCard(state: EventEditUiState, locale: Locale, onClick: (() -> Unit)?) { + IconInfoCard( + icon = Icons.Default.Repeat, + iconContentDescription = null, + onClick = onClick, + ) { + PickerCardBody( + title = state.form.rrule?.let { recurrenceText(it, locale) } + ?: AnnotatedString(stringResource(R.string.event_edit_recurrence_none)), + subtitle = stringResource(R.string.event_detail_recurrence), + ) + if (EventFormProblem.RecurrenceEndsBeforeStart in state.problems) { + Spacer(Modifier.height(2.dp)) + Text( + text = stringResource(R.string.event_edit_error_recurrence_ends_before_start), + style = MaterialTheme.typography.bodySmall, + color = MaterialTheme.colorScheme.error, + ) + } + } +} + +@OptIn(ExperimentalMaterial3Api::class) +@Composable +private fun AvailabilityCard(availability: Availability, onSelect: (Availability) -> Unit) { + IconInfoCard( + icon = Icons.Default.EventAvailable, + iconContentDescription = null, + header = { + Text( + text = stringResource(R.string.event_edit_availability), + style = MaterialTheme.typography.titleMedium, + ) + }, + ) { + Spacer(Modifier.height(8.dp)) + SingleChoiceSegmentedButtonRow(modifier = Modifier.fillMaxWidth()) { + SegmentedButton( + selected = availability == Availability.Busy, + onClick = { onSelect(Availability.Busy) }, + shape = SegmentedButtonDefaults.itemShape(index = 0, count = 2), + ) { Text(stringResource(R.string.event_availability_busy)) } + SegmentedButton( + selected = availability == Availability.Free, + onClick = { onSelect(Availability.Free) }, + shape = SegmentedButtonDefaults.itemShape(index = 1, count = 2), + ) { Text(stringResource(R.string.event_availability_free)) } + } + } +} + +/** + * The swatch the event will paint with: its own [color], else the calendar's. + * The Palette icon takes that colour as a preview. + */ +@Composable +private fun ColorCard( + color: Int?, + calendarColor: Int?, + supported: Boolean, + syncRisk: Boolean, + onClick: (() -> Unit)?, +) { + val swatch = color ?: calendarColor + IconInfoCard( + icon = Icons.Default.Palette, + iconContentDescription = stringResource(R.string.event_edit_color), + iconTint = if (supported && swatch != null) { + eventFill(swatch, LocalFloretDarkTheme.current, LocalSoftenColors.current) + } else { + MaterialTheme.colorScheme.onSurfaceVariant + }, + onClick = onClick, + ) { + PickerCardBody( + title = stringResource( + when { + !supported -> R.string.event_edit_color_unsupported + color != null -> R.string.event_edit_color_custom + else -> R.string.event_edit_color_default + }, + ), + subtitle = stringResource( + if (supported) R.string.event_edit_color else R.string.event_edit_color_unsupported_hint, + ), + showArrow = supported, + ) { + if (syncRisk) { + Spacer(Modifier.height(2.dp)) + Text( + text = stringResource(R.string.event_edit_color_sync_warning), + style = MaterialTheme.typography.bodySmall, + color = MaterialTheme.colorScheme.onSurfaceVariant, + ) + } + } + } +} + +/** + * Guests are an inline grouped list: each is a tonal card with a role toggle + + * remove, and the trailing card is an inline email field — type an address, + * press Done, it commits. Below sits an honest note — Calendula never sends + * invitations, so whether a guest is notified is the calendar backend's call. + */ +@Composable +private fun GuestsSection( + guests: List, + isLocalCalendar: Boolean, + viewModel: EventEditViewModel, + onPickContact: () -> Unit, +) { + val rows = guests.size + 1 + guests.forEachIndexed { index, attendee -> + GuestCard( + attendee = attendee, + position = positionOf(index, rows), + onToggleOptional = { viewModel.setAttendeeOptional(attendee, it) }, + onRemove = { viewModel.removeAttendee(attendee) }, + ) + } + AddGuestInlineCard( + position = positionOf(guests.size, rows), + onAdd = { viewModel.addAttendee(it) }, + onPickContact = onPickContact, + ) + Spacer(Modifier.height(8.dp)) + Text( + text = stringResource( + if (isLocalCalendar) { + R.string.event_edit_attendees_note_local + } else { + R.string.event_edit_attendees_note_synced + }, + ), + style = MaterialTheme.typography.bodySmall, + color = MaterialTheme.colorScheme.onSurfaceVariant, + modifier = Modifier.padding(horizontal = 4.dp), + ) +} + +/** The open [sheet]; each one closes itself through [onClose] once it has applied its pick. */ +@Composable +private fun EditSheetHost( + sheet: EditSheet, + state: EventEditUiState, + viewModel: EventEditViewModel, + firstDayOfWeek: DayOfWeek, + colorSyncRisk: Boolean, + onManageCalendars: (() -> Unit)?, + onClose: () -> Unit, +) { + val form = state.form + // Read in the form's own window, not the picker's: the focused field lives + // there, so this is the controller that can put its keyboard away. + val focusManager = LocalFocusManager.current + val keyboardController = LocalSoftwareKeyboardController.current + when (sheet) { + EditSheet.Calendar -> { + // A full-screen picker is a change of place, so the keyboard shouldn't + // follow it. The field keeps its text; only focus and the IME go. + LaunchedEffect(Unit) { + focusManager.clearFocus(force = true) + keyboardController?.hide() + } + CalendarPicker( + calendars = state.calendars, + selectedId = form.calendarId, + onSelect = { + viewModel.setCalendar(it) + onClose() + }, + // Close the picker first: it is a Compose Dialog in its own window, + // always above the activity's content, so the manager would + // otherwise open behind it and the tap would look dead. + onManageCalendars = onManageCalendars?.let { openManager -> + { + onClose() + openManager() + } + }, + onDismiss = onClose, + ) + } + EditSheet.Reminder -> ReminderPickerDialog( alreadyChosen = form.reminders, onSelect = { minutes -> viewModel.addReminder(minutes) - showReminderPicker = false + onClose() }, - onDismiss = { showReminderPicker = false }, + onDismiss = onClose, ) - } - - - if (showRecurrencePicker) { - RecurrencePickerDialog( + EditSheet.Recurrence -> RecurrencePickerDialog( current = form.rrule, startDate = form.start.date, firstDayOfWeek = firstDayOfWeek, onSelect = { rrule -> viewModel.setRecurrence(rrule) - showRecurrencePicker = false + onClose() }, - onDismiss = { showRecurrencePicker = false }, + onDismiss = onClose, ) - } - - if (showVisibilityPicker) { - VisibilityPickerDialog( + EditSheet.Visibility -> VisibilityPickerDialog( selected = form.accessLevel, onSelect = { level -> viewModel.setAccessLevel(level) - showVisibilityPicker = false + onClose() }, - onDismiss = { showVisibilityPicker = false }, + onDismiss = onClose, ) - } - - if (showTimezonePicker) { - TimeZonePickerDialog( + EditSheet.Timezone -> TimeZonePickerDialog( selected = form.timezone, deviceZoneId = ZoneId.systemDefault().id, recents = state.recentTimeZones, onSelect = viewModel::setTimezone, - onDismiss = { showTimezonePicker = false }, + onDismiss = onClose, ) - } - - if (showColorPicker) { - ColorPickerDialog( + EditSheet.Color -> ColorPickerDialog( palette = state.colorPalette, selected = form.color, hasExplicitColor = form.color != null, syncWarning = colorSyncRisk, onPickKey = { key, argb -> viewModel.setColorKey(key, argb) - showColorPicker = false + onClose() }, onPickRaw = { argb -> viewModel.setColorRaw(argb) - showColorPicker = false + onClose() }, onClear = { viewModel.clearColor() - showColorPicker = false + onClose() }, - onDismiss = { showColorPicker = false }, + onDismiss = onClose, ) - } - - if (showFieldPicker) { - FieldPickerDialog( + EditSheet.Field -> FieldPickerDialog( hiddenFields = state.hiddenFields, onSelect = { field -> viewModel.revealField(field) - showFieldPicker = false + onClose() }, - onDismiss = { showFieldPicker = false }, + onDismiss = onClose, ) } } @@ -1283,9 +1561,6 @@ private fun FieldPickerDialog( } } -/** Quick-pick lead times offered as chips in the reminder dialog. */ -private val REMINDER_QUICK_PICKS = REMINDER_PRESETS - /** * Reminder picker, two steps: the common lead times as a tappable list * (one tap adds and closes), with "Custom" at the bottom switching to an @@ -1319,11 +1594,11 @@ private fun ReminderPickerDialog( }, ) { if (!customMode) { - val presets = REMINDER_QUICK_PICKS.filterNot { it in alreadyChosen } + val presets = REMINDER_PRESETS.filterNot { it in alreadyChosen } val rowCount = presets.size + 1 presets.forEachIndexed { index, minutes -> GroupedRow( - title = reminderLabel(minutes), + title = reminderLeadTimeLabel(minutes), position = positionOf(index, rowCount), onClick = { onSelect(minutes) }, ) @@ -1461,12 +1736,7 @@ private fun RecurrencePickerDialog( GroupedRow( title = stringResource(R.string.event_edit_recurrence_none), position = positionOf(0, rowCount), - selected = current == null, - trailing = if (current == null) { - { SelectedCheck() } - } else { - null - }, + checked = current == null, onClick = { onSelect(null) }, ) RecurrenceFreq.entries.forEachIndexed { index, entry -> @@ -1474,24 +1744,14 @@ private fun RecurrencePickerDialog( title = stringResource(recurrencePresetLabel(entry)), summary = nextOccurrencesText(SimpleRecurrence(entry), startDate, locale), position = positionOf(index + 1, rowCount), - selected = isPlainPreset && parsed?.freq == entry, - trailing = if (isPlainPreset && parsed?.freq == entry) { - { SelectedCheck() } - } else { - null - }, + checked = isPlainPreset && parsed?.freq == entry, onClick = { onSelect(SimpleRecurrence(entry).toRRule()) }, ) } GroupedRow( title = stringResource(R.string.event_edit_recurrence_custom), position = positionOf(rowCount - 1, rowCount), - selected = current != null && !isPlainPreset, - trailing = if (current != null && !isPlainPreset) { - { SelectedCheck() } - } else { - null - }, + checked = current != null && !isPlainPreset, onClick = { customMode = true }, ) } else { @@ -1620,24 +1880,14 @@ private fun RecurrencePickerDialog( GroupedRow( title = stringResource(R.string.event_edit_recurrence_end_never), position = Position.Top, - selected = endMode == RecurrenceEndMode.Never, - trailing = if (endMode == RecurrenceEndMode.Never) { - { SelectedCheck() } - } else { - null - }, + checked = endMode == RecurrenceEndMode.Never, onClick = { endMode = RecurrenceEndMode.Never }, ) GroupedRow( title = stringResource(R.string.event_edit_recurrence_end_until), summary = untilSummary, position = Position.Middle, - selected = endMode == RecurrenceEndMode.Until, - trailing = if (endMode == RecurrenceEndMode.Until) { - { SelectedCheck() } - } else { - null - }, + checked = endMode == RecurrenceEndMode.Until, onClick = { endMode = RecurrenceEndMode.Until showUntilPicker = true @@ -1650,12 +1900,7 @@ private fun RecurrencePickerDialog( } else { Position.Bottom }, - selected = endMode == RecurrenceEndMode.Count, - trailing = if (endMode == RecurrenceEndMode.Count) { - { SelectedCheck() } - } else { - null - }, + checked = endMode == RecurrenceEndMode.Count, onClick = { endMode = RecurrenceEndMode.Count }, ) // Animated for the same reason the weekday card is: this is the @@ -1694,9 +1939,8 @@ private fun RecurrencePickerDialog( if (showUntilPicker) { CalendarDatePickerDialog( - initial = untilDate ?: LocalDate.fromEpochDays( - (Clock.System.now().toEpochMilliseconds() / MILLIS_PER_DAY).toInt(), - ), + initial = untilDate + ?: Clock.System.now().toLocalDateTime(TimeZone.currentSystemDefault()).date, onConfirm = { untilIso = it.toString() showUntilPicker = false @@ -1814,13 +2058,7 @@ private fun GroupedItemCard( titleMaxLines: Int = Int.MAX_VALUE, trailing: @Composable (() -> Unit)? = null, ) { - Surface( - color = MaterialTheme.colorScheme.surfaceContainerHigh, - shape = groupedShape(position), - modifier = Modifier - .fillMaxWidth() - .then(groupedGap(position)), - ) { + GroupedSurface(position = position) { Row( verticalAlignment = Alignment.CenterVertically, modifier = Modifier.padding(start = 16.dp, end = 8.dp, top = 8.dp, bottom = 8.dp), @@ -2091,7 +2329,7 @@ private fun ColorPickerDialog( onClear: () -> Unit, onDismiss: () -> Unit, ) { - val dark = isSystemInDarkTheme() + val dark = LocalFloretDarkTheme.current FullScreenPicker( title = stringResource(R.string.event_edit_color), onDismiss = onDismiss, @@ -2167,144 +2405,27 @@ private fun accessLevelSummary(level: AccessLevel): Int = when (level) { AccessLevel.Confidential -> R.string.event_access_confidential_summary } -/** Humanise a reminder lead time, mirroring the detail screen's rendering. */ -@Composable -private fun reminderLabel(minutes: Int): String = reminderLeadTimeLabel(minutes) - /** - * One info card mirroring the detail screen's DetailCard: tonal container, - * leading icon in the gutter, value to the right. Optionally clickable as a - * whole (calendar picker). + * "2:00 PM – 3:00 PM" in [zone], honouring the user's 12/24-hour setting. Collapses + * to one time for an instant event, which shouldn't read as a range against + * itself. Dates are deliberately absent — the rows above carry them. */ @Composable -private fun EditCard( - icon: ImageVector, - iconContentDescription: String?, - iconTint: Color = MaterialTheme.colorScheme.onSurfaceVariant, - onClick: (() -> Unit)? = null, - // Multiline-input cards align the icon with the field's first text line. - iconAtTop: Boolean = false, - // Tall cards pass their first row here: the icon centres on it, and - // [content] continues below, indented to the same text column. - header: (@Composable ColumnScope.() -> Unit)? = null, - content: @Composable ColumnScope.() -> Unit, -) { - val shape = RoundedCornerShape(16.dp) - val color = MaterialTheme.colorScheme.surfaceContainerHigh - val inner: @Composable () -> Unit = { - if (header != null) { - Column(modifier = Modifier.padding(16.dp)) { - Row(verticalAlignment = Alignment.CenterVertically) { - Icon( - imageVector = icon, - contentDescription = iconContentDescription, - tint = iconTint, - modifier = Modifier.size(24.dp), - ) - Spacer(Modifier.width(16.dp)) - Column(modifier = Modifier.weight(1f), content = header) - } - Column( - modifier = Modifier.padding(start = 40.dp), - content = content, - ) - } - } else { - Row( - modifier = Modifier.padding(16.dp), - verticalAlignment = if (iconAtTop) Alignment.Top else Alignment.CenterVertically, - ) { - // A top-aligned icon centres on the first text line, whatever - // that line measures at the user's font scale. - val iconOffset = if (iconAtTop) { - ((firstLineHeight() - 24.dp) / 2).coerceAtLeast(0.dp) - } else { - 0.dp - } - Icon( - imageVector = icon, - contentDescription = iconContentDescription, - tint = iconTint, - modifier = Modifier - .padding(top = iconOffset) - .size(24.dp), - ) - Spacer(Modifier.width(16.dp)) - Column(modifier = Modifier.weight(1f), content = content) - } - } - } - if (onClick != null) { - Surface( - onClick = onClick, - color = color, - shape = shape, - modifier = Modifier.fillMaxWidth(), - ) { inner() } - } else { - Surface( - color = color, - shape = shape, - modifier = Modifier.fillMaxWidth(), - ) { inner() } - } -} - -/** - * "2:00 PM – 3:00 PM", honouring the user's 12/24-hour setting. Collapses to one - * time when both land on the same minute (an instant event shouldn't read as a - * range against itself). Dates are deliberately absent — the rows above carry - * them. - */ -@Composable -private fun formatTimeRange(start: LocalDateTime, end: LocalDateTime, locale: Locale): String { +private fun formatTimeRange(start: Instant, end: Instant, zone: TimeZone, locale: Locale): String { val use24Hour = LocalUse24HourFormat.current - val timeFormat = remember(locale, use24Hour) { timeOfDayFormatter(use24Hour, locale) } - val from = timeFormat.format(start.time.toJavaLocalTime()) - val to = timeFormat.format(end.time.toJavaLocalTime()) - return if (from == to) from else "$from – $to" + return remember(start, end, zone, locale, use24Hour) { + fun format(at: Instant) = withRepeatedHourZone( + formatTimeOfDay(at, zone, use24Hour, locale), + at, + zone, + locale, + ) + if (start == end) format(start) else "${format(start)} – ${format(end)}" + } } /** - * Borderless text input used inside the cards (and as the headline title). - * Thin wrapper over the shared [InlineTextField] so the form and the rest of - * the app share one input style. Sentence-case by default, as floret-kit is; - * a field holding an identifier rather than prose passes - * [KeyboardCapitalization.None]. - */ -@Composable -private fun InlineField( - value: String, - onValueChange: (String) -> Unit, - placeholder: String, - textStyle: TextStyle = MaterialTheme.typography.titleMedium, - singleLine: Boolean = true, - minLines: Int = 1, - enabled: Boolean = true, - keyboardType: KeyboardType = KeyboardType.Text, - capitalization: KeyboardCapitalization = KeyboardCapitalization.Sentences, - imeAction: ImeAction = ImeAction.Default, - modifier: Modifier = Modifier - .fillMaxWidth() - .padding(vertical = 4.dp), -) { - InlineTextField( - value = value, - onValueChange = onValueChange, - placeholder = placeholder, - modifier = modifier, - textStyle = textStyle, - singleLine = singleLine, - minLines = minLines, - enabled = enabled, - keyboardType = keyboardType, - capitalization = capitalization, - imeAction = imeAction, - ) -} - -/** - * A right-aligned "n/max" counter for a capped [InlineField] (#331), hidden + * A right-aligned "n/max" counter for a capped [InlineTextField] (#331), hidden * until [length] gets close enough to [max] to matter — nobody needs to see * "12/255" while typing a short title. */ @@ -2326,7 +2447,7 @@ private fun FieldLengthCounter(length: Int, max: Int, modifier: Modifier = Modif } /** - * Height of one [InlineField] line: the resolved [TextStyle.lineHeight] plus the + * Height of one [InlineTextField] line: the resolved [TextStyle.lineHeight] plus the * field's 4dp vertical padding. In dp, so it tracks the user's font scale * instead of assuming the 24sp line of a 1.0 scale (#165). */ @@ -2344,6 +2465,8 @@ private fun firstLineHeight( private fun ScheduleRow( label: String, dateTime: LocalDateTime, + instant: Instant, + zone: TimeZone, isAllDay: Boolean, locale: Locale, onDateClick: () -> Unit, @@ -2385,8 +2508,11 @@ private fun ScheduleRow( .padding(vertical = 8.dp, horizontal = 6.dp), ) if (!isAllDay) { + val time = remember(dateTime, instant, zone, locale, timeFormat) { + withRepeatedHourZone(timeFormat.format(dateTime.time.toJavaLocalTime()), instant, zone, locale) + } Text( - text = timeFormat.format(dateTime.time.toJavaLocalTime()), + text = time, style = MaterialTheme.typography.titleMedium, color = valueColor, modifier = Modifier diff --git a/app/src/main/java/de/jeanlucmakiola/calendula/ui/edit/EventEditUiState.kt b/app/src/main/java/de/jeanlucmakiola/calendula/ui/edit/EventEditUiState.kt index 6a68d045..1be5d3b1 100644 --- a/app/src/main/java/de/jeanlucmakiola/calendula/ui/edit/EventEditUiState.kt +++ b/app/src/main/java/de/jeanlucmakiola/calendula/ui/edit/EventEditUiState.kt @@ -77,6 +77,11 @@ sealed interface SaveUiState { data object Gone : SaveUiState data object Saving : SaveUiState data object Saved : SaveUiState + /** The event was deleted from the form (#178). */ + data object Deleted : SaveUiState + data object DeleteFailed : SaveUiState + /** WRITE_CALENDAR was revoked before a delete from the form. */ + data object DeleteDenied : SaveUiState /** WRITE_CALENDAR was revoked between the tap and the provider call. */ data object NeedsPermission : SaveUiState data object Failed : SaveUiState 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 99894e80..8bfddabc 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 @@ -1,14 +1,16 @@ package de.jeanlucmakiola.calendula.ui.edit +import android.net.Uri import android.util.Log import androidx.lifecycle.ViewModel import androidx.lifecycle.viewModelScope import dagger.hilt.android.lifecycle.HiltViewModel import de.jeanlucmakiola.calendula.data.calendar.CalendarRepository import de.jeanlucmakiola.calendula.data.calendar.NoSuchEventException -import de.jeanlucmakiola.calendula.data.di.IoDispatcher +import de.jeanlucmakiola.calendula.data.ics.IcsExporter import de.jeanlucmakiola.calendula.data.prefs.CalendarPrefs import de.jeanlucmakiola.calendula.data.prefs.SettingsPrefs +import de.jeanlucmakiola.calendula.data.time.ZoneSource import de.jeanlucmakiola.calendula.data.prefs.firstDayOfWeek import de.jeanlucmakiola.calendula.data.prefs.resolveDefaultEventDuration import de.jeanlucmakiola.calendula.data.prefs.resolveDefaultReminder @@ -18,14 +20,29 @@ import de.jeanlucmakiola.calendula.domain.CalendarSource import de.jeanlucmakiola.calendula.domain.EditSnapshot 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.nextFullHour +import de.jeanlucmakiola.calendula.domain.toFormTime +import de.jeanlucmakiola.calendula.domain.resolvedZone +import de.jeanlucmakiola.calendula.domain.startInstant +import de.jeanlucmakiola.calendula.domain.withEnd +import de.jeanlucmakiola.calendula.domain.withStart +import de.jeanlucmakiola.calendula.domain.withTimes +import de.jeanlucmakiola.calendula.domain.withTimezone import de.jeanlucmakiola.calendula.domain.EventFormField import de.jeanlucmakiola.calendula.domain.RecurringWriteScope +import de.jeanlucmakiola.calendula.domain.atOccurrence import de.jeanlucmakiola.calendula.domain.isEventTarget import de.jeanlucmakiola.calendula.domain.populatedFields import de.jeanlucmakiola.calendula.domain.problems import de.jeanlucmakiola.calendula.domain.toEditSnapshot import de.jeanlucmakiola.calendula.ui.detail.EventDetailViewModel.Companion.NO_OCCURRENCE_TIME +import de.jeanlucmakiola.calendula.ui.common.DeleteOutcome +import de.jeanlucmakiola.calendula.ui.common.tryDeleteEvent +import de.jeanlucmakiola.calendula.ui.common.stageEventShare +import de.jeanlucmakiola.floret.android.stateWhileSubscribed +import de.jeanlucmakiola.floret.di.IoDispatcher import kotlinx.coroutines.CoroutineDispatcher import kotlinx.coroutines.ExperimentalCoroutinesApi import kotlinx.coroutines.flow.Flow @@ -132,9 +149,15 @@ class EventEditViewModel @Inject constructor( private val repository: CalendarRepository, private val prefs: CalendarPrefs, private val settingsPrefs: SettingsPrefs, + private val icsExporter: IcsExporter, @IoDispatcher private val io: CoroutineDispatcher, + private val zoneSource: ZoneSource, ) : ViewModel() { + /** The zone the form's unpinned times are read in, for the screen to show them in too. */ + val zone: StateFlow = zoneSource.zone + .stateIn(viewModelScope, SharingStarted.Eagerly, zoneSource.current()) + private val _form = MutableStateFlow(null) private val _saveState = MutableStateFlow(SaveUiState.Idle) // Problems stay hidden until the first save attempt, so a half-filled @@ -156,6 +179,11 @@ class EventEditViewModel @Inject constructor( // A one-time offer, raised when a .ics import opens, to replace the file's // reminders with the settings default (#49). Null while there's nothing to ask. private val _importReminderPrompt = MutableStateFlow(null) + // The form as the user received it: the loaded event, or a new form with its + // prefill and auto-applied defaults. Anything else is an unsaved change. + private val _baseline = MutableStateFlow(null) + // Bumped by reset(), so work started for a closed form never lands on the next. + private var session = 0 /** True when the event to edit couldn't be loaded; the screen closes itself. */ val loadFailed: StateFlow = _loadFailed.asStateFlow() @@ -176,6 +204,8 @@ class EventEditViewModel @Inject constructor( val beginMillis: Long, val endMillis: Long, val zone: TimeZone, + /** The event as loaded, on the tapped occurrence's times — what Share exports. */ + val detail: EventDetail, ) { val original: EventForm get() = snapshot.form } @@ -289,7 +319,11 @@ class EventEditViewModel @Inject constructor( EventEditUiState( form = resolved, calendars = pickerCalendars, - problems = if (local.showProblems) resolved.problems() else emptySet(), + problems = if (local.showProblems) { + resolved.problems(zoneSource.current()) + } else { + emptySet() + }, saveState = local.saveState, visibleFields = visibleFields, hiddenFields = (offerableFields - visibleFields).sorted(), @@ -305,12 +339,19 @@ class EventEditViewModel @Inject constructor( allowColorOnUnsupportedCalendars = external.allowColorOnUnsupported, ) } - .stateIn( + .stateWhileSubscribed( scope = viewModelScope, - started = SharingStarted.WhileSubscribed(5_000L), initialValue = null, ) + /** + * Whether leaving now would lose something the user did (#178): the form + * differs from how it opened, counting the defaults it applied itself. + */ + val hasUnsavedChanges: StateFlow = combine(_form, _baseline) { form, baseline -> + form != null && form != baseline + }.stateIn(viewModelScope, SharingStarted.Eagerly, false) + /** * First day of the week for ordering the recurrence weekday toggles — the * app's "week starts on" preference, matching the calendar views (Auto @@ -329,22 +370,32 @@ class EventEditViewModel @Inject constructor( */ fun openNew(date: LocalDate, startMinutes: Int? = null) { if (_form.value != null) return - val zone = TimeZone.currentSystemDefault() + val zone = zoneSource.current() val now = Clock.System.now() - val start = when { + val startAt = when { startMinutes != null -> - LocalDateTime(date, LocalTime(startMinutes / 60, startMinutes % 60)) - date == now.toLocalDateTime(zone).date -> { - // Today: the next full hour (may roll into tomorrow before midnight). - val hourMillis = 3_600_000L - val rounded = (now.toEpochMilliseconds() / hourMillis + 1) * hourMillis - Instant.fromEpochMilliseconds(rounded).toLocalDateTime(zone) - } - else -> LocalDateTime(date, LocalTime(9, 0)) + LocalDateTime(date, LocalTime(startMinutes / 60, startMinutes % 60)).toInstant(zone) + date == now.toLocalDateTime(zone).date -> nextFullHour(now) + else -> LocalDateTime(date, LocalTime(9, 0)).toInstant(zone) } - val end = (start.toInstant(zone) + SettingsPrefs.DEFAULT_EVENT_DURATION.minutes) - .toLocalDateTime(zone) - _form.value = EventForm(calendarId = null, start = start, end = end) + val endAt = startAt + SettingsPrefs.DEFAULT_EVENT_DURATION.minutes + open(EventForm(calendarId = null, start = startAt.toFormTime(zone), end = endAt.toFormTime(zone))) + applyDefaultReminder() + applyDefaultDuration() + } + + /** + * Initialise a fresh form for a block drafted on the timeline (#153), from + * [start] to [end]. These are the instants the block shows, so a time in the + * fall-back hour's repeat, or one moved out of the spring-forward gap, opens + * as drawn (#387). The user chose the length, so the default length doesn't + * apply. No-op when a form is already open, as [openNew]. + */ + fun openDraft(start: Instant, end: Instant) { + if (_form.value != null) return + val zone = zoneSource.current() + open(EventForm(calendarId = null, start = start.toFormTime(zone), end = end.toFormTime(zone))) + _durationTouched.value = true applyDefaultReminder() applyDefaultDuration() } @@ -377,7 +428,7 @@ class EventEditViewModel @Inject constructor( fun openImported(form: EventForm, source: ImportSource) { if (_form.value != null || _editTarget.value != null) return _revealed.value = form.populatedFields() - _form.value = form + open(form) if (source.ownsDuration) _durationTouched.value = true else applyDefaultDuration() when (source) { ImportSource.Insert, ImportSource.InsertOpenEnded -> @@ -402,16 +453,18 @@ class EventEditViewModel @Inject constructor( */ private fun applyDefaultReminder(calendarId: Long? = null) { if (_editTarget.value != null || _remindersTouched.value) return + val opened = session viewModelScope.launch { val defaults = reminderDefaults() val targetId = calendarId ?: resolvedCalendarId.first() // Re-check after suspending: bail if the form closed or the user edited. + if (opened != session) return@launch val form = _form.value ?: return@launch if (_editTarget.value != null || _remindersTouched.value) return@launch val reminders = defaults.resolveFor(targetId, form.isAllDay) - // Write through update(): the duration default resolves in parallel, - // so both must compose onto the current form, not a pre-suspend copy. - update { it.copy(reminders = reminders) } + // The duration default resolves in parallel, so both must compose + // onto the current form, not a pre-suspend copy. + applyDefault { it.copy(reminders = reminders) } // Surface the section so an auto-applied default is visible and // removable, even when Reminders isn't a default-shown field. if (reminders.isNotEmpty()) { @@ -440,6 +493,7 @@ class EventEditViewModel @Inject constructor( */ private fun applyDefaultDuration(calendarId: Long? = null) { if (_editTarget.value != null || _durationTouched.value) return + val opened = session viewModelScope.launch { val global = settingsPrefs.defaultEventDurationMinutes.first() val overrides = settingsPrefs.perCalendarEventDuration.first() @@ -451,14 +505,14 @@ class EventEditViewModel @Inject constructor( else -> calendarId ?: resolvedCalendarId.first() } // Re-check after suspending: bail if the form closed or the user edited. + if (opened != session) return@launch if (_editTarget.value != null || _durationTouched.value) return@launch if (_form.value?.isAllDay != false) return@launch val duration = resolveDefaultEventDuration(global, overrides, targetId) - val zone = TimeZone.currentSystemDefault() - update { form -> - form.copy( - end = (form.start.toInstant(zone) + duration.minutes).toLocalDateTime(zone), - ) + applyDefault { form -> + val zone = form.resolvedZone(zoneSource.current()) + val start = form.startInstant(zone) + form.withTimes(start, start + duration.minutes, zone) } } } @@ -471,10 +525,12 @@ class EventEditViewModel @Inject constructor( * configured and it isn't already exactly what the file carried. */ private fun maybePromptImportedReminderDefault(form: EventForm) { + val opened = session viewModelScope.launch { val targetId = resolvedCalendarId.first() val default = reminderDefaults().resolveFor(targetId, form.isAllDay) // Bail if the form closed or became an edit while we resolved. + if (opened != session) return@launch val current = _form.value ?: return@launch if (_editTarget.value != null) return@launch if (default.isEmpty() || default == current.reminders) return@launch @@ -490,7 +546,7 @@ class EventEditViewModel @Inject constructor( val prompt = _importReminderPrompt.value ?: return _importReminderPrompt.value = null // Already frozen as touched by openImported; this just swaps the values. - update { it.copy(reminders = prompt.defaultReminders) } + edit { it.copy(reminders = prompt.defaultReminders) } _revealed.value = _revealed.value + EventFormField.Reminders } @@ -510,31 +566,38 @@ class EventEditViewModel @Inject constructor( */ fun openForEdit(eventId: Long, beginMillis: Long, endMillis: Long) { if (_form.value != null || _editTarget.value != null) return + val opened = session viewModelScope.launch { val detail = try { repository.eventDetail(eventId) } catch (e: CancellationException) { throw e } catch (e: Exception) { - _loadFailed.value = true + if (opened == session) _loadFailed.value = true return@launch } - val zone = TimeZone.currentSystemDefault() + if (opened != session) return@launch + val zone = zoneSource.current() val begin = beginMillis.takeUnless { it == NO_OCCURRENCE_TIME } ?: detail.instance.start.toEpochMilliseconds() val end = endMillis.takeUnless { it == NO_OCCURRENCE_TIME } ?: detail.instance.end.toEpochMilliseconds() val snapshot = detail.toEditSnapshot(begin, end, zone) - _editTarget.value = EditTarget(eventId, snapshot, begin, end, zone) + _editTarget.value = EditTarget(eventId, snapshot, begin, end, zone, detail.atOccurrence(begin, end)) // Sections holding data must show even when not in the defaults. _revealed.value = snapshot.form.populatedFields() - _form.value = snapshot.form + open(snapshot.form) } } + /** The form as the user has it now, or null when none is open. */ + fun currentForm(): EventForm? = _form.value + /** Forget the open form; the next [openNew]/[openForEdit] starts clean. */ fun reset() { + session++ _form.value = null + _baseline.value = null _saveState.value = SaveUiState.Idle _showProblems.value = false _revealed.value = emptySet() @@ -553,24 +616,28 @@ class EventEditViewModel @Inject constructor( // The title field wraps (multi-line) so long titles stay visible (#33), but // a title is one logical line: drop any newline the IME's Enter key or a // paste would introduce, so it never reaches the provider's TITLE column. - fun setTitle(value: String) = update { + fun setTitle(value: String) = edit { val cleaned = value.replace("\n", "").replace("\r", "") it.copy(title = capLength(cleaned, it.title)) } // The location wraps too (#273) but is likewise one logical line. A pasted // multi-line address joins the way the contact picker's does (#146), so it // never runs together into "12 Main St10115 Berlin". - fun setLocation(value: String) = update { + fun setLocation(value: String) = edit { val cleaned = value.replace(LINE_BREAK, ", ") it.copy(location = capLength(cleaned, it.location)) } - fun setDescription(value: String) = update { it.copy(description = value) } + fun setDescription(value: String) = edit { it.copy(description = value) } fun setAllDay(value: Boolean) { // Going all-day drops any pinned zone: the times become bare dates that // the provider stores UTC-anchored, so a zone could only misrepresent // them. Coming back out of all-day leaves the event on the device zone, // which is the same thing a fresh event gets. - update { it.copy(isAllDay = value, timezone = if (value) null else it.timezone) } + // A kept pass of a repeated hour stays, so switching back out of all-day + // lands where the event was — unless dropping the pin changed the zone. + edit { + if (value) it.withTimezone(null, zoneSource.current()).copy(isAllDay = true) else it.copy(isAllDay = false) + } // The default reminder differs for all-day vs timed; re-apply the // type-appropriate default unless the user has hand-edited it (guarded). applyDefaultReminder() @@ -585,7 +652,7 @@ class EventEditViewModel @Inject constructor( * time — only real picks are remembered, not the device fallback. */ fun setTimezone(zoneId: String?) { - update { it.copy(timezone = zoneId) } + edit { it.withTimezone(zoneId, zoneSource.current()) } if (zoneId != null) { viewModelScope.launch { withContext(io) { settingsPrefs.addRecentTimeZone(zoneId) } } } @@ -597,35 +664,35 @@ class EventEditViewModel @Inject constructor( * The event falls back to the new calendar's colour until re-picked. */ fun setCalendar(id: Long) { - update { it.copy(calendarId = id, colorKey = null, color = null) } + edit { it.copy(calendarId = id, colorKey = null, color = null) } // A fresh event re-inherits the new calendar's default reminder and // length unless the user has already hand-edited them (guarded inside). applyDefaultReminder(id) applyDefaultDuration(id) } - fun setAvailability(value: Availability) = update { it.copy(availability = value) } - fun setAccessLevel(value: AccessLevel) = update { it.copy(accessLevel = value) } + fun setAvailability(value: Availability) = edit { it.copy(availability = value) } + fun setAccessLevel(value: AccessLevel) = edit { it.copy(accessLevel = value) } /** Pick a palette colour (round-trips via its key); [argb] is its swatch. */ - fun setColorKey(key: String, argb: Int) = update { it.copy(colorKey = key, color = argb) } + fun setColorKey(key: String, argb: Int) = edit { it.copy(colorKey = key, color = argb) } /** Pick a raw colour (local / opted-in calendars), clearing any palette key. */ - fun setColorRaw(argb: Int) = update { it.copy(colorKey = null, color = argb) } + fun setColorRaw(argb: Int) = edit { it.copy(colorKey = null, color = argb) } /** Clear the colour so the event inherits its calendar's. */ - fun clearColor() = update { it.copy(colorKey = null, color = null) } + fun clearColor() = edit { it.copy(colorKey = null, color = null) } /** Bare RRULE value from the recurrence picker; null = does not repeat. */ - fun setRecurrence(rrule: String?) = update { it.copy(rrule = rrule) } + fun setRecurrence(rrule: String?) = edit { it.copy(rrule = rrule) } fun addReminder(minutes: Int) { _remindersTouched.value = true - update { it.copy(reminders = (it.reminders + minutes).distinct().sorted()) } + edit { it.copy(reminders = (it.reminders + minutes).distinct().sorted()) } } fun removeReminder(minutes: Int) { _remindersTouched.value = true - update { it.copy(reminders = it.reminders - minutes) } + edit { it.copy(reminders = it.reminders - minutes) } } /** @@ -636,7 +703,7 @@ class EventEditViewModel @Inject constructor( fun addAttendee(email: String, name: String = "", optional: Boolean = false) { val trimmed = email.trim() if (trimmed.isEmpty()) return - update { form -> + edit { form -> val attendee = EventAttendee(email = trimmed, name = name.trim(), optional = optional) val rest = form.attendees.filterNot { it.email.equals(trimmed, ignoreCase = true) } form.copy(attendees = rest + attendee) @@ -644,10 +711,10 @@ class EventEditViewModel @Inject constructor( } fun removeAttendee(attendee: EventAttendee) = - update { it.copy(attendees = it.attendees.filterNot { a -> a.email.equals(attendee.email, ignoreCase = true) }) } + edit { it.copy(attendees = it.attendees.filterNot { a -> a.email.equals(attendee.email, ignoreCase = true) }) } /** Flip a guest between required and optional (the per-row role toggle). */ - fun setAttendeeOptional(attendee: EventAttendee, optional: Boolean) = update { form -> + fun setAttendeeOptional(attendee: EventAttendee, optional: Boolean) = edit { form -> form.copy( attendees = form.attendees.map { a -> if (a.email.equals(attendee.email, ignoreCase = true)) a.copy(optional = optional) else a @@ -663,12 +730,12 @@ class EventEditViewModel @Inject constructor( // default duration, so a later calendar switch keeps their span (#54). fun setEndDate(date: LocalDate) { _durationTouched.value = true - update { it.copy(end = LocalDateTime(date, it.end.time)) } + moveEnd { LocalDateTime(date, it.time) } } fun setEndTime(time: LocalTime) { _durationTouched.value = true - update { it.copy(end = LocalDateTime(it.end.date, time)) } + moveEnd { LocalDateTime(it.date, time) } } /** @@ -681,7 +748,7 @@ class EventEditViewModel @Inject constructor( val current = state.value ?: return if (current.saveState == SaveUiState.Saving) return val form = current.form - if (form.problems().isNotEmpty()) { + if (form.problems(zoneSource.current()).isNotEmpty()) { _showProblems.value = true return } @@ -726,8 +793,13 @@ class EventEditViewModel @Inject constructor( ignoreConflict: Boolean = false, ) { val target = _editTarget.value + val opened = session + // A form closed mid-save drops the result rather than handing it to the next one. + fun settle(result: SaveUiState) { + if (opened == session) _saveState.value = result + } viewModelScope.launch { - _saveState.value = SaveUiState.Saving + settle(SaveUiState.Saving) // No locking (plan 03, decision 5): right before writing, re-read // the event and compare against what the form loaded. An external // change parks the save in a conflict dialog instead of silently @@ -739,18 +811,18 @@ class EventEditViewModel @Inject constructor( } catch (e: CancellationException) { throw e } catch (e: NoSuchEventException) { - _saveState.value = SaveUiState.Gone + settle(SaveUiState.Gone) return@launch } catch (e: Exception) { // Can't verify — proceed; a real problem fails the write itself. null } if (fresh != null && fresh != target.snapshot) { - _saveState.value = SaveUiState.AwaitingConflict(scope) + settle(SaveUiState.AwaitingConflict(scope)) return@launch } } - _saveState.value = try { + val result = try { if (target == null) { repository.createEvent(form) prefs.setLastUsedCalendarId(requireNotNull(form.calendarId)) @@ -801,6 +873,37 @@ class EventEditViewModel @Inject constructor( Log.w(TAG, "Save failed (scope=$scope, eventId=${target?.eventId})", e) SaveUiState.Failed } + settle(result) + } + } + + /** Whether the event being edited recurs; null while not editing. */ + fun editedEventRecurs(): Boolean? = _editTarget.value?.let { !it.detail.rrule.isNullOrBlank() } + + /** The form as it stands, as a fresh one-off event — Duplicate in the edit form (#178). */ + fun duplicateForm(): EventForm? = state.value?.form?.copy(rrule = null) + + /** A staged `.ics` of the event as saved, or null when it can't be built. */ + suspend fun shareUri(): Uri? { + val detail = _editTarget.value?.detail ?: return null + return withContext(io) { icsExporter.stageEventShare(detail) } + } + + /** Delete the event being edited, as far as [scope] reaches; result lands in [saveState]. */ + fun delete(scope: RecurringWriteScope) { + val target = _editTarget.value ?: return + if (_saveState.value == SaveUiState.Saving) return + val opened = session + _saveState.value = SaveUiState.Saving + viewModelScope.launch { + val outcome = repository.tryDeleteEvent(target.eventId, target.beginMillis, scope) + if (opened != session) return@launch + _saveState.value = when (outcome) { + // Already gone is what a delete wants anyway. + DeleteOutcome.Deleted, DeleteOutcome.Gone -> SaveUiState.Deleted + DeleteOutcome.NeedsPermission -> SaveUiState.DeleteDenied + DeleteOutcome.Failed -> SaveUiState.DeleteFailed + } } } @@ -809,15 +912,34 @@ class EventEditViewModel @Inject constructor( _saveState.value = SaveUiState.Idle } - private fun moveStart(transform: (LocalDateTime) -> LocalDateTime) = update { form -> - val zone = TimeZone.currentSystemDefault() - val newStart = transform(form.start) - val duration = form.end.toInstant(zone) - form.start.toInstant(zone) - val newEnd = (newStart.toInstant(zone) + duration).toLocalDateTime(zone) - form.copy(start = newStart, end = newEnd) + private fun moveStart(transform: (LocalDateTime) -> LocalDateTime) = edit { form -> + form.withStart(transform(form.start.dateTime), form.resolvedZone(zoneSource.current()), opened(form)?.start) } - private inline fun update(block: (EventForm) -> EventForm) { + private fun moveEnd(transform: (LocalDateTime) -> LocalDateTime) = edit { form -> + form.withEnd(transform(form.end.dateTime), form.resolvedZone(zoneSource.current()), opened(form)?.end) + } + + /** + * The event as it was opened, while its times still mean the same instants: + * picking one of them again keeps its pass of a repeated hour (#387). + */ + private fun opened(form: EventForm): EventForm? = + _editTarget.value?.original?.takeIf { it.timezone == form.timezone && !it.isAllDay } + + private fun open(form: EventForm) { + _form.value = form + _baseline.value = form + } + + /** A default the form applied itself; it moves the baseline too, so it's no unsaved change. */ + private inline fun applyDefault(block: (EventForm) -> EventForm) { + _form.value = _form.value?.let(block) + _baseline.value = _baseline.value?.let(block) + } + + /** A change the user made. */ + private inline fun edit(block: (EventForm) -> EventForm) { _form.value = _form.value?.let(block) } } diff --git a/app/src/main/java/de/jeanlucmakiola/calendula/ui/filter/CalendarFilterList.kt b/app/src/main/java/de/jeanlucmakiola/calendula/ui/filter/CalendarFilterList.kt index 9b37431a..68191a85 100644 --- a/app/src/main/java/de/jeanlucmakiola/calendula/ui/filter/CalendarFilterList.kt +++ b/app/src/main/java/de/jeanlucmakiola/calendula/ui/filter/CalendarFilterList.kt @@ -20,8 +20,10 @@ import androidx.hilt.navigation.compose.hiltViewModel import androidx.lifecycle.compose.collectAsStateWithLifecycle import de.jeanlucmakiola.calendula.R import de.jeanlucmakiola.calendula.domain.FailureReason +import de.jeanlucmakiola.calendula.ui.common.CalendarAccountGroup import de.jeanlucmakiola.calendula.ui.common.CalendarColorChip -import de.jeanlucmakiola.calendula.ui.common.sourceAppName +import de.jeanlucmakiola.calendula.ui.common.accountGroupTitle +import de.jeanlucmakiola.calendula.ui.common.orUnnamed import de.jeanlucmakiola.floret.components.GroupedListInset import de.jeanlucmakiola.floret.components.GroupedRow import de.jeanlucmakiola.floret.components.positionOf @@ -43,6 +45,7 @@ fun CalendarFilterList( is FilterUiState.Failure -> FilterMessage(s.reason, modifier) is FilterUiState.Success -> FilterList( groups = s.groups, + hidden = s.hidden, onSetVisible = viewModel::setVisible, modifier = modifier, ) @@ -56,23 +59,15 @@ fun CalendarFilterList( */ @Composable private fun FilterList( - groups: List, + groups: List, + hidden: Set, onSetVisible: (Long, Boolean) -> Unit, modifier: Modifier = Modifier, ) { Column(modifier = modifier.fillMaxWidth()) { groups.forEach { group -> - val account = group.account.ifBlank { stringResource(R.string.calendar_unnamed) } Text( - text = if (group.ambiguous) { - stringResource( - R.string.calendars_account_from_source, - account, - sourceAppName(group.accountType), - ) - } else { - account - }, + text = accountGroupTitle(group), style = MaterialTheme.typography.labelMedium, color = MaterialTheme.colorScheme.onSurfaceVariant, modifier = Modifier.padding( @@ -83,18 +78,19 @@ private fun FilterList( ), ) group.calendars.forEachIndexed { index, cal -> + val visible = cal.id !in hidden GroupedRow( - title = cal.displayName.ifBlank { stringResource(R.string.calendar_unnamed) }, + title = cal.displayName.orUnnamed(), position = positionOf(index, group.calendars.size), minHeight = 56.dp, leading = { CalendarColorChip(cal.color) }, trailing = { Checkbox( - checked = cal.visible, + checked = visible, onCheckedChange = { onSetVisible(cal.id, it) }, ) }, - onClick = { onSetVisible(cal.id, !cal.visible) }, + onClick = { onSetVisible(cal.id, !visible) }, ) } } diff --git a/app/src/main/java/de/jeanlucmakiola/calendula/ui/filter/FilterUiState.kt b/app/src/main/java/de/jeanlucmakiola/calendula/ui/filter/FilterUiState.kt index ac693f52..765d9edf 100644 --- a/app/src/main/java/de/jeanlucmakiola/calendula/ui/filter/FilterUiState.kt +++ b/app/src/main/java/de/jeanlucmakiola/calendula/ui/filter/FilterUiState.kt @@ -1,6 +1,7 @@ package de.jeanlucmakiola.calendula.ui.filter import de.jeanlucmakiola.calendula.domain.FailureReason +import de.jeanlucmakiola.calendula.ui.common.CalendarAccountGroup /** * State for the calendar-filter sheet (M3). The user toggles per-calendar @@ -10,26 +11,9 @@ import de.jeanlucmakiola.calendula.domain.FailureReason sealed interface FilterUiState { data object Loading : FilterUiState data class Failure(val reason: FailureReason) : FilterUiState - data class Success(val groups: List) : FilterUiState + /** A calendar shows when its id is *not* in [hidden]. */ + data class Success( + val groups: List, + val hidden: Set, + ) : FilterUiState } - -/** - * Calendars grouped under the account that owns them (Nextcloud / Local / …). - * - * [accountType] and [ambiguous] carry what the header needs to tell two - * same-named accounts from different apps apart (#77); the label itself is - * built in the UI layer, which is where the source app's name can be looked up. - */ -data class AccountGroup( - val account: String, - val accountType: String, - val ambiguous: Boolean, - val calendars: List, -) - -data class CalendarRow( - val id: Long, - val displayName: String, - val color: Int, - val visible: Boolean, -) diff --git a/app/src/main/java/de/jeanlucmakiola/calendula/ui/filter/FilterViewModel.kt b/app/src/main/java/de/jeanlucmakiola/calendula/ui/filter/FilterViewModel.kt index 218c3649..fda4c1fb 100644 --- a/app/src/main/java/de/jeanlucmakiola/calendula/ui/filter/FilterViewModel.kt +++ b/app/src/main/java/de/jeanlucmakiola/calendula/ui/filter/FilterViewModel.kt @@ -4,20 +4,18 @@ import androidx.lifecycle.ViewModel import androidx.lifecycle.viewModelScope import dagger.hilt.android.lifecycle.HiltViewModel import de.jeanlucmakiola.calendula.data.calendar.CalendarRepository -import de.jeanlucmakiola.calendula.data.di.IoDispatcher import de.jeanlucmakiola.calendula.data.prefs.CalendarPrefs -import de.jeanlucmakiola.calendula.domain.CalendarSource import de.jeanlucmakiola.calendula.domain.FailureReason import de.jeanlucmakiola.calendula.domain.calendarListFailure import de.jeanlucmakiola.calendula.ui.common.groupByAccount +import de.jeanlucmakiola.floret.android.stateWhileSubscribed +import de.jeanlucmakiola.floret.di.IoDispatcher import kotlinx.coroutines.CoroutineDispatcher -import kotlinx.coroutines.flow.SharingStarted import kotlinx.coroutines.flow.StateFlow import kotlinx.coroutines.flow.catch import kotlinx.coroutines.flow.combine import kotlinx.coroutines.flow.first import kotlinx.coroutines.flow.flowOn -import kotlinx.coroutines.flow.stateIn import kotlinx.coroutines.launch import javax.inject.Inject @@ -40,14 +38,13 @@ class FilterViewModel @Inject constructor( if (failure != null) { FilterUiState.Failure(failure) } else { - FilterUiState.Success(groupCalendarsForFilter(enabled, hidden)) + FilterUiState.Success(enabled.groupByAccount(), hidden) } } .catch { emit(FilterUiState.Failure(FailureReason.ProviderUnavailable)) } .flowOn(io) - .stateIn( + .stateWhileSubscribed( scope = viewModelScope, - started = SharingStarted.WhileSubscribed(5_000L), initialValue = FilterUiState.Loading, ) @@ -61,28 +58,3 @@ class FilterViewModel @Inject constructor( } } -/** - * Group calendars under their owning account — by name *and* type, so two - * accounts that merely share a name stay apart (#77) — preserving the - * provider's order within each group and ordering groups by first appearance. - * A calendar is "visible" when its id is *not* in [hidden]. - */ -internal fun groupCalendarsForFilter( - calendars: List, - hidden: Set, -): List = - calendars.groupByAccount().map { group -> - AccountGroup( - account = group.label, - accountType = group.accountType, - ambiguous = group.ambiguous, - calendars = group.calendars.map { c -> - CalendarRow( - id = c.id, - displayName = c.displayName, - color = c.color, - visible = c.id !in hidden, - ) - }, - ) - } diff --git a/app/src/main/java/de/jeanlucmakiola/calendula/ui/imports/ImportScreen.kt b/app/src/main/java/de/jeanlucmakiola/calendula/ui/imports/ImportScreen.kt index 82054656..9fd95c6c 100644 --- a/app/src/main/java/de/jeanlucmakiola/calendula/ui/imports/ImportScreen.kt +++ b/app/src/main/java/de/jeanlucmakiola/calendula/ui/imports/ImportScreen.kt @@ -90,8 +90,10 @@ fun ImportScreen( val state by viewModel.state.collectAsStateWithLifecycle() // A single event isn't shown here — it opens the create form for review. + // Read live: the state composed with may be the previous import's result, + // which the load above has already replaced. LaunchedEffect(state) { - (state as? ImportUiState.Single)?.let { onOpenSingle(it.form); onClose() } + (viewModel.state.value as? ImportUiState.Single)?.let { onOpenSingle(it.form); onClose() } } // Hoisted target calendar so the always-visible top-bar Import action can diff --git a/app/src/main/java/de/jeanlucmakiola/calendula/ui/imports/ImportViewModel.kt b/app/src/main/java/de/jeanlucmakiola/calendula/ui/imports/ImportViewModel.kt index 8dceb1f8..7dba1bfc 100644 --- a/app/src/main/java/de/jeanlucmakiola/calendula/ui/imports/ImportViewModel.kt +++ b/app/src/main/java/de/jeanlucmakiola/calendula/ui/imports/ImportViewModel.kt @@ -5,7 +5,6 @@ import androidx.lifecycle.ViewModel import androidx.lifecycle.viewModelScope import dagger.hilt.android.lifecycle.HiltViewModel import de.jeanlucmakiola.calendula.data.calendar.CalendarRepository -import de.jeanlucmakiola.calendula.data.di.IoDispatcher import de.jeanlucmakiola.calendula.data.ics.IcsImporter import de.jeanlucmakiola.calendula.domain.CalendarSource import de.jeanlucmakiola.calendula.domain.EventForm @@ -15,6 +14,7 @@ import de.jeanlucmakiola.calendula.domain.ics.IcsParser import de.jeanlucmakiola.calendula.domain.ics.ParsedIcsEvent import de.jeanlucmakiola.calendula.domain.ics.toEventForm import de.jeanlucmakiola.calendula.domain.isEventTarget +import de.jeanlucmakiola.floret.di.IoDispatcher import kotlinx.coroutines.CoroutineDispatcher import kotlinx.coroutines.Job import kotlinx.coroutines.flow.MutableStateFlow diff --git a/app/src/main/java/de/jeanlucmakiola/calendula/ui/month/MonthChipTime.kt b/app/src/main/java/de/jeanlucmakiola/calendula/ui/month/MonthChipTime.kt index 78d05ddf..8154c258 100644 --- a/app/src/main/java/de/jeanlucmakiola/calendula/ui/month/MonthChipTime.kt +++ b/app/src/main/java/de/jeanlucmakiola/calendula/ui/month/MonthChipTime.kt @@ -7,7 +7,6 @@ import de.jeanlucmakiola.calendula.domain.EventInstance import de.jeanlucmakiola.calendula.ui.common.formatTimeOfDay import de.jeanlucmakiola.calendula.ui.common.rememberInlineTimeWidth import kotlinx.datetime.TimeZone -import kotlinx.datetime.toLocalDateTime import java.util.Locale /** @@ -23,8 +22,7 @@ internal fun monthChipTime( locale: Locale, ): String? { if (event.isAllDay || continuesLeft) return null - val start = event.start.toLocalDateTime(zone).time - return formatTimeOfDay(start.hour, start.minute, is24Hour, locale) + return formatTimeOfDay(event.start, zone, is24Hour, locale) } /** The narrowest chip that may show a time — the text it needs, plus its chrome. */ diff --git a/app/src/main/java/de/jeanlucmakiola/calendula/ui/month/MonthDrag.kt b/app/src/main/java/de/jeanlucmakiola/calendula/ui/month/MonthDrag.kt index 746dad4b..9e7df88e 100644 --- a/app/src/main/java/de/jeanlucmakiola/calendula/ui/month/MonthDrag.kt +++ b/app/src/main/java/de/jeanlucmakiola/calendula/ui/month/MonthDrag.kt @@ -4,6 +4,7 @@ import androidx.compose.runtime.Composable import androidx.compose.runtime.Stable import androidx.compose.runtime.compositionLocalOf import androidx.compose.runtime.getValue +import androidx.compose.runtime.mutableIntStateOf import androidx.compose.runtime.mutableStateOf import androidx.compose.runtime.remember import androidx.compose.runtime.setValue @@ -133,6 +134,10 @@ class MonthDragController { var settling: MonthChipDrag? by mutableStateOf(null) private set + /** How many real drops this controller has handed back. */ + var drops by mutableIntStateOf(0) + private set + /** * Which chip is lifted, and whether anything is. Separate snapshot state from * [drag], which changes every frame, so the chips and rows that only need @@ -291,6 +296,7 @@ class MonthDragController { settledGhost = true undoable = settling settledAbandonedMark = abandonedTicks?.value ?: 0 + drops++ return MonthChipDrop(landed.event, landed.grabDate, target) } diff --git a/app/src/main/java/de/jeanlucmakiola/calendula/ui/month/MonthScreen.kt b/app/src/main/java/de/jeanlucmakiola/calendula/ui/month/MonthScreen.kt index d4ed1cb3..72eff382 100644 --- a/app/src/main/java/de/jeanlucmakiola/calendula/ui/month/MonthScreen.kt +++ b/app/src/main/java/de/jeanlucmakiola/calendula/ui/month/MonthScreen.kt @@ -11,6 +11,8 @@ import androidx.compose.foundation.pager.PagerState import androidx.compose.foundation.pager.rememberPagerState import androidx.compose.runtime.setValue import androidx.compose.runtime.rememberUpdatedState +import de.jeanlucmakiola.calendula.ui.agenda.AgendaDay +import de.jeanlucmakiola.calendula.ui.agenda.agendaDays import de.jeanlucmakiola.calendula.ui.common.PublishChrome import de.jeanlucmakiola.calendula.ui.common.ScreenActions import de.jeanlucmakiola.calendula.ui.common.ScreenBody @@ -21,9 +23,9 @@ import de.jeanlucmakiola.calendula.ui.common.LocalViewFocus import de.jeanlucmakiola.calendula.ui.common.ViewMorphKey import de.jeanlucmakiola.calendula.ui.common.morphDay import de.jeanlucmakiola.calendula.ui.common.morphEvent -import de.jeanlucmakiola.calendula.ui.common.morphPageActive import de.jeanlucmakiola.calendula.ui.common.jumpToPage import de.jeanlucmakiola.calendula.ui.common.rememberCalendarPageSpec +import de.jeanlucmakiola.floret.identity.LocalFloretDarkTheme import kotlinx.coroutines.flow.StateFlow import kotlinx.coroutines.flow.drop import androidx.compose.animation.ExperimentalSharedTransitionApi @@ -46,7 +48,6 @@ import androidx.compose.foundation.background import androidx.compose.foundation.clickable import androidx.compose.foundation.gestures.awaitEachGesture import androidx.compose.foundation.gestures.awaitFirstDown -import androidx.compose.foundation.isSystemInDarkTheme import androidx.compose.foundation.layout.Arrangement import androidx.compose.foundation.layout.Box import androidx.compose.foundation.layout.BoxWithConstraints @@ -67,7 +68,6 @@ import androidx.compose.foundation.lazy.LazyListState import androidx.compose.foundation.lazy.itemsIndexed import androidx.compose.foundation.lazy.items import androidx.compose.foundation.lazy.rememberLazyListState -import androidx.compose.foundation.ExperimentalFoundationApi import androidx.compose.foundation.selection.selectable import androidx.compose.foundation.shape.CircleShape import androidx.compose.foundation.shape.RoundedCornerShape @@ -75,13 +75,10 @@ import androidx.compose.material3.ExperimentalMaterial3Api import androidx.compose.material3.HorizontalDivider import androidx.compose.material.icons.Icons import androidx.compose.material.icons.filled.Close -import androidx.compose.material.icons.filled.Menu -import androidx.compose.material.icons.filled.Search -import androidx.compose.material3.DrawerValue import androidx.compose.material3.Icon -import androidx.compose.material3.IconButton import androidx.compose.material3.InputChip import androidx.compose.material3.MaterialTheme +import androidx.compose.material3.ripple import androidx.compose.material3.Text import androidx.compose.runtime.Composable import androidx.compose.runtime.LaunchedEffect @@ -167,10 +164,9 @@ import de.jeanlucmakiola.calendula.ui.agenda.agendaDayLabel import de.jeanlucmakiola.calendula.ui.common.formatCalendarTitle import de.jeanlucmakiola.calendula.ui.common.AppBarSpacing import de.jeanlucmakiola.calendula.ui.common.CalendarFailure -import de.jeanlucmakiola.calendula.ui.common.CalendarView -import de.jeanlucmakiola.calendula.ui.common.IMPLEMENTED_VIEWS import de.jeanlucmakiola.calendula.ui.common.EventDimAlpha import de.jeanlucmakiola.calendula.ui.common.LocalDimCutoff +import de.jeanlucmakiola.calendula.ui.common.isPastOn import de.jeanlucmakiola.calendula.ui.common.LocalSoftenColors import de.jeanlucmakiola.calendula.ui.common.LocalUse24HourFormat import de.jeanlucmakiola.calendula.ui.common.inlineTimeLabel @@ -197,10 +193,13 @@ import kotlinx.datetime.LocalDate import kotlinx.datetime.TimeZone import kotlinx.datetime.plus import kotlinx.datetime.YearMonth +import kotlinx.datetime.toJavaDayOfWeek import kotlinx.datetime.toJavaLocalDate import kotlin.time.Instant import java.time.format.TextStyle as JavaTextStyle import java.util.Locale +import kotlinx.datetime.toJavaMonth +import kotlinx.datetime.yearMonth private val LocalTodayPulse = staticCompositionLocalOf { 0 } @@ -349,7 +348,7 @@ fun MonthScreen( if (dense) { val midweek = weekStartForIndex(listState.firstVisibleItemIndex + 1, weekStart) .plus(3, DateTimeUnit.DAY) - YearMonth(midweek.year, midweek.month) + midweek.yearMonth } else { yearMonthForIndex(monthIndexForItem(listState.firstVisibleItemIndex)) } @@ -398,7 +397,7 @@ fun MonthScreen( } } - val isOnCurrentMonth = titleMonth == YearMonth(today.year, today.month) + val isOnCurrentMonth = titleMonth == today.yearMonth var splitExpanded by rememberSaveable(viewStyle) { mutableStateOf(viewStyle == MonthViewStyle.Paged) } @@ -427,7 +426,7 @@ fun MonthScreen( val jumpToToday: () -> Unit = { todayPulse++ if (scrolling) { - val targetMonth = YearMonth(today.year, today.month) + val targetMonth = today.yearMonth pendingScrollMonth = targetMonth val requestId = ++scrollRequestId viewModel.goToToday() @@ -445,13 +444,13 @@ fun MonthScreen( } } else { viewModel.goToToday() - jumpToMonth(YearMonth(today.year, today.month)) + jumpToMonth(today.yearMonth) } } // Drawer jump-to-date. val jumpToDate: (LocalDate) -> Unit = { target -> if (scrolling) { - val targetMonth = YearMonth(target.year, target.month) + val targetMonth = target.yearMonth pendingScrollMonth = targetMonth val requestId = ++scrollRequestId viewModel.goToDate(target) @@ -469,7 +468,7 @@ fun MonthScreen( } } else { viewModel.goToDate(target) - jumpToMonth(YearMonth(target.year, target.month)) + jumpToMonth(target.yearMonth) } } @@ -533,7 +532,7 @@ fun MonthScreen( onOpenDay = onOpenDay, onEventClick = onEventClick, ) - } else if (viewStyle == MonthViewStyle.Split || viewStyle == MonthViewStyle.Paged) { + } else { SplitMonthContent( state = state, selected = selectedDate, @@ -553,23 +552,12 @@ fun MonthScreen( // still settling would land and take the tap back. onSelectDay = { date -> viewModel.selectDate(date) - jumpToMonth(YearMonth(date.year, date.month)) + jumpToMonth(date.yearMonth) }, onOpenDay = onOpenDay, onEventClick = onEventClick, onCreateEvent = { onCreateEvent(it, null) }, ) - } else { - MonthContent( - state = state, - pagerState = pagerState, - weekStart = weekStart, - monthState = viewModel::month, - showWeekNumbers = showWeekNumbers, - onRetry = jumpToToday, - onOpenDay = onOpenDay, - onEventClick = onEventClick, - ) } } } @@ -588,14 +576,14 @@ private const val MONTH_SETTLE_TIMEOUT_MILLIS = 450L @Composable private fun MonthDragOverlay(controller: MonthDragController) { var origin by remember { mutableStateOf(Offset.Zero) } - val dark = isSystemInDarkTheme() + val dark = LocalFloretDarkTheme.current val density = LocalDensity.current val timeChipWidth = rememberMonthTimeChipWidth() val reduceMotion = rememberReduceMotion() val moveInFlight = moveInFlight() // Here rather than beside the controller: this reads [drag], which changes // every frame, and this composable is the one that is meant to. - DragSnapHaptics(controller.drag?.targetDate) + DragSnapHaptics(controller.drag?.targetDate, controller.drops) // Hold the landed chip until the write is done — including the time a // recurring drop's scope dialog is up — and then, unlike the timeline, carry // it to its seat: it was dropped at whatever height the finger was at, while @@ -678,118 +666,6 @@ private fun MonthDragOverlay(controller: MonthDragController) { } } -@Composable -private fun MonthContent( - state: MonthUiState, - pagerState: PagerState, - weekStart: DayOfWeek, - monthState: (YearMonth, DayOfWeek) -> StateFlow, - showWeekNumbers: Boolean, - onRetry: () -> Unit, - onOpenDay: (LocalDate) -> Unit, - onEventClick: (EventInstance) -> Unit, -) { - val fadeSpec = rememberCalendarFadeSpec() - // Loading and failure concern the provider as a whole, so they stand in for - // the pager; a page still loading its own month handles that itself. - AnimatedContent( - targetState = state, - modifier = Modifier.fillMaxSize(), - contentKey = { it::class }, - transitionSpec = { fadeIn(fadeSpec) togetherWith fadeOut(fadeSpec) }, - label = "month-state", - ) { s -> - when (s) { - MonthUiState.Loading -> MonthGridLoading() - is MonthUiState.Failure -> CalendarFailure(reason = s.reason, onRetry = onRetry) - is MonthUiState.Success -> MonthPager( - pagerState = pagerState, - weekStart = weekStart, - monthState = monthState, - modifier = Modifier.fillMaxSize(), - ) { _, page -> - MonthGrid( - state = page, - showWeekNumbers = showWeekNumbers, - onOpenDay = onOpenDay, - onEventClick = onEventClick, - ) - } - } - } -} - -/** - * The paged and split styles' months as pages that follow the finger and snap - * once a swipe passes half a page or is flung (#336). Only the page on screen - * carries the chip drag and the morph tags: its neighbours show some of its - * dates among their leading and trailing days, and would otherwise claim its - * drops and its shared elements. - */ -@Composable -private fun MonthPager( - pagerState: PagerState, - weekStart: DayOfWeek, - monthState: (YearMonth, DayOfWeek) -> StateFlow, - modifier: Modifier = Modifier, - loading: @Composable () -> Unit = { MonthGridLoading() }, - page: @Composable (index: Int, state: MonthUiState.Success) -> Unit, -) { - val chipDrag = LocalMonthDrag.current - HorizontalPager( - state = pagerState, - modifier = modifier, - // The months either side are composed ahead, so a swipe lands on a loaded - // month rather than watching it fill in. - beyondViewportPageCount = 1, - verticalAlignment = Alignment.Top, - // A held chip moves within its month; the page stays put under it. - userScrollEnabled = chipDrag?.isDragging != true, - flingBehavior = PagerDefaults.flingBehavior( - state = pagerState, - snapAnimationSpec = rememberCalendarPageSpec(), - ), - ) { index -> - MonthPage( - index = index, - active = index == pagerState.currentPage, - morphActive = morphPageActive(index, pagerState.settledPage), - weekStart = weekStart, - monthState = monthState, - loading = loading, - page = page, - ) - } -} - -@Composable -private fun MonthPage( - index: Int, - active: Boolean, - morphActive: Boolean, - weekStart: DayOfWeek, - monthState: (YearMonth, DayOfWeek) -> StateFlow, - loading: @Composable () -> Unit, - page: @Composable (index: Int, state: MonthUiState.Success) -> Unit, -) { - val ym = yearMonthForIndex(index) - val state by remember(ym, weekStart) { monthState(ym, weekStart) }.collectAsStateWithLifecycle() - val today = LocalMonthToday.current - val chipDrag = LocalMonthDrag.current - val morph = LocalMonthMorph.current - val viewMorph = LocalViewMorph.current - CompositionLocalProvider( - LocalMonthDrag provides chipDrag.takeIf { active }, - LocalMonthMorph provides morph.takeIf { active }, - LocalViewMorph provides viewMorph.takeIf { morphActive }, - ) { - when (val s = state) { - is MonthUiState.Success -> page(index, s.withToday(today)) - else -> loading() - } - } -} - /** * Content for both scrolling styles. No swipe detector and no [AnimatedContent]: * vertical scrolling owns the gesture, and the list never swaps wholesale — it @@ -849,7 +725,7 @@ internal fun WeekdayHeader(weekStart: DayOfWeek, showWeekNumbers: Boolean) { if (showWeekNumbers) Spacer(Modifier.width(rememberWeekNumberGutter())) days.forEach { dow -> val isWeekend = dow == DayOfWeek.SATURDAY || dow == DayOfWeek.SUNDAY - val javaDow = java.time.DayOfWeek.of(dow.ordinal + 1) + val javaDow = dow.toJavaDayOfWeek() Text( text = javaDow.getDisplayName(JavaTextStyle.SHORT, locale), style = MaterialTheme.typography.labelMedium, @@ -966,7 +842,7 @@ internal fun monthBandHeight(rowHeight: Dp): Dp = /** Whether any day in this week holds more than [lanes] lanes can seat. */ private fun MonthWeek.overflowsAt(lanes: Int): Boolean = - days.withIndex().any { (col, day) -> overflowEvents(col, day, lanes).isNotEmpty() } + days.indices.any { col -> overflowEvents(col, lanes).isNotEmpty() } /** * Row height in the continuous grid. The paged grid divides the viewport between @@ -1068,7 +944,7 @@ internal fun ContinuousMonthGrid( modifier: Modifier = Modifier, ) { val monthCount = remember { continuousMonthCount() } - val todayMonth = remember(state.today) { YearMonth(state.today.year, state.today.month) } + val todayMonth = remember(state.today) { state.today.yearMonth } val timeChipWidth = rememberMonthTimeChipWidth() LazyColumn( state = listState, @@ -1462,8 +1338,14 @@ private fun SplitMonthContent( showWeekNumbers = showWeekNumbers, expandDrag = expandDrag, onSelectDay = onSelectDay, - onPaneSwipeNext = onPaneSwipeNext, - onPaneSwipePrev = onPaneSwipePrev, + onPaneSwipeNext = { + onPaneSwipeNext() + haptics.performHapticFeedback(HapticFeedbackType.SegmentTick) + }, + onPaneSwipePrev = { + onPaneSwipePrev() + haptics.performHapticFeedback(HapticFeedbackType.SegmentTick) + }, onClearSelection = onClearSelection, onOpenDay = onOpenDay, onEventClick = onEventClick, @@ -1648,18 +1530,30 @@ private fun SplitExpandHandle( modifier = modifier .fillMaxWidth() .height(SPLIT_HANDLE_ROW_HEIGHT) - .clickable(onClick = onToggle) .semantics { contentDescription = label }, contentAlignment = Alignment.Center, ) { Box( Modifier - .size(width = SPLIT_HANDLE_WIDTH, height = SPLIT_HANDLE_HEIGHT) - // Tagged too, so it slides from the pane's seam down to the foot - // of the grid rather than blinking out at one and in at the other. - .morphElement(MonthMorphKey.Handle) - .background(MaterialTheme.colorScheme.outlineVariant, CircleShape), - ) + .size(width = SPLIT_HANDLE_RIPPLE_WIDTH, height = SPLIT_HANDLE_ROW_HEIGHT) + .clip(RoundedCornerShape(percent = 50)) + .clickable( + interactionSource = null, + indication = ripple(), + onClick = onToggle, + ) + .clearAndSetSemantics { }, + contentAlignment = Alignment.Center, + ) { + Box( + Modifier + .size(width = SPLIT_HANDLE_WIDTH, height = SPLIT_HANDLE_HEIGHT) + // Tagged too, so it slides from the pane's seam down to the foot + // of the grid rather than blinking out at one and in at the other. + .morphElement(MonthMorphKey.Handle) + .background(MaterialTheme.colorScheme.outlineVariant, CircleShape), + ) + } } } @@ -1692,6 +1586,7 @@ private val SPLIT_DOT_SIZE = 5.dp private val SPLIT_HANDLE_WIDTH = 32.dp private val SPLIT_HANDLE_HEIGHT = 4.dp private val SPLIT_HANDLE_ROW_HEIGHT = 24.dp +private val SPLIT_HANDLE_RIPPLE_WIDTH = SPLIT_HANDLE_WIDTH + 24.dp /** The pane below the split grid fades in once the grid's morph has mostly landed. */ private const val SPLIT_PANE_FADE_IN_DELAY_MILLIS = 300 @@ -1721,7 +1616,7 @@ internal fun SplitMonthGrid( onSelectDay: (LocalDate) -> Unit, modifier: Modifier = Modifier, ) { - val dark = isSystemInDarkTheme() + val dark = LocalFloretDarkTheme.current val month = state.month val hasToday = state.today.year == month.year && state.today.month == month.month val ripple = rememberTodayRipple(active = hasToday) @@ -1746,11 +1641,11 @@ internal fun SplitMonthGrid( val inMonth = day.month == month.month && day.year == month.year // Seated by lane rather than gathered by colour, so each dot // is the event the expanded grid draws in that same lane. - val seated = week.laneEvents(col, day, SPLIT_DOT_LANES) + val seated = week.laneEvents(col, SPLIT_DOT_LANES) SplitDayCell( date = day, events = seated, - hidden = week.overflowEvents(col, day, SPLIT_DOT_LANES), + hidden = week.overflowEvents(col, SPLIT_DOT_LANES), isToday = day == state.today, // A page marks only the days its own month owns. Paging // moves the selection before this month's replacement @@ -1835,6 +1730,7 @@ private fun SplitDayCell( modifier = modifier .padding(horizontal = CELL_GAP, vertical = 1.dp) .todayRipple(relativeToToday, rippleProgress) + .clip(CELL_SHAPE) .selectable(selected = isSelected, onClick = onClick), contentAlignment = Alignment.TopCenter, ) { @@ -1940,7 +1836,7 @@ private fun SplitDots( modifier = Modifier .morphBounds(MonthMorphKey.Event(date, event.instanceId)) .size(SPLIT_DOT_SIZE) - .alpha(if (dimCutoff != null && event.hasEnded(dimCutoff)) EventDimAlpha else 1f) + .alpha(if (dimCutoff != null && event.isPastOn(date, dimCutoff)) EventDimAlpha else 1f) .background(eventAccent(event.color, dark, soften), CircleShape), ) } @@ -1954,13 +1850,12 @@ private fun SplitDots( color = MaterialTheme.colorScheme.onSurfaceVariant, modifier = Modifier .morphBounds(MonthMorphKey.Overflow(date)) - .alpha(if (allEnded(hidden, dimCutoff)) EventDimAlpha else 1f), + .alpha(if (allEnded(hidden, date, dimCutoff)) EventDimAlpha else 1f), ) } } } -@OptIn(ExperimentalFoundationApi::class) @Composable private fun SplitMonthAgendaPane( state: MonthUiState.Success, @@ -1978,33 +1873,16 @@ private fun SplitMonthAgendaPane( val dimCutoff = LocalDimCutoff.current val listState = key(state.month) { rememberLazyListState() } LazyColumn(state = listState, contentPadding = PaddingValues(top = 8.dp, bottom = 96.dp)) { - days.forEach { day -> - val events = state.instancesByDay[day].orEmpty() - stickyHeader(key = "header-$day") { - AgendaDayHeader(date = day, today = state.today, onOpenDay = onOpenDay) - } - if (events.isEmpty()) { - item(key = "empty-$day") { - AgendaEmptyDayRow( - text = stringResource(R.string.month_split_no_events), - onClick = { onCreateEvent(day) }, - ) - } - } else { - itemsIndexed(events, key = { _, event -> "$day-${event.instanceId}" }) { index, event -> - AgendaEventRow( - event = event, - day = day, - zone = state.zone, - position = positionOf(index, events.size), - dimmed = dimCutoff != null && event.hasEnded(dimCutoff), - modifier = animateItemMotion().morphEvent(ViewMorphKey.event(event, day)), - onClick = { onEventClick(event) }, - ) - } - } - item(key = "gap-$day") { Spacer(Modifier.height(8.dp)) } - } + agendaDays( + days = days.map { AgendaDay(it, state.instancesByDay[it].orEmpty()) }, + today = state.today, + zone = state.zone, + emptyText = R.string.month_split_no_events, + onEmptyClick = onCreateEvent, + dimmed = { event, day -> dimCutoff != null && event.isPastOn(day, dimCutoff) }, + onOpenDay = onOpenDay, + onEventClick = onEventClick, + ) } } @@ -2066,7 +1944,7 @@ internal fun SplitDayPane( day = day, zone = zone, position = positionOf(index, dayEvents.size), - dimmed = dimCutoff != null && event.hasEnded(dimCutoff), + dimmed = dimCutoff != null && event.isPastOn(day, dimCutoff), onClick = { onEventClick(event) }, // An event added to or removed from the day you are // already looking at moves its neighbours rather @@ -2230,13 +2108,13 @@ private fun MonthWeekRow( */ selected: LocalDate? = null, ) { - val dark = isSystemInDarkTheme() + val dark = LocalFloretDarkTheme.current val todayCol = week.days.indexOf(today).takeIf { it >= 0 && inMonth(today) } val ripple = rememberTodayRipple(active = todayCol != null) val overflowRow = rememberOverflowRowHeight() val laneCap = week.laneCapFor(rowHeight, overflowRow) - val laneCount = (week.spans.maxOfOrNull { it.lane } ?: -1) + 1 - val shownLanes = laneCount.coerceAtMost(laneCap) + // Once per row rather than per frame: a drag recomposes every frame. + val seatings = remember(week, laneCap) { week.days.indices.map { week.seating(it, laneCap) } } val morphing = morphInFlight() // Every chip's start time for this row at once, and only when the row's own // inputs change: formatting is a parsed pattern per call, and the dim cutoff @@ -2420,7 +2298,7 @@ private fun MonthWeekRow( .then(if (morphing || dragging) Modifier else Modifier.clipToBounds()), ) { // Spanning bars on their shared lanes. - week.spans.filter { it.lane < shownLanes }.forEach { span -> + week.spans.filter { it.lane < laneCap }.forEach { span -> val cols = span.endCol - span.startCol + 1 MonthBar( event = span.event, @@ -2492,19 +2370,13 @@ private fun MonthWeekRow( ) } } - // Single-day timed pills + overflow, per column. Pills fill the - // lane slots no bar occupies on THIS day (top-most first), so a - // bar-free day isn't pushed down by a multi-day event that only - // sits on other days of the week. + // Single-day timed pills + overflow, per column, in the lanes + // [seating] gave them. week.days.forEachIndexed { col, d -> - val timed = week.timedByDay[d].orEmpty() - val occupied = week.spans - .filter { it.lane < shownLanes && col in it.startCol..it.endCol } - .map { it.lane } - .toSet() - val freeSlots = (0 until laneCap).filter { it !in occupied } - val pillsShown = timed.take(freeSlots.size) - pillsShown.forEachIndexed { i, ev -> + val seating = seatings[col] + seating.seated.forEach { seat -> + if (seat.bar) return@forEach + val ev = seat.event MonthBar( event = ev, dark = dark, @@ -2516,7 +2388,7 @@ private fun MonthWeekRow( modifier = Modifier .offset( x = colW * col, - y = EVENT_ROW_HEIGHT * freeSlots[i], + y = EVENT_ROW_HEIGHT * seat.lane, ) .morphBounds(MonthMorphKey.Event(d, ev.instanceId)) .then( @@ -2532,17 +2404,10 @@ private fun MonthWeekRow( .padding(horizontal = MONTH_CHIP_INSET, vertical = 1.dp), ) } - val hidden = (week.countByDay[d] ?: 0) - occupied.size - pillsShown.size - if (hidden > 0) { - val hiddenEvents = buildList { - week.spans - .filter { it.lane >= shownLanes && col in it.startCol..it.endCol } - .forEach { add(it.event) } - addAll(timed.drop(pillsShown.size)) - } + if (seating.hidden.isNotEmpty()) { OverflowDots( - events = hiddenEvents, - total = hidden, + events = seating.hidden, + day = d, dark = dark, rowHeight = overflowRow, modifier = Modifier @@ -2766,11 +2631,12 @@ private fun WeekNumberGutter(weekStart: LocalDate, modifier: Modifier = Modifier val onOpenWeek = LocalOpenWeek.current Box( modifier = modifier + .padding(horizontal = CELL_GAP, vertical = 1.dp) + .clip(CELL_SHAPE) + .background(MaterialTheme.colorScheme.secondaryContainer) .then(if (onOpenWeek != null) Modifier.clickable(onClickLabel = openLabel) { onOpenWeek(weekStart) } else Modifier) - .padding(horizontal = CELL_GAP, vertical = 1.dp) - .background(MaterialTheme.colorScheme.secondaryContainer, CELL_SHAPE) .semantics { contentDescription = "$label $weekNumber" }, contentAlignment = Alignment.Center, ) { @@ -2837,7 +2703,7 @@ private fun DayNumberCell( private fun shortMonthName(date: LocalDate): String { val locale = currentLocale() return remember(date.month, locale) { - java.time.Month.of(date.month.ordinal + 1) + date.month.toJavaMonth() .getDisplayName(JavaTextStyle.SHORT, locale) } } @@ -2866,7 +2732,9 @@ private fun MonthBar( ) { val title = event.title.ifBlank { stringResource(R.string.event_untitled) } val dimCutoff = LocalDimCutoff.current - val dimmed = dimCutoff != null && event.hasEnded(dimCutoff) + // A bar is one piece, so it dims once the last day it covers has passed. + val dimmed = dimCutoff != null && + (event.hasEnded(dimCutoff) || days?.let { event.isPastOn(it.last(), dimCutoff) } == true) val paint = eventPaint(event, dark) // The same title/secondary ink pairing the week and day blocks use, with // the time on the quieter half. @@ -2919,7 +2787,7 @@ private fun MonthBar( @Composable private fun OverflowDots( events: List, - total: Int, + day: LocalDate, dark: Boolean, rowHeight: Dp, modifier: Modifier = Modifier, @@ -2937,25 +2805,25 @@ private fun OverflowDots( Box( modifier = Modifier .size(OVERFLOW_DOT_SIZE) - .alpha(if (allEnded(byColor.getValue(argb), dimCutoff)) EventDimAlpha else 1f) + .alpha(if (allEnded(byColor.getValue(argb), day, dimCutoff)) EventDimAlpha else 1f) .background(eventAccent(argb, dark, soften), CircleShape), ) } - val extra = total - dots.size + val extra = events.size - dots.size if (extra > 0) { Text( text = "+$extra", style = MaterialTheme.typography.labelSmall, color = MaterialTheme.colorScheme.onSurfaceVariant, - modifier = Modifier.alpha(if (allEnded(events, dimCutoff)) EventDimAlpha else 1f), + modifier = Modifier.alpha(if (allEnded(events, day, dimCutoff)) EventDimAlpha else 1f), ) } } } -/** True when dimming is on and every one of [events] is already over. */ -private fun allEnded(events: List, dimCutoff: Instant?): Boolean = - dimCutoff != null && events.isNotEmpty() && events.all { it.hasEnded(dimCutoff) } +/** True when dimming is on and every one of [events] is already over on [day]. */ +private fun allEnded(events: List, day: LocalDate, dimCutoff: Instant?): Boolean = + dimCutoff != null && events.isNotEmpty() && events.all { it.isPastOn(day, dimCutoff) } @Composable private fun MonthGridLoading() { @@ -2997,7 +2865,7 @@ private fun formatMonthTitle( abbreviated: Boolean = false, ): String = formatCalendarTitle( - date = java.time.LocalDate.of(ym.year, ym.month.ordinal + 1, 1), + date = ym.firstDay.toJavaLocalDate(), locale = locale, currentYear = currentYear, skeleton = if (abbreviated) "LLL" else "LLLL", diff --git a/app/src/main/java/de/jeanlucmakiola/calendula/ui/month/MonthStylePreview.kt b/app/src/main/java/de/jeanlucmakiola/calendula/ui/month/MonthStylePreview.kt index ffe8d276..f27dcc6f 100644 --- a/app/src/main/java/de/jeanlucmakiola/calendula/ui/month/MonthStylePreview.kt +++ b/app/src/main/java/de/jeanlucmakiola/calendula/ui/month/MonthStylePreview.kt @@ -8,16 +8,16 @@ import androidx.compose.runtime.remember import androidx.compose.ui.Modifier import androidx.compose.ui.unit.Dp import androidx.compose.ui.unit.dp -import de.jeanlucmakiola.calendula.ui.common.ScaledViewPreview import de.jeanlucmakiola.calendula.ui.common.sampleMonthEvents +import de.jeanlucmakiola.floret.components.ScaledViewPreview import kotlinx.datetime.DateTimeUnit import kotlinx.datetime.DayOfWeek import kotlinx.datetime.LocalDate import kotlinx.datetime.TimeZone -import kotlinx.datetime.YearMonth import kotlinx.datetime.plus import kotlinx.datetime.toLocalDateTime import kotlin.time.Clock +import kotlinx.datetime.yearMonth /** * A live, scaled-down Month view in a given [MonthViewStyle], for the settings @@ -51,7 +51,7 @@ internal fun MonthStylePreview( state = sample.continuous, listState = rememberLazyListState( initialFirstVisibleItemIndex = itemIndexForMonth( - monthIndexOf(YearMonth(today.year, today.month)), + monthIndexOf(today.yearMonth), ), ), showWeekNumbers = false, @@ -109,7 +109,7 @@ private fun sampleMonthState( weekStart: DayOfWeek, zone: TimeZone, ): SampleMonth { - val ym = YearMonth(today.year, today.month) + val ym = today.yearMonth val first = LocalDate(ym.year, ym.month, 1) val events = sampleMonthEvents(first, today, zone) diff --git a/app/src/main/java/de/jeanlucmakiola/calendula/ui/month/MonthUiState.kt b/app/src/main/java/de/jeanlucmakiola/calendula/ui/month/MonthUiState.kt index cfb3c833..a6cdfcc0 100644 --- a/app/src/main/java/de/jeanlucmakiola/calendula/ui/month/MonthUiState.kt +++ b/app/src/main/java/de/jeanlucmakiola/calendula/ui/month/MonthUiState.kt @@ -39,33 +39,55 @@ data class MonthWeek( val countByDay: Map, ) +/** One event seated in [lane] of a day; [bar] is a spanning bar rather than that day's own pill. */ +data class Seat(val lane: Int, val event: EventInstance, val bar: Boolean) + /** - * The events occupying each lane of [day] — column [col] of this week — in lane - * order, capped at [laneCap] lanes. + * How one day of a week row is seated with [laneCap] lanes: what sits in each + * lane, top-most first with empty lanes left out, and what had no lane left. + */ +data class DaySeating(val seated: List, val hidden: List) + +/** + * The seating of column [col] with [laneCap] lanes — the one every reader of a + * row builds on: the bars and pills the paged grid draws, the split style's dots + * ([laneEvents]), the hit test ([chipAt]) and the overflow ([overflowEvents]). * - * This is the same seating [spans]/[timedByDay] get when the paged grid draws a - * week: bars keep the lane the row layout gave them, and the day's timed events - * fill whatever slots are left, top-most first. Reading it here means the split - * style's dots and the paged style's bars describe a day in the *same order*, so - * dot _i_ and lane _i_ are the same event and one can morph into the other (#53). + * Bars keep the lane the row layout gave them, and the day's timed events fill + * whatever slots are left, top-most first, so a bar-free day isn't pushed down by + * a multi-day event that only sits on other days of the week. Overflow is the + * exact complement, bars before pills. + */ +fun MonthWeek.seating(col: Int, laneCap: Int): DaySeating { + val covering = spans.filter { col in it.startCol..it.endCol } + val byLane = arrayOfNulls(laneCap.coerceAtLeast(0)) + covering.forEach { span -> + if (span.lane < laneCap) byLane[span.lane] = Seat(span.lane, span.event, bar = true) + } + val timed = timedByDay[days[col]].orEmpty() + var pills = 0 + for (lane in byLane.indices) { + if (byLane[lane] == null && pills < timed.size) byLane[lane] = Seat(lane, timed[pills++], bar = false) + } + return DaySeating( + seated = byLane.filterNotNull(), + hidden = covering.filter { it.lane >= laneCap }.map { it.event } + timed.drop(pills), + ) +} + +/** + * The events occupying each lane of column [col], in lane order, capped at + * [laneCap] lanes — the same [seating] the paged grid draws a week with. Reading + * it here means the split style's dots and the paged style's bars describe a day + * in the *same order*, so dot _i_ and lane _i_ are the same event and one can + * morph into the other (#53). * * Deriving the dots independently — by distinct colour, as they first were — * left dot _i_ standing for no particular event, and quietly merged two events * that shared a calendar into a single dot. */ -fun MonthWeek.laneEvents(col: Int, day: LocalDate, laneCap: Int): List { - val byLane = arrayOfNulls(laneCap) - spans.forEach { span -> - if (span.lane < laneCap && col in span.startCol..span.endCol) { - byLane[span.lane] = span.event - } - } - val free = (0 until laneCap).filter { byLane[it] == null } - timedByDay[day].orEmpty().take(free.size).forEachIndexed { i, event -> - byLane[free[i]] = event - } - return byLane.filterNotNull() -} +fun MonthWeek.laneEvents(col: Int, laneCap: Int): List = + seating(col, laneCap).seated.map { it.event } /** * The event drawn in lane [lane] of column [col], or null for an empty slot. @@ -74,14 +96,7 @@ fun MonthWeek.laneEvents(col: Int, day: LocalDate, laneCap: Int): List= 0 } ?: return null - return timedByDay[days[col]].orEmpty().take(free.size).getOrNull(index) + return seating(col, laneCap).seated.firstOrNull { it.lane == lane }?.event } /** @@ -98,19 +113,11 @@ fun MonthWeek.spanAt(col: Int, lane: Int): MonthSpan? = spans.firstOrNull { it.lane == lane && col in it.startCol..it.endCol } /** - * The events on [day] that [laneEvents] had no lane left for — its exact + * The events in column [col] that [laneEvents] had no lane left for — its exact * complement, in the same bars-then-pills order. Returned as events rather than * a count because dimming is a per-event question (#79). */ -fun MonthWeek.overflowEvents(col: Int, day: LocalDate, laneCap: Int): List { - val seatedLanes = spans.count { it.lane < laneCap && col in it.startCol..it.endCol } - return buildList { - spans.forEach { span -> - if (span.lane >= laneCap && col in span.startCol..span.endCol) add(span.event) - } - addAll(timedByDay[day].orEmpty().drop(laneCap - seatedLanes)) - } -} +fun MonthWeek.overflowEvents(col: Int, laneCap: Int): List = seating(col, laneCap).hidden /** * State for the continuous style (#38): a vertical stream of *self-contained* diff --git a/app/src/main/java/de/jeanlucmakiola/calendula/ui/month/MonthViewModel.kt b/app/src/main/java/de/jeanlucmakiola/calendula/ui/month/MonthViewModel.kt index 7964eec9..e84d3822 100644 --- a/app/src/main/java/de/jeanlucmakiola/calendula/ui/month/MonthViewModel.kt +++ b/app/src/main/java/de/jeanlucmakiola/calendula/ui/month/MonthViewModel.kt @@ -1,14 +1,16 @@ package de.jeanlucmakiola.calendula.ui.month +import de.jeanlucmakiola.calendula.ui.common.startOfWeek +import de.jeanlucmakiola.calendula.ui.common.dayRange import androidx.lifecycle.ViewModel import androidx.lifecycle.viewModelScope import dagger.hilt.android.lifecycle.HiltViewModel import de.jeanlucmakiola.calendula.data.calendar.CalendarRepository -import de.jeanlucmakiola.calendula.data.di.IoDispatcher import de.jeanlucmakiola.calendula.data.prefs.SettingsPrefs import de.jeanlucmakiola.calendula.data.prefs.firstDayOfWeek import de.jeanlucmakiola.calendula.data.time.TodaySource import de.jeanlucmakiola.calendula.data.time.currentDate +import de.jeanlucmakiola.calendula.data.time.stateFollowingDays import de.jeanlucmakiola.calendula.domain.CalendarSource import de.jeanlucmakiola.calendula.domain.EventInstance import de.jeanlucmakiola.calendula.domain.FailureReason @@ -19,10 +21,11 @@ import de.jeanlucmakiola.calendula.domain.eventDisplayComparator import de.jeanlucmakiola.calendula.ui.week.coversDay import de.jeanlucmakiola.calendula.ui.week.layoutAllDay import de.jeanlucmakiola.calendula.ui.week.spansMultipleDays +import de.jeanlucmakiola.floret.android.stateWhileSubscribed +import de.jeanlucmakiola.floret.di.IoDispatcher import kotlinx.coroutines.CoroutineDispatcher import kotlinx.coroutines.ExperimentalCoroutinesApi import kotlinx.coroutines.flow.MutableStateFlow -import kotlinx.coroutines.flow.SharingStarted import kotlinx.coroutines.flow.StateFlow import kotlinx.coroutines.flow.catch import kotlinx.coroutines.flow.combine @@ -33,22 +36,19 @@ import kotlinx.coroutines.flow.filterNot import kotlinx.coroutines.flow.map import kotlin.math.abs import kotlinx.coroutines.flow.onEach -import kotlinx.coroutines.flow.stateIn import kotlinx.datetime.DateTimeUnit import kotlinx.datetime.DayOfWeek import kotlinx.datetime.LocalDate import kotlinx.datetime.Month import kotlinx.datetime.TimeZone import kotlinx.datetime.YearMonth -import kotlinx.datetime.atStartOfDayIn -import kotlinx.datetime.atTime import kotlinx.datetime.daysUntil import kotlinx.datetime.minus import kotlinx.datetime.plus -import kotlinx.datetime.toInstant import kotlinx.datetime.toLocalDateTime import kotlin.time.Instant import javax.inject.Inject +import kotlinx.datetime.yearMonth /** How many months either side of the requested one [MonthViewModel.month] keeps cached. */ private const val MONTH_CACHE_SPAN = 2 @@ -69,54 +69,35 @@ class MonthViewModel @Inject constructor( /** Whether to fade events that have already finished (display concern only). */ val dimCompletedEvents: StateFlow = settingsPrefs.dimCompletedEvents - .stateIn( + .stateWhileSubscribed( scope = viewModelScope, - started = SharingStarted.WhileSubscribed(5_000L), initialValue = false, ) /** Whether to show the calendar-week number gutter (#25; display only). */ val showWeekNumbers: StateFlow = settingsPrefs.showWeekNumbers - .stateIn( + .stateWhileSubscribed( scope = viewModelScope, - started = SharingStarted.WhileSubscribed(5_000L), initialValue = false, ) /** How the grid is laid out and navigated (#38, #53). */ val viewStyle: StateFlow = settingsPrefs.monthViewStyle - .stateIn( + .stateWhileSubscribed( scope = viewModelScope, - started = SharingStarted.WhileSubscribed(5_000L), initialValue = MonthViewStyle.Paged, ) private val todayDate: LocalDate get() = currentDate() - private var lastToday = todayDate - /** Today, kept current across midnight so a grid left open doesn't mark yesterday (#373). */ - val today: StateFlow = todaySource.today - .onEach { date -> - val old = lastToday - lastToday = date - if (old != date) followToday(old, date) - } - .stateIn(viewModelScope, SharingStarted.WhileSubscribed(5_000L), todayDate) + val today: StateFlow = + todaySource.today.stateFollowingDays(viewModelScope, todayDate, ::followToday) - private val _month = MutableStateFlow(YearMonth(todayDate.year, todayDate.month)) + private val _month = MutableStateFlow(todayDate.yearMonth) val month: StateFlow = _month - /** The pager page the anchor month sits on, for the paged and split styles. */ - val anchorPage: StateFlow = _month - .map { monthIndexOf(it) } - .stateIn( - scope = viewModelScope, - started = SharingStarted.WhileSubscribed(5_000L), - initialValue = monthIndexOf(_month.value), - ) - /** * The anchor month's state. Once loaded it never falls back to * [MonthUiState.Loading]: moving the anchor keeps the last result until the @@ -133,9 +114,8 @@ class MonthViewModel @Inject constructor( month(ym, ws).filterNot { it is MonthUiState.Loading } } .catch { emit(MonthUiState.Failure(FailureReason.ProviderUnavailable)) } - .stateIn( + .stateWhileSubscribed( scope = viewModelScope, - started = SharingStarted.WhileSubscribed(5_000L), initialValue = MonthUiState.Loading, ) @@ -170,7 +150,8 @@ class MonthViewModel @Inject constructor( fun onPageSettled(page: Int) { if (monthIndexOf(_month.value) == page) return _month.value = yearMonthForIndex(page) - realignSelection() + // Moving the grid to another month restores its full agenda. + _selectedDate.value = null } // --- Continuous + Dense styles (#38) ---------------------------------- @@ -195,11 +176,11 @@ class MonthViewModel @Inject constructor( /** Last reported visible range, so a widening step can re-centre on it. */ @Volatile - private var visibleMonths = monthIndexOf(YearMonth(todayDate.year, todayDate.month)) + private var visibleMonths = monthIndexOf(todayDate.yearMonth) .let { it..it } private val _loadedMonths = MutableStateFlow( - monthIndexOf(YearMonth(todayDate.year, todayDate.month)) + monthIndexOf(todayDate.yearMonth) .let { clampMonthWindow(it - INITIAL_PAD..it + INITIAL_PAD) }, ) @@ -215,13 +196,11 @@ class MonthViewModel @Inject constructor( // Widened to whole grid weeks at both ends: a month block still // has to know about an event that starts in the boundary week's // clipped-off days, or a bar running into the block would vanish. - val first = firstOfMonth(yearMonthForIndex(window.first)).startOfGridWeek(ws) - val last = firstOfMonth(yearMonthForIndex(window.last)) - .plus(1, DateTimeUnit.MONTH) - .minus(1, DateTimeUnit.DAY) - .startOfGridWeek(ws) + val first = yearMonthForIndex(window.first).firstDay.startOfWeek(ws) + val last = yearMonthForIndex(window.last).lastDay + .startOfWeek(ws) .plus(6, DateTimeUnit.DAY) - val range = first.atStartOfDayIn(zone)..last.atTime(23, 59, 59).toInstant(zone) + val range = dayRange(first, last, zone) combine( repository.calendars(), repository.instances(range), @@ -236,9 +215,8 @@ class MonthViewModel @Inject constructor( .onEach { if (it is ContinuousMonthUiState.Success) widenLoadedWindow() } .catch { emit(ContinuousMonthUiState.Failure(FailureReason.ProviderUnavailable)) } .flowOn(io) - .stateIn( + .stateWhileSubscribed( scope = viewModelScope, - started = SharingStarted.WhileSubscribed(5_000L), initialValue = ContinuousMonthUiState.Loading, ) @@ -320,7 +298,7 @@ class MonthViewModel @Inject constructor( * silently list a date the grid isn't pointing at. */ fun selectDate(date: LocalDate) { - val target = YearMonth(date.year, date.month) + val target = date.yearMonth _selectedDate.value = if (target == _month.value && _selectedDate.value == date) null else date if (target != _month.value) _month.value = target } @@ -335,17 +313,12 @@ class MonthViewModel @Inject constructor( } else { val next = selected.plus(days, DateTimeUnit.DAY) _selectedDate.value = next - _month.value = YearMonth(next.year, next.month) + _month.value = next.yearMonth } } - /** Moving the grid to another month restores its full agenda. */ - private fun realignSelection() { - _selectedDate.value = null - } - fun goToToday() { - _month.value = YearMonth(todayDate.year, todayDate.month) + _month.value = todayDate.yearMonth _selectedDate.value = null } @@ -356,8 +329,8 @@ class MonthViewModel @Inject constructor( */ private fun followToday(old: LocalDate, new: LocalDate) { if (viewStyle.value.isScrolling) return - if (_month.value != YearMonth(old.year, old.month)) return - _month.value = YearMonth(new.year, new.month) + if (_month.value != old.yearMonth) return + _month.value = new.yearMonth _selectedDate.value = null } @@ -377,7 +350,7 @@ class MonthViewModel @Inject constructor( /** Jump to the month containing [date] (drawer jump-to-date). */ fun goToDate(date: LocalDate) { - _month.value = YearMonth(date.year, date.month) + _month.value = date.yearMonth _selectedDate.value = date } @@ -427,7 +400,7 @@ internal fun layoutMonthWeeks( byDay: DayIndex, zone: TimeZone, ): List { - val gridStart = firstOfMonth(ym).startOfGridWeek(weekStart) + val gridStart = ym.firstDay.startOfWeek(weekStart) val weekCount = weekRowsInMonth(ym, weekStart) return (0 until weekCount).map { row -> @@ -548,12 +521,8 @@ internal fun monthGridRange( weekStart: DayOfWeek, zone: TimeZone, ): ClosedRange { - val firstOfMonth = LocalDate(ym.year, ym.month, 1) - val gridStart = firstOfMonth.startOfGridWeek(weekStart) - val gridEnd = gridStart.plus(41, DateTimeUnit.DAY) - val start = gridStart.atStartOfDayIn(zone) - val end = gridEnd.atTime(23, 59, 59).toInstant(zone) - return start..end + val gridStart = ym.firstDay.startOfWeek(weekStart) + return dayRange(gridStart, gridStart.plus(41, DateTimeUnit.DAY), zone) } /** @@ -581,7 +550,7 @@ internal fun edgeForPad(pad: Int): Int = minOf(WINDOW_EDGE, pad - 1).coerceAtLea * the first of the visible month. */ internal fun agendaStartForMonth(month: YearMonth, today: LocalDate): LocalDate = - if (YearMonth(today.year, today.month) == month) { + if (today.yearMonth == month) { today } else { LocalDate(month.year, month.month, 1) @@ -649,8 +618,6 @@ internal fun clampMonthWindow(window: IntRange): IntRange { return window.first.coerceIn(0, last)..window.last.coerceIn(0, last) } -internal fun firstOfMonth(ym: YearMonth): LocalDate = LocalDate(ym.year, ym.month, 1) - /** * The Dense style addresses *weeks* by absolute index instead: it has no month * blocks to key by, and a row's identity has to survive the months around it @@ -665,12 +632,12 @@ private val WEEK_INDEX_EPOCH = LocalDate(1900, 1, 1) private val WEEK_INDEX_END = LocalDate(2100, 12, 31) internal fun weekIndexOf(date: LocalDate, weekStart: DayOfWeek): Int { - val base = WEEK_INDEX_EPOCH.startOfGridWeek(weekStart) - return base.daysUntil(date.startOfGridWeek(weekStart)) / 7 + val base = WEEK_INDEX_EPOCH.startOfWeek(weekStart) + return base.daysUntil(date.startOfWeek(weekStart)) / 7 } internal fun weekStartForIndex(index: Int, weekStart: DayOfWeek): LocalDate = - WEEK_INDEX_EPOCH.startOfGridWeek(weekStart).plus(index * 7, DateTimeUnit.DAY) + WEEK_INDEX_EPOCH.startOfWeek(weekStart).plus(index * 7, DateTimeUnit.DAY) /** Total weeks the Dense grid scrolls through (1900 → 2100). */ internal fun continuousWeekCount(weekStart: DayOfWeek): Int = @@ -681,7 +648,7 @@ internal fun monthIndexForWeek(weekIndex: Int, weekStart: DayOfWeek): Int { // The row's midweek day: a boundary week is reported as whichever month owns // most of it, the same rule the title uses. val midweek = weekStartForIndex(weekIndex, weekStart).plus(3, DateTimeUnit.DAY) - return monthIndexOf(YearMonth(midweek.year, midweek.month)) + return monthIndexOf(midweek.yearMonth) } /** @@ -690,19 +657,16 @@ internal fun monthIndexForWeek(weekIndex: Int, weekStart: DayOfWeek): Int { * laid out too, rather than flickering as placeholders. */ internal fun weekWindowFor(window: IntRange, weekStart: DayOfWeek): IntRange { - val first = weekIndexOf(firstOfMonth(yearMonthForIndex(window.first)), weekStart) - 1 - val lastMonthEnd = firstOfMonth(yearMonthForIndex(window.last)) - .plus(1, DateTimeUnit.MONTH) - .minus(1, DateTimeUnit.DAY) + val first = weekIndexOf(yearMonthForIndex(window.first).firstDay, weekStart) - 1 + val lastMonthEnd = yearMonthForIndex(window.last).lastDay return first..(weekIndexOf(lastMonthEnd, weekStart) + 1) } /** How many week rows [ym] needs under [weekStart] — 4 (a non-leap February), 5 or 6. */ internal fun weekRowsInMonth(ym: YearMonth, weekStart: DayOfWeek): Int { - val first = firstOfMonth(ym) + val first = ym.firstDay val leadOffset = ((first.dayOfWeek.ordinal - weekStart.ordinal) + 7) % 7 - val daysInMonth = java.time.YearMonth.of(ym.year, ym.month.ordinal + 1).lengthOfMonth() - return (leadOffset + daysInMonth + 6) / 7 + return (leadOffset + ym.numberOfDays + 6) / 7 } /** @@ -746,9 +710,3 @@ internal fun clipWeekToMonth(week: MonthWeek, month: YearMonth): MonthWeek { countByDay = week.countByDay.filterKeys { it in own }, ) } - -internal fun LocalDate.startOfGridWeek(weekStart: DayOfWeek): LocalDate { - // DayOfWeek.ordinal: MONDAY=0..SUNDAY=6 → identical to ISO ordering. - val offset = ((dayOfWeek.ordinal - weekStart.ordinal) + 7) % 7 - return minus(offset, DateTimeUnit.DAY) -} diff --git a/app/src/main/java/de/jeanlucmakiola/calendula/ui/onboarding/BackupStep.kt b/app/src/main/java/de/jeanlucmakiola/calendula/ui/onboarding/BackupStep.kt index 87627f12..65001ed1 100644 --- a/app/src/main/java/de/jeanlucmakiola/calendula/ui/onboarding/BackupStep.kt +++ b/app/src/main/java/de/jeanlucmakiola/calendula/ui/onboarding/BackupStep.kt @@ -10,17 +10,14 @@ import androidx.compose.material.icons.Icons import androidx.compose.material.icons.filled.CloudOff import androidx.compose.material.icons.filled.FolderOpen import androidx.compose.material.icons.filled.Schedule -import androidx.compose.material3.Button -import androidx.compose.material3.MaterialTheme import androidx.compose.material3.Text import androidx.compose.material3.TextButton import androidx.compose.runtime.Composable import androidx.compose.ui.Modifier import androidx.compose.ui.res.stringResource -import androidx.compose.ui.text.style.TextAlign -import androidx.compose.ui.unit.dp import de.jeanlucmakiola.calendula.R import de.jeanlucmakiola.floret.components.BenefitRow +import de.jeanlucmakiola.floret.components.OnboardingPrimaryButton import de.jeanlucmakiola.floret.components.OnboardingScaffold import de.jeanlucmakiola.floret.components.OnboardingSpace @@ -53,15 +50,10 @@ internal fun BackupStep( topSpacing = OnboardingSpace.lg, hero = { IconHero(Icons.Filled.CloudOff) }, actions = { - Button( + OnboardingPrimaryButton( + text = stringResource(R.string.onboarding_backup_enable_button), onClick = { runCatching { pickFolder.launch(null) } }, - modifier = Modifier.fillMaxWidth().height(56.dp), - ) { - Text( - text = stringResource(R.string.onboarding_backup_enable_button), - style = MaterialTheme.typography.titleMedium, - ) - } + ) TextButton( onClick = onSkip, modifier = Modifier.fillMaxWidth(), @@ -69,20 +61,9 @@ internal fun BackupStep( Text(stringResource(R.string.onboarding_backup_skip_button)) } }, + headline = stringResource(R.string.onboarding_backup_title), + supporting = stringResource(R.string.onboarding_backup_body), ) { - Text( - text = stringResource(R.string.onboarding_backup_title), - style = MaterialTheme.typography.headlineMedium, - textAlign = TextAlign.Center, - ) - Spacer(Modifier.height(12.dp)) - Text( - text = stringResource(R.string.onboarding_backup_body), - style = MaterialTheme.typography.bodyLarge, - color = MaterialTheme.colorScheme.onSurfaceVariant, - textAlign = TextAlign.Center, - ) - Spacer(Modifier.height(OnboardingSpace.lg)) BenefitRow( diff --git a/app/src/main/java/de/jeanlucmakiola/calendula/ui/onboarding/CalendarsStep.kt b/app/src/main/java/de/jeanlucmakiola/calendula/ui/onboarding/CalendarsStep.kt index 97984eb4..ab37d675 100644 --- a/app/src/main/java/de/jeanlucmakiola/calendula/ui/onboarding/CalendarsStep.kt +++ b/app/src/main/java/de/jeanlucmakiola/calendula/ui/onboarding/CalendarsStep.kt @@ -9,7 +9,6 @@ import androidx.compose.material.icons.filled.CheckCircle import androidx.compose.material.icons.filled.CloudSync import androidx.compose.material.icons.filled.PhoneAndroid import androidx.compose.material.icons.filled.Settings -import androidx.compose.material3.Button import androidx.compose.material3.MaterialTheme import androidx.compose.material3.OutlinedButton import androidx.compose.material3.Text @@ -30,6 +29,7 @@ import de.jeanlucmakiola.calendula.data.calendar.CalendarColorPalette import de.jeanlucmakiola.calendula.ui.calendars.CalendarEditor import de.jeanlucmakiola.calendula.ui.settings.openUrl import de.jeanlucmakiola.floret.components.BenefitRow +import de.jeanlucmakiola.floret.components.OnboardingPrimaryButton import de.jeanlucmakiola.floret.components.OnboardingScaffold import de.jeanlucmakiola.floret.components.OnboardingSpace @@ -108,18 +108,13 @@ internal fun CalendarsStep( topSpacing = OnboardingSpace.lg, hero = { IconHero(Icons.Filled.CalendarMonth) }, actions = { - Button( + OnboardingPrimaryButton( + text = stringResource(R.string.onboarding_calendars_local_button), onClick = { onClearCreation() creating = true }, - modifier = Modifier.fillMaxWidth().height(56.dp), - ) { - Text( - text = stringResource(R.string.onboarding_calendars_local_button), - style = MaterialTheme.typography.titleMedium, - ) - } + ) OutlinedButton( onClick = { openUrl(context, DAVX5_URL) }, modifier = Modifier.fillMaxWidth().height(56.dp), @@ -133,20 +128,9 @@ internal fun CalendarsStep( Text(stringResource(R.string.onboarding_calendars_skip_button)) } }, + headline = stringResource(R.string.onboarding_calendars_title), + supporting = stringResource(R.string.onboarding_calendars_body), ) { - Text( - text = stringResource(R.string.onboarding_calendars_title), - style = MaterialTheme.typography.headlineMedium, - textAlign = TextAlign.Center, - ) - Spacer(Modifier.height(12.dp)) - Text( - text = stringResource(R.string.onboarding_calendars_body), - style = MaterialTheme.typography.bodyLarge, - color = MaterialTheme.colorScheme.onSurfaceVariant, - textAlign = TextAlign.Center, - ) - if (creation is CalendarCreation.Failed) { Spacer(Modifier.height(12.dp)) Text( @@ -189,30 +173,14 @@ private fun CalendarCreated( topSpacing = OnboardingSpace.lg, hero = { IconHero(Icons.Filled.CheckCircle) }, actions = { - Button( + OnboardingPrimaryButton( + text = stringResource(R.string.onboarding_calendars_created_continue), onClick = onContinue, - modifier = Modifier.fillMaxWidth().height(56.dp), - ) { - Text( - text = stringResource(R.string.onboarding_calendars_created_continue), - style = MaterialTheme.typography.titleMedium, - ) - } + ) }, + headline = stringResource(R.string.onboarding_calendars_created_title, name), + supporting = stringResource(R.string.onboarding_calendars_created_body), ) { - Text( - text = stringResource(R.string.onboarding_calendars_created_title, name), - style = MaterialTheme.typography.headlineMedium, - textAlign = TextAlign.Center, - ) - Spacer(Modifier.height(12.dp)) - Text( - text = stringResource(R.string.onboarding_calendars_created_body), - style = MaterialTheme.typography.bodyLarge, - color = MaterialTheme.colorScheme.onSurfaceVariant, - textAlign = TextAlign.Center, - ) - Spacer(Modifier.height(OnboardingSpace.lg)) BenefitRow( diff --git a/app/src/main/java/de/jeanlucmakiola/calendula/ui/onboarding/DoneStep.kt b/app/src/main/java/de/jeanlucmakiola/calendula/ui/onboarding/DoneStep.kt index 59c5154b..78e78638 100644 --- a/app/src/main/java/de/jeanlucmakiola/calendula/ui/onboarding/DoneStep.kt +++ b/app/src/main/java/de/jeanlucmakiola/calendula/ui/onboarding/DoneStep.kt @@ -1,17 +1,10 @@ package de.jeanlucmakiola.calendula.ui.onboarding -import androidx.compose.foundation.layout.Spacer -import androidx.compose.foundation.layout.fillMaxWidth -import androidx.compose.foundation.layout.height -import androidx.compose.material3.Button -import androidx.compose.material3.MaterialTheme -import androidx.compose.material3.Text import androidx.compose.runtime.Composable import androidx.compose.ui.Modifier import androidx.compose.ui.res.stringResource -import androidx.compose.ui.text.style.TextAlign -import androidx.compose.ui.unit.dp import de.jeanlucmakiola.calendula.R +import de.jeanlucmakiola.floret.components.OnboardingPrimaryButton import de.jeanlucmakiola.floret.components.OnboardingScaffold import de.jeanlucmakiola.floret.components.OnboardingSpace @@ -34,28 +27,12 @@ internal fun DoneStep( topSpacing = OnboardingSpace.lg, hero = { BrandHero(HeroBadge.Done) }, actions = { - Button( + OnboardingPrimaryButton( + text = stringResource(R.string.onboarding_done_button), onClick = onFinished, - modifier = Modifier.fillMaxWidth().height(56.dp), - ) { - Text( - text = stringResource(R.string.onboarding_done_button), - style = MaterialTheme.typography.titleMedium, - ) - } + ) }, - ) { - Text( - text = stringResource(R.string.onboarding_done_title), - style = MaterialTheme.typography.headlineMedium, - textAlign = TextAlign.Center, - ) - Spacer(Modifier.height(12.dp)) - Text( - text = stringResource(R.string.onboarding_done_body), - style = MaterialTheme.typography.bodyLarge, - color = MaterialTheme.colorScheme.onSurfaceVariant, - textAlign = TextAlign.Center, - ) - } + headline = stringResource(R.string.onboarding_done_title), + supporting = stringResource(R.string.onboarding_done_body), + ) } diff --git a/app/src/main/java/de/jeanlucmakiola/calendula/ui/onboarding/HiddenCalendarsStep.kt b/app/src/main/java/de/jeanlucmakiola/calendula/ui/onboarding/HiddenCalendarsStep.kt index 472d336e..ea498de1 100644 --- a/app/src/main/java/de/jeanlucmakiola/calendula/ui/onboarding/HiddenCalendarsStep.kt +++ b/app/src/main/java/de/jeanlucmakiola/calendula/ui/onboarding/HiddenCalendarsStep.kt @@ -7,24 +7,23 @@ import androidx.compose.foundation.layout.height import androidx.compose.foundation.layout.padding import androidx.compose.material.icons.Icons import androidx.compose.material.icons.filled.VisibilityOff -import androidx.compose.material3.Button import androidx.compose.material3.MaterialTheme -import androidx.compose.material3.Switch import androidx.compose.material3.Text import androidx.compose.material3.TextButton import androidx.compose.runtime.Composable import androidx.compose.ui.Modifier import androidx.compose.ui.res.stringResource -import androidx.compose.ui.semantics.contentDescription -import androidx.compose.ui.semantics.semantics import androidx.compose.ui.text.style.TextAlign import androidx.compose.ui.unit.dp import de.jeanlucmakiola.calendula.R import de.jeanlucmakiola.calendula.domain.CalendarSource import de.jeanlucmakiola.calendula.domain.hasVisibilitySwitch import de.jeanlucmakiola.calendula.ui.common.CalendarColorChip +import de.jeanlucmakiola.calendula.ui.common.CalendarVisibilitySwitch +import de.jeanlucmakiola.calendula.ui.common.orUnnamed import de.jeanlucmakiola.floret.components.GroupedListInset import de.jeanlucmakiola.floret.components.GroupedRow +import de.jeanlucmakiola.floret.components.OnboardingPrimaryButton import de.jeanlucmakiola.floret.components.OnboardingScaffold import de.jeanlucmakiola.floret.components.OnboardingSpace import de.jeanlucmakiola.floret.components.Position @@ -65,24 +64,17 @@ internal fun HiddenCalendarsStep( scrollingActions = true, hero = { IconHero(Icons.Filled.VisibilityOff) }, actions = { - Button( + OnboardingPrimaryButton( + text = stringResource( + if (anyVisible) { + R.string.onboarding_view_continue_button + } else { + R.string.onboarding_hidden_switch_all_button + }, + ), onClick = if (anyVisible) onFinished else onSwitchAllOn, - modifier = Modifier - .padding(horizontal = GroupedListInset) - .fillMaxWidth() - .height(56.dp), - ) { - Text( - text = stringResource( - if (anyVisible) { - R.string.onboarding_view_continue_button - } else { - R.string.onboarding_hidden_switch_all_button - }, - ), - style = MaterialTheme.typography.titleMedium, - ) - } + modifier = Modifier.padding(horizontal = GroupedListInset), + ) // Only while nothing is on: once something is, the step has been // answered and the one button left to press says so. if (!anyVisible) { @@ -129,7 +121,7 @@ internal fun HiddenCalendarsStep( calendars.forEachIndexed { index, calendar -> val off = !calendar.isVisibleInSystem GroupedRow( - title = calendar.displayName.ifBlank { stringResource(R.string.calendar_unnamed) }, + title = calendar.displayName.orUnnamed(), summary = calendar.accountName.takeIf { it.isNotBlank() }, position = when { calendars.size == 1 -> Position.Alone @@ -140,8 +132,8 @@ internal fun HiddenCalendarsStep( dimmed = off, trailing = if (calendar.hasVisibilitySwitch) { { - CalendarSwitch( - calendarName = calendar.displayName.ifBlank { stringResource(R.string.calendar_unnamed) }, + CalendarVisibilitySwitch( + calendarName = calendar.displayName.orUnnamed(), enabled = !off, onToggle = { on -> onSetVisible(calendar.id, on) }, ) @@ -156,18 +148,3 @@ internal fun HiddenCalendarsStep( Spacer(Modifier.height(OnboardingSpace.md)) } } - -/** The per-row switch, writing the device's own `Calendars.VISIBLE` as Settings does. */ -@Composable -private fun CalendarSwitch( - calendarName: String, - enabled: Boolean, - onToggle: (Boolean) -> Unit, -) { - val label = stringResource(R.string.calendars_visibility_a11y, calendarName) - Switch( - checked = enabled, - onCheckedChange = onToggle, - modifier = Modifier.semantics { contentDescription = label }, - ) -} diff --git a/app/src/main/java/de/jeanlucmakiola/calendula/ui/onboarding/OnboardingViewModel.kt b/app/src/main/java/de/jeanlucmakiola/calendula/ui/onboarding/OnboardingViewModel.kt index e6cbf3e6..9407aa9b 100644 --- a/app/src/main/java/de/jeanlucmakiola/calendula/ui/onboarding/OnboardingViewModel.kt +++ b/app/src/main/java/de/jeanlucmakiola/calendula/ui/onboarding/OnboardingViewModel.kt @@ -10,7 +10,6 @@ import dagger.hilt.android.qualifiers.ApplicationContext import de.jeanlucmakiola.calendula.data.backup.BackupScheduler import de.jeanlucmakiola.calendula.data.calendar.CalendarRepository import de.jeanlucmakiola.calendula.data.calendar.CalendarVisibilityReconciler -import de.jeanlucmakiola.calendula.data.di.IoDispatcher import de.jeanlucmakiola.calendula.data.prefs.CalendarPrefs import de.jeanlucmakiola.calendula.data.prefs.SettingsPrefs import de.jeanlucmakiola.calendula.data.prefs.WeekStartPref @@ -20,6 +19,8 @@ import de.jeanlucmakiola.calendula.domain.hasVisibilitySwitch import de.jeanlucmakiola.calendula.domain.orderedForManager import de.jeanlucmakiola.calendula.ui.common.CalendarView import de.jeanlucmakiola.calendula.ui.month.MonthViewStyle +import de.jeanlucmakiola.floret.android.stateWhileSubscribed +import de.jeanlucmakiola.floret.di.IoDispatcher import kotlinx.coroutines.CoroutineDispatcher import kotlinx.coroutines.ExperimentalCoroutinesApi import kotlinx.coroutines.flow.Flow @@ -92,9 +93,8 @@ class OnboardingViewModel @Inject constructor( list.catch { emit(null) }.flowOn(io) } } - .stateIn( + .stateWhileSubscribed( scope = viewModelScope, - started = SharingStarted.WhileSubscribed(5_000L), initialValue = null, ) @@ -166,15 +166,6 @@ class OnboardingViewModel @Inject constructor( hiddenTouched, ) { hidden, touched -> if (touched) null else hidden } - /** Both calendar steps' inputs: what each applies to, and whether it is answered. */ - private val calendarsFlags: Flow = combine( - calendarsApplies, - prefs.onboardingCalendarsDone, - hiddenApplies, - prefs.onboardingHiddenCalendarsDone, - ::CalendarsFlags, - ) - /** * The calendars the hidden-calendars step lists, so the user can judge which * to switch on rather than take the app's word that there are some. Live: a @@ -183,58 +174,44 @@ class OnboardingViewModel @Inject constructor( */ val hiddenCalendars: StateFlow> = calendars .map { it.orEmpty().orderedForManager() } - .stateIn( + .stateWhileSubscribed( scope = viewModelScope, - started = SharingStarted.WhileSubscribed(5_000L), initialValue = emptyList(), ) - private val flags: Flow = combine( - prefs.reminderOnboardingDone, - prefs.onboardingWizardArmed, - prefs.onboardingBackupDone, - prefs.onboardingViewDone, - prefs.onboardingMonthStyleDone, - ::OnboardingFlags, - ) - - /** The closing steps' own flags, and whether the notice applies at all. */ - private val closingFlags: Flow = combine( - calendarPrefs.visibilityNoticePending.map { it == true }, - prefs.onboardingVisibilityDone, - prefs.onboardingDoneShown, - ::ClosingFlags, - ) + /** What the two calendar steps apply to (#287). */ + private val calendarStepsApply: Flow> = + combine(calendarsApplies, hiddenApplies, ::Pair) val plan: StateFlow = combine( hasPermission, - flags, - closingFlags, + prefs.onboardingProgress, + calendarPrefs.visibilityNoticePending.map { it == true }, backupApplies, - calendarsFlags, - ) { granted, stored, closing, backup, calendars -> + calendarStepsApply, + ) { granted, progress, visibilityArmed, backup, (calendars, hidden) -> + val answered = progress.answered granted?.let { onboardingPlan( hasPermission = it, - remindersDone = stored.remindersDone, - wizardArmed = stored.wizardArmed, - backupDone = stored.backupDone, - viewDone = stored.viewDone, - monthStyleDone = stored.monthStyleDone, + remindersDone = OnboardingStep.Reminders in answered, + wizardArmed = progress.wizardArmed, + backupDone = OnboardingStep.Backup in answered, + viewDone = OnboardingStep.View in answered, + monthStyleDone = OnboardingStep.MonthStyle in answered, backupApplies = backup, - hiddenDone = calendars.hiddenDone, - hiddenApplies = calendars.hiddenApplies, - calendarsDone = calendars.done, - calendarsApplies = calendars.applies, - visibilityArmed = closing.visibilityArmed, - visibilityDone = closing.visibilityDone, - doneShown = closing.doneShown, + hiddenDone = OnboardingStep.HiddenCalendars in answered, + hiddenApplies = hidden, + calendarsDone = OnboardingStep.Calendars in answered, + calendarsApplies = calendars, + visibilityArmed = visibilityArmed, + visibilityDone = OnboardingStep.Visibility in answered, + doneShown = OnboardingStep.Done in answered, ) } - }.stateIn( + }.stateWhileSubscribed( scope = viewModelScope, - started = SharingStarted.WhileSubscribed(5_000L), initialValue = null, ) @@ -244,9 +221,8 @@ class OnboardingViewModel @Inject constructor( prefs.monthViewStyle, prefs.weekStart, ::ViewChoice, - ).stateIn( + ).stateWhileSubscribed( scope = viewModelScope, - started = SharingStarted.WhileSubscribed(5_000L), initialValue = null, ) @@ -261,7 +237,7 @@ class OnboardingViewModel @Inject constructor( * to a restarted process, leaving them the reminder step alone. */ private suspend fun armWizardIfFresh() { - if (!prefs.reminderOnboardingDone.first()) prefs.armOnboardingWizard() + prefs.armOnboardingWizard() } /** @@ -277,7 +253,7 @@ class OnboardingViewModel @Inject constructor( fun finishReminders(remindersEnabled: Boolean) { viewModelScope.launch { prefs.setRemindersEnabled(remindersEnabled) - prefs.setReminderOnboardingDone() + prefs.setOnboardingDone(OnboardingStep.Reminders) // Nothing else re-arms the scan: turning reminders off cancels the // alarm (#75). scanner.scan() @@ -291,24 +267,13 @@ class OnboardingViewModel @Inject constructor( * returned to, which [OnboardingPlan.canGoBack] already refuses. */ fun goBack() { - viewModelScope.launch { - when (plan.value?.previous) { - OnboardingStep.HiddenCalendars -> prefs.setOnboardingHiddenCalendarsDone(false) - OnboardingStep.Calendars -> prefs.setOnboardingCalendarsDone(false) - OnboardingStep.Reminders -> prefs.setReminderOnboardingDone(false) - OnboardingStep.Backup -> prefs.setOnboardingBackupDone(false) - OnboardingStep.View -> prefs.setOnboardingViewDone(false) - OnboardingStep.MonthStyle -> prefs.setOnboardingMonthStyleDone(false) - OnboardingStep.Visibility -> prefs.setOnboardingVisibilityDone(false) - OnboardingStep.Done -> prefs.setOnboardingDoneShown(false) - OnboardingStep.Permission, null -> Unit - } - } + val previous = plan.value?.previous ?: return + viewModelScope.launch { prefs.setOnboardingDone(previous, done = false) } } /** Close the backup step without setting anything up. */ fun skipBackup() { - viewModelScope.launch { prefs.setOnboardingBackupDone() } + viewModelScope.launch { prefs.setOnboardingDone(OnboardingStep.Backup) } } /** @@ -340,7 +305,7 @@ class OnboardingViewModel @Inject constructor( /** Close the calendar step once its confirmation has been read. */ fun finishCalendars() { viewModelScope.launch { - prefs.setOnboardingCalendarsDone() + prefs.setOnboardingDone(OnboardingStep.Calendars) _creation.value = null } } @@ -355,7 +320,7 @@ class OnboardingViewModel @Inject constructor( * choice, and so is going off to set up an account and coming back. */ fun skipCalendars() { - viewModelScope.launch { prefs.setOnboardingCalendarsDone() } + viewModelScope.launch { prefs.setOnboardingDone(OnboardingStep.Calendars) } } /** @@ -381,7 +346,7 @@ class OnboardingViewModel @Inject constructor( ) // Immediate feedback: the first backup lands while onboarding runs. BackupScheduler.runNow(context) - prefs.setOnboardingBackupDone() + prefs.setOnboardingDone(OnboardingStep.Backup) } } @@ -395,11 +360,11 @@ class OnboardingViewModel @Inject constructor( /** Close a picker step — the choice itself is saved as it is made. */ fun finishView() { - viewModelScope.launch { prefs.setOnboardingViewDone() } + viewModelScope.launch { prefs.setOnboardingDone(OnboardingStep.View) } } fun finishMonthStyle() { - viewModelScope.launch { prefs.setOnboardingMonthStyleDone() } + viewModelScope.launch { prefs.setOnboardingDone(OnboardingStep.MonthStyle) } } /** Switch one listed calendar on or off, from the hidden-calendars step (#287). */ @@ -436,7 +401,7 @@ class OnboardingViewModel @Inject constructor( /** Close the hidden-calendars step, switched on or left as they were (#287). */ fun finishHiddenCalendars() { viewModelScope.launch { - prefs.setOnboardingHiddenCalendarsDone() + prefs.setOnboardingDone(OnboardingStep.HiddenCalendars) // The error belongs to the attempt, not to the step: stepping back // into it later must not find a refusal nothing has asked for yet. _hiddenWriteFailed.value = false @@ -451,7 +416,7 @@ class OnboardingViewModel @Inject constructor( /** Acknowledge the calendar-visibility notice (#75). */ fun finishVisibility() { viewModelScope.launch { - prefs.setOnboardingVisibilityDone() + prefs.setOnboardingDone(OnboardingStep.Visibility) // Retiring the notice drops its step, so it waits until nothing // follows — the count must not fall on the way to a later screen. if (plan.value?.steps?.last() == OnboardingStep.Visibility) retireVisibilityNotice() @@ -488,36 +453,12 @@ class OnboardingViewModel @Inject constructor( } } -/** The stored answers the plan is derived from. */ -private data class OnboardingFlags( - val remindersDone: Boolean, - val wizardArmed: Boolean, - val backupDone: Boolean, - val viewDone: Boolean, - val monthStyleDone: Boolean, -) - /** How the calendar step's create attempt ended (#287). */ sealed interface CalendarCreation { data class Created(val name: String) : CalendarCreation data object Failed : CalendarCreation } -/** Both calendar steps' inputs (#287). */ -private data class CalendarsFlags( - val applies: Boolean?, - val done: Boolean, - val hiddenApplies: Boolean?, - val hiddenDone: Boolean, -) - -/** The tail of the flow: the visibility notice and the closing screen. */ -private data class ClosingFlags( - val visibilityArmed: Boolean, - val visibilityDone: Boolean, - val doneShown: Boolean, -) - /** What the view step starts from, and renders its previews with. */ data class ViewChoice( val defaultView: CalendarView, diff --git a/app/src/main/java/de/jeanlucmakiola/calendula/ui/onboarding/PermissionScreen.kt b/app/src/main/java/de/jeanlucmakiola/calendula/ui/onboarding/PermissionScreen.kt index da7d022b..7df5f0a4 100644 --- a/app/src/main/java/de/jeanlucmakiola/calendula/ui/onboarding/PermissionScreen.kt +++ b/app/src/main/java/de/jeanlucmakiola/calendula/ui/onboarding/PermissionScreen.kt @@ -1,6 +1,7 @@ package de.jeanlucmakiola.calendula.ui.onboarding import de.jeanlucmakiola.floret.components.BenefitRow +import de.jeanlucmakiola.floret.components.OnboardingPrimaryButton import de.jeanlucmakiola.floret.components.OnboardingScaffold import de.jeanlucmakiola.floret.components.OnboardingSpace @@ -13,28 +14,20 @@ import androidx.activity.result.contract.ActivityResultContracts import androidx.compose.foundation.layout.Spacer import androidx.compose.foundation.layout.fillMaxWidth import androidx.compose.foundation.layout.height -import androidx.compose.foundation.layout.size -import androidx.compose.foundation.layout.width import androidx.compose.material.icons.Icons import androidx.compose.material.icons.automirrored.filled.ArrowForward import androidx.compose.material.icons.filled.CalendarMonth import androidx.compose.material.icons.filled.Lock -import androidx.compose.material3.Button -import androidx.compose.material3.ButtonDefaults -import androidx.compose.material3.Icon -import androidx.compose.material3.MaterialTheme import androidx.compose.material3.Text import androidx.compose.material3.TextButton import androidx.compose.runtime.Composable -import androidx.compose.runtime.LaunchedEffect +import androidx.compose.runtime.mutableStateOf import androidx.compose.runtime.getValue +import androidx.compose.runtime.saveable.rememberSaveable +import androidx.compose.runtime.setValue import androidx.compose.ui.Modifier import androidx.compose.ui.platform.LocalContext import androidx.compose.ui.res.stringResource -import androidx.compose.ui.text.style.TextAlign -import androidx.compose.ui.unit.dp -import androidx.hilt.navigation.compose.hiltViewModel -import androidx.lifecycle.compose.collectAsStateWithLifecycle import de.jeanlucmakiola.calendula.R private val CALENDAR_PERMISSIONS = arrayOf( @@ -47,9 +40,8 @@ fun PermissionScreen( onGranted: () -> Unit, modifier: Modifier = Modifier, progress: (@Composable () -> Unit)? = null, - viewModel: PermissionViewModel = hiltViewModel(), ) { - val state by viewModel.state.collectAsStateWithLifecycle() + var denied by rememberSaveable { mutableStateOf(false) } // READ and WRITE are requested together (one system dialog — same // permission group), but only READ gates the app: declining write keeps @@ -58,33 +50,27 @@ fun PermissionScreen( contract = ActivityResultContracts.RequestMultiplePermissions(), ) { results -> if (results[Manifest.permission.READ_CALENDAR] == true) { - viewModel.onGranted() + onGranted() } else { - viewModel.onDenied() + denied = true } } - LaunchedEffect(state) { - if (state == PermissionUiState.Granted) onGranted() - } - - when (state) { - is PermissionUiState.Rationale -> RationaleContent( - onRequest = { launcher.launch(CALENDAR_PERMISSIONS) }, - progress = progress, - modifier = modifier, - ) - is PermissionUiState.Denied -> DeniedContent( + if (denied) { + DeniedContent( onRetry = { - viewModel.onRetry() + denied = false launcher.launch(CALENDAR_PERMISSIONS) }, progress = progress, modifier = modifier, ) - is PermissionUiState.Granted -> { - // Transient — LaunchedEffect above fires and parent replaces us. - } + } else { + RationaleContent( + onRequest = { launcher.launch(CALENDAR_PERMISSIONS) }, + progress = progress, + modifier = modifier, + ) } } @@ -100,37 +86,15 @@ private fun RationaleContent( topSpacing = OnboardingSpace.lg, hero = { BrandHero() }, actions = { - Button( + OnboardingPrimaryButton( + text = stringResource(R.string.permission_request_button), onClick = onRequest, - modifier = Modifier.fillMaxWidth().height(56.dp), - contentPadding = ButtonDefaults.ButtonWithIconContentPadding, - ) { - Text( - text = stringResource(R.string.permission_request_button), - style = MaterialTheme.typography.titleMedium, - ) - Spacer(Modifier.width(OnboardingSpace.xs)) - Icon( - imageVector = Icons.AutoMirrored.Filled.ArrowForward, - contentDescription = null, - modifier = Modifier.size(20.dp), - ) - } + trailingIcon = Icons.AutoMirrored.Filled.ArrowForward, + ) }, + headline = stringResource(R.string.permission_rationale_title), + supporting = stringResource(R.string.permission_rationale_body), ) { - Text( - text = stringResource(R.string.permission_rationale_title), - style = MaterialTheme.typography.headlineMedium, - textAlign = TextAlign.Center, - ) - Spacer(Modifier.height(12.dp)) - Text( - text = stringResource(R.string.permission_rationale_body), - style = MaterialTheme.typography.bodyLarge, - color = MaterialTheme.colorScheme.onSurfaceVariant, - textAlign = TextAlign.Center, - ) - Spacer(Modifier.height(OnboardingSpace.lg)) BenefitRow( @@ -159,7 +123,8 @@ private fun DeniedContent( progress = progress, hero = { BrandHero(HeroBadge.Denied) }, actions = { - Button( + OnboardingPrimaryButton( + text = stringResource(R.string.permission_open_settings_button), onClick = { val intent = Intent(Settings.ACTION_APPLICATION_DETAILS_SETTINGS).apply { data = Uri.fromParts("package", context.packageName, null) @@ -167,13 +132,7 @@ private fun DeniedContent( } context.startActivity(intent) }, - modifier = Modifier.fillMaxWidth().height(56.dp), - ) { - Text( - text = stringResource(R.string.permission_open_settings_button), - style = MaterialTheme.typography.titleMedium, - ) - } + ) TextButton( onClick = onRetry, modifier = Modifier.fillMaxWidth(), @@ -181,18 +140,7 @@ private fun DeniedContent( Text(stringResource(R.string.permission_retry_button)) } }, - ) { - Text( - text = stringResource(R.string.permission_denied_title), - style = MaterialTheme.typography.headlineMedium, - textAlign = TextAlign.Center, - ) - Spacer(Modifier.height(12.dp)) - Text( - text = stringResource(R.string.permission_denied_body), - style = MaterialTheme.typography.bodyLarge, - color = MaterialTheme.colorScheme.onSurfaceVariant, - textAlign = TextAlign.Center, - ) - } + headline = stringResource(R.string.permission_denied_title), + supporting = stringResource(R.string.permission_denied_body), + ) } diff --git a/app/src/main/java/de/jeanlucmakiola/calendula/ui/onboarding/PermissionUiState.kt b/app/src/main/java/de/jeanlucmakiola/calendula/ui/onboarding/PermissionUiState.kt deleted file mode 100644 index 49e8cd19..00000000 --- a/app/src/main/java/de/jeanlucmakiola/calendula/ui/onboarding/PermissionUiState.kt +++ /dev/null @@ -1,7 +0,0 @@ -package de.jeanlucmakiola.calendula.ui.onboarding - -sealed interface PermissionUiState { - data object Rationale : PermissionUiState - data object Denied : PermissionUiState - data object Granted : PermissionUiState -} diff --git a/app/src/main/java/de/jeanlucmakiola/calendula/ui/onboarding/PermissionViewModel.kt b/app/src/main/java/de/jeanlucmakiola/calendula/ui/onboarding/PermissionViewModel.kt deleted file mode 100644 index f5a5ac93..00000000 --- a/app/src/main/java/de/jeanlucmakiola/calendula/ui/onboarding/PermissionViewModel.kt +++ /dev/null @@ -1,29 +0,0 @@ -package de.jeanlucmakiola.calendula.ui.onboarding - -import androidx.lifecycle.ViewModel -import dagger.hilt.android.lifecycle.HiltViewModel -import kotlinx.coroutines.flow.MutableStateFlow -import kotlinx.coroutines.flow.StateFlow -import kotlinx.coroutines.flow.asStateFlow -import javax.inject.Inject - -@HiltViewModel -class PermissionViewModel @Inject constructor() : ViewModel() { - - private val _state = MutableStateFlow(PermissionUiState.Rationale) - val state: StateFlow = _state.asStateFlow() - - // The visibility reconcile a grant owes (#75) hangs off RootScreen, which - // also catches grants made outside the app. - fun onGranted() { - _state.value = PermissionUiState.Granted - } - - fun onDenied() { - _state.value = PermissionUiState.Denied - } - - fun onRetry() { - _state.value = PermissionUiState.Rationale - } -} diff --git a/app/src/main/java/de/jeanlucmakiola/calendula/ui/onboarding/ReminderStep.kt b/app/src/main/java/de/jeanlucmakiola/calendula/ui/onboarding/ReminderStep.kt index ef53c5a7..f5f121a9 100644 --- a/app/src/main/java/de/jeanlucmakiola/calendula/ui/onboarding/ReminderStep.kt +++ b/app/src/main/java/de/jeanlucmakiola/calendula/ui/onboarding/ReminderStep.kt @@ -1,6 +1,7 @@ package de.jeanlucmakiola.calendula.ui.onboarding import de.jeanlucmakiola.floret.components.BenefitRow +import de.jeanlucmakiola.floret.components.OnboardingPrimaryButton import de.jeanlucmakiola.floret.components.OnboardingScaffold import de.jeanlucmakiola.floret.components.OnboardingSpace @@ -14,15 +15,11 @@ import androidx.compose.foundation.layout.height import androidx.compose.material.icons.Icons import androidx.compose.material.icons.filled.NotificationsActive import androidx.compose.material.icons.filled.ContentCopy -import androidx.compose.material3.Button -import androidx.compose.material3.MaterialTheme import androidx.compose.material3.Text import androidx.compose.material3.TextButton import androidx.compose.runtime.Composable import androidx.compose.ui.Modifier import androidx.compose.ui.res.stringResource -import androidx.compose.ui.text.style.TextAlign -import androidx.compose.ui.unit.dp import de.jeanlucmakiola.calendula.R /** @@ -53,7 +50,8 @@ fun ReminderStep( topSpacing = OnboardingSpace.lg, hero = { IconHero(Icons.Filled.NotificationsActive) }, actions = { - Button( + OnboardingPrimaryButton( + text = stringResource(R.string.reminder_onboarding_enable_button), onClick = { if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.TIRAMISU) { launcher.launch(Manifest.permission.POST_NOTIFICATIONS) @@ -61,13 +59,7 @@ fun ReminderStep( onFinished(true) } }, - modifier = Modifier.fillMaxWidth().height(56.dp), - ) { - Text( - text = stringResource(R.string.reminder_onboarding_enable_button), - style = MaterialTheme.typography.titleMedium, - ) - } + ) TextButton( onClick = { onFinished(false) }, modifier = Modifier.fillMaxWidth(), @@ -75,20 +67,9 @@ fun ReminderStep( Text(stringResource(R.string.reminder_onboarding_skip_button)) } }, + headline = stringResource(R.string.reminder_onboarding_title), + supporting = stringResource(R.string.reminder_onboarding_body), ) { - Text( - text = stringResource(R.string.reminder_onboarding_title), - style = MaterialTheme.typography.headlineMedium, - textAlign = TextAlign.Center, - ) - Spacer(Modifier.height(12.dp)) - Text( - text = stringResource(R.string.reminder_onboarding_body), - style = MaterialTheme.typography.bodyLarge, - color = MaterialTheme.colorScheme.onSurfaceVariant, - textAlign = TextAlign.Center, - ) - Spacer(Modifier.height(OnboardingSpace.lg)) BenefitRow( diff --git a/app/src/main/java/de/jeanlucmakiola/calendula/ui/onboarding/ViewStep.kt b/app/src/main/java/de/jeanlucmakiola/calendula/ui/onboarding/ViewStep.kt index defdd8b7..1d512e25 100644 --- a/app/src/main/java/de/jeanlucmakiola/calendula/ui/onboarding/ViewStep.kt +++ b/app/src/main/java/de/jeanlucmakiola/calendula/ui/onboarding/ViewStep.kt @@ -19,8 +19,6 @@ import de.jeanlucmakiola.calendula.ui.agenda.AgendaViewPreview import de.jeanlucmakiola.calendula.ui.common.CalendarView import de.jeanlucmakiola.calendula.ui.common.IMPLEMENTED_VIEWS import de.jeanlucmakiola.calendula.ui.common.LocalMultiDayCount -import de.jeanlucmakiola.calendula.ui.common.PickerDescription -import de.jeanlucmakiola.calendula.ui.common.ViewPreviewFrame import de.jeanlucmakiola.calendula.ui.common.icon import de.jeanlucmakiola.calendula.ui.common.label import de.jeanlucmakiola.calendula.ui.month.MonthStylePreview @@ -28,11 +26,12 @@ import de.jeanlucmakiola.calendula.ui.month.MonthViewStyle import de.jeanlucmakiola.calendula.ui.month.descriptionRes import de.jeanlucmakiola.calendula.ui.month.labelRes import de.jeanlucmakiola.calendula.ui.week.WeekViewPreview +import de.jeanlucmakiola.floret.components.GroupedHint import de.jeanlucmakiola.floret.components.GroupedListInset import de.jeanlucmakiola.floret.components.OnboardingScaffold import de.jeanlucmakiola.floret.components.OnboardingSpace import de.jeanlucmakiola.floret.components.GroupedRow -import de.jeanlucmakiola.floret.components.SelectedCheck +import de.jeanlucmakiola.floret.components.ViewPreviewFrame import de.jeanlucmakiola.floret.components.positionOf import de.jeanlucmakiola.floret.locale.currentLocale @@ -77,11 +76,10 @@ internal fun ViewStep( } } IMPLEMENTED_VIEWS.forEachIndexed { index, view -> - val isSelected = view == choice.defaultView GroupedRow( title = view.label(), position = positionOf(index, IMPLEMENTED_VIEWS.size), - selected = isSelected, + checked = view == choice.defaultView, leading = { Icon( imageVector = view.icon, @@ -89,11 +87,6 @@ internal fun ViewStep( tint = MaterialTheme.colorScheme.onSurfaceVariant, ) }, - trailing = if (isSelected) { - { SelectedCheck() } - } else { - null - }, onClick = { onSelect(view) }, ) } @@ -127,18 +120,12 @@ internal fun MonthStyleStep( StepPreview(selected = choice.monthViewStyle) { style -> MonthStylePreview(style = style, weekStart = weekStart, height = PREVIEW_HEIGHT) } - PickerDescription(stringResource(choice.monthViewStyle.descriptionRes)) + GroupedHint(stringResource(choice.monthViewStyle.descriptionRes), verticalPadding = 8.dp) options.forEachIndexed { index, style -> - val isSelected = style == choice.monthViewStyle GroupedRow( title = stringResource(style.labelRes), position = positionOf(index, options.size), - selected = isSelected, - trailing = if (isSelected) { - { SelectedCheck() } - } else { - null - }, + checked = style == choice.monthViewStyle, onClick = { onSelect(style) }, ) } diff --git a/app/src/main/java/de/jeanlucmakiola/calendula/ui/onboarding/VisibilityStep.kt b/app/src/main/java/de/jeanlucmakiola/calendula/ui/onboarding/VisibilityStep.kt index d509766d..54dfe9d7 100644 --- a/app/src/main/java/de/jeanlucmakiola/calendula/ui/onboarding/VisibilityStep.kt +++ b/app/src/main/java/de/jeanlucmakiola/calendula/ui/onboarding/VisibilityStep.kt @@ -1,19 +1,12 @@ package de.jeanlucmakiola.calendula.ui.onboarding -import androidx.compose.foundation.layout.Spacer -import androidx.compose.foundation.layout.fillMaxWidth -import androidx.compose.foundation.layout.height import androidx.compose.material.icons.Icons import androidx.compose.material.icons.filled.VisibilityOff -import androidx.compose.material3.Button -import androidx.compose.material3.MaterialTheme -import androidx.compose.material3.Text import androidx.compose.runtime.Composable import androidx.compose.ui.Modifier import androidx.compose.ui.res.stringResource -import androidx.compose.ui.text.style.TextAlign -import androidx.compose.ui.unit.dp import de.jeanlucmakiola.calendula.R +import de.jeanlucmakiola.floret.components.OnboardingPrimaryButton import de.jeanlucmakiola.floret.components.OnboardingScaffold import de.jeanlucmakiola.floret.components.OnboardingSpace @@ -38,28 +31,12 @@ internal fun VisibilityStep( topSpacing = OnboardingSpace.lg, hero = { IconHero(Icons.Filled.VisibilityOff) }, actions = { - Button( + OnboardingPrimaryButton( + text = stringResource(R.string.onboarding_visibility_button), onClick = onFinished, - modifier = Modifier.fillMaxWidth().height(56.dp), - ) { - Text( - text = stringResource(R.string.onboarding_visibility_button), - style = MaterialTheme.typography.titleMedium, - ) - } + ) }, - ) { - Text( - text = stringResource(R.string.calendars_visibility_notice_title), - style = MaterialTheme.typography.headlineMedium, - textAlign = TextAlign.Center, - ) - Spacer(Modifier.height(12.dp)) - Text( - text = stringResource(R.string.calendars_visibility_notice_message), - style = MaterialTheme.typography.bodyLarge, - color = MaterialTheme.colorScheme.onSurfaceVariant, - textAlign = TextAlign.Center, - ) - } + headline = stringResource(R.string.calendars_visibility_notice_title), + supporting = stringResource(R.string.calendars_visibility_notice_message), + ) } diff --git a/app/src/main/java/de/jeanlucmakiola/calendula/ui/search/SearchScreen.kt b/app/src/main/java/de/jeanlucmakiola/calendula/ui/search/SearchScreen.kt index 84539050..58f39a58 100644 --- a/app/src/main/java/de/jeanlucmakiola/calendula/ui/search/SearchScreen.kt +++ b/app/src/main/java/de/jeanlucmakiola/calendula/ui/search/SearchScreen.kt @@ -1,14 +1,9 @@ package de.jeanlucmakiola.calendula.ui.search -import android.Manifest -import android.content.pm.PackageManager import androidx.activity.compose.BackHandler -import androidx.activity.compose.rememberLauncherForActivityResult -import androidx.activity.result.contract.ActivityResultContracts import androidx.compose.animation.AnimatedContent import androidx.compose.animation.animateColorAsState import androidx.compose.foundation.background -import androidx.compose.foundation.isSystemInDarkTheme import androidx.compose.foundation.layout.Arrangement import androidx.compose.foundation.layout.Box import androidx.compose.foundation.layout.Column @@ -61,7 +56,6 @@ import androidx.compose.ui.focus.FocusRequester import androidx.compose.ui.focus.focusRequester import androidx.compose.ui.graphics.Color import androidx.compose.ui.graphics.vector.ImageVector -import androidx.compose.ui.platform.LocalContext import androidx.compose.ui.platform.LocalSoftwareKeyboardController import androidx.compose.ui.res.pluralStringResource import androidx.compose.ui.res.stringResource @@ -73,7 +67,6 @@ import androidx.compose.ui.text.input.ImeAction import androidx.compose.ui.text.input.KeyboardCapitalization import androidx.compose.ui.text.style.TextAlign import androidx.compose.ui.unit.dp -import androidx.core.content.ContextCompat import androidx.hilt.navigation.compose.hiltViewModel import androidx.lifecycle.compose.collectAsStateWithLifecycle import de.jeanlucmakiola.calendula.R @@ -83,9 +76,11 @@ import de.jeanlucmakiola.calendula.domain.RecurringWriteScope import de.jeanlucmakiola.calendula.domain.SearchHit import de.jeanlucmakiola.calendula.domain.SearchMonth import de.jeanlucmakiola.calendula.domain.isDeclined +import de.jeanlucmakiola.floret.identity.LocalFloretDarkTheme import de.jeanlucmakiola.floret.identity.animateItemMotion import de.jeanlucmakiola.floret.identity.fadeThrough import de.jeanlucmakiola.floret.identity.predictiveBack +import de.jeanlucmakiola.calendula.ui.common.rememberWriteAction import de.jeanlucmakiola.calendula.ui.common.declinedTitle import de.jeanlucmakiola.floret.components.GroupedRow import de.jeanlucmakiola.floret.components.InlineTextField @@ -99,7 +94,6 @@ import de.jeanlucmakiola.calendula.ui.common.EventDimAlpha import de.jeanlucmakiola.calendula.ui.common.LocalSoftenColors import de.jeanlucmakiola.calendula.ui.common.RecurringScopeDialog import de.jeanlucmakiola.calendula.ui.common.eventAccent -import de.jeanlucmakiola.calendula.ui.common.eventFill import de.jeanlucmakiola.calendula.domain.spanFirstDay import de.jeanlucmakiola.calendula.ui.common.LocalUse24HourFormat import de.jeanlucmakiola.calendula.ui.common.timeOfDayFormatter @@ -135,7 +129,6 @@ fun SearchScreen( val deleteState by viewModel.deleteState.collectAsStateWithLifecycle() val focusRequester = remember { FocusRequester() } val keyboard = LocalSoftwareKeyboardController.current - val context = LocalContext.current val inSelection = selection.isNotEmpty() var showDeleteDialog by remember { mutableStateOf(false) } @@ -157,27 +150,8 @@ fun SearchScreen( keyboard?.show() } - // Same in-place WRITE_CALENDAR upgrade the detail screen does: a v1.0 install - // holds only READ_CALENDAR, and granting continues into the held delete. - var pendingWrite by remember { mutableStateOf<(() -> Unit)?>(null) } - val writePermissionLauncher = rememberLauncherForActivityResult( - contract = ActivityResultContracts.RequestPermission(), - ) { granted -> - if (granted) pendingWrite?.invoke() - pendingWrite = null - } - val requireWrite: (() -> Unit) -> Unit = { action -> - val granted = ContextCompat.checkSelfPermission( - context, - Manifest.permission.WRITE_CALENDAR, - ) == PackageManager.PERMISSION_GRANTED - if (granted) { - action() - } else { - pendingWrite = action - writePermissionLauncher.launch(Manifest.permission.WRITE_CALENDAR) - } - } + // A v1.0 install holds only READ_CALENDAR; granting continues into the held delete. + val onDeleteClick = rememberWriteAction { showDeleteDialog = true } // Back leaves selection mode before it leaves the screen, and without the // predictive-back scale-out — that would read as search closing and snapping @@ -198,7 +172,7 @@ fun SearchScreen( onBack = onBack, onCloseSelection = viewModel::clearSelection, onSelectAll = viewModel::selectAll, - onDelete = { requireWrite { showDeleteDialog = true } }, + onDelete = onDeleteClick, ) }, ) { padding -> @@ -513,7 +487,7 @@ private fun SearchResultRow( // Spans are empty for a blank title — the query never matches the // placeholder — so marking the substitute is safe. val title = event.title.ifBlank { stringResource(R.string.event_untitled) } - val dark = isSystemInDarkTheme() + val dark = LocalFloretDarkTheme.current val soften = LocalSoftenColors.current // On a picked row the headline is already recoloured for the secondary // container, so the match is carried by weight alone there. diff --git a/app/src/main/java/de/jeanlucmakiola/calendula/ui/search/SearchViewModel.kt b/app/src/main/java/de/jeanlucmakiola/calendula/ui/search/SearchViewModel.kt index d410f74d..858e3c05 100644 --- a/app/src/main/java/de/jeanlucmakiola/calendula/ui/search/SearchViewModel.kt +++ b/app/src/main/java/de/jeanlucmakiola/calendula/ui/search/SearchViewModel.kt @@ -4,17 +4,18 @@ import androidx.lifecycle.ViewModel import androidx.lifecycle.viewModelScope import dagger.hilt.android.lifecycle.HiltViewModel import de.jeanlucmakiola.calendula.data.calendar.CalendarRepository -import de.jeanlucmakiola.calendula.data.di.IoDispatcher import de.jeanlucmakiola.calendula.domain.EventInstance import de.jeanlucmakiola.calendula.domain.EventSearch import de.jeanlucmakiola.calendula.domain.RecurringWriteScope +import de.jeanlucmakiola.calendula.ui.common.deleteEvent import de.jeanlucmakiola.calendula.domain.SearchResults +import de.jeanlucmakiola.floret.android.stateWhileSubscribed +import de.jeanlucmakiola.floret.di.IoDispatcher import kotlinx.coroutines.CancellationException import kotlinx.coroutines.CoroutineDispatcher import kotlinx.coroutines.ExperimentalCoroutinesApi import kotlinx.coroutines.FlowPreview import kotlinx.coroutines.flow.MutableStateFlow -import kotlinx.coroutines.flow.SharingStarted import kotlinx.coroutines.flow.StateFlow import kotlinx.coroutines.flow.asStateFlow import kotlinx.coroutines.flow.catch @@ -25,7 +26,6 @@ import kotlinx.coroutines.flow.first import kotlinx.coroutines.flow.flowOn import kotlinx.coroutines.flow.map import kotlinx.coroutines.flow.mapLatest -import kotlinx.coroutines.flow.stateIn import kotlinx.coroutines.launch import kotlinx.coroutines.withContext import kotlinx.datetime.TimeZone @@ -120,7 +120,7 @@ class SearchViewModel @Inject constructor( } .catch { emit(SearchUiState.Idle) } .flowOn(io) - .stateIn(viewModelScope, SharingStarted.WhileSubscribed(5_000L), SearchUiState.Idle) + .stateWhileSubscribed(viewModelScope, SearchUiState.Idle) fun setQuery(value: String) { if (value != _query.value) _selection.value = emptySet() @@ -197,15 +197,11 @@ class SearchViewModel @Inject constructor( } private suspend fun deleteOne(event: EventInstance, scope: RecurringWriteScope) { - val begin = event.start.toEpochMilliseconds() - when { - !event.isRecurring -> repository.deleteEvent(event.eventId) - scope == RecurringWriteScope.ThisEvent -> - repository.deleteOccurrence(event.eventId, begin) - scope == RecurringWriteScope.ThisAndFollowing -> - repository.deleteEventFromOccurrence(event.eventId, begin) - else -> repository.deleteEvent(event.eventId) - } + repository.deleteEvent( + eventId = event.eventId, + beginMillis = event.start.toEpochMilliseconds(), + scope = if (event.isRecurring) scope else RecurringWriteScope.AllEvents, + ) } private suspend fun readOnlyCalendarIds(): Set = diff --git a/app/src/main/java/de/jeanlucmakiola/calendula/ui/settings/AppearanceSettings.kt b/app/src/main/java/de/jeanlucmakiola/calendula/ui/settings/AppearanceSettings.kt index 5774e5a8..a7618033 100644 --- a/app/src/main/java/de/jeanlucmakiola/calendula/ui/settings/AppearanceSettings.kt +++ b/app/src/main/java/de/jeanlucmakiola/calendula/ui/settings/AppearanceSettings.kt @@ -49,20 +49,20 @@ import androidx.compose.ui.unit.dp import androidx.lifecycle.compose.collectAsStateWithLifecycle import de.jeanlucmakiola.calendula.R import de.jeanlucmakiola.calendula.data.appname.LauncherName -import de.jeanlucmakiola.calendula.data.prefs.ThemeMode +import de.jeanlucmakiola.floret.prefs.ThemeMode import de.jeanlucmakiola.calendula.domain.FontRole -import de.jeanlucmakiola.calendula.ui.common.PickerDescription import de.jeanlucmakiola.calendula.ui.theme.BundledFont import de.jeanlucmakiola.calendula.ui.theme.FONT_CUSTOM_TOKEN import de.jeanlucmakiola.calendula.ui.theme.FONT_SYSTEM_TOKEN import de.jeanlucmakiola.calendula.ui.theme.resolveFontFamily import de.jeanlucmakiola.floret.components.CollapsingScaffold import de.jeanlucmakiola.floret.components.FullScreenPicker +import de.jeanlucmakiola.floret.components.GroupedHint import de.jeanlucmakiola.floret.components.GroupedListInset import de.jeanlucmakiola.floret.components.GroupedRow +import de.jeanlucmakiola.floret.components.GroupedSwitchRow import de.jeanlucmakiola.floret.components.OptionPicker import de.jeanlucmakiola.floret.components.Position -import de.jeanlucmakiola.floret.components.SelectedCheck import de.jeanlucmakiola.floret.components.positionOf /** @@ -127,17 +127,12 @@ internal fun AppearanceScreen( null }, ) - GroupedRow( + GroupedSwitchRow( title = stringResource(R.string.settings_soften_colors), + checked = state.softenColors, + onCheckedChange = viewModel::setSoftenColors, summary = stringResource(R.string.settings_soften_colors_summary), position = Position.Bottom, - trailing = { - Switch( - checked = state.softenColors, - onCheckedChange = viewModel::setSoftenColors, - ) - }, - onClick = { viewModel.setSoftenColors(!state.softenColors) }, ) Spacer(Modifier.height(16.dp)) @@ -209,19 +204,19 @@ internal fun AppearanceScreen( val systemDark = isSystemInDarkTheme() OptionPicker( title = stringResource(R.string.settings_theme), - header = { PickerDescription(stringResource(R.string.settings_theme_hint)) }, + header = { GroupedHint(stringResource(R.string.settings_theme_hint), verticalPadding = 8.dp) }, predictiveBack = true, options = ThemeMode.entries, selected = state.themeMode, label = { themeLabel(it) }, summary = { mode -> - if (mode == ThemeMode.SYSTEM) { - stringResource( + when (mode) { + ThemeMode.SYSTEM -> stringResource( R.string.settings_theme_system_summary, themeLabel(if (systemDark) ThemeMode.DARK else ThemeMode.LIGHT), ) - } else { - null + ThemeMode.BLACK -> stringResource(R.string.settings_theme_black_summary) + ThemeMode.LIGHT, ThemeMode.DARK -> null } }, onSelect = viewModel::setThemeMode, @@ -258,6 +253,7 @@ private fun themeLabel(mode: ThemeMode): String = stringResource( ThemeMode.SYSTEM -> R.string.settings_theme_system ThemeMode.LIGHT -> R.string.settings_theme_light ThemeMode.DARK -> R.string.settings_theme_dark + ThemeMode.BLACK -> R.string.settings_theme_black }, ) @@ -406,7 +402,7 @@ private fun FontOptionRow( GroupedRow( title = label, position = position, - selected = selected, + checked = selected, leading = { if (preview != null) { Text( @@ -418,11 +414,6 @@ private fun FontOptionRow( Icon(imageVector = leadingIcon, contentDescription = null) } }, - trailing = if (selected) { - { SelectedCheck() } - } else { - null - }, onClick = onClick, ) } diff --git a/app/src/main/java/de/jeanlucmakiola/calendula/ui/settings/EventFormSettings.kt b/app/src/main/java/de/jeanlucmakiola/calendula/ui/settings/EventFormSettings.kt index f7d0b393..590a0085 100644 --- a/app/src/main/java/de/jeanlucmakiola/calendula/ui/settings/EventFormSettings.kt +++ b/app/src/main/java/de/jeanlucmakiola/calendula/ui/settings/EventFormSettings.kt @@ -5,13 +5,10 @@ import androidx.compose.foundation.layout.Column import androidx.compose.foundation.layout.Spacer import androidx.compose.foundation.layout.height import androidx.compose.material.icons.Icons -import androidx.compose.material.icons.filled.ExpandLess -import androidx.compose.material.icons.filled.ExpandMore import androidx.compose.material.icons.filled.Keyboard import androidx.compose.material.icons.filled.Schedule import androidx.compose.material3.Icon import androidx.compose.material3.MaterialTheme -import androidx.compose.material3.Switch import androidx.compose.runtime.Composable import androidx.compose.runtime.getValue import androidx.compose.runtime.mutableStateOf @@ -28,8 +25,12 @@ import de.jeanlucmakiola.calendula.ui.common.DurationPicker import de.jeanlucmakiola.calendula.ui.common.durationLabel import de.jeanlucmakiola.calendula.ui.common.eventFormFieldIcon import de.jeanlucmakiola.calendula.ui.common.eventFormFieldLabel +import de.jeanlucmakiola.calendula.ui.common.orUnnamed import de.jeanlucmakiola.floret.components.CollapsingScaffold +import de.jeanlucmakiola.floret.components.ExpandIcon +import de.jeanlucmakiola.floret.components.GroupedHint import de.jeanlucmakiola.floret.components.GroupedRow +import de.jeanlucmakiola.floret.components.GroupedSwitchRow import de.jeanlucmakiola.floret.components.Position import de.jeanlucmakiola.floret.components.positionOf import de.jeanlucmakiola.floret.identity.collapseExit @@ -56,13 +57,15 @@ internal fun EventFormScreen( predictiveBack = true, visible = visible, ) { - SettingsHint(stringResource(R.string.settings_form_fields_hint)) + GroupedHint(stringResource(R.string.settings_form_fields_hint)) Spacer(Modifier.height(8.dp)) val fields = EventFormField.entries fields.forEachIndexed { index, field -> val checked = field in state.defaultFormFields - GroupedRow( + GroupedSwitchRow( title = stringResource(eventFormFieldLabel(field)), + checked = checked, + onCheckedChange = { viewModel.setFormFieldDefault(field, it) }, position = positionOf(index, fields.size), // The same icon the field carries in the new-event form. leading = { @@ -72,20 +75,15 @@ internal fun EventFormScreen( tint = MaterialTheme.colorScheme.onSurfaceVariant, ) }, - trailing = { - Switch( - checked = checked, - onCheckedChange = { viewModel.setFormFieldDefault(field, it) }, - ) - }, - onClick = { viewModel.setFormFieldDefault(field, !checked) }, ) } // Auto-focus the title on a new event (#10), on by default. Spacer(Modifier.height(24.dp)) - GroupedRow( + GroupedSwitchRow( title = stringResource(R.string.settings_autofocus_title), + checked = state.autofocusEventTitle, + onCheckedChange = { viewModel.setAutofocusEventTitle(it) }, summary = stringResource(R.string.settings_autofocus_title_hint), position = Position.Alone, leading = { @@ -95,13 +93,6 @@ internal fun EventFormScreen( tint = MaterialTheme.colorScheme.onSurfaceVariant, ) }, - trailing = { - Switch( - checked = state.autofocusEventTitle, - onCheckedChange = { viewModel.setAutofocusEventTitle(it) }, - ) - }, - onClick = { viewModel.setAutofocusEventTitle(!state.autofocusEventTitle) }, ) // How long a new timed event opens (#54), globally and per calendar — @@ -127,13 +118,7 @@ internal fun EventFormScreen( // Expanded, the header opens the calendar run below it and the // two read as one container (the shared expand pattern). position = if (durationSectionExpanded) Position.Top else Position.Bottom, - trailing = { - Icon( - imageVector = if (durationSectionExpanded) Icons.Default.ExpandLess else Icons.Default.ExpandMore, - contentDescription = null, - tint = MaterialTheme.colorScheme.onSurfaceVariant, - ) - }, + trailing = { ExpandIcon(durationSectionExpanded) }, onClick = { durationSectionExpanded = !durationSectionExpanded }, ) AnimatedVisibility( @@ -145,7 +130,7 @@ internal fun EventFormScreen( durationCalendars.forEachIndexed { index, calendar -> val override = state.perCalendarEventDuration[calendar.id] GroupedRow( - title = calendar.displayName.ifBlank { stringResource(R.string.calendar_unnamed) }, + title = calendar.displayName.orUnnamed(), summary = override?.let { durationLabel(it) } ?: stringResource( R.string.settings_calendar_duration_inherits, @@ -165,21 +150,12 @@ internal fun EventFormScreen( // Per-event colour on calendars that publish no colour set (some // CalDAV); off by default, since it may not survive their next sync. Spacer(Modifier.height(24.dp)) - GroupedRow( + GroupedSwitchRow( title = stringResource(R.string.settings_color_unsupported), + checked = state.allowColorOnUnsupportedCalendars, + onCheckedChange = { viewModel.setAllowColorOnUnsupportedCalendars(it) }, summary = stringResource(R.string.settings_color_unsupported_hint), position = Position.Alone, - trailing = { - Switch( - checked = state.allowColorOnUnsupportedCalendars, - onCheckedChange = { viewModel.setAllowColorOnUnsupportedCalendars(it) }, - ) - }, - onClick = { - viewModel.setAllowColorOnUnsupportedCalendars( - !state.allowColorOnUnsupportedCalendars, - ) - }, ) } diff --git a/app/src/main/java/de/jeanlucmakiola/calendula/ui/settings/MonthViewStylePicker.kt b/app/src/main/java/de/jeanlucmakiola/calendula/ui/settings/MonthViewStylePicker.kt index 4fd79864..c780a73d 100644 --- a/app/src/main/java/de/jeanlucmakiola/calendula/ui/settings/MonthViewStylePicker.kt +++ b/app/src/main/java/de/jeanlucmakiola/calendula/ui/settings/MonthViewStylePicker.kt @@ -6,16 +6,14 @@ import androidx.compose.ui.Modifier import androidx.compose.ui.res.stringResource import androidx.compose.ui.unit.dp import de.jeanlucmakiola.calendula.R -import de.jeanlucmakiola.calendula.ui.common.PickerDescription -import de.jeanlucmakiola.calendula.ui.common.ViewPreviewFrame import de.jeanlucmakiola.calendula.ui.month.MonthStylePreview import de.jeanlucmakiola.calendula.ui.month.MonthViewStyle import de.jeanlucmakiola.calendula.ui.month.descriptionRes import de.jeanlucmakiola.calendula.ui.month.labelRes import de.jeanlucmakiola.floret.components.FullScreenPicker -import de.jeanlucmakiola.floret.components.GroupedRow -import de.jeanlucmakiola.floret.components.SelectedCheck -import de.jeanlucmakiola.floret.components.positionOf +import de.jeanlucmakiola.floret.components.GroupedHint +import de.jeanlucmakiola.floret.components.OptionRows +import de.jeanlucmakiola.floret.components.ViewPreviewFrame import kotlinx.datetime.DayOfWeek /** @@ -29,7 +27,7 @@ import kotlinx.datetime.DayOfWeek * * Under the preview sits the selected style's own one-line blurb, then the * family's standard picker shape: connected single-line grouped rows with a - * tonal highlight and [SelectedCheck] on the current one. + * tonal highlight and a check on the current one. */ @Composable internal fun MonthViewStylePicker( @@ -58,23 +56,15 @@ internal fun MonthViewStylePicker( // The selected style's own blurb lives here, under its preview, rather // than on every row — the rows stay single-line and dense, and the words // describe exactly what is being shown above. - PickerDescription(stringResource(selected.descriptionRes)) - options.forEachIndexed { index, style -> - val isSelected = style == selected - GroupedRow( - title = stringResource(style.labelRes), - position = positionOf(index, options.size), - selected = isSelected, - trailing = if (isSelected) { - { SelectedCheck() } - } else { - null - }, - // Applies straight away; the preview above is the confirmation, - // so there is nothing to dismiss for. - onClick = { onSelect(style) }, - ) - } + GroupedHint(stringResource(selected.descriptionRes), verticalPadding = 8.dp) + // Applies straight away; the preview above is the confirmation, so + // there is nothing to dismiss for. + OptionRows( + options = options, + selected = selected, + label = { stringResource(it.labelRes) }, + onSelect = onSelect, + ) } } diff --git a/app/src/main/java/de/jeanlucmakiola/calendula/ui/settings/NotificationSettings.kt b/app/src/main/java/de/jeanlucmakiola/calendula/ui/settings/NotificationSettings.kt index 7fe559f0..b6fd7b28 100644 --- a/app/src/main/java/de/jeanlucmakiola/calendula/ui/settings/NotificationSettings.kt +++ b/app/src/main/java/de/jeanlucmakiola/calendula/ui/settings/NotificationSettings.kt @@ -3,7 +3,6 @@ package de.jeanlucmakiola.calendula.ui.settings import android.Manifest import android.content.Context import android.content.Intent -import android.content.pm.PackageManager import android.os.Build import android.os.PowerManager import android.provider.Settings @@ -15,11 +14,8 @@ import androidx.compose.foundation.layout.Spacer import androidx.compose.foundation.layout.height import androidx.compose.material.icons.Icons import androidx.compose.material.icons.automirrored.filled.KeyboardArrowRight -import androidx.compose.material.icons.filled.ExpandLess -import androidx.compose.material.icons.filled.ExpandMore import androidx.compose.material3.Icon import androidx.compose.material3.MaterialTheme -import androidx.compose.material3.Switch import androidx.compose.runtime.Composable import androidx.compose.runtime.DisposableEffect import androidx.compose.runtime.getValue @@ -30,7 +26,6 @@ import androidx.compose.ui.Modifier import androidx.compose.ui.platform.LocalContext import androidx.compose.ui.res.stringResource import androidx.compose.ui.unit.dp -import androidx.core.content.ContextCompat import androidx.core.net.toUri import androidx.lifecycle.Lifecycle import androidx.lifecycle.LifecycleEventObserver @@ -42,13 +37,18 @@ import de.jeanlucmakiola.calendula.ui.common.REMINDER_PRESETS import de.jeanlucmakiola.calendula.ui.common.ReminderDefaultPicker import de.jeanlucmakiola.calendula.ui.common.TimePickerAlert import de.jeanlucmakiola.calendula.ui.common.durationLabel +import de.jeanlucmakiola.calendula.ui.common.orUnnamed +import de.jeanlucmakiola.floret.android.hasPermission import de.jeanlucmakiola.floret.components.CollapsingScaffold +import de.jeanlucmakiola.floret.components.ExpandIcon import de.jeanlucmakiola.floret.components.GroupedRow +import de.jeanlucmakiola.floret.components.GroupedSwitchRow import de.jeanlucmakiola.floret.components.Position import de.jeanlucmakiola.floret.components.SelectedCheck import de.jeanlucmakiola.floret.identity.collapseExit import de.jeanlucmakiola.floret.identity.expandEnter import de.jeanlucmakiola.floret.reminders.ReminderOverride +import de.jeanlucmakiola.floret.reminders.minutesOrEmpty import de.jeanlucmakiola.floret.reminders.reminderOverrideFor import kotlinx.datetime.LocalTime @@ -73,9 +73,7 @@ internal fun NotificationsScreen( viewModel.setRemindersEnabled(enabled) val needsPermission = enabled && Build.VERSION.SDK_INT >= Build.VERSION_CODES.TIRAMISU && - ContextCompat.checkSelfPermission( - context, Manifest.permission.POST_NOTIFICATIONS, - ) != PackageManager.PERMISSION_GRANTED + !context.hasPermission(Manifest.permission.POST_NOTIFICATIONS) if (needsPermission) { launcher.launch(Manifest.permission.POST_NOTIFICATIONS) } @@ -95,14 +93,12 @@ internal fun NotificationsScreen( predictiveBack = true, visible = visible, ) { - GroupedRow( + GroupedSwitchRow( title = stringResource(R.string.settings_reminders), + checked = state.remindersEnabled, + onCheckedChange = toggleReminders, summary = stringResource(R.string.settings_reminders_hint), position = Position.Top, - trailing = { - Switch(checked = state.remindersEnabled, onCheckedChange = toggleReminders) - }, - onClick = { toggleReminders(!state.remindersEnabled) }, ) GroupedRow( title = stringResource(R.string.settings_default_reminder), @@ -162,13 +158,7 @@ internal fun NotificationsScreen( title = stringResource(R.string.settings_calendar_reminders_title), summary = stringResource(R.string.settings_calendar_reminders_hint), position = Position.Alone, - trailing = { - Icon( - imageVector = if (calendarSectionExpanded) Icons.Default.ExpandLess else Icons.Default.ExpandMore, - contentDescription = null, - tint = MaterialTheme.colorScheme.onSurfaceVariant, - ) - }, + trailing = { ExpandIcon(calendarSectionExpanded) }, onClick = { calendarSectionExpanded = !calendarSectionExpanded }, ) AnimatedVisibility( @@ -183,7 +173,7 @@ internal fun NotificationsScreen( // own section — link there instead. if (calendar.id in state.managedCalendarIds) { GroupedRow( - title = calendar.displayName.ifBlank { stringResource(R.string.calendar_unnamed) }, + title = calendar.displayName.orUnnamed(), summary = stringResource(R.string.settings_calendar_reminders_managed_hint), position = Position.Alone, leading = { CalendarColorChip(calendar.color) }, @@ -200,16 +190,10 @@ internal fun NotificationsScreen( } val expanded = calendar.id in expandedCalendars GroupedRow( - title = calendar.displayName.ifBlank { stringResource(R.string.calendar_unnamed) }, + title = calendar.displayName.orUnnamed(), position = if (expanded) Position.Top else Position.Alone, leading = { CalendarColorChip(calendar.color) }, - trailing = { - Icon( - imageVector = if (expanded) Icons.Default.ExpandLess else Icons.Default.ExpandMore, - contentDescription = null, - tint = MaterialTheme.colorScheme.onSurfaceVariant, - ) - }, + trailing = { ExpandIcon(expanded) }, onClick = { expandedCalendars = if (expanded) { expandedCalendars - calendar.id @@ -263,7 +247,7 @@ internal fun NotificationsScreen( presets = REMINDER_PRESETS, selected = state.defaultReminderMinutes.toReminderChoice(), allowInherit = false, - onSelect = { viewModel.setDefaultReminderMinutes(it.toMinutesList()) }, + onSelect = { viewModel.setDefaultReminderMinutes(it.minutesOrEmpty()) }, onDismiss = { showDefaultReminder = false }, ) } @@ -273,7 +257,7 @@ internal fun NotificationsScreen( presets = ALLDAY_REMINDER_PRESETS, selected = state.defaultAllDayReminderMinutes.toReminderChoice(), allowInherit = false, - onSelect = { viewModel.setDefaultAllDayReminderMinutes(it.toMinutesList()) }, + onSelect = { viewModel.setDefaultAllDayReminderMinutes(it.minutesOrEmpty()) }, onDismiss = { showAllDayReminder = false }, leadTimeSummary = allDayFiringTimeSummary(state.allDayReminderTimeMinutes), ) @@ -332,10 +316,6 @@ private data class OverrideTarget(val calendarId: Long, val isAllDay: Boolean) private fun List.toReminderChoice(): ReminderOverride = if (isEmpty()) ReminderOverride.None else ReminderOverride.Minutes(this) -/** A picked choice as global-default minutes (Inherit isn't offered for globals). */ -private fun ReminderOverride.toMinutesList(): List = - (this as? ReminderOverride.Minutes)?.minutes ?: emptyList() - /** Row summary for a calendar: its override, or the inherited global default. */ @Composable private fun calendarOverrideSummary( diff --git a/app/src/main/java/de/jeanlucmakiola/calendula/ui/settings/PastEventsPicker.kt b/app/src/main/java/de/jeanlucmakiola/calendula/ui/settings/PastEventsPicker.kt index 4b34acb4..33b9fa39 100644 --- a/app/src/main/java/de/jeanlucmakiola/calendula/ui/settings/PastEventsPicker.kt +++ b/app/src/main/java/de/jeanlucmakiola/calendula/ui/settings/PastEventsPicker.kt @@ -27,10 +27,9 @@ import de.jeanlucmakiola.calendula.data.prefs.PastEventDisplay import de.jeanlucmakiola.calendula.domain.EventInstance import de.jeanlucmakiola.calendula.ui.agenda.AgendaDayHeader import de.jeanlucmakiola.calendula.ui.agenda.AgendaEventRow -import de.jeanlucmakiola.calendula.ui.common.PickerDescription import de.jeanlucmakiola.floret.components.FullScreenPicker -import de.jeanlucmakiola.floret.components.GroupedRow -import de.jeanlucmakiola.floret.components.SelectedCheck +import de.jeanlucmakiola.floret.components.GroupedHint +import de.jeanlucmakiola.floret.components.OptionRows import de.jeanlucmakiola.floret.components.positionOf import de.jeanlucmakiola.floret.identity.rememberReduceMotion import kotlinx.datetime.LocalDate @@ -80,21 +79,13 @@ internal fun PastEventsPicker( } } } - PickerDescription(stringResource(R.string.settings_past_events_hint)) - options.forEachIndexed { index, mode -> - val isSelected = mode == selected - GroupedRow( - title = stringResource(pastEventDisplayLabelRes(mode)), - position = positionOf(index, options.size), - selected = isSelected, - trailing = if (isSelected) { - { SelectedCheck() } - } else { - null - }, - onClick = { onSelect(mode) }, - ) - } + GroupedHint(stringResource(R.string.settings_past_events_hint), verticalPadding = 8.dp) + OptionRows( + options = options, + selected = selected, + label = { stringResource(pastEventDisplayLabelRes(it)) }, + onSelect = onSelect, + ) } } diff --git a/app/src/main/java/de/jeanlucmakiola/calendula/ui/settings/SettingsCommon.kt b/app/src/main/java/de/jeanlucmakiola/calendula/ui/settings/SettingsCommon.kt index ebba6937..746ff28d 100644 --- a/app/src/main/java/de/jeanlucmakiola/calendula/ui/settings/SettingsCommon.kt +++ b/app/src/main/java/de/jeanlucmakiola/calendula/ui/settings/SettingsCommon.kt @@ -4,12 +4,10 @@ import android.content.Context import android.content.Intent import androidx.compose.foundation.background import androidx.compose.foundation.layout.Box -import androidx.compose.foundation.layout.padding import androidx.compose.foundation.layout.size import androidx.compose.foundation.shape.CircleShape import androidx.compose.material3.Icon import androidx.compose.material3.MaterialTheme -import androidx.compose.material3.Text import androidx.compose.runtime.Composable import androidx.compose.ui.Alignment import androidx.compose.ui.Modifier @@ -22,7 +20,6 @@ import de.jeanlucmakiola.calendula.R import de.jeanlucmakiola.calendula.ui.common.LocalUse24HourFormat import de.jeanlucmakiola.calendula.ui.common.formatMinuteOfDay import de.jeanlucmakiola.calendula.ui.common.reminderLeadTimeLabel -import de.jeanlucmakiola.floret.components.GroupedListInset import de.jeanlucmakiola.floret.locale.currentLocale /** @@ -63,36 +60,6 @@ internal fun CategoryIcon(icon: ImageVector, accent: ChipAccent) { } } -/** - * A small primary-coloured group label, matching the Calendars settings screen. - * Inset to [GroupedListInset] so it shares the cards' left margin. - */ -@Composable -internal fun SectionHeader(text: String) { - Text( - text = text, - style = MaterialTheme.typography.labelLarge, - color = MaterialTheme.colorScheme.primary, - modifier = Modifier.padding( - start = GroupedListInset, - end = GroupedListInset, - top = 16.dp, - bottom = 4.dp, - ), - ) -} - -/** Muted supporting text under a [SectionHeader], matching the form-fields hint. */ -@Composable -internal fun SettingsHint(text: String) { - Text( - text = text, - style = MaterialTheme.typography.bodyMedium, - color = MaterialTheme.colorScheme.onSurfaceVariant, - modifier = Modifier.padding(horizontal = GroupedListInset, vertical = 4.dp), - ) -} - internal fun openUrl(context: Context, url: String) { val intent = Intent(Intent.ACTION_VIEW, url.toUri()) runCatching { context.startActivity(intent) } diff --git a/app/src/main/java/de/jeanlucmakiola/calendula/ui/settings/SettingsScreen.kt b/app/src/main/java/de/jeanlucmakiola/calendula/ui/settings/SettingsScreen.kt index b53ee699..756dbe0a 100644 --- a/app/src/main/java/de/jeanlucmakiola/calendula/ui/settings/SettingsScreen.kt +++ b/app/src/main/java/de/jeanlucmakiola/calendula/ui/settings/SettingsScreen.kt @@ -61,14 +61,14 @@ import de.jeanlucmakiola.floret.components.CollapsingScaffold import de.jeanlucmakiola.floret.components.FullScreenPicker import de.jeanlucmakiola.floret.components.GroupedListInset import de.jeanlucmakiola.floret.components.GroupedRow -import de.jeanlucmakiola.floret.components.OptionPicker +import de.jeanlucmakiola.floret.components.GroupedSectionHeader +import de.jeanlucmakiola.floret.components.LanguagePickerRow import de.jeanlucmakiola.floret.components.Position import de.jeanlucmakiola.floret.crash.CrashReportDialog import de.jeanlucmakiola.floret.crash.CrashReporter import de.jeanlucmakiola.floret.crash.openIssueTracker import de.jeanlucmakiola.floret.crash.submitCrashReport import de.jeanlucmakiola.floret.identity.predictiveBackExit -import de.jeanlucmakiola.floret.locale.AppLanguage /** The settings sub-screens reached from the hub's category rows. */ private enum class SettingsSection { @@ -193,7 +193,7 @@ private fun SettingsHub( // Each group cycles its chip accents so no two rows in it look alike // (see [ChipAccent]). - SectionHeader(stringResource(R.string.settings_group_look)) + GroupedSectionHeader(stringResource(R.string.settings_group_look)) GroupedRow( title = stringResource(R.string.settings_section_appearance), summary = stringResource(R.string.settings_appearance_subtitle), @@ -224,7 +224,7 @@ private fun SettingsHub( ) Spacer(Modifier.height(8.dp)) - SectionHeader(stringResource(R.string.settings_group_data)) + GroupedSectionHeader(stringResource(R.string.settings_group_data)) GroupedRow( title = stringResource(R.string.settings_section_calendars), summary = stringResource(R.string.settings_manage_calendars_hint), @@ -250,7 +250,7 @@ private fun SettingsHub( ) Spacer(Modifier.height(8.dp)) - SectionHeader(stringResource(R.string.settings_group_app)) + GroupedSectionHeader(stringResource(R.string.settings_group_app)) GroupedRow( title = stringResource(R.string.settings_section_widgets), summary = stringResource(R.string.settings_widgets_subtitle), @@ -258,13 +258,33 @@ private fun SettingsHub( leading = { CategoryIcon(Icons.Default.Widgets, ChipAccent.Tertiary) }, onClick = { onOpenSection(SettingsSection.Widgets) }, ) - LanguageRow(position = Position.Middle) + LanguagePickerRow( + position = Position.Middle, + title = stringResource(R.string.settings_language), + autoLabel = stringResource(R.string.settings_language_auto), + localesConfig = R.xml.locales_config, + predictiveBack = true, + // Invite contributions right where users pick their language. + header = { + val context = LocalContext.current + val translateUrl = stringResource(R.string.about_translate_url) + GroupedRow( + title = stringResource(R.string.settings_translate), + summary = stringResource(R.string.settings_translate_hint), + position = Position.Alone, + leading = { CategoryIcon(Icons.Default.Translate, ChipAccent.Neutral) }, + onClick = { openUrl(context, translateUrl) }, + ) + Spacer(Modifier.height(16.dp)) + }, + leading = { CategoryIcon(Icons.Default.Language, ChipAccent.Secondary) }, + ) ReportProblemRow(position = Position.Bottom) // Source, licence and privacy sit at the bottom as reference material // rather than inside the About card. Spacer(Modifier.height(8.dp)) - SectionHeader(stringResource(R.string.settings_group_about)) + GroupedSectionHeader(stringResource(R.string.settings_group_about)) AboutLinkRow( label = stringResource(R.string.settings_about_source), url = stringResource(R.string.about_source_url), @@ -330,58 +350,6 @@ private fun ReportProblemRow(position: Position) { } } -@Composable -private fun LanguageRow(position: Position) { - val context = LocalContext.current - val supported = remember { AppLanguage.supportedTags(context, R.xml.locales_config) } - // Setting a locale recreates the activity; mirror the choice locally so the - // row updates instantly even before the recreation lands. - var current by remember { mutableStateOf(AppLanguage.currentTag(supported)) } - var showDialog by remember { mutableStateOf(false) } - - // null = follow the system; the rest are BCP-47 tags from locales_config.xml. - val options = remember(supported) { listOf(null) + supported } - - GroupedRow( - title = stringResource(R.string.settings_language), - summary = languageLabel(current), - position = position, - leading = { CategoryIcon(Icons.Default.Language, ChipAccent.Secondary) }, - onClick = { showDialog = true }, - ) - - if (showDialog) { - OptionPicker( - title = stringResource(R.string.settings_language), - predictiveBack = true, - options = options, - selected = current, - label = { languageLabel(it) }, - onSelect = { - current = it - AppLanguage.apply(it) - }, - onDismiss = { showDialog = false }, - // Invite contributions right where users pick their language. - header = { - val translateUrl = stringResource(R.string.about_translate_url) - GroupedRow( - title = stringResource(R.string.settings_translate), - summary = stringResource(R.string.settings_translate_hint), - position = Position.Alone, - leading = { CategoryIcon(Icons.Default.Translate, ChipAccent.Neutral) }, - onClick = { openUrl(context, translateUrl) }, - ) - Spacer(Modifier.height(16.dp)) - }, - ) - } -} - -@Composable -private fun languageLabel(tag: String?): String = - if (tag == null) stringResource(R.string.settings_language_auto) else AppLanguage.displayName(tag) - @Composable private fun AboutCard() { // Layout lives in floret-kit (components.AboutCard); Calendula supplies diff --git a/app/src/main/java/de/jeanlucmakiola/calendula/ui/settings/SettingsUiState.kt b/app/src/main/java/de/jeanlucmakiola/calendula/ui/settings/SettingsUiState.kt index 16111c17..5d4dcf1e 100644 --- a/app/src/main/java/de/jeanlucmakiola/calendula/ui/settings/SettingsUiState.kt +++ b/app/src/main/java/de/jeanlucmakiola/calendula/ui/settings/SettingsUiState.kt @@ -3,7 +3,7 @@ package de.jeanlucmakiola.calendula.ui.settings import de.jeanlucmakiola.floret.reminders.ReminderOverride import de.jeanlucmakiola.calendula.data.prefs.PastEventDisplay import de.jeanlucmakiola.calendula.data.prefs.SettingsPrefs -import de.jeanlucmakiola.calendula.data.prefs.ThemeMode +import de.jeanlucmakiola.floret.prefs.ThemeMode import de.jeanlucmakiola.calendula.data.prefs.TimeFormatPref import de.jeanlucmakiola.calendula.data.prefs.WeekStartPref import de.jeanlucmakiola.calendula.domain.CalendarSource @@ -47,6 +47,8 @@ data class SettingsUiState( val todayButtonInToolbar: Boolean = false, /** Whether events can be dragged to another slot to reschedule them (#68, #173). */ val dragToReschedule: Boolean = true, + /** Whether tapping an event opens the edit form instead of the detail screen (#178). */ + val tapOpensEditor: Boolean = false, /** How far ahead the in-app Agenda screen shows events (v2.11). */ val agendaScreenRange: AgendaRange = AgendaRange.Month, /** How far ahead the agenda widget shows events (v2.11). */ @@ -114,7 +116,7 @@ data class SettingsUiState( /** * State for the contact special-dates sub-page (issue #15). Exposed as its own - * flow rather than folded into [SettingsUiState] (whose combine is already full). + * flow rather than folded into [SettingsUiState]. * [titleTemplates] is always populated — a blank stored template resolves to the * localized default so the editor never shows an empty field. */ diff --git a/app/src/main/java/de/jeanlucmakiola/calendula/ui/settings/SettingsViewModel.kt b/app/src/main/java/de/jeanlucmakiola/calendula/ui/settings/SettingsViewModel.kt index 75ebca18..cbbe7075 100644 --- a/app/src/main/java/de/jeanlucmakiola/calendula/ui/settings/SettingsViewModel.kt +++ b/app/src/main/java/de/jeanlucmakiola/calendula/ui/settings/SettingsViewModel.kt @@ -6,6 +6,7 @@ import android.os.Build import androidx.glance.appwidget.GlanceAppWidgetManager import androidx.glance.appwidget.state.updateAppWidgetState import androidx.glance.appwidget.updateAll +import androidx.datastore.preferences.core.Preferences import androidx.lifecycle.ViewModel import androidx.lifecycle.viewModelScope import dagger.hilt.android.lifecycle.HiltViewModel @@ -17,14 +18,22 @@ import de.jeanlucmakiola.calendula.data.contacts.SpecialDatesCalendarSpec import de.jeanlucmakiola.calendula.data.contacts.SpecialDatesScheduler import de.jeanlucmakiola.calendula.data.contacts.SpecialDatesSyncEngine import de.jeanlucmakiola.calendula.data.contacts.resolveTitleTemplate -import de.jeanlucmakiola.calendula.data.di.IoDispatcher import de.jeanlucmakiola.calendula.data.fonts.CustomFontStore +import de.jeanlucmakiola.floret.android.stateWhileSubscribed +import de.jeanlucmakiola.floret.di.IoDispatcher import de.jeanlucmakiola.floret.reminders.ReminderOverride import de.jeanlucmakiola.floret.reminders.reminderOverrideFor import de.jeanlucmakiola.calendula.data.prefs.PastEventDisplay +import de.jeanlucmakiola.calendula.data.prefs.SettingsKeys import de.jeanlucmakiola.calendula.data.prefs.SettingsPrefs +import de.jeanlucmakiola.calendula.data.prefs.specialDatesCalendars +import de.jeanlucmakiola.calendula.data.prefs.specialDatesStatus +import de.jeanlucmakiola.calendula.data.prefs.specialDatesTitleTemplates +import de.jeanlucmakiola.calendula.data.prefs.specialDatesTypes +import de.jeanlucmakiola.calendula.data.prefs.timelineHours +import de.jeanlucmakiola.floret.prefs.get import de.jeanlucmakiola.calendula.data.prefs.SpecialDatesStalledReason -import de.jeanlucmakiola.calendula.data.prefs.ThemeMode +import de.jeanlucmakiola.floret.prefs.ThemeMode import de.jeanlucmakiola.calendula.data.prefs.TimeFormatPref import de.jeanlucmakiola.calendula.data.prefs.WeekStartPref import de.jeanlucmakiola.calendula.data.reminders.ReminderScanner @@ -35,7 +44,6 @@ import de.jeanlucmakiola.calendula.domain.contacts.SpecialDateType import de.jeanlucmakiola.calendula.ui.agenda.AgendaRange import de.jeanlucmakiola.calendula.ui.agenda.storageValue import de.jeanlucmakiola.calendula.ui.common.CalendarView -import de.jeanlucmakiola.calendula.ui.common.QuickSwitchConfig import de.jeanlucmakiola.calendula.ui.common.TimelineHours import de.jeanlucmakiola.calendula.ui.common.TimelineScale import de.jeanlucmakiola.calendula.ui.month.MonthViewStyle @@ -54,12 +62,10 @@ import kotlinx.coroutines.flow.MutableSharedFlow import kotlinx.coroutines.flow.MutableStateFlow import kotlinx.coroutines.flow.SharedFlow import kotlinx.coroutines.flow.asStateFlow -import kotlinx.coroutines.flow.SharingStarted import kotlinx.coroutines.flow.StateFlow import kotlinx.coroutines.flow.catch import kotlinx.coroutines.flow.combine import kotlinx.coroutines.flow.map -import kotlinx.coroutines.flow.stateIn import kotlinx.coroutines.launch import kotlinx.coroutines.sync.Mutex import kotlinx.coroutines.sync.withLock @@ -90,162 +96,68 @@ class SettingsViewModel @Inject constructor( .catch { emit(emptyList()) } val state: StateFlow = - combine( - // combine() types up to five flows, so the prefs split into two - // groups that fold together in the outer combine. - combine( - prefs.themeMode, - prefs.dynamicColor, - prefs.weekStart, - prefs.defaultFormFields, - prefs.remindersEnabled, - ) { theme, dynamic, weekStart, formFields, reminders -> - SettingsUiState( - themeMode = theme, - dynamicColor = dynamic && dynamicColorAvailable, - dynamicColorAvailable = dynamicColorAvailable, - weekStart = weekStart, - defaultFormFields = formFields, - remindersEnabled = reminders, - ) - }, - combine( - prefs.allowColorOnUnsupportedCalendars, - prefs.defaultReminderMinutes, - prefs.defaultAllDayReminderMinutes, - prefs.allDayReminderTimeMinutes, - prefs.snoozeMinutes, - ) { allowColor, defaultReminder, allDayReminder, allDayReminderTime, snooze -> - ReminderDefaults( - allowColor, defaultReminder, allDayReminder, allDayReminderTime, snooze, - ) - }, - combine( - prefs.perCalendarReminderOverride, - prefs.perCalendarAllDayReminderOverride, - writableCalendars, - prefs.managedCalendarIds, - // The new-event duration defaults (#54) fold into one flow so they - // fit this group — the outer combine is at its five-arg limit. - combine( - prefs.defaultEventDurationMinutes, - prefs.perCalendarEventDuration, - ) { duration, perCalendar -> EventDurations(duration, perCalendar) }, - ) { overrides, allDayOverrides, calendars, managedIds, durations -> - ReminderOverrides(overrides, allDayOverrides, calendars, managedIds, durations) - }, - combine( - prefs.defaultView, - prefs.agendaScreenRange, - prefs.agendaWidgetRange, - prefs.timeFormat, - // Display toggles folded into one flow so they fit this group — - // the outer combine is already at its five-arg limit. - combine( - prefs.showHourGrid, - prefs.showWeekNumbers, - prefs.agendaShowToday, - prefs.softenCalendarColors, - combine( - prefs.todayButtonInToolbar, - prefs.dragToReschedule, - prefs.multiDayCount, - ::Triple, - ), - ) { hourLines, weekNumbers, showToday, soften, (todayInToolbar, dragToMove, multiDay) -> - DisplayToggles( - hourLines, weekNumbers, showToday, soften, todayInToolbar, dragToMove, multiDay, - ) - }, - ) { view, screenRange, widgetRange, timeFormat, toggles -> - ViewSettings( - view, screenRange, widgetRange, timeFormat, - showHourGrid = toggles.showHourGrid, - showWeekNumbers = toggles.showWeekNumbers, - agendaShowToday = toggles.agendaShowToday, - softenColors = toggles.softenColors, - todayButtonInToolbar = toggles.todayButtonInToolbar, - dragToReschedule = toggles.dragToReschedule, - multiDayCount = toggles.multiDayCount, - ) - }, - combine( - prefs.agendaShowRangeBar, - prefs.autofocusEventTitle, - prefs.pastEventDisplay, - prefs.dimCompletedEvents, - // View customisation (#24) folded into one flow so it fits this - // group — the outer combine is already at its five-arg limit. - combine( - prefs.quickSwitchConfig, - prefs.drawerViewOrder, - prefs.monthViewStyle, - prefs.widgetSize, - combine(prefs.timelineScale, prefs.timelineHours, ::Pair), - ) { quickSwitch, drawer, monthStyle, widgetSize, (timelineScale, timelineHours) -> - ViewCustomization( - quickSwitch, drawer, monthStyle, widgetSize, timelineScale, timelineHours, - ) - }, - ) { showRangeBar, autofocus, pastEvents, dimCompleted, viewCustomization -> - MiscSettings(showRangeBar, autofocus, pastEvents, dimCompleted, viewCustomization) - }, - ) { base, defaults, overrides, views, misc -> - base.copy( - defaultView = views.defaultView, - agendaScreenRange = views.agendaScreenRange, - agendaWidgetRange = views.agendaWidgetRange, - timeFormat = views.timeFormat, - showHourGrid = views.showHourGrid, - showWeekNumbers = views.showWeekNumbers, - agendaShowToday = views.agendaShowToday, - softenColors = views.softenColors, - todayButtonInToolbar = views.todayButtonInToolbar, - dragToReschedule = views.dragToReschedule, - multiDayCount = views.multiDayCount, - agendaShowRangeBar = misc.showRangeBar, - autofocusEventTitle = misc.autofocusEventTitle, - pastEventDisplay = misc.pastEventDisplay, - dimCompletedEvents = misc.dimCompletedEvents, - quickSwitchConfig = misc.viewCustomization.quickSwitch, - drawerViewOrder = misc.viewCustomization.drawerOrder, - monthViewStyle = misc.viewCustomization.monthViewStyle, - widgetSize = misc.viewCustomization.widgetSize, - timelineScale = misc.viewCustomization.timelineScale, - timelineHours = misc.viewCustomization.timelineHours, - allowColorOnUnsupportedCalendars = defaults.allowColor, - defaultReminderMinutes = defaults.defaultReminder, - defaultAllDayReminderMinutes = defaults.allDayReminder, - allDayReminderTimeMinutes = defaults.allDayReminderTime, - snoozeMinutes = defaults.snoozeMinutes, - perCalendarReminderOverride = overrides.timed, - perCalendarAllDayReminderOverride = overrides.allDay, - writableCalendars = overrides.calendars, - managedCalendarIds = overrides.managedIds, - defaultEventDurationMinutes = overrides.durations.default, - perCalendarEventDuration = overrides.durations.perCalendar, + combine(prefs.data, writableCalendars) { stored, calendars -> stored.toUiState(calendars) } + .stateWhileSubscribed( + scope = viewModelScope, + initialValue = SettingsUiState(dynamicColorAvailable = dynamicColorAvailable), ) - }.stateIn( - scope = viewModelScope, - started = SharingStarted.WhileSubscribed(5_000L), - initialValue = SettingsUiState(dynamicColorAvailable = dynamicColorAvailable), - ) + + private fun Preferences.toUiState(calendars: List) = SettingsUiState( + themeMode = this[SettingsKeys.themeMode], + dynamicColor = this[SettingsKeys.dynamicColor] && dynamicColorAvailable, + dynamicColorAvailable = dynamicColorAvailable, + softenColors = this[SettingsKeys.softenCalendarColors], + weekStart = this[SettingsKeys.weekStart], + timeFormat = this[SettingsKeys.timeFormat], + showHourGrid = this[SettingsKeys.showHourGrid], + multiDayCount = this[SettingsKeys.multiDayCount], + pastEventDisplay = this[SettingsKeys.pastEventDisplay], + dimCompletedEvents = this[SettingsKeys.dimCompletedEvents], + showWeekNumbers = this[SettingsKeys.showWeekNumbers], + todayButtonInToolbar = this[SettingsKeys.todayButtonInToolbar], + dragToReschedule = this[SettingsKeys.dragToReschedule], + tapOpensEditor = this[SettingsKeys.tapOpensEditor], + agendaScreenRange = this[SettingsKeys.agendaScreenRange], + agendaWidgetRange = this[SettingsKeys.agendaWidgetRange], + agendaShowToday = this[SettingsKeys.agendaShowToday], + agendaShowRangeBar = this[SettingsKeys.agendaShowRangeBar], + widgetSize = this[SettingsKeys.widgetSize], + defaultView = this[SettingsKeys.defaultView], + quickSwitchConfig = this[SettingsKeys.quickSwitchConfig], + monthViewStyle = this[SettingsKeys.monthViewStyle], + timelineScale = this[SettingsKeys.timelineScale], + timelineHours = timelineHours, + drawerViewOrder = this[SettingsKeys.drawerViewOrder], + defaultFormFields = this[SettingsKeys.defaultFormFields], + autofocusEventTitle = this[SettingsKeys.autofocusEventTitle], + defaultEventDurationMinutes = this[SettingsKeys.defaultEventDurationMinutes], + perCalendarEventDuration = this[SettingsKeys.perCalendarEventDuration], + remindersEnabled = this[SettingsKeys.remindersEnabled], + defaultReminderMinutes = this[SettingsKeys.defaultReminderMinutes], + defaultAllDayReminderMinutes = this[SettingsKeys.defaultAllDayReminderMinutes], + allDayReminderTimeMinutes = this[SettingsKeys.allDayReminderTimeMinutes], + snoozeMinutes = this[SettingsKeys.snoozeMinutes], + perCalendarReminderOverride = this[SettingsKeys.perCalendarReminderOverride], + perCalendarAllDayReminderOverride = this[SettingsKeys.perCalendarAllDayReminderOverride], + writableCalendars = calendars, + allowColorOnUnsupportedCalendars = this[SettingsKeys.allowColorOnUnsupportedCalendars], + managedCalendarIds = specialDatesCalendars.values.toSet(), + ) /** * The app-wide custom-font choice (issue #19). Its own flow — both this * screen and [MainActivity] (which builds the typography) read it - * independently of the main settings combine. + * independently of the main settings state. */ - val fontState: StateFlow = combine( - prefs.brandFont, - prefs.plainFont, - prefs.brandFontStamp, - prefs.plainFontStamp, - ) { brand, plain, brandStamp, plainStamp -> - AppFontSettings(brand = brand, plain = plain, brandStamp = brandStamp, plainStamp = plainStamp) - }.stateIn( + val fontState: StateFlow = prefs.data.map { + AppFontSettings( + brand = it[SettingsKeys.brandFont], + plain = it[SettingsKeys.plainFont], + brandStamp = it[SettingsKeys.brandFontStamp], + plainStamp = it[SettingsKeys.plainFontStamp], + ) + }.stateWhileSubscribed( scope = viewModelScope, - started = SharingStarted.WhileSubscribed(5_000L), initialValue = AppFontSettings(), ) @@ -273,102 +185,29 @@ class SettingsViewModel @Inject constructor( // stale read and can leave the widget on an intermediate value. private val widgetRefreshMutex = Mutex() - private data class ReminderDefaults( - val allowColor: Boolean, - val defaultReminder: List, - val allDayReminder: List, - val allDayReminderTime: Int, - val snoozeMinutes: Int, - ) - - private data class ReminderOverrides( - val timed: Map>, - val allDay: Map>, - val calendars: List, - val managedIds: Set, - val durations: EventDurations, - ) - - private data class EventDurations( - val default: Int, - val perCalendar: Map, - ) - - private data class ViewSettings( - val defaultView: CalendarView, - val agendaScreenRange: AgendaRange, - val agendaWidgetRange: AgendaRange, - val timeFormat: TimeFormatPref, - val showHourGrid: Boolean, - val showWeekNumbers: Boolean, - val agendaShowToday: Boolean, - val softenColors: Boolean, - val todayButtonInToolbar: Boolean, - val dragToReschedule: Boolean, - val multiDayCount: Int, - ) - - private data class DisplayToggles( - val showHourGrid: Boolean, - val showWeekNumbers: Boolean, - val agendaShowToday: Boolean, - val softenColors: Boolean, - val todayButtonInToolbar: Boolean, - val dragToReschedule: Boolean, - val multiDayCount: Int, - ) - - private data class MiscSettings( - val showRangeBar: Boolean, - val autofocusEventTitle: Boolean, - val pastEventDisplay: PastEventDisplay, - val dimCompletedEvents: Boolean, - val viewCustomization: ViewCustomization, - ) - - private data class ViewCustomization( - val quickSwitch: QuickSwitchConfig, - val drawerOrder: List, - val monthViewStyle: MonthViewStyle, - val widgetSize: WidgetSize, - val timelineScale: TimelineScale, - val timelineHours: TimelineHours, - ) - - /** Contact special-dates sub-page (issue #15); its own flow — the main state is full. */ - val specialDatesState: StateFlow = combine( - combine( - prefs.specialDatesEnabled, - prefs.specialDatesTypes, - prefs.specialDatesTitleTemplates, - prefs.specialDatesShowYear, - prefs.specialDatesStatus, - ) { enabled, types, templates, showYear, status -> - SpecialDatesUiState( - enabled = enabled, - types = types, - // A blank stored template resolves to the localized default so the - // editor always shows something sensible. - titleTemplates = SpecialDateType.entries.associateWith { type -> - specialDatesSpec.resolveTitleTemplate(type, templates) - }, - showYear = showYear, - stalledPermission = status.stalled == SpecialDatesStalledReason.PermissionRevoked, - lastRun = status.lastRun, - ) - }, - prefs.specialDatesCalendars, - prefs.perCalendarAllDayReminderOverride, - ) { base, calendars, allDayOverrides -> - base.copy( + /** Contact special-dates sub-page (issue #15). */ + val specialDatesState: StateFlow = prefs.data.map { stored -> + val templates = stored.specialDatesTitleTemplates + val allDayOverrides = stored[SettingsKeys.perCalendarAllDayReminderOverride] + val status = stored.specialDatesStatus + SpecialDatesUiState( + enabled = stored[SettingsKeys.specialDatesEnabled], + types = stored.specialDatesTypes, + // A blank stored template resolves to the localized default so the + // editor always shows something sensible. + titleTemplates = SpecialDateType.entries.associateWith { type -> + specialDatesSpec.resolveTitleTemplate(type, templates) + }, // An override is always seeded on creation; present-empty = None. - reminderChoices = calendars.mapValues { (_, calendarId) -> + reminderChoices = stored.specialDatesCalendars.mapValues { (_, calendarId) -> allDayOverrides.reminderOverrideFor(calendarId) }, + showYear = stored[SettingsKeys.specialDatesShowYear], + stalledPermission = status.stalled == SpecialDatesStalledReason.PermissionRevoked, + lastRun = status.lastRun, ) - }.stateIn( + }.stateWhileSubscribed( scope = viewModelScope, - started = SharingStarted.WhileSubscribed(5_000L), initialValue = SpecialDatesUiState(), ) @@ -424,13 +263,9 @@ class SettingsViewModel @Inject constructor( /** Kick off an immediate reconcile (the "Sync now" action). */ fun syncSpecialDatesNow() = SpecialDatesScheduler.runNow(appContext) - fun setThemeMode(mode: ThemeMode) { - viewModelScope.launch { prefs.setThemeMode(mode) } - } + fun setThemeMode(mode: ThemeMode) = save { setThemeMode(mode) } - fun setDynamicColor(enabled: Boolean) { - viewModelScope.launch { prefs.setDynamicColor(enabled) } - } + fun setDynamicColor(enabled: Boolean) = save { setDynamicColor(enabled) } fun setSoftenColors(enabled: Boolean) { viewModelScope.launch { @@ -443,12 +278,10 @@ class SettingsViewModel @Inject constructor( } } - fun setFont(role: FontRole, token: String) { - viewModelScope.launch { - when (role) { - FontRole.BRAND -> prefs.setBrandFont(token) - FontRole.PLAIN -> prefs.setPlainFont(token) - } + fun setFont(role: FontRole, token: String) = save { + when (role) { + FontRole.BRAND -> setBrandFont(token) + FontRole.PLAIN -> setPlainFont(token) } } @@ -483,9 +316,7 @@ class SettingsViewModel @Inject constructor( } } - fun setAgendaScreenRange(range: AgendaRange) { - viewModelScope.launch { prefs.setAgendaScreenRange(range) } - } + fun setAgendaScreenRange(range: AgendaRange) = save { setAgendaScreenRange(range) } fun setAgendaWidgetRange(range: AgendaRange) { viewModelScope.launch { @@ -502,9 +333,7 @@ class SettingsViewModel @Inject constructor( } } - fun setAgendaShowRangeBar(enabled: Boolean) { - viewModelScope.launch { prefs.setAgendaShowRangeBar(enabled) } - } + fun setAgendaShowRangeBar(enabled: Boolean) = save { setAgendaShowRangeBar(enabled) } /** * Set the size the agenda widget draws its text at (#51), via the same @@ -538,29 +367,19 @@ class SettingsViewModel @Inject constructor( } } - fun setTimeFormat(pref: TimeFormatPref) { - viewModelScope.launch { prefs.setTimeFormat(pref) } - } + fun setTimeFormat(pref: TimeFormatPref) = save { setTimeFormat(pref) } - fun setMultiDayCount(count: Int) { - viewModelScope.launch { prefs.setMultiDayCount(count) } - } + fun setMultiDayCount(count: Int) = save { setMultiDayCount(count) } - fun setShowHourGrid(enabled: Boolean) { - viewModelScope.launch { prefs.setShowHourGrid(enabled) } - } + fun setShowHourGrid(enabled: Boolean) = save { setShowHourGrid(enabled) } - fun setShowWeekNumbers(enabled: Boolean) { - viewModelScope.launch { prefs.setShowWeekNumbers(enabled) } - } + fun setShowWeekNumbers(enabled: Boolean) = save { setShowWeekNumbers(enabled) } - fun setTodayButtonInToolbar(enabled: Boolean) { - viewModelScope.launch { prefs.setTodayButtonInToolbar(enabled) } - } + fun setTodayButtonInToolbar(enabled: Boolean) = save { setTodayButtonInToolbar(enabled) } - fun setDragToReschedule(enabled: Boolean) { - viewModelScope.launch { prefs.setDragToReschedule(enabled) } - } + fun setDragToReschedule(enabled: Boolean) = save { setDragToReschedule(enabled) } + + fun setTapOpensEditor(enabled: Boolean) = save { setTapOpensEditor(enabled) } /** * Switch the launcher label (#44). The card highlights at once, then settles @@ -591,53 +410,33 @@ class SettingsViewModel @Inject constructor( } } - fun setDimCompletedEvents(enabled: Boolean) { - viewModelScope.launch { prefs.setDimCompletedEvents(enabled) } - } + fun setDimCompletedEvents(enabled: Boolean) = save { setDimCompletedEvents(enabled) } - fun setDefaultView(view: CalendarView) { - viewModelScope.launch { prefs.setDefaultView(view) } - } + fun setDefaultView(view: CalendarView) = save { setDefaultView(view) } - fun setFormFieldDefault(field: EventFormField, enabled: Boolean) { - viewModelScope.launch { prefs.setFormFieldDefault(field, enabled) } - } + fun setFormFieldDefault(field: EventFormField, enabled: Boolean) = save { setFormFieldDefault(field, enabled) } /** * Enable or disable [view] in the quick-switch cycle, via an atomic * read-modify-write so a concurrent reorder can't clobber it. Any number of * views may be turned off; below two the pill hides itself (#150). */ - fun setQuickSwitchViewEnabled(view: CalendarView, enabled: Boolean) { - viewModelScope.launch { - prefs.updateQuickSwitch { config -> - config.copy( - enabled = if (enabled) config.enabled + view else config.enabled - view, - ) - } + fun setQuickSwitchViewEnabled(view: CalendarView, enabled: Boolean) = save { + updateQuickSwitch { config -> + config.copy(enabled = if (enabled) config.enabled + view else config.enabled - view) } } /** Reorder the quick-switch views (atomic read-modify-write; keeps the enabled set). */ - fun setQuickSwitchOrder(order: List) { - viewModelScope.launch { prefs.updateQuickSwitch { it.copy(order = order) } } - } + fun setQuickSwitchOrder(order: List) = save { updateQuickSwitch { it.copy(order = order) } } - fun setMonthViewStyle(style: MonthViewStyle) { - viewModelScope.launch { prefs.setMonthViewStyle(style) } - } + fun setMonthViewStyle(style: MonthViewStyle) = save { setMonthViewStyle(style) } - fun setTimelineScale(scale: TimelineScale) { - viewModelScope.launch { prefs.setTimelineScale(scale) } - } + fun setTimelineScale(scale: TimelineScale) = save { setTimelineScale(scale) } - fun setTimelineHours(hours: TimelineHours) { - viewModelScope.launch { prefs.setTimelineHours(hours) } - } + fun setTimelineHours(hours: TimelineHours) = save { setTimelineHours(hours) } - fun setDrawerViewOrder(order: List) { - viewModelScope.launch { prefs.setDrawerViewOrder(order) } - } + fun setDrawerViewOrder(order: List) = save { setDrawerViewOrder(order) } /** * A scan follows the write: switching reminders off cancels the scan alarm, @@ -650,26 +449,16 @@ class SettingsViewModel @Inject constructor( } } - fun setAutofocusEventTitle(enabled: Boolean) { - viewModelScope.launch { prefs.setAutofocusEventTitle(enabled) } - } + fun setAutofocusEventTitle(enabled: Boolean) = save { setAutofocusEventTitle(enabled) } - fun setDefaultEventDuration(minutes: Int) { - viewModelScope.launch { prefs.setDefaultEventDurationMinutes(minutes) } - } + fun setDefaultEventDuration(minutes: Int) = save { setDefaultEventDurationMinutes(minutes) } /** [minutes] null clears the override, so the calendar inherits the default. */ - fun setCalendarEventDuration(calendarId: Long, minutes: Int?) { - viewModelScope.launch { prefs.setCalendarEventDuration(calendarId, minutes) } - } + fun setCalendarEventDuration(calendarId: Long, minutes: Int?) = save { setCalendarEventDuration(calendarId, minutes) } - fun setDefaultReminderMinutes(minutes: List) { - viewModelScope.launch { prefs.setDefaultReminderMinutes(minutes) } - } + fun setDefaultReminderMinutes(minutes: List) = save { setDefaultReminderMinutes(minutes) } - fun setDefaultAllDayReminderMinutes(minutes: List) { - viewModelScope.launch { prefs.setDefaultAllDayReminderMinutes(minutes) } - } + fun setDefaultAllDayReminderMinutes(minutes: List) = save { setDefaultAllDayReminderMinutes(minutes) } /** The armed alarm was planned for the old hour, so re-plan against the new one. */ fun setAllDayReminderTimeMinutes(minutesOfDay: Int) { @@ -679,19 +468,15 @@ class SettingsViewModel @Inject constructor( } } - fun setSnoozeMinutes(minutes: Int) { - viewModelScope.launch { prefs.setSnoozeMinutes(minutes) } - } + fun setSnoozeMinutes(minutes: Int) = save { setSnoozeMinutes(minutes) } - fun setCalendarReminderOverride(calendarId: Long, override: ReminderOverride) { - viewModelScope.launch { prefs.setCalendarReminderOverride(calendarId, override) } - } + fun setCalendarReminderOverride(calendarId: Long, override: ReminderOverride) = save { setCalendarReminderOverride(calendarId, override) } - fun setCalendarAllDayReminderOverride(calendarId: Long, override: ReminderOverride) { - viewModelScope.launch { prefs.setCalendarAllDayReminderOverride(calendarId, override) } - } + fun setCalendarAllDayReminderOverride(calendarId: Long, override: ReminderOverride) = save { setCalendarAllDayReminderOverride(calendarId, override) } - fun setAllowColorOnUnsupportedCalendars(enabled: Boolean) { - viewModelScope.launch { prefs.setAllowColorOnUnsupportedCalendars(enabled) } + fun setAllowColorOnUnsupportedCalendars(enabled: Boolean) = save { setAllowColorOnUnsupportedCalendars(enabled) } + + private fun save(write: suspend SettingsPrefs.() -> Unit) { + viewModelScope.launch { prefs.write() } } } diff --git a/app/src/main/java/de/jeanlucmakiola/calendula/ui/settings/SpecialDatesSettings.kt b/app/src/main/java/de/jeanlucmakiola/calendula/ui/settings/SpecialDatesSettings.kt index 0e8559bb..2f20e9ac 100644 --- a/app/src/main/java/de/jeanlucmakiola/calendula/ui/settings/SpecialDatesSettings.kt +++ b/app/src/main/java/de/jeanlucmakiola/calendula/ui/settings/SpecialDatesSettings.kt @@ -1,7 +1,6 @@ package de.jeanlucmakiola.calendula.ui.settings import android.Manifest -import android.content.Context import androidx.activity.compose.rememberLauncherForActivityResult import androidx.activity.result.contract.ActivityResultContracts import androidx.compose.foundation.layout.Column @@ -14,7 +13,6 @@ import androidx.compose.material3.AlertDialog import androidx.compose.material3.FilledTonalButton import androidx.compose.material3.MaterialTheme import androidx.compose.material3.Surface -import androidx.compose.material3.Switch import androidx.compose.material3.Text import androidx.compose.material3.TextButton import androidx.compose.runtime.Composable @@ -34,9 +32,12 @@ import de.jeanlucmakiola.calendula.domain.contacts.SpecialDateType import de.jeanlucmakiola.calendula.ui.common.ReminderDefaultPicker import de.jeanlucmakiola.floret.components.CollapsingScaffold import de.jeanlucmakiola.floret.components.GroupedRow +import de.jeanlucmakiola.floret.components.GroupedSwitchRow import de.jeanlucmakiola.floret.components.InlineTextField import de.jeanlucmakiola.floret.components.Position +import de.jeanlucmakiola.floret.locale.relativeTimeAgo import de.jeanlucmakiola.floret.reminders.ReminderOverride +import de.jeanlucmakiola.floret.reminders.minutesOrEmpty // --------------------------------------------------------------------------- // Contact special dates (issue #15) @@ -106,38 +107,26 @@ internal fun SpecialDatesScreen( Spacer(Modifier.height(16.dp)) } - GroupedRow( + GroupedSwitchRow( title = stringResource(R.string.settings_special_dates_enable), + checked = state.enabled, + onCheckedChange = { want -> if (want) requestOrEnable() else confirmDisableAll = true }, summary = stringResource(R.string.settings_special_dates_enable_hint), position = Position.Alone, - trailing = { - Switch( - checked = state.enabled, - onCheckedChange = { want -> if (want) requestOrEnable() else confirmDisableAll = true }, - ) - }, - onClick = { if (state.enabled) confirmDisableAll = true else requestOrEnable() }, ) if (state.enabled) { SpecialDateType.entries.forEachIndexed { index, type -> Spacer(Modifier.height(if (index == 0) 24.dp else 16.dp)) val on = type in state.types - GroupedRow( + GroupedSwitchRow( title = stringResource(specialDateTypeLabel(type)), + checked = on, + onCheckedChange = { want -> + if (want) viewModel.setSpecialDateTypeEnabled(type, true) + else confirmDisableType = type + }, position = if (on) Position.Top else Position.Alone, - trailing = { - Switch( - checked = on, - onCheckedChange = { want -> - if (want) viewModel.setSpecialDateTypeEnabled(type, true) - else confirmDisableType = type - }, - ) - }, - onClick = { - if (on) confirmDisableType = type else viewModel.setSpecialDateTypeEnabled(type, true) - }, ) if (on) { GroupedRow( @@ -148,7 +137,7 @@ internal fun SpecialDatesScreen( ) GroupedRow( title = stringResource(R.string.settings_special_dates_reminders), - summary = reminderChoiceLabel(specialDatesReminderMinutes(state.reminderChoices[type])), + summary = reminderChoiceLabel(state.reminderChoices[type]?.minutesOrEmpty().orEmpty()), position = Position.Bottom, onClick = { reminderPickerType = type }, ) @@ -156,21 +145,16 @@ internal fun SpecialDatesScreen( } Spacer(Modifier.height(24.dp)) - GroupedRow( + GroupedSwitchRow( title = stringResource(R.string.settings_special_dates_show_year), + checked = state.showYear, + onCheckedChange = viewModel::setSpecialDatesShowYear, summary = stringResource(R.string.settings_special_dates_show_year_hint), position = Position.Top, - trailing = { - Switch( - checked = state.showYear, - onCheckedChange = viewModel::setSpecialDatesShowYear, - ) - }, - onClick = { viewModel.setSpecialDatesShowYear(!state.showYear) }, ) GroupedRow( title = stringResource(R.string.settings_special_dates_sync_now), - summary = specialDatesLastRunLabel(context, state.lastRun), + summary = specialDatesLastRunLabel(state.lastRun), position = Position.Bottom, onClick = viewModel::syncSpecialDatesNow, ) @@ -223,10 +207,6 @@ internal fun SpecialDatesScreen( } } -/** The lead-time list backing a managed calendar's reminder choice (for the summary label). */ -private fun specialDatesReminderMinutes(choice: ReminderOverride?): List = - (choice as? ReminderOverride.Minutes)?.minutes.orEmpty() - @Composable private fun SpecialDatesDisableDialog( message: String, @@ -305,16 +285,12 @@ private fun specialDateTypeLabel(type: SpecialDateType): Int = when (type) { } @Composable -private fun specialDatesLastRunLabel(context: Context, lastRun: Long): String = +private fun specialDatesLastRunLabel(lastRun: Long): String = if (lastRun <= 0L) { stringResource(R.string.settings_special_dates_never_synced) } else { stringResource( R.string.settings_special_dates_last_synced, - android.text.format.DateUtils.getRelativeTimeSpanString( - lastRun, - System.currentTimeMillis(), - android.text.format.DateUtils.MINUTE_IN_MILLIS, - ).toString(), + relativeTimeAgo(lastRun), ) } diff --git a/app/src/main/java/de/jeanlucmakiola/calendula/ui/settings/ViewsSettings.kt b/app/src/main/java/de/jeanlucmakiola/calendula/ui/settings/ViewsSettings.kt index 22ccb1ae..b214efc5 100644 --- a/app/src/main/java/de/jeanlucmakiola/calendula/ui/settings/ViewsSettings.kt +++ b/app/src/main/java/de/jeanlucmakiola/calendula/ui/settings/ViewsSettings.kt @@ -33,7 +33,6 @@ import de.jeanlucmakiola.calendula.data.prefs.resolveFirstDay import de.jeanlucmakiola.calendula.ui.common.AgendaRangePicker import de.jeanlucmakiola.calendula.ui.common.CalendarView import de.jeanlucmakiola.calendula.ui.common.IMPLEMENTED_VIEWS -import de.jeanlucmakiola.calendula.ui.common.PickerDescription import de.jeanlucmakiola.calendula.ui.common.LocalUse24HourFormat import de.jeanlucmakiola.calendula.ui.common.TimelineHours import de.jeanlucmakiola.calendula.ui.common.TimelineScale @@ -46,7 +45,10 @@ import de.jeanlucmakiola.calendula.ui.common.label import de.jeanlucmakiola.calendula.ui.common.labelRes import de.jeanlucmakiola.calendula.ui.month.labelRes import de.jeanlucmakiola.floret.components.CollapsingScaffold +import de.jeanlucmakiola.floret.components.GroupedHint import de.jeanlucmakiola.floret.components.GroupedRow +import de.jeanlucmakiola.floret.components.GroupedSectionHeader +import de.jeanlucmakiola.floret.components.GroupedSwitchRow import de.jeanlucmakiola.floret.components.OptionPicker import de.jeanlucmakiola.floret.components.Position import de.jeanlucmakiola.floret.components.ReorderableColumn @@ -54,6 +56,7 @@ import de.jeanlucmakiola.floret.components.ReorderableRowHeight import de.jeanlucmakiola.floret.locale.currentLocale import kotlinx.datetime.DayOfWeek import java.time.format.TextStyle as JavaTextStyle +import kotlinx.datetime.toJavaDayOfWeek /** * Views: everything that changes how a calendar view reads, grouped by the view @@ -74,6 +77,7 @@ internal fun ViewsScreen( var showDefaultView by remember { mutableStateOf(false) } var showWeekStart by remember { mutableStateOf(false) } var showTimeFormat by remember { mutableStateOf(false) } + var showTapOpens by remember { mutableStateOf(false) } var showPastEvents by remember { mutableStateOf(false) } var showAgendaScreenRange by remember { mutableStateOf(false) } var showTimelineScale by remember { mutableStateOf(false) } @@ -91,7 +95,7 @@ internal fun ViewsScreen( val config = state.quickSwitchConfig // What holds for every view, above the per-view groups. - SectionHeader(stringResource(R.string.settings_views_all_header)) + GroupedSectionHeader(stringResource(R.string.settings_views_all_header)) GroupedRow( title = stringResource(R.string.settings_default_view), summary = state.defaultView.label(), @@ -110,66 +114,57 @@ internal fun ViewsScreen( position = Position.Middle, onClick = { showTimeFormat = true }, ) - GroupedRow( + GroupedSwitchRow( title = stringResource(R.string.settings_today_toolbar), + checked = state.todayButtonInToolbar, + onCheckedChange = viewModel::setTodayButtonInToolbar, summary = stringResource(R.string.settings_today_toolbar_summary), position = Position.Middle, - trailing = { - Switch( - checked = state.todayButtonInToolbar, - onCheckedChange = viewModel::setTodayButtonInToolbar, - ) - }, - onClick = { viewModel.setTodayButtonInToolbar(!state.todayButtonInToolbar) }, ) - GroupedRow( + GroupedSwitchRow( title = stringResource(R.string.settings_dim_completed), + checked = state.dimCompletedEvents, + onCheckedChange = viewModel::setDimCompletedEvents, summary = stringResource(R.string.settings_dim_completed_summary), - position = Position.Middle, - trailing = { - Switch( - checked = state.dimCompletedEvents, - onCheckedChange = viewModel::setDimCompletedEvents, - ) - }, - onClick = { viewModel.setDimCompletedEvents(!state.dimCompletedEvents) }, - ) - GroupedRow( - title = stringResource(R.string.settings_drag_to_reschedule), - summary = stringResource(R.string.settings_drag_to_reschedule_summary), position = Position.Bottom, - trailing = { - Switch( - checked = state.dragToReschedule, - onCheckedChange = viewModel::setDragToReschedule, - ) - }, - onClick = { viewModel.setDragToReschedule(!state.dragToReschedule) }, ) Spacer(Modifier.height(8.dp)) - SectionHeader(stringResource(R.string.settings_month_header)) + + // How events respond to a tap and a long press (#178, #141). + GroupedSectionHeader(stringResource(R.string.settings_events_header)) + GroupedRow( + title = stringResource(R.string.settings_tap_opens), + summary = tapOpensLabel(state.tapOpensEditor), + position = Position.Top, + onClick = { showTapOpens = true }, + ) + GroupedSwitchRow( + title = stringResource(R.string.settings_drag_to_reschedule), + checked = state.dragToReschedule, + onCheckedChange = viewModel::setDragToReschedule, + summary = stringResource(R.string.settings_drag_to_reschedule_summary), + position = Position.Bottom, + ) + + Spacer(Modifier.height(8.dp)) + GroupedSectionHeader(stringResource(R.string.settings_month_header)) GroupedRow( title = stringResource(R.string.settings_month_view_style), summary = stringResource(state.monthViewStyle.labelRes), position = Position.Top, onClick = { showMonthStyle = true }, ) - GroupedRow( + GroupedSwitchRow( title = stringResource(R.string.settings_week_numbers), + checked = state.showWeekNumbers, + onCheckedChange = viewModel::setShowWeekNumbers, summary = stringResource(R.string.settings_week_numbers_summary), position = Position.Bottom, - trailing = { - Switch( - checked = state.showWeekNumbers, - onCheckedChange = viewModel::setShowWeekNumbers, - ) - }, - onClick = { viewModel.setShowWeekNumbers(!state.showWeekNumbers) }, ) Spacer(Modifier.height(8.dp)) - SectionHeader(stringResource(R.string.settings_week_day_header)) + GroupedSectionHeader(stringResource(R.string.settings_week_day_header)) GroupedRow( title = stringResource(R.string.settings_multi_day_count), summary = multiDayLabel(state.multiDayCount), @@ -187,8 +182,10 @@ internal fun ViewsScreen( dimmed = hours.enabled, onClick = if (hours.enabled) null else ({ showTimelineScale = true }), ) - GroupedRow( + GroupedSwitchRow( title = stringResource(R.string.settings_visible_hours), + checked = hours.enabled, + onCheckedChange = { viewModel.setTimelineHours(hours.copy(enabled = it)) }, summary = if (hours.enabled) { stringResource( R.string.settings_visible_hours_on_summary, @@ -199,13 +196,6 @@ internal fun ViewsScreen( stringResource(R.string.settings_visible_hours_summary) }, position = Position.Middle, - trailing = { - Switch( - checked = hours.enabled, - onCheckedChange = { viewModel.setTimelineHours(hours.copy(enabled = it)) }, - ) - }, - onClick = { viewModel.setTimelineHours(hours.copy(enabled = !hours.enabled)) }, ) if (hours.enabled) { GroupedRow( @@ -221,21 +211,16 @@ internal fun ViewsScreen( onClick = { showHoursEnd = true }, ) } - GroupedRow( + GroupedSwitchRow( title = stringResource(R.string.settings_hour_lines), + checked = state.showHourGrid, + onCheckedChange = viewModel::setShowHourGrid, summary = stringResource(R.string.settings_hour_lines_summary), position = Position.Bottom, - trailing = { - Switch( - checked = state.showHourGrid, - onCheckedChange = viewModel::setShowHourGrid, - ) - }, - onClick = { viewModel.setShowHourGrid(!state.showHourGrid) }, ) Spacer(Modifier.height(8.dp)) - SectionHeader(stringResource(R.string.settings_agenda_header)) + GroupedSectionHeader(stringResource(R.string.settings_agenda_header)) GroupedRow( title = stringResource(R.string.settings_agenda_range), summary = agendaRangeLabel(state.agendaScreenRange), @@ -248,34 +233,24 @@ internal fun ViewsScreen( position = Position.Middle, onClick = { showPastEvents = true }, ) - GroupedRow( + GroupedSwitchRow( title = stringResource(R.string.settings_agenda_show_today), + checked = state.agendaShowToday, + onCheckedChange = viewModel::setAgendaShowToday, summary = stringResource(R.string.settings_agenda_show_today_hint), position = Position.Middle, - trailing = { - Switch( - checked = state.agendaShowToday, - onCheckedChange = viewModel::setAgendaShowToday, - ) - }, - onClick = { viewModel.setAgendaShowToday(!state.agendaShowToday) }, ) - GroupedRow( + GroupedSwitchRow( title = stringResource(R.string.settings_agenda_range_bar), + checked = state.agendaShowRangeBar, + onCheckedChange = viewModel::setAgendaShowRangeBar, summary = stringResource(R.string.settings_agenda_range_bar_hint), position = Position.Bottom, - trailing = { - Switch( - checked = state.agendaShowRangeBar, - onCheckedChange = viewModel::setAgendaShowRangeBar, - ) - }, - onClick = { viewModel.setAgendaShowRangeBar(!state.agendaShowRangeBar) }, ) Spacer(Modifier.height(24.dp)) - SectionHeader(stringResource(R.string.settings_quick_switch_header)) - SettingsHint(stringResource(R.string.settings_quick_switch_hint)) + GroupedSectionHeader(stringResource(R.string.settings_quick_switch_header)) + GroupedHint(stringResource(R.string.settings_quick_switch_hint)) Spacer(Modifier.height(8.dp)) ReorderableColumn( items = config.order, @@ -299,8 +274,8 @@ internal fun ViewsScreen( } Spacer(Modifier.height(24.dp)) - SectionHeader(stringResource(R.string.settings_drawer_order_header)) - SettingsHint(stringResource(R.string.settings_drawer_order_hint)) + GroupedSectionHeader(stringResource(R.string.settings_drawer_order_header)) + GroupedHint(stringResource(R.string.settings_drawer_order_hint)) Spacer(Modifier.height(8.dp)) ReorderableColumn( items = state.drawerViewOrder, @@ -328,7 +303,7 @@ internal fun ViewsScreen( if (showDefaultView) { OptionPicker( title = stringResource(R.string.settings_default_view), - header = { PickerDescription(stringResource(R.string.settings_default_view_hint)) }, + header = { GroupedHint(stringResource(R.string.settings_default_view_hint), verticalPadding = 8.dp) }, predictiveBack = true, options = IMPLEMENTED_VIEWS, selected = state.defaultView, @@ -359,7 +334,7 @@ internal fun ViewsScreen( val systemIs24Hour = DateFormat.is24HourFormat(LocalContext.current) OptionPicker( title = stringResource(R.string.settings_time_format), - header = { PickerDescription(stringResource(R.string.settings_time_format_hint)) }, + header = { GroupedHint(stringResource(R.string.settings_time_format_hint), verticalPadding = 8.dp) }, predictiveBack = true, options = TimeFormatPref.entries, selected = state.timeFormat, @@ -387,6 +362,18 @@ internal fun ViewsScreen( onDismiss = { showTimeFormat = false }, ) } + if (showTapOpens) { + OptionPicker( + title = stringResource(R.string.settings_tap_opens), + header = { GroupedHint(stringResource(R.string.settings_tap_opens_hint), verticalPadding = 8.dp) }, + predictiveBack = true, + options = listOf(false, true), + selected = state.tapOpensEditor, + label = { tapOpensLabel(it) }, + onSelect = viewModel::setTapOpensEditor, + onDismiss = { showTapOpens = false }, + ) + } if (showPastEvents) { PastEventsPicker( selected = state.pastEventDisplay, @@ -397,7 +384,7 @@ internal fun ViewsScreen( if (showMultiDayCount) { OptionPicker( title = stringResource(R.string.settings_multi_day_count), - header = { PickerDescription(stringResource(R.string.settings_multi_day_count_hint)) }, + header = { GroupedHint(stringResource(R.string.settings_multi_day_count_hint), verticalPadding = 8.dp) }, predictiveBack = true, options = SettingsPrefs.MULTI_DAY_COUNTS.toList(), selected = state.multiDayCount, @@ -409,7 +396,7 @@ internal fun ViewsScreen( if (showTimelineScale) { OptionPicker( title = stringResource(R.string.settings_timeline_scale), - header = { PickerDescription(stringResource(R.string.settings_timeline_scale_hint)) }, + header = { GroupedHint(stringResource(R.string.settings_timeline_scale_hint), verticalPadding = 8.dp) }, predictiveBack = true, // A height pinched on the timeline is listed alongside the presets // rather than left as a silently unticked list: it is the current @@ -428,7 +415,7 @@ internal fun ViewsScreen( if (showHoursStart) { OptionPicker( title = stringResource(R.string.settings_visible_hours_start), - header = { PickerDescription(stringResource(R.string.settings_visible_hours_start_hint)) }, + header = { GroupedHint(stringResource(R.string.settings_visible_hours_start_hint), verticalPadding = 8.dp) }, predictiveBack = true, options = TimelineHours.startOptions(hours.endHour), selected = hours.startHour, @@ -440,7 +427,7 @@ internal fun ViewsScreen( if (showHoursEnd) { OptionPicker( title = stringResource(R.string.settings_visible_hours_end), - header = { PickerDescription(stringResource(R.string.settings_visible_hours_end_hint)) }, + header = { GroupedHint(stringResource(R.string.settings_visible_hours_end_hint), verticalPadding = 8.dp) }, predictiveBack = true, options = TimelineHours.endOptions(hours.startHour), selected = hours.endHour, @@ -518,10 +505,15 @@ private val WEEK_START_OPTIONS: List = internal fun weekStartLabel(pref: WeekStartPref): String = when (pref) { WeekStartPref.Auto -> stringResource(R.string.settings_week_start_auto) // Localised weekday name, so no per-day string resource is needed. - is WeekStartPref.Day -> java.time.DayOfWeek.of(pref.day.ordinal + 1) + is WeekStartPref.Day -> pref.day.toJavaDayOfWeek() .getDisplayName(JavaTextStyle.FULL, currentLocale()) } +@Composable +private fun tapOpensLabel(editor: Boolean): String = stringResource( + if (editor) R.string.settings_tap_opens_editor else R.string.settings_tap_opens_details, +) + @Composable private fun timeFormatLabel(pref: TimeFormatPref): String = stringResource( when (pref) { diff --git a/app/src/main/java/de/jeanlucmakiola/calendula/ui/settings/WeekStartPicker.kt b/app/src/main/java/de/jeanlucmakiola/calendula/ui/settings/WeekStartPicker.kt index 543a67bb..a7682fb7 100644 --- a/app/src/main/java/de/jeanlucmakiola/calendula/ui/settings/WeekStartPicker.kt +++ b/app/src/main/java/de/jeanlucmakiola/calendula/ui/settings/WeekStartPicker.kt @@ -8,14 +8,12 @@ import androidx.compose.ui.unit.dp import de.jeanlucmakiola.calendula.R import de.jeanlucmakiola.calendula.data.prefs.WeekStartPref import de.jeanlucmakiola.calendula.data.prefs.resolveFirstDay -import de.jeanlucmakiola.calendula.ui.common.PickerDescription -import de.jeanlucmakiola.calendula.ui.common.ViewPreviewFrame import de.jeanlucmakiola.calendula.ui.month.MonthStylePreview import de.jeanlucmakiola.calendula.ui.month.MonthViewStyle import de.jeanlucmakiola.floret.components.FullScreenPicker -import de.jeanlucmakiola.floret.components.GroupedRow -import de.jeanlucmakiola.floret.components.SelectedCheck -import de.jeanlucmakiola.floret.components.positionOf +import de.jeanlucmakiola.floret.components.GroupedHint +import de.jeanlucmakiola.floret.components.OptionRows +import de.jeanlucmakiola.floret.components.ViewPreviewFrame import de.jeanlucmakiola.floret.locale.currentLocale /** @@ -51,29 +49,23 @@ internal fun WeekStartPicker( height = PREVIEW_HEIGHT, ) } - PickerDescription(stringResource(R.string.settings_week_start_hint)) - options.forEachIndexed { index, option -> - val isSelected = option == selected - GroupedRow( - title = weekStartLabel(option), - summary = if (option == WeekStartPref.Auto) { + GroupedHint(stringResource(R.string.settings_week_start_hint), verticalPadding = 8.dp) + OptionRows( + options = options, + selected = selected, + label = { weekStartLabel(it) }, + onSelect = onSelect, + summary = { option -> + if (option == WeekStartPref.Auto) { stringResource( R.string.settings_week_start_auto_summary, weekStartLabel(WeekStartPref.Day(option.resolveFirstDay(locale))), ) } else { null - }, - position = positionOf(index, options.size), - selected = isSelected, - trailing = if (isSelected) { - { SelectedCheck() } - } else { - null - }, - onClick = { onSelect(option) }, - ) - } + } + }, + ) } } diff --git a/app/src/main/java/de/jeanlucmakiola/calendula/ui/settings/WidgetSettings.kt b/app/src/main/java/de/jeanlucmakiola/calendula/ui/settings/WidgetSettings.kt index d8301cc2..456efbe9 100644 --- a/app/src/main/java/de/jeanlucmakiola/calendula/ui/settings/WidgetSettings.kt +++ b/app/src/main/java/de/jeanlucmakiola/calendula/ui/settings/WidgetSettings.kt @@ -21,11 +21,11 @@ import de.jeanlucmakiola.calendula.R import de.jeanlucmakiola.calendula.data.prefs.resolveFirstDay import de.jeanlucmakiola.calendula.qs.NewEventTileService import de.jeanlucmakiola.calendula.ui.common.AgendaRangePicker -import de.jeanlucmakiola.calendula.ui.common.PickerDescription import de.jeanlucmakiola.calendula.ui.common.agendaRangeLabel import de.jeanlucmakiola.calendula.widget.WidgetSize import de.jeanlucmakiola.calendula.widget.agenda.metricsFor import de.jeanlucmakiola.floret.components.CollapsingScaffold +import de.jeanlucmakiola.floret.components.GroupedHint import de.jeanlucmakiola.floret.components.GroupedRow import de.jeanlucmakiola.floret.components.OptionPicker import de.jeanlucmakiola.floret.components.Position @@ -53,7 +53,7 @@ internal fun WidgetsScreen( predictiveBack = true, visible = visible, ) { - SettingsHint(stringResource(R.string.settings_widgets_hint)) + GroupedHint(stringResource(R.string.settings_widgets_hint)) Spacer(Modifier.height(8.dp)) GroupedRow( @@ -90,7 +90,7 @@ internal fun WidgetsScreen( if (showWidgetSize) { OptionPicker( title = stringResource(R.string.settings_widget_size), - header = { PickerDescription(stringResource(R.string.settings_widget_size_hint)) }, + header = { GroupedHint(stringResource(R.string.settings_widget_size_hint), verticalPadding = 8.dp) }, predictiveBack = true, options = WidgetSize.entries, selected = state.widgetSize, diff --git a/app/src/main/java/de/jeanlucmakiola/calendula/ui/theme/Theme.kt b/app/src/main/java/de/jeanlucmakiola/calendula/ui/theme/Theme.kt index 5e56f5b2..e7908610 100644 --- a/app/src/main/java/de/jeanlucmakiola/calendula/ui/theme/Theme.kt +++ b/app/src/main/java/de/jeanlucmakiola/calendula/ui/theme/Theme.kt @@ -16,13 +16,15 @@ import de.jeanlucmakiola.floret.identity.FloretExpressiveTheme * * The mechanics live in floret-kit's identity module; the look stays here, so a * sibling app reuses the same theming without inheriting Calendula's palette. - * The Settings screen overrides darkTheme, dynamicColor and typography; the bare - * defaults (used by the crash screen) just follow the system. + * The Settings screen overrides darkTheme, dynamicColor, pureBlack (the + * AMOLED theme, #181) and typography; the bare defaults (used by the crash + * screen) just follow the system. */ @Composable fun CalendulaTheme( darkTheme: Boolean = isSystemInDarkTheme(), dynamicColor: Boolean = true, + pureBlack: Boolean = false, typography: Typography = CalendulaTypography, content: @Composable () -> Unit, ) { @@ -31,6 +33,7 @@ fun CalendulaTheme( darkScheme = CalendulaDarkFallback, darkTheme = darkTheme, dynamicColor = dynamicColor, + pureBlack = pureBlack, typography = typography, content = content, ) diff --git a/app/src/main/java/de/jeanlucmakiola/calendula/ui/theme/WindowTheme.kt b/app/src/main/java/de/jeanlucmakiola/calendula/ui/theme/WindowTheme.kt new file mode 100644 index 00000000..31edbb44 --- /dev/null +++ b/app/src/main/java/de/jeanlucmakiola/calendula/ui/theme/WindowTheme.kt @@ -0,0 +1,59 @@ +package de.jeanlucmakiola.calendula.ui.theme + +import android.content.Context +import androidx.annotation.ColorRes +import androidx.core.content.edit +import de.jeanlucmakiola.calendula.R +import de.jeanlucmakiola.floret.prefs.ThemeMode + +/** + * A synchronous copy of the theme and dynamic-colour choices, for the window + * backdrop and the first Compose frame. The real setting lives in DataStore, which only + * answers asynchronously — too late for onCreate, so a Light, Dark or Black + * override flashed the night-qualifier backdrop on a cold start or a + * recreation (#181). MainActivity mirrors every stored value here and reads it + * back before setContent. + */ +internal object WindowThemeCache { + + private const val FILE = "window_theme" + private const val KEY_THEME_MODE = "theme_mode" + private const val KEY_DYNAMIC_COLOR = "dynamic_color" + + /** The last mirrored theme choice, or null before the first mirror. */ + fun read(context: Context): ThemeMode? = + context.getSharedPreferences(FILE, Context.MODE_PRIVATE) + .getString(KEY_THEME_MODE, null) + ?.let { name -> ThemeMode.entries.firstOrNull { it.name == name } } + + /** The last mirrored dynamic-colour choice, or null before the first mirror. */ + fun readDynamicColor(context: Context): Boolean? { + val prefs = context.getSharedPreferences(FILE, Context.MODE_PRIVATE) + return if (prefs.contains(KEY_DYNAMIC_COLOR)) prefs.getBoolean(KEY_DYNAMIC_COLOR, true) else null + } + + fun write(context: Context, mode: ThemeMode, dynamicColor: Boolean) { + val prefs = context.getSharedPreferences(FILE, Context.MODE_PRIVATE) + if (prefs.getString(KEY_THEME_MODE, null) == mode.name && + prefs.contains(KEY_DYNAMIC_COLOR) && prefs.getBoolean(KEY_DYNAMIC_COLOR, true) == dynamicColor + ) { + return + } + prefs.edit { + putString(KEY_THEME_MODE, mode.name) + putBoolean(KEY_DYNAMIC_COLOR, dynamicColor) + } + } +} + +/** + * The window backdrop matching this theme choice's Compose background, or null + * for [ThemeMode.SYSTEM], whose night-qualified theme default already matches. + */ +@ColorRes +internal fun ThemeMode.windowBackgroundRes(): Int? = when (this) { + ThemeMode.SYSTEM -> null + ThemeMode.LIGHT -> R.color.window_background_light + ThemeMode.DARK -> R.color.window_background_dark + ThemeMode.BLACK -> R.color.window_background_black +} diff --git a/app/src/main/java/de/jeanlucmakiola/calendula/ui/week/TimelineActions.kt b/app/src/main/java/de/jeanlucmakiola/calendula/ui/week/TimelineActions.kt new file mode 100644 index 00000000..2a0e69c5 --- /dev/null +++ b/app/src/main/java/de/jeanlucmakiola/calendula/ui/week/TimelineActions.kt @@ -0,0 +1,57 @@ +package de.jeanlucmakiola.calendula.ui.week + +import androidx.compose.foundation.ScrollState +import androidx.compose.runtime.Composable +import androidx.compose.runtime.Stable +import androidx.compose.runtime.remember +import androidx.compose.runtime.rememberUpdatedState +import de.jeanlucmakiola.calendula.domain.EventInstance +import de.jeanlucmakiola.calendula.ui.common.TimelineDragController +import de.jeanlucmakiola.calendula.ui.common.TimelineDrop +import de.jeanlucmakiola.calendula.ui.common.TimelineResizeDrop +import kotlinx.datetime.LocalDate + +/** + * What every timeline page hands down to its day columns: the shared vertical + * scroll, the drag controller, and the callbacks. One instance per screen, so + * passing it never makes a page recompose. + */ +@Stable +internal class TimelineActions( + val scrollState: ScrollState, + val dragController: TimelineDragController, + val onEventClick: (EventInstance) -> Unit, + val onOpenDay: (LocalDate) -> Unit, + val onCreateAt: (LocalDate, Int) -> Unit, + val onDrop: (TimelineDrop) -> Unit, + val onResize: (TimelineResizeDrop) -> Unit, +) + +/** The callbacks are read through their latest values, so the holder outlives them. */ +@Composable +internal fun rememberTimelineActions( + scrollState: ScrollState, + dragController: TimelineDragController, + onEventClick: (EventInstance) -> Unit, + onOpenDay: (LocalDate) -> Unit, + onCreateAt: (LocalDate, Int) -> Unit, + onDrop: (TimelineDrop) -> Unit, + onResize: (TimelineResizeDrop) -> Unit, +): TimelineActions { + val eventClick = rememberUpdatedState(onEventClick) + val openDay = rememberUpdatedState(onOpenDay) + val createAt = rememberUpdatedState(onCreateAt) + val drop = rememberUpdatedState(onDrop) + val resize = rememberUpdatedState(onResize) + return remember(scrollState, dragController) { + TimelineActions( + scrollState = scrollState, + dragController = dragController, + onEventClick = { eventClick.value(it) }, + onOpenDay = { openDay.value(it) }, + onCreateAt = { date, minutes -> createAt.value(date, minutes) }, + onDrop = { drop.value(it) }, + onResize = { resize.value(it) }, + ) + } +} diff --git a/app/src/main/java/de/jeanlucmakiola/calendula/ui/week/WeekPaging.kt b/app/src/main/java/de/jeanlucmakiola/calendula/ui/week/WeekPaging.kt index e19ed1ee..150b3f43 100644 --- a/app/src/main/java/de/jeanlucmakiola/calendula/ui/week/WeekPaging.kt +++ b/app/src/main/java/de/jeanlucmakiola/calendula/ui/week/WeekPaging.kt @@ -1,105 +1,69 @@ package de.jeanlucmakiola.calendula.ui.week +import de.jeanlucmakiola.calendula.ui.common.startOfWeek import kotlinx.datetime.DateTimeUnit import kotlinx.datetime.DayOfWeek import kotlinx.datetime.LocalDate import kotlinx.datetime.daysUntil import kotlinx.datetime.plus -/** Pages the week pager spans — a little under four centuries, centred on [PAGE_EPOCH]. */ +/** Pages the week pager spans — a little under four centuries. */ internal const val WEEK_PAGE_COUNT: Int = 20_000 -private const val EPOCH_PAGE = WEEK_PAGE_COUNT / 2 - -/** The week at [EPOCH_PAGE]; any date works, it only has to stay fixed. */ -private val PAGE_EPOCH = LocalDate(2000, 1, 3) - -/** First day of the week shown on pager [page], with weeks starting on [firstDay]. */ -internal fun weekStartForPage(page: Int, firstDay: DayOfWeek): LocalDate = - PAGE_EPOCH.startOfWeek(firstDay).plus((page - EPOCH_PAGE) * 7, DateTimeUnit.DAY) - -/** The pager page whose week contains [date], with weeks starting on [firstDay]. */ -internal fun weekPageFor(date: LocalDate, firstDay: DayOfWeek): Int { - val days = PAGE_EPOCH.startOfWeek(firstDay).daysUntil(date.startOfWeek(firstDay)) - return (EPOCH_PAGE + days / 7).coerceIn(0, WEEK_PAGE_COUNT - 1) -} - -/** How a timeline pager cuts the calendar into pages of [dayCount] days. */ -sealed interface PageGrid { - val dayCount: Int - val pageCount: Int - - /** First day shown on pager [page]. */ - fun startForPage(page: Int): LocalDate - - /** The pager page showing [date]. */ - fun pageFor(date: LocalDate): Int -} - -/** Whole weeks, starting on [firstDay]. */ -data class WeekGrid(val firstDay: DayOfWeek) : PageGrid { - override val dayCount: Int get() = 7 - override val pageCount: Int get() = WEEK_PAGE_COUNT - override fun startForPage(page: Int): LocalDate = weekStartForPage(page, firstDay) - override fun pageFor(date: LocalDate): Int = weekPageFor(date, firstDay) -} - /** Pages the multi-day pager spans — over three centuries at the widest page. */ internal const val DAYS_PAGE_COUNT: Int = 40_000 -private const val DAYS_EPOCH_PAGE = DAYS_PAGE_COUNT / 2 +/** Pages the day pager spans — a little under four centuries. */ +internal const val DAY_PAGE_COUNT: Int = 140_000 -/** A fixed day the multi-day pages are counted from. */ +/** A fixed day every grid's pages are counted from, at its middle page. */ private val DAYS_EPOCH = LocalDate(2000, 1, 1) +/** The week the week pager's middle page shows; any date works, it only has to stay fixed. */ +private val WEEK_EPOCH = LocalDate(2000, 1, 3) + /** - * Runs of [dayCount] days (#193), offset [phase] days from a fixed epoch so any - * date can start a page. The phase stays put while paging and only changes when - * a jump moves another date to the first column. + * How a timeline pager cuts the calendar: runs of [dayCount] days, offset + * [phase] days from a fixed epoch, over [pageCount] pages centred on it. The + * multi-day view's phase (#193) stays put while paging and only changes when a + * jump moves another date to the first column. */ -data class DaysGrid(override val dayCount: Int, val phase: Int) : PageGrid { - override val pageCount: Int get() = DAYS_PAGE_COUNT +data class DaysGrid(val dayCount: Int, val phase: Int, val pageCount: Int = DAYS_PAGE_COUNT) { - override fun startForPage(page: Int): LocalDate = - DAYS_EPOCH.plus(phase + (page - DAYS_EPOCH_PAGE) * dayCount, DateTimeUnit.DAY) + private val epochPage: Int get() = pageCount / 2 - override fun pageFor(date: LocalDate): Int = - (DAYS_EPOCH_PAGE + Math.floorDiv(DAYS_EPOCH.daysUntil(date) - phase, dayCount)) - .coerceIn(0, DAYS_PAGE_COUNT - 1) + /** First day shown on pager [page]. */ + fun startForPage(page: Int): LocalDate = + DAYS_EPOCH.plus(phase + (page - epochPage) * dayCount, DateTimeUnit.DAY) + + /** The pager page showing [date]. */ + fun pageFor(date: LocalDate): Int = + (epochPage + Math.floorDiv(DAYS_EPOCH.daysUntil(date) - phase, dayCount)) + .coerceIn(0, pageCount - 1) companion object { + /** Single days: every date starts a page of its own. */ + val days: DaysGrid = DaysGrid(dayCount = 1, phase = 0, pageCount = DAY_PAGE_COUNT) + + /** Whole weeks, starting on [firstDay]. */ + fun weeks(firstDay: DayOfWeek): DaysGrid = DaysGrid( + dayCount = 7, + phase = DAYS_EPOCH.daysUntil(WEEK_EPOCH.startOfWeek(firstDay)), + pageCount = WEEK_PAGE_COUNT, + ) + /** The grid of [dayCount]-day pages on which [date] is a page's first day. */ fun startingAt(date: LocalDate, dayCount: Int): DaysGrid = DaysGrid(dayCount, Math.floorMod(DAYS_EPOCH.daysUntil(date), dayCount)) } } -/** Pages the day pager spans — a little under four centuries, centred on [DAY_EPOCH]. */ -internal const val DAY_PAGE_COUNT: Int = 140_000 - -private const val DAY_EPOCH_PAGE = DAY_PAGE_COUNT / 2 - -/** The day at [DAY_EPOCH_PAGE]; any date works, it only has to stay fixed. */ -private val DAY_EPOCH = LocalDate(2000, 1, 1) - -/** Single days: every date starts a page of its own. */ -data object DayGrid : PageGrid { - override val dayCount: Int get() = 1 - override val pageCount: Int get() = DAY_PAGE_COUNT - - override fun startForPage(page: Int): LocalDate = - DAY_EPOCH.plus(page - DAY_EPOCH_PAGE, DateTimeUnit.DAY) - - override fun pageFor(date: LocalDate): Int = - (DAY_EPOCH_PAGE + DAY_EPOCH.daysUntil(date)).coerceIn(0, DAY_PAGE_COUNT - 1) -} - /** * Where the focused date goes when the pager settles on [page] (#184): kept if * the page still shows it, otherwise moved by the pages travelled, so it keeps * its place in the page — the same weekday a week on. */ -internal fun PageGrid.focusOnPage(focus: LocalDate, page: Int): LocalDate { +internal fun DaysGrid.focusOnPage(focus: LocalDate, page: Int): LocalDate { val start = startForPage(page) val end = start.plus(dayCount - 1, DateTimeUnit.DAY) if (focus in start..end) return focus diff --git a/app/src/main/java/de/jeanlucmakiola/calendula/ui/week/WeekScreen.kt b/app/src/main/java/de/jeanlucmakiola/calendula/ui/week/WeekScreen.kt index 384ed636..43a668c3 100644 --- a/app/src/main/java/de/jeanlucmakiola/calendula/ui/week/WeekScreen.kt +++ b/app/src/main/java/de/jeanlucmakiola/calendula/ui/week/WeekScreen.kt @@ -20,12 +20,12 @@ import de.jeanlucmakiola.calendula.ui.common.rememberCalendarPageSpec import de.jeanlucmakiola.calendula.ui.common.rememberViewSwitchSpec import de.jeanlucmakiola.calendula.ui.common.jumpToPage import de.jeanlucmakiola.calendula.ui.common.pagedHeight +import de.jeanlucmakiola.floret.identity.LocalFloretDarkTheme import kotlinx.coroutines.flow.StateFlow import kotlinx.coroutines.flow.drop import androidx.compose.foundation.background import androidx.compose.foundation.clickable import androidx.compose.foundation.gestures.detectTapGestures -import androidx.compose.foundation.isSystemInDarkTheme import androidx.compose.foundation.layout.Box import androidx.compose.foundation.layout.BoxWithConstraints import androidx.compose.foundation.layout.Column @@ -39,7 +39,6 @@ import androidx.compose.foundation.layout.offset import androidx.compose.foundation.layout.padding import androidx.compose.foundation.layout.size import androidx.compose.foundation.layout.width -import androidx.compose.foundation.ScrollState import androidx.compose.foundation.rememberScrollState import androidx.compose.foundation.shape.CircleShape import androidx.compose.foundation.shape.RoundedCornerShape @@ -52,6 +51,7 @@ import androidx.compose.material3.Surface import androidx.compose.material3.Text import androidx.compose.runtime.Composable import androidx.compose.runtime.CompositionLocalProvider +import androidx.compose.runtime.staticCompositionLocalOf import androidx.compose.runtime.LaunchedEffect import androidx.compose.runtime.derivedStateOf import androidx.compose.runtime.key @@ -59,11 +59,37 @@ import androidx.compose.runtime.remember import androidx.compose.runtime.rememberCoroutineScope import androidx.compose.runtime.rememberUpdatedState import androidx.compose.runtime.snapshotFlow +import androidx.activity.compose.BackHandler +import androidx.compose.ui.hapticfeedback.HapticFeedbackType +import androidx.compose.ui.platform.LocalHapticFeedback +import androidx.compose.ui.zIndex +import androidx.compose.ui.geometry.Offset +import androidx.compose.ui.graphics.toArgb +import de.jeanlucmakiola.calendula.ui.common.draftBlock +import de.jeanlucmakiola.calendula.ui.common.draftEvent +import de.jeanlucmakiola.calendula.ui.common.draftStartMin +import de.jeanlucmakiola.calendula.ui.common.isDraft +import de.jeanlucmakiola.calendula.ui.common.rememberDragSurface +import de.jeanlucmakiola.calendula.ui.common.rememberWriteAction +import de.jeanlucmakiola.calendula.ui.common.OutOfViewEdges +import de.jeanlucmakiola.calendula.ui.common.wallClockInstant +import de.jeanlucmakiola.calendula.ui.common.PickUp +import de.jeanlucmakiola.calendula.ui.common.SelectionBarClearance +import de.jeanlucmakiola.calendula.ui.common.ResizeEdge +import de.jeanlucmakiola.calendula.ui.common.ResizeHandle +import de.jeanlucmakiola.calendula.ui.common.ResizeHandleTarget +import de.jeanlucmakiola.calendula.ui.common.TimelineResizeDrop +import de.jeanlucmakiola.calendula.ui.common.eventAccent +import de.jeanlucmakiola.calendula.ui.common.LocalSoftenColors +import de.jeanlucmakiola.calendula.ui.common.PublishSelection +import de.jeanlucmakiola.calendula.ui.common.eventSelectAllowed +import de.jeanlucmakiola.calendula.ui.common.selectionLift import androidx.compose.ui.Alignment import androidx.compose.ui.BiasAlignment import androidx.compose.ui.Modifier import de.jeanlucmakiola.calendula.ui.common.LocalViewMorph import de.jeanlucmakiola.calendula.ui.common.StayPut +import kotlinx.coroutines.delay import kotlinx.coroutines.withTimeoutOrNull import kotlinx.coroutines.flow.first import androidx.compose.runtime.withFrameNanos @@ -73,12 +99,14 @@ import androidx.compose.runtime.SideEffect import de.jeanlucmakiola.calendula.ui.common.laneSlot import de.jeanlucmakiola.calendula.ui.common.LaneColumn import kotlin.math.roundToInt +import kotlin.time.Instant import androidx.compose.ui.unit.Constraints import androidx.compose.ui.layout.Layout import androidx.compose.ui.draw.alpha import androidx.compose.ui.draw.clip import androidx.compose.ui.draw.clipToBounds import androidx.compose.ui.graphics.graphicsLayer +import androidx.compose.animation.core.animateFloatAsState import androidx.compose.ui.layout.layout import androidx.compose.ui.graphics.RectangleShape import androidx.compose.ui.input.pointer.pointerInput @@ -98,7 +126,6 @@ import androidx.hilt.navigation.compose.hiltViewModel import androidx.lifecycle.compose.collectAsStateWithLifecycle import de.jeanlucmakiola.calendula.R import de.jeanlucmakiola.calendula.domain.EventInstance -import de.jeanlucmakiola.calendula.domain.hasEnded import de.jeanlucmakiola.calendula.ui.common.LocalChipGround import de.jeanlucmakiola.calendula.ui.common.eventPaint import de.jeanlucmakiola.calendula.ui.common.eventSurface @@ -135,6 +162,7 @@ import de.jeanlucmakiola.calendula.ui.common.rememberEventDragSource import de.jeanlucmakiola.calendula.ui.common.rememberTimelineDragController import de.jeanlucmakiola.calendula.ui.common.startInstant import de.jeanlucmakiola.calendula.ui.common.LocalDimCutoff +import de.jeanlucmakiola.calendula.ui.common.isPastOn import de.jeanlucmakiola.calendula.ui.common.EventChipShape import de.jeanlucmakiola.calendula.ui.common.trimmedLines import de.jeanlucmakiola.calendula.ui.common.NowLine @@ -173,10 +201,12 @@ import kotlinx.coroutines.launch import kotlinx.datetime.LocalDate import kotlinx.datetime.TimeZone import kotlinx.datetime.plus +import kotlinx.datetime.toJavaDayOfWeek import kotlinx.datetime.toJavaLocalDate import kotlinx.datetime.toLocalDateTime import java.time.format.TextStyle as JavaTextStyle import java.util.Locale +import kotlinx.datetime.yearMonth /** One lane of the all-day strip, sized to a trimmed bar line (#190). */ private val ALL_DAY_ROW_HEIGHT = 20.dp @@ -221,6 +251,7 @@ fun TimelineScreen( onOpenDay: (LocalDate) -> Unit, onEventClick: (EventInstance) -> Unit, onCreateEvent: (LocalDate, Int?) -> Unit, + onCreateDraft: (Instant, Instant) -> Unit, modifier: Modifier = Modifier, weekViewModel: WeekViewModel = hiltViewModel(), multiDayViewModel: MultiDayViewModel = hiltViewModel(), @@ -235,6 +266,7 @@ fun TimelineScreen( onOpenDay = onOpenDay, onEventClick = onEventClick, onCreateEvent = onCreateEvent, + onCreateDraft = onCreateDraft, modifier = modifier, ) } @@ -281,6 +313,12 @@ internal val CalendarView.timelineKind: TimelineKind else -> TimelineKind.Week } +/** + * The zone the shown timeline is laid out in, so its blocks, drags and drops all + * read the same wall clock (#387). + */ +internal val LocalTimelineZone = staticCompositionLocalOf { TimeZone.currentSystemDefault() } + /** How long a switch waits for the view it goes to before resizing into it without its events. */ private const val MORPH_DATA_WAIT_MS = 150L @@ -292,6 +330,7 @@ private fun PagedTimelineScreen( onOpenDay: (LocalDate) -> Unit, onEventClick: (EventInstance) -> Unit, onCreateEvent: (LocalDate, Int?) -> Unit, + onCreateDraft: (Instant, Instant) -> Unit, modifier: Modifier, ) { // The view on screen, which trails [view] while the columns resize into it. @@ -324,6 +363,7 @@ private fun PagedTimelineScreen( val grid = position.grid val anchorPage = position.page val dimCompleted by key(viewModel) { viewModel.dimCompletedEvents.collectAsStateWithLifecycle() } + val draftMinutes by key(viewModel) { viewModel.defaultEventDuration.collectAsStateWithLifecycle() } // The instant before which an event counts as completed, or null when dimming // is off. derivedStateOf keeps the per-minute "now" from recomposing the // screen while the setting is off (it stays null regardless of the tick). @@ -417,17 +457,19 @@ private fun PagedTimelineScreen( // Off the ticking clock rather than the loaded page, so it turns over at // midnight; derived, so the per-minute tick doesn't recompose the screen. - val zone = remember { TimeZone.currentSystemDefault() } + // The timeline's own zone, so "today" agrees with the blocks and drops (#387). + val zone by viewModel.zone.collectAsStateWithLifecycle() val today by remember(zone) { derivedStateOf { nowState.value.toLocalDateTime(zone).date } } val isOnCurrentWeek = state !is WeekUiState.Success || (today >= weekStart && today <= weekEnd) // Straight to the pager: a tap mid-fling must still land, and the anchor // hasn't caught up with the fling yet to tell the difference. A date that - // would open mid-page on this grid re-frames the pages around it instead. + // would open mid-page on this grid, in a view that frames its pages from the + // date (multi-day), re-frames the pages around it instead. val jumpToDate: (LocalDate) -> Unit = { target -> focus?.date = target val page = grid.pageFor(target) - if (grid is DaysGrid && grid.startForPage(page) != target) { + if (grid.startForPage(page) != target && viewModel.rule.value(target) != grid) { viewModel.jumpTo(target) } else { scope.launch { pagerState.jumpToPage(page, reduceMotion, pageSpec) } @@ -458,7 +500,10 @@ private fun PagedTimelineScreen( ) ScreenBody(modifier = modifier) { innerPadding -> - CompositionLocalProvider(LocalDimCutoff provides dimCutoff) { + CompositionLocalProvider( + LocalDimCutoff provides dimCutoff, + LocalTimelineZone provides zone, + ) { WeekContent( state = state, today = today, @@ -471,7 +516,9 @@ private fun PagedTimelineScreen( onRetry = viewModel::goToToday, onEventClick = onEventClick, onOpenDay = onOpenDay, - onCreateAt = { d, minutes -> onCreateEvent(d, minutes) }, + onCreateAt = onCreateEvent, + onCreateDraft = onCreateDraft, + draftMinutes = draftMinutes, modifier = Modifier .padding(innerPadding) .fillMaxSize(), @@ -485,7 +532,7 @@ private fun WeekContent( state: WeekUiState, today: LocalDate, pagerState: PagerState, - grid: PageGrid, + grid: DaysGrid, kind: TimelineKind, morph: TimelineMorph?, handoffStrip: Dp?, @@ -494,6 +541,8 @@ private fun WeekContent( onEventClick: (EventInstance) -> Unit, onOpenDay: (LocalDate) -> Unit, onCreateAt: (LocalDate, Int) -> Unit, + onCreateDraft: (Instant, Instant) -> Unit, + draftMinutes: Int, modifier: Modifier = Modifier, ) { val fadeSpec = rememberCalendarFadeSpec() @@ -508,19 +557,112 @@ private fun WeekContent( // Above the pager: a page change mid-drag would strand the floating block // inside the outgoing page. val dragController = rememberTimelineDragController() + SideEffect { dragController.draftMinutes = draftMinutes } val move = LocalEventMove.current - val zone = remember { TimeZone.currentSystemDefault() } - val onDrop: (TimelineDrop) -> Unit = { drop -> + val zone = LocalTimelineZone.current + val onDrop: (TimelineDrop) -> Unit = drop@{ drop -> + val start = drop.startInstant(zone) + val moved = drop.event.copy(start = start, end = start + (drop.event.end - drop.event.start)) + // A draft has nothing to write, so it stays selected where it landed (#153). + if (drop.event.isDraft) { + dragController.select(moved) + return@drop + } + // A selected event stays selected where it landed (#141). + if (dragController.selection?.event?.instanceId == drop.event.instanceId) { + dragController.select(moved, moved = true) + } move?.move( MoveRequest( eventId = drop.event.eventId, beginMillis = drop.event.start.toEpochMilliseconds(), endMillis = drop.event.end.toEpochMilliseconds(), - target = MoveTarget.Start(drop.startInstant(zone)), + target = MoveTarget.Start(start), ), ) } + // A resize keeps its event selected, at its new length (#141). + val onResize: (TimelineResizeDrop) -> Unit = resize@{ drop -> + val resized = drop.event.copy(start = drop.start, end = drop.end) + if (drop.event.isDraft) { + dragController.select(resized) + return@resize + } + // Still lifted under its copy, so it takes over without the ghost's fade-in dip. + dragController.select(resized, moved = true, fromLift = true) + move?.move( + MoveRequest( + eventId = drop.event.eventId, + beginMillis = drop.event.start.toEpochMilliseconds(), + endMillis = drop.event.end.toEpochMilliseconds(), + target = MoveTarget.Span(drop.start, drop.end), + ), + ) + } + + // A drafted block (#153) opens the new-event form at its own instants: the + // end it is drawn to differs on a DST change (#387). + val createDraft: (EventInstance) -> Unit = { draft -> + dragController.deselect() + onCreateDraft(draft.start, draft.end) + } + + // Selection (#141) ends on back, a page or view change, or any tap. + val selection = dragController.selection + PublishSelection( + event = selection?.event, + busy = dragController.isDragging, + compact = dragController.selectionCovered, + onDismiss = dragController::deselect, + onCreate = selection?.event?.takeIf { it.isDraft }?.let { draft -> { createDraft(draft) } }, + preview = { dragController.preview(zone) }, + ) + BackHandler(enabled = selection != null) { dragController.deselect() } + LaunchedEffect(pagerState, dragController) { + snapshotFlow { pagerState.currentPage }.drop(1).collect { + // Deselecting would delete a draft mid-drag, so it stays until it lands. + val draftInFlight = dragController.isDragging && dragController.selection?.event?.isDraft == true + if (!draftInFlight) dragController.deselect() + } + } + LaunchedEffect(morph != null) { if (morph != null) dragController.deselect() } + LaunchedEffect(selection, dragController.settling, dragController.isDragging, dragController.selectedCandidates.size) { + dragController.settleMovedSelection() + } + val orphaned = selection != null && dragController.selectedCandidates.isEmpty() && + !dragController.isDragging && dragController.settling == null + LaunchedEffect(orphaned) { + if (!orphaned) return@LaunchedEffect + // A beat for a re-read to bring the event back under a new row. + delay(SELECTION_ORPHAN_GRACE_MILLIS) + dragController.deselect() + } + var pendingDraft by remember { mutableStateOf(null) } + val createPendingDraft = rememberWriteAction { + pendingDraft?.let(createDraft) + pendingDraft = null + } + val openEvent: (EventInstance) -> Unit = { event -> + if (event.isDraft) { + pendingDraft = event + createPendingDraft() + } else { + dragController.deselect() + onEventClick(event) + } + } + + val actions = rememberTimelineActions( + scrollState = scrollState, + dragController = dragController, + onEventClick = openEvent, + onOpenDay = onOpenDay, + onCreateAt = onCreateAt, + onDrop = onDrop, + onResize = onResize, + ) + Box(modifier = modifier) { CompositionLocalProvider(LocalOpeningTimeline provides timelineScroll) { // Loading and failure concern the provider as a whole, so they stand in @@ -536,16 +678,7 @@ private fun WeekContent( WeekUiState.Loading -> WeekLoading(dayCount = grid.dayCount) is WeekUiState.Failure -> CalendarFailure(reason = s.reason, onRetry = onRetry) is WeekUiState.Success -> if (morph != null) { - TimelineMorphFrame( - morph = morph, - today = today, - scrollState = scrollState, - dragController = dragController, - onEventClick = onEventClick, - onOpenDay = onOpenDay, - onCreateAt = onCreateAt, - onDrop = onDrop, - ) + TimelineMorphFrame(morph = morph, today = today, actions = actions) } else WeekPager( pagerState = pagerState, grid = grid, @@ -553,12 +686,7 @@ private fun WeekContent( span = span, today = today, initialStripHeight = handoffStrip ?: s.allDayStripHeight(), - scrollState = scrollState, - dragController = dragController, - onEventClick = onEventClick, - onOpenDay = onOpenDay, - onCreateAt = onCreateAt, - onDrop = onDrop, + actions = actions, ) } } @@ -574,26 +702,21 @@ private fun WeekContent( @Composable private fun WeekPager( pagerState: PagerState, - grid: PageGrid, + grid: DaysGrid, kind: TimelineKind, span: (DaySpan) -> StateFlow, today: LocalDate, initialStripHeight: Dp, - scrollState: ScrollState, - dragController: TimelineDragController, - onEventClick: (EventInstance) -> Unit, - onOpenDay: (LocalDate) -> Unit, - onCreateAt: (LocalDate, Int) -> Unit, - onDrop: (TimelineDrop) -> Unit, + actions: TimelineActions, ) { + val dragController = actions.dragController val stripHeights = remember { mutableStateMapOf() } val allDayHeight = pagedHeight(pagerState, stripHeights, initialStripHeight) WeekFrame( weekStart = grid.startForPage(pagerState.currentPage), showWeekNumber = kind.showWeekNumber, allDayHeight = allDayHeight, - scrollState = scrollState, - dragController = dragController, + actions = actions, ) { HorizontalPager( state = pagerState, @@ -626,13 +749,8 @@ private fun WeekPager( }, headerBias = kind.headerBias, allDayHeight = allDayHeight, - scrollState = scrollState, - dragController = dragController, + actions = actions, active = page == pagerState.currentPage, - onEventClick = onEventClick, - onOpenDay = onOpenDay, - onCreateAt = onCreateAt, - onDrop = onDrop, ) } } @@ -661,12 +779,7 @@ private fun emptySpan(span: DaySpan, today: LocalDate): WeekUiState.Success { private fun TimelineMorphFrame( morph: TimelineMorph, today: LocalDate, - scrollState: ScrollState, - dragController: TimelineDragController, - onEventClick: (EventInstance) -> Unit, - onOpenDay: (LocalDate) -> Unit, - onCreateAt: (LocalDate, Int) -> Unit, - onDrop: (TimelineDrop) -> Unit, + actions: TimelineActions, ) { val fromState by morph.fromState.collectAsStateWithLifecycle() val toState by morph.toState.collectAsStateWithLifecycle() @@ -704,8 +817,7 @@ private fun TimelineMorphFrame( allDayHeight = fromStrip, animatedAllDayHeight = animatedStrip, weekNumberAlpha = badgeAlpha, - scrollState = scrollState, - dragController = dragController, + actions = actions, ) { TimelinePageContent( geometry = geometry, @@ -715,13 +827,8 @@ private fun TimelineMorphFrame( headerBias = headerBias, allDayHeight = fromStrip, animatedAllDayHeight = animatedStrip, - scrollState = scrollState, - dragController = dragController, + actions = actions, active = false, - onEventClick = onEventClick, - onOpenDay = onOpenDay, - onCreateAt = onCreateAt, - onDrop = onDrop, ) } } @@ -755,8 +862,7 @@ private fun WeekFrame( allDayHeight: Dp, animatedAllDayHeight: (() -> Dp)? = null, weekNumberAlpha: () -> Float = { 1f }, - scrollState: ScrollState, - dragController: TimelineDragController, + actions: TimelineActions, pages: @Composable () -> Unit, ) { val gutterFullHeight = remember(animatedAllDayHeight) { intArrayOf(-1) } @@ -790,10 +896,10 @@ private fun WeekFrame( else maxHeight val hourHeight = zoom.scale.hourHeight(fitHeight) HourGutter( - scrollState = scrollState, + scrollState = actions.scrollState, hourHeight = hourHeight, - dragController = dragController, - modifier = rememberTimelinePinchZoom(scrollState, fitHeight, hourHeight, zoom), + dragController = actions.dragController, + modifier = rememberTimelinePinchZoom(actions.scrollState, fitHeight, hourHeight, zoom), ) } } @@ -808,32 +914,21 @@ internal fun WeekSuccess( state: WeekUiState.Success, showWeekNumber: Boolean = true, headerBias: Float = 0f, - scrollState: ScrollState, allDayHeight: Dp, - dragController: TimelineDragController, - onEventClick: (EventInstance) -> Unit, - onOpenDay: (LocalDate) -> Unit, - onCreateAt: (LocalDate, Int) -> Unit, - onDrop: (TimelineDrop) -> Unit, + actions: TimelineActions, ) { WeekFrame( weekStart = state.weekStart, showWeekNumber = showWeekNumber, allDayHeight = allDayHeight, - scrollState = scrollState, - dragController = dragController, + actions = actions, ) { WeekPage( state = state, headerBias = headerBias, allDayHeight = allDayHeight, - scrollState = scrollState, - dragController = dragController, + actions = actions, active = true, - onEventClick = onEventClick, - onOpenDay = onOpenDay, - onCreateAt = onCreateAt, - onDrop = onDrop, ) } } @@ -849,13 +944,8 @@ private fun WeekPage( state: WeekUiState.Success, headerBias: Float, allDayHeight: Dp, - scrollState: ScrollState, - dragController: TimelineDragController, + actions: TimelineActions, active: Boolean, - onEventClick: (EventInstance) -> Unit, - onOpenDay: (LocalDate) -> Unit, - onCreateAt: (LocalDate, Int) -> Unit, - onDrop: (TimelineDrop) -> Unit, ) { val geometry = remember(state.weekStart, state.days.size) { ColumnGeometry.of(DaySpan(state.weekStart, state.days.size)) @@ -868,13 +958,8 @@ private fun WeekPage( bars = bars, headerBias = headerBias, allDayHeight = allDayHeight, - scrollState = scrollState, - dragController = dragController, + actions = actions, active = active, - onEventClick = onEventClick, - onOpenDay = onOpenDay, - onCreateAt = onCreateAt, - onDrop = onDrop, ) } @@ -891,13 +976,8 @@ private fun TimelinePageContent( headerBias: Float, allDayHeight: Dp, animatedAllDayHeight: (() -> Dp)? = null, - scrollState: ScrollState, - dragController: TimelineDragController, + actions: TimelineActions, active: Boolean, - onEventClick: (EventInstance) -> Unit, - onOpenDay: (LocalDate) -> Unit, - onCreateAt: (LocalDate, Int) -> Unit, - onDrop: (TimelineDrop) -> Unit, ) { Column(modifier = Modifier.fillMaxSize()) { Column( @@ -905,14 +985,14 @@ private fun TimelinePageContent( .fillMaxWidth() .background(MaterialTheme.colorScheme.surface), ) { - WeekDayHeader(geometry = geometry, today = today, bias = headerBias, onOpenDay = onOpenDay) + WeekDayHeader(geometry = geometry, today = today, bias = headerBias, onOpenDay = actions.onOpenDay) // This strip is painted on `surface`, so an outlined chip has to // fill with that and not with the columns' container (#230). CompositionLocalProvider( LocalChipGround provides MaterialTheme.colorScheme.surface, ) { AllDayStrip(geometry = geometry, bars = bars, height = allDayHeight, - animatedHeight = animatedAllDayHeight, onEventClick = onEventClick) + animatedHeight = animatedAllDayHeight, onEventClick = actions.onEventClick) } } Spacer(Modifier.height(TIMELINE_TOP_GAP)) @@ -922,12 +1002,8 @@ private fun TimelinePageContent( timedFor = timedFor, allDayHeight = allDayHeight, animatedAllDayHeight = animatedAllDayHeight, - scrollState = scrollState, - dragController = dragController, + actions = actions, active = active, - onEventClick = onEventClick, - onCreateAt = onCreateAt, - onDrop = onDrop, ) } } @@ -947,7 +1023,7 @@ private fun WeekDayHeader( .fillMaxWidth() .padding(top = HEADER_TOP_PADDING, bottom = HEADER_BOTTOM_PADDING, end = TIMELINE_CONTENT_END_INSET), ) { date -> - val javaDow = java.time.DayOfWeek.of(date.dayOfWeek.ordinal + 1) + val javaDow = date.dayOfWeek.toJavaDayOfWeek() val isToday = date == today Column( modifier = Modifier @@ -1053,7 +1129,7 @@ private fun AllDayStrip( animatedHeight: (() -> Dp)? = null, onEventClick: (EventInstance) -> Unit, ) { - val dark = isSystemInDarkTheme() + val dark = LocalFloretDarkTheme.current Row( modifier = Modifier @@ -1076,6 +1152,7 @@ private fun AllDayStrip( key(bar.event.eventId, bar.event.start) { AllDayBar( event = bar.event, + lastDay = bar.toRange.endInclusive, dark = dark, onClick = { onEventClick(bar.event) }, modifier = Modifier @@ -1111,13 +1188,15 @@ private fun AllDayStrip( @Composable private fun AllDayBar( event: EventInstance, + lastDay: LocalDate, dark: Boolean, onClick: () -> Unit, modifier: Modifier = Modifier, ) { val title = event.title.ifBlank { stringResource(R.string.event_untitled) } val dimCutoff = LocalDimCutoff.current - val dimmed = dimCutoff != null && event.hasEnded(dimCutoff) + // A bar is one piece, so it dims once the last day it covers here has passed. + val dimmed = dimCutoff != null && event.isPastOn(lastDay, dimCutoff) val paint = eventPaint(event, dark) Box( modifier = (if (dimmed) modifier.alpha(EventDimAlpha) else modifier) @@ -1148,15 +1227,13 @@ private fun Timeline( timedFor: (LocalDate) -> List, allDayHeight: Dp, animatedAllDayHeight: (() -> Dp)? = null, - scrollState: ScrollState, - dragController: TimelineDragController, + actions: TimelineActions, active: Boolean, - onEventClick: (EventInstance) -> Unit, - onCreateAt: (LocalDate, Int) -> Unit, - onDrop: (TimelineDrop) -> Unit, ) { + val scrollState = actions.scrollState + val dragController = actions.dragController val fullViewportHeight = remember(geometry) { intArrayOf(-1) } - val dark = isSystemInDarkTheme() + val dark = LocalFloretDarkTheme.current val zoom = LocalTimelineZoom.current val density = LocalDensity.current val isRtl = LocalLayoutDirection.current == LayoutDirection.Rtl @@ -1247,11 +1324,7 @@ private fun Timeline( columnWidth = columnWidth, visibleTop = visibleTop, viewportHeight = visibleViewport, - dragController = dragController, - onEventClick = onEventClick, - onCreateAt = onCreateAt, - onDrop = onDrop, - scrollState = scrollState, + actions = actions, modifier = Modifier.fillMaxHeight(), ) } @@ -1269,30 +1342,35 @@ private fun DayColumnCard( columnWidth: Dp, visibleTop: () -> Float, viewportHeight: () -> Float, - dragController: TimelineDragController, - onEventClick: (EventInstance) -> Unit, - onCreateAt: (LocalDate, Int) -> Unit, - onDrop: (TimelineDrop) -> Unit, - scrollState: ScrollState, + actions: TimelineActions, modifier: Modifier = Modifier, ) { + val scrollState = actions.scrollState + val dragController = actions.dragController val density = LocalDensity.current val hourPx = with(density) { hourHeight.toPx() } val morphing = LocalViewMorph.current != null val showHourGrid = LocalShowHourGrid.current - val zone = remember { TimeZone.currentSystemDefault() } + val zone = LocalTimelineZone.current + // A block drafted on an empty slot (#153), drawn over the part of it on this day. + val draft by remember(dragController) { + derivedStateOf { dragController.selection?.event?.takeIf { it.isDraft } } + } + val draftPiece = remember(draft, date, zone) { draft?.let { draftBlock(it, date, zone) } } + val shown = remember(blocks, draftPiece) { if (draftPiece == null) blocks else blocks + draftPiece } // Tells a settled drop when this column has caught up with it. - LaunchedEffect(blocks, dragController.settling) { - dragController.noteGrid(date, blocks) + LaunchedEffect(shown, dragController.settling) { + dragController.noteGrid(date, shown) } // The tap detector outlives the composition that installed it — a pinch or a // Settings change moves the hour height without restarting it — so it reads - // the height and the callback through state handles instead of capturing - // them, or taps land on the scale the column had before the zoom (#148). + // the height through a state handle instead of capturing it, or taps land on + // the scale the column had before the zoom (#148). The actions read their + // callbacks' latest values themselves. val currentHourPx = rememberUpdatedState(hourPx) - val currentOnCreateAt = rememberUpdatedState(onCreateAt) val edges = rememberOutOfViewEdges(blocks, scrollState, hourPx) val currentEdges = rememberUpdatedState(edges) + val draftSurface = rememberDraftSurface(date, edges, hourPx, dragController, actions.onDrop) Card( // Plain rectangular columns — the soft corners come from the outer // rounded scroll viewport, so inner rounding would look odd at the edges. @@ -1321,20 +1399,27 @@ private fun DayColumnCard( // blocks are consumed by their own handler first. Snaps to hour. .pointerInput(date) { detectTapGestures { offset -> + if (dragController.selection != null) { + dragController.deselect() + return@detectTapGestures + } if (currentEdges.value.tap(offset.y)) return@detectTapGestures - currentOnCreateAt.value( + actions.onCreateAt( date, tappedMinuteOfDay(offset.y, currentHourPx.value), ) } - }, + } + // Inside the tap detector, which consumes every down, so only a + // block or handle on top can claim the press first. + .then(draftSurface), ) { val minEventHeight = hourHeight * MIN_EVENT_FRACTION // Keyed by event, so a block that changes time or lane is the *same* // composable afterwards and tweens there. The ordinal disambiguates // a column holding two occurrences of one series. val ordinals = mutableMapOf() - blocks.forEach { block -> + shown.forEach { block -> val ordinal = ordinals.merge(block.event.eventId, 1, Int::plus)!! - 1 key(block.event.eventId, ordinal) { val top = hourHeight * (block.startMin / 60f) @@ -1345,6 +1430,7 @@ private fun DayColumnCard( widthFraction = 1f / block.laneCount, y = top, height = height, + landing = dragController.ghosts(block), ) // Where this block is cut at midnight, which decides both // its shape and the half-gap it gives up to the hour cells. @@ -1378,8 +1464,9 @@ private fun DayColumnCard( cuts = cuts, topInset = topInset, dragController = dragController, - onClick = { onEventClick(block.event) }, - onDrop = onDrop, + onClick = { actions.onEventClick(block.event) }, + onDrop = actions.onDrop, + onResize = actions.onResize, modifier = Modifier .laneSlot(place) .offset(y = place.y + topInset) @@ -1424,13 +1511,16 @@ private fun EventBlock( dragController: TimelineDragController, onClick: () -> Unit, onDrop: (TimelineDrop) -> Unit, + onResize: (TimelineResizeDrop) -> Unit, modifier: Modifier = Modifier, ) { val title = block.event.title.ifBlank { stringResource(R.string.event_untitled) } val use24Hour = LocalUse24HourFormat.current val locale = currentLocale() + val zone = LocalTimelineZone.current + val labelEndMin = remember(block, date, zone) { block.labelEndMin(date, zone) } val timeLabel = "${minToHm(block.startMin, use24Hour, locale)}–" + - minToHm(block.endMin, use24Hour, locale) + minToHm(labelEndMin, use24Hour, locale) val density = LocalDensity.current val metrics = rememberBlockTextMetrics(height) // Only full-width (non-overlapping) blocks that are tall enough show the @@ -1444,7 +1534,7 @@ private fun EventBlock( val textWidth = width - (BLOCK_OUTER_INSET + BLOCK_TEXT_PADDING) * 2 val shownTime = rememberBlockTimeRange( minToHm(block.startMin, use24Hour, locale), - minToHm(block.endMin, use24Hour, locale), + minToHm(labelEndMin, use24Hour, locale), textWidth, ) // A short block drops the title rather than serving a horizontally sliced @@ -1474,72 +1564,237 @@ private fun EventBlock( if (showTime) metrics.timeLine else 0.dp val timeMaxLines = if (showTime) blockTimeLines(shownTime, textWidth, spare) else 1 val dimCutoff = LocalDimCutoff.current - val dimmed = dimCutoff != null && block.event.hasEnded(dimCutoff) - val zone = remember { TimeZone.currentSystemDefault() } + val dimmed = dimCutoff != null && block.event.isPastOn(date, dimCutoff) val moveAction = eventMoveAction(block.event) - val draggable = eventDragAllowed(block.event) + val draft = block.event.isDraft + val draggable = draft || eventDragAllowed(block.event) + val selectable = eventSelectAllowed() + val selected = dragController.isSelected(block) + val haptics = LocalHapticFeedback.current // The drop takes this offset back off, so a tail clipped at midnight lands // where the event's own start belongs (#253). val clipOffset = remember(block, date, zone) { block.clipOffsetMinutes(date, zone) } val shape = remember(cuts) { timedBlockShape(cuts.top, cuts.bottom) } val topInsetPx = with(density) { topInset.toPx() } + // Long press (#141): move to drag, let go to select; selected blocks drag at once. val dragModifier = rememberEventDragSource( - enabled = draggable, + enabled = selectable, key = block.event.instanceId, + immediate = selected && draggable, onPickUp = { pointer, blockRoot, _ -> - dragController.begin( - block = block, - clipOffsetMin = clipOffset, - titleLines = if (showTitle) titleMaxLines else 0, - pointerInRoot = pointer, - // Measured off the block's placement rather than off where the - // hour grid seats it: the copy is drawn from that placement and - // re-seated the same half-gap down (#267). - blockInRoot = blockRoot.copy(y = blockRoot.y - topInsetPx), - ) + if (draggable) { + dragController.begin( + block = block, + clipOffsetMin = clipOffset, + zone = zone, + titleLines = if (showTitle) titleMaxLines else 0, + pointerInRoot = pointer, + // Measured off the block's placement rather than off where the + // hour grid seats it: the copy is drawn from that placement and + // re-seated the same half-gap down (#267). + blockInRoot = blockRoot.copy(y = blockRoot.y - topInsetPx), + ) + PickUp.Drag + } else { + haptics.performHapticFeedback(HapticFeedbackType.LongPress) + dragController.select(block.event) + PickUp.Hold + } }, onMove = dragController::move, onDrop = { dragController.finish()?.let(onDrop) }, onCancel = dragController::cancel, + onRelease = { dragController.select(block.event, fromLift = draggable) }, ) val lifted = draggable && dragController.ghosts(block) - val ghost = ghostAlpha(lifted) + // Released in place, the block takes over the copy's lift without a dip. + val takesOverLift = selected && dragController.selection?.fromLift == true + val ghostFade = ghostAlpha(lifted) + val ghost = when { + takesOverLift && !lifted -> 1f + // A draft leaves no ghost behind, and the copy it lands under is identical. + draft -> if (lifted) 0f else 1f + else -> ghostFade + } + val raise = selectionLift(selected, snap = takesOverLift) + // Tells the action bar to fold when it would cover the bottom handle. + val revealExtraPx = with(density) { (ResizeHandleTarget / 2).toPx() } + val barClearancePx = with(density) { SelectionBarClearance.toPx() } + val tracksBar = selected && !cuts.bottom + // Not while its own write is pending: it still shows the old times. + LaunchedEffect(selected, block.event, lifted) { + if (selected && !lifted) dragController.adoptSelection(block) + } + // Kept composed while hidden: removing them would cancel their own resize. + DisposableEffect(selected, block.event) { + if (selected) dragController.noteSelectedBlock(block.event, true) + onDispose { if (selected) dragController.noteSelectedBlock(block.event, false) } + } + val showHandles = selected && draggable + val handlesShown = !lifted && !dragController.isDragging Box( - modifier = (if (dimmed) modifier.alpha(EventDimAlpha) else modifier) + modifier = (if (dimmed && !selected) modifier.alpha(EventDimAlpha) else modifier) + .zIndex(if (selected) 1f else 0f) // The source stays put as a ghost while its floating copy travels. .then(if (ghost < 1f) Modifier.alpha(ghost) else Modifier) - .eventSurface(paint, shape, cuts) - .clickable(onClick = onClick) - // After clickable, so it is the inner node and wins the main pass; - // the tap still works, since a drag consumes the up. - .then(dragModifier) - .padding(horizontal = BLOCK_TEXT_PADDING, vertical = metrics.inset) - .semantics { - contentDescription = "$title, $timeLabel" - if (moveAction != null) customActions = listOf(moveAction) - }, + .then(if (raise > 0f) Modifier.selectionLift(raise, shape) else Modifier) + .then( + if (tracksBar) { + Modifier.onGloballyPositioned { + dragController.noteSelectedBottom(it, revealExtraPx, barClearancePx) + } + } else { + Modifier + }, + ), ) { - Column { - if (showTitle) { - BlockTitle( - title = title, - maxLines = titleMaxLines, - color = paint.titleInk, - textDecoration = paint.decoration, - fontWeight = paint.titleWeight, + Box( + modifier = Modifier + .fillMaxSize() + .eventSurface(paint, shape, cuts) + .clickable(onClick = onClick) + // After clickable, so it is the inner node and wins the main pass; + // the tap still works, since a drag consumes the up. + .then(dragModifier) + .padding(horizontal = BLOCK_TEXT_PADDING, vertical = metrics.inset) + .semantics { + contentDescription = "$title, $timeLabel" + if (moveAction != null) customActions = listOf(moveAction) + }, + ) { + Column { + if (showTitle) { + BlockTitle( + title = title, + maxLines = titleMaxLines, + color = paint.titleInk, + textDecoration = paint.decoration, + fontWeight = paint.titleWeight, + ) + } + if (showTime) { + BlockTimeLabel( + label = shownTime, + color = paint.secondaryInk, + maxLines = timeMaxLines, + ) + } + } + } + if (showHandles) { + val accent = eventAccent(block.event.color, dark, LocalSoftenColors.current) + val handleLines = if (showTitle) titleMaxLines else 0 + val begin = { edge: ResizeEdge -> + { pointer: Offset -> + dragController.beginResize(block, edge, zone, handleLines, pointer) + } + } + val end = { dragController.finishResize(zone)?.let(onResize) } + // No bounce: an overshoot reads as the block's ends jumping. + val handleIn by animateFloatAsState( + targetValue = if (handlesShown) 1f else 0f, + animationSpec = MaterialTheme.motionScheme.fastEffectsSpec(), + label = "handles", + ) + val handleAlpha = Modifier.graphicsLayer { + alpha = handleIn.coerceIn(0f, 1f) + scaleX = 0.5f + 0.5f * handleIn + scaleY = 0.5f + 0.5f * handleIn + } + if (!cuts.top) { + ResizeHandle( + color = accent, + enabled = handlesShown, + onStart = begin(ResizeEdge.Top), + onMove = dragController::move, + onEnd = { end() }, + onCancel = dragController::cancel, + modifier = Modifier + .align(Alignment.TopStart) + .offset(x = HANDLE_INSET - ResizeHandleTarget / 2, y = -ResizeHandleTarget / 2) + .then(handleAlpha), ) } - if (showTime) { - BlockTimeLabel( - label = shownTime, - color = paint.secondaryInk, - maxLines = timeMaxLines, + if (!cuts.bottom) { + ResizeHandle( + color = accent, + enabled = handlesShown, + onStart = begin(ResizeEdge.Bottom), + onMove = dragController::move, + onEnd = { end() }, + onCancel = dragController::cancel, + modifier = Modifier + .align(Alignment.BottomEnd) + .offset(x = ResizeHandleTarget / 2 - HANDLE_INSET, y = ResizeHandleTarget / 2) + .then(handleAlpha), ) } } } } +/** + * A long press on an empty stretch of [date]'s column (#153): drafts a block of + * the default length from the slot under the finger and lifts it, as a long + * press on an event does. Presses on a block or handle are left to them. + */ +@Composable +private fun rememberDraftSurface( + date: LocalDate, + edges: OutOfViewEdges, + hourPx: Float, + dragController: TimelineDragController, + onDrop: (TimelineDrop) -> Unit, +): Modifier { + val currentDrop by rememberUpdatedState(onDrop) + val title = stringResource(R.string.event_edit_new_title) + val color = MaterialTheme.colorScheme.primary.toArgb() + val zone = LocalTimelineZone.current + val currentEdges by rememberUpdatedState(edges) + // The draft this gesture lifted, selected again on release after the cancel. + val lifted = remember { arrayOfNulls(1) } + val currentHourPx by rememberUpdatedState(hourPx) + return rememberDragSurface( + enabled = eventSelectAllowed(), + key = date, + skipClaimedDown = true, + // A press on a block or handle was consumed by it and never gets here. + onPickUp = { local, pointer, node, _ -> + val hour = currentHourPx + if (hour <= 0f || currentEdges.covers(local.y)) return@rememberDragSurface false + val startMin = draftStartMin(local.y / hour * 60f) + val event = draftEvent( + title = title, + color = color, + start = wallClockInstant(date, startMin, zone), + minutes = dragController.draftMinutes, + ) + val block = draftBlock(event, date, zone) ?: return@rememberDragSurface false + lifted[0] = event + dragController.beginDraft( + block = block, + zone = zone, + pointerInRoot = pointer, + blockInRoot = node + Offset(0f, startMin / 60f * hour), + ) + true + }, + onMove = dragController::move, + onDrop = { dragController.finish()?.let(currentDrop) }, + // An abandoned pickup leaves no draft behind; a release selects it again below. + onCancel = { + dragController.cancel() + if (dragController.selection?.event?.isDraft == true) dragController.deselect() + }, + onRelease = { lifted[0]?.let { dragController.select(it, fromLift = true) } }, + ) +} + +private const val SELECTION_ORPHAN_GRACE_MILLIS = 500L + +/** How far in from the block's side a resize handle's centre sits. */ +private val HANDLE_INSET = 16.dp + private val SKELETON_HEADER_HEIGHT = 36.dp private val SKELETON_HEADER_PADDING = 8.dp @@ -1631,7 +1886,7 @@ private fun formatWeekTitle( abbreviated: Boolean = false, ): String { return formatCalendarTitle( - date = java.time.LocalDate.of(weekStart.year, weekStart.month.ordinal + 1, 1), + date = weekStart.yearMonth.firstDay.toJavaLocalDate(), locale = locale, currentYear = currentYear, skeleton = if (abbreviated) "LLL" else "LLLL", @@ -1647,7 +1902,7 @@ private fun formatDayTitle( abbreviated: Boolean = false, ): String = formatCalendarTitle( - date = java.time.LocalDate.of(date.year, date.month.ordinal + 1, date.day), + date = date.toJavaLocalDate(), locale = locale, currentYear = currentYear, skeleton = if (abbreviated) "dMMM" else "EEEdMMM", diff --git a/app/src/main/java/de/jeanlucmakiola/calendula/ui/week/WeekViewModel.kt b/app/src/main/java/de/jeanlucmakiola/calendula/ui/week/WeekViewModel.kt index 5561e973..fe5992fd 100644 --- a/app/src/main/java/de/jeanlucmakiola/calendula/ui/week/WeekViewModel.kt +++ b/app/src/main/java/de/jeanlucmakiola/calendula/ui/week/WeekViewModel.kt @@ -1,20 +1,24 @@ package de.jeanlucmakiola.calendula.ui.week +import de.jeanlucmakiola.calendula.ui.common.dayRange import androidx.lifecycle.ViewModel import androidx.lifecycle.viewModelScope import dagger.hilt.android.lifecycle.HiltViewModel import de.jeanlucmakiola.calendula.data.calendar.CalendarRepository -import de.jeanlucmakiola.calendula.data.di.IoDispatcher import de.jeanlucmakiola.calendula.data.prefs.SettingsPrefs import de.jeanlucmakiola.calendula.data.prefs.resolveFirstDay import de.jeanlucmakiola.calendula.data.time.TodaySource +import de.jeanlucmakiola.calendula.data.time.ZoneSource import de.jeanlucmakiola.calendula.data.time.currentDate +import de.jeanlucmakiola.calendula.data.time.stateFollowingDays import de.jeanlucmakiola.calendula.domain.CalendarSource import de.jeanlucmakiola.calendula.domain.EventInstance import de.jeanlucmakiola.calendula.domain.displayPriority import de.jeanlucmakiola.calendula.domain.FailureReason import de.jeanlucmakiola.calendula.domain.calendarListFailure import de.jeanlucmakiola.calendula.ui.common.PageStateCache +import de.jeanlucmakiola.floret.android.stateWhileSubscribed +import de.jeanlucmakiola.floret.di.IoDispatcher import kotlinx.coroutines.CoroutineDispatcher import kotlinx.coroutines.ExperimentalCoroutinesApi import kotlinx.coroutines.flow.Flow @@ -29,21 +33,23 @@ import kotlinx.coroutines.flow.flatMapLatest import kotlinx.coroutines.flow.flowOf import kotlinx.coroutines.flow.flowOn import kotlinx.coroutines.flow.map -import kotlinx.coroutines.flow.onEach import kotlinx.coroutines.flow.stateIn import kotlinx.datetime.DateTimeUnit import kotlinx.datetime.DayOfWeek import kotlinx.datetime.LocalDate +import kotlinx.datetime.FixedOffsetTimeZone import kotlinx.datetime.TimeZone +import kotlinx.datetime.toKotlinUtcOffset +import kotlinx.datetime.toJavaZoneId import kotlinx.datetime.atStartOfDayIn -import kotlinx.datetime.atTime import kotlinx.datetime.daysUntil import kotlinx.datetime.minus import kotlinx.datetime.plus -import kotlinx.datetime.toInstant import kotlinx.datetime.toLocalDateTime import java.util.Locale import kotlin.time.Instant +import kotlin.time.toKotlinDuration +import kotlin.time.toKotlinInstant import javax.inject.Inject import kotlin.math.abs @@ -56,10 +62,10 @@ private const val SPAN_CACHE_DAYS = 28 data class DaySpan(val start: LocalDate, val count: Int) /** How the pager cuts the calendar, and the page the anchor sits on. */ -data class PagerPosition(val grid: PageGrid, val page: Int) +data class PagerPosition(val grid: DaysGrid, val page: Int) /** Where [anchor] sits under [rule]. */ -fun positionOf(anchor: LocalDate, rule: (LocalDate) -> PageGrid): PagerPosition = +fun positionOf(anchor: LocalDate, rule: (LocalDate) -> DaysGrid): PagerPosition = rule(anchor).let { PagerPosition(it, it.pageFor(anchor)) } /** @@ -76,21 +82,33 @@ abstract class PagedTimelineViewModel( private val repository: CalendarRepository, settingsPrefs: SettingsPrefs, todaySource: TodaySource, + zoneSource: ZoneSource, private val io: CoroutineDispatcher, - gridRule: Flow<(LocalDate) -> PageGrid>, - initialRule: (LocalDate) -> PageGrid, + gridRule: Flow<(LocalDate) -> DaysGrid>, + initialRule: (LocalDate) -> DaysGrid, ) : ViewModel() { - private val zone = TimeZone.currentSystemDefault() + /** + * The zone every page is laid out in; drags and drops resolve in it too, and + * pages lay out again when the device moves zones (#387). + */ + val zone: StateFlow = zoneSource.zone + .stateIn(viewModelScope, SharingStarted.Eagerly, zoneSource.current()) /** Whether to fade events that have already finished (display concern only). */ val dimCompletedEvents: StateFlow = settingsPrefs.dimCompletedEvents - .stateIn( + .stateWhileSubscribed( scope = viewModelScope, - started = SharingStarted.WhileSubscribed(5_000L), initialValue = false, ) + /** How long a block drafted on an empty slot starts out (#153). */ + val defaultEventDuration: StateFlow = settingsPrefs.defaultEventDurationMinutes + .stateWhileSubscribed( + scope = viewModelScope, + initialValue = SettingsPrefs.DEFAULT_EVENT_DURATION, + ) + private val todayDate: LocalDate get() = currentDate() @@ -103,26 +121,18 @@ abstract class PagedTimelineViewModel( * The grid for a given anchor, held eagerly so a screen can place its pager * on its very first frame rather than a frame after the anchor moved. */ - val rule: StateFlow<(LocalDate) -> PageGrid> = + val rule: StateFlow<(LocalDate) -> DaysGrid> = gridRule.stateIn(viewModelScope, SharingStarted.Eagerly, initialRule) - private var lastToday = todayDate - /** Today, kept current across midnight so a page left open doesn't mark yesterday (#373). */ - private val today: StateFlow = todaySource.today - .onEach { date -> - val old = lastToday - lastToday = date - if (old != date) followToday(old, date) - } - .stateIn(viewModelScope, SharingStarted.WhileSubscribed(5_000L), todayDate) + private val today: StateFlow = + todaySource.today.stateFollowingDays(viewModelScope, todayDate, ::followToday) private val position: StateFlow = combine(_anchor, rule) { anchor, rule -> positionOf(anchor, rule) } .distinctUntilChanged() - .stateIn( + .stateWhileSubscribed( scope = viewModelScope, - started = SharingStarted.WhileSubscribed(5_000L), initialValue = positionOf(todayDate, initialRule), ) @@ -136,9 +146,8 @@ abstract class PagedTimelineViewModel( .distinctUntilChanged() .flatMapLatest { span -> span(span).filterNot { it is WeekUiState.Loading } } .catch { emit(WeekUiState.Failure(FailureReason.ProviderUnavailable)) } - .stateIn( + .stateWhileSubscribed( scope = viewModelScope, - started = SharingStarted.WhileSubscribed(5_000L), initialValue = WeekUiState.Loading, ) @@ -152,12 +161,14 @@ abstract class PagedTimelineViewModel( abs(cached.start.daysUntil(requested.start)) <= SPAN_CACHE_DAYS }, ) { span -> - combine( - repository.calendars(), - repository.instances(spanRange(span.start, span.count, zone)), - today, - ) { calendars, instances, today -> - buildState(span, calendars, instances, today) + zone.flatMapLatest { zone -> + combine( + repository.calendars(), + repository.instances(spanRange(span.start, span.count, zone)), + today, + ) { calendars, instances, today -> + buildState(span, calendars, instances, today, zone) + } } .catch { emit(WeekUiState.Failure(FailureReason.ProviderUnavailable)) } .flowOn(io) @@ -185,13 +196,13 @@ abstract class PagedTimelineViewModel( val grid = rule.value(anchor) if (grid.pageFor(anchor) == grid.pageFor(old)) _anchor.value = new } - fun goToDate(date: LocalDate) = jumpTo(date) private fun buildState( span: DaySpan, calendars: List, instances: List, today: LocalDate, + zone: TimeZone, ): WeekUiState { calendarListFailure(calendars)?.let { return WeekUiState.Failure(it) } val days = (0 until span.count).map { span.start.plus(it, DateTimeUnit.DAY) } @@ -213,18 +224,20 @@ class WeekViewModel @Inject constructor( repository: CalendarRepository, settingsPrefs: SettingsPrefs, todaySource: TodaySource, + zoneSource: ZoneSource, @IoDispatcher io: CoroutineDispatcher, ) : PagedTimelineViewModel( repository = repository, settingsPrefs = settingsPrefs, todaySource = todaySource, + zoneSource = zoneSource, io = io, gridRule = settingsPrefs.weekStart.map { pref -> - val grid = WeekGrid(pref.resolveFirstDay(Locale.getDefault())) - val rule: (LocalDate) -> PageGrid = { grid } + val grid = DaysGrid.weeks(pref.resolveFirstDay(Locale.getDefault())) + val rule: (LocalDate) -> DaysGrid = { grid } rule }, - initialRule = { WeekGrid(DayOfWeek.MONDAY) }, + initialRule = { DaysGrid.weeks(DayOfWeek.MONDAY) }, ) /** @@ -237,11 +250,13 @@ class MultiDayViewModel @Inject constructor( repository: CalendarRepository, settingsPrefs: SettingsPrefs, todaySource: TodaySource, + zoneSource: ZoneSource, @IoDispatcher io: CoroutineDispatcher, ) : PagedTimelineViewModel( repository = repository, settingsPrefs = settingsPrefs, todaySource = todaySource, + zoneSource = zoneSource, io = io, gridRule = settingsPrefs.multiDayCount.map { count -> { anchor: LocalDate -> DaysGrid.startingAt(anchor, count) } @@ -255,14 +270,16 @@ class DayViewModel @Inject constructor( repository: CalendarRepository, settingsPrefs: SettingsPrefs, todaySource: TodaySource, + zoneSource: ZoneSource, @IoDispatcher io: CoroutineDispatcher, ) : PagedTimelineViewModel( repository = repository, settingsPrefs = settingsPrefs, todaySource = todaySource, + zoneSource = zoneSource, io = io, - gridRule = flowOf { _: LocalDate -> DayGrid }, - initialRule = { DayGrid }, + gridRule = flowOf { _: LocalDate -> DaysGrid.days }, + initialRule = { DaysGrid.days }, ) /** @@ -317,20 +334,68 @@ internal fun layoutAllDay( private infix fun IntRange.overlaps(other: IntRange): Boolean = first <= other.last && other.first <= last -/** Beginning of the week (at [weekStart]) that contains this date. */ -internal fun LocalDate.startOfWeek(weekStart: DayOfWeek): LocalDate { - // DayOfWeek.ordinal: MONDAY=0..SUNDAY=6 → identical to ISO ordering. - val offset = ((dayOfWeek.ordinal - weekStart.ordinal) + 7) % 7 - return minus(offset, DateTimeUnit.DAY) +/** Instant range covering the [count] days starting at [start]. */ +internal fun spanRange(start: LocalDate, count: Int, zone: TimeZone): ClosedRange = + dayRange(start, start.plus(count - 1, DateTimeUnit.DAY), zone) + +/** + * This instant's wall-clock time as minutes past [day]'s midnight in [zone] — + * negative before that day, past 1440 after it. Elapsed time since midnight would + * put everything after a DST change an hour off on that day's grid (#387). + */ +internal fun Instant.minutesPast(day: LocalDate, zone: TimeZone): Int { + val local = toLocalDateTime(zone) + val days = (local.date.toEpochDays() - day.toEpochDays()).toInt() + return days * MINUTES_PER_DAY + local.time.toSecondOfDay() / 60 } -/** Instant range covering the [count] days starting at [start]. */ -internal fun spanRange(start: LocalDate, count: Int, zone: TimeZone): ClosedRange { - val from = start.atStartOfDayIn(zone) - val to = start.plus(count - 1, DateTimeUnit.DAY).atTime(23, 59, 59).toInstant(zone) - return from..to +/** [instant]'s [minutesPast] clamped to [day]. */ +internal fun wallClockMinutes(instant: Instant, day: LocalDate, zone: TimeZone): Int = + instant.minutesPast(day, zone).coerceIn(0, MINUTES_PER_DAY) + +/** + * Where a run from [start] to [end] that begins at [startMin] ends on [day]'s + * wall clock. A run that began before the fall-back hour's repeat and ends + * inside it is drawn to where that hour ends (03:00 in Berlin), since its own + * wall-clock end reads earlier than its real length (#387). + */ +internal fun wallClockEndMinutes( + startMin: Int, + start: Instant, + end: Instant, + day: LocalDate, + zone: TimeZone, +): Int { + val wall = end.minutesPast(day, zone) + if (end <= start) return maxOf(wall, startMin) + val drawn = repeatedHourEndMinutes(start, end, day, zone) ?: wall + return if (drawn > startMin) drawn else startMin + (end - start).inWholeMinutes.toInt() } +/** + * Where the fall-back hour's repeat [end] falls in ends, as minutes past [day]'s + * midnight: the wall clock the zone fell back from (03:00 in Berlin). Null unless + * [end] is in that repeat and [start] before it. + */ +private fun repeatedHourEndMinutes(start: Instant, end: Instant, day: LocalDate, zone: TimeZone): Int? { + // Just past [end], so an end on the transition itself still finds it. + val after = java.time.Instant.ofEpochMilli(end.toEpochMilliseconds() + 1) + val transition = zone.toJavaZoneId().rules.previousTransition(after) + ?.takeIf { it.isOverlap } ?: return null + val fellBack = transition.instant.toKotlinInstant() + if (start >= fellBack || end >= fellBack + transition.duration.abs().toKotlinDuration()) return null + // The moment it fell back, read on the clock it fell back from. + return fellBack.minutesPast(day, FixedOffsetTimeZone(transition.offsetBefore.toKotlinUtcOffset())) +} + +/** + * The end a block's time label names on [day]: its event's own wall-clock end, + * which for one ending in the fall-back hour's repeat is earlier than the + * [TimedBlock.endMin] it is drawn to (#387). + */ +internal fun TimedBlock.labelEndMin(day: LocalDate, zone: TimeZone): Int = + minOf(endMin, wallClockMinutes(event.end, day, zone)) + /** True if this event overlaps the calendar [day] in [zone] (any portion). */ internal fun EventInstance.coversDay(day: LocalDate, zone: TimeZone): Boolean { if (isAllDay) { @@ -384,14 +449,14 @@ internal fun layoutDay( if (ev.start == ev.end) { // Instant event: keep only if the point falls inside this day. if (ev.start < dayStart || ev.start >= dayEnd) return@mapNotNull null - val m = (ev.start - dayStart).inWholeMinutes.toInt().coerceIn(0, MINUTES_PER_DAY) + val m = wallClockMinutes(ev.start, day, zone) Raw(ev, m, m) } else { val s = maxOf(ev.start, dayStart) val e = minOf(ev.end, dayEnd) if (e <= s) return@mapNotNull null - val startMin = (s - dayStart).inWholeMinutes.toInt().coerceIn(0, MINUTES_PER_DAY) - val endMin = (e - dayStart).inWholeMinutes.toInt().coerceIn(startMin, MINUTES_PER_DAY) + val startMin = wallClockMinutes(s, day, zone) + val endMin = wallClockEndMinutes(startMin, s, e, day, zone).coerceAtMost(MINUTES_PER_DAY) Raw(ev, startMin, endMin) } } diff --git a/app/src/main/java/de/jeanlucmakiola/calendula/ui/week/WeekViewPreview.kt b/app/src/main/java/de/jeanlucmakiola/calendula/ui/week/WeekViewPreview.kt index d336cdf3..e7d87a0e 100644 --- a/app/src/main/java/de/jeanlucmakiola/calendula/ui/week/WeekViewPreview.kt +++ b/app/src/main/java/de/jeanlucmakiola/calendula/ui/week/WeekViewPreview.kt @@ -1,5 +1,6 @@ package de.jeanlucmakiola.calendula.ui.week +import de.jeanlucmakiola.calendula.ui.common.startOfWeek import androidx.compose.foundation.rememberScrollState import androidx.compose.runtime.Composable import androidx.compose.runtime.LaunchedEffect @@ -7,9 +8,9 @@ import androidx.compose.runtime.remember import androidx.compose.runtime.snapshotFlow import androidx.compose.ui.Modifier import androidx.compose.ui.unit.Dp -import de.jeanlucmakiola.calendula.ui.common.ScaledViewPreview import de.jeanlucmakiola.calendula.ui.common.rememberTimelineDragController import de.jeanlucmakiola.calendula.ui.common.sampleTimelineEvents +import de.jeanlucmakiola.floret.components.ScaledViewPreview import kotlinx.datetime.DateTimeUnit import kotlinx.datetime.DayOfWeek import kotlinx.datetime.LocalDate @@ -51,13 +52,16 @@ internal fun WeekViewPreview( state = state, showWeekNumber = dayCount == 7, headerBias = if (dayCount == 1) TimelineKind.Day.headerBias else 0f, - scrollState = scrollState, allDayHeight = state.allDayStripHeight(), - dragController = rememberTimelineDragController(), - onEventClick = {}, - onOpenDay = {}, - onCreateAt = { _, _ -> }, - onDrop = {}, + actions = rememberTimelineActions( + scrollState = scrollState, + dragController = rememberTimelineDragController(), + onEventClick = {}, + onOpenDay = {}, + onCreateAt = { _, _ -> }, + onDrop = {}, + onResize = {}, + ), ) } } diff --git a/app/src/main/res/values-night/colors.xml b/app/src/main/res/values-night/colors.xml index 15fc9905..db4932f2 100644 --- a/app/src/main/res/values-night/colors.xml +++ b/app/src/main/res/values-night/colors.xml @@ -2,5 +2,5 @@ - #FF101316 + @color/window_background_dark diff --git a/app/src/main/res/values/colors.xml b/app/src/main/res/values/colors.xml index 3435ae81..f941fbd3 100644 --- a/app/src/main/res/values/colors.xml +++ b/app/src/main/res/values/colors.xml @@ -6,5 +6,10 @@ - #FFFBFCFE + @color/window_background_light + + #FFFBFCFE + #FF101316 + #FF000000 diff --git a/app/src/main/res/values/strings.xml b/app/src/main/res/values/strings.xml index d4140855..0ef63792 100644 --- a/app/src/main/res/values/strings.xml +++ b/app/src/main/res/values/strings.xml @@ -97,6 +97,14 @@ Moving the whole series would change which days it falls on, so only this event can move. Moved to %1$s + Changed to %1$s + Change recurring event + Event actions + Hide event actions + Deselect event + Create event + Discard new event + Couldn\'t open the event Undo Move undone Couldn\'t move the event @@ -110,7 +118,13 @@ New event Close + More actions + Unsaved changes + Save changes + Discard changes + Keep editing Save + Create Add title Managed by “%1$s” — the title, date and repeat are kept in sync from your contacts. Reminders, location and notes are yours to edit. @@ -441,6 +455,8 @@ System Light Dark + Black + Dark with pure black backgrounds, for AMOLED screens Whether the app is light or dark. The choice applies immediately. Currently %1$s @@ -510,6 +526,11 @@ Fade events that have already ended in month and week view Drag to reschedule Move an event by dragging it to another day or time + Events + Tapping an event opens + Details + Edit form + Events you can\'t edit and reminder notifications always open the details. Past events Show Dim @@ -830,6 +851,9 @@ New event Create a new event + + Create event + New event Add Quick Settings tile diff --git a/app/src/test/java/de/jeanlucmakiola/calendula/TestEvents.kt b/app/src/test/java/de/jeanlucmakiola/calendula/TestEvents.kt new file mode 100644 index 00000000..c14caa68 --- /dev/null +++ b/app/src/test/java/de/jeanlucmakiola/calendula/TestEvents.kt @@ -0,0 +1,118 @@ +package de.jeanlucmakiola.calendula + +import de.jeanlucmakiola.calendula.domain.AccessLevel +import de.jeanlucmakiola.calendula.domain.Attendee +import de.jeanlucmakiola.calendula.domain.AttendeeStatus +import de.jeanlucmakiola.calendula.domain.Availability +import de.jeanlucmakiola.calendula.domain.EventDetail +import de.jeanlucmakiola.calendula.domain.EventInstance +import de.jeanlucmakiola.calendula.domain.EventResponse +import de.jeanlucmakiola.calendula.domain.EventStatus +import de.jeanlucmakiola.calendula.domain.Reminder +import kotlinx.datetime.DateTimeUnit +import kotlinx.datetime.LocalDate +import kotlinx.datetime.TimeZone +import kotlinx.datetime.atTime +import kotlinx.datetime.plus +import kotlinx.datetime.toInstant +import kotlin.time.Instant + +/** An [EventInstance] with every field defaulted; [eventId] follows [id]. */ +fun testEvent( + id: Long = 1L, + eventId: Long = id, + calendarId: Long = 1L, + title: String = "Event", + start: Instant = Instant.fromEpochMilliseconds(0), + end: Instant = start, + isAllDay: Boolean = false, + color: Int = 0, + location: String? = null, + isRecurring: Boolean = false, + response: EventResponse = EventResponse.Going, +): EventInstance = EventInstance( + instanceId = id, + eventId = eventId, + calendarId = calendarId, + title = title, + start = start, + end = end, + isAllDay = isAllDay, + color = color, + location = location, + isRecurring = isRecurring, + response = response, +) + +/** An all-day event over [from]..[toInclusive], at midnights in [zone] with an exclusive end. */ +fun allDayEvent( + from: LocalDate, + toInclusive: LocalDate = from, + id: Long = 1L, + title: String = "Event", + color: Int = 0, + zone: TimeZone = TimeZone.UTC, + calendarId: Long = 1L, +): EventInstance = testEvent( + id = id, + calendarId = calendarId, + title = title, + start = from.atTime(0, 0).toInstant(zone), + end = toInclusive.plus(1, DateTimeUnit.DAY).atTime(0, 0).toInstant(zone), + isAllDay = true, + color = color, +) + +/** A timed event from [date] [startHour]:[minute] to [endDate] [endHour]:[minute] in [zone]. */ +fun timedEvent( + date: LocalDate, + startHour: Int, + endHour: Int = startHour + 1, + zone: TimeZone = TimeZone.UTC, + id: Long = 1L, + title: String = "Event", + color: Int = 0, + endDate: LocalDate = date, + minute: Int = 0, + calendarId: Long = 1L, +): EventInstance = testEvent( + id = id, + calendarId = calendarId, + title = title, + start = date.atTime(startHour, minute).toInstant(zone), + end = endDate.atTime(endHour, minute).toInstant(zone), + color = color, +) + +/** An [EventDetail] around [instance] with every other field defaulted. */ +fun testDetail( + instance: EventInstance = testEvent(), + description: String? = null, + organizer: String? = null, + attendees: List = emptyList(), + rrule: String? = null, + reminders: List = emptyList(), + status: EventStatus = EventStatus.Confirmed, + availability: Availability = Availability.Busy, + accessLevel: AccessLevel = AccessLevel.Default, + eventTimezone: String? = null, + selfStatus: AttendeeStatus = AttendeeStatus.Unknown, + eventColor: Int? = null, + eventColorKey: String? = null, + isException: Boolean = false, +): EventDetail = EventDetail( + instance = instance, + description = description, + organizer = organizer, + attendees = attendees, + rrule = rrule, + reminders = reminders, + status = status, + availability = availability, + accessLevel = accessLevel, + eventTimezone = eventTimezone, + selfStatus = selfStatus, + eventColor = eventColor, + eventColorKey = eventColorKey, + isException = isException, +) diff --git a/app/src/test/java/de/jeanlucmakiola/calendula/TestRepositories.kt b/app/src/test/java/de/jeanlucmakiola/calendula/TestRepositories.kt new file mode 100644 index 00000000..51de87a3 --- /dev/null +++ b/app/src/test/java/de/jeanlucmakiola/calendula/TestRepositories.kt @@ -0,0 +1,55 @@ +package de.jeanlucmakiola.calendula + +import androidx.datastore.core.DataStore +import androidx.datastore.preferences.core.PreferenceDataStoreFactory +import androidx.datastore.preferences.core.Preferences +import de.jeanlucmakiola.calendula.data.calendar.CalendarDataSource +import de.jeanlucmakiola.calendula.data.calendar.CalendarRepositoryImpl +import de.jeanlucmakiola.calendula.data.prefs.CalendarPrefs +import de.jeanlucmakiola.calendula.data.prefs.SettingsPrefs +import kotlinx.coroutines.CoroutineDispatcher +import kotlinx.coroutines.CoroutineScope +import kotlinx.coroutines.Dispatchers +import kotlinx.coroutines.ExperimentalCoroutinesApi +import kotlinx.coroutines.test.TestDispatcher +import kotlinx.coroutines.test.UnconfinedTestDispatcher +import kotlinx.coroutines.test.resetMain +import kotlinx.coroutines.test.setMain +import org.junit.jupiter.api.extension.AfterEachCallback +import org.junit.jupiter.api.extension.BeforeEachCallback +import org.junit.jupiter.api.extension.ExtensionContext +import java.nio.file.Path + +/** A Preferences DataStore in [dir]; [scope] pins its writes, e.g. to a test dispatcher. */ +fun testDataStore(dir: Path, name: String, scope: CoroutineScope? = null): DataStore { + val file = { dir.resolve("$name.preferences_pb").toFile() } + return if (scope == null) { + PreferenceDataStoreFactory.create(produceFile = file) + } else { + PreferenceDataStoreFactory.create(scope = scope, produceFile = file) + } +} + +fun testPrefs(dir: Path, scope: CoroutineScope? = null): CalendarPrefs = + CalendarPrefs(testDataStore(dir, "test_prefs", scope)) + +fun testSettings(dir: Path, scope: CoroutineScope? = null): SettingsPrefs = + SettingsPrefs(testDataStore(dir, "test_settings", scope)) + +/** A [CalendarRepositoryImpl] over [source], with fresh prefs in [dir] unless given. */ +fun testRepository( + source: CalendarDataSource, + dir: Path, + io: CoroutineDispatcher, + prefs: CalendarPrefs = testPrefs(dir), + settings: SettingsPrefs = testSettings(dir), +): CalendarRepositoryImpl = CalendarRepositoryImpl(source, prefs, settings, io) + +/** Installs [dispatcher] as `Dispatchers.Main` around each test. */ +@OptIn(ExperimentalCoroutinesApi::class) +class MainDispatcherExtension( + val dispatcher: TestDispatcher = UnconfinedTestDispatcher(), +) : BeforeEachCallback, AfterEachCallback { + override fun beforeEach(context: ExtensionContext) = Dispatchers.setMain(dispatcher) + override fun afterEach(context: ExtensionContext) = Dispatchers.resetMain() +} diff --git a/app/src/test/java/de/jeanlucmakiola/calendula/data/calendar/CalendarRepositoryImplTest.kt b/app/src/test/java/de/jeanlucmakiola/calendula/data/calendar/CalendarRepositoryImplTest.kt index 076d7167..fcf402c6 100644 --- a/app/src/test/java/de/jeanlucmakiola/calendula/data/calendar/CalendarRepositoryImplTest.kt +++ b/app/src/test/java/de/jeanlucmakiola/calendula/data/calendar/CalendarRepositoryImplTest.kt @@ -1,17 +1,17 @@ package de.jeanlucmakiola.calendula.data.calendar -import androidx.datastore.core.DataStore -import androidx.datastore.preferences.core.PreferenceDataStoreFactory -import androidx.datastore.preferences.core.Preferences import app.cash.turbine.test import com.google.common.truth.Truth.assertThat -import de.jeanlucmakiola.calendula.data.prefs.CalendarPrefs -import de.jeanlucmakiola.calendula.data.prefs.SettingsPrefs import de.jeanlucmakiola.calendula.domain.CalendarSource import de.jeanlucmakiola.calendula.domain.EventColorOption import de.jeanlucmakiola.calendula.domain.EventForm import de.jeanlucmakiola.calendula.domain.EventInstance +import de.jeanlucmakiola.calendula.domain.FormTime import de.jeanlucmakiola.calendula.domain.SearchCandidate +import de.jeanlucmakiola.calendula.testEvent +import de.jeanlucmakiola.calendula.testPrefs +import de.jeanlucmakiola.calendula.testRepository +import de.jeanlucmakiola.calendula.testSettings import kotlinx.coroutines.Dispatchers import kotlinx.coroutines.flow.first import kotlinx.datetime.LocalDate @@ -29,21 +29,6 @@ import java.nio.file.Path @OptIn(ExperimentalCoroutinesApi::class) class CalendarRepositoryImplTest { - private fun newPrefs(tempDir: Path): CalendarPrefs = - CalendarPrefs(newDataStore(tempDir)) - - private fun newSettings(tempDir: Path): SettingsPrefs = - SettingsPrefs( - PreferenceDataStoreFactory.create( - produceFile = { tempDir.resolve("repo_test_settings.preferences_pb").toFile() }, - ), - ) - - private fun newDataStore(tempDir: Path): DataStore = - PreferenceDataStoreFactory.create( - produceFile = { tempDir.resolve("repo_test_prefs.preferences_pb").toFile() }, - ) - private fun makeCal( id: Long, name: String = "Cal $id", @@ -55,12 +40,12 @@ class CalendarRepositoryImplTest { id: Long, title: String = "E $id", calendarId: Long = 1L, - ): EventInstance = EventInstance( - instanceId = id, eventId = id, calendarId = calendarId, + ): EventInstance = testEvent( + id = id, calendarId = calendarId, title = title, start = Instant.fromEpochMilliseconds(1_000_000_000L), end = Instant.fromEpochMilliseconds(1_000_003_600L), - isAllDay = false, color = 0xFF000000.toInt(), location = null, + color = 0xFF000000.toInt(), ) @Test @@ -68,7 +53,7 @@ class CalendarRepositoryImplTest { val fake = FakeCalendarDataSource().apply { calendarsResult = listOf(makeCal(1L), makeCal(2L)) } - val repo = CalendarRepositoryImpl(fake, newPrefs(tempDir), newSettings(tempDir), UnconfinedTestDispatcher(testScheduler)) + val repo = testRepository(fake, tempDir, UnconfinedTestDispatcher(testScheduler)) repo.calendars().test { val first = awaitItem() @@ -82,7 +67,7 @@ class CalendarRepositoryImplTest { val fake = FakeCalendarDataSource().apply { calendarsResult = listOf(makeCal(1L)) } - val repo = CalendarRepositoryImpl(fake, newPrefs(tempDir), newSettings(tempDir), UnconfinedTestDispatcher(testScheduler)) + val repo = testRepository(fake, tempDir, UnconfinedTestDispatcher(testScheduler)) repo.calendars().test { assertThat(awaitItem().map { it.id }).containsExactly(1L) @@ -99,7 +84,7 @@ class CalendarRepositoryImplTest { fun `instances re-emit after a write the provider never notified about`(@TempDir tempDir: Path) = runTest { var current = listOf(makeEvent(10L)) val fake = FakeCalendarDataSource().apply { instancesResult = { _, _ -> current } } - val repo = CalendarRepositoryImpl(fake, newPrefs(tempDir), newSettings(tempDir), UnconfinedTestDispatcher(testScheduler)) + val repo = testRepository(fake, tempDir, UnconfinedTestDispatcher(testScheduler)) val range = Instant.fromEpochMilliseconds(0)..Instant.fromEpochMilliseconds(10_000L) repo.instances(range).test { @@ -120,7 +105,7 @@ class CalendarRepositoryImplTest { instancesResult = { _, _ -> current } writeError = WriteFailedException("boom") } - val repo = CalendarRepositoryImpl(fake, newPrefs(tempDir), newSettings(tempDir), UnconfinedTestDispatcher(testScheduler)) + val repo = testRepository(fake, tempDir, UnconfinedTestDispatcher(testScheduler)) val range = Instant.fromEpochMilliseconds(0)..Instant.fromEpochMilliseconds(10_000L) repo.instances(range).test { @@ -145,7 +130,7 @@ class CalendarRepositoryImplTest { listOf(makeEvent(10L)) } } - val repo = CalendarRepositoryImpl(fake, newPrefs(tempDir), newSettings(tempDir), UnconfinedTestDispatcher(testScheduler)) + val repo = testRepository(fake, tempDir, UnconfinedTestDispatcher(testScheduler)) val range = Instant.fromEpochMilliseconds(1_000L)..Instant.fromEpochMilliseconds(2_000L) repo.instances(range).test { @@ -161,7 +146,7 @@ class CalendarRepositoryImplTest { val fake = FakeCalendarDataSource().apply { instancesResult = {_, _ -> listOf(makeEvent(10L, "Good")) } } - val repo = CalendarRepositoryImpl(fake, newPrefs(tempDir), newSettings(tempDir), UnconfinedTestDispatcher(testScheduler)) + val repo = testRepository(fake, tempDir, UnconfinedTestDispatcher(testScheduler)) val range = Instant.fromEpochMilliseconds(0)..Instant.fromEpochMilliseconds(10_000L) repo.instances(range).test { @@ -173,7 +158,7 @@ class CalendarRepositoryImplTest { @Test fun `instances drops events whose calendar the user hid`(@TempDir tempDir: Path) = runTest { - val prefs = newPrefs(tempDir) + val prefs = testPrefs(tempDir) prefs.setHiddenCalendarIds(setOf(2L)) val fake = FakeCalendarDataSource().apply { instancesResult = { _, _ -> @@ -183,7 +168,7 @@ class CalendarRepositoryImplTest { ) } } - val repo = CalendarRepositoryImpl(fake, prefs, newSettings(tempDir), UnconfinedTestDispatcher(testScheduler)) + val repo = testRepository(fake, tempDir, UnconfinedTestDispatcher(testScheduler), prefs = prefs) val range = Instant.fromEpochMilliseconds(0)..Instant.fromEpochMilliseconds(10_000L) repo.instances(range).test { @@ -194,7 +179,7 @@ class CalendarRepositoryImplTest { @Test fun `instances re-emits when the hidden set changes`(@TempDir tempDir: Path) = runTest { - val prefs = newPrefs(tempDir) + val prefs = testPrefs(tempDir) val fake = FakeCalendarDataSource().apply { instancesResult = { _, _ -> listOf( @@ -203,7 +188,7 @@ class CalendarRepositoryImplTest { ) } } - val repo = CalendarRepositoryImpl(fake, prefs, newSettings(tempDir), UnconfinedTestDispatcher(testScheduler)) + val repo = testRepository(fake, tempDir, UnconfinedTestDispatcher(testScheduler), prefs = prefs) val range = Instant.fromEpochMilliseconds(0)..Instant.fromEpochMilliseconds(10_000L) repo.instances(range).test { @@ -229,7 +214,7 @@ class CalendarRepositoryImplTest { ) } } - val repo = CalendarRepositoryImpl(fake, newPrefs(tempDir), newSettings(tempDir), UnconfinedTestDispatcher(testScheduler)) + val repo = testRepository(fake, tempDir, UnconfinedTestDispatcher(testScheduler)) val range = Instant.fromEpochMilliseconds(0)..Instant.fromEpochMilliseconds(10_000L) repo.instances(range).test { @@ -242,7 +227,7 @@ class CalendarRepositoryImplTest { fun `instances applies the union of hidden and system-invisible calendars`( @TempDir tempDir: Path, ) = runTest { - val prefs = newPrefs(tempDir) + val prefs = testPrefs(tempDir) prefs.setHiddenCalendarIds(setOf(2L)) val fake = FakeCalendarDataSource().apply { calendarsResult = listOf(makeCal(1L), makeCal(2L), makeCal(3L, visible = false)) @@ -254,7 +239,7 @@ class CalendarRepositoryImplTest { ) } } - val repo = CalendarRepositoryImpl(fake, prefs, newSettings(tempDir), UnconfinedTestDispatcher(testScheduler)) + val repo = testRepository(fake, tempDir, UnconfinedTestDispatcher(testScheduler), prefs = prefs) val range = Instant.fromEpochMilliseconds(0)..Instant.fromEpochMilliseconds(10_000L) repo.instances(range).test { @@ -276,7 +261,7 @@ class CalendarRepositoryImplTest { ) } } - val repo = CalendarRepositoryImpl(fake, newPrefs(tempDir), newSettings(tempDir), UnconfinedTestDispatcher(testScheduler)) + val repo = testRepository(fake, tempDir, UnconfinedTestDispatcher(testScheduler)) val range = Instant.fromEpochMilliseconds(0)..Instant.fromEpochMilliseconds(10_000L) repo.instances(range).test { @@ -301,7 +286,7 @@ class CalendarRepositoryImplTest { val fake = FakeCalendarDataSource().apply { calendarsResult = listOf(makeCal(1L), makeCal(2L), makeCal(3L)) } - val repo = CalendarRepositoryImpl(fake, newPrefs(tempDir), newSettings(tempDir), Dispatchers.Unconfined) + val repo = testRepository(fake, tempDir, Dispatchers.Unconfined) repo.setCalendarsVisible(listOf(1L, 3L), false) @@ -315,7 +300,7 @@ class CalendarRepositoryImplTest { // READ granted, WRITE denied: the provider flag can't be written, so the // choice is parked in the pending set — and honoured from there, or the // user's switched-off calendars would come back on upgrade (#75). - val prefs = newPrefs(tempDir) + val prefs = testPrefs(tempDir) val fake = FakeCalendarDataSource().apply { canWrite = false calendarsResult = listOf(makeCal(1L), makeCal(2L)) @@ -326,7 +311,7 @@ class CalendarRepositoryImplTest { ) } } - val repo = CalendarRepositoryImpl(fake, prefs, newSettings(tempDir), UnconfinedTestDispatcher(testScheduler)) + val repo = testRepository(fake, tempDir, UnconfinedTestDispatcher(testScheduler), prefs = prefs) val range = Instant.fromEpochMilliseconds(0)..Instant.fromEpochMilliseconds(10_000L) repo.instances(range).test { @@ -345,12 +330,12 @@ class CalendarRepositoryImplTest { fun `calendars reports a pending switch-off as off`(@TempDir tempDir: Path) = runTest { // Otherwise the Settings switch would snap straight back on for a // read-only install, and the pickers would keep offering the calendar. - val prefs = newPrefs(tempDir) + val prefs = testPrefs(tempDir) val fake = FakeCalendarDataSource().apply { canWrite = false calendarsResult = listOf(makeCal(1L), makeCal(2L)) } - val repo = CalendarRepositoryImpl(fake, prefs, newSettings(tempDir), UnconfinedTestDispatcher(testScheduler)) + val repo = testRepository(fake, tempDir, UnconfinedTestDispatcher(testScheduler), prefs = prefs) repo.calendars().test { assertThat(awaitItem().map { it.isVisibleInSystem }).containsExactly(true, true) @@ -366,13 +351,13 @@ class CalendarRepositoryImplTest { fun `switching a calendar back on without write permission retires its entry`( @TempDir tempDir: Path, ) = runTest { - val prefs = newPrefs(tempDir) + val prefs = testPrefs(tempDir) prefs.addPendingDisabledCalendarIds(setOf(2L)) val fake = FakeCalendarDataSource().apply { canWrite = false calendarsResult = listOf(makeCal(1L), makeCal(2L)) } - val repo = CalendarRepositoryImpl(fake, prefs, newSettings(tempDir), Dispatchers.Unconfined) + val repo = testRepository(fake, tempDir, Dispatchers.Unconfined, prefs = prefs) repo.setCalendarsVisible(listOf(2L), true) @@ -383,12 +368,12 @@ class CalendarRepositoryImplTest { fun `a provider write clears anything still pending for that calendar`( @TempDir tempDir: Path, ) = runTest { - val prefs = newPrefs(tempDir) + val prefs = testPrefs(tempDir) prefs.addPendingDisabledCalendarIds(setOf(2L)) val fake = FakeCalendarDataSource().apply { calendarsResult = listOf(makeCal(1L), makeCal(2L)) } - val repo = CalendarRepositoryImpl(fake, prefs, newSettings(tempDir), Dispatchers.Unconfined) + val repo = testRepository(fake, tempDir, Dispatchers.Unconfined, prefs = prefs) repo.setCalendarsVisible(listOf(2L), false) @@ -404,7 +389,7 @@ class CalendarRepositoryImplTest { calendarsResult = listOf(makeCal(1L), makeCal(2L)) instancesResult = { _, _ -> listOf(makeEvent(10L, "A", calendarId = 1L)) } } - val repo = CalendarRepositoryImpl(fake, newPrefs(tempDir), newSettings(tempDir), UnconfinedTestDispatcher(testScheduler)) + val repo = testRepository(fake, tempDir, UnconfinedTestDispatcher(testScheduler)) val range = Instant.fromEpochMilliseconds(0)..Instant.fromEpochMilliseconds(10_000L) repo.calendars().test { @@ -430,9 +415,9 @@ class CalendarRepositoryImplTest { fun `calendars does not re-emit an unchanged list`(@TempDir tempDir: Path) = runTest { // The store is shared with SettingsPrefs, so an unrelated write would // otherwise re-run every view's combine for an identical list. - val prefs = newPrefs(tempDir) + val prefs = testPrefs(tempDir) val fake = FakeCalendarDataSource().apply { calendarsResult = listOf(makeCal(1L)) } - val repo = CalendarRepositoryImpl(fake, prefs, newSettings(tempDir), UnconfinedTestDispatcher(testScheduler)) + val repo = testRepository(fake, tempDir, UnconfinedTestDispatcher(testScheduler), prefs = prefs) repo.calendars().test { assertThat(awaitItem().map { it.id }).containsExactly(1L) @@ -452,7 +437,7 @@ class CalendarRepositoryImplTest { // The reconciler's shape: write VISIBLE = 0, then release the id // app-side. The provider's notification arrives afterwards, so the // release must not be read against the pre-write snapshot. - val prefs = newPrefs(tempDir) + val prefs = testPrefs(tempDir) prefs.addPendingDisabledCalendarIds(setOf(2L)) val fake = FakeCalendarDataSource().apply { calendarsResult = listOf(makeCal(1L), makeCal(2L)) @@ -460,7 +445,7 @@ class CalendarRepositoryImplTest { listOf(makeEvent(10L, "A", calendarId = 1L), makeEvent(11L, "B", calendarId = 2L)) } } - val repo = CalendarRepositoryImpl(fake, prefs, newSettings(tempDir), UnconfinedTestDispatcher(testScheduler)) + val repo = testRepository(fake, tempDir, UnconfinedTestDispatcher(testScheduler), prefs = prefs) val range = Instant.fromEpochMilliseconds(0)..Instant.fromEpochMilliseconds(10_000L) // Warm the snapshot the way an open view would. @@ -486,7 +471,7 @@ class CalendarRepositoryImplTest { fun `searchEvents drops results from calendars that are off or hidden`( @TempDir tempDir: Path, ) = runTest { - val prefs = newPrefs(tempDir) + val prefs = testPrefs(tempDir) prefs.setHiddenCalendarIds(setOf(3L)) val fake = FakeCalendarDataSource().apply { calendarsResult = listOf(makeCal(1L), makeCal(2L, visible = false), makeCal(3L)) @@ -498,7 +483,7 @@ class CalendarRepositoryImplTest { ) } } - val repo = CalendarRepositoryImpl(fake, prefs, newSettings(tempDir), Dispatchers.Unconfined) + val repo = testRepository(fake, tempDir, Dispatchers.Unconfined, prefs = prefs) assertThat(repo.searchEvents("e").map { it.event.title }).containsExactly("Shown") } @@ -506,12 +491,12 @@ class CalendarRepositoryImplTest { @Test fun `createEvent delegates and returns the new id`(@TempDir tempDir: Path) = runTest { val fake = FakeCalendarDataSource().apply { nextInsertId = 77L } - val repo = CalendarRepositoryImpl(fake, newPrefs(tempDir), newSettings(tempDir), Dispatchers.Unconfined) + val repo = testRepository(fake, tempDir, Dispatchers.Unconfined) val form = EventForm( calendarId = 1L, title = "Stand-up", - start = LocalDateTime(LocalDate(2026, 6, 12), LocalTime(9, 0)), - end = LocalDateTime(LocalDate(2026, 6, 12), LocalTime(9, 15)), + start = FormTime(LocalDateTime(LocalDate(2026, 6, 12), LocalTime(9, 0))), + end = FormTime(LocalDateTime(LocalDate(2026, 6, 12), LocalTime(9, 15))), ) val id = repo.createEvent(form) @@ -525,14 +510,14 @@ class CalendarRepositoryImplTest { @TempDir tempDir: Path, ) = runTest { val fake = FakeCalendarDataSource() - val settings = newSettings(tempDir) + val settings = testSettings(tempDir) settings.setAllDayReminderTimeMinutes(8 * 60) // 08:00 - val repo = CalendarRepositoryImpl(fake, newPrefs(tempDir), settings, Dispatchers.Unconfined) + val repo = testRepository(fake, tempDir, Dispatchers.Unconfined, settings = settings) val form = EventForm( calendarId = 1L, isAllDay = true, - start = LocalDateTime(LocalDate(2026, 6, 12), LocalTime(0, 0)), - end = LocalDateTime(LocalDate(2026, 6, 12), LocalTime(0, 0)), + start = FormTime(LocalDateTime(LocalDate(2026, 6, 12), LocalTime(0, 0))), + end = FormTime(LocalDateTime(LocalDate(2026, 6, 12), LocalTime(0, 0))), ) repo.createEvent(form) @@ -545,11 +530,11 @@ class CalendarRepositoryImplTest { val fake = FakeCalendarDataSource().apply { writeError = WriteFailedException("insert event") } - val repo = CalendarRepositoryImpl(fake, newPrefs(tempDir), newSettings(tempDir), Dispatchers.Unconfined) + val repo = testRepository(fake, tempDir, Dispatchers.Unconfined) val form = EventForm( calendarId = 1L, - start = LocalDateTime(LocalDate(2026, 6, 12), LocalTime(9, 0)), - end = LocalDateTime(LocalDate(2026, 6, 12), LocalTime(10, 0)), + start = FormTime(LocalDateTime(LocalDate(2026, 6, 12), LocalTime(9, 0))), + end = FormTime(LocalDateTime(LocalDate(2026, 6, 12), LocalTime(10, 0))), ) try { @@ -563,12 +548,12 @@ class CalendarRepositoryImplTest { @Test fun `updateEvent forwards id and both forms`(@TempDir tempDir: Path) = runTest { val fake = FakeCalendarDataSource() - val repo = CalendarRepositoryImpl(fake, newPrefs(tempDir), newSettings(tempDir), Dispatchers.Unconfined) + val repo = testRepository(fake, tempDir, Dispatchers.Unconfined) val original = EventForm( calendarId = 1L, title = "Stand-up", - start = LocalDateTime(LocalDate(2026, 6, 12), LocalTime(9, 0)), - end = LocalDateTime(LocalDate(2026, 6, 12), LocalTime(9, 15)), + start = FormTime(LocalDateTime(LocalDate(2026, 6, 12), LocalTime(9, 0))), + end = FormTime(LocalDateTime(LocalDate(2026, 6, 12), LocalTime(9, 15))), ) val updated = original.copy(title = "Daily") @@ -580,12 +565,12 @@ class CalendarRepositoryImplTest { @Test fun `moveEvent forwards id, target calendar and both forms`(@TempDir tempDir: Path) = runTest { val fake = FakeCalendarDataSource().apply { nextInsertId = 77L } - val repo = CalendarRepositoryImpl(fake, newPrefs(tempDir), newSettings(tempDir), Dispatchers.Unconfined) + val repo = testRepository(fake, tempDir, Dispatchers.Unconfined) val original = EventForm( calendarId = 1L, title = "Stand-up", - start = LocalDateTime(LocalDate(2026, 6, 12), LocalTime(9, 0)), - end = LocalDateTime(LocalDate(2026, 6, 12), LocalTime(9, 15)), + start = FormTime(LocalDateTime(LocalDate(2026, 6, 12), LocalTime(9, 0))), + end = FormTime(LocalDateTime(LocalDate(2026, 6, 12), LocalTime(9, 15))), ) val updated = original.copy(calendarId = 3L) @@ -602,11 +587,11 @@ class CalendarRepositoryImplTest { val fake = FakeCalendarDataSource().apply { writeError = WriteFailedException("insert moved event into calendar id=3") } - val repo = CalendarRepositoryImpl(fake, newPrefs(tempDir), newSettings(tempDir), Dispatchers.Unconfined) + val repo = testRepository(fake, tempDir, Dispatchers.Unconfined) val form = EventForm( calendarId = 1L, - start = LocalDateTime(LocalDate(2026, 6, 12), LocalTime(9, 0)), - end = LocalDateTime(LocalDate(2026, 6, 12), LocalTime(10, 0)), + start = FormTime(LocalDateTime(LocalDate(2026, 6, 12), LocalTime(9, 0))), + end = FormTime(LocalDateTime(LocalDate(2026, 6, 12), LocalTime(10, 0))), ) try { @@ -622,11 +607,11 @@ class CalendarRepositoryImplTest { val fake = FakeCalendarDataSource().apply { writeError = WriteFailedException("update event id=42") } - val repo = CalendarRepositoryImpl(fake, newPrefs(tempDir), newSettings(tempDir), Dispatchers.Unconfined) + val repo = testRepository(fake, tempDir, Dispatchers.Unconfined) val form = EventForm( calendarId = 1L, - start = LocalDateTime(LocalDate(2026, 6, 12), LocalTime(9, 0)), - end = LocalDateTime(LocalDate(2026, 6, 12), LocalTime(10, 0)), + start = FormTime(LocalDateTime(LocalDate(2026, 6, 12), LocalTime(9, 0))), + end = FormTime(LocalDateTime(LocalDate(2026, 6, 12), LocalTime(10, 0))), ) try { @@ -640,7 +625,7 @@ class CalendarRepositoryImplTest { @Test fun `deleteEvent delegates to the data source`(@TempDir tempDir: Path) = runTest { val fake = FakeCalendarDataSource() - val repo = CalendarRepositoryImpl(fake, newPrefs(tempDir), newSettings(tempDir), Dispatchers.Unconfined) + val repo = testRepository(fake, tempDir, Dispatchers.Unconfined) repo.deleteEvent(eventId = 42L) @@ -651,7 +636,7 @@ class CalendarRepositoryImplTest { @Test fun `deleteOccurrence forwards event id and begin time`(@TempDir tempDir: Path) = runTest { val fake = FakeCalendarDataSource() - val repo = CalendarRepositoryImpl(fake, newPrefs(tempDir), newSettings(tempDir), Dispatchers.Unconfined) + val repo = testRepository(fake, tempDir, Dispatchers.Unconfined) repo.deleteOccurrence(eventId = 42L, beginMillis = 1_000L) @@ -662,7 +647,7 @@ class CalendarRepositoryImplTest { @Test fun `deleteEventFromOccurrence forwards event id and begin time`(@TempDir tempDir: Path) = runTest { val fake = FakeCalendarDataSource() - val repo = CalendarRepositoryImpl(fake, newPrefs(tempDir), newSettings(tempDir), Dispatchers.Unconfined) + val repo = testRepository(fake, tempDir, Dispatchers.Unconfined) repo.deleteEventFromOccurrence(eventId = 42L, beginMillis = 1_000L) @@ -674,12 +659,12 @@ class CalendarRepositoryImplTest { @Test fun `updateOccurrence forwards target and form, returns the exception id`(@TempDir tempDir: Path) = runTest { val fake = FakeCalendarDataSource().apply { nextInsertId = 88L } - val repo = CalendarRepositoryImpl(fake, newPrefs(tempDir), newSettings(tempDir), Dispatchers.Unconfined) + val repo = testRepository(fake, tempDir, Dispatchers.Unconfined) val form = EventForm( calendarId = 1L, title = "Moved", - start = LocalDateTime(LocalDate(2026, 6, 12), LocalTime(9, 0)), - end = LocalDateTime(LocalDate(2026, 6, 12), LocalTime(10, 0)), + start = FormTime(LocalDateTime(LocalDate(2026, 6, 12), LocalTime(9, 0))), + end = FormTime(LocalDateTime(LocalDate(2026, 6, 12), LocalTime(10, 0))), ) val id = repo.updateOccurrence( @@ -697,12 +682,12 @@ class CalendarRepositoryImplTest { @Test fun `updateEventFromOccurrence forwards target and forms, returns the new id`(@TempDir tempDir: Path) = runTest { val fake = FakeCalendarDataSource().apply { nextInsertId = 99L } - val repo = CalendarRepositoryImpl(fake, newPrefs(tempDir), newSettings(tempDir), Dispatchers.Unconfined) + val repo = testRepository(fake, tempDir, Dispatchers.Unconfined) val original = EventForm( calendarId = 1L, title = "Weekly", - start = LocalDateTime(LocalDate(2026, 6, 12), LocalTime(9, 0)), - end = LocalDateTime(LocalDate(2026, 6, 12), LocalTime(10, 0)), + start = FormTime(LocalDateTime(LocalDate(2026, 6, 12), LocalTime(9, 0))), + end = FormTime(LocalDateTime(LocalDate(2026, 6, 12), LocalTime(10, 0))), rrule = "FREQ=WEEKLY", ) val updated = original.copy(title = "Weekly, renamed") @@ -724,7 +709,7 @@ class CalendarRepositoryImplTest { val fake = FakeCalendarDataSource().apply { writeError = WriteFailedException("delete event id=42") } - val repo = CalendarRepositoryImpl(fake, newPrefs(tempDir), newSettings(tempDir), Dispatchers.Unconfined) + val repo = testRepository(fake, tempDir, Dispatchers.Unconfined) try { repo.deleteEvent(eventId = 42L) @@ -737,7 +722,7 @@ class CalendarRepositoryImplTest { @Test fun `createLocalCalendar delegates and returns the new id`(@TempDir tempDir: Path) = runTest { val fake = FakeCalendarDataSource().apply { nextCalendarId = 501L } - val repo = CalendarRepositoryImpl(fake, newPrefs(tempDir), newSettings(tempDir), Dispatchers.Unconfined) + val repo = testRepository(fake, tempDir, Dispatchers.Unconfined) val id = repo.createLocalCalendar( displayName = "Home", @@ -754,7 +739,7 @@ class CalendarRepositoryImplTest { @Test fun `updateCalendar forwards id, name, color and description`(@TempDir tempDir: Path) = runTest { val fake = FakeCalendarDataSource() - val repo = CalendarRepositoryImpl(fake, newPrefs(tempDir), newSettings(tempDir), Dispatchers.Unconfined) + val repo = testRepository(fake, tempDir, Dispatchers.Unconfined) repo.updateCalendar( id = 5L, @@ -771,7 +756,7 @@ class CalendarRepositoryImplTest { @Test fun `deleteCalendar delegates to the data source`(@TempDir tempDir: Path) = runTest { val fake = FakeCalendarDataSource() - val repo = CalendarRepositoryImpl(fake, newPrefs(tempDir), newSettings(tempDir), Dispatchers.Unconfined) + val repo = testRepository(fake, tempDir, Dispatchers.Unconfined) repo.deleteCalendar(id = 7L) @@ -783,7 +768,7 @@ class CalendarRepositoryImplTest { val fake = FakeCalendarDataSource().apply { writeError = WriteFailedException("create local calendar 'Home'") } - val repo = CalendarRepositoryImpl(fake, newPrefs(tempDir), newSettings(tempDir), Dispatchers.Unconfined) + val repo = testRepository(fake, tempDir, Dispatchers.Unconfined) try { repo.createLocalCalendar(displayName = "Home", color = 0, description = null) @@ -798,7 +783,7 @@ class CalendarRepositoryImplTest { val fake = FakeCalendarDataSource().apply { eventDetailResult = { null } } - val repo = CalendarRepositoryImpl(fake, newPrefs(tempDir), newSettings(tempDir), Dispatchers.Unconfined) + val repo = testRepository(fake, tempDir, Dispatchers.Unconfined) try { repo.eventDetail(eventId = 999L) @@ -809,15 +794,15 @@ class CalendarRepositoryImplTest { } @Test - fun `eventColorPalette delegates to the data source for the given calendar`( + fun `eventColorPalette reads the given calendar's published palette`( @TempDir tempDir: Path, ) = runTest { val fake = FakeCalendarDataSource().apply { - eventColorPaletteResult = { id -> + publishedEventColorsResult = { id -> if (id == 7L) listOf(EventColorOption("5", 0xFF33B679.toInt())) else emptyList() } } - val repo = CalendarRepositoryImpl(fake, newPrefs(tempDir), newSettings(tempDir), Dispatchers.Unconfined) + val repo = testRepository(fake, tempDir, Dispatchers.Unconfined) assertThat(repo.eventColorPalette(7L)) .containsExactly(EventColorOption("5", 0xFF33B679.toInt())) @@ -831,7 +816,7 @@ class CalendarRepositoryImplTest { val fake = FakeCalendarDataSource().apply { existingUidsResult = setOf("dup@x") } - val repo = CalendarRepositoryImpl(fake, newPrefs(tempDir), newSettings(tempDir), Dispatchers.Unconfined) + val repo = testRepository(fake, tempDir, Dispatchers.Unconfined) val events = listOf( parsedEvent("dup@x"), // already present → skipped parsedEvent("new@x"), // inserted @@ -853,7 +838,7 @@ class CalendarRepositoryImplTest { // A foreign export can hold a row the provider throws on outright; that // must cost the user one event, not the whole file (Codeberg #225). val fake = FakeCalendarDataSource().apply { failingImportSummaries += "bad" } - val repo = CalendarRepositoryImpl(fake, newPrefs(tempDir), newSettings(tempDir), Dispatchers.Unconfined) + val repo = testRepository(fake, tempDir, Dispatchers.Unconfined) val events = listOf( parsedEvent("a@x", summary = "good"), parsedEvent("b@x", summary = "bad"), @@ -880,7 +865,7 @@ class CalendarRepositoryImplTest { importsBeforeError = 2 writeError = SecurityException("WRITE_CALENDAR revoked") } - val repo = CalendarRepositoryImpl(fake, newPrefs(tempDir), newSettings(tempDir), Dispatchers.Unconfined) + val repo = testRepository(fake, tempDir, Dispatchers.Unconfined) val summary = repo.importEvents( targetCalendarId = 3L, @@ -905,7 +890,7 @@ class CalendarRepositoryImplTest { importsBeforeError = 1 writeError = SecurityException("WRITE_CALENDAR revoked") } - val repo = CalendarRepositoryImpl(fake, newPrefs(tempDir), newSettings(tempDir), Dispatchers.Unconfined) + val repo = testRepository(fake, tempDir, Dispatchers.Unconfined) val summary = repo.importEvents( targetCalendarId = 3L, @@ -926,7 +911,7 @@ class CalendarRepositoryImplTest { val fake = FakeCalendarDataSource().apply { publishedEventColorsResult = { lookups++; emptyList() } } - val repo = CalendarRepositoryImpl(fake, newPrefs(tempDir), newSettings(tempDir), Dispatchers.Unconfined) + val repo = testRepository(fake, tempDir, Dispatchers.Unconfined) repo.importEvents(3L, List(5) { parsedEvent("e$it@x") }) @@ -944,9 +929,8 @@ class CalendarRepositoryImplTest { val published = listOf(EventColorOption("1", 0xFF808080.toInt())) val fake = FakeCalendarDataSource().apply { publishedEventColorsResult = { published } - eventColorPaletteResult = { emptyList() } } - val repo = CalendarRepositoryImpl(fake, newPrefs(tempDir), newSettings(tempDir), Dispatchers.Unconfined) + val repo = testRepository(fake, tempDir, Dispatchers.Unconfined) repo.importEvents(3L, listOf(parsedEvent("a@x"))) @@ -958,7 +942,7 @@ class CalendarRepositoryImplTest { @TempDir tempDir: Path, ) = runTest { val fake = FakeCalendarDataSource() - val repo = CalendarRepositoryImpl(fake, newPrefs(tempDir), newSettings(tempDir), Dispatchers.Unconfined) + val repo = testRepository(fake, tempDir, Dispatchers.Unconfined) repo.exportEvents(calendarIds = setOf(1L, 4L)) @@ -970,7 +954,7 @@ class CalendarRepositoryImplTest { @TempDir tempDir: Path, ) = runTest { val fake = FakeCalendarDataSource() - val repo = CalendarRepositoryImpl(fake, newPrefs(tempDir), newSettings(tempDir), Dispatchers.Unconfined) + val repo = testRepository(fake, tempDir, Dispatchers.Unconfined) repo.exportEvents() diff --git a/app/src/test/java/de/jeanlucmakiola/calendula/data/calendar/EventWriteMapperTest.kt b/app/src/test/java/de/jeanlucmakiola/calendula/data/calendar/EventWriteMapperTest.kt index db59c958..802d89da 100644 --- a/app/src/test/java/de/jeanlucmakiola/calendula/data/calendar/EventWriteMapperTest.kt +++ b/app/src/test/java/de/jeanlucmakiola/calendula/data/calendar/EventWriteMapperTest.kt @@ -5,12 +5,15 @@ import com.google.common.truth.Truth.assertThat import de.jeanlucmakiola.calendula.domain.AccessLevel import de.jeanlucmakiola.calendula.domain.Availability import de.jeanlucmakiola.calendula.domain.EventForm +import de.jeanlucmakiola.calendula.domain.FormTime import de.jeanlucmakiola.calendula.domain.realignRecurrence import kotlinx.datetime.LocalDate import kotlinx.datetime.LocalDateTime import kotlinx.datetime.LocalTime +import kotlinx.datetime.UtcOffset import org.junit.jupiter.api.Test import java.time.ZoneId +import kotlin.time.Instant class EventWriteMapperTest { @@ -24,8 +27,8 @@ class EventWriteMapperTest { ): EventForm = EventForm( calendarId = 1L, isAllDay = isAllDay, - start = start, - end = end, + start = FormTime(start), + end = FormTime(end), timezone = timezone, ) @@ -154,8 +157,8 @@ class EventWriteMapperTest { assertThat(values).doesNotContainKey(CalendarContract.Events.EVENT_TIMEZONE) val moved = original.copy( - start = LocalDateTime(LocalDate(2026, 6, 11), LocalTime(11, 0)), - end = LocalDateTime(LocalDate(2026, 6, 11), LocalTime(12, 30)), + start = FormTime(LocalDateTime(LocalDate(2026, 6, 11), LocalTime(11, 0))), + end = FormTime(LocalDateTime(LocalDate(2026, 6, 11), LocalTime(12, 30))), ) assertThat(update(original, moved)[CalendarContract.Events.EVENT_TIMEZONE]) .isEqualTo("America/New_York") @@ -201,8 +204,8 @@ class EventWriteMapperTest { fun `time edit on a one-off event writes absolute times and clears recurrence columns`() { val original = form() val updated = original.copy( - start = LocalDateTime(LocalDate(2026, 6, 11), LocalTime(11, 0)), - end = LocalDateTime(LocalDate(2026, 6, 11), LocalTime(12, 0)), + start = FormTime(LocalDateTime(LocalDate(2026, 6, 11), LocalTime(11, 0))), + end = FormTime(LocalDateTime(LocalDate(2026, 6, 11), LocalTime(12, 0))), ) val values = update(original, updated) // 2026-06-11 11:00 CEST == 09:00Z. @@ -221,8 +224,8 @@ class EventWriteMapperTest { val original = form().copy(rrule = "FREQ=WEEKLY") val updated = original.copy( // Pushed one hour later than the displayed occurrence. - start = LocalDateTime(LocalDate(2026, 6, 11), LocalTime(11, 0)), - end = LocalDateTime(LocalDate(2026, 6, 11), LocalTime(12, 30)), + start = FormTime(LocalDateTime(LocalDate(2026, 6, 11), LocalTime(11, 0))), + end = FormTime(LocalDateTime(LocalDate(2026, 6, 11), LocalTime(12, 30))), ) val values = update(original, updated) assertThat(values[CalendarContract.Events.DTSTART]).isEqualTo(seriesStart + 3_600_000L) @@ -263,8 +266,8 @@ class EventWriteMapperTest { end = LocalDateTime(LocalDate(2026, 7, 15), LocalTime(10, 0)), ).copy(rrule = "FREQ=WEEKLY") val moved = original.copy( - start = LocalDateTime(LocalDate(2026, 7, 15), LocalTime(10, 0)), - end = LocalDateTime(LocalDate(2026, 7, 15), LocalTime(11, 0)), + start = FormTime(LocalDateTime(LocalDate(2026, 7, 15), LocalTime(10, 0))), + end = FormTime(LocalDateTime(LocalDate(2026, 7, 15), LocalTime(11, 0))), ) assertThat(update(original, moved, series)[CalendarContract.Events.DTSTART]) @@ -279,8 +282,8 @@ class EventWriteMapperTest { end = LocalDateTime(LocalDate(2026, 1, 7), LocalTime(10, 0)), ).copy(rrule = "FREQ=WEEKLY") val moved = original.copy( - start = LocalDateTime(LocalDate(2026, 1, 9), LocalTime(14, 30)), - end = LocalDateTime(LocalDate(2026, 1, 9), LocalTime(15, 30)), + start = FormTime(LocalDateTime(LocalDate(2026, 1, 9), LocalTime(14, 30))), + end = FormTime(LocalDateTime(LocalDate(2026, 1, 9), LocalTime(15, 30))), ) assertThat(update(original, moved, series)[CalendarContract.Events.DTSTART]) @@ -297,8 +300,8 @@ class EventWriteMapperTest { end = LocalDateTime(LocalDate(2026, 6, 8), LocalTime(10, 0)), ).copy(rrule = "FREQ=WEEKLY;BYDAY=MO") val moved = original.copy( - start = LocalDateTime(LocalDate(2026, 6, 10), LocalTime(9, 0)), - end = LocalDateTime(LocalDate(2026, 6, 10), LocalTime(10, 0)), + start = FormTime(LocalDateTime(LocalDate(2026, 6, 10), LocalTime(9, 0))), + end = FormTime(LocalDateTime(LocalDate(2026, 6, 10), LocalTime(10, 0))), rrule = realignRecurrence("FREQ=WEEKLY;BYDAY=MO", LocalDate(2026, 6, 8), LocalDate(2026, 6, 10)), ) @@ -319,8 +322,8 @@ class EventWriteMapperTest { end = LocalDateTime(LocalDate(2026, 1, 7), LocalTime(10, 30)), ).copy(rrule = "FREQ=WEEKLY") val moved = original.copy( - start = LocalDateTime(LocalDate(2026, 1, 8), LocalTime(9, 0)), - end = LocalDateTime(LocalDate(2026, 1, 8), LocalTime(10, 30)), + start = FormTime(LocalDateTime(LocalDate(2026, 1, 8), LocalTime(9, 0))), + end = FormTime(LocalDateTime(LocalDate(2026, 1, 8), LocalTime(10, 30))), ) assertThat(update(original, moved, series)[CalendarContract.Events.DURATION]) @@ -331,8 +334,8 @@ class EventWriteMapperTest { fun `shifting a one-off event and back again restores the original values`() { val original = form() val moved = original.copy( - start = LocalDateTime(LocalDate(2026, 6, 12), LocalTime(14, 0)), - end = LocalDateTime(LocalDate(2026, 6, 12), LocalTime(15, 0)), + start = FormTime(LocalDateTime(LocalDate(2026, 6, 12), LocalTime(14, 0))), + end = FormTime(LocalDateTime(LocalDate(2026, 6, 12), LocalTime(15, 0))), ) val forward = update(original, moved) @@ -357,8 +360,8 @@ class EventWriteMapperTest { end = LocalDateTime(LocalDate(2026, 7, 15), LocalTime(10, 0)), ).copy(rrule = "FREQ=WEEKLY") val moved = original.copy( - start = LocalDateTime(LocalDate(2026, 7, 17), LocalTime(14, 30)), - end = LocalDateTime(LocalDate(2026, 7, 17), LocalTime(15, 30)), + start = FormTime(LocalDateTime(LocalDate(2026, 7, 17), LocalTime(14, 30))), + end = FormTime(LocalDateTime(LocalDate(2026, 7, 17), LocalTime(15, 30))), ) val movedAnchor = update(original, moved, series)[CalendarContract.Events.DTSTART] as Long @@ -678,8 +681,8 @@ class EventWriteMapperTest { /** [julySeries] pushed to [hour]:00, the shift an "all events" time edit makes. */ private fun EventForm.atHour(hour: Int): EventForm = copy( - start = LocalDateTime(LocalDate(2026, 7, 15), LocalTime(hour, 0)), - end = LocalDateTime(LocalDate(2026, 7, 15), LocalTime(hour + 1, 0)), + start = FormTime(LocalDateTime(LocalDate(2026, 7, 15), LocalTime(hour, 0))), + end = FormTime(LocalDateTime(LocalDate(2026, 7, 15), LocalTime(hour + 1, 0))), ) @Test @@ -728,8 +731,8 @@ class EventWriteMapperTest { end = LocalDateTime(LocalDate(2026, 7, 15), LocalTime(0, 0)), ).copy(rrule = "FREQ=WEEKLY") val moved = original.copy( - start = LocalDateTime(LocalDate(2026, 7, 17), LocalTime(0, 0)), - end = LocalDateTime(LocalDate(2026, 7, 17), LocalTime(0, 0)), + start = FormTime(LocalDateTime(LocalDate(2026, 7, 17), LocalTime(0, 0))), + end = FormTime(LocalDateTime(LocalDate(2026, 7, 17), LocalTime(0, 0))), ) assertThat(update(original, moved, series, "20260722")[CalendarContract.Events.EXDATE]) @@ -748,8 +751,8 @@ class EventWriteMapperTest { end = LocalDateTime(LocalDate(2026, 7, 15), LocalTime(0, 0)), ).copy(rrule = "FREQ=WEEKLY") val moved = original.copy( - start = LocalDateTime(LocalDate(2026, 7, 17), LocalTime(0, 0)), - end = LocalDateTime(LocalDate(2026, 7, 17), LocalTime(0, 0)), + start = FormTime(LocalDateTime(LocalDate(2026, 7, 17), LocalTime(0, 0))), + end = FormTime(LocalDateTime(LocalDate(2026, 7, 17), LocalTime(0, 0))), ) val values = update(original, moved, series, "20260722T000000Z") @@ -768,8 +771,8 @@ class EventWriteMapperTest { end = LocalDateTime(LocalDate(2026, 7, 15), LocalTime(0, 0)), ).copy(rrule = "FREQ=WEEKLY") val moved = original.copy( - start = LocalDateTime(LocalDate(2026, 7, 17), LocalTime(0, 0)), - end = LocalDateTime(LocalDate(2026, 7, 17), LocalTime(0, 0)), + start = FormTime(LocalDateTime(LocalDate(2026, 7, 17), LocalTime(0, 0))), + end = FormTime(LocalDateTime(LocalDate(2026, 7, 17), LocalTime(0, 0))), ) val values = update(original, moved, series, "20260722T000000") @@ -787,8 +790,8 @@ class EventWriteMapperTest { end = LocalDateTime(LocalDate(2026, 7, 15), LocalTime(0, 0)), ).copy(rrule = "FREQ=WEEKLY") val moved = original.copy( - start = LocalDateTime(LocalDate(2026, 7, 17), LocalTime(0, 0)), - end = LocalDateTime(LocalDate(2026, 7, 17), LocalTime(0, 0)), + start = FormTime(LocalDateTime(LocalDate(2026, 7, 17), LocalTime(0, 0))), + end = FormTime(LocalDateTime(LocalDate(2026, 7, 17), LocalTime(0, 0))), ) val values = update(original, moved, series, "20260722T090000Z") @@ -815,8 +818,8 @@ class EventWriteMapperTest { ).copy(rrule = "FREQ=WEEKLY") val timed = original.copy( isAllDay = false, - start = LocalDateTime(LocalDate(2026, 7, 15), LocalTime(9, 0)), - end = LocalDateTime(LocalDate(2026, 7, 15), LocalTime(10, 0)), + start = FormTime(LocalDateTime(LocalDate(2026, 7, 15), LocalTime(9, 0))), + end = FormTime(LocalDateTime(LocalDate(2026, 7, 15), LocalTime(10, 0))), ) // The excluded day gains the new 09:00 Berlin time-of-day == 07:00Z. assertThat(update(original, timed, series, "20260722")[CalendarContract.Events.EXDATE]) @@ -898,8 +901,8 @@ class EventWriteMapperTest { val series = instantAt("2026-01-07T09:00", "Europe/Berlin") val original = julySeries() val moved = original.copy( - start = LocalDateTime(LocalDate(2026, 7, 17), LocalTime(14, 30)), - end = LocalDateTime(LocalDate(2026, 7, 17), LocalTime(15, 30)), + start = FormTime(LocalDateTime(LocalDate(2026, 7, 17), LocalTime(14, 30))), + end = FormTime(LocalDateTime(LocalDate(2026, 7, 17), LocalTime(15, 30))), ) val exdate = "20260722T070000Z" @@ -1176,47 +1179,21 @@ class EventWriteMapperTest { assertThat(values[CalendarContract.Events.DURATION]).isEqualTo("P5400S") } - // --- buildCopiedExceptionValues (calendar move: exception replay) --- - - private fun exceptionSnapshot( - isCancelled: Boolean = false, - duration: String? = null, - // Occurrence starts one hour into the day and runs 30 minutes. - dtEndMillis: Long? = 1_781_164_800_000L + 3_600_000L + 1_800_000L, - ) = ExceptionRowSnapshot( - exceptionEventId = 42L, - originalInstanceMillis = 1_781_164_800_000L, - isCancelled = isCancelled, - status = if (isCancelled) CalendarContract.Events.STATUS_CANCELED else CalendarContract.Events.STATUS_CONFIRMED, - title = "Moved occurrence", - isAllDay = false, - dtStartMillis = 1_781_164_800_000L + 3_600_000L, - dtEndMillis = dtEndMillis, - duration = duration, - timezone = "Europe/Berlin", - availability = CalendarContract.Events.AVAILABILITY_BUSY, - accessLevel = CalendarContract.Events.ACCESS_DEFAULT, - location = "", - description = "Notes", - ) - @Test - fun `copied modified occurrence carries the original instance and DURATION not DTEND`() { - val values = buildCopiedExceptionValues(exceptionSnapshot()) - assertThat(values[CalendarContract.Events.ORIGINAL_INSTANCE_TIME]) - .isEqualTo(1_781_164_800_000L) - assertThat(values[CalendarContract.Events.TITLE]).isEqualTo("Moved occurrence") - assertThat(values[CalendarContract.Events.DTSTART]).isEqualTo(1_781_164_800_000L + 3_600_000L) - // 30-minute occurrence derived from DTEND, written as DURATION only. - assertThat(values[CalendarContract.Events.DURATION]).isEqualTo("P1800S") - assertThat(values).doesNotContainKey(CalendarContract.Events.DTEND) - assertThat(values).containsEntry(CalendarContract.Events.EVENT_LOCATION, null) - } - - @Test - fun `copied modified occurrence keeps a stored duration verbatim`() { - val values = buildCopiedExceptionValues(exceptionSnapshot(duration = "P900S", dtEndMillis = null)) - assertThat(values[CalendarContract.Events.DURATION]).isEqualTo("P900S") + fun `several occurrences are excluded in one exdate write`() { + val values = buildOccurrencesExdateValues( + existingExdate = "20260601T090000Z", + occurrences = listOf(1_781_168_400_000L, 1_781_254_800_000L, 1_781_168_400_000L), + dtStartMillis = 1_780_304_400_000L, + rrule = "FREQ=DAILY", + rdate = null, + duration = "P3600S", + timezone = "Europe/Berlin", + allDay = 0, + ) + assertThat(values[CalendarContract.Events.EXDATE]) + .isEqualTo("20260601T090000Z,20260611T090000Z,20260612T090000Z") + assertThat(values[CalendarContract.Events.RRULE]).isEqualTo("FREQ=DAILY") } @Test @@ -1387,4 +1364,67 @@ class EventWriteMapperTest { assertThat(parent[CalendarContract.Events.DTSTART]).isEqualTo(1_780_560_000_000L) assertThat(parent[CalendarContract.Events.RRULE]).isEqualTo("FREQ=WEEKLY") } + + @Test + fun `a time in the repeated fall-back hour is written at its own offset`() { + val repeated = LocalDateTime(LocalDate(2026, 10, 25), LocalTime(2, 0)) + val times = form(start = repeated, end = repeated) + .copy(start = FormTime(repeated, UtcOffset(hours = 2)), end = FormTime(repeated, UtcOffset(hours = 1))) + .toWriteTimes(berlin) + assertThat(times.dtStartMillis).isEqualTo(Instant.parse("2026-10-25T00:00:00Z").toEpochMilliseconds()) + assertThat(times.dtEndMillis).isEqualTo(Instant.parse("2026-10-25T01:00:00Z").toEpochMilliseconds()) + } + + @Test + fun `a move between the two repeated fall-back hours writes the new times`() { + // 02:30 CEST to 02:30 CET: the same wall clock, an hour later. + val repeated = LocalDateTime(LocalDate(2026, 10, 25), LocalTime(2, 30)) + val original = form(start = repeated, end = repeated) + .copy(start = FormTime(repeated, UtcOffset(hours = 2)), end = FormTime(repeated, UtcOffset(hours = 2))) + val updated = original.copy( + start = original.start.copy(offset = UtcOffset(hours = 1)), + end = original.end.copy(offset = UtcOffset(hours = 1)), + ) + val values = update(original, updated) + assertThat(values[CalendarContract.Events.DTSTART]) + .isEqualTo(Instant.parse("2026-10-25T01:30:00Z").toEpochMilliseconds()) + assertThat(values[CalendarContract.Events.DTEND]) + .isEqualTo(Instant.parse("2026-10-25T01:30:00Z").toEpochMilliseconds()) + } + + @Test + fun `an untouched form in the repeated fall-back hour writes no times`() { + val repeated = LocalDateTime(LocalDate(2026, 10, 25), LocalTime(2, 30)) + val original = form(start = repeated, end = repeated) + .copy(start = FormTime(repeated, UtcOffset(hours = 2)), end = FormTime(repeated, UtcOffset(hours = 1))) + assertThat(update(original, original.copy(title = "Renamed"))) + .doesNotContainKey(CalendarContract.Events.DTSTART) + } + + @Test + fun `a series anchored on the second repeated hour keeps it through a time edit`() { + // The series starts 02:30 CET on the fall-back day; an occurrence a week + // later gets ten more minutes. + val anchor = Instant.parse("2026-10-25T01:30:00Z").toEpochMilliseconds() + val original = form( + start = LocalDateTime(LocalDate(2026, 11, 1), LocalTime(2, 30)), + end = LocalDateTime(LocalDate(2026, 11, 1), LocalTime(3, 30)), + ).copy(rrule = "FREQ=WEEKLY") + val updated = original.copy(end = FormTime(LocalDateTime(LocalDate(2026, 11, 1), LocalTime(3, 40)))) + val values = update(original, updated, series = anchor) + assertThat(values[CalendarContract.Events.DTSTART]).isEqualTo(anchor) + } + + @Test + fun `a series anchor moved between the repeated hours follows the form`() { + // Editing the anchor occurrence itself from 02:30 CEST onto 02:30 CET. + val repeated = LocalDateTime(LocalDate(2026, 10, 25), LocalTime(2, 30)) + val anchor = Instant.parse("2026-10-25T00:30:00Z").toEpochMilliseconds() + val original = form(start = repeated, end = LocalDateTime(LocalDate(2026, 10, 25), LocalTime(4, 0))) + .copy(start = FormTime(repeated, UtcOffset(hours = 2)), rrule = "FREQ=WEEKLY") + val updated = original.copy(start = FormTime(repeated, UtcOffset(hours = 1))) + val values = update(original, updated, series = anchor) + assertThat(values[CalendarContract.Events.DTSTART]) + .isEqualTo(Instant.parse("2026-10-25T01:30:00Z").toEpochMilliseconds()) + } } diff --git a/app/src/test/java/de/jeanlucmakiola/calendula/data/calendar/FakeCalendarDataSource.kt b/app/src/test/java/de/jeanlucmakiola/calendula/data/calendar/FakeCalendarDataSource.kt index e4adc627..e22ec492 100644 --- a/app/src/test/java/de/jeanlucmakiola/calendula/data/calendar/FakeCalendarDataSource.kt +++ b/app/src/test/java/de/jeanlucmakiola/calendula/data/calendar/FakeCalendarDataSource.kt @@ -22,7 +22,6 @@ internal class FakeCalendarDataSource : CalendarDataSource { var instancesResult: (Long, Long) -> List = { _, _ -> emptyList() } var searchResult: (String) -> List = { _ -> emptyList() } var eventDetailResult: (Long) -> EventDetail? = { null } - var eventColorPaletteResult: (Long) -> List = { emptyList() } var publishedEventColorsResult: (Long) -> List = { emptyList() } var exportableEventsResult: List = emptyList() /** The [calendarIds] the last [exportableEvents] call received (null = all). */ @@ -80,8 +79,6 @@ internal class FakeCalendarDataSource : CalendarDataSource { override fun searchEvents(query: String): List = searchResult(query) override fun eventDetail(eventId: Long, allDayReminderTimeMinutes: Int): EventDetail? = eventDetailResult(eventId) - override fun eventColorPalette(calendarId: Long): List = - eventColorPaletteResult(calendarId) override fun publishedEventColors(calendarId: Long): List = publishedEventColorsResult(calendarId) override fun exportableEvents( diff --git a/app/src/test/java/de/jeanlucmakiola/calendula/data/contacts/SpecialDatesSyncEngineTest.kt b/app/src/test/java/de/jeanlucmakiola/calendula/data/contacts/SpecialDatesSyncEngineTest.kt index 09f9752c..43ffb651 100644 --- a/app/src/test/java/de/jeanlucmakiola/calendula/data/contacts/SpecialDatesSyncEngineTest.kt +++ b/app/src/test/java/de/jeanlucmakiola/calendula/data/contacts/SpecialDatesSyncEngineTest.kt @@ -1,12 +1,10 @@ package de.jeanlucmakiola.calendula.data.contacts import android.provider.CalendarContract -import androidx.datastore.core.DataStore -import androidx.datastore.preferences.core.PreferenceDataStoreFactory -import androidx.datastore.preferences.core.Preferences import com.google.common.truth.Truth.assertThat import de.jeanlucmakiola.calendula.data.calendar.FakeCalendarDataSource import de.jeanlucmakiola.calendula.data.calendar.ManagedEventRow +import de.jeanlucmakiola.calendula.testSettings import de.jeanlucmakiola.floret.reminders.ReminderOverride import de.jeanlucmakiola.calendula.data.prefs.SettingsPrefs import de.jeanlucmakiola.calendula.domain.contacts.ContactSpecialDate @@ -37,13 +35,6 @@ class SpecialDatesSyncEngineTest { } } - private fun prefs(tempDir: Path): SettingsPrefs { - val store: DataStore = PreferenceDataStoreFactory.create( - produceFile = { tempDir.resolve("settings_test.preferences_pb").toFile() }, - ) - return SettingsPrefs(store) - } - private fun birthday(key: String, name: String, month: Int, day: Int, year: Int?) = ContactSpecialDate(key, name, SpecialDateType.Birthday, month, day, year) @@ -53,7 +44,7 @@ class SpecialDatesSyncEngineTest { calendars: FakeCalendarDataSource = FakeCalendarDataSource(), enabled: Boolean = true, ): Pair { - val settings = prefs(tempDir) + val settings = testSettings(tempDir) if (enabled) settings.setSpecialDatesEnabled(true) return SpecialDatesSyncEngine(contacts, calendars, settings, FakeSpec()) to settings } diff --git a/app/src/test/java/de/jeanlucmakiola/calendula/data/prefs/CalendarPrefsTest.kt b/app/src/test/java/de/jeanlucmakiola/calendula/data/prefs/CalendarPrefsTest.kt index 7c1a9e99..9f0fb46b 100644 --- a/app/src/test/java/de/jeanlucmakiola/calendula/data/prefs/CalendarPrefsTest.kt +++ b/app/src/test/java/de/jeanlucmakiola/calendula/data/prefs/CalendarPrefsTest.kt @@ -1,9 +1,9 @@ package de.jeanlucmakiola.calendula.data.prefs -import androidx.datastore.core.DataStore -import androidx.datastore.preferences.core.PreferenceDataStoreFactory -import androidx.datastore.preferences.core.Preferences +import androidx.datastore.preferences.core.stringPreferencesKey import com.google.common.truth.Truth.assertThat +import de.jeanlucmakiola.calendula.testDataStore +import de.jeanlucmakiola.calendula.testPrefs import kotlinx.coroutines.flow.first import kotlinx.coroutines.test.runTest import org.junit.jupiter.api.Test @@ -12,20 +12,15 @@ import java.nio.file.Path class CalendarPrefsTest { - private fun newDataStore(tempDir: Path): DataStore = - PreferenceDataStoreFactory.create( - produceFile = { tempDir.resolve("test_prefs.preferences_pb").toFile() }, - ) - @Test fun `hiddenCalendarIds defaults to empty when unset`(@TempDir tempDir: Path) = runTest { - val prefs = CalendarPrefs(newDataStore(tempDir)) + val prefs = testPrefs(tempDir) assertThat(prefs.hiddenCalendarIds.first()).isEmpty() } @Test fun `setHiddenCalendarIds round-trips through DataStore`(@TempDir tempDir: Path) = runTest { - val store = newDataStore(tempDir) + val store = testDataStore(tempDir, "test_prefs") val prefs = CalendarPrefs(store) prefs.setHiddenCalendarIds(setOf(1L, 42L, 7L)) assertThat(prefs.hiddenCalendarIds.first()).isEqualTo(setOf(1L, 42L, 7L)) @@ -33,7 +28,7 @@ class CalendarPrefsTest { @Test fun `setting empty set clears storage`(@TempDir tempDir: Path) = runTest { - val prefs = CalendarPrefs(newDataStore(tempDir)) + val prefs = testPrefs(tempDir) prefs.setHiddenCalendarIds(setOf(1L)) prefs.setHiddenCalendarIds(emptySet()) assertThat(prefs.hiddenCalendarIds.first()).isEmpty() @@ -41,11 +36,11 @@ class CalendarPrefsTest { @Test fun `garbage stored string is parsed defensively`(@TempDir tempDir: Path) = runTest { - val store = newDataStore(tempDir) + val store = testDataStore(tempDir, "test_prefs") val prefs = CalendarPrefs(store) store.updateData { p -> val mutable = p.toMutablePreferences() - mutable[CalendarPrefs.HIDDEN_IDS_KEY] = "1,abc,3" + mutable[stringPreferencesKey("hidden_calendar_ids")] = "1,abc,3" mutable } assertThat(prefs.hiddenCalendarIds.first()).isEqualTo(setOf(1L, 3L)) @@ -57,10 +52,10 @@ class CalendarPrefsTest { ) = runTest { // Same key as the retired app-local "disabled calendars" model: an // upgrade inherits that set as switch-offs still owed to the provider. - val store = newDataStore(tempDir) + val store = testDataStore(tempDir, "test_prefs") val prefs = CalendarPrefs(store) store.updateData { p -> - p.toMutablePreferences().apply { this[CalendarPrefs.DISABLED_IDS_KEY] = "2,9" } + p.toMutablePreferences().apply { this[stringPreferencesKey("disabled_calendar_ids")] = "2,9" } } assertThat(prefs.pendingDisabledCalendarIds.first()).isEqualTo(setOf(2L, 9L)) } @@ -69,13 +64,13 @@ class CalendarPrefsTest { fun `the pending disabled set is empty when nothing was ever stored`( @TempDir tempDir: Path, ) = runTest { - val prefs = CalendarPrefs(newDataStore(tempDir)) + val prefs = testPrefs(tempDir) assertThat(prefs.pendingDisabledCalendarIds.first()).isEmpty() } @Test fun `pending ids are added and dropped one at a time`(@TempDir tempDir: Path) = runTest { - val prefs = CalendarPrefs(newDataStore(tempDir)) + val prefs = testPrefs(tempDir) prefs.addPendingDisabledCalendarIds(listOf(2L, 9L)) prefs.addPendingDisabledCalendarIds(listOf(4L)) @@ -88,7 +83,7 @@ class CalendarPrefsTest { fun `draining the pending set leaves the hidden set alone`( @TempDir tempDir: Path, ) = runTest { - val prefs = CalendarPrefs(newDataStore(tempDir)) + val prefs = testPrefs(tempDir) prefs.setHiddenCalendarIds(setOf(1L)) prefs.addPendingDisabledCalendarIds(setOf(2L)) @@ -104,7 +99,7 @@ class CalendarPrefsTest { ) = runTest { // Null is what makes the evaluation one-shot: "no" is stored just as // firmly as "yes", so the notice can't resurface on a later launch. - val prefs = CalendarPrefs(newDataStore(tempDir)) + val prefs = testPrefs(tempDir) assertThat(prefs.visibilityNoticePending.first()).isNull() prefs.setVisibilityNoticePending(true) diff --git a/app/src/test/java/de/jeanlucmakiola/calendula/data/prefs/SettingsPrefsTest.kt b/app/src/test/java/de/jeanlucmakiola/calendula/data/prefs/SettingsPrefsTest.kt index 42fc64f6..44101d11 100644 --- a/app/src/test/java/de/jeanlucmakiola/calendula/data/prefs/SettingsPrefsTest.kt +++ b/app/src/test/java/de/jeanlucmakiola/calendula/data/prefs/SettingsPrefsTest.kt @@ -1,11 +1,11 @@ package de.jeanlucmakiola.calendula.data.prefs +import de.jeanlucmakiola.calendula.testDataStore +import de.jeanlucmakiola.calendula.testSettings import de.jeanlucmakiola.floret.reminders.ReminderOverride -import androidx.datastore.core.DataStore -import androidx.datastore.preferences.core.PreferenceDataStoreFactory -import androidx.datastore.preferences.core.Preferences import androidx.compose.ui.unit.dp +import androidx.datastore.preferences.core.stringPreferencesKey import com.google.common.truth.Truth.assertThat import de.jeanlucmakiola.calendula.domain.EventFormField import de.jeanlucmakiola.calendula.domain.FontRole @@ -17,6 +17,8 @@ import de.jeanlucmakiola.calendula.ui.common.QuickSwitchConfig import de.jeanlucmakiola.calendula.ui.common.TimelineHours import de.jeanlucmakiola.calendula.ui.common.TimelineScale import de.jeanlucmakiola.calendula.ui.month.MonthViewStyle +import de.jeanlucmakiola.calendula.ui.onboarding.OnboardingStep +import de.jeanlucmakiola.floret.prefs.ThemeMode import kotlinx.coroutines.flow.first import kotlinx.coroutines.test.runTest import kotlinx.datetime.DayOfWeek @@ -27,14 +29,9 @@ import java.util.Locale class SettingsPrefsTest { - private fun newDataStore(tempDir: Path): DataStore = - PreferenceDataStoreFactory.create( - produceFile = { tempDir.resolve("settings_test.preferences_pb").toFile() }, - ) - @Test fun `defaults are system theme, dynamic colour on, auto week start`(@TempDir tempDir: Path) = runTest { - val prefs = SettingsPrefs(newDataStore(tempDir)) + val prefs = testSettings(tempDir) assertThat(prefs.themeMode.first()).isEqualTo(ThemeMode.SYSTEM) assertThat(prefs.dynamicColor.first()).isTrue() assertThat(prefs.weekStart.first()).isEqualTo(WeekStartPref.Auto) @@ -42,32 +39,39 @@ class SettingsPrefsTest { @Test fun `theme mode round-trips`(@TempDir tempDir: Path) = runTest { - val prefs = SettingsPrefs(newDataStore(tempDir)) + val prefs = testSettings(tempDir) prefs.setThemeMode(ThemeMode.DARK) assertThat(prefs.themeMode.first()).isEqualTo(ThemeMode.DARK) } + @Test + fun `black theme mode round-trips`(@TempDir tempDir: Path) = runTest { + val prefs = testSettings(tempDir) + prefs.setThemeMode(ThemeMode.BLACK) + assertThat(prefs.themeMode.first()).isEqualTo(ThemeMode.BLACK) + } + @Test fun `dynamic colour round-trips`(@TempDir tempDir: Path) = runTest { - val prefs = SettingsPrefs(newDataStore(tempDir)) + val prefs = testSettings(tempDir) prefs.setDynamicColor(false) assertThat(prefs.dynamicColor.first()).isFalse() } @Test fun `week start round-trips any day`(@TempDir tempDir: Path) = runTest { - val prefs = SettingsPrefs(newDataStore(tempDir)) + val prefs = testSettings(tempDir) prefs.setWeekStart(WeekStartPref.Day(DayOfWeek.SATURDAY)) assertThat(prefs.weekStart.first()).isEqualTo(WeekStartPref.Day(DayOfWeek.SATURDAY)) } @Test fun `legacy MONDAY week-start value migrates to Day`(@TempDir tempDir: Path) = runTest { - val store = newDataStore(tempDir) + val store = testDataStore(tempDir, "test_settings") val prefs = SettingsPrefs(store) store.updateData { p -> val m = p.toMutablePreferences() - m[SettingsPrefs.WEEK_START_KEY] = "MONDAY" + m[stringPreferencesKey("week_start")] = "MONDAY" m } assertThat(prefs.weekStart.first()).isEqualTo(WeekStartPref.Day(DayOfWeek.MONDAY)) @@ -75,11 +79,11 @@ class SettingsPrefsTest { @Test fun `garbage week-start value falls back to Auto`(@TempDir tempDir: Path) = runTest { - val store = newDataStore(tempDir) + val store = testDataStore(tempDir, "test_settings") val prefs = SettingsPrefs(store) store.updateData { p -> val m = p.toMutablePreferences() - m[SettingsPrefs.WEEK_START_KEY] = "FUNDAY" + m[stringPreferencesKey("week_start")] = "FUNDAY" m } assertThat(prefs.weekStart.first()).isEqualTo(WeekStartPref.Auto) @@ -87,7 +91,7 @@ class SettingsPrefsTest { @Test fun `time format defaults to auto and round-trips`(@TempDir tempDir: Path) = runTest { - val prefs = SettingsPrefs(newDataStore(tempDir)) + val prefs = testSettings(tempDir) assertThat(prefs.timeFormat.first()).isEqualTo(TimeFormatPref.AUTO) prefs.setTimeFormat(TimeFormatPref.TWELVE_HOUR) assertThat(prefs.timeFormat.first()).isEqualTo(TimeFormatPref.TWELVE_HOUR) @@ -95,7 +99,7 @@ class SettingsPrefsTest { @Test fun `hour lines default off and round-trips`(@TempDir tempDir: Path) = runTest { - val prefs = SettingsPrefs(newDataStore(tempDir)) + val prefs = testSettings(tempDir) assertThat(prefs.showHourGrid.first()).isFalse() prefs.setShowHourGrid(true) assertThat(prefs.showHourGrid.first()).isTrue() @@ -105,7 +109,7 @@ class SettingsPrefsTest { fun `timeline scale defaults to regular and round-trips`(@TempDir tempDir: Path) = runTest { // Regular is the historical 56dp scale — an existing install that never // opened the setting must keep the timeline it had (#56). - val prefs = SettingsPrefs(newDataStore(tempDir)) + val prefs = testSettings(tempDir) assertThat(prefs.timelineScale.first()).isEqualTo(TimelineScale.Regular) prefs.setTimelineScale(TimelineScale.FitDay) assertThat(prefs.timelineScale.first()).isEqualTo(TimelineScale.FitDay) @@ -115,7 +119,7 @@ class SettingsPrefsTest { fun `a pinched timeline height round-trips`(@TempDir tempDir: Path) = runTest { // The pinch settles on a height between the presets, so the preference // has to store the number, not just a named step (#56). - val prefs = SettingsPrefs(newDataStore(tempDir)) + val prefs = testSettings(tempDir) val pinched = TimelineScale.custom(63.5f.dp) prefs.setTimelineScale(pinched) assertThat(prefs.timelineScale.first()).isEqualTo(pinched) @@ -128,7 +132,7 @@ class SettingsPrefsTest { @Test fun `visible hours default off and round-trip`(@TempDir tempDir: Path) = runTest { - val prefs = SettingsPrefs(newDataStore(tempDir)) + val prefs = testSettings(tempDir) assertThat(prefs.timelineHours.first()).isEqualTo(TimelineHours(enabled = false, 7, 22)) prefs.setTimelineHours(TimelineHours(enabled = true, 6, 20)) assertThat(prefs.timelineHours.first()).isEqualTo(TimelineHours(enabled = true, 6, 20)) @@ -139,14 +143,14 @@ class SettingsPrefsTest { @Test fun `visible hours are stored valid`(@TempDir tempDir: Path) = runTest { - val prefs = SettingsPrefs(newDataStore(tempDir)) + val prefs = testSettings(tempDir) prefs.setTimelineHours(TimelineHours(enabled = true, 23, 22)) assertThat(prefs.timelineHours.first()).isEqualTo(TimelineHours(enabled = true, 20, 22)) } @Test fun `week numbers default off and round-trips`(@TempDir tempDir: Path) = runTest { - val prefs = SettingsPrefs(newDataStore(tempDir)) + val prefs = testSettings(tempDir) assertThat(prefs.showWeekNumbers.first()).isFalse() prefs.setShowWeekNumbers(true) assertThat(prefs.showWeekNumbers.first()).isTrue() @@ -154,7 +158,7 @@ class SettingsPrefsTest { @Test fun `autofocus event title defaults on and round-trips`(@TempDir tempDir: Path) = runTest { - val prefs = SettingsPrefs(newDataStore(tempDir)) + val prefs = testSettings(tempDir) assertThat(prefs.autofocusEventTitle.first()).isTrue() prefs.setAutofocusEventTitle(false) assertThat(prefs.autofocusEventTitle.first()).isFalse() @@ -162,7 +166,7 @@ class SettingsPrefsTest { @Test fun `agenda ranges default to month and round-trip independently`(@TempDir tempDir: Path) = runTest { - val prefs = SettingsPrefs(newDataStore(tempDir)) + val prefs = testSettings(tempDir) assertThat(prefs.agendaScreenRange.first()).isEqualTo(AgendaRange.Month) assertThat(prefs.agendaWidgetRange.first()).isEqualTo(AgendaRange.Month) @@ -174,7 +178,7 @@ class SettingsPrefsTest { @Test fun `month view style defaults to paged and round-trips`(@TempDir tempDir: Path) = runTest { - val prefs = SettingsPrefs(newDataStore(tempDir)) + val prefs = testSettings(tempDir) assertThat(prefs.monthViewStyle.first()).isEqualTo(MonthViewStyle.Paged) prefs.setMonthViewStyle(MonthViewStyle.Split) @@ -186,11 +190,11 @@ class SettingsPrefsTest { @Test fun `garbage stored month view style falls back to paged`(@TempDir tempDir: Path) = runTest { - val store = newDataStore(tempDir) + val store = testDataStore(tempDir, "test_settings") val prefs = SettingsPrefs(store) store.updateData { p -> val m = p.toMutablePreferences() - m[SettingsPrefs.MONTH_VIEW_STYLE_KEY] = "Carousel" + m[stringPreferencesKey("month_view_style")] = "Carousel" m } assertThat(prefs.monthViewStyle.first()).isEqualTo(MonthViewStyle.Paged) @@ -198,11 +202,11 @@ class SettingsPrefsTest { @Test fun `garbage stored enum falls back to default`(@TempDir tempDir: Path) = runTest { - val store = newDataStore(tempDir) + val store = testDataStore(tempDir, "test_settings") val prefs = SettingsPrefs(store) store.updateData { p -> val m = p.toMutablePreferences() - m[SettingsPrefs.THEME_MODE_KEY] = "PLAID" + m[stringPreferencesKey("theme_mode")] = "PLAID" m } assertThat(prefs.themeMode.first()).isEqualTo(ThemeMode.SYSTEM) @@ -210,7 +214,7 @@ class SettingsPrefsTest { @Test fun `form fields default to location and description`(@TempDir tempDir: Path) = runTest { - val prefs = SettingsPrefs(newDataStore(tempDir)) + val prefs = testSettings(tempDir) assertThat(prefs.defaultFormFields.first()).containsExactly( EventFormField.Location, EventFormField.Description, @@ -219,7 +223,7 @@ class SettingsPrefsTest { @Test fun `form field toggle round-trips`(@TempDir tempDir: Path) = runTest { - val prefs = SettingsPrefs(newDataStore(tempDir)) + val prefs = testSettings(tempDir) prefs.setFormFieldDefault(EventFormField.Reminders, enabled = true) prefs.setFormFieldDefault(EventFormField.Location, enabled = false) assertThat(prefs.defaultFormFields.first()).containsExactly( @@ -230,14 +234,14 @@ class SettingsPrefsTest { @Test fun `disabling every form field persists as none, not factory default`(@TempDir tempDir: Path) = runTest { - val prefs = SettingsPrefs(newDataStore(tempDir)) + val prefs = testSettings(tempDir) EventFormField.entries.forEach { prefs.setFormFieldDefault(it, enabled = false) } assertThat(prefs.defaultFormFields.first()).isEmpty() } @Test fun `quick-switch defaults to every view enabled in default order`(@TempDir tempDir: Path) = runTest { - val prefs = SettingsPrefs(newDataStore(tempDir)) + val prefs = testSettings(tempDir) val config = prefs.quickSwitchConfig.first() assertThat(config.order).containsExactlyElementsIn(IMPLEMENTED_VIEWS).inOrder() assertThat(config.enabled).containsExactlyElementsIn(IMPLEMENTED_VIEWS) @@ -246,12 +250,12 @@ class SettingsPrefsTest { @Test fun `quick-switch config round-trips order and disabled views`(@TempDir tempDir: Path) = runTest { - val prefs = SettingsPrefs(newDataStore(tempDir)) + val prefs = testSettings(tempDir) val config = QuickSwitchConfig( order = listOf(CalendarView.Agenda, CalendarView.Month, CalendarView.Week, CalendarView.Day), enabled = setOf(CalendarView.Agenda, CalendarView.Month), ) - prefs.setQuickSwitchConfig(config) + prefs.updateQuickSwitch { config } val loaded = prefs.quickSwitchConfig.first() assertThat(loaded.order).containsExactly( CalendarView.Agenda, CalendarView.Month, CalendarView.Week, @@ -263,12 +267,12 @@ class SettingsPrefsTest { @Test fun `quick-switch parse appends missing views enabled and drops unknowns`(@TempDir tempDir: Path) = runTest { - val store = newDataStore(tempDir) + val store = testDataStore(tempDir, "test_settings") val prefs = SettingsPrefs(store) // Only Day (disabled) and Week stored, plus a bogus name; Month & Agenda absent. store.updateData { p -> val m = p.toMutablePreferences() - m[SettingsPrefs.QUICK_SWITCH_VIEWS_KEY] = "!Day,Week,Hologram" + m[stringPreferencesKey("quick_switch_views")] = "!Day,Week,Hologram" m } val config = prefs.quickSwitchConfig.first() @@ -285,7 +289,7 @@ class SettingsPrefsTest { @Test fun `updateQuickSwitch transforms the stored value, so intents compose`(@TempDir tempDir: Path) = runTest { - val prefs = SettingsPrefs(newDataStore(tempDir)) + val prefs = testSettings(tempDir) // A toggle then a reorder, each expressed against the *stored* config — // the reorder must not resurrect the just-disabled view (the stale-UI- // snapshot race this API exists to prevent). @@ -304,7 +308,7 @@ class SettingsPrefsTest { @Test fun `drawer order defaults to the implemented order and round-trips`(@TempDir tempDir: Path) = runTest { - val prefs = SettingsPrefs(newDataStore(tempDir)) + val prefs = testSettings(tempDir) assertThat(prefs.drawerViewOrder.first()).containsExactlyElementsIn(IMPLEMENTED_VIEWS).inOrder() prefs.setDrawerViewOrder( listOf(CalendarView.Agenda, CalendarView.Day, CalendarView.Week, CalendarView.Month), @@ -317,11 +321,11 @@ class SettingsPrefsTest { @Test fun `drawer order parse appends missing views and drops unknowns`(@TempDir tempDir: Path) = runTest { - val store = newDataStore(tempDir) + val store = testDataStore(tempDir, "test_settings") val prefs = SettingsPrefs(store) store.updateData { p -> val m = p.toMutablePreferences() - m[SettingsPrefs.DRAWER_VIEW_ORDER_KEY] = "Agenda,Nope,Week" + m[stringPreferencesKey("drawer_view_order")] = "Agenda,Nope,Week" m } assertThat(prefs.drawerViewOrder.first()).containsExactly( @@ -332,11 +336,11 @@ class SettingsPrefsTest { @Test fun `unknown stored form-field names are dropped`(@TempDir tempDir: Path) = runTest { - val store = newDataStore(tempDir) + val store = testDataStore(tempDir, "test_settings") val prefs = SettingsPrefs(store) store.updateData { p -> val m = p.toMutablePreferences() - m[SettingsPrefs.FORM_FIELDS_KEY] = "Location,Hologram" + m[stringPreferencesKey("event_form_default_fields")] = "Location,Hologram" m } assertThat(prefs.defaultFormFields.first()).containsExactly(EventFormField.Location) @@ -344,60 +348,71 @@ class SettingsPrefsTest { @Test fun `reminders default to enabled, onboarding to not done`(@TempDir tempDir: Path) = runTest { - val prefs = SettingsPrefs(newDataStore(tempDir)) + val prefs = testSettings(tempDir) assertThat(prefs.remindersEnabled.first()).isTrue() - assertThat(prefs.reminderOnboardingDone.first()).isFalse() + assertThat(prefs.onboardingProgress.first().answered).isEmpty() } @Test fun `reminders toggle round-trips`(@TempDir tempDir: Path) = runTest { - val prefs = SettingsPrefs(newDataStore(tempDir)) + val prefs = testSettings(tempDir) prefs.setRemindersEnabled(false) assertThat(prefs.remindersEnabled.first()).isFalse() } @Test fun `reminder onboarding completes one-way`(@TempDir tempDir: Path) = runTest { - val prefs = SettingsPrefs(newDataStore(tempDir)) - prefs.setReminderOnboardingDone() - assertThat(prefs.reminderOnboardingDone.first()).isTrue() + val prefs = testSettings(tempDir) + prefs.setOnboardingDone(OnboardingStep.Reminders) + assertThat(prefs.onboardingProgress.first().answered).containsExactly(OnboardingStep.Reminders) + } + + @Test + fun `a step's answer can be cleared again`(@TempDir tempDir: Path) = runTest { + val prefs = testSettings(tempDir) + prefs.setOnboardingDone(OnboardingStep.Backup) + prefs.setOnboardingDone(OnboardingStep.View) + + prefs.setOnboardingDone(OnboardingStep.Backup, done = false) + + assertThat(prefs.onboardingProgress.first().answered).containsExactly(OnboardingStep.View) } @Test fun `the wizard arms on a first run`(@TempDir tempDir: Path) = runTest { - val prefs = SettingsPrefs(newDataStore(tempDir)) + val prefs = testSettings(tempDir) prefs.armOnboardingWizard() - assertThat(prefs.onboardingWizardArmed.first()).isTrue() + assertThat(prefs.onboardingProgress.first().wizardArmed).isTrue() } @Test fun `the wizard does not arm once the reminder step is answered`(@TempDir tempDir: Path) = runTest { // An existing install re-granting the permission is not re-onboarded. - val prefs = SettingsPrefs(newDataStore(tempDir)) - prefs.setReminderOnboardingDone() + val prefs = testSettings(tempDir) + prefs.setOnboardingDone(OnboardingStep.Reminders) prefs.armOnboardingWizard() - assertThat(prefs.onboardingWizardArmed.first()).isFalse() + assertThat(prefs.onboardingProgress.first().wizardArmed).isFalse() } @Test fun `closing the wizard disarms it`(@TempDir tempDir: Path) = runTest { - val prefs = SettingsPrefs(newDataStore(tempDir)) + val prefs = testSettings(tempDir) prefs.armOnboardingWizard() prefs.finishOnboardingWizard() - assertThat(prefs.onboardingDoneShown.first()).isTrue() - assertThat(prefs.onboardingWizardArmed.first()).isFalse() + assertThat(prefs.onboardingProgress.first().answered).containsExactly(OnboardingStep.Done) + assertThat(prefs.onboardingProgress.first().wizardArmed).isFalse() } @Test fun `default reminder is empty until set`(@TempDir tempDir: Path) = runTest { - val prefs = SettingsPrefs(newDataStore(tempDir)) + val prefs = testSettings(tempDir) assertThat(prefs.defaultReminderMinutes.first()).isEmpty() } @Test fun `default reminder round-trips none, single, and multiple lead times`(@TempDir tempDir: Path) = runTest { - val prefs = SettingsPrefs(newDataStore(tempDir)) + val prefs = testSettings(tempDir) prefs.setDefaultReminderMinutes(listOf(30)) assertThat(prefs.defaultReminderMinutes.first()).containsExactly(30) // Several lead times persist, normalised to distinct ascending order. @@ -409,12 +424,12 @@ class SettingsPrefsTest { @Test fun `legacy single-value default reminder parses as a one-element list`(@TempDir tempDir: Path) = runTest { - val store = newDataStore(tempDir) + val store = testDataStore(tempDir, "test_settings") val prefs = SettingsPrefs(store) // The pre-multi-reminder format stored a bare integer string. store.updateData { p -> val m = p.toMutablePreferences() - m[SettingsPrefs.DEFAULT_REMINDER_KEY] = "30" + m[stringPreferencesKey("default_reminder_minutes")] = "30" m } assertThat(prefs.defaultReminderMinutes.first()).containsExactly(30) @@ -422,11 +437,11 @@ class SettingsPrefsTest { @Test fun `garbage stored default reminder reads as empty`(@TempDir tempDir: Path) = runTest { - val store = newDataStore(tempDir) + val store = testDataStore(tempDir, "test_settings") val prefs = SettingsPrefs(store) store.updateData { p -> val m = p.toMutablePreferences() - m[SettingsPrefs.DEFAULT_REMINDER_KEY] = "soon" + m[stringPreferencesKey("default_reminder_minutes")] = "soon" m } assertThat(prefs.defaultReminderMinutes.first()).isEmpty() @@ -434,7 +449,7 @@ class SettingsPrefsTest { @Test fun `per-calendar override round-trips minutes, none, and inherit`(@TempDir tempDir: Path) = runTest { - val prefs = SettingsPrefs(newDataStore(tempDir)) + val prefs = testSettings(tempDir) assertThat(prefs.perCalendarReminderOverride.first()).isEmpty() prefs.setCalendarReminderOverride(7L, ReminderOverride.Minutes(listOf(15, 10_080))) @@ -455,7 +470,7 @@ class SettingsPrefsTest { fun `garbage per-calendar override values drop the entry, the none sentinel stays explicit`( @TempDir tempDir: Path, ) = runTest { - val store = newDataStore(tempDir) + val store = testDataStore(tempDir, "test_settings") val prefs = SettingsPrefs(store) // Only "none" deliberately means an explicit no-reminder override; a // value with no valid minutes is garbage and must drop its entry so the @@ -463,7 +478,7 @@ class SettingsPrefsTest { // reminders. Partially-valid values keep their salvageable minutes. store.updateData { p -> val m = p.toMutablePreferences() - m[SettingsPrefs.CALENDAR_REMINDER_OVERRIDE_KEY] = "5=none;7=abc;8=;9=30,abc;11=15" + m[stringPreferencesKey("per_calendar_reminder_override")] = "5=none;7=abc;8=;9=30,abc;11=15" m } assertThat(prefs.perCalendarReminderOverride.first()).containsExactly( @@ -473,7 +488,7 @@ class SettingsPrefsTest { @Test fun `all-day default round-trips, including none`(@TempDir tempDir: Path) = runTest { - val prefs = SettingsPrefs(newDataStore(tempDir)) + val prefs = testSettings(tempDir) assertThat(prefs.defaultAllDayReminderMinutes.first()).isEmpty() prefs.setDefaultAllDayReminderMinutes(listOf(1_440)) assertThat(prefs.defaultAllDayReminderMinutes.first()).containsExactly(1_440) @@ -483,7 +498,7 @@ class SettingsPrefsTest { @Test fun `per-calendar all-day override round-trips independently of the timed one`(@TempDir tempDir: Path) = runTest { - val prefs = SettingsPrefs(newDataStore(tempDir)) + val prefs = testSettings(tempDir) prefs.setCalendarReminderOverride(7L, ReminderOverride.Minutes(listOf(15))) prefs.setCalendarAllDayReminderOverride(7L, ReminderOverride.Minutes(listOf(1_440))) assertThat(prefs.perCalendarReminderOverride.first()).containsExactly(7L, listOf(15)) @@ -520,7 +535,7 @@ class SettingsPrefsTest { @Test fun `all-day reminder time defaults to 9am`(@TempDir tempDir: Path) = runTest { - val prefs = SettingsPrefs(newDataStore(tempDir)) + val prefs = testSettings(tempDir) assertThat(prefs.allDayReminderTimeMinutes.first()).isEqualTo(540) } @@ -528,7 +543,7 @@ class SettingsPrefsTest { fun `all-day reminder time round-trips and clamps to a valid minute-of-day`( @TempDir tempDir: Path, ) = runTest { - val prefs = SettingsPrefs(newDataStore(tempDir)) + val prefs = testSettings(tempDir) prefs.setAllDayReminderTimeMinutes(8 * 60 + 30) assertThat(prefs.allDayReminderTimeMinutes.first()).isEqualTo(510) prefs.setAllDayReminderTimeMinutes(5_000) @@ -539,7 +554,7 @@ class SettingsPrefsTest { @Test fun `snooze duration defaults to 10 minutes`(@TempDir tempDir: Path) = runTest { - val prefs = SettingsPrefs(newDataStore(tempDir)) + val prefs = testSettings(tempDir) assertThat(prefs.snoozeMinutes.first()).isEqualTo(10) } @@ -547,7 +562,7 @@ class SettingsPrefsTest { fun `snooze duration round-trips and clamps to at least one minute`( @TempDir tempDir: Path, ) = runTest { - val prefs = SettingsPrefs(newDataStore(tempDir)) + val prefs = testSettings(tempDir) prefs.setSnoozeMinutes(30) assertThat(prefs.snoozeMinutes.first()).isEqualTo(30) prefs.setSnoozeMinutes(0) @@ -558,7 +573,7 @@ class SettingsPrefsTest { fun `event duration defaults to an hour and clamps to a sane span`( @TempDir tempDir: Path, ) = runTest { - val prefs = SettingsPrefs(newDataStore(tempDir)) + val prefs = testSettings(tempDir) assertThat(prefs.defaultEventDurationMinutes.first()).isEqualTo(60) prefs.setDefaultEventDurationMinutes(480) assertThat(prefs.defaultEventDurationMinutes.first()).isEqualTo(480) @@ -572,7 +587,7 @@ class SettingsPrefsTest { fun `per-calendar duration round-trips and clears back to inherit`( @TempDir tempDir: Path, ) = runTest { - val prefs = SettingsPrefs(newDataStore(tempDir)) + val prefs = testSettings(tempDir) assertThat(prefs.perCalendarEventDuration.first()).isEmpty() prefs.setCalendarEventDuration(7L, 480) prefs.setCalendarEventDuration(9L, 30) @@ -585,12 +600,12 @@ class SettingsPrefsTest { fun `garbage per-calendar duration entries are dropped, the rest survive`( @TempDir tempDir: Path, ) = runTest { - val store = newDataStore(tempDir) + val store = testDataStore(tempDir, "test_settings") val prefs = SettingsPrefs(store) store.updateData { p -> val m = p.toMutablePreferences() // A bad id, a non-numeric length, one out of range, and a good entry. - m[SettingsPrefs.CALENDAR_EVENT_DURATION_KEY] = "x=60;7=soon;8=99999;9=45" + m[stringPreferencesKey("per_calendar_event_duration")] = "x=60;7=soon;8=99999;9=45" m } assertThat(prefs.perCalendarEventDuration.first()).containsExactly(9L, 45) @@ -606,7 +621,7 @@ class SettingsPrefsTest { @Test fun `custom-font stamps default to zero and bump per role independently`(@TempDir tempDir: Path) = runTest { - val prefs = SettingsPrefs(newDataStore(tempDir)) + val prefs = testSettings(tempDir) // Existing installs have no stamp key — that must read as 0. assertThat(prefs.brandFontStamp.first()).isEqualTo(0) assertThat(prefs.plainFontStamp.first()).isEqualTo(0) @@ -633,7 +648,7 @@ class SettingsPrefsTest { @Test fun `special dates feature is off with all types on by default`(@TempDir tempDir: Path) = runTest { - val prefs = SettingsPrefs(newDataStore(tempDir)) + val prefs = testSettings(tempDir) assertThat(prefs.specialDatesEnabled.first()).isFalse() assertThat(prefs.specialDatesTypes.first()).isEqualTo(SpecialDateType.entries.toSet()) assertThat(prefs.specialDatesCalendars.first()).isEmpty() @@ -643,7 +658,7 @@ class SettingsPrefsTest { @Test fun `special date type toggles round-trip`(@TempDir tempDir: Path) = runTest { - val prefs = SettingsPrefs(newDataStore(tempDir)) + val prefs = testSettings(tempDir) prefs.setSpecialDateTypeEnabled(SpecialDateType.Anniversary, false) assertThat(prefs.specialDatesTypes.first()) .isEqualTo(setOf(SpecialDateType.Birthday, SpecialDateType.Custom)) @@ -651,7 +666,7 @@ class SettingsPrefsTest { @Test fun `managed calendar ids round-trip and drive managedCalendarIds`(@TempDir tempDir: Path) = runTest { - val prefs = SettingsPrefs(newDataStore(tempDir)) + val prefs = testSettings(tempDir) prefs.setSpecialDatesCalendarId(SpecialDateType.Birthday, 7L) prefs.setSpecialDatesCalendarId(SpecialDateType.Anniversary, 9L) assertThat(prefs.specialDatesCalendars.first()) @@ -665,7 +680,7 @@ class SettingsPrefsTest { @Test fun `title template round-trips per type`(@TempDir tempDir: Path) = runTest { - val prefs = SettingsPrefs(newDataStore(tempDir)) + val prefs = testSettings(tempDir) assertThat(prefs.specialDatesTitleTemplates.first()[SpecialDateType.Birthday]).isEmpty() prefs.setSpecialDatesTitleTemplate(SpecialDateType.Birthday, "{name}'s birthday") assertThat(prefs.specialDatesTitleTemplates.first()[SpecialDateType.Birthday]) @@ -674,7 +689,7 @@ class SettingsPrefsTest { @Test fun `sync status records run and stalled reason`(@TempDir tempDir: Path) = runTest { - val prefs = SettingsPrefs(newDataStore(tempDir)) + val prefs = testSettings(tempDir) assertThat(prefs.specialDatesStatus.first()) .isEqualTo(SpecialDatesStatus(lastRun = 0L, stalled = null)) diff --git a/app/src/test/java/de/jeanlucmakiola/calendula/data/time/FakeZoneSource.kt b/app/src/test/java/de/jeanlucmakiola/calendula/data/time/FakeZoneSource.kt new file mode 100644 index 00000000..efc93898 --- /dev/null +++ b/app/src/test/java/de/jeanlucmakiola/calendula/data/time/FakeZoneSource.kt @@ -0,0 +1,11 @@ +package de.jeanlucmakiola.calendula.data.time + +import kotlinx.coroutines.flow.MutableStateFlow +import kotlinx.datetime.TimeZone + +/** A device zone a test sets, by default the machine's own. */ +class FakeZoneSource(zone: TimeZone = TimeZone.currentSystemDefault()) : ZoneSource { + override val zone: MutableStateFlow = MutableStateFlow(zone) + + override fun current(): TimeZone = zone.value +} 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 b2fb0580..cd9f7d58 100644 --- a/app/src/test/java/de/jeanlucmakiola/calendula/domain/EventFormTest.kt +++ b/app/src/test/java/de/jeanlucmakiola/calendula/domain/EventFormTest.kt @@ -1,10 +1,14 @@ package de.jeanlucmakiola.calendula.domain import com.google.common.truth.Truth.assertThat +import de.jeanlucmakiola.calendula.testDetail +import de.jeanlucmakiola.calendula.testEvent import kotlinx.datetime.LocalDate import kotlinx.datetime.LocalDateTime import kotlinx.datetime.LocalTime import kotlinx.datetime.TimeZone +import kotlinx.datetime.UtcOffset +import kotlinx.datetime.toLocalDateTime import org.junit.jupiter.api.Test import kotlin.time.Instant @@ -15,29 +19,29 @@ class EventFormTest { isAllDay: Boolean = false, start: LocalDateTime = LocalDateTime(LocalDate(2026, 6, 11), LocalTime(10, 0)), end: LocalDateTime = LocalDateTime(LocalDate(2026, 6, 11), LocalTime(11, 0)), - ): EventForm = EventForm(calendarId = calendarId, isAllDay = isAllDay, start = start, end = end) + ): EventForm = EventForm(calendarId = calendarId, isAllDay = isAllDay, start = FormTime(start), end = FormTime(end)) @Test fun `valid timed form has no problems`() { - assertThat(form().problems()).isEmpty() + assertThat(form().problems(berlin)).isEmpty() } @Test fun `missing calendar is a problem`() { - assertThat(form(calendarId = null).problems()) + assertThat(form(calendarId = null).problems(berlin)) .containsExactly(EventFormProblem.NoCalendar) } @Test fun `timed end before start is a problem`() { val bad = form(end = LocalDateTime(LocalDate(2026, 6, 11), LocalTime(9, 0))) - assertThat(bad.problems()).containsExactly(EventFormProblem.EndBeforeStart) + assertThat(bad.problems(berlin)).containsExactly(EventFormProblem.EndBeforeStart) } @Test fun `zero-length timed event is allowed`() { val instant = form(end = LocalDateTime(LocalDate(2026, 6, 11), LocalTime(10, 0))) - assertThat(instant.problems()).isEmpty() + assertThat(instant.problems(berlin)).isEmpty() } @Test @@ -47,7 +51,7 @@ class EventFormTest { start = LocalDateTime(LocalDate(2026, 6, 11), LocalTime(0, 0)), end = LocalDateTime(LocalDate(2026, 6, 11), LocalTime(0, 0)), ) - assertThat(allDay.problems()).isEmpty() + assertThat(allDay.problems(berlin)).isEmpty() } @Test @@ -57,7 +61,7 @@ class EventFormTest { start = LocalDateTime(LocalDate(2026, 6, 11), LocalTime(0, 0)), end = LocalDateTime(LocalDate(2026, 6, 10), LocalTime(0, 0)), ) - assertThat(bad.problems()).containsExactly(EventFormProblem.EndBeforeStart) + assertThat(bad.problems(berlin)).containsExactly(EventFormProblem.EndBeforeStart) } @Test @@ -66,7 +70,7 @@ class EventFormTest { calendarId = null, end = LocalDateTime(LocalDate(2026, 6, 11), LocalTime(9, 0)), ) - assertThat(bad.problems()).containsExactly( + assertThat(bad.problems(berlin)).containsExactly( EventFormProblem.NoCalendar, EventFormProblem.EndBeforeStart, ) @@ -76,28 +80,28 @@ class EventFormTest { fun `recurrence until before the first day is a problem`() { // Days before the start, so it parses to an earlier date in any zone. val bad = form().copy(rrule = "FREQ=DAILY;UNTIL=20260601T120000Z") - assertThat(bad.problems()) + assertThat(bad.problems(berlin)) .containsExactly(EventFormProblem.RecurrenceEndsBeforeStart) } @Test fun `recurrence until on or after the first day is fine`() { // Date-only UNTIL parses zone-independently. - assertThat(form().copy(rrule = "FREQ=DAILY;UNTIL=20260611").problems()).isEmpty() - assertThat(form().copy(rrule = "FREQ=WEEKLY").problems()).isEmpty() + assertThat(form().copy(rrule = "FREQ=DAILY;UNTIL=20260611").problems(berlin)).isEmpty() + assertThat(form().copy(rrule = "FREQ=WEEKLY").problems(berlin)).isEmpty() } @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()).isEmpty() + assertThat(form().copy(rrule = "FREQ=MONTHLY;BYDAY=2MO;UNTIL=20200101").problems(berlin)).isEmpty() } @Test fun `weekly byday rules are validated against the start`() { val bad = form().copy(rrule = "FREQ=WEEKLY;BYDAY=MO,FR;UNTIL=20200101") - assertThat(bad.problems()) + assertThat(bad.problems(berlin)) .containsExactly(EventFormProblem.RecurrenceEndsBeforeStart) } @@ -118,20 +122,16 @@ class EventFormTest { eventColor: Int? = null, eventColorKey: String? = null, eventTimezone: String? = null, - ): EventDetail = EventDetail( - instance = EventInstance( - instanceId = 1L, - eventId = 1L, + ): EventDetail = testDetail( + instance = testEvent( calendarId = 7L, title = title, start = Instant.fromEpochMilliseconds(rowStart), end = Instant.fromEpochMilliseconds(rowEnd), isAllDay = isAllDay, - color = 0, location = location, ), description = description, - organizer = null, attendees = attendees, rrule = rrule, reminders = reminders, @@ -150,8 +150,8 @@ class EventFormTest { endMillis = 1_781_164_800_000L + 90L * 60L * 1000L, zone = berlin, ) - assertThat(prefilled.start).isEqualTo(LocalDateTime(LocalDate(2026, 6, 11), LocalTime(10, 0))) - assertThat(prefilled.end).isEqualTo(LocalDateTime(LocalDate(2026, 6, 11), LocalTime(11, 30))) + assertThat(prefilled.start.dateTime).isEqualTo(LocalDateTime(LocalDate(2026, 6, 11), LocalTime(10, 0))) + assertThat(prefilled.end.dateTime).isEqualTo(LocalDateTime(LocalDate(2026, 6, 11), LocalTime(11, 30))) assertThat(prefilled.isAllDay).isFalse() assertThat(prefilled.calendarId).isEqualTo(7L) assertThat(prefilled.title).isEqualTo("Stand-up") @@ -182,7 +182,7 @@ class EventFormTest { assertThat(prefilled.timezone).isEqualTo("America/New_York") // 08:00Z is 10:00 in Berlin but 04:00 in New York — the form shows the // event's own wall-clock, which is what a later save re-anchors to. - assertThat(prefilled.start).isEqualTo(LocalDateTime(LocalDate(2026, 6, 11), LocalTime(4, 0))) + assertThat(prefilled.start.dateTime).isEqualTo(LocalDateTime(LocalDate(2026, 6, 11), LocalTime(4, 0))) assertThat(prefilled.populatedFields()).contains(EventFormField.Timezone) } @@ -206,68 +206,27 @@ class EventFormTest { ) // A malformed sync row must not be honoured, nor fail the open. assertThat(prefilled.timezone).isNull() - assertThat(prefilled.start).isEqualTo(LocalDateTime(LocalDate(2026, 6, 11), LocalTime(10, 0))) + assertThat(prefilled.start.dateTime).isEqualTo(LocalDateTime(LocalDate(2026, 6, 11), LocalTime(10, 0))) } @Test - fun `timesIn converts a pinned event into the target zone`() { - val form = EventForm( - calendarId = 1L, - start = LocalDateTime(LocalDate(2026, 7, 17), LocalTime(8, 0)), - end = LocalDateTime(LocalDate(2026, 7, 17), LocalTime(9, 0)), - timezone = "America/New_York", - ) - val (start, end) = form.timesIn(berlin)!! - // 08:00 New York (EDT, UTC-4) is 14:00 Berlin (CEST, UTC+2). - assertThat(start).isEqualTo(LocalDateTime(LocalDate(2026, 7, 17), LocalTime(14, 0))) - assertThat(end).isEqualTo(LocalDateTime(LocalDate(2026, 7, 17), LocalTime(15, 0))) - } - - @Test - fun `timesIn crosses the date line when the offset pushes past midnight`() { - val form = EventForm( - calendarId = 1L, - start = LocalDateTime(LocalDate(2026, 7, 17), LocalTime(20, 0)), - end = LocalDateTime(LocalDate(2026, 7, 17), LocalTime(21, 0)), - timezone = "America/New_York", - ) - val (start, _) = form.timesIn(berlin)!! - // 20:00 New York is 02:00 the NEXT day in Berlin — the date has to move - // with it, not just the clock. - assertThat(start).isEqualTo(LocalDateTime(LocalDate(2026, 7, 18), LocalTime(2, 0))) - } - - @Test - fun `timesIn tracks each zone's own DST rather than a fixed offset`() { - // In January both are on standard time: 08:00 EST is 14:00 CET — the - // same six hours as July, but only because both shifted. Late March, - // when the US has sprung forward and Europe hasn't, the gap is five. - val march = EventForm( - calendarId = 1L, - start = LocalDateTime(LocalDate(2026, 3, 20), LocalTime(8, 0)), - end = LocalDateTime(LocalDate(2026, 3, 20), LocalTime(9, 0)), - timezone = "America/New_York", - ) - assertThat(march.timesIn(berlin)!!.first) - .isEqualTo(LocalDateTime(LocalDate(2026, 3, 20), LocalTime(13, 0))) - } - - @Test - fun `timesIn returns null when there is nothing to disambiguate`() { + fun `isPinnedAwayFrom is false when there is nothing to disambiguate`() { val base = EventForm( calendarId = 1L, - start = LocalDateTime(LocalDate(2026, 7, 17), LocalTime(8, 0)), - end = LocalDateTime(LocalDate(2026, 7, 17), LocalTime(9, 0)), + start = FormTime(LocalDateTime(LocalDate(2026, 7, 17), LocalTime(8, 0))), + end = FormTime(LocalDateTime(LocalDate(2026, 7, 17), LocalTime(9, 0))), ) // Unpinned: the form's times already are the local times. - assertThat(base.timesIn(berlin)).isNull() + assertThat(base.isPinnedAwayFrom(berlin)).isFalse() // Pinned to the target itself: same thing. - assertThat(base.copy(timezone = "Europe/Berlin").timesIn(berlin)).isNull() + assertThat(base.copy(timezone = "Europe/Berlin").isPinnedAwayFrom(berlin)).isFalse() // All-day: date-anchored, so there's no zone conversion to show. - assertThat(base.copy(isAllDay = true, timezone = "America/New_York").timesIn(berlin)) - .isNull() + assertThat(base.copy(isAllDay = true, timezone = "America/New_York").isPinnedAwayFrom(berlin)) + .isFalse() // Unparseable: can't convert, mustn't throw. - assertThat(base.copy(timezone = "Mars/Olympus_Mons").timesIn(berlin)).isNull() + assertThat(base.copy(timezone = "Mars/Olympus_Mons").isPinnedAwayFrom(berlin)).isFalse() + // Pinned elsewhere: worth spelling out. + assertThat(base.copy(timezone = "America/New_York").isPinnedAwayFrom(berlin)).isTrue() } @Test @@ -425,4 +384,190 @@ class EventFormTest { assertThat(prefilled.color).isNull() assertThat(prefilled.populatedFields()).doesNotContain(EventFormField.Color) } + + @Test + fun `toEditForm keeps which repeated fall-back hour each end is in`() { + val start = Instant.parse("2026-10-25T00:00:00Z") + val end = Instant.parse("2026-10-25T01:00:00Z") + val prefilled = detail().toEditForm(start.toEpochMilliseconds(), end.toEpochMilliseconds(), berlin) + assertThat(prefilled.start.dateTime).isEqualTo(prefilled.end.dateTime) + assertThat(prefilled.startInstant(berlin)).isEqualTo(start) + assertThat(prefilled.endInstant(berlin)).isEqualTo(end) + } + + @Test + fun `a span ending in the repeated fall-back hour is valid`() { + // 02:45 CEST to 02:15 CET: half an hour, though the clock reads backwards. + val form = form().withTimes( + Instant.parse("2026-10-25T00:45:00Z"), + Instant.parse("2026-10-25T01:15:00Z"), + berlin, + ) + assertThat(form.end.dateTime).isLessThan(form.start.dateTime) + assertThat(form.problems(berlin)).isEmpty() + // Read as the same pass at both ends, it really does end first. + assertThat(form.copy(start = FormTime(form.start.dateTime), end = FormTime(form.end.dateTime)).problems(berlin)) + .containsExactly(EventFormProblem.EndBeforeStart) + } + + @Test + fun `an end picked in the repeated hour moves the way the hand did`() { + // 02:45 CEST to 02:15 CET. + val form = form().withTimes( + Instant.parse("2026-10-25T00:45:00Z"), + Instant.parse("2026-10-25T01:15:00Z"), + berlin, + ) + // Picking the end it already has keeps its pass. + assertThat(form.withEnd(form.end.dateTime, berlin)).isEqualTo(form) + // Later on the clock: later in time, still on the second pass. + assertThat(form.withEnd(LocalDateTime(LocalDate(2026, 10, 25), LocalTime(2, 50)), berlin).endInstant(berlin)) + .isEqualTo(Instant.parse("2026-10-25T01:50:00Z")) + // Earlier on the clock: earlier in time, not an hour earlier. + assertThat(form.withEnd(LocalDateTime(LocalDate(2026, 10, 25), LocalTime(2, 5)), berlin).endInstant(berlin)) + .isEqualTo(Instant.parse("2026-10-25T01:05:00Z")) + } + + @Test + fun `an end picked in the repeated hour stays after a second-pass start`() { + // 02:10 CET to 04:00, its end set to 02:40: only the second pass is after the start. + val form = form().withTimes( + Instant.parse("2026-10-25T01:10:00Z"), + Instant.parse("2026-10-25T03:00:00Z"), + berlin, + ) + val picked = form.withEnd(LocalDateTime(LocalDate(2026, 10, 25), LocalTime(2, 40)), berlin) + assertThat(picked.endInstant(berlin)).isEqualTo(Instant.parse("2026-10-25T01:40:00Z")) + assertThat(picked.problems(berlin)).isEmpty() + } + + @Test + fun `a repeated-hour end changed and changed back is the end it was`() { + // 01:00 CEST to 02:30 CEST, its end set to 03:00 and back. + val original = form().withTimes( + Instant.parse("2026-10-24T23:00:00Z"), + Instant.parse("2026-10-25T00:30:00Z"), + berlin, + ) + val repeated = LocalDateTime(LocalDate(2026, 10, 25), LocalTime(2, 30)) + val away = original.withEnd(LocalDateTime(LocalDate(2026, 10, 25), LocalTime(3, 0)), berlin) + assertThat(away.withEnd(repeated, berlin, original = original.end)).isEqualTo(original) + // Without the opened end to go by, coming back from 03:00 reads as the later pass. + assertThat(away.withEnd(repeated, berlin).endInstant(berlin)) + .isEqualTo(Instant.parse("2026-10-25T01:30:00Z")) + } + + @Test + fun `a start picked in the repeated hour keeps the length`() { + // 02:30 CET to 03:30, its start set back to 02:10. + val form = form().withTimes( + Instant.parse("2026-10-25T01:30:00Z"), + Instant.parse("2026-10-25T02:30:00Z"), + berlin, + ) + val picked = form.withStart(LocalDateTime(LocalDate(2026, 10, 25), LocalTime(2, 10)), berlin) + assertThat(picked.startInstant(berlin)).isEqualTo(Instant.parse("2026-10-25T01:10:00Z")) + assertThat(picked.endInstant(berlin)).isEqualTo(Instant.parse("2026-10-25T02:10:00Z")) + } + + @Test + fun `a pinned event's times land in the device zone`() { + val form = EventForm( + calendarId = 1L, + start = FormTime(LocalDateTime(LocalDate(2026, 7, 17), LocalTime(8, 0))), + end = FormTime(LocalDateTime(LocalDate(2026, 7, 17), LocalTime(9, 0))), + timezone = "America/New_York", + ) + val zone = form.resolvedZone(berlin) + // 08:00 New York (EDT, UTC-4) is 14:00 Berlin (CEST, UTC+2). + assertThat(form.startInstant(zone).toLocalDateTime(berlin)) + .isEqualTo(LocalDateTime(LocalDate(2026, 7, 17), LocalTime(14, 0))) + assertThat(form.endInstant(zone).toLocalDateTime(berlin)) + .isEqualTo(LocalDateTime(LocalDate(2026, 7, 17), LocalTime(15, 0))) + } + + @Test + fun `a pinned event's local time crosses the date line with the offset`() { + val form = EventForm( + calendarId = 1L, + start = FormTime(LocalDateTime(LocalDate(2026, 7, 17), LocalTime(20, 0))), + end = FormTime(LocalDateTime(LocalDate(2026, 7, 17), LocalTime(21, 0))), + timezone = "America/New_York", + ) + // 20:00 New York is 02:00 the NEXT day in Berlin. + assertThat(form.startInstant(form.resolvedZone(berlin)).toLocalDateTime(berlin)) + .isEqualTo(LocalDateTime(LocalDate(2026, 7, 18), LocalTime(2, 0))) + } + + @Test + fun `a pinned event's local time tracks each zone's own DST`() { + // Late March the US has sprung forward and Europe hasn't: five hours, not six. + val form = EventForm( + calendarId = 1L, + start = FormTime(LocalDateTime(LocalDate(2026, 3, 20), LocalTime(8, 0))), + end = FormTime(LocalDateTime(LocalDate(2026, 3, 20), LocalTime(9, 0))), + timezone = "America/New_York", + ) + assertThat(form.startInstant(form.resolvedZone(berlin)).toLocalDateTime(berlin)) + .isEqualTo(LocalDateTime(LocalDate(2026, 3, 20), LocalTime(13, 0))) + } + + @Test + fun `offsets are kept only for a repeated hour`() { + val summer = form().withTimes( + Instant.parse("2026-06-11T08:00:00Z"), + Instant.parse("2026-06-11T09:00:00Z"), + berlin, + ) + assertThat(summer.start.offset).isNull() + assertThat(summer.end.offset).isNull() + val repeated = form().withTimes( + Instant.parse("2026-10-25T00:45:00Z"), + Instant.parse("2026-10-25T01:15:00Z"), + berlin, + ) + assertThat(repeated.start.offset).isEqualTo(UtcOffset(hours = 2)) + assertThat(repeated.end.offset).isEqualTo(UtcOffset(hours = 1)) + } + + @Test + fun `an end changed and changed back is the form it was`() { + val original = detail().toEditForm( + Instant.parse("2026-06-11T08:00:00Z").toEpochMilliseconds(), + Instant.parse("2026-06-11T09:00:00Z").toEpochMilliseconds(), + berlin, + ) + val back = original + .withEnd(LocalDateTime(LocalDate(2026, 6, 11), LocalTime(12, 0)), berlin) + .withEnd(original.end.dateTime, berlin) + assertThat(back).isEqualTo(original) + } + + @Test + fun `a new zone drops the kept pass, the same zone keeps it`() { + val repeated = form().withTimes( + Instant.parse("2026-10-25T01:30:00Z"), + Instant.parse("2026-10-25T02:00:00Z"), + berlin, + ) + assertThat(repeated.withTimezone("Europe/Berlin", berlin)).isEqualTo(repeated.copy(timezone = "Europe/Berlin")) + val moved = repeated.withTimezone("Africa/Lagos", berlin) + assertThat(moved.start.offset).isNull() + assertThat(moved.end.offset).isNull() + // Back on Berlin, a picked 02:30 takes the earlier pass, as any picked time does. + assertThat(moved.withTimezone(null, berlin).startInstant(berlin)) + .isEqualTo(Instant.parse("2026-10-25T00:30:00Z")) + } + + @Test + fun `an end picked in the spring-forward gap moves on as a start does`() { + val form = form( + start = LocalDateTime(LocalDate(2026, 3, 29), LocalTime(1, 0)), + end = LocalDateTime(LocalDate(2026, 3, 29), LocalTime(1, 30)), + ) + val picked = form.withEnd(LocalDateTime(LocalDate(2026, 3, 29), LocalTime(2, 30)), berlin) + assertThat(picked.end.dateTime).isEqualTo(LocalDateTime(LocalDate(2026, 3, 29), LocalTime(3, 30))) + val started = form.withStart(LocalDateTime(LocalDate(2026, 3, 29), LocalTime(2, 30)), berlin) + assertThat(started.start.dateTime).isEqualTo(LocalDateTime(LocalDate(2026, 3, 29), LocalTime(3, 30))) + } } diff --git a/app/src/test/java/de/jeanlucmakiola/calendula/domain/EventInstanceSpanTest.kt b/app/src/test/java/de/jeanlucmakiola/calendula/domain/EventInstanceSpanTest.kt index 6591a756..a3b4ae25 100644 --- a/app/src/test/java/de/jeanlucmakiola/calendula/domain/EventInstanceSpanTest.kt +++ b/app/src/test/java/de/jeanlucmakiola/calendula/domain/EventInstanceSpanTest.kt @@ -1,6 +1,7 @@ package de.jeanlucmakiola.calendula.domain import com.google.common.truth.Truth.assertThat +import de.jeanlucmakiola.calendula.testEvent import kotlinx.datetime.LocalDate import kotlinx.datetime.LocalDateTime import kotlinx.datetime.TimeZone @@ -29,17 +30,8 @@ class EventInstanceSpanTest { private fun utc(y: Int, mo: Int, d: Int, h: Int = 0): Instant = LocalDateTime(y, mo, d, h, 0).toInstant(TimeZone.UTC) - private fun instance(start: Instant, end: Instant, isAllDay: Boolean) = EventInstance( - instanceId = 1L, - eventId = 1L, - calendarId = 1L, - title = "Event", - start = start, - end = end, - isAllDay = isAllDay, - color = 0xFF000000.toInt(), - location = null, - ) + private fun instance(start: Instant, end: Instant, isAllDay: Boolean) = + testEvent(start = start, end = end, isAllDay = isAllDay, color = 0xFF000000.toInt()) @Test fun `all-day event keeps its date west of UTC`() { diff --git a/app/src/test/java/de/jeanlucmakiola/calendula/domain/EventSearchTest.kt b/app/src/test/java/de/jeanlucmakiola/calendula/domain/EventSearchTest.kt index 0ebae1fc..818d3efd 100644 --- a/app/src/test/java/de/jeanlucmakiola/calendula/domain/EventSearchTest.kt +++ b/app/src/test/java/de/jeanlucmakiola/calendula/domain/EventSearchTest.kt @@ -1,6 +1,7 @@ package de.jeanlucmakiola.calendula.domain import com.google.common.truth.Truth.assertThat +import de.jeanlucmakiola.calendula.testEvent import kotlinx.datetime.TimeZone import org.junit.jupiter.api.Test import kotlin.time.Instant @@ -27,15 +28,11 @@ class EventSearchTest { ): SearchCandidate { val begin = Instant.parse(start) return SearchCandidate( - event = EventInstance( - instanceId = nextId, - eventId = nextId++, - calendarId = 1L, + event = testEvent( + id = nextId++, title = title, start = begin, end = begin.plus(kotlin.time.Duration.parse("1h")), - isAllDay = false, - color = 0, location = location, ), description = description, @@ -46,16 +43,12 @@ class EventSearchTest { private fun allDayCandidate(title: String, day: String): SearchCandidate { val begin = Instant.parse("${day}T00:00:00Z") return SearchCandidate( - event = EventInstance( - instanceId = nextId, - eventId = nextId++, - calendarId = 1L, + event = testEvent( + id = nextId++, title = title, start = begin, end = begin.plus(kotlin.time.Duration.parse("24h")), isAllDay = true, - color = 0, - location = null, ), ) } @@ -183,16 +176,12 @@ class EventSearchTest { // Behind UTC an all-day event sits at midnight UTC, which is the previous // month locally (#82) — the month has to come from the span's first day. val newYear = SearchCandidate( - event = EventInstance( - instanceId = 99L, - eventId = 99L, - calendarId = 1L, + event = testEvent( + id = 99L, title = "Test holiday", start = Instant.parse("2027-02-01T00:00:00Z"), end = Instant.parse("2027-02-02T00:00:00Z"), isAllDay = true, - color = 0, - location = null, ), ) @@ -308,6 +297,23 @@ class EventSearchTest { assertThat(snippet.text).isEqualTo("erste Zeile zweite Zeile") } + @Test + fun `an html description matches and snippets on its text, not its tags`() { + val html = "

Raum 4.12

" + assertThat(search(candidate("Notiz", description = html), query = "div").isEmpty).isTrue() + + val snippet = search(candidate("Notiz", description = html), query = "raum 4.12") + .allHits.single().descriptionSnippet + requireNotNull(snippet) + assertThat(snippet.text).isEqualTo("Raum 4.12") + } + + @Test + fun `a link address in an html description is still searchable`() { + val html = "

Join Zoom Meeting

" + assertThat(search(candidate("Call", description = html), query = "81234567890").allHits).hasSize(1) + } + @Test fun `a blank query matches nothing`() { assertThat(search(candidate("Test"), query = " ").isEmpty).isTrue() diff --git a/app/src/test/java/de/jeanlucmakiola/calendula/domain/EventShiftTest.kt b/app/src/test/java/de/jeanlucmakiola/calendula/domain/EventShiftTest.kt index 53c96ca4..3bef4c97 100644 --- a/app/src/test/java/de/jeanlucmakiola/calendula/domain/EventShiftTest.kt +++ b/app/src/test/java/de/jeanlucmakiola/calendula/domain/EventShiftTest.kt @@ -5,8 +5,10 @@ import kotlinx.datetime.LocalDate import kotlinx.datetime.LocalDateTime import kotlinx.datetime.LocalTime import kotlinx.datetime.TimeZone +import kotlinx.datetime.UtcOffset import kotlinx.datetime.toInstant import org.junit.jupiter.api.Test +import kotlin.time.Instant class EventShiftTest { @@ -22,8 +24,8 @@ class EventShiftTest { calendarId = 1L, title = "Standup", isAllDay = isAllDay, - start = start, - end = end, + start = FormTime(start), + end = FormTime(end), timezone = timezone, ) @@ -34,8 +36,8 @@ class EventShiftTest { val moved = original.shiftedTo(target, berlin) - assertThat(moved.start).isEqualTo(LocalDateTime(LocalDate(2026, 6, 12), LocalTime(14, 30))) - assertThat(moved.end).isEqualTo(LocalDateTime(LocalDate(2026, 6, 12), LocalTime(15, 30))) + assertThat(moved.start.dateTime).isEqualTo(LocalDateTime(LocalDate(2026, 6, 12), LocalTime(14, 30))) + assertThat(moved.end.dateTime).isEqualTo(LocalDateTime(LocalDate(2026, 6, 12), LocalTime(15, 30))) } @Test @@ -52,8 +54,8 @@ class EventShiftTest { val moved = original.shiftedTo(target, berlin) assertThat(moved.timezone).isEqualTo("America/New_York") - assertThat(moved.start).isEqualTo(LocalDateTime(LocalDate(2026, 6, 11), LocalTime(9, 30))) - assertThat(moved.end).isEqualTo(LocalDateTime(LocalDate(2026, 6, 11), LocalTime(10, 30))) + assertThat(moved.start.dateTime).isEqualTo(LocalDateTime(LocalDate(2026, 6, 11), LocalTime(9, 30))) + assertThat(moved.end.dateTime).isEqualTo(LocalDateTime(LocalDate(2026, 6, 11), LocalTime(10, 30))) } @Test @@ -69,10 +71,10 @@ class EventShiftTest { // Two real hours from 01:00 CET lands at 04:00 CEST: the hour in // between does not exist. - assertThat(moved.start).isEqualTo(LocalDateTime(LocalDate(2026, 3, 29), LocalTime(1, 0))) - assertThat(moved.end).isEqualTo(LocalDateTime(LocalDate(2026, 3, 29), LocalTime(4, 0))) - assertThat(moved.end.toInstant(berlin) - moved.start.toInstant(berlin)) - .isEqualTo(original.end.toInstant(berlin) - original.start.toInstant(berlin)) + assertThat(moved.start.dateTime).isEqualTo(LocalDateTime(LocalDate(2026, 3, 29), LocalTime(1, 0))) + assertThat(moved.end.dateTime).isEqualTo(LocalDateTime(LocalDate(2026, 3, 29), LocalTime(4, 0))) + assertThat(moved.end.dateTime.toInstant(berlin) - moved.start.dateTime.toInstant(berlin)) + .isEqualTo(original.end.dateTime.toInstant(berlin) - original.start.dateTime.toInstant(berlin)) } @Test @@ -83,13 +85,15 @@ class EventShiftTest { val moved = original.shiftedTo(target, berlin) - assertThat(moved.start).isEqualTo(LocalDateTime(LocalDate(2026, 3, 29), LocalTime(3, 30))) + assertThat(moved.start.dateTime).isEqualTo(LocalDateTime(LocalDate(2026, 3, 29), LocalTime(3, 30))) } @Test fun `a zero-distance drop leaves the form untouched`() { - val original = form() - assertThat(original.shiftedTo(original.start.toInstant(berlin), berlin)).isEqualTo(original) + // As read from the provider, offsets and all. + val start = form().start.dateTime.toInstant(berlin) + val original = form().withTimes(start, form().end.dateTime.toInstant(berlin), berlin) + assertThat(original.shiftedTo(start, berlin)).isEqualTo(original) } @Test @@ -99,7 +103,7 @@ class EventShiftTest { val moved = original.shiftedTo(target, newYork) - assertThat(moved.start).isEqualTo(LocalDateTime(LocalDate(2026, 6, 11), LocalTime(12, 0))) + assertThat(moved.start.dateTime).isEqualTo(LocalDateTime(LocalDate(2026, 6, 11), LocalTime(12, 0))) } @Test @@ -125,8 +129,8 @@ class EventShiftTest { val moved = multiDay.shiftedByDays(-2, berlin) - assertThat(moved.start).isEqualTo(LocalDateTime(LocalDate(2026, 6, 9), LocalTime(22, 0))) - assertThat(moved.end).isEqualTo(LocalDateTime(LocalDate(2026, 6, 11), LocalTime(2, 0))) + assertThat(moved.start.dateTime).isEqualTo(LocalDateTime(LocalDate(2026, 6, 9), LocalTime(22, 0))) + assertThat(moved.end.dateTime).isEqualTo(LocalDateTime(LocalDate(2026, 6, 11), LocalTime(2, 0))) } @Test @@ -140,11 +144,11 @@ class EventShiftTest { val moved = overnight.shiftedByDays(7, berlin) - assertThat(moved.start).isEqualTo(LocalDateTime(LocalDate(2026, 3, 28), LocalTime(22, 0))) - assertThat(moved.end.toInstant(berlin) - moved.start.toInstant(berlin)) - .isEqualTo(overnight.end.toInstant(berlin) - overnight.start.toInstant(berlin)) + assertThat(moved.start.dateTime).isEqualTo(LocalDateTime(LocalDate(2026, 3, 28), LocalTime(22, 0))) + assertThat(moved.end.dateTime.toInstant(berlin) - moved.start.dateTime.toInstant(berlin)) + .isEqualTo(overnight.end.dateTime.toInstant(berlin) - overnight.start.dateTime.toInstant(berlin)) // The wall-clock end therefore lands an hour later than a naive +7 days. - assertThat(moved.end).isEqualTo(LocalDateTime(LocalDate(2026, 3, 29), LocalTime(5, 0))) + assertThat(moved.end.dateTime).isEqualTo(LocalDateTime(LocalDate(2026, 3, 29), LocalTime(5, 0))) } @Test @@ -152,4 +156,111 @@ class EventShiftTest { val original = form() assertThat(original.shiftedByDays(0, berlin)).isEqualTo(original) } + + @Test + fun `resizing sets each edge on its own`() { + val original = form() + val end = LocalDateTime(LocalDate(2026, 6, 11), LocalTime(12, 30)).toInstant(berlin) + + val resized = original.resizedTo(original.start.dateTime.toInstant(berlin), end, berlin) + + assertThat(resized.start).isEqualTo(original.start) + assertThat(resized.end.dateTime).isEqualTo(LocalDateTime(LocalDate(2026, 6, 11), LocalTime(12, 30))) + } + + @Test + fun `a resize past midnight carries the end onto the next day`() { + val original = form() + val end = LocalDateTime(LocalDate(2026, 6, 12), LocalTime(1, 0)).toInstant(berlin) + + val resized = original.resizedTo(original.start.dateTime.toInstant(berlin), end, berlin) + + assertThat(resized.end.dateTime).isEqualTo(LocalDateTime(LocalDate(2026, 6, 12), LocalTime(1, 0))) + } + + @Test + fun `a pinned event is resized in its own zone`() { + val original = form( + start = LocalDateTime(LocalDate(2026, 6, 11), LocalTime(9, 0)), + end = LocalDateTime(LocalDate(2026, 6, 11), LocalTime(10, 0)), + timezone = "America/New_York", + ) + // "15:30 Berlin" is 09:30 in New York. + val start = LocalDateTime(LocalDate(2026, 6, 11), LocalTime(15, 30)).toInstant(berlin) + + val resized = original.resizedTo(start, original.end.dateTime.toInstant(newYork), berlin) + + assertThat(resized.start.dateTime).isEqualTo(LocalDateTime(LocalDate(2026, 6, 11), LocalTime(9, 30))) + assertThat(resized.end).isEqualTo(original.end) + } + + @Test + fun `an all-day event ignores a resize`() { + val allDay = form(isAllDay = true) + val start = allDay.start.dateTime.toInstant(berlin) + + assertThat(allDay.resizedTo(start, start, berlin)).isEqualTo(allDay) + } + + // 02:00 CEST to 02:00 CET on 2026-10-25: one real hour, one wall-clock value. + private val repeatStart = Instant.parse("2026-10-25T00:00:00Z") + private val repeatEnd = Instant.parse("2026-10-25T01:00:00Z") + + @Test + fun `moving an event in the repeated fall-back hour keeps its length`() { + val original = form().withTimes(repeatStart, repeatEnd, berlin) + val moved = original.shiftedTo(Instant.parse("2026-10-25T00:30:00Z"), berlin) + assertThat(moved.startInstant(berlin)).isEqualTo(Instant.parse("2026-10-25T00:30:00Z")) + assertThat(moved.endInstant(berlin)).isEqualTo(Instant.parse("2026-10-25T01:30:00Z")) + } + + @Test + fun `a move onto the second repeated hour stays there`() { + val target = Instant.parse("2026-10-25T01:30:00Z") + val moved = form().withTimes(repeatStart, repeatEnd, berlin).shiftedTo(target, berlin) + assertThat(moved.start.dateTime).isEqualTo(LocalDateTime(LocalDate(2026, 10, 25), LocalTime(2, 30))) + assertThat(moved.startInstant(berlin)).isEqualTo(target) + } + + @Test + fun `resolveIn takes the preferred offset only where the hour repeats`() { + val repeated = LocalDateTime(LocalDate(2026, 10, 25), LocalTime(2, 30)) + val cet = UtcOffset(hours = 1) + assertThat(repeated.resolveIn(berlin, cet)).isEqualTo(Instant.parse("2026-10-25T01:30:00Z")) + assertThat(repeated.resolveIn(berlin, null)).isEqualTo(Instant.parse("2026-10-25T00:30:00Z")) + // Not one of 14:00's offsets on a summer day: ignored. + val summer = LocalDateTime(LocalDate(2026, 6, 11), LocalTime(14, 0)) + assertThat(summer.resolveIn(berlin, cet)).isEqualTo(summer.toInstant(berlin)) + } + + @Test + fun `a day move onto the repeated hour doesn't depend on the source's season`() { + // 02:30 a week after the fall-back day (CET) and in summer (CEST), both + // moved onto it: the earlier pass either way, as a timeline drop. + val first = Instant.parse("2026-10-25T00:30:00Z") + val november = form().withTimes( + Instant.parse("2026-11-01T01:30:00Z"), + Instant.parse("2026-11-01T02:30:00Z"), + berlin, + ) + assertThat(november.shiftedByDays(-7, berlin).startInstant(berlin)).isEqualTo(first) + val summer = form( + start = LocalDateTime(LocalDate(2026, 10, 18), LocalTime(2, 30)), + end = LocalDateTime(LocalDate(2026, 10, 18), LocalTime(3, 30)), + ) + assertThat(summer.shiftedByDays(7, berlin).startInstant(berlin)).isEqualTo(first) + } + + @Test + fun `a day move onto the spring-forward gap keeps its wall clock`() { + // Saturday 02:30 to 03:30, moved onto Sunday 29 March, when 02:30 is skipped. + val moved = form( + start = LocalDateTime(LocalDate(2026, 3, 28), LocalTime(2, 30)), + end = LocalDateTime(LocalDate(2026, 3, 28), LocalTime(3, 30)), + ).shiftedByDays(1, berlin) + assertThat(moved.start.dateTime).isEqualTo(LocalDateTime(LocalDate(2026, 3, 29), LocalTime(2, 30))) + // It still means 03:30 CEST, an hour long. + assertThat(moved.startInstant(berlin)).isEqualTo(Instant.parse("2026-03-29T01:30:00Z")) + assertThat(moved.endInstant(berlin)).isEqualTo(Instant.parse("2026-03-29T02:30:00Z")) + } } diff --git a/app/src/test/java/de/jeanlucmakiola/calendula/domain/HtmlTextTest.kt b/app/src/test/java/de/jeanlucmakiola/calendula/domain/HtmlTextTest.kt new file mode 100644 index 00000000..1bc09871 --- /dev/null +++ b/app/src/test/java/de/jeanlucmakiola/calendula/domain/HtmlTextTest.kt @@ -0,0 +1,219 @@ +package de.jeanlucmakiola.calendula.domain + +import com.google.common.truth.Truth.assertThat +import org.junit.jupiter.api.Test + +class HtmlTextTest { + + @Test + fun `prose with angle brackets is not html`() { + assertThat(looksLikeHtml("I <3 this, and a < b > c")).isFalse() + assertThat(looksLikeHtml("Teams Meeting ")).isFalse() + assertThat(looksLikeHtml("Bring ")).isFalse() + } + + @Test + fun `common tags are html`() { + assertThat(looksLikeHtml("Line one
Line two")).isTrue() + assertThat(looksLikeHtml("

Hi

")).isTrue() + assertThat(looksLikeHtml("See here")).isTrue() + } + + @Test + fun `angle-bracketed links and addresses stay text`() { + val html = "Join
here or " + assertThat(parseHtml(html).text).isEqualTo("Join\nhere or ") + } + + @Test + fun `plain text passes through untouched`() { + val text = " Agenda:\n\n\n- one \n- two" + assertThat(descriptionRichText(text)).isEqualTo(RichText(text)) + } + + @Test + fun `blocks and breaks become lines and whitespace collapses`() { + val html = "
Hello\n world
Second
Third
" + assertThat(parseHtml(html).text).isEqualTo("Hello world\nSecond\nThird") + } + + @Test + fun `head, styles, scripts and comments are dropped`() { + val html = """ + +

Body

+ """.trimIndent() + assertThat(parseHtml(html).text).isEqualTo("Body") + } + + @Test + fun `an nbsp paragraph keeps one blank line, more collapse`() { + val html = "

One

 

 

 

Two

" + assertThat(parseHtml(html).text).isEqualTo("One\n\nTwo") + } + + @Test + fun `entities are decoded`() { + assertThat(parseHtml("

Fish & chips <3 €5 – café &bogus;

").text) + .isEqualTo("Fish & chips <3 €5 – café &bogus;") + } + + @Test + fun `inline styles cover their text`() { + val rich = parseHtml("

A bold and italic word

") + assertThat(rich.text).isEqualTo("A bold and italic word") + assertThat(rich.styles).containsExactly( + StyleRange(2, 6, InlineStyle.Bold), + StyleRange(11, 17, InlineStyle.Italic), + ) + } + + @Test + fun `fonts and colours are not kept`() { + val rich = parseHtml("Text") + assertThat(rich).isEqualTo(RichText("Text")) + } + + @Test + fun `links keep their href, unsafe schemes are dropped`() { + val rich = parseHtml( + "Join " + + "Dial Bad", + ) + assertThat(rich.text).isEqualTo("Join Dial Bad") + assertThat(rich.links).containsExactly( + LinkRange(0, 4, "https://teams.microsoft.com/l/x?a=1&b=2"), + LinkRange(5, 9, "tel:+4930123,,456#"), + ) + } + + @Test + fun `lists get bullets and numbers`() { + val html = "

Agenda

  • One
  • Two
    1. Sub
  1. A
  2. B
" + assertThat(parseHtml(html).text).isEqualTo("Agenda\n• One\n• Two\n 1. Sub\n1. A\n2. B") + } + + @Test + fun `table rows become lines with cells side by side`() { + val html = "" + + "
TimeTopic
9:00Intro
 Spacer row
" + assertThat(parseHtml(html).text).isEqualTo("Time · Topic\n9:00 · Intro\nSpacer row") + } + + @Test + fun `formatting on a dropped spacer cell doesn't leak onto the next`() { + val rich = parseHtml("
 Plain
") + assertThat(rich).isEqualTo(RichText("Plain")) + } + + @Test + fun `pre keeps its whitespace`() { + assertThat(parseHtml("
a  b\n  c
").text).isEqualTo("a b\n c") + } + + @Test + fun `spans shift with trimmed whitespace`() { + val rich = parseHtml("

 

Bold

") + assertThat(rich.text).isEqualTo("Bold") + assertThat(rich.styles).containsExactly(StyleRange(0, 4, InlineStyle.Bold)) + } + + @Test + fun `broken markup stays text`() { + assertThat(parseHtml("

x < y and z

").text).isEqualTo("x < y and z") + assertThat(parseHtml("

open tail").links) + .containsExactly(LinkRange(5, 9, "https://a.b")) + } + + @Test + fun `a paragraph inside a list item stays on the bullet's line`() { + assertThat(parseHtml("

").text) + .isEqualTo("• One\n• Two") + } + + @Test + fun `newlines are the lines when the markup sets none`() { + val rich = parseHtml("Agenda:\n1. Intro\n2. Q&A") + assertThat(rich.text).isEqualTo("Agenda:\n1. Intro\n2. Q&A") + } + + @Test + fun `newlines in markup with its own lines are just spaces`() { + assertThat(parseHtml("

wrapped\nsource line

").text).isEqualTo("wrapped source line") + } + + @Test + fun `a link scheme is lower-cased`() { + assertThat(parseHtml("Join").links.single().url) + .isEqualTo("https://Teams.example/Join") + } + + @Test + fun `a query parameter is not read as an entity`() { + assertThat(parseHtml("x").links.single().url) + .isEqualTo("https://x.example/?id=5®=eu×=3") + } + + @Test + fun `outlook cells with paragraphs still sit side by side`() { + val html = "" + + "

9:00

Intro

10:00

Talk

" + val rich = parseHtml(html) + assertThat(rich.text).isEqualTo("9:00 · Intro\n10:00 · Talk") + assertThat(rich.styles).containsExactly(StyleRange(7, 12, InlineStyle.Bold)) + } + + @Test + fun `empty cells anywhere in a row leave no separator`() { + val html = "
Time Topic
" + assertThat(parseHtml(html).text).isEqualTo("Time · Topic") + } + + @Test + fun `a trailing empty cell doesn't join the text after the table`() { + val html = "
10:00Demo

After

" + assertThat(parseHtml(html).text).isEqualTo("10:00 · Demo\nAfter") + } + + @Test + fun `an unclosed head or style doesn't swallow the description`() { + assertThat(parseHtml("

Agenda

").text).isEqualTo("Agenda") + assertThat(parseHtml("