feat(home): 인기 커뮤니티 섹션을 연결한다

This commit is contained in:
Yu Sung
2026-06-30 01:44:20 +09:00
parent 20601f40cf
commit 339ca78793
16 changed files with 578 additions and 110 deletions

View File

@@ -15,6 +15,38 @@ enum DateParser {
}
return nil
}
static func relativeTimeText(fromUTC text: String, fallback: String, now: Date = Date()) -> String {
guard let date = parse(text) else {
return fallback
}
let interval = max(0, now.timeIntervalSince(date))
let calendar = Calendar.current
let yearMonth = calendar.dateComponents([.year, .month], from: date, to: now)
if let years = yearMonth.year, years >= 1 {
return I18n.Time.yearsAgo(years)
}
if let months = yearMonth.month, months >= 1 {
return I18n.Time.monthsAgo(months)
}
if interval < 60 {
return I18n.Time.justNow
}
if interval < 3600 {
return I18n.Time.minutesAgo(max(1, Int(interval / 60)))
}
if interval < 86_400 {
return I18n.Time.hoursAgo(max(1, Int(interval / 3600)))
}
return I18n.Time.daysAgo(max(1, Int(interval / 86_400)))
}
// : ISO8601( ) ISO8601 RFC3339
private static let parsers: [(String) -> Date?] = [

View File

@@ -34,37 +34,6 @@ extension GetCommunityPostListResponse {
/// ( ///// ) .
/// , `date` .
func relativeTimeText(now: Date = Date()) -> String {
guard let createdAt = DateParser.parse(dateUtc) else {
return date
}
let nowDate = now
let interval = max(0, nowDate.timeIntervalSince(createdAt))
// / (/ )
let calendar = Calendar.current
let ym = calendar.dateComponents([.year, .month],
from: createdAt,
to: nowDate)
if let years = ym.year, years >= 1 {
return I18n.Time.yearsAgo(years)
}
if let months = ym.month, months >= 1 {
return I18n.Time.monthsAgo(months)
}
// //
if interval < 60 {
return I18n.Time.justNow
} else if interval < 3600 {
let minutes = Int(interval / 60)
return I18n.Time.minutesAgo(max(1, minutes))
} else if interval < 86_400 {
let hours = Int(interval / 3600)
return I18n.Time.hoursAgo(max(1, hours))
} else {
let days = Int(interval / 86_400)
return I18n.Time.daysAgo(max(1, days))
}
DateParser.relativeTimeText(fromUTC: dateUtc, fallback: date, now: now)
}
}

View File

@@ -1,129 +1,273 @@
import SwiftUI
struct CommunityPostCard: View {
let postId: Int
let creatorNickname: String
let creatorProfileImageUrl: String?
let content: String
let imageUrl: String?
let price: Int?
let audioUrl: String?
let price: Int
let existOrdered: Bool
let createdAt: String?
let likeCount: Int?
let commentCount: Int?
let createdAt: String
let isLike: Bool
let likeCount: Int
let commentCount: Int
let onTapLike: () -> Void
let onTapComment: () -> Void
let onTapPurchase: () -> Void
@State private var localIsLike: Bool
@State private var localLikeCount: Int
@StateObject private var playManager = CreatorCommunityMediaPlayerManager.shared
@StateObject private var contentPlayManager = ContentPlayManager.shared
init(
postId: Int,
creatorNickname: String,
creatorProfileImageUrl: String?,
content: String,
imageUrl: String?,
audioUrl: String?,
price: Int,
existOrdered: Bool,
createdAt: String,
isLike: Bool,
likeCount: Int,
commentCount: Int,
onTapLike: @escaping () -> Void = {},
onTapComment: @escaping () -> Void = {},
onTapPurchase: @escaping () -> Void = {}
) {
self.postId = postId
self.creatorNickname = creatorNickname
self.creatorProfileImageUrl = creatorProfileImageUrl
self.content = content
self.imageUrl = imageUrl
self.audioUrl = audioUrl
self.price = price
self.existOrdered = existOrdered
self.createdAt = createdAt
self.isLike = isLike
self.likeCount = likeCount
self.commentCount = commentCount
self.onTapLike = onTapLike
self.onTapComment = onTapComment
self.onTapPurchase = onTapPurchase
_localIsLike = State(initialValue: isLike)
_localLikeCount = State(initialValue: likeCount)
}
var body: some View {
VStack(alignment: .leading, spacing: SodaSpacing.s12) {
VStack(alignment: .leading, spacing: SodaSpacing.s16) {
header
Text(content)
.appFont(.body4)
.foregroundColor(.white)
.lineLimit(3)
.truncationMode(.tail)
contentText
if hasImage {
imageContent
}
footer
reactionBar
}
.padding(SodaSpacing.s12)
.padding(SodaSpacing.s14)
.background(Color.gray900)
.clipShape(RoundedRectangle(cornerRadius: SodaSpacing.s14, style: .continuous))
.onChange(of: isLike) { newValue in
localIsLike = newValue
}
.onChange(of: likeCount) { newValue in
localLikeCount = newValue
}
}
private var header: some View {
HStack(spacing: SodaSpacing.s8) {
DownsampledKFImage(url: URL(string: creatorProfileImageUrl ?? ""), size: CGSize(width: 32, height: 32))
DownsampledKFImage(url: URL(string: creatorProfileImageUrl ?? ""), size: CGSize(width: 42, height: 42))
.background(Color.gray800)
.clipShape(Circle())
.frame(width: 42, height: 42)
Text(creatorNickname)
.appFont(.body5)
.foregroundColor(.white)
.lineLimit(1)
VStack(alignment: .leading, spacing: 2) {
Text(creatorNickname)
.appFont(.body4)
.foregroundColor(.white)
.lineLimit(1)
Text(createdAt)
.appFont(.body5)
.foregroundColor(Color.gray500)
.lineLimit(1)
}
Spacer(minLength: 0)
}
}
private var imageContent: some View {
ZStack {
DownsampledKFImage(url: URL(string: imageUrl ?? ""), size: CGSize(width: 240, height: 150))
.background(Color.gray800)
.frame(maxWidth: .infinity)
.clipShape(RoundedRectangle(cornerRadius: SodaSpacing.s12, style: .continuous))
.blur(radius: isLocked ? 8 : 0)
private var contentText: some View {
Text(content)
.appFont(.body2)
.foregroundColor(.white)
.lineLimit(5)
.truncationMode(.tail)
.fixedSize(horizontal: false, vertical: true)
}
if isLocked {
VStack(spacing: SodaSpacing.s6) {
private var imageContent: some View {
GeometryReader { proxy in
ZStack {
DownsampledKFImage(
url: URL(string: imageUrl ?? ""),
size: CGSize(width: proxy.size.width, height: proxy.size.height)
)
.background(Color.gray800)
.frame(width: proxy.size.width, height: proxy.size.height)
.clipShape(RoundedRectangle(cornerRadius: SodaSpacing.s14, style: .continuous))
.blur(radius: isLocked ? 12 : 0)
if isLocked {
paidLockOverlay
} else if hasAudio {
audioPlayButton
}
}
}
.aspectRatio(346.0 / 236.0, contentMode: .fit)
.clipShape(RoundedRectangle(cornerRadius: SodaSpacing.s14, style: .continuous))
}
private var paidLockOverlay: some View {
Button(action: onTapPurchase) {
ZStack {
Color.gray700.opacity(0.35)
VStack(spacing: SodaSpacing.s4) {
Image("ic_new_community_lock")
.resizable()
.renderingMode(.template)
.foregroundColor(.white)
.frame(width: 24, height: 24)
if let price {
Text("\(price) can")
.appFont(.caption2)
.foregroundColor(Color.button)
.padding(.horizontal, SodaSpacing.s12)
.padding(.vertical, SodaSpacing.s6)
.overlay(
Capsule()
.stroke(Color.button, lineWidth: 1)
)
HStack(spacing: SodaSpacing.s6) {
Image("ic_can")
.resizable()
.frame(width: 20, height: 20)
Text("\(price)")
.appFont(.body2)
.foregroundColor(.black)
}
.padding(SodaSpacing.s8)
.background(Color.white)
.clipShape(Capsule())
}
}
}
.buttonStyle(.plain)
}
private var footer: some View {
HStack(spacing: SodaSpacing.s12) {
if let createdAt, !createdAt.isEmpty {
Text(createdAt)
.appFont(.caption2)
.foregroundColor(Color.gray500)
}
private var audioPlayButton: some View {
Button {
guard let audioUrl, !audioUrl.isEmpty else { return }
if let likeCount {
Text("Like \(likeCount)")
.appFont(.caption2)
.foregroundColor(Color.gray500)
}
if let commentCount {
Text("Comment \(commentCount)")
.appFont(.caption2)
.foregroundColor(Color.gray500)
}
contentPlayManager.pauseAudio()
playManager.toggleContent(item: CreatorCommunityContentItem(contentId: postId, url: audioUrl))
} label: {
Image(playManager.isPlaying && playManager.currentPlayingContentId == postId ? "btn_audio_content_pause" : "btn_audio_content_play")
.resizable()
.frame(width: 48, height: 48)
}
.buttonStyle(.plain)
}
private var reactionBar: some View {
HStack(spacing: 15) {
Button {
toggleLike()
} label: {
HStack(spacing: SodaSpacing.s4) {
Image(localIsLike ? "ic_feed_community_heart_fill" : "ic_feed_community_heart")
.resizable()
.frame(width: 18, height: 18)
Text("\(localLikeCount)")
.appFont(.body2)
.foregroundColor(Color.gray400)
}
}
.buttonStyle(.plain)
Button(action: onTapComment) {
HStack(spacing: SodaSpacing.s4) {
Image("ic_feed_community_reply")
.resizable()
.frame(width: 18, height: 18)
Text("\(commentCount)")
.appFont(.body2)
.foregroundColor(Color.gray400)
}
}
.buttonStyle(.plain)
}
.frame(height: 24)
}
private var hasImage: Bool {
!(imageUrl ?? "").isEmpty
}
private var hasAudio: Bool {
!(audioUrl ?? "").isEmpty
}
private var isLocked: Bool {
(price ?? 0) > 0 && !existOrdered
price > 0 && !existOrdered
}
private func toggleLike() {
localIsLike.toggle()
localLikeCount += localIsLike ? 1 : -1
localLikeCount = max(0, localLikeCount)
onTapLike()
}
}
struct CommunityPostCard_Previews: PreviewProvider {
private static let previewImageUrl = "https://picsum.photos/500/500"
static var previews: some View {
CommunityPostCard(
creatorNickname: "크리에이터",
creatorProfileImageUrl: nil,
content: "커뮤니티 본문입니다.",
imageUrl: nil,
price: nil,
existOrdered: false,
createdAt: "방금 전",
likeCount: 10,
commentCount: 2
)
.padding(SodaSpacing.s20)
VStack(spacing: SodaSpacing.s8) {
CommunityPostCard(
postId: 1,
creatorNickname: "크리에이터 이름",
creatorProfileImageUrl: previewImageUrl,
content: "크리에이터가 커뮤니티에 올린 글이 보이는 부분 크리에이터가 커뮤니티에 올린 글이 보이는 부분",
imageUrl: nil,
audioUrl: nil,
price: 0,
existOrdered: false,
createdAt: "2분 전",
isLike: false,
likeCount: 5,
commentCount: 6
)
CommunityPostCard(
postId: 2,
creatorNickname: "크리에이터 이름",
creatorProfileImageUrl: previewImageUrl,
content: "이미지가 있는 커뮤니티 게시글입니다.",
imageUrl: previewImageUrl,
audioUrl: "https://example.com/audio.mp3",
price: 30,
existOrdered: false,
createdAt: "2분 전",
isLike: true,
likeCount: 5,
commentCount: 6
)
}
.padding(SodaSpacing.s14)
.background(Color.black)
.previewLayout(.sizeThatFits)
}

View File

@@ -0,0 +1,101 @@
import SwiftUI
struct MainHomePopularCommunitySection: View {
let items: [HomePopularCommunityPostItem]
let onTapCommunity: (Int) -> Void
let onTapLike: (Int) -> Void
let onTapPurchase: (HomePopularCommunityPostItem) -> Void
init(
items: [HomePopularCommunityPostItem],
onTapCommunity: @escaping (Int) -> Void = { _ in },
onTapLike: @escaping (Int) -> Void = { _ in },
onTapPurchase: @escaping (HomePopularCommunityPostItem) -> Void = { _ in }
) {
self.items = items
self.onTapCommunity = onTapCommunity
self.onTapLike = onTapLike
self.onTapPurchase = onTapPurchase
}
var body: some View {
if !items.isEmpty {
VStack(alignment: .leading, spacing: SodaSpacing.s14) {
SectionTitle(title: I18n.HomeRecommendation.popularCommunitySectionTitle)
VStack(alignment: .leading, spacing: SodaSpacing.s8) {
ForEach(items, id: \.postId) { item in
CommunityPostCard(
postId: item.postId,
creatorNickname: item.creatorNickname,
creatorProfileImageUrl: item.creatorProfileImage,
content: item.content,
imageUrl: item.imageUrl,
audioUrl: item.audioUrl,
price: item.price,
existOrdered: item.existOrdered,
createdAt: item.relativeCreatedAtText(),
isLike: item.isLiked,
likeCount: item.likeCount,
commentCount: item.commentCount,
onTapLike: {
onTapLike(item.postId)
},
onTapComment: {
onTapCommunity(item.creatorId)
},
onTapPurchase: {
onTapPurchase(item)
}
)
}
}
.padding(.horizontal, SodaSpacing.s14)
}
}
}
}
struct MainHomePopularCommunitySection_Previews: PreviewProvider {
private static let previewImageUrl = "https://picsum.photos/500/500"
static var previews: some View {
MainHomePopularCommunitySection(
items: [
HomePopularCommunityPostItem(
postId: 1,
creatorId: 10,
creatorNickname: "크리에이터 이름",
creatorProfileImage: previewImageUrl,
content: "크리에이터가 커뮤니티에 올린 글이 보이는 부분 크리에이터가 커뮤니티에 올린 글이 보이는 부분",
imageUrl: nil,
audioUrl: nil,
price: 0,
existOrdered: false,
likeCount: 5,
commentCount: 6,
createdAt: "2026-06-29T12:00:00Z",
isLiked: false
),
HomePopularCommunityPostItem(
postId: 2,
creatorId: 11,
creatorNickname: "크리에이터 이름",
creatorProfileImage: previewImageUrl,
content: "이미지가 있는 커뮤니티 게시글입니다.",
imageUrl: previewImageUrl,
audioUrl: "https://example.com/audio.mp3",
price: 30,
existOrdered: false,
likeCount: 5,
commentCount: 6,
createdAt: "2026-06-29T12:00:00Z",
isLiked: true
)
]
)
.padding(.vertical, SodaSpacing.s20)
.background(Color.black)
.previewLayout(.sizeThatFits)
}
}

View File

@@ -10,6 +10,7 @@ struct MainHomeRecommendationView: View {
let onTapFollowAll: (@escaping () -> Void) -> Void
@StateObject private var viewModel = MainHomeRecommendationViewModel()
@StateObject private var communityMediaPlayer = CreatorCommunityMediaPlayerManager.shared
var body: some View {
ZStack {
@@ -75,6 +76,17 @@ struct MainHomeRecommendationView: View {
}
}
)
MainHomePopularCommunitySection(
items: viewModel.recommendations?.popularCommunityPosts ?? [],
onTapCommunity: onTapCommunity,
onTapLike: { postId in
viewModel.likeCommunityPost(postId: postId)
},
onTapPurchase: { item in
viewModel.openCommunityPostPurchase(postId: item.postId, price: item.price)
}
)
}
.padding(.vertical, SodaSpacing.s20)
}
@@ -90,6 +102,24 @@ struct MainHomeRecommendationView: View {
message: viewModel.errorMessage,
autohideIn: 2
)
.sodaToast(
isPresented: $communityMediaPlayer.isShowPopup,
message: communityMediaPlayer.errorMessage,
autohideIn: 2
)
.overlay {
if viewModel.isShowCommunityPostPurchaseDialog {
CommunityPostPurchaseDialog(
isShowing: $viewModel.isShowCommunityPostPurchaseDialog,
can: viewModel.purchasingCommunityPostPrice,
confirmAction: viewModel.purchaseCommunityPost
)
}
if communityMediaPlayer.isLoading {
LoadingView()
}
}
}
}

View File

@@ -3,14 +3,18 @@ import Combine
final class MainHomeRecommendationViewModel: ObservableObject {
private let repository = MainHomeRecommendationRepository()
private let communityRepository = CreatorCommunityRepository()
private var subscription = Set<AnyCancellable>()
@Published var isLoading = false
@Published var isShowPopup = false
@Published var errorMessage = ""
@Published var recommendations: HomeRecommendationResponse?
@Published var isShowCommunityPostPurchaseDialog = false
@Published var purchasingCommunityPostPrice = 0
@Published private(set) var completedFollowKeys = Set<String>()
@Published private(set) var followingKeys = Set<String>()
private var purchasingCommunityPostId = 0
func fetchRecommendations() {
isLoading = true
@@ -104,4 +108,77 @@ final class MainHomeRecommendationViewModel: ObservableObject {
func isFollowAllLoading(_ completionKey: String) -> Bool {
followingKeys.contains(completionKey)
}
func likeCommunityPost(postId: Int) {
guard postId > 0 else { return }
communityRepository.communityPostLike(postId: postId)
.sink { [weak self] result in
guard let self else { return }
switch result {
case .finished:
DEBUG_LOG("finish")
case .failure(let error):
ERROR_LOG(error.localizedDescription)
self.errorMessage = I18n.Common.commonError
self.isShowPopup = true
}
} receiveValue: { _ in }
.store(in: &subscription)
}
func openCommunityPostPurchase(postId: Int, price: Int) {
guard postId > 0, price > 0 else { return }
purchasingCommunityPostId = postId
purchasingCommunityPostPrice = price
isShowCommunityPostPurchaseDialog = true
}
func purchaseCommunityPost() {
let postId = purchasingCommunityPostId
guard postId > 0, !isLoading else { return }
isLoading = true
communityRepository.purchaseCommunityPost(postId: postId)
.sink { [weak self] result in
guard let self else { return }
switch result {
case .finished:
DEBUG_LOG("finish")
case .failure(let error):
ERROR_LOG(error.localizedDescription)
self.errorMessage = I18n.Common.commonError
self.isShowPopup = true
self.isLoading = false
}
} receiveValue: { [weak self] response in
guard let self else { return }
let responseData = response.data
do {
let jsonDecoder = JSONDecoder()
let decoded = try jsonDecoder.decode(ApiResponse<GetCommunityPostListResponse>.self, from: responseData)
if decoded.success {
self.purchasingCommunityPostId = 0
self.purchasingCommunityPostPrice = 0
self.fetchRecommendations()
} else {
self.errorMessage = decoded.message ?? I18n.Common.commonError
self.isShowPopup = true
self.isLoading = false
}
} catch {
self.errorMessage = I18n.Common.commonError
self.isShowPopup = true
self.isLoading = false
}
}
.store(in: &subscription)
}
}

View File

@@ -79,4 +79,9 @@ struct HomePopularCommunityPostItem: Decodable, Hashable {
let likeCount: Int
let commentCount: Int
let createdAt: String
let isLiked: Bool
func relativeCreatedAtText(now: Date = Date()) -> String {
DateParser.relativeTimeText(fromUTC: createdAt, fallback: createdAt, now: now)
}
}