diff --git a/app/src/main/java/de/jeanlucmakiola/calendula/ui/CalendarHost.kt b/app/src/main/java/de/jeanlucmakiola/calendula/ui/CalendarHost.kt index 812ac5fa..91aabc85 100644 --- a/app/src/main/java/de/jeanlucmakiola/calendula/ui/CalendarHost.kt +++ b/app/src/main/java/de/jeanlucmakiola/calendula/ui/CalendarHost.kt @@ -96,6 +96,9 @@ import de.jeanlucmakiola.calendula.ui.common.drillToDay import de.jeanlucmakiola.calendula.ui.common.drillToWeek import de.jeanlucmakiola.calendula.ui.common.rememberCalendarSlideSpec import de.jeanlucmakiola.calendula.ui.common.selectView +import de.jeanlucmakiola.calendula.ui.common.swapView +import de.jeanlucmakiola.calendula.ui.common.LocalMultiDayCount +import de.jeanlucmakiola.calendula.ui.week.MultiDayViewModel import de.jeanlucmakiola.calendula.ui.common.viewBaseStack import de.jeanlucmakiola.calendula.ui.detail.EventDetailScreen import de.jeanlucmakiola.calendula.ui.edit.EventEditViewModel @@ -187,7 +190,17 @@ fun CalendarHost( requests.leaveTarget = requests.leaveTarget.afterMove(viewStack, moved) viewStack = moved } - val onSelectView: (CalendarView) -> Unit = { target -> switchTo { it.selectView(target) } } + // A day count pinched or picked in the month (#389) lasts until the + // multi-day view is picked again. + val multiDayViewModel: MultiDayViewModel = hiltViewModel() + val multiDayRange by multiDayViewModel.rangeCount.collectAsStateWithLifecycle() + val onSelectView: (CalendarView) -> Unit = { target -> + if (target == CalendarView.MultiDay) multiDayViewModel.clearRange() + switchTo { it.selectView(target) } + } + val onPinchView: (CalendarView) -> Unit = { target -> + if (target != viewStack.last()) switchTo { it.swapView(target) } + } val onOpenDay: (LocalDate) -> Unit = { date -> focus.navigateTo(date) switchTo { it.drillToDay() } @@ -675,15 +688,17 @@ fun CalendarHost( ) { Scaffold( topBar = { - CalendarTopBar( - host = chromeHost, - selectedView = view, - quickSwitchViews = quickSwitchViews, - onCycleView = { onSelectView(viewStack.last().next(quickSwitchViews)) }, - onOpenDrawer = { switchScope.launch { drawerState.open() } }, - onOpenSearch = onOpenSearch, - showTodayButton = todayInToolbar, - ) + CompositionLocalProvider(LocalMultiDayCount provides (multiDayRange ?: LocalMultiDayCount.current)) { + CalendarTopBar( + host = chromeHost, + selectedView = view, + quickSwitchViews = quickSwitchViews, + onCycleView = { onSelectView(viewStack.last().next(quickSwitchViews)) }, + onOpenDrawer = { switchScope.launch { drawerState.open() } }, + onOpenSearch = onOpenSearch, + showTodayButton = todayInToolbar, + ) + } }, floatingActionButton = { // While an event is selected the FAB is its action bar's toggle (#141). @@ -736,6 +751,8 @@ fun CalendarHost( onEventClick = onEventClick, onCreateEvent = onCreateEvent, onCreateDraft = onCreateDraft, + onPinchView = onPinchView, + multiDayViewModel = multiDayViewModel, ) ViewScreen.Month -> MonthScreen( onOpenDay = onOpenDay, diff --git a/app/src/main/java/de/jeanlucmakiola/calendula/ui/common/CalendarView.kt b/app/src/main/java/de/jeanlucmakiola/calendula/ui/common/CalendarView.kt index 256ae93b..14f5feb3 100644 --- a/app/src/main/java/de/jeanlucmakiola/calendula/ui/common/CalendarView.kt +++ b/app/src/main/java/de/jeanlucmakiola/calendula/ui/common/CalendarView.kt @@ -126,6 +126,14 @@ fun List.selectView(target: CalendarView): List { fun viewBaseStack(default: CalendarView, source: CalendarView): List = if (source == default) listOf(default) else listOf(default, source) +/** + * Swap the view on top for [target] in place, as a pinch changing the days shown + * does (#389): a home view stays at the bottom and the new one goes over it, + * and one already further down is returned to. + */ +fun List.swapView(target: CalendarView): List = + if (size <= 1) selectView(target) else dropLast(1).selectView(target) + /** Push the day view as a drill-in over the current stack (no-op if already on it). */ fun List.drillToDay(): List = if (lastOrNull() == CalendarView.Day) this else this + CalendarView.Day diff --git a/app/src/main/java/de/jeanlucmakiola/calendula/ui/common/TimelineZoom.kt b/app/src/main/java/de/jeanlucmakiola/calendula/ui/common/TimelineZoom.kt index 3b6d3e6e..315cc102 100644 --- a/app/src/main/java/de/jeanlucmakiola/calendula/ui/common/TimelineZoom.kt +++ b/app/src/main/java/de/jeanlucmakiola/calendula/ui/common/TimelineZoom.kt @@ -15,6 +15,7 @@ import androidx.compose.runtime.rememberUpdatedState import androidx.compose.runtime.setValue import androidx.compose.runtime.staticCompositionLocalOf import androidx.compose.ui.Modifier +import androidx.compose.ui.geometry.Offset import androidx.compose.ui.input.pointer.PointerEventPass import androidx.compose.ui.input.pointer.pointerInput import androidx.compose.ui.unit.Dp @@ -160,12 +161,13 @@ fun rememberTimelinePinchZoom( viewportHeight: Dp, hourHeight: Dp, zoom: TimelineZoom, + axisLock: PinchAxisLock? = null, ): Modifier { // The gesture loop outlives any single composition, so it reads these // through state handles rather than capturing what they were when it started. val currentHourHeight = rememberUpdatedState(hourHeight) val currentViewport = rememberUpdatedState(viewportHeight) - return Modifier.pointerInput(scrollState, zoom) { + return Modifier.pointerInput(scrollState, zoom, axisLock) { awaitEachGesture { awaitFirstDown(requireUnconsumed = false, pass = PointerEventPass.Initial) var claimed = false @@ -181,7 +183,10 @@ fun rememberTimelinePinchZoom( val step = event.calculateZoom() if (!claimed) { slop *= step - if (abs(slop - 1f) >= PINCH_SLOP) { + // Under a lock, only once it has been decided for this axis. + if (abs(slop - 1f) >= PINCH_SLOP && + (axisLock == null || axisLock.axis == PinchAxis.Vertical) + ) { claimed = true zoom.beginPinch() } @@ -280,4 +285,45 @@ internal fun anchoredScroll( * enough to feel immediate, wide enough that the two-finger scroll a user meant * as a scroll stays one. */ -private const val PINCH_SLOP = 0.08f +internal const val PINCH_SLOP = 0.08f + +/** Which way a two-finger pinch on the timeline runs, decided once per gesture (#389). */ +enum class PinchAxis { + /** Side by side: the number of days shown. */ + Horizontal, + + /** Above each other: the hour scale (#56). */ + Vertical, +} + +/** + * The axis a pinch locks to, from how far the fingers' spread grew or shrank + * along each axis since they both came down. A horizontal pinch has to win + * clearly; anything less keeps the hour zoom it always was. + */ +fun lockPinchAxis(spreadChangeX: Float, spreadChangeY: Float): PinchAxis = + if (abs(spreadChangeX) > abs(spreadChangeY) * HORIZONTAL_AXIS_BIAS) PinchAxis.Horizontal else PinchAxis.Vertical + +/** How much more a pinch has to run sideways than up and down to count as horizontal. */ +private const val HORIZONTAL_AXIS_BIAS = 1.25f + +/** How far [points] sit from their centroid on average, along each axis. */ +fun spreadOf(points: List): Offset { + if (points.isEmpty()) return Offset.Zero + val cx = points.sumOf { it.x.toDouble() }.toFloat() / points.size + val cy = points.sumOf { it.y.toDouble() }.toFloat() / points.size + return Offset( + points.sumOf { abs(it.x - cx).toDouble() }.toFloat() / points.size, + points.sumOf { abs(it.y - cy).toDouble() }.toFloat() / points.size, + ) +} + +/** + * The axis of the pinch in progress, shared by the detectors that each handle + * one: the one that tells them apart sits above the others, sees each event + * first and decides; the hour zoom only takes a pinch decided [PinchAxis.Vertical]. + */ +class PinchAxisLock { + /** Null until the gesture under way has been decided. */ + var axis: PinchAxis? = null +} diff --git a/app/src/main/java/de/jeanlucmakiola/calendula/ui/week/DayCountPinch.kt b/app/src/main/java/de/jeanlucmakiola/calendula/ui/week/DayCountPinch.kt new file mode 100644 index 00000000..3f244173 --- /dev/null +++ b/app/src/main/java/de/jeanlucmakiola/calendula/ui/week/DayCountPinch.kt @@ -0,0 +1,112 @@ +package de.jeanlucmakiola.calendula.ui.week + +import de.jeanlucmakiola.calendula.ui.common.CalendarView +import kotlinx.datetime.DateTimeUnit +import kotlinx.datetime.LocalDate +import kotlinx.datetime.minus +import kotlinx.datetime.plus +import kotlin.math.floor +import kotlin.math.ln + +/** The fewest days a pinch shows. */ +const val MIN_PINCH_DAYS = 1 + +/** The most days a pinch shows, unless it started from more. */ +const val MAX_PINCH_DAYS = 7 + +/** The day counts a pinch can step through, starting from [origin] days. */ +fun pinchDayRange(origin: Int): IntRange = MIN_PINCH_DAYS..maxOf(MAX_PINCH_DAYS, origin) + +/** + * The day count a pinch that started on [origin] days and has spread the + * fingers by [zoom] shows, stepping from [current]. + * + * Each day takes the same share of spread, on a log scale, so seven to one day + * fits in one pinch. A step is only taken [STEP_HYSTERESIS] past the midpoint + * between two counts, and only given back as far past it the other way, so + * fingers held near a threshold don't flicker between two counts. + */ +fun steppedDayCount(current: Int, origin: Int, zoom: Float, range: IntRange = pinchDayRange(origin)): Int { + if (zoom <= 0f) return current + val position = origin - ln(zoom) / ln(DAY_STEP_ZOOM) + var count = current.coerceIn(range) + while (count > range.first && position < count - 0.5f - STEP_HYSTERESIS) count-- + while (count < range.last && position > count + 0.5f + STEP_HYSTERESIS) count++ + return count +} + +/** + * Where across the day columns [x] falls, from the first day's edge (0) to the + * last one's (1). The columns sit between the hour gutter on the start side and + * [endInsetPx] on the end side, mirrored right to left. + */ +fun columnFraction(x: Float, width: Float, gutterPx: Float, endInsetPx: Float, isRtl: Boolean): Float { + val columns = width - gutterPx - endInsetPx + if (columns <= 0f) return 0f + val fromStart = if (isRtl) width - gutterPx - x else x - gutterPx + return (fromStart / columns).coerceIn(0f, 1f) +} + +/** The column [fraction] falls in, of [count]. */ +private fun columnAt(fraction: Float, count: Int): Int = + floor(fraction * count).toInt().coerceIn(0, count - 1) + +/** The day under [fraction] across [span]. */ +fun DaySpan.dayAt(fraction: Float): LocalDate = start.plus(columnAt(fraction, count), DateTimeUnit.DAY) + +/** + * The first day of a [count]-day run that keeps [anchor] in the column under + * [fraction], so the day under the fingers stays there as the columns change. + */ +fun anchoredStart(anchor: LocalDate, fraction: Float, count: Int): LocalDate = + anchor.minus(columnAt(fraction, count), DateTimeUnit.DAY) + +/** What a pinch to [count] days shows: one day is the day view, more the multi-day view. */ +fun pinchedView(count: Int): CalendarView = if (count == 1) CalendarView.Day else CalendarView.MultiDay + +/** How much spread one day more or less takes: seven to one is about 3x. */ +private const val DAY_STEP_ZOOM = 1.2f + +/** How far past the midpoint between two counts a step is taken, in steps. */ +private const val STEP_HYSTERESIS = 0.2f + +/** Where a pinch's steps go: the view, the days it shows, and the multi-day count it holds. */ +internal data class PinchTarget(val view: CalendarView, val span: DaySpan, val rangeCount: Int?) + +/** + * One horizontal pinch (#389), from the page it started on. The day under the + * fingers when it started stays under them; coming back to the count it + * started from gives back the page and view it started on, so a pinch that + * changes its mind leaves the week a week. + * + * @param originRange the multi-day view's session count when the pinch started. + */ +internal class DayPinch( + private val originView: CalendarView, + private val origin: DaySpan, + private val originRange: Int?, + private val anchor: LocalDate, +) { + var count: Int = origin.count + private set + + /** Where the pinch goes at [zoom] with the fingers at [fraction], or null while the count holds. */ + fun step(zoom: Float, fraction: Float): PinchTarget? { + val next = steppedDayCount(count, origin.count, zoom) + if (next == count) return null + count = next + if (next == origin.count) return PinchTarget(originView, origin, originRange) + val view = pinchedView(next) + return PinchTarget( + view = view, + span = DaySpan(anchoredStart(anchor, fraction, next), next), + rangeCount = next.takeIf { view == CalendarView.MultiDay }, + ) + } + + companion object { + /** A pinch starting on [span] of [view] with the fingers at [fraction]. */ + fun start(view: CalendarView, span: DaySpan, rangeCount: Int?, fraction: Float): DayPinch = + DayPinch(view, span, rangeCount, span.dayAt(fraction)) + } +} diff --git a/app/src/main/java/de/jeanlucmakiola/calendula/ui/week/DayPinchGesture.kt b/app/src/main/java/de/jeanlucmakiola/calendula/ui/week/DayPinchGesture.kt new file mode 100644 index 00000000..17002b11 --- /dev/null +++ b/app/src/main/java/de/jeanlucmakiola/calendula/ui/week/DayPinchGesture.kt @@ -0,0 +1,71 @@ +package de.jeanlucmakiola.calendula.ui.week + +import androidx.compose.foundation.gestures.awaitEachGesture +import androidx.compose.foundation.gestures.awaitFirstDown +import androidx.compose.foundation.gestures.calculateCentroid +import androidx.compose.foundation.gestures.calculateZoom +import androidx.compose.ui.Modifier +import androidx.compose.ui.geometry.Offset +import androidx.compose.ui.input.pointer.PointerEventPass +import androidx.compose.ui.input.pointer.pointerInput +import de.jeanlucmakiola.calendula.ui.common.PINCH_SLOP +import de.jeanlucmakiola.calendula.ui.common.PinchAxis +import de.jeanlucmakiola.calendula.ui.common.PinchAxisLock +import de.jeanlucmakiola.calendula.ui.common.lockPinchAxis +import de.jeanlucmakiola.calendula.ui.common.spreadOf +import kotlin.math.abs + +/** What a sideways pinch on the timeline drives (#389). */ +internal interface DayCountPinchHandler { + /** A sideways pinch is taking over at [x] across [width]; false leaves it to the hour zoom. */ + fun begin(x: Float, width: Float): Boolean + + /** The fingers have spread by [zoom] since they came down, and sit at [x]. */ + fun update(zoom: Float, x: Float, width: Float) + + fun end() +} + +/** + * Tells a sideways pinch from an up-and-down one as it starts, and drives + * [handler] with the sideways ones. It sits above the pager and the hour zoom + * and watches the initial pass, so it decides each gesture before they see it: + * the hour zoom waits for [lock] to say [PinchAxis.Vertical], and a sideways + * pinch consumes the fingers from then on, which stops the pager and the scroll. + * It outlives the pages and the column resize, so one pinch can step several times. + */ +internal fun Modifier.dayCountPinch(lock: PinchAxisLock, handler: DayCountPinchHandler): Modifier = + pointerInput(lock, handler) { + awaitEachGesture { + awaitFirstDown(requireUnconsumed = false, pass = PointerEventPass.Initial) + lock.axis = null + var zoom = 1f + var startSpread: Offset? = null + var claimed = false + try { + while (true) { + val event = awaitPointerEvent(PointerEventPass.Initial) + val pressed = event.changes.filter { it.pressed } + if (pressed.isEmpty()) break + if (pressed.size >= 2) { + zoom *= event.calculateZoom() + val x = event.calculateCentroid(useCurrent = true).x + val width = size.width.toFloat() + if (lock.axis == null) { + val spread = spreadOf(pressed.map { it.position }) + val first = startSpread ?: spread.also { startSpread = it } + if (abs(zoom - 1f) >= PINCH_SLOP) { + val axis = lockPinchAxis(spread.x - first.x, spread.y - first.y) + claimed = axis == PinchAxis.Horizontal && handler.begin(x, width) + lock.axis = if (claimed) PinchAxis.Horizontal else PinchAxis.Vertical + } + } + if (claimed) handler.update(zoom, x, width) + } + if (claimed) event.changes.forEach { if (it.pressed) it.consume() } + } + } finally { + if (claimed) handler.end() + } + } + } diff --git a/app/src/main/java/de/jeanlucmakiola/calendula/ui/week/TimelineActions.kt b/app/src/main/java/de/jeanlucmakiola/calendula/ui/week/TimelineActions.kt index 6a338bfe..46e1375b 100644 --- a/app/src/main/java/de/jeanlucmakiola/calendula/ui/week/TimelineActions.kt +++ b/app/src/main/java/de/jeanlucmakiola/calendula/ui/week/TimelineActions.kt @@ -6,6 +6,7 @@ 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.PinchAxisLock import de.jeanlucmakiola.calendula.ui.common.StripDrop import de.jeanlucmakiola.calendula.ui.common.TimelineDragController import de.jeanlucmakiola.calendula.ui.common.TimelineDrop @@ -27,6 +28,8 @@ internal class TimelineActions( val onDrop: (TimelineDrop) -> Unit, val onResize: (TimelineResizeDrop) -> Unit, val onStripDrop: (StripDrop) -> Unit, + /** The axis of the pinch under way, when a sideways pinch can change the days shown (#389). */ + val pinchLock: PinchAxisLock? = null, ) /** The callbacks are read through their latest values, so the holder outlives them. */ @@ -40,6 +43,7 @@ internal fun rememberTimelineActions( onDrop: (TimelineDrop) -> Unit, onResize: (TimelineResizeDrop) -> Unit, onStripDrop: (StripDrop) -> Unit, + pinchLock: PinchAxisLock? = null, ): TimelineActions { val eventClick = rememberUpdatedState(onEventClick) val openDay = rememberUpdatedState(onOpenDay) @@ -47,7 +51,7 @@ internal fun rememberTimelineActions( val drop = rememberUpdatedState(onDrop) val resize = rememberUpdatedState(onResize) val stripDrop = rememberUpdatedState(onStripDrop) - return remember(scrollState, dragController) { + return remember(scrollState, dragController, pinchLock) { TimelineActions( scrollState = scrollState, dragController = dragController, @@ -57,6 +61,7 @@ internal fun rememberTimelineActions( onDrop = { drop.value(it) }, onResize = { resize.value(it) }, onStripDrop = { stripDrop.value(it) }, + pinchLock = pinchLock, ) } } diff --git a/app/src/main/java/de/jeanlucmakiola/calendula/ui/week/WeekScreen.kt b/app/src/main/java/de/jeanlucmakiola/calendula/ui/week/WeekScreen.kt index 0f00f711..52b22db2 100644 --- a/app/src/main/java/de/jeanlucmakiola/calendula/ui/week/WeekScreen.kt +++ b/app/src/main/java/de/jeanlucmakiola/calendula/ui/week/WeekScreen.kt @@ -91,6 +91,8 @@ import androidx.compose.ui.Modifier import de.jeanlucmakiola.calendula.ui.common.LocalViewMorph import de.jeanlucmakiola.calendula.ui.common.StayPut import kotlinx.coroutines.delay +import kotlinx.coroutines.channels.Channel +import de.jeanlucmakiola.calendula.ui.common.PinchAxisLock import kotlinx.coroutines.withTimeoutOrNull import kotlinx.coroutines.flow.first import androidx.compose.runtime.withFrameNanos @@ -269,6 +271,7 @@ fun TimelineScreen( onCreateEvent: (LocalDate, Int?) -> Unit, onCreateDraft: (Instant, Instant) -> Unit, modifier: Modifier = Modifier, + onPinchView: (CalendarView) -> Unit = {}, weekViewModel: WeekViewModel = hiltViewModel(), multiDayViewModel: MultiDayViewModel = hiltViewModel(), dayViewModel: DayViewModel = hiltViewModel(), @@ -283,6 +286,7 @@ fun TimelineScreen( onEventClick = onEventClick, onCreateEvent = onCreateEvent, onCreateDraft = onCreateDraft, + onPinchView = onPinchView, modifier = modifier, ) } @@ -290,7 +294,7 @@ fun TimelineScreen( /** Each timeline view's own pages and anchor, held side by side so a switch can show both. */ internal class TimelineViewModels( private val week: WeekViewModel, - private val multiDay: MultiDayViewModel, + val multiDay: MultiDayViewModel, private val day: DayViewModel, ) { operator fun get(view: CalendarView): PagedTimelineViewModel = when (view) { @@ -339,6 +343,7 @@ private fun PagedTimelineScreen( onEventClick: (EventInstance) -> Unit, onCreateEvent: (LocalDate, Int?) -> Unit, onCreateDraft: (Instant, Instant) -> Unit, + onPinchView: (CalendarView) -> Unit, modifier: Modifier, ) { // The view on screen, which trails [view] while the columns resize into it. @@ -416,6 +421,36 @@ private fun PagedTimelineScreen( val currentPager by rememberUpdatedState(pagerState) val currentGrid by rememberUpdatedState(grid) val currentState by rememberUpdatedState(state) + val currentReduceMotion by rememberUpdatedState(reduceMotion) + val currentSwitchSpec by rememberUpdatedState(switchSpec) + val currentLongSwitchSpec by rememberUpdatedState(longSwitchSpec) + + /** + * Resize the columns from [fromSpan] of [from] to [toSpan] of [to], then + * [land] there: whatever moves the target view's pages onto [toSpan] that + * hasn't already, in the same frame as it is shown. + */ + suspend fun resize(from: CalendarView, fromSpan: DaySpan, to: CalendarView, toSpan: DaySpan, land: () -> Unit) { + val fromLoaded = viewModels[from].span(fromSpan) + val toLoaded = viewModels[to].span(toSpan) + if (currentReduceMotion || currentState !is WeekUiState.Success) { + land() + shown = to + return + } + val switch = TimelineMorph(from.timelineKind, to.timelineKind, fromSpan, toSpan, fromLoaded, toLoaded) + try { + withTimeoutOrNull(MORPH_DATA_WAIT_MS) { toLoaded.first { it !is WeekUiState.Loading } } + morph = switch + switch.progress.animateTo(1f, if (switch.isLong) currentLongSwitchSpec else currentSwitchSpec) + handoffStrip = (toLoaded.value as? WeekUiState.Success)?.allDayStripHeight() + land() + shown = to + } finally { + morph = null + } + } + LaunchedEffect(view, navigationVersion) { if (navigationVersion != handledNavigation) { handledNavigation = navigationVersion @@ -437,22 +472,66 @@ private fun PagedTimelineScreen( val toModel = viewModels[view] toModel.jumpTo(target) val to = positionOf(target, toModel.rule.value) - val toSpan = DaySpan(to.grid.startForPage(to.page), to.grid.dayCount) - val fromLoaded = viewModels[from].span(fromSpan) - val toLoaded = toModel.span(toSpan) - if (reduceMotion || currentState !is WeekUiState.Success) { - shown = view - return@LaunchedEffect + resize(from, fromSpan, view, DaySpan(to.grid.startForPage(to.page), to.grid.dayCount)) {} + } + + // A sideways pinch steps through day counts (#389). Each step resizes the + // columns like a view switch; steps queue behind the one resizing, the + // latest winning, and the host is told the view once a step lands. + val haptics = LocalHapticFeedback.current + val currentOnPinchView by rememberUpdatedState(onPinchView) + val pinchTargets = remember { Channel(Channel.CONFLATED) } + LaunchedEffect(pinchTargets) { + for (target in pinchTargets) { + snapshotFlow { morph }.first { it == null } + // Off the view model rather than the pager: a step that just landed + // has moved the one and not yet recomposed the other. + val from = shown + val fromModel = viewModels[from] + val at = positionOf(fromModel.anchor.value, fromModel.rule.value) + val fromSpan = DaySpan(at.grid.startForPage(at.page), at.grid.dayCount) + if (from == target.view && fromSpan == target.span) continue + resize(from, fromSpan, target.view, target.span) { + focus?.date = target.span.start + val multiDay = viewModels.multiDay + when { + target.view != CalendarView.MultiDay -> viewModels[target.view].jumpTo(target.span.start) + target.rangeCount != null -> multiDay.showRange(target.span.start, target.rangeCount) + else -> { + multiDay.clearRange() + multiDay.jumpTo(target.span.start) + } + } + currentOnPinchView(target.view) + } } - val switch = TimelineMorph(from.timelineKind, view.timelineKind, fromSpan, toSpan, fromLoaded, toLoaded) - try { - withTimeoutOrNull(MORPH_DATA_WAIT_MS) { toLoaded.first { it !is WeekUiState.Loading } } - morph = switch - switch.progress.animateTo(1f, if (switch.isLong) longSwitchSpec else switchSpec) - handoffStrip = (toLoaded.value as? WeekUiState.Success)?.allDayStripHeight() - shown = view - } finally { - morph = null + } + val density = LocalDensity.current + val isRtl = LocalLayoutDirection.current == LayoutDirection.Rtl + val gutterPx = with(density) { GUTTER_WIDTH.toPx() } + val endInsetPx = with(density) { TIMELINE_CONTENT_END_INSET.toPx() } + val pinchHandler = remember(gutterPx, endInsetPx, isRtl, haptics) { + object : DayCountPinchHandler { + var pinch: DayPinch? = null + + fun fraction(x: Float, width: Float) = columnFraction(x, width, gutterPx, endInsetPx, isRtl) + + override fun begin(x: Float, width: Float): Boolean { + if (morph != null || currentState !is WeekUiState.Success) return false + val page = DaySpan(currentGrid.startForPage(currentPager.currentPage), currentGrid.dayCount) + pinch = DayPinch.start(currentShown, page, viewModels.multiDay.rangeCount.value, fraction(x, width)) + return true + } + + override fun update(zoom: Float, x: Float, width: Float) { + val target = pinch?.step(zoom, fraction(x, width)) ?: return + haptics.performHapticFeedback(HapticFeedbackType.SegmentTick) + pinchTargets.trySend(target) + } + + override fun end() { + pinch = null + } } } @@ -528,6 +607,7 @@ private fun PagedTimelineScreen( onCreateAt = onCreateEvent, onCreateDraft = onCreateDraft, draftMinutes = draftMinutes, + pinchHandler = pinchHandler, modifier = Modifier .padding(innerPadding) .fillMaxSize(), @@ -552,6 +632,7 @@ private fun WeekContent( onCreateAt: (LocalDate, Int) -> Unit, onCreateDraft: (Instant, Instant) -> Unit, draftMinutes: Int, + pinchHandler: DayCountPinchHandler, modifier: Modifier = Modifier, ) { val fadeSpec = rememberCalendarFadeSpec() @@ -683,6 +764,7 @@ private fun WeekContent( } } + val pinchLock = remember { PinchAxisLock() } val actions = rememberTimelineActions( scrollState = scrollState, dragController = dragController, @@ -692,9 +774,17 @@ private fun WeekContent( onDrop = onDrop, onResize = onResize, onStripDrop = onStripDrop, + pinchLock = pinchLock, ) + // A held block or bar keeps its gesture; a second finger ends that drag anyway. + val dayPinch = remember(pinchHandler, dragController) { + object : DayCountPinchHandler by pinchHandler { + override fun begin(x: Float, width: Float): Boolean = + !dragController.isDragging && pinchHandler.begin(x, width) + } + } - Box(modifier = modifier) { + Box(modifier = modifier.dayCountPinch(pinchLock, dayPinch)) { CompositionLocalProvider(LocalOpeningTimeline provides timelineScroll) { // Loading and failure concern the provider as a whole, so they stand in // for the pager; a page still loading its own week handles that itself. @@ -972,7 +1062,7 @@ private fun WeekFrame( scrollState = actions.scrollState, hourHeight = hourHeight, dragController = actions.dragController, - modifier = rememberTimelinePinchZoom(actions.scrollState, fitHeight, hourHeight, zoom), + modifier = rememberTimelinePinchZoom(actions.scrollState, fitHeight, hourHeight, zoom, actions.pinchLock), ) } } @@ -1406,7 +1496,7 @@ private fun Timeline( // The pinch sits above the scroll viewport: it has to outrank the // vertical scroll, and it does that by watching the initial pass, which // only reaches it if it is the viewport's ancestor. - val pinch = rememberTimelinePinchZoom(scrollState, fitHeight, hourHeight, zoom) + val pinch = rememberTimelinePinchZoom(scrollState, fitHeight, hourHeight, zoom, actions.pinchLock) // What a block's text is fitted to: the column it will end up in once a // view switch is past half way, so it reflows once rather than per frame. val textColumns by remember(geometry) { diff --git a/app/src/main/java/de/jeanlucmakiola/calendula/ui/week/WeekViewModel.kt b/app/src/main/java/de/jeanlucmakiola/calendula/ui/week/WeekViewModel.kt index db4c04a5..d093845d 100644 --- a/app/src/main/java/de/jeanlucmakiola/calendula/ui/week/WeekViewModel.kt +++ b/app/src/main/java/de/jeanlucmakiola/calendula/ui/week/WeekViewModel.kt @@ -40,6 +40,7 @@ import kotlinx.coroutines.flow.flowOf import kotlinx.coroutines.flow.flowOn import kotlinx.coroutines.flow.map import kotlinx.coroutines.flow.stateIn +import kotlinx.coroutines.launch import kotlinx.datetime.DateTimeUnit import kotlinx.datetime.DayOfWeek import kotlinx.datetime.LocalDate @@ -126,12 +127,34 @@ abstract class PagedTimelineViewModel( private val _anchor = MutableStateFlow(todayDate) val anchor: StateFlow = _anchor + private var settingsRule: (LocalDate) -> DaysGrid = initialRule + private var heldRule: ((LocalDate) -> DaysGrid)? = null + private val _rule = MutableStateFlow(initialRule) + /** * The grid for a given anchor, held eagerly so a screen can place its pager * on its very first frame rather than a frame after the anchor moved. */ - val rule: StateFlow<(LocalDate) -> DaysGrid> = - gridRule.stateIn(viewModelScope, SharingStarted.Eagerly, initialRule) + val rule: StateFlow<(LocalDate) -> DaysGrid> = _rule + + init { + viewModelScope.launch { + gridRule.collect { + settingsRule = it + if (heldRule == null) _rule.value = it + } + } + } + + /** + * Cut the pages by [rule] instead of the one from Settings until it is + * released with null. Takes effect at once, so a caller can place a pager + * on it in the same frame. + */ + protected fun holdRule(rule: ((LocalDate) -> DaysGrid)?) { + heldRule = rule + _rule.value = rule ?: settingsRule + } /** Today, kept current across midnight so a page left open doesn't mark yesterday (#373). */ private val today: StateFlow = @@ -252,7 +275,8 @@ class WeekViewModel @Inject constructor( /** * The multi-day view (#193): runs of the day count from Settings, with the * anchor always a page's first day, so today — or a date jumped to — opens in - * the first column. + * the first column. A pinch or a range picked in the month (#389) overrides + * the count for the session, until a view is picked from the switcher. */ @HiltViewModel class MultiDayViewModel @Inject constructor( @@ -272,7 +296,26 @@ class MultiDayViewModel @Inject constructor( }, initialRule = { DaysGrid.startingAt(it, SettingsPrefs.DEFAULT_MULTI_DAY_COUNT) }, view = CalendarView.MultiDay, -) +) { + private val _rangeCount = MutableStateFlow(null) + + /** The day count picked for this session, or null for the one from Settings. */ + val rangeCount: StateFlow = _rangeCount + + /** Show [count] days from [start], paging by [count] from there. */ + fun showRange(start: LocalDate, count: Int) { + _rangeCount.value = count + holdRule { anchor -> DaysGrid.startingAt(anchor, count) } + jumpTo(start) + } + + /** Back to the day count from Settings. */ + fun clearRange() { + if (_rangeCount.value == null) return + _rangeCount.value = null + holdRule(null) + } +} /** The day view: the timeline one day at a time. */ @HiltViewModel diff --git a/app/src/test/java/de/jeanlucmakiola/calendula/ui/common/PinchAxisTest.kt b/app/src/test/java/de/jeanlucmakiola/calendula/ui/common/PinchAxisTest.kt new file mode 100644 index 00000000..3353d76f --- /dev/null +++ b/app/src/test/java/de/jeanlucmakiola/calendula/ui/common/PinchAxisTest.kt @@ -0,0 +1,33 @@ +package de.jeanlucmakiola.calendula.ui.common + +import androidx.compose.ui.geometry.Offset +import com.google.common.truth.Truth.assertThat +import org.junit.jupiter.api.Test + +/** Telling a sideways pinch from an up-and-down one (#389). */ +class PinchAxisTest { + + @Test + fun `fingers spreading sideways lock to the day count`() { + assertThat(lockPinchAxis(spreadChangeX = 30f, spreadChangeY = 4f)).isEqualTo(PinchAxis.Horizontal) + assertThat(lockPinchAxis(spreadChangeX = -30f, spreadChangeY = 4f)).isEqualTo(PinchAxis.Horizontal) + } + + @Test + fun `fingers spreading up and down keep the hour zoom`() { + assertThat(lockPinchAxis(spreadChangeX = 3f, spreadChangeY = -30f)).isEqualTo(PinchAxis.Vertical) + } + + @Test + fun `a diagonal pinch stays the hour zoom it always was`() { + assertThat(lockPinchAxis(spreadChangeX = 20f, spreadChangeY = 20f)).isEqualTo(PinchAxis.Vertical) + assertThat(lockPinchAxis(spreadChangeX = 24f, spreadChangeY = 20f)).isEqualTo(PinchAxis.Vertical) + assertThat(lockPinchAxis(spreadChangeX = 30f, spreadChangeY = 20f)).isEqualTo(PinchAxis.Horizontal) + } + + @Test + fun `spread is the mean distance from the centroid per axis`() { + assertThat(spreadOf(listOf(Offset(0f, 10f), Offset(100f, 30f)))).isEqualTo(Offset(50f, 10f)) + assertThat(spreadOf(emptyList())).isEqualTo(Offset.Zero) + } +} diff --git a/app/src/test/java/de/jeanlucmakiola/calendula/ui/common/ViewBackStackTest.kt b/app/src/test/java/de/jeanlucmakiola/calendula/ui/common/ViewBackStackTest.kt index 9d830249..1adcd775 100644 --- a/app/src/test/java/de/jeanlucmakiola/calendula/ui/common/ViewBackStackTest.kt +++ b/app/src/test/java/de/jeanlucmakiola/calendula/ui/common/ViewBackStackTest.kt @@ -154,4 +154,24 @@ class ViewBackStackTest { ) assertThat(config.cycle.size).isAtLeast(QuickSwitchConfig.MIN_CYCLE) } + + @Test + fun `a pinch over the home view goes on top of it`() { + assertThat(listOf(CalendarView.Week).swapView(CalendarView.MultiDay)) + .containsExactly(CalendarView.Week, CalendarView.MultiDay).inOrder() + } + + @Test + fun `a pinch swaps the view on top in place`() { + val stack = listOf(CalendarView.Month, CalendarView.Week) + assertThat(stack.swapView(CalendarView.MultiDay)) + .containsExactly(CalendarView.Month, CalendarView.MultiDay).inOrder() + assertThat(stack.swapView(CalendarView.Week)).isEqualTo(stack) + } + + @Test + fun `a pinch back to the home view returns to it`() { + assertThat(listOf(CalendarView.Week, CalendarView.Day).swapView(CalendarView.Week)) + .containsExactly(CalendarView.Week) + } } diff --git a/app/src/test/java/de/jeanlucmakiola/calendula/ui/week/DayCountPinchTest.kt b/app/src/test/java/de/jeanlucmakiola/calendula/ui/week/DayCountPinchTest.kt new file mode 100644 index 00000000..0c62dd38 --- /dev/null +++ b/app/src/test/java/de/jeanlucmakiola/calendula/ui/week/DayCountPinchTest.kt @@ -0,0 +1,122 @@ +package de.jeanlucmakiola.calendula.ui.week + +import com.google.common.truth.Truth.assertThat +import de.jeanlucmakiola.calendula.ui.common.CalendarView +import kotlinx.datetime.LocalDate +import org.junit.jupiter.api.Test +import kotlin.math.pow + +/** A sideways pinch stepping through day counts (#389). */ +class DayCountPinchTest { + + private fun steps(n: Float) = 1.2f.pow(n) + + @Test + fun `a small spread keeps the count`() { + assertThat(steppedDayCount(current = 7, origin = 7, zoom = 1.1f)).isEqualTo(7) + } + + @Test + fun `a step's worth of spread shows a day less, closing shows a day more`() { + assertThat(steppedDayCount(current = 7, origin = 7, zoom = steps(1f))).isEqualTo(6) + assertThat(steppedDayCount(current = 3, origin = 3, zoom = steps(-1f))).isEqualTo(4) + } + + @Test + fun `seven to one day fits in one pinch`() { + assertThat(steppedDayCount(current = 7, origin = 7, zoom = steps(6f))).isEqualTo(1) + } + + @Test + fun `a step is taken past the midpoint and given back only past it the other way`() { + // Just past half a step: not yet. + assertThat(steppedDayCount(current = 7, origin = 7, zoom = steps(0.6f))).isEqualTo(7) + // At six, the same spread holds six rather than flicking back. + assertThat(steppedDayCount(current = 6, origin = 7, zoom = steps(0.6f))).isEqualTo(6) + assertThat(steppedDayCount(current = 6, origin = 7, zoom = steps(0.25f))).isEqualTo(7) + } + + @Test + fun `the count stays between one day and a week`() { + assertThat(steppedDayCount(current = 3, origin = 3, zoom = 100f)).isEqualTo(1) + assertThat(steppedDayCount(current = 3, origin = 3, zoom = 0.01f)).isEqualTo(7) + } + + @Test + fun `a pinch starting on more days than a week can close back to them`() { + assertThat(pinchDayRange(10)).isEqualTo(1..10) + assertThat(steppedDayCount(current = 10, origin = 10, zoom = 0.01f)).isEqualTo(10) + assertThat(steppedDayCount(current = 10, origin = 10, zoom = steps(1f))).isEqualTo(9) + } + + @Test + fun `the fingers' place is read across the day columns only`() { + assertThat(columnFraction(x = 100f, width = 1000f, gutterPx = 100f, endInsetPx = 20f, isRtl = false)) + .isEqualTo(0f) + assertThat(columnFraction(x = 540f, width = 1000f, gutterPx = 100f, endInsetPx = 20f, isRtl = false)) + .isEqualTo(0.5f) + assertThat(columnFraction(x = 50f, width = 1000f, gutterPx = 100f, endInsetPx = 20f, isRtl = false)) + .isEqualTo(0f) + assertThat(columnFraction(x = 995f, width = 1000f, gutterPx = 100f, endInsetPx = 20f, isRtl = false)) + .isEqualTo(1f) + } + + @Test + fun `right to left the first day is on the right, past the gutter`() { + assertThat(columnFraction(x = 460f, width = 1000f, gutterPx = 100f, endInsetPx = 20f, isRtl = true)) + .isEqualTo(0.5f) + assertThat(columnFraction(x = 900f, width = 1000f, gutterPx = 100f, endInsetPx = 20f, isRtl = true)) + .isEqualTo(0f) + } + + @Test + fun `the day under the fingers stays in their column`() { + val day = LocalDate(2026, 10, 16) + assertThat(anchoredStart(day, fraction = 0.5f, count = 3)).isEqualTo(LocalDate(2026, 10, 15)) + // The run the issue could not reach: the 16th first, from a pinch on the left. + assertThat(anchoredStart(day, fraction = 0.1f, count = 3)).isEqualTo(day) + assertThat(anchoredStart(day, fraction = 1f, count = 3)).isEqualTo(LocalDate(2026, 10, 14)) + assertThat(anchoredStart(day, fraction = 0.9f, count = 1)).isEqualTo(day) + } + + @Test + fun `the day under a fraction of a span`() { + val span = DaySpan(LocalDate(2026, 10, 12), 7) + assertThat(span.dayAt(0f)).isEqualTo(LocalDate(2026, 10, 12)) + assertThat(span.dayAt(0.6f)).isEqualTo(LocalDate(2026, 10, 16)) + assertThat(span.dayAt(1f)).isEqualTo(LocalDate(2026, 10, 18)) + } + + @Test + fun `one day is the day view, more the multi-day view`() { + assertThat(pinchedView(1)).isEqualTo(CalendarView.Day) + assertThat(pinchedView(2)).isEqualTo(CalendarView.MultiDay) + assertThat(pinchedView(7)).isEqualTo(CalendarView.MultiDay) + } + + @Test + fun `a pinch from the week anchors on the day under the fingers and gives the week back`() { + val week = DaySpan(LocalDate(2026, 10, 12), 7) + val pinch = DayPinch.start(CalendarView.Week, week, rangeCount = null, fraction = 0.6f) + + assertThat(pinch.step(zoom = 1.05f, fraction = 0.6f)).isNull() + assertThat(pinch.step(zoom = steps(1f), fraction = 0.6f)).isEqualTo( + PinchTarget(CalendarView.MultiDay, DaySpan(LocalDate(2026, 10, 13), 6), rangeCount = 6), + ) + assertThat(pinch.step(zoom = 1f, fraction = 0.6f)) + .isEqualTo(PinchTarget(CalendarView.Week, week, rangeCount = null)) + assertThat(pinch.step(zoom = steps(6f), fraction = 0.6f)) + .isEqualTo(PinchTarget(CalendarView.Day, DaySpan(LocalDate(2026, 10, 16), 1), rangeCount = null)) + assertThat(pinch.count).isEqualTo(1) + } + + @Test + fun `a pinch back to the multi-day count it started on restores its session count`() { + val run = DaySpan(LocalDate(2026, 10, 15), 4) + val pinch = DayPinch.start(CalendarView.MultiDay, run, rangeCount = 4, fraction = 0f) + assertThat(pinch.step(zoom = steps(-1f), fraction = 0f)) + .isEqualTo(PinchTarget(CalendarView.MultiDay, DaySpan(LocalDate(2026, 10, 15), 5), rangeCount = 5)) + assertThat(pinch.step(zoom = 1f, fraction = 0f)) + .isEqualTo(PinchTarget(CalendarView.MultiDay, run, rangeCount = 4)) + } +} diff --git a/docs/ARCHITECTURE.md b/docs/ARCHITECTURE.md index 327a8120..4ebfad3a 100644 --- a/docs/ARCHITECTURE.md +++ b/docs/ARCHITECTURE.md @@ -137,6 +137,13 @@ gesture finishes from its scaled preview. out. Blocks sit in their column as shares of its width (`LaneColumn`), so nothing recomposes per frame. The frame starts and ends exactly as the two pages lay out, so the pagers either side hand over without a jump. +- **A sideways pinch steps the day count (#389).** `dayCountPinch` sits above + the pager and decides each two-finger gesture's axis once (`PinchAxisLock`): + up-and-down stays the hour zoom, sideways steps 7…1 days with hysteresis + (`steppedDayCount`), each step a column resize like a view switch, anchored + on the day under the fingers. One day is the day view, more the multi-day + view with a session day count (`MultiDayViewModel.showRange`) that the + switcher clears; the pinch swaps the view in place on the back stack. - **Across screens, what both show morphs.** Inside a `SharedTransitionLayout`, an event shown in both views travels from its old bounds to its new ones, keyed per occurrence *and* per day it is drawn from (`ViewMorphKey`); only a