feat(pc): 增加桌面工作台和两级平面图
continuous-integration/drone/push Build is passing Details

This commit is contained in:
dongjf 2026-11-28 10:44:07 +08:00
parent 47a9392b33
commit 290afcdd10
27 changed files with 2990 additions and 3 deletions

View File

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

View File

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

4
apps/pc/.dockerignore Normal file
View File

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

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

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

11
apps/pc/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 /usr/share/nginx/html

25
apps/pc/README.md Normal file
View File

@ -0,0 +1,25 @@
# 见物桌面工作台
Vue 3、TypeScript、Vue Router 和 Vite。网页使用同源 `/api` 接现有网关,账号、物品和布局与 iOS 共享。
## 本地运行
使用 Node.js 24。在仓库根目录执行:
```sh
npm --prefix apps/pc ci
npm --prefix apps/pc run dev -- --port 4173
```
打开 `http://127.0.0.1:4173`。开发代理默认使用公网预览 API,可用 `ATLAS_GATEWAY_URL` 切换到其他网关。登录令牌只在当前页面内存中使用,刷新页面后重新登录。
## 构建与部署
```sh
npm --prefix apps/pc run build
docker build -t item-atlas-pc:0.1.0 apps/pc
```
镜像监听 8080。容器内 `ATLAS_GATEWAY_URL` 指向可达的网关;同一 Kubernetes 命名空间默认用 `http://item-atlas-gateway:8080`。就绪检查用 `/healthz`,Nginx 负责 SPA 路由和同源 API 转发。外部站点通过 HTTPS 接入。Drone 在现有流水线运行 `build-pc` 构建检查。
[产品交互](../../docs/ui/pc-workbench.md) · [域名与部署](../../docs/deployment/overview.md)

13
apps/pc/index.html Normal file
View File

@ -0,0 +1,13 @@
<!doctype html>
<html lang="zh-CN">
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<link rel="icon" href="/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,22 @@
server {
listen 8080;
root /usr/share/nginx/html;
location = /healthz { return 200; }
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 80s;
}
location /assets/ {
try_files $uri =404;
add_header Cache-Control "public, max-age=31536000, immutable";
}
location / {
add_header Cache-Control "no-cache";
add_header Content-Security-Policy "default-src 'self'; style-src 'self' 'unsafe-inline'; object-src 'none'; base-uri 'self'; frame-ancestors 'none'";
try_files $uri /index.html;
}
}

1252
apps/pc/package-lock.json generated Normal file

File diff suppressed because it is too large Load Diff

22
apps/pc/package.json Normal file
View File

@ -0,0 +1,22 @@
{
"name": "item-atlas-pc",
"version": "0.1.0",
"private": true,
"type": "module",
"scripts": {
"dev": "vite",
"check": "vue-tsc --noEmit",
"build": "vue-tsc --noEmit && vite build"
},
"dependencies": {
"@lucide/vue": "1.82.0",
"vue": "3.5.46",
"vue-router": "4.6.4"
},
"devDependencies": {
"@vitejs/plugin-vue": "6.0.9",
"typescript": "5.9.3",
"vite": "8.3.8",
"vue-tsc": "3.2.5"
}
}

BIN
apps/pc/public/brand.png Normal file

Binary file not shown.

After

Width:  |  Height:  |  Size: 5.5 KiB

128
apps/pc/src/App.vue Normal file
View File

@ -0,0 +1,128 @@
<script setup lang="ts">
import { computed, ref, watch } from 'vue'
import { Boxes, ChevronDown, House, LayoutGrid, LogOut, Map, Plus } from '@lucide/vue'
import { api, login, logout, message, signedIn } from './api'
import type { Space } from './types'
const username = ref('')
const password = ref('')
const error = ref('')
const busy = ref(false)
const spaces = ref<Space[]>([])
const selected = ref('')
const spaceName = ref('')
const creating = ref(false)
const dirty = ref(false)
const space = computed(() => spaces.value.find((entry) => entry.id === selected.value))
watch(signedIn, (active) => {
if (active) void loadSpaces()
else {
spaces.value = []
selected.value = ''
dirty.value = false
}
})
async function loadSpaces() {
busy.value = true
error.value = ''
try {
spaces.value = await api<Space[]>('/api/households')
if (!spaces.value.some((entry) => entry.id === selected.value)) selected.value = spaces.value[0]?.id ?? ''
} catch (cause) { if (signedIn.value) error.value = message(cause) }
finally { busy.value = false }
}
async function signIn() {
busy.value = true
error.value = ''
try {
await login(username.value.trim(), password.value)
password.value = ''
} catch (cause) { error.value = message(cause) }
finally { busy.value = false }
}
function mayLeave() {
return !dirty.value || window.confirm('平面图有未保存的修改,确定放弃吗?')
}
function switchSpace(event: Event) {
const input = event.target as HTMLSelectElement
if (!mayLeave()) { input.value = selected.value; return }
dirty.value = false
selected.value = input.value
}
async function createSpace() {
if (!spaceName.value.trim() || busy.value || !mayLeave()) return
busy.value = true
error.value = ''
try {
const entry = await api<Space>('/api/households', { method: 'POST', body: { name: spaceName.value.trim() } })
spaces.value = [...spaces.value, entry]
dirty.value = false
selected.value = entry.id
creating.value = false
spaceName.value = ''
} catch (cause) { error.value = message(cause) }
finally { busy.value = false }
}
function signOut() {
if (mayLeave()) { error.value = ''; void logout() }
}
</script>
<template>
<main v-if="!signedIn" class="login-page">
<div class="sign-in-card">
<div class="brand sign-in-brand"><img src="/brand.png" alt="" /><strong>见物</strong></div>
<p class="brand-line">于寻常处,见生活。</p>
<form class="fields" @submit.prevent="signIn">
<label>见物账号<input v-model="username" autocomplete="username" required maxlength="100" /></label>
<label>密码<input v-model="password" type="password" autocomplete="current-password" required /></label>
<p v-if="error" class="notice error" role="alert">{{ error }}</p>
<button class="primary full" :disabled="busy">{{ busy ? '登录中…' : '登录' }}</button>
</form>
</div>
</main>
<div v-else class="shell">
<aside class="rail">
<div class="brand"><img src="/brand.png" alt="" /><strong>见物</strong></div>
<div class="space-control">
<House :size="17" aria-hidden="true" />
<select aria-label="当前空间" :value="selected" @change="switchSpace">
<option v-if="!selected" value="" disabled>选择空间</option>
<option v-for="entry in spaces" :key="entry.id" :value="entry.id">{{ entry.name }}</option>
</select>
<ChevronDown :size="13" aria-hidden="true" />
</div>
<nav aria-label="工作台">
<RouterLink to="/items"><Boxes :size="18" />物品</RouterLink>
<RouterLink to="/floor-plan"><Map :size="18" />平面图</RouterLink>
</nav>
<div class="rail-footer">
<button class="quiet" @click="creating = !creating"><Plus :size="16" />新建空间</button>
<button class="quiet" @click="signOut"><LogOut :size="16" />退出登录</button>
</div>
</aside>
<main class="workspace">
<form v-if="creating" class="create-space" @submit.prevent="createSpace">
<label>空间名称<input v-model="spaceName" required maxlength="100" /></label>
<button class="primary" :disabled="busy">创建</button>
<button type="button" @click="creating = false">取消</button>
</form>
<p v-if="error" class="notice error workspace-notice" role="alert">{{ error }} <button @click="loadSpaces">重试</button></p>
<RouterView v-if="space" v-slot="{ Component }">
<component :is="Component" :key="space.id" :space="space" @dirty="dirty = $event" />
</RouterView>
<div v-else class="empty workspace-empty">
<LayoutGrid :size="30" />
<h1>{{ busy ? '正在读取空间' : '选择一个空间' }}</h1>
<button v-if="!busy && !spaces.length" class="primary" @click="creating = true"><Plus :size="16" />新建空间</button>
</div>
</main>
</div>
</template>

99
apps/pc/src/api.ts Normal file
View File

