From f67f68337350402491993755a0025e3edd9c5b61 Mon Sep 17 00:00:00 2001 From: dongjf <1+dongjf@noreply.git.tutudog.com> Date: Sun, 29 Nov 2026 17:32:35 +0800 Subject: [PATCH] =?UTF-8?q?feat(android):=20=E5=A2=9E=E5=8A=A0=E5=88=86?= =?UTF-8?q?=E7=BA=A7=E4=BD=8D=E7=BD=AE=E6=B5=8F=E8=A7=88=E5=92=8C=E5=B0=B1?= =?UTF-8?q?=E5=9C=B0=E5=BD=95=E5=85=A5?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- apps/android/README.md | 4 +- apps/android/app/build.gradle.kts | 4 +- .../java/com/tutudog/itematlas/AtlasApi.kt | 27 +- .../com/tutudog/itematlas/AtlasViewModel.kt | 105 ++++++-- .../com/tutudog/itematlas/InventoryBrowser.kt | 245 ++++++++++++++++++ .../com/tutudog/itematlas/MainActivity.kt | 114 +------- 6 files changed, 374 insertions(+), 125 deletions(-) create mode 100644 apps/android/app/src/main/java/com/tutudog/itematlas/InventoryBrowser.kt diff --git a/apps/android/README.md b/apps/android/README.md index d052c57..35db2f6 100644 --- a/apps/android/README.md +++ b/apps/android/README.md @@ -4,6 +4,8 @@ Android 8.0(API 26)及以上。使用 Kotlin、Jetpack Compose 和见物原 详情展示购入单价和移位记录。可以编辑名称、数量、别名和备注,存放位置由移位操作管理。编辑过程中若其他端先更新了同一物品,服务端会根据物品版本返回 409。用户确认载入最新内容后,可以基于新版本重新修改。 +「找物」用于全空间搜索。「位置」从房间和区域逐层打开,按服务端保存的同级顺序显示。可在某个位置查看直接存放的物品,也可切换到「含下级」。从该位置点「在此添加」,表单会预选当前路径,仍可改选或清空。拥有写权限的成员可以新建房间和子位置。 + 会话令牌只在应用进程内使用,续期由 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) diff --git a/apps/android/app/build.gradle.kts b/apps/android/app/build.gradle.kts index 966ac80..7aafd39 100644 --- a/apps/android/app/build.gradle.kts +++ b/apps/android/app/build.gradle.kts @@ -15,8 +15,8 @@ android { applicationId = "com.tutudog.itematlas" minSdk = 26 targetSdk = 35 - versionCode = 2 - versionName = "0.1.1" + versionCode = 3 + versionName = "0.1.2" 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" } diff --git a/apps/android/app/src/main/java/com/tutudog/itematlas/AtlasApi.kt b/apps/android/app/src/main/java/com/tutudog/itematlas/AtlasApi.kt index 0e902ff..999685a 100644 --- a/apps/android/app/src/main/java/com/tutudog/itematlas/AtlasApi.kt +++ b/apps/android/app/src/main/java/com/tutudog/itematlas/AtlasApi.kt @@ -23,7 +23,13 @@ data class Space(val id: String, val name: String, val role: String) { } @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 data class Item( @@ -68,6 +74,9 @@ class AtlasApi(origin: String = BuildConfig.ATLAS_API_ORIGIN) { @Serializable private data class SpaceInput(val name: String) + @Serializable + private data class PlaceInput(val name: String, val parentId: String?) + @Serializable 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 = json.decodeFromString(read(family(space, "locations"))) - suspend fun search(space: Space, query: String, offset: Int = 0): List { - val url = family(space, "items").newBuilder() + suspend fun createLocation(space: Space, name: String, parentId: String?): Place = + 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 { + val builder = family(space, "items").newBuilder() .addQueryParameter("q", query.trim()) .addQueryParameter("limit", "30") .addQueryParameter("offset", offset.toString()) - .build() - return json.decodeFromString(read(url)) + if (locationId != null) { + 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))) diff --git a/apps/android/app/src/main/java/com/tutudog/itematlas/AtlasViewModel.kt b/apps/android/app/src/main/java/com/tutudog/itematlas/AtlasViewModel.kt index af041c5..fac4401 100644 --- a/apps/android/app/src/main/java/com/tutudog/itematlas/AtlasViewModel.kt +++ b/apps/android/app/src/main/java/com/tutudog/itematlas/AtlasViewModel.kt @@ -13,12 +13,19 @@ import kotlinx.coroutines.flow.update import kotlinx.coroutines.launch enum class Screen { SignIn, Inventory, Detail, Add, Edit, Move } +enum class InventoryTab { Find, Locations } data class AtlasState( val screen: Screen = Screen.SignIn, + val tab: InventoryTab = InventoryTab.Find, val spaces: List = emptyList(), val space: Space? = null, val places: List = emptyList(), + val locationId: String? = null, + val includeDescendants: Boolean = false, + val loadingPlaces: Boolean = false, + val placesError: String? = null, + val creatingLocation: Boolean = false, val items: List = emptyList(), val selected: Item? = null, val recentMoves: List? = null, @@ -75,29 +82,84 @@ class AtlasViewModel : ViewModel() { detailJob?.cancel() mutable.update { 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, error = null, screen = Screen.Inventory) } search() - locations() + refreshLocations() } - private fun locations() { + fun refreshLocations() { val space = mutable.value.space ?: return placesJob?.cancel() + mutable.update { it.copy(loadingPlaces = true, placesError = null) } placesJob = viewModelScope.launch { try { 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) { 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) + } 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) { if (query == mutable.value.query) return 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) { val prior = mutable.value 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 listJob?.cancel() mutable.update { it.copy(loading = true, error = null) } @@ -114,9 +178,12 @@ class AtlasViewModel : ViewModel() { try { if (debounce) delay(200) 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 { - 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 { val merged = if (append) (it.items + found).distinctBy(Item::id) else found val next = offset + found.size @@ -134,9 +201,11 @@ class AtlasViewModel : ViewModel() { fun open(item: Item) { val space = mutable.value.space ?: return + listJob?.cancel() detailJob?.cancel() 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 { try { @@ -159,7 +228,7 @@ class AtlasViewModel : ViewModel() { pendingItem = null pendingKey = "" mutable.update { it.copy(screen = Screen.Add, error = null) } - locations() + refreshLocations() } 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 detailJob?.cancel() mutable.update { it.copy(screen = Screen.Move, writeConflict = false, error = null) } - locations() + refreshLocations() } fun move(position: Place?) { @@ -250,6 +319,11 @@ class AtlasViewModel : ViewModel() { if (mutable.value.busy) return detailJob?.cancel() 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) { mutable.value.selected?.let(::open) return @@ -295,12 +369,13 @@ class AtlasViewModel : ViewModel() { detailJob?.cancel() mutable.value = AtlasState(error = "登录已过期,请重新登录。") } else { - val detail = when (failure) { - is IOException -> "连接服务失败,请检查网络。" - is ApiError -> failure.message ?: "请求失败,请重试。" - else -> "无法读取服务返回的数据,请重试。" - } - mutable.update { it.copy(error = detail) } + mutable.update { it.copy(error = errorMessage(failure)) } } } + + private fun errorMessage(failure: Exception): String = when (failure) { + is IOException -> "连接服务失败,请检查网络。" + is ApiError -> failure.message ?: "请求失败,请重试。" + else -> "无法读取服务返回的数据,请重试。" + } } diff --git a/apps/android/app/src/main/java/com/tutudog/itematlas/InventoryBrowser.kt b/apps/android/app/src/main/java/com/tutudog/itematlas/InventoryBrowser.kt new file mode 100644 index 0000000..55d81b4 --- /dev/null +++ b/apps/android/app/src/main/java/com/tutudog/itematlas/InventoryBrowser.kt @@ -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 { 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("加载更多") } + } + } +} diff --git a/apps/android/app/src/main/java/com/tutudog/itematlas/MainActivity.kt b/apps/android/app/src/main/java/com/tutudog/itematlas/MainActivity.kt index e56efc4..304946b 100644 --- a/apps/android/app/src/main/java/com/tutudog/itematlas/MainActivity.kt +++ b/apps/android/app/src/main/java/com/tutudog/itematlas/MainActivity.kt @@ -10,10 +10,8 @@ import androidx.activity.viewModels import androidx.compose.foundation.Image 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.ColumnScope -import androidx.compose.foundation.layout.PaddingValues import androidx.compose.foundation.layout.Row import androidx.compose.foundation.layout.Spacer import androidx.compose.foundation.layout.fillMaxWidth @@ -29,8 +27,6 @@ import androidx.compose.foundation.text.KeyboardOptions import androidx.compose.foundation.verticalScroll import androidx.compose.material3.AlertDialog import androidx.compose.material3.Button -import androidx.compose.material3.DropdownMenu -import androidx.compose.material3.DropdownMenuItem import androidx.compose.material3.ExperimentalMaterial3Api import androidx.compose.material3.HorizontalDivider import androidx.compose.material3.LinearProgressIndicator @@ -90,7 +86,9 @@ class MainActivity : ComponentActivity() { private fun AtlasApp(model: AtlasViewModel) { val state by model.state.collectAsState() 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 = { if (state.screen != Screen.SignIn) { 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 private fun Detail(state: AtlasState, model: AtlasViewModel, modifier: Modifier) { Form(modifier) { @@ -316,11 +221,15 @@ private fun AddItem(state: AtlasState, model: AtlasViewModel, modifier: Modifier var quantity by rememberSaveable { mutableStateOf("1") } var aliases by rememberSaveable { mutableStateOf("") } var notes by rememberSaveable { mutableStateOf("") } - var placeId by rememberSaveable { mutableStateOf(null) } + var placeId by rememberSaveable { + mutableStateOf(state.locationId.takeIf { state.tab == InventoryTab.Locations }) + } val place = state.places.firstOrNull { it.id == placeId } Form(modifier) { 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, label = { Text("别名,可用逗号分隔") }) ItemNotes(notes, { notes = it }, !state.busy) @@ -390,6 +299,7 @@ private fun MoveItem(state: AtlasState, model: AtlasViewModel, modifier: Modifie DetailLine("当前位置", item.displayPlace()) val pickedLabel = place?.path ?: if (placeId == item.locationId) item.displayPlace() else "未设置位置" PlacePicker(state.places, pickedLabel, enabled) { placeId = it?.id } + PlaceStatus(state, model) WriteStatus(state, model) Button( onClick = { model.move(place) }, @@ -446,7 +356,7 @@ private fun PlaceOption(label: String, pick: () -> Unit) { } @Composable -private fun Status(state: AtlasState) { +internal fun Status(state: AtlasState) { if (state.busy) LinearProgressIndicator(Modifier.fillMaxWidth()) 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) } -private fun Item.displayPlace() = locationPath.ifBlank { "未设置位置" } +internal fun Item.displayPlace() = locationPath.ifBlank { "未设置位置" }