feat(chat-room) 채팅방

- 텍스트 메시지 UI 적용
This commit is contained in:
Yu Sung
2025-09-03 23:14:26 +09:00
parent a42edbe99c
commit 1ec22717cb
4 changed files with 530 additions and 4 deletions

View File

@@ -6,14 +6,192 @@
// //
import SwiftUI import SwiftUI
import Kingfisher
import UIKit
struct ChatRoomView: View { struct ChatRoomView: View {
@StateObject var viewModel = ChatRoomViewModel() @StateObject var viewModel = ChatRoomViewModel()
@AppStorage("can") private var can: Int = UserDefaults.int(forKey: .can)
var body: some View { var body: some View {
BaseView(isLoading: $viewModel.isLoading) { BaseView(isLoading: $viewModel.isLoading) {
ChatRoomBgView()
VStack(spacing: 0) {
HStack(spacing: 12) {
Image("ic_back")
.resizable()
.frame(width: 24, height: 24)
.onTapGesture {
AppState.shared.back()
}
KFImage(URL(string: viewModel.characterProfileUrl))
.placeholder {
Image(systemName: "person.crop.circle")
.resizable()
.scaledToFit()
}
.resizable()
.frame(width: 36, height: 36)
VStack(alignment: .leading, spacing: 4) {
Text(viewModel.characterName)
.font(.custom(Font.preBold.rawValue, size: 12))
.foregroundColor(.white)
.lineLimit(1)
.truncationMode(.tail)
Text(viewModel.characterType.rawValue)
.font(.custom(Font.preBold.rawValue, size: 10))
.foregroundColor(.white)
.padding(.horizontal, 4)
.padding(.vertical, 2)
.background(
Color(hex:
viewModel.characterType == .Clone ?
"0020C9" : "009D68"
)
)
.cornerRadius(6)
}
Spacer()
HStack(spacing: 4) {
Image("ic_can")
.resizable()
.frame(width: 20, height: 20)
Text("\(can)")
.font(.custom(Font.preRegular.rawValue, size: 16))
.foregroundColor(.white)
}
.padding(.horizontal, 10)
.padding(.vertical, 5)
.background(Color(hex: "263238"))
.cornerRadius(30)
Image("ic_seemore_vertical_white")
.resizable()
.frame(width: 24, height: 24)
.onTapGesture {}
}
.padding(.horizontal, 16)
.padding(.vertical, 8)
.frame(width: screenSize().width, height: 60)
HStack(spacing: 8) {
Image(systemName: "info.circle.fill")
.resizable()
.frame(width: 20, height: 20)
Text(
viewModel.characterType == .Character
? "보이스온 AI캐릭터톡은 대화의 자유도가 높아 대화에 참여하는 당신은 누구든 될 수 있습니다.\n세계관 속 캐릭터로 대화를 하거나 새로운 인물로 캐릭터와 당신만의 스토리를 만들어보세요.\n※ AI캐릭터톡은 오픈베타 서비스 중이며, 캐릭터의 대화가 어색하거나 불완전할 수 있습니다."
: "AI Clone은 크리에이터의 정보를 기반으로 대화하지만, 모든 정보를 완벽하게 반영하거나 실제 대화와 일치하지 않을 수 있습니다."
)
.font(.custom(Font.preRegular.rawValue, size: 12))
.foregroundColor(.white)
Image(systemName: "chevron.up")
.resizable()
.scaledToFit()
.frame(width: 20)
}
.padding(12)
.background(Color(hex: "13181B").opacity(0.7))
.cornerRadius(16)
.frame(width: screenSize().width - 48)
ScrollView(.vertical, showsIndicators: false) {
VStack(spacing: 16) {
Spacer()
ForEach(0..<viewModel.messages.count, id: \.self) {
let message = viewModel.messages[$0]
if message.mine {
UserMessageItemView(message: message)
} else {
AiMessageItemView(
message: message,
characterName: viewModel.characterName
)
}
}
}
.padding(.horizontal, 24)
}
.frame(width: screenSize().width)
.frame(maxHeight: .infinity)
HStack(spacing: 8) {
HStack(spacing: 0) {
ZStack(alignment: .leading) {
if viewModel.messageText.isEmpty {
Text("메시지를 입력하세요.")
.font(.custom(Font.preRegular.rawValue, size: 14))
.foregroundColor(Color(hex: "78909C"))
}
TextField("", text: $viewModel.messageText)
.font(.custom(Font.preRegular.rawValue, size: 14))
.foregroundColor(.white)
.onSubmit {
viewModel.sendMessage()
}
}
.frame(maxWidth: .infinity)
}
.padding(.horizontal, 16)
.padding(.vertical, 13)
.background(Color(hex: "263238"))
.cornerRadius(999)
.overlay(
RoundedRectangle(cornerRadius: 999)
.stroke(Color(hex: "263238"), lineWidth: 1)
)
Button(action: {
UIApplication.shared.sendAction(#selector(UIResponder.resignFirstResponder), to: nil, from: nil, for: nil)
viewModel.sendMessage()
}) {
Image("ic_message_send")
.resizable()
.frame(width: 24, height: 24)
}
}
.padding(.horizontal, 12)
.padding(.vertical, 12)
.frame(width: screenSize().width)
}
}
}
}
struct ChatRoomBgView: View {
let url: String? = nil
var body: some View {
ZStack {
if let url = url {
KFImage(URL(string: url))
.resizable()
.scaledToFill()
.ignoresSafeArea()
} else {
Image("img_sample")
.resizable()
.scaledToFill()
.ignoresSafeArea()
}
Color.black
.opacity(0.6)
.ignoresSafeArea()
} }
} }
} }

View File

@@ -15,8 +15,53 @@ final class ChatRoomViewModel: ObservableObject {
@Published var errorMessage: String = "" @Published var errorMessage: String = ""
@Published var isShowPopup = false @Published var isShowPopup = false
@Published private(set) var characterProfileUrl: String = ""
@Published private(set) var characterName: String = "Character Name"
@Published private(set) var characterType: CharacterType = .Character
// MARK: - Message State
@Published var messageText: String = ""
@Published private(set) var messages: [ServerChatMessage] = [
ServerChatMessage(
messageId: 1,
message: "(만약에) 멈춰 인프피",
profileImageUrl: "",
mine: true,
createdAt: Date().currentTimeMillis(),
messageType: "text",
imageUrl: nil,
price: nil,
hasAccess: true
),
ServerChatMessage(
messageId: 2,
message: "(언제부턴가) 너랑 노는게 제일 재밌고\n너랑 이야기 하는게 제일 신나더라,\n앞으로도 그럴 것 같아❤️",
profileImageUrl: "https://example.com/profile.jpg",
mine: false,
createdAt: Date().currentTimeMillis(),
messageType: "text",
imageUrl: nil,
price: nil,
hasAccess: true
)
]
// MARK: - Private // MARK: - Private
private let userRepository = UserRepository() private let userRepository = UserRepository()
private let repository = ChatRoomRepository() private let repository = ChatRoomRepository()
private var subscription = Set<AnyCancellable>() private var subscription = Set<AnyCancellable>()
// MARK: - Actions
@MainActor
func sendMessage() {
guard !messageText.trimmingCharacters(in: .whitespacesAndNewlines).isEmpty else {
return
}
let message = messageText.trimmingCharacters(in: .whitespacesAndNewlines)
messageText = ""
// TODO:
DEBUG_LOG("메시지 전송: \(message)")
}
} }

