feat(creator): 커뮤니티 게시글 상세를 연결한다

This commit is contained in:
Yu Sung
2026-07-08 01:56:57 +09:00
parent f2d589eca2
commit c0369e6f58
23 changed files with 2187 additions and 138 deletions

View File

@@ -0,0 +1,51 @@
import SwiftUI
struct CreatorChannelCommunityPostDetailCommentListView: View {
let creatorId: Int
let postId: Int
let commentCount: Int
let comments: [CreatorChannelCommunityCommentResponse]
let selectedComment: CreatorChannelCommunityCommentResponse?
let canEdit: (CreatorChannelCommunityCommentResponse) -> Bool
let canDelete: (CreatorChannelCommunityCommentResponse) -> Bool
let onAppearComment: (CreatorChannelCommunityCommentResponse) -> Void
let onTapReplyDetail: (CreatorChannelCommunityCommentResponse) -> Void
let onTapMore: (CreatorChannelCommunityCommentResponse) -> Void
let onTapEdit: (CreatorChannelCommunityCommentResponse) -> Void
let onTapDelete: (CreatorChannelCommunityCommentResponse) -> Void
var body: some View {
VStack(alignment: .leading, spacing: SodaSpacing.s16) {
Text("댓글 \(commentCount)")
.appFont(size: 16, weight: .medium)
.foregroundColor(.white)
.padding(.horizontal, SodaSpacing.s14)
LazyVStack(alignment: .leading, spacing: SodaSpacing.s20) {
ForEach(comments, id: \.commentId) { comment in
ZStack(alignment: .topTrailing) {
CreatorChannelCommunityPostDetailCommentRow(
comment: comment,
creatorId: creatorId,
onTapReplyDetail: { onTapReplyDetail(comment) },
onTapMore: { onTapMore(comment) }
)
if selectedComment?.commentId == comment.commentId {
CreatorChannelActionPopup(
canEdit: canEdit(comment),
canDelete: canDelete(comment),
onTapEdit: { onTapEdit(comment) },
onTapDelete: { onTapDelete(comment) }
)
.padding(.top, 28)
}
}
.onAppear { onAppearComment(comment) }
}
}
.padding(.horizontal, SodaSpacing.s14)
}
.padding(.vertical, SodaSpacing.s20)
}
}

View File