@ -0,0 +1,99 @@
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 }
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' })
if (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: 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 + ')')
}
return response.status === 204 ? undefined as T : 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 { onMounted, ref, watch } from 'vue'
import { Box, Keyboard, Sparkles, X } from '@lucide/vue'
import { api, message } from '../api'
import { family, type Draft, type Item, type Operation, type Place } from '../types'
const props = defineProps<{ space: string; places: Place[]; location: string; item?: Item }>()
const emit = defineEmits<{ close: []; saved: [id?: string] }>()
const dialog = ref<HTMLDialogElement>()
const mode = ref<'manual' | 'text'>('manual')
const name = ref(props.item?.name ?? '')
const quantity = ref(props.item?.quantity ?? 1)
const location = ref(props.location)
const aliases = ref(props.item?.aliases.join('、') ?? '')
const notes = ref(props.item?.notes ?? '')
const text = ref('')
const draft = ref<Draft>()
const candidates = ref<{ name: string; quantity: number; location: string; enabled: boolean; hint: string }[]>([])
const operation = ref<Operation>()
const busy = ref(false)
const error = ref('')
const root = family(props.space)
let lastInput = ''
let requestKey = ''
onMounted(() => dialog.value?.showModal())
watch(text, () => {
if (!operation.value) { draft.value = undefined; candidates.value = [] }
})
function close() {
if (!busy.value) emit('close')
}
async function run(action: () => Promise<void>) {
if (busy.value) return
busy.value = true
error.value = ''
try { await action() } catch (cause) { error.value = message(cause) }
finally { busy.value = false }
}
async function save() {
if (!name.value.trim()) { error.value = '请输入物品名称。'; 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: quantity.value, notes: notes.value, aliases: names }
const input = { ...body, locationId: location.value || null }
const serialized = JSON.stringify(input)
if (serialized !== lastInput) { lastInput = serialized; requestKey = crypto.randomUUID() }
const item = props.item
? await api<Item>(root + '/items/' + props.item.id, { method: 'PUT', body: { ...body, version: props.item.version } })
: await api<Item>(root + '/items', { method: 'POST', body: input, idempotencyKey: requestKey })
emit('saved', item.id)
})
}
async function generate() {
if (!text.value.trim()) return
await run(async () => {
const created = await api<Draft>(root + '/drafts', { method: 'POST', body: { text: text.value.trim(), source: 'MODEL' } })
draft.value = created
candidates.value = created.candidates.map((row) => {
const hint = row.location?.trim() ?? ''
const matches = hint ? props.places.filter((place) => place.path === hint || place.name === hint) : []
return { name: row.name, quantity: row.quantity ?? 1,
location: matches.length === 1 ? matches[0].id : hint ? '' : props.location,
enabled: row.action === 'RECORD', hint }
}).filter((_, index) => created.candidates[index].action !== 'SKIP')
if (created.status === 'MODEL_UNAVAILABLE') error.value = '模型暂不可用,可以保留这段文字并改用手动录入。'
else if (!candidates.value.length) error.value = '这段文字没有生成可核对的物品。'
})
}
async function checkOperation() {
if (!operation.value) return
const path = root + '/operations/' + operation.value.id
for (let retries = 0; retries < 8; retries++) {
if (operation.value.status === 'COMPLETED') { emit('saved'); return }
if (['FAILED', 'REJECTED', 'NEEDS_REVIEW'].includes(operation.value.status)) return
await new Promise((resolve) => setTimeout(resolve, 450))
operation.value = await api<Operation>(path)
}
if (operation.value.status === 'COMPLETED') emit('saved')
}
async function confirm() {
const current = draft.value
const items = candidates.value.filter((row) => row.enabled).map((row) => ({
name: row.name.trim(), quantity: row.quantity, locationId: row.location || null, notes: '', aliases: [],
}))
if (!current || !items.length) return
if (items.some((row) => !row.name)) { error.value = '已勾选的物品都需要名称。'; return }
await run(async () => {
operation.value = await api<Operation>(root + '/drafts/' + current.id + '/confirm', {
method: 'POST', body: { version: current.version, items, automatic: false },
})
await checkOperation()
})
}
</script>
<template>
<dialog ref="dialog" class="modal intake-modal" @cancel.prevent="close">
<header class="modal-header">
<h2>{{ item ? '编辑物品' : '录入物品' }}</h2>
<button class="icon-button" type="button" aria-label="关闭" :disabled="busy" @click="close"><X :size="20" /></button>
</header>
<div v-if="!item" class="segmented intake-tabs" aria-label="录入方式">
<button :aria-pressed="mode === 'manual'" :disabled="busy || !!operation" @click="mode = 'manual'"><Box :size="16" />手动添加</button>
<button :aria-pressed="mode === 'text'" :disabled="busy || !!operation" @click="mode = 'text'"><Keyboard :size="16" />文字批量录入</button>
</div>
<p v-if="error" class="notice error" role="alert">{{ error }}</p>
<form v-if="mode === 'manual'" class="fields" @submit.prevent="save">
<label>名称<input v-model="name" autofocus required maxlength="150" placeholder="例如 HDMI 线" /></label>
<div class="form-row">
<label>数量<input v-model.number="quantity" required type="number" min="1" max="9999" /></label>
<label v-if="!item">存放位置<select v-model="location"><option value="">暂不设置</option><option v-for="place in places" :key="place.id" :value="place.id">{{ place.path }}</option></select></label>
</div>
<label>别名<input v-model="aliases" placeholder="可用逗号隔开" /></label>
<label>备注<textarea v-model="notes" rows="3" maxlength="1500"></textarea></label>
<div class="modal-actions"><button type="button" @click="close">取消</button><button class="primary" :disabled="busy">{{ busy ? '保存中…' : '保存物品' }}</button></div>
</form>
<form v-else class="fields" @submit.prevent="confirm">
<label>要记录的物品<textarea v-model="text" rows="4" maxlength="4000" :disabled="busy || !!operation" placeholder="两根 HDMI 线放书房抽屉,备用钥匙放玄关。"></textarea></label>
<button v-if="!operation" type="button" :disabled="busy || !text.trim()" @click="generate"><Sparkles :size="16" />整理草稿</button>
<fieldset v-if="candidates.length" class="candidate-list" :disabled="busy || !!operation">
<legend>核对要保存的物品</legend>
<div v-for="(row, index) in candidates" :key="index" class="candidate">
<input v-model="row.enabled" type="checkbox" :aria-label="'选择第 ' + (index + 1) + ' 件'" />
<input v-model="row.name" required maxlength="150" aria-label="物品名称" />
<input v-model.number="row.quantity" required min="1" max="9999" type="number" aria-label="数量" />
<select v-model="row.location" :aria-label="row.hint ? '原话位置 ' + row.hint : '存放位置'"><option value="">暂不设置</option><option v-for="place in places" :key="place.id" :value="place.id">{{ place.path }}</option></select>
</div>
</fieldset>
<div class="modal-actions">
<button type="button" @click="close">{{ operation ? '关闭' : '取消' }}</button>
<template v-if="operation">
<span v-if="['FAILED', 'REJECTED', 'NEEDS_REVIEW'].includes(operation.status)" class="notice error">交付未完成,请记下操作号 {{ operation.id }}</span>
<button v-else type="button" class="primary" :disabled="busy" @click="run(checkOperation)">刷新交付进度</button>
</template>
<button v-else-if="candidates.length" class="primary" :disabled="busy || !candidates.some((row) => row.enabled)">确认保存</button>
</div>
</form>
</dialog>
</template>

View File

@ -0,0 +1,217 @@
<script setup lang="ts">
import { computed, ref, watch } from 'vue'
import { Archive, ArrowLeftRight, ArrowRight, Box, ChevronRight, Folder, House, Map, Plus, Search, Star } from '@lucide/vue'
import { useRoute, useRouter } from 'vue-router'
import { api, message } from '../api'
import { family, type Item, type ItemDetail, type Place, type Space } from '../types'
import IntakeDialog from './IntakeDialog.vue'
const props = defineProps<{ space: Space }>()
const route = useRoute()
const router = useRouter()
const root = family(props.space.id)
const canWrite = computed(() => props.space.role !== 'VIEWER')
const query = ref('')
const location = computed(() => typeof route.query.location === 'string' ? route.query.location : '')
const subtree = ref(true)
const onlyFavorites = ref(false)
const places = ref<Place[]>([])
const items = ref<Item[]>([])
const detail = ref<ItemDetail>()
const selected = ref('')
const detailError = ref('')
const listError = ref('')
const locationError = ref('')
const loading = ref(true)
const more = ref(false)
const next = ref(0)
const revision = ref(0)
const intake = ref<'add' | 'edit'>()
const moving = ref(false)
const moveTo = ref('')
const busy = ref(false)
const writeError = ref('')
const folder = computed(() => places.value.find((place) => place.id === location.value))
const hasChildren = computed(() => places.value.some((place) => place.parentId === folder.value?.id))
const filters = computed(() => {
const value = new URLSearchParams({ limit: '50', q: query.value.trim(), favorites: String(onlyFavorites.value) })
if (location.value) {
value.set('location', location.value)
if (subtree.value) value.set('includeDescendants', 'true')
}
return value.toString()
})
const path = computed(() => root + '/items?' + filters.value)
async function fetchPlaces(signal?: AbortSignal) {
try { places.value = await api<Place[]>(root + '/locations', { signal }); locationError.value = '' }
catch (cause) { if (!signal?.aborted) locationError.value = message(cause) }
}
watch(() => props.space.id, (_, __, clean) => {
const controller = new AbortController()
clean(() => controller.abort())
void fetchPlaces(controller.signal)
}, { immediate: true })
watch([path, revision], (_, __, clean) => {
const controller = new AbortController()
const endpoint = path.value
loading.value = true
listError.value = ''
items.value = []
more.value = false
next.value = 0
const timer = window.setTimeout(async () => {
try {
const page = await api<Item[]>(endpoint, { signal: controller.signal })
if (!controller.signal.aborted) { items.value = page; more.value = page.length === 50; next.value = page.length }
} catch (cause) { if (!controller.signal.aborted) listError.value = message(cause) }
finally { if (!controller.signal.aborted) loading.value = false }
}, query.value.trim() ? 180 : 0)
clean(() => { clearTimeout(timer); controller.abort() })
}, { immediate: true })
watch([selected, revision], async ([id], _, clean) => {
detail.value = undefined
detailError.value = ''
if (!id) return
const controller = new AbortController()
clean(() => controller.abort())
try { detail.value = await api<ItemDetail>(root + '/items/' + id, { signal: controller.signal }) }
catch (cause) { if (!controller.signal.aborted) detailError.value = message(cause) }
}, { immediate: true })
async function loadMore() {
const endpoint = path.value
const version = revision.value
const offset = next.value
loading.value = true
listError.value = ''
try {
const page = await api<Item[]>(endpoint + '&offset=' + offset)
if (path.value !== endpoint || revision.value !== version) return
const existing = new Set(items.value.map((item) => item.id))
items.value = [...items.value, ...page.filter((item) => !existing.has(item.id))]
next.value += page.length
more.value = page.length === 50 && next.value <= 10000
} catch (cause) { if (path.value === endpoint && revision.value === version) listError.value = message(cause) }
finally { if (path.value === endpoint && revision.value === version) loading.value = false }
}
function chooseLocation(id: string) {
selected.value = ''
void router.replace({ query: id ? { location: id } : {} })
}
function openItem(id: string) {
if (busy.value) return
moving.value = false
writeError.value = ''
selected.value = id
}
function saved(id?: string) {
intake.value = undefined
if (id) selected.value = id
revision.value++
}
async function update(method: string, suffix = '', body?: unknown) {
const item = detail.value?.item
if (!item || busy.value) return
busy.value = true
writeError.value = ''
try {
await api(root + '/items/' + item.id + suffix, { method, body })
if (method === 'DELETE') selected.value = ''
moving.value = false
revision.value++
} catch (cause) { writeError.value = message(cause) }
finally { busy.value = false }
}
function archiveItem(item: Item) {
if (window.confirm('删除「' + item.name + '」和它的照片?')) void update('DELETE', '?version=' + item.version)
}
</script>
<template>
<div class="inventory-page">
<header class="page-header">
<div><div class="crumb">{{ space.name }}<ChevronRight :size="14" />{{ folder?.path || '物品' }}</div><h1>物品</h1></div>
<button v-if="canWrite" class="primary" @click="intake = 'add'"><Plus :size="18" />录入物品</button>
</header>
<div class="inventory-grid" :class="{ 'has-detail': selected }">
<aside class="panel location-tree" aria-label="位置">
<h2>位置</h2>
<button class="tree-row" :class="{ current: !location && !onlyFavorites }" @click="onlyFavorites = false; chooseLocation('')"><House :size="16" />全部物品</button>
<button class="tree-row" :class="{ current: onlyFavorites }" @click="onlyFavorites = true; chooseLocation('')"><Star :size="16" />我的收藏</button>
<div class="tree-divider"></div>
<p v-if="locationError" class="notice error">{{ locationError }} <button @click="fetchPlaces()">重试</button></p>
<p v-else-if="!places.length" class="secondary small">空间还没有位置</p>
<button v-for="place in places" :key="place.id" class="tree-row" :class="{ current: location === place.id }"
:style="{ paddingInlineStart: (10 + Math.min(5, Math.max(0, (place.depth || 1) - 1)) * 13) + 'px' }"
:title="place.path" @click="onlyFavorites = false; chooseLocation(place.id)">
<Folder :size="15" /><span>{{ place.name }}</span>
</button>
<RouterLink class="tree-row tree-link" :to="{ name: 'plan', query: folder ? { position: folder.id } : {} }"><Map :size="16" />打开平面图</RouterLink>
</aside>
<section class="panel item-list" aria-label="物品列表">
<div class="list-toolbar">
<label class="search-field"><Search :size="17" /><input v-model="query" aria-label="找物" placeholder="搜名称、别名或位置" maxlength="150" /></label>
<label v-if="folder && hasChildren" class="check-field"><input v-model="subtree" type="checkbox" />含下级位置</label>
</div>
<p v-if="listError" class="notice error" role="alert">{{ listError }} <button @click="revision++">重试</button></p>
<div v-if="items.length" class="table-wrap">
<table>
<thead><tr><th>物品</th><th>存放位置</th><th>数量</th></tr></thead>
<tbody>
<tr v-for="item in items" :key="item.id" :class="{ 'active-row': selected === item.id }">
<td><button class="item-cell" @click="openItem(item.id)"><span class="item-mark"><Box :size="17" /></span><span>{{ item.name }}</span></button></td>
<td><button class="table-path" @click="openItem(item.id)">{{ item.locationPath || '未设置' }}</button></td>
<td>{{ item.quantity }}</td>
</tr>
</tbody>
</table>
</div>
<p v-if="loading" class="list-status" role="status">正在读取物品…</p>
<div v-else-if="!items.length && !listError" class="empty">
<Box :size="31" /><h2>{{ query.trim() ? '没有找到物品' : '这里还没有物品' }}</h2>
<button v-if="canWrite && !query.trim() && !onlyFavorites" @click="intake = 'add'"><Plus :size="16" />添加物品</button>
</div>
<div v-if="more" class="list-status"><button :disabled="loading" @click="loadMore">加载更多</button></div>
</section>
<aside v-if="selected" class="panel item-detail" aria-label="物品详情">
<div class="detail-header"><h2>物品详情</h2><button class="quiet" :disabled="busy" @click="openItem('')">关闭</button></div>
<p v-if="detailError" class="notice error">{{ detailError }} <button @click="revision++">重试</button></p>
<p v-else-if="!detail" class="secondary" role="status">正在读取详情…</p>
<template v-else>
<div class="detail-hero"><span class="item-mark"><Box :size="22" /></span><h3>{{ detail.item.name }}</h3></div>
<dl>
<dt>存放位置</dt><dd>{{ detail.item.locationPath || '未设置' }}</dd>
<dt>数量</dt><dd>{{ detail.item.quantity }}</dd>
<template v-if="detail.item.aliases.length"><dt>别名</dt><dd>{{ detail.item.aliases.join('、') }}</dd></template>
<template v-if="detail.item.notes"><dt>备注</dt><dd class="plain-text">{{ detail.item.notes }}</dd></template>
</dl>
<div class="detail-actions">
<RouterLink v-if="detail.item.locationId" class="action" :to="{ name: 'plan', query: { position: detail.item.locationId } }"><Map :size="16" />在图中查看</RouterLink>
<button :disabled="busy" @click="update('PUT', '/preference', { ...detail.preference, favorite: !detail.preference.favorite })"><Star :size="16" />{{ detail.preference.favorite ? '取消收藏' : '收藏' }}</button>
<button v-if="canWrite" :disabled="busy" @click="intake = 'edit'">编辑</button>
<button v-if="canWrite" :disabled="busy" @click="moving = !moving; moveTo = detail.item.locationId ?? ''"><ArrowLeftRight :size="16" />移位</button>
</div>
<form v-if="moving && canWrite" class="fields move-form" @submit.prevent="update('POST', '/moves', { locationId: moveTo || null, version: detail.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>
<button class="primary" :disabled="busy || (moveTo || null) === detail.item.locationId">确认移位</button>
</form>
<p v-if="writeError" class="notice error" role="alert">{{ writeError }}</p>
<div v-if="detail.moves.length" class="move-history">
<h3>移位记录</h3>
<p v-for="(entry, index) in detail.moves" :key="index"><span>{{ entry.fromPath || '未设置' }} <ArrowRight :size="13" /> {{ entry.toPath || '未设置' }}</span><time>{{ entry.movedAt.slice(0, 10) }}</time></p>
</div>
<button v-if="canWrite" class="quiet danger" :disabled="busy" @click="archiveItem(detail.item)"><Archive :size="16" />删除物品</button>
</template>
</aside>
</div>
<IntakeDialog v-if="intake" :space="space.id" :places="places" :location="location" :item="intake === 'edit' ? detail?.item : undefined" @close="intake = undefined" @saved="saved" />
</div>
</template>

