Merge branch 'feat/19-alarm-set-snackbar' into release/v1.0.0

# Conflicts:
#	app/src/main/java/de/jeanlucmakiola/clockula/ui/alarms/AlarmsScreen.kt
#	docs/ARCHITECTURE.md
This commit is contained in:
makiolaj committed 2026-10-26 20:50:55 +01:00
commit a186e5afcd
12 files changed
+1043 -71

No files matched your search

@@ -0,0 +1,24 @@
package de.jeanlucmakiola.clockula.domain.alarm
import de.jeanlucmakiola.clockula.domain.format.NextFireFormat
import de.jeanlucmakiola.clockula.domain.format.NextFireLabel
import kotlin.time.Instant
/**
* What "Alarm in 7 hours and 12 minutes" says once the user has
* set an alarm, or null when it should say nothing (#19).
*
* Only a natural occurrence is announced. A switched-off alarm will not ring at
* all; a ringing or snoozed one is answering the snooze, not the change the
* user just made, and "Alarm in 9 minutes" would read as a mistake.
*/
object AlarmSetCountdown {
/** Pure. The rounding is [NextFireFormat]'s, so the chip and the row agree. */
fun of(upcoming: UpcomingAlarm?, now: Instant): NextFireLabel? {
// A switched-off alarm resolves to FireSource.NONE, so this one check
// also covers it.
if (upcoming?.source != FireSource.OCCURRENCE) return null
val nextFire = upcoming.nextFire ?: return null
return NextFireFormat.labelFor(nextFire, now)
}
}
@@ -84,6 +84,15 @@ fun AlarmEditorScreen(
onBack = onBack,
modifier = modifier,
predictiveBack = true,
// In the snackbar slot, so it follows the predictive-back preview, and
// lifted over the live pill, which floats above every screen.
snackbarHost = {
AlarmSetChipBand(
notice = viewModel.alarmSetNotice,
onShown = viewModel::onAlarmSetNoticeShown,
modifier = Modifier.padding(bottom = LocalLivePillInset.current),
)
},
actions = {
if (state is AlarmEditorUiState.Editing) {
IconButton(onClick = { confirmingDelete = true }) {
@@ -144,6 +153,9 @@ private fun AlarmEditorContent(
// about losing a half-entered time).
var openPicker by rememberSaveable { mutableStateOf<OpenPicker?>(null) }
var pickingTime by rememberSaveable { mutableStateOf(openTimePicker) }
// True until the picker a new alarm opens on is first closed: cancelling
// that one still leaves a freshly set alarm to announce (#19).
var pickingNewAlarm by rememberSaveable { mutableStateOf(openTimePicker) }
TimeCard(time = editing.time, onClick = { pickingTime = true })
Spacer(Modifier.height(16.dp))
@@ -225,8 +237,13 @@ private fun AlarmEditorContent(
onConfirm = { hour, minute ->
viewModel.onTimePicked(hour, minute)
pickingTime = false
pickingNewAlarm = false
},
onDismiss = {
if (pickingNewAlarm) viewModel.onNewAlarmTimeKept()
pickingTime = false
pickingNewAlarm = false
},
onDismiss = { pickingTime = false },
)
}
when (openPicker) {
@@ -18,14 +18,21 @@ import de.jeanlucmakiola.clockula.ui.common.RingtonePicker
import de.jeanlucmakiola.clockula.ui.common.RingtonePickerUiState
import de.jeanlucmakiola.floret.di.ApplicationScope
import kotlinx.coroutines.CoroutineScope
import kotlinx.coroutines.CoroutineStart
import kotlinx.coroutines.flow.Flow
import kotlinx.coroutines.flow.MutableStateFlow
import kotlinx.coroutines.flow.StateFlow
import kotlinx.coroutines.flow.asStateFlow
import kotlinx.coroutines.flow.collectLatest
import kotlinx.coroutines.flow.combine
import kotlinx.coroutines.flow.map
import kotlinx.coroutines.launch
import kotlinx.coroutines.sync.Mutex
import kotlinx.coroutines.sync.withLock
import java.time.DayOfWeek
import javax.inject.Inject
import kotlin.time.Duration
import kotlin.time.Duration.Companion.seconds
/**
* The editor writes as the user goes: no Save, no dirty state, no discard
@@ -41,6 +48,7 @@ class AlarmEditorViewModel @Inject internal constructor(
private val engine: AlarmEngine,
private val ringtones: RingtoneCatalog,
private val preview: RingtonePreviewer,
private val announcer: AlarmSetAnnouncer,
// `@param:` — the qualifier has no explicit @Target, and K2 resolves a bare
// annotation on a constructor `val` to the property instead.
@param:ApplicationScope private val appScope: CoroutineScope,
@@ -74,6 +82,21 @@ class AlarmEditorViewModel @Inject internal constructor(
/** What the previewer is sounding, so the next preview knows to stop it. */
private var previewing: String? = null
/**
* "Alarm in …" after a change that moves when the alarm rings
* (#19). Nothing for a switched-off alarm, and nothing for the label or the
* sound: those move no fire time. Only ever about *this* alarm — the
* countdown names no alarm, so one about the row the user just switched
* on in the list would read as this one's.
*/
val alarmSetNotice: Flow<AlarmSetNotice?> =
announcer.notice.map { notice -> notice?.takeIf { it.alarmId == alarmId } }
fun onAlarmSetNoticeShown(notice: AlarmSetNotice) = announcer.consumed(notice)
/** Orders [scheduleWrite]s. */
private val scheduleWrites = Mutex()
/** Memoised catalog answers, keyed on URI — see [metaOf]. */
private val ringtoneMeta = mutableMapOf<String, RingtoneMeta>()
@@ -99,9 +122,17 @@ class AlarmEditorViewModel @Inject internal constructor(
/** Clamped, never throws. */
fun onTimePicked(hour: Int, minute: Int) =
edit(reschedule = true) { it.copy(time = TimeOfDay.clamped(hour, minute)) }
edit(reschedule = true, announces = true) { it.copy(time = TimeOfDay.clamped(hour, minute)) }
fun onDayToggled(day: DayOfWeek) = edit(reschedule = true) { alarm ->
/**
* The picker a new alarm opens on was closed without a time. The alarm
* exists and is enabled at its default hour all the same — this is the
* moment it was set, so it is announced (#19).
*/
fun onNewAlarmTimeKept() = announcer.announce(alarmId)
/** Announced once the taps settle: setting Mon–Fri is one chip, not five (#19). */
fun onDayToggled(day: DayOfWeek) = edit(reschedule = true, announces = true, settle = ANNOUNCE_SETTLE) { alarm ->
val days = if (day in alarm.repeatDays) alarm.repeatDays - day else alarm.repeatDays + day
alarm.copy(
repeatDays = days,
@@ -121,9 +152,14 @@ class AlarmEditorViewModel @Inject internal constructor(
}
fun onSkipNextChanged(skip: Boolean) {
viewModelScope.launch {
// Absolute, so it must land in tap order against a day toggle that
// disarms the skip: see [scheduleWrite].
scheduleWrite {
alarms.setSkipNextOccurrence(alarmId, skip)
engine.reschedule()
// Skipping moves the next ring a day or more out, which is exactly
// the kind of jump worth saying out loud.
announcer.announce(alarmId)
}
}
@@ -208,7 +244,7 @@ class AlarmEditorViewModel @Inject internal constructor(
/** Dismisses a ring first (M5 D11), deletes, and the state becomes [AlarmEditorUiState.Gone]. */
fun onDelete() {
viewModelScope.launch {
scheduleWrite {
if (engine.ringSession()?.alarm?.id == alarmId) engine.dismiss(alarmId)
alarms.delete(alarmId)
engine.reschedule()
@@ -235,13 +271,42 @@ class AlarmEditorViewModel @Inject internal constructor(
/**
* Every editor write. [reschedule] is on only for a change that can move a
* fire time — so fiddling with sound settings costs no AlarmManager traffic
* (M5 D12).
* (M5 D12). [announces] is on for the same changes, after [settle] (#19).
*
* A change that moves a fire time runs on the application scope. Pick →
* OK → back is the usual way to set an alarm, and back clears this
* ViewModel: on its own scope the reschedule — and the "Alarm in …"
* the list is meant to pick up — could be cancelled half-way, leaving a
* stored time the system had not been given yet.
*/
private fun edit(reschedule: Boolean = false, transform: (Alarm) -> Alarm) {
viewModelScope.launch {
alarms.edit(alarmId, transform)
if (reschedule) engine.reschedule()
private fun edit(
reschedule: Boolean = false,
announces: Boolean = false,
settle: Duration = Duration.ZERO,
transform: (Alarm) -> Alarm,
) {
if (!reschedule) {
viewModelScope.launch { alarms.edit(alarmId, transform) }
return
}
scheduleWrite {
alarms.edit(alarmId, transform)
engine.reschedule()
if (announces) announcer.announce(alarmId, settle)
}
}
/**
* A write that moves a fire time, its reschedule and whatever follows, on
* the application scope (see [edit]) and **in tap order**: started
* undispatched, each takes its place in [scheduleWrites]' fair queue on the
* caller's thread, before the first suspension. The application scope is
* multi-threaded, so without it "skip next" followed at once by untapping
* the only repeat day could commit out of order, leaving a one-shot with a
* skip armed — which the resolver answers by disabling it (D14).
*/
private fun scheduleWrite(block: suspend () -> Unit) {
appScope.launch(start = CoroutineStart.UNDISPATCHED) { scheduleWrites.withLock { block() } }
}
private suspend fun render(inputs: Inputs): AlarmEditorUiState {
@@ -313,3 +378,6 @@ class AlarmEditorViewModel @Inject internal constructor(
val accessMayLapse: Boolean,
)
}
/** How long the repeat days must stay untouched before the editor says when the alarm rings. */
private val ANNOUNCE_SETTLE: Duration = 1.seconds
@@ -0,0 +1,295 @@
package de.jeanlucmakiola.clockula.ui.alarms
import android.content.res.Resources
import androidx.compose.foundation.layout.BoxWithConstraints
import androidx.compose.foundation.layout.fillMaxHeight
import androidx.compose.foundation.layout.fillMaxWidth
import androidx.compose.foundation.layout.height
import androidx.compose.foundation.layout.padding
import androidx.compose.material3.MaterialTheme
import androidx.compose.runtime.Composable
import androidx.compose.runtime.LaunchedEffect
import androidx.compose.runtime.getValue
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.remember
import androidx.compose.runtime.rememberUpdatedState
import androidx.compose.runtime.setValue
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.platform.LocalAccessibilityManager
import androidx.compose.ui.platform.LocalResources
import androidx.compose.ui.unit.Dp
import androidx.compose.ui.unit.dp
import androidx.lifecycle.Lifecycle
import androidx.lifecycle.compose.LocalLifecycleOwner
import androidx.lifecycle.repeatOnLifecycle
import de.jeanlucmakiola.clockula.R
import de.jeanlucmakiola.clockula.alarm.AlarmEngine
import de.jeanlucmakiola.clockula.domain.alarm.AlarmSetCountdown
import de.jeanlucmakiola.clockula.domain.format.NextFireLabel
import de.jeanlucmakiola.clockula.domain.time.ElapsedRealtimeClock
import de.jeanlucmakiola.clockula.domain.time.WallClock
import de.jeanlucmakiola.floret.components.SnackChip
import de.jeanlucmakiola.floret.components.SnackChipHeight
import de.jeanlucmakiola.floret.components.SnackChipMargin
import de.jeanlucmakiola.floret.di.ApplicationScope
import kotlinx.coroutines.CoroutineScope
import kotlinx.coroutines.ExperimentalCoroutinesApi
import kotlinx.coroutines.Job
import kotlinx.coroutines.delay
import kotlinx.coroutines.flow.Flow
import kotlinx.coroutines.flow.MutableStateFlow
import kotlinx.coroutines.flow.collectLatest
import kotlinx.coroutines.flow.distinctUntilChanged
import kotlinx.coroutines.flow.flatMapLatest
import kotlinx.coroutines.flow.flowOf
import kotlinx.coroutines.flow.map
import kotlinx.coroutines.flow.update
import kotlinx.coroutines.isActive
import kotlinx.coroutines.launch
import javax.inject.Inject
import javax.inject.Singleton
import kotlin.time.Duration
import kotlin.time.Duration.Companion.seconds
/** "Alarm in …", about one alarm, as a screen should show it (#19). */
data class AlarmSetNotice(
val alarmId: Long,
val countdown: NextFireLabel,
/** Which announcement this is, so [AlarmSetAnnouncer.consumed] takes back only that one. */
val sequence: Long,
)
/**
* Says how long until an alarm rings, right after a user action in the app set
* it — the moment an AM/PM or wrong-day slip is cheapest to notice (#19).
*
* Only the list and the editor call it, so an alarm set through the
* `AlarmClock` intents never announces itself: those already get the
* status-bar icon.
*
* It records only *which* alarm was set, and when. What to say is derived from
* the engine while a screen shows it, so it is never a stale or superseded
* value, and an alarm switched off or deleted by any path — the row's switch,
* the ring screen, a notification, an intent, a restore — says nothing.
*
* App-wide, and a **state** rather than an event: the announcement stands
* until a screen has shown it to the end ([consumed]). The usual way to set an
* alarm is pick → OK → back, and back disposes the editor's chip a moment
* after it appeared; the list underneath picks the same announcement up. The
* settle runs on the application scope for the same reason — leaving the
* editor while its repeat days settle must not lose them.
*/
@Singleton
internal class AlarmSetAnnouncer @Inject constructor(
private val engine: AlarmEngine,
private val wall: WallClock,
private val elapsed: ElapsedRealtimeClock,
// `@param:` — the qualifier has no explicit @Target, and K2 resolves a bare
// annotation on a constructor `val` to the property instead.
@param:ApplicationScope private val appScope: CoroutineScope,
) {
/** One user action's announcement. [at] is monotonic: a wall clock set back must not refresh it. */
private data class Announcement(val alarmId: Long, val at: Duration, val sequence: Long)
private val current = MutableStateFlow<Announcement?>(null)
/** The request still settling, and the alarm it is about. Guarded by `this`. */
private var pending: Job? = null
private var pendingFor: Long? = null
private var sequence = 0L
/**
* The notice to show, or null.
*
* Freshness is judged once, when a screen picks the announcement up: past
* [FRESH_FOR] it is dropped unshown — a countdown surfacing when the user
* came back to the app a while later would be about something they did
* long ago — but one already showing is not cut off half-way. The engine
* is observed only while an announcement stands, and a new announcement
* re-subscribes, so its first read is from after the write that asked.
*/
@OptIn(ExperimentalCoroutinesApi::class)
val notice: Flow<AlarmSetNotice?> = current
.flatMapLatest { announcement ->
if (announcement == null || elapsed.elapsedRealtime() - announcement.at >= FRESH_FOR) {
flowOf(null)
} else {
// Worded once, from the first read: later writes — the next
// repeat-day tap, a label keystroke across a minute — must not
// restart a chip already showing. They can only take it
// down, when the alarm stops ringing at all.
var worded: AlarmSetNotice? = null
engine.upcoming().map { upcoming ->
val entry = upcoming.firstOrNull { it.alarm.id == announcement.alarmId }
val countdown = AlarmSetCountdown.of(entry, wall.now())
if (countdown == null) {
// Nothing to say is the answer for good: left standing,
// it would speak up long after the action, should
// something else switch the alarm back on.
clear(announcement.sequence)
null
} else {
worded ?: AlarmSetNotice(announcement.alarmId, countdown, announcement.sequence)
.also { worded = it }
}
}
}
}
.distinctUntilChanged()
/**
* Call once the write is stored. Announces [alarmId] after [settle], unless
* a newer request replaces this one first. Latest wins, across alarms too:
* the chip names no alarm, so a settling announcement about one must
* never land on top of the user's newer action on another and read as
* that one's countdown.
*/
fun announce(alarmId: Long, settle: Duration = Duration.ZERO) {
synchronized(this) {
pending?.cancel()
pendingFor = alarmId
pending = appScope.launch {
delay(settle)
synchronized(this@AlarmSetAnnouncer) {
// A retract or a newer request may have cancelled this one
// after its delay, while it waited for the monitor.
if (isActive) current.value = Announcement(alarmId, elapsed.elapsedRealtime(), ++sequence)
}
}
}
}
/**
* Takes back anything said or about to be said about [alarmId]. For a
* change of state the engine would read as "still rings" — a dismissal
* that skips the occurrence being counted down to.
*/
fun retract(alarmId: Long) {
synchronized(this) {
if (pendingFor == alarmId) {
pending?.cancel()
pendingFor = null
}
current.update { standing -> standing?.takeUnless { it.alarmId == alarmId } }
}
}
/** [notice] was shown until it timed out. */
fun consumed(notice: AlarmSetNotice) = clear(notice.sequence)
private fun clear(sequence: Long) {
current.update { standing -> standing?.takeUnless { it.sequence == sequence } }
}
private companion object {
/** Comfortably longer than the chip stands, so a hand-over between screens fits. */
val FRESH_FOR = 10.seconds
}
}
/**
* Shows [notice] as the family's [SnackChip] while the screen is resumed, in a
* FAB-height band along the bottom edge. Latest wins: a new countdown replaces
* the one on screen rather than queueing behind it, and a null takes it down.
*
* Resumed, not merely composed: during a navigation cross-fade only the screen
* arriving is resumed, so the two never show it at once, and in the background
* nobody would see it. [onShown] runs only when the chip stood for its full
* time; one cut short — by leaving, a rotation, the app going to the
* background — stays pending for whichever screen resumes next.
*
* The chip carries no timer of its own, so the stand is a short snackbar's,
* stretched the way the accessibility settings ask.
*
* [endClearance] is what the band keeps free at its end for a FAB sharing it;
* the message ellipsises short of it instead of running underneath.
*/
@Composable
internal fun AlarmSetChipBand(
notice: Flow<AlarmSetNotice?>,
onShown: (AlarmSetNotice) -> Unit,
modifier: Modifier = Modifier,
endClearance: Dp = 0.dp,
) {
val resources = LocalResources.current
val lifecycle = LocalLifecycleOwner.current.lifecycle
val accessibility = LocalAccessibilityManager.current
val shown by rememberUpdatedState(onShown)
// Kept after the chip hides, so its exit animation still has words in it.
var message by remember { mutableStateOf<String?>(null) }
var visible by remember { mutableStateOf(false) }
LaunchedEffect(notice, resources, lifecycle, accessibility) {
lifecycle.repeatOnLifecycle(Lifecycle.State.RESUMED) {
notice.collectLatest { current ->
if (current == null) return@collectLatest
// A notice with nothing to say is used up all the same, so it
// cannot sit pending for ever.
alarmSetMessage(resources, current.countdown)?.let { text ->
message = text
visible = true
try {
delay(
accessibility?.calculateRecommendedTimeoutMillis(
SHOWN_FOR_MILLIS,
containsIcons = false,
containsText = true,
containsControls = false,
) ?: SHOWN_FOR_MILLIS,
)
} finally {
visible = false
}
}
shown(current)
}
}
}
BoxWithConstraints(
modifier = modifier
.fillMaxWidth()
.padding(start = SnackChipMargin, end = SnackChipMargin, bottom = SnackChipMargin)
.height(SnackChipHeight),
contentAlignment = Alignment.CenterStart,
) {
message?.let { text ->
// The band's full height, as a chip with an Undo stands in the
// other apps; on the secondary container, so it reads apart from
// the alarm cards behind it.
SnackChip(
visible = visible,
message = text,
modifier = Modifier.fillMaxHeight(),
maxWidth = maxWidth - endClearance,
color = MaterialTheme.colorScheme.secondaryContainer,
)
}
}
}
/** A short snackbar's stand. */
private const val SHOWN_FOR_MILLIS = 4_000L
/**
* The full sentence: proper plurals, and the unit pairs the row's countdown
* uses — minutes, hours and minutes, or days and hours. A zero second unit is
* left out, as the row leaves it out: "7 hours", not "7 hours and 0 minutes".
*/
internal fun alarmSetMessage(resources: Resources, countdown: NextFireLabel): String? {
fun days(n: Int) = resources.getQuantityString(R.plurals.alarm_set_days, n, n)
fun hours(n: Int) = resources.getQuantityString(R.plurals.alarm_set_hours, n, n)
fun minutes(n: Int) = resources.getQuantityString(R.plurals.alarm_set_minutes, n, n)
fun pair(first: String, second: String?) =
if (second == null) first else resources.getString(R.string.alarm_set_units_pair, first, second)
val span = when (countdown) {
NextFireLabel.NotScheduled -> return null
NextFireLabel.Imminent -> return resources.getString(R.string.alarm_set_imminent)
is NextFireLabel.InMinutes -> minutes(countdown.minutes)
is NextFireLabel.InHoursMinutes ->
pair(hours(countdown.hours), countdown.minutes.takeIf { it > 0 }?.let(::minutes))
is NextFireLabel.InDaysHours ->
pair(days(countdown.days), countdown.hours.takeIf { it > 0 }?.let(::hours))
}
return resources.getString(R.string.alarm_set_for, span)
}
@@ -1,11 +1,17 @@
package de.jeanlucmakiola.clockula.ui.alarms
import android.content.Intent
import androidx.compose.foundation.layout.Box
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.Arrangement
import androidx.compose.foundation.layout.PaddingValues
import androidx.compose.foundation.layout.WindowInsets
import androidx.compose.foundation.layout.WindowInsetsSides
import androidx.compose.foundation.layout.fillMaxSize
import androidx.compose.foundation.layout.only
import androidx.compose.foundation.layout.padding
import androidx.compose.foundation.layout.systemBars
import androidx.compose.foundation.layout.windowInsetsPadding
import androidx.compose.foundation.lazy.LazyColumn
import androidx.compose.foundation.lazy.items
import androidx.compose.material.icons.Icons
@@ -19,6 +25,7 @@ import androidx.compose.material3.Text
import androidx.compose.runtime.Composable
import androidx.compose.runtime.LaunchedEffect
import androidx.compose.runtime.getValue
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.platform.LocalContext
import androidx.compose.ui.res.stringResource
@@ -66,65 +73,77 @@ fun AlarmsScreen(
viewModel.openEditor.collectLatest(onCreateAlarm)
}
CollapsingScaffold(
title = stringResource(R.string.tab_alarms),
modifier = modifier,
scrollable = false,
actions = {
IconButton(onClick = onOpenSettings) {
Icon(
imageVector = Icons.Rounded.Settings,
contentDescription = stringResource(R.string.settings_title),
)
}
},
floatingActionButton = {
FloatingActionButton(
onClick = viewModel::onAddAlarm,
// The pill is bottom-centre and the FAB bottom-end, so on a
// narrow phone they would otherwise overlap (M5 D6).
modifier = Modifier.padding(bottom = pillInset),
) {
Icon(Icons.Rounded.Add, contentDescription = addAlarm)
}
},
) {
LazyColumn(
modifier = Modifier.fillMaxSize(),
verticalArrangement = Arrangement.spacedBy(12.dp),
contentPadding = PaddingValues(
top = AlarmsDefaults.ListBottomPadding,
bottom = AlarmsDefaults.ListBottomPadding + AlarmsDefaults.FabBand + pillInset,
),
Box(modifier = modifier.fillMaxSize()) {
CollapsingScaffold(
title = stringResource(R.string.tab_alarms),
scrollable = false,
actions = {
IconButton(onClick = onOpenSettings) {
Icon(
imageVector = Icons.Rounded.Settings,
contentDescription = stringResource(R.string.settings_title),
)
}
},
floatingActionButton = {
FloatingActionButton(
onClick = viewModel::onAddAlarm,
// The pill is bottom-centre and the FAB bottom-end, so on a
// narrow phone they would otherwise overlap (M5 D6).
modifier = Modifier.padding(bottom = pillInset),
) {
Icon(Icons.Rounded.Add, contentDescription = addAlarm)
}
},
) {
if (rows != null && rows.isEmpty()) {
item { AlarmsEmptyState() }
}
items(rows.orEmpty(), key = { row -> row.id }) { row ->
AlarmRow(
row = row,
// A ringing alarm's row leads back to its ring screen, the
// way out if its notification was swiped away.
onClick = {
if (row.ringing) {
context.startActivity(
Intent(context, AlarmRingActivity::class.java)
.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK),
)
} else {
onEditAlarm(row.id)
}
},
onToggle = { enabled -> viewModel.onToggleEnabled(row.id, enabled) },
onDismissComing = {
row.dismissibleFireAt?.let { viewModel.onDismissComing(row.id, it) }
},
// An alarm whose time changed slides to its new place
// instead of teleporting.
modifier = animateItemMotion(),
)
LazyColumn(
modifier = Modifier.fillMaxSize(),
verticalArrangement = Arrangement.spacedBy(12.dp),
contentPadding = PaddingValues(
top = AlarmsDefaults.ListBottomPadding,
bottom = AlarmsDefaults.ListBottomPadding + AlarmsDefaults.FabBand + pillInset,
),
) {
if (rows != null && rows.isEmpty()) {
item { AlarmsEmptyState() }
}
items(rows.orEmpty(), key = { row -> row.id }) { row ->
AlarmRow(
row = row,
// A ringing alarm's row leads back to its ring screen, the
// way out if its notification was swiped away.
onClick = {
if (row.ringing) {
context.startActivity(
Intent(context, AlarmRingActivity::class.java)
.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK),
)
} else {
onEditAlarm(row.id)
}
},
onToggle = { enabled -> viewModel.onToggleEnabled(row.id, enabled) },
onDismissComing = {
row.dismissibleFireAt?.let { viewModel.onDismissComing(row.id, it) }
},
// An alarm whose time changed slides to its new place
// instead of teleporting.
modifier = animateItemMotion(),
)
}
}
}
// Beside the FAB, not stacked above it as a snackbar would be: the band is
// the FAB's own, measured from the same insets the scaffold gives it.
AlarmSetChipBand(
notice = viewModel.alarmSetNotice,
onShown = viewModel::onAlarmSetNoticeShown,
endClearance = AlarmsDefaults.FabBand,
modifier = Modifier
.align(Alignment.BottomStart)
.windowInsetsPadding(WindowInsets.systemBars.only(WindowInsetsSides.Bottom))
.padding(bottom = pillInset),
)
}
// "Which alarm should I dismiss?" — asked only when a search named more
@@ -29,6 +29,7 @@ class AlarmsViewModel @Inject internal constructor(
private val wall: WallClock,
private val zones: ZoneProvider,
private val source: AlarmListSource,
private val announcer: AlarmSetAnnouncer,
) : ViewModel() {
val state: StateFlow<AlarmsUiState> = source.rows()
@@ -45,6 +46,14 @@ class AlarmsViewModel @Inject internal constructor(
// into two navigations (M5 D22).
private val newAlarms = Channel<Long>(Channel.CONFLATED)
/**
* "Alarm in …", after the row's switch turns an alarm on — or
* handed over by the editor the user has just left (#19).
*/
val alarmSetNotice: Flow<AlarmSetNotice?> = announcer.notice
fun onAlarmSetNoticeShown(notice: AlarmSetNotice) = announcer.consumed(notice)
/** One-shot: the id of a freshly created alarm, for the caller to navigate to. */
val openEditor: Flow<Long> = newAlarms.receiveAsFlow().onEach { creating = false }
@@ -63,7 +72,8 @@ class AlarmsViewModel @Inject internal constructor(
val time = AlarmDefaults.nextWholeHour(wall.now(), zones.current())
val id = alarms.create(AlarmDraft(time = time))
// Created enabled, so it schedules at once — which is what tapping
// "+" asked for (M5 D22).
// "+" asked for (M5 D22). Not announced here: the editor opens on
// its time picker, and announces whichever time the user keeps.
engine.reschedule()
newAlarms.send(id)
}
@@ -74,6 +84,10 @@ class AlarmsViewModel @Inject internal constructor(
// One engine verb, so the contract's dismissal and the user's are the
// same code: it closes a ring, arms a repeating alarm's skip, or
// disables a one-shot — each of which moves state only the engine owns.
// First, so the chip never re-reads the skip and counts down to the
// occurrence after it. Not re-announced: this is the `AlarmClock`
// contract's request (M9 D13), which the chip stays out of (#19).
announcer.retract(alarmId)
viewModelScope.launch { engine.dismissUpcoming(alarmId) }
}
@@ -92,6 +106,10 @@ class AlarmsViewModel @Inject internal constructor(
if (!enabled) stopRingIfRinging(alarmId)
alarms.setEnabled(alarmId, enabled)
engine.reschedule()
// Switching on says when it will ring (#19). Switching off needs
// nothing: the notice is read from the engine, so one about this
// alarm falls silent by itself, and one about another stands.
if (enabled) announcer.announce(alarmId)
}
}
+16
View File
@@ -118,6 +118,22 @@
<string name="alarm_next_in_days_hours">in %1$dd %2$dh</string>
<string name="alarm_next_ringing">Ringing now</string>
<string name="alarm_next_snoozed">Snoozed \u00b7 %1$s</string>
<!-- #19: the chip after the user sets an alarm, short enough to sit beside the FAB. %1$s is alarm_set_days/hours/minutes, or two of them joined by alarm_set_units_pair. -->
<string name="alarm_set_for">Alarm in %1$s</string>
<string name="alarm_set_imminent">Alarm in less than 1 minute</string>
<string name="alarm_set_units_pair">%1$s and %2$s</string>
<plurals name="alarm_set_days">
<item quantity="one">%1$d day</item>
<item quantity="other">%1$d days</item>
</plurals>
<plurals name="alarm_set_hours">
<item quantity="one">%1$d hour</item>
<item quantity="other">%1$d hours</item>
</plurals>
<plurals name="alarm_set_minutes">
<item quantity="one">%1$d minute</item>
<item quantity="other">%1$d minutes</item>
</plurals>
<string name="alarm_skipping_next">Skipping next</string>
<string name="alarm_repeat_once">Once</string>
<string name="alarm_repeat_every_day">Every day</string>