import SwiftUI private struct CommunityPost: Decodable, Identifiable { let id: UUID let title: String let body: String let author: String let publishedAt: String let average: Double? let votes: Int let myRating: Int? var comments: Int var ratingText: String { if let average { return average.formatted(.number.precision(.fractionLength(1))) + " · \(votes) 人评分" } return "暂无评分" } } private struct FeedCursor: Decodable { let rank: Int let time: String let id: UUID } private struct FeedResponse: Decodable { let posts: [CommunityPost] let next: FeedCursor? } private struct CommunityComment: Decodable, Identifiable { let id: UUID let body: String let author: String let mine: Bool let createdAt: String } private struct CommentResponse: Decodable { struct Cursor: Decodable { let time: String; let id: UUID } let comments: [CommunityComment] let next: Cursor? } private struct CommunityAPI { let account: AtlasAccount static let posts = "/api/community/posts" func load(_ path: String, query: [URLQueryItem] = []) async throws -> T { var url = URLComponents() url.path = path if !query.isEmpty { url.queryItems = query } return try JSONDecoder().decode(T.self, from: await account.request(url.string ?? path, timeout: 12)) } 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) } } struct CommunityFeedView: View { let account: AtlasAccount var source: InventoryStore? = nil var mine = false @State private var query = "" @State private var posts: [CommunityPost] = [] @State private var next: FeedCursor? @State private var loading = true @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 private var term: String { query.trimmingCharacters(in: .whitespacesAndNewlines) } var body: some View { List { if loading { ProgressView("正在加载分享") } else if posts.isEmpty && error == nil { ContentUnavailableView(term.isEmpty ? "还没有分享" : "没找到相关分享", systemImage: "bubble.left.and.bubble.right", description: Text(mine ? "你公开的物品会显示在这里。" : "可以搜索公开物品,或发布自己的使用感受。")) } ForEach(posts) { post in NavigationLink { CommunityDetailView(account: account, postID: post.id) } label: { VStack(alignment: .leading, spacing: 9) { Text(post.title).font(.headline) Text(post.body).font(.subheadline).foregroundStyle(.secondary).lineLimit(3) HStack(spacing: 12) { Text(post.author).lineLimit(1) Spacer(minLength: 0) Label(post.ratingText, systemImage: "star") Label(String(post.comments), systemImage: "bubble") } .font(.caption).foregroundStyle(.secondary) } .padding(.vertical, 5) } } if let error { Section { Text(error).font(.footnote).foregroundStyle(.red) Button("重试") { revision += 1 } } } else if next != nil { Button(moreLoading ? "正在加载" : "更多分享") { Task { await load(append: true) } } .disabled(moreLoading || loading) } } .navigationTitle(mine ? "我公开的物品" : "社区") .navigationBarTitleDisplayMode(.inline) .searchable(text: $query, prompt: "搜公开物品和分享") .toolbar { if let source, source.space.role == "OWNER" && !mine { ToolbarItem(placement: .topBarTrailing) { Button { showingChooser = true } label: { Label("发布物品", systemImage: "square.and.pencil") } } } } .sheet(isPresented: $showingChooser) { if let source { CommunityItemChooser(store: source) { revision += 1 } } } .task(id: "\(revision):\(source?.revision ?? 0):\(term)") { await load() } .refreshable { await load() } } private func load(append: Bool = false) async { let cursor = append ? next : nil guard !append || (cursor != nil && !loading && !moreLoading) else { return } let requested = term let id = UUID() requestID = id error = nil loading = !append moreLoading = append if !append { next = nil; posts = [] } defer { if requestID == id { loading = 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 = 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 {} } } private struct CommunityDetailView: View { let account: AtlasAccount let postID: UUID @State private var post: CommunityPost? @State private var comments: [CommunityComment] = [] @State private var next: CommentResponse.Cursor? @State private var draft = "" @State private var error: String? @State private var busy = false @FocusState private var typing: Bool private var api: CommunityAPI { CommunityAPI(account: account) } private var path: String { CommunityAPI.posts + "/\(postID)" } var body: some View { List { if let post { Section { VStack(alignment: .leading, spacing: 10) { Text(post.title).font(.title2.bold()) Text(post.author + " · " + String(post.publishedAt.prefix(10))) .font(.footnote).foregroundStyle(.secondary) Text(post.body).textSelection(.enabled) }.padding(.vertical, 5) } Section("评分") { Label(post.ratingText, systemImage: "star").foregroundStyle(.secondary) Picker("我的评分", selection: Binding(get: { self.post?.myRating ?? 0 }, set: { stars in Task { await rate(stars == 0 ? nil : stars) } })) { Text("未评分").tag(0) ForEach(1...5, id: \.self) { Text("\($0) 星").tag($0) } }.disabled(busy) } Section("评论") { TextField("说说你的看法", text: $draft, axis: .vertical).focused($typing) Button("发表评论") { typing = false; Task { await sendComment() } } .disabled(busy || draft.utf16.count > 500 || draft.trimmingCharacters(in: .whitespacesAndNewlines).isEmpty) ForEach(comments) { comment in VStack(alignment: .leading, spacing: 6) { Text(comment.author).font(.subheadline.weight(.semibold)) Text(comment.body) Text(comment.createdAt.prefix(10)).font(.caption).foregroundStyle(.secondary) } .swipeActions { if comment.mine { Button("删除", role: .destructive) { Task { await deleteComment(comment) } } } } } if next != nil { Button("更多评论") { Task { await loadMore() } }.disabled(busy) } } } else if error == nil { ProgressView("正在打开分享") } if let error { Section { Text(error).font(.footnote).foregroundStyle(.red) Button("重新加载") { Task { await load() } } } } } .navigationTitle("物品分享") .navigationBarTitleDisplayMode(.inline) .dismissibleKeyboard(active: typing) { typing = false } .task { await load() } .refreshable { await load() } } private func load() async { await perform { post = nil comments = [] next = nil let result: CommunityPost = try await api.load(path) let listed: CommentResponse = try await api.load(path + "/comments") try Task.checkCancellation() post = result comments = listed.comments next = listed.next } } private func loadMore() async { guard let next else { return } await perform { let page: CommentResponse = try await api.load(path + "/comments", query: [ .init(name: "time", value: next.time), .init(name: "before", value: next.id.uuidString) ]) let existing = Set(comments.map(\.id)) comments += page.comments.filter { !existing.contains($0.id) } self.next = page.next } } private func sendComment() async { struct Input: Encodable { let body: String } let text = draft await perform { let comment: CommunityComment = try await api.send(path + "/comments", method: "POST", Input(body: text)) comments.insert(comment, at: 0) post?.comments += 1 if draft == text { draft = "" } } } private func deleteComment(_ comment: CommunityComment) async { await perform { _ = try await account.request(path + "/comments/\(comment.id)", method: "DELETE", timeout: 12) comments.removeAll { $0.id == comment.id } post?.comments -= 1 } } private func rate(_ stars: Int?) async { struct Input: Encodable { let stars: Int? } await perform { post = try await api.send(path + "/rating", method: "PUT", Input(stars: stars)) } } private func perform(_ action: () async throws -> Void) async { guard !busy else { return } busy = true error = nil defer { busy = false } do { try await action() } catch where !Task.isCancelled { self.error = error.localizedDescription } catch {} } } private struct CommunityItemChooser: View { let store: InventoryStore let onChange: () -> Void @Environment(\.dismiss) private var dismiss @State private var query = "" @State private var items: [Item] = [] @State private var selected: Item? @State private var loading = true @State private var hasMore = false @State private var error: String? @State private var generation = UUID() @State private var revision = 0 var body: some View { NavigationStack { List { if loading && items.isEmpty { ProgressView("正在查找物品") } ForEach(items) { item in Button { selected = item } label: { HStack { Text(item.name).foregroundStyle(.primary) Spacer() if item.published == true { Text("已公开").font(.caption).foregroundStyle(.secondary) } } } } if let error { Text(error).font(.footnote).foregroundStyle(.red) Button("重新加载") { revision += 1 } } else if !loading && items.isEmpty { ContentUnavailableView("没有可选物品", systemImage: "archivebox") } else if hasMore { Button("更多物品") { Task { await load(append: true) } }.disabled(loading) } } .navigationTitle("选择要分享的物品") .navigationBarTitleDisplayMode(.inline) .searchable(text: $query, prompt: "搜当前空间里的物品") .toolbar { ToolbarItem(placement: .cancellationAction) { Button("完成") { dismiss() } } } .task(id: "\(revision):\(query)") { await load() } .sheet(item: $selected) { item in PublicationEditor(store: store, item: item) { revision += 1 onChange() } } } } private func load(append: Bool = false) async { guard !append || !loading else { return } let id = UUID() generation = id let term = query if !append { items = []; hasMore = false } loading = true error = nil defer { if generation == id { loading = false } } do { if !append && !term.isEmpty { try await Task.sleep(for: .milliseconds(250)) } let page = try await store.search(term, favorites: false, offset: append ? items.count : 0) try Task.checkCancellation() guard generation == id, query == term else { return } items += page hasMore = page.count == 50 } catch where !Task.isCancelled && generation == id { self.error = error.localizedDescription } catch {} } } struct CommunityPublicationSection: View { let store: InventoryStore let item: Item @State private var editing = false var body: some View { if store.space.role == "OWNER" { Section("社区分享") { Button { editing = true } label: { LabeledContent(item.published == true ? "管理分享" : "分享到社区", value: item.published == true ? "已公开" : "私有") } } .sheet(isPresented: $editing) { PublicationEditor(store: store, item: item) {} } } } } private struct PublicationEditor: View { private struct Publication: Decodable { let postId: UUID? let title: String let body: String } private struct Draft: Encodable { var title: String var body = "" var isValid: Bool { !title.trimmingCharacters(in: .whitespacesAndNewlines).isEmpty && title.utf16.count <= 120 && !body.trimmingCharacters(in: .whitespacesAndNewlines).isEmpty && body.utf16.count <= 2000 } } let store: InventoryStore let item: Item let onChange: () -> Void @Environment(\.dismiss) private var dismiss @FocusState private var typing: Bool @State private var draft: Draft @State private var publication: Publication? @State private var busy = false @State private var confirmingPublish = false @State private var confirmingWithdrawal = false @State private var error: String? init(store: InventoryStore, item: Item, onChange: @escaping () -> Void) { self.store = store self.item = item self.onChange = onChange _draft = State(initialValue: Draft(title: String(item.name.prefix(120)))) } private var path: String { store.itemPath(item.id) + "/publication" } private var published: Bool { publication?.postId != nil } var body: some View { NavigationStack { Form { Section { if publication != nil { TextField("公开标题", text: $draft.title).focused($typing) TextField("物品怎么样?写下你的使用感受", text: $draft.body, axis: .vertical) .lineLimit(4...10).focused($typing) } else if error == nil { ProgressView("正在加载分享") } } footer: { Text("登录用户可以看到这里填写的标题和内容。发出前请检查有没有住址、联系方式或其他私人信息。") } if let error { Section { Text(error).font(.footnote).foregroundStyle(.red) if publication == nil { Button("重试") { Task { await load() } } } } } if published { Section { Button("撤回分享", role: .destructive) { typing = false; confirmingWithdrawal = true } .disabled(busy) } } } .navigationTitle(published ? "编辑社区分享" : "分享到社区") .navigationBarTitleDisplayMode(.inline) .dismissibleKeyboard(active: typing) { typing = false } .toolbar { ToolbarItem(placement: .cancellationAction) { Button("关闭") { dismiss() }.disabled(busy) } ToolbarItem(placement: .confirmationAction) { Button(published ? "保存" : "发布") { typing = false if published { Task { await save() } } else { confirmingPublish = true } }.disabled(publication == nil || busy || !draft.isValid) } } .confirmationDialog("公开这条分享?", isPresented: $confirmingPublish, titleVisibility: .visible) { Button("确认公开") { Task { await save() } } } message: { Text("这条分享会显示在社区和搜索结果中。") } .confirmationDialog("撤回这条分享?", isPresented: $confirmingWithdrawal, titleVisibility: .visible) { Button("撤回", role: .destructive) { Task { await withdraw() } } } message: { Text("社区里的评论和评分也会删除。你的空间里会保留这件物品。") } .task { await load() } } .interactiveDismissDisabled(busy) } private func load() async { await perform { let response: Publication = try await store.get(path) try Task.checkCancellation() if response.postId != nil { draft = Draft(title: response.title, body: response.body) } publication = response } } private func save() async { guard draft.isValid else { return } await perform { let _: Publication = try await store.send(path, method: "PUT", draft) store.changed() onChange() dismiss() } } private func withdraw() async { await perform { try await store.delete(path) onChange() dismiss() } } private func perform(_ action: () async throws -> Void) async { guard !busy else { return } busy = true error = nil defer { busy = false } do { try await action() } catch where !Task.isCancelled { self.error = error.localizedDescription } catch {} } }