diff --git a/Application/App/Sources/App/Dependency/AppGraph+PresentationDependencies.swift b/Application/App/Sources/App/Dependency/AppGraph+PresentationDependencies.swift index f4481bfbf..325a5733c 100644 --- a/Application/App/Sources/App/Dependency/AppGraph+PresentationDependencies.swift +++ b/Application/App/Sources/App/Dependency/AppGraph+PresentationDependencies.swift @@ -31,6 +31,9 @@ private extension AppGraph { fetchGoalUseCase: developmentGraphSet .developmentGoalUseCaseGraph .fetchDevelopmentGoalUseCase, + updateGoalUseCase: developmentGraphSet + .developmentGoalUseCaseGraph + .updateDevelopmentGoalUseCase, updateGoalStatusUseCase: developmentGraphSet .developmentGoalUseCaseGraph .updateDevelopmentGoalStatusUseCase diff --git a/Application/Data/Sources/DTO/DevelopmentGoalDTO.swift b/Application/Data/Sources/DTO/DevelopmentGoalDTO.swift index 58fe2311d..9af06b3e7 100644 --- a/Application/Data/Sources/DTO/DevelopmentGoalDTO.swift +++ b/Application/Data/Sources/DTO/DevelopmentGoalDTO.swift @@ -17,6 +17,16 @@ public struct DevelopmentGoalCreateRequest: Encodable { } } +public struct DevelopmentGoalUpdateRequest: Encodable { + public let title: String + public let markdownDescription: String + + public init(title: String, markdownDescription: String) { + self.title = title + self.markdownDescription = markdownDescription + } +} + public struct DevelopmentGoalStatusRequest { public let status: DevelopmentGoalStatus diff --git a/Application/Data/Sources/Protocol/DevelopmentGoalService.swift b/Application/Data/Sources/Protocol/DevelopmentGoalService.swift index 5669b3388..7ce4b39f4 100644 --- a/Application/Data/Sources/Protocol/DevelopmentGoalService.swift +++ b/Application/Data/Sources/Protocol/DevelopmentGoalService.swift @@ -10,6 +10,10 @@ public protocol DevelopmentGoalService { goalId: String, request: DevelopmentGoalCreateRequest ) async throws -> DevelopmentGoalResponse + func updateGoal( + goalId: String, + request: DevelopmentGoalUpdateRequest + ) async throws -> DevelopmentGoalResponse func fetchGoal(goalId: String) async throws -> DevelopmentGoalResponse func fetchGoals(_ query: DevelopmentGoalQuery) async throws -> [DevelopmentGoalResponse] func fetchCompletionSnapshot( diff --git a/Application/Data/Sources/Repository/DevelopmentGoalRepositoryImpl.swift b/Application/Data/Sources/Repository/DevelopmentGoalRepositoryImpl.swift index 2f7ad3eb2..d603bcbf1 100644 --- a/Application/Data/Sources/Repository/DevelopmentGoalRepositoryImpl.swift +++ b/Application/Data/Sources/Repository/DevelopmentGoalRepositoryImpl.swift @@ -30,6 +30,22 @@ final class DevelopmentGoalRepositoryImpl: DevelopmentGoalRepository { } } + func updateGoal( + _ goalId: String, + title: String, + description: String + ) async throws -> DevelopmentGoal { + do { + let response = try await service.updateGoal( + goalId: goalId, + request: .init(title: title, markdownDescription: description) + ) + return try response.toDomain() + } catch { + throw error.toDomain() + } + } + func fetchGoal(_ goalId: String) async throws -> DevelopmentGoal { do { return try await service.fetchGoal(goalId: goalId).toDomain() diff --git a/Application/Data/Tests/Repository/DevelopmentGoalRepositoryImplTests.swift b/Application/Data/Tests/Repository/DevelopmentGoalRepositoryImplTests.swift index b39d8d880..6a9254aee 100644 --- a/Application/Data/Tests/Repository/DevelopmentGoalRepositoryImplTests.swift +++ b/Application/Data/Tests/Repository/DevelopmentGoalRepositoryImplTests.swift @@ -28,6 +28,24 @@ struct DevelopmentGoalRepositoryImplTests { #expect(request.markdownDescription == "설명") } + @Test("목표 수정은 제목과 markdownDescription 요청을 서비스에 전달한다") + func 목표_수정은_제목과_markdownDescription_요청을_서비스에_전달한다() async throws { + let service = DevelopmentGoalServiceSpy() + let repository = DevelopmentGoalRepositoryImpl(service: service) + + let goal = try await repository.updateGoal( + "goal-1", + title: "바꾼 목표", + description: "바꾼 설명" + ) + + let request = try #require(await service.updateRequest()) + #expect(goal.id == "goal-1") + #expect(request.goalId == "goal-1") + #expect(request.title == "바꾼 목표") + #expect(request.markdownDescription == "바꾼 설명") + } + @Test("완료 검증 문맥은 목표 서비스 응답만으로 복원한다") func 완료_검증_문맥은_목표_서비스_응답만으로_복원한다() async throws { let service = DevelopmentGoalServiceSpy() @@ -79,6 +97,12 @@ private actor DevelopmentGoalServiceSpy: DevelopmentGoalService { let markdownDescription: String } + struct UpdateRequest { + let goalId: String + let title: String + let markdownDescription: String + } + struct TransitionRequest { let goalId: String let status: DevelopmentGoalStatus @@ -101,6 +125,7 @@ private actor DevelopmentGoalServiceSpy: DevelopmentGoalService { createdAt: .distantPast ) private var recordedCreateRequest: CreateRequest? + private var recordedUpdateRequest: UpdateRequest? private var recordedCompletionSnapshotGoalIds = [String]() private var recordedTransitionRequest: TransitionRequest? @@ -115,6 +140,18 @@ private actor DevelopmentGoalServiceSpy: DevelopmentGoalService { return goal } + func updateGoal( + goalId: String, + request: DevelopmentGoalUpdateRequest + ) async throws -> DevelopmentGoalResponse { + recordedUpdateRequest = .init( + goalId: goalId, + title: request.title, + markdownDescription: request.markdownDescription + ) + return goal + } + func fetchGoal(goalId: String) async throws -> DevelopmentGoalResponse { goal } @@ -141,6 +178,10 @@ private actor DevelopmentGoalServiceSpy: DevelopmentGoalService { recordedCreateRequest } + func updateRequest() -> UpdateRequest? { + recordedUpdateRequest + } + func completionSnapshotGoalIds() -> [String] { recordedCompletionSnapshotGoalIds } diff --git a/Application/Domain/Sources/Graph/DevelopmentGoalUseCaseGraph.swift b/Application/Domain/Sources/Graph/DevelopmentGoalUseCaseGraph.swift index c534ac378..c507e5ed8 100644 --- a/Application/Domain/Sources/Graph/DevelopmentGoalUseCaseGraph.swift +++ b/Application/Domain/Sources/Graph/DevelopmentGoalUseCaseGraph.swift @@ -32,6 +32,11 @@ public final class DevelopmentGoalUseCaseGraph { FetchDevelopmentGoalsUseCaseImpl(input.repository) } + @Provide + private func makeUpdateDevelopmentGoalUseCase() -> UpdateDevelopmentGoalUseCase { + UpdateDevelopmentGoalUseCaseImpl(input.repository) + } + @Provide private func makeUpdateDevelopmentGoalStatusUseCase() -> UpdateDevelopmentGoalStatusUseCase { UpdateDevelopmentGoalStatusUseCaseImpl(input.repository) diff --git a/Application/Domain/Sources/Protocol/DevelopmentGoalRepository.swift b/Application/Domain/Sources/Protocol/DevelopmentGoalRepository.swift index 34cef57fa..ddb7d4cff 100644 --- a/Application/Domain/Sources/Protocol/DevelopmentGoalRepository.swift +++ b/Application/Domain/Sources/Protocol/DevelopmentGoalRepository.swift @@ -11,6 +11,11 @@ public protocol DevelopmentGoalRepository { title: String, description: String ) async throws -> DevelopmentGoal + func updateGoal( + _ goalId: String, + title: String, + description: String + ) async throws -> DevelopmentGoal func fetchGoal(_ goalId: String) async throws -> DevelopmentGoal func fetchGoals(_ query: DevelopmentGoal.Query) async throws -> [DevelopmentGoal] func fetchCompletionSnapshot(for goalId: String) async throws -> DevelopmentGoal.CompletionSnapshot diff --git a/Application/Domain/Sources/UseCase/DevelopmentGoal/Update/UpdateDevelopmentGoalUseCase.swift b/Application/Domain/Sources/UseCase/DevelopmentGoal/Update/UpdateDevelopmentGoalUseCase.swift new file mode 100644 index 000000000..4bacf3340 --- /dev/null +++ b/Application/Domain/Sources/UseCase/DevelopmentGoal/Update/UpdateDevelopmentGoalUseCase.swift @@ -0,0 +1,10 @@ +// +// UpdateDevelopmentGoalUseCase.swift +// Domain +// +// Created by opfic on 11/23/26. +// + +public protocol UpdateDevelopmentGoalUseCase { + func execute(_ goalId: String, title: String, description: String) async throws -> DevelopmentGoal +} diff --git a/Application/Domain/Sources/UseCase/DevelopmentGoal/Update/UpdateDevelopmentGoalUseCaseImpl.swift b/Application/Domain/Sources/UseCase/DevelopmentGoal/Update/UpdateDevelopmentGoalUseCaseImpl.swift new file mode 100644 index 000000000..9b59d0668 --- /dev/null +++ b/Application/Domain/Sources/UseCase/DevelopmentGoal/Update/UpdateDevelopmentGoalUseCaseImpl.swift @@ -0,0 +1,18 @@ +// +// UpdateDevelopmentGoalUseCaseImpl.swift +// Domain +// +// Created by opfic on 11/23/26. +// + +public final class UpdateDevelopmentGoalUseCaseImpl: UpdateDevelopmentGoalUseCase { + private let repository: DevelopmentGoalRepository + + init(_ repository: DevelopmentGoalRepository) { + self.repository = repository + } + + public func execute(_ goalId: String, title: String, description: String) async throws -> DevelopmentGoal { + try await repository.updateGoal(goalId, title: title, description: description) + } +} diff --git a/Application/Domain/Tests/UseCase/DevelopmentGoal/DevelopmentGoalUseCaseTests.swift b/Application/Domain/Tests/UseCase/DevelopmentGoal/DevelopmentGoalUseCaseTests.swift index 1d433888b..e287bf6cc 100644 --- a/Application/Domain/Tests/UseCase/DevelopmentGoal/DevelopmentGoalUseCaseTests.swift +++ b/Application/Domain/Tests/UseCase/DevelopmentGoal/DevelopmentGoalUseCaseTests.swift @@ -184,6 +184,14 @@ private actor DevelopmentGoalRepositorySpy: DevelopmentGoalRepository { return goal } + func updateGoal( + _ goalId: String, + title: String, + description: String + ) async throws -> DevelopmentGoal { + goal + } + func fetchGoal(_ goalId: String) async throws -> DevelopmentGoal { recordedFetchedGoalIds.append(goalId) return goal diff --git a/Application/Domain/Tests/UseCase/DevelopmentRecord/DevelopmentRecordUseCaseTestSupport.swift b/Application/Domain/Tests/UseCase/DevelopmentRecord/DevelopmentRecordUseCaseTestSupport.swift index f2f56d32a..7c2d13d4c 100644 --- a/Application/Domain/Tests/UseCase/DevelopmentRecord/DevelopmentRecordUseCaseTestSupport.swift +++ b/Application/Domain/Tests/UseCase/DevelopmentRecord/DevelopmentRecordUseCaseTestSupport.swift @@ -24,6 +24,14 @@ actor DevelopmentRecordGoalRepositorySpy: DevelopmentGoalRepository { goal } + func updateGoal( + _ goalId: String, + title: String, + description: String + ) async throws -> DevelopmentGoal { + goal + } + func fetchGoal(_ goalId: String) async throws -> DevelopmentGoal { goal } diff --git a/Application/Domain/Tests/UseCase/Todo/UpdateTodoGoalUseCaseImplTests.swift b/Application/Domain/Tests/UseCase/Todo/UpdateTodoGoalUseCaseImplTests.swift index 47ce1194a..bcc3a9a51 100644 --- a/Application/Domain/Tests/UseCase/Todo/UpdateTodoGoalUseCaseImplTests.swift +++ b/Application/Domain/Tests/UseCase/Todo/UpdateTodoGoalUseCaseImplTests.swift @@ -120,6 +120,14 @@ private actor DevelopmentGoalRepositorySpy: DevelopmentGoalRepository { try result.get() } + func updateGoal( + _ goalId: String, + title: String, + description: String + ) async throws -> DevelopmentGoal { + try result.get() + } + func fetchGoal(_ goalId: String) async throws -> DevelopmentGoal { recordedFetchedGoalIds.append(goalId) return try result.get() diff --git a/Application/Infra/Sources/Service/DevelopmentGoalServiceImpl.swift b/Application/Infra/Sources/Service/DevelopmentGoalServiceImpl.swift index 5dcf8f012..a9f684a61 100644 --- a/Application/Infra/Sources/Service/DevelopmentGoalServiceImpl.swift +++ b/Application/Infra/Sources/Service/DevelopmentGoalServiceImpl.swift @@ -20,6 +20,7 @@ final class DevelopmentGoalServiceImpl: DevelopmentGoalService { case fetchGoals case fetchCompletionSnapshot case transitionGoalStatus + case updateGoal } } @@ -50,6 +51,26 @@ final class DevelopmentGoalServiceImpl: DevelopmentGoalService { } } + func updateGoal( + goalId: String, + request: DevelopmentGoalUpdateRequest + ) async throws -> DevelopmentGoalResponse { + guard let uid = Auth.auth().currentUser?.uid else { throw DataLayerError.notAuthenticated } + + do { + try Self.validateTitle(request.title) + let reference = store.document(FirestorePath.developmentGoal(uid, goalId: goalId)) + var data = try encoder.encode(request) + data[DevelopmentGoalFieldKey.updatedAt.rawValue] = FieldValue.serverTimestamp() + try await reference.updateData(data) + return try await fetchGoal(uid: uid, goalId: goalId) + } catch { + logger.error("Failed to update development goal", error: error) + record(error, code: .updateGoal) + throw error + } + } + func fetchGoal(goalId: String) async throws -> DevelopmentGoalResponse { guard let uid = Auth.auth().currentUser?.uid else { throw DataLayerError.notAuthenticated } diff --git a/Application/Presentation/HomeTab/Sources/Dependency/DevelopmentDependencyPreparation.swift b/Application/Presentation/HomeTab/Sources/Dependency/DevelopmentDependencyPreparation.swift index 95c758c7c..9edcabb50 100644 --- a/Application/Presentation/HomeTab/Sources/Dependency/DevelopmentDependencyPreparation.swift +++ b/Application/Presentation/HomeTab/Sources/Dependency/DevelopmentDependencyPreparation.swift @@ -13,10 +13,12 @@ public enum DevelopmentDependencyPreparation { _ dependencies: inout DependencyValues, createGoalUseCase: CreateDevelopmentGoalUseCase, fetchGoalUseCase: FetchDevelopmentGoalUseCase, + updateGoalUseCase: UpdateDevelopmentGoalUseCase, updateGoalStatusUseCase: UpdateDevelopmentGoalStatusUseCase ) { dependencies.developmentCreateGoalUseCase = createGoalUseCase dependencies.developmentFetchGoalUseCase = fetchGoalUseCase + dependencies.developmentUpdateGoalUseCase = updateGoalUseCase dependencies.developmentUpdateGoalStatusUseCase = updateGoalStatusUseCase } @@ -70,6 +72,11 @@ extension DependencyValues { set { self[FetchRecordsUseCaseKey.self] = newValue } } + var developmentUpdateGoalUseCase: UpdateDevelopmentGoalUseCase { + get { self[UpdateGoalUseCaseKey.self] } + set { self[UpdateGoalUseCaseKey.self] = newValue } + } + var developmentUpdateGoalStatusUseCase: UpdateDevelopmentGoalStatusUseCase { get { self[UpdateGoalStatusUseCaseKey.self] } set { self[UpdateGoalStatusUseCaseKey.self] = newValue } @@ -134,6 +141,12 @@ private enum FetchRecordsUseCaseKey: DependencyKey { } } +private enum UpdateGoalUseCaseKey: DependencyKey { + static var liveValue: UpdateDevelopmentGoalUseCase { + preconditionFailure("UpdateDevelopmentGoalUseCase must be provided.") + } +} + private enum UpdateGoalStatusUseCaseKey: DependencyKey { static var liveValue: UpdateDevelopmentGoalStatusUseCase { preconditionFailure("UpdateDevelopmentGoalStatusUseCase must be provided.") diff --git a/Application/Presentation/HomeTab/Sources/Goal/Create/GoalCreateFeature.swift b/Application/Presentation/HomeTab/Sources/Goal/Create/GoalCreateFeature.swift index d8ca9f713..4a15bda73 100644 --- a/Application/Presentation/HomeTab/Sources/Goal/Create/GoalCreateFeature.swift +++ b/Application/Presentation/HomeTab/Sources/Goal/Create/GoalCreateFeature.swift @@ -16,29 +16,35 @@ struct GoalCreateFeature { struct State: Equatable { @Presents var alert: AlertState? @Presents var todoSelection: GoalCreateTodoSelectionFeature.State? - var title = "" - var markdownContent = "" - var selectedTab = EditorTab.write + // 수정하는 개발 목표, 없으면 새 개발 목표 작성 + let goal: DevelopmentGoal? + var title: String + var content: String var selectedTodoIDs = Set() var pendingGoal: DevelopmentGoal? var result: DevelopmentGoal? var isSaving = false + // 수정은 처음 내용에서 바꾼 것이 있어야 저장 var isReadyToSave: Bool { - !isSaving && !title.trimmingCharacters(in: .whitespacesAndNewlines).isEmpty + !isSaving && hasDraft && !title.trimmingCharacters(in: .whitespacesAndNewlines).isEmpty } - // 버리기 전에 확인할 입력 내용이 있는지 여부 + // 버리기 전에 확인할 입력 내용이 있는지 여부, 수정은 처음 내용에서 바꾼 것이 있는지 여부 var hasDraft: Bool { - !title.trimmingCharacters(in: .whitespacesAndNewlines).isEmpty - || !markdownContent.trimmingCharacters(in: .whitespacesAndNewlines).isEmpty + if let goal { + return title != goal.title || content != goal.description + } + return !title.trimmingCharacters(in: .whitespacesAndNewlines).isEmpty + || !content.trimmingCharacters(in: .whitespacesAndNewlines).isEmpty || !selectedTodoIDs.isEmpty } - } - enum EditorTab: Equatable { - case write - case preview + init(goal: DevelopmentGoal? = nil) { + self.goal = goal + self.title = goal?.title ?? "" + self.content = goal?.description ?? "" + } } enum Action: BindableAction, Equatable { @@ -51,26 +57,31 @@ struct GoalCreateFeature { enum Alert: Equatable { case completeAfterTodoLinkFailure + case discard } enum ViewAction: Equatable { + case close case save case selectTodos } enum StoreAction: Equatable { case created(DevelopmentGoal) + case updated(DevelopmentGoal) case linkedTodos case todoLinkFailed case failed } enum Delegate: Equatable { + case close case saved(DevelopmentGoal) } } @Dependency(\.developmentCreateGoalUseCase) private var createGoalUseCase + @Dependency(\.developmentUpdateGoalUseCase) private var updateGoalUseCase @Dependency(\.developmentUpdateTodoGoalUseCase) private var updateTodoGoalUseCase var body: some ReducerOf { @@ -83,6 +94,9 @@ struct GoalCreateFeature { state.pendingGoal = nil state.result = goal return .send(.delegate(.saved(goal))) + case .alert(.presented(.discard)): + state.alert = nil + return .send(.delegate(.close)) case .alert, .binding, .delegate: break case .todoSelection(.dismiss): @@ -94,12 +108,23 @@ struct GoalCreateFeature { state.todoSelection = nil case .todoSelection: break + case .view(.close): + guard !state.isSaving else { break } + // 수정한 내용이 있으면 버릴지 물은 뒤 닫음 + if state.goal != nil, state.hasDraft { + state.alert = Self.discardAlert + break + } + return .send(.delegate(.close)) case .view(.save): guard state.isReadyToSave else { break } state.isSaving = true state.pendingGoal = nil state.result = nil - return createGoalEffect(title: state.title, description: state.markdownContent) + if let goal = state.goal { + return updateGoalEffect(goalId: goal.id, title: state.title, description: state.content) + } + return createGoalEffect(title: state.title, description: state.content) case .view(.selectTodos): guard !state.isSaving, state.todoSelection == nil else { break } state.todoSelection = GoalCreateTodoSelectionFeature.State( @@ -114,6 +139,10 @@ struct GoalCreateFeature { return .send(.delegate(.saved(goal))) } return linkTodosEffect(goalId: goal.id, todoIDs: state.selectedTodoIDs) + case .store(.updated(let goal)): + state.result = goal + state.isSaving = false + return .send(.delegate(.saved(goal))) case .store(.linkedTodos): guard let goal = state.pendingGoal else { break } state.pendingGoal = nil @@ -125,7 +154,7 @@ struct GoalCreateFeature { state.alert = Self.todoLinkFailureAlert case .store(.failed): state.isSaving = false - state.alert = Self.errorAlert + state.alert = Self.errorAlert(isEditing: state.goal != nil) } return .none @@ -152,6 +181,21 @@ private extension GoalCreateFeature { } } + func updateGoalEffect(goalId: String, title: String, description: String) -> Effect { + .run { [updateGoalUseCase] send in + do { + let goal = try await updateGoalUseCase.execute( + goalId, + title: title, + description: description + ) + await send(.store(.updated(goal))) + } catch { + await send(.store(.failed)) + } + } + } + func linkTodosEffect(goalId: String, todoIDs: Set) -> Effect { .run { [updateTodoGoalUseCase] send in do { @@ -165,7 +209,7 @@ private extension GoalCreateFeature { } } - static var errorAlert: AlertState { + static func errorAlert(isEditing: Bool) -> AlertState { AlertState { TextState(String(localized: "common_error_title", bundle: PresentationResources.bundle)) } actions: { @@ -174,12 +218,27 @@ private extension GoalCreateFeature { } } message: { TextState(String( - localized: "development_goal_create_error_message", + localized: isEditing ? "development_goal_edit_error_message" : "development_goal_create_error_message", bundle: PresentationResources.bundle )) } } + static var discardAlert: AlertState { + AlertState { + TextState(String(localized: "development_goal_edit_discard_title", bundle: PresentationResources.bundle)) + } actions: { + ButtonState(role: .destructive, action: .discard) { + TextState(String(localized: "development_goal_create_discard", bundle: PresentationResources.bundle)) + } + ButtonState(role: .cancel) { + TextState(String(localized: "common_cancel", bundle: PresentationResources.bundle)) + } + } message: { + TextState(String(localized: "development_goal_create_discard_message", bundle: PresentationResources.bundle)) + } + } + static var todoLinkFailureAlert: AlertState { AlertState { TextState(String(localized: "common_error_title", bundle: PresentationResources.bundle)) diff --git a/Application/Presentation/HomeTab/Sources/Goal/Create/GoalCreateView.swift b/Application/Presentation/HomeTab/Sources/Goal/Create/GoalCreateView.swift index 11bb78d62..222f30fdf 100644 --- a/Application/Presentation/HomeTab/Sources/Goal/Create/GoalCreateView.swift +++ b/Application/Presentation/HomeTab/Sources/Goal/Create/GoalCreateView.swift @@ -14,7 +14,6 @@ struct GoalCreateView: View { @Environment(\.usesDesktopLayout) private var usesDesktopLayout @Bindable var store: StoreOf @FocusState private var focusedField: GoalCreateField? - let onClose: () -> Void var body: some View { // 사이드바가 있으면 홈 내비게이션 안의 칸이라 시트용 내비게이션을 겹치지 않음 @@ -31,6 +30,8 @@ struct GoalCreateView: View { private var content: some View { let inset = isiOSAppOnMac ? 14 * AdaptiveSize.boardScale : 16 + // 수정은 같은 화면에 제목만 바꾸고 연결된 Todo 없이 표시 + let title = RecordPresentation.text(store.goal == nil ? "development_goal_create_title" : "development_goal_edit_title") return ScrollView { VStack(alignment: .leading, spacing: 0) { @@ -41,15 +42,17 @@ struct GoalCreateView: View { .padding(.horizontal, inset) // 사이드바가 있으면 연결된 Todo를 세부 정보 사이드바에 표시하고 저장은 칸 제목 줄에서 함 if !usesDesktopLayout { - GoalCreateTodoRow(store: store) - .padding(.vertical, 12) - .padding(.horizontal, inset) + if store.goal == nil { + GoalCreateTodoRow(store: store) + .padding(.vertical, 12) + .padding(.horizontal, inset) + } Button(action: save) { if store.isSaving { ProgressView() .tint(Color.background) } else { - Text(RecordPresentation.text("development_goal_save")) + Text(RecordPresentation.text(store.goal == nil ? "development_goal_save" : "todo_manage_save")) } } .buttonStyle(RecordButtonStyle(fillsWidth: true)) @@ -63,7 +66,7 @@ struct GoalCreateView: View { } .safeAreaInset(edge: .top, spacing: 0) { if usesDesktopLayout { - PaneTitleBar(Text(RecordPresentation.text("development_goal_create_title"))) { + PaneTitleBar(Text(title)) { Button(action: save) { Text(RecordPresentation.text("todo_manage_save")) .font(.adaptive(.body).weight(.semibold)) @@ -72,7 +75,9 @@ struct GoalCreateView: View { .buttonStyle(.plain) .disabled(!store.isReadyToSave) .opacity(store.isReadyToSave ? 1 : 0.4) - Button(action: onClose) { + Button { + store.send(.view(.close)) + } label: { Image(systemName: "xmark") } .topBarButtonStyle() @@ -81,10 +86,12 @@ struct GoalCreateView: View { } else { // 시트 손잡이 아래부터 글자 닫기 버튼과 가운데 제목 RecordTopBar( - RecordPresentation.text("development_goal_create_title"), + title, background: .secondaryBackground ) { - RecordTopBarTextButton(RecordPresentation.text("common_close"), action: onClose) + RecordTopBarTextButton(RecordPresentation.text("common_close")) { + store.send(.view(.close)) + } .disabled(store.isSaving) } trailing: { EmptyView() @@ -136,106 +143,50 @@ private struct GoalCreateTitleField: View { } private struct GoalCreateDescriptionEditor: View { - @Environment(\.isiOSAppOnMac) private var isiOSAppOnMac @Environment(\.usesDesktopLayout) private var usesDesktopLayout @Bindable var store: StoreOf let focusedField: FocusState.Binding + // 마크다운 없이 여러 줄 일반 글자로 작성 var body: some View { // 사이드바가 있는 창은 입력칸을 더 높게 표시 let minimumHeight = CGFloat(usesDesktopLayout ? 160 : 110) * AdaptiveSize.boardScale VStack(alignment: .leading, spacing: 0) { - // 사이드바가 있는 창은 작성·미리보기 버튼을 설명 이름 오른쪽 같은 줄에 표시 - HStack { - Text(RecordPresentation.text("development_goal_create_description_label")) - .font(.adaptive(.footnote)) - .foregroundStyle(Color.secondaryLabel) - if usesDesktopLayout { - Spacer() - modePicker - } - } - .padding(.top, 12) - .padding(.bottom, usesDesktopLayout ? 8 : 0) - - if !usesDesktopLayout { - modePicker - .padding(.vertical, 8) - } + Text(RecordPresentation.text("development_goal_create_description_label")) + .font(.adaptive(.footnote)) + .foregroundStyle(Color.secondaryLabel) + .padding(.top, 12) + .padding(.bottom, usesDesktopLayout ? 8 : 0) - switch store.selectedTab { - case .write: - // 안내 문구는 입력칸 아래에 표시 - TextEditorContentLayout(minimumHeight: minimumHeight, placesHintBelow: true) { - Text(RecordPresentation.text("development_goal_create_markdown_hint")) - .font(.adaptive(.caption)) - .foregroundStyle(Color.secondaryLabel) - UIKitTextEditor - .composable( - update: { textEditor in - textEditor.updateInput( - text: $store.markdownContent, - isFocused: focusedField.wrappedValue == .content, - onFocusChange: { isFocused in - if isFocused { - focusedField.wrappedValue = .content - } else if focusedField.wrappedValue == .content { - focusedField.wrappedValue = nil - } - }, - isEnabled: !store.isSaving - ) + UIKitTextEditor + .composable( + update: { textEditor in + textEditor.updateInput( + text: $store.content, + isFocused: focusedField.wrappedValue == .content, + onFocusChange: { isFocused in + if isFocused { + focusedField.wrappedValue = .content + } else if focusedField.wrappedValue == .content { + focusedField.wrappedValue = nil + } }, - sizeThatFits: { UIKitTextEditor.fittingSize(proposal: $0, textEditor: $1) } + isEnabled: !store.isSaving ) - .focused(focusedField, equals: .content) - .padding(12) - .recordInputBackground(isMultiline: true, isFocused: focusedField.wrappedValue == .content) - } + }, + sizeThatFits: { UIKitTextEditor.fittingSize(proposal: $0, textEditor: $1) } + ) + .focused(focusedField, equals: .content) + .padding(12) + .frame(maxWidth: .infinity, minHeight: minimumHeight, alignment: .topLeading) + .recordInputBackground(isMultiline: true, isFocused: focusedField.wrappedValue == .content) .padding(.top, 8) .contentShape(.rect) .onTapGesture { focusedField.wrappedValue = .content } - case .preview: - Group { - if store.markdownContent.isEmpty { - VStack(spacing: 8) { - Text(RecordPresentation.text("development_goal_create_preview_empty_title")) - .font(.adaptive(.headline)) - Text(RecordPresentation.text("development_goal_create_preview_empty_message")) - .font(.adaptive(.subheadline)) - .foregroundStyle(Color.secondaryLabel) - } - .multilineTextAlignment(.center) - .padding(12) - .frame(maxWidth: .infinity, minHeight: minimumHeight, alignment: .center) - } else { - MarkdownContentView( - content: store.markdownContent, - isScrollEnabled: false - ) - // MarkdownRenderer 내부의 좌우 여백을 상쇄해 입력 본문과 정렬 - .padding(.horizontal, -16) - .padding(12) - .frame(minHeight: minimumHeight, alignment: .topLeading) - } - } - .recordInputBackground(isMultiline: true) - .padding(.top, 8) - } } .disabled(store.isSaving) } - - private var modePicker: some View { - RecordModePicker(isWriting: store.selectedTab == .write) { - store.send(.binding(.set(\.selectedTab, .write))) - focusedField.wrappedValue = .content - } onPreview: { - focusedField.wrappedValue = nil - store.send(.binding(.set(\.selectedTab, .preview))) - } - } } // 카드 없이 페이지 여백에 맞춘 연결된 Todo 행 diff --git a/Application/Presentation/HomeTab/Sources/Home/HomeFeature+Effects.swift b/Application/Presentation/HomeTab/Sources/Home/HomeFeature+Effects.swift index ea1d4abea..07e395b57 100644 --- a/Application/Presentation/HomeTab/Sources/Home/HomeFeature+Effects.swift +++ b/Application/Presentation/HomeTab/Sources/Home/HomeFeature+Effects.swift @@ -148,9 +148,12 @@ extension HomeFeature { state.alert = alertState() } - static var discardGoalDraftAlertState: AlertState { + static func discardGoalDraftAlertState(isEditing: Bool) -> AlertState { AlertState { - TextState(String(localized: "development_goal_create_discard_title", bundle: PresentationResources.bundle)) + TextState(String( + localized: isEditing ? "development_goal_edit_discard_title" : "development_goal_create_discard_title", + bundle: PresentationResources.bundle + )) } actions: { ButtonState(role: .destructive, action: .discardGoalDraft) { TextState(String(localized: "development_goal_create_discard", bundle: PresentationResources.bundle)) diff --git a/Application/Presentation/HomeTab/Sources/Home/HomeFeature.swift b/Application/Presentation/HomeTab/Sources/Home/HomeFeature.swift index 04d593944..961a7052c 100644 --- a/Application/Presentation/HomeTab/Sources/Home/HomeFeature.swift +++ b/Application/Presentation/HomeTab/Sources/Home/HomeFeature.swift @@ -16,9 +16,9 @@ struct HomeFeature { @Presents var alert: AlertState? @Presents var sheet: SheetState? @Presents var fullScreenCover: FullScreenCoverState? - // 작성 중인 새 개발 목표를 버릴지 묻는 동안 미뤄 둔 동작 + // 작성 중인 새 개발 목표나 수정 중인 개발 목표를 버릴지 묻는 동안 미뤄 둔 동작 var actionAfterGoalDiscard: Action? - // 새 개발 목표 칸을 닫은 뒤 다시 처리할 사이드바 요청 + // 새 개발 목표나 개발 목표 칸을 닫은 뒤 다시 처리할 사이드바 요청 var sideBarRequestAfterGoalDiscard: SideBarRequest? var developmentGoalItems = [DevelopmentGoalItem]() var hasDevelopmentGoalsLoaded = false @@ -74,7 +74,7 @@ struct HomeFeature { case tapManageTodoCategory case tapTodoCategoryExpansionButton case tapTodoCategory(TodoCategory) - case closeGoalCreateForSideBarRequest(SideBarRequest) + case closeGoalDraftForSideBarRequest(SideBarRequest) } enum StoreAction: Equatable { @@ -204,14 +204,14 @@ struct HomeFeature { } BindingReducer() Reduce { state, action in - // 새 개발 목표 칸이 열린 동안 시트 자리를 바꾸는 동작 - if let goal = state.sheet?.goalCreateState { + // 새 개발 목표나 개발 목표 수정 칸이 열린 동안 시트 자리를 바꾸는 동작 + if let goal = state.sheet?.goalCreateState ?? state.sheet?.goalDetailState?.goalEdit { switch action { case .view(.tapCreateDevelopmentGoal), .view(.tapDevelopmentGoal), .view(.tapManageTodoCategory), .view(.tapTodoCategory), - .view(.closeGoalCreateForSideBarRequest), + .view(.closeGoalDraftForSideBarRequest), .store(.setSheet), .store(.setPresentation(.contentPicker, true)): // 저장하는 동안 시트 자리를 바꾸면 저장이 취소되어 막음 @@ -221,7 +221,7 @@ struct HomeFeature { // 작성 중인 내용이 있으면 버릴지 물은 뒤 고른 동작 실행 if goal.hasDraft { state.actionAfterGoalDiscard = action - state.alert = Self.discardGoalDraftAlertState + state.alert = Self.discardGoalDraftAlertState(isEditing: goal.goal != nil) return .none } default: @@ -233,8 +233,10 @@ struct HomeFeature { case .alert(.presented(.discardGoalDraft)): guard let action = state.actionAfterGoalDiscard else { break } state.actionAfterGoalDiscard = nil + // 개발 목표 칸에서 바꾼 상태와 기록은 수정을 버리고 칸을 닫아도 홈과 사이드바 목록에 반영 + let refreshesDevelopmentGoals = state.sheet?.goalDetailState != nil state.sheet = nil - return .send(action) + return refreshesDevelopmentGoals ? .merge(.send(action), .send(.view(.fetchData))) : .send(action) case .alert(.dismiss): state.actionAfterGoalDiscard = nil case .fullScreenCover(.presented(.todoEditor(.delegate(.created)))): @@ -259,6 +261,11 @@ struct HomeFeature { case .sheet(.presented(.goalCreate(.delegate(.saved)))): state.sheet = nil return .send(.view(.fetchData)) + case .sheet(.presented(.goalCreate(.delegate(.close)))): + return .send(.sheet(.dismiss)) + // 개발 목표 칸에서 고친 제목을 사이드바와 홈 목록에 반영 + case .sheet(.presented(.goalDetail(.delegate(.goalUpdated)))): + return .send(.view(.fetchData)) case .sheet: break case .binding: @@ -333,7 +340,7 @@ private extension HomeFeature { state.selectedTodoCategory = category state.sheet = nil return delayedTodoEditorEffect() - case .closeGoalCreateForSideBarRequest(let request): + case .closeGoalDraftForSideBarRequest(let request): state.sheet = nil state.sideBarRequestAfterGoalDiscard = request } diff --git a/Application/Presentation/HomeTab/Sources/Home/HomeView.swift b/Application/Presentation/HomeTab/Sources/Home/HomeView.swift index 27a073f1a..5ebdd1603 100644 --- a/Application/Presentation/HomeTab/Sources/Home/HomeView.swift +++ b/Application/Presentation/HomeTab/Sources/Home/HomeView.swift @@ -65,9 +65,7 @@ public struct HomeView: View { PaneSplitView { homeContent } detail: { - GoalCreateView(store: goalStore) { - store.send(.sheet(.dismiss)) - } + GoalCreateView(store: goalStore) } .detailSideBar { GoalCreateSideBarContent(store: goalStore) @@ -132,7 +130,7 @@ public struct HomeView: View { .onChange(of: sideBarRequest, initial: true) { _, request in handleSideBarRequest(request, showsSheetAsPane: showsSheetAsPane) } - // 작성 중인 새 개발 목표를 버린 뒤 미뤄 둔 사이드바 요청 처리 + // 작성 중인 새 개발 목표나 수정 중인 개발 목표를 버린 뒤 미뤄 둔 사이드바 요청 처리 .onChange(of: store.sideBarRequestAfterGoalDiscard) { _, request in handleSideBarRequest(request, showsSheetAsPane: showsSheetAsPane) } @@ -194,11 +192,11 @@ public struct HomeView: View { store.send(.sheet(.presented(.goalDetail(.view(.returnToGoal))))) return } - // 작성 중인 새 개발 목표가 있으면 칸을 닫기 전에 버릴지 물음 + // 작성 중인 새 개발 목표나 수정 중인 개발 목표가 있으면 칸을 닫기 전에 버릴지 물음 if let request, request.action != .createTodo, - store.sheet?.goalCreateState?.hasDraft == true { - store.send(.view(.closeGoalCreateForSideBarRequest(request))) + store.sheet?.goalCreateState?.hasDraft == true || store.sheet?.goalDetailState?.goalEdit?.hasDraft == true { + store.send(.view(.closeGoalDraftForSideBarRequest(request))) return } // 개발 목표 칸을 다른 화면으로 바꾸면 칸에서 바꾼 목표와 기록을 시트를 닫을 때처럼 홈과 사이드바 목록에 반영 @@ -242,7 +240,8 @@ public struct HomeView: View { case .open, nil: break } - if refreshesDevelopmentGoals { + // 버릴지 묻는 중이면 칸이 그대로라 다시 불러오지 않음 + if refreshesDevelopmentGoals && store.actionAfterGoalDiscard == nil { store.send(.view(.fetchData)) } } @@ -366,9 +365,7 @@ public struct HomeView: View { } case .goalCreate: if let goalStore = sheetStore.scope(state: \.goalCreateState, action: \.goalCreate) { - GoalCreateView(store: goalStore) { - store.send(.sheet(.dismiss)) - } + GoalCreateView(store: goalStore) } case .goalDetail: // 개발 목표는 시트 대신 홈 내비게이션에 쌓음 diff --git a/Application/Presentation/HomeTab/Sources/Record/GoalDetail/GoalDetailFeature.swift b/Application/Presentation/HomeTab/Sources/Record/GoalDetail/GoalDetailFeature.swift index dbf1dd3bc..69c0ffa78 100644 --- a/Application/Presentation/HomeTab/Sources/Record/GoalDetail/GoalDetailFeature.swift +++ b/Application/Presentation/HomeTab/Sources/Record/GoalDetail/GoalDetailFeature.swift @@ -27,6 +27,8 @@ struct GoalDetailFeature { @ObservableState struct State: Equatable { @Presents var alert: AlertState? + // 좁은 창은 시트, 넓은 창은 오른쪽 칸에 그려 창 폭이 바뀌어도 수정 중인 내용 유지 + @Presents var goalEdit: GoalCreateFeature.State? // 넓은 창의 칸과 시트가 같은 상태를 그려 창 폭이 바뀌어도 작성 중인 기록 유지 @Presents var recordEditor: RecordEditorFeature.State? @Presents var recordDetail: RecordDetailDestination? @@ -75,6 +77,7 @@ struct GoalDetailFeature { enum Action: BindableAction, Equatable { case alert(PresentationAction) + case goalEdit(PresentationAction) case recordEditor(PresentationAction) case recordDetail(PresentationAction) case recordDetailContent(RecordDetailFeature.Action) @@ -83,6 +86,7 @@ struct GoalDetailFeature { case binding(BindingAction) case view(ViewAction) case store(StoreAction) + case delegate(Delegate) enum Alert: Equatable { case confirmTransition(DevelopmentGoal.Status) @@ -92,6 +96,7 @@ struct GoalDetailFeature { case addRecord case appear(onDesktop: Bool) case continueRecord + case editGoal case fetch case manageTodos case refresh @@ -112,6 +117,10 @@ struct GoalDetailFeature { case transitionFailed case recordDetailDismissed } + + enum Delegate: Equatable { + case goalUpdated + } } @Dependency(\.developmentFetchGoalUseCase) private var fetchGoalUseCase @@ -132,6 +141,16 @@ struct GoalDetailFeature { return transitionEffect(goalId: state.goalId, status: status) case .alert: break + case .goalEdit(.presented(.delegate(.saved(let goal)))): + state.goal = goal + state.updatedGoalStatus = nil + state.goalEdit = nil + return .send(.delegate(.goalUpdated)) + case .goalEdit(.dismiss), + .goalEdit(.presented(.delegate(.close))): + state.goalEdit = nil + case .goalEdit, .delegate: + break case .recordEditor(.dismiss): state.recordEditor = nil case .recordEditor: @@ -164,7 +183,8 @@ struct GoalDetailFeature { state.allowsRecordMutation, !state.isLoading, !state.isTransitioning, - state.recordEditor == nil else { break } + state.recordEditor == nil, + state.goalEdit == nil else { break } state.recordEditor = RecordEditorFeature.State( goalId: state.goalId, goalTitle: state.goalTitle, @@ -186,6 +206,7 @@ struct GoalDetailFeature { !state.isLoading, !state.isTransitioning, state.recordEditor == nil, + state.goalEdit == nil, let record = state.items.first(where: \.hasDraft)?.record else { break } state.recordEditor = RecordEditorFeature.State( goalId: state.goalId, @@ -193,6 +214,15 @@ struct GoalDetailFeature { record: record, versionId: uuid().uuidString ) + case .view(.editGoal): + // 넓은 창은 같은 오른쪽 칸을 쓰는 기록 작성이 열려 있으면 수정을 열지 않음 + guard state.hasLoaded, + !state.isLoading, + !state.isTransitioning, + state.recordEditor == nil, + state.goalEdit == nil, + let goal = state.goal else { break } + state.goalEdit = GoalCreateFeature.State(goal: goal) case .view(.fetch): guard !state.hasLoaded, !state.isLoading else { break } state.isLoading = true @@ -231,6 +261,7 @@ struct GoalDetailFeature { guard state.recordEditor == nil, state.recordDetail == nil else { break } if item.hasDraft, state.allowsRecordMutation { + guard state.goalEdit == nil else { break } state.recordEditor = RecordEditorFeature.State( goalId: state.goalId, goalTitle: state.goalTitle, @@ -305,6 +336,9 @@ struct GoalDetailFeature { return .none } .ifLet(\.$alert, action: \.alert) + .ifLet(\.$goalEdit, action: \.goalEdit) { + GoalCreateFeature() + } .ifLet(\.$recordEditor, action: \.recordEditor) { RecordEditorFeature() } diff --git a/Application/Presentation/HomeTab/Sources/Record/GoalDetail/GoalDetailView.swift b/Application/Presentation/HomeTab/Sources/Record/GoalDetail/GoalDetailView.swift index a13509d38..c0dc7314f 100644 --- a/Application/Presentation/HomeTab/Sources/Record/GoalDetail/GoalDetailView.swift +++ b/Application/Presentation/HomeTab/Sources/Record/GoalDetail/GoalDetailView.swift @@ -56,11 +56,13 @@ public struct GoalDetailView: View { let isShown = store.shownOnDesktop == usesDesktopLayout let isHidden = { !isShown || store.shownOnDesktop != usesDesktopLayout } - // 사이드바가 있으면 기록 작성을 개발 목표 오른쪽 칸에 표시 - return PaneSplitView(splitsOnDesktop: store.recordEditor != nil) { + // 사이드바가 있으면 개발 목표 수정과 기록 작성을 개발 목표 오른쪽 칸에 표시 + return PaneSplitView(splitsOnDesktop: store.goalEdit != nil || store.recordEditor != nil) { mainContent } detail: { - if let editorStore = store.scope(state: \.recordEditor, action: \.recordEditor.presented) { + 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: { @@ -88,6 +90,13 @@ public struct GoalDetailView: View { .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() }, @@ -139,7 +148,7 @@ public struct GoalDetailView: View { } } else { // Duo는 뒤로 버튼을 오른쪽 세로 막대에 표시 - // 상태 메뉴는 직접 그린 팝오버라 세로 막대에 넣지 않고 제목 줄에 표시 + // 상태 메뉴는 버튼 자리에 맞춰 직접 그리는 메뉴라 세로 막대에 넣지 않고 제목 줄에 표시 RecordTopBar(RecordPresentation.text("development_goal_title")) { if deviceType != .duo { NavigationBackButton(action: { dismiss() }) @@ -151,17 +160,16 @@ public struct GoalDetailView: View { } } + // 상태 항목 아래 구분선 뒤에 수정 + // 제목 줄 오른쪽 끝 버튼이라 메뉴 오른쪽 끝을 버튼 오른쪽 끝에 맞춤 @ViewBuilder private var statusMenu: some View { if let status = store.goalStatus { - Image(systemName: "ellipsis") - .prominentMenu( - items: statusMenuItems(status), - isEnabled: !store.isLoading && !store.isTransitioning - ) { status in - store.send(.view(.selectStatus(status))) - } - .topBarButtonStyle() + DropdownMenu(alignment: .trailing, sections: menuSections(status)) { + Image(systemName: "ellipsis") + .topBarButtonStyle() + } + .disabled(store.isLoading || store.isTransitioning) } } @@ -188,9 +196,11 @@ public struct GoalDetailView: View { .frame(maxWidth: .infinity) .padding(.vertical, 16) } else if let description = store.goal?.description, !description.isEmpty { - MarkdownContentView(content: description, isScrollEnabled: false) - // MarkdownRenderer 내부의 좌우 여백을 상쇄해 제목과 정렬 - .padding(.horizontal, -16) + // 마크다운 없이 쓴 그대로 표시 + Text(description) + .font(.adaptive(isiOSAppOnMac ? .body : .subheadline)) + .foregroundStyle(Color.secondaryLabel) + .lineSpacing(6 * AdaptiveSize.boardScale) } } .frame(maxWidth: .infinity, alignment: .leading) @@ -269,29 +279,44 @@ public struct GoalDetailView: View { } } - private func statusMenuItems(_ status: DevelopmentGoal.Status) -> [ProminentMenuItem] { - switch status { + private func menuSections(_ status: DevelopmentGoal.Status) -> [DropdownMenuSection] { + let statusItems = switch status { case .inProgress: [ - ProminentMenuItem( - action: .completed, - title: RecordPresentation.text("development_goal_complete"), + DropdownMenuItem( + RecordPresentation.text("development_goal_complete"), systemImage: "checkmark.circle" - ), - ProminentMenuItem( - action: .archived, - title: RecordPresentation.text("development_goal_archive"), + ) { + store.send(.view(.selectStatus(.completed))) + }, + DropdownMenuItem( + RecordPresentation.text("development_goal_archive"), systemImage: "archivebox" - ) + ) { + store.send(.view(.selectStatus(.archived))) + } ] case .completed, .archived: [ - ProminentMenuItem( - action: .inProgress, - title: RecordPresentation.text("development_goal_resume"), + DropdownMenuItem( + RecordPresentation.text("development_goal_resume"), systemImage: "arrow.counterclockwise" - ) + ) { + store.send(.view(.selectStatus(.inProgress))) + } ] } + + return [ + DropdownMenuSection(items: statusItems), + DropdownMenuSection(items: [ + DropdownMenuItem( + RecordPresentation.text("development_goal_edit"), + systemImage: "pencil" + ) { + store.send(.view(.editGoal)) + } + ]) + ] } } diff --git a/Application/Presentation/HomeTab/Sources/Record/GoalDetail/GoalTodoLinkSheet.swift b/Application/Presentation/HomeTab/Sources/Record/GoalDetail/GoalTodoLinkSheet.swift index 89f8f3175..b1636811a 100644 --- a/Application/Presentation/HomeTab/Sources/Record/GoalDetail/GoalTodoLinkSheet.swift +++ b/Application/Presentation/HomeTab/Sources/Record/GoalDetail/GoalTodoLinkSheet.swift @@ -52,14 +52,21 @@ struct GoalTodoLinkSheet: View { .disabled(store.isUpdating) Spacer() HStack(spacing: 8) { - Image(systemName: "ellipsis") - .prominentMenu( - items: clearSelectionMenuItems, - isEnabled: store.canClearSelection - ) { _ in - store.send(.view(.clearSelection)) - } - .topBarButtonStyle() + // 제목 줄 오른쪽 버튼이라 메뉴 오른쪽 끝을 버튼 오른쪽 끝에 맞춤 + DropdownMenu(alignment: .trailing, sections: [ + DropdownMenuSection(items: [ + DropdownMenuItem( + RecordPresentation.text("development_goal_todo_clear_selection"), + systemImage: "xmark.circle" + ) { + store.send(.view(.clearSelection)) + } + ]) + ]) { + Image(systemName: "ellipsis") + .topBarButtonStyle() + } + .disabled(!store.canClearSelection) Button { store.send(.view(.save)) } label: { @@ -95,16 +102,6 @@ struct GoalTodoLinkSheet: View { } } - private var clearSelectionMenuItems: [ProminentMenuItem] { - [ - ProminentMenuItem( - action: .clearSelection, - title: RecordPresentation.text("development_goal_todo_clear_selection"), - systemImage: "xmark.circle" - ) - ] - } - @ViewBuilder private var sheetContent: some View { if store.isLoading, store.todos.isEmpty { @@ -146,7 +143,3 @@ struct GoalTodoLinkSheet: View { } } } - -private enum GoalTodoLinkMenuAction: Hashable { - case clearSelection -} diff --git a/Application/Presentation/HomeTab/Tests/Goal/Create/GoalCreateFeatureTests.swift b/Application/Presentation/HomeTab/Tests/Goal/Create/GoalCreateFeatureTests.swift index 4e90402ce..fd088385c 100644 --- a/Application/Presentation/HomeTab/Tests/Goal/Create/GoalCreateFeatureTests.swift +++ b/Application/Presentation/HomeTab/Tests/Goal/Create/GoalCreateFeatureTests.swift @@ -18,7 +18,7 @@ struct GoalCreateFeatureTests { let spy = CreateDevelopmentGoalUseCaseSpy(result: .success(goal)) var state = GoalCreateFeature.State() state.title = goal.title - state.markdownContent = "# 목표" + state.content = "# 목표" let store = TestStore(initialState: state) { GoalCreateFeature() } withDependencies: { @@ -39,6 +39,102 @@ struct GoalCreateFeatureTests { ]) } + @Test("수정하는 목표는 새로 만들지 않고 같은 ID로 제목과 설명을 저장한다") + func 수정하는_목표는_새로_만들지_않고_같은_ID로_제목과_설명을_저장한다() async throws { + let goal = try makeDevelopmentGoal(title: "버전 이력 완성") + let updated = try makeDevelopmentGoal(title: "버전 이력 정리") + let createSpy = CreateDevelopmentGoalUseCaseSpy(result: .success(goal)) + let updateSpy = UpdateDevelopmentGoalUseCaseSpy(result: .success(updated)) + var state = GoalCreateFeature.State(goal: goal) + state.title = updated.title + let store = TestStore(initialState: state) { + GoalCreateFeature() + } withDependencies: { + $0.developmentCreateGoalUseCase = createSpy + $0.developmentUpdateGoalUseCase = updateSpy + } + + await store.send(.view(.save)) { + $0.isSaving = true + } + await store.receive(.store(.updated(updated))) { + $0.result = updated + $0.isSaving = false + } + await store.receive(.delegate(.saved(updated))) + + #expect(await updateSpy.requests() == [ + .init(goalId: goal.id, title: updated.title, description: goal.description) + ]) + #expect(await createSpy.requests().isEmpty) + } + + @Test("바꾼 내용이 없는 수정은 저장하지 않는다") + func 바꾼_내용이_없는_수정은_저장하지_않는다() async throws { + let goal = try makeDevelopmentGoal() + let spy = UpdateDevelopmentGoalUseCaseSpy(result: .success(goal)) + let store = TestStore(initialState: GoalCreateFeature.State(goal: goal)) { + GoalCreateFeature() + } withDependencies: { + $0.developmentUpdateGoalUseCase = spy + } + + await store.send(.view(.save)) + + #expect(await spy.requests().isEmpty) + } + + @Test("수정 저장 실패는 수정 실패 알림을 표시한다") + func 수정_저장_실패는_수정_실패_알림을_표시한다() async throws { + let goal = try makeDevelopmentGoal() + var state = GoalCreateFeature.State(goal: goal) + state.title = "바꾼 제목" + let store = TestStore(initialState: state) { + GoalCreateFeature() + } withDependencies: { + $0.developmentUpdateGoalUseCase = UpdateDevelopmentGoalUseCaseSpy( + result: .failure(RecordTestError.failed) + ) + } + + await store.send(.view(.save)) { + $0.isSaving = true + } + await store.receive(.store(.failed)) { + $0.isSaving = false + $0.alert = makeEditErrorAlert() + } + } + + @Test("수정한 내용이 있으면 버릴지 물은 뒤 버리면 닫는다") + func 수정한_내용이_있으면_버릴지_물은_뒤_버리면_닫는다() async throws { + let goal = try makeDevelopmentGoal() + var state = GoalCreateFeature.State(goal: goal) + state.content = "바꾼 설명" + let store = TestStore(initialState: state) { + GoalCreateFeature() + } + + await store.send(.view(.close)) { + $0.alert = makeEditDiscardAlert() + } + await store.send(.alert(.presented(.discard))) { + $0.alert = nil + } + await store.receive(.delegate(.close)) + } + + @Test("바꾼 내용이 없는 수정은 묻지 않고 닫는다") + func 바꾼_내용이_없는_수정은_묻지_않고_닫는다() async throws { + let goal = try makeDevelopmentGoal() + let store = TestStore(initialState: GoalCreateFeature.State(goal: goal)) { + GoalCreateFeature() + } + + await store.send(.view(.close)) + await store.receive(.delegate(.close)) + } + @Test("선택한 Todo는 생성된 목표 ID로 연결한다") func 선택한_Todo는_생성된_목표_ID로_연결한다() async throws { let goal = try makeDevelopmentGoal() @@ -120,6 +216,33 @@ struct GoalCreateFeatureTests { } } + private func makeEditErrorAlert() -> AlertState { + AlertState { + TextState(String(localized: "common_error_title", bundle: PresentationResources.bundle)) + } actions: { + ButtonState(role: .cancel) { + TextState(String(localized: "common_close", bundle: PresentationResources.bundle)) + } + } message: { + TextState(String(localized: "development_goal_edit_error_message", bundle: PresentationResources.bundle)) + } + } + + private func makeEditDiscardAlert() -> AlertState { + AlertState { + TextState(String(localized: "development_goal_edit_discard_title", bundle: PresentationResources.bundle)) + } actions: { + ButtonState(role: .destructive, action: .discard) { + TextState(String(localized: "development_goal_create_discard", bundle: PresentationResources.bundle)) + } + ButtonState(role: .cancel) { + TextState(String(localized: "common_cancel", bundle: PresentationResources.bundle)) + } + } message: { + TextState(String(localized: "development_goal_create_discard_message", bundle: PresentationResources.bundle)) + } + } + private func makeTodoLinkFailureAlert() -> AlertState { AlertState { TextState(String(localized: "common_error_title", bundle: PresentationResources.bundle)) diff --git a/Application/Presentation/HomeTab/Tests/Home/HomeFeatureTestSupport.swift b/Application/Presentation/HomeTab/Tests/Home/HomeFeatureTestSupport.swift index 80b40e524..611cab136 100644 --- a/Application/Presentation/HomeTab/Tests/Home/HomeFeatureTestSupport.swift +++ b/Application/Presentation/HomeTab/Tests/Home/HomeFeatureTestSupport.swift @@ -123,8 +123,8 @@ struct StoreTestAdapter { await store.send(.sheet(.presented(.goalCreate(.binding(.set(\.title, title)))))) } - func closeGoalCreateForSideBarRequest(_ request: SideBarRequest) async { - await store.send(.view(.closeGoalCreateForSideBarRequest(request))) + func closeGoalDraftForSideBarRequest(_ request: SideBarRequest) async { + await store.send(.view(.closeGoalDraftForSideBarRequest(request))) } func discardGoalDraft() async { diff --git a/Application/Presentation/HomeTab/Tests/Home/HomeFeatureTests.swift b/Application/Presentation/HomeTab/Tests/Home/HomeFeatureTests.swift index 7c1df3c65..cb8e6e2d5 100644 --- a/Application/Presentation/HomeTab/Tests/Home/HomeFeatureTests.swift +++ b/Application/Presentation/HomeTab/Tests/Home/HomeFeatureTests.swift @@ -146,7 +146,7 @@ struct HomeFeatureTests { await adapter.setGoalCreateTitle("목표") await adapter.tapDevelopmentGoal("goal") - #expect(adapter.alert == HomeFeature.discardGoalDraftAlertState) + #expect(adapter.alert == HomeFeature.discardGoalDraftAlertState(isEditing: false)) #expect(adapter.sheet?.goalCreateState?.title == "목표") await adapter.discardGoalDraft() @@ -154,6 +154,25 @@ struct HomeFeatureTests { #expect(adapter.sheet?.goalDetailState?.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 = "바꾼 제목" + + await adapter.setSheet(.goalDetail(detail)) + await adapter.tapDevelopmentGoal("other") + + #expect(adapter.alert == HomeFeature.discardGoalDraftAlertState(isEditing: true)) + #expect(adapter.sheet?.goalDetailState?.goalEdit?.title == "바꾼 제목") + + await adapter.discardGoalDraft() + + #expect(adapter.sheet?.goalDetailState?.goalId == "other") + } + @Test("작성 중인 새 개발 목표를 버리지 않으면 칸을 유지한다") func 작성_중인_새_개발_목표를_버리지_않으면_칸을_유지한다() async { let adapter = StoreTestAdapter() @@ -174,7 +193,7 @@ struct HomeFeatureTests { await adapter.tapCreateDevelopmentGoal() await adapter.setGoalCreateTitle("목표") - await adapter.closeGoalCreateForSideBarRequest(request) + await adapter.closeGoalDraftForSideBarRequest(request) #expect(adapter.sideBarRequestAfterGoalDiscard == nil) @@ -207,6 +226,65 @@ struct HomeFeatureTests { #expect(adapter.sheet?.goalCreateState?.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 = "바꾼 제목" + + await adapter.setSheet(.goalDetail(detail)) + await adapter.tapManageTodoCategory() + + #expect(goalsSpy.queries.isEmpty) + + await adapter.discardGoalDraft() + + await waitUntil { !goalsSpy.queries.isEmpty } + #expect(goalsSpy.queries == [.init(status: .inProgress)]) + #expect(adapter.sheet?.goalDetailState == nil) + } + + @Test("수정 중인 개발 목표를 버리면 미뤄 둔 사이드바 요청을 다시 처리한다") + func 수정_중인_개발_목표를_버리면_미뤄_둔_사이드바_요청을_다시_처리한다() async throws { + let adapter = StoreTestAdapter() + let request = SideBarRequest(id: UUID(), action: .open(.home)) + let goal = try makeDevelopmentGoal() + var detail = GoalDetailFeature.State(goalId: goal.id) + detail.goalEdit = GoalCreateFeature.State(goal: goal) + detail.goalEdit?.content = "바꾼 설명" + + await adapter.setSheet(.goalDetail(detail)) + await adapter.closeGoalDraftForSideBarRequest(request) + + #expect(adapter.alert == HomeFeature.discardGoalDraftAlertState(isEditing: true)) + #expect(adapter.sideBarRequestAfterGoalDiscard == nil) + + await adapter.discardGoalDraft() + + #expect(adapter.sheet == nil) + #expect(adapter.sideBarRequestAfterGoalDiscard == request) + } + + @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 + + await adapter.setSheet(.goalDetail(detail)) + await adapter.tapDevelopmentGoal("other") + await adapter.setSheet(nil) + + #expect(adapter.alert == nil) + #expect(adapter.sheet?.goalDetailState?.goalEdit?.isSaving == true) + } + @Test("새 개발 목표를 저장하면 시트를 닫고 홈 데이터를 다시 조회한다") func 새_개발_목표를_저장하면_시트를_닫고_홈_데이터를_다시_조회한다() async throws { let goal = try makeDevelopmentGoal(id: "goal", createdAt: 1) diff --git a/Application/Presentation/HomeTab/Tests/Record/GoalDetailFeatureTests.swift b/Application/Presentation/HomeTab/Tests/Record/GoalDetailFeatureTests.swift index d2a092a84..c259afc6b 100644 --- a/Application/Presentation/HomeTab/Tests/Record/GoalDetailFeatureTests.swift +++ b/Application/Presentation/HomeTab/Tests/Record/GoalDetailFeatureTests.swift @@ -379,4 +379,59 @@ struct GoalDetailFeatureTests { .init(goalId: goal.id, status: .archived) ]) } + + @Test("목표 수정은 불러온 목표로 수정 화면을 연다") + func 목표_수정은_불러온_목표로_수정_화면을_연다() async throws { + let goal = try makeDevelopmentGoal() + var state = GoalDetailFeature.State(goalId: goal.id) + state.goal = goal + state.hasLoaded = true + let store = TestStore(initialState: state) { + GoalDetailFeature() + } + + await store.send(.view(.editGoal)) { + $0.goalEdit = GoalCreateFeature.State(goal: goal) + } + } + + @Test("기록 작성이 열려 있으면 목표 수정을 열지 않는다") + func 기록_작성이_열려_있으면_목표_수정을_열지_않는다() async throws { + let goal = try makeDevelopmentGoal() + var state = GoalDetailFeature.State(goalId: goal.id) + state.goal = goal + state.hasLoaded = true + state.recordEditor = RecordEditorFeature.State( + goalId: goal.id, + goalTitle: goal.title, + recordId: "record", + versionId: "version" + ) + let store = TestStore(initialState: state) { + GoalDetailFeature() + } + + await store.send(.view(.editGoal)) + } + + @Test("목표 수정 저장은 상세 목표를 바꾸고 수정을 알린다") + func 목표_수정_저장은_상세_목표를_바꾸고_수정을_알린다() async throws { + let goal = try makeDevelopmentGoal(status: .archived) + let updated = try makeDevelopmentGoal(title: "바꾼 제목", status: .archived) + var state = GoalDetailFeature.State(goalId: goal.id) + state.goal = goal + state.updatedGoalStatus = .archived + state.hasLoaded = true + state.goalEdit = GoalCreateFeature.State(goal: goal) + let store = TestStore(initialState: state) { + GoalDetailFeature() + } + + await store.send(.goalEdit(.presented(.delegate(.saved(updated))))) { + $0.goal = updated + $0.updatedGoalStatus = nil + $0.goalEdit = nil + } + await store.receive(.delegate(.goalUpdated)) + } } diff --git a/Application/Presentation/HomeTab/Tests/Record/RecordFeatureTestSupport.swift b/Application/Presentation/HomeTab/Tests/Record/RecordFeatureTestSupport.swift index 8282cabf5..d710dfac5 100644 --- a/Application/Presentation/HomeTab/Tests/Record/RecordFeatureTestSupport.swift +++ b/Application/Presentation/HomeTab/Tests/Record/RecordFeatureTestSupport.swift @@ -58,6 +58,30 @@ actor CreateDevelopmentGoalUseCaseSpy: CreateDevelopmentGoalUseCase { } } +actor UpdateDevelopmentGoalUseCaseSpy: UpdateDevelopmentGoalUseCase { + struct Request: Equatable { + let goalId: String + let title: String + let description: String + } + + private let result: Result + private var recordedRequests = [Request]() + + init(result: Result) { + self.result = result + } + + func execute(_ goalId: String, title: String, description: String) async throws -> DevelopmentGoal { + recordedRequests.append(.init(goalId: goalId, title: title, description: description)) + return try result.get() + } + + func requests() -> [Request] { + recordedRequests + } +} + actor UpdateDevelopmentGoalStatusUseCaseSpy: UpdateDevelopmentGoalStatusUseCase { struct Request: Equatable { let goalId: String diff --git a/Application/Presentation/PresentationShared/Resources/Localizable.xcstrings b/Application/Presentation/PresentationShared/Resources/Localizable.xcstrings index 9fb802963..c5fd1abfb 100644 --- a/Application/Presentation/PresentationShared/Resources/Localizable.xcstrings +++ b/Application/Presentation/PresentationShared/Resources/Localizable.xcstrings @@ -804,189 +804,206 @@ } } }, - "development_goal_create_markdown_hint" : { + "development_goal_create_title" : { "extractionState" : "manual", "localizations" : { "en" : { "stringUnit" : { "state" : "translated", - "value" : "Markdown is supported." + "value" : "New Development Goal" } }, "ko" : { "stringUnit" : { "state" : "translated", - "value" : "Markdown을 지원해요." + "value" : "새 개발 목표" } } } }, - "development_goal_create_preview_empty_message" : { + "development_goal_create_title_label" : { "extractionState" : "manual", "localizations" : { "en" : { "stringUnit" : { "state" : "translated", - "value" : "Write a description to preview it." + "value" : "Title" } }, "ko" : { "stringUnit" : { "state" : "translated", - "value" : "설명을 작성하면 미리볼 수 있어요." + "value" : "제목" } } } }, - "development_goal_create_preview_empty_title" : { + "development_goal_create_title_placeholder" : { "extractionState" : "manual", "localizations" : { "en" : { "stringUnit" : { "state" : "translated", - "value" : "No description yet" + "value" : "Enter a goal title" } }, "ko" : { "stringUnit" : { "state" : "translated", - "value" : "작성한 설명이 없어요" + "value" : "목표 제목을 입력하세요" } } } }, - "development_goal_create_title" : { + "development_goal_create_todo_hint" : { "extractionState" : "manual", "localizations" : { "en" : { "stringUnit" : { "state" : "translated", - "value" : "New Development Goal" + "value" : "You can link Todos later." } }, "ko" : { "stringUnit" : { "state" : "translated", - "value" : "새 개발 목표" + "value" : "나중에 연결할 수 있어요." } } } }, - "development_goal_create_title_label" : { + "development_goal_create_todo_label" : { "extractionState" : "manual", "localizations" : { "en" : { "stringUnit" : { "state" : "translated", - "value" : "Title" + "value" : "Linked Todo" } }, "ko" : { "stringUnit" : { "state" : "translated", - "value" : "제목" + "value" : "연결된 Todo" } } } }, - "development_goal_create_title_placeholder" : { + "development_goal_create_todo_link_error_message" : { "extractionState" : "manual", "localizations" : { "en" : { "stringUnit" : { "state" : "translated", - "value" : "Enter a goal title" + "value" : "The goal was created, but some Todo links could not be saved. You can link them again from the goal details." } }, "ko" : { "stringUnit" : { "state" : "translated", - "value" : "목표 제목을 입력하세요" + "value" : "목표는 만들었지만 일부 Todo를 연결하지 못했어요. 목표 상세에서 다시 연결할 수 있어요." } } } }, - "development_goal_create_todo_hint" : { + "development_goal_create_todo_select" : { "extractionState" : "manual", "localizations" : { "en" : { "stringUnit" : { "state" : "translated", - "value" : "You can link Todos later." + "value" : "Select Todos" } }, "ko" : { "stringUnit" : { "state" : "translated", - "value" : "나중에 연결할 수 있어요." + "value" : "Todo 선택" } } } }, - "development_goal_create_todo_label" : { + "development_goal_create_todo_selected_format" : { "extractionState" : "manual", "localizations" : { "en" : { "stringUnit" : { "state" : "translated", - "value" : "Linked Todo" + "value" : "%1$lld selected" } }, "ko" : { "stringUnit" : { "state" : "translated", - "value" : "연결된 Todo" + "value" : "%1$lld개 선택됨" } } } }, - "development_goal_create_todo_link_error_message" : { + "development_goal_edit" : { "extractionState" : "manual", "localizations" : { "en" : { "stringUnit" : { "state" : "translated", - "value" : "The goal was created, but some Todo links could not be saved. You can link them again from the goal details." + "value" : "Edit" } }, "ko" : { "stringUnit" : { "state" : "translated", - "value" : "목표는 만들었지만 일부 Todo를 연결하지 못했어요. 목표 상세에서 다시 연결할 수 있어요." + "value" : "수정" } } } }, - "development_goal_create_todo_select" : { + "development_goal_edit_discard_title" : { "extractionState" : "manual", "localizations" : { "en" : { "stringUnit" : { "state" : "translated", - "value" : "Select Todos" + "value" : "Discard your changes?" } }, "ko" : { "stringUnit" : { "state" : "translated", - "value" : "Todo 선택" + "value" : "수정한 내용을 버릴까요?" } } } }, - "development_goal_create_todo_selected_format" : { + "development_goal_edit_error_message" : { "extractionState" : "manual", "localizations" : { "en" : { "stringUnit" : { "state" : "translated", - "value" : "%1$lld selected" + "value" : "The development goal could not be updated. Please try again." } }, "ko" : { "stringUnit" : { "state" : "translated", - "value" : "%1$lld개 선택됨" + "value" : "개발 목표를 수정하지 못했어요. 다시 시도해주세요." + } + } + } + }, + "development_goal_edit_title" : { + "extractionState" : "manual", + "localizations" : { + "en" : { + "stringUnit" : { + "state" : "translated", + "value" : "Edit Development Goal" + } + }, + "ko" : { + "stringUnit" : { + "state" : "translated", + "value" : "개발 목표 수정" } } } diff --git a/Application/Presentation/PresentationShared/Sources/Extension/View+Menu.swift b/Application/Presentation/PresentationShared/Sources/Extension/View+Menu.swift deleted file mode 100644 index 545fd2ab0..000000000 --- a/Application/Presentation/PresentationShared/Sources/Extension/View+Menu.swift +++ /dev/null @@ -1,119 +0,0 @@ -// -// View+Menu.swift -// PresentationShared -// -// Created by opfic on 9/14/26. -// - -import SwiftUI - -public struct ProminentMenuItem: Identifiable { - public let action: Action - public let title: String - public let systemImage: String? - public let role: ButtonRole? - - public var id: Action { action } - - public init( - action: Action, - title: String, - systemImage: String? = nil, - role: ButtonRole? = nil - ) { - self.action = action - self.title = title - self.systemImage = systemImage - self.role = role - } -} - -public extension View { - func prominentMenu( - items: [ProminentMenuItem], - isEnabled: Bool = true, - onSelect: @escaping (Action) -> Void - ) -> some View { - ProminentMenu( - label: self, - items: items, - isEnabled: isEnabled, - onSelect: onSelect - ) - } -} - -private struct ProminentMenu: View { - @State private var isPresented = false - - let label: Label - let items: [ProminentMenuItem] - let isEnabled: Bool - let onSelect: (Action) -> Void - - // iOS 버전과 상관없이 리퀴드 글래스 없는 직접 그린 메뉴 표시 - var body: some View { - Button { - isPresented.toggle() - } label: { - // 바깥에서 정한 버튼 크기 전체를 누를 수 있게 함 - label - .frame(maxWidth: .infinity, maxHeight: .infinity) - .contentShape(.rect) - } - .buttonStyle(.plain) - .disabled(!isEnabled) - .popover( - isPresented: $isPresented, - attachmentAnchor: .point(.bottomTrailing), - arrowEdge: .top - ) { - customMenu - .presentationCompactAdaptation(.popover) - .presentationBackground(Color.secondaryBackground) - } - } - - private var customMenu: some View { - VStack(spacing: 0) { - ForEach(Array(items.enumerated()), id: \.element.id) { index, item in - if 0 < index { - Divider() - } - - Button(role: item.role) { - isPresented = false - onSelect(item.action) - } label: { - menuItemLabel(item) - .frame(maxWidth: .infinity, alignment: .leading) - .contentShape(.rect) - } - .buttonStyle(.plain) - .padding(.horizontal, 18) - .frame(minHeight: 52) - } - } - .frame(minWidth: 220) - .background(Color.secondaryBackground, in: .rect(cornerRadius: CornerRadius.menu)) - .compositingGroup() - .clipShape(.rect(cornerRadius: CornerRadius.menu)) - .shadow(color: Color.black.opacity(0.18), radius: 20, y: 10) - .padding(8) - } - - private func menuItemLabel(_ item: ProminentMenuItem) -> some View { - HStack(spacing: 12) { - if let systemImage = item.systemImage { - Image(systemName: systemImage) - .frame(width: 22) - } - - Text(item.title) - .font(.body) - - Spacer(minLength: 0) - } - .foregroundStyle(item.role == .destructive ? Color.red : Color.primary) - } -}