@@ -0,0 +1,134 @@
import SwiftUI
struct CreatorChannelCommunityPostDetailCommentRow: View {
let comment: CreatorChannelCommunityCommentResponse
let creatorId: Int
let onTapReplyDetail: () -> Void
let onTapMore: () -> Void
private var currentUserId: Int { UserDefaults.int(forKey: .userId) }
var body: some View {
Button(action: onTapReplyDetail) {
VStack(alignment: .leading, spacing: SodaSpacing.s12) {
HStack(alignment: .top, spacing: SodaSpacing.s8) {
DownsampledKFImage(url: URL(string: comment.writerProfileImageUrl), size: CGSize(width: 42, height: 42))
.background(Color.gray800)
.clipShape(Circle())
.frame(width: 42, height: 42)
VStack(alignment: .leading, spacing: SodaSpacing.s8) {
header
Text(comment.content)
.appFont(size: 16, weight: .regular)
.foregroundColor(.white)
.fixedSize(horizontal: false, vertical: true)
.frame(maxWidth: .infinity, alignment: .leading)
}
}
if let latestReply = comment.latestReply {
latestReplyCard(latestReply)
.padding(.leading, 50)
.background(alignment: .leading) {
CreatorChannelCommunityPostDetailReplyConnector()
.stroke(Color.gray800, style: StrokeStyle(lineWidth: 2, lineCap: .round, lineJoin: .round))
.frame(width: 42)
.padding(.leading, 20)
}
}
}
.frame(maxWidth: .infinity, alignment: .leading)
.contentShape(Rectangle())
}
.buttonStyle(.plain)
}
private var header: some View {
HStack(spacing: SodaSpacing.s8) {
Text(comment.writerNickname)
.appFont(size: 14, weight: .medium)
.foregroundColor(.white)
.lineLimit(1)
Text(comment.relativeTimeText())
.appFont(size: 14, weight: .regular)
.foregroundColor(Color.gray500)
.lineLimit(1)
if comment.isSecret {
Text(I18n.Explorer.secretComment)
.appFont(size: 11, weight: .medium)
.foregroundColor(Color.grayee)
.padding(.horizontal, 4)
.padding(.vertical, 2)
.background(Color.soda400.opacity(0.2))
.cornerRadius(3)
}
Spacer(minLength: 0)
if showsMoreButton {
Button(action: onTapMore) {
Image("ic_new_more")
.resizable()
.frame(width: 24, height: 24)
}
.buttonStyle(.plain)
}
}
}
private func latestReplyCard(_ latestReply: CreatorChannelCommunityReplyResponse) -> some View {
VStack(alignment: .leading, spacing: SodaSpacing.s8) {
HStack(spacing: SodaSpacing.s8) {
DownsampledKFImage(url: URL(string: latestReply.writerProfileImageUrl), size: CGSize(width: 20, height: 20))
.background(Color.gray800)
.clipShape(Circle())
.frame(width: 20, height: 20)
Text(latestReply.writerNickname)
.appFont(size: 13, weight: .medium)
.foregroundColor(.white)
.lineLimit(1)
Text(latestReply.relativeTimeText())
.appFont(size: 14, weight: .regular)
.foregroundColor(Color.gray500)
.lineLimit(1)
Spacer(minLength: 0)
}
Text(latestReply.content)
.appFont(size: 16, weight: .regular)
.foregroundColor(.white)
.fixedSize(horizontal: false, vertical: true)
.frame(maxWidth: .infinity, alignment: .leading)
}
.padding(SodaSpacing.s12)
.frame(maxWidth: .infinity, alignment: .leading)
.background(Color.gray900)
.clipShape(RoundedRectangle(cornerRadius: SodaSpacing.s14, style: .continuous))
}
private var showsMoreButton: Bool {
comment.writerId == currentUserId || creatorId == currentUserId
}
}
private struct CreatorChannelCommunityPostDetailReplyConnector: Shape {
func path(in rect: CGRect) -> Path {
var path = Path()
let startX: CGFloat = 0
let endX: CGFloat = rect.width
let endY = rect.height - 8
let bendY = max(0, endY - 14)
path.move(to: CGPoint(x: startX, y: 0))
path.addLine(to: CGPoint(x: startX, y: bendY))
path.addQuadCurve(to: CGPoint(x: endX, y: endY), control: CGPoint(x: startX, y: endY))
return path
}
}

View File