17
apps/pc/src/main.ts Normal file
View File

@ -0,0 +1,17 @@
import { createApp } from 'vue'
import { createRouter, createWebHistory } from 'vue-router'
import App from './App.vue'
import Inventory from './items/Inventory.vue'
import FloorPlan from './plan/FloorPlan.vue'
import './style.css'
const router = createRouter({
history: createWebHistory(),
routes: [
{ path: '/', redirect: '/items' },
{ path: '/items', name: 'items', component: Inventory },
{ path: '/floor-plan', name: 'plan', component: FloorPlan },
{ path: '/:pathMatch(.*)*', redirect: '/items' },
],
})
createApp(App).use(router).mount('#app')

View File

@ -0,0 +1,461 @@
<script setup lang="ts">
import { computed, onBeforeUnmount, onMounted, ref, shallowRef, watch } from 'vue'
import { Armchair, ArrowUpRight, Box, ChevronRight, Grid2X2, Layers, MousePointer2, Plus, Redo2, RotateCw, Save, Sparkles, SquareDashed, Trash2, Undo2, X } from '@lucide/vue'
import { onBeforeRouteLeave, onBeforeRouteUpdate, useRoute } from 'vue-router'
import { ApiError, api, message } from '../api'
import { family, type Place, type Space } from '../types'
import { defaultGeometry, fit, kind, roomConflict, templates, type Geometry, type Placement, type Slot,
type Snapshot, type Suggestion, type Template } from './geometry'
import PlanCanvas from './PlanCanvas.vue'
const props = defineProps<{ space: Space }>()
const emit = defineEmits<{ dirty: [dirty: boolean] }>()
const root = family(props.space.id)
const route = useRoute()
const canEdit = computed(() => props.space.role !== 'VIEWER')
const places = ref<Place[]>([])
const parent = ref('')
const target = ref<Place>()
const snapshot = shallowRef<Snapshot>()
const stable = shallowRef<Placement[]>([])
const placed = shallowRef<Placement[]>([])
const undoSteps = shallowRef<Placement[][]>([])
const redoSteps = shallowRef<Placement[][]>([])
const selected = ref('')
const snapping = ref(true)
const loading = ref(true)
const saving = ref(false)
const error = ref('')
const versionConflict = ref(false)
const status = ref('')
const aiDialog = ref<HTMLDialogElement>()
const prompt = ref('')
const suggesting = ref(false)
const aiError = ref('')
const suggestions = ref<Suggestion[]>([])
const accepted = ref<number[]>([])
const proposalPreview = computed(() => proposedLayout((index) => 'proposal-' + index))
const locationList = computed(() => places.value.filter((place) => !place.parentId))
const activeRoom = computed(() => locationList.value.find((place) => place.id === parent.value))
const activeShape = computed(() => placed.value.find((placement) => placement.id === selected.value))
const slotIds = computed(() => new Set(placed.value.map((placement) => placement.id)))
const unplaced = computed(() => snapshot.value?.locations.filter((slot) => !slotIds.value.has(slot.id)) ?? [])
const conflict = computed(() => roomConflict(placed.value))
const dirty = computed(() => JSON.stringify(stable.value) !== JSON.stringify(placed.value))
const palette = computed(() => Object.entries(templates)
.map(([key, value]) => ({ key: key as Template, label: value[0], kind: value[3] }))
.filter((entry) => !parent.value || entry.kind !== 'room'))
const templateGroups = [{ type: 'room', name: '房间', icon: Grid2X2 },
{ type: 'area', name: '区域', icon: SquareDashed }, { type: 'furniture', name: '家具和收纳', icon: Armchair }] as const
const dimensions = [{ key: 'xMm', label: '向右 X' }, { key: 'yMm', label: '向下 Y' },
{ key: 'widthMm', label: '宽度' }, { key: 'depthMm', label: '进深' }] as const
let reading: AbortController | undefined
let disposed = false
watch(dirty, (value) => emit('dirty', value))
watch(prompt, () => { suggestions.value = []; accepted.value = [] })
watch(() => route.query.position, () => { if (locationsReady) void followPosition() })
let locationsReady = false
function layoutPath(scope = parent.value) {
return root + '/location-layout' + (scope ? '?parentId=' + encodeURIComponent(scope) : '')
}
function loadSnapshot(data: Snapshot) {
snapshot.value = data
stable.value = data.locations.flatMap((slot) => slot.geometry
? [{ id: slot.id, name: slot.name, geometry: slot.geometry }] : [])
placed.value = stable.value
undoSteps.value = []
redoSteps.value = []
tidySelection()
}
async function loadPlan(scope = parent.value, focus = '', fallback = '') {
reading?.abort()
const controller = new AbortController()
reading = controller
parent.value = scope
snapshot.value = undefined
placed.value = []
stable.value = []
undoSteps.value = []
redoSteps.value = []
selected.value = ''
loading.value = true
error.value = ''
versionConflict.value = false
status.value = ''
suggestions.value = []
accepted.value = []
try {
let data = await api<Snapshot>(layoutPath(scope), { signal: controller.signal })
if (scope && fallback && focus && !data.locations.some((slot) => slot.id === focus && slot.geometry)) {
data = await api<Snapshot>(layoutPath(''), { signal: controller.signal })
scope = ''
focus = fallback
}
if (!controller.signal.aborted && !disposed) {
parent.value = scope
loadSnapshot(data)
if (data.locations.some((slot) => slot.id === focus)) selected.value = focus
}
} catch (cause) { if (!controller.signal.aborted) error.value = message(cause) }
finally { if (!controller.signal.aborted) loading.value = false }
}
async function followPosition() {
const id = typeof route.query.position === 'string' ? route.query.position : ''
const index = new Map(places.value.map((place) => [place.id, place]))
target.value = index.get(id)
const visited = new Set<string>()
let current = target.value
let child: Place | undefined
while (current?.parentId && !visited.has(current.id)) {
visited.add(current.id)
child = current
current = index.get(current.parentId)
}
if (!current || visited.has(current.id)) await loadPlan('')
else if (child) await loadPlan(current.id, child.id, current.id)
else await loadPlan('', current.id)
}
async function start() {
loading.value = true
error.value = ''
try {
places.value = await api<Place[]>(root + '/locations')
if (disposed) return
locationsReady = true
await followPosition()
} catch (cause) {
if (!disposed) { error.value = message(cause); loading.value = false }
}
}
function mayDiscard() {
return !saving.value && (!dirty.value || window.confirm('放弃未保存的平面图修改?'))
}
function changeRoom(event: Event) {
const input = event.target as HTMLSelectElement
if (!mayDiscard()) { input.value = parent.value; return }
target.value = undefined
void loadPlan(input.value)
}
function tidySelection() {
if (!placed.value.some((entry) => entry.id === selected.value)) selected.value = ''
}
function edit(next: Placement[]) {
if (JSON.stringify(next) === JSON.stringify(placed.value)) return
undoSteps.value = [...undoSteps.value.slice(-79), placed.value]
redoSteps.value = []
placed.value = next
status.value = ''
if (!versionConflict.value) error.value = ''
tidySelection()
}
function undo() {
const previous = undoSteps.value.at(-1)
if (!previous || saving.value) return
redoSteps.value = [...redoSteps.value, placed.value]
undoSteps.value = undoSteps.value.slice(0, -1)
placed.value = previous
tidySelection()
}
function redo() {
const next = redoSteps.value.at(-1)
if (!next || saving.value) return
undoSteps.value = [...undoSteps.value, placed.value]
redoSteps.value = redoSteps.value.slice(0, -1)
placed.value = next
tidySelection()
}
function uniqueName(base: string) {
const siblings = new Set([...(snapshot.value?.locations ?? []), ...placed.value].map((entry) => entry.name.toLowerCase()))
let name = base
for (let index = 2; siblings.has(name.toLowerCase()); index++) name = base + ' ' + index
return name
}
function add(template: Template, slot?: Slot) {
if (!snapshot.value || !canEdit.value || saving.value) return
const name = slot?.name ?? uniqueName(templates[template][0])
const geometry = defaultGeometry(template, snapshot.value, placed.value)
const id = slot?.id ?? crypto.randomUUID()
edit([...placed.value, { id, name, newName: slot ? undefined : name, geometry }])
selected.value = id
}
function placeSlot(slot: Slot) {
if (slot.geometry) {
edit([...placed.value, { id: slot.id, name: slot.name, geometry: slot.geometry }])
selected.value = slot.id
return
}
const preferred = Object.hasOwn(templates, slot.icon) ? slot.icon as Template : undefined
const template = preferred && (!parent.value || kind(preferred) !== 'room') ? preferred : parent.value ? 'STORAGE_BOX' : 'ROOM'
add(template, slot)
}
function updateGeometry(id: string, geometry: Geometry) {
if (!canEdit.value || !snapshot.value || saving.value) return
const allowed = fit(geometry, snapshot.value)
edit(placed.value.map((entry) => entry.id === id ? { ...entry, geometry: allowed } : entry))
}
function updateDimension(field: typeof dimensions[number]['key'], event: Event) {
const shape = activeShape.value
const input = event.target as HTMLInputElement
const value = input.valueAsNumber
if (!shape || !Number.isFinite(value)) {
if (shape) input.value = String(shape.geometry[field] / 10)
return
}
const geometry = { ...shape.geometry, [field]: Math.round(value * 10) }
updateGeometry(shape.id, geometry)
input.value = String((activeShape.value?.geometry[field] ?? shape.geometry[field]) / 10)
}
function rename(event: Event) {
const shape = activeShape.value
const input = event.target as HTMLInputElement
const name = input.value.trim()
if (!shape?.newName || !name) { if (shape) input.value = shape.name; return }
edit(placed.value.map((entry) => entry.id === shape.id ? { ...entry, name, newName: name } : entry))
}
function rotate() {
if (!activeShape.value) return
const { id, geometry } = activeShape.value
updateGeometry(id, { ...geometry, widthMm: geometry.depthMm, depthMm: geometry.widthMm, rotation: (geometry.rotation + 90) % 360 })
}
function remove() {
if (canEdit.value && selected.value && !saving.value) edit(placed.value.filter((entry) => entry.id !== selected.value))
}
function discard() {
if (!mayDiscard()) return
if (snapshot.value) loadSnapshot(snapshot.value)
if (!versionConflict.value) error.value = ''
status.value = ''
}
async function save() {
const baseline = snapshot.value
if (!baseline || !canEdit.value || !dirty.value || saving.value || conflict.value || versionConflict.value) return
saving.value = true
error.value = ''
status.value = ''
try {
const data = await api<Snapshot>(layoutPath(''), { method: 'PUT', body: {
parentId: parent.value || null, version: baseline.version,
placements: placed.value.map(({ id, newName, geometry }) => ({ id, newName, geometry })),
} })
if (disposed) return
loadSnapshot(data)
status.value = '平面图已保存'
try { places.value = await api<Place[]>(root + '/locations') }
catch { status.value = '平面图已保存。位置列表会在重新进入时更新。' }
} catch (cause) {
versionConflict.value = cause instanceof ApiError && cause.status === 409
error.value = message(cause)
}
finally { saving.value = false }
}
function openAi() {
aiError.value = ''
aiDialog.value?.showModal()
}
async function generate() {
if (!snapshot.value || !prompt.value.trim() || suggesting.value) return
suggesting.value = true
aiError.value = ''
try {
const draft = await api<{ changes: Suggestion[] }>(root + '/location-layout-drafts', { method: 'POST', body: {
parentId: parent.value || null, version: snapshot.value.version, description: prompt.value.trim(),
} })
suggestions.value = draft.changes
accepted.value = draft.changes.flatMap((proposal, index) => proposal.geometry ? [index] : [])
if (!draft.changes.length) aiError.value = '没有收到布局建议,可以补充位置名称或尺寸。'
} catch (cause) { aiError.value = message(cause) }
finally { suggesting.value = false }
}
function proposedLayout(makeID: (index: number) => string) {
const existing = new Map(placed.value.map((placement) => [placement.id, placement]))
for (const index of accepted.value) {
const suggestion = suggestions.value[index]
if (!suggestion.geometry) continue
const slot = snapshot.value?.locations.find((entry) => entry.id === suggestion.locationId)
const id = slot?.id ?? makeID(index)
const name = slot?.name ?? suggestion.name
existing.set(id, { id, name, newName: slot ? undefined : name, geometry: suggestion.geometry })
}
return [...existing.values()]
}
function applyAi() {
edit(proposedLayout(() => crypto.randomUUID()))
aiDialog.value?.close()
suggestions.value = []
accepted.value = []
}
function onKey(event: KeyboardEvent) {
if (!snapshot.value || !canEdit.value || saving.value || aiDialog.value?.open ||
(event.target instanceof Element && event.target.closest('input, textarea, select, [contenteditable]'))) return
const key = event.key.toLowerCase()
if ((event.metaKey || event.ctrlKey) && key === 'z') {
event.preventDefault()
if (event.shiftKey) redo()
else undo()
return
}
if (event.metaKey || event.ctrlKey) return
if (key === 'delete' || key === 'backspace') {
event.preventDefault()
remove()
return
}
if (key === 'escape') { selected.value = ''; return }
const direction = { arrowleft: [-1, 0], arrowright: [1, 0], arrowup: [0, -1], arrowdown: [0, 1] }[key]
const shape = activeShape.value
if (!shape || !direction) return
event.preventDefault()
const step = event.shiftKey ? 100 : 10
updateGeometry(shape.id, { ...shape.geometry, xMm: shape.geometry.xMm + direction[0] * step,
yMm: shape.geometry.yMm + direction[1] * step })
}
function beforeUnload(event: BeforeUnloadEvent) {
if (dirty.value) { event.preventDefault(); event.returnValue = '' }
}
onBeforeRouteLeave(mayDiscard)
onBeforeRouteUpdate((to, from) => to.query.position === from.query.position || mayDiscard())
onMounted(() => {
window.addEventListener('keydown', onKey)
window.addEventListener('beforeunload', beforeUnload)
void start()
})
onBeforeUnmount(() => {
disposed = true
reading?.abort()
window.removeEventListener('keydown', onKey)
window.removeEventListener('beforeunload', beforeUnload)
emit('dirty', false)
})
</script>
<template>
<div class="plan-page">
<header class="page-header">
<div><div class="crumb">{{ space.name }}<ChevronRight :size="14" />{{ activeRoom?.name || '全屋' }}</div><h1>平面图</h1></div>
<div v-if="canEdit && snapshot" class="header-actions">
<span v-if="dirty" class="save-status"><i></i>有未保存的修改</span>
<button :disabled="!dirty || saving" @click="discard">放弃修改</button>
<button class="primary" :disabled="!dirty || saving || !!conflict || versionConflict" @click="save"><Save :size="16" />{{ saving ? '保存中…' : '保存平面图' }}</button>
</div>
</header>
<p v-if="error" class="notice error" role="alert">
{{ error }}
<button v-if="versionConflict" @click="mayDiscard() && loadPlan()">读取服务器版本</button>
<button v-else-if="!snapshot" @click="locationsReady ? loadPlan() : start()">重试</button>
</p>
<p v-else-if="conflict" class="notice error" role="alert">「{{ conflict.name }}」与另一个房间重叠,请先调整位置。</p>
<p v-else-if="status" class="notice success" role="status">{{ status }}</p>
<div v-if="loading" class="empty panel plan-loading" role="status">正在读取平面图…</div>
<div v-else-if="snapshot" class="plan-shell">
<div class="plan-toolbar">
<div class="toolbar-group">
<Layers :size="17" aria-hidden="true" />
<select aria-label="平面图范围" :value="parent" :disabled="saving" @change="changeRoom">
<option value="">全屋平面图</option>
<option v-for="room in locationList" :key="room.id" :value="room.id">{{ room.name }} · 室内</option>
</select>
</div>
<div v-if="canEdit" class="toolbar-group plan-edit-tools">
<button class="icon-button" aria-label="撤回" title="撤回(Ctrl / ⌘ + Z)" :disabled="!undoSteps.length || saving" @click="undo"><Undo2 :size="18" /></button>
<button class="icon-button" aria-label="重做" title="重做(Ctrl / ⌘ + Shift + Z)" :disabled="!redoSteps.length || saving" @click="redo"><Redo2 :size="18" /></button>
<label class="check-field snap-toggle"><input v-model="snapping" type="checkbox" />吸附</label>
</div>
<button v-if="canEdit" class="ai-button" :disabled="saving" @click="openAi"><Sparkles :size="16" />AI 建模</button>
</div>
<div class="plan-columns" :class="{ readonly: !canEdit }">
<aside v-if="canEdit" class="plan-library" aria-label="模板与位置">
<div class="pane-title"><h2>添加到图上</h2></div>
<div v-if="unplaced.length" class="template-group">
<h3>已有位置</h3>
<button v-for="slot in unplaced" :key="slot.id" class="library-option" :disabled="saving" @click="placeSlot(slot)"><Plus :size="16" /><span>{{ slot.name }}</span></button>
</div>
<div v-for="group in templateGroups.filter((group) => !parent || group.type !== 'room')" :key="group.type" class="template-group">
<h3>{{ group.name }}</h3>
<button v-for="entry in palette.filter((entry) => entry.kind === group.type)" :key="entry.key" class="library-option" :disabled="saving" @click="add(entry.key)">
<component :is="group.icon" :size="16" /><span>{{ entry.label }}</span><Plus :size="14" class="append-icon" />
</button>
</div>
</aside>
<div class="canvas-column">
<div v-if="target" class="map-target">{{ target.path }}</div>
<PlanCanvas :key="parent || 'root'" :board="snapshot" :placements="placed" :selected="selected"
:editable="canEdit && !saving" :snapping="snapping" @select="selected = $event" @geometry="updateGeometry" />
<div class="canvas-footer"><span>{{ snapshot.widthMm / 1000 }} × {{ snapshot.depthMm / 1000 }} 米</span><span v-if="canEdit">滚轮缩放 · 拖空白平移 · 方向键微调</span></div>
</div>
<aside class="plan-properties" aria-label="位置属性">
<div class="pane-title"><h2>位置属性</h2></div>
<template v-if="activeShape">
<div class="shape-property">
<span class="property-symbol"><Box :size="20" /></span>
<input v-if="activeShape.newName && canEdit" :key="activeShape.id" aria-label="位置名称" :value="activeShape.name" maxlength="100" :disabled="saving" @change="rename" />
<h3 v-else>{{ activeShape.name }}</h3>
</div>
<fieldset class="property-fields" :disabled="saving || !canEdit">
<label v-for="field in dimensions" :key="field.key">{{ field.label }}
<span><input type="number" step="0.1" :min="field.key === 'widthMm' || field.key === 'depthMm' ? 10 : 0" :value="activeShape.geometry[field.key] / 10" @change="updateDimension(field.key, $event)" /><small>cm</small></span>
</label>
</fieldset>
<div v-if="canEdit" class="property-actions">
<button :disabled="saving" @click="rotate"><RotateCw :size="16" />旋转 90°</button>
<button class="danger" :disabled="saving" @click="remove"><Trash2 :size="16" />移出平面图</button>
</div>
<div v-if="!activeShape.newName" class="property-actions">
<button v-if="!parent" @click="mayDiscard() && loadPlan(activeShape.id)">打开室内平面图 <ArrowUpRight :size="15" /></button>
<RouterLink class="action" :to="{ name: 'items', query: { location: activeShape.id } }">查看这里的物品 <ArrowUpRight :size="15" /></RouterLink>
</div>
</template>
<div v-else class="property-empty"><MousePointer2 :size="20" /><p>在图上选择一个位置</p></div>
</aside>
</div>
</div>
<dialog ref="aiDialog" class="modal" @cancel="suggesting && $event.preventDefault()">
<header class="modal-header"><h2>AI 建模</h2><button class="icon-button" aria-label="关闭" :disabled="suggesting" @click="aiDialog?.close()"><X :size="20" /></button></header>
<form class="fields" @submit.prevent="generate">
<label>描述{{ parent ? '室内布局' : '房间布局' }}<textarea v-model="prompt" rows="5" maxlength="1600" :disabled="suggesting" placeholder="例如:主卧 4 米乘 3 米,北边靠墙放衣柜。"></textarea></label>
<p v-if="dirty" class="secondary small">AI 以已保存的平面图为参考,应用建议后仍可撤回。</p>
<p v-if="aiError" class="notice error" role="alert">{{ aiError }}</p>
<div v-if="snapshot && accepted.length" class="proposal-canvas">
<PlanCanvas :board="snapshot" :placements="proposalPreview" selected="" :editable="false" :snapping="false" />
</div>
<ul v-if="suggestions.length" class="suggestion-list">
<li v-for="(suggestion, index) in suggestions" :key="index">
<label><input v-model="accepted" type="checkbox" :value="index" :disabled="!suggestion.geometry || suggesting" /><span>{{ suggestion.name }}<small>{{ suggestion.note || (suggestion.geometry ? '可应用' : '需补充资料') }}</small></span></label>
</li>
</ul>
<div class="modal-actions">
<button :disabled="suggesting || !prompt.trim()"><Sparkles :size="16" />{{ suggesting ? '正在生成…' : '生成建议' }}</button>
<button v-if="suggestions.length" type="button" class="primary" :disabled="!accepted.length || suggesting" @click="applyAi">应用所选建议</button>
</div>
</form>
</dialog>
</div>
</template>

