Compare commits
2 Commits
ee9aa707a7
...
31cd5a2040
| Author | SHA1 | Date |
|---|---|---|
|
|
31cd5a2040 | |
|
|
a110c7a562 |
|
|
@ -15,3 +15,5 @@ docker build -t item-atlas-admin:dev .
|
||||||
列表使用 `GET /api/admin/households?q=&limit=25&offset=0`,按名称及 ID 排序。名称按字面包含匹配,查询长度最多 100,页大小为 1 至 100。响应中的 `hasMore` 决定是否提供下一页。查询、详情和删除沿用 `atlas-admin` 客户端与 `atlas-space-admin` 角色鉴权。部署后台镜像前先部署包含列表接口的物品服务,然后在内部入口用管理员与普通账号分别检查权限。
|
列表使用 `GET /api/admin/households?q=&limit=25&offset=0`,按名称及 ID 排序。名称按字面包含匹配,查询长度最多 100,页大小为 1 至 100。响应中的 `hasMore` 决定是否提供下一页。查询、详情和删除沿用 `atlas-admin` 客户端与 `atlas-space-admin` 角色鉴权。部署后台镜像前先部署包含列表接口的物品服务,然后在内部入口用管理员与普通账号分别检查权限。
|
||||||
|
|
||||||
「删除记录」显示管理员删除空间的时间、空间 ID 和操作人 ID。列表从 `GET /api/admin/space-deletions?limit=25` 读取,可以按 `householdId` 精确查。下一页传入响应中的 `nextBefore`,排序以删除时间和记录 ID 降序为准。读取同样需要管理员权限,响应禁止缓存。操作人与空间 ID 来自删除事务落库的审计记录。记录的查询不需要关联已删除的空间。
|
「删除记录」显示管理员删除空间的时间、空间 ID 和操作人 ID。列表从 `GET /api/admin/space-deletions?limit=25` 读取,可以按 `householdId` 精确查。下一页传入响应中的 `nextBefore`,排序以删除时间和记录 ID 降序为准。读取同样需要管理员权限,响应禁止缓存。操作人与空间 ID 来自删除事务落库的审计记录。记录的查询不需要关联已删除的空间。
|
||||||
|
|
||||||
|
「图片清理」读取 `GET /api/admin/media-cleanup`。它显示已到执行时间的任务、延后的任务、曾重试的任务及最早应执行时间。曾重试可同时属于前两组之一。上传结束前暂存的清理预留也计入队列,成功登记图片后会移除。服务端用一条 PostgreSQL 汇总查询读取现场状态,仅返回计数和时间。接口沿用管理员鉴权与 `Cache-Control: no-store`。如果环境没有配置图片存储,页面会提示清理任务保留在队列中。 [常用排错入口](../../docs/deployment/identity-and-media.md)
|
||||||
|
|
|
||||||
|
|
@ -8,11 +8,13 @@ interface Space extends SpaceSummary { items: number; photos: number }
|
||||||
interface SpacePage { spaces: SpaceSummary[]; hasMore: boolean }
|
interface SpacePage { spaces: SpaceSummary[]; hasMore: boolean }
|
||||||
interface SpaceDeletion { id: string; householdId: string; operatorId: string; deletedAt: string }
|
interface SpaceDeletion { id: string; householdId: string; operatorId: string; deletedAt: string }
|
||||||
interface DeletionPage { records: SpaceDeletion[]; nextBefore: string | null }
|
interface DeletionPage { records: SpaceDeletion[]; nextBefore: string | null }
|
||||||
type AdminView = 'spaces' | 'audit'
|
interface MediaCleanupStatus { workerEnabled: boolean; due: number; scheduled: number; retrying: number; oldestDueAt: string | null }
|
||||||
|
type AdminView = 'spaces' | 'audit' | 'media'
|
||||||
|
|
||||||
const pageSize = 25
|
const pageSize = 25
|
||||||
const spacesApi = '/api/admin/households'
|
const spacesApi = '/api/admin/households'
|
||||||
const auditApi = '/api/admin/space-deletions'
|
const auditApi = '/api/admin/space-deletions'
|
||||||
|
const cleanupApi = '/api/admin/media-cleanup'
|
||||||
const identityUrl = import.meta.env.VITE_OIDC_URL || 'https://api-atlas.tutudog.com/auth'
|
const identityUrl = import.meta.env.VITE_OIDC_URL || 'https://api-atlas.tutudog.com/auth'
|
||||||
|
|
||||||
const keycloak = new Keycloak({
|
const keycloak = new Keycloak({
|
||||||
|
|
@ -39,6 +41,7 @@ const auditInput = ref('')
|
||||||
const auditHousehold = ref('')
|
const auditHousehold = ref('')
|
||||||
const auditPage = ref<DeletionPage>()
|
const auditPage = ref<DeletionPage>()
|
||||||
const auditCursors = ref<(string | null)[]>([null])
|
const auditCursors = ref<(string | null)[]>([null])
|
||||||
|
const cleanup = ref<MediaCleanupStatus>()
|
||||||
const isId = (value: string) => /^[\da-f]{8}(-[\da-f]{4}){3}-[\da-f]{12}$/i.test(value)
|
const isId = (value: string) => /^[\da-f]{8}(-[\da-f]{4}){3}-[\da-f]{12}$/i.test(value)
|
||||||
const pageNumber = computed(() => pageOffset.value / pageSize + 1)
|
const pageNumber = computed(() => pageOffset.value / pageSize + 1)
|
||||||
const auditDate = new Intl.DateTimeFormat('zh-CN', { dateStyle: 'medium', timeStyle: 'medium' })
|
const auditDate = new Intl.DateTimeFormat('zh-CN', { dateStyle: 'medium', timeStyle: 'medium' })
|
||||||
|
|
@ -61,6 +64,7 @@ function clearManagementData() {
|
||||||
page.value = undefined
|
page.value = undefined
|
||||||
space.value = undefined
|
space.value = undefined
|
||||||
auditPage.value = undefined
|
auditPage.value = undefined
|
||||||
|
cleanup.value = undefined
|
||||||
confirming.value = false
|
confirming.value = false
|
||||||
confirmation.value = success.value = ''
|
confirmation.value = success.value = ''
|
||||||
}
|
}
|
||||||
|
|
@ -95,6 +99,21 @@ function selectView(next: AdminView) {
|
||||||
view.value = next
|
view.value = next
|
||||||
success.value = error.value = ''
|
success.value = error.value = ''
|
||||||
if (next === 'audit') void loadAudit([null], auditHousehold.value)
|
if (next === 'audit') void loadAudit([null], auditHousehold.value)
|
||||||
|
if (next === 'media') void loadMediaCleanup()
|
||||||
|
}
|
||||||
|
|
||||||
|
async function loadMediaCleanup() {
|
||||||
|
if (busy.value) return
|
||||||
|
busy.value = true
|
||||||
|
error.value = ''
|
||||||
|
cleanup.value = undefined
|
||||||
|
try {
|
||||||
|
cleanup.value = await (await request(cleanupApi)).json()
|
||||||
|
} catch (failure) {
|
||||||
|
error.value = failure instanceof Error ? failure.message : '图片清理状态加载失败。'
|
||||||
|
} finally {
|
||||||
|
busy.value = false
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
function searchAudit() {
|
function searchAudit() {
|
||||||
|
|
@ -208,6 +227,7 @@ async function deleteSpace() {
|
||||||
<nav class="views" aria-label="后台功能">
|
<nav class="views" aria-label="后台功能">
|
||||||
<el-button :type="view === 'spaces' ? 'primary' : 'default'" :aria-pressed="view === 'spaces'" :disabled="busy" @click="selectView('spaces')">空间管理</el-button>
|
<el-button :type="view === 'spaces' ? 'primary' : 'default'" :aria-pressed="view === 'spaces'" :disabled="busy" @click="selectView('spaces')">空间管理</el-button>
|
||||||
<el-button :type="view === 'audit' ? 'primary' : 'default'" :aria-pressed="view === 'audit'" :disabled="busy" @click="selectView('audit')">删除记录</el-button>
|
<el-button :type="view === 'audit' ? 'primary' : 'default'" :aria-pressed="view === 'audit'" :disabled="busy" @click="selectView('audit')">删除记录</el-button>
|
||||||
|
<el-button :type="view === 'media' ? 'primary' : 'default'" :aria-pressed="view === 'media'" :disabled="busy" @click="selectView('media')">图片清理</el-button>
|
||||||
</nav>
|
</nav>
|
||||||
</template>
|
</template>
|
||||||
<template v-if="authorized && view === 'spaces'">
|
<template v-if="authorized && view === 'spaces'">
|
||||||
|
|
@ -277,6 +297,26 @@ async function deleteSpace() {
|
||||||
</nav>
|
</nav>
|
||||||
</template>
|
</template>
|
||||||
</section>
|
</section>
|
||||||
|
<section v-if="authorized && view === 'media'" v-loading="busy" aria-label="图片清理">
|
||||||
|
<el-card shadow="never">
|
||||||
|
<header class="section-head">
|
||||||
|
<h2>图片清理</h2>
|
||||||
|
<el-button :disabled="busy" @click="loadMediaCleanup">刷新</el-button>
|
||||||
|
</header>
|
||||||
|
<template v-if="cleanup">
|
||||||
|
<el-alert v-if="!cleanup.workerEnabled" title="当前环境未配置图片存储,清理任务会保留在队列里。"
|
||||||
|
type="warning" show-icon :closable="false" />
|
||||||
|
<el-descriptions :column="2" border>
|
||||||
|
<el-descriptions-item label="待执行">{{ cleanup.due }}</el-descriptions-item>
|
||||||
|
<el-descriptions-item label="未到执行时间">{{ cleanup.scheduled }}</el-descriptions-item>
|
||||||
|
<el-descriptions-item label="曾重试">{{ cleanup.retrying }}</el-descriptions-item>
|
||||||
|
<el-descriptions-item label="最早待执行">
|
||||||
|
{{ cleanup.oldestDueAt ? auditDate.format(new Date(cleanup.oldestDueAt)) : '—' }}
|
||||||
|
</el-descriptions-item>
|
||||||
|
</el-descriptions>
|
||||||
|
</template>
|
||||||
|
</el-card>
|
||||||
|
</section>
|
||||||
</main>
|
</main>
|
||||||
</el-config-provider>
|
</el-config-provider>
|
||||||
</template>
|
</template>
|
||||||
|
|
@ -285,6 +325,8 @@ async function deleteSpace() {
|
||||||
body { margin: 0; background: #f4f6fa; font-family: system-ui, sans-serif; color: #222c41; }
|
body { margin: 0; background: #f4f6fa; font-family: system-ui, sans-serif; color: #222c41; }
|
||||||
main { max-width: 920px; margin: 0 auto; padding: 26px 20px; }
|
main { max-width: 920px; margin: 0 auto; padding: 26px 20px; }
|
||||||
header { display: flex; align-items: center; justify-content: space-between; margin-bottom: 24px; }
|
header { display: flex; align-items: center; justify-content: space-between; margin-bottom: 24px; }
|
||||||
|
.section-head { margin-bottom: 16px; }
|
||||||
|
.section-head h2 { margin: 0; font-size: 18px; }
|
||||||
h1 { margin: 0; font-size: 26px; }
|
h1 { margin: 0; font-size: 26px; }
|
||||||
h1 small { color: #596476; font-size: 15px; font-weight: 500; margin-left: 8px; }
|
h1 small { color: #596476; font-size: 15px; font-weight: 500; margin-left: 8px; }
|
||||||
h2 { margin-top: 0; }
|
h2 { margin-top: 0; }
|
||||||
|
|
|
||||||
|
|
@ -1,10 +1,16 @@
|
||||||
# 见物 Android
|
# 见物 Android
|
||||||
|
|
||||||
Android 8.0(API 26)及以上。使用 Kotlin、Jetpack Compose 和见物原生会话 API。用已有账号登录后,可新建或切换空间、按名称和别名找物、查看详情、手动添加物品和移位。录入可以不选位置,移位也可以清空位置。只读空间仅显示查询功能。
|
Android 8.0(API 26)及以上。使用 Kotlin、Jetpack Compose 和见物原生会话 API。应用分为找物、位置、社区和我的。用已有账号登录后可以新建或切换空间,按名称、别名或路径找物。录入可以暂时不填位置,移位也可以清空位置。
|
||||||
|
|
||||||
详情展示购入单价和移位记录。可以编辑名称、数量、别名和备注,存放位置由移位操作管理。编辑过程中若其他端先更新了同一物品,服务端会根据物品版本返回 409。用户确认载入最新内容后,可以基于新版本重新修改。
|
详情展示购入单价和移位记录,可以编辑名称、数量、别名和备注、设置关联、归档物品。个人收藏、星级和短评由账号各自保存。所有者可单独填写公开标题与正文并发布,社区支持搜索、查看作者、评论、打星和撤回。家中的存放路径、照片和备注仍按空间权限读取。
|
||||||
|
|
||||||
「找物」用于全空间搜索。「位置」从房间和区域逐层打开,按服务端保存的同级顺序显示。可在某个位置查看直接存放的物品,也可切换到「含下级」。从该位置点「在此添加」,表单会预选当前路径,仍可改选或清空。拥有写权限的成员可以新建房间和子位置。
|
「位置」支持平铺排序及全屋、室内两级平面图。用模板新建或摆放已有位置,可以拖动到 10 厘米网格、修改宽深、旋转、撤回和重做。模型建议经预览和选择后进入本地编辑,点保存才更新后端。保存和排序都带版本冲突检查。三级及以下使用平铺。
|
||||||
|
|
||||||
|
添加物品可以转入智能录入。手工文字和通过系统本机识别转写的文字都能生成草稿。草稿中可以改名称和数量、换位置、清空位置,再确认保存。用返回的操作编号查询异步交付状态。语音在支持本机 SpeechRecognizer 的 Android 12 及以上设备可用,每次最多 25 秒。
|
||||||
|
|
||||||
|
物品详情及位置中可拍照或从系统相册选图。客户端限制原文件为 30 MiB,裁剪图最长边 1440 像素,上传 JPEG 上限 5 MiB。服务器生成缩略图并管理原图,单处最多六张。只有有写权限的成员可上传和删除。 [图片权限和清理](../../docs/deployment/identity-and-media.md)
|
||||||
|
|
||||||
|
「我的」显示头像、签名、物品概览和当前空间收藏。按账号发出的邀请由对方在收件箱处理。所有者可改成员角色、移除普通成员及撤回邀请。
|
||||||
|
|
||||||
会话令牌只在应用进程内使用,续期由 API 客户端处理。应用被完全关闭后需要重新登录。应用不预置物品、账号或凭据。
|
会话令牌只在应用进程内使用,续期由 API 客户端处理。应用被完全关闭后需要重新登录。应用不预置物品、账号或凭据。
|
||||||
|
|
||||||
|
|
@ -22,6 +28,6 @@ adb install -r app/build/outputs/apk/debug/app-debug.apk
|
||||||
|
|
||||||
## 验收
|
## 验收
|
||||||
|
|
||||||
登录后切换空间,输入名称或别名并打开详情。分别尝试在有位置和无位置时录入,再移动到另一个位置或清空位置,核对详情中的移位记录。建三层位置,验证「仅此位置」「含下级」和从位置详情预选录入。两端同时打开同一件物品,用一端保存后再在另一端提交,检查冲突提示及重新载入。用只读成员检查物品写入口,用网络中断检查失败提示,退出后确认页面清空。拍照、语音、社区及平面图随后接入。
|
验收走登录、两级位置、找物及移位,另查室内平面图保存和放弃未保存修改。智能录入先生成文字草稿再确认,重读物品确认异步交付结果。照片用同一份样例核对缩略图、原图和删除。模拟器可以验证页面和系统意图回调,麦克风、相机以及权限弹窗按设备验收。 [客户端用例](../../docs/testing/cases.md)
|
||||||
|
|
||||||
[客户端架构](../../docs/architecture/clients.md) · [Android 构建](https://developer.android.com/build/building-cmdline)
|
[客户端架构](../../docs/architecture/clients.md) · [Android 构建](https://developer.android.com/build/building-cmdline)
|
||||||
|
|
|
||||||
|
|
@ -15,8 +15,8 @@ android {
|
||||||
applicationId = "com.tutudog.itematlas"
|
applicationId = "com.tutudog.itematlas"
|
||||||
minSdk = 26
|
minSdk = 26
|
||||||
targetSdk = 35
|
targetSdk = 35
|
||||||
versionCode = 3
|
versionCode = 4
|
||||||
versionName = "0.1.2"
|
versionName = "0.1.3"
|
||||||
|
|
||||||
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" }
|
||||||
|
|
|
||||||
|
|
@ -1,12 +1,27 @@
|
||||||
<?xml version="1.0" encoding="utf-8"?>
|
<?xml version="1.0" encoding="utf-8"?>
|
||||||
<manifest xmlns:android="http://schemas.android.com/apk/res/android">
|
<manifest xmlns:android="http://schemas.android.com/apk/res/android">
|
||||||
<uses-permission android:name="android.permission.INTERNET" />
|
<uses-permission android:name="android.permission.INTERNET" />
|
||||||
|
<uses-permission android:name="android.permission.RECORD_AUDIO" />
|
||||||
|
<queries>
|
||||||
|
<intent>
|
||||||
|
<action android:name="android.speech.RecognitionService" />
|
||||||
|
</intent>
|
||||||
|
</queries>
|
||||||
<application
|
<application
|
||||||
android:allowBackup="false"
|
android:allowBackup="false"
|
||||||
android:icon="@drawable/brand"
|
android:icon="@drawable/brand"
|
||||||
android:label="@string/app_name"
|
android:label="@string/app_name"
|
||||||
android:theme="@style/AtlasTheme"
|
android:theme="@style/AtlasTheme"
|
||||||
android:usesCleartextTraffic="false">
|
android:usesCleartextTraffic="false">
|
||||||
|
<provider
|
||||||
|
android:name="androidx.core.content.FileProvider"
|
||||||
|
android:authorities="${applicationId}.photos"
|
||||||
|
android:exported="false"
|
||||||
|
android:grantUriPermissions="true">
|
||||||
|
<meta-data
|
||||||
|
android:name="android.support.FILE_PROVIDER_PATHS"
|
||||||
|
android:resource="@xml/photo_paths" />
|
||||||
|
</provider>
|
||||||
<activity
|
<activity
|
||||||
android:name=".MainActivity"
|
android:name=".MainActivity"
|
||||||
android:exported="true"
|
android:exported="true"
|
||||||
|
|
|
||||||
|
|
@ -0,0 +1,31 @@
|
||||||
|
package com.tutudog.itematlas
|
||||||
|
|
||||||
|
import kotlinx.serialization.Serializable
|
||||||
|
|
||||||
|
@Serializable data class ItemPreference(val favorite: Boolean = false, val rating: Int? = null, val note: String? = null)
|
||||||
|
@Serializable enum class RelationKind(val label: String) { ACCESSORY("配件"), SIMILAR("同类"), TOGETHER("常一起用") }
|
||||||
|
@Serializable data class RelationInput(val itemId: String, val kind: RelationKind)
|
||||||
|
@Serializable data class RelatedItem(val itemId: String, val name: String, val locationPath: String, val kind: RelationKind)
|
||||||
|
@Serializable data class Publication(val postId: String? = null, val title: String = "", val body: String = "")
|
||||||
|
@Serializable data class PublishInput(val title: String, val body: String)
|
||||||
|
@Serializable data class CommunityPost(
|
||||||
|
val id: String, val title: String, val body: String, val author: String, val authorId: String,
|
||||||
|
val average: Double? = null, val votes: Long = 0, val myRating: Int? = null, val comments: Long = 0,
|
||||||
|
)
|
||||||
|
@Serializable data class FeedCursor(val rank: Int, val time: String, val id: String)
|
||||||
|
@Serializable data class CommunityFeed(val posts: List<CommunityPost>, val next: FeedCursor? = null)
|
||||||
|
@Serializable data class PostComment(val id: String, val body: String, val author: String, val mine: Boolean)
|
||||||
|
@Serializable data class CommentsCursor(val time: String, val id: String)
|
||||||
|
@Serializable data class CommentsPage(val comments: List<PostComment>, val next: CommentsCursor? = null)
|
||||||
|
@Serializable data class CommentInput(val body: String)
|
||||||
|
@Serializable data class PostRating(val stars: Int?)
|
||||||
|
@Serializable data class PublicProfile(val id: String, val name: String, val avatar: String, val publishedItems: Long)
|
||||||
|
@Serializable data class AccountProfile(val username: String, val nickname: String, val signature: String, val avatar: Avatar)
|
||||||
|
@Serializable data class ProfileInput(val nickname: String, val signature: String, val avatar: Avatar)
|
||||||
|
@Serializable data class AccountSummary(
|
||||||
|
val activeItems: Long, val pricedItems: Long, val archivedItems: Long,
|
||||||
|
val publishedItems: Long, val totalValueCents: String,
|
||||||
|
)
|
||||||
|
@Serializable enum class Avatar(val label: String, val symbol: String) {
|
||||||
|
PERSON("人物", "●"), CAT("猫", "🐈"), LEAF("叶子", "🍃"), MOON("月亮", "☾"), MOUNTAIN("山峰", "▲"), SPARK("星光", "✦"),
|
||||||
|
}
|
||||||
|
|
@ -12,8 +12,10 @@ import okhttp3.Call
|
||||||
import okhttp3.Callback
|
import okhttp3.Callback
|
||||||
import okhttp3.HttpUrl.Companion.toHttpUrl
|
import okhttp3.HttpUrl.Companion.toHttpUrl
|
||||||
import okhttp3.MediaType.Companion.toMediaType
|
import okhttp3.MediaType.Companion.toMediaType
|
||||||
|
import okhttp3.MultipartBody
|
||||||
import okhttp3.OkHttpClient
|
import okhttp3.OkHttpClient
|
||||||
import okhttp3.Request
|
import okhttp3.Request
|
||||||
|
import okhttp3.RequestBody
|
||||||
import okhttp3.RequestBody.Companion.toRequestBody
|
import okhttp3.RequestBody.Companion.toRequestBody
|
||||||
import okhttp3.Response
|
import okhttp3.Response
|
||||||
|
|
||||||
|
|
@ -48,7 +50,15 @@ data class Item(
|
||||||
data class Movement(val fromPath: String, val toPath: String, val movedAt: String)
|
data class Movement(val fromPath: String, val toPath: String, val movedAt: String)
|
||||||
|
|
||||||
@Serializable
|
@Serializable
|
||||||
data class ItemDetail(val item: Item, val moves: List<Movement> = emptyList())
|
data class ItemDetail(
|
||||||
|
val item: Item, val moves: List<Movement> = emptyList(),
|
||||||
|
val preference: ItemPreference = ItemPreference(), val relations: List<RelatedItem> = emptyList(),
|
||||||
|
)
|
||||||
|
|
||||||
|
@Serializable
|
||||||
|
data class Photo(val id: String)
|
||||||
|
|
||||||
|
enum class PhotoKind(val collection: String) { Item("items"), Location("locations") }
|
||||||
|
|
||||||
@Serializable
|
@Serializable
|
||||||
data class ItemInput(
|
data class ItemInput(
|
||||||
|
|
@ -98,6 +108,8 @@ class AtlasApi(origin: String = BuildConfig.ATLAS_API_ORIGIN) {
|
||||||
private val json = Json { ignoreUnknownKeys = true; encodeDefaults = true }
|
private val json = Json { ignoreUnknownKeys = true; encodeDefaults = true }
|
||||||
private val media = "application/json".toMediaType()
|
private val media = "application/json".toMediaType()
|
||||||
private val http = OkHttpClient.Builder().callTimeout(25, TimeUnit.SECONDS).build()
|
private val http = OkHttpClient.Builder().callTimeout(25, TimeUnit.SECONDS).build()
|
||||||
|
private val uploadHttp = http.newBuilder().readTimeout(25, TimeUnit.SECONDS).callTimeout(40, TimeUnit.SECONDS).build()
|
||||||
|
private val modelHttp = http.newBuilder().readTimeout(75, TimeUnit.SECONDS).callTimeout(80, TimeUnit.SECONDS).build()
|
||||||
private val sessionLock = Mutex()
|
private val sessionLock = Mutex()
|
||||||
private var session: Session? = null
|
private var session: Session? = null
|
||||||
|
|
||||||
|
|
@ -120,18 +132,59 @@ class AtlasApi(origin: String = BuildConfig.ATLAS_API_ORIGIN) {
|
||||||
suspend fun createSpace(name: String): Space =
|
suspend fun createSpace(name: String): Space =
|
||||||
json.decodeFromString(read(path("api", "households"), "POST", json.encodeToString(SpaceInput(name))))
|
json.decodeFromString(read(path("api", "households"), "POST", json.encodeToString(SpaceInput(name))))
|
||||||
|
|
||||||
|
suspend fun members(space: Space): List<SpaceMember> = json.decodeFromString(read(family(space, "members")))
|
||||||
|
|
||||||
|
suspend fun changeMemberRole(space: Space, member: SpaceMember, role: String): SpaceMember =
|
||||||
|
json.decodeFromString(read(family(space, "members", member.id, "role"), "PUT", json.encodeToString(ChangeRole(role))))
|
||||||
|
|
||||||
|
suspend fun removeMember(space: Space, member: SpaceMember) {
|
||||||
|
read(family(space, "members", member.id), "DELETE")
|
||||||
|
}
|
||||||
|
|
||||||
|
suspend fun sentInvitations(space: Space): List<SentInvite> =
|
||||||
|
json.decodeFromString(read(family(space, "direct-invitations")))
|
||||||
|
|
||||||
|
suspend fun invite(space: Space, request: InviteAccount) {
|
||||||
|
read(family(space, "direct-invitations"), "POST", json.encodeToString(request))
|
||||||
|
}
|
||||||
|
|
||||||
|
suspend fun cancelInvite(space: Space, invite: SentInvite) {
|
||||||
|
read(family(space, "direct-invitations", invite.id), "DELETE")
|
||||||
|
}
|
||||||
|
|
||||||
|
suspend fun receivedInvitations(): List<ReceivedInvite> =
|
||||||
|
json.decodeFromString(read(path("api", "households", "direct-invitations")))
|
||||||
|
|
||||||
|
suspend fun acceptInvite(invite: ReceivedInvite): Space =
|
||||||
|
json.decodeFromString(read(path("api", "households", "direct-invitations", invite.id, "accept"), "POST", "{}"))
|
||||||
|
|
||||||
|
suspend fun declineInvite(invite: ReceivedInvite) {
|
||||||
|
read(path("api", "households", "direct-invitations", invite.id), "DELETE")
|
||||||
|
}
|
||||||
|
|
||||||
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 createLocation(space: Space, name: String, parentId: String?): Place =
|
suspend fun createLocation(space: Space, name: String, parentId: String?): Place =
|
||||||
json.decodeFromString(read(family(space, "locations"), "POST", json.encodeToString(PlaceInput(name, parentId))))
|
json.decodeFromString(read(family(space, "locations"), "POST", json.encodeToString(PlaceInput(name, parentId))))
|
||||||
|
|
||||||
|
suspend fun loadOrder(space: Space, parentId: String?): LocationOrder {
|
||||||
|
val url = family(space, "locations", "order").newBuilder()
|
||||||
|
parentId?.let { url.addQueryParameter("parentId", it) }
|
||||||
|
return json.decodeFromString(read(url.build()))
|
||||||
|
}
|
||||||
|
|
||||||
|
suspend fun saveOrder(space: Space, input: OrderInput): LocationOrder =
|
||||||
|
json.decodeFromString(read(family(space, "locations", "order"), "PUT", json.encodeToString(input)))
|
||||||
|
|
||||||
suspend fun search(
|
suspend fun search(
|
||||||
space: Space, query: String, offset: Int = 0, locationId: String? = null, includeDescendants: Boolean = false,
|
space: Space, query: String, offset: Int = 0, locationId: String? = null, includeDescendants: Boolean = false,
|
||||||
|
favorites: Boolean = false,
|
||||||
): List<Item> {
|
): List<Item> {
|
||||||
val builder = family(space, "items").newBuilder()
|
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())
|
||||||
|
if (favorites) builder.addQueryParameter("favorites", "true")
|
||||||
if (locationId != null) {
|
if (locationId != null) {
|
||||||
builder.addQueryParameter("location", locationId)
|
builder.addQueryParameter("location", locationId)
|
||||||
if (includeDescendants) builder.addQueryParameter("includeDescendants", "true")
|
if (includeDescendants) builder.addQueryParameter("includeDescendants", "true")
|
||||||
|
|
@ -153,6 +206,134 @@ class AtlasApi(origin: String = BuildConfig.ATLAS_API_ORIGIN) {
|
||||||
json.decodeFromString(read(family(space, "items", item.id, "moves"), "POST",
|
json.decodeFromString(read(family(space, "items", item.id, "moves"), "POST",
|
||||||
json.encodeToString(MoveInput(position?.id, item.version))))
|
json.encodeToString(MoveInput(position?.id, item.version))))
|
||||||
|
|
||||||
|
suspend fun photos(space: Space, kind: PhotoKind, id: String): List<Photo> =
|
||||||
|
json.decodeFromString(read(family(space, kind.collection, id, "photos")))
|
||||||
|
|
||||||
|
suspend fun photo(space: Space, kind: PhotoKind, id: String, photo: Photo, thumbnail: Boolean): ByteArray {
|
||||||
|
val url = family(space, kind.collection, id, "photos", photo.id).newBuilder()
|
||||||
|
.addQueryParameter("thumbnail", thumbnail.toString()).build()
|
||||||
|
return authenticated { token ->
|
||||||
|
exchange(url, "GET", null, token, accept = "image/jpeg") { response ->
|
||||||
|
val source = response.body?.source() ?: throw IOException("Missing photo")
|
||||||
|
if (source.request(MAX_PHOTO_BYTES + 1L)) throw IOException("Photo exceeds size limit")
|
||||||
|
source.readByteArray()
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
suspend fun uploadPhoto(space: Space, kind: PhotoKind, id: String, jpeg: ByteArray, key: String): Photo {
|
||||||
|
require(jpeg.isNotEmpty() && jpeg.size <= MAX_PHOTO_BYTES)
|
||||||
|
val body = MultipartBody.Builder().setType(MultipartBody.FORM)
|
||||||
|
.addFormDataPart("image", "photo.jpg", jpeg.toRequestBody("image/jpeg".toMediaType()))
|
||||||
|
.build()
|
||||||
|
return authenticated { token ->
|
||||||
|
exchange(family(space, kind.collection, id, "photos"), "POST", body, token, key, client = uploadHttp) { response ->
|
||||||
|
json.decodeFromString<Photo>(response.body?.string().orEmpty())
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
suspend fun deletePhoto(space: Space, kind: PhotoKind, id: String, photo: Photo) {
|
||||||
|
read(family(space, kind.collection, id, "photos", photo.id), "DELETE")
|
||||||
|
}
|
||||||
|
|
||||||
|
suspend fun loadPlan(space: Space, parentId: String?): PlanSnapshot {
|
||||||
|
val url = family(space, "location-layout").newBuilder()
|
||||||
|
parentId?.let { url.addQueryParameter("parentId", it) }
|
||||||
|
return json.decodeFromString(read(url.build()))
|
||||||
|
}
|
||||||
|
|
||||||
|
suspend fun savePlan(space: Space, input: PlanSave): PlanSnapshot =
|
||||||
|
json.decodeFromString(read(family(space, "location-layout"), "PUT", json.encodeToString(input)))
|
||||||
|
|
||||||
|
suspend fun suggestPlan(space: Space, input: PlanPrompt): PlanSuggestions =
|
||||||
|
json.decodeFromString(readModel(family(space, "location-layout-drafts"), json.encodeToString(input)))
|
||||||
|
|
||||||
|
suspend fun providers(): List<ModelProvider> =
|
||||||
|
json.decodeFromString(read(path("api", "model-providers")))
|
||||||
|
|
||||||
|
suspend fun createDraft(space: Space, input: DraftInput): CaptureDraft =
|
||||||
|
json.decodeFromString(readModel(family(space, "drafts"), json.encodeToString(input)))
|
||||||
|
|
||||||
|
suspend fun confirmDraft(space: Space, draft: CaptureDraft, items: List<ItemInput>): CaptureOperation =
|
||||||
|
json.decodeFromString(read(family(space, "drafts", draft.id, "confirm"), "POST",
|
||||||
|
json.encodeToString(DraftConfirmation(draft.version, items))))
|
||||||
|
|
||||||
|
suspend fun operation(space: Space, current: CaptureOperation): CaptureOperation =
|
||||||
|
json.decodeFromString(read(family(space, "operations", current.id)))
|
||||||
|
|
||||||
|
suspend fun retryDraft(space: Space, current: CaptureOperation): CaptureOperation =
|
||||||
|
json.decodeFromString(read(family(space, "operations", current.id, "retry"), "POST", "{}"))
|
||||||
|
|
||||||
|
suspend fun feed(query: String, mine: Boolean, author: String?, cursor: FeedCursor?): CommunityFeed {
|
||||||
|
val url = posts().newBuilder().addQueryParameter("q", query).addQueryParameter("mine", mine.toString())
|
||||||
|
author?.let { url.addQueryParameter("authorId", it) }
|
||||||
|
cursor?.let {
|
||||||
|
url.addQueryParameter("rank", it.rank.toString()).addQueryParameter("time", it.time).addQueryParameter("before", it.id)
|
||||||
|
}
|
||||||
|
return json.decodeFromString(read(url.build()))
|
||||||
|
}
|
||||||
|
|
||||||
|
suspend fun post(id: String): CommunityPost = json.decodeFromString(read(posts(id)))
|
||||||
|
|
||||||
|
suspend fun publicProfile(id: String): PublicProfile =
|
||||||
|
json.decodeFromString(read(path("api", "community", "people", id)))
|
||||||
|
|
||||||
|
suspend fun comments(id: String, cursor: CommentsCursor? = null): CommentsPage {
|
||||||
|
val url = posts(id, "comments").newBuilder()
|
||||||
|
cursor?.let { url.addQueryParameter("time", it.time).addQueryParameter("before", it.id) }
|
||||||
|
return json.decodeFromString(read(url.build()))
|
||||||
|
}
|
||||||
|
|
||||||
|
suspend fun comment(id: String, text: String): PostComment =
|
||||||
|
json.decodeFromString(read(posts(id, "comments"), "POST", json.encodeToString(CommentInput(text))))
|
||||||
|
|
||||||
|
suspend fun deleteComment(id: String, comment: PostComment) {
|
||||||
|
read(posts(id, "comments", comment.id), "DELETE")
|
||||||
|
}
|
||||||
|
|
||||||
|
suspend fun rate(id: String, stars: Int?): CommunityPost =
|
||||||
|
json.decodeFromString(read(posts(id, "rating"), "PUT", json.encodeToString(PostRating(stars))))
|
||||||
|
|
||||||
|
suspend fun publication(space: Space, item: Item): Publication =
|
||||||
|
json.decodeFromString(read(family(space, "items", item.id, "publication")))
|
||||||
|
|
||||||
|
suspend fun publish(space: Space, item: Item, content: PublishInput): Publication =
|
||||||
|
json.decodeFromString(read(family(space, "items", item.id, "publication"), "PUT", json.encodeToString(content)))
|
||||||
|
|
||||||
|
suspend fun withdraw(space: Space, item: Item) {
|
||||||
|
read(family(space, "items", item.id, "publication"), "DELETE")
|
||||||
|
}
|
||||||
|
|
||||||
|
private fun posts(vararg parts: String) = path("api", "community", "posts", *parts)
|
||||||
|
|
||||||
|
suspend fun preference(space: Space, item: Item, value: ItemPreference): ItemPreference =
|
||||||
|
json.decodeFromString(read(family(space, "items", item.id, "preference"), "PUT", json.encodeToString(value)))
|
||||||
|
|
||||||
|
suspend fun profile(): AccountProfile = json.decodeFromString(read(path("api", "me", "profile")))
|
||||||
|
|
||||||
|
suspend fun saveProfile(input: ProfileInput): AccountProfile =
|
||||||
|
json.decodeFromString(read(path("api", "me", "profile"), "PUT", json.encodeToString(input)))
|
||||||
|
|
||||||
|
suspend fun summary(): AccountSummary = json.decodeFromString(read(path("api", "me", "inventory-summary")))
|
||||||
|
|
||||||
|
suspend fun archive(space: Space, item: Item) {
|
||||||
|
val url = family(space, "items", item.id).newBuilder().addQueryParameter("version", item.version.toString()).build()
|
||||||
|
read(url, "DELETE")
|
||||||
|
}
|
||||||
|
|
||||||
|
suspend fun link(space: Space, source: Item, relation: RelationInput) {
|
||||||
|
read(family(space, "items", source.id, "relations"), "PUT", json.encodeToString(relation))
|
||||||
|
}
|
||||||
|
|
||||||
|
suspend fun unlink(space: Space, source: Item, related: RelatedItem) {
|
||||||
|
read(family(space, "items", source.id, "relations", related.itemId), "DELETE")
|
||||||
|
}
|
||||||
|
|
||||||
|
private suspend fun readModel(url: okhttp3.HttpUrl, input: String): String = authenticated { token ->
|
||||||
|
exchange(url, "POST", input.toRequestBody(media), token, client = modelHttp) { it.body?.string().orEmpty() }
|
||||||
|
}
|
||||||
|
|
||||||
private fun family(space: Space, vararg segments: String) = path("api", "households", space.id, *segments)
|
private fun family(space: Space, vararg segments: String) = path("api", "households", space.id, *segments)
|
||||||
private fun path(vararg segments: String) = base.newBuilder().apply {
|
private fun path(vararg segments: String) = base.newBuilder().apply {
|
||||||
segments.forEach { addPathSegment(it) }
|
segments.forEach { addPathSegment(it) }
|
||||||
|
|
@ -178,13 +359,16 @@ class AtlasApi(origin: String = BuildConfig.ATLAS_API_ORIGIN) {
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
private suspend fun read(url: okhttp3.HttpUrl, method: String = "GET", body: String? = null, key: String? = null): String {
|
private suspend fun read(url: okhttp3.HttpUrl, method: String = "GET", body: String? = null, key: String? = null): String =
|
||||||
|
authenticated { token -> transport(url, method, body, token, key) }
|
||||||
|
|
||||||
|
private suspend fun <T> authenticated(request: suspend (String) -> T): T {
|
||||||
val first = access()
|
val first = access()
|
||||||
return try {
|
return try {
|
||||||
transport(url, method, body, first, key)
|
request(first)
|
||||||
} catch (failure: ApiError) {
|
} catch (failure: ApiError) {
|
||||||
if (failure.status != 401) throw failure
|
if (failure.status != 401) throw failure
|
||||||
transport(url, method, body, access(first), key)
|
request(access(first))
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|
@ -194,30 +378,47 @@ class AtlasApi(origin: String = BuildConfig.ATLAS_API_ORIGIN) {
|
||||||
payload: String?,
|
payload: String?,
|
||||||
token: String? = null,
|
token: String? = null,
|
||||||
key: String? = null,
|
key: String? = null,
|
||||||
): String = suspendCancellableCoroutine { continuation ->
|
): String = exchange(url, method, payload?.toRequestBody(media), token, key) { it.body?.string().orEmpty() }
|
||||||
val request = Request.Builder().url(url).method(method, payload?.toRequestBody(media))
|
|
||||||
.header("Accept", "application/json")
|
private suspend fun <T> exchange(
|
||||||
|
url: okhttp3.HttpUrl,
|
||||||
|
method: String,
|
||||||
|
body: RequestBody?,
|
||||||
|
token: String?,
|
||||||
|
key: String? = null,
|
||||||
|
accept: String = "application/json",
|
||||||
|
client: OkHttpClient = http,
|
||||||
|
decode: (Response) -> T,
|
||||||
|
): T = suspendCancellableCoroutine { continuation ->
|
||||||
|
val request = Request.Builder().url(url).method(method, body)
|
||||||
|
.header("Accept", accept)
|
||||||
.apply {
|
.apply {
|
||||||
token?.let { header("Authorization", "Bearer $it") }
|
token?.let { header("Authorization", "Bearer $it") }
|
||||||
key?.let { header("Idempotency-Key", it) }
|
key?.let { header("Idempotency-Key", it) }
|
||||||
}.build()
|
}.build()
|
||||||
val call = http.newCall(request)
|
val call = client.newCall(request)
|
||||||
continuation.invokeOnCancellation { call.cancel() }
|
continuation.invokeOnCancellation { call.cancel() }
|
||||||
call.enqueue(object : Callback {
|
call.enqueue(object : Callback {
|
||||||
override fun onFailure(call: Call, e: IOException) = continuation.resumeWith(Result.failure(e))
|
override fun onFailure(call: Call, e: IOException) {
|
||||||
|
if (BuildConfig.DEBUG && !call.isCanceled()) {
|
||||||
|
android.util.Log.d("AtlasApi", "$method failed: ${e.javaClass.simpleName}")
|
||||||
|
}
|
||||||
|
continuation.resumeWith(Result.failure(e))
|
||||||
|
}
|
||||||
|
|
||||||
override fun onResponse(call: Call, response: Response) {
|
override fun onResponse(call: Call, response: Response) {
|
||||||
continuation.resumeWith(runCatching {
|
continuation.resumeWith(runCatching {
|
||||||
response.use {
|
response.use {
|
||||||
val raw = it.body?.string().orEmpty()
|
|
||||||
if (!it.isSuccessful) {
|
if (!it.isSuccessful) {
|
||||||
val detail = runCatching { json.decodeFromString<Problem>(raw) }.getOrNull()
|
val detail = runCatching { json.decodeFromString<Problem>(it.body?.string().orEmpty()) }.getOrNull()
|
||||||
throw ApiError(it.code, detail?.detail ?: detail?.message ?: "请求失败(${it.code})")
|
throw ApiError(it.code, detail?.detail ?: detail?.message ?: "请求失败(${it.code})")
|
||||||
}
|
}
|
||||||
raw
|
decode(it)
|
||||||
}
|
}
|
||||||
})
|
})
|
||||||
}
|
}
|
||||||
})
|
})
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
internal const val MAX_PHOTO_BYTES = 5 * 1024 * 1024
|
||||||
|
|
|
||||||
|
|
@ -13,7 +13,7 @@ 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 }
|
enum class InventoryTab { Find, Locations, Community, Mine }
|
||||||
|
|
||||||
data class AtlasState(
|
data class AtlasState(
|
||||||
val screen: Screen = Screen.SignIn,
|
val screen: Screen = Screen.SignIn,
|
||||||
|
|
@ -29,6 +29,8 @@ data class AtlasState(
|
||||||
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,
|
||||||
|
val itemPreference: ItemPreference? = null,
|
||||||
|
val relatedItems: List<RelatedItem> = emptyList(),
|
||||||
val writeConflict: Boolean = false,
|
val writeConflict: Boolean = false,
|
||||||
val query: String = "",
|
val query: String = "",
|
||||||
val nextOffset: Int = 0,
|
val nextOffset: Int = 0,
|
||||||
|
|
@ -39,7 +41,7 @@ data class AtlasState(
|
||||||
)
|
)
|
||||||
|
|
||||||
class AtlasViewModel : ViewModel() {
|
class AtlasViewModel : ViewModel() {
|
||||||
private val api = AtlasApi()
|
internal val api = AtlasApi()
|
||||||
private val mutable = MutableStateFlow(AtlasState())
|
private val mutable = MutableStateFlow(AtlasState())
|
||||||
val state = mutable.asStateFlow()
|
val state = mutable.asStateFlow()
|
||||||
private var listJob: Job? = null
|
private var listJob: Job? = null
|
||||||
|
|
@ -65,18 +67,29 @@ class AtlasViewModel : ViewModel() {
|
||||||
|
|
||||||
fun createSpace(name: String) = action {
|
fun createSpace(name: String) = action {
|
||||||
val space = api.createSpace(name.trim())
|
val space = api.createSpace(name.trim())
|
||||||
mutable.update { it.copy(spaces = it.spaces + space) }
|
join(space)
|
||||||
|
}
|
||||||
|
|
||||||
|
fun join(space: Space) {
|
||||||
|
mutable.update { current ->
|
||||||
|
val updated = current.spaces.associateBy(Space::id) + (space.id to space)
|
||||||
|
current.copy(spaces = updated.values.toList())
|
||||||
|
}
|
||||||
switchSpace(space)
|
switchSpace(space)
|
||||||
}
|
}
|
||||||
|
|
||||||
private suspend fun fetchSpaces() {
|
private suspend fun fetchSpaces() {
|
||||||
val spaces = api.spaces()
|
val spaces = api.spaces()
|
||||||
mutable.update { it.copy(spaces = spaces) }
|
mutable.update { it.copy(spaces = spaces) }
|
||||||
spaces.firstOrNull()?.let(::switchSpace)
|
val active = mutable.value.space?.id
|
||||||
|
(spaces.firstOrNull { it.id == active } ?: spaces.firstOrNull())?.let(::switchSpace)
|
||||||
}
|
}
|
||||||
|
|
||||||
fun switchSpace(space: Space) {
|
fun switchSpace(space: Space) {
|
||||||
if (mutable.value.space?.id == space.id) return
|
if (mutable.value.space?.id == space.id) {
|
||||||
|
mutable.update { it.copy(space = space) }
|
||||||
|
return
|
||||||
|
}
|
||||||
listJob?.cancel()
|
listJob?.cancel()
|
||||||
placesJob?.cancel()
|
placesJob?.cancel()
|
||||||
detailJob?.cancel()
|
detailJob?.cancel()
|
||||||
|
|
@ -169,6 +182,7 @@ 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
|
||||||
|
if (prior.tab == InventoryTab.Community || prior.tab == InventoryTab.Mine) return
|
||||||
val location = prior.locationId.takeIf { prior.tab == InventoryTab.Locations }
|
val location = prior.locationId.takeIf { prior.tab == InventoryTab.Locations }
|
||||||
if (prior.tab == InventoryTab.Locations && location == null) return
|
if (prior.tab == InventoryTab.Locations && location == null) return
|
||||||
if (append && (prior.loading || !prior.hasMore)) return
|
if (append && (prior.loading || !prior.hasMore)) return
|
||||||
|
|
@ -205,13 +219,14 @@ class AtlasViewModel : ViewModel() {
|
||||||
detailJob?.cancel()
|
detailJob?.cancel()
|
||||||
mutable.update {
|
mutable.update {
|
||||||
it.copy(screen = Screen.Detail, selected = item, recentMoves = null, writeConflict = false,
|
it.copy(screen = Screen.Detail, selected = item, recentMoves = null, writeConflict = false,
|
||||||
loading = false, error = null)
|
itemPreference = null, relatedItems = emptyList(), loading = false, error = null)
|
||||||
}
|
}
|
||||||
detailJob = viewModelScope.launch {
|
detailJob = viewModelScope.launch {
|
||||||
try {
|
try {
|
||||||
val detail = api.detail(space, item.id)
|
val detail = api.detail(space, item.id)
|
||||||
if (mutable.value.selected?.id == item.id && mutable.value.space?.id == space.id) {
|
if (mutable.value.selected?.id == item.id && mutable.value.space?.id == space.id) {
|
||||||
mutable.update { it.copy(selected = detail.item, recentMoves = detail.moves) }
|
mutable.update { it.copy(selected = detail.item, recentMoves = detail.moves,
|
||||||
|
itemPreference = detail.preference, relatedItems = detail.relations) }
|
||||||
}
|
}
|
||||||
} catch (failure: Exception) {
|
} catch (failure: Exception) {
|
||||||
if (failure is CancellationException) throw failure
|
if (failure is CancellationException) throw failure
|
||||||
|
|
@ -308,6 +323,24 @@ class AtlasViewModel : ViewModel() {
|
||||||
refreshLocations()
|
refreshLocations()
|
||||||
}
|
}
|
||||||
|
|
||||||
|
fun archive(item: Item) {
|
||||||
|
val space = mutable.value.space?.takeIf(Space::writable) ?: return
|
||||||
|
action {
|
||||||
|
api.archive(space, item)
|
||||||
|
mutable.update { it.copy(screen = Screen.Inventory, selected = null, recentMoves = null,
|
||||||
|
itemPreference = null, relatedItems = emptyList()) }
|
||||||
|
search()
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
fun savePreference(item: Item, change: ItemPreference) {
|
||||||
|
val space = mutable.value.space ?: return
|
||||||
|
action {
|
||||||
|
val saved = api.preference(space, item, change)
|
||||||
|
if (mutable.value.selected?.id == item.id) mutable.update { it.copy(itemPreference = saved) }
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
fun move(position: Place?) {
|
fun move(position: Place?) {
|
||||||
val space = mutable.value.space?.takeIf { it.writable } ?: return
|
val space = mutable.value.space?.takeIf { it.writable } ?: return
|
||||||
val item = mutable.value.selected ?: return
|
val item = mutable.value.selected ?: return
|
||||||
|
|
@ -350,6 +383,11 @@ class AtlasViewModel : ViewModel() {
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
internal fun requestFailure(failure: Exception): String {
|
||||||
|
if (failure is ApiError && failure.status == 401) handle(failure)
|
||||||
|
return errorMessage(failure)
|
||||||
|
}
|
||||||
|
|
||||||
private fun action(block: suspend () -> Unit) {
|
private fun action(block: suspend () -> Unit) {
|
||||||
if (mutable.value.busy) return
|
if (mutable.value.busy) return
|
||||||
mutable.update { it.copy(busy = true, error = null) }
|
mutable.update { it.copy(busy = true, error = null) }
|
||||||
|
|
|
||||||
|
|
@ -0,0 +1,282 @@
|
||||||
|
package com.tutudog.itematlas
|
||||||
|
|
||||||
|
import androidx.compose.foundation.clickable
|
||||||
|
import androidx.compose.foundation.layout.Arrangement
|
||||||
|
import androidx.compose.foundation.layout.Column
|
||||||
|
import androidx.compose.foundation.layout.PaddingValues
|
||||||
|
import androidx.compose.foundation.layout.Row
|
||||||
|
import androidx.compose.foundation.layout.fillMaxSize
|
||||||
|
import androidx.compose.foundation.layout.fillMaxWidth
|
||||||
|
import androidx.compose.foundation.layout.padding
|
||||||
|
import androidx.compose.foundation.lazy.LazyColumn
|
||||||
|
import androidx.compose.foundation.lazy.items
|
||||||
|
import androidx.compose.foundation.rememberScrollState
|
||||||
|
import androidx.compose.foundation.verticalScroll
|
||||||
|
import androidx.compose.material3.AlertDialog
|
||||||
|
import androidx.compose.material3.Button
|
||||||
|
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.Surface
|
||||||
|
import androidx.compose.material3.Text
|
||||||
|
import androidx.compose.material3.TextButton
|
||||||
|
import androidx.compose.runtime.Composable
|
||||||
|
import androidx.compose.runtime.LaunchedEffect
|
||||||
|
import androidx.compose.runtime.getValue
|
||||||
|
import androidx.compose.runtime.mutableStateOf
|
||||||
|
import androidx.compose.runtime.remember
|
||||||
|
import androidx.compose.runtime.rememberCoroutineScope
|
||||||
|
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.Dialog
|
||||||
|
import androidx.compose.ui.window.DialogProperties
|
||||||
|
import java.util.Locale
|
||||||
|
import kotlinx.coroutines.CancellationException
|
||||||
|
import kotlinx.coroutines.delay
|
||||||
|
import kotlinx.coroutines.launch
|
||||||
|
|
||||||
|
@Composable
|
||||||
|
internal fun Community(model: AtlasViewModel) {
|
||||||
|
var query by remember { mutableStateOf("") }
|
||||||
|
var mine by remember { mutableStateOf(false) }
|
||||||
|
var author by remember { mutableStateOf<PublicProfile?>(null) }
|
||||||
|
var open by remember { mutableStateOf<CommunityPost?>(null) }
|
||||||
|
Column(verticalArrangement = Arrangement.spacedBy(8.dp)) {
|
||||||
|
val person = author
|
||||||
|
if (person != null) {
|
||||||
|
TextButton(onClick = { author = null; query = "" }) { Text("返回社区") }
|
||||||
|
Text("${person.name} · ${person.publishedItems} 条公开分享", style = MaterialTheme.typography.titleMedium)
|
||||||
|
}
|
||||||
|
OutlinedTextField(query, { query = it.take(120) }, Modifier.fillMaxWidth(),
|
||||||
|
label = { Text("搜索公开分享") }, singleLine = true)
|
||||||
|
if (person == null) FilterChip(mine, { mine = !mine }, { Text("我发布的") })
|
||||||
|
CommunityList(model, query.trim(), mine && person == null, person?.id) { open = it }
|
||||||
|
}
|
||||||
|
open?.let { selected ->
|
||||||
|
PostDetail(model, selected, close = { open = null }, showAuthor = { person ->
|
||||||
|
author = person
|
||||||
|
mine = false
|
||||||
|
query = ""
|
||||||
|
open = null
|
||||||
|
})
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
@Composable
|
||||||
|
private fun CommunityList(
|
||||||
|
model: AtlasViewModel, query: String, mine: Boolean, authorId: String?, viewPost: (CommunityPost) -> Unit,
|
||||||
|
) {
|
||||||
|
val scope = rememberCoroutineScope()
|
||||||
|
var page by remember(query, mine, authorId) { mutableStateOf<CommunityFeed?>(null) }
|
||||||
|
var error by remember(query, mine, authorId) { mutableStateOf<String?>(null) }
|
||||||
|
var busy by remember(query, mine, authorId) { mutableStateOf(false) }
|
||||||
|
var refresh by remember(query, mine, authorId) { mutableStateOf(0) }
|
||||||
|
|
||||||
|
suspend fun fetch(append: Boolean) {
|
||||||
|
if (busy) return
|
||||||
|
busy = true
|
||||||
|
error = null
|
||||||
|
try {
|
||||||
|
val next = model.api.feed(query, mine, authorId, if (append) page?.next else null)
|
||||||
|
page = if (append) next.copy(posts = (page?.posts.orEmpty() + next.posts).distinctBy(CommunityPost::id)) else next
|
||||||
|
} catch (failure: Exception) {
|
||||||
|
if (failure is CancellationException) throw failure
|
||||||
|
error = model.requestFailure(failure)
|
||||||
|
} finally { busy = false }
|
||||||
|
}
|
||||||
|
|
||||||
|
LaunchedEffect(query, mine, authorId, refresh) {
|
||||||
|
if (query.isNotEmpty()) delay(200)
|
||||||
|
fetch(false)
|
||||||
|
}
|
||||||
|
if (busy && page == null) LinearProgressIndicator(Modifier.fillMaxWidth())
|
||||||
|
error?.let {
|
||||||
|
Text(it, color = MaterialTheme.colorScheme.error)
|
||||||
|
TextButton(onClick = { refresh++ }) { Text("重试") }
|
||||||
|
}
|
||||||
|
page?.let { result ->
|
||||||
|
LazyColumn(contentPadding = PaddingValues(bottom = 16.dp)) {
|
||||||
|
if (result.posts.isEmpty()) item {
|
||||||
|
Text("没有匹配的分享。可以在物品详情发布自己的分享。", color = MaterialTheme.colorScheme.onSurfaceVariant)
|
||||||
|
}
|
||||||
|
items(result.posts, key = CommunityPost::id) { post ->
|
||||||
|
Column(Modifier.fillMaxWidth().clickable { viewPost(post) }.padding(vertical = 12.dp),
|
||||||
|
verticalArrangement = Arrangement.spacedBy(4.dp)) {
|
||||||
|
Text(post.title, style = MaterialTheme.typography.titleMedium)
|
||||||
|
Text(post.author + " · " + post.comments + " 条评论", style = MaterialTheme.typography.bodySmall)
|
||||||
|
}
|
||||||
|
HorizontalDivider()
|
||||||
|
}
|
||||||
|
if (result.next != null) item {
|
||||||
|
TextButton(enabled = !busy, onClick = { scope.launch { fetch(true) } }) { Text("加载更多") }
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
@Composable
|
||||||
|
private fun PostDetail(model: AtlasViewModel, initial: CommunityPost, close: () -> Unit, showAuthor: (PublicProfile) -> Unit) {
|
||||||
|
val scope = rememberCoroutineScope()
|
||||||
|
var post by remember(initial.id) { mutableStateOf<CommunityPost?>(null) }
|
||||||
|
var page by remember(initial.id) { mutableStateOf<CommentsPage?>(null) }
|
||||||
|
var comment by remember(initial.id) { mutableStateOf("") }
|
||||||
|
var error by remember(initial.id) { mutableStateOf<String?>(null) }
|
||||||
|
var busy by remember(initial.id) { mutableStateOf(true) }
|
||||||
|
var remove by remember { mutableStateOf<PostComment?>(null) }
|
||||||
|
|
||||||
|
suspend fun run(block: suspend () -> Unit) {
|
||||||
|
busy = true
|
||||||
|
error = null
|
||||||
|
try { block() }
|
||||||
|
catch (failure: Exception) {
|
||||||
|
if (failure is CancellationException) throw failure
|
||||||
|
if (failure is ApiError && failure.status == 404) { post = null; page = null }
|
||||||
|
error = model.requestFailure(failure)
|
||||||
|
} finally { busy = false }
|
||||||
|
}
|
||||||
|
|
||||||
|
suspend fun read() {
|
||||||
|
post = model.api.post(initial.id)
|
||||||
|
page = model.api.comments(initial.id)
|
||||||
|
}
|
||||||
|
|
||||||
|
LaunchedEffect(initial.id) { run { read() } }
|
||||||
|
Dialog(onDismissRequest = { if (!busy) close() }, properties = DialogProperties(usePlatformDefaultWidth = false)) {
|
||||||
|
Surface(Modifier.fillMaxSize()) {
|
||||||
|
Column(Modifier.padding(20.dp).verticalScroll(rememberScrollState()),
|
||||||
|
verticalArrangement = Arrangement.spacedBy(10.dp)) {
|
||||||
|
TextButton(enabled = !busy, onClick = close) { Text("返回社区") }
|
||||||
|
if (busy) LinearProgressIndicator(Modifier.fillMaxWidth())
|
||||||
|
error?.let {
|
||||||
|
Text(it, color = MaterialTheme.colorScheme.error)
|
||||||
|
TextButton(enabled = !busy, onClick = { scope.launch { run { read() } } }) { Text("重新加载") }
|
||||||
|
}
|
||||||
|
post?.let { current ->
|
||||||
|
Text(current.title, style = MaterialTheme.typography.headlineSmall)
|
||||||
|
TextButton(enabled = !busy, onClick = { scope.launch {
|
||||||
|
run { showAuthor(model.api.publicProfile(current.authorId)) }
|
||||||
|
} }) { Text(current.author) }
|
||||||
|
Text(current.body)
|
||||||
|
val score = current.average?.let { String.format(Locale.getDefault(), "%.1f", it) } ?: "—"
|
||||||
|
Text("评分 $score · ${current.votes} 人")
|
||||||
|
RatingPicker(current.myRating, !busy) { stars ->
|
||||||
|
scope.launch { run { post = model.api.rate(current.id, stars) } }
|
||||||
|
}
|
||||||
|
HorizontalDivider()
|
||||||
|
Text("评论", style = MaterialTheme.typography.titleLarge)
|
||||||
|
page?.comments.orEmpty().forEach { row ->
|
||||||
|
Column(verticalArrangement = Arrangement.spacedBy(3.dp)) {
|
||||||
|
Text(row.author, style = MaterialTheme.typography.labelLarge)
|
||||||
|
Text(row.body)
|
||||||
|
if (row.mine) TextButton(enabled = !busy, onClick = { remove = row }) { Text("删除评论") }
|
||||||
|
}
|
||||||
|
HorizontalDivider()
|
||||||
|
}
|
||||||
|
if (page?.next != null) TextButton(enabled = !busy, onClick = {
|
||||||
|
scope.launch {
|
||||||
|
run {
|
||||||
|
val next = model.api.comments(current.id, page?.next)
|
||||||
|
page = next.copy(comments = (page?.comments.orEmpty() + next.comments).distinctBy(PostComment::id))
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}) { Text("更多评论") }
|
||||||
|
OutlinedTextField(comment, { comment = it.take(500) }, Modifier.fillMaxWidth(), enabled = !busy,
|
||||||
|
label = { Text("评论内容") })
|
||||||
|
Button(enabled = !busy && comment.isNotBlank(), onClick = {
|
||||||
|
scope.launch {
|
||||||
|
run {
|
||||||
|
model.api.comment(current.id, comment.trim())
|
||||||
|
comment = ""
|
||||||
|
page = model.api.comments(current.id)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}) { Text("发表评论") }
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
remove?.let { row ->
|
||||||
|
AlertDialog(onDismissRequest = { remove = null }, title = { Text("删除这条评论?") },
|
||||||
|
confirmButton = { TextButton(onClick = {
|
||||||
|
remove = null
|
||||||
|
scope.launch { run { model.api.deleteComment(initial.id, row); page = model.api.comments(initial.id) } }
|
||||||
|
}) { Text("删除") } },
|
||||||
|
dismissButton = { TextButton(onClick = { remove = null }) { Text("取消") } })
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
@Composable
|
||||||
|
internal fun RatingPicker(value: Int?, enabled: Boolean, select: (Int?) -> Unit) {
|
||||||
|
Row(horizontalArrangement = Arrangement.spacedBy(3.dp), verticalAlignment = Alignment.CenterVertically) {
|
||||||
|
(1..5).forEach { count ->
|
||||||
|
FilterChip(count == value, { select(if (value == count) null else count) }, { Text("$count 星") }, enabled = enabled)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
@Composable
|
||||||
|
internal fun PublishEntry(model: AtlasViewModel, space: Space, item: Item) {
|
||||||
|
if (space.role != "OWNER") return
|
||||||
|
var open by remember(item.id) { mutableStateOf(false) }
|
||||||
|
OutlinedButton(onClick = { open = true }) { Text("社区分享") }
|
||||||
|
if (!open) return
|
||||||
|
val scope = rememberCoroutineScope()
|
||||||
|
var publication by remember { mutableStateOf<Publication?>(null) }
|
||||||
|
var title by remember { mutableStateOf("") }
|
||||||
|
var body by remember { mutableStateOf("") }
|
||||||
|
var busy by remember { mutableStateOf(true) }
|
||||||
|
var error by remember { mutableStateOf<String?>(null) }
|
||||||
|
var confirming by remember { mutableStateOf(false) }
|
||||||
|
|
||||||
|
suspend fun run(block: suspend () -> Unit) {
|
||||||
|
busy = true
|
||||||
|
error = null
|
||||||
|
try { block() }
|
||||||
|
catch (failure: Exception) {
|
||||||
|
if (failure is CancellationException) throw failure
|
||||||
|
error = model.requestFailure(failure)
|
||||||
|
} finally { busy = false }
|
||||||
|
}
|
||||||
|
|
||||||
|
suspend fun read() {
|
||||||
|
val current = model.api.publication(space, item)
|
||||||
|
publication = current
|
||||||
|
title = current.title
|
||||||
|
body = current.body
|
||||||
|
}
|
||||||
|
|
||||||
|
LaunchedEffect(Unit) { run { read() } }
|
||||||
|
AlertDialog(onDismissRequest = { if (!busy) open = false }, title = { Text("社区分享") },
|
||||||
|
text = {
|
||||||
|
Column(Modifier.verticalScroll(rememberScrollState()), verticalArrangement = Arrangement.spacedBy(8.dp)) {
|
||||||
|
Text("社区只会看到你填写的标题和正文。")
|
||||||
|
if (busy) LinearProgressIndicator(Modifier.fillMaxWidth())
|
||||||
|
error?.let { Text(it, color = MaterialTheme.colorScheme.error) }
|
||||||
|
if (publication != null) {
|
||||||
|
OutlinedTextField(title, { title = it.take(120) }, enabled = !busy, singleLine = true, label = { Text("公开标题") })
|
||||||
|
OutlinedTextField(body, { body = it.take(2000) }, enabled = !busy, minLines = 3, label = { Text("公开正文") })
|
||||||
|
if (publication?.postId != null) {
|
||||||
|
TextButton(enabled = !busy, onClick = { confirming = true }) { Text("撤回分享") }
|
||||||
|
}
|
||||||
|
} else if (!busy) TextButton(onClick = { scope.launch { run { read() } } }) { Text("重试") }
|
||||||
|
}
|
||||||
|
},
|
||||||
|
confirmButton = { TextButton(enabled = !busy && publication != null && title.isNotBlank() && body.isNotBlank(),
|
||||||
|
onClick = {
|
||||||
|
scope.launch {
|
||||||
|
run { model.api.publish(space, item, PublishInput(title.trim(), body.trim())); open = false }
|
||||||
|
}
|
||||||
|
}) { Text(if (publication?.postId == null) "发布" else "保存分享") } },
|
||||||
|
dismissButton = { TextButton(enabled = !busy, onClick = { open = false }) { Text("关闭") } })
|
||||||
|
if (confirming) AlertDialog(onDismissRequest = { confirming = false }, title = { Text("撤回这条分享?") },
|
||||||
|
confirmButton = { TextButton(onClick = {
|
||||||
|
confirming = false
|
||||||
|
scope.launch { run { model.api.withdraw(space, item); open = false } }
|
||||||
|
}) { Text("撤回") } },
|
||||||
|
dismissButton = { TextButton(onClick = { confirming = false }) { Text("取消") } })
|
||||||
|
}
|
||||||
|
|
@ -0,0 +1,183 @@
|
||||||
|
package com.tutudog.itematlas
|
||||||
|
|
||||||
|
import androidx.compose.foundation.layout.Arrangement
|
||||||
|
import androidx.compose.foundation.layout.Column
|
||||||
|
import androidx.compose.foundation.layout.Row
|
||||||
|
import androidx.compose.foundation.layout.fillMaxWidth
|
||||||
|
import androidx.compose.foundation.rememberScrollState
|
||||||
|
import androidx.compose.foundation.verticalScroll
|
||||||
|
import androidx.compose.material3.AlertDialog
|
||||||
|
import androidx.compose.material3.FilterChip
|
||||||
|
import androidx.compose.material3.HorizontalDivider
|
||||||
|
import androidx.compose.material3.LinearProgressIndicator
|
||||||
|
import androidx.compose.material3.MaterialTheme
|
||||||
|
import androidx.compose.material3.OutlinedTextField
|
||||||
|
import androidx.compose.material3.Text
|
||||||
|
import androidx.compose.material3.TextButton
|
||||||
|
import androidx.compose.runtime.Composable
|
||||||
|
import androidx.compose.runtime.LaunchedEffect
|
||||||
|
import androidx.compose.runtime.getValue
|
||||||
|
import androidx.compose.runtime.mutableStateOf
|
||||||
|
import androidx.compose.runtime.remember
|
||||||
|
import androidx.compose.runtime.rememberCoroutineScope
|
||||||
|
import androidx.compose.runtime.setValue
|
||||||
|
import androidx.compose.ui.Modifier
|
||||||
|
import androidx.compose.ui.unit.dp
|
||||||
|
import kotlinx.coroutines.CancellationException
|
||||||
|
import kotlinx.coroutines.launch
|
||||||
|
import kotlinx.serialization.Serializable
|
||||||
|
|
||||||
|
@Serializable data class SpaceMember(val id: String, val displayName: String, val role: String)
|
||||||
|
@Serializable data class ChangeRole(val role: String)
|
||||||
|
@Serializable data class InviteAccount(val username: String, val role: String)
|
||||||
|
@Serializable data class SentInvite(val id: String, val username: String, val role: String)
|
||||||
|
@Serializable data class ReceivedInvite(val id: String, val spaceName: String, val role: String)
|
||||||
|
|
||||||
|
private fun roleLabel(role: String) = when (role) {
|
||||||
|
"OWNER" -> "所有者"
|
||||||
|
"EDITOR" -> "可编辑"
|
||||||
|
else -> "仅查看"
|
||||||
|
}
|
||||||
|
|
||||||
|
@Composable
|
||||||
|
internal fun InvitationEntry(model: AtlasViewModel) {
|
||||||
|
var open by remember { mutableStateOf(false) }
|
||||||
|
TextButton(onClick = { open = true }) { Text("空间邀请") }
|
||||||
|
if (!open) return
|
||||||
|
val scope = rememberCoroutineScope()
|
||||||
|
var invites by remember { mutableStateOf<List<ReceivedInvite>?>(null) }
|
||||||
|
var busy by remember { mutableStateOf(false) }
|
||||||
|
var error by remember { mutableStateOf<String?>(null) }
|
||||||
|
|
||||||
|
suspend fun run(action: suspend () -> Unit) {
|
||||||
|
busy = true
|
||||||
|
error = null
|
||||||
|
try { action() }
|
||||||
|
catch (failure: Exception) {
|
||||||
|
if (failure is CancellationException) throw failure
|
||||||
|
error = model.requestFailure(failure)
|
||||||
|
} finally { busy = false }
|
||||||
|
}
|
||||||
|
|
||||||
|
LaunchedEffect(Unit) { run { invites = model.api.receivedInvitations() } }
|
||||||
|
AlertDialog(onDismissRequest = { if (!busy) open = false }, title = { Text("空间邀请") },
|
||||||
|
text = {
|
||||||
|
Column(Modifier.verticalScroll(rememberScrollState()), verticalArrangement = Arrangement.spacedBy(8.dp)) {
|
||||||
|
if (busy) LinearProgressIndicator(Modifier.fillMaxWidth())
|
||||||
|
error?.let { Text(it, color = MaterialTheme.colorScheme.error) }
|
||||||
|
if (invites?.isEmpty() == true) Text("暂时没有收到空间邀请。")
|
||||||
|
invites.orEmpty().forEach { invite ->
|
||||||
|
Text("${invite.spaceName} · ${roleLabel(invite.role)}", style = MaterialTheme.typography.titleMedium)
|
||||||
|
Row(horizontalArrangement = Arrangement.spacedBy(8.dp)) {
|
||||||
|
TextButton(enabled = !busy, onClick = { scope.launch {
|
||||||
|
run { model.join(model.api.acceptInvite(invite)); open = false }
|
||||||
|
} }) { Text("接受") }
|
||||||
|
TextButton(enabled = !busy, onClick = { scope.launch {
|
||||||
|
run {
|
||||||
|
model.api.declineInvite(invite)
|
||||||
|
invites = invites.orEmpty().filterNot { it.id == invite.id }
|
||||||
|
}
|
||||||
|
} }) { Text("拒绝") }
|
||||||
|
}
|
||||||
|
HorizontalDivider()
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}, confirmButton = { TextButton(enabled = !busy, onClick = { open = false }) { Text("关闭") } },
|
||||||
|
dismissButton = { TextButton(enabled = !busy, onClick = { scope.launch {
|
||||||
|
run { invites = model.api.receivedInvitations() }
|
||||||
|
} }) { Text("刷新") } })
|
||||||
|
}
|
||||||
|
|
||||||
|
@Composable
|
||||||
|
internal fun MembersEntry(model: AtlasViewModel, space: Space) {
|
||||||
|
var open by remember(space.id) { mutableStateOf(false) }
|
||||||
|
TextButton(onClick = { open = true }) { Text("空间成员") }
|
||||||
|
if (!open) return
|
||||||
|
val canManage = space.role == "OWNER"
|
||||||
|
val scope = rememberCoroutineScope()
|
||||||
|
var members by remember { mutableStateOf(emptyList<SpaceMember>()) }
|
||||||
|
var invited by remember { mutableStateOf(emptyList<SentInvite>()) }
|
||||||
|
var busy by remember { mutableStateOf(false) }
|
||||||
|
var error by remember { mutableStateOf<String?>(null) }
|
||||||
|
var username by remember { mutableStateOf("") }
|
||||||
|
var role by remember { mutableStateOf("VIEWER") }
|
||||||
|
var removing by remember { mutableStateOf<SpaceMember?>(null) }
|
||||||
|
|
||||||
|
suspend fun read() {
|
||||||
|
members = model.api.members(space)
|
||||||
|
if (canManage) invited = model.api.sentInvitations(space)
|
||||||
|
}
|
||||||
|
|
||||||
|
fun run(action: suspend () -> Unit) {
|
||||||
|
if (busy) return
|
||||||
|
busy = true
|
||||||
|
error = null
|
||||||
|
scope.launch {
|
||||||
|
try { action() }
|
||||||
|
catch (failure: Exception) {
|
||||||
|
if (failure is CancellationException) throw failure
|
||||||
|
error = model.requestFailure(failure)
|
||||||
|
} finally { busy = false }
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
LaunchedEffect(Unit) { run { read() } }
|
||||||
|
AlertDialog(onDismissRequest = { if (!busy) open = false }, title = { Text(space.name + " · 成员") },
|
||||||
|
text = {
|
||||||
|
Column(Modifier.verticalScroll(rememberScrollState()), verticalArrangement = Arrangement.spacedBy(8.dp)) {
|
||||||
|
if (busy) LinearProgressIndicator(Modifier.fillMaxWidth())
|
||||||
|
error?.let { Text(it, color = MaterialTheme.colorScheme.error) }
|
||||||
|
members.forEach { member ->
|
||||||
|
Text("${member.displayName} · ${roleLabel(member.role)}")
|
||||||
|
if (canManage && member.role != "OWNER") {
|
||||||
|
val next = if (member.role == "EDITOR") "VIEWER" else "EDITOR"
|
||||||
|
Row(horizontalArrangement = Arrangement.spacedBy(8.dp)) {
|
||||||
|
TextButton(enabled = !busy, onClick = { run {
|
||||||
|
val changed = model.api.changeMemberRole(space, member, next)
|
||||||
|
members = members.map { if (it.id == changed.id) changed else it }
|
||||||
|
} }) { Text("改为${roleLabel(next)}") }
|
||||||
|
TextButton(enabled = !busy, onClick = { removing = member }) { Text("移出空间") }
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if (canManage) {
|
||||||
|
HorizontalDivider()
|
||||||
|
Text("按账号邀请", style = MaterialTheme.typography.titleMedium)
|
||||||
|
OutlinedTextField(username, { username = it.take(64) }, enabled = !busy,
|
||||||
|
label = { Text("见物账号") }, singleLine = true)
|
||||||
|
Row(horizontalArrangement = Arrangement.spacedBy(8.dp)) {
|
||||||
|
listOf("VIEWER", "EDITOR").forEach { option ->
|
||||||
|
FilterChip(role == option, { role = option }, { Text(roleLabel(option)) }, enabled = !busy)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
TextButton(enabled = !busy && username.isNotBlank(), onClick = { run {
|
||||||
|
model.api.invite(space, InviteAccount(username.trim(), role))
|
||||||
|
username = ""
|
||||||
|
invited = model.api.sentInvitations(space)
|
||||||
|
} }) { Text("发送邀请") }
|
||||||
|
invited.forEach { invite ->
|
||||||
|
Row {
|
||||||
|
Text("${invite.username} · ${roleLabel(invite.role)}", Modifier.weight(1f))
|
||||||
|
TextButton(enabled = !busy, onClick = { run {
|
||||||
|
model.api.cancelInvite(space, invite)
|
||||||
|
invited = invited.filterNot { it.id == invite.id }
|
||||||
|
} }) { Text("撤回") }
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}, confirmButton = { TextButton(enabled = !busy, onClick = { open = false }) { Text("关闭") } },
|
||||||
|
dismissButton = { TextButton(enabled = !busy, onClick = { run { read() } }) { Text("刷新") } })
|
||||||
|
removing?.let { member ->
|
||||||
|
AlertDialog(onDismissRequest = { removing = null }, title = { Text("移出${member.displayName}?") },
|
||||||
|
text = { Text("对方将无法继续访问这个空间。") },
|
||||||
|
confirmButton = { TextButton(onClick = {
|
||||||
|
removing = null
|
||||||
|
run {
|
||||||
|
model.api.removeMember(space, member)
|
||||||
|
members = members.filterNot { it.id == member.id }
|
||||||
|
}
|
||||||
|
}) { Text("移出") } },
|
||||||
|
dismissButton = { TextButton(onClick = { removing = null }) { Text("取消") } })
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
@ -66,6 +66,7 @@ internal fun Inventory(state: AtlasState, model: AtlasViewModel, modifier: Modif
|
||||||
}
|
}
|
||||||
if (state.space == null) {
|
if (state.space == null) {
|
||||||
if (!state.busy) {
|
if (!state.busy) {
|
||||||
|
InvitationEntry(model)
|
||||||
Text(if (state.error == null) "暂无空间" else "空间暂时无法加载", style = MaterialTheme.typography.titleLarge)
|
Text(if (state.error == null) "暂无空间" else "空间暂时无法加载", style = MaterialTheme.typography.titleLarge)
|
||||||
if (state.error == null) {
|
if (state.error == null) {
|
||||||
Button(onClick = { showCreateSpace = true }) { Text("新建空间") }
|
Button(onClick = { showCreateSpace = true }) { Text("新建空间") }
|
||||||
|
|
@ -76,18 +77,18 @@ internal fun Inventory(state: AtlasState, model: AtlasViewModel, modifier: Modif
|
||||||
Status(state)
|
Status(state)
|
||||||
} else {
|
} else {
|
||||||
TabRow(selectedTabIndex = state.tab.ordinal) {
|
TabRow(selectedTabIndex = state.tab.ordinal) {
|
||||||
Tab(
|
val tabs = listOf(InventoryTab.Find to "找物", InventoryTab.Locations to "位置",
|
||||||
selected = state.tab == InventoryTab.Find, onClick = { model.switchTab(InventoryTab.Find) },
|
InventoryTab.Community to "社区", InventoryTab.Mine to "我的")
|
||||||
enabled = !state.busy, text = { Text("找物") },
|
tabs.forEach { (tab, label) ->
|
||||||
)
|
Tab(selected = state.tab == tab, onClick = { model.switchTab(tab) },
|
||||||
Tab(
|
enabled = !state.busy, text = { Text(label) })
|
||||||
selected = state.tab == InventoryTab.Locations, onClick = { model.switchTab(InventoryTab.Locations) },
|
}
|
||||||
enabled = !state.busy, text = { Text("位置") },
|
|
||||||
)
|
|
||||||
}
|
}
|
||||||
when (state.tab) {
|
when (state.tab) {
|
||||||
InventoryTab.Find -> FindItems(state, model)
|
InventoryTab.Find -> FindItems(state, model)
|
||||||
InventoryTab.Locations -> LocationItems(state, model)
|
InventoryTab.Locations -> LocationItems(state, model)
|
||||||
|
InventoryTab.Community -> Community(model)
|
||||||
|
InventoryTab.Mine -> Mine(model, checkNotNull(state.space))
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
@ -144,6 +145,12 @@ private fun LocationItems(state: AtlasState, model: AtlasViewModel) {
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
if (active != null) Text(active.path, style = MaterialTheme.typography.titleLarge)
|
if (active != null) Text(active.path, style = MaterialTheme.typography.titleLarge)
|
||||||
|
state.space?.let { space ->
|
||||||
|
Row(horizontalArrangement = Arrangement.spacedBy(8.dp)) {
|
||||||
|
if (active == null || active.parentId == null) LocationPlanEntry(model, space, active)
|
||||||
|
if (space.writable && children.size > 1) LocationOrderEntry(model, space, active, children)
|
||||||
|
}
|
||||||
|
}
|
||||||
PlaceStatus(state, model)
|
PlaceStatus(state, model)
|
||||||
if (!state.creatingLocation && active == null) Status(state)
|
if (!state.creatingLocation && active == null) Status(state)
|
||||||
key(state.space?.id, active?.id) {
|
key(state.space?.id, active?.id) {
|
||||||
|
|
@ -160,6 +167,9 @@ private fun LocationItems(state: AtlasState, model: AtlasViewModel) {
|
||||||
item { Text("还没有位置", color = MaterialTheme.colorScheme.onSurfaceVariant) }
|
item { Text("还没有位置", color = MaterialTheme.colorScheme.onSurfaceVariant) }
|
||||||
}
|
}
|
||||||
if (active != null) {
|
if (active != null) {
|
||||||
|
state.space?.let { space ->
|
||||||
|
item(key = "location-photos") { PhotosEntry(model, space, PhotoKind.Location, active.id) }
|
||||||
|
}
|
||||||
item {
|
item {
|
||||||
Row(Modifier.fillMaxWidth().padding(top = 16.dp), horizontalArrangement = Arrangement.SpaceBetween,
|
Row(Modifier.fillMaxWidth().padding(top = 16.dp), horizontalArrangement = Arrangement.SpaceBetween,
|
||||||
verticalAlignment = Alignment.CenterVertically) {
|
verticalAlignment = Alignment.CenterVertically) {
|
||||||
|
|
|
||||||
|
|
@ -0,0 +1,118 @@
|
||||||
|
package com.tutudog.itematlas
|
||||||
|
|
||||||
|
import androidx.compose.foundation.layout.Arrangement
|
||||||
|
import androidx.compose.foundation.layout.Column
|
||||||
|
import androidx.compose.foundation.layout.Row
|
||||||
|
import androidx.compose.foundation.layout.fillMaxWidth
|
||||||
|
import androidx.compose.foundation.layout.heightIn
|
||||||
|
import androidx.compose.foundation.rememberScrollState
|
||||||
|
import androidx.compose.foundation.verticalScroll
|
||||||
|
import androidx.compose.material3.AlertDialog
|
||||||
|
import androidx.compose.material3.FilterChip
|
||||||
|
import androidx.compose.material3.MaterialTheme
|
||||||
|
import androidx.compose.material3.OutlinedTextField
|
||||||
|
import androidx.compose.material3.Text
|
||||||
|
import androidx.compose.material3.TextButton
|
||||||
|
import androidx.compose.runtime.Composable
|
||||||
|
import androidx.compose.runtime.LaunchedEffect
|
||||||
|
import androidx.compose.runtime.getValue
|
||||||
|
import androidx.compose.runtime.mutableStateOf
|
||||||
|
import androidx.compose.runtime.remember
|
||||||
|
import androidx.compose.runtime.rememberCoroutineScope
|
||||||
|
import androidx.compose.runtime.setValue
|
||||||
|
import androidx.compose.ui.Modifier
|
||||||
|
import androidx.compose.ui.unit.dp
|
||||||
|
import kotlinx.coroutines.CancellationException
|
||||||
|
import kotlinx.coroutines.delay
|
||||||
|
import kotlinx.coroutines.launch
|
||||||
|
|
||||||
|
@Composable
|
||||||
|
internal fun ItemConnections(model: AtlasViewModel, space: Space, item: Item, related: List<RelatedItem>) {
|
||||||
|
val scope = rememberCoroutineScope()
|
||||||
|
var editing by remember(item.id) { mutableStateOf(false) }
|
||||||
|
var removing by remember(item.id) { mutableStateOf<RelatedItem?>(null) }
|
||||||
|
var error by remember(item.id) { mutableStateOf<String?>(null) }
|
||||||
|
var working by remember(item.id) { mutableStateOf(false) }
|
||||||
|
fun write(operation: suspend () -> Unit) {
|
||||||
|
if (working) return
|
||||||
|
working = true
|
||||||
|
error = null
|
||||||
|
scope.launch {
|
||||||
|
try { operation(); editing = false; model.open(item) }
|
||||||
|
catch (failure: Exception) {
|
||||||
|
if (failure is CancellationException) throw failure
|
||||||
|
error = model.requestFailure(failure)
|
||||||
|
} finally { working = false }
|
||||||
|
}
|
||||||
|
}
|
||||||
|
Text("关联物品", style = MaterialTheme.typography.titleMedium)
|
||||||
|
if (!editing) error?.let { Text(it, color = MaterialTheme.colorScheme.error) }
|
||||||
|
related.forEach { row ->
|
||||||
|
Row(Modifier.fillMaxWidth(), horizontalArrangement = Arrangement.SpaceBetween) {
|
||||||
|
Column(Modifier.weight(1f)) {
|
||||||
|
Text("${row.name} · ${row.kind.label}")
|
||||||
|
Text(row.locationPath.ifBlank { "未设置位置" }, style = MaterialTheme.typography.bodySmall)
|
||||||
|
}
|
||||||
|
if (space.writable) TextButton(enabled = !working, onClick = { removing = row }) { Text("移除") }
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if (space.writable) TextButton(enabled = !working, onClick = { error = null; editing = true }) { Text("添加关联") }
|
||||||
|
if (editing) LinkPicker(model, space, item, related, working, error, close = { editing = false }) { input ->
|
||||||
|
write { model.api.link(space, item, input) }
|
||||||
|
}
|
||||||
|
removing?.let { relation ->
|
||||||
|
AlertDialog(onDismissRequest = { removing = null }, title = { Text("移除与${relation.name}的关联?") },
|
||||||
|
confirmButton = { TextButton(onClick = {
|
||||||
|
removing = null
|
||||||
|
write { model.api.unlink(space, item, relation) }
|
||||||
|
}) { Text("移除") } },
|
||||||
|
dismissButton = { TextButton(onClick = { removing = null }) { Text("取消") } })
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
@Composable
|
||||||
|
private fun LinkPicker(
|
||||||
|
model: AtlasViewModel, space: Space, item: Item, linked: List<RelatedItem>, busy: Boolean,
|
||||||
|
writeError: String?, close: () -> Unit, connect: (RelationInput) -> Unit,
|
||||||
|
) {
|
||||||
|
var query by remember { mutableStateOf("") }
|
||||||
|
var found by remember { mutableStateOf(emptyList<Item>()) }
|
||||||
|
var selected by remember { mutableStateOf<Item?>(null) }
|
||||||
|
var type by remember { mutableStateOf(RelationKind.ACCESSORY) }
|
||||||
|
var error by remember { mutableStateOf<String?>(null) }
|
||||||
|
LaunchedEffect(query) {
|
||||||
|
error = null
|
||||||
|
if (query.isBlank()) { found = emptyList(); return@LaunchedEffect }
|
||||||
|
delay(200)
|
||||||
|
try {
|
||||||
|
found = model.api.search(space, query).filter { result ->
|
||||||
|
result.id != item.id && linked.none { existing -> existing.itemId == result.id }
|
||||||
|
}
|
||||||
|
} catch (failure: Exception) {
|
||||||
|
if (failure is CancellationException) throw failure
|
||||||
|
error = model.requestFailure(failure)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
AlertDialog(onDismissRequest = { if (!busy) close() }, title = { Text("添加关联") },
|
||||||
|
text = {
|
||||||
|
Column(verticalArrangement = Arrangement.spacedBy(8.dp)) {
|
||||||
|
OutlinedTextField(query, { query = it.take(150); selected = null; found = emptyList() },
|
||||||
|
enabled = !busy, singleLine = true, label = { Text("找同一空间的物品") })
|
||||||
|
Column(Modifier.heightIn(max = 180.dp).verticalScroll(rememberScrollState())) {
|
||||||
|
found.forEach { result ->
|
||||||
|
TextButton(enabled = !busy, onClick = { selected = result }) {
|
||||||
|
Text(if (selected?.id == result.id) "✓ ${result.name}" else result.name)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
Row(horizontalArrangement = Arrangement.spacedBy(5.dp)) {
|
||||||
|
RelationKind.entries.forEach { choice ->
|
||||||
|
FilterChip(type == choice, { type = choice }, { Text(choice.label) }, enabled = !busy)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
(writeError ?: error)?.let { Text(it, color = MaterialTheme.colorScheme.error) }
|
||||||
|
}
|
||||||
|
}, confirmButton = { TextButton(enabled = !busy && selected != null,
|
||||||
|
onClick = { selected?.let { connect(RelationInput(it.id, type)) } }) { Text("保存关联") } },
|
||||||
|
dismissButton = { TextButton(enabled = !busy, onClick = close) { Text("取消") } })
|
||||||
|
}
|
||||||
|
|
@ -0,0 +1,438 @@
|
||||||
|
package com.tutudog.itematlas
|
||||||
|
|
||||||
|
import android.content.ContentResolver
|
||||||
|
import android.content.Context
|
||||||
|
import android.graphics.Bitmap
|
||||||
|
import android.graphics.BitmapFactory
|
||||||
|
import android.graphics.Matrix
|
||||||
|
import android.media.ExifInterface
|
||||||
|
import android.net.Uri
|
||||||
|
import androidx.activity.compose.rememberLauncherForActivityResult
|
||||||
|
import androidx.activity.result.PickVisualMediaRequest
|
||||||
|
import androidx.activity.result.contract.ActivityResultContracts
|
||||||
|
import androidx.compose.foundation.Canvas
|
||||||
|
import androidx.compose.foundation.Image
|
||||||
|
import androidx.compose.foundation.clickable
|
||||||
|
import androidx.compose.foundation.gestures.detectDragGestures
|
||||||
|
import androidx.compose.foundation.layout.Arrangement
|
||||||
|
import androidx.compose.foundation.layout.Box
|
||||||
|
import androidx.compose.foundation.layout.Column
|
||||||
|
import androidx.compose.foundation.layout.Row
|
||||||
|
import androidx.compose.foundation.layout.aspectRatio
|
||||||
|
import androidx.compose.foundation.layout.fillMaxWidth
|
||||||
|
import androidx.compose.foundation.layout.padding
|
||||||
|
import androidx.compose.foundation.layout.size
|
||||||
|
import androidx.compose.foundation.lazy.LazyRow
|
||||||
|
import androidx.compose.foundation.lazy.items
|
||||||
|
import androidx.compose.material3.AlertDialog
|
||||||
|
import androidx.compose.material3.Button
|
||||||
|
import androidx.compose.material3.CircularProgressIndicator
|
||||||
|
import androidx.compose.material3.LinearProgressIndicator
|
||||||
|
import androidx.compose.material3.MaterialTheme
|
||||||
|
import androidx.compose.material3.OutlinedButton
|
||||||
|
import androidx.compose.material3.Slider
|
||||||
|
import androidx.compose.material3.Surface
|
||||||
|
import androidx.compose.material3.Text
|
||||||
|
import androidx.compose.material3.TextButton
|
||||||
|
import androidx.compose.runtime.Composable
|
||||||
|
import androidx.compose.runtime.LaunchedEffect
|
||||||
|
import androidx.compose.runtime.getValue
|
||||||
|
import androidx.compose.runtime.key
|
||||||
|
import androidx.compose.runtime.mutableStateOf
|
||||||
|
import androidx.compose.runtime.remember
|
||||||
|
import androidx.compose.runtime.rememberCoroutineScope
|
||||||
|
import androidx.compose.runtime.rememberUpdatedState
|
||||||
|
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.geometry.Offset
|
||||||
|
import androidx.compose.ui.geometry.Size
|
||||||
|
import androidx.compose.ui.graphics.Color
|
||||||
|
import androidx.compose.ui.graphics.asImageBitmap
|
||||||
|
import androidx.compose.ui.graphics.drawscope.Stroke
|
||||||
|
import androidx.compose.ui.input.pointer.pointerInput
|
||||||
|
import androidx.compose.ui.layout.ContentScale
|
||||||
|
import androidx.compose.ui.platform.LocalContext
|
||||||
|
import androidx.compose.ui.unit.IntOffset
|
||||||
|
import androidx.compose.ui.unit.IntSize
|
||||||
|
import androidx.compose.ui.unit.dp
|
||||||
|
import androidx.compose.ui.window.Dialog
|
||||||
|
import androidx.compose.ui.window.DialogProperties
|
||||||
|
import androidx.core.content.FileProvider
|
||||||
|
import java.io.ByteArrayOutputStream
|
||||||
|
import java.io.File
|
||||||
|
import java.io.IOException
|
||||||
|
import java.util.UUID
|
||||||
|
import kotlin.math.min
|
||||||
|
import kotlin.math.roundToInt
|
||||||
|
import kotlinx.coroutines.CancellationException
|
||||||
|
import kotlinx.coroutines.Dispatchers
|
||||||
|
import kotlinx.coroutines.launch
|
||||||
|
import kotlinx.coroutines.withContext
|
||||||
|
|
||||||
|
private const val MAX_SOURCE_BYTES = 30L * 1024 * 1024
|
||||||
|
private const val MAX_PHOTOS = 6
|
||||||
|
private const val CROP_OUTPUT_EDGE = 1440
|
||||||
|
|
||||||
|
@Composable
|
||||||
|
internal fun PhotosEntry(model: AtlasViewModel, space: Space, kind: PhotoKind, id: String) {
|
||||||
|
key(space.id, kind, id) {
|
||||||
|
var open by rememberSaveable { mutableStateOf(false) }
|
||||||
|
val title = if (kind == PhotoKind.Item) "物品照片" else "位置照片"
|
||||||
|
OutlinedButton(onClick = { open = true }) { Text(title) }
|
||||||
|
if (open) PhotoGallery(model, space, kind, id, title) { open = false }
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
@Composable
|
||||||
|
private fun PhotoGallery(
|
||||||
|
model: AtlasViewModel,
|
||||||
|
space: Space,
|
||||||
|
kind: PhotoKind,
|
||||||
|
id: String,
|
||||||
|
title: String,
|
||||||
|
close: () -> Unit,
|
||||||
|
) {
|
||||||
|
val context = LocalContext.current
|
||||||
|
val scope = rememberCoroutineScope()
|
||||||
|
var photos by remember { mutableStateOf<List<Photo>?>(null) }
|
||||||
|
var error by remember { mutableStateOf<String?>(null) }
|
||||||
|
var loading by remember { mutableStateOf(true) }
|
||||||
|
var busy by remember { mutableStateOf(false) }
|
||||||
|
var source by remember { mutableStateOf<Bitmap?>(null) }
|
||||||
|
var selected by remember { mutableStateOf<Photo?>(null) }
|
||||||
|
var capturedPath by rememberSaveable { mutableStateOf<String?>(null) }
|
||||||
|
var confirmDelete by remember { mutableStateOf(false) }
|
||||||
|
var requestKey by remember { mutableStateOf(UUID.randomUUID().toString()) }
|
||||||
|
var lastCrop by remember { mutableStateOf<Crop?>(null) }
|
||||||
|
|
||||||
|
suspend fun refresh() {
|
||||||
|
loading = true
|
||||||
|
error = null
|
||||||
|
try { photos = model.api.photos(space, kind, id) }
|
||||||
|
catch (failure: Exception) {
|
||||||
|
if (failure is CancellationException) throw failure
|
||||||
|
error = model.requestFailure(failure)
|
||||||
|
} finally { loading = false }
|
||||||
|
}
|
||||||
|
|
||||||
|
fun loadSource(uri: Uri, captured: File? = null) {
|
||||||
|
busy = true
|
||||||
|
error = null
|
||||||
|
scope.launch {
|
||||||
|
try {
|
||||||
|
source = withContext(Dispatchers.IO) { importImage(context, uri) }
|
||||||
|
requestKey = UUID.randomUUID().toString()
|
||||||
|
lastCrop = null
|
||||||
|
} catch (failure: Exception) {
|
||||||
|
if (failure is CancellationException) throw failure
|
||||||
|
error = if (failure is PhotoInputError) failure.message else "无法读取这张照片。"
|
||||||
|
} finally {
|
||||||
|
captured?.delete()
|
||||||
|
busy = false
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
val gallery = rememberLauncherForActivityResult(ActivityResultContracts.PickVisualMedia()) { uri ->
|
||||||
|
uri?.let { loadSource(it) }
|
||||||
|
}
|
||||||
|
val camera = rememberLauncherForActivityResult(ActivityResultContracts.TakePicture()) { taken ->
|
||||||
|
val file = capturedPath?.let(::File)
|
||||||
|
capturedPath = null
|
||||||
|
if (file != null) {
|
||||||
|
if (taken) loadSource(Uri.fromFile(file), file) else file.delete()
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
LaunchedEffect(Unit) { refresh() }
|
||||||
|
Dialog(onDismissRequest = { if (!busy && capturedPath == null) close() },
|
||||||
|
properties = DialogProperties(usePlatformDefaultWidth = false)) {
|
||||||
|
Surface(Modifier.fillMaxWidth().padding(16.dp), shape = MaterialTheme.shapes.large) {
|
||||||
|
Column(Modifier.padding(20.dp), verticalArrangement = Arrangement.spacedBy(12.dp)) {
|
||||||
|
Text(title, style = MaterialTheme.typography.titleLarge)
|
||||||
|
if (loading || busy) LinearProgressIndicator(Modifier.fillMaxWidth())
|
||||||
|
error?.let { Text(it, color = MaterialTheme.colorScheme.error) }
|
||||||
|
val visible = photos
|
||||||
|
if (visible?.isEmpty() == true) Text("还没有照片。")
|
||||||
|
if (visible != null && visible.isNotEmpty()) {
|
||||||
|
LazyRow(horizontalArrangement = Arrangement.spacedBy(8.dp)) {
|
||||||
|
items(visible, key = Photo::id) { photo ->
|
||||||
|
PhotoPreview(model, space, kind, id, photo, true,
|
||||||
|
Modifier.size(82.dp).clickable(enabled = !busy, onClickLabel = "打开原图") {
|
||||||
|
selected = photo
|
||||||
|
})
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if (visible == null && !loading) {
|
||||||
|
TextButton(onClick = { scope.launch { refresh() } }) { Text("重试") }
|
||||||
|
}
|
||||||
|
if (space.writable && visible != null) {
|
||||||
|
val canAdd = visible.size < MAX_PHOTOS && !busy && !loading && capturedPath == null
|
||||||
|
if (visible.size >= MAX_PHOTOS) Text("已达到六张照片的上限。")
|
||||||
|
Row(horizontalArrangement = Arrangement.spacedBy(8.dp)) {
|
||||||
|
Button(enabled = canAdd, onClick = {
|
||||||
|
try {
|
||||||
|
val folder = File(context.cacheDir, "photo-captures")
|
||||||
|
check(folder.isDirectory || folder.mkdirs())
|
||||||
|
val cutoff = System.currentTimeMillis() - 24 * 60 * 60 * 1000L
|
||||||
|
folder.listFiles()?.filter { it.lastModified() < cutoff }?.forEach { it.delete() }
|
||||||
|
val file = File.createTempFile("capture-", ".jpg", folder)
|
||||||
|
capturedPath = file.path
|
||||||
|
val uri = FileProvider.getUriForFile(context, context.packageName + ".photos", file)
|
||||||
|
camera.launch(uri)
|
||||||
|
} catch (_: Exception) {
|
||||||
|
capturedPath?.let { File(it).delete() }
|
||||||
|
capturedPath = null
|
||||||
|
error = "无法打开相机,可以从相册选图。"
|
||||||
|
}
|
||||||
|
}) { Text("拍照") }
|
||||||
|
OutlinedButton(enabled = canAdd, onClick = {
|
||||||
|
gallery.launch(PickVisualMediaRequest(ActivityResultContracts.PickVisualMedia.ImageOnly))
|
||||||
|
}) { Text("选照片") }
|
||||||
|
}
|
||||||
|
}
|
||||||
|
TextButton(enabled = !busy && capturedPath == null, onClick = close) { Text("完成") }
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
source?.let { bitmap ->
|
||||||
|
CropDialog(bitmap, busy, error, dismiss = { source = null; error = null }) { crop ->
|
||||||
|
busy = true
|
||||||
|
error = null
|
||||||
|
if (lastCrop != crop) {
|
||||||
|
requestKey = UUID.randomUUID().toString()
|
||||||
|
lastCrop = crop
|
||||||
|
}
|
||||||
|
val key = requestKey
|
||||||
|
scope.launch {
|
||||||
|
try {
|
||||||
|
val jpeg = withContext(Dispatchers.IO) { cropJpeg(bitmap, crop) }
|
||||||
|
val created = model.api.uploadPhoto(space, kind, id, jpeg, key)
|
||||||
|
photos = (photos.orEmpty() + created).distinctBy(Photo::id)
|
||||||
|
source = null
|
||||||
|
} catch (failure: Exception) {
|
||||||
|
if (failure is CancellationException) throw failure
|
||||||
|
error = if (failure is PhotoInputError) failure.message else model.requestFailure(failure)
|
||||||
|
} finally { busy = false }
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
selected?.let { photo ->
|
||||||
|
Dialog(onDismissRequest = { if (!busy) selected = null },
|
||||||
|
properties = DialogProperties(usePlatformDefaultWidth = false)) {
|
||||||
|
Surface(Modifier.fillMaxWidth().padding(16.dp), shape = MaterialTheme.shapes.large) {
|
||||||
|
Column(Modifier.padding(16.dp), verticalArrangement = Arrangement.spacedBy(8.dp)) {
|
||||||
|
Text("原图", style = MaterialTheme.typography.titleLarge)
|
||||||
|
PhotoPreview(model, space, kind, id, photo, false,
|
||||||
|
Modifier.fillMaxWidth().aspectRatio(1f))
|
||||||
|
error?.let { Text(it, color = MaterialTheme.colorScheme.error) }
|
||||||
|
Row(horizontalArrangement = Arrangement.spacedBy(8.dp)) {
|
||||||
|
if (space.writable) {
|
||||||
|
TextButton(enabled = !busy, onClick = { confirmDelete = true }) { Text("删除照片") }
|
||||||
|
}
|
||||||
|
TextButton(enabled = !busy, onClick = { selected = null; error = null }) { Text("关闭") }
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if (confirmDelete) AlertDialog(
|
||||||
|
onDismissRequest = { confirmDelete = false },
|
||||||
|
title = { Text("删除这张照片?") },
|
||||||
|
text = { Text("原图和缩略图都会删除。") },
|
||||||
|
confirmButton = {
|
||||||
|
TextButton(onClick = {
|
||||||
|
confirmDelete = false
|
||||||
|
busy = true
|
||||||
|
error = null
|
||||||
|
scope.launch {
|
||||||
|
try {
|
||||||
|
model.api.deletePhoto(space, kind, id, photo)
|
||||||
|
photos = photos.orEmpty().filterNot { it.id == photo.id }
|
||||||
|
selected = null
|
||||||
|
} catch (failure: Exception) {
|
||||||
|
if (failure is CancellationException) throw failure
|
||||||
|
error = model.requestFailure(failure)
|
||||||
|
if (failure is ApiError && failure.status == 404) {
|
||||||
|
photos = photos.orEmpty().filterNot { it.id == photo.id }
|
||||||
|
selected = null
|
||||||
|
}
|
||||||
|
} finally { busy = false }
|
||||||
|
}
|
||||||
|
}) { Text("确认删除") }
|
||||||
|
},
|
||||||
|
dismissButton = { TextButton(onClick = { confirmDelete = false }) { Text("取消") } },
|
||||||
|
)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
@Composable
|
||||||
|
private fun PhotoPreview(
|
||||||
|
model: AtlasViewModel, space: Space, kind: PhotoKind, id: String, photo: Photo,
|
||||||
|
thumbnail: Boolean, modifier: Modifier,
|
||||||
|
) {
|
||||||
|
var bitmap by remember(photo.id) { mutableStateOf<Bitmap?>(null) }
|
||||||
|
var error by remember(photo.id) { mutableStateOf(false) }
|
||||||
|
var attempt by remember { mutableStateOf(0) }
|
||||||
|
LaunchedEffect(photo.id, thumbnail, attempt) {
|
||||||
|
error = false
|
||||||
|
try {
|
||||||
|
val bytes = model.api.photo(space, kind, id, photo, thumbnail)
|
||||||
|
bitmap = withContext(Dispatchers.IO) {
|
||||||
|
BitmapFactory.decodeByteArray(bytes, 0, bytes.size) ?: throw IOException("Invalid photo")
|
||||||
|
}
|
||||||
|
} catch (failure: Exception) {
|
||||||
|
if (failure is CancellationException) throw failure
|
||||||
|
model.requestFailure(failure)
|
||||||
|
error = true
|
||||||
|
}
|
||||||
|
}
|
||||||
|
Surface(modifier, shape = MaterialTheme.shapes.medium, color = MaterialTheme.colorScheme.surfaceVariant) {
|
||||||
|
Box(contentAlignment = Alignment.Center) {
|
||||||
|
val picture = bitmap
|
||||||
|
when {
|
||||||
|
picture != null -> Image(picture.asImageBitmap(), if (thumbnail) "照片缩略图" else "照片原图",
|
||||||
|
contentScale = if (thumbnail) ContentScale.Crop else ContentScale.Fit)
|
||||||
|
error -> TextButton(onClick = { attempt++ }) { Text("重试") }
|
||||||
|
else -> CircularProgressIndicator(Modifier.size(20.dp))
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
private class PhotoInputError(message: String) : IOException(message)
|
||||||
|
|
||||||
|
private fun importImage(context: Context, uri: Uri): Bitmap {
|
||||||
|
val file = File.createTempFile("import-", ".img", context.cacheDir)
|
||||||
|
try {
|
||||||
|
copyPhoto(context.contentResolver, uri, file)
|
||||||
|
val bounds = BitmapFactory.Options().apply { inJustDecodeBounds = true }
|
||||||
|
BitmapFactory.decodeFile(file.path, bounds)
|
||||||
|
if (min(bounds.outWidth, bounds.outHeight) < 64) {
|
||||||
|
throw PhotoInputError("照片无法识别,或短边小于 64 像素。")
|
||||||
|
}
|
||||||
|
var sample = 1
|
||||||
|
while (maxOf(bounds.outWidth, bounds.outHeight) / sample > 2048) sample *= 2
|
||||||
|
val decoded = BitmapFactory.decodeFile(file.path, BitmapFactory.Options().apply { inSampleSize = sample })
|
||||||
|
?: throw PhotoInputError("无法读取这个图片格式。")
|
||||||
|
val orientation = runCatching {
|
||||||
|
ExifInterface(file.path).getAttributeInt(ExifInterface.TAG_ORIENTATION, ExifInterface.ORIENTATION_NORMAL)
|
||||||
|
}.getOrDefault(ExifInterface.ORIENTATION_NORMAL)
|
||||||
|
val transform = Matrix()
|
||||||
|
when (orientation) {
|
||||||
|
ExifInterface.ORIENTATION_FLIP_HORIZONTAL -> transform.setScale(-1f, 1f)
|
||||||
|
ExifInterface.ORIENTATION_ROTATE_180 -> transform.setRotate(180f)
|
||||||
|
ExifInterface.ORIENTATION_FLIP_VERTICAL -> transform.setScale(1f, -1f)
|
||||||
|
ExifInterface.ORIENTATION_TRANSPOSE -> { transform.setRotate(90f); transform.postScale(-1f, 1f) }
|
||||||
|
ExifInterface.ORIENTATION_ROTATE_90 -> transform.setRotate(90f)
|
||||||
|
ExifInterface.ORIENTATION_TRANSVERSE -> { transform.setRotate(-90f); transform.postScale(-1f, 1f) }
|
||||||
|
ExifInterface.ORIENTATION_ROTATE_270 -> transform.setRotate(-90f)
|
||||||
|
}
|
||||||
|
return if (transform.isIdentity) decoded else Bitmap.createBitmap(
|
||||||
|
decoded, 0, 0, decoded.width, decoded.height, transform, true,
|
||||||
|
).also { if (it !== decoded) decoded.recycle() }
|
||||||
|
} finally { file.delete() }
|
||||||
|
}
|
||||||
|
|
||||||
|
private fun copyPhoto(resolver: ContentResolver, uri: Uri, file: File) {
|
||||||
|
val input = resolver.openInputStream(uri) ?: throw PhotoInputError("无法打开这张照片。")
|
||||||
|
input.use { source ->
|
||||||
|
file.outputStream().use { target ->
|
||||||
|
val buffer = ByteArray(64 * 1024)
|
||||||
|
var total = 0L
|
||||||
|
while (true) {
|
||||||
|
val count = source.read(buffer)
|
||||||
|
if (count < 0) break
|
||||||
|
total += count
|
||||||
|
if (total > MAX_SOURCE_BYTES) throw PhotoInputError("原照片不能超过 30 MB。")
|
||||||
|
target.write(buffer, 0, count)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
private data class Crop(val x: Int, val y: Int, val edge: Int)
|
||||||
|
|
||||||
|
@Composable
|
||||||
|
private fun CropDialog(bitmap: Bitmap, busy: Boolean, error: String?, dismiss: () -> Unit, accept: (Crop) -> Unit) {
|
||||||
|
val shortest = min(bitmap.width, bitmap.height)
|
||||||
|
var edge by remember(bitmap) { mutableStateOf(shortest.toFloat()) }
|
||||||
|
var center by remember(bitmap) { mutableStateOf(Offset(bitmap.width * .5f, bitmap.height * .5f)) }
|
||||||
|
val shownEdge by rememberUpdatedState(edge)
|
||||||
|
val image = remember(bitmap) { bitmap.asImageBitmap() }
|
||||||
|
|
||||||
|
fun clamp(point: Offset, size: Float): Offset = Offset(
|
||||||
|
point.x.coerceIn(size / 2, bitmap.width - size / 2),
|
||||||
|
point.y.coerceIn(size / 2, bitmap.height - size / 2),
|
||||||
|
)
|
||||||
|
|
||||||
|
AlertDialog(
|
||||||
|
onDismissRequest = { if (!busy) dismiss() },
|
||||||
|
title = { Text("裁剪照片") },
|
||||||
|
text = {
|
||||||
|
Column(verticalArrangement = Arrangement.spacedBy(10.dp)) {
|
||||||
|
Text("拖动方框选择范围,下方滑杆可调大小。")
|
||||||
|
Canvas(Modifier.fillMaxWidth().aspectRatio(1f).pointerInput(bitmap, busy) {
|
||||||
|
if (busy) return@pointerInput
|
||||||
|
detectDragGestures { change, delta ->
|
||||||
|
val scale = min(size.width.toFloat() / bitmap.width, size.height.toFloat() / bitmap.height)
|
||||||
|
center = clamp(center + delta / scale, shownEdge)
|
||||||
|
change.consume()
|
||||||
|
}
|
||||||
|
}) {
|
||||||
|
val scale = min(size.width / image.width, size.height / image.height)
|
||||||
|
val dimensions = IntSize((image.width * scale).roundToInt(), (image.height * scale).roundToInt())
|
||||||
|
val origin = IntOffset(((size.width - dimensions.width) / 2).roundToInt(),
|
||||||
|
((size.height - dimensions.height) / 2).roundToInt())
|
||||||
|
drawImage(image, dstOffset = origin, dstSize = dimensions)
|
||||||
|
val x = origin.x + (center.x - edge / 2) * scale
|
||||||
|
val y = origin.y + (center.y - edge / 2) * scale
|
||||||
|
val side = edge * scale
|
||||||
|
val shade = Color.Black.copy(alpha = .55f)
|
||||||
|
val right = (origin.x + dimensions.width).toFloat()
|
||||||
|
val bottom = (origin.y + dimensions.height).toFloat()
|
||||||
|
drawRect(shade, Offset(origin.x.toFloat(), origin.y.toFloat()), Size(dimensions.width.toFloat(), (y - origin.y).coerceAtLeast(0f)))
|
||||||
|
drawRect(shade, Offset(origin.x.toFloat(), y + side), Size(dimensions.width.toFloat(), (bottom - y - side).coerceAtLeast(0f)))
|
||||||
|
drawRect(shade, Offset(origin.x.toFloat(), y), Size((x - origin.x).coerceAtLeast(0f), side))
|
||||||
|
drawRect(shade, Offset(x + side, y), Size((right - x - side).coerceAtLeast(0f), side))
|
||||||
|
drawRect(Color.White, Offset(x, y), Size(side, side), style = Stroke(2.dp.toPx()))
|
||||||
|
}
|
||||||
|
val minEdge = min(shortest, maxOf(64, shortest / 5)).toFloat()
|
||||||
|
if (minEdge < shortest) Slider(edge, { edge = it; center = clamp(center, it) },
|
||||||
|
enabled = !busy, valueRange = minEdge..shortest.toFloat())
|
||||||
|
error?.let { Text(it, color = MaterialTheme.colorScheme.error) }
|
||||||
|
if (busy) LinearProgressIndicator(Modifier.fillMaxWidth())
|
||||||
|
}
|
||||||
|
},
|
||||||
|
confirmButton = {
|
||||||
|
TextButton(enabled = !busy, onClick = {
|
||||||
|
val side = edge.roundToInt().coerceAtMost(shortest)
|
||||||
|
val x = (center.x - side / 2f).roundToInt().coerceIn(0, bitmap.width - side)
|
||||||
|
val y = (center.y - side / 2f).roundToInt().coerceIn(0, bitmap.height - side)
|
||||||
|
accept(Crop(x, y, side))
|
||||||
|
}) { Text("使用照片") }
|
||||||
|
},
|
||||||
|
dismissButton = { TextButton(enabled = !busy, onClick = dismiss) { Text("取消") } },
|
||||||
|
)
|
||||||
|
}
|
||||||
|
|
||||||
|
private fun cropJpeg(bitmap: Bitmap, crop: Crop): ByteArray {
|
||||||
|
val part = Bitmap.createBitmap(bitmap, crop.x, crop.y, crop.edge, crop.edge)
|
||||||
|
val output = if (crop.edge > CROP_OUTPUT_EDGE) {
|
||||||
|
Bitmap.createScaledBitmap(part, CROP_OUTPUT_EDGE, CROP_OUTPUT_EDGE, true)
|
||||||
|
} else part
|
||||||
|
try {
|
||||||
|
val bytes = ByteArrayOutputStream()
|
||||||
|
if (!output.compress(Bitmap.CompressFormat.JPEG, 88, bytes) || bytes.size() > MAX_PHOTO_BYTES) {
|
||||||
|
throw PhotoInputError("裁剪后的照片无法保存,请缩小裁剪范围。")
|
||||||
|
}
|
||||||
|
return bytes.toByteArray()
|
||||||
|
} finally {
|
||||||
|
if (output !== part) output.recycle()
|
||||||
|
if (part !== bitmap) part.recycle()
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
@ -0,0 +1,107 @@
|
||||||
|
package com.tutudog.itematlas
|
||||||
|
|
||||||
|
import androidx.compose.foundation.layout.Arrangement
|
||||||
|
import androidx.compose.foundation.layout.Column
|
||||||
|
import androidx.compose.foundation.layout.Row
|
||||||
|
import androidx.compose.foundation.layout.fillMaxWidth
|
||||||
|
import androidx.compose.foundation.layout.heightIn
|
||||||
|
import androidx.compose.foundation.lazy.LazyColumn
|
||||||
|
import androidx.compose.foundation.lazy.itemsIndexed
|
||||||
|
import androidx.compose.material3.AlertDialog
|
||||||
|
import androidx.compose.material3.LinearProgressIndicator
|
||||||
|
import androidx.compose.material3.MaterialTheme
|
||||||
|
import androidx.compose.material3.OutlinedButton
|
||||||
|
import androidx.compose.material3.Text
|
||||||
|
import androidx.compose.material3.TextButton
|
||||||
|
import androidx.compose.runtime.Composable
|
||||||
|
import androidx.compose.runtime.LaunchedEffect
|
||||||
|
import androidx.compose.runtime.getValue
|
||||||
|
import androidx.compose.runtime.key
|
||||||
|
import androidx.compose.runtime.mutableStateOf
|
||||||
|
import androidx.compose.runtime.remember
|
||||||
|
import androidx.compose.runtime.rememberCoroutineScope
|
||||||
|
import androidx.compose.runtime.setValue
|
||||||
|
import androidx.compose.ui.Alignment
|
||||||
|
import androidx.compose.ui.Modifier
|
||||||
|
import androidx.compose.ui.semantics.contentDescription
|
||||||
|
import androidx.compose.ui.semantics.semantics
|
||||||
|
import androidx.compose.ui.unit.dp
|
||||||
|
import kotlinx.coroutines.CancellationException
|
||||||
|
import kotlinx.coroutines.launch
|
||||||
|
import kotlinx.serialization.Serializable
|
||||||
|
|
||||||
|
@Serializable data class LocationOrder(val version: String, val ids: List<String>)
|
||||||
|
@Serializable data class OrderInput(val parentId: String?, val version: String, val ids: List<String>)
|
||||||
|
|
||||||
|
@Composable
|
||||||
|
internal fun LocationOrderEntry(model: AtlasViewModel, space: Space, parent: Place?, children: List<Place>) {
|
||||||
|
key(space.id, parent?.id) {
|
||||||
|
var open by remember { mutableStateOf(false) }
|
||||||
|
OutlinedButton(onClick = { open = true }) { Text("排序") }
|
||||||
|
if (open) OrderDialog(model, space, parent, children) { open = false }
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
@Composable
|
||||||
|
private fun OrderDialog(model: AtlasViewModel, space: Space, parent: Place?, children: List<Place>, close: () -> Unit) {
|
||||||
|
val scope = rememberCoroutineScope()
|
||||||
|
var order by remember { mutableStateOf<LocationOrder?>(null) }
|
||||||
|
var ids by remember { mutableStateOf(emptyList<String>()) }
|
||||||
|
var busy by remember { mutableStateOf(true) }
|
||||||
|
var error by remember { mutableStateOf<String?>(null) }
|
||||||
|
val names = children.associateBy(Place::id)
|
||||||
|
|
||||||
|
suspend fun run(block: suspend () -> Unit) {
|
||||||
|
busy = true
|
||||||
|
error = null
|
||||||
|
try { block() }
|
||||||
|
catch (failure: Exception) {
|
||||||
|
if (failure is CancellationException) throw failure
|
||||||
|
error = model.requestFailure(failure)
|
||||||
|
} finally { busy = false }
|
||||||
|
}
|
||||||
|
suspend fun read() {
|
||||||
|
val loaded = model.api.loadOrder(space, parent?.id)
|
||||||
|
order = loaded
|
||||||
|
ids = loaded.ids
|
||||||
|
if (ids.any { it !in names }) model.refreshLocations()
|
||||||
|
}
|
||||||
|
fun move(index: Int, target: Int) {
|
||||||
|
ids = ids.toMutableList().apply { add(target, removeAt(index)) }
|
||||||
|
}
|
||||||
|
|
||||||
|
LaunchedEffect(Unit) { run { read() } }
|
||||||
|
AlertDialog(onDismissRequest = { if (!busy) close() }, title = { Text("同级位置排序") },
|
||||||
|
text = {
|
||||||
|
Column(verticalArrangement = Arrangement.spacedBy(8.dp)) {
|
||||||
|
if (busy) LinearProgressIndicator(Modifier.fillMaxWidth())
|
||||||
|
error?.let {
|
||||||
|
Text(it, color = MaterialTheme.colorScheme.error)
|
||||||
|
TextButton(enabled = !busy, onClick = { scope.launch { run { read() } } }) { Text("重新加载") }
|
||||||
|
}
|
||||||
|
LazyColumn(Modifier.heightIn(max = 320.dp)) {
|
||||||
|
itemsIndexed(ids, key = { _, id -> id }) { index, id ->
|
||||||
|
val name = names[id]?.name ?: "正在读取位置"
|
||||||
|
Row(Modifier.fillMaxWidth(), verticalAlignment = Alignment.CenterVertically) {
|
||||||
|
Text(name, Modifier.weight(1f))
|
||||||
|
TextButton(enabled = index > 0 && !busy, onClick = { move(index, index - 1) },
|
||||||
|
modifier = Modifier.semantics { contentDescription = "上移 $name" }) { Text("↑") }
|
||||||
|
TextButton(enabled = index < ids.lastIndex && !busy, onClick = { move(index, index + 1) },
|
||||||
|
modifier = Modifier.semantics { contentDescription = "下移 $name" }) { Text("↓") }
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}, confirmButton = { TextButton(enabled = !busy && order?.let { ids != it.ids } == true,
|
||||||
|
onClick = {
|
||||||
|
val baseline = order ?: return@TextButton
|
||||||
|
scope.launch {
|
||||||
|
run {
|
||||||
|
model.api.saveOrder(space, OrderInput(parent?.id, baseline.version, ids))
|
||||||
|
model.refreshLocations()
|
||||||
|
close()
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}) { Text("保存排序") } },
|
||||||
|
dismissButton = { TextButton(enabled = !busy, onClick = close) { Text("取消") } })
|
||||||
|
}
|
||||||
|
|
@ -0,0 +1,473 @@
|
||||||
|
package com.tutudog.itematlas
|
||||||
|
|
||||||
|
import androidx.compose.foundation.Canvas
|
||||||
|
import androidx.compose.foundation.gestures.detectDragGestures
|
||||||
|
import androidx.compose.foundation.gestures.detectTapGestures
|
||||||
|
import androidx.compose.foundation.layout.Arrangement
|
||||||
|
import androidx.compose.foundation.layout.Box
|
||||||
|
import androidx.compose.foundation.layout.Column
|
||||||
|
import androidx.compose.foundation.layout.Row
|
||||||
|
import androidx.compose.foundation.layout.fillMaxSize
|
||||||
|
import androidx.compose.foundation.layout.fillMaxWidth
|
||||||
|
import androidx.compose.foundation.layout.height
|
||||||
|
import androidx.compose.foundation.layout.padding
|
||||||
|
import androidx.compose.foundation.rememberScrollState
|
||||||
|
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.Checkbox
|
||||||
|
import androidx.compose.material3.DropdownMenu
|
||||||
|
import androidx.compose.material3.DropdownMenuItem
|
||||||
|
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.Surface
|
||||||
|
import androidx.compose.material3.Text
|
||||||
|
import androidx.compose.material3.TextButton
|
||||||
|
import androidx.compose.runtime.Composable
|
||||||
|
import androidx.compose.runtime.LaunchedEffect
|
||||||
|
import androidx.compose.runtime.getValue
|
||||||
|
import androidx.compose.runtime.key
|
||||||
|
import androidx.compose.runtime.mutableStateOf
|
||||||
|
import androidx.compose.runtime.remember
|
||||||
|
import androidx.compose.runtime.rememberCoroutineScope
|
||||||
|
import androidx.compose.runtime.rememberUpdatedState
|
||||||
|
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.geometry.Offset
|
||||||
|
import androidx.compose.ui.geometry.Size
|
||||||
|
import androidx.compose.ui.graphics.Color
|
||||||
|
import androidx.compose.ui.graphics.drawscope.Stroke
|
||||||
|
import androidx.compose.ui.input.pointer.pointerInput
|
||||||
|
import androidx.compose.ui.text.TextStyle
|
||||||
|
import androidx.compose.ui.text.drawText
|
||||||
|
import androidx.compose.ui.text.font.FontWeight
|
||||||
|
import androidx.compose.ui.text.input.KeyboardType
|
||||||
|
import androidx.compose.ui.text.rememberTextMeasurer
|
||||||
|
import androidx.compose.ui.unit.Constraints
|
||||||
|
import androidx.compose.ui.unit.dp
|
||||||
|
import androidx.compose.ui.unit.sp
|
||||||
|
import androidx.compose.ui.window.Dialog
|
||||||
|
import androidx.compose.ui.window.DialogProperties
|
||||||
|
import kotlin.math.min
|
||||||
|
import kotlinx.coroutines.CancellationException
|
||||||
|
import kotlinx.coroutines.launch
|
||||||
|
|
||||||
|
@Composable
|
||||||
|
internal fun LocationPlanEntry(model: AtlasViewModel, space: Space, place: Place?) {
|
||||||
|
key(space.id, place?.id) {
|
||||||
|
var open by rememberSaveable { mutableStateOf(false) }
|
||||||
|
OutlinedButton(onClick = { open = true }) { Text("平面图") }
|
||||||
|
if (open) LocationPlan(model, space, place, dismiss = { open = false })
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
@Composable
|
||||||
|
private fun LocationPlan(model: AtlasViewModel, space: Space, place: Place?, dismiss: () -> Unit) {
|
||||||
|
val scope = rememberCoroutineScope()
|
||||||
|
var snapshot by remember { mutableStateOf<PlanSnapshot?>(null) }
|
||||||
|
var working by remember { mutableStateOf(emptyList<PlanLocation>()) }
|
||||||
|
var undo by remember { mutableStateOf(emptyList<List<PlanLocation>>()) }
|
||||||
|
var redo by remember { mutableStateOf(emptyList<List<PlanLocation>>()) }
|
||||||
|
var selected by remember { mutableStateOf<String?>(null) }
|
||||||
|
var loadError by remember { mutableStateOf<String?>(null) }
|
||||||
|
var status by remember { mutableStateOf<String?>(null) }
|
||||||
|
var busy by remember { mutableStateOf(false) }
|
||||||
|
var confirm by remember { mutableStateOf<String?>(null) }
|
||||||
|
var chooseTemplate by remember { mutableStateOf(false) }
|
||||||
|
var pendingTemplate by remember { mutableStateOf<PlanTemplate?>(null) }
|
||||||
|
var showAi by remember { mutableStateOf(false) }
|
||||||
|
var description by rememberSaveable { mutableStateOf("") }
|
||||||
|
val dirty = snapshot?.locations != working && snapshot != null
|
||||||
|
val parentId = place?.id
|
||||||
|
|
||||||
|
fun install(updated: PlanSnapshot) {
|
||||||
|
snapshot = updated
|
||||||
|
working = updated.locations
|
||||||
|
undo = emptyList()
|
||||||
|
redo = emptyList()
|
||||||
|
selected = selected?.takeIf { id -> working.any { it.id == id && it.geometry != null } }
|
||||||
|
}
|
||||||
|
|
||||||
|
fun beginEdit(previous: List<PlanLocation>) {
|
||||||
|
if (previous == working) return
|
||||||
|
undo = (undo + listOf(previous)).takeLast(60)
|
||||||
|
redo = emptyList()
|
||||||
|
loadError = null
|
||||||
|
status = null
|
||||||
|
}
|
||||||
|
|
||||||
|
fun edit(next: List<PlanLocation>) {
|
||||||
|
val previous = working
|
||||||
|
working = next
|
||||||
|
beginEdit(previous)
|
||||||
|
}
|
||||||
|
|
||||||
|
fun navigateAway() {
|
||||||
|
if (busy) return
|
||||||
|
if (dirty) confirm = "close" else dismiss()
|
||||||
|
}
|
||||||
|
|
||||||
|
suspend fun read() {
|
||||||
|
busy = true
|
||||||
|
loadError = null
|
||||||
|
status = null
|
||||||
|
try { install(model.api.loadPlan(space, parentId)) }
|
||||||
|
catch (failure: Exception) {
|
||||||
|
if (failure is CancellationException) throw failure
|
||||||
|
loadError = model.requestFailure(failure)
|
||||||
|
} finally { busy = false }
|
||||||
|
}
|
||||||
|
|
||||||
|
fun save(base: PlanSnapshot) {
|
||||||
|
busy = true
|
||||||
|
loadError = null
|
||||||
|
scope.launch {
|
||||||
|
try {
|
||||||
|
install(model.api.savePlan(space, base.save(parentId, working)))
|
||||||
|
model.refreshLocations()
|
||||||
|
status = "平面图已保存"
|
||||||
|
} catch (failure: Exception) {
|
||||||
|
if (failure is CancellationException) throw failure
|
||||||
|
loadError = model.requestFailure(failure)
|
||||||
|
} finally { busy = false }
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
LaunchedEffect(Unit) { read() }
|
||||||
|
Dialog(onDismissRequest = ::navigateAway, properties = DialogProperties(usePlatformDefaultWidth = false)) {
|
||||||
|
Surface(Modifier.fillMaxSize(), color = MaterialTheme.colorScheme.background) {
|
||||||
|
Column(Modifier.padding(16.dp), verticalArrangement = Arrangement.spacedBy(8.dp)) {
|
||||||
|
Row(Modifier.fillMaxWidth(), horizontalArrangement = Arrangement.SpaceBetween,
|
||||||
|
verticalAlignment = Alignment.CenterVertically) {
|
||||||
|
TextButton(onClick = ::navigateAway, enabled = !busy) { Text("返回") }
|
||||||
|
Text(place?.name?.let { "$it · 平面图" } ?: "全屋平面图", style = MaterialTheme.typography.titleLarge)
|
||||||
|
if (space.writable) Button(onClick = { snapshot?.let(::save) },
|
||||||
|
enabled = dirty && !busy) { Text("保存") }
|
||||||
|
}
|
||||||
|
if (busy) LinearProgressIndicator(Modifier.fillMaxWidth())
|
||||||
|
loadError?.let { Text(it, color = MaterialTheme.colorScheme.error) }
|
||||||
|
status?.let { Text(it, color = MaterialTheme.colorScheme.primary) }
|
||||||
|
val base = snapshot
|
||||||
|
if (base == null && !busy) TextButton(onClick = { scope.launch { read() } }) { Text("重试") }
|
||||||
|
if (base != null) {
|
||||||
|
val painted = working.filter { it.geometry != null }
|
||||||
|
val unplaced = working.filter { it.geometry == null }
|
||||||
|
Column(Modifier.fillMaxWidth().weight(1f).verticalScroll(rememberScrollState()),
|
||||||
|
verticalArrangement = Arrangement.spacedBy(12.dp)) {
|
||||||
|
PlanCanvas(base, working, selected, space.writable && !busy, { selected = it },
|
||||||
|
onDrag = { id, geometry -> working = working.map { if (it.id == id) it.copy(geometry = geometry) else it } },
|
||||||
|
onDragEnd = ::beginEdit, onDragCancel = { working = it })
|
||||||
|
Text("${base.widthMm / 10} × ${base.depthMm / 10} 厘米 · 网格 10 厘米",
|
||||||
|
style = MaterialTheme.typography.labelMedium)
|
||||||
|
if (painted.isEmpty()) Text("图上还没有位置。")
|
||||||
|
if (space.writable) {
|
||||||
|
Row(horizontalArrangement = Arrangement.spacedBy(4.dp)) {
|
||||||
|
TextButton(enabled = undo.isNotEmpty() && !busy, onClick = {
|
||||||
|
redo = redo + listOf(working)
|
||||||
|
working = undo.last()
|
||||||
|
undo = undo.dropLast(1)
|
||||||
|
status = null
|
||||||
|
}) { Text("撤回") }
|
||||||
|
TextButton(enabled = redo.isNotEmpty() && !busy, onClick = {
|
||||||
|
undo = undo + listOf(working)
|
||||||
|
working = redo.last()
|
||||||
|
redo = redo.dropLast(1)
|
||||||
|
}) { Text("重做") }
|
||||||
|
TextButton(enabled = dirty && !busy, onClick = { confirm = "reset" }) { Text("放弃修改") }
|
||||||
|
TextButton(enabled = !busy, onClick = {
|
||||||
|
if (dirty) confirm = "reload" else scope.launch { read() }
|
||||||
|
}) { Text("重新加载") }
|
||||||
|
}
|
||||||
|
Row(horizontalArrangement = Arrangement.spacedBy(8.dp)) {
|
||||||
|
Box {
|
||||||
|
Button(onClick = { chooseTemplate = true }, enabled = !busy) { Text("添加模板") }
|
||||||
|
DropdownMenu(expanded = chooseTemplate, onDismissRequest = { chooseTemplate = false }) {
|
||||||
|
PlanTemplate.entries.filter { parentId == null || !it.isRoom }.forEach { template ->
|
||||||
|
DropdownMenuItem(text = { Text(template.label) }, onClick = {
|
||||||
|
chooseTemplate = false
|
||||||
|
pendingTemplate = template
|
||||||
|
})
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
OutlinedButton(onClick = { showAi = true }, enabled = !busy && !dirty) { Text("AI 建模") }
|
||||||
|
}
|
||||||
|
}
|
||||||
|
val current = painted.firstOrNull { it.id == selected }
|
||||||
|
if (current != null && space.writable) key(current.id) {
|
||||||
|
PlanProperties(current, base, enabled = !busy, change = { geometry ->
|
||||||
|
edit(working.map { if (it.id == current.id) it.copy(geometry = geometry) else it })
|
||||||
|
}, remove = {
|
||||||
|
edit(working.mapNotNull {
|
||||||
|
when {
|
||||||
|
it.id != current.id -> it
|
||||||
|
base.locations.any { original -> original.id == it.id } -> it.copy(geometry = null)
|
||||||
|
else -> null
|
||||||
|
}
|
||||||
|
})
|
||||||
|
selected = null
|
||||||
|
})
|
||||||
|
}
|
||||||
|
if (painted.isNotEmpty()) {
|
||||||
|
HorizontalDivider()
|
||||||
|
Text("图上的位置", style = MaterialTheme.typography.titleMedium)
|
||||||
|
painted.forEach { location ->
|
||||||
|
TextButton(onClick = { selected = location.id }) {
|
||||||
|
Text(location.name, fontWeight = if (location.id == selected) FontWeight.SemiBold else null)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if (unplaced.isNotEmpty() && space.writable) {
|
||||||
|
HorizontalDivider()
|
||||||
|
Text("尚未摆放", style = MaterialTheme.typography.titleMedium)
|
||||||
|
unplaced.forEach { location ->
|
||||||
|
TextButton(enabled = !busy, onClick = {
|
||||||
|
val template = if (parentId == null) PlanTemplate.AREA else PlanTemplate.STORAGE_BOX
|
||||||
|
base.place(template, working)?.let { geometry ->
|
||||||
|
edit(working.map { if (it.id == location.id) it.copy(geometry = geometry) else it })
|
||||||
|
selected = location.id
|
||||||
|
}
|
||||||
|
}) { Text("摆放 ${location.name}") }
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
confirm?.let { action ->
|
||||||
|
AlertDialog(onDismissRequest = { confirm = null }, title = { Text("放弃未保存的修改?") },
|
||||||
|
text = { Text("已保存的位置和平面图会保留。") },
|
||||||
|
confirmButton = {
|
||||||
|
TextButton(onClick = {
|
||||||
|
confirm = null
|
||||||
|
when (action) {
|
||||||
|
"close" -> dismiss()
|
||||||
|
"reload" -> scope.launch { read() }
|
||||||
|
else -> snapshot?.let(::install)
|
||||||
|
}
|
||||||
|
}) { Text("放弃") }
|
||||||
|
},
|
||||||
|
dismissButton = { TextButton(onClick = { confirm = null }) { Text("继续编辑") } })
|
||||||
|
}
|
||||||
|
|
||||||
|
pendingTemplate?.let { template ->
|
||||||
|
val base = snapshot ?: return@let
|
||||||
|
var name by remember(template) {
|
||||||
|
val id = (1..working.size + 1).first { i ->
|
||||||
|
val proposed = if (i == 1) template.label else "${template.label} $i"
|
||||||
|
working.none { it.name == proposed }
|
||||||
|
}
|
||||||
|
mutableStateOf(if (id == 1) template.label else "${template.label} $id")
|
||||||
|
}
|
||||||
|
AlertDialog(onDismissRequest = { pendingTemplate = null }, title = { Text("添加${template.label}") },
|
||||||
|
text = {
|
||||||
|
OutlinedTextField(name, { name = it.take(100) }, label = { Text("位置名称") }, singleLine = true)
|
||||||
|
},
|
||||||
|
confirmButton = {
|
||||||
|
TextButton(enabled = name.isNotBlank(), onClick = {
|
||||||
|
val geometry = base.place(template, working)
|
||||||
|
if (geometry == null) loadError = "画布剩余空间不足,请先移动或缩小已有房间。"
|
||||||
|
else {
|
||||||
|
val id = newPlanId()
|
||||||
|
edit(working + PlanLocation(id, name.trim(), geometry))
|
||||||
|
selected = id
|
||||||
|
}
|
||||||
|
pendingTemplate = null
|
||||||
|
}) { Text("添加到图上") }
|
||||||
|
}, dismissButton = { TextButton(onClick = { pendingTemplate = null }) { Text("取消") } })
|
||||||
|
}
|
||||||
|
|
||||||
|
if (showAi) snapshot?.let { base ->
|
||||||
|
PlanAiDialog(model, space, base, parentId, description, { description = it }, close = { showAi = false }) { changes, ids ->
|
||||||
|
edit(applyPlanSuggestions(working, changes, ids))
|
||||||
|
showAi = false
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
@Composable
|
||||||
|
private fun PlanProperties(
|
||||||
|
current: PlanLocation, base: PlanSnapshot, enabled: Boolean,
|
||||||
|
change: (PlanGeometry) -> Unit, remove: () -> Unit,
|
||||||
|
) {
|
||||||
|
val shape = current.geometry ?: return
|
||||||
|
var width by remember(shape.widthMm) { mutableStateOf((shape.widthMm / 10).toString()) }
|
||||||
|
var depth by remember(shape.depthMm) { mutableStateOf((shape.depthMm / 10).toString()) }
|
||||||
|
Text(current.name, style = MaterialTheme.typography.titleMedium)
|
||||||
|
Row(horizontalArrangement = Arrangement.spacedBy(8.dp)) {
|
||||||
|
OutlinedTextField(width, { width = it.take(4) }, Modifier.weight(1f), enabled = enabled,
|
||||||
|
label = { Text("宽(厘米)") }, singleLine = true, keyboardOptions = KeyboardOptions(keyboardType = KeyboardType.Number))
|
||||||
|
OutlinedTextField(depth, { depth = it.take(4) }, Modifier.weight(1f), enabled = enabled,
|
||||||
|
label = { Text("深(厘米)") }, singleLine = true, keyboardOptions = KeyboardOptions(keyboardType = KeyboardType.Number))
|
||||||
|
}
|
||||||
|
Row(horizontalArrangement = Arrangement.spacedBy(6.dp)) {
|
||||||
|
val w = width.toIntOrNull()?.times(10)
|
||||||
|
val d = depth.toIntOrNull()?.times(10)
|
||||||
|
TextButton(enabled = enabled && w != null && d != null && w in 100..base.widthMm && d in 100..base.depthMm,
|
||||||
|
onClick = {
|
||||||
|
val scaled = shape.copy(widthMm = checkNotNull(w), depthMm = checkNotNull(d))
|
||||||
|
change(base.origin(scaled, shape.xMm.toFloat(), shape.yMm.toFloat()))
|
||||||
|
}) { Text("应用尺寸") }
|
||||||
|
TextButton(enabled = enabled && shape.depthMm <= base.widthMm && shape.widthMm <= base.depthMm, onClick = {
|
||||||
|
val rotated = shape.copy(widthMm = shape.depthMm, depthMm = shape.widthMm, rotation = (shape.rotation + 90) % 360)
|
||||||
|
change(base.origin(rotated, shape.xMm.toFloat(), shape.yMm.toFloat()))
|
||||||
|
}) { Text("旋转") }
|
||||||
|
TextButton(enabled = enabled, onClick = remove) { Text("移出图面") }
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
private class PlanViewport(size: Size, plan: PlanSnapshot) {
|
||||||
|
val scale = (min(size.width / plan.widthMm, size.height / plan.depthMm) * .94f).coerceAtLeast(.0001f)
|
||||||
|
val width = plan.widthMm * scale
|
||||||
|
val height = plan.depthMm * scale
|
||||||
|
val origin = Offset((size.width - width) / 2, (size.height - height) / 2)
|
||||||
|
|
||||||
|
fun hit(position: Offset, painted: List<PlanLocation>): PlanLocation? {
|
||||||
|
val mm = (position - origin) / scale
|
||||||
|
return painted.lastOrNull { row ->
|
||||||
|
row.geometry?.let { mm.x >= it.xMm && mm.x <= it.right && mm.y >= it.yMm && mm.y <= it.bottom } == true
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
@Composable
|
||||||
|
private fun PlanCanvas(
|
||||||
|
plan: PlanSnapshot, locations: List<PlanLocation>, selected: String?, writable: Boolean,
|
||||||
|
choose: (String?) -> Unit, onDrag: (String, PlanGeometry) -> Unit,
|
||||||
|
onDragEnd: (List<PlanLocation>) -> Unit, onDragCancel: (List<PlanLocation>) -> Unit,
|
||||||
|
) {
|
||||||
|
val onCanvas by rememberUpdatedState(locations)
|
||||||
|
val textMeasurer = rememberTextMeasurer()
|
||||||
|
val colors = MaterialTheme.colorScheme
|
||||||
|
val paint = Modifier.fillMaxWidth().height(300.dp).pointerInput(plan) {
|
||||||
|
detectTapGestures { point ->
|
||||||
|
val viewport = PlanViewport(Size(size.width.toFloat(), size.height.toFloat()), plan)
|
||||||
|
choose(viewport.hit(point, onCanvas)?.id)
|
||||||
|
}
|
||||||
|
}.pointerInput(plan, writable) {
|
||||||
|
if (!writable) return@pointerInput
|
||||||
|
val viewport = PlanViewport(Size(size.width.toFloat(), size.height.toFloat()), plan)
|
||||||
|
var previous: List<PlanLocation>? = null
|
||||||
|
var moved: PlanLocation? = null
|
||||||
|
var travel = Offset.Zero
|
||||||
|
detectDragGestures(
|
||||||
|
onDragStart = { point ->
|
||||||
|
previous = onCanvas
|
||||||
|
moved = viewport.hit(point, onCanvas)
|
||||||
|
travel = Offset.Zero
|
||||||
|
choose(moved?.id)
|
||||||
|
},
|
||||||
|
onDragEnd = { previous?.let(onDragEnd); previous = null },
|
||||||
|
onDragCancel = { previous?.let(onDragCancel); previous = null },
|
||||||
|
) { change, delta ->
|
||||||
|
val row = moved ?: return@detectDragGestures
|
||||||
|
val shape = row.geometry ?: return@detectDragGestures
|
||||||
|
travel += delta / viewport.scale
|
||||||
|
onDrag(row.id, plan.origin(shape, shape.xMm + travel.x, shape.yMm + travel.y))
|
||||||
|
change.consume()
|
||||||
|
}
|
||||||
|
}
|
||||||
|
Canvas(paint) {
|
||||||
|
val viewport = PlanViewport(size, plan)
|
||||||
|
val origin = viewport.origin
|
||||||
|
val scale = viewport.scale
|
||||||
|
drawRect(colors.surfaceVariant, origin, Size(viewport.width, viewport.height))
|
||||||
|
for (x in 0..plan.widthMm step 1000) {
|
||||||
|
val px = origin.x + x * scale
|
||||||
|
drawLine(colors.outlineVariant, Offset(px, origin.y), Offset(px, origin.y + viewport.height))
|
||||||
|
}
|
||||||
|
for (y in 0..plan.depthMm step 1000) {
|
||||||
|
val py = origin.y + y * scale
|
||||||
|
drawLine(colors.outlineVariant, Offset(origin.x, py), Offset(origin.x + viewport.width, py))
|
||||||
|
}
|
||||||
|
locations.forEach { row ->
|
||||||
|
val shape = row.geometry ?: return@forEach
|
||||||
|
val top = origin + Offset(shape.xMm * scale, shape.yMm * scale)
|
||||||
|
val size = Size(shape.widthMm * scale, shape.depthMm * scale)
|
||||||
|
val fill = if (shape.template.isRoom) Color(0xFFCDE4DB) else Color(0xFFF1D5A5)
|
||||||
|
drawRect(fill, top, size)
|
||||||
|
drawRect(if (row.id == selected) colors.primary else colors.outline, top, size,
|
||||||
|
style = Stroke(if (row.id == selected) 3.dp.toPx() else 1.dp.toPx()))
|
||||||
|
if (size.width > 24.dp.toPx() && size.height > 16.dp.toPx()) {
|
||||||
|
val inset = 4.dp.toPx()
|
||||||
|
val text = textMeasurer.measure(row.name, TextStyle(color = Color(0xFF172A23), fontSize = 11.sp),
|
||||||
|
maxLines = 1, overflow = androidx.compose.ui.text.style.TextOverflow.Ellipsis,
|
||||||
|
constraints = Constraints(maxWidth = (size.width - 2 * inset).toInt().coerceAtLeast(1)))
|
||||||
|
drawText(text, topLeft = top + Offset(inset, inset))
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
@Composable
|
||||||
|
private fun PlanAiDialog(
|
||||||
|
model: AtlasViewModel, space: Space, base: PlanSnapshot, parentId: String?,
|
||||||
|
description: String, describe: (String) -> Unit, close: () -> Unit,
|
||||||
|
apply: (List<PlanSuggestion>, List<String>) -> Unit,
|
||||||
|
) {
|
||||||
|
val scope = rememberCoroutineScope()
|
||||||
|
var busy by remember { mutableStateOf(false) }
|
||||||
|
var recording by remember { mutableStateOf(false) }
|
||||||
|
var error by remember { mutableStateOf<String?>(null) }
|
||||||
|
var changes by remember { mutableStateOf<List<PlanSuggestion>>(emptyList()) }
|
||||||
|
var ids by remember { mutableStateOf<List<String>>(emptyList()) }
|
||||||
|
var included by remember { mutableStateOf<Set<Int>>(emptySet()) }
|
||||||
|
val accepted = changes.filterIndexed { index, _ -> index in included }
|
||||||
|
val acceptedIds = ids.filterIndexed { index, _ -> index in included }
|
||||||
|
fun edit(next: String) {
|
||||||
|
describe(next.take(1600))
|
||||||
|
changes = emptyList()
|
||||||
|
included = emptySet()
|
||||||
|
}
|
||||||
|
AlertDialog(onDismissRequest = { if (!busy) close() }, title = { Text("AI 建模") },
|
||||||
|
text = {
|
||||||
|
Column(Modifier.verticalScroll(rememberScrollState()), verticalArrangement = Arrangement.spacedBy(8.dp)) {
|
||||||
|
OutlinedTextField(description, ::edit, Modifier.fillMaxWidth(),
|
||||||
|
enabled = !busy && !recording, label = { Text("描述你想摆放的位置") })
|
||||||
|
VoiceInput(!busy, onActive = { recording = it }, onText = { sentence ->
|
||||||
|
edit(listOf(description, sentence).filter(String::isNotBlank).joinToString(","))
|
||||||
|
})
|
||||||
|
TextButton(enabled = !busy && !recording && description.isNotBlank(), onClick = {
|
||||||
|
busy = true
|
||||||
|
error = null
|
||||||
|
scope.launch {
|
||||||
|
try {
|
||||||
|
changes = model.api.suggestPlan(space, PlanPrompt(parentId, base.version, description.trim())).changes
|
||||||
|
ids = changes.map { newPlanId() }
|
||||||
|
included = changes.indices.filter { changes[it].geometry != null }.toSet()
|
||||||
|
if (changes.isEmpty()) error = "没有生成位置,可以再补充尺寸和方向。"
|
||||||
|
} catch (failure: Exception) {
|
||||||
|
if (failure is CancellationException) throw failure
|
||||||
|
error = model.requestFailure(failure)
|
||||||
|
} finally { busy = false }
|
||||||
|
}
|
||||||
|
}) { Text("生成建议") }
|
||||||
|
if (busy) LinearProgressIndicator(Modifier.fillMaxWidth())
|
||||||
|
error?.let { Text(it, color = MaterialTheme.colorScheme.error) }
|
||||||
|
if (included.isNotEmpty()) PlanCanvas(base, applyPlanSuggestions(base.locations, accepted, acceptedIds),
|
||||||
|
null, false, {}, { _, _ -> }, {}, {})
|
||||||
|
changes.forEachIndexed { index, change ->
|
||||||
|
Row(verticalAlignment = Alignment.CenterVertically) {
|
||||||
|
Checkbox(index in included, onCheckedChange = {
|
||||||
|
included = if (it) included + index else included - index
|
||||||
|
}, enabled = !busy && change.geometry != null)
|
||||||
|
Column {
|
||||||
|
Text(change.name)
|
||||||
|
if (change.note.isNotBlank()) Text(change.note, style = MaterialTheme.typography.bodySmall)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
},
|
||||||
|
confirmButton = { TextButton(enabled = included.isNotEmpty() && !busy && !recording,
|
||||||
|
onClick = { apply(accepted, acceptedIds) }) { Text("应用所选建议") } },
|
||||||
|
dismissButton = { TextButton(enabled = !busy, onClick = close) { Text("关闭") } })
|
||||||
|
}
|
||||||
|
|
@ -167,11 +167,18 @@ private fun Detail(state: AtlasState, model: AtlasViewModel, modifier: Modifier)
|
||||||
}
|
}
|
||||||
if (item.aliases.isNotEmpty()) DetailLine("别名", item.aliases.joinToString("、"))
|
if (item.aliases.isNotEmpty()) DetailLine("别名", item.aliases.joinToString("、"))
|
||||||
if (item.notes.isNotBlank()) DetailLine("备注", item.notes)
|
if (item.notes.isNotBlank()) DetailLine("备注", item.notes)
|
||||||
|
state.space?.let { PhotosEntry(model, it, PhotoKind.Item, item.id) }
|
||||||
|
state.space?.let { space ->
|
||||||
|
PublishEntry(model, space, item)
|
||||||
|
ItemConnections(model, space, item, state.relatedItems)
|
||||||
|
}
|
||||||
|
state.itemPreference?.let { ItemReview(model, item, it, state.busy) }
|
||||||
if (state.space?.writable == true) {
|
if (state.space?.writable == true) {
|
||||||
Row(horizontalArrangement = Arrangement.spacedBy(12.dp)) {
|
Row(horizontalArrangement = Arrangement.spacedBy(12.dp)) {
|
||||||
OutlinedButton(onClick = model::startEdit, enabled = !state.busy) { Text("编辑物品") }
|
OutlinedButton(onClick = model::startEdit, enabled = !state.busy) { Text("编辑物品") }
|
||||||
OutlinedButton(onClick = model::startMove, enabled = !state.busy) { Text("移动物品") }
|
OutlinedButton(onClick = model::startMove, enabled = !state.busy) { Text("移动物品") }
|
||||||
}
|
}
|
||||||
|
ArchiveEntry(model, item, state.busy)
|
||||||
}
|
}
|
||||||
HorizontalDivider()
|
HorizontalDivider()
|
||||||
Text("移位记录", style = MaterialTheme.typography.titleMedium)
|
Text("移位记录", style = MaterialTheme.typography.titleMedium)
|
||||||
|
|
@ -226,6 +233,7 @@ private fun AddItem(state: AtlasState, model: AtlasViewModel, modifier: Modifier
|
||||||
}
|
}
|
||||||
val place = state.places.firstOrNull { it.id == placeId }
|
val place = state.places.firstOrNull { it.id == placeId }
|
||||||
Form(modifier) {
|
Form(modifier) {
|
||||||
|
SmartCaptureEntry(state, model)
|
||||||
ItemNameAndQuantity(title, { title = it }, quantity, { quantity = it }, !state.busy)
|
ItemNameAndQuantity(title, { title = it }, quantity, { quantity = it }, !state.busy)
|
||||||
val pickedLabel = place?.path ?: if (placeId == null) "未设置位置" else "所选位置已不可用"
|
val pickedLabel = place?.path ?: if (placeId == null) "未设置位置" else "所选位置已不可用"
|
||||||
PlacePicker(state.places, pickedLabel, !state.busy) { placeId = it?.id }
|
PlacePicker(state.places, pickedLabel, !state.busy) { placeId = it?.id }
|
||||||
|
|
@ -320,7 +328,7 @@ private fun WriteStatus(state: AtlasState, model: AtlasViewModel) {
|
||||||
}
|
}
|
||||||
|
|
||||||
@Composable
|
@Composable
|
||||||
private fun PlacePicker(places: List<Place>, label: String, enabled: Boolean, onSelect: (Place?) -> Unit) {
|
internal fun PlacePicker(places: List<Place>, label: String, enabled: Boolean, onSelect: (Place?) -> Unit) {
|
||||||
var showPicker by remember { mutableStateOf(false) }
|
var showPicker by remember { mutableStateOf(false) }
|
||||||
OutlinedButton(onClick = { showPicker = true }, enabled = enabled, modifier = Modifier.fillMaxWidth()) {
|
OutlinedButton(onClick = { showPicker = true }, enabled = enabled, modifier = Modifier.fillMaxWidth()) {
|
||||||
Text(label)
|
Text(label)
|
||||||
|
|
|
||||||
|
|
@ -0,0 +1,195 @@
|
||||||
|
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.Row
|
||||||
|
import androidx.compose.foundation.layout.fillMaxWidth
|
||||||
|
import androidx.compose.foundation.layout.padding
|
||||||
|
import androidx.compose.foundation.lazy.LazyColumn
|
||||||
|
import androidx.compose.foundation.lazy.items
|
||||||
|
import androidx.compose.material3.AlertDialog
|
||||||
|
import androidx.compose.material3.DropdownMenu
|
||||||
|
import androidx.compose.material3.DropdownMenuItem
|
||||||
|
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.Text
|
||||||
|
import androidx.compose.material3.TextButton
|
||||||
|
import androidx.compose.runtime.Composable
|
||||||
|
import androidx.compose.runtime.LaunchedEffect
|
||||||
|
import androidx.compose.runtime.getValue
|
||||||
|
import androidx.compose.runtime.mutableStateOf
|
||||||
|
import androidx.compose.runtime.remember
|
||||||
|
import androidx.compose.runtime.rememberCoroutineScope
|
||||||
|
import androidx.compose.runtime.setValue
|
||||||
|
import androidx.compose.ui.Modifier
|
||||||
|
import androidx.compose.ui.unit.dp
|
||||||
|
import java.math.BigDecimal
|
||||||
|
import java.text.NumberFormat
|
||||||
|
import java.util.Locale
|
||||||
|
import kotlinx.coroutines.CancellationException
|
||||||
|
import kotlinx.coroutines.launch
|
||||||
|
|
||||||
|
@Composable
|
||||||
|
internal fun Mine(model: AtlasViewModel, space: Space) {
|
||||||
|
val scope = rememberCoroutineScope()
|
||||||
|
var profile by remember { mutableStateOf<AccountProfile?>(null) }
|
||||||
|
var summary by remember { mutableStateOf<AccountSummary?>(null) }
|
||||||
|
var favorites by remember(space.id) { mutableStateOf<List<Item>?>(null) }
|
||||||
|
var more by remember(space.id) { mutableStateOf(false) }
|
||||||
|
var editing by remember { mutableStateOf(false) }
|
||||||
|
var busy by remember { mutableStateOf(false) }
|
||||||
|
var error by remember { mutableStateOf<String?>(null) }
|
||||||
|
|
||||||
|
suspend fun run(block: suspend () -> Unit) {
|
||||||
|
busy = true
|
||||||
|
error = null
|
||||||
|
try { block() }
|
||||||
|
catch (failure: Exception) {
|
||||||
|
if (failure is CancellationException) throw failure
|
||||||
|
error = model.requestFailure(failure)
|
||||||
|
} finally { busy = false }
|
||||||
|
}
|
||||||
|
|
||||||
|
suspend fun read() {
|
||||||
|
profile = model.api.profile()
|
||||||
|
summary = model.api.summary()
|
||||||
|
val initial = model.api.search(space, "", favorites = true)
|
||||||
|
favorites = initial
|
||||||
|
more = initial.size == 30
|
||||||
|
}
|
||||||
|
|
||||||
|
LaunchedEffect(space.id) { run { read() } }
|
||||||
|
LazyColumn(verticalArrangement = Arrangement.spacedBy(12.dp)) {
|
||||||
|
item {
|
||||||
|
if (busy) LinearProgressIndicator(Modifier.fillMaxWidth())
|
||||||
|
error?.let {
|
||||||
|
Text(it, color = MaterialTheme.colorScheme.error)
|
||||||
|
TextButton(enabled = !busy, onClick = { scope.launch { run { read() } } }) { Text("重试") }
|
||||||
|
}
|
||||||
|
}
|
||||||
|
profile?.let { user ->
|
||||||
|
item {
|
||||||
|
Text("${user.avatar.symbol} ${user.nickname.ifBlank { user.username }}", style = MaterialTheme.typography.headlineSmall)
|
||||||
|
if (user.signature.isNotBlank()) Text(user.signature, style = MaterialTheme.typography.bodyMedium)
|
||||||
|
TextButton(onClick = { editing = true }, enabled = !busy) { Text("编辑资料") }
|
||||||
|
HorizontalDivider()
|
||||||
|
}
|
||||||
|
}
|
||||||
|
summary?.let { info ->
|
||||||
|
item {
|
||||||
|
Text("物品概览", style = MaterialTheme.typography.titleLarge)
|
||||||
|
val amount = NumberFormat.getCurrencyInstance(Locale.CHINA)
|
||||||
|
.format(BigDecimal(info.totalValueCents).movePointLeft(2))
|
||||||
|
Text("购入总额 $amount")
|
||||||
|
Text("${info.activeItems} 件物品 · ${info.pricedItems} 件已填价格 · ${info.publishedItems} 件已公开")
|
||||||
|
Text("${info.archivedItems} 件已归档", style = MaterialTheme.typography.bodySmall)
|
||||||
|
HorizontalDivider()
|
||||||
|
}
|
||||||
|
}
|
||||||
|
item {
|
||||||
|
Row(horizontalArrangement = Arrangement.spacedBy(8.dp)) {
|
||||||
|
InvitationEntry(model)
|
||||||
|
MembersEntry(model, space)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
item { Text("当前空间的收藏", style = MaterialTheme.typography.titleLarge) }
|
||||||
|
val rows = favorites
|
||||||
|
if (rows?.isEmpty() == true) item { Text("还没有收藏。") }
|
||||||
|
items(rows.orEmpty(), key = Item::id) { item ->
|
||||||
|
Column(Modifier.fillMaxWidth().clickable { model.open(item) }.padding(vertical = 8.dp)) {
|
||||||
|
Text(item.name, style = MaterialTheme.typography.titleMedium)
|
||||||
|
Text(item.locationPath.ifBlank { "未设置位置" })
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if (more) item {
|
||||||
|
TextButton(enabled = !busy, onClick = { scope.launch {
|
||||||
|
run {
|
||||||
|
val current = favorites.orEmpty()
|
||||||
|
val next = model.api.search(space, "", offset = current.size, favorites = true)
|
||||||
|
favorites = (current + next).distinctBy(Item::id)
|
||||||
|
more = next.size == 30 && current.size + next.size <= 10000
|
||||||
|
}
|
||||||
|
} }) { Text("加载更多收藏") }
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if (editing) profile?.let { current ->
|
||||||
|
ProfileEditor(current, busy, error, close = { editing = false }) { input ->
|
||||||
|
scope.launch { run { profile = model.api.saveProfile(input); editing = false } }
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
@Composable
|
||||||
|
private fun ProfileEditor(
|
||||||
|
profile: AccountProfile, busy: Boolean, error: String?,
|
||||||
|
close: () -> Unit, save: (ProfileInput) -> Unit,
|
||||||
|
) {
|
||||||
|
var nickname by remember { mutableStateOf(profile.nickname) }
|
||||||
|
var signature by remember { mutableStateOf(profile.signature) }
|
||||||
|
var avatar by remember { mutableStateOf(profile.avatar) }
|
||||||
|
var choosing by remember { mutableStateOf(false) }
|
||||||
|
AlertDialog(onDismissRequest = { if (!busy) close() }, title = { Text("编辑资料") },
|
||||||
|
text = {
|
||||||
|
Column(verticalArrangement = Arrangement.spacedBy(8.dp)) {
|
||||||
|
Box {
|
||||||
|
OutlinedButton(enabled = !busy, onClick = { choosing = true }) { Text("头像 ${avatar.label}") }
|
||||||
|
DropdownMenu(choosing, onDismissRequest = { choosing = false }) {
|
||||||
|
Avatar.entries.forEach { choice ->
|
||||||
|
DropdownMenuItem(text = { Text("${choice.symbol} ${choice.label}") }, onClick = {
|
||||||
|
avatar = choice
|
||||||
|
choosing = false
|
||||||
|
})
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
OutlinedTextField(nickname, { nickname = it.take(32) }, enabled = !busy, singleLine = true, label = { Text("昵称") })
|
||||||
|
OutlinedTextField(signature, { signature = it.take(100) }, enabled = !busy, singleLine = true, label = { Text("签名") })
|
||||||
|
error?.let { Text(it, color = MaterialTheme.colorScheme.error) }
|
||||||
|
}
|
||||||
|
}, confirmButton = { TextButton(enabled = !busy,
|
||||||
|
onClick = { save(ProfileInput(nickname.trim(), signature.trim(), avatar)) }) { Text("保存资料") } },
|
||||||
|
dismissButton = { TextButton(enabled = !busy, onClick = close) { Text("取消") } })
|
||||||
|
}
|
||||||
|
|
||||||
|
@Composable
|
||||||
|
internal fun ItemReview(model: AtlasViewModel, item: Item, preference: ItemPreference, busy: Boolean) {
|
||||||
|
var reviewing by remember(item.id) { mutableStateOf(false) }
|
||||||
|
Row(horizontalArrangement = Arrangement.spacedBy(8.dp)) {
|
||||||
|
OutlinedButton(enabled = !busy, onClick = {
|
||||||
|
model.savePreference(item, preference.copy(favorite = !preference.favorite))
|
||||||
|
}) { Text(if (preference.favorite) "已收藏" else "收藏") }
|
||||||
|
OutlinedButton(enabled = !busy, onClick = { reviewing = true }) {
|
||||||
|
Text(preference.rating?.let { "我的评价 · $it 星" } ?: "我的评价")
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if (reviewing) {
|
||||||
|
var rating by remember { mutableStateOf(preference.rating) }
|
||||||
|
var note by remember { mutableStateOf(preference.note.orEmpty()) }
|
||||||
|
AlertDialog(onDismissRequest = { reviewing = false }, title = { Text("我的评价") },
|
||||||
|
text = {
|
||||||
|
Column(verticalArrangement = Arrangement.spacedBy(8.dp)) {
|
||||||
|
RatingPicker(rating, true) { rating = it }
|
||||||
|
OutlinedTextField(note, { note = it.take(500) }, label = { Text("短评") })
|
||||||
|
}
|
||||||
|
}, confirmButton = { TextButton(onClick = {
|
||||||
|
model.savePreference(item, preference.copy(rating = rating, note = note.trim().ifBlank { null }))
|
||||||
|
reviewing = false
|
||||||
|
}) { Text("保存评价") } },
|
||||||
|
dismissButton = { TextButton(onClick = { reviewing = false }) { Text("取消") } })
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
@Composable
|
||||||
|
internal fun ArchiveEntry(model: AtlasViewModel, item: Item, busy: Boolean) {
|
||||||
|
var confirm by remember(item.id) { mutableStateOf(false) }
|
||||||
|
TextButton(enabled = !busy, onClick = { confirm = true }) { Text("归档物品", color = MaterialTheme.colorScheme.error) }
|
||||||
|
if (confirm) AlertDialog(onDismissRequest = { confirm = false }, title = { Text("归档这件物品?") },
|
||||||
|
text = { Text("物品将从找物和公开分享里移除。") },
|
||||||
|
confirmButton = { TextButton(onClick = { confirm = false; model.archive(item) }) { Text("确认归档") } },
|
||||||
|
dismissButton = { TextButton(onClick = { confirm = false }) { Text("取消") } })
|
||||||
|
}
|
||||||
|
|
@ -0,0 +1,108 @@
|
||||||
|
package com.tutudog.itematlas
|
||||||
|
|
||||||
|
import java.util.UUID
|
||||||
|
import kotlin.math.roundToInt
|
||||||
|
import kotlinx.serialization.Serializable
|
||||||
|
|
||||||
|
@Serializable
|
||||||
|
enum class PlanTemplate(val label: String, val width: Int, val depth: Int, val isRoom: Boolean = false) {
|
||||||
|
LIVING_ROOM("客厅", 4000, 3400, true),
|
||||||
|
BEDROOM("卧室", 3200, 3000, true),
|
||||||
|
STUDY("书房", 3000, 2800, true),
|
||||||
|
KITCHEN("厨房", 2600, 2400, true),
|
||||||
|
BATHROOM("卫生间", 2000, 1800, true),
|
||||||
|
ROOM("房间", 3000, 2800, true),
|
||||||
|
ENTRY("玄关", 2200, 1500),
|
||||||
|
BALCONY("阳台", 2200, 1500),
|
||||||
|
AREA("开放区域", 2000, 1500),
|
||||||
|
SOFA("沙发", 2300, 1400),
|
||||||
|
BED("床", 1600, 2100),
|
||||||
|
DESK("书桌", 1400, 620),
|
||||||
|
TV_STAND("电视柜", 1400, 620),
|
||||||
|
WARDROBE("衣柜", 1600, 650),
|
||||||
|
BOOKCASE("书架", 1100, 450),
|
||||||
|
SHELF("层架", 1100, 450),
|
||||||
|
TABLE("边几", 600, 600),
|
||||||
|
STORAGE_BOX("收纳箱", 500, 450),
|
||||||
|
}
|
||||||
|
|
||||||
|
@Serializable
|
||||||
|
data class PlanGeometry(
|
||||||
|
val template: PlanTemplate, val xMm: Int, val yMm: Int,
|
||||||
|
val widthMm: Int, val depthMm: Int, val rotation: Int = 0,
|
||||||
|
) {
|
||||||
|
val right: Int get() = xMm + widthMm
|
||||||
|
val bottom: Int get() = yMm + depthMm
|
||||||
|
|
||||||
|
fun overlaps(other: PlanGeometry): Boolean =
|
||||||
|
xMm < other.right && other.xMm < right && yMm < other.bottom && other.yMm < bottom
|
||||||
|
}
|
||||||
|
|
||||||
|
@Serializable
|
||||||
|
data class PlanLocation(val id: String, val name: String, val geometry: PlanGeometry? = null)
|
||||||
|
|
||||||
|
@Serializable
|
||||||
|
data class PlanSnapshot(val version: String, val widthMm: Int, val depthMm: Int, val locations: List<PlanLocation>) {
|
||||||
|
fun origin(shape: PlanGeometry, x: Float, y: Float): PlanGeometry = shape.copy(
|
||||||
|
xMm = snap(x).coerceIn(0, widthMm - shape.widthMm),
|
||||||
|
yMm = snap(y).coerceIn(0, depthMm - shape.depthMm),
|
||||||
|
)
|
||||||
|
|
||||||
|
fun place(template: PlanTemplate, working: List<PlanLocation>): PlanGeometry? {
|
||||||
|
val width = template.width.coerceAtMost(widthMm)
|
||||||
|
val depth = template.depth.coerceAtMost(depthMm)
|
||||||
|
val shape = PlanGeometry(template, 0, 0, width, depth)
|
||||||
|
val painted = working.mapNotNull(PlanLocation::geometry)
|
||||||
|
for (y in 0..depthMm - depth step PLAN_GRID_MM) {
|
||||||
|
for (x in 0..widthMm - width step PLAN_GRID_MM) {
|
||||||
|
val candidate = shape.copy(xMm = x, yMm = y)
|
||||||
|
if (painted.none(candidate::overlaps)) return candidate
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return shape.takeUnless { template.isRoom }
|
||||||
|
}
|
||||||
|
|
||||||
|
fun save(parentId: String?, working: List<PlanLocation>): PlanSave = PlanSave(
|
||||||
|
parentId, version, working.mapNotNull { slot ->
|
||||||
|
slot.geometry?.let { shape ->
|
||||||
|
PlanPlacement(slot.id, slot.name.takeIf { locations.none { old -> old.id == slot.id } }, shape)
|
||||||
|
}
|
||||||
|
},
|
||||||
|
)
|
||||||
|
}
|
||||||
|
|
||||||
|
@Serializable
|
||||||
|
data class PlanPlacement(val id: String, val newName: String?, val geometry: PlanGeometry)
|
||||||
|
|
||||||
|
@Serializable
|
||||||
|
data class PlanSave(val parentId: String?, val version: String, val placements: List<PlanPlacement>)
|
||||||
|
|
||||||
|
@Serializable
|
||||||
|
data class PlanPrompt(val parentId: String?, val version: String, val description: String)
|
||||||
|
|
||||||
|
@Serializable
|
||||||
|
data class PlanSuggestion(
|
||||||
|
val locationId: String? = null, val name: String, val geometry: PlanGeometry? = null, val note: String = "",
|
||||||
|
)
|
||||||
|
|
||||||
|
@Serializable
|
||||||
|
data class PlanSuggestions(val changes: List<PlanSuggestion>)
|
||||||
|
|
||||||
|
internal const val PLAN_GRID_MM = 100
|
||||||
|
|
||||||
|
private fun snap(value: Float): Int = (value / PLAN_GRID_MM).roundToInt() * PLAN_GRID_MM
|
||||||
|
|
||||||
|
internal fun applyPlanSuggestions(
|
||||||
|
source: List<PlanLocation>, proposed: List<PlanSuggestion>, ids: List<String>,
|
||||||
|
): List<PlanLocation> {
|
||||||
|
val result = source.associateBy(PlanLocation::id).toMutableMap()
|
||||||
|
for ((index, change) in proposed.withIndex()) {
|
||||||
|
val shape = change.geometry ?: continue
|
||||||
|
val previous = result[change.locationId]
|
||||||
|
val id = previous?.id ?: ids[index]
|
||||||
|
result[id] = PlanLocation(id, previous?.name ?: change.name, shape)
|
||||||
|
}
|
||||||
|
return result.values.toList()
|
||||||
|
}
|
||||||
|
|
||||||
|
internal fun newPlanId(): String = UUID.randomUUID().toString()
|
||||||
|
|
@ -0,0 +1,216 @@
|
||||||
|
package com.tutudog.itematlas
|
||||||
|
|
||||||
|
import androidx.compose.foundation.layout.Arrangement
|
||||||
|
import androidx.compose.foundation.layout.Column
|
||||||
|
import androidx.compose.foundation.layout.Row
|
||||||
|
import androidx.compose.foundation.layout.fillMaxSize
|
||||||
|
import androidx.compose.foundation.layout.fillMaxWidth
|
||||||
|
import androidx.compose.foundation.layout.padding
|
||||||
|
import androidx.compose.foundation.rememberScrollState
|
||||||
|
import androidx.compose.foundation.text.KeyboardOptions
|
||||||
|
import androidx.compose.foundation.verticalScroll
|
||||||
|
import androidx.compose.material3.Button
|
||||||
|
import androidx.compose.material3.Checkbox
|
||||||
|
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.Surface
|
||||||
|
import androidx.compose.material3.Text
|
||||||
|
import androidx.compose.material3.TextButton
|
||||||
|
import androidx.compose.runtime.Composable
|
||||||
|
import androidx.compose.runtime.LaunchedEffect
|
||||||
|
import androidx.compose.runtime.getValue
|
||||||
|
import androidx.compose.runtime.mutableStateOf
|
||||||
|
import androidx.compose.runtime.remember
|
||||||
|
import androidx.compose.runtime.rememberCoroutineScope
|
||||||
|
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.text.input.KeyboardType
|
||||||
|
import androidx.compose.ui.unit.dp
|
||||||
|
import androidx.compose.ui.window.Dialog
|
||||||
|
import androidx.compose.ui.window.DialogProperties
|
||||||
|
import kotlinx.coroutines.CancellationException
|
||||||
|
import kotlinx.coroutines.delay
|
||||||
|
import kotlinx.coroutines.launch
|
||||||
|
import kotlinx.serialization.Serializable
|
||||||
|
|
||||||
|
@Serializable data class ModelProvider(val id: String, val name: String, val status: String)
|
||||||
|
@Serializable data class DraftInput(val text: String, val source: String)
|
||||||
|
@Serializable data class CaptureCandidate(val name: String, val quantity: Int? = null, val action: String, val location: String? = null)
|
||||||
|
@Serializable data class CaptureDraft(val id: String, val version: Int, val status: String, val candidates: List<CaptureCandidate>)
|
||||||
|
@Serializable data class DraftConfirmation(val version: Int, val items: List<ItemInput>, val automatic: Boolean = false)
|
||||||
|
@Serializable data class CaptureOperation(val id: String, val status: String)
|
||||||
|
|
||||||
|
private data class DraftRow(
|
||||||
|
val enabled: Boolean, val name: String, val quantity: String, val placeId: String?, val hint: String?,
|
||||||
|
)
|
||||||
|
|
||||||
|
@Composable
|
||||||
|
internal fun SmartCaptureEntry(state: AtlasState, model: AtlasViewModel) {
|
||||||
|
val space = state.space?.takeIf(Space::writable) ?: return
|
||||||
|
var open by rememberSaveable(space.id) { mutableStateOf(false) }
|
||||||
|
var text by rememberSaveable(space.id) { mutableStateOf("") }
|
||||||
|
var fromVoice by rememberSaveable(space.id) { mutableStateOf(false) }
|
||||||
|
OutlinedButton(enabled = !state.busy, onClick = { open = true }) { Text("智能录入") }
|
||||||
|
if (open) SmartCapture(model, space, state.places, state.locationId.takeIf { state.tab == InventoryTab.Locations },
|
||||||
|
text, fromVoice, { updated, voice -> text = updated; fromVoice = voice }, onClose = { open = false }, onSaved = {
|
||||||
|
open = false
|
||||||
|
text = ""
|
||||||
|
fromVoice = false
|
||||||
|
model.back()
|
||||||
|
})
|
||||||
|
}
|
||||||
|
|
||||||
|
@Composable
|
||||||
|
private fun SmartCapture(
|
||||||
|
model: AtlasViewModel, space: Space, places: List<Place>, defaultPlace: String?,
|
||||||
|
text: String, fromVoice: Boolean, update: (String, Boolean) -> Unit, onClose: () -> Unit, onSaved: () -> Unit,
|
||||||
|
) {
|
||||||
|
val scope = rememberCoroutineScope()
|
||||||
|
var providers by remember { mutableStateOf(emptyList<ModelProvider>()) }
|
||||||
|
var draft by remember { mutableStateOf<CaptureDraft?>(null) }
|
||||||
|
var rows by remember { mutableStateOf(emptyList<DraftRow>()) }
|
||||||
|
var operationId by rememberSaveable { mutableStateOf<String?>(null) }
|
||||||
|
var operationState by rememberSaveable { mutableStateOf<String?>(null) }
|
||||||
|
var busy by remember { mutableStateOf(false) }
|
||||||
|
var recording by remember { mutableStateOf(false) }
|
||||||
|
var error by remember { mutableStateOf<String?>(null) }
|
||||||
|
|
||||||
|
fun close() { if (!busy && operationId == null) onClose() }
|
||||||
|
|
||||||
|
fun editText(next: String, voice: Boolean) {
|
||||||
|
update(next.take(4000), voice)
|
||||||
|
draft = null
|
||||||
|
rows = emptyList()
|
||||||
|
}
|
||||||
|
|
||||||
|
fun run(block: suspend () -> Unit) {
|
||||||
|
if (busy) return
|
||||||
|
error = null
|
||||||
|
busy = true
|
||||||
|
scope.launch {
|
||||||
|
try { block() }
|
||||||
|
catch (failure: Exception) {
|
||||||
|
if (failure is CancellationException) throw failure
|
||||||
|
error = model.requestFailure(failure)
|
||||||
|
} finally { busy = false }
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
suspend fun poll(first: CaptureOperation) {
|
||||||
|
var at = first
|
||||||
|
repeat(8) { attempt ->
|
||||||
|
operationId = at.id
|
||||||
|
operationState = at.status
|
||||||
|
if (at.status == "COMPLETED") { onSaved(); return }
|
||||||
|
if (at.status in setOf("FAILED", "REJECTED", "NEEDS_REVIEW") || attempt == 7) return
|
||||||
|
delay(500)
|
||||||
|
at = model.api.operation(space, at)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
LaunchedEffect(Unit) {
|
||||||
|
try { providers = model.api.providers() }
|
||||||
|
catch (failure: Exception) {
|
||||||
|
if (failure is CancellationException) throw failure
|
||||||
|
if (failure is ApiError && failure.status == 401) model.requestFailure(failure)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
Dialog(onDismissRequest = ::close, properties = DialogProperties(usePlatformDefaultWidth = false)) {
|
||||||
|
Surface(Modifier.fillMaxSize()) {
|
||||||
|
Column(Modifier.padding(20.dp).verticalScroll(rememberScrollState()),
|
||||||
|
verticalArrangement = Arrangement.spacedBy(12.dp)) {
|
||||||
|
Row(Modifier.fillMaxWidth(), horizontalArrangement = Arrangement.SpaceBetween,
|
||||||
|
verticalAlignment = Alignment.CenterVertically) {
|
||||||
|
Text("智能录入", style = MaterialTheme.typography.titleLarge)
|
||||||
|
TextButton(onClick = ::close, enabled = !busy && operationId == null) { Text("返回手动添加") }
|
||||||
|
}
|
||||||
|
if (busy) LinearProgressIndicator(Modifier.fillMaxWidth())
|
||||||
|
error?.let { Text(it, color = MaterialTheme.colorScheme.error) }
|
||||||
|
val operation = operationId
|
||||||
|
if (operation != null) {
|
||||||
|
Text(when (operationState) {
|
||||||
|
"NEEDS_REVIEW" -> "系统需要核查这次录入。"
|
||||||
|
"REJECTED" -> "录入已被拒绝。请核对空间权限和物品信息。"
|
||||||
|
"FAILED" -> "录入交付失败,可以刷新状态。"
|
||||||
|
else -> "正在保存物品。"
|
||||||
|
})
|
||||||
|
Text("操作编号 $operation", style = MaterialTheme.typography.bodySmall)
|
||||||
|
Row(horizontalArrangement = Arrangement.spacedBy(8.dp)) {
|
||||||
|
OutlinedButton(enabled = !busy, onClick = {
|
||||||
|
run { poll(model.api.operation(space, CaptureOperation(operation, operationState.orEmpty()))) }
|
||||||
|
}) { Text("查询结果") }
|
||||||
|
if (operationState == "NEEDS_REVIEW") {
|
||||||
|
OutlinedButton(enabled = !busy, onClick = {
|
||||||
|
run { poll(model.api.retryDraft(space, CaptureOperation(operation, operationState.orEmpty()))) }
|
||||||
|
}) { Text("重试交付") }
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if (operationState in setOf("FAILED", "REJECTED", "NEEDS_REVIEW")) {
|
||||||
|
TextButton(enabled = !busy, onClick = { onClose() }) { Text("关闭") }
|
||||||
|
}
|
||||||
|
} else {
|
||||||
|
val local = providers.firstOrNull { it.id == "ollama" }
|
||||||
|
if (local != null) Text(if (local.status == "AVAILABLE") "本地模型可用" else "本地模型暂不可用",
|
||||||
|
style = MaterialTheme.typography.labelMedium)
|
||||||
|
OutlinedTextField(text, { editText(it, fromVoice) }, Modifier.fillMaxWidth(),
|
||||||
|
label = { Text("物品和放置位置") }, placeholder = { Text("两根数据线放书房抽屉,备用钥匙先不动") },
|
||||||
|
minLines = 3, maxLines = 7, enabled = !busy && !recording)
|
||||||
|
VoiceInput(!busy, onActive = { recording = it }, onText = { phrase ->
|
||||||
|
editText(listOf(text, phrase).filter(String::isNotBlank).joinToString(","), true)
|
||||||
|
})
|
||||||
|
Button(enabled = !busy && !recording && text.isNotBlank(), onClick = {
|
||||||
|
run {
|
||||||
|
val result = model.api.createDraft(space, DraftInput(text.trim(), if (fromVoice) "VOICE" else "MODEL"))
|
||||||
|
draft = result
|
||||||
|
rows = result.candidates.filter { it.action != "SKIP" }.map { candidate ->
|
||||||
|
val hint = candidate.location?.trim()?.takeIf(String::isNotEmpty)
|
||||||
|
val placeId = hint?.let { value ->
|
||||||
|
(places.singleOrNull { it.path == value } ?: places.singleOrNull { it.name == value })?.id
|
||||||
|
} ?: defaultPlace.takeIf { hint == null }
|
||||||
|
DraftRow(candidate.action == "RECORD", candidate.name, (candidate.quantity ?: 1).toString(), placeId, hint)
|
||||||
|
}
|
||||||
|
if (result.status == "MODEL_UNAVAILABLE") error = "本地模型暂不可用,原文已保留。"
|
||||||
|
else if (rows.isEmpty()) error = "这段内容没有可核对的物品。"
|
||||||
|
}
|
||||||
|
}) { Text("生成草稿") }
|
||||||
|
val ready = draft
|
||||||
|
if (ready != null && rows.isNotEmpty()) {
|
||||||
|
HorizontalDivider()
|
||||||
|
Text("核对要保存的物品", style = MaterialTheme.typography.titleMedium)
|
||||||
|
rows.forEachIndexed { index, row ->
|
||||||
|
fun edit(next: DraftRow) { rows = rows.toMutableList().apply { set(index, next) } }
|
||||||
|
Row(verticalAlignment = Alignment.CenterVertically) {
|
||||||
|
Checkbox(row.enabled, { edit(row.copy(enabled = it)) }, enabled = !busy)
|
||||||
|
OutlinedTextField(row.name, { edit(row.copy(name = it.take(150))) },
|
||||||
|
Modifier.weight(1f), enabled = !busy, singleLine = true, label = { Text("物品名称") })
|
||||||
|
}
|
||||||
|
if (row.enabled) {
|
||||||
|
OutlinedTextField(row.quantity, { edit(row.copy(quantity = it.take(4))) }, Modifier.fillMaxWidth(),
|
||||||
|
enabled = !busy, label = { Text("数量") }, singleLine = true,
|
||||||
|
keyboardOptions = KeyboardOptions(keyboardType = KeyboardType.Number))
|
||||||
|
val picked = places.firstOrNull { it.id == row.placeId }
|
||||||
|
PlacePicker(places, picked?.path ?: "未设置位置", !busy) { edit(row.copy(placeId = it?.id)) }
|
||||||
|
if (picked == null && row.hint != null) Text("原文位置是「${row.hint}」", style = MaterialTheme.typography.bodySmall)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
val enabledRows = rows.filter(DraftRow::enabled)
|
||||||
|
Button(enabled = !busy && !recording && enabledRows.isNotEmpty(), onClick = {
|
||||||
|
if (enabledRows.any { it.name.isBlank() || it.quantity.toIntOrNull() !in 1..9999 }) {
|
||||||
|
error = "请检查物品名称和数量。"
|
||||||
|
} else run {
|
||||||
|
poll(model.api.confirmDraft(space, ready, enabledRows.map {
|
||||||
|
ItemInput(it.name.trim(), it.quantity.toInt(), it.placeId, emptyList(), "")
|
||||||
|
}))
|
||||||
|
}
|
||||||
|
}) { Text("确认保存") }
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
@ -0,0 +1,167 @@
|
||||||
|
package com.tutudog.itematlas
|
||||||
|
|
||||||
|
import android.Manifest
|
||||||
|
import android.content.Intent
|
||||||
|
import android.content.pm.PackageManager
|
||||||
|
import android.os.Build
|
||||||
|
import android.os.Bundle
|
||||||
|
import android.os.SystemClock
|
||||||
|
import android.speech.RecognitionListener
|
||||||
|
import android.speech.RecognizerIntent
|
||||||
|
import android.speech.SpeechRecognizer
|
||||||
|
import androidx.activity.compose.rememberLauncherForActivityResult
|
||||||
|
import androidx.activity.result.contract.ActivityResultContracts
|
||||||
|
import androidx.compose.foundation.layout.Arrangement
|
||||||
|
import androidx.compose.foundation.layout.Column
|
||||||
|
import androidx.compose.material3.MaterialTheme
|
||||||
|
import androidx.compose.material3.OutlinedButton
|
||||||
|
import androidx.compose.material3.Text
|
||||||
|
import androidx.compose.runtime.Composable
|
||||||
|
import androidx.compose.runtime.DisposableEffect
|
||||||
|
import androidx.compose.runtime.LaunchedEffect
|
||||||
|
import androidx.compose.runtime.getValue
|
||||||
|
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.platform.LocalContext
|
||||||
|
import androidx.compose.ui.unit.dp
|
||||||
|
import androidx.core.content.ContextCompat
|
||||||
|
import kotlinx.coroutines.delay
|
||||||
|
import kotlinx.coroutines.launch
|
||||||
|
|
||||||
|
private const val VOICE_SECONDS = 25
|
||||||
|
|
||||||
|
@Composable
|
||||||
|
internal fun VoiceInput(enabled: Boolean, onActive: (Boolean) -> Unit, onText: (String) -> Unit) {
|
||||||
|
val context = LocalContext.current
|
||||||
|
val scope = rememberCoroutineScope()
|
||||||
|
val publish by rememberUpdatedState(onText)
|
||||||
|
val active by rememberUpdatedState(onActive)
|
||||||
|
var recognizer by remember { mutableStateOf<SpeechRecognizer?>(null) }
|
||||||
|
var running by remember { mutableStateOf(false) }
|
||||||
|
var started by remember { mutableStateOf(0L) }
|
||||||
|
var elapsed by remember { mutableStateOf(0) }
|
||||||
|
var preview by remember { mutableStateOf("") }
|
||||||
|
var error by remember { mutableStateOf<String?>(null) }
|
||||||
|
|
||||||
|
fun finish() {
|
||||||
|
val previous = recognizer
|
||||||
|
recognizer = null
|
||||||
|
previous?.destroy()
|
||||||
|
running = false
|
||||||
|
preview = ""
|
||||||
|
active(false)
|
||||||
|
}
|
||||||
|
|
||||||
|
fun stop() {
|
||||||
|
running = false
|
||||||
|
try { recognizer?.stopListening() }
|
||||||
|
catch (_: RuntimeException) { finish() }
|
||||||
|
}
|
||||||
|
|
||||||
|
fun start() {
|
||||||
|
if (Build.VERSION.SDK_INT < 31 || !SpeechRecognizer.isOnDeviceRecognitionAvailable(context)) {
|
||||||
|
error = "这台设备暂不支持本机语音识别,可以继续输入文字。"
|
||||||
|
return
|
||||||
|
}
|
||||||
|
error = null
|
||||||
|
elapsed = 0
|
||||||
|
val engine = try { SpeechRecognizer.createOnDeviceSpeechRecognizer(context) }
|
||||||
|
catch (_: RuntimeException) {
|
||||||
|
error = "本机语音识别暂不可用。"
|
||||||
|
return
|
||||||
|
}
|
||||||
|
val request = Intent(RecognizerIntent.ACTION_RECOGNIZE_SPEECH)
|
||||||
|
.putExtra(RecognizerIntent.EXTRA_LANGUAGE_MODEL, RecognizerIntent.LANGUAGE_MODEL_FREE_FORM)
|
||||||
|
.putExtra(RecognizerIntent.EXTRA_LANGUAGE, "zh-CN")
|
||||||
|
.putExtra(RecognizerIntent.EXTRA_PARTIAL_RESULTS, true)
|
||||||
|
.putExtra(RecognizerIntent.EXTRA_PREFER_OFFLINE, true)
|
||||||
|
recognizer = engine
|
||||||
|
running = true
|
||||||
|
started = SystemClock.elapsedRealtime()
|
||||||
|
active(true)
|
||||||
|
|
||||||
|
fun sentenceReady(text: String) {
|
||||||
|
if (recognizer !== engine) return
|
||||||
|
if (text.isNotBlank()) publish(text)
|
||||||
|
preview = ""
|
||||||
|
if (!running) {
|
||||||
|
finish()
|
||||||
|
return
|
||||||
|
}
|
||||||
|
scope.launch {
|
||||||
|
delay(200)
|
||||||
|
if (recognizer === engine && running) {
|
||||||
|
try { engine.startListening(request) }
|
||||||
|
catch (_: RuntimeException) { finish(); error = "语音识别已停止。" }
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
engine.setRecognitionListener(object : RecognitionListener {
|
||||||
|
override fun onReadyForSpeech(params: Bundle?) {}
|
||||||
|
override fun onBeginningOfSpeech() {}
|
||||||
|
override fun onRmsChanged(rmsdB: Float) {}
|
||||||
|
override fun onBufferReceived(buffer: ByteArray?) {}
|
||||||
|
override fun onEndOfSpeech() {}
|
||||||
|
override fun onEvent(eventType: Int, params: Bundle?) {}
|
||||||
|
override fun onResults(results: Bundle?) {
|
||||||
|
sentenceReady(results?.getStringArrayList(SpeechRecognizer.RESULTS_RECOGNITION)?.firstOrNull() ?: preview)
|
||||||
|
}
|
||||||
|
override fun onPartialResults(partialResults: Bundle?) {
|
||||||
|
if (recognizer === engine) {
|
||||||
|
preview = partialResults?.getStringArrayList(SpeechRecognizer.RESULTS_RECOGNITION)?.firstOrNull().orEmpty()
|
||||||
|
}
|
||||||
|
}
|
||||||
|
override fun onError(code: Int) {
|
||||||
|
if (recognizer !== engine) return
|
||||||
|
if (code == SpeechRecognizer.ERROR_NO_MATCH || code == SpeechRecognizer.ERROR_SPEECH_TIMEOUT) {
|
||||||
|
sentenceReady(preview)
|
||||||
|
} else {
|
||||||
|
if (preview.isNotBlank()) publish(preview)
|
||||||
|
finish()
|
||||||
|
error = "本机转写暂不可用,可以继续输入文字。"
|
||||||
|
}
|
||||||
|
}
|
||||||
|
})
|
||||||
|
try { engine.startListening(request) }
|
||||||
|
catch (_: RuntimeException) { finish(); error = "无法启动本机语音识别。" }
|
||||||
|
}
|
||||||
|
|
||||||
|
val permission = rememberLauncherForActivityResult(ActivityResultContracts.RequestPermission()) { granted ->
|
||||||
|
if (granted) start() else error = "麦克风权限未开启,可以继续输入文字。"
|
||||||
|
}
|
||||||
|
DisposableEffect(Unit) {
|
||||||
|
onDispose { recognizer?.destroy(); active(false) }
|
||||||
|
}
|
||||||
|
LaunchedEffect(running, started) {
|
||||||
|
if (running) {
|
||||||
|
while (elapsed < VOICE_SECONDS) {
|
||||||
|
delay(200)
|
||||||
|
elapsed = ((SystemClock.elapsedRealtime() - started) / 1000).toInt()
|
||||||
|
}
|
||||||
|
stop()
|
||||||
|
}
|
||||||
|
}
|
||||||
|
LaunchedEffect(running, recognizer) {
|
||||||
|
// Some system recognizers offer no final callback when stopped between phrases.
|
||||||
|
if (!running && recognizer != null) {
|
||||||
|
delay(2200)
|
||||||
|
if (preview.isNotBlank()) publish(preview)
|
||||||
|
finish()
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
Column(verticalArrangement = Arrangement.spacedBy(4.dp)) {
|
||||||
|
OutlinedButton(enabled = enabled && (running || recognizer == null), onClick = {
|
||||||
|
if (running) stop()
|
||||||
|
else if (ContextCompat.checkSelfPermission(context, Manifest.permission.RECORD_AUDIO) == PackageManager.PERMISSION_GRANTED) {
|
||||||
|
start()
|
||||||
|
} else permission.launch(Manifest.permission.RECORD_AUDIO)
|
||||||
|
}) { Text(if (running) "停止录音 · $elapsed / $VOICE_SECONDS 秒" else "语音输入") }
|
||||||
|
if (preview.isNotBlank()) Text(preview, style = MaterialTheme.typography.bodySmall)
|
||||||
|
error?.let { Text(it, style = MaterialTheme.typography.bodySmall, color = MaterialTheme.colorScheme.error) }
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
@ -0,0 +1,4 @@
|
||||||
|
<?xml version="1.0" encoding="utf-8"?>
|
||||||
|
<paths>
|
||||||
|
<cache-path name="camera" path="photo-captures/" />
|
||||||
|
</paths>
|
||||||
|
|
@ -0,0 +1,18 @@
|
||||||
|
package com.tutudog.itematlas.inventory;
|
||||||
|
|
||||||
|
import org.springframework.http.CacheControl;
|
||||||
|
import org.springframework.http.ResponseEntity;
|
||||||
|
import org.springframework.web.bind.annotation.GetMapping;
|
||||||
|
import org.springframework.web.bind.annotation.RestController;
|
||||||
|
|
||||||
|
@RestController
|
||||||
|
class MediaAdminController {
|
||||||
|
private final PhotoService photos;
|
||||||
|
|
||||||
|
MediaAdminController(PhotoService photos) { this.photos = photos; }
|
||||||
|
|
||||||
|
@GetMapping("/api/admin/media-cleanup")
|
||||||
|
ResponseEntity<PhotoService.CleanupStatus> cleanupStatus() {
|
||||||
|
return ResponseEntity.ok().cacheControl(CacheControl.noStore()).body(photos.cleanupStatus());
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
@ -4,6 +4,8 @@ import static org.springframework.http.HttpStatus.*;
|
||||||
|
|
||||||
import io.micrometer.core.instrument.MeterRegistry;
|
import io.micrometer.core.instrument.MeterRegistry;
|
||||||
import java.sql.Types;
|
import java.sql.Types;
|
||||||
|
import java.time.Instant;
|
||||||
|
import java.time.OffsetDateTime;
|
||||||
import java.util.List;
|
import java.util.List;
|
||||||
import java.util.Optional;
|
import java.util.Optional;
|
||||||
import java.util.UUID;
|
import java.util.UUID;
|
||||||
|
|
@ -41,6 +43,7 @@ class PhotoService {
|
||||||
}
|
}
|
||||||
|
|
||||||
record Photo(UUID id) {}
|
record Photo(UUID id) {}
|
||||||
|
record CleanupStatus(boolean workerEnabled, long due, long scheduled, long retrying, Instant oldestDueAt) {}
|
||||||
private record Cleanup(String prefix, int attempts) {}
|
private record Cleanup(String prefix, int attempts) {}
|
||||||
|
|
||||||
enum Target {
|
enum Target {
|
||||||
|
|
@ -155,6 +158,20 @@ class PhotoService {
|
||||||
.param("house", household).param("entity", entity).param("id", id).update();
|
.param("house", household).param("entity", entity).param("id", id).update();
|
||||||
}
|
}
|
||||||
|
|
||||||
|
CleanupStatus cleanupStatus() {
|
||||||
|
return db.sql("""
|
||||||
|
SELECT count(*) FILTER (WHERE due_at <= now()) AS due,
|
||||||
|
count(*) FILTER (WHERE due_at > now()) AS scheduled,
|
||||||
|
count(*) FILTER (WHERE attempts > 0) AS retrying,
|
||||||
|
min(due_at) FILTER (WHERE due_at <= now()) AS oldest_due
|
||||||
|
FROM media_cleanup
|
||||||
|
""").query((row, index) -> {
|
||||||
|
var oldest = row.getObject("oldest_due", OffsetDateTime.class);
|
||||||
|
return new CleanupStatus(storage != null, row.getLong("due"), row.getLong("scheduled"),
|
||||||
|
row.getLong("retrying"), oldest == null ? null : oldest.toInstant());
|
||||||
|
}).single();
|
||||||
|
}
|
||||||
|
|
||||||
@Scheduled(fixedDelay = 2000)
|
@Scheduled(fixedDelay = 2000)
|
||||||
void processCleanup() {
|
void processCleanup() {
|
||||||
if (storage == null) { return; }
|
if (storage == null) { return; }
|
||||||
|
|
|
||||||
|
|
@ -26,12 +26,12 @@ namespace=item-atlas-admin-preview
|
||||||
secret_dir=/path/on/ssd/item-atlas-admin-preview
|
secret_dir=/path/on/ssd/item-atlas-admin-preview
|
||||||
|
|
||||||
mvn -B -ntp -f backend/pom.xml -pl inventory-service -am package
|
mvn -B -ntp -f backend/pom.xml -pl inventory-service -am package
|
||||||
docker build -t item-atlas-inventory-service:admin-preview-0.1.2 backend/inventory-service
|
docker build -t item-atlas-inventory-service:admin-preview-0.1.3 backend/inventory-service
|
||||||
docker build --build-arg VITE_OIDC_URL=/auth \
|
docker build --build-arg VITE_OIDC_URL=/auth \
|
||||||
--build-arg VITE_OIDC_REALM=item-atlas-admin-preview \
|
--build-arg VITE_OIDC_REALM=item-atlas-admin-preview \
|
||||||
-t item-atlas-admin:admin-preview-0.1.2 apps/admin
|
-t item-atlas-admin:admin-preview-0.1.3 apps/admin
|
||||||
kind load docker-image --name "$kind_cluster" \
|
kind load docker-image --name "$kind_cluster" \
|
||||||
item-atlas-inventory-service:admin-preview-0.1.2 item-atlas-admin:admin-preview-0.1.2
|
item-atlas-inventory-service:admin-preview-0.1.3 item-atlas-admin:admin-preview-0.1.3
|
||||||
|
|
||||||
python3 deploy/admin-preview/prepare-secrets.py "$secret_dir"
|
python3 deploy/admin-preview/prepare-secrets.py "$secret_dir"
|
||||||
kubectl --context "$context" create namespace "$namespace"
|
kubectl --context "$context" create namespace "$namespace"
|
||||||
|
|
@ -54,6 +54,8 @@ kubectl --context "$context" -n "$namespace" port-forward --address 127.0.0.1 sv
|
||||||
|
|
||||||
打开 [管理后台](http://127.0.0.1:18482/)。管理员可以分页查空间、按名称或完整 ID 定位、查看物品和照片数量。普通账号登录后会看到权限提示。删除请使用专用测试空间,提交后打开「删除记录」,按空间 ID 核对操作人和时间。对应数据保存在 `space_admin_action`。照片记录被删除时,数据库触发器会在同一个事务登记 `media_cleanup`。本预览用于核对队列写入,真实对象清理由 [对象存储冒烟脚本](../../backend/tests/media_smoke.py) 在带存储的环境验收。
|
打开 [管理后台](http://127.0.0.1:18482/)。管理员可以分页查空间、按名称或完整 ID 定位、查看物品和照片数量。普通账号登录后会看到权限提示。删除请使用专用测试空间,提交后打开「删除记录」,按空间 ID 核对操作人和时间。对应数据保存在 `space_admin_action`。照片记录被删除时,数据库触发器会在同一个事务登记 `media_cleanup`。本预览用于核对队列写入,真实对象清理由 [对象存储冒烟脚本](../../backend/tests/media_smoke.py) 在带存储的环境验收。
|
||||||
|
|
||||||
|
打开「图片清理」检查队列统计。本机预览会标明没有配置图片存储。真实存储环境持续出现待执行或重试时,先核对最早待执行时间,再从物品服务日志查清理重试及对象存储请求耗时。更新此模块时,先交付支持该接口的物品服务,再更新 Web 镜像。
|
||||||
|
|
||||||
页面打不开先查 `/healthz` 和端口转发。浏览器返回登录页时看 Keycloak 回调地址和 Nginx `/auth` 路由。管理 API 返回 `401` 时核对 issuer、JWKS 和有效期,返回 `403` 时核对客户端和管理员角色。物品服务启动时 Flyway 会等待数据库,持续失败时查看 PVC、PostgreSQL 日志及 Flyway 日志。后台 Nginx 的访问日志保留路径、状态码与响应耗时,省略包含授权码的查询参数。
|
页面打不开先查 `/healthz` 和端口转发。浏览器返回登录页时看 Keycloak 回调地址和 Nginx `/auth` 路由。管理 API 返回 `401` 时核对 issuer、JWKS 和有效期,返回 `403` 时核对客户端和管理员角色。物品服务启动时 Flyway 会等待数据库,持续失败时查看 PVC、PostgreSQL 日志及 Flyway 日志。后台 Nginx 的访问日志保留路径、状态码与响应耗时,省略包含授权码的查询参数。
|
||||||
|
|
||||||
更新后台 Pod 后端口转发会断开,重新运行 `kubectl port-forward` 即可。停止转发后入口关闭,预览数据库保留在 PVC 中。 [端口转发](https://kubernetes.io/docs/reference/kubectl/generated/kubectl_port-forward/) · [Keycloak hostname](https://www.keycloak.org/server/hostname) · [Spring Boot Flyway 配置](https://docs.spring.io/spring-boot/4.0/appendix/application-properties/#application-properties.data-migration)
|
更新后台 Pod 后端口转发会断开,重新运行 `kubectl port-forward` 即可。停止转发后入口关闭,预览数据库保留在 PVC 中。 [端口转发](https://kubernetes.io/docs/reference/kubectl/generated/kubectl_port-forward/) · [Keycloak hostname](https://www.keycloak.org/server/hostname) · [Spring Boot Flyway 配置](https://docs.spring.io/spring-boot/4.0/appendix/application-properties/#application-properties.data-migration)
|
||||||
|
|
|
||||||
|
|
@ -23,7 +23,7 @@ spec:
|
||||||
automountServiceAccountToken: false
|
automountServiceAccountToken: false
|
||||||
containers:
|
containers:
|
||||||
- name: inventory
|
- name: inventory
|
||||||
image: item-atlas-inventory-service:admin-preview-0.1.2
|
image: item-atlas-inventory-service:admin-preview-0.1.3
|
||||||
imagePullPolicy: Never
|
imagePullPolicy: Never
|
||||||
envFrom:
|
envFrom:
|
||||||
- secretRef: {name: atlas-admin-inventory}
|
- secretRef: {name: atlas-admin-inventory}
|
||||||
|
|
|
||||||
|
|
@ -42,7 +42,7 @@ spec:
|
||||||
automountServiceAccountToken: false
|
automountServiceAccountToken: false
|
||||||
containers:
|
containers:
|
||||||
- name: nginx
|
- name: nginx
|
||||||
image: item-atlas-admin:admin-preview-0.1.2
|
image: item-atlas-admin:admin-preview-0.1.3
|
||||||
imagePullPolicy: Never
|
imagePullPolicy: Never
|
||||||
env:
|
env:
|
||||||
- {name: ATLAS_GATEWAY_URL, value: 'http://atlas-admin-gateway:8080'}
|
- {name: ATLAS_GATEWAY_URL, value: 'http://atlas-admin-gateway:8080'}
|
||||||
|
|
|
||||||
|
|
@ -6,9 +6,9 @@
|
||||||
| --- | --- | --- |
|
| --- | --- | --- |
|
||||||
| H5 | uni-app(Vue 3、TypeScript、Vite),使用 DCloud 的 CLI 模板 | [移动网页](../../apps/h5/README.md)面向手机找物、照片裁剪和快速录入。构建 H5 静态文件,由独立 Nginx 镜像托管。 |
|
| H5 | uni-app(Vue 3、TypeScript、Vite),使用 DCloud 的 CLI 模板 | [移动网页](../../apps/h5/README.md)面向手机找物、照片裁剪和快速录入。构建 H5 静态文件,由独立 Nginx 镜像托管。 |
|
||||||
| PC 网页 | Vue 3、TypeScript、Vite、Vue Router | [桌面工作台](../../apps/pc/README.md)支持搜索、物品录入、移位和两级平面图。独立 Nginx 镜像。 |
|
| PC 网页 | Vue 3、TypeScript、Vite、Vue Router | [桌面工作台](../../apps/pc/README.md)支持搜索、物品录入、移位和两级平面图。独立 Nginx 镜像。 |
|
||||||
| 管理后台 | Vue 3、TypeScript、Vite、Element Plus | [管理后台](../../apps/admin/README.md)支持查找和删除空间,以及按空间 ID 查看管理员删除记录。独立 Nginx 镜像。其他管理模块有多页路由需求时接入 Vue Router。 |
|
| 管理后台 | Vue 3、TypeScript、Vite、Element Plus | [管理后台](../../apps/admin/README.md)支持查找和删除空间、审计和图片清理队列。独立 Nginx 镜像。 |
|
||||||
| iOS | Swift、SwiftUI,最低 iOS 17 | [iOS 应用](../../apps/ios/README.md)接入账号、空间、物品、草稿和相册上传。拍照和录音按后续原生端验收范围补齐。 |
|
| iOS | Swift、SwiftUI,最低 iOS 17 | [iOS 应用](../../apps/ios/README.md)接入账号、空间、物品、草稿和相册上传。拍照和录音按后续原生端验收范围补齐。 |
|
||||||
| Android | Kotlin、Jetpack Compose | [Android 应用](../../apps/android/README.md)使用 Gradle,最低 Android 8.0。首版接入原生会话、空间、找物、录入和移位。 |
|
| Android | Kotlin、Jetpack Compose | [Android 应用](../../apps/android/README.md)使用 Gradle,最低 Android 8.0。支持空间和成员、物品照片、找物、智能录入、平面图、个人收藏及社区。 |
|
||||||
|
|
||||||
H5 选 uni-app 是为了用贴合移动端的组件和构建方式。正式交付范围只包含网页。微信小程序本期不列入需求、目录或构建目标。PC 和后台要处理高密度列表、桌面键盘交互以及表单,用标准 Vue 网页工程。Web 各端共享合适的 API 类型、校验和文案,H5 的 uni-app 组件单独维护。 [uni-app CLI](https://uniapp.dcloud.net.cn/worktile/CLI.html) · [uni-app Vue 3 TypeScript 模板](https://uniapp.dcloud.net.cn/quickstart-cli.html) · [Vue TypeScript](https://vuejs.org/guide/typescript/overview) · [Vue Router](https://router.vuejs.org/) · [Element Plus](https://element-plus.org/en-US/guide/quickstart)
|
H5 选 uni-app 是为了用贴合移动端的组件和构建方式。正式交付范围只包含网页。微信小程序本期不列入需求、目录或构建目标。PC 和后台要处理高密度列表、桌面键盘交互以及表单,用标准 Vue 网页工程。Web 各端共享合适的 API 类型、校验和文案,H5 的 uni-app 组件单独维护。 [uni-app CLI](https://uniapp.dcloud.net.cn/worktile/CLI.html) · [uni-app Vue 3 TypeScript 模板](https://uniapp.dcloud.net.cn/quickstart-cli.html) · [Vue TypeScript](https://vuejs.org/guide/typescript/overview) · [Vue Router](https://router.vuejs.org/) · [Element Plus](https://element-plus.org/en-US/guide/quickstart)
|
||||||
|
|
||||||
|
|
|
||||||
|
|
@ -1,6 +1,6 @@
|
||||||
# 首版测试用例
|
# 首版测试用例
|
||||||
|
|
||||||
R01–R10 对应[需求与验收](../product/requirements.md)。实现和当前可执行范围见[后端验收清单](backend-readiness.md)。
|
R01–R12 对应[需求与验收](../product/requirements.md)。实现和当前可执行范围见[后端验收清单](backend-readiness.md)。
|
||||||
|
|
||||||
| 用例 | 需求 | 准备与操作 | 预期结果 |
|
| 用例 | 需求 | 准备与操作 | 预期结果 |
|
||||||
| --- | --- | --- | --- |
|
| --- | --- | --- | --- |
|
||||||
|
|
@ -64,5 +64,7 @@ R01–R10 对应[需求与验收](../product/requirements.md)。实现和当前
|
||||||
| TC-53 浏览下级位置的物品 | R04、R11 | 在主卧和主卧抽屉各放一件物品,另在其他房间和无位置各放一件。在主卧详情来回切换物品范围。用只读成员重试,移动或归档抽屉里的物品后刷新。 | 「仅此位置」只显示直接存放的物品。「含下级位置」也显示抽屉里的物品和完整路径,两种范围的分页和缓存独立。其他房间、无位置和归档物品不混入。 |
|
| TC-53 浏览下级位置的物品 | R04、R11 | 在主卧和主卧抽屉各放一件物品,另在其他房间和无位置各放一件。在主卧详情来回切换物品范围。用只读成员重试,移动或归档抽屉里的物品后刷新。 | 「仅此位置」只显示直接存放的物品。「含下级位置」也显示抽屉里的物品和完整路径,两种范围的分页和缓存独立。其他房间、无位置和归档物品不混入。 |
|
||||||
| TC-54 PC 建模和找物联动 | R03、R04、R11、R12 | 在桌面浏览器添加房间,拖动后撤回和重做,改右侧宽深并保存。在室内图添加书桌,再从书桌进入录入,按别名找物并回到平面图定位。另试放弃修改、AI 预览和保存版本冲突。 | 全屋与室内使用各自的布局。操作可撤销,确认保存后重读一致。录入沿用书桌位置,人工保存前 AI 草稿不落库,版本冲突仍保留本地修改。 |
|
| TC-54 PC 建模和找物联动 | R03、R04、R11、R12 | 在桌面浏览器添加房间,拖动后撤回和重做,改右侧宽深并保存。在室内图添加书桌,再从书桌进入录入,按别名找物并回到平面图定位。另试放弃修改、AI 预览和保存版本冲突。 | 全屋与室内使用各自的布局。操作可撤销,确认保存后重读一致。录入沿用书桌位置,人工保存前 AI 草稿不落库,版本冲突仍保留本地修改。 |
|
||||||
| TC-55 H5 录入与照片 | R01、R02、R03、R04、R06、R09 | 在手机浏览器登录,新增房间与收纳盒,从盒子录入物品。选照片裁剪,分别看缩略图和原图。确认移位并搜索别名。再提交带两条物品的文字草稿和检查只读角色。 | 录入带入完整位置,图片按裁剪结果保存。删除后列表移除该照片。已确认的批量草稿可在列表重读。只读角色可找物,详情保留查看入口。 |
|
| TC-55 H5 录入与照片 | R01、R02、R03、R04、R06、R09 | 在手机浏览器登录,新增房间与收纳盒,从盒子录入物品。选照片裁剪,分别看缩略图和原图。确认移位并搜索别名。再提交带两条物品的文字草稿和检查只读角色。 | 录入带入完整位置,图片按裁剪结果保存。删除后列表移除该照片。已确认的批量草稿可在列表重读。只读角色可找物,详情保留查看入口。 |
|
||||||
|
| TC-56 Android 建模与录入 | R02、R06、R11、R12 | 添加全屋房间和室内家具,测试撤回与重做后保存重读。另加一件家具并放弃修改。用文字生成草稿,核对数量和位置后确认。 | 两级布局各自保留版本。放弃修改不创建位置。草稿保存前不新增物品,保存后能按别名或名称找回。 |
|
||||||
|
| TC-57 管理后台图片清理 | R01、R09 | 分别以匿名、普通账号和管理员访问清理状态。在隔离数据库准备已到期、延后和重试任务,核对数量与最早时间。 | 返回 401、403、200。成功响应禁止缓存且只含汇总状态。存储未配置时明确提示清理任务仍在队列。 |
|
||||||
|
|
||||||
[测试与演示计划](plan.md)
|
[测试与演示计划](plan.md)
|
||||||
|
|
|
||||||
Loading…
Reference in New Issue