feat(android): 增加分级位置浏览和就地录入
continuous-integration/drone/push Build is passing Details

This commit is contained in:
dongjf 2026-11-29 17:32:35 +08:00
parent 247278a4a9
commit f67f683373
6 changed files with 374 additions and 125 deletions

View File

@ -4,6 +4,8 @@ Android 8.0(API 26)及以上。使用 Kotlin、Jetpack Compose 和见物原
详情展示购入单价和移位记录。可以编辑名称、数量、别名和备注,存放位置由移位操作管理。编辑过程中若其他端先更新了同一物品,服务端会根据物品版本返回 409。用户确认载入最新内容后,可以基于新版本重新修改。 详情展示购入单价和移位记录。可以编辑名称、数量、别名和备注,存放位置由移位操作管理。编辑过程中若其他端先更新了同一物品,服务端会根据物品版本返回 409。用户确认载入最新内容后,可以基于新版本重新修改。
「找物」用于全空间搜索。「位置」从房间和区域逐层打开,按服务端保存的同级顺序显示。可在某个位置查看直接存放的物品,也可切换到「含下级」。从该位置点「在此添加」,表单会预选当前路径,仍可改选或清空。拥有写权限的成员可以新建房间和子位置。
会话令牌只在应用进程内使用,续期由 API 客户端处理。应用被完全关闭后需要重新登录。应用不预置物品、账号或凭据。 会话令牌只在应用进程内使用,续期由 API 客户端处理。应用被完全关闭后需要重新登录。应用不预置物品、账号或凭据。
## 构建和安装 ## 构建和安装
@ -20,6 +22,6 @@ adb install -r app/build/outputs/apk/debug/app-debug.apk
## 验收 ## 验收
登录后切换空间,输入名称或别名并打开详情。分别尝试在有位置和无位置时录入,再移动到另一个位置或清空位置,核对详情中的移位记录。两端同时打开同一件物品,用一端保存后再在另一端提交,检查冲突提示及重新载入。用只读成员检查物品写入口,用网络中断检查失败提示,退出后确认页面清空。拍照、语音、社区及平面图随后接入。 登录后切换空间,输入名称或别名并打开详情。分别尝试在有位置和无位置时录入,再移动到另一个位置或清空位置,核对详情中的移位记录。建三层位置,验证「仅此位置」「含下级」和从位置详情预选录入。两端同时打开同一件物品,用一端保存后再在另一端提交,检查冲突提示及重新载入。用只读成员检查物品写入口,用网络中断检查失败提示,退出后确认页面清空。拍照、语音、社区及平面图随后接入。
[客户端架构](../../docs/architecture/clients.md) · [Android 构建](https://developer.android.com/build/building-cmdline) [客户端架构](../../docs/architecture/clients.md) · [Android 构建](https://developer.android.com/build/building-cmdline)

View File

@ -15,8 +15,8 @@ android {
applicationId = "com.tutudog.itematlas" applicationId = "com.tutudog.itematlas"
minSdk = 26 minSdk = 26
targetSdk = 35 targetSdk = 35
versionCode = 2 versionCode = 3
versionName = "0.1.1" versionName = "0.1.2"
val apiOrigin = providers.gradleProperty("ATLAS_API_ORIGIN").orElse("https://api-atlas.tutudog.com").get() val apiOrigin = providers.gradleProperty("ATLAS_API_ORIGIN").orElse("https://api-atlas.tutudog.com").get()
require(Regex("https://[A-Za-z0-9.-]+(:[0-9]+)?").matches(apiOrigin)) { "ATLAS_API_ORIGIN must be an HTTPS origin" } require(Regex("https://[A-Za-z0-9.-]+(:[0-9]+)?").matches(apiOrigin)) { "ATLAS_API_ORIGIN must be an HTTPS origin" }

View File

@ -23,7 +23,13 @@ data class Space(val id: String, val name: String, val role: String) {
} }
@Serializable @Serializable
data class Place(val id: String, val name: String, val path: String, val parentId: String? = null) data class Place(
val id: String,
val name: String,
val path: String,
val parentId: String? = null,
val sortRank: Int? = null,
)
@Serializable @Serializable
data class Item( data class Item(
@ -68,6 +74,9 @@ class AtlasApi(origin: String = BuildConfig.ATLAS_API_ORIGIN) {
@Serializable @Serializable
private data class SpaceInput(val name: String) private data class SpaceInput(val name: String)
@Serializable
private data class PlaceInput(val name: String, val parentId: String?)
@Serializable @Serializable
private data class MoveInput(val locationId: String?, val version: Int) private data class MoveInput(val locationId: String?, val version: Int)
@ -113,13 +122,21 @@ class AtlasApi(origin: String = BuildConfig.ATLAS_API_ORIGIN) {
suspend fun locations(space: Space): List<Place> = json.decodeFromString(read(family(space, "locations"))) suspend fun locations(space: Space): List<Place> = json.decodeFromString(read(family(space, "locations")))
suspend fun search(space: Space, query: String, offset: Int = 0): List<Item> { suspend fun createLocation(space: Space, name: String, parentId: String?): Place =
val url = family(space, "items").newBuilder() json.decodeFromString(read(family(space, "locations"), "POST", json.encodeToString(PlaceInput(name, parentId))))
suspend fun search(
space: Space, query: String, offset: Int = 0, locationId: String? = null, includeDescendants: Boolean = false,
): List<Item> {
val builder = family(space, "items").newBuilder()
.addQueryParameter("q", query.trim()) .addQueryParameter("q", query.trim())
.addQueryParameter("limit", "30") .addQueryParameter("limit", "30")
.addQueryParameter("offset", offset.toString()) .addQueryParameter("offset", offset.toString())
.build() if (locationId != null) {
return json.decodeFromString(read(url)) builder.addQueryParameter("location", locationId)
if (includeDescendants) builder.addQueryParameter("includeDescendants", "true")
}
return json.decodeFromString(read(builder.build()))
} }
suspend fun detail(space: Space, id: String): ItemDetail = json.decodeFromString(read(family(space, "items", id))) suspend fun detail(space: Space, id: String): ItemDetail = json.decodeFromString(read(family(space, "items", id)))

View File

@ -13,12 +13,19 @@ import kotlinx.coroutines.flow.update
import kotlinx.coroutines.launch import kotlinx.coroutines.launch
enum class Screen { SignIn, Inventory, Detail, Add, Edit, Move } enum class Screen { SignIn, Inventory, Detail, Add, Edit, Move }
enum class InventoryTab { Find, Locations }
data class AtlasState( data class AtlasState(
val screen: Screen = Screen.SignIn, val screen: Screen = Screen.SignIn,
val tab: InventoryTab = InventoryTab.Find,
val spaces: List<Space> = emptyList(), val spaces: List<Space> = emptyList(),
val space: Space? = null, val space: Space? = null,
val places: List<Place> = emptyList(), val places: List<Place> = emptyList(),
val locationId: String? = null,
val includeDescendants: Boolean = false,
val loadingPlaces: Boolean = false,
val placesError: String? = null,
val creatingLocation: Boolean = false,
val items: List<Item> = emptyList(), val items: List<Item> = emptyList(),
val selected: Item? = null, val selected: Item? = null,
val recentMoves: List<Movement>? = null, val recentMoves: List<Movement>? = null,
@ -75,29 +82,84 @@ class AtlasViewModel : ViewModel() {
detailJob?.cancel() detailJob?.cancel()
mutable.update { mutable.update {
it.copy(space = space, places = emptyList(), items = emptyList(), selected = null, it.copy(space = space, places = emptyList(), items = emptyList(), selected = null,
locationId = null, includeDescendants = false, placesError = null, loadingPlaces = false,
loading = false, creatingLocation = false,
query = "", hasMore = false, nextOffset = 0, recentMoves = null, writeConflict = false, query = "", hasMore = false, nextOffset = 0, recentMoves = null, writeConflict = false,
error = null, screen = Screen.Inventory) error = null, screen = Screen.Inventory)
} }
search() search()
locations() refreshLocations()
} }
private fun locations() { fun refreshLocations() {
val space = mutable.value.space ?: return val space = mutable.value.space ?: return
placesJob?.cancel() placesJob?.cancel()
mutable.update { it.copy(loadingPlaces = true, placesError = null) }
placesJob = viewModelScope.launch { placesJob = viewModelScope.launch {
try { try {
val places = api.locations(space) val places = api.locations(space)
if (mutable.value.space?.id == space.id) mutable.update { it.copy(places = places) } val current = mutable.value
if (current.space?.id != space.id) return@launch
mutable.update { it.copy(places = places, loadingPlaces = false) }
if (current.locationId != null && places.none { it.id == current.locationId }) {
openLocation(null)
}
} catch (failure: Exception) { } catch (failure: Exception) {
if (failure is CancellationException) throw failure if (failure is CancellationException) throw failure
if (mutable.value.screen == Screen.Add || mutable.value.screen == Screen.Move) { if (failure is ApiError && failure.status == 401) {
handle(failure) handle(failure)
} else {
mutable.update { it.copy(loadingPlaces = false, placesError = errorMessage(failure)) }
} }
} }
} }
} }
fun switchTab(tab: InventoryTab) {
if (mutable.value.tab == tab) return
mutable.update { it.copy(tab = tab) }
refreshItemScope()
}
fun openLocation(id: String?) {
if (id != null && mutable.value.places.none { it.id == id }) return
mutable.update { it.copy(locationId = id, includeDescendants = false) }
if (mutable.value.tab == InventoryTab.Locations) refreshItemScope()
}
fun includeDescendants(include: Boolean) {
if (mutable.value.locationId == null || mutable.value.includeDescendants == include) return
mutable.update { it.copy(includeDescendants = include) }
refreshItemScope()
}
private fun refreshItemScope() {
listJob?.cancel()
mutable.update { it.copy(items = emptyList(), nextOffset = 0, hasMore = false, loading = false, error = null) }
if (mutable.value.screen == Screen.Inventory) search()
}
fun showLocationCreator(show: Boolean) {
if (mutable.value.busy || mutable.value.space?.writable != true) return
mutable.update { it.copy(creatingLocation = show, error = null) }
}
fun createLocation(name: String) {
val current = mutable.value
val space = current.space?.takeIf { it.writable } ?: return
val label = name.trim()
if (label.length !in 1..100) return
action {
placesJob?.cancel()
try {
val place = api.createLocation(space, label, current.locationId)
mutable.update { it.copy(places = (it.places + place).distinctBy(Place::id), creatingLocation = false) }
} finally {
refreshLocations()
}
}
}
fun setQuery(query: String) { fun setQuery(query: String) {
if (query == mutable.value.query) return if (query == mutable.value.query) return
mutable.update { it.copy(query = query.take(150), items = emptyList(), nextOffset = 0, hasMore = false) } mutable.update { it.copy(query = query.take(150), items = emptyList(), nextOffset = 0, hasMore = false) }
@ -107,6 +169,8 @@ class AtlasViewModel : ViewModel() {
fun search(append: Boolean = false, debounce: Boolean = false) { fun search(append: Boolean = false, debounce: Boolean = false) {
val prior = mutable.value val prior = mutable.value
val space = prior.space ?: return val space = prior.space ?: return
val location = prior.locationId.takeIf { prior.tab == InventoryTab.Locations }
if (prior.tab == InventoryTab.Locations && location == null) return
if (append && (prior.loading || !prior.hasMore)) return if (append && (prior.loading || !prior.hasMore)) return
listJob?.cancel() listJob?.cancel()
mutable.update { it.copy(loading = true, error = null) } mutable.update { it.copy(loading = true, error = null) }
@ -114,9 +178,12 @@ class AtlasViewModel : ViewModel() {
try { try {
if (debounce) delay(200) if (debounce) delay(200)
val offset = if (append) prior.nextOffset else 0 val offset = if (append) prior.nextOffset else 0
val found = api.search(space, prior.query, offset) val query = if (location == null) prior.query else ""
val found = api.search(space, query, offset, location, prior.includeDescendants)
mutable.update { mutable.update {
if (it.space?.id != space.id || it.query != prior.query) it val changedLocation = location != null &&
(it.locationId != location || it.includeDescendants != prior.includeDescendants)
if (it.space?.id != space.id || it.query != prior.query || it.tab != prior.tab || changedLocation) it
else { else {
val merged = if (append) (it.items + found).distinctBy(Item::id) else found val merged = if (append) (it.items + found).distinctBy(Item::id) else found
val next = offset + found.size val next = offset + found.size
@ -134,9 +201,11 @@ class AtlasViewModel : ViewModel() {
fun open(item: Item) { fun open(item: Item) {
val space = mutable.value.space ?: return val space = mutable.value.space ?: return
listJob?.cancel()
detailJob?.cancel() detailJob?.cancel()
mutable.update { mutable.update {
it.copy(screen = Screen.Detail, selected = item, recentMoves = null, writeConflict = false, error = null) it.copy(screen = Screen.Detail, selected = item, recentMoves = null, writeConflict = false,
loading = false, error = null)
} }
detailJob = viewModelScope.launch { detailJob = viewModelScope.launch {
try { try {
@ -159,7 +228,7 @@ class AtlasViewModel : ViewModel() {
pendingItem = null pendingItem = null
pendingKey = "" pendingKey = ""
mutable.update { it.copy(screen = Screen.Add, error = null) } mutable.update { it.copy(screen = Screen.Add, error = null) }
locations() refreshLocations()
} }
fun create(name: String, quantity: String, location: Place?, aliases: String, notes: String) { fun create(name: String, quantity: String, location: Place?, aliases: String, notes: String) {
@ -236,7 +305,7 @@ class AtlasViewModel : ViewModel() {
if (mutable.value.space?.writable != true || mutable.value.selected == null) return if (mutable.value.space?.writable != true || mutable.value.selected == null) return
detailJob?.cancel() detailJob?.cancel()
mutable.update { it.copy(screen = Screen.Move, writeConflict = false, error = null) } mutable.update { it.copy(screen = Screen.Move, writeConflict = false, error = null) }
locations() refreshLocations()
} }
fun move(position: Place?) { fun move(position: Place?) {
@ -250,6 +319,11 @@ class AtlasViewModel : ViewModel() {
if (mutable.value.busy) return if (mutable.value.busy) return
detailJob?.cancel() detailJob?.cancel()
val from = mutable.value.screen val from = mutable.value.screen
if (from == Screen.Inventory && mutable.value.tab == InventoryTab.Locations) {
val current = mutable.value
openLocation(current.places.firstOrNull { it.id == current.locationId }?.parentId)
return
}
if (from == Screen.Edit || from == Screen.Move) { if (from == Screen.Edit || from == Screen.Move) {
mutable.value.selected?.let(::open) mutable.value.selected?.let(::open)
return return
@ -295,12 +369,13 @@ class AtlasViewModel : ViewModel() {
detailJob?.cancel() detailJob?.cancel()
mutable.value = AtlasState(error = "登录已过期,请重新登录。") mutable.value = AtlasState(error = "登录已过期,请重新登录。")
} else { } else {
val detail = when (failure) { mutable.update { it.copy(error = errorMessage(failure)) }
}
}
private fun errorMessage(failure: Exception): String = when (failure) {
is IOException -> "连接服务失败,请检查网络。" is IOException -> "连接服务失败,请检查网络。"
is ApiError -> failure.message ?: "请求失败,请重试。" is ApiError -> failure.message ?: "请求失败,请重试。"
else -> "无法读取服务返回的数据,请重试。" else -> "无法读取服务返回的数据,请重试。"
} }
mutable.update { it.copy(error = detail) }
}
}
} }

View File

@ -0,0 +1,245 @@
package com.tutudog.itematlas
import androidx.compose.foundation.clickable
import androidx.compose.foundation.layout.Arrangement
import androidx.compose.foundation.layout.Box
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.PaddingValues
import androidx.compose.foundation.layout.Row
import androidx.compose.foundation.layout.fillMaxWidth
import androidx.compose.foundation.layout.padding
import androidx.compose.foundation.lazy.LazyColumn
import androidx.compose.foundation.lazy.LazyListScope
import androidx.compose.foundation.lazy.items
import androidx.compose.material3.AlertDialog
import androidx.compose.material3.Button
import androidx.compose.material3.DropdownMenu
import androidx.compose.material3.DropdownMenuItem
import androidx.compose.material3.FilterChip
import androidx.compose.material3.HorizontalDivider
import androidx.compose.material3.LinearProgressIndicator
import androidx.compose.material3.MaterialTheme
import androidx.compose.material3.OutlinedButton
import androidx.compose.material3.OutlinedTextField
import androidx.compose.material3.Tab
import androidx.compose.material3.TabRow
import androidx.compose.material3.Text
import androidx.compose.material3.TextButton
import androidx.compose.runtime.Composable
import androidx.compose.runtime.getValue
import androidx.compose.runtime.key
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.remember
import androidx.compose.runtime.saveable.rememberSaveable
import androidx.compose.runtime.setValue
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.unit.dp
import androidx.compose.ui.window.DialogProperties
@Composable
internal fun Inventory(state: AtlasState, model: AtlasViewModel, modifier: Modifier) {
var pickSpace by remember { mutableStateOf(false) }
var showCreateSpace by remember { mutableStateOf(false) }
Column(modifier.fillMaxWidth().padding(horizontal = 20.dp), verticalArrangement = Arrangement.spacedBy(12.dp)) {
Row(Modifier.fillMaxWidth(), horizontalArrangement = Arrangement.SpaceBetween, verticalAlignment = Alignment.CenterVertically) {
Box {
OutlinedButton(onClick = { pickSpace = true }, enabled = !state.busy) {
Text(state.space?.name ?: "我的空间")
}
DropdownMenu(expanded = pickSpace, onDismissRequest = { pickSpace = false }) {
state.spaces.forEach { space ->
DropdownMenuItem(text = { Text(space.name) }, onClick = {
pickSpace = false
model.switchSpace(space)
})
}
DropdownMenuItem(text = { Text("新建空间") }, onClick = {
pickSpace = false
showCreateSpace = true
})
}
}
if (state.space?.writable == true && state.tab == InventoryTab.Find) {
Button(onClick = model::startAdd, enabled = !state.busy) { Text("添加物品") }
}
}
if (state.space == null) {
if (!state.busy) {
Text(if (state.error == null) "暂无空间" else "空间暂时无法加载", style = MaterialTheme.typography.titleLarge)
if (state.error == null) {
Button(onClick = { showCreateSpace = true }) { Text("新建空间") }
} else {
OutlinedButton(onClick = model::retrySpaces) { Text("刷新空间") }
}
}
Status(state)
} else {
TabRow(selectedTabIndex = state.tab.ordinal) {
Tab(
selected = state.tab == InventoryTab.Find, onClick = { model.switchTab(InventoryTab.Find) },
enabled = !state.busy, text = { Text("找物") },
)
Tab(
selected = state.tab == InventoryTab.Locations, onClick = { model.switchTab(InventoryTab.Locations) },
enabled = !state.busy, text = { Text("位置") },
)
}
when (state.tab) {
InventoryTab.Find -> FindItems(state, model)
InventoryTab.Locations -> LocationItems(state, model)
}
}
}
if (showCreateSpace) {
var name by rememberSaveable { mutableStateOf("") }
AlertDialog(
onDismissRequest = { showCreateSpace = false },
title = { Text("新建空间") },
text = {
OutlinedTextField(name, { name = it.take(100) }, Modifier.fillMaxWidth(),
label = { Text("空间名称") }, singleLine = true)
},
confirmButton = {
TextButton(onClick = {
showCreateSpace = false
model.createSpace(name)
}, enabled = name.isNotBlank()) { Text("创建") }
},
dismissButton = { TextButton(onClick = { showCreateSpace = false }) { Text("取消") } },
)
}
}
@Composable
private fun FindItems(state: AtlasState, model: AtlasViewModel) {
OutlinedTextField(
state.query, model::setQuery, Modifier.fillMaxWidth(), singleLine = true,
label = { Text("按名称、别名或位置找物") },
trailingIcon = {
if (state.query.isNotEmpty()) TextButton(onClick = { model.setQuery("") }) { Text("清空") }
},
)
Status(state)
LazyColumn(contentPadding = PaddingValues(bottom = 20.dp)) {
itemResults(state, model, if (state.query.isBlank()) "这里还没有物品" else "没有找到匹配的物品")
}
}
private val locationOrder = compareBy<Place> { it.sortRank ?: Int.MAX_VALUE }.thenBy(Place::name).thenBy(Place::id)
@Composable
private fun LocationItems(state: AtlasState, model: AtlasViewModel) {
val active = state.places.firstOrNull { it.id == state.locationId }
val children = remember(state.places, active?.id) {
state.places.filter { it.parentId == active?.id }.sortedWith(locationOrder)
}
Row(Modifier.fillMaxWidth(), horizontalArrangement = Arrangement.SpaceBetween, verticalAlignment = Alignment.CenterVertically) {
if (active == null) Text("房间和区域", style = MaterialTheme.typography.titleLarge)
else TextButton(onClick = { model.openLocation(active.parentId) }, enabled = !state.busy) { Text("上一级") }
if (state.space?.writable == true) {
OutlinedButton(onClick = { model.showLocationCreator(true) }, enabled = !state.busy) {
Text(if (active == null) "新建位置" else "添加子位置")
}
}
}
if (active != null) Text(active.path, style = MaterialTheme.typography.titleLarge)
PlaceStatus(state, model)
if (!state.creatingLocation && active == null) Status(state)
key(state.space?.id, active?.id) {
LazyColumn(contentPadding = PaddingValues(bottom = 20.dp)) {
items(children, key = { "place/${it.id}" }) { place ->
Row(Modifier.fillMaxWidth().clickable(enabled = !state.busy) { model.openLocation(place.id) }
.padding(vertical = 14.dp), verticalAlignment = Alignment.CenterVertically) {
Text(place.name, Modifier.weight(1f), style = MaterialTheme.typography.titleMedium)
Text("›", color = MaterialTheme.colorScheme.onSurfaceVariant)
}
HorizontalDivider()
}
if (active == null && children.isEmpty() && !state.loadingPlaces && state.placesError == null) {
item { Text("还没有位置", color = MaterialTheme.colorScheme.onSurfaceVariant) }
}
if (active != null) {
item {
Row(Modifier.fillMaxWidth().padding(top = 16.dp), horizontalArrangement = Arrangement.SpaceBetween,
verticalAlignment = Alignment.CenterVertically) {
Text("物品", style = MaterialTheme.typography.titleLarge)
if (state.space?.writable == true) {
Button(onClick = model::startAdd, enabled = !state.busy) { Text("在此添加") }
}
}
if (children.isNotEmpty()) {
Row(horizontalArrangement = Arrangement.spacedBy(8.dp)) {
FilterChip(!state.includeDescendants, { model.includeDescendants(false) }, { Text("仅此位置") })
FilterChip(state.includeDescendants, { model.includeDescendants(true) }, { Text("含下级") })
}
}
if (!state.creatingLocation) Status(state)
}
itemResults(state, model, if (state.includeDescendants) "这里和下级位置还没有物品" else "此位置还没有物品")
}
}
}
if (state.creatingLocation) {
LocationDialog(state, model, active != null)
}
}
@Composable
private fun LocationDialog(state: AtlasState, model: AtlasViewModel, isChild: Boolean) {
var name by rememberSaveable { mutableStateOf("") }
AlertDialog(
onDismissRequest = { model.showLocationCreator(false) },
properties = DialogProperties(dismissOnBackPress = !state.busy, dismissOnClickOutside = !state.busy),
title = { Text(if (isChild) "添加子位置" else "新建位置") },
text = {
Column(verticalArrangement = Arrangement.spacedBy(8.dp)) {
OutlinedTextField(name, { name = it.take(100) }, Modifier.fillMaxWidth(),
label = { Text("位置名称") }, enabled = !state.busy, singleLine = true)
Status(state)
}
},
confirmButton = {
TextButton(onClick = { model.createLocation(name) }, enabled = name.isNotBlank() && !state.busy) { Text("创建") }
},
dismissButton = { TextButton(onClick = { model.showLocationCreator(false) }, enabled = !state.busy) { Text("取消") } },
)
}
@Composable
internal fun PlaceStatus(state: AtlasState, model: AtlasViewModel) {
if (state.loadingPlaces && state.places.isEmpty()) LinearProgressIndicator(Modifier.fillMaxWidth())
state.placesError?.let { message ->
Text(message, color = MaterialTheme.colorScheme.error)
TextButton(onClick = model::refreshLocations) { Text("重试位置加载") }
}
}
private fun LazyListScope.itemResults(state: AtlasState, model: AtlasViewModel, emptyText: String) {
if (state.loading) item { LinearProgressIndicator(Modifier.fillMaxWidth()) }
if (state.error != null && !state.creatingLocation) {
item { TextButton(onClick = { model.search() }) { Text("重新加载物品") } }
}
if (state.items.isEmpty() && !state.loading && state.error == null) {
item {
Text(emptyText, color = MaterialTheme.colorScheme.onSurfaceVariant, modifier = Modifier.padding(vertical = 16.dp))
}
}
items(state.items, key = { "item/${it.id}" }) { item ->
Row(Modifier.fillMaxWidth().clickable(enabled = !state.busy) { model.open(item) }.padding(vertical = 14.dp),
horizontalArrangement = Arrangement.spacedBy(16.dp), verticalAlignment = Alignment.CenterVertically) {
Column(Modifier.weight(1f), verticalArrangement = Arrangement.spacedBy(3.dp)) {
Text(item.name, style = MaterialTheme.typography.titleMedium)
Text(item.displayPlace(), style = MaterialTheme.typography.bodyMedium,
color = MaterialTheme.colorScheme.onSurfaceVariant)
}
Text("× ${item.quantity}", style = MaterialTheme.typography.bodyMedium)
}
HorizontalDivider()
}
if (state.hasMore) {
item {
TextButton(onClick = { model.search(append = true) }, enabled = !state.loading && !state.busy) { Text("加载更多") }
}
}
}

View File

@ -10,10 +10,8 @@ import androidx.activity.viewModels
import androidx.compose.foundation.Image import androidx.compose.foundation.Image
import androidx.compose.foundation.clickable import androidx.compose.foundation.clickable
import androidx.compose.foundation.layout.Arrangement import androidx.compose.foundation.layout.Arrangement
import androidx.compose.foundation.layout.Box
import androidx.compose.foundation.layout.Column import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.ColumnScope import androidx.compose.foundation.layout.ColumnScope
import androidx.compose.foundation.layout.PaddingValues
import androidx.compose.foundation.layout.Row import androidx.compose.foundation.layout.Row
import androidx.compose.foundation.layout.Spacer import androidx.compose.foundation.layout.Spacer
import androidx.compose.foundation.layout.fillMaxWidth import androidx.compose.foundation.layout.fillMaxWidth
@ -29,8 +27,6 @@ import androidx.compose.foundation.text.KeyboardOptions
import androidx.compose.foundation.verticalScroll import androidx.compose.foundation.verticalScroll
import androidx.compose.material3.AlertDialog import androidx.compose.material3.AlertDialog
import androidx.compose.material3.Button import androidx.compose.material3.Button
import androidx.compose.material3.DropdownMenu
import androidx.compose.material3.DropdownMenuItem
import androidx.compose.material3.ExperimentalMaterial3Api import androidx.compose.material3.ExperimentalMaterial3Api
import androidx.compose.material3.HorizontalDivider import androidx.compose.material3.HorizontalDivider
import androidx.compose.material3.LinearProgressIndicator import androidx.compose.material3.LinearProgressIndicator
@ -90,7 +86,9 @@ class MainActivity : ComponentActivity() {
private fun AtlasApp(model: AtlasViewModel) { private fun AtlasApp(model: AtlasViewModel) {
val state by model.state.collectAsState() val state by model.state.collectAsState()
val child = state.screen != Screen.SignIn && state.screen != Screen.Inventory val child = state.screen != Screen.SignIn && state.screen != Screen.Inventory
BackHandler(child, model::back) val insideLocation = state.screen == Screen.Inventory && state.tab == InventoryTab.Locations &&
state.locationId != null
BackHandler(child || insideLocation, model::back)
Scaffold(topBar = { Scaffold(topBar = {
if (state.screen != Screen.SignIn) { if (state.screen != Screen.SignIn) {
val title = when (state.screen) { val title = when (state.screen) {
@ -156,99 +154,6 @@ private fun SignIn(state: AtlasState, model: AtlasViewModel, modifier: Modifier)
} }
} }
@Composable
private fun Inventory(state: AtlasState, model: AtlasViewModel, modifier: Modifier) {
var pickSpace by remember { mutableStateOf(false) }
var showCreateSpace by remember { mutableStateOf(false) }
Column(modifier.fillMaxWidth().padding(horizontal = 20.dp), verticalArrangement = Arrangement.spacedBy(12.dp)) {
Row(Modifier.fillMaxWidth(), horizontalArrangement = Arrangement.SpaceBetween, verticalAlignment = Alignment.CenterVertically) {
Box {
OutlinedButton(onClick = { pickSpace = true }, enabled = !state.busy) {
Text(state.space?.name ?: "我的空间")
}
DropdownMenu(expanded = pickSpace, onDismissRequest = { pickSpace = false }) {
state.spaces.forEach { space ->
DropdownMenuItem(text = { Text(space.name) }, onClick = {
pickSpace = false
model.switchSpace(space)
})
}
DropdownMenuItem(text = { Text("新建空间") }, onClick = {
pickSpace = false
showCreateSpace = true
})
}
}
if (state.space?.writable == true) {
Button(onClick = model::startAdd, enabled = !state.busy) { Text("添加物品") }
}
}
if (state.space == null && !state.busy) {
Text(if (state.error == null) "暂无空间" else "空间暂时无法加载", style = MaterialTheme.typography.titleLarge)
if (state.error == null) {
Button(onClick = { showCreateSpace = true }) { Text("新建空间") }
} else {
OutlinedButton(onClick = { model.retrySpaces() }) { Text("刷新空间") }
}
}
if (state.space != null) {
OutlinedTextField(
state.query, model::setQuery, Modifier.fillMaxWidth(), singleLine = true,
label = { Text("按名称或别名找物") },
trailingIcon = {
if (state.query.isNotEmpty()) TextButton(onClick = { model.setQuery("") }) { Text("清空") }
},
)
}
Status(state)
if (state.loading) LinearProgressIndicator(Modifier.fillMaxWidth())
if (state.error != null && state.space != null) {
TextButton(onClick = { model.search() }) { Text("重新加载") }
}
if (state.space != null && state.items.isEmpty() && !state.loading && state.error == null) {
Text(if (state.query.isBlank()) "这里还没有物品" else "没有找到匹配的物品",
color = MaterialTheme.colorScheme.onSurfaceVariant, modifier = Modifier.padding(vertical = 16.dp))
}
LazyColumn(contentPadding = PaddingValues(bottom = 20.dp)) {
items(state.items, key = Item::id) { item ->
Row(Modifier.fillMaxWidth().clickable(enabled = !state.busy) { model.open(item) }.padding(vertical = 14.dp),
horizontalArrangement = Arrangement.spacedBy(16.dp), verticalAlignment = Alignment.CenterVertically) {
Column(Modifier.weight(1f), verticalArrangement = Arrangement.spacedBy(3.dp)) {
Text(item.name, style = MaterialTheme.typography.titleMedium)
Text(item.displayPlace(), style = MaterialTheme.typography.bodyMedium,
color = MaterialTheme.colorScheme.onSurfaceVariant)
}
Text("× ${item.quantity}", style = MaterialTheme.typography.bodyMedium)
}
HorizontalDivider()
}
if (state.hasMore) {
item {
TextButton(onClick = { model.search(append = true) }, enabled = !state.loading) { Text("加载更多") }
}
}
}
}
if (showCreateSpace) {
var name by rememberSaveable { mutableStateOf("") }
AlertDialog(
onDismissRequest = { showCreateSpace = false },
title = { Text("新建空间") },
text = {
OutlinedTextField(name, { name = it.take(100) }, Modifier.fillMaxWidth(),
label = { Text("空间名称") }, singleLine = true)
},
confirmButton = {
TextButton(onClick = {
showCreateSpace = false
model.createSpace(name)
}, enabled = name.isNotBlank()) { Text("创建") }
},
dismissButton = { TextButton(onClick = { showCreateSpace = false }) { Text("取消") } },
)
}
}
@Composable @Composable
private fun Detail(state: AtlasState, model: AtlasViewModel, modifier: Modifier) { private fun Detail(state: AtlasState, model: AtlasViewModel, modifier: Modifier) {
Form(modifier) { Form(modifier) {
@ -316,11 +221,15 @@ private fun AddItem(state: AtlasState, model: AtlasViewModel, modifier: Modifier
var quantity by rememberSaveable { mutableStateOf("1") } var quantity by rememberSaveable { mutableStateOf("1") }
var aliases by rememberSaveable { mutableStateOf("") } var aliases by rememberSaveable { mutableStateOf("") }
var notes by rememberSaveable { mutableStateOf("") } var notes by rememberSaveable { mutableStateOf("") }
var placeId by rememberSaveable { mutableStateOf<String?>(null) } var placeId by rememberSaveable {
mutableStateOf(state.locationId.takeIf { state.tab == InventoryTab.Locations })
}
val place = state.places.firstOrNull { it.id == placeId } val place = state.places.firstOrNull { it.id == placeId }
Form(modifier) { Form(modifier) {
ItemNameAndQuantity(title, { title = it }, quantity, { quantity = it }, !state.busy) ItemNameAndQuantity(title, { title = it }, quantity, { quantity = it }, !state.busy)
PlacePicker(state.places, place?.path ?: "未设置位置", !state.busy) { placeId = it?.id } val pickedLabel = place?.path ?: if (placeId == null) "未设置位置" else "所选位置已不可用"
PlacePicker(state.places, pickedLabel, !state.busy) { placeId = it?.id }
PlaceStatus(state, model)
OutlinedTextField(aliases, { aliases = it }, Modifier.fillMaxWidth(), enabled = !state.busy, OutlinedTextField(aliases, { aliases = it }, Modifier.fillMaxWidth(), enabled = !state.busy,
label = { Text("别名,可用逗号分隔") }) label = { Text("别名,可用逗号分隔") })
ItemNotes(notes, { notes = it }, !state.busy) ItemNotes(notes, { notes = it }, !state.busy)
@ -390,6 +299,7 @@ private fun MoveItem(state: AtlasState, model: AtlasViewModel, modifier: Modifie
DetailLine("当前位置", item.displayPlace()) DetailLine("当前位置", item.displayPlace())
val pickedLabel = place?.path ?: if (placeId == item.locationId) item.displayPlace() else "未设置位置" val pickedLabel = place?.path ?: if (placeId == item.locationId) item.displayPlace() else "未设置位置"
PlacePicker(state.places, pickedLabel, enabled) { placeId = it?.id } PlacePicker(state.places, pickedLabel, enabled) { placeId = it?.id }
PlaceStatus(state, model)
WriteStatus(state, model) WriteStatus(state, model)
Button( Button(
onClick = { model.move(place) }, onClick = { model.move(place) },
@ -446,7 +356,7 @@ private fun PlaceOption(label: String, pick: () -> Unit) {
} }
@Composable @Composable
private fun Status(state: AtlasState) { internal fun Status(state: AtlasState) {
if (state.busy) LinearProgressIndicator(Modifier.fillMaxWidth()) if (state.busy) LinearProgressIndicator(Modifier.fillMaxWidth())
state.error?.let { Text(it, color = MaterialTheme.colorScheme.error) } state.error?.let { Text(it, color = MaterialTheme.colorScheme.error) }
} }
@ -457,4 +367,4 @@ private fun Form(modifier: Modifier, content: @Composable ColumnScope.() -> Unit
verticalArrangement = Arrangement.spacedBy(12.dp), content = content) verticalArrangement = Arrangement.spacedBy(12.dp), content = content)
} }
private fun Item.displayPlace() = locationPath.ifBlank { "未设置位置" } internal fun Item.displayPlace() = locationPath.ifBlank { "未设置位置" }