feat(h5): 增加移动找物和录入工作台
continuous-integration/drone/push Build is passing Details

This commit is contained in:
dongjf 2026-11-28 20:13:03 +08:00
parent 80deca0193
commit 0a7c28c978
28 changed files with 8396 additions and 2 deletions

View File

@ -33,6 +33,11 @@ steps:
commands:
- npm --prefix apps/pc ci --no-audit --no-fund
- npm --prefix apps/pc run build
- name: build-h5
image: node:24-alpine
commands:
- npm --prefix apps/h5 ci --no-audit --no-fund
- npm --prefix apps/h5 run build
trigger:
event: [push, pull_request, tag]

View File

@ -2,7 +2,7 @@
| 路径 | 构建目标 | 制品名 |
| --- | --- | --- |
| `h5/` | uni-app 移动网页 | `item-atlas-h5` |
| [h5/](h5/README.md) | uni-app 移动网页 | `item-atlas-h5` |
| [pc/](pc/README.md) | 桌面浏览器网页 | `item-atlas-pc` |
| [admin/](admin/README.md) | 管理后台 | `item-atlas-admin` |
| [ios/](ios/README.md) | iOS 原生应用 | 见物 |

4
apps/h5/.dockerignore Normal file
View File

@ -0,0 +1,4 @@
node_modules
dist
.env*
.gitignore

4
apps/h5/.gitignore vendored Normal file
View File

@ -0,0 +1,4 @@
node_modules/
dist/
.env.local
.env.*.local

11
apps/h5/Dockerfile Normal file
View File

@ -0,0 +1,11 @@
FROM node:24-alpine AS build
WORKDIR /app
COPY package.json package-lock.json ./
RUN npm ci --no-audit --no-fund
COPY . .
RUN npm run build
FROM nginx:1.31-alpine
ENV ATLAS_GATEWAY_URL=http://item-atlas-gateway:8080
COPY nginx.conf.template /etc/nginx/templates/default.conf.template
COPY --from=build /app/dist/build/h5 /usr/share/nginx/html

27
apps/h5/README.md Normal file
View File