View File

@ -0,0 +1,169 @@
<script setup lang="ts">
import { computed, ref, useId, watch } from 'vue'
import { Maximize, Minus, Plus } from '@lucide/vue'
import { fit, kind, snap, type Bounds, type Geometry, type Guides, type Placement } from './geometry'
const props = defineProps<{ board: Bounds; placements: Placement[]; selected: string; editable: boolean; snapping: boolean }>()
const emit = defineEmits<{ select: [id: string]; geometry: [id: string, value: Geometry] }>()
const canvas = ref<SVGSVGElement>()
const fineGrid = useId()
const planGrid = useId()
const zoom = ref(1)
const center = ref({ x: 0, y: 0 })
const guides = ref<Guides>({})
const pending = ref<{ id: string; geometry: Geometry }>()
const dragging = ref(false)
const padding = 460
const extent = computed(() => ({ width: props.board.widthMm + padding * 2, height: props.board.depthMm + padding * 2 }))
type Gesture = {
pointer: number; x: number; y: number; units: number
move?: { id: string; original: Geometry; resize: boolean }
center: { x: number; y: number }
}
let gesture: Gesture | undefined
const viewBox = computed(() => {
const w = extent.value.width / zoom.value
const h = extent.value.height / zoom.value
return [center.value.x - w / 2, center.value.y - h / 2, w, h].join(' ')
})
const layers = computed(() => [...props.placements].sort((first, second) =>
Number(kind(first.geometry.template) === 'furniture') - Number(kind(second.geometry.template) === 'furniture')))
const selectedPlacement = computed(() => layers.value.find((placement) => placement.id === props.selected))
const current = (placement: Placement) => pending.value?.id === placement.id ? pending.value.geometry : placement.geometry
function reset() {
zoom.value = 1
center.value = { x: props.board.widthMm / 2, y: props.board.depthMm / 2 }
}
watch(() => props.board, reset, { immediate: true })
function unitsPerPixel() {
return 1 / Math.max(0.0001, canvas.value?.getScreenCTM()?.a ?? 1)
}
function setZoom(next: number) {
zoom.value = Math.min(5, Math.max(0.6, next))
}
function wheel(event: WheelEvent) {
const matrix = canvas.value?.getScreenCTM()
if (!matrix) return
const point = new DOMPoint(event.clientX, event.clientY).matrixTransform(matrix.inverse())
const before = zoom.value
setZoom(before * Math.exp(-event.deltaY * 0.002))
const ratio = before / zoom.value
center.value = { x: point.x - (point.x - center.value.x) * ratio, y: point.y - (point.y - center.value.y) * ratio }
}
function begin(event: PointerEvent, placement?: Placement, resize = false) {
if (gesture || (event.button !== 0 && event.button !== 1)) return
const edit = placement && event.button === 0 && !event.shiftKey && !event.ctrlKey
if (edit) {
emit('select', placement.id)
canvas.value?.focus({ preventScroll: true })
}
if (edit && !props.editable) return
if (!placement && event.button === 0 && !event.shiftKey) emit('select', '')
gesture = { pointer: event.pointerId, x: event.clientX, y: event.clientY,
units: unitsPerPixel(), center: { ...center.value },
move: edit ? { id: placement.id, original: placement.geometry, resize } : undefined }
canvas.value?.setPointerCapture(event.pointerId)
dragging.value = true
}
function move(event: PointerEvent) {
if (!gesture || gesture.pointer !== event.pointerId) return
const dx = (event.clientX - gesture.x) * gesture.units
const dy = (event.clientY - gesture.y) * gesture.units
if (!gesture.move) {
center.value = { x: gesture.center.x - dx, y: gesture.center.y - dy }
return
}
const { id, original, resize } = gesture.move
let proposed = resize
? { ...original, widthMm: Math.min(original.widthMm + dx, props.board.widthMm - original.xMm),
depthMm: Math.min(original.depthMm + dy, props.board.depthMm - original.yMm) }
: { ...original, xMm: original.xMm + dx, yMm: original.yMm + dy }
if (props.snapping && !event.altKey) {
const others = props.placements.filter((placement) => placement.id !== id).map((placement) => placement.geometry)
const aligned = snap(proposed, props.board, others, resize, Math.min(280, gesture.units * 8))
proposed = aligned.geometry
guides.value = aligned.guides
} else {
proposed = fit(proposed, props.board)
guides.value = {}
}
pending.value = { id, geometry: proposed }
}
function end(event: PointerEvent, commit: boolean) {
if (event.pointerId !== gesture?.pointer) return
if (commit && pending.value) emit('geometry', pending.value.id, pending.value.geometry)
gesture = undefined
pending.value = undefined
guides.value = {}
dragging.value = false
}
const furniture = (placement: Placement) => kind(placement.geometry.template) === 'furniture'
</script>
<template>
<div class="canvas-stage" :class="{ dragging }">
<svg ref="canvas" class="plan-svg" :viewBox="viewBox" tabindex="0" aria-label="位置平面图"
@wheel.prevent="wheel" @pointerdown="begin($event)" @pointermove="move"
@pointerup="end($event, true)" @pointercancel="end($event, false)" @lostpointercapture="end($event, false)">
<defs>
<pattern :id="fineGrid" width="100" height="100" patternUnits="userSpaceOnUse">
<path d="M100 0H0V100" fill="none" stroke="#d9e1df" stroke-width="12" />
</pattern>
<pattern :id="planGrid" width="500" height="500" patternUnits="userSpaceOnUse">
<rect width="500" height="500" :fill="'url(#' + fineGrid + ')'" />
<path d="M500 0H0V500" fill="none" stroke="#b8c8c3" stroke-width="15" />
</pattern>
</defs>
<rect :width="board.widthMm" :height="board.depthMm" fill="#fcfdfa" stroke="#93a6a0" vector-effect="non-scaling-stroke" />
<rect :width="board.widthMm" :height="board.depthMm" :fill="'url(#' + planGrid + ')'" />
<g v-for="placement in layers" :key="placement.id" tabindex="0" role="button" class="plan-shape"
:aria-label="placement.name" :aria-pressed="placement.id === selected"
:class="[kind(placement.geometry.template), { focused: placement.id === selected }]"
:transform="'translate(' + current(placement).xMm + ',' + current(placement).yMm + ')'"
@keydown.enter.prevent="emit('select', placement.id)"
@keydown.space.prevent="emit('select', placement.id)"
@pointerdown.stop.prevent="begin($event, placement)">
<rect class="plan-outline" :width="current(placement).widthMm" :height="current(placement).depthMm"
:rx="furniture(placement) ? 85 : 0" vector-effect="non-scaling-stroke" />
<svg v-if="furniture(placement)" class="furniture-symbol" x="0" y="0" :width="current(placement).widthMm"
:height="current(placement).depthMm" viewBox="0 0 100 100" preserveAspectRatio="none" pointer-events="none">
<g :transform="'rotate(' + current(placement).rotation + ' 50 50)'" fill="none" stroke="currentColor" stroke-width="2.6">
<template v-if="placement.geometry.template === 'BED'"><rect x="13" y="12" width="74" height="75" rx="8"/><rect x="22" y="18" width="24" height="19" rx="5"/><rect x="54" y="18" width="24" height="19" rx="5"/><path d="M13 45h74"/></template>
<template v-else-if="placement.geometry.template === 'SOFA'"><rect x="7" y="15" width="86" height="72" rx="12"/><path d="M20 74V36h60v38M40 36v38m20-38v38"/></template>
<template v-else-if="['WARDROBE','BOOKCASE','SHELF'].includes(placement.geometry.template)"><rect x="8" y="11" width="84" height="78" rx="3"/><path d="M35 11v78m30-78v78"/></template>
<template v-else><rect x="12" y="15" width="76" height="70" rx="8"/><path d="M19 70h62"/></template>
</g>
</svg>
<svg :x="0" :y="0" :width="current(placement).widthMm" :height="current(placement).depthMm" overflow="hidden" aria-hidden="true" pointer-events="none">
<text v-if="current(placement).widthMm >= 280 && current(placement).depthMm >= 220"
:x="furniture(placement) ? current(placement).widthMm / 2 : 125"
:y="furniture(placement) ? current(placement).depthMm / 2 : 170"
:text-anchor="furniture(placement) ? 'middle' : 'start'" dominant-baseline="central"
:font-size="furniture(placement) ? 145 : 215" class="shape-name">{{ placement.name }}</text>
</svg>
</g>
<rect v-if="selectedPlacement && editable" class="resize-grip" width="180" height="180" rx="24"
:x="current(selectedPlacement).xMm + current(selectedPlacement).widthMm - 90"
:y="current(selectedPlacement).yMm + current(selectedPlacement).depthMm - 90"
aria-hidden="true" vector-effect="non-scaling-stroke"
@pointerdown.stop.prevent="begin($event, selectedPlacement, true)" />
<path v-if="guides.x !== undefined" :d="'M' + guides.x + ' 0v' + board.depthMm" class="snap-guide" vector-effect="non-scaling-stroke" />
<path v-if="guides.y !== undefined" :d="'M0 ' + guides.y + 'h' + board.widthMm" class="snap-guide" vector-effect="non-scaling-stroke" />
</svg>
<div v-if="!placements.length" class="canvas-empty"> {{ editable ? '从左侧添加位置到图上' : '还没有摆放位置' }} </div>
<div class="canvas-zoom">
<button class="icon-button" aria-label="缩小" @click="setZoom(zoom / 1.25)"><Minus :size="16" /></button>
<span>{{ Math.round(zoom * 100) }}%</span>
<button class="icon-button" aria-label="放大" @click="setZoom(zoom * 1.25)"><Plus :size="16" /></button>
<button class="icon-button" aria-label="适应画布" @click="reset"><Maximize :size="16" /></button>
</div>
</div>
</template>

