diff --git a/Application/App/Sources/App/Dependency/AppGraph+PresentationDependencies.swift b/Application/App/Sources/App/Dependency/AppGraph+PresentationDependencies.swift index 325a5733..e1db5a45 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/Common/Component/ReadableContentWidthReader.swift b/Application/Presentation/Entry/Sources/Common/Component/ReadableContentWidthReader.swift new file mode 100644 index 00000000..7e001b21 --- /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/Common/Component/SplitShell.swift b/Application/Presentation/Entry/Sources/Common/Component/SplitShell.swift new file mode 100644 index 00000000..35368301 --- /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/CompositionFeature.swift b/Application/Presentation/Entry/Sources/Composition/CompositionFeature.swift new file mode 100644 index 00000000..01c87bb8 --- /dev/null +++ b/Application/Presentation/Entry/Sources/Composition/CompositionFeature.swift @@ -0,0 +1,231 @@ +// +// CompositionFeature.swift +// Entry +// +// Created by opfic on 6/16/26. +// + +import Combine +import PresentationShared +import Domain +import Foundation +import ProfileTab +import SwiftUI + +@Reducer +struct CompositionFeature { + @ObservableState + struct State: Equatable { + var windowControlsInset = CGFloat.zero + // Duo 세로 칸 자리의 양옆 안전 영역 + var verticalBarInsets = EdgeInsets() + // 화면 키보드가 떠 있는 동안 직접 그린 하단 탭 바를 숨김 + var isKeyboardVisible = false + // 탭 안 화면이 직접 그린 하단 탭 바 뒤로 들어가지 않도록 비울 높이 + var tabBarHeight = CGFloat.zero + var readableContentWidth = CGFloat.infinity + var selectedTab = AppTab.home + var openedTabs: Set = [] + // 창에 사이드바가 있는지 여부, 배치가 아닌 설정 규칙에만 사용 + var showsSideBar = false + // 앱 화면과 분리해 창 전체에 표시하는 설정 화면, 좁아진 창에서는 프로필 화면에 이어서 표시 + var isSettingsPresented = 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 { + case willShow(height: CGFloat) + case willHide + } + + enum Action: BindableAction, Equatable { + 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) + } + } + + private enum CancelID: Hashable { + case keyboard + } + + @Dependency(\.trackAnalyticsEventUseCase) var trackAnalyticsEventUseCase + @Dependency(\.keyboardEvents) var keyboardEvents + + var body: some ReducerOf { + 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 + } + } + .onChange(of: \.isAccountOpen) { _, isOpen in + Reduce { _, _ in + // 창 폭이 바뀌어 화면을 옮겨 그릴 때는 다시 조회하지 않고 계정 화면에 들어올 때만 조회 + // 계정 화면을 나가면 그 화면이 있던 창 정보를 지움 + .send(.settings(.account(isOpen ? .open : .setPresentationContext(nil)))) + } + } + } +} + +extension DependencyValues { + var keyboardEvents: @Sendable () -> AnyPublisher { + get { self[KeyboardEventsKey.self] } + set { self[KeyboardEventsKey.self] = newValue } + } +} + +private enum KeyboardEventsKey: DependencyKey { + 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 CompositionFeature.KeyboardEvent.willShow(height: frame?.height ?? 0) + } + .merge(with: center.publisher(for: UIResponder.keyboardWillHideNotification).map { _ in .willHide }) + .eraseToAnyPublisher() + } + + static var testValue: @Sendable () -> AnyPublisher { + liveValue + } +} + +private extension CompositionFeature { + func observeKeyboardEffect() -> Effect { + .run { [keyboardEvents] send in + for await event in keyboardEvents().values { + await send(.store(.keyboardChanged(event))) + } + } + .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 + trackAnalyticsEventUseCase.execute(.screenView(screenName)) + } + } +} + +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/Sources/Composition/CompositionView.swift b/Application/Presentation/Entry/Sources/Composition/CompositionView.swift new file mode 100644 index 00000000..3d2febfd --- /dev/null +++ b/Application/Presentation/Entry/Sources/Composition/CompositionView.swift @@ -0,0 +1,255 @@ +// +// CompositionView.swift +// Entry +// +// Created by opfic on 5/8/25. +// + +import SwiftUI +import ProfileTab +import PresentationShared + +// SplitShell의 자리마다 넣을 화면과 탭 바를 정하는 화면 +struct CompositionView: View { + @Environment(\.horizontalSizeClass) private var horizontalSizeClass + @Environment(\.isiOSAppOnMac) private var isiOSAppOnMac + @Environment(\.deviceType) private var deviceType + @Bindable private var store: StoreOf + private let windowEvent: TodoEditorWindowEvent + // 목록 칸과 상세 칸이 함께 들어가는 화면 영역 폭 + private let splitMinimumWidth = CGFloat(800) + + 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 + // iPhone, Duo, 좁은 iPad 창은 시스템 탭 바 대신 직접 그린 탭 사용 + let usesCustomTabBar = deviceType != .ipad || horizontalSizeClass == .compact + let isSystemTabBarHidden = showsSideBar || usesCustomTabBar + let verticalBarWidth = deviceType == .duo + ? max(store.verticalBarInsets.leading, store.verticalBarInsets.trailing) : 0 + // 시스템 탭 바처럼 키보드가 올라오면 키보드 뒤로 사라짐 + let showsTabBar = !showsSideBar && usesCustomTabBar && verticalBarWidth == 0 && !store.isKeyboardVisible + 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 { + // 최소는 화살표와 아이콘만 보이는 폭, Mac 최대는 Orca 사이드바와 같은 폭 + TreeSideBar( + store: store.scope(state: \.sideBar, action: \.sideBar), + selectedTab: selectedTab, + unreadPushCount: store.unreadPushCount.count + ) + .resizablePane( + width: store.sideBar.width, + minimumWidth: isiOSAppOnMac ? 72 * AdaptiveSize.boardScale : 84, + idealWidth: sideBarIdealWidth, + maximumWidth: isiOSAppOnMac ? 500 * AdaptiveSize.boardScale : 320 + ) { width in + store.send(.sideBar(.resized(width))) + } + // 칸 자르기 밖이라 잘리지 않도록 바탕은 칸 바깥에서 아래쪽 안전 영역까지 채움 + .background(Color.secondaryBackground, ignoresSafeAreaEdges: .bottom) + } + } center: { + ZStack { + // iPad는 시스템 탭 바를 쓰지 않아 Mac과 같이 구성 + // 넓은 창과 좁은 창을 오가도 탭 화면을 다시 만들지 않음 + if isiOSAppOnMac || deviceType == .ipad { + // 탭 전환 애니메이션 없이 한 번 연 탭을 유지하고 선택한 탭만 표시 + // 사이드바 하위 항목은 홈 화면이 알려 주므로 홈은 처음부터 생성 + ForEach(AppTab.allCases, id: \.self) { tab in + if store.openedTabs.contains(tab) || selectedTab == tab || visibleTab == tab || tab == .home { + TabScreen( + store: store, + tab: tab, + isSelected: selectedTab == tab && visibleTab == tab, + isVisible: visibleTab == tab, + isTabBarHidden: isSystemTabBarHidden, + tabBarInset: tabBarInset, + windowEvent: windowEvent + ) + .opacity(visibleTab == tab ? 1 : 0) + .allowsHitTesting(visibleTab == tab) + } + } + } else { + TabView(selection: $store.selectedTab.sending(\.selectTab)) { + ForEach(AppTab.allCases, id: \.self) { tab in + Tab(tab.title, systemImage: tab.symbolName, value: tab) { + TabScreen( + store: store, + tab: tab, + isSelected: selectedTab == tab && visibleTab == tab, + isVisible: visibleTab == tab, + isTabBarHidden: isSystemTabBarHidden, + tabBarInset: tabBarInset, + windowEvent: windowEvent + ) + } + .badge(tab == .notification ? store.unreadPushCount.count : 0) + } + } + } + } + .environment(\.usesPaneLayout, showsSideBar) + .environment(\.windowControlsInset, tabContentInset) + .environment(\.readableContentWidth, readableContentWidth) + .background { + ReadableContentWidthReader { width in + store.send(.binding(.set(\.readableContentWidth, width))) + } + } + // 접은 사이드바는 화면 칸 제목 줄의 버튼으로 다시 폄 + .environment( + \.expandSideBar, + store.sideBar.isCollapsed ? { store.send(.sideBar(.binding(.set(\.isCollapsed, false)))) } : nil + ) + // 닫힌 세부 정보 사이드바는 화면 칸 제목 줄의 버튼으로 엶 + .environment( + \.showDetailSideBar, + showsSideBar && !store.detailSideBar.isPresented + ? { store.send(.detailSideBar(.binding(.set(\.isPresented, true)))) } : nil + ) + .environment(\.isDetailSideBarPresented, showsSideBar && store.detailSideBar.isPresented) + .environment( + \.setDetailSideBarPresented, + showsSideBar ? { store.send(.detailSideBar(.binding(.set(\.isPresented, $0)))) } : nil + ) + } right: { + // 칸 화면이 사이드바를 직접 그리면 창 사이드바는 표시하지 않음 + if showsSideBar + && store.detailSideBar.isPresented + && store.detailSideBar.targets[selectedTab] != .hosted { + DetailSideBar( + target: store.detailSideBar.targets[selectedTab], + windowEvent: windowEvent + ) { + store.send(.detailSideBar(.binding(.set(\.isPresented, false)))) + } + } + } overlay: { + // 사이드바가 있는 창의 설정은 앱 화면을 덮어 창 전체에 표시하고 닫으면 보던 화면으로 돌아감 + 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과 같은 화면 구성 + // 접힌 Duo는 세로 막대가 늘 있어 첫 화면이나 접는 중에도 바꾸지 않음 + .environment( + \.deviceType, + deviceType == .duo && horizontalSizeClass == .regular && verticalBarWidth == 0 + ? .bar : deviceType + ) + // iPad 상태 표시줄 영역, Mac 창 제목 줄과 사이드바, 화면 영역을 나누는 구분선 + // iPad는 상태 표시줄 영역 맨 아래에 두어 상태 표시줄이 없는 창에서는 창 밖에 위치 + // Mac은 화면 영역 맨 위가 제목 줄 바로 아래라서 그 자리에 배치 + .overlay(alignment: .top) { + if showsSideBar { + Rectangle() + .fill(Color.separator) + .frame(height: 1) + .offset(y: isiOSAppOnMac ? 0 : -1) + .allowsHitTesting(false) + } + } + .overlay { + if 0 < verticalBarWidth { + DuoTabBar( + selectedTab: $store.selectedTab.sending(\.selectTab), + edge: store.verticalBarInsets.leading < store.verticalBarInsets.trailing ? .trailing : .leading, + width: verticalBarWidth, + unreadPushCount: store.unreadPushCount.count + ) + } + } + // Mac 창에서 상태 표시줄 자리로 비워 두는 상단 여백 제거 + .statusBarHidden(isiOSAppOnMac) + // iPad는 사이드바를 펴면 목록 칸과 상세 칸이 함께 들어가지 않는 창에서 사이드바를 접고 시작 + // 세로 화면처럼 좁은 창에서 상세 칸이 잘리지 않게 함 + .onGeometryChange(for: Bool.self) { proxy in + splitMinimumWidth + sideBarIdealWidth <= proxy.size.width + } action: { fitsSideBar in + guard !isiOSAppOnMac else { return } + store.send(.sideBar(.binding(.set(\.isCollapsed, !fitsSideBar)))) + } + .onGeometryChange(for: CGFloat.self) { proxy in + proxy.windowControlsInset + } action: { inset in + store.send(.binding(.set(\.windowControlsInset, inset))) + } + .toastHost() + .safeAreaInset(edge: .bottom, spacing: 0) { + if showsTabBar { + TabBar( + selectedTab: Binding( + get: { visibleTab }, + set: { store.send(.selectTab($0)) } + ), + axis: .horizontal, + unreadPushCount: store.unreadPushCount.count + ) + .padding(.horizontal, 8) + .padding(.top, 8) + .padding(.bottom, 4) + .background(Color.background, ignoresSafeAreaEdges: .bottom) + .overlay(alignment: .top) { + Rectangle() + .fill(Color.separator) + .frame(height: 1) + } + .onGeometryChange(for: CGFloat.self) { proxy in + proxy.size.height + } action: { height in + store.send(.binding(.set(\.tabBarHeight, height))) + } + } + } + .onGeometryChange(for: EdgeInsets.self) { proxy in + EdgeInsets( + top: 0, + leading: proxy.safeAreaInsets.leading, + bottom: 0, + trailing: proxy.safeAreaInsets.trailing + ) + } action: { insets in + store.send(.binding(.set(\.verticalBarInsets, insets))) + } + .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/DetailSideBarFeature.swift b/Application/Presentation/Entry/Sources/Composition/DetailSideBarFeature.swift new file mode 100644 index 00000000..72e3474c --- /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/DuoTabBar.swift b/Application/Presentation/Entry/Sources/Composition/DuoTabBar.swift new file mode 100644 index 00000000..76c5c7ae --- /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/SideBarFeature.swift b/Application/Presentation/Entry/Sources/Composition/SideBarFeature.swift new file mode 100644 index 00000000..62822146 --- /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: + 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/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 d91d959c..a7a8c948 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/Composition/TabScreen.swift b/Application/Presentation/Entry/Sources/Composition/TabScreen.swift new file mode 100644 index 00000000..e304ad0d --- /dev/null +++ b/Application/Presentation/Entry/Sources/Composition/TabScreen.swift @@ -0,0 +1,104 @@ +// +// 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 isVisible: Bool + let isTabBarHidden: Bool + let tabBarInset: CGFloat + let windowEvent: TodoEditorWindowEvent + + var body: some View { + content + .environment(\.isTabContentActive, isVisible) + .environment(\.sideBarRequest, store.sideBar.requests[tab]) + // 좁은 창에서도 고른 대상을 기록해 넓은 창으로 바뀌면 바로 세부 정보 사이드바에 표시 + .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(.sideBar(.locationChanged(tab, location))) + } + .onPreferenceChange(PaneDetailEditingPreferenceKey.self) { isEditing in + store.send(.sideBar(.paneEditingChanged(tab, isEditing))) + } + .onPreferenceChange(SideBarContentPreferenceKey.self) { content in + guard let content else { return } + store.send(.sideBar(.contentChanged(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, + settingsStore: store.scope(state: \.settings, action: \.settings), + 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 00000000..e489874d --- /dev/null +++ b/Application/Presentation/Entry/Sources/Composition/TreeSideBar.swift @@ -0,0 +1,225 @@ +// +// 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 + let store: StoreOf + let selectedTab: AppTab + let unreadPushCount: Int + + var body: some View { + let location = store.locations[selectedTab] ?? selectedTab.sideBarLocation + let expandedGroups = store.expandedGroups + let isCompact = (paneWidth ?? .infinity) < SideBarRow.compactWidth + let collapseButton = Button { + store.send(.binding(.set(\.isCollapsed, 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 ? unreadPushCount : 0 + ) { + store.send(.tapItem(tab, .open(tab.sideBarLocation))) + } + } + SideBarRow( + title: Text("development_goal_title", bundle: PresentationResources.bundle), + symbolName: "flag.checkered", + isExpanded: expandedGroups.contains(.developmentGoal) + ) { + store.send(.tapGroup(.developmentGoal), animation: .easeInOut(duration: 0.2)) + } + if expandedGroups.contains(.developmentGoal) { + ForEach(store.content.developmentGoals) { goal in + SideBarRow( + title: Text(goal.title), + symbolName: "flag", + isChild: true, + isSelected: location == .developmentGoal(goal.id) + ) { + store.send(.tapItem(.home, .open(.developmentGoal(goal.id)))) + } + } + } + SideBarRow( + title: Text(verbatim: "Todo"), + symbolName: "tray.fill", + isSelected: location == .todoCategoryManagement, + isExpanded: expandedGroups.contains(.todo) + ) { + store.send(.tapGroup(.todo), animation: .easeInOut(duration: 0.2)) + } + .contextMenu { + Button { + store.send(.tapItem(.home, .createTodo)) + } label: { + Label { + Text("sidebar_new_todo", bundle: PresentationResources.bundle) + } icon: { + Image(systemName: "square.and.pencil") + } + } + Button { + store.send(.tapItem(.home, .manageTodoCategory)) + } label: { + Label { + Text("todo_category_manage", bundle: PresentationResources.bundle) + } icon: { + Image(systemName: "square.grid.2x2") + } + } + } + if expandedGroups.contains(.todo) { + ForEach(store.content.todoCategories) { item in + SideBarRow( + title: Text(item.localizedName), + symbolName: item.symbolName, + symbolColor: item.color, + isChild: true, + isSelected: location == .todoCategory(item.id) + ) { + store.send(.tapItem(.home, .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 + ) { + store.send(.tapItem(.profile, .open(.profile))) + } + SideBarRow( + title: Text("nav_settings", bundle: PresentationResources.bundle), + symbolName: "gearshape.fill" + ) { + // 앱 화면과 분리한 설정 화면 표시 + store.send(.tapSettings) + } + } + .padding(.horizontal, 8 * AdaptiveSize.boardScale) + .padding(.vertical, 10 * AdaptiveSize.boardScale) + } + .padding(.top, geometry.windowControlsInset) + } + // 칸이 기본 폭보다 좁아도 잘라 내지 않고 지금 폭에 맞춰 배치 + .frame(width: paneWidth) + } +} + +// 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/UnreadPushCountFeature.swift b/Application/Presentation/Entry/Sources/Composition/UnreadPushCountFeature.swift new file mode 100644 index 00000000..61a73cfd --- /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/Sources/Dependency/PresentationDependencyPreparation.swift b/Application/Presentation/Entry/Sources/Dependency/PresentationDependencyPreparation.swift index 95d9caad..0cb344a0 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/Main/MainFeature.swift b/Application/Presentation/Entry/Sources/Main/MainFeature.swift deleted file mode 100644 index 172da32e..00000000 --- a/Application/Presentation/Entry/Sources/Main/MainFeature.swift +++ /dev/null @@ -1,338 +0,0 @@ -// -// MainFeature.swift -// Entry -// -// Created by opfic on 6/16/26. -// - -import Combine -import PresentationShared -import Core -import Domain -import Foundation -import SwiftUI -import UserNotifications - -@Reducer -struct MainFeature { - @ObservableState - struct State: Equatable { - @Presents var alert: AlertState? - var unreadPushCount = 0 - var isObservingUnreadPushCount = false - var windowControlsInset = CGFloat.zero - // Duo 세로 칸 자리의 양옆 안전 영역 - var verticalBarInsets = EdgeInsets() - // 화면 키보드가 떠 있는 동안 직접 그린 하단 탭 바를 숨김 - var isKeyboardVisible = false - // 탭 안 화면이 직접 그린 하단 탭 바 뒤로 들어가지 않도록 비울 높이 - var tabBarHeight = CGFloat.zero - var readableContentWidth = CGFloat.infinity - var openedTabs: Set = [] - var isSideBarCollapsed = false - // 사용자가 끌어서 정한 사이드바 폭, 정하지 않았으면 기본 폭 - var sideBarWidth: CGFloat? - var expandedSideBarGroups: Set = [] - var sideBarLocations: [MainTab: SideBarLocation] = [:] - var sideBarRequests: [MainTab: SideBarRequest] = [:] - // 칸에 작성 화면을 그린 탭, 덮는 화면처럼 닫기·저장 버튼으로 닫기 전에는 사이드바로 이동하지 않음 - var paneEditingTabs: Set = [] - var sideBarContent = SideBarContent() - var isDetailSideBarPresented = false - // 앱 화면과 분리해 창 전체에 표시하는 Mac 설정 화면 - var isSettingsPresented = false - // 창 전체 설정 화면에서 로그아웃, 회원 탈퇴나 그 알림창이 끝나지 않은 상태 - var isSettingsBusy = false - // 탭마다 세부 정보 사이드바 대상을 고르는 화면, 대상이 없어도 나타난 순서대로 위치 - var detailSideBarSelections: [MainTab: [DetailSideBarSelection]] = [:] - - // 탭마다 지금 고른 세부 정보 사이드바 대상, 대상을 고른 화면 중 가장 나중에 나타난 화면의 대상 - var detailSideBarTargets: [MainTab: DetailSideBarTarget] { - detailSideBarSelections.compactMapValues { $0.last { $0.target != nil }?.target } - } - } - - struct DetailSideBarSelection: Equatable { - let owner: UUID - var target: DetailSideBarTarget? - } - - enum KeyboardEvent: Equatable { - case willShow(height: CGFloat) - case willHide - } - - enum SideBarGroup: Hashable { - case todo - case developmentGoal - } - - enum Action: BindableAction, Equatable { - case alert(PresentationAction) - case binding(BindingAction) - case view(ViewAction) - case store(StoreAction) - - enum ViewAction: Equatable { - case onAppear - case selectedTabChanged(MainTab) - case sideBarLocationChanged(MainTab, SideBarLocation) - case sideBarContentChanged(SideBarContent) - case tapSideBarGroup(SideBarGroup) - case tapSideBarItem(MainTab, SideBarRequest.Action) - case paneEditingChanged(MainTab, Bool) - case sideBarResized(CGFloat) - case detailSideBarTargetChanged(MainTab, DetailSideBarTarget?, owner: UUID) - case detailSideBarOwnerRemoved(MainTab, 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 { - 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()) - 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) - 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 { - 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) - } - .merge(with: center.publisher(for: UIResponder.keyboardWillHideNotification).map { _ in .willHide }) - .eraseToAnyPublisher() - } - - static var testValue: @Sendable () -> AnyPublisher { - liveValue - } -} - -private extension MainFeature { - func observeKeyboardEffect() -> Effect { - .run { [keyboardEvents] send in - for await event in keyboardEvents().values { - await send(.store(.keyboardChanged(event))) - } - } - .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 - trackAnalyticsEventUseCase.execute(.screenView(screenName)) - } - } - - func updateBadgeCountEffect(_ count: Int) -> Effect { - .run { [setApplicationBadgeCount] _ in - do { - try await setApplicationBadgeCount(count) - } catch { - Logger(category: "MainFeature").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: "main_alert_badge_error_message", bundle: PresentationResources.bundle)) - } - } -} - -private extension MainTab { - 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/Sources/Main/MainView.swift b/Application/Presentation/Entry/Sources/Main/MainView.swift deleted file mode 100644 index bb7e2b77..00000000 --- a/Application/Presentation/Entry/Sources/Main/MainView.swift +++ /dev/null @@ -1,695 +0,0 @@ -// -// MainView.swift -// Entry -// -// Created by opfic on 5/8/25. -// - -import SwiftUI -import HomeTab -import NotificationTab -import ProfileTab -import PresentationShared -import TodayTab - -struct MainView: 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 - private let windowEvent: TodoEditorWindowEvent - // 목록 칸과 상세 칸이 함께 들어가는 화면 영역 폭 - private let splitMinimumWidth = CGFloat(800) - - init( - windowEvent: TodoEditorWindowEvent, - selectedTab: Binding - ) { - @Dependency(\.fetchSideBarWidthUseCase) var fetchSideBarWidthUseCase - var state = MainFeature.State() - state.sideBarWidth = fetchSideBarWidthUseCase.execute().map { CGFloat($0) } - self._store = State(initialValue: Store(initialState: state) { - MainFeature() - }) - self._selectedTab = selectedTab - self.windowEvent = windowEvent - } - - var body: some View { - let showsSideBar = isiOSAppOnMac || deviceType != .duo && horizontalSizeClass == .regular - let tabContentInset = horizontalSizeClass == .compact ? store.windowControlsInset : 0 - let readableContentWidth = showsSideBar ? store.readableContentWidth : .infinity - // iPhone, Duo, 좁은 iPad 창은 시스템 탭 바 대신 직접 그린 탭 사용 - let usesCustomTabBar = deviceType != .ipad || horizontalSizeClass == .compact - let isSystemTabBarHidden = showsSideBar || usesCustomTabBar - let verticalBarWidth = deviceType == .duo - ? max(store.verticalBarInsets.leading, store.verticalBarInsets.trailing) : 0 - // 시스템 탭 바처럼 키보드가 올라오면 키보드 뒤로 사라짐 - let showsTabBar = !showsSideBar && usesCustomTabBar && verticalBarWidth == 0 && !store.isKeyboardVisible - // 사이드바가 있는 창 오른쪽 세부 정보 사이드바, 설정 화면에서는 표시하지 않음 - let showsDetailSideBar = showsSideBar - && (store.sideBarLocations[selectedTab] ?? selectedTab.sideBarLocation) != .settings - let sideBarIdealWidth = isiOSAppOnMac ? 220 * AdaptiveSize.boardScale : 250 - let tabBarInset = showsTabBar ? store.tabBarHeight : 0 - - HStack(spacing: 0) { - if showsSideBar && !store.isSideBarCollapsed { - // 최소는 화살표와 아이콘만 보이는 폭, Mac 최대는 Orca 사이드바와 같은 폭 - TreeSideBar(selectedTab: $selectedTab, store: store) - .resizablePane( - width: store.sideBarWidth, - minimumWidth: isiOSAppOnMac ? 72 * AdaptiveSize.boardScale : 84, - idealWidth: sideBarIdealWidth, - maximumWidth: isiOSAppOnMac ? 500 * AdaptiveSize.boardScale : 320 - ) { width in - store.send(.view(.sideBarResized(width))) - } - // 칸 자르기 밖이라 잘리지 않도록 바탕은 칸 바깥에서 아래쪽 안전 영역까지 채움 - .background(Color.secondaryBackground, ignoresSafeAreaEdges: .bottom) - } - - ZStack { - // iPad는 시스템 탭 바를 쓰지 않아 Mac과 같이 구성 - // 넓은 창과 좁은 창을 오가도 탭 화면을 다시 만들지 않음 - if isiOSAppOnMac || deviceType == .ipad { - // 탭 전환 애니메이션 없이 한 번 연 탭을 유지하고 선택한 탭만 표시 - // 사이드바 하위 항목은 홈 화면이 알려 주므로 홈은 처음부터 생성 - ForEach(MainTab.allCases, id: \.self) { tab in - if store.openedTabs.contains(tab) || selectedTab == tab || tab == .home { - MainTabContent( - store: store, - tab: tab, - isSelected: selectedTab == tab, - isTabBarHidden: isSystemTabBarHidden, - tabBarInset: tabBarInset, - usesPaneLayout: showsSideBar, - windowControlsInset: tabContentInset, - readableContentWidth: readableContentWidth, - windowEvent: windowEvent - ) - .opacity(selectedTab == tab ? 1 : 0) - .allowsHitTesting(selectedTab == tab) - } - } - } else { - TabView(selection: $selectedTab) { - Tab( - MainTab.home.title, - systemImage: MainTab.home.symbolName, - value: MainTab.home - ) { - MainTabContent( - store: store, - tab: .home, - isSelected: selectedTab == .home, - isTabBarHidden: isSystemTabBarHidden, - tabBarInset: tabBarInset, - usesPaneLayout: showsSideBar, - windowControlsInset: tabContentInset, - readableContentWidth: readableContentWidth, - windowEvent: windowEvent - ) - } - Tab( - MainTab.today.title, - systemImage: MainTab.today.symbolName, - value: MainTab.today - ) { - MainTabContent( - store: store, - tab: .today, - isSelected: selectedTab == .today, - isTabBarHidden: isSystemTabBarHidden, - tabBarInset: tabBarInset, - usesPaneLayout: showsSideBar, - windowControlsInset: tabContentInset, - readableContentWidth: readableContentWidth, - windowEvent: windowEvent - ) - } - Tab( - MainTab.notification.title, - systemImage: MainTab.notification.symbolName, - value: MainTab.notification - ) { - MainTabContent( - store: store, - tab: .notification, - isSelected: selectedTab == .notification, - isTabBarHidden: isSystemTabBarHidden, - tabBarInset: tabBarInset, - usesPaneLayout: showsSideBar, - windowControlsInset: tabContentInset, - readableContentWidth: readableContentWidth, - windowEvent: windowEvent - ) - } - .badge(store.unreadPushCount) - Tab( - MainTab.profile.title, - systemImage: MainTab.profile.symbolName, - value: MainTab.profile - ) { - MainTabContent( - store: store, - tab: .profile, - isSelected: selectedTab == .profile, - isTabBarHidden: isSystemTabBarHidden, - tabBarInset: tabBarInset, - usesPaneLayout: showsSideBar, - windowControlsInset: tabContentInset, - readableContentWidth: readableContentWidth, - windowEvent: windowEvent - ) - } - } - } - } - .background { - ReadableContentWidthReader { width in - store.send(.binding(.set(\.readableContentWidth, width))) - } - } - // 접은 사이드바는 화면 칸 제목 줄의 버튼으로 다시 폄 - .environment( - \.expandSideBar, - store.isSideBarCollapsed ? { store.send(.binding(.set(\.isSideBarCollapsed, false))) } : nil - ) - .environment( - \.presentSettings, - showsSideBar ? { store.send(.binding(.set(\.isSettingsPresented, true))) } : nil - ) - // 닫힌 세부 정보 사이드바는 화면 칸 제목 줄의 버튼으로 엶 - .environment( - \.showDetailSideBar, - showsDetailSideBar && !store.isDetailSideBarPresented - ? { store.send(.binding(.set(\.isDetailSideBarPresented, true))) } : nil - ) - .environment(\.isDetailSideBarPresented, showsDetailSideBar && store.isDetailSideBarPresented) - .environment( - \.setDetailSideBarPresented, - showsDetailSideBar ? { store.send(.binding(.set(\.isDetailSideBarPresented, $0))) } : nil - ) - - // 칸 화면이 사이드바를 직접 그리면 창 사이드바는 표시하지 않음 - if showsDetailSideBar - && store.isDetailSideBarPresented - && store.detailSideBarTargets[selectedTab] != .hosted { - DetailSideBar( - target: store.detailSideBarTargets[selectedTab], - windowEvent: windowEvent - ) { - store.send(.binding(.set(\.isDetailSideBarPresented, false))) - } - } - } - // 사이드바가 있는 창의 설정은 앱 화면을 덮어 창 전체에 표시하고 닫으면 보던 화면으로 돌아감 - // 창이 좁아져도 진행 중인 로그아웃, 회원 탈퇴나 그 알림창이 끝날 때까지 표시 - .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) - } - } - // 세로로 펼친 Duo는 세로 막대가 없어 iPhone과 같은 화면 구성 - // 접힌 Duo는 세로 막대가 늘 있어 첫 화면이나 접는 중에도 바꾸지 않음 - .environment( - \.deviceType, - deviceType == .duo && horizontalSizeClass == .regular && verticalBarWidth == 0 - ? .bar : deviceType - ) - // iPad 상태 표시줄 영역, Mac 창 제목 줄과 사이드바, 화면 영역을 나누는 구분선 - // iPad는 상태 표시줄 영역 맨 아래에 두어 상태 표시줄이 없는 창에서는 창 밖에 위치 - // Mac은 화면 영역 맨 위가 제목 줄 바로 아래라서 그 자리에 배치 - .overlay(alignment: .top) { - if showsSideBar { - Rectangle() - .fill(Color.separator) - .frame(height: 1) - .offset(y: isiOSAppOnMac ? 0 : -1) - .allowsHitTesting(false) - } - } - .overlay { - if 0 < verticalBarWidth { - MainTabRail( - selectedTab: $selectedTab, - edge: store.verticalBarInsets.leading < store.verticalBarInsets.trailing ? .trailing : .leading, - width: verticalBarWidth, - unreadPushCount: store.unreadPushCount - ) - } - } - // Mac 창에서 상태 표시줄 자리로 비워 두는 상단 여백 제거 - .statusBarHidden(isiOSAppOnMac) - // iPad는 사이드바를 펴면 목록 칸과 상세 칸이 함께 들어가지 않는 창에서 사이드바를 접고 시작 - // 세로 화면처럼 좁은 창에서 상세 칸이 잘리지 않게 함 - .onGeometryChange(for: Bool.self) { proxy in - splitMinimumWidth + sideBarIdealWidth <= proxy.size.width - } action: { fitsSideBar in - guard !isiOSAppOnMac else { return } - store.send(.binding(.set(\.isSideBarCollapsed, !fitsSideBar))) - } - .onGeometryChange(for: CGFloat.self) { proxy in - proxy.windowControlsInset - } action: { inset in - store.send(.binding(.set(\.windowControlsInset, inset))) - } - .toastHost() - .safeAreaInset(edge: .bottom, spacing: 0) { - if showsTabBar { - MainTabBar( - selectedTab: $selectedTab, - axis: .horizontal, - unreadPushCount: store.unreadPushCount - ) - .padding(.horizontal, 8) - .padding(.top, 8) - .padding(.bottom, 4) - .background(Color.background, ignoresSafeAreaEdges: .bottom) - .overlay(alignment: .top) { - Rectangle() - .fill(Color.separator) - .frame(height: 1) - } - .onGeometryChange(for: CGFloat.self) { proxy in - proxy.size.height - } action: { height in - store.send(.binding(.set(\.tabBarHeight, height))) - } - } - } - .onGeometryChange(for: EdgeInsets.self) { proxy in - EdgeInsets( - top: 0, - leading: proxy.safeAreaInsets.leading, - bottom: 0, - trailing: proxy.safeAreaInsets.trailing - ) - } 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 { - store.send(.binding(.set(\.isSettingsPresented, false))) - } - } - .prominentAlert(store, state: \.alert, action: \.alert) - // 이 화면 알림창도 화면 안쪽 알림창과 같은 버튼 모양으로 표시 - .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 MainTabContent: View { - let store: StoreOf - let tab: MainTab - 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 MainTabRail: View { - @Binding var selectedTab: MainTab - let edge: HorizontalEdge - let width: CGFloat - let unreadPushCount: Int - - var body: some View { - MainTabBar( - 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: MainTab - 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([MainTab.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(MainTab.profile.title), - symbolName: MainTab.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/Root/Feature.swift b/Application/Presentation/Entry/Sources/Root/Feature.swift index 0c756845..c5fe27a2 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 selectedMainTab = MainTab.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) @@ -52,6 +53,7 @@ struct Feature { case networkStatusChanged(Bool) case setTheme(SystemTheme) case didLogined(Bool) + case sideBarWidthFetched(Double?) enum Alert: Equatable { case tapUpdateButton @@ -70,9 +72,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 +85,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 @@ -118,10 +120,15 @@ struct Feature { case .openWidgetRoute(let route): // 로그아웃 상태면 로그인 화면만 보이고 위젯 경로는 버림 guard state.signIn != false else { break } - // 로그인 여부를 확인하기 전이면 경로를 보관했다가 로그인 확인 뒤 적용 + // 로그인 여부를 확인하거나 앱 화면 상태를 만들기 전이면 경로를 보관했다가 만들 때 적용 state.widgetRoute = route - guard state.signIn == true else { break } - Self.applyWidgetRoute(route, to: &state) + guard state.signIn == true, state.composition != nil else { break } + 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,36 +141,49 @@ 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.selectedMainTab = .home + guard !wasSignedIn else { + // 앱 화면 상태를 만들기 전이면 만들 때 홈 탭으로 시작 + return state.composition == nil ? .none : .send(.composition(.selectTab(.home))) + } + // 사용자가 정한 사이드바 폭을 읽은 뒤 앱 화면 상태를 만듦 + return .run { [fetchSideBarWidthUseCase] send in + await send(.sideBarWidthFetched(fetchSideBarWidthUseCase.execute())) } } else { + state.composition = nil state.widgetRoute = nil return .merge( trackLoginScreenEffect(), 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 } + .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.selectedMainTab = 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 b3261c6e..bd0ae654 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 { - MainView( - windowEvent: windowEvent, - selectedTab: $store.selectedMainTab - ) - } 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/MainTab.swift b/Application/Presentation/Entry/Sources/Routing/AppTab.swift similarity index 75% rename from Application/Presentation/Entry/Sources/Routing/MainTab.swift rename to Application/Presentation/Entry/Sources/Routing/AppTab.swift index 0db358bd..a911aa3c 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 @@ -54,18 +54,3 @@ public enum MainTab: Hashable, CaseIterable { } } } - -extension SideBarLocation { - var tab: MainTab { - 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/Sources/Routing/WidgetRoute.swift b/Application/Presentation/Entry/Sources/Routing/WidgetRoute.swift index ba4f714b..328c850c 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/Composition/CompositionFeatureTestSupport.swift b/Application/Presentation/Entry/Tests/Composition/CompositionFeatureTestSupport.swift new file mode 100644 index 00000000..418a9e47 --- /dev/null +++ b/Application/Presentation/Entry/Tests/Composition/CompositionFeatureTestSupport.swift @@ -0,0 +1,193 @@ +// +// 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 + } +} + +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]() + + 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 new file mode 100644 index 00000000..bbffb1db --- /dev/null +++ b/Application/Presentation/Entry/Tests/Composition/CompositionFeatureTests.swift @@ -0,0 +1,284 @@ +// +// CompositionFeatureTests.swift +// EntryTests +// +// Created by opfic on 6/16/26. +// + +import Core +import PresentationShared +import Foundation +import Testing +@testable import Entry +@testable import ProfileTab + +@MainActor +struct CompositionFeatureTests { + @Test("CompositionFeature는 시작하면 unread count 관찰을 시작한다") + func CompositionFeature는_시작하면_unread_count_관찰을_시작한다() async { + let unreadPushCountUseCase = ObserveUnreadPushCountUseCaseSpy() + let store = makeStore(unreadPushCountUseCase: unreadPushCountUseCase) + + await store.send(.start) + await waitUntil { + unreadPushCountUseCase.observeCallCount == 1 + } + + #expect(unreadPushCountUseCase.observeCallCount == 1) + } + + @Test("CompositionFeature는 기존 상태관리처럼 notification 탭을 제외한 화면 전환을 추적한다") + func CompositionFeature는_기존_상태관리처럼_notification_탭을_제외한_화면_전환을_추적한다() async { + let reference = StateManagementReference() + let trackAnalyticsEventUseCase = CompositionTrackAnalyticsEventUseCaseSpy() + 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(.start) { + $0.openedTabs = [.home] + } + await waitUntil { + trackAnalyticsEventUseCase.screenNames == ["home"] + } + // 이미 고른 탭을 다시 고르면 다시 추적하지 않음 + await store.send(.selectTab(.home)) + await store.send(.selectTab(.today)) { + $0.selectedTab = .today + $0.openedTabs = [.home, .today] + } + await waitUntil { + trackAnalyticsEventUseCase.screenNames == ["home", "today"] + } + await store.send(.selectTab(.notification)) { + $0.selectedTab = .notification + $0.openedTabs = [.home, .today, .notification] + } + await store.send(.selectTab(.profile)) { + $0.selectedTab = .profile + $0.openedTabs = [.home, .today, .notification, .profile] + } + await waitUntil { + trackAnalyticsEventUseCase.screenNames == ["home", "today", "profile"] + } + + #expect(expectedEffects == [ + [.observeUnreadPushCount], + [.trackScreenView("home")], + [.trackScreenView("today")], + [], + [.trackScreenView("profile")] + ]) + #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() + + 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는 창이 좁아지면 설정을 이어서 표시할 프로필 탭을 유지한다") + 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는 창 폭이 바뀔 때는 계정 화면의 창 정보를 유지하고 계정 화면을 나가면 지운다") + 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() + + await store.send(.store(.keyboardChanged(.willShow(height: 0)))) + + #expect(!store.state.isKeyboardVisible) + + await store.send(.store(.keyboardChanged(.willShow(height: 300)))) { + $0.isKeyboardVisible = true + } + await store.send(.store(.keyboardChanged(.willHide))) { + $0.isKeyboardVisible = false + } + } +} diff --git a/Application/Presentation/Entry/Tests/Composition/DetailSideBarFeatureTests.swift b/Application/Presentation/Entry/Tests/Composition/DetailSideBarFeatureTests.swift new file mode 100644 index 00000000..e5b39dfb --- /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 00000000..b236fb98 --- /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 00000000..4d99b69a --- /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) + } +} diff --git a/Application/Presentation/Entry/Tests/Main/MainFeatureTests.swift b/Application/Presentation/Entry/Tests/Main/MainFeatureTests.swift deleted file mode 100644 index d16ac766..00000000 --- a/Application/Presentation/Entry/Tests/Main/MainFeatureTests.swift +++ /dev/null @@ -1,411 +0,0 @@ -// -// MainFeatureTests.swift -// EntryTests -// -// Created by opfic on 6/16/26. -// - -import Combine -import PresentationShared -import Domain -import Foundation -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() - let store = makeStore(unreadPushCountUseCase: unreadPushCountUseCase) - - let firstEffects = reference.reduce(.onAppear) - let secondEffects = reference.reduce(.onAppear) - await store.send(.view(.onAppear)) { - $0.isObservingUnreadPushCount = true - } - await store.send(.view(.onAppear)) - - #expect(firstEffects == [.observeUnreadPushCount]) - #expect(secondEffects.isEmpty) - #expect(unreadPushCountUseCase.observeCallCount == 1) - } - - @Test("MainFeature는 기존 Main 상태관리처럼 notification 탭을 제외한 화면 전환을 추적한다") - func MainFeature는_기존_Main_상태관리처럼_notification_탭을_제외한_화면_전환을_추적한다() async { - let reference = MainStateManagementReference() - let trackAnalyticsEventUseCase = MainTrackAnalyticsEventUseCaseSpy() - let store = makeStore(trackAnalyticsEventUseCase: trackAnalyticsEventUseCase) - - let expectedEffects = [ - reference.reduce(.selectedTabChanged(.home)), - reference.reduce(.selectedTabChanged(.today)), - reference.reduce(.selectedTabChanged(.notification)), - reference.reduce(.selectedTabChanged(.profile)) - ] - await store.send(.view(.selectedTabChanged(.home))) { - $0.openedTabs = [.home] - } - await store.send(.view(.selectedTabChanged(.today))) { - $0.openedTabs = [.home, .today] - } - await store.send(.view(.selectedTabChanged(.notification))) { - $0.openedTabs = [.home, .today, .notification] - } - await store.send(.view(.selectedTabChanged(.profile))) { - $0.openedTabs = [.home, .today, .notification, .profile] - } - await waitUntil { - trackAnalyticsEventUseCase.screenNames == ["home", "today", "profile"] - } - - #expect(expectedEffects == [ - [.trackScreenView("home")], - [.trackScreenView("today")], - [], - [.trackScreenView("profile")] - ]) - #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() - 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("MainFeature는 기존 Main 상태관리처럼 alert 표시 여부와 문구를 함께 갱신한다") - func MainFeature는_기존_Main_상태관리처럼_alert_state를_갱신한다() async { - let reference = MainStateManagementReference() - 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 == expectedMainErrorAlert()) - } - - @Test("MainFeature는 기존 Main 상태관리처럼 unread count 관찰 시작 실패 시 alert를 표시한다") - func MainFeature는_기존_Main_상태관리처럼_unread_count_관찰_시작_실패_시_alert를_표시한다() async { - let reference = MainStateManagementReference() - let unreadPushCountUseCase = MainObserveUnreadPushCountUseCaseSpy(error: MainTestError.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("MainFeature는 다른 경로로 하위 항목에 들어오면 그 묶음을 펼치고 묶음을 접어도 위치를 유지한다") - func MainFeature는_다른_경로로_하위_항목에_들어오면_그_묶음을_펼치고_묶음을_접어도_위치를_유지한다() 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("MainFeature는 사라지는 화면이 다른 화면이 고른 세부 정보 사이드바 대상을 지우지 않게 한다") - func MainFeature는_사라지는_화면이_다른_화면이_고른_세부_정보_사이드바_대상을_지우지_않게_한다() 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("MainFeature는 위 화면이 사라지면 아래 화면이 고른 세부 정보 사이드바 대상을 다시 표시한다") - func MainFeature는_위_화면이_사라지면_아래_화면이_고른_세부_정보_사이드바_대상을_다시_표시한다() 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("MainFeature는 먼저 나타난 화면이 나중에 대상을 골라도 나중에 나타난 화면의 대상을 유지한다") - func MainFeature는_먼저_나타난_화면이_나중에_대상을_골라도_나중에_나타난_화면의_대상을_유지한다() 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("MainFeature는 칸에 작성 화면을 그린 탭의 사이드바 이동 요청을 무시한다") - func MainFeature는_칸에_작성_화면을_그린_탭의_사이드바_이동_요청을_무시한다() async { - let store = TestStore(initialState: MainFeature.State()) { - MainFeature() - } 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("MainFeature는 화면 회전 때 오는 높이 0인 키보드 표시 알림을 무시한다") - func MainFeature는_화면_회전_때_오는_높이_0인_키보드_표시_알림을_무시한다() async { - let store = makeStore() - - await store.send(.store(.keyboardChanged(.willShow(height: 0)))) - - #expect(!store.state.isKeyboardVisible) - - await store.send(.store(.keyboardChanged(.willShow(height: 300)))) { - $0.isKeyboardVisible = true - } - await store.send(.store(.keyboardChanged(.willHide))) { - $0.isKeyboardVisible = false - } - } - - @Test("MainFeature는 unread count 관찰 값을 기존 Main 상태관리의 setUnreadPushCount 상태 변화로 반영한다") - func MainFeature는_unread_count_관찰_값을_기존_Main_상태관리의_setUnreadPushCount_상태_변화로_반영한다() async { - let reference = MainStateManagementReference() - let subject = PassthroughSubject() - let unreadPushCountUseCase = MainObserveUnreadPushCountUseCaseSpy(publisher: subject.eraseToAnyPublisher()) - let badgeCountSpy = MainApplicationBadgeCountSpy() - 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 = MainObserveUnreadPushCountUseCaseSpy(), - trackAnalyticsEventUseCase: TrackAnalyticsEventUseCase = MainTrackAnalyticsEventUseCaseSpy(), - badgeCountSpy: MainApplicationBadgeCountSpy = MainApplicationBadgeCountSpy() -) -> TestStoreOf { - let store = TestStore(initialState: MainFeature.State()) { - MainFeature() - } 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 MainStateManagementReference { - struct State: Equatable { - var alert: AlertState? - var unreadPushCount = 0 - } - - enum Action { - case onAppear - case selectedTabChanged(MainTab) - 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 = expectedMainErrorAlert() - } -} - -private func expectedMainErrorAlert() -> 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: "main_alert_badge_error_message", bundle: PresentationResources.bundle)) - } -} - -private final class MainObserveUnreadPushCountUseCaseSpy: 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 MainTrackAnalyticsEventUseCaseSpy: 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 MainApplicationBadgeCountSpy: @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 MainTestError: Error { - case failure -} - -private extension MainTab { - 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/Root/FeatureTestSupport.swift b/Application/Presentation/Entry/Tests/Root/FeatureTestSupport.swift index a0a9d2c9..9647b2a1 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,11 +51,12 @@ struct RootStoreTestAdapter: RootStateDriving { isNetworkConnected: store.state.isNetworkConnected, signIn: store.state.signIn, theme: store.state.theme, - selectedMainTab: store.state.selectedMainTab + selectedTab: store.state.composition?.selectedTab ) } 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,6 +89,8 @@ struct RootStoreTestAdapter: RootStateDriving { $0.setApplicationBadgeCount = { count in try await badgeCountSpy.setBadgeCount(count) } + $0.fetchSideBarWidthUseCase = RootFetchSideBarWidthUseCaseStub(width: sideBarWidth) + $0.observeUnreadPushCountUseCase = ObserveUnreadPushCountUseCaseSpy() } store.exhaustivity = .off(showSkippedAssertions: false) } @@ -114,6 +118,7 @@ struct RootStoreTestAdapter: RootStateDriving { func didLogined(_ signIn: Bool) async { await store.send(.didLogined(signIn)) + await drainReceivedActions() } func presentTodoDetail(_ todoId: String) async { @@ -124,12 +129,13 @@ 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(.composition(.selectTab(tab))) } func openWidgetRoute(_ route: WidgetRoute) async { await store.send(.openWidgetRoute(route)) + await drainReceivedActions() } func tapUpdateButton() async { @@ -161,7 +167,7 @@ func verifyNetworkDisconnectedAlert(adapter: some RootStateDriving) async { isNetworkConnected: false, signIn: nil, theme: .automatic, - selectedMainTab: .home + selectedTab: nil ) ) } @@ -179,7 +185,7 @@ func verifySetAlert(adapter: some RootStateDriving) async { isNetworkConnected: false, signIn: nil, theme: .automatic, - selectedMainTab: .home + selectedTab: nil ) ) } @@ -190,7 +196,6 @@ func verifyThemeUpdate(adapter: some RootStateDriving) async { #expect(adapter.snapshot.theme == .dark) #expect(adapter.snapshot.alertTitle == nil) - #expect(adapter.snapshot.selectedMainTab == .home) } @MainActor @@ -204,7 +209,7 @@ func verifyDidLoginedFalse( } #expect(adapter.snapshot.signIn == false) - #expect(adapter.snapshot.selectedMainTab == .home) + #expect(adapter.snapshot.selectedTab == nil) #expect(trackAnalyticsEventUseCaseSpy.screenNames == ["login"]) } @@ -213,12 +218,21 @@ func verifyDidLoginedTrue( adapter: some RootStateDriving, trackAnalyticsEventUseCaseSpy: RootTrackAnalyticsEventUseCaseSpy ) async { - await adapter.selectMainTab(.today) await adapter.didLogined(true) #expect(adapter.snapshot.signIn == true) - #expect(adapter.snapshot.selectedMainTab == .home) - #expect(trackAnalyticsEventUseCaseSpy.screenNames.isEmpty) + #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) } @MainActor @@ -247,7 +261,7 @@ func verifyObservedInitialValues(adapter: some RootStateDriving) async { isNetworkConnected: false, signIn: false, theme: .dark, - selectedMainTab: .home + selectedTab: nil ) ) } @@ -264,17 +278,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 == nil) #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") } @@ -353,6 +367,14 @@ actor RootCheckAppUpdateUseCaseSpy: CheckAppUpdateUseCase { } } +struct RootFetchSideBarWidthUseCaseStub: FetchSideBarWidthUseCase { + let width: Double? + + func execute() -> Double? { + width + } +} + actor RootOpenURLSpy { private var urls = [URL]() diff --git a/Application/Presentation/Entry/Tests/Root/FeatureTests.swift b/Application/Presentation/Entry/Tests/Root/FeatureTests.swift index 76eb5c07..8d25371f 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 { @@ -54,8 +55,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 +196,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 +210,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 +230,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,16 +242,39 @@ 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") } + + @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 { diff --git a/Application/Presentation/PresentationShared/Resources/Localizable.xcstrings b/Application/Presentation/PresentationShared/Resources/Localizable.xcstrings index c5fd1abf..398a6fc2 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" : { diff --git a/Application/Presentation/PresentationShared/Sources/Common/SideBarNavigation.swift b/Application/Presentation/PresentationShared/Sources/Common/SideBarNavigation.swift index 770cf336..08ddfe9e 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 b7383744..b0d27a4f 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 66f948ec..fa54593f 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 3bae85ee..9f98abcb 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 f0c0a67c..7ee2fead 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 07004043..3e6f3d63 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 70603ce6..d9301efd 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 5f556265..13775fc8 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