item-atlas/apps/ios/ItemAtlas/CommunityView.swift

755 lines
30 KiB
Swift

import SwiftUI
private struct CommunityPost: Decodable, Identifiable {
let id: UUID
let title: String
let body: String
let author: String
let authorId: UUID?
let authorAvatar: ProfileAvatar?
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 authorId: UUID?
let authorAvatar: ProfileAvatar?
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 PublicCommunityProfile: Decodable {
let name: String
let avatar: ProfileAvatar
let publishedItems: Int64
static func path(_ id: UUID) -> String { "/api/community/people/\(id)" }
}
private struct PublicAuthorLink: View {
let account: AtlasAccount
let name: String
let id: UUID?
let avatar: ProfileAvatar?
var body: some View {
if let id {
NavigationLink {
CommunityFeedView(account: account, publicAuthor: id)
} label: {
HStack(spacing: 6) {
AvatarBadge(avatar: avatar ?? .person, size: 23)
Text(name).lineLimit(1)
}
}
.buttonStyle(.borderless)
.accessibilityLabel("查看" + name + "的主页")
} else {
Text(name).lineLimit(1)
}
}
}
private struct CommunityAPI {
let account: AtlasAccount
static let posts = "/api/community/posts"
func load<T: Decodable>(_ 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))
}
static func feedPath(mine: Bool, author: UUID? = nil, 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 author { url.queryItems?.append(.init(name: "authorId", value: author.uuidString)) }
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<T: Encodable, R: Decodable>(_ 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
let publicAuthor: UUID?
@State private var query = ""
@State private var posts: [CommunityPost]
@State private var next: FeedCursor?
@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
@State private var publicProfile: PublicCommunityProfile?
@State private var profileError: String?
init(account: AtlasAccount, source: InventoryStore? = nil, mine: Bool = false, publicAuthor: UUID? = nil) {
self.account = account
self.source = source
self.mine = mine
self.publicAuthor = publicAuthor
_publicProfile = State(initialValue: publicAuthor.flatMap { account.cached(PublicCommunityProfile.path($0)) })
let preview: FeedResponse? = account.cached(CommunityAPI.feedPath(mine: mine, author: publicAuthor))
_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 publicAuthor != nil { profileHeader }
if displayedTerm != term && error == nil {
ProgressView("正在加载分享")
} else if posts.isEmpty && error == nil {
ContentUnavailableView {
Label(term.isEmpty ? "还没有分享" : "没找到相关分享", systemImage: "bubble.left.and.bubble.right")
} description: {
Text(emptyDescription)
} actions: {
if !term.isEmpty {
Button("清除搜索") { query = "" }.buttonStyle(.bordered)
} else if canPublish {
Button("发布物品") { showingChooser = true }.buttonStyle(.borderedProminent)
}
}
}
ForEach(displayedTerm == term ? posts : []) { post in
VStack(alignment: .leading, spacing: 10) {
NavigationLink {
CommunityDetailView(account: account, postID: post.id)
} label: {
VStack(alignment: .leading, spacing: 5) {
Text(post.title).font(.headline).foregroundStyle(.primary)
Text(post.body).font(.subheadline).foregroundStyle(.secondary).lineLimit(3)
}
.frame(maxWidth: .infinity, alignment: .leading)
.contentShape(Rectangle())
}
.buttonStyle(.plain)
HStack(spacing: 10) {
if publicAuthor == nil {
PublicAuthorLink(account: account, name: post.author, id: post.authorId, avatar: post.authorAvatar)
}
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("重试") { Task { await load(refresh: true) } }
}
} else if next != nil && displayedTerm == term {
Button(moreLoading ? "正在加载" : "更多分享") { Task { await load(append: true) } }
.disabled(moreLoading || updating)
}
}
.navigationTitle(publicAuthor != nil ? "社区主页" : (mine ? "我公开的物品" : "社区"))
.navigationBarTitleDisplayMode(.inline)
.searchable(text: $query, prompt: publicAuthor == nil ? "搜公开物品和分享" : "搜此人的公开物品")
.toolbar {
if canPublish {
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() }
.task(id: publicAuthor) { await loadProfile() }
.refreshable {
async let header: Void = loadProfile(refresh: true)
await load(refresh: true)
await header
}
}
private var canPublish: Bool { source?.space.role == "OWNER" && !mine && publicAuthor == nil }
private var emptyDescription: String {
if !term.isEmpty { return "试试其他关键词。" }
if mine { return "你公开的物品会显示在这里。" }
if publicAuthor != nil { return "这个主页会显示对方的公开分享。" }
return "可以搜索公开物品,或发布自己的使用感受。"
}
private var profileHeader: some View {
Section {
if let publicProfile {
HStack(spacing: 12) {
AvatarBadge(avatar: publicProfile.avatar, size: 50)
VStack(alignment: .leading, spacing: 4) {
Text(publicProfile.name).font(.headline)
Text("\(publicProfile.publishedItems) 件公开物品")
.font(.subheadline).foregroundStyle(.secondary)
}
}
.padding(.vertical, 6)
.accessibilityElement(children: .combine)
} else if let profileError {
Text(profileError).font(.footnote).foregroundStyle(.secondary)
Button("重载社区资料") { Task { await loadProfile(refresh: true) } }
} else {
ProgressView("正在加载社区资料")
}
}
}
private func loadProfile(refresh: Bool = false) async {
guard let publicAuthor else { return }
do {
publicProfile = try await account.read(PublicCommunityProfile.path(publicAuthor), refresh: refresh)
profileError = nil
} catch is CancellationError {
} catch where !Task.isCancelled {
if (error as? AtlasError)?.resourceUnavailable == true { publicProfile = nil }
profileError = error.localizedDescription
} catch {}
}
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
updating = !append
moreLoading = append
let firstPage = !append && requested.isEmpty
let path = CommunityAPI.feedPath(mine: mine, author: publicAuthor, 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 { updating = false; moreLoading = false }
}
do {
if !append && !requested.isEmpty { try await Task.sleep(for: .milliseconds(250)) }
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)
}
try Task.checkCancellation()
guard requestID == id, term == requested else { return }
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..<result.posts.count, with: result.posts)
} else {
posts = result.posts
next = result.next
}
displayedTerm = requested
} catch is CancellationError {
} catch where !Task.isCancelled && requestID == id {
if (error as? AtlasError)?.resourceUnavailable == true {
posts = []
next = nil
displayedTerm = nil
}
self.error = error.localizedDescription
} catch {}
}
}
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)" }
init(account: AtlasAccount, postID: UUID) {
self.account = account
self.postID = postID
let path = CommunityAPI.posts + "/\(postID)"
_post = State(initialValue: account.cached(path))
let preview: CommentResponse? = account.cached(path + "/comments")
_comments = State(initialValue: preview?.comments ?? [])
_next = State(initialValue: preview?.next)
}
var body: some View {
List {
if let post {
Section {
VStack(alignment: .leading, spacing: 10) {
Text(post.title).font(.title2.bold())
HStack(spacing: 8) {
PublicAuthorLink(account: account, name: post.author, id: post.authorId, avatar: post.authorAvatar)
Text(post.publishedAt.prefix(10))
}
.font(.footnote).foregroundStyle(.secondary)
Text(post.body).textSelection(.enabled)
}.padding(.vertical, 5)
}
Section("评分") {
Label(post.ratingText, systemImage: "star").foregroundStyle(.secondary)
HStack(spacing: 3) {
ForEach(1...5, id: \.self) { stars in
Button { Task { await rate(stars) } } label: {
Image(systemName: stars <= (post.myRating ?? 0) ? "star.fill" : "star")
.font(.title3)
.foregroundStyle(Color.orange)
.frame(maxWidth: .infinity, minHeight: 44)
.contentShape(Rectangle())
}
.buttonStyle(.borderless)
.accessibilityLabel("评 \(stars) 星")
.accessibilityAddTraits(post.myRating == stars ? .isSelected : [])
}
}
.disabled(busy)
if post.myRating != nil {
Button("清除我的评分") { Task { await rate(nil) } }.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)
if comments.isEmpty && !busy {
Text("还没有评论").font(.subheadline).foregroundStyle(.secondary)
}
ForEach(comments) { comment in
VStack(alignment: .leading, spacing: 6) {
PublicAuthorLink(account: account, name: comment.author, id: comment.authorId, avatar: comment.authorAvatar)
.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(refresh: true) } }
}
}
}
.navigationTitle("物品分享")
.navigationBarTitleDisplayMode(.inline)
.dismissibleKeyboard(active: typing) { typing = false }
.task { await load() }
.refreshable { await load(refresh: true) }
}
private func load(refresh: Bool = false) async {
await perform {
do {
async let listing: CommentResponse = account.read(path + "/comments", refresh: refresh)
let result: CommunityPost = try await account.read(path, refresh: refresh)
try Task.checkCancellation()
post = result
let listed = try await listing
try Task.checkCancellation()
comments = listed.comments
next = listed.next
} catch let error as AtlasError where error.resourceUnavailable {
post = nil
comments = []
next = nil
account.invalidateReads(CommunityAPI.posts, discard: true)
throw error
}
}
}
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
account.invalidateReads(CommunityAPI.posts)
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
account.invalidateReads(CommunityAPI.posts)
}
}
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))
account.invalidateReads(CommunityAPI.posts)
}
}
private func perform(_ action: () async throws -> Void) async {
guard !busy else { return }
busy = true
error = nil
defer { busy = false }
do { try await action() }
catch is CancellationError {}
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 showingIntake = false
@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
private var term: String { query.trimmingCharacters(in: .whitespacesAndNewlines) }
var body: some View {
NavigationStack {
if showingIntake {
IntakeView(store: store, onReturnToChooser: {
loading = true
showingIntake = false
})
} else {
chooser
}
}
}
private var chooser: some View {
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 {
emptyState
} 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):\(term)") { await load() }
.sheet(item: $selected) { item in
PublicationEditor(store: store, item: item) {
revision += 1
onChange()
}
}
}
private var emptyState: some View {
ContentUnavailableView {
Label(term.isEmpty ? "没有可选物品" : "没找到物品", systemImage: "archivebox")
} description: {
Text(term.isEmpty ? "录入一件物品,就可以回来选它。" : "换个名字或别名试试。")
} actions: {
if term.isEmpty && store.canWrite {
Button("录入物品") { showingIntake = true }.buttonStyle(.borderedProminent)
} else if !term.isEmpty {
Button("清除搜索") { query = "" }.buttonStyle(.bordered)
}
}
}
private func load(append: Bool = false) async {
guard !append || !loading else { return }
let id = UUID()
generation = id
let requested = term
if !append { items = []; hasMore = false }
loading = true
error = nil
defer { if generation == id { loading = false } }
do {
if !append && !requested.isEmpty { try await Task.sleep(for: .milliseconds(250)) }
let page = try await store.search(requested, favorites: false, offset: append ? items.count : 0)
try Task.checkCancellation()
guard generation == id, term == requested 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" || item.communityPostId != nil {
Section("社区分享") {
if let postId = item.communityPostId {
NavigationLink {
CommunityDetailView(account: store.account, postID: postId)
} label: {
Label("查看社区评论和评分", systemImage: "bubble.left.and.bubble.right")
}
}
if store.space.role == "OWNER" {
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(inventorySummaryChanged: true)
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 {}
}
}