View File

@ -0,0 +1,92 @@
export const templates = {
LIVING_ROOM: ['客厅', 4000, 3400, 'room'],
BEDROOM: ['卧室', 3000, 2800, 'room'],
STUDY: ['书房', 3000, 2800, 'room'],
KITCHEN: ['厨房', 2600, 2400, 'room'],
BATHROOM: ['卫生间', 2100, 1900, 'room'],
ROOM: ['房间', 3000, 2800, 'room'],
ENTRY: ['玄关', 2200, 1500, 'area'],
BALCONY: ['阳台', 2200, 1500, 'area'],
AREA: ['开放区域', 2200, 1500, 'area'],
SOFA: ['沙发', 2300, 1400, 'furniture'],
BED: ['床', 1600, 2100, 'furniture'],
DESK: ['书桌', 1400, 620, 'furniture'],
TV_STAND: ['电视柜', 1400, 620, 'furniture'],
WARDROBE: ['衣柜', 1600, 650, 'furniture'],
BOOKCASE: ['书架', 1100, 450, 'furniture'],
SHELF: ['层架', 1100, 450, 'furniture'],
TABLE: ['边几', 600, 600, 'furniture'],
STORAGE_BOX: ['收纳箱', 500, 450, 'furniture'],
} as const
export type Template = keyof typeof templates
export type Geometry = {
template: Template; xMm: number; yMm: number; widthMm: number; depthMm: number; rotation: number
}
export type Slot = { id: string; name: string; icon: string; geometry: Geometry | null }
export type Snapshot = { version: string; widthMm: number; depthMm: number; locations: Slot[] }
export type Placement = { id: string; name: string; newName?: string; geometry: Geometry }
export type Suggestion = { locationId: string | null; name: string; note: string; geometry: Geometry | null }
export type Bounds = Pick<Snapshot, 'widthMm' | 'depthMm'>
export type Guides = { x?: number; y?: number }
export const grid = 100
export const kind = (template: Template) => templates[template][3]
export const overlap = (a: Geometry, b: Geometry) => a.xMm < b.xMm + b.widthMm && b.xMm < a.xMm + a.widthMm
&& a.yMm < b.yMm + b.depthMm && b.yMm < a.yMm + a.depthMm
const limit = (value: number, min: number, max: number) => Math.max(min, Math.min(max, Math.round(value)))
export function fit(shape: Geometry, board: Bounds): Geometry {
const widthMm = limit(shape.widthMm, 100, board.widthMm)
const depthMm = limit(shape.depthMm, 100, board.depthMm)
return { ...shape, widthMm, depthMm, xMm: limit(shape.xMm, 0, board.widthMm - widthMm),
yMm: limit(shape.yMm, 0, board.depthMm - depthMm) }
}
export function roomConflict(placements: Placement[]) {
const rooms = placements.filter(({ geometry }) => kind(geometry.template) === 'room')
return rooms.find((room, index) => rooms.slice(0, index).some((other) => overlap(room.geometry, other.geometry)))
}
export function defaultGeometry(template: Template, board: Bounds, placements: Placement[]) {
const shape = fit({ template, xMm: 0, yMm: 0, widthMm: templates[template][1],
depthMm: templates[template][2], rotation: 0 }, board)
for (let y = 200; y <= board.depthMm - shape.depthMm; y += 200) {
for (let x = 200; x <= board.widthMm - shape.widthMm; x += 200) {
const candidate = { ...shape, xMm: x, yMm: y }
if (placements.every(({ geometry }) => !overlap(candidate, geometry))) return candidate
}
}
return shape
}
function alignment(start: number, size: number, bound: number, coordinates: number[], resize: boolean, tolerance: number) {
const anchors = resize ? [start + size] : [start, start + size / 2, start + size]
let guide: number | undefined
let adjustment = tolerance + 1
for (const anchor of anchors) {
for (const line of coordinates) {
if (Math.abs(line - anchor) < Math.abs(adjustment)) {
adjustment = line - anchor
guide = line
}
}
}
if (Math.abs(adjustment) > tolerance) {
return { value: Math.round((resize ? size : start) / grid) * grid }
}
const value = resize ? size + adjustment : start + adjustment
if (value < (resize ? 100 : 0) || value > (resize ? bound - start : bound - size)) return { value }
return { value, guide }
}
export function snap(shape: Geometry, board: Bounds, others: Geometry[], resize: boolean, tolerance: number) {
const x = alignment(shape.xMm, shape.widthMm, board.widthMm,
[0, board.widthMm, ...others.flatMap((g) => [g.xMm, g.xMm + g.widthMm / 2, g.xMm + g.widthMm])], resize, tolerance)
const y = alignment(shape.yMm, shape.depthMm, board.depthMm,
[0, board.depthMm, ...others.flatMap((g) => [g.yMm, g.yMm + g.depthMm / 2, g.yMm + g.depthMm])], resize, tolerance)
const geometry = fit(resize
? { ...shape, widthMm: Math.min(x.value, board.widthMm - shape.xMm), depthMm: Math.min(y.value, board.depthMm - shape.yMm) }
: { ...shape, xMm: x.value, yMm: y.value }, board)
return { geometry, guides: { x: x.guide, y: y.guide } }
}

