feat(main): 홈 대화 탭을 추가한다

This commit is contained in:
Yu Sung
2026-07-08 15:54:07 +09:00
parent 403eee262f
commit 09443761af
13 changed files with 938 additions and 23 deletions

View File

@@ -0,0 +1,89 @@
import SwiftUI
struct MainChatRoomListItem: View {
let room: MainChatRoomItem
let onTap: (Int, String) -> Void
var body: some View {
Button {
onTap(room.roomId, room.chatType)
} label: {
HStack(alignment: .center, spacing: SodaSpacing.s14) {
DownsampledKFImage(url: URL(string: room.targetImageUrl), size: CGSize(width: 58, height: 58))
.clipShape(Circle())
VStack(alignment: .leading, spacing: SodaSpacing.s12) {
HStack(alignment: .center, spacing: SodaSpacing.s6) {
Text(room.targetName)
.appFont(size: 18, weight: .bold)
.foregroundColor(.white)
.lineLimit(1)
.truncationMode(.tail)
if room.isDirectMessage {
MainChatDirectTagView()
}
Spacer(minLength: SodaSpacing.s8)
Text(room.chatListDateText())
.appFont(size: 14, weight: .medium)
.foregroundColor(Color.gray500)
.lineLimit(1)
}
Text(room.lastMessage)
.appFont(size: 16, weight: .medium)
.foregroundColor(Color.gray500)
.lineLimit(1)
.truncationMode(.tail)
}
.frame(maxWidth: .infinity, alignment: .leading)
}
.padding(SodaSpacing.s14)
.contentShape(Rectangle())
}
.buttonStyle(.plain)
}
}
private struct MainChatDirectTagView: View {
var body: some View {
Text(I18n.MainChat.directTag)
.appFont(size: 12, weight: .bold)
.italic()
.foregroundColor(.white)
.padding(.horizontal, SodaSpacing.s4)
.padding(.vertical, SodaSpacing.s4)
.background(Color.soda400)
.cornerRadius(4)
}
}
private extension MainChatRoomItem {
var isDirectMessage: Bool {
chatType == "DM"
}
func chatListDateText(now: Date = Date()) -> String {
DateParser.chatListDateText(fromUTC: lastMessageAt, fallback: lastMessageAt, now: now)
}
}
struct MainChatRoomListItem_Previews: PreviewProvider {
static var previews: some View {
MainChatRoomListItem(
room: MainChatRoomItem(
roomId: 1,
chatType: "DM",
targetName: "크리에이터 이름",
targetImageUrl: "https://picsum.photos/500/500",
lastMessage: "마지막 대화 내용이 들어가는 부분입니다. 한 줄 넘어가는경우 말줄임",
lastMessageAt: "2026-07-01T01:30:00Z"
),
onTap: { _, _ in }
)
.background(Color.black)
.previewLayout(.sizeThatFits)
}
}

View File

@@ -0,0 +1,29 @@
import Foundation
enum MainChatFilter: CaseIterable, Hashable {
case all
case ai
case dm
var queryValue: String {
switch self {
case .all:
return "ALL"
case .ai:
return "AI"
case .dm:
return "DM"
}
}
var title: String {
switch self {
case .all:
return I18n.MainChat.filterAll
case .ai:
return I18n.MainChat.filterAI
case .dm:
return I18n.MainChat.filterDM
}
}
}

View File

@@ -0,0 +1,93 @@
import SwiftUI
struct MainChatView: View {
let onTapCanCharge: () -> Void
let onTapSearch: () -> Void
@StateObject private var viewModel = MainChatViewModel()
var body: some View {
VStack(spacing: 0) {
DefaultTitleBar(title: MainTab.chat.title) {
HStack(spacing: SodaSpacing.s14) {
Image("ic_bar_cash")
.onTapGesture { onTapCanCharge() }
Image("ic_bar_search")
.onTapGesture { onTapSearch() }
}
}
CapsuleTabBar(
items: MainChatFilter.allCases,
selectedItem: selectedFilterBinding,
title: { $0.title }
)
chatListContent
.frame(maxWidth: .infinity, maxHeight: .infinity)
}
.background(Color.black.ignoresSafeArea())
.onAppear { viewModel.fetchFirstPageIfNeeded() }
.sodaToast(
isPresented: $viewModel.isShowPopup,
message: viewModel.errorMessage,
autohideIn: 2
)
}
private var selectedFilterBinding: Binding<MainChatFilter> {
Binding(
get: { viewModel.selectedFilter },
set: { viewModel.applyFilter($0) }
)
}
@ViewBuilder
private var chatListContent: some View {
if viewModel.isLoading && viewModel.rooms.isEmpty {
ProgressView()
.progressViewStyle(.circular)
.tint(Color.soda400)
.frame(maxWidth: .infinity, maxHeight: .infinity)
} else if viewModel.shouldShowEmptyState {
Text(I18n.MainChat.emptyStateMessage)
.appFont(size: 16, weight: .medium)
.foregroundColor(Color.gray500)
.frame(maxWidth: .infinity, maxHeight: .infinity)
} else {
ScrollView(showsIndicators: false) {
LazyVStack(spacing: 0) {
ForEach(viewModel.rooms) { room in
MainChatRoomListItem(room: room) { roomId, chatType in
handleChatRoomTap(roomId: roomId, chatType: chatType)
}
.onAppear {
viewModel.fetchNextPageIfNeeded(currentItem: room)
}
}
if viewModel.isLoadingNextPage {
ProgressView()
.progressViewStyle(.circular)
.tint(Color.soda400)
.padding(.vertical, SodaSpacing.s20)
}
}
.padding(.top, 0)
}
}
}
private func handleChatRoomTap(roomId: Int, chatType: String) {
guard chatType == "AI" else { return }
AppState.shared.setAppStep(step: .chatRoom(id: roomId))
}
}
struct MainChatView_Previews: PreviewProvider {
static var previews: some View {
MainChatView(onTapCanCharge: {}, onTapSearch: {})
}
}

