diff --git a/Application/Presentation/Entry/Sources/Common/Component/SplitShell.swift b/Application/Presentation/Entry/Sources/Common/Component/SplitShell.swift index 35368301f..e47ada705 100644 --- a/Application/Presentation/Entry/Sources/Common/Component/SplitShell.swift +++ b/Application/Presentation/Entry/Sources/Common/Component/SplitShell.swift @@ -6,33 +6,54 @@ // import SwiftUI +import PresentationShared -// 왼쪽, 가운데, 오른쪽 자리와 창 전체를 덮는 자리만 있는 껍데기 +// 가운데, 왼쪽, 오른쪽 자리와 창 전체를 덮는 자리만 있는 껍데기 // 자리마다 어떤 화면이 언제 나올지는 쓰는 쪽에서 결정 -struct SplitShell: View { - private let left: Left - private let center: Center - private let right: Right +struct SplitShell: View { + // 왼쪽 자리를 켜 둔 상태, 켜고 끄는 바인딩으로 가운데와 왼쪽 클로저에 넘김 + @State private var isLeftOn = true + // 오른쪽 자리를 켜 둔 상태, 켜고 끄는 바인딩으로 가운데와 오른쪽 클로저에 넘김 + @State private var isRightOn = false + // 가운데 화면이 올린 세부 정보 사이드바 내용, 오른쪽 자리에 그릴지는 쓰는 쪽에서 결정 + @State private var rightContent: DetailSideBarContent? + // 이 폭보다 좁아지면 왼쪽 자리를 끄고 넓어지면 켬, 없으면 창 폭으로 바꾸지 않음 + private let leftFitWidth: CGFloat? + private let center: (_ isLeftOn: Binding, _ isRightOn: Binding) -> Center + private let left: (Binding) -> Left + private let right: (DetailSideBarContent?, Binding) -> Right private let overlay: Overlay init( - @ViewBuilder left: () -> Left, - @ViewBuilder center: () -> Center, - @ViewBuilder right: () -> Right, + leftFitWidth: CGFloat? = nil, + @ViewBuilder center: @escaping (_ isLeftOn: Binding, _ isRightOn: Binding) -> Center, + @ViewBuilder left: @escaping (Binding) -> Left, + @ViewBuilder right: @escaping (DetailSideBarContent?, Binding) -> Right, @ViewBuilder overlay: () -> Overlay ) { - self.left = left() - self.center = center() - self.right = right() + self.leftFitWidth = leftFitWidth + self.center = center + self.left = left + self.right = right self.overlay = overlay() } var body: some View { HStack(spacing: 0) { - left - center - right + left($isLeftOn) + center($isLeftOn, $isRightOn) + .onPreferenceChange(DetailSideBarContentPreferenceKey.self) { content in + rightContent = content + } + right(rightContent, $isRightOn) } .overlay { overlay } + .onGeometryChange(for: Bool?.self) { proxy in + leftFitWidth.map { $0 <= proxy.size.width } + } action: { fits in + if let fits { + isLeftOn = fits + } + } } } diff --git a/Application/Presentation/Entry/Sources/Composition/CompositionFeature.swift b/Application/Presentation/Entry/Sources/Composition/CompositionFeature.swift index 01c87bb85..392cd2ec5 100644 --- a/Application/Presentation/Entry/Sources/Composition/CompositionFeature.swift +++ b/Application/Presentation/Entry/Sources/Composition/CompositionFeature.swift @@ -31,7 +31,6 @@ struct CompositionFeature { // 앱 화면과 분리해 창 전체에 표시하는 설정 화면, 좁아진 창에서는 프로필 화면에 이어서 표시 var isSettingsPresented = false var sideBar = SideBarFeature.State() - var detailSideBar = DetailSideBarFeature.State() var unreadPushCount = UnreadPushCountFeature.State() // 창 폭이 바뀌어도 보던 항목과 진행 중인 로그아웃, 회원 탈퇴를 이어 가게 화면보다 위에서 보관 var settings = SettingsFeature.State() @@ -54,7 +53,6 @@ struct CompositionFeature { 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) @@ -80,9 +78,6 @@ struct CompositionFeature { Scope(state: \.sideBar, action: \.sideBar) { SideBarFeature() } - Scope(state: \.detailSideBar, action: \.detailSideBar) { - DetailSideBarFeature() - } Scope(state: \.unreadPushCount, action: \.unreadPushCount) { UnreadPushCountFeature() } @@ -111,13 +106,13 @@ struct CompositionFeature { return selectTabEffect(tab, state: &state) case .sideBar(.tapSettings): return .send(.settings(.open)) - case .sideBar, .detailSideBar, .unreadPushCount: + case .sideBar, .unreadPushCount: break case .settings(.open): state.isSettingsPresented = true case .settings(.close): state.isSettingsPresented = false - case .settings(.binding(\.screen)): + case .settings(.binding(\.isListPushed)): guard state.settings.screen == nil, state.isSettingsPresented else { break } // 좁아진 창에서 설정을 닫으면 설정 아래에 있던 프로필 화면 표시 state.isSettingsPresented = false diff --git a/Application/Presentation/Entry/Sources/Composition/CompositionView.swift b/Application/Presentation/Entry/Sources/Composition/CompositionView.swift index 3d2febfd6..497bd303d 100644 --- a/Application/Presentation/Entry/Sources/Composition/CompositionView.swift +++ b/Application/Presentation/Entry/Sources/Composition/CompositionView.swift @@ -41,26 +41,9 @@ struct CompositionView: View { // 사이드바가 있는 창에서 연 설정은 좁아지면 고른 탭을 바꾸지 않고 프로필 화면에 이어서 표시 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: { + // iPad는 사이드바를 펴면 목록 칸과 상세 칸이 함께 들어가지 않는 창에서 사이드바를 접고 시작 + // 세로 화면처럼 좁은 창에서 상세 칸이 잘리지 않게 함 + SplitShell(leftFitWidth: isiOSAppOnMac ? nil : splitMinimumWidth + sideBarIdealWidth) { $isSideBarOn, $isDetailSideBarOn in ZStack { // iPad는 시스템 탭 바를 쓰지 않아 Mac과 같이 구성 // 넓은 창과 좁은 창을 오가도 탭 화면을 다시 만들지 않음 @@ -110,31 +93,42 @@ struct CompositionView: View { } } // 접은 사이드바는 화면 칸 제목 줄의 버튼으로 다시 폄 - .environment( - \.expandSideBar, - store.sideBar.isCollapsed ? { store.send(.sideBar(.binding(.set(\.isCollapsed, false)))) } : nil - ) + .environment(\.expandSideBar, isSideBarOn ? nil : { isSideBarOn = true }) // 닫힌 세부 정보 사이드바는 화면 칸 제목 줄의 버튼으로 엶 - .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 + .environment(\.showDetailSideBar, showsSideBar && !isDetailSideBarOn ? { isDetailSideBarOn = true } : nil) + .environment(\.setDetailSideBarPresented, showsSideBar ? { isDetailSideBarOn = $0 } : nil) + } left: { $isSideBarOn in + if showsSideBar && isSideBarOn { + // 최소는 화살표와 아이콘만 보이는 폭, Mac 최대는 Orca 사이드바와 같은 폭 + TreeSideBar( + store: store.scope(state: \.sideBar, action: \.sideBar), + selectedTab: selectedTab, + unreadPushCount: store.unreadPushCount.count ) { - store.send(.detailSideBar(.binding(.set(\.isPresented, false)))) + isSideBarOn = false + } + .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) + } + } right: { content, $isDetailSideBarOn in + // 탭 화면이 올린 내용, 올린 내용이 없으면 안내 표시 + if showsSideBar && isDetailSideBarOn { + DetailSideBar { + isDetailSideBarOn = false + } content: { + if let content { + content + } else { + DetailSideBarPlaceholder() + } } } } overlay: { @@ -178,14 +172,6 @@ struct CompositionView: View { } // 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 diff --git a/Application/Presentation/Entry/Sources/Composition/DetailSideBarFeature.swift b/Application/Presentation/Entry/Sources/Composition/DetailSideBarFeature.swift deleted file mode 100644 index 72e3474cf..000000000 --- a/Application/Presentation/Entry/Sources/Composition/DetailSideBarFeature.swift +++ /dev/null @@ -1,59 +0,0 @@ -// -// DetailSideBarFeature.swift -// Entry -// -// Created by opfic on 11/25/26. -// - -import Foundation -import PresentationShared - -@Reducer -struct DetailSideBarFeature { - @ObservableState - struct State: Equatable { - var isPresented = false - // 탭마다 대상을 고르는 화면, 대상이 없어도 나타난 순서대로 위치 - var selections: [AppTab: [Selection]] = [:] - - // 탭마다 지금 고른 대상, 대상을 고른 화면 중 가장 나중에 나타난 화면의 대상 - var targets: [AppTab: DetailSideBarTarget] { - selections.compactMapValues { $0.last { $0.target != nil }?.target } - } - } - - struct Selection: Equatable { - let owner: UUID - var target: DetailSideBarTarget? - } - - enum Action: BindableAction, Equatable { - case binding(BindingAction) - case targetChanged(AppTab, DetailSideBarTarget?, owner: UUID) - case ownerRemoved(AppTab, owner: UUID) - } - - var body: some ReducerOf { - BindingReducer() - Reduce { state, action in - switch action { - case .binding: - break - case .targetChanged(let tab, let target, let owner): - // 대상을 바꿔도 화면이 나타난 순서의 자리 유지 - var selections = state.selections[tab, default: []] - if let index = selections.firstIndex(where: { $0.owner == owner }) { - selections[index].target = target - } else { - selections.append(Selection(owner: owner, target: target)) - } - state.selections[tab] = selections - case .ownerRemoved(let tab, let owner): - // 사라지는 화면은 자기 자리만 지우고, 그 아래 화면이 고른 대상을 다시 표시 - state.selections[tab]?.removeAll { $0.owner == owner } - } - - return .none - } - } -} diff --git a/Application/Presentation/Entry/Sources/Composition/SideBarFeature.swift b/Application/Presentation/Entry/Sources/Composition/SideBarFeature.swift index 628221465..d97b8f74b 100644 --- a/Application/Presentation/Entry/Sources/Composition/SideBarFeature.swift +++ b/Application/Presentation/Entry/Sources/Composition/SideBarFeature.swift @@ -18,7 +18,6 @@ struct SideBarFeature { @ObservableState struct State: Equatable { - var isCollapsed = false // 사용자가 끌어서 정한 폭, 정하지 않았으면 기본 폭 var width: CGFloat? var expandedGroups: Set = [] diff --git a/Application/Presentation/Entry/Sources/Composition/TabScreen.swift b/Application/Presentation/Entry/Sources/Composition/TabScreen.swift index e304ad0de..956707ac0 100644 --- a/Application/Presentation/Entry/Sources/Composition/TabScreen.swift +++ b/Application/Presentation/Entry/Sources/Composition/TabScreen.swift @@ -25,9 +25,12 @@ struct TabScreen: 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))) } + // 고른 탭 화면이 올린 세부 정보 사이드바 내용만 창에 전달 + .transformPreference(DetailSideBarContentPreferenceKey.self) { content in + if !isSelected { + content = nil + } + } .onPreferenceChange(SideBarLocationPreferenceKey.self) { location in guard let location else { return } store.send(.sideBar(.locationChanged(tab, location))) @@ -57,7 +60,7 @@ struct TabScreen: View { windowEvent: windowEvent ) case .notification: - PushNotificationListView(isSelected: isSelected) + PushNotificationListView(isSelected: isSelected, windowEvent: windowEvent) case .profile: ProfileView( isSelected: isSelected, diff --git a/Application/Presentation/Entry/Sources/Composition/TreeSideBar.swift b/Application/Presentation/Entry/Sources/Composition/TreeSideBar.swift index e489874de..405cc0311 100644 --- a/Application/Presentation/Entry/Sources/Composition/TreeSideBar.swift +++ b/Application/Presentation/Entry/Sources/Composition/TreeSideBar.swift @@ -15,13 +15,15 @@ struct TreeSideBar: View { let store: StoreOf let selectedTab: AppTab let unreadPushCount: Int + // 사이드바를 접는 동작 + let onCollapse: () -> Void 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))) + onCollapse() } label: { Image(systemName: "sidebar.left") } diff --git a/Application/Presentation/Entry/Sources/Root/Feature.swift b/Application/Presentation/Entry/Sources/Root/Feature.swift index c5fe27a28..11106d109 100644 --- a/Application/Presentation/Entry/Sources/Root/Feature.swift +++ b/Application/Presentation/Entry/Sources/Root/Feature.swift @@ -22,7 +22,8 @@ struct Feature { @ObservableState struct State: Equatable { @Presents var alert: AlertState? - @Presents var sheet: SheetState? + // 위젯과 푸시 알림으로 연 보기 전용 Todo 상세 + @Presents var sheet: TodoDetailFeature.State? var hasCheckedAppUpdate = false var isAppUpdateRequired = false var isNetworkConnected = true @@ -36,17 +37,11 @@ struct Feature { var isObservingTheme = false } - @ObservableState - struct SheetState: Equatable, Identifiable { - let todoId: String - var id: String { todoId } - } - enum Action: Equatable { case alert(PresentationAction) case appUpdateCheckCompleted(Bool) case composition(CompositionFeature.Action) - case sheet(PresentationAction) + case sheet(PresentationAction) case onAppear case presentTodoDetail(String) case openWidgetRoute(WidgetRoute) @@ -58,10 +53,6 @@ struct Feature { enum Alert: Equatable { case tapUpdateButton } - - enum Sheet: Equatable { - case tapCloseButton - } } @Dependency(\.observeAuthSessionUseCase) var observeAuthSessionUseCase @@ -87,8 +78,6 @@ struct Feature { state.alert = Self.appUpdateAlertState() case .composition: break - case .sheet(.dismiss), .sheet(.presented(.tapCloseButton)): - state.sheet = nil case .sheet: break case .onAppear: @@ -116,7 +105,7 @@ struct Feature { return effect case .presentTodoDetail(let todoId): - state.sheet = .init(todoId: todoId) + state.sheet = TodoDetailFeature.State(todoId: todoId, showEditButton: false) case .openWidgetRoute(let route): // 로그아웃 상태면 로그인 화면만 보이고 위젯 경로는 버림 guard state.signIn != false else { break } @@ -127,7 +116,7 @@ struct Feature { case .tab(let tab): return .send(.composition(.selectTab(tab))) case .todayTodo(let id): - state.sheet = .init(todoId: id) + state.sheet = TodoDetailFeature.State(todoId: id, showEditButton: false) } case .networkStatusChanged(let isConnected): let wasConnected = state.isNetworkConnected @@ -166,7 +155,7 @@ struct Feature { case .tab(let tab): composition.selectedTab = tab case .todayTodo(let id): - state.sheet = .init(todoId: id) + state.sheet = TodoDetailFeature.State(todoId: id, showEditButton: false) case nil: break } @@ -181,20 +170,11 @@ struct Feature { } .ifLet(\.$alert, action: \.alert) .ifLet(\.$sheet, action: \.sheet) { - SheetFeature() + TodoDetailFeature() } } } -private struct SheetFeature: Reducer { - typealias State = Feature.SheetState - typealias Action = Feature.Action.Sheet - - var body: some ReducerOf { - EmptyReducer() - } -} - extension DependencyValues { var appStoreURL: URL? { get { self[AppStoreURLKey.self] } diff --git a/Application/Presentation/Entry/Sources/Root/RootView.swift b/Application/Presentation/Entry/Sources/Root/RootView.swift index bd0ae654e..63ad57a0c 100644 --- a/Application/Presentation/Entry/Sources/Root/RootView.swift +++ b/Application/Presentation/Entry/Sources/Root/RootView.swift @@ -48,7 +48,13 @@ public struct RootView: View { } .prominentAlert(store, state: \.alert, action: \.alert) .prominentSheet(item: $store.scope(state: \.sheet, action: \.sheet)) { sheetStore in - sheetContent(todoId: sheetStore.todoId) + NavigationStack { + TodoDetailView(store: sheetStore) + } + // 시트가 떠 있는 동안 다른 Todo를 열면 화면을 다시 만들어 그 Todo를 조회 + .id(sheetStore.todoId) + .environment(\.deviceType, .bar) + .background(Color.background) } .onReceive(pushNotificationTodoIdPublisher) { todoId in store.send(.presentTodoDetail(todoId)) @@ -57,16 +63,4 @@ public struct RootView: View { // 글자 크기를 정하지 않은 글자도 Mac 크기로 표시 .font(AdaptiveSize.macFontSize(.body).map { .system(size: $0) }) } - - private func sheetContent(todoId: String) -> some View { - NavigationStack { - TodoDetailView(store: Store( - initialState: TodoDetailFeature.State(todoId: todoId, showEditButton: false) - ) { - TodoDetailFeature() - }) - } - .environment(\.deviceType, .bar) - .background(Color.background) - } } diff --git a/Application/Presentation/Entry/Tests/Composition/CompositionFeatureTests.swift b/Application/Presentation/Entry/Tests/Composition/CompositionFeatureTests.swift index bbffb1db8..b3714609c 100644 --- a/Application/Presentation/Entry/Tests/Composition/CompositionFeatureTests.swift +++ b/Application/Presentation/Entry/Tests/Composition/CompositionFeatureTests.swift @@ -151,12 +151,12 @@ struct CompositionFeatureTests { 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)))) + await store.send(.settings(.binding(.set(\.pushedRoute, nil)))) #expect(store.state.isSettingsPresented) #expect(store.state.selectedTab == .home) - await store.send(.settings(.binding(.set(\.screen, nil)))) + await store.send(.settings(.binding(.set(\.isListPushed, false)))) #expect(!store.state.isSettingsPresented) #expect(store.state.selectedTab == .profile) diff --git a/Application/Presentation/Entry/Tests/Composition/DetailSideBarFeatureTests.swift b/Application/Presentation/Entry/Tests/Composition/DetailSideBarFeatureTests.swift deleted file mode 100644 index e5b39dfb0..000000000 --- a/Application/Presentation/Entry/Tests/Composition/DetailSideBarFeatureTests.swift +++ /dev/null @@ -1,74 +0,0 @@ -// -// 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/HomeTab/Sources/Category/CategoryManageFeature.swift b/Application/Presentation/HomeTab/Sources/Category/CategoryManageFeature.swift index 634143e41..d2ff84957 100644 --- a/Application/Presentation/HomeTab/Sources/Category/CategoryManageFeature.swift +++ b/Application/Presentation/HomeTab/Sources/Category/CategoryManageFeature.swift @@ -15,6 +15,8 @@ struct CategoryManageFeature { struct State: Equatable { @Presents var categorySheet: CategorySheetState? @Presents var alert: AlertState? + // 추가하거나 고칠 카테고리를 세부 정보 사이드바에 보여 달라고 한 횟수, 바뀌면 닫힌 세부 정보 사이드바를 엶 + var revealCount = 0 var preferences: [TodoCategoryItem] } @@ -128,6 +130,7 @@ struct CategoryManageFeature { case .categorySheet: break case .tapAddUserCategory: + state.revealCount += 1 if let randomHexValue = Color.randomValue.hexValue { // 목록에 새 카테고리를 바로 만들고 고른 채로 시트나 세부 정보 사이드바에 표시 let category = UserTodoCategory( @@ -156,6 +159,7 @@ struct CategoryManageFeature { state.categorySheet?.preferences = preferences return .send(.delegate(.changed(state.preferences))) case .tapEditUserCategory(let item): + state.revealCount += 1 if item.isUserCategory, case .user(let category) = item.category { state.categorySheet = CategorySheetState( category: category, diff --git a/Application/Presentation/HomeTab/Sources/Category/CategoryManageView.swift b/Application/Presentation/HomeTab/Sources/Category/CategoryManageView.swift index b32acf8f9..29b14d4fe 100644 --- a/Application/Presentation/HomeTab/Sources/Category/CategoryManageView.swift +++ b/Application/Presentation/HomeTab/Sources/Category/CategoryManageView.swift @@ -9,10 +9,8 @@ import SwiftUI import PresentationShared struct CategoryManageView: View { - @Environment(\.isTabContentActive) private var isTabContentActive @Environment(\.isiOSAppOnMac) private var isiOSAppOnMac @Environment(\.usesDesktopLayout) private var usesDesktopLayout - @Environment(\.setDetailSideBarPresented) private var setDetailSideBarPresented @Bindable var store: StoreOf // 좁은 창에서 시트로 연 카테고리 관리를 닫는 동작 var onClose: (() -> Void)? @@ -40,9 +38,6 @@ struct CategoryManageView: View { footer: UIHostingConfiguration { Button { store.send(.tapAddUserCategory) - if usesDesktopLayout { - setDetailSideBarPresented?(true) - } } label: { Text("todo_manage_add_category_title", bundle: PresentationResources.bundle) .font(.adaptive(isiOSAppOnMac ? .headline : .subheadline).weight(.semibold)) @@ -65,10 +60,7 @@ struct CategoryManageView: View { CategoryManageRow( item: item, onToggle: { store.send(.tapItem(item)) }, - onEdit: { - store.send(.tapEditUserCategory(item)) - setDetailSideBarPresented?(true) - }, + onEdit: { store.send(.tapEditUserCategory(item)) }, onDelete: { store.send(.tapDeleteUserCategory(item)) }, onSelect: usesDesktopLayout ? { store.send(.selectCategory(item)) } : nil ) @@ -102,32 +94,21 @@ struct CategoryManageView: View { } .background((usesDesktopLayout ? Color.background : .secondaryBackground).ignoresSafeArea()) // 사이드바가 있으면 고른 카테고리를 시트 대신 세부 정보 사이드바에 표시 - .prominentSheet( - item: $store.scope(state: \.categorySheet, action: \.categorySheet) - .activePresentation(when: isTabContentActive && !usesDesktopLayout) + .compositionSheet( + item: $store.scope(state: \.categorySheet, action: \.categorySheet), + reveal: store.revealCount ) { sheetStore in CategoryManageSheet(store: sheetStore) - } - .prominentAlert(store, state: \.alert, action: \.alert) - .detailSideBar(isActive: usesDesktopLayout) { - if let sheetStore = store.scope(state: \.categorySheet, action: \.categorySheet.presented) { - ScrollView { - CategoryEditForm(store: sheetStore) { - if let item = store.preferences.first(where: { $0.id == sheetStore.category.id }) { - store.send(.tapDeleteUserCategory(item)) - } + } right: { sheetStore in + ScrollView { + CategoryEditForm(store: sheetStore) { + if let item = store.preferences.first(where: { $0.id == sheetStore.category.id }) { + store.send(.tapDeleteUserCategory(item)) } } - } else { - DetailSideBarPlaceholder() - } - } - // 카테고리 관리를 벗어나면 카테고리를 보여 주던 세부 정보 사이드바도 닫음 - .onChange(of: isTabContentActive) { _, isActive in - if usesDesktopLayout && !isActive { - setDetailSideBarPresented?(false) } } + .prominentAlert(store, state: \.alert, action: \.alert) } } diff --git a/Application/Presentation/HomeTab/Sources/Home/HomeFeature+Effects.swift b/Application/Presentation/HomeTab/Sources/Home/HomeFeature+Effects.swift index 07e395b57..10747d326 100644 --- a/Application/Presentation/HomeTab/Sources/Home/HomeFeature+Effects.swift +++ b/Application/Presentation/HomeTab/Sources/Home/HomeFeature+Effects.swift @@ -132,7 +132,10 @@ extension HomeFeature { state.selectedTodoCategory = nil } case .contentPicker: - state.sheet = isPresented ? .contentPicker : state.showContentPicker ? nil : state.sheet + if isPresented { + state.closePresentations() + } + state.showContentPicker = isPresented } } diff --git a/Application/Presentation/HomeTab/Sources/Home/HomeFeature.swift b/Application/Presentation/HomeTab/Sources/Home/HomeFeature.swift index cb591993e..0127aa412 100644 --- a/Application/Presentation/HomeTab/Sources/Home/HomeFeature.swift +++ b/Application/Presentation/HomeTab/Sources/Home/HomeFeature.swift @@ -11,15 +11,27 @@ import PresentationShared @Reducer struct HomeFeature { + // 홈 내비게이션에 쌓는 카테고리 목록과 검색 + @Reducer + enum Path { + case category(TodoListFeature) + case search(SearchFeature) + } + @ObservableState struct State: Equatable { @Presents var alert: AlertState? - @Presents var sheet: SheetState? + @Presents var categoryManage: CategoryManageFeature.State? + @Presents var goalCreate: GoalCreateFeature.State? + // 넓은 창의 홈 자리와 좁은 창의 내비게이션이 같은 상태를 그려 창 폭이 바뀌어도 작성 중인 기록 유지 + @Presents var goalDetail: GoalDetailFeature.State? @Presents var fullScreenCover: FullScreenCoverState? + var path = StackState() // 작성 중인 새 개발 목표나 수정 중인 개발 목표를 버릴지 묻는 동안 미뤄 둔 동작 var actionAfterGoalDiscard: Action? - // 새 개발 목표나 개발 목표 칸을 닫은 뒤 다시 처리할 사이드바 요청 - var sideBarRequestAfterGoalDiscard: SideBarRequest? + var showContentPicker = false + // 사이드바가 있는 창, 사이드바 요청 처리와 사이드바 위치에 사용 + var usesDesktopLayout = false var developmentGoalItems = [DevelopmentGoalItem]() var hasDevelopmentGoalsLoaded = false var hasDevelopmentGoalsLoadFailure = false @@ -33,11 +45,6 @@ struct HomeFeature { var contentPickerHeight = CGFloat.zero var loading = LoadingFeature.State() - var showContentPicker: Bool { - if case .contentPicker? = sheet { return true } - return false - } - var showTodoEditor: Bool { fullScreenCover?.todoEditor != nil } var todoEditorCategory: TodoCategory? { @@ -52,12 +59,47 @@ struct HomeFeature { loading.visibleTargets.contains(LoadingTarget.developmentGoals.target) } + // 사이드바에서 고른 채로 표시할 위치 + var sideBarLocation: SideBarLocation { + if let goalDetail { + return .developmentGoal(goalDetail.goalId) + } + if usesDesktopLayout && categoryManage != nil { + return .todoCategoryManagement + } + if case .search? = path.last { + return .search + } + if case .category(let list)? = path.first { + return .todoCategory(list.category.storageValue) + } + return .home + } + + // 사이드바 Todo, 개발 목표 묶음의 하위 항목 + var sideBarContent: SideBarContent { + SideBarContent( + todoCategories: preferences.filter(\.isVisible), + developmentGoals: developmentGoalItems.map { SideBarGoal(id: $0.id, title: $0.goal.title) } + ) + } + + // 홈 루트에 띄운 화면은 한 번에 하나만 표시 + mutating func closePresentations() { + categoryManage = nil + goalCreate = nil + goalDetail = nil + showContentPicker = false + } } enum Action: BindableAction, Equatable { case alert(PresentationAction) - case sheet(PresentationAction) + case categoryManage(PresentationAction) + case goalCreate(PresentationAction) + case goalDetail(PresentationAction) case fullScreenCover(PresentationAction) + case path(StackActionOf) case binding(BindingAction) case view(ViewAction) case store(StoreAction) @@ -76,12 +118,12 @@ struct HomeFeature { case tapManageTodoCategory case tapTodoCategoryExpansionButton case tapTodoCategory(TodoCategory) - case closeGoalDraftForSideBarRequest(SideBarRequest) + case tapSearch + case sideBarRequested(SideBarRequest) } enum StoreAction: Equatable { case networkStatusChanged(Bool) - case setSheet(SheetState?) case setPresentation(Presentation, Bool) case setAlert(isPresented: Bool) case developmentGoalsLoaded([DevelopmentGoalItem]) @@ -90,66 +132,6 @@ struct HomeFeature { } } - @ObservableState - @CasePathable - enum SheetState: Equatable { - case reorderTodo(CategoryManageFeature.State) - case contentPicker - case goalCreate(GoalCreateFeature.State) - // 넓은 창의 칸과 시트가 같은 상태를 그려 창 폭이 바뀌어도 작성 중인 기록 유지 - case goalDetail(GoalDetailFeature.State) - - var categoryManageState: CategoryManageFeature.State? { - get { - guard case .reorderTodo(let state) = self else { return nil } - return state - } - set { - guard let newValue else { return } - self = .reorderTodo(newValue) - } - } - - var goalCreateState: GoalCreateFeature.State? { - get { - guard case .goalCreate(let state) = self else { return nil } - return state - } - set { - guard let newValue else { return } - self = .goalCreate(newValue) - } - } - - var goalDetailState: GoalDetailFeature.State? { - get { - guard case .goalDetail(let state) = self else { return nil } - return state - } - set { - guard let newValue else { return } - self = .goalDetail(newValue) - } - } - - var isDevelopmentGoalPresentation: Bool { - switch self { - case .goalCreate, .goalDetail: - true - case .reorderTodo, .contentPicker: - false - } - } - } - - @CasePathable - enum Sheet: Equatable { - case tapCloseButton - case categoryManage(CategoryManageFeature.Action) - case goalCreate(GoalCreateFeature.Action) - case goalDetail(GoalDetailFeature.Action) - } - @ObservableState struct FullScreenCoverState: Equatable { var destination: Destination @@ -196,6 +178,7 @@ struct HomeFeature { @Dependency(\.homeFetchRecentDevelopmentRecordUseCase) var recentRecordUseCase @Dependency(\.homeFetchTodosUseCase) var fetchTodosUseCase @Dependency(\.homeUpdateTodoCategoryPreferencesUseCase) var updatePreferencesUseCase + @Dependency(\.homeFetchRecentSearchQueriesUseCase) var fetchRecentSearchQueriesUseCase @Dependency(\.homeNetworkConnectivityUseCase) var networkConnectivityUseCase @Dependency(\.trackAnalyticsEventUseCase) var trackAnalyticsEventUseCase @Dependency(\.continuousClock) var clock @@ -206,17 +189,15 @@ struct HomeFeature { } BindingReducer() Reduce { state, action in - // 새 개발 목표나 개발 목표 수정 칸이 열린 동안 시트 자리를 바꾸는 동작 - if let goal = state.sheet?.goalCreateState ?? state.sheet?.goalDetailState?.goalEdit { + // 새 개발 목표나 개발 목표 수정 칸이 열린 동안 홈 루트에 띄운 화면을 바꾸는 동작 + if let goal = state.goalCreate ?? state.goalDetail?.goalEdit { switch action { case .view(.tapCreateDevelopmentGoal), .view(.tapDevelopmentGoal), .view(.tapManageTodoCategory), .view(.tapTodoCategory), - .view(.closeGoalDraftForSideBarRequest), - .store(.setSheet), .store(.setPresentation(.contentPicker, true)): - // 저장하는 동안 시트 자리를 바꾸면 저장이 취소되어 막음 + // 저장하는 동안 화면을 바꾸면 저장이 취소되어 막음 if goal.isSaving { return .none } @@ -236,8 +217,8 @@ struct HomeFeature { guard let action = state.actionAfterGoalDiscard else { break } state.actionAfterGoalDiscard = nil // 개발 목표 칸에서 바꾼 상태와 기록은 수정을 버리고 칸을 닫아도 홈과 사이드바 목록에 반영 - let refreshesDevelopmentGoals = state.sheet?.goalDetailState != nil - state.sheet = nil + let refreshesDevelopmentGoals = state.goalDetail != nil + state.closePresentations() return refreshesDevelopmentGoals ? .merge(.send(action), .send(.view(.fetchData))) : .send(action) case .alert(.dismiss): state.actionAfterGoalDiscard = nil @@ -248,27 +229,32 @@ struct HomeFeature { state.selectedTodoCategory = nil case .fullScreenCover: break - case .sheet(.dismiss): - let refreshesDevelopmentGoals = state.sheet?.isDevelopmentGoalPresentation == true - state.sheet = nil - if refreshesDevelopmentGoals { - return .send(.view(.fetchData)) - } - case .sheet(.presented(.tapCloseButton)): - state.sheet = nil - case .sheet(.presented(.categoryManage(.delegate(.changed(let preferences))))): + case .categoryManage(.presented(.delegate(.changed(let preferences)))): // 카테고리 관리는 시트와 칸 모두 고친 값을 바로 저장 state.preferences = preferences return delayedTodoCategoryPreferencesUpdateEffect(preferences) - case .sheet(.presented(.goalCreate(.delegate(.saved)))): - state.sheet = nil + case .categoryManage: + break + case .goalCreate(.presented(.delegate(.saved))): + state.goalCreate = nil + return .send(.view(.fetchData)) + case .goalCreate(.presented(.delegate(.close))): + return .send(.goalCreate(.dismiss)) + // 개발 목표 화면을 닫으면 바꾼 목표와 기록을 홈과 사이드바 목록에 반영하고, 이미 닫힌 뒤 늦게 온 닫힘은 다시 불러오지 않음 + case .goalCreate(.dismiss): + guard state.goalCreate != nil else { break } return .send(.view(.fetchData)) - case .sheet(.presented(.goalCreate(.delegate(.close)))): - return .send(.sheet(.dismiss)) + case .goalCreate: + break // 개발 목표 칸에서 고친 제목을 사이드바와 홈 목록에 반영 - case .sheet(.presented(.goalDetail(.delegate(.goalUpdated)))): + case .goalDetail(.presented(.delegate(.goalUpdated))): + return .send(.view(.fetchData)) + case .goalDetail(.dismiss): + guard state.goalDetail != nil else { break } return .send(.view(.fetchData)) - case .sheet: + case .goalDetail: + break + case .path: break case .binding: break @@ -283,12 +269,19 @@ struct HomeFeature { return .none } .ifLet(\.$alert, action: \.alert) - .ifLet(\.$sheet, action: \.sheet) { - SheetFeature() + .ifLet(\.$categoryManage, action: \.categoryManage) { + CategoryManageFeature() + } + .ifLet(\.$goalCreate, action: \.goalCreate) { + GoalCreateFeature() + } + .ifLet(\.$goalDetail, action: \.goalDetail) { + GoalDetailFeature() } .ifLet(\.$fullScreenCover, action: \.fullScreenCover) { FullScreenCoverFeature() } + .forEach(\.path, action: \.path) } } @@ -326,25 +319,30 @@ private extension HomeFeature { ) case .tapCreateDevelopmentGoal: if state.showContentPicker { - state.sheet = nil + state.showContentPicker = false return delayedDevelopmentGoalCreateEffect() } - state.sheet = .goalCreate(GoalCreateFeature.State()) + state.closePresentations() + state.goalCreate = GoalCreateFeature.State() case .tapDevelopmentGoal(let goalID): - state.sheet = .goalDetail(GoalDetailFeature.State(goalId: goalID)) + state.closePresentations() + state.goalDetail = GoalDetailFeature.State(goalId: goalID) case .tapManageTodoCategory: // 이미 연 카테고리 관리는 고르던 카테고리를 그대로 유지 - guard state.sheet?.categoryManageState == nil else { break } - state.sheet = .reorderTodo(CategoryManageFeature.State(preferences: state.preferences)) + guard state.categoryManage == nil else { break } + state.closePresentations() + state.categoryManage = CategoryManageFeature.State(preferences: state.preferences) case .tapTodoCategoryExpansionButton: state.isTodoCategoryExpanded.toggle() case .tapTodoCategory(let category): state.selectedTodoCategory = category - state.sheet = nil + state.closePresentations() return delayedTodoEditorEffect() - case .closeGoalDraftForSideBarRequest(let request): - state.sheet = nil - state.sideBarRequestAfterGoalDiscard = request + case .tapSearch: + // 열 때마다 빈 입력칸으로 시작하고 최근 검색은 열 때 읽음 + state.path.append(.search(SearchFeature.State(recentQueries: fetchRecentSearchQueriesUseCase.execute()))) + case .sideBarRequested(let request): + return sideBarRequested(request, state: &state) } return .none @@ -357,8 +355,6 @@ private extension HomeFeature { switch action { case .networkStatusChanged(let isConnected): state.isNetworkConnected = isConnected - case .setSheet(let sheet): - state.sheet = sheet case .setPresentation(let presentation, let isPresented): Self.setPresentation(&state, presentation: presentation, isPresented: isPresented) case .setAlert(let isPresented): @@ -375,22 +371,80 @@ private extension HomeFeature { return .none } -} - -private struct SheetFeature: Reducer { - typealias State = HomeFeature.SheetState - typealias Action = HomeFeature.Sheet - var body: some ReducerOf { - EmptyReducer() - .ifCaseLet(\.reorderTodo, action: \.categoryManage) { - CategoryManageFeature() + // 사이드바에서 보낸 이동과 작성 요청 + func sideBarRequested(_ request: SideBarRequest, state: inout State) -> Effect { + // 이미 표시 중인 개발 목표를 다시 누르면 다시 열지 않고 쌓아 연 화면만 닫아 개발 목표 첫 화면 표시 + if case .open(.developmentGoal(let goalID)) = request.action, state.goalDetail?.goalId == goalID { + return .send(.goalDetail(.presented(.view(.returnToGoal)))) } - .ifCaseLet(\.goalCreate, action: \.goalCreate) { - GoalCreateFeature() + let goal = state.goalCreate ?? state.goalDetail?.goalEdit + // 작성 중인 새 개발 목표나 수정 중인 개발 목표가 있으면 칸을 닫기 전에 버릴지 물음 + // 버리면 칸을 닫은 뒤 같은 요청을 다시 처리 + if request.action != .createTodo, let goal, goal.hasDraft { + // 저장하는 동안 칸을 바꾸면 저장이 취소되어 막음 + guard !goal.isSaving else { return .none } + state.actionAfterGoalDiscard = .view(.sideBarRequested(request)) + state.alert = Self.discardGoalDraftAlertState(isEditing: goal.goal != nil) + return .none } - .ifCaseLet(\.goalDetail, action: \.goalDetail) { - GoalDetailFeature() + // 사이드바가 있으면 카테고리 관리, 새 개발 목표, 개발 목표를 시트 대신 칸으로 표시 + let showsPane = state.usesDesktopLayout + && (state.categoryManage != nil || state.goalCreate != nil || state.goalDetail != nil) + // 개발 목표 칸을 다른 화면으로 바꾸면 칸에서 바꾼 목표와 기록을 시트를 닫을 때처럼 홈과 사이드바 목록에 반영 + let refreshesDevelopmentGoals = showsPane && (state.goalCreate != nil || state.goalDetail != nil) + // 새 Todo 작성으로 작성 중인 개발 목표를 버릴지 묻는 경우 + var asksGoalDiscard = false + var effects = [Effect]() + // 사이드바로 다른 곳을 열면 칸으로 표시하던 화면은 닫고, 저장하는 동안은 닫지 않음 + if showsPane, case .open = request.action, goal?.isSaving != true { + state.closePresentations() } + switch request.action { + case .open(.home): + state.path.removeAll() + case .open(.todoCategory(let id)): + guard let item = state.preferences.first(where: { $0.id == id }) else { break } + // 같은 카테고리 목록만 쌓여 있으면 보던 목록을 그대로 둠 + if state.path.count == 1, case .category(let list)? = state.path.first, list.category == item.todoCategory { + break + } + state.path = StackState([.category(TodoListFeature.State(category: item.todoCategory))]) + case .open(.developmentGoal(let goalID)): + // 사이드바가 있으면 개발 목표를 홈 루트에 그려 위에 쌓인 목록을 비움 + if state.usesDesktopLayout { + state.path.removeAll() + } + effects.append(.send(.view(.tapDevelopmentGoal(goalID)))) + case .createTodo: + if case .category? = state.path.first, let id = state.path.ids.first { + // 카테고리 목록이 보이면 그 목록이 자기 작성 버튼과 같은 방식으로 작성 + effects.append(.send(.path(.element(id: id, action: .category(.store(.setFullScreenCover(.editor))))))) + } else if state.isNetworkConnected { + // 홈 작성 버튼처럼 연결이 끊기면 열지 않고 쌓아 연 검색도 그대로 둠 + // 쌓아 연 검색은 내리고 홈 작성 버튼과 같은 방식으로 작성 + state.path.removeAll() + asksGoalDiscard = goal.map { !$0.isSaving && $0.hasDraft } ?? false + effects.append(.send(.store(.setPresentation(.contentPicker, true)))) + } + case .manageTodoCategory: + // 카테고리를 불러오기 전 빈 목록으로 저장하지 않도록 무시 + guard !state.preferences.isEmpty else { break } + // 사이드바가 있으면 카테고리 관리 칸을 홈 루트에 그려 위에 쌓인 목록을 비움 + if state.usesDesktopLayout { + state.path.removeAll() + } + effects.append(.send(.view(.tapManageTodoCategory))) + case .open: + break + } + // 버릴지 묻는 중이면 칸이 그대로라 다시 불러오지 않음 + if refreshesDevelopmentGoals && state.actionAfterGoalDiscard == nil && !asksGoalDiscard { + effects.append(.send(.view(.fetchData))) + } + return .concatenate(effects) } } + +extension HomeFeature.Path.State: Equatable {} +extension HomeFeature.Path.Action: Equatable {} diff --git a/Application/Presentation/HomeTab/Sources/Home/HomeView.swift b/Application/Presentation/HomeTab/Sources/Home/HomeView.swift index 545dbf612..f2875f732 100644 --- a/Application/Presentation/HomeTab/Sources/Home/HomeView.swift +++ b/Application/Presentation/HomeTab/Sources/Home/HomeView.swift @@ -15,9 +15,6 @@ public struct HomeView: View { @Environment(\.windowControlsInset) private var windowControlsInset @Environment(\.readableContentWidth) private var readableContentWidth @Environment(\.deviceType) private var deviceType - @Environment(\.sideBarRequest) private var sideBarRequest - @Environment(\.setDetailSideBarPresented) private var setDetailSideBarPresented - @State private var router = NavigationRouter() @State private var store: StoreOf private let isSelected: Bool private let windowEvent: TodoEditorWindowEvent @@ -34,216 +31,68 @@ public struct HomeView: View { } public var body: some View { - let goalDetailID = store.sheet?.goalDetailState?.goalId - let sideBarLocation: SideBarLocation = if let goalDetailID { - .developmentGoal(goalDetailID) - } else if usesDesktopLayout && store.sheet?.categoryManageState != nil { - .todoCategoryManagement - } else if router.path.last == .search { - .search - } else if case .category(let item)? = router.root { - .todoCategory(item.id) - } else { - .home - } - // 사이드바가 있으면 카테고리 관리, 새 개발 목표, 개발 목표를 시트 대신 칸으로 표시 - let showsSheetAsPane = usesDesktopLayout - && (store.sheet?.categoryManageState != nil || store.sheet?.goalCreateState != nil || goalDetailID != nil) - // 칸으로 나눈 화면은 새로 만들기를 시트 대신 만들기 버튼 옆 팝오버로 표시 - let showsPickerAsPopover = usesPaneLayout && store.showContentPicker - let sheetBinding = $store.scope(state: \.sheet, action: \.sheet) - .activePresentation(when: isSelected) - - NavigationStack(path: $router.path) { - Group { - if usesDesktopLayout, - let manageStore = store.scope(state: \.sheet?.categoryManageState, action: \.sheet.presented.categoryManage) { - CategoryManageView(store: manageStore) - } else if usesDesktopLayout, - let goalStore = store.scope(state: \.sheet?.goalCreateState, action: \.sheet.presented.goalCreate) { - // 홈 오른쪽 칸에서 쓰고 연결된 Todo는 세부 정보 사이드바에 표시 - PaneSplitView { - homeContent - } detail: { - GoalCreateView(store: goalStore) - } - .detailSideBar { - GoalCreateSideBarContent(store: goalStore) - } - } else if usesDesktopLayout, - let goalStore = store.scope(state: \.sheet?.goalDetailState, action: \.sheet.presented.goalDetail) { - // 홈 자리에 개발 목표를 표시하고 기록 작성은 오른쪽 칸에 표시 - GoalDetailView(store: goalStore) - .id(goalDetailID) - } else if usesPaneLayout, - let editorStore = store.scope( - state: \.fullScreenCover?.todoEditor, - action: \.fullScreenCover.presented.todoEditor - ) { - // 홈 오른쪽 칸에서 새 Todo 작성 - PaneSplitView { - homeContent - } detail: { - TodoEditorView(store: editorStore, onClose: { store.send(.fullScreenCover(.dismiss)) }) - } - } else { - homeContent + NavigationStack(path: $store.scope(state: \.path, action: \.path)) { + PaneSplitView { + homeContent + } + // 새 개발 목표에 연결한 Todo는 세부 정보 사이드바에 표시 + .compositionRight(isActive: store.goalCreate != nil) { + if let goalStore = store.scope(state: \.goalCreate, action: \.goalCreate.presented) { + GoalCreateSideBarContent(store: goalStore) } } - .navigationDestination( - for: HomeRoute.self, - interactivePop: { - switch $0 { - case .category: true - case .todo: true - case .search: true - } - }, - destination: { destinationView($0).environment(\.showsPaneTitleBar, usesPaneLayout) } - ) - // 좁은 창은 개발 목표를 홈 내비게이션에 쌓고, 넓어지면 같은 상태를 홈 자리에 표시 - .navigationDestination( - item: $store.scope(state: \.sheet?.goalDetailState, action: \.sheet.goalDetail) - .hiddenInPane(usesDesktopLayout), - interactivePop: true + // 좁은 창은 개발 목표를 홈 내비게이션에 쌓고, 넓어지면 같은 상태를 홈 자리에 표시하고 기록 작성은 오른쪽 칸에 표시 + .compositionCenter( + item: $store.scope(state: \.goalDetail, action: \.goalDetail), + narrow: .push ) { goalStore in - GoalDetailView(store: goalStore) + GoalDetailView(store: goalStore, windowEvent: windowEvent) + .id(goalStore.goalId) } - } - .desktopNavigationTransition() - // 사이드바 구조로 바뀌면 쌓아 연 Todo 상세는 내리고 카테고리 목록 옆 칸에 표시 - .closesPushedDetail { - router.path.removeAll { - if case .todo = $0 { return true } - return false + // 사이드바가 있으면 카테고리 관리를 시트 대신 홈 자리에 표시 + // 사이드바에서 개발 목표를 열어 개발 목표 화면으로 바뀌어도 닫힘을 받아 세부 정보 사이드바를 닫도록 개발 목표 바깥에 둠 + .compositionCenter( + item: $store.scope(state: \.categoryManage, action: \.categoryManage), + narrow: .sheet, + isActive: isSelected, + closesRight: true + ) { manageStore in + CategoryManageView(store: manageStore) { + store.send(.categoryManage(.dismiss)) + } } + } destination: { pathStore in + Group { + switch pathStore.case { + case .category(let listStore): + TodoListView(store: listStore, windowEvent: windowEvent) + case .search(let searchStore): + SearchView(store: searchStore, windowEvent: windowEvent) + } + } + .stackDestination(usesDesktopLayout: usesDesktopLayout, usesPaneLayout: usesPaneLayout) } - .preference(key: SideBarLocationPreferenceKey.self, value: sideBarLocation) - .preference( - key: SideBarContentPreferenceKey.self, - value: SideBarContent( - todoCategories: store.preferences.filter(\.isVisible), - developmentGoals: store.developmentGoalItems.map { SideBarGoal(id: $0.id, title: $0.goal.title) } - ) - ) - // 사이드바 요청으로 처음 여는 탭도 그 요청을 반영 - .onChange(of: sideBarRequest, initial: true) { _, request in - handleSideBarRequest(request, showsSheetAsPane: showsSheetAsPane) + .desktopNavigationTransition() + .onChange(of: usesDesktopLayout, initial: true) { _, usesDesktopLayout in + store.send(.binding(.set(\.usesDesktopLayout, usesDesktopLayout))) } - // 작성 중인 새 개발 목표나 수정 중인 개발 목표를 버린 뒤 미뤄 둔 사이드바 요청 처리 - .onChange(of: store.sideBarRequestAfterGoalDiscard) { _, request in - handleSideBarRequest(request, showsSheetAsPane: showsSheetAsPane) + .compositionLeft(location: store.sideBarLocation, content: store.sideBarContent) { + // 홈이 아닌 탭으로 켜져도 사이드바 하위 항목을 채움 + if !isSelected { + store.send(.view(.fetchData)) + } + } onRequest: { request in + store.send(.view(.sideBarRequested(request))) } .onAppear { store.send(.view(.startObserving)) } - // 사이드바가 있으면 홈이 아닌 탭으로 켜지거나 좁은 창에서 넓어져도 사이드바 하위 항목을 채우도록 불러옴 - .onChange(of: usesDesktopLayout, initial: true) { _, usesDesktopLayout in - if usesDesktopLayout && !isSelected { - store.send(.view(.fetchData)) - } - } .onChange(of: isSelected, initial: true) { _, isSelected in if isSelected { store.send(.view(.fetchData)) } } - // 카테고리 관리를 벗어나면 카테고리를 보여 주던 세부 정보 사이드바도 닫음 - // 창 폭이 바뀌어 칸과 시트를 오갈 때는 카테고리 관리 상태가 남아 닫지 않음 - .onChange(of: store.sheet?.categoryManageState == nil) { _, isClosed in - if usesDesktopLayout && isClosed { - setDetailSideBarPresented?(false) - } - } .prominentAlert(store, state: \.alert, action: \.alert) - .prominentSheet( - item: Binding( - get: { - showsSheetAsPane || showsPickerAsPopover || goalDetailID != nil - ? nil : sheetBinding.wrappedValue - }, - // 앞 시트가 늦게 닫히며 보내는 닫힘이 칸이나 팝오버로 연 화면을 지우지 않도록 지금 상태로 판단 - set: { sheet in - // 내비게이션에 쌓은 개발 목표는 시트 닫힘으로 지우지 않음 - guard store.sheet?.goalDetailState == nil else { return } - guard !usesDesktopLayout - || store.sheet?.categoryManageState == nil - && store.sheet?.goalCreateState == nil - && store.sheet?.goalDetailState == nil - else { return } - guard !(usesPaneLayout && store.showContentPicker) else { return } - sheetBinding.wrappedValue = sheet - } - ), - content: sheetContent - ) - .fullScreenCover( - item: $store.scope(state: \.fullScreenCover, action: \.fullScreenCover) - .activePresentation(when: isSelected) - .hiddenInPane(usesPaneLayout && store.showTodoEditor), - content: coverContent - ) - } - - private func handleSideBarRequest(_ request: SideBarRequest?, showsSheetAsPane: Bool) { - // 이미 표시 중인 개발 목표를 다시 누르면 다시 열지 않고 쌓아 연 화면만 닫아 개발 목표 첫 화면 표시 - if case .open(.developmentGoal(let goalID))? = request?.action, - store.sheet?.goalDetailState?.goalId == goalID { - store.send(.sheet(.presented(.goalDetail(.view(.returnToGoal))))) - return - } - // 작성 중인 새 개발 목표나 수정 중인 개발 목표가 있으면 칸을 닫기 전에 버릴지 물음 - if let request, - request.action != .createTodo, - store.sheet?.goalCreateState?.hasDraft == true || store.sheet?.goalDetailState?.goalEdit?.hasDraft == true { - store.send(.view(.closeGoalDraftForSideBarRequest(request))) - return - } - // 개발 목표 칸을 다른 화면으로 바꾸면 칸에서 바꾼 목표와 기록을 시트를 닫을 때처럼 홈과 사이드바 목록에 반영 - let refreshesDevelopmentGoals = request != nil - && showsSheetAsPane - && store.sheet?.isDevelopmentGoalPresentation == true - // 사이드바로 다른 곳을 열면 칸으로 표시하던 화면은 닫음 - if showsSheetAsPane, case .open = request?.action { - store.send(.store(.setSheet(nil))) - } - switch request?.action { - case .open(.home): - router.path = [] - case .open(.todoCategory(let id)): - guard let item = store.preferences.first(where: { $0.id == id }) else { break } - router.replace(with: .category(item)) - case .open(.developmentGoal(let goalID)): - // 사이드바가 있으면 개발 목표를 홈 루트에 그려 위에 쌓인 목록을 비움 - if usesDesktopLayout { - router.path = [] - } - store.send(.view(.tapDevelopmentGoal(goalID))) - case .createTodo: - // 홈 작성 버튼처럼 연결이 끊기면 열지 않고 쌓아 연 검색도 그대로 둠 - guard store.isNetworkConnected else { break } - // 쌓아 연 검색은 내리고 홈 작성 버튼과 같은 방식으로 작성 - if router.root == .search { - router.path = [] - } - // 카테고리 목록이 보이면 그 목록이 자기 작성 버튼과 같은 방식으로 작성 - guard router.root == nil else { break } - store.send(.store(.setPresentation(.contentPicker, true))) - case .manageTodoCategory: - // 카테고리를 불러오기 전 빈 목록으로 저장하지 않도록 무시 - guard !store.preferences.isEmpty else { break } - // 사이드바가 있으면 카테고리 관리 칸을 홈 루트에 그려 위에 쌓인 목록을 비움 - if usesDesktopLayout { - router.path = [] - } - store.send(.view(.tapManageTodoCategory)) - case .open, nil: - break - } - // 버릴지 묻는 중이면 칸이 그대로라 다시 불러오지 않음 - if refreshesDevelopmentGoals && store.actionAfterGoalDiscard == nil { - store.send(.view(.fetchData)) - } } private var homeContent: some View { @@ -263,6 +112,31 @@ public struct HomeView: View { .sharedBackgroundHidden() } } + // 좁은 창은 새로 만들기를 시트로, 칸으로 나눈 화면은 만들기 버튼 옆 팝오버로 표시 + // 버튼 옆으로 붙으면 위쪽이 상태 표시 영역에 가려지므로 버튼 아래로 표시 + .compositionPicker( + isPresented: $store.showContentPicker, + isActive: isSelected, + arrowEdge: .top, + maxHeight: min(640, store.visibleHeight) + ) { + HomeContentPicker(store: store) { store.send(.view(.tapTodoCategory($0))) } + } + // 사이드바가 있으면 새 Todo를 홈 오른쪽 칸에서 작성 + .compositionEditor( + item: $store.scope(state: \.fullScreenCover, action: \.fullScreenCover), + isActive: isSelected + ) { coverStore, onClose in + coverContent(coverStore, onClose: onClose) + } + // 좁은 창은 새 개발 목표를 닫기, 저장 버튼으로만 닫는 시트로 작성하고 사이드바가 있으면 홈 오른쪽 칸에서 작성 + .compositionEditor( + item: $store.scope(state: \.goalCreate, action: \.goalCreate), + narrow: .sheet, + isActive: isSelected + ) { goalStore, _ in + GoalCreateView(store: goalStore) + } } private var duoToolbarItems: some ToolbarContent { @@ -270,7 +144,7 @@ public struct HomeView: View { // 접힌 뒤 펼칠 때 레일 아이콘이 사라지는 현상 방지 Group { Button { - router.push(.search) + store.send(.view(.tapSearch)) } label: { Image(systemName: "magnifyingglass") } @@ -291,26 +165,7 @@ public struct HomeView: View { PaneTitleBar(Text("nav_home", bundle: PresentationResources.bundle)) { searchButton HomeCreateButton(store: store) - .popover( - isPresented: Binding( - get: { isSelected && store.showContentPicker }, - // 좁은 창으로 바뀌며 팝오버가 닫혀도 같은 상태를 시트로 다시 그림 - set: { isPresented in - if usesPaneLayout { - store.send(.store(.setPresentation(.contentPicker, isPresented))) - } - } - ), - // 버튼 옆으로 붙으면 위쪽이 상태 표시 영역에 가려지므로 버튼 아래로 표시 - arrowEdge: .top - ) { - HomeContentPicker(store: store) { store.send(.view(.tapTodoCategory($0))) } - // 화면이 낮거나 Duo 접는 선에 걸리면 팝오버 높이를 줄이고 목록을 스크롤 - .frame(width: 320 * AdaptiveSize.boardScale) - .frame(minHeight: 0, idealHeight: min(640, store.visibleHeight), maxHeight: min(640, store.visibleHeight)) - .presentationBackground(Color.secondaryBackground) - .presentationCompactAdaptation(.popover) - } + .compositionPickerAnchor() } } else { HStack(spacing: 0) { @@ -335,7 +190,7 @@ public struct HomeView: View { @ViewBuilder private var searchButton: some View { // 모든 기기에서 덮는 화면 대신 홈 내비게이션에 쌓아 열고, 사이드바가 있는 창은 사이드바 옆에 표시 - let openSearch = { router.push(.search) } + let openSearch = { _ = store.send(.view(.tapSearch)) } if !usesPaneLayout { Button(action: openSearch) { @@ -350,73 +205,18 @@ public struct HomeView: View { } } - @ViewBuilder - private func sheetContent(_ sheetStore: Store) -> some View { - switch sheetStore.state { - case .contentPicker: - HomeContentPicker(store: store) { store.send(.view(.tapTodoCategory($0))) } - case .reorderTodo: - if let manageStore = sheetStore.scope(state: \.categoryManageState, action: \.categoryManage) { - // 넓은 창으로 바뀌어 닫히는 시트가 칸으로 연 화면의 세부 정보 사이드바를 가져가지 않음 - CategoryManageView(store: manageStore) { - store.send(.sheet(.dismiss)) - } - .environment(\.selectDetailSideBarTarget, nil) - } - case .goalCreate: - if let goalStore = sheetStore.scope(state: \.goalCreateState, action: \.goalCreate) { - GoalCreateView(store: goalStore) - } - case .goalDetail: - // 개발 목표는 시트 대신 홈 내비게이션에 쌓음 - EmptyView() - } - } - @ViewBuilder private func coverContent( - _ coverStore: Store + _ coverStore: Store, + onClose: (() -> Void)? ) -> some View { switch coverStore.destination { case .todoEditor: if let todoEditorStore = coverStore.scope(state: \.todoEditor, action: \.todoEditor) { - TodoEditorView(store: todoEditorStore) + TodoEditorView(store: todoEditorStore, onClose: onClose) } } } - - @ViewBuilder - private func destinationView(_ route: HomeRoute) -> some View { - switch route { - case .category(let item): - TodoListView( - store: Store(initialState: TodoListFeature.State(category: item.todoCategory)) { - TodoListFeature() - }, - windowEvent: windowEvent, - onSelectTodo: { router.push(.todo(TodoIdItem(id: $0))) } - ) - .id(item.id) - case .todo(let item): - TodoDetailView( - store: Store( - initialState: TodoDetailFeature.State(todoId: item.id, showEditButton: true) - ) { - TodoDetailFeature() - }, - windowEvent: windowEvent - ) - .id(item.id) - case .search: - SearchView(isOnTop: router.path.last == .search) { router.push(.todo(TodoIdItem(id: $0))) } - } - } -} - -public enum HomeRoute: Hashable { - case category(TodoCategoryItem) - case todo(TodoIdItem) - case search } private struct HomeCreateButton: View { @@ -604,7 +404,7 @@ private struct HomeTodoCategoryLink: View { var body: some View { let tileSize = isiOSAppOnMac ? 37 * AdaptiveSize.boardScale : 40 - NavigationLink(value: HomeRoute.category(item)) { + NavigationLink(state: HomeFeature.Path.State.category(TodoListFeature.State(category: item.todoCategory))) { VStack(spacing: 6) { Image(systemName: item.symbolName) .font(.adaptive(.body).weight(.medium)) @@ -654,7 +454,7 @@ private struct HomeContentPicker: View { HStack { if isiOSAppOnMac { Button { - store.send(.sheet(.presented(.tapCloseButton))) + store.send(.store(.setPresentation(.contentPicker, false))) } label: { Image(systemName: "xmark") .font(.adaptive(.body)) @@ -665,7 +465,7 @@ private struct HomeContentPicker: View { .buttonStyle(.plain) } else { Button { - store.send(.sheet(.presented(.tapCloseButton))) + store.send(.store(.setPresentation(.contentPicker, false))) } label: { Image(systemName: "xmark") } @@ -688,7 +488,7 @@ private struct HomeContentPicker: View { background: .secondaryBackground ) { RecordTopBarTextButton(RecordPresentation.text("common_close")) { - store.send(.sheet(.presented(.tapCloseButton))) + store.send(.store(.setPresentation(.contentPicker, false))) } } trailing: { EmptyView() diff --git a/Application/Presentation/HomeTab/Sources/Record/Detail/RecordDetailView.swift b/Application/Presentation/HomeTab/Sources/Record/Detail/RecordDetailView.swift index 8f92c0039..0d2a3e14d 100644 --- a/Application/Presentation/HomeTab/Sources/Record/Detail/RecordDetailView.swift +++ b/Application/Presentation/HomeTab/Sources/Record/Detail/RecordDetailView.swift @@ -63,15 +63,8 @@ public struct RecordDetailView: View { .duoToolbarVisibility(showsBackButton: true) .onAppear { store.send(.view(.appear(onDesktop: usesDesktopLayout))) } .prominentAlert(store, state: \.alert, action: \.alert) - // 좁은 창의 기록 정정은 닫기·저장·확정 버튼으로만 닫는 전체 화면 - .fullScreenCover( - item: editor.hiddenInPane { usesDesktopLayout || isHidden() } - ) { _ in - correctionEditor - } - .prominentSheet( - item: editor.hiddenInPane { !usesDesktopLayout || isHidden() } - ) { _ in + // 기록 정정은 좁은 창에서 닫기, 저장, 확정 버튼으로만 닫는 전체 화면이고 넓은 창에서 시트 + .compositionEditor(item: editor.hiddenInPane(isHidden), inPane: false) { _, _ in correctionEditor } .navigationDestination( diff --git a/Application/Presentation/HomeTab/Sources/Record/GoalDetail/GoalDetailFeature.swift b/Application/Presentation/HomeTab/Sources/Record/GoalDetail/GoalDetailFeature.swift index 69c0ffa78..2453cc18e 100644 --- a/Application/Presentation/HomeTab/Sources/Record/GoalDetail/GoalDetailFeature.swift +++ b/Application/Presentation/HomeTab/Sources/Record/GoalDetail/GoalDetailFeature.swift @@ -32,7 +32,8 @@ struct GoalDetailFeature { // 넓은 창의 칸과 시트가 같은 상태를 그려 창 폭이 바뀌어도 작성 중인 기록 유지 @Presents var recordEditor: RecordEditorFeature.State? @Presents var recordDetail: RecordDetailDestination? - @Presents var todoDetail: TodoDetailDestination? + // 연결한 Todo 상세, 창 폭과 상관없이 개발 목표 위에 쌓음 + @Presents var todoDetail: TodoDetailFeature.State? @Presents var todoLinkSheet: GoalTodoLinkFeature.State? // 창 폭이 바뀌어 기록 상세 표시가 잠깐 닫혀도 진행 중인 조회·되돌리기와 안에서 연 화면을 잃지 않도록 따로 보관하는 상세 상태 var recordDetailContent: RecordDetailFeature.State? @@ -53,6 +54,8 @@ struct GoalDetailFeature { var shownOnDesktop: Bool? // 창 폭이 바뀌어 빠지는 자리가 먼저 닫은 기록 상세, 같은 차례에 새 자리가 나타나면 되살림 var dismissedRecordDetail: RecordDetailDestination? + // 창 폭이 바뀌어 빠지는 자리가 먼저 닫은 Todo 상세, 같은 차례에 새 자리가 나타나면 되살림 + var dismissedTodoDetail: TodoDetailFeature.State? var goalTitle: String { goal?.title ?? "" @@ -81,7 +84,7 @@ struct GoalDetailFeature { case recordEditor(PresentationAction) case recordDetail(PresentationAction) case recordDetailContent(RecordDetailFeature.Action) - case todoDetail(PresentationAction) + case todoDetail(PresentationAction) case todoLinkSheet(PresentationAction) case binding(BindingAction) case view(ViewAction) @@ -116,6 +119,7 @@ struct GoalDetailFeature { case todosFailed case transitionFailed case recordDetailDismissed + case todoDetailDismissed } enum Delegate: Equatable { @@ -164,7 +168,10 @@ struct GoalDetailFeature { case .recordDetail, .recordDetailContent: break case .todoDetail(.dismiss): - state.todoDetail = nil + state.dismissedTodoDetail = state.todoDetail + return .run { send in + await send(.store(.todoDetailDismissed)) + } case .todoDetail: break case .todoLinkSheet(.dismiss), @@ -196,6 +203,9 @@ struct GoalDetailFeature { if state.recordDetail == nil { state.recordDetail = state.dismissedRecordDetail } + if state.todoDetail == nil { + state.todoDetail = state.dismissedTodoDetail + } state.recordDetailContent?.restoreDismissedScreens() } state.shownOnDesktop = onDesktop @@ -288,7 +298,7 @@ struct GoalDetailFeature { case .view(.selectTodo(let todoId)): guard state.linkedTodos.contains(where: { $0.id == todoId }), state.todoDetail == nil else { break } - state.todoDetail = TodoDetailDestination(todoId: todoId) + state.todoDetail = TodoDetailFeature.State(todoId: todoId, showEditButton: false) case .view(.selectStatus(let status)): guard let goalStatus = state.goalStatus, !state.isLoading, @@ -331,6 +341,8 @@ struct GoalDetailFeature { if state.recordDetail == nil { state.recordDetailContent = nil } + case .store(.todoDetailDismissed): + state.dismissedTodoDetail = nil } return .none @@ -348,6 +360,9 @@ struct GoalDetailFeature { .ifLet(\.$todoLinkSheet, action: \.todoLinkSheet) { GoalTodoLinkFeature() } + .ifLet(\.$todoDetail, action: \.todoDetail) { + TodoDetailFeature() + } } } @@ -437,9 +452,3 @@ struct RecordDetailDestination: Equatable, Identifiable { var id: String { record.id } let record: DevelopmentRecord } - -@ObservableState -struct TodoDetailDestination: Equatable, Identifiable { - var id: String { todoId } - let todoId: String -} diff --git a/Application/Presentation/HomeTab/Sources/Record/GoalDetail/GoalDetailView.swift b/Application/Presentation/HomeTab/Sources/Record/GoalDetail/GoalDetailView.swift index 474fe11b0..2e832efb3 100644 --- a/Application/Presentation/HomeTab/Sources/Record/GoalDetail/GoalDetailView.swift +++ b/Application/Presentation/HomeTab/Sources/Record/GoalDetail/GoalDetailView.swift @@ -15,6 +15,7 @@ public struct GoalDetailView: View { @Environment(\.usesDesktopLayout) private var usesDesktopLayout @Environment(\.isiOSAppOnMac) private var isiOSAppOnMac @Bindable var store: StoreOf + let windowEvent: TodoEditorWindowEvent public var body: some View { // 좁은 창은 홈 내비게이션에 쌓고, 사이드바가 있으면 홈 내비게이션 안의 칸으로 표시 @@ -57,60 +58,44 @@ public struct GoalDetailView: View { let isHidden = { !isShown || store.shownOnDesktop != usesDesktopLayout } // 사이드바가 있으면 개발 목표 수정과 기록 작성을 개발 목표 오른쪽 칸에 표시 - return PaneSplitView(splitsOnDesktop: store.goalEdit != nil || store.recordEditor != nil) { + // 좁은 창 표시는 빠지는 자리에서 넓은 창의 개발 목표가 이미 나타났으면 띄우지 않음 + let isNarrowHidden = { store.shownOnDesktop == true && !usesDesktopLayout } + + return PaneSplitView { mainContent - } detail: { - if let editStore = store.scope(state: \.goalEdit, action: \.goalEdit.presented) { - GoalCreateView(store: editStore) - } else if let editorStore = store.scope(state: \.recordEditor, action: \.recordEditor.presented) { - RecordEditorView( - store: editorStore, - onCompletion: { - store.send(.view(.refresh)) - }, - onClose: { - store.send(.recordEditor(.dismiss)) - } - ) - } - } - // 좁은 창은 닫기·저장·확정 버튼으로만 닫는 전체 화면 - // 넓은 창으로 바뀌어 칸에 옮겨 그린 뒤 늦게 닫히는 전체 화면은 작성 중인 기록을 지우지 않음 - .fullScreenCover( - item: $store.scope(state: \.recordEditor, action: \.recordEditor) - .hiddenInPane { usesDesktopLayout || store.shownOnDesktop == true } - ) { editorStore in - RecordEditorView( - store: editorStore, - onCompletion: { - store.send(.view(.refresh)) + // 좁은 창은 닫기, 저장, 확정 버튼으로만 닫는 전체 화면 + .compositionEditor( + item: $store.scope(state: \.recordEditor, action: \.recordEditor) + .hiddenInPane(isNarrowHidden) + ) { editorStore, onClose in + RecordEditorView( + store: editorStore, + onCompletion: { + store.send(.view(.refresh)) + }, + onClose: onClose + ) + } + // 좁은 창은 새 개발 목표와 같은 시트로 수정하고 닫기, 저장 버튼으로만 닫음 + .compositionEditor( + item: $store.scope(state: \.goalEdit, action: \.goalEdit) + .hiddenInPane(isNarrowHidden), + narrow: .sheet + ) { editStore, _ in + GoalCreateView(store: editStore) } - ) } .prominentSheet(item: $store.scope(state: \.todoLinkSheet, action: \.todoLinkSheet)) { GoalTodoLinkSheet(store: $0) } - // 좁은 창은 새 개발 목표와 같은 시트로 수정하고 닫기, 저장 버튼으로만 닫음 - .prominentSheet( - item: $store.scope(state: \.goalEdit, action: \.goalEdit) - .hiddenInPane { usesDesktopLayout || store.shownOnDesktop == true } - ) { - GoalCreateView(store: $0) - } - .navigationDestination( - item: $store.scope(state: \.recordDetail, action: \.recordDetail) - .hiddenInPane { usesDesktopLayout || isHidden() }, - interactivePop: true - ) { _ in + // 사이드바가 있는 창은 기록을 사이드바까지 덮는 상세 판으로 열고 버전 이력은 판 안에서 이동 + .compositionDetail( + item: $store.scope(state: \.recordDetail, action: \.recordDetail).hiddenInPane(isHidden) + ) { _, _ in if let detailStore = store.scope(state: \.recordDetailContent, action: \.recordDetailContent) { RecordDetailView(store: detailStore, onUpdate: { store.send(.view(.refresh)) }) } - } - // 사이드바가 있는 창은 기록을 사이드바까지 덮는 상세 판으로 열고 버전 이력은 판 안에서 이동 - .detailPanel( - item: $store.scope(state: \.recordDetail, action: \.recordDetail) - .hiddenInPane { !usesDesktopLayout || isHidden() } - ) { _ in + } panel: { _ in NavigationStack { if let detailStore = store.scope(state: \.recordDetailContent, action: \.recordDetailContent) { RecordDetailView(store: detailStore, onUpdate: { store.send(.view(.refresh)) }) @@ -118,24 +103,20 @@ public struct GoalDetailView: View { } .desktopNavigationTransition() } + // 창 폭이 바뀌면 개발 목표가 새 자리에 나타난 뒤에 다시 쌓음 .navigationDestination( - item: $store.scope(state: \.todoDetail, action: \.todoDetail), + item: $store.scope(state: \.todoDetail, action: \.todoDetail).hiddenInPane(isHidden), interactivePop: true ) { // 사이드바가 있으면 Todo 목록 옆 칸의 상세와 같은 칸 모양으로 표시하고 뒤로 가면 개발 목표로 돌아감 - TodoDetailView( - store: Store( - initialState: TodoDetailFeature.State( - todoId: $0.todoId, - showEditButton: false - ) - ) { - TodoDetailFeature() - }, - showsBackOnDesktop: true - ) + TodoDetailView(store: $0, showsBackOnDesktop: true) .environment(\.showsPaneTitleBar, usesDesktopLayout) - .detailSideBarTarget(.todo(id: $0.todoId, isEditable: false)) + .compositionRight { + if let todoId = store.todoDetail?.todoId { + TodoDetailSideBarView(todoId: todoId, isEditable: false, windowEvent: windowEvent) + .id(todoId) + } + } } .onAppear { store.send(.view(.appear(onDesktop: usesDesktopLayout))) } } diff --git a/Application/Presentation/HomeTab/Sources/Record/History/RecordVersionHistoryView.swift b/Application/Presentation/HomeTab/Sources/Record/History/RecordVersionHistoryView.swift index 9b72c7b31..142990ab5 100644 --- a/Application/Presentation/HomeTab/Sources/Record/History/RecordVersionHistoryView.swift +++ b/Application/Presentation/HomeTab/Sources/Record/History/RecordVersionHistoryView.swift @@ -64,19 +64,13 @@ struct RecordVersionHistoryView: View { .safeAreaInset(edge: .top, spacing: 0) { topBar } .background(Color.background.ignoresSafeArea()) .duoToolbarVisibility(showsBackButton: true) - .navigationDestination( - item: versionDetail.hiddenInPane { usesDesktopLayout || isHidden() }, - interactivePop: true - ) { destination in + // 사이드바가 있는 창은 이전 버전을 사이드바까지 덮는 상세 판으로 열기 + .compositionDetail(item: versionDetail.hiddenInPane(isHidden)) { destination, _ in RecordVersionDetailView( store: store, version: destination.version ) - } - // 사이드바가 있는 창은 이전 버전을 사이드바까지 덮는 상세 판으로 열기 - .detailPanel( - item: versionDetail.hiddenInPane { !usesDesktopLayout || isHidden() } - ) { destination in + } panel: { destination in RecordVersionDetailView( store: store, version: destination.version diff --git a/Application/Presentation/HomeTab/Sources/Search/SearchFeature.swift b/Application/Presentation/HomeTab/Sources/Search/SearchFeature.swift index 9bcdbe0f9..8228234bc 100644 --- a/Application/Presentation/HomeTab/Sources/Search/SearchFeature.swift +++ b/Application/Presentation/HomeTab/Sources/Search/SearchFeature.swift @@ -15,14 +15,14 @@ struct SearchFeature { @ObservableState struct State: Equatable { @Presents var alert: AlertState? + // 연 결과 상세, 좁은 창은 홈 내비게이션에 쌓고 사이드바가 있는 창은 사이드바까지 덮는 상세 판에 표시 + @Presents var detail: TodoDetailFeature.State? var loading = LoadingFeature.State() var isSearching = false var searchQuery = "" var todos: [SearchTodoItem] = [] var recentQueries = OrderedSet() var showAllTodos = false - // Mac에서 사이드바까지 덮는 상세 판에 연 Todo - var panelTodo: TodoIdItem? let contentsLimit = 5 init(recentQueries: [String] = []) { @@ -53,7 +53,9 @@ struct SearchFeature { enum Action: BindableAction, Equatable { case onAppear case alert(PresentationAction) + case detail(PresentationAction) case binding(BindingAction) + case selectTodo(String) case addRecentQuery(String) case removeRecentQuery(String) case clearRecentQueries @@ -97,6 +99,10 @@ struct SearchFeature { } case .alert: break + case .detail: + break + case .selectTodo(let todoId): + state.detail = TodoDetailFeature.State(todoId: todoId, showEditButton: true) case .binding(\.isSearching): if !state.isSearching { return Self.cancelSearchEffect(isLoading: state.isLoading) @@ -151,6 +157,9 @@ struct SearchFeature { return .none } .ifLet(\.$alert, action: \.alert) + .ifLet(\.$detail, action: \.detail) { + TodoDetailFeature() + } } } diff --git a/Application/Presentation/HomeTab/Sources/Search/SearchView.swift b/Application/Presentation/HomeTab/Sources/Search/SearchView.swift index 8a496aa18..bde13f8d9 100644 --- a/Application/Presentation/HomeTab/Sources/Search/SearchView.swift +++ b/Application/Presentation/HomeTab/Sources/Search/SearchView.swift @@ -16,43 +16,21 @@ struct SearchView: View { @Environment(\.windowControlsInset) private var windowControlsInset @Environment(\.readableContentWidth) private var readableContentWidth @Environment(\.deviceType) private var deviceType - @State private var store: StoreOf - // 홈 내비게이션에 쌓아 연 검색에서 Todo 상세를 홈 내비게이션에 쌓는 동작 - private let onSelectTodo: (String) -> Void - // 홈 내비게이션 맨 위에 있는지 여부, 아래에 깔린 동안은 상세 판을 띄우지 않음 - private let isOnTop: Bool + @Bindable private var store: StoreOf + // 좁은 창에서 쌓아 연 결과 상세의 편집을 Mac 편집 창과 같은 경로로 전달 + private let windowEvent: TodoEditorWindowEvent? - // 열 때마다 빈 입력칸으로 시작하고 최근 검색은 열 때 읽음 - // 닫으면 Store와 함께 진행 중인 검색 요청과 상세 판도 사라짐 - init(isOnTop: Bool, onSelectTodo: @escaping (String) -> Void) { - @Dependency(\.homeFetchRecentSearchQueriesUseCase) var fetchRecentSearchQueriesUseCase - self._store = State(initialValue: Store( - initialState: SearchFeature.State( - recentQueries: fetchRecentSearchQueriesUseCase.execute() - ) - ) { - SearchFeature() - }) - self.onSelectTodo = onSelectTodo - self.isOnTop = isOnTop + // 닫으면 쌓은 상태와 함께 진행 중인 검색 요청과 상세도 사라짐 + init(store: StoreOf, windowEvent: TodoEditorWindowEvent?) { + self.store = store + self.windowEvent = windowEvent } var body: some View { content { todoId in - // 사이드바가 있는 창은 사이드바까지 덮는 상세 판으로 열기 - // 좁은 창에서 쌓아 연 상세도 기억해 넓어지면 같은 Todo를 상세 판으로 표시 - store.send(.binding(.set(\.panelTodo, TodoIdItem(id: todoId)))) - if !usesDesktopLayout { - onSelectTodo(todoId) - } + store.send(.selectTodo(todoId)) } .duoToolbarVisibility(showsBackButton: true) - // 좁은 창에서 쌓아 연 결과 상세를 내리면 넓어져도 상세 판으로 다시 열지 않음 - .onAppear { - if !usesDesktopLayout { - store.send(.binding(.set(\.panelTodo, nil))) - } - } } private func content(onSelectTodo: @escaping (String) -> Void) -> some View { @@ -90,13 +68,14 @@ struct SearchView: View { } .background(Color.background.ignoresSafeArea()) .prominentAlert(store, state: \.alert, action: \.alert) - // 좁은 창으로 바뀌면 상세 판을 숨기고 넓어지면 다시 표시 - // 쌓아 연 상세를 편집하는 중에 넓어지면 편집을 마치고 상세가 내려간 뒤 표시 - .detailPanel(item: $store.panelTodo.activePresentation(when: usesDesktopLayout && isOnTop)) { item in + // 좁은 창은 홈 내비게이션에 쌓고, 사이드바가 있는 창은 사이드바까지 덮는 상세 판에 표시 + // 창 폭이 바뀌면 같은 상세 상태를 바뀐 자리에서 이어 그림 + .compositionDetail(item: $store.scope(state: \.detail, action: \.detail)) { detailStore, _ in + TodoDetailView(store: detailStore, windowEvent: windowEvent) + } panel: { detailStore in TodoDetailPanel( - todoId: item.id, - location: Text("search_title", bundle: PresentationResources.bundle), - isEditable: true + store: detailStore, + location: Text("search_title", bundle: PresentationResources.bundle) ) } } diff --git a/Application/Presentation/HomeTab/Sources/Todo/List/TodoListFeature+Effects.swift b/Application/Presentation/HomeTab/Sources/Todo/List/TodoListFeature+Effects.swift index ad1f5cdcb..31a479f6a 100644 --- a/Application/Presentation/HomeTab/Sources/Todo/List/TodoListFeature+Effects.swift +++ b/Application/Presentation/HomeTab/Sources/Todo/List/TodoListFeature+Effects.swift @@ -74,9 +74,10 @@ extension TodoListFeature { func swipeTodoEffect(_ todo: TodoListItem, state: inout State) -> Effect { guard state.todos.contains(where: { $0.id == todo.id }) else { return .none } state.undoTodoId = todo.id - // 지운 Todo의 상세 칸은 되돌리기와 관계없이 바로 닫음 - if state.selectedTodoId == todo.id { - state.selectedTodoId = nil + // 지운 Todo의 상세는 되돌리기와 관계없이 바로 닫음 + if state.detail?.todoId == todo.id { + state.detail = nil + state.showsDetailInPane = false } Self.setTodoHidden(&state, todoId: todo.id, isHidden: true) return deleteEffect(todo) diff --git a/Application/Presentation/HomeTab/Sources/Todo/List/TodoListFeature.swift b/Application/Presentation/HomeTab/Sources/Todo/List/TodoListFeature.swift index dc3cc3097..25a499f37 100644 --- a/Application/Presentation/HomeTab/Sources/Todo/List/TodoListFeature.swift +++ b/Application/Presentation/HomeTab/Sources/Todo/List/TodoListFeature.swift @@ -17,6 +17,10 @@ struct TodoListFeature { struct State: Equatable { @Presents var alert: AlertState? @Presents var fullScreenCover: FullScreenCoverState? + // 연 Todo 상세, 좁은 창은 내비게이션에 쌓고 사이드바가 있는 창은 상세 판이나 오른쪽 칸에 표시 + @Presents var detail: TodoDetailFeature.State? + // 사이드바가 있는 창에서 상세 판 대신 목록 오른쪽 칸에 표시 + var showsDetailInPane = false var category: TodoCategory var todos: [TodoListItem] = [] var query: TodoQuery @@ -24,12 +28,8 @@ struct TodoListFeature { var isSearching = false var loading = LoadingFeature.State() var searchQuery = "" - var selectedTodoId: String? - // 사이드바가 있는 창에서 사이드바까지 덮는 상세 판에 연 Todo - var panelTodo: TodoIdItem? // Mac에서 마우스를 올린 행, 선택 행처럼 둥글게 표시하고 맞닿는 구분선을 숨김 var hoveredTodoId: String? - var detailRevision = 0 var undoTodoId: String? var nextCursor: TodoCursor? @@ -71,9 +71,10 @@ struct TodoListFeature { } } - enum Action: BindableAction { + enum Action: BindableAction, Equatable { case alert(PresentationAction) case fullScreenCover(PresentationAction) + case detail(PresentationAction) case binding(BindingAction) case view(ViewAction) case store(StoreAction) @@ -86,6 +87,9 @@ struct TodoListFeature { enum ViewAction: Equatable { case refresh + // 사이드바가 있는 창은 연 곳(상세 판이나 오른쪽 칸)의 내용을 바꿈 + case selectTodo(String) + case openTodo(String, inPane: Bool) case swipeTodo(TodoListItem) case resetFilters case finishDeleteToast(String) @@ -147,6 +151,10 @@ struct TodoListFeature { state.fullScreenCover = nil case .fullScreenCover: break + case .detail(.dismiss): + state.showsDetailInPane = false + case .detail: + break case .binding(\.query.sortTarget), .binding(\.query.sortOrder), .binding(\.query.isPinned), .binding(\.query.completionFilter): state.nextCursor = nil @@ -187,6 +195,9 @@ struct TodoListFeature { .ifLet(\.$fullScreenCover, action: \.fullScreenCover) { FullScreenCoverFeature() } + .ifLet(\.$detail, action: \.detail) { + TodoDetailFeature() + } } } @@ -302,6 +313,14 @@ private extension TodoListFeature { switch action { case .refresh: return fetchEffect(query: state.query, cursor: nil, showsIndicator: false) + case .selectTodo(let todoId): + // 이미 연 Todo는 불러온 상세와 열어 둔 시트를 그대로 둠 + if state.detail?.todoId != todoId { + state.detail = TodoDetailFeature.State(todoId: todoId, showEditButton: true) + } + case .openTodo(let todoId, let inPane): + state.showsDetailInPane = inPane + return reduce(.selectTodo(todoId), state: &state) case .onAppear: return fetchEffect(query: state.query, cursor: nil) case .windowTodoUpdated: @@ -369,9 +388,9 @@ private extension TodoListFeature { if let index = state.todos.firstIndex(where: { $0.id == todo.id }) { state.todos[index] = todo } - // 상세 칸이 바뀐 완료·중요 상태를 다시 조회하도록 갱신 - if todo.id == state.selectedTodoId { - state.detailRevision += 1 + // 연 상세와 세부 정보 사이드바가 바뀐 완료, 중요 상태를 다시 조회 + if todo.id == state.detail?.todoId { + return .send(.detail(.presented(.fetch))) } case .setTodoHidden(let todoId, let isHidden): Self.setTodoHidden(&state, todoId: todoId, isHidden: isHidden) diff --git a/Application/Presentation/HomeTab/Sources/Todo/List/TodoListView.swift b/Application/Presentation/HomeTab/Sources/Todo/List/TodoListView.swift index 42396f59e..37b6e240c 100644 --- a/Application/Presentation/HomeTab/Sources/Todo/List/TodoListView.swift +++ b/Application/Presentation/HomeTab/Sources/Todo/List/TodoListView.swift @@ -13,101 +13,75 @@ import PresentationShared struct TodoListView: View { @Environment(\.isTabContentActive) private var isTabContentActive - @Environment(\.usesDesktopLayout) private var usesDesktopLayout - @Environment(\.usesPaneLayout) private var usesPaneLayout - @State private var store: StoreOf + @Bindable private var store: StoreOf private let windowEvent: TodoEditorWindowEvent? - private let onSelectTodo: (String) -> Void - init( - store: StoreOf, - windowEvent: TodoEditorWindowEvent? = nil, - onSelectTodo: @escaping (String) -> Void = { _ in } - ) { + init(store: StoreOf, windowEvent: TodoEditorWindowEvent? = nil) { self.store = store self.windowEvent = windowEvent - self.onSelectTodo = onSelectTodo } var body: some View { - // 사이드바가 있는 창은 목록을 창 전체 폭으로 두고 오른쪽 칸에서 연 Todo나 작성 화면이 있을 때만 두 칸으로 나눔 - PaneSplitView(splitsOnDesktop: store.selectedTodoId != nil || store.fullScreenCover != nil) { + PaneSplitView { TodoListContent(store: store) { todoId in - // 사이드바가 있는 창은 오른쪽 칸을 열지 않았으면 상세 판으로 열고 열었으면 오른쪽 칸 내용을 바꿈 - if usesDesktopLayout && store.selectedTodoId == nil { - store.send(.binding(.set(\.panelTodo, TodoIdItem(id: todoId)))) - return - } - // 칸 화면으로 바뀌면 같은 Todo를 옆 칸에 표시하도록 칸으로 나누지 않은 화면에서도 선택 기억 - store.send(.binding(.set(\.selectedTodoId, todoId))) - if !usesPaneLayout { - onSelectTodo(todoId) - } + store.send(.view(.selectTodo(todoId))) } - } detail: { - // 칸으로 나눈 화면은 새 Todo를 덮는 화면 대신 상세 칸 자리에서 작성 - if usesPaneLayout, - let editorStore = store.scope( - state: \.fullScreenCover?.todoEditor, - action: \.fullScreenCover.presented.todoEditor - ) { - TodoEditorView(store: editorStore, onClose: { store.send(.fullScreenCover(.dismiss)) }) - } else { - TodoDetailPane( - todoId: store.selectedTodoId, - showEditButton: true, + // 좁은 창은 목록 위에 쌓고, 사이드바가 있는 창은 상세 판이나 오른쪽 칸에 표시 + // 창 폭이 바뀌면 같은 상세 상태를 바뀐 자리에서 이어 그림 + .compositionDetail( + item: $store.scope(state: \.detail, action: \.detail), + inPane: store.showsDetailInPane, + isActive: isTabContentActive + ) { detailStore, onClose in + TodoDetailView( + store: detailStore, windowEvent: windowEvent, - onClose: usesDesktopLayout ? { store.send(.binding(.set(\.selectedTodoId, nil))) } : nil + isPaneDetail: onClose != nil, + onClose: onClose ) - .id(store.detailRevision) + // 칸 안에서 다른 Todo로 바꾸면 그 Todo를 조회 + .id(detailStore.todoId) + } panel: { detailStore in + // 목록에서 빠진 Todo는 지울 경로가 없어 판 메뉴에서 삭제 생략 + let todo = store.todos.first { $0.id == detailStore.todoId } + + TodoDetailPanel( + store: detailStore, + location: Text(TodoCategoryItem(from: store.category).localizedName), + windowEvent: windowEvent, + onMoveToPane: { + store.send(.binding(.set(\.showsDetailInPane, true))) + }, + onDelete: todo.map { todo in + { + store.send(.view(.swipeTodo(todo))) + presentDeleteTodoToast(todo.id, store: store) + } + } + ) + } + // 칸으로 나눈 화면은 새 Todo를 덮는 화면 대신 상세 칸 자리에서 작성 + .compositionEditor( + item: $store.scope(state: \.fullScreenCover, action: \.fullScreenCover), + isActive: isTabContentActive + ) { coverStore, onClose in + fullScreenCoverContent(coverStore, onClose: onClose) } } - // 좁은 창으로 바뀌면 상세 판을 숨기고 넓어지면 다시 표시 - .detailPanel(item: $store.panelTodo.activePresentation(when: isTabContentActive && usesDesktopLayout)) { item in - // 목록에서 빠진 Todo는 지울 경로가 없어 판 메뉴에서 삭제 생략 - let todo = store.todos.first { $0.id == item.id } - - TodoDetailPanel( - todoId: item.id, - location: Text(TodoCategoryItem(from: store.category).localizedName), - isEditable: true, - windowEvent: windowEvent, - onMoveToPane: { - store.send(.binding(.set(\.panelTodo, nil))) - store.send(.binding(.set(\.selectedTodoId, item.id))) - }, - onDelete: todo.map { todo in - { - store.send(.binding(.set(\.panelTodo, nil))) - store.send(.view(.swipeTodo(todo))) - presentDeleteTodoToast(todo.id, store: store) - } - } - ) + // 옆 칸에 연 Todo의 속성은 세부 정보 사이드바에 표시 + .compositionRight(isActive: store.showsDetailInPane && store.detail != nil) { + if let detailStore = store.scope(state: \.detail, action: \.detail.presented) { + TodoDetailSideBarView(store: detailStore) + .id(detailStore.todoId) + } } - .detailSideBarTarget( - store.selectedTodoId.map { .todo(id: $0, isEditable: true, revision: store.detailRevision) } - ) .prominentAlert(store, state: \.alert, action: \.alert) .onReceive(windowSubmits) { _ in // 상세 칸에서 편집한 Todo를 옆 목록에도 반영 store.send(.view(.windowTodoUpdated)) } - .fullScreenCover( - item: $store.scope(state: \.fullScreenCover, action: \.fullScreenCover) - .activePresentation(when: isTabContentActive) - .hiddenInPane(usesPaneLayout) - ) { coverStore in - fullScreenCoverContent(coverStore) - } .background(Color.background.ignoresSafeArea()) .task { store.send(.view(.onAppear)) } - // 좁은 창에서 쌓아 연 상세를 내리면 넓어져도 오른쪽 칸으로 다시 열지 않음 - .onAppear { - if !usesDesktopLayout { - store.send(.binding(.set(\.selectedTodoId, nil))) - } - } } private var windowSubmits: AnyPublisher { @@ -118,12 +92,13 @@ struct TodoListView: View { private func fullScreenCoverContent( _ coverStore: Store< TodoListFeature.FullScreenCoverState, - TodoListFeature.Action.FullScreenCover> + TodoListFeature.Action.FullScreenCover>, + onClose: (() -> Void)? ) -> some View { switch coverStore.destination { case .editor: if let todoEditorStore = coverStore.scope(state: \.todoEditor, action: \.todoEditor) { - TodoEditorView(store: todoEditorStore) + TodoEditorView(store: todoEditorStore, onClose: onClose) } } } @@ -153,7 +128,7 @@ private struct TodoListContent: View { } else { // 칸으로 나누지 않은 화면은 상세 칸이 없어 선택 표시 생략 let highlightedTodoIds = ( - [store.hoveredTodoId] + (usesPaneLayout ? [store.selectedTodoId, store.panelTodo?.id] : []) + [store.hoveredTodoId] + (usesPaneLayout ? [store.detail?.todoId] : []) ).compactMap { $0 } LazyVStack(alignment: .leading, spacing: 0) { @@ -195,7 +170,7 @@ private struct TodoListContent: View { // 사이드바가 있는 창의 우클릭과 길게 누른 메뉴는 상세 판과 오른쪽 칸으로 여는 항목을 맨 위에 표시 if usesDesktopLayout { Button { - store.send(.binding(.set(\.panelTodo, TodoIdItem(id: todo.id)))) + store.send(.view(.openTodo(todo.id, inPane: false))) } label: { Label { Text("detail_panel_open", bundle: PresentationResources.bundle) @@ -204,7 +179,7 @@ private struct TodoListContent: View { } } Button { - store.send(.binding(.set(\.selectedTodoId, todo.id))) + store.send(.view(.openTodo(todo.id, inPane: true))) } label: { Label { Text("detail_panel_open_in_pane", bundle: PresentationResources.bundle) @@ -328,7 +303,6 @@ private struct TodoListTopBar: View { @Environment(\.readableContentWidth) private var readableContentWidth @Environment(\.showsPaneTitleBar) private var showsPaneTitleBar @Environment(\.deviceType) private var deviceType - @Environment(\.sideBarRequest) private var sideBarRequest @Namespace private var searchTransition let store: StoreOf @@ -384,11 +358,6 @@ private struct TodoListTopBar: View { } } .background(Color.background, ignoresSafeAreaEdges: .top) - // 사이드바 Todo 메뉴의 작성은 이 목록의 작성 버튼과 같은 방식으로 작성 - .onChange(of: sideBarRequest) { _, request in - guard request?.action == .createTodo else { return } - store.send(.store(.setFullScreenCover(.editor))) - } } @ViewBuilder diff --git a/Application/Presentation/HomeTab/Tests/Home/HomeFeatureTestSupport.swift b/Application/Presentation/HomeTab/Tests/Home/HomeFeatureTestSupport.swift index 611cab136..e6b32c901 100644 --- a/Application/Presentation/HomeTab/Tests/Home/HomeFeatureTestSupport.swift +++ b/Application/Presentation/HomeTab/Tests/Home/HomeFeatureTestSupport.swift @@ -25,15 +25,15 @@ struct StoreTestAdapter { var hasDevelopmentGoalsLoadFailure: Bool { store.state.hasDevelopmentGoalsLoadFailure } var isNetworkConnected: Bool { store.state.isNetworkConnected } var showContentPicker: Bool { store.state.showContentPicker } - var showCategoryManage: Bool { - store.state.sheet?.categoryManageState != nil - } + var showCategoryManage: Bool { store.state.categoryManage != nil } var showTodoEditor: Bool { store.state.showTodoEditor } - var sheet: HomeFeature.SheetState? { store.state.sheet } + var categoryManage: CategoryManageFeature.State? { store.state.categoryManage } + var goalCreate: GoalCreateFeature.State? { store.state.goalCreate } + var goalDetail: GoalDetailFeature.State? { store.state.goalDetail } var alert: AlertState? { store.state.alert } - var sideBarRequestAfterGoalDiscard: SideBarRequest? { store.state.sideBarRequestAfterGoalDiscard } init( + initialState: HomeFeature.State = HomeFeature.State(), fetchPreferencesUseCase: FetchTodoCategoryPreferencesUseCase = FetchTodoCategoryPreferencesUseCaseSpy(), updatePreferencesUseCase: UpdateTodoCategoryPreferencesUseCase = UpdateTodoCategoryPreferencesUseCaseSpy(), networkConnectivityUseCase: ObserveNetworkConnectivityUseCase = ObserveNetworkConnectivityUseCaseSpy(), @@ -45,7 +45,7 @@ struct StoreTestAdapter { ) { let clock = TestClock() self.clock = clock - store = TestStore(initialState: HomeFeature.State()) { + store = TestStore(initialState: initialState) { HomeFeature() } withDependencies: { $0.fetchTodoCategoryPreferencesUseCase = fetchPreferencesUseCase @@ -99,32 +99,29 @@ struct StoreTestAdapter { await store.send(.view(.tapDevelopmentGoal(goalID))) } - func setSheet(_ sheet: HomeFeature.SheetState?) async { - await store.send(.store(.setSheet(sheet))) - } - func tapAddCategoryManageItem() async { - await store.send(.sheet(.presented(.categoryManage(.tapAddUserCategory)))) + await store.send(.categoryManage(.presented(.tapAddUserCategory))) } func tapCategoryManageItem(_ item: TodoCategoryItem) async { - await store.send(.sheet(.presented(.categoryManage(.tapItem(item))))) + await store.send(.categoryManage(.presented(.tapItem(item)))) } func changeCategoryPreferences(_ items: [TodoCategoryItem]) async { - await store.send(.sheet(.presented(.categoryManage(.delegate(.changed(items)))))) + await store.send(.categoryManage(.presented(.delegate(.changed(items))))) } func setGoalCreateSaving() async { - await store.send(.sheet(.presented(.goalCreate(.binding(.set(\.isSaving, true)))))) + await store.send(.goalCreate(.presented(.binding(.set(\.isSaving, true))))) } func setGoalCreateTitle(_ title: String) async { - await store.send(.sheet(.presented(.goalCreate(.binding(.set(\.title, title)))))) + await store.send(.goalCreate(.presented(.binding(.set(\.title, title))))) } - func closeGoalDraftForSideBarRequest(_ request: SideBarRequest) async { - await store.send(.view(.closeGoalDraftForSideBarRequest(request))) + func sideBarRequested(_ request: SideBarRequest) async { + await store.send(.view(.sideBarRequested(request))) + await drainReceivedActions() } func discardGoalDraft() async { @@ -137,7 +134,7 @@ struct StoreTestAdapter { } func goalCreateSaved(_ goal: DevelopmentGoal) async { - await store.send(.sheet(.presented(.goalCreate(.delegate(.saved(goal)))))) + await store.send(.goalCreate(.presented(.delegate(.saved(goal))))) await drainReceivedActions() } @@ -146,8 +143,13 @@ struct StoreTestAdapter { await settle() } - func dismissSheet() async { - await store.send(.sheet(.dismiss)) + func dismissGoalCreate() async { + await store.send(.goalCreate(.dismiss)) + await drainReceivedActions() + } + + func dismissCategoryManage() async { + await store.send(.categoryManage(.dismiss)) await drainReceivedActions() } diff --git a/Application/Presentation/HomeTab/Tests/Home/HomeFeatureTests.swift b/Application/Presentation/HomeTab/Tests/Home/HomeFeatureTests.swift index cb8e6e2d5..ab9e3ff91 100644 --- a/Application/Presentation/HomeTab/Tests/Home/HomeFeatureTests.swift +++ b/Application/Presentation/HomeTab/Tests/Home/HomeFeatureTests.swift @@ -127,15 +127,15 @@ struct HomeFeatureTests { await adapter.tapCreateDevelopmentGoal() - #expect(adapter.sheet == .goalCreate(GoalCreateFeature.State())) + #expect(adapter.goalCreate == GoalCreateFeature.State()) - await adapter.dismissSheet() + await adapter.dismissGoalCreate() - #expect(adapter.sheet == nil) + #expect(adapter.goalCreate == nil) await adapter.tapDevelopmentGoal("goal") - #expect(adapter.sheet?.goalDetailState?.goalId == "goal") + #expect(adapter.goalDetail?.goalId == "goal") } @Test("작성 중인 새 개발 목표가 있으면 버릴지 물은 뒤 버리면 고른 목표를 연다") @@ -147,30 +147,30 @@ struct HomeFeatureTests { await adapter.tapDevelopmentGoal("goal") #expect(adapter.alert == HomeFeature.discardGoalDraftAlertState(isEditing: false)) - #expect(adapter.sheet?.goalCreateState?.title == "목표") + #expect(adapter.goalCreate?.title == "목표") await adapter.discardGoalDraft() - #expect(adapter.sheet?.goalDetailState?.goalId == "goal") + #expect(adapter.goalDetail?.goalId == "goal") } @Test("수정 중인 개발 목표가 있으면 버릴지 물은 뒤 버리면 고른 목표를 연다") func 수정_중인_개발_목표가_있으면_버릴지_물은_뒤_버리면_고른_목표를_연다() async throws { - let adapter = StoreTestAdapter() let goal = try makeDevelopmentGoal() - var detail = GoalDetailFeature.State(goalId: goal.id) - detail.goalEdit = GoalCreateFeature.State(goal: goal) - detail.goalEdit?.title = "바꾼 제목" + var state = HomeFeature.State() + state.goalDetail = GoalDetailFeature.State(goalId: goal.id) + state.goalDetail?.goalEdit = GoalCreateFeature.State(goal: goal) + state.goalDetail?.goalEdit?.title = "바꾼 제목" + let adapter = StoreTestAdapter(initialState: state) - await adapter.setSheet(.goalDetail(detail)) await adapter.tapDevelopmentGoal("other") #expect(adapter.alert == HomeFeature.discardGoalDraftAlertState(isEditing: true)) - #expect(adapter.sheet?.goalDetailState?.goalEdit?.title == "바꾼 제목") + #expect(adapter.goalDetail?.goalEdit?.title == "바꾼 제목") await adapter.discardGoalDraft() - #expect(adapter.sheet?.goalDetailState?.goalId == "other") + #expect(adapter.goalDetail?.goalId == "other") } @Test("작성 중인 새 개발 목표를 버리지 않으면 칸을 유지한다") @@ -183,24 +183,25 @@ struct HomeFeatureTests { await adapter.cancelGoalDraftDiscard() #expect(adapter.alert == nil) - #expect(adapter.sheet?.goalCreateState?.title == "목표") + #expect(adapter.goalCreate?.title == "목표") } @Test("작성 중인 새 개발 목표를 버리면 미뤄 둔 사이드바 요청을 다시 처리한다") func 작성_중인_새_개발_목표를_버리면_미뤄_둔_사이드바_요청을_다시_처리한다() async { let adapter = StoreTestAdapter() - let request = SideBarRequest(id: UUID(), action: .open(.home)) + let request = SideBarRequest(id: UUID(), action: .open(.developmentGoal("goal"))) await adapter.tapCreateDevelopmentGoal() await adapter.setGoalCreateTitle("목표") - await adapter.closeGoalDraftForSideBarRequest(request) + await adapter.sideBarRequested(request) - #expect(adapter.sideBarRequestAfterGoalDiscard == nil) + #expect(adapter.alert == HomeFeature.discardGoalDraftAlertState(isEditing: false)) + #expect(adapter.goalDetail == nil) await adapter.discardGoalDraft() - #expect(adapter.sheet == nil) - #expect(adapter.sideBarRequestAfterGoalDiscard == request) + #expect(adapter.goalCreate == nil) + #expect(adapter.goalDetail?.goalId == "goal") } @Test("입력하지 않은 새 개발 목표는 묻지 않고 고른 목표를 연다") @@ -211,31 +212,33 @@ struct HomeFeatureTests { await adapter.tapDevelopmentGoal("goal") #expect(adapter.alert == nil) - #expect(adapter.sheet?.goalDetailState?.goalId == "goal") + #expect(adapter.goalDetail?.goalId == "goal") } @Test("새 개발 목표를 저장하는 동안 시트를 바꾸지 않는다") func 새_개발_목표를_저장하는_동안_시트를_바꾸지_않는다() async { - let adapter = StoreTestAdapter() + var state = HomeFeature.State() + state.usesDesktopLayout = true + let adapter = StoreTestAdapter(initialState: state) await adapter.tapCreateDevelopmentGoal() await adapter.setGoalCreateSaving() await adapter.tapDevelopmentGoal("goal") - await adapter.setSheet(nil) + await adapter.sideBarRequested(SideBarRequest(id: UUID(), action: .open(.home))) - #expect(adapter.sheet?.goalCreateState?.isSaving == true) + #expect(adapter.goalCreate?.isSaving == true) } @Test("수정 중인 개발 목표를 버리고 칸을 닫으면 개발 목표 목록을 다시 조회한다") func 수정_중인_개발_목표를_버리고_칸을_닫으면_개발_목표_목록을_다시_조회한다() async throws { let goalsSpy = FetchDevelopmentGoalsUseCaseSpy() - let adapter = StoreTestAdapter(fetchDevelopmentGoalsUseCase: goalsSpy) let goal = try makeDevelopmentGoal() - var detail = GoalDetailFeature.State(goalId: goal.id) - detail.goalEdit = GoalCreateFeature.State(goal: goal) - detail.goalEdit?.title = "바꾼 제목" + var state = HomeFeature.State() + state.goalDetail = GoalDetailFeature.State(goalId: goal.id) + state.goalDetail?.goalEdit = GoalCreateFeature.State(goal: goal) + state.goalDetail?.goalEdit?.title = "바꾼 제목" + let adapter = StoreTestAdapter(initialState: state, fetchDevelopmentGoalsUseCase: goalsSpy) - await adapter.setSheet(.goalDetail(detail)) await adapter.tapManageTodoCategory() #expect(goalsSpy.queries.isEmpty) @@ -244,45 +247,45 @@ struct HomeFeatureTests { await waitUntil { !goalsSpy.queries.isEmpty } #expect(goalsSpy.queries == [.init(status: .inProgress)]) - #expect(adapter.sheet?.goalDetailState == nil) + #expect(adapter.goalDetail == nil) } @Test("수정 중인 개발 목표를 버리면 미뤄 둔 사이드바 요청을 다시 처리한다") func 수정_중인_개발_목표를_버리면_미뤄_둔_사이드바_요청을_다시_처리한다() async throws { - let adapter = StoreTestAdapter() - let request = SideBarRequest(id: UUID(), action: .open(.home)) + let request = SideBarRequest(id: UUID(), action: .open(.developmentGoal("other"))) let goal = try makeDevelopmentGoal() - var detail = GoalDetailFeature.State(goalId: goal.id) - detail.goalEdit = GoalCreateFeature.State(goal: goal) - detail.goalEdit?.content = "바꾼 설명" + var state = HomeFeature.State() + state.goalDetail = GoalDetailFeature.State(goalId: goal.id) + state.goalDetail?.goalEdit = GoalCreateFeature.State(goal: goal) + state.goalDetail?.goalEdit?.content = "바꾼 설명" + let adapter = StoreTestAdapter(initialState: state) - await adapter.setSheet(.goalDetail(detail)) - await adapter.closeGoalDraftForSideBarRequest(request) + await adapter.sideBarRequested(request) #expect(adapter.alert == HomeFeature.discardGoalDraftAlertState(isEditing: true)) - #expect(adapter.sideBarRequestAfterGoalDiscard == nil) + #expect(adapter.goalDetail?.goalId == goal.id) await adapter.discardGoalDraft() - #expect(adapter.sheet == nil) - #expect(adapter.sideBarRequestAfterGoalDiscard == request) + #expect(adapter.goalDetail?.goalId == "other") } @Test("수정 중인 개발 목표를 저장하는 동안 시트를 바꾸지 않는다") func 수정_중인_개발_목표를_저장하는_동안_시트를_바꾸지_않는다() async throws { - let adapter = StoreTestAdapter() let goal = try makeDevelopmentGoal() - var detail = GoalDetailFeature.State(goalId: goal.id) - detail.goalEdit = GoalCreateFeature.State(goal: goal) - detail.goalEdit?.title = "바꾼 제목" - detail.goalEdit?.isSaving = true + var state = HomeFeature.State() + state.usesDesktopLayout = true + state.goalDetail = GoalDetailFeature.State(goalId: goal.id) + state.goalDetail?.goalEdit = GoalCreateFeature.State(goal: goal) + state.goalDetail?.goalEdit?.title = "바꾼 제목" + state.goalDetail?.goalEdit?.isSaving = true + let adapter = StoreTestAdapter(initialState: state) - await adapter.setSheet(.goalDetail(detail)) await adapter.tapDevelopmentGoal("other") - await adapter.setSheet(nil) + await adapter.sideBarRequested(SideBarRequest(id: UUID(), action: .open(.home))) #expect(adapter.alert == nil) - #expect(adapter.sheet?.goalDetailState?.goalEdit?.isSaving == true) + #expect(adapter.goalDetail?.goalEdit?.isSaving == true) } @Test("새 개발 목표를 저장하면 시트를 닫고 홈 데이터를 다시 조회한다") @@ -296,7 +299,7 @@ struct HomeFeatureTests { await adapter.goalCreateSaved(goal) await waitUntil { adapter.hasDevelopmentGoalsLoaded } - #expect(adapter.sheet == nil) + #expect(adapter.goalCreate == nil) #expect(adapter.developmentGoalItems.map(\.id) == [goal.id]) } @@ -306,11 +309,11 @@ struct HomeFeatureTests { await adapter.tapManageTodoCategory() await adapter.tapAddCategoryManageItem() - let id = adapter.sheet?.categoryManageState?.categorySheet?.category.id + let id = adapter.categoryManage?.categorySheet?.category.id await adapter.tapManageTodoCategory() #expect(id != nil) - #expect(adapter.sheet?.categoryManageState?.categorySheet?.category.id == id) + #expect(adapter.categoryManage?.categorySheet?.category.id == id) } @Test("카테고리 관리에서 바로 저장한 변경은 마지막 값만 저장한다") @@ -339,7 +342,7 @@ struct HomeFeatureTests { await adapter.tapManageTodoCategory() await adapter.changeCategoryPreferences([feature, issue]) - await adapter.dismissSheet() + await adapter.dismissCategoryManage() await adapter.advanceClock(by: .seconds(1)) await waitUntil { !updateSpy.updates.isEmpty } diff --git a/Application/Presentation/HomeTab/Tests/Record/GoalDetailTodoFeatureTests.swift b/Application/Presentation/HomeTab/Tests/Record/GoalDetailTodoFeatureTests.swift index a264e8ca1..74140fb36 100644 --- a/Application/Presentation/HomeTab/Tests/Record/GoalDetailTodoFeatureTests.swift +++ b/Application/Presentation/HomeTab/Tests/Record/GoalDetailTodoFeatureTests.swift @@ -90,7 +90,7 @@ struct GoalDetailTodoFeatureTests { } await store.send(.view(.selectTodo(todo.id))) { - $0.todoDetail = TodoDetailDestination(todoId: todo.id) + $0.todoDetail = TodoDetailFeature.State(todoId: todo.id, showEditButton: false) } } diff --git a/Application/Presentation/HomeTab/Tests/Todo/TodoListFeatureTestDoubles.swift b/Application/Presentation/HomeTab/Tests/Todo/TodoListFeatureTestDoubles.swift index f746e701c..7d3b5902b 100644 --- a/Application/Presentation/HomeTab/Tests/Todo/TodoListFeatureTestDoubles.swift +++ b/Application/Presentation/HomeTab/Tests/Todo/TodoListFeatureTestDoubles.swift @@ -29,8 +29,8 @@ final class TodoListStoreTestAdapter { } var showAlert: Bool { store.state.alert != nil } var appliedFilterCount: Int { store.state.appliedFilterCount } - var selectedTodoId: String? { store.state.selectedTodoId } - var detailRevision: Int { store.state.detailRevision } + var detailTodoId: String? { store.state.detail?.todoId } + var showsDetailInPane: Bool { store.state.showsDetailInPane } init( fetchUseCase: FetchTodosUseCase = TodoListFetchTodosUseCaseSpy(), @@ -51,6 +51,7 @@ final class TodoListStoreTestAdapter { $0.todoListDeleteTodoUseCase = deleteUseCase $0.todoListUndoDeleteTodoUseCase = undoDeleteUseCase $0.trackAnalyticsEventUseCase = trackAnalyticsEventUseCase + $0.fetchReferenceItemsUseCase = TodoListFetchReferenceItemsUseCaseStub() $0.continuousClock = ContinuousClock() configureDependencies?(&$0) } @@ -153,8 +154,16 @@ final class TodoListStoreTestAdapter { await store.send(.view(.finishDeleteToast(todoId))) } - func selectTodo(_ todoId: String?) async { - await store.send(.binding(.set(\.selectedTodoId, todoId))) + func selectTodo(_ todoId: String) async { + await store.send(.view(.selectTodo(todoId))) + } + + func openTodo(_ todoId: String, inPane: Bool) async { + await store.send(.view(.openTodo(todoId, inPane: inPane))) + } + + func dismissDetail() async { + await store.send(.detail(.dismiss)) } func tapToggleCompleted(_ todo: TodoListItem) async { @@ -296,6 +305,12 @@ final class TodoListFetchTodoByIdUseCaseSpy: FetchTodoByIdUseCase { } } +final class TodoListFetchReferenceItemsUseCaseStub: FetchReferenceItemsUseCase { + func execute(_ numbers: [Int]) async throws -> [Int: TodoReference] { + [:] + } +} + final class TodoListUpsertTodoUseCaseSpy: UpsertTodoUseCase { var error: Error? var completion: AsyncStream? diff --git a/Application/Presentation/HomeTab/Tests/Todo/TodoListFeatureTests.swift b/Application/Presentation/HomeTab/Tests/Todo/TodoListFeatureTests.swift index 980c7bc71..3b6719346 100644 --- a/Application/Presentation/HomeTab/Tests/Todo/TodoListFeatureTests.swift +++ b/Application/Presentation/HomeTab/Tests/Todo/TodoListFeatureTests.swift @@ -370,34 +370,56 @@ struct TodoListFeatureTests { #expect(adapter.todos.isEmpty) } - @Test("swipeTodo는 선택한 Todo를 지울 때만 선택을 해제한다") - func swipeTodo는_선택한_Todo를_지울_때만_선택을_해제한다() async { + @Test("swipeTodo는 연 Todo를 지울 때만 상세를 닫는다") + func swipeTodo는_연_Todo를_지울_때만_상세를_닫는다() async { let selected = TodoListItem(from: makeTodoListTodo(id: "todo-selected"))! let other = TodoListItem(from: makeTodoListTodo(id: "todo-other"))! let adapter = TodoListStoreTestAdapter() await adapter.appendTodos([selected, other]) - await adapter.selectTodo("todo-selected") + await adapter.openTodo("todo-selected", inPane: true) await adapter.swipeTodo(other) - #expect(adapter.selectedTodoId == "todo-selected") + #expect(adapter.detailTodoId == "todo-selected") + #expect(adapter.showsDetailInPane) await adapter.swipeTodo(selected) - #expect(adapter.selectedTodoId == nil) + #expect(adapter.detailTodoId == nil) + #expect(!adapter.showsDetailInPane) await adapter.undoDelete() - #expect(adapter.selectedTodoId == nil) + #expect(adapter.detailTodoId == nil) } - @Test("tapToggleCompleted는 선택한 Todo일 때만 상세 칸을 다시 조회하도록 갱신한다") - func tapToggleCompleted는_선택한_Todo일_때만_상세_칸을_다시_조회하도록_갱신한다() async { + @Test("selectTodo는 연 자리를 유지하고, 상세를 닫으면 오른쪽 칸 표시도 끈다") + func selectTodo는_연_자리를_유지하고_상세를_닫으면_오른쪽_칸_표시도_끈다() async { + let adapter = TodoListStoreTestAdapter() + + await adapter.selectTodo("todo-a") + + #expect(adapter.detailTodoId == "todo-a") + #expect(!adapter.showsDetailInPane) + + await adapter.openTodo("todo-b", inPane: true) + await adapter.selectTodo("todo-c") + + #expect(adapter.detailTodoId == "todo-c") + #expect(adapter.showsDetailInPane) + + await adapter.dismissDetail() + + #expect(adapter.detailTodoId == nil) + #expect(!adapter.showsDetailInPane) + } + + @Test("tapToggleCompleted는 연 Todo일 때만 상세를 다시 조회한다") + func tapToggleCompleted는_연_Todo일_때만_상세를_다시_조회한다() async { let todo = makeTodoListTodo(id: "todo-toggle", isPinned: false, isCompleted: false) let item = TodoListItem(from: todo)! - let adapter = TodoListStoreTestAdapter( - fetchTodoByIdUseCase: TodoListFetchTodoByIdUseCaseSpy(todos: [todo]) - ) + let fetchByIdSpy = TodoListFetchTodoByIdUseCaseSpy(todos: [todo]) + let adapter = TodoListStoreTestAdapter(fetchTodoByIdUseCase: fetchByIdSpy) await adapter.appendTodos([item]) await adapter.tapToggleCompleted(item) @@ -406,16 +428,16 @@ struct TodoListFeatureTests { adapter.todos.first?.isCompleted == true } - #expect(adapter.detailRevision == 0) + #expect(fetchByIdSpy.todoIds == ["todo-toggle"]) await adapter.selectTodo("todo-toggle") await adapter.tapToggleCompleted(adapter.todos[0]) await waitUntil { - adapter.detailRevision == 1 + fetchByIdSpy.todoIds.count == 3 } - #expect(adapter.detailRevision == 1) + #expect(fetchByIdSpy.todoIds == ["todo-toggle", "todo-toggle", "todo-toggle"]) } @Test("tapToggleCompleted와 tapTogglePinned는 조회한 Todo를 갱신해 목록에 반영한다") diff --git a/Application/Presentation/NotificationTab/Sources/PushNotificationListFeature.swift b/Application/Presentation/NotificationTab/Sources/PushNotificationListFeature.swift index 8ea49d8cf..6f11acd91 100644 --- a/Application/Presentation/NotificationTab/Sources/PushNotificationListFeature.swift +++ b/Application/Presentation/NotificationTab/Sources/PushNotificationListFeature.swift @@ -16,14 +16,14 @@ struct PushNotificationListFeature { @ObservableState struct State: Equatable { @Presents var alert: AlertState? - @Presents var sheet: SheetState? + // 고른 알림의 Todo 상세, 좁은 창은 시트로 띄우고 사이드바가 있는 창은 상세 판이나 오른쪽 칸에 표시 + @Presents var detail: TodoDetailFeature.State? var notifications: [PushNotificationItem] = [] var nextCursor: PushNotificationCursor? var query: PushNotificationQuery var selectedNotificationId: String? - var selectedTodoId: TodoIdItem? // 사이드바가 있는 창에서 목록 오른쪽 칸을 연 상태, 닫혀 있으면 고른 Todo를 상세 판으로 표시 - var isDetailPanePresented = false + var showsDetailInPane = false var loading = LoadingFeature.State() var undoNotificationId: String? @@ -44,15 +44,9 @@ struct PushNotificationListFeature { } } - @ObservableState - struct SheetState: Equatable, Identifiable { - let todoId: String - var id: String { todoId } - } - enum Action: BindableAction { case alert(PresentationAction) - case sheet(PresentationAction) + case detail(PresentationAction) case binding(BindingAction) case view(ViewAction) case store(StoreAction) @@ -72,12 +66,6 @@ struct PushNotificationListFeature { case toggleUnreadOnly case resetFilters case selectNotification(String?) - case syncSheetPresentation - case hideSheet - } - - enum Sheet: Equatable { - case tapCloseButton } enum StoreAction: Equatable { @@ -112,13 +100,11 @@ struct PushNotificationListFeature { switch action { case .alert: break - case .sheet(.dismiss), .sheet(.presented(.tapCloseButton)): - state.sheet = nil + case .detail(.dismiss): state.selectedNotificationId = nil - state.selectedTodoId = nil // 오른쪽 칸에서 연 알림을 좁은 창의 시트로 닫으면 다시 넓혀도 빈 오른쪽 칸을 열지 않음 - state.isDetailPanePresented = false - case .sheet: + state.showsDetailInPane = false + case .detail: break case .binding(\.query.timeFilter): state.nextCursor = nil @@ -137,21 +123,12 @@ struct PushNotificationListFeature { return .none } .ifLet(\.$alert, action: \.alert) - .ifLet(\.$sheet, action: \.sheet) { - PushNotificationListSheetFeature() + .ifLet(\.$detail, action: \.detail) { + TodoDetailFeature() } } } -private struct PushNotificationListSheetFeature: Reducer { - typealias State = PushNotificationListFeature.SheetState - typealias Action = PushNotificationListFeature.Action.Sheet - - var body: some ReducerOf { - EmptyReducer() - } -} - private extension PushNotificationListFeature { func reduce( _ action: Action.ViewAction, @@ -229,27 +206,19 @@ private extension PushNotificationListFeature { return refreshForQueryChangeEffect(query: state.query) case .selectNotification(let notificationId): state.selectedNotificationId = notificationId - guard let notificationId else { - state.selectedTodoId = nil - return .none - } - guard let index = state.notifications.firstIndex(where: { $0.id == notificationId }) else { - state.selectedTodoId = nil + guard let notificationId, + let index = state.notifications.firstIndex(where: { $0.id == notificationId }) else { + state.detail = nil return .none } let item = state.notifications[index] - state.selectedTodoId = TodoIdItem(id: item.todoId) + // 같은 Todo의 알림은 불러온 상세와 열어 둔 시트를 그대로 둠 + if state.detail?.todoId != item.todoId { + state.detail = TodoDetailFeature.State(todoId: item.todoId, showEditButton: false) + } guard !item.isRead else { return .none } state.notifications[index].isRead = true return toggleReadEffect(notificationId: item.id, todoId: item.todoId, rollbackRead: false) - case .syncSheetPresentation: - if let todoId = state.selectedTodoId?.id { - state.sheet = .init(todoId: todoId) - } else { - state.sheet = nil - } - case .hideSheet: - state.sheet = nil } return .none diff --git a/Application/Presentation/NotificationTab/Sources/PushNotificationListView.swift b/Application/Presentation/NotificationTab/Sources/PushNotificationListView.swift index e834b0d66..cd716feef 100644 --- a/Application/Presentation/NotificationTab/Sources/PushNotificationListView.swift +++ b/Application/Presentation/NotificationTab/Sources/PushNotificationListView.swift @@ -13,8 +13,9 @@ public struct PushNotificationListView: View { @Environment(\.usesDesktopLayout) private var usesDesktopLayout @State private var store: StoreOf private let isSelected: Bool + private let windowEvent: TodoEditorWindowEvent - public init(isSelected: Bool) { + public init(isSelected: Bool, windowEvent: TodoEditorWindowEvent) { @Dependency(\.fetchPushNotificationQueryUseCase) var fetchQueryUseCase self._store = State(initialValue: Store( initialState: PushNotificationListFeature.State( @@ -24,16 +25,14 @@ public struct PushNotificationListView: View { PushNotificationListFeature() }) self.isSelected = isSelected + self.windowEvent = windowEvent } public var body: some View { - // 사이드바가 있는 창에서 오른쪽 칸을 열었을 때만 목록 | 상세 두 칸으로 나눔 - let showsPane = usesDesktopLayout && store.isDetailPanePresented - NavigationStack { - PaneSplitView(splitsOnDesktop: showsPane) { + PaneSplitView { // 사이드바가 있는 창은 상세 판이나 오른쪽 칸에 연 알림을 목록에 선택 표시 - PushNotificationListContent(store: store, showsSelection: usesDesktopLayout) + PushNotificationListContent(store: store) .background(Color.background) .refreshable(isEnabled: PullToRefreshAvailability.isEnabled) { let task = store.send(.view(.refresh)) @@ -41,84 +40,58 @@ public struct PushNotificationListView: View { store.send(.view(.startObserving)) } .duoToolbarVisibility() - } detail: { - TodoDetailPane( - todoId: store.selectedTodoId?.id, - showEditButton: false, - onClose: usesDesktopLayout ? closeDetailPane : nil - ) + // 좁은 창은 시트로 띄우고, 사이드바가 있는 창은 상세 판이나 오른쪽 칸에 표시 + // 오른쪽 칸을 연 동안은 고른 알림이 없어도 칸에 안내 표시 + // 창 폭이 바뀌면 같은 상세 상태를 바뀐 자리에서 이어 그림 + .compositionDetail( + item: $store.scope(state: \.detail, action: \.detail), + narrow: .sheet, + inPane: store.showsDetailInPane, + emptyPane: true, + isActive: isSelected + ) { detailStore, onClose in + if let onClose { + TodoDetailView(store: detailStore, isPaneDetail: true, onClose: onClose) + // 칸 안에서 다른 Todo로 바꾸면 그 Todo를 조회 + .id(detailStore.todoId) + } else { + NavigationStack { + TodoDetailView(store: detailStore) + } + .environment(\.windowControlsInset, 0) + .environment(\.deviceType, .bar) + .background(Color.background) + } + } panel: { detailStore in + TodoDetailPanel( + store: detailStore, + location: Text("nav_push_notifications", bundle: PresentationResources.bundle), + onMoveToPane: { + store.send(.binding(.set(\.showsDetailInPane, true))) + } + ) + } } // 오른쪽 칸은 칸 제목 줄 정보 버튼 대신 창 오른쪽 세부 정보 사이드바에 속성 표시 - .detailSideBarTarget( - showsPane ? store.selectedTodoId.map { .todo(id: $0.id, isEditable: false) } : nil - ) - } - .prominentAlert(store, state: \.alert, action: \.alert) - .prominentSheet(item: sheetStore.activePresentation(when: isSelected && !usesDesktopLayout)) { store in - sheetContent(store) - } - .detailPanel(item: sheetStore.activePresentation(when: isSelected && usesDesktopLayout)) { sheetStore in - TodoDetailPanel( - todoId: sheetStore.todoId, - location: Text("nav_push_notifications", bundle: PresentationResources.bundle), - isEditable: false, - onMoveToPane: { - store.send(.binding(.set(\.isDetailPanePresented, true))) + .compositionRight(isActive: usesDesktopLayout && store.showsDetailInPane && store.detail != nil) { + if let todoId = store.detail?.todoId { + TodoDetailSideBarView(todoId: todoId, isEditable: false, windowEvent: windowEvent) + .id(todoId) } - ) + } } + .prominentAlert(store, state: \.alert, action: \.alert) .onChange(of: isSelected, initial: true) { _, isSelected in if isSelected { store.send(.view(.fetchNotifications)) } } - .onChange(of: store.selectedTodoId?.id, initial: true) { - if !showsPane { - store.send(.view(.syncSheetPresentation)) - } - } - // 오른쪽 칸을 열면 상세 판만 닫고, 오른쪽 칸을 닫으면 고른 Todo를 상세 판이나 시트로 표시 - .onChange(of: showsPane) { _, showsPane in - store.send(.view(showsPane ? .hideSheet : .syncSheetPresentation)) - } .overlay { if store.isLoading { LoadingView() } } } - - // 선택을 먼저 비워 오른쪽 칸을 닫을 때 같은 Todo를 상세 판으로 다시 열지 않음 - private func closeDetailPane() { - store.send(.view(.selectNotification(nil))) - store.send(.binding(.set(\.isDetailPanePresented, false))) - } - - @ViewBuilder - private func sheetContent( - _ sheetStore: Store - ) -> some View { - NavigationStack { - TodoDetailView(store: Store( - initialState: TodoDetailFeature.State( - todoId: sheetStore.todoId, - showEditButton: false - ) - ) { - TodoDetailFeature() - }) - .id(sheetStore.todoId) - } - .environment(\.windowControlsInset, 0) - .environment(\.deviceType, .bar) - .background(Color.background) - } - - private var sheetStore: Binding< - Store?> { - $store.scope(state: \.sheet, action: \.sheet) - } } private struct PushNotificationListContent: View { @@ -127,8 +100,6 @@ private struct PushNotificationListContent: View { @Environment(\.windowControlsInset) private var windowControlsInset @ScaledMetric(relativeTo: .body) private var iconSize = 32 let store: StoreOf - // 고른 알림을 상세 판이나 옆 칸에 표시하는 동안 목록 행에 선택 표시 - let showsSelection: Bool @ViewBuilder var body: some View { @@ -168,7 +139,8 @@ private struct PushNotificationListContent: View { LazyVStack(spacing: 0) { ForEach(items) { item in let category = TodoCategoryItem(from: item.todoCategory) - let isSelected = showsSelection && item.id == store.selectedNotificationId + // 사이드바가 있는 창은 고른 알림을 상세 판이나 옆 칸에 표시하는 동안 목록 행에 선택 표시 + let isSelected = usesDesktopLayout && item.id == store.selectedNotificationId HStack(alignment: .top, spacing: 10) { // 테두리 있는 회색 사각형에 카테고리 색 기호 @@ -234,7 +206,7 @@ private struct PushNotificationListContent: View { // 우클릭과 길게 누른 메뉴는 상세 판과 오른쪽 칸으로 여는 항목을 맨 위에 표시 if usesDesktopLayout { Button { - store.send(.binding(.set(\.isDetailPanePresented, false))) + store.send(.binding(.set(\.showsDetailInPane, false))) store.send(.view(.selectNotification(item.id))) } label: { Label { @@ -244,7 +216,7 @@ private struct PushNotificationListContent: View { } } Button { - store.send(.binding(.set(\.isDetailPanePresented, true))) + store.send(.binding(.set(\.showsDetailInPane, true))) store.send(.view(.selectNotification(item.id))) } label: { Label { diff --git a/Application/Presentation/NotificationTab/Tests/PushNotificationListFeatureTests.swift b/Application/Presentation/NotificationTab/Tests/PushNotificationListFeatureTests.swift index 4a53843b8..9dbed4916 100644 --- a/Application/Presentation/NotificationTab/Tests/PushNotificationListFeatureTests.swift +++ b/Application/Presentation/NotificationTab/Tests/PushNotificationListFeatureTests.swift @@ -309,8 +309,8 @@ struct PushNotificationListFeatureTests { #expect(adapter.notifications.first?.isRead == true) } - @Test("syncSheetPresentation은 선택한 Todo를 시트로 표시한다") - func syncSheetPresentation은_선택한_Todo를_시트로_표시한다() async throws { + @Test("고른 알림의 Todo 상세를 닫으면 고른 알림도 비운다") + func 고른_알림의_Todo_상세를_닫으면_고른_알림도_비운다() async throws { let fetchSpy = PushNotificationListFetchUseCaseSpy(pages: [ PushNotificationPage( items: [ @@ -324,15 +324,12 @@ struct PushNotificationListFeatureTests { await adapter.fetchNotifications() await adapter.selectNotification("notification-1") - await adapter.syncSheetPresentation() + #expect(adapter.detailTodoId == "todo-1") - #expect(adapter.sheetTodoId == "todo-1") + await adapter.dismissDetail() - await adapter.dismissSheet() - - #expect(adapter.sheetTodoId == nil) + #expect(adapter.detailTodoId == nil) #expect(adapter.selectedNotificationId == nil) - #expect(adapter.selectedTodoId == nil) } @Test("오른쪽 칸에서 연 알림을 시트로 옮긴 뒤 닫으면 오른쪽 칸 상태도 닫는다") @@ -348,38 +345,13 @@ struct PushNotificationListFeatureTests { let adapter = PushNotificationListStoreTestAdapter(fetchUseCase: fetchSpy) await adapter.fetchNotifications() - await adapter.setDetailPanePresented(true) - await adapter.selectNotification("notification-1") - // 창이 좁아져 오른쪽 칸 대신 시트로 표시 - await adapter.syncSheetPresentation() - - await adapter.dismissSheet() - - #expect(adapter.selectedTodoId == nil) - #expect(!adapter.isDetailPanePresented) - } - - @Test("hideSheet은 시트만 닫고 선택한 알림과 Todo를 유지한다") - func hideSheet은_시트만_닫고_선택한_알림과_Todo를_유지한다() async throws { - let fetchSpy = PushNotificationListFetchUseCaseSpy(pages: [ - PushNotificationPage( - items: [ - makePushNotification(id: "notification-1", number: 1, isRead: true) - ], - nextCursor: nil - ) - ]) - let adapter = PushNotificationListStoreTestAdapter(fetchUseCase: fetchSpy) - - await adapter.fetchNotifications() + await adapter.setShowsDetailInPane(true) await adapter.selectNotification("notification-1") - await adapter.syncSheetPresentation() - - await adapter.hideSheet() + // 창이 좁아져 오른쪽 칸 대신 같은 상세 상태를 시트로 표시한 뒤 닫음 + await adapter.dismissDetail() - #expect(adapter.sheetTodoId == nil) - #expect(adapter.selectedNotificationId == "notification-1") - #expect(adapter.selectedTodoId?.id == "todo-1") + #expect(adapter.detailTodoId == nil) + #expect(!adapter.showsDetailInPane) } @Test("delete와 undoDelete는 숨김 상태와 최종 제거 상태를 제어한다") diff --git a/Application/Presentation/NotificationTab/Tests/PushNotificationListTestAssertions.swift b/Application/Presentation/NotificationTab/Tests/PushNotificationListTestAssertions.swift index 9ce799772..41f244611 100644 --- a/Application/Presentation/NotificationTab/Tests/PushNotificationListTestAssertions.swift +++ b/Application/Presentation/NotificationTab/Tests/PushNotificationListTestAssertions.swift @@ -139,10 +139,10 @@ func verifySelectNotification( await adapter.selectNotification("notification-1") let selectedNotificationId = adapter.selectedNotificationId - let selectedTodoId = adapter.selectedTodoId + let detailTodoId = adapter.detailTodoId let notifications = adapter.notifications #expect(selectedNotificationId == "notification-1") - #expect(selectedTodoId?.id == "todo-1") + #expect(detailTodoId == "todo-1") #expect(notifications.first?.isRead == true) await waitUntilMainActor { @@ -152,9 +152,9 @@ func verifySelectNotification( await adapter.selectNotification(nil) let resetSelectedNotificationId = adapter.selectedNotificationId - let resetSelectedTodoId = adapter.selectedTodoId + let resetDetailTodoId = adapter.detailTodoId #expect(resetSelectedNotificationId == nil) - #expect(resetSelectedTodoId == nil) + #expect(resetDetailTodoId == nil) } @MainActor diff --git a/Application/Presentation/NotificationTab/Tests/PushNotificationListTestSupport.swift b/Application/Presentation/NotificationTab/Tests/PushNotificationListTestSupport.swift index 7e1801c44..a62f55dec 100644 --- a/Application/Presentation/NotificationTab/Tests/PushNotificationListTestSupport.swift +++ b/Application/Presentation/NotificationTab/Tests/PushNotificationListTestSupport.swift @@ -19,7 +19,7 @@ protocol PushNotificationListStateDriving { var query: PushNotificationQuery { get } var nextCursor: PushNotificationCursor? { get } var selectedNotificationId: String? { get } - var selectedTodoId: TodoIdItem? { get } + var detailTodoId: String? { get } var appliedFilterCount: Int { get } func startObserving() async @@ -45,10 +45,9 @@ struct PushNotificationListStoreTestAdapter: PushNotificationListStateDriving { var query: PushNotificationQuery { store.state.query } var nextCursor: PushNotificationCursor? { store.state.nextCursor } var selectedNotificationId: String? { store.state.selectedNotificationId } - var selectedTodoId: TodoIdItem? { store.state.selectedTodoId } + var detailTodoId: String? { store.state.detail?.todoId } var appliedFilterCount: Int { store.state.appliedFilterCount } - var sheetTodoId: String? { store.state.sheet?.todoId } - var isDetailPanePresented: Bool { store.state.isDetailPanePresented } + var showsDetailInPane: Bool { store.state.showsDetailInPane } init( fetchUseCase: FetchPushNotificationsUseCase = PushNotificationListFetchUseCaseSpy(), @@ -148,20 +147,12 @@ struct PushNotificationListStoreTestAdapter: PushNotificationListStateDriving { await store.send(.view(.finishDeleteToast(notificationId))) } - func syncSheetPresentation() async { - await store.send(.view(.syncSheetPresentation)) + func dismissDetail() async { + await store.send(.detail(.dismiss)) } - func dismissSheet() async { - await store.send(.sheet(.dismiss)) - } - - func setDetailPanePresented(_ isPresented: Bool) async { - await store.send(.binding(.set(\.isDetailPanePresented, isPresented))) - } - - func hideSheet() async { - await store.send(.view(.hideSheet)) + func setShowsDetailInPane(_ showsDetailInPane: Bool) async { + await store.send(.binding(.set(\.showsDetailInPane, showsDetailInPane))) } func finishEffects() async { diff --git a/Application/Presentation/PresentationShared/Sources/Common/Component/CompositionContainer.swift b/Application/Presentation/PresentationShared/Sources/Common/Component/CompositionContainer.swift new file mode 100644 index 000000000..d471fc8e1 --- /dev/null +++ b/Application/Presentation/PresentationShared/Sources/Common/Component/CompositionContainer.swift @@ -0,0 +1,442 @@ +// +// CompositionContainer.swift +// PresentationShared +// +// Created by opfic on 11/27/26. +// + +import SwiftUI + +// 좁은 창에서 띄우는 컨테이너 +public enum CompositionNarrow { + case sheet + case cover + case push +} + +public extension View { + // 읽는 화면 + // 좁은 창은 내비게이션에 쌓거나 시트로 띄우고, 사이드바가 있는 창은 사이드바까지 덮는 상세 판으로 띄움 + // inPane이 참이면 사이드바가 있는 창에서 상세 판 대신 이 화면을 감싼 PaneSplitView의 상세 칸에 올림 + // emptyPane이 참이면 고른 항목이 없어도 상세 칸에 안내를 올림 + // isActive가 거짓이면 창 위에 덮는 시트와 상세 판은 띄우지 않고, 내비게이션에 쌓은 화면과 상세 칸은 그대로 둠 + // content는 상세 칸에 그릴 때만 닫는 동작을 받음 + func compositionDetail( + item: Binding, + narrow: CompositionNarrow = .push, + inPane: Bool = false, + emptyPane: Bool = false, + isActive: Bool = true, + @ViewBuilder content: @escaping (Item, (() -> Void)?) -> Content, + @ViewBuilder panel: @escaping (Item) -> Panel + ) -> some View { + modifier(CompositionDetailModifier( + item: item, + narrow: narrow, + inPane: inPane, + emptyPane: emptyPane, + isActive: isActive, + detail: content, + panel: panel + )) + } + + // 저장이나 닫기 버튼으로만 닫는 작성 화면 + // 좁은 창은 전체 화면이나 시트로 띄우고, 사이드바가 있는 창은 이 화면을 감싼 PaneSplitView의 상세 칸에 올림 + // 상세 칸에는 읽는 화면보다 작성 화면을 먼저 올리고, 작성 화면끼리는 바깥에 붙인 수정자의 화면을 올림 + // inPane이 거짓이면 사이드바가 있는 창에서도 시트로 띄움 + // isActive가 거짓이면 창 위에 띄우지 않고 상세 칸은 그대로 둠 + // content는 상세 칸에 그릴 때만 닫는 동작을 받음 + func compositionEditor( + item: Binding, + narrow: CompositionNarrow = .cover, + inPane: Bool = true, + isActive: Bool = true, + @ViewBuilder content: @escaping (Item, (() -> Void)?) -> Content + ) -> some View { + modifier(CompositionEditorModifier( + item: item, + narrow: narrow, + inPane: inPane, + isActive: isActive, + editor: content + )) + } + + // 바꾸면 바로 저장하는 시트 + // 좁은 창은 시트로 띄우고, 사이드바가 있는 창은 SplitShell 오른쪽 세부 정보 사이드바에 표시 + // reveal이 바뀌면 사이드바가 있는 창에서 닫힌 세부 정보 사이드바를 엶 + func compositionSheet( + item: Binding, + reveal: Int = 0, + @ViewBuilder sheet: @escaping (Item) -> Sheet, + @ViewBuilder right: @escaping (Item) -> Right + ) -> some View { + modifier(CompositionSheetModifier(item: item, reveal: reveal, sheet: sheet, right: right)) + } + + // 좁은 창은 시트로 띄우거나 내비게이션에 쌓고, 사이드바가 있는 창은 이 화면 대신 내비게이션 루트에 그림 + // isActive가 거짓이면 좁은 창에서 띄우지 않음 + // closesRight가 참이면 사이드바가 있는 창에서 닫거나 탭 화면을 벗어날 때 세부 정보 사이드바도 닫음 + // 창 폭이 바뀌어 시트와 루트를 오갈 때는 상태가 남아 닫지 않음 + func compositionCenter( + item: Binding, + narrow: CompositionNarrow, + isActive: Bool = true, + closesRight: Bool = false, + @ViewBuilder content: @escaping (Item) -> Content + ) -> some View { + modifier(CompositionCenterModifier( + item: item, + narrow: narrow, + isActive: isActive, + closesRight: closesRight, + center: content + )) + } + + // 고르는 화면 + // 좁은 창은 시트로 띄우고, 칸으로 나눈 화면은 compositionPickerAnchor를 붙인 버튼 옆 팝오버로 띄움 + // maxHeight가 없으면 팝오버를 내용 높이에 맞춤 + func compositionPicker( + isPresented: Binding, + isActive: Bool = true, + arrowEdge: Edge? = nil, + maxHeight: CGFloat? = nil, + @ViewBuilder content: @escaping () -> Content + ) -> some View { + modifier(CompositionPickerModifier( + isPresented: isPresented, + isActive: isActive, + arrowEdge: arrowEdge, + maxHeight: maxHeight, + picker: content + )) + } + + // 바깥의 compositionPicker가 칸으로 나눈 화면에서 띄우는 팝오버를 붙일 버튼 + func compositionPickerAnchor() -> some View { + modifier(CompositionPickerAnchorModifier()) + } +} + +// 창 폭이 바뀐 뒤 시스템이 표시할 때 받아 둔 바인딩으로 늦게 닫아도 지금 창 폭으로 거르도록 참조로 보관하는 값 +private final class LiveLayout { + private(set) var usesDesktopLayout = false + private(set) var usesPaneLayout = false + private(set) var inPane = false + + // 그릴 때마다 지금 값으로 바꾸고 같은 참조를 돌려줌 + func update(usesDesktopLayout: Bool = false, usesPaneLayout: Bool = false, inPane: Bool = false) -> LiveLayout { + self.usesDesktopLayout = usesDesktopLayout + self.usesPaneLayout = usesPaneLayout + self.inPane = inPane + return self + } +} + +private struct CompositionDetailModifier: ViewModifier { + @Environment(\.usesDesktopLayout) private var usesDesktopLayout + @State private var layout = LiveLayout() + @State private var id = UUID() + let item: Binding + let narrow: CompositionNarrow + let inPane: Bool + let emptyPane: Bool + let isActive: Bool + let detail: (Item, (() -> Void)?) -> Detail + let panel: (Item) -> Panel + + func body(content: Content) -> some View { + // 창 폭이 바뀌면 같은 상태를 짝이 되는 컨테이너가 다시 그리고, 빠지는 쪽의 늦은 닫힘은 상태를 지우지 않음 + let layout = layout.update(usesDesktopLayout: usesDesktopLayout, inPane: inPane) + let narrowItem = item.hiddenInPane { layout.usesDesktopLayout } + let panelItem = item.activePresentation(when: isActive) + .hiddenInPane { !layout.usesDesktopLayout || layout.inPane } + + narrowContent(content, item: narrowItem) + .detailPanel(item: panelItem, content: panel) + // 가려진 탭에서도 상세 칸을 그대로 두도록 isActive와 상관없이 올림 + .transformPreference(PaneDetailContentPreferenceKey.self) { value in + guard inPane, value == nil, item.wrappedValue != nil || emptyPane else { return } + value = PaneDetailContent(id: id, isEditor: false, key: item.wrappedValue.map { AnyHashable($0.id) }) { + AnyView(paneContent) + } + } + } + + @ViewBuilder + private func narrowContent(_ content: Content, item: Binding) -> some View { + switch narrow { + case .push: + content + .navigationDestination(item: item, interactivePop: true) { detail($0, nil) } + case .sheet: + content + .prominentSheet(item: item.activePresentation(when: isActive)) { detail($0, nil) } + case .cover: + content + .fullScreenCover(item: item.activePresentation(when: isActive)) { detail($0, nil) } + } + } + + // 상세 칸이 그릴 때마다 지금 고른 항목을 읽음 + @ViewBuilder + private var paneContent: some View { + if let value = item.wrappedValue { + detail(value, { item.wrappedValue = nil }) + .environment(\.showsPaneTitleBar, true) + } else { + PanePlaceholder() + } + } +} + +private struct CompositionEditorModifier: ViewModifier { + @Environment(\.usesDesktopLayout) private var usesDesktopLayout + @State private var layout = LiveLayout() + @State private var id = UUID() + let item: Binding + let narrow: CompositionNarrow + let inPane: Bool + let isActive: Bool + let editor: (Item, (() -> Void)?) -> Editor + + func body(content: Content) -> some View { + // 넓은 창으로 바뀌어 칸에 옮겨 그린 뒤 늦게 닫히는 화면은 작성 중인 초안을 지우지 않음 + let layout = layout.update(usesDesktopLayout: usesDesktopLayout) + let activeItem = item.activePresentation(when: isActive) + let narrowItem = activeItem.hiddenInPane { layout.usesDesktopLayout } + + presentedContent(content, activeItem: activeItem, narrowItem: narrowItem, layout: layout) + // 가려진 탭에서도 작성 중인 화면을 상세 칸에 그대로 두도록 isActive와 상관없이 올림 + .transformPreference(PaneDetailContentPreferenceKey.self) { value in + guard inPane, item.wrappedValue != nil else { return } + value = PaneDetailContent(id: id, isEditor: true, key: item.wrappedValue.map { AnyHashable($0.id) }) { + AnyView(paneContent) + } + } + } + + @ViewBuilder + private func presentedContent( + _ content: Content, + activeItem: Binding, + narrowItem: Binding, + layout: LiveLayout + ) -> some View { + switch (narrow, inPane) { + case (.cover, true): + content + .fullScreenCover(item: narrowItem) { editor($0, nil) } + case (.sheet, true): + content + .prominentSheet(item: narrowItem) { editor($0, nil) } + case (.cover, false): + content + .fullScreenCover(item: narrowItem) { editor($0, nil) } + .prominentSheet(item: activeItem.hiddenInPane { !layout.usesDesktopLayout }) { editor($0, nil) } + case (.sheet, false): + content + .prominentSheet(item: activeItem) { editor($0, nil) } + case (.push, _): + content + .navigationDestination(item: narrowItem, interactivePop: true) { editor($0, nil) } + } + } + + // 상세 칸이 그릴 때마다 지금 작성 중인 항목을 읽음 + @ViewBuilder + private var paneContent: some View { + if let value = item.wrappedValue { + editor(value, { item.wrappedValue = nil }) + } + } +} + +private struct CompositionCenterModifier: ViewModifier { + @Environment(\.isTabContentActive) private var isTabContentActive + @Environment(\.usesDesktopLayout) private var usesDesktopLayout + @Environment(\.setDetailSideBarPresented) private var setDetailSideBarPresented + @State private var layout = LiveLayout() + let item: Binding + let narrow: CompositionNarrow + let isActive: Bool + let closesRight: Bool + let center: (Item) -> Center + + func body(content: Content) -> some View { + // 창 폭이 바뀌어도 좁은 창의 표시를 같은 화면에 두어, 넓어진 뒤 늦게 닫히는 표시가 상태를 지우지 않음 + let layout = layout.update(usesDesktopLayout: usesDesktopLayout) + let narrowItem = item.activePresentation(when: isActive).hiddenInPane { layout.usesDesktopLayout } + let isClosed = item.wrappedValue == nil + let shown = Group { + if usesDesktopLayout, let value = item.wrappedValue { + center(value) + } else { + content + } + } + + presentedContent(shown, item: narrowItem) + // 루트에 그린 화면을 닫거나 탭 화면을 벗어나면 그 화면이 보여 주던 세부 정보 사이드바도 닫음 + .onChange(of: isClosed) { _, isClosed in + if closesRight && usesDesktopLayout && isClosed { + setDetailSideBarPresented?(false) + } + } + .onChange(of: isTabContentActive) { _, isActive in + if closesRight && usesDesktopLayout && !isActive && !isClosed { + setDetailSideBarPresented?(false) + } + } + } + + @ViewBuilder + private func presentedContent(_ shown: some View, item: Binding) -> some View { + switch narrow { + case .sheet: + shown + .prominentSheet(item: item, content: center) + case .cover: + shown + .fullScreenCover(item: item, content: center) + case .push: + shown + .navigationDestination(item: item, interactivePop: true, destination: center) + } + } +} + +private struct CompositionSheetModifier: ViewModifier { + @Environment(\.isTabContentActive) private var isTabContentActive + @Environment(\.usesDesktopLayout) private var usesDesktopLayout + @Environment(\.setDetailSideBarPresented) private var setDetailSideBarPresented + @State private var layout = LiveLayout() + let item: Binding + let reveal: Int + let sheet: (Item) -> Sheet + let right: (Item) -> Right + + func body(content: Content) -> some View { + // 넓은 창으로 바뀌어 세부 정보 사이드바로 옮긴 뒤 늦게 닫히는 시트는 고른 항목을 지우지 않음 + let layout = layout.update(usesDesktopLayout: usesDesktopLayout) + + content + .prominentSheet( + item: item.activePresentation(when: isTabContentActive) + .hiddenInPane { layout.usesDesktopLayout }, + content: sheet + ) + // 고른 항목이 없으면 세부 정보 사이드바에 안내 표시 + .modifier(CompositionRightModifier( + isActive: usesDesktopLayout, + reveal: 0, + key: item.wrappedValue.map { AnyHashable($0.id) } + ) { + Group { + if let value = item.wrappedValue { + right(value) + } else { + DetailSideBarPlaceholder() + } + } + }) + .onChange(of: reveal) { + if usesDesktopLayout { + setDetailSideBarPresented?(true) + } + } + } +} + +// compositionPicker가 compositionPickerAnchor에 넘기는 팝오버 내용 +private struct CompositionPickerContent { + let isPresented: Binding + let arrowEdge: Edge? + let maxHeight: CGFloat? + let content: () -> AnyView +} + +private extension EnvironmentValues { + var compositionPicker: CompositionPickerContent? { + get { self[CompositionPickerKey.self] } + set { self[CompositionPickerKey.self] = newValue } + } + + private struct CompositionPickerKey: EnvironmentKey { + static var defaultValue: CompositionPickerContent? { nil } + } +} + +private struct CompositionPickerModifier: ViewModifier { + @Environment(\.usesPaneLayout) private var usesPaneLayout + @State private var layout = LiveLayout() + let isPresented: Binding + let isActive: Bool + let arrowEdge: Edge? + let maxHeight: CGFloat? + let picker: () -> Picker + + func body(content: Content) -> some View { + // 창 폭이 바뀌어 팝오버와 시트를 오가면 같은 상태를 바뀐 쪽에 다시 그리고, 빠지는 쪽의 늦은 닫힘은 거름 + let layout = layout.update(usesPaneLayout: usesPaneLayout) + let sheetBinding = Binding( + get: { !layout.usesPaneLayout && isPresented.wrappedValue }, + set: { value in + if !layout.usesPaneLayout { + isPresented.wrappedValue = value + } + } + ) + let popoverBinding = Binding( + get: { layout.usesPaneLayout && isPresented.wrappedValue }, + set: { value in + if layout.usesPaneLayout { + isPresented.wrappedValue = value + } + } + ) + + content + .prominentSheet(isPresented: sheetBinding.activePresentation(when: isActive)) { + picker() + } + .environment( + \.compositionPicker, + CompositionPickerContent( + isPresented: popoverBinding.activePresentation(when: isActive), + arrowEdge: arrowEdge, + maxHeight: maxHeight + ) { + AnyView(picker()) + } + ) + } +} + +private struct CompositionPickerAnchorModifier: ViewModifier { + @Environment(\.compositionPicker) private var picker + + func body(content: Content) -> some View { + content + .popover(isPresented: picker?.isPresented ?? .constant(false), arrowEdge: picker?.arrowEdge) { + if let picker { + Group { + // 화면이 낮거나 Duo 접는 선에 걸리면 팝오버 높이를 줄이고 목록을 스크롤 + if let maxHeight = picker.maxHeight { + picker.content() + .frame(width: 320 * AdaptiveSize.boardScale) + .frame(minHeight: 0, idealHeight: maxHeight, maxHeight: maxHeight) + } else { + picker.content() + .frame(width: 320 * AdaptiveSize.boardScale) + .fixedSize(horizontal: false, vertical: true) + } + } + .presentationBackground(Color.secondaryBackground) + .presentationCompactAdaptation(.popover) + } + } + } +} diff --git a/Application/Presentation/PresentationShared/Sources/Common/Component/DetailPanel.swift b/Application/Presentation/PresentationShared/Sources/Common/Component/DetailPanel.swift index bb5f5f276..4d8043944 100644 --- a/Application/Presentation/PresentationShared/Sources/Common/Component/DetailPanel.swift +++ b/Application/Presentation/PresentationShared/Sources/Common/Component/DetailPanel.swift @@ -56,7 +56,6 @@ private struct DetailPanelFrame: View { // 판 안 제목 줄은 창 사이드바를 펴거나 세부 정보 사이드바를 여는 버튼 없이 표시 .environment(\.expandSideBar, nil) .environment(\.showDetailSideBar, nil) - .environment(\.selectDetailSideBarTarget, nil) .environment(\.windowControlsInset, 0) .environment(\.showsPaneTitleBar, false) .frame(maxWidth: .infinity, maxHeight: .infinity) diff --git a/Application/Presentation/PresentationShared/Sources/Common/Component/DetailSideBar.swift b/Application/Presentation/PresentationShared/Sources/Common/Component/DetailSideBar.swift index 3d1eb3ba6..f525d22d3 100644 --- a/Application/Presentation/PresentationShared/Sources/Common/Component/DetailSideBar.swift +++ b/Application/Presentation/PresentationShared/Sources/Common/Component/DetailSideBar.swift @@ -7,15 +7,6 @@ import SwiftUI -// 세부 정보 사이드바에 속성을 표시할 대상 -public enum DetailSideBarTarget: Hashable { - // 고칠 수 없는 활동 기록 Todo는 읽기 전용 - // 다른 곳에서 바꾼 Todo를 다시 조회하도록 목록이 올리는 revision - case todo(id: String, isEditable: Bool, revision: Int = 0) - // 칸 화면이 사이드바 내용을 직접 그리는 대상 - case hosted -} - // 사이드바가 있는 창 오른쪽에 두는 세부 정보 사이드바 public struct DetailSideBar: View { private let onClose: () -> Void @@ -57,34 +48,6 @@ public struct DetailSideBar: View { } } -public extension DetailSideBar where Content == DetailSideBarTargetContent { - init( - target: DetailSideBarTarget?, - windowEvent: TodoEditorWindowEvent?, - onClose: @escaping () -> Void - ) { - self.init(onClose: onClose) { - DetailSideBarTargetContent(target: target, windowEvent: windowEvent) - } - } -} - -// 창이 그리는 사이드바의 대상별 내용 -public struct DetailSideBarTargetContent: View { - let target: DetailSideBarTarget? - let windowEvent: TodoEditorWindowEvent? - - public var body: some View { - switch target { - case .todo(let id, let isEditable, _): - TodoDetailSideBarView(todoId: id, isEditable: isEditable, windowEvent: windowEvent) - .id(target) - case .hosted, nil: - DetailSideBarPlaceholder() - } - } -} - // 고른 대상이 없을 때의 안내 public struct DetailSideBarPlaceholder: View { public init() { } @@ -104,66 +67,72 @@ public struct DetailSideBarPlaceholder: View { } public extension View { - // 지금 고른 대상을 세부 정보 사이드바에 표시 - func detailSideBarTarget(_ target: DetailSideBarTarget?) -> some View { - modifier(DetailSideBarTargetModifier(target: target)) - } - - // 창 오른쪽 끝 칸 화면이 세부 정보 사이드바 내용을 직접 그림, 사이드바가 있는 창에서만 표시 - func detailSideBar( + // 이 화면의 세부 정보 사이드바 내용, 사이드바가 있는 창에서 SplitShell 오른쪽에 표시 + // 화면은 내용만 올리고 사이드바는 CompositionView가 그림 + // reveal이 바뀌면 사이드바가 있는 창에서 닫힌 세부 정보 사이드바를 엶 + func compositionRight( isActive: Bool = true, - @ViewBuilder content: () -> Content + reveal: Int = 0, + @ViewBuilder content: @escaping () -> Content ) -> some View { - modifier(HostedDetailSideBarModifier(isActive: isActive, sideBarContent: content())) + modifier(CompositionRightModifier(isActive: isActive, reveal: reveal, key: nil, sideBarContent: content)) } } -private struct DetailSideBarTargetModifier: ViewModifier { - @Environment(\.selectDetailSideBarTarget) private var selectDetailSideBarTarget - @Environment(\.removeDetailSideBarTarget) private var removeDetailSideBarTarget - @State private var owner = UUID() - let target: DetailSideBarTarget? +// 화면이 올린 세부 정보 사이드바 내용 +// 같은 화면이 같은 항목을 올린 동안은 같은 값으로 보고, 내용이 읽는 상태가 바뀌면 이 View만 다시 그림 +public struct DetailSideBarContent: View, Equatable { + let id: UUID + // 내용이 바인딩으로 읽는 항목의 식별자 + // 그리는 중의 바인딩은 만든 때의 값을 돌려주므로 항목이 바뀌면 새 내용으로 보고 다시 전달 + let key: AnyHashable? + let content: () -> AnyView - func body(content: Content) -> some View { - content - .onAppear { selectDetailSideBarTarget?(target, owner) } - .onChange(of: target) { _, target in - selectDetailSideBarTarget?(target, owner) - } - // 화면을 벗어나면 고른 대상 해제 - .onDisappear { removeDetailSideBarTarget?(owner) } + public var body: some View { + content() + } + + public static func == (lhs: Self, rhs: Self) -> Bool { + lhs.id == rhs.id && lhs.key == rhs.key + } +} + +// 탭 화면이 올린 세부 정보 사이드바 내용, 나중에 나타난 화면의 내용을 표시 +public struct DetailSideBarContentPreferenceKey: PreferenceKey { + public static var defaultValue: DetailSideBarContent? { nil } + + public static func reduce(value: inout DetailSideBarContent?, nextValue: () -> DetailSideBarContent?) { + value = nextValue() ?? value } } -private struct HostedDetailSideBarModifier: ViewModifier { - @Environment(\.selectDetailSideBarTarget) private var selectDetailSideBarTarget - @Environment(\.removeDetailSideBarTarget) private var removeDetailSideBarTarget - @Environment(\.isDetailSideBarPresented) private var isDetailSideBarPresented +struct CompositionRightModifier: ViewModifier { + @Environment(\.usesDesktopLayout) private var usesDesktopLayout @Environment(\.setDetailSideBarPresented) private var setDetailSideBarPresented - @State private var owner = UUID() + @State private var id = UUID() + // 화면을 벗어나 가려진 동안은 내용을 올리지 않음 + @State private var isAppeared = false let isActive: Bool - let sideBarContent: SideBarContent + let reveal: Int + // 내용이 바인딩으로 읽는 항목의 식별자 + let key: AnyHashable? + let sideBarContent: () -> SideBarContent func body(content: Content) -> some View { - HStack(spacing: 0) { - content - if isActive && isDetailSideBarPresented && selectDetailSideBarTarget != nil { - DetailSideBar { - setDetailSideBarPresented?(false) - } content: { - sideBarContent + // 상세 판과 시트는 따로 덮는 화면이라 그 안에서 올린 내용은 창까지 오지 않음 + let isShown = isActive && isAppeared + + content + .transformPreference(DetailSideBarContentPreferenceKey.self) { value in + guard isShown, value == nil else { return } + value = DetailSideBarContent(id: id, key: key) { AnyView(sideBarContent()) } + } + .onAppear { isAppeared = true } + .onDisappear { isAppeared = false } + .onChange(of: reveal) { + if usesDesktopLayout { + setDetailSideBarPresented?(true) } - // 왼쪽 사이드바를 펴는 버튼은 창 오른쪽 사이드바 제목 줄에 두지 않음 - .environment(\.expandSideBar, nil) } - } - // 창이 그리는 사이드바 대신 이 화면의 사이드바 표시 - .onAppear { - if isActive { selectDetailSideBarTarget?(.hosted, owner) } - } - .onChange(of: isActive) { _, isActive in - selectDetailSideBarTarget?(isActive ? .hosted : nil, owner) - } - .onDisappear { removeDetailSideBarTarget?(owner) } } } diff --git a/Application/Presentation/PresentationShared/Sources/Common/Component/PanePlaceholder.swift b/Application/Presentation/PresentationShared/Sources/Common/Component/PanePlaceholder.swift new file mode 100644 index 000000000..11be70d28 --- /dev/null +++ b/Application/Presentation/PresentationShared/Sources/Common/Component/PanePlaceholder.swift @@ -0,0 +1,30 @@ +// +// PanePlaceholder.swift +// PresentationShared +// +// Created by opfic on 11/13/26. +// + +import SwiftUI + +// 상세 칸에서 고른 항목이 없을 때 표시하는 안내 +public struct PanePlaceholder: View { + public init() {} + + public var body: some View { + VStack(spacing: 12) { + Image(systemName: "doc.text") + .font(.adaptive(.largeTitle)) + .foregroundStyle(Color.tertiaryLabel) + Text("pane_select_detail", bundle: PresentationResources.bundle) + .font(.adaptive(.callout)) + .foregroundStyle(Color.secondaryLabel) + } + .frame(maxWidth: .infinity, maxHeight: .infinity) + // 목록 칸 제목 줄과 구분선 높이 맞춤 + .safeAreaInset(edge: .top, spacing: 0) { + PaneTitleBar(Text(verbatim: "")) + } + .background(Color.background) + } +} diff --git a/Application/Presentation/PresentationShared/Sources/Common/Component/PaneSplitView.swift b/Application/Presentation/PresentationShared/Sources/Common/Component/PaneSplitView.swift index 4372d7271..52a4ecb6a 100644 --- a/Application/Presentation/PresentationShared/Sources/Common/Component/PaneSplitView.swift +++ b/Application/Presentation/PresentationShared/Sources/Common/Component/PaneSplitView.swift @@ -8,40 +8,38 @@ import SwiftUI // 사이드바가 있는 창에서 목록 칸 오른쪽에 상세 칸을 나란히 두는 화면 -public struct PaneSplitView: View { +// 상세 칸 내용은 목록 칸 안의 compositionDetail, compositionEditor가 올리고, 올린 내용이 있을 때만 두 칸으로 나눔 +public struct PaneSplitView: View { @Environment(\.usesDesktopLayout) private var usesDesktopLayout @State private var width = CGFloat.infinity // 경계선을 끌어 정한 목록 칸 폭, 없으면 기본 폭 @State private var primaryWidth: CGFloat? - // 상세 칸이 편집 화면처럼 화면을 덮는 표시를 띄운 동안 - @State private var isDetailPresenting = false // 상세 칸에 작성 화면을 그린 동안 @State private var isDetailEditing = false - // 사이드바가 있는 창은 따로 정한 화면만 두 칸으로 나눔 - private let splitsOnDesktop: Bool + // 목록 칸 안의 수정자가 올린 상세 칸 내용 + @State private var detail: PaneDetailContent? private let primary: Primary - // 상세 칸을 그릴 때만 만들어 칸이 없는 화면에서 상세 내용을 만들지 않음 - private let detail: () -> Detail - public init( - splitsOnDesktop: Bool = true, - @ViewBuilder primary: () -> Primary, - @ViewBuilder detail: @escaping () -> Detail - ) { - self.splitsOnDesktop = splitsOnDesktop + public init(@ViewBuilder primary: () -> Primary) { self.primary = primary() - self.detail = detail } public var body: some View { // 두 칸이 기본 폭으로 함께 들어가지 않는 창은 반씩 나눠 처음부터 상세 칸이 잘리지 않게 함 let paneWidth = min(400, width / 2) - let showsDetail = usesDesktopLayout && splitsOnDesktop + let showsDetail = usesDesktopLayout && detail != nil HStack(spacing: 0) { // 넓은 창과 좁은 창을 오가도 목록 칸을 다시 만들지 않도록 같은 구조로 두고 사이드바 구조에서만 폭 조절 // 경계선은 사이드바 경계선부터 창 오른쪽 끝까지 이동 primary + .onPreferenceChange(PaneDetailContentPreferenceKey.self) { content in + detail = content + } + // 바깥 PaneSplitView로 올라가지 않도록 받은 내용을 비움 + .transformPreference(PaneDetailContentPreferenceKey.self) { content in + content = nil + } .resizablePane( width: primaryWidth, minimumWidth: 0, @@ -60,23 +58,19 @@ public struct PaneSplitView: View { value = nil } } - // 좁은 창으로 바뀌어도 상세 칸이 띄운 편집 화면이 닫히지 않도록 폭 0으로 남겨 두고 닫히면 해제 - if showsDetail || isDetailPresenting { + // 좁은 창으로 바뀌면 상세 칸을 빼고, 같은 상태를 화면이 좁은 창의 표시로 이어 그림 + if showsDetail, let detail { // 상세 칸이 기본 폭보다 좁으면 내용을 줄이지 않고 잘라서 표시 Color.clear .overlay(alignment: .leading) { - detail() - .frame(minWidth: showsDetail ? paneWidth : 0, maxWidth: .infinity) + detail + .frame(minWidth: paneWidth, maxWidth: .infinity) // 사이드바 펴기 버튼은 왼쪽 칸 제목 줄에만 표시 .environment(\.expandSideBar, nil) - .onPreferenceChange(PaneDetailPresentingPreferenceKey.self) { isPresenting in - isDetailPresenting = isPresenting - } .onPreferenceChange(PaneDetailEditingPreferenceKey.self) { isEditing in isDetailEditing = isEditing } } - .frame(maxWidth: showsDetail ? .infinity : 0) .mask { Rectangle() } @@ -101,41 +95,32 @@ public struct PaneSplitView: View { } } -public extension View { - // 사이드바 구조로 바뀌면 좁은 창에서 쌓아 연 상세 화면을 내리는 동작 - // 상세 화면이 편집 화면을 띄운 동안에는 닫힌 뒤 실행 - func closesPushedDetail(_ action: @escaping () -> Void) -> some View { - modifier(PushedDetailCloser(action: action)) +// 목록 칸 안의 수정자가 올린 상세 칸 내용 +// 같은 수정자가 같은 항목을 올린 동안은 같은 값으로 보고, 내용이 읽는 상태가 바뀌면 이 View만 다시 그림 +struct PaneDetailContent: View, Equatable { + let id: UUID + // 저장이나 닫기 버튼으로만 닫는 작성 화면, 읽는 화면보다 먼저 표시 + let isEditor: Bool + // 내용이 바인딩으로 읽는 항목의 식별자 + // 그리는 중의 바인딩은 만든 때의 값을 돌려주므로 항목이 바뀌면 새 내용으로 보고 다시 전달 + let key: AnyHashable? + let content: () -> AnyView + + var body: some View { + content() } -} - -private struct PushedDetailCloser: ViewModifier { - @Environment(\.usesDesktopLayout) private var usesDesktopLayout - @State private var isDetailPresenting = false - let action: () -> Void - func body(content: Content) -> some View { - content - .onPreferenceChange(PaneDetailPresentingPreferenceKey.self) { isPresenting in - isDetailPresenting = isPresenting - if usesDesktopLayout && !isPresenting { - action() - } - } - .onChange(of: usesDesktopLayout) { _, isDesktop in - if isDesktop && !isDetailPresenting { - action() - } - } + static func == (lhs: Self, rhs: Self) -> Bool { + lhs.id == rhs.id && lhs.isEditor == rhs.isEditor && lhs.key == rhs.key } } -// 상세 칸이 편집 화면처럼 화면을 덮는 표시를 띄웠는지 전달 -struct PaneDetailPresentingPreferenceKey: PreferenceKey { - static let defaultValue = false +// 목록 칸 안의 화면이 올린 상세 칸 내용 +struct PaneDetailContentPreferenceKey: PreferenceKey { + static var defaultValue: PaneDetailContent? { nil } - static func reduce(value: inout Bool, nextValue: () -> Bool) { - value = value || nextValue() + static func reduce(value: inout PaneDetailContent?, nextValue: () -> PaneDetailContent?) { + value = nextValue() ?? value } } diff --git a/Application/Presentation/PresentationShared/Sources/Common/Component/ProminentPresentation.swift b/Application/Presentation/PresentationShared/Sources/Common/Component/ProminentPresentation.swift index c01ebb998..79de76d63 100644 --- a/Application/Presentation/PresentationShared/Sources/Common/Component/ProminentPresentation.swift +++ b/Application/Presentation/PresentationShared/Sources/Common/Component/ProminentPresentation.swift @@ -19,6 +19,8 @@ struct ProminentPresentation: ViewModifier { @State private var isDismissing = false @State private var isShown = false @State private var presented: Item? + // 지금 띄우라고 한 항목이 있는지, 닫힘이 끝날 때 띄울 때 잡아 둔 바인딩 대신 읽음 + @State private var isRequested = false let item: Binding @ViewBuilder let overlay: (Item, Bool, @escaping () -> Void) -> Overlay @@ -30,6 +32,7 @@ struct ProminentPresentation: ViewModifier { content .onChange(of: item.wrappedValue?.id, initial: true) { _, id in + isRequested = id != nil if id == nil { hide(isAnimated: isAnimated) } else { @@ -48,7 +51,7 @@ struct ProminentPresentation: ViewModifier { ), onDismiss: { isDismissing = false - if item.wrappedValue == nil { + if !isRequested { presented = nil } else { // 닫히는 동안 들어온 표시는 닫힘이 끝난 뒤 다시 띄움 diff --git a/Application/Presentation/PresentationShared/Sources/Common/NavigationRouter.swift b/Application/Presentation/PresentationShared/Sources/Common/NavigationRouter.swift deleted file mode 100644 index 76dec79d4..000000000 --- a/Application/Presentation/PresentationShared/Sources/Common/NavigationRouter.swift +++ /dev/null @@ -1,40 +0,0 @@ -// -// NavigationRouter.swift -// PresentationShared -// -// Created by 최윤진 on 1/1/26. -// - -import SwiftUI - -@Observable -public final class NavigationRouter { - public var path: [Route] = [] - - public var root: Route? { - path.first - } - - public var detailPath: [Route] { - get { - Array(path.dropFirst()) - } - set { - if let route = root { - path = [route] + newValue - } else { - path = newValue - } - } - } - - public init() {} - - public func replace(with route: Route) { - path = [route] - } - - public func push(_ route: Route) { - path.append(route) - } -} diff --git a/Application/Presentation/PresentationShared/Sources/Common/SideBarNavigation.swift b/Application/Presentation/PresentationShared/Sources/Common/SideBarNavigation.swift index 08ddfe9e0..7dd385401 100644 --- a/Application/Presentation/PresentationShared/Sources/Common/SideBarNavigation.swift +++ b/Application/Presentation/PresentationShared/Sources/Common/SideBarNavigation.swift @@ -79,3 +79,47 @@ public struct SideBarContentPreferenceKey: PreferenceKey { value = nextValue() ?? value } } + +public extension View { + // 탭 루트 화면이 사이드바에 표시할 위치와 묶음 하위 항목을 올리고 사이드바 요청을 받음 + // 사이드바가 있는 창으로 켜지거나 좁은 창에서 넓어지면 하위 항목을 채우도록 onLoad 호출 + func compositionLeft( + location: SideBarLocation, + content: SideBarContent, + onLoad: @escaping () -> Void, + onRequest: @escaping (SideBarRequest) -> Void + ) -> some View { + modifier(CompositionLeftModifier( + location: location, + sideBarContent: content, + onLoad: onLoad, + onRequest: onRequest + )) + } +} + +private struct CompositionLeftModifier: ViewModifier { + @Environment(\.sideBarRequest) private var sideBarRequest + @Environment(\.usesDesktopLayout) private var usesDesktopLayout + let location: SideBarLocation + let sideBarContent: SideBarContent + let onLoad: () -> Void + let onRequest: (SideBarRequest) -> Void + + func body(content: Content) -> some View { + content + .preference(key: SideBarLocationPreferenceKey.self, value: location) + .preference(key: SideBarContentPreferenceKey.self, value: sideBarContent) + // 사이드바 요청으로 처음 여는 탭도 그 요청을 반영 + .onChange(of: sideBarRequest, initial: true) { _, request in + if let request { + onRequest(request) + } + } + .onChange(of: usesDesktopLayout, initial: true) { _, usesDesktopLayout in + if usesDesktopLayout { + onLoad() + } + } + } +} diff --git a/Application/Presentation/PresentationShared/Sources/Extension/EnvironmentValues+.swift b/Application/Presentation/PresentationShared/Sources/Extension/EnvironmentValues+.swift index b0d27a4fd..d03927959 100644 --- a/Application/Presentation/PresentationShared/Sources/Extension/EnvironmentValues+.swift +++ b/Application/Presentation/PresentationShared/Sources/Extension/EnvironmentValues+.swift @@ -45,24 +45,6 @@ public extension EnvironmentValues { set { self[ExpandSideBarKey.self] = newValue } } - // 고른 대상과 고른 화면을 세부 정보 사이드바에 알리는 동작, 메인 창 탭 화면 안에서만 있음 - var selectDetailSideBarTarget: ((DetailSideBarTarget?, UUID) -> Void)? { - get { self[SelectDetailSideBarTargetKey.self] } - set { self[SelectDetailSideBarTargetKey.self] = newValue } - } - - // 화면이 사라질 때 세부 정보 사이드바에서 그 화면을 빼는 동작, 메인 창 탭 화면 안에서만 있음 - var removeDetailSideBarTarget: ((UUID) -> Void)? { - get { self[RemoveDetailSideBarTargetKey.self] } - set { self[RemoveDetailSideBarTargetKey.self] = newValue } - } - - // 세부 정보 사이드바가 열려 있는지 여부 - var isDetailSideBarPresented: Bool { - get { self[IsDetailSideBarPresentedKey.self] } - set { self[IsDetailSideBarPresentedKey.self] = newValue } - } - // 세부 정보 사이드바를 열고 닫는 동작, 세부 정보 사이드바가 있는 창 안에서만 있음 var setDetailSideBarPresented: ((Bool) -> Void)? { get { self[SetDetailSideBarPresentedKey.self] } @@ -147,18 +129,6 @@ public extension EnvironmentValues { static let defaultValue: (() -> Void)? = nil } - private struct SelectDetailSideBarTargetKey: EnvironmentKey { - static let defaultValue: ((DetailSideBarTarget?, UUID) -> Void)? = nil - } - - private struct RemoveDetailSideBarTargetKey: EnvironmentKey { - static let defaultValue: ((UUID) -> Void)? = nil - } - - private struct IsDetailSideBarPresentedKey: EnvironmentKey { - static let defaultValue = false - } - private struct SetDetailSideBarPresentedKey: EnvironmentKey { static let defaultValue: ((Bool) -> Void)? = nil } diff --git a/Application/Presentation/PresentationShared/Sources/Extension/View+NavigationDestination.swift b/Application/Presentation/PresentationShared/Sources/Extension/View+NavigationDestination.swift index 8ad886f97..c795d053c 100644 --- a/Application/Presentation/PresentationShared/Sources/Extension/View+NavigationDestination.swift +++ b/Application/Presentation/PresentationShared/Sources/Extension/View+NavigationDestination.swift @@ -34,15 +34,12 @@ public extension View { } } - func navigationDestination( - for type: Item.Type, - interactivePop: @escaping (Item) -> Bool, - @ViewBuilder destination: @escaping (Item) -> Destination - ) -> some View { - navigationDestination(for: type) { value in - destination(value) - .modifier(NavigationPopGesture(isEnabled: interactivePop(value))) - } + // 경로로 쌓은 화면의 설정, 밀어서 뒤로 가게 함 + // 위에 쌓은 화면에 가려진 동안에도 창 폭이 바뀐 것을 받도록 아래 화면에서 읽은 값을 넣음 + func stackDestination(usesDesktopLayout: Bool, usesPaneLayout: Bool) -> some View { + environment(\.showsPaneTitleBar, usesPaneLayout) + .environment(\.usesDesktopLayout, usesDesktopLayout) + .modifier(NavigationPopGesture(isEnabled: true)) } // 사이드바가 있는 창에서 쌓는 화면을 밀리는 효과 없이 내용만 바꿈 diff --git a/Application/Presentation/PresentationShared/Sources/Todo/Detail/TodoDetailFeature.swift b/Application/Presentation/PresentationShared/Sources/Todo/Detail/TodoDetailFeature.swift index 540338264..0384c794a 100644 --- a/Application/Presentation/PresentationShared/Sources/Todo/Detail/TodoDetailFeature.swift +++ b/Application/Presentation/PresentationShared/Sources/Todo/Detail/TodoDetailFeature.swift @@ -12,7 +12,7 @@ import Foundation @Reducer public struct TodoDetailFeature { @ObservableState - public struct State: Equatable { + public struct State: Equatable, Identifiable { @Presents public var alert: AlertState? @Presents public var sheet: SheetState? @Presents public var fullScreenCover: FullScreenCoverState? @@ -26,6 +26,8 @@ public struct TodoDetailFeature { // 좁은 창 세부 정보 시트의 속성 // 시트를 닫아도 저장 결과를 받도록 시트 밖에서 소유 var info: TodoDetailSideBarFeature.State + // 상세 판 안 오른쪽 세부 정보 열을 연 동안 + var isDetailColumnPresented = false public init(todoId: String, showEditButton: Bool) { self.todoId = todoId @@ -33,6 +35,11 @@ public struct TodoDetailFeature { self.info = TodoDetailSideBarFeature.State(todoId: todoId, isEditable: showEditButton) } + // 다른 Todo로 바꾸면 띄운 화면을 새로 만들어 그 Todo를 조회 + public var id: String { + todoId + } + public var isLoading: Bool { loading.isLoading } @@ -84,11 +91,13 @@ public struct TodoDetailFeature { } } - public enum Action { + public enum Action: Equatable { case alert(PresentationAction) case sheet(PresentationAction) case fullScreenCover(PresentationAction) case onAppear + // 화면을 다시 그려도 불러온 Todo를 유지하고, 다른 곳에서 바꾼 Todo는 여는 화면이 다시 조회 + case fetch case fetchFailed case setSheet(SheetState?) case setFullScreenCover(FullScreenCoverState?) @@ -96,15 +105,16 @@ public struct TodoDetailFeature { case setReferenceItems([Int: TodoReferenceItem]) case loading(LoadingFeature.Action) case info(TodoDetailSideBarFeature.Action) + case setDetailColumnPresented(Bool) @CasePathable - public enum Sheet { + public enum Sheet: Equatable { case tapCloseButton case todo(TodoDetailFeature.Action) } @CasePathable - public enum FullScreenCover { + public enum FullScreenCover: Equatable { case todoEditor(TodoEditorFeature.Action) } } @@ -146,6 +156,10 @@ public struct TodoDetailFeature { case .fullScreenCover: break case .onAppear: + // 좁은 창과 넓은 창의 화면을 오가도 같은 상태를 이어 그리므로 처음 한 번만 조회 + guard state.todo == nil else { break } + return fetchTodoEffect(todoId: state.todoId) + case .fetch: return fetchTodoEffect(todoId: state.todoId) case .fetchFailed: state.alert = Self.alertState() @@ -181,13 +195,15 @@ public struct TodoDetailFeature { state.referenceItems = [:] return resolveMarkdownEffect(content: todo.content) case .info(.editor(.saveFailed)): - // 시트를 닫은 뒤 실패한 저장은 상세 화면에서 알림 - if state.sheet != .info { + // 시트를 닫은 뒤 실패한 저장은 상세 화면에서 알림, 상세 판 세부 정보 열에서 실패한 저장은 열에서 알림 + if state.sheet != .info && !state.isDetailColumnPresented { state.info.editor?.alert = nil state.alert = Self.alertState() } case .info: break + case .setDetailColumnPresented(let isPresented): + state.isDetailColumnPresented = isPresented } return .none diff --git a/Application/Presentation/PresentationShared/Sources/Todo/Detail/TodoDetailPane.swift b/Application/Presentation/PresentationShared/Sources/Todo/Detail/TodoDetailPane.swift deleted file mode 100644 index 34f02bcba..000000000 --- a/Application/Presentation/PresentationShared/Sources/Todo/Detail/TodoDetailPane.swift +++ /dev/null @@ -1,70 +0,0 @@ -// -// TodoDetailPane.swift -// PresentationShared -// -// Created by opfic on 11/13/26. -// - -import SwiftUI -import ComposableArchitecture - -// 사이드바가 있는 창에서 목록 오른쪽 칸의 Todo 상세, 선택 전에는 선택 안내 -public struct TodoDetailPane: View { - private let todoId: String? - private let showEditButton: Bool - private let windowEvent: TodoEditorWindowEvent? - private let onClose: (() -> Void)? - - public init( - todoId: String?, - showEditButton: Bool, - windowEvent: TodoEditorWindowEvent? = nil, - onClose: (() -> Void)? = nil - ) { - self.todoId = todoId - self.showEditButton = showEditButton - self.windowEvent = windowEvent - self.onClose = onClose - } - - public var body: some View { - if let todoId { - TodoDetailView( - store: Store( - initialState: TodoDetailFeature.State(todoId: todoId, showEditButton: showEditButton) - ) { - TodoDetailFeature() - }, - windowEvent: windowEvent, - isPaneDetail: true, - onClose: onClose - ) - .environment(\.showsPaneTitleBar, true) - .id(todoId) - } else { - PanePlaceholder() - } - } -} - -// 상세 칸에서 고른 항목이 없을 때 표시하는 안내 -public struct PanePlaceholder: View { - public init() {} - - public var body: some View { - VStack(spacing: 12) { - Image(systemName: "doc.text") - .font(.adaptive(.largeTitle)) - .foregroundStyle(Color.tertiaryLabel) - Text("pane_select_detail", bundle: PresentationResources.bundle) - .font(.adaptive(.callout)) - .foregroundStyle(Color.secondaryLabel) - } - .frame(maxWidth: .infinity, maxHeight: .infinity) - // 목록 칸 제목 줄과 구분선 높이 맞춤 - .safeAreaInset(edge: .top, spacing: 0) { - PaneTitleBar(Text(verbatim: "")) - } - .background(Color.background) - } -} diff --git a/Application/Presentation/PresentationShared/Sources/Todo/Detail/TodoDetailPanel.swift b/Application/Presentation/PresentationShared/Sources/Todo/Detail/TodoDetailPanel.swift index 8f2d37e8f..dbf1c1043 100644 --- a/Application/Presentation/PresentationShared/Sources/Todo/Detail/TodoDetailPanel.swift +++ b/Application/Presentation/PresentationShared/Sources/Todo/Detail/TodoDetailPanel.swift @@ -6,33 +6,29 @@ // import SwiftUI -import Combine import ComposableArchitecture // 사이드바가 있는 창의 상세 판에 연 보기 전용 Todo // 위쪽 막대의 버튼으로 판 안 오른쪽 세부 정보 열을 열고 닫음 +// 판 메뉴의 중요 표시와 완료도 세부 정보 열과 같은 속성 상태로 바로 저장 public struct TodoDetailPanel: View { @Environment(\.dismiss) private var dismiss - @State private var store: StoreOf + @State private var store: StoreOf private let location: Text private let windowEvent: TodoEditorWindowEvent? // 목록 | 상세 두 칸을 쓰는 화면만 오른쪽 칸으로 옮기기 표시 private let onMoveToPane: (() -> Void)? private let onDelete: (() -> Void)? + // 상세 상태는 연 화면의 Feature가 갖고, 창 폭이 바뀌면 같은 상태를 다른 화면이 이어 그림 public init( - todoId: String, + store: StoreOf, location: Text, - isEditable: Bool, windowEvent: TodoEditorWindowEvent? = nil, onMoveToPane: (() -> Void)? = nil, onDelete: (() -> Void)? = nil ) { - self._store = State(initialValue: Store( - initialState: TodoDetailPanelFeature.State(todoId: todoId, isEditable: isEditable) - ) { - TodoDetailPanelFeature() - }) + self._store = State(initialValue: store) self.location = location self.windowEvent = windowEvent self.onMoveToPane = onMoveToPane @@ -43,10 +39,10 @@ public struct TodoDetailPanel: View { VStack(spacing: 0) { DetailPanelBar( location: location, - title: Text(verbatim: store.detail.todo.map { "#\($0.number)" } ?? "") + title: Text(verbatim: store.todo.map { "#\($0.number)" } ?? "") ) { Button { - store.send(.binding(.set(\.isDetailColumnPresented, !store.isDetailColumnPresented))) + store.send(.setDetailColumnPresented(!store.isDetailColumnPresented)) } label: { Image(systemName: "sidebar.right") } @@ -56,10 +52,7 @@ public struct TodoDetailPanel: View { } HStack(spacing: 0) { - TodoDetailView( - store: store.scope(state: \.detail, action: \.detail), - windowEvent: windowEvent - ) + TodoDetailView(store: store, windowEvent: windowEvent) if store.isDetailColumnPresented { VStack(spacing: 0) { PaneTitleBar(background: .secondaryBackground) { @@ -67,11 +60,8 @@ public struct TodoDetailPanel: View { } actions: { EmptyView() } - // 저장 결과 전달과 다른 곳에서 고친 값 반영은 판이 맡음 - TodoDetailSideBarView( - store: store.scope(state: \.sideBar, action: \.sideBar), - windowEvent: nil - ) + // 저장 결과 전달과 다른 곳에서 고친 값 반영은 판 안 상세가 맡음 + TodoDetailSideBarView(store: store) } .frame(width: 280 * AdaptiveSize.boardScale) .background(Color.secondaryBackground) @@ -83,32 +73,8 @@ public struct TodoDetailPanel: View { } } } - // 세부 정보 열을 닫아 둔 동안 판 메뉴로 저장하다 실패하면 판에서 알림 표시 - .background { - if !store.isDetailColumnPresented, - let editorStore = store.scope(state: \.sideBar.editor, action: \.sideBar.editor) { - Color.clear - .prominentAlert(editorStore, state: \.alert, action: \.alert) - } - } // 세부 정보 열을 닫아 둔 동안에도 판 메뉴로 중요 표시와 완료를 바꾸도록 속성을 불러옴 - .onAppear { store.send(.sideBar(.onAppear)) } - .onChange(of: store.sideBar.editor?.saveResult) { _, result in - // 판에서 저장한 Todo를 목록과 판 상세에도 반영 - guard case .updated(let todo)? = result else { return } - windowEvent?.submitUpdate(value: TodoEditorWindowValue(todo: todo), todo: todo) - } - .onReceive(windowSubmits) { submit in - // 판이 저장해 보낸 Todo는 다시 받지 않음 - guard case .update(let value, let todo) = submit, - value.matchesEdit(todoId: store.sideBar.todoId), - store.sideBar.editor?.saveResult != .updated(todo) else { return } - store.send(.sideBar(.setTodo(todo))) - } - } - - private var windowSubmits: AnyPublisher { - windowEvent?.submits ?? Empty().eraseToAnyPublisher() + .onAppear { store.send(.info(.onAppear)) } } @ViewBuilder @@ -123,9 +89,9 @@ public struct TodoDetailPanel: View { } Divider() } - if store.sideBar.isEditable, let editor = store.sideBar.editor { + if store.info.isEditable, let editor = store.info.editor { Button { - store.send(.sideBar(.editor(.binding(.set(\.isPinned, !editor.isPinned))))) + store.send(.info(.editor(.binding(.set(\.isPinned, !editor.isPinned))))) } label: { Label { Text(editor.isPinned ? "todo_action_unpin" : "todo_action_pin", bundle: PresentationResources.bundle) @@ -134,7 +100,7 @@ public struct TodoDetailPanel: View { } } Button { - store.send(.sideBar(.editor(.binding(.set(\.isCompleted, !editor.isCompleted))))) + store.send(.info(.editor(.binding(.set(\.isCompleted, !editor.isCompleted))))) } label: { Label { Text( diff --git a/Application/Presentation/PresentationShared/Sources/Todo/Detail/TodoDetailPanelFeature.swift b/Application/Presentation/PresentationShared/Sources/Todo/Detail/TodoDetailPanelFeature.swift deleted file mode 100644 index 9b76d6f93..000000000 --- a/Application/Presentation/PresentationShared/Sources/Todo/Detail/TodoDetailPanelFeature.swift +++ /dev/null @@ -1,43 +0,0 @@ -// -// TodoDetailPanelFeature.swift -// PresentationShared -// -// Created by opfic on 11/16/26. -// - -import ComposableArchitecture - -// Mac 상세 판의 보기 전용 Todo 상세와 판 안 세부 정보 열 -@Reducer -public struct TodoDetailPanelFeature { - @ObservableState - public struct State: Equatable { - var detail: TodoDetailFeature.State - // 판 메뉴의 중요 표시와 완료도 세부 정보 열과 같이 바로 저장 - var sideBar: TodoDetailSideBarFeature.State - var isDetailColumnPresented = false - - public init(todoId: String, isEditable: Bool) { - self.detail = TodoDetailFeature.State(todoId: todoId, showEditButton: false) - self.sideBar = TodoDetailSideBarFeature.State(todoId: todoId, isEditable: isEditable) - } - } - - public enum Action: BindableAction { - case binding(BindingAction) - case detail(TodoDetailFeature.Action) - case sideBar(TodoDetailSideBarFeature.Action) - } - - public init() { } - - public var body: some ReducerOf { - BindingReducer() - Scope(state: \.detail, action: \.detail) { - TodoDetailFeature() - } - Scope(state: \.sideBar, action: \.sideBar) { - TodoDetailSideBarFeature() - } - } -} diff --git a/Application/Presentation/PresentationShared/Sources/Todo/Detail/TodoDetailSideBarView.swift b/Application/Presentation/PresentationShared/Sources/Todo/Detail/TodoDetailSideBarView.swift index a005b745f..4d15b4ff0 100644 --- a/Application/Presentation/PresentationShared/Sources/Todo/Detail/TodoDetailSideBarView.swift +++ b/Application/Presentation/PresentationShared/Sources/Todo/Detail/TodoDetailSideBarView.swift @@ -28,6 +28,12 @@ public struct TodoDetailSideBarView: View { self.windowEvent = windowEvent } + // 열어 둔 Todo 상세와 속성 상태를 함께 쓰는 세부 정보 열 + // 저장 결과 전달과 다른 곳에서 고친 값 반영은 상세 화면이 맡음 + public init(store: StoreOf) { + self.init(store: store.scope(state: \.info, action: \.info), windowEvent: nil) + } + // 상세 판과 세부 정보 시트처럼 바깥 화면이 속성 상태를 함께 쓰는 세부 정보 열 init( store: StoreOf, diff --git a/Application/Presentation/PresentationShared/Sources/Todo/Detail/TodoDetailView.swift b/Application/Presentation/PresentationShared/Sources/Todo/Detail/TodoDetailView.swift index 802f13c67..b4dd6b66f 100644 --- a/Application/Presentation/PresentationShared/Sources/Todo/Detail/TodoDetailView.swift +++ b/Application/Presentation/PresentationShared/Sources/Todo/Detail/TodoDetailView.swift @@ -52,8 +52,6 @@ public struct TodoDetailView: View { detailContent(editsInPane: editsInPane) .onAppear { store.send(.onAppear) } - // 좁은 창으로 바뀌어도 편집 화면이 닫히지 않도록 상세 칸을 남겨 두게 알림 - .preference(key: PaneDetailPresentingPreferenceKey.self, value: store.fullScreenCover != nil) // 편집 화면에서 저장하면 창 폭과 상관없이 Mac 편집 창과 같은 경로로 옆 목록에도 전달 // 편집 화면이 닫히며 놓치지 않도록 상세 상태에 남긴 저장 결과로 전달 .onChange(of: store.savedTodo) { _, todo in diff --git a/Application/Presentation/PresentationShared/Sources/Todo/Editor/TodoEditorView.swift b/Application/Presentation/PresentationShared/Sources/Todo/Editor/TodoEditorView.swift index e51cfb160..991e11c49 100644 --- a/Application/Presentation/PresentationShared/Sources/Todo/Editor/TodoEditorView.swift +++ b/Application/Presentation/PresentationShared/Sources/Todo/Editor/TodoEditorView.swift @@ -59,7 +59,7 @@ public struct TodoEditorView: View { } .prominentAlert(store, state: \.alert, action: \.alert) // 사이드바가 있는 창은 작성 중인 속성을 세부 정보 사이드바에 표시 - .detailSideBar { + .compositionRight { ScrollView { TodoSideBarProperties( editorStore: store, diff --git a/Application/Presentation/PresentationShared/Tests/Todo/TodoDetailFeatureTests.swift b/Application/Presentation/PresentationShared/Tests/Todo/TodoDetailFeatureTests.swift index 179170f6a..6c8e06dab 100644 --- a/Application/Presentation/PresentationShared/Tests/Todo/TodoDetailFeatureTests.swift +++ b/Application/Presentation/PresentationShared/Tests/Todo/TodoDetailFeatureTests.swift @@ -284,6 +284,48 @@ struct TodoDetailFeatureTests { #expect(adapter.infoEditor?.tags == ["tag"]) } + @Test("화면을 옮겨 그려 다시 나타나도 다시 조회하지 않고, 다시 조회를 요청하면 조회한다") + func 화면을_옮겨_그려_다시_나타나도_다시_조회하지_않고_다시_조회를_요청하면_조회한다() async { + let todo = makeTodo(id: "todo-1", content: "content") + let fetchSpy = FetchTodoByIdUseCaseSpy(todo: todo) + let adapter = DetailStoreTestAdapter( + fetchUseCase: fetchSpy, + referenceUseCase: FetchReferenceItemsUseCaseSpy(), + todoId: "todo-1" + ) + + adapter.onAppear() + + await waitUntil { + adapter.todo == todo + } + + adapter.onAppear() + adapter.fetch() + + await waitUntil { + fetchSpy.todoIds.count == 2 + } + + #expect(fetchSpy.todoIds == ["todo-1", "todo-1"]) + } + + @Test("상세 판 세부 정보 열에서 저장에 실패하면 열 안 알림을 그대로 둔다") + func 상세_판_세부_정보_열에서_저장에_실패하면_열_안_알림을_그대로_둔다() async { + let upsertSpy = TodoEditorUpsertTodoUseCaseSpy() + upsertSpy.error = DetailTestError.failure + let adapter = makeInfoAdapter(upsertSpy: upsertSpy) + + await adapter.openDetailColumnAndTogglePinned() + + await waitUntil { + adapter.infoEditor?.alert != nil + } + + #expect(adapter.infoEditor?.alert != nil) + #expect(adapter.alert == nil) + } + private func makeInfoAdapter(upsertSpy: TodoEditorUpsertTodoUseCaseSpy) -> DetailStoreTestAdapter { DetailStoreTestAdapter( fetchUseCase: FetchTodoByIdUseCaseSpy(todo: makeTodo()), @@ -369,6 +411,10 @@ private struct DetailStoreTestAdapter: DetailTestAdapter { store.send(.onAppear) } + func fetch() { + store.send(.fetch) + } + func onSheetTodoAppear() { store.send(.sheet(.presented(.todo(.onAppear)))) } func setSheet(_ sheet: TodoDetailFeature.SheetState?) { @@ -412,6 +458,17 @@ private struct DetailStoreTestAdapter: DetailTestAdapter { await openInfo() store.send(.info(.editor(.binding(.set(\.isPinned, true))))) } + + func openDetailColumnAndTogglePinned() async { + store.send(.setDetailColumnPresented(true)) + store.send(.info(.onAppear)) + + await waitUntil { + store.info.editor != nil + } + + store.send(.info(.editor(.binding(.set(\.isPinned, true))))) + } } private func todoDetailState( diff --git a/Application/Presentation/ProfileTab/Sources/Profile/ActivityCard.swift b/Application/Presentation/ProfileTab/Sources/Profile/ActivityCard.swift index 7639039fb..827b92216 100644 --- a/Application/Presentation/ProfileTab/Sources/Profile/ActivityCard.swift +++ b/Application/Presentation/ProfileTab/Sources/Profile/ActivityCard.swift @@ -11,7 +11,6 @@ import Domain import PresentationShared struct ActivityCard: View { - @Environment(\.isTabContentActive) private var isTabContentActive @Environment(\.usesPaneLayout) private var usesPaneLayout @Environment(\.isiOSAppOnMac) private var isiOSAppOnMac @Bindable var store: StoreOf @@ -95,19 +94,7 @@ struct ActivityCard: View { } .buttonStyle(.plain) // 칸으로 나눈 화면은 분기 선택을 시트 대신 버튼 옆 팝오버로 표시 - .popover( - isPresented: $store.showQuarterPicker - .hiddenInPane(!usesPaneLayout) - .activePresentation(when: isTabContentActive), - // Mac은 분기 표시 아래로 표시 - arrowEdge: isiOSAppOnMac ? .top : nil - ) { - QuarterPickerSheet(store: store) - .frame(width: 320 * AdaptiveSize.boardScale) - .fixedSize(horizontal: false, vertical: true) - .presentationBackground(Color.secondaryBackground) - .presentationCompactAdaptation(.popover) - } + .compositionPickerAnchor() Spacer() Button { store.send(.moveQuarter(1)) @@ -196,7 +183,8 @@ struct ActivityCard: View { // 행 배치를 바꾸지 않고 선택한 행 배경만 바깥으로 넓힘 // 선택 표시는 다른 목록 행과 같은 회색 .background { - if usesPaneLayout && store.selectedTodoRoute == .activity(activity.todoId) { + if usesPaneLayout && store.showsDetailInPane + && store.detail?.todoId == activity.todoId && store.detail?.showEditButton == false { RoundedRectangle(cornerRadius: CornerRadius.control) .fill(Color.fill) .padding(.horizontal, -8) diff --git a/Application/Presentation/ProfileTab/Sources/Profile/ProfileFeature.swift b/Application/Presentation/ProfileTab/Sources/Profile/ProfileFeature.swift index ba0f6c21f..eaec6a405 100644 --- a/Application/Presentation/ProfileTab/Sources/Profile/ProfileFeature.swift +++ b/Application/Presentation/ProfileTab/Sources/Profile/ProfileFeature.swift @@ -34,6 +34,9 @@ struct ProfileFeature { @ObservableState struct State: Equatable { @Presents var alert: AlertState? + // 활동 기록이나 최근 Todo에서 연 Todo 상세, 활동 기록 Todo는 고칠 수 없어 편집 버튼 없이 표시 + // 좁은 창은 내비게이션에 쌓고 사이드바가 있는 창은 상세 판이나 오른쪽 칸에 표시 + @Presents var detail: TodoDetailFeature.State? var name = "" var email = "" var isNetworkConnected = true @@ -54,16 +57,18 @@ struct ProfileFeature { var dayActivitiesByDate: [Date: [HeatmapActivityItem]] = [:] var selectedActivityKinds: Set = [.created, .completed, .deleted] var selectedDay: HeatmapDay? - var selectedTodoRoute: ProfileRoute? - // 사이드바가 있는 창에서 사이드바까지 덮는 상세 판에 연 Todo - var panelTodoRoute: ProfileRoute? + // 사이드바가 있는 창에서 상세 판 대신 오른쪽 칸에 표시 + var showsDetailInPane = false var showDoneButton = false var loading = LoadingFeature.State() } enum Action: BindableAction { case alert(PresentationAction) + case detail(PresentationAction) case binding(BindingAction) + // 사이드바가 있는 창은 연 곳(상세 판이나 오른쪽 칸)의 내용을 바꿈 + case selectTodo(String, isEditable: Bool) case startObserving case fetchData case refresh @@ -119,6 +124,15 @@ struct ProfileFeature { state.alert = nil case .alert: break + case .detail(.dismiss): + state.showsDetailInPane = false + case .detail: + break + case .selectTodo(let todoId, let isEditable): + // 이미 연 Todo는 불러온 상세와 열어 둔 시트를 그대로 둠 + if state.detail?.todoId != todoId || state.detail?.showEditButton != isEditable { + state.detail = TodoDetailFeature.State(todoId: todoId, showEditButton: isEditable) + } case .binding(\.isCreatedActivitySelected): return updateHeatmapActivityKindsEffectIfNeeded(.created, state: state) case .binding(\.isCompletedActivitySelected): @@ -243,6 +257,9 @@ struct ProfileFeature { return .none } .ifLet(\.$alert, action: \.alert) + .ifLet(\.$detail, action: \.detail) { + TodoDetailFeature() + } } } diff --git a/Application/Presentation/ProfileTab/Sources/Profile/ProfileView.swift b/Application/Presentation/ProfileTab/Sources/Profile/ProfileView.swift index fa54593f1..e86897b8e 100644 --- a/Application/Presentation/ProfileTab/Sources/Profile/ProfileView.swift +++ b/Application/Presentation/ProfileTab/Sources/Profile/ProfileView.swift @@ -16,9 +16,8 @@ public struct ProfileView: View { @Environment(\.readableContentWidth) private var readableContentWidth @Environment(\.usesPaneLayout) private var usesPaneLayout @Environment(\.deviceType) private var deviceType - @Environment(\.sideBarRequest) private var sideBarRequest + @Environment(\.isiOSAppOnMac) private var isiOSAppOnMac @State private var store: StoreOf - @State private var router = NavigationRouter() @Bindable private var settingsStore: StoreOf private let isSelected: Bool private let windowEvent: TodoEditorWindowEvent @@ -38,19 +37,19 @@ public struct ProfileView: View { } public var body: some View { - NavigationStack(path: path) { + NavigationStack { // 사이드바가 있는 창은 프로필을 창 전체 폭으로 두고 오른쪽 칸으로 옮긴 Todo가 있을 때만 두 칸으로 나눔 - PaneSplitView(splitsOnDesktop: store.selectedTodoRoute != nil) { + PaneSplitView { ScrollView { // 카드 없이 각 섹션이 페이지 여백을 가짐 LazyVStack(alignment: .leading, spacing: 0) { UserInfoCard(store: store, isSelected: isSelected) ActivityCard(store: store) { todoId in - showTodo(.activity(todoId)) + store.send(.selectTodo(todoId, isEditable: false)) } ProfileGoalSummary(store: store) RecentActivityCard(store: store) { todoId in - showTodo(.recentTodo(todoId)) + store.send(.selectTodo(todoId, isEditable: true)) } } .padding(.bottom, 24) @@ -68,73 +67,65 @@ public struct ProfileView: View { } } .background(Color.background) - } detail: { - let closeDetailPane: (() -> Void)? = usesDesktopLayout - ? { store.send(.binding(.set(\.selectedTodoRoute, nil))) } : nil - - switch store.selectedTodoRoute { - case .activity(let todoId): - TodoDetailPane(todoId: todoId, showEditButton: false, onClose: closeDetailPane) - case .recentTodo(let todoId): - TodoDetailPane( - todoId: todoId, - showEditButton: true, - windowEvent: windowEvent, - onClose: closeDetailPane + // 좁은 창은 프로필 위에 쌓고, 사이드바가 있는 창은 상세 판이나 오른쪽 칸에 표시 + // 창 폭이 바뀌면 같은 상세 상태를 바뀐 자리에서 이어 그림 + .compositionDetail( + item: $store.scope(state: \.detail, action: \.detail), + inPane: store.showsDetailInPane, + isActive: isSelected + ) { detailStore, onClose in + // 활동 기록 Todo는 고칠 수 없어 편집 결과를 받을 창 이벤트 없이 표시 + TodoDetailView( + store: detailStore, + windowEvent: detailStore.showEditButton ? windowEvent : nil, + isPaneDetail: onClose != nil, + onClose: onClose ) - default: - TodoDetailPane(todoId: nil, showEditButton: false) - } - } - .detailSideBarTarget(store.selectedTodoRoute?.detailSideBarTarget) - // 좁은 창으로 바뀌면 상세 판을 숨기고 넓어지면 다시 표시 - .detailPanel(item: $store.panelTodoRoute.activePresentation(when: isSelected && usesDesktopLayout)) { route in - if case .todo(let todoId, let isEditable, _)? = route.detailSideBarTarget { + // 칸 안에서 다른 Todo로 바꾸거나 같은 Todo를 다른 목록에서 다시 고르면 그 Todo를 조회 + .id([AnyHashable(detailStore.todoId), detailStore.showEditButton]) + } panel: { detailStore in TodoDetailPanel( - todoId: todoId, + store: detailStore, location: Text("nav_profile", bundle: PresentationResources.bundle), - isEditable: isEditable, - windowEvent: isEditable ? windowEvent : nil, + windowEvent: detailStore.showEditButton ? windowEvent : nil, onMoveToPane: { - store.send(.binding(.set(\.panelTodoRoute, nil))) - store.send(.binding(.set(\.selectedTodoRoute, route))) + store.send(.binding(.set(\.showsDetailInPane, true))) } ) } } + .compositionRight(isActive: store.showsDetailInPane && store.detail != nil) { + if let detail = store.detail { + TodoDetailSideBarView( + todoId: detail.todoId, + isEditable: detail.showEditButton, + windowEvent: windowEvent + ) + // 같은 Todo도 편집할 수 있는지가 바뀌면 다시 만듦 + .id([AnyHashable(detail.todoId), detail.showEditButton]) + } + } + // 좁은 창은 설정 목록과 고른 항목 화면을 프로필 위에 쌓고, 사이드바가 있는 창은 창 전체 설정 화면에 그려 쌓지 않음 .navigationDestination( - for: ProfileRoute.self, - interactivePop: { - switch $0 { - case .settings, .theme, .activity, .recentTodo: true - default: false - } - }, - destination: { destinationView($0).environment(\.showsPaneTitleBar, usesPaneLayout) } - ) + isPresented: $settingsStore.isListPushed.hiddenInPane(usesDesktopLayout), + interactivePop: true + ) { + SettingsView(store: settingsStore) { route in + settingsStore.send(.select(route)) + } + .environment(\.showsPaneTitleBar, usesPaneLayout) + .navigationDestination( + item: $settingsStore.pushedRoute.hiddenInPane(usesDesktopLayout), + interactivePop: settingsStore.pushedRoute == .theme + ) { route in + settingsPage(route) + .environment(\.showsPaneTitleBar, usesPaneLayout) + } + } } .desktopNavigationTransition() // 창 폭이 바뀌어 같은 설정을 다시 쌓거나 내릴 때 밀리는 효과 없이 바꿈 .transaction(value: usesDesktopLayout) { $0.disablesAnimations = true } - // 사이드바 구조로 바뀌면 쌓아 연 Todo 상세는 내리고 같은 Todo를 옆 칸에 표시 - .closesPushedDetail { - switch router.path.last { - case .activity?, .recentTodo?: - let route = router.path.removeLast() - store.send(.binding(.set(\.selectedTodoRoute, route))) - default: - break - } - } - // 사이드바 요청으로 처음 여는 탭도 그 요청을 반영 - .onChange(of: sideBarRequest, initial: true) { _, request in - switch request?.action { - case .open(.profile): - router.path = [] - default: - break - } - } .onChange(of: isSelected, initial: true) { _, isSelected in if isSelected { store.send(.fetchData) @@ -145,11 +136,14 @@ public struct ProfileView: View { settingsStore.send(.startObserving) } .prominentAlert(store, state: \.alert, action: \.alert) - .prominentSheet( - isPresented: $store.showQuarterPicker - .hiddenInPane(usesPaneLayout) - .activePresentation(when: isSelected) - ) { QuarterPickerSheet(store: store) } + // 좁은 창은 분기 선택을 시트로, 칸으로 나눈 화면은 분기 표시 옆 팝오버로 표시하고 Mac은 분기 표시 아래로 표시 + .compositionPicker( + isPresented: $store.showQuarterPicker, + isActive: isSelected, + arrowEdge: isiOSAppOnMac ? .top : nil + ) { + QuarterPickerSheet(store: store) + } .overlay { if store.isLoading { LoadingView() @@ -208,73 +202,6 @@ 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[.. some View { - switch route { - case .settings: - SettingsView(store: settingsStore) { route in - settingsStore.send(.select(route)) - } - case .activity(let todoId): - TodoDetailView(store: Store( - initialState: TodoDetailFeature.State(todoId: todoId, showEditButton: false) - ) { - TodoDetailFeature() - }) - case .recentTodo(let todoId): - TodoDetailView(store: Store( - initialState: TodoDetailFeature.State(todoId: todoId, showEditButton: true) - ) { - TodoDetailFeature() - }, windowEvent: windowEvent) - case .theme, .pushNotification, .account, .information: - settingsPage(route) - } - } - // 설정에서 고르는 아래 화면 @ViewBuilder private func settingsPage(_ route: ProfileRoute) -> some View { @@ -292,7 +219,7 @@ public struct ProfileView: View { store: settingsStore.scope(state: \.account, action: \.account), settingsStore: settingsStore ) - case .settings, .activity, .recentTodo, .information: + case .settings, .information: EmptyView() } } @@ -328,8 +255,6 @@ private struct ProfileGoalSummary: View { public enum ProfileRoute: Hashable, Identifiable { case settings - case activity(String) - case recentTodo(String) case theme case pushNotification case account @@ -338,14 +263,3 @@ public enum ProfileRoute: Hashable, Identifiable { public var id: Self { self } } - -private extension ProfileRoute { - // 활동 기록 Todo는 고칠 수 없어 읽기 전용으로 표시 - var detailSideBarTarget: DetailSideBarTarget? { - switch self { - case .activity(let todoId): .todo(id: todoId, isEditable: false) - case .recentTodo(let todoId): .todo(id: todoId, isEditable: true) - default: nil - } - } -} diff --git a/Application/Presentation/ProfileTab/Sources/Profile/RecentActivityCard.swift b/Application/Presentation/ProfileTab/Sources/Profile/RecentActivityCard.swift index 2bc14bc1a..fb147da75 100644 --- a/Application/Presentation/ProfileTab/Sources/Profile/RecentActivityCard.swift +++ b/Application/Presentation/ProfileTab/Sources/Profile/RecentActivityCard.swift @@ -36,7 +36,8 @@ struct RecentActivityCard: View { } label: { RecentTodoRow( todo: todo, - isSelected: usesPaneLayout && store.selectedTodoRoute == .recentTodo(todo.id) + isSelected: usesPaneLayout && store.showsDetailInPane + && store.detail?.todoId == todo.id && store.detail?.showEditButton == true ) .todoDetailPreview(todoId: todo.id) } diff --git a/Application/Presentation/ProfileTab/Sources/Settings/DesktopSettingsView.swift b/Application/Presentation/ProfileTab/Sources/Settings/DesktopSettingsView.swift index 7ee2fead7..24de779e6 100644 --- a/Application/Presentation/ProfileTab/Sources/Settings/DesktopSettingsView.swift +++ b/Application/Presentation/ProfileTab/Sources/Settings/DesktopSettingsView.swift @@ -158,7 +158,7 @@ public struct DesktopSettingsView: View { // 위쪽 줄 구분선과 첫 항목 사이 여백 .contentMargins(.top, isiOSAppOnMac ? 20 * AdaptiveSize.boardScale : 24, for: .scrollContent) .background(Color.background) - case .settings, .activity, .recentTodo: + case .settings: EmptyView() } } @@ -178,7 +178,7 @@ private extension ProfileRoute { String(localized: "settings_account_section", bundle: PresentationResources.bundle) case .information: String(localized: "settings_information", bundle: PresentationResources.bundle) - case .settings, .activity, .recentTodo: + case .settings: "" } } @@ -193,7 +193,7 @@ private extension ProfileRoute { "person" case .information: "info.circle" - case .settings, .activity, .recentTodo: + case .settings: "" } } diff --git a/Application/Presentation/ProfileTab/Sources/Settings/SettingsFeature.swift b/Application/Presentation/ProfileTab/Sources/Settings/SettingsFeature.swift index 3e6f3d63a..60fb4154e 100644 --- a/Application/Presentation/ProfileTab/Sources/Settings/SettingsFeature.swift +++ b/Application/Presentation/ProfileTab/Sources/Settings/SettingsFeature.swift @@ -41,6 +41,26 @@ public struct SettingsFeature { // 열린 설정 화면, 좁은 창은 프로필 화면에 쌓고 사이드바가 있는 창은 창 전체 설정 화면에 표시 public var screen: Screen? + // 좁은 창에서 프로필 위에 쌓은 설정 목록, 뒤로 가면 설정을 닫음 + public var isListPushed: Bool { + get { screen != nil } + set { + if !newValue { + screen = nil + } + } + } + + // 좁은 창에서 설정 목록 위에 쌓은 고른 항목 화면, 뒤로 가면 설정 목록으로 돌아감 + public var pushedRoute: ProfileRoute? { + get { screen == .detail ? selectedRoute : nil } + set { + if newValue == nil && screen == .detail { + screen = .list + } + } + } + public init() { } static func betaTestURL(appEnvironment: String?, testFlightURL: String?) -> URL? { diff --git a/Application/Presentation/ProfileTab/Tests/Profile/ProfileFeatureTests.swift b/Application/Presentation/ProfileTab/Tests/Profile/ProfileFeatureTests.swift index 2bd3a6f3f..754b07413 100644 --- a/Application/Presentation/ProfileTab/Tests/Profile/ProfileFeatureTests.swift +++ b/Application/Presentation/ProfileTab/Tests/Profile/ProfileFeatureTests.swift @@ -223,6 +223,28 @@ struct ProfileFeatureTests { #expect(adapter.selectedActivityKinds == [.created]) #expect(spy.activityTypes.isEmpty) } + + @Test("ProfileFeature는 고른 Todo를 연 자리에서 바꾸고, 상세를 닫으면 오른쪽 칸 표시도 끈다") + func ProfileFeature는_고른_Todo를_연_자리에서_바꾸고_상세를_닫으면_오른쪽_칸_표시도_끈다() async { + let store = TestStore(initialState: ProfileFeature.State()) { + ProfileFeature() + } + + await store.send(.selectTodo("activity", isEditable: false)) { + $0.detail = TodoDetailFeature.State(todoId: "activity", showEditButton: false) + } + await store.send(.binding(.set(\.showsDetailInPane, true))) { + $0.showsDetailInPane = true + } + // 같은 Todo도 최근 Todo에서 고르면 편집할 수 있는 상세로 바꿈 + await store.send(.selectTodo("activity", isEditable: true)) { + $0.detail = TodoDetailFeature.State(todoId: "activity", showEditButton: true) + } + await store.send(.detail(.dismiss)) { + $0.detail = nil + $0.showsDetailInPane = false + } + } } private final class FetchTodosUseCaseSpy: FetchTodosUseCase { diff --git a/Application/Presentation/TodayTab/Sources/TodayFeature+State.swift b/Application/Presentation/TodayTab/Sources/TodayFeature+State.swift index 666f4ce43..9b97fe271 100644 --- a/Application/Presentation/TodayTab/Sources/TodayFeature+State.swift +++ b/Application/Presentation/TodayTab/Sources/TodayFeature+State.swift @@ -33,6 +33,8 @@ extension TodayFeature { @ObservableState struct State: Equatable { @Presents var alert: AlertState? + // 연 Todo 상세, 좁은 창은 내비게이션에 쌓고 사이드바가 있는 창은 상세 판이나 오른쪽 칸에 표시 + @Presents var detail: TodoDetailFeature.State? var todos = [TodayTodoItem]() var completedTodayTodos = [TodayTodoItem]() var categories = [TodoCategoryItem]() @@ -40,15 +42,14 @@ extension TodayFeature { var selectedCategoryID: String? var isCategoryFilterPresented = false var isTodoInspectorPresented = false + // 세부 정보 사이드바에 표시하는 Todo, 오른쪽 칸을 열면 칸의 Todo와 같음 var selectedTodoId: String? - // 오른쪽 칸 상세가 모르는 곳에서 고른 Todo가 바뀌면 올려 상세를 다시 만듦 - var detailPaneRevision = 0 - // 사이드바가 있는 창에서 사이드바까지 덮는 상세 판에 연 Todo - var panelTodo: TodoIdItem? + // 세부 정보 사이드바에 Todo를 보여 달라고 한 횟수, 바뀌면 닫힌 세부 정보 사이드바를 엶 + var revealCount = 0 // Mac에서 마우스를 올린 행, 선택 행처럼 둥글게 표시하고 맞닿는 구분선을 숨김 var hoveredTodoId: String? - // 사이드바가 있는 창에서 목록 오른쪽 칸을 연 상태, 세부 정보 사이드바만 쓰는 선택과 구분 - var isDetailPanePresented = false + // 사이드바가 있는 창에서 상세 판 대신 목록 오른쪽 칸에 표시, 세부 정보 사이드바만 쓰는 선택과 구분 + var showsDetailInPane = false // 좁은 창 세부 정보 시트의 속성 // 시트를 닫아도 저장 결과를 받도록 시트 밖에서 소유 var todoInfo: TodoDetailSideBarFeature.State? diff --git a/Application/Presentation/TodayTab/Sources/TodayFeature.swift b/Application/Presentation/TodayTab/Sources/TodayFeature.swift index 88199d166..bcfe25378 100644 --- a/Application/Presentation/TodayTab/Sources/TodayFeature.swift +++ b/Application/Presentation/TodayTab/Sources/TodayFeature.swift @@ -42,7 +42,13 @@ struct TodayFeature { enum Action: BindableAction, Equatable { case alert(PresentationAction) + case detail(PresentationAction) case binding(BindingAction) + // 사이드바가 있는 창은 연 곳(상세 판이나 오른쪽 칸)의 내용을 바꿈 + case selectTodo(String) + // 사이드바가 있는 창에서 오른쪽 칸을 열었으면 칸의 Todo도 바꿈 + case inspectTodo(String) + case moveDetailToPane case refresh case fetchData case checkCurrentDate(Date) @@ -90,8 +96,30 @@ struct TodayFeature { switch action { case .alert: break + case .detail(.dismiss): + state.showsDetailInPane = false + case .detail: + break case .binding: break + case .selectTodo(let todoId): + if state.showsDetailInPane { + state.selectedTodoId = todoId + } + // 이미 연 Todo는 불러온 상세와 열어 둔 시트를 그대로 둠 + if state.detail?.todoId != todoId { + state.detail = TodoDetailFeature.State(todoId: todoId, showEditButton: true) + } + case .inspectTodo(let todoId): + state.revealCount += 1 + state.selectedTodoId = todoId + if state.showsDetailInPane && state.detail?.todoId != todoId { + state.detail = TodoDetailFeature.State(todoId: todoId, showEditButton: true) + } + case .moveDetailToPane: + guard let todoId = state.detail?.todoId else { break } + state.selectedTodoId = todoId + state.showsDetailInPane = true case .refresh: let interval = prepareTodayInterval(state: &state, now: now) return .concatenate( @@ -130,6 +158,7 @@ struct TodayFeature { case .dismissTodoInspector: state.isTodoInspectorPresented = false case .moveTodoInspectorToSideBar: + state.revealCount += 1 guard state.isTodoInspectorPresented, let info = state.todoInfo else { break } // 고친 값은 이미 저장해 시트만 닫고 같은 Todo를 세부 정보 사이드바에 표시 state.isTodoInspectorPresented = false @@ -165,18 +194,18 @@ struct TodayFeature { state.alert = Self.alertState() case .store(.setTodos(let incomplete, let completedToday, let interval)): guard state.todayInterval == interval else { break } - let selectedItem = state.selectedTodoId.flatMap { latestItem(id: $0, state: state) } + let detailItem = state.detail.flatMap { latestItem(id: $0.todoId, state: state) } state.todos = incomplete state.isIncompleteDataLoaded = true state.completedTodayTodos = completedToday state.isCompletedTodayDataLoaded = true - reloadDetailPaneIfChanged(from: selectedItem, state: &state) + return reloadDetailIfChanged(from: detailItem, state: state) case .store(.setCompletedTodayTodos(let todos, let interval)): guard state.todayInterval == interval else { break } - let selectedItem = state.selectedTodoId.flatMap { latestItem(id: $0, state: state) } + let detailItem = state.detail.flatMap { latestItem(id: $0.todoId, state: state) } state.completedTodayTodos = todos state.isCompletedTodayDataLoaded = true - reloadDetailPaneIfChanged(from: selectedItem, state: &state) + return reloadDetailIfChanged(from: detailItem, state: state) case .store(.setCategories(let categories)): state.categories = categories let visibleCategoryIDs = Set(state.visibleCategories.map(\.id)) @@ -185,11 +214,11 @@ struct TodayFeature { state.selectedCategoryID = nil } case .store(.updateTodo(let item)): - // 인스펙터나 완료 버튼으로 바꾼 Todo는 오른쪽 칸 상세도 다시 만듦 - if item.id == state.selectedTodoId { - state.detailPaneRevision += 1 - } update(item, state: &state) + // 인스펙터나 완료 버튼으로 바꾼 Todo는 연 상세도 다시 조회 + if item.id == state.detail?.todoId { + return .send(.detail(.presented(.fetch))) + } case .store(.removeTodo(let todoId)): state.todos.removeAll { $0.id == todoId } state.completedTodayTodos.removeAll { $0.id == todoId } @@ -203,6 +232,9 @@ struct TodayFeature { .ifLet(\.todoInfo, action: \.todoInfo) { TodoDetailSideBarFeature() } + .ifLet(\.$detail, action: \.detail) { + TodoDetailFeature() + } } } @@ -251,11 +283,11 @@ private extension TodayFeature { } } - // 다시 불러온 목록에서 고른 Todo가 바뀌었으면 오른쪽 칸 상세도 다시 만듦 - func reloadDetailPaneIfChanged(from selectedItem: TodayTodoItem?, state: inout State) { - guard let selectedItem, - latestItem(id: selectedItem.id, state: state)?.updatedAt != selectedItem.updatedAt else { return } - state.detailPaneRevision += 1 + // 다시 불러온 목록에서 연 Todo가 바뀌었으면 상세도 다시 조회 + func reloadDetailIfChanged(from detailItem: TodayTodoItem?, state: State) -> Effect { + guard let detailItem, + latestItem(id: detailItem.id, state: state)?.updatedAt != detailItem.updatedAt else { return .none } + return .send(.detail(.presented(.fetch))) } func prepareTodayInterval(state: inout State, now: Date) -> DateInterval { diff --git a/Application/Presentation/TodayTab/Sources/TodayRoute.swift b/Application/Presentation/TodayTab/Sources/TodayRoute.swift deleted file mode 100644 index c031d73af..000000000 --- a/Application/Presentation/TodayTab/Sources/TodayRoute.swift +++ /dev/null @@ -1,12 +0,0 @@ -// -// TodayRoute.swift -// TodayTab -// -// Created by opfic on 7/5/26. -// - -import PresentationShared - -public enum TodayRoute: Hashable { - case todo(TodoIdItem) -} diff --git a/Application/Presentation/TodayTab/Sources/TodayView.swift b/Application/Presentation/TodayTab/Sources/TodayView.swift index 492d520c2..f71db1731 100644 --- a/Application/Presentation/TodayTab/Sources/TodayView.swift +++ b/Application/Presentation/TodayTab/Sources/TodayView.swift @@ -18,8 +18,6 @@ public struct TodayView: View { @Environment(\.usesPaneLayout) private var usesPaneLayout @Environment(\.windowControlsInset) private var windowControlsInset @Environment(\.readableContentWidth) private var readableContentWidth - @Environment(\.setDetailSideBarPresented) private var setDetailSideBarPresented - @State private var router = NavigationRouter() @State private var store: StoreOf private let isSelected: Bool private let windowEvent: TodoEditorWindowEvent @@ -38,17 +36,17 @@ public struct TodayView: View { } public var body: some View { - NavigationStack(path: $router.path) { + NavigationStack { let sections = store.sections // 사이드바가 있는 창은 목록을 창 전체 폭으로 두고 오른쪽 칸을 열었고 그 Todo가 목록에 있을 때만 두 칸으로 나눔 - let showsPane = store.isDetailPanePresented - && sections.flatMap(\.items).contains { $0.id == store.selectedTodoId } + let showsPane = store.showsDetailInPane + && sections.flatMap(\.items).contains { $0.id == store.detail?.todoId } - PaneSplitView(splitsOnDesktop: showsPane) { + PaneSplitView { ScrollView { // 칸으로 나누지 않은 화면은 상세 칸이 없어 선택 표시 생략 let highlightedTodoIds = ( - [store.hoveredTodoId] + (usesPaneLayout ? [store.selectedTodoId, store.panelTodo?.id] : []) + [store.hoveredTodoId] + (usesPaneLayout ? [store.selectedTodoId, store.detail?.todoId] : []) ).compactMap { $0 } LazyVStack(alignment: .leading, spacing: 0) { @@ -69,20 +67,12 @@ public struct TodayView: View { isNavigationEnabled: !store.isTodoInspectorPresented, highlightedTodoIds: highlightedTodoIds, onSelect: { item in - // 사이드바가 있는 창은 오른쪽 칸을 열지 않았으면 상세 판으로 열고 열었으면 오른쪽 칸 내용을 바꿈 - if usesDesktopLayout && !showsPane { - store.send(.binding(.set(\.panelTodo, TodoIdItem(id: item.id)))) - } else if usesPaneLayout { - store.send(.binding(.set(\.selectedTodoId, item.id))) - } else { - router.push(.todo(TodoIdItem(id: item.id))) - } + store.send(.selectTodo(item.id)) }, onInspect: { item in // 사이드바가 있으면 고른 Todo를 창 오른쪽 세부 정보 사이드바에 표시 if usesDesktopLayout { - store.send(.binding(.set(\.selectedTodoId, item.id))) - setDetailSideBarPresented?(true) + store.send(.inspectTodo(item.id)) } else { store.send(.showTodoInspector(item)) } @@ -134,62 +124,50 @@ public struct TodayView: View { .background(Color.background) .refreshable { await store.send(.refresh).finish() } .duoToolbarVisibility() - } detail: { - let item = sections.flatMap(\.items).first { $0.id == store.selectedTodoId } - // 목록에서 빠진 Todo는 선택 안내로 대체 - TodoDetailPane( - todoId: item?.id, - showEditButton: true, - windowEvent: windowEvent, - onClose: usesDesktopLayout ? { store.send(.binding(.set(\.isDetailPanePresented, false))) } : nil - ) - // 인스펙터 등에서 목록 행이 바뀌면 상세 칸도 다시 조회 - .id(store.detailPaneRevision) + // 좁은 창은 목록 위에 쌓고, 사이드바가 있는 창은 상세 판이나 오른쪽 칸에 표시 + // 목록에서 빠진 Todo는 오른쪽 칸에 그리지 않음 + // 창 폭이 바뀌면 같은 상세 상태를 바뀐 자리에서 이어 그림 + .compositionDetail( + item: $store.scope(state: \.detail, action: \.detail), + inPane: showsPane, + isActive: isSelected + ) { detailStore, onClose in + TodoDetailView( + store: detailStore, + windowEvent: windowEvent, + isPaneDetail: onClose != nil, + onClose: onClose + ) + // 칸 안에서 다른 Todo로 바꾸면 그 Todo를 조회 + .id(detailStore.todoId) + } panel: { detailStore in + // 목록에서 빠진 Todo는 오른쪽 칸에 그릴 수 없어 판 메뉴에서 오른쪽 칸으로 옮기기 생략 + let isListed = sections.flatMap(\.items).contains { $0.id == detailStore.todoId } + + TodoDetailPanel( + store: detailStore, + location: Text("nav_today", bundle: PresentationResources.bundle), + windowEvent: windowEvent, + onMoveToPane: isListed ? { store.send(.moveDetailToPane) } : nil + ) + } } - // 좁은 창으로 바뀌면 상세 판을 숨기고 넓어지면 다시 표시 - .detailPanel(item: $store.panelTodo.activePresentation(when: isSelected && usesDesktopLayout)) { item in - // 목록에서 빠진 Todo는 오른쪽 칸에 그릴 수 없어 판 메뉴에서 오른쪽 칸으로 옮기기 생략 - let isListed = sections.flatMap(\.items).contains { $0.id == item.id } - - TodoDetailPanel( - todoId: item.id, - location: Text("nav_today", bundle: PresentationResources.bundle), - isEditable: true, - windowEvent: windowEvent, - onMoveToPane: isListed ? { - store.send(.binding(.set(\.panelTodo, nil))) - store.send(.binding(.set(\.selectedTodoId, item.id))) - store.send(.binding(.set(\.isDetailPanePresented, true))) - } : nil - ) + .compositionRight( + isActive: sections.flatMap(\.items).contains { $0.id == store.selectedTodoId }, + reveal: store.revealCount + ) { + if let todoId = store.selectedTodoId { + TodoDetailSideBarView(todoId: todoId, isEditable: true, windowEvent: windowEvent) + .id(todoId) + } } - .detailSideBarTarget( - sections.flatMap(\.items) - .first { $0.id == store.selectedTodoId } - .map { .todo(id: $0.id, isEditable: true) } - ) - .navigationDestination( - for: TodayRoute.self, - interactivePop: { _ in true }, - destination: { destination($0).environment(\.showsPaneTitleBar, usesPaneLayout) } - ) } .desktopNavigationTransition() // 오른쪽 칸에 연 Todo가 목록에서 빠지면 닫기 버튼 없는 선택 안내 대신 오른쪽 칸을 닫음 - // 좁은 창에서 빠져도 닫아 넓어진 뒤 다른 Todo의 세부 정보만 바꿀 때 오른쪽 칸이 열리지 않게 함 - .onChange(of: store.sections.flatMap(\.items).contains { $0.id == store.selectedTodoId }) { _, isListed in - if store.isDetailPanePresented && !isListed { - store.send(.binding(.set(\.isDetailPanePresented, false))) - } - } - // 사이드바 구조로 바뀌면 쌓아 연 상세 화면은 내리고 같은 Todo를 옆 칸에 표시 - .closesPushedDetail { - guard case .todo(let item)? = router.path.last else { return } - // 목록에서 빠진 Todo는 오른쪽 칸에 그릴 수 없어 오른쪽 칸을 열지 않음 - let isListed = store.sections.flatMap(\.items).contains { $0.id == item.id } - store.send(.binding(.set(\.selectedTodoId, item.id))) - store.send(.binding(.set(\.isDetailPanePresented, isListed))) - router.path = [] + // 좁은 창은 쌓아 연 상세를 그대로 두고, 넓어지면 오른쪽 칸 대신 상세 판으로 표시 + .onChange(of: store.sections.flatMap(\.items).contains { $0.id == store.detail?.todoId }) { _, isListed in + guard store.showsDetailInPane && !isListed else { return } + store.send(usesDesktopLayout ? .detail(.dismiss) : .binding(.set(\.showsDetailInPane, false))) } // 사이드바가 있으면 창 오른쪽 세부 정보 사이드바, 좁은 화면과 Duo 펼침은 직접 그린 시트로 표시 .prominentSheet( @@ -204,7 +182,6 @@ public struct TodayView: View { .onChange(of: usesDesktopLayout) { _, usesDesktopLayout in if usesDesktopLayout && store.isTodoInspectorPresented { store.send(.moveTodoInspectorToSideBar) - setDetailSideBarPresented?(true) } } // 상단 safe area 배경 @@ -237,21 +214,6 @@ public struct TodayView: View { } } - private func destination(_ route: TodayRoute) -> some View { - switch route { - case .todo(let item): - TodoDetailView( - store: Store( - initialState: TodoDetailFeature.State(todoId: item.id, showEditButton: true) - ) { - TodoDetailFeature() - }, - windowEvent: windowEvent - ) - .id(item.id) - } - } - private func monitorDateChanges() async { while !Task.isCancelled { let date = Date() diff --git a/Application/Presentation/TodayTab/Tests/TodayFeatureTestAssertions.swift b/Application/Presentation/TodayTab/Tests/TodayFeatureTestAssertions.swift index f6c03727e..c185b0c4a 100644 --- a/Application/Presentation/TodayTab/Tests/TodayFeatureTestAssertions.swift +++ b/Application/Presentation/TodayTab/Tests/TodayFeatureTestAssertions.swift @@ -11,7 +11,7 @@ import Domain @testable import TodayTab @MainActor -private func waitUntilTodayMainActor( +func waitUntilTodayMainActor( timeout: Duration = .seconds(1), pollInterval: Duration = .milliseconds(20), _ condition: @escaping @MainActor () -> Bool diff --git a/Application/Presentation/TodayTab/Tests/TodayFeatureTestDoubles.swift b/Application/Presentation/TodayTab/Tests/TodayFeatureTestDoubles.swift index d861888be..cfb9e6167 100644 --- a/Application/Presentation/TodayTab/Tests/TodayFeatureTestDoubles.swift +++ b/Application/Presentation/TodayTab/Tests/TodayFeatureTestDoubles.swift @@ -78,7 +78,8 @@ struct TodayStoreTestAdapter: TodayStateDriving { var isTodoInspectorPresented: Bool { store.state.isTodoInspectorPresented } var todoInfoTitle: String? { store.state.todoInfo?.editor?.title } var selectedTodoId: String? { store.state.selectedTodoId } - var detailPaneRevision: Int { store.state.detailPaneRevision } + var detailTodoId: String? { store.state.detail?.todoId } + var showsDetailInPane: Bool { store.state.showsDetailInPane } var visibleCategoryIDs: [String] { store.state.visibleCategories.map(\.id) } var showAlert: Bool { store.state.alert != nil } var isLoading: Bool { store.state.isLoading } @@ -109,6 +110,7 @@ struct TodayStoreTestAdapter: TodayStateDriving { $0.fetchTodoByIdUseCase = fetchTodoByIdUseCase $0.upsertTodoUseCase = upsertUseCase $0.trackAnalyticsEventUseCase = trackAnalyticsEventUseCase + $0.fetchReferenceItemsUseCase = TodayFetchReferenceItemsUseCaseStub() $0.date.now = now $0.continuousClock = ContinuousClock() configureDependencies?(&$0) @@ -149,6 +151,22 @@ struct TodayStoreTestAdapter: TodayStateDriving { await store.send(.store(.updateTodo(item))) } + func openTodo(_ id: String) async { + await store.send(.selectTodo(id)) + } + + func inspectTodo(_ id: String) async { + await store.send(.inspectTodo(id)) + } + + func moveDetailToPane() async { + await store.send(.moveDetailToPane) + } + + func dismissDetail() async { + await store.send(.detail(.dismiss)) + } + func receiveDetailTodo(_ item: TodayTodoItem) async { await store.send(.detailTodoUpdated(item)) } diff --git a/Application/Presentation/TodayTab/Tests/TodayFeatureTestSpies.swift b/Application/Presentation/TodayTab/Tests/TodayFeatureTestSpies.swift index d434f05a7..fe4db4215 100644 --- a/Application/Presentation/TodayTab/Tests/TodayFeatureTestSpies.swift +++ b/Application/Presentation/TodayTab/Tests/TodayFeatureTestSpies.swift @@ -68,6 +68,12 @@ private actor FetchTodosUseCaseCallRecorder { } } +final class TodayFetchReferenceItemsUseCaseStub: FetchReferenceItemsUseCase { + func execute(_ numbers: [Int]) async throws -> [Int: TodoReference] { + [:] + } +} + final class TodayFetchTodoByIdUseCaseSpy: FetchTodoByIdUseCase { var todos: [Todo] var error: Error? diff --git a/Application/Presentation/TodayTab/Tests/TodayFeatureTests.swift b/Application/Presentation/TodayTab/Tests/TodayFeatureTests.swift index 72397c42c..a736c5453 100644 --- a/Application/Presentation/TodayTab/Tests/TodayFeatureTests.swift +++ b/Application/Presentation/TodayTab/Tests/TodayFeatureTests.swift @@ -109,25 +109,53 @@ struct TodayFeatureTests { #expect(adapter.showAlert) } - @Test("상세 칸이 저장해 보낸 Todo는 목록 행만 바꾸고 상세 칸은 다시 만들지 않는다") - func 상세_칸이_저장해_보낸_Todo는_목록_행만_바꾸고_상세_칸은_다시_만들지_않는다() async throws { + @Test("상세가 저장해 보낸 Todo는 목록 행만 바꾸고 상세는 다시 조회하지 않는다") + func 상세가_저장해_보낸_Todo는_목록_행만_바꾸고_상세는_다시_조회하지_않는다() async throws { var todo = makeTodayTodo(id: "detail", title: "수정 전") - let adapter = TodayStoreTestAdapter() + let fetchByIdSpy = TodayFetchTodoByIdUseCaseSpy(todos: [todo]) + let adapter = TodayStoreTestAdapter(fetchTodoByIdUseCase: fetchByIdSpy) await adapter.receiveUpdatedTodo(try #require(TodayTodoItem(from: todo))) - await adapter.selectTodo("detail") - let revision = adapter.detailPaneRevision + await adapter.openTodo("detail") todo.title = "상세에서 수정" await adapter.receiveDetailTodo(try #require(TodayTodoItem(from: todo))) #expect(adapter.todos.first?.title == "상세에서 수정") - #expect(adapter.detailPaneRevision == revision) + #expect(fetchByIdSpy.todoIds.isEmpty) todo.title = "목록에서 수정" await adapter.receiveUpdatedTodo(try #require(TodayTodoItem(from: todo))) + await waitUntilTodayMainActor { + !fetchByIdSpy.todoIds.isEmpty + } + #expect(adapter.todos.first?.title == "목록에서 수정") - #expect(adapter.detailPaneRevision == revision + 1) + #expect(fetchByIdSpy.todoIds == ["detail"]) + } + + @Test("오른쪽 칸을 연 동안만 세부 정보로 고른 Todo가 칸의 Todo도 바꾼다") + func 오른쪽_칸을_연_동안만_세부_정보로_고른_Todo가_칸의_Todo도_바꾼다() async { + let adapter = TodayStoreTestAdapter() + + await adapter.openTodo("panel") + await adapter.inspectTodo("inspected") + + #expect(adapter.detailTodoId == "panel") + #expect(adapter.selectedTodoId == "inspected") + + await adapter.moveDetailToPane() + await adapter.inspectTodo("next") + + #expect(adapter.showsDetailInPane) + #expect(adapter.detailTodoId == "next") + #expect(adapter.selectedTodoId == "next") + + await adapter.dismissDetail() + + #expect(adapter.detailTodoId == nil) + #expect(!adapter.showsDetailInPane) + #expect(adapter.selectedTodoId == "next") } @Test("넓은 창으로 바뀌면 세부 정보 시트를 저장 없이 닫고 같은 Todo를 고른다")