Compare commits

...
Author SHA1 Message Date
Jean-Luc Makiolaandmakiolaj 5665cb8c95 Fix issues from the 2.23.0 branch review (#428)
Beta — Codeberg pre-release / detect (push) Successful in 6s
Beta — Codeberg pre-release / beta (push) Skipped
Fixes from reviewing the 2.23.0 release branch, plus a second pass over those fixes.

- Moved recurring exceptions keep their colour when they change calendar, instead of losing their colour key.
- An external request (widget, edit intent, share) now resets the form it replaces. Forms reset only after their slide-out ends, so they never go blank on the way out.
- Import, duplicate and picker state survive rotation, and recreating the activity no longer replays the launch intent.
- A shared .ics attachment opens the import, even when the email app adds a subject line as text. Plain text still opens a new event.
- Stale import state no longer reopens the previous import's form.
- The theme and dynamic colour are cached so a cold start draws the right colours from the first frame.
- Write-permission prompts (tap to edit, delete, duplicate, selection actions, week drafts) keep their pending action across rotation, and tap to edit falls back to details when the prompt is refused.
- Zone and date sources share one app-scoped receiver instead of one per collector.
- Scrolling back over an empty agenda past grows the window by at most a year per step, not exponentially.
- RRULE part names and the RRULE: prefix are matched case-insensitively on import.
- Search closes when another overlay takes over.

Closes #306, #178, #387, #367

Co-authored-by: Jean-Luc Makiola <business@jeanlucmakiola.de>
Reviewed-on: https://codeberg.org/jlmakiola/calendula/pulls/428
2026-10-19 19:38:37 +02:00
Jean-Luc Makiolaandmakiolaj 17b3753ad3 Merge the month seating copies, resize state and page grids (#418)
Beta — Codeberg pre-release / detect (push) Successful in 6s
Beta — Codeberg pre-release / beta (push) Skipped
Step 8 of the simplification review: the three behaviour-sensitive merges. Each lands behind a characterization test written and passed against the old code first.

**Month row seating**
- `MonthWeek.seating(col, laneCap)` is the one source for which event sits in which lane and what overflows. `laneEvents`, `chipAt`, `overflowEvents` and MonthWeekRow's inline copy all build on it, so dots, bars and pills can't drift apart (#53).
- MonthWeekRow computes the seating once per row (`remember(week, laneCap)`) instead of re-filtering every column on each recomposition.
- `OverflowDots.total` and `shownLanes` are gone; they always equalled `events.size` and `laneCap`.
- MonthSeatingTest pins the four old copies against each other over 400 generated weeks × lane caps 0–6; they agreed everywhere, and `seating()` matches them.

**Timeline resize**
- TimelineDragController's eight loose `resize*` fields are one `ResizeSession?`, so cancel clears it in one assignment. Moves mutate it in place; no per-frame allocation. None of the fields were Compose state.
- Only difference: a resize starting without the previous one ending used to inherit the old held slot; it now starts clean.

**Timeline paging**
- Week, multi-day and day page through one `DaysGrid` with `weeks(firstDay)`, `days` and `startingAt(date, count)` factories; the PageGrid interface, WeekGrid and DayGrid are gone. Page numbers and grid equality (used by pager keys) are unchanged; PageNumberingTest pins them.
- jumpToDate no longer detects the multi-day view by class; it re-frames when the target would open mid-page, which a test checks against the old rule for every in-range date.

Not yet checked on a device. Worth a look: month bars/pills/+N dots on crowded days in paged and split styles plus the split morph, chip taps and month drag; resize of both edges incl. across midnight, cancel then plain drag, RTL; paging, view switching, jump to date/today, week-start and multi-day count changes.

Co-authored-by: Jean-Luc Makiola <business@jeanlucmakiola.de>
Reviewed-on: https://codeberg.org/jlmakiola/calendula/pulls/418
2026-10-16 14:42:31 +02:00
Jean-Luc Makiolaandmakiolaj efc36f1bff Restructure the editor, timeline and calendar host (#417)
Beta — Codeberg pre-release / detect (push) Successful in 5s
Beta — Codeberg pre-release / beta (push) Skipped
Step 7 of the simplification review: structure changes in the three biggest UI files. No intended visible change, except one fix noted under the host.

**Editor** (EventEditScreen)
- Pass-through wrappers removed: InlineField → floret InlineTextField, SaveScopeDialog → RecurringScopeDialog, REMINDER_QUICK_PICKS → REMINDER_PRESETS, reminderLabel/reminderLeadText → reminderLeadTimeLabel, currentDetailLocale → currentLocale.
- One PickerCardBody draws the time zone, recurrence, visibility and colour cards.
- The seven saveable showXPicker booleans are one saveable `EditSheet?` slot, so two sheets can't be open at once. EventEditContent goes from ~770 to ~250 lines; each card section and the sheet host are their own composables.
- Not done: GroupedSurface on the grouped form cards, since it adds a visible press-morph.

**Timeline** (WeekScreen, TimelineDrag)
- A remembered TimelineActions holder (scroll state, drag controller, five callbacks) replaces the seven values threaded through nine composables. Callbacks go through rememberUpdatedState, so the holder stays stable and pages don't recompose.
- TimelineDragController shares pieces(), settle(), column() (the RTL flip, was 5 copies) and snapToSlot() between move and resize. No extra per-frame work.

**Calendar host** (CalendarHost, RootScreen, MainActivity, view models)
- SlideOverlay replaces seven copies of the overlay enter/exit block; rememberHeld replaces the hand-paired held keys; one saveable CreateRequest replaces three create fields, and the widget create path calls openCreate.
- An ExternalRequests holder built in MainActivity replaces 13 parameters declared twice in RootScreen and CalendarHost.
- Month, week and agenda view models share one rollover-following today flow. CalendarHost keeps its own, which survives recreation.
- Fix: after rotation or process death with the detail or edit overlay open, closing it slid out a blank screen, because the held key was only set by in-app opens. It now keeps its content through the slide-out, as ARCHITECTURE.md describes.

Not yet checked on a device. Worth a look before release: open/close of detail, edit and create from every entry point (tap, notification, widget, QS tile, ACTION_INSERT/EDIT, .ics), rotation with an overlay open, every editor picker incl. rotation, and timeline move/resize/drag-to-create incl. RTL and after pinch-zoom.

Co-authored-by: Jean-Luc Makiola <business@jeanlucmakiola.de>
Reviewed-on: https://codeberg.org/jlmakiola/calendula/pulls/417
2026-10-16 14:26:53 +02:00
45 changed files with 1823 additions and 1473 deletions
+1 -1
View File
@@ -152,7 +152,7 @@
</intent-filter>
<!-- Text shared or selected in another app opens a prefilled new
event (MainActivity.sharedTextExtrasOrNull, issue #306). -->
event (MainActivity.sharedTextRequestOrNull, issue #306). -->
<intent-filter>
<action android:name="android.intent.action.SEND" />
<category android:name="android.intent.category.DEFAULT" />
@@ -6,6 +6,7 @@ import android.content.res.Configuration
import android.net.Uri
import android.os.Bundle
import android.provider.CalendarContract
import android.provider.OpenableColumns
import androidx.activity.SystemBarStyle
import androidx.activity.compose.setContent
import androidx.activity.enableEdgeToEdge
@@ -36,6 +37,8 @@ import de.jeanlucmakiola.calendula.data.prefs.is24Hour
import de.jeanlucmakiola.calendula.domain.EventForm
import de.jeanlucmakiola.calendula.domain.buildInsertEventForm
import de.jeanlucmakiola.calendula.domain.sharedTextOrNull
import de.jeanlucmakiola.calendula.ui.ExternalRequests
import de.jeanlucmakiola.calendula.ui.InsertRequest
import de.jeanlucmakiola.calendula.ui.RootScreen
import de.jeanlucmakiola.calendula.ui.common.LocalShowHourGrid
import de.jeanlucmakiola.calendula.ui.common.LocalMultiDayCount
@@ -59,6 +62,8 @@ import de.jeanlucmakiola.calendula.ui.theme.WindowThemeCache
import de.jeanlucmakiola.calendula.ui.theme.windowBackgroundRes
import de.jeanlucmakiola.calendula.ui.theme.calendulaTypography
import de.jeanlucmakiola.calendula.ui.theme.resolveFontFamily
import kotlinx.coroutines.flow.MutableStateFlow
import kotlinx.coroutines.flow.combine
import kotlinx.coroutines.launch
import kotlinx.datetime.LocalDate
import kotlinx.datetime.TimeZone
@@ -67,9 +72,6 @@ import kotlin.time.Clock
import kotlin.time.Instant
import javax.inject.Inject
/** A prefilled create form from an external launch, with the source it came from. */
private data class InsertRequest(val form: EventForm, val source: ImportSource)
@AndroidEntryPoint
class MainActivity : AppCompatActivity() {
@@ -81,23 +83,12 @@ class MainActivity : AppCompatActivity() {
// picks up the in-app override instead of the night resource qualifier.
private var systemBarsDark = false
// The occurrence a reminder notification was tapped for (eventId, begin,
// end — the detail screen's key shape). singleTop + onNewIntent route a
// tap into the running activity; CalendarHost consumes and clears it.
private var requestedDetailKey by mutableStateOf<LongArray?>(null)
// A navigation a home-screen widget asked for (open a date / start a
// create). Consumed once by CalendarHost, same pattern as the detail key.
private var requestedNav by mutableStateOf<WidgetNavRequest?>(null)
// An .ics file opened/shared into the app (ACTION_VIEW/SEND). Consumed once
// by CalendarHost's import flow.
private var requestedImportUri by mutableStateOf<Uri?>(null)
// A prefilled new-event form from an external ACTION_INSERT launch (another
// app/widget asking us to create an event, issue #30) or shared text (#306).
// Consumed once by CalendarHost, which opens it in the create form for review.
private var requestedInsert by mutableStateOf<InsertRequest?>(null)
private val requests = ExternalRequests(
onExternalFormClosed = {
insertFormOpen = false
if (launchedForInsert) finish()
},
)
// Whether such a form is still open. Only then does a recreation re-read the
// intent to bring it back; a saved or dismissed one stays closed.
@@ -107,11 +98,6 @@ class MainActivity : AppCompatActivity() {
// app that asked instead of leaving the calendar on top of it.
private var launchedForInsert = false
// An external "edit this event" (ACTION_EDIT on content://.../events/<id>):
// opens the occurrence in the edit form. Same occurrence-key shape as the
// detail channel; consumed once by CalendarHost.
private var requestedEditKey by mutableStateOf<LongArray?>(null)
// A captured crash report awaiting the user's decision, surfaced as a dialog
// over the calendar on the next launch (the single-crash path). A startup
// crash-loop is handled out of band, before setContent — see below.
@@ -141,10 +127,17 @@ class MainActivity : AppCompatActivity() {
cachedTheme?.windowBackgroundRes()?.let { window.setBackgroundDrawableResource(it) }
systemBarsDark = (cachedTheme ?: ThemeMode.SYSTEM).isDark(systemDark)
applyEdgeToEdge()
val appearance = MutableStateFlow(
Appearance(
themeMode = cachedTheme ?: ThemeMode.SYSTEM,
dynamicColor = WindowThemeCache.readDynamicColor(this),
),
)
lifecycleScope.launch {
settingsPrefs.themeMode.collect { mode ->
WindowThemeCache.write(this@MainActivity, mode)
window.setBackgroundDrawableResource(mode.windowBackgroundRes() ?: R.color.window_background)
combine(settingsPrefs.themeMode, settingsPrefs.dynamicColor, ::Appearance).collect { stored ->
WindowThemeCache.write(this@MainActivity, stored.themeMode, stored.dynamicColor ?: true)
window.setBackgroundDrawableResource(stored.themeMode.windowBackgroundRes() ?: R.color.window_background)
appearance.value = stored
}
}
// Android hands the intent that started the task back to onCreate every
@@ -160,25 +153,30 @@ class MainActivity : AppCompatActivity() {
// is what carries one through a recreation — the create form only while
// it's still open.
val replaying = savedInstanceState != null || intent.isRelaunch()
requests.replayed = savedInstanceState != null
if (!replaying) {
requestedDetailKey = intent.detailKeyOrNull() ?: intent.viewEventKeyOrNull()
requestedEditKey = intent.editEventKeyOrNull()
requests.detailKey = intent.detailKeyOrNull() ?: intent.viewEventKeyOrNull()
requests.editKey = intent.editEventKeyOrNull()
}
requestedNav = intent.navRequestOrNull()
requests.nav = intent.navRequestOrNull()
?.takeUnless { replaying && it is WidgetNavRequest.OpenEvent }
requestedImportUri = intent.importUriOrNull()
requests.importUri = intent.importUriOrNull()
val insertOpenBefore = savedInstanceState?.getBoolean(KEY_INSERT_FORM_OPEN) == true
requestedInsert = intent.createRequestOrNull()?.takeIf { !replaying || insertOpenBefore }
insertFormOpen = requestedInsert != null
requests.insert = intent.createRequestOrNull()?.takeIf { !replaying || insertOpenBefore }
insertFormOpen = requests.insert != null
launchedForInsert = savedInstanceState?.getBoolean(KEY_LAUNCHED_FOR_INSERT)
?: (requestedInsert != null)
?: (requests.insert != null)
if (CrashReporter.shouldPrompt(this)) pendingCrashReport = CrashReporter.pendingReport(this)
setContent {
// One activity-scoped SettingsViewModel drives both the theme here
// and the Settings screen, so a theme change applies app-wide at once.
val settingsViewModel: SettingsViewModel = hiltViewModel()
val settings by settingsViewModel.state.collectAsStateWithLifecycle()
val darkTheme = settings.themeMode.isDark(isSystemInDarkTheme())
// Seeded from the cache, so the first frame doesn't draw the default
// theme and palette before the stored choices arrive.
val shownAppearance by appearance.collectAsStateWithLifecycle()
val themeMode = shownAppearance.themeMode
val darkTheme = themeMode.isDark(isSystemInDarkTheme())
// onCreate can only see the night resource qualifier, not the in-app
// override — re-apply from the resolved theme so the bar icons follow
// the app's light/dark choice.
@@ -216,8 +214,8 @@ class MainActivity : AppCompatActivity() {
}
CalendulaTheme(
darkTheme = darkTheme,
dynamicColor = settings.dynamicColor,
pureBlack = settings.themeMode.isPureBlack,
dynamicColor = shownAppearance.dynamicColor ?: settings.dynamicColor,
pureBlack = themeMode.isPureBlack,
typography = typography,
) {
Box(modifier = Modifier.fillMaxSize()) {
@@ -230,21 +228,7 @@ class MainActivity : AppCompatActivity() {
) {
RootScreen(
modifier = Modifier.fillMaxSize(),
requestedDetailKey = requestedDetailKey,
onDetailKeyConsumed = { requestedDetailKey = null },
widgetNavRequest = requestedNav,
onWidgetNavConsumed = { requestedNav = null },
requestedImportUri = requestedImportUri,
onImportConsumed = { requestedImportUri = null },
requestedInsertForm = requestedInsert?.form,
requestedInsertSource = requestedInsert?.source ?: ImportSource.Insert,
onInsertConsumed = { requestedInsert = null },
onExternalFormClosed = {
insertFormOpen = false
if (launchedForInsert) finish()
},
requestedEditKey = requestedEditKey,
onEditKeyConsumed = { requestedEditKey = null },
requests = requests,
)
}
// A persistent corner marker so a debug build is never
@@ -304,14 +288,22 @@ class MainActivity : AppCompatActivity() {
override fun onNewIntent(intent: Intent) {
super.onNewIntent(intent)
(intent.detailKeyOrNull() ?: intent.viewEventKeyOrNull())?.let { requestedDetailKey = it }
intent.navRequestOrNull()?.let { requestedNav = it }
intent.importUriOrNull()?.let { requestedImportUri = it }
requests.replayed = false
(intent.detailKeyOrNull() ?: intent.viewEventKeyOrNull())?.let { requests.detailKey = it }
intent.navRequestOrNull()?.let { requests.nav = it }
intent.importUriOrNull()?.let { requests.importUri = it }
intent.createRequestOrNull()?.let {
requestedInsert = it
requests.insert = it
insertFormOpen = true
}
intent.editEventKeyOrNull()?.let { requestedEditKey = it }
intent.editEventKeyOrNull()?.let { requests.editKey = it }
// The user moved on into the app, so closing the create form no longer
// hands control back to the app that started it.
if (requests.detailKey != null || requests.nav != null || requests.importUri != null ||
requests.editKey != null
) {
launchedForInsert = false
}
}
/**
@@ -332,9 +324,10 @@ class MainActivity : AppCompatActivity() {
private fun Intent.importUriOrNull(): Uri? {
val uri = when (action) {
Intent.ACTION_VIEW -> data
// Plain text is a create (#306), never a file to import.
Intent.ACTION_SEND -> IntentCompat.getParcelableExtra(this, Intent.EXTRA_STREAM, Uri::class.java)
.takeUnless { type == SHARED_TEXT_TYPE }
// Shared text is a create (#306); a text/plain file is imported only
// when it is calendar data, e.g. an .ics attachment labelled text/plain.
Intent.ACTION_SEND -> sharedStreamOrNull()
?.takeUnless { type == SHARED_TEXT_TYPE && !it.isCalendarFile() }
else -> null
} ?: return null
// The calendar "view time" Uri (a date tap) is also ACTION_VIEW/content;
@@ -388,7 +381,7 @@ class MainActivity : AppCompatActivity() {
*/
private fun Intent.sharedTextRequestOrNull(): InsertRequest? {
val shared = when (action) {
Intent.ACTION_SEND -> if (type == SHARED_TEXT_TYPE) {
Intent.ACTION_SEND -> if (type == SHARED_TEXT_TYPE && sharedStreamOrNull()?.isCalendarFile() != true) {
sharedTextOrNull(
subject = getCharSequenceExtra(Intent.EXTRA_SUBJECT)?.toString(),
text = getCharSequenceExtra(Intent.EXTRA_TEXT)?.toString(),
@@ -409,6 +402,23 @@ class MainActivity : AppCompatActivity() {
return InsertRequest(form, ImportSource.InsertOpenEnded)
}
private fun Intent.sharedStreamOrNull(): Uri? =
IntentCompat.getParcelableExtra(this, Intent.EXTRA_STREAM, Uri::class.java)
/** Whether a shared file is iCalendar/vCalendar data, by its resolved type or its name. */
private fun Uri.isCalendarFile(): Boolean {
val resolvedType = runCatching { contentResolver.getType(this) }.getOrNull()
if (resolvedType in CALENDAR_TYPES) return true
val name = when (scheme) {
"content" -> runCatching {
contentResolver.query(this, arrayOf(OpenableColumns.DISPLAY_NAME), null, null, null)
?.use { c -> if (c.moveToFirst()) c.getString(0) else null }
}.getOrNull()
else -> lastPathSegment
} ?: return false
return CALENDAR_EXTENSIONS.any { name.endsWith(it, ignoreCase = true) }
}
/** A Long extra's value, or null when the extra is absent. */
private fun Intent.longExtraOrNull(key: String): Long? =
if (hasExtra(key)) getLongExtra(key, 0L) else null
@@ -535,6 +545,8 @@ class MainActivity : AppCompatActivity() {
// ACTION_VIEW on content://com.android.calendar/time/<epochMillis>.
private const val CALENDAR_PROVIDER_HOST = "com.android.calendar"
private const val SHARED_TEXT_TYPE = "text/plain"
private val CALENDAR_TYPES = setOf("text/calendar", "text/x-vcalendar", "application/ics")
private val CALENDAR_EXTENSIONS = listOf(".ics", ".vcs")
private const val KEY_INSERT_FORM_OPEN = "insert_form_open"
private const val KEY_LAUNCHED_FOR_INSERT = "launched_for_insert"
@@ -627,3 +639,6 @@ class MainActivity : AppCompatActivity() {
}
}
}
/** The theme choices the window needs before the settings screen's state loads. */
private data class Appearance(val themeMode: ThemeMode, val dynamicColor: Boolean?)
@@ -725,7 +725,7 @@ class AndroidCalendarDataSource @Inject constructor(
),
null,
)?.use { c ->
c.mapAll { EventColorOption(key = it.getString(0).orEmpty(), argb = it.getInt(1)) }
c.mapRows { EventColorOption(key = getString(0).orEmpty(), argb = getInt(1)) }
}
?.filter { it.key.isNotEmpty() }
?: emptyList()
@@ -1116,7 +1116,7 @@ class AndroidCalendarDataSource @Inject constructor(
?: throw WriteFailedException("read modified occurrence id=${ex.exceptionEventId}")
val endMillis = ex.dtEndMillis ?: (ex.dtStartMillis + parseRfc2445DurationMillis(ex.duration))
val form = detail.toEditForm(ex.dtStartMillis, endMillis, zone)
.copy(calendarId = targetCalendarId)
.copy(calendarId = targetCalendarId, colorKey = null)
.toDetachedOccurrence()
detached += insertEvent(form, allDayReminderTimeMinutes)
}
@@ -1691,11 +1691,6 @@ class AndroidCalendarDataSource @Inject constructor(
null,
)?.use { c -> c.mapRows { toReminder() } } ?: emptyList()
/** Iterate every row and map; skips nothing. */
private inline fun <T> Cursor.mapAll(mapper: (Cursor) -> T): List<T> = buildList {
while (moveToNext()) add(mapper(this@mapAll))
}
/** A fresh globally-unique `UID_2445`, for an event that carries none of its own. */
private fun mintUid(): String = "${UUID.randomUUID()}@calendula"
@@ -0,0 +1,8 @@
package de.jeanlucmakiola.calendula.data.di
import javax.inject.Qualifier
/** The process-wide `CoroutineScope` that app-lifetime singletons share their flows in. */
@Qualifier
@Retention(AnnotationRetention.BINARY)
annotation class ApplicationScope
@@ -24,6 +24,9 @@ import de.jeanlucmakiola.calendula.data.time.AndroidTodaySource
import de.jeanlucmakiola.calendula.data.time.AndroidZoneSource
import de.jeanlucmakiola.calendula.data.time.TodaySource
import de.jeanlucmakiola.calendula.data.time.ZoneSource
import kotlinx.coroutines.CoroutineScope
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.SupervisorJob
import javax.inject.Singleton
private val Context.calendulaDataStore: DataStore<Preferences> by preferencesDataStore(
@@ -85,4 +88,9 @@ object DataProvideModule {
@Singleton
fun provideDataStore(@ApplicationContext context: Context): DataStore<Preferences> =
context.calendulaDataStore
@Provides
@Singleton
@ApplicationScope
fun provideApplicationScope(): CoroutineScope = CoroutineScope(SupervisorJob() + Dispatchers.Default)
}
@@ -3,11 +3,18 @@ package de.jeanlucmakiola.calendula.data.time
import android.content.Context
import android.content.Intent
import dagger.hilt.android.qualifiers.ApplicationContext
import de.jeanlucmakiola.calendula.data.di.ApplicationScope
import de.jeanlucmakiola.floret.android.broadcastTicks
import de.jeanlucmakiola.floret.android.stateWhileSubscribed
import kotlinx.coroutines.CoroutineScope
import kotlinx.coroutines.ExperimentalCoroutinesApi
import kotlinx.coroutines.delay
import kotlinx.coroutines.flow.Flow
import kotlinx.coroutines.flow.SharingStarted
import kotlinx.coroutines.flow.shareIn
import kotlinx.coroutines.flow.StateFlow
import kotlinx.coroutines.flow.distinctUntilChanged
import kotlinx.coroutines.flow.onEach
import kotlinx.coroutines.flow.transformLatest
import kotlinx.datetime.LocalDate
import kotlinx.datetime.TimeZone
@@ -23,10 +30,12 @@ interface TodaySource {
/**
* Re-reads the date on every minute boundary while collected, and at once on the
* system's date, time and zone broadcasts, which can arrive late or not at all.
* One receiver and tick loop is shared by every collector.
*/
@OptIn(ExperimentalCoroutinesApi::class)
class AndroidTodaySource @Inject constructor(
@ApplicationContext private val context: Context,
@ApplicationScope scope: CoroutineScope,
) : TodaySource {
override val today: Flow<LocalDate> = context
@@ -38,8 +47,27 @@ class AndroidTodaySource @Inject constructor(
}
}
.distinctUntilChanged()
.shareIn(scope, SharingStarted.WhileSubscribed(replayExpirationMillis = 0), replay = 1)
}
private const val MINUTE_MILLIS = 60_000L
fun currentDate(): LocalDate = Clock.System.now().toLocalDateTime(TimeZone.currentSystemDefault()).date
/**
* Today as a hot flow seeded with [initial]. [onRollover] runs with the previous
* and the new date each time the day changes while collected, so a screen left
* open over midnight can move off yesterday (#373).
*/
fun Flow<LocalDate>.stateFollowingDays(
scope: CoroutineScope,
initial: LocalDate,
onRollover: (old: LocalDate, new: LocalDate) -> Unit,
): StateFlow<LocalDate> {
var last = initial
return onEach { date ->
val old = last
last = date
if (old != date) onRollover(old, date)
}.stateWhileSubscribed(scope, initial)
}
@@ -3,10 +3,14 @@ package de.jeanlucmakiola.calendula.data.time
import android.content.Context
import android.content.Intent
import dagger.hilt.android.qualifiers.ApplicationContext
import de.jeanlucmakiola.calendula.data.di.ApplicationScope
import de.jeanlucmakiola.floret.android.broadcastTicks
import kotlinx.coroutines.CoroutineScope
import kotlinx.coroutines.flow.Flow
import kotlinx.coroutines.flow.SharingStarted
import kotlinx.coroutines.flow.distinctUntilChanged
import kotlinx.coroutines.flow.map
import kotlinx.coroutines.flow.shareIn
import kotlinx.datetime.TimeZone
import javax.inject.Inject
@@ -23,14 +27,16 @@ interface ZoneSource {
fun current(): TimeZone
}
/** Follows the system's zone broadcast. */
/** Follows the system's zone broadcast, one receiver shared by every collector. */
class AndroidZoneSource @Inject constructor(
@ApplicationContext private val context: Context,
@ApplicationScope scope: CoroutineScope,
) : ZoneSource {
override val zone: Flow<TimeZone> = context.broadcastTicks(Intent.ACTION_TIMEZONE_CHANGED)
.map { current() }
.distinctUntilChanged()
.shareIn(scope, SharingStarted.WhileSubscribed(replayExpirationMillis = 0), replay = 1)
override fun current(): TimeZone = TimeZone.currentSystemDefault()
}
@@ -131,6 +131,10 @@ private class HtmlRenderer(private val html: String) {
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()
@@ -149,6 +153,11 @@ private class HtmlRenderer(private val html: String) {
return end + 1
}
/** An angle-bracketed URL or address (`<https://…>`, `<a@b.c>`), 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
@@ -66,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
@@ -84,8 +86,8 @@ fun sanitizeRrule(raw: String?): SanitizedRrule {
// 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(raw.orEmpty().trim())) {
val key = part.key?.trim().orEmpty()
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
@@ -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
@@ -28,10 +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
@@ -39,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
@@ -63,7 +68,7 @@ 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.rememberWriteGateOr
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
@@ -99,7 +104,6 @@ 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
/**
@@ -116,29 +120,18 @@ import kotlin.time.Instant
* 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 = {},
onExternalFormClosed: () -> Unit = {},
requestedEditKey: LongArray? = null,
onEditKeyConsumed: () -> Unit = {},
viewModel: CalendarHostViewModel = hiltViewModel(),
) {
// Wait for the persisted default view before seeding the stack, so the app
@@ -163,7 +156,7 @@ fun CalendarHost(
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
@@ -194,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<LongArray?>(null) }
var heldKey by remember { mutableStateOf<LongArray?>(null) }
val onOpenDetail: (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
}
}
@@ -238,31 +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<String?>(null) }
var heldCreateIso by remember { mutableStateOf<String?>(null) }
var createStartMinutes by rememberSaveable { mutableStateOf<Int?>(null) }
var heldCreateMinutes by remember { mutableStateOf<Int?>(null) }
// 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).
var createDraftMillis by rememberSaveable { mutableStateOf<LongArray?>(null) }
var heldCreateDraftMillis by remember { mutableStateOf<LongArray?>(null) }
fun openCreate(date: LocalDate, startMinutes: Int?, draftMillis: LongArray?) {
heldCreateIso = date.toString()
createDateIso = date.toString()
heldCreateMinutes = startMinutes
createStartMinutes = startMinutes
heldCreateDraftMillis = draftMillis
createDraftMillis = draftMillis
// Event form (v1.2 create), opened on a date, a tapped slot or a drafted block.
var createRequest by rememberSaveable(stateSaver = createRequestSaver) {
mutableStateOf<CreateRequest?>(null)
}
val onCreateEvent: (LocalDate, Int?) -> Unit = { date, startMinutes -> openCreate(date, startMinutes, 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, null, longArrayOf(start.toEpochMilliseconds(), end.toEpochMilliseconds()))
openCreate(date.toString(), draftMillis = longArrayOf(start.toEpochMilliseconds(), end.toEpochMilliseconds()))
}
// Edit form (v1.3) — reuses the detail screen's occurrence key; for
@@ -272,25 +241,33 @@ fun CalendarHost(
// falling back to the auto-refreshing calendar is the only honest
// destination.
var editKey by rememberSaveable { mutableStateOf<LongArray?>(null) }
var heldEditKey by remember { mutableStateOf<LongArray?>(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<android.net.Uri?>(null) }
var importForm by remember { mutableStateOf<EventForm?>(null) }
var importUri by rememberSaveable { mutableStateOf<android.net.Uri?>(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<EventForm?, Boolean>(
save = { it != null },
restore = { open -> if (open) importViewModel.currentForm() else null },
),
) { mutableStateOf<EventForm?>(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 remember { mutableIntStateOf(0) }
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<Pair<EventForm, ImportSource>?>(null) }
val importViewModel: EventEditViewModel = hiltViewModel(key = "import")
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
@@ -306,7 +283,7 @@ fun CalendarHost(
importForm = null
if (importFromRequest) {
importFromRequest = false
onExternalFormClosed()
requests.onExternalFormClosed()
}
}
}
@@ -314,7 +291,7 @@ fun CalendarHost(
// 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
@@ -325,41 +302,64 @@ 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) {
if (importForm == null) {
openImportForm(requestedInsertForm, requestedInsertSource, fromRequest = true)
} else {
pendingInsert = requestedInsertForm to requestedInsertSource
val requestedInsert = requests.insert
LaunchedEffect(requestedInsert) {
if (requestedInsert != null) {
if (isReplayOfRestoredImport()) {
requests.insert = null
return@LaunchedEffect
}
onInsertConsumed()
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
importFromRequest = false
if (importFromRequest) {
importFromRequest = false
requests.onExternalFormClosed()
}
pendingInsert = null
importViewModel.reset()
}
@@ -367,21 +367,25 @@ fun CalendarHost(
// 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++
@@ -392,23 +396,19 @@ fun CalendarHost(
// 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
@@ -416,26 +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
heldCreateDraftMillis = null
createDraftMillis = null
onWidgetNavConsumed()
openCreate(req.dateIso ?: currentDate().toString())
requests.nav = null
}
null -> {}
}
@@ -448,23 +441,28 @@ fun CalendarHost(
val eventActions: EventActionsViewModel = hiltViewModel()
val moveOutcome by reschedule.outcome.collectAsStateWithLifecycle()
val selectionFailure by eventActions.failure.collectAsStateWithLifecycle()
val onEditEvent: (EventInstance) -> Unit = { event ->
val key = longArrayOf(
event.eventId,
event.start.toEpochMilliseconds(),
event.end.toEpochMilliseconds(),
)
heldEditKey = key
editKey = key
}
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
val requireWriteOr = rememberWriteGateOr()
// 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<LongArray?>(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)
@@ -472,9 +470,9 @@ fun CalendarHost(
!toEditor -> onOpenDetail(event)
tapContext.canWriteCalendar() -> onEditEvent(event)
tapWriteRefused -> onOpenDetail(event)
else -> requireWriteOr({ onEditEvent(event) }) {
tapWriteRefused = true
onOpenDetail(event)
else -> {
tapAwaitingWrite = event.occurrenceKey()
editAwaitingTap()
}
}
}
@@ -494,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
@@ -696,11 +689,7 @@ fun CalendarHost(
// 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,
@@ -708,23 +697,15 @@ 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
@@ -738,32 +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,
initialDraft = createDraftMillis ?: heldCreateDraftMillis,
onClose = { createDateIso = null },
onSaved = { createDateIso = null },
onManageCalendars = { showCalendars = true },
visible = createDateIso != null,
viewModel = hiltViewModel(key = "create"),
)
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,
@@ -780,23 +757,16 @@ fun CalendarHost(
// below to show why, so open it.
onLoadFailed = {
editKey = null
if (detailKey == null) {
heldKey = key
detailKey = key
}
if (detailKey == null) detailKey = key
},
visible = editKey != null,
viewModel = hiltViewModel(key = "edit"),
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 },
@@ -854,11 +824,7 @@ fun CalendarHost(
// 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 },
@@ -867,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
@@ -910,5 +872,48 @@ private val viewStackSaver = listSaver<List<CalendarView>, 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<CreateRequest?, List<Any?>>(
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?) },
)
@@ -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<LongArray?>(null)
/** A home-screen widget, shortcut or tile navigation (open a date, an event, a view, or create). */
var nav by mutableStateOf<WidgetNavRequest?>(null)
/** An .ics file opened or shared into the app (ACTION_VIEW/SEND). */
var importUri by mutableStateOf<Uri?>(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<InsertRequest?>(null)
/** An external "edit this event" (ACTION_EDIT), in the detail key's shape. */
var editKey by mutableStateOf<LongArray?>(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)
@@ -1,6 +1,5 @@
package de.jeanlucmakiola.calendula.ui
import android.Manifest
import androidx.compose.animation.AnimatedContent
import androidx.compose.animation.fadeIn
import androidx.compose.animation.fadeOut
@@ -23,13 +22,13 @@ 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
import de.jeanlucmakiola.calendula.ui.onboarding.OnboardingViewModel
import de.jeanlucmakiola.calendula.ui.onboarding.onboardingSlideTransition
import de.jeanlucmakiola.calendula.ui.onboarding.rememberOnboardingSlideSpec
import de.jeanlucmakiola.floret.android.hasPermission
import de.jeanlucmakiola.floret.identity.rememberReduceMotion
/** What the root is showing: a wizard step, the app, or neither yet. */
@@ -42,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 = {},
onExternalFormClosed: () -> Unit = {},
requestedEditKey: LongArray? = null,
onEditKeyConsumed: () -> Unit = {},
) {
val context = LocalContext.current
var hasPermission by remember {
mutableStateOf(
context.hasPermission(Manifest.permission.READ_CALENDAR)
)
mutableStateOf(context.canReadCalendar())
}
// A launch scan already covers the app coming up with the permission, so
@@ -72,7 +57,7 @@ fun RootScreen(
DisposableEffect(lifecycle) {
val obs = LifecycleEventObserver { _, event ->
if (event == Lifecycle.Event.ON_RESUME) {
hasPermission = context.hasPermission(Manifest.permission.READ_CALENDAR)
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.
@@ -142,19 +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,
onExternalFormClosed = onExternalFormClosed,
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.
@@ -393,11 +393,8 @@ private fun AgendaList(
val itemDates = agendaItemDates(days)
val anchorRow = itemDates.indexOfFirst { it >= anchor }.coerceAtLeast(0)
SideEffect { anchorIndex.intValue = anchorRow }
// A new anchor opens the list on its row from the first frame, with past
// days above. 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. The first run
// may restore a remembered day instead.
// 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]
@@ -10,6 +10,7 @@ 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
@@ -26,7 +27,6 @@ import kotlinx.coroutines.flow.combine
import kotlinx.coroutines.flow.flatMapLatest
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
@@ -98,21 +98,14 @@ class AgendaViewModel @Inject constructor(
var lastTopDate: LocalDate? = null
private set
private var lastToday = todayDate
/**
* 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<LocalDate> = todaySource.today
.onEach { date ->
val old = lastToday
lastToday = date
if (old != date && _window.value.anchor == old) {
_window.value = _window.value.copy(anchor = date)
}
private val today: StateFlow<LocalDate> =
todaySource.today.stateFollowingDays(viewModelScope, todayDate) { old, date ->
if (_window.value.anchor == old) _window.value = _window.value.copy(anchor = date)
}
.stateWhileSubscribed(viewModelScope, 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
@@ -170,15 +163,17 @@ class AgendaViewModel @Inject constructor(
}
/**
* Extend the window [PAST_CHUNK_DAYS] further back (#367). Ignored while the
* previous extension is still loading, so a scroll that keeps asking only
* moves one chunk at a time.
* 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
_window.value = window.copy(pastDays = window.pastDays + PAST_CHUNK_DAYS)
val step = window.pastDays.coerceIn(PAST_CHUNK_DAYS, MAX_PAST_STEP_DAYS)
_window.value = window.copy(pastDays = window.pastDays + step)
}
fun rememberTopDay(date: LocalDate) {
@@ -240,6 +235,9 @@ 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<Instant> =
dayRange(anchor, anchor.plus(days, DateTimeUnit.DAY), zone)
@@ -26,8 +26,6 @@ import androidx.compose.material3.Text
import androidx.compose.runtime.Composable
import androidx.compose.runtime.Stable
import androidx.compose.runtime.getValue
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.remember
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.graphics.graphicsLayer
@@ -82,8 +80,7 @@ fun CalendarFabColumn(
)
}
// Held past the selection clearing, so the bar has something to fold away.
val heldBar = remember { mutableStateOf<(@Composable () -> Unit)?>(null) }
if (selection != null && heldBar.value !== selection.bar) heldBar.value = selection.bar
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),
@@ -101,7 +98,7 @@ fun CalendarFabColumn(
shrinkTowards = Alignment.End,
) + fadeOut(),
) {
heldBar.value?.invoke()
heldBar?.invoke()
}
val label = stringResource(
when {
@@ -17,6 +17,7 @@ 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
@@ -72,6 +73,10 @@ suspend fun CalendarRepository.deleteEvent(
/** 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)
@@ -96,33 +101,28 @@ suspend fun CalendarRepository.tryDeleteEvent(
}
/**
* Runs an action that writes to the calendar, asking for `WRITE_CALENDAR` first
* where the install only holds read access (v1.0 installs). A grant continues
* straight into the action that asked for it.
* [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 rememberWriteGate(): (() -> Unit) -> Unit {
val gate = rememberWriteGateOr()
return { action -> gate(action) {} }
}
/** [rememberWriteGate], running the fallback instead when the user refuses. */
@Composable
fun rememberWriteGateOr(): (action: () -> Unit, fallback: () -> Unit) -> Unit {
fun rememberWriteAction(onDenied: () -> Unit = {}, action: () -> Unit): () -> Unit {
val context = LocalContext.current
var pending by remember { mutableStateOf<Pair<() -> Unit, () -> Unit>?>(null) }
val currentAction by rememberUpdatedState(action)
val currentDenied by rememberUpdatedState(onDenied)
val launcher = rememberLauncherForActivityResult(
contract = ActivityResultContracts.RequestPermission(),
) { granted ->
pending?.let { (action, fallback) -> if (granted) action() else fallback() }
pending = null
if (granted) currentAction() else currentDenied()
}
return { action, fallback ->
if (context.canWriteCalendar()) {
action()
} else {
pending = action to fallback
launcher.launch(Manifest.permission.WRITE_CALENDAR)
return remember(context, launcher) {
{
if (context.canWriteCalendar()) {
currentAction()
} else {
launcher.launch(Manifest.permission.WRITE_CALENDAR)
}
}
}
}
@@ -7,6 +7,7 @@ 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
@@ -26,7 +27,6 @@ import kotlinx.coroutines.flow.flowOn
import kotlinx.coroutines.flow.map
import kotlinx.coroutines.launch
import kotlinx.coroutines.withContext
import kotlinx.datetime.TimeZone
import kotlin.coroutines.cancellation.CancellationException
import javax.inject.Inject
@@ -42,6 +42,7 @@ 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. */
@@ -64,7 +65,7 @@ class EventActionsViewModel @Inject constructor(
suspend fun duplicateForm(event: EventInstance): EventForm? {
val detail = load(event) ?: return null
val canModify = calendars.value[event.calendarId]?.canModifyContents == true
return detail.toDuplicateForm(canModify, TimeZone.currentSystemDefault())
return detail.toDuplicateForm(canModify, zoneSource.current())
}
/** A staged `.ics` for [event], or null — reported — when it can't be built. */
@@ -32,7 +32,6 @@ fun rememberFabSelection(
val calendars by viewModel.calendars.collectAsStateWithLifecycle()
val context = LocalContext.current
val scope = rememberCoroutineScope()
val requireWrite = rememberWriteGate()
val chooserTitle = stringResource(R.string.event_share_chooser_title)
// What the FAB has been told for this selection, over what the coverage says.
@@ -43,10 +42,28 @@ fun rememberFabSelection(
val currentEdit by rememberUpdatedState(onEdit)
val currentDuplicate by rememberUpdatedState(onDuplicate)
val currentDismissChip by rememberUpdatedState(onDismissChip)
val currentWrite by rememberUpdatedState(requireWrite)
// 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
selection.create?.let { create ->
if (selection.create != null) {
return remember(selection, expanded, chipShown) {
FabSelection(
expanded = expanded,
@@ -56,7 +73,7 @@ fun rememberFabSelection(
},
bar = {
DraftSelectionBar(
onCreate = { currentWrite { create() } },
onCreate = onCreate,
onDiscard = selection.dismiss,
)
},
@@ -78,28 +95,15 @@ fun rememberFabSelection(
EventSelectionBar(
canEdit = canEdit,
canDelete = canDelete,
onEdit = {
currentWrite {
selection.dismiss()
currentEdit(event)
}
},
onDuplicate = {
currentWrite {
scope.launch {
val form = viewModel.duplicateForm(event) ?: return@launch
selection.dismiss()
currentDuplicate(form)
}
}
},
onEdit = onEditSelected,
onDuplicate = onDuplicateSelected,
onShare = {
scope.launch {
val uri = viewModel.shareUri(event) ?: return@launch
if (!context.sendEventShare(uri, chooserTitle)) viewModel.reportShareFailed()
}
},
onDelete = { currentWrite { viewModel.requestDelete(event) } },
onDelete = onDeleteSelected,
)
},
)
@@ -20,7 +20,6 @@ import androidx.compose.runtime.derivedStateOf
import androidx.compose.runtime.getValue
import androidx.compose.runtime.remember
import androidx.compose.ui.graphics.graphicsLayer
import androidx.compose.runtime.mutableStateOf
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.platform.LocalDensity
@@ -111,14 +110,13 @@ fun HourGutter(
}
}
// Held while it fades, so it goes out where it was rather than blinking off.
val badgeMin = remember { mutableStateOf<Int?>(null) }
dragStartMin?.let { badgeMin.value = it }
val badgeMin = rememberHeld(dragStartMin)
val badgeIn by animateFloatAsState(
targetValue = if (dragStartMin != null) 1f else 0f,
animationSpec = MaterialTheme.motionScheme.fastEffectsSpec(),
label = "gutterBadge",
)
badgeMin.value?.takeIf { badgeIn > 0f }?.let { startMin ->
badgeMin?.takeIf { badgeIn > 0f }?.let { startMin ->
val top = (hourHeight * (startMin / 60f) - BADGE_HEIGHT / 2).coerceAtLeast(0.dp)
Box(
modifier = Modifier
@@ -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 <T : Any> rememberHeld(live: T?): T? {
val held = remember { HeldValue<T>() }
if (live != null) held.value = live
return live ?: held.value
}
private class HeldValue<T : Any> {
var value: T? = null
}
@@ -390,17 +390,20 @@ internal fun resizedSpan(
}
if (wrongWay) return startMin to endMin
}
val snapped = (edgeMin / DRAG_SNAP_MINUTES).roundToInt() * DRAG_SNAP_MINUTES
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 (minutes / DRAG_SNAP_MINUTES).roundToInt() * DRAG_SNAP_MINUTES
return snapToSlot(minutes)
}
/** How far past its column's side the finger has to go before a resize changes day. */
@@ -623,25 +626,8 @@ class TimelineDragController {
*/
private var originSlot: Triple<LocalDate, Int, Int>? = null
/** The edge a resize is dragging, or null for a plain drag (#141). */
private var resizeEdge: ResizeEdge? = null
/** The day the resized event starts on; its edges are minutes from that midnight. */
private var resizeDay: LocalDate? = null
private var resizeStartMin = 0
private var resizeEndMin = 0
/** How far the finger sits past the edge it grabbed, so the edge doesn't jump to it. */
private var resizeGrabMin = 0f
/** The column the resized edge is in, held until the finger is well into another. */
private var resizeColumn: Int? = null
/** The slot the resized edge sits on, held against a finger trembling between two. */
private var resizeSlot: Int? = null
/** The day, counted from the event's start day, the finger is resizing in. */
private var resizeEdgeDay = 0
/** The resize in progress, or null for a plain drag (#141). */
private var resize: ResizeSession? = null
fun begin(
block: TimedBlock,
@@ -688,10 +674,7 @@ class TimelineDragController {
}
fun cancel() {
resizeEdge = null
resizeDay = null
resizeColumn = null
resizeSlot = null
resize = null
source = null
clipOffsetMin = 0
dragZone = null
@@ -766,6 +749,12 @@ class TimelineDragController {
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
@@ -775,8 +764,8 @@ class TimelineDragController {
liftedInstanceId = landed.event.instanceId
settledOrigin = landed.event.eventId to landed.event.start
settledAbandonedMark = abandonedTicks?.value ?: 0
settledEnd = end
drops++
return TimelineDrop(landed.event, landed.date, landed.startMin, clipOffset)
}
/**
@@ -791,11 +780,9 @@ class TimelineDragController {
pointerInRoot: Offset,
) {
val span = wallClockSpan(block.event, zone)
val session = ResizeSession(edge, span.day, span.startMin, span.endMin)
source = block
resizeEdge = edge
resizeDay = span.day
resizeStartMin = span.startMin
resizeEndMin = span.endMin
resize = session
clipOffsetMin = 0
this.titleLines = titleLines
settling = null
@@ -804,12 +791,12 @@ class TimelineDragController {
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 (resizeEndMin - 1).floorDiv(MINUTES_PER_DAY).coerceAtLeast(0)
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))
resizeColumn = edgeIndex.takeIf { it >= 0 }
?.let { if (geometry.isRtl) geometry.days.lastIndex - it else it }
resizeGrabMin = (pointerResizeMinutes() ?: 0f) -
if (edge == ResizeEdge.Top) resizeStartMin else resizeEndMin
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
@@ -825,7 +812,7 @@ class TimelineDragController {
fun preview(zone: TimeZone): EventInstance? {
val (date, startMin, spanMin) = landingSlot?.takeIf { it != originSlot } ?: return null
val event = source?.event ?: return null
val edge = resizeEdge
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)
@@ -841,17 +828,11 @@ class TimelineDragController {
fun finishResize(zone: TimeZone): TimelineResizeDrop? {
val landed = drag
val origin = originSlot
val edge = resizeEdge
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)
settlingSelected = selection?.event?.instanceId == landed.event.instanceId
settling = if (landed.edgeOnly) landed.copy(pieces = emptyList()) else landed
liftedInstanceId = landed.event.instanceId
settledOrigin = landed.event.eventId to landed.event.start
settledAbandonedMark = abandonedTicks?.value ?: 0
settledEnd = drop.end
drops++
settle(landed, end = drop.end)
return drop
}
@@ -859,36 +840,33 @@ class TimelineDragController {
* 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(): Float? {
private fun pointerResizeMinutes(session: ResizeSession): Float? {
val grid = geometry.grid?.takeIf { it.isAttached } ?: return null
val day = resizeDay ?: 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 column = stickyColumn(
val held = stickyColumn(
position = (pointer.x - origin.x) / columnPx,
held = resizeColumn,
held = session.column,
lastIndex = days.lastIndex,
)
resizeColumn = column
val dayIndex = if (geometry.isRtl) days.lastIndex - column else column
val dayOffset = (days[dayIndex].toEpochDays() - day.toEpochDays()).toInt()
resizeEdgeDay = dayOffset
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(edge: ResizeEdge) {
private fun recomputeResize(session: ResizeSession) {
val block = source ?: return
val day = resizeDay ?: return
val raw = pointerResizeMinutes() ?: return
val slot = stickySnap(raw - resizeGrabMin, resizeSlot)
resizeSlot = slot
val (start, end) = resizedSpan(edge, resizeStartMin, resizeEndMin, slot.toFloat(), resizeEdgeDay)
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 hourPx = geometry.hourPx
val columnPx = geometry.columnWidthPx
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()
@@ -901,20 +879,7 @@ class TimelineDragController {
eventStartMin = start,
eventSpanMin = end - start,
titleLines = titleLines,
pieces = slices.map { slice ->
val dayIndex = startIndex + slice.dayOffset
val col = if (geometry.isRtl) days.lastIndex - dayIndex else dayIndex
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, startIndex, origin),
edgeOnly = slices.isEmpty(),
markerMin = if (edge == ResizeEdge.Top) {
start.mod(MINUTES_PER_DAY)
@@ -959,7 +924,7 @@ class TimelineDragController {
* no move events while auto-scroll walks the content underneath it.
*/
fun recompute() {
resizeEdge?.let {
resize?.let {
recomputeResize(it)
return
}
@@ -972,10 +937,9 @@ 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 snapped = snapToSlot(rawMinutes)
val zone = dragZone ?: return
val column = ((pointer.x - origin.x) / columnPx).toInt().coerceIn(0, days.lastIndex)
val dayIndex = if (geometry.isRtl) days.lastIndex - column else column
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
@@ -1003,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<DragSlice>, dayIndex: Int, origin: Offset): List<TimelineDragPiece> {
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
@@ -1057,6 +1027,27 @@ 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() }
@@ -84,7 +84,6 @@ import de.jeanlucmakiola.calendula.domain.EventForm
import de.jeanlucmakiola.calendula.domain.EventInstance
import de.jeanlucmakiola.calendula.domain.EventStatus
import de.jeanlucmakiola.calendula.domain.InlineStyle
import de.jeanlucmakiola.calendula.domain.Reminder
import de.jeanlucmakiola.calendula.domain.RichText
import de.jeanlucmakiola.calendula.domain.TimeZoneOption
import de.jeanlucmakiola.calendula.domain.timeZoneOptionOf
@@ -96,7 +95,7 @@ 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.rememberWriteGate
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
@@ -170,14 +169,11 @@ fun EventDetailScreen(
// v1.0 installs only hold READ_CALENDAR; the first write asks for the
// upgrade in place and continues straight into the tapped action.
val requireWrite = rememberWriteGate()
val onDeleteClick = { requireWrite { showDeleteDialog = true } }
val onEditClick = { requireWrite(onEdit) }
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)
@@ -303,7 +299,7 @@ private fun EventDetailContent(
val detail = state.detail
val instance = detail.instance
val dark = LocalFloretDarkTheme.current
val locale = currentDetailLocale()
val locale = currentLocale()
val accent = eventAccent(instance.color, dark, LocalSoftenColors.current)
Column(
@@ -536,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),
)
@@ -683,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
@@ -707,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
@@ -7,6 +7,7 @@ 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.EventForm
import de.jeanlucmakiola.calendula.domain.FailureReason
import de.jeanlucmakiola.calendula.domain.RecurringWriteScope
@@ -31,7 +32,6 @@ import kotlinx.coroutines.flow.flow
import kotlinx.coroutines.flow.flowOf
import kotlinx.coroutines.flow.flowOn
import kotlinx.coroutines.launch
import kotlinx.datetime.TimeZone
import kotlin.coroutines.cancellation.CancellationException
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<Target?>(null)
@@ -141,7 +142,7 @@ class EventDetailViewModel @Inject constructor(
*/
fun duplicateForm(): EventForm? {
val loaded = state.value as? EventDetailUiState.Success ?: return null
return loaded.detail.toDuplicateForm(loaded.canModify, TimeZone.currentSystemDefault())
return loaded.detail.toDuplicateForm(loaded.canModify, zoneSource.current())
}
private suspend fun loadDetail(target: Target): EventDetailUiState = try {
File diff suppressed because it is too large Load Diff
@@ -590,6 +590,9 @@ class EventEditViewModel @Inject constructor(
}
}
/** 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++
@@ -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
@@ -841,7 +841,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
@@ -1627,11 +1627,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
@@ -2098,8 +2098,8 @@ private fun MonthWeekRow(
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
@@ -2283,7 +2283,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,
@@ -2355,19 +2355,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,
@@ -2379,7 +2373,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(
@@ -2395,18 +2389,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,
events = seating.hidden,
day = d,
total = hidden,
dark = dark,
rowHeight = overflowRow,
modifier = Modifier
@@ -2786,7 +2772,6 @@ private fun MonthBar(
private fun OverflowDots(
events: List<EventInstance>,
day: LocalDate,
total: Int,
dark: Boolean,
rowHeight: Dp,
modifier: Modifier = Modifier,
@@ -2808,7 +2793,7 @@ private fun OverflowDots(
.background(eventAccent(argb, dark, soften), CircleShape),
)
}
val extra = total - dots.size
val extra = events.size - dots.size
if (extra > 0) {
Text(
text = "+$extra",
@@ -39,33 +39,55 @@ data class MonthWeek(
val countByDay: Map<LocalDate, Int>,
)
/** 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<Seat>, val hidden: List<EventInstance>)
/**
* 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<Seat>(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<EventInstance> {
val byLane = arrayOfNulls<EventInstance>(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<EventInstance> =
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<EventInst
*/
fun MonthWeek.chipAt(col: Int, lane: Int, laneCap: Int): EventInstance? {
if (col !in days.indices || lane !in 0 until laneCap) return null
spanAt(col, lane)?.let { return it.event }
val occupied = spans
.filter { it.lane < laneCap && col in it.startCol..it.endCol }
.map { it.lane }
.toSet()
val free = (0 until laneCap).filter { it !in occupied }
val index = free.indexOf(lane).takeIf { it >= 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<EventInstance> {
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<EventInstance> = seating(col, laneCap).hidden
/**
* State for the continuous style (#38): a vertical stream of *self-contained*
@@ -10,6 +10,7 @@ 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
@@ -90,16 +91,9 @@ class MonthViewModel @Inject constructor(
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<LocalDate> = todaySource.today
.onEach { date ->
val old = lastToday
lastToday = date
if (old != date) followToday(old, date)
}
.stateWhileSubscribed(viewModelScope, todayDate)
val today: StateFlow<LocalDate> =
todaySource.today.stateFollowingDays(viewModelScope, todayDate, ::followToday)
private val _month = MutableStateFlow(todayDate.yearMonth)
val month: StateFlow<YearMonth> = _month
@@ -1,9 +1,6 @@
package de.jeanlucmakiola.calendula.ui.search
import android.Manifest
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
@@ -59,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
@@ -80,11 +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.android.hasPermission
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
@@ -133,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) }
@@ -155,24 +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 = context.hasPermission(Manifest.permission.WRITE_CALENDAR)
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
@@ -193,7 +172,7 @@ fun SearchScreen(
onBack = onBack,
onCloseSelection = viewModel::clearSelection,
onSelectAll = viewModel::selectAll,
onDelete = { requireWrite { showDeleteDialog = true } },
onDelete = onDeleteClick,
)
},
) { padding ->
@@ -7,6 +7,7 @@ import de.jeanlucmakiola.calendula.data.calendar.CalendarRepository
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
@@ -196,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<Long> =
@@ -7,8 +7,8 @@ import de.jeanlucmakiola.calendula.R
import de.jeanlucmakiola.floret.prefs.ThemeMode
/**
* A synchronous copy of the theme choice, for the window backdrop drawn before
* the first Compose frame. The real setting lives in DataStore, which only
* 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
@@ -18,6 +18,7 @@ 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? =
@@ -25,10 +26,23 @@ internal object WindowThemeCache {
.getString(KEY_THEME_MODE, null)
?.let { name -> ThemeMode.entries.firstOrNull { it.name == name } }
fun write(context: Context, mode: ThemeMode) {
/** 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)
if (prefs.getString(KEY_THEME_MODE, null) == mode.name) return
prefs.edit { putString(KEY_THEME_MODE, mode.name) }
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)
}
}
}
@@ -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) },
)
}
}
@@ -7,100 +7,63 @@ 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
@@ -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
@@ -71,7 +70,7 @@ 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.rememberWriteGate
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
@@ -465,11 +464,12 @@ private fun PagedTimelineScreen(
// 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) }
@@ -516,7 +516,7 @@ private fun PagedTimelineScreen(
onRetry = viewModel::goToToday,
onEventClick = onEventClick,
onOpenDay = onOpenDay,
onCreateAt = { d, minutes -> onCreateEvent(d, minutes) },
onCreateAt = onCreateEvent,
onCreateDraft = onCreateDraft,
draftMinutes = draftMinutes,
modifier = Modifier
@@ -532,7 +532,7 @@ private fun WeekContent(
state: WeekUiState,
today: LocalDate,
pagerState: PagerState,
grid: PageGrid,
grid: DaysGrid,
kind: TimelineKind,
morph: TimelineMorph?,
handoffStrip: Dp?,
@@ -638,16 +638,31 @@ private fun WeekContent(
delay(SELECTION_ORPHAN_GRACE_MILLIS)
dragController.deselect()
}
val requireWrite = rememberWriteGate()
var pendingDraft by remember { mutableStateOf<EventInstance?>(null) }
val createPendingDraft = rememberWriteAction {
pendingDraft?.let(createDraft)
pendingDraft = null
}
val openEvent: (EventInstance) -> Unit = { event ->
if (event.isDraft) {
requireWrite { createDraft(event) }
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
@@ -663,17 +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 = openEvent,
onOpenDay = onOpenDay,
onCreateAt = onCreateAt,
onDrop = onDrop,
onResize = onResize,
)
TimelineMorphFrame(morph = morph, today = today, actions = actions)
} else WeekPager(
pagerState = pagerState,
grid = grid,
@@ -681,13 +686,7 @@ private fun WeekContent(
span = span,
today = today,
initialStripHeight = handoffStrip ?: s.allDayStripHeight(),
scrollState = scrollState,
dragController = dragController,
onEventClick = openEvent,
onOpenDay = onOpenDay,
onCreateAt = onCreateAt,
onDrop = onDrop,
onResize = onResize,
actions = actions,
)
}
}
@@ -703,27 +702,21 @@ private fun WeekContent(
@Composable
private fun WeekPager(
pagerState: PagerState,
grid: PageGrid,
grid: DaysGrid,
kind: TimelineKind,
span: (DaySpan) -> StateFlow<WeekUiState>,
today: LocalDate,
initialStripHeight: Dp,
scrollState: ScrollState,
dragController: TimelineDragController,
onEventClick: (EventInstance) -> Unit,
onOpenDay: (LocalDate) -> Unit,
onCreateAt: (LocalDate, Int) -> Unit,
onDrop: (TimelineDrop) -> Unit,
onResize: (TimelineResizeDrop) -> Unit,
actions: TimelineActions,
) {
val dragController = actions.dragController
val stripHeights = remember { mutableStateMapOf<Int, Dp>() }
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,
@@ -756,14 +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,
onResize = onResize,
)
}
}
@@ -792,13 +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,
onResize: (TimelineResizeDrop) -> Unit,
actions: TimelineActions,
) {
val fromState by morph.fromState.collectAsStateWithLifecycle()
val toState by morph.toState.collectAsStateWithLifecycle()
@@ -836,8 +817,7 @@ private fun TimelineMorphFrame(
allDayHeight = fromStrip,
animatedAllDayHeight = animatedStrip,
weekNumberAlpha = badgeAlpha,
scrollState = scrollState,
dragController = dragController,
actions = actions,
) {
TimelinePageContent(
geometry = geometry,
@@ -847,14 +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,
onResize = onResize,
)
}
}
@@ -888,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) }
@@ -923,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),
)
}
}
@@ -941,34 +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,
onResize: (TimelineResizeDrop) -> 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,
onResize = onResize,
)
}
}
@@ -984,14 +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,
onResize: (TimelineResizeDrop) -> Unit,
) {
val geometry = remember(state.weekStart, state.days.size) {
ColumnGeometry.of(DaySpan(state.weekStart, state.days.size))
@@ -1004,14 +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,
onResize = onResize,
)
}
@@ -1028,14 +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,
onResize: (TimelineResizeDrop) -> Unit,
) {
Column(modifier = Modifier.fillMaxSize()) {
Column(
@@ -1043,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))
@@ -1060,13 +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,
onResize = onResize,
)
}
}
@@ -1290,14 +1227,11 @@ private fun Timeline(
timedFor: (LocalDate) -> List<TimedBlock>,
allDayHeight: Dp,
animatedAllDayHeight: (() -> Dp)? = null,
scrollState: ScrollState,
dragController: TimelineDragController,
actions: TimelineActions,
active: Boolean,
onEventClick: (EventInstance) -> Unit,
onCreateAt: (LocalDate, Int) -> Unit,
onDrop: (TimelineDrop) -> Unit,
onResize: (TimelineResizeDrop) -> Unit,
) {
val scrollState = actions.scrollState
val dragController = actions.dragController
val fullViewportHeight = remember(geometry) { intArrayOf(-1) }
val dark = LocalFloretDarkTheme.current
val zoom = LocalTimelineZoom.current
@@ -1390,12 +1324,7 @@ private fun Timeline(
columnWidth = columnWidth,
visibleTop = visibleTop,
viewportHeight = visibleViewport,
dragController = dragController,
onEventClick = onEventClick,
onCreateAt = onCreateAt,
onDrop = onDrop,
onResize = onResize,
scrollState = scrollState,
actions = actions,
modifier = Modifier.fillMaxHeight(),
)
}
@@ -1413,14 +1342,11 @@ private fun DayColumnCard(
columnWidth: Dp,
visibleTop: () -> Float,
viewportHeight: () -> Float,
dragController: TimelineDragController,
onEventClick: (EventInstance) -> Unit,
onCreateAt: (LocalDate, Int) -> Unit,
onDrop: (TimelineDrop) -> Unit,
onResize: (TimelineResizeDrop) -> 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
@@ -1438,13 +1364,13 @@ private fun DayColumnCard(
}
// 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, onDrop)
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.
@@ -1478,7 +1404,7 @@ private fun DayColumnCard(
return@detectTapGestures
}
if (currentEdges.value.tap(offset.y)) return@detectTapGestures
currentOnCreateAt.value(
actions.onCreateAt(
date,
tappedMinuteOfDay(offset.y, currentHourPx.value),
)
@@ -1538,9 +1464,9 @@ private fun DayColumnCard(
cuts = cuts,
topInset = topInset,
dragController = dragController,
onClick = { onEventClick(block.event) },
onDrop = onDrop,
onResize = onResize,
onClick = { actions.onEventClick(block.event) },
onDrop = actions.onDrop,
onResize = actions.onResize,
modifier = Modifier
.laneSlot(place)
.offset(y = place.y + topInset)
@@ -10,6 +10,7 @@ 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
@@ -32,7 +33,6 @@ 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
@@ -62,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)) }
/**
@@ -84,8 +84,8 @@ abstract class PagedTimelineViewModel(
todaySource: TodaySource,
zoneSource: ZoneSource,
private val io: CoroutineDispatcher,
gridRule: Flow<(LocalDate) -> PageGrid>,
initialRule: (LocalDate) -> PageGrid,
gridRule: Flow<(LocalDate) -> DaysGrid>,
initialRule: (LocalDate) -> DaysGrid,
) : ViewModel() {
/**
@@ -121,19 +121,12 @@ 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<LocalDate> = todaySource.today
.onEach { date ->
val old = lastToday
lastToday = date
if (old != date) followToday(old, date)
}
.stateWhileSubscribed(viewModelScope, todayDate)
private val today: StateFlow<LocalDate> =
todaySource.today.stateFollowingDays(viewModelScope, todayDate, ::followToday)
private val position: StateFlow<PagerPosition> =
combine(_anchor, rule) { anchor, rule -> positionOf(anchor, rule) }
@@ -240,11 +233,11 @@ class WeekViewModel @Inject constructor(
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) },
)
/**
@@ -285,8 +278,8 @@ class DayViewModel @Inject constructor(
todaySource = todaySource,
zoneSource = zoneSource,
io = io,
gridRule = flowOf { _: LocalDate -> DayGrid },
initialRule = { DayGrid },
gridRule = flowOf { _: LocalDate -> DaysGrid.days },
initialRule = { DaysGrid.days },
)
/**
@@ -52,14 +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 = {},
onResize = {},
actions = rememberTimelineActions(
scrollState = scrollState,
dragController = rememberTimelineDragController(),
onEventClick = {},
onOpenDay = {},
onCreateAt = { _, _ -> },
onDrop = {},
onResize = {},
),
)
}
}
@@ -19,6 +19,12 @@ class HtmlTextTest {
assertThat(looksLikeHtml("See <a href=\"https://x.y\">here</a>")).isTrue()
}
@Test
fun `angle-bracketed links and addresses stay text`() {
val html = "Join<br>here <https://teams.microsoft.com/l/x> or <a@b.c>"
assertThat(parseHtml(html).text).isEqualTo("Join\nhere <https://teams.microsoft.com/l/x> or <a@b.c>")
}
@Test
fun `plain text passes through untouched`() {
val text = " Agenda:\n\n\n- one \n- two"
@@ -18,6 +18,14 @@ class IcsRecurrenceTest {
assertThat(sanitizeRrule("RRULE:FREQ=DAILY").rule).isEqualTo("FREQ=DAILY")
}
@Test
fun `part names and the prefix are matched case-insensitively`() {
val result = sanitizeRrule("rrule:freq=weekly;byday=mo")
assertThat(result.rule).isEqualTo("FREQ=WEEKLY;BYDAY=MO")
assertThat(result.repaired).isFalse()
}
@Test
fun `an empty list part is dropped`() {
val bareByDay = sanitizeRrule("FREQ=WEEKLY;INTERVAL=1;BYDAY=")
@@ -5,6 +5,7 @@ import com.google.common.truth.Truth.assertThat
import de.jeanlucmakiola.calendula.MainDispatcherExtension
import de.jeanlucmakiola.calendula.data.calendar.FakeCalendarDataSource
import de.jeanlucmakiola.calendula.data.ics.IcsExporter
import de.jeanlucmakiola.calendula.data.time.FakeZoneSource
import de.jeanlucmakiola.calendula.domain.CalendarSource
import de.jeanlucmakiola.calendula.testDetail
import de.jeanlucmakiola.calendula.testEvent
@@ -56,7 +57,7 @@ class EventDetailViewModelTest {
settings = testSettings(tempDir, CoroutineScope(dispatcher)),
)
// Only `shareUri()` touches the exporter, and nothing here shares.
return EventDetailViewModel(repo, IcsExporter(ContextWrapper(null)), dispatcher)
return EventDetailViewModel(repo, IcsExporter(ContextWrapper(null)), dispatcher, FakeZoneSource())
}
private fun fakeSource(description: () -> String?) = FakeCalendarDataSource().apply {
@@ -37,7 +37,7 @@ class LaneEventsTest {
val week = rowOfJuly6(listOf(bar, meeting))
// Jul 7 is column 1 of a Monday-anchored row starting Jul 6.
assertThat(week.laneEvents(col = 1, day = LocalDate(2026, 7, 7), laneCap = 3))
assertThat(week.laneEvents(col = 1, laneCap = 3))
.containsExactly(bar, meeting)
.inOrder()
}
@@ -48,7 +48,7 @@ class LaneEventsTest {
val monday = timed(LocalDate(2026, 7, 6), hour = 9, id = 2L)
val week = rowOfJuly6(listOf(bar, monday))
assertThat(week.laneEvents(col = 0, day = LocalDate(2026, 7, 6), laneCap = 3))
assertThat(week.laneEvents(col = 0, laneCap = 3))
.containsExactly(monday)
}
@@ -58,10 +58,9 @@ class LaneEventsTest {
val week = rowOfJuly6(listOf(bar))
(1..3).forEach { col ->
val day = LocalDate(2026, 7, 6 + col)
assertThat(week.laneEvents(col, day, laneCap = 3)).containsExactly(bar)
assertThat(week.laneEvents(col, laneCap = 3)).containsExactly(bar)
}
assertThat(week.laneEvents(col = 4, day = LocalDate(2026, 7, 10), laneCap = 3)).isEmpty()
assertThat(week.laneEvents(col = 4, laneCap = 3)).isEmpty()
}
/** The bug the colour-gathered dots had: one dot for two events on one calendar. */
@@ -71,7 +70,7 @@ class LaneEventsTest {
val second = timed(LocalDate(2026, 7, 6), hour = 14, id = 2L, color = RED)
val week = rowOfJuly6(listOf(first, second))
assertThat(week.laneEvents(col = 0, day = LocalDate(2026, 7, 6), laneCap = 3))
assertThat(week.laneEvents(col = 0, laneCap = 3))
.containsExactly(first, second)
.inOrder()
}
@@ -81,7 +80,7 @@ class LaneEventsTest {
val events = (0 until 5).map { timed(LocalDate(2026, 7, 6), hour = 8 + it, id = it + 1L) }
val week = rowOfJuly6(events)
val seated = week.laneEvents(col = 0, day = LocalDate(2026, 7, 6), laneCap = 3)
val seated = week.laneEvents(col = 0, laneCap = 3)
assertThat(seated).hasSize(3)
assertThat(seated).containsExactlyElementsIn(events.take(3)).inOrder()
assertThat(week.countByDay[LocalDate(2026, 7, 6)]!! - seated.size).isEqualTo(2)
@@ -95,7 +94,7 @@ class LaneEventsTest {
}
val week = rowOfJuly6(bars)
val seated = week.laneEvents(col = 0, day = LocalDate(2026, 7, 6), laneCap = 3)
val seated = week.laneEvents(col = 0, laneCap = 3)
assertThat(seated).hasSize(3)
assertThat(week.spans.filter { it.lane >= 3 }.map { it.event })
.containsNoneIn(seated)
@@ -105,14 +104,13 @@ class LaneEventsTest {
fun `overflow is exactly what seating left behind`() {
val events = (0 until 5).map { timed(LocalDate(2026, 7, 6), hour = 8 + it, id = it + 1L) }
val week = rowOfJuly6(events)
val day = LocalDate(2026, 7, 6)
val seated = week.laneEvents(col = 0, day = day, laneCap = 3)
val overflow = week.overflowEvents(col = 0, day = day, laneCap = 3)
val seated = week.laneEvents(col = 0, laneCap = 3)
val overflow = week.overflowEvents(col = 0, laneCap = 3)
assertThat(overflow).containsExactlyElementsIn(events.drop(3)).inOrder()
assertThat(seated + overflow).containsExactlyElementsIn(events)
assertThat(seated.size + overflow.size).isEqualTo(week.countByDay[day])
assertThat(seated.size + overflow.size).isEqualTo(week.countByDay[LocalDate(2026, 7, 6)])
}
@Test
@@ -124,8 +122,7 @@ class LaneEventsTest {
val parked = week.spans.filter { it.lane >= 3 }.map { it.event }
(0..2).forEach { col ->
val day = LocalDate(2026, 7, 6 + col)
assertThat(week.overflowEvents(col, day, laneCap = 3))
assertThat(week.overflowEvents(col, laneCap = 3))
.containsExactlyElementsIn(parked)
}
}
@@ -134,7 +131,7 @@ class LaneEventsTest {
fun `a day that fits has no overflow`() {
val week = rowOfJuly6(listOf(timed(LocalDate(2026, 7, 6), hour = 9, id = 1L)))
assertThat(week.overflowEvents(col = 0, day = LocalDate(2026, 7, 6), laneCap = 3)).isEmpty()
assertThat(week.overflowEvents(col = 0, laneCap = 3)).isEmpty()
}
private companion object {
@@ -0,0 +1,170 @@
package de.jeanlucmakiola.calendula.ui.month
import com.google.common.truth.Truth.assertWithMessage
import de.jeanlucmakiola.calendula.domain.EventInstance
import de.jeanlucmakiola.calendula.domain.EventResponse
import de.jeanlucmakiola.calendula.testEvent
import kotlinx.datetime.DateTimeUnit
import kotlinx.datetime.LocalDate
import kotlinx.datetime.TimeZone
import kotlinx.datetime.YearMonth
import kotlinx.datetime.atTime
import kotlinx.datetime.plus
import kotlinx.datetime.toInstant
import org.junit.jupiter.api.Test
import kotlin.random.Random
import kotlin.time.Duration.Companion.minutes
/**
* The month row's seating — which event sits in which lane of a day, and which
* fall to the overflow — is read in four places: the bars and pills a row draws,
* the split style's dots ([laneEvents]), the hit test ([chipAt]) and the overflow
* ([overflowEvents]). They must agree for dot _i_ to morph into lane _i_ (#53).
*
* The references below are the four copies as they were before they shared one
* implementation, the row's taken from its composable; this pins the shared one
* to all of them across a spread of generated weeks.
*/
class MonthSeatingTest {
private val zone = TimeZone.of("Europe/Berlin")
private val firstMonday = LocalDate(2026, 3, 23)
private var overflowed = 0
private var stackedBars = 0
@Test
fun `every reader of a week sees the same seating`() {
val random = Random(53)
repeat(400) { round ->
val start = firstMonday.plus(round % 9, DateTimeUnit.WEEK)
val days = (0 until 7).map { start.plus(it, DateTimeUnit.DAY) }
val events = randomEvents(random, start, count = random.nextInt(0, 14))
val laid = layoutCalendarWeek(days, events, zone)
val weeks = listOf(laid, clipWeekToMonth(laid, YearMonth(days[3].year, days[3].month)))
weeks.forEach { week ->
for (laneCap in 0..6) checkWeek(week, laneCap, "round $round, laneCap $laneCap")
if (week.spans.any { it.lane > 0 }) stackedBars++
}
}
assertWithMessage("generated days with overflow").that(overflowed).isGreaterThan(500)
assertWithMessage("generated weeks with stacked bars").that(stackedBars).isGreaterThan(100)
}
private fun checkWeek(week: MonthWeek, laneCap: Int, label: String) {
week.days.forEachIndexed { col, day ->
val where = "$label, col $col"
val row = rowSeating(week, col, day, laneCap)
val dots = refLaneEvents(week, col, day, laneCap)
val hits = (0 until laneCap).mapNotNull { lane -> refChipAt(week, col, lane, laneCap)?.let { lane to it } }
val overflow = refOverflowEvents(week, col, day, laneCap)
if (overflow.isNotEmpty()) overflowed++
assertWithMessage("$where: hit test vs row").that(hits).isEqualTo(row.seated)
assertWithMessage("$where: dots vs row").that(dots).isEqualTo(row.seated.map { it.second })
assertWithMessage("$where: overflow vs row").that(overflow).isEqualTo(row.hiddenEvents)
assertWithMessage("$where: dot count vs hidden list")
.that(row.hiddenCount.coerceAtLeast(0)).isEqualTo(row.hiddenEvents.size)
assertWithMessage("$where: laneEvents").that(week.laneEvents(col, laneCap)).isEqualTo(dots)
assertWithMessage("$where: overflowEvents").that(week.overflowEvents(col, laneCap)).isEqualTo(overflow)
(-1..laneCap).forEach { lane ->
assertWithMessage("$where: chipAt lane $lane")
.that(week.chipAt(col, lane, laneCap))
.isEqualTo(refChipAt(week, col, lane, laneCap))
}
val seating = week.seating(col, laneCap)
assertWithMessage("$where: seating lanes")
.that(seating.seated.map { it.lane to it.event }).isEqualTo(row.seated)
assertWithMessage("$where: seating hidden").that(seating.hidden).isEqualTo(row.hiddenEvents)
}
}
private fun randomEvents(random: Random, weekStart: LocalDate, count: Int): List<EventInstance> =
(1..count).map { n ->
val id = n.toLong()
val day = weekStart.plus(random.nextInt(-4, 10), DateTimeUnit.DAY)
val response = if (random.nextInt(6) == 0) EventResponse.Declined else EventResponse.Going
when (random.nextInt(5)) {
0, 1 -> {
val from = day.atTime(0, 0).toInstant(TimeZone.UTC)
val to = day.plus(random.nextInt(1, 10), DateTimeUnit.DAY).atTime(0, 0).toInstant(TimeZone.UTC)
testEvent(id = id, title = "A$id", start = from, end = to, isAllDay = true, response = response)
}
2 -> {
// Crosses midnight, sometimes ending on it exactly.
val from = day.atTime(random.nextInt(18, 24), 0).toInstant(zone)
val to = from + (random.nextInt(1, 60) * 30).minutes
testEvent(id = id, title = "M$id", start = from, end = to, response = response)
}
else -> {
val from = day.atTime(random.nextInt(0, 23), random.nextInt(0, 4) * 15).toInstant(zone)
val length = if (random.nextInt(8) == 0) 0 else random.nextInt(1, 8) * 15
testEvent(id = id, title = "T$id", start = from, end = from + length.minutes, response = response)
}
}
}
private class RowSeating(
val seated: List<Pair<Int, EventInstance>>,
val hiddenEvents: List<EventInstance>,
val hiddenCount: Int,
)
/** MonthWeekRow's bars, pills and overflow dots, as the composable worked them out. */
private fun rowSeating(week: MonthWeek, col: Int, d: LocalDate, laneCap: Int): RowSeating {
val laneCount = (week.spans.maxOfOrNull { it.lane } ?: -1) + 1
val shownLanes = laneCount.coerceAtMost(laneCap)
val bars = week.spans
.filter { it.lane < shownLanes && col in it.startCol..it.endCol }
.map { it.lane to it.event }
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)
val pills = pillsShown.mapIndexed { i, ev -> freeSlots[i] to ev }
val hidden = (week.countByDay[d] ?: 0) - occupied.size - pillsShown.size
val hiddenEvents = buildList {
week.spans
.filter { it.lane >= shownLanes && col in it.startCol..it.endCol }
.forEach { add(it.event) }
addAll(timed.drop(pillsShown.size))
}
return RowSeating((bars + pills).sortedBy { it.first }, hiddenEvents, hidden)
}
private fun refLaneEvents(week: MonthWeek, col: Int, day: LocalDate, laneCap: Int): List<EventInstance> {
val byLane = arrayOfNulls<EventInstance>(laneCap)
week.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 }
week.timedByDay[day].orEmpty().take(free.size).forEachIndexed { i, event -> byLane[free[i]] = event }
return byLane.filterNotNull()
}
private fun refChipAt(week: MonthWeek, col: Int, lane: Int, laneCap: Int): EventInstance? {
if (col !in week.days.indices || lane !in 0 until laneCap) return null
week.spans.firstOrNull { it.lane == lane && col in it.startCol..it.endCol }?.let { return it.event }
val occupied = week.spans
.filter { it.lane < laneCap && col in it.startCol..it.endCol }
.map { it.lane }
.toSet()
val free = (0 until laneCap).filter { it !in occupied }
val index = free.indexOf(lane).takeIf { it >= 0 } ?: return null
return week.timedByDay[week.days[col]].orEmpty().take(free.size).getOrNull(index)
}
private fun refOverflowEvents(week: MonthWeek, col: Int, day: LocalDate, laneCap: Int): List<EventInstance> {
val seatedLanes = week.spans.count { it.lane < laneCap && col in it.startCol..it.endCol }
return buildList {
week.spans.forEach { span ->
if (span.lane >= laneCap && col in span.startCol..span.endCol) add(span.event)
}
addAll(week.timedByDay[day].orEmpty().drop(laneCap - seatedLanes))
}
}
}
@@ -13,13 +13,13 @@ class FocusOnPageTest {
@Test
fun `a page that still shows the focus keeps it`() {
val grid = WeekGrid(DayOfWeek.MONDAY)
val grid = DaysGrid.weeks(DayOfWeek.MONDAY)
assertThat(grid.focusOnPage(wednesday, grid.pageFor(wednesday))).isEqualTo(wednesday)
}
@Test
fun `a week on keeps the weekday`() {
val grid = WeekGrid(DayOfWeek.MONDAY)
val grid = DaysGrid.weeks(DayOfWeek.MONDAY)
val page = grid.pageFor(wednesday)
assertThat(grid.focusOnPage(wednesday, page + 1)).isEqualTo(LocalDate(2026, 10, 7))
assertThat(grid.focusOnPage(wednesday, page - 2)).isEqualTo(LocalDate(2026, 9, 16))
@@ -34,7 +34,7 @@ class FocusOnPageTest {
@Test
fun `a day page is the focus`() {
val page = DayGrid.pageFor(wednesday)
assertThat(DayGrid.focusOnPage(wednesday, page + 5)).isEqualTo(LocalDate(2026, 10, 5))
val page = DaysGrid.days.pageFor(wednesday)
assertThat(DaysGrid.days.focusOnPage(wednesday, page + 5)).isEqualTo(LocalDate(2026, 10, 5))
}
}
@@ -0,0 +1,137 @@
package de.jeanlucmakiola.calendula.ui.week
import com.google.common.truth.Truth.assertThat
import kotlinx.datetime.DateTimeUnit
import kotlinx.datetime.DayOfWeek
import kotlinx.datetime.LocalDate
import kotlinx.datetime.daysUntil
import kotlinx.datetime.minus
import kotlinx.datetime.plus
import org.junit.jupiter.api.Test
/**
* Pins each grid's page numbering to the formulas it shipped with: a pager
* restores its page by number, so a change here moves the user to another date.
*/
class PageNumberingTest {
private val dates: List<LocalDate> = buildList {
var d = LocalDate(1500, 1, 1)
while (d < LocalDate(2500, 1, 1)) {
add(d)
d = d.plus(37, DateTimeUnit.DAY)
}
var e = LocalDate(1999, 12, 1)
while (e < LocalDate(2000, 2, 1)) {
add(e)
e = e.plus(1, DateTimeUnit.DAY)
}
}
private fun pages(count: Int): List<Int> =
listOf(-7, -1, 0, 1, count / 2 - 3, count / 2 - 1, count / 2, count / 2 + 1, count - 2, count - 1, count, count + 5) +
(0 until count step 997)
@Test
fun `week pages keep their numbering for every first day`() {
DayOfWeek.entries.forEach { firstDay ->
val grid = DaysGrid.weeks(firstDay)
assertThat(grid.dayCount).isEqualTo(7)
assertThat(grid.pageCount).isEqualTo(LEGACY_WEEK_COUNT)
pages(LEGACY_WEEK_COUNT).forEach { page ->
assertThat(grid.startForPage(page)).isEqualTo(legacyWeekStart(page, firstDay))
}
dates.forEach { date ->
assertThat(grid.pageFor(date)).isEqualTo(legacyWeekPage(date, firstDay))
}
}
}
@Test
fun `multi-day pages keep their numbering for every count and phase`() {
(1..7).forEach { count ->
(-count..count * 2).forEach { phase ->
val grid = DaysGrid(count, phase)
assertThat(grid.pageCount).isEqualTo(LEGACY_DAYS_COUNT)
pages(LEGACY_DAYS_COUNT).forEach { page ->
assertThat(grid.startForPage(page)).isEqualTo(legacyDaysStart(page, count, phase))
}
dates.forEach { date ->
assertThat(grid.pageFor(date)).isEqualTo(legacyDaysPage(date, count, phase))
}
}
dates.filter { it.year in 1950..2050 }.forEach { date ->
val grid = DaysGrid.startingAt(date, count)
assertThat(grid.startForPage(grid.pageFor(date))).isEqualTo(date)
}
}
}
@Test
fun `day pages keep their numbering`() {
val grid = DaysGrid.days
assertThat(grid.dayCount).isEqualTo(1)
assertThat(grid.pageCount).isEqualTo(LEGACY_DAY_COUNT)
pages(LEGACY_DAY_COUNT).forEach { page ->
assertThat(grid.startForPage(page)).isEqualTo(legacyDayStart(page))
}
dates.forEach { date ->
assertThat(grid.pageFor(date)).isEqualTo(legacyDayPage(date))
}
}
@Test
fun `a multi-day jump re-frames exactly when the date would open mid-page`() {
val inRange = dates.filter { it.year in 1950..2050 }
(3..6).forEach { count ->
val grid = DaysGrid.startingAt(LocalDate(2026, 10, 16), count)
inRange.forEach { target ->
val midPage = grid.startForPage(grid.pageFor(target)) != target
assertThat(DaysGrid.startingAt(target, count) != grid).isEqualTo(midPage)
}
}
}
@Test
fun `grids are equal exactly when they page the same way`() {
assertThat(DaysGrid.weeks(DayOfWeek.MONDAY)).isEqualTo(DaysGrid.weeks(DayOfWeek.MONDAY))
assertThat(DaysGrid.weeks(DayOfWeek.MONDAY)).isNotEqualTo(DaysGrid.weeks(DayOfWeek.SUNDAY))
assertThat(DaysGrid(3, 1)).isEqualTo(DaysGrid(3, 1))
assertThat(DaysGrid(3, 1)).isNotEqualTo(DaysGrid(3, 2))
assertThat(DaysGrid(3, 1)).isNotEqualTo(DaysGrid(4, 1))
assertThat(DaysGrid.days).isEqualTo(DaysGrid.days)
assertThat(DaysGrid.days.hashCode()).isEqualTo(DaysGrid.days.hashCode())
}
private companion object {
const val LEGACY_WEEK_COUNT = 20_000
const val LEGACY_DAYS_COUNT = 40_000
const val LEGACY_DAY_COUNT = 140_000
val WEEK_EPOCH = LocalDate(2000, 1, 3)
val DAYS_EPOCH = LocalDate(2000, 1, 1)
fun LocalDate.weekStart(firstDay: DayOfWeek): LocalDate =
minus(((dayOfWeek.ordinal - firstDay.ordinal) + 7) % 7, DateTimeUnit.DAY)
fun legacyWeekStart(page: Int, firstDay: DayOfWeek): LocalDate =
WEEK_EPOCH.weekStart(firstDay).plus((page - LEGACY_WEEK_COUNT / 2) * 7, DateTimeUnit.DAY)
fun legacyWeekPage(date: LocalDate, firstDay: DayOfWeek): Int {
val days = WEEK_EPOCH.weekStart(firstDay).daysUntil(date.weekStart(firstDay))
return (LEGACY_WEEK_COUNT / 2 + days / 7).coerceIn(0, LEGACY_WEEK_COUNT - 1)
}
fun legacyDaysStart(page: Int, count: Int, phase: Int): LocalDate =
DAYS_EPOCH.plus(phase + (page - LEGACY_DAYS_COUNT / 2) * count, DateTimeUnit.DAY)
fun legacyDaysPage(date: LocalDate, count: Int, phase: Int): Int =
(LEGACY_DAYS_COUNT / 2 + Math.floorDiv(DAYS_EPOCH.daysUntil(date) - phase, count))
.coerceIn(0, LEGACY_DAYS_COUNT - 1)
fun legacyDayStart(page: Int): LocalDate =
DAYS_EPOCH.plus(page - LEGACY_DAY_COUNT / 2, DateTimeUnit.DAY)
fun legacyDayPage(date: LocalDate): Int =
(LEGACY_DAY_COUNT / 2 + DAYS_EPOCH.daysUntil(date)).coerceIn(0, LEGACY_DAY_COUNT - 1)
}
}
@@ -16,34 +16,34 @@ class WeekPagingTest {
@Test
fun `a page and its week round-trip for every first day`() {
DayOfWeek.entries.forEach { firstDay ->
val page = weekPageFor(sunday, firstDay)
val start = weekStartForPage(page, firstDay)
val page = DaysGrid.weeks(firstDay).pageFor(sunday)
val start = DaysGrid.weeks(firstDay).startForPage(page)
assertThat(start).isEqualTo(sunday.startOfWeek(firstDay))
assertThat(weekPageFor(start, firstDay)).isEqualTo(page)
assertThat(DaysGrid.weeks(firstDay).pageFor(start)).isEqualTo(page)
}
}
@Test
fun `every day of a week maps to the same page`() {
val start = sunday.startOfWeek(DayOfWeek.MONDAY)
val pages = (0..6).map { weekPageFor(start.plus(it, DateTimeUnit.DAY), DayOfWeek.MONDAY) }
val pages = (0..6).map { DaysGrid.weeks(DayOfWeek.MONDAY).pageFor(start.plus(it, DateTimeUnit.DAY)) }
assertThat(pages.toSet()).hasSize(1)
}
@Test
fun `adjacent pages are adjacent weeks`() {
val page = weekPageFor(sunday, DayOfWeek.SUNDAY)
assertThat(weekStartForPage(page + 1, DayOfWeek.SUNDAY))
val page = DaysGrid.weeks(DayOfWeek.SUNDAY).pageFor(sunday)
assertThat(DaysGrid.weeks(DayOfWeek.SUNDAY).startForPage(page + 1))
.isEqualTo(LocalDate(2026, 10, 4))
assertThat(weekStartForPage(page - 1, DayOfWeek.SUNDAY))
assertThat(DaysGrid.weeks(DayOfWeek.SUNDAY).startForPage(page - 1))
.isEqualTo(LocalDate(2026, 9, 20))
}
@Test
fun `dates before the epoch page resolve too`() {
val old = LocalDate(1990, 5, 16)
val page = weekPageFor(old, DayOfWeek.MONDAY)
assertThat(weekStartForPage(page, DayOfWeek.MONDAY)).isEqualTo(LocalDate(1990, 5, 14))
val page = DaysGrid.weeks(DayOfWeek.MONDAY).pageFor(old)
assertThat(DaysGrid.weeks(DayOfWeek.MONDAY).startForPage(page)).isEqualTo(LocalDate(1990, 5, 14))
}
@Test
@@ -69,14 +69,14 @@ class WeekPagingTest {
@Test
fun `a day page and its day round-trip`() {
listOf(LocalDate(2026, 9, 27), LocalDate(1990, 5, 16), LocalDate(2100, 2, 28)).forEach { day ->
assertThat(DayGrid.startForPage(DayGrid.pageFor(day))).isEqualTo(day)
assertThat(DaysGrid.days.startForPage(DaysGrid.days.pageFor(day))).isEqualTo(day)
}
}
@Test
fun `adjacent day pages are adjacent days across a month end`() {
val page = DayGrid.pageFor(LocalDate(2026, 2, 28))
assertThat(DayGrid.startForPage(page + 1)).isEqualTo(LocalDate(2026, 3, 1))
assertThat(DayGrid.startForPage(page - 1)).isEqualTo(LocalDate(2026, 2, 27))
val page = DaysGrid.days.pageFor(LocalDate(2026, 2, 28))
assertThat(DaysGrid.days.startForPage(page + 1)).isEqualTo(LocalDate(2026, 3, 1))
assertThat(DaysGrid.days.startForPage(page - 1)).isEqualTo(LocalDate(2026, 2, 27))
}
}