View File

@@ -0,0 +1,119 @@
import Foundation
import Combine
final class MainChatViewModel: ObservableObject {
private let repository = MainChatRepository()
private var subscription = Set<AnyCancellable>()
private var latestRequestId = 0
@Published var rooms = [MainChatRoomItem]()
@Published var selectedFilter: MainChatFilter = .all
@Published var isLoading = false
@Published var isLoadingNextPage = false
@Published var hasMore = false
@Published var nextCursor: String?
@Published var hasLoaded = false
@Published var errorMessage = ""
@Published var isShowPopup = false
var shouldShowEmptyState: Bool {
hasLoaded && isLoading == false && rooms.isEmpty
}
func fetchFirstPageIfNeeded() {
guard hasLoaded == false else { return }
fetchFirstPage(filter: selectedFilter)
}
func fetchFirstPage(filter: MainChatFilter) {
selectedFilter = filter
clearRooms()
fetchChatRooms(filter: filter, cursor: nil, isNextPage: false)
}
func applyFilter(_ filter: MainChatFilter) {
guard selectedFilter != filter else { return }
fetchFirstPage(filter: filter)
}
func fetchNextPageIfNeeded(currentItem: MainChatRoomItem) {
guard rooms.last?.roomId == currentItem.roomId else { return }
guard hasMore, let nextCursor, isLoading == false, isLoadingNextPage == false else { return }
fetchChatRooms(filter: selectedFilter, cursor: nextCursor, isNextPage: true)
}
private func fetchChatRooms(filter: MainChatFilter, cursor: String?, isNextPage: Bool) {
latestRequestId += 1
let requestId = latestRequestId
if isNextPage {
isLoadingNextPage = true
} else {
isLoading = true
}
repository.getChatRooms(filter: filter.queryValue, cursor: cursor)
.sink { [weak self] result in
guard let self else { return }
guard requestId == self.latestRequestId else { return }
switch result {
case .finished:
DEBUG_LOG("finish")
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 jsonDecoder = JSONDecoder()
let decoded = try jsonDecoder.decode(ApiResponse<MainChatRoomsResponse>.self, from: response.data)
if let data = decoded.data, decoded.success {
self.applySuccessState(data, isNextPage: isNextPage)
} else {
self.errorMessage = decoded.message ?? I18n.MainChat.loadFailedMessage
self.isShowPopup = true
}
} catch {
ERROR_LOG(error.localizedDescription)
self.errorMessage = I18n.MainChat.loadFailedMessage
self.isShowPopup = true
}
self.hasLoaded = true
self.isLoading = false
self.isLoadingNextPage = false
}
.store(in: &subscription)
}
private func applySuccessState(_ data: MainChatRoomsResponse, isNextPage: Bool) {
hasMore = data.hasMore
nextCursor = data.nextCursor
if isNextPage {
rooms.append(contentsOf: data.rooms)
} else {
rooms = data.rooms
}
}
private func applyFailureState() {
errorMessage = I18n.MainChat.loadFailedMessage
isShowPopup = true
hasLoaded = true
isLoading = false
isLoadingNextPage = false
}
private func clearRooms() {
rooms = []
hasMore = false
nextCursor = nil
hasLoaded = false
}
}

View File

@@ -0,0 +1,18 @@
import Foundation
struct MainChatRoomsResponse: Decodable {
let rooms: [MainChatRoomItem]
let hasMore: Bool
let nextCursor: String?
}
struct MainChatRoomItem: Decodable, Identifiable {
let roomId: Int
let chatType: String
let targetName: String
let targetImageUrl: String
let lastMessage: String
let lastMessageAt: String
var id: Int { roomId }
}

View File

@@ -0,0 +1,45 @@
import Foundation
import Moya
enum MainChatApi {
case getChatRooms(filter: String, cursor: String?)
}
extension MainChatApi: TargetType {
var baseURL: URL {
return URL(string: BASE_URL)!
}
var path: String {
switch self {
case .getChatRooms:
return "/api/v2/chat/rooms"
}
}
var method: Moya.Method {
switch self {
case .getChatRooms:
return .get
}
}
var task: Moya.Task {
switch self {
case .getChatRooms(let filter, let cursor):
var parameters: [String: Any] = [
"filter": filter
]
if let cursor {
parameters["cursor"] = cursor
}
return .requestParameters(parameters: parameters, encoding: URLEncoding.queryString)
}
}
var headers: [String: String]? {
return ["Authorization": "Bearer \(UserDefaults.string(forKey: UserDefaultsKey.token))"]
}
}

View File

@@ -0,0 +1,12 @@
import Foundation
import Combine
import CombineMoya
import Moya
final class MainChatRepository {
private let api = MoyaProvider<MainChatApi>()
func getChatRooms(filter: String, cursor: String?) -> AnyPublisher<Response, MoyaError> {
return api.requestPublisher(.getChatRooms(filter: filter, cursor: cursor))
}
}