View File

@@ -6,13 +6,176 @@
// //
import SwiftUI import SwiftUI
import Kingfisher
struct AiMessageBubbleShape: Shape {
func path(in rect: CGRect) -> Path {
let path = UIBezierPath()
// ( , 4px )
path.move(to: CGPoint(x: 4, y: 0))
// ( 16px )
path.addLine(to: CGPoint(x: rect.width - 16, y: 0))
// (16px )
path.addArc(withCenter: CGPoint(x: rect.width - 16, y: 16),
radius: 16,
startAngle: -CGFloat.pi / 2,
endAngle: 0,
clockwise: true)
// ( 16px )
path.addLine(to: CGPoint(x: rect.width, y: rect.height - 16))
// (16px )
path.addArc(withCenter: CGPoint(x: rect.width - 16, y: rect.height - 16),
radius: 16,
startAngle: 0,
endAngle: CGFloat.pi / 2,
clockwise: true)
// ( 16px )
path.addLine(to: CGPoint(x: 16, y: rect.height))
// (16px )
path.addArc(withCenter: CGPoint(x: 16, y: rect.height - 16),
radius: 16,
startAngle: CGFloat.pi / 2,
endAngle: CGFloat.pi,
clockwise: true)
// ( 4px )
path.addLine(to: CGPoint(x: 0, y: 4))
// (4px )
path.addArc(withCenter: CGPoint(x: 4, y: 4),
radius: 4,
startAngle: CGFloat.pi,
endAngle: -CGFloat.pi / 2,
clockwise: true)
path.close()
return Path(path.cgPath)
}
}
struct AiMessageItemView: View { struct AiMessageItemView: View {
let message: ServerChatMessage
let characterName: String
var body: some View { var body: some View {
Text(/*@START_MENU_TOKEN@*/"Hello, World!"/*@END_MENU_TOKEN@*/) HStack(alignment: .bottom, spacing: 4) {
//
HStack(alignment: .top, spacing: 9) {
//
KFImage(URL(string: message.profileImageUrl))
.placeholder {
Image(systemName: "person.crop.circle")
.resizable()
.scaledToFit()
}
.resizable()
.frame(width: 30, height: 30)
.clipShape(Circle())
//
VStack(alignment: .leading, spacing: 4) {
HStack(spacing: 4) {
Text(characterName)
.font(.custom(Font.preRegular.rawValue, size: 12))
.foregroundColor(.white)
}
//
HStack(spacing: 10) {
styledMessageText(message.message)
.lineLimit(nil)
.multilineTextAlignment(.leading)
}
.padding(.horizontal, 10)
.padding(.vertical, 8)
.background(
Color.black.opacity(0.1)
)
.clipShape(AiMessageBubbleShape())
}
}
//
VStack {
Text(formatTime(from: message.createdAt))
.font(.custom(Font.preRegular.rawValue, size: 10))
.foregroundColor(.white)
}
Spacer()
}
.frame(maxWidth: .infinity, alignment: .leading)
}
private func formatTime(from timestamp: Int64) -> String {
let date = Date(timeIntervalSince1970: TimeInterval(timestamp / 1000))
return date.convertDateFormat(dateFormat: "a h:mm")
}
private func styledMessageText(_ message: String) -> Text {
var result = Text("")
let components = message.components(separatedBy: "(")
for (index, component) in components.enumerated() {
if index == 0 {
//
if !component.isEmpty {
result = result + Text(component)
.font(.custom(Font.preRegular.rawValue, size: 16))
.foregroundColor(.white)
}
} else {
// "("
if let closeIndex = component.firstIndex(of: ")") {
let beforeClose = String(component[..<closeIndex])
let afterClose = String(component[component.index(after: closeIndex)...])
// ( )
result = result + Text("(\(beforeClose))")
.font(.system(size: 16, design: .default).italic())
.foregroundColor(Color(hex: "e2e2e2").opacity(0.49))
// ( )
if !afterClose.isEmpty {
result = result + Text(afterClose)
.font(.custom(Font.preRegular.rawValue, size: 16))
.foregroundColor(.white)
}
} else {
//
result = result + Text("(\(component)")
.font(.custom(Font.preRegular.rawValue, size: 16))
.foregroundColor(.white)
}
}
}
return result
} }
} }
#Preview { #Preview {
AiMessageItemView() AiMessageItemView(
message: ServerChatMessage(
messageId: 1,
message: "(언제부턴가) 너랑 노는게 제일 재밌고\n너랑 이야기 하는게 제일 신나더라,\n앞으로도 그럴 것 같아❤️",
profileImageUrl: "https://example.com/profile.jpg",
mine: false,
createdAt: Date().currentTimeMillis(),
messageType: "text",
imageUrl: nil,
price: nil,
hasAccess: true
),
characterName: "보라"
)
.padding()
.background(Color.black)
} }

