Compare commits
38
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
2d9b38abb6 | ||
|
|
459432d065 | ||
|
|
8987573295 | ||
|
|
1807f228e7 | ||
|
|
b794c35d8e | ||
|
|
43ef4027f5 | ||
|
|
2a55bc3baa | ||
|
|
14c10c6d0b | ||
|
|
f5e28eae8d | ||
|
|
b6cec2f95e | ||
|
|
d012948de6 | ||
|
|
8ff8a2de1f | ||
|
|
3f81bb9ea5 | ||
|
|
a08ad15c4a | ||
|
|
c9cc40ff60 | ||
|
|
343a8904ea | ||
|
|
075940d29e | ||
|
|
670cdb226a | ||
|
|
a8da8bc7a3 | ||
|
|
cfcba283f1 | ||
|
|
85d4dc535c | ||
|
|
edf80fe8b8 | ||
|
|
0ecd6de27b | ||
|
|
610409012f | ||
|
|
7e45656479 | ||
|
|
94b04c1365 | ||
|
|
d1557825c6 | ||
|
|
d43a741c93 | ||
|
|
6da0648b77 | ||
|
|
3b48987ab7 | ||
|
|
04a677dc10 | ||
|
|
46ca2db63a | ||
|
|
a87ebc33b6 | ||
|
|
3471447ab6 | ||
|
|
b206e0e6a5 | ||
|
|
35f5dc1666 | ||
|
|
225901ceee | ||
|
|
77e103c66c |
No files matched your search
@@ -33,7 +33,7 @@ jobs:
|
||||
# directly drops the docker-in-docker requirement entirely.
|
||||
# Full tag pinned; Renovate's github-actions manager keeps it bumped.
|
||||
container:
|
||||
image: ghcr.io/renovatebot/renovate:44.237.3
|
||||
image: ghcr.io/renovatebot/renovate:43.232.0
|
||||
steps:
|
||||
- name: Run Renovate
|
||||
run: renovate
|
||||
|
||||
@@ -7,41 +7,10 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0
|
||||
|
||||
## [Unreleased]
|
||||
|
||||
## [2.24.2] — 2026-11-13
|
||||
|
||||
### Fixed
|
||||
- **Quick moves no longer get lost.** Dropping an event while an earlier move was still saving used to snap it back without a word. Drops now wait in line and are saved in order, and a moved event stays where you dropped it until the calendar shows it there. If an event changed before a drop could be saved, or the line is full, a message says so instead ([#494]).
|
||||
- **Undo after a run of moves** keeps the first move's Undo, and each failed move gets its own message rather than replacing the last one ([#494]).
|
||||
|
||||
### Changed
|
||||
- **The day view's title names the month**, like the week and 3-day views. Weekday and date already sit in the column header below it ([#501]).
|
||||
- Library updates (kotlinx-datetime, AppCompat).
|
||||
|
||||
## [2.24.1] — 2026-11-12
|
||||
|
||||
### Added
|
||||
- **A classic style for the agenda widget.** Its settings now have a Style option: Cards keeps the new look, Classic brings back the 2.23 layout with a line per day and a colour stripe beside each event, under the current header. Dates in another year show the year. Classic has an Invert text colour switch, so its text stays readable on light and dark wallpapers ([#489]).
|
||||
- **Widget opacity.** Every widget with a Solid or Tinted background has an Opacity slider from 20 to 100%. Below 50%, the card-style widgets back their content like a Transparent widget so it stays readable ([#489]).
|
||||
|
||||
### Fixed
|
||||
- **Week numbers match your region.** With weeks starting on Sunday, the month and week views showed every week number one too low. Rows are now numbered by your region's rules, so ISO regions such as Germany are unchanged ([#493]).
|
||||
- **The month widget shows events at every height.** At some sizes a week row had room for a little more than the date but not a full line of events, and drew none. It now fits a slimmer line there, and a row with a single line shows "+N" on days with more events than fit ([#491]).
|
||||
- **Dimmed past events in dark widgets are readable again.** They used to turn pastel with white text on top ([#475]).
|
||||
- **A widget set to Light or Dark matches the system colours.** With Material You, the + button and today's date could look different from a widget that follows the app ([#475]).
|
||||
|
||||
### Changed
|
||||
- **Fewer permissions.** Calendula no longer asks for network state, wake lock or foreground service access, which a library added without the app needing them ([#448]).
|
||||
- Translation updates from [Calendula's Weblate](https://weblate.dev.jeanlucmakiola.de/projects/calendula/).
|
||||
|
||||
## [2.24.0] — 2026-11-06
|
||||
|
||||
### Added
|
||||
- **Six new home-screen widgets.** Quick add (1×1) opens a new event on today with the same defaults as the app's + button ([#435]). Date (1×1) shows today's weekday and day number on a rounded shape and opens today ([#376]). Week strip (4×1) shows this week's days with a dot in each event's colour and today filled ([#436]). Upcoming (2×2) shows today's date over your next events, as many as fit ([#437]). Today lists today's events; once they're over it says "Nothing left today" and shows tomorrow's first one or two ([#438]). Countdown counts down to your next timed event, or to an event or series you pick, like a holiday in 12 days ([#439]).
|
||||
- **A month and day widget.** A compact month grid sits beside the events of one day. Tap a day in the grid to see its events, and tap the list to open that day in the app ([#441]).
|
||||
- **Each widget has its own settings.** Placing a widget, or long-pressing it and choosing Edit, opens a settings screen with a live preview. Pick a solid, tinted or transparent background, a light or dark theme or the app's, and which calendars it shows. Widgets that list events also have their time range, text size and how past events look. Settings → Widgets lists the widgets on your home screen so you can change them from there. These options used to be shared by all widgets; widgets you already placed keep what you had set ([#292]).
|
||||
- **Turn off start times in the month view.** Settings → Views → Month → Start times hides the time in front of event titles, so narrow fonts keep more of the title. With it on, the time now only shows when the whole title, or at least its first 12 characters, still fits beside it ([#476]).
|
||||
- **Drag all-day events.** In the day, 3-day and week views, long-press an event in the all-day strip and move it sideways to another day, or down into the grid to turn it into a timed event ([#296]).
|
||||
- **Traditional Chinese**, started as a community translation through [Calendula's Weblate](https://weblate.dev.jeanlucmakiola.de/projects/calendula/). It covers only a few screens so far, so the rest still shows in English until it fills out. Pick it under Settings → Language. Thanks to AventineC.
|
||||
|
||||
### Changed
|
||||
- **The agenda and month widgets have a new look.** The agenda puts each day in its own card, with a round date pill beside the first event and today's pill filled. The month widget has rounded day cells, weekday pills, shaded days outside the month and a + for a new event. The agenda's refresh button is gone, since widgets now update on their own ([#71], [#90]).
|
||||
@@ -49,29 +18,11 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0
|
||||
- **The widget picker shows what each widget looks like.** On Android 15 and later the previews are the real widgets with sample events, in your language and colours; on older versions they are redrawn to match.
|
||||
- **Widgets are listed by their name alone,** without "Calendula" in front, and each has a short description in the picker ([#71]).
|
||||
- **Past events in widgets stay readable when dimmed.** Their background fades further and their text less ([#90]).
|
||||
- **Events from midnight to midnight show as all-day events.** A timed event that starts and ends at midnight now sits in the all-day strip, shows as "All day" in the agenda and widgets, and its reminder names the day instead of 00:00 – 00:00. The event itself stays as it was saved ([#296]).
|
||||
- **Cancelled and tentative events are marked.** Cancelled events are struck through and listed last, like declined invites, and tentative ones get the outline used for unanswered invites. Cancelled one-off events and series no longer disappear ([#388]).
|
||||
- **One notification per event.** An event with several reminders now keeps a single notification, which each later reminder updates in place ([#463]).
|
||||
- **Go further back and forward in time.** Every view and the date picker now reach from 1600 to 2399 ([#457]).
|
||||
- **The split month agenda only lists days with events.** In other months it no longer starts with an empty 1st, and a month with nothing in it says so in one row ([#142]).
|
||||
|
||||
### Fixed
|
||||
- **Widgets show your changes straight away.** After you added, edited or deleted an event, a widget could keep showing the old events until something else redrew it ([#420], [#229]).
|
||||
- **Widgets follow the app's language.** After you picked a language in Settings, widgets kept the old one until something redrew them ([#90]).
|
||||
- **The month widget handles busy months.** It could show "Can't show content", or only one or two events per day. Each day now shows as many events as its height fits, and the rest fold into +N ([#372]).
|
||||
- **Short events late in the day are fully visible.** An event like 23:58–23:59 used to be cut down to a sliver at the bottom of the day, week and 3-day views. It now keeps its usual minimum height and sits flush against midnight ([#483]).
|
||||
- **The month view no longer crashes after going before 1900** in the day or week view ([#457]).
|
||||
- **Month pages keep updating.** After a small swipe that snapped back, a month page could stop showing new or edited events, and opening an event from the split view could show its old times ([#440], [#454]).
|
||||
- **Smoother expand and collapse in the split month view.** The day cells morph cleanly between the two layouts, and week numbers now animate along with them ([#473]).
|
||||
- **Back clears the selected day in the split month view.** With a day picked, the back gesture used to close the app; it now goes back to the whole month's agenda first ([#142]).
|
||||
|
||||
## [2.23.1] — 2026-10-28
|
||||
|
||||
### Changed
|
||||
- **The split month view fits more events.** With a day selected, its date is no longer shown twice: the filter chip now stands in for the day's header. Tapping the chip opens the day, and its ✕ clears the filter. The day headers in the month agenda below the grid take less room too ([#142]).
|
||||
|
||||
### Fixed
|
||||
- **Event dots in the split month grid stay in place on busy days.** A day with a "+N" next to its dots used to push them further down the cell ([#142]).
|
||||
|
||||
## [2.23.0] — 2026-10-21
|
||||
|
||||
@@ -1905,7 +1856,6 @@ automatically, with zero telemetry and no internet permission.
|
||||
[#146]: https://codeberg.org/jlmakiola/calendula/issues/146
|
||||
[#267]: https://codeberg.org/jlmakiola/calendula/issues/267
|
||||
[#239]: https://codeberg.org/jlmakiola/calendula/issues/239
|
||||
[#296]: https://codeberg.org/jlmakiola/calendula/issues/296
|
||||
[#297]: https://codeberg.org/jlmakiola/calendula/issues/297
|
||||
[#298]: https://codeberg.org/jlmakiola/calendula/issues/298
|
||||
[#309]: https://codeberg.org/jlmakiola/calendula/issues/309
|
||||
@@ -1955,7 +1905,6 @@ automatically, with zero telemetry and no internet permission.
|
||||
[#306]: https://codeberg.org/jlmakiola/calendula/issues/306
|
||||
[#178]: https://codeberg.org/jlmakiola/calendula/issues/178
|
||||
[#116]: https://codeberg.org/jlmakiola/calendula/issues/116
|
||||
[#388]: https://codeberg.org/jlmakiola/calendula/issues/388
|
||||
[#413]: https://codeberg.org/jlmakiola/calendula/issues/413
|
||||
[#71]: https://codeberg.org/jlmakiola/calendula/issues/71
|
||||
[#90]: https://codeberg.org/jlmakiola/calendula/issues/90
|
||||
@@ -1970,18 +1919,4 @@ automatically, with zero telemetry and no internet permission.
|
||||
[#437]: https://codeberg.org/jlmakiola/calendula/issues/437
|
||||
[#438]: https://codeberg.org/jlmakiola/calendula/issues/438
|
||||
[#439]: https://codeberg.org/jlmakiola/calendula/issues/439
|
||||
[#440]: https://codeberg.org/jlmakiola/calendula/issues/440
|
||||
[#441]: https://codeberg.org/jlmakiola/calendula/issues/441
|
||||
[#454]: https://codeberg.org/jlmakiola/calendula/issues/454
|
||||
[#457]: https://codeberg.org/jlmakiola/calendula/issues/457
|
||||
[#463]: https://codeberg.org/jlmakiola/calendula/issues/463
|
||||
[#473]: https://codeberg.org/jlmakiola/calendula/issues/473
|
||||
[#476]: https://codeberg.org/jlmakiola/calendula/issues/476
|
||||
[#483]: https://codeberg.org/jlmakiola/calendula/issues/483
|
||||
[#448]: https://codeberg.org/jlmakiola/calendula/issues/448
|
||||
[#475]: https://codeberg.org/jlmakiola/calendula/issues/475
|
||||
[#489]: https://codeberg.org/jlmakiola/calendula/issues/489
|
||||
[#491]: https://codeberg.org/jlmakiola/calendula/issues/491
|
||||
[#493]: https://codeberg.org/jlmakiola/calendula/issues/493
|
||||
[#494]: https://codeberg.org/jlmakiola/calendula/issues/494
|
||||
[#501]: https://codeberg.org/jlmakiola/calendula/issues/501
|
||||
@@ -7,4 +7,4 @@ source "https://rubygems.org"
|
||||
# Pinned exactly; Renovate's bundler manager keeps it bumped. No Gemfile.lock is
|
||||
# committed on purpose: this resolves an uploader's transitive deps, not the
|
||||
# app's, and none of it affects the reproducible release build.
|
||||
gem "fastlane", "2.241.1"
|
||||
gem "fastlane", "2.237.0"
|
||||
@@ -32,8 +32,8 @@ android {
|
||||
// (up to 2.22.3: 2.22.3 -> 22203; from 2.22.4: 2.23.0-beta.1 -> 2230001,
|
||||
// 2.22.4 -> 2220499), and CI fails if the committed one doesn't match.
|
||||
// See docs/RELEASING.md.
|
||||
versionCode = 2240299
|
||||
versionName = "2.24.2"
|
||||
versionCode = 2240002
|
||||
versionName = "2.24.0-beta.2"
|
||||
|
||||
testInstrumentationRunner = "androidx.test.runner.AndroidJUnitRunner"
|
||||
}
|
||||
|
||||
@@ -41,11 +41,6 @@
|
||||
-->
|
||||
<uses-permission android:name="android.permission.RECEIVE_BOOT_COMPLETED" />
|
||||
|
||||
<!-- WorkManager declares these for network constraints and foreground workers, neither of which the app uses (#448). -->
|
||||
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" tools:node="remove" />
|
||||
<uses-permission android:name="android.permission.WAKE_LOCK" tools:node="remove" />
|
||||
<uses-permission android:name="android.permission.FOREGROUND_SERVICE" tools:node="remove" />
|
||||
|
||||
<!-- Package visibility (Android 11+): without this, getLaunchIntentForPackage
|
||||
returns null and the calendar manager's per-account "manage" button can't
|
||||
open the source sync app (DAVx5, ICSx5, Google Calendar, …). The LAUNCHER
|
||||
|
||||
@@ -67,10 +67,7 @@ import kotlinx.coroutines.flow.MutableStateFlow
|
||||
import kotlinx.coroutines.flow.combine
|
||||
import kotlinx.coroutines.launch
|
||||
import kotlinx.datetime.LocalDate
|
||||
import kotlinx.datetime.LocalDateTime
|
||||
import kotlinx.datetime.LocalTime
|
||||
import kotlinx.datetime.TimeZone
|
||||
import kotlinx.datetime.toInstant
|
||||
import kotlinx.datetime.toLocalDateTime
|
||||
import kotlin.time.Clock
|
||||
import kotlin.time.Instant
|
||||
@@ -623,20 +620,6 @@ class MainActivity : AppCompatActivity() {
|
||||
putExtra(EXTRA_SOURCE_VIEW, source.name)
|
||||
}
|
||||
|
||||
/**
|
||||
* Open the day view on [date] over the default home view — the daily
|
||||
* summary's tap (#459). Spoken as the system's own "view time" intent,
|
||||
* at the day's local noon, so it lands on the path a clock tap takes.
|
||||
*/
|
||||
fun openDayIntent(context: Context, date: LocalDate): Intent {
|
||||
val noon = LocalDateTime(date, LocalTime(12, 0))
|
||||
.toInstant(TimeZone.currentSystemDefault())
|
||||
.toEpochMilliseconds()
|
||||
return Intent(Intent.ACTION_VIEW, "content://$CALENDAR_PROVIDER_HOST/time/$noon".toUri())
|
||||
.setClass(context, MainActivity::class.java)
|
||||
.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK)
|
||||
}
|
||||
|
||||
/** Open the create-event form prefilled for [date] (home-screen widgets). */
|
||||
fun openCreateIntent(context: Context, date: LocalDate): Intent =
|
||||
Intent(context, MainActivity::class.java).apply {
|
||||
|
||||
@@ -35,7 +35,6 @@ import de.jeanlucmakiola.calendula.domain.ics.ParsedIcsEvent
|
||||
import de.jeanlucmakiola.calendula.domain.ics.semanticReminderMinutes
|
||||
import de.jeanlucmakiola.calendula.domain.ics.parseRfc2445DurationMillis
|
||||
import de.jeanlucmakiola.calendula.domain.rruleTruncatedAt
|
||||
import de.jeanlucmakiola.calendula.domain.fixedReminderOffsets
|
||||
import de.jeanlucmakiola.calendula.domain.toEditForm
|
||||
import kotlinx.datetime.TimeZone
|
||||
import kotlinx.datetime.toJavaLocalDate
|
||||
@@ -568,31 +567,8 @@ class AndroidCalendarDataSource @Inject constructor(
|
||||
}
|
||||
}
|
||||
|
||||
override fun instances(beginMillis: Long, endMillis: Long): List<EventInstance> {
|
||||
val listed = queryInstances(beginMillis, endMillis, null, null)
|
||||
// A provider that does expand cancelled events already listed them.
|
||||
val shown = listed.mapTo(HashSet()) { it.eventId }
|
||||
val cancelled = queryCancelledOneOffs(beginMillis, endMillis).filter { it.eventId !in shown }
|
||||
return if (cancelled.isEmpty()) listed else (listed + cancelled).sortedBy { it.start }
|
||||
}
|
||||
|
||||
/** Cancelled one-off events overlapping the window, which AOSP leaves out of Instances (#388). */
|
||||
private fun queryCancelledOneOffs(beginMillis: Long, endMillis: Long): List<EventInstance> {
|
||||
val selection = "${CalendarContract.Events.STATUS} = ${CalendarContract.Events.STATUS_CANCELED} AND " +
|
||||
"${CalendarContract.Events.DELETED} = 0 AND " +
|
||||
"${CalendarContract.Events.RRULE} IS NULL AND ${CalendarContract.Events.RDATE} IS NULL AND " +
|
||||
"${CalendarContract.Events.ORIGINAL_ID} IS NULL AND " +
|
||||
"${CalendarContract.Events.ORIGINAL_SYNC_ID} IS NULL AND " +
|
||||
"${CalendarContract.Events.DTSTART} < ? AND " +
|
||||
"COALESCE(${CalendarContract.Events.DTEND}, ${CalendarContract.Events.DTSTART}) >= ?"
|
||||
return resolver.query(
|
||||
CalendarContract.Events.CONTENT_URI,
|
||||
CancelledEventProjection.COLUMNS,
|
||||
selection,
|
||||
arrayOf(endMillis.toString(), beginMillis.toString()),
|
||||
null,
|
||||
)?.use { c -> c.mapRowsNotNull { toCancelledOneOff() } } ?: emptyList()
|
||||
}
|
||||
override fun instances(beginMillis: Long, endMillis: Long): List<EventInstance> =
|
||||
queryInstances(beginMillis, endMillis, null, null)
|
||||
|
||||
override fun eventInstances(eventId: Long, beginMillis: Long, endMillis: Long): List<EventInstance> =
|
||||
// The series' own rows plus its exceptions, so an occurrence edited on
|
||||
@@ -611,8 +587,13 @@ class AndroidCalendarDataSource @Inject constructor(
|
||||
args: Array<String>?,
|
||||
): List<EventInstance> {
|
||||
ensureObserversRegistered()
|
||||
// Hide deleted occurrences (cancelled exceptions, #47) but keep a cancelled
|
||||
// event of its own (#388); NULL status is a normal event. DELETED: #364.
|
||||
// Hide cancelled occurrences: "delete only this event" writes a
|
||||
// cancelled exception for the one instance (#47). A cancelled event or
|
||||
// series of its own stays, crossed out (#388), so only exception rows
|
||||
// are filtered. A NULL status is a normal, un-cancelled event, so it
|
||||
// must survive the filter — a bare `!= CANCELED` would drop it (NULL !=
|
||||
// 2 is NULL, not true). DELETED = 0: a provider that soft-deletes may
|
||||
// keep the row's instances until a purge (#364).
|
||||
val visible = "(${CalendarContract.Instances.STATUS} IS NULL OR " +
|
||||
"${CalendarContract.Instances.STATUS} != ${CalendarContract.Events.STATUS_CANCELED} OR " +
|
||||
"(${CalendarContract.Instances.ORIGINAL_ID} IS NULL AND " +
|
||||
@@ -646,8 +627,7 @@ class AndroidCalendarDataSource @Inject constructor(
|
||||
.toTypedArray()
|
||||
val selection = "($match) AND " +
|
||||
"${CalendarContract.Events.DELETED} = 0 AND " +
|
||||
"${CalendarContract.Events.ORIGINAL_ID} IS NULL AND " +
|
||||
"${CalendarContract.Events.ORIGINAL_SYNC_ID} IS NULL"
|
||||
"${CalendarContract.Events.ORIGINAL_ID} IS NULL"
|
||||
return resolver.query(
|
||||
CalendarContract.Events.CONTENT_URI,
|
||||
SearchProjection.COLUMNS,
|
||||
@@ -920,15 +900,11 @@ class AndroidCalendarDataSource @Inject constructor(
|
||||
minutes
|
||||
}
|
||||
|
||||
/**
|
||||
* [form]'s reminders as the distinct raw provider offsets to store, its
|
||||
* fixed-time ones (#459) measured from the start it is saved with.
|
||||
*/
|
||||
/** [form]'s reminders as the distinct raw provider offsets to store. */
|
||||
private fun encodedReminders(form: EventForm, allDayReminderTimeMinutes: Int): List<Int> =
|
||||
(
|
||||
form.reminders.map { providerReminderMinutes(form, it, allDayReminderTimeMinutes) } +
|
||||
form.fixedReminderOffsets(TimeZone.currentSystemDefault())
|
||||
).distinct()
|
||||
form.reminders
|
||||
.map { providerReminderMinutes(form, it, allDayReminderTimeMinutes) }
|
||||
.distinct()
|
||||
|
||||
override fun insertEvent(form: EventForm, allDayReminderTimeMinutes: Int): Long {
|
||||
// A globally-unique UID so a later .ics backup/restore can identify
|
||||
@@ -1031,11 +1007,7 @@ class AndroidCalendarDataSource @Inject constructor(
|
||||
// Untouched reminder sets are left alone so unrelated edits can't
|
||||
// disturb provider rows the form never knew about. The diff is on the
|
||||
// form's semantic minutes; reconcile works in encoded provider minutes.
|
||||
// A fixed-time reminder also changes when the start's day or time does.
|
||||
val zone = TimeZone.currentSystemDefault()
|
||||
if (updated.reminders.toSet() != original.reminders.toSet() ||
|
||||
updated.fixedReminderOffsets(zone).toSet() != original.fixedReminderOffsets(zone).toSet()
|
||||
) {
|
||||
if (updated.reminders.toSet() != original.reminders.toSet()) {
|
||||
reconcileReminders(eventId, encodedReminders(updated, allDayReminderTimeMinutes))
|
||||
}
|
||||
// Same untouched-set guard for guests: only reconcile when the form's
|
||||
@@ -1236,9 +1208,8 @@ class AndroidCalendarDataSource @Inject constructor(
|
||||
)
|
||||
}
|
||||
// Whether the provider copied the parent's reminder rows is its
|
||||
// business — reconciling against the actual rows handles both ways. The
|
||||
// exception is a one-off, so a fixed-time reminder takes real minutes.
|
||||
reconcileReminders(exceptionId, encodedReminders(form.toDetachedOccurrence(), allDayReminderTimeMinutes))
|
||||
// business — reconciling against the actual rows handles both ways.
|
||||
reconcileReminders(exceptionId, encodedReminders(form, allDayReminderTimeMinutes))
|
||||
reconcileAttendees(exceptionId, form.attendees)
|
||||
return exceptionId
|
||||
}
|
||||
|
||||
@@ -9,7 +9,6 @@ import de.jeanlucmakiola.calendula.domain.EventColorOption
|
||||
import de.jeanlucmakiola.calendula.domain.EventForm
|
||||
import de.jeanlucmakiola.calendula.domain.FormTime
|
||||
import de.jeanlucmakiola.calendula.domain.EventStatus
|
||||
import de.jeanlucmakiola.calendula.domain.forNewEvent
|
||||
import de.jeanlucmakiola.calendula.domain.ics.ParsedIcsEvent
|
||||
import de.jeanlucmakiola.calendula.domain.nearestTo
|
||||
import kotlinx.datetime.toJavaLocalDate
|
||||
@@ -133,8 +132,7 @@ internal fun buildEventInsertValues(
|
||||
put(CalendarContract.Events.EVENT_TIMEZONE, times.timezone)
|
||||
put(CalendarContract.Events.AVAILABILITY, form.availability.toProviderValue())
|
||||
put(CalendarContract.Events.ACCESS_LEVEL, form.accessLevel.toProviderValue())
|
||||
form.status.forNewEvent().takeIf { it != EventStatus.Confirmed }
|
||||
?.let { put(CalendarContract.Events.STATUS, it.toProviderStatus()) }
|
||||
if (form.status != EventStatus.Confirmed) put(CalendarContract.Events.STATUS, form.status.toProviderStatus())
|
||||
form.location.trim().takeIf { it.isNotEmpty() }
|
||||
?.let { put(CalendarContract.Events.EVENT_LOCATION, it) }
|
||||
form.description.trim().takeIf { it.isNotEmpty() }
|
||||
@@ -285,7 +283,7 @@ internal fun buildOccurrenceExceptionValues(
|
||||
put(CalendarContract.Events.EVENT_TIMEZONE, times.timezone)
|
||||
put(CalendarContract.Events.AVAILABILITY, form.availability.toProviderValue())
|
||||
put(CalendarContract.Events.ACCESS_LEVEL, form.accessLevel.toProviderValue())
|
||||
put(CalendarContract.Events.STATUS, form.status.forNewEvent().toProviderStatus())
|
||||
put(CalendarContract.Events.STATUS, form.status.toProviderStatus())
|
||||
put(CalendarContract.Events.EVENT_LOCATION, form.location.trim().ifEmpty { null })
|
||||
put(CalendarContract.Events.DESCRIPTION, form.description.trim().ifEmpty { null })
|
||||
if (form.colorKey == null) putAll(eventColorColumns(null, form.color))
|
||||
@@ -361,8 +359,7 @@ internal fun buildMovedMasterValues(
|
||||
}
|
||||
put(CalendarContract.Events.AVAILABILITY, snapshot.availability)
|
||||
put(CalendarContract.Events.ACCESS_LEVEL, snapshot.accessLevel)
|
||||
snapshot.status?.takeIf { it != CalendarContract.Events.STATUS_CANCELED }
|
||||
?.let { put(CalendarContract.Events.STATUS, it) }
|
||||
snapshot.status?.let { put(CalendarContract.Events.STATUS, it) }
|
||||
put(CalendarContract.Events.EVENT_LOCATION, snapshot.location?.ifEmpty { null })
|
||||
put(CalendarContract.Events.DESCRIPTION, snapshot.description?.ifEmpty { null })
|
||||
}
|
||||
@@ -866,7 +863,7 @@ internal fun buildImportedEventValues(
|
||||
// timed rows keep the event's own zone.
|
||||
put(CalendarContract.Events.EVENT_TIMEZONE, if (event.isAllDay) "UTC" else event.zoneId)
|
||||
put(CalendarContract.Events.AVAILABILITY, event.availability.toProviderValue())
|
||||
put(CalendarContract.Events.STATUS, event.status.forNewEvent().toProviderStatus())
|
||||
put(CalendarContract.Events.STATUS, event.status.toProviderStatus())
|
||||
event.location?.trim()?.takeIf { it.isNotEmpty() }
|
||||
?.let { put(CalendarContract.Events.EVENT_LOCATION, it) }
|
||||
event.description?.trim()?.takeIf { it.isNotEmpty() }
|
||||
|
||||
@@ -42,13 +42,6 @@ internal fun ColumnReader.toEventInstance(): EventInstance? {
|
||||
)
|
||||
}
|
||||
|
||||
/**
|
||||
* A [CancelledEventProjection] row as an instance. Its id is the negated event
|
||||
* id, so it can't collide with a provider instance id.
|
||||
*/
|
||||
internal fun ColumnReader.toCancelledOneOff(): EventInstance? =
|
||||
toEventInstance()?.let { it.copy(instanceId = -it.eventId) }
|
||||
|
||||
/**
|
||||
* `SELF_ATTENDEE_STATUS` as the calendar surfaces read it: a tentative "maybe"
|
||||
* counts as going, and everything that is not an open or refused invitation —
|
||||
|
||||
@@ -79,28 +79,6 @@ internal object InstanceProjection {
|
||||
const val IDX_STATUS = 11
|
||||
}
|
||||
|
||||
/**
|
||||
* A cancelled one-off straight from the Events table, laid out on
|
||||
* [InstanceProjection]'s indices so [toCancelledOneOff] reuses its mapper. AOSP
|
||||
* writes no Instances rows for a cancelled event (#388).
|
||||
*/
|
||||
internal object CancelledEventProjection {
|
||||
val COLUMNS: Array<String> = arrayOf(
|
||||
CalendarContract.Events._ID,
|
||||
CalendarContract.Events._ID,
|
||||
CalendarContract.Events.CALENDAR_ID,
|
||||
CalendarContract.Events.TITLE,
|
||||
CalendarContract.Events.DTSTART,
|
||||
CalendarContract.Events.DTEND,
|
||||
CalendarContract.Events.ALL_DAY,
|
||||
CalendarContract.Events.EVENT_COLOR,
|
||||
CalendarContract.Events.CALENDAR_COLOR,
|
||||
CalendarContract.Events.EVENT_LOCATION,
|
||||
CalendarContract.Events.SELF_ATTENDEE_STATUS,
|
||||
CalendarContract.Events.STATUS,
|
||||
)
|
||||
}
|
||||
|
||||
internal object EventDetailProjection {
|
||||
val COLUMNS: Array<String> = arrayOf(
|
||||
CalendarContract.Events._ID,
|
||||
|
||||
@@ -81,7 +81,7 @@ class CalendarPrefs @Inject constructor(
|
||||
}
|
||||
|
||||
/** A comma-joined id set; non-numeric tokens are dropped, and an empty set removes the key. */
|
||||
internal fun idSetPref(name: String): Pref<Set<Long>> = nullableStringPref(name).map(
|
||||
private fun idSetPref(name: String): Pref<Set<Long>> = nullableStringPref(name).map(
|
||||
{ stored -> stored.orEmpty().split(',').mapNotNull { it.trim().toLongOrNull() }.toSet() },
|
||||
{ ids -> if (ids.isEmpty()) null else ids.sorted().joinToString(",") },
|
||||
)
|
||||
@@ -4,8 +4,6 @@ import androidx.datastore.core.DataStore
|
||||
import androidx.datastore.preferences.core.Preferences
|
||||
import de.jeanlucmakiola.floret.prefs.PrefStore
|
||||
import de.jeanlucmakiola.floret.prefs.nullableLongPref
|
||||
import de.jeanlucmakiola.floret.prefs.nullableStringPref
|
||||
import java.time.LocalDate
|
||||
import javax.inject.Inject
|
||||
import javax.inject.Singleton
|
||||
|
||||
@@ -29,20 +27,7 @@ class ReminderStatePrefs @Inject constructor(
|
||||
|
||||
suspend fun setLastScanMillis(millis: Long) = prefs.set(LAST_SCAN, millis)
|
||||
|
||||
/**
|
||||
* The day the last daily summary listed (#459): recorded at once, so neither
|
||||
* a pass failing after posting nor a later time picked the same evening
|
||||
* lists it twice.
|
||||
*/
|
||||
suspend fun lastDigestDay(): LocalDate? =
|
||||
prefs.get(LAST_DIGEST_DAY)?.let { runCatching { LocalDate.parse(it) }.getOrNull() }
|
||||
|
||||
suspend fun setLastDigestDay(day: LocalDate) = prefs.set(LAST_DIGEST_DAY, day.toString())
|
||||
|
||||
suspend fun clearLastDigestDay() = prefs.set(LAST_DIGEST_DAY, null)
|
||||
|
||||
private companion object {
|
||||
val LAST_SCAN = nullableLongPref("reminder_last_scan_millis")
|
||||
val LAST_DIGEST_DAY = nullableStringPref("reminder_last_digest_day")
|
||||
}
|
||||
}
|
||||
@@ -1,15 +1,10 @@
|
||||
package de.jeanlucmakiola.calendula.data.prefs
|
||||
|
||||
import androidx.datastore.core.DataStore
|
||||
import androidx.datastore.preferences.core.MutablePreferences
|
||||
import androidx.datastore.preferences.core.Preferences
|
||||
import de.jeanlucmakiola.calendula.domain.EventFormField
|
||||
import de.jeanlucmakiola.calendula.domain.FontRole
|
||||
import de.jeanlucmakiola.calendula.domain.contacts.SpecialDateType
|
||||
import de.jeanlucmakiola.calendula.domain.reminders.DEFAULT_DIGEST_TIME_MINUTES
|
||||
import de.jeanlucmakiola.calendula.domain.reminders.DailyDigestSettings
|
||||
import de.jeanlucmakiola.calendula.domain.reminders.DigestDay
|
||||
import de.jeanlucmakiola.calendula.domain.reminders.FixedTimeReminder
|
||||
import de.jeanlucmakiola.calendula.ui.agenda.AgendaRange
|
||||
import de.jeanlucmakiola.calendula.ui.agenda.parseAgendaRange
|
||||
import de.jeanlucmakiola.calendula.ui.agenda.storageValue
|
||||
@@ -151,7 +146,6 @@ class SettingsPrefs @Inject constructor(
|
||||
val pastEventDisplay: Flow<PastEventDisplay> = prefs.flow(SettingsKeys.pastEventDisplay)
|
||||
val dimCompletedEvents: Flow<Boolean> = prefs.flow(SettingsKeys.dimCompletedEvents)
|
||||
val showWeekNumbers: Flow<Boolean> = prefs.flow(SettingsKeys.showWeekNumbers)
|
||||
val monthShowStartTimes: Flow<Boolean> = prefs.flow(SettingsKeys.monthShowStartTimes)
|
||||
val monthViewStyle: Flow<MonthViewStyle> = prefs.flow(SettingsKeys.monthViewStyle)
|
||||
val timelineScale: Flow<TimelineScale> = prefs.flow(SettingsKeys.timelineScale)
|
||||
val multiDayCount: Flow<Int> = prefs.flow(SettingsKeys.multiDayCount)
|
||||
@@ -171,8 +165,6 @@ class SettingsPrefs @Inject constructor(
|
||||
val defaultEventDurationMinutes: Flow<Int> = prefs.flow(SettingsKeys.defaultEventDurationMinutes)
|
||||
val perCalendarEventDuration: Flow<Map<Long, Int>> = prefs.flow(SettingsKeys.perCalendarEventDuration)
|
||||
val remindersEnabled: Flow<Boolean> = prefs.flow(SettingsKeys.remindersEnabled)
|
||||
val mutedReminderCalendarIds: Flow<Set<Long>> = prefs.flow(SettingsKeys.mutedReminderCalendarIds)
|
||||
val notificationCategoryHintDismissed: Flow<Boolean> = prefs.flow(SettingsKeys.notificationCategoryHintDismissed)
|
||||
val allowColorOnUnsupportedCalendars: Flow<Boolean> =
|
||||
prefs.flow(SettingsKeys.allowColorOnUnsupportedCalendars)
|
||||
val defaultReminderMinutes: Flow<List<Int>> = prefs.flow(SettingsKeys.defaultReminderMinutes)
|
||||
@@ -183,20 +175,6 @@ class SettingsPrefs @Inject constructor(
|
||||
prefs.flow(SettingsKeys.perCalendarReminderOverride)
|
||||
val perCalendarAllDayReminderOverride: Flow<Map<Long, List<Int>>> =
|
||||
prefs.flow(SettingsKeys.perCalendarAllDayReminderOverride)
|
||||
val defaultFixedTimeReminder: Flow<FixedTimeReminder?> = prefs.flow(SettingsKeys.defaultFixedTimeReminder)
|
||||
val perCalendarFixedTimeReminderOverride: Flow<Map<Long, FixedTimeReminder?>> =
|
||||
prefs.flow(SettingsKeys.perCalendarFixedTimeReminderOverride)
|
||||
|
||||
/**
|
||||
* Every "N days before at HH:MM" the defaults name, so an offset landing on
|
||||
* one reads back as that reminder rather than a lead time (#459).
|
||||
*/
|
||||
val knownFixedTimeReminders: Flow<Set<FixedTimeReminder>> = prefs.snapshot {
|
||||
setOfNotNull(it[SettingsKeys.defaultFixedTimeReminder]) +
|
||||
it[SettingsKeys.perCalendarFixedTimeReminderOverride].values.filterNotNull() +
|
||||
it[SettingsKeys.recentFixedTimeReminders]
|
||||
}
|
||||
val dailyDigest: Flow<DailyDigestSettings> = prefs.snapshot { it.dailyDigest }
|
||||
val autoBackupEnabled: Flow<Boolean> = prefs.flow(SettingsKeys.autoBackupEnabled)
|
||||
val autoBackupIntervalMinutes: Flow<Long> = prefs.flow(SettingsKeys.autoBackupIntervalMinutes)
|
||||
val autoBackupFolderUri: Flow<String?> = prefs.flow(SettingsKeys.autoBackupFolderUri)
|
||||
@@ -234,7 +212,6 @@ class SettingsPrefs @Inject constructor(
|
||||
suspend fun setPastEventDisplay(mode: PastEventDisplay) = prefs.set(SettingsKeys.pastEventDisplay, mode)
|
||||
suspend fun setDimCompletedEvents(enabled: Boolean) = prefs.set(SettingsKeys.dimCompletedEvents, enabled)
|
||||
suspend fun setShowWeekNumbers(enabled: Boolean) = prefs.set(SettingsKeys.showWeekNumbers, enabled)
|
||||
suspend fun setMonthShowStartTimes(enabled: Boolean) = prefs.set(SettingsKeys.monthShowStartTimes, enabled)
|
||||
suspend fun setMonthViewStyle(style: MonthViewStyle) = prefs.set(SettingsKeys.monthViewStyle, style)
|
||||
suspend fun setTimelineScale(scale: TimelineScale) = prefs.set(SettingsKeys.timelineScale, scale)
|
||||
suspend fun setMultiDayCount(count: Int) = prefs.set(SettingsKeys.multiDayCount, count)
|
||||
@@ -294,12 +271,6 @@ class SettingsPrefs @Inject constructor(
|
||||
|
||||
suspend fun setRemindersEnabled(enabled: Boolean) = prefs.set(SettingsKeys.remindersEnabled, enabled)
|
||||
|
||||
suspend fun dismissNotificationCategoryHint() = prefs.set(SettingsKeys.notificationCategoryHintDismissed, true)
|
||||
|
||||
suspend fun setCalendarRemindersEnabled(calendarId: Long, enabled: Boolean) {
|
||||
prefs.update(SettingsKeys.mutedReminderCalendarIds) { if (enabled) it - calendarId else it + calendarId }
|
||||
}
|
||||
|
||||
suspend fun setAllowColorOnUnsupportedCalendars(enabled: Boolean) =
|
||||
prefs.set(SettingsKeys.allowColorOnUnsupportedCalendars, enabled)
|
||||
|
||||
@@ -351,77 +322,6 @@ class SettingsPrefs @Inject constructor(
|
||||
suspend fun setCalendarAllDayReminderOverride(calendarId: Long, override: ReminderOverride) =
|
||||
prefs.applyOverride(SettingsKeys.perCalendarAllDayReminderOverride, calendarId, override)
|
||||
|
||||
/** The replaced default stays a known pattern, so events that got it keep reading as it. */
|
||||
suspend fun setDefaultFixedTimeReminder(reminder: FixedTimeReminder?) {
|
||||
prefs.edit {
|
||||
val old = it[SettingsKeys.defaultFixedTimeReminder]
|
||||
if (old != reminder) retireFixedTimeReminder(it, old)
|
||||
it[SettingsKeys.defaultFixedTimeReminder] = reminder
|
||||
}
|
||||
}
|
||||
|
||||
/** [override] [FixedTimeOverride.Inherit] drops the calendar's entry; a replaced value stays known. */
|
||||
suspend fun setCalendarFixedTimeReminderOverride(calendarId: Long, override: FixedTimeOverride) {
|
||||
prefs.edit {
|
||||
val current = it[SettingsKeys.perCalendarFixedTimeReminderOverride]
|
||||
val old = current[calendarId]
|
||||
if (old != (override as? FixedTimeOverride.At)?.reminder) retireFixedTimeReminder(it, old)
|
||||
it[SettingsKeys.perCalendarFixedTimeReminderOverride] = when (override) {
|
||||
FixedTimeOverride.Inherit -> current - calendarId
|
||||
FixedTimeOverride.Off -> current + (calendarId to null)
|
||||
is FixedTimeOverride.At -> current + (calendarId to override.reminder)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Remember fixed-time reminders saved by hand (#459), so their rows read
|
||||
* back as them; the defaults are known anyway and take no slot.
|
||||
*/
|
||||
suspend fun rememberFixedTimeReminders(reminders: Collection<FixedTimeReminder>) {
|
||||
prefs.edit {
|
||||
val defaults = setOfNotNull(it[SettingsKeys.defaultFixedTimeReminder]) +
|
||||
it[SettingsKeys.perCalendarFixedTimeReminderOverride].values.filterNotNull()
|
||||
val fresh = reminders.filterNot { reminder -> reminder in defaults }
|
||||
if (fresh.isNotEmpty()) {
|
||||
it[SettingsKeys.recentFixedTimeReminders] = (fresh + it[SettingsKeys.recentFixedTimeReminders]).distinct()
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/** Keep a default being replaced known, unless it still is a default elsewhere. */
|
||||
private fun retireFixedTimeReminder(preferences: MutablePreferences, reminder: FixedTimeReminder?) {
|
||||
if (reminder == null) return
|
||||
val defaults = listOfNotNull(preferences[SettingsKeys.defaultFixedTimeReminder]) +
|
||||
preferences[SettingsKeys.perCalendarFixedTimeReminderOverride].values.filterNotNull()
|
||||
if (defaults.count { it == reminder } > 1) return
|
||||
preferences[SettingsKeys.recentFixedTimeReminders] =
|
||||
(listOf(reminder) + preferences[SettingsKeys.recentFixedTimeReminders]).distinct()
|
||||
}
|
||||
|
||||
suspend fun setDailyDigestEnabled(enabled: Boolean) = editDigest { it[SettingsKeys.dailyDigestEnabled] = enabled }
|
||||
|
||||
suspend fun setDailyDigestTimeMinutes(minutesOfDay: Int) =
|
||||
editDigest { it[SettingsKeys.dailyDigestTimeMinutes] = minutesOfDay }
|
||||
|
||||
suspend fun setDailyDigestDay(day: DigestDay) = editDigest { it[SettingsKeys.dailyDigestDay] = day }
|
||||
|
||||
/**
|
||||
* Change when the summary arrives, stamping the moment: a summary whose time
|
||||
* had already passed today is not owed by the change itself.
|
||||
*/
|
||||
private suspend fun editDigest(change: (MutablePreferences) -> Unit) {
|
||||
prefs.edit {
|
||||
change(it)
|
||||
it[SettingsKeys.dailyDigestArmedAt] = System.currentTimeMillis()
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
suspend fun setCalendarInDailyDigest(calendarId: Long, included: Boolean) {
|
||||
prefs.update(SettingsKeys.digestExcludedCalendarIds) { if (included) it - calendarId else it + calendarId }
|
||||
}
|
||||
|
||||
suspend fun setAutoBackupEnabled(enabled: Boolean) = prefs.set(SettingsKeys.autoBackupEnabled, enabled)
|
||||
|
||||
suspend fun setAutoBackupIntervalMinutes(minutes: Long) =
|
||||
@@ -471,7 +371,6 @@ class SettingsPrefs @Inject constructor(
|
||||
/** 09:00 as minutes from midnight; the default all-day reminder fire time. */
|
||||
internal const val DEFAULT_ALLDAY_REMINDER_TIME = 540
|
||||
internal const val MINUTES_PER_DAY = 1_440
|
||||
internal const val MAX_RECENT_FIXED_TIME_REMINDERS = 12
|
||||
/** Default snooze delay for the notification "Snooze" action. */
|
||||
const val DEFAULT_SNOOZE_MINUTES = 10
|
||||
const val DEFAULT_MULTI_DAY_COUNT = 3
|
||||
@@ -546,9 +445,6 @@ object SettingsKeys {
|
||||
*/
|
||||
val showWeekNumbers: Pref<Boolean> = booleanPref("show_week_numbers", false)
|
||||
|
||||
/** Whether Month chips may show the start time before the title when wide enough (#219, #476). */
|
||||
val monthShowStartTimes: Pref<Boolean> = booleanPref("month_show_start_times", true)
|
||||
|
||||
/** How the Month view lays itself out (#38, #53). */
|
||||
val monthViewStyle: Pref<MonthViewStyle> = enumPref("month_view_style", MonthViewStyle.Paged)
|
||||
|
||||
@@ -693,18 +589,6 @@ object SettingsKeys {
|
||||
*/
|
||||
val remindersEnabled: Pref<Boolean> = booleanPref("reminders_enabled", true)
|
||||
|
||||
/**
|
||||
* Calendars whose reminders Calendula doesn't post (#272), independent of
|
||||
* `Calendars.VISIBLE`: the events still show, only the notifications stop.
|
||||
*/
|
||||
val mutedReminderCalendarIds: Pref<Set<Long>> = idSetPref("muted_reminder_calendar_ids")
|
||||
|
||||
/**
|
||||
* Whether the one-time hint that some skins (Samsung) start new notification
|
||||
* categories switched off has been dismissed (#145).
|
||||
*/
|
||||
val notificationCategoryHintDismissed: Pref<Boolean> = booleanPref("notification_category_hint_dismissed", false)
|
||||
|
||||
/**
|
||||
* Whether to offer a custom event colour on calendars that publish no colour
|
||||
* palette; synced ones without a palette (some CalDAV) may drop or overwrite
|
||||
@@ -794,48 +678,6 @@ object SettingsKeys {
|
||||
val perCalendarAllDayReminderOverride: Pref<Map<Long, List<Int>>> =
|
||||
reminderOverridePref("per_calendar_allday_reminder_override")
|
||||
|
||||
/**
|
||||
* The "N days before at HH:MM" reminder added to new **timed** events
|
||||
* (#459), or null for none — the factory default. Stored as `days@minute`.
|
||||
*/
|
||||
val defaultFixedTimeReminder: Pref<FixedTimeReminder?> =
|
||||
nullableStringPref("default_fixed_time_reminder").map(FixedTimeReminder::parse) { it?.toToken() }
|
||||
|
||||
/**
|
||||
* Per-calendar overrides of [defaultFixedTimeReminder]: present with a
|
||||
* value replaces it, present as null turns it off, absent inherits.
|
||||
* Serialised as `id=days@minute` or `id=none`, joined by `;`.
|
||||
*/
|
||||
val perCalendarFixedTimeReminderOverride: Pref<Map<Long, FixedTimeReminder?>> =
|
||||
nullableStringPref("per_calendar_fixed_time_reminder").map(::parseFixedTimeOverrides) {
|
||||
it.toStoredFixedTimeOverrides()
|
||||
}
|
||||
|
||||
/** The daily summary notification (#459): opt-in, and which day it lists at what time. */
|
||||
val dailyDigestEnabled: Pref<Boolean> = booleanPref("daily_digest_enabled", false)
|
||||
val dailyDigestTimeMinutes: Pref<Int> =
|
||||
intPref("daily_digest_time_minutes", DEFAULT_DIGEST_TIME_MINUTES).coerced {
|
||||
it.coerceIn(0, SettingsPrefs.MINUTES_PER_DAY - 1)
|
||||
}
|
||||
val dailyDigestDay: Pref<DigestDay> = enumPref("daily_digest_day", DigestDay.Tomorrow)
|
||||
|
||||
/** Calendars left out of the daily summary; every other one is in. */
|
||||
val digestExcludedCalendarIds: Pref<Set<Long>> = idSetPref("digest_excluded_calendar_ids")
|
||||
|
||||
/** When the summary's switch, time or day last changed; a moment before it is never owed. */
|
||||
val dailyDigestArmedAt: Pref<Long> = longPref("daily_digest_armed_at", 0L)
|
||||
|
||||
/**
|
||||
* Fixed-time reminders last saved by hand, and defaults since replaced,
|
||||
* newest first — with the current defaults, the patterns a stored offset is
|
||||
* recognised as. Capped, so the oldest falls out of recognition.
|
||||
*/
|
||||
val recentFixedTimeReminders: Pref<List<FixedTimeReminder>> =
|
||||
nullableStringPref("recent_fixed_time_reminders").map(
|
||||
{ stored -> stored?.split(LIST_SEP).orEmpty().mapNotNull(FixedTimeReminder::parse).distinct() },
|
||||
{ reminders -> reminders.take(SettingsPrefs.MAX_RECENT_FIXED_TIME_REMINDERS).joinToString(LIST_SEP) { it.toToken() } },
|
||||
)
|
||||
|
||||
/** Whether periodic automatic `.ics` export of local calendars is on (issue #8). */
|
||||
val autoBackupEnabled: Pref<Boolean> = booleanPref("auto_backup_enabled", false)
|
||||
|
||||
@@ -1032,57 +874,6 @@ data class BackupStatus(
|
||||
val consecutiveFailures: Int,
|
||||
)
|
||||
|
||||
/** The daily summary's settings, read together. */
|
||||
internal val Preferences.dailyDigest: DailyDigestSettings
|
||||
get() = DailyDigestSettings(
|
||||
enabled = this[SettingsKeys.dailyDigestEnabled],
|
||||
timeMinutes = this[SettingsKeys.dailyDigestTimeMinutes],
|
||||
day = this[SettingsKeys.dailyDigestDay],
|
||||
excludedCalendarIds = this[SettingsKeys.digestExcludedCalendarIds],
|
||||
armedAtMillis = this[SettingsKeys.dailyDigestArmedAt],
|
||||
)
|
||||
|
||||
/** A calendar's choice for the fixed-time default, as a picker returns it. */
|
||||
sealed interface FixedTimeOverride {
|
||||
data object Inherit : FixedTimeOverride
|
||||
data object Off : FixedTimeOverride
|
||||
data class At(val reminder: FixedTimeReminder) : FixedTimeOverride
|
||||
}
|
||||
|
||||
/** [calendarId]'s entry read as a [FixedTimeOverride]. */
|
||||
fun Map<Long, FixedTimeReminder?>.fixedTimeOverrideFor(calendarId: Long): FixedTimeOverride = when {
|
||||
!containsKey(calendarId) -> FixedTimeOverride.Inherit
|
||||
else -> getValue(calendarId)?.let { FixedTimeOverride.At(it) } ?: FixedTimeOverride.Off
|
||||
}
|
||||
|
||||
/** The fixed-time reminder a new timed event on [calendarId] gets, or null for none. */
|
||||
fun resolveDefaultFixedTimeReminder(
|
||||
global: FixedTimeReminder?,
|
||||
overrides: Map<Long, FixedTimeReminder?>,
|
||||
calendarId: Long?,
|
||||
): FixedTimeReminder? =
|
||||
if (calendarId != null && overrides.containsKey(calendarId)) overrides[calendarId] else global
|
||||
|
||||
private fun parseFixedTimeOverrides(stored: String?): Map<Long, FixedTimeReminder?> =
|
||||
stored?.split(ENTRY_SEP).orEmpty().mapNotNull { entry ->
|
||||
val parts = entry.split(KEY_VALUE_SEP)
|
||||
if (parts.size != 2) return@mapNotNull null
|
||||
val calendarId = parts[0].trim().toLongOrNull() ?: return@mapNotNull null
|
||||
val value = parts[1].trim()
|
||||
if (value == NONE) return@mapNotNull calendarId to null
|
||||
val reminder = FixedTimeReminder.parse(value) ?: return@mapNotNull null
|
||||
calendarId to reminder
|
||||
}.toMap()
|
||||
|
||||
private fun Map<Long, FixedTimeReminder?>.toStoredFixedTimeOverrides(): String? =
|
||||
if (isEmpty()) {
|
||||
null
|
||||
} else {
|
||||
entries.sortedBy { it.key }.joinToString(ENTRY_SEP) { (id, reminder) ->
|
||||
"$id$KEY_VALUE_SEP${reminder?.toToken() ?: NONE}"
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* The lead times to prefill on a new event: the matching per-calendar override
|
||||
* if [calendarId] has one for this event kind, otherwise the global default for
|
||||
|
||||
@@ -1,157 +0,0 @@
|
||||
package de.jeanlucmakiola.calendula.data.reminders
|
||||
|
||||
import android.app.NotificationChannel
|
||||
import android.app.NotificationManager
|
||||
import android.app.PendingIntent
|
||||
import android.content.Context
|
||||
import android.util.Log
|
||||
import androidx.core.app.NotificationCompat
|
||||
import androidx.core.app.NotificationManagerCompat
|
||||
import dagger.hilt.android.qualifiers.ApplicationContext
|
||||
import de.jeanlucmakiola.calendula.MainActivity
|
||||
import de.jeanlucmakiola.calendula.R
|
||||
import de.jeanlucmakiola.calendula.data.prefs.SettingsPrefs
|
||||
import de.jeanlucmakiola.calendula.data.prefs.is24Hour
|
||||
import de.jeanlucmakiola.calendula.data.prefs.resolveFirstDay
|
||||
import de.jeanlucmakiola.calendula.domain.reminders.ReminderEventInstance
|
||||
import kotlinx.coroutines.flow.first
|
||||
import kotlinx.datetime.isoDayNumber
|
||||
import kotlinx.datetime.toKotlinLocalDate
|
||||
import java.time.DayOfWeek
|
||||
import java.time.LocalDate
|
||||
import java.time.ZoneId
|
||||
import java.time.format.DateTimeFormatter
|
||||
import java.util.Locale
|
||||
import javax.inject.Inject
|
||||
import javax.inject.Singleton
|
||||
|
||||
/**
|
||||
* Posts the daily summary (#459): one notification listing a day's events, on
|
||||
* its own channel, replacing the one before it. Tapping opens that day.
|
||||
*/
|
||||
@Singleton
|
||||
class DailyDigestNotifier @Inject constructor(
|
||||
@ApplicationContext private val context: Context,
|
||||
private val settingsPrefs: SettingsPrefs,
|
||||
) {
|
||||
|
||||
/**
|
||||
* Post the summary of [day] listing [listed], or withdraw the last one when
|
||||
* there is nothing to list — yesterday's would otherwise stand in for it.
|
||||
*/
|
||||
suspend fun post(day: LocalDate, listed: List<ReminderEventInstance>) {
|
||||
val manager = NotificationManagerCompat.from(context)
|
||||
if (listed.isEmpty()) {
|
||||
manager.cancel(TAG_DIGEST, NOTIFICATION_ID)
|
||||
return
|
||||
}
|
||||
ensureChannel()
|
||||
val zone = ZoneId.systemDefault()
|
||||
val locale = Locale.getDefault()
|
||||
val is24Hour = settingsPrefs.timeFormat.first()
|
||||
.is24Hour(android.text.format.DateFormat.is24HourFormat(context))
|
||||
val today = LocalDate.now(zone)
|
||||
val firstDayOfWeek = DayOfWeek.of(settingsPrefs.weekStart.first().resolveFirstDay(locale).isoDayNumber)
|
||||
// The date rides along: the summary stays up into the day it lists,
|
||||
// when "Tomorrow" alone would point at the wrong one.
|
||||
val date = DateTimeFormatter.ofPattern(
|
||||
android.text.format.DateFormat.getBestDateTimePattern(locale, "EEEdMMM"),
|
||||
locale,
|
||||
).format(day)
|
||||
val dayLabel = when (day) {
|
||||
today -> context.getString(R.string.digest_day_relative, context.getString(R.string.reminder_day_today), date)
|
||||
today.plusDays(1) ->
|
||||
context.getString(R.string.digest_day_relative, context.getString(R.string.reminder_day_tomorrow), date)
|
||||
else -> date
|
||||
}
|
||||
val allDay = context.getString(R.string.event_detail_all_day)
|
||||
val lines = listed.map { entry ->
|
||||
// Read against the listed day, so a timed event on it shows its bare
|
||||
// range and one crossing midnight its dates.
|
||||
val time = if (entry.isAllDay) allDay else reminderTimeText(
|
||||
beginMillis = entry.beginMillis,
|
||||
endMillis = entry.endMillis,
|
||||
isAllDay = entry.isAllDay,
|
||||
zone = zone,
|
||||
locale = locale,
|
||||
is24Hour = is24Hour,
|
||||
today = day,
|
||||
firstDayOfWeek = firstDayOfWeek,
|
||||
todayLabel = allDay,
|
||||
tomorrowLabel = context.getString(R.string.reminder_day_tomorrow),
|
||||
yesterdayLabel = context.getString(R.string.reminder_day_yesterday),
|
||||
)
|
||||
context.getString(R.string.digest_line, time, entry.title.ifBlank { context.getString(R.string.event_untitled) })
|
||||
}
|
||||
val title = context.resources.getQuantityString(R.plurals.digest_title, listed.size, dayLabel, listed.size)
|
||||
val style = NotificationCompat.InboxStyle().setBigContentTitle(title)
|
||||
lines.take(MAX_LINES).forEach(style::addLine)
|
||||
if (lines.size > MAX_LINES) {
|
||||
val more = lines.size - MAX_LINES
|
||||
style.setSummaryText(context.resources.getQuantityString(R.plurals.digest_more, more, more))
|
||||
}
|
||||
val notification = NotificationCompat.Builder(context, CHANNEL_ID)
|
||||
.setSmallIcon(R.drawable.ic_notification)
|
||||
.setContentTitle(title)
|
||||
.setContentText(listed.joinToString(", ") { it.title.ifBlank { context.getString(R.string.event_untitled) } })
|
||||
.setStyle(style)
|
||||
.setCategory(NotificationCompat.CATEGORY_REMINDER)
|
||||
.setAutoCancel(true)
|
||||
// Gone once its day is over; "Tomorrow" would read wrong by then anyway.
|
||||
.setTimeoutAfter(
|
||||
(day.plusDays(1).atStartOfDay(zone).toInstant().toEpochMilli() - System.currentTimeMillis())
|
||||
.coerceAtLeast(1L),
|
||||
)
|
||||
.setContentIntent(openDay(day))
|
||||
.build()
|
||||
try {
|
||||
manager.notify(TAG_DIGEST, NOTIFICATION_ID, notification)
|
||||
} catch (e: SecurityException) {
|
||||
Log.w(TAG, "Could not post the daily summary", e)
|
||||
}
|
||||
}
|
||||
|
||||
/** Whether the summary's own channel is switched off in the system settings. */
|
||||
fun isChannelOff(): Boolean =
|
||||
context.getSystemService(NotificationManager::class.java)
|
||||
.getNotificationChannel(CHANNEL_ID)?.importance == NotificationManager.IMPORTANCE_NONE
|
||||
|
||||
/** Withdraw the summary showing, if any. */
|
||||
fun cancel() {
|
||||
NotificationManagerCompat.from(context).cancel(TAG_DIGEST, NOTIFICATION_ID)
|
||||
}
|
||||
|
||||
/** The summary's channel id, created if missing — for the settings deep-link. */
|
||||
fun channelId(): String {
|
||||
ensureChannel()
|
||||
return CHANNEL_ID
|
||||
}
|
||||
|
||||
/** Creates the channel, or renames it after a language change; the user's settings on it stay. */
|
||||
private fun ensureChannel() {
|
||||
val manager = context.getSystemService(NotificationManager::class.java)
|
||||
manager.createNotificationChannel(
|
||||
NotificationChannel(
|
||||
CHANNEL_ID,
|
||||
context.getString(R.string.digest_channel_name),
|
||||
NotificationManager.IMPORTANCE_DEFAULT,
|
||||
).apply { description = context.getString(R.string.digest_channel_description) },
|
||||
)
|
||||
}
|
||||
|
||||
private fun openDay(day: LocalDate): PendingIntent = PendingIntent.getActivity(
|
||||
context,
|
||||
REQUEST_CODE,
|
||||
MainActivity.openDayIntent(context, day.toKotlinLocalDate()),
|
||||
PendingIntent.FLAG_UPDATE_CURRENT or PendingIntent.FLAG_IMMUTABLE,
|
||||
)
|
||||
|
||||
private companion object {
|
||||
const val TAG = "DailyDigestNotifier"
|
||||
const val CHANNEL_ID = "daily_digest"
|
||||
const val TAG_DIGEST = "daily_digest"
|
||||
const val NOTIFICATION_ID = 2
|
||||
const val REQUEST_CODE = 0xD16E
|
||||
const val MAX_LINES = 6
|
||||
}
|
||||
}
|
||||
@@ -1,161 +0,0 @@
|
||||
package de.jeanlucmakiola.calendula.data.reminders
|
||||
|
||||
import de.jeanlucmakiola.calendula.domain.CalendarSource
|
||||
import de.jeanlucmakiola.calendula.ui.common.groupByAccount
|
||||
|
||||
/** The single channel every reminder posted on before they moved per calendar (#145). */
|
||||
const val LEGACY_REMINDER_CHANNEL_ID = "reminders"
|
||||
|
||||
private const val CHANNEL_PREFIX = "reminders.calendar."
|
||||
private const val GROUP_PREFIX = "reminders.account."
|
||||
private const val LOCAL_GROUP_ID = GROUP_PREFIX + "local"
|
||||
|
||||
/** The notification channel [calendarId]'s reminders post on. */
|
||||
fun reminderChannelId(calendarId: Long): String = CHANNEL_PREFIX + calendarId
|
||||
|
||||
/** Whether [channelId] is one of the per-calendar reminder channels. */
|
||||
fun isReminderChannelId(channelId: String): Boolean = channelId.startsWith(CHANNEL_PREFIX)
|
||||
|
||||
/** Whether [groupId] is one of the per-account reminder channel groups. */
|
||||
fun isReminderGroupId(groupId: String): Boolean = groupId.startsWith(GROUP_PREFIX)
|
||||
|
||||
/**
|
||||
* One account's channel group, labelled as the calendar manager labels it. The
|
||||
* app's own device calendars share a single group ([isLocal]); [ambiguous]
|
||||
* marks a [label] another group shows too, so it should name the source app.
|
||||
*/
|
||||
data class ReminderChannelGroupSpec(
|
||||
val id: String,
|
||||
val label: String,
|
||||
val accountType: String,
|
||||
val isLocal: Boolean,
|
||||
val ambiguous: Boolean,
|
||||
)
|
||||
|
||||
data class ReminderChannelSpec(
|
||||
val id: String,
|
||||
val calendarId: Long,
|
||||
val name: String,
|
||||
/** Null only for a channel created before its calendar could be looked up. */
|
||||
val groupId: String?,
|
||||
/**
|
||||
* Whether a sync creates it up front. A calendar that syncs no events never
|
||||
* fires, so its channel only appears once something posts on it.
|
||||
*/
|
||||
val upFront: Boolean = true,
|
||||
)
|
||||
|
||||
/** What a channel already looks like in the system, as far as the plan compares it. */
|
||||
data class ExistingReminderChannel(val id: String, val name: String, val description: String?, val groupId: String?)
|
||||
|
||||
data class ReminderChannelPlan(
|
||||
val groups: List<ReminderChannelGroupSpec>,
|
||||
val channels: List<ReminderChannelSpec>,
|
||||
/**
|
||||
* The [channels] a sync writes: missing up-front ones, and existing ones
|
||||
* whose name or (localized) description changed, or that still lack a group.
|
||||
*/
|
||||
val channelsToWrite: List<ReminderChannelSpec>,
|
||||
/** The [groups] holding a channel that exists or is about to be written. */
|
||||
val groupsInUse: List<ReminderChannelGroupSpec>,
|
||||
val staleChannelIds: List<String>,
|
||||
val staleGroupIds: List<String>,
|
||||
)
|
||||
|
||||
/**
|
||||
* What the reminder channels should look like for [calendars]: one channel per
|
||||
* calendar inside a group per account, which of them need writing, and the
|
||||
* reminder channels and groups in [existing] / [existingGroupIds] no calendar
|
||||
* claims any more. Ids outside the reminder namespace (the backup channel, the
|
||||
* legacy channel) are never touched.
|
||||
*/
|
||||
fun planReminderChannels(
|
||||
calendars: List<CalendarSource>,
|
||||
existing: Collection<ExistingReminderChannel>,
|
||||
existingGroupIds: Collection<String>,
|
||||
unnamed: String,
|
||||
description: String,
|
||||
): ReminderChannelPlan {
|
||||
val (local, synced) = calendars.partition { it.isLocal }
|
||||
val groups = buildList {
|
||||
if (local.isNotEmpty()) {
|
||||
add(ReminderChannelGroupSpec(LOCAL_GROUP_ID, "", local.first().accountType, isLocal = true, ambiguous = false))
|
||||
}
|
||||
synced.groupByAccount().forEach { group ->
|
||||
add(
|
||||
ReminderChannelGroupSpec(
|
||||
id = accountGroupId(group.key.type, group.key.name),
|
||||
label = group.label,
|
||||
accountType = group.accountType,
|
||||
isLocal = false,
|
||||
ambiguous = group.ambiguous,
|
||||
),
|
||||
)
|
||||
}
|
||||
}
|
||||
val channels = calendars.map { calendar ->
|
||||
ReminderChannelSpec(
|
||||
id = reminderChannelId(calendar.id),
|
||||
calendarId = calendar.id,
|
||||
name = calendar.displayName.ifBlank { unnamed },
|
||||
groupId = if (calendar.isLocal) LOCAL_GROUP_ID else accountGroupId(calendar.accountType, calendar.accountName),
|
||||
upFront = calendar.isLocal || calendar.syncsEvents,
|
||||
)
|
||||
}
|
||||
val existingById = existing.associateBy { it.id }
|
||||
val wantedChannels = channels.mapTo(HashSet()) { it.id }
|
||||
val wantedGroups = groups.mapTo(HashSet()) { it.id }
|
||||
val toWrite = channels.filter { spec ->
|
||||
val current = existingById[spec.id]
|
||||
if (current == null) {
|
||||
spec.upFront
|
||||
} else {
|
||||
current.name != spec.name || current.description != description ||
|
||||
(current.groupId == null && spec.groupId != null)
|
||||
}
|
||||
}
|
||||
val usedGroupIds = channels
|
||||
.filter { it.id in existingById || it in toWrite }
|
||||
.mapNotNullTo(HashSet()) { it.groupId }
|
||||
return ReminderChannelPlan(
|
||||
groups = groups,
|
||||
channels = channels,
|
||||
channelsToWrite = toWrite,
|
||||
groupsInUse = groups.filter { it.id in usedGroupIds },
|
||||
staleChannelIds = existingById.keys.filter { isReminderChannelId(it) && it !in wantedChannels },
|
||||
staleGroupIds = existingGroupIds.filter { isReminderGroupId(it) && it !in wantedGroups },
|
||||
)
|
||||
}
|
||||
|
||||
private fun accountGroupId(type: String, name: String): String = "$GROUP_PREFIX$type/$name"
|
||||
|
||||
/** A channel as far as its blocked state goes: switched off itself, and the group it sits in. */
|
||||
data class ReminderChannelState(val blocked: Boolean, val groupId: String?)
|
||||
|
||||
/** Reminder notifications the system blocks, while Calendula would post them. */
|
||||
data class ReminderChannelStatus(
|
||||
val appBlocked: Boolean = false,
|
||||
val blockedCalendarIds: Set<Long> = emptySet(),
|
||||
/** The blocked ones whose whole account group is off, which only the app's own screen can undo. */
|
||||
val groupBlockedCalendarIds: Set<Long> = emptySet(),
|
||||
)
|
||||
|
||||
/**
|
||||
* What the system blocks of [calendarIds]' reminders: all of them while the
|
||||
* app's notifications are off, otherwise those whose channel, or the group it
|
||||
* sits in, is switched off. A calendar without a channel yet isn't blocked.
|
||||
*/
|
||||
fun reminderChannelStatus(
|
||||
calendarIds: Collection<Long>,
|
||||
appEnabled: Boolean,
|
||||
channels: Map<String, ReminderChannelState>,
|
||||
blockedGroupIds: Set<String>,
|
||||
): ReminderChannelStatus {
|
||||
val groupBlocked = calendarIds.filterTo(HashSet()) { channels[reminderChannelId(it)]?.groupId in blockedGroupIds }
|
||||
val blocked = if (!appEnabled) {
|
||||
calendarIds.toSet()
|
||||
} else {
|
||||
calendarIds.filterTo(HashSet()) { channels[reminderChannelId(it)]?.blocked == true } + groupBlocked
|
||||
}
|
||||
return ReminderChannelStatus(appBlocked = !appEnabled, blockedCalendarIds = blocked, groupBlockedCalendarIds = groupBlocked)
|
||||
}
|
||||
@@ -1,208 +0,0 @@
|
||||
package de.jeanlucmakiola.calendula.data.reminders
|
||||
|
||||
import android.app.NotificationChannel
|
||||
import android.app.NotificationChannelGroup
|
||||
import android.app.NotificationManager
|
||||
import android.content.Context
|
||||
import android.util.Log
|
||||
import dagger.hilt.android.qualifiers.ApplicationContext
|
||||
import de.jeanlucmakiola.calendula.R
|
||||
import de.jeanlucmakiola.calendula.data.calendar.CalendarDataSource
|
||||
import de.jeanlucmakiola.calendula.domain.CalendarSource
|
||||
import de.jeanlucmakiola.calendula.ui.common.sourceAppLabel
|
||||
import java.util.Locale
|
||||
import javax.inject.Inject
|
||||
import javax.inject.Singleton
|
||||
|
||||
/**
|
||||
* The reminder notification channels: one per calendar, grouped by account
|
||||
* (#145), created up front so each calendar can be muted or given its own sound
|
||||
* in the system settings before it ever fires.
|
||||
*
|
||||
* A channel the user has touched keeps their settings; [sync] only creates the
|
||||
* missing ones, renames changed ones, and deletes those whose calendar is gone.
|
||||
*/
|
||||
@Singleton
|
||||
class ReminderChannels @Inject constructor(
|
||||
@ApplicationContext private val context: Context,
|
||||
private val calendarDataSource: CalendarDataSource,
|
||||
) {
|
||||
private val manager: NotificationManager
|
||||
get() = context.getSystemService(NotificationManager::class.java)
|
||||
|
||||
/** What the last [sync] saw, so an unchanged provider costs no channel writes. */
|
||||
@Volatile
|
||||
private var lastSync: Any? = null
|
||||
|
||||
/**
|
||||
* Bring the channels in line with the provider's calendars. An empty
|
||||
* snapshot changes nothing: that is a provider hiccup far more often than
|
||||
* every calendar gone at once.
|
||||
*/
|
||||
@Synchronized
|
||||
fun sync() {
|
||||
val calendars = calendarDataSource.calendars()
|
||||
if (calendars.isEmpty()) return
|
||||
val manager = manager
|
||||
val existing = manager.notificationChannels
|
||||
val existingIds = existing.mapTo(HashSet()) { it.id }
|
||||
if (syncKey(calendars, existingIds) == lastSync && LEGACY_REMINDER_CHANNEL_ID !in existingIds) return
|
||||
val groups = manager.notificationChannelGroups
|
||||
val plan = plan(calendars, existing, groups.map { it.id })
|
||||
plan.staleChannelIds.forEach(manager::deleteNotificationChannel)
|
||||
plan.staleGroupIds.forEach(manager::deleteNotificationChannelGroup)
|
||||
val groupNames = groups.associate { it.id to it.name?.toString() }
|
||||
write(
|
||||
groups = plan.groupsInUse.filter { groupNames[it.id] != groupLabel(it) },
|
||||
channels = plan.channelsToWrite,
|
||||
existing = existing,
|
||||
)
|
||||
val ids = existingIds - plan.staleChannelIds.toSet() + plan.channelsToWrite.map { it.id }
|
||||
lastSync = syncKey(calendars, if (retireLegacyChannel()) ids - LEGACY_REMINDER_CHANNEL_ID else ids)
|
||||
}
|
||||
|
||||
private fun syncKey(calendars: List<CalendarSource>, channelIds: Set<String>): Any = listOf(
|
||||
calendars.map { listOf(it.id, it.displayName, it.accountName, it.accountType, it.isLocal, it.syncsEvents) },
|
||||
Locale.getDefault(),
|
||||
channelIds,
|
||||
)
|
||||
|
||||
/**
|
||||
* The channel to post [calendarId]'s reminder on, created first if a sync
|
||||
* has not got to it yet. Null when the calendar no longer exists. Should the
|
||||
* calendar lookup fail or come back empty, the channel is still created,
|
||||
* plainly named and ungrouped, for the next sync to name and file — a
|
||||
* reminder is never lost to its channel.
|
||||
*/
|
||||
@Synchronized
|
||||
fun channelFor(calendarId: Long): String? {
|
||||
val id = reminderChannelId(calendarId)
|
||||
val manager = manager
|
||||
if (manager.getNotificationChannel(id) != null) return id
|
||||
val existing = manager.notificationChannels
|
||||
val calendars = try {
|
||||
calendarDataSource.calendars()
|
||||
} catch (e: Exception) {
|
||||
Log.w(TAG, "Could not look up calendar $calendarId for its channel", e)
|
||||
emptyList()
|
||||
}
|
||||
val fallback = ReminderChannelSpec(id, calendarId, context.getString(R.string.reminder_channel_name), null)
|
||||
if (calendars.isEmpty()) {
|
||||
write(emptyList(), listOf(fallback), existing)
|
||||
return id
|
||||
}
|
||||
val plan = plan(calendars, existing, emptyList())
|
||||
val spec = plan.channels.firstOrNull { it.calendarId == calendarId } ?: return null
|
||||
try {
|
||||
val knownGroups = manager.notificationChannelGroups.mapTo(HashSet()) { it.id }
|
||||
write(
|
||||
groups = plan.groups.filter { it.id == spec.groupId && it.id !in knownGroups },
|
||||
channels = listOf(spec),
|
||||
existing = existing,
|
||||
)
|
||||
} catch (e: RuntimeException) {
|
||||
Log.w(TAG, "Could not file the channel of calendar $calendarId", e)
|
||||
write(emptyList(), listOf(fallback), existing)
|
||||
}
|
||||
return id
|
||||
}
|
||||
|
||||
/** What the system currently lets through for [calendarIds]' reminders (#145). */
|
||||
fun status(calendarIds: Collection<Long>): ReminderChannelStatus {
|
||||
val manager = manager
|
||||
val appEnabled = manager.areNotificationsEnabled()
|
||||
val channels = manager.notificationChannels.associate {
|
||||
it.id to ReminderChannelState(it.importance == NotificationManager.IMPORTANCE_NONE, it.group)
|
||||
}
|
||||
val blockedGroups = manager.notificationChannelGroups.filter { it.isBlocked }.mapTo(HashSet()) { it.id }
|
||||
return reminderChannelStatus(calendarIds, appEnabled, channels, blockedGroups)
|
||||
}
|
||||
|
||||
private fun plan(
|
||||
calendars: List<CalendarSource>,
|
||||
existing: List<NotificationChannel>,
|
||||
existingGroupIds: List<String>,
|
||||
): ReminderChannelPlan = planReminderChannels(
|
||||
calendars = calendars,
|
||||
existing = existing.map { ExistingReminderChannel(it.id, it.name.toString(), it.description, it.group) },
|
||||
existingGroupIds = existingGroupIds,
|
||||
unnamed = context.getString(R.string.calendar_unnamed),
|
||||
description = context.getString(R.string.reminder_channel_description),
|
||||
)
|
||||
|
||||
private fun write(
|
||||
groups: List<ReminderChannelGroupSpec>,
|
||||
channels: List<ReminderChannelSpec>,
|
||||
existing: List<NotificationChannel>,
|
||||
) {
|
||||
val manager = manager
|
||||
if (groups.isNotEmpty()) {
|
||||
manager.createNotificationChannelGroups(groups.map { NotificationChannelGroup(it.id, groupLabel(it)) })
|
||||
}
|
||||
if (channels.isEmpty()) return
|
||||
val byId = existing.associateBy { it.id }
|
||||
val description = context.getString(R.string.reminder_channel_description)
|
||||
val template = byId[LEGACY_REMINDER_CHANNEL_ID]
|
||||
// Importance only applies on creation; an existing channel keeps its own.
|
||||
manager.createNotificationChannels(
|
||||
channels.map { spec ->
|
||||
val current = byId[spec.id]
|
||||
NotificationChannel(
|
||||
spec.id,
|
||||
spec.name,
|
||||
current?.importance ?: template?.importance ?: NotificationManager.IMPORTANCE_HIGH,
|
||||
).apply {
|
||||
this.description = description
|
||||
spec.groupId?.let { group = it }
|
||||
if (current == null && template != null) inheritFrom(template)
|
||||
}
|
||||
},
|
||||
)
|
||||
}
|
||||
|
||||
/**
|
||||
* Carry the old single channel's sound, vibration, lights and badge over to
|
||||
* a new per-calendar one (the system resets lock-screen visibility itself), so an upgrade keeps how reminders sounded.
|
||||
*/
|
||||
private fun NotificationChannel.inheritFrom(template: NotificationChannel) {
|
||||
setSound(template.sound, template.audioAttributes)
|
||||
// The pattern setter also flips vibration on or off, so it goes first.
|
||||
vibrationPattern = template.vibrationPattern
|
||||
enableVibration(template.shouldVibrate())
|
||||
enableLights(template.shouldShowLights())
|
||||
lightColor = template.lightColor
|
||||
setShowBadge(template.canShowBadge())
|
||||
// Only honoured with Do Not Disturb access, so usually left to the user.
|
||||
setBypassDnd(template.canBypassDnd())
|
||||
}
|
||||
|
||||
/**
|
||||
* Delete the pre-#145 channel once the per-calendar ones carry its settings,
|
||||
* but not while a reminder posted on it is still on screen — deleting the
|
||||
* channel would take that notification with it. Returns whether it is gone.
|
||||
*/
|
||||
private fun retireLegacyChannel(): Boolean {
|
||||
val manager = manager
|
||||
if (manager.getNotificationChannel(LEGACY_REMINDER_CHANNEL_ID) == null) return true
|
||||
val showing = runCatching {
|
||||
manager.activeNotifications.any { it.notification.channelId == LEGACY_REMINDER_CHANNEL_ID }
|
||||
}.getOrElse { e ->
|
||||
Log.w(TAG, "Could not read active notifications", e)
|
||||
true
|
||||
}
|
||||
if (!showing) manager.deleteNotificationChannel(LEGACY_REMINDER_CHANNEL_ID)
|
||||
return !showing
|
||||
}
|
||||
|
||||
private fun groupLabel(group: ReminderChannelGroupSpec): String {
|
||||
if (group.isLocal) return context.getString(R.string.calendars_local_header)
|
||||
val name = group.label.ifBlank { context.getString(R.string.calendar_unnamed) }
|
||||
if (!group.ambiguous) return name
|
||||
return context.getString(R.string.calendars_account_from_source, name, sourceAppLabel(context, group.accountType))
|
||||
}
|
||||
|
||||
private companion object {
|
||||
const val TAG = "ReminderChannels"
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1,6 +1,8 @@
|
||||
package de.jeanlucmakiola.calendula.data.reminders
|
||||
|
||||
import android.Manifest
|
||||
import android.app.NotificationChannel
|
||||
import android.app.NotificationManager
|
||||
import android.app.PendingIntent
|
||||
import android.content.Context
|
||||
import android.os.Build
|
||||
@@ -27,8 +29,8 @@ import javax.inject.Inject
|
||||
import javax.inject.Singleton
|
||||
|
||||
/**
|
||||
* Posts one notification per occurrence on its calendar's channel
|
||||
* ([ReminderChannels], #145). Tapping opens the event's detail screen.
|
||||
* Posts one notification per occurrence on a dedicated channel. Tapping opens
|
||||
* the event's detail screen.
|
||||
*
|
||||
* The tag is the [occurrenceKey], so each reminder for an occurrence replaces
|
||||
* the one before it in place (#463). A different reminder alerts afresh; the
|
||||
@@ -41,7 +43,6 @@ class ReminderNotifier @Inject constructor(
|
||||
private val settingsPrefs: SettingsPrefs,
|
||||
private val calendarPrefs: CalendarPrefs,
|
||||
private val calendarDataSource: CalendarDataSource,
|
||||
private val channels: ReminderChannels,
|
||||
) {
|
||||
|
||||
/** False when the user declined `POST_NOTIFICATIONS` or muted the app. */
|
||||
@@ -52,28 +53,19 @@ class ReminderNotifier @Inject constructor(
|
||||
}
|
||||
|
||||
/**
|
||||
* The single choke point for "this calendar posts no reminders": switched
|
||||
* off (also covering a snooze armed before the switch-off, and a read-only
|
||||
* install whose switch lives in [CalendarPrefs]), or its notifications
|
||||
* turned off in Calendula's own settings (#272).
|
||||
* The single choke point for "this calendar is switched off", covering the
|
||||
* two paths that reach [post] around the scan's own filter: a snooze armed
|
||||
* before the switch-off, and a read-only install whose switch lives in
|
||||
* [CalendarPrefs].
|
||||
*/
|
||||
private suspend fun isSilenced(calendarId: Long): Boolean =
|
||||
calendarId in settingsPrefs.mutedReminderCalendarIds.first() ||
|
||||
calendarId in calendarPrefs.pendingDisabledCalendarIds.first() ||
|
||||
calendarId in calendarPrefs.pendingDisabledCalendarIds.first() ||
|
||||
calendarDataSource.isCalendarVisible(calendarId) == false
|
||||
|
||||
/** Post [alert], unless its calendar is silenced or gone. */
|
||||
/** Post [alert], unless its calendar is switched off. */
|
||||
suspend fun post(alert: ReminderAlert) {
|
||||
if (isSilenced(alert.calendarId)) return
|
||||
val channelId = try {
|
||||
channels.channelFor(alert.calendarId) ?: run {
|
||||
Log.i(TAG, "Dropped the reminder of event ${alert.eventId}: calendar ${alert.calendarId} is gone")
|
||||
return
|
||||
}
|
||||
} catch (e: Exception) {
|
||||
Log.w(TAG, "No channel for the reminder of event ${alert.eventId}", e)
|
||||
return
|
||||
}
|
||||
ensureChannel()
|
||||
val title = displayTitle(alert)
|
||||
val is24Hour = settingsPrefs.timeFormat.first()
|
||||
.is24Hour(android.text.format.DateFormat.is24HourFormat(context))
|
||||
@@ -96,7 +88,7 @@ class ReminderNotifier @Inject constructor(
|
||||
yesterdayLabel = context.getString(R.string.reminder_day_yesterday),
|
||||
)
|
||||
val text = listOfNotNull(time, alert.location).joinToString(" · ")
|
||||
val notification = NotificationCompat.Builder(context, channelId)
|
||||
val notification = NotificationCompat.Builder(context, CHANNEL_ID)
|
||||
.setSmallIcon(R.drawable.ic_notification)
|
||||
.setContentTitle(title)
|
||||
.setContentText(text)
|
||||
@@ -161,7 +153,7 @@ class ReminderNotifier @Inject constructor(
|
||||
private fun cancelLegacy(alert: ReminderAlert) {
|
||||
val manager = NotificationManagerCompat.from(context)
|
||||
manager.activeNotifications
|
||||
.filter { it.id == NOTIFICATION_ID && it.notification.channelId == LEGACY_REMINDER_CHANNEL_ID }
|
||||
.filter { it.id == NOTIFICATION_ID && it.notification.channelId == CHANNEL_ID }
|
||||
.filter { !it.notification.extras.containsKey(EXTRA_REMINDER_KEY) }
|
||||
.filter { it.notification.`when` == alert.beginMillis }
|
||||
.filter { it.notification.extras.getCharSequence(NotificationCompat.EXTRA_TITLE)?.toString() == displayTitle(alert) }
|
||||
@@ -189,8 +181,21 @@ class ReminderNotifier @Inject constructor(
|
||||
PendingIntent.FLAG_UPDATE_CURRENT or PendingIntent.FLAG_IMMUTABLE,
|
||||
)
|
||||
|
||||
/** Channel creation is idempotent; re-running refreshes the localized name. */
|
||||
private fun ensureChannel() {
|
||||
val channel = NotificationChannel(
|
||||
CHANNEL_ID,
|
||||
context.getString(R.string.reminder_channel_name),
|
||||
NotificationManager.IMPORTANCE_HIGH,
|
||||
).apply {
|
||||
description = context.getString(R.string.reminder_channel_description)
|
||||
}
|
||||
NotificationManagerCompat.from(context).createNotificationChannel(channel)
|
||||
}
|
||||
|
||||
private companion object {
|
||||
const val TAG = "ReminderNotifier"
|
||||
const val CHANNEL_ID = "reminders"
|
||||
|
||||
// One id, distinct tags: the tag (occurrence) already keys the
|
||||
// notification, so a fixed id keeps cancellation/replacement simple.
|
||||
|
||||
@@ -6,13 +6,9 @@ import android.util.Log
|
||||
import dagger.hilt.android.qualifiers.ApplicationContext
|
||||
import de.jeanlucmakiola.calendula.data.calendar.CalendarDataSource
|
||||
import de.jeanlucmakiola.calendula.data.calendar.withoutProviderDefaults
|
||||
import de.jeanlucmakiola.calendula.data.prefs.CalendarPrefs
|
||||
import de.jeanlucmakiola.calendula.data.prefs.ReminderStatePrefs
|
||||
import de.jeanlucmakiola.calendula.data.prefs.SettingsPrefs
|
||||
import de.jeanlucmakiola.calendula.domain.reminders.DailyDigestSettings
|
||||
import de.jeanlucmakiola.calendula.domain.reminders.digestEntries
|
||||
import de.jeanlucmakiola.calendula.domain.reminders.planReminders
|
||||
import de.jeanlucmakiola.calendula.domain.reminders.scheduleDigest
|
||||
import de.jeanlucmakiola.calendula.domain.reminders.reminderQueryHorizon
|
||||
import de.jeanlucmakiola.calendula.domain.reminders.reminderWatermark
|
||||
import de.jeanlucmakiola.calendula.domain.reminders.scheduleReminders
|
||||
@@ -47,12 +43,9 @@ class ReminderScanner @Inject constructor(
|
||||
private val source: ReminderInstanceSource,
|
||||
private val calendarDataSource: CalendarDataSource,
|
||||
private val notifier: ReminderNotifier,
|
||||
private val digestNotifier: DailyDigestNotifier,
|
||||
private val channels: ReminderChannels,
|
||||
private val snoozes: ReminderSnoozeScheduler,
|
||||
private val alarms: ReminderAlarmScheduler,
|
||||
private val state: ReminderStatePrefs,
|
||||
private val calendarPrefs: CalendarPrefs,
|
||||
private val settingsPrefs: SettingsPrefs,
|
||||
@IoDispatcher private val io: kotlinx.coroutines.CoroutineDispatcher,
|
||||
) {
|
||||
@@ -84,37 +77,18 @@ class ReminderScanner @Inject constructor(
|
||||
val now = System.currentTimeMillis()
|
||||
if (!hasReadCalendar()) return
|
||||
|
||||
val lastFired = reminderWatermark(state.lastScanMillis(), now)
|
||||
val horizon = now + MAX_ALARM_INTERVAL_MILLIS
|
||||
val digestSettings = settingsPrefs.dailyDigest.first()
|
||||
val nextDigest = if (digestSettings.enabled) postDigest(digestSettings, lastFired, now) else null
|
||||
val nextReminder = try {
|
||||
if (settingsPrefs.remindersEnabled.first()) reminders(lastFired, now, horizon) else null
|
||||
} catch (e: Exception) {
|
||||
// The watermark stays, so the next pass owes these reminders again;
|
||||
// keep that pass, and the summary's next moment, armed.
|
||||
alarms.scheduleScan(minOf(nextDigest ?: horizon, now + RETRY_AFTER_FAILURE_MILLIS))
|
||||
throw e
|
||||
if (!settingsPrefs.remindersEnabled.first()) {
|
||||
// Reminders off: drop the wake-up, but keep the watermark moving
|
||||
// so switching them back on doesn't replay the backlog.
|
||||
alarms.cancelScan()
|
||||
state.setLastScanMillis(now)
|
||||
return
|
||||
}
|
||||
|
||||
// Advance even when nothing could be posted, so muting notifications
|
||||
// doesn't build a backlog — and while both are off, so switching one
|
||||
// back on doesn't replay it.
|
||||
state.setLastScanMillis(now)
|
||||
val next = listOfNotNull(nextReminder, nextDigest).minOrNull()
|
||||
if (next == null) alarms.cancelScan() else alarms.scheduleScan(minOf(next, horizon))
|
||||
}
|
||||
|
||||
/** Post the event reminders that are due; returns the next wake-up they need. */
|
||||
private suspend fun reminders(lastFired: Long, now: Long, horizon: Long): Long {
|
||||
syncChannels()
|
||||
val lookahead = reminderQueryHorizon(LOOKAHEAD_MILLIS, source.longestReminderMinutes())
|
||||
// Reach into the past too: an all-day "at time of event" encodes to a
|
||||
// negative offset, and a catch-up pass needs the occurrences it missed.
|
||||
// Calendars muted in-app (#272) plan nothing, so they arm no wake-ups.
|
||||
val muted = settingsPrefs.mutedReminderCalendarIds.first()
|
||||
val occurrences = source.occurrences(now - PAST_WINDOW_MILLIS, now + lookahead)
|
||||
.filter { it.calendarId !in muted }
|
||||
val planned = planReminders(
|
||||
instances = occurrences,
|
||||
minutesByEvent = source.reminderMinutes(occurrences.map { it.eventId })
|
||||
@@ -125,9 +99,9 @@ class ReminderScanner @Inject constructor(
|
||||
|
||||
val schedule = scheduleReminders(
|
||||
planned = planned,
|
||||
lastFiredMillis = lastFired,
|
||||
lastFiredMillis = reminderWatermark(state.lastScanMillis(), now),
|
||||
nowMillis = now,
|
||||
horizonMillis = horizon,
|
||||
horizonMillis = now + MAX_ALARM_INTERVAL_MILLIS,
|
||||
)
|
||||
|
||||
if (notifier.canPost()) {
|
||||
@@ -137,61 +111,10 @@ class ReminderScanner @Inject constructor(
|
||||
notifier.post(alert)
|
||||
}
|
||||
}
|
||||
return schedule.nextAlarmMillis
|
||||
}
|
||||
|
||||
/**
|
||||
* Post the daily summary if it is owed (#459); returns its next moment. It
|
||||
* leaves out calendars excluded from it, not those muted for reminders —
|
||||
* a calendar too noisy to ping per event can still belong in the overview.
|
||||
*/
|
||||
private suspend fun postDigest(settings: DailyDigestSettings, lastFired: Long, now: Long): Long {
|
||||
val zone = ZoneId.systemDefault()
|
||||
val listed = try {
|
||||
state.lastDigestDay()
|
||||
} catch (e: Exception) {
|
||||
Log.w(TAG, "Could not read the last daily summary", e)
|
||||
null
|
||||
}
|
||||
val schedule = scheduleDigest(
|
||||
timeMinutes = settings.timeMinutes,
|
||||
day = settings.day,
|
||||
zone = zone,
|
||||
// A moment that passed before the summary was last changed is not owed.
|
||||
lastFiredMillis = maxOf(lastFired, settings.armedAtMillis),
|
||||
nowMillis = now,
|
||||
lastListedDay = listed,
|
||||
)
|
||||
val day = schedule.dueDay
|
||||
// A blocked channel would swallow it; the day stays owed until allowed.
|
||||
if (day != null && notifier.canPost() && !digestNotifier.isChannelOff()) {
|
||||
// A failed summary must not cost the event reminders this pass owes.
|
||||
try {
|
||||
// A day either side: all-day occurrences sit at UTC midnight, which
|
||||
// can fall outside the local day they stand for.
|
||||
val from = day.minusDays(1).atStartOfDay(zone).toInstant().toEpochMilli()
|
||||
val to = day.plusDays(2).atStartOfDay(zone).toInstant().toEpochMilli()
|
||||
val left = settings.excludedCalendarIds + calendarPrefs.pendingDisabledCalendarIds.first()
|
||||
digestNotifier.post(day, digestEntries(source.occurrences(from, to), day, zone, left))
|
||||
state.setLastDigestDay(day)
|
||||
} catch (e: Exception) {
|
||||
Log.w(TAG, "Daily summary failed", e)
|
||||
}
|
||||
}
|
||||
return schedule.nextAlarmMillis
|
||||
}
|
||||
|
||||
/**
|
||||
* A provider change re-scans, so a calendar added, renamed or removed keeps
|
||||
* its channel in step here. Skipped while reminders are off, when the
|
||||
* channels have nothing to do. A failure never costs the reminders.
|
||||
*/
|
||||
private fun syncChannels() {
|
||||
try {
|
||||
channels.sync()
|
||||
} catch (e: Exception) {
|
||||
Log.w(TAG, "Reminder channel sync failed", e)
|
||||
}
|
||||
// Advance even when nothing could be posted, so muting notifications
|
||||
// doesn't build a backlog.
|
||||
state.setLastScanMillis(now)
|
||||
alarms.scheduleScan(schedule.nextAlarmMillis)
|
||||
}
|
||||
|
||||
private fun hasReadCalendar(): Boolean = context.hasPermission(Manifest.permission.READ_CALENDAR)
|
||||
@@ -235,8 +158,5 @@ class ReminderScanner @Inject constructor(
|
||||
const val MAX_ALARM_INTERVAL_MILLIS = 24L * 60 * 60 * 1000
|
||||
|
||||
const val PROVIDER_CHANGE_DEBOUNCE_MILLIS = 2_000L
|
||||
|
||||
/** How soon a pass whose reminders failed is tried again. */
|
||||
const val RETRY_AFTER_FAILURE_MILLIS = 15L * 60 * 1000
|
||||
}
|
||||
}
|
||||
@@ -1,6 +1,5 @@
|
||||
package de.jeanlucmakiola.calendula.data.reminders
|
||||
|
||||
import de.jeanlucmakiola.calendula.domain.runsMidnightToMidnight
|
||||
import de.jeanlucmakiola.calendula.ui.common.timeOfDayFormatter
|
||||
import java.time.DayOfWeek
|
||||
import java.time.Instant
|
||||
@@ -12,8 +11,6 @@ import java.time.format.FormatStyle
|
||||
import java.time.format.TextStyle
|
||||
import java.time.temporal.ChronoUnit
|
||||
import java.util.Locale
|
||||
import kotlinx.datetime.toKotlinTimeZone
|
||||
import kotlin.time.Instant as KInstant
|
||||
|
||||
/**
|
||||
* The one line of time context in a reminder notification. Pure so it can be
|
||||
@@ -35,8 +32,7 @@ import kotlin.time.Instant as KInstant
|
||||
* - all-day, multi-day: "Tomorrow – 12 Jun 2026" (relative start, explicit end)
|
||||
*
|
||||
* All-day instances store UTC midnights with an exclusive end, so they are read
|
||||
* in UTC and the end day is the last *covered* day (issue #308). A timed event
|
||||
* from local midnight to local midnight reads like one too, in [zone] (#296).
|
||||
* in UTC and the end day is the last *covered* day (issue #308).
|
||||
*/
|
||||
fun reminderTimeText(
|
||||
beginMillis: Long,
|
||||
@@ -51,17 +47,11 @@ fun reminderTimeText(
|
||||
tomorrowLabel: String,
|
||||
yesterdayLabel: String,
|
||||
): String {
|
||||
val wholeDays = !isAllDay && runsMidnightToMidnight(
|
||||
KInstant.fromEpochMilliseconds(beginMillis),
|
||||
KInstant.fromEpochMilliseconds(endMillis),
|
||||
zone.toKotlinTimeZone(),
|
||||
)
|
||||
if (isAllDay || wholeDays) {
|
||||
val dayZone = if (isAllDay) ZoneOffset.UTC else zone
|
||||
if (isAllDay) {
|
||||
val dateFormat = DateTimeFormatter.ofLocalizedDate(FormatStyle.MEDIUM).withLocale(locale)
|
||||
// (atZone().toLocalDate() instead of LocalDate.ofInstant — API 34+)
|
||||
val firstDay = Instant.ofEpochMilli(beginMillis).atZone(dayZone).toLocalDate()
|
||||
val lastDay = Instant.ofEpochMilli(endMillis).atZone(dayZone).toLocalDate()
|
||||
val firstDay = Instant.ofEpochMilli(beginMillis).atZone(ZoneOffset.UTC).toLocalDate()
|
||||
val lastDay = Instant.ofEpochMilli(endMillis).atZone(ZoneOffset.UTC).toLocalDate()
|
||||
.minusDays(1)
|
||||
.coerceAtLeast(firstDay)
|
||||
val start = relativeDayPrefix(
|
||||
|
||||
@@ -1,35 +1,18 @@
|
||||
package de.jeanlucmakiola.calendula.domain
|
||||
|
||||
import kotlinx.datetime.TimeZone
|
||||
import kotlinx.datetime.atStartOfDayIn
|
||||
import kotlin.time.Instant
|
||||
|
||||
/** Lower values appear first in lists and get the upper visible lanes in grids. */
|
||||
fun EventInstance.displayPriority(zone: TimeZone): Int = when {
|
||||
isCrossedOut -> 3
|
||||
spansMultipleDays(zone) -> 0
|
||||
coversWholeDays(zone) -> 1
|
||||
isAllDay -> 1
|
||||
else -> 2
|
||||
}
|
||||
|
||||
/**
|
||||
* Shared order for agenda and split day lists. Grid bars add their lane geometry.
|
||||
* Each event's priority is worked out once, not on every comparison.
|
||||
*/
|
||||
fun List<EventInstance>.sortedForDisplay(zone: TimeZone): List<EventInstance> =
|
||||
map { Triple(it, it.displayPriority(zone), it.displayStart(zone)) }
|
||||
.sortedWith(
|
||||
compareBy<Triple<EventInstance, Int, Instant>> { it.second }
|
||||
.thenBy { it.third }
|
||||
.thenBy { it.first.title }
|
||||
.thenBy { it.first.instanceId },
|
||||
)
|
||||
.map { it.first }
|
||||
|
||||
/**
|
||||
* Where an event starts for ordering: a whole-day event at local midnight of its
|
||||
* first day, since an all-day one is stored at UTC midnight and would otherwise
|
||||
* sort around timed events by the device's offset (#296).
|
||||
*/
|
||||
internal fun EventInstance.displayStart(zone: TimeZone): Instant =
|
||||
if (coversWholeDays(zone)) spanFirstDay(zone).atStartOfDayIn(zone) else start
|
||||
/** Shared order for agenda and split day lists. Grid bars add their lane geometry. */
|
||||
fun eventDisplayComparator(zone: TimeZone): Comparator<EventInstance> =
|
||||
compareBy<EventInstance> { it.displayPriority(zone) }
|
||||
.thenBy { it.start }
|
||||
.thenBy { it.title }
|
||||
.thenBy { it.instanceId }
|
||||
@@ -1,7 +1,5 @@
|
||||
package de.jeanlucmakiola.calendula.domain
|
||||
|
||||
import de.jeanlucmakiola.calendula.domain.reminders.FixedTimeReminder
|
||||
import de.jeanlucmakiola.calendula.domain.reminders.splitTimedReminders
|
||||
import kotlinx.datetime.LocalDate
|
||||
import kotlinx.datetime.LocalDateTime
|
||||
import kotlinx.datetime.LocalTime
|
||||
@@ -42,12 +40,6 @@ data class EventForm(
|
||||
val description: String = "",
|
||||
/** Reminder lead times in minutes before the start, deduplicated. */
|
||||
val reminders: List<Int> = emptyList(),
|
||||
/**
|
||||
* "N days before at HH:MM" reminders of a timed event (#459), written as lead
|
||||
* times measured from [start] at save time. Ignored while [isAllDay], so a
|
||||
* round trip through all-day keeps them.
|
||||
*/
|
||||
val fixedReminders: List<FixedTimeReminder> = emptyList(),
|
||||
val availability: Availability = Availability.Busy,
|
||||
val accessLevel: AccessLevel = AccessLevel.Default,
|
||||
/** Confirmed / Tentative / Cancelled (#388). */
|
||||
@@ -256,20 +248,11 @@ internal fun allDayFormTimes(start: LocalDate, endExclusive: LocalDate?): Pair<F
|
||||
internal fun String?.normalizedRrule(): String? = this?.removePrefix("RRULE:")?.takeIf { it.isNotBlank() }
|
||||
|
||||
/**
|
||||
* Whether this form may be saved apart from its series, as one modified
|
||||
* occurrence or as a split-off "this & following" tail. A cancelled exception
|
||||
* row is how Android records a deleted occurrence, and Google reads an inserted
|
||||
* cancelled event as deleted, so either would vanish rather than show struck
|
||||
* through (#388).
|
||||
* Whether this form may be saved as a single modified occurrence. A cancelled
|
||||
* exception row is how Android records a deleted occurrence, so a cancelled one
|
||||
* would vanish rather than show struck through (#388).
|
||||
*/
|
||||
fun EventForm.canSaveApartFromSeries(): Boolean = status != EventStatus.Cancelled
|
||||
|
||||
/**
|
||||
* The status a newly inserted row may carry. Google reads an inserted cancelled
|
||||
* event as deleted, so every new row (a copy, an import, a calendar move or an
|
||||
* exception) starts confirmed instead (#388).
|
||||
*/
|
||||
fun EventStatus.forNewEvent(): EventStatus = if (this == EventStatus.Cancelled) EventStatus.Confirmed else this
|
||||
fun EventForm.canSaveAsOccurrence(): Boolean = status != EventStatus.Cancelled
|
||||
|
||||
/**
|
||||
* Whether this form's times mean something else in [target] — a timed event
|
||||
@@ -294,7 +277,7 @@ fun EventForm.populatedFields(): Set<EventFormField> = buildSet {
|
||||
if (location.isNotBlank()) add(EventFormField.Location)
|
||||
if (description.isNotBlank()) add(EventFormField.Description)
|
||||
if (timezone != null) add(EventFormField.Timezone)
|
||||
if (reminders.isNotEmpty() || (!isAllDay && fixedReminders.isNotEmpty())) add(EventFormField.Reminders)
|
||||
if (reminders.isNotEmpty()) add(EventFormField.Reminders)
|
||||
if (rrule != null) add(EventFormField.Recurrence)
|
||||
if (availability != Availability.Busy) add(EventFormField.Availability)
|
||||
if (status != EventStatus.Confirmed) add(EventFormField.Status)
|
||||
@@ -332,37 +315,12 @@ fun EventForm.problems(deviceZone: TimeZone): Set<EventFormProblem> = buildSet {
|
||||
* cleared so the create resolves to a writable calendar, which lets a read-only
|
||||
* event be copied into an editable one. [instance]'s own times carry over.
|
||||
*/
|
||||
fun EventDetail.toDuplicateForm(
|
||||
canModify: Boolean,
|
||||
zone: TimeZone,
|
||||
knownFixed: Set<FixedTimeReminder> = emptySet(),
|
||||
): EventForm =
|
||||
fun EventDetail.toDuplicateForm(canModify: Boolean, zone: TimeZone): EventForm =
|
||||
toEditForm(
|
||||
beginMillis = instance.start.toEpochMilliseconds(),
|
||||
endMillis = instance.end.toEpochMilliseconds(),
|
||||
zone = zone,
|
||||
).withFixedTimeRemindersRead(knownFixed, zone).copy(
|
||||
).copy(
|
||||
rrule = null,
|
||||
calendarId = instance.calendarId.takeIf { canModify },
|
||||
status = status.forNewEvent(),
|
||||
)
|
||||
|
||||
/**
|
||||
* This form with its timed reminders read back into lead times and
|
||||
* [EventForm.fixedReminders] ([splitTimedReminders]), the wall clock taken in
|
||||
* [deviceZone]. All-day forms come back untouched.
|
||||
*/
|
||||
fun EventForm.withFixedTimeRemindersRead(known: Set<FixedTimeReminder>, deviceZone: TimeZone): EventForm {
|
||||
if (isAllDay || reminders.isEmpty()) return this
|
||||
val split = splitTimedReminders(
|
||||
reminders, startInstant(resolvedZone(deviceZone)), deviceZone, known, wallClock = rrule != null,
|
||||
)
|
||||
return copy(reminders = split.leadMinutes, fixedReminders = (fixedReminders + split.fixed).distinct())
|
||||
}
|
||||
|
||||
/** The offsets [EventForm.fixedReminders] store for this form's start; empty for an all-day form. */
|
||||
fun EventForm.fixedReminderOffsets(deviceZone: TimeZone): List<Int> {
|
||||
if (isAllDay || fixedReminders.isEmpty()) return emptyList()
|
||||
val start = startInstant(resolvedZone(deviceZone))
|
||||
return fixedReminders.map { it.offsetMinutes(start, deviceZone, wallClock = rrule != null) }
|
||||
}
|
||||
@@ -173,11 +173,8 @@ fun EventForm.shiftedByDays(days: Int, deviceZone: TimeZone): EventForm {
|
||||
return copy(start = movedStart, end = (startAt + span).toFormTime(zone))
|
||||
}
|
||||
|
||||
/**
|
||||
* The form with new start and end, each in the form's own zone — a resize. An
|
||||
* all-day event becomes timed: one dragged out of the all-day strip.
|
||||
*/
|
||||
/** The form with new start and end, each in the form's own zone — a resize. All-day is untouched. */
|
||||
fun EventForm.resizedTo(newStart: Instant, newEnd: Instant, deviceZone: TimeZone): EventForm {
|
||||
val timed = copy(isAllDay = false)
|
||||
return timed.withTimes(newStart, newEnd, timed.resolvedZone(deviceZone))
|
||||
if (isAllDay) return this
|
||||
return withTimes(newStart, newEnd, resolvedZone(deviceZone))
|
||||
}
|
||||
@@ -150,20 +150,6 @@ fun EventInstance.spanLastDay(zone: TimeZone): LocalDate {
|
||||
fun EventInstance.spansMultipleDays(zone: TimeZone): Boolean =
|
||||
spanFirstDay(zone) != spanLastDay(zone)
|
||||
|
||||
/**
|
||||
* Whether this event fills whole days in [zone], so the grids and lists lay it
|
||||
* out with the all-day events: an all-day event, or a timed one running from
|
||||
* local midnight to local midnight (#296). The event itself stays timed.
|
||||
*/
|
||||
fun EventInstance.coversWholeDays(zone: TimeZone): Boolean = isAllDay || runsMidnightToMidnight(start, end, zone)
|
||||
|
||||
/** Whether a timed span from [start] to [end] runs from local midnight to local midnight in [zone] (#296). */
|
||||
fun runsMidnightToMidnight(start: Instant, end: Instant, zone: TimeZone): Boolean =
|
||||
end > start && start.isStartOfDay(zone) && end.isStartOfDay(zone)
|
||||
|
||||
private fun Instant.isStartOfDay(zone: TimeZone): Boolean =
|
||||
this == toLocalDateTime(zone).date.atStartOfDayIn(zone)
|
||||
|
||||
data class EventDetail(
|
||||
val instance: EventInstance,
|
||||
val description: String?,
|
||||
|
||||
@@ -2,7 +2,6 @@ package de.jeanlucmakiola.calendula.domain.ics
|
||||
|
||||
import de.jeanlucmakiola.calendula.domain.EventForm
|
||||
import de.jeanlucmakiola.calendula.domain.allDayFormTimes
|
||||
import de.jeanlucmakiola.calendula.domain.forNewEvent
|
||||
import de.jeanlucmakiola.calendula.domain.normalizedRrule
|
||||
import de.jeanlucmakiola.calendula.domain.toFormTime
|
||||
import kotlinx.datetime.TimeZone
|
||||
@@ -36,7 +35,7 @@ fun ParsedIcsEvent.toEventForm(zone: TimeZone): EventForm {
|
||||
description = description.orEmpty(),
|
||||
reminders = semanticReminderMinutes(),
|
||||
availability = availability,
|
||||
status = status.forNewEvent(),
|
||||
status = status,
|
||||
rrule = recurrenceRule.normalizedRrule(),
|
||||
)
|
||||
}
|
||||
@@ -1,87 +0,0 @@
|
||||
package de.jeanlucmakiola.calendula.domain.reminders
|
||||
|
||||
import java.time.Instant
|
||||
import java.time.LocalDate
|
||||
import java.time.LocalTime
|
||||
import java.time.ZoneId
|
||||
import java.time.ZoneOffset
|
||||
|
||||
/** Which day the daily summary (#459) lists, counted from the day it arrives. */
|
||||
enum class DigestDay(val daysAhead: Long) { Today(0), Tomorrow(1) }
|
||||
|
||||
/** 20:00, when the daily summary arrives until changed. */
|
||||
const val DEFAULT_DIGEST_TIME_MINUTES = 1_200
|
||||
|
||||
/**
|
||||
* The daily summary's settings. Calendars in [excludedCalendarIds] are left out
|
||||
* of it; [armedAtMillis] is when its switch, time or day last changed.
|
||||
*/
|
||||
data class DailyDigestSettings(
|
||||
val enabled: Boolean = false,
|
||||
val timeMinutes: Int = DEFAULT_DIGEST_TIME_MINUTES,
|
||||
val day: DigestDay = DigestDay.Tomorrow,
|
||||
val excludedCalendarIds: Set<Long> = emptySet(),
|
||||
val armedAtMillis: Long = 0L,
|
||||
)
|
||||
|
||||
/**
|
||||
* What one scan concluded for the summary: list [dueDay] now (null when nothing
|
||||
* is owed), and wake up again at [nextAlarmMillis].
|
||||
*/
|
||||
data class DigestSchedule(
|
||||
val dueDay: LocalDate?,
|
||||
val nextAlarmMillis: Long,
|
||||
)
|
||||
|
||||
/**
|
||||
* When the summary is owed: a moment in `(lastFiredMillis, nowMillis]` is due.
|
||||
* Only the latest such moment counts — a phone off for three evenings gets one
|
||||
* summary, not three — and only while the day it lists has not passed and is
|
||||
* not [lastListedDay]: each day is listed once.
|
||||
*/
|
||||
fun scheduleDigest(
|
||||
timeMinutes: Int,
|
||||
day: DigestDay,
|
||||
zone: ZoneId,
|
||||
lastFiredMillis: Long,
|
||||
nowMillis: Long,
|
||||
lastListedDay: LocalDate? = null,
|
||||
): DigestSchedule {
|
||||
val time = LocalTime.of(timeMinutes / 60, timeMinutes % 60)
|
||||
val fireAt = { date: LocalDate -> date.atTime(time).atZone(zone).toInstant().toEpochMilli() }
|
||||
val today = Instant.ofEpochMilli(nowMillis).atZone(zone).toLocalDate()
|
||||
val latestDate = if (fireAt(today) <= nowMillis) today else today.minusDays(1)
|
||||
val listed = latestDate.plusDays(day.daysAhead)
|
||||
val dueAt = fireAt(latestDate)
|
||||
val dueDay = listed.takeIf { dueAt > lastFiredMillis && !it.isBefore(today) && it != lastListedDay }
|
||||
return DigestSchedule(dueDay = dueDay, nextAlarmMillis = fireAt(latestDate.plusDays(1)))
|
||||
}
|
||||
|
||||
/**
|
||||
* The occurrences the summary for [day] lists: all-day ones covering it (their
|
||||
* UTC dates), then timed ones overlapping it in [zone], each group in start
|
||||
* order. Calendars in [excludedCalendarIds] are left out.
|
||||
*/
|
||||
fun digestEntries(
|
||||
instances: List<ReminderEventInstance>,
|
||||
day: LocalDate,
|
||||
zone: ZoneId,
|
||||
excludedCalendarIds: Set<Long>,
|
||||
): List<ReminderEventInstance> {
|
||||
val dayStart = day.atStartOfDay(zone).toInstant().toEpochMilli()
|
||||
val dayEnd = day.plusDays(1).atStartOfDay(zone).toInstant().toEpochMilli()
|
||||
val utcDay = day.atStartOfDay(ZoneOffset.UTC).toInstant().toEpochMilli()
|
||||
return instances
|
||||
.asSequence()
|
||||
.filter { it.calendarId !in excludedCalendarIds }
|
||||
.filter {
|
||||
if (it.isAllDay) {
|
||||
it.beginMillis <= utcDay && maxOf(it.endMillis, it.beginMillis + 1) > utcDay
|
||||
} else {
|
||||
it.beginMillis < dayEnd && maxOf(it.endMillis, it.beginMillis + 1) > dayStart
|
||||
}
|
||||
}
|
||||
.distinctBy { occurrenceKey(it.eventId, it.beginMillis) }
|
||||
.sortedWith(compareBy({ !it.isAllDay }, { it.beginMillis }, { it.title }))
|
||||
.toList()
|
||||
}
|
||||
@@ -1,142 +0,0 @@
|
||||
package de.jeanlucmakiola.calendula.domain.reminders
|
||||
|
||||
import kotlinx.datetime.DateTimeUnit
|
||||
import kotlinx.datetime.LocalDateTime
|
||||
import kotlinx.datetime.LocalTime
|
||||
import kotlinx.datetime.TimeZone
|
||||
import kotlinx.datetime.minus
|
||||
import kotlinx.datetime.toInstant
|
||||
import kotlinx.datetime.toLocalDateTime
|
||||
import kotlin.time.Duration.Companion.minutes
|
||||
import kotlin.time.Instant
|
||||
|
||||
/**
|
||||
* A timed event's reminder "[daysBefore] days before, at [minuteOfDay]" (#459).
|
||||
*
|
||||
* The provider only knows lead times, so it is stored as an ordinary `Reminders`
|
||||
* row whose offset is the distance from that wall-clock moment to the start
|
||||
* ([offsetMinutes]) — it fires on every device and in every app. The pattern is
|
||||
* only known to Calendula while it can be read back ([classifyTimedReminder]); the
|
||||
* editor then re-derives the offset whenever the start moves.
|
||||
*/
|
||||
data class FixedTimeReminder(val daysBefore: Int, val minuteOfDay: Int) {
|
||||
|
||||
init {
|
||||
require(daysBefore in 1..MAX_DAYS_BEFORE) { "daysBefore out of range: $daysBefore" }
|
||||
require(minuteOfDay in 0 until MINUTES_PER_DAY) { "minuteOfDay out of range: $minuteOfDay" }
|
||||
}
|
||||
|
||||
/** The wall clock this reminder names for an event starting at [start], read in [zone]. */
|
||||
private fun alarmWallClock(start: Instant, zone: TimeZone): LocalDateTime {
|
||||
val day = start.toLocalDateTime(zone).date.minus(daysBefore, DateTimeUnit.DAY)
|
||||
return LocalDateTime(day, LocalTime(minuteOfDay / 60, minuteOfDay % 60))
|
||||
}
|
||||
|
||||
/**
|
||||
* The provider offset to store for an event starting at [start]: the real
|
||||
* minutes to that moment, or with [wallClock] the minutes on the clock face.
|
||||
* A recurring series stores one offset for every occurrence, so it takes the
|
||||
* wall-clock reading — otherwise an occurrence opened next to a DST change
|
||||
* would bake that hour into all the others.
|
||||
*/
|
||||
fun offsetMinutes(start: Instant, zone: TimeZone, wallClock: Boolean = false): Int {
|
||||
val alarm = alarmWallClock(start, zone)
|
||||
return if (wallClock) {
|
||||
(start.toLocalDateTime(zone).toInstant(TimeZone.UTC) - alarm.toInstant(TimeZone.UTC)).inWholeMinutes.toInt()
|
||||
} else {
|
||||
(start - alarm.toInstant(zone)).inWholeMinutes.toInt()
|
||||
}
|
||||
}
|
||||
|
||||
/** The stored form, `days@minuteOfDay`. */
|
||||
fun toToken(): String = "$daysBefore$TOKEN_SEP$minuteOfDay"
|
||||
|
||||
companion object {
|
||||
/** Two weeks, well inside the four weeks Google Calendar takes for a reminder. */
|
||||
const val MAX_DAYS_BEFORE = 14
|
||||
private const val TOKEN_SEP = "@"
|
||||
|
||||
/** [toToken] read back; null for anything malformed or out of range. */
|
||||
fun parse(token: String?): FixedTimeReminder? {
|
||||
val parts = token?.trim()?.split(TOKEN_SEP) ?: return null
|
||||
if (parts.size != 2) return null
|
||||
val days = parts[0].toIntOrNull() ?: return null
|
||||
val minute = parts[1].toIntOrNull() ?: return null
|
||||
if (days !in 1..MAX_DAYS_BEFORE || minute !in 0 until MINUTES_PER_DAY) return null
|
||||
return FixedTimeReminder(days, minute)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* The "N days before at HH:MM" a raw offset lands on for an event starting at
|
||||
* [start], or null when it fires on the start's own day (or after it), or
|
||||
* further back than [FixedTimeReminder.MAX_DAYS_BEFORE]. [wallClock] reads the
|
||||
* offset as [FixedTimeReminder.offsetMinutes] wrote it.
|
||||
*/
|
||||
fun fixedTimeReminderAt(
|
||||
offsetMinutes: Int,
|
||||
start: Instant,
|
||||
zone: TimeZone,
|
||||
wallClock: Boolean = false,
|
||||
): FixedTimeReminder? {
|
||||
if (offsetMinutes <= 0) return null
|
||||
val startLocal = start.toLocalDateTime(zone)
|
||||
val alarm = if (wallClock) {
|
||||
(startLocal.toInstant(TimeZone.UTC) - offsetMinutes.minutes).toLocalDateTime(TimeZone.UTC)
|
||||
} else {
|
||||
(start - offsetMinutes.minutes).toLocalDateTime(zone)
|
||||
}
|
||||
val startDate = startLocal.date
|
||||
val days = startDate.toEpochDays() - alarm.date.toEpochDays()
|
||||
if (days !in 1..FixedTimeReminder.MAX_DAYS_BEFORE) return null
|
||||
return FixedTimeReminder(days.toInt(), alarm.hour * 60 + alarm.minute)
|
||||
}
|
||||
|
||||
/** A timed event's reminders, read back: plain lead times and the fixed-time ones. */
|
||||
data class TimedReminders(
|
||||
val leadMinutes: List<Int>,
|
||||
val fixed: List<FixedTimeReminder>,
|
||||
)
|
||||
|
||||
/**
|
||||
* The fixed-time reminder [offsetMinutes] stands for on an event starting at
|
||||
* [start], or null when it reads as a plain lead time. The provider can't say
|
||||
* which an offset was meant as, so only the patterns in [known] — the configured
|
||||
* defaults, past and present, and the ones saved by hand on this device — are
|
||||
* recognised: guessing from the offset's shape alone would turn ordinary leads
|
||||
* ("12 hours before") into fixed-time ones. Where a lead and a known pattern
|
||||
* coincide ("1 day before" on an event at the default's own time) the pattern
|
||||
* wins. A wrong reading fires at the same moment; only a later change of the
|
||||
* start's time of day then treats the reminder the other way.
|
||||
*/
|
||||
fun classifyTimedReminder(
|
||||
offsetMinutes: Int,
|
||||
start: Instant,
|
||||
zone: TimeZone,
|
||||
known: Set<FixedTimeReminder>,
|
||||
wallClock: Boolean = false,
|
||||
): FixedTimeReminder? = fixedTimeReminderAt(offsetMinutes, start, zone, wallClock)?.takeIf { it in known }
|
||||
|
||||
/** Sort a timed event's raw offsets into lead times and fixed-time reminders ([classifyTimedReminder]). */
|
||||
fun splitTimedReminders(
|
||||
offsets: List<Int>,
|
||||
start: Instant,
|
||||
zone: TimeZone,
|
||||
known: Set<FixedTimeReminder>,
|
||||
wallClock: Boolean = false,
|
||||
): TimedReminders {
|
||||
val leads = mutableListOf<Int>()
|
||||
val fixed = mutableListOf<FixedTimeReminder>()
|
||||
offsets.distinct().forEach { offset ->
|
||||
val pattern = classifyTimedReminder(offset, start, zone, known, wallClock)
|
||||
if (pattern != null) fixed += pattern else leads += offset
|
||||
}
|
||||
return TimedReminders(leads.sorted(), fixed.distinct().sortedWith(FIXED_ORDER))
|
||||
}
|
||||
|
||||
/** Most days before first, then by time — the order they fire in. */
|
||||
val FIXED_ORDER: Comparator<FixedTimeReminder> =
|
||||
compareByDescending<FixedTimeReminder> { it.daysBefore }.thenBy { it.minuteOfDay }
|
||||
|
||||
private const val MINUTES_PER_DAY = 1_440
|
||||
@@ -485,8 +485,9 @@ fun CalendarHost(
|
||||
movableCalendarIds = movableCalendarIds,
|
||||
dragEnabled = dragToReschedule,
|
||||
move = { reschedule.move(it) },
|
||||
drops = reschedule.drops,
|
||||
inFlight = reschedule.inFlight,
|
||||
undoStarted = reschedule.undoStarted,
|
||||
abandoned = reschedule.abandoned,
|
||||
edit = onEditEvent,
|
||||
)
|
||||
}
|
||||
|
||||
@@ -59,16 +59,11 @@ import java.util.Locale
|
||||
// split style can list a day with exactly the same visual language instead of
|
||||
// growing a parallel set of event rows.
|
||||
|
||||
/**
|
||||
* A day's header; tapping it opens the Day view. [compact] trims the padding for
|
||||
* the month view's split pane, where vertical space is short (#142).
|
||||
*/
|
||||
@Composable
|
||||
internal fun AgendaDayHeader(
|
||||
date: LocalDate,
|
||||
today: LocalDate,
|
||||
onOpenDay: (LocalDate) -> Unit,
|
||||
compact: Boolean = false,
|
||||
) {
|
||||
Surface(
|
||||
color = MaterialTheme.colorScheme.surface,
|
||||
@@ -84,12 +79,7 @@ internal fun AgendaDayHeader(
|
||||
} else {
|
||||
MaterialTheme.colorScheme.onSurfaceVariant
|
||||
},
|
||||
modifier = Modifier.padding(
|
||||
start = 28.dp,
|
||||
end = 28.dp,
|
||||
top = if (compact) 8.dp else 16.dp,
|
||||
bottom = if (compact) 4.dp else 8.dp,
|
||||
),
|
||||
modifier = Modifier.padding(start = 28.dp, end = 28.dp, top = 16.dp, bottom = 8.dp),
|
||||
)
|
||||
}
|
||||
}
|
||||
@@ -230,11 +220,10 @@ internal fun LazyListScope.agendaDays(
|
||||
dimmed: (EventInstance, LocalDate) -> Boolean,
|
||||
onOpenDay: (LocalDate) -> Unit,
|
||||
onEventClick: (EventInstance) -> Unit,
|
||||
compact: Boolean = false,
|
||||
) {
|
||||
days.forEach { day ->
|
||||
stickyHeader(key = "header-${day.date}") {
|
||||
AgendaDayHeader(date = day.date, today = today, onOpenDay = onOpenDay, compact = compact)
|
||||
AgendaDayHeader(date = day.date, today = today, onOpenDay = onOpenDay)
|
||||
}
|
||||
if (day.events.isEmpty()) {
|
||||
item(key = "placeholder-${day.date}") {
|
||||
@@ -262,6 +251,6 @@ internal fun LazyListScope.agendaDays(
|
||||
)
|
||||
}
|
||||
}
|
||||
item(key = "gap-${day.date}") { Spacer(Modifier.height(if (compact) 4.dp else 8.dp)) }
|
||||
item(key = "gap-${day.date}") { Spacer(Modifier.height(8.dp)) }
|
||||
}
|
||||
}
|
||||
@@ -1,6 +1,5 @@
|
||||
package de.jeanlucmakiola.calendula.ui.agenda
|
||||
|
||||
import de.jeanlucmakiola.calendula.ui.common.FabClearance
|
||||
import de.jeanlucmakiola.calendula.ui.common.PublishChrome
|
||||
import de.jeanlucmakiola.calendula.ui.common.ScreenActions
|
||||
import de.jeanlucmakiola.calendula.ui.common.ScreenBody
|
||||
@@ -433,7 +432,7 @@ private fun AgendaList(
|
||||
modifier = modifier.nestedScroll(loadOnScrollUp),
|
||||
state = listState,
|
||||
// Bottom inset clears the FAB stack so the last row stays tappable.
|
||||
contentPadding = PaddingValues(top = 8.dp, bottom = FabClearance),
|
||||
contentPadding = PaddingValues(top = 8.dp, bottom = 96.dp),
|
||||
) {
|
||||
agendaDays(
|
||||
days = days,
|
||||
|
||||
@@ -1,8 +1,7 @@
|
||||
package de.jeanlucmakiola.calendula.ui.agenda
|
||||
|
||||
import de.jeanlucmakiola.calendula.domain.EventInstance
|
||||
import de.jeanlucmakiola.calendula.domain.coversWholeDays
|
||||
import de.jeanlucmakiola.calendula.domain.sortedForDisplay
|
||||
import de.jeanlucmakiola.calendula.domain.eventDisplayComparator
|
||||
import de.jeanlucmakiola.calendula.domain.FailureReason
|
||||
import de.jeanlucmakiola.calendula.domain.spanFirstDay
|
||||
import de.jeanlucmakiola.calendula.domain.spanLastDay
|
||||
@@ -19,7 +18,7 @@ import kotlin.time.Instant
|
||||
* surface only formats the instants into its own locale/24h string.
|
||||
*/
|
||||
sealed interface AgendaTimeLabel {
|
||||
/** An event filling whole days (#296), or a whole in-between day of a multi-day span. */
|
||||
/** An all-day event, or a whole in-between day of a multi-day span. */
|
||||
data object AllDay : AgendaTimeLabel
|
||||
/** The first day of a multi-day timed event: when it begins. */
|
||||
data class Starts(val start: Instant) : AgendaTimeLabel
|
||||
@@ -31,7 +30,7 @@ sealed interface AgendaTimeLabel {
|
||||
|
||||
/** The [AgendaTimeLabel] for [event] as it appears on [day], resolved in [zone]. */
|
||||
fun agendaTimeLabel(event: EventInstance, day: LocalDate, zone: TimeZone): AgendaTimeLabel {
|
||||
if (event.coversWholeDays(zone)) return AgendaTimeLabel.AllDay
|
||||
if (event.isAllDay) return AgendaTimeLabel.AllDay
|
||||
val firstDay = event.spanFirstDay(zone)
|
||||
val lastDay = event.spanLastDay(zone)
|
||||
return when {
|
||||
@@ -88,7 +87,7 @@ fun groupAgendaDays(
|
||||
return byDay.map { (date, dayEvents) ->
|
||||
AgendaDay(
|
||||
date = date,
|
||||
events = dayEvents.sortedForDisplay(zone),
|
||||
events = dayEvents.sortedWith(eventDisplayComparator(zone)),
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1,6 +1,5 @@
|
||||
package de.jeanlucmakiola.calendula.ui.common
|
||||
|
||||
import android.content.Context
|
||||
import androidx.compose.runtime.Composable
|
||||
import androidx.compose.runtime.remember
|
||||
import androidx.compose.ui.platform.LocalContext
|
||||
@@ -73,13 +72,11 @@ fun accountGroupTitle(group: CalendarAccountGroup): String {
|
||||
@Composable
|
||||
fun sourceAppName(accountType: String): String {
|
||||
val context = LocalContext.current
|
||||
return remember(accountType) { sourceAppLabel(context, accountType) }
|
||||
}
|
||||
|
||||
/** [sourceAppName] outside composition, e.g. for notification channel groups. */
|
||||
fun sourceAppLabel(context: Context, accountType: String): String {
|
||||
val pm = context.packageManager
|
||||
return sourceAppPackages(context, accountType).firstNotNullOfOrNull { pkg ->
|
||||
runCatching { pm.getApplicationLabel(pm.getApplicationInfo(pkg, 0)).toString() }.getOrNull()
|
||||
} ?: accountType
|
||||
return remember(accountType) {
|
||||
val pm = context.packageManager
|
||||
val packages = sourceAppPackages(context, accountType)
|
||||
packages.firstNotNullOfOrNull { pkg ->
|
||||
runCatching { pm.getApplicationLabel(pm.getApplicationInfo(pkg, 0)).toString() }.getOrNull()
|
||||
} ?: accountType
|
||||
}
|
||||
}
|
||||
@@ -38,9 +38,6 @@ import de.jeanlucmakiola.calendula.R
|
||||
/** The standard FAB's size, shared by the selection bar that unrolls from it (#141). */
|
||||
val FabSize = 56.dp
|
||||
|
||||
/** Bottom inset that lets a scrolling view's last row or hour scroll clear of the FAB. */
|
||||
val FabClearance = 96.dp
|
||||
|
||||
/** What the FAB is while an event is selected (#141): the toggle for its action bar. */
|
||||
@Stable
|
||||
class FabSelection(
|
||||
|
||||
@@ -8,9 +8,9 @@ import java.util.Locale
|
||||
* out in [locale]'s own order, with the year shown only when [date] falls outside
|
||||
* [currentYear].
|
||||
*
|
||||
* Pass [skeleton] *without* a year field, e.g. "LLLL" for a month. A skeleton
|
||||
* is a field list, so wanting the year is just asking for one more field; the
|
||||
* locale still decides where it lands ("July 2026" vs "2026年7月").
|
||||
* Pass [skeleton] *without* a year field — "LLLL" for a month, "EEEdMMM" for a
|
||||
* day. A skeleton is a field list, so wanting the year is just asking for one
|
||||
* more field; the locale still decides where it lands ("July 2026" vs "2026年7月").
|
||||
*
|
||||
* Dropping the year in the current year is the one bit of policy here: the title
|
||||
* sits directly above a grid that already says which year it is, and the year's
|
||||
|
||||
@@ -15,7 +15,6 @@ import de.jeanlucmakiola.calendula.domain.EventInstance
|
||||
import de.jeanlucmakiola.calendula.domain.RecurringWriteScope
|
||||
import de.jeanlucmakiola.calendula.domain.atOccurrence
|
||||
import de.jeanlucmakiola.calendula.domain.toDuplicateForm
|
||||
import de.jeanlucmakiola.calendula.data.prefs.SettingsPrefs
|
||||
import de.jeanlucmakiola.floret.android.stateWhileSubscribed
|
||||
import de.jeanlucmakiola.floret.di.IoDispatcher
|
||||
import kotlinx.coroutines.CoroutineDispatcher
|
||||
@@ -44,7 +43,6 @@ class EventActionsViewModel @Inject constructor(
|
||||
private val icsExporter: IcsExporter,
|
||||
@IoDispatcher private val io: CoroutineDispatcher,
|
||||
private val zoneSource: ZoneSource,
|
||||
private val settingsPrefs: SettingsPrefs,
|
||||
) : ViewModel() {
|
||||
|
||||
/** Every calendar by id, for what a selected event's bar may offer. */
|
||||
@@ -67,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, zoneSource.current(), settingsPrefs.knownFixedTimeReminders.first())
|
||||
return detail.toDuplicateForm(canModify, zoneSource.current())
|
||||
}
|
||||
|
||||
/** A staged `.ics` for [event], or null — reported — when it can't be built. */
|
||||
|
||||
@@ -68,6 +68,7 @@ fun EventMoveHost(
|
||||
),
|
||||
onSelect = viewModel::moveWithScope,
|
||||
onDismiss = viewModel::cancelScope,
|
||||
allowOccurrence = !pending.seriesOnly,
|
||||
allowSeries = !pending.occurrenceOnly,
|
||||
reason = stringResource(R.string.event_move_occurrence_only)
|
||||
.takeIf { pending.occurrenceOnly },
|
||||
@@ -90,11 +91,7 @@ fun EventMoveHost(
|
||||
MoveOutcome.Undone -> stringResource(R.string.event_move_undone)
|
||||
MoveOutcome.WriteDenied -> stringResource(R.string.event_move_write_denied)
|
||||
MoveOutcome.Gone -> stringResource(R.string.event_move_gone)
|
||||
MoveOutcome.Stale -> stringResource(R.string.event_move_stale)
|
||||
MoveOutcome.Skipped -> stringResource(R.string.event_move_skipped)
|
||||
MoveOutcome.QueueFull -> stringResource(R.string.event_move_queue_full)
|
||||
MoveOutcome.BlockedSeriesEnd -> stringResource(R.string.event_move_blocked_series_end)
|
||||
MoveOutcome.BlockedCancelledSeries -> stringResource(R.string.event_move_blocked_cancelled_series)
|
||||
MoveOutcome.Failed -> stringResource(R.string.event_move_failed)
|
||||
}
|
||||
|
||||
|
||||
@@ -1,15 +1,12 @@
|
||||
package de.jeanlucmakiola.calendula.ui.common
|
||||
|
||||
import androidx.compose.animation.core.animateFloatAsState
|
||||
import kotlinx.coroutines.delay
|
||||
import androidx.compose.animation.core.tween
|
||||
import androidx.compose.runtime.rememberUpdatedState
|
||||
import androidx.compose.runtime.Composable
|
||||
import androidx.compose.runtime.Immutable
|
||||
import androidx.compose.runtime.LaunchedEffect
|
||||
import androidx.compose.runtime.compositionLocalOf
|
||||
import androidx.compose.runtime.getValue
|
||||
import androidx.compose.runtime.mutableStateOf
|
||||
import androidx.compose.runtime.mutableIntStateOf
|
||||
import androidx.compose.runtime.remember
|
||||
import androidx.compose.runtime.setValue
|
||||
import androidx.compose.ui.res.stringResource
|
||||
@@ -19,7 +16,6 @@ import de.jeanlucmakiola.calendula.R
|
||||
import de.jeanlucmakiola.calendula.domain.EventInstance
|
||||
import kotlinx.coroutines.flow.MutableStateFlow
|
||||
import kotlinx.coroutines.flow.StateFlow
|
||||
import java.util.concurrent.atomic.AtomicLong
|
||||
|
||||
/**
|
||||
* Drag-to-reschedule wiring (#68), provided once at `CalendarHost` and read by
|
||||
@@ -41,18 +37,24 @@ class EventMoveScope(
|
||||
val dragEnabled: Boolean,
|
||||
/**
|
||||
* Hand a drop to the writer. Returns nothing on purpose: a drop is answered
|
||||
* before its write resolves, so [drops] — not a return value — is what tells
|
||||
* a held copy whether anything landed.
|
||||
* before its write resolves, so [abandoned] — not a return value — is what
|
||||
* tells a held copy that nothing landed.
|
||||
*/
|
||||
val move: (MoveRequest) -> Unit,
|
||||
/**
|
||||
* Each drop's progress by its token — see `RescheduleViewModel.drops`. A flow
|
||||
* rather than a value so this scope stays the same object across a move —
|
||||
* every visible block reads it as a composition local.
|
||||
* True while a dropped event is being written, including the time its scope
|
||||
* dialog is up. A flow rather than a value so this scope stays the same
|
||||
* object across a move — every visible block reads it as a composition local.
|
||||
*/
|
||||
val drops: StateFlow<DropStates>,
|
||||
/** The undo write that just began — see `RescheduleViewModel.undoStarted`. */
|
||||
val undoStarted: StateFlow<UndoStart?>,
|
||||
val inFlight: StateFlow<Boolean>,
|
||||
/** Ticks when an undo write begins — see `RescheduleViewModel.undoStarted`. */
|
||||
val undoStarted: StateFlow<Int>,
|
||||
/**
|
||||
* Ticks when a drop ends with nothing landing — see
|
||||
* `RescheduleViewModel.abandoned`. [move] answers before the write is
|
||||
* resolved, so this is what tells a held copy to stop waiting.
|
||||
*/
|
||||
val abandoned: StateFlow<Int>,
|
||||
/** Open an event in the edit form — the pointer-free route to the same change. */
|
||||
val edit: (EventInstance) -> Unit,
|
||||
) {
|
||||
@@ -61,42 +63,30 @@ class EventMoveScope(
|
||||
|
||||
val LocalEventMove = compositionLocalOf<EventMoveScope?> { null }
|
||||
|
||||
private val moveTokens = AtomicLong()
|
||||
private val NEVER_IN_FLIGHT = MutableStateFlow(false)
|
||||
|
||||
/** A fresh identity for one drop or undo, unique for the process. */
|
||||
fun nextMoveToken(): Long = moveTokens.incrementAndGet()
|
||||
private val NEVER_UNDONE = MutableStateFlow(0)
|
||||
|
||||
/** How many abandoned drops [DropStates] remembers — far more than can be on screen at once. */
|
||||
private const val ABANDONED_KEPT = 32
|
||||
|
||||
/** Per-drop progress, by token — see `RescheduleViewModel.drops`. */
|
||||
@Immutable
|
||||
data class DropStates(
|
||||
val pending: Set<Long> = emptySet(),
|
||||
val abandoned: Set<Long> = emptySet(),
|
||||
) {
|
||||
fun started(token: Long): DropStates = copy(pending = pending + token)
|
||||
|
||||
fun ended(token: Long, landed: Boolean): DropStates = copy(
|
||||
pending = pending - token,
|
||||
// Insertion-ordered, so the oldest go first.
|
||||
abandoned = if (landed) abandoned else (abandoned + token).let { kept ->
|
||||
if (kept.size > ABANDONED_KEPT) kept.drop(kept.size - ABANDONED_KEPT).toSet() else kept
|
||||
},
|
||||
)
|
||||
}
|
||||
|
||||
private val NO_DROPS = MutableStateFlow(DropStates())
|
||||
|
||||
private val NEVER_UNDONE = MutableStateFlow<UndoStart?>(null)
|
||||
private val NEVER_ABANDONED = MutableStateFlow(0)
|
||||
|
||||
/**
|
||||
* Every drop's progress — empty wherever moving is off. A drag overlay keeps
|
||||
* the token of its own drop and holds its copy while that token is pending.
|
||||
* Whether a dropped event is still being written — false wherever moving is off.
|
||||
* The drag overlays hold a landed block on its target for this window.
|
||||
*/
|
||||
@Composable
|
||||
fun dropStates(): DropStates {
|
||||
val flow = LocalEventMove.current?.drops ?: NO_DROPS
|
||||
fun moveInFlight(): Boolean {
|
||||
val flow = LocalEventMove.current?.inFlight ?: NEVER_IN_FLIGHT
|
||||
return flow.collectAsStateWithLifecycle().value
|
||||
}
|
||||
|
||||
/**
|
||||
* How many drops have ended with nothing landing. Read as a plain count so a
|
||||
* drag overlay can capture it at the moment of the drop and tell, later, whether
|
||||
* *its own* drop was one of them.
|
||||
*/
|
||||
@Composable
|
||||
fun abandonedMoves(): Int {
|
||||
val flow = LocalEventMove.current?.abandoned ?: NEVER_ABANDONED
|
||||
return flow.collectAsStateWithLifecycle().value
|
||||
}
|
||||
|
||||
@@ -105,53 +95,17 @@ fun dropStates(): DropStates {
|
||||
* this composable came on screen.
|
||||
*/
|
||||
@Composable
|
||||
fun OnUndoStarted(onUndo: (UndoStart) -> Unit) {
|
||||
fun OnUndoStarted(onUndo: () -> Unit) {
|
||||
val flow = LocalEventMove.current?.undoStarted ?: NEVER_UNDONE
|
||||
val start by flow.collectAsStateWithLifecycle()
|
||||
var seen by remember { mutableStateOf(start) }
|
||||
LaunchedEffect(start) {
|
||||
val started = start
|
||||
if (started == null || started == seen) return@LaunchedEffect
|
||||
seen = started
|
||||
onUndo(started)
|
||||
val tick by flow.collectAsStateWithLifecycle()
|
||||
var seen by remember { mutableIntStateOf(tick) }
|
||||
LaunchedEffect(tick) {
|
||||
if (tick == seen) return@LaunchedEffect
|
||||
seen = tick
|
||||
onUndo()
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* The life of a drop parked by a newer pickup (#494): held while its [token]
|
||||
* is pending, then a beat after the grid [seated] it — or [timeoutMillis] if it
|
||||
* never does — handed over and faded, then released. Returns the copy's alpha.
|
||||
* An abandoned drop skips the wait; nothing is coming to seat it.
|
||||
*/
|
||||
@Composable
|
||||
fun rememberHeldSettle(
|
||||
token: Long,
|
||||
seated: Boolean,
|
||||
timeoutMillis: Long,
|
||||
onHandOver: () -> Unit,
|
||||
onRelease: () -> Unit,
|
||||
): Float {
|
||||
val drops = dropStates()
|
||||
val pending = token in drops.pending
|
||||
val abandoned = token in drops.abandoned
|
||||
val handOver by rememberUpdatedState(onHandOver)
|
||||
val release by rememberUpdatedState(onRelease)
|
||||
var fading by remember(token) { mutableStateOf(false) }
|
||||
LaunchedEffect(token, pending, abandoned, seated) {
|
||||
if (pending) return@LaunchedEffect
|
||||
if (!abandoned) delay(if (seated) SETTLE_GRACE_MILLIS else timeoutMillis)
|
||||
fading = true
|
||||
handOver()
|
||||
delay(SETTLE_FADE_MILLIS.toLong())
|
||||
release()
|
||||
}
|
||||
return animateFloatAsState(
|
||||
targetValue = if (fading) 0f else 1f,
|
||||
animationSpec = tween(SETTLE_FADE_MILLIS),
|
||||
label = "held-settle",
|
||||
).value
|
||||
}
|
||||
|
||||
/** Opacity the source block keeps while its floating copy travels. */
|
||||
const val GHOST_ALPHA: Float = 0.3f
|
||||
|
||||
|
||||
@@ -3,12 +3,15 @@ package de.jeanlucmakiola.calendula.ui.common
|
||||
import androidx.compose.runtime.Composable
|
||||
import androidx.compose.runtime.remember
|
||||
import androidx.compose.ui.graphics.Color
|
||||
import androidx.compose.ui.platform.LocalDensity
|
||||
import androidx.compose.ui.text.AnnotatedString
|
||||
import androidx.compose.ui.text.SpanStyle
|
||||
import androidx.compose.ui.text.TextStyle
|
||||
import androidx.compose.ui.text.buildAnnotatedString
|
||||
import androidx.compose.ui.text.font.FontWeight
|
||||
import androidx.compose.ui.text.rememberTextMeasurer
|
||||
import androidx.compose.ui.text.withStyle
|
||||
import androidx.compose.ui.unit.Dp
|
||||
import androidx.compose.ui.unit.sp
|
||||
import de.jeanlucmakiola.floret.locale.currentLocale
|
||||
|
||||
@@ -42,17 +45,33 @@ fun inlineTimeLabel(time: String?, title: String, timeInk: Color): AnnotatedStri
|
||||
append(title)
|
||||
}
|
||||
|
||||
/**
|
||||
* The characters of title that have to survive a time prefix for it to be worth
|
||||
* its place — lowercase Latin of average advance, priced at the surface's own
|
||||
* text style rather than guessed in dp.
|
||||
*/
|
||||
private const val TITLE_SAMPLE = "notepad"
|
||||
|
||||
/** The widest wall-clock time in either convention: two-digit hour, and a meridiem in 12-hour. */
|
||||
private const val SAMPLE_HOUR = 12
|
||||
private const val SAMPLE_MINUTE = 45
|
||||
|
||||
/**
|
||||
* The widest time the current convention writes, for pricing a time prefix by
|
||||
* measurement: it follows the 12/24-hour setting and the locale's own format.
|
||||
* The narrowest run of [style] text that may carry a time in front of a title:
|
||||
* wide enough for the widest time in the current convention plus [TITLE_SAMPLE].
|
||||
*
|
||||
* Measured rather than a device breakpoint, so it follows the font scale, the
|
||||
* 12/24-hour setting, the locale's own time format and whatever else has
|
||||
* already been taken off the width.
|
||||
*/
|
||||
@Composable
|
||||
fun rememberWidestTimeSample(): String {
|
||||
fun rememberInlineTimeWidth(style: TextStyle): Dp {
|
||||
val measurer = rememberTextMeasurer()
|
||||
val density = LocalDensity.current
|
||||
val locale = currentLocale()
|
||||
val is24Hour = LocalUse24HourFormat.current
|
||||
return remember(is24Hour, locale) { formatTimeOfDay(SAMPLE_HOUR, SAMPLE_MINUTE, is24Hour, locale) }
|
||||
val sample = formatTimeOfDay(SAMPLE_HOUR, SAMPLE_MINUTE, LocalUse24HourFormat.current, locale)
|
||||
return remember(sample, style, density, measurer) {
|
||||
val label = inlineTimeLabel(sample, TITLE_SAMPLE, Color.Unspecified)
|
||||
with(density) { measurer.measure(label, style).size.width.toDp() }
|
||||
}
|
||||
}
|
||||
@@ -1,216 +0,0 @@
|
||||
package de.jeanlucmakiola.calendula.ui.common
|
||||
|
||||
import androidx.compose.foundation.layout.Arrangement
|
||||
import androidx.compose.foundation.layout.Column
|
||||
import androidx.compose.foundation.layout.Row
|
||||
import androidx.compose.foundation.layout.Spacer
|
||||
import androidx.compose.foundation.layout.fillMaxWidth
|
||||
import androidx.compose.foundation.layout.height
|
||||
import androidx.compose.foundation.layout.padding
|
||||
import androidx.compose.foundation.layout.width
|
||||
import androidx.compose.foundation.shape.RoundedCornerShape
|
||||
import androidx.compose.material3.FilledTonalButton
|
||||
import androidx.compose.material3.MaterialTheme
|
||||
import androidx.compose.material3.Surface
|
||||
import androidx.compose.material3.Text
|
||||
import androidx.compose.runtime.Composable
|
||||
import androidx.compose.runtime.LaunchedEffect
|
||||
import androidx.compose.runtime.getValue
|
||||
import androidx.compose.runtime.mutableStateOf
|
||||
import androidx.compose.runtime.saveable.Saver
|
||||
import androidx.compose.runtime.saveable.rememberSaveable
|
||||
import androidx.compose.runtime.setValue
|
||||
import androidx.compose.ui.Alignment
|
||||
import androidx.compose.ui.Modifier
|
||||
import androidx.compose.ui.res.pluralStringResource
|
||||
import androidx.compose.ui.res.stringResource
|
||||
import androidx.compose.ui.unit.dp
|
||||
import de.jeanlucmakiola.calendula.R
|
||||
import de.jeanlucmakiola.calendula.data.prefs.FixedTimeOverride
|
||||
import de.jeanlucmakiola.calendula.domain.reminders.FixedTimeReminder
|
||||
import de.jeanlucmakiola.floret.components.CustomExpandRow
|
||||
import de.jeanlucmakiola.floret.components.DialogAmountField
|
||||
import de.jeanlucmakiola.floret.components.FullScreenPicker
|
||||
import de.jeanlucmakiola.floret.components.GroupedHint
|
||||
import de.jeanlucmakiola.floret.components.GroupedRow
|
||||
import de.jeanlucmakiola.floret.components.Position
|
||||
import de.jeanlucmakiola.floret.locale.currentLocale
|
||||
import kotlinx.datetime.LocalTime
|
||||
|
||||
/** "1 day before at 20:00", in the app's 12/24-hour convention. */
|
||||
@Composable
|
||||
fun fixedTimeReminderLabel(reminder: FixedTimeReminder): String = stringResource(
|
||||
R.string.reminder_fixed_time,
|
||||
pluralStringResource(R.plurals.reminder_days, reminder.daysBefore, reminder.daysBefore),
|
||||
formatMinuteOfDay(reminder.minuteOfDay, LocalUse24HourFormat.current, currentLocale()),
|
||||
)
|
||||
|
||||
/**
|
||||
* The "N days before at HH:MM" editor (#459): a day count and a time, read as
|
||||
* one sentence. Seeded from [initial]; [onValueChange] follows every edit (null
|
||||
* while the day count is out of range). With a [confirmLabel] it carries its own
|
||||
* confirm, reporting through [onConfirm]; without one the host picker commits
|
||||
* from its actions slot. [connected] gives it the shape that meets a row above it.
|
||||
*/
|
||||
@Composable
|
||||
fun FixedTimeReminderEditor(
|
||||
initial: FixedTimeReminder,
|
||||
modifier: Modifier = Modifier,
|
||||
confirmLabel: String? = null,
|
||||
onConfirm: (FixedTimeReminder) -> Unit = {},
|
||||
onValueChange: (FixedTimeReminder?) -> Unit = {},
|
||||
connected: Boolean = true,
|
||||
) {
|
||||
var daysText by rememberSaveable { mutableStateOf(initial.daysBefore.toString()) }
|
||||
var minuteOfDay by rememberSaveable { mutableStateOf(initial.minuteOfDay) }
|
||||
var pickingTime by rememberSaveable { mutableStateOf(false) }
|
||||
val days = daysText.toIntOrNull()?.takeIf { it in 1..FixedTimeReminder.MAX_DAYS_BEFORE }
|
||||
val value = days?.let { FixedTimeReminder(it, minuteOfDay) }
|
||||
LaunchedEffect(value) { onValueChange(value) }
|
||||
|
||||
Surface(
|
||||
color = MaterialTheme.colorScheme.surfaceContainerHigh,
|
||||
shape = if (connected) {
|
||||
RoundedCornerShape(topStart = 6.dp, topEnd = 6.dp, bottomStart = 22.dp, bottomEnd = 22.dp)
|
||||
} else {
|
||||
RoundedCornerShape(22.dp)
|
||||
},
|
||||
modifier = modifier
|
||||
.fillMaxWidth()
|
||||
.padding(horizontal = 16.dp),
|
||||
) {
|
||||
Column(
|
||||
modifier = Modifier.padding(16.dp),
|
||||
verticalArrangement = Arrangement.spacedBy(16.dp),
|
||||
) {
|
||||
Row(verticalAlignment = Alignment.CenterVertically) {
|
||||
DialogAmountField(value = daysText, onValueChange = { daysText = it }, placeholder = "1")
|
||||
Spacer(Modifier.width(12.dp))
|
||||
Text(
|
||||
text = stringResource(R.string.reminder_fixed_days_before_at),
|
||||
style = MaterialTheme.typography.bodyLarge,
|
||||
color = MaterialTheme.colorScheme.onSurfaceVariant,
|
||||
modifier = Modifier.weight(1f, fill = false),
|
||||
)
|
||||
Spacer(Modifier.width(12.dp))
|
||||
FilledTonalButton(onClick = { pickingTime = true }) {
|
||||
Text(formatMinuteOfDay(minuteOfDay, LocalUse24HourFormat.current, currentLocale()))
|
||||
}
|
||||
}
|
||||
Row(verticalAlignment = Alignment.CenterVertically) {
|
||||
Text(
|
||||
text = value?.let { fixedTimeReminderLabel(it) }
|
||||
?: stringResource(R.string.reminder_fixed_days_range, FixedTimeReminder.MAX_DAYS_BEFORE),
|
||||
style = MaterialTheme.typography.bodyMedium,
|
||||
color = MaterialTheme.colorScheme.onSurfaceVariant,
|
||||
modifier = Modifier.weight(1f),
|
||||
)
|
||||
if (confirmLabel != null) {
|
||||
Spacer(Modifier.width(16.dp))
|
||||
FilledTonalButton(
|
||||
enabled = value != null,
|
||||
onClick = { value?.let(onConfirm) },
|
||||
) { Text(confirmLabel) }
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
if (pickingTime) {
|
||||
TimePickerAlert(
|
||||
initial = LocalTime(minuteOfDay / 60, minuteOfDay % 60),
|
||||
onConfirm = {
|
||||
minuteOfDay = it.hour * 60 + it.minute
|
||||
pickingTime = false
|
||||
},
|
||||
onDismiss = { pickingTime = false },
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Picker for a fixed-time default (#459), full-screen: off, or a reminder at a
|
||||
* set time edited in place — and, on a per-calendar picker ([inheritedLabel]
|
||||
* non-null), deferring to the global default, [inherited], which also seeds the
|
||||
* editor. Applies live; the user leaves via back.
|
||||
*/
|
||||
@Composable
|
||||
fun FixedTimeReminderPicker(
|
||||
title: String,
|
||||
selected: FixedTimeOverride,
|
||||
onSelect: (FixedTimeOverride) -> Unit,
|
||||
onDismiss: () -> Unit,
|
||||
inheritedLabel: String? = null,
|
||||
inherited: FixedTimeReminder? = null,
|
||||
) {
|
||||
var current by rememberSaveable(stateSaver = FixedTimeOverrideSaver) { mutableStateOf(selected) }
|
||||
var editing by rememberSaveable { mutableStateOf(false) }
|
||||
// Mirrors [selected] until the first pick, as ReminderDefaultPicker does.
|
||||
var userEdited by rememberSaveable { mutableStateOf(false) }
|
||||
LaunchedEffect(selected) {
|
||||
if (!userEdited) current = selected
|
||||
}
|
||||
fun apply(choice: FixedTimeOverride) {
|
||||
userEdited = true
|
||||
current = choice
|
||||
onSelect(choice)
|
||||
}
|
||||
val chosen = (current as? FixedTimeOverride.At)?.reminder
|
||||
|
||||
FullScreenPicker(title = title, onDismiss = onDismiss) {
|
||||
GroupedHint(text = stringResource(R.string.settings_fixed_reminder_hint))
|
||||
Spacer(Modifier.height(8.dp))
|
||||
val rowCount = if (inheritedLabel != null) 3 else 2
|
||||
if (inheritedLabel != null) {
|
||||
GroupedRow(
|
||||
title = stringResource(R.string.reminder_use_default),
|
||||
summary = inheritedLabel,
|
||||
position = Position.Top,
|
||||
checked = current is FixedTimeOverride.Inherit,
|
||||
onClick = { apply(FixedTimeOverride.Inherit) },
|
||||
)
|
||||
}
|
||||
GroupedRow(
|
||||
title = stringResource(R.string.reminder_none),
|
||||
position = if (rowCount == 3) Position.Middle else Position.Top,
|
||||
checked = current is FixedTimeOverride.Off,
|
||||
onClick = { apply(FixedTimeOverride.Off) },
|
||||
)
|
||||
CustomExpandRow(
|
||||
title = stringResource(R.string.reminder_fixed_at_set_time),
|
||||
summary = chosen?.let { fixedTimeReminderLabel(it) },
|
||||
position = Position.Bottom,
|
||||
expanded = editing,
|
||||
onExpandedChange = { editing = it },
|
||||
checked = chosen != null,
|
||||
) {
|
||||
FixedTimeReminderEditor(
|
||||
initial = chosen ?: inherited ?: DEFAULT_FIXED_TIME_REMINDER,
|
||||
confirmLabel = stringResource(R.string.reminder_custom_set),
|
||||
onConfirm = {
|
||||
apply(FixedTimeOverride.At(it))
|
||||
editing = false
|
||||
},
|
||||
)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/** What the editor offers first: the evening before. */
|
||||
val DEFAULT_FIXED_TIME_REMINDER = FixedTimeReminder(daysBefore = 1, minuteOfDay = 20 * 60)
|
||||
|
||||
private val FixedTimeOverrideSaver = Saver<FixedTimeOverride, String>(
|
||||
save = {
|
||||
when (it) {
|
||||
FixedTimeOverride.Inherit -> "inherit"
|
||||
FixedTimeOverride.Off -> "off"
|
||||
is FixedTimeOverride.At -> it.reminder.toToken()
|
||||
}
|
||||
},
|
||||
restore = {
|
||||
when (it) {
|
||||
"inherit" -> FixedTimeOverride.Inherit
|
||||
"off" -> FixedTimeOverride.Off
|
||||
else -> FixedTimeReminder.parse(it)?.let(FixedTimeOverride::At) ?: FixedTimeOverride.Off
|
||||
}
|
||||
},
|
||||
)
|
||||
@@ -56,8 +56,7 @@ private const val DIMMED_HOUR_ALPHA = 0.3f
|
||||
* The timeline's hour gutter. Scrolls in sync with the day columns through the
|
||||
* shared [scrollState], and while [dragController] holds a lifted block it dims
|
||||
* the hour labels and floats a badge with the drag's current start time at the
|
||||
* row the block would land on. Its content ends in the same [FabClearance]
|
||||
* the day columns do, or the two drift apart at the bottom of the scroll.
|
||||
* row the block would land on.
|
||||
*/
|
||||
@Composable
|
||||
fun HourGutter(
|
||||
@@ -87,8 +86,7 @@ fun HourGutter(
|
||||
.width(GUTTER_WIDTH)
|
||||
.padding(start = GUTTER_CONTENT_START_INSET)
|
||||
.fillMaxHeight()
|
||||
.verticalScroll(scrollState)
|
||||
.padding(bottom = FabClearance),
|
||||
.verticalScroll(scrollState),
|
||||
) {
|
||||
Column {
|
||||
(0 until 24).forEach { h ->
|
||||
|
||||
@@ -70,24 +70,27 @@ data class OutOfViewEvents(val above: TimedBlock?, val below: TimedBlock?) {
|
||||
/** Which edge of the viewport a hidden event sits past. */
|
||||
enum class ViewportEdge { Top, Bottom }
|
||||
|
||||
/** Where [block]'s rendered bottom lands, in minutes — short blocks keep a floor. */
|
||||
internal fun renderedEndMin(block: TimedBlock): Float =
|
||||
maxOf(block.endMin.toFloat(), block.startMin + MIN_EVENT_FRACTION * 60f)
|
||||
|
||||
/**
|
||||
* The blocks of one column lying out of a viewport spanning [topMin]..[bottomMin]
|
||||
* (minutes of the day), nearest first. A block leaves this set as soon as any
|
||||
* part of its [renderedSpan] enters the viewport.
|
||||
* part of its rendered height enters the viewport.
|
||||
*/
|
||||
fun outOfViewEvents(
|
||||
blocks: List<TimedBlock>,
|
||||
topMin: Float,
|
||||
bottomMin: Float,
|
||||
): OutOfViewEvents {
|
||||
val spans = blocks.map { it to it.renderedSpan() }
|
||||
val above = spans
|
||||
.filter { (_, span) -> span.bottomMin <= topMin }
|
||||
.maxWithOrNull(compareBy({ it.second.bottomMin }, { it.first.startMin }))
|
||||
val below = spans
|
||||
.filter { (_, span) -> span.topMin >= bottomMin }
|
||||
.minWithOrNull(compareBy({ it.second.topMin }, { -it.second.bottomMin }))
|
||||
return OutOfViewEvents(above?.first, below?.first)
|
||||
val above = blocks
|
||||
.filter { renderedEndMin(it) <= topMin }
|
||||
.maxWithOrNull(compareBy<TimedBlock>({ renderedEndMin(it) }, { it.startMin }))
|
||||
val below = blocks
|
||||
.filter { it.startMin >= bottomMin }
|
||||
.minWithOrNull(compareBy<TimedBlock>({ it.startMin }, { -renderedEndMin(it) }))
|
||||
return OutOfViewEvents(above, below)
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -104,9 +107,8 @@ fun revealScrollTarget(
|
||||
marginPx: Float,
|
||||
maxScroll: Int,
|
||||
): Int {
|
||||
val span = block.renderedSpan()
|
||||
val startPx = span.topMin / 60f * hourPx
|
||||
val endPx = span.bottomMin / 60f * hourPx
|
||||
val startPx = block.startMin / 60f * hourPx
|
||||
val endPx = renderedEndMin(block) / 60f * hourPx
|
||||
val target = when (edge) {
|
||||
ViewportEdge.Top -> startPx - marginPx
|
||||
ViewportEdge.Bottom -> minOf(endPx + marginPx - viewportPx, startPx - marginPx)
|
||||
@@ -291,7 +293,6 @@ private fun EdgeBar(
|
||||
modifier: Modifier = Modifier,
|
||||
) {
|
||||
block ?: return
|
||||
val span = remember(block) { block.renderedSpan() }
|
||||
val color = eventFill(block.event.color, dark, LocalSoftenColors.current)
|
||||
val label = stringResource(
|
||||
if (edge == ViewportEdge.Top) R.string.timeline_earlier_events else R.string.timeline_later_events,
|
||||
@@ -302,8 +303,8 @@ private fun EdgeBar(
|
||||
.height(EDGE_TOUCH_HEIGHT)
|
||||
.graphicsLayer {
|
||||
val gapPx = when (edge) {
|
||||
ViewportEdge.Top -> scrollState.value - span.bottomMin / 60f * hourPx
|
||||
ViewportEdge.Bottom -> span.topMin / 60f * hourPx -
|
||||
ViewportEdge.Top -> scrollState.value - renderedEndMin(block) / 60f * hourPx
|
||||
ViewportEdge.Bottom -> block.startMin / 60f * hourPx -
|
||||
(scrollState.value + scrollState.viewportSize)
|
||||
}
|
||||
alpha = edgeBarAlpha(gapPx, fadeLeadPx)
|
||||
|
||||
@@ -6,7 +6,7 @@ import dagger.hilt.android.lifecycle.HiltViewModel
|
||||
import de.jeanlucmakiola.calendula.data.time.ZoneSource
|
||||
import de.jeanlucmakiola.calendula.data.calendar.CalendarRepository
|
||||
import de.jeanlucmakiola.calendula.data.calendar.NoSuchEventException
|
||||
import de.jeanlucmakiola.calendula.domain.canSaveApartFromSeries
|
||||
import de.jeanlucmakiola.calendula.domain.canSaveAsOccurrence
|
||||
import de.jeanlucmakiola.calendula.domain.EventDetail
|
||||
import de.jeanlucmakiola.calendula.domain.EventForm
|
||||
import de.jeanlucmakiola.calendula.domain.EventFormProblem
|
||||
@@ -23,19 +23,15 @@ import de.jeanlucmakiola.calendula.domain.resolvedZone
|
||||
import de.jeanlucmakiola.calendula.domain.shiftedByDays
|
||||
import de.jeanlucmakiola.calendula.domain.shiftedTo
|
||||
import de.jeanlucmakiola.calendula.domain.toEditForm
|
||||
import de.jeanlucmakiola.calendula.domain.withFixedTimeRemindersRead
|
||||
import de.jeanlucmakiola.calendula.data.prefs.SettingsPrefs
|
||||
import de.jeanlucmakiola.floret.android.stateWhileSubscribed
|
||||
import de.jeanlucmakiola.floret.di.IoDispatcher
|
||||
import kotlinx.coroutines.CoroutineDispatcher
|
||||
import kotlinx.coroutines.flow.first
|
||||
import kotlinx.coroutines.flow.MutableStateFlow
|
||||
import kotlinx.coroutines.flow.StateFlow
|
||||
import kotlinx.coroutines.flow.asStateFlow
|
||||
import kotlinx.coroutines.flow.catch
|
||||
import kotlinx.coroutines.flow.flowOn
|
||||
import kotlinx.coroutines.flow.map
|
||||
import kotlinx.coroutines.flow.update
|
||||
import kotlinx.coroutines.launch
|
||||
import kotlinx.datetime.DateTimeUnit
|
||||
import kotlinx.datetime.LocalDate
|
||||
@@ -44,21 +40,12 @@ import kotlinx.datetime.atStartOfDayIn
|
||||
import kotlinx.datetime.plus
|
||||
import kotlinx.datetime.toLocalDateTime
|
||||
import kotlin.coroutines.cancellation.CancellationException
|
||||
import kotlin.time.Duration.Companion.seconds
|
||||
import kotlin.time.Instant
|
||||
import kotlin.time.TimeMark
|
||||
import kotlin.time.TimeSource
|
||||
import javax.inject.Inject
|
||||
|
||||
private const val MILLIS_PER_MINUTE = 60_000
|
||||
private const val MINUTES_PER_DAY = 24 * 60
|
||||
|
||||
/** How many drops may wait behind the one in flight before more are refused. */
|
||||
private const val MAX_QUEUED = 8
|
||||
|
||||
/** How long after a write its event's drawn times may still be the old ones. */
|
||||
private val RECENT_WRITE = 3.seconds
|
||||
|
||||
/** Where a dragged event should land. */
|
||||
sealed interface MoveTarget {
|
||||
/** A new start instant — a timeline drag, which moves time and day at once. */
|
||||
@@ -71,10 +58,7 @@ sealed interface MoveTarget {
|
||||
*/
|
||||
data class ByDays(val days: Int) : MoveTarget
|
||||
|
||||
/**
|
||||
* New start and end instants — a timeline resize, which changes the length,
|
||||
* or an all-day event dragged into the time grid, which becomes timed.
|
||||
*/
|
||||
/** New start and end instants — a timeline resize, which changes the length. */
|
||||
data class Span(val start: Instant, val end: Instant) : MoveTarget
|
||||
}
|
||||
|
||||
@@ -87,10 +71,6 @@ data class MoveRequest(
|
||||
val beginMillis: Long,
|
||||
val endMillis: Long,
|
||||
val target: MoveTarget,
|
||||
/** Whether the dragged occurrence is all-day, which decides the zone its day is read in. */
|
||||
val isAllDay: Boolean,
|
||||
/** The drop's own identity, from [nextMoveToken], which the view holding its copy waits on. */
|
||||
val token: Long,
|
||||
)
|
||||
|
||||
/**
|
||||
@@ -100,7 +80,12 @@ data class MoveRequest(
|
||||
* re-derive (`BYDAY=MO,WE`, `2TH`, …), or the shift wouldn't carry the anchor
|
||||
* across the same midnights the occurrence crossed.
|
||||
*/
|
||||
data class MoveScopePrompt(val occurrenceOnly: Boolean, val resize: Boolean = false)
|
||||
data class MoveScopePrompt(
|
||||
val occurrenceOnly: Boolean,
|
||||
val resize: Boolean = false,
|
||||
/** A cancelled series, whose occurrences can't move on their own (#388). */
|
||||
val seriesOnly: Boolean = false,
|
||||
)
|
||||
|
||||
/** The inverse of a completed move, for the undo action. */
|
||||
data class MoveUndo(
|
||||
@@ -109,13 +94,8 @@ data class MoveUndo(
|
||||
val moved: EventForm,
|
||||
/** The form as it stood before the move. */
|
||||
val restored: EventForm,
|
||||
/** The token of the drop this undoes, so the view that drew it carries the right chip back. */
|
||||
val dropToken: Long,
|
||||
)
|
||||
|
||||
/** An undo write that just began: its own [token], and the [dropToken] of the drop it undoes. */
|
||||
data class UndoStart(val token: Long, val dropToken: Long)
|
||||
|
||||
sealed interface MoveOutcome {
|
||||
/**
|
||||
* Written. [startMillis] is where the dragged occurrence now begins, for the
|
||||
@@ -137,28 +117,9 @@ sealed interface MoveOutcome {
|
||||
/** The event vanished (sync, another device) between the read and the write. */
|
||||
data object Gone : MoveOutcome
|
||||
|
||||
/** Drops that waited behind a scope dialog, cancelled rather than run after it (#494). */
|
||||
data object Skipped : MoveOutcome
|
||||
|
||||
/** More drops waiting than the queue holds; this one was not taken. */
|
||||
data object QueueFull : MoveOutcome
|
||||
|
||||
/**
|
||||
* The drop's recurring occurrence may no longer be where it was picked up —
|
||||
* its series was just written — and can't be followed there, so it is not
|
||||
* written (#494).
|
||||
*/
|
||||
data object Stale : MoveOutcome
|
||||
|
||||
/** The drop would push the series past its own `UNTIL`, generating nothing. */
|
||||
data object BlockedSeriesEnd : MoveOutcome
|
||||
|
||||
/**
|
||||
* A cancelled series only moves as a whole, and this drop would change which
|
||||
* days it falls on (#388).
|
||||
*/
|
||||
data object BlockedCancelledSeries : MoveOutcome
|
||||
|
||||
data object Failed : MoveOutcome
|
||||
}
|
||||
|
||||
@@ -175,7 +136,6 @@ class RescheduleViewModel @Inject constructor(
|
||||
private val repository: CalendarRepository,
|
||||
@IoDispatcher private val io: CoroutineDispatcher,
|
||||
private val zoneSource: ZoneSource,
|
||||
private val settingsPrefs: SettingsPrefs,
|
||||
) : ViewModel() {
|
||||
|
||||
private val _scopePrompt = MutableStateFlow<MoveScopePrompt?>(null)
|
||||
@@ -188,32 +148,36 @@ class RescheduleViewModel @Inject constructor(
|
||||
|
||||
private val _inFlight = MutableStateFlow(false)
|
||||
|
||||
/** True while any drop or undo runs or waits — what the confirmation chip holds for. */
|
||||
/**
|
||||
* True from the moment a drop is accepted until its write settles — the
|
||||
* window the dropped block holds its landing position for.
|
||||
*/
|
||||
val inFlight: StateFlow<Boolean> = _inFlight.asStateFlow()
|
||||
|
||||
private val _drops = MutableStateFlow(DropStates())
|
||||
private val _abandoned = MutableStateFlow(0)
|
||||
|
||||
/**
|
||||
* Each drop's own state, by its [MoveRequest.token]: pending from the moment
|
||||
* it is accepted until its write settles, and abandoned once it ends with
|
||||
* nothing on the target day — refused, failed, or its scope dialog dismissed.
|
||||
* Per drop, so a queued drop's held copy waits on its own write and is never
|
||||
* let go by another drop's failure (#253, #494).
|
||||
* Ticks when a drop ends with nothing on the target day: refused outright,
|
||||
* refused before the write, written and failed, or its scope dialog
|
||||
* dismissed. [move] answers before any of that is known, so without this
|
||||
* signal the view that drew the drop held its copy out for the full settle
|
||||
* timeout waiting for a grid that was never going to draw it (#253).
|
||||
*/
|
||||
val drops: StateFlow<DropStates> = _drops.asStateFlow()
|
||||
val abandoned: StateFlow<Int> = _abandoned.asStateFlow()
|
||||
|
||||
private val _undoStarted = MutableStateFlow<UndoStart?>(null)
|
||||
private val _undoStarted = MutableStateFlow(0)
|
||||
|
||||
/**
|
||||
* An undo write the moment it begins, before the provider has anything to
|
||||
* Ticks the moment an undo write begins, before the provider has anything to
|
||||
* re-read, so the view that drew the drop can carry its chip back rather than
|
||||
* let it reappear on the old day. Its fate then reads off [drops].
|
||||
* let it reappear on the old day.
|
||||
*/
|
||||
val undoStarted: StateFlow<UndoStart?> = _undoStarted.asStateFlow()
|
||||
val undoStarted: StateFlow<Int> = _undoStarted.asStateFlow()
|
||||
|
||||
/**
|
||||
* Set while a drop is being prepared, waits on its scope dialog, or is
|
||||
* written. Drops arriving in that window wait in [queue] and run in order.
|
||||
* Set from the moment a drop is accepted until its write settles. Two drops
|
||||
* of the same recurring event inside that window would compute their shift
|
||||
* from the same pre-move occurrence, and the shifts would compound.
|
||||
*/
|
||||
private var busy = false
|
||||
set(value) {
|
||||
@@ -221,22 +185,6 @@ class RescheduleViewModel @Inject constructor(
|
||||
_inFlight.value = value
|
||||
}
|
||||
|
||||
/** Whether a move has been announced since the pipeline was last idle — see [report]. */
|
||||
private var movedThisRun = false
|
||||
|
||||
/** Outcomes waiting for the chip, shown one after another as each is consumed. */
|
||||
private val notices = ArrayDeque<MoveOutcome>()
|
||||
|
||||
/**
|
||||
* When each event's series (by id) or single occurrence (by id and begin)
|
||||
* was last written. The grid draws the old times until it re-reads, so a
|
||||
* drop on a recurring event written moments ago may carry stale times (#494).
|
||||
*/
|
||||
private val written = mutableMapOf<Pair<Long, Long?>, TimeMark>()
|
||||
|
||||
/** Drops that arrived while another was in flight, oldest first (#494). */
|
||||
private val queue = ArrayDeque<MoveRequest>()
|
||||
|
||||
/**
|
||||
* The calendars whose events may be dragged. Nothing below the UI guards
|
||||
* this, so a block outside this set registers no drag gesture at all.
|
||||
@@ -261,63 +209,49 @@ class RescheduleViewModel @Inject constructor(
|
||||
val canRealign: Boolean,
|
||||
/** The series row's DTSTART date after the move — what its `UNTIL` must clear. */
|
||||
val newAnchorDate: LocalDate,
|
||||
) {
|
||||
/** A timed event's new length, rather than an all-day one dragged into the grid. */
|
||||
val isResize: Boolean get() = request.target is MoveTarget.Span && !original.isAllDay
|
||||
}
|
||||
)
|
||||
|
||||
/**
|
||||
* Take a drop: run it now, or queue it behind the ones in flight. False means
|
||||
* nothing will be written — the queue is full — and the drop is marked
|
||||
* abandoned in [drops], so its held copy is let go by the one signal rather
|
||||
* than by every caller remembering to.
|
||||
* Take a drop, unless one is already being written. False means nothing will
|
||||
* be written; [abandoned] ticks for that refusal too, so a held copy is let
|
||||
* go by the one signal rather than by every caller remembering to.
|
||||
*
|
||||
* The Boolean is diagnostic — the tests read it, [EventMoveScope] does not
|
||||
* hand it on. It answers before the write is resolved anyway.
|
||||
* hand it on. A caller that gated on it would be back to releasing its copy
|
||||
* from two places, and it answers before the write is resolved anyway.
|
||||
*/
|
||||
fun move(request: MoveRequest): Boolean {
|
||||
if (queue.size >= MAX_QUEUED) {
|
||||
_drops.update { it.ended(request.token, landed = false) }
|
||||
report(MoveOutcome.QueueFull)
|
||||
if (busy || _scopePrompt.value != null) {
|
||||
_abandoned.value += 1
|
||||
return false
|
||||
}
|
||||
if (_scopePrompt.value != null) {
|
||||
_drops.update { it.ended(request.token, landed = false) }
|
||||
report(MoveOutcome.Skipped)
|
||||
return false
|
||||
}
|
||||
_drops.update { it.started(request.token) }
|
||||
if (busy) queue.addLast(request) else run(request)
|
||||
return true
|
||||
}
|
||||
|
||||
private fun run(request: MoveRequest) {
|
||||
busy = true
|
||||
viewModelScope.launch {
|
||||
val prepared = prepare(request)
|
||||
if (prepared == null) {
|
||||
settle(request.token, landed = false)
|
||||
_abandoned.value += 1
|
||||
busy = false
|
||||
return@launch
|
||||
}
|
||||
// A cancelled series only moves as a whole (#388).
|
||||
val seriesOnly = !prepared.original.canSaveApartFromSeries()
|
||||
if (!prepared.isRecurring || (seriesOnly && prepared.canRealign)) {
|
||||
settle(request.token, write(prepared, RecurringWriteScope.AllEvents))
|
||||
} else if (seriesOnly) {
|
||||
report(MoveOutcome.BlockedCancelledSeries)
|
||||
settle(request.token, landed = false)
|
||||
val seriesOnly = !prepared.original.canSaveAsOccurrence()
|
||||
if (!prepared.isRecurring) {
|
||||
write(prepared, RecurringWriteScope.AllEvents)
|
||||
busy = false
|
||||
} else if (seriesOnly && !prepared.canRealign) {
|
||||
// Neither the occurrence nor the series can take this move.
|
||||
_abandoned.value += 1
|
||||
busy = false
|
||||
} else {
|
||||
// Still busy: the scope dialog is now the thing in flight. Drops
|
||||
// waiting behind it are cancelled, not held behind a question
|
||||
// about another event.
|
||||
skipQueued()
|
||||
// Still busy: the scope dialog is now the thing in flight.
|
||||
pending = prepared
|
||||
_scopePrompt.value = MoveScopePrompt(
|
||||
occurrenceOnly = !prepared.canRealign,
|
||||
resize = prepared.isResize,
|
||||
resize = request.target is MoveTarget.Span,
|
||||
seriesOnly = seriesOnly,
|
||||
)
|
||||
}
|
||||
}
|
||||
return true
|
||||
}
|
||||
|
||||
/** Answer the scope dialog. */
|
||||
@@ -325,95 +259,39 @@ class RescheduleViewModel @Inject constructor(
|
||||
val prepared = pending ?: return
|
||||
// Guard against the dialog ever offering a scope the rule can't carry.
|
||||
if (!prepared.canRealign && scope != RecurringWriteScope.ThisEvent) return
|
||||
if (scope == RecurringWriteScope.ThisEvent && !prepared.original.canSaveAsOccurrence()) return
|
||||
pending = null
|
||||
_scopePrompt.value = null
|
||||
viewModelScope.launch {
|
||||
settle(prepared.request.token, write(prepared, scope))
|
||||
write(prepared, scope)
|
||||
busy = false
|
||||
}
|
||||
}
|
||||
|
||||
/** Dismiss the scope dialog without writing. */
|
||||
fun cancelScope() {
|
||||
val prepared = pending ?: return
|
||||
pending = null
|
||||
busy = false
|
||||
_scopePrompt.value = null
|
||||
settle(prepared.request.token, landed = false)
|
||||
}
|
||||
|
||||
/** End the drop [token], then run the next queued one, if any. */
|
||||
private fun settle(token: Long, landed: Boolean) {
|
||||
_drops.update { it.ended(token, landed) }
|
||||
// Straight on to the next, so busy never reads false between two drops.
|
||||
val next = queue.removeFirstOrNull()
|
||||
if (next != null) {
|
||||
run(next)
|
||||
} else {
|
||||
busy = false
|
||||
movedThisRun = false
|
||||
}
|
||||
}
|
||||
|
||||
private fun skipQueued() {
|
||||
if (queue.isEmpty()) return
|
||||
val skipped = queue.map { it.token }
|
||||
queue.clear()
|
||||
_drops.update { states -> skipped.fold(states) { acc, token -> acc.ended(token, landed = false) } }
|
||||
report(MoveOutcome.Skipped)
|
||||
}
|
||||
|
||||
/**
|
||||
* Queue [outcome] for the chip. While drops run back to back only the first
|
||||
* move is announced, so its Undo stays on offer; every failure gets its own
|
||||
* turn after it, since the grid shows what moved but only the chip says what
|
||||
* didn't. A later write to the announced move's event takes that Undo away,
|
||||
* as putting the event back would undo the later move too.
|
||||
*/
|
||||
private fun report(outcome: MoveOutcome, eventId: Long? = null) {
|
||||
if (outcome is MoveOutcome.Moved) {
|
||||
if (movedThisRun) {
|
||||
dropUndoFor(eventId)
|
||||
return
|
||||
}
|
||||
movedThisRun = true
|
||||
} else if (outcome == (notices.lastOrNull() ?: _outcome.value)) {
|
||||
return
|
||||
}
|
||||
if (_outcome.value == null) _outcome.value = outcome else notices.addLast(outcome)
|
||||
}
|
||||
|
||||
private fun dropUndoFor(eventId: Long?) {
|
||||
fun MoveOutcome.withoutUndo(): MoveOutcome =
|
||||
if (this is MoveOutcome.Moved && undo?.eventId == eventId) copy(undo = null) else this
|
||||
_outcome.value = _outcome.value?.withoutUndo()
|
||||
val rest = notices.map { it.withoutUndo() }
|
||||
notices.clear()
|
||||
notices.addAll(rest)
|
||||
}
|
||||
|
||||
private fun markWritten(eventId: Long, beginMillis: Long?) {
|
||||
written[eventId to beginMillis] = TimeSource.Monotonic.markNow()
|
||||
}
|
||||
|
||||
private fun writtenRecently(eventId: Long, beginMillis: Long): Boolean {
|
||||
written.entries.removeAll { it.value.elapsedNow() > RECENT_WRITE }
|
||||
return (eventId to null) in written || (eventId to beginMillis) in written
|
||||
_abandoned.value += 1
|
||||
}
|
||||
|
||||
/**
|
||||
* Put a completed move back where it came from. The outcome stands until the
|
||||
* inverse write reports back, so the one chip changes what it says rather
|
||||
* than closing and reopening. False when another write is already running —
|
||||
* the chip hides its action for that window, so this is the backstop. An
|
||||
* undo is a journey of its own: [undoStarted] names its token, and [drops]
|
||||
* reports whether it landed.
|
||||
* the chip hides its action for that window, so this is the backstop.
|
||||
*
|
||||
* [abandoned] ticks once an inverse that *started* fails to land: [undoStarted]
|
||||
* has sent the chip back on its journey by then and nothing else will seat it.
|
||||
* A refusal ticks nothing — it launched no journey of its own, and the counter
|
||||
* is global, so a tick here would release some other drop's held copy before
|
||||
* the grid has drawn it.
|
||||
*/
|
||||
fun undo(undo: MoveUndo): Boolean {
|
||||
if (busy) return false
|
||||
val token = nextMoveToken()
|
||||
_drops.update { it.started(token) }
|
||||
busy = true
|
||||
_undoStarted.value = UndoStart(token, undo.dropToken)
|
||||
markWritten(undo.eventId, null)
|
||||
_undoStarted.value += 1
|
||||
viewModelScope.launch {
|
||||
_outcome.value = try {
|
||||
repository.updateEvent(undo.eventId, undo.moved, undo.restored)
|
||||
@@ -427,43 +305,34 @@ class RescheduleViewModel @Inject constructor(
|
||||
} catch (e: Exception) {
|
||||
MoveOutcome.Failed
|
||||
}
|
||||
settle(token, landed = _outcome.value is MoveOutcome.Undone)
|
||||
// Read off the outcome, the way [write] does — no second copy of the
|
||||
// same fact to drift from it.
|
||||
if (_outcome.value !is MoveOutcome.Undone) _abandoned.value += 1
|
||||
busy = false
|
||||
}
|
||||
return true
|
||||
}
|
||||
|
||||
/** Clear the outcome once the screen has shown it, bringing on the next one waiting. */
|
||||
/** Clear the outcome once the screen has shown it. */
|
||||
fun consumeOutcome() {
|
||||
_outcome.value = notices.removeFirstOrNull()
|
||||
_outcome.value = null
|
||||
}
|
||||
|
||||
private suspend fun prepare(dropped: MoveRequest): PreparedMove? {
|
||||
val zone = zoneSource.current()
|
||||
private suspend fun prepare(request: MoveRequest): PreparedMove? {
|
||||
val detail = try {
|
||||
repository.eventDetail(dropped.eventId)
|
||||
repository.eventDetail(request.eventId)
|
||||
} catch (e: CancellationException) {
|
||||
throw e
|
||||
} catch (e: NoSuchEventException) {
|
||||
report(MoveOutcome.Gone)
|
||||
_outcome.value = MoveOutcome.Gone
|
||||
return null
|
||||
} catch (e: Exception) {
|
||||
report(MoveOutcome.Failed)
|
||||
_outcome.value = MoveOutcome.Failed
|
||||
return null
|
||||
}
|
||||
// The drop carries the times the grid drew, which an earlier write may
|
||||
// have moved on since (#494).
|
||||
val request = if (detail.rrule == null || detail.isException) {
|
||||
followed(dropped, detail, zone)
|
||||
} else if (writtenRecently(dropped.eventId, dropped.beginMillis)) {
|
||||
report(MoveOutcome.Stale)
|
||||
return null
|
||||
} else {
|
||||
dropped
|
||||
}
|
||||
|
||||
// Read fixed-time reminders out, so the move keeps them on their wall clock (#459).
|
||||
val zone = zoneSource.current()
|
||||
val original = detail.toEditForm(request.beginMillis, request.endMillis, zone)
|
||||
.withFixedTimeRemindersRead(settingsPrefs.knownFixedTimeReminders.first(), zone)
|
||||
val shifted = when (val target = request.target) {
|
||||
is MoveTarget.Start -> original.shiftedTo(target.instant, zone)
|
||||
is MoveTarget.ByDays -> original.shiftedByDays(target.days, zone)
|
||||
@@ -475,7 +344,7 @@ class RescheduleViewModel @Inject constructor(
|
||||
// The UNTIL check is deferred to the write, which knows how far the move
|
||||
// reaches and so which date has to clear it.
|
||||
if ((shifted.problems(zone) - EventFormProblem.RecurrenceEndsBeforeStart).isNotEmpty()) {
|
||||
report(MoveOutcome.Failed)
|
||||
_outcome.value = MoveOutcome.Failed
|
||||
return null
|
||||
}
|
||||
|
||||
@@ -520,14 +389,14 @@ class RescheduleViewModel @Inject constructor(
|
||||
)
|
||||
}
|
||||
|
||||
/** Write [prepared] in [scope]; true when it landed. */
|
||||
private suspend fun write(prepared: PreparedMove, scope: RecurringWriteScope): Boolean {
|
||||
private suspend fun write(prepared: PreparedMove, scope: RecurringWriteScope) {
|
||||
val request = prepared.request
|
||||
if (endsBeforeItStarts(prepared, scope)) {
|
||||
report(MoveOutcome.BlockedSeriesEnd)
|
||||
return false
|
||||
_outcome.value = MoveOutcome.BlockedSeriesEnd
|
||||
_abandoned.value += 1
|
||||
return
|
||||
}
|
||||
val outcome = try {
|
||||
_outcome.value = try {
|
||||
when {
|
||||
!prepared.isRecurring || scope == RecurringWriteScope.AllEvents ->
|
||||
repository.updateEvent(request.eventId, prepared.original, prepared.updated)
|
||||
@@ -562,37 +431,9 @@ class RescheduleViewModel @Inject constructor(
|
||||
} catch (e: Exception) {
|
||||
MoveOutcome.Failed
|
||||
}
|
||||
if (outcome is MoveOutcome.Moved) {
|
||||
markWritten(request.eventId, request.beginMillis.takeIf { scope == RecurringWriteScope.ThisEvent && prepared.isRecurring })
|
||||
}
|
||||
report(outcome, request.eventId)
|
||||
return outcome is MoveOutcome.Moved
|
||||
}
|
||||
|
||||
/**
|
||||
* A one-off [dropped] rebased onto where its event now is, so the last drop
|
||||
* wins: absolute targets stand as they are, and a whole-day shift is re-aimed
|
||||
* at the day it was dropped on. Unchanged when the event hasn't moved.
|
||||
*/
|
||||
private fun followed(dropped: MoveRequest, detail: EventDetail, zone: TimeZone): MoveRequest {
|
||||
val now = detail.instance
|
||||
val target = when (val target = dropped.target) {
|
||||
is MoveTarget.ByDays -> {
|
||||
// Each day read the way its own kind anchors it: all-day at UTC.
|
||||
val aimed = Instant.fromEpochMilliseconds(dropped.beginMillis)
|
||||
.toLocalDateTime(if (dropped.isAllDay) TimeZone.UTC else zone).date
|
||||
.plus(target.days, DateTimeUnit.DAY)
|
||||
val from = now.start.toLocalDateTime(if (now.isAllDay) TimeZone.UTC else zone).date
|
||||
MoveTarget.ByDays((aimed.toEpochDays() - from.toEpochDays()).toInt())
|
||||
}
|
||||
else -> target
|
||||
}
|
||||
return dropped.copy(
|
||||
beginMillis = now.start.toEpochMilliseconds(),
|
||||
endMillis = now.end.toEpochMilliseconds(),
|
||||
target = target,
|
||||
isAllDay = now.isAllDay,
|
||||
)
|
||||
// Nothing landed, so the copy the view is holding has nothing to fade
|
||||
// into — let it go now rather than at the end of the settle timeout.
|
||||
if (_outcome.value !is MoveOutcome.Moved) _abandoned.value += 1
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -631,9 +472,9 @@ class RescheduleViewModel @Inject constructor(
|
||||
val anchorZone = if (original.isAllDay) TimeZone.UTC else original.resolvedZone(zone)
|
||||
val anchorMinute = detail.instance.start.toLocalDateTime(anchorZone)
|
||||
.time.toMillisecondOfDay() / MILLIS_PER_MINUTE
|
||||
// An all-day form's time is a placeholder; its anchor sits at midnight.
|
||||
val fromMillis = if (original.isAllDay) 0 else original.start.time.toMillisecondOfDay()
|
||||
val delta = (shifted.start.time.toMillisecondOfDay() - fromMillis) / MILLIS_PER_MINUTE
|
||||
val delta = (
|
||||
shifted.start.time.toMillisecondOfDay() - original.start.time.toMillisecondOfDay()
|
||||
) / MILLIS_PER_MINUTE
|
||||
return anchorMinute + delta in 0 until MINUTES_PER_DAY
|
||||
}
|
||||
|
||||
@@ -659,7 +500,6 @@ class RescheduleViewModel @Inject constructor(
|
||||
eventId = prepared.request.eventId,
|
||||
moved = prepared.updated,
|
||||
restored = prepared.original,
|
||||
dropToken = prepared.request.token,
|
||||
)
|
||||
} else {
|
||||
null
|
||||
@@ -667,7 +507,7 @@ class RescheduleViewModel @Inject constructor(
|
||||
|
||||
/** Where a resized occurrence now ends; null for a move, which keeps its length. */
|
||||
private fun resizedEndMillis(prepared: PreparedMove): Long? {
|
||||
if (!prepared.isResize) return null
|
||||
if (prepared.request.target !is MoveTarget.Span) return null
|
||||
val form = prepared.updated
|
||||
return form.endInstant(form.resolvedZone(zoneSource.current())).toEpochMilliseconds()
|
||||
}
|
||||
|
||||
@@ -20,7 +20,6 @@ import androidx.compose.runtime.LaunchedEffect
|
||||
import androidx.compose.runtime.Stable
|
||||
import androidx.compose.runtime.derivedStateOf
|
||||
import androidx.compose.runtime.getValue
|
||||
import androidx.compose.runtime.key
|
||||
import androidx.compose.runtime.mutableStateListOf
|
||||
import androidx.compose.runtime.mutableIntStateOf
|
||||
import androidx.compose.runtime.mutableStateOf
|
||||
@@ -61,6 +60,7 @@ import de.jeanlucmakiola.floret.identity.LocalFloretDarkTheme
|
||||
import de.jeanlucmakiola.floret.identity.rememberReduceMotion
|
||||
import de.jeanlucmakiola.floret.locale.currentLocale
|
||||
import kotlinx.coroutines.delay
|
||||
import kotlinx.coroutines.flow.StateFlow
|
||||
import kotlinx.datetime.DateTimeUnit
|
||||
import kotlinx.datetime.LocalDate
|
||||
import kotlinx.datetime.atStartOfDayIn
|
||||
@@ -78,9 +78,6 @@ import kotlin.time.Instant
|
||||
/** Start granularity a dragged block snaps to, matching the big calendar apps. */
|
||||
const val DRAG_SNAP_MINUTES: Int = 15
|
||||
|
||||
/** How far below a strip drag's timed block top the finger holds it, in minutes. */
|
||||
private const val STRIP_GRAB_MINUTES = 15
|
||||
|
||||
/** How close to a timeline edge the finger must get before the view scrolls. */
|
||||
private val AUTO_SCROLL_EDGE = 64.dp
|
||||
|
||||
@@ -129,29 +126,6 @@ data class TimelineDrag(
|
||||
val slot: Triple<LocalDate, Int, Int> get() = Triple(date, startMin, eventSpanMin)
|
||||
}
|
||||
|
||||
/**
|
||||
* An event lifted off the all-day strip: held over the strip it moves [dayShift]
|
||||
* days and stays whole-day, held over the time grid it becomes a timed block.
|
||||
*/
|
||||
data class StripDrag(val event: EventInstance, val dayShift: Int = 0, val overGrid: Boolean = false)
|
||||
|
||||
/** Where a strip drag asks its event to go. */
|
||||
sealed interface StripDrop {
|
||||
val event: EventInstance
|
||||
|
||||
/** The drop's identity, which its held copy waits on. */
|
||||
val token: Long
|
||||
|
||||
data class Days(override val event: EventInstance, val days: Int, override val token: Long) : StripDrop
|
||||
|
||||
data class Timed(
|
||||
override val event: EventInstance,
|
||||
val start: Instant,
|
||||
val end: Instant,
|
||||
override val token: Long,
|
||||
) : StripDrop
|
||||
}
|
||||
|
||||
/** The event a long press left selected (#141). */
|
||||
data class TimelineSelection(
|
||||
val event: EventInstance,
|
||||
@@ -275,10 +249,9 @@ internal fun dragPieceBounds(
|
||||
): DragPieceBounds {
|
||||
val top = if (slice.continuesBefore) 0f else insetPx
|
||||
val bottom = if (slice.continuesAfter) 0f else insetPx
|
||||
val span = renderedSpan(slice.startMin, slice.startMin + slice.spanMin, slice.continuesAfter)
|
||||
val full = (span.bottomMin - span.topMin) / 60f * hourPx
|
||||
val full = maxOf(slice.spanMin / 60f * hourPx, MIN_EVENT_FRACTION * hourPx)
|
||||
return DragPieceBounds(
|
||||
top = span.topMin / 60f * hourPx + top,
|
||||
top = slice.startMin / 60f * hourPx + top,
|
||||
height = (full - top - bottom).coerceAtLeast(0f),
|
||||
)
|
||||
}
|
||||
@@ -305,9 +278,7 @@ data class TimelineDrop(
|
||||
val date: LocalDate,
|
||||
val startMin: Int,
|
||||
/** Minutes from the event's start to the dragged block's top edge. */
|
||||
val clipOffsetMin: Int,
|
||||
/** The drop's identity, which its held copy waits on. */
|
||||
val token: Long,
|
||||
val clipOffsetMin: Int = 0,
|
||||
)
|
||||
|
||||
/** The id a drafted block's stand-in event carries, which no provider row has (#153). */
|
||||
@@ -338,49 +309,19 @@ internal fun draftStartMin(minutes: Float): Int =
|
||||
internal fun draftBlock(draft: EventInstance, date: LocalDate, zone: TimeZone): TimedBlock? {
|
||||
// Clipped to the day the way the grid lays out events, so it's drawn the same across a DST change (#387).
|
||||
// The end is exclusive, so a draft ending at midnight belongs to the day before.
|
||||
val dayEnd = date.plus(1, DateTimeUnit.DAY).atStartOfDayIn(zone)
|
||||
val start = maxOf(draft.start, date.atStartOfDayIn(zone))
|
||||
val end = minOf(draft.end, dayEnd)
|
||||
val end = minOf(draft.end, date.plus(1, DateTimeUnit.DAY).atStartOfDayIn(zone))
|
||||
if (end <= start) return null
|
||||
val startMin = wallClockMinutes(start, date, zone)
|
||||
val endMin = wallClockEndMinutes(startMin, start, end, date, zone).coerceAtMost(MINUTES_PER_DAY)
|
||||
return TimedBlock(draft, startMin, endMin, lane = 0, laneCount = 1, continuesAfter = draft.end > dayEnd)
|
||||
return TimedBlock(draft, startMin, endMin, lane = 0, laneCount = 1)
|
||||
}
|
||||
|
||||
/** Which end of an event a resize handle moves (#141). */
|
||||
enum class ResizeEdge { Top, Bottom }
|
||||
|
||||
/** A drop parked by a newer pickup while its write still runs — see [TimelineDragController.held]. */
|
||||
data class HeldDrop(
|
||||
val copy: TimelineDrag,
|
||||
val token: Long,
|
||||
val instanceId: Long,
|
||||
/** The event row and start the drop came from, as [TimelineDragController.ghosts] matches them. */
|
||||
val origin: Pair<Long, Instant>,
|
||||
/** A resize's new end, which has to have landed too before the drop counts as seated. */
|
||||
val end: Instant?,
|
||||
/** Whether the grid now draws the drop at its landing slot. */
|
||||
val seated: Boolean = false,
|
||||
val handedOver: Boolean = false,
|
||||
) {
|
||||
fun ghosts(block: TimedBlock): Boolean = block.event.instanceId == instanceId ||
|
||||
(block.event.eventId == origin.first && block.event.start == origin.second)
|
||||
}
|
||||
|
||||
/** A strip drop parked by a newer one while its write still runs — see [TimelineDragController.heldStrips]. */
|
||||
data class HeldStrip(val drag: StripDrag, val token: Long, val seated: Boolean = false)
|
||||
|
||||
/** An event's new start and end, as a resize leaves them. */
|
||||
data class ResizedSpan(val start: Instant, val end: Instant)
|
||||
|
||||
/** Where a finished resize asks its event to begin and end. */
|
||||
data class TimelineResizeDrop(
|
||||
val event: EventInstance,
|
||||
val start: Instant,
|
||||
val end: Instant,
|
||||
/** The drop's identity, which its held copy waits on. */
|
||||
val token: Long,
|
||||
)
|
||||
data class TimelineResizeDrop(val event: EventInstance, val start: Instant, val end: Instant)
|
||||
|
||||
/**
|
||||
* [event] resized by its [edge] to the span [startMin]..+[spanMin] from [date]'s
|
||||
@@ -391,16 +332,17 @@ data class TimelineResizeDrop(
|
||||
* it was drawn (see [repicked]). An end takes a pass the grid draws at the drop
|
||||
* point, so the block settles under the finger.
|
||||
*/
|
||||
internal fun resizedSpan(
|
||||
internal fun resizedDrop(
|
||||
event: EventInstance,
|
||||
edge: ResizeEdge?,
|
||||
date: LocalDate,
|
||||
startMin: Int,
|
||||
spanMin: Int,
|
||||
zone: TimeZone,
|
||||
): ResizedSpan {
|
||||
): TimelineResizeDrop {
|
||||
val drawn = wallClockSpan(event, zone)
|
||||
return ResizedSpan(
|
||||
return TimelineResizeDrop(
|
||||
event = event,
|
||||
start = if (edge == ResizeEdge.Top) {
|
||||
event.start.toFormTime(zone).repicked(
|
||||
wallClockTime(date, startMin),
|
||||
@@ -551,14 +493,6 @@ class TimelineDragController {
|
||||
*/
|
||||
private var settledOrigin: Pair<Long, Instant>? by mutableStateOf(null)
|
||||
|
||||
/**
|
||||
* Earlier drops still being written when another block was picked up. They
|
||||
* keep their copy and their ghost until their own token settles, rather than
|
||||
* vanishing and flashing back at the old slot (#494).
|
||||
*/
|
||||
var held: List<HeldDrop> by mutableStateOf(emptyList())
|
||||
private set
|
||||
|
||||
/** How long a block drafted on an empty slot starts out, in minutes (#153). */
|
||||
var draftMinutes: Int = SettingsPrefs.DEFAULT_EVENT_DURATION
|
||||
|
||||
@@ -657,8 +591,14 @@ class TimelineDragController {
|
||||
var settlingSelected: Boolean = false
|
||||
private set
|
||||
|
||||
/** The token of the drop [settling] waits on. */
|
||||
var settledToken: Long = 0L
|
||||
/**
|
||||
* The abandoned-move counter, read at the drop so the mark can't be a
|
||||
* composition behind the tick it is compared against.
|
||||
*/
|
||||
var abandonedTicks: StateFlow<Int>? = null
|
||||
|
||||
/** What [abandonedTicks] stood at when the settling drop was let go. */
|
||||
var settledAbandonedMark: Int = 0
|
||||
private set
|
||||
|
||||
private var source: TimedBlock? = null
|
||||
@@ -689,32 +629,6 @@ class TimelineDragController {
|
||||
/** The resize in progress, or null for a plain drag (#141). */
|
||||
private var resize: ResizeSession? = null
|
||||
|
||||
/** The strip drag in progress; over the grid it drives [drag] through a timed stand-in. */
|
||||
var stripDrag: StripDrag? by mutableStateOf(null)
|
||||
private set
|
||||
|
||||
/** A strip drop held at its new days until the strip redraws the event there. */
|
||||
var stripSettling: StripDrag? by mutableStateOf(null)
|
||||
private set
|
||||
|
||||
/** Whether the strip now draws [stripSettling] at its new days itself. */
|
||||
var stripSeated: Boolean by mutableStateOf(false)
|
||||
private set
|
||||
|
||||
/** Strip drops parked by a newer strip drop while their writes still run (#494). */
|
||||
var heldStrips: List<HeldStrip> by mutableStateOf(emptyList())
|
||||
private set
|
||||
|
||||
/** The token of the drop [stripSettling] waits on. */
|
||||
var stripToken: Long = 0L
|
||||
private set
|
||||
|
||||
/** The shown day the finger picked the strip bar up on. */
|
||||
private var stripGrabIndex = 0
|
||||
|
||||
/** Whether a strip drag over the grid has cleared its top edge, and may now scroll up. */
|
||||
private var stripScrollArmed = false
|
||||
|
||||
fun begin(
|
||||
block: TimedBlock,
|
||||
clipOffsetMin: Int,
|
||||
@@ -731,7 +645,7 @@ class TimelineDragController {
|
||||
dragDuration = (block.event.end - block.event.start).coerceAtLeast(Duration.ZERO)
|
||||
dragKept = zone.repeatedHourOffsetAt(block.event.start)
|
||||
this.titleLines = titleLines
|
||||
parkSettling()
|
||||
settling = null
|
||||
isDragging = true
|
||||
liftedInstanceId = block.event.instanceId
|
||||
grab = pointerInRoot - blockInRoot
|
||||
@@ -753,86 +667,6 @@ class TimelineDragController {
|
||||
begin(block, clipOffsetMin = 0, zone, titleLines = 1, pointerInRoot = pointerInRoot, blockInRoot = blockInRoot)
|
||||
}
|
||||
|
||||
/**
|
||||
* Lift [event] off the all-day strip. Over the time grid it is dragged as a
|
||||
* block [draftMinutes] long, whose top sits a little above the finger.
|
||||
*/
|
||||
fun beginStrip(event: EventInstance, zone: TimeZone, pointerInRoot: Offset) {
|
||||
val grid = geometry.grid?.takeIf { it.isAttached } ?: return
|
||||
if (geometry.columnWidthPx <= 0f || geometry.days.isEmpty()) return
|
||||
deselect()
|
||||
if (stripSettling?.event?.instanceId == event.instanceId) releaseStrip()
|
||||
stripScrollArmed = false
|
||||
val timed = event.copy(isAllDay = false, end = event.start + draftMinutes.minutes)
|
||||
source = TimedBlock(timed, 0, draftMinutes, lane = 0, laneCount = 1)
|
||||
clipOffsetMin = 0
|
||||
dragZone = zone
|
||||
dragDuration = draftMinutes.minutes
|
||||
dragKept = null
|
||||
titleLines = 1
|
||||
parkSettling()
|
||||
isDragging = true
|
||||
liftedInstanceId = event.instanceId
|
||||
grab = Offset(0f, geometry.hourPx * STRIP_GRAB_MINUTES / 60f)
|
||||
pointer = pointerInRoot
|
||||
pickupPointer = pointerInRoot
|
||||
pointerMoved = false
|
||||
originSlot = null
|
||||
stripGrabIndex = dayIndexAt(pointerInRoot.x, grid.positionInRoot().x)
|
||||
stripDrag = StripDrag(event)
|
||||
}
|
||||
|
||||
/** The shown day under [x], clamped to the days on screen. */
|
||||
private fun dayIndexAt(x: Float, originX: Float): Int =
|
||||
column(((x - originX) / geometry.columnWidthPx).toInt().coerceIn(0, geometry.days.lastIndex))
|
||||
|
||||
/** End a strip drag, handing back where it landed — null when it went nowhere. */
|
||||
fun finishStrip(): StripDrop? {
|
||||
val held = stripDrag ?: return null
|
||||
val landed = drag
|
||||
val zone = dragZone
|
||||
cancel()
|
||||
if (held.overGrid && landed != null && zone != null && !landed.edgeOnly) {
|
||||
val token = settle(landed)
|
||||
val start = dropStartInstant(landed.event, landed.date, landed.startMin, clipOffsetMin = 0, zone)
|
||||
return StripDrop.Timed(held.event, start, start + draftMinutes.minutes, token)
|
||||
}
|
||||
if (held.overGrid || held.dayShift == 0) return null
|
||||
// One still settling keeps its place on the strip until its own write lands (#494).
|
||||
stripSettling?.let { heldStrips = heldStrips + HeldStrip(it, stripToken, stripSeated) }
|
||||
stripSettling = held
|
||||
stripSeated = false
|
||||
stripToken = nextMoveToken()
|
||||
drops++
|
||||
return StripDrop.Days(held.event, held.dayShift, stripToken)
|
||||
}
|
||||
|
||||
/** Let the held strip drop go, once the strip shows the event at its new days or the move failed. */
|
||||
fun releaseStrip() {
|
||||
stripSettling = null
|
||||
stripSeated = false
|
||||
}
|
||||
|
||||
/** Note that the strip draws the settling drop at its new days. */
|
||||
fun seatStrip() {
|
||||
if (stripSettling != null) stripSeated = true
|
||||
}
|
||||
|
||||
/** Note that the strip draws the parked strip drop [token] at its new days. */
|
||||
fun seatHeldStrip(token: Long) {
|
||||
if (heldStrips.any { it.token == token && !it.seated }) {
|
||||
heldStrips = heldStrips.map { if (it.token == token) it.copy(seated = true) else it }
|
||||
}
|
||||
}
|
||||
|
||||
/** Let the parked strip drop [token] go. */
|
||||
fun releaseHeldStrip(token: Long) {
|
||||
heldStrips = heldStrips.filterNot { it.token == token }
|
||||
}
|
||||
|
||||
/** Every strip drop still shown at its new days: the parked ones, then the latest. */
|
||||
fun stripPreviews(): List<StripDrag> = heldStrips.map { it.drag } + listOfNotNull(stripDrag ?: stripSettling)
|
||||
|
||||
fun move(pointerInRoot: Offset) {
|
||||
pointer = pointerInRoot
|
||||
if (!pointerMoved && (pointerInRoot - pickupPointer).getDistance() > slopPx) pointerMoved = true
|
||||
@@ -841,7 +675,6 @@ class TimelineDragController {
|
||||
|
||||
fun cancel() {
|
||||
resize = null
|
||||
stripDrag = null
|
||||
source = null
|
||||
clipOffsetMin = 0
|
||||
dragZone = null
|
||||
@@ -867,36 +700,12 @@ class TimelineDragController {
|
||||
* an event that crosses midnight (#253).
|
||||
*/
|
||||
fun ghosts(block: TimedBlock): Boolean {
|
||||
if (held.any { !it.handedOver && it.ghosts(block) }) return true
|
||||
if (liftedInstanceId == null) return false
|
||||
if (block.event.instanceId == liftedInstanceId) return true
|
||||
val (eventId, start) = settledOrigin ?: return false
|
||||
return block.event.eventId == eventId && block.event.start == start
|
||||
}
|
||||
|
||||
/** Move a still-settling drop to [held] before a new pickup takes the slot. */
|
||||
private fun parkSettling() {
|
||||
val landed = settling
|
||||
val origin = settledOrigin
|
||||
if (landed != null && origin != null && !landed.event.isDraft) {
|
||||
held = held + HeldDrop(landed, settledToken, landed.event.instanceId, origin, settledEnd, settledOnGrid)
|
||||
}
|
||||
settling = null
|
||||
settledOnGrid = false
|
||||
settledOrigin = null
|
||||
settledEnd = null
|
||||
}
|
||||
|
||||
/** Stop ghosting the held drop [token]'s source while its copy fades. */
|
||||
fun handOverHeld(token: Long) {
|
||||
held = held.map { if (it.token == token) it.copy(handedOver = true) else it }
|
||||
}
|
||||
|
||||
/** Drop the held copy [token] once it has faded. */
|
||||
fun releaseHeld(token: Long) {
|
||||
held = held.filterNot { it.token == token }
|
||||
}
|
||||
|
||||
/**
|
||||
* What a day column now holds, so a settled drop can tell when the grid has
|
||||
* caught up with it. Matched on the landing slot plus either the event row
|
||||
@@ -904,23 +713,16 @@ class TimelineDragController {
|
||||
* blank title matches nothing: every untitled event has one (#253).
|
||||
*/
|
||||
fun noteGrid(date: LocalDate, blocks: List<TimedBlock>) {
|
||||
if (held.any { !it.seated && drawsDrop(it.copy, it.end, date, blocks) }) {
|
||||
held = held.map { if (!it.seated && drawsDrop(it.copy, it.end, date, blocks)) it.copy(seated = true) else it }
|
||||
}
|
||||
val landed = settling ?: return
|
||||
if (settledOnGrid) return
|
||||
settledOnGrid = drawsDrop(landed, settledEnd, date, blocks)
|
||||
}
|
||||
|
||||
/** Whether [blocks], [date]'s column, draws the drop [landed] where it landed. */
|
||||
private fun drawsDrop(landed: TimelineDrag, end: Instant?, date: LocalDate, blocks: List<TimedBlock>): Boolean {
|
||||
// Where this day would draw it, which for a drop clipped at midnight is
|
||||
// the day's own start rather than the edge the finger held (#253) — and
|
||||
// which for a tail dragged clear of its day is the day before it.
|
||||
val offset = (date.toEpochDays() - landed.date.toEpochDays()).toInt()
|
||||
val slice = dragSlices(landed.eventStartMin, landed.eventSpanMin, offset..offset)
|
||||
.firstOrNull() ?: return false
|
||||
return blocks.any { block ->
|
||||
.firstOrNull() ?: return
|
||||
val end = settledEnd
|
||||
settledOnGrid = blocks.any { block ->
|
||||
block.startMin == slice.startMin &&
|
||||
// A resize may keep its start, so its end has to have landed too.
|
||||
(end == null || block.event.end == end) &&
|
||||
@@ -947,31 +749,23 @@ 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
|
||||
val token = settle(landed)
|
||||
return TimelineDrop(landed.event, landed.date, landed.startMin, clipOffset, token)
|
||||
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. Returns the drop's fresh token.
|
||||
*/
|
||||
private fun settle(landed: TimelineDrag, end: Instant? = null): Long {
|
||||
// Landed on midnight to midnight, the event moves to the all-day strip (#296).
|
||||
val leavesGrid = !landed.event.isDraft && landed.eventSpanMin > 0 &&
|
||||
landed.eventStartMin.mod(MINUTES_PER_DAY) == 0 &&
|
||||
landed.eventSpanMin % MINUTES_PER_DAY == 0
|
||||
/** Keep [landed]'s copy on the target as [settling] until [release]; [end] is a resize's. */
|
||||
private fun settle(landed: TimelineDrag, end: Instant? = null) {
|
||||
settlingSelected = selection?.event?.instanceId == landed.event.instanceId
|
||||
// An edge piece is a hint for the finger, not a preview of the landing
|
||||
// slot: the event belongs to a day this timeline has no column for, so
|
||||
// [noteGrid] can never seat it and it would sit at the top of today for
|
||||
// the whole settle timeout, long after the event moved off-screen.
|
||||
settling = if (landed.edgeOnly || leavesGrid) landed.copy(pieces = emptyList()) else landed
|
||||
settling = if (landed.edgeOnly) landed.copy(pieces = emptyList()) else landed
|
||||
liftedInstanceId = landed.event.instanceId
|
||||
settledOrigin = landed.event.eventId to landed.event.start
|
||||
settledToken = nextMoveToken()
|
||||
settledAbandonedMark = abandonedTicks?.value ?: 0
|
||||
settledEnd = end
|
||||
drops++
|
||||
return settledToken
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -991,7 +785,7 @@ class TimelineDragController {
|
||||
resize = session
|
||||
clipOffsetMin = 0
|
||||
this.titleLines = titleLines
|
||||
parkSettling()
|
||||
settling = null
|
||||
isDragging = true
|
||||
pointerMoved = true
|
||||
liftedInstanceId = block.event.instanceId
|
||||
@@ -1001,9 +795,7 @@ class TimelineDragController {
|
||||
val edgeIndex = geometry.days.indexOf(span.day.plus(edgeDay, DateTimeUnit.DAY))
|
||||
session.column = edgeIndex.takeIf { it >= 0 }
|
||||
?.let { column(it) }
|
||||
// The top handle sits on the drawn top, which a short block near midnight lifts (#483).
|
||||
val lift = if (edge == ResizeEdge.Top) block.startMin - block.renderedSpan().topMin else 0f
|
||||
session.grabMin = (pointerResizeMinutes(session) ?: 0f) + lift -
|
||||
session.grabMin = (pointerResizeMinutes(session) ?: 0f) -
|
||||
if (edge == ResizeEdge.Top) session.startMin else session.endMin
|
||||
originSlot = null
|
||||
recompute()
|
||||
@@ -1022,10 +814,10 @@ class TimelineDragController {
|
||||
val event = source?.event ?: return null
|
||||
val edge = resize?.edge
|
||||
if (edge != null) {
|
||||
val drop = resizedSpan(event, edge, date, startMin, spanMin, zone)
|
||||
val drop = resizedDrop(event, edge, date, startMin, spanMin, zone)
|
||||
return event.copy(start = drop.start, end = drop.end)
|
||||
}
|
||||
val start = dropStartInstant(event, date, startMin, clipOffsetMin, zone)
|
||||
val start = TimelineDrop(event, date, startMin, clipOffsetMin).startInstant(zone)
|
||||
return event.copy(start = start, end = start + dragDuration)
|
||||
}
|
||||
|
||||
@@ -1039,8 +831,9 @@ class TimelineDragController {
|
||||
val edge = resize?.edge
|
||||
cancel()
|
||||
if (landed == null || landed.slot == origin) return null
|
||||
val span = resizedSpan(landed.event, edge, landed.date, landed.eventStartMin, landed.eventSpanMin, zone)
|
||||
return TimelineResizeDrop(landed.event, span.start, span.end, settle(landed, end = span.end))
|
||||
val drop = resizedDrop(landed.event, edge, landed.date, landed.eventStartMin, landed.eventSpanMin, zone)
|
||||
settle(landed, end = drop.end)
|
||||
return drop
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -1062,9 +855,7 @@ class TimelineDragController {
|
||||
session.column = held
|
||||
val dayOffset = (days[column(held)].toEpochDays() - session.day.toEpochDays()).toInt()
|
||||
session.edgeDay = dayOffset
|
||||
// Held to its column's midnight: the clearance under it is not the next day.
|
||||
val minutes = ((pointer.y - origin.y) / hourPx * 60f).coerceAtMost(MINUTES_PER_DAY.toFloat())
|
||||
return dayOffset * MINUTES_PER_DAY + minutes
|
||||
return dayOffset * MINUTES_PER_DAY + (pointer.y - origin.y) / hourPx * 60f
|
||||
}
|
||||
|
||||
private fun recomputeResize(session: ResizeSession) {
|
||||
@@ -1137,29 +928,6 @@ class TimelineDragController {
|
||||
recomputeResize(it)
|
||||
return
|
||||
}
|
||||
stripDrag?.let {
|
||||
recomputeStrip(it)
|
||||
return
|
||||
}
|
||||
recomputeDrag()
|
||||
}
|
||||
|
||||
/** Over the strip the bar moves by whole days; past its bottom edge it is a timed block. */
|
||||
private fun recomputeStrip(held: StripDrag) {
|
||||
val grid = geometry.grid?.takeIf { it.isAttached } ?: return
|
||||
val viewport = geometry.viewport?.takeIf { it.isAttached } ?: return
|
||||
if (geometry.columnWidthPx <= 0f || geometry.days.isEmpty()) return
|
||||
if (pointer.y >= viewport.boundsInRoot().top) {
|
||||
stripDrag = held.copy(overGrid = true)
|
||||
recomputeDrag()
|
||||
} else {
|
||||
drag = null
|
||||
val shift = dayIndexAt(pointer.x, grid.positionInRoot().x) - stripGrabIndex
|
||||
stripDrag = held.copy(dayShift = shift, overGrid = false)
|
||||
}
|
||||
}
|
||||
|
||||
private fun recomputeDrag() {
|
||||
val block = source ?: return
|
||||
val grid = geometry.grid?.takeIf { it.isAttached } ?: return
|
||||
val hourPx = geometry.hourPx
|
||||
@@ -1245,18 +1013,11 @@ class TimelineDragController {
|
||||
}
|
||||
|
||||
private fun edgeStep(): Float {
|
||||
val strip = stripDrag
|
||||
if (strip?.overGrid == false) return 0f
|
||||
val viewport = geometry.viewport?.takeIf { it.isAttached } ?: return 0f
|
||||
val edge = geometry.edgePx
|
||||
if (edge <= 0f) return 0f
|
||||
val bounds = viewport.boundsInRoot()
|
||||
val fromTop = pointer.y - bounds.top
|
||||
// Coming down out of the strip the finger starts inside the top edge.
|
||||
if (strip != null && !stripScrollArmed) {
|
||||
if (fromTop < edge) return 0f
|
||||
stripScrollArmed = true
|
||||
}
|
||||
val fromBottom = bounds.bottom - pointer.y
|
||||
return when {
|
||||
fromTop < edge -> -(edge - fromTop) / edge * geometry.stepPx
|
||||
@@ -1294,6 +1055,7 @@ fun rememberTimelineDragController(): TimelineDragController {
|
||||
controller.geometry.edgePx = with(density) { AUTO_SCROLL_EDGE.toPx() }
|
||||
controller.geometry.stepPx = with(density) { AUTO_SCROLL_STEP.toPx() }
|
||||
controller.slopPx = LocalViewConfiguration.current.touchSlop
|
||||
controller.abandonedTicks = LocalEventMove.current?.abandoned
|
||||
return controller
|
||||
}
|
||||
|
||||
@@ -1315,6 +1077,10 @@ fun TimedBlock.clipOffsetMinutes(day: LocalDate, zone: TimeZone): Int {
|
||||
fun TimedBlock.continuesBefore(day: LocalDate, zone: TimeZone): Boolean =
|
||||
event.start < day.atStartOfDayIn(zone)
|
||||
|
||||
/** True when the event runs past [day]'s midnight, so this block is cut there. */
|
||||
fun TimedBlock.continuesAfter(day: LocalDate, zone: TimeZone): Boolean =
|
||||
event.end > day.plus(1, DateTimeUnit.DAY).atStartOfDayIn(zone)
|
||||
|
||||
/**
|
||||
* The instant a drop asks for — the *event's* new start, so the tail of an
|
||||
* overnight event drops back onto the day its own start belongs to. Read in the
|
||||
@@ -1323,16 +1089,7 @@ fun TimedBlock.continuesBefore(day: LocalDate, zone: TimeZone): Boolean =
|
||||
* visibly settles there.
|
||||
*/
|
||||
fun TimelineDrop.startInstant(zone: TimeZone): Instant =
|
||||
dropStartInstant(event, date, startMin, clipOffsetMin, zone)
|
||||
|
||||
/** Where [event] starts when its block's top edge lands [startMin] past [date]'s midnight — see [TimelineDrop]. */
|
||||
internal fun dropStartInstant(
|
||||
event: EventInstance,
|
||||
date: LocalDate,
|
||||
startMin: Int,
|
||||
clipOffsetMin: Int,
|
||||
zone: TimeZone,
|
||||
): Instant = wallClockInstant(date, startMin - clipOffsetMin, zone, kept = zone.repeatedHourOffsetAt(event.start))
|
||||
wallClockInstant(date, startMin - clipOffsetMin, zone, kept = zone.repeatedHourOffsetAt(event.start))
|
||||
|
||||
/**
|
||||
* The wall-clock minutes an event lasting [duration] covers when it starts
|
||||
@@ -1404,7 +1161,6 @@ private const val SETTLE_TIMEOUT_MILLIS = 900L
|
||||
*/
|
||||
const val SETTLE_FADE_MILLIS: Int = 250
|
||||
|
||||
|
||||
/**
|
||||
* The floating block, drawn over the whole calendar so it is free of the day
|
||||
* column's clip and of the scroll viewport's rounded corners.
|
||||
@@ -1412,14 +1168,16 @@ const val SETTLE_FADE_MILLIS: Int = 250
|
||||
@Composable
|
||||
fun TimelineDragOverlay(controller: TimelineDragController, modifier: Modifier = Modifier) {
|
||||
var origin by remember { mutableStateOf(Offset.Zero) }
|
||||
val density = LocalDensity.current
|
||||
val dark = LocalFloretDarkTheme.current
|
||||
val use24Hour = LocalUse24HourFormat.current
|
||||
val locale = currentLocale()
|
||||
val reduceMotion = rememberReduceMotion()
|
||||
val drops = dropStates()
|
||||
val moveInFlight = controller.settledToken in drops.pending
|
||||
val stripInFlight = controller.stripToken in drops.pending
|
||||
val moveInFlight = moveInFlight()
|
||||
|
||||
// Both live here rather than beside the controller: they read [drag], which
|
||||
// changes every frame, and this composable is the one that is meant to.
|
||||
DragSnapHaptics(controller.drag?.slot ?: controller.stripDrag?.dayShift, controller.drops)
|
||||
DragSnapHaptics(controller.drag?.slot, controller.drops)
|
||||
// Only once the finger has moved: a long press held near an edge must not
|
||||
// scroll the drop target out from under a finger that only means to select.
|
||||
LaunchedEffect(controller.isDragging && controller.pointerMoved) {
|
||||
@@ -1429,11 +1187,12 @@ fun TimelineDragOverlay(controller: TimelineDragController, modifier: Modifier =
|
||||
// recurring drop's scope dialog is up — and then until the grid draws the
|
||||
// drop itself.
|
||||
var handingOver by remember(controller.settling) { mutableStateOf(false) }
|
||||
val abandoned = controller.settledToken in drops.abandoned
|
||||
val abandoned = abandonedMoves()
|
||||
LaunchedEffect(controller.settling, moveInFlight, controller.settledOnGrid, abandoned) {
|
||||
if (controller.settling == null || moveInFlight) return@LaunchedEffect
|
||||
// An abandoned drop: nothing will land and there is nothing to wait for.
|
||||
if (!abandoned) {
|
||||
// Past the mark this drop was let go on, it was abandoned: nothing will
|
||||
// land and there is nothing to wait for.
|
||||
if (abandoned == controller.settledAbandonedMark) {
|
||||
delay(if (controller.settledOnGrid) SETTLE_GRACE_MILLIS else SETTLE_TIMEOUT_MILLIS)
|
||||
}
|
||||
handingOver = true
|
||||
@@ -1442,16 +1201,6 @@ fun TimelineDragOverlay(controller: TimelineDragController, modifier: Modifier =
|
||||
controller.release()
|
||||
}
|
||||
|
||||
// The same hold for a bar moved along the all-day strip.
|
||||
val stripAbandoned = controller.stripToken in drops.abandoned
|
||||
LaunchedEffect(controller.stripSettling, stripInFlight, controller.stripSeated, stripAbandoned) {
|
||||
if (controller.stripSettling == null || stripInFlight) return@LaunchedEffect
|
||||
if (!stripAbandoned) {
|
||||
delay(if (controller.stripSeated) SETTLE_GRACE_MILLIS else SETTLE_TIMEOUT_MILLIS)
|
||||
}
|
||||
controller.releaseStrip()
|
||||
}
|
||||
|
||||
Box(
|
||||
modifier = modifier
|
||||
.fillMaxSize()
|
||||
@@ -1460,12 +1209,6 @@ fun TimelineDragOverlay(controller: TimelineDragController, modifier: Modifier =
|
||||
.clearAndSetSemantics { }
|
||||
.onGloballyPositioned { origin = it.positionInRoot() },
|
||||
) {
|
||||
controller.held.forEach { parked ->
|
||||
key(parked.token) { HeldTimelineCopy(controller, parked, origin) }
|
||||
}
|
||||
controller.heldStrips.forEach { parked ->
|
||||
key(parked.token) { HeldStripSettle(controller, parked) }
|
||||
}
|
||||
val drag = controller.drag ?: controller.settling ?: return@Box
|
||||
// Landed: the copy sinks back to the grid's own plane while the write runs.
|
||||
val landed = controller.drag == null
|
||||
@@ -1479,58 +1222,6 @@ fun TimelineDragOverlay(controller: TimelineDragController, modifier: Modifier =
|
||||
animationSpec = tween(SETTLE_FADE_MILLIS),
|
||||
label = "drag-handover",
|
||||
)
|
||||
TimelineCopy(drag, controller.geometry, origin, lift, copyAlpha)
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* [TimelineDragController.ghosts] for [block], derived so the block recomposes
|
||||
* only when its own answer changes rather than on every lift, park and release.
|
||||
*/
|
||||
@Composable
|
||||
fun TimelineDragController.ghostsDerived(block: TimedBlock): Boolean {
|
||||
val ghosted by remember(this, block) { derivedStateOf { ghosts(block) } }
|
||||
return ghosted
|
||||
}
|
||||
|
||||
/** A drop parked by a newer pickup: held at its landing slot until its own write settles. */
|
||||
@Composable
|
||||
private fun HeldTimelineCopy(controller: TimelineDragController, parked: HeldDrop, origin: Offset) {
|
||||
val alpha = rememberHeldSettle(
|
||||
token = parked.token,
|
||||
seated = parked.seated,
|
||||
timeoutMillis = SETTLE_TIMEOUT_MILLIS,
|
||||
onHandOver = { controller.handOverHeld(parked.token) },
|
||||
onRelease = { controller.releaseHeld(parked.token) },
|
||||
)
|
||||
TimelineCopy(parked.copy, controller.geometry, origin, lift = 0f, copyAlpha = alpha)
|
||||
}
|
||||
|
||||
/** A strip drop parked by a newer one: shown at its new days until its own write settles. */
|
||||
@Composable
|
||||
private fun HeldStripSettle(controller: TimelineDragController, parked: HeldStrip) {
|
||||
rememberHeldSettle(
|
||||
token = parked.token,
|
||||
seated = parked.seated,
|
||||
timeoutMillis = SETTLE_TIMEOUT_MILLIS,
|
||||
onHandOver = {},
|
||||
onRelease = { controller.releaseHeldStrip(parked.token) },
|
||||
)
|
||||
}
|
||||
|
||||
/** [drag]'s pieces drawn over the calendar, clipped to the timeline's viewport. */
|
||||
@Composable
|
||||
private fun TimelineCopy(
|
||||
drag: TimelineDrag,
|
||||
geometry: TimelineGeometry,
|
||||
origin: Offset,
|
||||
lift: Float,
|
||||
copyAlpha: Float,
|
||||
) {
|
||||
val density = LocalDensity.current
|
||||
val dark = LocalFloretDarkTheme.current
|
||||
val use24Hour = LocalUse24HourFormat.current
|
||||
val locale = currentLocale()
|
||||
val paint = eventPaint(drag.event, dark)
|
||||
val title = drag.event.title.ifBlank { stringResource(R.string.event_untitled) }
|
||||
// Read off the event rather than the held block, so grabbing either half
|
||||
@@ -1546,7 +1237,7 @@ private fun TimelineCopy(
|
||||
// so no column clip or rounded corner cuts it, but it still belongs to
|
||||
// the timeline: a piece a whole day tall reaches far past both ends of
|
||||
// the viewport, and unclipped it paints over the headers above (#267).
|
||||
val port = geometry.viewport?.takeIf { it.isAttached }?.boundsInRoot()
|
||||
val port = controller.geometry.viewport?.takeIf { it.isAttached }?.boundsInRoot()
|
||||
// How much of each piece the viewport actually shows. A multi-day event
|
||||
// has a piece per day, and the widest one is a full 24 hours — taller
|
||||
// than the screen, its top at a midnight scrolled out of sight. Picking
|
||||
@@ -1598,6 +1289,7 @@ private fun TimelineCopy(
|
||||
)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/** One piece of a dragged block, floating over the calendar. */
|
||||
|
||||
@@ -43,21 +43,14 @@ data class TimelineHours(
|
||||
|
||||
/**
|
||||
* The scroll offset that puts [startHour] at the top of a timeline laid out
|
||||
* with [maxValue] scroll range over a [viewportPx] viewport, [clearancePx] of
|
||||
* which is the empty inset under midnight, or null while that
|
||||
* with [maxValue] scroll range over a [viewportPx] viewport, or null while that
|
||||
* layout is not yet at [hourPx] per hour — the scale changes a frame before the
|
||||
* content grows to match it, and scrolling against the old layout would land on
|
||||
* the wrong hour.
|
||||
*/
|
||||
internal fun startHourScroll(
|
||||
maxValue: Int,
|
||||
viewportPx: Int,
|
||||
startHour: Int,
|
||||
hourPx: Float,
|
||||
clearancePx: Int = 0,
|
||||
): Int? {
|
||||
internal fun startHourScroll(maxValue: Int, viewportPx: Int, startHour: Int, hourPx: Float): Int? {
|
||||
if (viewportPx <= 0 || maxValue < 0 || maxValue == Int.MAX_VALUE) return null
|
||||
val laidOutHourPx = (maxValue + viewportPx - clearancePx) / 24f
|
||||
val laidOutHourPx = (maxValue + viewportPx) / 24f
|
||||
if (abs(laidOutHourPx - hourPx) > 1f) return null
|
||||
return (startHour * laidOutHourPx).roundToInt().coerceIn(0, maxValue)
|
||||
}
|
||||
@@ -4,8 +4,6 @@ import androidx.annotation.StringRes
|
||||
import androidx.compose.ui.unit.Dp
|
||||
import androidx.compose.ui.unit.dp
|
||||
import de.jeanlucmakiola.calendula.R
|
||||
import de.jeanlucmakiola.calendula.ui.week.MINUTES_PER_DAY
|
||||
import de.jeanlucmakiola.calendula.ui.week.TimedBlock
|
||||
|
||||
/**
|
||||
* How tall one hour is drawn in the week and day timelines (#56).
|
||||
@@ -61,9 +59,8 @@ sealed interface TimelineScale {
|
||||
}
|
||||
|
||||
/**
|
||||
* Hour height for this scale. [viewportHeight] is the height the day is fitted
|
||||
* to, the scrolling timeline's [dayFitHeight], and is not consulted by the
|
||||
* fixed presets.
|
||||
* Hour height for this scale. [viewportHeight] is the visible height of the
|
||||
* scrolling timeline and is only consulted by [TimelineScale.FitDay].
|
||||
*
|
||||
* The fit-day result is clamped: below [FIT_DAY_MIN] the 24 gutter labels stop
|
||||
* being legible, and above [FIT_DAY_MAX] a short landscape day would stretch its
|
||||
@@ -88,13 +85,6 @@ fun TimelineScale.hourHeight(viewportHeight: Dp): Dp = when (this) {
|
||||
.coerceAtLeast(fillHourHeight(viewportHeight))
|
||||
}
|
||||
|
||||
/**
|
||||
* The part of a [viewportHeight]-tall timeline the day is fitted to: the
|
||||
* [FabClearance] under midnight, which lets the last hour scroll clear of the
|
||||
* FAB (#483), is left out. Pass this, not the raw viewport, to [hourHeight].
|
||||
*/
|
||||
fun dayFitHeight(viewportHeight: Dp): Dp = (viewportHeight - FabClearance).coerceAtLeast(0.dp)
|
||||
|
||||
/**
|
||||
* The minute of the day a tap [offsetY] px down a timeline column means, snapped
|
||||
* to the hour it landed in.
|
||||
@@ -115,28 +105,6 @@ fun tappedMinuteOfDay(offsetY: Float, hourPx: Float): Int =
|
||||
*/
|
||||
const val MIN_EVENT_FRACTION = 26f / 60f
|
||||
|
||||
/** Where a timed block is drawn down its day, in minutes from midnight. */
|
||||
data class RenderedSpan(val topMin: Float, val bottomMin: Float)
|
||||
|
||||
/**
|
||||
* Where a block of [startMin]..[endMin] is drawn, at least [MIN_EVENT_FRACTION]
|
||||
* of an hour tall. A short block near midnight rises until that floor ends at
|
||||
* midnight instead of running off the day, unless it [continuesAfter] into the
|
||||
* next one (#483).
|
||||
*/
|
||||
fun renderedSpan(startMin: Int, endMin: Int, continuesAfter: Boolean): RenderedSpan {
|
||||
val floor = MIN_EVENT_FRACTION * 60f
|
||||
val bottom = maxOf(endMin.toFloat(), startMin + floor)
|
||||
return if (continuesAfter || bottom <= MINUTES_PER_DAY) {
|
||||
RenderedSpan(startMin.toFloat(), bottom)
|
||||
} else {
|
||||
RenderedSpan(MINUTES_PER_DAY - floor, MINUTES_PER_DAY.toFloat())
|
||||
}
|
||||
}
|
||||
|
||||
/** This block's [renderedSpan]. */
|
||||
fun TimedBlock.renderedSpan(): RenderedSpan = renderedSpan(startMin, endMin, continuesAfter)
|
||||
|
||||
/** Smallest hour height [TimelineScale.FitDay] will resolve to. */
|
||||
val FIT_DAY_MIN = 24.dp
|
||||
|
||||
|
||||
@@ -32,21 +32,16 @@ val LocalTimelineScroll = staticCompositionLocalOf<TimelineScrollMemory?> { null
|
||||
|
||||
/** A timeline's scroll, and where it opens before it can scroll there. */
|
||||
@Stable
|
||||
class TimelineScroll(
|
||||
val state: ScrollState,
|
||||
noonPending: Boolean,
|
||||
private val openingHour: Int?,
|
||||
private val clearancePx: Float = 0f,
|
||||
) {
|
||||
class TimelineScroll(val state: ScrollState, noonPending: Boolean, private val openingHour: Int?) {
|
||||
/** Whether it is still to be put on noon, which it only can be once laid out. */
|
||||
var noonPending by mutableStateOf(noonPending)
|
||||
internal set
|
||||
|
||||
/** The top of what it shows, or will once open, over [content] pixels of day in a [viewport] pixels high. */
|
||||
/** The top of what it shows, or will once open, over [content] pixels in a [viewport] pixels high. */
|
||||
fun top(viewport: Float, content: Float): Float =
|
||||
if (noonPending) {
|
||||
(openingHour?.let { it * content / 24f } ?: (content - viewport) / 2f)
|
||||
.coerceIn(0f, (content + clearancePx - viewport).coerceAtLeast(0f))
|
||||
.coerceIn(0f, (content - viewport).coerceAtLeast(0f))
|
||||
} else state.value.toFloat()
|
||||
}
|
||||
|
||||
@@ -63,7 +58,6 @@ fun rememberTimelineScrollState(timelineTop: Dp): TimelineScroll {
|
||||
val density = LocalDensity.current
|
||||
val zoom = LocalTimelineZoom.current
|
||||
val topPx = with(density) { timelineTop.toPx() }
|
||||
val clearancePx = with(density) { FabClearance.roundToPx() }
|
||||
val remembered = memory?.midnightY
|
||||
val scrollState = rememberScrollState(
|
||||
initial = remembered?.let { (topPx - it).roundToInt().coerceAtLeast(0) } ?: 0,
|
||||
@@ -73,7 +67,6 @@ fun rememberTimelineScrollState(timelineTop: Dp): TimelineScroll {
|
||||
scrollState,
|
||||
noonPending = remembered == null,
|
||||
openingHour = zoom.hours.takeIf { it.enabled }?.startHour,
|
||||
clearancePx = clearancePx.toFloat(),
|
||||
)
|
||||
}
|
||||
val currentTop by rememberUpdatedState(topPx)
|
||||
@@ -87,20 +80,20 @@ fun rememberTimelineScrollState(timelineTop: Dp): TimelineScroll {
|
||||
val startHour = zoom.open()
|
||||
if (startHour == null) {
|
||||
snapshotFlow { scrollState.maxValue }.first { it > 0 }
|
||||
scrollState.scrollTo(((scrollState.maxValue - clearancePx) / 2).coerceAtLeast(0))
|
||||
scrollState.scrollTo(scrollState.maxValue / 2)
|
||||
} else {
|
||||
// Fitted to the scroll viewport itself: the layout resolves scales
|
||||
// against the viewport plus the all-day strip, which would push the
|
||||
// end hour below the screen.
|
||||
val viewport = snapshotFlow { scrollState.viewportSize }.first { it > 0 }
|
||||
val hourHeight = zoom.scale.hourHeight(dayFitHeight(with(density) { viewport.toDp() }))
|
||||
val hourHeight = zoom.scale.hourHeight(with(density) { viewport.toDp() })
|
||||
zoom.holdFit(hourHeight)
|
||||
val hourPx = with(density) { hourHeight.toPx() }
|
||||
val target = withTimeoutOrNull(FIT_LAYOUT_TIMEOUT_MILLIS) {
|
||||
snapshotFlow {
|
||||
startHourScroll(scrollState.maxValue, scrollState.viewportSize, startHour, hourPx, clearancePx)
|
||||
startHourScroll(scrollState.maxValue, scrollState.viewportSize, startHour, hourPx)
|
||||
}.filterNotNull().first()
|
||||
} ?: (startHour * (scrollState.maxValue + scrollState.viewportSize - clearancePx) / 24)
|
||||
} ?: (startHour * (scrollState.maxValue + scrollState.viewportSize) / 24)
|
||||
.coerceIn(0, scrollState.maxValue.coerceAtLeast(0))
|
||||
scrollState.scrollTo(target)
|
||||
}
|
||||
|
||||
@@ -1,21 +0,0 @@
|
||||
package de.jeanlucmakiola.calendula.ui.common
|
||||
|
||||
import android.content.res.Resources
|
||||
import androidx.compose.runtime.Composable
|
||||
import androidx.compose.runtime.remember
|
||||
import de.jeanlucmakiola.floret.time.rowWeekNumber
|
||||
import kotlinx.datetime.LocalDate
|
||||
import kotlinx.datetime.toJavaLocalDate
|
||||
import java.time.temporal.WeekFields
|
||||
|
||||
/**
|
||||
* The week number of the grid row starting on [rowStart], numbered by the
|
||||
* device region's rules (#493). The region, not the app language: an English
|
||||
* UI in the Netherlands still numbers weeks the ISO way. Shared by the Month
|
||||
* gutter and the Week badge so the two always agree.
|
||||
*/
|
||||
@Composable
|
||||
internal fun rememberRowWeekNumber(rowStart: LocalDate): Int {
|
||||
val fields = remember { WeekFields.of(Resources.getSystem().configuration.locales[0]) }
|
||||
return remember(rowStart, fields) { rowStart.toJavaLocalDate().rowWeekNumber(fields) }
|
||||
}
|
||||
@@ -108,7 +108,6 @@ import de.jeanlucmakiola.calendula.ui.common.LocalUse24HourFormat
|
||||
import de.jeanlucmakiola.calendula.ui.common.timeOfDayFormatter
|
||||
import de.jeanlucmakiola.calendula.ui.common.withRepeatedHourZone
|
||||
import de.jeanlucmakiola.calendula.ui.common.recurrenceText
|
||||
import de.jeanlucmakiola.calendula.ui.common.fixedTimeReminderLabel
|
||||
import de.jeanlucmakiola.calendula.ui.common.reminderLeadTimeLabel
|
||||
import kotlinx.coroutines.launch
|
||||
import kotlinx.datetime.TimeZone
|
||||
@@ -533,8 +532,7 @@ private fun EventDetailContent(
|
||||
.sortedBy { it.minutes }
|
||||
.forEach { reminder ->
|
||||
Text(
|
||||
text = state.fixedReminders[reminder.minutes]?.let { fixedTimeReminderLabel(it) }
|
||||
?: reminderLeadTimeLabel(reminder.minutes),
|
||||
text = reminderLeadTimeLabel(reminder.minutes),
|
||||
style = MaterialTheme.typography.titleMedium,
|
||||
modifier = Modifier.padding(vertical = 2.dp),
|
||||
)
|
||||
|
||||
@@ -3,7 +3,6 @@ package de.jeanlucmakiola.calendula.ui.detail
|
||||
import de.jeanlucmakiola.calendula.domain.EventDetail
|
||||
import de.jeanlucmakiola.calendula.domain.FailureReason
|
||||
import de.jeanlucmakiola.calendula.domain.RichText
|
||||
import de.jeanlucmakiola.calendula.domain.reminders.FixedTimeReminder
|
||||
|
||||
/**
|
||||
* UI state for the event-detail screen (spec S4).
|
||||
@@ -27,10 +26,6 @@ sealed interface EventDetailUiState {
|
||||
val phoneLinks: EventPhoneLinks = EventPhoneLinks(),
|
||||
/** The description as drawn — HTML rendered (#271); null when there is none. */
|
||||
val description: RichText? = null,
|
||||
/** Reminder offsets that read as "N days before at HH:MM" (#459), by raw minutes. */
|
||||
val fixedReminders: Map<Int, FixedTimeReminder> = emptyMap(),
|
||||
/** The fixed-time patterns the reminders were read against. */
|
||||
val knownFixed: Set<FixedTimeReminder> = emptySet(),
|
||||
) : EventDetailUiState
|
||||
}
|
||||
|
||||
|
||||
@@ -1,7 +1,5 @@
|
||||
package de.jeanlucmakiola.calendula.ui.detail
|
||||
|
||||
import de.jeanlucmakiola.calendula.data.prefs.SettingsPrefs
|
||||
import de.jeanlucmakiola.calendula.domain.reminders.classifyTimedReminder
|
||||
import android.net.Uri
|
||||
import androidx.lifecycle.ViewModel
|
||||
import androidx.lifecycle.viewModelScope
|
||||
@@ -48,7 +46,6 @@ class EventDetailViewModel @Inject constructor(
|
||||
private val icsExporter: IcsExporter,
|
||||
@IoDispatcher private val io: CoroutineDispatcher,
|
||||
private val zoneSource: ZoneSource,
|
||||
private val settingsPrefs: SettingsPrefs,
|
||||
) : ViewModel() {
|
||||
|
||||
private val _target = MutableStateFlow<Target?>(null)
|
||||
@@ -145,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, zoneSource.current(), loaded.knownFixed)
|
||||
return loaded.detail.toDuplicateForm(loaded.canModify, zoneSource.current())
|
||||
}
|
||||
|
||||
private suspend fun loadDetail(target: Target): EventDetailUiState = try {
|
||||
@@ -160,17 +157,6 @@ class EventDetailViewModel @Inject constructor(
|
||||
}
|
||||
val calendar = repository.calendars().first()
|
||||
.firstOrNull { it.id == corrected.instance.calendarId }
|
||||
val knownFixed = settingsPrefs.knownFixedTimeReminders.first()
|
||||
val fixedReminders = if (corrected.instance.isAllDay) {
|
||||
emptyMap()
|
||||
} else {
|
||||
val zone = zoneSource.current()
|
||||
corrected.reminders.map { it.minutes }.distinct().mapNotNull { minutes ->
|
||||
classifyTimedReminder(
|
||||
minutes, corrected.instance.start, zone, knownFixed, wallClock = corrected.rrule != null,
|
||||
)?.let { minutes to it }
|
||||
}.toMap()
|
||||
}
|
||||
val description = corrected.description
|
||||
?.let(::descriptionRichText)
|
||||
?.takeIf { it.text.isNotBlank() }
|
||||
@@ -187,8 +173,6 @@ class EventDetailViewModel @Inject constructor(
|
||||
description = description?.text,
|
||||
),
|
||||
description = description,
|
||||
fixedReminders = fixedReminders,
|
||||
knownFixed = knownFixed,
|
||||
)
|
||||
} catch (e: CancellationException) {
|
||||
throw e
|
||||
|
||||
@@ -118,6 +118,7 @@ import androidx.compose.ui.unit.dp
|
||||
import androidx.hilt.navigation.compose.hiltViewModel
|
||||
import androidx.lifecycle.compose.collectAsStateWithLifecycle
|
||||
import de.jeanlucmakiola.calendula.R
|
||||
import de.jeanlucmakiola.calendula.domain.canSaveAsOccurrence
|
||||
import de.jeanlucmakiola.calendula.domain.AccessLevel
|
||||
import de.jeanlucmakiola.calendula.domain.Availability
|
||||
import de.jeanlucmakiola.calendula.domain.EventStatus
|
||||
@@ -125,10 +126,6 @@ import de.jeanlucmakiola.calendula.domain.CalendarSource
|
||||
import de.jeanlucmakiola.calendula.domain.EventAttendee
|
||||
import de.jeanlucmakiola.calendula.domain.EventColorOption
|
||||
import de.jeanlucmakiola.calendula.domain.EventForm
|
||||
import de.jeanlucmakiola.calendula.domain.reminders.FixedTimeReminder
|
||||
import de.jeanlucmakiola.calendula.ui.common.DEFAULT_FIXED_TIME_REMINDER
|
||||
import de.jeanlucmakiola.calendula.ui.common.FixedTimeReminderEditor
|
||||
import de.jeanlucmakiola.calendula.ui.common.fixedTimeReminderLabel
|
||||
import de.jeanlucmakiola.calendula.domain.startInstant
|
||||
import de.jeanlucmakiola.calendula.domain.endInstant
|
||||
import de.jeanlucmakiola.calendula.domain.resolvedZone
|
||||
@@ -157,7 +154,6 @@ import de.jeanlucmakiola.calendula.ui.common.LocalSoftenColors
|
||||
import de.jeanlucmakiola.calendula.ui.common.eventAccent
|
||||
import de.jeanlucmakiola.calendula.ui.common.eventFill
|
||||
import de.jeanlucmakiola.floret.components.DialogAmountField
|
||||
import de.jeanlucmakiola.floret.components.GroupedHint
|
||||
import de.jeanlucmakiola.floret.components.DialogUnitDropdown
|
||||
import de.jeanlucmakiola.calendula.ui.common.eventFormFieldIcon
|
||||
import de.jeanlucmakiola.calendula.ui.common.eventFormFieldLabel
|
||||
@@ -456,12 +452,12 @@ fun EventEditScreen(
|
||||
|
||||
if (state?.saveState == SaveUiState.AwaitingScope) {
|
||||
// A changed rule rules out the single occurrence — an exception row
|
||||
// can't carry its own rule.
|
||||
// can't carry its own rule — and so does a cancelled one (#388).
|
||||
RecurringScopeDialog(
|
||||
title = stringResource(R.string.event_edit_recurring_title),
|
||||
onSelect = viewModel::saveWithScope,
|
||||
onDismiss = viewModel::consumeSaveResult,
|
||||
allowOccurrence = state?.recurrenceChanged != true,
|
||||
allowOccurrence = state?.recurrenceChanged != true && state?.form?.canSaveAsOccurrence() != false,
|
||||
)
|
||||
}
|
||||
|
||||
@@ -880,9 +876,7 @@ private fun EventEditContent(
|
||||
Spacer(Modifier.height(gap))
|
||||
RemindersSection(
|
||||
reminders = form.reminders,
|
||||
fixedReminders = if (form.isAllDay) emptyList() else form.fixedReminders,
|
||||
onRemove = viewModel::removeReminder,
|
||||
onRemoveFixed = viewModel::removeFixedReminder,
|
||||
onAdd = { sheet = EditSheet.Reminder },
|
||||
)
|
||||
}
|
||||
@@ -1291,25 +1285,9 @@ private fun LocationCard(
|
||||
* connected corners, the last row being "Add reminder".
|
||||
*/
|
||||
@Composable
|
||||
private fun RemindersSection(
|
||||
reminders: List<Int>,
|
||||
fixedReminders: List<FixedTimeReminder>,
|
||||
onRemove: (Int) -> Unit,
|
||||
onRemoveFixed: (FixedTimeReminder) -> Unit,
|
||||
onAdd: () -> Unit,
|
||||
) {
|
||||
val rows = fixedReminders.size + reminders.size + 1
|
||||
fixedReminders.forEachIndexed { index, reminder ->
|
||||
GroupedItemCard(
|
||||
position = positionOf(index, rows),
|
||||
icon = Icons.Default.Notifications,
|
||||
title = fixedTimeReminderLabel(reminder),
|
||||
removeContentDescription = stringResource(R.string.event_edit_remove_reminder),
|
||||
onRemove = { onRemoveFixed(reminder) },
|
||||
)
|
||||
}
|
||||
reminders.forEachIndexed { i, minutes ->
|
||||
val index = fixedReminders.size + i
|
||||
private fun RemindersSection(reminders: List<Int>, onRemove: (Int) -> Unit, onAdd: () -> Unit) {
|
||||
val rows = reminders.size + 1
|
||||
reminders.forEachIndexed { index, minutes ->
|
||||
GroupedItemCard(
|
||||
position = positionOf(index, rows),
|
||||
icon = Icons.Default.Notifications,
|
||||
@@ -1320,7 +1298,7 @@ private fun RemindersSection(
|
||||
}
|
||||
AddActionCard(
|
||||
label = stringResource(R.string.event_edit_add_reminder),
|
||||
position = positionOf(rows - 1, rows),
|
||||
position = positionOf(reminders.size, rows),
|
||||
onClick = onAdd,
|
||||
)
|
||||
}
|
||||
@@ -1512,15 +1490,10 @@ private fun EditSheetHost(
|
||||
}
|
||||
EditSheet.Reminder -> ReminderPickerDialog(
|
||||
alreadyChosen = form.reminders,
|
||||
offerFixedTime = !form.isAllDay,
|
||||
onSelect = { minutes ->
|
||||
viewModel.addReminder(minutes)
|
||||
onClose()
|
||||
},
|
||||
onSelectFixed = { reminder ->
|
||||
viewModel.addFixedReminder(reminder)
|
||||
onClose()
|
||||
},
|
||||
onDismiss = onClose,
|
||||
)
|
||||
EditSheet.Recurrence -> RecurrencePickerDialog(
|
||||
@@ -1609,14 +1582,10 @@ private fun FieldPickerDialog(
|
||||
@Composable
|
||||
private fun ReminderPickerDialog(
|
||||
alreadyChosen: List<Int>,
|
||||
offerFixedTime: Boolean,
|
||||
onSelect: (Int) -> Unit,
|
||||
onSelectFixed: (FixedTimeReminder) -> Unit,
|
||||
onDismiss: () -> Unit,
|
||||
) {
|
||||
var customMode by rememberSaveable { mutableStateOf(false) }
|
||||
var fixedMode by rememberSaveable { mutableStateOf(false) }
|
||||
var pendingFixed by remember { mutableStateOf<FixedTimeReminder?>(null) }
|
||||
var amountText by rememberSaveable { mutableStateOf("") }
|
||||
var unit by rememberSaveable { mutableStateOf(ReminderUnit.Minutes) }
|
||||
val customMinutes = amountText.toIntOrNull()
|
||||
@@ -1627,31 +1596,18 @@ private fun ReminderPickerDialog(
|
||||
title = stringResource(R.string.event_edit_add_reminder),
|
||||
onDismiss = onDismiss,
|
||||
actions = {
|
||||
// The quick-pick list adds on tap; only the custom steps need Add.
|
||||
// The quick-pick list adds on tap; only the custom step needs Add.
|
||||
if (customMode) {
|
||||
TextButton(
|
||||
enabled = customMinutes != null && customMinutes !in alreadyChosen,
|
||||
onClick = { customMinutes?.let(onSelect) },
|
||||
) { Text(stringResource(R.string.event_edit_add)) }
|
||||
} else if (fixedMode) {
|
||||
TextButton(
|
||||
enabled = pendingFixed != null,
|
||||
onClick = { pendingFixed?.let(onSelectFixed) },
|
||||
) { Text(stringResource(R.string.event_edit_add)) }
|
||||
}
|
||||
},
|
||||
) {
|
||||
if (fixedMode) {
|
||||
GroupedHint(text = stringResource(R.string.event_edit_reminder_fixed_hint))
|
||||
Spacer(Modifier.height(8.dp))
|
||||
FixedTimeReminderEditor(
|
||||
initial = DEFAULT_FIXED_TIME_REMINDER,
|
||||
onValueChange = { pendingFixed = it },
|
||||
connected = false,
|
||||
)
|
||||
} else if (!customMode) {
|
||||
if (!customMode) {
|
||||
val presets = REMINDER_PRESETS.filterNot { it in alreadyChosen }
|
||||
val rowCount = presets.size + if (offerFixedTime) 2 else 1
|
||||
val rowCount = presets.size + 1
|
||||
presets.forEachIndexed { index, minutes ->
|
||||
GroupedRow(
|
||||
title = reminderLeadTimeLabel(minutes),
|
||||
@@ -1659,14 +1615,6 @@ private fun ReminderPickerDialog(
|
||||
onClick = { onSelect(minutes) },
|
||||
)
|
||||
}
|
||||
if (offerFixedTime) {
|
||||
GroupedRow(
|
||||
title = stringResource(R.string.reminder_fixed_at_set_time),
|
||||
summary = stringResource(R.string.event_edit_reminder_fixed_summary),
|
||||
position = positionOf(presets.size, rowCount),
|
||||
onClick = { fixedMode = true },
|
||||
)
|
||||
}
|
||||
GroupedRow(
|
||||
title = stringResource(R.string.event_edit_reminder_custom),
|
||||
position = positionOf(rowCount - 1, rowCount),
|
||||
|
||||
@@ -13,13 +13,8 @@ import de.jeanlucmakiola.calendula.data.prefs.SettingsPrefs
|
||||
import de.jeanlucmakiola.calendula.data.time.ZoneSource
|
||||
import de.jeanlucmakiola.calendula.data.prefs.firstDayOfWeek
|
||||
import de.jeanlucmakiola.calendula.data.prefs.resolveDefaultEventDuration
|
||||
import de.jeanlucmakiola.calendula.data.prefs.resolveDefaultFixedTimeReminder
|
||||
import de.jeanlucmakiola.calendula.data.prefs.resolveDefaultReminder
|
||||
import de.jeanlucmakiola.calendula.domain.reminders.FIXED_ORDER
|
||||
import de.jeanlucmakiola.calendula.domain.reminders.FixedTimeReminder
|
||||
import de.jeanlucmakiola.calendula.domain.fixedReminderOffsets
|
||||
import de.jeanlucmakiola.calendula.domain.withFixedTimeRemindersRead
|
||||
import de.jeanlucmakiola.calendula.domain.canSaveApartFromSeries
|
||||
import de.jeanlucmakiola.calendula.domain.canSaveAsOccurrence
|
||||
import de.jeanlucmakiola.calendula.domain.AccessLevel
|
||||
import de.jeanlucmakiola.calendula.domain.Availability
|
||||
import de.jeanlucmakiola.calendula.domain.EventStatus
|
||||
@@ -144,7 +139,6 @@ enum class ImportSource(internal val ownsDuration: Boolean) {
|
||||
data class ImportReminderPrompt(
|
||||
val currentReminderCount: Int,
|
||||
val defaultReminders: List<Int>,
|
||||
val defaultFixedReminders: List<FixedTimeReminder> = emptyList(),
|
||||
)
|
||||
|
||||
/**
|
||||
@@ -214,8 +208,6 @@ class EventEditViewModel @Inject constructor(
|
||||
val zone: TimeZone,
|
||||
/** The event as loaded, on the tapped occurrence's times — what Share exports. */
|
||||
val detail: EventDetail,
|
||||
/** The fixed-time patterns its reminders were read against, so a re-read splits alike. */
|
||||
val knownFixed: Set<FixedTimeReminder>,
|
||||
) {
|
||||
val original: EventForm get() = snapshot.form
|
||||
}
|
||||
@@ -233,13 +225,7 @@ class EventEditViewModel @Inject constructor(
|
||||
val allDay: List<Int>,
|
||||
val timedOverrides: Map<Long, List<Int>>,
|
||||
val allDayOverrides: Map<Long, List<Int>>,
|
||||
val fixed: FixedTimeReminder?,
|
||||
val fixedOverrides: Map<Long, FixedTimeReminder?>,
|
||||
) {
|
||||
/** The fixed-time reminders a new event on [calendarId] gets (#459); none on an all-day one. */
|
||||
fun resolveFixedFor(calendarId: Long?, isAllDay: Boolean): List<FixedTimeReminder> =
|
||||
if (isAllDay) emptyList() else listOfNotNull(resolveDefaultFixedTimeReminder(fixed, fixedOverrides, calendarId))
|
||||
|
||||
/** The default reminders for an event on [calendarId] of the given kind. */
|
||||
fun resolveFor(calendarId: Long?, isAllDay: Boolean): List<Int> = resolveDefaultReminder(
|
||||
timedGlobal = timed,
|
||||
@@ -449,7 +435,7 @@ class EventEditViewModel @Inject constructor(
|
||||
if (source.ownsDuration) _durationTouched.value = true else applyDefaultDuration()
|
||||
when (source) {
|
||||
ImportSource.Insert, ImportSource.InsertOpenEnded ->
|
||||
if (form.reminders.isNotEmpty() || form.fixedReminders.isNotEmpty()) _remindersTouched.value = true
|
||||
if (form.reminders.isNotEmpty()) _remindersTouched.value = true
|
||||
else applyDefaultReminder()
|
||||
|
||||
ImportSource.File -> {
|
||||
@@ -479,35 +465,27 @@ class EventEditViewModel @Inject constructor(
|
||||
val form = _form.value ?: return@launch
|
||||
if (_editTarget.value != null || _remindersTouched.value) return@launch
|
||||
val reminders = defaults.resolveFor(targetId, form.isAllDay)
|
||||
val fixed = defaults.resolveFixedFor(targetId, form.isAllDay)
|
||||
// The duration default resolves in parallel, so both must compose
|
||||
// onto the current form, not a pre-suspend copy.
|
||||
applyDefault { it.copy(reminders = reminders, fixedReminders = fixed) }
|
||||
applyDefault { it.copy(reminders = reminders) }
|
||||
// Surface the section so an auto-applied default is visible and
|
||||
// removable, even when Reminders isn't a default-shown field.
|
||||
if (reminders.isNotEmpty() || fixed.isNotEmpty()) {
|
||||
if (reminders.isNotEmpty()) {
|
||||
_revealed.value = _revealed.value + EventFormField.Reminders
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/** Snapshot the settings-default reminder flows into one value. */
|
||||
/** Snapshot the four settings-default reminder flows into one value. */
|
||||
private suspend fun reminderDefaults(): ReminderDefaults = combine(
|
||||
combine(
|
||||
settingsPrefs.defaultReminderMinutes,
|
||||
settingsPrefs.defaultAllDayReminderMinutes,
|
||||
settingsPrefs.perCalendarReminderOverride,
|
||||
settingsPrefs.perCalendarAllDayReminderOverride,
|
||||
::Quadruple,
|
||||
),
|
||||
settingsPrefs.defaultFixedTimeReminder,
|
||||
settingsPrefs.perCalendarFixedTimeReminderOverride,
|
||||
) { (timed, allDay, timedOv, allDayOv), fixed, fixedOv ->
|
||||
ReminderDefaults(timed, allDay, timedOv, allDayOv, fixed, fixedOv)
|
||||
settingsPrefs.defaultReminderMinutes,
|
||||
settingsPrefs.defaultAllDayReminderMinutes,
|
||||
settingsPrefs.perCalendarReminderOverride,
|
||||
settingsPrefs.perCalendarAllDayReminderOverride,
|
||||
) { timed, allDay, timedOv, allDayOv ->
|
||||
ReminderDefaults(timed, allDay, timedOv, allDayOv)
|
||||
}.first()
|
||||
|
||||
private data class Quadruple<A, B, C, D>(val a: A, val b: B, val c: C, val d: D)
|
||||
|
||||
/**
|
||||
* Stretch a new timed event to the configured default length (#54) — the
|
||||
* resolved calendar's per-calendar duration, otherwise the global default —
|
||||
@@ -553,19 +531,15 @@ class EventEditViewModel @Inject constructor(
|
||||
val opened = session
|
||||
viewModelScope.launch {
|
||||
val targetId = resolvedCalendarId.first()
|
||||
val defaults = reminderDefaults()
|
||||
val default = defaults.resolveFor(targetId, form.isAllDay)
|
||||
val fixed = defaults.resolveFixedFor(targetId, form.isAllDay)
|
||||
val default = reminderDefaults().resolveFor(targetId, form.isAllDay)
|
||||
// Bail if the form closed or became an edit while we resolved.
|
||||
if (opened != session) return@launch
|
||||
val current = _form.value ?: return@launch
|
||||
if (_editTarget.value != null) return@launch
|
||||
if (default.isEmpty() && fixed.isEmpty()) return@launch
|
||||
if (default == current.reminders && fixed == current.fixedReminders) return@launch
|
||||
if (default.isEmpty() || default == current.reminders) return@launch
|
||||
_importReminderPrompt.value = ImportReminderPrompt(
|
||||
currentReminderCount = current.reminders.size + current.fixedReminders.size,
|
||||
currentReminderCount = current.reminders.size,
|
||||
defaultReminders = default,
|
||||
defaultFixedReminders = fixed,
|
||||
)
|
||||
}
|
||||
}
|
||||
@@ -575,7 +549,7 @@ class EventEditViewModel @Inject constructor(
|
||||
val prompt = _importReminderPrompt.value ?: return
|
||||
_importReminderPrompt.value = null
|
||||
// Already frozen as touched by openImported; this just swaps the values.
|
||||
edit { it.copy(reminders = prompt.defaultReminders, fixedReminders = prompt.defaultFixedReminders) }
|
||||
edit { it.copy(reminders = prompt.defaultReminders) }
|
||||
_revealed.value = _revealed.value + EventFormField.Reminders
|
||||
}
|
||||
|
||||
@@ -605,15 +579,14 @@ class EventEditViewModel @Inject constructor(
|
||||
if (opened == session) _loadFailed.value = true
|
||||
return@launch
|
||||
}
|
||||
val knownFixed = settingsPrefs.knownFixedTimeReminders.first()
|
||||
if (opened != session) return@launch
|
||||
val zone = zoneSource.current()
|
||||
val begin = beginMillis.takeUnless { it == NO_OCCURRENCE_TIME }
|
||||
?: detail.instance.start.toEpochMilliseconds()
|
||||
val end = endMillis.takeUnless { it == NO_OCCURRENCE_TIME }
|
||||
?: detail.instance.end.toEpochMilliseconds()
|
||||
val snapshot = detail.toEditSnapshot(begin, end, zone).withFixedTimeRemindersRead(knownFixed, zone)
|
||||
_editTarget.value = EditTarget(eventId, snapshot, begin, end, zone, detail.atOccurrence(begin, end), knownFixed)
|
||||
val snapshot = detail.toEditSnapshot(begin, end, zone)
|
||||
_editTarget.value = EditTarget(eventId, snapshot, begin, end, zone, detail.atOccurrence(begin, end))
|
||||
// Sections holding data must show even when not in the defaults.
|
||||
_revealed.value = snapshot.form.populatedFields()
|
||||
open(snapshot.form)
|
||||
@@ -718,11 +691,7 @@ class EventEditViewModel @Inject constructor(
|
||||
|
||||
fun addReminder(minutes: Int) {
|
||||
_remindersTouched.value = true
|
||||
edit {
|
||||
// A lead firing with a set-time reminder would be one row once saved.
|
||||
if (minutes in it.fixedReminderOffsets(zoneSource.current())) it
|
||||
else it.copy(reminders = (it.reminders + minutes).distinct().sorted())
|
||||
}
|
||||
edit { it.copy(reminders = (it.reminders + minutes).distinct().sorted()) }
|
||||
}
|
||||
|
||||
fun removeReminder(minutes: Int) {
|
||||
@@ -730,26 +699,6 @@ class EventEditViewModel @Inject constructor(
|
||||
edit { it.copy(reminders = it.reminders - minutes) }
|
||||
}
|
||||
|
||||
/**
|
||||
* Add an "N days before at HH:MM" reminder (#459); timed events only. A lead
|
||||
* time landing on the same moment is replaced by it — the two would be one
|
||||
* row once saved.
|
||||
*/
|
||||
fun addFixedReminder(reminder: FixedTimeReminder) {
|
||||
_remindersTouched.value = true
|
||||
edit { form ->
|
||||
if (form.isAllDay) return@edit form
|
||||
val withFixed = form.copy(fixedReminders = (form.fixedReminders + reminder).distinct().sortedWith(FIXED_ORDER))
|
||||
val offsets = withFixed.fixedReminderOffsets(zoneSource.current()).toSet()
|
||||
withFixed.copy(reminders = form.reminders.filterNot { it in offsets })
|
||||
}
|
||||
}
|
||||
|
||||
fun removeFixedReminder(reminder: FixedTimeReminder) {
|
||||
_remindersTouched.value = true
|
||||
edit { it.copy(fixedReminders = it.fixedReminders - reminder) }
|
||||
}
|
||||
|
||||
/**
|
||||
* Add a guest, keyed on a trimmed lower-cased email so re-adding the same
|
||||
* address just refreshes it (no duplicate row). A blank email is ignored —
|
||||
@@ -821,10 +770,7 @@ class EventEditViewModel @Inject constructor(
|
||||
// Managed events are a yearly series whose editable fields (reminders,
|
||||
// notes, location) live on the series row — never offer the scope dialog,
|
||||
// which would split the series into an exception the sync then reverts.
|
||||
// A cancelled one only saves as the whole series (#388).
|
||||
if (target != null && target.original.rrule != null && !current.isManaged && !movingCalendar &&
|
||||
form.canSaveApartFromSeries()
|
||||
) {
|
||||
if (target != null && target.original.rrule != null && !current.isManaged && !movingCalendar) {
|
||||
_saveState.value = SaveUiState.AwaitingScope
|
||||
return
|
||||
}
|
||||
@@ -835,6 +781,7 @@ class EventEditViewModel @Inject constructor(
|
||||
fun saveWithScope(scope: RecurringWriteScope) {
|
||||
val current = state.value ?: return
|
||||
if (current.saveState != SaveUiState.AwaitingScope) return
|
||||
if (scope == RecurringWriteScope.ThisEvent && !current.form.canSaveAsOccurrence()) return
|
||||
performSave(current.form, scope)
|
||||
}
|
||||
|
||||
@@ -866,7 +813,6 @@ class EventEditViewModel @Inject constructor(
|
||||
val fresh = try {
|
||||
repository.eventDetail(target.eventId)
|
||||
.toEditSnapshot(target.beginMillis, target.endMillis, target.zone)
|
||||
.withFixedTimeRemindersRead(target.knownFixed, target.zone)
|
||||
} catch (e: CancellationException) {
|
||||
throw e
|
||||
} catch (e: NoSuchEventException) {
|
||||
@@ -881,17 +827,6 @@ class EventEditViewModel @Inject constructor(
|
||||
return@launch
|
||||
}
|
||||
}
|
||||
// Remembered before the write, so the rows read back as these
|
||||
// reminders from the first re-read on (#459).
|
||||
if (!form.isAllDay && form.fixedReminders.isNotEmpty()) {
|
||||
try {
|
||||
settingsPrefs.rememberFixedTimeReminders(form.fixedReminders)
|
||||
} catch (e: CancellationException) {
|
||||
throw e
|
||||
} catch (e: Exception) {
|
||||
Log.w(TAG, "Could not remember the set-time reminders", e)
|
||||
}
|
||||
}
|
||||
val result = try {
|
||||
if (target == null) {
|
||||
repository.createEvent(form)
|
||||
@@ -1013,7 +948,3 @@ class EventEditViewModel @Inject constructor(
|
||||
_form.value = _form.value?.let(block)
|
||||
}
|
||||
}
|
||||
|
||||
/** [EditSnapshot.form] with its timed reminders read back into lead times and fixed-time ones. */
|
||||
private fun EditSnapshot.withFixedTimeRemindersRead(known: Set<FixedTimeReminder>, zone: TimeZone): EditSnapshot =
|
||||
copy(form = form.withFixedTimeRemindersRead(known, zone))
|
||||
@@ -2,28 +2,17 @@ package de.jeanlucmakiola.calendula.ui.month
|
||||
|
||||
import androidx.compose.material3.MaterialTheme
|
||||
import androidx.compose.runtime.Composable
|
||||
import androidx.compose.runtime.Stable
|
||||
import androidx.compose.runtime.remember
|
||||
import androidx.compose.ui.graphics.Color
|
||||
import androidx.compose.ui.platform.LocalDensity
|
||||
import androidx.compose.ui.text.TextMeasurer
|
||||
import androidx.compose.ui.text.TextStyle
|
||||
import androidx.compose.ui.text.rememberTextMeasurer
|
||||
import androidx.compose.ui.unit.Density
|
||||
import androidx.compose.ui.unit.Dp
|
||||
import de.jeanlucmakiola.calendula.domain.EventInstance
|
||||
import de.jeanlucmakiola.calendula.domain.coversWholeDays
|
||||
import de.jeanlucmakiola.calendula.ui.common.formatTimeOfDay
|
||||
import de.jeanlucmakiola.calendula.ui.common.inlineTimeLabel
|
||||
import de.jeanlucmakiola.calendula.ui.common.rememberWidestTimeSample
|
||||
import de.jeanlucmakiola.calendula.ui.common.trimmedLines
|
||||
import de.jeanlucmakiola.calendula.ui.common.rememberInlineTimeWidth
|
||||
import kotlinx.datetime.TimeZone
|
||||
import java.util.Locale
|
||||
|
||||
/**
|
||||
* The start time a chip shows before its title (#219), or null when it has none
|
||||
* to show: a chip filling whole days never carries a time (#296), and neither
|
||||
* does a bar carried in from an earlier week, whose start is not in this segment.
|
||||
* to show: an all-day chip never carries a time, and neither does a bar carried
|
||||
* in from an earlier week, whose start is not in this segment.
|
||||
*/
|
||||
internal fun monthChipTime(
|
||||
event: EventInstance,
|
||||
@@ -32,75 +21,11 @@ internal fun monthChipTime(
|
||||
is24Hour: Boolean,
|
||||
locale: Locale,
|
||||
): String? {
|
||||
if (event.coversWholeDays(zone) || continuesLeft) return null
|
||||
if (event.isAllDay || continuesLeft) return null
|
||||
return formatTimeOfDay(event.start, zone, is24Hour, locale)
|
||||
}
|
||||
|
||||
/** How many characters of a longer title a chip must keep beside its start time (#476). */
|
||||
internal const val MONTH_TITLE_MIN_CHARS = 12
|
||||
|
||||
/**
|
||||
* The part of [title] that has to stay readable beside a start time: all of it,
|
||||
* or its first [MONTH_TITLE_MIN_CHARS] characters, counted in code points so an
|
||||
* emoji is never cut in half.
|
||||
*/
|
||||
internal fun monthTitleToKeep(title: String): String {
|
||||
if (title.codePointCount(0, title.length) <= MONTH_TITLE_MIN_CHARS) return title
|
||||
return title.substring(0, title.offsetByCodePoints(0, MONTH_TITLE_MIN_CHARS))
|
||||
}
|
||||
|
||||
/**
|
||||
* Whether a chip shows its start time (#219, #476): only with the setting
|
||||
* [enabled], and only when [availableWidth] (the chip less its chrome) holds
|
||||
* [labelWidth], the widest time followed by [monthTitleToKeep] of the title.
|
||||
*/
|
||||
internal fun monthChipShowsTime(
|
||||
enabled: Boolean,
|
||||
availableWidth: Float,
|
||||
labelWidth: Float,
|
||||
): Boolean = enabled && labelWidth <= availableWidth
|
||||
|
||||
/**
|
||||
* Prices month chips' time labels for [monthChipShowsTime] in the chips' own
|
||||
* text style. One per grid; each title is measured once for its lifetime.
|
||||
*/
|
||||
@Stable
|
||||
internal class MonthChipTimeFit(
|
||||
private val measurer: TextMeasurer,
|
||||
private val style: TextStyle,
|
||||
private val density: Density,
|
||||
private val timeSample: String,
|
||||
) {
|
||||
private val chromePx = with(density) { MONTH_CHIP_CHROME.toPx() }
|
||||
private val labelWidths = HashMap<String, Int>()
|
||||
|
||||
fun showsTime(chipWidth: Dp, title: String): Boolean {
|
||||
if (labelWidths.size >= MAX_CACHED_TITLES) labelWidths.clear()
|
||||
val labelWidth = labelWidths.getOrPut(title) {
|
||||
val label = inlineTimeLabel(timeSample, monthTitleToKeep(title), Color.Unspecified)
|
||||
measurer.measure(label, style, softWrap = false, maxLines = 1).size.width
|
||||
}
|
||||
return monthChipShowsTime(
|
||||
enabled = true,
|
||||
availableWidth = with(density) { chipWidth.toPx() } - chromePx,
|
||||
labelWidth = labelWidth.toFloat(),
|
||||
)
|
||||
}
|
||||
|
||||
private companion object {
|
||||
const val MAX_CACHED_TITLES = 1000
|
||||
}
|
||||
}
|
||||
|
||||
/** The grid's [MonthChipTimeFit], or null when start times are switched off (#476). */
|
||||
/** The narrowest chip that may show a time — the text it needs, plus its chrome. */
|
||||
@Composable
|
||||
internal fun rememberMonthChipTimeFit(showStartTimes: Boolean): MonthChipTimeFit? {
|
||||
if (!showStartTimes) return null
|
||||
val measurer = rememberTextMeasurer(cacheSize = 0)
|
||||
val style = MaterialTheme.typography.labelSmall.trimmedLines()
|
||||
val density = LocalDensity.current
|
||||
val timeSample = rememberWidestTimeSample()
|
||||
return remember(measurer, style, density, timeSample) {
|
||||
MonthChipTimeFit(measurer, style, density, timeSample)
|
||||
}
|
||||
}
|
||||
internal fun rememberMonthTimeChipWidth(): Dp =
|
||||
rememberInlineTimeWidth(MaterialTheme.typography.labelSmall) + MONTH_CHIP_CHROME
|
||||
@@ -14,7 +14,8 @@ import androidx.compose.ui.layout.boundsInRoot
|
||||
import androidx.compose.ui.layout.positionInRoot
|
||||
import androidx.compose.ui.unit.IntSize
|
||||
import de.jeanlucmakiola.calendula.domain.EventInstance
|
||||
import de.jeanlucmakiola.calendula.ui.common.nextMoveToken
|
||||
import de.jeanlucmakiola.calendula.ui.common.LocalEventMove
|
||||
import kotlinx.coroutines.flow.StateFlow
|
||||
import kotlinx.datetime.LocalDate
|
||||
import kotlin.math.abs
|
||||
|
||||
@@ -106,22 +107,11 @@ data class MonthChipDrag(
|
||||
val time: String? = null,
|
||||
)
|
||||
|
||||
/** A drop parked by a newer pickup while its write still runs — see [MonthDragController.held]. */
|
||||
data class HeldChip(
|
||||
val copy: MonthChipDrag,
|
||||
val token: Long,
|
||||
val handedOver: Boolean = false,
|
||||
/** Where the grid now draws the drop, in root coordinates, once a row seats it. */
|
||||
val seat: Offset? = null,
|
||||
)
|
||||
|
||||
/** Where a finished chip drag asks its event to go, as a whole-day shift. */
|
||||
data class MonthChipDrop(
|
||||
val event: EventInstance,
|
||||
val grabDate: LocalDate,
|
||||
val targetDate: LocalDate,
|
||||
/** The drop's identity, which its held copy waits on — see [MonthDragController.settledToken]. */
|
||||
val token: Long,
|
||||
)
|
||||
|
||||
/**
|
||||
@@ -177,22 +167,19 @@ class MonthDragController {
|
||||
private set
|
||||
|
||||
/**
|
||||
* This controller's recent drops by token, kept past [release] for
|
||||
* [beginUndo] — the confirmation chip carries Undo long after the copy is
|
||||
* gone, and it may be any of them the chip offers to undo.
|
||||
* The last drop this controller made, kept past [release] for [beginUndo] —
|
||||
* the confirmation chip carries Undo long after the copy is gone.
|
||||
*/
|
||||
private val undoable = LinkedHashMap<Long, MonthChipDrag>()
|
||||
private var undoable: MonthChipDrag? = null
|
||||
|
||||
/**
|
||||
* Earlier drops still being written when another chip was picked up. They
|
||||
* keep their copy and their ghost until their own token settles, rather than
|
||||
* vanishing and flashing back on the old day (#494).
|
||||
* The abandoned-move counter, read at the drop so the mark can't be a
|
||||
* composition behind the tick it is compared against.
|
||||
*/
|
||||
var held: List<HeldChip> by mutableStateOf(emptyList())
|
||||
private set
|
||||
var abandonedTicks: StateFlow<Int>? = null
|
||||
|
||||
/** The token of the drop (or undo) [settling] is waiting on. */
|
||||
var settledToken: Long = 0L
|
||||
/** What [abandonedTicks] stood at when the settling chip was let go. */
|
||||
var settledAbandonedMark: Int = 0
|
||||
private set
|
||||
|
||||
private var event: EventInstance? = null
|
||||
@@ -221,7 +208,7 @@ class MonthDragController {
|
||||
this.event = event
|
||||
this.grabDate = grabDate
|
||||
this.time = time
|
||||
parkSettling()
|
||||
settling = null
|
||||
isDragging = true
|
||||
liftedInstanceId = event.instanceId
|
||||
grab = pointerInRoot - chipInRoot
|
||||
@@ -247,39 +234,6 @@ class MonthDragController {
|
||||
settledGhost = false
|
||||
}
|
||||
|
||||
/**
|
||||
* Whether [event]'s chip belongs to a held drop and must stay a ghost: its
|
||||
* source, or once a row seats it, the chip the grid draws on its target day.
|
||||
*/
|
||||
fun isHeldChip(event: EventInstance, days: List<LocalDate>?): Boolean = held.any { parked ->
|
||||
!parked.handedOver && (
|
||||
parked.copy.event.instanceId == event.instanceId ||
|
||||
(
|
||||
parked.seat != null && days != null && parked.copy.targetDate in days &&
|
||||
isSameEvent(event, parked.copy.event)
|
||||
)
|
||||
)
|
||||
}
|
||||
|
||||
/** Move a still-settling drop to [held] before a new pickup takes the slot. */
|
||||
private fun parkSettling() {
|
||||
val landed = settling
|
||||
if (landed != null) held = held + HeldChip(landed, settledToken)
|
||||
settling = null
|
||||
settledInRoot = null
|
||||
settledGhost = false
|
||||
}
|
||||
|
||||
/** Stop ghosting the held drop [token]'s source while its copy fades. */
|
||||
fun handOverHeld(token: Long) {
|
||||
held = held.map { if (it.token == token) it.copy(handedOver = true) else it }
|
||||
}
|
||||
|
||||
/** Drop the held copy [token] once it has faded. */
|
||||
fun releaseHeld(token: Long) {
|
||||
held = held.filterNot { it.token == token }
|
||||
}
|
||||
|
||||
/**
|
||||
* Whether [days] holds the chip the grid has drawn for the settled drop —
|
||||
* the seat the copy is on its way to, which must ghost until it gets there.
|
||||
@@ -296,13 +250,6 @@ class MonthDragController {
|
||||
* nearest where the chip was let go is the one the finger was over.
|
||||
*/
|
||||
fun noteSettled(token: Any) {
|
||||
val row = rows[token]
|
||||
if (row != null && held.any { it.seat == null }) {
|
||||
held = held.map { parked ->
|
||||
val target = parked.copy.targetDate
|
||||
if (parked.seat != null || target == null) parked else parked.copy(seat = row.seatOf(parked.copy.event, target))
|
||||
}
|
||||
}
|
||||
val landed = settling ?: return
|
||||
val target = landed.targetDate ?: return
|
||||
val at = rows[token]?.seatOf(landed.event, target) ?: return
|
||||
@@ -318,16 +265,16 @@ class MonthDragController {
|
||||
* there is no drop of this controller's left to undo, or the grid doesn't
|
||||
* seat the moved event where the chip would have to start from.
|
||||
*/
|
||||
fun beginUndo(token: Long, dropToken: Long): Boolean {
|
||||
val last = undoable.remove(dropToken) ?: return false
|
||||
parkSettling()
|
||||
fun beginUndo(): Boolean {
|
||||
val last = undoable ?: return false
|
||||
undoable = null
|
||||
val from = last.targetDate ?: return false
|
||||
val at = rows.values.firstNotNullOfOrNull { it.seatOf(last.event, from) } ?: return false
|
||||
settling = last.copy(grabDate = from, targetDate = last.grabDate, topLeftInRoot = at)
|
||||
liftedInstanceId = last.event.instanceId
|
||||
settledGhost = true
|
||||
settledInRoot = null
|
||||
settledToken = token
|
||||
settledAbandonedMark = abandonedTicks?.value ?: 0
|
||||
return true
|
||||
}
|
||||
|
||||
@@ -347,11 +294,10 @@ class MonthDragController {
|
||||
)
|
||||
liftedInstanceId = landed.event.instanceId
|
||||
settledGhost = true
|
||||
settledToken = nextMoveToken()
|
||||
undoable[settledToken] = requireNotNull(settling)
|
||||
if (undoable.size > UNDOABLE_KEPT) undoable.remove(undoable.keys.first())
|
||||
undoable = settling
|
||||
settledAbandonedMark = abandonedTicks?.value ?: 0
|
||||
drops++
|
||||
return MonthChipDrop(landed.event, landed.grabDate, target, settledToken)
|
||||
return MonthChipDrop(landed.event, landed.grabDate, target)
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -409,10 +355,9 @@ class MonthDragController {
|
||||
|
||||
@Composable
|
||||
fun rememberMonthDragController(): MonthDragController {
|
||||
return remember { MonthDragController() }
|
||||
val controller = remember { MonthDragController() }
|
||||
controller.abandonedTicks = LocalEventMove.current?.abandoned
|
||||
return controller
|
||||
}
|
||||
|
||||
val LocalMonthDrag = compositionLocalOf<MonthDragController?> { null }
|
||||
|
||||
/** How many recent drops a month controller keeps for an undo to carry back. */
|
||||
private const val UNDOABLE_KEPT = 8
|
||||
@@ -34,10 +34,6 @@ internal sealed interface MonthMorphKey {
|
||||
|
||||
data class DayNumber(val date: LocalDate) : MonthMorphKey
|
||||
|
||||
data class WeekNumber(val weekStart: LocalDate) : MonthMorphKey
|
||||
|
||||
data class CellRipple(val date: LocalDate) : MonthMorphKey
|
||||
|
||||
/**
|
||||
* One event *on one day*. Keyed by date as well as instance because a
|
||||
* multi-day event has a dot on every day it covers but only one bar, drawn
|
||||
@@ -115,8 +111,8 @@ internal fun morphInFlight(): Boolean {
|
||||
*
|
||||
* Rendering in place puts everything back in one z-order and one clip, which is
|
||||
* what makes the grid read as a single surface changing shape rather than a
|
||||
* stack of pieces sliding past each other. Event marks are the exception: they
|
||||
* render in the overlay so the expanding day backgrounds cannot cover them.
|
||||
* stack of pieces sliding past each other. Nothing here needs to escape its
|
||||
* ancestors: the cells, marks and markers all travel within the grid.
|
||||
*/
|
||||
@OptIn(ExperimentalSharedTransitionApi::class)
|
||||
@Composable
|
||||
@@ -145,7 +141,6 @@ internal fun Modifier.morphElement(key: MonthMorphKey): Modifier {
|
||||
@Composable
|
||||
internal fun Modifier.morphBounds(key: MonthMorphKey): Modifier {
|
||||
val morph = LocalMonthMorph.current ?: return this
|
||||
val isEvent = key is MonthMorphKey.Event
|
||||
return with(morph.shared) {
|
||||
this@morphBounds.sharedBounds(
|
||||
sharedContentState = rememberSharedContentState(key),
|
||||
@@ -153,8 +148,7 @@ internal fun Modifier.morphBounds(key: MonthMorphKey): Modifier {
|
||||
enter = fadeIn(),
|
||||
exit = fadeOut(),
|
||||
resizeMode = SharedTransitionScope.ResizeMode.RemeasureToBounds,
|
||||
renderInOverlayDuringTransition = isEvent,
|
||||
zIndexInOverlay = if (isEvent) 1f else 0f,
|
||||
renderInOverlayDuringTransition = false,
|
||||
)
|
||||
}
|
||||
}
|
||||
@@ -2,12 +2,7 @@ package de.jeanlucmakiola.calendula.ui.month
|
||||
|
||||
import androidx.activity.compose.BackHandler
|
||||
import androidx.compose.animation.AnimatedContent
|
||||
import androidx.compose.foundation.interaction.MutableInteractionSource
|
||||
import androidx.compose.foundation.indication
|
||||
import androidx.compose.foundation.LocalIndication
|
||||
import androidx.compose.animation.EnterExitState
|
||||
import androidx.compose.animation.EnterTransition
|
||||
import androidx.compose.animation.ExitTransition
|
||||
import androidx.compose.foundation.gestures.detectVerticalDragGestures
|
||||
import androidx.compose.foundation.gestures.detectHorizontalDragGestures
|
||||
import androidx.compose.foundation.pager.HorizontalPager
|
||||
@@ -17,7 +12,6 @@ import androidx.compose.foundation.pager.rememberPagerState
|
||||
import androidx.compose.runtime.setValue
|
||||
import androidx.compose.runtime.rememberUpdatedState
|
||||
import de.jeanlucmakiola.calendula.ui.agenda.agendaDays
|
||||
import de.jeanlucmakiola.calendula.ui.common.FabClearance
|
||||
import de.jeanlucmakiola.calendula.ui.common.PublishChrome
|
||||
import de.jeanlucmakiola.calendula.ui.common.ScreenActions
|
||||
import de.jeanlucmakiola.calendula.ui.common.ScreenBody
|
||||
@@ -68,7 +62,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.layout.wrapContentHeight
|
||||
import androidx.compose.foundation.lazy.LazyColumn
|
||||
import androidx.compose.foundation.lazy.LazyListState
|
||||
import androidx.compose.foundation.lazy.itemsIndexed
|
||||
@@ -125,11 +118,11 @@ import de.jeanlucmakiola.calendula.ui.common.eventTitleOverflow
|
||||
import de.jeanlucmakiola.calendula.ui.common.MoveTarget
|
||||
import de.jeanlucmakiola.calendula.ui.common.MoveRequest
|
||||
import de.jeanlucmakiola.calendula.ui.common.LocalEventMove
|
||||
import de.jeanlucmakiola.calendula.ui.common.dropStates
|
||||
import de.jeanlucmakiola.calendula.ui.common.moveInFlight
|
||||
import de.jeanlucmakiola.calendula.ui.common.abandonedMoves
|
||||
import de.jeanlucmakiola.calendula.ui.common.OnUndoStarted
|
||||
import de.jeanlucmakiola.calendula.ui.common.ghostAlpha
|
||||
import de.jeanlucmakiola.calendula.ui.common.DragSnapHaptics
|
||||
import de.jeanlucmakiola.calendula.ui.common.rememberHeldSettle
|
||||
import de.jeanlucmakiola.calendula.ui.common.SETTLE_FADE_MILLIS
|
||||
import de.jeanlucmakiola.calendula.ui.common.SETTLE_GRACE_MILLIS
|
||||
import de.jeanlucmakiola.calendula.ui.common.EventMoveScope
|
||||
@@ -163,9 +156,10 @@ import androidx.lifecycle.compose.collectAsStateWithLifecycle
|
||||
import de.jeanlucmakiola.calendula.R
|
||||
import de.jeanlucmakiola.calendula.domain.EventInstance
|
||||
import de.jeanlucmakiola.calendula.domain.hasEnded
|
||||
import de.jeanlucmakiola.calendula.ui.agenda.agendaDayLabel
|
||||
import de.jeanlucmakiola.calendula.ui.agenda.AgendaDayHeader
|
||||
import de.jeanlucmakiola.calendula.ui.agenda.AgendaEmptyDayRow
|
||||
import de.jeanlucmakiola.calendula.ui.agenda.AgendaEventRow
|
||||
import de.jeanlucmakiola.calendula.ui.agenda.agendaDayLabel
|
||||
import de.jeanlucmakiola.calendula.ui.common.formatCalendarTitle
|
||||
import de.jeanlucmakiola.calendula.ui.common.AppBarSpacing
|
||||
import de.jeanlucmakiola.calendula.ui.common.CalendarFailure
|
||||
@@ -187,6 +181,7 @@ import de.jeanlucmakiola.floret.identity.itemEnter
|
||||
import de.jeanlucmakiola.floret.identity.rememberReduceMotion
|
||||
import de.jeanlucmakiola.floret.locale.currentLocale
|
||||
import de.jeanlucmakiola.calendula.ui.common.next
|
||||
import de.jeanlucmakiola.floret.time.isoWeekNumber
|
||||
import kotlinx.coroutines.delay
|
||||
import kotlinx.coroutines.flow.distinctUntilChanged
|
||||
import kotlinx.coroutines.flow.filterNotNull
|
||||
@@ -204,7 +199,6 @@ import java.time.format.TextStyle as JavaTextStyle
|
||||
import java.util.Locale
|
||||
import kotlinx.datetime.toJavaMonth
|
||||
import kotlinx.datetime.yearMonth
|
||||
import de.jeanlucmakiola.calendula.ui.common.rememberRowWeekNumber
|
||||
|
||||
private val LocalTodayPulse = staticCompositionLocalOf { 0 }
|
||||
|
||||
@@ -284,7 +278,6 @@ fun MonthScreen(
|
||||
val dimCompleted by viewModel.dimCompletedEvents.collectAsStateWithLifecycle()
|
||||
val showWeekNumbers by viewModel.showWeekNumbers.collectAsStateWithLifecycle()
|
||||
val showToday by viewModel.showToday.collectAsStateWithLifecycle()
|
||||
val showStartTimes by viewModel.showStartTimes.collectAsStateWithLifecycle()
|
||||
// The instant before which an event counts as completed, or null when dimming
|
||||
// is off. derivedStateOf keeps the per-minute "now" from recomposing the
|
||||
// screen while the setting is off (it stays null regardless of the tick).
|
||||
@@ -515,7 +508,7 @@ fun MonthScreen(
|
||||
val chipDrag = rememberMonthDragController()
|
||||
// Undo moves the event back, so the chip travels back too. The
|
||||
// signal comes from the write, not from the chip that offers it.
|
||||
OnUndoStarted { start -> chipDrag.beginUndo(start.token, start.dropToken) }
|
||||
OnUndoStarted { chipDrag.beginUndo() }
|
||||
Box(
|
||||
modifier = Modifier
|
||||
.padding(innerPadding)
|
||||
@@ -532,20 +525,17 @@ fun MonthScreen(
|
||||
) {
|
||||
if (scrolling) {
|
||||
ContinuousMonthContent(
|
||||
// Held on the skeleton until the start-time setting has
|
||||
// loaded, so chips don't redraw without their times.
|
||||
state = if (showStartTimes == null) ContinuousMonthUiState.Loading else continuousState,
|
||||
state = continuousState,
|
||||
listState = listState,
|
||||
dense = dense,
|
||||
showWeekNumbers = showWeekNumbers,
|
||||
showStartTimes = showStartTimes == true,
|
||||
onRetry = jumpToToday,
|
||||
onOpenDay = onOpenDay,
|
||||
onEventClick = onEventClick,
|
||||
)
|
||||
} else {
|
||||
SplitMonthContent(
|
||||
state = if (showStartTimes == null) MonthUiState.Loading else state,
|
||||
state = state,
|
||||
selected = selectedDate,
|
||||
initiallyExpanded = viewStyle == MonthViewStyle.Paged,
|
||||
expanded = splitExpanded,
|
||||
@@ -554,7 +544,6 @@ fun MonthScreen(
|
||||
weekStart = weekStart,
|
||||
monthState = viewModel::month,
|
||||
showWeekNumbers = showWeekNumbers,
|
||||
showStartTimes = showStartTimes == true,
|
||||
showToday = showToday,
|
||||
onPaneSwipeNext = { viewModel.stepSplitPane(1) },
|
||||
onPaneSwipePrev = { viewModel.stepSplitPane(-1) },
|
||||
@@ -576,7 +565,7 @@ fun MonthScreen(
|
||||
}
|
||||
}
|
||||
}
|
||||
MonthDragOverlay(chipDrag, showStartTimes = showStartTimes == true)
|
||||
MonthDragOverlay(chipDrag)
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -589,13 +578,13 @@ private const val MONTH_SETTLE_TIMEOUT_MILLIS = 450L
|
||||
|
||||
/** The chip in flight, drawn over the grid and following the finger. */
|
||||
@Composable
|
||||
private fun MonthDragOverlay(controller: MonthDragController, showStartTimes: Boolean) {
|
||||
private fun MonthDragOverlay(controller: MonthDragController) {
|
||||
var origin by remember { mutableStateOf(Offset.Zero) }
|
||||
val timeFit = rememberMonthChipTimeFit(showStartTimes)
|
||||
val dark = LocalFloretDarkTheme.current
|
||||
val density = LocalDensity.current
|
||||
val timeChipWidth = rememberMonthTimeChipWidth()
|
||||
val reduceMotion = rememberReduceMotion()
|
||||
val drops = dropStates()
|
||||
val moveInFlight = controller.settledToken in drops.pending
|
||||
val abandoned = controller.settledToken in drops.abandoned
|
||||
val moveInFlight = moveInFlight()
|
||||
// Here rather than beside the controller: this reads [drag], which changes
|
||||
// every frame, and this composable is the one that is meant to.
|
||||
DragSnapHaptics(controller.drag?.targetDate, controller.drops)
|
||||
@@ -608,12 +597,14 @@ private fun MonthDragOverlay(controller: MonthDragController, showStartTimes: Bo
|
||||
val glide = remember { Animatable(Offset.Zero, Offset.VectorConverter) }
|
||||
val glideSpec = MaterialTheme.motionScheme.fastSpatialSpec<Offset>()
|
||||
val seat = controller.settledInRoot
|
||||
val abandoned = abandonedMoves()
|
||||
LaunchedEffect(controller.settling, moveInFlight, seat, abandoned) {
|
||||
val landed = controller.settling
|
||||
if (landed == null || moveInFlight) return@LaunchedEffect
|
||||
if (seat == null) {
|
||||
// An abandoned drop has no seat coming.
|
||||
if (!abandoned) delay(MONTH_SETTLE_TIMEOUT_MILLIS)
|
||||
// Past the mark this drop was let go on, it was abandoned and no
|
||||
// seat is ever coming.
|
||||
if (abandoned == controller.settledAbandonedMark) delay(MONTH_SETTLE_TIMEOUT_MILLIS)
|
||||
} else {
|
||||
if (!gliding) glide.snapTo(landed.topLeftInRoot)
|
||||
gliding = true
|
||||
@@ -633,9 +624,6 @@ private fun MonthDragOverlay(controller: MonthDragController, showStartTimes: Bo
|
||||
.clearAndSetSemantics { }
|
||||
.onGloballyPositioned { origin = it.positionInRoot() },
|
||||
) {
|
||||
controller.held.forEach { parked ->
|
||||
key(parked.token) { HeldMonthChip(controller, parked, origin, timeFit) }
|
||||
}
|
||||
val drag = controller.drag ?: controller.settling ?: return@Box
|
||||
// Landed: the copy sinks back to the grid's own plane while the write runs.
|
||||
val lift by animateFloatAsState(
|
||||
@@ -647,93 +635,41 @@ private fun MonthDragOverlay(controller: MonthDragController, showStartTimes: Bo
|
||||
animationSpec = tween(SETTLE_FADE_MILLIS),
|
||||
label = "chip-handover",
|
||||
)
|
||||
MonthChipCopy(
|
||||
drag = drag,
|
||||
// Read at layout, so the glide doesn't recompose every frame.
|
||||
at = { if (gliding) glide.value else drag.topLeftInRoot },
|
||||
origin = origin,
|
||||
lift = lift,
|
||||
alpha = copyAlpha,
|
||||
timeFit = timeFit,
|
||||
MonthBar(
|
||||
event = drag.event,
|
||||
dark = dark,
|
||||
continuesLeft = false,
|
||||
continuesRight = false,
|
||||
// The time the source chip carried, drawn only if this one-column
|
||||
// cut-out of it has the room — which a slice of a multi-day bar has
|
||||
// not, however wide the bar was.
|
||||
time = drag.time,
|
||||
showTime = with(density) { drag.sizePx.width.toDp() } >= timeChipWidth,
|
||||
modifier = Modifier
|
||||
// Absolute: these are root coordinates, and the direction-aware
|
||||
// offset would mirror them across the screen in an RTL layout.
|
||||
.absoluteOffset {
|
||||
val at = if (gliding) glide.value else drag.topLeftInRoot
|
||||
IntOffset(
|
||||
(at.x - origin.x).roundToInt(),
|
||||
(at.y - origin.y).roundToInt(),
|
||||
)
|
||||
}
|
||||
.width(with(density) { drag.sizePx.width.toDp() })
|
||||
.height(with(density) { drag.sizePx.height.toDp() })
|
||||
.padding(horizontal = MONTH_CHIP_INSET, vertical = 1.dp)
|
||||
.graphicsLayer {
|
||||
scaleX = 1f + 0.04f * lift
|
||||
scaleY = 1f + 0.04f * lift
|
||||
shadowElevation = 8.dp.toPx() * lift
|
||||
alpha = copyAlpha
|
||||
shape = EventChipShape
|
||||
clip = false
|
||||
},
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
/** A drop parked by a newer pickup: held on its landing day until its own write settles. */
|
||||
@Composable
|
||||
private fun HeldMonthChip(
|
||||
controller: MonthDragController,
|
||||
parked: HeldChip,
|
||||
origin: Offset,
|
||||
timeFit: MonthChipTimeFit?,
|
||||
) {
|
||||
val reduceMotion = rememberReduceMotion()
|
||||
val glide = remember { Animatable(parked.copy.topLeftInRoot, Offset.VectorConverter) }
|
||||
val glideSpec = MaterialTheme.motionScheme.fastSpatialSpec<Offset>()
|
||||
val seat = parked.seat
|
||||
val landed = parked.token !in dropStates().pending
|
||||
// Carried onto its seat once the write is in, as the settling chip is.
|
||||
LaunchedEffect(seat, landed) {
|
||||
if (seat == null || !landed) return@LaunchedEffect
|
||||
if (reduceMotion) glide.snapTo(seat) else glide.animateTo(seat, glideSpec)
|
||||
}
|
||||
val alpha = rememberHeldSettle(
|
||||
token = parked.token,
|
||||
seated = seat != null,
|
||||
timeoutMillis = MONTH_SETTLE_TIMEOUT_MILLIS,
|
||||
onHandOver = { controller.handOverHeld(parked.token) },
|
||||
onRelease = { controller.releaseHeld(parked.token) },
|
||||
)
|
||||
MonthChipCopy(parked.copy, { glide.value }, origin, lift = 0f, alpha = alpha, timeFit = timeFit)
|
||||
}
|
||||
|
||||
/** [drag]'s chip floating over the grid with its top left at [at], in root coordinates. */
|
||||
@Composable
|
||||
private fun MonthChipCopy(
|
||||
drag: MonthChipDrag,
|
||||
at: () -> Offset,
|
||||
origin: Offset,
|
||||
lift: Float,
|
||||
alpha: Float,
|
||||
timeFit: MonthChipTimeFit?,
|
||||
) {
|
||||
val density = LocalDensity.current
|
||||
val dark = LocalFloretDarkTheme.current
|
||||
MonthBar(
|
||||
event = drag.event,
|
||||
dark = dark,
|
||||
continuesLeft = false,
|
||||
continuesRight = false,
|
||||
// The time the source chip carried, drawn only if this one-column
|
||||
// cut-out of it has the room — which a slice of a multi-day bar has
|
||||
// not, however wide the bar was.
|
||||
time = drag.time,
|
||||
timeFit = timeFit,
|
||||
chipWidth = with(density) { drag.sizePx.width.toDp() },
|
||||
modifier = Modifier
|
||||
// Absolute: these are root coordinates, and the direction-aware
|
||||
// offset would mirror them across the screen in an RTL layout.
|
||||
.absoluteOffset {
|
||||
val topLeft = at()
|
||||
IntOffset(
|
||||
(topLeft.x - origin.x).roundToInt(),
|
||||
(topLeft.y - origin.y).roundToInt(),
|
||||
)
|
||||
}
|
||||
.width(with(density) { drag.sizePx.width.toDp() })
|
||||
.height(with(density) { drag.sizePx.height.toDp() })
|
||||
.padding(horizontal = MONTH_CHIP_INSET, vertical = 1.dp)
|
||||
.graphicsLayer {
|
||||
scaleX = 1f + 0.04f * lift
|
||||
scaleY = 1f + 0.04f * lift
|
||||
shadowElevation = 8.dp.toPx() * lift
|
||||
this.alpha = alpha
|
||||
shape = EventChipShape
|
||||
clip = false
|
||||
},
|
||||
)
|
||||
}
|
||||
|
||||
/**
|
||||
* Content for both scrolling styles. No swipe detector and no [AnimatedContent]:
|
||||
* vertical scrolling owns the gesture, and the list never swaps wholesale — it
|
||||
@@ -745,7 +681,6 @@ private fun ContinuousMonthContent(
|
||||
listState: LazyListState,
|
||||
dense: Boolean,
|
||||
showWeekNumbers: Boolean,
|
||||
showStartTimes: Boolean,
|
||||
onRetry: () -> Unit,
|
||||
onOpenDay: (LocalDate) -> Unit,
|
||||
onEventClick: (EventInstance) -> Unit,
|
||||
@@ -762,7 +697,6 @@ private fun ContinuousMonthContent(
|
||||
state = state,
|
||||
listState = listState,
|
||||
showWeekNumbers = showWeekNumbers,
|
||||
showStartTimes = showStartTimes,
|
||||
onOpenDay = onOpenDay,
|
||||
onEventClick = onEventClick,
|
||||
)
|
||||
@@ -771,7 +705,6 @@ private fun ContinuousMonthContent(
|
||||
state = state,
|
||||
listState = listState,
|
||||
showWeekNumbers = showWeekNumbers,
|
||||
showStartTimes = showStartTimes,
|
||||
onOpenDay = onOpenDay,
|
||||
onEventClick = onEventClick,
|
||||
)
|
||||
@@ -944,7 +877,6 @@ private val DENSE_HEADER_GAP = 4.dp
|
||||
internal fun MonthGrid(
|
||||
state: MonthUiState.Success,
|
||||
showWeekNumbers: Boolean,
|
||||
showStartTimes: Boolean,
|
||||
onOpenDay: (LocalDate) -> Unit,
|
||||
onEventClick: (EventInstance) -> Unit,
|
||||
/** See [MonthWeekRow]'s `selected`: an anchor for the morph, never a mark. */
|
||||
@@ -969,13 +901,13 @@ internal fun MonthGrid(
|
||||
val month = state.month
|
||||
// Once per grid: the value depends on the typography, the density, the
|
||||
// locale and the 24-hour setting, none of which vary by row (#219).
|
||||
val timeFit = rememberMonthChipTimeFit(showStartTimes)
|
||||
val timeChipWidth = rememberMonthTimeChipWidth()
|
||||
state.weeks.forEach { week ->
|
||||
MonthWeekRow(
|
||||
week = week,
|
||||
today = state.today,
|
||||
zone = state.zone,
|
||||
timeFit = timeFit,
|
||||
timeChipWidth = timeChipWidth,
|
||||
rowHeight = rowHeight,
|
||||
inMonth = { it.month == month.month && it.year == month.year },
|
||||
showWeekNumbers = showWeekNumbers,
|
||||
@@ -1011,19 +943,18 @@ internal fun ContinuousMonthGrid(
|
||||
state: ContinuousMonthUiState.Success,
|
||||
listState: LazyListState,
|
||||
showWeekNumbers: Boolean,
|
||||
showStartTimes: Boolean,
|
||||
onOpenDay: (LocalDate) -> Unit,
|
||||
onEventClick: (EventInstance) -> Unit,
|
||||
modifier: Modifier = Modifier,
|
||||
) {
|
||||
val monthCount = remember { continuousMonthCount() }
|
||||
val todayMonth = remember(state.today) { state.today.yearMonth }
|
||||
val timeFit = rememberMonthChipTimeFit(showStartTimes)
|
||||
val timeChipWidth = rememberMonthTimeChipWidth()
|
||||
LazyColumn(
|
||||
state = listState,
|
||||
modifier = modifier.fillMaxSize(),
|
||||
// Bottom inset clears the FAB stack so the last row stays tappable.
|
||||
contentPadding = PaddingValues(bottom = FabClearance),
|
||||
contentPadding = PaddingValues(bottom = 96.dp),
|
||||
) {
|
||||
repeat(monthCount) { index ->
|
||||
val month = yearMonthForIndex(index)
|
||||
@@ -1041,7 +972,7 @@ internal fun ContinuousMonthGrid(
|
||||
weekStart = state.weekStart,
|
||||
today = state.today,
|
||||
zone = state.zone,
|
||||
timeFit = timeFit,
|
||||
timeChipWidth = timeChipWidth,
|
||||
showWeekNumbers = showWeekNumbers,
|
||||
onOpenDay = onOpenDay,
|
||||
onEventClick = onEventClick,
|
||||
@@ -1063,7 +994,7 @@ private fun ContinuousMonthBlock(
|
||||
weekStart: DayOfWeek,
|
||||
today: LocalDate,
|
||||
zone: TimeZone,
|
||||
timeFit: MonthChipTimeFit?,
|
||||
timeChipWidth: Dp,
|
||||
showWeekNumbers: Boolean,
|
||||
onOpenDay: (LocalDate) -> Unit,
|
||||
onEventClick: (EventInstance) -> Unit,
|
||||
@@ -1084,7 +1015,7 @@ private fun ContinuousMonthBlock(
|
||||
week = week,
|
||||
today = today,
|
||||
zone = zone,
|
||||
timeFit = timeFit,
|
||||
timeChipWidth = timeChipWidth,
|
||||
rowHeight = CONTINUOUS_ROW_HEIGHT,
|
||||
inMonth = { it.month == month.month && it.year == month.year },
|
||||
// The block owns its month alone: a day from either
|
||||
@@ -1150,13 +1081,12 @@ internal fun DenseMonthGrid(
|
||||
state: ContinuousMonthUiState.Success,
|
||||
listState: LazyListState,
|
||||
showWeekNumbers: Boolean,
|
||||
showStartTimes: Boolean,
|
||||
onOpenDay: (LocalDate) -> Unit,
|
||||
onEventClick: (EventInstance) -> Unit,
|
||||
modifier: Modifier = Modifier,
|
||||
) {
|
||||
val weekCount = remember(state.weekStart) { continuousWeekCount(state.weekStart) }
|
||||
val timeFit = rememberMonthChipTimeFit(showStartTimes)
|
||||
val timeChipWidth = rememberMonthTimeChipWidth()
|
||||
LazyColumn(
|
||||
state = listState,
|
||||
modifier = modifier
|
||||
@@ -1169,7 +1099,7 @@ internal fun DenseMonthGrid(
|
||||
.padding(top = DENSE_HEADER_GAP),
|
||||
verticalArrangement = Arrangement.spacedBy(2.dp),
|
||||
// Bottom inset clears the FAB stack so the last row stays tappable.
|
||||
contentPadding = PaddingValues(bottom = FabClearance),
|
||||
contentPadding = PaddingValues(bottom = 96.dp),
|
||||
) {
|
||||
items(count = weekCount, key = { it }) { index ->
|
||||
val week = state.weeksByIndex[index]
|
||||
@@ -1180,7 +1110,7 @@ internal fun DenseMonthGrid(
|
||||
week = week,
|
||||
today = state.today,
|
||||
zone = state.zone,
|
||||
timeFit = timeFit,
|
||||
timeChipWidth = timeChipWidth,
|
||||
rowHeight = CONTINUOUS_ROW_HEIGHT,
|
||||
// Every day in the stream belongs to a month equally — there
|
||||
// is no "other month" to recede here.
|
||||
@@ -1272,7 +1202,6 @@ private fun SplitMonthContent(
|
||||
weekStart: DayOfWeek,
|
||||
monthState: (YearMonth, DayOfWeek) -> StateFlow<MonthUiState>,
|
||||
showWeekNumbers: Boolean,
|
||||
showStartTimes: Boolean,
|
||||
showToday: Boolean,
|
||||
onPaneSwipeNext: () -> Unit,
|
||||
onPaneSwipePrev: () -> Unit,
|
||||
@@ -1283,12 +1212,9 @@ private fun SplitMonthContent(
|
||||
onEventClick: (EventInstance) -> Unit,
|
||||
onCreateEvent: (LocalDate) -> Unit,
|
||||
) {
|
||||
val fadeSpec = rememberCalendarFadeSpec()
|
||||
val reduceMotion = rememberReduceMotion()
|
||||
val haptics = LocalHapticFeedback.current
|
||||
// Registered first so the expand handler below wins while the grid is open.
|
||||
BackHandler(enabled = selected != null && !expanded) {
|
||||
onClearSelection()
|
||||
}
|
||||
BackHandler(enabled = expanded != initiallyExpanded) {
|
||||
onExpandedChange(initiallyExpanded)
|
||||
}
|
||||
@@ -1357,9 +1283,8 @@ private fun SplitMonthContent(
|
||||
modifier = Modifier.fillMaxSize(),
|
||||
// Both faces fill the same page — the grid grows into exactly the
|
||||
// room the pane gives up — so there is no size change to contain.
|
||||
// Fading the faces made the shared cell backgrounds briefly
|
||||
// disappear beneath their incoming counterparts.
|
||||
transitionSpec = { EnterTransition.None togetherWith ExitTransition.None },
|
||||
// The travel between them is the shared elements' job.
|
||||
transitionSpec = { fadeIn(fadeSpec) togetherWith fadeOut(fadeSpec) },
|
||||
label = "split-expand",
|
||||
) { isExpanded ->
|
||||
// The view switch's morph stays off a face until it has fully
|
||||
@@ -1390,7 +1315,6 @@ private fun SplitMonthContent(
|
||||
state = page,
|
||||
selected = pageSelected,
|
||||
showWeekNumbers = showWeekNumbers,
|
||||
showStartTimes = showStartTimes,
|
||||
expandDrag = expandDrag,
|
||||
onPickDay = onPickDay,
|
||||
// A tapped chip is asking for that event, not for its
|
||||
@@ -1416,9 +1340,6 @@ private fun SplitMonthContent(
|
||||
state = page,
|
||||
paneReady = paneReady,
|
||||
selected = pageSelected,
|
||||
selectionIndicatorVisible = reduceMotion ||
|
||||
(transition.currentState == EnterExitState.Visible &&
|
||||
transition.targetState == EnterExitState.Visible),
|
||||
showWeekNumbers = showWeekNumbers,
|
||||
showToday = showToday,
|
||||
expandDrag = expandDrag,
|
||||
@@ -1462,7 +1383,6 @@ private fun SplitMonthCollapsed(
|
||||
state: MonthUiState.Success,
|
||||
paneReady: Boolean,
|
||||
selected: LocalDate?,
|
||||
selectionIndicatorVisible: Boolean,
|
||||
showWeekNumbers: Boolean,
|
||||
showToday: Boolean,
|
||||
expandDrag: Modifier,
|
||||
@@ -1484,7 +1404,6 @@ private fun SplitMonthCollapsed(
|
||||
SplitMonthGrid(
|
||||
state = state,
|
||||
selected = selected,
|
||||
selectionIndicatorVisible = selectionIndicatorVisible,
|
||||
showWeekNumbers = showWeekNumbers,
|
||||
onSelectDay = onSelectDay,
|
||||
modifier = Modifier.height(splitGridHeight(state.weeks.size)),
|
||||
@@ -1512,13 +1431,24 @@ private fun SplitMonthCollapsed(
|
||||
.then(paneModifier)
|
||||
.then(rememberSplitPaneSwipe(onPaneSwipeNext, onPaneSwipePrev)),
|
||||
) {
|
||||
InputChip(
|
||||
selected = true,
|
||||
onClick = onClearSelection,
|
||||
label = { Text(agendaDayLabel(selected, state.today)) },
|
||||
trailingIcon = {
|
||||
Icon(
|
||||
Icons.Default.Close,
|
||||
contentDescription = stringResource(R.string.month_split_clear_filter),
|
||||
)
|
||||
},
|
||||
modifier = Modifier.padding(start = 16.dp),
|
||||
)
|
||||
SplitDayPane(
|
||||
date = selected,
|
||||
today = state.today,
|
||||
events = state.instancesByDay[selected],
|
||||
zone = state.zone,
|
||||
onOpenDay = onOpenDay,
|
||||
onClearSelection = onClearSelection,
|
||||
onEventClick = onEventClick,
|
||||
onCreateEvent = onCreateEvent,
|
||||
modifier = Modifier.weight(1f).fillMaxWidth(),
|
||||
@@ -1565,7 +1495,6 @@ private fun SplitMonthExpanded(
|
||||
/** Marked nowhere here; it only anchors the outline's morph. */
|
||||
selected: LocalDate?,
|
||||
showWeekNumbers: Boolean,
|
||||
showStartTimes: Boolean,
|
||||
expandDrag: Modifier,
|
||||
onPickDay: (LocalDate) -> Unit,
|
||||
onEventClick: (EventInstance) -> Unit,
|
||||
@@ -1578,7 +1507,6 @@ private fun SplitMonthExpanded(
|
||||
MonthGrid(
|
||||
state = state,
|
||||
showWeekNumbers = showWeekNumbers,
|
||||
showStartTimes = showStartTimes,
|
||||
onOpenDay = onPickDay,
|
||||
onEventClick = onEventClick,
|
||||
selected = selected,
|
||||
@@ -1692,7 +1620,6 @@ private val SPLIT_PANE_EASING = CubicBezierEasing(0.05f, 0.7f, 0.1f, 1f)
|
||||
internal fun SplitMonthGrid(
|
||||
state: MonthUiState.Success,
|
||||
selected: LocalDate?,
|
||||
selectionIndicatorVisible: Boolean = true,
|
||||
showWeekNumbers: Boolean,
|
||||
onSelectDay: (LocalDate) -> Unit,
|
||||
modifier: Modifier = Modifier,
|
||||
@@ -1738,7 +1665,6 @@ internal fun SplitMonthGrid(
|
||||
// removes that without timing anything against the
|
||||
// page transition.
|
||||
isSelected = day == selected && inMonth,
|
||||
selectionIndicatorVisible = selectionIndicatorVisible,
|
||||
inMonth = inMonth,
|
||||
relativeToToday = todayCol?.let { col - it },
|
||||
rippleProgress = { ripple.value },
|
||||
@@ -1767,7 +1693,6 @@ private fun SplitDayCell(
|
||||
hidden: List<EventInstance>,
|
||||
isToday: Boolean,
|
||||
isSelected: Boolean,
|
||||
selectionIndicatorVisible: Boolean,
|
||||
inMonth: Boolean,
|
||||
relativeToToday: Int?,
|
||||
rippleProgress: () -> Float,
|
||||
@@ -1797,7 +1722,7 @@ private fun SplitDayCell(
|
||||
// pace it lingered after the thing it marks had already moved.
|
||||
val outlineSpec = MaterialTheme.motionScheme.fastEffectsSpec<Float>()
|
||||
val selection = animateFloatAsState(
|
||||
targetValue = if (isSelected && selectionIndicatorVisible) 1f else 0f,
|
||||
targetValue = if (isSelected) 1f else 0f,
|
||||
animationSpec = if (reduceMotion) snap() else outlineSpec,
|
||||
label = "split-day-selection",
|
||||
)
|
||||
@@ -1809,19 +1734,12 @@ private fun SplitDayCell(
|
||||
// built — and so the pill can be tagged for the morph on its own. Tagged as
|
||||
// one piece with its contents inside, the dots would be nested shared
|
||||
// elements within a shared element and travel twice.
|
||||
// The cell keeps the click and selection semantics, so TalkBack reads the
|
||||
// day number with them; the topmost layer only draws the ripple.
|
||||
val interaction = remember { MutableInteractionSource() }
|
||||
Box(
|
||||
modifier = modifier
|
||||
.padding(horizontal = CELL_GAP, vertical = 1.dp)
|
||||
.todayRipple(relativeToToday, rippleProgress)
|
||||
.selectable(
|
||||
selected = isSelected,
|
||||
interactionSource = interaction,
|
||||
indication = null,
|
||||
onClick = onClick,
|
||||
),
|
||||
.clip(CELL_SHAPE)
|
||||
.selectable(selected = isSelected, onClick = onClick),
|
||||
contentAlignment = Alignment.TopCenter,
|
||||
) {
|
||||
Box(
|
||||
@@ -1883,13 +1801,6 @@ private fun SplitDayCell(
|
||||
Spacer(Modifier.height(2.dp))
|
||||
SplitDots(date = date, events = events, hidden = hidden, dark = dark)
|
||||
}
|
||||
Box(
|
||||
Modifier
|
||||
.fillMaxSize()
|
||||
.morphElement(MonthMorphKey.CellRipple(date))
|
||||
.clip(CELL_SHAPE)
|
||||
.indication(interaction, LocalIndication.current),
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1911,10 +1822,7 @@ private fun SplitDots(
|
||||
if (events.isEmpty()) return
|
||||
val soften = LocalSoftenColors.current
|
||||
val dimCutoff = LocalDimCutoff.current
|
||||
// Held to the dots' height so a "+N" doesn't grow the row and push the dots
|
||||
// down; the label overflows it evenly instead (#142).
|
||||
Row(
|
||||
modifier = Modifier.height(SPLIT_DOT_SIZE),
|
||||
horizontalArrangement = Arrangement.spacedBy(2.dp),
|
||||
verticalAlignment = Alignment.CenterVertically,
|
||||
) {
|
||||
@@ -1949,7 +1857,6 @@ private fun SplitDots(
|
||||
style = MaterialTheme.typography.labelSmall,
|
||||
color = MaterialTheme.colorScheme.onSurfaceVariant,
|
||||
modifier = Modifier
|
||||
.wrapContentHeight(unbounded = true)
|
||||
.morphBounds(MonthMorphKey.Overflow(date))
|
||||
.alpha(if (allEnded(hidden, date, dimCutoff)) EventDimAlpha else 1f),
|
||||
)
|
||||
@@ -1970,10 +1877,10 @@ private fun SplitMonthAgendaPane(
|
||||
}
|
||||
val dimCutoff = LocalDimCutoff.current
|
||||
val listState = key(state.month) { rememberLazyListState() }
|
||||
LazyColumn(state = listState, contentPadding = PaddingValues(bottom = FabClearance)) {
|
||||
LazyColumn(state = listState, contentPadding = PaddingValues(bottom = 96.dp)) {
|
||||
// A fixed first item, so a day added above the first listed one shows
|
||||
// up rather than landing above a list that holds its scroll position.
|
||||
item(key = "top") { Spacer(Modifier.height(4.dp)) }
|
||||
item(key = "top") { Spacer(Modifier.height(8.dp)) }
|
||||
if (days.isEmpty()) {
|
||||
val start = agendaStartForMonth(state.month, state.today)
|
||||
item(key = "empty") {
|
||||
@@ -1994,7 +1901,6 @@ private fun SplitMonthAgendaPane(
|
||||
dimmed = { event, day -> dimCutoff != null && event.isPastOn(day, dimCutoff) },
|
||||
onOpenDay = onOpenDay,
|
||||
onEventClick = onEventClick,
|
||||
compact = true,
|
||||
)
|
||||
}
|
||||
}
|
||||
@@ -2002,8 +1908,7 @@ private fun SplitMonthAgendaPane(
|
||||
/**
|
||||
* The selected day's events, in the agenda's own row vocabulary so the two
|
||||
* surfaces read as one app. The date header opens the full Day view, matching
|
||||
* the Week and Agenda headers (#37). It is shown as the filter chip itself,
|
||||
* whose ✕ clears the day filter back to the whole month (#142).
|
||||
* the Week and Agenda headers (#37).
|
||||
*/
|
||||
@Composable
|
||||
internal fun SplitDayPane(
|
||||
@@ -2013,7 +1918,6 @@ internal fun SplitDayPane(
|
||||
events: List<EventInstance>?,
|
||||
zone: TimeZone,
|
||||
onOpenDay: (LocalDate) -> Unit,
|
||||
onClearSelection: () -> Unit,
|
||||
onEventClick: (EventInstance) -> Unit,
|
||||
onCreateEvent: (LocalDate) -> Unit,
|
||||
modifier: Modifier = Modifier,
|
||||
@@ -2025,23 +1929,7 @@ internal fun SplitDayPane(
|
||||
val enter = itemEnter()
|
||||
val fadeSpec = rememberCalendarFadeSpec()
|
||||
Column(modifier = modifier) {
|
||||
InputChip(
|
||||
selected = true,
|
||||
onClick = { onOpenDay(date) },
|
||||
label = {
|
||||
Text(agendaDayLabel(date, today), style = MaterialTheme.typography.titleSmall)
|
||||
},
|
||||
trailingIcon = {
|
||||
Icon(
|
||||
Icons.Default.Close,
|
||||
contentDescription = stringResource(R.string.month_split_clear_filter),
|
||||
modifier = Modifier
|
||||
.clip(CircleShape)
|
||||
.clickable(onClick = onClearSelection),
|
||||
)
|
||||
},
|
||||
modifier = Modifier.padding(start = 16.dp),
|
||||
)
|
||||
AgendaDayHeader(date = date, today = today, onOpenDay = onOpenDay)
|
||||
AnimatedContent(
|
||||
targetState = date to events,
|
||||
modifier = Modifier.weight(1f).fillMaxWidth(),
|
||||
@@ -2064,7 +1952,7 @@ internal fun SplitDayPane(
|
||||
else -> LazyColumn(
|
||||
// Bottom inset clears the FAB stack so the last row stays
|
||||
// tappable.
|
||||
contentPadding = PaddingValues(bottom = FabClearance),
|
||||
contentPadding = PaddingValues(bottom = 96.dp),
|
||||
) {
|
||||
itemsIndexed(
|
||||
items = dayEvents,
|
||||
@@ -2220,8 +2108,8 @@ private fun MonthWeekRow(
|
||||
today: LocalDate,
|
||||
/** The zone the grid was laid out in — never re-read here (see [MonthUiState.Success.zone]). */
|
||||
zone: TimeZone,
|
||||
/** Prices chips' start times, once per grid; null when they are switched off (#219, #476). */
|
||||
timeFit: MonthChipTimeFit?,
|
||||
/** The narrowest chip that may carry a start time, measured once per grid (#219). */
|
||||
timeChipWidth: Dp,
|
||||
/** The height this row was given, which decides its lanes — see [laneCapFor]. */
|
||||
rowHeight: Dp,
|
||||
inMonth: (LocalDate) -> Boolean,
|
||||
@@ -2310,7 +2198,7 @@ private fun MonthWeekRow(
|
||||
// Once the grid holds the settled chip, tell the controller where this row
|
||||
// has seated it, so the copy in flight can glide onto it. Keyed on the week,
|
||||
// which is what changes when the re-read lands.
|
||||
LaunchedEffect(week, dragController?.settling, dragController?.held) {
|
||||
LaunchedEffect(week, dragController?.settling) {
|
||||
dragController?.noteSettled(rowToken)
|
||||
}
|
||||
|
||||
@@ -2347,8 +2235,8 @@ private fun MonthWeekRow(
|
||||
),
|
||||
),
|
||||
) {
|
||||
// What a chip has to spend, against what [timeFit] says its start
|
||||
// time costs it (#219).
|
||||
// What a chip has to spend, against the [timeChipWidth] a start time
|
||||
// costs it (#219).
|
||||
val colW = maxWidth / 7
|
||||
// Held here rather than read at the offset: the dots are placed
|
||||
// inside a plain lambda, which is no longer in this scope. The box
|
||||
@@ -2438,8 +2326,7 @@ private fun MonthWeekRow(
|
||||
continuesRight = span.continuesRight,
|
||||
days = week.days.subList(span.startCol, span.endCol + 1),
|
||||
time = chipTimes[span.event.instanceId],
|
||||
timeFit = timeFit,
|
||||
chipWidth = colW * cols,
|
||||
showTime = colW * cols >= timeChipWidth,
|
||||
modifier = Modifier
|
||||
.offset(
|
||||
x = colW * span.startCol,
|
||||
@@ -2516,8 +2403,7 @@ private fun MonthWeekRow(
|
||||
continuesRight = false,
|
||||
days = listOf(d),
|
||||
time = chipTimes[ev.instanceId],
|
||||
timeFit = timeFit,
|
||||
chipWidth = colW,
|
||||
showTime = colW >= timeChipWidth,
|
||||
modifier = Modifier
|
||||
.offset(
|
||||
x = colW * col,
|
||||
@@ -2615,7 +2501,6 @@ private fun MonthWeekRow(
|
||||
}
|
||||
}
|
||||
.padding(horizontal = CELL_GAP, vertical = 1.dp)
|
||||
.morphElement(MonthMorphKey.CellRipple(d))
|
||||
.clip(CELL_SHAPE)
|
||||
.clickable {
|
||||
// Cleared on read: a click with no fresh down
|
||||
@@ -2743,8 +2628,6 @@ private fun monthChipDragModifier(
|
||||
beginMillis = drop.event.start.toEpochMilliseconds(),
|
||||
endMillis = drop.event.end.toEpochMilliseconds(),
|
||||
target = MoveTarget.ByDays(delta),
|
||||
isAllDay = drop.event.isAllDay,
|
||||
token = drop.token,
|
||||
),
|
||||
)
|
||||
}
|
||||
@@ -2755,20 +2638,19 @@ private fun monthChipDragModifier(
|
||||
/**
|
||||
* Left-gutter calendar-week cell (#25): a full-height tonal pill mirroring the
|
||||
* day cells' geometry, set apart by the secondaryContainer tint (matching the
|
||||
* Week view's badge), with the week number centred like a day number. It is
|
||||
* numbered by the device region from the row's mid-week day, as in the Week
|
||||
* view, so it is right for any first weekday (#493).
|
||||
* Week view's badge), with the ISO week number centred like a day number. The
|
||||
* week is computed on the row's first day — the same basis as the Week view — so
|
||||
* the two agree.
|
||||
*/
|
||||
@Composable
|
||||
private fun WeekNumberGutter(weekStart: LocalDate, modifier: Modifier = Modifier) {
|
||||
val weekNumber = rememberRowWeekNumber(weekStart)
|
||||
val weekNumber = remember(weekStart) { weekStart.toJavaLocalDate().isoWeekNumber() }
|
||||
val label = stringResource(R.string.week_number_label)
|
||||
val openLabel = stringResource(R.string.month_open_week, weekNumber)
|
||||
val onOpenWeek = LocalOpenWeek.current
|
||||
Box(
|
||||
modifier = modifier
|
||||
.padding(horizontal = CELL_GAP, vertical = 1.dp)
|
||||
.morphElement(MonthMorphKey.WeekNumber(weekStart))
|
||||
.clip(CELL_SHAPE)
|
||||
.background(MaterialTheme.colorScheme.secondaryContainer)
|
||||
.then(if (onOpenWeek != null) Modifier.clickable(onClickLabel = openLabel) {
|
||||
@@ -2847,7 +2729,7 @@ private fun shortMonthName(date: LocalDate): String {
|
||||
|
||||
/**
|
||||
* A filled event pill/bar — softened (or raw) fill, title clipped to one line,
|
||||
* with the start time before it where the chip is wide enough ([timeFit], #219, #476).
|
||||
* with the start time before it where the chip is wide enough ([showTime], #219).
|
||||
*/
|
||||
@Composable
|
||||
private fun MonthBar(
|
||||
@@ -2864,13 +2746,10 @@ private fun MonthBar(
|
||||
days: List<LocalDate>? = null,
|
||||
/** The chip's start time, or null where it has none — see `monthChipTime` (#219). */
|
||||
time: String? = null,
|
||||
/** Decides whether [time] is drawn at [chipWidth]; null draws none. A screen reader gets it either way. */
|
||||
timeFit: MonthChipTimeFit? = null,
|
||||
/** The chip's full width, chrome included. */
|
||||
chipWidth: Dp = 0.dp,
|
||||
/** Whether this chip has the width to draw [time]; a screen reader gets it either way. */
|
||||
showTime: Boolean = false,
|
||||
) {
|
||||
val title = event.title.ifBlank { stringResource(R.string.event_untitled) }
|
||||
val showTime = time != null && timeFit != null && timeFit.showsTime(chipWidth, title)
|
||||
val dimCutoff = LocalDimCutoff.current
|
||||
// A bar is one piece, so it dims once the last day it covers has passed.
|
||||
val dimmed = dimCutoff != null &&
|
||||
@@ -2890,17 +2769,8 @@ private fun MonthBar(
|
||||
val moveAction = eventMoveAction(event)
|
||||
// The source stays put as a ghost while its floating copy travels.
|
||||
val monthDrag = LocalMonthDrag.current
|
||||
// Derived, so a chip recomposes only when its own answer changes rather than
|
||||
// on every lift, park and release anywhere in the grid.
|
||||
val lifted by remember(monthDrag, event, days) {
|
||||
derivedStateOf {
|
||||
monthDrag != null && (
|
||||
monthDrag.liftedInstanceId == event.instanceId ||
|
||||
monthDrag.isSettledChip(event, days) ||
|
||||
monthDrag.isHeldChip(event, days)
|
||||
)
|
||||
}
|
||||
}
|
||||
val lifted = monthDrag?.liftedInstanceId == event.instanceId ||
|
||||
monthDrag?.isSettledChip(event, days) == true
|
||||
val ghost = ghostAlpha(lifted)
|
||||
val shape = monthBarShape(continuesLeft, continuesRight)
|
||||
Box(
|
||||
|
||||
@@ -31,7 +31,6 @@ import kotlinx.datetime.yearMonth
|
||||
internal fun MonthStylePreview(
|
||||
style: MonthViewStyle,
|
||||
weekStart: DayOfWeek,
|
||||
showStartTimes: Boolean,
|
||||
height: Dp,
|
||||
modifier: Modifier = Modifier,
|
||||
) {
|
||||
@@ -45,7 +44,6 @@ internal fun MonthStylePreview(
|
||||
MonthViewStyle.Paged -> MonthGrid(
|
||||
state = sample.month,
|
||||
showWeekNumbers = false,
|
||||
showStartTimes = showStartTimes,
|
||||
onOpenDay = {},
|
||||
onEventClick = {},
|
||||
)
|
||||
@@ -57,7 +55,6 @@ internal fun MonthStylePreview(
|
||||
),
|
||||
),
|
||||
showWeekNumbers = false,
|
||||
showStartTimes = showStartTimes,
|
||||
onOpenDay = {},
|
||||
onEventClick = {},
|
||||
)
|
||||
@@ -70,7 +67,6 @@ internal fun MonthStylePreview(
|
||||
initialFirstVisibleItemIndex = weekIndexOf(today, weekStart) - 1,
|
||||
),
|
||||
showWeekNumbers = false,
|
||||
showStartTimes = showStartTimes,
|
||||
onOpenDay = {},
|
||||
onEventClick = {},
|
||||
)
|
||||
@@ -87,7 +83,6 @@ internal fun MonthStylePreview(
|
||||
events = sample.month.instancesByDay[today].orEmpty(),
|
||||
zone = zone,
|
||||
onOpenDay = {},
|
||||
onClearSelection = {},
|
||||
onEventClick = {},
|
||||
onCreateEvent = {},
|
||||
modifier = Modifier.fillMaxWidth().height(SPLIT_PANE_HEIGHT),
|
||||
|
||||
@@ -13,7 +13,6 @@ 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.coversWholeDays
|
||||
import de.jeanlucmakiola.calendula.domain.FailureReason
|
||||
import de.jeanlucmakiola.calendula.domain.calendarListFailure
|
||||
import de.jeanlucmakiola.calendula.ui.agenda.AgendaDay
|
||||
@@ -21,7 +20,7 @@ import de.jeanlucmakiola.calendula.ui.agenda.anchorTodayIfMissing
|
||||
import de.jeanlucmakiola.calendula.ui.common.CalendarSpan
|
||||
import de.jeanlucmakiola.calendula.ui.common.PageStateCache
|
||||
import de.jeanlucmakiola.calendula.domain.isCrossedOut
|
||||
import de.jeanlucmakiola.calendula.domain.sortedForDisplay
|
||||
import de.jeanlucmakiola.calendula.domain.eventDisplayComparator
|
||||
import de.jeanlucmakiola.calendula.ui.week.coversDay
|
||||
import de.jeanlucmakiola.calendula.ui.week.layoutAllDay
|
||||
import de.jeanlucmakiola.calendula.ui.week.spansMultipleDays
|
||||
@@ -92,16 +91,6 @@ class MonthViewModel @Inject constructor(
|
||||
initialValue = true,
|
||||
)
|
||||
|
||||
/**
|
||||
* Whether chips may show their start time before the title (#476; display
|
||||
* only). Null until the setting has loaded, so the grid can wait for it.
|
||||
*/
|
||||
val showStartTimes: StateFlow<Boolean?> = settingsPrefs.monthShowStartTimes
|
||||
.stateWhileSubscribed(
|
||||
scope = viewModelScope,
|
||||
initialValue = null,
|
||||
)
|
||||
|
||||
/** How the grid is laid out and navigated (#38, #53). */
|
||||
val viewStyle: StateFlow<MonthViewStyle> = settingsPrefs.monthViewStyle
|
||||
.stateWhileSubscribed(
|
||||
@@ -502,7 +491,7 @@ internal fun layoutCalendarWeek(
|
||||
// crossing midnight into the next week row covers a single day in each, and
|
||||
// counting per row drew it as two unrelated pills (#253).
|
||||
val (bars, singles) = weekEvents.partition { ev ->
|
||||
ev.coversWholeDays(zone) || ev.spansMultipleDays(zone)
|
||||
ev.isAllDay || ev.spansMultipleDays(zone)
|
||||
}
|
||||
val spans = layoutAllDay(bars, days, zone).map { s ->
|
||||
MonthSpan(
|
||||
@@ -542,7 +531,7 @@ internal fun instancesByDay(
|
||||
days.associateWith { day ->
|
||||
instances
|
||||
.filter { it.coversDay(day, zone) }
|
||||
.sortedForDisplay(zone)
|
||||
.sortedWith(eventDisplayComparator(zone))
|
||||
}
|
||||
|
||||
/**
|
||||
|
||||
@@ -220,7 +220,6 @@ class OnboardingViewModel @Inject constructor(
|
||||
prefs.defaultView,
|
||||
prefs.monthViewStyle,
|
||||
prefs.weekStart,
|
||||
prefs.monthShowStartTimes,
|
||||
::ViewChoice,
|
||||
).stateWhileSubscribed(
|
||||
scope = viewModelScope,
|
||||
@@ -465,7 +464,6 @@ data class ViewChoice(
|
||||
val defaultView: CalendarView,
|
||||
val monthViewStyle: MonthViewStyle,
|
||||
val weekStart: WeekStartPref,
|
||||
val monthShowStartTimes: Boolean,
|
||||
)
|
||||
|
||||
/**
|
||||
|
||||
@@ -63,7 +63,6 @@ internal fun ViewStep(
|
||||
CalendarView.Month -> MonthStylePreview(
|
||||
style = choice.monthViewStyle,
|
||||
weekStart = weekStart,
|
||||
showStartTimes = choice.monthShowStartTimes,
|
||||
height = PREVIEW_HEIGHT,
|
||||
)
|
||||
CalendarView.Week -> WeekViewPreview(weekStart = weekStart, height = PREVIEW_HEIGHT)
|
||||
@@ -119,12 +118,7 @@ internal fun MonthStyleStep(
|
||||
navigationIcon = navigationIcon,
|
||||
) {
|
||||
StepPreview(selected = choice.monthViewStyle) { style ->
|
||||
MonthStylePreview(
|
||||
style = style,
|
||||
weekStart = weekStart,
|
||||
showStartTimes = choice.monthShowStartTimes,
|
||||
height = PREVIEW_HEIGHT,
|
||||
)
|
||||
MonthStylePreview(style = style, weekStart = weekStart, height = PREVIEW_HEIGHT)
|
||||
}
|
||||
GroupedHint(stringResource(choice.monthViewStyle.descriptionRes), verticalPadding = 8.dp)
|
||||
options.forEachIndexed { index, style ->
|
||||
|
||||
@@ -94,7 +94,6 @@ import de.jeanlucmakiola.calendula.ui.common.EventDimAlpha
|
||||
import de.jeanlucmakiola.calendula.ui.common.LocalSoftenColors
|
||||
import de.jeanlucmakiola.calendula.ui.common.RecurringScopeDialog
|
||||
import de.jeanlucmakiola.calendula.ui.common.eventAccent
|
||||
import de.jeanlucmakiola.calendula.domain.coversWholeDays
|
||||
import de.jeanlucmakiola.calendula.domain.spanFirstDay
|
||||
import de.jeanlucmakiola.calendula.ui.common.LocalUse24HourFormat
|
||||
import de.jeanlucmakiola.calendula.ui.common.timeOfDayFormatter
|
||||
@@ -610,7 +609,7 @@ private fun searchSummary(hit: SearchHit, highlight: SpanStyle): AnnotatedString
|
||||
.format(event.spanFirstDay(TimeZone.currentSystemDefault()).toJavaLocalDate())
|
||||
}
|
||||
val use24Hour = LocalUse24HourFormat.current
|
||||
val timeText = if (event.coversWholeDays(TimeZone.currentSystemDefault())) {
|
||||
val timeText = if (event.isAllDay) {
|
||||
stringResource(R.string.event_detail_all_day)
|
||||
} else {
|
||||
remember(locale, use24Hour) { timeOfDayFormatter(use24Hour, locale) }.format(start)
|
||||
|
||||
@@ -33,7 +33,6 @@ import kotlinx.datetime.DayOfWeek
|
||||
internal fun MonthViewStylePicker(
|
||||
selected: MonthViewStyle,
|
||||
weekStart: DayOfWeek,
|
||||
showStartTimes: Boolean,
|
||||
onSelect: (MonthViewStyle) -> Unit,
|
||||
onDismiss: () -> Unit,
|
||||
) {
|
||||
@@ -51,7 +50,6 @@ internal fun MonthViewStylePicker(
|
||||
MonthStylePreview(
|
||||
style = shown,
|
||||
weekStart = weekStart,
|
||||
showStartTimes = showStartTimes,
|
||||
height = PREVIEW_HEIGHT,
|
||||
)
|
||||
}
|
||||
|
||||
+42
-352
@@ -9,28 +9,19 @@ import android.provider.Settings
|
||||
import androidx.activity.compose.rememberLauncherForActivityResult
|
||||
import androidx.activity.result.contract.ActivityResultContracts
|
||||
import androidx.compose.animation.AnimatedVisibility
|
||||
import androidx.compose.foundation.layout.Arrangement
|
||||
import androidx.compose.foundation.layout.Column
|
||||
import androidx.compose.foundation.layout.Row
|
||||
import androidx.compose.foundation.layout.Spacer
|
||||
import androidx.compose.foundation.layout.fillMaxWidth
|
||||
import androidx.compose.foundation.layout.height
|
||||
import androidx.compose.material.icons.Icons
|
||||
import androidx.compose.material.icons.automirrored.filled.KeyboardArrowRight
|
||||
import androidx.compose.material.icons.automirrored.filled.OpenInNew
|
||||
import androidx.compose.material.icons.outlined.Info
|
||||
import androidx.compose.material3.Icon
|
||||
import androidx.compose.material3.MaterialTheme
|
||||
import androidx.compose.material3.Text
|
||||
import androidx.compose.material3.TextButton
|
||||
import androidx.compose.runtime.Composable
|
||||
import androidx.compose.runtime.DisposableEffect
|
||||
import androidx.compose.runtime.getValue
|
||||
import androidx.compose.runtime.mutableStateOf
|
||||
import androidx.compose.runtime.remember
|
||||
import androidx.compose.runtime.rememberCoroutineScope
|
||||
import androidx.compose.runtime.setValue
|
||||
import androidx.compose.ui.Alignment
|
||||
import androidx.compose.ui.Modifier
|
||||
import androidx.compose.ui.platform.LocalContext
|
||||
import androidx.compose.ui.res.stringResource
|
||||
@@ -38,18 +29,8 @@ import androidx.compose.ui.unit.dp
|
||||
import androidx.core.net.toUri
|
||||
import androidx.lifecycle.Lifecycle
|
||||
import androidx.lifecycle.LifecycleEventObserver
|
||||
import androidx.lifecycle.compose.LifecycleResumeEffect
|
||||
import androidx.lifecycle.compose.LocalLifecycleOwner
|
||||
import androidx.lifecycle.compose.collectAsStateWithLifecycle
|
||||
import de.jeanlucmakiola.calendula.R
|
||||
import de.jeanlucmakiola.calendula.data.prefs.FixedTimeOverride
|
||||
import de.jeanlucmakiola.calendula.data.prefs.fixedTimeOverrideFor
|
||||
import de.jeanlucmakiola.calendula.domain.CalendarSource
|
||||
import de.jeanlucmakiola.calendula.domain.reminders.DailyDigestSettings
|
||||
import de.jeanlucmakiola.calendula.domain.reminders.DigestDay
|
||||
import de.jeanlucmakiola.calendula.domain.reminders.FixedTimeReminder
|
||||
import de.jeanlucmakiola.calendula.ui.common.FixedTimeReminderPicker
|
||||
import de.jeanlucmakiola.calendula.ui.common.fixedTimeReminderLabel
|
||||
import de.jeanlucmakiola.calendula.ui.common.CalendarColorChip
|
||||
import de.jeanlucmakiola.calendula.ui.common.DurationPicker
|
||||
import de.jeanlucmakiola.calendula.ui.common.REMINDER_PRESETS
|
||||
@@ -58,13 +39,10 @@ import de.jeanlucmakiola.calendula.ui.common.TimePickerAlert
|
||||
import de.jeanlucmakiola.calendula.ui.common.durationLabel
|
||||
import de.jeanlucmakiola.calendula.ui.common.orUnnamed
|
||||
import de.jeanlucmakiola.floret.android.hasPermission
|
||||
import de.jeanlucmakiola.floret.android.openNotificationSettings
|
||||
import de.jeanlucmakiola.floret.components.CollapsingScaffold
|
||||
import de.jeanlucmakiola.floret.components.ExpandIcon
|
||||
import de.jeanlucmakiola.floret.components.GroupedRow
|
||||
import de.jeanlucmakiola.floret.components.GroupedSwitchRow
|
||||
import de.jeanlucmakiola.floret.components.IconInfoCard
|
||||
import de.jeanlucmakiola.floret.components.OptionPicker
|
||||
import de.jeanlucmakiola.floret.components.Position
|
||||
import de.jeanlucmakiola.floret.components.SelectedCheck
|
||||
import de.jeanlucmakiola.floret.identity.collapseExit
|
||||
@@ -72,7 +50,6 @@ import de.jeanlucmakiola.floret.identity.expandEnter
|
||||
import de.jeanlucmakiola.floret.reminders.ReminderOverride
|
||||
import de.jeanlucmakiola.floret.reminders.minutesOrEmpty
|
||||
import de.jeanlucmakiola.floret.reminders.reminderOverrideFor
|
||||
import kotlinx.coroutines.launch
|
||||
import kotlinx.datetime.LocalTime
|
||||
|
||||
/**
|
||||
@@ -92,9 +69,8 @@ internal fun NotificationsScreen(
|
||||
val launcher = rememberLauncherForActivityResult(
|
||||
contract = ActivityResultContracts.RequestPermission(),
|
||||
) { /* The pref is already on; a denial just leaves the OS gate shut. */ }
|
||||
// Turning either kind of notification on asks for the permission if missing.
|
||||
fun askingPermission(set: (Boolean) -> Unit): (Boolean) -> Unit = { enabled ->
|
||||
set(enabled)
|
||||
val toggleReminders: (Boolean) -> Unit = { enabled ->
|
||||
viewModel.setRemindersEnabled(enabled)
|
||||
val needsPermission = enabled &&
|
||||
Build.VERSION.SDK_INT >= Build.VERSION_CODES.TIRAMISU &&
|
||||
!context.hasPermission(Manifest.permission.POST_NOTIFICATIONS)
|
||||
@@ -102,31 +78,14 @@ internal fun NotificationsScreen(
|
||||
launcher.launch(Manifest.permission.POST_NOTIFICATIONS)
|
||||
}
|
||||
}
|
||||
val toggleReminders = askingPermission(viewModel::setRemindersEnabled)
|
||||
val toggleDigest = askingPermission(viewModel::setDailyDigestEnabled)
|
||||
|
||||
var showDefaultReminder by remember { mutableStateOf(false) }
|
||||
var showAllDayReminder by remember { mutableStateOf(false) }
|
||||
var showAllDayReminderTime by remember { mutableStateOf(false) }
|
||||
var showSnooze by remember { mutableStateOf(false) }
|
||||
var showFixedDefault by remember { mutableStateOf(false) }
|
||||
var fixedOverrideFor by remember { mutableStateOf<Long?>(null) }
|
||||
var showDigestDay by remember { mutableStateOf(false) }
|
||||
var showDigestTime by remember { mutableStateOf(false) }
|
||||
var overrideDialog by remember { mutableStateOf<OverrideTarget?>(null) }
|
||||
var calendarSectionExpanded by remember { mutableStateOf(false) }
|
||||
var expandedCalendars by remember { mutableStateOf(emptySet<Long>()) }
|
||||
val scope = rememberCoroutineScope()
|
||||
val channelStatus by viewModel.channelStatus.collectAsStateWithLifecycle()
|
||||
val digestBlocked by viewModel.digestBlocked.collectAsStateWithLifecycle()
|
||||
val calendarIds = state.reminderCalendars.map { it.id }
|
||||
LifecycleResumeEffect(calendarIds) {
|
||||
viewModel.refreshChannelStatus(calendarIds)
|
||||
onPauseOrDispose { }
|
||||
}
|
||||
val openCalendarSound: (Long) -> Unit = { calendarId ->
|
||||
scope.launch { context.openNotificationSettings(viewModel.soundSettingsChannel(calendarId)) }
|
||||
}
|
||||
|
||||
CollapsingScaffold(
|
||||
title = stringResource(R.string.settings_section_notifications),
|
||||
@@ -134,21 +93,6 @@ internal fun NotificationsScreen(
|
||||
predictiveBack = true,
|
||||
visible = visible,
|
||||
) {
|
||||
if (IS_SAMSUNG && !state.notificationCategoryHintDismissed) {
|
||||
NotificationCategoryHint(
|
||||
onOpen = {
|
||||
viewModel.dismissNotificationCategoryHint()
|
||||
scope.launch {
|
||||
viewModel.syncReminderChannels()
|
||||
// The summary's category too, so it is on the list to check.
|
||||
if (state.dailyDigest.enabled) viewModel.digestChannel()
|
||||
context.openNotificationSettings()
|
||||
}
|
||||
},
|
||||
onDismiss = viewModel::dismissNotificationCategoryHint,
|
||||
)
|
||||
Spacer(Modifier.height(16.dp))
|
||||
}
|
||||
GroupedSwitchRow(
|
||||
title = stringResource(R.string.settings_reminders),
|
||||
checked = state.remindersEnabled,
|
||||
@@ -156,34 +100,12 @@ internal fun NotificationsScreen(
|
||||
summary = stringResource(R.string.settings_reminders_hint),
|
||||
position = Position.Top,
|
||||
)
|
||||
GroupedRow(
|
||||
title = stringResource(R.string.settings_notification_sound),
|
||||
summary = if (channelStatus.appBlocked) {
|
||||
stringResource(R.string.settings_notifications_blocked_hint)
|
||||
} else {
|
||||
stringResource(R.string.settings_notification_sound_hint)
|
||||
},
|
||||
position = Position.Middle,
|
||||
trailing = { ExternalLinkIcon() },
|
||||
onClick = {
|
||||
scope.launch {
|
||||
viewModel.syncReminderChannels()
|
||||
context.openNotificationSettings()
|
||||
}
|
||||
},
|
||||
)
|
||||
GroupedRow(
|
||||
title = stringResource(R.string.settings_default_reminder),
|
||||
summary = reminderChoiceLabel(state.defaultReminderMinutes),
|
||||
position = Position.Middle,
|
||||
onClick = { showDefaultReminder = true },
|
||||
)
|
||||
GroupedRow(
|
||||
title = stringResource(R.string.settings_fixed_reminder),
|
||||
summary = fixedReminderChoiceLabel(state.defaultFixedTimeReminder),
|
||||
position = Position.Middle,
|
||||
onClick = { showFixedDefault = true },
|
||||
)
|
||||
GroupedRow(
|
||||
title = stringResource(R.string.settings_default_reminder_allday),
|
||||
summary = reminderChoiceLabel(state.defaultAllDayReminderMinutes),
|
||||
@@ -200,21 +122,6 @@ internal fun NotificationsScreen(
|
||||
onClick = { showAllDayReminderTime = true },
|
||||
)
|
||||
|
||||
Spacer(Modifier.height(24.dp))
|
||||
DailyDigestRows(
|
||||
digest = state.dailyDigest,
|
||||
blocked = channelStatus.appBlocked || digestBlocked,
|
||||
onEnable = toggleDigest,
|
||||
onPickDay = { showDigestDay = true },
|
||||
onPickTime = { showDigestTime = true },
|
||||
onOpenSound = {
|
||||
// The app's own page while the app is blocked: the channel's would be greyed out.
|
||||
scope.launch {
|
||||
context.openNotificationSettings(viewModel.digestChannel().takeUnless { channelStatus.appBlocked })
|
||||
}
|
||||
},
|
||||
)
|
||||
|
||||
// Reliability is a soft, optional battery-optimisation exemption via
|
||||
// a system-settings deep-link, shown as live status.
|
||||
Spacer(Modifier.height(24.dp))
|
||||
@@ -242,8 +149,10 @@ internal fun NotificationsScreen(
|
||||
onClick = { showSnooze = true },
|
||||
)
|
||||
|
||||
// Per-calendar notifications and reminder overrides (#145, #272).
|
||||
if (state.reminderCalendars.isNotEmpty()) {
|
||||
// Per-calendar overrides, folded behind one header. Each writable
|
||||
// calendar may keep, drop or replace the global default, separately for
|
||||
// timed and all-day events.
|
||||
if (state.writableCalendars.isNotEmpty()) {
|
||||
Spacer(Modifier.height(24.dp))
|
||||
GroupedRow(
|
||||
title = stringResource(R.string.settings_calendar_reminders_title),
|
||||
@@ -258,22 +167,30 @@ internal fun NotificationsScreen(
|
||||
exit = collapseExit(),
|
||||
) {
|
||||
Column {
|
||||
state.reminderCalendars.forEach { calendar ->
|
||||
state.writableCalendars.forEach { calendar ->
|
||||
Spacer(Modifier.height(16.dp))
|
||||
// Special-dates calendars own their reminders in their
|
||||
// own section — link there instead.
|
||||
if (calendar.id in state.managedCalendarIds) {
|
||||
GroupedRow(
|
||||
title = calendar.displayName.orUnnamed(),
|
||||
summary = stringResource(R.string.settings_calendar_reminders_managed_hint),
|
||||
position = Position.Alone,
|
||||
leading = { CalendarColorChip(calendar.color) },
|
||||
trailing = {
|
||||
Icon(
|
||||
imageVector = Icons.AutoMirrored.Filled.KeyboardArrowRight,
|
||||
contentDescription = null,
|
||||
tint = MaterialTheme.colorScheme.onSurfaceVariant,
|
||||
)
|
||||
},
|
||||
onClick = onOpenSpecialDates,
|
||||
)
|
||||
return@forEach
|
||||
}
|
||||
val expanded = calendar.id in expandedCalendars
|
||||
val notifying = calendar.id !in state.mutedReminderCalendarIds
|
||||
val blocked = notifying && calendar.id in channelStatus.blockedCalendarIds
|
||||
GroupedRow(
|
||||
title = calendar.displayName.orUnnamed(),
|
||||
summary = when {
|
||||
// Still in the summary, so only its reminders are off.
|
||||
!notifying && state.dailyDigest.enabled &&
|
||||
calendar.id !in state.dailyDigest.excludedCalendarIds ->
|
||||
stringResource(R.string.settings_calendar_reminders_off)
|
||||
!notifying -> stringResource(R.string.settings_calendar_notifications_off)
|
||||
blocked -> stringResource(R.string.settings_notifications_blocked)
|
||||
else -> null
|
||||
},
|
||||
position = if (expanded) Position.Top else Position.Alone,
|
||||
leading = { CalendarColorChip(calendar.color) },
|
||||
trailing = { ExpandIcon(expanded) },
|
||||
@@ -290,18 +207,22 @@ internal fun NotificationsScreen(
|
||||
enter = expandEnter(),
|
||||
exit = collapseExit(),
|
||||
) {
|
||||
CalendarNotificationRows(
|
||||
calendar = calendar,
|
||||
state = state,
|
||||
notifying = notifying,
|
||||
blocked = blocked,
|
||||
onSetNotifying = { viewModel.setCalendarRemindersEnabled(calendar.id, it) },
|
||||
onOpenSound = { openCalendarSound(calendar.id) },
|
||||
onOpenSpecialDates = onOpenSpecialDates,
|
||||
onEditOverride = { overrideDialog = it },
|
||||
onEditFixedOverride = { fixedOverrideFor = calendar.id },
|
||||
onSetInDigest = { viewModel.setCalendarInDailyDigest(calendar.id, it) },
|
||||
)
|
||||
Column {
|
||||
val timed = state.perCalendarReminderOverride.reminderOverrideFor(calendar.id)
|
||||
GroupedRow(
|
||||
title = stringResource(R.string.settings_default_reminder),
|
||||
summary = calendarOverrideSummary(timed, state.defaultReminderMinutes),
|
||||
position = Position.Middle,
|
||||
onClick = { overrideDialog = OverrideTarget(calendar.id, isAllDay = false) },
|
||||
)
|
||||
val allDay = state.perCalendarAllDayReminderOverride.reminderOverrideFor(calendar.id)
|
||||
GroupedRow(
|
||||
title = stringResource(R.string.settings_default_reminder_allday),
|
||||
summary = calendarOverrideSummary(allDay, state.defaultAllDayReminderMinutes),
|
||||
position = Position.Bottom,
|
||||
onClick = { overrideDialog = OverrideTarget(calendar.id, isAllDay = true) },
|
||||
)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -309,44 +230,6 @@ internal fun NotificationsScreen(
|
||||
}
|
||||
}
|
||||
|
||||
if (showFixedDefault) {
|
||||
FixedTimeReminderPicker(
|
||||
title = stringResource(R.string.settings_fixed_reminder),
|
||||
selected = state.defaultFixedTimeReminder?.let { FixedTimeOverride.At(it) } ?: FixedTimeOverride.Off,
|
||||
onSelect = { viewModel.setDefaultFixedTimeReminder((it as? FixedTimeOverride.At)?.reminder) },
|
||||
onDismiss = { showFixedDefault = false },
|
||||
)
|
||||
}
|
||||
fixedOverrideFor?.let { calendarId ->
|
||||
FixedTimeReminderPicker(
|
||||
title = stringResource(R.string.settings_fixed_reminder),
|
||||
selected = state.perCalendarFixedTimeReminderOverride.fixedTimeOverrideFor(calendarId),
|
||||
onSelect = { viewModel.setCalendarFixedTimeReminderOverride(calendarId, it) },
|
||||
onDismiss = { fixedOverrideFor = null },
|
||||
inheritedLabel = fixedReminderChoiceLabel(state.defaultFixedTimeReminder),
|
||||
inherited = state.defaultFixedTimeReminder,
|
||||
)
|
||||
}
|
||||
if (showDigestDay) {
|
||||
OptionPicker(
|
||||
title = stringResource(R.string.settings_digest_day),
|
||||
options = DigestDay.entries,
|
||||
selected = state.dailyDigest.day,
|
||||
label = { stringResource(digestDayLabel(it)) },
|
||||
onSelect = viewModel::setDailyDigestDay,
|
||||
onDismiss = { showDigestDay = false },
|
||||
)
|
||||
}
|
||||
if (showDigestTime) {
|
||||
TimePickerAlert(
|
||||
initial = LocalTime(state.dailyDigest.timeMinutes / 60, state.dailyDigest.timeMinutes % 60),
|
||||
onConfirm = {
|
||||
viewModel.setDailyDigestTimeMinutes(it.hour * 60 + it.minute)
|
||||
showDigestTime = false
|
||||
},
|
||||
onDismiss = { showDigestTime = false },
|
||||
)
|
||||
}
|
||||
if (showSnooze) {
|
||||
DurationPicker(
|
||||
title = stringResource(R.string.settings_snooze_duration),
|
||||
@@ -426,199 +309,6 @@ internal fun NotificationsScreen(
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* One calendar's expanded rows: its notification switch and channel deep-link
|
||||
* for every calendar, then the default-reminder overrides where it takes them —
|
||||
* or, for a special-dates calendar, a link to the section that owns them.
|
||||
*/
|
||||
@Composable
|
||||
private fun CalendarNotificationRows(
|
||||
calendar: CalendarSource,
|
||||
state: SettingsUiState,
|
||||
notifying: Boolean,
|
||||
blocked: Boolean,
|
||||
onSetNotifying: (Boolean) -> Unit,
|
||||
onOpenSound: () -> Unit,
|
||||
onOpenSpecialDates: () -> Unit,
|
||||
onEditOverride: (OverrideTarget) -> Unit,
|
||||
onEditFixedOverride: () -> Unit,
|
||||
onSetInDigest: (Boolean) -> Unit,
|
||||
) {
|
||||
val managed = calendar.id in state.managedCalendarIds
|
||||
val takesOverrides = calendar.canModifyContents && !managed
|
||||
val digestOn = state.dailyDigest.enabled
|
||||
Column {
|
||||
GroupedSwitchRow(
|
||||
title = stringResource(R.string.settings_calendar_notifications),
|
||||
checked = notifying,
|
||||
onCheckedChange = onSetNotifying,
|
||||
summary = stringResource(R.string.settings_calendar_notifications_hint),
|
||||
position = Position.Middle,
|
||||
)
|
||||
GroupedRow(
|
||||
title = stringResource(R.string.settings_notification_sound),
|
||||
summary = if (blocked) {
|
||||
stringResource(R.string.settings_notifications_blocked_hint)
|
||||
} else {
|
||||
stringResource(R.string.settings_calendar_notification_sound_hint)
|
||||
},
|
||||
position = if (managed || takesOverrides || digestOn) Position.Middle else Position.Bottom,
|
||||
trailing = { ExternalLinkIcon() },
|
||||
onClick = onOpenSound,
|
||||
)
|
||||
if (digestOn) {
|
||||
GroupedSwitchRow(
|
||||
title = stringResource(R.string.settings_calendar_in_digest),
|
||||
checked = calendar.id !in state.dailyDigest.excludedCalendarIds,
|
||||
onCheckedChange = onSetInDigest,
|
||||
summary = stringResource(R.string.settings_calendar_in_digest_hint),
|
||||
position = if (managed || takesOverrides) Position.Middle else Position.Bottom,
|
||||
)
|
||||
}
|
||||
if (managed) {
|
||||
GroupedRow(
|
||||
title = stringResource(R.string.settings_default_reminder_allday),
|
||||
summary = stringResource(R.string.settings_calendar_reminders_managed_hint),
|
||||
position = Position.Bottom,
|
||||
trailing = {
|
||||
Icon(
|
||||
imageVector = Icons.AutoMirrored.Filled.KeyboardArrowRight,
|
||||
contentDescription = null,
|
||||
tint = MaterialTheme.colorScheme.onSurfaceVariant,
|
||||
)
|
||||
},
|
||||
onClick = onOpenSpecialDates,
|
||||
)
|
||||
} else if (takesOverrides) {
|
||||
val timed = state.perCalendarReminderOverride.reminderOverrideFor(calendar.id)
|
||||
GroupedRow(
|
||||
title = stringResource(R.string.settings_default_reminder),
|
||||
summary = calendarOverrideSummary(timed, state.defaultReminderMinutes),
|
||||
position = Position.Middle,
|
||||
onClick = { onEditOverride(OverrideTarget(calendar.id, isAllDay = false)) },
|
||||
)
|
||||
GroupedRow(
|
||||
title = stringResource(R.string.settings_fixed_reminder),
|
||||
summary = when (val fixed = state.perCalendarFixedTimeReminderOverride.fixedTimeOverrideFor(calendar.id)) {
|
||||
FixedTimeOverride.Inherit -> stringResource(
|
||||
R.string.settings_calendar_reminder_inherits,
|
||||
fixedReminderChoiceLabel(state.defaultFixedTimeReminder),
|
||||
)
|
||||
FixedTimeOverride.Off -> stringResource(R.string.reminder_none)
|
||||
is FixedTimeOverride.At -> fixedTimeReminderLabel(fixed.reminder)
|
||||
},
|
||||
position = Position.Middle,
|
||||
onClick = onEditFixedOverride,
|
||||
)
|
||||
val allDay = state.perCalendarAllDayReminderOverride.reminderOverrideFor(calendar.id)
|
||||
GroupedRow(
|
||||
title = stringResource(R.string.settings_default_reminder_allday),
|
||||
summary = calendarOverrideSummary(allDay, state.defaultAllDayReminderMinutes),
|
||||
position = Position.Bottom,
|
||||
onClick = { onEditOverride(OverrideTarget(calendar.id, isAllDay = true)) },
|
||||
)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* The daily summary (#459): its switch, and once on, which day it lists, when,
|
||||
* and its channel's system settings.
|
||||
*/
|
||||
@Composable
|
||||
private fun DailyDigestRows(
|
||||
digest: DailyDigestSettings,
|
||||
blocked: Boolean,
|
||||
onEnable: (Boolean) -> Unit,
|
||||
onPickDay: () -> Unit,
|
||||
onPickTime: () -> Unit,
|
||||
onOpenSound: () -> Unit,
|
||||
) {
|
||||
GroupedSwitchRow(
|
||||
title = stringResource(R.string.settings_digest),
|
||||
checked = digest.enabled,
|
||||
onCheckedChange = onEnable,
|
||||
summary = if (digest.enabled) {
|
||||
stringResource(
|
||||
R.string.settings_digest_summary,
|
||||
stringResource(digestDayLabel(digest.day)),
|
||||
settingsTimeOfDay(digest.timeMinutes),
|
||||
)
|
||||
} else {
|
||||
stringResource(R.string.settings_digest_hint)
|
||||
},
|
||||
position = if (digest.enabled) Position.Top else Position.Alone,
|
||||
)
|
||||
AnimatedVisibility(visible = digest.enabled, enter = expandEnter(), exit = collapseExit()) {
|
||||
Column {
|
||||
GroupedRow(
|
||||
title = stringResource(R.string.settings_digest_day),
|
||||
summary = stringResource(digestDayLabel(digest.day)),
|
||||
position = Position.Middle,
|
||||
onClick = onPickDay,
|
||||
)
|
||||
GroupedRow(
|
||||
title = stringResource(R.string.settings_digest_time),
|
||||
summary = settingsTimeOfDay(digest.timeMinutes),
|
||||
position = Position.Middle,
|
||||
onClick = onPickTime,
|
||||
)
|
||||
GroupedRow(
|
||||
title = stringResource(R.string.settings_notification_sound),
|
||||
summary = if (blocked) {
|
||||
stringResource(R.string.settings_notifications_blocked_hint)
|
||||
} else {
|
||||
stringResource(R.string.settings_digest_sound_hint)
|
||||
},
|
||||
position = Position.Bottom,
|
||||
trailing = { ExternalLinkIcon() },
|
||||
onClick = onOpenSound,
|
||||
)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/** Samsung's One UI can start a new notification category switched off (#145). */
|
||||
private val IS_SAMSUNG = Build.MANUFACTURER.equals("samsung", ignoreCase = true)
|
||||
|
||||
/** The one-time Samsung note, with a way into the app's notification settings. */
|
||||
@Composable
|
||||
private fun NotificationCategoryHint(onOpen: () -> Unit, onDismiss: () -> Unit) {
|
||||
IconInfoCard(
|
||||
icon = Icons.Outlined.Info,
|
||||
iconContentDescription = null,
|
||||
iconAlignment = Alignment.Top,
|
||||
) {
|
||||
Text(
|
||||
text = stringResource(R.string.settings_notification_category_hint),
|
||||
style = MaterialTheme.typography.bodyMedium,
|
||||
)
|
||||
Row(Modifier.fillMaxWidth(), horizontalArrangement = Arrangement.End) {
|
||||
TextButton(onClick = onDismiss) { Text(stringResource(R.string.reminder_action_dismiss)) }
|
||||
TextButton(onClick = onOpen) { Text(stringResource(R.string.settings_notification_category_hint_open)) }
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private fun digestDayLabel(day: DigestDay): Int = when (day) {
|
||||
DigestDay.Today -> R.string.settings_digest_day_today
|
||||
DigestDay.Tomorrow -> R.string.settings_digest_day_tomorrow
|
||||
}
|
||||
|
||||
/** A fixed-time default's label, or "None". */
|
||||
@Composable
|
||||
private fun fixedReminderChoiceLabel(reminder: FixedTimeReminder?): String =
|
||||
reminder?.let { fixedTimeReminderLabel(it) } ?: stringResource(R.string.reminder_none)
|
||||
|
||||
@Composable
|
||||
private fun ExternalLinkIcon() {
|
||||
Icon(
|
||||
imageVector = Icons.AutoMirrored.Filled.OpenInNew,
|
||||
contentDescription = null,
|
||||
tint = MaterialTheme.colorScheme.onSurfaceVariant,
|
||||
)
|
||||
}
|
||||
|
||||
/** Which calendar + event kind a per-calendar reminder-override dialog targets. */
|
||||
private data class OverrideTarget(val calendarId: Long, val isAllDay: Boolean)
|
||||
|
||||
|
||||
@@ -1,7 +1,5 @@
|
||||
package de.jeanlucmakiola.calendula.ui.settings
|
||||
|
||||
import de.jeanlucmakiola.calendula.domain.reminders.DailyDigestSettings
|
||||
import de.jeanlucmakiola.calendula.domain.reminders.FixedTimeReminder
|
||||
import de.jeanlucmakiola.floret.reminders.ReminderOverride
|
||||
import de.jeanlucmakiola.calendula.data.prefs.PastEventDisplay
|
||||
import de.jeanlucmakiola.calendula.data.prefs.SettingsPrefs
|
||||
@@ -44,8 +42,6 @@ data class SettingsUiState(
|
||||
val dimCompletedEvents: Boolean = false,
|
||||
/** Whether the Month grid shows calendar-week numbers in a left gutter (#25). */
|
||||
val showWeekNumbers: Boolean = false,
|
||||
/** Whether Month chips may show start times before their titles (#476). */
|
||||
val monthShowStartTimes: Boolean = true,
|
||||
/** Whether the jump-to-today control sits in the top bar instead of the FAB (#60). */
|
||||
val todayButtonInToolbar: Boolean = false,
|
||||
/** Whether events can be dragged to another slot to reschedule them (#68, #173). */
|
||||
@@ -98,20 +94,8 @@ data class SettingsUiState(
|
||||
val perCalendarReminderOverride: Map<Long, List<Int>> = emptyMap(),
|
||||
/** Per-calendar overrides of [defaultAllDayReminderMinutes] for all-day events. */
|
||||
val perCalendarAllDayReminderOverride: Map<Long, List<Int>> = emptyMap(),
|
||||
/** The "N days before at HH:MM" default for new timed events (#459); null = none. */
|
||||
val defaultFixedTimeReminder: FixedTimeReminder? = null,
|
||||
/** Per-calendar overrides of [defaultFixedTimeReminder]: absent inherits, null turns it off. */
|
||||
val perCalendarFixedTimeReminderOverride: Map<Long, FixedTimeReminder?> = emptyMap(),
|
||||
/** The daily summary notification (#459). */
|
||||
val dailyDigest: DailyDigestSettings = DailyDigestSettings(),
|
||||
/** Switched-on calendars you can edit: the per-calendar event-duration rows. */
|
||||
/** Writable calendars, shown as per-calendar reminder-override rows. */
|
||||
val writableCalendars: List<CalendarSource> = emptyList(),
|
||||
/** Switched-on calendars, each with its own notification switch and channel (#145, #272). */
|
||||
val reminderCalendars: List<CalendarSource> = emptyList(),
|
||||
/** Calendars whose reminders Calendula doesn't post (#272). */
|
||||
val mutedReminderCalendarIds: Set<Long> = emptySet(),
|
||||
/** Whether the Samsung notification-category hint has been dismissed (#145); hidden until prefs load. */
|
||||
val notificationCategoryHintDismissed: Boolean = true,
|
||||
/**
|
||||
* Whether the event-colour picker is offered on calendars that publish no
|
||||
* colour palette (the colour may then not survive their next sync).
|
||||
|
||||
@@ -3,7 +3,6 @@ package de.jeanlucmakiola.calendula.ui.settings
|
||||
import android.content.Context
|
||||
import android.net.Uri
|
||||
import android.os.Build
|
||||
import android.util.Log
|
||||
import androidx.datastore.preferences.core.Preferences
|
||||
import androidx.lifecycle.ViewModel
|
||||
import androidx.lifecycle.viewModelScope
|
||||
@@ -19,15 +18,8 @@ import de.jeanlucmakiola.calendula.data.contacts.resolveTitleTemplate
|
||||
import de.jeanlucmakiola.calendula.data.fonts.CustomFontStore
|
||||
import de.jeanlucmakiola.floret.android.stateWhileSubscribed
|
||||
import de.jeanlucmakiola.floret.di.IoDispatcher
|
||||
import de.jeanlucmakiola.calendula.data.prefs.FixedTimeOverride
|
||||
import de.jeanlucmakiola.calendula.data.prefs.dailyDigest
|
||||
import de.jeanlucmakiola.calendula.data.prefs.ReminderStatePrefs
|
||||
import de.jeanlucmakiola.calendula.data.reminders.DailyDigestNotifier
|
||||
import de.jeanlucmakiola.calendula.domain.reminders.DigestDay
|
||||
import de.jeanlucmakiola.calendula.domain.reminders.FixedTimeReminder
|
||||
import de.jeanlucmakiola.floret.reminders.ReminderOverride
|
||||
import de.jeanlucmakiola.floret.reminders.reminderOverrideFor
|
||||
import de.jeanlucmakiola.calendula.data.prefs.CalendarPrefs
|
||||
import de.jeanlucmakiola.calendula.data.prefs.PastEventDisplay
|
||||
import de.jeanlucmakiola.calendula.data.prefs.SettingsKeys
|
||||
import de.jeanlucmakiola.calendula.data.prefs.SettingsPrefs
|
||||
@@ -41,8 +33,6 @@ import de.jeanlucmakiola.calendula.data.prefs.SpecialDatesStalledReason
|
||||
import de.jeanlucmakiola.floret.prefs.ThemeMode
|
||||
import de.jeanlucmakiola.calendula.data.prefs.TimeFormatPref
|
||||
import de.jeanlucmakiola.calendula.data.prefs.WeekStartPref
|
||||
import de.jeanlucmakiola.calendula.data.reminders.ReminderChannelStatus
|
||||
import de.jeanlucmakiola.calendula.data.reminders.ReminderChannels
|
||||
import de.jeanlucmakiola.calendula.data.reminders.ReminderScanner
|
||||
import de.jeanlucmakiola.calendula.domain.CalendarSource
|
||||
import de.jeanlucmakiola.calendula.domain.EventFormField
|
||||
@@ -55,9 +45,7 @@ import de.jeanlucmakiola.calendula.ui.common.TimelineScale
|
||||
import de.jeanlucmakiola.calendula.ui.month.MonthViewStyle
|
||||
import de.jeanlucmakiola.calendula.ui.theme.AppFontSettings
|
||||
import de.jeanlucmakiola.calendula.ui.theme.FONT_CUSTOM_TOKEN
|
||||
import kotlinx.coroutines.CancellationException
|
||||
import kotlinx.coroutines.CoroutineDispatcher
|
||||
import kotlinx.coroutines.Job
|
||||
import kotlinx.coroutines.flow.Flow
|
||||
import kotlinx.coroutines.flow.MutableSharedFlow
|
||||
import kotlinx.coroutines.flow.MutableStateFlow
|
||||
@@ -74,15 +62,11 @@ import javax.inject.Inject
|
||||
@HiltViewModel
|
||||
class SettingsViewModel @Inject constructor(
|
||||
private val prefs: SettingsPrefs,
|
||||
calendarPrefs: CalendarPrefs,
|
||||
repository: CalendarRepository,
|
||||
private val specialDatesEngine: SpecialDatesSyncEngine,
|
||||
specialDatesSpec: SpecialDatesCalendarSpec,
|
||||
private val launcherNameManager: LauncherNameManager,
|
||||
private val reminderScanner: ReminderScanner,
|
||||
private val reminderChannels: ReminderChannels,
|
||||
private val digestNotifier: DailyDigestNotifier,
|
||||
private val reminderState: ReminderStatePrefs,
|
||||
@IoDispatcher private val io: CoroutineDispatcher,
|
||||
@ApplicationContext private val appContext: Context,
|
||||
) : ViewModel() {
|
||||
@@ -90,16 +74,16 @@ class SettingsViewModel @Inject constructor(
|
||||
private val dynamicColorAvailable = Build.VERSION.SDK_INT >= Build.VERSION_CODES.S
|
||||
|
||||
/**
|
||||
* Calendars that are switched on — the only ones that plan reminders at
|
||||
* all (#75), so the only ones with notification settings.
|
||||
* Writable calendars that are switched on — the only ones that take a
|
||||
* per-calendar reminder override, since a switched-off one plans no
|
||||
* reminders at all (#75).
|
||||
*/
|
||||
private val visibleCalendars: Flow<List<CalendarSource>> =
|
||||
combine(repository.calendars(), calendarPrefs.pendingDisabledCalendarIds) { calendars, pending ->
|
||||
calendars.filter { it.isVisibleInSystem && it.id !in pending }
|
||||
}.catch { emit(emptyList()) }
|
||||
private val writableCalendars: Flow<List<CalendarSource>> = repository.calendars()
|
||||
.map { calendars -> calendars.filter { it.canModifyContents && it.isVisibleInSystem } }
|
||||
.catch { emit(emptyList()) }
|
||||
|
||||
val state: StateFlow<SettingsUiState> =
|
||||
combine(prefs.data, visibleCalendars) { stored, calendars -> stored.toUiState(calendars) }
|
||||
combine(prefs.data, writableCalendars) { stored, calendars -> stored.toUiState(calendars) }
|
||||
.stateWhileSubscribed(
|
||||
scope = viewModelScope,
|
||||
initialValue = SettingsUiState(dynamicColorAvailable = dynamicColorAvailable),
|
||||
@@ -117,7 +101,6 @@ class SettingsViewModel @Inject constructor(
|
||||
pastEventDisplay = this[SettingsKeys.pastEventDisplay],
|
||||
dimCompletedEvents = this[SettingsKeys.dimCompletedEvents],
|
||||
showWeekNumbers = this[SettingsKeys.showWeekNumbers],
|
||||
monthShowStartTimes = this[SettingsKeys.monthShowStartTimes],
|
||||
todayButtonInToolbar = this[SettingsKeys.todayButtonInToolbar],
|
||||
dragToReschedule = this[SettingsKeys.dragToReschedule],
|
||||
tapOpensEditor = this[SettingsKeys.tapOpensEditor],
|
||||
@@ -141,13 +124,7 @@ class SettingsViewModel @Inject constructor(
|
||||
snoozeMinutes = this[SettingsKeys.snoozeMinutes],
|
||||
perCalendarReminderOverride = this[SettingsKeys.perCalendarReminderOverride],
|
||||
perCalendarAllDayReminderOverride = this[SettingsKeys.perCalendarAllDayReminderOverride],
|
||||
defaultFixedTimeReminder = this[SettingsKeys.defaultFixedTimeReminder],
|
||||
perCalendarFixedTimeReminderOverride = this[SettingsKeys.perCalendarFixedTimeReminderOverride],
|
||||
dailyDigest = dailyDigest,
|
||||
writableCalendars = calendars.filter { it.canModifyContents },
|
||||
reminderCalendars = calendars,
|
||||
mutedReminderCalendarIds = this[SettingsKeys.mutedReminderCalendarIds],
|
||||
notificationCategoryHintDismissed = this[SettingsKeys.notificationCategoryHintDismissed],
|
||||
writableCalendars = calendars,
|
||||
allowColorOnUnsupportedCalendars = this[SettingsKeys.allowColorOnUnsupportedCalendars],
|
||||
managedCalendarIds = specialDatesCalendars.values.toSet(),
|
||||
)
|
||||
@@ -315,8 +292,6 @@ class SettingsViewModel @Inject constructor(
|
||||
|
||||
fun setShowWeekNumbers(enabled: Boolean) = save { setShowWeekNumbers(enabled) }
|
||||
|
||||
fun setMonthShowStartTimes(enabled: Boolean) = save { setMonthShowStartTimes(enabled) }
|
||||
|
||||
fun setTodayButtonInToolbar(enabled: Boolean) = save { setTodayButtonInToolbar(enabled) }
|
||||
|
||||
fun setDragToReschedule(enabled: Boolean) = save { setDragToReschedule(enabled) }
|
||||
@@ -372,73 +347,13 @@ class SettingsViewModel @Inject constructor(
|
||||
* A scan follows the write: switching reminders off cancels the scan alarm,
|
||||
* so switching them back on has to arm a new one (#75).
|
||||
*/
|
||||
fun setRemindersEnabled(enabled: Boolean) = saveAndScan { setRemindersEnabled(enabled) }
|
||||
|
||||
/**
|
||||
* Re-plans, since a muted calendar armed no wake-up for its next reminder.
|
||||
* Unmuting scans once more before the write, so the watermark starts at the
|
||||
* unmute and nothing that came due while muted is replayed.
|
||||
*/
|
||||
fun setCalendarRemindersEnabled(calendarId: Long, enabled: Boolean) {
|
||||
fun setRemindersEnabled(enabled: Boolean) {
|
||||
viewModelScope.launch {
|
||||
if (enabled) reminderScanner.scan()
|
||||
prefs.setCalendarRemindersEnabled(calendarId, enabled)
|
||||
prefs.setRemindersEnabled(enabled)
|
||||
reminderScanner.scan()
|
||||
}
|
||||
}
|
||||
|
||||
private val _channelStatus = MutableStateFlow(ReminderChannelStatus())
|
||||
|
||||
/** What the system blocks of the reminders; re-read with [refreshChannelStatus] (#145). */
|
||||
val channelStatus: StateFlow<ReminderChannelStatus> = _channelStatus.asStateFlow()
|
||||
|
||||
private var channelStatusJob: Job? = null
|
||||
|
||||
fun refreshChannelStatus(calendarIds: Collection<Long>) {
|
||||
channelStatusJob?.cancel()
|
||||
channelStatusJob = viewModelScope.launch {
|
||||
onChannels { status(calendarIds) }?.let { _channelStatus.value = it }
|
||||
_digestBlocked.value = withContext(io) { runCatching { digestNotifier.isChannelOff() }.getOrDefault(false) }
|
||||
}
|
||||
}
|
||||
|
||||
private val _digestBlocked = MutableStateFlow(false)
|
||||
|
||||
/**
|
||||
* Whether the daily summary's own channel is switched off (#459); the app-wide
|
||||
* block is [channelStatus]'s. Refreshed with [refreshChannelStatus].
|
||||
*/
|
||||
val digestBlocked: StateFlow<Boolean> = _digestBlocked.asStateFlow()
|
||||
|
||||
fun dismissNotificationCategoryHint() = save { dismissNotificationCategoryHint() }
|
||||
|
||||
/**
|
||||
* The channel whose system screen to open for [calendarId] (#340), created
|
||||
* if needed; null when only the app's own screen can help — the app or the
|
||||
* calendar's account group is blocked there, or the channel couldn't be made.
|
||||
*/
|
||||
suspend fun soundSettingsChannel(calendarId: Long): String? = onChannels {
|
||||
val channelId = channelFor(calendarId) ?: return@onChannels null
|
||||
val status = status(listOf(calendarId))
|
||||
channelId.takeUnless { status.appBlocked || calendarId in status.groupBlockedCalendarIds }
|
||||
}
|
||||
|
||||
/** Create the per-calendar channels before showing the app's channel list, even with reminders off. */
|
||||
suspend fun syncReminderChannels() {
|
||||
onChannels { sync() }
|
||||
}
|
||||
|
||||
private suspend fun <T> onChannels(block: ReminderChannels.() -> T): T? = withContext(io) {
|
||||
try {
|
||||
reminderChannels.block()
|
||||
} catch (e: CancellationException) {
|
||||
throw e
|
||||
} catch (e: Exception) {
|
||||
Log.w("SettingsViewModel", "Reminder channel update failed", e)
|
||||
null
|
||||
}
|
||||
}
|
||||
|
||||
fun setAutofocusEventTitle(enabled: Boolean) = save { setAutofocusEventTitle(enabled) }
|
||||
|
||||
fun setDefaultEventDuration(minutes: Int) = save { setDefaultEventDurationMinutes(minutes) }
|
||||
@@ -451,7 +366,12 @@ class SettingsViewModel @Inject constructor(
|
||||
fun setDefaultAllDayReminderMinutes(minutes: List<Int>) = save { setDefaultAllDayReminderMinutes(minutes) }
|
||||
|
||||
/** The armed alarm was planned for the old hour, so re-plan against the new one. */
|
||||
fun setAllDayReminderTimeMinutes(minutesOfDay: Int) = saveAndScan { setAllDayReminderTimeMinutes(minutesOfDay) }
|
||||
fun setAllDayReminderTimeMinutes(minutesOfDay: Int) {
|
||||
viewModelScope.launch {
|
||||
prefs.setAllDayReminderTimeMinutes(minutesOfDay)
|
||||
reminderScanner.scan()
|
||||
}
|
||||
}
|
||||
|
||||
fun setSnoozeMinutes(minutes: Int) = save { setSnoozeMinutes(minutes) }
|
||||
|
||||
@@ -461,53 +381,6 @@ class SettingsViewModel @Inject constructor(
|
||||
|
||||
fun setAllowColorOnUnsupportedCalendars(enabled: Boolean) = save { setAllowColorOnUnsupportedCalendars(enabled) }
|
||||
|
||||
fun setDefaultFixedTimeReminder(reminder: FixedTimeReminder?) = save { setDefaultFixedTimeReminder(reminder) }
|
||||
|
||||
fun setCalendarFixedTimeReminderOverride(calendarId: Long, override: FixedTimeOverride) =
|
||||
save { setCalendarFixedTimeReminderOverride(calendarId, override) }
|
||||
|
||||
/** Every summary change re-plans, so the next one is armed for its new moment (#459). */
|
||||
fun setDailyDigestEnabled(enabled: Boolean) {
|
||||
viewModelScope.launch {
|
||||
prefs.setDailyDigestEnabled(enabled)
|
||||
// Created now, so a phone that starts new categories switched off
|
||||
// shows it blocked here rather than dropping the first summary.
|
||||
if (enabled) {
|
||||
digestChannel()
|
||||
_digestBlocked.value = withContext(io) { runCatching { digestNotifier.isChannelOff() }.getOrDefault(false) }
|
||||
}
|
||||
// After the scan, so one already under way can't post past the cancel;
|
||||
// a summary left showing would go stale with nothing to replace it.
|
||||
reminderScanner.scan()
|
||||
if (!enabled) digestNotifier.cancel()
|
||||
}
|
||||
}
|
||||
|
||||
fun setDailyDigestTimeMinutes(minutesOfDay: Int) = saveAndScan { setDailyDigestTimeMinutes(minutesOfDay) }
|
||||
|
||||
/** A new mode lists afresh: from "tomorrow" to "today", the day just listed comes again. */
|
||||
fun setDailyDigestDay(day: DigestDay) {
|
||||
viewModelScope.launch {
|
||||
prefs.setDailyDigestDay(day)
|
||||
reminderState.clearLastDigestDay()
|
||||
reminderScanner.scan()
|
||||
}
|
||||
}
|
||||
|
||||
fun setCalendarInDailyDigest(calendarId: Long, included: Boolean) = save { setCalendarInDailyDigest(calendarId, included) }
|
||||
|
||||
/** The summary's channel, created if needed so its system settings can open. */
|
||||
suspend fun digestChannel(): String? = withContext(io) {
|
||||
runCatching { digestNotifier.channelId() }.getOrNull()
|
||||
}
|
||||
|
||||
private fun saveAndScan(write: suspend SettingsPrefs.() -> Unit) {
|
||||
viewModelScope.launch {
|
||||
prefs.write()
|
||||
reminderScanner.scan()
|
||||
}
|
||||
}
|
||||
|
||||
private fun save(write: suspend SettingsPrefs.() -> Unit) {
|
||||
viewModelScope.launch { prefs.write() }
|
||||
}
|
||||
|
||||
@@ -160,13 +160,6 @@ internal fun ViewsScreen(
|
||||
checked = state.showWeekNumbers,
|
||||
onCheckedChange = viewModel::setShowWeekNumbers,
|
||||
summary = stringResource(R.string.settings_week_numbers_summary),
|
||||
position = Position.Middle,
|
||||
)
|
||||
GroupedSwitchRow(
|
||||
title = stringResource(R.string.settings_month_start_times),
|
||||
checked = state.monthShowStartTimes,
|
||||
onCheckedChange = viewModel::setMonthShowStartTimes,
|
||||
summary = stringResource(R.string.settings_month_start_times_summary),
|
||||
position = Position.Bottom,
|
||||
)
|
||||
|
||||
@@ -303,7 +296,6 @@ internal fun ViewsScreen(
|
||||
selected = state.monthViewStyle,
|
||||
// The preview is a real grid, so it uses the real week start too.
|
||||
weekStart = state.weekStart.resolveFirstDay(currentLocale()),
|
||||
showStartTimes = state.monthShowStartTimes,
|
||||
onSelect = viewModel::setMonthViewStyle,
|
||||
onDismiss = { showMonthStyle = false },
|
||||
)
|
||||
@@ -332,7 +324,6 @@ internal fun ViewsScreen(
|
||||
selected = state.weekStart,
|
||||
// The preview is a real grid, so it uses the user's own month style.
|
||||
monthStyle = state.monthViewStyle,
|
||||
showStartTimes = state.monthShowStartTimes,
|
||||
options = WEEK_START_OPTIONS,
|
||||
onSelect = viewModel::setWeekStart,
|
||||
onDismiss = { showWeekStart = false },
|
||||
|
||||
@@ -27,7 +27,6 @@ import de.jeanlucmakiola.floret.locale.currentLocale
|
||||
internal fun WeekStartPicker(
|
||||
selected: WeekStartPref,
|
||||
monthStyle: MonthViewStyle,
|
||||
showStartTimes: Boolean,
|
||||
options: List<WeekStartPref>,
|
||||
onSelect: (WeekStartPref) -> Unit,
|
||||
onDismiss: () -> Unit,
|
||||
@@ -47,7 +46,6 @@ internal fun WeekStartPicker(
|
||||
MonthStylePreview(
|
||||
style = monthStyle,
|
||||
weekStart = day,
|
||||
showStartTimes = showStartTimes,
|
||||
height = PREVIEW_HEIGHT,
|
||||
)
|
||||
}
|
||||
|
||||
@@ -6,7 +6,6 @@ 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.StripDrop
|
||||
import de.jeanlucmakiola.calendula.ui.common.TimelineDragController
|
||||
import de.jeanlucmakiola.calendula.ui.common.TimelineDrop
|
||||
import de.jeanlucmakiola.calendula.ui.common.TimelineResizeDrop
|
||||
@@ -26,7 +25,6 @@ internal class TimelineActions(
|
||||
val onCreateAt: (LocalDate, Int) -> Unit,
|
||||
val onDrop: (TimelineDrop) -> Unit,
|
||||
val onResize: (TimelineResizeDrop) -> Unit,
|
||||
val onStripDrop: (StripDrop) -> Unit,
|
||||
)
|
||||
|
||||
/** The callbacks are read through their latest values, so the holder outlives them. */
|
||||
@@ -39,14 +37,12 @@ internal fun rememberTimelineActions(
|
||||
onCreateAt: (LocalDate, Int) -> Unit,
|
||||
onDrop: (TimelineDrop) -> Unit,
|
||||
onResize: (TimelineResizeDrop) -> Unit,
|
||||
onStripDrop: (StripDrop) -> Unit,
|
||||
): TimelineActions {
|
||||
val eventClick = rememberUpdatedState(onEventClick)
|
||||
val openDay = rememberUpdatedState(onOpenDay)
|
||||
val createAt = rememberUpdatedState(onCreateAt)
|
||||
val drop = rememberUpdatedState(onDrop)
|
||||
val resize = rememberUpdatedState(onResize)
|
||||
val stripDrop = rememberUpdatedState(onStripDrop)
|
||||
return remember(scrollState, dragController) {
|
||||
TimelineActions(
|
||||
scrollState = scrollState,
|
||||
@@ -56,7 +52,6 @@ internal fun rememberTimelineActions(
|
||||
onCreateAt = { date, minutes -> createAt.value(date, minutes) },
|
||||
onDrop = { drop.value(it) },
|
||||
onResize = { resize.value(it) },
|
||||
onStripDrop = { stripDrop.value(it) },
|
||||
)
|
||||
}
|
||||
}
|
||||
@@ -106,16 +106,9 @@ import androidx.compose.ui.draw.alpha
|
||||
import androidx.compose.ui.draw.clip
|
||||
import androidx.compose.ui.draw.clipToBounds
|
||||
import androidx.compose.ui.graphics.graphicsLayer
|
||||
import androidx.compose.animation.core.FiniteAnimationSpec
|
||||
import androidx.compose.animation.core.animateFloatAsState
|
||||
import androidx.compose.animation.core.snap
|
||||
import androidx.compose.material3.ExperimentalMaterial3ExpressiveApi
|
||||
import androidx.compose.runtime.State
|
||||
import androidx.compose.ui.layout.ParentDataModifier
|
||||
import androidx.compose.ui.unit.Density
|
||||
import androidx.compose.ui.layout.layout
|
||||
import androidx.compose.ui.graphics.RectangleShape
|
||||
import androidx.compose.ui.graphics.Shape
|
||||
import androidx.compose.ui.input.pointer.pointerInput
|
||||
import androidx.compose.ui.layout.onGloballyPositioned
|
||||
import androidx.compose.ui.platform.LocalDensity
|
||||
@@ -132,9 +125,6 @@ import androidx.compose.ui.unit.dp
|
||||
import androidx.hilt.navigation.compose.hiltViewModel
|
||||
import androidx.lifecycle.compose.collectAsStateWithLifecycle
|
||||
import de.jeanlucmakiola.calendula.R
|
||||
import de.jeanlucmakiola.calendula.domain.dateZone
|
||||
import de.jeanlucmakiola.calendula.domain.spanFirstDay
|
||||
import de.jeanlucmakiola.calendula.domain.spanLastDay
|
||||
import de.jeanlucmakiola.calendula.domain.EventInstance
|
||||
import de.jeanlucmakiola.calendula.ui.common.LocalChipGround
|
||||
import de.jeanlucmakiola.calendula.ui.common.eventPaint
|
||||
@@ -157,12 +147,10 @@ import de.jeanlucmakiola.calendula.ui.common.LocalEventMove
|
||||
import de.jeanlucmakiola.calendula.ui.common.MoveRequest
|
||||
import de.jeanlucmakiola.calendula.ui.common.MoveTarget
|
||||
import de.jeanlucmakiola.calendula.ui.common.TimelineDragController
|
||||
import de.jeanlucmakiola.calendula.ui.common.ghostsDerived
|
||||
import de.jeanlucmakiola.calendula.ui.common.StripDrag
|
||||
import de.jeanlucmakiola.calendula.ui.common.StripDrop
|
||||
import de.jeanlucmakiola.calendula.ui.common.TimelineDragOverlay
|
||||
import de.jeanlucmakiola.calendula.ui.common.TimelineDrop
|
||||
import de.jeanlucmakiola.calendula.ui.common.clipOffsetMinutes
|
||||
import de.jeanlucmakiola.calendula.ui.common.continuesAfter
|
||||
import de.jeanlucmakiola.calendula.ui.common.continuesBefore
|
||||
import de.jeanlucmakiola.calendula.ui.common.ChipCuts
|
||||
import de.jeanlucmakiola.calendula.ui.common.timedBlockCuts
|
||||
@@ -197,10 +185,8 @@ import de.jeanlucmakiola.floret.locale.currentLocale
|
||||
import de.jeanlucmakiola.calendula.ui.common.LocalUse24HourFormat
|
||||
import de.jeanlucmakiola.calendula.ui.common.LocalShowHourGrid
|
||||
import de.jeanlucmakiola.calendula.ui.common.LocalTimelineZoom
|
||||
import de.jeanlucmakiola.calendula.ui.common.renderedSpan
|
||||
import de.jeanlucmakiola.calendula.ui.common.MIN_EVENT_FRACTION
|
||||
import de.jeanlucmakiola.calendula.ui.common.hourHeight
|
||||
import de.jeanlucmakiola.calendula.ui.common.dayFitHeight
|
||||
import de.jeanlucmakiola.calendula.ui.common.FabClearance
|
||||
import de.jeanlucmakiola.calendula.ui.common.rememberTimelinePinchZoom
|
||||
import de.jeanlucmakiola.calendula.ui.common.formatMinuteOfDay
|
||||
import de.jeanlucmakiola.calendula.ui.common.GUTTER_CONTENT_START_INSET
|
||||
@@ -210,8 +196,8 @@ import de.jeanlucmakiola.calendula.ui.common.TIMELINE_CONTENT_END_INSET
|
||||
import de.jeanlucmakiola.calendula.ui.common.hourCellBlockInset
|
||||
import de.jeanlucmakiola.calendula.ui.common.hourGridCells
|
||||
import de.jeanlucmakiola.calendula.ui.common.tappedMinuteOfDay
|
||||
import de.jeanlucmakiola.floret.time.isoWeekNumber
|
||||
import kotlinx.coroutines.launch
|
||||
import kotlinx.datetime.DateTimeUnit
|
||||
import kotlinx.datetime.LocalDate
|
||||
import kotlinx.datetime.TimeZone
|
||||
import kotlinx.datetime.plus
|
||||
@@ -221,7 +207,6 @@ import kotlinx.datetime.toLocalDateTime
|
||||
import java.time.format.TextStyle as JavaTextStyle
|
||||
import java.util.Locale
|
||||
import kotlinx.datetime.yearMonth
|
||||
import de.jeanlucmakiola.calendula.ui.common.rememberRowWeekNumber
|
||||
|
||||
/** One lane of the all-day strip, sized to a trimmed bar line (#190). */
|
||||
private val ALL_DAY_ROW_HEIGHT = 20.dp
|
||||
@@ -311,6 +296,14 @@ internal enum class TimelineKind(
|
||||
// A run of days often straddles two weeks, so no single number fits it.
|
||||
MultiDay(showWeekNumber = false, todayText = R.string.week_today_action, headerBias = 0f),
|
||||
Day(showWeekNumber = false, todayText = R.string.day_today_action, headerBias = -1f),
|
||||
;
|
||||
|
||||
fun title(start: LocalDate, end: LocalDate, locale: Locale, currentYear: Int, abbreviated: Boolean): String =
|
||||
if (this == Day) {
|
||||
formatDayTitle(start, locale, currentYear, abbreviated)
|
||||
} else {
|
||||
formatWeekTitle(start, end, locale, currentYear, abbreviated)
|
||||
}
|
||||
}
|
||||
|
||||
internal val CalendarView.timelineKind: TimelineKind
|
||||
@@ -485,10 +478,9 @@ private fun PagedTimelineScreen(
|
||||
val jumpToToday = { jumpToDate(today) }
|
||||
|
||||
val locale = currentLocale()
|
||||
// The day view names the month too: its header already shows weekday and date (#501).
|
||||
val (title, shortTitle) = remember(weekStart, weekEnd, locale, today.year) {
|
||||
formatTimelineTitle(weekStart, weekEnd, locale, today.year, abbreviated = false) to
|
||||
formatTimelineTitle(weekStart, weekEnd, locale, today.year, abbreviated = true)
|
||||
val (title, shortTitle) = remember(titleKind, weekStart, weekEnd, locale, today.year) {
|
||||
titleKind.title(weekStart, weekEnd, locale, today.year, abbreviated = false) to
|
||||
titleKind.title(weekStart, weekEnd, locale, today.year, abbreviated = true)
|
||||
}
|
||||
PublishChrome(
|
||||
ScreenChrome(
|
||||
@@ -585,9 +577,7 @@ private fun WeekContent(
|
||||
eventId = drop.event.eventId,
|
||||
beginMillis = drop.event.start.toEpochMilliseconds(),
|
||||
endMillis = drop.event.end.toEpochMilliseconds(),
|
||||
isAllDay = drop.event.isAllDay,
|
||||
target = MoveTarget.Start(start),
|
||||
token = drop.token,
|
||||
),
|
||||
)
|
||||
}
|
||||
@@ -606,26 +596,7 @@ private fun WeekContent(
|
||||
eventId = drop.event.eventId,
|
||||
beginMillis = drop.event.start.toEpochMilliseconds(),
|
||||
endMillis = drop.event.end.toEpochMilliseconds(),
|
||||
isAllDay = drop.event.isAllDay,
|
||||
target = MoveTarget.Span(drop.start, drop.end),
|
||||
token = drop.token,
|
||||
),
|
||||
)
|
||||
}
|
||||
|
||||
// Off the all-day strip: sideways moves days, into the grid makes it timed.
|
||||
val onStripDrop: (StripDrop) -> Unit = { drop ->
|
||||
move?.move(
|
||||
MoveRequest(
|
||||
eventId = drop.event.eventId,
|
||||
beginMillis = drop.event.start.toEpochMilliseconds(),
|
||||
endMillis = drop.event.end.toEpochMilliseconds(),
|
||||
isAllDay = drop.event.isAllDay,
|
||||
target = when (drop) {
|
||||
is StripDrop.Days -> MoveTarget.ByDays(drop.days)
|
||||
is StripDrop.Timed -> MoveTarget.Span(drop.start, drop.end)
|
||||
},
|
||||
token = drop.token,
|
||||
),
|
||||
)
|
||||
}
|
||||
@@ -690,7 +661,6 @@ private fun WeekContent(
|
||||
onCreateAt = onCreateAt,
|
||||
onDrop = onDrop,
|
||||
onResize = onResize,
|
||||
onStripDrop = onStripDrop,
|
||||
)
|
||||
|
||||
Box(modifier = modifier) {
|
||||
@@ -766,11 +736,7 @@ private fun WeekPager(
|
||||
val loaded = pageState as? WeekUiState.Success
|
||||
// Until its days arrive a page shows their frame without events.
|
||||
val empty = remember(pageSpan, today) { emptySpan(pageSpan, today) }
|
||||
// A bar held over other days in the strip makes room there before it is dropped.
|
||||
val held = dragController.stripPreviews().takeIf { page == pagerState.currentPage }.orEmpty()
|
||||
val zone = LocalTimelineZone.current
|
||||
val shown = remember(loaded, held, zone) { loaded?.withStripPreview(held, zone) }
|
||||
val stripHeight = shown?.allDayStripHeight()
|
||||
val stripHeight = loaded?.allDayStripHeight()
|
||||
DisposableEffect(page, stripHeight) {
|
||||
if (stripHeight != null) stripHeights[page] = stripHeight
|
||||
onDispose { stripHeights.remove(page) }
|
||||
@@ -778,8 +744,8 @@ private fun WeekPager(
|
||||
ViewMorphPage(active = morphPageActive(page, pagerState.settledPage)) {
|
||||
WeekPage(
|
||||
// A cached page may predate midnight; today comes off the clock (#373).
|
||||
state = remember(shown, empty, today) {
|
||||
shown?.takeIf { it.today != today }?.copy(today = today) ?: shown ?: empty
|
||||
state = remember(loaded, empty, today) {
|
||||
loaded?.takeIf { it.today != today }?.copy(today = today) ?: loaded ?: empty
|
||||
},
|
||||
headerBias = kind.headerBias,
|
||||
allDayHeight = allDayHeight,
|
||||
@@ -791,43 +757,6 @@ private fun WeekPager(
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* [this] with the strip bars [held] sideways laid out at the days they are over,
|
||||
* so the bars there move aside live. Each bar keeps its own event, and with it
|
||||
* its key and the gesture on it; one moved off the page keeps a lane it is not
|
||||
* seen in.
|
||||
*/
|
||||
internal fun WeekUiState.Success.withStripPreview(held: List<StripDrag>, zone: TimeZone): WeekUiState.Success {
|
||||
val shifts = held.filter { !it.overGrid && it.dayShift != 0 }.associate { it.event.instanceId to it.dayShift }
|
||||
if (shifts.isEmpty()) return this
|
||||
val originals = allDaySpans.filter { it.event.instanceId in shifts }.associateBy { it.event.instanceId }
|
||||
if (originals.isEmpty()) return this
|
||||
val events = allDaySpans.map { span ->
|
||||
shifts[span.event.instanceId]?.let { span.event.shiftedDays(it, zone) } ?: span.event
|
||||
}
|
||||
val spans = layoutAllDay(events, days, zone).map { span ->
|
||||
originals[span.event.instanceId]?.let { span.copy(event = it.event) } ?: span
|
||||
}
|
||||
val laidOut = spans.mapTo(HashSet()) { it.event.instanceId }
|
||||
return copy(allDaySpans = spans + originals.values.filter { it.event.instanceId !in laidOut }.map { it.copy(lane = 0) })
|
||||
}
|
||||
|
||||
private fun EventInstance.shiftedDays(days: Int, zone: TimeZone): EventInstance {
|
||||
val dates = dateZone(zone)
|
||||
return copy(start = start.plus(days, DateTimeUnit.DAY, dates), end = end.plus(days, DateTimeUnit.DAY, dates))
|
||||
}
|
||||
|
||||
/** Whether these bars draw the strip drop [drop] at the days it was dropped on. */
|
||||
private fun List<PlacedBar>.drawStripDrop(drop: StripDrag, zone: TimeZone): Boolean {
|
||||
val target = drop.event.spanFirstDay(zone).plus(drop.dayShift, DateTimeUnit.DAY)
|
||||
return any { bar ->
|
||||
bar.event.instanceId != drop.event.instanceId &&
|
||||
(bar.event.eventId == drop.event.eventId ||
|
||||
(drop.event.title.isNotBlank() && bar.event.title == drop.event.title)) &&
|
||||
bar.event.spanFirstDay(zone) == target
|
||||
}
|
||||
}
|
||||
|
||||
/** A page with no events yet, for one whose days are still loading. */
|
||||
private fun emptySpan(span: DaySpan, today: LocalDate): WeekUiState.Success {
|
||||
val days = (0 until span.count).map { span.start.plus(it, kotlinx.datetime.DateTimeUnit.DAY) }
|
||||
@@ -963,9 +892,8 @@ private fun WeekFrame(
|
||||
),
|
||||
) {
|
||||
val zoom = LocalTimelineZoom.current
|
||||
val fitHeight = dayFitHeight(
|
||||
if (animatedAllDayHeight == null) maxHeight + allDayHeight else maxHeight,
|
||||
)
|
||||
val fitHeight = if (animatedAllDayHeight == null) maxHeight + allDayHeight
|
||||
else maxHeight
|
||||
val hourHeight = zoom.scale.hourHeight(fitHeight)
|
||||
HourGutter(
|
||||
scrollState = actions.scrollState,
|
||||
@@ -1064,7 +992,7 @@ private fun TimelinePageContent(
|
||||
LocalChipGround provides MaterialTheme.colorScheme.surface,
|
||||
) {
|
||||
AllDayStrip(geometry = geometry, bars = bars, height = allDayHeight,
|
||||
animatedHeight = animatedAllDayHeight, actions = actions, active = active)
|
||||
animatedHeight = animatedAllDayHeight, onEventClick = actions.onEventClick)
|
||||
}
|
||||
}
|
||||
Spacer(Modifier.height(TIMELINE_TOP_GAP))
|
||||
@@ -1154,7 +1082,7 @@ private fun WeekDayHeader(
|
||||
*/
|
||||
@Composable
|
||||
private fun WeekNumberCell(weekStart: LocalDate, showBadge: Boolean, modifier: Modifier = Modifier) {
|
||||
val weekNumber = rememberRowWeekNumber(weekStart)
|
||||
val weekNumber = remember(weekStart) { weekStart.toJavaLocalDate().isoWeekNumber() }
|
||||
Column(
|
||||
modifier = modifier
|
||||
.fillMaxWidth()
|
||||
@@ -1199,23 +1127,9 @@ private fun AllDayStrip(
|
||||
bars: List<PlacedBar>,
|
||||
height: Dp,
|
||||
animatedHeight: (() -> Dp)? = null,
|
||||
actions: TimelineActions,
|
||||
active: Boolean,
|
||||
onEventClick: (EventInstance) -> Unit,
|
||||
) {
|
||||
val dark = LocalFloretDarkTheme.current
|
||||
val zone = LocalTimelineZone.current
|
||||
val dragController = actions.dragController
|
||||
// Only the page the finger is on draws the drag; the controller is shared.
|
||||
val held = (dragController.stripDrag ?: dragController.stripSettling)?.takeIf { active }
|
||||
val sideways = held?.takeIf { !it.overGrid }
|
||||
val lifted = dragController.liftedInstanceId?.takeIf { active && dragController.stripDrag?.overGrid != false }
|
||||
val settling = dragController.stripSettling?.takeIf { active }
|
||||
val heldStrips = dragController.heldStrips.takeIf { active }.orEmpty()
|
||||
// Seated once the re-read draws the event at the days it was dropped on.
|
||||
LaunchedEffect(settling, heldStrips, bars) {
|
||||
if (settling != null && bars.drawStripDrop(settling, zone)) dragController.seatStrip()
|
||||
heldStrips.forEach { if (!it.seated && bars.drawStripDrop(it.drag, zone)) dragController.seatHeldStrip(it.token) }
|
||||
}
|
||||
|
||||
Row(
|
||||
modifier = Modifier
|
||||
@@ -1236,20 +1150,12 @@ private fun AllDayStrip(
|
||||
content = {
|
||||
bars.forEach { bar ->
|
||||
key(bar.event.eventId, bar.event.start) {
|
||||
val moving = sideways?.event?.instanceId == bar.event.instanceId
|
||||
val lane = animatedStripLane(bar.toLane)
|
||||
AllDayBar(
|
||||
event = bar.event,
|
||||
lastDay = bar.toRange.endInclusive,
|
||||
dark = dark,
|
||||
dragController = dragController,
|
||||
lifted = moving,
|
||||
ghosted = lifted == bar.event.instanceId,
|
||||
onClick = { actions.onEventClick(bar.event) },
|
||||
onDrop = actions.onStripDrop,
|
||||
onClick = { onEventClick(bar.event) },
|
||||
modifier = Modifier
|
||||
.then(if (moving) Modifier.zIndex(1f) else Modifier)
|
||||
.then(StripLane(lane))
|
||||
.morphEvent(ViewMorphKey.event(bar.event, bar.keyDate))
|
||||
.padding(horizontal = 1.dp, vertical = 1.dp),
|
||||
)
|
||||
@@ -1266,19 +1172,10 @@ private fun AllDayStrip(
|
||||
val progress = geometry.progress()
|
||||
val placed = measurables.mapIndexed { i, measurable ->
|
||||
val bar = bars[i]
|
||||
val shift = sideways?.takeIf { it.event.instanceId == bar.event.instanceId }?.dayShift ?: 0
|
||||
val extent = if (shift == 0) {
|
||||
geometry.extent(bar.fromRange, bar.toRange, width, 0f)
|
||||
} else {
|
||||
// The whole event, not the part this page shows: it may come in from off screen.
|
||||
val moved = bar.event.spanFirstDay(zone)..bar.event.spanLastDay(zone)
|
||||
geometry.extent(moved.shiftedBy(shift), moved.shiftedBy(shift), width, 0f)
|
||||
}
|
||||
val extent = geometry.extent(bar.fromRange, bar.toRange, width, 0f)
|
||||
val left = extent.left.roundToInt()
|
||||
val barWidth = (extent.right.roundToInt() - left).coerceAtLeast(0)
|
||||
// Standing still a bar tweens to a new lane, as bars make room for a dragged one.
|
||||
val lane = (measurable.parentData as? StripLane)?.lane?.takeIf { bar.fromLane == bar.toLane }
|
||||
val y = ((lane?.value ?: lerp(bar.fromLane.toFloat(), bar.toLane.toFloat(), progress)) * rowPx).roundToInt()
|
||||
val y = (lerp(bar.fromLane.toFloat(), bar.toLane.toFloat(), progress) * rowPx).roundToInt()
|
||||
Triple(measurable.measure(Constraints.fixed(barWidth, rowPx.roundToInt())), left, y)
|
||||
}
|
||||
layout(constraints.maxWidth, constraints.maxHeight) {
|
||||
@@ -1288,31 +1185,12 @@ private fun AllDayStrip(
|
||||
}
|
||||
}
|
||||
|
||||
private data class StripLane(val lane: State<Float>) : ParentDataModifier {
|
||||
override fun Density.modifyParentData(parentData: Any?): Any = this@StripLane
|
||||
}
|
||||
|
||||
@OptIn(ExperimentalMaterial3ExpressiveApi::class)
|
||||
@Composable
|
||||
private fun animatedStripLane(lane: Int): State<Float> {
|
||||
val spec: FiniteAnimationSpec<Float> =
|
||||
if (rememberReduceMotion()) snap() else MaterialTheme.motionScheme.fastSpatialSpec()
|
||||
return animateFloatAsState(lane.toFloat(), spec, label = "strip-lane")
|
||||
}
|
||||
|
||||
private fun ClosedRange<LocalDate>.shiftedBy(days: Int): ClosedRange<LocalDate> =
|
||||
start.plus(days, DateTimeUnit.DAY)..endInclusive.plus(days, DateTimeUnit.DAY)
|
||||
|
||||
@Composable
|
||||
private fun AllDayBar(
|
||||
event: EventInstance,
|
||||
lastDay: LocalDate,
|
||||
dark: Boolean,
|
||||
dragController: TimelineDragController,
|
||||
lifted: Boolean,
|
||||
ghosted: Boolean,
|
||||
onClick: () -> Unit,
|
||||
onDrop: (StripDrop) -> Unit,
|
||||
modifier: Modifier = Modifier,
|
||||
) {
|
||||
val title = event.title.ifBlank { stringResource(R.string.event_untitled) }
|
||||
@@ -1320,29 +1198,8 @@ private fun AllDayBar(
|
||||
// A bar is one piece, so it dims once the last day it covers here has passed.
|
||||
val dimmed = dimCutoff != null && event.isPastOn(lastDay, dimCutoff)
|
||||
val paint = eventPaint(event, dark)
|
||||
val zone = LocalTimelineZone.current
|
||||
val draggable = eventDragAllowed(event)
|
||||
// Long press lifts the bar: sideways moves its days, down into the grid makes it timed.
|
||||
val dragModifier = rememberEventDragSource(
|
||||
enabled = draggable,
|
||||
key = event.instanceId,
|
||||
onPickUp = { pointer, _, _ ->
|
||||
dragController.beginStrip(event, zone, pointer)
|
||||
if (dragController.stripDrag != null) PickUp.Drag else PickUp.None
|
||||
},
|
||||
onMove = dragController::move,
|
||||
onDrop = { dragController.finishStrip()?.let(onDrop) },
|
||||
onCancel = dragController::cancel,
|
||||
onRelease = dragController::cancel,
|
||||
)
|
||||
// Ghosted while it hangs over the grid as a timed block, and until that drop lands.
|
||||
val ghost = ghostAlpha(ghosted)
|
||||
val raise = selectionLift(lifted)
|
||||
Box(
|
||||
modifier = (if (dimmed) modifier.alpha(EventDimAlpha) else modifier)
|
||||
.alpha(ghost)
|
||||
.selectionLift(raise, EventChipShape)
|
||||
.then(dragModifier)
|
||||
.eventSurface(paint, EventChipShape)
|
||||
.clickable(onClick = onClick)
|
||||
.padding(horizontal = 6.dp, vertical = 2.dp)
|
||||
@@ -1397,9 +1254,7 @@ private fun Timeline(
|
||||
else Modifier.stableMorphViewport(animatedAllDayHeight, fullViewportHeight),
|
||||
),
|
||||
) {
|
||||
val fitHeight = dayFitHeight(
|
||||
if (animatedAllDayHeight == null) maxHeight + allDayHeight else maxHeight,
|
||||
)
|
||||
val fitHeight = if (animatedAllDayHeight == null) maxHeight + allDayHeight else maxHeight
|
||||
val hourHeight = zoom.scale.hourHeight(fitHeight)
|
||||
val totalHeight = hourHeight * 24
|
||||
// The pinch sits above the scroll viewport: it has to outrank the
|
||||
@@ -1432,11 +1287,9 @@ private fun Timeline(
|
||||
.fillMaxSize()
|
||||
.then(pinch)
|
||||
.padding(end = TIMELINE_CONTENT_END_INSET)
|
||||
.clip(RoundedCornerShape(TIMELINE_CORNER))
|
||||
.clip(RoundedCornerShape(16.dp))
|
||||
.verticalScroll(scrollState)
|
||||
.onGloballyPositioned { if (active) dragController.geometry.viewport = it }
|
||||
// Past midnight, outside the columns: nothing there takes a tap or a drop.
|
||||
.padding(bottom = FabClearance),
|
||||
.onGloballyPositioned { if (active) dragController.geometry.viewport = it },
|
||||
) {
|
||||
TimelineColumns(
|
||||
geometry = geometry,
|
||||
@@ -1472,7 +1325,6 @@ private fun Timeline(
|
||||
visibleTop = visibleTop,
|
||||
viewportHeight = visibleViewport,
|
||||
actions = actions,
|
||||
shape = columnShape(day == geometry.dates.first(), day == geometry.dates.last()),
|
||||
modifier = Modifier.fillMaxHeight(),
|
||||
)
|
||||
}
|
||||
@@ -1480,19 +1332,6 @@ private fun Timeline(
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* The outer columns round their bottom corner at midnight: the room left below
|
||||
* for the buttons means the rounded window no longer does it there.
|
||||
*/
|
||||
private fun columnShape(first: Boolean, last: Boolean): Shape =
|
||||
if (!first && !last) RectangleShape
|
||||
else RoundedCornerShape(
|
||||
bottomStart = if (first) TIMELINE_CORNER else 0.dp,
|
||||
bottomEnd = if (last) TIMELINE_CORNER else 0.dp,
|
||||
)
|
||||
|
||||
private val TIMELINE_CORNER = 16.dp
|
||||
|
||||
@Composable
|
||||
private fun DayColumnCard(
|
||||
blocks: List<TimedBlock>,
|
||||
@@ -1504,7 +1343,6 @@ private fun DayColumnCard(
|
||||
visibleTop: () -> Float,
|
||||
viewportHeight: () -> Float,
|
||||
actions: TimelineActions,
|
||||
shape: Shape = RectangleShape,
|
||||
modifier: Modifier = Modifier,
|
||||
) {
|
||||
val scrollState = actions.scrollState
|
||||
@@ -1535,8 +1373,8 @@ private fun DayColumnCard(
|
||||
val draftSurface = rememberDraftSurface(date, edges, hourPx, dragController, actions.onDrop)
|
||||
Card(
|
||||
// Plain rectangular columns — the soft corners come from the outer
|
||||
// rounded scroll viewport, apart from the outer ones' bottoms ([columnShape]).
|
||||
shape = shape,
|
||||
// rounded scroll viewport, so inner rounding would look odd at the edges.
|
||||
shape = RectangleShape,
|
||||
colors = CardDefaults.cardColors(
|
||||
// With the grid on, the container colour moves onto the hour cells
|
||||
// and the column behind them recedes to surface, so the gap between
|
||||
@@ -1576,6 +1414,7 @@ private fun DayColumnCard(
|
||||
// block or handle on top can claim the press first.
|
||||
.then(draftSurface),
|
||||
) {
|
||||
val minEventHeight = hourHeight * MIN_EVENT_FRACTION
|
||||
// Keyed by event, so a block that changes time or lane is the *same*
|
||||
// composable afterwards and tweens there. The ordinal disambiguates
|
||||
// a column holding two occurrences of one series.
|
||||
@@ -1583,24 +1422,24 @@ private fun DayColumnCard(
|
||||
shown.forEach { block ->
|
||||
val ordinal = ordinals.merge(block.event.eventId, 1, Int::plus)!! - 1
|
||||
key(block.event.eventId, ordinal) {
|
||||
// Where this block is cut at midnight, which decides both
|
||||
// its shape and the half-gap it gives up to the hour cells.
|
||||
val cuts = remember(block, date, zone) {
|
||||
timedBlockCuts(
|
||||
block.continuesBefore(date, zone),
|
||||
block.continuesAfter,
|
||||
)
|
||||
}
|
||||
val span = remember(block) { block.renderedSpan() }
|
||||
val top = hourHeight * (span.topMin / 60f)
|
||||
val height = hourHeight * ((span.bottomMin - span.topMin) / 60f)
|
||||
val top = hourHeight * (block.startMin / 60f)
|
||||
val rawHeight = hourHeight * ((block.endMin - block.startMin) / 60f)
|
||||
val height = if (rawHeight < minEventHeight) minEventHeight else rawHeight
|
||||
val place = animatedBlockPlacement(
|
||||
xFraction = block.lane.toFloat() / block.laneCount,
|
||||
widthFraction = 1f / block.laneCount,
|
||||
y = top,
|
||||
height = height,
|
||||
landing = dragController.ghostsDerived(block),
|
||||
landing = dragController.ghosts(block),
|
||||
)
|
||||
// Where this block is cut at midnight, which decides both
|
||||
// its shape and the half-gap it gives up to the hour cells.
|
||||
val cuts = remember(block, date, zone) {
|
||||
timedBlockCuts(
|
||||
block.continuesBefore(date, zone),
|
||||
block.continuesAfter(date, zone),
|
||||
)
|
||||
}
|
||||
val topInset = hourCellBlockInset(showHourGrid, cuts.top)
|
||||
val bottomInset = hourCellBlockInset(showHourGrid, cuts.bottom)
|
||||
val blockHeight = (place.height - topInset - bottomInset)
|
||||
@@ -1767,7 +1606,7 @@ private fun EventBlock(
|
||||
onCancel = dragController::cancel,
|
||||
onRelease = { dragController.select(block.event, fromLift = draggable) },
|
||||
)
|
||||
val lifted = draggable && dragController.ghostsDerived(block)
|
||||
val lifted = draggable && dragController.ghosts(block)
|
||||
// Released in place, the block takes over the copy's lift without a dip.
|
||||
val takesOverLift = selected && dragController.selection?.fromLift == true
|
||||
val ghostFade = ghostAlpha(lifted)
|
||||
@@ -1936,7 +1775,7 @@ private fun rememberDraftSurface(
|
||||
block = block,
|
||||
zone = zone,
|
||||
pointerInRoot = pointer,
|
||||
blockInRoot = node + Offset(0f, block.renderedSpan().topMin / 60f * hour),
|
||||
blockInRoot = node + Offset(0f, startMin / 60f * hour),
|
||||
)
|
||||
true
|
||||
},
|
||||
@@ -1984,10 +1823,8 @@ private fun WeekLoading(dayCount: Int) {
|
||||
BoxWithConstraints(modifier = Modifier.fillMaxSize()) {
|
||||
// Same scale resolution as the loaded timeline, so the skeleton's
|
||||
// columns don't resize the moment the real week arrives.
|
||||
val fitHeight = dayFitHeight(
|
||||
maxHeight + SKELETON_HEADER_HEIGHT + SKELETON_HEADER_PADDING * 2 -
|
||||
headerHeight - TIMELINE_TOP_GAP,
|
||||
)
|
||||
val fitHeight = maxHeight + SKELETON_HEADER_HEIGHT + SKELETON_HEADER_PADDING * 2 -
|
||||
headerHeight - TIMELINE_TOP_GAP
|
||||
val hourHeight = scale.hourHeight(fitHeight)
|
||||
val totalHeight = hourHeight * 24
|
||||
// The skeleton wears the loaded columns' own ground, so the arrival
|
||||
@@ -2000,8 +1837,7 @@ private fun WeekLoading(dayCount: Int) {
|
||||
modifier = Modifier
|
||||
.fillMaxSize()
|
||||
.padding(end = TIMELINE_CONTENT_END_INSET)
|
||||
.verticalScroll(scrollState)
|
||||
.padding(bottom = FabClearance),
|
||||
.verticalScroll(scrollState),
|
||||
) {
|
||||
Spacer(Modifier.width(GUTTER_WIDTH))
|
||||
repeat(dayCount) {
|
||||
@@ -2027,7 +1863,7 @@ private fun minToHm(min: Int, is24Hour: Boolean, locale: java.util.Locale): Stri
|
||||
formatMinuteOfDay(min, is24Hour, locale)
|
||||
|
||||
/**
|
||||
* Every timeline's title, the day view's included: just the month [weekStart] falls in.
|
||||
* The week's title: just the month [weekStart] falls in.
|
||||
*
|
||||
* The day numbers are already in the column headers directly below, so spelling
|
||||
* out "13.–19. Jul" restates them in the widest string in the bar. Naming the
|
||||
@@ -2042,7 +1878,7 @@ private fun minToHm(min: Int, is24Hour: Boolean, locale: java.util.Locale): Stri
|
||||
* "December" with no year would be actively misleading while the reader is
|
||||
* looking straight at January dates.
|
||||
*/
|
||||
private fun formatTimelineTitle(
|
||||
private fun formatWeekTitle(
|
||||
weekStart: LocalDate,
|
||||
weekEnd: LocalDate,
|
||||
locale: Locale,
|
||||
@@ -2057,3 +1893,17 @@ private fun formatTimelineTitle(
|
||||
forceYear = weekEnd.year != weekStart.year,
|
||||
)
|
||||
}
|
||||
|
||||
/** The day's title: its weekday and date, abbreviated to the date alone when short of room. */
|
||||
private fun formatDayTitle(
|
||||
date: LocalDate,
|
||||
locale: Locale,
|
||||
currentYear: Int,
|
||||
abbreviated: Boolean = false,
|
||||
): String =
|
||||
formatCalendarTitle(
|
||||
date = date.toJavaLocalDate(),
|
||||
locale = locale,
|
||||
currentYear = currentYear,
|
||||
skeleton = if (abbreviated) "dMMM" else "EEEdMMM",
|
||||
)
|
||||
@@ -15,8 +15,6 @@ import kotlinx.datetime.LocalDate
|
||||
* minimum tap-target height)
|
||||
* @param lane 0-based column within [laneCount]
|
||||
* @param laneCount number of columns the event's overlap-cluster needs
|
||||
* @param continuesAfter whether the event runs past this day's midnight, so the
|
||||
* block is cut there
|
||||
*/
|
||||
data class TimedBlock(
|
||||
val event: EventInstance,
|
||||
@@ -24,7 +22,6 @@ data class TimedBlock(
|
||||
val endMin: Int,
|
||||
val lane: Int,
|
||||
val laneCount: Int,
|
||||
val continuesAfter: Boolean = false,
|
||||
)
|
||||
|
||||
/**
|
||||
|
||||
@@ -1,7 +1,6 @@
|
||||
package de.jeanlucmakiola.calendula.ui.week
|
||||
|
||||
import de.jeanlucmakiola.calendula.ui.common.dayRange
|
||||
import de.jeanlucmakiola.calendula.ui.common.renderedSpan
|
||||
import androidx.lifecycle.ViewModel
|
||||
import androidx.lifecycle.viewModelScope
|
||||
import dagger.hilt.android.lifecycle.HiltViewModel
|
||||
@@ -14,9 +13,7 @@ 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.coversWholeDays
|
||||
import de.jeanlucmakiola.calendula.domain.displayPriority
|
||||
import de.jeanlucmakiola.calendula.domain.displayStart
|
||||
import de.jeanlucmakiola.calendula.domain.FailureReason
|
||||
import de.jeanlucmakiola.calendula.domain.calendarListFailure
|
||||
import de.jeanlucmakiola.calendula.ui.common.PageStateCache
|
||||
@@ -209,7 +206,8 @@ abstract class PagedTimelineViewModel(
|
||||
): WeekUiState {
|
||||
calendarListFailure(calendars)?.let { return WeekUiState.Failure(it) }
|
||||
val days = (0 until span.count).map { span.start.plus(it, DateTimeUnit.DAY) }
|
||||
val (allDay, timed) = instances.splitWholeDays(zone)
|
||||
val allDay = instances.filter { it.isAllDay }
|
||||
val timed = instances.filterNot { it.isAllDay }
|
||||
return WeekUiState.Success(
|
||||
weekStart = span.start,
|
||||
today = today,
|
||||
@@ -294,21 +292,20 @@ internal fun layoutAllDay(
|
||||
days: List<LocalDate>,
|
||||
zone: TimeZone,
|
||||
): List<AllDaySpan> {
|
||||
data class Raw(val event: EventInstance, val startCol: Int, val endCol: Int, val priority: Int)
|
||||
data class Raw(val event: EventInstance, val startCol: Int, val endCol: Int)
|
||||
|
||||
val raw = events
|
||||
.mapNotNull { ev ->
|
||||
val covered = days.indices.filter { ev.coversDay(days[it], zone) }
|
||||
if (covered.isEmpty()) null else Raw(ev, covered.first(), covered.last(), ev.displayPriority(zone))
|
||||
if (covered.isEmpty()) null else Raw(ev, covered.first(), covered.last())
|
||||
}
|
||||
// Declined bars are packed after every other one, so on any day they
|
||||
// cover they land in a lane below it (#230).
|
||||
.sortedWith(
|
||||
compareBy<Raw> { it.priority }
|
||||
compareBy<Raw> { it.event.displayPriority(zone) }
|
||||
.thenBy { it.startCol }
|
||||
.thenBy { it.endCol }
|
||||
.thenBy { it.event.displayStart(zone) }
|
||||
.thenBy { it.event.title }
|
||||
.thenBy { it.event.start }
|
||||
.thenBy { it.event.instanceId },
|
||||
)
|
||||
|
||||
@@ -429,21 +426,12 @@ internal fun EventInstance.spansMultipleDays(zone: TimeZone): Boolean {
|
||||
return coversDay(secondDay, zone)
|
||||
}
|
||||
|
||||
/**
|
||||
* Split events into those for the all-day strip and those for the time grid:
|
||||
* all-day events and timed ones from midnight to midnight go to the strip (#296).
|
||||
*/
|
||||
internal fun List<EventInstance>.splitWholeDays(zone: TimeZone): Pair<List<EventInstance>, List<EventInstance>> =
|
||||
partition { it.coversWholeDays(zone) }
|
||||
|
||||
/**
|
||||
* Clip [events] to a single [day] and assign lanes so overlapping events render
|
||||
* side-by-side. Lane count is computed per overlap-cluster (a maximal run of
|
||||
* chained-overlapping events), matching the common phone week-view behaviour.
|
||||
* Overlap is judged on each block's [renderedSpan], so a short block's floor
|
||||
* (lifted off midnight, #483) never hides another block.
|
||||
*
|
||||
* Takes the timed half of [splitWholeDays]; the rest lives in the all-day strip.
|
||||
* All-day events are ignored here — they live in the all-day strip.
|
||||
*/
|
||||
internal fun layoutDay(
|
||||
events: List<EventInstance>,
|
||||
@@ -453,53 +441,55 @@ internal fun layoutDay(
|
||||
val dayStart = day.atStartOfDayIn(zone)
|
||||
val dayEnd = day.plus(1, DateTimeUnit.DAY).atStartOfDayIn(zone)
|
||||
|
||||
data class Raw(val event: EventInstance, val startMin: Int, val endMin: Int)
|
||||
|
||||
val raw = events.asSequence()
|
||||
.filterNot { it.isAllDay }
|
||||
.mapNotNull { ev ->
|
||||
if (ev.start == ev.end) {
|
||||
// Instant event: keep only if the point falls inside this day.
|
||||
if (ev.start < dayStart || ev.start >= dayEnd) return@mapNotNull null
|
||||
val m = wallClockMinutes(ev.start, day, zone)
|
||||
TimedBlock(ev, m, m, lane = 0, laneCount = 1)
|
||||
Raw(ev, m, m)
|
||||
} else {
|
||||
val s = maxOf(ev.start, dayStart)
|
||||
val e = minOf(ev.end, dayEnd)
|
||||
if (e <= s) return@mapNotNull null
|
||||
val startMin = wallClockMinutes(s, day, zone)
|
||||
val endMin = wallClockEndMinutes(startMin, s, e, day, zone).coerceAtMost(MINUTES_PER_DAY)
|
||||
TimedBlock(ev, startMin, endMin, lane = 0, laneCount = 1, continuesAfter = ev.end > dayEnd)
|
||||
Raw(ev, startMin, endMin)
|
||||
}
|
||||
}
|
||||
.map { it to it.renderedSpan() }
|
||||
.sortedWith(compareBy({ it.second.topMin }, { it.second.bottomMin }))
|
||||
.sortedWith(compareBy({ it.startMin }, { it.endMin }))
|
||||
.toList()
|
||||
|
||||
val result = ArrayList<TimedBlock>(raw.size)
|
||||
var i = 0
|
||||
while (i < raw.size) {
|
||||
// Grow a cluster of chained-overlapping events.
|
||||
var clusterEnd = raw[i].second.bottomMin
|
||||
var clusterEnd = raw[i].endMin
|
||||
var j = i + 1
|
||||
while (j < raw.size && raw[j].second.topMin < clusterEnd) {
|
||||
clusterEnd = maxOf(clusterEnd, raw[j].second.bottomMin)
|
||||
while (j < raw.size && raw[j].startMin < clusterEnd) {
|
||||
clusterEnd = maxOf(clusterEnd, raw[j].endMin)
|
||||
j++
|
||||
}
|
||||
val cluster = raw.subList(i, j)
|
||||
// Greedy first-fit column assignment (= max overlap depth in the cluster).
|
||||
val laneEnd = ArrayList<Float>()
|
||||
val laneEnd = ArrayList<Int>()
|
||||
val lanes = IntArray(cluster.size)
|
||||
cluster.forEachIndexed { k, (_, span) ->
|
||||
var placed = laneEnd.indexOfFirst { it <= span.topMin }
|
||||
cluster.forEachIndexed { k, r ->
|
||||
var placed = laneEnd.indexOfFirst { it <= r.startMin }
|
||||
if (placed == -1) {
|
||||
laneEnd.add(span.bottomMin)
|
||||
laneEnd.add(r.endMin)
|
||||
placed = laneEnd.size - 1
|
||||
} else {
|
||||
laneEnd[placed] = span.bottomMin
|
||||
laneEnd[placed] = r.endMin
|
||||
}
|
||||
lanes[k] = placed
|
||||
}
|
||||
val laneCount = laneEnd.size
|
||||
cluster.forEachIndexed { k, (block, _) ->
|
||||
result.add(block.copy(lane = lanes[k], laneCount = laneCount))
|
||||
cluster.forEachIndexed { k, r ->
|
||||
result.add(TimedBlock(r.event, r.startMin, r.endMin, lanes[k], laneCount))
|
||||
}
|
||||
i = j
|
||||
}
|
||||
|
||||
@@ -61,7 +61,6 @@ internal fun WeekViewPreview(
|
||||
onCreateAt = { _, _ -> },
|
||||
onDrop = {},
|
||||
onResize = {},
|
||||
onStripDrop = {},
|
||||
),
|
||||
)
|
||||
}
|
||||
@@ -76,12 +75,12 @@ private fun sampleWeekState(
|
||||
): WeekUiState.Success {
|
||||
val start = if (dayCount == 7) today.startOfWeek(weekStart) else today
|
||||
val days = (0 until dayCount).map { start.plus(it, DateTimeUnit.DAY) }
|
||||
val (allDay, timed) = sampleTimelineEvents(days, today, zone).splitWholeDays(zone)
|
||||
val events = sampleTimelineEvents(days, today, zone)
|
||||
return WeekUiState.Success(
|
||||
weekStart = start,
|
||||
today = today,
|
||||
days = days,
|
||||
allDaySpans = layoutAllDay(allDay, days, zone),
|
||||
timedByDay = days.associateWith { layoutDay(timed, it, zone) },
|
||||
allDaySpans = layoutAllDay(events.filter { it.isAllDay }, days, zone),
|
||||
timedByDay = days.associateWith { layoutDay(events, it, zone) },
|
||||
)
|
||||
}
|
||||
@@ -4,7 +4,6 @@ import android.content.Context
|
||||
import androidx.datastore.preferences.core.MutablePreferences
|
||||
import androidx.datastore.preferences.core.Preferences
|
||||
import androidx.datastore.preferences.core.booleanPreferencesKey
|
||||
import androidx.datastore.preferences.core.floatPreferencesKey
|
||||
import androidx.datastore.preferences.core.stringPreferencesKey
|
||||
import androidx.datastore.preferences.core.stringSetPreferencesKey
|
||||
import androidx.glance.GlanceId
|
||||
@@ -27,22 +26,14 @@ enum class WidgetTheme { FOLLOW_APP, LIGHT, DARK }
|
||||
data class WidgetAppearance(
|
||||
val background: WidgetBackground = WidgetBackground.TINTED,
|
||||
val theme: WidgetTheme = WidgetTheme.FOLLOW_APP,
|
||||
/** How opaque a Solid or Tinted fill is (#489). */
|
||||
val opacity: Float = 1f,
|
||||
)
|
||||
|
||||
/** The agenda widget's look: the 2.24 day cards, or v2.23's plain day headers and stripes (#489). */
|
||||
enum class AgendaWidgetStyle { CARDS, CLASSIC }
|
||||
|
||||
/** What the agenda widget lists, per placed widget. */
|
||||
data class AgendaWidgetOptions(
|
||||
val range: AgendaRange,
|
||||
val textSize: WidgetSize,
|
||||
val showToday: Boolean,
|
||||
val pastDisplay: PastEventDisplay,
|
||||
val style: AgendaWidgetStyle = AgendaWidgetStyle.CARDS,
|
||||
/** Classic style only: draw the text in the opposite theme's colours, for a faded fill over the wallpaper. */
|
||||
val invertText: Boolean = false,
|
||||
)
|
||||
|
||||
internal fun WidgetTheme.resolve(app: ThemeMode): WidgetThemeMode = when (this) {
|
||||
@@ -57,9 +48,6 @@ internal fun WidgetTheme.resolve(app: ThemeMode): WidgetThemeMode = when (this)
|
||||
|
||||
private val BackgroundKey = stringPreferencesKey("cfg_background")
|
||||
private val ThemeKey = stringPreferencesKey("cfg_theme")
|
||||
private val OpacityKey = floatPreferencesKey("cfg_opacity")
|
||||
private val AgendaStyleKey = stringPreferencesKey("cfg_agenda_style")
|
||||
private val InvertTextKey = booleanPreferencesKey("cfg_invert_text")
|
||||
private val AgendaRangeKey = stringPreferencesKey("cfg_agenda_range")
|
||||
private val TextSizeKey = stringPreferencesKey("cfg_text_size")
|
||||
private val ShowTodayKey = booleanPreferencesKey("cfg_show_today")
|
||||
@@ -70,7 +58,6 @@ internal val Preferences.widgetAppearance: WidgetAppearance
|
||||
get() = WidgetAppearance(
|
||||
background = this[BackgroundKey].toEnum(WidgetBackground.TINTED),
|
||||
theme = this[ThemeKey].toEnum(WidgetTheme.FOLLOW_APP),
|
||||
opacity = this[OpacityKey] ?: 1f,
|
||||
)
|
||||
|
||||
/**
|
||||
@@ -83,8 +70,6 @@ internal fun Preferences.agendaWidgetOptions(defaults: AgendaWidgetOptions) = Ag
|
||||
textSize = this[TextSizeKey].toEnum(defaults.textSize),
|
||||
showToday = this[ShowTodayKey] ?: defaults.showToday,
|
||||
pastDisplay = this[PastDisplayKey].toEnum(defaults.pastDisplay),
|
||||
style = this[AgendaStyleKey].toEnum(defaults.style),
|
||||
invertText = this[InvertTextKey] ?: defaults.invertText,
|
||||
)
|
||||
|
||||
/** Whether this widget has agenda options of its own, rather than following the app's. */
|
||||
@@ -93,7 +78,6 @@ internal val Preferences.hasAgendaOptions: Boolean get() = this[AgendaRangeKey]
|
||||
internal fun MutablePreferences.putAppearance(appearance: WidgetAppearance) {
|
||||
this[BackgroundKey] = appearance.background.name
|
||||
this[ThemeKey] = appearance.theme.name
|
||||
this[OpacityKey] = appearance.opacity
|
||||
}
|
||||
|
||||
internal fun MutablePreferences.putAgendaOptions(options: AgendaWidgetOptions) {
|
||||
@@ -101,8 +85,6 @@ internal fun MutablePreferences.putAgendaOptions(options: AgendaWidgetOptions) {
|
||||
this[TextSizeKey] = options.textSize.name
|
||||
this[ShowTodayKey] = options.showToday
|
||||
this[PastDisplayKey] = options.pastDisplay.name
|
||||
this[AgendaStyleKey] = options.style.name
|
||||
this[InvertTextKey] = options.invertText
|
||||
}
|
||||
|
||||
/**
|
||||
|
||||
@@ -126,8 +126,6 @@ sealed interface AgendaWidgetData {
|
||||
/** "Always show today" (#35): anchor today at the top even with no events left. */
|
||||
val showToday: Boolean,
|
||||
val textSize: WidgetSize,
|
||||
val style: AgendaWidgetStyle = AgendaWidgetStyle.CARDS,
|
||||
val invertText: Boolean = false,
|
||||
/** Snapshot instant the data was read at, for "has this event ended?" tests. */
|
||||
val now: Instant,
|
||||
) : AgendaWidgetData
|
||||
@@ -186,8 +184,6 @@ internal suspend fun Context.loadAgendaWidgetData(
|
||||
pastDisplay = options.pastDisplay,
|
||||
showToday = options.showToday,
|
||||
textSize = options.textSize,
|
||||
style = options.style,
|
||||
invertText = options.invertText,
|
||||
now = Clock.System.now(),
|
||||
)
|
||||
}
|
||||
|
||||
@@ -2,7 +2,6 @@ package de.jeanlucmakiola.calendula.widget
|
||||
|
||||
import androidx.compose.runtime.Composable
|
||||
import androidx.compose.ui.graphics.Color
|
||||
import androidx.compose.ui.graphics.compositeOver
|
||||
import androidx.compose.ui.unit.Dp
|
||||
import androidx.compose.ui.unit.TextUnit
|
||||
import androidx.compose.ui.unit.dp
|
||||
@@ -19,6 +18,7 @@ import androidx.glance.layout.padding
|
||||
import androidx.glance.text.FontWeight
|
||||
import androidx.glance.text.Text
|
||||
import androidx.glance.text.TextStyle
|
||||
import de.jeanlucmakiola.calendula.MainActivity
|
||||
import de.jeanlucmakiola.calendula.R
|
||||
import de.jeanlucmakiola.calendula.domain.EventInstance
|
||||
import de.jeanlucmakiola.calendula.domain.isCrossedOut
|
||||
@@ -26,33 +26,20 @@ import de.jeanlucmakiola.calendula.ui.common.CalendarView
|
||||
import de.jeanlucmakiola.calendula.ui.common.SECONDARY_INK_ALPHA
|
||||
import de.jeanlucmakiola.calendula.ui.common.eventFill
|
||||
import de.jeanlucmakiola.calendula.ui.common.eventInk
|
||||
import de.jeanlucmakiola.calendula.ui.theme.CalendulaDarkFallback
|
||||
import de.jeanlucmakiola.calendula.widget.agenda.metricsFor
|
||||
import de.jeanlucmakiola.floret.components.Position
|
||||
import de.jeanlucmakiola.floret.glance.WidgetGroupedRow
|
||||
import de.jeanlucmakiola.floret.glance.themedColor
|
||||
|
||||
/** How much of a past event's tone stays in its dimmed fill (#90). */
|
||||
private const val WidgetDimFillAlpha = 0.3f
|
||||
/** A past event's fill when dimmed: fainter than the app's whole-row dim, so its text can stay readable (#90). */
|
||||
internal const val WidgetDimFillAlpha = 0.3f
|
||||
|
||||
/** A dimmed event's ink, held above its fill. */
|
||||
private const val WidgetDimInkAlpha = 0.65f
|
||||
|
||||
/**
|
||||
* An event's fill in the light or [dark] theme. A dimmed one is its tone faded
|
||||
* into that theme's surface, kept opaque: a translucent tint lands on the row
|
||||
* shape's white, not on the widget, and its ink would be picked for the wrong tone (#475).
|
||||
*/
|
||||
internal fun widgetEventFill(rawArgb: Int, dark: Boolean, soften: Boolean, dimmed: Boolean): Color {
|
||||
val tone = eventFill(rawArgb, dark, soften)
|
||||
if (!dimmed) return tone
|
||||
val surface = if (dark) CalendulaDarkFallback.surface else Color.White
|
||||
return tone.copy(alpha = WidgetDimFillAlpha).compositeOver(surface)
|
||||
}
|
||||
|
||||
/** Ink for an event on [fill], faded when the row is [dimmed]. */
|
||||
internal fun widgetEventInk(fill: Color, alpha: Float, dimmed: Boolean): Color =
|
||||
eventInk(fill, if (dimmed) alpha * WidgetDimInkAlpha else alpha)
|
||||
/** Ink for an event on [fill], picked against the opaque tone and faded when the fill is dimmed. */
|
||||
internal fun widgetEventInk(fill: Color, alpha: Float): Color =
|
||||
eventInk(fill.copy(alpha = 1f), if (fill.alpha < 1f) alpha * WidgetDimInkAlpha else alpha)
|
||||
|
||||
/** Text and row sizes of a compact event list, from a widget's [WidgetSize]. */
|
||||
internal data class EventRowMetrics(val title: TextUnit, val time: TextUnit, val rowHeight: Dp, val message: TextUnit)
|
||||
@@ -85,8 +72,9 @@ internal fun WidgetEventRow(
|
||||
quiet: Boolean = false,
|
||||
) {
|
||||
val context = LocalContext.current
|
||||
val day = widgetEventFill(event.color, dark = false, soften, dimmed)
|
||||
val night = widgetEventFill(event.color, dark = true, soften, dimmed)
|
||||
fun tone(dark: Boolean): Color = eventFill(event.color, dark, soften).let { if (dimmed) it.copy(alpha = WidgetDimFillAlpha) else it }
|
||||
val day = tone(dark = false)
|
||||
val night = tone(dark = true)
|
||||
val card = widgetCardColor()
|
||||
WidgetGroupedRow(position = position, color = if (quiet) card else themedColor(day = day, night = night)) {
|
||||
Column(
|
||||
@@ -96,7 +84,13 @@ internal fun WidgetEventRow(
|
||||
.padding(horizontal = 12.dp)
|
||||
.clickable(
|
||||
actionStartActivity(
|
||||
event.openIntent(context, source),
|
||||
MainActivity.openEventIntent(
|
||||
context = context,
|
||||
eventId = event.eventId,
|
||||
beginMillis = event.start.toEpochMilliseconds(),
|
||||
endMillis = event.end.toEpochMilliseconds(),
|
||||
source = source,
|
||||
),
|
||||
),
|
||||
),
|
||||
verticalAlignment = Alignment.CenterVertically,
|
||||
@@ -104,12 +98,12 @@ internal fun WidgetEventRow(
|
||||
val titleInk = if (quiet) {
|
||||
GlanceTheme.colors.onSurface
|
||||
} else {
|
||||
themedColor(day = widgetEventInk(day, 1f, dimmed), night = widgetEventInk(night, 1f, dimmed))
|
||||
themedColor(day = widgetEventInk(day, 1f), night = widgetEventInk(night, 1f))
|
||||
}
|
||||
val timeInk = if (quiet) {
|
||||
GlanceTheme.colors.onSurfaceVariant
|
||||
} else {
|
||||
themedColor(day = widgetEventInk(day, SECONDARY_INK_ALPHA, dimmed), night = widgetEventInk(night, SECONDARY_INK_ALPHA, dimmed))
|
||||
themedColor(day = widgetEventInk(day, SECONDARY_INK_ALPHA), night = widgetEventInk(night, SECONDARY_INK_ALPHA))
|
||||
}
|
||||
Text(
|
||||
text = event.title.ifBlank { context.getString(R.string.event_untitled) },
|
||||
|
||||
@@ -26,7 +26,7 @@ import de.jeanlucmakiola.calendula.widget.split.MonthDayWidget
|
||||
import de.jeanlucmakiola.calendula.widget.split.MonthDayWidgetReceiver
|
||||
|
||||
/** A content option a widget's config screen offers, besides background and theme. */
|
||||
enum class WidgetOption { STYLE, RANGE, TEXT_SIZE, PAST_DISPLAY, SHOW_TODAY, CALENDARS }
|
||||
enum class WidgetOption { RANGE, TEXT_SIZE, PAST_DISPLAY, SHOW_TODAY, CALENDARS }
|
||||
|
||||
/**
|
||||
* Every widget the app ships, told apart by their receiver: what redraws,
|
||||
@@ -42,14 +42,7 @@ enum class WidgetKind(
|
||||
AGENDA(
|
||||
AgendaWidgetReceiver::class.java,
|
||||
R.string.widget_agenda_label,
|
||||
setOf(
|
||||
WidgetOption.STYLE,
|
||||
WidgetOption.RANGE,
|
||||
WidgetOption.TEXT_SIZE,
|
||||
WidgetOption.PAST_DISPLAY,
|
||||
WidgetOption.SHOW_TODAY,
|
||||
WidgetOption.CALENDARS,
|
||||
),
|
||||
setOf(WidgetOption.RANGE, WidgetOption.TEXT_SIZE, WidgetOption.PAST_DISPLAY, WidgetOption.SHOW_TODAY, WidgetOption.CALENDARS),
|
||||
DpSize(260.dp, 280.dp),
|
||||
),
|
||||
MONTH(
|
||||
|
||||
@@ -19,9 +19,6 @@ import kotlinx.datetime.toJavaDayOfWeek
|
||||
import kotlinx.datetime.toJavaLocalDate
|
||||
import kotlinx.datetime.toLocalDateTime
|
||||
import kotlin.time.Instant
|
||||
import de.jeanlucmakiola.calendula.MainActivity
|
||||
import de.jeanlucmakiola.calendula.ui.common.CalendarView
|
||||
import androidx.glance.appwidget.action.actionStartActivity
|
||||
|
||||
/** Cards sit one tone off the root fill, and stay opaque over a wallpaper (#292). */
|
||||
@Composable
|
||||
@@ -30,19 +27,6 @@ internal fun widgetCardColor(): ColorProvider = when (LocalWidgetBackground.curr
|
||||
WidgetBackground.TINTED, WidgetBackground.TRANSPARENT -> GlanceTheme.colors.widgetBackground
|
||||
}
|
||||
|
||||
/** Opens this occurrence in the app, backing out to [source]. */
|
||||
internal fun EventInstance.openIntent(context: Context, source: CalendarView) = MainActivity.openEventIntent(
|
||||
context = context,
|
||||
eventId = eventId,
|
||||
beginMillis = start.toEpochMilliseconds(),
|
||||
endMillis = end.toEpochMilliseconds(),
|
||||
source = source,
|
||||
)
|
||||
|
||||
/** Opens [date] in the app's agenda. */
|
||||
internal fun openDayAction(context: Context, date: LocalDate) =
|
||||
actionStartActivity(MainActivity.openDateIntent(context, date, CalendarView.Agenda))
|
||||
|
||||
/** An event's time on [day]: "All day", "Starts 14:00", "Ends 9:00" or "14:00 – 15:30". */
|
||||
internal fun widgetTimeLabel(context: Context, event: EventInstance, day: LocalDate, is24Hour: Boolean): String =
|
||||
when (val label = agendaTimeLabel(event, day, systemZone())) {
|
||||
|
||||
@@ -34,7 +34,7 @@ fun CalendulaGlanceTheme(mode: WidgetThemeMode, content: @Composable () -> Unit)
|
||||
@Composable
|
||||
internal fun CalendulaWidgetRoot(appearance: WidgetAppearance, appTheme: ThemeMode, content: @Composable () -> Unit) {
|
||||
CalendulaGlanceTheme(appearance.theme.resolve(appTheme)) {
|
||||
WidgetSurface(background = appearance.background, opacity = appearance.opacity, content = content)
|
||||
WidgetSurface(background = appearance.background, content = content)
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -12,15 +12,6 @@ internal val ROW_H_PAD = 12.dp
|
||||
/** Space between the date-pill gutter and a day's card. */
|
||||
internal val GUTTER_GAP = 6.dp
|
||||
|
||||
/** The classic style's row inset, colour stripe and the gap after it (#489). */
|
||||
internal val CLASSIC_ROW_H_PAD = 4.dp
|
||||
internal val STRIPE_WIDTH = 5.dp
|
||||
internal val STRIPE_GAP = 10.dp
|
||||
|
||||
/** The stripe and its gap, and where the classic style's event text starts, so its placeholder lines up with the titles. */
|
||||
internal val STRIPE_INSET = STRIPE_WIDTH + STRIPE_GAP
|
||||
internal val TEXT_INDENT = CLASSIC_ROW_H_PAD + STRIPE_INSET
|
||||
|
||||
/**
|
||||
* Every size the agenda widget varies by [WidgetSize]. Values that genuinely
|
||||
* shouldn't grow (the horizontal row constants above, corner radii) stay
|
||||
@@ -38,8 +29,6 @@ internal data class AgendaMetrics(
|
||||
val rowVPad: Dp, // event row vertical padding
|
||||
val dayGap: Dp, // space between two days' cards
|
||||
val monthLabel: TextUnit, // month name above a new month's first day
|
||||
val dayHeader: TextUnit, // classic style's day label ("Today · …")
|
||||
val dayHeaderTopPad: Dp, // classic style's space above a day label
|
||||
) {
|
||||
/** One event row's height, shared by the date pill beside it and the placeholder row. */
|
||||
val rowHeight: Dp get() = contentH + rowVPad * 2
|
||||
@@ -72,8 +61,6 @@ private val SMALL_METRICS = AgendaMetrics(
|
||||
rowVPad = 4.dp,
|
||||
dayGap = 8.dp,
|
||||
monthLabel = 12.sp,
|
||||
dayHeader = 13.sp,
|
||||
dayHeaderTopPad = 10.dp,
|
||||
)
|
||||
|
||||
private val MEDIUM_METRICS = AgendaMetrics(
|
||||
@@ -88,8 +75,6 @@ private val MEDIUM_METRICS = AgendaMetrics(
|
||||
rowVPad = 5.dp,
|
||||
dayGap = 9.dp,
|
||||
monthLabel = 14.sp,
|
||||
dayHeader = 14.sp, // M3 Title Small
|
||||
dayHeaderTopPad = 11.dp,
|
||||
)
|
||||
|
||||
private val LARGE_METRICS = AgendaMetrics(
|
||||
@@ -104,8 +89,6 @@ private val LARGE_METRICS = AgendaMetrics(
|
||||
rowVPad = 6.dp,
|
||||
dayGap = 10.dp,
|
||||
monthLabel = 14.sp,
|
||||
dayHeader = 16.sp, // M3 Title Medium
|
||||
dayHeaderTopPad = 12.dp,
|
||||
)
|
||||
|
||||
private val EXTRA_LARGE_METRICS = AgendaMetrics(
|
||||
@@ -120,8 +103,6 @@ private val EXTRA_LARGE_METRICS = AgendaMetrics(
|
||||
rowVPad = 8.dp,
|
||||
dayGap = 12.dp,
|
||||
monthLabel = 16.sp,
|
||||
dayHeader = 18.sp, // †
|
||||
dayHeaderTopPad = 14.dp,
|
||||
)
|
||||
|
||||
/** Indexed by [WidgetSize.ordinal] so lookup allocates nothing per recomposition. */
|
||||
|
||||
@@ -11,7 +11,6 @@ import de.jeanlucmakiola.calendula.widget.glanceDeclinedDecoration
|
||||
import android.content.Context
|
||||
import androidx.compose.runtime.Composable
|
||||
import androidx.compose.ui.graphics.Color
|
||||
import androidx.compose.ui.unit.Dp
|
||||
import androidx.compose.ui.unit.dp
|
||||
import androidx.glance.GlanceId
|
||||
import androidx.glance.GlanceModifier
|
||||
@@ -56,15 +55,8 @@ import de.jeanlucmakiola.calendula.ui.agenda.anchorTodayIfMissing
|
||||
import de.jeanlucmakiola.calendula.ui.common.CalendarView
|
||||
import de.jeanlucmakiola.calendula.ui.common.formatCalendarTitle
|
||||
import de.jeanlucmakiola.floret.locale.localizedDateFormatter
|
||||
import de.jeanlucmakiola.calendula.widget.widgetEventFill
|
||||
import de.jeanlucmakiola.calendula.ui.common.eventAccent
|
||||
import de.jeanlucmakiola.calendula.ui.common.EventDimAlpha
|
||||
import de.jeanlucmakiola.calendula.widget.AgendaWidgetStyle
|
||||
import de.jeanlucmakiola.floret.glance.LocalWidgetBackground
|
||||
import de.jeanlucmakiola.floret.glance.LocalWidgetSeeThrough
|
||||
import androidx.compose.runtime.CompositionLocalProvider
|
||||
import de.jeanlucmakiola.floret.glance.WidgetBackground
|
||||
import de.jeanlucmakiola.floret.glance.withAlpha
|
||||
import de.jeanlucmakiola.calendula.ui.common.eventFill
|
||||
import de.jeanlucmakiola.calendula.widget.WidgetDimFillAlpha
|
||||
import de.jeanlucmakiola.calendula.widget.widgetEventInk
|
||||
import de.jeanlucmakiola.calendula.ui.common.SECONDARY_INK_ALPHA
|
||||
import de.jeanlucmakiola.calendula.widget.AgendaWidgetData
|
||||
@@ -73,8 +65,6 @@ import de.jeanlucmakiola.calendula.widget.CalendulaWidgetRoot
|
||||
import de.jeanlucmakiola.calendula.widget.WidgetAppearance
|
||||
import de.jeanlucmakiola.calendula.widget.widgetCardColor
|
||||
import de.jeanlucmakiola.calendula.widget.widgetTimeLabel
|
||||
import de.jeanlucmakiola.calendula.widget.openIntent
|
||||
import de.jeanlucmakiola.calendula.widget.openDayAction
|
||||
import de.jeanlucmakiola.calendula.widget.loadAgendaWidget
|
||||
import de.jeanlucmakiola.calendula.widget.widgetAppearance
|
||||
import de.jeanlucmakiola.floret.components.Position
|
||||
@@ -97,8 +87,7 @@ import kotlinx.datetime.toJavaDayOfWeek
|
||||
|
||||
/**
|
||||
* "Upcoming" agenda widget — a continuously scrolling list of the next ~30 days
|
||||
* of events: each day one card of grouped rows with its date pill beside it, or
|
||||
* in the classic style a label line over plain colour-stripe rows (#489).
|
||||
* of events, each day one card of grouped rows with its date pill beside it.
|
||||
* Reuses the app's [groupAgendaDays] grouping so it matches the in-app agenda.
|
||||
*/
|
||||
class AgendaWidget : GlanceAppWidget() {
|
||||
@@ -161,10 +150,10 @@ private const val PREVIEW_ROWS = 10
|
||||
* user scrolling a home-screen widget past a hundred rows is not a case worth
|
||||
* risking a failed update for.
|
||||
*/
|
||||
internal const val MAX_AGENDA_ROWS = 100
|
||||
private const val MAX_AGENDA_ROWS = 100
|
||||
|
||||
/** Flat row model: one [LazyColumn] item per event or placeholder, a day's first one carrying its date pill. */
|
||||
internal sealed interface AgendaRow {
|
||||
private sealed interface AgendaRow {
|
||||
val date: LocalDate
|
||||
|
||||
data class Event(override val date: LocalDate, val event: EventInstance) : AgendaRow
|
||||
@@ -179,21 +168,16 @@ private fun AgendaWidgetBody(data: AgendaWidgetData, preview: Boolean) {
|
||||
val size = (data as? AgendaWidgetData.Ready)?.textSize ?: WidgetSize.SMALL
|
||||
val fontScale = androidx.glance.LocalContext.current.resources.configuration.fontScale
|
||||
val metrics = metricsFor(size).scaledForFont(fontScale)
|
||||
// The classic style adds no backings for a faded fill, only on a transparent one (#489).
|
||||
val classic = (data as? AgendaWidgetData.Ready)?.style == AgendaWidgetStyle.CLASSIC
|
||||
val seeThrough = if (classic) LocalWidgetBackground.current == WidgetBackground.TRANSPARENT else LocalWidgetSeeThrough.current
|
||||
CompositionLocalProvider(LocalWidgetSeeThrough provides seeThrough) {
|
||||
Column(
|
||||
modifier = GlanceModifier
|
||||
.fillMaxSize()
|
||||
.padding(horizontal = 8.dp, vertical = 6.dp),
|
||||
) {
|
||||
AgendaHeader()
|
||||
Spacer(GlanceModifier.height(6.dp))
|
||||
when (data) {
|
||||
AgendaWidgetData.NeedsPermission -> WidgetMessage(R.string.widget_needs_permission, metrics)
|
||||
is AgendaWidgetData.Ready -> AgendaRows(data = data, metrics = metrics, preview = preview)
|
||||
}
|
||||
Column(
|
||||
modifier = GlanceModifier
|
||||
.fillMaxSize()
|
||||
.padding(horizontal = 8.dp, vertical = 6.dp),
|
||||
) {
|
||||
AgendaHeader()
|
||||
Spacer(GlanceModifier.height(6.dp))
|
||||
when (data) {
|
||||
AgendaWidgetData.NeedsPermission -> WidgetMessage(R.string.widget_needs_permission, metrics)
|
||||
is AgendaWidgetData.Ready -> AgendaRows(data = data, metrics = metrics, preview = preview)
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -235,248 +219,60 @@ private fun AgendaRows(
|
||||
day.events.forEach { add(AgendaRow.Event(day.date, it)) }
|
||||
}
|
||||
}
|
||||
}
|
||||
when (data.style) {
|
||||
AgendaWidgetStyle.CARDS -> CardRows(rows, data, metrics, preview)
|
||||
AgendaWidgetStyle.CLASSIC -> ClassicRows(rows, data, metrics, preview)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/** Each day is one card of grouped rows (#71), with its date pill beside the first row. */
|
||||
@Composable
|
||||
private fun CardRows(allRows: List<AgendaRow>, data: AgendaWidgetData.Ready, metrics: AgendaMetrics, preview: Boolean) {
|
||||
val rows = allRows.take(MAX_AGENDA_ROWS)
|
||||
val positions = dayPositions(rows.map { it.date })
|
||||
val cardColor = widgetCardColor()
|
||||
val item: @Composable (Int) -> Unit = { index ->
|
||||
val row = rows[index]
|
||||
val position = positions[index]
|
||||
val first = position == Position.Top || position == Position.Alone
|
||||
val dayRow: @Composable (GlanceModifier) -> Unit = { modifier ->
|
||||
Row(modifier = modifier.fillMaxWidth()) {
|
||||
Box(modifier = GlanceModifier.width(metrics.pillWidth)) {
|
||||
if (first) DatePill(row.date, data.today, cardColor, metrics)
|
||||
}
|
||||
Spacer(GlanceModifier.width(GUTTER_GAP))
|
||||
Box(modifier = GlanceModifier.defaultWeight()) {
|
||||
val rowColor = when (row) {
|
||||
is AgendaRow.Event -> row.fill(data).let { themedColor(day = it.day, night = it.night) }
|
||||
is AgendaRow.Placeholder -> cardColor
|
||||
}.take(MAX_AGENDA_ROWS)
|
||||
// Each day is one card of grouped rows (#71), with its date pill
|
||||
// beside the first row.
|
||||
val positions = dayPositions(rows)
|
||||
val cardColor = widgetCardColor()
|
||||
val item: @Composable (Int) -> Unit = { index ->
|
||||
val row = rows[index]
|
||||
val position = positions[index]
|
||||
val first = position == Position.Top || position == Position.Alone
|
||||
val dayRow: @Composable (GlanceModifier) -> Unit = { modifier ->
|
||||
Row(modifier = modifier.fillMaxWidth()) {
|
||||
Box(modifier = GlanceModifier.width(metrics.pillWidth)) {
|
||||
if (first) DatePill(row.date, data.today, cardColor, metrics)
|
||||
}
|
||||
WidgetGroupedRow(position = position, color = rowColor) {
|
||||
AgendaRowContent(row, data, metrics)
|
||||
Spacer(GlanceModifier.width(GUTTER_GAP))
|
||||
Box(modifier = GlanceModifier.defaultWeight()) {
|
||||
val rowColor = when (row) {
|
||||
is AgendaRow.Event -> row.fill(data).let { themedColor(day = it.day, night = it.night) }
|
||||
is AgendaRow.Placeholder -> cardColor
|
||||
}
|
||||
WidgetGroupedRow(position = position, color = rowColor) {
|
||||
AgendaRowContent(row, data, metrics)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
val gap = GlanceModifier.padding(top = if (first && index > 0) metrics.dayGap else 0.dp)
|
||||
// The pills carry no month, so a new month gets its name above its first day.
|
||||
if (first && index > 0 && row.date.month != rows[index - 1].date.month) {
|
||||
Column(modifier = gap.fillMaxWidth()) {
|
||||
MonthLabel(row.date, data.today, metrics)
|
||||
dayRow(GlanceModifier)
|
||||
}
|
||||
} else {
|
||||
dayRow(gap)
|
||||
}
|
||||
}
|
||||
RowList(rows.size, preview, item)
|
||||
}
|
||||
|
||||
/** [count] rows of [item]: a plain column in a [preview], else a [LazyColumn]. */
|
||||
@Composable
|
||||
private fun RowList(count: Int, preview: Boolean, item: @Composable (Int) -> Unit) {
|
||||
if (preview) {
|
||||
Column(modifier = GlanceModifier.fillMaxSize()) {
|
||||
repeat(minOf(count, PREVIEW_ROWS)) { item(it) }
|
||||
}
|
||||
} else {
|
||||
LazyColumn(modifier = GlanceModifier.fillMaxSize()) {
|
||||
items(count) { item(it) }
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/** A classic list entry: a day's label line, or one of its rows. */
|
||||
internal sealed interface ClassicItem {
|
||||
val date: LocalDate
|
||||
|
||||
data class Header(override val date: LocalDate) : ClassicItem
|
||||
data class Entry(val row: AgendaRow) : ClassicItem {
|
||||
override val date: LocalDate get() = row.date
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* [rows] with a label before each day's first, held to [limit] items in all,
|
||||
* headers included; a label the cut leaves with nothing under it is dropped.
|
||||
*/
|
||||
internal fun classicItems(rows: List<AgendaRow>, limit: Int = MAX_AGENDA_ROWS): List<ClassicItem> = buildList {
|
||||
rows.forEachIndexed { index, row ->
|
||||
if (index == 0 || row.date != rows[index - 1].date) add(ClassicItem.Header(row.date))
|
||||
add(ClassicItem.Entry(row))
|
||||
}
|
||||
}.take(limit).dropLastWhile { it is ClassicItem.Header }
|
||||
|
||||
/**
|
||||
* v2.23's look (#489): a label line per day over plain rows with a colour
|
||||
* stripe. On a transparent root each day sits on its own backing card, so the
|
||||
* text stays readable over the wallpaper; a faded fill is left to the opacity
|
||||
* and "Invert text colour" options.
|
||||
*/
|
||||
@Composable
|
||||
private fun ClassicRows(rows: List<AgendaRow>, data: AgendaWidgetData.Ready, metrics: AgendaMetrics, preview: Boolean) {
|
||||
val items = classicItems(rows, if (preview) PREVIEW_ROWS else MAX_AGENDA_ROWS)
|
||||
val backed = LocalWidgetBackground.current == WidgetBackground.TRANSPARENT
|
||||
val ink = classicInk(inverted = data.invertText && !backed)
|
||||
val positions = if (backed) dayPositions(items.map { it.date }) else emptyList()
|
||||
val cardColor = widgetCardColor()
|
||||
val item: @Composable (Int) -> Unit = { index ->
|
||||
val entry = items[index]
|
||||
val content: @Composable () -> Unit = {
|
||||
when (entry) {
|
||||
is ClassicItem.Header -> DayHeaderRow(
|
||||
date = entry.date,
|
||||
today = data.today,
|
||||
startPad = if (backed) CLASSIC_CARD_H_PAD else 8.dp,
|
||||
topPad = when {
|
||||
backed -> CLASSIC_CARD_TOP_PAD
|
||||
index == 0 -> 0.dp
|
||||
else -> metrics.dayHeaderTopPad
|
||||
},
|
||||
ink = ink,
|
||||
metrics = metrics,
|
||||
)
|
||||
is ClassicItem.Entry -> when (val row = entry.row) {
|
||||
is AgendaRow.Placeholder -> ClassicPlaceholderRow(row.date, backed, ink, metrics)
|
||||
is AgendaRow.Event -> ClassicEventRow(row, data, backed, ink, metrics)
|
||||
val gap = GlanceModifier.padding(top = if (first && index > 0) metrics.dayGap else 0.dp)
|
||||
// The pills carry no month, so a new month gets its name above its first day.
|
||||
if (first && index > 0 && row.date.month != rows[index - 1].date.month) {
|
||||
Column(modifier = gap.fillMaxWidth()) {
|
||||
MonthLabel(row.date, data.today, metrics)
|
||||
dayRow(GlanceModifier)
|
||||
}
|
||||
} else {
|
||||
dayRow(gap)
|
||||
}
|
||||
}
|
||||
if (backed) {
|
||||
val gap = if (entry is ClassicItem.Header && index > 0) metrics.dayGap else 0.dp
|
||||
WidgetGroupedRow(
|
||||
position = positions[index],
|
||||
modifier = GlanceModifier.padding(top = gap),
|
||||
color = cardColor,
|
||||
gapBelow = false,
|
||||
content = content,
|
||||
)
|
||||
if (preview) {
|
||||
Column(modifier = GlanceModifier.fillMaxSize()) {
|
||||
repeat(minOf(rows.size, PREVIEW_ROWS)) { item(it) }
|
||||
}
|
||||
} else {
|
||||
content()
|
||||
}
|
||||
}
|
||||
RowList(items.size, preview, item)
|
||||
}
|
||||
|
||||
/** The classic style's text colours: the theme's, or its inverse for the "Invert text colour" option. */
|
||||
private data class ClassicInk(val title: ColorProvider, val secondary: ColorProvider, val today: ColorProvider)
|
||||
|
||||
@Composable
|
||||
private fun classicInk(inverted: Boolean): ClassicInk = with(GlanceTheme.colors) {
|
||||
if (inverted) {
|
||||
ClassicInk(inverseOnSurface, inverseOnSurface.withAlpha(INVERTED_SECONDARY_INK), inversePrimary)
|
||||
} else {
|
||||
ClassicInk(onSurface, onSurfaceVariant, primary)
|
||||
}
|
||||
}
|
||||
|
||||
/** A classic day label, "Today · Wed, 17 Jun"; opens that day in the app. */
|
||||
@Composable
|
||||
private fun DayHeaderRow(date: LocalDate, today: LocalDate, startPad: Dp, topPad: Dp, ink: ClassicInk, metrics: AgendaMetrics) {
|
||||
val context = androidx.glance.LocalContext.current
|
||||
Text(
|
||||
text = agendaDayLabel(context, date, today),
|
||||
maxLines = 1,
|
||||
style = TextStyle(
|
||||
color = if (date == today) ink.today else ink.secondary,
|
||||
fontSize = metrics.dayHeader,
|
||||
fontWeight = FontWeight.Medium,
|
||||
),
|
||||
modifier = GlanceModifier
|
||||
.fillMaxWidth()
|
||||
.padding(start = startPad, end = 8.dp, top = topPad, bottom = metrics.rowVPad)
|
||||
.clickable(openDayAction(context, date)),
|
||||
)
|
||||
}
|
||||
|
||||
/** "No more events today" as a muted line under an anchored, event-less today (#35), indented to the titles. */
|
||||
@Composable
|
||||
private fun ClassicPlaceholderRow(date: LocalDate, backed: Boolean, ink: ClassicInk, metrics: AgendaMetrics) {
|
||||
val context = androidx.glance.LocalContext.current
|
||||
Text(
|
||||
text = context.getString(R.string.agenda_no_more_today),
|
||||
maxLines = 1,
|
||||
style = TextStyle(color = ink.secondary, fontSize = metrics.placeholder),
|
||||
modifier = GlanceModifier
|
||||
.fillMaxWidth()
|
||||
.padding(start = if (backed) CLASSIC_CARD_H_PAD + STRIPE_INSET else TEXT_INDENT, end = 8.dp, top = 2.dp, bottom = metrics.rowVPad + 2.dp)
|
||||
.clickable(openDayAction(context, date)),
|
||||
)
|
||||
}
|
||||
|
||||
/** A classic event row: the calendar's colour stripe beside the title and time; a dimmed one fades both. */
|
||||
@Composable
|
||||
private fun ClassicEventRow(row: AgendaRow.Event, data: AgendaWidgetData.Ready, backed: Boolean, ink: ClassicInk, metrics: AgendaMetrics) {
|
||||
val context = androidx.glance.LocalContext.current
|
||||
val event = row.event
|
||||
val dimmed = row.dimmed(data)
|
||||
fun accent(dark: Boolean) = eventAccent(event.color, dark, data.soften).let {
|
||||
if (dimmed) it.copy(alpha = EventDimAlpha) else it
|
||||
}
|
||||
Row(
|
||||
modifier = GlanceModifier
|
||||
.fillMaxWidth()
|
||||
.padding(horizontal = if (backed) CLASSIC_CARD_H_PAD else CLASSIC_ROW_H_PAD, vertical = metrics.rowVPad)
|
||||
.clickable(actionStartActivity(event.openIntent(context, CalendarView.Agenda))),
|
||||
verticalAlignment = Alignment.CenterVertically,
|
||||
) {
|
||||
Box(
|
||||
modifier = GlanceModifier
|
||||
.width(STRIPE_WIDTH)
|
||||
.height(metrics.contentH)
|
||||
.cornerRadius(3.dp)
|
||||
.background(themedColor(day = accent(dark = false), night = accent(dark = true))),
|
||||
) {}
|
||||
Spacer(GlanceModifier.width(STRIPE_GAP))
|
||||
Column(modifier = GlanceModifier.defaultWeight()) {
|
||||
Text(
|
||||
text = event.title.ifBlank { context.getString(R.string.event_untitled) },
|
||||
maxLines = 1,
|
||||
style = TextStyle(
|
||||
color = if (dimmed) ink.title.withAlpha(CLASSIC_DIM_INK) else ink.title,
|
||||
fontSize = metrics.eventTitle,
|
||||
textDecoration = glanceDeclinedDecoration(event.isCrossedOut),
|
||||
),
|
||||
)
|
||||
Text(
|
||||
text = eventTimeSummary(context, event, row.date, data.is24Hour),
|
||||
maxLines = 1,
|
||||
style = TextStyle(
|
||||
color = if (dimmed) ink.secondary.withAlpha(CLASSIC_DIM_INK) else ink.secondary,
|
||||
fontSize = metrics.eventTime,
|
||||
),
|
||||
)
|
||||
LazyColumn(modifier = GlanceModifier.fillMaxSize()) {
|
||||
items(rows.size) { item(it) }
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/** Space above a day's label on its own backing card, and its rows' inset, clear of the card's corners. */
|
||||
private val CLASSIC_CARD_TOP_PAD = 8.dp
|
||||
private val CLASSIC_CARD_H_PAD = 10.dp
|
||||
|
||||
/** How strongly a finished event's text shows in the classic style, on any fill. */
|
||||
private const val CLASSIC_DIM_INK = 0.5f
|
||||
|
||||
/** The inverted secondary text's strength, as `onSurfaceVariant` sits below `onSurface`. */
|
||||
private const val INVERTED_SECONDARY_INK = 0.75f
|
||||
|
||||
/** Where each row sits among the rows of its day, from each row's date, for the grouped-card shapes. */
|
||||
private fun dayPositions(dates: List<LocalDate>): List<Position> = buildList {
|
||||
/** Where each row sits among the rows of its day, for the grouped-card shapes. */
|
||||
private fun dayPositions(rows: List<AgendaRow>): List<Position> = buildList {
|
||||
var start = 0
|
||||
for (end in 1..dates.size) {
|
||||
if (end == dates.size || dates[end] != dates[start]) {
|
||||
for (end in 1..rows.size) {
|
||||
if (end == rows.size || rows[end].date != rows[start].date) {
|
||||
for (i in start until end) add(positionOf(i - start, end - start))
|
||||
start = end
|
||||
}
|
||||
@@ -547,7 +343,7 @@ private fun DatePill(date: LocalDate, today: LocalDate, cardColor: ColorProvider
|
||||
.height(metrics.rowHeight)
|
||||
.cornerRadius(metrics.pillWidth / 2)
|
||||
.background(container)
|
||||
.clickable(openDayAction(context, date))
|
||||
.clickable(actionStartActivity(MainActivity.openDateIntent(context, date, CalendarView.Agenda)))
|
||||
.semantics { contentDescription = label },
|
||||
horizontalAlignment = Alignment.CenterHorizontally,
|
||||
verticalAlignment = Alignment.CenterVertically,
|
||||
@@ -579,7 +375,11 @@ private fun PlaceholderRow(date: LocalDate, metrics: AgendaMetrics) {
|
||||
.fillMaxWidth()
|
||||
.height(metrics.rowHeight)
|
||||
.padding(horizontal = ROW_H_PAD)
|
||||
.clickable(openDayAction(context, date)),
|
||||
.clickable(
|
||||
actionStartActivity(
|
||||
MainActivity.openDateIntent(context, date, CalendarView.Agenda),
|
||||
),
|
||||
),
|
||||
contentAlignment = Alignment.CenterStart,
|
||||
) {
|
||||
Text(
|
||||
@@ -591,19 +391,14 @@ private fun PlaceholderRow(date: LocalDate, metrics: AgendaMetrics) {
|
||||
}
|
||||
|
||||
/** An event row's light and dark fill: its calendar's container tone, faded when the row is dimmed. */
|
||||
private data class EventFill(val day: Color, val night: Color, val dimmed: Boolean)
|
||||
|
||||
/** Whether this row is drawn faded as a finished event. */
|
||||
private fun AgendaRow.Event.dimmed(data: AgendaWidgetData.Ready): Boolean =
|
||||
data.pastDisplay == PastEventDisplay.DIM && event.hasEnded(data.now)
|
||||
private data class EventFill(val day: Color, val night: Color)
|
||||
|
||||
private fun AgendaRow.Event.fill(data: AgendaWidgetData.Ready): EventFill {
|
||||
val dimmed = dimmed(data)
|
||||
return EventFill(
|
||||
day = widgetEventFill(event.color, dark = false, data.soften, dimmed),
|
||||
night = widgetEventFill(event.color, dark = true, data.soften, dimmed),
|
||||
dimmed = dimmed,
|
||||
)
|
||||
val dimmed = data.pastDisplay == PastEventDisplay.DIM && event.hasEnded(data.now)
|
||||
fun tone(dark: Boolean) = eventFill(event.color, dark, data.soften).let {
|
||||
if (dimmed) it.copy(alpha = WidgetDimFillAlpha) else it
|
||||
}
|
||||
return EventFill(day = tone(dark = false), night = tone(dark = true))
|
||||
}
|
||||
|
||||
@Composable
|
||||
@@ -616,17 +411,27 @@ private fun EventRow(
|
||||
) {
|
||||
val context = androidx.glance.LocalContext.current
|
||||
val title = event.title.ifBlank { context.getString(R.string.event_untitled) }
|
||||
val titleInk = themedColor(day = widgetEventInk(fill.day, 1f, fill.dimmed), night = widgetEventInk(fill.night, 1f, fill.dimmed))
|
||||
val titleInk = themedColor(day = widgetEventInk(fill.day, 1f), night = widgetEventInk(fill.night, 1f))
|
||||
val timeInk = themedColor(
|
||||
day = widgetEventInk(fill.day, SECONDARY_INK_ALPHA, fill.dimmed),
|
||||
night = widgetEventInk(fill.night, SECONDARY_INK_ALPHA, fill.dimmed),
|
||||
day = widgetEventInk(fill.day, SECONDARY_INK_ALPHA),
|
||||
night = widgetEventInk(fill.night, SECONDARY_INK_ALPHA),
|
||||
)
|
||||
Column(
|
||||
modifier = GlanceModifier
|
||||
.fillMaxWidth()
|
||||
.height(metrics.rowHeight)
|
||||
.padding(horizontal = ROW_H_PAD)
|
||||
.clickable(actionStartActivity(event.openIntent(context, CalendarView.Agenda))),
|
||||
.clickable(
|
||||
actionStartActivity(
|
||||
MainActivity.openEventIntent(
|
||||
context = context,
|
||||
eventId = event.eventId,
|
||||
beginMillis = event.start.toEpochMilliseconds(),
|
||||
endMillis = event.end.toEpochMilliseconds(),
|
||||
source = CalendarView.Agenda,
|
||||
),
|
||||
),
|
||||
),
|
||||
verticalAlignment = Alignment.CenterVertically,
|
||||
) {
|
||||
Text(
|
||||
@@ -669,7 +474,7 @@ private fun agendaDayLabel(context: Context, date: LocalDate, today: LocalDate):
|
||||
val java = java.time.LocalDate.of(date.year, date.month.ordinal + 1, date.day)
|
||||
// Weekday + date in the locale's own field order (compact: no year), rather
|
||||
// than a hardcoded day-month layout.
|
||||
val formatted = localizedDateFormatter(locale, if (date.year == today.year) "EEEdMMM" else "EEEdMMMy").format(java)
|
||||
val formatted = localizedDateFormatter(locale, "EEEdMMM").format(java)
|
||||
return if (relative != null) "$relative · $formatted" else formatted
|
||||
}
|
||||
|
||||
|
||||
@@ -69,16 +69,6 @@ import de.jeanlucmakiola.floret.glance.GlanceWidgetPreview
|
||||
import de.jeanlucmakiola.floret.glance.WallpaperWindow
|
||||
import de.jeanlucmakiola.floret.glance.WidgetBackground
|
||||
import kotlin.math.roundToInt
|
||||
import de.jeanlucmakiola.floret.components.GroupedSliderRow
|
||||
import de.jeanlucmakiola.floret.components.InfoPopover
|
||||
import de.jeanlucmakiola.calendula.widget.AgendaWidgetStyle
|
||||
import java.text.NumberFormat
|
||||
import de.jeanlucmakiola.floret.locale.currentLocale
|
||||
import androidx.compose.runtime.remember
|
||||
import androidx.compose.animation.AnimatedVisibility
|
||||
import androidx.compose.material.icons.outlined.Info
|
||||
import androidx.compose.material3.Switch
|
||||
import androidx.compose.foundation.layout.Row
|
||||
|
||||
private val PreviewMaxHeight = 280.dp
|
||||
|
||||
@@ -246,42 +236,6 @@ private fun ConfigOptions(
|
||||
onSelect = { onAppearance(state.appearance.copy(background = it)) },
|
||||
position = Position.Top,
|
||||
)
|
||||
val faded = state.appearance.background != WidgetBackground.TRANSPARENT
|
||||
val content = state.draft.content
|
||||
val classic = state.kind == WidgetKind.AGENDA && content.style == AgendaWidgetStyle.CLASSIC
|
||||
if (faded) {
|
||||
val opacity = state.appearance.opacity
|
||||
GroupedSliderRow(
|
||||
title = stringResource(R.string.widget_config_opacity),
|
||||
value = opacity,
|
||||
onValueChange = { onAppearance(state.appearance.copy(opacity = it)) },
|
||||
position = Position.Middle,
|
||||
valueLabel = currentLocale().let { locale ->
|
||||
remember(opacity, locale) { NumberFormat.getPercentInstance(locale).format(opacity) }
|
||||
},
|
||||
valueRange = MIN_OPACITY..1f,
|
||||
steps = OPACITY_STEPS,
|
||||
titleAccessory = {
|
||||
InfoPopover(
|
||||
text = stringResource(
|
||||
if (classic) R.string.widget_config_readability_hint_classic else R.string.widget_config_readability_hint,
|
||||
),
|
||||
contentDescription = stringResource(R.string.widget_config_readability_info),
|
||||
)
|
||||
},
|
||||
)
|
||||
}
|
||||
if (faded && classic) {
|
||||
GroupedRow(
|
||||
title = stringResource(R.string.widget_config_invert_text),
|
||||
summary = stringResource(R.string.widget_config_invert_text_summary),
|
||||
position = Position.Middle,
|
||||
trailing = {
|
||||
Switch(checked = content.invertText, onCheckedChange = { onContent(content.copy(invertText = it)) })
|
||||
},
|
||||
onClick = { onContent(content.copy(invertText = !content.invertText)) },
|
||||
)
|
||||
}
|
||||
GroupedChoiceRow(
|
||||
title = stringResource(R.string.settings_theme),
|
||||
options = WidgetTheme.entries,
|
||||
@@ -311,7 +265,6 @@ private fun ContentOptions(
|
||||
onCalendarShown: (Long, Boolean) -> Unit,
|
||||
) {
|
||||
val options = state.draft.content
|
||||
var showStyle by rememberSaveable { mutableStateOf(false) }
|
||||
var showRange by rememberSaveable { mutableStateOf(false) }
|
||||
var showSize by rememberSaveable { mutableStateOf(false) }
|
||||
var showPast by rememberSaveable { mutableStateOf(false) }
|
||||
@@ -324,12 +277,6 @@ private fun ContentOptions(
|
||||
GroupedSectionHeader(stringResource(R.string.widget_config_content))
|
||||
rows.forEach { option ->
|
||||
when (option) {
|
||||
WidgetOption.STYLE -> GroupedRow(
|
||||
title = stringResource(R.string.widget_config_style),
|
||||
summary = agendaStyleLabel(options.style),
|
||||
position = position(option),
|
||||
onClick = { showStyle = true },
|
||||
)
|
||||
WidgetOption.RANGE -> GroupedRow(
|
||||
title = stringResource(R.string.widget_config_range),
|
||||
summary = agendaRangeLabel(options.range),
|
||||
@@ -372,17 +319,6 @@ private fun ContentOptions(
|
||||
)
|
||||
}
|
||||
|
||||
if (showStyle) {
|
||||
OptionPicker(
|
||||
title = stringResource(R.string.widget_config_style),
|
||||
predictiveBack = true,
|
||||
options = AgendaWidgetStyle.entries,
|
||||
selected = options.style,
|
||||
label = { agendaStyleLabel(it) },
|
||||
onSelect = { onChange(options.copy(style = it)) },
|
||||
onDismiss = { showStyle = false },
|
||||
)
|
||||
}
|
||||
if (showRange) {
|
||||
AgendaRangePicker(
|
||||
title = stringResource(R.string.widget_config_range),
|
||||
@@ -420,18 +356,6 @@ private fun ContentOptions(
|
||||
}
|
||||
}
|
||||
|
||||
@Composable
|
||||
private fun agendaStyleLabel(style: AgendaWidgetStyle): String = stringResource(
|
||||
when (style) {
|
||||
AgendaWidgetStyle.CARDS -> R.string.widget_config_style_cards
|
||||
AgendaWidgetStyle.CLASSIC -> R.string.widget_config_style_classic
|
||||
},
|
||||
)
|
||||
|
||||
/** The faintest fill the opacity slider allows, and its 10% steps between that and opaque. */
|
||||
private const val MIN_OPACITY = 0.2f
|
||||
private const val OPACITY_STEPS = 7
|
||||
|
||||
@Composable
|
||||
internal fun backgroundLabel(background: WidgetBackground): String = stringResource(
|
||||
when (background) {
|
||||
|
||||
@@ -2,7 +2,6 @@ package de.jeanlucmakiola.calendula.widget.countdown
|
||||
|
||||
import de.jeanlucmakiola.calendula.domain.EventInstance
|
||||
import de.jeanlucmakiola.calendula.domain.EventStatus
|
||||
import de.jeanlucmakiola.calendula.domain.coversWholeDays
|
||||
import de.jeanlucmakiola.calendula.domain.isCrossedOut
|
||||
import kotlinx.datetime.DateTimeUnit
|
||||
import kotlinx.datetime.TimeZone
|
||||
@@ -76,13 +75,12 @@ fun nextLabelChange(event: EventInstance, now: Instant, zone: TimeZone): Instant
|
||||
}
|
||||
|
||||
/**
|
||||
* The next-event mode's pick: timed and not filling whole days (#296), not
|
||||
* declined or cancelled, not over; of those, the one whose countdown changes
|
||||
* soonest — a running event's end, else a start.
|
||||
* The next-event mode's pick: timed, not declined or cancelled, not over; of those, the one
|
||||
* whose countdown changes soonest — a running event's end, else a start.
|
||||
*/
|
||||
fun pickNextEvent(instances: List<EventInstance>, now: Instant, zone: TimeZone): EventInstance? =
|
||||
fun pickNextEvent(instances: List<EventInstance>, now: Instant): EventInstance? =
|
||||
instances
|
||||
.filter { !it.coversWholeDays(zone) && !it.isCrossedOut && it.end > now }
|
||||
.filter { !it.isAllDay && !it.isCrossedOut && it.end > now }
|
||||
.minByOrNull { target(it, now) }
|
||||
|
||||
/** A pinned event's occurrence to count to: the running or next one that is not cancelled (#388). */
|
||||
|
||||
@@ -75,11 +75,7 @@ internal suspend fun Context.loadCountdown(
|
||||
val repository = widgetEntryPoint().calendarRepository()
|
||||
val event = when (options.mode) {
|
||||
CountdownMode.NEXT ->
|
||||
pickNextEvent(
|
||||
repository.instances(now..now + NextEventHorizon).first().withoutCalendars(load.hiddenCalendars),
|
||||
now,
|
||||
systemZone(),
|
||||
)
|
||||
pickNextEvent(repository.instances(now..now + NextEventHorizon).first().withoutCalendars(load.hiddenCalendars), now)
|
||||
CountdownMode.PINNED -> options.eventId?.let { id ->
|
||||
pickPinnedOccurrence(repository.eventOccurrences(id, now - 1.days..now + PinnedHorizon), now, systemZone())
|
||||
}
|
||||
|
||||
@@ -40,9 +40,7 @@ import androidx.glance.text.TextStyle
|
||||
import de.jeanlucmakiola.calendula.MainActivity
|
||||
import de.jeanlucmakiola.calendula.R
|
||||
import de.jeanlucmakiola.calendula.domain.EventInstance
|
||||
import de.jeanlucmakiola.calendula.domain.coversWholeDays
|
||||
import de.jeanlucmakiola.calendula.ui.common.CalendarView
|
||||
import de.jeanlucmakiola.calendula.widget.openIntent
|
||||
import de.jeanlucmakiola.calendula.ui.common.eventAccent
|
||||
import de.jeanlucmakiola.calendula.widget.CalendulaWidgetReceiver
|
||||
import de.jeanlucmakiola.calendula.widget.CalendulaWidgetRoot
|
||||
@@ -133,7 +131,13 @@ private fun EventCountdown(event: EventInstance, data: CountdownData.Ready) {
|
||||
val context = LocalContext.current
|
||||
val label = countdownLabel(event.counted(systemZone()), data.now, systemZone())
|
||||
val open = actionStartActivity(
|
||||
event.openIntent(context, CalendarView.Agenda),
|
||||
MainActivity.openEventIntent(
|
||||
context = context,
|
||||
eventId = event.eventId,
|
||||
beginMillis = event.start.toEpochMilliseconds(),
|
||||
endMillis = event.end.toEpochMilliseconds(),
|
||||
source = CalendarView.Agenda,
|
||||
),
|
||||
)
|
||||
// Over a wallpaper the text sits on its own card, as every other widget's rows do.
|
||||
val card = GlanceModifier.wallpaperBacking(radius = 16.dp)
|
||||
@@ -206,13 +210,12 @@ private fun whenText(context: Context, event: EventInstance, data: CountdownData
|
||||
val at = if (running) counted.end else counted.start
|
||||
val date = at.toLocalDateTime(systemZone()).date
|
||||
val day = relativeDayLabel(context, date, data.today)
|
||||
val wholeDays = event.coversWholeDays(systemZone())
|
||||
return when {
|
||||
wholeDays && running -> context.getString(
|
||||
event.isAllDay && running -> context.getString(
|
||||
R.string.widget_countdown_until,
|
||||
relativeDayLabel(context, date.minus(1, DateTimeUnit.DAY), data.today),
|
||||
)
|
||||
wholeDays -> "$day · ${context.getString(R.string.event_detail_all_day)}"
|
||||
event.isAllDay -> "$day · ${context.getString(R.string.event_detail_all_day)}"
|
||||
running -> context.getString(R.string.agenda_span_ends, "$day · ${formatWidgetTime(at, data.is24Hour)}")
|
||||
else -> "$day · ${formatWidgetTime(at, data.is24Hour)}"
|
||||
}
|
||||
|
||||
@@ -36,25 +36,11 @@ internal fun <T : Any> mergeGaps(columns: Int, cellAt: (Int) -> GridCell<T>?): L
|
||||
return cells
|
||||
}
|
||||
|
||||
/** What a cell of the single mixed lane shows: an event's bar, or a day's event count. */
|
||||
internal sealed interface LaneItem {
|
||||
data class Bar(val event: EventInstance) : LaneItem
|
||||
data class Count(val count: Int) : LaneItem
|
||||
}
|
||||
|
||||
/**
|
||||
* One week of the grid seated with [laneCap] lanes, drawn [compact] when the
|
||||
* row is too short for a full one. [showsOverflow] is off when the week has no
|
||||
* room for the "+N" row; a [mixed] single lane then shows each day's count in
|
||||
* place of its bar where the day has more than fits (#491).
|
||||
* One week of the grid seated with [laneCap] lanes. [showsOverflow] is off when
|
||||
* the week has no room for even the "+N" row.
|
||||
*/
|
||||
internal class WeekLayout(
|
||||
val week: MonthWeek,
|
||||
val laneCap: Int,
|
||||
val showsOverflow: Boolean = true,
|
||||
val compact: Boolean = false,
|
||||
val mixed: Boolean = false,
|
||||
) {
|
||||
internal class WeekLayout(val week: MonthWeek, val laneCap: Int, val showsOverflow: Boolean = true) {
|
||||
private val seating: List<DaySeating> = week.days.indices.map { week.seating(it, laneCap) }
|
||||
|
||||
/** Lanes filled from the top; empty lanes below are not drawn. */
|
||||
@@ -69,16 +55,6 @@ internal class WeekLayout(
|
||||
}
|
||||
}
|
||||
|
||||
/** The single lane of a [mixed] week, bars cut short where a day shows its count instead; null otherwise. */
|
||||
val mixedLane: List<GridCell<LaneItem>>? = if (!mixed) null else mergeGaps(week.days.size) { col ->
|
||||
val day = seating[col]
|
||||
if (day.hidden.isNotEmpty()) return@mergeGaps GridCell(LaneItem.Count(week.countByDay[week.days[col]] ?: day.hidden.size), 1)
|
||||
val seat = day.seated.firstOrNull() ?: return@mergeGaps null
|
||||
val spanEnd = if (seat.bar) week.spanAt(col, seat.lane)?.endCol ?: col else col
|
||||
val end = (col + 1..spanEnd).firstOrNull { seating[it].hidden.isNotEmpty() }?.minus(1) ?: spanEnd
|
||||
GridCell(LaneItem.Bar(seat.event), end - col + 1)
|
||||
}
|
||||
|
||||
/** The "+N" row as counts and merged gaps; empty when everything fits. */
|
||||
val overflow: List<GridCell<Int>> = seating.map { it.hidden.size }.let { hidden ->
|
||||
if (hidden.none { it > 0 }) emptyList()
|
||||
@@ -86,31 +62,19 @@ internal class WeekLayout(
|
||||
}
|
||||
}
|
||||
|
||||
/** How many lanes a week row holds, and whether they're the [compact] height. */
|
||||
internal data class LaneFit(val lanes: Int, val compact: Boolean = false)
|
||||
|
||||
/**
|
||||
* Event lanes a week row [weekHeight] tall holds under its day number, held to
|
||||
* [MAX_LANES] so a tall widget's payload stays bounded (#214). A row too short
|
||||
* for one full lane still gets a compact one when its text fits at [fontScale] (#491).
|
||||
* [MAX_LANES] so a tall widget's payload stays bounded (#214).
|
||||
*/
|
||||
internal fun lanesFitting(weekHeight: Dp, fontScale: Float): LaneFit {
|
||||
val room = weekHeight.value - DAY_ROW_DP - LANES_TOP_DP
|
||||
val full = (room / LANE_ROW_DP).toInt().coerceIn(0, MAX_LANES)
|
||||
val compactFits = room >= COMPACT_LANE_ROW_DP && fontScale <= COMPACT_MAX_FONT_SCALE
|
||||
return if (full == 0 && compactFits) LaneFit(1, compact = true) else LaneFit(full)
|
||||
}
|
||||
internal fun lanesFitting(weekHeight: Dp): Int =
|
||||
((weekHeight.value - DAY_ROW_DP - LANES_TOP_DP) / LANE_ROW_DP).toInt().coerceIn(0, MAX_LANES)
|
||||
|
||||
/**
|
||||
* Seats each week in [fit]'s lanes. A week whose events need more gives its
|
||||
* last lane to the "+N" row instead. A single lane has no room for that row,
|
||||
* so it mixes bars and per-day counts (#491).
|
||||
* Seats each week in [lanes] lanes. A week whose events need more gives its
|
||||
* last lane to the "+N" row instead.
|
||||
*/
|
||||
internal fun fitWeeks(weeks: List<MonthWeek>, fit: LaneFit): List<WeekLayout> = weeks.map { week ->
|
||||
val lanes = fit.lanes
|
||||
if (lanes <= 1) {
|
||||
return@map WeekLayout(week, laneCap = lanes, showsOverflow = false, compact = fit.compact, mixed = lanes == 1)
|
||||
}
|
||||
internal fun fitWeeks(weeks: List<MonthWeek>, lanes: Int): List<WeekLayout> = weeks.map { week ->
|
||||
if (lanes == 0) return@map WeekLayout(week, laneCap = 0, showsOverflow = false)
|
||||
val needed = WeekLayout(week, UNCAPPED_LANES).usedLanes
|
||||
WeekLayout(week, if (needed <= lanes) lanes else lanes - 1)
|
||||
}
|
||||
@@ -121,7 +85,4 @@ internal const val MAX_LANES = 8
|
||||
private const val DAY_ROW_DP = 18f
|
||||
private const val LANES_TOP_DP = 2f
|
||||
private const val LANE_ROW_DP = 15f
|
||||
/** Matches `widget_month_lane_compact`'s height; its 9sp text clips past [COMPACT_MAX_FONT_SCALE]. */
|
||||
private const val COMPACT_LANE_ROW_DP = 12f
|
||||
private const val COMPACT_MAX_FONT_SCALE = 1f
|
||||
private const val UNCAPPED_LANES = 64
|
||||
@@ -91,21 +91,6 @@ private fun weekViews(
|
||||
week.setViewVisibility(TODAY_IDS[col], if (isToday) View.VISIBLE else View.GONE)
|
||||
if (isToday) week.setImageTint(context, TODAY_IDS[col], colors.primary)
|
||||
}
|
||||
layout.mixedLane?.let { cells ->
|
||||
val lane = laneViews(context, layout.compact)
|
||||
cells.forEach { cell ->
|
||||
lane.addView(
|
||||
R.id.lane,
|
||||
when (val item = cell.item) {
|
||||
null -> gap(context, cell.cols)
|
||||
is LaneItem.Bar -> bar(context, item.event, cell.cols, soften, mode)
|
||||
is LaneItem.Count -> more(context, item.count, colors)
|
||||
},
|
||||
)
|
||||
}
|
||||
week.addView(R.id.week_lanes, lane)
|
||||
return week
|
||||
}
|
||||
layout.lanes.forEach { cells ->
|
||||
val lane = laneViews(context)
|
||||
cells.forEach { cell ->
|
||||
@@ -121,7 +106,10 @@ private fun weekViews(
|
||||
if (count == null) {
|
||||
lane.addView(R.id.lane, gap(context, cell.cols))
|
||||
} else {
|
||||
lane.addView(R.id.lane, more(context, count, colors))
|
||||
val more = RemoteViews(context.packageName, R.layout.widget_month_more)
|
||||
more.setTextViewText(R.id.more, "+$count")
|
||||
more.setTextColor(context, R.id.more, colors.onSurfaceVariant)
|
||||
lane.addView(R.id.lane, more)
|
||||
}
|
||||
}
|
||||
week.addView(R.id.week_lanes, lane)
|
||||
@@ -129,15 +117,8 @@ private fun weekViews(
|
||||
return week
|
||||
}
|
||||
|
||||
private fun more(context: Context, count: Int, colors: GridColors) =
|
||||
RemoteViews(context.packageName, R.layout.widget_month_more).apply {
|
||||
setTextViewText(R.id.more, "+$count")
|
||||
setTextColor(context, R.id.more, colors.onSurfaceVariant)
|
||||
}
|
||||
|
||||
private fun laneViews(context: Context, compact: Boolean = false) =
|
||||
RemoteViews(context.packageName, if (compact) R.layout.widget_month_lane_compact else R.layout.widget_month_lane)
|
||||
.apply { removeAllViews(R.id.lane) }
|
||||
private fun laneViews(context: Context) =
|
||||
RemoteViews(context.packageName, R.layout.widget_month_lane).apply { removeAllViews(R.id.lane) }
|
||||
|
||||
private fun gap(context: Context, cols: Int) = RemoteViews(context.packageName, GAP_LAYOUTS[cols - 1])
|
||||
|
||||
|
||||
@@ -254,7 +254,7 @@ private fun MonthWidgetBody(source: MonthWidgetSource, index: Int) {
|
||||
val context = LocalContext.current
|
||||
val fontScale = context.resources.configuration.fontScale
|
||||
val weekHeight = (LocalSize.current.height - gridChromeHeight(fontScale)) / weeks.size
|
||||
val layouts = fitWeeks(weeks, lanesFitting(weekHeight, fontScale))
|
||||
val layouts = fitWeeks(weeks, lanesFitting(weekHeight))
|
||||
val mode = LocalWidgetThemeMode.current
|
||||
val colors = GridColors(
|
||||
onSurface = remoteColor(WidgetColorRole.ON_SURFACE),
|
||||
|
||||
@@ -1,6 +1,5 @@
|
||||
package de.jeanlucmakiola.calendula.widget.split
|
||||
|
||||
import de.jeanlucmakiola.calendula.domain.isCrossedOut
|
||||
import de.jeanlucmakiola.calendula.widget.InAppLanguage
|
||||
import de.jeanlucmakiola.calendula.widget.WidgetKind
|
||||
import de.jeanlucmakiola.calendula.widget.previewSizeOf
|
||||
@@ -269,9 +268,7 @@ internal fun MonthDayWidgetContent(
|
||||
val day = selected ?: source.today
|
||||
val zone = systemZone()
|
||||
val days = monthGridDays(index, source.weekStart)
|
||||
// Declined and cancelled events are no plan for the day, as on the week strip (#388).
|
||||
val planned = source.instances.filterNot { it.isCrossedOut }
|
||||
val busy = groupAgendaDays(days.first(), days.last(), planned, zone).map { it.date }.toSet()
|
||||
val busy = groupAgendaDays(days.first(), days.last(), source.instances, zone).map { it.date }.toSet()
|
||||
Column(modifier = GlanceModifier.fillMaxSize().padding(horizontal = 8.dp, vertical = 6.dp)) {
|
||||
Header(index, source.today)
|
||||
Spacer(GlanceModifier.height(4.dp))
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
package de.jeanlucmakiola.calendula.widget.week
|
||||
|
||||
import de.jeanlucmakiola.calendula.domain.isCrossedOut
|
||||
import de.jeanlucmakiola.calendula.domain.EventStatus
|
||||
import de.jeanlucmakiola.calendula.widget.InAppLanguage
|
||||
import de.jeanlucmakiola.calendula.widget.WidgetKind
|
||||
import de.jeanlucmakiola.calendula.widget.previewSizeOf
|
||||
@@ -146,8 +146,8 @@ private fun DayTile(date: LocalDate, data: DaysWidgetData.Ready) {
|
||||
else -> GlanceTheme.colors.onSurface
|
||||
}
|
||||
val locale = widgetLocale()
|
||||
// A declined or cancelled event is no plan for the day, so it adds no dot and no count (#388).
|
||||
val events = data.eventsOn(date).filterNot { it.isCrossedOut }
|
||||
// A cancelled event is no plan for the day, so it adds no dot and no count (#388).
|
||||
val events = data.eventsOn(date).filter { it.status != EventStatus.Cancelled }
|
||||
val colors = events.map { it.color }.distinct()
|
||||
val label = localizedDateFormatter(locale, "EEEEdMMMM").format(date.toJavaLocalDate())
|
||||
Column(
|
||||
|
||||
@@ -1,8 +0,0 @@
|
||||
<?xml version="1.0" encoding="utf-8"?>
|
||||
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
|
||||
android:id="@+id/lane"
|
||||
android:layout_width="match_parent"
|
||||
android:layout_height="12dp"
|
||||
android:orientation="horizontal"
|
||||
android:paddingBottom="1dp"
|
||||
android:weightSum="7" />
|
||||
@@ -292,7 +292,7 @@
|
||||
<string name="settings_dim_completed_summary">تعتيم الأحداث التي انتهت بالفعل في عرض الشهر والأسبوع</string>
|
||||
<string name="settings_today_toolbar">زر اليوم في شريط الأدوات</string>
|
||||
<string name="settings_today_toolbar_summary">إظهار زر الانتقال إلى اليوم في شريط الأدوات بدلاً من زر عائم</string>
|
||||
<string name="settings_app_name_summary">اعرض Calendula كـ ”التقويم“ في مشغّل التطبيقات الخاص بك. فقط الاسم في المشغّل يتغير؛ وقد ينتقل الرمز إلى مكان جديد بعد التبديل.</string>
|
||||
<string name="settings_app_name_summary">اعرض Calendula كـ ”Calendar“ في مشغّل التطبيقات الخاص بك. فقط الاسم في المشغّل يتغير؛ وقد ينتقل الرمز إلى مكان جديد بعد التبديل.</string>
|
||||
<string name="settings_past_events_dim">تعتيم</string>
|
||||
<string name="settings_past_events">الأحداث السابقة</string>
|
||||
<string name="settings_agenda_range">مدى الجدول</string>
|
||||
@@ -456,7 +456,7 @@
|
||||
<string name="calendars_restore_action">استعادة من ملف .ics</string>
|
||||
<string name="calendars_restore_hint">استيراد الأحداث من نسخة احتياطية أو تطبيق تقويم آخر.</string>
|
||||
<string name="calendars_auto_backup">النسخ الاحتياطي التلقائي</string>
|
||||
<string name="calendars_auto_backup_hint">تصدير تقويماتك المحلية بشكل دوري إلى مجلد كـ ملف .ics</string>
|
||||
<string name="calendars_auto_backup_hint">قم بتصدير تقويماتك المحلية بشكل دوري إلى مجلد كـ ملف .ics.</string>
|
||||
<string name="calendars_auto_backup_folder">مجلد النسخ الاحتياطي</string>
|
||||
<string name="calendars_auto_backup_folder_unset">اضغط لاختيار مجلد</string>
|
||||
<string name="calendars_auto_backup_every">كل %1$s</string>
|
||||
@@ -638,7 +638,7 @@
|
||||
<item quantity="many">يتم استيراد %d حدث</item>
|
||||
<item quantity="other">يتم استيراد %d حدث</item>
|
||||
</plurals>
|
||||
<string name="event_move_recurring_title">نقل الحدث المتكرّر</string>
|
||||
<string name="event_move_recurring_title">نقل الحدث المتكرر</string>
|
||||
<string name="event_edit_conflict_overwrite_hint">فقط الحقول التي عدلتها هي التي ستحل محل التغيير الخارجي</string>
|
||||
<string name="reorder_drag_handle">اسحب لإعادة الترتيب</string>
|
||||
<string name="settings_drawer_order_hint">اسحب لإعادة ترتيب طرق العرض المدرجة في قائمة التنقل.</string>
|
||||
@@ -665,7 +665,7 @@
|
||||
<string name="duration_hours_minutes">%1$s %2$s</string>
|
||||
<string name="settings_widgets_hint">إعدادات لأدوات الشاشة الرئيسية وعنصر الإعدادات السريعة. أضف أداة عن طريق الضغط لفترة طويلة على شاشتك الرئيسية.</string>
|
||||
<string name="import_warning_attendees">لم يتم استيراد قوائم الضيوف.</string>
|
||||
<string name="settings_reliable_delivery_exempt">معفى من تحسين البطارية — تصل التذكيرات في الوقت المحدّد.</string>
|
||||
<string name="settings_reliable_delivery_exempt">معفى من تحسين البطارية — تصل التذكيرات في الوقت المحدد.</string>
|
||||
<string name="settings_reliable_delivery">توصيل موثوق</string>
|
||||
<string name="settings_allday_reminder_time_hint">تنطلق التذكيرات لأحداث التي تستمر طوال اليوم عند %1$s</string>
|
||||
<string name="agenda_range_override_hint">فقط للآن — يعيد التعيين للمدى المحفوظ خاصتك عند إعادة فتح Calendula.</string>
|
||||
@@ -804,30 +804,4 @@
|
||||
<string name="reminder_day_today">اليوم</string>
|
||||
<string name="event_detail_open_in_maps">فتح في الخرائط</string>
|
||||
<string name="link_open_failed">لا تطبيق يمكنه فتح هذا الرابط</string>
|
||||
<string name="settings_support_kofi">Ko-fi</string>
|
||||
<string name="settings_support_liberapay">Liberapay</string>
|
||||
<string name="settings_support_liberapay_hint">التبرعات المتكررة</string>
|
||||
<string name="settings_support_kofi_hint">الإكراميات لمرة واحدة</string>
|
||||
<string name="settings_theme_black">أسود</string>
|
||||
<string name="settings_theme_black_summary">داكن مع خلفيات سوداء نقية، لشاشات AMOLED</string>
|
||||
<string name="event_resize_done">تم التغيير إلى %1$s</string>
|
||||
<string name="event_resize_recurring_title">تغيير الحدث المتكرّر</string>
|
||||
<string name="event_selection_actions">إجراءات الحدث</string>
|
||||
<string name="event_selection_hide">إخفاء إجراءات الحدث</string>
|
||||
<string name="event_selection_close">إلغاء تحديد الحدث</string>
|
||||
<string name="event_draft_create">إنشاء حدث</string>
|
||||
<string name="event_draft_discard">تجاهل الحدث الجديد</string>
|
||||
<string name="event_action_load_failed">تعذّر فتح الحدث</string>
|
||||
<string name="event_edit_more_actions">المزيد من الإجراءات</string>
|
||||
<string name="event_edit_unsaved_title">تغييرات غير محفوظة</string>
|
||||
<string name="event_edit_unsaved_save">حفظ التغييرات</string>
|
||||
<string name="event_edit_unsaved_discard">تجاهل التغييرات</string>
|
||||
<string name="event_edit_create">إنشاء</string>
|
||||
<string name="settings_tap_opens_details">التفاصيل</string>
|
||||
<string name="settings_tap_opens_editor">نموذج التعديل</string>
|
||||
<string name="process_text_create_event">إنشاء حدث</string>
|
||||
<string name="settings_events_header">الأحداث</string>
|
||||
<string name="settings_tap_opens">النقر بحدث يفتح</string>
|
||||
<string name="settings_tap_opens_hint">الأحداث التي لا يمكنك تعديلها وإشعارات التذكير دائمًا تفتح التفاصيل.</string>
|
||||
<string name="event_edit_unsaved_keep">متابعة التعديل</string>
|
||||
</resources>
|
||||
@@ -697,7 +697,7 @@
|
||||
<string name="onboarding_calendars_benefit_sync_title">Або наладзьце сынхранізацыю з уліковым запісам</string>
|
||||
<string name="onboarding_calendars_created_more_title">Прастора для іншых</string>
|
||||
<string name="onboarding_calendars_created_title">«%1$s» гатовы</string>
|
||||
<string name="onboarding_calendars_benefit_sync_body">Calendula паказвае ўліковыя запісы, якія ўжо сынхранізуюцца. Для выкананьня сынхранізацыі сэрвэры CalDAV патрабуець DAVx.</string>
|
||||
<string name="onboarding_calendars_benefit_sync_body">Calendula паказвае ўліковыя запісы, якія ўжо сынхранізуюцца. Для выкананьня сынхранізацыі сэрвэры CalDAV патрабуець DAVx\\u2075.</string>
|
||||
<string name="onboarding_calendars_created_body">Ён застаецца на гэтай прыладзе. У ім будуць запісвацца новыя падзеі, пакуль ня будзе выбраны іншы каляндар.</string>
|
||||
<string name="onboarding_calendars_created_more_body">Праз мэню Налады → Календары можна задаць колькасьць, назвы і колеры наяўных календароў.</string>
|
||||
<string name="onboarding_calendars_created_continue">Далей</string>
|
||||
@@ -708,37 +708,4 @@
|
||||
<string name="onboarding_hidden_failed">Гэты не атрымалася ўключыць. У мэню Налады → Календары знаходзяцца такія самыя перамыкачы.</string>
|
||||
<string name="onboarding_calendars_create_failed">Не атрымалася стварыць каляндар з-за адмовы сховішча вашай прылады.</string>
|
||||
<string name="reminder_day_today">Сёньня</string>
|
||||
<string name="event_resize_done">Зьменена на %1$s</string>
|
||||
<string name="event_resize_recurring_title">Зьмяніць пэрыядычную падзею</string>
|
||||
<string name="event_selection_actions">Дзеяньні падзеі</string>
|
||||
<string name="event_selection_hide">Схаваць дзеяньні падзеі</string>
|
||||
<string name="event_selection_close">Адмяніць выбар падзеі</string>
|
||||
<string name="event_draft_create">Стварыць падзею</string>
|
||||
<string name="event_draft_discard">Адкінуць новую падзею</string>
|
||||
<string name="event_action_load_failed">Не атрымалася адкрыць падзею</string>
|
||||
<string name="event_edit_more_actions">Іншыя дзеяньні</string>
|
||||
<string name="event_edit_unsaved_title">Незахаваныя зьмены</string>
|
||||
<string name="event_edit_unsaved_save">Захаваць зьмены</string>
|
||||
<string name="event_edit_unsaved_discard">Адкінуць зьмены</string>
|
||||
<string name="event_edit_unsaved_keep">Працягнуць рэдагаваньне</string>
|
||||
<string name="event_edit_create">Стварыць</string>
|
||||
<plurals name="view_multi_day">
|
||||
<item quantity="one">%d суткі</item>
|
||||
<item quantity="few">%d сутак</item>
|
||||
<item quantity="many">%d сутак</item>
|
||||
<item quantity="other">%d сутак</item>
|
||||
</plurals>
|
||||
<string name="settings_theme_black">Чорная</string>
|
||||
<string name="settings_theme_black_summary">Цёмная з чыста чорным тлом для экранаў AMOLED</string>
|
||||
<string name="settings_multi_day_count">Паказ некалькіх сутак</string>
|
||||
<string name="settings_multi_day_count_hint">Сколькі сутак бачныя ў рэжыме паказу некалькіх сутак. Сёньня адкрываецца ў першым слупку.</string>
|
||||
<string name="settings_timeline_scale_by_visible_hours">Задаецца праз бачныя гадзіны</string>
|
||||
<string name="settings_visible_hours">Бачныя гадзіны</string>
|
||||
<string name="settings_visible_hours_summary">Упісваць дыяпазон гадзін на экране пры праглядзе тыдня, некалькіх сутак або адных сутак</string>
|
||||
<string name="settings_visible_hours_on_summary">Пры адкрыцьці прагляду на экране зьявіцца дыяпазон %1$s—%2$s</string>
|
||||
<string name="settings_visible_hours_start">Ад</string>
|
||||
<string name="settings_visible_hours_end">Да</string>
|
||||
<string name="settings_visible_hours_start_hint">Гадзіна зьверху экрана ў рэжыме прагляду тыдня, некалькіх сутак або сутак. Каб пабачыць ранейшыя гадзіны, трэба прагортка.</string>
|
||||
<string name="settings_visible_hours_end_hint">Апошняя гадзіна ўнізе экрану ў рэжыме прагляду. Каб пабачыць пазьнейшыя гадзіны трэба прагортка. Таксама зьвядзеньнем пальцаў па экране можна зьмяніць маштаб да наступнага адкрыцьця рэжыму.</string>
|
||||
<string name="settings_events_header">Падзеі</string>
|
||||
</resources>
|
||||
@@ -471,7 +471,7 @@
|
||||
<string name="settings_reminders_hint">Vidíte připomínky dvakrát? Zobrazuje je i jiná aplikace kalendáře – v jedné z nich je vypněte.</string>
|
||||
<string name="settings_default_reminder">Výchozí připomínka</string>
|
||||
<string name="settings_default_reminder_allday">Celodenní události</string>
|
||||
<string name="settings_allday_reminder_time">Čas připomínky celodenní události</string>
|
||||
<string name="settings_allday_reminder_time">Čas celodenní připomínky</string>
|
||||
<string name="settings_allday_reminder_time_hint">Připomínky na celodenní události se spouštějí v %1$s</string>
|
||||
<string name="settings_allday_reminder_fires_at">Upozorní v %1$s</string>
|
||||
<string name="reminder_none">Žádná</string>
|
||||
@@ -489,7 +489,7 @@
|
||||
<string name="settings_snooze_duration">Doba odložení</string>
|
||||
<string name="settings_section_calendars">Kalendáře</string>
|
||||
<string name="settings_manage_calendars">Správa kalendářů</string>
|
||||
<string name="settings_manage_calendars_hint">Správa místních a synchronizovaných kalendářů</string>
|
||||
<string name="settings_manage_calendars_hint">Vytvořte místní kalendáře; spravujte synchronizované kalendáře</string>
|
||||
<string name="settings_section_language">Jazyk</string>
|
||||
<string name="settings_language">Jazyk aplikace</string>
|
||||
<string name="settings_language_auto">Výchozí nastavení systému</string>
|
||||
@@ -515,9 +515,9 @@
|
||||
<string name="settings_time_format_hint">Způsob zápisu času v celé aplikaci. Funkce „Automaticky“ se řídí nastavením vašeho systému.</string>
|
||||
<string name="settings_past_events_hint">Jak program zachází s událostmi, které již skončily.</string>
|
||||
<string name="settings_dynamic_color_summary">Aplikace převezme barvy z vaší tapety.</string>
|
||||
<string name="settings_section_special_dates">Události kontaktů</string>
|
||||
<string name="settings_special_dates_enable">Zobrazit události kontaktů</string>
|
||||
<string name="settings_special_dates_enable_hint">Zkopírujte data narozenin či dalších událostí svých kontaktů do místních kalendářů. Aplikace čte pouze kontakty v tomto zařízení – nikam se nic nenahrává, vaše kontakty zůstávají beze změny.</string>
|
||||
<string name="settings_section_special_dates">Speciální data kontaktů</string>
|
||||
<string name="settings_special_dates_enable">Zobrazit data kontaktů</string>
|
||||
<string name="settings_special_dates_enable_hint">Zkopírujte data narozenin a další data svých kontaktů do místních kalendářů. Aplikace čte pouze kontakty v tomto zařízení – nikam se nic nenahrává, vaše kontakty zůstávají beze změny.</string>
|
||||
<string name="settings_special_dates_type_birthday">Narozeniny</string>
|
||||
<string name="settings_special_dates_type_anniversary">Výročí</string>
|
||||
<string name="settings_special_dates_type_custom">Ostatní data</string>
|
||||
@@ -529,11 +529,11 @@
|
||||
<string name="settings_special_dates_never_synced">Zatím nesynchronizováno</string>
|
||||
<string name="settings_special_dates_last_synced">Naposledy synchronizováno %1$s</string>
|
||||
<string name="settings_special_dates_calendar_hint">Barvu a viditelnost jednotlivých kalendářů nastavte v nastavení kalendářů.</string>
|
||||
<string name="settings_calendar_reminders_managed_hint">Nastavte v části Události kontaktů</string>
|
||||
<string name="settings_calendar_reminders_managed_hint">Nastavte v části Speciální data kontaktu</string>
|
||||
<string name="settings_special_dates_paused_title">Pozastaveno</string>
|
||||
<string name="settings_special_dates_paused_hint">Calendula už nemá přístup k vašim kontaktům, tudíž zůstávají bez aktualizace.</string>
|
||||
<string name="settings_special_dates_grant">Udělit přístup</string>
|
||||
<string name="settings_special_dates_disable_title">Vypnout události kontaktů?</string>
|
||||
<string name="settings_special_dates_disable_title">Vypnout data kontaktů?</string>
|
||||
<string name="settings_special_dates_disable_type_message">Tímto se odstraní kalendář „%1$s“ a jeho události. Veškeré připomínky a poznámky, které jste do nich přidali, budou ztraceny.</string>
|
||||
<string name="settings_special_dates_disable_confirm">Vypnout</string>
|
||||
<string name="dialog_save">Uložit</string>
|
||||
@@ -566,7 +566,7 @@
|
||||
<string name="calendars_state_read_only">Pouze pro čtení</string>
|
||||
<string name="calendars_state_not_synced">Není synchronizováno s tímto zařízením</string>
|
||||
<string name="calendars_state_managed">Vyplněno z vašich kontaktů</string>
|
||||
<string name="calendars_managed_delete_locked">Tento kalendář se plní ze seznamu vašich kontaktů, takže jej aplikace Calendula při příští synchronizaci znovu vytvoří. Chcete-li jej odstranit, vypněte možnost událostí kontaktů v nabídce Nastavení → Události kontaktů.</string>
|
||||
<string name="calendars_managed_delete_locked">Tento kalendář se plní z vašich kontaktů, takže jej aplikace Calendula při příští synchronizaci znovu vytvoří. Chcete-li jej odstranit, vypněte možnost speciálních dat v nabídce Nastavení → Speciální data.</string>
|
||||
<string name="calendars_synced_header">Synchronizované kalendáře</string>
|
||||
<string name="calendars_synced_hint">Tyto kontakty pocházejí z účtů ve vašem zařízení. Vytvářejte je a upravujte v příslušné aplikaci.</string>
|
||||
<string name="calendars_manage_in_app">Spravovat v aplikaci</string>
|
||||
@@ -689,7 +689,7 @@
|
||||
<string name="crash_report_open_failed">Nepodařilo se otevřít systém pro hlášení problémů. Zpráva je zkopírována ve vaší schránce.</string>
|
||||
<string name="special_dates_calendar_birthday">Narozeniny</string>
|
||||
<string name="special_dates_calendar_anniversary">Výročí</string>
|
||||
<string name="special_dates_calendar_custom">Ostatní data</string>
|
||||
<string name="special_dates_calendar_custom">Speciální data</string>
|
||||
<string name="special_dates_default_title_birthday">Narozeniny má {name} ({year})</string>
|
||||
<string name="special_dates_default_title_anniversary">Výročí má {name} ({year})</string>
|
||||
<string name="special_dates_default_title_custom">{name}</string>
|
||||
@@ -764,26 +764,4 @@
|
||||
<string name="settings_support_kofi_hint">Jednorázové příspěvky</string>
|
||||
<string name="settings_support_liberapay">Liberapay</string>
|
||||
<string name="settings_support_liberapay_hint">Pravidelné příspěvky</string>
|
||||
<string name="event_resize_done">Změněno na %1$s</string>
|
||||
<string name="event_resize_recurring_title">Změnit opakující se událost</string>
|
||||
<string name="event_selection_actions">Akce událostí</string>
|
||||
<string name="event_selection_hide">Skrýt akce událostí</string>
|
||||
<string name="event_selection_close">Zrušit výběr události</string>
|
||||
<string name="event_draft_create">Vytvořit událost</string>
|
||||
<string name="event_draft_discard">Zahodit novou událost</string>
|
||||
<string name="event_action_load_failed">Událost se nepodařilo otevřít</string>
|
||||
<string name="event_edit_more_actions">Další akce</string>
|
||||
<string name="event_edit_unsaved_title">Neuložené změny</string>
|
||||
<string name="event_edit_unsaved_save">Uložit změny</string>
|
||||
<string name="event_edit_unsaved_discard">Zahodit změny</string>
|
||||
<string name="event_edit_unsaved_keep">Pokračovat v úpravách</string>
|
||||
<string name="event_edit_create">Vytvořit</string>
|
||||
<string name="settings_theme_black">Černý</string>
|
||||
<string name="settings_theme_black_summary">Tmavý s čistě černým pozadím, pro AMOLED obrazovky</string>
|
||||
<string name="settings_events_header">Události</string>
|
||||
<string name="settings_tap_opens">Klepnutím na událost se otevře</string>
|
||||
<string name="settings_tap_opens_details">Podrobnosti</string>
|
||||
<string name="settings_tap_opens_editor">Formulář pro úpravu</string>
|
||||
<string name="settings_tap_opens_hint">U upomínek a událostí, které nelze upravit, se vždy otevře stránka s podrobnostmi.</string>
|
||||
<string name="process_text_create_event">Vytvořit událost</string>
|
||||
</resources>
|
||||
@@ -592,7 +592,7 @@
|
||||
<string name="settings_month_header">Monatsansicht</string>
|
||||
<string name="settings_month_view_style">Stil der Monatsansicht</string>
|
||||
<string name="month_style_paged">Seiten</string>
|
||||
<string name="month_style_paged_summary">Ein Monat füllt den Bildschirm. Wische nach links oder rechts, um den Monat zu wechseln, oder wische nach oben, um die Monatsagenda anzuzeigen.</string>
|
||||
<string name="month_style_paged_summary">Ein Monat füllt den Bildschirm. Wische nach links oder rechts, um den Monat zu wechseln.</string>
|
||||
<string name="month_style_continuous">Fortlaufende Monate</string>
|
||||
<string name="month_style_continuous_summary">Jeder Monat steht unter seiner eigenen Überschrift, mit etwas Abstand zum nächsten.</string>
|
||||
<string name="month_style_dense">Nahtlose Wochen</string>
|
||||
@@ -727,40 +727,4 @@
|
||||
<string name="settings_visible_hours">Sichtbare Stunden</string>
|
||||
<string name="settings_visible_hours_start">Von</string>
|
||||
<string name="settings_visible_hours_end">Bis</string>
|
||||
<string name="month_open_week">Woche %1$d öffnen</string>
|
||||
<string name="month_split_clear_filter">Zeig die Agenda des ganzen Monats</string>
|
||||
<string name="event_resize_done">Zu %1$s geändert</string>
|
||||
<string name="event_selection_actions">Termin Aktionen</string>
|
||||
<string name="event_selection_hide">Termin Aktionen verstecken</string>
|
||||
<string name="event_selection_close">Termin abwählen</string>
|
||||
<string name="event_draft_discard">Neuen Termin verwerfen</string>
|
||||
<string name="event_action_load_failed">Termin konnte nicht geöffnet werden</string>
|
||||
<string name="event_edit_unsaved_title">Ungespeicherte Änderungen</string>
|
||||
<string name="event_edit_unsaved_save">Änderungen speichern</string>
|
||||
<string name="event_edit_unsaved_discard">Änderungen verwerfen</string>
|
||||
<string name="event_edit_create">Erstellen</string>
|
||||
<string name="event_detail_open_in_maps">In Maps öffnen</string>
|
||||
<string name="settings_theme_black_summary">Dunkel mit schwarzem Hintergrund, für AMOLED Bildschirme</string>
|
||||
<string name="settings_multi_day_count">Mehrtagesansicht</string>
|
||||
<string name="settings_multi_day_count_hint">Bestimmt, wie viele Tage in der Mehrtagesansicht angezeigt werden sollen. Die erste Spalte ist immer der aktuelle Tag.</string>
|
||||
<string name="settings_timeline_scale_by_visible_hours">Durch sichtbares Zeitfenster bestimmt</string>
|
||||
<string name="settings_visible_hours_summary">Zeigt in Wochen-, Mehrtages- und Tagesansicht anstatt aller Stunden ein bestimmtes Zeitfenster an</string>
|
||||
<string name="settings_visible_hours_on_summary">Ansicht zeigt nur Zeit von %1$s bis %2$s</string>
|
||||
<string name="settings_visible_hours_start_hint">Die Stunde am oberen Bildschirmrand, wenn die Wochen-, Mehrtages- oder Tagesansicht geöffnet wird. Frühere Stunden können durch Scrollen erreicht werden.</string>
|
||||
<string name="settings_visible_hours_end_hint">Die Stunde am unteren Bildschirmrand, wenn eine Ansicht geöffnet wird. Spätere Stunden erreichst du weiterhin durch Scrollen, und das Zoomen per Pinch-Geste bleibt bestehen, bis die Ansicht erneut geöffnet wird.</string>
|
||||
<string name="settings_events_header">Termine</string>
|
||||
<string name="settings_tap_opens">Aktion beim Tippen auf einen Termin</string>
|
||||
<string name="settings_tap_opens_details">Details</string>
|
||||
<string name="settings_tap_opens_editor">Termin-Formular</string>
|
||||
<string name="settings_tap_opens_hint">Termine, die nicht bearbeitet werden können, und Erinnerungsbenachrichtigungen öffnen immer die Details.</string>
|
||||
<string name="settings_support_kofi_hint">Einmalige Spenden</string>
|
||||
<string name="settings_support_liberapay_hint">Regelmäßige Spenden</string>
|
||||
<string name="process_text_create_event">Termin erstellen</string>
|
||||
<string name="settings_support_kofi">Ko-fi</string>
|
||||
<string name="settings_support_liberapay">Liberapay</string>
|
||||
<string name="event_resize_recurring_title">Wiederkehrenden Termin verschieben</string>
|
||||
<string name="event_draft_create">Neuen Termin erstellen</string>
|
||||
<string name="event_edit_more_actions">Weitere Aktionen</string>
|
||||
<string name="event_edit_unsaved_keep">Weiter bearbeiten</string>
|
||||
<string name="settings_theme_black">Zurück</string>
|
||||
</resources>
|
||||
@@ -374,7 +374,7 @@
|
||||
<string name="settings_special_dates_type_anniversary">Anniversaires</string>
|
||||
<string name="settings_special_dates_type_custom">Autres dates</string>
|
||||
<string name="settings_special_dates_template">Format du titre</string>
|
||||
<string name="settings_special_dates_template_hint">Utilisez {name} pour le nom et {year} pour l’année (celle de naissance ou celle du début d’un anniversaire ; masqué si inconnu).</string>
|
||||
<string name="settings_special_dates_template_hint">Utilisez {name} pour le nom et {year} pour l’année (celle de naissance ou celle du début d’un anniversaire ; masqué si inconnu).</string>
|
||||
<string name="settings_special_dates_show_year">Montrer l\'année</string>
|
||||
<string name="settings_special_dates_show_year_hint">Inclure {year} dans les titres lorsque l\'année est connue</string>
|
||||
<string name="settings_special_dates_sync_now">Synchroniser maintenant</string>
|
||||
@@ -412,7 +412,7 @@
|
||||
<string name="calendars_edit_title">Editer un agenda</string>
|
||||
<string name="calendars_name_label">Nom</string>
|
||||
<string name="calendars_description_hint">Ajouter une description</string>
|
||||
<string name="calendars_delete_confirm_title">Supprimer ce calendrier ?</string>
|
||||
<string name="calendars_delete_confirm_title">Supprimer ce calendrier ?</string>
|
||||
<string name="calendars_delete_confirm_message">\"%1$s\" et tous ses événements seront définitivement retirés de cet appareil.</string>
|
||||
<string name="calendars_write_error">Impossible de sauvegarder les changements.</string>
|
||||
<string name="calendars_backup_hint">Les calendriers locaux ne sont synchronisés nulle part, alors exportez-les vers un fichier .ics pour en garder une copie.</string>
|
||||
@@ -515,16 +515,16 @@
|
||||
<string name="event_edit_timezone_all">Toutes les zones horaire</string>
|
||||
<string name="event_edit_timezone_none">Aucune zone horaire ne correspond à “%1$s”</string>
|
||||
<string name="event_edit_recurrence_incomplete">Entrez un nombre entre 1 et 999</string>
|
||||
<string name="event_edit_recurrence_next">Prochain : %1$s</string>
|
||||
<string name="event_edit_recurrence_next">Prochain : %1$s</string>
|
||||
<string name="event_detail_title">Titre</string>
|
||||
<string name="event_access_private_summary">Les autres ne voient seulement que vous êtes occupé</string>
|
||||
<string name="event_access_confidential_summary">Marqué confidentiel ; ce que cela veut dire est au bon vouloir de votre compte de calendrier</string>
|
||||
<string name="event_access_confidential_summary">Marqué confidentiel ; ce que cela veut dire est au bon vouloir de votre compte de calendrier</string>
|
||||
<string name="reminder_after">%1$s après</string>
|
||||
<string name="duration_custom_max">Au plus %1$s</string>
|
||||
<string name="onboarding_step_counter">Étape %1$d sur %2$d</string>
|
||||
<string name="settings_today_toolbar_summary">Afficher un bouton pour revenir au jour présent dans la barre d\'outils au lieu d\'un bouton flottant</string>
|
||||
<string name="settings_app_name">Nom de l\'application</string>
|
||||
<string name="settings_app_name_summary">Afficher Calendula comme \"Calendrier\" dans votre lanceur d\'applications. Le nom change seulement dans le lanceur ; l\'icône pourrait changer d\'emplacement après le renommage.</string>
|
||||
<string name="settings_app_name_summary">Afficher Calendula comme \"Calendrier\" dans votre lanceur d\'applications. Le nom change seulement dans le lanceur ; l\'icône pourrait changer d\'emplacement après le renommage.</string>
|
||||
<string name="settings_timeline_scale">Hauteur d\'une heure</string>
|
||||
<string name="timeline_scale_fit_day">Remplir complètement</string>
|
||||
<string name="timeline_scale_fit_day_summary">Affiche les 24 heures à l\'écran, pas de défilement</string>
|
||||
@@ -551,15 +551,15 @@
|
||||
<string name="event_access_public_summary">Toute personne ayant accès voit tous les détails</string>
|
||||
<string name="duration_hours_minutes">%1$s:%2$s</string>
|
||||
<string name="onboarding_backup_title">Vos événements ne sont accessibles qu\'ici</string>
|
||||
<string name="onboarding_backup_body">Aucune synchronisation n\'existe sur ce téléphone : le perdre signifierait perdre votre calendrier. Calendula peut faire des sauvegardes pour vous.</string>
|
||||
<string name="onboarding_backup_body">Aucune synchronisation n\'existe sur ce téléphone : le perdre signifierait perdre votre calendrier. Calendula peut faire des sauvegardes pour vous.</string>
|
||||
<string name="onboarding_backup_benefit_folder_title">Un dossier que vous choisissez</string>
|
||||
<string name="onboarding_backup_benefit_folder_body">Les sauvegardes sont juste des fichiers .ics — enregistrez-les dans un dossier synchronisé, ou bien sur une carte SD.</string>
|
||||
<string name="onboarding_backup_benefit_daily_title">Une fois par jour, automatiquement</string>
|
||||
<string name="onboarding_backup_benefit_daily_body">Calendula exporte vos calendriers locaux en arrière-plan. Changez la fréquence dans les réglages.</string>
|
||||
<string name="onboarding_backup_enable_button">Choisissez un dossier et sauvegarder</string>
|
||||
<string name="onboarding_backup_skip_button">Pas pour l\'instant</string>
|
||||
<string name="onboarding_view_title">Que doit s\'afficher en premier ?</string>
|
||||
<string name="onboarding_month_style_title">À quoi doivent ressembler les mois ?</string>
|
||||
<string name="onboarding_view_title">Que doit s\'afficher en premier ?</string>
|
||||
<string name="onboarding_month_style_title">À quoi doivent ressembler les mois ?</string>
|
||||
<string name="onboarding_view_continue_button">Continuer</string>
|
||||
<string name="onboarding_back">Retour</string>
|
||||
<string name="onboarding_visibility_button">Compris</string>
|
||||
@@ -579,9 +579,9 @@
|
||||
<string name="search_select_all">Tout sélectionner</string>
|
||||
<string name="search_delete_selected">Supprimer la sélection</string>
|
||||
<plurals name="search_delete_title">
|
||||
<item quantity="one">Supprimer %d événement ?</item>
|
||||
<item quantity="many">Supprimer %d événements ?</item>
|
||||
<item quantity="other">Supprimer %d événements ?</item>
|
||||
<item quantity="one">Supprimer %d événement ?</item>
|
||||
<item quantity="many">Supprimer %d événements ?</item>
|
||||
<item quantity="other">Supprimer %d événements ?</item>
|
||||
</plurals>
|
||||
<plurals name="search_delete_done">
|
||||
<item quantity="one">%d événement supprimé</item>
|
||||
@@ -595,9 +595,9 @@
|
||||
<string name="settings_font_specimen_heading">Jeudi 14 mai</string>
|
||||
<string name="settings_font_specimen_body">Revue d\'équipe à 10h00, puis déjeuner avec Robin au café de la Place du Marché.</string>
|
||||
<string name="settings_week_start_auto_summary">Actuellement %1$s</string>
|
||||
<string name="settings_today_toolbar">Bouton « aujourd\'hui » dans la barre d\'outils</string>
|
||||
<string name="settings_time_format_auto_summary">Suivant le système : %1$s</string>
|
||||
<string name="settings_timeline_scale_hint">Espace vertical occupé par une heure dans les vues « Semaine » et « Jour ». Ce paramètre s\'applique aux deux vues. Vous pouvez également étirer l\'affichage avec deux doigts pour utiliser n\'importe quelle hauteur.</string>
|
||||
<string name="settings_today_toolbar">Bouton « aujourd\'hui » dans la barre d\'outils</string>
|
||||
<string name="settings_time_format_auto_summary">Suivant le système : %1$s</string>
|
||||
<string name="settings_timeline_scale_hint">Espace vertical occupé par une heure dans les vues « Semaine » et « Jour ». Ce paramètre s\'applique aux deux vues. Vous pouvez également étirer l\'affichage avec deux doigts pour utiliser n\'importe quelle hauteur.</string>
|
||||
<string name="settings_widget_size_hint">Taille du texte affiché par le widget d\'agenda sur l\'écran d\'accueil. Le widget mensuel n\'a pas ce réglage — sa grille s\'adapte toujours à l\'espace que vous lui allouez.</string>
|
||||
<string name="settings_widget_size_small">Petit</string>
|
||||
<string name="settings_widget_size_medium">Moyen</string>
|
||||
@@ -637,7 +637,7 @@
|
||||
<string name="settings_week_day_header">Semaine & jour</string>
|
||||
<string name="settings_default_view_hint">La vue ouverte par Calendula au démarrage.</string>
|
||||
<string name="settings_week_start_hint">Le jour par lequel chaque semaine commence, dans toutes les vues et widgets.</string>
|
||||
<string name="settings_time_format_hint">Format d\'affichage de l\'heure dans l\'application. Le format « Automatique » suit les paramètres de votre système.</string>
|
||||
<string name="settings_time_format_hint">Format d\'affichage de l\'heure dans l\'application. Le format « Automatique » suit les paramètres de votre système.</string>
|
||||
<string name="settings_past_events_hint">Comment l\'agenda gère les événements déjà terminés.</string>
|
||||
<string name="settings_dynamic_color_summary">Les couleurs de l\'application proviennent de votre fond d\'écran.</string>
|
||||
<string name="settings_licences">Licences open source</string>
|
||||
@@ -646,16 +646,16 @@
|
||||
<string name="licences_title">Licences open source</string>
|
||||
<string name="licences_intro">Calendula comprend les projets ci-dessous. Appuyez sur n\'importe quelle entrée pour afficher son code source.</string>
|
||||
<string name="licences_footer">Chaque projet présenté ici est inclus tel quel, sans modifications, sous la licence indiquée.</string>
|
||||
<string name="calendars_visibility_hint">Désactivez un calendrier pour le masquer sur cet appareil : ses événements disparaîtront de l\'application et vous ne recevrez plus de rappels. Il s\'agit du même bouton que celui utilisé par vos autres applications de calendrier, ce qui signifie qu\'il sera aussi masqué sur ces dernières. Rien n\'est supprimé, aucun autre appareil n\'est affecté et vous pouvez le réactiver ici à tout moment.</string>
|
||||
<string name="calendars_visibility_hint">Désactivez un calendrier pour le masquer sur cet appareil : ses événements disparaîtront de l\'application et vous ne recevrez plus de rappels. Il s\'agit du même bouton que celui utilisé par vos autres applications de calendrier, ce qui signifie qu\'il sera aussi masqué sur ces dernières. Rien n\'est supprimé, aucun autre appareil n\'est affecté et vous pouvez le réactiver ici à tout moment.</string>
|
||||
<string name="calendars_visibility_a11y">Montrer \"%1$s\"</string>
|
||||
<string name="calendars_visibility_notice_title">Certains calendriers sont masqués</string>
|
||||
<string name="calendars_visibility_notice_message">Calendula affiche les calendriers activés pour cet appareil, et certains des vôtres sont désactivés. Pour voir leurs événements, activez-les dans Réglages → Calendriers.</string>
|
||||
<string name="calendar_picker_missing_title">Il vous manque un calendrier ?</string>
|
||||
<string name="calendar_picker_missing_title">Il vous manque un calendrier ?</string>
|
||||
<string name="calendar_picker_missing_summary">Il est peut-être désactivé, en lecture seule ou rempli à partir de vos contacts — gérez vos calendriers ici.</string>
|
||||
<string name="calendars_state_read_only">Lecture seule</string>
|
||||
<string name="calendars_state_not_synced">Non synchronisé avec cet appareil</string>
|
||||
<string name="calendars_state_managed">Rempli à partir de vos contacts</string>
|
||||
<string name="calendars_managed_delete_locked">Ce calendrier est rempli à partir de vos contacts ; Calendula le recréera donc lors de la prochaine synchronisation. Pour le supprimer, désactivez les dates spéciales dans Paramètres → Dates spéciales.</string>
|
||||
<string name="calendars_managed_delete_locked">Ce calendrier est rempli à partir de vos contacts ; Calendula le recréera donc lors de la prochaine synchronisation. Pour le supprimer, désactivez les dates spéciales dans Paramètres → Dates spéciales.</string>
|
||||
<string name="calendars_account_from_source">%1$s (%2$s)</string>
|
||||
<string name="import_done_failed_label">Non ajouté</string>
|
||||
<string name="import_done_failed_note">Certains événements n\'ont pas pu être ajoutés et ont donc été omis.</string>
|
||||
|
||||
@@ -244,7 +244,7 @@
|
||||
<string name="settings_time_format_12h">12 ore</string>
|
||||
<string name="settings_time_format_24h">24 ore</string>
|
||||
<string name="settings_hour_lines">Grglia oraria</string>
|
||||
<string name="settings_hour_lines_summary">Mostra una linea di separazione per ogni ora in una cella a sé stante nella visualizzazione settimanale e giornaliera</string>
|
||||
<string name="settings_hour_lines_summary">Mostra una riga separatrice per ogni ora nella vista Settimana e Giorno</string>
|
||||
<string name="settings_dim_completed">Attenua gli eventi completati</string>
|
||||
<string name="settings_dim_completed_summary">Attenua gli eventi conclusi nella vista Mese e Settimana</string>
|
||||
<string name="settings_past_events">Eventi passati</string>
|
||||
@@ -422,7 +422,7 @@
|
||||
<string name="settings_font_import_failed">Impossibile leggere il file come font</string>
|
||||
<string name="settings_section_views">Vista</string>
|
||||
<string name="settings_quick_switch_header">Pulsante di cambio rapido</string>
|
||||
<string name="settings_quick_switch_hint">Scegli attraverso quali viste scorrere col pulsante in alto a destra, trascinale per riordinarle. Se sono attive meno di due schermate, il pulsante viene nascosto. Le viste disattivate rimangono accessibili dal menu di navigazione.</string>
|
||||
<string name="settings_quick_switch_hint">Scegli attraverso quali viste scorrere col pulsante in alto a destra, trascinale per riordinarle. Le viste disattivate rimangono raggiungibili dal menù di navigazione.</string>
|
||||
<string name="settings_drawer_order_header">Menù di navigazione</string>
|
||||
<string name="settings_drawer_order_hint">Trascina per riordinare le viste elencate nel menù di navigazione.</string>
|
||||
<string name="reorder_drag_handle">Trascina per riordinare</string>
|
||||
@@ -551,14 +551,12 @@
|
||||
<string name="search_select_all">Seleziona tutti</string>
|
||||
<string name="search_delete_selected">Elimina i selezionati</string>
|
||||
<plurals name="search_delete_title">
|
||||
<item quantity="one">Eliminare %d l\'evento?</item>
|
||||
<item quantity="many">Eliminare %d gli eventi?</item>
|
||||
<item quantity="other">Eliminare %d eventi?</item>
|
||||
<item quantity="one">Eliminare l\'evento?</item>
|
||||
<item quantity="other">Eliminare l\'evento?</item>
|
||||
</plurals>
|
||||
<plurals name="search_delete_done">
|
||||
<item quantity="one">%d evento eliminato</item>
|
||||
<item quantity="many">%d eventi eliminati</item>
|
||||
<item quantity="other">%d eventi eliminati</item>
|
||||
<item quantity="one">Evento eliminato</item>
|
||||
<item quantity="other">Evento eliminato</item>
|
||||
</plurals>
|
||||
<string name="search_delete_partial">%1$d eliminati, %2$d no</string>
|
||||
<string name="search_delete_denied_partial">%1$d eliminati, poi permessi di scrittura negati</string>
|
||||
@@ -600,7 +598,7 @@
|
||||
<string name="settings_month_header">Vista Mese</string>
|
||||
<string name="settings_month_view_style">Stile vista Mese</string>
|
||||
<string name="month_style_paged">Pagine</string>
|
||||
<string name="month_style_paged_summary">Viene mostrato un singolo mese. Scorri a destra o a sinistra per cambiare mese oppure scorri verso l\'alto per visualizzare l\'agenda mensile.</string>
|
||||
<string name="month_style_paged_summary">Viene mostrato un singolo mese. Scorri a destra o a sinistra per cambiare mese.</string>
|
||||
<string name="month_style_continuous">Scorrimento</string>
|
||||
<string name="settings_past_events_hint">Ciò che fa l\'Agenda con eventi conclusi.</string>
|
||||
<string name="settings_dynamic_color_summary">Deduci il colore dell\'app dallo sfondo.</string>
|
||||
@@ -698,9 +696,9 @@
|
||||
<string name="onboarding_calendars_create_failed">Impossibile creare il calendario. La memoria del calendario del tuo telefono non lo ha accettato.</string>
|
||||
<string name="reminder_day_today">Oggi</string>
|
||||
<plurals name="view_multi_day">
|
||||
<item quantity="one">%d giorno</item>
|
||||
<item quantity="many">%d giorni</item>
|
||||
<item quantity="other">%d giorni</item>
|
||||
<item quantity="one">Giorno</item>
|
||||
<item quantity="many">Giorni</item>
|
||||
<item quantity="other">Giorno</item>
|
||||
</plurals>
|
||||
<string name="settings_multi_day_count">Visualizzazione su più giorni</string>
|
||||
<string name="settings_multi_day_count_hint">La vista più giorni mostra, affiancati, i giorni. La data odierna è visualizzata nella prima colonna.</string>
|
||||
@@ -738,30 +736,4 @@
|
||||
<item quantity="many">Non è stato possibile aggiungere gli eventi %d.</item>
|
||||
<item quantity="other">Non è stato possibile aggiungere l\'evento %d.</item>
|
||||
</plurals>
|
||||
<string name="event_draft_create">Crea evento</string>
|
||||
<string name="event_draft_discard">Scarta nuovo evento</string>
|
||||
<string name="event_action_load_failed">Impossibile aprire l\'evento</string>
|
||||
<string name="event_selection_close">Deseleziona evento</string>
|
||||
<string name="event_edit_more_actions">Più azioni</string>
|
||||
<string name="event_edit_unsaved_title">Modifiche non salvate</string>
|
||||
<string name="event_edit_unsaved_save">Salva modifiche</string>
|
||||
<string name="event_edit_unsaved_discard">Scarta modifiche</string>
|
||||
<string name="event_edit_unsaved_keep">Continua a modificare</string>
|
||||
<string name="event_edit_create">Crea</string>
|
||||
<string name="event_resize_done">Modificato in %1$s</string>
|
||||
<string name="event_resize_recurring_title">Modifica evento ricorrente</string>
|
||||
<string name="event_selection_actions">Azioni evento</string>
|
||||
<string name="event_selection_hide">Nascondi azioni evento</string>
|
||||
<string name="settings_theme_black">Nero</string>
|
||||
<string name="settings_theme_black_summary">Scuro con sfondi completamente neri, per schermi AMOLED</string>
|
||||
<string name="settings_events_header">Eventi</string>
|
||||
<string name="settings_tap_opens">Cliccando su un evento si apre</string>
|
||||
<string name="settings_tap_opens_details">Dettagli</string>
|
||||
<string name="settings_tap_opens_editor">Modifica modulo</string>
|
||||
<string name="settings_tap_opens_hint">Gli eventi che non è possibile modificare e le notifiche di promemoria, aprono sempre la pagina dei dettagli.</string>
|
||||
<string name="settings_support_kofi">Ko-fi</string>
|
||||
<string name="settings_support_kofi_hint">Contributi una tantum</string>
|
||||
<string name="settings_support_liberapay">Liberapay</string>
|
||||
<string name="settings_support_liberapay_hint">Donazioni ricorrenti</string>
|
||||
<string name="process_text_create_event">Crea evento</string>
|
||||
</resources>
|
||||
@@ -716,30 +716,4 @@
|
||||
<string name="settings_visible_hours_end">Tot</string>
|
||||
<string name="settings_visible_hours_start_hint">Het uur bovenaan het scherm bij het openen van de week-, meerdaagse of dagweergave. Eerdere uren blijven bereikbaar door te scrollen.</string>
|
||||
<string name="settings_visible_hours_end_hint">Het uur onderaan het scherm bij het openen van een weergave. Latere uren blijven bereikbaar door te scrollen, en in- of uitzoomen met twee vingers geldt totdat de weergave opnieuw wordt geopend.</string>
|
||||
<string name="event_resize_done">Gewijzigd naar %1$s</string>
|
||||
<string name="event_resize_recurring_title">Terugkerende gebeurtenis wijzigen</string>
|
||||
<string name="event_selection_actions">Acties voor gebeurtenis</string>
|
||||
<string name="event_selection_hide">Acties voor gebeurtenis verbergen</string>
|
||||
<string name="event_selection_close">Selectie van gebeurtenis opheffen</string>
|
||||
<string name="event_draft_create">Gebeurtenis maken</string>
|
||||
<string name="event_draft_discard">Nieuwe gebeurtenis verwerpen</string>
|
||||
<string name="event_action_load_failed">Kan de gebeurtenis niet openen</string>
|
||||
<string name="event_edit_more_actions">Meer acties</string>
|
||||
<string name="event_edit_unsaved_title">Niet-opgeslagen wijzigingen</string>
|
||||
<string name="event_edit_unsaved_save">Wijzigingen opslaan</string>
|
||||
<string name="event_edit_unsaved_discard">Wijzigingen verwerpen</string>
|
||||
<string name="event_edit_unsaved_keep">Verder bewerken</string>
|
||||
<string name="event_edit_create">Maken</string>
|
||||
<string name="settings_theme_black">Zwart</string>
|
||||
<string name="settings_theme_black_summary">Donker met volledig zwarte achtergronden, voor AMOLED-schermen</string>
|
||||
<string name="settings_events_header">Gebeurtenissen</string>
|
||||
<string name="settings_tap_opens">Tikken op een gebeurtenis opent</string>
|
||||
<string name="settings_tap_opens_details">Details</string>
|
||||
<string name="settings_tap_opens_editor">Bewerkformulier</string>
|
||||
<string name="settings_tap_opens_hint">Gebeurtenissen die je niet kunt bewerken en meldingen van herinneringen openen altijd de details.</string>
|
||||
<string name="settings_support_kofi">Ko-fi</string>
|
||||
<string name="settings_support_kofi_hint">Eenmalige bijdragen</string>
|
||||
<string name="settings_support_liberapay">Liberapay</string>
|
||||
<string name="settings_support_liberapay_hint">Terugkerende donaties</string>
|
||||
<string name="process_text_create_event">Gebeurtenis maken</string>
|
||||
</resources>
|
||||
@@ -1,28 +0,0 @@
|
||||
<?xml version="1.0" encoding="utf-8"?>
|
||||
<resources>
|
||||
<string-array name="backup_interval_units">
|
||||
<item>Minutes</item>
|
||||
<item>Hours</item>
|
||||
<item>Days</item>
|
||||
<item>Weeks</item>
|
||||
</string-array>
|
||||
<string name="app_tagline">一個現代的行事曆。</string>
|
||||
<string name="app_name_calendar_alias">行事曆</string>
|
||||
<string name="state_loading">加載中……</string>
|
||||
<string name="state_retry">重試</string>
|
||||
<string name="state_failure_unknown">出錯了。</string>
|
||||
<string name="state_failure_permission">需使用行事曆。</string>
|
||||
<string name="state_failure_permission_body">Calendula會直接從系統行事曆讀取你的活動,即需要有行事曆存取才能顯示行程。</string>
|
||||
<string name="state_failure_permission_action">授權進入</string>
|
||||
<string name="state_failure_no_calendars">無設定行事曆。</string>
|
||||
<string name="state_failure_no_calendars_body">在這台裝置新增行事曆帳號,行程將會顯示在這。</string>
|
||||
<string name="state_failure_no_calendars_action">開放系統行事曆設定</string>
|
||||
<string name="state_failure_all_hidden">你所有的行事曆都關閉了。</string>
|
||||
<string name="state_failure_all_hidden_body">至少開啟一項行事曆以查看其活動。</string>
|
||||
<string name="state_failure_all_hidden_action">管理行事曆</string>
|
||||
<string name="state_failure_no_import_target">沒有一個行事曆能加入新行程。</string>
|
||||
<string name="state_failure_no_import_target_body">被開啟的行事曆是唯讀的、由其他應用程式管理,或未與此裝置同步。開啟一個可以記錄活動的行事曆或新增一個本地活動。</string>
|
||||
<string name="state_failure_event_not_found">該事項已不存在。</string>
|
||||
<string name="state_failure_event_not_found_body">可能被刪除或被關閉。</string>
|
||||
<string name="state_failure_provider">無法識別該行事曆。</string>
|
||||
</resources>
|
||||
@@ -110,11 +110,7 @@
|
||||
<string name="event_move_failed">Couldn\'t move the event</string>
|
||||
<string name="event_move_write_denied">Calendula needs write access to move events</string>
|
||||
<string name="event_move_gone">That event no longer exists</string>
|
||||
<string name="event_move_stale">That event moved before your drop could be saved</string>
|
||||
<string name="event_move_queue_full">Too many moves at once, so that one wasn\'t saved</string>
|
||||
<string name="event_move_skipped">Moves made while the question was open weren\'t saved</string>
|
||||
<string name="event_move_blocked_series_end">Can\'t move an event past the end of its series</string>
|
||||
<string name="event_move_blocked_cancelled_series">A cancelled series can only move as a whole, and this would change which days it falls on</string>
|
||||
|
||||
<string name="dialog_cancel">Cancel</string>
|
||||
<string name="dialog_ok">OK</string>
|
||||
@@ -520,15 +516,6 @@
|
||||
<string name="widget_config_background_tinted">Tinted</string>
|
||||
<string name="widget_config_background_transparent">Transparent</string>
|
||||
<string name="widget_config_theme_follow_app">Follow app</string>
|
||||
<string name="widget_config_opacity">Opacity</string>
|
||||
<string name="widget_config_invert_text">Invert text colour</string>
|
||||
<string name="widget_config_invert_text_summary">Light text on a dark theme turns dark, and the other way round</string>
|
||||
<string name="widget_config_readability_info">About readability</string>
|
||||
<string name="widget_config_readability_hint">At low opacity the wallpaper shows through, so some text may be harder to read. Raise the opacity if it is.</string>
|
||||
<string name="widget_config_readability_hint_classic">At low opacity the wallpaper shows through, so some text may be hard to read. If it is, raise the opacity or invert the text colour.</string>
|
||||
<string name="widget_config_style">Style</string>
|
||||
<string name="widget_config_style_cards">Cards</string>
|
||||
<string name="widget_config_style_classic">Classic</string>
|
||||
<string name="widget_config_content">Content</string>
|
||||
<string name="widget_config_range">Time range</string>
|
||||
<string name="widget_config_text_size">Text size</string>
|
||||
@@ -590,8 +577,6 @@
|
||||
<string name="settings_week_start_auto_summary">Currently %1$s</string>
|
||||
<string name="settings_week_numbers">Week numbers</string>
|
||||
<string name="settings_week_numbers_summary">Show calendar-week numbers in month view</string>
|
||||
<string name="settings_month_start_times">Start times</string>
|
||||
<string name="settings_month_start_times_summary">Show the start time before an event\'s title when there is room</string>
|
||||
<string name="settings_today_toolbar">Today button in toolbar</string>
|
||||
<string name="settings_today_toolbar_summary">Show a jump-to-today button in the toolbar instead of a floating button</string>
|
||||
<string name="settings_app_name">App name</string>
|
||||
@@ -731,56 +716,8 @@
|
||||
<string name="reminder_custom_amount">Amount</string>
|
||||
<string name="reminder_custom_set">Set</string>
|
||||
<string name="settings_calendar_reminders_title">Per-calendar reminders</string>
|
||||
<string name="settings_calendar_reminders_hint">Turn notifications off or pick a sound per calendar, and override the default reminder for calendars you can edit.</string>
|
||||
<string name="settings_calendar_notifications">Notifications</string>
|
||||
<string name="settings_calendar_notifications_hint">Notify at this calendar\'s reminder times</string>
|
||||
<string name="settings_calendar_notifications_off">Notifications off</string>
|
||||
<string name="settings_calendar_reminders_off">Reminders off</string>
|
||||
<string name="settings_notification_sound">Notification sound</string>
|
||||
<string name="settings_notification_sound_hint">Sound, vibration and pop-ups for each calendar, in system settings</string>
|
||||
<string name="settings_notifications_blocked">Blocked in system settings</string>
|
||||
<string name="settings_notifications_blocked_hint">Blocked in system settings — tap to allow</string>
|
||||
<string name="settings_notification_category_hint">On Samsung phones, new notification categories can start switched off. If a calendar\'s reminders don\'t arrive, check that its category is on.</string>
|
||||
<string name="settings_notification_category_hint_open">Open settings</string>
|
||||
<string name="settings_calendar_notification_sound_hint">Sound, vibration and pop-ups for this calendar, in system settings</string>
|
||||
<string name="settings_calendar_reminders_hint">Override the default per calendar — separately for timed and all-day events. A calendar can keep the default, drop it, or set its own.</string>
|
||||
<string name="settings_calendar_reminder_inherits">Default (%1$s)</string>
|
||||
<!-- Reminders at a set time (#459). %1$s is a lead in days ("1 day before"), %2$s a clock time. -->
|
||||
<string name="reminder_fixed_time">%1$s at %2$s</string>
|
||||
<string name="reminder_fixed_at_set_time">At a set time</string>
|
||||
<!-- Read as one sentence with a number field before it and a time after it: "[2] days before, at [20:00]". The full wording shows below it. -->
|
||||
<string name="reminder_fixed_days_before_at">days before, at</string>
|
||||
<string name="reminder_fixed_days_range">Pick 1 to %1$d days</string>
|
||||
<string name="settings_fixed_reminder">Reminder at a set time</string>
|
||||
<string name="event_edit_reminder_fixed_summary">E.g. the evening before</string>
|
||||
<string name="event_edit_reminder_fixed_hint">Fires at this time however early or late the event starts, and moves along when you change the event\'s time.</string>
|
||||
<string name="settings_fixed_reminder_hint">Added to new timed events, e.g. the evening before. It follows the event when you move it to another time.</string>
|
||||
<!-- Daily summary notification (#459) -->
|
||||
<string name="settings_digest">Daily summary</string>
|
||||
<string name="settings_digest_hint">One notification listing a day\'s events</string>
|
||||
<!-- %1$s is settings_digest_day_today/tomorrow, %2$s a clock time. -->
|
||||
<string name="settings_digest_summary">%1$s at %2$s</string>
|
||||
<string name="settings_digest_day">Lists</string>
|
||||
<string name="settings_digest_day_today">Today\'s events</string>
|
||||
<string name="settings_digest_day_tomorrow">Tomorrow\'s events</string>
|
||||
<string name="settings_digest_time">Time</string>
|
||||
<string name="settings_digest_sound_hint">Sound and pop-up for the summary, in system settings</string>
|
||||
<string name="settings_calendar_in_digest">In daily summary</string>
|
||||
<string name="settings_calendar_in_digest_hint">List this calendar\'s events in the daily summary</string>
|
||||
<string name="digest_channel_name">Daily summary</string>
|
||||
<string name="digest_channel_description">One notification listing a day\'s events</string>
|
||||
<!-- %1$s is "Today", "Tomorrow" or a date; %2$d the number of events. -->
|
||||
<plurals name="digest_title">
|
||||
<item quantity="one">%1$s: %2$d event</item>
|
||||
<item quantity="other">%1$s: %2$d events</item>
|
||||
</plurals>
|
||||
<!-- %1$s is "Today" or "Tomorrow", %2$s a short date, e.g. "Fri, 14 Nov". -->
|
||||
<string name="digest_day_relative">%1$s, %2$s</string>
|
||||
<!-- One event in the summary: %1$s its time ("09:00 – 10:00" or "All day"), %2$s its title. -->
|
||||
<string name="digest_line">%1$s · %2$s</string>
|
||||
<plurals name="digest_more">
|
||||
<item quantity="one">+%d more</item>
|
||||
<item quantity="other">+%d more</item>
|
||||
</plurals>
|
||||
<string name="settings_reliable_delivery">Reliable delivery</string>
|
||||
<string name="settings_reliable_delivery_hint">Android may delay reminders to save battery. Exempt Calendula so they arrive on time.</string>
|
||||
<string name="settings_reliable_delivery_exempt">Exempt from battery optimisation — reminders arrive on time.</string>
|
||||
|
||||
@@ -24,5 +24,4 @@
|
||||
<locale android:name="ru" />
|
||||
<locale android:name="sk" />
|
||||
<locale android:name="zh-CN" />
|
||||
<locale android:name="zh-TW" />
|
||||
</locale-config>
|
||||
@@ -1147,18 +1147,6 @@ class EventWriteMapperTest {
|
||||
assertThat(values).containsEntry(CalendarContract.Events.STATUS, CalendarContract.Events.STATUS_TENTATIVE)
|
||||
}
|
||||
|
||||
@Test
|
||||
fun `no new row is written cancelled`() {
|
||||
val cancelled = form().copy(status = EventStatus.Cancelled)
|
||||
assertThat(buildEventInsertValues(cancelled, "uid", cancelled.toWriteTimes(berlin)))
|
||||
.doesNotContainKey(CalendarContract.Events.STATUS)
|
||||
assertThat(buildOccurrenceExceptionValues(cancelled, originalInstanceMillis = 0L, zone = berlin))
|
||||
.containsEntry(CalendarContract.Events.STATUS, CalendarContract.Events.STATUS_CONFIRMED)
|
||||
val snapshot = masterSnapshot().copy(status = CalendarContract.Events.STATUS_CANCELED)
|
||||
assertThat(buildMovedMasterValues(snapshot, targetCalendarId = 9L, uid = "u@calendula"))
|
||||
.doesNotContainKey(CalendarContract.Events.STATUS)
|
||||
}
|
||||
|
||||
// --- buildMovedMasterValues (calendar move: verbatim series copy) ---
|
||||
|
||||
private fun masterSnapshot(
|
||||
|
||||
Loaded 100 of 208 files, more files were not shown because too many files have changed in this diff.
Show more
Reference in new issue
Block a user