diff --git a/apps/ios/ItemAtlas.xcodeproj/project.pbxproj b/apps/ios/ItemAtlas.xcodeproj/project.pbxproj index c20110e..14dada4 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 = 12; + CURRENT_PROJECT_VERSION = 13; 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 = 12; + CURRENT_PROJECT_VERSION = 13; 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 b7376d9..fab9a78 100644 --- a/apps/ios/ItemAtlas/Account.swift +++ b/apps/ios/ItemAtlas/Account.swift @@ -5,7 +5,13 @@ import Security struct AtlasError: LocalizedError { let message: String var errorDescription: String? { message } - init(_ message: String) { self.message = message } + let status: Int? + init(_ message: String, status: Int? = nil) { + self.message = message + self.status = status + } + + var resourceUnavailable: Bool { status == 403 || status == 404 } } struct AtlasEndpoints { let api: URL @@ -79,6 +85,7 @@ final class AtlasAccount { private(set) var error: String? private let configuration = try? AtlasEndpoints() private let http: URLSession + @ObservationIgnored private let previews = SessionReadCache() private var tokens: SessionTokens? private var metadata: OIDCMetadata? private var refreshTask: Task? @@ -140,6 +147,28 @@ final class AtlasAccount { } } + func cached(_ path: String) -> T? { + guard let data = cachedPreview(path) else { return nil } + return try? JSONDecoder().decode(T.self, from: data) + } + + func cachedPreview(_ path: String) -> Data? { signedIn ? previews.cached(path) : nil } + + func read(_ path: String, refresh: Bool = false) async throws -> T { + try JSONDecoder().decode(T.self, from: await readPreview(path, refresh: refresh)) + } + + func readPreview(_ path: String, refresh: Bool = false) async throws -> Data { + guard signedIn else { throw CancellationError() } + return try await previews.load(path, refresh: refresh) { + try await self.request(path, timeout: 12) + } + } + + func invalidateReads(_ prefix: String, discard: Bool = false) { + previews.invalidate(prefix, discard: discard) + } + func request(_ path: String, method: String = "GET", data: Data? = nil, contentType: String = "application/json", timeout: TimeInterval? = nil, idempotencyKey: UUID? = nil) async throws -> Data { @@ -169,7 +198,10 @@ final class AtlasAccount { guard let status = (response as? HTTPURLResponse)?.statusCode, (200..<300).contains(status) else { let problem = try? JSONDecoder().decode(Problem.self, from: body) let status = (response as? HTTPURLResponse)?.statusCode ?? 0 - throw AtlasError(problem?.detail ?? "请求失败(\(status)),请稍后重试。") + if status == 403 || status == 404, method == "GET" { + previews.discard(path) + } + throw AtlasError(problem?.detail ?? "请求失败(\(status)),请稍后重试。", status: status) } return body } @@ -270,6 +302,7 @@ final class AtlasAccount { refreshTask?.cancel() refreshTask = nil generation = UUID() + previews.invalidate("", discard: true) tokens = nil signedIn = false error = nil diff --git a/apps/ios/ItemAtlas/CommunityView.swift b/apps/ios/ItemAtlas/CommunityView.swift index 096e928..8c2a836 100644 --- a/apps/ios/ItemAtlas/CommunityView.swift +++ b/apps/ios/ItemAtlas/CommunityView.swift @@ -53,6 +53,18 @@ private struct CommunityAPI { return try JSONDecoder().decode(T.self, from: await account.request(url.string ?? path, timeout: 12)) } + static func feedPath(mine: Bool, term: String = "", after cursor: FeedCursor? = nil) -> String { + var url = URLComponents() + url.path = posts + url.queryItems = [.init(name: "q", value: term), .init(name: "mine", value: String(mine))] + if let cursor { + url.queryItems?.append(contentsOf: [.init(name: "rank", value: String(cursor.rank)), + .init(name: "time", value: cursor.time), + .init(name: "before", value: cursor.id.uuidString)]) + } + return url.string ?? posts + } + func send(_ path: String, method: String, _ body: T) async throws -> R { let data = try await account.request(path, method: method, data: JSONEncoder().encode(body), timeout: 12) return try JSONDecoder().decode(R.self, from: data) @@ -64,27 +76,42 @@ struct CommunityFeedView: View { var source: InventoryStore? = nil var mine = false @State private var query = "" - @State private var posts: [CommunityPost] = [] + @State private var posts: [CommunityPost] @State private var next: FeedCursor? - @State private var loading = true + @State private var displayedTerm: String? + @State private var updating = false @State private var moreLoading = false @State private var error: String? @State private var requestID: UUID? @State private var showingChooser = false @State private var revision = 0 + init(account: AtlasAccount, source: InventoryStore? = nil, mine: Bool = false) { + self.account = account + self.source = source + self.mine = mine + let preview: FeedResponse? = account.cached(CommunityAPI.feedPath(mine: mine)) + _posts = State(initialValue: preview?.posts ?? []) + _next = State(initialValue: preview?.next) + _displayedTerm = State(initialValue: preview == nil ? nil : "") + } + + static func warm(account: AtlasAccount) async { + let _: FeedResponse? = try? await account.read(CommunityAPI.feedPath(mine: false)) + } + private var term: String { query.trimmingCharacters(in: .whitespacesAndNewlines) } var body: some View { List { - if loading { + if displayedTerm != term && error == nil { ProgressView("正在加载分享") } else if posts.isEmpty && error == nil { ContentUnavailableView(term.isEmpty ? "还没有分享" : "没找到相关分享", systemImage: "bubble.left.and.bubble.right", description: Text(mine ? "你公开的物品会显示在这里。" : "可以搜索公开物品,或发布自己的使用感受。")) } - ForEach(posts) { post in + ForEach(displayedTerm == term ? posts : []) { post in NavigationLink { CommunityDetailView(account: account, postID: post.id) } label: { @@ -105,11 +132,11 @@ struct CommunityFeedView: View { if let error { Section { Text(error).font(.footnote).foregroundStyle(.red) - Button("重试") { revision += 1 } + Button("重试") { Task { await load(refresh: true) } } } - } else if next != nil { + } else if next != nil && displayedTerm == term { Button(moreLoading ? "正在加载" : "更多分享") { Task { await load(append: true) } } - .disabled(moreLoading || loading) + .disabled(moreLoading || updating) } } .navigationTitle(mine ? "我公开的物品" : "社区") @@ -126,38 +153,61 @@ struct CommunityFeedView: View { if let source { CommunityItemChooser(store: source) { revision += 1 } } } .task(id: "\(revision):\(source?.revision ?? 0):\(term)") { await load() } - .refreshable { await load() } + .refreshable { await load(refresh: true) } } - private func load(append: Bool = false) async { - let cursor = append ? next : nil - guard !append || (cursor != nil && !loading && !moreLoading) else { return } + private func load(append: Bool = false, refresh: Bool = false) async { let requested = term + let cursor = append ? next : nil + guard !append || (cursor != nil && !updating && !moreLoading && displayedTerm == requested) else { return } let id = UUID() requestID = id error = nil - loading = !append + updating = !append moreLoading = append - if !append { next = nil; posts = [] } + let firstPage = !append && requested.isEmpty + let path = CommunityAPI.feedPath(mine: mine, term: requested, after: cursor) + if firstPage, displayedTerm != requested, let preview: FeedResponse = account.cached(path) { + posts = preview.posts + next = preview.next + displayedTerm = requested + } defer { - if requestID == id { loading = false; moreLoading = false } + if requestID == id { updating = false; moreLoading = false } } do { if !append && !requested.isEmpty { try await Task.sleep(for: .milliseconds(250)) } - var parameters = [URLQueryItem(name: "q", value: requested), - URLQueryItem(name: "mine", value: String(mine))] - if let cursor { - parameters += [.init(name: "rank", value: String(cursor.rank)), - .init(name: "time", value: cursor.time), .init(name: "before", value: cursor.id.uuidString)] + let result: FeedResponse + if firstPage { + result = try await account.read(path, refresh: refresh) + } else { + let data = try await account.request(path, timeout: 12) + result = try JSONDecoder().decode(FeedResponse.self, from: data) } - let result: FeedResponse = try await CommunityAPI(account: account).load(CommunityAPI.posts, query: parameters) try Task.checkCancellation() guard requestID == id, term == requested else { return } - let existing = Set(posts.map(\.id)) - posts += result.posts.filter { !existing.contains($0.id) } - next = result.next - } catch where !Task.isCancelled && requestID == id { self.error = error.localizedDescription } - catch {} + if append { + let existing = Set(posts.map(\.id)) + posts += result.posts.filter { !existing.contains($0.id) } + next = result.next + } else if !refresh, displayedTerm == requested, !result.posts.isEmpty, + posts.count > result.posts.count, + posts.prefix(result.posts.count).map(\.id) == result.posts.map(\.id) { + posts.replaceSubrange(0.. 4000 { - Text("录入文字达到长度上限,请分开整理。").font(.footnote).foregroundStyle(.secondary) - } - if !text.isEmpty && draft == nil { - Button("生成物品草稿") { typing = false; Task { await parse() } } - .disabled(!canParse) - } - } + if !voice.transcript.isEmpty { + Text(voice.transcript).foregroundStyle(.secondary) } - if voice.phase == .idle, let draft { - Section("核对物品和位置") { - if draft.candidates.isEmpty { - Text(draft.status == "MODEL_UNAVAILABLE" - ? "AI 暂不可用。你可以再试一次,或手动添加物品。" - : "还没整理出物品。可以修改原话,或让 AI 整理较长的描述。") - .font(.footnote).foregroundStyle(.secondary) - Button("用 AI 整理") { typing = false; Task { await parse(source: "MODEL") } } - .disabled(!canParse) - } - ForEach(draft.candidates.indices, id: \.self) { index in - let candidate = draft.candidates[index] - if candidate.action == "SKIP" { - Text("\(candidate.name) · 跳过").foregroundStyle(.secondary) - } else { - VStack(alignment: .leading) { - Text("\(candidate.name) ×\(candidate.quantity ?? 1)") - if let hint = candidate.location, !hint.isEmpty { - Text("原话位置:\(hint)").font(.footnote).foregroundStyle(.secondary) - } - LocationPicker(store: store, - selection: Binding(get: { selections[index] }, set: { selections[index] = $0 }), - title: "存放位置", allowsClearing: true) - }.disabled(operation != nil) - } - } - if !draft.candidates.isEmpty { - Button("保存物品") { typing = false; Task { await submit(draft) } } - .disabled(busy || selections.isEmpty || operation != nil || voice.phase != .idle) - if selections.isEmpty { - Text("选好存放位置后就可以保存。").font(.footnote).foregroundStyle(.secondary) + if let error = voice.error { Text(error).font(.footnote).foregroundStyle(.secondary) } + DisclosureGroup("录音设置") { + Picker("录音方式", selection: $recordingMode) { + Text("点按开始,再点结束").tag(RecordingMode.tap) + Text("按住录音,松手结束").tag(RecordingMode.hold) + }.disabled(voice.phase != .idle) + } + } + if voice.phase == .idle { + Section("录入文字") { + TextEditor(text: $text) + .frame(minHeight: 88) + .focused($typing) + .accessibilityLabel("录入文字") + .disabled(busy || operation != nil) + .overlay(alignment: .topLeading) { + if text.isEmpty { + Text("录音转写会显示在这里,也可以直接输入。") + .foregroundStyle(.secondary) + .padding(.horizontal, 5) + .padding(.vertical, 8) + .allowsHitTesting(false) + .accessibilityHidden(true) } } + if text.utf16.count > 4000 { + Text("录入文字达到长度上限,请分开整理。").font(.footnote).foregroundStyle(.secondary) + } + if !text.isEmpty && draft == nil { + Button("生成物品草稿") { typing = false; Task { await parse() } } + .disabled(!canParse) } } - if let operation { - Section { - Text(statusText(operation.status)) - if operation.status == "COMPLETED" { - Button("继续录入") { reset(clearText: true) } - } else if ["FAILED", "REJECTED"].contains(operation.status) { - Button("返回核对") { reset(clearText: false) } - } else if operation.status == "NEEDS_REVIEW" { - Button("重试交付") { Task { await retry(operation) } }.disabled(busy) + } + if voice.phase == .idle, let draft { + Section("核对物品和位置") { + if draft.candidates.isEmpty { + Text(draft.status == "MODEL_UNAVAILABLE" + ? "AI 暂不可用。你可以再试一次,或手动添加物品。" + : "还没整理出物品。可以修改原话,或让 AI 整理较长的描述。") + .font(.footnote).foregroundStyle(.secondary) + Button("用 AI 整理") { typing = false; Task { await parse(source: "MODEL") } } + .disabled(!canParse) + } + ForEach(draft.candidates.indices, id: \.self) { index in + let candidate = draft.candidates[index] + if candidate.action == "SKIP" { + Text("\(candidate.name) · 跳过").foregroundStyle(.secondary) } else { - Button("刷新进度") { Task { await poll(operation) } }.disabled(busy) + VStack(alignment: .leading) { + Text("\(candidate.name) ×\(candidate.quantity ?? 1)") + if let hint = candidate.location, !hint.isEmpty { + Text("原话位置:\(hint)").font(.footnote).foregroundStyle(.secondary) + } + LocationPicker(store: store, + selection: Binding(get: { selections[index] }, set: { selections[index] = $0 }), + title: "存放位置", allowsClearing: true) + }.disabled(operation != nil) + } + } + if !draft.candidates.isEmpty { + Button("保存物品") { typing = false; Task { await submit(draft) } } + .disabled(busy || selections.isEmpty || operation != nil || voice.phase != .idle) + if selections.isEmpty { + Text("选好存放位置后就可以保存。").font(.footnote).foregroundStyle(.secondary) } } } - if busy { ProgressView() } - if let error { Text(error).foregroundStyle(.red) } } - .dismissibleKeyboard(active: typing) { typing = false } - .navigationTitle("录入") - .navigationBarTitleDisplayMode(.inline) - .toolbar { - ToolbarItem(placement: .topBarTrailing) { - Button { showingHelp = true } label: { Label("录入说明", systemImage: "questionmark.circle") } - .disabled(voice.phase != .idle) - } - } - .onDisappear { voice.cancel() } - .onChange(of: scenePhase) { _, phase in - if phase == .background { voice.cancel() } - } - .onChange(of: text) { _, updated in - if operation == nil && draft?.originalText != updated { - draft = nil - selections = [:] - } - } - .sheet(isPresented: $showingHelp) { - NavigationStack { - List { - Section("录音录入") { - Text("1. 点「开始录音」。也可以在设置里切换为按住说。") - Text("2. 说完点结束或松手。每次最多 25 秒,中间可以停顿。") - Text("3. 查看转写和草稿。可以修改文字,或点「用 AI 整理」。") - Text("4. 核对物品和存放位置,再点「保存物品」。") - } - Section("手动添加") { - Text("点「手动添加物品」,填写名称,选好存放位置再保存。") - } - } - .navigationTitle("怎么录入") - .navigationBarTitleDisplayMode(.inline) - .toolbar { - ToolbarItem(placement: .confirmationAction) { Button("完成") { showingHelp = false } } + if let operation { + Section { + Text(statusText(operation.status)) + if operation.status == "COMPLETED" { + Button("继续录入") { reset(clearText: true) } + } else if ["FAILED", "REJECTED"].contains(operation.status) { + Button("返回核对") { reset(clearText: false) } + } else if operation.status == "NEEDS_REVIEW" { + Button("重试交付") { Task { await retry(operation) } }.disabled(busy) + } else { + Button("刷新进度") { Task { await poll(operation) } }.disabled(busy) } } } - .sheet(isPresented: $showingAdd) { ItemEditor(store: store) } - } else { - ContentUnavailableView("当前空间只有查看权限", systemImage: "lock") - .navigationTitle("录入").navigationBarTitleDisplayMode(.inline) + if busy { ProgressView() } + if let error { Text(error).foregroundStyle(.red) } } + .dismissibleKeyboard(active: typing) { typing = false } + .navigationTitle("录入") + .navigationBarTitleDisplayMode(.inline) + .toolbar { + ToolbarItem(placement: .topBarTrailing) { + Button { showingHelp = true } label: { Label("录入说明", systemImage: "questionmark.circle") } + .disabled(voice.phase != .idle) + } + } + .onDisappear { voice.cancel() } + .onChange(of: scenePhase) { _, phase in + if phase == .background { voice.cancel() } + } + .onChange(of: text) { _, updated in + if operation == nil && draft?.originalText != updated { + draft = nil + selections = [:] + } + } + .sheet(isPresented: $showingHelp) { + NavigationStack { + List { + Section("录音录入") { + Text("1. 点「开始录音」。也可以在设置里切换为按住说。") + Text("2. 说完点结束或松手。每次最多 25 秒,中间可以停顿。") + Text("3. 查看转写和草稿。可以修改文字,或点「用 AI 整理」。") + Text("4. 核对物品和存放位置,再点「保存物品」。") + } + Section("手动添加") { + Text("点「手动添加物品」,填写名称,选好存放位置再保存。") + } + } + .navigationTitle("怎么录入") + .navigationBarTitleDisplayMode(.inline) + .toolbar { + ToolbarItem(placement: .confirmationAction) { Button("完成") { showingHelp = false } } + } + } + } + .sheet(isPresented: $showingAdd) { ItemEditor(store: store, initialLocation: initialLocation?.id) } + } else { + ContentUnavailableView("当前空间只有查看权限", systemImage: "lock") + .navigationTitle("录入").navigationBarTitleDisplayMode(.inline) } } @@ -273,7 +280,9 @@ struct IntakeView: View { } private func suggestedPlace(_ original: String?) -> Place? { - guard let original else { return nil } + guard let original, !original.trimmingCharacters(in: .whitespacesAndNewlines).isEmpty else { + return store.locations.first { $0.id == initialLocation?.id } + } func key(_ value: String) -> String { value.folding(options: [.caseInsensitive, .widthInsensitive], locale: Locale(identifier: "zh-CN")) .filter { !$0.isWhitespace && $0 != "/" } diff --git a/apps/ios/ItemAtlas/InventoryStore.swift b/apps/ios/ItemAtlas/InventoryStore.swift index 8e53f09..42c6365 100644 --- a/apps/ios/ItemAtlas/InventoryStore.swift +++ b/apps/ios/ItemAtlas/InventoryStore.swift @@ -103,7 +103,9 @@ enum PhotoTarget: Hashable { final class InventoryStore { let account: AtlasAccount let space: Space - private(set) var locations: [Place] = [] + private(set) var locations: [Place] + private(set) var locationsReady: Bool + private(set) var locationAccessLost = false private(set) var revision = 0 var root: String { "/api/households/\(space.id)" } var canWrite: Bool { space.canWrite } @@ -111,22 +113,54 @@ final class InventoryStore { init(account: AtlasAccount, space: Space) { self.account = account self.space = space + let preview: [Place]? = account.cached("/api/households/\(space.id)/locations") + locations = preview ?? [] + locationsReady = preview != nil } - func refreshLocations() async throws { - let updated: [Place] = try await get(root + "/locations") - try Task.checkCancellation() - locations = updated + func refreshLocations(refresh: Bool = false) async throws { + let requestedRevision = revision + do { + let updated: [Place] = try await account.read(root + "/locations", refresh: refresh) + guard revision == requestedRevision else { return } + locations = updated + locationsReady = true + locationAccessLost = false + } catch let error as AtlasError where error.resourceUnavailable { + guard revision == requestedRevision else { return } + locations = [] + locationsReady = false + locationAccessLost = true + account.invalidateReads(root + "/", discard: true) + throw error + } } - func search(_ query: String, favorites: Bool, location: UUID? = nil, offset: Int = 0) async throws -> [Item] { + func warm() async { + async let places: Void? = try? refreshLocations() + async let items: [Item]? = try? search("", favorites: false) + _ = await (places, items) + } + + func cachedItems(favorites: Bool, location: UUID? = nil) -> [Item]? { + account.cached(itemSearchPath("", favorites: favorites, location: location, offset: 0)) + } + + func search(_ query: String, favorites: Bool, location: UUID? = nil, offset: Int = 0, + refresh: Bool = false) async throws -> [Item] { + let path = itemSearchPath(query, favorites: favorites, location: location, offset: offset) + if query.isEmpty && offset == 0 { return try await account.read(path, refresh: refresh) } + let data = try await account.request(path, timeout: 12) + return try JSONDecoder().decode([Item].self, from: data) + } + + private func itemSearchPath(_ query: String, favorites: Bool, location: UUID?, offset: Int) -> String { var url = URLComponents() url.path = root + "/items" 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)) } - let data = try await account.request(url.string ?? root + "/items", timeout: 12) - return try JSONDecoder().decode([Item].self, from: data) + return url.string ?? root + "/items" } func get(_ path: String) async throws -> T { @@ -137,6 +171,7 @@ final class InventoryStore { idempotencyKey: UUID? = nil) async throws -> R { let response = try await account.request(path, method: method, data: JSONEncoder().encode(value), idempotencyKey: idempotencyKey) + if path.hasSuffix("/publication") { account.invalidateReads("/api/community/posts") } return try JSONDecoder().decode(R.self, from: response) } @@ -194,14 +229,31 @@ final class InventoryStore { changed() } - func image(target: PhotoTarget, photo: UUID, thumbnail: Bool) async throws -> Data { - try await account.request(root + target.path + "/\(photo)?thumbnail=\(thumbnail)") + func imagePath(target: PhotoTarget, photo: UUID, thumbnail: Bool) -> String { + root + target.path + "/\(photo)?thumbnail=\(thumbnail)" } - func delete(_ path: String) async throws { + func image(target: PhotoTarget, photo: UUID, thumbnail: Bool, refresh: Bool = false) async throws -> Data { + let path = imagePath(target: target, photo: photo, thumbnail: thumbnail) + if thumbnail { return try await account.readPreview(path, refresh: refresh) } + return try await account.request(path) + } + + func delete(_ path: String, affectsCommunity: Bool = false) async throws { _ = try await account.request(path, method: "DELETE") + let resource = path.components(separatedBy: "?")[0] + account.invalidateReads(resource, discard: true) + if resource == root { + account.invalidateReads("/api/households", discard: true) + } + if resource == root || resource.hasSuffix("/publication") || affectsCommunity { + account.invalidateReads("/api/community/posts", discard: true) + } changed() } - func changed() { revision += 1 } + func changed() { + account.invalidateReads(root + "/") + revision += 1 + } } diff --git a/apps/ios/ItemAtlas/InventoryView.swift b/apps/ios/ItemAtlas/InventoryView.swift index 35d3261..7f78e07 100644 --- a/apps/ios/ItemAtlas/InventoryView.swift +++ b/apps/ios/ItemAtlas/InventoryView.swift @@ -72,10 +72,16 @@ struct ItemListView: View { let store: InventoryStore var favoritesOnly = false @Environment(\.colorScheme) private var colorScheme - @State private var results = ItemListResults() + @State private var results: ItemListResults @State private var query = "" @FocusState private var searching: Bool + init(store: InventoryStore, favoritesOnly: Bool = false) { + self.store = store + self.favoritesOnly = favoritesOnly + _results = State(initialValue: ItemListResults(firstPage: store.cachedItems(favorites: favoritesOnly))) + } + var body: some View { VStack(spacing: 0) { HStack(spacing: 10) { @@ -106,7 +112,7 @@ struct ItemListView: View { .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) } + .refreshable { await results.load(store: store, query: query, favorites: favoritesOnly, refresh: true) } } } @@ -116,7 +122,6 @@ final class ItemListResults { struct LoadID: Hashable { let query: String let revision: Int - let retry: Int } private(set) var rows: [Item] = [] @@ -124,18 +129,27 @@ final class ItemListResults { private(set) var loadingMore = false private(set) var more = false private(set) var error: String? - private var retryCount = 0 - private var displayedQuery = "" + private(set) var displayedQuery: String? + private var displayedRevision: Int? private var activeRequest: UUID? - func loadID(query: String, revision: Int) -> LoadID { - LoadID(query: query.trimmingCharacters(in: .whitespacesAndNewlines), revision: revision, retry: retryCount) + init(firstPage: [Item]?) { + if let firstPage { showFirstPage(firstPage, query: "") } } - func retry() { retryCount += 1 } + private func showFirstPage(_ page: [Item], query: String) { + rows = page + more = page.count == 50 + displayedQuery = query + loading = false + } + + func loadID(query: String, revision: Int) -> LoadID { + LoadID(query: query.trimmingCharacters(in: .whitespacesAndNewlines), revision: revision) + } func load(store: InventoryStore, query: String = "", favorites: Bool = false, - location: UUID? = nil, append: Bool = false) async { + location: UUID? = nil, append: Bool = false, refresh: Bool = false) async { let input = query.trimmingCharacters(in: .whitespacesAndNewlines) guard !append || (more && !loading && !loadingMore && input == displayedQuery) else { return } let request = UUID() @@ -146,7 +160,10 @@ final class ItemListResults { loadingMore = true } else { loadingMore = false - loading = rows.isEmpty || displayedQuery != input + if displayedQuery != input, input.isEmpty, let cache = store.cachedItems(favorites: favorites, location: location) { + showFirstPage(cache, query: input) + } + loading = displayedQuery != input if loading { rows = []; more = false } } defer { @@ -158,18 +175,28 @@ final class ItemListResults { 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) + offset: append ? rows.count : 0, refresh: refresh) 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) } + more = page.count == 50 && rows.count <= 10000 + } else if !refresh, displayedRevision == revision, displayedQuery == input, + rows.count > page.count, page.count == 50, + rows.prefix(page.count).map(\.id) == page.map(\.id) { + rows.replaceSubrange(0.. 0) try Task.checkCancellation() image = UIImage(data: bytes) + displayed = photo error = image == nil - } catch where !Task.isCancelled { self.error = true } + } catch is CancellationError { + } catch where !Task.isCancelled { + if (error as? AtlasError)?.resourceUnavailable == true { image = nil } + self.error = true + } catch {} } } @@ -53,7 +63,7 @@ struct PhotoImage: View { struct PhotoGallery: View { let store: InventoryStore let target: PhotoTarget - @State private var photos: [Photo] = [] + @State private var photos: [Photo]? @State private var picker: PhotosPickerItem? @State private var crop: CropSource? @State private var cameraCrop: CropSource? @@ -62,10 +72,16 @@ struct PhotoGallery: View { @State private var busy = false @State private var error: String? + init(store: InventoryStore, target: PhotoTarget) { + self.store = store + self.target = target + _photos = State(initialValue: store.account.cached(store.root + target.path)) + } + var body: some View { Section(target.title) { VStack(alignment: .leading, spacing: 14) { - if !photos.isEmpty { + if let photos, !photos.isEmpty { ScrollView(.horizontal) { HStack { ForEach(photos) { photo in @@ -79,8 +95,8 @@ struct PhotoGallery: View { } } .scrollIndicators(.hidden) - } else { Text("暂无照片").foregroundStyle(.secondary) } - if store.canWrite && photos.count < 6 { + } else if photos != nil { Text("暂无照片").foregroundStyle(.secondary) } + if store.canWrite && (photos?.count ?? 0) < 6 { HStack(spacing: 20) { if UIImagePickerController.isSourceTypeAvailable(.camera) { Button { Task { await openCamera() } } label: { @@ -98,7 +114,7 @@ struct PhotoGallery: View { if busy { ProgressView() } if let error { Text(error).foregroundStyle(.red).font(.footnote) } if error != nil { - Button("刷新照片") { Task { await load() } }.buttonStyle(.borderless) + Button("刷新照片") { Task { await load(refresh: true) } }.buttonStyle(.borderless) } } .padding(.vertical, 4) @@ -158,13 +174,17 @@ struct PhotoGallery: View { showingCamera = true } - private func load() async { + private func load(refresh: Bool = false) async { do { - let updated: [Photo] = try await store.get(store.root + target.path) + let updated: [Photo] = try await store.account.read(store.root + target.path, refresh: refresh) try Task.checkCancellation() photos = updated error = nil - } catch where !Task.isCancelled { self.error = error.localizedDescription } + } catch is CancellationError { + } catch where !Task.isCancelled { + if (error as? AtlasError)?.resourceUnavailable == true { photos = nil } + self.error = error.localizedDescription + } catch {} } } diff --git a/apps/ios/ItemAtlas/LocationView.swift b/apps/ios/ItemAtlas/LocationView.swift index 72f379a..5eaddb5 100644 --- a/apps/ios/ItemAtlas/LocationView.swift +++ b/apps/ios/ItemAtlas/LocationView.swift @@ -11,21 +11,42 @@ private struct LocationContents: View { let store: InventoryStore let initialLocation: Place? @Environment(\.dismiss) private var dismiss - @State private var items = ItemListResults() + @State private var items: ItemListResults @State private var addingLocation = false @State private var editingLocation = false @State private var editingAppearance = false @State private var confirmingDelete = false @State private var error: String? - @State private var retry = 0 @State private var busy = false + init(store: InventoryStore, initialLocation: Place?) { + self.store = store + self.initialLocation = initialLocation + let preview = initialLocation.flatMap { store.cachedItems(favorites: false, location: $0.id) } + _items = State(initialValue: ItemListResults(firstPage: preview)) + } + private var location: Place? { - guard let initialLocation else { return nil } - return store.locations.first { $0.id == initialLocation.id } ?? initialLocation + guard let initialLocation, !store.locationAccessLost else { return nil } + if store.locationsReady { return store.locations.first { $0.id == initialLocation.id } } + return initialLocation } var body: some View { + Group { + if store.locationAccessLost || (initialLocation != nil && store.locationsReady && location == nil) { + ContentUnavailableView("位置不可用", systemImage: "archivebox", + description: Text("这个位置可能已被删除,或当前账号无法访问。")) + } else { + contents + } + } + .navigationTitle(location?.name ?? "位置") + .navigationBarTitleDisplayMode(.inline) + .task(id: store.revision) { await reloadLocations() } + } + + private var contents: some View { List { if let location { Section { @@ -42,8 +63,39 @@ private struct LocationContents: View { } .disabled(busy) } + } + if store.canWrite { + Section { + NavigationLink { + IntakeView(store: store, initialLocation: location) + } label: { + Label { + VStack(alignment: .leading, spacing: 4) { + Text(location == nil ? "录入物品" : "在这里录入") + .font(.headline) + .foregroundStyle(.primary) + Text("语音录入或手动添加") + .font(.subheadline) + .foregroundStyle(.secondary) + } + } icon: { + Image(systemName: "plus") + .font(.headline.weight(.semibold)) + .foregroundStyle(.white) + .frame(width: 37, height: 37) + .background(Color.atlasBlue, in: .rect(cornerRadius: 11)) + .accessibilityHidden(true) + } + .padding(.vertical, 5) + } + } + } + if let location { PhotoGallery(store: store, target: .location(location.id)) } + if !store.locationsReady && error == nil { + ProgressView("正在加载位置") + } Section(LocationLevel(depth: (location?.levelDepth ?? 0) + 1).title) { ForEach(store.locations.filter { $0.parentId == location?.id }) { child in NavigationLink { LocationContents(store: store, initialLocation: child) } label: { @@ -63,10 +115,11 @@ private struct LocationContents: View { 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 } } + if let error { + Text(error).foregroundStyle(.red) + Button("重试") { Task { await reloadLocations(refresh: true) } } + } } - .navigationTitle(location?.name ?? "位置") - .navigationBarTitleDisplayMode(.inline) .toolbar { if location != nil && store.canWrite { ToolbarItem(placement: .topBarTrailing) { @@ -77,17 +130,17 @@ private struct LocationContents: View { .task(id: items.loadID(query: "", revision: store.revision)) { if let location { await items.load(store: store, location: location.id) } } - .task(id: "\(retry):\(store.revision)") { - do { try await store.refreshLocations(); error = nil } - catch where !Task.isCancelled { self.error = error.localizedDescription } - catch {} + .refreshable { + async let places: Void = reloadLocations(refresh: true) + if let location { await items.load(store: store, location: location.id, refresh: true) } + await places } .sheet(isPresented: $addingLocation) { PlaceEditor(store: store, parent: location?.id) { _ in } } .sheet(isPresented: $editingLocation) { if let location { - PlaceEditor(store: store, existing: location) { _ in retry += 1 } + PlaceEditor(store: store, existing: location) { _ in } } } .sheet(isPresented: $editingAppearance) { @@ -110,6 +163,13 @@ private struct LocationContents: View { } } message: { Text("请先清空物品和子位置。删除这个位置时,里面的照片会一起删除。") } } + + private func reloadLocations(refresh: Bool = false) async { + do { try await store.refreshLocations(refresh: refresh); error = nil } + catch is CancellationError {} + catch where !Task.isCancelled { self.error = error.localizedDescription } + catch {} + } } struct PlaceEditor: View { diff --git a/apps/ios/ItemAtlas/MyView.swift b/apps/ios/ItemAtlas/MyView.swift index 4dd7446..2d1fecf 100644 --- a/apps/ios/ItemAtlas/MyView.swift +++ b/apps/ios/ItemAtlas/MyView.swift @@ -84,6 +84,13 @@ struct MyView: View { @State private var showingProfile = false @State private var confirmingSignOut = false + init(account: AtlasAccount, store: InventoryStore? = nil, openSpaces: @escaping () -> Void) { + self.account = account + self.store = store + self.openSpaces = openSpaces + _profile = State(initialValue: account.cached("/api/me/profile")) + } + var body: some View { List { Section { @@ -114,7 +121,7 @@ struct MyView: View { } if let profileError { Text(profileError).font(.footnote).foregroundStyle(.secondary) - Button("重新加载资料") { Task { await loadProfile() } } + Button("重新加载资料") { Task { await loadProfile(refresh: true) } } } } @@ -161,8 +168,8 @@ struct MyView: View { } .navigationTitle("我的") .navigationBarTitleDisplayMode(.inline) - .task { if profile == nil { await loadProfile() } } - .refreshable { await loadProfile() } + .task { await loadProfile() } + .refreshable { await loadProfile(refresh: true) } .sheet(isPresented: $showingProfile) { if let profile { ProfileEditor(account: account, profile: profile) { self.profile = $0 } @@ -173,13 +180,13 @@ struct MyView: View { } } - private func loadProfile() async { + private func loadProfile(refresh: Bool = false) async { do { - let data = try await account.request("/api/me/profile", timeout: 12) - try Task.checkCancellation() - profile = try JSONDecoder().decode(AccountProfile.self, from: data) + profile = try await account.read("/api/me/profile", refresh: refresh) profileError = nil + } catch is CancellationError { } catch where !Task.isCancelled { + if (error as? AtlasError)?.resourceUnavailable == true { profile = nil } profileError = "暂时无法加载账号资料。" } catch {} } @@ -260,6 +267,7 @@ private struct ProfileEditor: View { error = nil do { let data = try await account.request("/api/me/profile", method: "PUT", data: JSONEncoder().encode(update), timeout: 12) + account.invalidateReads("/api/me/profile", discard: true) saved(try JSONDecoder().decode(AccountProfile.self, from: data)) dismiss() } catch { self.error = error.localizedDescription } diff --git a/apps/ios/ItemAtlas/SessionReadCache.swift b/apps/ios/ItemAtlas/SessionReadCache.swift new file mode 100644 index 0000000..e4bf4c6 --- /dev/null +++ b/apps/ios/ItemAtlas/SessionReadCache.swift @@ -0,0 +1,71 @@ +import Foundation + +@MainActor +final class SessionReadCache { + private struct Entry { + let bytes: Data + let storedAt: ContinuousClock.Instant + var fresh: Bool + } + + private struct Request { + let task: Task + let id = UUID() + } + + private let clock = ContinuousClock() + private var entries: [String: Entry] = [:] + private var requests: [String: Request] = [:] + + func cached(_ path: String) -> Data? { + guard let entry = entries[path], entry.storedAt.duration(to: clock.now) < .seconds(300) else { return nil } + return entry.bytes + } + + func load(_ path: String, refresh: Bool, fetch: @escaping @MainActor () async throws -> Data) async throws -> Data { + try Task.checkCancellation() + if !refresh, let entry = entries[path], entry.fresh, + entry.storedAt.duration(to: clock.now) < .seconds(30) { return entry.bytes } + + let request: Request + if let pending = requests[path] { + request = pending + } else { + request = Request(task: Task { try await fetch() }) + requests[path] = request + } + let bytes: Data + do { + bytes = try await request.task.value + } catch { + if requests[path]?.id == request.id { requests[path] = nil } + throw error + } + // A write or sign-out can invalidate a request while its callers are suspended. + guard !request.task.isCancelled else { throw CancellationError() } + if requests[path]?.id == request.id { + requests[path] = nil + if bytes.count <= 128 * 1024 { + entries[path] = Entry(bytes: bytes, storedAt: clock.now, fresh: true) + if entries.count > 64, let oldest = entries.min(by: { $0.value.storedAt < $1.value.storedAt }) { + entries[oldest.key] = nil + } + } else { + entries[path] = nil + } + } + try Task.checkCancellation() + return bytes + } + + func discard(_ path: String) { entries[path] = nil } + + func invalidate(_ prefix: String, discard: Bool = false) { + for path in entries.keys.filter({ $0.hasPrefix(prefix) }) { + if discard { entries[path] = nil } else { entries[path]?.fresh = false } + } + for path in requests.keys.filter({ $0.hasPrefix(prefix) }) { + requests.removeValue(forKey: path)?.task.cancel() + } + } +} diff --git a/docs/architecture/clients.md b/docs/architecture/clients.md index 14b7745..67f89a0 100644 --- a/docs/architecture/clients.md +++ b/docs/architecture/clients.md @@ -16,4 +16,12 @@ H5 选 uni-app 是为了用贴合移动端的组件和构建方式。正式交 各端按自己的导航、拍照、录音及权限规范单独设计。iOS 在 SwiftUI 内提交账号密码,服务端按账号编号核对空间成员。Web 管理后台使用 Keycloak。签名和商店发布在准备分发时配置。 [SwiftUI](https://developer.apple.com/swiftui/) · [Jetpack Compose](https://developer.android.com/compose) +## iOS 首屏缓存 + +进入空间时并行准备找物首屏和位置树。社区首屏在登录后的空间列表期间已开始读取。列表和物品详情从当前会话的内存快照起步,物品首次打开也能先显示列表已有的名称、位置和数量。网络响应更新同一页面,空列表也是有效快照。 + +缓存键使用完整的 API 路径和查询参数。家庭数据按空间隔离。默认列表只缓存无搜索词的第一页,新的搜索和下一页按需请求。账号资料、已打开的详情、照片清单和小图也可复用。快照最近 30 秒可直接用于同一路径的普通读取,过期后再次读取会发起校验,下拉刷新可立即请求。进行中的同路径读取共用一次网络请求。缓存上限为 64 条,每条最多 128 KiB。超过五分钟的旧快照不用于新页面初始化。 + +相关写入会使快照失效并取消对应的进行中读取。退出登录清空该会话的缓存。读到无权访问或记录不存在时,相应页面清除旧内容。缓存留在进程内,重新启动从网络预读。后端鉴权和 HTTP 缓存策略均按原接口处理。 + [客户端工程目录](../../apps/README.md) · [产品需求](../product/requirements.md) · [部署与域名](../deployment/overview.md) diff --git a/docs/product/ios-experience.md b/docs/product/ios-experience.md index 50eb709..b91dd8b 100644 --- a/docs/product/ios-experience.md +++ b/docs/product/ios-experience.md @@ -4,7 +4,9 @@ 入口用「家里有的,心里有数。」和一张家里随手放东西的场景画。用一句实话演示见物的用途,例如「数据线放在书房抽屉」。下方直接进入自己的空间。首次使用时可以新建空空间,或在空间列表里接受家人的邀请。 -## 录音录入 +## 录入 + +底部依次是「找物」「位置」「社区」「我的」。「位置」顶部有「录入物品」。进入房间或子位置后,点「在这里录入」会带上当前的位置,手动添加时可以更改。语音草稿如果提到了其他位置,会按原话匹配,保存前可检查。 默认点「开始录音」,说完再点「结束录音」。也可以在「录音设置」选择按住说、松手结束。每次最多 25 秒,录音中能看到经过的秒数和文字。停顿后继续说,前面的转写留在这一段里。 @@ -16,8 +18,6 @@ 下面是当前空间、空间设置和切换空间。收藏在「我的收藏」里,按当前空间显示。切换空间后可以查看该空间的收藏。收藏列表为空时直接显示空状态,加载出错可以重试。退出登录放在页面底部。 -底部依次是找物、位置、录入、社区、我的。录入页右上角的问号保留四步说明。 - 找物页右上角显示当前空间。点开可看到可访问的空间和当前选中项,也可以进入完整的「我的空间」列表。 ## 位置图标和物品信息 @@ -42,7 +42,9 @@ ## 找物 -搜索框接收名称、别名和位置。完整名称优先于完整别名,再排前缀、包含和位置。结果优先露出位置路径。录入或改名后,搜索直接读到数据库提交的结果。 +搜索框接收名称、别名和位置。完整名称优先于完整别名,再排前缀、包含和位置。结果优先露出位置路径。录入或改名后,找物会重新请求最新结果。 + +进空间时会预读物品和位置,登录后也会预读社区。切回已经加载过的页面会先显示上一份列表,包括空列表。稍后收到新数据时再更新,也可以下拉立即刷新。 ## 社区 diff --git a/docs/testing/cases.md b/docs/testing/cases.md index 7a8f301..13cb8bc 100644 --- a/docs/testing/cases.md +++ b/docs/testing/cases.md @@ -41,5 +41,8 @@ R01–R10 对应[需求与验收](../product/requirements.md)。实现和当前 | TC-35 位置层级与个人图标 | R02、R09 | 建空间下五级位置。两个账号为同一个位置分别选择照片和预设图标。随后删除被选中的照片。 | 前三级与内层分组清楚。两人分别看到自己的设置。照片删除后,使用该照片的账号恢复空间默认,另一账号的图标保留。 | | TC-36 社区发布与搜索 | R10 | 新建物品后用另一账号搜索。所有者填写公开标题和描述后发布,分别搜索公开标题和私人位置名。 | 新建物品私有。发布后其他已登录账号可读,完整标题优先。家里的位置、物品记录和照片不随分享公开。 | | TC-37 社区互动与撤回 | R10 | 连续修改评分、发表和删除自己的评论。撤回分享,再重新发布并归档源物品。 | 同一账号在同一个帖子只计一次评分。撤回后原地址失效,重新发布没有旧互动,物品归档后新地址失效。 | +| TC-38 iOS 录入导航 | R03、R06 | 打开「位置」后点「录入物品」并返回。再进入一个房间,点「在这里录入」,打开手动添加。切到只读成员后检查入口。 | 底栏四项。录入从位置页进入,房间录入预填当前存放位置。只读成员无录入入口。 | +| TC-39 iOS 首屏和后台刷新 | 质量 | 登录后打开找物、位置与社区,来回切换,分别保留有内容和空列表。断网重进,再恢复网络并下拉刷新。 | 有快照时保留已显示的列表。刷新失败可以重试,恢复后更新数据。搜索词不同的结果不混用。 | +| TC-40 iOS 会话缓存隔离 | R01 | 加载空间 A 的数据,切到空间 B,再退出并换另一个账号。 | 家庭数据按所在空间读取,旧账号的内存快照已经清除。 | [测试与演示计划](plan.md) diff --git a/docs/ui/README.md b/docs/ui/README.md index 700e406..d50f5cc 100644 --- a/docs/ui/README.md +++ b/docs/ui/README.md @@ -9,7 +9,7 @@ - [iOS 整体方向稿](ios/design-overview.png) · [原生登录页设计稿](ios/native-sign-in.png) · [iOS 设计与交互](ios-welcome.md) - [低保真原型](wireframes.md) · [产品需求](../product/requirements.md) · [测试用例](../testing/cases.md) -找物列表采用小图和完整位置路径,柜子、收纳盒等末级位置加重显示。PC 左侧保留位置树,查看和移位可以在当前物品的详情里开始。草稿把待处理的内容放到最前面,用户仍可展开原话核对。录入按钮靠近移动端底部,待确认、可录入和跳过都用文字标明。 +找物列表采用小图和完整位置路径,柜子、收纳盒等末级位置加重显示。PC 左侧保留位置树,查看和移位可以在当前物品的详情里开始。草稿把待处理的内容放到最前面,用户仍可展开原话核对。iOS 将「录入物品」放在位置页顶部。进入房间或子位置后,入口改为「在这里录入」。待确认、可录入和跳过都用文字标明。 深蓝用于导航,亮蓝用于主操作和选中状态,琥珀色用于待确认。管理后台沿用动作和状态颜色,表格根据实际字段定密度。可编辑稿由 [HTML](concept.html)、[样式](concept.css) 和[物品示例图](assets/item-catalog.png)组成。