View File

@@ -7,12 +7,152 @@
import SwiftUI import SwiftUI
struct UserMessageBubbleShape: Shape {
func path(in rect: CGRect) -> Path {
let path = UIBezierPath()
// ( , 16px )
path.move(to: CGPoint(x: 16, y: 0))
// ( 4px )
path.addLine(to: CGPoint(x: rect.width - 4, y: 0))
// (4px )
path.addArc(withCenter: CGPoint(x: rect.width - 4, y: 4),
radius: 4,
startAngle: -CGFloat.pi / 2,
endAngle: 0,
clockwise: true)
// ( 16px )
path.addLine(to: CGPoint(x: rect.width, y: rect.height - 16))
// (16px )
path.addArc(withCenter: CGPoint(x: rect.width - 16, y: rect.height - 16),
radius: 16,
startAngle: 0,
endAngle: CGFloat.pi / 2,
clockwise: true)
// ( 16px )
path.addLine(to: CGPoint(x: 16, y: rect.height))
// (16px )
path.addArc(withCenter: CGPoint(x: 16, y: rect.height - 16),
radius: 16,
startAngle: CGFloat.pi / 2,
endAngle: CGFloat.pi,
clockwise: true)
// ( 16px )
path.addLine(to: CGPoint(x: 0, y: 16))
// (16px )
path.addArc(withCenter: CGPoint(x: 16, y: 16),
radius: 16,
startAngle: CGFloat.pi,
endAngle: -CGFloat.pi / 2,
clockwise: true)
path.close()
return Path(path.cgPath)
}
}
struct UserMessageItemView: View { struct UserMessageItemView: View {
let message: ServerChatMessage
var body: some View { var body: some View {
Text(/*@START_MENU_TOKEN@*/"Hello, World!"/*@END_MENU_TOKEN@*/) HStack(alignment: .bottom, spacing: 4) {
Spacer()
//
VStack {
Text(formatTime(from: message.createdAt))
.font(.custom(Font.preRegular.rawValue, size: 10))
.foregroundColor(.white)
}
//
HStack(spacing: 9) {
VStack(alignment: .trailing, spacing: 4) {
//
HStack(spacing: 10) {
styledMessageText(message.message)
.lineLimit(nil)
.multilineTextAlignment(.leading)
}
.padding(.horizontal, 10)
.padding(.vertical, 8)
.background(Color.button)
.clipShape(UserMessageBubbleShape())
}
}
}
.frame(maxWidth: .infinity, alignment: .trailing)
}
private func formatTime(from timestamp: Int64) -> String {
let date = Date(timeIntervalSince1970: TimeInterval(timestamp / 1000))
return date.convertDateFormat(dateFormat: "a h:mm")
}
private func styledMessageText(_ message: String) -> Text {
var result = Text("")
let components = message.components(separatedBy: "(")
for (index, component) in components.enumerated() {
if index == 0 {
//
if !component.isEmpty {
result = result + Text(component)
.font(.custom(Font.preRegular.rawValue, size: 16))
.foregroundColor(.white)
}
} else {
// "("
if let closeIndex = component.firstIndex(of: ")") {
let beforeClose = String(component[..<closeIndex])
let afterClose = String(component[component.index(after: closeIndex)...])
// ( )
result = result + Text("(\(beforeClose))")
.font(.system(size: 16, design: .default).italic())
.foregroundColor(Color(hex: "333333"))
// ( )
if !afterClose.isEmpty {
result = result + Text(afterClose)
.font(.custom(Font.preRegular.rawValue, size: 16))
.foregroundColor(.white)
}
} else {
//
result = result + Text("(\(component)")
.font(.custom(Font.preRegular.rawValue, size: 16))
.foregroundColor(.white)
}
}
}
return result
} }
} }
#Preview { #Preview {
UserMessageItemView() UserMessageItemView(
message: ServerChatMessage(
messageId: 1,
message: "(만약에) 멈춰 인프피",
profileImageUrl: "",
mine: true,
createdAt: Date().currentTimeMillis(),
messageType: "text",
imageUrl: nil,
price: nil,
hasAccess: true
)
)
.padding()
.background(Color.black)
} }