@@ -0,0 +1,194 @@
import SwiftUI
import SDWebImageSwiftUI
struct CreatorChannelCommunityPostDetailContentView: View {
let detail: CreatorChannelCommunityPostDetailResponse
let onTapLike: () -> Void
let onTapPurchase: () -> Void
@StateObject private var playManager = CreatorCommunityMediaPlayerManager.shared
@StateObject private var contentPlayManager = ContentPlayManager.shared
var body: some View {
VStack(alignment: .leading, spacing: SodaSpacing.s16) {
if detail.isPinned {
pinnedLabel
}
header
Text(detail.content)
.appFont(size: 16, weight: .regular)
.foregroundColor(.white)
.fixedSize(horizontal: false, vertical: true)
.frame(maxWidth: .infinity, alignment: .leading)
mediaContent
reactionBar
}
.padding(SodaSpacing.s14)
.frame(maxWidth: .infinity, alignment: .leading)
.background(Color.black)
}
private var pinnedLabel: some View {
HStack(spacing: 2) {
Image("ic_pin")
.resizable()
.scaledToFit()
.frame(width: 18, height: 18)
Text("Notice")
.appFont(size: 14, weight: .medium)
.foregroundColor(Color(hex: "73FF01"))
}
}
private var header: some View {
HStack(spacing: SodaSpacing.s8) {
DownsampledKFImage(url: URL(string: detail.creatorProfileUrl), size: CGSize(width: 42, height: 42))
.background(Color.gray800)
.clipShape(Circle())
.frame(width: 42, height: 42)
VStack(alignment: .leading, spacing: 2) {
Text(detail.creatorNickname)
.appFont(size: 14, weight: .medium)
.foregroundColor(.white)
.lineLimit(1)
Text(detail.relativeTimeText())
.appFont(size: 14, weight: .regular)
.foregroundColor(Color.gray500)
.lineLimit(1)
}
Spacer(minLength: 0)
if detail.price > 0 && detail.existOrdered && isOwnPost == false {
purchaseCompleteTag
}
}
}
@ViewBuilder
private var mediaContent: some View {
if isPaidLocked {
Button(action: onTapPurchase) {
RoundedRectangle(cornerRadius: SodaSpacing.s14, style: .continuous)
.fill(Color.gray800)
.frame(maxWidth: .infinity)
.frame(height: 236)
.overlay(paidLockedOverlay)
}
.buttonStyle(.plain)
} else if let imageUrl = detail.imageUrl, imageUrl.isEmpty == false {
ZStack {
WebImage(url: URL(string: imageUrl))
.resizable()
.scaledToFit()
.frame(maxWidth: .infinity)
.background(Color.gray800)
audioPlayButton
}
.frame(maxWidth: .infinity)
.clipShape(RoundedRectangle(cornerRadius: SodaSpacing.s14, style: .continuous))
} else if detail.audioUrl?.isEmpty == false {
RoundedRectangle(cornerRadius: SodaSpacing.s14, style: .continuous)
.fill(Color.gray900)
.frame(maxWidth: .infinity)
.frame(height: 132)
.overlay(audioPlayButton)
}
}
@ViewBuilder
private var audioPlayButton: some View {
if let audioUrl = detail.audioUrl, audioUrl.isEmpty == false {
Button {
contentPlayManager.pauseAudio()
playManager.toggleContent(item: CreatorCommunityContentItem(contentId: detail.postId, url: audioUrl))
} label: {
Image(playManager.isPlaying && playManager.currentPlayingContentId == detail.postId ? "btn_audio_content_pause" : "btn_audio_content_play")
.resizable()
.frame(width: 48, height: 48)
}
.buttonStyle(.plain)
}
}
private var paidLockedOverlay: some View {
VStack(spacing: SodaSpacing.s4) {
Image("ic_new_community_lock")
.resizable()
.renderingMode(.template)
.foregroundColor(.white)
.frame(width: 24, height: 24)
HStack(spacing: SodaSpacing.s6) {
Image("ic_bar_cash")
.resizable()
.frame(width: 20, height: 20)
Text("\(detail.price)")
.appFont(size: 16, weight: .medium)
.foregroundColor(Color.black)
}
.padding(SodaSpacing.s8)
.background(Color.white)
.clipShape(Capsule())
}
}
private var purchaseCompleteTag: some View {
Text("구매완료")
.appFont(size: 12, weight: .medium)
.foregroundColor(Color.black)
.padding(.horizontal, SodaSpacing.s8)
.padding(.vertical, SodaSpacing.s4)
.background(Color.soda400)
.clipShape(Capsule())
}
private var reactionBar: some View {
HStack(spacing: 15) {
if isPaidLocked == false {
Button(action: onTapLike) {
HStack(spacing: SodaSpacing.s4) {
Image(detail.isLiked ? "ic_feed_community_heart_fill" : "ic_feed_community_heart")
.resizable()
.frame(width: 18, height: 18)
Text("\(detail.likeCount)")
.appFont(size: 16, weight: .regular)
.foregroundColor(Color.gray500)
}
}
.buttonStyle(.plain)
if detail.isCommentAvailable {
HStack(spacing: SodaSpacing.s4) {
Image("ic_feed_community_reply")
.resizable()
.frame(width: 18, height: 18)
Text("\(detail.commentCount)")
.appFont(size: 16, weight: .regular)
.foregroundColor(Color.gray500)
}
}
}
}
.frame(height: 24)
}
private var isOwnPost: Bool {
detail.creatorId == UserDefaults.int(forKey: .userId)
}
private var isPaidLocked: Bool {
detail.price > 0 && detail.existOrdered == false && isOwnPost == false
}
}

View File

