diff --git a/Projects/App/Sources/Navigation/Battle/BattleCoordinator.swift b/Projects/App/Sources/Navigation/Battle/BattleCoordinator.swift index 20c23525..eac6f81e 100644 --- a/Projects/App/Sources/Navigation/Battle/BattleCoordinator.swift +++ b/Projects/App/Sources/Navigation/Battle/BattleCoordinator.swift @@ -73,6 +73,11 @@ private extension BattleCoordinator { state.routes.push(.chatRoom(.init(route: .init(battleId: battleId)))) return .none + case let .routeAction(_, action: .battle(.delegate(.openPerspective(battleId)))): + // Android: 이미 참여한 배틀은 관점 화면으로 바로 간다. + state.routes.push(.chat(.init(route: .comment(battleId: battleId)))) + return .none + case .routeAction(_, action: .chatRoom(.delegate(.dismiss))): return .send(.view(.backAction)) diff --git a/Projects/App/Sources/Navigation/Chat/ChatCoordinator.swift b/Projects/App/Sources/Navigation/Chat/ChatCoordinator.swift index 13ee22af..cfa1d4b0 100644 --- a/Projects/App/Sources/Navigation/Chat/ChatCoordinator.swift +++ b/Projects/App/Sources/Navigation/Chat/ChatCoordinator.swift @@ -157,6 +157,9 @@ extension ChatCoordinator { } return .none + case .routeAction(_, action: .preVote(.delegate(.openExplore))): + return .send(.delegate(.openExplore)) + case .routeAction(_, action: .chatRoom(.delegate(.dismiss))): return .send(.view(.backAction)) @@ -259,7 +262,7 @@ extension ChatCoordinator { action: ChatDelegate ) -> Effect { switch action { - case .dismiss, .popToRoot: + case .dismiss, .popToRoot, .openExplore: .none } } diff --git a/Projects/App/Sources/Navigation/Class/ClassCoordinator.swift b/Projects/App/Sources/Navigation/Class/ClassCoordinator.swift index 35584024..5a8cd372 100644 --- a/Projects/App/Sources/Navigation/Class/ClassCoordinator.swift +++ b/Projects/App/Sources/Navigation/Class/ClassCoordinator.swift @@ -100,7 +100,7 @@ public struct ClassCoordinator { requestID: UUID, room: ClassRoom, members: [ClassMember], - currentMemberID: Int + currentMemberID: Int? ) case membersFailed( routeID: Int, @@ -243,6 +243,16 @@ private extension ClassCoordinator { case .dismiss, .presented(.delegate(.dismiss)): state.deadlineSelection = nil case let .presented(.delegate(.confirmed(deadline, settingInstanceID: instanceID))): + if case var .classEdit(edit)? = state.routes.last?.screen { + guard state.deadlineSelection?.settingInstanceID == instanceID, + edit.instanceID == instanceID + else { return .none } + edit.deadline = deadline + edit.deadlineValidationMessage = nil + state.routes[screenAt: state.routes.count - 1] = .classEdit(edit) + state.deadlineSelection = nil + return .none + } guard state.deadlineSelection?.settingInstanceID == instanceID, case var .setting(setting)? = state.routes.last?.screen, setting.instanceID == instanceID, setting.canEditDeadline @@ -289,38 +299,7 @@ private extension ClassCoordinator { editor.room.id == room.id, editor.isSaving else { return .none } - for (index, route) in state.routes.enumerated() { - switch route.screen { - case var .myClasses(list): - for roomIndex in list.rooms.indices where list.rooms[roomIndex].id == room.id { - list.rooms[roomIndex] = room - } - if list.viewState == .loaded || list.viewState == .empty { - list.viewState = list.visibleRooms.isEmpty ? .empty : .loaded - } - state.routes[screenAt: index] = .myClasses(list) - case var .detail(detail) where detail.room.id == room.id: - detail.room = room - state.routes[screenAt: index] = .detail(detail) - case var .ownerDashboard(dashboard) where dashboard.room.id == room.id: - dashboard.room = room - state.routes[screenAt: index] = .ownerDashboard(dashboard) - case var .closedBattle(closed) where closed.room.id == room.id: - closed.room = room - state.routes[screenAt: index] = .closedBattle(closed) - case var .members(member) where member.room.id == room.id: - member.room = room - state.routes[screenAt: index] = .members(member) - case var .report(report) where report.room.id == room.id: - report.room = room - state.routes[screenAt: index] = .report(report) - default: - break - } - } - for (battleID, cachedRoom) in state.chatRoomsByBattleID where cachedRoom.id == room.id { - state.chatRoomsByBattleID[battleID] = room - } + applyUpdatedRoom(state: &state, room: room) state.deadlineEdit = nil return .none @@ -329,6 +308,45 @@ private extension ClassCoordinator { } } + /// 마감일·이름 변경 결과를 스택의 모든 화면과 채팅방 캐시에 반영한다. + func applyUpdatedRoom( + state: inout State, + room: ClassRoom + ) { + for (index, route) in state.routes.enumerated() { + switch route.screen { + case var .myClasses(list): + for roomIndex in list.rooms.indices where list.rooms[roomIndex].id == room.id { + list.rooms[roomIndex] = room + } + if list.viewState == .loaded || list.viewState == .empty { + list.viewState = list.visibleRooms.isEmpty ? .empty : .loaded + } + state.routes[screenAt: index] = .myClasses(list) + case var .detail(detail) where detail.room.id == room.id: + detail.room = room + state.routes[screenAt: index] = .detail(detail) + case var .ownerDashboard(dashboard) where dashboard.room.id == room.id: + dashboard.room = room + state.routes[screenAt: index] = .ownerDashboard(dashboard) + case var .closedBattle(closed) where closed.room.id == room.id: + closed.room = room + state.routes[screenAt: index] = .closedBattle(closed) + case var .members(member) where member.room.id == room.id: + member.room = room + state.routes[screenAt: index] = .members(member) + case var .report(report) where report.room.id == room.id: + report.room = room + state.routes[screenAt: index] = .report(report) + default: + break + } + } + for (battleID, cachedRoom) in state.chatRoomsByBattleID where cachedRoom.id == room.id { + state.chatRoomsByBattleID[battleID] = room + } + } + func invalidateCompletingJoin(state: inout State) { state.pendingJoinID = nil state.completingJoinCodeInstanceID = nil @@ -1034,9 +1052,36 @@ private extension ClassCoordinator { case let .routeAction(routeID, action: .ownerDashboard(.delegate(.editClass))): guard routeID == state.routes.count - 1, - case let .ownerDashboard(dashboard)? = state.routes.last?.screen + case let .ownerDashboard(dashboard)? = state.routes.last?.screen, + dashboard.room.role == .owner + else { return .none } + state.routes.push(.classEdit(.init(room: dashboard.room))) + return .none + + case let .routeAction(routeID, action: .classEdit(.delegate(.editDeadline(instanceID)))): + guard routeID == state.routes.count - 1, + state.deadlineEdit == nil, + case let .classEdit(edit)? = state.routes.last?.screen, + edit.instanceID == instanceID, edit.hasDeadline + else { return .none } + var selection = ClassDeadlineSelectionFeature.State() + selection.settingInstanceID = instanceID + // Android ClassEdit: 기존 마감일 이후로만 연장할 수 있다. + selection.minimumDate = max(edit.room.deadline, date.now) + selection.draftDeadline = edit.deadline + state.deadlineSelection = selection + return .none + + case .routeAction(_, action: .classEdit(.delegate(.dismiss))): + return .send(.view(.backAction)) + + case let .routeAction(routeID, action: .classEdit(.delegate(.saved(room)))): + guard routeID == state.routes.count - 1, + case .classEdit? = state.routes.last?.screen else { return .none } - return openDeadlineEditor(state: &state, room: dashboard.room) + applyUpdatedRoom(state: &state, room: room) + state.routes.pop() + return .none case .routeAction(_, action: .ownerDashboard(.delegate(.deleteClass))): return returnToClassDetail(state: &state, action: .deleteTapped) @@ -1099,8 +1144,14 @@ private extension ClassCoordinator { case let .routeAction(routeID, action: .battleFlow(.delegate(.dismiss))): guard routeID == state.routes.count - 1, - case .battleFlow? = state.routes.last?.screen else { return .none } - return .send(.view(.backAction)) + case let .battleFlow(flow)? = state.routes.last?.screen else { return .none } + state.routes.goBack() + // 운영자 본인 참여처럼 배틀을 마치면 서버 인원 수가 바뀐다. 상세로 돌아오면 다시 받아 숫자를 맞춘다. + guard let roomID = flow.room?.id, + case let .detail(detail)? = state.routes.last?.screen, + detail.room.id == roomID + else { return .none } + return fetchDetail(state: &state, routeID: state.routes.count - 1) case let .routeAction(routeID, action: .battleFlow(.delegate(.openReport(classID: classID)))): guard routeID == state.routes.count - 1, @@ -1286,8 +1337,9 @@ private extension ClassCoordinator { else { return .none } switch result { case let .success(room): - guard room.id == roomID else { return .none } - return openDeadlineEditor(state: &state, room: room) + guard room.id == roomID, room.role == .owner else { return .none } + state.routes.push(.classEdit(.init(room: room))) + return .none case let .failure(error): list.customAlert = .alert( title: "클래스 정보를 불러오지 못했어요", @@ -1458,6 +1510,7 @@ extension ClassCoordinator { case recommend(ClassRecommendFeature) case battlePreview(ClassBattlePreviewFeature) case setting(ClassSettingFeature) + case classEdit(ClassEditFeature) case share(ClassShareFeature) case ownerName(ClassJoinFeature) case myClasses(MyClassFeature) diff --git a/Projects/App/Sources/Navigation/Class/ClassCoordinatorView.swift b/Projects/App/Sources/Navigation/Class/ClassCoordinatorView.swift index 42d3b21a..3509a656 100644 --- a/Projects/App/Sources/Navigation/Class/ClassCoordinatorView.swift +++ b/Projects/App/Sources/Navigation/Class/ClassCoordinatorView.swift @@ -46,6 +46,10 @@ public struct ClassCoordinatorView: View { case let .setting(settingStore): ClassSettingView(store: settingStore) + case let .classEdit(editStore): + ClassEditView(store: editStore) + .toolbar(.hidden, for: .tabBar) + case let .share(shareStore): ClassShareView(store: shareStore) diff --git a/Projects/App/Sources/Navigation/MainTab/MainTabCoordinator.swift b/Projects/App/Sources/Navigation/MainTab/MainTabCoordinator.swift index e5174dbb..5a3a03e1 100644 --- a/Projects/App/Sources/Navigation/MainTab/MainTabCoordinator.swift +++ b/Projects/App/Sources/Navigation/MainTab/MainTabCoordinator.swift @@ -200,6 +200,27 @@ public struct MainTabCoordinator { state.selectedTab = Tab.myPage.rawValue return .none + // Android `navigateToTab(Explore)` — 투표 포인트 부족 안내에서 배틀 흐름을 닫고 탐색 탭으로 간다. + case .home(.router(.routeAction(_, action: .chat(.delegate(.openExplore))))): + state.homeState.routes.goBackToRoot() + return .send(.selectTab(Tab.explore.rawValue)) + + case .explore(.router(.routeAction(_, action: .chat(.delegate(.openExplore))))): + state.exploreState.routes.goBackToRoot() + return .none + + case .quickBattle(.router(.routeAction(_, action: .chat(.delegate(.openExplore))))): + state.quickBattleState.routes.goBackToRoot() + return .send(.selectTab(Tab.explore.rawValue)) + + case .classroom(.router(.routeAction(_, action: .chat(.delegate(.openExplore))))): + state.classState.routes.goBackToRoot() + return .send(.selectTab(Tab.explore.rawValue)) + + case .myPage(.router(.routeAction(_, action: .chat(.delegate(.openExplore))))): + state.myPageState.routes.goBackToRoot() + return .send(.selectTab(Tab.explore.rawValue)) + case .myPage(.router(.routeAction(_, action: .settings(.delegate(.sessionEnded))))): return .send(.delegate(.sessionEnded)) @@ -249,7 +270,14 @@ private extension MainTabCoordinator { action: .home(.view(.homeTabReselected)) )))) case .explore: - state.exploreState.routes.goBackToRoot() + guard state.exploreState.routes.count == 1 else { + state.exploreState.routes.goBackToRoot() + return .none + } + return .send(.explore(.router(.routeAction( + id: 0, + action: .hifi(.view(.exploreTabReselected)) + )))) case .quickBattle: state.quickBattleState.routes.goBackToRoot() case .classroom: diff --git a/Projects/App/Tests/Sources/ClassCoordinatorTests.swift b/Projects/App/Tests/Sources/ClassCoordinatorTests.swift index b849ffe8..2b6c3f5b 100644 --- a/Projects/App/Tests/Sources/ClassCoordinatorTests.swift +++ b/Projects/App/Tests/Sources/ClassCoordinatorTests.swift @@ -282,7 +282,7 @@ struct ClassCoordinatorTests { } @Test - func 일반_사전투표는_기참여시_기존처럼_자동직행하고_사후투표는_기존_선택을_요구한다() async throws { + func 일반_사전투표는_완료_단계면_자동직행하고_사후투표는_기존_선택을_요구한다() async throws { let session = ClassMockChatSession() let battleAPI: any BattleInterface = session let battleID = await session.register(room: ClassRoom.mocks[0]) @@ -292,9 +292,29 @@ struct ClassCoordinatorTests { content: "의견", optionId: 1 )) + let fetched = try await battleAPI.fetchBattle(battleId: battleID) + func detail(_ step: BattleStep) -> BattleDetail { + BattleDetail( + battleInfo: fetched.battleInfo, + description: fetched.description, + shareUrl: fetched.shareUrl, + userVoteStatus: fetched.userVoteStatus, + currentStep: step, + categoryTags: fetched.categoryTags, + philosopherTags: fetched.philosopherTags, + valueTags: fetched.valueTags + ) + } + // Android BattleRouting: 관점이 있어도 단계가 COMPLETED 가 아니면 사전투표에 머문다. + let listeningStore = TestStore(initialState: PreVoteFeature.State(battleId: battleID)) { PreVoteFeature() } + listeningStore.exhaustivity = .off + await listeningStore.send(.inner(.myPerspectiveResponse(.success(perspective)))) + await listeningStore.send(.inner(.battleDetailResponse(.success(detail(.postVote))))) + #expect(listeningStore.state.battle != nil) + let preStore = TestStore(initialState: PreVoteFeature.State(battleId: battleID)) { PreVoteFeature() } preStore.exhaustivity = .off - await preStore.send(.inner(.myPerspectiveResponse(.success(perspective)))) + await preStore.send(.inner(.battleDetailResponse(.success(detail(.completed))))) await preStore.receive(\.delegate, .alreadyFinalVoted(battleId: battleID)) #expect(!preStore.state.isShowingParticipationResult) @@ -514,12 +534,13 @@ struct ClassCoordinatorTests { ))) await store.finish() - guard case let .ownerDashboard(current)? = store.state.routes.last?.screen else { - Issue.record("운영자 요약 화면이 유지되지 않았습니다.") + // Android ClassEdit 처럼 관리 메뉴 '수정'은 이름·마감일 수정 화면을 연다. + guard case let .classEdit(edit)? = store.state.routes.last?.screen else { + Issue.record("클래스 수정 화면이 열리지 않았습니다.") return } - #expect(current.instanceID == dashboard.instanceID) - #expect(store.state.deadlineEdit?.room == room) + #expect(edit.room == room) + #expect(store.state.deadlineEdit == nil) } @Test @@ -727,8 +748,9 @@ struct ClassCoordinatorTests { .success(room) )) #expect(!store.state.showsTabBar) - await store.send(.deadlineEdit(.presented(.view(.backTapped)))) - await store.receive(\.deadlineEdit.presented.delegate.dismiss) + await store.send(.router(.routeAction(id: 2, action: .classEdit(.view(.backTapped))))) + await store.receive(\.router.routeAction) + await store.receive(\.view.backAction) #expect(store.state.showsTabBar) } @@ -1513,9 +1535,10 @@ struct ClassCoordinatorTests { )))) if edit { #expect(await useCase.cancelledRequestIDs.isEmpty) - #expect(store.state.deadlineEdit?.room == room) - guard case .ownerDashboard? = store.state.routes.last?.screen else { - Issue.record("마감일 편집 시 운영자 보고서가 유지되지 않음") + // 수정은 보고서 위에 클래스 수정 화면을 쌓으므로 보고서 로드는 그대로 둔다. + guard case .classEdit? = store.state.routes.last?.screen, + case .ownerDashboard? = store.state.routes.dropLast().last?.screen else { + Issue.record("클래스 수정 시 운영자 보고서가 유지되지 않음") return } await store.send(.view(.backToRootAction)) @@ -2431,10 +2454,10 @@ struct ClassDeadlineSheetCoordinatorTests { roomID: room.id, .success(room) )) - #expect(store.state.routes.count == 2) - #expect(store.state.deadlineEdit?.room == room) + #expect(store.state.routes.count == 3) + #expect(store.state.routes.last.map { if case .classEdit = $0.screen { true } else { false } } == true) - await store.send(.deadlineEdit(.dismiss)) + await store.send(.view(.backAction)) await store.send(.router(.routeAction(id: 1, action: .myClasses(.delegate(.openRoom(room)))))) await store.send(.router(.routeAction(id: 2, action: .detail(.delegate(.openDeadline(room)))))) #expect(store.state.routes.count == 3) @@ -2443,8 +2466,8 @@ struct ClassDeadlineSheetCoordinatorTests { await store.send(.deadlineEdit(.dismiss)) await store.send(.router(.routeAction(id: 2, action: .detail(.delegate(.openReport(room)))))) await store.send(.router(.routeAction(id: 3, action: .ownerDashboard(.delegate(.editClass))))) - #expect(store.state.routes.count == 4) - #expect(store.state.deadlineEdit?.room == room) + #expect(store.state.routes.count == 5) + #expect(store.state.routes.last.map { if case .classEdit = $0.screen { true } else { false } } == true) } @Test diff --git a/Projects/App/Tests/Sources/MainTabCoordinatorTests.swift b/Projects/App/Tests/Sources/MainTabCoordinatorTests.swift index f1517030..35abf9f2 100644 --- a/Projects/App/Tests/Sources/MainTabCoordinatorTests.swift +++ b/Projects/App/Tests/Sources/MainTabCoordinatorTests.swift @@ -109,8 +109,16 @@ struct MainTabCoordinatorTests { } #expect(events.value == [.tabExplore]) + // 탐색 재선택은 Android 처럼 목록을 맨 위로 올린다(탐색 화면 상태만 바뀐다). + store.exhaustivity = .off await store.send(.tabTapped(MainTabCoordinator.Tab.explore.rawValue)) await store.receive(\.tabReselected, MainTabCoordinator.Tab.explore.rawValue) + await store.receive(\.explore.router.routeAction) + guard case let .hifi(explore) = store.state.exploreState.routes[0].screen else { + Issue.record("탐색 루트 화면이 HifiFeature 가 아님") + return + } + #expect(explore.scrollToTopRequest == 1) await store.send(.tabTapped(-1)) await store.finish() #expect(events.value == [.tabExplore]) diff --git a/Projects/Domain/BattleDomain/Interface/Sources/Entity/Battle/PreVote/PreVoteBattle.swift b/Projects/Domain/BattleDomain/Interface/Sources/Entity/Battle/PreVote/PreVoteBattle.swift index f9a150f2..e5a1674c 100644 --- a/Projects/Domain/BattleDomain/Interface/Sources/Entity/Battle/PreVote/PreVoteBattle.swift +++ b/Projects/Domain/BattleDomain/Interface/Sources/Entity/Battle/PreVote/PreVoteBattle.swift @@ -21,6 +21,14 @@ public struct PreVoteBattle: Equatable, Identifiable { public var id: Int { battleId } + /// Android `title.replace(", ", ",\n")` — 쉼표 뒤에서 줄을 바꾼다. + public var displayTitle: String { + [titleLine1, titleLine2] + .filter { !$0.isEmpty } + .joined(separator: "\n") + .replacingOccurrences(of: ", ", with: ",\n") + } + public init( battleId: Int, backgroundImageURL: String?, diff --git a/Projects/Domain/BattleDomain/Interface/Sources/Entity/BattleError.swift b/Projects/Domain/BattleDomain/Interface/Sources/Entity/BattleError.swift index b924fc0a..5e47b76d 100644 --- a/Projects/Domain/BattleDomain/Interface/Sources/Entity/BattleError.swift +++ b/Projects/Domain/BattleDomain/Interface/Sources/Entity/BattleError.swift @@ -15,6 +15,8 @@ public enum BattleError: LocalizedError, Equatable { case backendError(String) case serverError(Int) case unknown(String) + /// 서버 `CREDIT_400_INSUFFICIENT`: 투표에 필요한 포인트가 부족하다. + case insufficientPoints public var errorDescription: String? { switch self { @@ -32,6 +34,8 @@ public enum BattleError: LocalizedError, Equatable { "서버 오류 (코드: \(code))" case let .unknown(message): "알 수 없는 오류: \(message)" + case .insufficientPoints: + "포인트가 부족합니다" } } @@ -51,6 +55,8 @@ public enum BattleError: LocalizedError, Equatable { "잠시 후 다시 시도해주세요" case .unknown: "예상치 못한 오류가 발생했습니다" + case .insufficientPoints: + "투표에 필요한 포인트가 부족합니다" } } @@ -70,6 +76,8 @@ public enum BattleError: LocalizedError, Equatable { "잠시 후 다시 시도하거나 고객센터에 문의하세요" case .unknown: "문제가 지속되면 고객센터에 문의해주세요" + case .insufficientPoints: + "출석체크로 포인트를 모은 뒤 다시 시도해주세요" } } } diff --git a/Projects/Domain/BattleDomain/Sources/Repository/BattleRepositoryImpl.swift b/Projects/Domain/BattleDomain/Sources/Repository/BattleRepositoryImpl.swift index 363ea399..70fde064 100644 --- a/Projects/Domain/BattleDomain/Sources/Repository/BattleRepositoryImpl.swift +++ b/Projects/Domain/BattleDomain/Sources/Repository/BattleRepositoryImpl.swift @@ -43,10 +43,12 @@ public final class BattleRepositoryImpl: BattleInterface, @unchecked Sendable { battleId: Int, optionId: Int ) async throws -> PreVoteResult { - let data = try await client.send( - BattleService.preVote(battleId: battleId, body: PreVoteRequest(optionId: optionId)), - as: PreVoteDataDTO.self - ) + let data = try await Self.mapInsufficientPoints { + try await client.send( + BattleService.preVote(battleId: battleId, body: PreVoteRequest(optionId: optionId)), + as: PreVoteDataDTO.self + ) + } return data.toDomain() } @@ -64,10 +66,12 @@ public final class BattleRepositoryImpl: BattleInterface, @unchecked Sendable { battleId: Int, optionId: Int ) async throws -> PreVoteResult { - let data = try await client.send( - BattleService.postVote(battleId: battleId, body: PreVoteRequest(optionId: optionId)), - as: PreVoteDataDTO.self - ) + let data = try await Self.mapInsufficientPoints { + try await client.send( + BattleService.postVote(battleId: battleId, body: PreVoteRequest(optionId: optionId)), + as: PreVoteDataDTO.self + ) + } return data.toDomain() } @@ -159,4 +163,16 @@ public final class BattleRepositoryImpl: BattleInterface, @unchecked Sendable { return data.toDomain() } + + /// Android `SubmitVoteUseCase` — 서버 `CREDIT_400_INSUFFICIENT` 는 포인트 부족으로 바꾼다. + private static func mapInsufficientPoints(_ operation: () async throws -> T) async throws -> T { + do { + return try await operation() + } catch let error as PickeNetworkError { + if case let .response(response) = error, response.code == "CREDIT_400_INSUFFICIENT" { + throw BattleError.insufficientPoints + } + throw error + } + } } diff --git a/Projects/Domain/BattleDomain/Tests/Sources/BattleRepositoryTests.swift b/Projects/Domain/BattleDomain/Tests/Sources/BattleRepositoryTests.swift index 2f657b6b..2047683d 100644 --- a/Projects/Domain/BattleDomain/Tests/Sources/BattleRepositoryTests.swift +++ b/Projects/Domain/BattleDomain/Tests/Sources/BattleRepositoryTests.swift @@ -173,6 +173,28 @@ struct BattleRepositoryTests { #expect(result.status == .updated) } + @Test func 투표_포인트_부족_코드는_insufficientPoints_로_바꾼다() async throws { + let json = """ + { + "statusCode": 400, + "data": null, + "error": { "code": "CREDIT_400_INSUFFICIENT", "message": "포인트가 부족합니다" } + } + """ + let repo = withDependencies { + $0.networkClient = StubNetworkClient(stubData: Data(json.utf8)) + } operation: { + BattleRepositoryImpl() + } + + await #expect(throws: BattleError.insufficientPoints) { + try await repo.submitPreVote(battleId: 1, optionId: 7) + } + await #expect(throws: BattleError.insufficientPoints) { + try await repo.submitPostVote(battleId: 1, optionId: 3) + } + } + // MARK: - fetchVoteStats @Test func fetchVoteStats_는_100_초과_ratio_를_비율로_정규화한다() async throws { diff --git a/Projects/Domain/ClassDomain/Interface/Sources/Entity/ClassMember/ClassMemberList.swift b/Projects/Domain/ClassDomain/Interface/Sources/Entity/ClassMember/ClassMemberList.swift index 37dabd1d..36b2cf50 100644 --- a/Projects/Domain/ClassDomain/Interface/Sources/Entity/ClassMember/ClassMemberList.swift +++ b/Projects/Domain/ClassDomain/Interface/Sources/Entity/ClassMember/ClassMemberList.swift @@ -1,10 +1,11 @@ public struct ClassMemberList: Equatable, Sendable { public let members: [ClassMember] - public let currentMemberID: Int + /// 비참여 운영자처럼 명단에 내 행이 없으면 nil. + public let currentMemberID: Int? public init( members: [ClassMember], - currentMemberID: Int + currentMemberID: Int? ) { self.members = members self.currentMemberID = currentMemberID diff --git a/Projects/Domain/ClassDomain/Sources/Model/Mapper/ClassMemberDTO+.swift b/Projects/Domain/ClassDomain/Sources/Model/Mapper/ClassMemberDTO+.swift index f8168db2..2610216e 100644 --- a/Projects/Domain/ClassDomain/Sources/Model/Mapper/ClassMemberDTO+.swift +++ b/Projects/Domain/ClassDomain/Sources/Model/Mapper/ClassMemberDTO+.swift @@ -13,13 +13,11 @@ extension ClassMemberDTO { } extension ClassMemberDTO { - static func toMemberList(_ payload: [Self]) throws -> ClassMemberList { - guard let current = payload.first(where: \.me) else { - throw ClassError.userMessage("내 멤버 정보를 찾을 수 없어요.") - } - return ClassMemberList( + static func toMemberList(_ payload: [Self]) -> ClassMemberList { + // 서버는 참여하지 않은 운영자 행을 명단에 넣지 않는다. 내 행이 없어도 명단은 보여준다(Android 동일). + ClassMemberList( members: payload.map { $0.toDomain() }, - currentMemberID: current.memberId + currentMemberID: payload.first(where: \.me)?.memberId ) } } diff --git a/Projects/Domain/ClassDomain/Sources/Repository/ClassRepositoryImpl+Member.swift b/Projects/Domain/ClassDomain/Sources/Repository/ClassRepositoryImpl+Member.swift index 98eda7e0..9e841992 100644 --- a/Projects/Domain/ClassDomain/Sources/Repository/ClassRepositoryImpl+Member.swift +++ b/Projects/Domain/ClassDomain/Sources/Repository/ClassRepositoryImpl+Member.swift @@ -17,7 +17,7 @@ extension ClassRepositoryImpl { ClassMemberService.members(classID: classID), as: [ClassMemberDTO].self ) - return try ClassMemberDTO.toMemberList(data) + return ClassMemberDTO.toMemberList(data) } catch { throw Self.memberError(error) } diff --git a/Projects/Domain/ClassDomain/Tests/Sources/ClassMemberAPITests.swift b/Projects/Domain/ClassDomain/Tests/Sources/ClassMemberAPITests.swift index a2d9a270..88a9ce83 100644 --- a/Projects/Domain/ClassDomain/Tests/Sources/ClassMemberAPITests.swift +++ b/Projects/Domain/ClassDomain/Tests/Sources/ClassMemberAPITests.swift @@ -35,7 +35,7 @@ struct ClassMemberAPITests { ] """ let payload = try JSONDecoder().decode([ClassMemberDTO].self, from: Data(json.utf8)) - let members = try ClassMemberDTO.toMemberList(payload) + let members = ClassMemberDTO.toMemberList(payload) #expect(members.currentMemberID == 11) #expect(members.members.map(\.id) == [10, 11]) @@ -49,8 +49,9 @@ struct ClassMemberAPITests { [{"memberId":10,"displayName":"운영자","role":"OWNER","characterUrl":null,"me":false}] """ let payload = try JSONDecoder().decode([ClassMemberDTO].self, from: Data(json.utf8)) - #expect(throws: ClassError.userMessage("내 멤버 정보를 찾을 수 없어요.")) { - try ClassMemberDTO.toMemberList(payload) - } + // 참여하지 않은 운영자가 보는 명단처럼 내 행이 없어도 실패하지 않고, 아무도 본인으로 잡지 않는다. + let members = ClassMemberDTO.toMemberList(payload) + #expect(members.currentMemberID == nil) + #expect(members.members.map(\.id) == [10]) } } diff --git a/Projects/Domain/HomeDomain/Interface/Sources/Section/Comment/HomeBestComment.swift b/Projects/Domain/HomeDomain/Interface/Sources/Section/Comment/HomeBestComment.swift index 918c55cc..04a451f8 100644 --- a/Projects/Domain/HomeDomain/Interface/Sources/Section/Comment/HomeBestComment.swift +++ b/Projects/Domain/HomeDomain/Interface/Sources/Section/Comment/HomeBestComment.swift @@ -5,26 +5,26 @@ import Foundation -/// 홈 API가 제공하는 Best 댓글. 없는 battleId는 DTO 매핑에서 제외한다. +/// 홈 Best 댓글 — `GET /api/v1/perspectives/weekly-best` 항목 (Android `HomeBestCommentUiModel`). public struct HomeBestComment: Equatable, Identifiable { + public let perspectiveId: Int public let battleId: Int public let battleTitle: String - public let optionTitle: String public let content: String public var id: Int { - battleId + perspectiveId } public init( + perspectiveId: Int, battleId: Int, battleTitle: String, - optionTitle: String, content: String ) { + self.perspectiveId = perspectiveId self.battleId = battleId self.battleTitle = battleTitle - self.optionTitle = optionTitle self.content = content } } diff --git a/Projects/Domain/HomeDomain/Sources/Model/HomeDataDTO+.swift b/Projects/Domain/HomeDomain/Sources/Model/HomeDataDTO+.swift index 62c1e900..e56c9887 100644 --- a/Projects/Domain/HomeDomain/Sources/Model/HomeDataDTO+.swift +++ b/Projects/Domain/HomeDomain/Sources/Model/HomeDataDTO+.swift @@ -63,14 +63,13 @@ public extension BestBattleDTO { } } -public extension BestCommentDTO { - func toDomain() -> HomeBestComment? { - guard let battleId else { return nil } - return HomeBestComment( +public extension WeeklyBestPerspectiveItemDTO { + func toDomain() -> HomeBestComment { + HomeBestComment( + perspectiveId: perspectiveId, battleId: battleId, - battleTitle: battleTitle ?? "", - optionTitle: optionTitle ?? "", - content: content ?? "" + battleTitle: battleTitle, + content: content ) } } @@ -129,7 +128,7 @@ public extension NewBattleDTO { public extension HomeDataDTO { /// 전체 DTO 를 화면용 도메인 객체 6 묶음으로 변환. - func toDomain() -> HomeBundle { + func toDomain(bestComments: [HomeBestComment] = []) -> HomeBundle { HomeBundle( newNotice: newNotice, heroes: editorPicks.enumerated().map { idx, dto in @@ -139,7 +138,7 @@ public extension HomeDataDTO { bestBattles: bestBattles.enumerated().map { idx, dto in dto.toDomain(rank: idx + 1) }, - bestComments: bestComments?.compactMap { $0.toDomain() } ?? [], + bestComments: bestComments, quizzes: todayQuizzes.map { $0.toDomain() }, votes: todayVotes.map { $0.toDomain() }, newBattles: newBattles.map { $0.toDomain() } diff --git a/Projects/Domain/HomeDomain/Sources/Model/HomeDataDTO.swift b/Projects/Domain/HomeDomain/Sources/Model/HomeDataDTO.swift index 3ff4891b..9a03188e 100644 --- a/Projects/Domain/HomeDomain/Sources/Model/HomeDataDTO.swift +++ b/Projects/Domain/HomeDomain/Sources/Model/HomeDataDTO.swift @@ -15,18 +15,25 @@ public struct HomeDataDTO: Decodable { public let editorPicks: [EditorPickDTO] public let trendingBattles: [TrendingBattleDTO] public let bestBattles: [BestBattleDTO] - public let bestComments: [BestCommentDTO]? public let todayQuizzes: [TodayQuizDTO] public let todayVotes: [TodayVoteDTO] public let newBattles: [NewBattleDTO] } -/// Android 홈 계약의 선택 필드. 현재 서버가 아직 보내지 않는 경우에도 홈 로드는 유지한다. -public struct BestCommentDTO: Decodable { - public let battleId: Int? - public let battleTitle: String? - public let optionTitle: String? - public let content: String? +/// `GET /api/v1/perspectives/weekly-best` 응답 — 홈 Best 댓글 (Android `WeeklyBestPerspectiveResponseDto`). +public struct WeeklyBestPerspectiveDataDTO: Decodable { + public let weekStart: String + public let weekEnd: String + public let items: [WeeklyBestPerspectiveItemDTO] +} + +public struct WeeklyBestPerspectiveItemDTO: Decodable { + public let perspectiveId: Int + public let battleId: Int + public let battleTitle: String + public let content: String + public let likeCount: Int + public let participated: Bool } public struct TagDTO: Decodable, Equatable { diff --git a/Projects/Domain/HomeDomain/Sources/Repository/HomeRepositoryImpl.swift b/Projects/Domain/HomeDomain/Sources/Repository/HomeRepositoryImpl.swift index 72781651..3a7d30ff 100644 --- a/Projects/Domain/HomeDomain/Sources/Repository/HomeRepositoryImpl.swift +++ b/Projects/Domain/HomeDomain/Sources/Repository/HomeRepositoryImpl.swift @@ -20,12 +20,23 @@ public final class HomeRepositoryImpl: HomeInterface, @unchecked Sendable { public init() {} + /// Android `HomeViewModel` 처럼 홈과 주간 베스트 관점을 함께 받아 Best 댓글을 상위 3개로 채운다. + /// 주간 베스트는 운영 서버에 아직 없을 수 있어 실패하면 Best 댓글 섹션만 비운다. public func fetchHome() async throws -> HomeBundle { - let data = try await client.send( + async let home = client.send( HomeService.home, as: HomeDataDTO.self ) + async let weeklyBest = try? client.send( + PerspectiveService.weeklyBest, + as: WeeklyBestPerspectiveDataDTO.self + ) - return data.toDomain() + let bestComments = await weeklyBest?.items + .prefix(Self.bestCommentCount) + .map { $0.toDomain() } ?? [] + return try await home.toDomain(bestComments: bestComments) } + + private static let bestCommentCount = 3 } diff --git a/Projects/Domain/HomeDomain/Tests/Sources/HomeRepositoryTests.swift b/Projects/Domain/HomeDomain/Tests/Sources/HomeRepositoryTests.swift index 8cde60e8..b713a25b 100644 --- a/Projects/Domain/HomeDomain/Tests/Sources/HomeRepositoryTests.swift +++ b/Projects/Domain/HomeDomain/Tests/Sources/HomeRepositoryTests.swift @@ -70,10 +70,6 @@ struct HomeRepositoryTests { "viewCount": 900 } ], - "bestComments": [ - { "battleId": 21, "battleTitle": "인간은 본래 선한가", "optionTitle": "선하다", "content": "선하게 태어나요" }, - { "battleId": null, "battleTitle": "제외", "optionTitle": "", "content": "" } - ], "todayQuizzes": [ { "battleId": 31, @@ -149,10 +145,30 @@ struct HomeRepositoryTests { } """ + private static let weeklyBestEnvelope = """ + { + "statusCode": 200, + "data": { + "weekStart": "2026-11-02", + "weekEnd": "2026-11-08", + "items": [ + { "perspectiveId": 501, "battleId": 21, "battleTitle": "인간은 본래 선한가", "content": "선하게 태어나요", "likeCount": 30, "participated": true }, + { "perspectiveId": 502, "battleId": 22, "battleTitle": "진실을 말해야 하는가", "content": "둘", "likeCount": 20, "participated": false }, + { "perspectiveId": 503, "battleId": 21, "battleTitle": "인간은 본래 선한가", "content": "셋", "likeCount": 10, "participated": false }, + { "perspectiveId": 504, "battleId": 22, "battleTitle": "진실을 말해야 하는가", "content": "넷", "likeCount": 5, "participated": false } + ] + } + } + """ + @Test func fetchHome_성공시_도메인_번들로_매핑된다() async throws { let data = try #require(Self.fullEnvelope.data(using: .utf8)) + let weeklyBest = try #require(Self.weeklyBestEnvelope.data(using: .utf8)) let repository = withDependencies { - $0.networkClient = StubNetworkClient(stubData: data) + $0.networkClient = StubNetworkClient( + stubData: data, + weeklyBestData: weeklyBest + ) } operation: { HomeRepositoryImpl() } @@ -179,12 +195,14 @@ struct HomeRepositoryTests { #expect(bundle.bestBattles[1].rank == 2) #expect(bundle.bestBattles[1].battleId == 22) #expect(bundle.bestBattles[1].tags.isEmpty) - #expect(bundle.bestComments == [HomeBestComment( + // Android 처럼 주간 베스트 관점 상위 3개만 쓴다. + #expect(bundle.bestComments.map(\.perspectiveId) == [501, 502, 503]) + #expect(bundle.bestComments[0] == HomeBestComment( + perspectiveId: 501, battleId: 21, battleTitle: "인간은 본래 선한가", - optionTitle: "선하다", content: "선하게 태어나요" - )]) + )) #expect(bundle.quizzes.count == 1) #expect(bundle.quizzes[0].isCorrectA == true) @@ -201,6 +219,25 @@ struct HomeRepositoryTests { #expect(bundle.newBattles[0].philosopherBImageURL == URL(string: "https://example.com/philo-b.png")) } + @Test func fetchHome_주간_베스트가_실패해도_홈은_불러오고_Best_댓글만_비운다() async throws { + let data = try #require(Self.fullEnvelope.data(using: .utf8)) + let weeklyBestFailure = try #require(Self.emptyDataEnvelope.data(using: .utf8)) + let repository = withDependencies { + $0.networkClient = StubNetworkClient( + stubData: data, + weeklyBestData: weeklyBestFailure + ) + } operation: { + HomeRepositoryImpl() + } + + let bundle = try await repository.fetchHome() + + #expect(bundle.newNotice == true) + #expect(bundle.bestBattles.count == 2) + #expect(bundle.bestComments.isEmpty) + } + @Test func fetchHome_빈_섹션이면_빈_배열로_매핑된다() async throws { let data = try #require(Self.emptyEnvelope.data(using: .utf8)) let repository = withDependencies { diff --git a/Projects/Domain/HomeDomain/Tests/Sources/TestSupport.swift b/Projects/Domain/HomeDomain/Tests/Sources/TestSupport.swift index e922f095..f3bd9f9c 100644 --- a/Projects/Domain/HomeDomain/Tests/Sources/TestSupport.swift +++ b/Projects/Domain/HomeDomain/Tests/Sources/TestSupport.swift @@ -8,6 +8,7 @@ import Foundation import Testing +import APIEndpoint import PickeNetwork /// 고정 데이터를 서버 응답 봉투(`{ statusCode, data, error }`)로 해석해 돌려주는 스텁 클라이언트. @@ -26,12 +27,17 @@ struct StubNetworkClient: PickeNetworkClient { let stubData: Data var statusCode: Int = 200 + /// 주간 베스트 관점 요청에만 돌려줄 응답. nil 이면 `stubData` 를 쓴다. + var weeklyBestData: Data? func send( - _: some PickeDataRequest, + _ request: some PickeDataRequest, as _: T.Type ) async throws(PickeNetworkError) -> T { - try decode(T.self) + if let weeklyBestData, request.path == PerspectiveService.weeklyBest.path { + return try decode(T.self, from: weeklyBestData) + } + return try decode(T.self) } func send(_: R) async throws(PickeNetworkError) -> R.Response { @@ -48,10 +54,13 @@ struct StubNetworkClient: PickeNetworkClient { func upload(_: some PickeFileUploadRequest) async throws(PickeNetworkError) {} - private func decode(_: T.Type) throws(PickeNetworkError) -> T { + private func decode( + _: T.Type, + from source: Data? = nil + ) throws(PickeNetworkError) -> T { let envelope: Envelope do { - envelope = try JSONDecoder().decode(Envelope.self, from: stubData) + envelope = try JSONDecoder().decode(Envelope.self, from: source ?? stubData) } catch { throw .decoding(.failed(error)) } diff --git a/Projects/Domain/SearchDomain/Sources/SearchBattleDataDTO+.swift b/Projects/Domain/SearchDomain/Sources/SearchBattleDataDTO+.swift index 0344d250..7e030d1a 100644 --- a/Projects/Domain/SearchDomain/Sources/SearchBattleDataDTO+.swift +++ b/Projects/Domain/SearchDomain/Sources/SearchBattleDataDTO+.swift @@ -31,9 +31,8 @@ public extension SearchBattleDTO { ) } - /// 초 단위 오디오 길이를 분으로 환산 (최소 1분). + /// Android `audioDuration / 60` — 초를 분으로 내림한다(60초 미만은 0분). private static func toMinutes(_ seconds: Int) -> Int { - guard seconds > 0 else { return 0 } - return max(1, Int((Double(seconds) / 60).rounded())) + max(0, seconds) / 60 } } diff --git a/Projects/Feature/Battle/Sources/Main/Model/DailyBattle.swift b/Projects/Feature/Battle/Sources/Main/Model/DailyBattle.swift index 18bc0dad..62e2295b 100644 --- a/Projects/Feature/Battle/Sources/Main/Model/DailyBattle.swift +++ b/Projects/Feature/Battle/Sources/Main/Model/DailyBattle.swift @@ -8,7 +8,6 @@ import Foundation import BattleDomainInterface -import PickeCoreUtility public struct DailyBattle: Equatable, Identifiable { public var battleId: Int @@ -57,6 +56,11 @@ public struct DailyBattle: Equatable, Identifiable { self.stance = stance self.quote = quote } + + /// Android `OpinionCard` — 인용구를 큰따옴표로 감싼다. + public var quotedText: String { + "\"\(quote)\"" + } } /// 서버 `BattleInfo`(오늘의 배틀 아이템) → 화면 모델 매핑. @@ -67,7 +71,8 @@ public struct DailyBattle: Equatable, Identifiable { tags: info.tags.map(\.name), title: info.title, question: info.summary, - durationText: info.audioDuration.durationText, + // Android `TodayBattleItem.toUiModel` — 초를 분으로 올림해 "N분" 으로 표기한다. + durationText: "\((info.audioDuration + 59) / 60)분", options: info.options.prefix(2).map { // API title = 짧은 입장 라벨("선하다"), API stance = 설명 문장(긴 인용구). Option(id: $0.optionId, representative: $0.representative, stance: $0.title, quote: $0.stance) diff --git a/Projects/Feature/Battle/Sources/Main/Reducer/BattleFeature.swift b/Projects/Feature/Battle/Sources/Main/Reducer/BattleFeature.swift index 00d1b6aa..f8f56e3e 100644 --- a/Projects/Feature/Battle/Sources/Main/Reducer/BattleFeature.swift +++ b/Projects/Feature/Battle/Sources/Main/Reducer/BattleFeature.swift @@ -34,12 +34,20 @@ public struct BattleFeature { public var votedBattleIds: Set = [] /// 시스템 공유 시트 트리거. public var shareItem: ShareItem? + /// Android `isEntering` — 입장 요청 중에는 버튼을 막는다. + public var isEntering: Bool = false + /// Android 불러오기 실패 토스트 문구. 보여준 뒤 `toastShown` 으로 비운다. + public var toastMessage: String? public init() {} public func selectedOption(for battleId: Int) -> Int? { selectedOptionByBattle[battleId] } + + public func isEnterEnabled(for battleId: Int) -> Bool { + selectedOptionByBattle[battleId] != nil && !isEntering + } } public enum Action: ViewAction, BindableAction { @@ -58,20 +66,26 @@ public struct BattleFeature { case optionTapped(battleId: Int, optionId: Int) case enterBattleTapped(battleId: Int) case pagingTapped(index: Int) + case toastShown } public enum AsyncAction: Equatable { case fetchRequested case prepareShare(ShareContent) + case checkEntryStep(battleId: Int, optionId: Int) + case submitPreVote(battleId: Int, optionId: Int) } public enum InnerAction: Equatable { case todayResponse(Result) case sharePrepared(ShareItem) + case entryStepResponse(battleId: Int, optionId: Int, Result) + case preVoteResponse(battleId: Int, Result) } nonisolated enum CancelID: Hashable { case fetchToday + case enter } @Dependency(\.battleUseCase) private var battleUseCase @@ -79,8 +93,10 @@ public struct BattleFeature { @Dependency(\.shareUseCase) private var shareUseCase public enum DelegateAction: Equatable { - /// 배틀 입장 → 채팅방 진입 + /// 배틀 입장(사전투표 완료) → 채팅방 진입 case openBattle(battleId: Int) + /// 이미 참여한 배틀 → 관점(댓글) 화면 진입 + case openPerspective(battleId: Int) /// 상단 백탭 → 홈 탭으로 복귀 case backToHome } @@ -143,20 +159,22 @@ extension BattleFeature { case let .optionTapped(battleId, optionId): analyticsUseCase.track(.uiAction(action: .quickBattleOption, screen: .quickBattle)) - // 같은 옵션 재탭 시 해제, 아니면 선택. - if state.selectedOptionByBattle[battleId] == optionId { - state.selectedOptionByBattle[battleId] = nil - } else { - state.selectedOptionByBattle[battleId] = optionId - } + // Android 는 같은 카드를 다시 눌러도 선택을 유지한다. + state.selectedOptionByBattle[battleId] = optionId + return .none + + case .toastShown: + state.toastMessage = nil return .none case let .enterBattleTapped(battleId): analyticsUseCase.track(.uiAction(action: .quickBattleEnter, screen: .quickBattle)) - // 선택해야만 입장 가능. 입장 시 투표 확정 → 복귀 시 옵션 변경 비활성화. - guard state.selectedOptionByBattle[battleId] != nil else { return .none } - state.votedBattleIds.insert(battleId) - return .send(.delegate(.openBattle(battleId: battleId))) + // Android `enterBattle` — 배틀 단계를 확인해 처음이면 선택한 옵션으로 사전투표를 낸 뒤 입장한다. + guard state.isEnterEnabled(for: battleId), + let optionId = state.selectedOptionByBattle[battleId] + else { return .none } + state.isEntering = true + return .send(.async(.checkEntryStep(battleId: battleId, optionId: optionId))) } } @@ -180,6 +198,26 @@ extension BattleFeature { return .run { [useCase = shareUseCase] send in await send(.inner(.sharePrepared(useCase.makeShareItem(content)))) } + + case let .checkEntryStep(battleId, optionId): + return .run { [useCase = battleUseCase] send in + let result = await Result { + try await useCase.fetchBattle(battleId: battleId).currentStep + } + .mapError(BattleError.from) + return await send(.inner(.entryStepResponse(battleId: battleId, optionId: optionId, result))) + } + .cancellable(id: CancelID.enter, cancelInFlight: true) + + case let .submitPreVote(battleId, optionId): + return .run { [useCase = battleUseCase] send in + let result = await Result { + try await useCase.submitPreVote(battleId: battleId, optionId: optionId) + } + .mapError(BattleError.from) + return await send(.inner(.preVoteResponse(battleId: battleId, result))) + } + .cancellable(id: CancelID.enter, cancelInFlight: true) } } @@ -192,9 +230,11 @@ extension BattleFeature { state.viewState = .loaded switch result { case let .success(page): - state.battles = page.items.map(DailyBattle.from) + // Android `items.take(1)` — 첫 배틀 하나만 보인다. + state.battles = page.items.prefix(1).map(DailyBattle.from) case let .failure(error): state.battles = [] + state.toastMessage = "정보를 불러오지 못했어요" PickeLogger.error("[BattleFeature] fetchTodayBattles failed: \(error.localizedDescription)", category: .ui) } return .none @@ -202,6 +242,32 @@ extension BattleFeature { case let .sharePrepared(item): state.shareItem = item return .none + + case let .entryStepResponse(battleId, optionId, result): + // Android: 단계가 NONE 이거나 조회에 실패하면 사전투표, 그 밖에는 관점 화면으로 간다. + if case let .success(step) = result, step != .none { + state.isEntering = false + return .send(.delegate(.openPerspective(battleId: battleId))) + } + return .send(.async(.submitPreVote(battleId: battleId, optionId: optionId))) + + case let .preVoteResponse(battleId, result): + state.isEntering = false + switch result { + case .success: + analyticsUseCase.track( + .battleStep(BattleStepData(stepName: .preVote, contentID: "\(battleId)")) + ) + state.votedBattleIds.insert(battleId) + return .send(.delegate(.openBattle(battleId: battleId))) + case .failure(.insufficientPoints): + state.toastMessage = "포인트가 부족합니다." + return .none + case let .failure(error): + PickeLogger.error("[BattleFeature] submitPreVote failed: \(error.localizedDescription)", category: .ui) + state.toastMessage = "요청을 처리하지 못했어요" + return .none + } } } } diff --git a/Projects/Feature/Battle/Sources/Main/View/BattleView.swift b/Projects/Feature/Battle/Sources/Main/View/BattleView.swift index 0cff6a46..a86d09df 100644 --- a/Projects/Feature/Battle/Sources/Main/View/BattleView.swift +++ b/Projects/Feature/Battle/Sources/Main/View/BattleView.swift @@ -30,10 +30,9 @@ public struct BattleView: View { } public var body: some View { - // ZStack 은 safe-area 존중(ignoresSafeArea 미적용) → appBar 가 노치 아래 + 항상 최상단 탭 가능. - // 배경/pager 는 각자 내부에서 ignoresSafeArea 로 풀블리드 유지. + // Android `TodayBattleScreen` — 화면 배경은 순수 검정. ZStack { - Color.neutral900.ignoresSafeArea() + Color.black.ignoresSafeArea() if store.viewState == .loading { BattleSkeletonView() @@ -44,10 +43,9 @@ public struct BattleView: View { } } .frame(maxWidth: .infinity, maxHeight: .infinity) - // PreVoteView 패턴: 상단 paging 바 + 앱바를 overlay 로 올려 항상 최상단·탭 가능하게. .overlay(alignment: .top) { - VStack(spacing: 14) { - // 배틀이 여러 건일 때만 상단 paging 바 노출. 터치 시 해당 배틀로 이동. + VStack(spacing: 0) { + // 배틀이 여러 건일 때만 상단 paging 바 노출(Android: 위·좌우 16). if store.battles.count > 1 { BattlePagingBar( pageCount: store.battles.count, @@ -59,15 +57,20 @@ public struct BattleView: View { withAnimation(.easeInOut(duration: 0.25)) { currentBattleId = id } } ) + .padding([.horizontal, .top], 16) } appBar() } - .padding(.top, 10) .zIndex(10) } .navigationBarHidden(true) .hidesSystemBars() .onAppear { send(.onAppear) } + .onChange(of: store.toastMessage, initial: true) { _, message in + guard let message else { return } + ToastManager.shared.showError(message) + send(.toastShown) + } // 데이터 로드 후 첫 페이지를 현재 배틀로 초기화 (스크롤 전엔 scrollPosition 이 nil). .onChange(of: store.battles.map(\.id)) { _, ids in if currentBattleId == nil { currentBattleId = ids.first } @@ -79,7 +82,7 @@ public struct BattleView: View { } } -// MARK: - Pager (세로 페이징) +// MARK: - Pager private extension BattleView { @ViewBuilder @@ -88,7 +91,8 @@ private extension BattleView { ScrollView(.vertical, showsIndicators: false) { LazyVStack(spacing: 0) { ForEach(store.battles) { battle in - battlePage(battle, size: proxy.size) + battlePage(battle) + .frame(width: proxy.size.width, height: proxy.size.height) } } .scrollTargetLayout() @@ -97,142 +101,139 @@ private extension BattleView { .scrollPosition(id: $currentBattleId) .scrollDisabled(store.battles.count <= 1) } - .ignoresSafeArea() } - // PreVoteView 패턴: 배경 이미지와 콘텐츠 각각에 proxy 폭을 명시해 폭을 제약한다. + /// Android `BattleContent` + 하단 바 — 히어로(남는 높이 전부) → 32 → 선택지 → 16 → 버튼(16/16/16/20). @ViewBuilder - func battlePage(_ battle: DailyBattle, size: CGSize) -> some View { - ZStack(alignment: .bottom) { - backgroundImage(battle.imageURL) - .frame(width: size.width, height: size.height) - - bottomContent(battle) - .frame(width: size.width) + func battlePage(_ battle: DailyBattle) -> some View { + VStack(spacing: 0) { + hero(battle) + .frame(maxWidth: .infinity, maxHeight: .infinity) + vsOptions(battle) + .padding(.horizontal, 16) + .padding(.top, 32) + .padding(.bottom, 16) + enterButton(battle) + .padding(.horizontal, 16) + .padding(.top, 16) + .padding(.bottom, 20) } - .frame(width: size.width, height: size.height) } } -// MARK: - Background +// MARK: - Hero private extension BattleView { + /// 이미지를 꽉 채우고 위→아래 `[검정 0.2, 검정 0.6, 검정]` 그라데이션, 내용은 아래 가운데. @ViewBuilder - func backgroundImage(_ imageURL: String?) -> some View { - ZStack { - if let imageURL, let url = URL(string: imageURL) { - PickeRemoteImage(url: url) { Color.neutral800 } - } else { - Color.neutral800 - } + func hero(_ battle: DailyBattle) -> some View { + ZStack(alignment: .bottom) { + Color.clear + .overlay { + PickeRemoteImage(url: battle.imageURL) { + SkeletonView(.rect, base: .gray600, highlight: .gray400) + } + } + .overlay { + LinearGradient( + colors: [.black.opacity(0.2), .black.opacity(0.6), .black], + startPoint: .top, + endPoint: .bottom + ) + } + .clipped() + .ignoresSafeArea(edges: .top) - LinearGradient( - stops: [ - .init(color: .neutral900.opacity(0), location: 0), - .init(color: .neutral900.opacity(0.85), location: 0.55), - .init(color: .neutral900, location: 1), - ], - startPoint: .top, - endPoint: .bottom - ) + contentSection(battle) + .padding(.horizontal, 16) } - .frame(maxWidth: .infinity, maxHeight: .infinity) - .clipped() } } // MARK: - App Bar private extension BattleView { + /// 뒤로 가기는 iOS 기존 상단 바(`PickeNavigationBar`)를 유지하고, 공유만 Android 아이콘을 쓴다. 빈 화면에는 뒤로만. @ViewBuilder func appBar() -> some View { PickeNavigationBar(onBack: { send(.backTapped) }) { - // 데이터 없을 땐 공유 숨김. if let battleId = currentBattleId ?? store.battles.first?.battleId { Button { send(.shareTapped(battleId: battleId)) } label: { - Image(systemName: "square.and.arrow.up") - .font(.system(size: 18, weight: .semibold)) + Image(asset: .share) + .renderingMode(.template) + .resizable() + .scaledToFit() .frame(width: 24, height: 24) } .buttonStyle(.plain) + .accessibilityLabel("공유") } } - .foregroundStyle(.beige50) + .foregroundStyle(.textInverse) .contentShape(Rectangle()) } } -// MARK: - Bottom Content +// MARK: - Content private extension BattleView { - @ViewBuilder - func bottomContent(_ battle: DailyBattle) -> some View { - VStack(spacing: 32) { - contentSection(battle) - vsOptions(battle) - enterButton(battle) - } - .frame(maxWidth: .infinity) - .padding(.horizontal, 16) - .padding(.bottom, 40) - } - @ViewBuilder func contentSection(_ battle: DailyBattle) -> some View { - VStack(spacing: 16) { - VStack(spacing: 12) { - VStack(spacing: 20) { - tagsRow(battle.tags) - Text(battle.title) - .pretendardFont(.bold24) - .foregroundStyle(.beige50) - .kerning(-0.6) - .multilineTextAlignment(.center) - .lineSpacing(24 * 0.18) - .lineLimit(2) - .minimumScaleFactor(0.85) - .fixedSize(horizontal: false, vertical: true) - } - - if !battle.question.isEmpty { - Text(battle.question) - .pretendardFont(.bodyMedium) - .foregroundStyle(.gray300) - .multilineTextAlignment(.center) - .fixedSize(horizontal: false, vertical: true) - } - } - + VStack(spacing: 0) { + tagsRow(battle.tags) + Text(battle.title) + .pretendardFont(.bold24, lineSpacingMultiple: 1.3) + .foregroundStyle(.textInverse) + .multilineTextAlignment(.center) + .fixedSize(horizontal: false, vertical: true) + .padding(.top, 20) + Text(battle.question) + .pretendardFont(.bodyMedium, lineSpacingMultiple: 1.4) + .foregroundStyle(.textMuted) + .multilineTextAlignment(.center) + .fixedSize(horizontal: false, vertical: true) + .padding(.top, 12) durationBadge(battle.durationText) + .padding(.top, 16) } + .frame(maxWidth: .infinity) } + /// Android 태그 — `beige600` 면, radius 2, 최소 높이 20·가로 4, 12 SemiBold `textPrimary`, 간격 8. @ViewBuilder func tagsRow(_ tags: [String]) -> some View { - HStack(spacing: 9) { + HStack(spacing: 8) { ForEach(Array(tags.enumerated()), id: \.offset) { _, tag in Text("#\(tag)") - .pickeBadge(.filled, size: .tag) + .pretendardFont(.semiBold12) + .foregroundStyle(.textPrimary) + .padding(.horizontal, 4) + .frame(minHeight: 20) + .background(.beige600, in: RoundedRectangle(cornerRadius: .radiusDefault)) } } } + /// Android 시간 뱃지 — 테두리 1 `gray300` radius 2, 안쪽 13/7, 시계 16 + 4 + 12 SemiBold `textMuted`. @ViewBuilder func durationBadge(_ text: String) -> some View { HStack(spacing: 4) { - Image(systemName: "clock") - .font(.system(size: 11, weight: .semibold)) + Image(asset: .clock) + .renderingMode(.template) + .resizable() + .scaledToFit() + .frame(width: 16, height: 16) Text(text) .pretendardFont(.semiBold12) } - .foregroundStyle(.gray300) - .padding(.horizontal, 12) - .padding(.vertical, 6) - .roundedBorder(.gray500) + .foregroundStyle(.textMuted) + .padding(.horizontal, 13) + .padding(.vertical, 7) + .roundedBorder(.gray300) } } -// MARK: - VS Options (세로 카드 + VS 배지) +// MARK: - VS Options private extension BattleView { @ViewBuilder @@ -249,12 +250,13 @@ private extension BattleView { } if options.count > 1 { - vsBadge() + vsBadge } } } - /// 선택 시 picke.pen 강조(neutral900 배경 + 골드 테두리), 미선택은 gray700. + /// Android `OpinionCard` — 최소 높이 140, 안쪽 20/24, 이름 10 Bold `textSecondary` → 8 → 입장 18 SemiBold + /// `textInverse` → 10 → 인용 12 Medium `textMuted`. 선택 `gray900` + `secondary500` 테두리, 그 외 `gray700`. @ViewBuilder func optionCard( _ option: DailyBattle.Option, @@ -265,72 +267,83 @@ private extension BattleView { VStack(spacing: 0) { Text(option.representative) .pretendardFont(.bold10) - .foregroundStyle(.secondary500) - .kerning(1.5) - .padding(.bottom, 8) - + .foregroundStyle(.textSecondary) Text(option.stance) - .pretendardFont(.bold18) - .foregroundStyle(.beige50) - .kerning(-0.45) - .multilineTextAlignment(.center) - .lineLimit(1) - .minimumScaleFactor(0.8) - .padding(.horizontal, 20) - - if !option.quote.isEmpty { - Text(option.quote) - .pretendardFont(.labelSmall) - .foregroundStyle(.gray300) - .multilineTextAlignment(.center) - .lineLimit(2) - .padding(.top, 10) - .padding(.horizontal, 20) - } + .pretendardFont(family: .SemiBold, size: 18) + .foregroundStyle(.textInverse) + .fixedSize(horizontal: false, vertical: true) + .padding(.top, 8) + Text(option.quotedText) + .pretendardFont(.labelSmall) + .foregroundStyle(.textMuted) + .fixedSize(horizontal: false, vertical: true) + .padding(.top, 10) } - .frame(maxWidth: .infinity) + .multilineTextAlignment(.center) + .padding(.horizontal, 20) .padding(.vertical, 24) - .pickeCard(isSelected ? .neutral900 : .gray700, border: isSelected ? .secondary500 : .clear) + .frame(maxWidth: .infinity, minHeight: 140) + .pickeCard( + isSelected ? .gray900 : .gray700, + border: isSelected ? .secondary500 : .clear + ) + .contentShape(Rectangle()) } .buttonStyle(.plain) } - @ViewBuilder - func vsBadge() -> some View { + /// Android VS — 40 원 `secondary200`, 14 SemiBold `textDefault`, 테두리 없음. + var vsBadge: some View { Text("VS") .pretendardFont(.headingSmall) - .foregroundStyle(.neutral900) + .foregroundStyle(.textDefault) .frame(width: 40, height: 40) .background(.secondary200, in: Circle()) - .overlay(Circle().stroke(.beige50, lineWidth: 1.5)) } } // MARK: - CTA private extension BattleView { + /// Android `PickeButton` — 높이 48 이상, radius 2, 14 SemiBold, 비활성 `primary300`. @ViewBuilder func enterButton(_ battle: DailyBattle) -> some View { - Button("배틀 입장하기") { send(.enterBattleTapped(battleId: battle.battleId)) } - .ctaButtonStyle(.primary, size: .large, height: 52) - .disabled(store.selectedOptionByBattle[battle.battleId] == nil) + let isEnabled = store.state.isEnterEnabled(for: battle.battleId) + Button { + send(.enterBattleTapped(battleId: battle.battleId)) + } label: { + Text("배틀 입장하기") + .pretendardFont(.headingSmall) + .foregroundStyle(.surfaceBeigeDefault) + .frame(maxWidth: .infinity, minHeight: 48) + .roundedBackground( + isEnabled ? .buttonPrimaryBackgroundDefault : .primary300, + radius: .radiusDefault + ) + } + .buttonStyle(.plain) + // `.disabled` 는 글자까지 흐리게 해서, 배경색만 바꾸고 누름만 막는다. + .allowsHitTesting(isEnabled) } } -// MARK: - Empty / Skeleton +// MARK: - Empty private extension BattleView { + /// Android 빈 화면 — 로고 160×120 `borderBeigeDefault`, 14 Regular `surfaceBeigeStrong` 가운데. @ViewBuilder func emptyState() -> some View { - VStack(spacing: 8) { - Image(asset: .noDataLogo) + VStack(spacing: 0) { + Image(asset: .appLogo) + .renderingMode(.template) .resizable() .scaledToFit() - .frame(width: 135, height: 90) - - Text("아직 빠른 배틀이 선정되지 않았어요\n 조금만 기다려주세요!") - .pretendardFont(.bodyMedium) - .foregroundStyle(.beige300) + .foregroundStyle(.borderBeigeDefault) + .frame(width: 160, height: 120) + Text("아직 빠른 배틀이 선정되지 않았어요\n조금만 기다려주세요!") + .pretendardFont(.bodyMedium, lineSpacingMultiple: 1.4) + .foregroundStyle(.surfaceBeigeStrong) + .multilineTextAlignment(.center) } .frame(maxWidth: .infinity, maxHeight: .infinity) } diff --git a/Projects/Feature/Battle/Tests/Sources/BattleParityTests.swift b/Projects/Feature/Battle/Tests/Sources/BattleParityTests.swift new file mode 100644 index 00000000..dda0e576 --- /dev/null +++ b/Projects/Feature/Battle/Tests/Sources/BattleParityTests.swift @@ -0,0 +1,116 @@ +// +// BattleParityTests.swift +// BattleTests +// +// Created by Picke on 11/10/26. +// + +@testable import Battle +import BattleDomainInterface +import ComposableArchitecture +import Foundation +import Testing + +/// Android `TodayBattleViewModel` 동작과 맞춘 부분. +@MainActor +struct BattleParityTests { + @Test + func durationRoundsUpToMinutes() { + #expect(DailyBattle.from(Self.info(audioDuration: 61)).durationText == "2분") + #expect(DailyBattle.from(Self.info(audioDuration: 120)).durationText == "2분") + #expect(DailyBattle.from(Self.info(audioDuration: 0)).durationText == "0분") + } + + @Test + func showsOnlyFirstBattle() async { + let store = Self.store() + let page = TodayBattlePage(items: [Self.info(battleId: 1), Self.info(battleId: 2)], totalCount: 2) + + await store.send(.inner(.todayResponse(.success(page)))) + #expect(store.state.battles.map(\.battleId) == [1]) + } + + @Test + func tappingSelectedOptionKeepsSelection() async { + let store = Self.store() + + await store.send(.view(.optionTapped(battleId: 1, optionId: 7))) + await store.send(.view(.optionTapped(battleId: 1, optionId: 7))) + #expect(store.state.selectedOptionByBattle[1] == 7) + } + + @Test + func enteringFreshBattleSubmitsPreVoteThenOpensChat() async { + var state = BattleFeature.State() + state.selectedOptionByBattle = [1: 7] + let store = Self.store(state) + + await store.send(.view(.enterBattleTapped(battleId: 1))) + #expect(store.state.isEntering) + #expect(!store.state.isEnterEnabled(for: 1)) + + await store.send(.inner(.entryStepResponse(battleId: 1, optionId: 7, .success(.none)))) + await store.receive(\.async, .submitPreVote(battleId: 1, optionId: 7)) + await store.receive(\.inner) + await store.receive(\.delegate, .openBattle(battleId: 1)) + #expect(!store.state.isEntering) + } + + @Test + func enteringJoinedBattleOpensPerspective() async { + var state = BattleFeature.State() + state.isEntering = true + let store = Self.store(state) + + await store.send(.inner(.entryStepResponse(battleId: 1, optionId: 7, .success(.postVote)))) + await store.receive(\.delegate, .openPerspective(battleId: 1)) + #expect(!store.state.isEntering) + } + + @Test + func stepLookupFailureStillSubmitsPreVote() async { + let store = Self.store() + + await store.send(.inner(.entryStepResponse(battleId: 1, optionId: 7, .failure(.noData)))) + await store.receive(\.async, .submitPreVote(battleId: 1, optionId: 7)) + } + + @Test + func preVoteFailureShowsToast() async { + let store = Self.store() + + await store.send(.inner(.preVoteResponse(battleId: 1, .failure(.insufficientPoints)))) + #expect(store.state.toastMessage == "포인트가 부족합니다.") + await store.send(.inner(.preVoteResponse(battleId: 1, .failure(.serverError(500))))) + #expect(store.state.toastMessage == "요청을 처리하지 못했어요") + } +} + +extension BattleParityTests { + private static func store(_ state: BattleFeature.State = .init()) -> TestStoreOf { + let store = TestStore(initialState: state) { + BattleFeature() + } withDependencies: { + $0.battleUseCase = MockBattleRepository() + } + store.exhaustivity = .off + return store + } + + private static func info( + battleId: Int = 1, + audioDuration: Int = 60 + ) -> BattleInfo { + BattleInfo( + battleId: battleId, + title: "제목", + summary: "요약", + thumbnailUrl: "", + viewCount: 0, + participantsCount: 0, + audioDuration: audioDuration, + tags: [], + options: [] + ) + } +} diff --git a/Projects/Feature/Chat/Interface/Sources/ChatInterface.swift b/Projects/Feature/Chat/Interface/Sources/ChatInterface.swift index 2ea95b06..22982cc3 100644 --- a/Projects/Feature/Chat/Interface/Sources/ChatInterface.swift +++ b/Projects/Feature/Chat/Interface/Sources/ChatInterface.swift @@ -32,6 +32,8 @@ public struct ChatRoomRoute: Equatable, Sendable { public enum ChatDelegate: Equatable, Sendable { case dismiss case popToRoot + /// 포인트 부족 안내에서 탐색 탭으로 이동. 받는 쪽이 이 Chat 플로우를 닫고 탭을 바꾼다. + case openExplore } /// ChatRoomFeature 가 상위 coordinator 로 올려보내는 delegate 계약. diff --git a/Projects/Feature/Chat/Sources/ChatRoom/Reducer/ChatRoomFeature.swift b/Projects/Feature/Chat/Sources/ChatRoom/Reducer/ChatRoomFeature.swift index d2fcb009..bcf512aa 100644 --- a/Projects/Feature/Chat/Sources/ChatRoom/Reducer/ChatRoomFeature.swift +++ b/Projects/Feature/Chat/Sources/ChatRoom/Reducer/ChatRoomFeature.swift @@ -24,7 +24,6 @@ public struct ChatRoomFeature { @ObservableState public struct State: Equatable { public let instanceID = UUID() - public var bundle: ChatRoomBundle = .mock public var scenario: BattleScenario? public var isPlaying: Bool = false public var playbackRate: Float = 1 @@ -39,6 +38,12 @@ public struct ChatRoomFeature { /// 한 번 끝까지 재생된 콘텐츠는 이후 재진입 시 시킹/건너뛰기를 허용한다. public var hasFinishedListening: Bool = false public var hasPresentedFinalVoteAlert: Bool = false + /// Android `isReviewing` — "다시 들어볼래요" 뒤에는 대사를 모두 보이고 리스트 끝에 "최종투표 하러가기" 를 둔다. + public var isReviewing: Bool = false + /// Android `maxListenedPositionMs` — 슬라이더·말풍선 탭은 지금까지 들은 위치까지만 이동한다. + public var maxListenedTime: TimeInterval = 0 + /// Android `ScenarioUiEvent` 토스트 문구. 보여준 뒤 `toastShown` 으로 비운다. + public var toastMessage: String? @Presents public var customAlert: CustomAlertState? /// 현재 재생 중인 시나리오 노드 id (없으면 startNodeId 폴백) @@ -61,46 +66,48 @@ public struct ChatRoomFeature { /// 흘리므로, 목표 시간 근처에 도달하기 전까지 옵저버 tick 을 무시해 오디오-텍스트 불일치를 막는다. public var pendingSeekTime: TimeInterval? - public static let supportedPlaybackRates: [Float] = [1, 1.25, 1.5, 2] + /// Android `AudioPlayerDefaults.PLAYBACK_SPEEDS` — 탭할 때마다 이 순서로 돈다. + public static let supportedPlaybackRates: [Float] = [1, 1.5, 2, 3] public var playbackRateTitle: String { - switch playbackRate { - case 1: return "1.0" - case 1.25: return "1.25" - case 1.5: return "1.5" - case 2: return "2.0" - default: return "1.0" - } + String(format: "%.1f", playbackRate) + } + + public var nextPlaybackRate: Float { + let rates = Self.supportedPlaybackRates + let index = rates.firstIndex(of: playbackRate) ?? 0 + return rates[(index + 1) % rates.count] } public var totalDuration: TimeInterval { if playerDuration > 0 { return playerDuration } - guard let scenario else { return bundle.totalDuration } + // Android 는 불러오기 전 제목·시간을 비워 둔다(0:00). 목업 값을 보이지 않는다. + guard let scenario else { return 0 } let nodesTotal = scenario.nodes.reduce(0) { $0 + $1.audioDuration } - return nodesTotal > 0 ? TimeInterval(nodesTotal) : bundle.totalDuration + return TimeInterval(nodesTotal) } public var battleTitle: String { - scenario?.title ?? bundle.battleTitle + scenario?.title ?? "" } public var messages: [ChatMessage] { - // scenario 가 nil(미로드/로드 실패)이면 목업을 노출하지 않는다. - // 과거엔 bundle.messages(목업 전체)를 반환해 "재생 안 됨 + 전체 내용 노출" 버그가 있었다. + // scenario 가 nil(미로드/로드 실패)이면 빈 목록이다. guard let scenario else { return [] } return ChatRoomTimelineUseCase().messages( scenario: scenario, visibleNodeIds: visibleNodeIds, currentNodeId: currentNodeId, - currentTime: currentTime + currentTime: isReviewing ? max(currentTime, totalDuration) : currentTime ) } - /// 현재 재생 중(가장 최근 노출된) 메시지 id. 문장 단위 노출이라 마지막 노출 버블이 활성. + /// 지금 재생 위치의 대사. 다시 듣는 중에는 전체가 보이므로 시작 시각으로 고른다(Android `indexOfLast`). public var activeMessageId: UUID? { - messages.last?.id + let currentMs = Int(currentTime * 1000) + return messages.last { ($0.startTimeMs ?? 0) <= currentMs }?.id } public var audioUrl: String? { @@ -111,8 +118,23 @@ public struct ChatRoomFeature { return scenario.audios.values.first } - public var canScrub: Bool { - hasFinishedListening + /// Android `isForwardEnabled` — 선택지·최종투표 대화상자·오디오 오류 중에는 15초 넘기기를 막는다. + public var isForwardEnabled: Bool { + !shouldShowOptions && customAlert == nil && !hasAudioError + } + + /// 현재 노드 구간. Android 는 노드마다 오디오가 따로라 이동이 노드 안에서만 일어난다. + public var currentNodeRange: ClosedRange { + guard let currentNode else { return 0 ... max(totalDuration, 0) } + let start = nodeStartTime(for: currentNode.nodeId) + return start ... max(start, nodeEndTime(for: currentNode)) + } + + /// Android `seekToPosition` — 노드 끝과 들은 위치 중 앞쪽까지만 이동한다. + public func clampedSeekTime(_ time: TimeInterval) -> TimeInterval { + let range = currentNodeRange + let upper = max(range.lowerBound, min(range.upperBound, maxListenedTime)) + return min(max(time, range.lowerBound), upper) } public var currentNode: ScenarioNode? { @@ -184,14 +206,15 @@ public struct ChatRoomFeature { case onAppear case onDisappear case backButtonTapped - case refreshTapped - case retryTapped + case toastShown case togglePlayTapped case playbackRateSelected(Float) case seekBackwardTapped case seekForwardTapped case replayTapped case scrub(TimeInterval) + case messageTapped(UUID) + case goToFinalVoteTapped case optionTapped(String) case confirmOptionTapped } @@ -280,23 +303,9 @@ extension ChatRoomFeature { } ) - case .refreshTapped: - state.currentTime = 0 - state.isPlaying = false - state.currentNodeId = state.scenario?.startNodeId - state.visibleNodeIds = state.scenario.map { [$0.startNodeId] } ?? [] - state.isWaitingForNodeSelection = false - state.selectedOptionLabel = nil - state.confirmedSelection = nil - // 처음부터 다시 들을 때도 최종투표 팝업이 다시 뜨도록 1회성 플래그를 리셋한다. - state.hasPresentedFinalVoteAlert = false - return .run { [player = audioPlayer] _ in - await player.pause() - await player.seek(to: 0) - } - - case .retryTapped: - return .send(.async(.fetchScenario)) + case .toastShown: + state.toastMessage = nil + return .none case .togglePlayTapped: analyticsUseCase.track(.uiAction(action: .chatroomPlay, screen: .chatroom)) @@ -319,8 +328,8 @@ extension ChatRoomFeature { case .seekBackwardTapped: analyticsUseCase.track(.uiAction(action: .chatroomSeekBackward, screen: .chatroom)) - // 15초 되감기 버튼은 첫 재생 중에도 항상 동작한다 (canScrub 게이트는 드래그 스크럽 전용). - let target = max(0, state.currentTime - 15) + // Android `seekRewind` — 현재 노드 시작 아래로는 가지 않는다. + let target = max(state.currentNodeRange.lowerBound, state.currentTime - 15) state.currentTime = target state.pendingSeekTime = target return .run { [player = audioPlayer] _ in @@ -328,9 +337,10 @@ extension ChatRoomFeature { } case .seekForwardTapped: + // Android `seekForward` — 막힌 상태면 무시하고, 노드 끝까지만 넘긴다. + guard state.isForwardEnabled else { return .none } analyticsUseCase.track(.uiAction(action: .chatroomSeekForward, screen: .chatroom)) - // 15초 넘기기 버튼은 첫 재생 중에도 항상 동작한다 (canScrub 게이트는 드래그 스크럽 전용). - let target = min(state.totalDuration, state.currentTime + 15) + let target = min(state.currentNodeRange.upperBound, state.currentTime + 15) state.currentTime = target state.pendingSeekTime = target return .run { [player = audioPlayer] _ in @@ -338,24 +348,29 @@ extension ChatRoomFeature { } case .replayTapped: - // 다시듣기는 끝까지 들은 적이 있는 경우(canScrub)에만 동작한다. - guard state.canScrub else { return .none } - state.currentTime = 0 - state.isPlaying = true - state.currentNodeId = state.scenario?.startNodeId - state.visibleNodeIds = state.scenario.map { [$0.startNodeId] } ?? [] - state.isWaitingForNodeSelection = false - state.selectedOptionLabel = nil - state.confirmedSelection = nil - state.hasPresentedFinalVoteAlert = false - return .run { [player = audioPlayer] _ in - await player.seek(to: 0) - await player.play() - } + // Android `replayFromStart` — 항상 동작하며 현재 노드 처음부터 다시 재생한다. + return seekAndPlay( + state: &state, + to: state.currentNodeRange.lowerBound + ) + + case let .messageTapped(id): + // Android 말풍선 탭 — 현재 노드 대사만 그 시작 위치로 이동해 재생한다. + guard let message = state.messages.first(where: { $0.id == id }), + let startMs = message.startTimeMs + else { return .none } + let start = TimeInterval(startMs) / 1000 + guard state.currentNodeRange.contains(start) else { return .none } + return seekAndPlay( + state: &state, + to: state.clampedSeekTime(start) + ) + + case .goToFinalVoteTapped: + return requestFinalVote(state: &state) case let .scrub(time): - guard state.canScrub else { return .none } - let target = min(max(0, time), state.totalDuration) + let target = state.clampedSeekTime(time) state.currentTime = target state.pendingSeekTime = target return .run { [player = audioPlayer] _ in @@ -469,7 +484,9 @@ extension ChatRoomFeature { } return .none case let .failure(error): + // Android `ShowLoadFailedToast` — 토스트만 띄우고 빈 목록을 유지한다(다시 시도 없음). state.scenarioLoadFailed = true + state.toastMessage = "정보를 불러오지 못했어요" PickeLogger.error( "[ChatRoomFeature] fetchScenario failed: \(error) — \(error.localizedDescription)", category: .ui @@ -485,6 +502,7 @@ extension ChatRoomFeature { state.pendingSeekTime = nil } state.currentTime = time + state.maxListenedTime = max(state.maxListenedTime, time) if let effect = advanceNodeIfNeeded(state: &state, time: time) { return effect } @@ -499,7 +517,8 @@ extension ChatRoomFeature { ) } state.isPlaying = false - if !state.hasPresentedFinalVoteAlert { + // Android `handleNodeEnd` — 다시 듣는 중에는 대화상자를 다시 띄우지 않는다. + if !state.isReviewing, !state.hasPresentedFinalVoteAlert { state.hasPresentedFinalVoteAlert = true state.customAlert = .finalVote() } @@ -526,6 +545,28 @@ extension ChatRoomFeature { } } + private func seekAndPlay( + state: inout State, + to target: TimeInterval + ) -> Effect { + state.currentTime = target + state.pendingSeekTime = target + state.isPlaying = true + return .run { [player = audioPlayer] _ in + await player.seek(to: target) + await player.play() + } + } + + private func requestFinalVote(state: inout State) -> Effect { + state.isPlaying = false + let battleId = state.battleId + return .run { [player = audioPlayer] send in + await player.pause() + await send(.delegate(.requestFinalVote(battleId: battleId))) + } + } + private func advanceNodeIfNeeded( state: inout State, time: TimeInterval @@ -572,25 +613,20 @@ extension ChatRoomFeature { switch customAlertAction { case .confirmTapped: state.customAlert = nil - let battleId = state.battleId - return .run { [player = audioPlayer] send in - await player.pause() - await send(.delegate(.requestFinalVote(battleId: battleId))) - } + return requestFinalVote(state: &state) case .cancelTapped: + // Android `restartCurrentAudio` — 대사를 모두 보인 채 현재 노드 처음부터 다시 듣는다. state.customAlert = nil - state.currentTime = 0 - state.isPlaying = true - // 다시 듣기(replay) 후 끝까지 들으면 최종투표 팝업이 재노출되도록 1회성 플래그를 리셋한다. - state.hasPresentedFinalVoteAlert = false - return .run { [player = audioPlayer] _ in - await player.seek(to: 0) - await player.play() - } + state.isReviewing = true + return seekAndPlay( + state: &state, + to: state.currentNodeRange.lowerBound + ) } case .dismiss: + // Android 는 바깥 터치·닫기도 "최종투표하기" 와 같다. state.customAlert = nil - return .none + return requestFinalVote(state: &state) } } } diff --git a/Projects/Feature/Chat/Sources/ChatRoom/View/ChatRoomView.swift b/Projects/Feature/Chat/Sources/ChatRoom/View/ChatRoomView.swift index 90fbee21..17bf1eea 100644 --- a/Projects/Feature/Chat/Sources/ChatRoom/View/ChatRoomView.swift +++ b/Projects/Feature/Chat/Sources/ChatRoom/View/ChatRoomView.swift @@ -15,76 +15,61 @@ import SwiftUI public struct ChatRoomView: View { @Bindable public var store: StoreOf - /// [고정 36 슬롯][8][말풍선 고정폭][8][고정 36 슬롯] — 재생 상태와 무관하게 말풍선 크기 고정. + /// Android `ChatBubble` · `ScenarioScreen` 치수. private enum Metric { - static let sideSlotWidth: CGFloat = 36 - static let slotSpacing: CGFloat = 8 - static let equalizerSize: CGFloat = 24 - static let avatarSize: CGFloat = 32 - static let avatarImageWidth: CGFloat = 24 - static let avatarImageHeight: CGFloat = 28 - static let bubblePadding: CGFloat = 12 + static let avatarSize: CGFloat = 40 + /// `ProfileImageKind.PHILOSOPHER` — 안쪽 이미지 40 × 28/40. + static let avatarImageSize: CGFloat = 28 + static let bubbleMaxWidth: CGFloat = 272 static let rowSpacing: CGFloat = 6 - static let speakerChangeSpacing: CGFloat = 16 - static let bodyLineSpacing: CGFloat = 4.8 + static let speakerGroupSpacing: CGFloat = 14 + static let dimmedOpacity: CGFloat = 0.8 } + private static let optionsAnchorID = "scenarioOptions" + public init(store: StoreOf) { self.store = store } public var body: some View { Group { - if shouldShowSkeleton { + if store.isLoadingScenario, store.scenario == nil { + // 스켈레톤은 iOS 기존 것을 쓴다(상단 바·플레이어 바 자리까지 포함). ChatRoomSkeletonView() - } else if shouldShowLoadError { - scenarioErrorView() } else { - VStack(spacing: 0) { - navigationBar() - messageList() - if store.shouldShowOptions { - interactiveOptionsSection() - } - playerBar() - // 마지막 말풍선이 플레이어 바에 딱 붙어 보이지 않도록 위 여백. - .padding(.top, 16) - } + screenContent() } } - .screenBackground() - .overlay(alignment: .top) { - if store.hasAudioError { - FloatingErrorView(message: "오디오를 불러오는 중 문제가 발생했어요") - .padding(.top, 64) - .transition(.move(edge: .top).combined(with: .opacity)) - .zIndex(1) - } - } - .animation(.easeInOut(duration: 0.25), value: store.hasAudioError) .navigationBarHidden(true) .hidesSystemBars() .onAppear { send(.onAppear) } .onDisappear { send(.onDisappear) } + .onChange(of: store.toastMessage, initial: true) { _, message in + guard let message else { return } + ToastManager.shared.showError(message) + send(.toastShown) + } .customAlert($store.scope(state: \.customAlert, action: \.scope.customAlert)) } - private var shouldShowSkeleton: Bool { - store.isLoadingScenario && store.scenario == nil - } - - /// 시나리오 로드 실패 & 아직 로드된 시나리오가 없을 때 오류+재시도 노출. - private var shouldShowLoadError: Bool { - store.scenarioLoadFailed && store.scenario == nil - } - @ViewBuilder - private func scenarioErrorView() -> some View { + private func screenContent() -> some View { VStack(spacing: 0) { navigationBar() - PickeRetryErrorView(message: "대화를 불러오지 못했어요") { send(.retryTapped) } + messageList() + .frame(maxWidth: .infinity, maxHeight: .infinity) + .overlay(alignment: .top) { + if store.hasAudioError { + FloatingErrorView(message: "오디오를 불러오는 중 문제가 발생했어요") + .padding(.top, 16) + .transition(.move(edge: .top).combined(with: .opacity)) + } + } + playerBar } - .frame(maxWidth: .infinity, maxHeight: .infinity) + .screenBackground() + .animation(.easeInOut(duration: 0.25), value: store.hasAudioError) } } @@ -93,26 +78,13 @@ public struct ChatRoomView: View { extension ChatRoomView { @ViewBuilder private func navigationBar() -> some View { + // Android `PickeTopAppBar` — 가운데 제목만, 배경 `backgroundBeige`, 구분선 없음. + // Android 는 시스템 뒤로 가기를 쓰지만 iOS 는 시스템 버튼이 없어 뒤로 버튼은 남긴다. PickeNavigationBar( - onBack: { send(.backButtonTapped) } - ) { - Button { send(.refreshTapped) } label: { - Image(systemName: "arrow.clockwise") - .font(.system(size: 18, weight: .semibold)) - .frame(width: 24, height: 24) - } - .buttonStyle(.plain) - } - .overlay(alignment: .center) { - Text(store.battleTitle) - .pretendardFont(.headingMedium) - .foregroundStyle(.neutral800) - .lineLimit(1) - .padding(.horizontal, 56) - } - .foregroundStyle(.neutral800) - .background(.beige50) - .bottomDivider(.beige600) + onBack: { send(.backButtonTapped) }, + centerTitle: store.battleTitle + ) + .foregroundStyle(.textDefault) } } @@ -130,26 +102,42 @@ extension ChatRoomView { selectionHistorySection() } ForEach(Array(rows.enumerated()), id: \.element.id) { index, row in - messageRow(row) - .padding(.top, index > 0 && row.showsHeader ? Metric.speakerChangeSpacing : 0) - .transition(.opacity) - // 중간(분기) 선택 확정 내역 — 선택 지점 뒤에 유지 노출. (안드로이드 파리티) + // Android `isNewSpeaker || isNewNode` — 화자가 바뀌거나 선택 지점 바로 뒤면 이름·아바타를 다시 보인다. + let showsHeader = row.showsHeader || index == (insertAfter ?? -2) + 1 + messageRow( + row.message, + showsHeader: showsHeader + ) + .padding(.top, index > 0 && showsHeader ? Metric.speakerGroupSpacing : 0) + .transition(.opacity) if index == insertAfter { selectionHistorySection() } } + if store.shouldShowOptions { + interactiveOptionsSection() + .id(Self.optionsAnchorID) + } + if store.isReviewing { + finalVoteButton + .padding(.top, 24) + } } - .padding(.horizontal, 20) + .padding(.horizontal, 16) .padding(.top, 24) .padding(.bottom, 40) - // 대사가 한 줄씩 추가될 때 슬라이드/페이드인. .animation(.easeInOut(duration: 0.25), value: store.messages) } - .frame(maxWidth: .infinity, maxHeight: .infinity) .onChange(of: store.activeMessageId) { _, activeMessageId in - guard let activeMessageId else { return } + guard let activeMessageId, !store.shouldShowOptions else { return } withAnimation(.easeInOut(duration: 0.25)) { - proxy.scrollTo(activeMessageId, anchor: .bottom) + proxy.scrollTo(activeMessageId, anchor: .top) + } + } + .onChange(of: store.shouldShowOptions) { _, isShown in + guard isShown else { return } + withAnimation(.easeInOut(duration: 0.25)) { + proxy.scrollTo(Self.optionsAnchorID, anchor: .bottom) } } } @@ -162,42 +150,6 @@ extension ChatRoomView { return firstAfter - 1 } - @ViewBuilder - private func selectionHistorySection() -> some View { - if let selection = store.confirmedSelection { - VStack(spacing: 24) { - HStack(spacing: 16) { - PickeDivider(.gray200) - Text("아래가 당신의 선택입니다.") - .pretendardFont(.labelMedium) - .italic() - .foregroundStyle(.gray500) - .fixedSize() - PickeDivider(.gray200) - } - - VStack(spacing: 12) { - ForEach(selection.options, id: \.label) { option in - historyOptionCard(option, isChosen: option.nextNodeId == selection.selectedNodeId) - } - } - } - .padding(.vertical, 16) - } - } - - @ViewBuilder - private func historyOptionCard(_ option: ScenarioInteractiveOption, isChosen: Bool) -> some View { - Text(option.label) - .pretendardFont(.labelSmall) - .foregroundStyle(isChosen ? .gray900 : .gray500) - .multilineTextAlignment(.center) - .frame(maxWidth: .infinity, alignment: .center) - .padding(.horizontal, 16) - .padding(.vertical, 20) - .pickeCard(.beige400, border: isChosen ? .secondary500 : .beige700) - } - private var messageRows: [MessageRow] { var rows: [MessageRow] = [] for message in store.messages { @@ -207,120 +159,128 @@ extension ChatRoomView { return rows } + /// Android `ScenarioChatBubble` — 재생 중인 대사만 활성. 멈추면 모든 대사가 흐려진다. @ViewBuilder - private func messageRow(_ row: MessageRow) -> some View { - let message = row.message - let speaker = message.speaker - let isActive = message.id == store.activeMessageId - - switch speaker.side { + private func messageRow( + _ message: ChatMessage, + showsHeader: Bool + ) -> some View { + let isActive = store.isPlaying && message.id == store.activeMessageId + switch message.speaker.side { case .center: - narratorBubble(text: message.text, isActive: isActive) - .opacity(isActive ? 1 : 0.8) - .id(message.id) - + narratorBubble( + text: message.text, + isActive: isActive + ) + .contentShape(Rectangle()) + .onTapGesture { send(.messageTapped(message.id)) } + .id(message.id) case .left, .right: - HStack(alignment: .top, spacing: 8) { - sideSlot(showsAvatar: speaker.side == .left && row.showsHeader, speaker: speaker) - - VStack(alignment: speaker.side == .left ? .leading : .trailing, spacing: 6) { - if row.showsHeader { - Text(speaker.name) - .pretendardFont(.headingSmall) - .foregroundStyle(.gray400) - } - withEqualizer( - bubble(text: message.text, side: speaker.side, isActive: isActive), - side: speaker.side, - isVisible: isActive && store.isPlaying - ) - } - .frame(maxWidth: .infinity) - - sideSlot(showsAvatar: speaker.side == .right && row.showsHeader, speaker: speaker) - } - .opacity(isActive ? 1 : 0.8) + chatBubble( + message, + showsHeader: showsHeader, + isActive: isActive + ) .id(message.id) } } - /// 재생 중 이퀄라이저를 말풍선 반대편 슬롯 중앙에 얹는다. - /// - /// 말풍선의 overlay 라 레이아웃 폭을 차지하지 않아 "재생 상태와 무관하게 말풍선 크기 고정" - /// 불변식이 유지되고, 헤더(이름) 유무와 무관하게 항상 말풍선 세로 중앙에 온다. @ViewBuilder - private func withEqualizer( - _ content: some View, - side: ChatSpeakerSide, - isVisible: Bool + private func chatBubble( + _ message: ChatMessage, + showsHeader: Bool, + isActive: Bool ) -> some View { - // 아이콘 중심을 말풍선 바깥 슬롯 중앙에 맞춘다: 간격 + 슬롯 절반 + 아이콘 절반. - let shift = Metric.slotSpacing + Metric.sideSlotWidth / 2 + Metric.equalizerSize / 2 - content.overlay(alignment: side == .left ? .trailing : .leading) { - if isVisible { - waveformIcon() - .offset(x: side == .left ? shift : -shift) + let isLeft = message.speaker.side == .left + HStack(alignment: .top, spacing: 6) { + if isLeft { + avatarSlot(message.speaker, isVisible: showsHeader) } - } - } - - @ViewBuilder - private func sideSlot(showsAvatar: Bool, speaker: ChatSpeaker) -> some View { - ZStack { - if showsAvatar { - avatar(speaker) + VStack(alignment: isLeft ? .leading : .trailing, spacing: 6) { + if showsHeader { + Text(message.speaker.name) + .pretendardFont(.headingSmall) + .foregroundStyle(.textDefault) + } + HStack(spacing: 6) { + if !isLeft, isActive { + AudioEqualizerView() + } + bubble( + text: message.text, + isLeft: isLeft + ) + .onTapGesture { send(.messageTapped(message.id)) } + if isLeft, isActive { + AudioEqualizerView() + } + } + } + if !isLeft { + avatarSlot(message.speaker, isVisible: showsHeader) } } - .frame(width: Metric.sideSlotWidth) - } - - @ViewBuilder - private func avatar(_ speaker: ChatSpeaker) -> some View { - PickeRemoteImage( - url: speaker.imageURL ?? "", - shape: .round(cornerRadius: Metric.avatarSize / 2) - ) - .content(.fit) - .frame(width: Metric.avatarImageWidth, height: Metric.avatarImageHeight) - .frame(width: Metric.avatarSize, height: Metric.avatarSize) - .background(.beige600, in: Circle()) + .frame(maxWidth: .infinity, alignment: isLeft ? .leading : .trailing) + .opacity(isActive ? 1 : Metric.dimmedOpacity) } + /// Android `ChatBubbleAvatar` — 안 보일 때도 40 자리를 비워 둔다. @ViewBuilder - private func waveformIcon() -> some View { - AudioEqualizerView(isPlaying: store.isPlaying) - .frame(width: 24, height: 24) + private func avatarSlot( + _ speaker: ChatSpeaker, + isVisible: Bool + ) -> some View { + if isVisible { + Circle() + .fill(.borderBeigeDefault) + .overlay { + PickeRemoteImage(url: speaker.imageURL) { + Color.clear + } + .content(.fit) + .frame(width: Metric.avatarImageSize, height: Metric.avatarImageSize) + } + .frame(width: Metric.avatarSize, height: Metric.avatarSize) + } else { + Color.clear + .frame(width: Metric.avatarSize, height: Metric.avatarSize) + } } + /// 말풍선 폭은 최대 272 까지 채운다(Android `widthIn(max = 272).fillMaxWidth()`). @ViewBuilder private func bubble( text: String, - side: ChatSpeakerSide, - isActive: Bool + isLeft: Bool ) -> some View { - let background: Color = side == .left ? .white : .beige500 - let border: Color = side == .left ? .beige500 : .beige700 Text(text) - .pretendardFont(.labelSmall) - .foregroundStyle(isActive ? .gray700 : .gray300) - .lineSpacing(Metric.bodyLineSpacing) + .pretendardFont(.regular13, lineSpacingMultiple: 1.4) + .foregroundStyle(.textBody) .multilineTextAlignment(.leading) .fixedSize(horizontal: false, vertical: true) .frame(maxWidth: .infinity, alignment: .leading) - .padding(Metric.bubblePadding) - .pickeCard(background, border: border) + .padding(.horizontal, 8) + .padding(.vertical, isLeft ? 6 : 8) + .pickeCard( + isLeft ? .surfaceBeigeDefault : .surfaceBeigeStrong, + border: .borderBeigeDefault + ) + .frame(maxWidth: Metric.bubbleMaxWidth) } @ViewBuilder - private func narratorBubble(text: String, isActive: Bool) -> some View { + private func narratorBubble( + text: String, + isActive: Bool + ) -> some View { Text(text.replacingOccurrences(of: ", ", with: ",\n")) - .pretendardFont(.labelSmall) + .pretendardFont(.labelSmall, lineSpacingMultiple: 1.4) .italic() - .foregroundStyle(isActive ? .gray700 : .gray300) - .lineSpacing(Metric.bodyLineSpacing) + .foregroundStyle(isActive ? .textSubtle : .textMuted) .multilineTextAlignment(.center) .padding(.vertical, 6) .frame(maxWidth: .infinity) + .opacity(isActive ? 1 : Metric.dimmedOpacity) } private struct MessageRow: Equatable, Identifiable { @@ -336,138 +296,144 @@ extension ChatRoomView { // MARK: - Interactive Options extension ChatRoomView { + /// Android `InteractiveOptionsUI`(확정 전) — 리스트 맨 끝에 안내선 + 카드 + "입장 선택하기". @ViewBuilder private func interactiveOptionsSection() -> some View { - VStack(spacing: 12) { - optionsHeader() - optionsList() - confirmButton() + VStack(spacing: 0) { + optionsGuide("이제 당신의 입장을 선택해주세요") + VStack(spacing: 12) { + ForEach(store.visibleOptions, id: \.label) { option in + Button { + send(.optionTapped(option.label)) + } label: { + optionCard( + option.label, + isSelected: store.selectedOptionLabel == option.label + ) + } + .buttonStyle(.plain) + } + confirmButton + } + .padding(.top, 24) } - .padding(.horizontal, 16) - .padding(.vertical, 12) - .frame(maxWidth: .infinity) - .background(.beige200) + .padding(.top, 32) + .padding(.bottom, 16) } + /// Android `InteractiveOptionsUI`(확정 후) — 같은 모양, 카드는 누를 수 없고 확인 버튼이 없다. @ViewBuilder - private func optionsHeader() -> some View { - HStack(spacing: 16) { + private func selectionHistorySection() -> some View { + if let selection = store.confirmedSelection { + VStack(spacing: 0) { + optionsGuide("아래가 당신의 선택입니다.") + VStack(spacing: 12) { + ForEach(selection.options, id: \.label) { option in + optionCard( + option.label, + isSelected: option.nextNodeId == selection.selectedNodeId + ) + } + } + .padding(.top, 24) + .padding(.bottom, 12) + } + .padding(.top, 32) + .padding(.bottom, 16) + } + } + + @ViewBuilder + private func optionsGuide(_ text: String) -> some View { + HStack(spacing: 0) { PickeDivider(.gray200) - Text("이제 당신의 입장을 선택해주세요") + Text(text) .pretendardFont(.labelMedium) .italic() - .foregroundStyle(.gray500) + .foregroundStyle(.textSubtler) .fixedSize() + .padding(.horizontal, 16) PickeDivider(.gray200) } } - @ViewBuilder - private func optionsList() -> some View { - VStack(spacing: 12) { - ForEach(store.visibleOptions, id: \.label) { option in - optionCard(option) - } + /// Android `OptionSelectionCard` — `surfaceBeigeStrong` 면, 테두리 선택 `secondary500` / 그 외 `borderBeigeSelected`. + private func optionCard( + _ label: String, + isSelected: Bool + ) -> some View { + Text(label) + .pretendardFont(.labelSmall) + .foregroundStyle(isSelected ? .textDefault : .textSubtler) + .multilineTextAlignment(.center) + .frame(maxWidth: .infinity) + .padding(.horizontal, 16) + .padding(.vertical, 20) + .pickeCard( + .surfaceBeigeStrong, + border: isSelected ? .secondary500 : .borderBeigeSelected + ) + .contentShape(Rectangle()) + } + + private var confirmButton: some View { + optionConfirmButton( + "입장 선택하기", + isEnabled: store.isConfirmEnabled + ) { + send(.confirmOptionTapped) } } - @ViewBuilder - private func optionCard(_ option: ScenarioInteractiveOption) -> some View { - let isSelected = store.selectedOptionLabel == option.label + /// Android `isReviewing` — 다시 들을 때 리스트 끝에 붙는 버튼. + private var finalVoteButton: some View { + optionConfirmButton( + "최종투표 하러가기", + isEnabled: true + ) { + send(.goToFinalVoteTapped) + } + } - Button { - send(.optionTapped(option.label)) - } label: { - Text(option.label) + /// Android `OptionConfirmButton` — radius 2, 세로 16, 12 Medium. + private func optionConfirmButton( + _ title: String, + isEnabled: Bool, + action: @escaping () -> Void + ) -> some View { + Button(action: action) { + Text(title) .pretendardFont(.labelSmall) - .foregroundStyle(isSelected ? .gray900 : .gray500) - .multilineTextAlignment(.center) - .frame(maxWidth: .infinity, alignment: .center) - .padding(.horizontal, 16) - .padding(.vertical, 20) - .pickeCard(.beige400, border: isSelected ? .secondary500 : .beige700) + .foregroundStyle(.buttonPrimaryTextDefault) + .frame(maxWidth: .infinity) + .padding(.vertical, 16) + .roundedBackground( + isEnabled ? .buttonPrimaryBackgroundDefault : .buttonPrimaryBackgroundDisabled, + radius: .radiusDefault + ) } .buttonStyle(.plain) - } - - @ViewBuilder - private func confirmButton() -> some View { - Button("입장 선택하기") { send(.confirmOptionTapped) } - .ctaButtonStyle(.primary, size: .large, height: 42) - .disabled(!store.isConfirmEnabled) + .disabled(!isEnabled) } } // MARK: - Player Bar extension ChatRoomView { - @ViewBuilder - private func playerBar() -> some View { - VStack(spacing: 16) { - progressBar() - AudioPlayerControlView( - isPlaying: .constant(store.isPlaying), - onBackward: { send(.seekBackwardTapped) }, - onTogglePlay: { send(.togglePlayTapped) }, - onForward: { send(.seekForwardTapped) }, - onReplay: { send(.replayTapped) }, - isReplayEnabled: store.canScrub, - tint: .neutral900, - playbackRateTitle: store.playbackRateTitle, - onPlaybackRateSelected: { send(.playbackRateSelected($0)) } - ) - } - .padding(.horizontal, 24) - .padding(.top, 16) - .padding(.bottom, 8) - .background(.beige50) - .topDivider(.beige600) - } - - @ViewBuilder - private func progressBar() -> some View { - VStack(spacing: 8) { - GeometryReader { proxy in - let progress = store.totalDuration > 0 - ? CGFloat(store.currentTime / store.totalDuration) - : 0 - ZStack(alignment: .leading) { - Capsule().fill(.beige600).frame(height: 4) - Capsule().fill(.primary500).frame(width: proxy.size.width * progress, height: 4) - Circle() - .fill(.primary500) - .frame(width: 16, height: 16) - .offset(x: max(0, proxy.size.width * progress - 8)) - } - .frame(maxWidth: .infinity, maxHeight: .infinity) - .contentShape(Rectangle()) - .gesture( - DragGesture(minimumDistance: 0) - .onChanged { value in - guard store.canScrub, - proxy.size.width > 0, - store.totalDuration > 0 else { return } - let ratio = min(max(value.location.x / proxy.size.width, 0), 1) - send(.scrub(store.totalDuration * Double(ratio))) - } - ) - .allowsHitTesting(store.canScrub) - } - .frame(height: 16) - - HStack { - Text(timeString(store.currentTime)) - Spacer() - Text(timeString(store.totalDuration)) - } - .pretendardFont(.medium11) - .foregroundStyle(.neutral300) - } - } - - private func timeString(_ seconds: TimeInterval) -> String { - let total = Int(seconds) - return String(format: "%d:%02d", total / 60, total % 60) + private var playerBar: some View { + PickeAudioPlayerBar( + isPlaying: store.isPlaying, + currentTime: store.currentTime, + totalDuration: store.totalDuration, + playbackRateTitle: store.playbackRateTitle, + isForwardEnabled: store.isForwardEnabled, + onTogglePlay: { send(.togglePlayTapped) }, + onSeek: { send(.scrub($0)) }, + onBackward: { send(.seekBackwardTapped) }, + onForward: { send(.seekForwardTapped) }, + onPlaybackRateTapped: { send(.playbackRateSelected(store.nextPlaybackRate)) }, + onReplay: { send(.replayTapped) } + ) } } diff --git a/Projects/Feature/Chat/Sources/Comment/View/CommentView.swift b/Projects/Feature/Chat/Sources/Comment/View/CommentView.swift index d615c4bc..1e0c8c7e 100644 --- a/Projects/Feature/Chat/Sources/Comment/View/CommentView.swift +++ b/Projects/Feature/Chat/Sources/Comment/View/CommentView.swift @@ -66,9 +66,7 @@ private extension CommentView { // Android PerspectiveScreen: 상단 바·통계·탭은 고정, 아래 목록만 스크롤한다. 배경 backgroundBeige. VStack(spacing: 0) { navigationBar - if !store.hasLoadedHeader { - CommentHeaderSkeletonView() - } else if !store.headerLoadFailed { + if !store.headerLoadFailed { summarySection() filterTabs() } @@ -312,6 +310,7 @@ private extension CommentView { if store.isLoadingComments, store.comments.isEmpty { CommentSkeletonView() + .padding(.horizontal, 16) } else if store.comments.isEmpty { emptyState() } else { diff --git a/Projects/Feature/Chat/Sources/Comment/View/Components/CommentHeaderSkeletonView.swift b/Projects/Feature/Chat/Sources/Comment/View/Components/CommentHeaderSkeletonView.swift deleted file mode 100644 index 89a850c1..00000000 --- a/Projects/Feature/Chat/Sources/Comment/View/Components/CommentHeaderSkeletonView.swift +++ /dev/null @@ -1,56 +0,0 @@ -// -// CommentHeaderSkeletonView.swift -// Chat -// -// Created by Picke on 11/10/26. -// - -import SwiftUI - -import PickeDesignKit - -/// Android `PerspectiveHeaderSkeleton` + `PerspectiveTabBarSkeleton` — 첫 조회 중 통계·탭 자리. -struct CommentHeaderSkeletonView: View { - var body: some View { - VStack(spacing: 0) { - statsRow() - SkeletonView.line(width: 64, height: 20) - .frame(maxWidth: .infinity) - .padding(16) - .overlay(alignment: .bottom) { - Rectangle() - .fill(.borderBeigeDefault) - .frame(height: 2) - } - } - .allowsHitTesting(false) - } - - @ViewBuilder - private func statsRow() -> some View { - HStack(spacing: 8) { - sideColumn() - VStack(spacing: 24) { - SkeletonView.line(width: 96, height: 20) - SkeletonView.beige(.round(cornerRadius: 3)) - .frame(height: 6) - } - .frame(maxWidth: .infinity) - sideColumn() - } - .padding(.horizontal, 16) - .padding(.vertical, 4) - } - - @ViewBuilder - private func sideColumn() -> some View { - VStack(spacing: 0) { - SkeletonView.beige(.circle) - .frame(width: 40, height: 40) - SkeletonView.line(width: 40, height: 14) - .padding(.top, 2) - SkeletonView.line(width: 28, height: 16) - } - .frame(width: 64) - } -} diff --git a/Projects/Feature/Chat/Sources/Comment/View/Components/CommentSkeletonView.swift b/Projects/Feature/Chat/Sources/Comment/View/Components/CommentSkeletonView.swift index adfbfb19..28cb848f 100644 --- a/Projects/Feature/Chat/Sources/Comment/View/Components/CommentSkeletonView.swift +++ b/Projects/Feature/Chat/Sources/Comment/View/Components/CommentSkeletonView.swift @@ -9,52 +9,34 @@ import SwiftUI import PickeDesignKit -/// Android `PerspectiveListSkeleton` — 카드 4개, 가로 16·세로 12, 간격 12. struct CommentSkeletonView: View { + var count: Int = 3 + var body: some View { VStack(spacing: 12) { - ForEach(0 ..< 4, id: \.self) { _ in + ForEach(0 ..< count, id: \.self) { _ in card() } } - .padding(.horizontal, 16) - .padding(.vertical, 12) - .allowsHitTesting(false) } @ViewBuilder private func card() -> some View { - VStack(alignment: .leading, spacing: 0) { - HStack(spacing: 8) { - SkeletonView.beige(.circle) - .frame(width: 32, height: 32) + VStack(alignment: .leading, spacing: 8) { + HStack(spacing: 6) { + SkeletonView(.round(cornerRadius: 14)) + .frame(width: 28, height: 28) VStack(alignment: .leading, spacing: 4) { - SkeletonView.line(width: 40, height: 16) - SkeletonView.line(width: 50, height: 12) + SkeletonView(.round(cornerRadius: 4)).frame(width: 80, height: 12) + SkeletonView(.round(cornerRadius: 4)).frame(width: 48, height: 10) } - Spacer(minLength: 0) - } - SkeletonView.line(width: 70, height: 20) - .padding(.top, 8) - SkeletonView.line(width: 260, height: 16) - .padding(.top, 12) - SkeletonView.line(width: 200, height: 16) - .padding(.top, 4) - HStack(spacing: 0) { - SkeletonView.line(width: 40, height: 14) - Spacer(minLength: 0) - SkeletonView.line(width: 24, height: 14) - SkeletonView.line(width: 24, height: 14) - .padding(.leading, 12) + Spacer() } - .padding(.top, 12) + SkeletonView(.round(cornerRadius: 4)).frame(maxWidth: .infinity).frame(height: 12) + SkeletonView(.round(cornerRadius: 4)).frame(width: 200, height: 12) } - .padding(14) + .padding(12) .frame(maxWidth: .infinity, alignment: .leading) - .pickeCard( - .surfaceBeigeDefault, - border: .borderBeigeDefault, - insideBorder: true - ) + .pickeCard(.beige50, border: .beige600) } } diff --git a/Projects/Feature/Chat/Sources/CommentReply/View/Components/CommentReplySkeletonView.swift b/Projects/Feature/Chat/Sources/CommentReply/View/Components/CommentReplySkeletonView.swift index 3c4afca4..fc22a6c9 100644 --- a/Projects/Feature/Chat/Sources/CommentReply/View/Components/CommentReplySkeletonView.swift +++ b/Projects/Feature/Chat/Sources/CommentReply/View/Components/CommentReplySkeletonView.swift @@ -9,52 +9,60 @@ import SwiftUI import PickeDesignKit -/// Android `CommentSkeleton` — 원본 카드(본문 2줄) → "답글" 헤더 → 카드 4개(각각 아래 구분선). struct CommentReplySkeletonView: View { + var replyCount: Int = 3 + var body: some View { VStack(spacing: 0) { - card(showsSecondLine: true) - SkeletonView.line(width: 70, height: 16) - .frame(maxWidth: .infinity, alignment: .leading) - .padding(.horizontal, 16) - .padding(.vertical, 12) - .background(.surfaceBeigeSubtle) - ForEach(0 ..< 4, id: \.self) { _ in - card(showsSecondLine: false) - .overlay(alignment: .bottom) { - PickeDivider(.borderBeigeDefault) - } + parentCard() + .padding(12) + .background(.beige50) + .bottomDivider(.beige600) + + VStack(alignment: .leading, spacing: 8) { + SkeletonView(.round(cornerRadius: 4)) + .frame(width: 64, height: 14) + .padding(.horizontal, 12) + .padding(.top, 12) + + ForEach(0 ..< replyCount, id: \.self) { _ in + card() + .padding(.horizontal, 12) + } } + .padding(.bottom, 24) + .frame(maxWidth: .infinity, alignment: .leading) + .background(.beige50) } - .allowsHitTesting(false) + .frame(maxWidth: .infinity, maxHeight: .infinity, alignment: .top) + } + + @ViewBuilder + private func parentCard() -> some View { + card() } @ViewBuilder - private func card(showsSecondLine: Bool) -> some View { - VStack(alignment: .leading, spacing: 0) { - HStack(spacing: 8) { - SkeletonView.beige(.circle) - .frame(width: 32, height: 32) + private func card() -> some View { + VStack(alignment: .leading, spacing: 8) { + HStack(alignment: .top, spacing: 8) { + SkeletonView(.round(cornerRadius: 18)) + .frame(width: 36, height: 36) VStack(alignment: .leading, spacing: 4) { - SkeletonView.line(width: 48, height: 16) - SkeletonView.line(width: 40, height: 12) + SkeletonView(.round(cornerRadius: 4)).frame(width: 90, height: 14) + SkeletonView(.round(cornerRadius: 4)).frame(width: 56, height: 16) } - Spacer(minLength: 0) + Spacer() } - SkeletonView.line(width: 70, height: 20) - .padding(.top, 8) - SkeletonView.line(width: 260, height: 16) - .padding(.top, 12) - if showsSecondLine { - SkeletonView.line(width: 180, height: 16) - .padding(.top, 4) + SkeletonView(.round(cornerRadius: 4)).frame(maxWidth: .infinity).frame(height: 12) + SkeletonView(.round(cornerRadius: 4)).frame(width: 220, height: 12) + HStack { + Spacer() + SkeletonView(.round(cornerRadius: 4)).frame(width: 44, height: 14) } - SkeletonView.line(width: 36, height: 16) - .frame(maxWidth: .infinity, alignment: .trailing) - .padding(.top, 12) } - .padding(16) + .padding(12) .frame(maxWidth: .infinity, alignment: .leading) - .background(.surfaceBeigeDefault) + .pickeCard(.beige50, border: .beige600) } } diff --git a/Projects/Feature/Chat/Sources/Curation/View/Components/CurationSkeletonView.swift b/Projects/Feature/Chat/Sources/Curation/View/Components/CurationSkeletonView.swift index fb0e9054..2bc50c05 100644 --- a/Projects/Feature/Chat/Sources/Curation/View/Components/CurationSkeletonView.swift +++ b/Projects/Feature/Chat/Sources/Curation/View/Components/CurationSkeletonView.swift @@ -5,91 +5,58 @@ // Created by Picke on 10/11/26. // -import PickeDesignKit import SwiftUI -/// Android `RecommendListSkeleton` — 카드 4개, 좌우·위 16, 아래 80, 간격 16. +import PickeDesignKit + struct CurationSkeletonView: View { + var count: Int = 4 + var body: some View { VStack(spacing: 16) { - ForEach(0 ..< 4, id: \.self) { _ in + ForEach(0 ..< count, id: \.self) { _ in card() } } - .padding(.horizontal, 16) - .padding(.top, 16) - .padding(.bottom, 80) - .frame(maxHeight: .infinity, alignment: .top) - .allowsHitTesting(false) } @ViewBuilder private func card() -> some View { - VStack(alignment: .leading, spacing: 0) { - HStack(spacing: 0) { - line(width: 50, height: 18) - Spacer(minLength: 0) - line(width: 70, height: 14) + VStack(alignment: .leading, spacing: 16) { + // meta + HStack(spacing: 10) { + SkeletonView(.round(cornerRadius: .radiusDefault)).frame(width: 44, height: 18) + Spacer() + SkeletonView(.round(cornerRadius: 4)).frame(width: 36, height: 12) + SkeletonView(.round(cornerRadius: 4)).frame(width: 36, height: 12) + } + VStack(alignment: .leading, spacing: 4) { + SkeletonView(.round(cornerRadius: 4)).frame(maxWidth: .infinity).frame(height: 14) + SkeletonView(.round(cornerRadius: 4)).frame(width: 220, height: 12) } - line(width: 200, height: 18) - .padding(.top, 12) - line(width: 240, height: 14) - .padding(.top, 6) - HStack(spacing: 2) { - opinionBox() - block(.circle) - .frame(width: 40, height: 40) - opinionBox() + // versus + HStack(spacing: 8) { + optionPlaceholder() + SkeletonView(.round(cornerRadius: 12)).frame(width: 24, height: 24) + optionPlaceholder() } - .padding(.top, 8) } .padding(12) .frame(maxWidth: .infinity, alignment: .leading) - .roundedBorder( - .borderBeigeDefault, - lineWidth: 1, - radius: .radiusDefault, - insideBorder: true - ) + .pickeCard(.beige50, border: .beige600) } @ViewBuilder - private func opinionBox() -> some View { + private func optionPlaceholder() -> some View { HStack(spacing: 4) { - block(.circle) - .frame(width: 40, height: 40) - VStack(alignment: .leading, spacing: 2) { - line(width: 50, height: 14) - line(width: 36, height: 12) + SkeletonView(.round(cornerRadius: 20)).frame(width: 40, height: 40) + VStack(spacing: 2) { + SkeletonView(.round(cornerRadius: 4)).frame(width: 44, height: 11) + SkeletonView(.round(cornerRadius: 4)).frame(width: 30, height: 10) } - Spacer(minLength: 0) } - .padding(8) .frame(maxWidth: .infinity) - .roundedBorder( - .borderBeigeDisabled, - lineWidth: 1, - radius: .radiusDefault, - insideBorder: true - ) - } - - /// Android `PickeSkeletonLine` — radius 4, 좁은 자리에서는 줄어든다. - private func line( - width: CGFloat, - height: CGFloat - ) -> some View { - block(.round(cornerRadius: 4)) - .frame(maxWidth: width) - .frame(height: height) - } - - /// Android `Modifier.shimmer()` 기본 색. - private func block(_ shape: SkeletonShape) -> some View { - SkeletonView( - shape, - base: .surfaceBeigeStrong, - highlight: .surfaceBeigeDefault - ) + .padding(8) + .pickeCard(.beige300, border: .beige600) } } diff --git a/Projects/Feature/Chat/Sources/Curation/View/CurationView.swift b/Projects/Feature/Chat/Sources/Curation/View/CurationView.swift index 399aef7c..77513120 100644 --- a/Projects/Feature/Chat/Sources/Curation/View/CurationView.swift +++ b/Projects/Feature/Chat/Sources/Curation/View/CurationView.swift @@ -28,6 +28,8 @@ public struct CurationView: View { GeometryReader { viewport in if store.viewState == .loading, store.battles.isEmpty { CurationSkeletonView() + .padding(.horizontal, 16) + .padding(.top, 16) } else { battleList(viewport: viewport) } diff --git a/Projects/Feature/Chat/Sources/Vote/Reducer/PreVoteFeature.swift b/Projects/Feature/Chat/Sources/Vote/Reducer/PreVoteFeature.swift index 656a1044..fe17b3e6 100644 --- a/Projects/Feature/Chat/Sources/Vote/Reducer/PreVoteFeature.swift +++ b/Projects/Feature/Chat/Sources/Vote/Reducer/PreVoteFeature.swift @@ -49,6 +49,13 @@ public struct PreVoteFeature { /// 클래스의 기존 콘텐츠에서 기참여 결과 화면을 보여줄 때만 설정한다. public var showsResultsForExistingParticipation: Bool = false @Presents public var customAlert: CustomAlertState? + /// Android `VoteUiEvent` 토스트 문구. 보여준 뒤 `toastShown` 으로 비운다. + public var toastMessage: String? + + /// Android `VoteBattleNotFound` — 상세를 못 불러오면 빈 상태 화면을 보인다. + public var isBattleNotFound: Bool { + detailLoadFailed && battle == nil + } public var isShowingParticipationResult: Bool { showsResultsForExistingParticipation && voteMode == .pre && ( @@ -95,6 +102,7 @@ public struct PreVoteFeature { case onAppear case backButtonTapped case retryTapped + case toastShown case shareTapped case shareSnapshotRendered(Data?) case optionTapped(optionId: Int) @@ -135,6 +143,8 @@ public struct PreVoteFeature { case voteSubmitted(battleId: Int, voteMode: VoteMode, result: PreVoteResult, isMindChanged: Bool) /// 이미 최종 투표(POST_VOTE)까지 마친 상태 — 댓글 화면으로 바로 이동. case alreadyFinalVoted(battleId: Int) + /// 포인트 부족 안내의 "배틀 주제 구경하러 가기" — 탐색 탭으로 이동. + case openExplore } nonisolated enum CancelID: Hashable { @@ -192,9 +202,9 @@ extension PreVoteFeature { if state.battleDetail == nil, state.battle == nil, state.viewState != .loading { effects.append(.send(.async(.fetchBattleDetail))) } - // 사전(pre) 진입 시에만 내 참여(perspective) 여부를 조회한다. - // 일반 배틀은 기참여 시 관점 화면으로 직행한다. 클래스 기존 콘텐츠는 결과 화면을 유지한다. - if state.voteMode == .pre, state.myPerspective == nil { + // 클래스 기존 콘텐츠만 내 참여(perspective) 여부를 조회해 결과 화면을 유지한다. + // 일반 배틀은 Android `BattleRouting` 처럼 상세의 단계(currentStep)로 진입을 판정한다. + if state.voteMode == .pre, state.showsResultsForExistingParticipation, state.myPerspective == nil { // 일반 배틀은 기참여 시 관점으로 직행하고 클래스 기존 콘텐츠는 결과 요약을 보여주므로, 확인 전에는 투표 UI를 숨긴다. state.isCheckingParticipation = true effects.append(.send(.async(.fetchMyPerspective))) @@ -215,8 +225,13 @@ extension PreVoteFeature { return .send(.async(.prepareShare(shareContent(state: state, snapshot: snapshot)))) case let .optionTapped(optionId): + // Android `selectedOptionId = optionId` — 같은 카드를 다시 눌러도 선택을 유지한다. guard !state.isShowingParticipationResult else { return .none } - state.selectedOptionId = (state.selectedOptionId == optionId) ? nil : optionId + state.selectedOptionId = optionId + return .none + + case .toastShown: + state.toastMessage = nil return .none case .primaryButtonTapped: @@ -370,8 +385,13 @@ extension PreVoteFeature { state.battleDetail = detail state.battle = makeBattle(from: detail) state.detailLoadFailed = false + // Android: 일반 배틀은 단계가 COMPLETED 이면 관점 화면으로 바로 간다. + if state.voteMode == .pre, !state.showsResultsForExistingParticipation, detail.currentStep == .completed { + return .send(.delegate(.alreadyFinalVoted(battleId: state.battleId))) + } case let .failure(error): state.detailLoadFailed = true + state.toastMessage = "정보를 불러오지 못했어요" PickeLogger.error( "[PreVoteFeature] fetchBattle failed: \(error) — \(error.localizedDescription)", category: .ui @@ -389,8 +409,7 @@ extension PreVoteFeature { state.selectedOptionId = nil return .none } - // 일반 배틀은 기존대로 관점(댓글) 화면으로 바로 직행. - return .send(.delegate(.alreadyFinalVoted(battleId: state.battleId))) + // 일반 배틀의 진입 판정은 상세 단계(currentStep)로 한다(위 battleDetailResponse). } case let .failure(error): PickeLogger.error("[PreVoteFeature] fetchMyPerspective failed: \(error.localizedDescription)", category: .ui) @@ -421,6 +440,11 @@ extension PreVoteFeature { ))) case let .failure(error): PickeLogger.error("[PreVoteFeature] submitPreVote failed: \(error.localizedDescription)", category: .ui) + if error == .insufficientPoints { + state.customAlert = .pointShortage() + } else { + state.toastMessage = "요청을 처리하지 못했어요" + } return .none } @@ -446,6 +470,9 @@ extension PreVoteFeature { result: voteResult, isMindChanged: mindChanged ))) + case let .failure(error) where error == .insufficientPoints: + state.customAlert = .pointShortage() + return .none case let .failure(error): // 최종투표는 1회만 가능 — 이미 투표한 경우 서버가 500. // 재투표가 불가하므로 결과(댓글) 화면으로 이동한다. @@ -509,7 +536,7 @@ extension PreVoteFeature { action: DelegateAction ) -> Effect { switch action { - case .dismiss, .voteSubmitted, .alreadyFinalVoted: + case .dismiss, .voteSubmitted, .alreadyFinalVoted, .openExplore: return .none } } @@ -523,12 +550,20 @@ extension PreVoteFeature { switch alertAction { case let .presented(customAlertAction): switch customAlertAction { + case .confirmTapped where state.customAlert == .pointShortage(): + state.customAlert = nil + return .send(.delegate(.openExplore)) + case .confirmTapped: let perspectiveId = state.myPerspective?.perspectiveId state.customAlert = nil guard let perspectiveId else { return .none } return .send(.async(.deleteMyPerspective(perspectiveId: perspectiveId))) + case .cancelTapped where state.customAlert == .pointShortage(): + state.customAlert = nil + return .none + case .cancelTapped: state.customAlert = nil // 이미 참여한 배틀에서 '취소' — 밖으로 나가지 않고 관점(댓글) 화면으로 이동. diff --git a/Projects/Feature/Chat/Sources/Vote/View/PreVoteLayout.swift b/Projects/Feature/Chat/Sources/Vote/View/PreVoteLayout.swift deleted file mode 100644 index f8806694..00000000 --- a/Projects/Feature/Chat/Sources/Vote/View/PreVoteLayout.swift +++ /dev/null @@ -1,40 +0,0 @@ -// -// PreVoteLayout.swift -// Chat -// -// Created by Picke on 10/11/26. -// - -import CoreGraphics - -enum PreVoteLayout { - static let contentOverlapTopOffset: CGFloat = 280 - static let backgroundImageHeight: CGFloat = 512 - static let imageToContentGradientHeight: CGFloat = 260 - static let rootContentSpacing: CGFloat = 40 - static let contentToOptionSpacing: CGFloat = 40 - static let optionCardHeight: CGFloat = 106 - static let contentHorizontalPadding: CGFloat = 16 - static let contentTopPadding: CGFloat = 80 - static let ctaHeight: CGFloat = 52 - static let ctaBottomSpacing: CGFloat = 40 - static let ctaHorizontalPadding: CGFloat = 16 - /// CTA 가 safeAreaInset 으로 스크롤 하단에 예약하는 총 높이(버튼 + 하단 여백). - static let ctaReservedHeight: CGFloat = ctaHeight + ctaBottomSpacing - /// CTA 는 safeAreaInset 이 예약하므로, 콘텐츠 하단 여백은 옵션과 CTA 사이 간격만 남긴다. - static let contentBottomSpacing: CGFloat = rootContentSpacing - static let snapshotWidth: CGFloat = 360 - - /// 제목·요약 길이에 따라 그라데이션 여백을 동적으로 결정(3단계). - /// 텍스트가 짧을수록 여백을 키워 콘텐츠를 아래로, 길수록 줄여 위로 끌어올린다. - static func contentGradientSpacerHeight( - titleLength: Int, - summaryLength: Int - ) -> CGFloat { - switch titleLength + summaryLength { - case ...60: 76 - case 61 ... 90: 60 - default: 52 - } - } -} diff --git a/Projects/Feature/Chat/Sources/Vote/View/PreVoteView.swift b/Projects/Feature/Chat/Sources/Vote/View/PreVoteView.swift index bacdf14a..4d0e67bd 100644 --- a/Projects/Feature/Chat/Sources/Vote/View/PreVoteView.swift +++ b/Projects/Feature/Chat/Sources/Vote/View/PreVoteView.swift @@ -20,44 +20,34 @@ public struct PreVoteView: View { self.store = store } - /// 안드로이드 시안: 사후(최종) 투표는 사전투표와 구분되도록 화면 배경을 통째로 검정으로 교체. - /// (VoteScreen.kt — PRE: surface, POST: Color.Black. 옵션 카드/CTA/상단바 색은 동일) private var isPostVote: Bool { store.voteMode == .post } - private var screenBackground: Color { - isPostVote ? .black : .beige50 - } - - private var titleColor: Color { - isPostVote ? .beige50 : .neutral500 + /// Android `VoteScreenStyle.containerColor` — 사전 `surfaceBeigeDefault`, 최종 검정. + private var containerColor: Color { + isPostVote ? .black : .surfaceBeigeDefault } public var body: some View { Group { - if shouldShowLoadError { - loadErrorContent() + if store.isBattleNotFound { + battleNotFound() } else if shouldShowSkeleton { PreVoteSkeletonView(isDark: isPostVote) - } else { - loadedContent() + } else if let battle = store.battle { + loadedContent(battle) } } - .background(screenBackground.ignoresSafeArea()) + .background(containerColor.ignoresSafeArea()) .navigationBarHidden(true) .hidesSystemBars() - .overlay(alignment: .top) { - if !shouldShowSkeleton, !shouldShowLoadError { - navigationBar() - .background(.clear) - .padding(.top, 12) - .frame(maxWidth: .infinity) - .contentShape(Rectangle()) - .zIndex(10) - } - } .onAppear { send(.onAppear) } + .onChange(of: store.toastMessage, initial: true) { _, message in + guard let message else { return } + ToastManager.shared.showError(message) + send(.toastShown) + } .onChange(of: store.shareSnapshotRequest) { _, request in guard let request else { return } send(.shareSnapshotRendered(captureCardSnapshot(request))) @@ -70,223 +60,148 @@ public struct PreVoteView: View { .customAlert($store.scope(state: \.customAlert, action: \.scope.customAlert)) } - /// 로드 실패 & 아직 표시할 배틀이 없을 때 무한 스켈레톤 대신 오류+재시도 노출. - private var shouldShowLoadError: Bool { - store.detailLoadFailed && store.battle == nil - } - private var shouldShowSkeleton: Bool { - (store.viewState == .loading || store.battle == nil || store.isCheckingParticipation) && !shouldShowLoadError + store.viewState == .loading || store.battle == nil || store.isCheckingParticipation } + /// Android `VoteBattleNotFound` — `backgroundBeige` 상단 바 + 빈 상태 "해당 배틀은 존재하지 않습니다". @ViewBuilder - private func loadErrorContent() -> some View { + private func battleNotFound() -> some View { VStack(spacing: 0) { PickeNavigationBar(onBack: { send(.backButtonTapped) }) - .foregroundStyle(.neutral800) - - PickeRetryErrorView(message: "배틀을 불러오지 못했어요") { send(.retryTapped) } + .foregroundStyle(.textDefault) + PickeEmptyStateView(message: "해당 배틀은 존재하지 않습니다") + .frame(maxWidth: .infinity, maxHeight: .infinity) } - .frame(maxWidth: .infinity, maxHeight: .infinity) + .screenBackground() } + /// Android `VoteContent` — 히어로(남는 높이 전부) → 24 → 선택지 → 32 → 하단 버튼(패딩 20). @ViewBuilder - private func loadedContent() -> some View { - if let battle = store.battle { - GeometryReader { proxy in - let topInset = PreVoteLayout.contentOverlapTopOffset - + PreVoteLayout.contentGradientSpacerHeight( - titleLength: battle.titleLine1.count + battle.titleLine2.count, - summaryLength: battle.summary.count - ) - - ZStack(alignment: .top) { - backgroundImage(battle) - .frame(width: proxy.size.width) - - // 히어로 오버랩 여백을 스크롤 콘텐츠 안에 둔다. 공간이 남는 화면(16 Pro 등)에서는 - // minHeight 로 뷰포트를 채워 옵션 카드가 CTA 바로 위에 붙고, 부족한 화면에서는 - // 여백까지 함께 스크롤돼 카드가 잘린 채 고정되지 않는다. - ScrollView { - VStack(spacing: 0) { - Color.clear - .frame(height: topInset) - - contentArea(battle) - } - .frame( - minHeight: max(0, proxy.size.height - PreVoteLayout.ctaReservedHeight), - alignment: .top - ) - } - .scrollIndicators(.hidden) - .frame(width: proxy.size.width, height: proxy.size.height, alignment: .top) - .safeAreaInset(edge: .bottom, spacing: 0) { - primaryButton() - .padding(.horizontal, PreVoteLayout.ctaHorizontalPadding) - .padding(.bottom, PreVoteLayout.ctaBottomSpacing) - } - } - .ignoresSafeArea(edges: .top) - } - } else { - PreVoteSkeletonView(isDark: isPostVote) + private func loadedContent(_ battle: PreVoteBattle) -> some View { + VStack(spacing: 0) { + heroSection(battle) + .frame(maxWidth: .infinity, maxHeight: .infinity) + optionSection(battle) + .padding(.horizontal, 20) + .padding(.top, 24) + .padding(.bottom, 32) + primaryButton + .padding(20) + } + .overlay(alignment: .top) { + navigationBar() } } } -// MARK: - Background +// MARK: - Hero extension PreVoteView { + /// Android `VoteBattleInfoSection` — 이미지를 꽉 채우고 위→아래 `[검정 0.3, 투명, 배경색]` 그라데이션. @ViewBuilder - private func backgroundImage(_ battle: PreVoteBattle) -> some View { - ZStack { - if let urlString = battle.backgroundImageURL, - let url = URL(string: urlString) - { - PickeRemoteImage(url: url) - } else { - Color.neutral200 - } - - Color.black.opacity(0.4) + private func heroSection(_ battle: PreVoteBattle) -> some View { + ZStack(alignment: .bottomLeading) { + heroImage(battle) + contentSection(battle, onDarkBackground: isPostVote) + .padding(.horizontal, 20) + .padding(.bottom, 16) + } + } - VStack { - Spacer() - imageToContentGradient() + private func heroImage(_ battle: PreVoteBattle) -> some View { + Color.clear + .overlay { + PickeRemoteImage(url: battle.backgroundImageURL) { + heroPlaceholder + } } - } - .frame(maxWidth: .infinity) - .frame(height: PreVoteLayout.backgroundImageHeight) - .clipped() + .overlay { + LinearGradient( + colors: [.black.opacity(0.3), .clear, containerColor], + startPoint: .top, + endPoint: .bottom + ) + } + .clipped() + .ignoresSafeArea(edges: .top) } +} +extension PreVoteView { + /// Android 이미지 로딩 shimmer — 최종투표는 `gray600`→`gray400`. @ViewBuilder - private func imageToContentGradient() -> some View { - LinearGradient( - stops: [ - .init(color: screenBackground.opacity(0), location: 0), - .init(color: screenBackground.opacity(0.55), location: 0.55), - .init(color: screenBackground, location: 1), - ], - startPoint: .top, - endPoint: .bottom - ) - .frame(height: PreVoteLayout.imageToContentGradientHeight) + private var heroPlaceholder: some View { + if isPostVote { + SkeletonView(.rect, base: .gray600, highlight: .gray400) + } else { + SkeletonView.beige(.rect) + } } } // MARK: - Navigation bar extension PreVoteView { + /// 뒤로 가기는 iOS 기존 상단 바(`PickeNavigationBar`)를 쓰고, 공유만 Android 아이콘(20)을 쓴다. @ViewBuilder private func navigationBar() -> some View { - HStack { - Button { send(.backButtonTapped) } label: { - Image(systemName: "chevron.left") - .font(.system(size: 24, weight: .regular)) - .frame(width: 20, height: 10) - .contentShape(Rectangle()) - } - .buttonStyle(.plain) - - Spacer() - - Button { - send(.shareTapped) - } label: { - Image(systemName: "square.and.arrow.up") - .font(.system(size: 24, weight: .regular)) + PickeNavigationBar(onBack: { send(.backButtonTapped) }) { + Button { send(.shareTapped) } label: { + Image(asset: .share) + .renderingMode(.template) + .resizable() + .scaledToFit() + .frame(width: 20, height: 20) .frame(width: 24, height: 24) - .contentShape(Rectangle()) } .buttonStyle(.plain) + .accessibilityLabel("공유") } - .padding(.horizontal, 16) - .foregroundStyle(.beige50) + .foregroundStyle(.textInverse) } } -// MARK: - Content (gradient + 카피 + 선택지 + CTA) +// MARK: - Content (태그 + 제목 + 설명) extension PreVoteView { - @ViewBuilder - private func contentArea(_ battle: PreVoteBattle) -> some View { - VStack(spacing: 0) { - contentSection(battle) - // 유연 간격: 콘텐츠는 위(상단 spacer)에 고정, 옵션은 아래로 당겨 CTA 위 40 유지. - Spacer(minLength: PreVoteLayout.contentToOptionSpacing) - optionSection(battle) - } - .padding(.horizontal, PreVoteLayout.contentHorizontalPadding) - .padding(.top, PreVoteLayout.contentTopPadding) - .padding(.bottom, PreVoteLayout.contentBottomSpacing) - .frame(maxWidth: .infinity) - .background( - LinearGradient( - stops: [ - .init(color: screenBackground.opacity(0), location: 0), - .init(color: screenBackground.opacity(0.72), location: 0.42), - .init(color: screenBackground, location: 0.7), - .init(color: screenBackground, location: 1), - ], - startPoint: .top, - endPoint: .bottom - ) - ) - } - @ViewBuilder private func contentSection( _ battle: PreVoteBattle, - titleColorOverride: Color? = nil + onDarkBackground: Bool ) -> some View { - VStack(alignment: .leading, spacing: 12) { - VStack(alignment: .leading, spacing: 20) { - tagsRow(battle) - titleText(battle, colorOverride: titleColorOverride) - } - summaryText(battle) + VStack(alignment: .leading, spacing: 0) { + tagsRow(battle) + Text(battle.displayTitle) + .pretendardFont(.headingXXLarge, lineSpacingMultiple: 1.3) + .foregroundStyle(onDarkBackground ? .surfaceBeigeDefault : .textDefault) + .multilineTextAlignment(.leading) + .fixedSize(horizontal: false, vertical: true) + .padding(.top, 16) + Text(battle.summary) + .pretendardFont(.bodyMedium, lineSpacingMultiple: 1.4) + .foregroundStyle(onDarkBackground ? .gray400 : .textSubtle) + .multilineTextAlignment(.leading) + .fixedSize(horizontal: false, vertical: true) + .padding(.top, 12) } .frame(maxWidth: .infinity, alignment: .leading) } + /// Android `VoteTagChip` — 흰색 0.8 면, radius 2, 안쪽 8/2, 12 Medium `primary500`, 간격 8. @ViewBuilder private func tagsRow(_ battle: PreVoteBattle) -> some View { - HStack(spacing: 9) { + HStack(spacing: 8) { ForEach(battle.tags, id: \.self) { tag in Text(tag) - .pickeBadge(.filled, size: .tag) + .pretendardFont(.labelSmall) + .foregroundStyle(.primary500) + .padding(.horizontal, 8) + .padding(.vertical, 2) + .background(.white.opacity(0.8), in: RoundedRectangle(cornerRadius: .radiusDefault)) } } } - - @ViewBuilder - private func titleText( - _ battle: PreVoteBattle, - colorOverride: Color? = nil - ) -> some View { - Text([battle.titleLine1, battle.titleLine2].filter { !$0.isEmpty }.joined(separator: "\n")) - .pretendardFont(.bold24) - .foregroundStyle(colorOverride ?? titleColor) - .kerning(-0.6) - .lineSpacing(24 * 0.4) - .multilineTextAlignment(.leading) - .lineLimit(nil) - .fixedSize(horizontal: false, vertical: true) - .frame(maxWidth: .infinity, alignment: .leading) - } - - @ViewBuilder - private func summaryText(_ battle: PreVoteBattle) -> some View { - Text(battle.summary) - .pretendardFont(.regular13) - .foregroundStyle(.neutral400) - .lineSpacing(13 * 0.4) - .multilineTextAlignment(.leading) - .lineLimit(nil) - .frame(maxWidth: .infinity, alignment: .leading) - } } // MARK: - 선택지 @@ -302,92 +217,106 @@ extension PreVoteView { optionCard(battle.leftOption, avatarOverride: avatarOverrides[battle.leftOption.optionId]) optionCard(battle.rightOption, avatarOverride: avatarOverrides[battle.rightOption.optionId]) } - .frame(maxWidth: .infinity) - vsBadge() + // Android `height(IntrinsicSize.Max)` — 두 카드 높이를 큰 쪽에 맞춘다. + .fixedSize(horizontal: false, vertical: true) + vsBadge } } + /// Android `VoteOptionCard` — `surfaceBeigeSubtle` 면, 선택 `secondary500` / 그 외 `borderBeigeDisabled`, + /// 안쪽 세로 24·가로 16, 아바타 40 → 16 → 제목 16 SemiBold → 4 → 대표 10 SemiBold. 비선택 0.8. @ViewBuilder private func optionCard( _ option: PreVoteOption, avatarOverride: UIImage? = nil ) -> some View { let isSelected = store.selectedOptionId == option.optionId - - return Button { + Button { send(.optionTapped(optionId: option.optionId)) } label: { - VStack(spacing: 12) { + VStack(spacing: 0) { avatarView(imageURL: option.imageURL, override: avatarOverride) - - VStack(spacing: 2) { - Text(option.stance) - .pretendardFont(.headingSmall) - .foregroundStyle(.neutral600) - .kerning(-0.35) - .lineLimit(2) - .minimumScaleFactor(0.85) - .multilineTextAlignment(.center) - - Text(option.representative) - .pretendardFont(.labelSmall) - .foregroundStyle(.neutral300) - .lineLimit(1) - .minimumScaleFactor(0.85) - .multilineTextAlignment(.center) - } + Text(option.stance) + .pretendardFont(.headingMedium, lineSpacingMultiple: 1.3) + .foregroundStyle(.textDefault) + .multilineTextAlignment(.center) + .fixedSize(horizontal: false, vertical: true) + .padding(.top, 16) + Text(option.representative) + .pretendardFont(.labelXSmall) + .foregroundStyle(.textSubtler) + .padding(.top, 4) } - .padding(8) - .frame(maxWidth: .infinity) - .frame(height: PreVoteLayout.optionCardHeight) + .padding(.vertical, 24) + .padding(.horizontal, 16) + .frame(maxWidth: .infinity, maxHeight: .infinity) .pickeCard( - .beige300, - border: isSelected ? (isPostVote ? .secondary500 : .beige700) : .beige500 + .surfaceBeigeSubtle, + border: isSelected ? .secondary500 : .borderBeigeDisabled ) - .opacity(isSelected ? 1.0 : 0.88) + .opacity(isSelected ? 1 : 0.8) + .contentShape(Rectangle()) } .buttonStyle(.plain) } + /// Android `ProfileImage(40)` — `borderBeigeDefault` 원 + 가운데 2/3 크기 이미지(fit). @ViewBuilder - private func avatarView(imageURL: String, override: UIImage? = nil) -> some View { - Group { - if let override { - Image(uiImage: override) - .resizable() - .scaledToFit() - } else { - PickeRemoteImage(url: imageURL) { - SkeletonView(.round()) - .frame(width: 28, height: 20) + private func avatarView( + imageURL: String, + override: UIImage? = nil + ) -> some View { + Circle() + .fill(.borderBeigeDefault) + .overlay { + Group { + if let override { + Image(uiImage: override) + .resizable() + .scaledToFit() + } else { + PickeRemoteImage(url: imageURL) { + Color.clear + } + .content(.fit) + } } - .content(.fit) + .frame(width: 40 * 2 / 3, height: 40 * 2 / 3) } - } - .frame(width: 28, height: 20) - .frame(width: 40, height: 40) - .background(.beige600, in: Circle()) + .frame(width: 40, height: 40) } - @ViewBuilder - private func vsBadge() -> some View { + /// Android `VoteVersusBadge` — 36 원 `secondary200`, "VS" 14 Medium `textDefault`. + private var vsBadge: some View { Text("VS") - .pretendardFont(.bold11) - .foregroundStyle(.neutral800) - .frame(width: 28, height: 28) + .pretendardFont(.labelMedium) + .foregroundStyle(.textDefault) + .frame(width: 36, height: 36) .background(.secondary200, in: Circle()) - .overlay(Circle().stroke(.beige50, lineWidth: 1.5)) } } // MARK: - CTA extension PreVoteView { - @ViewBuilder - private func primaryButton() -> some View { - Button(store.primaryButtonTitle) { send(.primaryButtonTapped) } - .ctaButtonStyle(.primary, size: .large, height: PreVoteLayout.ctaHeight) - .disabled(!store.isPrimaryButtonEnabled) + /// Android `PickeButton` — 높이 48 이상, radius 2, 14 SemiBold `surfaceBeigeDefault`, 비활성 `primary300`. + private var primaryButton: some View { + Button { + send(.primaryButtonTapped) + } label: { + Text(store.primaryButtonTitle) + .pretendardFont(.headingSmall) + .foregroundStyle(.surfaceBeigeDefault) + .frame(maxWidth: .infinity, minHeight: 48) + .roundedBackground( + store.isPrimaryButtonEnabled ? .buttonPrimaryBackgroundDefault : .primary300, + radius: .radiusDefault + ) + } + .buttonStyle(.plain) + // `.disabled` 는 글자까지 흐리게 해서, Android 처럼 배경색만 바꾸고 누름만 막는다. + .allowsHitTesting(store.isPrimaryButtonEnabled) + .accessibilityAddTraits(store.isPrimaryButtonEnabled ? [] : .isStaticText) } } @@ -408,14 +337,14 @@ extension PreVoteView { _ battle: PreVoteBattle, avatarOverrides: [Int: UIImage] ) -> some View { - VStack(spacing: PreVoteLayout.contentToOptionSpacing) { + VStack(spacing: 24) { // 스냅샷 배경은 모드와 무관하게 밝은색이라, 사후(post) 화면의 밝은 제목색을 // 그대로 쓰면 베이지 위 베이지로 묻힌다 → 항상 어두운 제목색으로 고정. - contentSection(battle, titleColorOverride: .neutral500) + contentSection(battle, onDarkBackground: false) optionSection(battle, avatarOverrides: avatarOverrides) } .padding(16) - .frame(width: PreVoteLayout.snapshotWidth) + .frame(width: 360) .background(.beige50) } } diff --git a/Projects/Feature/Chat/Tests/Sources/ChatRoomParityTests.swift b/Projects/Feature/Chat/Tests/Sources/ChatRoomParityTests.swift new file mode 100644 index 00000000..7b9198d0 --- /dev/null +++ b/Projects/Feature/Chat/Tests/Sources/ChatRoomParityTests.swift @@ -0,0 +1,169 @@ +// +// ChatRoomParityTests.swift +// ChatTests +// +// Created by Picke on 11/10/26. +// + +import AudioPlayerServiceInterface +@testable import Chat +import ComposableArchitecture +import Foundation +import HomeDomainInterface +import PickeSharedUI +import Testing + +/// Android `ScenarioViewModel` 동작과 맞춘 부분. +@MainActor +struct ChatRoomParityTests { + @Test + func playbackRateCyclesLikeAndroid() { + var state = ChatRoomFeature.State() + var titles: [String] = [] + for _ in 0 ..< 4 { + titles.append(state.playbackRateTitle) + state.playbackRate = state.nextPlaybackRate + } + #expect(titles == ["1.0", "1.5", "2.0", "3.0"]) + #expect(state.playbackRate == 1) + } + + @Test + func scrubStopsAtListenedPosition() async { + var state = Self.listeningState() + state.maxListenedTime = 12 + let store = Self.store(state) + + await store.send(.view(.scrub(30))) + #expect(store.state.currentTime == 12) + } + + @Test + func forwardIsBlockedWhileFinalVoteDialogIsShown() async { + var state = Self.listeningState() + state.currentTime = 5 + state.customAlert = .finalVote() + let store = Self.store(state) + + #expect(store.state.isForwardEnabled == false) + await store.send(.view(.seekForwardTapped)) + #expect(store.state.currentTime == 5) + } + + @Test + func reviewingShowsEveryLineAndDoesNotAskAgain() async { + let store = Self.store(Self.listeningState()) + + await store.send(.inner(.playerTimeUpdated(40))) + #expect(store.state.customAlert == .finalVote()) + + await store.send(.scope(.customAlert(.presented(.cancelTapped)))) + #expect(store.state.isReviewing) + #expect(store.state.currentTime == 0) + #expect(store.state.isPlaying) + #expect(store.state.messages.count == 3) + + await store.send(.inner(.playerTimeUpdated(40))) + #expect(store.state.customAlert == nil) + } + + @Test + func dismissingFinalVoteDialogGoesToFinalVote() async { + var state = Self.listeningState() + state.customAlert = .finalVote() + let store = Self.store(state) + + await store.send(.scope(.customAlert(.dismiss))) + await store.receive { action in + guard case .delegate(.requestFinalVote(battleId: 990)) = action else { return false } + return true + } + } + + @Test + func tappingLineSeeksToItsStart() async throws { + var state = Self.listeningState() + state.currentTime = 25 + state.maxListenedTime = 25 + let store = Self.store(state) + let second = try #require(store.state.messages.first { $0.text == "두 번째 대사" }) + + await store.send(.view(.messageTapped(second.id))) + #expect(store.state.currentTime == 10) + #expect(store.state.isPlaying) + } + + @Test + func loadFailureShowsToastOnly() async { + let store = Self.store(ChatRoomFeature.State()) + + await store.send(.inner(.scenarioResponse(.failure(.noData)))) + #expect(store.state.toastMessage == "정보를 불러오지 못했어요") + #expect(store.state.messages.isEmpty) + #expect(store.state.battleTitle.isEmpty) + #expect(store.state.totalDuration == 0) + } +} + +extension ChatRoomParityTests { + private static func store(_ state: ChatRoomFeature.State) -> TestStoreOf { + let store = TestStore(initialState: state) { + ChatRoomFeature() + } withDependencies: { + $0.audioPlayer = SilentAudioPlayer() + } + store.exhaustivity = .off + return store + } + + private static func listeningState() -> ChatRoomFeature.State { + var state = ChatRoomFeature.State(battleId: 990) + state.scenario = scenario + state.currentNodeId = 1 + state.visibleNodeIds = [1] + state.playerDuration = 40 + return state + } + + private static let scenario = BattleScenario( + battleId: 990, + title: "테스트 배틀", + philosophers: [], + isInteractive: false, + startNodeId: 1, + recommendedPathKey: .common, + audios: [:], + nodes: [ + ScenarioNode( + nodeId: 1, + nodeName: "START", + audioDuration: 40, + autoNextNodeId: nil, + scripts: [ + ScenarioScript(scriptId: 1, startTimeMs: 0, speakerType: .a, speakerName: "플라톤", text: "첫 번째 대사"), + ScenarioScript(scriptId: 2, startTimeMs: 10000, speakerType: .b, speakerName: "사르트르", text: "두 번째 대사"), + ScenarioScript(scriptId: 3, startTimeMs: 20000, speakerType: .a, speakerName: "플라톤", text: "세 번째 대사"), + ], + interactiveOptions: [] + ), + ] + ) +} + +private actor SilentAudioPlayer: AudioPlayerInterface { + func setPlaybackRate(_: Float) async {} + func load(url _: URL) async -> Bool { + true + } + + func play() async {} + func pause() async {} + func seek(to _: TimeInterval) async {} + func duration() async -> TimeInterval { + 0 + } + + nonisolated func currentTimes() -> AsyncStream { + AsyncStream { $0.finish() } + } +} diff --git a/Projects/Feature/Chat/Tests/Sources/ChatTests.swift b/Projects/Feature/Chat/Tests/Sources/ChatTests.swift index bdbdef56..49a9b950 100644 --- a/Projects/Feature/Chat/Tests/Sources/ChatTests.swift +++ b/Projects/Feature/Chat/Tests/Sources/ChatTests.swift @@ -104,15 +104,16 @@ struct ChatTests { $0.audioPlayer = player } - #expect(ChatRoomFeature.State.supportedPlaybackRates == [1, 1.25, 1.5, 2]) + #expect(ChatRoomFeature.State.supportedPlaybackRates == [1, 1.5, 2, 3]) #expect(store.state.playbackRateTitle == "1.0") - await store.send(.view(.playbackRateSelected(1.25))) { - $0.playbackRate = 1.25 + #expect(store.state.nextPlaybackRate == 1.5) + await store.send(.view(.playbackRateSelected(1.5))) { + $0.playbackRate = 1.5 } await store.finish() - #expect(store.state.playbackRateTitle == "1.25") + #expect(store.state.playbackRateTitle == "1.5") #expect(store.state.isPlaying == false) - #expect(await player.events == [.rate(1.25)]) + #expect(await player.events == [.rate(1.5)]) } @Test @MainActor @@ -124,7 +125,7 @@ struct ChatTests { $0.audioPlayer = player } - for rate in [Float(0), 1.75, .nan, .infinity, -.infinity] { + for rate in [Float(0), 1.25, 1.75, .nan, .infinity, -.infinity] { await store.send(.view(.playbackRateSelected(rate))) } await store.finish() @@ -194,9 +195,11 @@ struct ChatTests { await store.send(.inner(.playerTimeUpdated(15.6))) { $0.pendingSeekTime = nil $0.currentTime = 15.6 + $0.maxListenedTime = 15.6 } await store.send(.inner(.playerTimeUpdated(16.1))) { $0.currentTime = 16.1 + $0.maxListenedTime = 16.1 } await store.finish() } diff --git a/Projects/Feature/Chat/Tests/Sources/PreVoteParityTests.swift b/Projects/Feature/Chat/Tests/Sources/PreVoteParityTests.swift new file mode 100644 index 00000000..68fe0425 --- /dev/null +++ b/Projects/Feature/Chat/Tests/Sources/PreVoteParityTests.swift @@ -0,0 +1,73 @@ +// +// PreVoteParityTests.swift +// ChatTests +// +// Created by Picke on 11/10/26. +// + +@testable import Chat +import BattleDomainInterface +import ComposableArchitecture +import Foundation +import PickeSharedUI +import Testing + +/// Android `VoteViewModel` 동작과 맞춘 부분. +@MainActor +struct PreVoteParityTests { + @Test + func tappingSelectedOptionKeepsSelection() async { + var state = PreVoteFeature.State(battleId: 41) + state.battle = .mock + let store = TestStore(initialState: state) { PreVoteFeature() } + + await store.send(.view(.optionTapped(optionId: 1))) { + $0.selectedOptionId = 1 + } + await store.send(.view(.optionTapped(optionId: 1))) + } + + @Test + func detailFailureShowsToastAndNotFound() async { + let store = TestStore(initialState: PreVoteFeature.State(battleId: 41)) { PreVoteFeature() } + store.exhaustivity = .off + + await store.send(.inner(.battleDetailResponse(.failure(.noData)))) + #expect(store.state.toastMessage == "정보를 불러오지 못했어요") + #expect(store.state.isBattleNotFound) + } + + @Test + func preVoteFailureShowsActionFailedToast() async { + let store = TestStore(initialState: PreVoteFeature.State(battleId: 41)) { PreVoteFeature() } + store.exhaustivity = .off + + await store.send(.inner(.preVoteResponse(.failure(.serverError(500))))) + #expect(store.state.toastMessage == "요청을 처리하지 못했어요") + } + + @Test + func insufficientPointsShowsDialogAndOpensExplore() async { + let store = TestStore(initialState: PreVoteFeature.State(battleId: 41)) { PreVoteFeature() } + store.exhaustivity = .off + + await store.send(.inner(.preVoteResponse(.failure(.insufficientPoints)))) + #expect(store.state.customAlert == .pointShortage()) + #expect(store.state.toastMessage == nil) + + await store.send(.scope(.customAlert(.presented(.confirmTapped)))) + await store.receive(\.delegate, .openExplore) + #expect(store.state.customAlert == nil) + } + + @Test + func postVoteInsufficientPointsStaysOnScreen() async { + let store = TestStore( + initialState: PreVoteFeature.State(battleId: 41, voteMode: .post) + ) { PreVoteFeature() } + store.exhaustivity = .off + + await store.send(.inner(.postVoteResponse(.failure(.insufficientPoints)))) + #expect(store.state.customAlert == .pointShortage()) + } +} diff --git a/Projects/Feature/Class/Sources/ClassBattleFlow/Reducer/ClassBattleFlowFeature.swift b/Projects/Feature/Class/Sources/ClassBattleFlow/Reducer/ClassBattleFlowFeature.swift index 62f543fc..ba546520 100644 --- a/Projects/Feature/Class/Sources/ClassBattleFlow/Reducer/ClassBattleFlowFeature.swift +++ b/Projects/Feature/Class/Sources/ClassBattleFlow/Reducer/ClassBattleFlowFeature.swift @@ -108,9 +108,8 @@ public struct ClassBattleFlowFeature { case .ttsListening: return hasListened && pendingCheckpointID == nil && hasAnsweredCurrentPath case .completed: - return !hasSubmittedInCurrentSession - && hasPublishedPerspective == false - && !draft.trimmingCharacters(in: .whitespacesAndNewlines).isEmpty + // Android PerspectiveScreen 처럼 의견을 이미 올렸어도 추가로 작성할 수 있다. + return !draft.trimmingCharacters(in: .whitespacesAndNewlines).isEmpty } } @@ -181,8 +180,8 @@ public struct ClassBattleFlowFeature { public var shouldShowComposer: Bool { if editingPerspectiveID != nil { return true } + // Android PerspectiveScreen 은 하단 입력창을 항상 둔다. 첫 의견을 올린 뒤에도 숨기지 않는다. return step == .some(.completed) && canParticipate - && hasPublishedPerspective == false && !hasSubmittedInCurrentSession } /// 공개되지 않은 내 의견(검수중·거절됨)이 목록에 없을 때 목록 맨 위에 보여 줄 행. diff --git a/Projects/Feature/Class/Sources/ClassBattleFlow/View/ClassBattleFlowView.swift b/Projects/Feature/Class/Sources/ClassBattleFlow/View/ClassBattleFlowView.swift index 90123f09..07729ab0 100644 --- a/Projects/Feature/Class/Sources/ClassBattleFlow/View/ClassBattleFlowView.swift +++ b/Projects/Feature/Class/Sources/ClassBattleFlow/View/ClassBattleFlowView.swift @@ -511,7 +511,7 @@ private extension ClassBattleFlowView { .pickeCard(bubbleBackground, border: bubbleBorder) .overlay(alignment: line.side == "B" ? .leading : .trailing) { if row.isActive && store.isPlaying { - AudioEqualizerView(isPlaying: true) + AudioEqualizerView() .frame(width: 24, height: 24) .offset(x: line.side == "B" ? -36 : 36) } diff --git a/Projects/Feature/Class/Sources/ClassEdit/Reducer/ClassEditFeature.swift b/Projects/Feature/Class/Sources/ClassEdit/Reducer/ClassEditFeature.swift new file mode 100644 index 00000000..0b1a95d4 --- /dev/null +++ b/Projects/Feature/Class/Sources/ClassEdit/Reducer/ClassEditFeature.swift @@ -0,0 +1,179 @@ +// +// ClassEditFeature.swift +// Class +// +// Created by Picke on 11/11/26. +// + +import ClassDomainInterface +import ComposableArchitecture +import Foundation +import PickeCoreUtility + +/// 운영자 클래스 수정 — Android `ClassEditScreen` 처럼 이름 변경과 마감일 연장을 한 화면에서 한다. +@Reducer +public struct ClassEditFeature { + public init() {} + + @ObservableState + public struct State: Equatable { + public var room: ClassRoom + public var instanceID = UUID() + public var name: String + public var deadline: Date + public var isNameInvalid = false + public var deadlineValidationMessage: String? + public var errorMessage: String? + public var isSaving = false + + public init(room: ClassRoom) { + self.room = room + name = room.name + deadline = room.deadline + } + + public var hasDeadline: Bool { + room.deadline != .distantFuture + } + + public var trimmedName: String { + name.trimmingCharacters(in: .whitespacesAndNewlines) + } + + public var isNameChanged: Bool { + trimmedName != room.name + } + + public var isDeadlineChanged: Bool { + deadline != room.deadline + } + + public var canSave: Bool { + room.role == .owner && !isSaving && (isNameChanged || isDeadlineChanged) + } + + public var deadlineText: String { + hasDeadline ? deadline.formatted(.fullKoreanDateTime) : "마감일 없음" + } + } + + public enum Action: ViewAction, BindableAction { + case binding(BindingAction) + case view(View) + case inner(InnerAction) + case delegate(DelegateAction) + } + + @CasePathable + public enum View: Equatable { + case backTapped + case deadlineFieldTapped + case saveTapped + } + + @CasePathable + public enum InnerAction: Equatable { + case saveResponse(Result) + } + + @CasePathable + public enum DelegateAction: Equatable { + case dismiss + case editDeadline(instanceID: UUID) + case saved(ClassRoom) + } + + public enum CancelID: Hashable, Sendable { + case save(UUID) + } + + @Dependency(\.classRoomUseCase) private var classUseCase + + public var body: some Reducer { + BindingReducer() + Reduce { state, action in + switch action { + case .binding(\.name): + state.isNameInvalid = false + state.errorMessage = nil + return .none + case .binding: + return .none + case let .view(viewAction): + return handleViewAction(state: &state, action: viewAction) + case let .inner(.saveResponse(result)): + state.isSaving = false + switch result { + case let .success(room): + state.room = room + return .send(.delegate(.saved(room))) + case .failure(.invalidDeadline), .failure(.deadlineExtensionOnly): + // Android 처럼 서버의 마감일 오류는 마감일 필드 아래 범위 안내로 보여준다. + state.deadlineValidationMessage = Self.deadlineRangeMessage + return .none + case let .failure(error): + state.errorMessage = error.message + return .none + } + case .delegate: + return .none + } + } + } +} + +private extension ClassEditFeature { + func handleViewAction( + state: inout State, + action: View + ) -> Effect { + switch action { + case .backTapped: + guard !state.isSaving else { return .none } + return .send(.delegate(.dismiss)) + case .deadlineFieldTapped: + guard !state.isSaving, state.hasDeadline else { return .none } + return .send(.delegate(.editDeadline(instanceID: state.instanceID))) + case .saveTapped: + guard state.canSave else { return .none } + state.isNameInvalid = state.trimmedName.isEmpty + state.deadlineValidationMessage = deadlineValidationMessage(state: state) + guard !state.isNameInvalid, state.deadlineValidationMessage == nil else { return .none } + state.isSaving = true + state.errorMessage = nil + let roomID = state.room.id + let name = state.isNameChanged ? state.trimmedName : nil + let deadline = state.isDeadlineChanged ? state.deadline : nil + return .run { [classUseCase] send in + let result = await Result { + var updated: ClassRoom? + if let name { + updated = try await classUseCase.updateName(id: roomID, name: name) + } + if let deadline { + updated = try await classUseCase.updateDeadline(id: roomID, deadline: deadline) + } + guard let updated else { throw ClassError.userMessage("변경할 내용이 없어요.") } + return updated + } + .mapError(ClassError.from) + await send(.inner(.saveResponse(result))) + } + .cancellable(id: CancelID.save(state.instanceID), cancelInFlight: true) + } + } + + /// Android `ClassEditViewModel.updateClass` — 마감일은 기존보다 뒤, 이용권 종료일 이전으로만 연장한다. + func deadlineValidationMessage(state: State) -> String? { + guard state.isDeadlineChanged else { return nil } + let isNotExtended = state.deadline <= state.room.deadline + // Android 는 날짜 단위로 비교한다. 이용권 종료일 당일은 시각과 상관없이 고를 수 있다. + let calendar = Calendar.current + let isAfterTicketEnd = state.room.ticketExpiresAt.map { + calendar.startOfDay(for: state.deadline) > calendar.startOfDay(for: $0) + } ?? false + return isNotExtended || isAfterTicketEnd ? Self.deadlineRangeMessage : nil + } + + static let deadlineRangeMessage = "기존 마감일 이후부터 이용권 종료일까지 선택할 수 있어요" +} diff --git a/Projects/Feature/Class/Sources/ClassEdit/View/ClassEditView.swift b/Projects/Feature/Class/Sources/ClassEdit/View/ClassEditView.swift new file mode 100644 index 00000000..4c120119 --- /dev/null +++ b/Projects/Feature/Class/Sources/ClassEdit/View/ClassEditView.swift @@ -0,0 +1,160 @@ +// +// ClassEditView.swift +// Class +// +// Created by Picke on 11/11/26. +// + +import ComposableArchitecture +import PickeCoreUtility +import PickeDesignKit +import SwiftUI + +/// Android `ClassEditScreen` — 클래스 명 + 참여 마감일 + 저장 버튼. +@ViewAction(for: ClassEditFeature.self) +public struct ClassEditView: View { + @Bindable public var store: StoreOf + @FocusState private var isNameFocused: Bool + + public init(store: StoreOf) { + self.store = store + } + + public var body: some View { + VStack(spacing: 0) { + navigationBar + formScroll + saveButton + .padding(.horizontal, 16) + .padding(.bottom, 16) + } + .screenBackground() + .toolbar(.hidden, for: .navigationBar) + } +} + +private extension ClassEditView { + var navigationBar: some View { + PickeNavigationBar( + onBack: { send(.backTapped) }, + centerTitle: "클래스 수정" + ) + .foregroundStyle(.gray500) + } + + var formScroll: some View { + ScrollView { + VStack(alignment: .leading, spacing: 32) { + Text("클래스 정보를 수정해 주세요") + .pretendardFont(.semiBold24) + .foregroundStyle(.gray800) + .frame(maxWidth: .infinity, alignment: .leading) + + nameSection() + deadlineSection() + battleSection() + + if let message = store.errorMessage { + Text(message) + .pretendardFont(.regular13) + .foregroundStyle(.red) + } + } + .padding(16) + } + .scrollIndicators(.hidden) + .scrollBounceBehavior(.basedOnSize) + } + + @ViewBuilder + func nameSection() -> some View { + VStack(alignment: .leading, spacing: 8) { + HStack(spacing: 4) { + sectionLabel("클래스 명") + Text("*") + .pretendardFont(.semiBold15) + .foregroundStyle(.primary500) + } + + TextField( + "", + text: $store.name, + prompt: Text("ex) 2학년 3반 1학기 토론") + .font( + .pretendardFontFamily( + family: .Medium, + size: 13 + ) + ) + .foregroundStyle(.gray300) + ) + .pickeTextField() + .focused($isNameFocused) + .disabled(store.isSaving) + .accessibilityIdentifier("class-edit-name") + + if store.isNameInvalid { + Text("공백만으로는 클래스를 만들 수 없어요") + .pretendardFont(.regular13) + .foregroundStyle(.red) + } + } + } + + @ViewBuilder + func deadlineSection() -> some View { + VStack(alignment: .leading, spacing: 8) { + sectionLabel("참여 마감일") + deadlineField + if let message = store.deadlineValidationMessage { + Text(message) + .pretendardFont(.regular13) + .foregroundStyle(.red) + } + } + } + + var deadlineField: some View { + Button { + isNameFocused = false + send(.deadlineFieldTapped) + } label: { + Text(store.deadlineText) + .pretendardFont(.labelMedium) + .foregroundStyle(store.hasDeadline ? .gray800 : .gray300) + .padding(.leading, 8) + .frame(maxWidth: .infinity, minHeight: 44, alignment: .leading) + .pickeCard(.beige50, border: .beige600) + } + .buttonStyle(.plain) + .disabled(!store.hasDeadline || store.isSaving) + .accessibilityIdentifier("class-edit-deadline") + } + + @ViewBuilder + func battleSection() -> some View { + VStack(alignment: .leading, spacing: 12) { + sectionLabel("선택한 배틀") + ClassSelectedBattleCard(battle: store.room.battle) + } + } + + func sectionLabel(_ title: String) -> some View { + Text(title) + .pretendardFont(.semiBold15) + .foregroundStyle(.gray800) + .frame(minHeight: 23, alignment: .leading) + } + + var saveButton: some View { + Button { + isNameFocused = false + send(.saveTapped) + } label: { + Text("클래스 수정하기") + } + .ctaButtonStyle(.primary, size: .large, height: 52) + .disabled(!store.canSave) + .accessibilityIdentifier("class-edit-save") + } +} diff --git a/Projects/Feature/Class/Sources/ClassMember/Reducer/ClassMemberFeature.swift b/Projects/Feature/Class/Sources/ClassMember/Reducer/ClassMemberFeature.swift index bf3c16c7..4b7cf8d1 100644 --- a/Projects/Feature/Class/Sources/ClassMember/Reducer/ClassMemberFeature.swift +++ b/Projects/Feature/Class/Sources/ClassMember/Reducer/ClassMemberFeature.swift @@ -27,7 +27,7 @@ public struct ClassMemberFeature { public let instanceID: UUID public var room: ClassRoom public var members: [ClassMember] - public var currentMemberID: Int + public var currentMemberID: Int? public var viewState: ViewState public var isLoading = false public var loadErrorMessage: String? @@ -46,7 +46,7 @@ public struct ClassMemberFeature { public init( room: ClassRoom, members: [ClassMember] = [], - currentMemberID: Int = 1, + currentMemberID: Int? = 1, instanceID: UUID? = nil, preloadedViewState: ViewState? = nil ) { @@ -108,7 +108,7 @@ public struct ClassMemberFeature { case editName(PresentationAction) case customAlert(PresentationAction) case loadingStarted(UUID) - case membersLoaded(room: ClassRoom, members: [ClassMember], currentMemberID: Int, requestID: UUID) + case membersLoaded(room: ClassRoom, members: [ClassMember], currentMemberID: Int?, requestID: UUID) case loadFailed(requestID: UUID, message: String) case dataUpdated(room: ClassRoom, members: [ClassMember]) case dataFailed(String) @@ -128,7 +128,7 @@ public struct ClassMemberFeature { public enum DelegateAction: Equatable { case dismiss case retryMembers(roomID: Int) - case removeMember(roomID: Int, memberID: Int, currentMemberID: Int) + case removeMember(roomID: Int, memberID: Int, currentMemberID: Int?) case updateDisplayName(roomID: Int, memberID: Int, currentMemberID: Int, name: String) } @@ -312,15 +312,16 @@ extension ClassMemberFeature { case .nameSaved: guard !state.isSaving, state.editName != nil, - state.members.contains(where: { $0.id == state.currentMemberID }) + let currentMemberID = state.currentMemberID, + state.members.contains(where: { $0.id == currentMemberID }) else { return .none } let name = state.draftName.trimmingCharacters(in: .whitespacesAndNewlines) guard !name.isEmpty else { return .none } state.isSaving = true return .send(.delegate(.updateDisplayName( roomID: state.room.id, - memberID: state.currentMemberID, - currentMemberID: state.currentMemberID, + memberID: currentMemberID, + currentMemberID: currentMemberID, name: name ))) case let .removeTapped(id): diff --git a/Projects/Feature/Class/Tests/Sources/ClassBattleFlowTests.swift b/Projects/Feature/Class/Tests/Sources/ClassBattleFlowTests.swift index a9205c62..43c8bd8d 100644 --- a/Projects/Feature/Class/Tests/Sources/ClassBattleFlowTests.swift +++ b/Projects/Feature/Class/Tests/Sources/ClassBattleFlowTests.swift @@ -563,7 +563,7 @@ struct ClassBattleFlowTests { } @Test - func 이미_제출한_의견은_빈_재조회_응답으로_다시_작성할_수_없다() async { + func 이미_제출한_의견이_있어도_빈_재조회_응답_뒤_입력창은_남는다() async { var state = battleState(room: .mocks[0]) state.session = session(step: .completed, commentRequired: false) state.viewState = .loaded @@ -575,7 +575,7 @@ struct ClassBattleFlowTests { await store.send(.inner(.myPerspectiveResponse(requestID, .success([])))) { $0.myPerspectiveRequestID = nil } - #expect(!store.state.shouldShowComposer) + #expect(store.state.shouldShowComposer) } @Test @@ -1269,7 +1269,7 @@ struct ClassBattleFlowTests { func 내_의견_수정은_입력창에_내용을_채우고_보내면_수정_후_다시_불러온다() async { var state = completedState(perspectives: [perspectiveItem(id: 5, isMine: true)]) state.hasPublishedPerspective = true - #expect(!state.shouldShowComposer) + #expect(state.shouldShowComposer) let store = TestStore(initialState: state) { ClassBattleFlowFeature() } withDependencies: { $0.uuid = .incrementing $0.audioPlayer = ClassBattleFlowAudioPlayer(spy: ClassBattleFlowSpy()) @@ -1314,7 +1314,7 @@ struct ClassBattleFlowTests { #expect(store.state.editingPerspectiveID == nil) #expect(store.state.draft.isEmpty) - #expect(!store.state.shouldShowComposer) + #expect(store.state.shouldShowComposer) } @Test @@ -1518,7 +1518,7 @@ struct ClassBattleFlowTests { await store.receive(\.inner, .myPerspectiveResponse(myPerspectiveRequestID, .success([]))) #expect(store.state.hasPublishedPerspective == true) - #expect(!store.state.shouldShowComposer) + #expect(store.state.shouldShowComposer) } @Test @@ -1600,7 +1600,7 @@ struct ClassBattleFlowTests { await store.receive(\.inner, .myPerspectiveResponse(myPerspectiveRequestID, .success([]))) #expect(store.state.hasPublishedPerspective == true) - #expect(!store.state.shouldShowComposer) + #expect(store.state.shouldShowComposer) } @Test diff --git a/Projects/Feature/Class/Tests/Sources/ClassEditTests.swift b/Projects/Feature/Class/Tests/Sources/ClassEditTests.swift new file mode 100644 index 00000000..2ba1b0f8 --- /dev/null +++ b/Projects/Feature/Class/Tests/Sources/ClassEditTests.swift @@ -0,0 +1,202 @@ +// +// ClassEditTests.swift +// ClassTests +// +// Created by Picke on 11/11/26. +// + +@testable import Class +import ClassDomainInterface +import ComposableArchitecture +import Foundation +import Testing + +@MainActor +struct ClassEditTests { + private let referenceNow = Date(timeIntervalSince1970: 1_900_000_000) + + @Test + func 이름이나_마감일을_바꿔야_운영자가_저장할_수_있다() { + var owner = ClassEditFeature.State(room: makeRoom()) + var member = ClassEditFeature.State(room: makeRoom(role: .member)) + #expect(!owner.canSave) + + owner.name = " 새 클래스 이름 " + member.name = "새 클래스 이름" + #expect(owner.trimmedName == "새 클래스 이름") + #expect(owner.canSave) + #expect(!member.canSave) + } + + @Test + func 이름만_바꾸면_이름_변경만_요청하고_저장_결과를_전달한다() async { + let room = makeRoom() + let renamed = makeRoom(name: "새 클래스 이름") + let calls = LockIsolated<[String]>([]) + var state = ClassEditFeature.State(room: room) + state.name = "새 클래스 이름" + let store = TestStore(initialState: state) { ClassEditFeature() } withDependencies: { + $0.classRoomUseCase = ClassEditRoomStub( + onUpdateName: { name in calls.withValue { $0.append("name:\(name)") }; return renamed }, + onUpdateDeadline: { _ in calls.withValue { $0.append("deadline") }; return room } + ) + } + + await store.send(.view(.saveTapped)) { + $0.isSaving = true + } + await store.receive(\.inner, .saveResponse(.success(renamed))) { + $0.isSaving = false + $0.room = renamed + } + await store.receive(\.delegate, .saved(renamed)) + #expect(calls.value == ["name:새 클래스 이름"]) + } + + @Test + func 빈_이름은_저장하지_않고_오류를_보여준다() async { + var state = ClassEditFeature.State(room: makeRoom()) + state.name = " " + let store = TestStore(initialState: state) { ClassEditFeature() } + + await store.send(.view(.saveTapped)) { + $0.isNameInvalid = true + } + } + + @Test + func 기존_마감일보다_앞당기면_저장하지_않는다() async { + let room = makeRoom() + var state = ClassEditFeature.State(room: room) + state.deadline = room.deadline.addingTimeInterval(-3600) + let store = TestStore(initialState: state) { ClassEditFeature() } + + await store.send(.view(.saveTapped)) { + $0.deadlineValidationMessage = "기존 마감일 이후부터 이용권 종료일까지 선택할 수 있어요" + } + } + + @Test + func 마감일_필드는_마감일이_있는_클래스만_선택을_요청한다() async { + let withDeadline = ClassEditFeature.State(room: makeRoom()) + let store = TestStore(initialState: withDeadline) { ClassEditFeature() } + await store.send(.view(.deadlineFieldTapped)) + await store.receive(\.delegate, .editDeadline(instanceID: withDeadline.instanceID)) + + let noDeadline = TestStore( + initialState: ClassEditFeature.State(room: makeRoom(deadline: .distantFuture)) + ) { ClassEditFeature() } + await noDeadline.send(.view(.deadlineFieldTapped)) + } + + @Test + func 서버_마감일_오류는_마감일_범위_안내로_보여준다() async { + let room = makeRoom() + var state = ClassEditFeature.State(room: room) + state.deadline = room.deadline.addingTimeInterval(3600) + let store = TestStore(initialState: state) { ClassEditFeature() } withDependencies: { + $0.classRoomUseCase = ClassEditRoomStub( + onUpdateName: { _ in room }, + onUpdateDeadline: { _ in throw ClassError.deadlineExtensionOnly } + ) + } + + await store.send(.view(.saveTapped)) { + $0.isSaving = true + } + await store.receive(\.inner, .saveResponse(.failure(.deadlineExtensionOnly))) { + $0.isSaving = false + $0.deadlineValidationMessage = "기존 마감일 이후부터 이용권 종료일까지 선택할 수 있어요" + } + } + + @Test + func 이용권_종료일_당일은_시각과_상관없이_고를_수_있다() async { + let ticketEnd = Calendar.current.startOfDay(for: referenceNow.addingTimeInterval(86400 * 3)) + let room = makeRoom(ticketExpiresAt: ticketEnd) + var sameDay = ClassEditFeature.State(room: room) + sameDay.deadline = ticketEnd.addingTimeInterval(3600 * 20) + let store = TestStore(initialState: sameDay) { ClassEditFeature() } withDependencies: { + $0.classRoomUseCase = ClassEditRoomStub( + onUpdateName: { _ in room }, + onUpdateDeadline: { _ in room } + ) + } + await store.send(.view(.saveTapped)) { + $0.isSaving = true + } + await store.receive(\.inner, .saveResponse(.success(room))) { + $0.isSaving = false + } + await store.receive(\.delegate, .saved(room)) + + var nextDay = ClassEditFeature.State(room: room) + nextDay.deadline = ticketEnd.addingTimeInterval(86400 + 60) + let rejected = TestStore(initialState: nextDay) { ClassEditFeature() } + await rejected.send(.view(.saveTapped)) { + $0.deadlineValidationMessage = "기존 마감일 이후부터 이용권 종료일까지 선택할 수 있어요" + } + } + + private func makeRoom( + name: String? = nil, + deadline: Date? = nil, + role: ClassRole = .owner, + ticketExpiresAt: Date? = nil + ) -> ClassRoom { + let source = ClassRoom.mocks[0] + return ClassRoom( + id: source.id, + name: name ?? source.name, + joinCode: source.joinCode, + battle: source.battle, + deadline: deadline ?? referenceNow.addingTimeInterval(86400), + memberCount: source.memberCount, + role: role, + status: source.status, + allowsAnonymousOpinion: source.allowsAnonymousOpinion, + requiresComment: source.requiresComment, + ownerParticipates: source.ownerParticipates, + memberCapacity: source.memberCapacity, + ticketExpiresAt: ticketExpiresAt + ) + } +} + +private struct ClassEditRoomStub: ClassRoomInterface { + let onUpdateName: @Sendable (String) async throws -> ClassRoom + let onUpdateDeadline: @Sendable (Date) async throws -> ClassRoom + + func updateName(id _: Int, name: String) async throws -> ClassRoom { + try await onUpdateName(name) + } + + func updateDeadline(id _: Int, deadline: Date) async throws -> ClassRoom { + try await onUpdateDeadline(deadline) + } + + func fetchMyClasses() async throws -> [ClassRoom] { + [] + } + + func createClass(_: ClassCreation) async throws -> ClassRoom { + throw ClassError.userMessage("unused") + } + + func fetchClass(id _: Int) async throws -> ClassRoom { + throw ClassError.userMessage("unused") + } + + func fetchClass(joinCode _: String) async throws -> ClassRoom { + throw ClassError.userMessage("unused") + } + + func joinClass(joinCode _: String, + nickname _: String) async throws -> ClassRoom + { + throw ClassError.userMessage("unused") + } + + func deleteClass(id _: Int) async throws {} + func leaveClass(id _: Int) async throws {} +} diff --git a/Projects/Feature/Hifi/Sources/Reducer/HifiFeature.swift b/Projects/Feature/Hifi/Sources/Reducer/HifiFeature.swift index a8c6255c..fcea1268 100644 --- a/Projects/Feature/Hifi/Sources/Reducer/HifiFeature.swift +++ b/Projects/Feature/Hifi/Sources/Reducer/HifiFeature.swift @@ -50,6 +50,10 @@ public struct HifiFeature { /// 종 아이콘 빨간점 — 미읽음 알림 존재 여부. 화면 진입마다 /unread 서버값으로 갱신(저장 안 함). public var hasUnreadNotification: Bool = false + /// Android 불러오기 실패 토스트 문구. 보여준 뒤 `toastShown` 으로 비운다. + public var toastMessage: String? + /// Android `scrollToTopTrigger` — 탐색 탭을 다시 누르면 1 늘려 목록을 맨 위로 올린다. + public var scrollToTopRequest: Int = 0 public init() {} } @@ -70,6 +74,8 @@ public struct HifiFeature { case itemTapped(id: Int) case reachedBottom case notificationTapped + case toastShown + case exploreTabReselected /// 탐색 화면 배너 광고 클릭 case adBannerClicked case serverAdClicked(network: String) @@ -157,6 +163,14 @@ extension HifiFeature { case let .itemTapped(id): return .send(.delegate(.openBattle(battleId: id))) + case .toastShown: + state.toastMessage = nil + return .none + + case .exploreTabReselected: + state.scrollToTopRequest += 1 + return .none + case .notificationTapped: return .send(.delegate(.openNotification)) @@ -278,6 +292,8 @@ extension HifiFeature { state.loadedCategory = category state.loadedSort = sort case let .failure(error): + // Android: 처음·추가 불러오기 모두 실패하면 토스트를 띄운다. + state.toastMessage = "정보를 불러오지 못했어요" PickeLogger.error("[HifiFeature] searchBattles failed: \(error.localizedDescription)", category: .ui) } return .none diff --git a/Projects/Feature/Hifi/Sources/View/Components/HifiHeaderView.swift b/Projects/Feature/Hifi/Sources/View/Components/HifiHeaderView.swift index 6f01568d..b0c63e09 100644 --- a/Projects/Feature/Hifi/Sources/View/Components/HifiHeaderView.swift +++ b/Projects/Feature/Hifi/Sources/View/Components/HifiHeaderView.swift @@ -9,44 +9,21 @@ import SwiftUI import PickeDesignKit -/// 홈 화면 최상단 GNB 위 헤더 (PicKé 로고 + 알림 아이콘). +/// Android `PickeTopAppBar(showLogo = true)` — 높이 48, 로고 63×40 `gray900`, 배경 `backgroundBeige`. +/// Android 는 알림 버튼을 숨겨 두었으므로 로고만 둔다. struct HifiHeaderView: View { - let hasUnread: Bool - let onNotificationTapped: () -> Void - var body: some View { - HStack { + HStack(spacing: 0) { Image(asset: .appLogo) + .renderingMode(.template) .resizable() .scaledToFit() - .frame(width: 62, height: 39) - - Spacer() - - Button(action: onNotificationTapped) { - bellIcon() - } - } - .padding(.horizontal, 24) - .padding(.vertical, 8) - .frame(height: 56) - .background(.beige50) - } -} - -private extension HifiHeaderView { - @ViewBuilder - func bellIcon() -> some View { - if hasUnread { - Image(asset: .bell) - .resizable() - .scaledToFit() - .frame(width: 24, height: 24) - } else { - Image(systemName: "bell") - .font(.system(size: 20, weight: .regular)) - .foregroundStyle(.neutral900) - .frame(width: 24, height: 24) + .foregroundStyle(.gray900) + .frame(width: 63, height: 40) + Spacer(minLength: 0) } + .padding(.horizontal, 16) + .frame(height: 48) + .background(.bgBeige) } } diff --git a/Projects/Feature/Hifi/Sources/View/HifiView.swift b/Projects/Feature/Hifi/Sources/View/HifiView.swift index f0f26490..5dfb8d80 100644 --- a/Projects/Feature/Hifi/Sources/View/HifiView.swift +++ b/Projects/Feature/Hifi/Sources/View/HifiView.swift @@ -28,10 +28,15 @@ public struct HifiView: View { fixedTopBar() contentArea() } - .screenBackground(.beige50) + .screenBackground(.bgBeige) .navigationBarHidden(true) .toolbar(.hidden, for: .navigationBar) .onAppear { send(.onAppear) } + .onChange(of: store.toastMessage, initial: true) { _, message in + guard let message else { return } + ToastManager.shared.showError(message) + send(.toastShown) + } } } @@ -41,11 +46,11 @@ private extension HifiView { @ViewBuilder func fixedTopBar() -> some View { VStack(spacing: 0) { - HifiHeaderView(hasUnread: store.hasUnreadNotification) { send(.notificationTapped) } + HifiHeaderView() categoryTabs() sortRow() } - .background(.beige50) + .background(.bgBeige) .frame(maxWidth: .infinity) .zIndex(1) // 스크롤 중 상단 바가 슬라이드·어긋나 보이던 13 mini/iOS 18.6 잔상 제거. @@ -66,6 +71,8 @@ private extension HifiView { } } .frame(maxWidth: .infinity, maxHeight: .infinity) + // Android: 정렬 줄과 목록은 흰 바탕 위에 카드를 올린다. + .background(.white) .clipped() .contentShape(Rectangle()) .simultaneousGesture(categorySwipe) @@ -78,17 +85,8 @@ private extension HifiView { @ViewBuilder func emptyState() -> some View { - VStack(spacing: 8) { - Image(asset: .noDataLogo) - .resizable() - .scaledToFit() - .frame(width: 135, height: 90) - - Text("새로운 콘텐츠가 없습니다") - .pretendardFont(.bodyMedium) - .foregroundStyle(.beige800) - } - .frame(maxWidth: .infinity, maxHeight: .infinity) + PickeEmptyStateView(message: "아직 준비된 배틀이 없어요!") + .frame(maxWidth: .infinity, maxHeight: .infinity) } } @@ -107,40 +105,52 @@ private extension HifiView { @ViewBuilder func exploreList() -> some View { GeometryReader { viewport in - ScrollView { - LazyVStack(spacing: 0) { - ForEach(store.exploreItems) { item in - // 마지막 카드 아래엔 구분선을 그리지 않는다. - exploreRow(item, showsDivider: item.id != store.exploreItems.last?.id) - .onAppear { - // 무한 스크롤: 마지막 아이템 노출 시 다음 페이지 로드 - if item.id == store.exploreItems.last?.id { - send(.reachedBottom) + ScrollViewReader { proxy in + ScrollView { + LazyVStack(spacing: 0) { + Color.clear + .frame(height: 0) + .id(Self.topAnchorID) + ForEach(store.exploreItems) { item in + // Android: 카드 위마다 구분선, 마지막 카드 아래에도 한 줄. + exploreRow(item, isLast: item.id == store.exploreItems.last?.id) + .onAppear { + // 무한 스크롤: 마지막 아이템 노출 시 다음 페이지 로드 + if item.id == store.exploreItems.last?.id { + send(.reachedBottom) + } } - } - if let ad = store.withState({ state in - state.exploreItems.firstIndex(where: { $0.id == item.id }) - .flatMap { state.ad(after: $0) } - }) { - FeedAdRow( - ad: ad, - viewport: viewport.frame(in: .global), - onVisible: { send(.adVisible(code: ad.code, itemID: item.id)) }, - onAdClick: { send(.serverAdClicked(network: ad.network)) } - ) - .id(ad.code) + if let ad = store.withState({ state in + state.exploreItems.firstIndex(where: { $0.id == item.id }) + .flatMap { state.ad(after: $0) } + }) { + FeedAdRow( + ad: ad, + viewport: viewport.frame(in: .global), + onVisible: { send(.adVisible(code: ad.code, itemID: item.id)) }, + onAdClick: { send(.serverAdClicked(network: ad.network)) } + ) + .id(ad.code) + } } } + // 마지막 카드가 하단에 딱 붙지 않도록 10pt 여백. + .padding(.bottom, 10) + } + .scrollIndicators(.hidden) + .scrollBounceBehavior(.basedOnSize, axes: .vertical) + .onChange(of: store.scrollToTopRequest) { + withAnimation { + proxy.scrollTo(Self.topAnchorID, anchor: .top) + } } - // 마지막 카드가 하단에 딱 붙지 않도록 10pt 여백. - .padding(.bottom, 10) } - .scrollIndicators(.hidden) - .scrollBounceBehavior(.basedOnSize, axes: .vertical) } } + static let topAnchorID = "exploreTop" + /// 좌우 스와이프로 카테고리 전환 (빈 상태/스켈레톤 포함 콘텐츠 영역 전체에 적용). /// 인접 카테고리 계산은 Feature 가 담당. var categorySwipe: some Gesture { @@ -168,8 +178,7 @@ private extension HifiView { .frame(maxWidth: .infinity) } } - .padding(.horizontal, 16) - .background(.white) + // Android `PickeTabBar` — 화면 전체 폭, 배경 투명. .transaction { transaction in transaction.animation = nil } @@ -213,53 +222,62 @@ private extension HifiView { // MARK: - List Row private extension HifiView { + /// Android `ExploreCard` — 가로 16·세로 14, 썸네일과 간격 12, 제목 → 6 → 요약, 아래에 시간·조회수. @ViewBuilder - func exploreRow(_ item: ExploreItem, showsDivider: Bool = true) -> some View { + func exploreRow( + _ item: ExploreItem, + isLast: Bool + ) -> some View { Button { send(.itemTapped(id: item.id)) } label: { - HStack(alignment: .center, spacing: 8) { + HStack(alignment: .top, spacing: 12) { thumbnail(item.imageURL) - - VStack(alignment: .leading, spacing: 24) { - VStack(alignment: .leading, spacing: 8) { - HStack(alignment: .top, spacing: 6) { - Text("#\(item.category)") - .pickeBadge(.filled, size: .tag) - - Text(item.title) - .pretendardFont(.headingSmall) - .foregroundStyle(.neutral500) - .kerning(-0.35) - .lineSpacing(14 * 0.28) - .lineLimit(1) - .truncationMode(.tail) - .frame(maxWidth: .infinity, alignment: .leading) - } - - Text(item.summary) - .pretendardFont(.regular13) - .foregroundStyle(.neutral400) - .lineSpacing(13 * 0.4) - .lineLimit(2) - .truncationMode(.tail) - .frame(maxWidth: .infinity, alignment: .leading) - .padding(.horizontal, 2) - } - - footer(item) - } + rowText(item) + .frame(height: Self.thumbnailHeight) } .padding(.horizontal, 16) - .padding(.vertical, 12) - .background(.beige50) + .padding(.vertical, 14) + .frame(maxWidth: .infinity, alignment: .leading) + .background(.surfaceBeigeDefault) + .overlay(alignment: .top) { + PickeDivider(.borderBeigeDefault) + } .overlay(alignment: .bottom) { - if showsDivider { - PickeDivider(.beige600) + if isLast { + PickeDivider(.borderBeigeDefault) } } + .contentShape(Rectangle()) } .buttonStyle(.plain) } + @ViewBuilder + func rowText(_ item: ExploreItem) -> some View { + VStack(alignment: .leading, spacing: 0) { + HStack(alignment: .top, spacing: 6) { + Text("#\(item.category)") + .pickeBadge(.filled, size: .tag) + Text(item.title) + .pretendardFont(.headingSmall) + .foregroundStyle(.textSubtler) + .lineLimit(1) + .truncationMode(.tail) + .frame(maxWidth: .infinity, alignment: .leading) + } + Text(item.summary) + .pretendardFont(.regular13, lineSpacingMultiple: 1.4) + .foregroundStyle(.gray400) + .lineLimit(2) + .truncationMode(.tail) + .frame(maxWidth: .infinity, alignment: .leading) + .padding(.top, 6) + Spacer(minLength: 0) + footer(item) + } + } + + static let thumbnailHeight: CGFloat = 80 * 4 / 3 + @ViewBuilder func thumbnail(_ url: String?) -> some View { Group { @@ -270,29 +288,35 @@ private extension HifiView { } } // 행 높이와 무관하게 크기 고정 — 안드로이드 ExploreScreen (80dp, 3:4 비율) 파리티. - .frame(width: 80, height: 80 * 4 / 3) + .frame(width: 80, height: Self.thumbnailHeight) .clipShape(RoundedRectangle(cornerRadius: .radiusDefault)) } + /// Android 푸터 — 아이콘 16 `textMuted`, 4, 12 Medium `gray400`, 항목 간 12, 오른쪽 정렬. @ViewBuilder func footer(_ item: ExploreItem) -> some View { - HStack(spacing: 6) { - Spacer() - HStack(spacing: 2) { - Image(systemName: "clock") - .font(.system(size: 11, weight: .regular)) - Text("\(item.minutes)분") - .pretendardFont(.labelSmall) - } - .foregroundStyle(.neutral300) + HStack(spacing: 12) { + Spacer(minLength: 0) + footerItem(.clock, text: "\(item.minutes)분") + footerItem(.eye, text: item.viewCount.decimalFormatted) + } + } - HStack(spacing: 2) { - Image(systemName: "eye") - .font(.system(size: 11, weight: .regular)) - Text(item.viewCount.decimalFormatted) - .pretendardFont(.labelSmall) - } - .foregroundStyle(.neutral300) + @ViewBuilder + func footerItem( + _ icon: ImageAsset, + text: String + ) -> some View { + HStack(spacing: 4) { + Image(asset: icon) + .renderingMode(.template) + .resizable() + .scaledToFit() + .foregroundStyle(.textMuted) + .frame(width: 16, height: 16) + Text(text) + .pretendardFont(.labelSmall) + .foregroundStyle(.gray400) } } } diff --git a/Projects/Feature/Hifi/Tests/Sources/HifiTests.swift b/Projects/Feature/Hifi/Tests/Sources/HifiTests.swift index f186a9b1..1d9218c0 100644 --- a/Projects/Feature/Hifi/Tests/Sources/HifiTests.swift +++ b/Projects/Feature/Hifi/Tests/Sources/HifiTests.swift @@ -5,6 +5,7 @@ // Created by Picke on 10/11/26. // +import Foundation import Testing import ComposableArchitecture import AdDomainInterface @@ -62,17 +63,48 @@ struct HifiTests { await store.send(.view(.adVisible(code: "first", itemID: 6))) { $0.reportedAdCodesByItemID = [6: ["first"]] } - await store.receive(\.inner.impressionResponse) + await store.receive { action in + guard case .inner(.impressionResponse) = action else { return false } + return true + } await store.send(.view(.adVisible(code: "first", itemID: 6))) await store.send(.view(.adVisible(code: "first", itemID: 12))) { $0.reportedAdCodesByItemID[12] = ["first"] } - await store.receive(\.inner.impressionResponse) + await store.receive { action in + guard case .inner(.impressionResponse) = action else { return false } + return true + } let codes = await client.codes #expect(codes == ["first", "first"]) await store.finish() } + @Test @MainActor + func searchFailureShowsToast() async { + var state = HifiFeature.State() + state.viewState = .loading + let store = TestStore(initialState: state) { HifiFeature() } + store.exhaustivity = .off + + await store.send(.inner(.searchResponse( + .failure(.noData), + reset: true, + category: state.selectedCategory, + sort: state.selectedSort + ))) + #expect(store.state.toastMessage == "정보를 불러오지 못했어요") + } + + @Test @MainActor + func reselectingTabRequestsScrollToTop() async { + let store = TestStore(initialState: HifiFeature.State()) { HifiFeature() } + + await store.send(.view(.exploreTabReselected)) { + $0.scrollToTopRequest = 1 + } + } + private func ad(_ code: String) -> FeedAd { FeedAd( code: code, diff --git a/Projects/Feature/Home/Project.swift b/Projects/Feature/Home/Project.swift index 67e6d2cd..1a6ba4a3 100644 --- a/Projects/Feature/Home/Project.swift +++ b/Projects/Feature/Home/Project.swift @@ -20,6 +20,7 @@ let project = Project.makeModule( settings: .settings(), dependencies: [ .core(.logger), + .core(.coreUtility), .SPM.composableArchitecture, .domain(.auth, .interface), .ui(.designKit), diff --git a/Projects/Feature/Home/Sources/Main/Model/AttendanceDayRecord.swift b/Projects/Feature/Home/Sources/Main/Model/AttendanceDayRecord.swift new file mode 100644 index 00000000..3414ad7a --- /dev/null +++ b/Projects/Feature/Home/Sources/Main/Model/AttendanceDayRecord.swift @@ -0,0 +1,36 @@ +// +// AttendanceDayRecord.swift +// Home +// +// Created by Picke on 11/11/26. +// + +import Foundation + +/// Android `LocalPreferences` 의 마지막 출석 체크일·시트 노출일. 날짜는 `Date.formatted(.yearMonthDay)` (한국 시간 `yyyy-MM-dd`). +public struct AttendanceDayRecord { + static let checkedKey = "picke.attendance.lastCheckedDate" + static let sheetShownKey = "picke.attendance.lastSheetShownDate" + + private let defaults: UserDefaults + + public init(defaults: UserDefaults = .standard) { + self.defaults = defaults + } + + public func isChecked(on day: String) -> Bool { + defaults.string(forKey: Self.checkedKey) == day + } + + public func markChecked(on day: String) { + defaults.set(day, forKey: Self.checkedKey) + } + + public func isSheetShown(on day: String) -> Bool { + defaults.string(forKey: Self.sheetShownKey) == day + } + + public func markSheetShown(on day: String) { + defaults.set(day, forKey: Self.sheetShownKey) + } +} diff --git a/Projects/Feature/Home/Sources/Main/Reducer/HomeFeature.swift b/Projects/Feature/Home/Sources/Main/Reducer/HomeFeature.swift index ccf51011..8029ed20 100644 --- a/Projects/Feature/Home/Sources/Main/Reducer/HomeFeature.swift +++ b/Projects/Feature/Home/Sources/Main/Reducer/HomeFeature.swift @@ -14,6 +14,7 @@ import HomeInterface import NotificationDomainInterface import PickeAnalyticsInterface import PickeCoreLogger +import PickeCoreUtility @Reducer public struct HomeFeature { @@ -108,6 +109,8 @@ public struct HomeFeature { case homeTabReselected /// 실패 토스트를 띄운 뒤 메시지를 비운다. case toastShown + /// 앱이 다시 활성화됨 — Android `AppLifecycleObserver.onStart` 처럼 오늘 출석이 안 됐으면 체크한다. + case appBecameActive } @CasePathable @@ -117,28 +120,34 @@ public struct HomeFeature { case refreshHome /// 벨 배지용 미읽음 여부 서버 동기화 (GET /api/v1/notifications/unread). case syncUnreadBadge - /// 오늘의 출석 체크 (POST /attendance/check) — 성공 시 주간 현황까지 이어 조회한다. - case checkAttendance + /// 출석 체크 후 주간 현황을 조회해 시트를 띄운다(Android `checkInAndShowAttendanceSheetIfNeeded`). + case checkAttendance(day: String) + /// 시트 없이 출석 체크만 한다(Android `checkAttendanceIfNeeded`). + case checkAttendanceOnly(day: String) } @CasePathable public enum InnerAction: Equatable { case homeResponse(Result) case unreadBadgeResponse(Result) - /// 출석 체크 성공 + 주간 현황 조회까지 끝난 결과. - case attendanceResponse(weekly: WeeklyAttendance, pointsEarned: Int) + /// 주간 현황 조회까지 끝난 결과(체크 성공 여부와 관계없이 시트를 띄운다). + case attendanceResponse(day: String, weekly: WeeklyAttendance, pointsEarned: Int) + /// 출석 체크 성공 — 오늘 날짜를 기록해 하루 1회만 부른다. + case attendanceChecked(day: String) } nonisolated enum CancelID: Hashable { case fetchHome case syncUnreadBadge case attendance + case attendanceCheckOnly } @Dependency(\.homeUseCase) private var homeUseCase @Dependency(\.notificationUseCase) private var notificationUseCase @Dependency(\.attendanceUseCase) private var attendanceUseCase @Dependency(\.analyticsUseCase) private var analyticsUseCase + @Dependency(\.date.now) private var now public var body: some Reducer { BindingReducer() @@ -165,12 +174,6 @@ public struct HomeFeature { } extension HomeFeature { - /// staging 빌드 여부. 출석 시트를 테스트로 상시 노출할지 가르는 게이트. - /// 값은 xcconfig → Info.plist(SENTRY_ENVIRONMENT) 로 주입된다(Stage=staging, Prod=production). - static var isStagingEnvironment: Bool { - (Bundle.main.object(forInfoDictionaryKey: "SENTRY_ENVIRONMENT") as? String) == "staging" - } - private func handleViewAction( state: inout State, action: View @@ -180,11 +183,8 @@ extension HomeFeature { analyticsUseCase.track(.screenView(screen: .home, referrer: nil)) // 벨 배지는 진입/재진입마다 서버(/unread)로 갱신 — fetchHome 이 스킵돼도 stale 방지. let syncBadge: Effect = .send(.async(.syncUnreadBadge)) - // 출석 체크는 세션당 1회 — 하루 1회 제한이라 재진입마다 호출할 이유가 없다. - let attendance: Effect = state.hasTriedAttendance - ? .none - : .send(.async(.checkAttendance)) - state.hasTriedAttendance = true + // Android: 출석 시트는 홈 진입 시 하루 1회(세션당 한 번 시도), 체크만은 하루 1회. + let attendance = attendanceEffectOnAppear(state: &state) // 홈 조회는 첫 진입 한 번만(Android ViewModel init) — 실패·로딩 중·로드 완료면 다시 부르지 않고 새로고침으로만 다시 부른다. // 초기값 `.loaded` + 미로드 = 한 번도 요청하지 않은 상태. guard !state.hasLoadedHome, state.viewState == .loaded else { @@ -192,6 +192,11 @@ extension HomeFeature { } return .merge(syncBadge, attendance, .send(.async(.fetchHome))) + case .appBecameActive: + let today = now.formatted(.yearMonthDay) + guard !AttendanceDayRecord().isChecked(on: today) else { return .none } + return .send(.async(.checkAttendanceOnly(day: today))) + case .pullToRefresh: guard state.viewState != .loading else { return .none } return .send(.async(.refreshHome)) @@ -272,19 +277,28 @@ extension HomeFeature { } .cancellable(id: CancelID.syncUnreadBadge, cancelInFlight: true) - case .checkAttendance: + case let .checkAttendance(day): return .run { [useCase = attendanceUseCase] send in let result = try? await useCase.checkAttendance() - // 정책: Prod 는 오늘 첫 출석 성공(result != nil) 때만 노출. - // staging 은 테스트 목적으로 이미 출석(409)이어도 결과와 무관하게 상시 노출한다. - guard Self.isStagingEnvironment || result != nil else { return } + if result != nil { + await send(.inner(.attendanceChecked(day: day))) + } + // Android: 체크 결과(이미 출석·실패)와 관계없이 주간 조회가 성공하면 시트를 띄운다. guard let weekly = try? await useCase.fetchWeeklyAttendance() else { return } await send(.inner(.attendanceResponse( + day: day, weekly: weekly, pointsEarned: (result?.pointsEarned ?? 0) + (result?.streakBonusPoints ?? 0) ))) } .cancellable(id: CancelID.attendance, cancelInFlight: true) + + case let .checkAttendanceOnly(day): + return .run { [useCase = attendanceUseCase] send in + guard (try? await useCase.checkAttendance()) != nil else { return } + await send(.inner(.attendanceChecked(day: day))) + } + .cancellable(id: CancelID.attendanceCheckOnly, cancelInFlight: true) } } @@ -333,7 +347,12 @@ extension HomeFeature { } return .none - case let .attendanceResponse(weekly, pointsEarned): + case let .attendanceChecked(day): + AttendanceDayRecord().markChecked(on: day) + return .none + + case let .attendanceResponse(day, weekly, pointsEarned): + AttendanceDayRecord().markSheetShown(on: day) var modalState = AttendanceModalFeature.State() modalState.weekly = weekly modalState.pointsEarned = pointsEarned @@ -342,6 +361,21 @@ extension HomeFeature { } } + /// 홈 진입 시 출석 처리 — 오늘 시트를 아직 안 보였으면 체크+시트, 보였는데 체크가 안 됐으면 체크만. + private func attendanceEffectOnAppear(state: inout State) -> Effect { + guard !state.hasTriedAttendance else { return .none } + state.hasTriedAttendance = true + let today = now.formatted(.yearMonthDay) + let record = AttendanceDayRecord() + if !record.isSheetShown(on: today) { + return .send(.async(.checkAttendance(day: today))) + } + if !record.isChecked(on: today) { + return .send(.async(.checkAttendanceOnly(day: today))) + } + return .none + } + private func handleAttendanceModal( state: inout State, action: PresentationAction diff --git a/Projects/Feature/Home/Sources/Main/View/Components/HomeBestCommentRow.swift b/Projects/Feature/Home/Sources/Main/View/Components/HomeBestCommentRow.swift index 14d58fc4..6c58522b 100644 --- a/Projects/Feature/Home/Sources/Main/View/Components/HomeBestCommentRow.swift +++ b/Projects/Feature/Home/Sources/Main/View/Components/HomeBestCommentRow.swift @@ -6,14 +6,10 @@ import HomeDomainInterface import PickeDesignKit import SwiftUI -import UIKit -/// Best 댓글 행 — Android `HomeBestCommentItem` 시안. -/// 본문 첫 줄 앞에 배지 폭만큼 투명 자리를 두고, 선택지 배지는 첫 줄 기준선에 overlay 로 겹친다. -/// Android 처럼 배지가 글꼴보다 위·아래로 튀어나온 만큼만 본문 위·아래를 늘리고 줄 간격(13 × 1.4)은 그대로 둔다. +/// Best 댓글 행 — Android `HomeBestCommentItem` 시안 (배틀 제목 1줄 + 답글 아이콘 + 본문 2줄). struct HomeBestCommentRow: View { let comment: HomeBestComment - @Environment(\.displayScale) private var displayScale var body: some View { VStack(alignment: .leading, spacing: 8) { @@ -29,22 +25,18 @@ struct HomeBestCommentRow: View { } extension HomeBestCommentRow { - /// 본문 글꼴(Android bodyXsRegular) — 배지 위치 계산과 한 곳에서 맞춘다. - private static let contentFont: CustomSizeFont = .regular13 + /// Android bodyXsRegular + lineHeight 20.2sp (13 × 1.4 기준 줄 간격). private static let contentLineHeightMultiple: CGFloat = 1.4 private var accessibilityText: String { - let commentText = [comment.optionTitle, comment.content] - .filter { !$0.isEmpty } - .joined(separator: " ") - return [comment.battleTitle, commentText] + [comment.battleTitle, comment.content] .filter { !$0.isEmpty } .joined(separator: ", ") } private var battleTitleText: some View { Text(comment.battleTitle) - .pretendardFont(.semiBold13) + .pretendardFont(.regular13) .foregroundStyle(.textMuted) .lineLimit(1) .truncationMode(.tail) @@ -52,138 +44,18 @@ extension HomeBestCommentRow { @ViewBuilder private func contentSection() -> some View { - let badge = OptionBadgeImage.make( - title: comment.optionTitle, - scale: displayScale - ) HStack(alignment: .top, spacing: 0) { Image(asset: .replyCorner) .resizable() .frame(width: 16, height: 16) .foregroundStyle(.primary500) - contentText(badge: badge) - .pretendardFont(Self.contentFont, lineSpacingMultiple: Self.contentLineHeightMultiple) + Text(verbatim: comment.content) + .pretendardFont(.regular13, lineSpacingMultiple: Self.contentLineHeightMultiple) .foregroundStyle(.textSubtler) .lineLimit(2) .truncationMode(.tail) - // 배지를 Text 안에 넣으면 SwiftUI 가 줄 위쪽을 배지 높이만큼 잡는다 → 본문엔 투명 자리만 두고 배지는 첫 줄 기준선에 겹친다. - .overlay(alignment: Alignment(horizontal: .leading, vertical: .firstTextBaseline)) { - if let badge { - Image(uiImage: badge) - .renderingMode(.original) - .alignmentGuide(.firstTextBaseline) { [descent = badgeDescent(badge)] dimension in - dimension.height - descent - } - } - } - .padding(.top, badge.map(badgeTopOverflow) ?? 0) - .padding(.bottom, badge.map(badgeBottomOverflow) ?? 0) .padding(.horizontal, 2) .frame(maxWidth: .infinity, alignment: .leading) } } - - private func contentText(badge: UIImage?) -> Text { - guard let badge else { - return Text(verbatim: comment.content) - } - let placeholderText = Text(Image(uiImage: OptionBadgeImage.placeholder(for: badge))) - return Text("\(placeholderText)\(Text(verbatim: comment.content))") - } - - private static var contentUIFont: UIFont { - UIFont.pretendardFontFamily( - family: contentFont.fontFamily, - size: contentFont.size - ) - } - - /// 배지 세로 중앙을 본문 글꼴 (ascent − descent) / 2 에 맞춘다(Android PlaceholderVerticalAlign.TextCenter). - /// 반환값은 기준선 아래로 내려가는 배지 높이. - private func badgeDescent(_ badge: UIImage) -> CGFloat { - let font = Self.contentUIFont - let textCenter = (font.ascender + font.descender) / 2 - return badge.size.height / 2 - textCenter - } - - /// 배지 위가 글꼴 ascent 보다 높은 만큼 — Android 는 첫 줄 위쪽이 이만큼 늘어난다(Trim.Both 는 글꼴 수치 기준). - private func badgeTopOverflow(_ badge: UIImage) -> CGFloat { - let badgeTop = badge.size.height - badgeDescent(badge) - return max(0, badgeTop - Self.contentUIFont.ascender) - } - - /// 배지 아래가 글꼴 descent 보다 낮은 만큼 — Android 는 첫 줄 글꼴 수치를 마지막 줄에도 써서 본문 아래가 이만큼 늘어난다. - private func badgeBottomOverflow(_ badge: UIImage) -> CGFloat { - max(0, badgeDescent(badge) + Self.contentUIFont.descender) - } -} - -/// 선택지 배지 이미지 — 배경 radius 2, Medium 12(Android bodyXxsMedium, 한 줄이라 자연 높이), 가로 4·세로 2, 뒤쪽 투명 간격 4 포함. -@MainActor -private enum OptionBadgeImage { - private static var cache: [String: UIImage] = [:] - /// 선택지 제목은 서버에서 계속 바뀌므로 캐시가 쌓이지 않게 상한을 둔다. - private static let cacheLimit = 64 - - private static let horizontalPadding: CGFloat = 4 - private static let verticalPadding: CGFloat = 2 - private static let trailingSpacing: CGFloat = 4 - private static let cornerRadius: CGFloat = 2 - private static let badgeFont: CustomSizeFont = .labelSmall - - static func make( - title: String, - scale: CGFloat - ) -> UIImage? { - guard !title.isEmpty else { return nil } - let key = "\(title)|\(scale)" - if let cached = cache[key] { - return cached - } - - let font = UIFont.pretendardFontFamily( - family: badgeFont.fontFamily, - size: badgeFont.size - ) - let attributes: [NSAttributedString.Key: Any] = [ - .font: font, - .foregroundColor: UIColor(Color.badgeFilledText), - ] - let textWidth = ceil((title as NSString).size(withAttributes: attributes).width) - let badgeWidth = textWidth + horizontalPadding * 2 - let badgeHeight = font.lineHeight + verticalPadding * 2 - - let format = UIGraphicsImageRendererFormat() - format.scale = scale - let renderer = UIGraphicsImageRenderer( - size: CGSize(width: badgeWidth + trailingSpacing, height: badgeHeight), - format: format - ) - let image = renderer.image { _ in - let badgeRect = CGRect(x: 0, y: 0, width: badgeWidth, height: badgeHeight) - UIColor(Color.badgeFilledBackground).setFill() - UIBezierPath(roundedRect: badgeRect, cornerRadius: cornerRadius).fill() - let textOrigin = CGPoint( - x: horizontalPadding, - y: verticalPadding - ) - (title as NSString).draw(at: textOrigin, withAttributes: attributes) - } - if cache.count >= cacheLimit { - cache.removeAll() - } - cache[key] = image - return image - } - - /// 본문 안에서 배지 폭만 차지하는 투명 자리 — 높이 1이라 줄 위쪽 높이를 바꾸지 않는다. - static func placeholder(for badge: UIImage) -> UIImage { - let format = UIGraphicsImageRendererFormat() - format.scale = badge.scale - let renderer = UIGraphicsImageRenderer( - size: CGSize(width: badge.size.width, height: 1), - format: format - ) - return renderer.image { _ in } - } } diff --git a/Projects/Feature/Home/Sources/Main/View/HomeView.swift b/Projects/Feature/Home/Sources/Main/View/HomeView.swift index 2f90fd41..f260b388 100644 --- a/Projects/Feature/Home/Sources/Main/View/HomeView.swift +++ b/Projects/Feature/Home/Sources/Main/View/HomeView.swift @@ -15,6 +15,7 @@ import SwiftUI @ViewAction(for: HomeFeature.self) public struct HomeView: View { @Bindable public var store: StoreOf + @Environment(\.scenePhase) private var scenePhase private static let topAnchorID = "homeTop" @@ -42,6 +43,11 @@ public struct HomeView: View { AttendanceModalView(store: modalStore) } .onAppear { send(.onAppear) } + .onChange(of: scenePhase) { oldPhase, newPhase in + // Android `AppLifecycleObserver.onStart` — 앱으로 돌아올 때마다 하루 1회 출석 체크. + guard oldPhase != .active, newPhase == .active else { return } + send(.appBecameActive) + } .onChange(of: store.toastMessage, initial: true) { _, message in guard let message else { return } ToastManager.shared.showError(message) diff --git a/Projects/Feature/Home/Tests/Sources/AttendanceParityTests.swift b/Projects/Feature/Home/Tests/Sources/AttendanceParityTests.swift new file mode 100644 index 00000000..c208b711 --- /dev/null +++ b/Projects/Feature/Home/Tests/Sources/AttendanceParityTests.swift @@ -0,0 +1,100 @@ +// +// AttendanceParityTests.swift +// HomeTests +// +// Created by Picke on 11/11/26. +// + +import AttendanceDomainInterface +import ComposableArchitecture +import Foundation +@testable import Home +import PickeCoreUtility +import Testing + +/// Android `AppLifecycleObserver.checkAttendanceIfNeeded` · `HomeViewModel.checkInAndShowAttendanceSheetIfNeeded` 와 맞춘 출석. +@MainActor +@Suite(.serialized) +struct AttendanceParityTests { + /// 2026-11-11 12:00 KST + private static let now = Date(timeIntervalSince1970: 1_794_366_000) + + init() { + UserDefaults.standard.removeObject(forKey: AttendanceDayRecord.checkedKey) + UserDefaults.standard.removeObject(forKey: AttendanceDayRecord.sheetShownKey) + } + + @Test + func dayStringUsesKoreanTime() { + // 2026-11-10 15:30 UTC = 2026-11-11 00:30 KST + let date = Date(timeIntervalSince1970: 1_794_324_600) + #expect(date.formatted(.yearMonthDay) == "2026-11-11") + } + + @Test + func returningToAppChecksAttendanceOncePerDay() async { + let store = Self.store(FakeAttendance(checkSucceeds: true)) + let today = Self.now.formatted(.yearMonthDay) + + await store.send(.view(.appBecameActive)) + await store.receive(\.async, .checkAttendanceOnly(day: today)) + await store.receive(\.inner, .attendanceChecked(day: today)) + #expect(AttendanceDayRecord().isChecked(on: today)) + + // 같은 날 다시 돌아오면 부르지 않는다. + await store.send(.view(.appBecameActive)) + } + + @Test + func failedCheckIsRetriedOnNextReturn() async { + let store = Self.store(FakeAttendance(checkSucceeds: false)) + let today = Self.now.formatted(.yearMonthDay) + + await store.send(.view(.appBecameActive)) + await store.receive(\.async, .checkAttendanceOnly(day: today)) + await store.finish() + #expect(!AttendanceDayRecord().isChecked(on: today)) + } + + @Test + func sheetShowsEvenWhenAlreadyAttended() async { + let store = Self.store(FakeAttendance(checkSucceeds: false)) + let today = Self.now.formatted(.yearMonthDay) + + await store.send(.async(.checkAttendance(day: today))) + await store.receive(\.inner) + #expect(store.state.attendanceModal != nil) + #expect(AttendanceDayRecord().isSheetShown(on: today)) + } +} + +extension AttendanceParityTests { + private static func store(_ attendance: FakeAttendance) -> TestStoreOf { + let store = TestStore(initialState: HomeFeature.State()) { + HomeFeature() + } withDependencies: { + $0.attendanceUseCase = attendance + $0.date = .constant(now) + } + store.exhaustivity = .off + return store + } +} + +private struct FakeAttendance: AttendanceInterface { + struct Failure: Error {} + let checkSucceeds: Bool + + func checkAttendance() async throws -> AttendanceCheckResult { + guard checkSucceeds else { throw Failure() } + return .empty + } + + func fetchWeeklyAttendance() async throws -> WeeklyAttendance { + .empty + } + + func fetchAttendanceSummary() async throws -> AttendanceSummary { + .empty + } +} diff --git a/Projects/Feature/Home/Tests/Sources/HomeTests.swift b/Projects/Feature/Home/Tests/Sources/HomeTests.swift index ef92ed88..0db6f2a4 100644 --- a/Projects/Feature/Home/Tests/Sources/HomeTests.swift +++ b/Projects/Feature/Home/Tests/Sources/HomeTests.swift @@ -109,9 +109,9 @@ struct HomeTests { @MainActor func pullToRefreshReloadsWithoutSkeleton() async { let comment = HomeBestComment( + perspectiveId: 501, battleId: 21, battleTitle: "인간은 본래 선한가", - optionTitle: "선하다", content: "선하게 태어나요" ) var state = HomeFeature.State() @@ -137,9 +137,9 @@ struct HomeTests { @MainActor func pullToRefreshFailureKeepsContentAndShowsToast() async { let comment = HomeBestComment( + perspectiveId: 501, battleId: 21, battleTitle: "인간은 본래 선한가", - optionTitle: "선하다", content: "선하게 태어나요" ) var state = HomeFeature.State() @@ -217,9 +217,9 @@ struct HomeTests { @MainActor func bestCommentTapTracksBestCommentSectionAndPresentsPreVote() async { let comment = HomeBestComment( + perspectiveId: 501, battleId: 21, battleTitle: "인간은 본래 선한가", - optionTitle: "선하다", content: "선하게 태어나요" ) let tracked = LockIsolated<[ContentActionData]>([]) @@ -280,9 +280,9 @@ struct HomeTests { @MainActor func homeResponseStoresBestCommentsWithoutMockFallback() async { let comment = HomeBestComment( + perspectiveId: 501, battleId: 21, battleTitle: "인간은 본래 선한가", - optionTitle: "선하다", content: "선하게 태어나요" ) let store = TestStore(initialState: HomeFeature.State()) { diff --git a/Projects/Service/API/Sources/Perspective/PerspectiveAPI.swift b/Projects/Service/API/Sources/Perspective/PerspectiveAPI.swift index b46f0118..3a27a178 100644 --- a/Projects/Service/API/Sources/Perspective/PerspectiveAPI.swift +++ b/Projects/Service/API/Sources/Perspective/PerspectiveAPI.swift @@ -16,6 +16,7 @@ public enum PerspectiveAPI { case likes(perspectiveId: Int) case reports(perspectiveId: Int) case reportComment(perspectiveId: Int, commentId: Int) + case weeklyBest public var description: String { switch self { @@ -35,6 +36,8 @@ public enum PerspectiveAPI { return "\(perspectiveId)/comments/\(commentId)" case let .deleteComment(perspectiveId, commentId): return "\(perspectiveId)/comments/\(commentId)" + case .weeklyBest: + return "weekly-best" } } } diff --git a/Projects/Service/APIEndpoint/Sources/Perspective/PerspectiveService.swift b/Projects/Service/APIEndpoint/Sources/Perspective/PerspectiveService.swift index 72e0dce7..7a9e1fa1 100644 --- a/Projects/Service/APIEndpoint/Sources/Perspective/PerspectiveService.swift +++ b/Projects/Service/APIEndpoint/Sources/Perspective/PerspectiveService.swift @@ -29,6 +29,8 @@ public enum PerspectiveService { case fetchPerspectiveLikes(perspectiveId: Int) case reportPerspective(perspectiveId: Int) case reportComment(perspectiveId: Int, commentId: Int) + /// 홈 Best 댓글 — 직전 한 주 좋아요 상위 관점 (토큰 선택). + case weeklyBest } extension PerspectiveService: PickeDataRequest { @@ -60,12 +62,14 @@ extension PerspectiveService: PickeDataRequest { return PerspectiveAPI.reports(perspectiveId: perspectiveId).description case let .reportComment(perspectiveId, commentId): return PerspectiveAPI.reportComment(perspectiveId: perspectiveId, commentId: commentId).description + case .weeklyBest: + return PerspectiveAPI.weeklyBest.description } } public var method: HTTPMethod { switch self { - case .detail, .listLabeledComments, .fetchPerspectiveLikes: + case .detail, .listLabeledComments, .fetchPerspectiveLikes, .weeklyBest: return .get case .createComment, .likePerspective, .reportPerspective, .reportComment: return .post @@ -93,7 +97,8 @@ extension PerspectiveService: PickeDataRequest { .unlikePerspective, .fetchPerspectiveLikes, .reportPerspective, - .reportComment: + .reportComment, + .weeklyBest: return nil } } diff --git a/Projects/UI/PickeDesignKit/Resources/ImageAssets.xcassets/Common/arrowLeft.imageset/Contents.json b/Projects/UI/PickeDesignKit/Resources/ImageAssets.xcassets/Common/arrowLeft.imageset/Contents.json new file mode 100644 index 00000000..6ca8fbf6 --- /dev/null +++ b/Projects/UI/PickeDesignKit/Resources/ImageAssets.xcassets/Common/arrowLeft.imageset/Contents.json @@ -0,0 +1,16 @@ +{ + "images" : [ + { + "filename" : "arrowLeft.svg", + "idiom" : "universal" + } + ], + "info" : { + "author" : "xcode", + "version" : 1 + }, + "properties" : { + "preserves-vector-representation" : true, + "template-rendering-intent" : "template" + } +} diff --git a/Projects/UI/PickeDesignKit/Resources/ImageAssets.xcassets/Common/arrowLeft.imageset/arrowLeft.svg b/Projects/UI/PickeDesignKit/Resources/ImageAssets.xcassets/Common/arrowLeft.imageset/arrowLeft.svg new file mode 100644 index 00000000..da58110f --- /dev/null +++ b/Projects/UI/PickeDesignKit/Resources/ImageAssets.xcassets/Common/arrowLeft.imageset/arrowLeft.svg @@ -0,0 +1 @@ + diff --git a/Projects/UI/PickeDesignKit/Resources/ImageAssets.xcassets/Common/play.imageset/Contents.json b/Projects/UI/PickeDesignKit/Resources/ImageAssets.xcassets/Common/play.imageset/Contents.json new file mode 100644 index 00000000..2f57ff0f --- /dev/null +++ b/Projects/UI/PickeDesignKit/Resources/ImageAssets.xcassets/Common/play.imageset/Contents.json @@ -0,0 +1,16 @@ +{ + "images" : [ + { + "filename" : "play.svg", + "idiom" : "universal" + } + ], + "info" : { + "author" : "xcode", + "version" : 1 + }, + "properties" : { + "preserves-vector-representation" : true, + "template-rendering-intent" : "template" + } +} diff --git a/Projects/UI/PickeDesignKit/Resources/ImageAssets.xcassets/Common/play.imageset/play.svg b/Projects/UI/PickeDesignKit/Resources/ImageAssets.xcassets/Common/play.imageset/play.svg new file mode 100644 index 00000000..c0331234 --- /dev/null +++ b/Projects/UI/PickeDesignKit/Resources/ImageAssets.xcassets/Common/play.imageset/play.svg @@ -0,0 +1 @@ + diff --git a/Projects/UI/PickeDesignKit/Resources/ImageAssets.xcassets/Common/playBack.imageset/Contents.json b/Projects/UI/PickeDesignKit/Resources/ImageAssets.xcassets/Common/playBack.imageset/Contents.json new file mode 100644 index 00000000..d5b2ca83 --- /dev/null +++ b/Projects/UI/PickeDesignKit/Resources/ImageAssets.xcassets/Common/playBack.imageset/Contents.json @@ -0,0 +1,16 @@ +{ + "images" : [ + { + "filename" : "playBack.svg", + "idiom" : "universal" + } + ], + "info" : { + "author" : "xcode", + "version" : 1 + }, + "properties" : { + "preserves-vector-representation" : true, + "template-rendering-intent" : "template" + } +} diff --git a/Projects/UI/PickeDesignKit/Resources/ImageAssets.xcassets/Common/playBack.imageset/playBack.svg b/Projects/UI/PickeDesignKit/Resources/ImageAssets.xcassets/Common/playBack.imageset/playBack.svg new file mode 100644 index 00000000..15b0e09e --- /dev/null +++ b/Projects/UI/PickeDesignKit/Resources/ImageAssets.xcassets/Common/playBack.imageset/playBack.svg @@ -0,0 +1 @@ + diff --git a/Projects/UI/PickeDesignKit/Resources/ImageAssets.xcassets/Common/playForward.imageset/Contents.json b/Projects/UI/PickeDesignKit/Resources/ImageAssets.xcassets/Common/playForward.imageset/Contents.json new file mode 100644 index 00000000..46b3599b --- /dev/null +++ b/Projects/UI/PickeDesignKit/Resources/ImageAssets.xcassets/Common/playForward.imageset/Contents.json @@ -0,0 +1,16 @@ +{ + "images" : [ + { + "filename" : "playForward.svg", + "idiom" : "universal" + } + ], + "info" : { + "author" : "xcode", + "version" : 1 + }, + "properties" : { + "preserves-vector-representation" : true, + "template-rendering-intent" : "template" + } +} diff --git a/Projects/UI/PickeDesignKit/Resources/ImageAssets.xcassets/Common/playForward.imageset/playForward.svg b/Projects/UI/PickeDesignKit/Resources/ImageAssets.xcassets/Common/playForward.imageset/playForward.svg new file mode 100644 index 00000000..da26b71f --- /dev/null +++ b/Projects/UI/PickeDesignKit/Resources/ImageAssets.xcassets/Common/playForward.imageset/playForward.svg @@ -0,0 +1 @@ + diff --git a/Projects/UI/PickeDesignKit/Resources/ImageAssets.xcassets/Common/playStop.imageset/Contents.json b/Projects/UI/PickeDesignKit/Resources/ImageAssets.xcassets/Common/playStop.imageset/Contents.json new file mode 100644 index 00000000..549980f4 --- /dev/null +++ b/Projects/UI/PickeDesignKit/Resources/ImageAssets.xcassets/Common/playStop.imageset/Contents.json @@ -0,0 +1,16 @@ +{ + "images" : [ + { + "filename" : "playStop.svg", + "idiom" : "universal" + } + ], + "info" : { + "author" : "xcode", + "version" : 1 + }, + "properties" : { + "preserves-vector-representation" : true, + "template-rendering-intent" : "template" + } +} diff --git a/Projects/UI/PickeDesignKit/Resources/ImageAssets.xcassets/Common/playStop.imageset/playStop.svg b/Projects/UI/PickeDesignKit/Resources/ImageAssets.xcassets/Common/playStop.imageset/playStop.svg new file mode 100644 index 00000000..dc802b06 --- /dev/null +++ b/Projects/UI/PickeDesignKit/Resources/ImageAssets.xcassets/Common/playStop.imageset/playStop.svg @@ -0,0 +1 @@ + diff --git a/Projects/UI/PickeDesignKit/Resources/ImageAssets.xcassets/Common/replay.imageset/Contents.json b/Projects/UI/PickeDesignKit/Resources/ImageAssets.xcassets/Common/replay.imageset/Contents.json new file mode 100644 index 00000000..b9825c33 --- /dev/null +++ b/Projects/UI/PickeDesignKit/Resources/ImageAssets.xcassets/Common/replay.imageset/Contents.json @@ -0,0 +1,16 @@ +{ + "images" : [ + { + "filename" : "replay.svg", + "idiom" : "universal" + } + ], + "info" : { + "author" : "xcode", + "version" : 1 + }, + "properties" : { + "preserves-vector-representation" : true, + "template-rendering-intent" : "template" + } +} diff --git a/Projects/UI/PickeDesignKit/Resources/ImageAssets.xcassets/Common/replay.imageset/replay.svg b/Projects/UI/PickeDesignKit/Resources/ImageAssets.xcassets/Common/replay.imageset/replay.svg new file mode 100644 index 00000000..7a09dd0b --- /dev/null +++ b/Projects/UI/PickeDesignKit/Resources/ImageAssets.xcassets/Common/replay.imageset/replay.svg @@ -0,0 +1 @@ + diff --git a/Projects/UI/PickeDesignKit/Resources/ImageAssets.xcassets/Common/share.imageset/Contents.json b/Projects/UI/PickeDesignKit/Resources/ImageAssets.xcassets/Common/share.imageset/Contents.json new file mode 100644 index 00000000..71b0b507 --- /dev/null +++ b/Projects/UI/PickeDesignKit/Resources/ImageAssets.xcassets/Common/share.imageset/Contents.json @@ -0,0 +1,16 @@ +{ + "images" : [ + { + "filename" : "share.svg", + "idiom" : "universal" + } + ], + "info" : { + "author" : "xcode", + "version" : 1 + }, + "properties" : { + "preserves-vector-representation" : true, + "template-rendering-intent" : "template" + } +} diff --git a/Projects/UI/PickeDesignKit/Resources/ImageAssets.xcassets/Common/share.imageset/share.svg b/Projects/UI/PickeDesignKit/Resources/ImageAssets.xcassets/Common/share.imageset/share.svg new file mode 100644 index 00000000..ffda4d7a --- /dev/null +++ b/Projects/UI/PickeDesignKit/Resources/ImageAssets.xcassets/Common/share.imageset/share.svg @@ -0,0 +1 @@ + diff --git a/Projects/UI/PickeDesignKit/Sources/Token/Image/ImageAsset.swift b/Projects/UI/PickeDesignKit/Sources/Token/Image/ImageAsset.swift index bf9383a4..3b3d0393 100644 --- a/Projects/UI/PickeDesignKit/Sources/Token/Image/ImageAsset.swift +++ b/Projects/UI/PickeDesignKit/Sources/Token/Image/ImageAsset.swift @@ -50,8 +50,11 @@ public enum ImageAsset: String { case replyCorner // MARK: - 공용 아이콘 + case close case arrowRight + case arrowLeft + case share case think case more case edit @@ -59,6 +62,11 @@ public enum ImageAsset: String { case report case warning case send + case play + case playStop + case playBack + case playForward + case replay // MARK: - 철학자 아바타 diff --git a/Projects/UI/PickeDesignKit/Sources/UI/Floating/FloatingErrorView.swift b/Projects/UI/PickeDesignKit/Sources/UI/Floating/FloatingErrorView.swift index 296c7e48..76706f5d 100644 --- a/Projects/UI/PickeDesignKit/Sources/UI/Floating/FloatingErrorView.swift +++ b/Projects/UI/PickeDesignKit/Sources/UI/Floating/FloatingErrorView.swift @@ -7,6 +7,7 @@ import SwiftUI +/// Android `PickeErrorBanner` — `errorDefault` 면, radius 8, 그림자 4, 안쪽 16/12, 경고 아이콘 + 14 SemiBold `beige50`. public struct FloatingErrorView: View { private let message: String @@ -16,20 +17,21 @@ public struct FloatingErrorView: View { public var body: some View { HStack(spacing: 8) { - Image(systemName: "exclamationmark.triangle.fill") - .font(.system(size: 16, weight: .semibold)) + Image(asset: .warning) + .renderingMode(.template) + .resizable() + .scaledToFit() .foregroundStyle(.beige50) + .frame(width: 18.8, height: 16.75) Text(message) .pretendardFont(.headingSmall) .foregroundStyle(.beige50) - .kerning(-0.35) - .lineSpacing(14 * 0.28) .fixedSize(horizontal: false, vertical: true) } .padding(.vertical, 12) .padding(.horizontal, 16) - .roundedBackground(.errorStrong, radius: 9) - .shadow(color: Color(hex: "5B0604").opacity(0.28), radius: 5.25, x: 0, y: 0) + .roundedBackground(.errorDefault, radius: 8) + .shadow(color: .black.opacity(0.2), radius: 4, x: 0, y: 2) } } diff --git a/Projects/UI/PickeSharedUI/Sources/Alert/CustomAlertState.swift b/Projects/UI/PickeSharedUI/Sources/Alert/CustomAlertState.swift index 95e9342e..5cb6c0c3 100644 --- a/Projects/UI/PickeSharedUI/Sources/Alert/CustomAlertState.swift +++ b/Projects/UI/PickeSharedUI/Sources/Alert/CustomAlertState.swift @@ -86,13 +86,24 @@ public extension CustomAlertState where Action == CustomAlertAction { static func finalVote() -> CustomAlertState { CustomAlertState( - title: "최종투표하고 투표 결과를 보시겠습니까?", + title: "최종투표하고 투표 결과를 확인하시겠습니까?", confirmTitle: "최종투표하기", cancelTitle: "다시 들어볼래요", style: .finalVote ) } + /// Android `PickeSingleActionDialog`(투표 포인트 부족) — 버튼 하나. + static func pointShortage() -> CustomAlertState { + CustomAlertState( + title: "컨텐츠를 시청하기 위한\n포인트가 부족해요!", + message: "매일 출석체크만 해도 5P를 받을 수 있어요!", + confirmTitle: "배틀 주제 구경하러 가기", + cancelTitle: "", + style: .notice + ) + } + static func deletePerspective() -> CustomAlertState { CustomAlertState( title: "관점을 삭제하시겠습니까?", diff --git a/Projects/UI/PickeSharedUI/Sources/Alert/CustomPopup/CustomConfirmationPopupView+Content.swift b/Projects/UI/PickeSharedUI/Sources/Alert/CustomPopup/CustomConfirmationPopupView+Content.swift index 743ac997..a7992e2c 100644 --- a/Projects/UI/PickeSharedUI/Sources/Alert/CustomPopup/CustomConfirmationPopupView+Content.swift +++ b/Projects/UI/PickeSharedUI/Sources/Alert/CustomPopup/CustomConfirmationPopupView+Content.swift @@ -118,52 +118,14 @@ extension CustomConfirmationPopup { } } + /// Android 관점 삭제 `PickeConfirmDialog` — 왼쪽 "삭제하기"(확정), 오른쪽 채운 "뒤로가기"(취소). var deleteConfirmContent: some View { - VStack(spacing: 16) { - Text(title) - .pretendardFont(.labelMedium) - .foregroundStyle(.primary800) - .lineSpacing(14 * 0.4) - .multilineTextAlignment(.center) - .frame(maxWidth: .infinity) - .padding(.horizontal, 20) - - HStack(spacing: 0) { - // 삭제하기 (왼쪽·밝은 버튼) = 확정(삭제) - Button(action: onConfirm) { - Text(confirmTitle) - .pretendardFont(.labelMedium) - .foregroundStyle(.primary500) - .lineSpacing(14 * 0.4) - .frame(maxWidth: .infinity) - .padding(.vertical, 12) - .background(.secondary50, in: Rectangle()) - } - .buttonStyle(.plain) - - // 뒤로가기 (오른쪽·어두운 버튼) = 취소 - Button(action: onCancel) { - Text(cancelTitle) - .pretendardFont(.labelMedium) - .foregroundStyle(.secondary50) - .lineSpacing(14 * 0.4) - .frame(maxWidth: .infinity) - .padding(.vertical, 12) - .background(.primary500, in: Rectangle()) - } - .buttonStyle(.plain) - } - } - .padding(.top, 20) - .frame(maxWidth: 313) - .pickeCard( - .beige500, - border: .primary500, - lineWidth: 1.5 + pickeConfirmDialog( + leftTitle: confirmTitle, + leftAction: onConfirm, + rightTitle: cancelTitle, + rightAction: onCancel ) - .opacity(0.9) - .clipShape(RoundedRectangle(cornerRadius: .radiusDefault)) - .onTapGesture {} } @ViewBuilder @@ -270,45 +232,72 @@ extension CustomConfirmationPopup { .onTapGesture {} } + /// Android 최종투표 `PickeConfirmDialog` — 왼쪽 "다시 들어볼래요"(취소), 오른쪽 채운 "최종투표하기"(확정). var finalVoteContent: some View { - VStack(spacing: 16) { + pickeConfirmDialog( + leftTitle: cancelTitle, + leftAction: onCancel, + rightTitle: confirmTitle, + rightAction: onConfirm + ) + } + + /// Android `PickeConfirmDialog` — 면 `borderBeigeDisabled`, 테두리 1 `primary500`, radius 2, + /// 본문 안쪽 24·14 SemiBold `primary500`·줄높이 24, 가로·세로 구분선 `primary500`, + /// 왼쪽 투명 면 `primary500` 글자 / 오른쪽 `primary500` 면 `textInverse` 글자, 버튼 세로 16. + func pickeConfirmDialog( + leftTitle: String, + leftAction: @escaping () -> Void, + rightTitle: String, + rightAction: @escaping () -> Void + ) -> some View { + VStack(spacing: 0) { Text(title) - .pretendardFont(.labelMedium) - .foregroundStyle(.neutral900) - .lineSpacing(14 * 0.4) + .pretendardFont(.headingSmall, lineSpacingMultiple: 24 / 14) + .foregroundStyle(.primary500) .multilineTextAlignment(.center) .frame(maxWidth: .infinity) - .padding(.horizontal, 20) + .padding(24) + + Rectangle() + .fill(.primary500) + .frame(height: 1) HStack(spacing: 0) { - Button(action: onCancel) { - Text(cancelTitle) - .pretendardFont(.labelMedium) + Button(action: leftAction) { + Text(leftTitle) + .pretendardFont(.headingSmall) .foregroundStyle(.primary500) - .lineSpacing(14 * 0.4) .frame(maxWidth: .infinity) - .padding(.vertical, 12) - .background(.secondary50, in: Rectangle()) + .padding(.vertical, 16) + .contentShape(Rectangle()) } .buttonStyle(.plain) - Button(action: onConfirm) { - Text(confirmTitle) - .pretendardFont(.labelMedium) - .foregroundStyle(.secondary50) - .lineSpacing(14 * 0.4) + Rectangle() + .fill(.primary500) + .frame(width: 1) + + Button(action: rightAction) { + Text(rightTitle) + .pretendardFont(.headingSmall) + .foregroundStyle(.textInverse) .frame(maxWidth: .infinity) - .padding(.vertical, 12) - .background(.primary500, in: Rectangle()) + .padding(.vertical, 16) + .background(.primary500) + .contentShape(Rectangle()) } .buttonStyle(.plain) } + .fixedSize(horizontal: false, vertical: true) } - .padding(.top, 20) .frame(maxWidth: 313) - .background(.beige500) - .opacity(0.9) - .clipShape(RoundedRectangle(cornerRadius: 2)) + .background(.borderBeigeDisabled) + .clipShape(RoundedRectangle(cornerRadius: .radiusDefault)) + .overlay { + RoundedRectangle(cornerRadius: .radiusDefault) + .strokeBorder(.primary500, lineWidth: 1) + } .onTapGesture {} } } @@ -316,7 +305,7 @@ extension CustomConfirmationPopup { #if DEBUG #Preview("최종 투표 확인") { CustomConfirmationPopup( - title: "최종투표하고 투표 결과를 보시겠습니까?", + title: "최종투표하고 투표 결과를 확인하시겠습니까?", message: "", confirmTitle: "최종투표하기", cancelTitle: "다시 들어볼래요", diff --git a/Projects/UI/PickeSharedUI/Sources/Alert/CustomPopup/CustomConfirmationPopupView.swift b/Projects/UI/PickeSharedUI/Sources/Alert/CustomPopup/CustomConfirmationPopupView.swift index 8edea487..3fe0d5e3 100644 --- a/Projects/UI/PickeSharedUI/Sources/Alert/CustomPopup/CustomConfirmationPopupView.swift +++ b/Projects/UI/PickeSharedUI/Sources/Alert/CustomPopup/CustomConfirmationPopupView.swift @@ -50,7 +50,8 @@ struct CustomConfirmationPopup: View { Color.black .opacity(isContentVisible ? 0.6 : 0) .ignoresSafeArea() - .onTapGesture(perform: onCancel) + // Android 최종투표 대화상자는 바깥 터치도 "최종투표하기" 와 같다. + .onTapGesture(perform: style == .finalVote ? onConfirm : onCancel) popupContent .frame(maxWidth: popupMaxWidth(for: proxy.size.width)) diff --git a/Projects/UI/PickeSharedUI/Sources/AudioPlayer/AudioEqualizerView.swift b/Projects/UI/PickeSharedUI/Sources/AudioPlayer/AudioEqualizerView.swift index f65ba7ad..af0cb353 100644 --- a/Projects/UI/PickeSharedUI/Sources/AudioPlayer/AudioEqualizerView.swift +++ b/Projects/UI/PickeSharedUI/Sources/AudioPlayer/AudioEqualizerView.swift @@ -9,61 +9,36 @@ import SwiftUI import PickeDesignKit +/// Android `ChatBubblePlayingIndicator` — 막대 5개(폭 2.5, 높이 6/10/15/10/6, 간격 2, `iconPrimaryDefault`). +/// 막대마다 120ms 씩 늦게 0.6배 ↔ 최대 배율을 400ms 로 오간다. public struct AudioEqualizerView: View { - private let isPlaying: Bool - private let barCount: Int - private let barWidth: CGFloat - private let spacing: CGFloat - private let minHeight: CGFloat - private let maxHeight: CGFloat - private let color: Color + private static let barWidth: CGFloat = 2.5 + private static let barHeights: [CGFloat] = [6, 10, 15, 10, 6] + private static let maxScales: [CGFloat] = [1.1, 1.3, 1.6, 1.3, 1.1] + private static let minScale: CGFloat = 0.6 - @State private var animating = false + @State private var isAnimating = false - public init( - isPlaying: Bool, - barCount: Int = 4, - barWidth: CGFloat = 3, - spacing: CGFloat = 2, - minHeight: CGFloat = 6, - maxHeight: CGFloat = 18, - color: Color = .primary500 - ) { - self.isPlaying = isPlaying - self.barCount = barCount - self.barWidth = barWidth - self.spacing = spacing - self.minHeight = minHeight - self.maxHeight = maxHeight - self.color = color - } + public init() {} public var body: some View { - HStack(alignment: .center, spacing: spacing) { - ForEach(0 ..< barCount, id: \.self) { index in + HStack(alignment: .center, spacing: 2) { + ForEach(Self.barHeights.indices, id: \.self) { index in Capsule() - .fill(color) - .frame(width: barWidth, height: barHeight(for: index)) + .fill(.iconPrimaryDefault) + .frame(width: Self.barWidth, height: Self.barHeights[index]) + .scaleEffect( + x: 1, + y: isAnimating ? Self.maxScales[index] : Self.minScale + ) + .animation( + .linear(duration: 0.4) + .repeatForever(autoreverses: true) + .delay(Double(index) * 0.12), + value: isAnimating + ) } } - .frame(height: maxHeight) - .animation( - isPlaying - ? .easeInOut(duration: 0.45).repeatForever(autoreverses: true) - : .default, - value: animating - ) - .onAppear { animating = isPlaying } - .onChange(of: isPlaying) { _, newValue in - animating = newValue - } - } - - /// 재생 중이면 막대마다 위상을 다르게 줘서 출렁이는 느낌을 낸다. 정지 시엔 최소 높이로 고정. - private func barHeight(for index: Int) -> CGFloat { - guard isPlaying, animating else { return minHeight } - let ratios: [CGFloat] = [1.0, 0.55, 0.85, 0.4] - let ratio = ratios[index % ratios.count] - return minHeight + (maxHeight - minHeight) * ratio + .onAppear { isAnimating = true } } } diff --git a/Projects/UI/PickeSharedUI/Sources/AudioPlayer/PickeAudioPlayerBar.swift b/Projects/UI/PickeSharedUI/Sources/AudioPlayer/PickeAudioPlayerBar.swift new file mode 100644 index 00000000..2e4d9071 --- /dev/null +++ b/Projects/UI/PickeSharedUI/Sources/AudioPlayer/PickeAudioPlayerBar.swift @@ -0,0 +1,243 @@ +// +// PickeAudioPlayerBar.swift +// PickeSharedUI +// +// Created by Picke on 11/10/26. +// + +import PickeDesignKit +import SwiftUI + +/// Android `AudioPlayerBar` — 슬라이더(20, 트랙 2·썸 12) + 시간(13 Regular) + 컨트롤 행(55). +/// 시나리오 청취 화면과 클래스 배틀 미리보기가 함께 쓴다. +public struct PickeAudioPlayerBar: View { + private let isPlaying: Bool + private let currentTime: TimeInterval + private let totalDuration: TimeInterval + private let playbackRateTitle: String + private let isForwardEnabled: Bool + private let isSeekEnabled: Bool + private let onTogglePlay: () -> Void + private let onSeek: (TimeInterval) -> Void + private let onBackward: () -> Void + private let onForward: () -> Void + private let onPlaybackRateTapped: () -> Void + private let onReplay: () -> Void + + private enum Metric { + static let sliderHeight: CGFloat = 20 + static let trackHeight: CGFloat = 2 + static let thumbSize: CGFloat = 12 + static let controlRowHeight: CGFloat = 55 + } + + public init( + isPlaying: Bool, + currentTime: TimeInterval, + totalDuration: TimeInterval, + playbackRateTitle: String, + isForwardEnabled: Bool = true, + isSeekEnabled: Bool = true, + onTogglePlay: @escaping () -> Void, + onSeek: @escaping (TimeInterval) -> Void, + onBackward: @escaping () -> Void, + onForward: @escaping () -> Void, + onPlaybackRateTapped: @escaping () -> Void, + onReplay: @escaping () -> Void + ) { + self.isPlaying = isPlaying + self.currentTime = currentTime + self.totalDuration = totalDuration + self.playbackRateTitle = playbackRateTitle + self.isForwardEnabled = isForwardEnabled + self.isSeekEnabled = isSeekEnabled + self.onTogglePlay = onTogglePlay + self.onSeek = onSeek + self.onBackward = onBackward + self.onForward = onForward + self.onPlaybackRateTapped = onPlaybackRateTapped + self.onReplay = onReplay + } + + public var body: some View { + VStack(spacing: 0) { + slider + timeRow() + controlRow() + } + .padding(.horizontal, 24) + .padding(.vertical, 20) + .frame(maxWidth: .infinity) + .background { + Rectangle() + .fill(.surfaceBeigeDefault) + .ignoresSafeArea(edges: .bottom) + } + } +} + +// MARK: - Slider + +extension PickeAudioPlayerBar { + private var progress: CGFloat { + guard totalDuration > 0 else { return 0 } + return min(max(CGFloat(currentTime / totalDuration), 0), 1) + } + + private var slider: some View { + GeometryReader { proxy in + let width = proxy.size.width + ZStack(alignment: .leading) { + Rectangle() + .fill(.textMuted) + .frame(height: Metric.trackHeight) + Rectangle() + .fill(.primary500) + .frame(width: width * progress, height: Metric.trackHeight) + Circle() + .fill(.primary500) + .frame(width: Metric.thumbSize, height: Metric.thumbSize) + .offset(x: (width - Metric.thumbSize) * progress) + } + .frame(maxWidth: .infinity, maxHeight: .infinity) + .contentShape(Rectangle()) + .gesture( + DragGesture(minimumDistance: 0) + .onChanged { value in + guard width > 0, totalDuration > 0 else { return } + let ratio = min(max(value.location.x / width, 0), 1) + onSeek(totalDuration * Double(ratio)) + } + ) + .allowsHitTesting(isSeekEnabled) + } + .frame(height: Metric.sliderHeight) + } + + @ViewBuilder + private func timeRow() -> some View { + HStack(spacing: 0) { + Text(Self.timeString(currentTime)) + Spacer(minLength: 0) + Text(Self.timeString(totalDuration)) + } + .pretendardFont(.regular13) + .foregroundStyle(.textMuted) + } + + private static func timeString(_ seconds: TimeInterval) -> String { + let total = max(Int(seconds), 0) + return String(format: "%d:%02d", total / 60, total % 60) + } +} + +// MARK: - Controls + +extension PickeAudioPlayerBar { + @ViewBuilder + private func controlRow() -> some View { + HStack(alignment: .bottom, spacing: 0) { + playbackRateButton + HStack(spacing: 12) { + skipButton( + .playBack, + isEnabled: true, + accessibilityLabel: "15초 뒤로", + action: onBackward + ) + playButton + skipButton( + .playForward, + isEnabled: isForwardEnabled, + accessibilityLabel: "15초 앞으로", + action: onForward + ) + } + .frame(maxWidth: .infinity, maxHeight: .infinity) + replayButton + } + .frame(height: Metric.controlRowHeight) + } + + private var playbackRateButton: some View { + Button(action: onPlaybackRateTapped) { + VStack(spacing: 0) { + Text(playbackRateTitle) + .pretendardFont(family: .Medium, size: 16) + .foregroundStyle(.textDefault) + caption("배속", color: .textMuted) + } + .frame(minWidth: 40) + .contentShape(Rectangle()) + } + .buttonStyle(.plain) + .accessibilityLabel("재생 배속") + .accessibilityValue("\(playbackRateTitle)배속") + } + + private var playButton: some View { + Button(action: onTogglePlay) { + Image(asset: isPlaying ? .playStop : .play) + .resizable() + .scaledToFit() + .foregroundStyle(.gray600) + .frame(width: 22, height: 31) + .padding(.vertical, 8) + .frame(width: 55) + .contentShape(Rectangle()) + } + .buttonStyle(.plain) + .accessibilityLabel(isPlaying ? "일시정지" : "재생") + } + + private var replayButton: some View { + Button(action: onReplay) { + VStack(spacing: 0) { + Image(asset: .replay) + .resizable() + .scaledToFit() + .foregroundStyle(.textDefault) + .frame(width: 24, height: 24) + caption("다시듣기", color: .textMuted) + } + .frame(minWidth: 40) + .contentShape(Rectangle()) + } + .buttonStyle(.plain) + .accessibilityLabel("처음부터 다시 듣기") + } + + @ViewBuilder + private func skipButton( + _ icon: ImageAsset, + isEnabled: Bool, + accessibilityLabel: String, + action: @escaping () -> Void + ) -> some View { + Button(action: action) { + VStack(spacing: 4) { + Spacer(minLength: 0) + Image(asset: icon) + .resizable() + .scaledToFit() + .foregroundStyle(isEnabled ? .gray600 : .gray200) + .frame(width: 20, height: 20) + caption("15초", color: isEnabled ? .textMuted : .gray200) + } + .frame(maxHeight: .infinity) + .contentShape(Rectangle()) + } + .buttonStyle(.plain) + .disabled(!isEnabled) + .accessibilityLabel(accessibilityLabel) + } + + private func caption( + _ text: String, + color: Color + ) -> some View { + Text(text) + .pretendardFont(.labelSmall) + .foregroundStyle(color) + } +}