From be43ca78433baac647857cf2e59dfa8ccd098638 Mon Sep 17 00:00:00 2001 From: opficdev Date: Thu, 26 Nov 2026 14:44:42 +0900 Subject: [PATCH 1/8] =?UTF-8?q?refactor:=20MainView,=20MainFeature,=20Main?= =?UTF-8?q?Tab,=20MainTabBar=20=EC=9D=B4=EB=A6=84=EC=9D=84=20CompositionVi?= =?UTF-8?q?ew,=20CompositionFeature,=20AppTab,=20TabBar=EB=A1=9C=20?= =?UTF-8?q?=EB=B3=80=EA=B2=BD?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../AppGraph+PresentationDependencies.swift | 2 +- .../CompositionFeature.swift} | 44 +++---- .../CompositionView.swift} | 76 ++++++------ .../TabBar.swift} | 14 +-- .../PresentationDependencyPreparation.swift | 2 +- .../Entry/Sources/Root/Feature.swift | 6 +- .../Entry/Sources/Root/RootView.swift | 4 +- .../Routing/{MainTab.swift => AppTab.swift} | 6 +- .../Entry/Sources/Routing/WidgetRoute.swift | 2 +- .../CompositionFeatureTests.swift} | 114 +++++++++--------- .../Entry/Tests/Root/FeatureTestSupport.swift | 30 ++--- .../Entry/Tests/Root/FeatureTests.swift | 18 +-- .../Resources/Localizable.xcstrings | 34 +++--- 13 files changed, 176 insertions(+), 176 deletions(-) rename Application/Presentation/Entry/Sources/{Main/MainFeature.swift => Composition/CompositionFeature.swift} (88%) rename Application/Presentation/Entry/Sources/{Main/MainView.swift => Composition/CompositionView.swift} (94%) rename Application/Presentation/Entry/Sources/{Main/MainTabBar.swift => Composition/TabBar.swift} (90%) rename Application/Presentation/Entry/Sources/Routing/{MainTab.swift => AppTab.swift} (94%) rename Application/Presentation/Entry/Tests/{Main/MainFeatureTests.swift => Composition/CompositionFeatureTests.swift} (66%) diff --git a/Application/App/Sources/App/Dependency/AppGraph+PresentationDependencies.swift b/Application/App/Sources/App/Dependency/AppGraph+PresentationDependencies.swift index 325a5733c..e1db5a45b 100644 --- a/Application/App/Sources/App/Dependency/AppGraph+PresentationDependencies.swift +++ b/Application/App/Sources/App/Dependency/AppGraph+PresentationDependencies.swift @@ -88,7 +88,7 @@ private extension AppGraph { &dependencies, signInUseCase: authenticationGraphSet.authenticationUseCaseGraph.signInUseCase ) - PresentationDependencyPreparation.prepareMain( + PresentationDependencyPreparation.prepareComposition( &dependencies, observeUnreadPushCountUseCase: pushNotificationGraphSet .pushNotificationUseCaseGraph diff --git a/Application/Presentation/Entry/Sources/Main/MainFeature.swift b/Application/Presentation/Entry/Sources/Composition/CompositionFeature.swift similarity index 88% rename from Application/Presentation/Entry/Sources/Main/MainFeature.swift rename to Application/Presentation/Entry/Sources/Composition/CompositionFeature.swift index 172da32e1..b5fbbcfe5 100644 --- a/Application/Presentation/Entry/Sources/Main/MainFeature.swift +++ b/Application/Presentation/Entry/Sources/Composition/CompositionFeature.swift @@ -1,5 +1,5 @@ // -// MainFeature.swift +// CompositionFeature.swift // Entry // // Created by opfic on 6/16/26. @@ -14,7 +14,7 @@ import SwiftUI import UserNotifications @Reducer -struct MainFeature { +struct CompositionFeature { @ObservableState struct State: Equatable { @Presents var alert: AlertState? @@ -28,15 +28,15 @@ struct MainFeature { // 탭 안 화면이 직접 그린 하단 탭 바 뒤로 들어가지 않도록 비울 높이 var tabBarHeight = CGFloat.zero var readableContentWidth = CGFloat.infinity - var openedTabs: Set = [] + var openedTabs: Set = [] var isSideBarCollapsed = false // 사용자가 끌어서 정한 사이드바 폭, 정하지 않았으면 기본 폭 var sideBarWidth: CGFloat? var expandedSideBarGroups: Set = [] - var sideBarLocations: [MainTab: SideBarLocation] = [:] - var sideBarRequests: [MainTab: SideBarRequest] = [:] + var sideBarLocations: [AppTab: SideBarLocation] = [:] + var sideBarRequests: [AppTab: SideBarRequest] = [:] // 칸에 작성 화면을 그린 탭, 덮는 화면처럼 닫기·저장 버튼으로 닫기 전에는 사이드바로 이동하지 않음 - var paneEditingTabs: Set = [] + var paneEditingTabs: Set = [] var sideBarContent = SideBarContent() var isDetailSideBarPresented = false // 앱 화면과 분리해 창 전체에 표시하는 Mac 설정 화면 @@ -44,10 +44,10 @@ struct MainFeature { // 창 전체 설정 화면에서 로그아웃, 회원 탈퇴나 그 알림창이 끝나지 않은 상태 var isSettingsBusy = false // 탭마다 세부 정보 사이드바 대상을 고르는 화면, 대상이 없어도 나타난 순서대로 위치 - var detailSideBarSelections: [MainTab: [DetailSideBarSelection]] = [:] + var detailSideBarSelections: [AppTab: [DetailSideBarSelection]] = [:] // 탭마다 지금 고른 세부 정보 사이드바 대상, 대상을 고른 화면 중 가장 나중에 나타난 화면의 대상 - var detailSideBarTargets: [MainTab: DetailSideBarTarget] { + var detailSideBarTargets: [AppTab: DetailSideBarTarget] { detailSideBarSelections.compactMapValues { $0.last { $0.target != nil }?.target } } } @@ -75,15 +75,15 @@ struct MainFeature { enum ViewAction: Equatable { case onAppear - case selectedTabChanged(MainTab) - case sideBarLocationChanged(MainTab, SideBarLocation) + case selectedTabChanged(AppTab) + case sideBarLocationChanged(AppTab, SideBarLocation) case sideBarContentChanged(SideBarContent) case tapSideBarGroup(SideBarGroup) - case tapSideBarItem(MainTab, SideBarRequest.Action) - case paneEditingChanged(MainTab, Bool) + case tapSideBarItem(AppTab, SideBarRequest.Action) + case paneEditingChanged(AppTab, Bool) case sideBarResized(CGFloat) - case detailSideBarTargetChanged(MainTab, DetailSideBarTarget?, owner: UUID) - case detailSideBarOwnerRemoved(MainTab, owner: UUID) + case detailSideBarTargetChanged(AppTab, DetailSideBarTarget?, owner: UUID) + case detailSideBarOwnerRemoved(AppTab, owner: UUID) } enum StoreAction: Equatable { @@ -196,7 +196,7 @@ extension DependencyValues { set { self[SetApplicationBadgeCountKey.self] = newValue } } - var keyboardEvents: @Sendable () -> AnyPublisher { + var keyboardEvents: @Sendable () -> AnyPublisher { get { self[KeyboardEventsKey.self] } set { self[KeyboardEventsKey.self] = newValue } } @@ -253,23 +253,23 @@ private enum SetApplicationBadgeCountKey: DependencyKey { } private enum KeyboardEventsKey: DependencyKey { - static let liveValue: @Sendable () -> AnyPublisher = { + static let liveValue: @Sendable () -> AnyPublisher = { let center = NotificationCenter.default return center.publisher(for: UIResponder.keyboardWillShowNotification) .map { notification in let frame = (notification.userInfo?[UIResponder.keyboardFrameEndUserInfoKey] as? NSValue)?.cgRectValue - return MainFeature.KeyboardEvent.willShow(height: frame?.height ?? 0) + return CompositionFeature.KeyboardEvent.willShow(height: frame?.height ?? 0) } .merge(with: center.publisher(for: UIResponder.keyboardWillHideNotification).map { _ in .willHide }) .eraseToAnyPublisher() } - static var testValue: @Sendable () -> AnyPublisher { + static var testValue: @Sendable () -> AnyPublisher { liveValue } } -private extension MainFeature { +private extension CompositionFeature { func observeKeyboardEffect() -> Effect { .run { [keyboardEvents] send in for await event in keyboardEvents().values { @@ -304,7 +304,7 @@ private extension MainFeature { do { try await setApplicationBadgeCount(count) } catch { - Logger(category: "MainFeature").error("Failed to update application badge count", error: error) + Logger(category: "CompositionFeature").error("Failed to update application badge count", error: error) } } } @@ -317,12 +317,12 @@ private extension MainFeature { TextState(String(localized: "common_close", bundle: PresentationResources.bundle)) } } message: { - TextState(String(localized: "main_alert_badge_error_message", bundle: PresentationResources.bundle)) + TextState(String(localized: "composition_alert_badge_error_message", bundle: PresentationResources.bundle)) } } } -private extension MainTab { +private extension AppTab { var analyticsScreenName: String? { switch self { case .home: diff --git a/Application/Presentation/Entry/Sources/Main/MainView.swift b/Application/Presentation/Entry/Sources/Composition/CompositionView.swift similarity index 94% rename from Application/Presentation/Entry/Sources/Main/MainView.swift rename to Application/Presentation/Entry/Sources/Composition/CompositionView.swift index bb7e2b776..696928afd 100644 --- a/Application/Presentation/Entry/Sources/Main/MainView.swift +++ b/Application/Presentation/Entry/Sources/Composition/CompositionView.swift @@ -1,5 +1,5 @@ // -// MainView.swift +// CompositionView.swift // Entry // // Created by opfic on 5/8/25. @@ -12,25 +12,25 @@ import ProfileTab import PresentationShared import TodayTab -struct MainView: View { +struct CompositionView: View { @Environment(\.horizontalSizeClass) private var horizontalSizeClass @Environment(\.isiOSAppOnMac) private var isiOSAppOnMac @Environment(\.deviceType) private var deviceType - @Binding var selectedTab: MainTab - @State private var store: StoreOf + @Binding var selectedTab: AppTab + @State private var store: StoreOf private let windowEvent: TodoEditorWindowEvent // 목록 칸과 상세 칸이 함께 들어가는 화면 영역 폭 private let splitMinimumWidth = CGFloat(800) init( windowEvent: TodoEditorWindowEvent, - selectedTab: Binding + selectedTab: Binding ) { @Dependency(\.fetchSideBarWidthUseCase) var fetchSideBarWidthUseCase - var state = MainFeature.State() + var state = CompositionFeature.State() state.sideBarWidth = fetchSideBarWidthUseCase.execute().map { CGFloat($0) } self._store = State(initialValue: Store(initialState: state) { - MainFeature() + CompositionFeature() }) self._selectedTab = selectedTab self.windowEvent = windowEvent @@ -75,9 +75,9 @@ struct MainView: View { if isiOSAppOnMac || deviceType == .ipad { // 탭 전환 애니메이션 없이 한 번 연 탭을 유지하고 선택한 탭만 표시 // 사이드바 하위 항목은 홈 화면이 알려 주므로 홈은 처음부터 생성 - ForEach(MainTab.allCases, id: \.self) { tab in + ForEach(AppTab.allCases, id: \.self) { tab in if store.openedTabs.contains(tab) || selectedTab == tab || tab == .home { - MainTabContent( + TabScreen( store: store, tab: tab, isSelected: selectedTab == tab, @@ -95,11 +95,11 @@ struct MainView: View { } else { TabView(selection: $selectedTab) { Tab( - MainTab.home.title, - systemImage: MainTab.home.symbolName, - value: MainTab.home + AppTab.home.title, + systemImage: AppTab.home.symbolName, + value: AppTab.home ) { - MainTabContent( + TabScreen( store: store, tab: .home, isSelected: selectedTab == .home, @@ -112,11 +112,11 @@ struct MainView: View { ) } Tab( - MainTab.today.title, - systemImage: MainTab.today.symbolName, - value: MainTab.today + AppTab.today.title, + systemImage: AppTab.today.symbolName, + value: AppTab.today ) { - MainTabContent( + TabScreen( store: store, tab: .today, isSelected: selectedTab == .today, @@ -129,11 +129,11 @@ struct MainView: View { ) } Tab( - MainTab.notification.title, - systemImage: MainTab.notification.symbolName, - value: MainTab.notification + AppTab.notification.title, + systemImage: AppTab.notification.symbolName, + value: AppTab.notification ) { - MainTabContent( + TabScreen( store: store, tab: .notification, isSelected: selectedTab == .notification, @@ -147,11 +147,11 @@ struct MainView: View { } .badge(store.unreadPushCount) Tab( - MainTab.profile.title, - systemImage: MainTab.profile.symbolName, - value: MainTab.profile + AppTab.profile.title, + systemImage: AppTab.profile.symbolName, + value: AppTab.profile ) { - MainTabContent( + TabScreen( store: store, tab: .profile, isSelected: selectedTab == .profile, @@ -238,7 +238,7 @@ struct MainView: View { } .overlay { if 0 < verticalBarWidth { - MainTabRail( + DuoTabBar( selectedTab: $selectedTab, edge: store.verticalBarInsets.leading < store.verticalBarInsets.trailing ? .trailing : .leading, width: verticalBarWidth, @@ -264,7 +264,7 @@ struct MainView: View { .toastHost() .safeAreaInset(edge: .bottom, spacing: 0) { if showsTabBar { - MainTabBar( + TabBar( selectedTab: $selectedTab, axis: .horizontal, unreadPushCount: store.unreadPushCount @@ -377,9 +377,9 @@ struct ReadableContentWidthReader: UIViewRepresentable { } } -private struct MainTabContent: View { - let store: StoreOf - let tab: MainTab +private struct TabScreen: View { + let store: StoreOf + let tab: AppTab let isSelected: Bool let isTabBarHidden: Bool let tabBarInset: CGFloat @@ -439,14 +439,14 @@ private struct MainTabContent: View { // Duo 세로 칸 경계선과 아래쪽 탭 // 위쪽 상태 표시와 툴바 버튼 자리는 시스템 세로 막대가 맡음 -private struct MainTabRail: View { - @Binding var selectedTab: MainTab +private struct DuoTabBar: View { + @Binding var selectedTab: AppTab let edge: HorizontalEdge let width: CGFloat let unreadPushCount: Int var body: some View { - MainTabBar( + TabBar( selectedTab: $selectedTab, axis: .vertical, unreadPushCount: unreadPushCount @@ -471,8 +471,8 @@ private struct MainTabRail: View { private struct TreeSideBar: View { @Environment(\.isiOSAppOnMac) private var isiOSAppOnMac @Environment(\.paneWidth) private var paneWidth - @Binding var selectedTab: MainTab - let store: StoreOf + @Binding var selectedTab: AppTab + let store: StoreOf var body: some View { let location = store.sideBarLocations[selectedTab] ?? selectedTab.sideBarLocation @@ -505,7 +505,7 @@ private struct TreeSideBar: View { } ScrollView { VStack(spacing: isiOSAppOnMac ? AdaptiveSize.boardScale : 2) { - ForEach([MainTab.home, .today, .notification], id: \.self) { tab in + ForEach([AppTab.home, .today, .notification], id: \.self) { tab in SideBarRow( title: Text(tab.title), symbolName: tab.symbolName, @@ -581,8 +581,8 @@ private struct TreeSideBar: View { } VStack(spacing: isiOSAppOnMac ? AdaptiveSize.boardScale : 2) { SideBarRow( - title: Text(MainTab.profile.title), - symbolName: MainTab.profile.symbolName, + title: Text(AppTab.profile.title), + symbolName: AppTab.profile.symbolName, isSelected: location == .profile ) { open(.profile) diff --git a/Application/Presentation/Entry/Sources/Main/MainTabBar.swift b/Application/Presentation/Entry/Sources/Composition/TabBar.swift similarity index 90% rename from Application/Presentation/Entry/Sources/Main/MainTabBar.swift rename to Application/Presentation/Entry/Sources/Composition/TabBar.swift index d91d959cc..a7a8c948c 100644 --- a/Application/Presentation/Entry/Sources/Main/MainTabBar.swift +++ b/Application/Presentation/Entry/Sources/Composition/TabBar.swift @@ -1,5 +1,5 @@ // -// MainTabBar.swift +// TabBar.swift // Entry // // Created by opfic on 11/14/26. @@ -10,8 +10,8 @@ import PresentationShared // OS와 기기에 상관없이 같은 모양으로 직접 그리는 탭 // 가로는 화면 아래 탭 바, 세로는 Duo 세로 칸 아래쪽 탭 -struct MainTabBar: View { - @Binding var selectedTab: MainTab +struct TabBar: View { + @Binding var selectedTab: AppTab let axis: Axis let unreadPushCount: Int @@ -20,8 +20,8 @@ struct MainTabBar: View { ? AnyLayout(HStackLayout(alignment: .top, spacing: 0)) : AnyLayout(VStackLayout(spacing: 22)) layout { - ForEach(MainTab.allCases, id: \.self) { tab in - MainTabBarItem( + ForEach(AppTab.allCases, id: \.self) { tab in + TabBarItem( tab: tab, isSelected: selectedTab == tab, badgeCount: tab == .notification ? unreadPushCount : 0, @@ -34,8 +34,8 @@ struct MainTabBar: View { } } -private struct MainTabBarItem: View { - let tab: MainTab +private struct TabBarItem: View { + let tab: AppTab let isSelected: Bool let badgeCount: Int let isFlexible: Bool diff --git a/Application/Presentation/Entry/Sources/Dependency/PresentationDependencyPreparation.swift b/Application/Presentation/Entry/Sources/Dependency/PresentationDependencyPreparation.swift index 95d9caad6..0cb344a08 100644 --- a/Application/Presentation/Entry/Sources/Dependency/PresentationDependencyPreparation.swift +++ b/Application/Presentation/Entry/Sources/Dependency/PresentationDependencyPreparation.swift @@ -33,7 +33,7 @@ public enum PresentationDependencyPreparation { dependencies.signInUseCase = signInUseCase } - public static func prepareMain( + public static func prepareComposition( _ dependencies: inout DependencyValues, observeUnreadPushCountUseCase: ObserveUnreadPushCountUseCase, fetchSideBarWidthUseCase: FetchSideBarWidthUseCase, diff --git a/Application/Presentation/Entry/Sources/Root/Feature.swift b/Application/Presentation/Entry/Sources/Root/Feature.swift index 0c756845e..102c6b9aa 100644 --- a/Application/Presentation/Entry/Sources/Root/Feature.swift +++ b/Application/Presentation/Entry/Sources/Root/Feature.swift @@ -28,7 +28,7 @@ struct Feature { var isNetworkConnected = true var signIn: Bool? var theme: SystemTheme = .automatic - var selectedMainTab = MainTab.home + var selectedTab = AppTab.home var widgetRoute: WidgetRoute? var isObservingNetworkConnectivity = false var isObservingSession = false @@ -137,7 +137,7 @@ struct Feature { if !wasSignedIn, let route = state.widgetRoute { Self.applyWidgetRoute(route, to: &state) } else { - state.selectedMainTab = .home + state.selectedTab = .home } } else { state.widgetRoute = nil @@ -159,7 +159,7 @@ struct Feature { private static func applyWidgetRoute(_ route: WidgetRoute, to state: inout State) { switch route { case .tab(let tab): - state.selectedMainTab = tab + state.selectedTab = tab case .todayTodo(let id): state.sheet = .init(todoId: id) } diff --git a/Application/Presentation/Entry/Sources/Root/RootView.swift b/Application/Presentation/Entry/Sources/Root/RootView.swift index b3261c6ea..22d1672f1 100644 --- a/Application/Presentation/Entry/Sources/Root/RootView.swift +++ b/Application/Presentation/Entry/Sources/Root/RootView.swift @@ -36,9 +36,9 @@ public struct RootView: View { Color.background.ignoresSafeArea() if let signIn = store.signIn { if signIn { - MainView( + CompositionView( windowEvent: windowEvent, - selectedTab: $store.selectedMainTab + selectedTab: $store.selectedTab ) } else { LoginView() diff --git a/Application/Presentation/Entry/Sources/Routing/MainTab.swift b/Application/Presentation/Entry/Sources/Routing/AppTab.swift similarity index 94% rename from Application/Presentation/Entry/Sources/Routing/MainTab.swift rename to Application/Presentation/Entry/Sources/Routing/AppTab.swift index 0db358bd9..e0aff2c5c 100644 --- a/Application/Presentation/Entry/Sources/Routing/MainTab.swift +++ b/Application/Presentation/Entry/Sources/Routing/AppTab.swift @@ -1,5 +1,5 @@ // -// MainTab.swift +// AppTab.swift // Entry // // Created by opfic on 4/30/26. @@ -8,7 +8,7 @@ import Foundation import PresentationShared -public enum MainTab: Hashable, CaseIterable { +public enum AppTab: Hashable, CaseIterable { case home case today case notification @@ -56,7 +56,7 @@ public enum MainTab: Hashable, CaseIterable { } extension SideBarLocation { - var tab: MainTab { + var tab: AppTab { switch self { case .home, .todoCategory, .todoCategoryManagement, .developmentGoal, .search: .home diff --git a/Application/Presentation/Entry/Sources/Routing/WidgetRoute.swift b/Application/Presentation/Entry/Sources/Routing/WidgetRoute.swift index ba4f714b7..328c850c5 100644 --- a/Application/Presentation/Entry/Sources/Routing/WidgetRoute.swift +++ b/Application/Presentation/Entry/Sources/Routing/WidgetRoute.swift @@ -6,6 +6,6 @@ // public enum WidgetRoute: Equatable { - case tab(MainTab) + case tab(AppTab) case todayTodo(String) } diff --git a/Application/Presentation/Entry/Tests/Main/MainFeatureTests.swift b/Application/Presentation/Entry/Tests/Composition/CompositionFeatureTests.swift similarity index 66% rename from Application/Presentation/Entry/Tests/Main/MainFeatureTests.swift rename to Application/Presentation/Entry/Tests/Composition/CompositionFeatureTests.swift index d16ac7666..b693fcafb 100644 --- a/Application/Presentation/Entry/Tests/Main/MainFeatureTests.swift +++ b/Application/Presentation/Entry/Tests/Composition/CompositionFeatureTests.swift @@ -1,5 +1,5 @@ // -// MainFeatureTests.swift +// CompositionFeatureTests.swift // EntryTests // // Created by opfic on 6/16/26. @@ -13,11 +13,11 @@ import Testing @testable import Entry @MainActor -struct MainFeatureTests { - @Test("MainFeature는 기존 Main 상태관리처럼 최초 onAppear에서만 unread count 관찰을 시작한다") - func MainFeature는_기존_Main_상태관리처럼_최초_onAppear에서만_unread_count_관찰을_시작한다() async { - let reference = MainStateManagementReference() - let unreadPushCountUseCase = MainObserveUnreadPushCountUseCaseSpy() +struct CompositionFeatureTests { + @Test("CompositionFeature는 기존 상태관리처럼 최초 onAppear에서만 unread count 관찰을 시작한다") + func CompositionFeature는_기존_상태관리처럼_최초_onAppear에서만_unread_count_관찰을_시작한다() async { + let reference = StateManagementReference() + let unreadPushCountUseCase = ObserveUnreadPushCountUseCaseSpy() let store = makeStore(unreadPushCountUseCase: unreadPushCountUseCase) let firstEffects = reference.reduce(.onAppear) @@ -32,10 +32,10 @@ struct MainFeatureTests { #expect(unreadPushCountUseCase.observeCallCount == 1) } - @Test("MainFeature는 기존 Main 상태관리처럼 notification 탭을 제외한 화면 전환을 추적한다") - func MainFeature는_기존_Main_상태관리처럼_notification_탭을_제외한_화면_전환을_추적한다() async { - let reference = MainStateManagementReference() - let trackAnalyticsEventUseCase = MainTrackAnalyticsEventUseCaseSpy() + @Test("CompositionFeature는 기존 상태관리처럼 notification 탭을 제외한 화면 전환을 추적한다") + func CompositionFeature는_기존_상태관리처럼_notification_탭을_제외한_화면_전환을_추적한다() async { + let reference = StateManagementReference() + let trackAnalyticsEventUseCase = CompositionTrackAnalyticsEventUseCaseSpy() let store = makeStore(trackAnalyticsEventUseCase: trackAnalyticsEventUseCase) let expectedEffects = [ @@ -69,10 +69,10 @@ struct MainFeatureTests { #expect(trackAnalyticsEventUseCase.screenNames == ["home", "today", "profile"]) } - @Test("MainFeature는 기존 Main 상태관리처럼 unread count를 갱신하고 badge 갱신을 요청한다") - func MainFeature는_기존_Main_상태관리처럼_unread_count를_갱신하고_badge_갱신을_요청한다() async { - let reference = MainStateManagementReference() - let badgeCountSpy = MainApplicationBadgeCountSpy() + @Test("CompositionFeature는 기존 상태관리처럼 unread count를 갱신하고 badge 갱신을 요청한다") + func CompositionFeature는_기존_상태관리처럼_unread_count를_갱신하고_badge_갱신을_요청한다() async { + let reference = StateManagementReference() + let badgeCountSpy = CompositionApplicationBadgeCountSpy() let store = makeStore(badgeCountSpy: badgeCountSpy) let effects = reference.reduce(.setUnreadPushCount(7)) @@ -88,9 +88,9 @@ struct MainFeatureTests { #expect(badgeCountSpy.counts == [7]) } - @Test("MainFeature는 기존 Main 상태관리처럼 alert 표시 여부와 문구를 함께 갱신한다") - func MainFeature는_기존_Main_상태관리처럼_alert_state를_갱신한다() async { - let reference = MainStateManagementReference() + @Test("CompositionFeature는 기존 상태관리처럼 alert 표시 여부와 문구를 함께 갱신한다") + func CompositionFeature는_기존_상태관리처럼_alert_state를_갱신한다() async { + let reference = StateManagementReference() let store = makeStore() let presentEffects = reference.reduce(.setAlert) @@ -103,13 +103,13 @@ struct MainFeatureTests { } #expect(presentEffects.isEmpty) - #expect(reference.state.alert == expectedMainErrorAlert()) + #expect(reference.state.alert == expectedCompositionErrorAlert()) } - @Test("MainFeature는 기존 Main 상태관리처럼 unread count 관찰 시작 실패 시 alert를 표시한다") - func MainFeature는_기존_Main_상태관리처럼_unread_count_관찰_시작_실패_시_alert를_표시한다() async { - let reference = MainStateManagementReference() - let unreadPushCountUseCase = MainObserveUnreadPushCountUseCaseSpy(error: MainTestError.failure) + @Test("CompositionFeature는 기존 상태관리처럼 unread count 관찰 시작 실패 시 alert를 표시한다") + func CompositionFeature는_기존_상태관리처럼_unread_count_관찰_시작_실패_시_alert를_표시한다() async { + let reference = StateManagementReference() + let unreadPushCountUseCase = ObserveUnreadPushCountUseCaseSpy(error: CompositionTestError.failure) let store = makeStore(unreadPushCountUseCase: unreadPushCountUseCase) _ = reference.reduce(.onAppear) @@ -122,8 +122,8 @@ struct MainFeatureTests { } } - @Test("MainFeature는 다른 경로로 하위 항목에 들어오면 그 묶음을 펼치고 묶음을 접어도 위치를 유지한다") - func MainFeature는_다른_경로로_하위_항목에_들어오면_그_묶음을_펼치고_묶음을_접어도_위치를_유지한다() async { + @Test("CompositionFeature는 다른 경로로 하위 항목에 들어오면 그 묶음을 펼치고 묶음을 접어도 위치를 유지한다") + func CompositionFeature는_다른_경로로_하위_항목에_들어오면_그_묶음을_펼치고_묶음을_접어도_위치를_유지한다() async { let store = makeStore() await store.send(.view(.sideBarLocationChanged(.home, .todoCategory("issue")))) { @@ -140,8 +140,8 @@ struct MainFeatureTests { } } - @Test("MainFeature는 사라지는 화면이 다른 화면이 고른 세부 정보 사이드바 대상을 지우지 않게 한다") - func MainFeature는_사라지는_화면이_다른_화면이_고른_세부_정보_사이드바_대상을_지우지_않게_한다() async { + @Test("CompositionFeature는 사라지는 화면이 다른 화면이 고른 세부 정보 사이드바 대상을 지우지 않게 한다") + func CompositionFeature는_사라지는_화면이_다른_화면이_고른_세부_정보_사이드바_대상을_지우지_않게_한다() async { let store = makeStore() let goal = UUID() let category = UUID() @@ -157,8 +157,8 @@ struct MainFeatureTests { #expect(store.state.detailSideBarTargets[.home] == nil) } - @Test("MainFeature는 위 화면이 사라지면 아래 화면이 고른 세부 정보 사이드바 대상을 다시 표시한다") - func MainFeature는_위_화면이_사라지면_아래_화면이_고른_세부_정보_사이드바_대상을_다시_표시한다() async { + @Test("CompositionFeature는 위 화면이 사라지면 아래 화면이 고른 세부 정보 사이드바 대상을 다시 표시한다") + func CompositionFeature는_위_화면이_사라지면_아래_화면이_고른_세부_정보_사이드바_대상을_다시_표시한다() async { let store = makeStore() let list = UUID() let editor = UUID() @@ -174,8 +174,8 @@ struct MainFeatureTests { #expect(store.state.detailSideBarTargets[.home] == .todo(id: "other", isEditable: true)) } - @Test("MainFeature는 먼저 나타난 화면이 나중에 대상을 골라도 나중에 나타난 화면의 대상을 유지한다") - func MainFeature는_먼저_나타난_화면이_나중에_대상을_골라도_나중에_나타난_화면의_대상을_유지한다() async { + @Test("CompositionFeature는 먼저 나타난 화면이 나중에 대상을 골라도 나중에 나타난 화면의 대상을 유지한다") + func CompositionFeature는_먼저_나타난_화면이_나중에_대상을_골라도_나중에_나타난_화면의_대상을_유지한다() async { let store = makeStore() let list = UUID() let editor = UUID() @@ -191,10 +191,10 @@ struct MainFeatureTests { #expect(store.state.detailSideBarTargets[.home] == .todo(id: "todo", isEditable: true)) } - @Test("MainFeature는 칸에 작성 화면을 그린 탭의 사이드바 이동 요청을 무시한다") - func MainFeature는_칸에_작성_화면을_그린_탭의_사이드바_이동_요청을_무시한다() async { - let store = TestStore(initialState: MainFeature.State()) { - MainFeature() + @Test("CompositionFeature는 칸에 작성 화면을 그린 탭의 사이드바 이동 요청을 무시한다") + func CompositionFeature는_칸에_작성_화면을_그린_탭의_사이드바_이동_요청을_무시한다() async { + let store = TestStore(initialState: CompositionFeature.State()) { + CompositionFeature() } withDependencies: { $0.uuid = .incrementing } @@ -211,8 +211,8 @@ struct MainFeatureTests { #expect(store.state.sideBarRequests[.home]?.action == .open(.home)) } - @Test("MainFeature는 화면 회전 때 오는 높이 0인 키보드 표시 알림을 무시한다") - func MainFeature는_화면_회전_때_오는_높이_0인_키보드_표시_알림을_무시한다() async { + @Test("CompositionFeature는 화면 회전 때 오는 높이 0인 키보드 표시 알림을 무시한다") + func CompositionFeature는_화면_회전_때_오는_높이_0인_키보드_표시_알림을_무시한다() async { let store = makeStore() await store.send(.store(.keyboardChanged(.willShow(height: 0)))) @@ -227,12 +227,12 @@ struct MainFeatureTests { } } - @Test("MainFeature는 unread count 관찰 값을 기존 Main 상태관리의 setUnreadPushCount 상태 변화로 반영한다") - func MainFeature는_unread_count_관찰_값을_기존_Main_상태관리의_setUnreadPushCount_상태_변화로_반영한다() async { - let reference = MainStateManagementReference() + @Test("CompositionFeature는 unread count 관찰 값을 기존 상태관리의 setUnreadPushCount 상태 변화로 반영한다") + func CompositionFeature는_unread_count_관찰_값을_기존_상태관리의_setUnreadPushCount_상태_변화로_반영한다() async { + let reference = StateManagementReference() let subject = PassthroughSubject() - let unreadPushCountUseCase = MainObserveUnreadPushCountUseCaseSpy(publisher: subject.eraseToAnyPublisher()) - let badgeCountSpy = MainApplicationBadgeCountSpy() + let unreadPushCountUseCase = ObserveUnreadPushCountUseCaseSpy(publisher: subject.eraseToAnyPublisher()) + let badgeCountSpy = CompositionApplicationBadgeCountSpy() let store = makeStore( unreadPushCountUseCase: unreadPushCountUseCase, badgeCountSpy: badgeCountSpy @@ -261,12 +261,12 @@ struct MainFeatureTests { @MainActor private func makeStore( - unreadPushCountUseCase: ObserveUnreadPushCountUseCase = MainObserveUnreadPushCountUseCaseSpy(), - trackAnalyticsEventUseCase: TrackAnalyticsEventUseCase = MainTrackAnalyticsEventUseCaseSpy(), - badgeCountSpy: MainApplicationBadgeCountSpy = MainApplicationBadgeCountSpy() -) -> TestStoreOf { - let store = TestStore(initialState: MainFeature.State()) { - MainFeature() + unreadPushCountUseCase: ObserveUnreadPushCountUseCase = ObserveUnreadPushCountUseCaseSpy(), + trackAnalyticsEventUseCase: TrackAnalyticsEventUseCase = CompositionTrackAnalyticsEventUseCaseSpy(), + badgeCountSpy: CompositionApplicationBadgeCountSpy = CompositionApplicationBadgeCountSpy() +) -> TestStoreOf { + let store = TestStore(initialState: CompositionFeature.State()) { + CompositionFeature() } withDependencies: { $0.observeUnreadPushCountUseCase = unreadPushCountUseCase $0.trackAnalyticsEventUseCase = trackAnalyticsEventUseCase @@ -279,7 +279,7 @@ private func makeStore( } @MainActor -private final class MainStateManagementReference { +private final class StateManagementReference { struct State: Equatable { var alert: AlertState? var unreadPushCount = 0 @@ -287,7 +287,7 @@ private final class MainStateManagementReference { enum Action { case onAppear - case selectedTabChanged(MainTab) + case selectedTabChanged(AppTab) case setUnreadPushCount(Int) case setAlert } @@ -323,11 +323,11 @@ private final class MainStateManagementReference { } private func setAlert() { - state.alert = expectedMainErrorAlert() + state.alert = expectedCompositionErrorAlert() } } -private func expectedMainErrorAlert() -> AlertState { +private func expectedCompositionErrorAlert() -> AlertState { AlertState { TextState(String(localized: "common_error_title", bundle: PresentationResources.bundle)) } actions: { @@ -335,11 +335,11 @@ private func expectedMainErrorAlert() -> AlertState { TextState(String(localized: "common_close", bundle: PresentationResources.bundle)) } } message: { - TextState(String(localized: "main_alert_badge_error_message", bundle: PresentationResources.bundle)) + TextState(String(localized: "composition_alert_badge_error_message", bundle: PresentationResources.bundle)) } } -private final class MainObserveUnreadPushCountUseCaseSpy: ObserveUnreadPushCountUseCase { +private final class ObserveUnreadPushCountUseCaseSpy: ObserveUnreadPushCountUseCase { var publisher: AnyPublisher var error: Error? private(set) var observeCallCount = 0 @@ -363,7 +363,7 @@ private final class MainObserveUnreadPushCountUseCaseSpy: ObserveUnreadPushCount } } -private final class MainTrackAnalyticsEventUseCaseSpy: TrackAnalyticsEventUseCase { +private final class CompositionTrackAnalyticsEventUseCaseSpy: TrackAnalyticsEventUseCase { private var events = [AnalyticsEvent]() var screenNames: [String] { @@ -378,7 +378,7 @@ private final class MainTrackAnalyticsEventUseCaseSpy: TrackAnalyticsEventUseCas } } -private final class MainApplicationBadgeCountSpy: @unchecked Sendable { +private final class CompositionApplicationBadgeCountSpy: @unchecked Sendable { private(set) var counts = [Int]() var error: Error? @@ -391,11 +391,11 @@ private final class MainApplicationBadgeCountSpy: @unchecked Sendable { } } -private enum MainTestError: Error { +private enum CompositionTestError: Error { case failure } -private extension MainTab { +private extension AppTab { var analyticsScreenName: String? { switch self { case .home: diff --git a/Application/Presentation/Entry/Tests/Root/FeatureTestSupport.swift b/Application/Presentation/Entry/Tests/Root/FeatureTestSupport.swift index a0a9d2c9c..bc2082b53 100644 --- a/Application/Presentation/Entry/Tests/Root/FeatureTestSupport.swift +++ b/Application/Presentation/Entry/Tests/Root/FeatureTestSupport.swift @@ -26,7 +26,7 @@ protocol RootStateDriving { func didLogined(_ signIn: Bool) async func presentTodoDetail(_ todoId: String) async func dismissSheet() async - func selectMainTab(_ tab: MainTab) async + func selectTab(_ tab: AppTab) async func openWidgetRoute(_ route: WidgetRoute) async func tapUpdateButton() async } @@ -37,7 +37,7 @@ struct RootStateSnapshot: Equatable { let isNetworkConnected: Bool let signIn: Bool? let theme: SystemTheme - let selectedMainTab: MainTab + let selectedTab: AppTab } @MainActor @@ -51,7 +51,7 @@ struct RootStoreTestAdapter: RootStateDriving { isNetworkConnected: store.state.isNetworkConnected, signIn: store.state.signIn, theme: store.state.theme, - selectedMainTab: store.state.selectedMainTab + selectedTab: store.state.selectedTab ) } var sheetTodoId: String? { store.state.sheet?.todoId } @@ -124,8 +124,8 @@ struct RootStoreTestAdapter: RootStateDriving { await store.send(.sheet(.dismiss)) } - func selectMainTab(_ tab: MainTab) async { - await store.send(.binding(.set(\.selectedMainTab, tab))) + func selectTab(_ tab: AppTab) async { + await store.send(.binding(.set(\.selectedTab, tab))) } func openWidgetRoute(_ route: WidgetRoute) async { @@ -161,7 +161,7 @@ func verifyNetworkDisconnectedAlert(adapter: some RootStateDriving) async { isNetworkConnected: false, signIn: nil, theme: .automatic, - selectedMainTab: .home + selectedTab: .home ) ) } @@ -179,7 +179,7 @@ func verifySetAlert(adapter: some RootStateDriving) async { isNetworkConnected: false, signIn: nil, theme: .automatic, - selectedMainTab: .home + selectedTab: .home ) ) } @@ -190,7 +190,7 @@ func verifyThemeUpdate(adapter: some RootStateDriving) async { #expect(adapter.snapshot.theme == .dark) #expect(adapter.snapshot.alertTitle == nil) - #expect(adapter.snapshot.selectedMainTab == .home) + #expect(adapter.snapshot.selectedTab == .home) } @MainActor @@ -204,7 +204,7 @@ func verifyDidLoginedFalse( } #expect(adapter.snapshot.signIn == false) - #expect(adapter.snapshot.selectedMainTab == .home) + #expect(adapter.snapshot.selectedTab == .home) #expect(trackAnalyticsEventUseCaseSpy.screenNames == ["login"]) } @@ -213,11 +213,11 @@ func verifyDidLoginedTrue( adapter: some RootStateDriving, trackAnalyticsEventUseCaseSpy: RootTrackAnalyticsEventUseCaseSpy ) async { - await adapter.selectMainTab(.today) + await adapter.selectTab(.today) await adapter.didLogined(true) #expect(adapter.snapshot.signIn == true) - #expect(adapter.snapshot.selectedMainTab == .home) + #expect(adapter.snapshot.selectedTab == .home) #expect(trackAnalyticsEventUseCaseSpy.screenNames.isEmpty) } @@ -247,7 +247,7 @@ func verifyObservedInitialValues(adapter: some RootStateDriving) async { isNetworkConnected: false, signIn: false, theme: .dark, - selectedMainTab: .home + selectedTab: .home ) ) } @@ -264,17 +264,17 @@ func verifyTodoDetailSheetPresentation(adapter: some RootStateDriving) async { @MainActor func verifyWidgetRouteOpensWhenSignedIn(adapter: some RootStateDriving) async { await adapter.openWidgetRoute(.tab(.today)) - #expect(adapter.snapshot.selectedMainTab == .home) + #expect(adapter.snapshot.selectedTab == .home) #expect(adapter.widgetRoute == .tab(.today)) await adapter.didLogined(true) - #expect(adapter.snapshot.selectedMainTab == .today) + #expect(adapter.snapshot.selectedTab == .today) #expect(adapter.widgetRoute == .tab(.today)) #expect(adapter.sheetTodoId == nil) await adapter.presentTodoDetail("push-todo") await adapter.openWidgetRoute(.todayTodo("todo-1")) - #expect(adapter.snapshot.selectedMainTab == .today) + #expect(adapter.snapshot.selectedTab == .today) #expect(adapter.sheetTodoId == "todo-1") } diff --git a/Application/Presentation/Entry/Tests/Root/FeatureTests.swift b/Application/Presentation/Entry/Tests/Root/FeatureTests.swift index 76eb5c07f..3851fa123 100644 --- a/Application/Presentation/Entry/Tests/Root/FeatureTests.swift +++ b/Application/Presentation/Entry/Tests/Root/FeatureTests.swift @@ -54,8 +54,8 @@ struct FeatureTests { #expect(badgeSpy.counts == [0]) } - @Test("Feature didLogined(true)는 기존 Root 상태관리처럼 signIn 상태를 true로 갱신하고 selectedMainTab을 home으로 되돌린다") - func RootFeature_didLogined_true는_기존_Root_상태관리처럼_signIn_상태를_true로_갱신하고_selectedMainTab을_home으로_되돌린다() async { + @Test("Feature didLogined(true)는 기존 Root 상태관리처럼 signIn 상태를 true로 갱신하고 selectedTab을 home으로 되돌린다") + func RootFeature_didLogined_true는_기존_Root_상태관리처럼_signIn_상태를_true로_갱신하고_selectedTab을_home으로_되돌린다() async { let trackSpy = RootTrackAnalyticsEventUseCaseSpy() let adapter = RootStoreTestAdapter(trackAnalyticsEventUseCase: trackSpy) @@ -195,7 +195,7 @@ struct FeatureTests { #expect(adapter.widgetRoute == .todayTodo("todo-1")) await adapter.didLogined(true) - #expect(adapter.snapshot.selectedMainTab == .home) + #expect(adapter.snapshot.selectedTab == .home) #expect(adapter.widgetRoute == .todayTodo("todo-1")) #expect(adapter.sheetTodoId == "todo-1") } @@ -209,7 +209,7 @@ struct FeatureTests { #expect(adapter.widgetRoute == nil) await adapter.didLogined(true) - #expect(adapter.snapshot.selectedMainTab == .home) + #expect(adapter.snapshot.selectedTab == .home) #expect(adapter.sheetTodoId == nil) } @@ -229,10 +229,10 @@ struct FeatureTests { let adapter = RootStoreTestAdapter() await adapter.didLogined(true) - await adapter.selectMainTab(.profile) + await adapter.selectTab(.profile) await adapter.openWidgetRoute(.todayTodo("todo-2")) - #expect(adapter.snapshot.selectedMainTab == .profile) + #expect(adapter.snapshot.selectedTab == .profile) #expect(adapter.sheetTodoId == "todo-2") } @@ -241,14 +241,14 @@ struct FeatureTests { let adapter = RootStoreTestAdapter() await adapter.didLogined(true) - await adapter.selectMainTab(.profile) + await adapter.selectTab(.profile) await adapter.openWidgetRoute(.tab(.today)) - #expect(adapter.snapshot.selectedMainTab == .today) + #expect(adapter.snapshot.selectedTab == .today) #expect(adapter.sheetTodoId == nil) await adapter.openWidgetRoute(.todayTodo("todo-1")) - #expect(adapter.snapshot.selectedMainTab == .today) + #expect(adapter.snapshot.selectedTab == .today) #expect(adapter.sheetTodoId == "todo-1") } } diff --git a/Application/Presentation/PresentationShared/Resources/Localizable.xcstrings b/Application/Presentation/PresentationShared/Resources/Localizable.xcstrings index c5fd1abfb..398a6fc28 100644 --- a/Application/Presentation/PresentationShared/Resources/Localizable.xcstrings +++ b/Application/Presentation/PresentationShared/Resources/Localizable.xcstrings @@ -447,6 +447,23 @@ } } }, + "composition_alert_badge_error_message" : { + "extractionState" : "manual", + "localizations" : { + "en" : { + "stringUnit" : { + "state" : "translated", + "value" : "There was a problem loading the notification badge." + } + }, + "ko" : { + "stringUnit" : { + "state" : "translated", + "value" : "알림 배지를 불러오는 중 문제가 발생했어요." + } + } + } + }, "detail_panel_move_to_pane" : { "extractionState" : "manual", "localizations" : { @@ -2742,23 +2759,6 @@ } } }, - "main_alert_badge_error_message" : { - "extractionState" : "manual", - "localizations" : { - "en" : { - "stringUnit" : { - "state" : "translated", - "value" : "There was a problem loading the notification badge." - } - }, - "ko" : { - "stringUnit" : { - "state" : "translated", - "value" : "알림 배지를 불러오는 중 문제가 발생했어요." - } - } - } - }, "nav_account" : { "extractionState" : "manual", "localizations" : { From 34f593e217663f95b4ee51d1490fed331936dee0 Mon Sep 17 00:00:00 2001 From: opficdev Date: Thu, 26 Nov 2026 14:49:11 +0900 Subject: [PATCH 2/8] =?UTF-8?q?refactor:=20CompositionView=EC=97=90?= =?UTF-8?q?=EC=84=9C=20TreeSideBar,=20TabScreen,=20DuoTabBar,=20ReadableCo?= =?UTF-8?q?ntentWidthReader=EB=A5=BC=20=EA=B0=81=20=ED=8C=8C=EC=9D=BC?= =?UTF-8?q?=EB=A1=9C=20=EB=B6=84=EB=A6=AC?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../ReadableContentWidthReader.swift | 39 ++ .../Sources/Composition/CompositionView.swift | 386 ------------------ .../Entry/Sources/Composition/DuoTabBar.swift | 39 ++ .../Entry/Sources/Composition/TabScreen.swift | 108 +++++ .../Sources/Composition/TreeSideBar.swift | 236 +++++++++++ 5 files changed, 422 insertions(+), 386 deletions(-) create mode 100644 Application/Presentation/Entry/Sources/Common/Component/ReadableContentWidthReader.swift create mode 100644 Application/Presentation/Entry/Sources/Composition/DuoTabBar.swift create mode 100644 Application/Presentation/Entry/Sources/Composition/TabScreen.swift create mode 100644 Application/Presentation/Entry/Sources/Composition/TreeSideBar.swift diff --git a/Application/Presentation/Entry/Sources/Common/Component/ReadableContentWidthReader.swift b/Application/Presentation/Entry/Sources/Common/Component/ReadableContentWidthReader.swift new file mode 100644 index 000000000..7e001b218 --- /dev/null +++ b/Application/Presentation/Entry/Sources/Common/Component/ReadableContentWidthReader.swift @@ -0,0 +1,39 @@ +// +// ReadableContentWidthReader.swift +// Entry +// +// Created by opfic on 11/25/26. +// + +import SwiftUI + +// 화면 영역의 readableContentGuide 폭 전달 +struct ReadableContentWidthReader: UIViewRepresentable { + let action: (CGFloat) -> Void + + func makeUIView(context: Context) -> ReaderView { + let view = ReaderView() + view.isUserInteractionEnabled = false + return view + } + + func updateUIView(_ uiView: ReaderView, context: Context) { + uiView.action = action + } + + final class ReaderView: UIView { + var action: ((CGFloat) -> Void)? + private var width: CGFloat? + + override func layoutSubviews() { + super.layoutSubviews() + let width = readableContentGuide.layoutFrame.width + guard width != self.width else { return } + self.width = width + // 레이아웃 중 상태 변경 방지 + DispatchQueue.main.async { [action] in + action?(width) + } + } + } +} diff --git a/Application/Presentation/Entry/Sources/Composition/CompositionView.swift b/Application/Presentation/Entry/Sources/Composition/CompositionView.swift index 696928afd..31adb7e1b 100644 --- a/Application/Presentation/Entry/Sources/Composition/CompositionView.swift +++ b/Application/Presentation/Entry/Sources/Composition/CompositionView.swift @@ -6,11 +6,8 @@ // import SwiftUI -import HomeTab -import NotificationTab import ProfileTab import PresentationShared -import TodayTab struct CompositionView: View { @Environment(\.horizontalSizeClass) private var horizontalSizeClass @@ -310,386 +307,3 @@ struct CompositionView: View { .environment(\.usesDesktopLayout, showsSideBar) } } - -// toolbarVisibility 적용 전 첫 프레임의 탭 바 노출 방지 -// 바깥 SwiftUI 여백은 탭 안 UIKit 화면까지 전달되지 않아 직접 그린 탭 바 높이를 탭 컨트롤러 안전 영역에 더함 -private struct TabBarVisibility: UIViewControllerRepresentable { - let isHidden: Bool - let bottomInset: CGFloat - - func makeUIViewController(context: Context) -> Controller { - Controller() - } - - func updateUIViewController(_ controller: Controller, context: Context) { - controller.isTabBarHidden = isHidden - controller.bottomInset = bottomInset - controller.apply() - } - - final class Controller: UIViewController { - var isTabBarHidden = false - var bottomInset = CGFloat.zero - - override func didMove(toParent parent: UIViewController?) { - super.didMove(toParent: parent) - apply() - } - - func apply() { - guard let tabBarController else { return } - tabBarController.isTabBarHidden = isTabBarHidden - if tabBarController.additionalSafeAreaInsets.bottom != bottomInset { - tabBarController.additionalSafeAreaInsets.bottom = bottomInset - } - } - } -} - -// 화면 영역의 readableContentGuide 폭 전달 -struct ReadableContentWidthReader: UIViewRepresentable { - let action: (CGFloat) -> Void - - func makeUIView(context: Context) -> ReaderView { - let view = ReaderView() - view.isUserInteractionEnabled = false - return view - } - - func updateUIView(_ uiView: ReaderView, context: Context) { - uiView.action = action - } - - final class ReaderView: UIView { - var action: ((CGFloat) -> Void)? - private var width: CGFloat? - - override func layoutSubviews() { - super.layoutSubviews() - let width = readableContentGuide.layoutFrame.width - guard width != self.width else { return } - self.width = width - // 레이아웃 중 상태 변경 방지 - DispatchQueue.main.async { [action] in - action?(width) - } - } - } -} - -private struct TabScreen: View { - let store: StoreOf - let tab: AppTab - let isSelected: Bool - let isTabBarHidden: Bool - let tabBarInset: CGFloat - let usesPaneLayout: Bool - let windowControlsInset: CGFloat - let readableContentWidth: CGFloat - let windowEvent: TodoEditorWindowEvent - - var body: some View { - content - .environment(\.isTabContentActive, isSelected) - .environment(\.usesPaneLayout, usesPaneLayout) - .environment(\.windowControlsInset, windowControlsInset) - .environment(\.readableContentWidth, readableContentWidth) - .environment(\.sideBarRequest, store.sideBarRequests[tab]) - // 좁은 창에서도 고른 대상을 기록해 넓은 창으로 바뀌면 바로 세부 정보 사이드바에 표시 - .environment(\.selectDetailSideBarTarget) { store.send(.view(.detailSideBarTargetChanged(tab, $0, owner: $1))) } - .environment(\.removeDetailSideBarTarget) { store.send(.view(.detailSideBarOwnerRemoved(tab, owner: $0))) } - .onPreferenceChange(SideBarLocationPreferenceKey.self) { location in - guard let location else { return } - store.send(.view(.sideBarLocationChanged(tab, location))) - } - .onPreferenceChange(PaneDetailEditingPreferenceKey.self) { isEditing in - store.send(.view(.paneEditingChanged(tab, isEditing))) - } - .onPreferenceChange(SideBarContentPreferenceKey.self) { content in - guard let content else { return } - store.send(.view(.sideBarContentChanged(content))) - } - .toolbarVisibility(isTabBarHidden ? .hidden : .visible, for: .tabBar) - .background { TabBarVisibility(isHidden: isTabBarHidden, bottomInset: tabBarInset) } - } - - @ViewBuilder - private var content: some View { - switch tab { - case .home: - HomeView( - isSelected: isSelected, - windowEvent: windowEvent - ) - case .today: - TodayView( - isSelected: isSelected, - windowEvent: windowEvent - ) - case .notification: - PushNotificationListView(isSelected: isSelected) - case .profile: - ProfileView( - isSelected: isSelected, - windowEvent: windowEvent - ) - } - } -} - -// Duo 세로 칸 경계선과 아래쪽 탭 -// 위쪽 상태 표시와 툴바 버튼 자리는 시스템 세로 막대가 맡음 -private struct DuoTabBar: View { - @Binding var selectedTab: AppTab - let edge: HorizontalEdge - let width: CGFloat - let unreadPushCount: Int - - var body: some View { - TabBar( - selectedTab: $selectedTab, - axis: .vertical, - unreadPushCount: unreadPushCount - ) - // 시스템 세로 막대 버튼처럼 화면 끝 쪽을 더 띄움 - .padding(edge == .trailing ? .trailing : .leading, 12) - .frame(width: width) - .frame(maxHeight: .infinity, alignment: .bottom) - .overlay(alignment: edge == .trailing ? .leading : .trailing) { - Rectangle() - .fill(Color.separator) - .frame(width: 1) - .ignoresSafeArea(edges: .vertical) - .allowsHitTesting(false) - } - .frame(maxWidth: .infinity, alignment: edge == .trailing ? .trailing : .leading) - .ignoresSafeArea(edges: .horizontal) - } -} - -// Mac과 넓은 iPad 창에서 Finder처럼 위치를 고르는 트리 사이드바 -private struct TreeSideBar: View { - @Environment(\.isiOSAppOnMac) private var isiOSAppOnMac - @Environment(\.paneWidth) private var paneWidth - @Binding var selectedTab: AppTab - let store: StoreOf - - var body: some View { - let location = store.sideBarLocations[selectedTab] ?? selectedTab.sideBarLocation - let expandedGroups = store.expandedSideBarGroups - let isCompact = (paneWidth ?? .infinity) < SideBarRow.compactWidth - let collapseButton = Button { - store.send(.binding(.set(\.isSideBarCollapsed, true))) - } label: { - Image(systemName: "sidebar.left") - } - .topBarButtonStyle() - - GeometryReader { geometry in - VStack(spacing: 0) { - // 칸 제목 줄과 같은 높이의 사이드바 접기 줄 - PaneTitleBar(background: .secondaryBackground) { - EmptyView() - } actions: { - if !isCompact { - collapseButton - } - } - // 아이콘만 보일 때는 아래 줄 아이콘과 같은 세로선에 배치 - .overlay(alignment: .leading) { - if isCompact { - collapseButton - .frame(width: isiOSAppOnMac ? 18 * AdaptiveSize.boardScale : 20) - .padding(.leading, isiOSAppOnMac ? (8 + 4 + 14 + 6) * AdaptiveSize.boardScale : 8 + 6 + 16 + 8) - } - } - ScrollView { - VStack(spacing: isiOSAppOnMac ? AdaptiveSize.boardScale : 2) { - ForEach([AppTab.home, .today, .notification], id: \.self) { tab in - SideBarRow( - title: Text(tab.title), - symbolName: tab.symbolName, - isSelected: location == tab.sideBarLocation, - badgeCount: tab == .notification ? store.unreadPushCount : 0 - ) { - open(tab.sideBarLocation) - } - } - SideBarRow( - title: Text("development_goal_title", bundle: PresentationResources.bundle), - symbolName: "flag.checkered", - isExpanded: expandedGroups.contains(.developmentGoal) - ) { - store.send(.view(.tapSideBarGroup(.developmentGoal)), animation: .easeInOut(duration: 0.2)) - } - if expandedGroups.contains(.developmentGoal) { - ForEach(store.sideBarContent.developmentGoals) { goal in - SideBarRow( - title: Text(goal.title), - symbolName: "flag", - isChild: true, - isSelected: location == .developmentGoal(goal.id) - ) { - open(.developmentGoal(goal.id)) - } - } - } - SideBarRow( - title: Text(verbatim: "Todo"), - symbolName: "tray.fill", - isSelected: location == .todoCategoryManagement, - isExpanded: expandedGroups.contains(.todo) - ) { - store.send(.view(.tapSideBarGroup(.todo)), animation: .easeInOut(duration: 0.2)) - } - .contextMenu { - Button { - request(.createTodo) - } label: { - Label { - Text("sidebar_new_todo", bundle: PresentationResources.bundle) - } icon: { - Image(systemName: "square.and.pencil") - } - } - Button { - request(.manageTodoCategory) - } label: { - Label { - Text("todo_category_manage", bundle: PresentationResources.bundle) - } icon: { - Image(systemName: "square.grid.2x2") - } - } - } - if expandedGroups.contains(.todo) { - ForEach(store.sideBarContent.todoCategories) { item in - SideBarRow( - title: Text(item.localizedName), - symbolName: item.symbolName, - symbolColor: item.color, - isChild: true, - isSelected: location == .todoCategory(item.id) - ) { - open(.todoCategory(item.id)) - } - } - } - } - .padding(.horizontal, 8 * AdaptiveSize.boardScale) - .padding(.vertical, 10 * AdaptiveSize.boardScale) - } - VStack(spacing: isiOSAppOnMac ? AdaptiveSize.boardScale : 2) { - SideBarRow( - title: Text(AppTab.profile.title), - symbolName: AppTab.profile.symbolName, - isSelected: location == .profile - ) { - open(.profile) - } - SideBarRow( - title: Text("nav_settings", bundle: PresentationResources.bundle), - symbolName: "gearshape.fill", - isSelected: location == .settings - ) { - // 앱 화면과 분리한 설정 화면 표시 - store.send(.binding(.set(\.isSettingsPresented, true))) - } - } - .padding(.horizontal, 8 * AdaptiveSize.boardScale) - .padding(.vertical, 10 * AdaptiveSize.boardScale) - } - .padding(.top, geometry.windowControlsInset) - } - // 칸이 기본 폭보다 좁아도 잘라 내지 않고 지금 폭에 맞춰 배치 - .frame(width: paneWidth) - } - - private func open(_ location: SideBarLocation) { - selectedTab = location.tab - store.send(.view(.tapSideBarItem(location.tab, .open(location)))) - } - - // Todo 우클릭 메뉴의 작성과 카테고리 관리는 홈 화면에서 표시 - private func request(_ action: SideBarRequest.Action) { - selectedTab = .home - store.send(.view(.tapSideBarItem(.home, action))) - } -} - -// Mac과 iPad가 같은 모양으로 쓰는 트리 사이드바 항목 -// Mac은 Mac 화면 크기, iPad는 손가락으로 누르는 크기 -private struct SideBarRow: View { - // 이름이 들어갈 자리가 없어 아이콘만 표시하는 폭 - static let compactWidth = ProcessInfo.processInfo.isiOSAppOnMac ? 104 * AdaptiveSize.boardScale : 120 - - @Environment(\.isiOSAppOnMac) private var isiOSAppOnMac - @Environment(\.paneWidth) private var paneWidth - let title: Text - let symbolName: String - var symbolColor: Color? - var isChild = false - var isSelected = false - // 묶음 이름 줄만 펼침 여부가 있음 - var isExpanded: Bool? - var badgeCount = 0 - let action: () -> Void - - var body: some View { - let isCompact = (paneWidth ?? .infinity) < Self.compactWidth - - Button(action: action) { - HStack(spacing: isiOSAppOnMac ? 6 * AdaptiveSize.boardScale : 8) { - Image(systemName: "chevron.right") - .font(.adaptive(.caption2).weight(.bold)) - .foregroundStyle(Color.secondaryLabel) - .rotationEffect(.degrees(isExpanded == true ? 90 : 0)) - .opacity(isExpanded == nil ? 0 : 1) - .frame(width: isiOSAppOnMac ? 14 * AdaptiveSize.boardScale : 16) - Image(systemName: symbolName) - .font(.adaptive(.body)) - .foregroundStyle(symbolColor ?? .secondaryLabel) - .frame(width: isiOSAppOnMac ? 18 * AdaptiveSize.boardScale : 20) - // 아이콘만 보일 때 읽지 않은 알림은 아이콘 오른쪽 위 점으로 표시 - .overlay(alignment: .topTrailing) { - if isCompact && 0 < badgeCount { - Circle() - .fill(Color.accent) - .frame(width: 7 * AdaptiveSize.boardScale, height: 7 * AdaptiveSize.boardScale) - .offset(x: 3 * AdaptiveSize.boardScale, y: -2 * AdaptiveSize.boardScale) - } - } - title - .font(.adaptive(isiOSAppOnMac ? .body : .subheadline).weight(isChild ? .medium : .semibold)) - .lineLimit(1) - // 아이콘만 보일 때도 이름 줄 높이는 유지 - .frame(maxWidth: isCompact ? 0 : nil) - .opacity(isCompact ? 0 : 1) - // 읽지 않은 개수는 이름 바로 오른쪽에 표시 - if !isCompact && 0 < badgeCount { - Text(verbatim: badgeCount.formatted()) - .font(.adaptive(.caption2)) - .monospacedDigit() - .foregroundStyle(Color.white) - .padding(.horizontal, 4 * AdaptiveSize.boardScale) - .frame(minWidth: 18 * AdaptiveSize.boardScale, minHeight: 18 * AdaptiveSize.boardScale) - .background(Color.accent, in: .capsule) - .fixedSize() - } - } - .foregroundStyle(Color.label) - .frame(maxWidth: .infinity, alignment: .leading) - .padding(.leading, isiOSAppOnMac ? (isChild && !isCompact ? 22 : 4) * AdaptiveSize.boardScale : (isChild && !isCompact ? 34 : 6)) - .padding(.trailing, isiOSAppOnMac ? 8 * AdaptiveSize.boardScale : 10) - .frame(minHeight: isiOSAppOnMac ? 28 * AdaptiveSize.boardScale : 44) - .hoverHighlight(in: RoundedRectangle(cornerRadius: CornerRadius.control), isEnabled: !isSelected) - // 선택 표시는 마우스 표시와 같은 회색 - .background { - RoundedRectangle(cornerRadius: CornerRadius.control) - .fill(isSelected ? Color.fill : .clear) - } - .contentShape(.rect) - } - .buttonStyle(.plain) - } -} diff --git a/Application/Presentation/Entry/Sources/Composition/DuoTabBar.swift b/Application/Presentation/Entry/Sources/Composition/DuoTabBar.swift new file mode 100644 index 000000000..76c5c7aee --- /dev/null +++ b/Application/Presentation/Entry/Sources/Composition/DuoTabBar.swift @@ -0,0 +1,39 @@ +// +// DuoTabBar.swift +// Entry +// +// Created by opfic on 11/25/26. +// + +import SwiftUI +import PresentationShared + +// Duo 세로 칸 경계선과 아래쪽 탭 +// 위쪽 상태 표시와 툴바 버튼 자리는 시스템 세로 막대가 맡음 +struct DuoTabBar: View { + @Binding var selectedTab: AppTab + let edge: HorizontalEdge + let width: CGFloat + let unreadPushCount: Int + + var body: some View { + TabBar( + selectedTab: $selectedTab, + axis: .vertical, + unreadPushCount: unreadPushCount + ) + // 시스템 세로 막대 버튼처럼 화면 끝 쪽을 더 띄움 + .padding(edge == .trailing ? .trailing : .leading, 12) + .frame(width: width) + .frame(maxHeight: .infinity, alignment: .bottom) + .overlay(alignment: edge == .trailing ? .leading : .trailing) { + Rectangle() + .fill(Color.separator) + .frame(width: 1) + .ignoresSafeArea(edges: .vertical) + .allowsHitTesting(false) + } + .frame(maxWidth: .infinity, alignment: edge == .trailing ? .trailing : .leading) + .ignoresSafeArea(edges: .horizontal) + } +} diff --git a/Application/Presentation/Entry/Sources/Composition/TabScreen.swift b/Application/Presentation/Entry/Sources/Composition/TabScreen.swift new file mode 100644 index 000000000..c4fbb68be --- /dev/null +++ b/Application/Presentation/Entry/Sources/Composition/TabScreen.swift @@ -0,0 +1,108 @@ +// +// TabScreen.swift +// Entry +// +// Created by opfic on 11/25/26. +// + +import SwiftUI +import HomeTab +import NotificationTab +import ProfileTab +import PresentationShared +import TodayTab + +struct TabScreen: View { + let store: StoreOf + let tab: AppTab + let isSelected: Bool + let isTabBarHidden: Bool + let tabBarInset: CGFloat + let usesPaneLayout: Bool + let windowControlsInset: CGFloat + let readableContentWidth: CGFloat + let windowEvent: TodoEditorWindowEvent + + var body: some View { + content + .environment(\.isTabContentActive, isSelected) + .environment(\.usesPaneLayout, usesPaneLayout) + .environment(\.windowControlsInset, windowControlsInset) + .environment(\.readableContentWidth, readableContentWidth) + .environment(\.sideBarRequest, store.sideBarRequests[tab]) + // 좁은 창에서도 고른 대상을 기록해 넓은 창으로 바뀌면 바로 세부 정보 사이드바에 표시 + .environment(\.selectDetailSideBarTarget) { store.send(.view(.detailSideBarTargetChanged(tab, $0, owner: $1))) } + .environment(\.removeDetailSideBarTarget) { store.send(.view(.detailSideBarOwnerRemoved(tab, owner: $0))) } + .onPreferenceChange(SideBarLocationPreferenceKey.self) { location in + guard let location else { return } + store.send(.view(.sideBarLocationChanged(tab, location))) + } + .onPreferenceChange(PaneDetailEditingPreferenceKey.self) { isEditing in + store.send(.view(.paneEditingChanged(tab, isEditing))) + } + .onPreferenceChange(SideBarContentPreferenceKey.self) { content in + guard let content else { return } + store.send(.view(.sideBarContentChanged(content))) + } + .toolbarVisibility(isTabBarHidden ? .hidden : .visible, for: .tabBar) + .background { TabBarVisibility(isHidden: isTabBarHidden, bottomInset: tabBarInset) } + } + + @ViewBuilder + private var content: some View { + switch tab { + case .home: + HomeView( + isSelected: isSelected, + windowEvent: windowEvent + ) + case .today: + TodayView( + isSelected: isSelected, + windowEvent: windowEvent + ) + case .notification: + PushNotificationListView(isSelected: isSelected) + case .profile: + ProfileView( + isSelected: isSelected, + windowEvent: windowEvent + ) + } + } +} + +// toolbarVisibility 적용 전 첫 프레임의 탭 바 노출 방지 +// 바깥 SwiftUI 여백은 탭 안 UIKit 화면까지 전달되지 않아 직접 그린 탭 바 높이를 탭 컨트롤러 안전 영역에 더함 +private struct TabBarVisibility: UIViewControllerRepresentable { + let isHidden: Bool + let bottomInset: CGFloat + + func makeUIViewController(context: Context) -> Controller { + Controller() + } + + func updateUIViewController(_ controller: Controller, context: Context) { + controller.isTabBarHidden = isHidden + controller.bottomInset = bottomInset + controller.apply() + } + + final class Controller: UIViewController { + var isTabBarHidden = false + var bottomInset = CGFloat.zero + + override func didMove(toParent parent: UIViewController?) { + super.didMove(toParent: parent) + apply() + } + + func apply() { + guard let tabBarController else { return } + tabBarController.isTabBarHidden = isTabBarHidden + if tabBarController.additionalSafeAreaInsets.bottom != bottomInset { + tabBarController.additionalSafeAreaInsets.bottom = bottomInset + } + } + } +} diff --git a/Application/Presentation/Entry/Sources/Composition/TreeSideBar.swift b/Application/Presentation/Entry/Sources/Composition/TreeSideBar.swift new file mode 100644 index 000000000..8c96ae419 --- /dev/null +++ b/Application/Presentation/Entry/Sources/Composition/TreeSideBar.swift @@ -0,0 +1,236 @@ +// +// TreeSideBar.swift +// Entry +// +// Created by opfic on 11/25/26. +// + +import SwiftUI +import PresentationShared + +// Mac과 넓은 iPad 창에서 Finder처럼 위치를 고르는 트리 사이드바 +struct TreeSideBar: View { + @Environment(\.isiOSAppOnMac) private var isiOSAppOnMac + @Environment(\.paneWidth) private var paneWidth + @Binding var selectedTab: AppTab + let store: StoreOf + + var body: some View { + let location = store.sideBarLocations[selectedTab] ?? selectedTab.sideBarLocation + let expandedGroups = store.expandedSideBarGroups + let isCompact = (paneWidth ?? .infinity) < SideBarRow.compactWidth + let collapseButton = Button { + store.send(.binding(.set(\.isSideBarCollapsed, true))) + } label: { + Image(systemName: "sidebar.left") + } + .topBarButtonStyle() + + GeometryReader { geometry in + VStack(spacing: 0) { + // 칸 제목 줄과 같은 높이의 사이드바 접기 줄 + PaneTitleBar(background: .secondaryBackground) { + EmptyView() + } actions: { + if !isCompact { + collapseButton + } + } + // 아이콘만 보일 때는 아래 줄 아이콘과 같은 세로선에 배치 + .overlay(alignment: .leading) { + if isCompact { + collapseButton + .frame(width: isiOSAppOnMac ? 18 * AdaptiveSize.boardScale : 20) + .padding(.leading, isiOSAppOnMac ? (8 + 4 + 14 + 6) * AdaptiveSize.boardScale : 8 + 6 + 16 + 8) + } + } + ScrollView { + VStack(spacing: isiOSAppOnMac ? AdaptiveSize.boardScale : 2) { + ForEach([AppTab.home, .today, .notification], id: \.self) { tab in + SideBarRow( + title: Text(tab.title), + symbolName: tab.symbolName, + isSelected: location == tab.sideBarLocation, + badgeCount: tab == .notification ? store.unreadPushCount : 0 + ) { + open(tab.sideBarLocation) + } + } + SideBarRow( + title: Text("development_goal_title", bundle: PresentationResources.bundle), + symbolName: "flag.checkered", + isExpanded: expandedGroups.contains(.developmentGoal) + ) { + store.send(.view(.tapSideBarGroup(.developmentGoal)), animation: .easeInOut(duration: 0.2)) + } + if expandedGroups.contains(.developmentGoal) { + ForEach(store.sideBarContent.developmentGoals) { goal in + SideBarRow( + title: Text(goal.title), + symbolName: "flag", + isChild: true, + isSelected: location == .developmentGoal(goal.id) + ) { + open(.developmentGoal(goal.id)) + } + } + } + SideBarRow( + title: Text(verbatim: "Todo"), + symbolName: "tray.fill", + isSelected: location == .todoCategoryManagement, + isExpanded: expandedGroups.contains(.todo) + ) { + store.send(.view(.tapSideBarGroup(.todo)), animation: .easeInOut(duration: 0.2)) + } + .contextMenu { + Button { + request(.createTodo) + } label: { + Label { + Text("sidebar_new_todo", bundle: PresentationResources.bundle) + } icon: { + Image(systemName: "square.and.pencil") + } + } + Button { + request(.manageTodoCategory) + } label: { + Label { + Text("todo_category_manage", bundle: PresentationResources.bundle) + } icon: { + Image(systemName: "square.grid.2x2") + } + } + } + if expandedGroups.contains(.todo) { + ForEach(store.sideBarContent.todoCategories) { item in + SideBarRow( + title: Text(item.localizedName), + symbolName: item.symbolName, + symbolColor: item.color, + isChild: true, + isSelected: location == .todoCategory(item.id) + ) { + open(.todoCategory(item.id)) + } + } + } + } + .padding(.horizontal, 8 * AdaptiveSize.boardScale) + .padding(.vertical, 10 * AdaptiveSize.boardScale) + } + VStack(spacing: isiOSAppOnMac ? AdaptiveSize.boardScale : 2) { + SideBarRow( + title: Text(AppTab.profile.title), + symbolName: AppTab.profile.symbolName, + isSelected: location == .profile + ) { + open(.profile) + } + SideBarRow( + title: Text("nav_settings", bundle: PresentationResources.bundle), + symbolName: "gearshape.fill", + isSelected: location == .settings + ) { + // 앱 화면과 분리한 설정 화면 표시 + store.send(.binding(.set(\.isSettingsPresented, true))) + } + } + .padding(.horizontal, 8 * AdaptiveSize.boardScale) + .padding(.vertical, 10 * AdaptiveSize.boardScale) + } + .padding(.top, geometry.windowControlsInset) + } + // 칸이 기본 폭보다 좁아도 잘라 내지 않고 지금 폭에 맞춰 배치 + .frame(width: paneWidth) + } + + private func open(_ location: SideBarLocation) { + selectedTab = location.tab + store.send(.view(.tapSideBarItem(location.tab, .open(location)))) + } + + // Todo 우클릭 메뉴의 작성과 카테고리 관리는 홈 화면에서 표시 + private func request(_ action: SideBarRequest.Action) { + selectedTab = .home + store.send(.view(.tapSideBarItem(.home, action))) + } +} + +// Mac과 iPad가 같은 모양으로 쓰는 트리 사이드바 항목 +// Mac은 Mac 화면 크기, iPad는 손가락으로 누르는 크기 +private struct SideBarRow: View { + // 이름이 들어갈 자리가 없어 아이콘만 표시하는 폭 + static let compactWidth = ProcessInfo.processInfo.isiOSAppOnMac ? 104 * AdaptiveSize.boardScale : 120 + + @Environment(\.isiOSAppOnMac) private var isiOSAppOnMac + @Environment(\.paneWidth) private var paneWidth + let title: Text + let symbolName: String + var symbolColor: Color? + var isChild = false + var isSelected = false + // 묶음 이름 줄만 펼침 여부가 있음 + var isExpanded: Bool? + var badgeCount = 0 + let action: () -> Void + + var body: some View { + let isCompact = (paneWidth ?? .infinity) < Self.compactWidth + + Button(action: action) { + HStack(spacing: isiOSAppOnMac ? 6 * AdaptiveSize.boardScale : 8) { + Image(systemName: "chevron.right") + .font(.adaptive(.caption2).weight(.bold)) + .foregroundStyle(Color.secondaryLabel) + .rotationEffect(.degrees(isExpanded == true ? 90 : 0)) + .opacity(isExpanded == nil ? 0 : 1) + .frame(width: isiOSAppOnMac ? 14 * AdaptiveSize.boardScale : 16) + Image(systemName: symbolName) + .font(.adaptive(.body)) + .foregroundStyle(symbolColor ?? .secondaryLabel) + .frame(width: isiOSAppOnMac ? 18 * AdaptiveSize.boardScale : 20) + // 아이콘만 보일 때 읽지 않은 알림은 아이콘 오른쪽 위 점으로 표시 + .overlay(alignment: .topTrailing) { + if isCompact && 0 < badgeCount { + Circle() + .fill(Color.accent) + .frame(width: 7 * AdaptiveSize.boardScale, height: 7 * AdaptiveSize.boardScale) + .offset(x: 3 * AdaptiveSize.boardScale, y: -2 * AdaptiveSize.boardScale) + } + } + title + .font(.adaptive(isiOSAppOnMac ? .body : .subheadline).weight(isChild ? .medium : .semibold)) + .lineLimit(1) + // 아이콘만 보일 때도 이름 줄 높이는 유지 + .frame(maxWidth: isCompact ? 0 : nil) + .opacity(isCompact ? 0 : 1) + // 읽지 않은 개수는 이름 바로 오른쪽에 표시 + if !isCompact && 0 < badgeCount { + Text(verbatim: badgeCount.formatted()) + .font(.adaptive(.caption2)) + .monospacedDigit() + .foregroundStyle(Color.white) + .padding(.horizontal, 4 * AdaptiveSize.boardScale) + .frame(minWidth: 18 * AdaptiveSize.boardScale, minHeight: 18 * AdaptiveSize.boardScale) + .background(Color.accent, in: .capsule) + .fixedSize() + } + } + .foregroundStyle(Color.label) + .frame(maxWidth: .infinity, alignment: .leading) + .padding(.leading, isiOSAppOnMac ? (isChild && !isCompact ? 22 : 4) * AdaptiveSize.boardScale : (isChild && !isCompact ? 34 : 6)) + .padding(.trailing, isiOSAppOnMac ? 8 * AdaptiveSize.boardScale : 10) + .frame(minHeight: isiOSAppOnMac ? 28 * AdaptiveSize.boardScale : 44) + .hoverHighlight(in: RoundedRectangle(cornerRadius: CornerRadius.control), isEnabled: !isSelected) + // 선택 표시는 마우스 표시와 같은 회색 + .background { + RoundedRectangle(cornerRadius: CornerRadius.control) + .fill(isSelected ? Color.fill : .clear) + } + .contentShape(.rect) + } + .buttonStyle(.plain) + } +} From 0985ac578f5371b4c01c9f7a36d77bb4656a88e6 Mon Sep 17 00:00:00 2001 From: opficdev Date: Thu, 26 Nov 2026 14:53:35 +0900 Subject: [PATCH 3/8] =?UTF-8?q?refactor:=20=EC=99=BC=EC=AA=BD,=20=EA=B0=80?= =?UTF-8?q?=EC=9A=B4=EB=8D=B0,=20=EC=98=A4=EB=A5=B8=EC=AA=BD,=20=EB=8D=AE?= =?UTF-8?q?=EA=B0=9C=20=EC=9E=90=EB=A6=AC=EB=A7=8C=20=EC=9E=88=EB=8A=94=20?= =?UTF-8?q?SplitShell=EC=9D=84=20=EC=B6=94=EA=B0=80=ED=95=98=EA=B3=A0=20Co?= =?UTF-8?q?mpositionView=EA=B0=80=20=EC=9E=90=EB=A6=AC=EB=A7=88=EB=8B=A4?= =?UTF-8?q?=20=ED=99=94=EB=A9=B4=EC=9D=84=20=EB=84=A3=EB=8F=84=EB=A1=9D=20?= =?UTF-8?q?=EB=B3=80=EA=B2=BD?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../Sources/Common/Component/SplitShell.swift | 38 +++++++ .../Sources/Composition/CompositionView.swift | 100 ++++-------------- .../Entry/Sources/Composition/TabScreen.swift | 6 -- 3 files changed, 60 insertions(+), 84 deletions(-) create mode 100644 Application/Presentation/Entry/Sources/Common/Component/SplitShell.swift diff --git a/Application/Presentation/Entry/Sources/Common/Component/SplitShell.swift b/Application/Presentation/Entry/Sources/Common/Component/SplitShell.swift new file mode 100644 index 000000000..35368301f --- /dev/null +++ b/Application/Presentation/Entry/Sources/Common/Component/SplitShell.swift @@ -0,0 +1,38 @@ +// +// SplitShell.swift +// Entry +// +// Created by opfic on 11/25/26. +// + +import SwiftUI + +// 왼쪽, 가운데, 오른쪽 자리와 창 전체를 덮는 자리만 있는 껍데기 +// 자리마다 어떤 화면이 언제 나올지는 쓰는 쪽에서 결정 +struct SplitShell: View { + private let left: Left + private let center: Center + private let right: Right + private let overlay: Overlay + + init( + @ViewBuilder left: () -> Left, + @ViewBuilder center: () -> Center, + @ViewBuilder right: () -> Right, + @ViewBuilder overlay: () -> Overlay + ) { + self.left = left() + self.center = center() + self.right = right() + self.overlay = overlay() + } + + var body: some View { + HStack(spacing: 0) { + left + center + right + } + .overlay { overlay } + } +} diff --git a/Application/Presentation/Entry/Sources/Composition/CompositionView.swift b/Application/Presentation/Entry/Sources/Composition/CompositionView.swift index 31adb7e1b..cda8e1f96 100644 --- a/Application/Presentation/Entry/Sources/Composition/CompositionView.swift +++ b/Application/Presentation/Entry/Sources/Composition/CompositionView.swift @@ -9,6 +9,7 @@ import SwiftUI import ProfileTab import PresentationShared +// SplitShell의 자리마다 넣을 화면과 탭 바를 정하는 화면 struct CompositionView: View { @Environment(\.horizontalSizeClass) private var horizontalSizeClass @Environment(\.isiOSAppOnMac) private var isiOSAppOnMac @@ -50,7 +51,7 @@ struct CompositionView: View { let sideBarIdealWidth = isiOSAppOnMac ? 220 * AdaptiveSize.boardScale : 250 let tabBarInset = showsTabBar ? store.tabBarHeight : 0 - HStack(spacing: 0) { + SplitShell { if showsSideBar && !store.isSideBarCollapsed { // 최소는 화살표와 아이콘만 보이는 폭, Mac 최대는 Orca 사이드바와 같은 폭 TreeSideBar(selectedTab: $selectedTab, store: store) @@ -65,7 +66,7 @@ struct CompositionView: View { // 칸 자르기 밖이라 잘리지 않도록 바탕은 칸 바깥에서 아래쪽 안전 영역까지 채움 .background(Color.secondaryBackground, ignoresSafeAreaEdges: .bottom) } - + } center: { ZStack { // iPad는 시스템 탭 바를 쓰지 않아 Mac과 같이 구성 // 넓은 창과 좁은 창을 오가도 탭 화면을 다시 만들지 않음 @@ -80,9 +81,6 @@ struct CompositionView: View { isSelected: selectedTab == tab, isTabBarHidden: isSystemTabBarHidden, tabBarInset: tabBarInset, - usesPaneLayout: showsSideBar, - windowControlsInset: tabContentInset, - readableContentWidth: readableContentWidth, windowEvent: windowEvent ) .opacity(selectedTab == tab ? 1 : 0) @@ -91,78 +89,25 @@ struct CompositionView: View { } } else { TabView(selection: $selectedTab) { - Tab( - AppTab.home.title, - systemImage: AppTab.home.symbolName, - value: AppTab.home - ) { - TabScreen( - store: store, - tab: .home, - isSelected: selectedTab == .home, - isTabBarHidden: isSystemTabBarHidden, - tabBarInset: tabBarInset, - usesPaneLayout: showsSideBar, - windowControlsInset: tabContentInset, - readableContentWidth: readableContentWidth, - windowEvent: windowEvent - ) - } - Tab( - AppTab.today.title, - systemImage: AppTab.today.symbolName, - value: AppTab.today - ) { - TabScreen( - store: store, - tab: .today, - isSelected: selectedTab == .today, - isTabBarHidden: isSystemTabBarHidden, - tabBarInset: tabBarInset, - usesPaneLayout: showsSideBar, - windowControlsInset: tabContentInset, - readableContentWidth: readableContentWidth, - windowEvent: windowEvent - ) - } - Tab( - AppTab.notification.title, - systemImage: AppTab.notification.symbolName, - value: AppTab.notification - ) { - TabScreen( - store: store, - tab: .notification, - isSelected: selectedTab == .notification, - isTabBarHidden: isSystemTabBarHidden, - tabBarInset: tabBarInset, - usesPaneLayout: showsSideBar, - windowControlsInset: tabContentInset, - readableContentWidth: readableContentWidth, - windowEvent: windowEvent - ) - } - .badge(store.unreadPushCount) - Tab( - AppTab.profile.title, - systemImage: AppTab.profile.symbolName, - value: AppTab.profile - ) { - TabScreen( - store: store, - tab: .profile, - isSelected: selectedTab == .profile, - isTabBarHidden: isSystemTabBarHidden, - tabBarInset: tabBarInset, - usesPaneLayout: showsSideBar, - windowControlsInset: tabContentInset, - readableContentWidth: readableContentWidth, - windowEvent: windowEvent - ) + ForEach(AppTab.allCases, id: \.self) { tab in + Tab(tab.title, systemImage: tab.symbolName, value: tab) { + TabScreen( + store: store, + tab: tab, + isSelected: selectedTab == tab, + isTabBarHidden: isSystemTabBarHidden, + tabBarInset: tabBarInset, + windowEvent: windowEvent + ) + } + .badge(tab == .notification ? store.unreadPushCount : 0) } } } } + .environment(\.usesPaneLayout, showsSideBar) + .environment(\.windowControlsInset, tabContentInset) + .environment(\.readableContentWidth, readableContentWidth) .background { ReadableContentWidthReader { width in store.send(.binding(.set(\.readableContentWidth, width))) @@ -188,7 +133,7 @@ struct CompositionView: View { \.setDetailSideBarPresented, showsDetailSideBar ? { store.send(.binding(.set(\.isDetailSideBarPresented, $0))) } : nil ) - + } right: { // 칸 화면이 사이드바를 직접 그리면 창 사이드바는 표시하지 않음 if showsDetailSideBar && store.isDetailSideBarPresented @@ -200,10 +145,9 @@ struct CompositionView: View { store.send(.binding(.set(\.isDetailSideBarPresented, false))) } } - } - // 사이드바가 있는 창의 설정은 앱 화면을 덮어 창 전체에 표시하고 닫으면 보던 화면으로 돌아감 - // 창이 좁아져도 진행 중인 로그아웃, 회원 탈퇴나 그 알림창이 끝날 때까지 표시 - .overlay { + } overlay: { + // 사이드바가 있는 창의 설정은 앱 화면을 덮어 창 전체에 표시하고 닫으면 보던 화면으로 돌아감 + // 창이 좁아져도 진행 중인 로그아웃, 회원 탈퇴나 그 알림창이 끝날 때까지 표시 if store.isSettingsPresented && (showsSideBar || store.isSettingsBusy) { DesktopSettingsView { isBusy in store.send(.binding(.set(\.isSettingsBusy, isBusy))) diff --git a/Application/Presentation/Entry/Sources/Composition/TabScreen.swift b/Application/Presentation/Entry/Sources/Composition/TabScreen.swift index c4fbb68be..26c343e4e 100644 --- a/Application/Presentation/Entry/Sources/Composition/TabScreen.swift +++ b/Application/Presentation/Entry/Sources/Composition/TabScreen.swift @@ -18,17 +18,11 @@ struct TabScreen: View { let isSelected: Bool let isTabBarHidden: Bool let tabBarInset: CGFloat - let usesPaneLayout: Bool - let windowControlsInset: CGFloat - let readableContentWidth: CGFloat let windowEvent: TodoEditorWindowEvent var body: some View { content .environment(\.isTabContentActive, isSelected) - .environment(\.usesPaneLayout, usesPaneLayout) - .environment(\.windowControlsInset, windowControlsInset) - .environment(\.readableContentWidth, readableContentWidth) .environment(\.sideBarRequest, store.sideBarRequests[tab]) // 좁은 창에서도 고른 대상을 기록해 넓은 창으로 바뀌면 바로 세부 정보 사이드바에 표시 .environment(\.selectDetailSideBarTarget) { store.send(.view(.detailSideBarTargetChanged(tab, $0, owner: $1))) } From 04db3205d391f7cf9df7ba469e49de42e8db4d35 Mon Sep 17 00:00:00 2001 From: opficdev Date: Thu, 26 Nov 2026 14:58:58 +0900 Subject: [PATCH 4/8] =?UTF-8?q?refactor:=20CompositionFeature=EC=97=90?= =?UTF-8?q?=EC=84=9C=20SideBarFeature,=20DetailSideBarFeature,=20UnreadPus?= =?UTF-8?q?hCountFeature=EB=A5=BC=20=EB=82=98=EB=88=A0=20Scope=EB=A1=9C=20?= =?UTF-8?q?=ED=95=A9=EC=B9=A8?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../Composition/CompositionFeature.swift | 234 ++----------- .../Sources/Composition/CompositionView.swift | 48 +-- .../Composition/DetailSideBarFeature.swift | 59 ++++ .../Sources/Composition/SideBarFeature.swift | 124 +++++++ .../Entry/Sources/Composition/TabScreen.swift | 12 +- .../Sources/Composition/TreeSideBar.swift | 25 +- .../Composition/UnreadPushCountFeature.swift | 124 +++++++ .../CompositionFeatureTestSupport.swift | 180 ++++++++++ .../Composition/CompositionFeatureTests.swift | 331 +----------------- .../DetailSideBarFeatureTests.swift | 74 ++++ .../Composition/SideBarFeatureTests.swift | 54 +++ .../UnreadPushCountFeatureTests.swift | 94 +++++ 12 files changed, 790 insertions(+), 569 deletions(-) create mode 100644 Application/Presentation/Entry/Sources/Composition/DetailSideBarFeature.swift create mode 100644 Application/Presentation/Entry/Sources/Composition/SideBarFeature.swift create mode 100644 Application/Presentation/Entry/Sources/Composition/UnreadPushCountFeature.swift create mode 100644 Application/Presentation/Entry/Tests/Composition/CompositionFeatureTestSupport.swift create mode 100644 Application/Presentation/Entry/Tests/Composition/DetailSideBarFeatureTests.swift create mode 100644 Application/Presentation/Entry/Tests/Composition/SideBarFeatureTests.swift create mode 100644 Application/Presentation/Entry/Tests/Composition/UnreadPushCountFeatureTests.swift diff --git a/Application/Presentation/Entry/Sources/Composition/CompositionFeature.swift b/Application/Presentation/Entry/Sources/Composition/CompositionFeature.swift index b5fbbcfe5..ba112b46b 100644 --- a/Application/Presentation/Entry/Sources/Composition/CompositionFeature.swift +++ b/Application/Presentation/Entry/Sources/Composition/CompositionFeature.swift @@ -7,19 +7,14 @@ import Combine import PresentationShared -import Core import Domain import Foundation import SwiftUI -import UserNotifications @Reducer struct CompositionFeature { @ObservableState struct State: Equatable { - @Presents var alert: AlertState? - var unreadPushCount = 0 - var isObservingUnreadPushCount = false var windowControlsInset = CGFloat.zero // Duo 세로 칸 자리의 양옆 안전 영역 var verticalBarInsets = EdgeInsets() @@ -28,33 +23,15 @@ struct CompositionFeature { // 탭 안 화면이 직접 그린 하단 탭 바 뒤로 들어가지 않도록 비울 높이 var tabBarHeight = CGFloat.zero var readableContentWidth = CGFloat.infinity + var hasAppeared = false var openedTabs: Set = [] - var isSideBarCollapsed = false - // 사용자가 끌어서 정한 사이드바 폭, 정하지 않았으면 기본 폭 - var sideBarWidth: CGFloat? - var expandedSideBarGroups: Set = [] - var sideBarLocations: [AppTab: SideBarLocation] = [:] - var sideBarRequests: [AppTab: SideBarRequest] = [:] - // 칸에 작성 화면을 그린 탭, 덮는 화면처럼 닫기·저장 버튼으로 닫기 전에는 사이드바로 이동하지 않음 - var paneEditingTabs: Set = [] - var sideBarContent = SideBarContent() - var isDetailSideBarPresented = false // 앱 화면과 분리해 창 전체에 표시하는 Mac 설정 화면 var isSettingsPresented = false // 창 전체 설정 화면에서 로그아웃, 회원 탈퇴나 그 알림창이 끝나지 않은 상태 var isSettingsBusy = false - // 탭마다 세부 정보 사이드바 대상을 고르는 화면, 대상이 없어도 나타난 순서대로 위치 - var detailSideBarSelections: [AppTab: [DetailSideBarSelection]] = [:] - - // 탭마다 지금 고른 세부 정보 사이드바 대상, 대상을 고른 화면 중 가장 나중에 나타난 화면의 대상 - var detailSideBarTargets: [AppTab: DetailSideBarTarget] { - detailSideBarSelections.compactMapValues { $0.last { $0.target != nil }?.target } - } - } - - struct DetailSideBarSelection: Equatable { - let owner: UUID - var target: DetailSideBarTarget? + var sideBar = SideBarFeature.State() + var detailSideBar = DetailSideBarFeature.State() + var unreadPushCount = UnreadPushCountFeature.State() } enum KeyboardEvent: Equatable { @@ -62,194 +39,78 @@ struct CompositionFeature { case willHide } - enum SideBarGroup: Hashable { - case todo - case developmentGoal - } - enum Action: BindableAction, Equatable { - case alert(PresentationAction) case binding(BindingAction) case view(ViewAction) + case sideBar(SideBarFeature.Action) + case detailSideBar(DetailSideBarFeature.Action) + case unreadPushCount(UnreadPushCountFeature.Action) case store(StoreAction) enum ViewAction: Equatable { case onAppear case selectedTabChanged(AppTab) - case sideBarLocationChanged(AppTab, SideBarLocation) - case sideBarContentChanged(SideBarContent) - case tapSideBarGroup(SideBarGroup) - case tapSideBarItem(AppTab, SideBarRequest.Action) - case paneEditingChanged(AppTab, Bool) - case sideBarResized(CGFloat) - case detailSideBarTargetChanged(AppTab, DetailSideBarTarget?, owner: UUID) - case detailSideBarOwnerRemoved(AppTab, owner: UUID) } enum StoreAction: Equatable { - case setUnreadPushCount(Int) case keyboardChanged(KeyboardEvent) - case setAlert } } private enum CancelID: Hashable { - case unreadPushCount case keyboard } - @Dependency(\.observeUnreadPushCountUseCase) var observeUnreadPushCountUseCase - @Dependency(\.uuid) var uuid @Dependency(\.trackAnalyticsEventUseCase) var trackAnalyticsEventUseCase - @Dependency(\.setApplicationBadgeCount) var setApplicationBadgeCount - @Dependency(\.updateSideBarWidthUseCase) var updateSideBarWidthUseCase @Dependency(\.keyboardEvents) var keyboardEvents var body: some ReducerOf { + Scope(state: \.sideBar, action: \.sideBar) { + SideBarFeature() + } + Scope(state: \.detailSideBar, action: \.detailSideBar) { + DetailSideBarFeature() + } + Scope(state: \.unreadPushCount, action: \.unreadPushCount) { + UnreadPushCountFeature() + } BindingReducer() Reduce { state, action in switch action { - case .alert: - break case .binding: break case .view(.onAppear): - guard !state.isObservingUnreadPushCount else { break } - state.isObservingUnreadPushCount = true - return .merge(observeUnreadPushCountEffect(), observeKeyboardEffect()) + guard !state.hasAppeared else { break } + state.hasAppeared = true + return .merge( + .send(.unreadPushCount(.startObserving)), + observeKeyboardEffect() + ) case .view(.selectedTabChanged(let tab)): state.openedTabs.insert(tab) - guard let screenName = tab.analyticsScreenName else { break } - return trackScreenViewEffect(screenName) - case .view(.sideBarLocationChanged(let tab, let location)): - state.sideBarLocations[tab] = location - // 홈 카테고리 격자처럼 다른 경로로 하위 항목에 들어오면 그 묶음을 펼침 - switch location { - case .todoCategory: - state.expandedSideBarGroups.insert(.todo) - case .developmentGoal: - state.expandedSideBarGroups.insert(.developmentGoal) - case .home, .todoCategoryManagement, .search, .today, .notification, .profile, .settings: - break - } - case .view(.sideBarContentChanged(let content)): - state.sideBarContent = content - case .view(.tapSideBarGroup(let group)): - if state.expandedSideBarGroups.contains(group) { - state.expandedSideBarGroups.remove(group) - } else { - state.expandedSideBarGroups.insert(group) - } - case .view(.tapSideBarItem(let tab, let action)): - guard !state.paneEditingTabs.contains(tab) else { break } - state.sideBarRequests[tab] = SideBarRequest(id: uuid(), action: action) - case .view(.paneEditingChanged(let tab, let isEditing)): - if isEditing { - state.paneEditingTabs.insert(tab) - } else { - state.paneEditingTabs.remove(tab) - } - case .view(.sideBarResized(let width)): - state.sideBarWidth = width - return .run { [updateSideBarWidthUseCase] _ in - updateSideBarWidthUseCase.execute(Double(width)) - } - case .view(.detailSideBarTargetChanged(let tab, let target, let owner)): - // 대상을 바꿔도 화면이 나타난 순서의 자리 유지 - var selections = state.detailSideBarSelections[tab, default: []] - if let index = selections.firstIndex(where: { $0.owner == owner }) { - selections[index].target = target - } else { - selections.append(DetailSideBarSelection(owner: owner, target: target)) - } - state.detailSideBarSelections[tab] = selections - case .view(.detailSideBarOwnerRemoved(let tab, let owner)): - // 사라지는 화면은 자기 자리만 지우고, 그 아래 화면이 고른 대상을 다시 표시 - state.detailSideBarSelections[tab]?.removeAll { $0.owner == owner } - case .store(.setUnreadPushCount(let count)): - state.unreadPushCount = count - return updateBadgeCountEffect(count) + return trackScreenViewEffect(tab) + case .sideBar(.tapSettings): + state.isSettingsPresented = true + case .sideBar, .detailSideBar, .unreadPushCount: + break case .store(.keyboardChanged(.willShow(let height))): // 화면을 돌리면 키보드 없이도 높이 0인 키보드 표시 알림이 와서 무시 guard 0 < height else { break } state.isKeyboardVisible = true case .store(.keyboardChanged(.willHide)): state.isKeyboardVisible = false - case .store(.setAlert): - state.alert = Self.alertState() } return .none } - .ifLet(\.$alert, action: \.alert) } } extension DependencyValues { - var observeUnreadPushCountUseCase: ObserveUnreadPushCountUseCase { - get { self[ObserveUnreadPushCountUseCaseKey.self] } - set { self[ObserveUnreadPushCountUseCaseKey.self] = newValue } - } - - var setApplicationBadgeCount: @Sendable (Int) async throws -> Void { - get { self[SetApplicationBadgeCountKey.self] } - set { self[SetApplicationBadgeCountKey.self] = newValue } - } - var keyboardEvents: @Sendable () -> AnyPublisher { get { self[KeyboardEventsKey.self] } set { self[KeyboardEventsKey.self] = newValue } } - - var fetchSideBarWidthUseCase: FetchSideBarWidthUseCase { - get { self[FetchSideBarWidthUseCaseKey.self] } - set { self[FetchSideBarWidthUseCaseKey.self] = newValue } - } - - var updateSideBarWidthUseCase: UpdateSideBarWidthUseCase { - get { self[UpdateSideBarWidthUseCaseKey.self] } - set { self[UpdateSideBarWidthUseCaseKey.self] = newValue } - } -} - -private enum FetchSideBarWidthUseCaseKey: DependencyKey { - static var liveValue: FetchSideBarWidthUseCase { - preconditionFailure("FetchSideBarWidthUseCase must be provided.") - } - - static var testValue: FetchSideBarWidthUseCase { - liveValue - } -} - -private enum UpdateSideBarWidthUseCaseKey: DependencyKey { - static var liveValue: UpdateSideBarWidthUseCase { - preconditionFailure("UpdateSideBarWidthUseCase must be provided.") - } - - static var testValue: UpdateSideBarWidthUseCase { - liveValue - } -} - -private enum ObserveUnreadPushCountUseCaseKey: DependencyKey { - static var liveValue: ObserveUnreadPushCountUseCase { - preconditionFailure("ObserveUnreadPushCountUseCase must be provided.") - } - - static var testValue: ObserveUnreadPushCountUseCase { - liveValue - } -} - -private enum SetApplicationBadgeCountKey: DependencyKey { - static let liveValue: @Sendable (Int) async throws -> Void = { count in - try await UNUserNotificationCenter.current().setBadgeCount(count) - } - - static var testValue: @Sendable (Int) async throws -> Void { - liveValue - } } private enum KeyboardEventsKey: DependencyKey { @@ -279,47 +140,12 @@ private extension CompositionFeature { .cancellable(id: CancelID.keyboard, cancelInFlight: true) } - func observeUnreadPushCountEffect() -> Effect { - .run { [observeUnreadPushCountUseCase] send in - do { - let publisher = try observeUnreadPushCountUseCase.observe() - for try await count in publisher.values { - await send(.store(.setUnreadPushCount(count))) - } - } catch { - await send(.store(.setAlert)) - } - } - .cancellable(id: CancelID.unreadPushCount, cancelInFlight: true) - } - - func trackScreenViewEffect(_ screenName: String) -> Effect { - .run { [trackAnalyticsEventUseCase] _ in + func trackScreenViewEffect(_ tab: AppTab) -> Effect { + guard let screenName = tab.analyticsScreenName else { return .none } + return .run { [trackAnalyticsEventUseCase] _ in trackAnalyticsEventUseCase.execute(.screenView(screenName)) } } - - func updateBadgeCountEffect(_ count: Int) -> Effect { - .run { [setApplicationBadgeCount] _ in - do { - try await setApplicationBadgeCount(count) - } catch { - Logger(category: "CompositionFeature").error("Failed to update application badge count", error: error) - } - } - } - - static func alertState() -> AlertState { - AlertState { - TextState(String(localized: "common_error_title", bundle: PresentationResources.bundle)) - } actions: { - ButtonState(role: .cancel) { - TextState(String(localized: "common_close", bundle: PresentationResources.bundle)) - } - } message: { - TextState(String(localized: "composition_alert_badge_error_message", bundle: PresentationResources.bundle)) - } - } } private extension AppTab { diff --git a/Application/Presentation/Entry/Sources/Composition/CompositionView.swift b/Application/Presentation/Entry/Sources/Composition/CompositionView.swift index cda8e1f96..293842a47 100644 --- a/Application/Presentation/Entry/Sources/Composition/CompositionView.swift +++ b/Application/Presentation/Entry/Sources/Composition/CompositionView.swift @@ -26,7 +26,7 @@ struct CompositionView: View { ) { @Dependency(\.fetchSideBarWidthUseCase) var fetchSideBarWidthUseCase var state = CompositionFeature.State() - state.sideBarWidth = fetchSideBarWidthUseCase.execute().map { CGFloat($0) } + state.sideBar.width = fetchSideBarWidthUseCase.execute().map { CGFloat($0) } self._store = State(initialValue: Store(initialState: state) { CompositionFeature() }) @@ -47,21 +47,25 @@ struct CompositionView: View { let showsTabBar = !showsSideBar && usesCustomTabBar && verticalBarWidth == 0 && !store.isKeyboardVisible // 사이드바가 있는 창 오른쪽 세부 정보 사이드바, 설정 화면에서는 표시하지 않음 let showsDetailSideBar = showsSideBar - && (store.sideBarLocations[selectedTab] ?? selectedTab.sideBarLocation) != .settings + && (store.sideBar.locations[selectedTab] ?? selectedTab.sideBarLocation) != .settings let sideBarIdealWidth = isiOSAppOnMac ? 220 * AdaptiveSize.boardScale : 250 let tabBarInset = showsTabBar ? store.tabBarHeight : 0 SplitShell { - if showsSideBar && !store.isSideBarCollapsed { + if showsSideBar && !store.sideBar.isCollapsed { // 최소는 화살표와 아이콘만 보이는 폭, Mac 최대는 Orca 사이드바와 같은 폭 - TreeSideBar(selectedTab: $selectedTab, store: store) + TreeSideBar( + selectedTab: $selectedTab, + store: store.scope(state: \.sideBar, action: \.sideBar), + unreadPushCount: store.unreadPushCount.count + ) .resizablePane( - width: store.sideBarWidth, + width: store.sideBar.width, minimumWidth: isiOSAppOnMac ? 72 * AdaptiveSize.boardScale : 84, idealWidth: sideBarIdealWidth, maximumWidth: isiOSAppOnMac ? 500 * AdaptiveSize.boardScale : 320 ) { width in - store.send(.view(.sideBarResized(width))) + store.send(.sideBar(.resized(width))) } // 칸 자르기 밖이라 잘리지 않도록 바탕은 칸 바깥에서 아래쪽 안전 영역까지 채움 .background(Color.secondaryBackground, ignoresSafeAreaEdges: .bottom) @@ -100,7 +104,7 @@ struct CompositionView: View { windowEvent: windowEvent ) } - .badge(tab == .notification ? store.unreadPushCount : 0) + .badge(tab == .notification ? store.unreadPushCount.count : 0) } } } @@ -116,7 +120,7 @@ struct CompositionView: View { // 접은 사이드바는 화면 칸 제목 줄의 버튼으로 다시 폄 .environment( \.expandSideBar, - store.isSideBarCollapsed ? { store.send(.binding(.set(\.isSideBarCollapsed, false))) } : nil + store.sideBar.isCollapsed ? { store.send(.sideBar(.binding(.set(\.isCollapsed, false)))) } : nil ) .environment( \.presentSettings, @@ -125,24 +129,24 @@ struct CompositionView: View { // 닫힌 세부 정보 사이드바는 화면 칸 제목 줄의 버튼으로 엶 .environment( \.showDetailSideBar, - showsDetailSideBar && !store.isDetailSideBarPresented - ? { store.send(.binding(.set(\.isDetailSideBarPresented, true))) } : nil + showsDetailSideBar && !store.detailSideBar.isPresented + ? { store.send(.detailSideBar(.binding(.set(\.isPresented, true)))) } : nil ) - .environment(\.isDetailSideBarPresented, showsDetailSideBar && store.isDetailSideBarPresented) + .environment(\.isDetailSideBarPresented, showsDetailSideBar && store.detailSideBar.isPresented) .environment( \.setDetailSideBarPresented, - showsDetailSideBar ? { store.send(.binding(.set(\.isDetailSideBarPresented, $0))) } : nil + showsDetailSideBar ? { store.send(.detailSideBar(.binding(.set(\.isPresented, $0)))) } : nil ) } right: { // 칸 화면이 사이드바를 직접 그리면 창 사이드바는 표시하지 않음 if showsDetailSideBar - && store.isDetailSideBarPresented - && store.detailSideBarTargets[selectedTab] != .hosted { + && store.detailSideBar.isPresented + && store.detailSideBar.targets[selectedTab] != .hosted { DetailSideBar( - target: store.detailSideBarTargets[selectedTab], + target: store.detailSideBar.targets[selectedTab], windowEvent: windowEvent ) { - store.send(.binding(.set(\.isDetailSideBarPresented, false))) + store.send(.detailSideBar(.binding(.set(\.isPresented, false)))) } } } overlay: { @@ -183,7 +187,7 @@ struct CompositionView: View { selectedTab: $selectedTab, edge: store.verticalBarInsets.leading < store.verticalBarInsets.trailing ? .trailing : .leading, width: verticalBarWidth, - unreadPushCount: store.unreadPushCount + unreadPushCount: store.unreadPushCount.count ) } } @@ -195,7 +199,7 @@ struct CompositionView: View { splitMinimumWidth + sideBarIdealWidth <= proxy.size.width } action: { fitsSideBar in guard !isiOSAppOnMac else { return } - store.send(.binding(.set(\.isSideBarCollapsed, !fitsSideBar))) + store.send(.sideBar(.binding(.set(\.isCollapsed, !fitsSideBar)))) } .onGeometryChange(for: CGFloat.self) { proxy in proxy.windowControlsInset @@ -208,7 +212,7 @@ struct CompositionView: View { TabBar( selectedTab: $selectedTab, axis: .horizontal, - unreadPushCount: store.unreadPushCount + unreadPushCount: store.unreadPushCount.count ) .padding(.horizontal, 8) .padding(.top, 8) @@ -246,7 +250,11 @@ struct CompositionView: View { store.send(.binding(.set(\.isSettingsPresented, false))) } } - .prominentAlert(store, state: \.alert, action: \.alert) + .prominentAlert( + store.scope(state: \.unreadPushCount, action: \.unreadPushCount), + state: \.alert, + action: \.alert + ) // 이 화면 알림창도 화면 안쪽 알림창과 같은 버튼 모양으로 표시 .environment(\.usesDesktopLayout, showsSideBar) } diff --git a/Application/Presentation/Entry/Sources/Composition/DetailSideBarFeature.swift b/Application/Presentation/Entry/Sources/Composition/DetailSideBarFeature.swift new file mode 100644 index 000000000..72e3474cf --- /dev/null +++ b/Application/Presentation/Entry/Sources/Composition/DetailSideBarFeature.swift @@ -0,0 +1,59 @@ +// +// DetailSideBarFeature.swift +// Entry +// +// Created by opfic on 11/25/26. +// + +import Foundation +import PresentationShared + +@Reducer +struct DetailSideBarFeature { + @ObservableState + struct State: Equatable { + var isPresented = false + // 탭마다 대상을 고르는 화면, 대상이 없어도 나타난 순서대로 위치 + var selections: [AppTab: [Selection]] = [:] + + // 탭마다 지금 고른 대상, 대상을 고른 화면 중 가장 나중에 나타난 화면의 대상 + var targets: [AppTab: DetailSideBarTarget] { + selections.compactMapValues { $0.last { $0.target != nil }?.target } + } + } + + struct Selection: Equatable { + let owner: UUID + var target: DetailSideBarTarget? + } + + enum Action: BindableAction, Equatable { + case binding(BindingAction) + case targetChanged(AppTab, DetailSideBarTarget?, owner: UUID) + case ownerRemoved(AppTab, owner: UUID) + } + + var body: some ReducerOf { + BindingReducer() + Reduce { state, action in + switch action { + case .binding: + break + case .targetChanged(let tab, let target, let owner): + // 대상을 바꿔도 화면이 나타난 순서의 자리 유지 + var selections = state.selections[tab, default: []] + if let index = selections.firstIndex(where: { $0.owner == owner }) { + selections[index].target = target + } else { + selections.append(Selection(owner: owner, target: target)) + } + state.selections[tab] = selections + case .ownerRemoved(let tab, let owner): + // 사라지는 화면은 자기 자리만 지우고, 그 아래 화면이 고른 대상을 다시 표시 + state.selections[tab]?.removeAll { $0.owner == owner } + } + + return .none + } + } +} diff --git a/Application/Presentation/Entry/Sources/Composition/SideBarFeature.swift b/Application/Presentation/Entry/Sources/Composition/SideBarFeature.swift new file mode 100644 index 000000000..e237174ac --- /dev/null +++ b/Application/Presentation/Entry/Sources/Composition/SideBarFeature.swift @@ -0,0 +1,124 @@ +// +// SideBarFeature.swift +// Entry +// +// Created by opfic on 11/25/26. +// + +import Domain +import Foundation +import PresentationShared + +@Reducer +struct SideBarFeature { + enum Group: Hashable { + case todo + case developmentGoal + } + + @ObservableState + struct State: Equatable { + var isCollapsed = false + // 사용자가 끌어서 정한 폭, 정하지 않았으면 기본 폭 + var width: CGFloat? + var expandedGroups: Set = [] + var locations: [AppTab: SideBarLocation] = [:] + var requests: [AppTab: SideBarRequest] = [:] + // 칸에 작성 화면을 그린 탭, 덮는 화면처럼 닫기나 저장 버튼으로 닫기 전에는 사이드바로 이동하지 않음 + var paneEditingTabs: Set = [] + var content = SideBarContent() + } + + enum Action: BindableAction, Equatable { + case binding(BindingAction) + case locationChanged(AppTab, SideBarLocation) + case contentChanged(SideBarContent) + case paneEditingChanged(AppTab, Bool) + case resized(CGFloat) + case tapGroup(Group) + case tapItem(AppTab, SideBarRequest.Action) + case tapSettings + } + + @Dependency(\.uuid) var uuid + @Dependency(\.updateSideBarWidthUseCase) var updateSideBarWidthUseCase + + var body: some ReducerOf { + BindingReducer() + Reduce { state, action in + switch action { + case .binding: + break + case .locationChanged(let tab, let location): + state.locations[tab] = location + // 홈 카테고리 격자처럼 다른 경로로 하위 항목에 들어오면 그 묶음을 펼침 + switch location { + case .todoCategory: + state.expandedGroups.insert(.todo) + case .developmentGoal: + state.expandedGroups.insert(.developmentGoal) + case .home, .todoCategoryManagement, .search, .today, .notification, .profile, .settings: + break + } + case .contentChanged(let content): + state.content = content + case .paneEditingChanged(let tab, let isEditing): + if isEditing { + state.paneEditingTabs.insert(tab) + } else { + state.paneEditingTabs.remove(tab) + } + case .resized(let width): + state.width = width + return .run { [updateSideBarWidthUseCase] _ in + updateSideBarWidthUseCase.execute(Double(width)) + } + case .tapGroup(let group): + if state.expandedGroups.contains(group) { + state.expandedGroups.remove(group) + } else { + state.expandedGroups.insert(group) + } + case .tapItem(let tab, let action): + guard !state.paneEditingTabs.contains(tab) else { break } + state.requests[tab] = SideBarRequest(id: uuid(), action: action) + case .tapSettings: + break + } + + return .none + } + } +} + +extension DependencyValues { + var fetchSideBarWidthUseCase: FetchSideBarWidthUseCase { + get { self[FetchSideBarWidthUseCaseKey.self] } + set { self[FetchSideBarWidthUseCaseKey.self] = newValue } + } + + var updateSideBarWidthUseCase: UpdateSideBarWidthUseCase { + get { self[UpdateSideBarWidthUseCaseKey.self] } + set { self[UpdateSideBarWidthUseCaseKey.self] = newValue } + } +} + +private enum FetchSideBarWidthUseCaseKey: DependencyKey { + static var liveValue: FetchSideBarWidthUseCase { + preconditionFailure("FetchSideBarWidthUseCase must be provided.") + } + + static var testValue: FetchSideBarWidthUseCase { + liveValue + } +} + +private enum UpdateSideBarWidthUseCaseKey: DependencyKey { + static var liveValue: UpdateSideBarWidthUseCase { + preconditionFailure("UpdateSideBarWidthUseCase must be provided.") + } + + static var testValue: UpdateSideBarWidthUseCase { + liveValue + } +} diff --git a/Application/Presentation/Entry/Sources/Composition/TabScreen.swift b/Application/Presentation/Entry/Sources/Composition/TabScreen.swift index 26c343e4e..0305d8e0c 100644 --- a/Application/Presentation/Entry/Sources/Composition/TabScreen.swift +++ b/Application/Presentation/Entry/Sources/Composition/TabScreen.swift @@ -23,20 +23,20 @@ struct TabScreen: View { var body: some View { content .environment(\.isTabContentActive, isSelected) - .environment(\.sideBarRequest, store.sideBarRequests[tab]) + .environment(\.sideBarRequest, store.sideBar.requests[tab]) // 좁은 창에서도 고른 대상을 기록해 넓은 창으로 바뀌면 바로 세부 정보 사이드바에 표시 - .environment(\.selectDetailSideBarTarget) { store.send(.view(.detailSideBarTargetChanged(tab, $0, owner: $1))) } - .environment(\.removeDetailSideBarTarget) { store.send(.view(.detailSideBarOwnerRemoved(tab, owner: $0))) } + .environment(\.selectDetailSideBarTarget) { store.send(.detailSideBar(.targetChanged(tab, $0, owner: $1))) } + .environment(\.removeDetailSideBarTarget) { store.send(.detailSideBar(.ownerRemoved(tab, owner: $0))) } .onPreferenceChange(SideBarLocationPreferenceKey.self) { location in guard let location else { return } - store.send(.view(.sideBarLocationChanged(tab, location))) + store.send(.sideBar(.locationChanged(tab, location))) } .onPreferenceChange(PaneDetailEditingPreferenceKey.self) { isEditing in - store.send(.view(.paneEditingChanged(tab, isEditing))) + store.send(.sideBar(.paneEditingChanged(tab, isEditing))) } .onPreferenceChange(SideBarContentPreferenceKey.self) { content in guard let content else { return } - store.send(.view(.sideBarContentChanged(content))) + store.send(.sideBar(.contentChanged(content))) } .toolbarVisibility(isTabBarHidden ? .hidden : .visible, for: .tabBar) .background { TabBarVisibility(isHidden: isTabBarHidden, bottomInset: tabBarInset) } diff --git a/Application/Presentation/Entry/Sources/Composition/TreeSideBar.swift b/Application/Presentation/Entry/Sources/Composition/TreeSideBar.swift index 8c96ae419..78c123d8f 100644 --- a/Application/Presentation/Entry/Sources/Composition/TreeSideBar.swift +++ b/Application/Presentation/Entry/Sources/Composition/TreeSideBar.swift @@ -13,14 +13,15 @@ struct TreeSideBar: View { @Environment(\.isiOSAppOnMac) private var isiOSAppOnMac @Environment(\.paneWidth) private var paneWidth @Binding var selectedTab: AppTab - let store: StoreOf + let store: StoreOf + let unreadPushCount: Int var body: some View { - let location = store.sideBarLocations[selectedTab] ?? selectedTab.sideBarLocation - let expandedGroups = store.expandedSideBarGroups + let location = store.locations[selectedTab] ?? selectedTab.sideBarLocation + let expandedGroups = store.expandedGroups let isCompact = (paneWidth ?? .infinity) < SideBarRow.compactWidth let collapseButton = Button { - store.send(.binding(.set(\.isSideBarCollapsed, true))) + store.send(.binding(.set(\.isCollapsed, true))) } label: { Image(systemName: "sidebar.left") } @@ -51,7 +52,7 @@ struct TreeSideBar: View { title: Text(tab.title), symbolName: tab.symbolName, isSelected: location == tab.sideBarLocation, - badgeCount: tab == .notification ? store.unreadPushCount : 0 + badgeCount: tab == .notification ? unreadPushCount : 0 ) { open(tab.sideBarLocation) } @@ -61,10 +62,10 @@ struct TreeSideBar: View { symbolName: "flag.checkered", isExpanded: expandedGroups.contains(.developmentGoal) ) { - store.send(.view(.tapSideBarGroup(.developmentGoal)), animation: .easeInOut(duration: 0.2)) + store.send(.tapGroup(.developmentGoal), animation: .easeInOut(duration: 0.2)) } if expandedGroups.contains(.developmentGoal) { - ForEach(store.sideBarContent.developmentGoals) { goal in + ForEach(store.content.developmentGoals) { goal in SideBarRow( title: Text(goal.title), symbolName: "flag", @@ -81,7 +82,7 @@ struct TreeSideBar: View { isSelected: location == .todoCategoryManagement, isExpanded: expandedGroups.contains(.todo) ) { - store.send(.view(.tapSideBarGroup(.todo)), animation: .easeInOut(duration: 0.2)) + store.send(.tapGroup(.todo), animation: .easeInOut(duration: 0.2)) } .contextMenu { Button { @@ -104,7 +105,7 @@ struct TreeSideBar: View { } } if expandedGroups.contains(.todo) { - ForEach(store.sideBarContent.todoCategories) { item in + ForEach(store.content.todoCategories) { item in SideBarRow( title: Text(item.localizedName), symbolName: item.symbolName, @@ -134,7 +135,7 @@ struct TreeSideBar: View { isSelected: location == .settings ) { // 앱 화면과 분리한 설정 화면 표시 - store.send(.binding(.set(\.isSettingsPresented, true))) + store.send(.tapSettings) } } .padding(.horizontal, 8 * AdaptiveSize.boardScale) @@ -148,13 +149,13 @@ struct TreeSideBar: View { private func open(_ location: SideBarLocation) { selectedTab = location.tab - store.send(.view(.tapSideBarItem(location.tab, .open(location)))) + store.send(.tapItem(location.tab, .open(location))) } // Todo 우클릭 메뉴의 작성과 카테고리 관리는 홈 화면에서 표시 private func request(_ action: SideBarRequest.Action) { selectedTab = .home - store.send(.view(.tapSideBarItem(.home, action))) + store.send(.tapItem(.home, action)) } } diff --git a/Application/Presentation/Entry/Sources/Composition/UnreadPushCountFeature.swift b/Application/Presentation/Entry/Sources/Composition/UnreadPushCountFeature.swift new file mode 100644 index 000000000..61a73cfd0 --- /dev/null +++ b/Application/Presentation/Entry/Sources/Composition/UnreadPushCountFeature.swift @@ -0,0 +1,124 @@ +// +// UnreadPushCountFeature.swift +// Entry +// +// Created by opfic on 11/25/26. +// + +import Core +import Domain +import Foundation +import PresentationShared +import UserNotifications + +@Reducer +struct UnreadPushCountFeature { + private enum CancelID: Hashable { + case count + } + + @ObservableState + struct State: Equatable { + @Presents var alert: AlertState? + var count = 0 + } + + enum Action: Equatable { + case alert(PresentationAction) + case startObserving + case setCount(Int) + case setAlert + } + + @Dependency(\.observeUnreadPushCountUseCase) var observeUnreadPushCountUseCase + @Dependency(\.setApplicationBadgeCount) var setApplicationBadgeCount + + var body: some ReducerOf { + Reduce { state, action in + switch action { + case .alert: + break + case .startObserving: + return observeCountEffect() + case .setCount(let count): + state.count = count + return updateBadgeCountEffect(count) + case .setAlert: + state.alert = Self.alertState() + } + + return .none + } + .ifLet(\.$alert, action: \.alert) + } +} + +extension DependencyValues { + var observeUnreadPushCountUseCase: ObserveUnreadPushCountUseCase { + get { self[ObserveUnreadPushCountUseCaseKey.self] } + set { self[ObserveUnreadPushCountUseCaseKey.self] = newValue } + } + + var setApplicationBadgeCount: @Sendable (Int) async throws -> Void { + get { self[SetApplicationBadgeCountKey.self] } + set { self[SetApplicationBadgeCountKey.self] = newValue } + } +} + +private enum ObserveUnreadPushCountUseCaseKey: DependencyKey { + static var liveValue: ObserveUnreadPushCountUseCase { + preconditionFailure("ObserveUnreadPushCountUseCase must be provided.") + } + + static var testValue: ObserveUnreadPushCountUseCase { + liveValue + } +} + +private enum SetApplicationBadgeCountKey: DependencyKey { + static let liveValue: @Sendable (Int) async throws -> Void = { count in + try await UNUserNotificationCenter.current().setBadgeCount(count) + } + + static var testValue: @Sendable (Int) async throws -> Void { + liveValue + } +} + +private extension UnreadPushCountFeature { + func observeCountEffect() -> Effect { + .run { [observeUnreadPushCountUseCase] send in + do { + let publisher = try observeUnreadPushCountUseCase.observe() + for try await count in publisher.values { + await send(.setCount(count)) + } + } catch { + await send(.setAlert) + } + } + .cancellable(id: CancelID.count, cancelInFlight: true) + } + + func updateBadgeCountEffect(_ count: Int) -> Effect { + .run { [setApplicationBadgeCount] _ in + do { + try await setApplicationBadgeCount(count) + } catch { + Logger(category: "UnreadPushCountFeature").error("Failed to update application badge count", error: error) + } + } + } + + static func alertState() -> AlertState { + AlertState { + TextState(String(localized: "common_error_title", bundle: PresentationResources.bundle)) + } actions: { + ButtonState(role: .cancel) { + TextState(String(localized: "common_close", bundle: PresentationResources.bundle)) + } + } message: { + TextState(String(localized: "composition_alert_badge_error_message", bundle: PresentationResources.bundle)) + } + } +} diff --git a/Application/Presentation/Entry/Tests/Composition/CompositionFeatureTestSupport.swift b/Application/Presentation/Entry/Tests/Composition/CompositionFeatureTestSupport.swift new file mode 100644 index 000000000..243d27dd4 --- /dev/null +++ b/Application/Presentation/Entry/Tests/Composition/CompositionFeatureTestSupport.swift @@ -0,0 +1,180 @@ +// +// CompositionFeatureTestSupport.swift +// EntryTests +// +// Created by opfic on 11/25/26. +// + +import Combine +import PresentationShared +import Domain +import Foundation +@testable import Entry + +@MainActor +func makeStore( + unreadPushCountUseCase: ObserveUnreadPushCountUseCase = ObserveUnreadPushCountUseCaseSpy(), + trackAnalyticsEventUseCase: TrackAnalyticsEventUseCase = CompositionTrackAnalyticsEventUseCaseSpy(), + badgeCountSpy: CompositionApplicationBadgeCountSpy = CompositionApplicationBadgeCountSpy() +) -> TestStoreOf { + let store = TestStore(initialState: CompositionFeature.State()) { + CompositionFeature() + } withDependencies: { + $0.observeUnreadPushCountUseCase = unreadPushCountUseCase + $0.trackAnalyticsEventUseCase = trackAnalyticsEventUseCase + $0.setApplicationBadgeCount = { count in + try await badgeCountSpy.setBadgeCount(count) + } + } + store.exhaustivity = .off(showSkippedAssertions: false) + return store +} + +@MainActor +func makeUnreadPushCountStore( + unreadPushCountUseCase: ObserveUnreadPushCountUseCase = ObserveUnreadPushCountUseCaseSpy(), + badgeCountSpy: CompositionApplicationBadgeCountSpy = CompositionApplicationBadgeCountSpy() +) -> TestStoreOf { + let store = TestStore(initialState: UnreadPushCountFeature.State()) { + UnreadPushCountFeature() + } withDependencies: { + $0.observeUnreadPushCountUseCase = unreadPushCountUseCase + $0.setApplicationBadgeCount = { count in + try await badgeCountSpy.setBadgeCount(count) + } + } + store.exhaustivity = .off(showSkippedAssertions: false) + return store +} + +@MainActor +final class StateManagementReference { + struct State: Equatable { + var alert: AlertState? + var unreadPushCount = 0 + } + + enum Action { + case onAppear + case selectedTabChanged(AppTab) + case setUnreadPushCount(Int) + case setAlert + } + + enum Effect: Equatable { + case observeUnreadPushCount + case trackScreenView(String) + case updateBadgeCount(Int) + } + + private(set) var state = State() + private var isObservingUnreadPushCount = false + + func reduce(_ action: Action) -> [Effect] { + switch action { + case .onAppear: + if !isObservingUnreadPushCount { + isObservingUnreadPushCount = true + return [.observeUnreadPushCount] + } + case .selectedTabChanged(let tab): + if let screenName = tab.analyticsScreenName { + return [.trackScreenView(screenName)] + } + case .setUnreadPushCount(let count): + state.unreadPushCount = count + return [.updateBadgeCount(count)] + case .setAlert: + setAlert() + } + + return [] + } + + private func setAlert() { + state.alert = expectedCompositionErrorAlert() + } +} + +func expectedCompositionErrorAlert() -> AlertState { + AlertState { + TextState(String(localized: "common_error_title", bundle: PresentationResources.bundle)) + } actions: { + ButtonState(role: .cancel) { + TextState(String(localized: "common_close", bundle: PresentationResources.bundle)) + } + } message: { + TextState(String(localized: "composition_alert_badge_error_message", bundle: PresentationResources.bundle)) + } +} + +final class ObserveUnreadPushCountUseCaseSpy: ObserveUnreadPushCountUseCase { + var publisher: AnyPublisher + var error: Error? + private(set) var observeCallCount = 0 + + init( + publisher: AnyPublisher = Empty().eraseToAnyPublisher(), + error: Error? = nil + ) { + self.publisher = publisher + self.error = error + } + + func observe() throws -> AnyPublisher { + observeCallCount += 1 + + if let error { + throw error + } + + return publisher + } +} + +final class CompositionTrackAnalyticsEventUseCaseSpy: TrackAnalyticsEventUseCase { + private var events = [AnalyticsEvent]() + + var screenNames: [String] { + events.compactMap { event in + guard case .screenView(let screenName) = event else { return nil } + return screenName + } + } + + func execute(_ event: AnalyticsEvent) { + events.append(event) + } +} + +final class CompositionApplicationBadgeCountSpy: @unchecked Sendable { + private(set) var counts = [Int]() + var error: Error? + + func setBadgeCount(_ count: Int) async throws { + counts.append(count) + + if let error { + throw error + } + } +} + +enum CompositionTestError: Error { + case failure +} + +private extension AppTab { + var analyticsScreenName: String? { + switch self { + case .home: + return "home" + case .today: + return "today" + case .notification: + return nil + case .profile: + return "profile" + } + } +} diff --git a/Application/Presentation/Entry/Tests/Composition/CompositionFeatureTests.swift b/Application/Presentation/Entry/Tests/Composition/CompositionFeatureTests.swift index b693fcafb..020b74baf 100644 --- a/Application/Presentation/Entry/Tests/Composition/CompositionFeatureTests.swift +++ b/Application/Presentation/Entry/Tests/Composition/CompositionFeatureTests.swift @@ -5,9 +5,7 @@ // Created by opfic on 6/16/26. // -import Combine import PresentationShared -import Domain import Foundation import Testing @testable import Entry @@ -23,9 +21,12 @@ struct CompositionFeatureTests { let firstEffects = reference.reduce(.onAppear) let secondEffects = reference.reduce(.onAppear) await store.send(.view(.onAppear)) { - $0.isObservingUnreadPushCount = true + $0.hasAppeared = true } await store.send(.view(.onAppear)) + await waitUntil { + unreadPushCountUseCase.observeCallCount == 1 + } #expect(firstEffects == [.observeUnreadPushCount]) #expect(secondEffects.isEmpty) @@ -69,148 +70,6 @@ struct CompositionFeatureTests { #expect(trackAnalyticsEventUseCase.screenNames == ["home", "today", "profile"]) } - @Test("CompositionFeature는 기존 상태관리처럼 unread count를 갱신하고 badge 갱신을 요청한다") - func CompositionFeature는_기존_상태관리처럼_unread_count를_갱신하고_badge_갱신을_요청한다() async { - let reference = StateManagementReference() - let badgeCountSpy = CompositionApplicationBadgeCountSpy() - let store = makeStore(badgeCountSpy: badgeCountSpy) - - let effects = reference.reduce(.setUnreadPushCount(7)) - await store.send(.store(.setUnreadPushCount(7))) { - $0.unreadPushCount = reference.state.unreadPushCount - } - await waitUntil { - badgeCountSpy.counts == [7] - } - - #expect(reference.state.unreadPushCount == 7) - #expect(effects == [.updateBadgeCount(7)]) - #expect(badgeCountSpy.counts == [7]) - } - - @Test("CompositionFeature는 기존 상태관리처럼 alert 표시 여부와 문구를 함께 갱신한다") - func CompositionFeature는_기존_상태관리처럼_alert_state를_갱신한다() async { - let reference = StateManagementReference() - let store = makeStore() - - let presentEffects = reference.reduce(.setAlert) - await store.send(.store(.setAlert)) { - $0.alert = reference.state.alert - } - - await store.send(.alert(.dismiss)) { - $0.alert = nil - } - - #expect(presentEffects.isEmpty) - #expect(reference.state.alert == expectedCompositionErrorAlert()) - } - - @Test("CompositionFeature는 기존 상태관리처럼 unread count 관찰 시작 실패 시 alert를 표시한다") - func CompositionFeature는_기존_상태관리처럼_unread_count_관찰_시작_실패_시_alert를_표시한다() async { - let reference = StateManagementReference() - let unreadPushCountUseCase = ObserveUnreadPushCountUseCaseSpy(error: CompositionTestError.failure) - let store = makeStore(unreadPushCountUseCase: unreadPushCountUseCase) - - _ = reference.reduce(.onAppear) - _ = reference.reduce(.setAlert) - await store.send(.view(.onAppear)) { - $0.isObservingUnreadPushCount = true - } - await store.receive(.store(.setAlert)) { - $0.alert = reference.state.alert - } - } - - @Test("CompositionFeature는 다른 경로로 하위 항목에 들어오면 그 묶음을 펼치고 묶음을 접어도 위치를 유지한다") - func CompositionFeature는_다른_경로로_하위_항목에_들어오면_그_묶음을_펼치고_묶음을_접어도_위치를_유지한다() async { - let store = makeStore() - - await store.send(.view(.sideBarLocationChanged(.home, .todoCategory("issue")))) { - $0.sideBarLocations[.home] = .todoCategory("issue") - $0.expandedSideBarGroups = [.todo] - } - await store.send(.view(.tapSideBarGroup(.todo))) { - $0.expandedSideBarGroups = [] - } - #expect(store.state.sideBarLocations[.home] == .todoCategory("issue")) - await store.send(.view(.sideBarLocationChanged(.home, .developmentGoal("goal")))) { - $0.sideBarLocations[.home] = .developmentGoal("goal") - $0.expandedSideBarGroups = [.developmentGoal] - } - } - - @Test("CompositionFeature는 사라지는 화면이 다른 화면이 고른 세부 정보 사이드바 대상을 지우지 않게 한다") - func CompositionFeature는_사라지는_화면이_다른_화면이_고른_세부_정보_사이드바_대상을_지우지_않게_한다() async { - let store = makeStore() - let goal = UUID() - let category = UUID() - - await store.send(.view(.detailSideBarTargetChanged(.home, .hosted, owner: goal))) - await store.send(.view(.detailSideBarTargetChanged(.home, .hosted, owner: category))) - await store.send(.view(.detailSideBarOwnerRemoved(.home, owner: goal))) - - #expect(store.state.detailSideBarTargets[.home] == .hosted) - - await store.send(.view(.detailSideBarOwnerRemoved(.home, owner: category))) - - #expect(store.state.detailSideBarTargets[.home] == nil) - } - - @Test("CompositionFeature는 위 화면이 사라지면 아래 화면이 고른 세부 정보 사이드바 대상을 다시 표시한다") - func CompositionFeature는_위_화면이_사라지면_아래_화면이_고른_세부_정보_사이드바_대상을_다시_표시한다() async { - let store = makeStore() - let list = UUID() - let editor = UUID() - - await store.send(.view(.detailSideBarTargetChanged(.home, .todo(id: "todo", isEditable: true), owner: list))) - await store.send(.view(.detailSideBarTargetChanged(.home, .hosted, owner: editor))) - await store.send(.view(.detailSideBarTargetChanged(.home, .todo(id: "other", isEditable: true), owner: list))) - - #expect(store.state.detailSideBarTargets[.home] == .hosted) - - await store.send(.view(.detailSideBarOwnerRemoved(.home, owner: editor))) - - #expect(store.state.detailSideBarTargets[.home] == .todo(id: "other", isEditable: true)) - } - - @Test("CompositionFeature는 먼저 나타난 화면이 나중에 대상을 골라도 나중에 나타난 화면의 대상을 유지한다") - func CompositionFeature는_먼저_나타난_화면이_나중에_대상을_골라도_나중에_나타난_화면의_대상을_유지한다() async { - let store = makeStore() - let list = UUID() - let editor = UUID() - - await store.send(.view(.detailSideBarTargetChanged(.home, nil, owner: list))) - await store.send(.view(.detailSideBarTargetChanged(.home, .hosted, owner: editor))) - await store.send(.view(.detailSideBarTargetChanged(.home, .todo(id: "todo", isEditable: true), owner: list))) - - #expect(store.state.detailSideBarTargets[.home] == .hosted) - - await store.send(.view(.detailSideBarOwnerRemoved(.home, owner: editor))) - - #expect(store.state.detailSideBarTargets[.home] == .todo(id: "todo", isEditable: true)) - } - - @Test("CompositionFeature는 칸에 작성 화면을 그린 탭의 사이드바 이동 요청을 무시한다") - func CompositionFeature는_칸에_작성_화면을_그린_탭의_사이드바_이동_요청을_무시한다() async { - let store = TestStore(initialState: CompositionFeature.State()) { - CompositionFeature() - } withDependencies: { - $0.uuid = .incrementing - } - store.exhaustivity = .off(showSkippedAssertions: false) - - await store.send(.view(.paneEditingChanged(.home, true))) - await store.send(.view(.tapSideBarItem(.home, .open(.home)))) - - #expect(store.state.sideBarRequests[.home] == nil) - - await store.send(.view(.paneEditingChanged(.home, false))) - await store.send(.view(.tapSideBarItem(.home, .open(.home)))) - - #expect(store.state.sideBarRequests[.home]?.action == .open(.home)) - } - @Test("CompositionFeature는 화면 회전 때 오는 높이 0인 키보드 표시 알림을 무시한다") func CompositionFeature는_화면_회전_때_오는_높이_0인_키보드_표시_알림을_무시한다() async { let store = makeStore() @@ -226,186 +85,4 @@ struct CompositionFeatureTests { $0.isKeyboardVisible = false } } - - @Test("CompositionFeature는 unread count 관찰 값을 기존 상태관리의 setUnreadPushCount 상태 변화로 반영한다") - func CompositionFeature는_unread_count_관찰_값을_기존_상태관리의_setUnreadPushCount_상태_변화로_반영한다() async { - let reference = StateManagementReference() - let subject = PassthroughSubject() - let unreadPushCountUseCase = ObserveUnreadPushCountUseCaseSpy(publisher: subject.eraseToAnyPublisher()) - let badgeCountSpy = CompositionApplicationBadgeCountSpy() - let store = makeStore( - unreadPushCountUseCase: unreadPushCountUseCase, - badgeCountSpy: badgeCountSpy - ) - - _ = reference.reduce(.onAppear) - await store.send(.view(.onAppear)) { - $0.isObservingUnreadPushCount = true - } - - let effects = reference.reduce(.setUnreadPushCount(3)) - subject.send(3) - await store.receive(.store(.setUnreadPushCount(3))) { - $0.unreadPushCount = reference.state.unreadPushCount - } - await waitUntil { - badgeCountSpy.counts == [3] - } - - #expect(reference.state.unreadPushCount == 3) - #expect(effects == [.updateBadgeCount(3)]) - #expect(badgeCountSpy.counts == [3]) - subject.send(completion: .finished) - } -} - -@MainActor -private func makeStore( - unreadPushCountUseCase: ObserveUnreadPushCountUseCase = ObserveUnreadPushCountUseCaseSpy(), - trackAnalyticsEventUseCase: TrackAnalyticsEventUseCase = CompositionTrackAnalyticsEventUseCaseSpy(), - badgeCountSpy: CompositionApplicationBadgeCountSpy = CompositionApplicationBadgeCountSpy() -) -> TestStoreOf { - let store = TestStore(initialState: CompositionFeature.State()) { - CompositionFeature() - } withDependencies: { - $0.observeUnreadPushCountUseCase = unreadPushCountUseCase - $0.trackAnalyticsEventUseCase = trackAnalyticsEventUseCase - $0.setApplicationBadgeCount = { count in - try await badgeCountSpy.setBadgeCount(count) - } - } - store.exhaustivity = .off(showSkippedAssertions: false) - return store -} - -@MainActor -private final class StateManagementReference { - struct State: Equatable { - var alert: AlertState? - var unreadPushCount = 0 - } - - enum Action { - case onAppear - case selectedTabChanged(AppTab) - case setUnreadPushCount(Int) - case setAlert - } - - enum Effect: Equatable { - case observeUnreadPushCount - case trackScreenView(String) - case updateBadgeCount(Int) - } - - private(set) var state = State() - private var isObservingUnreadPushCount = false - - func reduce(_ action: Action) -> [Effect] { - switch action { - case .onAppear: - if !isObservingUnreadPushCount { - isObservingUnreadPushCount = true - return [.observeUnreadPushCount] - } - case .selectedTabChanged(let tab): - if let screenName = tab.analyticsScreenName { - return [.trackScreenView(screenName)] - } - case .setUnreadPushCount(let count): - state.unreadPushCount = count - return [.updateBadgeCount(count)] - case .setAlert: - setAlert() - } - - return [] - } - - private func setAlert() { - state.alert = expectedCompositionErrorAlert() - } -} - -private func expectedCompositionErrorAlert() -> AlertState { - AlertState { - TextState(String(localized: "common_error_title", bundle: PresentationResources.bundle)) - } actions: { - ButtonState(role: .cancel) { - TextState(String(localized: "common_close", bundle: PresentationResources.bundle)) - } - } message: { - TextState(String(localized: "composition_alert_badge_error_message", bundle: PresentationResources.bundle)) - } -} - -private final class ObserveUnreadPushCountUseCaseSpy: ObserveUnreadPushCountUseCase { - var publisher: AnyPublisher - var error: Error? - private(set) var observeCallCount = 0 - - init( - publisher: AnyPublisher = Empty().eraseToAnyPublisher(), - error: Error? = nil - ) { - self.publisher = publisher - self.error = error - } - - func observe() throws -> AnyPublisher { - observeCallCount += 1 - - if let error { - throw error - } - - return publisher - } -} - -private final class CompositionTrackAnalyticsEventUseCaseSpy: TrackAnalyticsEventUseCase { - private var events = [AnalyticsEvent]() - - var screenNames: [String] { - events.compactMap { event in - guard case .screenView(let screenName) = event else { return nil } - return screenName - } - } - - func execute(_ event: AnalyticsEvent) { - events.append(event) - } -} - -private final class CompositionApplicationBadgeCountSpy: @unchecked Sendable { - private(set) var counts = [Int]() - var error: Error? - - func setBadgeCount(_ count: Int) async throws { - counts.append(count) - - if let error { - throw error - } - } -} - -private enum CompositionTestError: Error { - case failure -} - -private extension AppTab { - var analyticsScreenName: String? { - switch self { - case .home: - return "home" - case .today: - return "today" - case .notification: - return nil - case .profile: - return "profile" - } - } } diff --git a/Application/Presentation/Entry/Tests/Composition/DetailSideBarFeatureTests.swift b/Application/Presentation/Entry/Tests/Composition/DetailSideBarFeatureTests.swift new file mode 100644 index 000000000..e5b39dfb0 --- /dev/null +++ b/Application/Presentation/Entry/Tests/Composition/DetailSideBarFeatureTests.swift @@ -0,0 +1,74 @@ +// +// DetailSideBarFeatureTests.swift +// EntryTests +// +// Created by opfic on 11/25/26. +// + +import Foundation +import PresentationShared +import Testing +@testable import Entry + +@MainActor +struct DetailSideBarFeatureTests { + @Test("DetailSideBarFeature는 사라지는 화면이 다른 화면이 고른 세부 정보 사이드바 대상을 지우지 않게 한다") + func DetailSideBarFeature는_사라지는_화면이_다른_화면이_고른_세부_정보_사이드바_대상을_지우지_않게_한다() async { + let store = TestStore(initialState: DetailSideBarFeature.State()) { + DetailSideBarFeature() + } + store.exhaustivity = .off(showSkippedAssertions: false) + let goal = UUID() + let category = UUID() + + await store.send(.targetChanged(.home, .hosted, owner: goal)) + await store.send(.targetChanged(.home, .hosted, owner: category)) + await store.send(.ownerRemoved(.home, owner: goal)) + + #expect(store.state.targets[.home] == .hosted) + + await store.send(.ownerRemoved(.home, owner: category)) + + #expect(store.state.targets[.home] == nil) + } + + @Test("DetailSideBarFeature는 위 화면이 사라지면 아래 화면이 고른 세부 정보 사이드바 대상을 다시 표시한다") + func DetailSideBarFeature는_위_화면이_사라지면_아래_화면이_고른_세부_정보_사이드바_대상을_다시_표시한다() async { + let store = TestStore(initialState: DetailSideBarFeature.State()) { + DetailSideBarFeature() + } + store.exhaustivity = .off(showSkippedAssertions: false) + let list = UUID() + let editor = UUID() + + await store.send(.targetChanged(.home, .todo(id: "todo", isEditable: true), owner: list)) + await store.send(.targetChanged(.home, .hosted, owner: editor)) + await store.send(.targetChanged(.home, .todo(id: "other", isEditable: true), owner: list)) + + #expect(store.state.targets[.home] == .hosted) + + await store.send(.ownerRemoved(.home, owner: editor)) + + #expect(store.state.targets[.home] == .todo(id: "other", isEditable: true)) + } + + @Test("DetailSideBarFeature는 먼저 나타난 화면이 나중에 대상을 골라도 나중에 나타난 화면의 대상을 유지한다") + func DetailSideBarFeature는_먼저_나타난_화면이_나중에_대상을_골라도_나중에_나타난_화면의_대상을_유지한다() async { + let store = TestStore(initialState: DetailSideBarFeature.State()) { + DetailSideBarFeature() + } + store.exhaustivity = .off(showSkippedAssertions: false) + let list = UUID() + let editor = UUID() + + await store.send(.targetChanged(.home, nil, owner: list)) + await store.send(.targetChanged(.home, .hosted, owner: editor)) + await store.send(.targetChanged(.home, .todo(id: "todo", isEditable: true), owner: list)) + + #expect(store.state.targets[.home] == .hosted) + + await store.send(.ownerRemoved(.home, owner: editor)) + + #expect(store.state.targets[.home] == .todo(id: "todo", isEditable: true)) + } +} diff --git a/Application/Presentation/Entry/Tests/Composition/SideBarFeatureTests.swift b/Application/Presentation/Entry/Tests/Composition/SideBarFeatureTests.swift new file mode 100644 index 000000000..b236fb983 --- /dev/null +++ b/Application/Presentation/Entry/Tests/Composition/SideBarFeatureTests.swift @@ -0,0 +1,54 @@ +// +// SideBarFeatureTests.swift +// EntryTests +// +// Created by opfic on 11/25/26. +// + +import Foundation +import PresentationShared +import Testing +@testable import Entry + +@MainActor +struct SideBarFeatureTests { + @Test("SideBarFeature는 다른 경로로 하위 항목에 들어오면 그 묶음을 펼치고 묶음을 접어도 위치를 유지한다") + func SideBarFeature는_다른_경로로_하위_항목에_들어오면_그_묶음을_펼치고_묶음을_접어도_위치를_유지한다() async { + let store = TestStore(initialState: SideBarFeature.State()) { + SideBarFeature() + } + + await store.send(.locationChanged(.home, .todoCategory("issue"))) { + $0.locations[.home] = .todoCategory("issue") + $0.expandedGroups = [.todo] + } + await store.send(.tapGroup(.todo)) { + $0.expandedGroups = [] + } + #expect(store.state.locations[.home] == .todoCategory("issue")) + await store.send(.locationChanged(.home, .developmentGoal("goal"))) { + $0.locations[.home] = .developmentGoal("goal") + $0.expandedGroups = [.developmentGoal] + } + } + + @Test("SideBarFeature는 칸에 작성 화면을 그린 탭의 사이드바 이동 요청을 무시한다") + func SideBarFeature는_칸에_작성_화면을_그린_탭의_사이드바_이동_요청을_무시한다() async { + let store = TestStore(initialState: SideBarFeature.State()) { + SideBarFeature() + } withDependencies: { + $0.uuid = .incrementing + } + store.exhaustivity = .off(showSkippedAssertions: false) + + await store.send(.paneEditingChanged(.home, true)) + await store.send(.tapItem(.home, .open(.home))) + + #expect(store.state.requests[.home] == nil) + + await store.send(.paneEditingChanged(.home, false)) + await store.send(.tapItem(.home, .open(.home))) + + #expect(store.state.requests[.home]?.action == .open(.home)) + } +} diff --git a/Application/Presentation/Entry/Tests/Composition/UnreadPushCountFeatureTests.swift b/Application/Presentation/Entry/Tests/Composition/UnreadPushCountFeatureTests.swift new file mode 100644 index 000000000..4d99b69a5 --- /dev/null +++ b/Application/Presentation/Entry/Tests/Composition/UnreadPushCountFeatureTests.swift @@ -0,0 +1,94 @@ +// +// UnreadPushCountFeatureTests.swift +// EntryTests +// +// Created by opfic on 11/25/26. +// + +import Combine +import PresentationShared +import Testing +@testable import Entry + +@MainActor +struct UnreadPushCountFeatureTests { + @Test("UnreadPushCountFeature는 기존 상태관리처럼 unread count를 갱신하고 badge 갱신을 요청한다") + func UnreadPushCountFeature는_기존_상태관리처럼_unread_count를_갱신하고_badge_갱신을_요청한다() async { + let reference = StateManagementReference() + let badgeCountSpy = CompositionApplicationBadgeCountSpy() + let store = makeUnreadPushCountStore(badgeCountSpy: badgeCountSpy) + + let effects = reference.reduce(.setUnreadPushCount(7)) + await store.send(.setCount(7)) { + $0.count = reference.state.unreadPushCount + } + await waitUntil { + badgeCountSpy.counts == [7] + } + + #expect(reference.state.unreadPushCount == 7) + #expect(effects == [.updateBadgeCount(7)]) + #expect(badgeCountSpy.counts == [7]) + } + + @Test("UnreadPushCountFeature는 기존 상태관리처럼 alert 표시 여부와 문구를 함께 갱신한다") + func UnreadPushCountFeature는_기존_상태관리처럼_alert_state를_갱신한다() async { + let reference = StateManagementReference() + let store = makeUnreadPushCountStore() + + let presentEffects = reference.reduce(.setAlert) + await store.send(.setAlert) { + $0.alert = reference.state.alert + } + + await store.send(.alert(.dismiss)) { + $0.alert = nil + } + + #expect(presentEffects.isEmpty) + #expect(reference.state.alert == expectedCompositionErrorAlert()) + } + + @Test("UnreadPushCountFeature는 기존 상태관리처럼 unread count 관찰 시작 실패 시 alert를 표시한다") + func UnreadPushCountFeature는_기존_상태관리처럼_unread_count_관찰_시작_실패_시_alert를_표시한다() async { + let reference = StateManagementReference() + let unreadPushCountUseCase = ObserveUnreadPushCountUseCaseSpy(error: CompositionTestError.failure) + let store = makeUnreadPushCountStore(unreadPushCountUseCase: unreadPushCountUseCase) + + _ = reference.reduce(.onAppear) + _ = reference.reduce(.setAlert) + await store.send(.startObserving) + await store.receive(.setAlert) { + $0.alert = reference.state.alert + } + } + + @Test("UnreadPushCountFeature는 unread count 관찰 값을 기존 상태관리의 setUnreadPushCount 상태 변화로 반영한다") + func UnreadPushCountFeature는_unread_count_관찰_값을_기존_상태관리의_setUnreadPushCount_상태_변화로_반영한다() async { + let reference = StateManagementReference() + let subject = PassthroughSubject() + let unreadPushCountUseCase = ObserveUnreadPushCountUseCaseSpy(publisher: subject.eraseToAnyPublisher()) + let badgeCountSpy = CompositionApplicationBadgeCountSpy() + let store = makeUnreadPushCountStore( + unreadPushCountUseCase: unreadPushCountUseCase, + badgeCountSpy: badgeCountSpy + ) + + _ = reference.reduce(.onAppear) + await store.send(.startObserving) + + let effects = reference.reduce(.setUnreadPushCount(3)) + subject.send(3) + await store.receive(.setCount(3)) { + $0.count = reference.state.unreadPushCount + } + await waitUntil { + badgeCountSpy.counts == [3] + } + + #expect(reference.state.unreadPushCount == 3) + #expect(effects == [.updateBadgeCount(3)]) + #expect(badgeCountSpy.counts == [3]) + subject.send(completion: .finished) + } +} From c60b26b5c509b4b51ef3219de30b606d73da6a49 Mon Sep 17 00:00:00 2001 From: opficdev Date: Thu, 26 Nov 2026 15:02:27 +0900 Subject: [PATCH 5/8] =?UTF-8?q?refactor:=20=EB=A3=A8=ED=8A=B8=20Feature?= =?UTF-8?q?=EA=B0=80=20=EB=A1=9C=EA=B7=B8=EC=9D=B8=ED=95=9C=20=EB=8F=99?= =?UTF-8?q?=EC=95=88=EC=97=90=EB=A7=8C=20CompositionFeature=EB=A5=BC=20?= =?UTF-8?q?=EB=A7=8C=EB=93=A4=EA=B3=A0=20=EA=B3=A0=EB=A5=B8=20=ED=83=AD?= =?UTF-8?q?=EC=9D=84=20CompositionFeature=EA=B0=80=20=EB=B3=B4=EA=B4=80?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../Composition/CompositionFeature.swift | 32 +++++++------ .../Sources/Composition/CompositionView.swift | 29 ++++-------- .../Sources/Composition/TreeSideBar.swift | 25 +++------- .../Entry/Sources/Root/Feature.swift | 47 +++++++++++-------- .../Entry/Sources/Root/RootView.swift | 13 ++--- .../Entry/Sources/Routing/AppTab.swift | 15 ------ .../Composition/CompositionFeatureTests.swift | 46 ++++++++++++------ .../Entry/Tests/Root/FeatureTestSupport.swift | 38 +++++++++++---- 8 files changed, 124 insertions(+), 121 deletions(-) diff --git a/Application/Presentation/Entry/Sources/Composition/CompositionFeature.swift b/Application/Presentation/Entry/Sources/Composition/CompositionFeature.swift index ba112b46b..1ef1e315e 100644 --- a/Application/Presentation/Entry/Sources/Composition/CompositionFeature.swift +++ b/Application/Presentation/Entry/Sources/Composition/CompositionFeature.swift @@ -23,7 +23,7 @@ struct CompositionFeature { // 탭 안 화면이 직접 그린 하단 탭 바 뒤로 들어가지 않도록 비울 높이 var tabBarHeight = CGFloat.zero var readableContentWidth = CGFloat.infinity - var hasAppeared = false + var selectedTab = AppTab.home var openedTabs: Set = [] // 앱 화면과 분리해 창 전체에 표시하는 Mac 설정 화면 var isSettingsPresented = false @@ -41,17 +41,13 @@ struct CompositionFeature { enum Action: BindableAction, Equatable { case binding(BindingAction) - case view(ViewAction) + case start + case selectTab(AppTab) case sideBar(SideBarFeature.Action) case detailSideBar(DetailSideBarFeature.Action) case unreadPushCount(UnreadPushCountFeature.Action) case store(StoreAction) - enum ViewAction: Equatable { - case onAppear - case selectedTabChanged(AppTab) - } - enum StoreAction: Equatable { case keyboardChanged(KeyboardEvent) } @@ -79,16 +75,17 @@ struct CompositionFeature { switch action { case .binding: break - case .view(.onAppear): - guard !state.hasAppeared else { break } - state.hasAppeared = true + case .start: + state.openedTabs.insert(state.selectedTab) return .merge( .send(.unreadPushCount(.startObserving)), - observeKeyboardEffect() + observeKeyboardEffect(), + trackScreenViewEffect(state.selectedTab) ) - case .view(.selectedTabChanged(let tab)): - state.openedTabs.insert(tab) - return trackScreenViewEffect(tab) + case .selectTab(let tab): + return selectTabEffect(tab, state: &state) + case .sideBar(.tapItem(let tab, _)): + return selectTabEffect(tab, state: &state) case .sideBar(.tapSettings): state.isSettingsPresented = true case .sideBar, .detailSideBar, .unreadPushCount: @@ -140,6 +137,13 @@ private extension CompositionFeature { .cancellable(id: CancelID.keyboard, cancelInFlight: true) } + func selectTabEffect(_ tab: AppTab, state: inout State) -> Effect { + guard state.selectedTab != tab else { return .none } + state.selectedTab = tab + state.openedTabs.insert(tab) + return trackScreenViewEffect(tab) + } + func trackScreenViewEffect(_ tab: AppTab) -> Effect { guard let screenName = tab.analyticsScreenName else { return .none } return .run { [trackAnalyticsEventUseCase] _ in diff --git a/Application/Presentation/Entry/Sources/Composition/CompositionView.swift b/Application/Presentation/Entry/Sources/Composition/CompositionView.swift index 293842a47..19715ddc3 100644 --- a/Application/Presentation/Entry/Sources/Composition/CompositionView.swift +++ b/Application/Presentation/Entry/Sources/Composition/CompositionView.swift @@ -14,27 +14,18 @@ struct CompositionView: View { @Environment(\.horizontalSizeClass) private var horizontalSizeClass @Environment(\.isiOSAppOnMac) private var isiOSAppOnMac @Environment(\.deviceType) private var deviceType - @Binding var selectedTab: AppTab - @State private var store: StoreOf + @Bindable private var store: StoreOf private let windowEvent: TodoEditorWindowEvent // 목록 칸과 상세 칸이 함께 들어가는 화면 영역 폭 private let splitMinimumWidth = CGFloat(800) - init( - windowEvent: TodoEditorWindowEvent, - selectedTab: Binding - ) { - @Dependency(\.fetchSideBarWidthUseCase) var fetchSideBarWidthUseCase - var state = CompositionFeature.State() - state.sideBar.width = fetchSideBarWidthUseCase.execute().map { CGFloat($0) } - self._store = State(initialValue: Store(initialState: state) { - CompositionFeature() - }) - self._selectedTab = selectedTab + init(store: StoreOf, windowEvent: TodoEditorWindowEvent) { + self.store = store self.windowEvent = windowEvent } var body: some View { + let selectedTab = store.selectedTab let showsSideBar = isiOSAppOnMac || deviceType != .duo && horizontalSizeClass == .regular let tabContentInset = horizontalSizeClass == .compact ? store.windowControlsInset : 0 let readableContentWidth = showsSideBar ? store.readableContentWidth : .infinity @@ -55,8 +46,8 @@ struct CompositionView: View { if showsSideBar && !store.sideBar.isCollapsed { // 최소는 화살표와 아이콘만 보이는 폭, Mac 최대는 Orca 사이드바와 같은 폭 TreeSideBar( - selectedTab: $selectedTab, store: store.scope(state: \.sideBar, action: \.sideBar), + selectedTab: selectedTab, unreadPushCount: store.unreadPushCount.count ) .resizablePane( @@ -92,7 +83,7 @@ struct CompositionView: View { } } } else { - TabView(selection: $selectedTab) { + TabView(selection: $store.selectedTab.sending(\.selectTab)) { ForEach(AppTab.allCases, id: \.self) { tab in Tab(tab.title, systemImage: tab.symbolName, value: tab) { TabScreen( @@ -184,7 +175,7 @@ struct CompositionView: View { .overlay { if 0 < verticalBarWidth { DuoTabBar( - selectedTab: $selectedTab, + selectedTab: $store.selectedTab.sending(\.selectTab), edge: store.verticalBarInsets.leading < store.verticalBarInsets.trailing ? .trailing : .leading, width: verticalBarWidth, unreadPushCount: store.unreadPushCount.count @@ -210,7 +201,7 @@ struct CompositionView: View { .safeAreaInset(edge: .bottom, spacing: 0) { if showsTabBar { TabBar( - selectedTab: $selectedTab, + selectedTab: $store.selectedTab.sending(\.selectTab), axis: .horizontal, unreadPushCount: store.unreadPushCount.count ) @@ -240,10 +231,6 @@ struct CompositionView: View { } action: { insets in store.send(.binding(.set(\.verticalBarInsets, insets))) } - .onAppear { store.send(.view(.onAppear)) } - .onChange(of: selectedTab, initial: true) { _, tab in - store.send(.view(.selectedTabChanged(tab))) - } // iPad 창이 좁아져 사이드바가 없어지면 진행 중인 요청과 알림창이 끝난 뒤 창 전체 설정 화면을 닫고 보던 화면으로 돌아감 .onChange(of: showsSideBar || store.isSettingsBusy) { _, keepsSettings in if !keepsSettings { diff --git a/Application/Presentation/Entry/Sources/Composition/TreeSideBar.swift b/Application/Presentation/Entry/Sources/Composition/TreeSideBar.swift index 78c123d8f..61685a95f 100644 --- a/Application/Presentation/Entry/Sources/Composition/TreeSideBar.swift +++ b/Application/Presentation/Entry/Sources/Composition/TreeSideBar.swift @@ -12,8 +12,8 @@ import PresentationShared struct TreeSideBar: View { @Environment(\.isiOSAppOnMac) private var isiOSAppOnMac @Environment(\.paneWidth) private var paneWidth - @Binding var selectedTab: AppTab let store: StoreOf + let selectedTab: AppTab let unreadPushCount: Int var body: some View { @@ -54,7 +54,7 @@ struct TreeSideBar: View { isSelected: location == tab.sideBarLocation, badgeCount: tab == .notification ? unreadPushCount : 0 ) { - open(tab.sideBarLocation) + store.send(.tapItem(tab, .open(tab.sideBarLocation))) } } SideBarRow( @@ -72,7 +72,7 @@ struct TreeSideBar: View { isChild: true, isSelected: location == .developmentGoal(goal.id) ) { - open(.developmentGoal(goal.id)) + store.send(.tapItem(.home, .open(.developmentGoal(goal.id)))) } } } @@ -86,7 +86,7 @@ struct TreeSideBar: View { } .contextMenu { Button { - request(.createTodo) + store.send(.tapItem(.home, .createTodo)) } label: { Label { Text("sidebar_new_todo", bundle: PresentationResources.bundle) @@ -95,7 +95,7 @@ struct TreeSideBar: View { } } Button { - request(.manageTodoCategory) + store.send(.tapItem(.home, .manageTodoCategory)) } label: { Label { Text("todo_category_manage", bundle: PresentationResources.bundle) @@ -113,7 +113,7 @@ struct TreeSideBar: View { isChild: true, isSelected: location == .todoCategory(item.id) ) { - open(.todoCategory(item.id)) + store.send(.tapItem(.home, .open(.todoCategory(item.id)))) } } } @@ -127,7 +127,7 @@ struct TreeSideBar: View { symbolName: AppTab.profile.symbolName, isSelected: location == .profile ) { - open(.profile) + store.send(.tapItem(.profile, .open(.profile))) } SideBarRow( title: Text("nav_settings", bundle: PresentationResources.bundle), @@ -146,17 +146,6 @@ struct TreeSideBar: View { // 칸이 기본 폭보다 좁아도 잘라 내지 않고 지금 폭에 맞춰 배치 .frame(width: paneWidth) } - - private func open(_ location: SideBarLocation) { - selectedTab = location.tab - store.send(.tapItem(location.tab, .open(location))) - } - - // Todo 우클릭 메뉴의 작성과 카테고리 관리는 홈 화면에서 표시 - private func request(_ action: SideBarRequest.Action) { - selectedTab = .home - store.send(.tapItem(.home, action)) - } } // Mac과 iPad가 같은 모양으로 쓰는 트리 사이드바 항목 diff --git a/Application/Presentation/Entry/Sources/Root/Feature.swift b/Application/Presentation/Entry/Sources/Root/Feature.swift index 102c6b9aa..1a34aecf5 100644 --- a/Application/Presentation/Entry/Sources/Root/Feature.swift +++ b/Application/Presentation/Entry/Sources/Root/Feature.swift @@ -28,7 +28,8 @@ struct Feature { var isNetworkConnected = true var signIn: Bool? var theme: SystemTheme = .automatic - var selectedTab = AppTab.home + // 로그인한 동안에만 있는 앱 화면 상태 + var composition: CompositionFeature.State? var widgetRoute: WidgetRoute? var isObservingNetworkConnectivity = false var isObservingSession = false @@ -41,10 +42,10 @@ struct Feature { var id: String { todoId } } - enum Action: BindableAction, Equatable { + enum Action: Equatable { case alert(PresentationAction) case appUpdateCheckCompleted(Bool) - case binding(BindingAction) + case composition(CompositionFeature.Action) case sheet(PresentationAction) case onAppear case presentTodoDetail(String) @@ -70,9 +71,9 @@ struct Feature { @Dependency(\.appStoreURL) var appStoreURL @Dependency(\.openURL) var openURL @Dependency(\.setApplicationBadgeCount) var setApplicationBadgeCount + @Dependency(\.fetchSideBarWidthUseCase) var fetchSideBarWidthUseCase var body: some ReducerOf { - BindingReducer() Reduce { state, action in switch action { case .alert(.presented(.tapUpdateButton)): @@ -83,7 +84,7 @@ struct Feature { guard isRequired else { break } state.isAppUpdateRequired = true state.alert = Self.appUpdateAlertState() - case .binding: + case .composition: break case .sheet(.dismiss), .sheet(.presented(.tapCloseButton)): state.sheet = nil @@ -121,7 +122,12 @@ struct Feature { // 로그인 여부를 확인하기 전이면 경로를 보관했다가 로그인 확인 뒤 적용 state.widgetRoute = route guard state.signIn == true else { break } - Self.applyWidgetRoute(route, to: &state) + switch route { + case .tab(let tab): + return .send(.composition(.selectTab(tab))) + case .todayTodo(let id): + state.sheet = .init(todoId: id) + } case .networkStatusChanged(let isConnected): let wasConnected = state.isNetworkConnected state.isNetworkConnected = isConnected @@ -134,12 +140,21 @@ struct Feature { let wasSignedIn = state.signIn == true state.signIn = result if result { - if !wasSignedIn, let route = state.widgetRoute { - Self.applyWidgetRoute(route, to: &state) - } else { - state.selectedTab = .home + guard !wasSignedIn else { return .send(.composition(.selectTab(.home))) } + var composition = CompositionFeature.State() + composition.sideBar.width = fetchSideBarWidthUseCase.execute().map { CGFloat($0) } + switch state.widgetRoute { + case .tab(let tab): + composition.selectedTab = tab + case .todayTodo(let id): + state.sheet = .init(todoId: id) + case nil: + break } + state.composition = composition + return .send(.composition(.start)) } else { + state.composition = nil state.widgetRoute = nil return .merge( trackLoginScreenEffect(), @@ -150,20 +165,14 @@ struct Feature { return .none } + .ifLet(\.composition, action: \.composition) { + CompositionFeature() + } .ifLet(\.$alert, action: \.alert) .ifLet(\.$sheet, action: \.sheet) { SheetFeature() } } - - private static func applyWidgetRoute(_ route: WidgetRoute, to state: inout State) { - switch route { - case .tab(let tab): - state.selectedTab = tab - case .todayTodo(let id): - state.sheet = .init(todoId: id) - } - } } private struct SheetFeature: Reducer { diff --git a/Application/Presentation/Entry/Sources/Root/RootView.swift b/Application/Presentation/Entry/Sources/Root/RootView.swift index 22d1672f1..bd0ae654e 100644 --- a/Application/Presentation/Entry/Sources/Root/RootView.swift +++ b/Application/Presentation/Entry/Sources/Root/RootView.swift @@ -34,15 +34,10 @@ public struct RootView: View { public var body: some View { ZStack { Color.background.ignoresSafeArea() - if let signIn = store.signIn { - if signIn { - CompositionView( - windowEvent: windowEvent, - selectedTab: $store.selectedTab - ) - } else { - LoginView() - } + if let compositionStore = store.scope(state: \.composition, action: \.composition) { + CompositionView(store: compositionStore, windowEvent: windowEvent) + } else if store.signIn == false { + LoginView() } } .preferredColorScheme(store.theme.colorScheme) diff --git a/Application/Presentation/Entry/Sources/Routing/AppTab.swift b/Application/Presentation/Entry/Sources/Routing/AppTab.swift index e0aff2c5c..a911aa3c4 100644 --- a/Application/Presentation/Entry/Sources/Routing/AppTab.swift +++ b/Application/Presentation/Entry/Sources/Routing/AppTab.swift @@ -54,18 +54,3 @@ public enum AppTab: Hashable, CaseIterable { } } } - -extension SideBarLocation { - var tab: AppTab { - switch self { - case .home, .todoCategory, .todoCategoryManagement, .developmentGoal, .search: - .home - case .today: - .today - case .notification: - .notification - case .profile, .settings: - .profile - } - } -} diff --git a/Application/Presentation/Entry/Tests/Composition/CompositionFeatureTests.swift b/Application/Presentation/Entry/Tests/Composition/CompositionFeatureTests.swift index 020b74baf..66e60568a 100644 --- a/Application/Presentation/Entry/Tests/Composition/CompositionFeatureTests.swift +++ b/Application/Presentation/Entry/Tests/Composition/CompositionFeatureTests.swift @@ -12,24 +12,16 @@ import Testing @MainActor struct CompositionFeatureTests { - @Test("CompositionFeature는 기존 상태관리처럼 최초 onAppear에서만 unread count 관찰을 시작한다") - func CompositionFeature는_기존_상태관리처럼_최초_onAppear에서만_unread_count_관찰을_시작한다() async { - let reference = StateManagementReference() + @Test("CompositionFeature는 시작하면 unread count 관찰을 시작한다") + func CompositionFeature는_시작하면_unread_count_관찰을_시작한다() async { let unreadPushCountUseCase = ObserveUnreadPushCountUseCaseSpy() let store = makeStore(unreadPushCountUseCase: unreadPushCountUseCase) - let firstEffects = reference.reduce(.onAppear) - let secondEffects = reference.reduce(.onAppear) - await store.send(.view(.onAppear)) { - $0.hasAppeared = true - } - await store.send(.view(.onAppear)) + await store.send(.start) await waitUntil { unreadPushCountUseCase.observeCallCount == 1 } - #expect(firstEffects == [.observeUnreadPushCount]) - #expect(secondEffects.isEmpty) #expect(unreadPushCountUseCase.observeCallCount == 1) } @@ -40,21 +32,33 @@ struct CompositionFeatureTests { let store = makeStore(trackAnalyticsEventUseCase: trackAnalyticsEventUseCase) let expectedEffects = [ + reference.reduce(.onAppear), reference.reduce(.selectedTabChanged(.home)), reference.reduce(.selectedTabChanged(.today)), reference.reduce(.selectedTabChanged(.notification)), reference.reduce(.selectedTabChanged(.profile)) ] - await store.send(.view(.selectedTabChanged(.home))) { + await store.send(.start) { $0.openedTabs = [.home] } - await store.send(.view(.selectedTabChanged(.today))) { + await waitUntil { + trackAnalyticsEventUseCase.screenNames == ["home"] + } + // 이미 고른 탭을 다시 고르면 다시 추적하지 않음 + await store.send(.selectTab(.home)) + await store.send(.selectTab(.today)) { + $0.selectedTab = .today $0.openedTabs = [.home, .today] } - await store.send(.view(.selectedTabChanged(.notification))) { + await waitUntil { + trackAnalyticsEventUseCase.screenNames == ["home", "today"] + } + await store.send(.selectTab(.notification)) { + $0.selectedTab = .notification $0.openedTabs = [.home, .today, .notification] } - await store.send(.view(.selectedTabChanged(.profile))) { + await store.send(.selectTab(.profile)) { + $0.selectedTab = .profile $0.openedTabs = [.home, .today, .notification, .profile] } await waitUntil { @@ -62,6 +66,7 @@ struct CompositionFeatureTests { } #expect(expectedEffects == [ + [.observeUnreadPushCount], [.trackScreenView("home")], [.trackScreenView("today")], [], @@ -70,6 +75,17 @@ struct CompositionFeatureTests { #expect(trackAnalyticsEventUseCase.screenNames == ["home", "today", "profile"]) } + @Test("CompositionFeature는 사이드바 항목을 고르면 작성 화면을 그린 탭이라도 그 탭을 선택한다") + func CompositionFeature는_사이드바_항목을_고르면_작성_화면을_그린_탭이라도_그_탭을_선택한다() async { + let store = makeStore() + + await store.send(.sideBar(.paneEditingChanged(.profile, true))) + await store.send(.sideBar(.tapItem(.profile, .open(.profile)))) + + #expect(store.state.selectedTab == .profile) + #expect(store.state.sideBar.requests[.profile] == nil) + } + @Test("CompositionFeature는 화면 회전 때 오는 높이 0인 키보드 표시 알림을 무시한다") func CompositionFeature는_화면_회전_때_오는_높이_0인_키보드_표시_알림을_무시한다() async { let store = makeStore() diff --git a/Application/Presentation/Entry/Tests/Root/FeatureTestSupport.swift b/Application/Presentation/Entry/Tests/Root/FeatureTestSupport.swift index bc2082b53..8cc57e2fa 100644 --- a/Application/Presentation/Entry/Tests/Root/FeatureTestSupport.swift +++ b/Application/Presentation/Entry/Tests/Root/FeatureTestSupport.swift @@ -37,7 +37,7 @@ struct RootStateSnapshot: Equatable { let isNetworkConnected: Bool let signIn: Bool? let theme: SystemTheme - let selectedTab: AppTab + let selectedTab: AppTab? } @MainActor @@ -51,7 +51,7 @@ struct RootStoreTestAdapter: RootStateDriving { isNetworkConnected: store.state.isNetworkConnected, signIn: store.state.signIn, theme: store.state.theme, - selectedTab: store.state.selectedTab + selectedTab: store.state.composition?.selectedTab ) } var sheetTodoId: String? { store.state.sheet?.todoId } @@ -87,6 +87,8 @@ struct RootStoreTestAdapter: RootStateDriving { $0.setApplicationBadgeCount = { count in try await badgeCountSpy.setBadgeCount(count) } + $0.fetchSideBarWidthUseCase = RootFetchSideBarWidthUseCaseStub() + $0.observeUnreadPushCountUseCase = ObserveUnreadPushCountUseCaseSpy() } store.exhaustivity = .off(showSkippedAssertions: false) } @@ -114,6 +116,7 @@ struct RootStoreTestAdapter: RootStateDriving { func didLogined(_ signIn: Bool) async { await store.send(.didLogined(signIn)) + await drainReceivedActions() } func presentTodoDetail(_ todoId: String) async { @@ -125,11 +128,12 @@ struct RootStoreTestAdapter: RootStateDriving { } func selectTab(_ tab: AppTab) async { - await store.send(.binding(.set(\.selectedTab, tab))) + await store.send(.composition(.selectTab(tab))) } func openWidgetRoute(_ route: WidgetRoute) async { await store.send(.openWidgetRoute(route)) + await drainReceivedActions() } func tapUpdateButton() async { @@ -161,7 +165,7 @@ func verifyNetworkDisconnectedAlert(adapter: some RootStateDriving) async { isNetworkConnected: false, signIn: nil, theme: .automatic, - selectedTab: .home + selectedTab: nil ) ) } @@ -179,7 +183,7 @@ func verifySetAlert(adapter: some RootStateDriving) async { isNetworkConnected: false, signIn: nil, theme: .automatic, - selectedTab: .home + selectedTab: nil ) ) } @@ -190,7 +194,6 @@ func verifyThemeUpdate(adapter: some RootStateDriving) async { #expect(adapter.snapshot.theme == .dark) #expect(adapter.snapshot.alertTitle == nil) - #expect(adapter.snapshot.selectedTab == .home) } @MainActor @@ -204,7 +207,7 @@ func verifyDidLoginedFalse( } #expect(adapter.snapshot.signIn == false) - #expect(adapter.snapshot.selectedTab == .home) + #expect(adapter.snapshot.selectedTab == nil) #expect(trackAnalyticsEventUseCaseSpy.screenNames == ["login"]) } @@ -213,12 +216,21 @@ func verifyDidLoginedTrue( adapter: some RootStateDriving, trackAnalyticsEventUseCaseSpy: RootTrackAnalyticsEventUseCaseSpy ) async { + await adapter.didLogined(true) + + #expect(adapter.snapshot.signIn == true) + #expect(adapter.snapshot.selectedTab == .home) + await waitUntil { + trackAnalyticsEventUseCaseSpy.screenNames == ["home"] + } + #expect(trackAnalyticsEventUseCaseSpy.screenNames == ["home"]) + await adapter.selectTab(.today) + await adapter.didLogined(false) await adapter.didLogined(true) #expect(adapter.snapshot.signIn == true) #expect(adapter.snapshot.selectedTab == .home) - #expect(trackAnalyticsEventUseCaseSpy.screenNames.isEmpty) } @MainActor @@ -247,7 +259,7 @@ func verifyObservedInitialValues(adapter: some RootStateDriving) async { isNetworkConnected: false, signIn: false, theme: .dark, - selectedTab: .home + selectedTab: nil ) ) } @@ -264,7 +276,7 @@ func verifyTodoDetailSheetPresentation(adapter: some RootStateDriving) async { @MainActor func verifyWidgetRouteOpensWhenSignedIn(adapter: some RootStateDriving) async { await adapter.openWidgetRoute(.tab(.today)) - #expect(adapter.snapshot.selectedTab == .home) + #expect(adapter.snapshot.selectedTab == nil) #expect(adapter.widgetRoute == .tab(.today)) await adapter.didLogined(true) @@ -353,6 +365,12 @@ actor RootCheckAppUpdateUseCaseSpy: CheckAppUpdateUseCase { } } +struct RootFetchSideBarWidthUseCaseStub: FetchSideBarWidthUseCase { + func execute() -> Double? { + nil + } +} + actor RootOpenURLSpy { private var urls = [URL]() From c13a4e091b57f9250f5ea18e14fa7d4e86f73f61 Mon Sep 17 00:00:00 2001 From: opficdev Date: Thu, 26 Nov 2026 15:05:44 +0900 Subject: [PATCH 6/8] =?UTF-8?q?fix:=20iPad=20=EC=B0=BD=20=ED=8F=AD?= =?UTF-8?q?=EC=9D=B4=20=EB=B0=94=EB=80=8C=EC=96=B4=EB=8F=84=20=EB=B3=B4?= =?UTF-8?q?=EB=8D=98=20=EC=84=A4=EC=A0=95=20=ED=99=94=EB=A9=B4=EC=9D=B4=20?= =?UTF-8?q?=EC=9D=B4=EC=96=B4=EC=A7=80=EB=8F=84=EB=A1=9D=20SettingsFeature?= =?UTF-8?q?=EA=B0=80=20=EC=97=B4=EB=A6=B0=20=EC=84=A4=EC=A0=95=20=ED=99=94?= =?UTF-8?q?=EB=A9=B4=EA=B3=BC=20=EA=B3=84=EC=A0=95=20=EC=83=81=ED=83=9C?= =?UTF-8?q?=EB=A5=BC=20=EB=B3=B4=EA=B4=80?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../Composition/CompositionFeature.swift | 140 +++++++++++----- .../Sources/Composition/CompositionView.swift | 69 ++++---- .../Sources/Composition/SideBarFeature.swift | 2 +- .../Entry/Sources/Composition/TabScreen.swift | 4 +- .../Sources/Composition/TreeSideBar.swift | 3 +- .../CompositionFeatureTestSupport.swift | 13 ++ .../Composition/CompositionFeatureTests.swift | 153 ++++++++++++++++++ .../Sources/Common/SideBarNavigation.swift | 1 - .../Extension/EnvironmentValues+.swift | 10 -- .../Sources/Profile/ProfileView.swift | 96 ++++++----- .../Sources/Settings/AccountFeature.swift | 22 ++- .../Sources/Settings/AccountView.swift | 10 +- .../Settings/DesktopSettingsView.swift | 39 ++--- .../Sources/Settings/SettingsFeature.swift | 50 +++++- .../Tests/Settings/AccountFeatureTests.swift | 14 +- .../Tests/Settings/SettingsFeatureTests.swift | 42 +++++ 16 files changed, 482 insertions(+), 186 deletions(-) diff --git a/Application/Presentation/Entry/Sources/Composition/CompositionFeature.swift b/Application/Presentation/Entry/Sources/Composition/CompositionFeature.swift index 1ef1e315e..3e409b063 100644 --- a/Application/Presentation/Entry/Sources/Composition/CompositionFeature.swift +++ b/Application/Presentation/Entry/Sources/Composition/CompositionFeature.swift @@ -9,6 +9,7 @@ import Combine import PresentationShared import Domain import Foundation +import ProfileTab import SwiftUI @Reducer @@ -25,13 +26,21 @@ struct CompositionFeature { var readableContentWidth = CGFloat.infinity var selectedTab = AppTab.home var openedTabs: Set = [] - // 앱 화면과 분리해 창 전체에 표시하는 Mac 설정 화면 + // 창에 사이드바가 있는지 여부, 배치가 아닌 설정 규칙에만 사용 + var showsSideBar = false + // 앱 화면과 분리해 창 전체에 표시하는 설정 화면, 좁아진 창에서는 프로필 화면에 이어서 표시 var isSettingsPresented = false - // 창 전체 설정 화면에서 로그아웃, 회원 탈퇴나 그 알림창이 끝나지 않은 상태 - var isSettingsBusy = false var sideBar = SideBarFeature.State() var detailSideBar = DetailSideBarFeature.State() var unreadPushCount = UnreadPushCountFeature.State() + // 창 폭이 바뀌어도 보던 항목과 진행 중인 로그아웃, 회원 탈퇴를 이어 가게 화면보다 위에서 보관 + var settings = SettingsFeature.State() + + // 계정 화면이 열려 있는지 여부, 창 전체 설정은 목차에서 고른 항목이고 좁은 창은 쌓은 설정의 맨 위 화면 + var isAccountOpen: Bool { + let isDetailOpen = showsSideBar ? settings.screen != nil : settings.screen == .detail + return isDetailOpen && settings.selectedRoute == .account + } } enum KeyboardEvent: Equatable { @@ -43,11 +52,17 @@ struct CompositionFeature { case binding(BindingAction) case start case selectTab(AppTab) + case view(ViewAction) case sideBar(SideBarFeature.Action) case detailSideBar(DetailSideBarFeature.Action) case unreadPushCount(UnreadPushCountFeature.Action) + case settings(SettingsFeature.Action) case store(StoreAction) + enum ViewAction: Equatable { + case sideBarVisibilityChanged(Bool) + } + enum StoreAction: Equatable { case keyboardChanged(KeyboardEvent) } @@ -61,44 +76,91 @@ struct CompositionFeature { @Dependency(\.keyboardEvents) var keyboardEvents var body: some ReducerOf { - Scope(state: \.sideBar, action: \.sideBar) { - SideBarFeature() - } - Scope(state: \.detailSideBar, action: \.detailSideBar) { - DetailSideBarFeature() - } - Scope(state: \.unreadPushCount, action: \.unreadPushCount) { - UnreadPushCountFeature() + CombineReducers { + Scope(state: \.sideBar, action: \.sideBar) { + SideBarFeature() + } + Scope(state: \.detailSideBar, action: \.detailSideBar) { + DetailSideBarFeature() + } + Scope(state: \.unreadPushCount, action: \.unreadPushCount) { + UnreadPushCountFeature() + } + Scope(state: \.settings, action: \.settings) { + SettingsFeature() + } + BindingReducer() + Reduce { state, action in + switch action { + case .binding: + break + case .start: + state.openedTabs.insert(state.selectedTab) + return .merge( + .send(.unreadPushCount(.startObserving)), + observeKeyboardEffect(), + trackScreenViewEffect(state.selectedTab) + ) + case .selectTab(let tab): + // 좁아진 창에 설정이 이어져 있어도 탭이나 위젯에서 고른 탭을 표시 + if !state.showsSideBar { + state.isSettingsPresented = false + } + return selectTabEffect(tab, state: &state) + case .sideBar(.tapItem(let tab, _)): + return selectTabEffect(tab, state: &state) + case .sideBar(.tapSettings): + return .send(.settings(.open)) + case .sideBar, .detailSideBar, .unreadPushCount: + break + case .settings(.open): + state.isSettingsPresented = true + case .settings(.close): + state.isSettingsPresented = false + case .settings(.binding(\.screen)): + guard state.settings.screen == nil, state.isSettingsPresented else { break } + // 좁아진 창에서 설정을 닫으면 설정 아래에 있던 프로필 화면 표시 + state.isSettingsPresented = false + return selectTabEffect(.profile, state: &state) + case .settings: + break + case .view(.sideBarVisibilityChanged(true)): + state.showsSideBar = true + // 사이드바가 있는 창으로 바뀌면 보던 설정을 창 전체 설정 화면에 이어서 표시 + guard state.settings.screen != nil else { break } + // 다른 탭을 보던 중이면 쌓아 연 설정만 내리고 창 전체 설정 화면은 띄우지 않음 + guard state.isSettingsPresented || state.selectedTab == .profile else { + state.settings.screen = nil + break + } + state.isSettingsPresented = true + // 창 전체 설정 화면은 고른 항목을 표시하므로 다시 좁아지면 그 항목 화면을 이어서 쌓음 + // 앱 정보는 좁은 창에 항목 화면이 없어 설정 목록 유지 + if state.settings.selectedRoute != .information { + state.settings.screen = .detail + } + case .view(.sideBarVisibilityChanged(false)): + state.showsSideBar = false + // 좁아진 창에서 설정을 이어서 표시하는 프로필 화면 유지 + if state.isSettingsPresented { + state.openedTabs.insert(.profile) + } + case .store(.keyboardChanged(.willShow(let height))): + // 화면을 돌리면 키보드 없이도 높이 0인 키보드 표시 알림이 와서 무시 + guard 0 < height else { break } + state.isKeyboardVisible = true + case .store(.keyboardChanged(.willHide)): + state.isKeyboardVisible = false + } + + return .none + } } - BindingReducer() - Reduce { state, action in - switch action { - case .binding: - break - case .start: - state.openedTabs.insert(state.selectedTab) - return .merge( - .send(.unreadPushCount(.startObserving)), - observeKeyboardEffect(), - trackScreenViewEffect(state.selectedTab) - ) - case .selectTab(let tab): - return selectTabEffect(tab, state: &state) - case .sideBar(.tapItem(let tab, _)): - return selectTabEffect(tab, state: &state) - case .sideBar(.tapSettings): - state.isSettingsPresented = true - case .sideBar, .detailSideBar, .unreadPushCount: - break - case .store(.keyboardChanged(.willShow(let height))): - // 화면을 돌리면 키보드 없이도 높이 0인 키보드 표시 알림이 와서 무시 - guard 0 < height else { break } - state.isKeyboardVisible = true - case .store(.keyboardChanged(.willHide)): - state.isKeyboardVisible = false + .onChange(of: \.isAccountOpen) { _, isOpen in + Reduce { _, _ in + // 창 폭이 바뀌어 화면을 옮겨 그릴 때는 다시 조회하지 않고 계정 화면에 들어올 때만 조회 + isOpen ? .send(.settings(.account(.open))) : .none } - - return .none } } } diff --git a/Application/Presentation/Entry/Sources/Composition/CompositionView.swift b/Application/Presentation/Entry/Sources/Composition/CompositionView.swift index 19715ddc3..3d2febfd6 100644 --- a/Application/Presentation/Entry/Sources/Composition/CompositionView.swift +++ b/Application/Presentation/Entry/Sources/Composition/CompositionView.swift @@ -36,11 +36,10 @@ struct CompositionView: View { ? max(store.verticalBarInsets.leading, store.verticalBarInsets.trailing) : 0 // 시스템 탭 바처럼 키보드가 올라오면 키보드 뒤로 사라짐 let showsTabBar = !showsSideBar && usesCustomTabBar && verticalBarWidth == 0 && !store.isKeyboardVisible - // 사이드바가 있는 창 오른쪽 세부 정보 사이드바, 설정 화면에서는 표시하지 않음 - let showsDetailSideBar = showsSideBar - && (store.sideBar.locations[selectedTab] ?? selectedTab.sideBarLocation) != .settings let sideBarIdealWidth = isiOSAppOnMac ? 220 * AdaptiveSize.boardScale : 250 let tabBarInset = showsTabBar ? store.tabBarHeight : 0 + // 사이드바가 있는 창에서 연 설정은 좁아지면 고른 탭을 바꾸지 않고 프로필 화면에 이어서 표시 + let visibleTab = !showsSideBar && store.isSettingsPresented ? AppTab.profile : selectedTab SplitShell { if showsSideBar && !store.sideBar.isCollapsed { @@ -69,17 +68,18 @@ struct CompositionView: View { // 탭 전환 애니메이션 없이 한 번 연 탭을 유지하고 선택한 탭만 표시 // 사이드바 하위 항목은 홈 화면이 알려 주므로 홈은 처음부터 생성 ForEach(AppTab.allCases, id: \.self) { tab in - if store.openedTabs.contains(tab) || selectedTab == tab || tab == .home { + if store.openedTabs.contains(tab) || selectedTab == tab || visibleTab == tab || tab == .home { TabScreen( store: store, tab: tab, - isSelected: selectedTab == tab, + isSelected: selectedTab == tab && visibleTab == tab, + isVisible: visibleTab == tab, isTabBarHidden: isSystemTabBarHidden, tabBarInset: tabBarInset, windowEvent: windowEvent ) - .opacity(selectedTab == tab ? 1 : 0) - .allowsHitTesting(selectedTab == tab) + .opacity(visibleTab == tab ? 1 : 0) + .allowsHitTesting(visibleTab == tab) } } } else { @@ -89,7 +89,8 @@ struct CompositionView: View { TabScreen( store: store, tab: tab, - isSelected: selectedTab == tab, + isSelected: selectedTab == tab && visibleTab == tab, + isVisible: visibleTab == tab, isTabBarHidden: isSystemTabBarHidden, tabBarInset: tabBarInset, windowEvent: windowEvent @@ -113,24 +114,20 @@ struct CompositionView: View { \.expandSideBar, store.sideBar.isCollapsed ? { store.send(.sideBar(.binding(.set(\.isCollapsed, false)))) } : nil ) - .environment( - \.presentSettings, - showsSideBar ? { store.send(.binding(.set(\.isSettingsPresented, true))) } : nil - ) // 닫힌 세부 정보 사이드바는 화면 칸 제목 줄의 버튼으로 엶 .environment( \.showDetailSideBar, - showsDetailSideBar && !store.detailSideBar.isPresented + showsSideBar && !store.detailSideBar.isPresented ? { store.send(.detailSideBar(.binding(.set(\.isPresented, true)))) } : nil ) - .environment(\.isDetailSideBarPresented, showsDetailSideBar && store.detailSideBar.isPresented) + .environment(\.isDetailSideBarPresented, showsSideBar && store.detailSideBar.isPresented) .environment( \.setDetailSideBarPresented, - showsDetailSideBar ? { store.send(.detailSideBar(.binding(.set(\.isPresented, $0)))) } : nil + showsSideBar ? { store.send(.detailSideBar(.binding(.set(\.isPresented, $0)))) } : nil ) } right: { // 칸 화면이 사이드바를 직접 그리면 창 사이드바는 표시하지 않음 - if showsDetailSideBar + if showsSideBar && store.detailSideBar.isPresented && store.detailSideBar.targets[selectedTab] != .hosted { DetailSideBar( @@ -142,15 +139,12 @@ struct CompositionView: View { } } overlay: { // 사이드바가 있는 창의 설정은 앱 화면을 덮어 창 전체에 표시하고 닫으면 보던 화면으로 돌아감 - // 창이 좁아져도 진행 중인 로그아웃, 회원 탈퇴나 그 알림창이 끝날 때까지 표시 - if store.isSettingsPresented && (showsSideBar || store.isSettingsBusy) { - DesktopSettingsView { isBusy in - store.send(.binding(.set(\.isSettingsBusy, isBusy))) - } onClose: { - store.send(.binding(.set(\.isSettingsPresented, false))) - } - .environment(\.readableContentWidth, readableContentWidth) - .background(Color.background) + if showsSideBar + && store.settings.screen != nil + && (store.isSettingsPresented || selectedTab == .profile) { + DesktopSettingsView(store: store.scope(state: \.settings, action: \.settings)) + .environment(\.readableContentWidth, readableContentWidth) + .background(Color.background) } } // 세로로 펼친 Duo는 세로 막대가 없어 iPhone과 같은 화면 구성 @@ -201,7 +195,10 @@ struct CompositionView: View { .safeAreaInset(edge: .bottom, spacing: 0) { if showsTabBar { TabBar( - selectedTab: $store.selectedTab.sending(\.selectTab), + selectedTab: Binding( + get: { visibleTab }, + set: { store.send(.selectTab($0)) } + ), axis: .horizontal, unreadPushCount: store.unreadPushCount.count ) @@ -231,17 +228,27 @@ struct CompositionView: View { } action: { insets in store.send(.binding(.set(\.verticalBarInsets, insets))) } - // iPad 창이 좁아져 사이드바가 없어지면 진행 중인 요청과 알림창이 끝난 뒤 창 전체 설정 화면을 닫고 보던 화면으로 돌아감 - .onChange(of: showsSideBar || store.isSettingsBusy) { _, keepsSettings in - if !keepsSettings { - store.send(.binding(.set(\.isSettingsPresented, false))) - } + .onChange(of: showsSideBar, initial: true) { _, showsSideBar in + store.send(.view(.sideBarVisibilityChanged(showsSideBar))) } .prominentAlert( store.scope(state: \.unreadPushCount, action: \.unreadPushCount), state: \.alert, action: \.alert ) + // 창 폭이 바뀌어 계정 화면을 옮겨 그려도 떠 있는 알림창이 닫히지 않게 이 화면에서 표시 + .background { + Color.clear + .prominentAlert( + store.scope(state: \.settings.account, action: \.settings.account), + state: \.alert, + action: \.alert + ) + .environment( + \.isTabContentActive, + store.isAccountOpen && (store.isSettingsPresented || selectedTab == .profile) + ) + } // 이 화면 알림창도 화면 안쪽 알림창과 같은 버튼 모양으로 표시 .environment(\.usesDesktopLayout, showsSideBar) } diff --git a/Application/Presentation/Entry/Sources/Composition/SideBarFeature.swift b/Application/Presentation/Entry/Sources/Composition/SideBarFeature.swift index e237174ac..628221465 100644 --- a/Application/Presentation/Entry/Sources/Composition/SideBarFeature.swift +++ b/Application/Presentation/Entry/Sources/Composition/SideBarFeature.swift @@ -57,7 +57,7 @@ struct SideBarFeature { state.expandedGroups.insert(.todo) case .developmentGoal: state.expandedGroups.insert(.developmentGoal) - case .home, .todoCategoryManagement, .search, .today, .notification, .profile, .settings: + case .home, .todoCategoryManagement, .search, .today, .notification, .profile: break } case .contentChanged(let content): diff --git a/Application/Presentation/Entry/Sources/Composition/TabScreen.swift b/Application/Presentation/Entry/Sources/Composition/TabScreen.swift index 0305d8e0c..e304ad0de 100644 --- a/Application/Presentation/Entry/Sources/Composition/TabScreen.swift +++ b/Application/Presentation/Entry/Sources/Composition/TabScreen.swift @@ -16,13 +16,14 @@ struct TabScreen: View { let store: StoreOf let tab: AppTab let isSelected: Bool + let isVisible: Bool let isTabBarHidden: Bool let tabBarInset: CGFloat let windowEvent: TodoEditorWindowEvent var body: some View { content - .environment(\.isTabContentActive, isSelected) + .environment(\.isTabContentActive, isVisible) .environment(\.sideBarRequest, store.sideBar.requests[tab]) // 좁은 창에서도 고른 대상을 기록해 넓은 창으로 바뀌면 바로 세부 정보 사이드바에 표시 .environment(\.selectDetailSideBarTarget) { store.send(.detailSideBar(.targetChanged(tab, $0, owner: $1))) } @@ -60,6 +61,7 @@ struct TabScreen: View { case .profile: ProfileView( isSelected: isSelected, + settingsStore: store.scope(state: \.settings, action: \.settings), windowEvent: windowEvent ) } diff --git a/Application/Presentation/Entry/Sources/Composition/TreeSideBar.swift b/Application/Presentation/Entry/Sources/Composition/TreeSideBar.swift index 61685a95f..e489874de 100644 --- a/Application/Presentation/Entry/Sources/Composition/TreeSideBar.swift +++ b/Application/Presentation/Entry/Sources/Composition/TreeSideBar.swift @@ -131,8 +131,7 @@ struct TreeSideBar: View { } SideBarRow( title: Text("nav_settings", bundle: PresentationResources.bundle), - symbolName: "gearshape.fill", - isSelected: location == .settings + symbolName: "gearshape.fill" ) { // 앱 화면과 분리한 설정 화면 표시 store.send(.tapSettings) diff --git a/Application/Presentation/Entry/Tests/Composition/CompositionFeatureTestSupport.swift b/Application/Presentation/Entry/Tests/Composition/CompositionFeatureTestSupport.swift index 243d27dd4..418a9e47d 100644 --- a/Application/Presentation/Entry/Tests/Composition/CompositionFeatureTestSupport.swift +++ b/Application/Presentation/Entry/Tests/Composition/CompositionFeatureTestSupport.swift @@ -132,6 +132,19 @@ final class ObserveUnreadPushCountUseCaseSpy: ObserveUnreadPushCountUseCase { } } +actor CompositionFetchAuthProvidersUseCaseSpy: FetchAuthProvidersUseCase { + private var count = 0 + + func execute() async throws -> (currentProvider: AuthProvider?, allProviders: [AuthProvider]) { + count += 1 + return (nil, []) + } + + func executeCallCount() -> Int { + count + } +} + final class CompositionTrackAnalyticsEventUseCaseSpy: TrackAnalyticsEventUseCase { private var events = [AnalyticsEvent]() diff --git a/Application/Presentation/Entry/Tests/Composition/CompositionFeatureTests.swift b/Application/Presentation/Entry/Tests/Composition/CompositionFeatureTests.swift index 66e60568a..002737583 100644 --- a/Application/Presentation/Entry/Tests/Composition/CompositionFeatureTests.swift +++ b/Application/Presentation/Entry/Tests/Composition/CompositionFeatureTests.swift @@ -9,6 +9,7 @@ import PresentationShared import Foundation import Testing @testable import Entry +@testable import ProfileTab @MainActor struct CompositionFeatureTests { @@ -75,6 +76,29 @@ struct CompositionFeatureTests { #expect(trackAnalyticsEventUseCase.screenNames == ["home", "today", "profile"]) } + @Test("CompositionFeature는 프로필 칸에 작성 화면을 그린 동안에도 설정을 창 전체에 표시하고 닫으면 내린다") + func CompositionFeature는_프로필_칸에_작성_화면을_그린_동안에도_설정을_창_전체에_표시하고_닫으면_내린다() async { + let store = TestStore(initialState: CompositionFeature.State()) { + CompositionFeature() + } + store.exhaustivity = .off(showSkippedAssertions: false) + + await store.send(.sideBar(.paneEditingChanged(.profile, true))) + await store.send(.sideBar(.tapSettings)) + await store.receive(.settings(.open)) + + #expect(store.state.isSettingsPresented) + #expect(store.state.settings.screen == .detail) + #expect(store.state.settings.selectedRoute == .theme) + // 설정을 여는 것만으로 프로필 탭을 만들지 않음 + #expect(store.state.openedTabs.isEmpty) + + await store.send(.settings(.close)) + + #expect(!store.state.isSettingsPresented) + #expect(store.state.settings.screen == nil) + } + @Test("CompositionFeature는 사이드바 항목을 고르면 작성 화면을 그린 탭이라도 그 탭을 선택한다") func CompositionFeature는_사이드바_항목을_고르면_작성_화면을_그린_탭이라도_그_탭을_선택한다() async { let store = makeStore() @@ -86,6 +110,135 @@ struct CompositionFeatureTests { #expect(store.state.sideBar.requests[.profile] == nil) } + @Test("CompositionFeature는 창이 좁아지면 설정을 이어서 표시할 프로필 탭을 유지한다") + func CompositionFeature는_창이_좁아지면_설정을_이어서_표시할_프로필_탭을_유지한다() async { + let store = TestStore(initialState: CompositionFeature.State()) { + CompositionFeature() + } + store.exhaustivity = .off(showSkippedAssertions: false) + + await store.send(.settings(.open)) + await store.send(.settings(.select(.pushNotification))) + await store.send(.view(.sideBarVisibilityChanged(false))) + + #expect(store.state.isSettingsPresented) + #expect(store.state.settings.screen == .detail) + #expect(store.state.settings.selectedRoute == .pushNotification) + #expect(store.state.openedTabs == [.profile]) + } + + @Test( + "CompositionFeature는 창이 넓어지면 프로필 탭에서 보던 설정만 창 전체에 이어서 표시한다", + arguments: [AppTab.profile, .home] + ) + func CompositionFeature는_창이_넓어지면_프로필_탭에서_보던_설정만_창_전체에_이어서_표시한다(tab: AppTab) async { + let store = makeStore() + + await store.send(.settings(.select(.pushNotification))) + await store.send(.selectTab(tab)) + await store.send(.view(.sideBarVisibilityChanged(true))) + + #expect(store.state.isSettingsPresented == (tab == .profile)) + #expect(store.state.settings.screen == (tab == .profile ? .detail : nil)) + #expect(store.state.settings.selectedRoute == .pushNotification) + } + + @Test("CompositionFeature는 좁아진 창에 이어진 설정을 닫으면 프로필 탭을 선택한다") + func CompositionFeature는_좁아진_창에_이어진_설정을_닫으면_프로필_탭을_선택한다() async { + let store = makeStore() + + await store.send(.view(.sideBarVisibilityChanged(true))) + await store.send(.settings(.open)) + await store.send(.view(.sideBarVisibilityChanged(false))) + await store.send(.settings(.binding(.set(\.screen, .list)))) + + #expect(store.state.isSettingsPresented) + #expect(store.state.selectedTab == .home) + + await store.send(.settings(.binding(.set(\.screen, nil)))) + + #expect(!store.state.isSettingsPresented) + #expect(store.state.selectedTab == .profile) + } + + @Test("CompositionFeature는 좁아진 창에 설정이 이어져 있어도 이미 선택한 탭을 다시 고르면 그 탭을 표시한다") + func CompositionFeature는_좁아진_창에_설정이_이어져_있어도_이미_선택한_탭을_다시_고르면_그_탭을_표시한다() async { + let store = makeStore() + + await store.send(.view(.sideBarVisibilityChanged(true))) + await store.send(.settings(.open)) + await store.send(.selectTab(.home)) + + // 사이드바가 있는 창의 설정은 탭을 골라도 유지 + #expect(store.state.isSettingsPresented) + + await store.send(.view(.sideBarVisibilityChanged(false))) + await store.send(.selectTab(.home)) + + #expect(!store.state.isSettingsPresented) + #expect(store.state.settings.screen == .detail) + #expect(store.state.settings.selectedRoute == .theme) + } + + @Test("CompositionFeature는 창 폭이 바뀔 때는 다시 조회하지 않고 계정 화면에 들어올 때만 조회한다") + func CompositionFeature는_창_폭이_바뀔_때는_다시_조회하지_않고_계정_화면에_들어올_때만_조회한다() async { + let fetchUseCase = CompositionFetchAuthProvidersUseCaseSpy() + let store = TestStore(initialState: CompositionFeature.State()) { + CompositionFeature() + } withDependencies: { + $0.fetchAuthProvidersUseCase = fetchUseCase + } + store.exhaustivity = .off(showSkippedAssertions: false) + + await store.send(.view(.sideBarVisibilityChanged(true))) + await store.send(.settings(.open)) + await store.send(.settings(.select(.account))) + await store.receive(.settings(.account(.open))) + await store.receive(.settings(.account(.setProviders(currentProvider: nil, allProviders: [])))) + + await store.send(.view(.sideBarVisibilityChanged(false))) + await store.send(.view(.sideBarVisibilityChanged(true))) + await store.send(.settings(.select(.theme))) + + #expect(await fetchUseCase.executeCallCount() == 1) + + await store.send(.settings(.select(.account))) + await store.receive(.settings(.account(.open))) + await store.receive(.settings(.account(.setProviders(currentProvider: nil, allProviders: [])))) + + #expect(await fetchUseCase.executeCallCount() == 2) + } + + @Test("CompositionFeature는 설정 목록까지 돌아온 뒤 창을 넓혀 계정 화면이 나오면 한 번 조회하고 다시 좁혀도 계정 화면을 이어서 표시한다") + func CompositionFeature는_설정_목록까지_돌아온_뒤_창을_넓혀_계정_화면이_나오면_한_번_조회하고_다시_좁혀도_계정_화면을_이어서_표시한다() async { + let fetchUseCase = CompositionFetchAuthProvidersUseCaseSpy() + var state = CompositionFeature.State() + state.selectedTab = .profile + state.settings.selectedRoute = .account + state.settings.screen = .list + let store = TestStore(initialState: state) { + CompositionFeature() + } withDependencies: { + $0.fetchAuthProvidersUseCase = fetchUseCase + } + store.exhaustivity = .off(showSkippedAssertions: false) + + await store.send(.view(.sideBarVisibilityChanged(true))) + await store.receive(.settings(.account(.open))) + await store.receive(.settings(.account(.setProviders(currentProvider: nil, allProviders: [])))) + + #expect(store.state.settings.screen == .detail) + + await store.send(.settings(.account(.setAlert(.signOut)))) + await store.send(.view(.sideBarVisibilityChanged(false))) + await store.send(.view(.sideBarVisibilityChanged(true))) + + // 폭이 바뀌어도 계정 화면이 이어져 다시 조회하지 않고 알림창 유지 + #expect(store.state.isAccountOpen) + #expect(store.state.settings.account.alert != nil) + #expect(await fetchUseCase.executeCallCount() == 1) + } + @Test("CompositionFeature는 화면 회전 때 오는 높이 0인 키보드 표시 알림을 무시한다") func CompositionFeature는_화면_회전_때_오는_높이_0인_키보드_표시_알림을_무시한다() async { let store = makeStore() diff --git a/Application/Presentation/PresentationShared/Sources/Common/SideBarNavigation.swift b/Application/Presentation/PresentationShared/Sources/Common/SideBarNavigation.swift index 770cf3369..08ddfe9e0 100644 --- a/Application/Presentation/PresentationShared/Sources/Common/SideBarNavigation.swift +++ b/Application/Presentation/PresentationShared/Sources/Common/SideBarNavigation.swift @@ -19,7 +19,6 @@ public enum SideBarLocation: Hashable { // 사이드바 항목이 아닌 홈 검색, 사이드바에서 아무 항목도 고르지 않은 상태 case search case profile - case settings } public struct SideBarGoal: Hashable, Identifiable { diff --git a/Application/Presentation/PresentationShared/Sources/Extension/EnvironmentValues+.swift b/Application/Presentation/PresentationShared/Sources/Extension/EnvironmentValues+.swift index b73837447..b0d27a4fd 100644 --- a/Application/Presentation/PresentationShared/Sources/Extension/EnvironmentValues+.swift +++ b/Application/Presentation/PresentationShared/Sources/Extension/EnvironmentValues+.swift @@ -45,12 +45,6 @@ public extension EnvironmentValues { set { self[ExpandSideBarKey.self] = newValue } } - // 앱 화면과 분리한 설정 화면을 여는 동작, 사이드바가 있는 메인 창 탭 화면 안에서만 있음 - var presentSettings: (() -> Void)? { - get { self[PresentSettingsKey.self] } - set { self[PresentSettingsKey.self] = newValue } - } - // 고른 대상과 고른 화면을 세부 정보 사이드바에 알리는 동작, 메인 창 탭 화면 안에서만 있음 var selectDetailSideBarTarget: ((DetailSideBarTarget?, UUID) -> Void)? { get { self[SelectDetailSideBarTargetKey.self] } @@ -153,10 +147,6 @@ public extension EnvironmentValues { static let defaultValue: (() -> Void)? = nil } - private struct PresentSettingsKey: EnvironmentKey { - static let defaultValue: (() -> Void)? = nil - } - private struct SelectDetailSideBarTargetKey: EnvironmentKey { static let defaultValue: ((DetailSideBarTarget?, UUID) -> Void)? = nil } diff --git a/Application/Presentation/ProfileTab/Sources/Profile/ProfileView.swift b/Application/Presentation/ProfileTab/Sources/Profile/ProfileView.swift index 66f948ec6..fa54593f1 100644 --- a/Application/Presentation/ProfileTab/Sources/Profile/ProfileView.swift +++ b/Application/Presentation/ProfileTab/Sources/Profile/ProfileView.swift @@ -17,37 +17,28 @@ public struct ProfileView: View { @Environment(\.usesPaneLayout) private var usesPaneLayout @Environment(\.deviceType) private var deviceType @Environment(\.sideBarRequest) private var sideBarRequest - @Environment(\.presentSettings) private var presentSettings - @State private var settingsStore: StoreOf - // 계정 화면에서 뒤로 가도 진행 중인 로그아웃, 회원 탈퇴가 취소되지 않게 프로필 화면이 보관 - @State private var accountStore: StoreOf @State private var store: StoreOf @State private var router = NavigationRouter() + @Bindable private var settingsStore: StoreOf private let isSelected: Bool private let windowEvent: TodoEditorWindowEvent public init( isSelected: Bool, + settingsStore: StoreOf, windowEvent: TodoEditorWindowEvent ) { let store = Store(initialState: ProfileFeature.State()) { ProfileFeature() } - let settingsStore = Store(initialState: SettingsFeature.State()) { - SettingsFeature() - } - let accountStore = Store(initialState: AccountFeature.State()) { - AccountFeature() - } self._store = State(initialValue: store) - self._settingsStore = State(initialValue: settingsStore) - self._accountStore = State(initialValue: accountStore) + self.settingsStore = settingsStore self.isSelected = isSelected self.windowEvent = windowEvent } public var body: some View { - NavigationStack(path: $router.path) { + NavigationStack(path: path) { // 사이드바가 있는 창은 프로필을 창 전체 폭으로 두고 오른쪽 칸으로 옮긴 Todo가 있을 때만 두 칸으로 나눔 PaneSplitView(splitsOnDesktop: store.selectedTodoRoute != nil) { ScrollView { @@ -123,6 +114,8 @@ public struct ProfileView: View { ) } .desktopNavigationTransition() + // 창 폭이 바뀌어 같은 설정을 다시 쌓거나 내릴 때 밀리는 효과 없이 바꿈 + .transaction(value: usesDesktopLayout) { $0.disablesAnimations = true } // 사이드바 구조로 바뀌면 쌓아 연 Todo 상세는 내리고 같은 Todo를 옆 칸에 표시 .closesPushedDetail { switch router.path.last { @@ -133,21 +126,6 @@ public struct ProfileView: View { break } } - // 사이드바가 있는 창으로 바뀌면 쌓아 연 설정은 내리고 창 전체 설정 화면으로 표시 - .onChange(of: usesDesktopLayout) { _, usesDesktopLayout in - if usesDesktopLayout, router.root == .settings, let presentSettings { - router.path = [] - // 다른 탭을 보던 중이면 쌓아 연 설정만 내리고 창 전체 설정 화면은 띄우지 않음 - if isSelected { - presentSettings() - } - } - } - // 설정 아래 화면도 사이드바에서는 설정으로 표시 - .preference( - key: SideBarLocationPreferenceKey.self, - value: router.root == .settings ? .settings : .profile - ) // 사이드바 요청으로 처음 여는 탭도 그 요청을 반영 .onChange(of: sideBarRequest, initial: true) { _, request in switch request?.action { @@ -183,7 +161,7 @@ public struct ProfileView: View { ToolbarItem(placement: .topBarTrailing) { // 접힌 뒤 펼칠 때 레일 아이콘이 사라지는 현상 방지 Button { - router.push(.settings) + settingsStore.send(.openList) } label: { Image(systemName: "gearshape") } @@ -193,18 +171,12 @@ public struct ProfileView: View { @ViewBuilder private var titleBar: some View { - let openSettings = { - // 사이드바가 있는 창은 앱 화면과 분리한 설정 화면 표시 - if let presentSettings { - presentSettings() - } else { - router.push(.settings) - } - } - if usesPaneLayout { PaneTitleBar(Text("nav_profile", bundle: PresentationResources.bundle)) { - Button(action: openSettings) { + // 사이드바가 있는 창은 앱 화면과 분리한 설정 화면 표시 + Button { + settingsStore.send(.open) + } label: { Image(systemName: "gearshape") } .topBarButtonStyle() @@ -217,7 +189,9 @@ public struct ProfileView: View { Spacer() if deviceType != .duo { // 리퀴드 글래스 없이 배경 없는 40pt 아이콘 버튼 - Button(action: openSettings) { + Button { + settingsStore.send(.openList) + } label: { Image(systemName: "gearshape") } .buttonStyle(ProfileTopBarIconButtonStyle()) @@ -234,6 +208,37 @@ public struct ProfileView: View { } } + // 사이드바가 있는 창의 설정은 창 전체 설정 화면에 그리므로 쌓지 않음 + private var path: Binding<[ProfileRoute]> { + Binding( + get: { + guard !usesDesktopLayout else { return router.path } + switch settingsStore.screen { + case .list: + return router.path + [.settings] + case .detail: + return router.path + [.settings, settingsStore.selectedRoute] + case nil: + return router.path + } + }, + set: { path in + let settingsIndex = path.firstIndex(of: .settings) ?? path.endIndex + router.path = Array(path[..? + public struct State: Equatable { + @Presents public var alert: AlertState? var currentProvider: AuthProvider? var connectedProviders: [AuthProvider] = [] var disconnectedProviders: [AuthProvider] = [] @@ -33,9 +33,9 @@ struct AccountFeature { } } - enum Action { + public enum Action: Equatable { case alert(PresentationAction) - case onAppear + case open case linkWithProvider(AuthProvider) case setPresentationContext(AuthPresentationContext?) case unlinkFromProvider(AuthProvider) @@ -43,13 +43,13 @@ struct AccountFeature { case setProviders(currentProvider: AuthProvider?, allProviders: [AuthProvider]) case loading(LoadingFeature.Action) - enum Alert: Equatable { + public enum Alert: Equatable { case tapDeleteAuthButton case tapSignOutButton } } - enum AlertType: Equatable { + public enum AlertType: Equatable { case signOut case deleteAuth case linkEmailNotFound @@ -65,7 +65,7 @@ struct AccountFeature { @Dependency(\.deleteAuthUseCase) var deleteAuthUseCase @Dependency(\.signOutUseCase) var signOutUseCase - var body: some ReducerOf { + public var body: some ReducerOf { Scope(state: \.loading, action: \.loading) { LoadingFeature() } @@ -81,7 +81,7 @@ struct AccountFeature { return signOutEffect() case .alert: break - case .onAppear: + case .open: // 화면을 떠난 뒤 실패한 요청의 알림창은 다시 들어올 때 띄우지 않음 state.alert = nil return fetchProvidersEffect() @@ -284,7 +284,6 @@ private extension AccountFeature { try await deleteAuthUseCase.execute() // 유스케이스 완료가 LoginView 전환 완료를 의미하지 않으므로 화면이 교체될 때까지 로딩 유지 } catch { - // 로딩보다 알림창을 먼저 띄워 좁아진 창의 설정 화면이 알림창 전에 닫히지 않게 함 await send(.setAlert(.error)) await send(.loading(.end(target: .default, mode: .delayed))) } @@ -298,7 +297,6 @@ private extension AccountFeature { try await signOutUseCase.execute() // 유스케이스 완료가 LoginView 전환 완료를 의미하지 않으므로 화면이 교체될 때까지 로딩 유지 } catch { - // 로딩보다 알림창을 먼저 띄워 좁아진 창의 설정 화면이 알림창 전에 닫히지 않게 함 await send(.setAlert(.error)) await send(.loading(.end(target: .default, mode: .delayed))) } diff --git a/Application/Presentation/ProfileTab/Sources/Settings/AccountView.swift b/Application/Presentation/ProfileTab/Sources/Settings/AccountView.swift index 3bae85eeb..9f98abcb9 100644 --- a/Application/Presentation/ProfileTab/Sources/Settings/AccountView.swift +++ b/Application/Presentation/ProfileTab/Sources/Settings/AccountView.swift @@ -73,13 +73,11 @@ struct AccountView: View { } .background(Color.background) .duoToolbarVisibility(showsBackButton: true) - .onAppear { store.send(.onAppear) } - .prominentAlert(store, state: \.alert, action: \.alert) .background { - WindowSceneIdentifierReader { - store.send(.setPresentationContext( - $0.map(AuthPresentationContext.init(identifier:)) - )) + WindowSceneIdentifierReader { identifier in + // 창 폭이 바뀌어 빠지는 화면이 늦게 보낸 빈 값이 새로 그린 화면의 값을 지우지 않음 + guard let identifier else { return } + store.send(.setPresentationContext(AuthPresentationContext(identifier: identifier))) } } } diff --git a/Application/Presentation/ProfileTab/Sources/Settings/DesktopSettingsView.swift b/Application/Presentation/ProfileTab/Sources/Settings/DesktopSettingsView.swift index f0c0a67c5..7ee2fead7 100644 --- a/Application/Presentation/ProfileTab/Sources/Settings/DesktopSettingsView.swift +++ b/Application/Presentation/ProfileTab/Sources/Settings/DesktopSettingsView.swift @@ -14,19 +14,10 @@ import PresentationShared public struct DesktopSettingsView: View { @Environment(\.readableContentWidth) private var readableContentWidth @Environment(\.isiOSAppOnMac) private var isiOSAppOnMac - @State private var store = Store(initialState: SettingsFeature.State()) { - SettingsFeature() - } - // 목차에서 다른 항목을 골라도 진행 중인 로그아웃, 회원 탈퇴가 취소되지 않게 설정 화면이 보관 - @State private var accountStore = Store(initialState: AccountFeature.State()) { - AccountFeature() - } - private let onBusyChange: (Bool) -> Void - private let onClose: () -> Void + @Bindable private var store: StoreOf - public init(onBusyChange: @escaping (Bool) -> Void, onClose: @escaping () -> Void) { - self.onBusyChange = onBusyChange - self.onClose = onClose + public init(store: StoreOf) { + self.store = store } public var body: some View { @@ -38,16 +29,8 @@ public struct DesktopSettingsView: View { .safeAreaInset(edge: .top, spacing: 0) { titleBar } .environment(\.showsPaneTitleBar, true) } - // 화면을 닫으면 Store가 해제되어 진행 중인 로그아웃, 회원 탈퇴가 취소되므로 끝날 때까지 화면 전체 비활성화 - .disabled(accountStore.activeLoadingRow != nil) - // 진행 중인 로그아웃, 회원 탈퇴나 계정 화면에 떠 있는 알림창이 남아 있으면 창이 좁아져도 화면을 닫지 않게 알림 - // 다른 항목으로 옮긴 뒤 실패한 요청의 알림창은 보이지 않아 제외 - .onChange( - of: accountStore.activeLoadingRow != nil || (store.selectedRoute == .account && accountStore.alert != nil), - initial: true - ) { _, isBusy in - onBusyChange(isBusy) - } + // 로그아웃, 회원 탈퇴가 끝날 때까지 비활성화 + .disabled(store.account.activeLoadingRow != nil) .onAppear { store.send(.startObserving) } } @@ -55,7 +38,9 @@ public struct DesktopSettingsView: View { VStack(spacing: 0) { // 칸 제목 줄과 같은 높이의 앱으로 돌아가기 줄 PaneTitleBar(background: .secondaryBackground) { - Button(action: onClose) { + Button { + store.send(.close) + } label: { HStack(spacing: 8 * AdaptiveSize.boardScale) { Image(systemName: "arrow.left") Text("settings_back_to_app", bundle: PresentationResources.bundle) @@ -76,7 +61,7 @@ public struct DesktopSettingsView: View { let isDisabled = !store.isNetworkConnected && (route == .pushNotification || route == .account) Button { - store.send(.binding(.set(\.selectedRoute, route))) + store.send(.select(route)) } label: { HStack(spacing: isiOSAppOnMac ? 8 * AdaptiveSize.boardScale : 10) { Image(systemName: route.settingsSymbolName) @@ -130,7 +115,9 @@ public struct DesktopSettingsView: View { Text(store.selectedRoute.settingsTitle) } } actions: { - Button(action: onClose) { + Button { + store.send(.close) + } label: { Image(systemName: "xmark") } .topBarButtonStyle() @@ -150,7 +137,7 @@ public struct DesktopSettingsView: View { }, isPaneDetail: true, showsTopBar: false) case .account: AccountView( - store: accountStore, + store: store.scope(state: \.account, action: \.account), settingsStore: store, isPaneDetail: true, showsTopBar: false diff --git a/Application/Presentation/ProfileTab/Sources/Settings/SettingsFeature.swift b/Application/Presentation/ProfileTab/Sources/Settings/SettingsFeature.swift index 070040437..3e6f3d63a 100644 --- a/Application/Presentation/ProfileTab/Sources/Settings/SettingsFeature.swift +++ b/Application/Presentation/ProfileTab/Sources/Settings/SettingsFeature.swift @@ -12,14 +12,22 @@ import Foundation import PresentationShared @Reducer -struct SettingsFeature { +public struct SettingsFeature { private enum CancelID: Hashable { case networkConnectivity case systemTheme } + public enum Screen: Equatable { + case list + // 고른 항목 화면 + case detail + } + @ObservableState - struct State: Equatable { + public struct State: Equatable { + // 계정 화면에서 뒤로 가도 진행 중인 로그아웃, 회원 탈퇴가 취소되지 않게 설정이 보관 + public var account = AccountFeature.State() var theme: SystemTheme = .automatic var isNetworkConnected = true var appVersion = Self.appVersion() @@ -28,8 +36,12 @@ struct SettingsFeature { testFlightURL: Bundle.main.object(forInfoDictionaryKey: "TESTFLIGHT_URL") as? String ) var policyURL = Bundle.main.object(forInfoDictionaryKey: "PRIVACY_POLICY_URL") as? String - // 칸 화면에서 설정 옆 칸에, Mac 설정 화면에서 목차 옆에 표시하는 화면 - var selectedRoute = ProfileRoute.theme + // 설정에서 고른 항목, 목록으로 돌아가도 창 전체 설정 화면에 표시할 항목으로 유지 + public var selectedRoute = ProfileRoute.theme + // 열린 설정 화면, 좁은 창은 프로필 화면에 쌓고 사이드바가 있는 창은 창 전체 설정 화면에 표시 + public var screen: Screen? + + public init() { } static func betaTestURL(appEnvironment: String?, testFlightURL: String?) -> URL? { guard appEnvironment?.trimmingCharacters(in: .whitespacesAndNewlines) == "prod", @@ -56,8 +68,13 @@ struct SettingsFeature { } } - enum Action: BindableAction { + public enum Action: BindableAction, Equatable { + case account(AccountFeature.Action) case binding(BindingAction) + case open + case openList + case select(ProfileRoute) + case close case startObserving case networkStatusChanged(Bool) } @@ -66,14 +83,35 @@ struct SettingsFeature { @Dependency(\.profileSystemThemeUseCase) var systemThemeUseCase @Dependency(\.updateSystemThemeUseCase) var updateSystemThemeUseCase - var body: some ReducerOf { + public init() { } + + public var body: some ReducerOf { + Scope(state: \.account, action: \.account) { + AccountFeature() + } BindingReducer() Reduce { state, action in switch action { + case .account: + break case .binding(\.theme): return updateSystemThemeEffect(state.theme) case .binding: break + case .open: + // 창 전체 설정 화면을 새로 열 때는 첫 항목부터 표시 + state.selectedRoute = .theme + state.screen = .detail + case .openList: + // 좁은 창에서 설정을 새로 열 때도 앞서 고른 항목 대신 첫 항목을 고른 채 목록 표시 + state.selectedRoute = .theme + state.screen = .list + case .select(let route): + state.selectedRoute = route + // 앱 정보는 좁은 창에 항목 화면이 없어 설정 목록에서 표시 + state.screen = route == .information ? .list : .detail + case .close: + state.screen = nil case .startObserving: return .merge( observeNetworkConnectivityEffect(), diff --git a/Application/Presentation/ProfileTab/Tests/Settings/AccountFeatureTests.swift b/Application/Presentation/ProfileTab/Tests/Settings/AccountFeatureTests.swift index 70603ce6c..d9301efda 100644 --- a/Application/Presentation/ProfileTab/Tests/Settings/AccountFeatureTests.swift +++ b/Application/Presentation/ProfileTab/Tests/Settings/AccountFeatureTests.swift @@ -22,7 +22,7 @@ struct AccountFeatureTests { ) let driver = AccountTestDriver(fetchUseCase: fetchSpy) - driver.onAppear() + driver.open() await waitUntil { driver.currentProvider == .google @@ -144,7 +144,7 @@ struct AccountFeatureTests { fetchSpy.error = AccountTestError.failure let driver = AccountTestDriver(fetchUseCase: fetchSpy) - driver.onAppear() + driver.open() await waitUntil { driver.alert != nil @@ -261,7 +261,7 @@ struct AccountFeatureTests { fetchSpy.error = AccountTestError.failure let driver = AccountTestDriver(fetchUseCase: fetchSpy) - driver.onAppear() + driver.open() await waitUntil { driver.alert != nil @@ -278,14 +278,14 @@ struct AccountFeatureTests { fetchSpy.error = AccountTestError.failure let driver = AccountTestDriver(fetchUseCase: fetchSpy) - driver.onAppear() + driver.open() await waitUntil { driver.alert != nil } fetchSpy.error = nil - driver.onAppear() + driver.open() #expect(driver.alert == nil) } @@ -380,8 +380,8 @@ private struct AccountTestDriver { } } - func onAppear() { - feature.send(.onAppear) + func open() { + feature.send(.open) } func linkWithProvider(_ provider: AuthProvider) { diff --git a/Application/Presentation/ProfileTab/Tests/Settings/SettingsFeatureTests.swift b/Application/Presentation/ProfileTab/Tests/Settings/SettingsFeatureTests.swift index 5f5562650..13775fc80 100644 --- a/Application/Presentation/ProfileTab/Tests/Settings/SettingsFeatureTests.swift +++ b/Application/Presentation/ProfileTab/Tests/Settings/SettingsFeatureTests.swift @@ -83,6 +83,48 @@ struct SettingsFeatureTests { #expect(adapter.theme == .light) #expect(updateSpy.themes == [.light]) } + + @Test("설정을 새로 열면 앞서 고른 항목과 상관없이 첫 항목부터 표시한다") + func 설정을_새로_열면_앞서_고른_항목과_상관없이_첫_항목부터_표시한다() async { + let store = TestStore(initialState: SettingsFeature.State()) { + SettingsFeature() + } + + await store.send(.select(.account)) { + $0.selectedRoute = .account + $0.screen = .detail + } + await store.send(.close) { + $0.screen = nil + } + await store.send(.open) { + $0.selectedRoute = .theme + $0.screen = .detail + } + await store.send(.select(.account)) { + $0.selectedRoute = .account + } + await store.send(.close) { + $0.screen = nil + } + // 좁은 창은 설정 목록부터 쌓음 + await store.send(.openList) { + $0.selectedRoute = .theme + $0.screen = .list + } + } + + @Test("좁은 창에 항목 화면이 없는 앱 정보를 고르면 설정 목록까지만 쌓는다") + func 좁은_창에_항목_화면이_없는_앱_정보를_고르면_설정_목록까지만_쌓는다() async { + let store = TestStore(initialState: SettingsFeature.State()) { + SettingsFeature() + } + + await store.send(.select(.information)) { + $0.selectedRoute = .information + $0.screen = .list + } + } } @MainActor From 67922d49502684dd820428047524e73fa370c925 Mon Sep 17 00:00:00 2001 From: opficdev Date: Thu, 26 Nov 2026 17:25:57 +0900 Subject: [PATCH 7/8] =?UTF-8?q?refactor:=20=EB=A3=A8=ED=8A=B8=20Feature?= =?UTF-8?q?=EA=B0=80=20=EC=82=AC=EC=9D=B4=EB=93=9C=EB=B0=94=20=ED=8F=AD?= =?UTF-8?q?=EC=9D=84=20run=EC=97=90=EC=84=9C=20=EC=9D=BD=EC=9D=80=20?= =?UTF-8?q?=EB=92=A4=20CompositionFeature=EB=A5=BC=20=EB=A7=8C=EB=93=A4?= =?UTF-8?q?=EB=8F=84=EB=A1=9D=20=EB=B3=80=EA=B2=BD?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../Entry/Sources/Root/Feature.swift | 39 ++++++++++++------- .../Entry/Tests/Root/FeatureTestSupport.swift | 10 +++-- .../Entry/Tests/Root/FeatureTests.swift | 24 ++++++++++++ 3 files changed, 56 insertions(+), 17 deletions(-) diff --git a/Application/Presentation/Entry/Sources/Root/Feature.swift b/Application/Presentation/Entry/Sources/Root/Feature.swift index 1a34aecf5..c5fe27a28 100644 --- a/Application/Presentation/Entry/Sources/Root/Feature.swift +++ b/Application/Presentation/Entry/Sources/Root/Feature.swift @@ -53,6 +53,7 @@ struct Feature { case networkStatusChanged(Bool) case setTheme(SystemTheme) case didLogined(Bool) + case sideBarWidthFetched(Double?) enum Alert: Equatable { case tapUpdateButton @@ -119,9 +120,9 @@ struct Feature { case .openWidgetRoute(let route): // 로그아웃 상태면 로그인 화면만 보이고 위젯 경로는 버림 guard state.signIn != false else { break } - // 로그인 여부를 확인하기 전이면 경로를 보관했다가 로그인 확인 뒤 적용 + // 로그인 여부를 확인하거나 앱 화면 상태를 만들기 전이면 경로를 보관했다가 만들 때 적용 state.widgetRoute = route - guard state.signIn == true else { break } + guard state.signIn == true, state.composition != nil else { break } switch route { case .tab(let tab): return .send(.composition(.selectTab(tab))) @@ -140,19 +141,14 @@ struct Feature { let wasSignedIn = state.signIn == true state.signIn = result if result { - guard !wasSignedIn else { return .send(.composition(.selectTab(.home))) } - var composition = CompositionFeature.State() - composition.sideBar.width = fetchSideBarWidthUseCase.execute().map { CGFloat($0) } - switch state.widgetRoute { - case .tab(let tab): - composition.selectedTab = tab - case .todayTodo(let id): - state.sheet = .init(todoId: id) - case nil: - break + guard !wasSignedIn else { + // 앱 화면 상태를 만들기 전이면 만들 때 홈 탭으로 시작 + return state.composition == nil ? .none : .send(.composition(.selectTab(.home))) + } + // 사용자가 정한 사이드바 폭을 읽은 뒤 앱 화면 상태를 만듦 + return .run { [fetchSideBarWidthUseCase] send in + await send(.sideBarWidthFetched(fetchSideBarWidthUseCase.execute())) } - state.composition = composition - return .send(.composition(.start)) } else { state.composition = nil state.widgetRoute = nil @@ -161,6 +157,21 @@ struct Feature { clearApplicationBadgeCountEffect() ) } + case .sideBarWidthFetched(let width): + // 폭을 읽는 동안 로그아웃했거나 이미 만들었으면 다시 만들지 않음 + guard state.signIn == true, state.composition == nil else { break } + var composition = CompositionFeature.State() + composition.sideBar.width = width.map { CGFloat($0) } + switch state.widgetRoute { + case .tab(let tab): + composition.selectedTab = tab + case .todayTodo(let id): + state.sheet = .init(todoId: id) + case nil: + break + } + state.composition = composition + return .send(.composition(.start)) } return .none diff --git a/Application/Presentation/Entry/Tests/Root/FeatureTestSupport.swift b/Application/Presentation/Entry/Tests/Root/FeatureTestSupport.swift index 8cc57e2fa..9647b2a15 100644 --- a/Application/Presentation/Entry/Tests/Root/FeatureTestSupport.swift +++ b/Application/Presentation/Entry/Tests/Root/FeatureTestSupport.swift @@ -56,6 +56,7 @@ struct RootStoreTestAdapter: RootStateDriving { } var sheetTodoId: String? { store.state.sheet?.todoId } var widgetRoute: WidgetRoute? { store.state.widgetRoute } + var sideBarWidth: CGFloat? { store.state.composition?.sideBar.width } init( sessionUseCase: ObserveAuthSessionUseCase = ObserveAuthSessionUseCaseSpy(currentValue: true), @@ -69,7 +70,8 @@ struct RootStoreTestAdapter: RootStateDriving { checkAppUpdateUseCase: CheckAppUpdateUseCase = RootCheckAppUpdateUseCaseSpy(), appStoreURL: URL? = URL(string: "https://apps.apple.com/us/app/devlog/id6760288611"), openURLSpy: RootOpenURLSpy = RootOpenURLSpy(), - badgeCountSpy: RootApplicationBadgeCountSpy = RootApplicationBadgeCountSpy() + badgeCountSpy: RootApplicationBadgeCountSpy = RootApplicationBadgeCountSpy(), + sideBarWidth: Double? = nil ) { store = TestStore(initialState: Feature.State()) { Feature() @@ -87,7 +89,7 @@ struct RootStoreTestAdapter: RootStateDriving { $0.setApplicationBadgeCount = { count in try await badgeCountSpy.setBadgeCount(count) } - $0.fetchSideBarWidthUseCase = RootFetchSideBarWidthUseCaseStub() + $0.fetchSideBarWidthUseCase = RootFetchSideBarWidthUseCaseStub(width: sideBarWidth) $0.observeUnreadPushCountUseCase = ObserveUnreadPushCountUseCaseSpy() } store.exhaustivity = .off(showSkippedAssertions: false) @@ -366,8 +368,10 @@ actor RootCheckAppUpdateUseCaseSpy: CheckAppUpdateUseCase { } struct RootFetchSideBarWidthUseCaseStub: FetchSideBarWidthUseCase { + let width: Double? + func execute() -> Double? { - nil + width } } diff --git a/Application/Presentation/Entry/Tests/Root/FeatureTests.swift b/Application/Presentation/Entry/Tests/Root/FeatureTests.swift index 3851fa123..8d25371f1 100644 --- a/Application/Presentation/Entry/Tests/Root/FeatureTests.swift +++ b/Application/Presentation/Entry/Tests/Root/FeatureTests.swift @@ -9,6 +9,7 @@ import Core import Foundation import PresentationShared import Testing +@testable import Entry @MainActor struct FeatureTests { @@ -251,6 +252,29 @@ struct FeatureTests { #expect(adapter.snapshot.selectedTab == .today) #expect(adapter.sheetTodoId == "todo-1") } + + @Test("로그인하면 저장된 사이드바 폭을 읽어 앱 화면 상태를 만든다") + func 로그인하면_저장된_사이드바_폭을_읽어_앱_화면_상태를_만든다() async { + let adapter = RootStoreTestAdapter(sideBarWidth: 300) + + await adapter.didLogined(true) + + #expect(adapter.snapshot.selectedTab == .home) + #expect(adapter.sideBarWidth == 300) + } + + @Test("사이드바 폭을 읽는 동안 로그아웃하면 앱 화면 상태를 만들지 않는다") + func 사이드바_폭을_읽는_동안_로그아웃하면_앱_화면_상태를_만들지_않는다() async { + var state = Feature.State() + state.signIn = false + let store = TestStore(initialState: state) { + Feature() + } + + await store.send(.sideBarWidthFetched(300)) + + #expect(store.state.composition == nil) + } } private enum CheckAppUpdateUseCaseTestError: Error { From bfdd747db0bc01eebb02e9a26247b81df2d678ef Mon Sep 17 00:00:00 2001 From: opficdev Date: Thu, 26 Nov 2026 17:26:00 +0900 Subject: [PATCH 8/8] =?UTF-8?q?fix:=20=EA=B3=84=EC=A0=95=20=ED=99=94?= =?UTF-8?q?=EB=A9=B4=EC=9D=84=20=EB=82=98=EA=B0=80=EB=A9=B4=20AccountFeatu?= =?UTF-8?q?re=EC=9D=98=20presentationContext=EB=A5=BC=20=EC=A7=80=EC=9A=B0?= =?UTF-8?q?=EB=8F=84=EB=A1=9D=20=EC=88=98=EC=A0=95?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../Composition/CompositionFeature.swift | 3 ++- .../Composition/CompositionFeatureTests.swift | 27 +++++++++++++++++++ 2 files changed, 29 insertions(+), 1 deletion(-) diff --git a/Application/Presentation/Entry/Sources/Composition/CompositionFeature.swift b/Application/Presentation/Entry/Sources/Composition/CompositionFeature.swift index 3e409b063..01c87bb85 100644 --- a/Application/Presentation/Entry/Sources/Composition/CompositionFeature.swift +++ b/Application/Presentation/Entry/Sources/Composition/CompositionFeature.swift @@ -159,7 +159,8 @@ struct CompositionFeature { .onChange(of: \.isAccountOpen) { _, isOpen in Reduce { _, _ in // 창 폭이 바뀌어 화면을 옮겨 그릴 때는 다시 조회하지 않고 계정 화면에 들어올 때만 조회 - isOpen ? .send(.settings(.account(.open))) : .none + // 계정 화면을 나가면 그 화면이 있던 창 정보를 지움 + .send(.settings(.account(isOpen ? .open : .setPresentationContext(nil)))) } } } diff --git a/Application/Presentation/Entry/Tests/Composition/CompositionFeatureTests.swift b/Application/Presentation/Entry/Tests/Composition/CompositionFeatureTests.swift index 002737583..bbffb1db8 100644 --- a/Application/Presentation/Entry/Tests/Composition/CompositionFeatureTests.swift +++ b/Application/Presentation/Entry/Tests/Composition/CompositionFeatureTests.swift @@ -5,6 +5,7 @@ // Created by opfic on 6/16/26. // +import Core import PresentationShared import Foundation import Testing @@ -239,6 +240,32 @@ struct CompositionFeatureTests { #expect(await fetchUseCase.executeCallCount() == 1) } + @Test("CompositionFeature는 창 폭이 바뀔 때는 계정 화면의 창 정보를 유지하고 계정 화면을 나가면 지운다") + func CompositionFeature는_창_폭이_바뀔_때는_계정_화면의_창_정보를_유지하고_계정_화면을_나가면_지운다() async { + let context = AuthPresentationContext(identifier: "scene") + let store = TestStore(initialState: CompositionFeature.State()) { + CompositionFeature() + } withDependencies: { + $0.fetchAuthProvidersUseCase = CompositionFetchAuthProvidersUseCaseSpy() + } + store.exhaustivity = .off(showSkippedAssertions: false) + + await store.send(.view(.sideBarVisibilityChanged(true))) + await store.send(.settings(.open)) + await store.send(.settings(.select(.account))) + await store.receive(.settings(.account(.open))) + await store.send(.settings(.account(.setPresentationContext(context)))) + await store.send(.view(.sideBarVisibilityChanged(false))) + await store.send(.view(.sideBarVisibilityChanged(true))) + + #expect(store.state.settings.account.presentationContext == context) + + await store.send(.settings(.select(.theme))) + await store.receive(.settings(.account(.setPresentationContext(nil)))) + + #expect(store.state.settings.account.presentationContext == nil) + } + @Test("CompositionFeature는 화면 회전 때 오는 높이 0인 키보드 표시 알림을 무시한다") func CompositionFeature는_화면_회전_때_오는_높이_0인_키보드_표시_알림을_무시한다() async { let store = makeStore()