这是indexloc提供的服务,不要输入任何密码
Skip to content

Predictive back support for ThreePane #8

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 1 commit into from
Oct 19, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
@@ -0,0 +1,52 @@
/*
* Copyright 2021 Google LLC
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/

package com.tunjid.treenav.compose.configurations

import androidx.compose.foundation.layout.Box
import androidx.compose.ui.Modifier
import com.tunjid.treenav.Node
import com.tunjid.treenav.compose.PaneScope
import com.tunjid.treenav.compose.PanedNavHostConfiguration
import com.tunjid.treenav.compose.delegated
import com.tunjid.treenav.compose.paneStrategy

/**
* A [PanedNavHostConfiguration] that allows for centrally defining the [Modifier] for
* each [Pane] displayed within it.
*
* @param paneModifier a lambda for specifying the [Modifier] for each [Pane] in a [PaneScope].
*/
fun <Pane, NavigationState : Node, Destination : Node> PanedNavHostConfiguration<
Pane,
NavigationState,
Destination
>.paneModifierConfiguration(
paneModifier: PaneScope<Pane, Destination>.() -> Modifier = { Modifier },
): PanedNavHostConfiguration<Pane, NavigationState, Destination> = delegated {
val originalTransform = strategyTransform(it)
paneStrategy(
transitions = originalTransform.transitions,
paneMapping = originalTransform.paneMapper,
render = render@{ destination ->
Box(
modifier = paneModifier()
) {
originalTransform.render(this@render, destination)
}
}
)
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,76 @@
/*
* Copyright 2021 Google LLC
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/

package com.tunjid.treenav.compose.threepane.configurations

import androidx.compose.runtime.State
import androidx.compose.runtime.getValue
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.setValue
import com.tunjid.treenav.Node
import com.tunjid.treenav.compose.PanedNavHostConfiguration
import com.tunjid.treenav.compose.delegated
import com.tunjid.treenav.compose.paneStrategy
import com.tunjid.treenav.compose.threepane.ThreePane

/**
* An [PanedNavHostConfiguration] that moves the destination in a [ThreePane.Primary] pane, to
* to the [ThreePane.TransientPrimary] pane when a predictive back gesture is in progress.
*
* @param isPreviewingBack provides the state of the predictive back gesture.
* True if the gesture is ongoing.
* @param backPreviewTransform provides the [NavigationState] if the predictive back gesture
* were to be completed.
*/
inline fun <NavigationState : Node, reified Destination : Node> PanedNavHostConfiguration<
ThreePane,
NavigationState,
Destination
>.predictiveBackConfiguration(
isPreviewingBack: State<Boolean>,
crossinline backPreviewTransform: NavigationState.() -> NavigationState,
): PanedNavHostConfiguration<ThreePane, NavigationState, Destination> {
var lastPrimaryDestination by mutableStateOf<Destination?>(null)
return delegated(
destinationTransform = { navigationState ->
val current = destinationTransform(navigationState)
lastPrimaryDestination = current
if (isPreviewingBack.value) destinationTransform(navigationState.backPreviewTransform())
else current
},
strategyTransform = { destination ->
val originalStrategy = strategyTransform(destination)
paneStrategy(
transitions = originalStrategy.transitions,
paneMapping = paneMapper@{ inner ->
val originalMapping = originalStrategy.paneMapper(inner)
val isPreviewing by isPreviewingBack
if (!isPreviewing) return@paneMapper originalMapping
// Back is being previewed, therefore the original mapping is already for back.
// Pass the previous primary value into transient.
val transientDestination = checkNotNull(lastPrimaryDestination) {
"Attempted to show last destination without calling destination transform"
}
val paneMapping = strategyTransform(transientDestination)
.paneMapper(transientDestination)
val transient = paneMapping[ThreePane.Primary]
originalMapping + (ThreePane.TransientPrimary to transient)
},
render = originalStrategy.render
)
}
)
}
1 change: 1 addition & 0 deletions sample/android/src/main/AndroidManifest.xml
Original file line number Diff line number Diff line change
Expand Up @@ -23,6 +23,7 @@
android:label="@string/app_name"
android:roundIcon="@mipmap/ic_launcher_round"
android:supportsRtl="true"
android:enableOnBackInvokedCallback="true"
android:theme="@style/Theme.Tyler">
<activity
android:name="com.tunjid.tyler.MainActivity"
Expand Down
25 changes: 24 additions & 1 deletion sample/android/src/main/java/com/tunjid/tyler/MainActivity.kt
Original file line number Diff line number Diff line change
Expand Up @@ -17,19 +17,42 @@
package com.tunjid.tyler

import android.os.Bundle
import androidx.activity.BackEventCompat
import androidx.activity.compose.PredictiveBackHandler
import androidx.activity.compose.setContent
import androidx.activity.enableEdgeToEdge
import androidx.appcompat.app.AppCompatActivity
import androidx.compose.runtime.remember
import androidx.compose.ui.geometry.Offset
import com.tunjid.demo.common.ui.AppTheme
import com.tunjid.demo.common.ui.SampleApp
import com.tunjid.demo.common.ui.SampleAppState
import kotlinx.coroutines.flow.Flow
import kotlinx.coroutines.flow.collectIndexed
import kotlin.coroutines.cancellation.CancellationException

class MainActivity : AppCompatActivity() {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
enableEdgeToEdge()
setContent {
AppTheme {
SampleApp()
val appState = remember { SampleAppState() }
SampleApp(appState)

PredictiveBackHandler { progress: Flow<BackEventCompat> ->
try {
progress.collectIndexed { index, backEvent ->
// if (index == 0) onStarted()
val touchOffset = Offset(backEvent.touchX, backEvent.touchY)
val progressFraction = backEvent.progress
appState.updatePredictiveBack(touchOffset, progressFraction)
}
appState.goBack()
} catch (e: CancellationException) {
appState.cancelPredictiveBack()
}
}
}
}
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -18,26 +18,32 @@ package com.tunjid.demo.common.ui

import androidx.compose.animation.ExperimentalSharedTransitionApi
import androidx.compose.animation.SharedTransitionScope
import androidx.compose.foundation.background
import androidx.compose.foundation.layout.Box
import androidx.compose.foundation.layout.Row
import androidx.compose.foundation.layout.Spacer
import androidx.compose.foundation.layout.fillMaxHeight
import androidx.compose.foundation.layout.fillMaxSize
import androidx.compose.material3.Icon
import androidx.compose.material3.MaterialTheme
import androidx.compose.material3.Text
import androidx.compose.material3.adaptive.ExperimentalMaterial3AdaptiveApi
import androidx.compose.material3.adaptive.navigationsuite.NavigationSuiteScaffold
import androidx.compose.runtime.Composable
import androidx.compose.runtime.DisposableEffect
import androidx.compose.runtime.Stable
import androidx.compose.runtime.State
import androidx.compose.runtime.derivedStateOf
import androidx.compose.runtime.getValue
import androidx.compose.runtime.mutableFloatStateOf
import androidx.compose.runtime.mutableIntStateOf
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.remember
import androidx.compose.ui.Modifier
import androidx.compose.ui.geometry.Offset
import androidx.compose.ui.layout.onSizeChanged
import androidx.compose.ui.platform.LocalDensity
import androidx.compose.ui.unit.IntOffset
import androidx.compose.ui.unit.round
import com.tunjid.demo.common.ui.SampleAppState.Companion.rememberPanedNavHostState
import com.tunjid.demo.common.ui.chat.chatPaneStrategy
import com.tunjid.demo.common.ui.chatrooms.chatRoomPaneStrategy
Expand All @@ -51,20 +57,23 @@ import com.tunjid.treenav.compose.PanedNavHost
import com.tunjid.treenav.compose.PanedNavHostConfiguration
import com.tunjid.treenav.compose.SavedStatePanedNavHostState
import com.tunjid.treenav.compose.configurations.animatePaneBoundsConfiguration
import com.tunjid.treenav.compose.configurations.paneModifierConfiguration
import com.tunjid.treenav.compose.moveablesharedelement.MovableSharedElementHostState
import com.tunjid.treenav.compose.panedNavHostConfiguration
import com.tunjid.treenav.compose.threepane.ThreePane
import com.tunjid.treenav.compose.threepane.configurations.canAnimateOnStartingFrames
import com.tunjid.treenav.compose.threepane.configurations.predictiveBackConfiguration
import com.tunjid.treenav.compose.threepane.configurations.threePanedMovableSharedElementConfiguration
import com.tunjid.treenav.compose.threepane.configurations.threePanedNavHostConfiguration
import com.tunjid.treenav.current
import com.tunjid.treenav.pop
import com.tunjid.treenav.popToRoot
import kotlinx.coroutines.CoroutineScope
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.launch
import kotlin.math.roundToInt

@OptIn(ExperimentalSharedTransitionApi::class, ExperimentalMaterial3AdaptiveApi::class)
@OptIn(ExperimentalSharedTransitionApi::class)
@Composable
fun SampleApp(
appState: SampleAppState = remember { SampleAppState() },
Expand All @@ -83,19 +92,36 @@ fun SampleApp(
) {
SharedTransitionScope { sharedTransitionModifier ->
val windowWidthDp = remember { mutableIntStateOf(0) }
val surfaceColor = MaterialTheme.colorScheme.surface
val density = LocalDensity.current
val movableSharedElementHostState = remember {
MovableSharedElementHostState(
sharedTransitionScope = this,
canAnimateOnStartingFrames = PaneState<ThreePane, SampleDestination>::canAnimateOnStartingFrames
)
}

PanedNavHost(
state = appState.rememberPanedNavHostState {
this
.paneModifierConfiguration {
if (paneState.pane == ThreePane.TransientPrimary) Modifier
.background(surfaceColor)
.fillMaxSize()
.predictiveBackModifier(
touchOffsetState = appState.backTouchOffsetState,
progressState = appState.backProgressFractionState
)
else Modifier.fillMaxSize()

}
.threePanedNavHostConfiguration(
windowWidthDpState = windowWidthDp
)
.predictiveBackConfiguration(
isPreviewingBack = appState.predictiveBackStatus,
backPreviewTransform = MultiStackNav::pop,
)
.threePanedMovableSharedElementConfiguration(
movableSharedElementHostState = movableSharedElementHostState
)
Expand Down Expand Up @@ -141,6 +167,7 @@ fun SampleApp(
.fillMaxHeight()
) {
Destination(pane)
if (pane == ThreePane.Primary) Destination(ThreePane.TransientPrimary)
}
}
}
Expand All @@ -157,19 +184,41 @@ class SampleAppState(
private val navigationState = mutableStateOf(
navigationRepository.navigationStateFlow.value
)
val currentNavigation by navigationState

private val panedNavHostConfiguration = sampleAppNavHostConfiguration(
navigationState
)

val backTouchOffsetState = mutableStateOf(IntOffset.Zero)
val backProgressFractionState = mutableFloatStateOf(Float.NaN)

val currentNavigation by navigationState
val predictiveBackStatus = derivedStateOf { !backProgressFractionState.value.isNaN() }

fun setTab(destination: SampleDestination.NavTabs) {
navigationRepository.navigate {
if (it.currentIndex == destination.ordinal) it.popToRoot()
else it.copy(currentIndex = destination.ordinal)
}
}

fun updatePredictiveBack(
touchOffset: Offset,
fraction: Float,
) {
backTouchOffsetState.value = touchOffset.round()
backProgressFractionState.value = fraction
}

fun cancelPredictiveBack() {
backTouchOffsetState.value = IntOffset.Zero
backProgressFractionState.value = Float.NaN
}

fun goBack() {
cancelPredictiveBack()
navigationRepository.navigate(MultiStackNav::pop)
}

companion object {
@Composable
fun SampleAppState.rememberPanedNavHostState(
Expand Down
Loading
Loading