@@ -0,0 +1,152 @@
import SwiftUI
struct CreatorChannelCommunityPostDetailInputBar: View {
@Binding var text: String
@Binding var isSecret: Bool
let isShowSecret: Bool
let isSendEnabled: Bool
let isEditing: Bool
let onTapSend: () -> Void
let onTapCancelEditing: () -> Void
var body: some View {
VStack(spacing: 0) {
Rectangle()
.fill(Color.gray800)
.frame(height: 1)
if isShowSecret {
secretToggle
}
HStack(alignment: .bottom, spacing: SodaSpacing.s8) {
if isEditing {
Button(action: onTapCancelEditing) {
Image("ic_close_white")
.resizable()
.scaledToFit()
.frame(width: 20, height: 20)
.frame(width: 36, height: 36)
}
.buttonStyle(.plain)
}
TextField(I18n.CreatorChannelCommunity.commentPlaceholder, text: $text, axis: .vertical)
.autocapitalization(.none)
.disableAutocorrection(true)
.appFont(size: 15, weight: .regular)
.foregroundColor(.white)
.accentColor(Color.soda400)
.lineLimit(1...3)
.padding(.horizontal, SodaSpacing.s14)
.padding(.vertical, SodaSpacing.s8)
.frame(minHeight: 40)
.background(Color.gray900)
.clipShape(RoundedRectangle(cornerRadius: 20, style: .continuous))
Button(action: {
guard isSendEnabled else { return }
onTapSend()
}) {
Image(isSendEnabled ? "ic_arrow_up_white" : "ic_arrow_up_gray")
.resizable()
.scaledToFit()
.frame(width: 20, height: 20)
.frame(width: 36, height: 36)
.background(isSendEnabled ? Color.soda400 : Color.gray900)
.clipShape(Circle())
}
.buttonStyle(.plain)
.disabled(isSendEnabled == false)
}
.padding(.horizontal, SodaSpacing.s14)
.padding(.vertical, SodaSpacing.s8)
}
.background(Color.black)
}
private var secretToggle: some View {
Button {
isSecret.toggle()
} label: {
HStack(spacing: SodaSpacing.s6) {
Image(isSecret ? "btn_square_select_checked" : "btn_square_select_normal")
.resizable()
.frame(width: 18, height: 18)
Text(I18n.Explorer.secretComment)
.appFont(size: 13, weight: .regular)
.foregroundColor(Color.gray500)
Spacer(minLength: 0)
}
.padding(.horizontal, SodaSpacing.s14)
.padding(.top, SodaSpacing.s8)
}
.buttonStyle(.plain)
}
}
struct CreatorChannelCommunityPostDetailInputBar_Previews: PreviewProvider {
static var previews: some View {
Group {
PreviewWrapper(
text: "Secret comment",
isSecret: true,
isShowSecret: true,
isSendEnabled: true,
isEditing: false
)
.padding(.vertical, SodaSpacing.s16)
.background(Color.black)
.previewLayout(.sizeThatFits)
.previewDisplayName("isShowSecret: true")
PreviewWrapper(
text: "Public comment",
isSecret: false,
isShowSecret: false,
isSendEnabled: true,
isEditing: false
)
.padding(.vertical, SodaSpacing.s16)
.background(Color.black)
.previewLayout(.sizeThatFits)
.previewDisplayName("isShowSecret: false")
}
}
private struct PreviewWrapper: View {
@State private var text: String
@State private var isSecret: Bool
let isShowSecret: Bool
let isSendEnabled: Bool
let isEditing: Bool
init(
text: String,
isSecret: Bool,
isShowSecret: Bool,
isSendEnabled: Bool,
isEditing: Bool
) {
_text = State(initialValue: text)
_isSecret = State(initialValue: isSecret)
self.isShowSecret = isShowSecret
self.isSendEnabled = isSendEnabled
self.isEditing = isEditing
}
var body: some View {
CreatorChannelCommunityPostDetailInputBar(
text: $text,
isSecret: $isSecret,
isShowSecret: isShowSecret,
isSendEnabled: isSendEnabled,
isEditing: isEditing,
onTapSend: {},
onTapCancelEditing: {}
)
}
}
}

View File

