diff --git a/apps/ios/ItemAtlas.xcodeproj/project.pbxproj b/apps/ios/ItemAtlas.xcodeproj/project.pbxproj index 52452ed..71bf59e 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 = 7; + CURRENT_PROJECT_VERSION = 8; 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 = 7; + CURRENT_PROJECT_VERSION = 8; GENERATE_INFOPLIST_FILE = YES; ASSETCATALOG_COMPILER_APPICON_NAME = AppIcon; ATLAS_API_BASE_URL = "https://api-atlas.tutudog.com"; diff --git a/apps/ios/ItemAtlas/Account.swift b/apps/ios/ItemAtlas/Account.swift index f63de32..a407b10 100644 --- a/apps/ios/ItemAtlas/Account.swift +++ b/apps/ios/ItemAtlas/Account.swift @@ -141,7 +141,7 @@ final class AtlasAccount { } func request(_ path: String, method: String = "GET", data: Data? = nil, - contentType: String = "application/json") async throws -> Data { + contentType: String = "application/json", timeout: TimeInterval? = nil) async throws -> Data { guard let configuration, let url = URL(string: path, relativeTo: configuration.api)?.absoluteURL, Self.sameOrigin(url, configuration.api), path.hasPrefix("/api/") else { throw AtlasError("接口地址无效。") @@ -149,6 +149,7 @@ final class AtlasAccount { let requestGeneration = generation var request = URLRequest(url: url, cachePolicy: .reloadIgnoringLocalCacheData) request.httpMethod = method + if let timeout { request.timeoutInterval = timeout } request.httpBody = data if data != nil { request.setValue(contentType, forHTTPHeaderField: "Content-Type") } let access = try await accessToken(configuration) diff --git a/apps/ios/ItemAtlas/IntakeView.swift b/apps/ios/ItemAtlas/IntakeView.swift index a778d73..f4a480a 100644 --- a/apps/ios/ItemAtlas/IntakeView.swift +++ b/apps/ios/ItemAtlas/IntakeView.swift @@ -146,6 +146,7 @@ struct IntakeView: View { } .dismissibleKeyboard(active: typing) { typing = false } .navigationTitle("录入") + .navigationBarTitleDisplayMode(.inline) .toolbar { ToolbarItem(placement: .topBarTrailing) { Button { showingHelp = true } label: { Label("录入说明", systemImage: "questionmark.circle") } @@ -166,10 +167,10 @@ struct IntakeView: View { NavigationStack { List { Section("录音录入") { - Text("默认点一下开始,再点一下结束。录音设置也可以改成按住说、松手结束。") - Text("每次最多 25 秒,中间停一下可以接着说。首次允许权限后,可重新开始录音。") - Text("结束后可以修改转写。见物会先生成物品草稿。描述比较长时,可以点「用 AI 整理」。") - Text("核对物品和存放位置,然后点「保存物品」。") + Text("1. 点「开始录音」。也可以在设置里切换为按住说。") + Text("2. 说完点结束或松手。每次最多 25 秒,中间可以停顿。") + Text("3. 查看转写和草稿。可以修改文字,或点「用 AI 整理」。") + Text("4. 核对物品和存放位置,再点「保存物品」。") } Section("手动添加") { Text("点「手动添加物品」,填写名称,选好存放位置再保存。") @@ -184,7 +185,8 @@ struct IntakeView: View { } .sheet(isPresented: $showingAdd) { ItemEditor(store: store) } } else { - ContentUnavailableView("当前空间只有查看权限", systemImage: "lock").navigationTitle("录入") + ContentUnavailableView("当前空间只有查看权限", systemImage: "lock") + .navigationTitle("录入").navigationBarTitleDisplayMode(.inline) } } } diff --git a/apps/ios/ItemAtlas/InventoryStore.swift b/apps/ios/ItemAtlas/InventoryStore.swift index 0b0c45a..a11ffd0 100644 --- a/apps/ios/ItemAtlas/InventoryStore.swift +++ b/apps/ios/ItemAtlas/InventoryStore.swift @@ -88,7 +88,8 @@ final class InventoryStore { url.queryItems = [.init(name: "q", value: query), .init(name: "offset", value: String(offset)), .init(name: "favorites", value: favorites ? "true" : "false")] if let location { url.queryItems?.append(.init(name: "location", value: location.uuidString)) } - return try await get(url.string ?? root + "/items") + let data = try await account.request(url.string ?? root + "/items", timeout: 12) + return try JSONDecoder().decode([Item].self, from: data) } func get(_ path: String) async throws -> T { diff --git a/apps/ios/ItemAtlas/InventoryView.swift b/apps/ios/ItemAtlas/InventoryView.swift index 5d1f854..169fc0b 100644 --- a/apps/ios/ItemAtlas/InventoryView.swift +++ b/apps/ios/ItemAtlas/InventoryView.swift @@ -2,77 +2,148 @@ import SwiftUI struct InventoryView: View { let store: InventoryStore + + var body: some View { + NavigationStack { ItemListView(store: store) } + } +} + +struct ItemListView: View { + let store: InventoryStore var favoritesOnly = false @Environment(\.colorScheme) private var colorScheme + @State private var results = ItemListResults() @State private var query = "" @FocusState private var searching: Bool var body: some View { - NavigationStack { - VStack(spacing: 0) { - VStack(alignment: .leading, spacing: 14) { - HStack(alignment: .firstTextBaseline, spacing: 12) { - Text(favoritesOnly ? "收藏" : "找物").font(.largeTitle.bold()) - .accessibilityAddTraits(.isHeader) - .layoutPriority(1) - Spacer() - Label(store.space.name, systemImage: "house") - .font(.subheadline) - .foregroundStyle(.secondary) - .lineLimit(1) - } - HStack(spacing: 10) { - Image(systemName: "magnifyingglass").foregroundStyle(.secondary).accessibilityHidden(true) - TextField("搜物品、别名或位置", text: $query) - .focused($searching).submitLabel(.search).onSubmit { searching = false } - .textInputAutocapitalization(.never) - if !query.isEmpty { - Button { query = "" } label: { Image(systemName: "xmark.circle.fill").foregroundStyle(.secondary) } - .accessibilityLabel("清除搜索") - } - if searching { - Button { searching = false } label: { Image(systemName: "keyboard.chevron.compact.down") } - .accessibilityLabel("收起键盘") - } - } - .padding(.horizontal, 12) - .frame(minHeight: 46) - .background(Color(uiColor: .secondarySystemGroupedBackground), in: .rect(cornerRadius: 13)) + VStack(spacing: 0) { + HStack(spacing: 10) { + Image(systemName: "magnifyingglass").foregroundStyle(.secondary).accessibilityHidden(true) + TextField("搜物品、别名或位置", text: $query) + .focused($searching).submitLabel(.search).onSubmit { searching = false } + .textInputAutocapitalization(.never) + if !query.isEmpty { + Button { query = "" } label: { Image(systemName: "xmark.circle.fill").foregroundStyle(.secondary) } + .accessibilityLabel("清除搜索") + } + if searching { + Button { searching = false } label: { Image(systemName: "keyboard.chevron.compact.down") } + .accessibilityLabel("收起键盘") } - .padding(18) - .background(Color.entryBackground(for: colorScheme)) - List { ItemsSection(store: store, query: query, favorites: favoritesOnly) } - .listStyle(.plain).scrollDismissesKeyboard(.interactively) } - .toolbar(.hidden, for: .navigationBar) + .padding(.horizontal, 12) + .frame(minHeight: 44) + .background(Color(uiColor: .secondarySystemGroupedBackground), in: .rect(cornerRadius: 13)) + .padding(.horizontal, 16) + .padding(.vertical, 8) + .background(Color.entryBackground(for: colorScheme)) + List { ItemsSection(store: store, results: results, query: query, favorites: favoritesOnly) } + .listStyle(.plain).scrollDismissesKeyboard(.interactively) } + .navigationTitle(favoritesOnly ? "我的收藏" : "找物") + .navigationBarTitleDisplayMode(.inline) + .toolbar { + ToolbarItem(placement: .topBarTrailing) { + Text(store.space.name).font(.caption).foregroundStyle(.secondary) + .lineLimit(1).frame(maxWidth: 108, alignment: .trailing) + .accessibilityLabel("当前空间:\(store.space.name)") + } + } + .task(id: results.loadID(query: query, revision: store.revision)) { + await results.load(store: store, query: query, favorites: favoritesOnly) + } + .refreshable { await results.load(store: store, query: query, favorites: favoritesOnly) } + } +} + +@MainActor +@Observable +final class ItemListResults { + struct LoadID: Hashable { + let query: String + let revision: Int + let retry: Int + } + + private(set) var rows: [Item] = [] + private(set) var loading = true + private(set) var loadingMore = false + private(set) var more = false + private(set) var error: String? + private var retryCount = 0 + private var displayedQuery = "" + private var activeRequest: UUID? + + func loadID(query: String, revision: Int) -> LoadID { + LoadID(query: query.trimmingCharacters(in: .whitespacesAndNewlines), revision: revision, retry: retryCount) + } + + func retry() { retryCount += 1 } + + func load(store: InventoryStore, query: String = "", favorites: Bool = false, + location: UUID? = nil, append: Bool = false) async { + let input = query.trimmingCharacters(in: .whitespacesAndNewlines) + guard !append || (more && !loading && !loadingMore && input == displayedQuery) else { return } + let request = UUID() + activeRequest = request + let revision = store.revision + error = nil + if append { + loadingMore = true + } else { + loadingMore = false + loading = rows.isEmpty || displayedQuery != input + if loading { rows = []; more = false } + } + defer { + if activeRequest == request { + loading = false + loadingMore = false + } + } + do { + if !append && !input.isEmpty { try await Task.sleep(for: .milliseconds(240)) } + let page = try await store.search(input, favorites: favorites, location: location, + offset: append ? rows.count : 0) + try Task.checkCancellation() + guard activeRequest == request, store.revision == revision else { return } + if append { + let existing = Set(rows.map(\.id)) + rows += page.filter { !existing.contains($0.id) } + } else { + rows = page + displayedQuery = input + } + more = page.count == 50 && rows.count <= 10000 + } catch where !Task.isCancelled && activeRequest == request { + if let urlError = error as? URLError, urlError.code == .timedOut { + self.error = "请求超时,请重试。" + } else { + self.error = error.localizedDescription + } + } catch {} } } struct ItemsSection: View { let store: InventoryStore + let results: ItemListResults var query = "" var favorites = false var location: UUID? = nil - @State private var rows: [Item] = [] - @State private var displayedQuery = "" - @State private var loading = true - @State private var more = false - @State private var loadingMore = false - @State private var error: String? - @State private var retry = 0 @State private var showingAdd = false private var input: String { query.trimmingCharacters(in: .whitespacesAndNewlines) } var body: some View { Section { - if loading { ProgressView("加载中") } - else if rows.isEmpty && error == nil { + if results.loading { ProgressView("加载中") } + else if results.rows.isEmpty && results.error == nil { ContentUnavailableView(emptyTitle, systemImage: favorites ? "star" : "archivebox", description: Text(emptyDescription)) } - ForEach(rows) { item in + ForEach(results.rows) { item in NavigationLink { ItemDetailView(store: store, itemID: item.id) } label: { HStack(spacing: 12) { PhotoImage(store: store, item: item.id, photo: item.coverPhotoId, thumbnail: true) @@ -87,18 +158,19 @@ struct ItemsSection: View { .padding(.vertical, 4) } } - if more { - Button(loadingMore ? "加载中" : "加载更多") { Task { await load(append: true) } }.disabled(loadingMore) + if results.more && results.error == nil { + Button(results.loadingMore ? "加载中" : "加载更多") { + Task { await results.load(store: store, query: query, favorites: favorites, location: location, append: true) } + }.disabled(results.loadingMore) } - if let error { + if let error = results.error { Text(error).foregroundStyle(.red) - Button("重试") { retry += 1 } + Button("重试") { results.retry() } } if !favorites && store.canWrite && input.isEmpty { - Button { showingAdd = true } label: { Label("记一件", systemImage: "plus") } + Button { showingAdd = true } label: { Label("添加物品", systemImage: "plus") } } } - .task(id: "\(store.revision):\(retry):\(input)") { await load() } .sheet(isPresented: $showingAdd) { ItemEditor(store: store, initialLocation: location) } } @@ -109,36 +181,9 @@ struct ItemsSection: View { private var emptyDescription: String { if !input.isEmpty { return "试试别名、房间或收纳盒名称。" } - if favorites { return "可以在详情里收藏常用的东西。" } + if favorites { return "在当前空间的物品详情里点收藏,就会出现在这里。" } return store.canWrite ? "从手边的一件东西开始。" : "空间成员添加物品后会显示在这里。" } - - private func load(append: Bool = false) async { - let requested = input - let revision = store.revision - if append { - loadingMore = true - } else if rows.isEmpty || displayedQuery != requested { - loading = true - rows = [] - more = false - } - defer { if append { loadingMore = false } } - do { - if !append && !requested.isEmpty { try await Task.sleep(for: .milliseconds(240)) } - let page = try await store.search(requested, favorites: favorites, location: location, offset: append ? rows.count : 0) - try Task.checkCancellation() - guard requested == input, revision == store.revision else { return } - if append { - let existing = Set(rows.map(\.id)) - rows += page.filter { !existing.contains($0.id) } - } else { rows = page; displayedQuery = requested } - more = page.count == 50 && rows.count <= 10000 - error = nil - } catch where !Task.isCancelled { self.error = error.localizedDescription } - catch { return } - if !append { loading = false } - } } struct ItemDetailView: View { diff --git a/apps/ios/ItemAtlas/ItemAtlasApp.swift b/apps/ios/ItemAtlas/ItemAtlasApp.swift index c2f6375..25cbaf3 100644 --- a/apps/ios/ItemAtlas/ItemAtlasApp.swift +++ b/apps/ios/ItemAtlas/ItemAtlasApp.swift @@ -26,6 +26,7 @@ private struct SpacesView: View { @State private var selected: Space? @State private var showingCreate = false @State private var showingJoin = false + @State private var showingMyProfile = false @State private var loaded = false @State private var error: String? @State private var invitations: [ReceivedSpaceInvitation] = [] @@ -70,16 +71,16 @@ private struct SpacesView: View { .task { await load(chooseSingle: !loaded) } .refreshable { await load() } .navigationTitle("我的空间") + .navigationBarTitleDisplayMode(.inline) .toolbar { - ToolbarItem(placement: .topBarTrailing) { - Menu { - Button("使用邀请码") { showingJoin = true } - Button("退出登录", role: .destructive) { Task { await account.signOut() } } - } label: { - Label("更多", systemImage: "ellipsis.circle") - } + ToolbarItemGroup(placement: .topBarTrailing) { + Button { showingJoin = true } label: { Label("使用邀请码", systemImage: "person.badge.plus") } + Button { showingMyProfile = true } label: { Label("我的", systemImage: "person.crop.circle") } } } + .sheet(isPresented: $showingMyProfile) { + NavigationStack { MyView(account: account, openSpaces: { showingMyProfile = false }) } + } .sheet(isPresented: $showingCreate) { SpaceEditor(account: account, joining: false) { selected = $0 } } @@ -140,8 +141,9 @@ private struct SpaceTabs: View { InventoryView(store: store).tabItem { Label("找物", systemImage: "magnifyingglass") } LocationView(store: store).tabItem { Label("位置", systemImage: "square.stack") } IntakeView(store: store).tabItem { Label("录入", systemImage: "square.and.pencil") } - InventoryView(store: store, favoritesOnly: true).tabItem { Label("收藏", systemImage: "star") } - SpaceSettings(store: store, openSpaces: openSpaces).tabItem { Label("空间", systemImage: "house") } + NavigationStack { + MyView(account: store.account, store: store, openSpaces: openSpaces) + }.tabItem { Label("我的", systemImage: "person.crop.circle") } } } } @@ -194,7 +196,7 @@ private struct SpaceEditor: View { } } -private struct SpaceSettings: View { +struct SpaceSettings: View { let store: InventoryStore let openSpaces: () -> Void @State private var confirming = false @@ -203,37 +205,34 @@ private struct SpaceSettings: View { @State private var error: String? var body: some View { - NavigationStack { - List { - LabeledContent("当前空间", value: store.space.name) - Button("切换空间", action: openSpaces).disabled(busy) - if store.space.role == "OWNER" { - Section("成员") { - Button { showingInvite = true } label: { - Label("邀请成员", systemImage: "person.badge.plus") - } - } - Section { - Button("删除空间", role: .destructive) { confirming = true }.disabled(busy) + List { + LabeledContent("当前空间", value: store.space.name) + if store.space.role == "OWNER" { + Section("成员") { + Button { showingInvite = true } label: { + Label("邀请成员", systemImage: "person.badge.plus") } } - Button("退出登录", role: .destructive) { Task { await store.account.signOut() } }.disabled(busy) - if let error { Text(error).foregroundStyle(.red) } - } - .navigationTitle("空间") - .sheet(isPresented: $showingInvite) { SpaceInvitationView(store: store) } - .confirmationDialog("删除「\(store.space.name)」?", isPresented: $confirming, titleVisibility: .visible) { - Button("删除空间和图片", role: .destructive) { - Task { - busy = true - defer { busy = false } - do { try await store.delete(store.root); openSpaces() } - catch { self.error = error.localizedDescription } - } + Section { + Button("删除空间", role: .destructive) { confirming = true }.disabled(busy) } - } message: { - Text("此空间里的物品、位置和图片都会删除,空间成员会失去访问权限。") } + if let error { Text(error).foregroundStyle(.red) } + } + .navigationTitle("空间设置") + .navigationBarTitleDisplayMode(.inline) + .sheet(isPresented: $showingInvite) { SpaceInvitationView(store: store) } + .confirmationDialog("删除「\(store.space.name)」?", isPresented: $confirming, titleVisibility: .visible) { + Button("删除空间和图片", role: .destructive) { + Task { + busy = true + defer { busy = false } + do { try await store.delete(store.root); openSpaces() } + catch { self.error = error.localizedDescription } + } + } + } message: { + Text("此空间里的物品、位置和图片都会删除,空间成员会失去访问权限。") } } } diff --git a/apps/ios/ItemAtlas/LocationView.swift b/apps/ios/ItemAtlas/LocationView.swift index 6822cef..745f36d 100644 --- a/apps/ios/ItemAtlas/LocationView.swift +++ b/apps/ios/ItemAtlas/LocationView.swift @@ -11,6 +11,7 @@ private struct LocationContents: View { let store: InventoryStore let location: Place? @Environment(\.dismiss) private var dismiss + @State private var items = ItemListResults() @State private var editingLocation = false @State private var confirmingDelete = false @State private var error: String? @@ -33,12 +34,16 @@ private struct LocationContents: View { } } if let location { - ItemsSection(store: store, location: location.id) + ItemsSection(store: store, results: items, location: location.id) if store.canWrite { Button("删除位置", role: .destructive) { confirmingDelete = true }.disabled(busy) } } if let error { Text(error).foregroundStyle(.red); Button("重试") { retry += 1 } } } .navigationTitle(location?.name ?? "位置") + .navigationBarTitleDisplayMode(.inline) + .task(id: items.loadID(query: "", revision: store.revision)) { + if let location { await items.load(store: store, location: location.id) } + } .task(id: retry) { do { try await store.refreshLocations(); error = nil } catch { self.error = error.localizedDescription } diff --git a/apps/ios/ItemAtlas/MyView.swift b/apps/ios/ItemAtlas/MyView.swift new file mode 100644 index 0000000..5150ca0 --- /dev/null +++ b/apps/ios/ItemAtlas/MyView.swift @@ -0,0 +1,262 @@ +import SwiftUI + +private struct AccountProfile: Decodable { + let username: String? + let nickname: String + let signature: String + let avatar: ProfileAvatar + + var displayName: String { nickname.isEmpty ? (username ?? "我的账号") : nickname } + + struct Update: Encodable { + var nickname: String + var signature: String + var avatar: ProfileAvatar + } +} + +private enum ProfileAvatar: String, CaseIterable, Codable, Identifiable { + case person = "PERSON" + case cat = "CAT" + case leaf = "LEAF" + case moon = "MOON" + case mountain = "MOUNTAIN" + case spark = "SPARK" + + var id: Self { self } + + var symbol: String { + switch self { + case .person: "person.fill" + case .cat: "cat.fill" + case .leaf: "leaf.fill" + case .moon: "moon.stars.fill" + case .mountain: "mountain.2.fill" + case .spark: "sparkle" + } + } + + var title: String { + switch self { + case .person: "默认" + case .cat: "小猫" + case .leaf: "叶子" + case .moon: "夜空" + case .mountain: "山丘" + case .spark: "星光" + } + } + + var color: Color { + switch self { + case .person: .atlasBlue + case .cat: .orange + case .leaf: .green + case .moon: .purple + case .mountain: .teal + case .spark: .pink + } + } +} + +private struct AvatarBadge: View { + let avatar: ProfileAvatar + let size: CGFloat + + var body: some View { + Image(systemName: avatar.symbol) + .font(.system(size: size * 0.40, weight: .medium)) + .symbolRenderingMode(.hierarchical) + .foregroundStyle(avatar.color) + .frame(width: size, height: size) + .background(avatar.color.opacity(0.12), in: Circle()) + .accessibilityHidden(true) + } +} + +struct MyView: View { + let account: AtlasAccount + var store: InventoryStore? = nil + let openSpaces: () -> Void + + @State private var profile: AccountProfile? + @State private var profileError: String? + @State private var showingProfile = false + @State private var confirmingSignOut = false + + var body: some View { + List { + Section { + if let profile { + Button { showingProfile = true } label: { + HStack(spacing: 13) { + AvatarBadge(avatar: profile.avatar, size: 52) + VStack(alignment: .leading, spacing: 4) { + Text(profile.displayName).font(.headline) + if !profile.nickname.isEmpty, let username = profile.username { + Text("账号 " + username).font(.caption).foregroundStyle(.secondary) + } + Text(profile.signature.isEmpty ? "添加签名" : profile.signature) + .font(.subheadline).foregroundStyle(.secondary).lineLimit(2) + } + .frame(maxWidth: .infinity, alignment: .leading) + Image(systemName: "pencil") + .foregroundStyle(Color.atlasBlue) + .accessibilityHidden(true) + } + .padding(.vertical, 5) + .foregroundStyle(.primary) + } + .buttonStyle(.plain) + .accessibilityHint("编辑头像、昵称和签名") + } else if profileError == nil { + ProgressView("正在加载资料") + } + if let profileError { + Text(profileError).font(.footnote).foregroundStyle(.secondary) + Button("重新加载资料") { Task { await loadProfile() } } + } + } + + Section("空间") { + if let store { + NavigationLink { + SpaceSettings(store: store, openSpaces: openSpaces) + } label: { + Label { + VStack(alignment: .leading, spacing: 3) { + Text(store.space.name) + Text("空间设置").font(.caption).foregroundStyle(.secondary) + } + } icon: { + Image(systemName: "house") + } + } + Button(action: openSpaces) { Label("切换空间", systemImage: "arrow.left.arrow.right") } + } else { + Button(action: openSpaces) { Label("查看我的空间", systemImage: "house") } + } + } + + if let store { + Section { + NavigationLink { + ItemListView(store: store, favoritesOnly: true) + } label: { + Label("我的收藏", systemImage: "star") + } + } + } + + Section { + Button(role: .destructive) { confirmingSignOut = true } label: { + Label("退出登录", systemImage: "rectangle.portrait.and.arrow.right") + } + } + } + .navigationTitle("我的") + .navigationBarTitleDisplayMode(.inline) + .task { if profile == nil { await loadProfile() } } + .refreshable { await loadProfile() } + .sheet(isPresented: $showingProfile) { + if let profile { + ProfileEditor(account: account, profile: profile) { self.profile = $0 } + } + } + .confirmationDialog("退出当前账号?", isPresented: $confirmingSignOut, titleVisibility: .visible) { + Button("退出登录", role: .destructive) { Task { await account.signOut() } } + } + } + + private func loadProfile() async { + do { + let data = try await account.request("/api/me/profile", timeout: 12) + try Task.checkCancellation() + profile = try JSONDecoder().decode(AccountProfile.self, from: data) + profileError = nil + } catch where !Task.isCancelled { + profileError = "暂时无法加载账号资料。" + } catch {} + } +} + +private struct ProfileEditor: View { + let account: AtlasAccount + let saved: (AccountProfile) -> Void + @Environment(\.dismiss) private var dismiss + @FocusState private var typing: Bool + @State private var update: AccountProfile.Update + @State private var busy = false + @State private var error: String? + + init(account: AtlasAccount, profile: AccountProfile, saved: @escaping (AccountProfile) -> Void) { + self.account = account + self.saved = saved + _update = State(initialValue: AccountProfile.Update(nickname: profile.nickname, signature: profile.signature, + avatar: profile.avatar)) + } + + var body: some View { + NavigationStack { + Form { + Section("头像") { + LazyVGrid(columns: Array(repeating: GridItem(.flexible()), count: 3), spacing: 14) { + ForEach(ProfileAvatar.allCases) { avatar in + Button { + update.avatar = avatar + } label: { + VStack(spacing: 5) { + AvatarBadge(avatar: avatar, size: 48) + .padding(2) + .overlay { + Circle().strokeBorder(update.avatar == avatar ? Color.atlasBlue : .clear, + lineWidth: 2) + } + Text(avatar.title).font(.caption).foregroundStyle(.primary) + } + .frame(maxWidth: .infinity) + } + .buttonStyle(.plain) + .accessibilityAddTraits(update.avatar == avatar ? .isSelected : []) + } + } + .padding(.vertical, 7) + } + Section { + TextField("昵称", text: $update.nickname).focused($typing) + TextField("签名", text: $update.signature).focused($typing) + } header: { + Text("资料") + } footer: { + if update.nickname.utf16.count > 32 || update.signature.utf16.count > 100 { + Text("昵称最多 32 字符,签名最多 100 字符。") + } + } + if let error { Text(error).foregroundStyle(.red) } + } + .dismissibleKeyboard(active: typing) { typing = false } + .navigationTitle("编辑资料") + .navigationBarTitleDisplayMode(.inline) + .toolbar { + ToolbarItem(placement: .cancellationAction) { Button("取消") { dismiss() }.disabled(busy) } + ToolbarItem(placement: .confirmationAction) { + Button("保存") { typing = false; Task { await save() } } + .disabled(busy || update.nickname.utf16.count > 32 || update.signature.utf16.count > 100) + } + } + } + .interactiveDismissDisabled(busy) + } + + private func save() async { + guard !busy else { return } + busy = true + defer { busy = false } + error = nil + do { + let data = try await account.request("/api/me/profile", method: "PUT", data: JSONEncoder().encode(update), timeout: 12) + saved(try JSONDecoder().decode(AccountProfile.self, from: data)) + dismiss() + } catch { self.error = error.localizedDescription } + } +} diff --git a/backend/gateway/src/main/resources/application.yml b/backend/gateway/src/main/resources/application.yml index dc468bf..a34b545 100644 --- a/backend/gateway/src/main/resources/application.yml +++ b/backend/gateway/src/main/resources/application.yml @@ -35,7 +35,7 @@ spring: - id: inventory uri: ${ATLAS_INVENTORY_URL:http://127.0.0.1:8081} predicates: - - Path=/api/households,/api/households/**,/api/admin/** + - Path=/api/me/profile,/api/households,/api/households/**,/api/admin/** filters: - RequestSize=64KB server: diff --git a/backend/inventory-service/src/main/java/com/tutudog/itematlas/inventory/AccountProfileController.java b/backend/inventory-service/src/main/java/com/tutudog/itematlas/inventory/AccountProfileController.java new file mode 100644 index 0000000..babcece --- /dev/null +++ b/backend/inventory-service/src/main/java/com/tutudog/itematlas/inventory/AccountProfileController.java @@ -0,0 +1,40 @@ +package com.tutudog.itematlas.inventory; + +import jakarta.validation.Valid; +import org.springframework.http.CacheControl; +import org.springframework.http.ResponseEntity; +import org.springframework.security.core.Authentication; +import org.springframework.security.oauth2.server.resource.authentication.JwtAuthenticationToken; +import org.springframework.web.bind.annotation.GetMapping; +import org.springframework.web.bind.annotation.PutMapping; +import org.springframework.web.bind.annotation.RequestBody; +import org.springframework.web.bind.annotation.RequestMapping; +import org.springframework.web.bind.annotation.RestController; + +@RestController +@RequestMapping("/api/me/profile") +class AccountProfileController { + private final AccountProfileService service; + + AccountProfileController(AccountProfileService service) { this.service = service; } + + @GetMapping + ResponseEntity get(Authentication user) { + return ResponseEntity.ok().cacheControl(CacheControl.noStore()) + .body(service.get(user.getName(), loginName(user))); + } + + @PutMapping + ResponseEntity save(Authentication user, + @Valid @RequestBody AccountProfileService.Update update) { + return ResponseEntity.ok().cacheControl(CacheControl.noStore()) + .body(service.save(user.getName(), loginName(user), update)); + } + + private static String loginName(Authentication user) { + if (user instanceof JwtAuthenticationToken token) { + return token.getToken().getClaimAsString("preferred_username"); + } + return user.getName(); + } +} diff --git a/backend/inventory-service/src/main/java/com/tutudog/itematlas/inventory/AccountProfileService.java b/backend/inventory-service/src/main/java/com/tutudog/itematlas/inventory/AccountProfileService.java new file mode 100644 index 0000000..247a6db --- /dev/null +++ b/backend/inventory-service/src/main/java/com/tutudog/itematlas/inventory/AccountProfileService.java @@ -0,0 +1,55 @@ +package com.tutudog.itematlas.inventory; + +import jakarta.validation.constraints.NotNull; +import jakarta.validation.constraints.Pattern; +import jakarta.validation.constraints.Size; +import java.sql.Types; +import org.springframework.jdbc.core.simple.JdbcClient; +import org.springframework.stereotype.Service; +import org.springframework.transaction.annotation.Transactional; + +@Service +class AccountProfileService { + private final JdbcClient db; + + AccountProfileService(JdbcClient db) { this.db = db; } + + Profile get(String subject, String loginName) { + return db.sql(""" + SELECT COALESCE(a.username, :loginName) AS username, + COALESCE(p.nickname, '') AS nickname, + COALESCE(p.signature, '') AS signature, + COALESCE(p.avatar, 'PERSON') AS avatar + FROM (VALUES (CAST(:subject AS text))) AS account(subject) + LEFT JOIN native_account a ON a.subject=account.subject + LEFT JOIN account_profile p ON p.subject=account.subject + """) + .param("subject", subject).param("loginName", loginName, Types.VARCHAR) + .query((rs, row) -> new Profile(rs.getString("username"), rs.getString("nickname"), + rs.getString("signature"), Avatar.valueOf(rs.getString("avatar")))) + .single(); + } + + @Transactional + Profile save(String subject, String loginName, Update update) { + db.sql(""" + INSERT INTO account_profile(subject,nickname,signature,avatar) + VALUES (:subject,:nickname,:signature,:avatar) + ON CONFLICT (subject) DO UPDATE SET nickname=excluded.nickname, + signature=excluded.signature,avatar=excluded.avatar + """) + .param("subject", subject).param("nickname", update.nickname().strip()) + .param("signature", update.signature().strip()).param("avatar", update.avatar().name()).update(); + return get(subject, loginName); + } + + enum Avatar { PERSON, CAT, LEAF, MOON, MOUNTAIN, SPARK } + + record Profile(String username, String nickname, String signature, Avatar avatar) {} + + record Update( + @NotNull @Size(max = 32) @Pattern(regexp = "[^\\p{Cntrl}]*") String nickname, + @NotNull @Size(max = 100) @Pattern(regexp = "[^\\p{Cntrl}]*") String signature, + @NotNull Avatar avatar + ) {} +} diff --git a/backend/inventory-service/src/main/resources/db/migration/V8__account_profile.sql b/backend/inventory-service/src/main/resources/db/migration/V8__account_profile.sql new file mode 100644 index 0000000..4bc0a7b --- /dev/null +++ b/backend/inventory-service/src/main/resources/db/migration/V8__account_profile.sql @@ -0,0 +1,6 @@ +CREATE TABLE account_profile ( + subject text PRIMARY KEY, + nickname varchar(32) NOT NULL, + signature varchar(100) NOT NULL, + avatar varchar(16) NOT NULL CHECK (avatar IN ('PERSON', 'CAT', 'LEAF', 'MOON', 'MOUNTAIN', 'SPARK')) +); diff --git a/backend/tests/ios_experience_smoke.py b/backend/tests/ios_experience_smoke.py index d9ea789..fb26bc0 100644 --- a/backend/tests/ios_experience_smoke.py +++ b/backend/tests/ios_experience_smoke.py @@ -7,6 +7,7 @@ from smoke import RUN, await_operation, call, ready def verify(): ready() + verify_profiles() space = call("POST", "/api/households", {"name": "见物体验 " + RUN}, status=201) root = "/api/households/" + space["id"] try: @@ -16,6 +17,27 @@ def verify(): call("DELETE", root, status=202) +def verify_profiles(): + path = "/api/me/profile" + call("GET", path, user=None, status=401) + owner = call("GET", path) + viewer = call("GET", path, user="viewer") + assert viewer["username"] == "viewer" + fields = ("nickname", "signature", "avatar") + try: + update = {"nickname": " 小见 ", "signature": " 把常用物放回原处 ", "avatar": "LEAF"} + result = call("PUT", path, update) + assert result == {"username": owner["username"], "nickname": "小见", "signature": "把常用物放回原处", "avatar": "LEAF"} + assert call("GET", path) == result + assert call("GET", path, user="viewer") == viewer + call("PUT", path, dict(update, avatar="UNKNOWN"), status=400) + call("PUT", path, dict(update, signature="字" * 101), status=400) + assert call("GET", path) == result + finally: + call("PUT", path, {field: owner[field] for field in fields}) + print("PASS private editable profile, account display and input validation", flush=True) + + def verify_search_and_voice(root): def location(name, parent=None): return call("POST", root + "/locations", {"name": name, "parentId": parent}, status=201)["id"] @@ -34,6 +56,10 @@ def verify_search_and_voice(root): contains = call("POST", root + "/items", item("旧数据线备用", drawer), status=201)["id"] percent = call("POST", root + "/items", item("标签%尺寸", entry), status=201)["id"] + assert call("GET", root + "/items?favorites=true") == [] + call("PUT", root + "/items/" + exact + "/preference", {"favorite": True}) + assert [row["id"] for row in call("GET", root + "/items?favorites=true")] == [exact] + def search(term): return [row["id"] for row in call("GET", root + "/items?" + urlencode({"q": term}))] diff --git a/docs/architecture/account-profile.md b/docs/architecture/account-profile.md new file mode 100644 index 0000000..f96ac48 --- /dev/null +++ b/docs/architecture/account-profile.md @@ -0,0 +1,19 @@ +# 账号资料与收藏 + +iOS 的「我的」显示账号资料、当前空间、收藏和退出入口。个人资料跨空间,收藏仍按当前空间和个人账号筛选。 + +## 资料接口 + +`GET /api/me/profile` 返回账号、昵称、签名和头像。没有资料记录时,直接返回默认头像和空的昵称、签名。新老账号都可使用,原生账号名称从账号表读取,旧会话可以使用已验证的用户名声明。 + +`PUT /api/me/profile` 保存昵称、签名和内置头像标识。昵称最多 32 字符,签名最多 100 字符。头像从服务端允许的六个标识中选择。网关沿用请求大小限制,物品服务使用已验证会话的 subject 定位当前用户。两条接口都设置 `Cache-Control: no-store`。 + +Flyway V8 新增 `account_profile`,主键是账号的 subject。资料同空间成员表分开,一份资料可在各空间显示。更新使用 PostgreSQL 的主键冲突更新,在同一个事务中返回保存结果。现有登录会话和物品数据保持兼容,回退应用时可以保留新增表。 + +## 收藏加载 + +收藏复用物品列表 API 的 `favorites=true` 参数。数据库同时匹配当前空间、账号和物品。iOS 在实际显示的导航页启动请求。切换搜索词或列表刷新会使旧请求失效,失败后结束加载并提供重试。 + +## 验收 + +`backend/tests/ios_experience_smoke.py` 检查未登录访问、不同账号资料隔离、保存回读、输入验证、空收藏和有收藏的返回。客户端覆盖 [TC-28 与 TC-29](../testing/cases.md)。 diff --git a/docs/product/ios-experience.md b/docs/product/ios-experience.md index 8da67b2..e3ca103 100644 --- a/docs/product/ios-experience.md +++ b/docs/product/ios-experience.md @@ -10,6 +10,14 @@ 结束后可修改原话。见物先用规则生成物品和位置草稿,较长的描述可以点「用 AI 整理」。核对名称、数量和位置后,点「保存物品」。也可以直接点「手动添加物品」填写表单。录入页右上角的问号可以查看这两套操作。 +## 我的 + +顶部的一行显示头像、账号或昵称、签名。点这一行可修改头像、昵称和签名,保存后跟随账号。首版头像从六个内置图案中选择。 + +下面是当前空间、空间设置和切换空间。收藏在「我的收藏」里,按当前空间显示。切换空间后可以查看该空间的收藏。收藏列表为空时直接显示空状态,加载出错可以重试。退出登录放在页面底部。 + +找物、位置、录入、我的使用同一套紧凑导航栏。录入页右上角的问号保留四步说明。 + ## 家庭邀请 空间所有者输入对方的见物账号并选择角色。对方在「我的空间」看到邀请,接受后才获得访问权限。单独用手机号查找需要可验证的手机号和防枚举机制,首版按用户已知的见物账号精确发送。现有码仍可兑换。 diff --git a/docs/testing/cases.md b/docs/testing/cases.md index df017ff..9a5e2a6 100644 --- a/docs/testing/cases.md +++ b/docs/testing/cases.md @@ -31,5 +31,7 @@ R01–R09 对应[需求与验收](../product/requirements.md)。实现和当前 | TC-25 按账号邀请 | R01 | 所有者邀请查看者,另一个账号尝试读取和接受。被邀请者同时接受两次,并尝试写入。 | 只有本人看到邀请并加入,两次接受返回同一成员,查看者不能写入。 | | TC-26 iOS 录音权限 | R06 | 在真机首次点「开始录音」,允许麦克风和语音识别。停止后再次录音。随后在设置关闭语音识别,回到录入页再点一次。 | 授权后可录音和重录。拒绝权限时保留录入页,提示开启权限或直接打字。 | | TC-27 停顿与录音时长 | R06 | 点按开始,说一句后停两秒再说另一句。分别测试手动结束、录满 25 秒和按住说后松手。 | 两句都在转写中,录音进度显示用时。手动结束、松手或时长达到上限后结束采集。 | +| TC-28 我的和账号资料 | R01 | 已登录打开「我的」,编辑头像、昵称、签名。重新打开后再用另一个账号查看资料。 | 资料随账号保存,默认头像可用,两个账号互相独立。没有空间时可从空间列表打开资料。 | +| TC-29 我的收藏 | R08 | 从「我的」进入收藏,检查空状态。收藏一件物品后再次进入,再切换空间,模拟一次加载失败并重试。 | 空、有内容和加载失败各有状态。当前空间的个人收藏在列表显示,失败后可重试。 | [测试与演示计划](plan.md)