Hold every dropped copy until its own write lands, cancel drops behind a dialog, keep the first Undo (#494)

This commit is contained in:
makiolaj committed 2026-11-13 13:18:11 +01:00
1 parent 0595124ecd
commit 1925e1c2f4
7 files changed
+307 -63

No files matched your search

@@ -91,6 +91,7 @@ fun EventMoveHost(
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.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)
@@ -121,6 +121,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
/**
* The drop's occurrence is no longer where it was picked up — an earlier
* write moved it — and a recurring one can't be followed there, so it is not
@@ -198,8 +201,8 @@ class RescheduleViewModel @Inject constructor(
_inFlight.value = value
}
/** Whether a drop since the pipeline was last idle failed — see [report]. */
private var failedThisRun = false
/** Whether the chip has shown anything since the pipeline was last idle — see [report]. */
private var reportedThisRun = false
/** Drops that arrived while another was in flight, oldest first (#494). */
private val queue = ArrayDeque<MoveRequest>()
@@ -247,6 +250,11 @@ class RescheduleViewModel @Inject constructor(
_drops.update { it.ended(request.token, landed = false) }
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
@@ -268,7 +276,10 @@ class RescheduleViewModel @Inject constructor(
report(MoveOutcome.BlockedCancelledSeries)
settle(request.token, landed = false)
} else {
// Still busy: the scope dialog is now the thing in flight.
// 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()
pending = prepared
_scopePrompt.value = MoveScopePrompt(
occurrenceOnly = !prepared.canRealign,
@@ -307,19 +318,35 @@ class RescheduleViewModel @Inject constructor(
run(next)
} else {
busy = false
failedThisRun = false
reportedThisRun = 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)
}
/**
* Show [outcome] on the chip. While drops run back to back, a failure stays
* up rather than being replaced by a later drop's success: the grid shows
* what moved, but only the chip says what didn't.
* Show [outcome] on the chip. While drops run back to back, the first move's
* chip and its Undo stay up rather than being replaced by the next success,
* and a failure replaces it: the grid shows what moved, but only the chip
* says what didn't. A later write to the shown move's own event takes that
* Undo away, since putting the event back would undo the later move too.
*/
private fun report(outcome: MoveOutcome) {
private fun report(outcome: MoveOutcome, eventId: Long? = null) {
val failure = outcome !is MoveOutcome.Moved && outcome !is MoveOutcome.Undone
if (!failure && failedThisRun) return
if (failure) failedThisRun = true
if (!failure && reportedThisRun) {
val shown = _outcome.value as? MoveOutcome.Moved
if (shown?.undo != null && shown.undo.eventId == eventId) {
_outcome.value = shown.copy(undo = null)
}
return
}
reportedThisRun = true
_outcome.value = outcome
}
@@ -480,7 +507,7 @@ class RescheduleViewModel @Inject constructor(
} catch (e: Exception) {
MoveOutcome.Failed
}
report(outcome)
report(outcome, request.eventId)
return outcome is MoveOutcome.Moved
}
@@ -20,6 +20,7 @@ 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
@@ -350,6 +351,19 @@ internal fun draftBlock(draft: EventInstance, date: LocalDate, zone: TimeZone):
enum class ResizeEdge { Top, Bottom }
/** Where a finished resize asks its event to begin and end. */
/** 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>,
val handedOver: Boolean = false,
) {
fun ghosts(block: TimedBlock): Boolean = block.event.instanceId == instanceId ||
(block.event.eventId == origin.first && block.event.start == origin.second)
}
data class TimelineResizeDrop(
val event: EventInstance,
val start: Instant,
@@ -528,6 +542,14 @@ 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
@@ -696,7 +718,7 @@ class TimelineDragController {
dragDuration = (block.event.end - block.event.start).coerceAtLeast(Duration.ZERO)
dragKept = zone.repeatedHourOffsetAt(block.event.start)
this.titleLines = titleLines
settling = null
parkSettling()
isDragging = true
liftedInstanceId = block.event.instanceId
grab = pointerInRoot - blockInRoot
@@ -735,7 +757,7 @@ class TimelineDragController {
dragDuration = draftMinutes.minutes
dragKept = null
titleLines = 1
settling = null
parkSettling()
isDragging = true
liftedInstanceId = event.instanceId
grab = Offset(0f, geometry.hourPx * STRIP_GRAB_MINUTES / 60f)
@@ -815,12 +837,36 @@ 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)
}
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
@@ -908,7 +954,7 @@ class TimelineDragController {
resize = session
clipOffsetMin = 0
this.titleLines = titleLines
settling = null
parkSettling()
isDragging = true
pointerMoved = true
liftedInstanceId = block.event.instanceId
@@ -1312,6 +1358,9 @@ private const val SETTLE_TIMEOUT_MILLIS = 900L
*/
const val SETTLE_FADE_MILLIS: Int = 250
/** How long a held copy waits after its write before fading — the grid's re-read, unconfirmed. */
const val HELD_SETTLE_MILLIS: Long = 300L
/**
* 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.
@@ -1319,10 +1368,6 @@ 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
@@ -1371,6 +1416,9 @@ fun TimelineDragOverlay(controller: TimelineDragController, modifier: Modifier =
.clearAndSetSemantics { }
.onGloballyPositioned { origin = it.positionInRoot() },
) {
controller.held.forEach { parked ->
key(parked.token) { HeldTimelineCopy(controller, parked, origin) }
}
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
@@ -1384,6 +1432,47 @@ fun TimelineDragOverlay(controller: TimelineDragController, modifier: Modifier =
animationSpec = tween(SETTLE_FADE_MILLIS),
label = "drag-handover",
)
TimelineCopy(drag, controller.geometry, origin, lift, copyAlpha)
}
}
/** 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 drops = dropStates()
val pending = parked.token in drops.pending
val abandoned = parked.token in drops.abandoned
var fading by remember { mutableStateOf(false) }
LaunchedEffect(pending, abandoned) {
if (pending) return@LaunchedEffect
// No seat to confirm this one, so give the grid a beat to re-read.
if (!abandoned) delay(HELD_SETTLE_MILLIS)
fading = true
controller.handOverHeld(parked.token)
delay(SETTLE_FADE_MILLIS.toLong())
controller.releaseHeld(parked.token)
}
val alpha by animateFloatAsState(
targetValue = if (fading) 0f else 1f,
animationSpec = tween(SETTLE_FADE_MILLIS),
label = "held-handover",
)
TimelineCopy(parked.copy, controller.geometry, origin, lift = 0f, copyAlpha = alpha)
}
/** [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
@@ -1399,7 +1488,7 @@ fun TimelineDragOverlay(controller: TimelineDragController, modifier: Modifier =
// 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 = controller.geometry.viewport?.takeIf { it.isAttached }?.boundsInRoot()
val port = 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
@@ -1451,7 +1540,6 @@ fun TimelineDragOverlay(controller: TimelineDragController, modifier: Modifier =
)
}
}
}
}
/** One piece of a dragged block, floating over the calendar. */
@@ -106,6 +106,13 @@ 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 a finished chip drag asks its event to go, as a whole-day shift. */
data class MonthChipDrop(
val event: EventInstance,
@@ -173,6 +180,14 @@ class MonthDragController {
*/
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).
*/
var held: List<HeldChip> by mutableStateOf(emptyList())
private set
/** The token of the drop (or undo) [settling] is waiting on. */
var settledToken: Long = 0L
private set
@@ -203,7 +218,7 @@ class MonthDragController {
this.event = event
this.grabDate = grabDate
this.time = time
settling = null
parkSettling()
isDragging = true
liftedInstanceId = event.instanceId
grab = pointerInRoot - chipInRoot
@@ -229,6 +244,29 @@ class MonthDragController {
settledGhost = false
}
/** Whether [event]'s chip is the source of a held drop, so still a ghost. */
fun isHeldSource(event: EventInstance): Boolean =
held.any { !it.handedOver && it.copy.event.instanceId == event.instanceId }
/** 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.
@@ -129,6 +129,7 @@ import de.jeanlucmakiola.calendula.ui.common.dropStates
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.HELD_SETTLE_MILLIS
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
@@ -590,8 +591,6 @@ private const val MONTH_SETTLE_TIMEOUT_MILLIS = 450L
@Composable
private fun MonthDragOverlay(controller: MonthDragController, showStartTimes: Boolean) {
var origin by remember { mutableStateOf(Offset.Zero) }
val dark = LocalFloretDarkTheme.current
val density = LocalDensity.current
val timeFit = rememberMonthChipTimeFit(showStartTimes)
val reduceMotion = rememberReduceMotion()
val drops = dropStates()
@@ -634,6 +633,9 @@ 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(
@@ -645,42 +647,94 @@ private fun MonthDragOverlay(controller: MonthDragController, showStartTimes: Bo
animationSpec = tween(SETTLE_FADE_MILLIS),
label = "chip-handover",
)
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,
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,
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 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 drops = dropStates()
val pending = parked.token in drops.pending
val abandoned = parked.token in drops.abandoned
var fading by remember { mutableStateOf(false) }
LaunchedEffect(pending, abandoned) {
if (pending) return@LaunchedEffect
// No seat to confirm this one, so give the grid a beat to re-read.
if (!abandoned) delay(HELD_SETTLE_MILLIS)
fading = true
controller.handOverHeld(parked.token)
delay(SETTLE_FADE_MILLIS.toLong())
controller.releaseHeld(parked.token)
}
val alpha by animateFloatAsState(
targetValue = if (fading) 0f else 1f,
animationSpec = tween(SETTLE_FADE_MILLIS),
label = "held-chip-handover",
)
MonthChipCopy(parked.copy, { parked.copy.topLeftInRoot }, 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
@@ -2837,7 +2891,8 @@ private fun MonthBar(
// The source stays put as a ghost while its floating copy travels.
val monthDrag = LocalMonthDrag.current
val lifted = monthDrag?.liftedInstanceId == event.instanceId ||
monthDrag?.isSettledChip(event, days) == true
monthDrag?.isSettledChip(event, days) == true ||
monthDrag?.isHeldSource(event) == true
val ghost = ghostAlpha(lifted)
val shape = monthBarShape(continuesLeft, continuesRight)
Box(
+1
View File
@@ -111,6 +111,7 @@
<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_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>
@@ -413,27 +413,61 @@ class RescheduleViewModelTest {
}
@Test
fun `a drop made while a scope dialog is up runs once it is answered`(
fun `drops waiting when a scope dialog opens are cancelled, not held behind it`(
@TempDir tempDir: Path,
) = runTest(dispatcher) {
val fake = FakeCalendarDataSource().apply {
eventDetailResult = { id -> if (id == 42L) detail(rrule = "FREQ=WEEKLY") else detail() }
}
val vm = viewModel(tempDir, fake)
val vm = slowViewModel(tempDir, fake)
vm.move(oneHourLater())
advanceUntilIdle()
val queued = toWednesday().copy(eventId = 7L, token = nextMoveToken())
assertThat(vm.move(queued)).isTrue()
vm.move(queued)
advanceUntilIdle()
assertThat(fake.updatedEvents).isEmpty()
assertThat(vm.drops.value.pending).contains(queued.token)
assertThat(vm.scopePrompt.value).isNotNull()
assertThat(vm.drops.value.abandoned).containsExactly(queued.token)
assertThat(vm.outcome.value).isEqualTo(MoveOutcome.Skipped)
// One made while the dialog is up is refused the same way.
val during = toWednesday().copy(eventId = 7L, token = nextMoveToken())
assertThat(vm.move(during)).isFalse()
vm.moveWithScope(RecurringWriteScope.AllEvents)
advanceUntilIdle()
assertThat(fake.updatedEvents.map { it.first }).containsExactly(42L)
// The skip stays on the chip; the grid shows the move itself.
assertThat(vm.outcome.value).isEqualTo(MoveOutcome.Skipped)
}
assertThat(fake.updatedEvents.map { it.first }).containsExactly(42L, 7L).inOrder()
assertThat(vm.drops.value.pending).isEmpty()
@Test
fun `the first move of a run keeps the chip and its undo`(@TempDir tempDir: Path) = runTest(dispatcher) {
val fake = FakeCalendarDataSource().apply { eventDetailResult = { detail() } }
val vm = slowViewModel(tempDir, fake)
vm.move(oneHourLater())
vm.move(toWednesday().copy(eventId = 7L, token = nextMoveToken()))
advanceUntilIdle()
val shown = vm.outcome.value as MoveOutcome.Moved
assertThat(fake.updatedEvents).hasSize(2)
assertThat(shown.undo?.eventId).isEqualTo(42L)
}
@Test
fun `a later move of the same event takes the first move's undo away`(
@TempDir tempDir: Path,
) = runTest(dispatcher) {
val fake = FakeCalendarDataSource().apply { eventDetailResult = { detail() } }
val vm = slowViewModel(tempDir, fake)
vm.move(oneHourLater())
vm.move(toWednesday())
advanceUntilIdle()
assertThat(fake.updatedEvents).hasSize(2)
assertThat((vm.outcome.value as MoveOutcome.Moved).undo).isNull()
}
@Test