@@ -0,0 +1,116 @@
import SwiftUI
struct CreatorChannelCommunityPostDetailView: View {
let postId: Int
let onCommunityRefresh: (() -> Void)?
@StateObject private var viewModel = CreatorChannelCommunityPostDetailViewModel()
var body: some View {
ZStack {
VStack(spacing: 0) {
CreatorChannelReplyDetailTitleBar {
AppState.shared.back()
}
ScrollView(.vertical, showsIndicators: false) {
VStack(alignment: .leading, spacing: 0) {
if let detail = viewModel.detail {
CreatorChannelCommunityPostDetailContentView(
detail: detail,
onTapLike: viewModel.toggleLike,
onTapPurchase: showPurchaseError
)
if detail.isCommentAvailable {
CreatorChannelCommunityPostDetailCommentListView(
creatorId: detail.creatorId,
postId: detail.postId,
commentCount: detail.commentCount,
comments: viewModel.comments,
selectedComment: viewModel.selectedComment,
canEdit: viewModel.canEdit,
canDelete: viewModel.canDelete,
onAppearComment: viewModel.fetchNextCommentsIfNeeded,
onTapReplyDetail: showReplyDetail,
onTapMore: viewModel.selectComment,
onTapEdit: viewModel.beginEditing,
onTapDelete: viewModel.presentDeleteDialog
)
}
}
Spacer(minLength: SodaSpacing.s20)
}
}
}
.background(Color.black.ignoresSafeArea())
if viewModel.isLoading && viewModel.hasLoaded == false {
LoadingView()
}
if viewModel.isShowDeleteDialog {
SodaV2ActionModal(
title: I18n.Common.commentDeleteTitle,
message: I18n.Common.confirmDeleteQuestion,
button1: SodaV2ActionModalButton(
label: I18n.Common.delete,
action: viewModel.confirmDelete
),
button2: SodaV2ActionModalButton(
label: I18n.Common.cancel,
action: dismissDeleteDialog
),
onDimmedTap: dismissDeleteDialog
)
}
}
.navigationBarBackButtonHidden(true)
.onAppear {
viewModel.configure(postId: postId, onCommunityRefresh: onCommunityRefresh)
}
.safeAreaInset(edge: .bottom) {
if viewModel.detail?.isCommentAvailable == true {
CreatorChannelCommunityPostDetailInputBar(
text: $viewModel.commentText,
isSecret: $viewModel.isSecret,
isShowSecret: viewModel.isShowSecret,
isSendEnabled: viewModel.isCommentSendEnabled,
isEditing: viewModel.isEditing,
onTapSend: viewModel.sendComment,
onTapCancelEditing: viewModel.cancelEditing
)
}
}
.sodaToast(isPresented: $viewModel.isShowPopup, message: viewModel.errorMessage, autohideIn: 1)
}
private func dismissDeleteDialog() {
viewModel.isShowDeleteDialog = false
viewModel.deletingComment = nil
}
private func showReplyDetail(_ comment: CreatorChannelCommunityCommentResponse) {
guard let detail = viewModel.detail else { return }
AppState.shared.setAppStep(
step: .creatorChannelReplyDetail(
context: .communityPostDetail(
creatorId: detail.creatorId,
postId: detail.postId,
parentComment: comment
),
onCommunityRefresh: {
viewModel.fetchDetail(postId: postId)
onCommunityRefresh?()
}
)
)
}
private func showPurchaseError() {
viewModel.errorMessage = I18n.Common.commonError
viewModel.isShowPopup = true
}
}

View File