231
apps/pc/src/style.css Normal file
View File

@ -0,0 +1,231 @@
:root {
font-family: Inter, "PingFang SC", "Microsoft YaHei", system-ui, sans-serif;
color: #172c36;
background: #f2f5f4;
font-synthesis: none;
--ink: #172c36;
--muted: #52676e;
--line: #dce5e3;
--paper: #fff;
--accent: #17624e;
--accent-soft: #e4f1ea;
--rail: #172d32;
}
* { box-sizing: border-box; }
body { margin: 0; min-width: 340px; }
button, input, select, textarea { font: inherit; color: inherit; }
button, .action {
display: inline-flex; align-items: center; justify-content: center; gap: 7px;
min-height: 36px; padding: 0 12px; border: 1px solid var(--line); border-radius: 7px;
background: #fff; cursor: pointer; text-decoration: none; color: var(--ink); font-size: 13px; font-weight: 580;
}
button:hover:not(:disabled), .action:hover { background: #f1f7f4; border-color: #a9c2b8; }
button:disabled { opacity: .47; cursor: default; }
button:focus-visible, a:focus-visible, input:focus-visible, select:focus-visible, textarea:focus-visible { outline: 2px solid #238766; outline-offset: 2px; }
.primary { background: var(--accent); color: white; border-color: var(--accent); font-weight: 650; }
.primary:hover:not(:disabled) { background: #104d3c; border-color: #104d3c; }
.quiet { border-color: transparent; background: transparent; }
.icon-button { padding: 0; width: 36px; flex-shrink: 0; }
.danger { color: #a02f39; }
.full { width: 100%; }
.secondary { color: var(--muted); }
.small { font-size: 13px; }
h1, h2, h3, p { margin: 0; }
h1 { font-size: clamp(26px, 2.6vw, 36px); font-weight: 720; letter-spacing: -.035em; }
h2 { font-size: 16px; font-weight: 680; }
h3 { font-size: 14px; }
a { color: var(--accent); }
.notice { padding: 10px 13px; border-radius: 8px; background: #edf4f3; font-size: 13px; line-height: 1.5; overflow-wrap: anywhere; }
.notice.error { color: #902c35; background: #fff0ef; }
.notice.success { color: #1b5d42; background: #e7f4e9; }
.notice button { min-height: 26px; border: none; padding: 0 7px; margin-inline-start: 4px; }
.brand { display: flex; align-items: center; gap: 11px; }
.brand img { width: 36px; height: 36px; border-radius: 9px; object-fit: contain; background: white; padding: 4px; }
.brand strong { font-size: 21px; font-weight: 760; letter-spacing: .1em; }
.login-page { min-height: 100dvh; display: grid; place-items: center; padding: 26px; background: #eaf1ee; }
.sign-in-card { width: min(100%, 420px); padding: 39px; background: white; border: 1px solid #d8e4de; border-radius: 15px; box-shadow: 0 18px 70px #22463814; }
.sign-in-brand img { width: 49px; height: 49px; padding: 0; }
.sign-in-brand strong { font-size: 33px; }
.brand-line { color: var(--muted); margin: 12px 0 26px; font-size: 15px; letter-spacing: .09em; }
.sign-in-card .primary { min-height: 43px; margin-top: 6px; }
.shell { display: grid; grid-template-columns: 174px minmax(0, 1fr); min-height: 100dvh; }
.rail { position: sticky; top: 0; height: 100dvh; display: flex; flex-direction: column; gap: 24px; padding: 23px 15px; background: var(--rail); color: #eef5ee; }
.rail .brand { padding-left: 6px; }
.space-control { position: relative; display: flex; align-items: center; gap: 9px; min-width: 0; padding: 0 9px; min-height: 42px; border: 1px solid #456064; border-radius: 7px; }
.space-control svg { color: #b4c9c3; flex-shrink: 0; }
.space-control select { background: transparent; border: 0; appearance: none; min-width: 0; flex: 1; padding: 7px 0; color: white; }
.space-control option { color: var(--ink); }
.rail nav, .rail-footer { display: grid; gap: 5px; }
.rail nav a, .rail-footer button { display: flex; justify-content: start; align-items: center; gap: 10px; min-height: 42px; text-decoration: none; color: #c4d6d0; padding: 0 11px; border-radius: 7px; font-size: 14px; }
.rail nav a:hover, .rail-footer button:hover:not(:disabled) { background: #29464a; color: white; }
.rail nav .router-link-active { background: #31564e; color: #f2fff8; font-weight: 700; }
.rail-footer { margin-top: auto; }
.workspace { min-width: 0; padding: 0 clamp(16px, 2.5vw, 38px) 24px; }
.workspace-notice, .create-space { margin-top: 15px; }
.create-space { display: flex; align-items: end; gap: 9px; padding: 12px; background: var(--paper); border: 1px solid var(--line); border-radius: 9px; }
.create-space label { display: grid; gap: 5px; flex: 1; font-size: 13px; }
.page-header { display: flex; justify-content: space-between; align-items: end; gap: 15px; padding: 24px 0 20px; }
.page-header .primary { min-height: 39px; }
.crumb { display: flex; align-items: center; flex-wrap: wrap; gap: 6px; color: var(--muted); font-size: 12px; margin-bottom: 6px; }
.header-actions { display: flex; align-items: center; flex-wrap: wrap; gap: 8px; }
.save-status { color: var(--muted); display: inline-flex; align-items: center; gap: 6px; font-size: 12px; margin-right: 6px; }
.save-status i { width: 7px; height: 7px; border-radius: 50%; background: #bd7c2e; }
.panel, .plan-shell { background: var(--paper); border: 1px solid var(--line); border-radius: 11px; min-width: 0; }
.empty { display: flex; flex-direction: column; align-items: center; justify-content: center; gap: 10px; padding: 48px 16px; color: var(--muted); text-align: center; }
.workspace-empty { height: 75vh; }
.inventory-grid { display: grid; grid-template-columns: 192px minmax(0, 1fr); gap: 14px; align-items: start; }
.inventory-grid.has-detail { grid-template-columns: 192px minmax(0, 1fr) clamp(238px, 23vw, 320px); }
.location-tree { padding: 12px 8px; max-height: calc(100dvh - 128px); overflow: auto; }
.location-tree h2 { padding: 4px 10px 12px; }
.location-tree .small { padding: 8px 10px; }
.tree-row { display: flex; justify-content: start; width: 100%; min-width: 0; padding: 0 10px; border: 0; background: transparent; text-align: start; }
.tree-row svg { flex-shrink: 0; color: var(--muted); }
.tree-row span { white-space: nowrap; text-overflow: ellipsis; overflow: hidden; }
.tree-row.current { background: var(--accent-soft); color: var(--accent); font-weight: 700; }
.tree-divider { border-top: 1px solid var(--line); margin: 9px 5px; }
.tree-link { margin-top: 10px; }
.item-list { min-height: 375px; }
.list-toolbar { display: flex; align-items: center; gap: 11px; padding: 12px; }
.search-field { display: flex; align-items: center; gap: 8px; flex: 1; min-width: 0; color: var(--muted); background: #f4f7f6; border: 1px solid #dbe5e1; border-radius: 7px; padding: 0 10px; }
.search-field input { border: none; background: transparent; min-width: 0; width: 100%; min-height: 38px; }
.search-field input:focus-visible { outline-offset: -2px; }
.check-field { display: inline-flex; align-items: center; gap: 6px; font-size: 13px; white-space: nowrap; }
input[type="checkbox"] { accent-color: var(--accent); width: 15px; height: 15px; margin: 0; }
.table-wrap { overflow-x: auto; }
table { width: 100%; border-collapse: collapse; font-size: 13px; }
td, th { padding: 9px 12px; text-align: left; border-bottom: 1px solid #eaf0ed; }
td:first-child, th:first-child { padding-left: 14px; }
th { color: var(--muted); font-weight: 550; background: #f5f8f7; white-space: nowrap; }
tr:hover td, tr.active-row td { background: #f1f8f4; }
td:last-child, th:last-child { text-align: right; white-space: nowrap; }
.item-cell, .table-path { background: none; border: 0; padding: 0; text-align: start; justify-content: start; }
.item-cell:hover:not(:disabled), .table-path:hover:not(:disabled) { background: transparent; color: var(--accent); }
.item-cell { gap: 9px; word-break: break-word; font-weight: 650; }
.table-path { color: var(--muted); }
.item-mark, .property-symbol { width: 32px; height: 32px; flex-shrink: 0; display: grid; place-items: center; border-radius: 7px; color: #245d4b; background: #e8f3ec; }
.list-status { color: var(--muted); padding: 14px; text-align: center; font-size: 13px; }
.item-list > .notice { margin: 0 12px 10px; }
.item-detail { padding: 13px; }
.detail-header, .detail-hero, .detail-actions { display: flex; gap: 8px; align-items: center; }
.detail-header { justify-content: space-between; }
.detail-hero { margin-top: 12px; overflow-wrap: anywhere; }
.detail-hero .item-mark { width: 42px; height: 42px; }
.detail-hero h3 { font-size: 18px; }
.item-detail dt { font-size: 12px; color: var(--muted); margin-top: 10px; }
.item-detail dd { margin: 3px 0; font-size: 14px; overflow-wrap: anywhere; }
.plain-text { white-space: pre-wrap; }
.detail-actions { flex-wrap: wrap; }
.move-form, .move-history, .item-detail > .notice { margin-top: 12px; }
.move-history h3 { margin-bottom: 7px; }
.move-history p { display: grid; gap: 2px; padding: 5px 0; font-size: 12px; }
.move-history svg { vertical-align: middle; }
.move-history time { color: var(--muted); }
.item-detail > .danger { margin-top: 11px; }
.plan-page > .notice { margin-bottom: 10px; }
.plan-shell { overflow: hidden; }
.plan-toolbar { display: flex; align-items: center; flex-wrap: wrap; gap: 12px; padding: 8px 12px; border-bottom: 1px solid var(--line); }
.toolbar-group { display: flex; align-items: center; gap: 7px; color: var(--muted); }
.plan-toolbar select { min-height: 34px; min-width: 120px; max-width: 210px; background: white; }
.plan-edit-tools { padding-left: 12px; border-left: 1px solid var(--line); }
.snap-toggle { padding-left: 4px; }
.ai-button { margin-left: auto; border-color: #d5e4de; color: var(--accent); background: #f1f8f4; }
.plan-columns { display: grid; grid-template-columns: 171px minmax(0, 1fr) 211px; height: max(575px, calc(100dvh - 184px)); }
.plan-columns.readonly { grid-template-columns: minmax(0, 1fr) 211px; }
.plan-library, .plan-properties { overflow: auto; }
.plan-library { border-right: 1px solid var(--line); padding: 13px 10px; }
.plan-properties { border-left: 1px solid var(--line); padding: 13px 11px; }
.pane-title { padding: 2px 5px 12px; }
.pane-title h2 { font-size: 14px; }
.template-group { display: grid; gap: 2px; padding-bottom: 12px; }
.template-group h3 { font-weight: 540; font-size: 11px; color: var(--muted); padding: 7px 6px 4px; }
.library-option { width: 100%; text-align: left; justify-content: start; border: 0; min-height: 32px; padding: 0 6px; gap: 7px; }
.library-option svg { color: #467569; flex-shrink: 0; }
.library-option span { overflow: hidden; text-overflow: ellipsis; white-space: nowrap; }
.library-option .append-icon { margin-left: auto; color: #69887f; }
.canvas-column { min-width: 0; min-height: 0; display: flex; flex-direction: column; position: relative; }
.canvas-stage { min-height: 0; flex: 1; position: relative; overflow: hidden; display: grid; background: #e6eeea; }
.plan-svg { width: 100%; height: 100%; position: absolute; inset: 0; touch-action: none; user-select: none; cursor: grab; }
.dragging .plan-svg { cursor: grabbing; }
.plan-shape { color: #52796f; cursor: pointer; outline: none; }
.plan-outline { fill: #d4e6de66; stroke: #55786f; stroke-width: 1.5; }
.furniture .plan-outline { fill: #d6ebe1; stroke: #438572; }
.area .plan-outline { fill: #e2ede7aa; stroke-dasharray: 5 4; }
.plan-shape:hover .plan-outline, .plan-shape:focus-visible .plan-outline, .plan-shape.focused .plan-outline { stroke: #147755; stroke-width: 2.4; }
.plan-shape.focused .plan-outline { fill: #b1d8c59c; }
.shape-name { fill: #1c423a; font-weight: 680; paint-order: stroke; stroke: #fcfdfa; stroke-width: 19; stroke-linejoin: round; }
.resize-grip { fill: #1c795e; stroke: white; stroke-width: 1.5; cursor: nwse-resize; }
.snap-guide { stroke: #0875ad; stroke-width: 1.2; stroke-dasharray: 5 5; pointer-events: none; }
.canvas-empty { position: absolute; inset: 0; display: grid; place-items: center; color: var(--muted); pointer-events: none; font-size: 14px; }
.canvas-zoom { position: absolute; display: flex; gap: 4px; align-items: center; right: 10px; bottom: 10px; border-radius: 8px; padding: 3px; background: white; box-shadow: 0 2px 7px #183a3526; }
.canvas-zoom span { min-width: 40px; text-align: center; font-size: 12px; color: var(--muted); }
.canvas-zoom button { border: 0; min-height: 32px; width: 32px; }
.canvas-footer { display: flex; align-items: center; justify-content: space-between; flex-wrap: wrap; gap: 5px; min-height: 31px; padding: 4px 10px; color: var(--muted); font-size: 11px; border-top: 1px solid var(--line); }
.map-target { display: block; padding: 7px 10px; font-size: 12px; color: var(--accent); border-bottom: 1px solid var(--line); overflow-wrap: anywhere; }
.shape-property { display: flex; align-items: center; gap: 7px; padding: 4px; margin-bottom: 12px; }
.shape-property input { min-width: 0; width: 100%; }
.shape-property h3 { overflow-wrap: anywhere; }
.property-fields { margin: 0; border: 0; padding: 0 4px; display: grid; gap: 7px; grid-template-columns: repeat(2,minmax(0,1fr)); }
.property-fields label { display: grid; gap: 5px; color: var(--muted); font-size: 11px; }
.property-fields label span { display: flex; align-items: center; border: 1px solid var(--line); border-radius: 6px; }
.property-fields input { min-width: 0; width: 100%; border: 0; padding: 4px; min-height: 32px; }
.property-fields small { padding-right: 4px; }
.property-actions { display: grid; gap: 6px; padding: 10px 4px 0; }
.property-empty { display: grid; justify-items: center; gap: 8px; padding: 29px 4px; text-align: center; color: var(--muted); font-size: 13px; }
.plan-loading { min-height: 350px; }
.modal { width: min(92vw, 590px); max-height: 89dvh; border: 1px solid #d5e2dd; border-radius: 12px; padding: 19px; color: var(--ink); box-shadow: 0 26px 90px #0b272944; }
.intake-modal { width: min(94vw, 685px); }
.modal::backdrop { background: #12272b85; }
.modal-header { display: flex; justify-content: space-between; align-items: center; margin-bottom: 12px; gap: 5px; }
.modal-header h2 { font-size: 19px; }
.modal .notice { margin-bottom: 9px; }
.fields { display: grid; gap: 11px; }
.fields > button { justify-self: start; }
.fields label { display: grid; gap: 6px; font-size: 13px; font-weight: 620; min-width: 0; }
.fields input, .fields textarea, .fields select, .create-space input, .shape-property input, .plan-toolbar select {
padding: 7px 8px; border: 1px solid var(--line); border-radius: 6px; background: white; min-height: 35px; font-weight: 450;
}
textarea { resize: vertical; }
.form-row { display: grid; grid-template-columns: minmax(82px, .32fr) minmax(0, 1fr); gap: 11px; }
.modal-actions { display: flex; flex-wrap: wrap; align-items: center; justify-content: end; gap: 8px; }
.segmented { display: flex; align-items: center; gap: 3px; width: fit-content; padding: 3px; border-radius: 8px; background: #edf3ef; }
.segmented button { background: transparent; border-color: transparent; min-height: 32px; }
.segmented button[aria-pressed="true"] { background: white; color: var(--accent); border-color: #d7e5dd; }
.intake-tabs { margin-bottom: 12px; }
.candidate-list { border: 1px solid var(--line); border-radius: 8px; padding: 6px 8px; margin: 0; min-width: 0; }
.candidate-list legend { font-size: 13px; color: var(--muted); padding: 0 5px; }
.candidate { display: grid; grid-template-columns: 18px minmax(75px, 1fr) 68px minmax(85px, 1fr); gap: 6px; align-items: center; margin: 4px; }
.candidate input, .candidate select { min-width: 0; }
.suggestion-list { margin: 0; padding: 0; list-style: none; }
.proposal-canvas { height: 245px; display: flex; border: 1px solid var(--line); border-radius: 8px; overflow: hidden; }
.suggestion-list label { display: flex; align-items: center; gap: 8px; border-top: 1px solid var(--line); padding: 8px; }
.suggestion-list input { min-height: 0; }
.suggestion-list small { display: block; color: var(--muted); font-weight: 460; margin-top: 2px; }
@media (max-width: 1080px) {
.shell { grid-template-columns: 135px minmax(0, 1fr); }
.rail { padding: 16px 9px; }
.inventory-grid, .inventory-grid.has-detail { grid-template-columns: 151px minmax(0, 1fr); }
.item-detail { grid-column: 2; }
.plan-columns { grid-template-columns: 125px minmax(0, 1fr) 170px; }
.plan-columns.readonly { grid-template-columns: minmax(0, 1fr) 170px; }
}
@media (max-width: 760px) {
.shell { display: block; }
.rail { position: static; height: auto; flex-direction: row; align-items: center; gap: 7px; padding: 8px; flex-wrap: wrap; }
.rail .brand { padding: 0; }
.rail .brand strong { font-size: 16px; }
.rail .brand img { width: 26px; height: 26px; }
.rail nav, .rail-footer { display: flex; margin: 0; }
.rail nav a, .rail-footer button { padding: 0 7px; min-height: 35px; font-size: 12px; }
.rail-footer button svg { display: none; }
.space-control { max-width: 145px; min-height: 34px; }
.workspace { padding-inline: 10px; }
.page-header { align-items: start; padding-top: 15px; }
.inventory-grid, .inventory-grid.has-detail { grid-template-columns: 1fr; gap: 8px; }
.location-tree { max-height: 145px; }
.item-detail { grid-column: 1; }
.plan-columns, .plan-columns.readonly { grid-template-columns: 1fr; grid-template-rows: auto; height: auto; }
.canvas-column { grid-row: 1; height: 45vh; min-height: 285px; }
.plan-library, .plan-properties { max-height: 190px; border: 0; border-top: 1px solid var(--line); }
.template-group { display: flex; flex-wrap: wrap; align-items: center; }
.library-option { width: auto; }
}

18
apps/pc/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

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

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

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

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

View File

@ -5,7 +5,7 @@
| 端 | 技术选型 | 使用与交付 | | 端 | 技术选型 | 使用与交付 |
| --- | --- | --- | | --- | --- | --- |
| H5 | uni-app(Vue 3、TypeScript、Vite),使用 DCloud 的 CLI 模板 | 面向临时找物、相机上传和快速录入。首版构建 H5 静态文件,由 Nginx 镜像托管。 | | H5 | uni-app(Vue 3、TypeScript、Vite),使用 DCloud 的 CLI 模板 | 面向临时找物、相机上传和快速录入。首版构建 H5 静态文件,由 Nginx 镜像托管。 |
| PC 网页 | Vue 3、TypeScript、Vite、Vue Router | 面向批量草稿、详情查看和浏览位置树。独立 Nginx 镜像。 | | PC 网页 | Vue 3、TypeScript、Vite、Vue Router | [桌面工作台](../../apps/pc/README.md)支持搜索、物品录入、移位和两级平面图。独立 Nginx 镜像。 |
| 管理后台 | Vue 3、TypeScript、Vite、Element Plus | 已有空间查询、删除及图片清理入口。独立 Nginx 镜像。其他管理模块有多页路由需求时接入 Vue Router。 | | 管理后台 | Vue 3、TypeScript、Vite、Element Plus | 已有空间查询、删除及图片清理入口。独立 Nginx 镜像。其他管理模块有多页路由需求时接入 Vue Router。 |
| iOS | Swift、SwiftUI,最低 iOS 17 | [iOS 应用](../../apps/ios/README.md)接入账号、空间、物品、草稿和相册上传。拍照和录音按后续原生端验收范围补齐。 | | iOS | Swift、SwiftUI,最低 iOS 17 | [iOS 应用](../../apps/ios/README.md)接入账号、空间、物品、草稿和相册上传。拍照和录音按后续原生端验收范围补齐。 |
| Android | Kotlin、Jetpack Compose | Gradle 工程。相机、录音走 Android 平台能力,使用同一 HTTPS API。 | | Android | Kotlin、Jetpack Compose | Gradle 工程。相机、录音走 Android 平台能力,使用同一 HTTPS API。 |

View File

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

View File

@ -19,7 +19,7 @@
| 走查 | 要看的页面和状态 | | 走查 | 要看的页面和状态 |
| --- | --- | | --- | --- |
| H5 | 找物、详情、移位、位置树、手工与批量录入。补齐空结果、权限不足、模型不可用、确认中、失败重试。 | | H5 | 找物、详情、移位、位置树、手工与批量录入。补齐空结果、权限不足、模型不可用、确认中、失败重试。 |
| PC | 列表和详情、位置树导航、批量草稿表格。补键盘导航、窄窗口和长位置路径。 | | PC | [桌面工作台](pc-workbench.md)包含位置树、物品详情、文字批量录入和两级平面图。 |
| 管理后台 | 用户和家庭、模型状态、额度及异常操作。明确筛选、记录详情和角色权限。 | | 管理后台 | 用户和家庭、模型状态、额度及异常操作。明确筛选、记录详情和角色权限。 |
| iOS、Android | 从同一套术语和任务出发,单独画原生导航、相机、录音权限与返回后的状态。 | | iOS、Android | 从同一套术语和任务出发,单独画原生导航、相机、录音权限与返回后的状态。 |

20
docs/ui/pc-workbench.md Normal file
View File

@ -0,0 +1,20 @@
# PC 端桌面工作台
## 物品
左侧位置树负责缩小范围,中间列表显示名称、位置和数量。选中物品后在右侧查看和移位。位置有下级时可以展开全部后代范围,同名位置通过完整路径区分。录入优先支持手填,也可把一段文字交给现有模型服务,再逐条核对、修改位置并确认。
浏览器可以通过 HTTPS 和麦克风权限录音。录音数据与文字转写是两个步骤。不同浏览器的实时转写能力和处理地点不同,首版使用表单和文本草稿。后续接入录音时,可以用统一转写服务,再把文字交给现有草稿接口。 [W3C 媒体捕获](https://www.w3.org/TR/mediacapture-streams/) · [W3C 录音接口](https://www.w3.org/TR/mediastream-recording/)
## 平面图
左侧是可添加的模板和已有位置,中间画布占主要面积,右侧修改坐标、宽度和进深。总图与室内图共用现有一级和二级布局;三级以下仍由位置树管理。房间和家具使用不同描边,同名物件选中后仍可由位置路径找到。
- 滚轮按指针位置缩放,拖空白平移,右下角可恢复适合画布的视图。
- 拖动物件或拉右下角调整大小。默认吸附到 10 厘米网格、墙边及相邻物件边线和中心线。按住 Alt 可临时关闭吸附。方向键微调 1 厘米,Shift 加方向键微调 10 厘米。
- Ctrl / ⌘ + Z 撤回,附加 Shift 重做。移出平面图只改摆放图,不删除位置。放弃整次修改会恢复已保存版本。
- AI 建模按已保存的平面图生成建议。勾选后应用到当前草稿,保存才写入数据库。保存发生版本冲突时保留编辑状态。
## 后续
批量录入继续补交付重试与恢复,之后接相册和裁剪、成员管理与社区。浏览器录音和统一转写单独验收权限、设备和取消操作。