Android: swipe between tree and chat, servers, and chat tabs
A sideways swipe over the channel tree turns to the chat (lying to its
right) or to the neighbouring connected server, as picked in Design
settings ("Swipe sideways": off, channel tree and chat, connected
servers). A swipe over the chat lines goes to the neighbouring tab, on
by default, and the tab row scrolls it into view. The page beside the
one on show follows the finger (SwipeHost); a swipe with nowhere to go
is left to the host further out, so the chat's tabs hand over to the
chat/tree swipe at either end. The choices are Android-only, kept in
their own SharedPreferences (SwipePrefs).
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
@@ -165,6 +165,8 @@ class SessionController(private val context: Context) {
|
|||||||
private val _route = MutableStateFlow(routePrefs.load())
|
private val _route = MutableStateFlow(routePrefs.load())
|
||||||
val route: StateFlow<AudioRoute> = _route
|
val route: StateFlow<AudioRoute> = _route
|
||||||
|
|
||||||
|
val swipe = SwipePrefs(context)
|
||||||
|
|
||||||
private val _inputDevices = MutableStateFlow(audio.io().inputDevices())
|
private val _inputDevices = MutableStateFlow(audio.io().inputDevices())
|
||||||
val inputDevices: StateFlow<List<AudioDevice>> = _inputDevices
|
val inputDevices: StateFlow<List<AudioDevice>> = _inputDevices
|
||||||
private val _outputDevices = MutableStateFlow(audio.io().outputDevices())
|
private val _outputDevices = MutableStateFlow(audio.io().outputDevices())
|
||||||
|
|||||||
@@ -0,0 +1,37 @@
|
|||||||
|
package eu.lixko.ts3j.client.android
|
||||||
|
|
||||||
|
import android.content.Context
|
||||||
|
import kotlinx.coroutines.flow.MutableStateFlow
|
||||||
|
import kotlinx.coroutines.flow.StateFlow
|
||||||
|
|
||||||
|
/** What a sideways swipe over the channel tree does. */
|
||||||
|
enum class TreeSwipe { OFF, CHAT, SERVERS }
|
||||||
|
|
||||||
|
/** The swipe gestures, an Android-only choice kept apart from the shared settings. */
|
||||||
|
class SwipePrefs(context: Context) {
|
||||||
|
|
||||||
|
private val prefs = context.getSharedPreferences("swipe", Context.MODE_PRIVATE)
|
||||||
|
|
||||||
|
private val _tree = MutableStateFlow(
|
||||||
|
TreeSwipe.entries.firstOrNull { it.name == prefs.getString(TREE, null) } ?: TreeSwipe.CHAT)
|
||||||
|
val tree: StateFlow<TreeSwipe> = _tree
|
||||||
|
|
||||||
|
private val _chatTabs = MutableStateFlow(prefs.getBoolean(CHAT_TABS, true))
|
||||||
|
/** Whether a sideways swipe over the chat goes to the neighbouring conversation. */
|
||||||
|
val chatTabs: StateFlow<Boolean> = _chatTabs
|
||||||
|
|
||||||
|
fun setTree(swipe: TreeSwipe) {
|
||||||
|
prefs.edit().putString(TREE, swipe.name).apply()
|
||||||
|
_tree.value = swipe
|
||||||
|
}
|
||||||
|
|
||||||
|
fun setChatTabs(enabled: Boolean) {
|
||||||
|
prefs.edit().putBoolean(CHAT_TABS, enabled).apply()
|
||||||
|
_chatTabs.value = enabled
|
||||||
|
}
|
||||||
|
|
||||||
|
private companion object {
|
||||||
|
const val TREE = "tree"
|
||||||
|
const val CHAT_TABS = "chatTabs"
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -4,6 +4,7 @@ import android.Manifest
|
|||||||
import android.content.pm.PackageManager
|
import android.content.pm.PackageManager
|
||||||
import androidx.activity.compose.rememberLauncherForActivityResult
|
import androidx.activity.compose.rememberLauncherForActivityResult
|
||||||
import androidx.activity.result.contract.ActivityResultContracts
|
import androidx.activity.result.contract.ActivityResultContracts
|
||||||
|
import androidx.compose.foundation.layout.fillMaxSize
|
||||||
import androidx.compose.material3.AlertDialog
|
import androidx.compose.material3.AlertDialog
|
||||||
import androidx.compose.material3.SnackbarHostState
|
import androidx.compose.material3.SnackbarHostState
|
||||||
import androidx.compose.material3.Text
|
import androidx.compose.material3.Text
|
||||||
@@ -17,10 +18,12 @@ import androidx.compose.runtime.remember
|
|||||||
import androidx.compose.runtime.saveable.rememberSaveable
|
import androidx.compose.runtime.saveable.rememberSaveable
|
||||||
import androidx.compose.runtime.saveable.rememberSaveableStateHolder
|
import androidx.compose.runtime.saveable.rememberSaveableStateHolder
|
||||||
import androidx.compose.runtime.setValue
|
import androidx.compose.runtime.setValue
|
||||||
|
import androidx.compose.ui.Modifier
|
||||||
import androidx.compose.ui.platform.LocalContext
|
import androidx.compose.ui.platform.LocalContext
|
||||||
import androidx.lifecycle.compose.collectAsStateWithLifecycle
|
import androidx.lifecycle.compose.collectAsStateWithLifecycle
|
||||||
import eu.lixko.ts3j.client.android.SessionController
|
import eu.lixko.ts3j.client.android.SessionController
|
||||||
import eu.lixko.ts3j.client.android.SessionEvent
|
import eu.lixko.ts3j.client.android.SessionEvent
|
||||||
|
import eu.lixko.ts3j.client.android.TreeSwipe
|
||||||
|
|
||||||
@Composable
|
@Composable
|
||||||
fun App(vm: SessionController) {
|
fun App(vm: SessionController) {
|
||||||
@@ -92,11 +95,25 @@ fun App(vm: SessionController) {
|
|||||||
myTeamSpeakOpen -> MyTeamSpeakScreen(vm, onBack = { myTeamSpeakOpen = false })
|
myTeamSpeakOpen -> MyTeamSpeakScreen(vm, onBack = { myTeamSpeakOpen = false })
|
||||||
settingsOpen -> SettingsScreen(vm, onContacts = { openContacts(null) }, onBack = { settingsOpen = false })
|
settingsOpen -> SettingsScreen(vm, onContacts = { openContacts(null) }, onBack = { settingsOpen = false })
|
||||||
server != null && !connectOpen -> {
|
server != null && !connectOpen -> {
|
||||||
serverStates.SaveableStateProvider(server.id) {
|
val servers by vm.servers.collectAsStateWithLifecycle()
|
||||||
CompositionLocalProvider(LocalServerImages provides server.images) {
|
val treeSwipe by vm.swipe.tree.collectAsStateWithLifecycle()
|
||||||
PictureViewerHost(server) {
|
val serverSwipe = rememberSwipeState()
|
||||||
ServerScreen(vm, server, snackbar, { settingsOpen = true }, openContacts, enableMicrophone,
|
SwipeHost(
|
||||||
onConnectOther = { connectOpen = true }, onEditBookmark = { editingBookmark = it })
|
serverSwipe, server,
|
||||||
|
neighbour = { at, dir ->
|
||||||
|
if (treeSwipe != TreeSwipe.SERVERS) null
|
||||||
|
else servers.indexOf(at).takeIf { it >= 0 }?.let { servers.getOrNull(it + dir) }
|
||||||
|
},
|
||||||
|
onSwipe = vm::select,
|
||||||
|
modifier = Modifier.fillMaxSize(),
|
||||||
|
) { shown ->
|
||||||
|
serverStates.SaveableStateProvider(shown.id) {
|
||||||
|
CompositionLocalProvider(LocalServerImages provides shown.images) {
|
||||||
|
PictureViewerHost(shown) {
|
||||||
|
ServerScreen(vm, shown, snackbar, { settingsOpen = true }, openContacts, enableMicrophone,
|
||||||
|
onConnectOther = { connectOpen = true }, onEditBookmark = { editingBookmark = it },
|
||||||
|
serverSwipe = serverSwipe, active = shown == server)
|
||||||
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -5,6 +5,7 @@ import androidx.compose.foundation.layout.Arrangement
|
|||||||
import androidx.compose.foundation.layout.Column
|
import androidx.compose.foundation.layout.Column
|
||||||
import androidx.compose.foundation.layout.PaddingValues
|
import androidx.compose.foundation.layout.PaddingValues
|
||||||
import androidx.compose.foundation.layout.Row
|
import androidx.compose.foundation.layout.Row
|
||||||
|
import androidx.compose.foundation.layout.fillMaxSize
|
||||||
import androidx.compose.foundation.layout.fillMaxWidth
|
import androidx.compose.foundation.layout.fillMaxWidth
|
||||||
import androidx.compose.foundation.layout.padding
|
import androidx.compose.foundation.layout.padding
|
||||||
import androidx.compose.foundation.layout.size
|
import androidx.compose.foundation.layout.size
|
||||||
@@ -29,7 +30,6 @@ import androidx.compose.runtime.Composable
|
|||||||
import androidx.compose.runtime.LaunchedEffect
|
import androidx.compose.runtime.LaunchedEffect
|
||||||
import androidx.compose.runtime.getValue
|
import androidx.compose.runtime.getValue
|
||||||
import androidx.compose.runtime.setValue
|
import androidx.compose.runtime.setValue
|
||||||
import androidx.compose.runtime.key
|
|
||||||
import androidx.compose.runtime.remember
|
import androidx.compose.runtime.remember
|
||||||
import androidx.compose.runtime.rememberUpdatedState
|
import androidx.compose.runtime.rememberUpdatedState
|
||||||
import androidx.compose.runtime.snapshotFlow
|
import androidx.compose.runtime.snapshotFlow
|
||||||
@@ -79,9 +79,23 @@ fun ChatPane(
|
|||||||
/** A line to scroll to. */
|
/** A line to scroll to. */
|
||||||
reveal: Long? = null,
|
reveal: Long? = null,
|
||||||
onRevealed: () -> Unit = {},
|
onRevealed: () -> Unit = {},
|
||||||
|
/** Whether a swipe over the lines goes to the neighbouring conversation. */
|
||||||
|
swipeTabs: Boolean = false,
|
||||||
|
/** For the lines, such as a swipe out of the chat. */
|
||||||
|
linesModifier: Modifier = Modifier,
|
||||||
) {
|
) {
|
||||||
Column(modifier) {
|
Column(modifier) {
|
||||||
|
val tabs = rememberLazyListState()
|
||||||
|
// A conversation picked by other means than its chip, such as a swipe, comes into view.
|
||||||
|
LaunchedEffect(selected.key) {
|
||||||
|
val index = chats.all.indexOfFirst { it.key == selected.key }
|
||||||
|
val info = tabs.layoutInfo
|
||||||
|
if (index >= 0 && info.visibleItemsInfo.none { it.index == index && it.offset >= 0 && it.offset + it.size <= info.viewportEndOffset }) {
|
||||||
|
tabs.animateScrollToItem(index)
|
||||||
|
}
|
||||||
|
}
|
||||||
LazyRow(
|
LazyRow(
|
||||||
|
state = tabs,
|
||||||
contentPadding = PaddingValues(horizontal = 8.dp),
|
contentPadding = PaddingValues(horizontal = 8.dp),
|
||||||
horizontalArrangement = Arrangement.spacedBy(8.dp),
|
horizontalArrangement = Arrangement.spacedBy(8.dp),
|
||||||
) {
|
) {
|
||||||
@@ -89,8 +103,20 @@ fun ChatPane(
|
|||||||
ConversationChip(conversation, conversation.key == selected.key, onSelect, onClose)
|
ConversationChip(conversation, conversation.key == selected.key, onSelect, onClose)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
// Each conversation opens at its newest line.
|
val swipe = rememberSwipeState()
|
||||||
key(selected.key) { Lines(lines, onLink, Modifier.weight(1f), find, current, reveal, onRevealed) }
|
SwipeHost(
|
||||||
|
swipe, selected.key,
|
||||||
|
neighbour = { key, dir ->
|
||||||
|
if (!swipeTabs) null
|
||||||
|
else chats.all.indexOfFirst { it.key == key }.takeIf { it >= 0 }?.let { chats.all.getOrNull(it + dir)?.key }
|
||||||
|
},
|
||||||
|
onSwipe = onSelect,
|
||||||
|
modifier = Modifier.weight(1f).then(linesModifier).swipeSource(swipe),
|
||||||
|
) { key ->
|
||||||
|
// Each conversation opens at its newest line; the one beside it while swiping shows all of its own.
|
||||||
|
if (key == selected.key) Lines(lines, onLink, Modifier.fillMaxSize(), find, current, reveal, onRevealed)
|
||||||
|
else chats[key]?.let { Lines(it.lines, onLink, Modifier.fillMaxSize(), TextQuery.EMPTY, null, null) {} }
|
||||||
|
}
|
||||||
// One unsent message per conversation, kept while another one is on screen.
|
// One unsent message per conversation, kept while another one is on screen.
|
||||||
val drafts = rememberSaveable(saver = DraftsSaver) { mutableStateMapOf<String, String>() }
|
val drafts = rememberSaveable(saver = DraftsSaver) { mutableStateMapOf<String, String>() }
|
||||||
val draftKey = selected.key.toString()
|
val draftKey = selected.key.toString()
|
||||||
|
|||||||
@@ -10,6 +10,7 @@ import androidx.compose.foundation.layout.Box
|
|||||||
import androidx.compose.foundation.layout.Column
|
import androidx.compose.foundation.layout.Column
|
||||||
import androidx.compose.foundation.layout.Row
|
import androidx.compose.foundation.layout.Row
|
||||||
import androidx.compose.foundation.layout.consumeWindowInsets
|
import androidx.compose.foundation.layout.consumeWindowInsets
|
||||||
|
import androidx.compose.foundation.layout.fillMaxSize
|
||||||
import androidx.compose.foundation.layout.fillMaxWidth
|
import androidx.compose.foundation.layout.fillMaxWidth
|
||||||
import androidx.compose.foundation.layout.height
|
import androidx.compose.foundation.layout.height
|
||||||
import androidx.compose.foundation.layout.heightIn
|
import androidx.compose.foundation.layout.heightIn
|
||||||
@@ -78,6 +79,7 @@ import eu.lixko.ts3j.client.android.ServerController
|
|||||||
import eu.lixko.ts3j.client.android.SessionController
|
import eu.lixko.ts3j.client.android.SessionController
|
||||||
import eu.lixko.ts3j.client.android.SessionState
|
import eu.lixko.ts3j.client.android.SessionState
|
||||||
import eu.lixko.ts3j.client.android.TreeFind
|
import eu.lixko.ts3j.client.android.TreeFind
|
||||||
|
import eu.lixko.ts3j.client.android.TreeSwipe
|
||||||
import eu.lixko.ts3j.client.android.findIn
|
import eu.lixko.ts3j.client.android.findIn
|
||||||
import eu.lixko.ts3j.client.config.Settings
|
import eu.lixko.ts3j.client.config.Settings
|
||||||
import eu.lixko.ts3j.client.config.WhisperList
|
import eu.lixko.ts3j.client.config.WhisperList
|
||||||
@@ -129,6 +131,10 @@ fun ServerScreen(
|
|||||||
onEnableMicrophone: () -> Unit,
|
onEnableMicrophone: () -> Unit,
|
||||||
onConnectOther: () -> Unit,
|
onConnectOther: () -> Unit,
|
||||||
onEditBookmark: (BookmarkEdit) -> Unit,
|
onEditBookmark: (BookmarkEdit) -> Unit,
|
||||||
|
/** Turns to another server, for a swipe over the tree. */
|
||||||
|
serverSwipe: SwipeState? = null,
|
||||||
|
/** False for a server beside the one on show while swiping to it. */
|
||||||
|
active: Boolean = true,
|
||||||
) {
|
) {
|
||||||
val state by server.state.collectAsStateWithLifecycle()
|
val state by server.state.collectAsStateWithLifecycle()
|
||||||
val tree by server.tree.collectAsStateWithLifecycle()
|
val tree by server.tree.collectAsStateWithLifecycle()
|
||||||
@@ -181,6 +187,12 @@ fun ServerScreen(
|
|||||||
}
|
}
|
||||||
val infoUpdates by server.infoUpdates.collectAsStateWithLifecycle()
|
val infoUpdates by server.infoUpdates.collectAsStateWithLifecycle()
|
||||||
|
|
||||||
|
val treeSwipe by vm.swipe.tree.collectAsStateWithLifecycle()
|
||||||
|
val chatTabSwipe by vm.swipe.chatTabs.collectAsStateWithLifecycle()
|
||||||
|
// The chat lies to the right of the tree.
|
||||||
|
val chatBesideTree = treeSwipe == TreeSwipe.CHAT
|
||||||
|
val pageSwipe = rememberSwipeState()
|
||||||
|
|
||||||
val chatRequest by server.chatRequest.collectAsStateWithLifecycle()
|
val chatRequest by server.chatRequest.collectAsStateWithLifecycle()
|
||||||
LaunchedEffect(chatRequest) {
|
LaunchedEffect(chatRequest) {
|
||||||
val key = chatRequest ?: return@LaunchedEffect
|
val key = chatRequest ?: return@LaunchedEffect
|
||||||
@@ -190,8 +202,8 @@ fun ServerScreen(
|
|||||||
}
|
}
|
||||||
|
|
||||||
val viewing = if (showChat) conversation.key else null
|
val viewing = if (showChat) conversation.key else null
|
||||||
LifecycleResumeEffect(viewing) {
|
LifecycleResumeEffect(viewing, active) {
|
||||||
server.viewing = viewing
|
if (active) server.viewing = viewing
|
||||||
onPauseOrDispose { server.viewing = null }
|
onPauseOrDispose { server.viewing = null }
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -275,10 +287,10 @@ fun ServerScreen(
|
|||||||
return
|
return
|
||||||
}
|
}
|
||||||
|
|
||||||
BackHandler(showChat) { showChat = false }
|
BackHandler(active && showChat) { showChat = false }
|
||||||
BackHandler(moving != null && !showChat) { moving = null }
|
BackHandler(active && moving != null && !showChat) { moving = null }
|
||||||
BackHandler(moving == null && selection.isNotEmpty() && !showChat) { picked = emptySet() }
|
BackHandler(active && moving == null && selection.isNotEmpty() && !showChat) { picked = emptySet() }
|
||||||
BackHandler(find.open) { find.open = false }
|
BackHandler(active && find.open) { find.open = false }
|
||||||
|
|
||||||
Scaffold(
|
Scaffold(
|
||||||
// A hardware keyboard's Ctrl+F, as on the desktop.
|
// A hardware keyboard's Ctrl+F, as on the desktop.
|
||||||
@@ -319,8 +331,13 @@ fun ServerScreen(
|
|||||||
},
|
},
|
||||||
snackbarHost = { SnackbarHost(snackbar) },
|
snackbarHost = { SnackbarHost(snackbar) },
|
||||||
) { padding ->
|
) { padding ->
|
||||||
Column(Modifier.padding(padding).consumeWindowInsets(padding).imePadding()) {
|
SwipeHost(
|
||||||
if (!showChat) {
|
pageSwipe, showChat,
|
||||||
|
neighbour = { chat, dir -> if (chatBesideTree && (dir > 0) != chat) !chat else null },
|
||||||
|
onSwipe = { showChat = it },
|
||||||
|
modifier = Modifier.padding(padding).consumeWindowInsets(padding).imePadding(),
|
||||||
|
) { chat ->
|
||||||
|
if (!chat) Column(Modifier.fillMaxSize()) {
|
||||||
val movingNow = moving
|
val movingNow = moving
|
||||||
if (movingNow != null) {
|
if (movingNow != null) {
|
||||||
val clients = movingNow.mapNotNull { tree.client(it) }
|
val clients = movingNow.mapNotNull { tree.client(it) }
|
||||||
@@ -374,7 +391,11 @@ fun ServerScreen(
|
|||||||
}
|
}
|
||||||
},
|
},
|
||||||
onServer = { serverSheet = true },
|
onServer = { serverSheet = true },
|
||||||
modifier = Modifier.weight(1f),
|
modifier = Modifier.weight(1f).swipeSource(when (treeSwipe) {
|
||||||
|
TreeSwipe.CHAT -> pageSwipe
|
||||||
|
TreeSwipe.SERVERS -> serverSwipe
|
||||||
|
TreeSwipe.OFF -> null
|
||||||
|
}),
|
||||||
reveal = reveal,
|
reveal = reveal,
|
||||||
onRevealed = { reveal = null },
|
onRevealed = { reveal = null },
|
||||||
found = remember(treeHits) { treeHits.mapTo(HashSet()) { TreeRef(treeFind.channels, it) } },
|
found = remember(treeHits) { treeHits.mapTo(HashSet()) { TreeRef(treeFind.channels, it) } },
|
||||||
@@ -403,12 +424,14 @@ fun ServerScreen(
|
|||||||
onSend = { server.send(conversation.key, it) },
|
onSend = { server.send(conversation.key, it) },
|
||||||
onAttach = attachments.share,
|
onAttach = attachments.share,
|
||||||
onLink = onLink,
|
onLink = onLink,
|
||||||
modifier = Modifier.weight(1f),
|
modifier = Modifier.fillMaxSize(),
|
||||||
lines = chatLines,
|
lines = chatLines,
|
||||||
find = chatQuery,
|
find = chatQuery,
|
||||||
current = chatAt,
|
current = chatAt,
|
||||||
reveal = chatReveal,
|
reveal = chatReveal,
|
||||||
onRevealed = { chatReveal = null },
|
onRevealed = { chatReveal = null },
|
||||||
|
swipeTabs = chatTabSwipe,
|
||||||
|
linesModifier = Modifier.swipeSource(if (chatBesideTree) pageSwipe else null),
|
||||||
)
|
)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -18,6 +18,7 @@ import androidx.compose.ui.Modifier
|
|||||||
import androidx.lifecycle.compose.collectAsStateWithLifecycle
|
import androidx.lifecycle.compose.collectAsStateWithLifecycle
|
||||||
import eu.lixko.ts3j.client.android.IconTheme
|
import eu.lixko.ts3j.client.android.IconTheme
|
||||||
import eu.lixko.ts3j.client.android.SessionController
|
import eu.lixko.ts3j.client.android.SessionController
|
||||||
|
import eu.lixko.ts3j.client.android.TreeSwipe
|
||||||
import kotlinx.coroutines.Dispatchers
|
import kotlinx.coroutines.Dispatchers
|
||||||
import kotlinx.coroutines.launch
|
import kotlinx.coroutines.launch
|
||||||
import kotlinx.coroutines.withContext
|
import kotlinx.coroutines.withContext
|
||||||
@@ -101,6 +102,15 @@ private fun DesignScreen(vm: SessionController, onBack: () -> Unit) {
|
|||||||
colors.mutedAway = it
|
colors.mutedAway = it
|
||||||
vm.clientRowColorsChanged()
|
vm.clientRowColorsChanged()
|
||||||
}
|
}
|
||||||
|
val treeSwipe by vm.swipe.tree.collectAsStateWithLifecycle()
|
||||||
|
Picker("Swipe sideways", listOf(
|
||||||
|
TreeSwipe.OFF to "Off",
|
||||||
|
TreeSwipe.CHAT to "Channel tree and chat",
|
||||||
|
TreeSwipe.SERVERS to "Connected servers",
|
||||||
|
), treeSwipe, vm.swipe::setTree)
|
||||||
|
Section("Chat")
|
||||||
|
val chatTabSwipe by vm.swipe.chatTabs.collectAsStateWithLifecycle()
|
||||||
|
Toggle("Swipe between chat tabs", chatTabSwipe, vm.swipe::setChatTabs)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -0,0 +1,152 @@
|
|||||||
|
package eu.lixko.ts3j.client.android.ui
|
||||||
|
|
||||||
|
import androidx.compose.animation.core.animate
|
||||||
|
import androidx.compose.foundation.gestures.awaitEachGesture
|
||||||
|
import androidx.compose.foundation.gestures.awaitFirstDown
|
||||||
|
import androidx.compose.foundation.gestures.awaitHorizontalTouchSlopOrCancellation
|
||||||
|
import androidx.compose.foundation.gestures.horizontalDrag
|
||||||
|
import androidx.compose.foundation.layout.Box
|
||||||
|
import androidx.compose.foundation.layout.fillMaxSize
|
||||||
|
import androidx.compose.runtime.Composable
|
||||||
|
import androidx.compose.runtime.LaunchedEffect
|
||||||
|
import androidx.compose.runtime.Stable
|
||||||
|
import androidx.compose.runtime.getValue
|
||||||
|
import androidx.compose.runtime.key
|
||||||
|
import androidx.compose.runtime.mutableFloatStateOf
|
||||||
|
import androidx.compose.runtime.mutableStateOf
|
||||||
|
import androidx.compose.runtime.remember
|
||||||
|
import androidx.compose.runtime.rememberCoroutineScope
|
||||||
|
import androidx.compose.runtime.rememberUpdatedState
|
||||||
|
import androidx.compose.runtime.setValue
|
||||||
|
import androidx.compose.ui.Modifier
|
||||||
|
import androidx.compose.ui.draw.clipToBounds
|
||||||
|
import androidx.compose.ui.graphics.graphicsLayer
|
||||||
|
import androidx.compose.ui.input.pointer.PointerEventPass
|
||||||
|
import androidx.compose.ui.input.pointer.PointerId
|
||||||
|
import androidx.compose.ui.input.pointer.pointerInput
|
||||||
|
import androidx.compose.ui.input.pointer.positionChange
|
||||||
|
import androidx.compose.ui.input.pointer.positionChangeIgnoreConsumed
|
||||||
|
import androidx.compose.ui.input.pointer.util.VelocityTracker
|
||||||
|
import androidx.compose.ui.input.pointer.util.addPointerInputChange
|
||||||
|
import androidx.compose.ui.unit.dp
|
||||||
|
import kotlinx.coroutines.Job
|
||||||
|
import kotlinx.coroutines.launch
|
||||||
|
import kotlin.math.abs
|
||||||
|
import kotlin.math.sign
|
||||||
|
|
||||||
|
/** How fast a short swipe must be to turn the page. */
|
||||||
|
private val FLING_VELOCITY = 600.dp
|
||||||
|
|
||||||
|
/** Where a sideways swipe between a [SwipeHost]'s pages is at. */
|
||||||
|
@Stable
|
||||||
|
class SwipeState {
|
||||||
|
/** How far the page on show has moved, in pixels; negative to the left. */
|
||||||
|
internal var shift by mutableFloatStateOf(0f)
|
||||||
|
/** Whether a swipe is under way, so the pages either side are on show too. */
|
||||||
|
internal var active by mutableStateOf(false)
|
||||||
|
/** The pointer that went down over one of the [swipeSource]s. */
|
||||||
|
internal var armed: PointerId? = null
|
||||||
|
}
|
||||||
|
|
||||||
|
@Composable
|
||||||
|
internal fun rememberSwipeState() = remember { SwipeState() }
|
||||||
|
|
||||||
|
/** Lets a swipe that starts over this element turn [state]'s pages. */
|
||||||
|
internal fun Modifier.swipeSource(state: SwipeState?): Modifier =
|
||||||
|
if (state == null) this else pointerInput(state) {
|
||||||
|
awaitEachGesture {
|
||||||
|
// Seen before the host looks at the same press.
|
||||||
|
state.armed = awaitFirstDown(requireUnconsumed = false, pass = PointerEventPass.Initial).id
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Pages side by side, [current] on show and those either side ([neighbour] gives them, -1 to the left,
|
||||||
|
* 1 to the right) following the finger. A swipe has to start over a [swipeSource] of [state];
|
||||||
|
* one that has no page to go to is left to a host further out. [onSwipe] is told of the page swiped to.
|
||||||
|
* Pages are told apart by equality, so [T] should be a key rather than a snapshot of what it shows.
|
||||||
|
*/
|
||||||
|
@Composable
|
||||||
|
internal fun <T : Any> SwipeHost(
|
||||||
|
state: SwipeState,
|
||||||
|
current: T,
|
||||||
|
neighbour: (T, Int) -> T?,
|
||||||
|
onSwipe: (T) -> Unit,
|
||||||
|
modifier: Modifier = Modifier,
|
||||||
|
page: @Composable (T) -> Unit,
|
||||||
|
) {
|
||||||
|
var shown by remember { mutableStateOf(current) }
|
||||||
|
/** A page swiped to that [current] has not caught up with yet. */
|
||||||
|
var awaited by remember { mutableStateOf<T?>(null) }
|
||||||
|
val latest by rememberUpdatedState(current)
|
||||||
|
val pageNear by rememberUpdatedState(neighbour)
|
||||||
|
val swiped by rememberUpdatedState(onSwipe)
|
||||||
|
val scope = rememberCoroutineScope()
|
||||||
|
var settling by remember { mutableStateOf<Job?>(null) }
|
||||||
|
LaunchedEffect(current) {
|
||||||
|
awaited = null
|
||||||
|
if (!state.active) shown = current
|
||||||
|
}
|
||||||
|
|
||||||
|
Box(modifier.clipToBounds().pointerInput(state) {
|
||||||
|
awaitEachGesture {
|
||||||
|
val down = awaitFirstDown(requireUnconsumed = false)
|
||||||
|
if (state.armed != down.id) return@awaitEachGesture
|
||||||
|
val start = awaitHorizontalTouchSlopOrCancellation(down.id) { change, over ->
|
||||||
|
if (pageNear(shown, direction(over)) != null) change.consume()
|
||||||
|
} ?: return@awaitEachGesture
|
||||||
|
settling?.cancel()
|
||||||
|
state.active = true
|
||||||
|
val width = size.width.toFloat()
|
||||||
|
val left = pageNear(shown, -1)
|
||||||
|
val right = pageNear(shown, 1)
|
||||||
|
val drag = { dx: Float ->
|
||||||
|
state.shift = (state.shift + dx).coerceIn(if (right != null) -width else 0f, if (left != null) width else 0f)
|
||||||
|
}
|
||||||
|
val velocity = VelocityTracker()
|
||||||
|
velocity.addPointerInputChange(start)
|
||||||
|
drag(start.positionChangeIgnoreConsumed().x)
|
||||||
|
val lifted = horizontalDrag(start.id) { change ->
|
||||||
|
drag(change.positionChange().x)
|
||||||
|
change.consume()
|
||||||
|
velocity.addPointerInputChange(change)
|
||||||
|
}
|
||||||
|
val fling = if (lifted) velocity.calculateVelocity().x else 0f
|
||||||
|
val from = state.shift
|
||||||
|
val dir = when {
|
||||||
|
abs(fling) > FLING_VELOCITY.toPx() -> direction(fling)
|
||||||
|
abs(from) > width / 3 -> direction(from)
|
||||||
|
else -> 0
|
||||||
|
}
|
||||||
|
// A fling back against the swipe turns no page.
|
||||||
|
val target = if (dir != 0 && dir == direction(from)) pageNear(shown, dir) else null
|
||||||
|
settling = scope.launch {
|
||||||
|
animate(from, if (target != null) -dir * width else 0f, fling) { value, _ -> state.shift = value }
|
||||||
|
if (target != null) {
|
||||||
|
shown = target
|
||||||
|
awaited = target
|
||||||
|
swiped(target)
|
||||||
|
} else if (awaited == null) {
|
||||||
|
shown = latest
|
||||||
|
}
|
||||||
|
state.shift = 0f
|
||||||
|
state.active = false
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}) {
|
||||||
|
val at = shown
|
||||||
|
val pages = if (!state.active) listOf(at to 0)
|
||||||
|
else listOfNotNull(neighbour(at, -1)?.to(-1), at to 0, neighbour(at, 1)?.to(1))
|
||||||
|
for ((item, slot) in pages) {
|
||||||
|
// Keyed, so the page swiped to keeps its state when it becomes the one on show.
|
||||||
|
key(item) {
|
||||||
|
Box(Modifier.fillMaxSize().graphicsLayer { translationX = state.shift + slot * size.width }) {
|
||||||
|
page(item)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/** A drag or fling to the left heads for what lies to the right. */
|
||||||
|
private fun direction(dx: Float): Int = -sign(dx).toInt()
|
||||||
Reference in New Issue
Block a user