@@ -0,0 +1,383 @@
import Foundation
import Combine
import Moya
final class CreatorChannelCommunityPostDetailViewModel: ObservableObject {
private let repository = CreatorChannelCommunityRepository()
private let communityRepository = CreatorCommunityRepository()
private var subscription = Set<AnyCancellable>()
private var postId = 0
private var onCommunityRefresh: (() -> Void)?
private var latestRequestId = 0
@Published var detail: CreatorChannelCommunityPostDetailResponse?
@Published var comments = [CreatorChannelCommunityCommentResponse]()
@Published var commentText = ""
@Published var isSecret = false
@Published var isLoading = false
@Published var isLoadingNextPage = false
@Published var hasLoaded = false
@Published var errorMessage = ""
@Published var isShowPopup = false
@Published var selectedComment: CreatorChannelCommunityCommentResponse?
@Published var editingComment: CreatorChannelCommunityCommentResponse?
@Published var deletingComment: CreatorChannelCommunityCommentResponse?
@Published var isShowDeleteDialog = false
@Published var page = 0
@Published var size = 20
@Published var hasNext = false
var isOwnPost: Bool {
detail?.creatorId == UserDefaults.int(forKey: .userId)
}
var isShowSecret: Bool {
guard let detail else { return false }
return detail.price > 0 && detail.existOrdered && detail.creatorId != UserDefaults.int(forKey: .userId)
}
var isCommentSendEnabled: Bool {
guard detail?.isCommentAvailable == true else { return false }
return commentText.trimmingCharacters(in: .whitespacesAndNewlines).isEmpty == false && isLoading == false
}
var isEditing: Bool {
editingComment != nil
}
func configure(postId: Int, onCommunityRefresh: (() -> Void)?) {
self.onCommunityRefresh = onCommunityRefresh
guard self.postId != postId || hasLoaded == false else { return }
self.postId = postId
fetchDetail(postId: postId)
}
func fetchDetail(postId: Int) {
self.postId = postId
latestRequestId += 1
let requestId = latestRequestId
isLoading = true
repository.getCommunityPostDetail(postId: postId)
.sink { [weak self] result in
guard let self else { return }
guard requestId == self.latestRequestId else { return }
switch result {
case .finished:
DEBUG_LOG("finish")
self.isLoading = false
case .failure(let error):
ERROR_LOG(error.localizedDescription)
self.applyFailureState()
}
} receiveValue: { [weak self] response in
guard let self else { return }
guard requestId == self.latestRequestId else { return }
do {
let decoded = try JSONDecoder().decode(ApiResponse<CreatorChannelCommunityPostDetailResponse>.self, from: response.data)
if let data = decoded.data, decoded.success {
self.applyDetail(data)
} else {
self.errorMessage = decoded.message ?? I18n.Common.commonError
self.isShowPopup = true
}
} catch {
ERROR_LOG(error.localizedDescription)
print(error)
self.errorMessage = I18n.Common.commonError
self.isShowPopup = true
}
self.isLoading = false
self.hasLoaded = true
}
.store(in: &subscription)
}
func fetchNextCommentsIfNeeded(currentComment: CreatorChannelCommunityCommentResponse) {
guard comments.last?.commentId == currentComment.commentId else { return }
guard detail?.isCommentAvailable == true else { return }
guard hasNext, isLoadingNextPage == false, isLoading == false else { return }
guard postId > 0 else { return }
let requestPage = page + 1
isLoadingNextPage = true
repository.getCommunityPostComments(postId: postId, page: requestPage, size: size)
.sink { [weak self] result in
guard let self else { return }
switch result {
case .finished:
DEBUG_LOG("finish")
self.isLoadingNextPage = false
case .failure(let error):
ERROR_LOG(error.localizedDescription)
self.applyFailureState()
}
} receiveValue: { [weak self] response in
guard let self else { return }
do {
let decoded = try JSONDecoder().decode(ApiResponse<CreatorChannelCommunityCommentsResponse>.self, from: response.data)
if let data = decoded.data, decoded.success {
self.page = data.page
self.size = data.size
self.hasNext = data.hasNext
self.comments.append(contentsOf: data.comments)
} else {
self.errorMessage = decoded.message ?? I18n.Common.commonError
self.isShowPopup = true
}
} catch {
ERROR_LOG(error.localizedDescription)
self.errorMessage = I18n.Common.commonError
self.isShowPopup = true
}
self.isLoadingNextPage = false
}
.store(in: &subscription)
}
func toggleLike() {
guard let detail, isLoading == false else { return }
let previousDetail = detail
let nextIsLiked = !detail.isLiked
self.detail = detail.updatingLike(isLiked: nextIsLiked)
communityRepository.communityPostLike(postId: detail.postId)
.sink { [weak self] result in
guard let self else { return }
if case .failure(let error) = result {
ERROR_LOG(error.localizedDescription)
self.detail = previousDetail
self.errorMessage = I18n.Common.commonError
self.isShowPopup = true
}
} receiveValue: { [weak self] response in
guard let self else { return }
do {
let decoded = try JSONDecoder().decode(ApiResponseWithoutData.self, from: response.data)
if decoded.success == false {
self.detail = previousDetail
self.errorMessage = decoded.message ?? I18n.Common.commonError
self.isShowPopup = true
}
} catch {
ERROR_LOG(error.localizedDescription)
self.detail = previousDetail
self.errorMessage = I18n.Common.commonError
self.isShowPopup = true
}
}
.store(in: &subscription)
}
func sendComment() {
guard isCommentSendEnabled else { return }
if let editingComment {
modify(comment: editingComment)
} else {
createComment()
}
}
func canEdit(_ comment: CreatorChannelCommunityCommentResponse) -> Bool {
comment.writerId == UserDefaults.int(forKey: .userId)
}
func canDelete(_ comment: CreatorChannelCommunityCommentResponse) -> Bool {
canEdit(comment) || isOwnPost
}
func selectComment(_ comment: CreatorChannelCommunityCommentResponse) {
selectedComment = selectedComment?.commentId == comment.commentId ? nil : comment
}
func clearSelectedComment() {
selectedComment = nil
}
func beginEditing(_ comment: CreatorChannelCommunityCommentResponse) {
guard canEdit(comment) else { return }
selectedComment = nil
editingComment = comment
commentText = comment.content
}
func cancelEditing() {
editingComment = nil
commentText = ""
}
func presentDeleteDialog(_ comment: CreatorChannelCommunityCommentResponse) {
guard canDelete(comment) else { return }
selectedComment = nil
deletingComment = comment
isShowDeleteDialog = true
}
func confirmDelete() {
guard let deletingComment, isLoading == false else { return }
isShowDeleteDialog = false
delete(comment: deletingComment)
}
private func applyDetail(_ data: CreatorChannelCommunityPostDetailResponse) {
detail = data
page = data.comments.page
size = data.comments.size
hasNext = data.comments.hasNext
hasLoaded = true
if data.isCommentAvailable {
comments = data.comments.comments
} else {
comments = []
commentText = ""
isSecret = false
selectedComment = nil
editingComment = nil
deletingComment = nil
isShowDeleteDialog = false
}
}
private func createComment() {
guard postId > 0 else { return }
isLoading = true
communityRepository.createCommunityPostComment(
comment: commentText.trimmingCharacters(in: .whitespacesAndNewlines),
postId: postId,
parentId: nil,
isSecret: isShowSecret ? isSecret : false
)
.sink { [weak self] result in
guard let self else { return }
if case .failure(let error) = result {
ERROR_LOG(error.localizedDescription)
self.applyFailureState()
}
} receiveValue: { [weak self] response in
self?.handleCommentMutationResponse(response)
}
.store(in: &subscription)
}
private func modify(comment: CreatorChannelCommunityCommentResponse) {
let content = commentText.trimmingCharacters(in: .whitespacesAndNewlines)
guard content.isEmpty == false, content != comment.content else {
errorMessage = I18n.Explorer.noChanges
isShowPopup = true
return
}
isLoading = true
var request = ModifyCommunityPostCommentRequest(commentId: comment.commentId)
request.comment = content
communityRepository.modifyComment(request: request)
.sink { [weak self] result in
guard let self else { return }
if case .failure(let error) = result {
ERROR_LOG(error.localizedDescription)
self.applyFailureState()
}
} receiveValue: { [weak self] response in
self?.handleCommentMutationResponse(response)
}
.store(in: &subscription)
}
private func delete(comment: CreatorChannelCommunityCommentResponse) {
isLoading = true
var request = ModifyCommunityPostCommentRequest(commentId: comment.commentId)
request.isActive = false
communityRepository.modifyComment(request: request)
.sink { [weak self] result in
guard let self else { return }
if case .failure(let error) = result {
ERROR_LOG(error.localizedDescription)
self.applyFailureState()
}
} receiveValue: { [weak self] response in
self?.handleCommentMutationResponse(response)
}
.store(in: &subscription)
}
private func handleCommentMutationResponse(_ response: Moya.Response) {
isLoading = false
do {
let decoded = try JSONDecoder().decode(ApiResponseWithoutData.self, from: response.data)
if decoded.success {
applyCommentMutationSuccessState()
onCommunityRefresh?()
fetchDetail(postId: postId)
} else {
errorMessage = decoded.message ?? I18n.Common.commonError
isShowPopup = true
}
} catch {
ERROR_LOG(error.localizedDescription)
errorMessage = I18n.Common.commonError
isShowPopup = true
}
}
private func applyCommentMutationSuccessState() {
commentText = ""
isSecret = false
selectedComment = nil
editingComment = nil
deletingComment = nil
isShowDeleteDialog = false
}
private func applyFailureState() {
isLoading = false
isLoadingNextPage = false
hasLoaded = true
errorMessage = I18n.Common.commonError
isShowPopup = true
}
}
private extension CreatorChannelCommunityPostDetailResponse {
func updatingLike(isLiked: Bool) -> CreatorChannelCommunityPostDetailResponse {
let nextLikeCount = max(0, likeCount + (isLiked ? 1 : -1))
return CreatorChannelCommunityPostDetailResponse(
postId: postId,
creatorId: creatorId,
creatorNickname: creatorNickname,
creatorProfileUrl: creatorProfileUrl,
createdAtUtc: createdAtUtc,
content: content,
imageUrl: imageUrl,
audioUrl: audioUrl,
price: price,
isCommentAvailable: isCommentAvailable,
existOrdered: existOrdered,
likeCount: nextLikeCount,
commentCount: commentCount,
isPinned: isPinned,
isLiked: isLiked,
comments: comments
)
}
}