@ -0,0 +1,27 @@
# 见物移动网页
在手机浏览器中使用现有见物账号,空间、位置和物品与 iOS 和 PC 共用。找物支持按名称、别名和位置搜。位置页可以逐层查看,已有下级时可汇总其中的物品。录入提供表单和文字批量草稿,存放位置可留空。
物品详情支持编辑、移位、收藏及照片。拍照和相册统一进入裁剪,输入上限 30 MiB,输出最长边 1440 像素、上限 5 MiB。上传后显示服务端的缩略图,点开读取原图。照片写入、删除和清理走现有物品接口。能否直接调起摄像头取决于浏览器和设备。
## 本地启动
使用 Node.js 24。工作目录为仓库根目录。
```sh
npm --prefix apps/h5 ci
npm --prefix apps/h5 run dev -- --port 4180
```
打开 `http://127.0.0.1:4180`。开发代理默认为已开通的 PC 公网入口,也可以用 `ATLAS_GATEWAY_URL` 指定目标网关。会话保留在页面内存中,整页刷新后重新登录。
## 构建镜像
```sh
npm --prefix apps/h5 run build
docker build -t item-atlas-h5:0.1.0 apps/h5
```
产物位于 `dist/build/h5`,路由使用 URL 的片段。Nginx 容器监听 8080,健康检查用 `/healthz`,通过同源 `/api` 访问内部网关。Drone 的 `build-h5` 步骤执行依赖锁定和构建检查。
[H5 工程模板](https://uniapp.dcloud.net.cn/quickstart-cli.html) · [客户端架构](../../docs/architecture/clients.md)

14
apps/h5/index.html Normal file
View File

@ -0,0 +1,14 @@
<!doctype html>
<html lang="zh-CN">
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1, viewport-fit=cover" />
<meta name="theme-color" content="#f5f7f4" />
<link rel="icon" href="/static/brand.png" />
<title>见物</title>
</head>
<body>
<div id="app"></div>
<script type="module" src="/src/main.ts"></script>
</body>
</html>

View File

@ -0,0 +1,24 @@
server {
listen 8080;
root /usr/share/nginx/html;
client_max_body_size 6m;
location = /healthz { return 200; }
location = /api/admin { return 404; }
location ^~ /api/admin/ { return 404; }
location /api/ {
proxy_pass ${ATLAS_GATEWAY_URL};
proxy_ssl_server_name on;
proxy_set_header Host $proxy_host;
proxy_set_header X-Forwarded-Proto $scheme;
proxy_read_timeout 85s;
}
location /assets/ {
try_files $uri =404;
add_header Cache-Control "public, max-age=31536000, immutable";
}
location / {
add_header Cache-Control "no-cache";
try_files $uri /index.html;
}
}

7076
apps/h5/package-lock.json generated Normal file

File diff suppressed because it is too large Load Diff

26
apps/h5/package.json Normal file
View File

@ -0,0 +1,26 @@
{
"name": "item-atlas-h5",
"version": "0.1.0",
"private": true,
"type": "module",
"scripts": {
"dev": "uni -p h5",
"check": "vue-tsc --noEmit",
"build": "vue-tsc --noEmit && uni build -p h5"
},
"dependencies": {
"@dcloudio/uni-app": "3.0.0-5030420261029002",
"@dcloudio/uni-components": "3.0.0-5030420261029002",
"@dcloudio/uni-h5": "3.0.0-5030420261029002",
"@lucide/vue": "1.82.0",
"vue": "3.4.21",
"vue-i18n": "9.14.5"
},
"devDependencies": {
"@dcloudio/types": "3.4.31",
"@dcloudio/vite-plugin-uni": "3.0.0-5030420261029002",
"typescript": "5.7.3",
"vite": "5.2.8",
"vue-tsc": "2.2.12"
}
}

5
apps/h5/src/App.vue Normal file
View File

@ -0,0 +1,5 @@
<script lang="ts">
export default {}
</script>
<style src="./style.css"></style>

101
apps/h5/src/api.ts Normal file
View File

@ -0,0 +1,101 @@
import { ref } from 'vue'
type Grant = { accessToken: string; refreshToken: string; expiresIn: number }
type Session = Grant & { expiry: number }
type Options = { method?: string; body?: unknown; signal?: AbortSignal; idempotencyKey?: string; blob?: boolean }
export class ApiError extends Error {
constructor(readonly status: number, message: string) { super(message) }
}
export const signedIn = ref(false)
let session: Session | null = null
let generation = 0
let renewing: Promise<Session> | null = null
async function request<T>(path: string, options: Options, access?: string): Promise<T> {
const headers = new Headers({ Accept: 'application/json' })
const form = options.body instanceof FormData ? options.body : undefined
if (!form && options.body !== undefined) headers.set('Content-Type', 'application/json')
if (access) headers.set('Authorization', 'Bearer ' + access)
if (options.idempotencyKey) headers.set('Idempotency-Key', options.idempotencyKey)
const response = await fetch(path, {
method: options.method, headers, signal: options.signal, cache: 'no-store',
body: form ?? (options.body === undefined ? undefined : JSON.stringify(options.body)),
})
if (!response.ok) {
const issue = await response.json().catch(() => ({}))
throw new ApiError(response.status, issue.detail || issue.message || '请求失败(' + response.status + ')')
}
if (response.status === 204 || response.status === 202 && !response.headers.get('content-type')?.includes('json')) return undefined as T
return (options.blob ? await response.blob() : await response.json()) as T
}
function clear() {
generation++
session = null
renewing = null
signedIn.value = false
}
function install(grant: Grant) {
session = { ...grant, expiry: Date.now() + grant.expiresIn * 1000 }
signedIn.value = true
return session
}
export async function login(username: string, password: string) {
const attempt = ++generation
const grant = await request<Grant>('/api/session/login', { method: 'POST', body: { username, password } })
if (attempt === generation) install(grant)
}
export async function logout() {
const pending = renewing
const refreshToken = session?.refreshToken
clear()
// A completed refresh may have already rotated the token on the server.
await pending?.catch(() => {})
if (refreshToken) await request('/api/session/logout', { method: 'POST', body: { refreshToken } }).catch(() => {})
}
function refresh(rejected?: string): Promise<Session> {
if (renewing) return renewing
if (!session) return Promise.reject(new ApiError(401, '请重新登录。'))
if (session.expiry > Date.now() + 30000 && session.accessToken !== rejected) return Promise.resolve(session)
const attempt = generation
const task = request<Grant>('/api/session/refresh', { method: 'POST', body: { refreshToken: session.refreshToken } })
.then(async (grant) => {
if (attempt !== generation) {
await request('/api/session/logout', { method: 'POST', body: { refreshToken: grant.refreshToken } }).catch(() => {})
throw new DOMException('会话已结束', 'AbortError')
}
return install(grant)
})
.catch((error) => {
if (attempt === generation && error instanceof ApiError && error.status === 401) clear()
throw error
})
.finally(() => { if (renewing === task) renewing = null })
renewing = task
return task
}
export async function api<T>(path: string, options: Options = {}): Promise<T> {
const attempt = generation
const access = (await refresh()).accessToken
let result: T
try {
result = await request<T>(path, options, access)
} catch (error) {
if (!(error instanceof ApiError) || error.status !== 401 || attempt !== generation) throw error
options.signal?.throwIfAborted()
result = await request<T>(path, options, (await refresh(access)).accessToken)
}
if (attempt !== generation) throw new DOMException('会话已结束', 'AbortError')
return result
}
export const message = (error: unknown) => error instanceof TypeError
? '连接服务失败,请检查网络后重试。'
: error instanceof Error ? error.message : '请求失败,请重试。'

View File

@ -0,0 +1,147 @@
<script setup lang="ts">
import { onBeforeUnmount, onMounted, ref } from 'vue'
import { Camera, ImagePlus, Trash2, X } from '@lucide/vue'
import { api, message } from '../api'
import PhotoCrop from './PhotoCrop.vue'
const props = defineProps<{ endpoint: string; writable: boolean }>()
const photos = ref<{ id: string; small?: string }[]>([])
const file = ref<File>()
const pending = ref<{ blob: Blob; key: string }>()
const busy = ref(false)
const error = ref('')
const viewer = ref<HTMLDialogElement>()
const opened = ref<{ id: string; url: string }>()
let read: AbortController | undefined
let viewing: AbortController | undefined
let disposed = false
let pickerInput: HTMLInputElement | undefined
function revokeRows(rows: typeof photos.value) {
rows.forEach((entry) => { if (entry.small) URL.revokeObjectURL(entry.small) })
}
async function load() {
read?.abort()
const controller = new AbortController()
read = controller
try {
const items = await api<{ id: string }[]>(props.endpoint, { signal: controller.signal })
const withThumbnails = await Promise.all(items.map(async ({ id }) => {
const blob = await api<Blob>(props.endpoint + '/' + id + '?thumbnail=true', { blob: true, signal: controller.signal }).catch(() => null)
return { id, small: blob ? URL.createObjectURL(blob) : undefined }
}))
if (controller.signal.aborted || disposed) { revokeRows(withThumbnails); return }
revokeRows(photos.value)
photos.value = withThumbnails
} catch (cause) { if (!controller.signal.aborted) error.value = message(cause) }
}
function choosePhoto(camera: boolean) {
if (busy.value || pending.value) return
pickerInput?.remove()
const input = document.createElement('input')
pickerInput = input
input.type = 'file'
input.accept = 'image/*'
if (camera) input.setAttribute('capture', 'environment')
input.hidden = true
input.addEventListener('change', () => {
const selected = input.files?.[0]
input.remove()
if (!selected || disposed) return
error.value = ''
if (!selected.size || selected.size > 30 * 1024 * 1024) error.value = '请选择 30 MiB 以内的照片。'
else file.value = selected
}, { once: true })
input.addEventListener('cancel', () => input.remove(), { once: true })
document.body.append(input)
input.click()
}
function chosen(blob: Blob) {
file.value = undefined
pending.value = { blob, key: crypto.randomUUID() }
void upload()
}
async function upload() {
if (!pending.value || busy.value) return
busy.value = true
error.value = ''
try {
const body = new FormData()
body.append('image', pending.value.blob, 'item.jpg')
await api(props.endpoint, { method: 'POST', body, idempotencyKey: pending.value.key })
pending.value = undefined
await load()
} catch (cause) { error.value = message(cause) }
finally { busy.value = false }
}
function closeViewer() {
viewing?.abort()
viewer.value?.close()
if (opened.value) URL.revokeObjectURL(opened.value.url)
opened.value = undefined
}
async function show(id: string) {
closeViewer()
const controller = new AbortController()
viewing = controller
error.value = ''
try {
const blob = await api<Blob>(props.endpoint + '/' + id, { blob: true, signal: controller.signal })
if (!disposed && !controller.signal.aborted) {
opened.value = { id, url: URL.createObjectURL(blob) }
viewer.value?.showModal()
}
} catch (cause) { if (!controller.signal.aborted) error.value = message(cause) }
}
async function deletePhoto() {
const photo = opened.value
if (!photo || busy.value || !window.confirm('删除这张照片?')) return
busy.value = true
error.value = ''
try {
await api(props.endpoint + '/' + photo.id, { method: 'DELETE' })
closeViewer()
await load()
} catch (cause) { error.value = message(cause) }
finally { busy.value = false }
}
onMounted(load)
onBeforeUnmount(() => {
disposed = true
read?.abort()
closeViewer()
pickerInput?.remove()
revokeRows(photos.value)
})
</script>
<template>
<section class="card detail-section">
<div class="section-top"><h2>照片</h2><small v-if="photos.length">{{ photos.length }} / 6</small></div>
<p v-if="error" class="notice error" role="alert">{{ error }}</p>
<div v-if="photos.length" class="photo-strip">
<button v-for="photo in photos" :key="photo.id" aria-label="打开物品照片" @click="show(photo.id)"><img v-if="photo.small" :src="photo.small" alt="" /><ImagePlus v-else :size="22" /></button>
</div>
<p v-else class="secondary">还没有照片</p>
<div v-if="writable && photos.length < 6 && !pending" class="form-actions">
<button :disabled="busy" @click="choosePhoto(true)"><Camera :size="17" />拍照</button>
<button :disabled="busy" @click="choosePhoto(false)"><ImagePlus :size="17" />选照片</button>
</div>
<div v-if="pending" class="form-actions"><button :disabled="busy" @click="pending = undefined">取消上传</button><button :disabled="busy" @click="upload">{{ busy ? '正在上传…' : '重试上传' }}</button></div>
<PhotoCrop v-if="file" :file="file" @ready="chosen" @close="file = undefined" />
<dialog ref="viewer" class="photo-dialog" @cancel.prevent="closeViewer">
<header class="section-top"><h2>物品照片</h2><button class="square quiet" aria-label="关闭照片" @click="closeViewer"><X :size="20" /></button></header>
<img v-if="opened" class="large-photo" :src="opened.url" alt="物品照片" />
<p v-if="error" class="notice error" role="alert">{{ error }}</p>
<button v-if="writable" class="danger" :disabled="busy" @click="deletePhoto"><Trash2 :size="16" />删除照片</button>
</dialog>
</section>
</template>

View File

@ -0,0 +1,95 @@
<script setup lang="ts">
import { onBeforeUnmount, onMounted, ref, watch } from 'vue'
import { Crop, X } from '@lucide/vue'
import { message } from '../api'
const props = defineProps<{ file: File }>()
const emit = defineEmits<{ close: []; ready: [photo: Blob] }>()
const holder = ref<HTMLElement>()
const dialog = ref<HTMLDialogElement>()
const image = new Image()
const imageURL = URL.createObjectURL(props.file)
const canvas = document.createElement('canvas')
canvas.width = 600
canvas.height = 600
canvas.setAttribute('aria-label', '照片裁剪预览')
const zoom = ref(1)
const center = ref({ x: 0.5, y: 0.5 })
const loading = ref(true)
const busy = ref(false)
const error = ref('')
let drag: { pointer: number; x: number; y: number; center: { x: number; y: number } } | undefined
function source() {
const side = Math.min(image.naturalWidth, image.naturalHeight) / zoom.value
return { side, x: (image.naturalWidth - side) * center.value.x, y: (image.naturalHeight - side) * center.value.y }
}
function paint(target: HTMLCanvasElement) {
const ctx = target.getContext('2d')
if (!ctx || !image.naturalWidth) return
const crop = source()
ctx.fillStyle = '#fff'
ctx.fillRect(0, 0, target.width, target.height)
ctx.drawImage(image, crop.x, crop.y, crop.side, crop.side, 0, 0, target.width, target.height)
}
function move(event: PointerEvent) {
if (!drag || event.pointerId !== drag.pointer) return
const crop = source()
const scale = crop.side / Math.max(1, holder.value?.clientWidth ?? 300)
const limit = (position: number) => Math.max(0, Math.min(1, position))
center.value = {
x: limit(drag.center.x - (event.clientX - drag.x) * scale / Math.max(1, image.naturalWidth - crop.side)),
y: limit(drag.center.y - (event.clientY - drag.y) * scale / Math.max(1, image.naturalHeight - crop.side)),
}
}
function start(event: PointerEvent) {
if (loading.value || error.value || event.button !== 0) return
drag = { pointer: event.pointerId, x: event.clientX, y: event.clientY, center: center.value }
holder.value?.setPointerCapture(event.pointerId)
}
async function exportCrop() {
if (loading.value || busy.value || error.value) return
busy.value = true
try {
const target = document.createElement('canvas')
target.width = target.height = Math.min(1440, Math.max(200, Math.round(source().side)))
paint(target)
const blob = await new Promise<Blob | null>((resolve) => target.toBlob(resolve, 'image/jpeg', 0.84))
if (!blob || blob.size > 5 * 1024 * 1024) throw new Error('裁剪后照片仍超过 5 MiB,请缩小后重试。')
emit('ready', blob)
} catch (cause) { error.value = message(cause) }
finally { busy.value = false }
}
watch([zoom, center], () => paint(canvas))
onMounted(() => {
dialog.value?.showModal()
holder.value?.append(canvas)
image.onload = () => {
loading.value = false
if (image.naturalWidth * image.naturalHeight > 54_000_000) error.value = '照片分辨率过高,请选择一张较小的照片。'
else paint(canvas)
}
image.onerror = () => { loading.value = false; error.value = '浏览器无法读取这张照片,请换用 JPEG、PNG 或 WebP。' }
image.src = imageURL
})
onBeforeUnmount(() => { image.onload = image.onerror = null; image.src = ''; URL.revokeObjectURL(imageURL) })
</script>
<template>
<dialog ref="dialog" class="photo-dialog" @cancel.prevent="emit('close')">
<header class="section-top"><h2>裁剪照片</h2><button class="square quiet" aria-label="关闭裁剪" @click="emit('close')"><X :size="20" /></button></header>
<div ref="holder" class="crop-area" @pointerdown="start" @pointermove="move" @pointerup="drag = undefined" @pointercancel="drag = undefined"></div>
<p v-if="error" class="notice error" role="alert">{{ error }}</p>
<p v-else-if="loading" class="secondary" role="status">正在读取照片…</p>
<div v-else class="form">
<label>缩放 <slider :value="Math.round(zoom * 100)" :min="100" :max="300" :step="5" active-color="#1b604a"
@changing="zoom = $event.detail.value / 100" @change="zoom = $event.detail.value / 100" /></label>
<div class="form-actions"><button @click="center = { x: .5, y: .5 }; zoom = 1">重置</button><button class="primary" :disabled="busy" @click="exportCrop"><Crop :size="16" />使用照片</button></div>
</div>
</dialog>
</template>

6
apps/h5/src/main.ts Normal file
View File

@ -0,0 +1,6 @@
import { createSSRApp } from 'vue'
import App from './App.vue'
export function createApp() {
return { app: createSSRApp(App) }
}

View File

@ -0,0 +1,8 @@
{
"name": "见物",
"versionName": "0.1.0",
"versionCode": "1",
"vueVersion": "3",
"h5": { "title": "见物", "router": { "mode": "hash" } },
"uniStatistics": { "enable": false }
}

11
apps/h5/src/pages.json Normal file
View File

@ -0,0 +1,11 @@
{
"pages": [
{ "path": "pages/index", "style": { "navigationBarTitleText": "见物" } },
{ "path": "pages/item", "style": { "navigationBarTitleText": "物品详情" } },
{ "path": "pages/intake", "style": { "navigationBarTitleText": "录入物品" } }
],
"globalStyle": {
"navigationStyle": "custom",
"backgroundColor": "#f5f7f4"
}
}

310
apps/h5/src/pages/index.vue Normal file
View File

@ -0,0 +1,310 @@
<script setup lang="ts">
import { computed, onBeforeUnmount, ref, watch } from 'vue'
import { onShow } from '@dcloudio/uni-app'
import { Box, Check, ChevronDown, ChevronLeft, ChevronRight, Folder, House, LogOut, MapPin, Plus, Search, Star, UserRound, X } from '@lucide/vue'
import { ApiError, api, login, logout, message, signedIn } from '../api'
import { family, type Item, type Place, type Space } from '../types'
import { activeSpace, canWrite, loadPlaces, loadSpaces, openIntake, openItem, places, revision, selectSpace, spaces } from '../workspace'
const username = ref('')
const password = ref('')
const signingIn = ref(false)
const spaceBusy = ref(false)
const creating = ref(false)
const newName = ref('')
const addingPlace = ref(false)
const placeName = ref('')
const placeBusy = ref(false)
const topError = ref('')
const placesError = ref('')
const readingPlaces = ref(false)
const tab = ref<'items' | 'places' | 'profile'>('items')
const query = ref('')
const favorites = ref(false)
const parentId = ref('')
const subtree = ref(true)
const rows = ref<Item[]>([])
const loadedKey = ref('')
const nextOffset = ref(0)
const loading = ref(false)
const more = ref(false)
const listError = ref('')
const place = computed(() => places.value.find((entry) => entry.id === parentId.value))
const children = computed(() => places.value
.filter((entry) => (entry.parentId ?? '') === parentId.value)
.sort((left, right) => (left.sortRank ?? Number.MAX_SAFE_INTEGER) - (right.sortRank ?? Number.MAX_SAFE_INTEGER)))
const scope = computed(() => tab.value === 'places' ? parentId.value : '')
const endpoint = computed(() => {
if (!activeSpace.value || tab.value === 'profile' || (tab.value === 'places' && !scope.value)) return ''
const params = new URLSearchParams({ limit: '30', q: tab.value === 'items' ? query.value.trim() : '',
favorites: String(tab.value === 'items' && favorites.value) })
if (scope.value) {
params.set('location', scope.value)
if (subtree.value) params.set('includeDescendants', 'true')
}
return family(activeSpace.value.id) + '/items?' + params.toString()
})
let listRequest: AbortController | undefined
let timer: number | undefined
let seenRevision = -1
const previews = new Map<string, { rows: Item[]; revision: number }>()
async function bootstrap() {
if (!signedIn.value || spaceBusy.value) return
spaceBusy.value = true
topError.value = ''
try { await loadSpaces() }
catch (error) { if (signedIn.value) topError.value = message(error) }
finally { spaceBusy.value = false }
}
onShow(() => {
if (!signedIn.value) return
if (!activeSpace.value) void bootstrap()
if (seenRevision !== revision.value) {
seenRevision = revision.value
restart(false)
void readPlaces()
}
})
async function signIn() {
if (signingIn.value) return
signingIn.value = true
topError.value = ''
try {
await login(username.value.trim(), password.value)
password.value = ''
await bootstrap()
} catch (error) { topError.value = message(error) }
finally { signingIn.value = false }
}
async function readPlaces() {
placesError.value = ''
readingPlaces.value = true
try {
await loadPlaces()
if (parentId.value && !places.value.some((entry) => entry.id === parentId.value)) parentId.value = ''
} catch (error) { placesError.value = message(error) }
finally { readingPlaces.value = false }
}
function switchSpace(event: Event) {
const chosen = spaces.value.find((space) => space.id === (event.target as HTMLSelectElement).value)
if (chosen) selectSpace(chosen)
}
function signedOut() {
previews.clear()
query.value = ''
favorites.value = false
parentId.value = ''
tab.value = 'items'
topError.value = ''
void logout()
}
async function createSpace() {
if (spaceBusy.value || !newName.value.trim()) return
spaceBusy.value = true
topError.value = ''
try {
const space = await api<Space>('/api/households', { method: 'POST', body: { name: newName.value.trim() } })
spaces.value = [...spaces.value, space]
selectSpace(space)
creating.value = false
newName.value = ''
} catch (error) { topError.value = message(error) }
finally { spaceBusy.value = false }
}
watch(() => activeSpace.value?.id, () => {
previews.clear()
parentId.value = ''
favorites.value = false
addingPlace.value = false
if (activeSpace.value) void readPlaces()
})
watch([endpoint, revision], () => {
seenRevision = revision.value
restart(tab.value === 'items' && !!query.value.trim())
})
function restart(debounce: boolean) {
clearTimeout(timer)
listRequest?.abort()
const current = endpoint.value
if (loadedKey.value !== current) {
const cached = previews.get(current)
rows.value = cached?.revision === revision.value ? cached.rows : []
more.value = rows.value.length === 30
nextOffset.value = rows.value.length
loadedKey.value = current
}
listError.value = ''
loading.value = !!current
if (current) timer = window.setTimeout(() => void loadRows(), debounce ? 170 : 0)
}
async function loadRows(append = false) {
const current = endpoint.value
if (!current) return
listRequest?.abort()
const request = new AbortController()
listRequest = request
loading.value = true
listError.value = ''
try {
const page = await api<Item[]>(current + (append ? '&offset=' + nextOffset.value : ''), { signal: request.signal })
if (request.signal.aborted || current !== endpoint.value) return
const seen = new Set(append ? rows.value.map((item) => item.id) : [])
rows.value = append ? [...rows.value, ...page.filter((item) => !seen.has(item.id))] : page
nextOffset.value = (append ? nextOffset.value : 0) + page.length
loadedKey.value = current
more.value = page.length === 30 && nextOffset.value <= 10000
if (!append) {
previews.delete(current)
previews.set(current, { rows: page, revision: revision.value })
if (previews.size > 10) previews.delete(previews.keys().next().value as string)
}
} catch (error) {
if (!request.signal.aborted) {
if (error instanceof ApiError && [403, 404].includes(error.status)) {
previews.delete(current)
rows.value = []
more.value = false
}
listError.value = message(error)
}
}
finally { if (!request.signal.aborted) loading.value = false }
}
const roleLabel = (space: Space) => ({ OWNER: '所有者', EDITOR: '可编辑', VIEWER: '仅查看' })[space.role]
function openPlace(entry: Place) { parentId.value = entry.id; subtree.value = true; addingPlace.value = false }
function showFavorites() { favorites.value = true; query.value = ''; tab.value = 'items' }
async function createPlace() {
const space = activeSpace.value
if (!space || !canWrite.value || placeBusy.value || !placeName.value.trim()) return
placeBusy.value = true
placesError.value = ''
try {
const child = await api<Place>(family(space.id) + '/locations',
{ method: 'POST', body: { name: placeName.value.trim(), parentId: parentId.value || null } })
if (activeSpace.value?.id !== space.id) return
places.value = [...places.value, child]
addingPlace.value = false
placeName.value = ''
revision.value++
void readPlaces()
} catch (error) { if (activeSpace.value?.id === space.id) placesError.value = message(error) }
finally { placeBusy.value = false }
}
onBeforeUnmount(() => { clearTimeout(timer); listRequest?.abort() })
</script>
<template>
<main v-if="!signedIn" class="phone welcome">
<div class="welcome-brand"><img src="/static/brand.png" alt="" /><span>见物</span></div>
<div class="welcome-copy">
<h1>于寻常处,<br />见生活。</h1>
<p>记下家里的东西,下次找它,知道从哪里找起。</p>
</div>
<form class="form sign-form" @submit="signIn">
<label>见物账号<input v-model="username" aria-label="见物账号" required autocomplete="username" maxlength="100" /></label>
<label>密码<input v-model="password" aria-label="密码" required type="password" autocomplete="current-password" /></label>
<p v-if="topError" class="notice error" role="alert">{{ topError }}</p>
<button class="primary" form-type="submit" :disabled="signingIn">{{ signingIn ? '登录中…' : '登录' }}</button>
</form>
</main>
<main v-else class="phone workbench">
<header class="work-top">
<div class="brand-small"><img src="/static/brand.png" alt="" /><span>见物</span></div>
<div v-if="spaces.length" class="space-select">
<House :size="15" /><select aria-label="当前空间" :value="activeSpace?.id" @change="switchSpace">
<option v-for="space in spaces" :key="space.id" :value="space.id">{{ space.name }}</option>
</select><ChevronDown :size="13" />
</div>
</header>
<p v-if="topError" class="notice error" role="alert">{{ topError }} <button class="inline" @click="bootstrap">重试</button></p>
<div v-if="!activeSpace && !spaceBusy" class="blank">
<House :size="27" /><h1>先建一个空间</h1>
<button class="primary" @click="creating = true">新建空间</button>
</div>
<p v-else-if="!activeSpace" class="center secondary" role="status">正在读取空间…</p>
<template v-if="activeSpace">
<section v-if="tab === 'items'">
<div class="section-top">
<h1>{{ favorites ? '我的收藏' : '找物' }}</h1>
<button v-if="favorites" class="quiet" @click="favorites = false">全部物品</button>
<button v-else class="square" aria-label="我的收藏" @click="showFavorites"><Star :size="19" /></button>
</div>
<form class="search" @submit="loadRows()">
<Search :size="19" /><input v-model="query" type="search" maxlength="150" aria-label="找物" placeholder="搜名称、别名或位置" />
<button v-if="query" class="square quiet" aria-label="清除搜索" @click="query = ''"><X :size="15" /></button>
</form>
</section>
<section v-if="tab === 'places'">
<div class="section-top"><h1>位置</h1><button v-if="parentId" class="quiet" @click="parentId = place?.parentId || ''; addingPlace = false"><ChevronLeft :size="16" />上一级</button></div>
<p v-if="place" class="location-path"><MapPin :size="17" />{{ place.path }}</p>
<p v-if="placesError" class="notice error" role="alert">{{ placesError }} <button class="inline" @click="readPlaces">重试</button></p>
<div v-if="children.length" class="card row-list">
<button v-for="child in children" :key="child.id" class="result-row" @click="openPlace(child)">
<span class="tile amber"><Folder :size="20" /></span><span class="row-info"><strong>{{ child.name }}</strong><span>{{ child.path }}</span></span><ChevronRight :size="17" />
</button>
</div>
<p v-else-if="readingPlaces" class="center secondary" role="status">正在读取位置…</p>
<div v-else-if="!place && !placesError && !addingPlace" class="blank"><Folder :size="29" /><h2>这里还没有位置</h2></div>
<button v-if="canWrite && !addingPlace" class="add-place" @click="addingPlace = true"><Plus :size="16" />{{ parentId ? '新建子位置' : '新建位置' }}</button>
<form v-if="addingPlace" class="form card create-form" @submit="createPlace">
<label>位置名称<input v-model="placeName" aria-label="位置名称" required maxlength="100" /></label>
<div class="form-actions"><button @click="addingPlace = false">取消</button><button class="primary" form-type="submit" :disabled="placeBusy">保存位置</button></div>
</form>
<div v-if="place" class="subhead">
<h2>这里的物品</h2>
<button v-if="children.length" class="quiet" :aria-pressed="subtree" @click="subtree = !subtree"><Check v-if="subtree" :size="15" />含下级位置</button>
<button v-if="canWrite" class="quiet" @click="openIntake(place.id)"><Plus :size="16" />在这里录入</button>
</div>
</section>
<section v-if="endpoint" aria-label="物品结果">
<p v-if="listError" class="notice error" role="alert">{{ listError }} <button class="inline" @click="loadRows()">重试</button></p>
<div v-if="rows.length" class="card row-list">
<button v-for="item in rows" :key="item.id" class="result-row" @click="openItem(item.id)">
<span class="tile"><Box :size="20" /></span>
<span class="row-info"><strong>{{ item.name }}</strong><span>{{ item.locationPath || '未设置位置' }}</span></span>
<small v-if="item.quantity > 1">×{{ item.quantity }}</small><ChevronRight :size="17" />
</button>
</div>
<p v-if="loading && !rows.length" class="center secondary" role="status">正在读取物品…</p>
<div v-else-if="!rows.length && !listError" class="blank">
<Box :size="30" /><h2>{{ query.trim() && tab === 'items' ? '没有找到物品' : favorites && tab === 'items' ? '还没有收藏' : '这里还没有物品' }}</h2>
<button v-if="canWrite && !favorites && !query.trim()" @click="openIntake(scope)"><Plus :size="16" />录入物品</button>
</div>
<div v-if="more" class="center"><button :disabled="loading" @click="loadRows(true)">加载更多</button></div>
</section>
<section v-if="tab === 'profile'">
<div class="section-top"><h1>我的</h1></div>
<div class="card profile-card"><span class="tile"><UserRound :size="23" /></span><div><strong>{{ username }}</strong><p>{{ activeSpace.name }} · {{ roleLabel(activeSpace) }}</p></div></div>
<div class="card row-list">
<button class="result-row" @click="showFavorites"><Star :size="19" /><span class="row-info"><strong>我的收藏</strong></span><ChevronRight :size="17" /></button>
<button class="result-row" @click="creating = true"><Plus :size="20" /><span class="row-info"><strong>新建空间</strong></span><ChevronRight :size="17" /></button>
<button class="result-row" @click="signedOut"><LogOut :size="18" /><span class="row-info"><strong>退出登录</strong></span></button>
</div>
</section>
</template>
<form v-if="creating" class="form card create-form" @submit="createSpace">
<h2>新建空间</h2>
<label>空间名称<input v-model="newName" required maxlength="100" /></label>
<div class="form-actions"><button @click="creating = false">取消</button><button class="primary" form-type="submit" :disabled="spaceBusy">创建</button></div>
</form>
<nav v-if="activeSpace" class="dock" aria-label="主导航">
<button :aria-current="tab === 'items' ? 'page' : undefined" @click="tab = 'items'"><Search :size="20" />找物</button>
<button :aria-current="tab === 'places' ? 'page' : undefined" @click="tab = 'places'"><Folder :size="20" />位置</button>
<button v-if="canWrite" class="dock-add" @click="openIntake(scope)"><span><Plus :size="24" /></span>录入</button>
<button :aria-current="tab === 'profile' ? 'page' : undefined" @click="tab = 'profile'"><UserRound :size="20" />我的</button>
</nav>
</main>
</template>

View File

@ -0,0 +1,199 @@
<script setup lang="ts">
import { computed, ref, watch } from 'vue'
import { onLoad } from '@dcloudio/uni-app'
import { ArrowLeft, Box, Keyboard, Sparkles } from '@lucide/vue'
import { api, message, signedIn } from '../api'
import { family, type Draft, type Item, type ItemDetail, type Operation } from '../types'
import { activeSpace, backHome, canWrite, loadPlaces, openItem, places, revision } from '../workspace'
const mode = ref<'manual' | 'text'>('manual')
const editing = ref('')
const baseline = ref<Item>()
const root = computed(() => activeSpace.value ? family(activeSpace.value.id) : '')
const location = ref('')
const originalLocation = ref('')
const name = ref('')
const quantity = ref(1)
const aliases = ref('')
const notes = ref('')
const text = ref('')
const draft = ref<Draft>()
const rows = ref<{ enabled: boolean; name: string; quantity: number; location: string; hint: string }[]>([])
const operation = ref<Operation>()
const busy = ref(false)
const loading = ref(false)
const error = ref('')
const terminal = ['FAILED', 'REJECTED', 'NEEDS_REVIEW']
let idempotencyKey = ''
let previousInput = ''
onLoad((options) => {
editing.value = options?.item ?? ''
originalLocation.value = options?.location ?? ''
location.value = originalLocation.value
if (!signedIn.value || !root.value) return
void loadPlaces().catch((cause) => { error.value = message(cause) })
if (editing.value) void loadEdit()
})
async function loadEdit() {
loading.value = true
error.value = ''
try {
const detail = await api<ItemDetail>(root.value + '/items/' + encodeURIComponent(editing.value))
baseline.value = detail.item
name.value = detail.item.name
quantity.value = detail.item.quantity
aliases.value = detail.item.aliases.join('、')
notes.value = detail.item.notes
} catch (cause) { error.value = message(cause) }
finally { loading.value = false }
}
watch(text, () => {
if (!operation.value) { draft.value = undefined; rows.value = [] }
})
function back() {
if (busy.value) return
if (getCurrentPages().length > 1) void uni.navigateBack()
else backHome()
}
async function run(action: () => Promise<void>) {
if (busy.value || !canWrite.value || !root.value) return
busy.value = true
error.value = ''
try { await action() } catch (cause) { error.value = message(cause) }
finally { busy.value = false }
}
function done(newItemId?: string) {
revision.value++
busy.value = false
if (newItemId && getCurrentPages().length > 1) {
// Replace the form so Back returns directly to the list.
void uni.redirectTo({ url: '/pages/item?id=' + encodeURIComponent(newItemId) })
} else if (newItemId) openItem(newItemId)
else back()
}
async function save() {
if (!name.value.trim()) { error.value = '请输入物品名称。'; return }
if (!Number.isInteger(Number(quantity.value)) || Number(quantity.value) < 1 || Number(quantity.value) > 9999) {
error.value = '数量须为 1 到 9999 的整数。'
return
}
await run(async () => {
const names = [...new Set(aliases.value.split(/[、,,]/).map((part) => part.trim()).filter(Boolean))]
if (names.length > 20 || names.some((part) => part.length > 80)) throw new Error('最多填写 20 个别名,每个最长 80 个字符。')
const body = { name: name.value.trim(), quantity: Number(quantity.value), notes: notes.value, aliases: names }
if (editing.value) {
if (!baseline.value) return
await api<Item>(root.value + '/items/' + baseline.value.id, { method: 'PUT', body: { ...body, version: baseline.value.version } })
done()
return
}
const input = { ...body, locationId: location.value || null }
const serialized = JSON.stringify(input)
if (serialized !== previousInput) { previousInput = serialized; idempotencyKey = crypto.randomUUID() }
const item = await api<Item>(root.value + '/items', { method: 'POST', body: input, idempotencyKey })
done(item.id)
})
}
async function generate() {
if (!text.value.trim()) return
await run(async () => {
const current = await api<Draft>(root.value + '/drafts', { method: 'POST', body: { text: text.value.trim(), source: 'MODEL' } })
draft.value = current
rows.value = current.candidates.filter((entry) => entry.action !== 'SKIP').map((entry) => {
const hint = entry.location?.trim() ?? ''
const matches = hint ? places.value.filter((place) => place.name === hint || place.path === hint) : []
return { enabled: entry.action === 'RECORD', name: entry.name, quantity: entry.quantity ?? 1, hint,
location: matches.length === 1 ? matches[0].id : hint ? '' : originalLocation.value }
})
if (current.status === 'MODEL_UNAVAILABLE') error.value = '模型暂不可用,可以保留原文,切回手动添加。'
else if (!rows.value.length) error.value = '这段文字没有生成可核对的物品。'
})
}
async function poll() {
if (!operation.value) return
const url = root.value + '/operations/' + operation.value.id
for (let attempt = 0; attempt < 7; attempt++) {
if (operation.value.status === 'COMPLETED') { done(); return }
if (terminal.includes(operation.value.status)) return
await new Promise((resolve) => setTimeout(resolve, 450))
operation.value = await api<Operation>(url)
}
if (operation.value.status === 'COMPLETED') done()
}
async function confirm() {
if (!draft.value || !rows.value.some((row) => row.enabled) || operation.value) return
const items = rows.value.filter((row) => row.enabled).map((row) => ({
name: row.name.trim(), quantity: Number(row.quantity), locationId: row.location || null, notes: '', aliases: [],
}))
if (items.some((row) => !row.name || !Number.isInteger(row.quantity) || row.quantity < 1 || row.quantity > 9999)) {
error.value = '已勾选的物品需要名称和 1 到 9999 的整数数量。'
return
}
await run(async () => {
operation.value = await api<Operation>(root.value + '/drafts/' + draft.value!.id + '/confirm',
{ method: 'POST', body: { version: draft.value!.version, items, automatic: false } })
await poll()
})
}
function retry() {
void run(async () => {
if (!operation.value) return
operation.value = await api<Operation>(root.value + '/operations/' + operation.value.id + '/retry', { method: 'POST' })
await poll()
})
}
</script>
<template>
<main class="phone panel-page">
<header class="page-top"><button class="square quiet" aria-label="返回" :disabled="busy" @click="back"><ArrowLeft :size="21" /></button><h1>{{ editing ? '编辑物品' : '录入物品' }}</h1></header>
<div v-if="!signedIn || !canWrite" class="blank"><h2>{{ signedIn ? '当前空间仅可查看' : '请先登录' }}</h2><button @click="backHome">返回首页</button></div>
<p v-else-if="loading" class="center secondary" role="status">正在读取物品…</p>
<template v-else>
<div v-if="!editing" class="segmented" aria-label="录入方式">
<button :aria-pressed="mode === 'manual'" :disabled="busy || !!operation" @click="mode = 'manual'"><Box :size="17" />手动添加</button>
<button :aria-pressed="mode === 'text'" :disabled="busy || !!operation" @click="mode = 'text'"><Keyboard :size="17" />文字批量录入</button>
</div>
<p v-if="error" class="notice error" role="alert">{{ error }} <button v-if="editing && !baseline" class="inline" @click="loadEdit">重试</button></p>
<form v-if="mode === 'manual' && (!editing || baseline)" class="card form intake-form" @submit="save">
<label>物品名称<input v-model="name" aria-label="物品名称" required maxlength="150" placeholder="例如 HDMI 线" /></label>
<label>数量<input v-model.number="quantity" aria-label="数量" type="number" min="1" max="9999" required /></label>
<label v-if="!editing">存放位置<select v-model="location" aria-label="存放位置"><option value="">暂不设置</option><option v-for="place in places" :key="place.id" :value="place.id">{{ place.path }}</option></select></label>
<label>别名<input v-model="aliases" aria-label="别名" placeholder="可用逗号隔开" /></label>
<label>备注<textarea v-model="notes" aria-label="备注" rows="3" maxlength="1500"></textarea></label>
<button class="primary" form-type="submit" :disabled="busy">{{ busy ? '保存中…' : '保存物品' }}</button>
</form>
<form v-else-if="mode === 'text'" class="form" @submit="confirm">
<div class="card form intake-form">
<label>要记录的物品<textarea v-model="text" aria-label="要记录的物品" rows="4" maxlength="4000" :disabled="busy || !!operation" placeholder="例如两根数据线放书房抽屉,备用钥匙放玄关。"></textarea></label>
<button v-if="!operation" :disabled="busy || !text.trim()" @click="generate"><Sparkles :size="17" />整理草稿</button>
</div>
<fieldset v-if="rows.length" class="card form intake-form" :disabled="busy || !!operation">
<legend>核对要保存的物品</legend>
<div v-for="(row, index) in rows" :key="index" class="draft-row">
<button class="quiet" :aria-pressed="row.enabled" @click="row.enabled = !row.enabled">{{ row.enabled ? '已选' : '选入' }}</button>
<input v-model="row.name" :aria-label="'第 ' + (index + 1) + ' 件物品的名称'" required maxlength="150" />
<input v-model.number="row.quantity" type="number" aria-label="数量" min="1" max="9999" required />
<label>存放位置<select v-model="row.location"><option value="">暂不设置</option><option v-for="place in places" :key="place.id" :value="place.id">{{ place.path }}</option></select></label>
<small v-if="row.hint && !row.location">原话位置 {{ row.hint }}</small>
</div>
</fieldset>
<button v-if="!operation && rows.length" class="primary" form-type="submit" :disabled="busy || !rows.some((row) => row.enabled)">确认保存</button>
<p v-if="operation && terminal.includes(operation.status)" class="notice error">交付未完成。操作号 {{ operation.id }}</p>
<button v-if="operation?.status === 'NEEDS_REVIEW'" class="primary" :disabled="busy" @click="retry">重试交付</button>
<button v-else-if="operation && !terminal.includes(operation.status)" :disabled="busy" @click="run(poll)">{{ busy ? '正在交付…' : '刷新交付进度' }}</button>
</form>
</template>
</main>
</template>

106
apps/h5/src/pages/item.vue Normal file
View File

@ -0,0 +1,106 @@
<script setup lang="ts">
import { computed, ref } from 'vue'
import { onLoad, onShow } from '@dcloudio/uni-app'
import { ArrowLeft, ArrowRight, ArrowUpDown, Box, MapPin, Pencil, Star, Trash2 } from '@lucide/vue'
import { api, message, signedIn } from '../api'
import { family, type ItemDetail } from '../types'
import { activeSpace, backHome, canWrite, loadPlaces, openIntake, openItem, places, revision } from '../workspace'
import ItemPhotos from '../components/ItemPhotos.vue'
const id = ref('')
const info = ref<ItemDetail>()
const loading = ref(false)
const busy = ref(false)
const error = ref('')
const moving = ref(false)
const moveTo = ref('')
const endpoint = computed(() => activeSpace.value && id.value ? family(activeSpace.value.id) + '/items/' + encodeURIComponent(id.value) : '')
let request = 0
onLoad((options) => { id.value = options?.id ?? '' })
onShow(() => { if (endpoint.value && signedIn.value) void load() })
async function load() {
const endpointAtStart = endpoint.value
const ticket = ++request
loading.value = true
error.value = ''
try {
const detail = await api<ItemDetail>(endpointAtStart)
if (ticket === request && endpointAtStart === endpoint.value) info.value = detail
} catch (cause) { if (ticket === request) { info.value = undefined; error.value = message(cause) } }
finally { if (ticket === request) loading.value = false }
}
function back() {
if (getCurrentPages().length > 1) void uni.navigateBack()
else backHome()
}
async function change(method: string, suffix: string, body?: unknown) {
if (busy.value || !endpoint.value) return
busy.value = true
error.value = ''
try {
await api(endpoint.value + suffix, { method, body })
revision.value++
if (method === 'DELETE') { back(); return }
moving.value = false
await load()
} catch (cause) { error.value = message(cause) }
finally { busy.value = false }
}
function windowConfirmDelete(version: number) {
if (window.confirm('删除这件物品和它的照片?')) void change('DELETE', '?version=' + version)
}
function startMove(location: string | null) {
moveTo.value = location ?? ''
moving.value = true
void loadPlaces().catch((cause) => { error.value = message(cause) })
}
</script>
<template>
<main class="phone panel-page">
<header class="page-top"><button class="square quiet" aria-label="返回" @click="back"><ArrowLeft :size="21" /></button><h1>物品详情</h1></header>
<div v-if="!signedIn || !activeSpace" class="blank"><h2>请先登录并选择空间</h2><button class="primary" @click="backHome">回到登录</button></div>
<p v-else-if="loading && !info" class="center secondary" role="status">正在读取物品…</p>
<p v-if="error" class="notice error" role="alert">{{ error }} <button v-if="signedIn && !info" class="inline" @click="load">重试</button></p>
<template v-if="info && signedIn && activeSpace">
<section class="card detail-hero">
<span class="tile"><Box :size="27" /></span><div><h2>{{ info.item.name }}</h2><p>数量 {{ info.item.quantity }}</p></div>
<button class="square" :aria-label="info.preference.favorite ? '取消收藏' : '收藏'" :aria-pressed="info.preference.favorite" :disabled="busy" @click="change('PUT', '/preference', { ...info.preference, favorite: !info.preference.favorite })"><Star :size="19" :fill="info.preference.favorite ? 'currentColor' : 'none'" /></button>
</section>
<section class="card detail-section">
<h2>存放位置</h2>
<p class="location-path"><MapPin :size="19" />{{ info.item.locationPath || '未设置位置' }}</p>
<div v-if="canWrite" class="form-actions">
<button :disabled="busy" @click="startMove(info.item.locationId)"><ArrowUpDown :size="16" />{{ info.item.locationId ? '移位' : '设置位置' }}</button>
<button :disabled="busy" @click="openIntake('', info.item.id)"><Pencil :size="16" />编辑物品</button>
</div>
<form v-if="moving" class="form move-form" @submit="change('POST', '/moves', { locationId: moveTo || null, version: info.item.version })">
<label>新位置<select v-model="moveTo"><option value="">未设置位置</option><option v-for="place in places" :key="place.id" :value="place.id">{{ place.path }}</option></select></label>
<div class="form-actions"><button @click="moving = false">取消</button><button class="primary" form-type="submit" :disabled="busy || (moveTo || null) === info.item.locationId">确认移位</button></div>
</form>
</section>
<section v-if="info.item.aliases.length || info.item.notes || info.item.priceCents != null" class="card detail-section">
<h2>物品信息</h2>
<dl><template v-if="info.item.aliases.length"><dt>别名</dt><dd>{{ info.item.aliases.join('、') }}</dd></template>
<template v-if="info.item.priceCents != null"><dt>购入单价</dt><dd>¥{{ (info.item.priceCents / 100).toFixed(2) }}</dd></template>
<template v-if="info.item.notes"><dt>备注</dt><dd>{{ info.item.notes }}</dd></template></dl>
</section>
<ItemPhotos :key="endpoint" :endpoint="endpoint + '/photos'" :writable="canWrite" />
<section v-if="info.relations.length" class="card detail-section">
<h2>关联物品</h2>
<div class="row-list"><button v-for="relation in info.relations" :key="relation.itemId" class="result-row" @click="openItem(relation.itemId)"><span class="row-info"><strong>{{ relation.name }}</strong><span>{{ relation.locationPath || '未设置位置' }}</span></span></button></div>
</section>
<section v-if="info.moves.length" class="card detail-section">
<h2>移位记录</h2>
<div v-for="(move, index) in info.moves" :key="index" class="history-row"><span>{{ move.fromPath || '未设置位置' }} <ArrowRight :size="14" /> {{ move.toPath || '未设置位置' }}</span><time>{{ move.movedAt.slice(0, 10) }}</time></div>
</section>
<button v-if="canWrite" class="danger archive" :disabled="busy" @click="windowConfirmDelete(info.item.version)"><Trash2 :size="16" />删除物品</button>
</template>
</main>
</template>

Binary file not shown.

After

Width:  |  Height:  |  Size: 5.5 KiB

114
apps/h5/src/style.css Normal file
View File

@ -0,0 +1,114 @@
:root{font-family:Inter,"PingFang SC","Microsoft YaHei",system-ui,sans-serif;color:#1c302d;background:#e8eeea;font-synthesis:none;--ink:#1c302d;--muted:#566e66;--paper:#fff;--line:#dee8e3;--accent:#1b604a;--soft:#e8f3eb;--background:#f6f8f5}
*{box-sizing:border-box}
body{margin:0}
h1,h2,p{margin:0}
h1{font-size:29px;font-weight:750;letter-spacing:-.04em}
h2{font-size:16px;font-weight:700}
small,.secondary{color:var(--muted);font-size:13px}
:is(button,uni-button),input,select,textarea{font:inherit;color:inherit}
:is(.phone,.photo-dialog) :is(button,uni-button){display:inline-flex;align-items:center;justify-content:center;gap:6px;min-height:44px;padding:0 12px;border:1px solid var(--line);border-radius:9px;background:#fff;cursor:pointer;font-size:14px;font-weight:630;line-height:1.3;margin:0}
:is(.phone,.photo-dialog) :is(button,uni-button)::after{border:0}
:is(.phone,.photo-dialog) :is(button,uni-button):disabled{opacity:.49;cursor:default}
:is(.phone,.photo-dialog) :is(button,uni-button):focus-visible,input:focus-visible,select:focus-visible,textarea:focus-visible{outline:2px solid #268561;outline-offset:2px}
:is(.phone,.photo-dialog) :is(button,uni-button) svg{flex-shrink:0}
:is(.phone,.photo-dialog) .primary{background:var(--accent);border-color:var(--accent);color:#fff}
:is(.phone,.photo-dialog) .quiet{background:transparent;border-color:transparent}
:is(.phone,.photo-dialog) .inline{padding:0 5px;min-height:26px;background:transparent;color:inherit;border:0;text-decoration:underline}
:is(.phone,.photo-dialog) .square{width:44px;padding:0}
:is(.phone,.photo-dialog) .danger{color:#a63642}
.phone{width:min(100%,560px);min-height:100dvh;margin:0 auto;padding:calc(12px + env(safe-area-inset-top)) 17px 26px;background:var(--background)}
.welcome{display:flex;flex-direction:column;justify-content:center;gap:26px;padding-inline:clamp(22px,7vw,40px);background:linear-gradient(155deg,#e7efe5,#f9fbf8 62%);padding-bottom:calc(32px + env(safe-area-inset-bottom))}
.welcome-brand,.brand-small{display:flex;align-items:center;gap:8px;font-weight:750;letter-spacing:.12em}
.welcome-brand img{width:42px;height:42px;border-radius:10px}
.welcome-brand{font-size:22px}
.welcome-copy h1{font-size:clamp(38px,10vw,50px);line-height:1.11;letter-spacing:-.04em}
.welcome-copy p{color:var(--muted);font-size:14px;margin-top:12px;max-width:33ch}
.sign-form{padding-top:1px}
.workbench{padding-bottom:calc(94px + env(safe-area-inset-bottom))}
.work-top,.section-top,.subhead,.page-top{display:flex;align-items:center;justify-content:space-between;gap:8px}
.work-top{min-height:44px;margin-bottom:15px}
.brand-small img{width:32px;height:32px;border-radius:8px}
.brand-small{font-size:18px}
.space-select{display:flex;align-items:center;gap:5px;max-width:62%;min-height:40px;padding:0 8px;border:1px solid var(--line);border-radius:10px;background:white;color:#315c4b}
.space-select svg{flex-shrink:0}
.space-select select{min-width:0;border:0;appearance:none;background:transparent;font-size:14px}
.section-top{min-height:44px;margin-bottom:10px}
.subhead{margin:14px 0 8px;min-height:40px;flex-wrap:wrap}
.subhead :is(button,uni-button){min-height:34px;padding:0 5px}
.search{display:flex;align-items:center;gap:9px;min-height:48px;padding:0 10px;background:#fff;border:1px solid var(--line);border-radius:12px;margin-bottom:12px;color:var(--muted)}
.search input,.search uni-input{flex:1;min-width:0;border:0;background:transparent;height:44px;padding:0;color:var(--ink)}
.search .square{width:35px;min-height:37px}
.card{background:var(--paper);border:1px solid var(--line);border-radius:13px;min-width:0}
.row-list{display:grid;overflow:hidden}
:is(.phone,.photo-dialog) .result-row{width:100%;justify-content:start;gap:10px;padding:10px;border:0;border-radius:0;min-height:59px;text-align:left}
.result-row+.result-row{border-top:1px solid #edf1ef}
.result-row>svg:last-child{margin-left:auto;color:#648176}
.row-info{display:grid;gap:4px;flex:1;min-width:0;overflow-wrap:anywhere}
.row-info strong{font-size:15px;line-height:1.22}
.row-info span{font-size:12px;color:var(--muted);line-height:1.3}
.tile{display:grid;place-items:center;width:38px;height:38px;flex-shrink:0;border-radius:10px;background:var(--soft);color:var(--accent)}
.tile.amber{background:#f3eee1;color:#7b6037}
.blank{display:grid;min-height:200px;align-content:center;justify-items:center;gap:10px;color:var(--muted);padding:25px 10px;text-align:center}
.blank h1,.blank h2{color:var(--ink)}
.center{text-align:center;padding:13px}
.notice{padding:10px 11px;border-radius:8px;background:#e8f3ed;line-height:1.45;font-size:13px;overflow-wrap:anywhere}
.notice.error{background:#fdf0ee;color:#98343d}
.workbench>.notice,.panel-page>.notice{margin-bottom:10px}
.profile-card{display:flex;align-items:center;gap:10px;padding:15px;margin-bottom:13px}
.profile-card p{color:var(--muted);font-size:13px;margin-top:3px}
.dock{position:fixed;bottom:0;left:50%;transform:translateX(-50%);width:min(100%,560px);display:flex;align-items:center;justify-content:space-around;gap:2px;z-index:5;padding:7px 8px calc(7px + env(safe-area-inset-bottom));border-top:1px solid #dde6e0;background:#fcfdfb}
.dock :is(button,uni-button){flex:1;flex-direction:column;gap:4px;min-height:48px;padding:0;border:0;background:none;font-size:11px;color:var(--muted)}
.dock :is(button,uni-button)[aria-current=page]{color:var(--accent);font-weight:750}
.dock .dock-add span{display:grid;place-items:center;width:37px;height:33px;border-radius:11px;background:var(--accent);color:#fff}
.panel-page{padding-bottom:calc(25px + env(safe-area-inset-bottom))}
.page-top{justify-content:start;min-height:48px;margin-bottom:12px}
.page-top h1{font-size:21px}
.detail-hero{display:flex;align-items:center;padding:12px;gap:10px;margin-bottom:9px;overflow-wrap:anywhere}
.detail-hero .tile{width:49px;height:49px}
.detail-hero .square{margin-left:auto}
.detail-hero h2{font-size:21px}
.detail-hero p{font-size:12px;margin-top:4px;color:var(--muted)}
.detail-section{padding:11px 12px;margin-bottom:9px;display:grid;gap:8px}
.detail-section .section-top{margin:0;min-height:25px}
.location-path{display:flex;align-items:start;gap:6px;color:#356454;font-size:14px;line-height:1.45;margin-bottom:8px;overflow-wrap:anywhere}
.location-path svg{flex-shrink:0}
.detail-section dl{margin:0;display:grid;gap:4px;grid-template-columns:64px minmax(0,1fr);font-size:13px}
.detail-section dt{color:var(--muted)}
.detail-section dd{margin:0;white-space:pre-wrap;overflow-wrap:anywhere}
.history-row{display:grid;gap:4px;font-size:13px}
.history-row svg{vertical-align:middle}
.history-row time{color:var(--muted);font-size:11px}
.archive{margin:6px auto 0;display:flex}
.form{display:grid;gap:10px;min-width:0;margin:0}
.form :is(label,uni-label){display:grid;gap:5px;font-size:13px;font-weight:650;min-width:0}
.form input,.form uni-input,.form select,.form textarea,.form uni-textarea{width:100%;min-width:0;padding:8px 9px;min-height:44px;border:1px solid var(--line);border-radius:8px;background:#fff;font-size:16px;font-weight:450}
.form .uni-input-input,.form .uni-textarea-textarea{padding:0;font:inherit}
.form uni-textarea{min-height:88px;height:103px}
.form textarea{resize:vertical}
.form-actions{display:flex;justify-content:end;gap:7px;flex-wrap:wrap}
.create-form,.intake-form{padding:12px}
.create-form{margin-top:12px}
.add-place{margin-top:9px}
.move-form{padding-top:8px;border-top:1px solid var(--line)}
.segmented{display:flex;gap:4px;margin-bottom:11px;padding:4px;background:#eaf0ec;border-radius:10px}
.segmented :is(button,uni-button){flex:1;border-color:transparent;background:transparent;min-height:39px;padding:0 5px;font-size:13px}
.segmented :is(button,uni-button)[aria-pressed=true]{background:#fff;border-color:var(--line);color:var(--accent)}
.draft-row{display:grid;grid-template-columns:50px minmax(0,1fr) 62px;gap:5px;padding:6px 0;border-bottom:1px solid var(--line)}
.draft-row :is(label,uni-label),.draft-row small{grid-column:1/-1}
.draft-row :is(button,uni-button)[aria-pressed=true]{background:var(--soft);color:var(--accent)}
.draft-row :is(button,uni-button){font-size:12px;padding:0}
.photo-strip{display:grid;grid-template-columns:repeat(3,minmax(0,1fr));gap:6px}
.photo-strip :is(button,uni-button){aspect-ratio:1;padding:0;overflow:hidden}
.photo-strip img{width:100%;height:100%;object-fit:cover}
.photo-dialog{width:min(93vw,480px);border:1px solid var(--line);border-radius:13px;padding:12px;color:var(--ink);max-height:88dvh}
.photo-dialog::backdrop{background:#14272688}
.crop-area{width:min(100%,355px);aspect-ratio:1;touch-action:none;background:#e5eeea;border-radius:8px;overflow:hidden;margin:0 auto 8px}
.crop-area canvas{display:block;width:100%;height:100%}
.large-photo{display:block;max-width:100%;max-height:64vh;margin:0 auto 8px;border-radius:8px;object-fit:contain}
@media(min-width:561px){.phone{box-shadow:0 0 45px #193d2d14}}
/* Uni wraps a form's slots in a span on H5. Lay out the actual controls inside it. */
uni-form.form > span{display:grid;gap:10px;min-width:0}
uni-form.search > span{display:flex;align-items:center;gap:9px;width:100%;min-width:0}
.phone .dock :is(button,uni-button){display:flex;flex-direction:column}
.phone .archive{margin:6px auto 0}

18
apps/h5/src/types.ts Normal file
View File

@ -0,0 +1,18 @@
export type Space = { id: string; name: string; role: 'OWNER' | 'EDITOR' | 'VIEWER' }
export type Place = { id: string; parentId: string | null; name: string; path: string; depth: number; sortRank: number | null }
export type Item = {
id: string; name: string; quantity: number; notes: string; locationId: string | null;
locationPath: string; version: number; aliases: string[]; coverPhotoId: string | null; priceCents: number | null
}
export type ItemDetail = {
item: Item
moves: { fromPath: string; toPath: string; movedAt: string }[]
relations: { itemId: string; name: string; locationPath: string; kind: string }[]
preference: { favorite: boolean; rating: number | null; note: string }
}
export type Draft = {
id: string; version: number; status: string
candidates: { name: string; quantity: number | null; action: 'RECORD' | 'SKIP' | 'REVIEW'; location: string | null }[]
}
export type Operation = { id: string; status: string }
export const family = (space: string) => '/api/households/' + space

53
apps/h5/src/workspace.ts Normal file
View File

@ -0,0 +1,53 @@
import { computed, ref, watch } from 'vue'
import { api, signedIn } from './api'
import { family, type Place, type Space } from './types'
export const spaces = ref<Space[]>([])
export const activeSpace = ref<Space>()
export const places = ref<Place[]>([])
export const revision = ref(0)
export const canWrite = computed(() => !!activeSpace.value && activeSpace.value.role !== 'VIEWER')
let locationRequest: AbortController | undefined
export function selectSpace(space: Space) {
if (activeSpace.value?.id === space.id) return
locationRequest?.abort()
activeSpace.value = space
places.value = []
revision.value++
}
export async function loadSpaces() {
spaces.value = await api<Space[]>('/api/households')
const selected = spaces.value.find((space) => space.id === activeSpace.value?.id) ?? spaces.value[0]
if (selected) selectSpace(selected)
else { activeSpace.value = undefined; places.value = []; revision.value++ }
}
export async function loadPlaces() {
const space = activeSpace.value
if (!space) return
locationRequest?.abort()
const request = new AbortController()
locationRequest = request
try {
const result = await api<Place[]>(family(space.id) + '/locations', { signal: request.signal })
if (!request.signal.aborted && activeSpace.value?.id === space.id) places.value = result
} catch (error) { if (!request.signal.aborted) throw error }
}
export function backHome() { void uni.reLaunch({ url: '/pages/index' }) }
export function openItem(id: string) { void uni.navigateTo({ url: '/pages/item?id=' + encodeURIComponent(id) }) }
export function openIntake(location = '', item = '') {
if (!canWrite.value) return
void uni.navigateTo({ url: '/pages/intake?location=' + encodeURIComponent(location) + '&item=' + encodeURIComponent(item) })
}
watch(signedIn, (active) => {
if (active) return
locationRequest?.abort()
spaces.value = []
activeSpace.value = undefined
places.value = []
revision.value++
})

13
apps/h5/tsconfig.json Normal file
View File

@ -0,0 +1,13 @@
{
"compilerOptions": {
"target": "ES2022",
"module": "ESNext",
"moduleResolution": "Bundler",
"strict": true,
"skipLibCheck": true,
"noEmit": true,
"lib": ["ES2022", "DOM", "DOM.Iterable"],
"types": ["@dcloudio/types", "vite/client"]
},
"include": ["src/**/*.ts", "src/**/*.vue"]
}

16
apps/h5/vite.config.mjs Normal file
View File

@ -0,0 +1,16 @@
import { defineConfig } from 'vite'
import plugin from '@dcloudio/vite-plugin-uni'
export default defineConfig({
plugins: [(plugin.default ?? plugin)()],
server: {
host: '127.0.0.1',
proxy: {
'/api': {
target: process.env.ATLAS_GATEWAY_URL || 'https://pc-atlas.tutudog.com',
changeOrigin: true,
proxyTimeout: 85000,
},
},
},
})

View File

@ -4,7 +4,7 @@
| 端 | 技术选型 | 使用与交付 |
| --- | --- | --- |
| H5 | uni-app(Vue 3、TypeScript、Vite),使用 DCloud 的 CLI 模板 | 面向临时找物、相机上传和快速录入。首版构建 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 镜像。 |
| 管理后台 | Vue 3、TypeScript、Vite、Element Plus | 已有空间查询、删除及图片清理入口。独立 Nginx 镜像。其他管理模块有多页路由需求时接入 Vue Router。 |
| iOS | Swift、SwiftUI,最低 iOS 17 | [iOS 应用](../../apps/ios/README.md)接入账号、空间、物品、草稿和相册上传。拍照和录音按后续原生端验收范围补齐。 |

View File

@ -63,5 +63,6 @@ R01–R10 对应[需求与验收](../product/requirements.md)。实现和当前
| TC-52 从平面图选存放位置 | R03、R06、R11 | 在手动添加、智能草稿或移位中打开位置选择,点「从平面图选择」。点房间,进入室内位置,再从家具进入抽屉。另选一次没有摆在图上的位置,并取消一次选择。 | 标记和底部路径随点选更新。可直接选房间或家具,也可进入抽屉。未摆放位置可从列表选。选中只回填表单,取消保留原位置。 |
| TC-53 浏览下级位置的物品 | R04、R11 | 在主卧和主卧抽屉各放一件物品,另在其他房间和无位置各放一件。在主卧详情来回切换物品范围。用只读成员重试,移动或归档抽屉里的物品后刷新。 | 「仅此位置」只显示直接存放的物品。「含下级位置」也显示抽屉里的物品和完整路径,两种范围的分页和缓存独立。其他房间、无位置和归档物品不混入。 |
| TC-54 PC 建模和找物联动 | R03、R04、R11、R12 | 在桌面浏览器添加房间,拖动后撤回和重做,改右侧宽深并保存。在室内图添加书桌,再从书桌进入录入,按别名找物并回到平面图定位。另试放弃修改、AI 预览和保存版本冲突。 | 全屋与室内使用各自的布局。操作可撤销,确认保存后重读一致。录入沿用书桌位置,人工保存前 AI 草稿不落库,版本冲突仍保留本地修改。 |
| TC-55 H5 录入与照片 | R01、R02、R03、R04、R06、R09 | 在手机浏览器登录,新增房间与收纳盒,从盒子录入物品。选照片裁剪,分别看缩略图和原图。确认移位并搜索别名。再提交带两条物品的文字草稿和检查只读角色。 | 录入带入完整位置,图片按裁剪结果保存。删除后列表移除该照片。已确认的批量草稿可在列表重读。只读角色可找物,详情保留查看入口。 |
[测试与演示计划](plan.md)