Compare commits

2 Commits
8 changed files with 205 additions and 177 deletions
-1
View File
@@ -67,7 +67,6 @@ android {
dependencies {
implementation(platform(libs.androidx.compose.bom))
implementation(libs.reorderable)
implementation(libs.androidx.activity.compose)
implementation(libs.androidx.compose.material3)
implementation("androidx.compose.material:material-icons-extended")
@@ -86,15 +86,6 @@ fun AboutScreen(
Spacer(modifier = Modifier.height(48.dp))
ListItem(
headlineContent = { Text(stringResource(R.string.author_homepage)) },
supportingContent = { Text(stringResource(R.string.author_handle)) },
modifier = Modifier.clickable {
val intent = Intent(Intent.ACTION_VIEW, Uri.parse("https://airnan.cn"))
context.startActivity(intent)
}
)
ListItem(
headlineContent = { Text(stringResource(R.string.source_code)) },
supportingContent = { Text(stringResource(R.string.view_on_gitea)) },
@@ -106,7 +97,6 @@ fun AboutScreen(
ListItem(
headlineContent = { Text(stringResource(R.string.open_source_licenses)) },
supportingContent = { Text(stringResource(R.string.licenses_desc)) },
modifier = Modifier.clickable { onNavigateToLicenses() }
)
@@ -1,4 +1,5 @@
package cn.airnan.a2fair.ui.settings
import androidx.compose.foundation.clickable
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.WindowInsets
@@ -6,15 +6,14 @@ import android.content.Context
import android.widget.Toast
import androidx.compose.animation.AnimatedVisibility
import androidx.compose.foundation.ExperimentalFoundationApi
import androidx.compose.foundation.LocalIndication
import androidx.compose.foundation.background
import androidx.compose.foundation.clickable
import androidx.compose.foundation.combinedClickable
import androidx.compose.foundation.interaction.MutableInteractionSource
import androidx.compose.foundation.gestures.awaitEachGesture
import androidx.compose.foundation.gestures.awaitFirstDown
import androidx.compose.foundation.layout.*
import androidx.compose.foundation.lazy.LazyColumn
import androidx.compose.foundation.lazy.items
import androidx.compose.foundation.lazy.rememberLazyListState
import androidx.compose.foundation.shape.CircleShape
import androidx.compose.material.icons.Icons
import androidx.compose.material.icons.filled.Add
@@ -33,19 +32,23 @@ import androidx.compose.runtime.*
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.draw.clip
import androidx.compose.ui.draw.shadow
import androidx.compose.ui.focus.FocusRequester
import androidx.compose.ui.focus.focusRequester
import androidx.compose.ui.focus.onFocusChanged
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.graphics.Shape
import androidx.compose.ui.graphics.drawscope.Stroke
import androidx.compose.ui.graphics.graphicsLayer
import androidx.compose.ui.graphics.vector.ImageVector
import androidx.compose.ui.hapticfeedback.HapticFeedbackType
import androidx.compose.ui.input.nestedscroll.nestedScroll
import androidx.compose.ui.input.pointer.pointerInput
import androidx.compose.ui.input.pointer.positionChange
import androidx.compose.ui.input.pointer.changedToUp
import androidx.compose.ui.layout.onSizeChanged
import androidx.compose.ui.platform.LocalDensity
import androidx.compose.ui.platform.LocalFocusManager
import androidx.compose.ui.platform.LocalContext
import androidx.compose.ui.platform.LocalHapticFeedback
import androidx.compose.ui.zIndex
import androidx.compose.ui.res.stringResource
import androidx.compose.ui.text.font.FontWeight
import androidx.compose.ui.text.style.TextAlign
@@ -59,9 +62,6 @@ import cn.airnan.a2fair.data.entity.Token
import cn.airnan.a2fair.data.entity.TokenType
import kotlin.math.abs
import kotlinx.coroutines.delay
import sh.calvin.reorderable.ReorderableColumn
import sh.calvin.reorderable.ReorderableItem
import sh.calvin.reorderable.rememberReorderableLazyListState
@OptIn(ExperimentalMaterial3Api::class, ExperimentalMaterial3ExpressiveApi::class)
@Composable
@@ -77,10 +77,12 @@ fun TokensScreen(
val focusManager = LocalFocusManager.current
val scrollBehavior = TopAppBarDefaults.exitUntilCollapsedScrollBehavior()
// Group drag-reorder state: pending local order while dragging, persisted on release
val hapticFeedback = LocalHapticFeedback.current
var pendingGroupOrder by remember { mutableStateOf<List<Group?>?>(null) }
val lazyListState = rememberLazyListState()
// Group & token drag-reorder state
var draggedGroupKey by remember { mutableStateOf<Long?>(null) } // real id; -1 = Uncategorized
var dragGroupTranslateY by remember { mutableFloatStateOf(0f) }
var draggedTokenId by remember { mutableStateOf<Long?>(null) }
var dragTokenTranslateY by remember { mutableFloatStateOf(0f) }
val cardHeights = remember { mutableMapOf<String, Int>() }
var renameTarget by remember { mutableStateOf<Group?>(null) }
var deleteTarget by remember { mutableStateOf<Group?>(null) }
@@ -137,7 +139,12 @@ fun TokensScreen(
)
} else {
MediumFlexibleTopAppBar(
title = { Text(stringResource(R.string.app_name)) },
title = { Text(stringResource(R.string.tokens)) },
actions = {
IconButton(onClick = { isSearchExpanded = true }) {
Icon(Icons.Default.Search, contentDescription = stringResource(R.string.search))
}
},
scrollBehavior = scrollBehavior
)
}
@@ -153,33 +160,6 @@ fun TokensScreen(
.fillMaxSize()
.padding(padding)
) {
if (!isSearchExpanded) {
Surface(
shape = MaterialTheme.shapes.extraLarge,
color = MaterialTheme.colorScheme.surfaceContainerHigh,
modifier = Modifier
.fillMaxWidth()
.padding(horizontal = 16.dp, vertical = 4.dp)
.clickable { isSearchExpanded = true }
) {
Row(
modifier = Modifier.padding(horizontal = 16.dp, vertical = 14.dp),
verticalAlignment = Alignment.CenterVertically
) {
Icon(
imageVector = Icons.Default.Search,
contentDescription = null,
tint = MaterialTheme.colorScheme.onSurfaceVariant
)
Spacer(modifier = Modifier.width(12.dp))
Text(
text = stringResource(R.string.search_tokens),
style = MaterialTheme.typography.bodyLarge,
color = MaterialTheme.colorScheme.onSurfaceVariant
)
}
}
}
val latestUiState by rememberUpdatedState(uiState)
if (uiState.groupedTokens.isEmpty()) {
if (uiState.searchQuery.isBlank()) {
@@ -200,41 +180,26 @@ fun TokensScreen(
}
} else {
// Token List
val displayGroups =
(pendingGroupOrder ?: latestUiState.groupedTokens.keys.toList())
.mapNotNull { key -> latestUiState.groupedTokens[key]?.let { key to it } }
val reorderableLazyListState =
rememberReorderableLazyListState(lazyListState) { from, to ->
val keys = pendingGroupOrder ?: latestUiState.groupedTokens.keys.toList()
val fromIndex = keys.indexOfFirst { groupItemKey(it) == from.key }
val toIndex = keys.indexOfFirst { groupItemKey(it) == to.key }
if (fromIndex in keys.indices && toIndex in keys.indices) {
pendingGroupOrder =
keys.toMutableList().apply { add(toIndex, removeAt(fromIndex)) }
hapticFeedback.performHapticFeedback(HapticFeedbackType.SegmentFrequentTick)
}
}
LazyColumn(
state = lazyListState,
modifier = Modifier.fillMaxSize(),
contentPadding = PaddingValues(bottom = 80.dp),
contentPadding = PaddingValues(bottom = 80.dp)
) {
items(displayGroups, key = { groupItemKey(it.first) }) { (group, tokens) ->
uiState.groupedTokens.forEach { (group, tokens) ->
val groupId = group?.id
val groupKey = groupId ?: -1L
val isCollapsed = uiState.collapsedGroups.contains(groupId ?: -1L)
ReorderableItem(reorderableLazyListState, groupItemKey(group)) { groupDragging ->
val groupDragScope = this
val groupInteractionSource = remember { MutableInteractionSource() }
item(key = "group_${groupId ?: "unassigned"}") {
Card(
modifier = Modifier
.fillMaxWidth()
.padding(horizontal = 16.dp, vertical = 6.dp),
elevation = CardDefaults.cardElevation(
defaultElevation = if (groupDragging) 6.dp else 0.dp
)
.padding(horizontal = 16.dp, vertical = 6.dp)
.zIndex(if (draggedGroupKey == groupKey) 1f else 0f)
.graphicsLayer {
if (draggedGroupKey == groupKey) translationY = dragGroupTranslateY
}
.onSizeChanged { cardHeights["g:$groupKey"] = it.height },
elevation = CardDefaults.cardElevation(defaultElevation = 0.dp)
) {
Column {
GroupHeader(
@@ -243,49 +208,112 @@ fun TokensScreen(
onToggle = { viewModel.toggleGroupCollapse(groupId) },
onRename = { group?.let { renameTarget = it } },
onDelete = { group?.let { deleteTarget = it } },
dragModifier = with(groupDragScope) {
Modifier.draggableHandle(
interactionSource = groupInteractionSource,
onDragStarted = {
hapticFeedback.performHapticFeedback(HapticFeedbackType.GestureThresholdActivate)
},
onDragStopped = {
pendingGroupOrder?.let { viewModel.applyGroupOrder(it) }
pendingGroupOrder = null
dragModifier = Modifier.dragHandle(
key = groupKey,
onDragStart = {
draggedGroupKey = groupKey
dragGroupTranslateY = 0f
},
onDragDelta = { dy ->
dragGroupTranslateY += dy
// Swap with neighbour once dragged past its height
val keys = latestUiState.groupedTokens.keys.toList()
val index = keys.indexOfFirst { (it?.id ?: -1L) == groupKey }
if (index >= 0) {
if (dragGroupTranslateY > 0f && index < keys.lastIndex) {
val next = keys[index + 1]
val nextKey = next?.id ?: -1L
val nextHeight = cardHeights["g:$nextKey"] ?: 0
if (nextHeight > 0 && dragGroupTranslateY >= nextHeight) {
dragGroupTranslateY -= nextHeight
val newKeys = keys.toMutableList()
newKeys[index] = next
newKeys[index + 1] = group
viewModel.applyGroupOrder(newKeys)
}
} else if (dragGroupTranslateY < 0f && index > 0) {
val prev = keys[index - 1]
val prevKey = prev?.id ?: -1L
val prevHeight = cardHeights["g:$prevKey"] ?: 0
if (prevHeight > 0 && -dragGroupTranslateY >= prevHeight) {
dragGroupTranslateY += prevHeight
val newKeys = keys.toMutableList()
newKeys[index] = prev
newKeys[index - 1] = group
viewModel.applyGroupOrder(newKeys)
}
}
}
)
},
interactionSource = groupInteractionSource
},
onDragEnd = {
draggedGroupKey = null
dragGroupTranslateY = 0f
}
)
)
if (!isCollapsed) {
ReorderableColumn(
list = tokens,
onMove = {
hapticFeedback.performHapticFeedback(HapticFeedbackType.SegmentFrequentTick)
},
onSettle = { from, to ->
val newOrder = tokens.toMutableList().apply { add(to, removeAt(from)) }
viewModel.applyTokenOrder(newOrder)
},
) { index, token, tokenDragging ->
key(token.id) {
ReorderableItem {
val tokenDragScope = this
val rowInteractionSource = remember { MutableInteractionSource() }
TokenCard(
token = token,
onIncrement = { viewModel.incrementCounter(token) },
onEdit = { onNavigateToTokenEdit(token.id) },
isDragging = tokenDragging,
interactionSource = rowInteractionSource,
dragModifier = with(tokenDragScope) {
Modifier.draggableHandle(
interactionSource = rowInteractionSource
)
tokens.forEachIndexed { index, token ->
Box(
modifier = Modifier
.zIndex(if (draggedTokenId == token.id) 1f else 0f)
.graphicsLayer {
if (draggedTokenId == token.id) translationY = dragTokenTranslateY
}
.onSizeChanged { cardHeights["t:${token.id}"] = it.height }
) {
TokenCard(
token = token,
onIncrement = { viewModel.incrementCounter(token) },
onEdit = { onNavigateToTokenEdit(token.id) },
dragModifier = Modifier.dragHandle(
key = token.id,
onDragStart = {
draggedTokenId = token.id
dragTokenTranslateY = 0f
},
onDragDelta = { dy ->
dragTokenTranslateY += dy
// Reorder within the same group only
val groupTokens = latestUiState.groupedTokens[group]
if (groupTokens != null) {
val idx = groupTokens.indexOfFirst { it.id == token.id }
if (idx >= 0) {
if (idx < groupTokens.lastIndex && dragTokenTranslateY > 0f) {
val next = groupTokens[idx + 1]
val nextHeight = cardHeights["t:${next.id}"] ?: 0
if (nextHeight > 0 && dragTokenTranslateY >= nextHeight) {
dragTokenTranslateY -= nextHeight
val newOrder = groupTokens.toMutableList()
newOrder[idx] = next
newOrder[idx + 1] = token
viewModel.applyTokenOrder(newOrder)
}
} else if (idx > 0 && dragTokenTranslateY < 0f) {
val prev = groupTokens[idx - 1]
val prevHeight = cardHeights["t:${prev.id}"] ?: 0
if (prevHeight > 0 && -dragTokenTranslateY >= prevHeight) {
dragTokenTranslateY += prevHeight
val newOrder = groupTokens.toMutableList()
newOrder[idx] = prev
newOrder[idx - 1] = token
viewModel.applyTokenOrder(newOrder)
}
}
}
}
},
onDragEnd = {
draggedTokenId = null
dragTokenTranslateY = 0f
}
)
}
)
}
if (index < tokens.lastIndex) {
HorizontalDivider(modifier = Modifier.padding(horizontal = 16.dp))
}
}
}
@@ -364,6 +392,35 @@ fun TokensScreen(
}
}
/**
* Drag handle: consumes the down event immediately so ancestor click/long-press
* (copy, detail drawer, collapse) never fires; drag deltas reported as cumulative dy.
*/
private fun Modifier.dragHandle(
key: Any?,
onDragStart: () -> Unit,
onDragDelta: (Float) -> Unit,
onDragEnd: () -> Unit
): Modifier = pointerInput(key) {
awaitEachGesture {
val down = awaitFirstDown(requireUnconsumed = false)
down.consume()
onDragStart()
try {
while (true) {
val event = awaitPointerEvent()
val change = event.changes.firstOrNull() ?: break
if (change.changedToUp()) break
val dy = change.positionChange().y
change.consume()
onDragDelta(dy)
}
} finally {
onDragEnd()
}
}
}
@OptIn(ExperimentalMaterial3ExpressiveApi::class)
@Composable
private fun EmptyState(
@@ -426,60 +483,59 @@ fun GroupHeader(
onToggle: () -> Unit,
onRename: () -> Unit = {},
onDelete: () -> Unit = {},
dragModifier: Modifier = Modifier,
interactionSource: MutableInteractionSource? = null
dragModifier: Modifier = Modifier
) {
var menuExpanded by remember { mutableStateOf(false) }
Row(
modifier = Modifier
.fillMaxWidth()
.combinedClickable(
interactionSource = interactionSource,
indication = LocalIndication.current,
onClick = onToggle
)
.combinedClickable(onClick = onToggle)
.padding(horizontal = 16.dp, vertical = 12.dp),
verticalAlignment = Alignment.CenterVertically
) {
Icon(
imageVector = Icons.Default.DragIndicator,
contentDescription = stringResource(R.string.drag_handle_desc),
tint = MaterialTheme.colorScheme.onSurfaceVariant,
modifier = dragModifier
)
Spacer(modifier = Modifier.width(10.dp))
if (group != null) {
Icon(
imageVector = Icons.Default.DragIndicator,
contentDescription = stringResource(R.string.drag_handle_desc),
tint = MaterialTheme.colorScheme.onSurfaceVariant,
modifier = dragModifier
)
Spacer(modifier = Modifier.width(10.dp))
}
Text(
text = group?.name ?: stringResource(R.string.uncategorized),
style = MaterialTheme.typography.titleMedium.copy(fontWeight = FontWeight.Bold),
style = MaterialTheme.typography.titleMedium,
fontWeight = FontWeight.Bold,
color = MaterialTheme.colorScheme.primary,
modifier = Modifier.weight(1f)
)
Spacer(modifier = Modifier.width(4.dp))
Box {
IconButton(onClick = { menuExpanded = true }) {
Icon(
imageVector = Icons.Default.MoreVert,
contentDescription = stringResource(R.string.rename)
)
}
DropdownMenu(
expanded = menuExpanded,
onDismissRequest = { menuExpanded = false }
) {
DropdownMenuItem(
text = { Text(stringResource(R.string.rename)) },
onClick = {
menuExpanded = false
onRename()
}
)
DropdownMenuItem(
text = { Text(stringResource(R.string.delete)) },
onClick = {
menuExpanded = false
onDelete()
}
)
}
IconButton(onClick = { menuExpanded = true }) {
Icon(
imageVector = Icons.Default.MoreVert,
contentDescription = stringResource(R.string.rename)
)
}
DropdownMenu(
expanded = menuExpanded,
onDismissRequest = { menuExpanded = false }
) {
DropdownMenuItem(
text = { Text(stringResource(R.string.rename)) },
onClick = {
menuExpanded = false
onRename()
}
)
DropdownMenuItem(
text = { Text(stringResource(R.string.delete)) },
onClick = {
menuExpanded = false
onDelete()
}
)
}
}
Icon(
imageVector = if (isCollapsed) Icons.Default.ExpandMore else Icons.Default.ExpandLess,
@@ -494,9 +550,7 @@ fun TokenCard(
token: Token,
onIncrement: () -> Unit,
onEdit: () -> Unit,
dragModifier: Modifier = Modifier,
isDragging: Boolean = false,
interactionSource: MutableInteractionSource? = null
dragModifier: Modifier = Modifier
) {
val warningColor = Color(0xFFFF1744)
val otpPlaceholder = stringResource(R.string.otp_placeholder)
@@ -580,15 +634,7 @@ fun TokenCard(
Row(
modifier = Modifier
.fillMaxWidth()
.then(
if (isDragging) Modifier
.shadow(elevation = 8.dp)
.background(MaterialTheme.colorScheme.surface)
else Modifier
)
.combinedClickable(
interactionSource = interactionSource,
indication = LocalIndication.current,
onClick = {
copyToClipboard(context, currentCode, token.serviceName)
},
@@ -656,11 +702,14 @@ fun TokenCard(
modifier = Modifier.size(44.dp),
contentAlignment = Alignment.Center
) {
val ringStroke = Stroke(width = with(LocalDensity.current) { 3.dp.toPx() })
CircularWavyProgressIndicator(
progress = { progress },
modifier = Modifier.size(44.dp),
color = if (showNextPreview) warningColor else MaterialTheme.colorScheme.primary,
trackColor = MaterialTheme.colorScheme.outlineVariant,
stroke = ringStroke,
trackStroke = ringStroke,
)
Text(
text = "$remainingSeconds",
@@ -733,5 +782,3 @@ private fun copyToClipboard(context: Context, code: String, label: String) {
clipboard.setPrimaryClip(clip)
Toast.makeText(context, context.getString(R.string.code_copied, label), Toast.LENGTH_SHORT).show()
}
private fun groupItemKey(group: Group?): String = "group_${group?.id ?: "unassigned"}"
@@ -82,8 +82,6 @@
<string name="backup_restore">备份与恢复</string>
<string name="theme">主题</string>
<string name="about">关于</string>
<string name="author_homepage">作者主页</string>
<string name="author_handle">@码农阿楠</string>
<!-- Security Settings -->
<string name="app_lock_pin">应用锁 PIN 码</string>
-2
View File
@@ -82,8 +82,6 @@
<string name="backup_restore">Backup &amp; Restore</string>
<string name="theme">Theme</string>
<string name="about">About</string>
<string name="author_homepage">Author homepage</string>
<string name="author_handle">@Airnan</string>
<!-- Security Settings -->
<string name="app_lock_pin">App Lock PIN</string>
-2
View File
@@ -1,6 +1,5 @@
[versions]
agp = "9.2.1"
reorderable = "3.1.0"
coreKtx = "1.15.0"
junit = "4.13.2"
junitVersion = "1.3.0"
@@ -37,7 +36,6 @@ androidx-compose-ui-tooling-preview = { group = "androidx.compose.ui", name = "u
androidx-compose-ui-test-manifest = { group = "androidx.compose.ui", name = "ui-test-manifest" }
androidx-compose-ui-test-junit4 = { group = "androidx.compose.ui", name = "ui-test-junit4" }
androidx-compose-material3 = { group = "androidx.compose.material3", name = "material3", version = "1.5.0-beta01" }
reorderable = { module = "sh.calvin.reorderable:reorderable", version.ref = "reorderable" }
androidx-navigation-compose = { group = "androidx.navigation", name = "navigation-compose", version.ref = "navigationCompose" }
androidx-room-runtime = { group = "androidx.room", name = "room-runtime", version.ref = "room" }
androidx-room-ktx = { group = "androidx.room", name = "room-ktx", version.ref = "room" }
-3
View File
@@ -1,3 +0,0 @@
[tools]
cmake = "3.22.1"
ninja = "1.13.2"