From 27d4a8fb8ea6ae1473571a76514a8fbe96642b87 Mon Sep 17 00:00:00 2001 From: dongjf <1+dongjf@noreply.git.tutudog.com> Date: Fri, 27 Nov 2026 17:26:14 +0800 Subject: [PATCH] =?UTF-8?q?feat:=20=E6=94=AF=E6=8C=81=E5=90=8C=E7=BA=A7?= =?UTF-8?q?=E4=BD=8D=E7=BD=AE=E6=8E=92=E5=BA=8F=E5=B9=B6=E7=AE=80=E5=8C=96?= =?UTF-8?q?=E5=AE=B6=E5=85=B7=E6=8F=92=E7=94=BB?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- apps/ios/ItemAtlas.xcodeproj/project.pbxproj | 4 +- apps/ios/ItemAtlas/InventoryStore.swift | 34 ++++++ apps/ios/ItemAtlas/LocationPicker.swift | 2 +- apps/ios/ItemAtlas/LocationView.swift | 113 +++++++++++++++++- .../inventory/InventoryController.java | 12 ++ .../itematlas/inventory/InventoryDtos.java | 6 +- .../itematlas/inventory/InventoryService.java | 75 +++++++++++- .../db/migration/V16__location_sort_order.sql | 4 + backend/tests/ios_experience_smoke.py | 47 ++++++++ docs/architecture/location-layout.md | 10 +- docs/product/ios-experience.md | 2 + docs/ui/ios/location-layout.html | 41 ++++++- docs/ui/ios/location-layout.md | 4 +- 13 files changed, 336 insertions(+), 18 deletions(-) create mode 100644 backend/inventory-service/src/main/resources/db/migration/V16__location_sort_order.sql diff --git a/apps/ios/ItemAtlas.xcodeproj/project.pbxproj b/apps/ios/ItemAtlas.xcodeproj/project.pbxproj index 2e53591..f70ad06 100644 --- a/apps/ios/ItemAtlas.xcodeproj/project.pbxproj +++ b/apps/ios/ItemAtlas.xcodeproj/project.pbxproj @@ -117,7 +117,7 @@ isa = XCBuildConfiguration; buildSettings = { CODE_SIGN_STYLE = Automatic; - CURRENT_PROJECT_VERSION = 21; + CURRENT_PROJECT_VERSION = 22; GENERATE_INFOPLIST_FILE = YES; ASSETCATALOG_COMPILER_APPICON_NAME = AppIcon; ATLAS_API_BASE_URL = "https://api-atlas.tutudog.com"; @@ -138,7 +138,7 @@ isa = XCBuildConfiguration; buildSettings = { CODE_SIGN_STYLE = Automatic; - CURRENT_PROJECT_VERSION = 21; + CURRENT_PROJECT_VERSION = 22; GENERATE_INFOPLIST_FILE = YES; ASSETCATALOG_COMPILER_APPICON_NAME = AppIcon; ATLAS_API_BASE_URL = "https://api-atlas.tutudog.com"; diff --git a/apps/ios/ItemAtlas/InventoryStore.swift b/apps/ios/ItemAtlas/InventoryStore.swift index 781c156..330aa8c 100644 --- a/apps/ios/ItemAtlas/InventoryStore.swift +++ b/apps/ios/ItemAtlas/InventoryStore.swift @@ -18,8 +18,22 @@ struct Place: Decodable, Identifiable { var iconPhotoId: UUID? = nil var displayIcon: String? = nil var depth: Int? = nil + var sortRank: Int? = nil var levelDepth: Int { depth ?? (parentId == nil ? 1 : path.components(separatedBy: " / ").count) } + + static func displayOrder(_ siblings: [Place]) -> [Place] { + siblings.enumerated().sorted { left, right in + let leftRank = left.element.sortRank ?? Int.max + let rightRank = right.element.sortRank ?? Int.max + return leftRank == rightRank ? left.offset < right.offset : leftRank < rightRank + }.map(\.element) + } +} + +struct LocationOrder: Decodable { + let version: String + let ids: [UUID] } struct Item: Decodable, Identifiable { @@ -218,6 +232,26 @@ final class InventoryStore { updateLocation(place) } + func locationOrder(parent: UUID?) async throws -> LocationOrder { + let query = parent.map { "?parentId=\($0)" } ?? "" + return try await get(root + "/locations/order" + query) + } + + func saveLocationOrder(parent: UUID?, version: String, ids: [UUID]) async throws { + struct Input: Encodable { + let parentId: UUID? + let version: String + let ids: [UUID] + } + let result: LocationOrder = try await send(root + "/locations/order", method: "PUT", + Input(parentId: parent, version: version, ids: ids)) + let ranks = Dictionary(uniqueKeysWithValues: result.ids.enumerated().map { ($0.element, $0.offset) }) + for index in locations.indices where locations[index].parentId == parent { + locations[index].sortRank = ranks[locations[index].id] + } + changed() + } + private func updateLocation(_ place: Place) { if let index = locations.firstIndex(where: { $0.id == place.id }) { locations[index] = place diff --git a/apps/ios/ItemAtlas/LocationPicker.swift b/apps/ios/ItemAtlas/LocationPicker.swift index bca711d..26bfced 100644 --- a/apps/ios/ItemAtlas/LocationPicker.swift +++ b/apps/ios/ItemAtlas/LocationPicker.swift @@ -56,7 +56,7 @@ struct LocationTree { init(_ places: [Place]) { self.places = places - byParent = Dictionary(grouping: places, by: \.parentId) + byParent = Dictionary(grouping: places, by: \.parentId).mapValues(Place.displayOrder) } var isEmpty: Bool { places.isEmpty } diff --git a/apps/ios/ItemAtlas/LocationView.swift b/apps/ios/ItemAtlas/LocationView.swift index f124b18..ffdc6e7 100644 --- a/apps/ios/ItemAtlas/LocationView.swift +++ b/apps/ios/ItemAtlas/LocationView.swift @@ -18,6 +18,7 @@ private struct LocationContents: View { @State private var addingLocation = false @State private var editingLocation = false @State private var editingAppearance = false + @State private var sortingLocations = false @State private var confirmingDelete = false @State private var error: String? @State private var busy = false @@ -36,6 +37,10 @@ private struct LocationContents: View { return initialLocation } + private var children: [Place] { + Place.displayOrder(store.locations.filter { $0.parentId == location?.id }) + } + var body: some View { Group { if store.locationAccessLost || (initialLocation != nil && store.locationsReady && location == nil) { @@ -61,7 +66,7 @@ private struct LocationContents: View { ProgressView("正在加载位置") } Section { - ForEach(store.locations.filter { $0.parentId == location?.id }) { child in + ForEach(children) { child in NavigationLink { LocationContents(store: store, initialLocation: child, onIntake: onIntake) } label: { HStack(spacing: 11) { LocationMark(store: store, place: child) @@ -75,7 +80,17 @@ private struct LocationContents: View { } } } header: { - LocationLevelHeading(level: LocationLevel(depth: (location?.levelDepth ?? 0) + 1)) + HStack { + LocationLevelHeading(level: LocationLevel(depth: (location?.levelDepth ?? 0) + 1)) + if store.canWrite && children.count > 1 { + Spacer() + Button("排序") { sortingLocations = true } + .buttonStyle(.borderless) + .font(.subheadline.weight(.semibold)) + .frame(minHeight: 44) + } + } + .textCase(nil) } if let location { ItemsSection(store: store, results: items, location: location.id, onIntake: { onIntake(location) }) @@ -114,6 +129,9 @@ private struct LocationContents: View { PlaceEditor(store: store, existing: location, personal: true) { _ in } } } + .sheet(isPresented: $sortingLocations) { + LocationOrderEditor(store: store, parent: location ?? initialLocation, siblings: children) + } .confirmationDialog("删除这个位置?", isPresented: $confirmingDelete, titleVisibility: .visible) { Button("删除位置", role: .destructive) { guard let location else { return } @@ -170,6 +188,97 @@ private struct LocationContents: View { } } +private struct LocationOrderEditor: View { + let store: InventoryStore + let parent: Place? + @Environment(\.dismiss) private var dismiss + @State private var siblings: [Place] + @State private var snapshot: LocationOrder? + @State private var loading = true + @State private var saving = false + @State private var error: String? + + init(store: InventoryStore, parent: Place?, siblings: [Place]) { + self.store = store + self.parent = parent + _siblings = State(initialValue: siblings) + } + + var body: some View { + NavigationStack { + List { + if let error { + Section { + Text(error).font(.footnote).foregroundStyle(.secondary) + if snapshot == nil { + Button("加载最新顺序") { Task { await load() } }.disabled(loading) + } + } + } + Section { + ForEach(siblings) { sibling in + HStack(spacing: 10) { + LocationMark(store: store, place: sibling) + Text(sibling.name) + } + .moveDisabled(snapshot == nil || loading || saving) + } + .onMove { from, to in siblings.move(fromOffsets: from, toOffset: to) } + } header: { + if loading { ProgressView("正在读取顺序") } + else { Text(parent?.path ?? "空间内的一级位置") } + } + } + .environment(\.editMode, .constant(.active)) + .navigationTitle("位置排序") + .navigationBarTitleDisplayMode(.inline) + .toolbar { + ToolbarItem(placement: .cancellationAction) { + Button("取消") { dismiss() }.disabled(saving) + } + ToolbarItem(placement: .confirmationAction) { + Button("保存") { Task { await save() } } + .disabled(snapshot == nil || loading || saving || snapshot?.ids == siblings.map(\.id)) + } + } + } + .interactiveDismissDisabled(saving) + .task { await load() } + } + + private func load() async { + loading = true + error = nil + defer { loading = false } + do { + let order = try await store.locationOrder(parent: parent?.id) + try await store.refreshLocations(refresh: true) + let byID = Dictionary(uniqueKeysWithValues: store.locations.map { ($0.id, $0) }) + let latest = order.ids.compactMap { byID[$0] } + guard latest.count == order.ids.count else { throw AtlasError("同级位置有变化,请重新加载。") } + siblings = latest + snapshot = order + } catch is CancellationError { + } catch { + self.error = error.localizedDescription + } + } + + private func save() async { + guard let snapshot, !saving else { return } + saving = true + error = nil + defer { saving = false } + do { + try await store.saveLocationOrder(parent: parent?.id, version: snapshot.version, ids: siblings.map(\.id)) + dismiss() + } catch { + if (error as? AtlasError)?.status == 409 { self.snapshot = nil } + self.error = error.localizedDescription + } + } +} + struct PlaceEditor: View { let store: InventoryStore let parent: UUID? diff --git a/backend/inventory-service/src/main/java/com/tutudog/itematlas/inventory/InventoryController.java b/backend/inventory-service/src/main/java/com/tutudog/itematlas/inventory/InventoryController.java index 61b9379..6fe5dfc 100644 --- a/backend/inventory-service/src/main/java/com/tutudog/itematlas/inventory/InventoryController.java +++ b/backend/inventory-service/src/main/java/com/tutudog/itematlas/inventory/InventoryController.java @@ -25,6 +25,18 @@ class InventoryController { return service.locations(household, user.getName()); } + @GetMapping(FAMILY + "/locations/order") + LocationOrder locationOrder(@PathVariable UUID household, Principal user, + @RequestParam(required = false) UUID parentId) { + return service.locationOrder(household, user.getName(), parentId); + } + + @PutMapping(FAMILY + "/locations/order") + LocationOrder saveLocationOrder(@PathVariable UUID household, Principal user, + @RequestBody @Valid LocationOrderInput input) { + return service.saveLocationOrder(household, user.getName(), input); + } + @PostMapping(FAMILY + "/locations") ResponseEntity createLocation(@PathVariable UUID household, Principal user, @RequestBody @Valid LocationInput input) { diff --git a/backend/inventory-service/src/main/java/com/tutudog/itematlas/inventory/InventoryDtos.java b/backend/inventory-service/src/main/java/com/tutudog/itematlas/inventory/InventoryDtos.java index 2ce7798..86306f7 100644 --- a/backend/inventory-service/src/main/java/com/tutudog/itematlas/inventory/InventoryDtos.java +++ b/backend/inventory-service/src/main/java/com/tutudog/itematlas/inventory/InventoryDtos.java @@ -7,6 +7,7 @@ import jakarta.validation.constraints.Min; import jakarta.validation.constraints.NotBlank; import jakarta.validation.constraints.NotEmpty; import jakarta.validation.constraints.NotNull; +import jakarta.validation.constraints.Pattern; import jakarta.validation.constraints.Size; import java.time.OffsetDateTime; import java.util.List; @@ -25,8 +26,11 @@ final class InventoryDtos { } record Location(UUID id, UUID parentId, String name, String path, LocationIcon icon, UUID coverPhotoId, - UUID iconPhotoId, LocationIcon displayIcon, int depth) {} + UUID iconPhotoId, LocationIcon displayIcon, int depth, Integer sortRank) {} record LocationInput(@NotBlank @Size(max = 100) String name, UUID parentId, LocationIcon icon) {} + record LocationOrder(String version, List ids) {} + record LocationOrderInput(UUID parentId, @NotNull @Pattern(regexp = "[0-9a-f]{64}") String version, + @NotNull List<@NotNull UUID> ids) {} record ThumbnailSelection(UUID photoId, LocationIcon icon) {} record Appearance(@NotNull ItemIcon icon, @Min(0) @Max(9_990_000_000_000L) Long priceCents) {} record Item(UUID id, String name, int quantity, String notes, UUID locationId, diff --git a/backend/inventory-service/src/main/java/com/tutudog/itematlas/inventory/InventoryService.java b/backend/inventory-service/src/main/java/com/tutudog/itematlas/inventory/InventoryService.java index 6bb2d47..ecf5521 100644 --- a/backend/inventory-service/src/main/java/com/tutudog/itematlas/inventory/InventoryService.java +++ b/backend/inventory-service/src/main/java/com/tutudog/itematlas/inventory/InventoryService.java @@ -3,9 +3,14 @@ package com.tutudog.itematlas.inventory; import static com.tutudog.itematlas.inventory.InventoryDtos.*; import static org.springframework.http.HttpStatus.*; +import java.nio.charset.StandardCharsets; +import java.security.MessageDigest; +import java.security.NoSuchAlgorithmException; import java.sql.Types; import java.time.OffsetDateTime; import java.util.Arrays; +import java.util.HashSet; +import java.util.HexFormat; import java.util.List; import java.util.Objects; import java.util.UUID; @@ -22,7 +27,8 @@ class InventoryService { rs.getObject("id", UUID.class), rs.getObject("parent_id", UUID.class), rs.getString("name"), rs.getString("path"), LocationIcon.valueOf(rs.getString("icon")), rs.getObject("cover_photo_id", UUID.class), rs.getObject("icon_photo_id", UUID.class), - LocationIcon.valueOf(rs.getString("display_icon")), rs.getInt("depth")); + LocationIcon.valueOf(rs.getString("display_icon")), rs.getInt("depth"), + rs.getObject("sort_rank", Integer.class)); private static final RowMapper ITEM = (rs, row) -> new Item( rs.getObject("id", UUID.class), rs.getString("name"), rs.getInt("quantity"), rs.getString("notes"), rs.getObject("location_id", UUID.class), rs.getString("path"), @@ -30,7 +36,7 @@ class InventoryService { rs.getObject("cover_photo_id", UUID.class), ItemIcon.valueOf(rs.getString("icon")), rs.getObject("price_cents", Long.class), rs.getBoolean("published"), rs.getObject("post_id", UUID.class)); private static final String SELECT_LOCATIONS = """ - SELECT p.*,l.icon,cardinality(p.ancestors) AS depth,thumb.photo_id AS icon_photo_id, + SELECT p.*,l.icon,l.sort_rank,cardinality(p.ancestors) AS depth,thumb.photo_id AS icon_photo_id, COALESCE(thumb.icon,l.icon) AS display_icon, (SELECT photo.id FROM location_photo photo WHERE (photo.household_id,photo.location_id)=(p.household_id,p.id) @@ -86,6 +92,55 @@ class InventoryService { .param("household", household).param("actor", actor).query(LOCATION).list(); } + LocationOrder locationOrder(UUID household, String actor, UUID parent) { + access.role(household, actor); + return siblingOrder(household, parent); + } + + @Transactional + LocationOrder saveLocationOrder(UUID household, String actor, LocationOrderInput input) { + // Location creation, moves, and archival take the same household lock. + access.requireWrite(household, actor); + var current = siblingOrder(household, input.parentId()); + if (current.ids().equals(input.ids())) { return current; } + if (!current.version().equals(input.version())) { + throw new ResponseStatusException(CONFLICT, "这个位置列表已更新,请加载最新顺序后再调整"); + } + if (input.ids().size() != current.ids().size() + || !new HashSet<>(input.ids()).equals(new HashSet<>(current.ids()))) { + throw new ResponseStatusException(BAD_REQUEST, "排序必须包含当前同级的全部位置"); + } + db.sql(""" + UPDATE location l SET sort_rank=(ordered.position-1)::integer + FROM unnest(CAST(:ids AS uuid[])) WITH ORDINALITY AS ordered(id,position) + WHERE l.household_id=:household AND l.id=ordered.id + """).param("household", household).param("ids", input.ids().toArray(UUID[]::new), Types.ARRAY).update(); + return orderSnapshot(input.ids()); + } + + private LocationOrder siblingOrder(UUID household, UUID parent) { + if (parent != null) { location(household, parent); } + var ids = db.sql(""" + SELECT p.id FROM location_paths(:household) p + JOIN location l ON (l.household_id,l.id)=(p.household_id,p.id) + WHERE p.parent_id IS NOT DISTINCT FROM :parent + ORDER BY l.sort_rank NULLS LAST,p.path,p.id + """).param("household", household).param("parent", parent, Types.OTHER).query(UUID.class).list(); + return orderSnapshot(ids); + } + + private static LocationOrder orderSnapshot(List ids) { + try { + var digest = MessageDigest.getInstance("SHA-256"); + for (UUID id : ids) { + digest.update(id.toString().getBytes(StandardCharsets.US_ASCII)); + } + return new LocationOrder(HexFormat.of().formatHex(digest.digest()), ids); + } catch (NoSuchAlgorithmException ex) { + throw new IllegalStateException("SHA-256 unavailable", ex); + } + } + Location location(UUID household, String actor, UUID id) { access.role(household, actor); return locationFor(household, id, actor); @@ -114,19 +169,27 @@ class InventoryService { throw new ResponseStatusException(CONFLICT, "不能移动到自己或子位置"); } } - UUID target = id == null ? UUID.randomUUID() : location(household, id).id(); + Location existing = id == null ? null : location(household, id); + UUID target = existing == null ? UUID.randomUUID() : existing.id(); + Integer rank = existing != null && Objects.equals(existing.parentId(), parent) ? existing.sortRank() + : db.sql(""" + SELECT max(sort_rank)+1 FROM location + WHERE household_id=:household AND parent_id IS NOT DISTINCT FROM :parent AND archived_at IS NULL + """).param("household", household).param("parent", parent, Types.OTHER) + .query(Integer.class).optional().orElse(null); String sql = id == null ? """ - INSERT INTO location(household_id,id,parent_id,name,icon) - VALUES (:household,:id,:parent,:name,COALESCE(:icon,'FOLDER')) + INSERT INTO location(household_id,id,parent_id,name,icon,sort_rank) + VALUES (:household,:id,:parent,:name,COALESCE(:icon,'FOLDER'),:rank) """ : """ - UPDATE location SET name=:name,parent_id=:parent,icon=COALESCE(:icon,icon) + UPDATE location SET name=:name,parent_id=:parent,icon=COALESCE(:icon,icon),sort_rank=:rank WHERE household_id=:household AND id=:id """; try { db.sql(sql).param("id", target).param("household", household) .param("parent", parent, Types.OTHER).param("name", input.name().strip()) + .param("rank", rank, Types.INTEGER) .param("icon", input.icon() == null ? null : input.icon().name(), Types.VARCHAR).update(); } catch (DuplicateKeyException ex) { throw new ResponseStatusException(CONFLICT, "当前层级已有同名位置"); diff --git a/backend/inventory-service/src/main/resources/db/migration/V16__location_sort_order.sql b/backend/inventory-service/src/main/resources/db/migration/V16__location_sort_order.sql new file mode 100644 index 0000000..dd47a7b --- /dev/null +++ b/backend/inventory-service/src/main/resources/db/migration/V16__location_sort_order.sql @@ -0,0 +1,4 @@ +ALTER TABLE location ADD COLUMN sort_rank integer CHECK (sort_rank >= 0); + +CREATE INDEX active_location_sort_rank ON location(household_id, parent_id, sort_rank DESC) + WHERE archived_at IS NULL AND sort_rank IS NOT NULL; diff --git a/backend/tests/ios_experience_smoke.py b/backend/tests/ios_experience_smoke.py index 6b7801b..2e206a8 100644 --- a/backend/tests/ios_experience_smoke.py +++ b/backend/tests/ios_experience_smoke.py @@ -17,6 +17,7 @@ def verify(): verify_search_and_voice(root) verify_optional_locations(root) verify_direct_invitations(root) + verify_location_order(root) verify_community(root) finally: call("DELETE", root, status=202) @@ -254,6 +255,52 @@ def verify_direct_invitations(root): print("PASS addressed invitations, private inbox, atomic acceptance and role checks", flush=True) +def verify_location_order(root): + locations = root + "/locations" + endpoint = locations + "/order" + + def place(name, parent=None): + return call("POST", locations, {"name": name, "parentId": parent}, status=201) + + def payload(order, ids, parent=None): + return {"version": order["version"], "ids": ids, "parentId": parent} + + room = place("排序房间") + first = place("A 柜", room["id"]) + second = place("B 柜", room["id"]) + nested = endpoint + "?" + urlencode({"parentId": room["id"]}) + initial = call("GET", nested, user="viewer") + assert initial["ids"] == [first["id"], second["id"]] + assert first["sortRank"] is None and second["sortRank"] is None + + request = payload(initial, list(reversed(initial["ids"])), room["id"]) + call("PUT", endpoint, request, user="viewer", status=403) + call("GET", nested, user="other", status=404) + call("PUT", endpoint, payload(initial, [first["id"], room["id"]], room["id"]), status=400) + call("PUT", endpoint, payload(initial, [first["id"]] * 2, room["id"]), status=400) + saved = call("PUT", endpoint, request) + assert saved == call("GET", nested) == call("PUT", endpoint, request) + assert initial["version"] != saved["version"] + call("PUT", endpoint, payload(initial, initial["ids"], room["id"]), status=409) + + third = place("0 应排在末尾", room["id"]) + assert third["sortRank"] == 2 + assert call("GET", nested)["ids"] == saved["ids"] + [third["id"]] + call("PUT", locations + "/" + second["id"], {"name": "改名后仍在首位", "parentId": room["id"]}) + assert call("GET", nested)["ids"][0] == second["id"] + call("DELETE", locations + "/" + first["id"], status=204) + call("PUT", endpoint, request, status=409) + assert call("GET", nested)["ids"] == [second["id"], third["id"]] + + root_order = call("GET", endpoint) + reversed_root = list(reversed(root_order["ids"])) + assert call("PUT", endpoint, payload(root_order, reversed_root))["ids"] == reversed_root + all_places = {row["id"]: row for row in call("GET", locations)} + assert [all_places[item]["sortRank"] for item in reversed_root] == list(range(len(reversed_root))) + assert call("GET", nested)["ids"] == [second["id"], third["id"]] + print("PASS persisted sibling order, append, scoped roles, stale edits and idempotent retry", flush=True) + + def verify_community(root): room = call("POST", root + "/locations", {"name": "测试住址" + RUN, "icon": "BEDROOM"}, status=201) posts = "/api/community/posts" diff --git a/docs/architecture/location-layout.md b/docs/architecture/location-layout.md index 37c6f37..d0c1248 100644 --- a/docs/architecture/location-layout.md +++ b/docs/architecture/location-layout.md @@ -2,10 +2,16 @@ `inventory-service` 是位置树与布局的写入方。现有物品、照片、路径和社区关联仍使用 `location.id`。俯视图和平铺由同一批位置构建。位置树负责业务归属,布局负责同级顺序和几何展示。 -## 数据和兼容 +## 已实现的同级排序 + +- `GET /api/households/{household}/locations/order` 返回当前同级位置的 `ids` 和顺序版本。查询参数 `parentId` 为空时读取一级位置。版本由有序 ID 计算,位置的增删和跨层移动也会影响对应版本。 +- `PUT /api/households/{household}/locations/order` 接收 `parentId`、读取时的 `version` 和排序后的完整 `ids`。服务复用家庭写入事务锁,确认空间写权限、同级活动位置集合和版本后,一次写入 `location.sort_rank`。旧版本有变更时返回 `409`。顺序已经一致时可以安全重试。 +- Flyway V16 增加可空的 `sort_rank`。从未排序的老数据保留原有顺序。某层保存过自定义顺序后,新建或移入的位置追加到队尾。选择位置的树和 iOS 平铺列表读取相同的排名。 + +## 俯视图和建模草稿的数据设计 - `location_layout_scope` 以 `household_id` 和 `parent_location_id` 定位一组兄弟位置。根层的父 ID 为空,联合唯一约束使用 `NULLS NOT DISTINCT`。记录画布范围和 `revision`。三级以下可只保存排序。 -- `location_presentation` 以 `household_id` 和 `location_id` 关联原位置。保存同级 `sort_rank`,以及可空的 `mold_key`、`x_mm`、`y_mm`、`width_mm`、`depth_mm`、`rotation`。几何字段整体为空表示未摆放,排序字段也可独立为空。模板键用白名单。原有图标及个人照片缩略图继续沿用。 +- `location_presentation` 以 `household_id` 和 `location_id` 关联原位置。保存可空的 `mold_key`、`x_mm`、`y_mm`、`width_mm`、`depth_mm`、`rotation`。几何字段整体为空表示未摆放,同级排序沿用 `location.sort_rank`。模板键用白名单。原有图标及个人照片缩略图继续沿用。 - 历史位置无需批量猜尺寸或坐标。有手动顺序时按顺序显示,其余使用既有的路径和 ID 顺序。新增位置追加到队尾。已设顺序的同级节点在刷新后仍稳定可读。 - 缩放和平移只改变客户端视图。保存以整数毫米为单位,画布默认按 10 厘米吸附。模板给估算尺寸,明确度量可通过数值输入覆盖。朝向按 90° 存储并计算实际占用边界。 - 家具可以叠放在房间轮廓内,开放区域也可用虚线描在大房间里。两个封闭房间之间的明显重叠显示冲突。缩小一级位置前检查已有二级家具是否会超出范围,提示定位到对应家具调整。 diff --git a/docs/product/ios-experience.md b/docs/product/ios-experience.md index 2a41335..e0951a6 100644 --- a/docs/product/ios-experience.md +++ b/docs/product/ios-experience.md @@ -32,6 +32,8 @@ 位置照片和路径放在同一张概览卡里,支持拍照、相册和裁剪。删掉用作个人图标的那张照片后,位置会恢复空间默认图标。删除位置时,其照片随位置清理。概览下方先列子位置,再列「这里的物品」。「在这里录入」位于物品区顶部,表单会带上当前位置。 +同一级有两处或以上位置时,空间所有者和编辑者可点标题旁的「排序」,拖动后保存。其他成员刷新后看到同一个顺序,选位置时也沿用这个顺序。如果同时有人修改了列表,排序页会保留当前编辑,提示加载最新顺序。 + 添加或编辑物品时,可以填写可选的购入单价、选择绿色物品图标、从相册选照片并裁剪。点「保存」后先保存物品,再上传照片。照片上传失败时,可以点「重试上传」,也可以稍后从详情添加。没有封面照片时,物品列表显示所选物品图标。已有照片可在物品详情继续查看、添加和删除。 ## 选存放位置 diff --git a/docs/ui/ios/location-layout.html b/docs/ui/ios/location-layout.html index 998102b..49c5cf9 100644 --- a/docs/ui/ios/location-layout.html +++ b/docs/ui/ios/location-layout.html @@ -253,7 +253,6 @@ box: ["收纳箱", "furniture", 16, 20], table: ["边几", "furniture", 18, 19], generic: ["其他", "zone", 20, 20] }; - const artwork = JSON.parse(root.querySelector(".layout-artwork")?.textContent || "{}"); const floorByMold = { livingRoom:"oak", bedroom:"oak", study:"oak", kitchen:"tile", bathroom:"tile", storage:"soft", entry:"tile", dining:"oak", balcony:"tile", hallway:"soft", zone:"soft", generic:"soft" @@ -312,9 +311,47 @@ el.addEventListener("click", action); return el; }; + const palette = { + sage:"#94aa91", sageLight:"#c4d1a6", cream:"#f8e8c8", tan:"#d8af84", + wood:"#ad795c", deep:"#634c4d", slate:"#526575", white:"#fff5e4" + }; + const pictures = new Map(); + const silhouettes = { + sofa: [[6,7,106,39,"sage",10],[79,30,33,39,"sage",9],[15,18,25,20,"sageLight",5], + [41,18,25,20,"sageLight",5],[67,18,25,20,"sageLight",5],[85,37,21,23,"sageLight",5], + [6,14,13,30,"sage",5],[100,14,12,52,"sage",5]], + cabinet: [[5,13,110,64,"tan",9],[17,49,26,19,"cream",4],[47,49,26,19,"cream",4], + [77,49,26,19,"cream",4],[44,28,32,11,"slate",3],[15,16,90,17,"slate",5]], + shelf: [[6,8,108,64,"wood",7],[14,15,92,45,"cream",3],[41,15,4,45,"wood",2],[74,15,4,45,"wood",2], + [19,25,7,30,"sage",2],[26,30,8,25,"slate",2],[49,22,8,33,"tan",2], + [57,27,11,28,"sage",2],[83,32,6,23,"slate",2],[89,26,11,29,"tan",2]], + bed: [[20,4,80,72,"tan",9],[24,9,72,14,"deep",4],[28,16,31,16,"white",4],[61,16,31,16,"white",4], + [26,32,68,37,"cream",7],[26,53,68,16,"sage",5]], + wardrobe: [[5,12,110,56,"wood",8],[12,18,22,43,"tan",3],[37,18,22,43,"tan",3],[62,18,22,43,"tan",3], + [87,18,21,43,"tan",3],[28,34,4,11,"deep",2],[41,34,4,11,"deep",2], + [78,34,4,11,"deep",2],[91,34,4,11,"deep",2]], + desk: [[7,12,106,55,"wood",8],[12,17,96,42,"tan",5],[29,24,23,29,"cream",4],[65,25,31,21,"slate",4], + [75,46,11,6,"slate",2]], + table: [[28,8,64,64,"wood",32],[32,10,56,55,"tan",28]], + box: [[25,8,70,64,"tan",12],[26,10,68,22,"cream",8],[48,46,24,10,"deep",5]], + rack: [[5,15,110,52,"sage",7],[12,23,21,36,"sageLight",4],[37,23,21,36,"sageLight",4], + [62,23,21,36,"sageLight",4],[87,23,21,36,"sageLight",4]] + }; + function illustration(mold) { + const drawing = document.createElement("canvas"); + drawing.width = 240; drawing.height = 160; + const pen = drawing.getContext("2d"); + pen.scale(2,2); pen.strokeStyle = "#594e50"; pen.lineWidth = 1.5; + silhouettes[mold].forEach(([x,y,w,h,color,radius]) => { + pen.beginPath(); pen.roundRect(x,y,w,h,radius); + pen.fillStyle = palette[color]; pen.fill(); pen.stroke(); + }); + return drawing.toDataURL(); + } function furnitureArt(mold) { + if (!pictures.has(mold)) pictures.set(mold,illustration(mold)); const image = document.createElement("img"); - image.src = artwork[mold] || "location-models/" + mold + ".png"; + image.src = pictures.get(mold); image.alt = ""; image.draggable = false; return image; } diff --git a/docs/ui/ios/location-layout.md b/docs/ui/ios/location-layout.md index c137743..7bc8a14 100644 --- a/docs/ui/ios/location-layout.md +++ b/docs/ui/ios/location-layout.md @@ -28,9 +28,9 @@ | --- | --- | --- | | 房间 | 客厅、卧室、书房、厨房、卫生间、储藏室 | 用墙线圈定闭合边界。木地板、方砖和素面材质区分用途,名称放在左上。 | | 开放区域 | 玄关、餐区、阳台、走廊、其他区域 | 虚线边界,材质弱于房间。可叠在开放式房间的轮廓内。 | -| 家具与收纳 | 沙发、床、桌、边几、衣柜、电视柜、书架、层架、收纳箱、其他 | 使用透明底俯视素材,保留转角、枕头、柜门和层板等辨认特征。可更改宽深和朝向。 | +| 家具与收纳 | 沙发、床、桌、边几、衣柜、电视柜、书架、层架、收纳箱、其他 | 采用简洁的卡通俯视图。用转角、枕头、柜门和层板辨认物件。可更改宽深和朝向。 | -查看时突出房间边界和家具形状。进入编辑才显示网格、选中轮廓和手柄。「添加模板」用图片预览,可按房间、区域和家具选择。名称和选中状态独立渲染,家具转动时标签继续正向可读。透明底素材可叠在浅色或深色画布上。 [家具素材与来源](location-models/README.md) +查看时突出房间边界和家具形状。进入编辑才显示网格、选中轮廓和手柄。「添加模板」用插画预览,可按房间、区域和家具选择。名称和选中状态独立渲染,家具转动时标签继续正向可读。 [早期材质探索](location-models/README.md) ## 用描述生成草稿